-
Notifications
You must be signed in to change notification settings - Fork 295
Expand file tree
/
Copy pathuseScrollRestoration.ts
More file actions
72 lines (56 loc) · 1.92 KB
/
useScrollRestoration.ts
File metadata and controls
72 lines (56 loc) · 1.92 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
import { useEffect } from 'react';
import { useRouter } from 'next/router';
const scrollPositions: Record<string, number> = {};
const RESTORE_TIMEOUT_MS = 1000;
const getScrollKey = (asPath: string): string => {
if (typeof window === 'undefined') {
return asPath;
}
const historyKey = (window.history.state as { key?: string } | null)?.key;
return historyKey ? `${asPath}:${historyKey}` : asPath;
};
export const useScrollRestoration = (): void => {
const { asPath } = useRouter();
useEffect(() => {
const handleScroll = () => {
scrollPositions[getScrollKey(asPath)] = window.scrollY;
};
window.addEventListener('scroll', handleScroll, { passive: true });
return () => {
window.removeEventListener('scroll', handleScroll);
};
}, [asPath]);
useEffect(() => {
const target = scrollPositions[getScrollKey(asPath)] ?? 0;
if (target === 0) {
return undefined;
}
// Wait until the page is tall enough before scrolling, so we don't clamp
// to the bottom while feed content is still hydrating.
const deadline = performance.now() + RESTORE_TIMEOUT_MS;
let frame = 0;
const tick = () => {
const maxScroll =
document.documentElement.scrollHeight - window.innerHeight;
if (maxScroll >= target || performance.now() >= deadline) {
window.scrollTo(0, Math.min(target, Math.max(0, maxScroll)));
return;
}
frame = requestAnimationFrame(tick);
};
frame = requestAnimationFrame(tick);
return () => cancelAnimationFrame(frame);
}, [asPath]);
};
export const useManualScrollRestoration = (): void => {
useEffect(() => {
if (typeof window.history?.scrollRestoration !== 'undefined') {
window.history.scrollRestoration = 'manual';
}
return () => {
if (typeof window.history?.scrollRestoration !== 'undefined') {
window.history.scrollRestoration = 'auto';
}
};
}, []);
};