()
| 14 | }; |
| 15 | |
| 16 | export 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 | |
| 60 | export const useManualScrollRestoration = (): void => { |
| 61 | useEffect(() => { |
no test coverage detected