@tanstack/react-router 1.7.1 → 1.8.0

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.
Files changed (200) hide show
  1. package/dist/cjs/CatchBoundary.cjs +106 -0
  2. package/dist/cjs/CatchBoundary.cjs.map +1 -0
  3. package/dist/cjs/Matches.cjs +278 -0
  4. package/dist/cjs/Matches.cjs.map +1 -0
  5. package/{build/cjs/RouterProvider.js → dist/cjs/RouterProvider.cjs} +55 -58
  6. package/dist/cjs/RouterProvider.cjs.map +1 -0
  7. package/dist/cjs/awaited.cjs +51 -0
  8. package/dist/cjs/awaited.cjs.map +1 -0
  9. package/dist/cjs/defer.cjs +30 -0
  10. package/dist/cjs/defer.cjs.map +1 -0
  11. package/dist/cjs/fileRoute.cjs +19 -0
  12. package/dist/cjs/fileRoute.cjs.map +1 -0
  13. package/dist/cjs/history.d.cts +7 -0
  14. package/{build/cjs/index.js → dist/cjs/index.cjs} +39 -51
  15. package/dist/cjs/index.cjs.map +1 -0
  16. package/dist/cjs/lazyRouteComponent.cjs +40 -0
  17. package/dist/cjs/lazyRouteComponent.cjs.map +1 -0
  18. package/dist/cjs/link.cjs +196 -0
  19. package/dist/cjs/link.cjs.map +1 -0
  20. package/dist/cjs/link.d.cts +85 -0
  21. package/{build/cjs/path.js → dist/cjs/path.cjs} +77 -94
  22. package/dist/cjs/path.cjs.map +1 -0
  23. package/dist/cjs/qss.cjs +45 -0
  24. package/dist/cjs/qss.cjs.map +1 -0
  25. package/dist/cjs/redirects.cjs +15 -0
  26. package/dist/cjs/redirects.cjs.map +1 -0
  27. package/dist/cjs/route.cjs +143 -0
  28. package/dist/cjs/route.cjs.map +1 -0
  29. package/dist/cjs/router.cjs +1070 -0
  30. package/dist/cjs/router.cjs.map +1 -0
  31. package/dist/cjs/routerContext.cjs +29 -0
  32. package/dist/cjs/routerContext.cjs.map +1 -0
  33. package/{build/cjs/scroll-restoration.js → dist/cjs/scroll-restoration.cjs} +58 -75
  34. package/dist/cjs/scroll-restoration.cjs.map +1 -0
  35. package/{build/cjs/searchParams.js → dist/cjs/searchParams.cjs} +18 -36
  36. package/dist/cjs/searchParams.cjs.map +1 -0
  37. package/dist/cjs/useBlocker.cjs +36 -0
  38. package/dist/cjs/useBlocker.cjs.map +1 -0
  39. package/dist/cjs/useNavigate.cjs +55 -0
  40. package/dist/cjs/useNavigate.cjs.map +1 -0
  41. package/dist/cjs/useParams.cjs +16 -0
  42. package/dist/cjs/useParams.cjs.map +1 -0
  43. package/dist/cjs/useRouteContext.cjs +11 -0
  44. package/dist/cjs/useRouteContext.cjs.map +1 -0
  45. package/dist/cjs/useRouter.cjs +33 -0
  46. package/dist/cjs/useRouter.cjs.map +1 -0
  47. package/dist/cjs/useRouterState.cjs +12 -0
  48. package/dist/cjs/useRouterState.cjs.map +1 -0
  49. package/dist/cjs/useSearch.cjs +13 -0
  50. package/dist/cjs/useSearch.cjs.map +1 -0
  51. package/{build/cjs/utils.js → dist/cjs/utils.cjs} +25 -116
  52. package/dist/cjs/utils.cjs.map +1 -0
  53. package/dist/esm/CatchBoundary.d.ts +36 -0
  54. package/dist/esm/CatchBoundary.js +89 -0
  55. package/dist/esm/CatchBoundary.js.map +1 -0
  56. package/dist/esm/Matches.d.ts +71 -0
  57. package/dist/esm/Matches.js +261 -0
  58. package/{build/cjs → dist/esm}/Matches.js.map +1 -1
  59. package/dist/esm/RouterProvider.d.ts +27 -0
  60. package/dist/esm/RouterProvider.js +136 -0
  61. package/{build/cjs → dist/esm}/RouterProvider.js.map +1 -1
  62. package/dist/esm/awaited.d.ts +9 -0
  63. package/dist/esm/awaited.js +51 -0
  64. package/dist/esm/awaited.js.map +1 -0
  65. package/dist/esm/defer.d.ts +22 -0
  66. package/dist/esm/defer.js +30 -0
  67. package/{build/cjs → dist/esm}/defer.js.map +1 -1
  68. package/dist/esm/fileRoute.d.ts +21 -0
  69. package/dist/esm/fileRoute.js +19 -0
  70. package/dist/esm/fileRoute.js.map +1 -0
  71. package/{build/types → dist/esm}/history.d.ts +1 -1
  72. package/dist/esm/index.d.ts +30 -0
  73. package/dist/esm/index.js +118 -0
  74. package/dist/esm/index.js.map +1 -0
  75. package/dist/esm/lazyRouteComponent.d.ts +2 -0
  76. package/dist/esm/lazyRouteComponent.js +23 -0
  77. package/{build/cjs → dist/esm}/lazyRouteComponent.js.map +1 -1
  78. package/{build/types → dist/esm}/link.d.ts +3 -1
  79. package/dist/esm/link.js +179 -0
  80. package/dist/esm/link.js.map +1 -0
  81. package/dist/esm/location.d.ts +12 -0
  82. package/dist/esm/path.d.ts +17 -0
  83. package/dist/esm/path.js +200 -0
  84. package/dist/esm/path.js.map +1 -0
  85. package/dist/esm/qss.d.ts +2 -0
  86. package/dist/esm/qss.js +45 -0
  87. package/dist/esm/qss.js.map +1 -0
  88. package/dist/esm/redirects.d.ts +11 -0
  89. package/dist/esm/redirects.js +15 -0
  90. package/{build/cjs → dist/esm}/redirects.js.map +1 -1
  91. package/dist/esm/route.d.ts +300 -0
  92. package/dist/esm/route.js +143 -0
  93. package/dist/esm/route.js.map +1 -0
  94. package/dist/esm/routeInfo.d.ts +31 -0
  95. package/dist/esm/router.d.ts +201 -0
  96. package/dist/esm/router.js +1070 -0
  97. package/{build/cjs → dist/esm}/router.js.map +1 -1
  98. package/dist/esm/routerContext.d.ts +3 -0
  99. package/dist/esm/routerContext.js +13 -0
  100. package/{build/cjs → dist/esm}/routerContext.js.map +1 -1
  101. package/dist/esm/scroll-restoration.d.ts +18 -0
  102. package/dist/esm/scroll-restoration.js +168 -0
  103. package/dist/esm/scroll-restoration.js.map +1 -0
  104. package/dist/esm/searchParams.d.ts +7 -0
  105. package/dist/esm/searchParams.js +63 -0
  106. package/{build/cjs → dist/esm}/searchParams.js.map +1 -1
  107. package/dist/esm/useBlocker.d.ts +9 -0
  108. package/dist/esm/useBlocker.js +19 -0
  109. package/{build/cjs → dist/esm}/useBlocker.js.map +1 -1
  110. package/dist/esm/useNavigate.d.ts +20 -0
  111. package/dist/esm/useNavigate.js +38 -0
  112. package/{build/cjs → dist/esm}/useNavigate.js.map +1 -1
  113. package/dist/esm/useParams.d.ts +7 -0
  114. package/dist/esm/useParams.js +16 -0
  115. package/{build/cjs → dist/esm}/useParams.js.map +1 -1
  116. package/dist/esm/useRouteContext.d.ts +7 -0
  117. package/dist/esm/useRouteContext.js +11 -0
  118. package/{build/cjs → dist/esm}/useRouteContext.js.map +1 -1
  119. package/dist/esm/useRouter.d.ts +5 -0
  120. package/dist/esm/useRouter.js +16 -0
  121. package/{build/cjs → dist/esm}/useRouter.js.map +1 -1
  122. package/dist/esm/useRouterState.d.ts +6 -0
  123. package/dist/esm/useRouterState.js +12 -0
  124. package/{build/cjs → dist/esm}/useRouterState.js.map +1 -1
  125. package/dist/esm/useSearch.d.ts +7 -0
  126. package/dist/esm/useSearch.js +13 -0
  127. package/dist/esm/useSearch.js.map +1 -0
  128. package/dist/esm/utils.d.ts +46 -0
  129. package/dist/esm/utils.js +137 -0
  130. package/{build/cjs → dist/esm}/utils.js.map +1 -1
  131. package/package.json +43 -22
  132. package/src/fileRoute.ts +4 -5
  133. package/src/link.tsx +5 -4
  134. package/src/route.ts +5 -6
  135. package/src/useSearch.tsx +5 -2
  136. package/build/cjs/CatchBoundary.js +0 -128
  137. package/build/cjs/CatchBoundary.js.map +0 -1
  138. package/build/cjs/Matches.js +0 -260
  139. package/build/cjs/_virtual/_rollupPluginBabelHelpers.js +0 -29
  140. package/build/cjs/_virtual/_rollupPluginBabelHelpers.js.map +0 -1
  141. package/build/cjs/awaited.js +0 -60
  142. package/build/cjs/awaited.js.map +0 -1
  143. package/build/cjs/defer.js +0 -42
  144. package/build/cjs/fileRoute.js +0 -31
  145. package/build/cjs/fileRoute.js.map +0 -1
  146. package/build/cjs/index.js.map +0 -1
  147. package/build/cjs/lazyRouteComponent.js +0 -54
  148. package/build/cjs/link.js +0 -224
  149. package/build/cjs/link.js.map +0 -1
  150. package/build/cjs/path.js.map +0 -1
  151. package/build/cjs/qss.js +0 -63
  152. package/build/cjs/qss.js.map +0 -1
  153. package/build/cjs/redirects.js +0 -28
  154. package/build/cjs/route.js +0 -292
  155. package/build/cjs/route.js.map +0 -1
  156. package/build/cjs/router.js +0 -1116
  157. package/build/cjs/routerContext.js +0 -42
  158. package/build/cjs/scroll-restoration.js.map +0 -1
  159. package/build/cjs/useBlocker.js +0 -55
  160. package/build/cjs/useNavigate.js +0 -88
  161. package/build/cjs/useParams.js +0 -27
  162. package/build/cjs/useRouteContext.js +0 -23
  163. package/build/cjs/useRouter.js +0 -44
  164. package/build/cjs/useRouterState.js +0 -24
  165. package/build/cjs/useSearch.js +0 -25
  166. package/build/cjs/useSearch.js.map +0 -1
  167. package/build/esm/index.js +0 -2874
  168. package/build/esm/index.js.map +0 -1
  169. package/build/stats-html.html +0 -4838
  170. package/build/stats-react.json +0 -1471
  171. package/build/umd/index.development.js +0 -3573
  172. package/build/umd/index.development.js.map +0 -1
  173. package/build/umd/index.production.js +0 -22
  174. package/build/umd/index.production.js.map +0 -1
  175. /package/{build/types/CatchBoundary.d.ts → dist/cjs/CatchBoundary.d.cts} +0 -0
  176. /package/{build/types/Matches.d.ts → dist/cjs/Matches.d.cts} +0 -0
  177. /package/{build/types/RouterProvider.d.ts → dist/cjs/RouterProvider.d.cts} +0 -0
  178. /package/{build/types/awaited.d.ts → dist/cjs/awaited.d.cts} +0 -0
  179. /package/{build/types/defer.d.ts → dist/cjs/defer.d.cts} +0 -0
  180. /package/{build/types/fileRoute.d.ts → dist/cjs/fileRoute.d.cts} +0 -0
  181. /package/{build/types/index.d.ts → dist/cjs/index.d.cts} +0 -0
  182. /package/{build/types/lazyRouteComponent.d.ts → dist/cjs/lazyRouteComponent.d.cts} +0 -0
  183. /package/{build/types/location.d.ts → dist/cjs/location.d.cts} +0 -0
  184. /package/{build/types/path.d.ts → dist/cjs/path.d.cts} +0 -0
  185. /package/{build/types/qss.d.ts → dist/cjs/qss.d.cts} +0 -0
  186. /package/{build/types/redirects.d.ts → dist/cjs/redirects.d.cts} +0 -0
  187. /package/{build/types/route.d.ts → dist/cjs/route.d.cts} +0 -0
  188. /package/{build/types/routeInfo.d.ts → dist/cjs/routeInfo.d.cts} +0 -0
  189. /package/{build/types/router.d.ts → dist/cjs/router.d.cts} +0 -0
  190. /package/{build/types/routerContext.d.ts → dist/cjs/routerContext.d.cts} +0 -0
  191. /package/{build/types/scroll-restoration.d.ts → dist/cjs/scroll-restoration.d.cts} +0 -0
  192. /package/{build/types/searchParams.d.ts → dist/cjs/searchParams.d.cts} +0 -0
  193. /package/{build/types/useBlocker.d.ts → dist/cjs/useBlocker.d.cts} +0 -0
  194. /package/{build/types/useNavigate.d.ts → dist/cjs/useNavigate.d.cts} +0 -0
  195. /package/{build/types/useParams.d.ts → dist/cjs/useParams.d.cts} +0 -0
  196. /package/{build/types/useRouteContext.d.ts → dist/cjs/useRouteContext.d.cts} +0 -0
  197. /package/{build/types/useRouter.d.ts → dist/cjs/useRouter.d.cts} +0 -0
  198. /package/{build/types/useRouterState.d.ts → dist/cjs/useRouterState.d.cts} +0 -0
  199. /package/{build/types/useSearch.d.ts → dist/cjs/useSearch.d.cts} +0 -0
  200. /package/{build/types/utils.d.ts → dist/cjs/utils.d.cts} +0 -0
