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

Function useScrollRestoration

packages/shared/src/hooks/useScrollRestoration.ts:16–58  ·  view source on GitHub ↗
()

Source from the content-addressed store, hash-verified

14};
15
16export const useScrollRestoration = (): void => {
17 const { asPath } = useRouter();
18
19 useEffect(() => {
20 const handleScroll = () => {
21 scrollPositions[getScrollKey(asPath)] = window.scrollY;
22 };
23
24 window.addEventListener('scroll', handleScroll, { passive: true });
25
26 return () => {
27 window.removeEventListener('scroll', handleScroll);
28 };
29 }, [asPath]);
30
31 useEffect(() => {
32 const target = scrollPositions[getScrollKey(asPath)] ?? 0;
33 if (target === 0) {
34 return undefined;
35 }
36
37 // Wait until the page is tall enough before scrolling, so we don't clamp
38 // to the bottom while feed content is still hydrating.
39 const deadline = performance.now() + RESTORE_TIMEOUT_MS;
40 let frame = 0;
41
42 const tick = () => {
43 const maxScroll =
44 document.documentElement.scrollHeight - window.innerHeight;
45
46 if (maxScroll >= target || performance.now() >= deadline) {
47 window.scrollTo(0, Math.min(target, Math.max(0, maxScroll)));
48 return;
49 }
50
51 frame = requestAnimationFrame(tick);
52 };
53
54 frame = requestAnimationFrame(tick);
55
56 return () => cancelAnimationFrame(frame);
57 }, [asPath]);
58};
59
60export const useManualScrollRestoration = (): void => {
61 useEffect(() => {

Callers 3

MainFeedLayoutFunction · 0.90
DailyPageFunction · 0.90
DemoPageFunction · 0.90

Calls 2

getScrollKeyFunction · 0.85
useRouterFunction · 0.50

Tested by

no test coverage detected