@tanstack/solid-router 1.114.14 → 1.114.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,240 +1,6 @@
1
- import { functionalUpdate } from '@tanstack/router-core';
1
+ import { defaultGetScrollRestorationKey, restoreScroll, storageKey, } from '@tanstack/router-core';
2
2
  import { useRouter } from './useRouter';
3
3
  import { ScriptOnce } from './ScriptOnce';
4
- export const storageKey = 'tsr-scroll-restoration-v1_3';
5
- let sessionsStorage = false;
6
- try {
7
- sessionsStorage =
8
- typeof window !== 'undefined' && typeof window.sessionStorage === 'object';
9
- }
10
- catch { }
11
- const throttle = (fn, wait) => {
12
- let timeout;
13
- return (...args) => {
14
- if (!timeout) {
15
- timeout = setTimeout(() => {
16
- fn(...args);
17
- timeout = null;
18
- }, wait);
19
- }
20
- };
21
- };
22
- export const scrollRestorationCache = sessionsStorage
23
- ? (() => {
24
- const state = JSON.parse(window.sessionStorage.getItem(storageKey) || 'null') || {};
25
- return {
26
- state,
27
- // This setter is simply to make sure that we set the sessionStorage right
28
- // after the state is updated. It doesn't necessarily need to be a functional
29
- // update.
30
- set: (updater) => ((scrollRestorationCache.state =
31
- // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
32
- functionalUpdate(updater, scrollRestorationCache.state) ||
33
- scrollRestorationCache.state),
34
- window.sessionStorage.setItem(storageKey, JSON.stringify(scrollRestorationCache.state))),
35
- };
36
- })()
37
- : undefined;
38
- /**
39
- * The default `getKey` function for `useScrollRestoration`.
40
- * It returns the `key` from the location state or the `href` of the location.
41
- *
42
- * The `location.href` is used as a fallback to support the use case where the location state is not available like the initial render.
43
- */
44
- export const defaultGetScrollRestorationKey = (location) => {
45
- return location.state.key || location.href;
46
- };
47
- export function getCssSelector(el) {
48
- const path = [];
49
- let parent;
50
- while ((parent = el.parentNode)) {
51
- path.unshift(`${el.tagName}:nth-child(${[].indexOf.call(parent.children, el) + 1})`);
52
- el = parent;
53
- }
54
- return `${path.join(' > ')}`.toLowerCase();
55
- }
56
- let ignoreScroll = false;
57
- // NOTE: This function must remain pure and not use any outside variables
58
- // unless they are passed in as arguments. Why? Because we need to be able to
59
- // toString() it into a script tag to execute as early as possible in the browser
60
- // during SSR. Additionally, we also call it from within the router lifecycle
61
- export function restoreScroll(storageKey, key, behavior, shouldScrollRestoration, scrollToTopSelectors) {
62
- let byKey;
63
- try {
64
- byKey = JSON.parse(sessionStorage.getItem(storageKey) || '{}');
65
- }
66
- catch (error) {
67
- console.error(error);
68
- return;
69
- }
70
- const resolvedKey = key || window.history.state?.key;
71
- const elementEntries = byKey[resolvedKey];
72
- //
73
- ignoreScroll = true;
74
- (() => {
75
- // If we have a cached entry for this location state,
76
- // we always need to prefer that over the hash scroll.
77
- if (shouldScrollRestoration && elementEntries) {
78
- for (const elementSelector in elementEntries) {
79
- const entry = elementEntries[elementSelector];
80
- if (elementSelector === 'window') {
81
- window.scrollTo({
82
- top: entry.scrollY,
83
- left: entry.scrollX,
84
- behavior,
85
- });
86
- }
87
- else if (elementSelector) {
88
- const element = document.querySelector(elementSelector);
89
- if (element) {
90
- element.scrollLeft = entry.scrollX;
91
- element.scrollTop = entry.scrollY;
92
- }
93
- }
94
- }
95
- return;
96
- }
97
- // If we don't have a cached entry for the hash,
98
- // Which means we've never seen this location before,
99
- // we need to check if there is a hash in the URL.
100
- // If there is, we need to scroll it's ID into view.
101
- const hash = window.location.hash.split('#')[1];
102
- if (hash) {
103
- const hashScrollIntoViewOptions = (window.history.state || {}).__hashScrollIntoViewOptions ?? true;
104
- if (hashScrollIntoViewOptions) {
105
- const el = document.getElementById(hash);
106
- if (el) {
107
- el.scrollIntoView(hashScrollIntoViewOptions);
108
- }
109
- }
110
- return;
111
- }
112
- // If there is no cached entry for the hash and there is no hash in the URL,
113
- // we need to scroll to the top of the page for every scrollToTop element
114
- ;
115
- [
116
- 'window',
117
- ...(scrollToTopSelectors?.filter((d) => d !== 'window') ?? []),
118
- ].forEach((selector) => {
119
- const element = selector === 'window' ? window : document.querySelector(selector);
120
- if (element) {
121
- element.scrollTo({
122
- top: 0,
123
- left: 0,
124
- behavior,
125
- });
126
- }
127
- });
128
- })();
129
- //
130
- ignoreScroll = false;
131
- }
132
- export function setupScrollRestoration(router, force) {
133
- const shouldScrollRestoration = force ?? router.options.scrollRestoration ?? false;
134
- if (shouldScrollRestoration) {
135
- router.isScrollRestoring = true;
136
- }
137
- if (typeof document === 'undefined' || router.isScrollRestorationSetup) {
138
- return;
139
- }
140
- router.isScrollRestorationSetup = true;
141
- //
142
- ignoreScroll = false;
143
- const getKey = router.options.getScrollRestorationKey || defaultGetScrollRestorationKey;
144
- window.history.scrollRestoration = 'manual';
145
- // // Create a MutationObserver to monitor DOM changes
146
- // const mutationObserver = new MutationObserver(() => {
147
- // ;ignoreScroll = true
148
- // requestAnimationFrame(() => {
149
- // ;ignoreScroll = false
150
- // // Attempt to restore scroll position on each dom
151
- // // mutation until the user scrolls. We do this
152
- // // because dynamic content may come in at different
153
- // // ticks after the initial render and we want to
154
- // // keep up with that content as much as possible.
155
- // // As soon as the user scrolls, we no longer need
156
- // // to attempt router.
157
- // // console.log('mutation observer restoreScroll')
158
- // restoreScroll(
159
- // storageKey,
160
- // getKey(router.state.location),
161
- // router.options.scrollRestorationBehavior,
162
- // )
163
- // })
164
- // })
165
- // const observeDom = () => {
166
- // // Observe changes to the entire document
167
- // mutationObserver.observe(document, {
168
- // childList: true, // Detect added or removed child nodes
169
- // subtree: true, // Monitor all descendants
170
- // characterData: true, // Detect text content changes
171
- // })
172
- // }
173
- // const unobserveDom = () => {
174
- // mutationObserver.disconnect()
175
- // }
176
- // observeDom()
177
- const onScroll = (event) => {
178
- // unobserveDom()
179
- if (ignoreScroll || !router.isScrollRestoring) {
180
- return;
181
- }
182
- let elementSelector = '';
183
- if (event.target === document || event.target === window) {
184
- elementSelector = 'window';
185
- }
186
- else {
187
- const attrId = event.target.getAttribute('data-scroll-restoration-id');
188
- if (attrId) {
189
- elementSelector = `[data-scroll-restoration-id="${attrId}"]`;
190
- }
191
- else {
192
- elementSelector = getCssSelector(event.target);
193
- }
194
- }
195
- const restoreKey = getKey(router.state.location);
196
- scrollRestorationCache.set((state) => {
197
- const keyEntry = (state[restoreKey] =
198
- state[restoreKey] || {});
199
- const elementEntry = (keyEntry[elementSelector] =
200
- keyEntry[elementSelector] || {});
201
- if (elementSelector === 'window') {
202
- elementEntry.scrollX = window.scrollX || 0;
203
- elementEntry.scrollY = window.scrollY || 0;
204
- }
205
- else if (elementSelector) {
206
- const element = document.querySelector(elementSelector);
207
- if (element) {
208
- elementEntry.scrollX = element.scrollLeft || 0;
209
- elementEntry.scrollY = element.scrollTop || 0;
210
- }
211
- }
212
- return state;
213
- });
214
- };
215
- // Throttle the scroll event to avoid excessive updates
216
- if (typeof document !== 'undefined') {
217
- document.addEventListener('scroll', throttle(onScroll, 100), true);
218
- }
219
- router.subscribe('onRendered', (event) => {
220
- // unobserveDom()
221
- const cacheKey = getKey(event.toLocation);
222
- // If the user doesn't want to restore the scroll position,
223
- // we don't need to do anything.
224
- if (!router.resetNextScroll) {
225
- router.resetNextScroll = true;
226
- return;
227
- }
228
- restoreScroll(storageKey, cacheKey, router.options.scrollRestorationBehavior || undefined, router.isScrollRestoring || undefined, router.options.scrollToTopSelectors || undefined);
229
- if (router.isScrollRestoring) {
230
- // Mark the location as having been seen
231
- scrollRestorationCache.set((state) => {
232
- state[cacheKey] = state[cacheKey] || {};
233
- return state;
234
- });
235
- }
236
- });
237
- }
238
4
  export function ScrollRestoration() {
239
5
  const router = useRouter();
240
6
  const getKey = router.options.getScrollRestorationKey || defaultGetScrollRestorationKey;
@@ -1 +1 @@
1
- {"version":3,"file":"scroll-restoration.jsx","sourceRoot":"","sources":["../../src/scroll-restoration.tsx"],"names":[],"mappings":"AAAA,OAAO,EAAE,gBAAgB,EAAE,MAAM,uBAAuB,CAAA;AACxD,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAA;AACvC,OAAO,E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sourceRoot":"","sources":["../../src/scroll-restoration.tsx"],"names":[],"mappings":"AAAA,OAAO,EACL,8BAA8B,EAC9B,aAAa,EACb,UAAU,GACX,MAAM,uBAAuB,CAAA;AAC9B,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAA;AACvC,OAAO,EAAE,UAAU,EAAE,MAAM,cAAc,CAAA;AAEzC,MAAM,UAAU,iBAAiB;IAC/B,MAAM,MAAM,GAAG,SAAS,EAAE,CAAA;IAC1B,MAAM,MAAM,GACV,MAAM,CAAC,OAAO,CAAC,uBAAuB,IAAI,8BAA8B,CAAA;IAC1E,MAAM,OAAO,GAAG,MAAM,CAAC,MAAM,CAAC,cAAc,CAAC,CAAA;IAC7C,MAAM,WAAW,GACf,OAAO,KAAK,8BAA8B,CAAC,MAAM,CAAC,cAAc,CAAC;QAC/D,CAAC,CAAC,OAAO;QACT,CAAC,CAAC,IAAI,CAAA;IAEV,IAAI,CAAC,MAAM,CAAC,iBAAiB,IAAI,CAAC,MAAM,CAAC,QAAQ,EAAE,CAAC;QAClD,OAAO,IAAI,CAAA;IACb,CAAC;IAED,OAAO,CACL,CAAC,UAAU,CACT,QAAQ,CAAC,CAAC,IAAI,aAAa,CAAC,QAAQ,EAAE,KAAK,IAAI,CAAC,SAAS,CAAC,UAAU,CAAC,IAAI,IAAI,CAAC,SAAS,CAAC,WAAW,CAAC,oBAAoB,CAAC,CACzH,GAAG,CAAC,CAAC,KAAK,CAAC,EACX,CACH,CAAA;AACH,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tanstack/solid-router",
3
- "version": "1.114.14",
3
+ "version": "1.114.15",
4
4
  "description": "Modern and scalable routing for Solid applications",
5
5
  "author": "Tanner Linsley",
6
6
  "license": "MIT",
@@ -61,7 +61,7 @@
61
61
  "tiny-invariant": "^1.3.3",
62
62
  "tiny-warning": "^1.0.3",
63
63
  "@tanstack/history": "1.114.12",
64
- "@tanstack/router-core": "1.114.12"
64
+ "@tanstack/router-core": "1.114.15"
65
65
  },
66
66
  "devDependencies": {
67
67
  "@solidjs/testing-library": "^0.8.10",
@@ -1,12 +1,15 @@
1
- import { useRouter } from './useRouter'
2
1
  import {
3
2
  defaultGetScrollRestorationKey,
4
3
  getCssSelector,
5
4
  scrollRestorationCache,
6
5
  setupScrollRestoration,
7
- } from './scroll-restoration'
8
- import type { ScrollRestorationOptions } from './scroll-restoration'
9
- import type { ParsedLocation } from '@tanstack/router-core'
6
+ } from '@tanstack/router-core'
7
+ import { useRouter } from './useRouter'
8
+ import type {
9
+ ParsedLocation,
10
+ ScrollRestorationEntry,
11
+ ScrollRestorationOptions,
12
+ } from '@tanstack/router-core'
10
13
 
11
14
  function useScrollRestoration() {
12
15
  const router = useRouter()
@@ -41,7 +44,7 @@ export function useElementScrollRestoration(
41
44
  ) & {
42
45
  getKey?: (location: ParsedLocation) => string
43
46
  },
44
- ) {
47
+ ): ScrollRestorationEntry | undefined {
45
48
  useScrollRestoration()
46
49
 
47
50
  const router = useRouter()
package/src/router.ts CHANGED
@@ -25,11 +25,11 @@ import {
25
25
  replaceEqualDeep,
26
26
  resolvePath,
27
27
  rootRouteId,
28
+ setupScrollRestoration,
28
29
  trimPath,
29
30
  trimPathLeft,
30
31
  trimPathRight,
31
32
  } from '@tanstack/router-core'
32
- import { setupScrollRestoration } from './scroll-restoration'
33
33
  import type * as Solid from 'solid-js'
34
34
  import type { HistoryLocation, RouterHistory } from '@tanstack/history'
35
35
 
@@ -1,328 +1,11 @@
1
- import { functionalUpdate } from '@tanstack/router-core'
1
+ import {
2
+ defaultGetScrollRestorationKey,
3
+ restoreScroll,
4
+ storageKey,
5
+ } from '@tanstack/router-core'
2
6
  import { useRouter } from './useRouter'
3
7
  import { ScriptOnce } from './ScriptOnce'
4
8
 
5
- import type {
6
- AnyRouter,
7
- NonNullableUpdater,
8
- ParsedLocation,
9
- } from '@tanstack/router-core'
10
-
11
- export type ScrollRestorationEntry = { scrollX: number; scrollY: number }
12
-
13
- export type ScrollRestorationByElement = Record<string, ScrollRestorationEntry>
14
-
15
- export type ScrollRestorationByKey = Record<string, ScrollRestorationByElement>
16
-
17
- export type ScrollRestorationCache = {
18
- state: ScrollRestorationByKey
19
- set: (updater: NonNullableUpdater<ScrollRestorationByKey>) => void
20
- }
21
- export type ScrollRestorationOptions = {
22
- getKey?: (location: ParsedLocation) => string
23
- scrollBehavior?: ScrollToOptions['behavior']
24
- }
25
-
26
- export const storageKey = 'tsr-scroll-restoration-v1_3'
27
- let sessionsStorage = false
28
- try {
29
- sessionsStorage =
30
- typeof window !== 'undefined' && typeof window.sessionStorage === 'object'
31
- } catch {}
32
- const throttle = (fn: (...args: Array<any>) => void, wait: number) => {
33
- let timeout: any
34
- return (...args: Array<any>) => {
35
- if (!timeout) {
36
- timeout = setTimeout(() => {
37
- fn(...args)
38
- timeout = null
39
- }, wait)
40
- }
41
- }
42
- }
43
- export const scrollRestorationCache: ScrollRestorationCache = sessionsStorage
44
- ? (() => {
45
- const state: ScrollRestorationByKey =
46
- JSON.parse(window.sessionStorage.getItem(storageKey) || 'null') || {}
47
-
48
- return {
49
- state,
50
- // This setter is simply to make sure that we set the sessionStorage right
51
- // after the state is updated. It doesn't necessarily need to be a functional
52
- // update.
53
- set: (updater) => (
54
- (scrollRestorationCache.state =
55
- // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
56
- functionalUpdate(updater, scrollRestorationCache.state) ||
57
- scrollRestorationCache.state),
58
- window.sessionStorage.setItem(
59
- storageKey,
60
- JSON.stringify(scrollRestorationCache.state),
61
- )
62
- ),
63
- }
64
- })()
65
- : (undefined as any)
66
- /**
67
- * The default `getKey` function for `useScrollRestoration`.
68
- * It returns the `key` from the location state or the `href` of the location.
69
- *
70
- * The `location.href` is used as a fallback to support the use case where the location state is not available like the initial render.
71
- */
72
-
73
- export const defaultGetScrollRestorationKey = (location: ParsedLocation) => {
74
- return location.state.key! || location.href
75
- }
76
-
77
- export function getCssSelector(el: any): string {
78
- const path = []
79
- let parent
80
- while ((parent = el.parentNode)) {
81
- path.unshift(
82
- `${el.tagName}:nth-child(${([].indexOf as any).call(parent.children, el) + 1})`,
83
- )
84
- el = parent
85
- }
86
- return `${path.join(' > ')}`.toLowerCase()
87
- }
88
-
89
- let ignoreScroll = false
90
-
91
- // NOTE: This function must remain pure and not use any outside variables
92
- // unless they are passed in as arguments. Why? Because we need to be able to
93
- // toString() it into a script tag to execute as early as possible in the browser
94
- // during SSR. Additionally, we also call it from within the router lifecycle
95
- export function restoreScroll(
96
- storageKey: string,
97
- key: string | undefined,
98
- behavior: ScrollToOptions['behavior'] | undefined,
99
- shouldScrollRestoration: boolean | undefined,
100
- scrollToTopSelectors: Array<string> | undefined,
101
- ) {
102
- let byKey: ScrollRestorationByKey
103
-
104
- try {
105
- byKey = JSON.parse(sessionStorage.getItem(storageKey) || '{}')
106
- } catch (error: any) {
107
- console.error(error)
108
- return
109
- }
110
-
111
- const resolvedKey = key || window.history.state?.key
112
- const elementEntries = byKey[resolvedKey]
113
-
114
- //
115
- ignoreScroll = true
116
-
117
- //
118
- ;(() => {
119
- // If we have a cached entry for this location state,
120
- // we always need to prefer that over the hash scroll.
121
- if (shouldScrollRestoration && elementEntries) {
122
- for (const elementSelector in elementEntries) {
123
- const entry = elementEntries[elementSelector]!
124
- if (elementSelector === 'window') {
125
- window.scrollTo({
126
- top: entry.scrollY,
127
- left: entry.scrollX,
128
- behavior,
129
- })
130
- } else if (elementSelector) {
131
- const element = document.querySelector(elementSelector)
132
- if (element) {
133
- element.scrollLeft = entry.scrollX
134
- element.scrollTop = entry.scrollY
135
- }
136
- }
137
- }
138
-
139
- return
140
- }
141
-
142
- // If we don't have a cached entry for the hash,
143
- // Which means we've never seen this location before,
144
- // we need to check if there is a hash in the URL.
145
- // If there is, we need to scroll it's ID into view.
146
- const hash = window.location.hash.split('#')[1]
147
-
148
- if (hash) {
149
- const hashScrollIntoViewOptions =
150
- (window.history.state || {}).__hashScrollIntoViewOptions ?? true
151
-
152
- if (hashScrollIntoViewOptions) {
153
- const el = document.getElementById(hash)
154
- if (el) {
155
- el.scrollIntoView(hashScrollIntoViewOptions)
156
- }
157
- }
158
-
159
- return
160
- }
161
-
162
- // If there is no cached entry for the hash and there is no hash in the URL,
163
- // we need to scroll to the top of the page for every scrollToTop element
164
- ;[
165
- 'window',
166
- ...(scrollToTopSelectors?.filter((d) => d !== 'window') ?? []),
167
- ].forEach((selector) => {
168
- const element =
169
- selector === 'window' ? window : document.querySelector(selector)
170
- if (element) {
171
- element.scrollTo({
172
- top: 0,
173
- left: 0,
174
- behavior,
175
- })
176
- }
177
- })
178
- })()
179
-
180
- //
181
- ignoreScroll = false
182
- }
183
-
184
- export function setupScrollRestoration(router: AnyRouter, force?: boolean) {
185
- const shouldScrollRestoration =
186
- force ?? router.options.scrollRestoration ?? false
187
-
188
- if (shouldScrollRestoration) {
189
- router.isScrollRestoring = true
190
- }
191
-
192
- if (typeof document === 'undefined' || router.isScrollRestorationSetup) {
193
- return
194
- }
195
-
196
- router.isScrollRestorationSetup = true
197
-
198
- //
199
- ignoreScroll = false
200
-
201
- const getKey =
202
- router.options.getScrollRestorationKey || defaultGetScrollRestorationKey
203
-
204
- window.history.scrollRestoration = 'manual'
205
-
206
- // // Create a MutationObserver to monitor DOM changes
207
- // const mutationObserver = new MutationObserver(() => {
208
- // ;ignoreScroll = true
209
- // requestAnimationFrame(() => {
210
- // ;ignoreScroll = false
211
-
212
- // // Attempt to restore scroll position on each dom
213
- // // mutation until the user scrolls. We do this
214
- // // because dynamic content may come in at different
215
- // // ticks after the initial render and we want to
216
- // // keep up with that content as much as possible.
217
- // // As soon as the user scrolls, we no longer need
218
- // // to attempt router.
219
- // // console.log('mutation observer restoreScroll')
220
- // restoreScroll(
221
- // storageKey,
222
- // getKey(router.state.location),
223
- // router.options.scrollRestorationBehavior,
224
- // )
225
- // })
226
- // })
227
-
228
- // const observeDom = () => {
229
- // // Observe changes to the entire document
230
- // mutationObserver.observe(document, {
231
- // childList: true, // Detect added or removed child nodes
232
- // subtree: true, // Monitor all descendants
233
- // characterData: true, // Detect text content changes
234
- // })
235
- // }
236
-
237
- // const unobserveDom = () => {
238
- // mutationObserver.disconnect()
239
- // }
240
-
241
- // observeDom()
242
-
243
- const onScroll = (event: Event) => {
244
- // unobserveDom()
245
-
246
- if (ignoreScroll || !router.isScrollRestoring) {
247
- return
248
- }
249
-
250
- let elementSelector = ''
251
-
252
- if (event.target === document || event.target === window) {
253
- elementSelector = 'window'
254
- } else {
255
- const attrId = (event.target as Element).getAttribute(
256
- 'data-scroll-restoration-id',
257
- )
258
-
259
- if (attrId) {
260
- elementSelector = `[data-scroll-restoration-id="${attrId}"]`
261
- } else {
262
- elementSelector = getCssSelector(event.target)
263
- }
264
- }
265
-
266
- const restoreKey = getKey(router.state.location)
267
-
268
- scrollRestorationCache.set((state) => {
269
- const keyEntry = (state[restoreKey] =
270
- state[restoreKey] || ({} as ScrollRestorationByElement))
271
-
272
- const elementEntry = (keyEntry[elementSelector] =
273
- keyEntry[elementSelector] || ({} as ScrollRestorationEntry))
274
-
275
- if (elementSelector === 'window') {
276
- elementEntry.scrollX = window.scrollX || 0
277
- elementEntry.scrollY = window.scrollY || 0
278
- } else if (elementSelector) {
279
- const element = document.querySelector(elementSelector)
280
- if (element) {
281
- elementEntry.scrollX = element.scrollLeft || 0
282
- elementEntry.scrollY = element.scrollTop || 0
283
- }
284
- }
285
-
286
- return state
287
- })
288
- }
289
-
290
- // Throttle the scroll event to avoid excessive updates
291
- if (typeof document !== 'undefined') {
292
- document.addEventListener('scroll', throttle(onScroll, 100), true)
293
- }
294
-
295
- router.subscribe('onRendered', (event) => {
296
- // unobserveDom()
297
-
298
- const cacheKey = getKey(event.toLocation)
299
-
300
- // If the user doesn't want to restore the scroll position,
301
- // we don't need to do anything.
302
- if (!router.resetNextScroll) {
303
- router.resetNextScroll = true
304
- return
305
- }
306
-
307
- restoreScroll(
308
- storageKey,
309
- cacheKey,
310
- router.options.scrollRestorationBehavior || undefined,
311
- router.isScrollRestoring || undefined,
312
- router.options.scrollToTopSelectors || undefined,
313
- )
314
-
315
- if (router.isScrollRestoring) {
316
- // Mark the location as having been seen
317
- scrollRestorationCache.set((state) => {
318
- state[cacheKey] = state[cacheKey] || ({} as ScrollRestorationByElement)
319
-
320
- return state
321
- })
322
- }
323
- })
324
- }
325
-
326
9
  export function ScrollRestoration() {
327
10
  const router = useRouter()
328
11
  const getKey =