({
enabled,
onBack,
}: UseCloseOnBackProps)
| 29 | // stack and scroll restoration still see the page's entry, and treats a |
| 30 | // back onto the page's entry as a close. |
| 31 | export const useCloseOnBack = ({ |
| 32 | enabled, |
| 33 | onBack, |
| 34 | }: UseCloseOnBackProps): UseCloseOnBack => { |
| 35 | const router = useRouter() as NextRouter | null; |
| 36 | const onBackRef = useRef(onBack); |
| 37 | onBackRef.current = onBack; |
| 38 | const key = useRef<string | undefined>(undefined); |
| 39 | const isPushed = useRef(false); |
| 40 | const releasing = useRef<Promise<void> | null>(null); |
| 41 | // The extension's router is not Next's, and its companion runs on other |
| 42 | // sites' history. |
| 43 | const canUse = |
| 44 | enabled && !isExtension && typeof router?.beforePopState === 'function'; |
| 45 | |
| 46 | const push = useCallback(() => { |
| 47 | const state = historyState(); |
| 48 | key.current = state?.key; |
| 49 | globalThis.history.pushState({ ...state, [entryFlag]: true }, ''); |
| 50 | isPushed.current = true; |
| 51 | }, []); |
| 52 | |
| 53 | const release = useCallback((): Promise<void> => { |
| 54 | if (releasing.current) { |
| 55 | return releasing.current; |
| 56 | } |
| 57 | if (!isPushed.current || !historyState()?.[entryFlag] || !router) { |
| 58 | isPushed.current = false; |
| 59 | return Promise.resolve(); |
| 60 | } |
| 61 | |
| 62 | isPushed.current = false; |
| 63 | const pageKey = key.current; |
| 64 | releasing.current = new Promise<void>((resolve) => { |
| 65 | const onPopState = () => { |
| 66 | globalThis.removeEventListener('popstate', onPopState); |
| 67 | router.beforePopState(() => true); |
| 68 | releasing.current = null; |
| 69 | resolve(); |
| 70 | }; |
| 71 | // The page is already showing: Next must not route to it again. |
| 72 | router.beforePopState( |
| 73 | (state) => (state as HistoryState)?.key !== pageKey, |
| 74 | ); |
| 75 | globalThis.addEventListener('popstate', onPopState); |
| 76 | globalThis.history.back(); |
| 77 | }); |
| 78 | |
| 79 | return releasing.current; |
| 80 | }, [router]); |
| 81 | |
| 82 | useEffect(() => { |
| 83 | if (!canUse || !router) { |
| 84 | return undefined; |
| 85 | } |
| 86 | |
| 87 | push(); |
| 88 |
no test coverage detected