@tanstack/react-router 1.114.14 → 1.114.16

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,326 +1,10 @@
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
- import type {
5
- AnyRouter,
6
- NonNullableUpdater,
7
- ParsedLocation,
8
- } from '@tanstack/router-core'
9
-
10
- export type ScrollRestorationEntry = { scrollX: number; scrollY: number }
11
-
12
- export type ScrollRestorationByElement = Record<string, ScrollRestorationEntry>
13
-
14
- export type ScrollRestorationByKey = Record<string, ScrollRestorationByElement>
15
-
16
- export type ScrollRestorationCache = {
17
- state: ScrollRestorationByKey
18
- set: (updater: NonNullableUpdater<ScrollRestorationByKey>) => void
19
- }
20
- export type ScrollRestorationOptions = {
21
- getKey?: (location: ParsedLocation) => string
22
- scrollBehavior?: ScrollToOptions['behavior']
23
- }
24
-
25
- export const storageKey = 'tsr-scroll-restoration-v1_3'
26
- let sessionsStorage = false
27
- try {
28
- sessionsStorage =
29
- typeof window !== 'undefined' && typeof window.sessionStorage === 'object'
30
- } catch {}
31
- const throttle = (fn: (...args: Array<any>) => void, wait: number) => {
32
- let timeout: any
33
- return (...args: Array<any>) => {
34
- if (!timeout) {
35
- timeout = setTimeout(() => {
36
- fn(...args)
37
- timeout = null
38
- }, wait)
39
- }
40
- }
41
- }
42
- export const scrollRestorationCache: ScrollRestorationCache = sessionsStorage
43
- ? (() => {
44
- const state: ScrollRestorationByKey =
45
- JSON.parse(window.sessionStorage.getItem(storageKey) || 'null') || {}
46
-
47
- return {
48
- state,
49
- // This setter is simply to make sure that we set the sessionStorage right
50
- // after the state is updated. It doesn't necessarily need to be a functional
51
- // update.
52
- set: (updater) => (
53
- (scrollRestorationCache.state =
54
- // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
55
- functionalUpdate(updater, scrollRestorationCache.state) ||
56
- scrollRestorationCache.state),
57
- window.sessionStorage.setItem(
58
- storageKey,
59
- JSON.stringify(scrollRestorationCache.state),
60
- )
61
- ),
62
- }
63
- })()
64
- : (undefined as any)
65
- /**
66
- * The default `getKey` function for `useScrollRestoration`.
67
- * It returns the `key` from the location state or the `href` of the location.
68
- *
69
- * The `location.href` is used as a fallback to support the use case where the location state is not available like the initial render.
70
- */
71
-
72
- export const defaultGetScrollRestorationKey = (location: ParsedLocation) => {
73
- return location.state.key! || location.href
74
- }
75
-
76
- export function getCssSelector(el: any): string {
77
- const path = []
78
- let parent
79
- while ((parent = el.parentNode)) {
80
- path.unshift(
81
- `${el.tagName}:nth-child(${([].indexOf as any).call(parent.children, el) + 1})`,
82
- )
83
- el = parent
84
- }
85
- return `${path.join(' > ')}`.toLowerCase()
86
- }
87
-
88
- let ignoreScroll = false
89
-
90
- // NOTE: This function must remain pure and not use any outside variables
91
- // unless they are passed in as arguments. Why? Because we need to be able to
92
- // toString() it into a script tag to execute as early as possible in the browser
93
- // during SSR. Additionally, we also call it from within the router lifecycle
94
- export function restoreScroll(
95
- storageKey: string,
96
- key: string | undefined,
97
- behavior: ScrollToOptions['behavior'] | undefined,
98
- shouldScrollRestoration: boolean | undefined,
99
- scrollToTopSelectors: Array<string> | undefined,
100
- ) {
101
- let byKey: ScrollRestorationByKey
102
-
103
- try {
104
- byKey = JSON.parse(sessionStorage.getItem(storageKey) || '{}')
105
- } catch (error: any) {
106
- console.error(error)
107
- return
108
- }
109
-
110
- const resolvedKey = key || window.history.state?.key
111
- const elementEntries = byKey[resolvedKey]
112
-
113
- //
114
- ignoreScroll = true
115
-
116
- //
117
- ;(() => {
118
- // If we have a cached entry for this location state,
119
- // we always need to prefer that over the hash scroll.
120
- if (shouldScrollRestoration && elementEntries) {
121
- for (const elementSelector in elementEntries) {
122
- const entry = elementEntries[elementSelector]!
123
- if (elementSelector === 'window') {
124
- window.scrollTo({
125
- top: entry.scrollY,
126
- left: entry.scrollX,
127
- behavior,
128
- })
129
- } else if (elementSelector) {
130
- const element = document.querySelector(elementSelector)
131
- if (element) {
132
- element.scrollLeft = entry.scrollX
133
- element.scrollTop = entry.scrollY
134
- }
135
- }
136
- }
137
-
138
- return
139
- }
140
-
141
- // If we don't have a cached entry for the hash,
142
- // Which means we've never seen this location before,
143
- // we need to check if there is a hash in the URL.
144
- // If there is, we need to scroll it's ID into view.
145
- const hash = window.location.hash.split('#')[1]
146
-
147
- if (hash) {
148
- const hashScrollIntoViewOptions =
149
- (window.history.state || {}).__hashScrollIntoViewOptions ?? true
150
-
151
- if (hashScrollIntoViewOptions) {
152
- const el = document.getElementById(hash)
153
- if (el) {
154
- el.scrollIntoView(hashScrollIntoViewOptions)
155
- }
156
- }
157
-
158
- return
159
- }
160
-
161
- // If there is no cached entry for the hash and there is no hash in the URL,
162
- // we need to scroll to the top of the page for every scrollToTop element
163
- ;[
164
- 'window',
165
- ...(scrollToTopSelectors?.filter((d) => d !== 'window') ?? []),
166
- ].forEach((selector) => {
167
- const element =
168
- selector === 'window' ? window : document.querySelector(selector)
169
- if (element) {
170
- element.scrollTo({
171
- top: 0,
172
- left: 0,
173
- behavior,
174
- })
175
- }
176
- })
177
- })()
178
-
179
- //
180
- ignoreScroll = false
181
- }
182
-
183
- export function setupScrollRestoration(router: AnyRouter, force?: boolean) {
184
- const shouldScrollRestoration =
185
- force ?? router.options.scrollRestoration ?? false
186
-
187
- if (shouldScrollRestoration) {
188
- router.isScrollRestoring = true
189
- }
190
-
191
- if (typeof document === 'undefined' || router.isScrollRestorationSetup) {
192
- return
193
- }
194
-
195
- router.isScrollRestorationSetup = true
196
-
197
- //
198
- ignoreScroll = false
199
-
200
- const getKey =
201
- router.options.getScrollRestorationKey || defaultGetScrollRestorationKey
202
-
203
- window.history.scrollRestoration = 'manual'
204
-
205
- // // Create a MutationObserver to monitor DOM changes
206
- // const mutationObserver = new MutationObserver(() => {
207
- // ;ignoreScroll = true
208
- // requestAnimationFrame(() => {
209
- // ;ignoreScroll = false
210
-
211
- // // Attempt to restore scroll position on each dom
212
- // // mutation until the user scrolls. We do this
213
- // // because dynamic content may come in at different
214
- // // ticks after the initial render and we want to
215
- // // keep up with that content as much as possible.
216
- // // As soon as the user scrolls, we no longer need
217
- // // to attempt router.
218
- // // console.log('mutation observer restoreScroll')
219
- // restoreScroll(
220
- // storageKey,
221
- // getKey(router.state.location),
222
- // router.options.scrollRestorationBehavior,
223
- // )
224
- // })
225
- // })
226
-
227
- // const observeDom = () => {
228
- // // Observe changes to the entire document
229
- // mutationObserver.observe(document, {
230
- // childList: true, // Detect added or removed child nodes
231
- // subtree: true, // Monitor all descendants
232
- // characterData: true, // Detect text content changes
233
- // })
234
- // }
235
-
236
- // const unobserveDom = () => {
237
- // mutationObserver.disconnect()
238
- // }
239
-
240
- // observeDom()
241
-
242
- const onScroll = (event: Event) => {
243
- // unobserveDom()
244
-
245
- if (ignoreScroll || !router.isScrollRestoring) {
246
- return
247
- }
248
-
249
- let elementSelector = ''
250
-
251
- if (event.target === document || event.target === window) {
252
- elementSelector = 'window'
253
- } else {
254
- const attrId = (event.target as Element).getAttribute(
255
- 'data-scroll-restoration-id',
256
- )
257
-
258
- if (attrId) {
259
- elementSelector = `[data-scroll-restoration-id="${attrId}"]`
260
- } else {
261
- elementSelector = getCssSelector(event.target)
262
- }
263
- }
264
-
265
- const restoreKey = getKey(router.state.location)
266
-
267
- scrollRestorationCache.set((state) => {
268
- const keyEntry = (state[restoreKey] =
269
- state[restoreKey] || ({} as ScrollRestorationByElement))
270
-
271
- const elementEntry = (keyEntry[elementSelector] =
272
- keyEntry[elementSelector] || ({} as ScrollRestorationEntry))
273
-
274
- if (elementSelector === 'window') {
275
- elementEntry.scrollX = window.scrollX || 0
276
- elementEntry.scrollY = window.scrollY || 0
277
- } else if (elementSelector) {
278
- const element = document.querySelector(elementSelector)
279
- if (element) {
280
- elementEntry.scrollX = element.scrollLeft || 0
281
- elementEntry.scrollY = element.scrollTop || 0
282
- }
283
- }
284
-
285
- return state
286
- })
287
- }
288
-
289
- // Throttle the scroll event to avoid excessive updates
290
- if (typeof document !== 'undefined') {
291
- document.addEventListener('scroll', throttle(onScroll, 100), true)
292
- }
293
-
294
- router.subscribe('onRendered', (event) => {
295
- // unobserveDom()
296
-
297
- const cacheKey = getKey(event.toLocation)
298
-
299
- // If the user doesn't want to restore the scroll position,
300
- // we don't need to do anything.
301
- if (!router.resetNextScroll) {
302
- router.resetNextScroll = true
303
- return
304
- }
305
-
306
- restoreScroll(
307
- storageKey,
308
- cacheKey,
309
- router.options.scrollRestorationBehavior || undefined,
310
- router.isScrollRestoring || undefined,
311
- router.options.scrollToTopSelectors || undefined,
312
- )
313
-
314
- if (router.isScrollRestoring) {
315
- // Mark the location as having been seen
316
- scrollRestorationCache.set((state) => {
317
- state[cacheKey] = state[cacheKey] || ({} as ScrollRestorationByElement)
318
-
319
- return state
320
- })
321
- }
322
- })
323
- }
324
8
 
