|
1 | 1 | import * as React from 'react' |
2 | 2 | import { useCallback, useEffect } from 'react' |
3 | | -import { useBeforeUnload, useLocation, useNavigation } from 'react-router-dom' |
| 3 | +import { useLocation, useNavigation } from 'react-router-dom' |
4 | 4 |
|
5 | | -type Direction = "vertical" | "horizontal"; |
6 | | -type ScrollAttribute = "scrollTop" | "scrollLeft"; |
| 5 | +type Direction = 'vertical' | 'horizontal' |
| 6 | +type ScrollAttribute = 'scrollTop' | 'scrollLeft' |
7 | 7 | const DIRECTION: { [direction in Direction]: ScrollAttribute } = { |
8 | 8 | vertical: 'scrollTop', |
9 | 9 | horizontal: 'scrollLeft', |
10 | | -}; |
| 10 | +} |
11 | 11 |
|
12 | 12 | export function ElementScrollRestoration({ |
13 | 13 | elementQuery, |
14 | | - direction = "vertical", |
| 14 | + direction = 'vertical', |
15 | 15 | ...props |
16 | | -}: { elementQuery: string; direction?: Direction } & React.HTMLProps<HTMLScriptElement>) { |
| 16 | +}: { |
| 17 | + elementQuery: string |
| 18 | + direction?: Direction |
| 19 | +} & React.HTMLProps<HTMLScriptElement>) { |
17 | 20 | const STORAGE_KEY = `position:${elementQuery}` |
18 | 21 | const navigation = useNavigation() |
19 | 22 | const location = useLocation() |
@@ -61,11 +64,18 @@ export function ElementScrollRestoration({ |
61 | 64 | } |
62 | 65 | }, [STORAGE_KEY, elementQuery, navigation.state, updatePositions]) |
63 | 66 |
|
64 | | - useBeforeUnload(() => { |
65 | | - updatePositions() |
66 | | - }) |
| 67 | + useEffect(() => { |
| 68 | + window.addEventListener('pagehide', updatePositions) |
| 69 | + return () => { |
| 70 | + window.removeEventListener('pagehide', updatePositions) |
| 71 | + } |
| 72 | + }, [updatePositions]) |
67 | 73 |
|
68 | | - function restoreScroll(storageKey: string, elementQuery: string, scrollAttribute: ScrollAttribute) { |
| 74 | + function restoreScroll( |
| 75 | + storageKey: string, |
| 76 | + elementQuery: string, |
| 77 | + scrollAttribute: ScrollAttribute, |
| 78 | + ) { |
69 | 79 | const element = document.querySelector(elementQuery) |
70 | 80 | if (!element) { |
71 | 81 | console.warn(`Element not found: ${elementQuery}. Cannot restore scroll.`) |
@@ -95,7 +105,9 @@ export function ElementScrollRestoration({ |
95 | 105 | dangerouslySetInnerHTML={{ |
96 | 106 | __html: `(${restoreScroll})(${JSON.stringify( |
97 | 107 | STORAGE_KEY, |
98 | | - )}, ${JSON.stringify(elementQuery)}, ${JSON.stringify(scrollAttribute)})`, |
| 108 | + )}, ${JSON.stringify(elementQuery)}, ${JSON.stringify( |
| 109 | + scrollAttribute, |
| 110 | + )})`, |
99 | 111 | }} |
100 | 112 | /> |
101 | 113 | ) |
|
0 commit comments