Open History to see the last commit
1import {
2 defaultGetScrollRestorationKey,
3 getCssSelector,
4 scrollRestorationCache,
5 setupScrollRestoration,
6} from '@tanstack/router-core'
7import { useRouter } from './useRouter'
8import type {
9 ParsedLocation,
10 ScrollRestorationEntry,
11 ScrollRestorationOptions,
12} from '@tanstack/router-core'
13β
14function useScrollRestoration() {
15 const router = useRouter()
16 setupScrollRestoration(router, true)
17}
18β
19/**
20 * @deprecated Use the `scrollRestoration` router option instead.
21 */
22export function ScrollRestoration(_props: ScrollRestorationOptions) {
23 useScrollRestoration()
24β
25 if (process.env.NODE_ENV === 'development') {
26 console.warn(
27 "The ScrollRestoration component is deprecated. Use createRouter's `scrollRestoration` option instead.",
28 )
29 }
30β
31 return null
32}
33β
34export function useElementScrollRestoration(
35 options: (
36 | {
37 id: string
38 getElement?: () => Window | Element | undefined | null
39 }
40 | {
41 id?: string
42 getElement: () => Window | Element | undefined | null
43 }
44 ) & {
45 getKey?: (location: ParsedLocation) => string
46 },
47): ScrollRestorationEntry | undefined {
48 useScrollRestoration()
49β
50 const router = useRouter()
51 const getKey = options.getKey || defaultGetScrollRestorationKey
52β
53 let elementSelector = ''
54β
55 if (options.id) {
56 elementSelector = `[data-scroll-restoration-id="${options.id}"]`
57 } else {
58 const element = options.getElement?.()
59 if (!element) {
60 return
61 }
62 elementSelector =
63 element instanceof Window ? 'window' : getCssSelector(element)
64 }
65β
66 const restoreKey = getKey(router.latestLocation)
67 const byKey = scrollRestorationCache?.state[restoreKey]
68 return byKey?.[elementSelector]
69}