325
9
  export function ScrollRestoration() {
326
10
  const router = useRouter()
@@ -1,135 +1,19 @@
1
1
  import type {
2
2
  AnyRouter,
3
3
  Constrain,
4
- ConstrainLiteral,
5
- FromPathOption,
6
- NavigateOptions,
7
- PathParamOptions,
8
- Redirect,
4
+ InferFrom,
5
+ InferMaskFrom,
6
+ InferMaskTo,
7
+ InferSelected,
8
+ InferShouldThrow,
9
+ InferStrict,
10
+ InferTo,
9
11
  RegisteredRouter,
10
- RouteIds,
11
- SearchParamOptions,
12
- ToPathOption,
13
- UseParamsResult,
14
- UseSearchResult,
15
12
  } from '@tanstack/router-core'
16
13
  import type { LinkComponentProps } from './link'
17
14
  import type { UseParamsOptions } from './useParams'
18
15
  import type { UseSearchOptions } from './useSearch'
19
16
 
20
- export type ValidateFromPath<
21
- TRouter extends AnyRouter = RegisteredRouter,
22
- TFrom = string,
23
- > = FromPathOption<TRouter, TFrom>
24
-
25
- export type ValidateToPath<
26
- TRouter extends AnyRouter = RegisteredRouter,
27
- TTo extends string | undefined = undefined,
28
- TFrom extends string = string,
29
- > = ToPathOption<TRouter, TFrom, TTo>
30
-
31
- export type ValidateSearch<
32
- TRouter extends AnyRouter = RegisteredRouter,
33
- TTo extends string | undefined = undefined,
34
- TFrom extends string = string,
35
- > = SearchParamOptions<TRouter, TFrom, TTo>
36
-
37
- export type ValidateParams<
38
- TRouter extends AnyRouter = RegisteredRouter,
39
- TTo extends string | undefined = undefined,
40
- TFrom extends string = string,
41
- > = PathParamOptions<TRouter, TFrom, TTo>
42
-
43
- /**
44
- * @internal
45
- */
46
- export type InferFrom<
47
- TOptions,
48
- TDefaultFrom extends string = string,
49
- > = TOptions extends {
50
- from: infer TFrom extends string
51
- }
52
- ? TFrom
53
- : TDefaultFrom
54
-
55
- /**
56
- * @internal
57
- */
58
- export type InferTo<TOptions> = TOptions extends {
59
- to: infer TTo extends string
60
- }
61
- ? TTo
62
- : undefined
63
-
64
- /**
65
- * @internal
66
- */
67
- export type InferMaskTo<TOptions> = TOptions extends {
68
- mask: { to: infer TTo extends string }
69
- }
70
- ? TTo
71
- : ''
72
-
73
- export type InferMaskFrom<TOptions> = TOptions extends {
74
- mask: { from: infer TFrom extends string }
75
- }
76
- ? TFrom
77
- : string
78
-
79
- export type ValidateNavigateOptions<
80
- TRouter extends AnyRouter = RegisteredRouter,
81
- TOptions = unknown,
82
- TDefaultFrom extends string = string,
83
- > = Constrain<
84
- TOptions,
85
- NavigateOptions<
86
- TRouter,
87
- InferFrom<TOptions, TDefaultFrom>,
88
- InferTo<TOptions>,
89
- InferMaskFrom<TOptions>,
90
- InferMaskTo<TOptions>
91
- >
92
- >
93
-
94
- export type ValidateNavigateOptionsArray<
95
- TRouter extends AnyRouter = RegisteredRouter,
96
- TOptions extends ReadonlyArray<any> = ReadonlyArray<unknown>,
97
- TDefaultFrom extends string = string,
98
- > = {
99
- [K in keyof TOptions]: ValidateNavigateOptions<
100
- TRouter,
101
- TOptions[K],
102
- TDefaultFrom
103
- >
104
- }
105
-
106
- export type ValidateRedirectOptions<
107
- TRouter extends AnyRouter = RegisteredRouter,
108
- TOptions = unknown,
109
- TDefaultFrom extends string = string,
110
- > = Constrain<
111
- TOptions,
112
- Redirect<
113
- TRouter,
114
- InferFrom<TOptions, TDefaultFrom>,
115
- InferTo<TOptions>,
116
- InferMaskFrom<TOptions>,
117
- InferMaskTo<TOptions>
118
- >
119
- >
120
-
121
- export type ValidateRedirectOptionsArray<
122
- TRouter extends AnyRouter = RegisteredRouter,
123
- TOptions extends ReadonlyArray<any> = ReadonlyArray<unknown>,
124
- TDefaultFrom extends string = string,
125
- > = {
126
- [K in keyof TOptions]: ValidateRedirectOptions<
127
- TRouter,
128
- TOptions[K],
129
- TDefaultFrom
130
- >
131
- }
132
-
133
17
  export type ValidateLinkOptions<
134
18
  TRouter extends AnyRouter = RegisteredRouter,
135
19
  TOptions = unknown,
@@ -147,52 +31,6 @@ export type ValidateLinkOptions<
147
31
  >
148
32
  >
149
33
 
150
- export type ValidateLinkOptionsArray<
151
- TRouter extends AnyRouter = RegisteredRouter,
152
- TOptions extends ReadonlyArray<any> = ReadonlyArray<unknown>,
153
- TDefaultFrom extends string = string,
154
- TComp = 'a',
155
- > = {
156
- [K in keyof TOptions]: ValidateLinkOptions<
157
- TRouter,
158
- TOptions[K],
159
- TDefaultFrom,
160
- TComp
161
- >
162
- }
163
-
164
- export type ValidateId<
165
- TRouter extends AnyRouter = RegisteredRouter,
166
- TId extends string = string,
167
- > = ConstrainLiteral<TId, RouteIds<TRouter['routeTree']>>
168
-
169
- /**
170
- * @internal
171
- */
172
- export type InferStrict<TOptions> = TOptions extends {
173
- strict: infer TStrict extends boolean
174
- }
175
- ? TStrict
176
- : true
177
-
178
- /**
179
- * @internal
180
- */
181
- export type InferShouldThrow<TOptions> = TOptions extends {
182
- shouldThrow: infer TShouldThrow extends boolean
183
- }
184
- ? TShouldThrow
185
- : true
186
-
187
- /**
188
- * @internal
189
- */
190
- export type InferSelected<TOptions> = TOptions extends {
191
- select: (...args: Array<any>) => infer TSelected
192
- }
193
- ? TSelected
194
- : unknown
195
-
196
34
  /**
197
35
  * @internal
198
36
  */
@@ -217,16 +55,6 @@ export type ValidateUseSearchOptions<
217
55
  >
218
56
  >
219
57
 
220
- export type ValidateUseSearchResult<
221
- TOptions,
222
- TRouter extends AnyRouter = RegisteredRouter,
223
- > = UseSearchResult<
224
- TRouter,
225
- InferFrom<TOptions>,
226
- InferStrict<TOptions>,
227
- InferSelected<TOptions>
228
- >
229
-
230
58
  export type ValidateUseParamsOptions<
231
59
  TOptions,
232
60
  TRouter extends AnyRouter = RegisteredRouter,
@@ -241,16 +69,16 @@ export type ValidateUseParamsOptions<
241
69
  InferSelected<TOptions>
242
70
  >
243
71
  >
244
-
245
- export type ValidateUseParamsResult<
246
- TOptions,
72
+ export type ValidateLinkOptionsArray<
247
73
  TRouter extends AnyRouter = RegisteredRouter,
248
- > = Constrain<
249
- TOptions,
250
- UseParamsResult<
74
+ TOptions extends ReadonlyArray<any> = ReadonlyArray<unknown>,
75
+ TDefaultFrom extends string = string,
76
+ TComp = 'a',
77
+ > = {
78
+ [K in keyof TOptions]: ValidateLinkOptions<
251
79
  TRouter,
252
- InferFrom<TOptions>,
253
- InferStrict<TOptions>,
254
- InferSelected<TOptions>
80
+ TOptions[K],
81
+ TDefaultFrom,
82
+ TComp
255
83
  >
256
- >
84
+ }