(enabled: boolean)
| 22 | // reading History. Reads document.title after a short delay so the page's |
| 23 | // SEO effect has set it. |
| 24 | export const useRecordRecentPages = (enabled: boolean): void => { |
| 25 | const router = useRouter(); |
| 26 | |
| 27 | useEffect(() => { |
| 28 | if (!enabled || typeof window === 'undefined' || !router?.events) { |
| 29 | return undefined; |
| 30 | } |
| 31 | |
| 32 | let timeoutId: number | undefined; |
| 33 | const capture = (url: string) => { |
| 34 | if (router.pathname === '/posts/[id]') { |
| 35 | return; |
| 36 | } |
| 37 | const path = url.split('?')[0].split('#')[0]; |
| 38 | // Only the latest navigation matters — drop any pending capture so |
| 39 | // rapid navigation doesn't stack timers or record stale titles. |
| 40 | window.clearTimeout(timeoutId); |
| 41 | timeoutId = window.setTimeout(() => { |
| 42 | const title = cleanTitle(document.title); |
| 43 | if (title) { |
| 44 | recordRecentPage({ path, title }); |
| 45 | } |
| 46 | }, 250); |
| 47 | }; |
| 48 | |
| 49 | capture(router.asPath); |
| 50 | router.events.on('routeChangeComplete', capture); |
| 51 | return () => { |
| 52 | window.clearTimeout(timeoutId); |
| 53 | router.events.off('routeChangeComplete', capture); |
| 54 | }; |
| 55 | }, [enabled, router]); |
| 56 | }; |
no test coverage detected