Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: improve loading performance of individual highlight #1349

Merged
merged 17 commits into from
Jul 14, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
17 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,12 @@ import { HiOutlineEmojiHappy } from "react-icons/hi";
import { TfiMoreAlt } from "react-icons/tfi";
import { FiEdit, FiLinkedin, FiTwitter } from "react-icons/fi";
import { BsCalendar2Event, BsLink45Deg } from "react-icons/bs";
import { FaUserPlus } from "react-icons/fa";
import { GrFlag } from "react-icons/gr";
import Emoji from "react-emoji-render";
import { usePostHog } from "posthog-js/react";
import { MdError } from "react-icons/md";
import { format } from "date-fns";
import { FaUserPlus } from "react-icons/fa";
import Title from "components/atoms/Typography/title";

import { Textarea } from "components/atoms/Textarea/text-area";
Expand All @@ -26,10 +26,10 @@ import { fetchGithubPRInfo } from "lib/hooks/fetchGithubPRInfo";
import { updateHighlights } from "lib/hooks/updateHighlight";
import { deleteHighlight } from "lib/hooks/deleteHighlight";
import { useToast } from "lib/hooks/useToast";
import useFollowUser from "lib/hooks/useFollowUser";
import useHighlightReactions from "lib/hooks/useHighlightReactions";
import useUserHighlightReactions from "lib/hooks/useUserHighlightReactions";
import Tooltip from "components/atoms/Tooltip/tooltip";
import useFollowUser from "lib/hooks/useFollowUser";
import GhOpenGraphImg from "../GhOpenGraphImg/gh-open-graph-img";
import {
Dialog,
Expand Down Expand Up @@ -86,6 +86,9 @@ const ContributorHighlightCard = ({
const [alertOpen, setAlertOpen] = useState(false);
const [deleteLoading, setDeleteLoading] = useState(false);
const [host, setHost] = useState("");
const { follow, unFollow, isError } = useFollowUser(
loggedInUser && loggedInUser?.user_metadata.username !== user ? user : ""
);

const [date, setDate] = useState<Date | undefined>(shipped_date ? new Date(shipped_date) : undefined);

Expand Down Expand Up @@ -213,32 +216,7 @@ const ContributorHighlightCard = ({
if (window !== undefined) {
setHost(window.location.origin as string);
}
}, [highlight]);

function FollowUser() {
const { follow, unFollow, isError } = useFollowUser(user);

return loggedInUser ? (
<DropdownMenuItem className={`rounded-md ${loggedInUser.user_metadata.user_name === user && "hidden"}`}>
<div onClick={isError ? follow : unFollow} className="flex gap-2.5 py-1 items-center pl-3 pr-7 cursor-pointer">
<FaUserPlus size={22} />
<span>
{!isError ? "Unfollow" : "Follow"} {user}
</span>
</div>
</DropdownMenuItem>
) : (
<DropdownMenuItem className="rounded-md">
<div
onClick={async () => await signIn({ provider: "github" })}
className="flex gap-2.5 py-1 items-center pl-3 pr-7"
>
<FaUserPlus size={22} />
<span>Follow {user}</span>
</div>
</DropdownMenuItem>
);
}
}, []);

return (
<article className="flex flex-col md:max-w-[40rem] flex-1 gap-3 lg:gap-6">
Expand Down Expand Up @@ -291,7 +269,31 @@ const ContributorHighlightCard = ({
<span>Copy link</span>
</div>
</DropdownMenuItem>
<FollowUser />
{loggedInUser ? (
<DropdownMenuItem
className={`rounded-md ${loggedInUser?.user_metadata?.user_name === user && "hidden"}`}
>
<div
onClick={isError ? follow : unFollow}
className="flex gap-2.5 py-1 items-center pl-3 pr-7 cursor-pointer"
>
<FaUserPlus size={22} />
<span>
{!isError ? "Unfollow" : "Follow"} {user}
</span>
</div>
</DropdownMenuItem>
) : (
<DropdownMenuItem className="rounded-md">
<div
onClick={async () => signIn({ provider: "github" })}
className="flex gap-2.5 py-1 items-center pl-3 pr-7"
>
<FaUserPlus size={22} />
<span>Follow {user}</span>
</div>
</DropdownMenuItem>
)}
{loggedInUser && (
<DropdownMenuItem
className={`rounded-md ${
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,20 @@ import Icon from "components/atoms/Icon/icon";

interface HighlightsFilterCardProps {
repos: { repoName: string; repoIcon: string; full_name: string }[];
setSelected?: React.Dispatch<React.SetStateAction<string>>;
setSelected?: (selected: string) => void;
selectedFilter: string;
}
const HighlightsFilterCard = ({ repos, setSelected, selectedFilter }: HighlightsFilterCardProps): JSX.Element => {
const [selected, setSelectedRepo] = useState("");

const handleClick = (name: string) => {
setSelectedRepo((prev) => (prev === name ? "" : name));
setSelected?.((prev) => (prev === name ? "" : name));
};

useEffect(() => {
setSelected?.(selected);
}, [selected]);

useEffect(() => {
// This is to handle resetting the filter state when the tab is switched
setSelectedRepo(selectedFilter);
Expand Down
18 changes: 7 additions & 11 deletions pages/feed/[id].tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import { GetServerSidePropsContext } from "next";

import fetchSocialCard from "lib/utils/fetch-social-card";
import Feed from "../feed";
import Feed from "./index";

export default Feed;

Expand All @@ -13,27 +12,24 @@ export type HighlightSSRPropsContext = GetServerSidePropsContext<{ id: string }>

export async function handleHighlightSSR({ params }: GetServerSidePropsContext<{ id: string }>) {
const { id } = params!;
let highlight: DbHighlight | null = null;
let ogImage;

async function fetchUserData() {
async function fetchHighlight() {
const req = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/user/highlights/${id}`, {
headers: {
accept: "application/json",
},
});

if (req.ok) {
highlight = (await req.json()) as DbHighlight;
return (await req.json()) as DbHighlight;
}
}

// Runs the data fetching in parallel. Decreases the loading time by 50%.
const [, ogData] = await Promise.allSettled([fetchUserData(), fetchSocialCard(`highlights/${id}`)]);
return null;
}

ogImage = ogData.status === "fulfilled" ? ogData.value : "";
const highlight = await fetchHighlight();

return {
props: { highlight, ogImage },
props: { highlight },
};
}
62 changes: 31 additions & 31 deletions pages/feed/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,6 @@ type highlightReposType = { repoName: string; repoIcon: string; full_name: strin

interface HighlightSSRProps {
highlight: DbHighlight | null;
ogImage?: string;
}

const Feeds: WithPageLayout<HighlightSSRProps> = (props: HighlightSSRProps) => {
Expand All @@ -44,16 +43,26 @@ const Feeds: WithPageLayout<HighlightSSRProps> = (props: HighlightSSRProps) => {

const { data: featuredHighlights } = useFetchFeaturedHighlights();

const repoTofilterList = (repos: { full_name: string }[]): highlightReposType[] => {
const filtersArray = repos.map(({ full_name }) => {
const [orgName, repo] = full_name.split("/");
return { repoName: repo, repoIcon: `https://www.github.com/${orgName}.png?size=300`, full_name };
});

return filtersArray;
};

const router = useRouter();
const [hydrated, setHydrated] = useState(false);
const [openSingleHighlight, setOpenSingleHighlight] = useState(false);
const [selectedRepo, setSelectedRepo] = useState("");
const [activeTab, setActiveTab] = useState<activeTabType>("home");
const [repoList, setRepoList] = useState<highlightReposType[]>(repos as highlightReposType[]);
const [repoList, setRepoList] = useState<highlightReposType[]>(repoTofilterList(repos as highlightReposType[]));
const [hydrated, setHydrated] = useState(false);

const { id } = router.query;
const singleHighlight = props.highlight;
const highlightId = props.highlight?.id as string;
const ogImage = props?.highlight
? `${process.env.NEXT_PUBLIC_OPENGRAPH_URL}/highlights/${props.highlight.id}`
: undefined;

const { data: followersRepo } = useFetchFollowersHighlightRepos();

Expand All @@ -69,39 +78,20 @@ const Feeds: WithPageLayout<HighlightSSRProps> = (props: HighlightSSRProps) => {
{ name: "Highlights", count: highlights_count ?? 0 },
];

const repoTofilterList = (repos: { full_name: string }[]): highlightReposType[] => {
const filtersArray = repos.map(({ full_name }) => {
const [orgName, repo] = full_name.split("/");
return { repoName: repo, repoIcon: `https://www.github.com/${orgName}.png?size=300`, full_name };
});

return filtersArray;
};

useEffect(() => {
setSelectedRepo("");
if (activeTab === "home") {
setRepoList(repoTofilterList(repos));
} else if (activeTab === "following") {
setRepoList(repoTofilterList(followersRepo));
}
}, [activeTab, followersRepo, repos]);
}, [activeTab]);

useEffect(() => {
if (selectedRepo) {
router.push(`/feed?repo=${selectedRepo}`);
setPage(1);
}
if (id) {
if (singleHighlight && !openSingleHighlight) {
router.push(`/feed/${props.highlight?.id}`);
setOpenSingleHighlight(true);
router.push(`/feed/${id}`);
}

if (!selectedRepo && !id) {
router.push("/feed");
setPage(1);
}
}, [selectedRepo, id]);
}, [singleHighlight]);

useEffect(() => {
setHydrated(true);
Expand All @@ -113,7 +103,7 @@ const Feeds: WithPageLayout<HighlightSSRProps> = (props: HighlightSSRProps) => {
<SEO
title={`${props?.highlight ? "Highlight | OpenSauced" : "Highlights | OpenSauced"}`}
description={`${props?.highlight?.highlight || "OpenSauced Highlight"}`}
image={props?.ogImage}
image={ogImage}
twitterCard="summary_large_image"
/>
<div className="hidden">
Expand All @@ -127,7 +117,7 @@ const Feeds: WithPageLayout<HighlightSSRProps> = (props: HighlightSSRProps) => {
<SEO
title={`${props?.highlight ? "Highlight | OpenSauced" : "Highlights | OpenSauced"}`}
description={`${props?.highlight?.highlight || "OpenSauced Highlight"}`}
image={props?.ogImage}
image={ogImage}
twitterCard="summary_large_image"
/>
<div className="container flex flex-col gap-16 px-2 pt-12 mx-auto md:px-16 lg:justify-end md:flex-row">
Expand Down Expand Up @@ -255,7 +245,17 @@ const Feeds: WithPageLayout<HighlightSSRProps> = (props: HighlightSSRProps) => {
</Tabs>
<div className="hidden gap-6 mt-10 md:flex-1 md:flex md:flex-col">
{repoList && repoList.length > 0 && (
<HighlightsFilterCard selectedFilter={selectedRepo} setSelected={setSelectedRepo} repos={repoList} />
<HighlightsFilterCard
selectedFilter={selectedRepo}
setSelected={(repo) => {
if (!openSingleHighlight) {
router.push(`/feed${repo ? `?repo=${repo}` : ""}`);
setPage(1);
setSelectedRepo(repo);
}
}}
repos={repoList}
/>
)}

{featuredHighlights && featuredHighlights.length > 0 && (
Expand Down