@@ -1,2874 +0,0 @@
1
- /**
2
- * @tanstack/react-router/src/index.tsx
3
- *
4
- * Copyright (c) TanStack
5
- *
6
- * This source code is licensed under the MIT license found in the
7
- * LICENSE.md file in the root directory of this source tree.
8
- *
9
- * @license MIT
10
- */
11
- import { createBrowserHistory, createMemoryHistory } from '@tanstack/history';
12
- export * from '@tanstack/history';
13
- import invariant from 'tiny-invariant';
14
- export { default as invariant } from 'tiny-invariant';
15
- import warning from 'tiny-warning';
16
- export { default as warning } from 'tiny-warning';
17
- import * as React from 'react';
18
- import { useStore } from '@tanstack/react-store';
19
- import { Store } from '@tanstack/store';
20
-
21
- function CatchBoundary(props) {
22
- const errorComponent = props.errorComponent ?? ErrorComponent;
23
- return /*#__PURE__*/React.createElement(CatchBoundaryImpl, {
24
- getResetKey: props.getResetKey,
25
- onCatch: props.onCatch,
26
- children: ({
27
- error
28
- }) => {
29
- if (error) {
30
- return /*#__PURE__*/React.createElement(errorComponent, {
31
- error
32
- });
33
- }
34
- return props.children;
35
- }
36
- });
37
- }
38
- class CatchBoundaryImpl extends React.Component {
39
- state = {
40
- error: null
41
- };
42
- static getDerivedStateFromProps(props) {
43
- return {
44
- resetKey: props.getResetKey()
45
- };
46
- }
47
- static getDerivedStateFromError(error) {
48
- return {
49
- error
50
- };
51
- }
52
- componentDidUpdate(prevProps, prevState) {
53
- if (prevState.error && prevState.resetKey !== this.state.resetKey) {
54
- this.setState({
55
- error: null
56
- });
57
- }
58
- }
59
- componentDidCatch(error) {
60
- console.error(error);
61
- this.props.onCatch?.(error);
62
- }
63
- render() {
64
- return this.props.children(this.state);
65
- }
66
- }
67
- function ErrorComponent({
68
- error
69
- }) {
70
- const [show, setShow] = React.useState(process.env.NODE_ENV !== 'production');
71
- return /*#__PURE__*/React.createElement("div", {
72
- style: {
73
- padding: '.5rem',
74
- maxWidth: '100%'
75
- }
76
- }, /*#__PURE__*/React.createElement("div", {
77
- style: {
78
- display: 'flex',
79
- alignItems: 'center',
80
- gap: '.5rem'
81
- }
82
- }, /*#__PURE__*/React.createElement("strong", {
83
- style: {
84
- fontSize: '1rem'
85
- }
86
- }, "Something went wrong!"), /*#__PURE__*/React.createElement("button", {
87
- style: {
88
- appearance: 'none',
89
- fontSize: '.6em',
90
- border: '1px solid currentColor',
91
- padding: '.1rem .2rem',
92
- fontWeight: 'bold',
93
- borderRadius: '.25rem'
94
- },
95
- onClick: () => setShow(d => !d)
96
- }, show ? 'Hide Error' : 'Show Error')), /*#__PURE__*/React.createElement("div", {
97
- style: {
98
- height: '.25rem'
99
- }
100
- }), show ? /*#__PURE__*/React.createElement("div", null, /*#__PURE__*/React.createElement("pre", {
101
- style: {
102
- fontSize: '.7em',
103
- border: '1px solid red',
104
- borderRadius: '.25rem',
105
- padding: '.3rem',
106
- color: 'red',
107
- overflow: 'auto'
108
- }
109
- }, error.message ? /*#__PURE__*/React.createElement("code", null, error.message) : null)) : null);
110
- }
111
-
112
- let routerContext = /*#__PURE__*/React.createContext(null);
113
- if (typeof document !== 'undefined') {
114
- if (window.__TSR_ROUTER_CONTEXT__) {
115
- routerContext = window.__TSR_ROUTER_CONTEXT__;
116
- } else {
117
- window.__TSR_ROUTER_CONTEXT__ = routerContext;
118
- }
119
- }
120
-
121
- function useRouter(opts) {
122
- const resolvedContext = typeof document !== 'undefined' ? window.__TSR_ROUTER_CONTEXT__ || routerContext : routerContext;
123
- const value = React.useContext(resolvedContext);
124
- warning(!((opts?.warn ?? true) && !value), 'useRouter must be used inside a <RouterProvider> component!');
125
- return value;
126
- }
127
-
128
- function useRouterState(opts) {
129
- const contextRouter = useRouter({
130
- warn: opts?.router === undefined
131
- });
132
- return useStore((opts?.router || contextRouter).__store, opts?.select);
133
- }
134
-
135
- // from https://stackoverflow.com/a/76458160
136
-
137
- // export type Expand<T> = T
138
-
139
- // type Compute<T> = { [K in keyof T]: T[K] } | never
140
-
141
- // type AllKeys<T> = T extends any ? keyof T : never
142
-
143
- // export type MergeUnion<T, Keys extends keyof T = keyof T> = Compute<
144
- // {
145
- // [K in Keys]: T[Keys]
146
- // } & {
147
- // [K in AllKeys<T>]?: T extends any
148
- // ? K extends keyof T
149
- // ? T[K]
150
- // : never
151
- // : never
152
- // }
153
- // >
154
-
155
- // // Sample types to merge
156
- // type TypeA = {
157
- // shared: string
158
- // onlyInA: string
159
- // nested: {
160
- // shared: string
161
- // aProp: string
162
- // }
163
- // array: string[]
164
- // }
165
-
166
- // type TypeB = {
167
- // shared: number
168
- // onlyInB: number
169
- // nested: {
170
- // shared: number
171
- // bProp: number
172
- // }
173
- // array: number[]
174
- // }
175
-
176
- // type TypeC = {
177
- // shared: boolean
178
- // onlyInC: boolean
179
- // nested: {
180
- // shared: boolean
181
- // cProp: boolean
182
- // }
183
- // array: boolean[]
184
- // }
185
-
186
- // type Test = Expand<Assign<TypeA, TypeB>>
187
-
188
- // // Using DeepMerge to merge TypeA and TypeB
189
- // type MergedType = Expand<AssignAll<[TypeA, TypeB, TypeC]>>
190
-
191
- // from https://github.com/type-challenges/type-challenges/issues/737
192
-
193
- //
194
-
195
- const isServer = typeof document === 'undefined';
196
- function last(arr) {
197
- return arr[arr.length - 1];
198
- }
199
- function isFunction(d) {
200
- return typeof d === 'function';
201
- }
202
- function functionalUpdate(updater, previous) {
203
- if (isFunction(updater)) {
204
- return updater(previous);
205
- }
206
- return updater;
207
- }
208
- function pick(parent, keys) {
209
- return keys.reduce((obj, key) => {
210
- obj[key] = parent[key];
211
- return obj;
212
- }, {});
213
- }
214
-
215
- /**
216
- * This function returns `prev` if `_next` is deeply equal.
217
- * If not, it will replace any deeply equal children of `b` with those of `a`.
218
- * This can be used for structural sharing between immutable JSON values for example.
219
- * Do not use this with signals
220
- */
221
- function replaceEqualDeep(prev, _next) {
222
- if (prev === _next) {
223
- return prev;
224
- }
225
- const next = _next;
226
- const array = isPlainArray(prev) && isPlainArray(next);
227
- if (array || isPlainObject(prev) && isPlainObject(next)) {
228
- const prevItems = array ? prev : Object.keys(prev);
229
- const prevSize = prevItems.length;
230
- const nextItems = array ? next : Object.keys(next);
231
- const nextSize = nextItems.length;
232
- const copy = array ? [] : {};
233
- let equalItems = 0;
234
- for (let i = 0; i < nextSize; i++) {
235
- const key = array ? i : nextItems[i];
236
- if (!array && prev[key] === undefined && next[key] === undefined && prevItems.includes(key)) {
237
- copy[key] = undefined;
238
- equalItems++;
239
- } else {
240
- copy[key] = replaceEqualDeep(prev[key], next[key]);
241
- if (copy[key] === prev[key] && prev[key] !== undefined) {
242
- equalItems++;
243
- }
244
- }
245
- }
246
- return prevSize === nextSize && equalItems === prevSize ? prev : copy;
247
- }
248
- return next;
249
- }
250
-
251
- // Copied from: https://github.com/jonschlinkert/is-plain-object
252
- function isPlainObject(o) {
253
- if (!hasObjectPrototype(o)) {
254
- return false;
255
- }
256
-
257
- // If has modified constructor
258
- const ctor = o.constructor;
259
- if (typeof ctor === 'undefined') {
260
- return true;
261
- }
262
-
263
- // If has modified prototype
264
- const prot = ctor.prototype;
265
- if (!hasObjectPrototype(prot)) {
266
- return false;
267
- }
268
-
269
- // If constructor does not have an Object-specific method
270
- if (!prot.hasOwnProperty('isPrototypeOf')) {
271
- return false;
272
- }
273
-
274
- // Most likely a plain Object
275
- return true;
276
- }
277
- function hasObjectPrototype(o) {
278
- return Object.prototype.toString.call(o) === '[object Object]';
279
- }
280
- function isPlainArray(value) {
281
- return Array.isArray(value) && value.length === Object.keys(value).length;
282
- }
283
- function deepEqual(a, b, partial = false) {
284
- if (a === b) {
285
- return true;
286
- }
287
- if (typeof a !== typeof b) {
288
- return false;
289
- }
290
- if (isPlainObject(a) && isPlainObject(b)) {
291
- const aKeys = Object.keys(a);
292
- const bKeys = Object.keys(b);
293
- if (!partial && aKeys.length !== bKeys.length) {
294
- return false;
295
- }
296
- return !bKeys.some(key => !(key in a) || !deepEqual(a[key], b[key], partial));
297
- }
298
- if (Array.isArray(a) && Array.isArray(b)) {
299
- return !a.some((item, index) => !deepEqual(item, b[index], partial));
300
- }
301
- return false;
302
- }
303
- function useStableCallback(fn) {
304
- const fnRef = React.useRef(fn);
305
- fnRef.current = fn;
306
- const ref = React.useRef((...args) => fnRef.current(...args));
307
- return ref.current;
308
- }
309
- function shallow(objA, objB) {
310
- if (Object.is(objA, objB)) {
311
- return true;
312
- }
313
- if (typeof objA !== 'object' || objA === null || typeof objB !== 'object' || objB === null) {
314
- return false;
315
- }
316
- const keysA = Object.keys(objA);
317
- if (keysA.length !== Object.keys(objB).length) {
318
- return false;
319
- }
320
- for (let i = 0; i < keysA.length; i++) {
321
- if (!Object.prototype.hasOwnProperty.call(objB, keysA[i]) || !Object.is(objA[keysA[i]], objB[keysA[i]])) {
322
- return false;
323
- }
324
- }
325
- return true;
326
- }
327
- const useLayoutEffect$1 = typeof window !== 'undefined' ? React.useLayoutEffect : React.useEffect;
328
- function escapeJSON(jsonString) {
329
- return jsonString.replace(/\\/g, '\\\\') // Escape backslashes
330
- .replace(/'/g, "\\'") // Escape single quotes
331
- .replace(/"/g, '\\"'); // Escape double quotes
332
- }
333
-
334
- const matchContext = /*#__PURE__*/React.createContext(undefined);
335
- function Matches() {
336
- const router = useRouter();
337
- const matchId = useRouterState({
338
- select: s => {
339
- return getRenderedMatches(s)[0]?.id;
340
- }
341
- });
342
- return /*#__PURE__*/React.createElement(matchContext.Provider, {
343
- value: matchId
344
- }, /*#__PURE__*/React.createElement(CatchBoundary, {
345
- getResetKey: () => router.state.resolvedLocation.state?.key,
346
- errorComponent: ErrorComponent,
347
- onCatch: () => {
348
- warning(false, `Error in router! Consider setting an 'errorComponent' in your RootRoute! 👍`);
349
- }
350
- }, matchId ? /*#__PURE__*/React.createElement(Match, {
351
- matchId: matchId
352
- }) : null));
353
- }
354
- function SafeFragment(props) {
355
- return /*#__PURE__*/React.createElement(React.Fragment, null, props.children);
356
- }
357
- function Match({
358
- matchId
359
- }) {
360
- const router = useRouter();
361
- const routeId = useRouterState({
362
- select: s => getRenderedMatches(s).find(d => d.id === matchId)?.routeId
363
- });
364
- invariant(routeId, `Could not find routeId for matchId "${matchId}". Please file an issue!`);
365
- const route = router.routesById[routeId];
366
- const PendingComponent = route.options.pendingComponent ?? router.options.defaultPendingComponent;
367
- const pendingElement = PendingComponent ? /*#__PURE__*/React.createElement(PendingComponent, null) : null;
368
- const routeErrorComponent = route.options.errorComponent ?? router.options.defaultErrorComponent ?? ErrorComponent;
369
- const ResolvedSuspenseBoundary = route.options.wrapInSuspense ?? PendingComponent ?? route.options.component?.preload ?? route.options.pendingComponent?.preload ?? route.options.errorComponent?.preload ? React.Suspense : SafeFragment;
370
- const ResolvedCatchBoundary = routeErrorComponent ? CatchBoundary : SafeFragment;
371
- return /*#__PURE__*/React.createElement(matchContext.Provider, {
372
- value: matchId
373
- }, /*#__PURE__*/React.createElement(ResolvedSuspenseBoundary, {
374
- fallback: pendingElement
375
- }, /*#__PURE__*/React.createElement(ResolvedCatchBoundary, {
376
- getResetKey: () => router.state.resolvedLocation.state?.key,
377
- errorComponent: routeErrorComponent,
378
- onCatch: () => {
379
- warning(false, `Error in route match: ${matchId}`);
380
- }
381
- }, /*#__PURE__*/React.createElement(MatchInner, {
382
- matchId: matchId,
383
- pendingElement: pendingElement
384
- }))));
385
- }
386
- function MatchInner({
387
- matchId,
388
- pendingElement
389
- }) {
390
- const router = useRouter();
391
- const routeId = useRouterState({
392
- select: s => getRenderedMatches(s).find(d => d.id === matchId)?.routeId
393
- });
394
- const route = router.routesById[routeId];
395
- const match = useRouterState({
396
- select: s => pick(getRenderedMatches(s).find(d => d.id === matchId), ['status', 'error', 'showPending', 'loadPromise'])
397
- });
398
- if (match.status === 'error') {
399
- if (isServerSideError(match.error)) {
400
- const deserializeError = router.options.errorSerializer?.deserialize ?? defaultDeserializeError;
401
- throw deserializeError(match.error.data);
402
- } else {
403
- throw match.error;
404
- }
405
- }
406
- if (match.status === 'pending') {
407
- if (match.showPending) {
408
- return pendingElement;
409
- }
410
- throw match.loadPromise;
411
- }
412
- if (match.status === 'success') {
413
- let Comp = route.options.component ?? router.options.defaultComponent;
414
- if (Comp) {
415
- return /*#__PURE__*/React.createElement(Comp, null);
416
- }
417
- return /*#__PURE__*/React.createElement(Outlet, null);
418
- }
419
- invariant(false, 'Idle routeMatch status encountered during rendering! You should never see this. File an issue!');
420
- }
421
- const Outlet = /*#__PURE__*/React.memo(function Outlet() {
422
- const matchId = React.useContext(matchContext);
423
- const childMatchId = useRouterState({
424
- select: s => {
425
- const matches = getRenderedMatches(s);
426
- const index = matches.findIndex(d => d.id === matchId);
427
- return matches[index + 1]?.id;
428
- }
429
- });
430
- if (!childMatchId) {
431
- return null;
432
- }
433
- return /*#__PURE__*/React.createElement(Match, {
434
- matchId: childMatchId
435
- });
436
- });
437
- function useMatchRoute() {
438
- useRouterState({
439
- select: s => [s.location, s.resolvedLocation]
440
- });
441
- const {
442
- matchRoute
443
- } = useRouter();
444
- return React.useCallback(opts => {
445
- const {
446
- pending,
447
- caseSensitive,
448
- fuzzy,
449
- includeSearch,
450
- ...rest
451
- } = opts;
452
- return matchRoute(rest, {
453
- pending,
454
- caseSensitive,
455
- fuzzy,
456
- includeSearch
457
- });
458
- }, []);
459
- }
460
- function MatchRoute(props) {
461
- const matchRoute = useMatchRoute();
462
- const params = matchRoute(props);
463
- if (typeof props.children === 'function') {
464
- return props.children(params);
465
- }
466
- return !!params ? props.children : null;
467
- }
468
- function getRenderedMatches(state) {
469
- return state.pendingMatches?.some(d => d.showPending) ? state.pendingMatches : state.matches;
470
- }
471
- function useMatch(opts) {
472
- const router = useRouter();
473
- const nearestMatchId = React.useContext(matchContext);
474
- const nearestMatchRouteId = getRenderedMatches(router.state).find(d => d.id === nearestMatchId)?.routeId;
475
- const matchRouteId = (() => {
476
- const matches = getRenderedMatches(router.state);
477
- const match = opts?.from ? matches.find(d => d.routeId === opts?.from) : matches.find(d => d.id === nearestMatchId);
478
- return match.routeId;
479
- })();
480
- if (opts?.strict ?? true) {
481
- invariant(nearestMatchRouteId == matchRouteId, `useMatch("${matchRouteId}") is being called in a component that is meant to render the '${nearestMatchRouteId}' route. Did you mean to 'useMatch("${matchRouteId}", { strict: false })' or 'useRoute("${matchRouteId}")' instead?`);
482
- }
483
- const matchSelection = useRouterState({
484
- select: state => {
485
- const match = getRenderedMatches(state).find(d => d.id === nearestMatchId);
486
- invariant(match, `Could not find ${opts?.from ? `an active match from "${opts.from}"` : 'a nearest match!'}`);
487
- return opts?.select ? opts.select(match) : match;
488
- }
489
- });
490
- return matchSelection;
491
- }
492
- function useMatches(opts) {
493
- return useRouterState({
494
- select: state => {
495
- let matches = getRenderedMatches(state);
496
- return opts?.select ? opts.select(matches) : matches;
497
- }
498
- });
499
- }
500
- function useParentMatches(opts) {
501
- const contextMatchId = React.useContext(matchContext);
502
- return useMatches({
503
- select: matches => {
504
- matches = matches.slice(matches.findIndex(d => d.id === contextMatchId));
505
- return opts?.select ? opts.select(matches) : matches;
506
- }
507
- });
508
- }
509
- function useLoaderDeps(opts) {
510
- return useMatch({
511
- ...opts,
512
- select: s => {
513
- return typeof opts.select === 'function' ? opts.select(s?.loaderDeps) : s?.loaderDeps;
514
- }
515
- });
516
- }
517
- function useLoaderData(opts) {
518
- return useMatch({
519
- ...opts,
520
- select: s => {
521
- return typeof opts.select === 'function' ? opts.select(s?.loaderData) : s?.loaderData;
522
- }
523
- });
524
- }
525
- function isServerSideError(error) {
526
- if (!(typeof error === 'object' && error && 'data' in error)) return false;
527
- if (!('__isServerError' in error && error.__isServerError)) return false;
528
- if (!(typeof error.data === 'object' && error.data)) return false;
529
- return error.__isServerError === true;
530
- }
531
- function defaultDeserializeError(serializedData) {
532
- if ('name' in serializedData && 'message' in serializedData) {
533
- const error = new Error(serializedData.message);
534
- error.name = serializedData.name;
535
- return error;
536
- }
537
- return serializedData.data;
538
- }
539
-
540
- // @ts-nocheck
541
-
542
- // qss has been slightly modified and inlined here for our use cases (and compression's sake). We've included it as a hard dependency for MIT license attribution.
543
-
544
- function encode(obj, pfx) {
545
- var k,
546
- i,
547
- tmp,
548
- str = '';
549
- for (k in obj) {
550
- if ((tmp = obj[k]) !== void 0) {
551
- if (Array.isArray(tmp)) {
552
- for (i = 0; i < tmp.length; i++) {
553
- str && (str += '&');
554
- str += encodeURIComponent(k) + '=' + encodeURIComponent(tmp[i]);
555
- }
556
- } else {
557
- str && (str += '&');
558
- str += encodeURIComponent(k) + '=' + encodeURIComponent(tmp);
559
- }
560
- }
561
- }
562
- return (pfx || '') + str;
563
- }
564
- function toValue(mix) {
565
- if (!mix) return '';
566
- var str = decodeURIComponent(mix);
567
- if (str === 'false') return false;
568
- if (str === 'true') return true;
569
- return +str * 0 === 0 && +str + '' === str ? +str : str;
570
- }
571
- function decode(str) {
572
- var tmp,
573
- k,
574
- out = {},
575
- arr = str.split('&');
576
- while (tmp = arr.shift()) {
577
- tmp = tmp.split('=');
578
- k = tmp.shift();
579
- if (out[k] !== void 0) {
580
- out[k] = [].concat(out[k], toValue(tmp.shift()));
581
- } else {
582
- out[k] = toValue(tmp.shift());
583
- }
584
- }
585
- return out;
586
- }
587
-
588
- const defaultParseSearch = parseSearchWith(JSON.parse);
589
- const defaultStringifySearch = stringifySearchWith(JSON.stringify, JSON.parse);
590
- function parseSearchWith(parser) {
591
- return searchStr => {
592
- if (searchStr.substring(0, 1) === '?') {
593
- searchStr = searchStr.substring(1);
594
- }
595
- let query = decode(searchStr);
596
-
597
- // Try to parse any query params that might be json
598
- for (let key in query) {
599
- const value = query[key];
600
- if (typeof value === 'string') {
601
- try {
602
- query[key] = parser(value);
603
- } catch (err) {
604
- //
605
- }
606
- }
607
- }
608
- return query;
609
- };
610
- }
611
- function stringifySearchWith(stringify, parser) {
612
- function stringifyValue(val) {
613
- if (typeof val === 'object' && val !== null) {
614
- try {
615
- return stringify(val);
616
- } catch (err) {
617
- // silent
618
- }
619
- } else if (typeof val === 'string' && typeof parser === 'function') {
620
- try {
621
- // Check if it's a valid parseable string.
622
- // If it is, then stringify it again.
623
- parser(val);
624
- return stringify(val);
625
- } catch (err) {
626
- // silent
627
- }
628
- }
629
- return val;
630
- }
631
- return search => {
632
- search = {
633
- ...search
634
- };
635
- if (search) {
636
- Object.keys(search).forEach(key => {
637
- const val = search[key];
638
- if (typeof val === 'undefined' || val === undefined) {
639
- delete search[key];
640
- } else {
641
- search[key] = stringifyValue(val);
642
- }
643
- });
644
- }
645
- const searchStr = encode(search).toString();
646
- return searchStr ? `?${searchStr}` : '';
647
- };
648
- }
649
-
650
- const useTransition = React.useTransition || (() => [false, cb => {
651
- cb();
652
- }]);
653
- function RouterProvider({
654
- router,
655
- ...rest
656
- }) {
657
- // Allow the router to update options on the router instance
658
- router.update({
659
- ...router.options,
660
- ...rest,
661
- context: {
662
- ...router.options.context,
663
- ...rest?.context
664
- }
665
- });
666
- const matches = router.options.InnerWrap ? /*#__PURE__*/React.createElement(router.options.InnerWrap, null, /*#__PURE__*/React.createElement(Matches, null)) : /*#__PURE__*/React.createElement(Matches, null);
667
- const provider = /*#__PURE__*/React.createElement(routerContext.Provider, {
668
- value: router
669
- }, matches, /*#__PURE__*/React.createElement(Transitioner, null));
670
- if (router.options.Wrap) {
671
- return /*#__PURE__*/React.createElement(router.options.Wrap, null, provider);
672
- }
673
- return provider;
674
- }
675
- function Transitioner() {
676
- const mountLoadCount = React.useRef(0);
677
- const router = useRouter();
678
- const routerState = useRouterState({
679
- select: s => pick(s, ['isLoading', 'location', 'resolvedLocation', 'isTransitioning'])
680
- });
681
- const [isTransitioning, startReactTransition] = useTransition();
682
- router.startReactTransition = startReactTransition;
683
- React.useEffect(() => {
684
- if (isTransitioning) {
685
- router.__store.setState(s => ({
686
- ...s,
687
- isTransitioning
688
- }));
689
- }
690
- }, [isTransitioning]);
691
- const tryLoad = () => {
692
- const apply = cb => {
693
- if (!routerState.isTransitioning) {
694
- startReactTransition(() => cb());
695
- } else {
696
- cb();
697
- }
698
- };
699
- apply(() => {
700
- try {
701
- router.load();
702
- } catch (err) {
703
- console.error(err);
704
- }
705
- });
706
- };
707
- useLayoutEffect$1(() => {
708
- const unsub = router.history.subscribe(() => {
709
- router.latestLocation = router.parseLocation(router.latestLocation);
710
- if (routerState.location !== router.latestLocation) {
711
- tryLoad();
712
- }
713
- });
714
- const nextLocation = router.buildLocation({
715
- search: true,
716
- params: true,
717
- hash: true,
718
- state: true
719
- });
720
- if (routerState.location.href !== nextLocation.href) {
721
- router.commitLocation({
722
- ...nextLocation,
723
- replace: true
724
- });
725
- }
726
- return () => {
727
- unsub();
728
- };
729
- }, [router.history]);
730
- useLayoutEffect$1(() => {
731
- if (React.useTransition ? routerState.isTransitioning && !isTransitioning : !routerState.isLoading && routerState.resolvedLocation !== routerState.location) {
732
- router.emit({
733
- type: 'onResolved',
734
- fromLocation: routerState.resolvedLocation,
735
- toLocation: routerState.location,
736
- pathChanged: routerState.location.href !== routerState.resolvedLocation?.href
737
- });
738
- if (document.querySelector) {
739
- if (routerState.location.hash !== '') {
740
- const el = document.getElementById(routerState.location.hash);
741
- if (el) {
742
- el.scrollIntoView();
743
- }
744
- }
745
- }
746
- router.__store.setState(s => ({
747
- ...s,
748
- isTransitioning: false,
749
- resolvedLocation: s.location
750
- }));
751
- }
752
- }, [routerState.isTransitioning, isTransitioning, routerState.isLoading, routerState.resolvedLocation, routerState.location]);
753
- useLayoutEffect$1(() => {
754
- if (!window.__TSR_DEHYDRATED__ && !mountLoadCount.current) {
755
- mountLoadCount.current++;
756
- tryLoad();
757
- }
758
- }, []);
759
- return null;
760
- }
761
- function getRouteMatch(state, id) {
762
- return [...state.cachedMatches, ...(state.pendingMatches ?? []), ...state.matches].find(d => d.id === id);
763
- }
764
-
765
- function joinPaths(paths) {
766
- return cleanPath(paths.filter(Boolean).join('/'));
767
- }
768
- function cleanPath(path) {
769
- // remove double slashes
770
- return path.replace(/\/{2,}/g, '/');
771
- }
772
- function trimPathLeft(path) {
773
- return path === '/' ? path : path.replace(/^\/{1,}/, '');
774
- }
775
- function trimPathRight(path) {
776
- return path === '/' ? path : path.replace(/\/{1,}$/, '');
777
- }
778
- function trimPath(path) {
779
- return trimPathRight(trimPathLeft(path));
780
- }
781
- function resolvePath(basepath, base, to) {
782
- base = base.replace(new RegExp(`^${basepath}`), '/');
783
- to = to.replace(new RegExp(`^${basepath}`), '/');
784
- let baseSegments = parsePathname(base);
785
- const toSegments = parsePathname(to);
786
- toSegments.forEach((toSegment, index) => {
787
- if (toSegment.value === '/') {
788
- if (!index) {
789
- // Leading slash
790
- baseSegments = [toSegment];
791
- } else if (index === toSegments.length - 1) {
792
- // Trailing Slash
793
- baseSegments.push(toSegment);
794
- } else ;
795
- } else if (toSegment.value === '..') {
796
- // Extra trailing slash? pop it off
797
- if (baseSegments.length > 1 && last(baseSegments)?.value === '/') {
798
- baseSegments.pop();
799
- }
800
- baseSegments.pop();
801
- } else if (toSegment.value === '.') {
802
- return;
803
- } else {
804
- baseSegments.push(toSegment);
805
- }
806
- });
807
- const joined = joinPaths([basepath, ...baseSegments.map(d => d.value)]);
808
- return cleanPath(joined);
809
- }
810
- function parsePathname(pathname) {
811
- if (!pathname) {
812
- return [];
813
- }
814
- pathname = cleanPath(pathname);
815
- const segments = [];
816
- if (pathname.slice(0, 1) === '/') {
817
- pathname = pathname.substring(1);
818
- segments.push({
819
- type: 'pathname',
820
- value: '/'
821
- });
822
- }
823
- if (!pathname) {
824
- return segments;
825
- }
826
-
827
- // Remove empty segments and '.' segments
828
- const split = pathname.split('/').filter(Boolean);
829
- segments.push(...split.map(part => {
830
- if (part === '$' || part === '*') {
831
- return {
832
- type: 'wildcard',
833
- value: part
834
- };
835
- }
836
- if (part.charAt(0) === '$') {
837
- return {
838
- type: 'param',
839
- value: part
840
- };
841
- }
842
- return {
843
- type: 'pathname',
844
- value: part
845
- };
846
- }));
847
- if (pathname.slice(-1) === '/') {
848
- pathname = pathname.substring(1);
849
- segments.push({
850
- type: 'pathname',
851
- value: '/'
852
- });
853
- }
854
- return segments;
855
- }
856
- function interpolatePath(path, params, leaveWildcards = false) {
857
- const interpolatedPathSegments = parsePathname(path);
858
- return joinPaths(interpolatedPathSegments.map(segment => {
859
- if (segment.type === 'wildcard') {
860
- const value = params[segment.value];
861
- if (leaveWildcards) return `${segment.value}${value ?? ''}`;
862
- return value;
863
- }
864
- if (segment.type === 'param') {
865
- return params[segment.value.substring(1)] ?? 'undefined';
866
- }
867
- return segment.value;
868
- }));
869
- }
870
- function matchPathname(basepath, currentPathname, matchLocation) {
871
- const pathParams = matchByPath(basepath, currentPathname, matchLocation);
872
- // const searchMatched = matchBySearch(location.search, matchLocation)
873
-
874
- if (matchLocation.to && !pathParams) {
875
- return;
876
- }
877
- return pathParams ?? {};
878
- }
879
- function removeBasepath(basepath, pathname) {
880
- return basepath != '/' ? pathname.substring(basepath.length) : pathname;
881
- }
882
- function matchByPath(basepath, from, matchLocation) {
883
- // Remove the base path from the pathname
884
- from = removeBasepath(basepath, from);
885
- // Default to to $ (wildcard)
886
- const to = `${matchLocation.to ?? '$'}`;
887
- // Parse the from and to
888
- const baseSegments = parsePathname(from);
889
- const routeSegments = parsePathname(to);
890
- if (!from.startsWith('/')) {
891
- baseSegments.unshift({
892
- type: 'pathname',
893
- value: '/'
894
- });
895
- }
896
- if (!to.startsWith('/')) {
897
- routeSegments.unshift({
898
- type: 'pathname',
899
- value: '/'
900
- });
901
- }
902
- const params = {};
903
- let isMatch = (() => {
904
- for (let i = 0; i < Math.max(baseSegments.length, routeSegments.length); i++) {
905
- const baseSegment = baseSegments[i];
906
- const routeSegment = routeSegments[i];
907
- const isLastBaseSegment = i >= baseSegments.length - 1;
908
- const isLastRouteSegment = i >= routeSegments.length - 1;
909
- if (routeSegment) {
910
- if (routeSegment.type === 'wildcard') {
911
- if (baseSegment?.value) {
912
- const _splat = joinPaths(baseSegments.slice(i).map(d => d.value));
913
- // TODO: Deprecate *
914
- params['*'] = _splat;
915
- params['_splat'] = _splat;
916
- return true;
917
- }
918
- return false;
919
- }
920
- if (routeSegment.type === 'pathname') {
921
- if (routeSegment.value === '/' && !baseSegment?.value) {
922
- return true;
923
- }
924
- if (baseSegment) {
925
- if (matchLocation.caseSensitive) {
926
- if (routeSegment.value !== baseSegment.value) {
927
- return false;
928
- }
929
- } else if (routeSegment.value.toLowerCase() !== baseSegment.value.toLowerCase()) {
930
- return false;
931
- }
932
- }
933
- }
934
- if (!baseSegment) {
935
- return false;
936
- }
937
- if (routeSegment.type === 'param') {
938
- if (baseSegment?.value === '/') {
939
- return false;
940
- }
941
- if (baseSegment.value.charAt(0) !== '$') {
942
- params[routeSegment.value.substring(1)] = baseSegment.value;
943
- }
944
- }
945
- }
946
- if (!isLastBaseSegment && isLastRouteSegment) {
947
- params['**'] = joinPaths(baseSegments.slice(i + 1).map(d => d.value));
948
- return !!matchLocation.fuzzy && routeSegment?.value !== '/';
949
- }
950
- }
951
- return true;
952
- })();
953
- return isMatch ? params : undefined;
954
- }
955
-
956
- // Detect if we're in the DOM
957
-
958
- function redirect(opts) {
959
- opts.isRedirect = true;
960
- if (opts.throw) {
961
- throw opts;
962
- }
963
- return opts;
964
- }
965
- function isRedirect(obj) {
966
- return !!obj?.isRedirect;
967
- }
968
-
969
- // import warning from 'tiny-warning'
970
-
971
- //
972
-
973
- const componentTypes = ['component', 'errorComponent', 'pendingComponent'];
974
- class Router {
975
- // Option-independent properties
976
- tempLocationKey = `${Math.round(Math.random() * 10000000)}`;
977
- resetNextScroll = true;
978
- navigateTimeout = null;
979
- latestLoadPromise = Promise.resolve();
980
- subscribers = new Set();
981
- injectedHtml = [];
982
-
983
- // Must build in constructor
984
-
985
- constructor(options) {
986
- this.update({
987
- defaultPreloadDelay: 50,
988
- defaultPendingMs: 1000,
989
- defaultPendingMinMs: 500,
990
- context: undefined,
991
- ...options,
992
- stringifySearch: options?.stringifySearch ?? defaultStringifySearch,
993
- parseSearch: options?.parseSearch ?? defaultParseSearch
994
- });
995
- }
996
-
997
- // These are default implementations that can optionally be overridden
998
- // by the router provider once rendered. We provide these so that the
999
- // router can be used in a non-react environment if necessary
1000
- startReactTransition = fn => fn();
1001
- update = newOptions => {
1002
- const previousOptions = this.options;
1003
- this.options = {
1004
- ...this.options,
1005
- ...newOptions
1006
- };
1007
- if (!this.basepath || newOptions.basepath && newOptions.basepath !== previousOptions.basepath) {
1008
- if (newOptions.basepath === undefined || newOptions.basepath === '' || newOptions.basepath === '/') {
1009
- this.basepath = '/';
1010
- } else {
1011
- this.basepath = `/${trimPath(newOptions.basepath)}`;
1012
- }
1013
- }
1014
- if (!this.history || this.options.history && this.options.history !== this.history) {
1015
- this.history = this.options.history ?? (typeof document !== 'undefined' ? createBrowserHistory() : createMemoryHistory({
1016
- initialEntries: [this.options.basepath || '/']
1017
- }));
1018
- this.latestLocation = this.parseLocation();
1019
- }
1020
- if (this.options.routeTree !== this.routeTree) {
1021
- this.routeTree = this.options.routeTree;
1022
- this.buildRouteTree();
1023
- }
1024
- if (!this.__store) {
1025
- this.__store = new Store(getInitialRouterState(this.latestLocation), {
1026
- onUpdate: () => {
1027
- this.__store.state = {
1028
- ...this.state,
1029
- status: this.state.isTransitioning || this.state.isLoading ? 'pending' : 'idle'
1030
- };
1031
- }
1032
- });
1033
- }
1034
- };
1035
- get state() {
1036
- return this.__store.state;
1037
- }
1038
- buildRouteTree = () => {
1039
- this.routesById = {};
1040
- this.routesByPath = {};
1041
- const notFoundRoute = this.options.notFoundRoute;
1042
- if (notFoundRoute) {
1043
- notFoundRoute.init({
1044
- originalIndex: 99999999999
1045
- });
1046
- this.routesById[notFoundRoute.id] = notFoundRoute;
1047
- }
1048
- const recurseRoutes = childRoutes => {
1049
- childRoutes.forEach((childRoute, i) => {
1050
- childRoute.init({
1051
- originalIndex: i
1052
- });
1053
- const existingRoute = this.routesById[childRoute.id];
1054
- invariant(!existingRoute, `Duplicate routes found with id: ${String(childRoute.id)}`);
1055
- this.routesById[childRoute.id] = childRoute;
1056
- if (!childRoute.isRoot && childRoute.path) {
1057
- const trimmedFullPath = trimPathRight(childRoute.fullPath);
1058
- if (!this.routesByPath[trimmedFullPath] || childRoute.fullPath.endsWith('/')) {
1059
- this.routesByPath[trimmedFullPath] = childRoute;
1060
- }
1061
- }
1062
- const children = childRoute.children;
1063
- if (children?.length) {
1064
- recurseRoutes(children);
1065
- }
1066
- });
1067
- };
1068
- recurseRoutes([this.routeTree]);
1069
- const scoredRoutes = [];
1070
- Object.values(this.routesById).forEach((d, i) => {
1071
- if (d.isRoot || !d.path) {
1072
- return;
1073
- }
1074
- const trimmed = trimPathLeft(d.fullPath);
1075
- const parsed = parsePathname(trimmed);
1076
- while (parsed.length > 1 && parsed[0]?.value === '/') {
1077
- parsed.shift();
1078
- }
1079
- const scores = parsed.map(d => {
1080
- if (d.value === '/') {
1081
- return 0.75;
1082
- }
1083
- if (d.type === 'param') {
1084
- return 0.5;
1085
- }
1086
- if (d.type === 'wildcard') {
1087
- return 0.25;
1088
- }
1089
- return 1;
1090
- });
1091
- scoredRoutes.push({
1092
- child: d,
1093
- trimmed,
1094
- parsed,
1095
- index: i,
1096
- scores
1097
- });
1098
- });
1099
- this.flatRoutes = scoredRoutes.sort((a, b) => {
1100
- const minLength = Math.min(a.scores.length, b.scores.length);
1101
-
1102
- // Sort by min available score
1103
- for (let i = 0; i < minLength; i++) {
1104
- if (a.scores[i] !== b.scores[i]) {
1105
- return b.scores[i] - a.scores[i];
1106
- }
1107
- }
1108
-
1109
- // Sort by length of score
1110
- if (a.scores.length !== b.scores.length) {
1111
- return b.scores.length - a.scores.length;
1112
- }
1113
-
1114
- // Sort by min available parsed value
1115
- for (let i = 0; i < minLength; i++) {
1116
- if (a.parsed[i].value !== b.parsed[i].value) {
1117
- return a.parsed[i].value > b.parsed[i].value ? 1 : -1;
1118
- }
1119
- }
1120
-
1121
- // Sort by original index
1122
- return a.index - b.index;
1123
- }).map((d, i) => {
1124
- d.child.rank = i;
1125
- return d.child;
1126
- });
1127
- };
1128
- subscribe = (eventType, fn) => {
1129
- const listener = {
1130
- eventType,
1131
- fn
1132
- };
1133
- this.subscribers.add(listener);
1134
- return () => {
1135
- this.subscribers.delete(listener);
1136
- };
1137
- };
1138
- emit = routerEvent => {
1139
- this.subscribers.forEach(listener => {
1140
- if (listener.eventType === routerEvent.type) {
1141
- listener.fn(routerEvent);
1142
- }
1143
- });
1144
- };
1145
- checkLatest = promise => {
1146
- return this.latestLoadPromise !== promise ? this.latestLoadPromise : undefined;
1147
- };
1148
- parseLocation = previousLocation => {
1149
- const parse = ({
1150
- pathname,
1151
- search,
1152
- hash,
1153
- state
1154
- }) => {
1155
- const parsedSearch = this.options.parseSearch(search);
1156
- return {
1157
- pathname: pathname,
1158
- searchStr: search,
1159
- search: replaceEqualDeep(previousLocation?.search, parsedSearch),
1160
- hash: hash.split('#').reverse()[0] ?? '',
1161
- href: `${pathname}${search}${hash}`,
1162
- state: replaceEqualDeep(previousLocation?.state, state)
1163
- };
1164
- };
1165
- const location = parse(this.history.location);
1166
- let {
1167
- __tempLocation,
1168
- __tempKey
1169
- } = location.state;
1170
- if (__tempLocation && (!__tempKey || __tempKey === this.tempLocationKey)) {
1171
- // Sync up the location keys
1172
- const parsedTempLocation = parse(__tempLocation);
1173
- parsedTempLocation.state.key = location.state.key;
1174
- delete parsedTempLocation.state.__tempLocation;
1175
- return {
1176
- ...parsedTempLocation,
1177
- maskedLocation: location
1178
- };
1179
- }
1180
- return location;
1181
- };
1182
- resolvePathWithBase = (from, path) => {
1183
- return resolvePath(this.basepath, from, cleanPath(path));
1184
- };
1185
- get looseRoutesById() {
1186
- return this.routesById;
1187
- }
1188
- matchRoutes = (pathname, locationSearch, opts) => {
1189
- let routeParams = {};
1190
- let foundRoute = this.flatRoutes.find(route => {
1191
- const matchedParams = matchPathname(this.basepath, trimPathRight(pathname), {
1192
- to: route.fullPath,
1193
- caseSensitive: route.options.caseSensitive ?? this.options.caseSensitive,
1194
- fuzzy: true
1195
- });
1196
- if (matchedParams) {
1197
- routeParams = matchedParams;
1198
- return true;
1199
- }
1200
- return false;
1201
- });
1202
- let routeCursor = foundRoute || this.routesById['__root__'];
1203
- let matchedRoutes = [routeCursor];
1204
-
1205
- // Check to see if the route needs a 404 entry
1206
- if (
1207
- // If we found a route, and it's not an index route and we have left over path
1208
- (foundRoute ? foundRoute.path !== '/' && routeParams['**'] :
1209
- // Or if we didn't find a route and we have left over path
1210
- trimPathRight(pathname)) &&
1211
- // And we have a 404 route configured
1212
- this.options.notFoundRoute) {
1213
- matchedRoutes.push(this.options.notFoundRoute);
1214
- }
1215
- while (routeCursor?.parentRoute) {
1216
- routeCursor = routeCursor.parentRoute;
1217
- if (routeCursor) matchedRoutes.unshift(routeCursor);
1218
- }
1219
-
1220
- // Existing matches are matches that are already loaded along with
1221
- // pending matches that are still loading
1222
-
1223
- const parseErrors = matchedRoutes.map(route => {
1224
- let parsedParamsError;
1225
- if (route.options.parseParams) {
1226
- try {
1227
- const parsedParams = route.options.parseParams(routeParams);
1228
- // Add the parsed params to the accumulated params bag
1229
- Object.assign(routeParams, parsedParams);
1230
- } catch (err) {
1231
- parsedParamsError = new PathParamError(err.message, {
1232
- cause: err
1233
- });
1234
- if (opts?.throwOnError) {
1235
- throw parsedParamsError;
1236
- }
1237
- return parsedParamsError;
1238
- }
1239
- }
1240
- return;
1241
- });
1242
- const matches = [];
1243
- matchedRoutes.forEach((route, index) => {
1244
- // Take each matched route and resolve + validate its search params
1245
- // This has to happen serially because each route's search params
1246
- // can depend on the parent route's search params
1247
- // It must also happen before we create the match so that we can
1248
- // pass the search params to the route's potential key function
1249
- // which is used to uniquely identify the route match in state
1250
-
1251
- const parentMatch = matches[index - 1];
1252
- const [preMatchSearch, searchError] = (() => {
1253
- // Validate the search params and stabilize them
1254
- const parentSearch = parentMatch?.search ?? locationSearch;
1255
- try {
1256
- const validator = typeof route.options.validateSearch === 'object' ? route.options.validateSearch.parse : route.options.validateSearch;
1257
- let search = validator?.(parentSearch) ?? {};
1258
- return [{
1259
- ...parentSearch,
1260
- ...search
1261
- }, undefined];
1262
- } catch (err) {
1263
- const searchError = new SearchParamError(err.message, {
1264
- cause: err
1265
- });
1266
- if (opts?.throwOnError) {
1267
- throw searchError;
1268
- }
1269
- return [parentSearch, searchError];
1270
- }
1271
- })();
1272
-
1273
- // This is where we need to call route.options.loaderDeps() to get any additional
1274
- // deps that the route's loader function might need to run. We need to do this
1275
- // before we create the match so that we can pass the deps to the route's
1276
- // potential key function which is used to uniquely identify the route match in state
1277
-
1278
- const loaderDeps = route.options.loaderDeps?.({
1279
- search: preMatchSearch
1280
- }) ?? '';
1281
- const loaderDepsHash = loaderDeps ? JSON.stringify(loaderDeps) : '';
1282
- const interpolatedPath = interpolatePath(route.fullPath, routeParams);
1283
- const matchId = interpolatePath(route.id, routeParams, true) + loaderDepsHash;
1284
-
1285
- // Waste not, want not. If we already have a match for this route,
1286
- // reuse it. This is important for layout routes, which might stick
1287
- // around between navigation actions that only change leaf routes.
1288
- const existingMatch = getRouteMatch(this.state, matchId);
1289
- const cause = this.state.matches.find(d => d.id === matchId) ? 'stay' : 'enter';
1290
-
1291
- // Create a fresh route match
1292
- const hasLoaders = !!(route.options.loader || componentTypes.some(d => route.options[d]?.preload));
1293
- const match = existingMatch ? {
1294
- ...existingMatch,
1295
- cause
1296
- } : {
1297
- id: matchId,
1298
- routeId: route.id,
1299
- params: routeParams,
1300
- pathname: joinPaths([this.basepath, interpolatedPath]),
1301
- updatedAt: Date.now(),
1302
- search: {},
1303
- searchError: undefined,
1304
- status: hasLoaders ? 'pending' : 'success',
1305
- showPending: false,
1306
- isFetching: false,
1307
- error: undefined,
1308
- paramsError: parseErrors[index],
1309
- loadPromise: Promise.resolve(),
1310
- routeContext: undefined,
1311
- context: undefined,
1312
- abortController: new AbortController(),
1313
- fetchCount: 0,
1314
- cause,
1315
- loaderDeps,
1316
- invalid: false,
1317
- preload: false
1318
- };
1319
-
1320
- // Regardless of whether we're reusing an existing match or creating
1321
- // a new one, we need to update the match's search params
1322
- match.search = replaceEqualDeep(match.search, preMatchSearch);
1323
- // And also update the searchError if there is one
1324
- match.searchError = searchError;
1325
- matches.push(match);
1326
- });
1327
- return matches;
1328
- };
1329
- cancelMatch = id => {
1330
- getRouteMatch(this.state, id)?.abortController?.abort();
1331
- };
1332
- cancelMatches = () => {
1333
- this.state.pendingMatches?.forEach(match => {
1334
- this.cancelMatch(match.id);
1335
- });
1336
- };
1337
- buildLocation = opts => {
1338
- const build = (dest = {}, matches) => {
1339
- const relevantMatches = this.state.pendingMatches || this.state.matches;
1340
- const fromSearch = relevantMatches[relevantMatches.length - 1]?.search || this.latestLocation.search;
1341
- let pathname = this.resolvePathWithBase(dest.from ?? this.latestLocation.pathname, `${dest.to ?? ''}`);
1342
- const fromMatches = this.matchRoutes(this.latestLocation.pathname, fromSearch);
1343
- const stayingMatches = matches?.filter(d => fromMatches?.find(e => e.routeId === d.routeId));
1344
- const prevParams = {
1345
- ...last(fromMatches)?.params
1346
- };
1347
- let nextParams = (dest.params ?? true) === true ? prevParams : functionalUpdate(dest.params, prevParams);
1348
- if (nextParams) {
1349
- matches?.map(d => this.looseRoutesById[d.routeId].options.stringifyParams).filter(Boolean).forEach(fn => {
1350
- nextParams = {
1351
- ...nextParams,
1352
- ...fn(nextParams)
1353
- };
1354
- });
1355
- }
1356
- pathname = interpolatePath(pathname, nextParams ?? {});
1357
- const preSearchFilters = stayingMatches?.map(match => this.looseRoutesById[match.routeId].options.preSearchFilters ?? []).flat().filter(Boolean) ?? [];
1358
- const postSearchFilters = stayingMatches?.map(match => this.looseRoutesById[match.routeId].options.postSearchFilters ?? []).flat().filter(Boolean) ?? [];
1359
-
1360
- // Pre filters first
1361
- const preFilteredSearch = preSearchFilters?.length ? preSearchFilters?.reduce((prev, next) => next(prev), fromSearch) : fromSearch;
1362
-
1363
- // Then the link/navigate function
1364
- const destSearch = dest.search === true ? preFilteredSearch // Preserve resolvedFrom true
1365
- : dest.search ? functionalUpdate(dest.search, preFilteredSearch) ?? {} // Updater
1366
- : preSearchFilters?.length ? preFilteredSearch // Preserve resolvedFrom filters
1367
- : {};
1368
-
1369
- // Then post filters
1370
- const postFilteredSearch = postSearchFilters?.length ? postSearchFilters.reduce((prev, next) => next(prev), destSearch) : destSearch;
1371
- const search = replaceEqualDeep(fromSearch, postFilteredSearch);
1372
- const searchStr = this.options.stringifySearch(search);
1373
- const hash = dest.hash === true ? this.latestLocation.hash : dest.hash ? functionalUpdate(dest.hash, this.latestLocation.hash) : undefined;
1374
- const hashStr = hash ? `#${hash}` : '';
1375
- let nextState = dest.state === true ? this.latestLocation.state : dest.state ? functionalUpdate(dest.state, this.latestLocation.state) : this.latestLocation.state;
1376
- nextState = replaceEqualDeep(this.latestLocation.state, nextState);
1377
- return {
1378
- pathname,
1379
- search,
1380
- searchStr,
1381
- state: nextState,
1382
- hash: hash ?? '',
1383
- href: `${pathname}${searchStr}${hashStr}`,
1384
- unmaskOnReload: dest.unmaskOnReload
1385
- };
1386
- };
1387
- const buildWithMatches = (dest = {}, maskedDest) => {
1388
- let next = build(dest);
1389
- let maskedNext = maskedDest ? build(maskedDest) : undefined;
1390
- if (!maskedNext) {
1391
- let params = {};
1392
- let foundMask = this.options.routeMasks?.find(d => {
1393
- const match = matchPathname(this.basepath, next.pathname, {
1394
- to: d.from,
1395
- caseSensitive: false,
1396
- fuzzy: false
1397
- });
1398
- if (match) {
1399
- params = match;
1400
- return true;
1401
- }
1402
- return false;
1403
- });
1404
- if (foundMask) {
1405
- maskedDest = {
1406
- ...pick(opts, ['from']),
1407
- ...foundMask,
1408
- params
1409
- };
1410
- maskedNext = build(maskedDest);
1411
- }
1412
- }
1413
- const nextMatches = this.matchRoutes(next.pathname, next.search);
1414
- const maskedMatches = maskedNext ? this.matchRoutes(maskedNext.pathname, maskedNext.search) : undefined;
1415
- const maskedFinal = maskedNext ? build(maskedDest, maskedMatches) : undefined;
1416
- const final = build(dest, nextMatches);
1417
- if (maskedFinal) {
1418
- final.maskedLocation = maskedFinal;
1419
- }
1420
- return final;
1421
- };
1422
- if (opts.mask) {
1423
- return buildWithMatches(opts, {
1424
- ...pick(opts, ['from']),
1425
- ...opts.mask
1426
- });
1427
- }
1428
- return buildWithMatches(opts);
1429
- };
1430
- commitLocation = async ({
1431
- startTransition,
1432
- ...next
1433
- }) => {
1434
- if (this.navigateTimeout) clearTimeout(this.navigateTimeout);
1435
- const isSameUrl = this.latestLocation.href === next.href;
1436
-
1437
- // If the next urls are the same and we're not replacing,
1438
- // do nothing
1439
- if (!isSameUrl || !next.replace) {
1440
- let {
1441
- maskedLocation,
1442
- ...nextHistory
1443
- } = next;
1444
- if (maskedLocation) {
1445
- nextHistory = {
1446
- ...maskedLocation,
1447
- state: {
1448
- ...maskedLocation.state,
1449
- __tempKey: undefined,
1450
- __tempLocation: {
1451
- ...nextHistory,
1452
- search: nextHistory.searchStr,
1453
- state: {
1454
- ...nextHistory.state,
1455
- __tempKey: undefined,
1456
- __tempLocation: undefined,
1457
- key: undefined
1458
- }
1459
- }
1460
- }
1461
- };
1462
- if (nextHistory.unmaskOnReload ?? this.options.unmaskOnReload ?? false) {
1463
- nextHistory.state.__tempKey = this.tempLocationKey;
1464
- }
1465
- }
1466
- const apply = () => {
1467
- this.history[next.replace ? 'replace' : 'push'](nextHistory.href, nextHistory.state);
1468
- };
1469
- if (startTransition ?? true) {
1470
- this.startReactTransition(apply);
1471
- } else {
1472
- apply();
1473
- }
1474
- }
1475
- this.resetNextScroll = next.resetScroll ?? true;
1476
- return this.latestLoadPromise;
1477
- };
1478
- buildAndCommitLocation = ({
1479
- replace,
1480
- resetScroll,
1481
- startTransition,
1482
- ...rest
1483
- } = {}) => {
1484
- const location = this.buildLocation(rest);
1485
- return this.commitLocation({
1486
- ...location,
1487
- startTransition,
1488
- replace,
1489
- resetScroll
1490
- });
1491
- };
1492
- navigate = ({
1493
- from,
1494
- to,
1495
- ...rest
1496
- }) => {
1497
- // If this link simply reloads the current route,
1498
- // make sure it has a new key so it will trigger a data refresh
1499
-
1500
- // If this `to` is a valid external URL, return
1501
- // null for LinkUtils
1502
- const toString = String(to);
1503
- // const fromString = from !== undefined ? String(from) : from
1504
- let isExternal;
1505
- try {
1506
- new URL(`${toString}`);
1507
- isExternal = true;
1508
- } catch (e) {}
1509
- invariant(!isExternal, 'Attempting to navigate to external url with this.navigate!');
1510
- return this.buildAndCommitLocation({
1511
- ...rest,
1512
- from,
1513
- to
1514
- // to: toString,
1515
- });
1516
- };
1517
- loadMatches = async ({
1518
- checkLatest,
1519
- matches,
1520
- preload
1521
- }) => {
1522
- let latestPromise;
1523
- let firstBadMatchIndex;
1524
- const updateMatch = match => {
1525
- // const isPreload = this.state.cachedMatches.find((d) => d.id === match.id)
1526
- const isPending = this.state.pendingMatches?.find(d => d.id === match.id);
1527
- const isMatched = this.state.matches.find(d => d.id === match.id);
1528
- const matchesKey = isPending ? 'pendingMatches' : isMatched ? 'matches' : 'cachedMatches';
1529
- this.__store.setState(s => ({
1530
- ...s,
1531
- [matchesKey]: s[matchesKey]?.map(d => d.id === match.id ? match : d)
1532
- }));
1533
- };
1534
-
1535
- // Check each match middleware to see if the route can be accessed
1536
- try {
1537
- for (let [index, match] of matches.entries()) {
1538
- const parentMatch = matches[index - 1];
1539
- const route = this.looseRoutesById[match.routeId];
1540
- const abortController = new AbortController();
1541
- const handleErrorAndRedirect = (err, code) => {
1542
- err.routerCode = code;
1543
- firstBadMatchIndex = firstBadMatchIndex ?? index;
1544
- if (isRedirect(err)) {
1545
- throw err;
1546
- }
1547
- try {
1548
- route.options.onError?.(err);
1549
- } catch (errorHandlerErr) {
1550
- err = errorHandlerErr;
1551
- if (isRedirect(errorHandlerErr)) {
1552
- throw errorHandlerErr;
1553
- }
1554
- }
1555
- matches[index] = match = {
1556
- ...match,
1557
- error: err,
1558
- status: 'error',
1559
- updatedAt: Date.now(),
1560
- abortController: new AbortController()
1561
- };
1562
- };
1563
- try {
1564
- if (match.paramsError) {
1565
- handleErrorAndRedirect(match.paramsError, 'PARSE_PARAMS');
1566
- }
1567
- if (match.searchError) {
1568
- handleErrorAndRedirect(match.searchError, 'VALIDATE_SEARCH');
1569
- }
1570
- const parentContext = parentMatch?.context ?? this.options.context ?? {};
1571
- const pendingMs = route.options.pendingMs ?? this.options.defaultPendingMs;
1572
- const pendingPromise = typeof pendingMs === 'number' && pendingMs <= 0 ? Promise.resolve() : new Promise(r => setTimeout(r, pendingMs));
1573
- const beforeLoadContext = (await route.options.beforeLoad?.({
1574
- search: match.search,
1575
- abortController,
1576
- params: match.params,
1577
- preload: !!preload,
1578
- context: parentContext,
1579
- location: this.state.location,
1580
- // TOOD: just expose state and router, etc
1581
- navigate: opts => this.navigate({
1582
- ...opts,
1583
- from: match.pathname
1584
- }),
1585
- buildLocation: this.buildLocation,
1586
- cause: preload ? 'preload' : match.cause
1587
- })) ?? {};
1588
- if (isRedirect(beforeLoadContext)) {
1589
- throw beforeLoadContext;
1590
- }
1591
- const context = {
1592
- ...parentContext,
1593
- ...beforeLoadContext
1594
- };
1595
- matches[index] = match = {
1596
- ...match,
1597
- routeContext: replaceEqualDeep(match.routeContext, beforeLoadContext),
1598
- context: replaceEqualDeep(match.context, context),
1599
- abortController,
1600
- pendingPromise
1601
- };
1602
- } catch (err) {
1603
- handleErrorAndRedirect(err, 'BEFORE_LOAD');
1604
- break;
1605
- }
1606
- }
1607
- } catch (err) {
1608
- if (isRedirect(err)) {
1609
- if (!preload) this.navigate(err);
1610
- return matches;
1611
- }
1612
- throw err;
1613
- }
1614
- const validResolvedMatches = matches.slice(0, firstBadMatchIndex);
1615
- const matchPromises = [];
1616
- validResolvedMatches.forEach((match, index) => {
1617
- matchPromises.push(new Promise(async resolve => {
1618
- const parentMatchPromise = matchPromises[index - 1];
1619
- const route = this.looseRoutesById[match.routeId];
1620
- const handleErrorAndRedirect = err => {
1621
- if (isRedirect(err)) {
1622
- if (!preload) {
1623
- this.navigate(err);
1624
- }
1625
- return true;
1626
- }
1627
- return false;
1628
- };
1629
- let loadPromise;
1630
- matches[index] = match = {
1631
- ...match,
1632
- showPending: false
1633
- };
1634
- let didShowPending = false;
1635
- const pendingMs = route.options.pendingMs ?? this.options.defaultPendingMs;
1636
- const pendingMinMs = route.options.pendingMinMs ?? this.options.defaultPendingMinMs;
1637
- const shouldPending = !preload && typeof pendingMs === 'number' && (route.options.pendingComponent ?? this.options.defaultPendingComponent);
1638
- const loaderContext = {
1639
- params: match.params,
1640
- deps: match.loaderDeps,
1641
- preload: !!preload,
1642
- parentMatchPromise,
1643
- abortController: match.abortController,
1644
- context: match.context,
1645
- location: this.state.location,
1646
- navigate: opts => this.navigate({
1647
- ...opts,
1648
- from: match.pathname
1649
- }),
1650
- cause: preload ? 'preload' : match.cause
1651
- };
1652
- const fetch = async () => {
1653
- if (match.isFetching) {
1654
- loadPromise = getRouteMatch(this.state, match.id)?.loadPromise;
1655
- } else {
1656
- // If the user doesn't want the route to reload, just
1657
- // resolve with the existing loader data
1658
-
1659
- if (match.fetchCount && match.status === 'success') {
1660
- resolve();
1661
- }
1662
-
1663
- // Otherwise, load the route
1664
- matches[index] = match = {
1665
- ...match,
1666
- isFetching: true,
1667
- fetchCount: match.fetchCount + 1
1668
- };
1669
- const componentsPromise = Promise.all(componentTypes.map(async type => {
1670
- const component = route.options[type];
1671
- if (component?.preload) {
1672
- await component.preload();
1673
- }
1674
- }));
1675
- const loaderPromise = route.options.loader?.(loaderContext);
1676
- loadPromise = Promise.all([componentsPromise, loaderPromise]).then(d => d[1]);
1677
- }
1678
- matches[index] = match = {
1679
- ...match,
1680
- loadPromise
1681
- };
1682
- updateMatch(match);
1683
- try {
1684
- const loaderData = await loadPromise;
1685
- if (latestPromise = checkLatest()) return await latestPromise;
1686
- if (isRedirect(loaderData)) {
1687
- if (handleErrorAndRedirect(loaderData)) return;
1688
- }
1689
- if (didShowPending && pendingMinMs) {
1690
- await new Promise(r => setTimeout(r, pendingMinMs));
1691
- }
1692
- if (latestPromise = checkLatest()) return await latestPromise;
1693
- matches[index] = match = {
1694
- ...match,
1695
- error: undefined,
1696
- status: 'success',
1697
- isFetching: false,
1698
- updatedAt: Date.now(),
1699
- loaderData,
1700
- loadPromise: undefined
1701
- };
1702
- } catch (error) {
1703
- if (latestPromise = checkLatest()) return await latestPromise;
1704
- if (handleErrorAndRedirect(error)) return;
1705
- try {
1706
- route.options.onError?.(error);
1707
- } catch (onErrorError) {
1708
- error = onErrorError;
1709
- if (handleErrorAndRedirect(onErrorError)) return;
1710
- }
1711
- matches[index] = match = {
1712
- ...match,
1713
- error,
1714
- status: 'error',
1715
- isFetching: false
1716
- };
1717
- }
1718
- updateMatch(match);
1719
- };
1720
-
1721
- // This is where all of the stale-while-revalidate magic happens
1722
- const age = Date.now() - match.updatedAt;
1723
- let staleAge = preload ? route.options.preloadStaleTime ?? this.options.defaultPreloadStaleTime ?? 30_000 // 30 seconds for preloads by default
1724
- : route.options.staleTime ?? this.options.defaultStaleTime ?? 0;
1725
-
1726
- // Default to reloading the route all the time
1727
- let shouldReload;
1728
- const shouldReloadOption = route.options.shouldReload;
1729
-
1730
- // Allow shouldReload to get the last say,
1731
- // if provided.
1732
- shouldReload = typeof shouldReloadOption === 'function' ? shouldReloadOption(loaderContext) : shouldReloadOption;
1733
- matches[index] = match = {
1734
- ...match,
1735
- preload: !!preload && !this.state.matches.find(d => d.id === match.id)
1736
- };
1737
- if (match.status !== 'success') {
1738
- // If we need to potentially show the pending component,
1739
- // start a timer to show it after the pendingMs
1740
- if (shouldPending) {
1741
- match.pendingPromise?.then(async () => {
1742
- if (latestPromise = checkLatest()) return latestPromise;
1743
- didShowPending = true;
1744
- matches[index] = match = {
1745
- ...match,
1746
- showPending: true
1747
- };
1748
- updateMatch(match);
1749
- resolve();
1750
- });
1751
- }
1752
-
1753
- // Critical Fetching, we need to await
1754
- await fetch();
1755
- } else if (match.invalid || (shouldReload ?? age > staleAge)) {
1756
- // Background Fetching, no need to wait
1757
- fetch();
1758
- }
1759
- resolve();
1760
- }));
1761
- });
1762
- await Promise.all(matchPromises);
1763
- return matches;
1764
- };
1765
- invalidate = () => {
1766
- const invalidate = d => ({
1767
- ...d,
1768
- invalid: true
1769
- });
1770
- this.__store.setState(s => ({
1771
- ...s,
1772
- matches: s.matches.map(invalidate),
1773
- cachedMatches: s.cachedMatches.map(invalidate),
1774
- pendingMatches: s.pendingMatches?.map(invalidate)
1775
- }));
1776
- this.load();
1777
- };
1778
- load = async () => {
1779
- const promise = new Promise(async (resolve, reject) => {
1780
- const next = this.latestLocation;
1781
- const prevLocation = this.state.resolvedLocation;
1782
- const pathDidChange = prevLocation.href !== next.href;
1783
- let latestPromise;
1784
-
1785
- // Cancel any pending matches
1786
- this.cancelMatches();
1787
- this.emit({
1788
- type: 'onBeforeLoad',
1789
- fromLocation: prevLocation,
1790
- toLocation: next,
1791
- pathChanged: pathDidChange
1792
- });
1793
- let pendingMatches;
1794
- const previousMatches = this.state.matches;
1795
- this.__store.batch(() => {
1796
- this.cleanCache();
1797
-
1798
- // Match the routes
1799
- pendingMatches = this.matchRoutes(next.pathname, next.search, {
1800
- debug: true
1801
- });
1802
-
1803
- // Ingest the new matches
1804
- // If a cached moved to pendingMatches, remove it from cachedMatches
1805
- this.__store.setState(s => ({
1806
- ...s,
1807
- isLoading: true,
1808
- location: next,
1809
- pendingMatches,
1810
- cachedMatches: s.cachedMatches.filter(d => {
1811
- return !pendingMatches.find(e => e.id === d.id);
1812
- })
1813
- }));
1814
- });
1815
- try {
1816
- try {
1817
- // Load the matches
1818
- await this.loadMatches({
1819
- matches: pendingMatches,
1820
- checkLatest: () => this.checkLatest(promise)
1821
- });
1822
- } catch (err) {
1823
- // swallow this error, since we'll display the
1824
- // errors on the route components
1825
- }
1826
-
1827
- // Only apply the latest transition
1828
- if (latestPromise = this.checkLatest(promise)) {
1829
- return latestPromise;
1830
- }
1831
- const exitingMatches = previousMatches.filter(match => !pendingMatches.find(d => d.id === match.id));
1832
- const enteringMatches = pendingMatches.filter(match => !previousMatches.find(d => d.id === match.id));
1833
- const stayingMatches = previousMatches.filter(match => pendingMatches.find(d => d.id === match.id));
1834
-
1835
- // Commit the pending matches. If a previous match was
1836
- // removed, place it in the cachedMatches
1837
- this.__store.batch(() => {
1838
- this.__store.setState(s => ({
1839
- ...s,
1840
- isLoading: false,
1841
- matches: s.pendingMatches,
1842
- pendingMatches: undefined,
1843
- cachedMatches: [...s.cachedMatches, ...exitingMatches.filter(d => d.status !== 'error')]
1844
- }));
1845
- this.cleanCache();
1846
- })
1847
-
1848
- //
1849
- ;
1850
- [[exitingMatches, 'onLeave'], [enteringMatches, 'onEnter'], [stayingMatches, 'onStay']].forEach(([matches, hook]) => {
1851
- matches.forEach(match => {
1852
- this.looseRoutesById[match.routeId].options[hook]?.(match);
1853
- });
1854
- });
1855
- this.emit({
1856
- type: 'onLoad',
1857
- fromLocation: prevLocation,
1858
- toLocation: next,
1859
- pathChanged: pathDidChange
1860
- });
1861
- resolve();
1862
- } catch (err) {
1863
- // Only apply the latest transition
1864
- if (latestPromise = this.checkLatest(promise)) {
1865
- return latestPromise;
1866
- }
1867
- reject(err);
1868
- }
1869
- });
1870
- this.latestLoadPromise = promise;
1871
- return this.latestLoadPromise;
1872
- };
1873
- cleanCache = () => {
1874
- // This is where all of the garbage collection magic happens
1875
- this.__store.setState(s => {
1876
- return {
1877
- ...s,
1878
- cachedMatches: s.cachedMatches.filter(d => {
1879
- const route = this.looseRoutesById[d.routeId];
1880
- if (!route.options.loader) {
1881
- return false;
1882
- }
1883
-
1884
- // If the route was preloaded, use the preloadGcTime
1885
- // otherwise, use the gcTime
1886
- const gcTime = (d.preload ? route.options.preloadGcTime ?? this.options.defaultPreloadGcTime : route.options.gcTime ?? this.options.defaultGcTime) ?? 5 * 60 * 1000;
1887
- return d.status !== 'error' && Date.now() - d.updatedAt < gcTime;
1888
- })
1889
- };
1890
- });
1891
- };
1892
- preloadRoute = async (navigateOpts = this.state.location) => {
1893
- let next = this.buildLocation(navigateOpts);
1894
- let matches = this.matchRoutes(next.pathname, next.search, {
1895
- throwOnError: true
1896
- });
1897
- const loadedMatchIds = Object.fromEntries([...this.state.matches, ...(this.state.pendingMatches ?? []), ...this.state.cachedMatches]?.map(d => [d.id, true]));
1898
- this.__store.batch(() => {
1899
- matches.forEach(match => {
1900
- if (!loadedMatchIds[match.id]) {
1901
- this.__store.setState(s => ({
1902
- ...s,
1903
- cachedMatches: [...s.cachedMatches, match]
1904
- }));
1905
- }
1906
- });
1907
- });
1908
- matches = await this.loadMatches({
1909
- matches,
1910
- preload: true,
1911
- checkLatest: () => undefined
1912
- });
1913
- return matches;
1914
- };
1915
- matchRoute = (location, opts) => {
1916
- location = {
1917
- ...location,
1918
- to: location.to ? this.resolvePathWithBase(location.from || '', location.to) : undefined
1919
- };
1920
- const next = this.buildLocation(location);
1921
- if (opts?.pending && this.state.status !== 'pending') {
1922
- return false;
1923
- }
1924
- const baseLocation = opts?.pending ? this.latestLocation : this.state.resolvedLocation;
1925
- if (!baseLocation) {
1926
- return false;
1927
- }
1928
- const match = matchPathname(this.basepath, baseLocation.pathname, {
1929
- ...opts,
1930
- to: next.pathname
1931
- });
1932
- if (!match) {
1933
- return false;
1934
- }
1935
- if (match && (opts?.includeSearch ?? true)) {
1936
- return deepEqual(baseLocation.search, next.search, true) ? match : false;
1937
- }
1938
- return match;
1939
- };
1940
- injectHtml = async html => {
1941
- this.injectedHtml.push(html);
1942
- };
1943
- dehydrateData = (key, getData) => {
1944
- if (typeof document === 'undefined') {
1945
- const strKey = typeof key === 'string' ? key : JSON.stringify(key);
1946
- this.injectHtml(async () => {
1947
- const id = `__TSR_DEHYDRATED__${strKey}`;
1948
- const data = typeof getData === 'function' ? await getData() : getData;
1949
- return `<script id='${id}' suppressHydrationWarning>window["__TSR_DEHYDRATED__${escapeJSON(strKey)}"] = ${JSON.stringify(data)}
1950
- ;(() => {
1951
- var el = document.getElementById('${id}')
1952
- el.parentElement.removeChild(el)
1953
- })()
1954
- </script>`;
1955
- });
1956
- return () => this.hydrateData(key);
1957
- }
1958
- return () => undefined;
1959
- };
1960
- hydrateData = key => {
1961
- if (typeof document !== 'undefined') {
1962
- const strKey = typeof key === 'string' ? key : JSON.stringify(key);
1963
- return window[`__TSR_DEHYDRATED__${strKey}`];
1964
- }
1965
- return undefined;
1966
- };
1967
- dehydrate = () => {
1968
- const pickError = this.options.errorSerializer?.serialize ?? defaultSerializeError;
1969
- return {
1970
- state: {
1971
- dehydratedMatches: this.state.matches.map(d => ({
1972
- ...pick(d, ['id', 'status', 'updatedAt', 'loaderData']),
1973
- // If an error occurs server-side during SSRing,
1974
- // send a small subset of the error to the client
1975
- error: d.error ? {
1976
- data: pickError(d.error),
1977
- __isServerError: true
1978
- } : undefined
1979
- }))
1980
- }
1981
- };
1982
- };
1983
- hydrate = async __do_not_use_server_ctx => {
1984
- let _ctx = __do_not_use_server_ctx;
1985
- // Client hydrates from window
1986
- if (typeof document !== 'undefined') {
1987
- _ctx = window.__TSR_DEHYDRATED__;
1988
- }
1989
- invariant(_ctx, 'Expected to find a __TSR_DEHYDRATED__ property on window... but we did not. Did you forget to render <DehydrateRouter /> in your app?');
1990
- const ctx = _ctx;
1991
- this.dehydratedData = ctx.payload;
1992
- this.options.hydrate?.(ctx.payload);
1993
- const dehydratedState = ctx.router.state;
1994
- let matches = this.matchRoutes(this.state.location.pathname, this.state.location.search).map(match => {
1995
- const dehydratedMatch = dehydratedState.dehydratedMatches.find(d => d.id === match.id);
1996
- invariant(dehydratedMatch, `Could not find a client-side match for dehydrated match with id: ${match.id}!`);
1997
- if (dehydratedMatch) {
1998
- return {
1999
- ...match,
2000
- ...dehydratedMatch
2001
- };
2002
- }
2003
- return match;
2004
- });
2005
- this.__store.setState(s => {
2006
- return {
2007
- ...s,
2008
- matches: matches
2009
- };
2010
- });
2011
- };
2012
-
2013
- // resolveMatchPromise = (matchId: string, key: string, value: any) => {
2014
- // state.matches
2015
- // .find((d) => d.id === matchId)
2016
- // ?.__promisesByKey[key]?.resolve(value)
2017
- // }
2018
- }
2019
-
2020
- // A function that takes an import() argument which is a function and returns a new function that will
2021
- // proxy arguments from the caller to the imported function, retaining all type
2022
- // information along the way
2023
- function lazyFn(fn, key) {
2024
- return async (...args) => {
2025
- const imported = await fn();
2026
- return imported[key || 'default'](...args);
2027
- };
2028
- }
2029
- class SearchParamError extends Error {}
2030
- class PathParamError extends Error {}
2031
- function getInitialRouterState(location) {
2032
- return {
2033
- isLoading: false,
2034
- isTransitioning: false,
2035
- status: 'idle',
2036
- resolvedLocation: {
2037
- ...location
2038
- },
2039
- location,
2040
- matches: [],
2041
- pendingMatches: [],
2042
- cachedMatches: [],
2043
- lastUpdated: Date.now()
2044
- };
2045
- }
2046
- function defaultSerializeError(err) {
2047
- if (err instanceof Error) return {
2048
- name: err.name,
2049
- message: err.message
2050
- };
2051
- return {
2052
- data: err
2053
- };
2054
- }
2055
-
2056
- function defer(_promise, options) {
2057
- const promise = _promise;
2058
- if (!promise.__deferredState) {
2059
- promise.__deferredState = {
2060
- uid: Math.random().toString(36).slice(2),
2061
- status: 'pending'
2062
- };
2063
- const state = promise.__deferredState;
2064
- promise.then(data => {
2065
- state.status = 'success';
2066
- state.data = data;
2067
- }).catch(error => {
2068
- state.status = 'error';
2069
- state.error = {
2070
- data: (options?.serializeError ?? defaultSerializeError)(error),
2071
- __isServerError: true
2072
- };
2073
- });
2074
- }
2075
- return promise;
2076
- }
2077
- function isDehydratedDeferred(obj) {
2078
- return typeof obj === 'object' && obj !== null && !(obj instanceof Promise) && !obj.then && '__deferredState' in obj;
2079
- }
2080
-
2081
- function useAwaited({
2082
- promise
2083
- }) {
2084
- const router = useRouter();
2085
- let state = promise.__deferredState;
2086
- const key = `__TSR__DEFERRED__${state.uid}`;
2087
- if (isDehydratedDeferred(promise)) {
2088
- state = router.hydrateData(key);
2089
- if (!state) throw new Error('Could not find dehydrated data');
2090
- promise = Promise.resolve(state.data);
2091
- promise.__deferredState = state;
2092
- }
2093
- if (state.status === 'pending') {
2094
- throw promise;
2095
- }
2096
- if (state.status === 'error') {
2097
- if (typeof document !== 'undefined') {
2098
- if (isServerSideError(state.error)) {
2099
- throw (router.options.errorSerializer?.deserialize ?? defaultDeserializeError)(state.error.data);
2100
- } else {
2101
- warning(false, "Encountered a server-side error that doesn't fit the expected shape");
2102
- throw state.error;
2103
- }
2104
- } else {
2105
- router.dehydrateData(key, state);
2106
- throw {
2107
- data: (router.options.errorSerializer?.serialize ?? defaultSerializeError)(state.error),
2108
- __isServerError: true
2109
- };
2110
- }
2111
- }
2112
- router.dehydrateData(key, state);
2113
- return [state.data];
2114
- }
2115
- function Await(props) {
2116
- const awaited = useAwaited(props);
2117
- return props.children(...awaited);
2118
- }
2119
-
2120
- function useParams(opts) {
2121
- return useRouterState({
2122
- select: state => {
2123
- const params = last(getRenderedMatches(state))?.params;
2124
- return opts?.select ? opts.select(params) : params;
2125
- }
2126
- });
2127
- }
2128
-
2129
- function useSearch(opts) {
2130
- return useMatch({
2131
- ...opts,
2132
- select: match => {
2133
- return opts?.select ? opts.select(match.search) : match.search;
2134
- }
2135
- });
2136
- }
2137
-
2138
- const rootRouteId = '__root__';
2139
-
2140
- // The parse type here allows a zod schema to be passed directly to the validator
2141
-
2142
- // TODO: This is part of a future APi to move away from classes and
2143
- // towards a more functional API. It's not ready yet.
2144
-
2145
- // type RouteApiInstance<
2146
- // TId extends RouteIds<RegisteredRouter['routeTree']>,
2147
- // TRoute extends AnyRoute = RouteById<RegisteredRouter['routeTree'], TId>,
2148
- // TFullSearchSchema extends Record<
2149
- // string,
2150
- // any
2151
- // > = TRoute['types']['fullSearchSchema'],
2152
- // TAllParams extends AnyPathParams = TRoute['types']['allParams'],
2153
- // TAllContext extends Record<string, any> = TRoute['types']['allContext'],
2154
- // TLoaderDeps extends Record<string, any> = TRoute['types']['loaderDeps'],
2155
- // TLoaderData extends any = TRoute['types']['loaderData'],
2156
- // > = {
2157
- // id: TId
2158
- // useMatch: <TSelected = TAllContext>(opts?: {
2159
- // select?: (s: TAllContext) => TSelected
2160
- // }) => TSelected
2161
-
2162
- // useRouteContext: <TSelected = TAllContext>(opts?: {
2163
- // select?: (s: TAllContext) => TSelected
2164
- // }) => TSelected
2165
-
2166
- // useSearch: <TSelected = TFullSearchSchema>(opts?: {
2167
- // select?: (s: TFullSearchSchema) => TSelected
2168
- // }) => TSelected
2169
-
2170
- // useParams: <TSelected = TAllParams>(opts?: {
2171
- // select?: (s: TAllParams) => TSelected
2172
- // }) => TSelected
2173
-
2174
- // useLoaderDeps: <TSelected = TLoaderDeps>(opts?: {
2175
- // select?: (s: TLoaderDeps) => TSelected
2176
- // }) => TSelected
2177
-
2178
- // useLoaderData: <TSelected = TLoaderData>(opts?: {
2179
- // select?: (s: TLoaderData) => TSelected
2180
- // }) => TSelected
2181
- // }
2182
-
2183
- // export function RouteApi_v2<
2184
- // TId extends RouteIds<RegisteredRouter['routeTree']>,
2185
- // TRoute extends AnyRoute = RouteById<RegisteredRouter['routeTree'], TId>,
2186
- // TFullSearchSchema extends Record<
2187
- // string,
2188
- // any
2189
- // > = TRoute['types']['fullSearchSchema'],
2190
- // TAllParams extends AnyPathParams = TRoute['types']['allParams'],
2191
- // TAllContext extends Record<string, any> = TRoute['types']['allContext'],
2192
- // TLoaderDeps extends Record<string, any> = TRoute['types']['loaderDeps'],
2193
- // TLoaderData extends any = TRoute['types']['loaderData'],
2194
- // >({
2195
- // id,
2196
- // }: {
2197
- // id: TId
2198
- // }): RouteApiInstance<
2199
- // TId,
2200
- // TRoute,
2201
- // TFullSearchSchema,
2202
- // TAllParams,
2203
- // TAllContext,
2204
- // TLoaderDeps,
2205
- // TLoaderData
2206
- // > {
2207
- // return {
2208
- // id,
2209
-
2210
- // useMatch: (opts) => {
2211
- // return useMatch({ ...opts, from: id })
2212
- // },
2213
-
2214
- // useRouteContext: (opts) => {
2215
- // return useMatch({
2216
- // ...opts,
2217
- // from: id,
2218
- // select: (d: any) => (opts?.select ? opts.select(d.context) : d.context),
2219
- // } as any)
2220
- // },
2221
-
2222
- // useSearch: (opts) => {
2223
- // return useSearch({ ...opts, from: id } as any)
2224
- // },
2225
-
2226
- // useParams: (opts) => {
2227
- // return useParams({ ...opts, from: id } as any)
2228
- // },
2229
-
2230
- // useLoaderDeps: (opts) => {
2231
- // return useLoaderDeps({ ...opts, from: id } as any) as any
2232
- // },
2233
-
2234
- // useLoaderData: (opts) => {
2235
- // return useLoaderData({ ...opts, from: id } as any) as any
2236
- // },
2237
- // }
2238
- // }
2239
-
2240
- class RouteApi {
2241
- constructor({
2242
- id
2243
- }) {
2244
- this.id = id;
2245
- }
2246
- useMatch = opts => {
2247
- return useMatch({
2248
- select: opts?.select,
2249
- from: this.id
2250
- });
2251
- };
2252
- useRouteContext = opts => {
2253
- return useMatch({
2254
- from: this.id,
2255
- select: d => opts?.select ? opts.select(d.context) : d.context
2256
- });
2257
- };
2258
- useSearch = opts => {
2259
- return useSearch({
2260
- ...opts,
2261
- from: this.id
2262
- });
2263
- };
2264
- useParams = opts => {
2265
- return useParams({
2266
- ...opts,
2267
- from: this.id
2268
- });
2269
- };
2270
- useLoaderDeps = opts => {
2271
- return useLoaderDeps({
2272
- ...opts,
2273
- from: this.id
2274
- });
2275
- };
2276
- useLoaderData = opts => {
2277
- return useLoaderData({
2278
- ...opts,
2279
- from: this.id
2280
- });
2281
- };
2282
- }
2283
- class Route {
2284
- // Set up in this.init()
2285
-
2286
- // customId!: TCustomId
2287
-
2288
- // Optional
2289
-
2290
- constructor(options) {
2291
- this.options = options || {};
2292
- this.isRoot = !options?.getParentRoute;
2293
- invariant(!(options?.id && options?.path), `Route cannot have both an 'id' and a 'path' option.`);
2294
- this.$$typeof = Symbol.for('react.memo');
2295
- }
2296
- init = opts => {
2297
- this.originalIndex = opts.originalIndex;
2298
- const options = this.options;
2299
- const isRoot = !options?.path && !options?.id;
2300
- this.parentRoute = this.options?.getParentRoute?.();
2301
- if (isRoot) {
2302
- this.path = rootRouteId;
2303
- } else {
2304
- invariant(this.parentRoute, `Child Route instances must pass a 'getParentRoute: () => ParentRoute' option that returns a Route instance.`);
2305
- }
2306
- let path = isRoot ? rootRouteId : options.path;
2307
-
2308
- // If the path is anything other than an index path, trim it up
2309
- if (path && path !== '/') {
2310
- path = trimPath(path);
2311
- }
2312
- const customId = options?.id || path;
2313
-
2314
- // Strip the parentId prefix from the first level of children
2315
- let id = isRoot ? rootRouteId : joinPaths([this.parentRoute.id === rootRouteId ? '' : this.parentRoute.id, customId]);
2316
- if (path === rootRouteId) {
2317
- path = '/';
2318
- }
2319
- if (id !== rootRouteId) {
2320
- id = joinPaths(['/', id]);
2321
- }
2322
- const fullPath = id === rootRouteId ? '/' : joinPaths([this.parentRoute.fullPath, path]);
2323
- this.path = path;
2324
- this.id = id;
2325
- // this.customId = customId as TCustomId
2326
- this.fullPath = fullPath;
2327
- this.to = fullPath;
2328
- };
2329
- addChildren = children => {
2330
- this.children = children;
2331
- return this;
2332
- };
2333
- updateLoader = options => {
2334
- Object.assign(this.options, options);
2335
- return this;
2336
- };
2337
- update = options => {
2338
- Object.assign(this.options, options);
2339
- return this;
2340
- };
2341
- useMatch = opts => {
2342
- return useMatch({
2343
- ...opts,
2344
- from: this.id
2345
- });
2346
- };
2347
- useRouteContext = opts => {
2348
- return useMatch({
2349
- ...opts,
2350
- from: this.id,
2351
- select: d => opts?.select ? opts.select(d.context) : d.context
2352
- });
2353
- };
2354
- useSearch = opts => {
2355
- return useSearch({
2356
- ...opts,
2357
- from: this.id
2358
- });
2359
- };
2360
- useParams = opts => {
2361
- return useParams({
2362
- ...opts,
2363
- from: this.id
2364
- });
2365
- };
2366
- useLoaderDeps = opts => {
2367
- return useLoaderDeps({
2368
- ...opts,
2369
- from: this.id
2370
- });
2371
- };
2372
- useLoaderData = opts => {
2373
- return useLoaderData({
2374
- ...opts,
2375
- from: this.id
2376
- });
2377
- };
2378
- }
2379
- function rootRouteWithContext() {
2380
- return options => {
2381
- return new RootRoute(options);
2382
- };
2383
- }
2384
- class RootRoute extends Route {
2385
- constructor(options) {
2386
- super(options);
2387
- }
2388
- }
2389
- function createRouteMask(opts) {
2390
- return opts;
2391
- }
2392
-
2393
- //
2394
-
2395
- class NotFoundRoute extends Route {
2396
- constructor(options) {
2397
- super({
2398
- ...options,
2399
- id: '404'
2400
- });
2401
- }
2402
- }
2403
-
2404
- class FileRoute {
2405
- constructor(path) {
2406
- this.path = path;
2407
- }
2408
- createRoute = options => {
2409
- const route = new Route(options);
2410
- route.isRoot = false;
2411
- return route;
2412
- };
2413
- }
2414
- function FileRouteLoader(_path) {
2415
- return loaderFn => loaderFn;
2416
- }
2417
-
2418
- function lazyRouteComponent(importer, exportName) {
2419
- let loadPromise;
2420
- const load = () => {
2421
- if (!loadPromise) {
2422
- loadPromise = importer();
2423
- }
2424
- return loadPromise;
2425
- };
2426
- const lazyComp = /*#__PURE__*/React.lazy(async () => {
2427
- const moduleExports = await load();
2428
- const comp = moduleExports[exportName ?? 'default'];
2429
- return {
2430
- default: comp
2431
- };
2432
- });
2433
- lazyComp.preload = load;
2434
- return lazyComp;
2435
- }
2436
-
2437
- function _extends() {
2438
- _extends = Object.assign ? Object.assign.bind() : function (target) {
2439
- for (var i = 1; i < arguments.length; i++) {
2440
- var source = arguments[i];
2441
- for (var key in source) {
2442
- if (Object.prototype.hasOwnProperty.call(source, key)) {
2443
- target[key] = source[key];
2444
- }
2445
- }
2446
- }
2447
- return target;
2448
- };
2449
- return _extends.apply(this, arguments);
2450
- }
2451
-
2452
- const preloadWarning = 'Error preloading route! ☝️';
2453
- function useLinkProps(options) {
2454
- const router = useRouter();
2455
- const matchPathname = useMatch({
2456
- strict: false,
2457
- select: s => s.pathname
2458
- });
2459
- const {
2460
- // custom props
2461
- children,
2462
- target,
2463
- activeProps = () => ({
2464
- className: 'active'
2465
- }),
2466
- inactiveProps = () => ({}),
2467
- activeOptions,
2468
- disabled,
2469
- hash,
2470
- search,
2471
- params,
2472
- to,
2473
- state,
2474
- mask,
2475
- preload: userPreload,
2476
- preloadDelay: userPreloadDelay,
2477
- replace,
2478
- startTransition,
2479
- resetScroll,
2480
- // element props
2481
- style,
2482
- className,
2483
- onClick,
2484
- onFocus,
2485
- onMouseEnter,
2486
- onMouseLeave,
2487
- onTouchStart,
2488
- ...rest
2489
- } = options;
2490
-
2491
- // If this link simply reloads the current route,
2492
- // make sure it has a new key so it will trigger a data refresh
2493
-
2494
- // If this `to` is a valid external URL, return
2495
- // null for LinkUtils
2496
-
2497
- const dest = {
2498
- from: options.to ? matchPathname : undefined,
2499
- ...options
2500
- };
2501
- let type = 'internal';
2502
- try {
2503
- new URL(`${to}`);
2504
- type = 'external';
2505
- } catch {}
2506
- if (type === 'external') {
2507
- return {
2508
- href: to
2509
- };
2510
- }
2511
- const next = router.buildLocation(dest);
2512
- const preload = userPreload ?? router.options.defaultPreload;
2513
- const preloadDelay = userPreloadDelay ?? router.options.defaultPreloadDelay ?? 0;
2514
- const isActive = useRouterState({
2515
- select: s => {
2516
- // Compare path/hash for matches
2517
- const currentPathSplit = s.location.pathname.split('/');
2518
- const nextPathSplit = next.pathname.split('/');
2519
- const pathIsFuzzyEqual = nextPathSplit.every((d, i) => d === currentPathSplit[i]);
2520
- // Combine the matches based on user router.options
2521
- const pathTest = activeOptions?.exact ? s.location.pathname === next.pathname : pathIsFuzzyEqual;
2522
- const hashTest = activeOptions?.includeHash ? s.location.hash === next.hash : true;
2523
- const searchTest = activeOptions?.includeSearch ?? true ? deepEqual(s.location.search, next.search, !activeOptions?.exact) : true;
2524
-
2525
- // The final "active" test
2526
- return pathTest && hashTest && searchTest;
2527
- }
2528
- });
2529
-
2530
- // The click handler
2531
- const handleClick = e => {
2532
- if (!disabled && !isCtrlEvent(e) && !e.defaultPrevented && (!target || target === '_self') && e.button === 0) {
2533
- e.preventDefault();
2534
-
2535
- // All is well? Navigate!
2536
- router.commitLocation({
2537
- ...next,
2538
- replace,
2539
- resetScroll,
2540
- startTransition
2541
- });
2542
- }
2543
- };
2544
-
2545
- // The click handler
2546
- const handleFocus = e => {
2547
- if (preload) {
2548
- router.preloadRoute(dest).catch(err => {
2549
- console.warn(err);
2550
- console.warn(preloadWarning);
2551
- });
2552
- }
2553
- };
2554
- const handleTouchStart = e => {
2555
- if (preload) {
2556
- router.preloadRoute(dest).catch(err => {
2557
- console.warn(err);
2558
- console.warn(preloadWarning);
2559
- });
2560
- }
2561
- };
2562
- const handleEnter = e => {
2563
- const target = e.target || {};
2564
- if (preload) {
2565
- if (target.preloadTimeout) {
2566
- return;
2567
- }
2568
- target.preloadTimeout = setTimeout(() => {
2569
- target.preloadTimeout = null;
2570
- router.preloadRoute(dest).catch(err => {
2571
- console.warn(err);
2572
- console.warn(preloadWarning);
2573
- });
2574
- }, preloadDelay);
2575
- }
2576
- };
2577
- const handleLeave = e => {
2578
- const target = e.target || {};
2579
- if (target.preloadTimeout) {
2580
- clearTimeout(target.preloadTimeout);
2581
- target.preloadTimeout = null;
2582
- }
2583
- };
2584
- const composeHandlers = handlers => e => {
2585
- if (e.persist) e.persist();
2586
- handlers.filter(Boolean).forEach(handler => {
2587
- if (e.defaultPrevented) return;
2588
- handler(e);
2589
- });
2590
- };
2591
-
2592
- // Get the active props
2593
- const resolvedActiveProps = isActive ? functionalUpdate(activeProps, {}) ?? {} : {};
2594
-
2595
- // Get the inactive props
2596
- const resolvedInactiveProps = isActive ? {} : functionalUpdate(inactiveProps, {}) ?? {};
2597
- return {
2598
- ...resolvedActiveProps,
2599
- ...resolvedInactiveProps,
2600
- ...rest,
2601
- href: disabled ? undefined : next.maskedLocation ? next.maskedLocation.href : next.href,
2602
- onClick: composeHandlers([onClick, handleClick]),
2603
- onFocus: composeHandlers([onFocus, handleFocus]),
2604
- onMouseEnter: composeHandlers([onMouseEnter, handleEnter]),
2605
- onMouseLeave: composeHandlers([onMouseLeave, handleLeave]),
2606
- onTouchStart: composeHandlers([onTouchStart, handleTouchStart]),
2607
- target,
2608
- style: {
2609
- ...style,
2610
- ...resolvedActiveProps.style,
2611
- ...resolvedInactiveProps.style
2612
- },
2613
- className: [className, resolvedActiveProps.className, resolvedInactiveProps.className].filter(Boolean).join(' ') || undefined,
2614
- ...(disabled ? {
2615
- role: 'link',
2616
- 'aria-disabled': true
2617
- } : undefined),
2618
- ['data-status']: isActive ? 'active' : undefined
2619
- };
2620
- }
2621
- const Link = /*#__PURE__*/React.forwardRef((props, ref) => {
2622
- const linkProps = useLinkProps(props);
2623
- return /*#__PURE__*/React.createElement("a", _extends({
2624
- ref: ref
2625
- }, linkProps, {
2626
- children: typeof props.children === 'function' ? props.children({
2627
- isActive: linkProps['data-status'] === 'active'
2628
- }) : props.children
2629
- }));
2630
- });
2631
- function isCtrlEvent(e) {
2632
- return !!(e.metaKey || e.altKey || e.ctrlKey || e.shiftKey);
2633
- }
2634
-
2635
- const useLayoutEffect = typeof window !== 'undefined' ? React.useLayoutEffect : React.useEffect;
2636
- const windowKey = 'window';
2637
- const delimiter = '___';
2638
- let weakScrolledElements = new WeakSet();
2639
- const sessionsStorage = typeof window !== 'undefined' && window.sessionStorage;
2640
- let cache = sessionsStorage ? (() => {
2641
- const storageKey = 'tsr-scroll-restoration-v2';
2642
- const state = JSON.parse(window.sessionStorage.getItem(storageKey) || 'null') || {
2643
- cached: {},
2644
- next: {}
2645
- };
2646
- return {
2647
- state,
2648
- set: updater => {
2649
- cache.state = functionalUpdate(updater, cache.state);
2650
- window.sessionStorage.setItem(storageKey, JSON.stringify(cache.state));
2651
- }
2652
- };
2653
- })() : undefined;
2654
- const defaultGetKey = location => location.state.key;
2655
- function useScrollRestoration(options) {
2656
- const router = useRouter();
2657
- useLayoutEffect(() => {
2658
- const getKey = options?.getKey || defaultGetKey;
2659
- const {
2660
- history
2661
- } = window;
2662
- if (history.scrollRestoration) {
2663
- history.scrollRestoration = 'manual';
2664
- }
2665
- const onScroll = event => {
2666
- if (weakScrolledElements.has(event.target)) return;
2667
- weakScrolledElements.add(event.target);
2668
- let elementSelector = '';
2669
- if (event.target === document || event.target === window) {
2670
- elementSelector = windowKey;
2671
- } else {
2672
- const attrId = event.target.getAttribute('data-scroll-restoration-id');
2673
- if (attrId) {
2674
- elementSelector = `[data-scroll-restoration-id="${attrId}"]`;
2675
- } else {
2676
- elementSelector = getCssSelector(event.target);
2677
- }
2678
- }
2679
- if (!cache.state.next[elementSelector]) {
2680
- cache.set(c => ({
2681
- ...c,
2682
- next: {
2683
- ...c.next,
2684
- [elementSelector]: {
2685
- scrollX: NaN,
2686
- scrollY: NaN
2687
- }
2688
- }
2689
- }));
2690
- }
2691
- };
2692
- if (typeof document !== 'undefined') {
2693
- document.addEventListener('scroll', onScroll, true);
2694
- }
2695
- const unsubOnBeforeLoad = router.subscribe('onBeforeLoad', event => {
2696
- if (event.pathChanged) {
2697
- const restoreKey = getKey(event.fromLocation);
2698
- for (const elementSelector in cache.state.next) {
2699
- const entry = cache.state.next[elementSelector];
2700
- if (elementSelector === windowKey) {
2701
- entry.scrollX = window.scrollX || 0;
2702
- entry.scrollY = window.scrollY || 0;
2703
- } else if (elementSelector) {
2704
- const element = document.querySelector(elementSelector);
2705
- entry.scrollX = element?.scrollLeft || 0;
2706
- entry.scrollY = element?.scrollTop || 0;
2707
- }
2708
- cache.set(c => {
2709
- const next = {
2710
- ...c.next
2711
- };
2712
- delete next[elementSelector];
2713
- return {
2714
- ...c,
2715
- next,
2716
- cached: {
2717
- ...c.cached,
2718
- [[restoreKey, elementSelector].join(delimiter)]: entry
2719
- }
2720
- };
2721
- });
2722
- }
2723
- }
2724
- });
2725
- const unsubOnResolved = router.subscribe('onResolved', event => {
2726
- if (event.pathChanged) {
2727
- if (!router.resetNextScroll) {
2728
- return;
2729
- }
2730
- router.resetNextScroll = true;
2731
- const getKey = options?.getKey || defaultGetKey;
2732
- const restoreKey = getKey(event.toLocation);
2733
- let windowRestored = false;
2734
- for (const cacheKey in cache.state.cached) {
2735
- const entry = cache.state.cached[cacheKey];
2736
- const [key, elementSelector] = cacheKey.split(delimiter);
2737
- if (key === restoreKey) {
2738
- if (elementSelector === windowKey) {
2739
- windowRestored = true;
2740
- window.scrollTo(entry.scrollX, entry.scrollY);
2741
- } else if (elementSelector) {
2742
- const element = document.querySelector(elementSelector);
2743
- if (element) {
2744
- element.scrollLeft = entry.scrollX;
2745
- element.scrollTop = entry.scrollY;
2746
- }
2747
- }
2748
- }
2749
- }
2750
- if (!windowRestored) {
2751
- window.scrollTo(0, 0);
2752
- }
2753
- cache.set(c => ({
2754
- ...c,
2755
- next: {}
2756
- }));
2757
- weakScrolledElements = new WeakSet();
2758
- }
2759
- });
2760
- return () => {
2761
- document.removeEventListener('scroll', onScroll);
2762
- unsubOnBeforeLoad();
2763
- unsubOnResolved();
2764
- };
2765
- }, []);
2766
- }
2767
- function ScrollRestoration(props) {
2768
- useScrollRestoration(props);
2769
- return null;
2770
- }
2771
- function useElementScrollRestoration(options) {
2772
- const router = useRouter();
2773
- const getKey = options?.getKey || defaultGetKey;
2774
- let elementSelector = '';
2775
- if (options.id) {
2776
- elementSelector = `[data-scroll-restoration-id="${options.id}"]`;
2777
- } else {
2778
- const element = options.getElement?.();
2779
- if (!element) {
2780
- return;
2781
- }
2782
- elementSelector = getCssSelector(element);
2783
- }
2784
- const restoreKey = getKey(router.latestLocation);
2785
- const cacheKey = [restoreKey, elementSelector].join(delimiter);
2786
- return cache.state.cached[cacheKey];
2787
- }
2788
- function getCssSelector(el) {
2789
- let path = [],
2790
- parent;
2791
- while (parent = el.parentNode) {
2792
- path.unshift(`${el.tagName}:nth-child(${[].indexOf.call(parent.children, el) + 1})`);
2793
- el = parent;
2794
- }
2795
- return `${path.join(' > ')}`.toLowerCase();
2796
- }
2797
-
2798
- function useBlocker(blockerFn, condition = true) {
2799
- const {
2800
- history
2801
- } = useRouter();
2802
- React.useEffect(() => {
2803
- if (!condition) return;
2804
- return history.block(blockerFn);
2805
- });
2806
- }
2807
- function Block({
2808
- blocker,
2809
- condition,
2810
- children
2811
- }) {
2812
- useBlocker(blocker, condition);
2813
- return children ?? null;
2814
- }
2815
-
2816
- function useNavigate(_defaultOpts) {
2817
- const {
2818
- navigate
2819
- } = useRouter();
2820
- const matchPathname = useMatch({
2821
- strict: false,
2822
- select: s => s.pathname
2823
- });
2824
- return React.useCallback(({
2825
- from,
2826
- ...rest
2827
- }) => {
2828
- return navigate({
2829
- from: rest?.to ? matchPathname : undefined,
2830
- ...rest
2831
- });
2832
- }, []);
2833
- }
2834
-
2835
- // NOTE: I don't know of anyone using this. It's undocumented, so let's wait until someone needs it
2836
- // export function typedNavigate<
2837
- // TRouteTree extends AnyRoute = RegisteredRouter['routeTree'],
2838
- // TDefaultFrom extends RoutePaths<TRouteTree> = '/',
2839
- // >(navigate: (opts: NavigateOptions<any>) => Promise<void>) {
2840
- // return navigate as <
2841
- // TFrom extends RoutePaths<TRouteTree> = TDefaultFrom,
2842
- // TTo extends string = '',
2843
- // TMaskFrom extends RoutePaths<TRouteTree> = '/',
2844
- // TMaskTo extends string = '',
2845
- // >(
2846
- // opts?: NavigateOptions<TRouteTree, TFrom, TTo, TMaskFrom, TMaskTo>,
2847
- // ) => Promise<void>
2848
- // } //
2849
-
2850
- function Navigate(props) {
2851
- const {
2852
- navigate
2853
- } = useRouter();
2854
- const match = useMatch({
2855
- strict: false
2856
- });
2857
- React.useEffect(() => {
2858
- navigate({
2859
- from: props.to ? match.pathname : undefined,
2860
- ...props
2861
- });
2862
- }, []);
2863
- return null;
2864
- }
2865
-
2866
- function useRouteContext(opts) {
2867
- return useMatch({
2868
- ...opts,
2869
- select: match => opts?.select ? opts.select(match.context) : match.context
2870
- });
2871
- }
2872
-
2873
- export { Await, Block, CatchBoundary, CatchBoundaryImpl, ErrorComponent, FileRoute, FileRouteLoader, Link, Match, MatchRoute, Matches, Navigate, NotFoundRoute, Outlet, PathParamError, RootRoute, Route, RouteApi, Router, RouterProvider, ScrollRestoration, SearchParamError, cleanPath, componentTypes, createRouteMask, decode, deepEqual, defaultDeserializeError, defaultParseSearch, defaultSerializeError, defaultStringifySearch, defer, encode, escapeJSON, functionalUpdate, getInitialRouterState, getRenderedMatches, getRouteMatch, interpolatePath, isDehydratedDeferred, isPlainArray, isPlainObject, isRedirect, isServer, isServerSideError, joinPaths, last, lazyFn, lazyRouteComponent, matchByPath, matchContext, matchPathname, parsePathname, parseSearchWith, pick, redirect, removeBasepath, replaceEqualDeep, resolvePath, rootRouteId, rootRouteWithContext, routerContext, shallow, stringifySearchWith, trimPath, trimPathLeft, trimPathRight, useAwaited, useBlocker, useElementScrollRestoration, useLayoutEffect$1 as useLayoutEffect, useLinkProps, useLoaderData, useLoaderDeps, useMatch, useMatchRoute, useMatches, useNavigate, useParams, useParentMatches, useRouteContext, useRouter, useRouterState, useScrollRestoration, useSearch, useStableCallback };
2874
- //# sourceMappingURL=index.js.map