MCPcopy Create free account
hub / github.com/dailydotdev/apps / usePostPrefetch

Function usePostPrefetch

packages/shared/src/hooks/usePostPrefetch.ts:27–106  ·  view source on GitHub ↗
()

Source from the content-addressed store, hash-verified

25 `${anchor.pathname}${anchor.search}${anchor.hash}`;
26
27export const usePostPrefetch = (): void => {
28 const router = useRouter();
29 const isPhone = useIsPhone();
30
31 // The post page's phone header is a chunk of its own that next/dynamic
32 // fetches on the page's first render; loaded here once, the page paints
33 // with its header instead of a round trip ahead of it.
34 useEffect(() => {
35 if (isPhone) {
36 import(
37 /* webpackChunkName: "goBackHeaderMobile" */ '../components/post/GoBackHeaderMobile'
38 ).catch(() => undefined);
39 }
40 }, [isPhone]);
41
42 // A post's page data is a round trip the cards' plain links never ask
43 // for ahead of time, as a Link would. Posts in view are fetched once
44 // they are near, and any link the finger lands on, so the page is
45 // usually there by the tap.
46 useEffect(() => {
47 const { connection } = navigator as Navigator & {
48 connection?: { saveData?: boolean };
49 };
50 if (!isPhone || connection?.saveData) {
51 return undefined;
52 }
53 const fetched = new Set<string>();
54 const prefetch = (anchor: HTMLAnchorElement) => {
55 const href = pathOf(anchor);
56 if (fetched.has(href)) {
57 return;
58 }
59 fetched.add(href);
60 router.prefetch(href).catch(() => undefined);
61 };
62 const onPress = (event: Event) => {
63 const anchor = pageLink(event.target);
64 if (anchor) {
65 prefetch(anchor);
66 }
67 };
68 const near = new IntersectionObserver(
69 (entries) =>
70 entries.forEach((entry) => {
71 if (entry.isIntersecting) {
72 near.unobserve(entry.target);
73 prefetch(entry.target as HTMLAnchorElement);
74 }
75 }),
76 { rootMargin: '50% 0px' },
77 );
78 const seen = new WeakSet<Element>();
79 let scan = 0;
80 const watchPosts = () => {
81 scan = 0;
82 document
83 .querySelectorAll<HTMLAnchorElement>('main a[href^="/posts/"]')
84 .forEach((anchor) => {

Callers 2

PageFunction · 0.90
InternalAppFunction · 0.90

Calls 4

useIsPhoneFunction · 0.90
watchPostsFunction · 0.85
prefetchFunction · 0.70
useRouterFunction · 0.50

Tested by 1

PageFunction · 0.72