@tanstack/react-router 1.97.26 → 1.98.1
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.
- package/dist/cjs/Match.cjs +78 -28
- package/dist/cjs/Match.cjs.map +1 -1
- package/dist/cjs/Matches.cjs +4 -1
- package/dist/cjs/Matches.cjs.map +1 -1
- package/dist/cjs/Matches.d.cts +2 -0
- package/dist/cjs/ScriptOnce.cjs +1 -1
- package/dist/cjs/ScriptOnce.cjs.map +1 -1
- package/dist/cjs/ScrollRestoration.cjs +39 -0
- package/dist/cjs/ScrollRestoration.cjs.map +1 -0
- package/dist/cjs/ScrollRestoration.d.cts +15 -0
- package/dist/cjs/Transitioner.cjs +3 -33
- package/dist/cjs/Transitioner.cjs.map +1 -1
- package/dist/cjs/index.cjs +3 -4
- package/dist/cjs/index.cjs.map +1 -1
- package/dist/cjs/index.d.cts +2 -3
- package/dist/cjs/route.cjs.map +1 -1
- package/dist/cjs/route.d.cts +10 -2
- package/dist/cjs/router.cjs +37 -23
- package/dist/cjs/router.cjs.map +1 -1
- package/dist/cjs/router.d.cts +28 -27
- package/dist/cjs/scroll-restoration.cjs +168 -165
- package/dist/cjs/scroll-restoration.cjs.map +1 -1
- package/dist/cjs/scroll-restoration.d.cts +25 -15
- package/dist/esm/Match.js +80 -30
- package/dist/esm/Match.js.map +1 -1
- package/dist/esm/Matches.d.ts +2 -0
- package/dist/esm/Matches.js +4 -1
- package/dist/esm/Matches.js.map +1 -1
- package/dist/esm/ScriptOnce.js +1 -1
- package/dist/esm/ScriptOnce.js.map +1 -1
- package/dist/esm/ScrollRestoration.d.ts +15 -0
- package/dist/esm/ScrollRestoration.js +39 -0
- package/dist/esm/ScrollRestoration.js.map +1 -0
- package/dist/esm/Transitioner.js +4 -34
- package/dist/esm/Transitioner.js.map +1 -1
- package/dist/esm/index.d.ts +2 -3
- package/dist/esm/index.js +1 -2
- package/dist/esm/route.d.ts +10 -2
- package/dist/esm/route.js.map +1 -1
- package/dist/esm/router.d.ts +28 -27
- package/dist/esm/router.js +38 -24
- package/dist/esm/router.js.map +1 -1
- package/dist/esm/scroll-restoration.d.ts +25 -15
- package/dist/esm/scroll-restoration.js +168 -148
- package/dist/esm/scroll-restoration.js.map +1 -1
- package/package.json +3 -3
- package/src/Match.tsx +101 -54
- package/src/Matches.tsx +3 -1
- package/src/ScriptOnce.tsx +1 -1
- package/src/ScrollRestoration.tsx +65 -0
- package/src/Transitioner.tsx +4 -40
- package/src/index.tsx +3 -3
- package/src/route.ts +38 -1
- package/src/router.ts +75 -49
- package/src/scroll-restoration.tsx +271 -183
package/dist/cjs/router.d.cts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { Store, NoInfer } from '@tanstack/react-store';
|
|
2
2
|
import { HistoryLocation, HistoryState, ParsedHistoryState, RouterHistory } from '@tanstack/history';
|
|
3
3
|
import { AnyContext, AnySchema, CommitLocationOptions, ControlledPromise, Manifest, NonNullableUpdater, ParsedLocation, PickAsRequired, ResolveRelativePath, SearchParser, SearchSerializer, StartSerializer, TrailingSlashOption, Updater, ViewTransitionOptions } from '@tanstack/router-core';
|
|
4
|
-
import { AnyRoute, AnyRouteWithContext, ErrorRouteComponent, NotFoundRouteComponent, RootRoute, RouteComponent, RouteMask } from './route.cjs';
|
|
4
|
+
import { AnyRoute, AnyRouteWithContext, ErrorRouteComponent, MakeRemountDepsOptionsUnion, NotFoundRouteComponent, RootRoute, RouteComponent, RouteMask } from './route.cjs';
|
|
5
5
|
import { FullSearchSchema, RouteById, RoutePaths, RoutesById, RoutesByPath } from './routeInfo.cjs';
|
|
6
6
|
import { AnyRouteMatch, MakeRouteMatch, MakeRouteMatchUnion, MatchRouteOptions } from './Matches.cjs';
|
|
7
7
|
import { BuildLocationFn, NavigateFn } from './RouterProvider.cjs';
|
|
@@ -331,6 +331,15 @@ export interface RouterOptions<TRouteTree extends AnyRoute, TTrailingSlashOption
|
|
|
331
331
|
* @link [Guide](https://tanstack.com/router/latest/docs/framework/react/guide/path-params#allowed-characters)
|
|
332
332
|
*/
|
|
333
333
|
pathParamsAllowedCharacters?: Array<';' | ':' | '@' | '&' | '=' | '+' | '$' | ','>;
|
|
334
|
+
defaultRemountDeps?: (opts: MakeRemountDepsOptionsUnion<TRouteTree>) => any;
|
|
335
|
+
/**
|
|
336
|
+
* If `false`, scroll restoration will be disabled
|
|
337
|
+
*
|
|
338
|
+
* @default true
|
|
339
|
+
*/
|
|
340
|
+
scrollRestoration?: boolean;
|
|
341
|
+
getScrollRestorationKey?: (location: ParsedLocation) => string;
|
|
342
|
+
scrollRestorationBehavior?: ScrollBehavior;
|
|
334
343
|
}
|
|
335
344
|
export interface RouterErrorSerializer<TSerializedError> {
|
|
336
345
|
serialize: (err: unknown) => TSerializedError;
|
|
@@ -345,7 +354,7 @@ export interface RouterState<TRouteTree extends AnyRoute = AnyRoute, TRouteMatch
|
|
|
345
354
|
pendingMatches?: Array<TRouteMatch>;
|
|
346
355
|
cachedMatches: Array<TRouteMatch>;
|
|
347
356
|
location: ParsedLocation<FullSearchSchema<TRouteTree>>;
|
|
348
|
-
resolvedLocation
|
|
357
|
+
resolvedLocation?: ParsedLocation<FullSearchSchema<TRouteTree>>;
|
|
349
358
|
statusCode: number;
|
|
350
359
|
redirect?: ResolvedRedirect;
|
|
351
360
|
}
|
|
@@ -374,46 +383,36 @@ export interface MatchedRoutesResult {
|
|
|
374
383
|
}
|
|
375
384
|
export type RouterConstructorOptions<TRouteTree extends AnyRoute, TTrailingSlashOption extends TrailingSlashOption, TDefaultStructuralSharingOption extends boolean, TRouterHistory extends RouterHistory, TDehydrated extends Record<string, any>> = Omit<RouterOptions<TRouteTree, TTrailingSlashOption, TDefaultStructuralSharingOption, TRouterHistory, TDehydrated>, 'context'> & RouterContextOptions<TRouteTree>;
|
|
376
385
|
export declare const componentTypes: readonly ["component", "errorComponent", "pendingComponent", "notFoundComponent"];
|
|
386
|
+
type NavigationEventInfo = {
|
|
387
|
+
fromLocation?: ParsedLocation;
|
|
388
|
+
toLocation: ParsedLocation;
|
|
389
|
+
pathChanged: boolean;
|
|
390
|
+
hrefChanged: boolean;
|
|
391
|
+
hashChanged: boolean;
|
|
392
|
+
};
|
|
377
393
|
export type RouterEvents = {
|
|
378
394
|
onBeforeNavigate: {
|
|
379
395
|
type: 'onBeforeNavigate';
|
|
380
|
-
|
|
381
|
-
toLocation: ParsedLocation;
|
|
382
|
-
pathChanged: boolean;
|
|
383
|
-
hrefChanged: boolean;
|
|
384
|
-
};
|
|
396
|
+
} & NavigationEventInfo;
|
|
385
397
|
onBeforeLoad: {
|
|
386
398
|
type: 'onBeforeLoad';
|
|
387
|
-
|
|
388
|
-
toLocation: ParsedLocation;
|
|
389
|
-
pathChanged: boolean;
|
|
390
|
-
hrefChanged: boolean;
|
|
391
|
-
};
|
|
399
|
+
} & NavigationEventInfo;
|
|
392
400
|
onLoad: {
|
|
393
401
|
type: 'onLoad';
|
|
394
|
-
|
|
395
|
-
toLocation: ParsedLocation;
|
|
396
|
-
pathChanged: boolean;
|
|
397
|
-
hrefChanged: boolean;
|
|
398
|
-
};
|
|
402
|
+
} & NavigationEventInfo;
|
|
399
403
|
onResolved: {
|
|
400
404
|
type: 'onResolved';
|
|
401
|
-
|
|
402
|
-
toLocation: ParsedLocation;
|
|
403
|
-
pathChanged: boolean;
|
|
404
|
-
hrefChanged: boolean;
|
|
405
|
-
};
|
|
405
|
+
} & NavigationEventInfo;
|
|
406
406
|
onBeforeRouteMount: {
|
|
407
407
|
type: 'onBeforeRouteMount';
|
|
408
|
-
|
|
409
|
-
toLocation: ParsedLocation;
|
|
410
|
-
pathChanged: boolean;
|
|
411
|
-
hrefChanged: boolean;
|
|
412
|
-
};
|
|
408
|
+
} & NavigationEventInfo;
|
|
413
409
|
onInjectedHtml: {
|
|
414
410
|
type: 'onInjectedHtml';
|
|
415
411
|
promise: Promise<string>;
|
|
416
412
|
};
|
|
413
|
+
onRendered: {
|
|
414
|
+
type: 'onRendered';
|
|
415
|
+
} & NavigationEventInfo;
|
|
417
416
|
};
|
|
418
417
|
export type RouterEvent = RouterEvents[keyof RouterEvents];
|
|
419
418
|
export type RouterListener<TRouterEvent extends RouterEvent> = {
|
|
@@ -434,6 +433,8 @@ export declare class Router<in out TRouteTree extends AnyRoute, in out TTrailing
|
|
|
434
433
|
isViewTransitionTypesSupported?: boolean;
|
|
435
434
|
subscribers: Set<RouterListener<RouterEvent>>;
|
|
436
435
|
viewTransitionPromise?: ControlledPromise<true>;
|
|
436
|
+
isScrollRestoring: boolean;
|
|
437
|
+
isScrollRestorationSetup: boolean;
|
|
437
438
|
__store: Store<RouterState<TRouteTree>>;
|
|
438
439
|
options: PickAsRequired<RouterOptions<TRouteTree, TTrailingSlashOption, TDefaultStructuralSharingOption, TRouterHistory, TDehydrated>, 'stringifySearch' | 'parseSearch' | 'context'>;
|
|
439
440
|
history: TRouterHistory;
|
|
@@ -1,191 +1,194 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
3
|
-
const
|
|
3
|
+
const jsxRuntime = require("react/jsx-runtime");
|
|
4
4
|
const routerCore = require("@tanstack/router-core");
|
|
5
5
|
const useRouter = require("./useRouter.cjs");
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
if (e) {
|
|
9
|
-
for (const k in e) {
|
|
10
|
-
if (k !== "default") {
|
|
11
|
-
const d = Object.getOwnPropertyDescriptor(e, k);
|
|
12
|
-
Object.defineProperty(n, k, d.get ? d : {
|
|
13
|
-
enumerable: true,
|
|
14
|
-
get: () => e[k]
|
|
15
|
-
});
|
|
16
|
-
}
|
|
17
|
-
}
|
|
18
|
-
}
|
|
19
|
-
n.default = e;
|
|
20
|
-
return Object.freeze(n);
|
|
21
|
-
}
|
|
22
|
-
const React__namespace = /* @__PURE__ */ _interopNamespaceDefault(React);
|
|
23
|
-
const useLayoutEffect = typeof window !== "undefined" ? React__namespace.useLayoutEffect : React__namespace.useEffect;
|
|
24
|
-
const windowKey = "window";
|
|
25
|
-
const delimiter = "___";
|
|
26
|
-
let weakScrolledElements = /* @__PURE__ */ new WeakSet();
|
|
6
|
+
const ScriptOnce = require("./ScriptOnce.cjs");
|
|
7
|
+
const storageKey = "tsr-scroll-restoration-v1_3";
|
|
27
8
|
const sessionsStorage = typeof window !== "undefined" && window.sessionStorage;
|
|
28
|
-
const
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
9
|
+
const throttle = (fn, wait) => {
|
|
10
|
+
let timeout;
|
|
11
|
+
return (...args) => {
|
|
12
|
+
if (!timeout) {
|
|
13
|
+
timeout = setTimeout(() => {
|
|
14
|
+
fn(...args);
|
|
15
|
+
timeout = null;
|
|
16
|
+
}, wait);
|
|
17
|
+
}
|
|
18
|
+
};
|
|
19
|
+
};
|
|
20
|
+
const scrollRestorationCache = sessionsStorage ? (() => {
|
|
21
|
+
const state = JSON.parse(window.sessionStorage.getItem(storageKey) || "null") || {};
|
|
33
22
|
return {
|
|
34
23
|
state,
|
|
35
|
-
set
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
24
|
+
// This setter is simply to make sure that we set the sessionStorage right
|
|
25
|
+
// after the state is updated. It doesn't necessarily need to be a functional
|
|
26
|
+
// update.
|
|
27
|
+
set: (updater) => (scrollRestorationCache.state = // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
|
|
28
|
+
routerCore.functionalUpdate(updater, scrollRestorationCache.state) || scrollRestorationCache.state, window.sessionStorage.setItem(
|
|
29
|
+
storageKey,
|
|
30
|
+
JSON.stringify(scrollRestorationCache.state)
|
|
31
|
+
))
|
|
39
32
|
};
|
|
40
33
|
})() : void 0;
|
|
41
|
-
const
|
|
34
|
+
const defaultGetScrollRestorationKey = (location) => {
|
|
42
35
|
return location.state.key || location.href;
|
|
43
36
|
};
|
|
44
|
-
function
|
|
45
|
-
const
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
37
|
+
function getCssSelector(el) {
|
|
38
|
+
const path = [];
|
|
39
|
+
let parent;
|
|
40
|
+
while (parent = el.parentNode) {
|
|
41
|
+
path.unshift(
|
|
42
|
+
`${el.tagName}:nth-child(${[].indexOf.call(parent.children, el) + 1})`
|
|
43
|
+
);
|
|
44
|
+
el = parent;
|
|
45
|
+
}
|
|
46
|
+
return `${path.join(" > ")}`.toLowerCase();
|
|
47
|
+
}
|
|
48
|
+
let ignoreScroll = false;
|
|
49
|
+
function restoreScroll(storageKey2, key, behavior, shouldScrollRestoration) {
|
|
50
|
+
var _a;
|
|
51
|
+
let byKey;
|
|
52
|
+
try {
|
|
53
|
+
byKey = JSON.parse(sessionStorage.getItem(storageKey2) || "{}");
|
|
54
|
+
} catch (error) {
|
|
55
|
+
console.error(error);
|
|
56
|
+
return;
|
|
57
|
+
}
|
|
58
|
+
const resolvedKey = key || ((_a = window.history.state) == null ? void 0 : _a.key);
|
|
59
|
+
const elementEntries = byKey[resolvedKey];
|
|
60
|
+
ignoreScroll = true;
|
|
61
|
+
(() => {
|
|
62
|
+
if (shouldScrollRestoration && elementEntries) {
|
|
63
|
+
for (const elementSelector in elementEntries) {
|
|
64
|
+
const entry = elementEntries[elementSelector];
|
|
65
|
+
if (elementSelector === "window") {
|
|
66
|
+
console.log("windowRestored", entry);
|
|
67
|
+
window.scrollTo({
|
|
68
|
+
top: entry.scrollY,
|
|
69
|
+
left: entry.scrollX,
|
|
70
|
+
behavior
|
|
71
|
+
});
|
|
72
|
+
} else if (elementSelector) {
|
|
73
|
+
const element = document.querySelector(elementSelector);
|
|
74
|
+
if (element) {
|
|
75
|
+
element.scrollLeft = entry.scrollX;
|
|
76
|
+
element.scrollTop = entry.scrollY;
|
|
75
77
|
}
|
|
76
|
-
}
|
|
78
|
+
}
|
|
77
79
|
}
|
|
78
|
-
|
|
79
|
-
if (typeof document !== "undefined") {
|
|
80
|
-
document.addEventListener("scroll", onScroll, true);
|
|
80
|
+
return;
|
|
81
81
|
}
|
|
82
|
-
const
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
} else if (elementSelector) {
|
|
91
|
-
const element = document.querySelector(elementSelector);
|
|
92
|
-
entry.scrollX = (element == null ? void 0 : element.scrollLeft) || 0;
|
|
93
|
-
entry.scrollY = (element == null ? void 0 : element.scrollTop) || 0;
|
|
94
|
-
}
|
|
95
|
-
cache.set((c) => {
|
|
96
|
-
const next = { ...c.next };
|
|
97
|
-
delete next[elementSelector];
|
|
98
|
-
return {
|
|
99
|
-
...c,
|
|
100
|
-
next,
|
|
101
|
-
cached: {
|
|
102
|
-
...c.cached,
|
|
103
|
-
[[restoreKey, elementSelector].join(delimiter)]: entry
|
|
104
|
-
}
|
|
105
|
-
};
|
|
106
|
-
});
|
|
82
|
+
const hash = window.location.hash.split("#")[1];
|
|
83
|
+
if (hash) {
|
|
84
|
+
const hashScrollIntoViewOptions = (window.history.state || {}).__hashScrollIntoViewOptions ?? true;
|
|
85
|
+
if (hashScrollIntoViewOptions) {
|
|
86
|
+
console.log("scrollIntoView");
|
|
87
|
+
const el = document.getElementById(hash);
|
|
88
|
+
if (el) {
|
|
89
|
+
el.scrollIntoView(hashScrollIntoViewOptions);
|
|
107
90
|
}
|
|
108
91
|
}
|
|
92
|
+
return;
|
|
93
|
+
}
|
|
94
|
+
window.scrollTo({
|
|
95
|
+
top: 0,
|
|
96
|
+
left: 0,
|
|
97
|
+
behavior
|
|
109
98
|
});
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
(event) => {
|
|
113
|
-
if (event.hrefChanged) {
|
|
114
|
-
if (!router.resetNextScroll) {
|
|
115
|
-
return;
|
|
116
|
-
}
|
|
117
|
-
router.resetNextScroll = true;
|
|
118
|
-
const restoreKey = getKey(event.toLocation);
|
|
119
|
-
let windowRestored = false;
|
|
120
|
-
for (const cacheKey in cache.state.cached) {
|
|
121
|
-
const entry = cache.state.cached[cacheKey];
|
|
122
|
-
const [key, elementSelector] = cacheKey.split(delimiter);
|
|
123
|
-
if (key === restoreKey) {
|
|
124
|
-
if (elementSelector === windowKey) {
|
|
125
|
-
windowRestored = true;
|
|
126
|
-
window.scrollTo({
|
|
127
|
-
top: entry.scrollY,
|
|
128
|
-
left: entry.scrollX,
|
|
129
|
-
behavior: options == null ? void 0 : options.scrollBehavior
|
|
130
|
-
});
|
|
131
|
-
} else if (elementSelector) {
|
|
132
|
-
const element = document.querySelector(elementSelector);
|
|
133
|
-
if (element) {
|
|
134
|
-
element.scrollLeft = entry.scrollX;
|
|
135
|
-
element.scrollTop = entry.scrollY;
|
|
136
|
-
}
|
|
137
|
-
}
|
|
138
|
-
}
|
|
139
|
-
}
|
|
140
|
-
if (!windowRestored) {
|
|
141
|
-
window.scrollTo(0, 0);
|
|
142
|
-
}
|
|
143
|
-
cache.set((c) => ({ ...c, next: {} }));
|
|
144
|
-
weakScrolledElements = /* @__PURE__ */ new WeakSet();
|
|
145
|
-
}
|
|
146
|
-
}
|
|
147
|
-
);
|
|
148
|
-
return () => {
|
|
149
|
-
document.removeEventListener("scroll", onScroll);
|
|
150
|
-
unsubOnBeforeLoad();
|
|
151
|
-
unsubOnBeforeRouteMount();
|
|
152
|
-
};
|
|
153
|
-
}, [options == null ? void 0 : options.getKey, options == null ? void 0 : options.scrollBehavior, router]);
|
|
154
|
-
}
|
|
155
|
-
function ScrollRestoration(props) {
|
|
156
|
-
useScrollRestoration(props);
|
|
157
|
-
return null;
|
|
99
|
+
})();
|
|
100
|
+
ignoreScroll = false;
|
|
158
101
|
}
|
|
159
|
-
function
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
if (
|
|
165
|
-
|
|
166
|
-
}
|
|
167
|
-
|
|
168
|
-
|
|
102
|
+
function setupScrollRestoration(router, force) {
|
|
103
|
+
const shouldScrollRestoration = force ?? router.options.scrollRestoration ?? false;
|
|
104
|
+
if (shouldScrollRestoration) {
|
|
105
|
+
router.isScrollRestoring = true;
|
|
106
|
+
}
|
|
107
|
+
if (typeof document === "undefined" || router.isScrollRestorationSetup) {
|
|
108
|
+
return;
|
|
109
|
+
}
|
|
110
|
+
router.isScrollRestorationSetup = true;
|
|
111
|
+
ignoreScroll = false;
|
|
112
|
+
const getKey = router.options.getScrollRestorationKey || defaultGetScrollRestorationKey;
|
|
113
|
+
window.history.scrollRestoration = "manual";
|
|
114
|
+
const onScroll = (event) => {
|
|
115
|
+
if (ignoreScroll || !router.isScrollRestoring) {
|
|
169
116
|
return;
|
|
170
117
|
}
|
|
171
|
-
elementSelector =
|
|
118
|
+
let elementSelector = "";
|
|
119
|
+
if (event.target === document || event.target === window) {
|
|
120
|
+
elementSelector = "window";
|
|
121
|
+
} else {
|
|
122
|
+
const attrId = event.target.getAttribute(
|
|
123
|
+
"data-scroll-restoration-id"
|
|
124
|
+
);
|
|
125
|
+
if (attrId) {
|
|
126
|
+
elementSelector = `[data-scroll-restoration-id="${attrId}"]`;
|
|
127
|
+
} else {
|
|
128
|
+
elementSelector = getCssSelector(event.target);
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
const restoreKey = getKey(router.state.location);
|
|
132
|
+
scrollRestorationCache.set((state) => {
|
|
133
|
+
const keyEntry = state[restoreKey] = state[restoreKey] || {};
|
|
134
|
+
const elementEntry = keyEntry[elementSelector] = keyEntry[elementSelector] || {};
|
|
135
|
+
if (elementSelector === "window") {
|
|
136
|
+
elementEntry.scrollX = window.scrollX || 0;
|
|
137
|
+
elementEntry.scrollY = window.scrollY || 0;
|
|
138
|
+
} else if (elementSelector) {
|
|
139
|
+
const element = document.querySelector(elementSelector);
|
|
140
|
+
if (element) {
|
|
141
|
+
elementEntry.scrollX = element.scrollLeft || 0;
|
|
142
|
+
elementEntry.scrollY = element.scrollTop || 0;
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
return state;
|
|
146
|
+
});
|
|
147
|
+
};
|
|
148
|
+
if (typeof document !== "undefined") {
|
|
149
|
+
document.addEventListener("scroll", throttle(onScroll, 100), true);
|
|
172
150
|
}
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
151
|
+
router.subscribe("onRendered", (event) => {
|
|
152
|
+
const cacheKey = getKey(event.toLocation);
|
|
153
|
+
if (!router.resetNextScroll) {
|
|
154
|
+
router.resetNextScroll = true;
|
|
155
|
+
return;
|
|
156
|
+
}
|
|
157
|
+
restoreScroll(
|
|
158
|
+
storageKey,
|
|
159
|
+
cacheKey,
|
|
160
|
+
router.options.scrollRestorationBehavior,
|
|
161
|
+
router.isScrollRestoring
|
|
183
162
|
);
|
|
184
|
-
|
|
163
|
+
if (router.isScrollRestoring) {
|
|
164
|
+
scrollRestorationCache.set((state) => {
|
|
165
|
+
state[cacheKey] = state[cacheKey] || {};
|
|
166
|
+
return state;
|
|
167
|
+
});
|
|
168
|
+
}
|
|
169
|
+
});
|
|
170
|
+
}
|
|
171
|
+
function ScrollRestoration() {
|
|
172
|
+
const router = useRouter.useRouter();
|
|
173
|
+
const getKey = router.options.getScrollRestorationKey || defaultGetScrollRestorationKey;
|
|
174
|
+
const userKey = getKey(router.latestLocation);
|
|
175
|
+
const resolvedKey = userKey !== defaultGetScrollRestorationKey(router.latestLocation) ? userKey : null;
|
|
176
|
+
if (!router.isScrollRestoring || !router.isServer) {
|
|
177
|
+
return null;
|
|
185
178
|
}
|
|
186
|
-
return
|
|
179
|
+
return /* @__PURE__ */ jsxRuntime.jsx(
|
|
180
|
+
ScriptOnce.ScriptOnce,
|
|
181
|
+
{
|
|
182
|
+
children: `(${restoreScroll.toString()})(${JSON.stringify(storageKey)},${JSON.stringify(resolvedKey)}, undefined, true)`,
|
|
183
|
+
log: false
|
|
184
|
+
}
|
|
185
|
+
);
|
|
187
186
|
}
|
|
188
187
|
exports.ScrollRestoration = ScrollRestoration;
|
|
189
|
-
exports.
|
|
190
|
-
exports.
|
|
188
|
+
exports.defaultGetScrollRestorationKey = defaultGetScrollRestorationKey;
|
|
189
|
+
exports.getCssSelector = getCssSelector;
|
|
190
|
+
exports.restoreScroll = restoreScroll;
|
|
191
|
+
exports.scrollRestorationCache = scrollRestorationCache;
|
|
192
|
+
exports.setupScrollRestoration = setupScrollRestoration;
|
|
193
|
+
exports.storageKey = storageKey;
|
|
191
194
|
//# sourceMappingURL=scroll-restoration.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"scroll-restoration.cjs","sources":["../../src/scroll-restoration.tsx"],"sourcesContent":["import * as React from 'react'\nimport { functionalUpdate } from '@tanstack/router-core'\nimport { useRouter } from './useRouter'\nimport type { NonNullableUpdater, ParsedLocation } from '@tanstack/router-core'\n\nconst useLayoutEffect =\n typeof window !== 'undefined' ? React.useLayoutEffect : React.useEffect\n\nconst windowKey = 'window'\nconst delimiter = '___'\n\nlet weakScrolledElements = new WeakSet<any>()\n\ntype CacheValue = Record<string, { scrollX: number; scrollY: number }>\ntype CacheState = {\n cached: CacheValue\n next: CacheValue\n}\n\ntype Cache = {\n state: CacheState\n set: (updater: NonNullableUpdater<CacheState>) => void\n}\n\nconst sessionsStorage = typeof window !== 'undefined' && window.sessionStorage\n\nconst cache: Cache = sessionsStorage\n ? (() => {\n const storageKey = 'tsr-scroll-restoration-v2'\n\n const state: CacheState = JSON.parse(\n window.sessionStorage.getItem(storageKey) || 'null',\n ) || { cached: {}, next: {} }\n\n return {\n state,\n set: (updater) => {\n cache.state = functionalUpdate(updater, cache.state)\n window.sessionStorage.setItem(storageKey, JSON.stringify(cache.state))\n },\n }\n })()\n : (undefined as any)\n\nexport type ScrollRestorationOptions = {\n getKey?: (location: ParsedLocation) => string\n scrollBehavior?: ScrollToOptions['behavior']\n}\n\n/**\n * The default `getKey` function for `useScrollRestoration`.\n * It returns the `key` from the location state or the `href` of the location.\n *\n * The `location.href` is used as a fallback to support the use case where the location state is not available like the initial render.\n */\nconst defaultGetKey = (location: ParsedLocation) => {\n return location.state.key! || location.href\n}\n\nexport function useScrollRestoration(options?: ScrollRestorationOptions) {\n const router = useRouter()\n\n useLayoutEffect(() => {\n const getKey = options?.getKey || defaultGetKey\n\n const { history } = window\n history.scrollRestoration = 'manual'\n\n const onScroll = (event: Event) => {\n if (weakScrolledElements.has(event.target)) return\n weakScrolledElements.add(event.target)\n\n let elementSelector = ''\n\n if (event.target === document || event.target === window) {\n elementSelector = windowKey\n } else {\n const attrId = (event.target as Element).getAttribute(\n 'data-scroll-restoration-id',\n )\n\n if (attrId) {\n elementSelector = `[data-scroll-restoration-id=\"${attrId}\"]`\n } else {\n elementSelector = getCssSelector(event.target)\n }\n }\n\n if (!cache.state.next[elementSelector]) {\n cache.set((c) => ({\n ...c,\n next: {\n ...c.next,\n [elementSelector]: {\n scrollX: NaN,\n scrollY: NaN,\n },\n },\n }))\n }\n }\n\n if (typeof document !== 'undefined') {\n document.addEventListener('scroll', onScroll, true)\n }\n\n const unsubOnBeforeLoad = router.subscribe('onBeforeLoad', (event) => {\n if (event.hrefChanged) {\n const restoreKey = getKey(event.fromLocation)\n for (const elementSelector in cache.state.next) {\n const entry = cache.state.next[elementSelector]!\n if (elementSelector === windowKey) {\n entry.scrollX = window.scrollX || 0\n entry.scrollY = window.scrollY || 0\n } else if (elementSelector) {\n const element = document.querySelector(elementSelector)\n entry.scrollX = element?.scrollLeft || 0\n entry.scrollY = element?.scrollTop || 0\n }\n\n cache.set((c) => {\n const next = { ...c.next }\n delete next[elementSelector]\n\n return {\n ...c,\n next,\n cached: {\n ...c.cached,\n [[restoreKey, elementSelector].join(delimiter)]: entry,\n },\n }\n })\n }\n }\n })\n\n const unsubOnBeforeRouteMount = router.subscribe(\n 'onBeforeRouteMount',\n (event) => {\n if (event.hrefChanged) {\n if (!router.resetNextScroll) {\n return\n }\n\n router.resetNextScroll = true\n\n const restoreKey = getKey(event.toLocation)\n let windowRestored = false\n\n for (const cacheKey in cache.state.cached) {\n const entry = cache.state.cached[cacheKey]!\n const [key, elementSelector] = cacheKey.split(delimiter)\n if (key === restoreKey) {\n if (elementSelector === windowKey) {\n windowRestored = true\n window.scrollTo({\n top: entry.scrollY,\n left: entry.scrollX,\n behavior: options?.scrollBehavior,\n })\n } else if (elementSelector) {\n const element = document.querySelector(elementSelector)\n if (element) {\n element.scrollLeft = entry.scrollX\n element.scrollTop = entry.scrollY\n }\n }\n }\n }\n\n if (!windowRestored) {\n window.scrollTo(0, 0)\n }\n\n cache.set((c) => ({ ...c, next: {} }))\n weakScrolledElements = new WeakSet<any>()\n }\n },\n )\n\n return () => {\n document.removeEventListener('scroll', onScroll)\n unsubOnBeforeLoad()\n unsubOnBeforeRouteMount()\n }\n }, [options?.getKey, options?.scrollBehavior, router])\n}\n\nexport function ScrollRestoration(props: ScrollRestorationOptions) {\n useScrollRestoration(props)\n return null\n}\n\nexport function useElementScrollRestoration(\n options: (\n | {\n id: string\n getElement?: () => Element | undefined | null\n }\n | {\n id?: string\n getElement: () => Element | undefined | null\n }\n ) & {\n getKey?: (location: ParsedLocation) => string\n },\n) {\n const router = useRouter()\n const getKey = options.getKey || defaultGetKey\n\n let elementSelector = ''\n\n if (options.id) {\n elementSelector = `[data-scroll-restoration-id=\"${options.id}\"]`\n } else {\n const element = options.getElement?.()\n if (!element) {\n return\n }\n elementSelector = getCssSelector(element)\n }\n\n const restoreKey = getKey(router.latestLocation)\n const cacheKey = [restoreKey, elementSelector].join(delimiter)\n return cache.state.cached[cacheKey]\n}\n\nfunction getCssSelector(el: any): string {\n const path = []\n let parent\n while ((parent = el.parentNode)) {\n path.unshift(\n `${el.tagName}:nth-child(${\n ([].indexOf as any).call(parent.children, el) + 1\n })`,\n )\n el = parent\n }\n return `${path.join(' > ')}`.toLowerCase()\n}\n"],"names":["React","functionalUpdate","useRouter"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAKA,MAAM,kBACJ,OAAO,WAAW,cAAcA,iBAAM,kBAAkBA,iBAAM;AAEhE,MAAM,YAAY;AAClB,MAAM,YAAY;AAElB,IAAI,2CAA2B,QAAa;AAa5C,MAAM,kBAAkB,OAAO,WAAW,eAAe,OAAO;AAEhE,MAAM,QAAe,mBAChB,MAAM;AACL,QAAM,aAAa;AAEnB,QAAM,QAAoB,KAAK;AAAA,IAC7B,OAAO,eAAe,QAAQ,UAAU,KAAK;AAAA,OAC1C,EAAE,QAAQ,IAAI,MAAM,CAAA,EAAG;AAErB,SAAA;AAAA,IACL;AAAA,IACA,KAAK,CAAC,YAAY;AAChB,YAAM,QAAQC,WAAAA,iBAAiB,SAAS,MAAM,KAAK;AACnD,aAAO,eAAe,QAAQ,YAAY,KAAK,UAAU,MAAM,KAAK,CAAC;AAAA,IAAA;AAAA,EAEzE;AACF,GAAA,IACC;AAaL,MAAM,gBAAgB,CAAC,aAA6B;AAC3C,SAAA,SAAS,MAAM,OAAQ,SAAS;AACzC;AAEO,SAAS,qBAAqB,SAAoC;AACvE,QAAM,SAASC,UAAAA,UAAU;AAEzB,kBAAgB,MAAM;AACd,UAAA,UAAS,mCAAS,WAAU;AAE5B,UAAA,EAAE,YAAY;AACpB,YAAQ,oBAAoB;AAEtB,UAAA,WAAW,CAAC,UAAiB;AACjC,UAAI,qBAAqB,IAAI,MAAM,MAAM,EAAG;AACvB,2BAAA,IAAI,MAAM,MAAM;AAErC,UAAI,kBAAkB;AAEtB,UAAI,MAAM,WAAW,YAAY,MAAM,WAAW,QAAQ;AACtC,0BAAA;AAAA,MAAA,OACb;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AAAA,UAAU;AACnB,QAAA,SAAS,QAAQ,UAAU;AAEjC,MAAI,kBAAkB;AAEtB,MAAI,QAAQ,IAAI;AACI,sBAAA,gCAAgC,QAAQ,EAAE;AAAA,EAAA,OACvD;AACC,UAAA,WAAU,aAAQ,eAAR;AAChB,QAAI,CAAC,SAAS;AACZ;AAAA,IAAA;AAEF,sBAAkB,eAAe,OAAO;AAAA,EAAA;AAGpC,QAAA,aAAa,OAAO,OAAO,cAAc;AAC/C,QAAM,WAAW,CAAC,YAAY,eAAe,EAAE,KAAK,SAAS;AACtD,SAAA,MAAM,MAAM,OAAO,QAAQ;AACpC;AAEA,SAAS,eAAe,IAAiB;AACvC,QAAM,OAAO,CAAC;AACV,MAAA;AACI,SAAA,SAAS,GAAG,YAAa;AAC1B,SAAA;AAAA,MACH,GAAG,GAAG,OAAO,cACV,CAAA,EAAG,QAAgB,KAAK,OAAO,UAAU,EAAE,IAAI,CAClD;AAAA,IACF;AACK,SAAA;AAAA,EAAA;AAEP,SAAO,GAAG,KAAK,KAAK,KAAK,CAAC,GAAG,YAAY;AAC3C;;;;"}
|
|
1
|
+
{"version":3,"file":"scroll-restoration.cjs","sources":["../../src/scroll-restoration.tsx"],"sourcesContent":["import { functionalUpdate } from '@tanstack/router-core'\nimport { useRouter } from './useRouter'\nimport { ScriptOnce } from './ScriptOnce'\nimport type { AnyRouter } from './router'\nimport type { NonNullableUpdater, ParsedLocation } from '@tanstack/router-core'\n\nexport type ScrollRestorationEntry = { scrollX: number; scrollY: number }\n\nexport type ScrollRestorationByElement = Record<string, ScrollRestorationEntry>\n\nexport type ScrollRestorationByKey = Record<string, ScrollRestorationByElement>\n\nexport type ScrollRestorationCache = {\n state: ScrollRestorationByKey\n set: (updater: NonNullableUpdater<ScrollRestorationByKey>) => void\n}\nexport type ScrollRestorationOptions = {\n getKey?: (location: ParsedLocation) => string\n scrollBehavior?: ScrollToOptions['behavior']\n}\n\nexport const storageKey = 'tsr-scroll-restoration-v1_3'\nconst sessionsStorage = typeof window !== 'undefined' && window.sessionStorage\nconst throttle = (fn: (...args: Array<any>) => void, wait: number) => {\n let timeout: any\n return (...args: Array<any>) => {\n if (!timeout) {\n timeout = setTimeout(() => {\n fn(...args)\n timeout = null\n }, wait)\n }\n }\n}\nexport const scrollRestorationCache: ScrollRestorationCache = sessionsStorage\n ? (() => {\n const state: ScrollRestorationByKey =\n JSON.parse(window.sessionStorage.getItem(storageKey) || 'null') || {}\n\n return {\n state,\n // This setter is simply to make sure that we set the sessionStorage right\n // after the state is updated. It doesn't necessarily need to be a functional\n // update.\n set: (updater) => (\n (scrollRestorationCache.state =\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n functionalUpdate(updater, scrollRestorationCache.state) ||\n scrollRestorationCache.state),\n window.sessionStorage.setItem(\n storageKey,\n JSON.stringify(scrollRestorationCache.state),\n )\n ),\n }\n })()\n : (undefined as any)\n/**\n * The default `getKey` function for `useScrollRestoration`.\n * It returns the `key` from the location state or the `href` of the location.\n *\n * The `location.href` is used as a fallback to support the use case where the location state is not available like the initial render.\n */\n\nexport const defaultGetScrollRestorationKey = (location: ParsedLocation) => {\n return location.state.key! || location.href\n}\n\nexport function getCssSelector(el: any): string {\n const path = []\n let parent\n while ((parent = el.parentNode)) {\n path.unshift(\n `${el.tagName}:nth-child(${([].indexOf as any).call(parent.children, el) + 1})`,\n )\n el = parent\n }\n return `${path.join(' > ')}`.toLowerCase()\n}\n\nlet ignoreScroll = false\n\n// NOTE: This function must remain pure and not use any outside variables\n// unless they are passed in as arguments. Why? Because we need to be able to\n// toString() it into a script tag to execute as early as possible in the browser\n// during SSR. Additionally, we also call it from within the router lifecycle\nexport function restoreScroll(\n storageKey: string,\n key?: string,\n behavior?: ScrollToOptions['behavior'],\n shouldScrollRestoration?: boolean,\n) {\n let byKey: ScrollRestorationByKey\n\n try {\n byKey = JSON.parse(sessionStorage.getItem(storageKey) || '{}')\n } catch (error: any) {\n console.error(error)\n return\n }\n\n const resolvedKey = key || window.history.state?.key\n const elementEntries = byKey[resolvedKey]\n\n //\n ignoreScroll = true\n\n //\n ;(() => {\n // If we have a cached entry for this location state,\n // we always need to prefer that over the hash scroll.\n if (shouldScrollRestoration && elementEntries) {\n for (const elementSelector in elementEntries) {\n const entry = elementEntries[elementSelector]!\n if (elementSelector === 'window') {\n console.log('windowRestored', entry)\n window.scrollTo({\n top: entry.scrollY,\n left: entry.scrollX,\n behavior,\n })\n } else if (elementSelector) {\n const element = document.querySelector(elementSelector)\n if (element) {\n element.scrollLeft = entry.scrollX\n element.scrollTop = entry.scrollY\n }\n }\n }\n\n return\n }\n\n // If we don't have a cached entry for the hash,\n // Which means we've never seen this location before,\n // we need to check if there is a hash in the URL.\n // If there is, we need to scroll it's ID into view.\n const hash = window.location.hash.split('#')[1]\n\n if (hash) {\n const hashScrollIntoViewOptions =\n (window.history.state || {}).__hashScrollIntoViewOptions ?? true\n\n if (hashScrollIntoViewOptions) {\n console.log('scrollIntoView')\n const el = document.getElementById(hash)\n if (el) {\n el.scrollIntoView(hashScrollIntoViewOptions)\n }\n }\n\n return\n }\n\n // If there is no cached entry for the hash and there is no hash in the URL,\n // we need to scroll to the top of the page.\n window.scrollTo({\n top: 0,\n left: 0,\n behavior,\n })\n })()\n\n //\n ignoreScroll = false\n}\n\nexport function setupScrollRestoration(router: AnyRouter, force?: boolean) {\n const shouldScrollRestoration =\n force ?? router.options.scrollRestoration ?? false\n\n if (shouldScrollRestoration) {\n router.isScrollRestoring = true\n }\n\n if (typeof document === 'undefined' || router.isScrollRestorationSetup) {\n return\n }\n\n router.isScrollRestorationSetup = true\n\n //\n ignoreScroll = false\n\n const getKey =\n router.options.getScrollRestorationKey || defaultGetScrollRestorationKey\n\n window.history.scrollRestoration = 'manual'\n\n // // Create a MutationObserver to monitor DOM changes\n // const mutationObserver = new MutationObserver(() => {\n // ;ignoreScroll = true\n // requestAnimationFrame(() => {\n // ;ignoreScroll = false\n\n // // Attempt to restore scroll position on each dom\n // // mutation until the user scrolls. We do this\n // // because dynamic content may come in at different\n // // ticks after the initial render and we want to\n // // keep up with that content as much as possible.\n // // As soon as the user scrolls, we no longer need\n // // to attempt router.\n // // console.log('mutation observer restoreScroll')\n // restoreScroll(\n // storageKey,\n // getKey(router.state.location),\n // router.options.scrollRestorationBehavior,\n // )\n // })\n // })\n\n // const observeDom = () => {\n // // Observe changes to the entire document\n // mutationObserver.observe(document, {\n // childList: true, // Detect added or removed child nodes\n // subtree: true, // Monitor all descendants\n // characterData: true, // Detect text content changes\n // })\n // }\n\n // const unobserveDom = () => {\n // mutationObserver.disconnect()\n // }\n\n // observeDom()\n\n const onScroll = (event: Event) => {\n // unobserveDom()\n\n if (ignoreScroll || !router.isScrollRestoring) {\n return\n }\n\n let elementSelector = ''\n\n if (event.target === document || event.target === window) {\n elementSelector = 'window'\n } else {\n const attrId = (event.target as Element).getAttribute(\n 'data-scroll-restoration-id',\n )\n\n if (attrId) {\n elementSelector = `[data-scroll-restoration-id=\"${attrId}\"]`\n } else {\n elementSelector = getCssSelector(event.target)\n }\n }\n\n const restoreKey = getKey(router.state.location)\n\n scrollRestorationCache.set((state) => {\n const keyEntry = (state[restoreKey] =\n state[restoreKey] || ({} as ScrollRestorationByElement))\n\n const elementEntry = (keyEntry[elementSelector] =\n keyEntry[elementSelector] || ({} as ScrollRestorationEntry))\n\n if (elementSelector === 'window') {\n elementEntry.scrollX = window.scrollX || 0\n elementEntry.scrollY = window.scrollY || 0\n } else if (elementSelector) {\n const element = document.querySelector(elementSelector)\n if (element) {\n elementEntry.scrollX = element.scrollLeft || 0\n elementEntry.scrollY = element.scrollTop || 0\n }\n }\n\n return state\n })\n }\n\n // Throttle the scroll event to avoid excessive updates\n if (typeof document !== 'undefined') {\n document.addEventListener('scroll', throttle(onScroll, 100), true)\n }\n\n router.subscribe('onRendered', (event) => {\n // unobserveDom()\n\n const cacheKey = getKey(event.toLocation)\n\n // If the user doesn't want to restore the scroll position,\n // we don't need to do anything.\n if (!router.resetNextScroll) {\n router.resetNextScroll = true\n return\n }\n\n restoreScroll(\n storageKey,\n cacheKey,\n router.options.scrollRestorationBehavior,\n router.isScrollRestoring,\n )\n\n if (router.isScrollRestoring) {\n // Mark the location as having been seen\n scrollRestorationCache.set((state) => {\n state[cacheKey] = state[cacheKey] || ({} as ScrollRestorationByElement)\n\n return state\n })\n }\n })\n}\n\nexport function ScrollRestoration() {\n const router = useRouter()\n const getKey =\n router.options.getScrollRestorationKey || defaultGetScrollRestorationKey\n const userKey = getKey(router.latestLocation)\n const resolvedKey =\n userKey !== defaultGetScrollRestorationKey(router.latestLocation)\n ? userKey\n : null\n\n if (!router.isScrollRestoring || !router.isServer) {\n return null\n }\n\n return (\n <ScriptOnce\n children={`(${restoreScroll.toString()})(${JSON.stringify(storageKey)},${JSON.stringify(resolvedKey)}, undefined, true)`}\n log={false}\n />\n )\n}\n"],"names":["functionalUpdate","storageKey","useRouter","jsx","ScriptOnce"],"mappings":";;;;;;AAqBO,MAAM,aAAa;AAC1B,MAAM,kBAAkB,OAAO,WAAW,eAAe,OAAO;AAChE,MAAM,WAAW,CAAC,IAAmC,SAAiB;AAChE,MAAA;AACJ,SAAO,IAAI,SAAqB;AAC9B,QAAI,CAAC,SAAS;AACZ,gBAAU,WAAW,MAAM;AACzB,WAAG,GAAG,IAAI;AACA,kBAAA;AAAA,SACT,IAAI;AAAA,IAAA;AAAA,EAEX;AACF;AACa,MAAA,yBAAiD,mBACzD,MAAM;AACC,QAAA,QACJ,KAAK,MAAM,OAAO,eAAe,QAAQ,UAAU,KAAK,MAAM,KAAK,CAAC;AAE/D,SAAA;AAAA,IACL;AAAA;AAAA;AAAA;AAAA,IAIA,KAAK,CAAC,aACH,uBAAuB;AAAA,IAEtBA,4BAAiB,SAAS,uBAAuB,KAAK,KACtD,uBAAuB,OACzB,OAAO,eAAe;AAAA,MACpB;AAAA,MACA,KAAK,UAAU,uBAAuB,KAAK;AAAA,IAC7C;AAAA,EAEJ;AACF,OACC;AAQQ,MAAA,iCAAiC,CAA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
|
|
1
|
+
import { AnyRouter } from './router.cjs';
|
|
2
|
+
import { NonNullableUpdater, ParsedLocation } from '@tanstack/router-core';
|
|
3
|
+
export type ScrollRestorationEntry = {
|
|
4
|
+
scrollX: number;
|
|
5
|
+
scrollY: number;
|
|
6
|
+
};
|
|
7
|
+
export type ScrollRestorationByElement = Record<string, ScrollRestorationEntry>;
|
|
8
|
+
export type ScrollRestorationByKey = Record<string, ScrollRestorationByElement>;
|
|
9
|
+
export type ScrollRestorationCache = {
|
|
10
|
+
state: ScrollRestorationByKey;
|
|
11
|
+
set: (updater: NonNullableUpdater<ScrollRestorationByKey>) => void;
|
|
12
|
+
};
|
|
2
13
|
export type ScrollRestorationOptions = {
|
|
3
14
|
getKey?: (location: ParsedLocation) => string;
|
|
4
15
|
scrollBehavior?: ScrollToOptions['behavior'];
|
|
5
16
|
};
|
|
6
|
-
export declare
|
|
7
|
-
export declare
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
} | undefined;
|
|
17
|
+
export declare const storageKey = "tsr-scroll-restoration-v1_3";
|
|
18
|
+
export declare const scrollRestorationCache: ScrollRestorationCache;
|
|
19
|
+
/**
|
|
20
|
+
* The default `getKey` function for `useScrollRestoration`.
|
|
21
|
+
* It returns the `key` from the location state or the `href` of the location.
|
|
22
|
+
*
|
|
23
|
+
* The `location.href` is used as a fallback to support the use case where the location state is not available like the initial render.
|
|
24
|
+
*/
|
|
25
|
+
export declare const defaultGetScrollRestorationKey: (location: ParsedLocation) => string;
|
|
26
|
+
export declare function getCssSelector(el: any): string;
|
|
27
|
+
export declare function restoreScroll(storageKey: string, key?: string, behavior?: ScrollToOptions['behavior'], shouldScrollRestoration?: boolean): void;
|
|
28
|
+
export declare function setupScrollRestoration(router: AnyRouter, force?: boolean): void;
|
|
29
|
+
export declare function ScrollRestoration(): import("react/jsx-runtime").JSX.Element | null;
|