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 12 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,7 +3,6 @@ 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";
Expand All @@ -26,7 +25,6 @@ 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";
Expand All @@ -51,6 +49,7 @@ import {
} from "../AlertDialog/alert-dialog";
import { Popover, PopoverContent, PopoverTrigger } from "../Popover/popover";
import { Calendar } from "../Calendar/calendar";
import FollowUser from "./follow-user";

interface ContributorHighlightCardProps {
title?: string;
Expand Down Expand Up @@ -213,32 +212,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 +265,7 @@ const ContributorHighlightCard = ({
<span>Copy link</span>
</div>
</DropdownMenuItem>
<FollowUser />
<FollowUser username={user} />
{loggedInUser && (
<DropdownMenuItem
className={`rounded-md ${
Expand Down
29 changes: 29 additions & 0 deletions components/molecules/ContributorHighlight/follow-user.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import { DropdownMenuItem } from "@radix-ui/react-dropdown-menu";
import { FaUserPlus } from "react-icons/fa";
import useFollowUser from "lib/hooks/useFollowUser";
import useSupabaseAuth from "lib/hooks/useSupabaseAuth";

const FollowUser = ({ username }: { username: string }) => {
const { user, signIn } = useSupabaseAuth();
const { follow, unFollow, isError } = useFollowUser(username);

return user ? (
<DropdownMenuItem className={`rounded-md ${user?.user_metadata?.user_name === username && "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"} {username}
</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 {username}</span>
</div>
</DropdownMenuItem>
);
};

export default FollowUser;
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 },
};
}
49 changes: 27 additions & 22 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,15 +78,6 @@ 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") {
Expand All @@ -91,17 +91,22 @@ const Feeds: WithPageLayout<HighlightSSRProps> = (props: HighlightSSRProps) => {
if (selectedRepo) {
router.push(`/feed?repo=${selectedRepo}`);
setPage(1);
}
if (id) {
setOpenSingleHighlight(true);
router.push(`/feed/${id}`);
return;
}

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

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

useEffect(() => {
setHydrated(true);
Expand All @@ -113,7 +118,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 +132,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