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

Function restoreScrollPosition

packages/shared/src/lib/scrollRestoration.ts:70–149  ·  view source on GitHub ↗
(target: number)

Source from the content-addressed store, hash-verified

68export const cancelScrollRestoration = (): void => activeRestoration?.();
69
70export const restoreScrollPosition = (target: number): (() => void) => {
71 cancelScrollRestoration();
72 const initialPosition = window.scrollY;
73 const scrollKey = getHistoryEntryKey();
74 const controller = new AbortController();
75 let observer: ResizeObserver | undefined;
76 let frame = 0;
77 let timeout = 0;
78 let poll = 0;
79 let stopped = false;
80
81 const stop = () => {
82 stopped = true;
83 cancelAnimationFrame(frame);
84 window.clearTimeout(timeout);
85 window.clearInterval(poll);
86 observer?.disconnect();
87 controller.abort();
88 if (activeRestoration === stop) {
89 activeRestoration = undefined;
90 }
91 };
92
93 const restore = () => {
94 if (stopped) {
95 return;
96 }
97 if (getHistoryEntryKey() !== scrollKey) {
98 stop();
99 return;
100 }
101
102 const maxScroll =
103 document.documentElement.scrollHeight - window.innerHeight;
104 if (maxScroll >= target) {
105 window.scrollTo(0, target);
106 expectShellScroll(target);
107 stop();
108 }
109 };
110
111 const scheduleRestore = () => {
112 cancelAnimationFrame(frame);
113 frame = requestAnimationFrame(restore);
114 };
115
116 activeRestoration = stop;
117 timeout = window.setTimeout(stop, RESTORE_TIMEOUT_MS);
118 if (typeof ResizeObserver === 'undefined') {
119 poll = window.setInterval(scheduleRestore, RESTORE_POLL_INTERVAL_MS);
120 } else {
121 observer = new ResizeObserver(scheduleRestore);
122 observer.observe(document.body);
123 }
124
125 const { signal } = controller;
126 window.addEventListener('resize', restore, { signal });
127 window.addEventListener('wheel', stop, { passive: true, signal });

Callers 4

restoreFunction · 0.90
usePostModalNavigationFunction · 0.90
useScrollRestorationFunction · 0.90
onAfterCloseFunction · 0.90

Calls 6

cancelScrollRestorationFunction · 0.85
saveScrollPositionFunction · 0.85
scheduleRestoreFunction · 0.85
getHistoryEntryKeyFunction · 0.70
stopFunction · 0.70
restoreFunction · 0.70

Tested by

no test coverage detected