@tanstack/react-router 1.98.0 → 1.98.3
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 +60 -22
- 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/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 +1 -2
- package/dist/cjs/router.cjs +14 -12
- package/dist/cjs/router.cjs.map +1 -1
- package/dist/cjs/router.d.cts +26 -26
- package/dist/cjs/scroll-restoration.cjs +166 -165
- package/dist/cjs/scroll-restoration.cjs.map +1 -1
- package/dist/cjs/scroll-restoration.d.cts +25 -15
- package/dist/esm/Match.js +62 -24
- package/dist/esm/Match.js.map +1 -1
- 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 +1 -2
- package/dist/esm/index.js +1 -2
- package/dist/esm/router.d.ts +26 -26
- package/dist/esm/router.js +15 -13
- package/dist/esm/router.js.map +1 -1
- package/dist/esm/scroll-restoration.d.ts +25 -15
- package/dist/esm/scroll-restoration.js +166 -148
- package/dist/esm/scroll-restoration.js.map +1 -1
- package/package.json +3 -3
- package/src/Match.tsx +79 -48
- package/src/Matches.tsx +1 -1
- package/src/ScriptOnce.tsx +1 -1
- package/src/ScrollRestoration.tsx +65 -0
- package/src/Transitioner.tsx +4 -40
- package/src/index.tsx +1 -3
- package/src/router.ts +43 -38
- package/src/scroll-restoration.tsx +268 -182
|
@@ -1,19 +1,29 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { AnyRouter } from './router.js';
|
|
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;
|
|
@@ -1,174 +1,192 @@
|
|
|
1
|
-
import
|
|
1
|
+
import { jsx } from "react/jsx-runtime";
|
|
2
2
|
import { functionalUpdate } from "@tanstack/router-core";
|
|
3
3
|
import { useRouter } from "./useRouter.js";
|
|
4
|
-
|
|
5
|
-
const
|
|
6
|
-
const delimiter = "___";
|
|
7
|
-
let weakScrolledElements = /* @__PURE__ */ new WeakSet();
|
|
4
|
+
import { ScriptOnce } from "./ScriptOnce.js";
|
|
5
|
+
const storageKey = "tsr-scroll-restoration-v1_3";
|
|
8
6
|
const sessionsStorage = typeof window !== "undefined" && window.sessionStorage;
|
|
9
|
-
const
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
7
|
+
const throttle = (fn, wait) => {
|
|
8
|
+
let timeout;
|
|
9
|
+
return (...args) => {
|
|
10
|
+
if (!timeout) {
|
|
11
|
+
timeout = setTimeout(() => {
|
|
12
|
+
fn(...args);
|
|
13
|
+
timeout = null;
|
|
14
|
+
}, wait);
|
|
15
|
+
}
|
|
16
|
+
};
|
|
17
|
+
};
|
|
18
|
+
const scrollRestorationCache = sessionsStorage ? (() => {
|
|
19
|
+
const state = JSON.parse(window.sessionStorage.getItem(storageKey) || "null") || {};
|
|
14
20
|
return {
|
|
15
21
|
state,
|
|
16
|
-
set
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
22
|
+
// This setter is simply to make sure that we set the sessionStorage right
|
|
23
|
+
// after the state is updated. It doesn't necessarily need to be a functional
|
|
24
|
+
// update.
|
|
25
|
+
set: (updater) => (scrollRestorationCache.state = // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
|
|
26
|
+
functionalUpdate(updater, scrollRestorationCache.state) || scrollRestorationCache.state, window.sessionStorage.setItem(
|
|
27
|
+
storageKey,
|
|
28
|
+
JSON.stringify(scrollRestorationCache.state)
|
|
29
|
+
))
|
|
20
30
|
};
|
|
21
31
|
})() : void 0;
|
|
22
|
-
const
|
|
32
|
+
const defaultGetScrollRestorationKey = (location) => {
|
|
23
33
|
return location.state.key || location.href;
|
|
24
34
|
};
|
|
25
|
-
function
|
|
26
|
-
const
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
35
|
+
function getCssSelector(el) {
|
|
36
|
+
const path = [];
|
|
37
|
+
let parent;
|
|
38
|
+
while (parent = el.parentNode) {
|
|
39
|
+
path.unshift(
|
|
40
|
+
`${el.tagName}:nth-child(${[].indexOf.call(parent.children, el) + 1})`
|
|
41
|
+
);
|
|
42
|
+
el = parent;
|
|
43
|
+
}
|
|
44
|
+
return `${path.join(" > ")}`.toLowerCase();
|
|
45
|
+
}
|
|
46
|
+
let ignoreScroll = false;
|
|
47
|
+
function restoreScroll(storageKey2, key, behavior, shouldScrollRestoration) {
|
|
48
|
+
var _a;
|
|
49
|
+
let byKey;
|
|
50
|
+
try {
|
|
51
|
+
byKey = JSON.parse(sessionStorage.getItem(storageKey2) || "{}");
|
|
52
|
+
} catch (error) {
|
|
53
|
+
console.error(error);
|
|
54
|
+
return;
|
|
55
|
+
}
|
|
56
|
+
const resolvedKey = key || ((_a = window.history.state) == null ? void 0 : _a.key);
|
|
57
|
+
const elementEntries = byKey[resolvedKey];
|
|
58
|
+
ignoreScroll = true;
|
|
59
|
+
(() => {
|
|
60
|
+
if (shouldScrollRestoration && elementEntries) {
|
|
61
|
+
for (const elementSelector in elementEntries) {
|
|
62
|
+
const entry = elementEntries[elementSelector];
|
|
63
|
+
if (elementSelector === "window") {
|
|
64
|
+
window.scrollTo({
|
|
65
|
+
top: entry.scrollY,
|
|
66
|
+
left: entry.scrollX,
|
|
67
|
+
behavior
|
|
68
|
+
});
|
|
69
|
+
} else if (elementSelector) {
|
|
70
|
+
const element = document.querySelector(elementSelector);
|
|
71
|
+
if (element) {
|
|
72
|
+
element.scrollLeft = entry.scrollX;
|
|
73
|
+
element.scrollTop = entry.scrollY;
|
|
56
74
|
}
|
|
57
|
-
}
|
|
75
|
+
}
|
|
58
76
|
}
|
|
59
|
-
|
|
60
|
-
if (typeof document !== "undefined") {
|
|
61
|
-
document.addEventListener("scroll", onScroll, true);
|
|
77
|
+
return;
|
|
62
78
|
}
|
|
63
|
-
const
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
entry.scrollY = window.scrollY || 0;
|
|
71
|
-
} else if (elementSelector) {
|
|
72
|
-
const element = document.querySelector(elementSelector);
|
|
73
|
-
entry.scrollX = (element == null ? void 0 : element.scrollLeft) || 0;
|
|
74
|
-
entry.scrollY = (element == null ? void 0 : element.scrollTop) || 0;
|
|
75
|
-
}
|
|
76
|
-
cache.set((c) => {
|
|
77
|
-
const next = { ...c.next };
|
|
78
|
-
delete next[elementSelector];
|
|
79
|
-
return {
|
|
80
|
-
...c,
|
|
81
|
-
next,
|
|
82
|
-
cached: {
|
|
83
|
-
...c.cached,
|
|
84
|
-
[[restoreKey, elementSelector].join(delimiter)]: entry
|
|
85
|
-
}
|
|
86
|
-
};
|
|
87
|
-
});
|
|
79
|
+
const hash = window.location.hash.split("#")[1];
|
|
80
|
+
if (hash) {
|
|
81
|
+
const hashScrollIntoViewOptions = (window.history.state || {}).__hashScrollIntoViewOptions ?? true;
|
|
82
|
+
if (hashScrollIntoViewOptions) {
|
|
83
|
+
const el = document.getElementById(hash);
|
|
84
|
+
if (el) {
|
|
85
|
+
el.scrollIntoView(hashScrollIntoViewOptions);
|
|
88
86
|
}
|
|
89
87
|
}
|
|
88
|
+
return;
|
|
89
|
+
}
|
|
90
|
+
window.scrollTo({
|
|
91
|
+
top: 0,
|
|
92
|
+
left: 0,
|
|
93
|
+
behavior
|
|
90
94
|
});
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
(event) => {
|
|
94
|
-
if (event.hrefChanged) {
|
|
95
|
-
if (!router.resetNextScroll) {
|
|
96
|
-
return;
|
|
97
|
-
}
|
|
98
|
-
router.resetNextScroll = true;
|
|
99
|
-
const restoreKey = getKey(event.toLocation);
|
|
100
|
-
let windowRestored = false;
|
|
101
|
-
for (const cacheKey in cache.state.cached) {
|
|
102
|
-
const entry = cache.state.cached[cacheKey];
|
|
103
|
-
const [key, elementSelector] = cacheKey.split(delimiter);
|
|
104
|
-
if (key === restoreKey) {
|
|
105
|
-
if (elementSelector === windowKey) {
|
|
106
|
-
windowRestored = true;
|
|
107
|
-
window.scrollTo({
|
|
108
|
-
top: entry.scrollY,
|
|
109
|
-
left: entry.scrollX,
|
|
110
|
-
behavior: options == null ? void 0 : options.scrollBehavior
|
|
111
|
-
});
|
|
112
|
-
} else if (elementSelector) {
|
|
113
|
-
const element = document.querySelector(elementSelector);
|
|
114
|
-
if (element) {
|
|
115
|
-
element.scrollLeft = entry.scrollX;
|
|
116
|
-
element.scrollTop = entry.scrollY;
|
|
117
|
-
}
|
|
118
|
-
}
|
|
119
|
-
}
|
|
120
|
-
}
|
|
121
|
-
if (!windowRestored) {
|
|
122
|
-
window.scrollTo(0, 0);
|
|
123
|
-
}
|
|
124
|
-
cache.set((c) => ({ ...c, next: {} }));
|
|
125
|
-
weakScrolledElements = /* @__PURE__ */ new WeakSet();
|
|
126
|
-
}
|
|
127
|
-
}
|
|
128
|
-
);
|
|
129
|
-
return () => {
|
|
130
|
-
document.removeEventListener("scroll", onScroll);
|
|
131
|
-
unsubOnBeforeLoad();
|
|
132
|
-
unsubOnBeforeRouteMount();
|
|
133
|
-
};
|
|
134
|
-
}, [options == null ? void 0 : options.getKey, options == null ? void 0 : options.scrollBehavior, router]);
|
|
135
|
-
}
|
|
136
|
-
function ScrollRestoration(props) {
|
|
137
|
-
useScrollRestoration(props);
|
|
138
|
-
return null;
|
|
95
|
+
})();
|
|
96
|
+
ignoreScroll = false;
|
|
139
97
|
}
|
|
140
|
-
function
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
if (
|
|
146
|
-
|
|
147
|
-
}
|
|
148
|
-
|
|
149
|
-
|
|
98
|
+
function setupScrollRestoration(router, force) {
|
|
99
|
+
const shouldScrollRestoration = force ?? router.options.scrollRestoration ?? false;
|
|
100
|
+
if (shouldScrollRestoration) {
|
|
101
|
+
router.isScrollRestoring = true;
|
|
102
|
+
}
|
|
103
|
+
if (typeof document === "undefined" || router.isScrollRestorationSetup) {
|
|
104
|
+
return;
|
|
105
|
+
}
|
|
106
|
+
router.isScrollRestorationSetup = true;
|
|
107
|
+
ignoreScroll = false;
|
|
108
|
+
const getKey = router.options.getScrollRestorationKey || defaultGetScrollRestorationKey;
|
|
109
|
+
window.history.scrollRestoration = "manual";
|
|
110
|
+
const onScroll = (event) => {
|
|
111
|
+
if (ignoreScroll || !router.isScrollRestoring) {
|
|
150
112
|
return;
|
|
151
113
|
}
|
|
152
|
-
elementSelector =
|
|
114
|
+
let elementSelector = "";
|
|
115
|
+
if (event.target === document || event.target === window) {
|
|
116
|
+
elementSelector = "window";
|
|
117
|
+
} else {
|
|
118
|
+
const attrId = event.target.getAttribute(
|
|
119
|
+
"data-scroll-restoration-id"
|
|
120
|
+
);
|
|
121
|
+
if (attrId) {
|
|
122
|
+
elementSelector = `[data-scroll-restoration-id="${attrId}"]`;
|
|
123
|
+
} else {
|
|
124
|
+
elementSelector = getCssSelector(event.target);
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
const restoreKey = getKey(router.state.location);
|
|
128
|
+
scrollRestorationCache.set((state) => {
|
|
129
|
+
const keyEntry = state[restoreKey] = state[restoreKey] || {};
|
|
130
|
+
const elementEntry = keyEntry[elementSelector] = keyEntry[elementSelector] || {};
|
|
131
|
+
if (elementSelector === "window") {
|
|
132
|
+
elementEntry.scrollX = window.scrollX || 0;
|
|
133
|
+
elementEntry.scrollY = window.scrollY || 0;
|
|
134
|
+
} else if (elementSelector) {
|
|
135
|
+
const element = document.querySelector(elementSelector);
|
|
136
|
+
if (element) {
|
|
137
|
+
elementEntry.scrollX = element.scrollLeft || 0;
|
|
138
|
+
elementEntry.scrollY = element.scrollTop || 0;
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
return state;
|
|
142
|
+
});
|
|
143
|
+
};
|
|
144
|
+
if (typeof document !== "undefined") {
|
|
145
|
+
document.addEventListener("scroll", throttle(onScroll, 100), true);
|
|
153
146
|
}
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
147
|
+
router.subscribe("onRendered", (event) => {
|
|
148
|
+
const cacheKey = getKey(event.toLocation);
|
|
149
|
+
if (!router.resetNextScroll) {
|
|
150
|
+
router.resetNextScroll = true;
|
|
151
|
+
return;
|
|
152
|
+
}
|
|
153
|
+
restoreScroll(
|
|
154
|
+
storageKey,
|
|
155
|
+
cacheKey,
|
|
156
|
+
router.options.scrollRestorationBehavior,
|
|
157
|
+
router.isScrollRestoring
|
|
164
158
|
);
|
|
165
|
-
|
|
159
|
+
if (router.isScrollRestoring) {
|
|
160
|
+
scrollRestorationCache.set((state) => {
|
|
161
|
+
state[cacheKey] = state[cacheKey] || {};
|
|
162
|
+
return state;
|
|
163
|
+
});
|
|
164
|
+
}
|
|
165
|
+
});
|
|
166
|
+
}
|
|
167
|
+
function ScrollRestoration() {
|
|
168
|
+
const router = useRouter();
|
|
169
|
+
const getKey = router.options.getScrollRestorationKey || defaultGetScrollRestorationKey;
|
|
170
|
+
const userKey = getKey(router.latestLocation);
|
|
171
|
+
const resolvedKey = userKey !== defaultGetScrollRestorationKey(router.latestLocation) ? userKey : null;
|
|
172
|
+
if (!router.isScrollRestoring || !router.isServer) {
|
|
173
|
+
return null;
|
|
166
174
|
}
|
|
167
|
-
return
|
|
175
|
+
return /* @__PURE__ */ jsx(
|
|
176
|
+
ScriptOnce,
|
|
177
|
+
{
|
|
178
|
+
children: `(${restoreScroll.toString()})(${JSON.stringify(storageKey)},${JSON.stringify(resolvedKey)}, undefined, true)`,
|
|
179
|
+
log: false
|
|
180
|
+
}
|
|
181
|
+
);
|
|
168
182
|
}
|
|
169
183
|
export {
|
|
170
184
|
ScrollRestoration,
|
|
171
|
-
|
|
172
|
-
|
|
185
|
+
defaultGetScrollRestorationKey,
|
|
186
|
+
getCssSelector,
|
|
187
|
+
restoreScroll,
|
|
188
|
+
scrollRestorationCache,
|
|
189
|
+
setupScrollRestoration,
|
|
190
|
+
storageKey
|
|
173
191
|
};
|
|
174
192
|
//# sourceMappingURL=scroll-restoration.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"scroll-restoration.js","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":[],"mappings":";;;AAKA,MAAM,kBACJ,OAAO,WAAW,cAAc,MAAM,kBAAkB,MAAM;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,QAAQ,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,SAAS,UAAU;AAEzB,kBAAgB,MAAM;AACd,UAAA,UAAS,mCAAS,WAAU;AAE5B,UAAA,EAAE,YAAY;AACpB,YAAQ,oBAAoB;A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AA;AACM,8BAAA;AAAA,IAC1B;AAAA,EAAA,GACC,CAAC,mCAAS,QAAQ,mCAAS,gBAAgB,MAAM,CAAC;AACvD;AAEO,SAAS,kBAAkB,OAAiC;AACjE,uBAAqB,KAAK;AACnB,SAAA;AACT;AAEO,SAAS,4BACd,SAYA;;AACA,QAAM,SAAS,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.js","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 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 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":["storageKey"],"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,IAEtB,iBAAiB,SAAS,uBAAuB,KAAK,KACtD,uBAAuB,OAC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
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tanstack/react-router",
|
|
3
|
-
"version": "1.98.
|
|
3
|
+
"version": "1.98.3",
|
|
4
4
|
"description": "Modern and scalable routing for React applications",
|
|
5
5
|
"author": "Tanner Linsley",
|
|
6
6
|
"license": "MIT",
|
|
@@ -53,8 +53,8 @@
|
|
|
53
53
|
"jsesc": "^3.1.0",
|
|
54
54
|
"tiny-invariant": "^1.3.3",
|
|
55
55
|
"tiny-warning": "^1.0.3",
|
|
56
|
-
"@tanstack/history": "1.98.
|
|
57
|
-
"@tanstack/router-core": "^1.98.
|
|
56
|
+
"@tanstack/history": "1.98.1",
|
|
57
|
+
"@tanstack/router-core": "^1.98.1"
|
|
58
58
|
},
|
|
59
59
|
"devDependencies": {
|
|
60
60
|
"@testing-library/jest-dom": "^6.6.3",
|
package/src/Match.tsx
CHANGED
|
@@ -5,6 +5,7 @@ import invariant from 'tiny-invariant'
|
|
|
5
5
|
import warning from 'tiny-warning'
|
|
6
6
|
import {
|
|
7
7
|
createControlledPromise,
|
|
8
|
+
getLocationChangeInfo,
|
|
8
9
|
pick,
|
|
9
10
|
rootRouteId,
|
|
10
11
|
} from '@tanstack/router-core'
|
|
@@ -16,6 +17,8 @@ import { isRedirect } from './redirects'
|
|
|
16
17
|
import { matchContext } from './matchContext'
|
|
17
18
|
import { SafeFragment } from './SafeFragment'
|
|
18
19
|
import { renderRouteNotFound } from './renderRouteNotFound'
|
|
20
|
+
import { ScrollRestoration } from './scroll-restoration'
|
|
21
|
+
import type { ParsedLocation } from '@tanstack/router-core'
|
|
19
22
|
import type { AnyRoute } from './route'
|
|
20
23
|
|
|
21
24
|
export const Match = React.memo(function MatchImpl({
|
|
@@ -72,41 +75,88 @@ export const Match = React.memo(function MatchImpl({
|
|
|
72
75
|
select: (s) => s.loadedAt,
|
|
73
76
|
})
|
|
74
77
|
|
|
78
|
+
const parentRouteId = useRouterState({
|
|
79
|
+
select: (s) => {
|
|
80
|
+
const index = s.matches.findIndex((d) => d.id === matchId)
|
|
81
|
+
return s.matches[index - 1]?.routeId as string
|
|
82
|
+
},
|
|
83
|
+
})
|
|
84
|
+
|
|
75
85
|
return (
|
|
76
|
-
|
|
77
|
-
<
|
|
78
|
-
<
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
>
|
|
88
|
-
<ResolvedNotFoundBoundary
|
|
89
|
-
fallback={(error) => {
|
|
90
|
-
// If the current not found handler doesn't exist or it has a
|
|
91
|
-
// route ID which doesn't match the current route, rethrow the error
|
|
92
|
-
if (
|
|
93
|
-
!routeNotFoundComponent ||
|
|
94
|
-
(error.routeId && error.routeId !== routeId) ||
|
|
95
|
-
(!error.routeId && !route.isRoot)
|
|
96
|
-
)
|
|
97
|
-
throw error
|
|
98
|
-
|
|
99
|
-
return React.createElement(routeNotFoundComponent, error as any)
|
|
86
|
+
<>
|
|
87
|
+
<matchContext.Provider value={matchId}>
|
|
88
|
+
<ResolvedSuspenseBoundary fallback={pendingElement}>
|
|
89
|
+
<ResolvedCatchBoundary
|
|
90
|
+
getResetKey={() => resetKey}
|
|
91
|
+
errorComponent={routeErrorComponent || ErrorComponent}
|
|
92
|
+
onCatch={(error, errorInfo) => {
|
|
93
|
+
// Forward not found errors (we don't want to show the error component for these)
|
|
94
|
+
if (isNotFound(error)) throw error
|
|
95
|
+
warning(false, `Error in route match: ${matchId}`)
|
|
96
|
+
routeOnCatch?.(error, errorInfo)
|
|
100
97
|
}}
|
|
101
98
|
>
|
|
102
|
-
<
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
99
|
+
<ResolvedNotFoundBoundary
|
|
100
|
+
fallback={(error) => {
|
|
101
|
+
// If the current not found handler doesn't exist or it has a
|
|
102
|
+
// route ID which doesn't match the current route, rethrow the error
|
|
103
|
+
if (
|
|
104
|
+
!routeNotFoundComponent ||
|
|
105
|
+
(error.routeId && error.routeId !== routeId) ||
|
|
106
|
+
(!error.routeId && !route.isRoot)
|
|
107
|
+
)
|
|
108
|
+
throw error
|
|
109
|
+
|
|
110
|
+
return React.createElement(routeNotFoundComponent, error as any)
|
|
111
|
+
}}
|
|
112
|
+
>
|
|
113
|
+
<MatchInner matchId={matchId} />
|
|
114
|
+
</ResolvedNotFoundBoundary>
|
|
115
|
+
</ResolvedCatchBoundary>
|
|
116
|
+
</ResolvedSuspenseBoundary>
|
|
117
|
+
</matchContext.Provider>
|
|
118
|
+
{parentRouteId === rootRouteId ? (
|
|
119
|
+
<>
|
|
120
|
+
<OnRendered />
|
|
121
|
+
<ScrollRestoration />
|
|
122
|
+
</>
|
|
123
|
+
) : null}
|
|
124
|
+
</>
|
|
107
125
|
)
|
|
108
126
|
})
|
|
109
127
|
|
|
128
|
+
// On Rendered can't happen above the root layout because it actually
|
|
129
|
+
// renders a dummy dom element to track the rendered state of the app.
|
|
130
|
+
// We render a script tag with a key that changes based on the current
|
|
131
|
+
// location state.key. Also, because it's below the root layout, it
|
|
132
|
+
// allows us to fire onRendered events even after a hydration mismatch
|
|
133
|
+
// error that occurred above the root layout (like bad head/link tags,
|
|
134
|
+
// which is common).
|
|
135
|
+
function OnRendered() {
|
|
136
|
+
const router = useRouter()
|
|
137
|
+
|
|
138
|
+
const prevLocationRef = React.useRef<undefined | ParsedLocation<{}>>(
|
|
139
|
+
undefined,
|
|
140
|
+
)
|
|
141
|
+
|
|
142
|
+
return (
|
|
143
|
+
<script
|
|
144
|
+
key={router.state.resolvedLocation?.state.key}
|
|
145
|
+
suppressHydrationWarning
|
|
146
|
+
ref={(el) => {
|
|
147
|
+
if (el) {
|
|
148
|
+
router.emit({
|
|
149
|
+
type: 'onRendered',
|
|
150
|
+
...getLocationChangeInfo(router.state),
|
|
151
|
+
})
|
|
152
|
+
} else {
|
|
153
|
+
prevLocationRef.current = router.state.resolvedLocation
|
|
154
|
+
}
|
|
155
|
+
}}
|
|
156
|
+
/>
|
|
157
|
+
)
|
|
158
|
+
}
|
|
159
|
+
|
|
110
160
|
export const MatchInner = React.memo(function MatchInnerImpl({
|
|
111
161
|
matchId,
|
|
112
162
|
}: {
|
|
@@ -150,25 +200,6 @@ export const MatchInner = React.memo(function MatchInnerImpl({
|
|
|
150
200
|
return <Outlet />
|
|
151
201
|
}, [key, route.options.component, router.options.defaultComponent])
|
|
152
202
|
|
|
153
|
-
// function useChangedDiff(value: any) {
|
|
154
|
-
// const ref = React.useRef(value)
|
|
155
|
-
// const changed = ref.current !== value
|
|
156
|
-
// if (changed) {
|
|
157
|
-
// console.log(
|
|
158
|
-
// 'Changed:',
|
|
159
|
-
// value,
|
|
160
|
-
// Object.fromEntries(
|
|
161
|
-
// Object.entries(value).filter(
|
|
162
|
-
// ([key, val]) => val !== ref.current[key],
|
|
163
|
-
// ),
|
|
164
|
-
// ),
|
|
165
|
-
// )
|
|
166
|
-
// }
|
|
167
|
-
// ref.current = value
|
|
168
|
-
// }
|
|
169
|
-
|
|
170
|
-
// useChangedDiff(match)
|
|
171
|
-
|
|
172
203
|
const RouteErrorComponent =
|
|
173
204
|
(route.options.errorComponent ?? router.options.defaultErrorComponent) ||
|
|
174
205
|
ErrorComponent
|
package/src/Matches.tsx
CHANGED
|
@@ -199,7 +199,7 @@ export function useMatchRoute<TRouter extends AnyRouter = RegisteredRouter>() {
|
|
|
199
199
|
const router = useRouter()
|
|
200
200
|
|
|
201
201
|
useRouterState({
|
|
202
|
-
select: (s) => [s.location.href, s.resolvedLocation
|
|
202
|
+
select: (s) => [s.location.href, s.resolvedLocation?.href, s.status],
|
|
203
203
|
structuralSharing: true as any,
|
|
204
204
|
})
|
|
205
205
|
|
package/src/ScriptOnce.tsx
CHANGED
|
@@ -22,7 +22,7 @@ export function ScriptOnce({
|
|
|
22
22
|
? `console.info(\`Injected From Server:
|
|
23
23
|
${jsesc(children.toString(), { quotes: 'backtick' })}\`)`
|
|
24
24
|
: '',
|
|
25
|
-
'if (typeof
|
|
25
|
+
'if (typeof __TSR_SSR__ !== "undefined") __TSR_SSR__.cleanScripts()',
|
|
26
26
|
]
|
|
27
27
|
.filter(Boolean)
|
|
28
28
|
.join('\n'),
|