@tanstack/react-router 1.0.0 → 1.0.2

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 (147) hide show
  1. package/build/cjs/RouterProvider.js +3 -1
  2. package/build/cjs/RouterProvider.js.map +1 -1
  3. package/build/cjs/link.js +4 -1
  4. package/build/cjs/link.js.map +1 -1
  5. package/build/cjs/router.js +5 -4
  6. package/build/cjs/router.js.map +1 -1
  7. package/build/cjs/useNavigate.js +9 -6
  8. package/build/cjs/useNavigate.js.map +1 -1
  9. package/build/esm/index.js +21 -12
  10. package/build/esm/index.js.map +1 -1
  11. package/build/stats-html.html +1 -1
  12. package/build/stats-react.json +367 -367
  13. package/build/types/index.d.ts +24 -932
  14. package/build/types/link.d.ts +1 -1
  15. package/build/types/useNavigate.d.ts +2 -2
  16. package/build/umd/index.development.js +21 -12
  17. package/build/umd/index.development.js.map +1 -1
  18. package/build/umd/index.production.js +1 -1
  19. package/build/umd/index.production.js.map +1 -1
  20. package/package.json +2 -2
  21. package/src/RouterProvider.tsx +3 -1
  22. package/src/link.tsx +13 -7
  23. package/src/router.ts +5 -4
  24. package/src/useNavigate.tsx +10 -8
  25. package/build/cjs/_virtual/with-selector.development.js +0 -16
  26. package/build/cjs/_virtual/with-selector.development.js.map +0 -1
  27. package/build/cjs/_virtual/with-selector.js +0 -16
  28. package/build/cjs/_virtual/with-selector.js.map +0 -1
  29. package/build/cjs/_virtual/with-selector.production.min.js +0 -16
  30. package/build/cjs/_virtual/with-selector.production.min.js.map +0 -1
  31. package/build/cjs/build/esm/index.js +0 -79
  32. package/build/cjs/build/esm/index.js.map +0 -1
  33. package/build/cjs/node_modules/.pnpm/@tanstack_react-store@0.2.1_react-dom@18.2.0_react@18.2.0/node_modules/@tanstack/react-store/build/modern/index.js +0 -47
  34. package/build/cjs/node_modules/.pnpm/@tanstack_react-store@0.2.1_react-dom@18.2.0_react@18.2.0/node_modules/@tanstack/react-store/build/modern/index.js.map +0 -1
  35. package/build/cjs/node_modules/.pnpm/@tanstack_store@0.1.3/node_modules/@tanstack/store/build/modern/index.js +0 -70
  36. package/build/cjs/node_modules/.pnpm/@tanstack_store@0.1.3/node_modules/@tanstack/store/build/modern/index.js.map +0 -1
  37. package/build/cjs/node_modules/.pnpm/use-sync-external-store@1.2.0_react@18.2.0/node_modules/use-sync-external-store/cjs/use-sync-external-store-shim/with-selector.development.js +0 -188
  38. package/build/cjs/node_modules/.pnpm/use-sync-external-store@1.2.0_react@18.2.0/node_modules/use-sync-external-store/cjs/use-sync-external-store-shim/with-selector.development.js.map +0 -1
  39. package/build/cjs/node_modules/.pnpm/use-sync-external-store@1.2.0_react@18.2.0/node_modules/use-sync-external-store/cjs/use-sync-external-store-shim/with-selector.production.min.js +0 -39
  40. package/build/cjs/node_modules/.pnpm/use-sync-external-store@1.2.0_react@18.2.0/node_modules/use-sync-external-store/cjs/use-sync-external-store-shim/with-selector.production.min.js.map +0 -1
  41. package/build/cjs/node_modules/.pnpm/use-sync-external-store@1.2.0_react@18.2.0/node_modules/use-sync-external-store/shim/with-selector.js +0 -26
  42. package/build/cjs/node_modules/.pnpm/use-sync-external-store@1.2.0_react@18.2.0/node_modules/use-sync-external-store/shim/with-selector.js.map +0 -1
  43. package/build/cjs/packages/react-router/src/CatchBoundary.js +0 -123
  44. package/build/cjs/packages/react-router/src/CatchBoundary.js.map +0 -1
  45. package/build/cjs/packages/react-router/src/Matches.js +0 -235
  46. package/build/cjs/packages/react-router/src/Matches.js.map +0 -1
  47. package/build/cjs/packages/react-router/src/RouterProvider.js +0 -144
  48. package/build/cjs/packages/react-router/src/RouterProvider.js.map +0 -1
  49. package/build/cjs/packages/react-router/src/awaited.js +0 -43
  50. package/build/cjs/packages/react-router/src/awaited.js.map +0 -1
  51. package/build/cjs/packages/react-router/src/defer.js +0 -37
  52. package/build/cjs/packages/react-router/src/defer.js.map +0 -1
  53. package/build/cjs/packages/react-router/src/fileRoute.js +0 -27
  54. package/build/cjs/packages/react-router/src/fileRoute.js.map +0 -1
  55. package/build/cjs/packages/react-router/src/index.js +0 -61
  56. package/build/cjs/packages/react-router/src/index.js.map +0 -1
  57. package/build/cjs/packages/react-router/src/lazyRouteComponent.js +0 -54
  58. package/build/cjs/packages/react-router/src/lazyRouteComponent.js.map +0 -1
  59. package/build/cjs/packages/react-router/src/link.js +0 -148
  60. package/build/cjs/packages/react-router/src/link.js.map +0 -1
  61. package/build/cjs/packages/react-router/src/path.js +0 -209
  62. package/build/cjs/packages/react-router/src/path.js.map +0 -1
  63. package/build/cjs/packages/react-router/src/qss.js +0 -63
  64. package/build/cjs/packages/react-router/src/qss.js.map +0 -1
  65. package/build/cjs/packages/react-router/src/react.js +0 -634
  66. package/build/cjs/packages/react-router/src/react.js.map +0 -1
  67. package/build/cjs/packages/react-router/src/redirects.js +0 -25
  68. package/build/cjs/packages/react-router/src/redirects.js.map +0 -1
  69. package/build/cjs/packages/react-router/src/route.js +0 -134
  70. package/build/cjs/packages/react-router/src/route.js.map +0 -1
  71. package/build/cjs/packages/react-router/src/router.js +0 -1111
  72. package/build/cjs/packages/react-router/src/router.js.map +0 -1
  73. package/build/cjs/packages/react-router/src/scroll-restoration.js +0 -53
  74. package/build/cjs/packages/react-router/src/scroll-restoration.js.map +0 -1
  75. package/build/cjs/packages/react-router/src/searchParams.js +0 -81
  76. package/build/cjs/packages/react-router/src/searchParams.js.map +0 -1
  77. package/build/cjs/packages/react-router/src/useBlocker.js +0 -61
  78. package/build/cjs/packages/react-router/src/useBlocker.js.map +0 -1
  79. package/build/cjs/packages/react-router/src/useNavigate.js +0 -75
  80. package/build/cjs/packages/react-router/src/useNavigate.js.map +0 -1
  81. package/build/cjs/packages/react-router/src/useParams.js +0 -26
  82. package/build/cjs/packages/react-router/src/useParams.js.map +0 -1
  83. package/build/cjs/packages/react-router/src/useSearch.js +0 -25
  84. package/build/cjs/packages/react-router/src/useSearch.js.map +0 -1
  85. package/build/cjs/packages/react-router/src/utils.js +0 -239
  86. package/build/cjs/packages/react-router/src/utils.js.map +0 -1
  87. package/build/cjs/react/CatchBoundary.js +0 -123
  88. package/build/cjs/react/CatchBoundary.js.map +0 -1
  89. package/build/cjs/react/awaited.js +0 -43
  90. package/build/cjs/react/awaited.js.map +0 -1
  91. package/build/cjs/react/defer.js +0 -37
  92. package/build/cjs/react/defer.js.map +0 -1
  93. package/build/cjs/react.js +0 -650
  94. package/build/cjs/react.js.map +0 -1
  95. package/build/cjs/routerConfig.js +0 -209
  96. package/build/cjs/routerConfig.js.map +0 -1
  97. package/build/cjs/src/CatchBoundary.js +0 -126
  98. package/build/cjs/src/CatchBoundary.js.map +0 -1
  99. package/build/cjs/src/Matches.js +0 -235
  100. package/build/cjs/src/Matches.js.map +0 -1
  101. package/build/cjs/src/RouterProvider.js +0 -1051
  102. package/build/cjs/src/RouterProvider.js.map +0 -1
  103. package/build/cjs/src/awaited.js +0 -45
  104. package/build/cjs/src/awaited.js.map +0 -1
  105. package/build/cjs/src/defer.js +0 -39
  106. package/build/cjs/src/defer.js.map +0 -1
  107. package/build/cjs/src/fileRoute.js +0 -29
  108. package/build/cjs/src/fileRoute.js.map +0 -1
  109. package/build/cjs/src/index.js +0 -134
  110. package/build/cjs/src/index.js.map +0 -1
  111. package/build/cjs/src/lazyRouteComponent.js +0 -57
  112. package/build/cjs/src/lazyRouteComponent.js.map +0 -1
  113. package/build/cjs/src/link.js +0 -151
  114. package/build/cjs/src/link.js.map +0 -1
  115. package/build/cjs/src/path.js +0 -211
  116. package/build/cjs/src/path.js.map +0 -1
  117. package/build/cjs/src/qss.js +0 -65
  118. package/build/cjs/src/qss.js.map +0 -1
  119. package/build/cjs/src/redirects.js +0 -27
  120. package/build/cjs/src/redirects.js.map +0 -1
  121. package/build/cjs/src/route.js +0 -139
  122. package/build/cjs/src/route.js.map +0 -1
  123. package/build/cjs/src/router.js +0 -203
  124. package/build/cjs/src/router.js.map +0 -1
  125. package/build/cjs/src/scroll-restoration.js +0 -186
  126. package/build/cjs/src/scroll-restoration.js.map +0 -1
  127. package/build/cjs/src/searchParams.js +0 -83
  128. package/build/cjs/src/searchParams.js.map +0 -1
  129. package/build/cjs/src/useBlocker.js +0 -64
  130. package/build/cjs/src/useBlocker.js.map +0 -1
  131. package/build/cjs/src/useNavigate.js +0 -78
  132. package/build/cjs/src/useNavigate.js.map +0 -1
  133. package/build/cjs/src/useParams.js +0 -28
  134. package/build/cjs/src/useParams.js.map +0 -1
  135. package/build/cjs/src/useSearch.js +0 -27
  136. package/build/cjs/src/useSearch.js.map +0 -1
  137. package/build/cjs/src/utils.js +0 -230
  138. package/build/cjs/src/utils.js.map +0 -1
  139. package/build/cjs/useStore.js +0 -99
  140. package/build/cjs/useStore.js.map +0 -1
  141. package/build/types/RouteMatch.d.ts +0 -23
  142. package/build/types/injectHtml.d.ts +0 -0
  143. package/build/types/react/CatchBoundary.d.ts +0 -33
  144. package/build/types/react/awaited.d.ts +0 -9
  145. package/build/types/react/defer.d.ts +0 -19
  146. package/build/types/react.d.ts +0 -141
  147. package/build/types/useStore.d.ts +0 -12
@@ -1,1051 +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
- 'use strict';
12
-
13
- Object.defineProperty(exports, '__esModule', { value: true });
14
-
15
- var history = require('@tanstack/history');
16
- var React = require('react');
17
- var invariant = require('tiny-invariant');
18
- var warning = require('tiny-warning');
19
- var Matches = require('./Matches.js');
20
- var path = require('./path.js');
21
- var redirects = require('./redirects.js');
22
- var router = require('./router.js');
23
- var utils = require('./utils.js');
24
-
25
- function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
26
-
27
- function _interopNamespace(e) {
28
- if (e && e.__esModule) return e;
29
- var n = Object.create(null);
30
- if (e) {
31
- Object.keys(e).forEach(function (k) {
32
- if (k !== 'default') {
33
- var d = Object.getOwnPropertyDescriptor(e, k);
34
- Object.defineProperty(n, k, d.get ? d : {
35
- enumerable: true,
36
- get: function () { return e[k]; }
37
- });
38
- }
39
- });
40
- }
41
- n["default"] = e;
42
- return Object.freeze(n);
43
- }
44
-
45
- var React__namespace = /*#__PURE__*/_interopNamespace(React);
46
- var invariant__default = /*#__PURE__*/_interopDefaultLegacy(invariant);
47
- var warning__default = /*#__PURE__*/_interopDefaultLegacy(warning);
48
-
49
- const routerContext = /*#__PURE__*/React__namespace.createContext(null);
50
- if (typeof document !== 'undefined') {
51
- window.__TSR_ROUTER_CONTEXT__ = routerContext;
52
- }
53
- const preloadWarning = 'Error preloading route! ☝️';
54
- function isCtrlEvent(e) {
55
- return !!(e.metaKey || e.altKey || e.ctrlKey || e.shiftKey);
56
- }
57
- class SearchParamError extends Error {}
58
- class PathParamError extends Error {}
59
- function getInitialRouterState(location) {
60
- return {
61
- status: 'idle',
62
- resolvedLocation: location,
63
- location,
64
- matches: [],
65
- pendingMatches: [],
66
- lastUpdated: Date.now()
67
- };
68
- }
69
- function RouterProvider({
70
- router: router$1,
71
- ...rest
72
- }) {
73
- const options = {
74
- ...router$1.options,
75
- ...rest,
76
- context: {
77
- ...router$1.options.context,
78
- ...rest?.context
79
- }
80
- };
81
- const history$1 = React__namespace.useState(() => options.history ?? history.createBrowserHistory())[0];
82
- const tempLocationKeyRef = React__namespace.useRef(`${Math.round(Math.random() * 10000000)}`);
83
- const resetNextScrollRef = React__namespace.useRef(true);
84
- const navigateTimeoutRef = React__namespace.useRef(null);
85
- const latestLoadPromiseRef = React__namespace.useRef(Promise.resolve());
86
- const checkLatest = promise => {
87
- return latestLoadPromiseRef.current !== promise ? latestLoadPromiseRef.current : undefined;
88
- };
89
- const parseLocation = utils.useStableCallback(previousLocation => {
90
- const parse = ({
91
- pathname,
92
- search,
93
- hash,
94
- state
95
- }) => {
96
- const parsedSearch = options.parseSearch(search);
97
- return {
98
- pathname: pathname,
99
- searchStr: search,
100
- search: utils.replaceEqualDeep(previousLocation?.search, parsedSearch),
101
- hash: hash.split('#').reverse()[0] ?? '',
102
- href: `${pathname}${search}${hash}`,
103
- state: utils.replaceEqualDeep(previousLocation?.state, state)
104
- };
105
- };
106
- const location = parse(history$1.location);
107
- let {
108
- __tempLocation,
109
- __tempKey
110
- } = location.state;
111
- if (__tempLocation && (!__tempKey || __tempKey === tempLocationKeyRef.current)) {
112
- // Sync up the location keys
113
- const parsedTempLocation = parse(__tempLocation);
114
- parsedTempLocation.state.key = location.state.key;
115
- delete parsedTempLocation.state.__tempLocation;
116
- return {
117
- ...parsedTempLocation,
118
- maskedLocation: location
119
- };
120
- }
121
- return location;
122
- });
123
- const latestLocationRef = React__namespace.useRef(parseLocation());
124
- const [preState, setState] = React__namespace.useState(() => getInitialRouterState(latestLocationRef.current));
125
- const [isTransitioning, startReactTransition] = React__namespace.useTransition();
126
- const pendingMatchesRef = React__namespace.useRef([]);
127
- const state = React__namespace.useMemo(() => ({
128
- ...preState,
129
- status: isTransitioning ? 'pending' : 'idle',
130
- location: isTransitioning ? latestLocationRef.current : preState.location,
131
- pendingMatches: pendingMatchesRef.current
132
- }), [preState, isTransitioning]);
133
- React__namespace.useLayoutEffect(() => {
134
- if (!isTransitioning && state.resolvedLocation !== state.location) {
135
- router$1.emit({
136
- type: 'onResolved',
137
- fromLocation: state.resolvedLocation,
138
- toLocation: state.location,
139
- pathChanged: state.location.href !== state.resolvedLocation?.href
140
- });
141
- pendingMatchesRef.current = [];
142
- setState(s => ({
143
- ...s,
144
- resolvedLocation: s.location
145
- }));
146
- }
147
- });
148
- const basepath = `/${path.trimPath(options.basepath ?? '') ?? ''}`;
149
- const resolvePathWithBase = utils.useStableCallback((from, path$1) => {
150
- return path.resolvePath(basepath, from, path.cleanPath(path$1));
151
- });
152
- const [routesById, routesByPath] = React__namespace.useMemo(() => {
153
- const routesById = {};
154
- const routesByPath = {};
155
- const recurseRoutes = routes => {
156
- routes.forEach((route, i) => {
157
- route.init({
158
- originalIndex: i
159
- });
160
- const existingRoute = routesById[route.id];
161
- invariant__default["default"](!existingRoute, `Duplicate routes found with id: ${String(route.id)}`);
162
- routesById[route.id] = route;
163
- if (!route.isRoot && route.path) {
164
- const trimmedFullPath = path.trimPathRight(route.fullPath);
165
- if (!routesByPath[trimmedFullPath] || route.fullPath.endsWith('/')) {
166
- routesByPath[trimmedFullPath] = route;
167
- }
168
- }
169
- const children = route.children;
170
- if (children?.length) {
171
- recurseRoutes(children);
172
- }
173
- });
174
- };
175
- recurseRoutes([router$1.routeTree]);
176
- return [routesById, routesByPath];
177
- }, []);
178
- const looseRoutesById = routesById;
179
- const flatRoutes = React__namespace.useMemo(() => Object.values(routesByPath).map((d, i) => {
180
- const trimmed = path.trimPath(d.fullPath);
181
- const parsed = path.parsePathname(trimmed);
182
- while (parsed.length > 1 && parsed[0]?.value === '/') {
183
- parsed.shift();
184
- }
185
- const score = parsed.map(d => {
186
- if (d.type === 'param') {
187
- return 0.5;
188
- }
189
- if (d.type === 'wildcard') {
190
- return 0.25;
191
- }
192
- return 1;
193
- });
194
- return {
195
- child: d,
196
- trimmed,
197
- parsed,
198
- index: i,
199
- score
200
- };
201
- }).sort((a, b) => {
202
- let isIndex = a.trimmed === '/' ? 1 : b.trimmed === '/' ? -1 : 0;
203
- if (isIndex !== 0) return isIndex;
204
- const length = Math.min(a.score.length, b.score.length);
205
-
206
- // Sort by length of score
207
- if (a.score.length !== b.score.length) {
208
- return b.score.length - a.score.length;
209
- }
210
-
211
- // Sort by min available score
212
- for (let i = 0; i < length; i++) {
213
- if (a.score[i] !== b.score[i]) {
214
- return b.score[i] - a.score[i];
215
- }
216
- }
217
-
218
- // Sort by min available parsed value
219
- for (let i = 0; i < length; i++) {
220
- if (a.parsed[i].value !== b.parsed[i].value) {
221
- return a.parsed[i].value > b.parsed[i].value ? 1 : -1;
222
- }
223
- }
224
-
225
- // Sort by length of trimmed full path
226
- if (a.trimmed !== b.trimmed) {
227
- return a.trimmed > b.trimmed ? 1 : -1;
228
- }
229
-
230
- // Sort by original index
231
- return a.index - b.index;
232
- }).map((d, i) => {
233
- d.child.rank = i;
234
- return d.child;
235
- }), [routesByPath]);
236
- const matchRoutes = utils.useStableCallback((pathname, locationSearch, opts) => {
237
- let routeParams = {};
238
- let foundRoute = flatRoutes.find(route => {
239
- const matchedParams = path.matchPathname(basepath, path.trimPathRight(pathname), {
240
- to: route.fullPath,
241
- caseSensitive: route.options.caseSensitive ?? options.caseSensitive,
242
- fuzzy: false
243
- });
244
- if (matchedParams) {
245
- routeParams = matchedParams;
246
- return true;
247
- }
248
- return false;
249
- });
250
- let routeCursor = foundRoute || routesById['__root__'];
251
- let matchedRoutes = [routeCursor];
252
- // let includingLayouts = true
253
- while (routeCursor?.parentRoute) {
254
- routeCursor = routeCursor.parentRoute;
255
- if (routeCursor) matchedRoutes.unshift(routeCursor);
256
- }
257
-
258
- // Existing matches are matches that are already loaded along with
259
- // pending matches that are still loading
260
-
261
- const parseErrors = matchedRoutes.map(route => {
262
- let parsedParamsError;
263
- if (route.options.parseParams) {
264
- try {
265
- const parsedParams = route.options.parseParams(routeParams);
266
- // Add the parsed params to the accumulated params bag
267
- Object.assign(routeParams, parsedParams);
268
- } catch (err) {
269
- parsedParamsError = new PathParamError(err.message, {
270
- cause: err
271
- });
272
- if (opts?.throwOnError) {
273
- throw parsedParamsError;
274
- }
275
- return parsedParamsError;
276
- }
277
- }
278
- return;
279
- });
280
- const matches = matchedRoutes.map((route, index) => {
281
- const interpolatedPath = path.interpolatePath(route.path, routeParams);
282
- const matchId = path.interpolatePath(route.id, routeParams, true);
283
-
284
- // Waste not, want not. If we already have a match for this route,
285
- // reuse it. This is important for layout routes, which might stick
286
- // around between navigation actions that only change leaf routes.
287
- const existingMatch = getRouteMatch(state, matchId);
288
- if (existingMatch) {
289
- return {
290
- ...existingMatch
291
- };
292
- }
293
-
294
- // Create a fresh route match
295
- const hasLoaders = !!(route.options.loader || router.componentTypes.some(d => route.options[d]?.preload));
296
- const routeMatch = {
297
- id: matchId,
298
- routeId: route.id,
299
- params: routeParams,
300
- pathname: path.joinPaths([basepath, interpolatedPath]),
301
- updatedAt: Date.now(),
302
- routeSearch: {},
303
- search: {},
304
- status: hasLoaders ? 'pending' : 'success',
305
- isFetching: false,
306
- invalid: false,
307
- error: undefined,
308
- paramsError: parseErrors[index],
309
- searchError: undefined,
310
- loadPromise: Promise.resolve(),
311
- context: undefined,
312
- abortController: new AbortController(),
313
- shouldReloadDeps: undefined,
314
- fetchedAt: 0
315
- };
316
- return routeMatch;
317
- });
318
-
319
- // Take each match and resolve its search params and context
320
- // This has to happen after the matches are created or found
321
- // so that we can use the parent match's search params and context
322
- matches.forEach((match, i) => {
323
- const parentMatch = matches[i - 1];
324
- const route = looseRoutesById[match.routeId];
325
- const searchInfo = (() => {
326
- // Validate the search params and stabilize them
327
- const parentSearchInfo = {
328
- search: parentMatch?.search ?? locationSearch,
329
- routeSearch: parentMatch?.routeSearch ?? locationSearch
330
- };
331
- try {
332
- const validator = typeof route.options.validateSearch === 'object' ? route.options.validateSearch.parse : route.options.validateSearch;
333
- let routeSearch = validator?.(parentSearchInfo.search) ?? {};
334
- let search = {
335
- ...parentSearchInfo.search,
336
- ...routeSearch
337
- };
338
- routeSearch = utils.replaceEqualDeep(match.routeSearch, routeSearch);
339
- search = utils.replaceEqualDeep(match.search, search);
340
- return {
341
- routeSearch,
342
- search,
343
- searchDidChange: match.routeSearch !== routeSearch
344
- };
345
- } catch (err) {
346
- match.searchError = new SearchParamError(err.message, {
347
- cause: err
348
- });
349
- if (opts?.throwOnError) {
350
- throw match.searchError;
351
- }
352
- return parentSearchInfo;
353
- }
354
- })();
355
- Object.assign(match, searchInfo);
356
- });
357
- return matches;
358
- });
359
- const cancelMatch = utils.useStableCallback(id => {
360
- getRouteMatch(state, id)?.abortController?.abort();
361
- });
362
- const cancelMatches = utils.useStableCallback(state => {
363
- state.matches.forEach(match => {
364
- cancelMatch(match.id);
365
- });
366
- });
367
- const buildLocation = utils.useStableCallback(opts => {
368
- const build = (dest = {}, matches) => {
369
- const from = latestLocationRef.current;
370
- const fromPathname = dest.from ?? from.pathname;
371
- let pathname = resolvePathWithBase(fromPathname, `${dest.to ?? ''}`);
372
- const fromMatches = matchRoutes(fromPathname, from.search);
373
- const stayingMatches = matches?.filter(d => fromMatches?.find(e => e.routeId === d.routeId));
374
- const prevParams = {
375
- ...utils.last(fromMatches)?.params
376
- };
377
- let nextParams = (dest.params ?? true) === true ? prevParams : utils.functionalUpdate(dest.params, prevParams);
378
- if (nextParams) {
379
- matches?.map(d => looseRoutesById[d.routeId].options.stringifyParams).filter(Boolean).forEach(fn => {
380
- nextParams = {
381
- ...nextParams,
382
- ...fn(nextParams)
383
- };
384
- });
385
- }
386
- pathname = path.interpolatePath(pathname, nextParams ?? {});
387
- const preSearchFilters = stayingMatches?.map(match => looseRoutesById[match.routeId].options.preSearchFilters ?? []).flat().filter(Boolean) ?? [];
388
- const postSearchFilters = stayingMatches?.map(match => looseRoutesById[match.routeId].options.postSearchFilters ?? []).flat().filter(Boolean) ?? [];
389
-
390
- // Pre filters first
391
- const preFilteredSearch = preSearchFilters?.length ? preSearchFilters?.reduce((prev, next) => next(prev), from.search) : from.search;
392
-
393
- // Then the link/navigate function
394
- const destSearch = dest.search === true ? preFilteredSearch // Preserve resolvedFrom true
395
- : dest.search ? utils.functionalUpdate(dest.search, preFilteredSearch) ?? {} // Updater
396
- : preSearchFilters?.length ? preFilteredSearch // Preserve resolvedFrom filters
397
- : {};
398
-
399
- // Then post filters
400
- const postFilteredSearch = postSearchFilters?.length ? postSearchFilters.reduce((prev, next) => next(prev), destSearch) : destSearch;
401
- const search = utils.replaceEqualDeep(from.search, postFilteredSearch);
402
- const searchStr = options.stringifySearch(search);
403
- const hash = dest.hash === true ? from.hash : dest.hash ? utils.functionalUpdate(dest.hash, from.hash) : from.hash;
404
- const hashStr = hash ? `#${hash}` : '';
405
- let nextState = dest.state === true ? from.state : dest.state ? utils.functionalUpdate(dest.state, from.state) : from.state;
406
- nextState = utils.replaceEqualDeep(from.state, nextState);
407
- return {
408
- pathname,
409
- search,
410
- searchStr,
411
- state: nextState,
412
- hash,
413
- href: history$1.createHref(`${pathname}${searchStr}${hashStr}`),
414
- unmaskOnReload: dest.unmaskOnReload
415
- };
416
- };
417
- const buildWithMatches = (dest = {}, maskedDest) => {
418
- let next = build(dest);
419
- let maskedNext = maskedDest ? build(maskedDest) : undefined;
420
- if (!maskedNext) {
421
- let params = {};
422
- let foundMask = options.routeMasks?.find(d => {
423
- const match = path.matchPathname(basepath, next.pathname, {
424
- to: d.from,
425
- caseSensitive: false,
426
- fuzzy: false
427
- });
428
- if (match) {
429
- params = match;
430
- return true;
431
- }
432
- return false;
433
- });
434
- if (foundMask) {
435
- foundMask = {
436
- ...foundMask,
437
- from: path.interpolatePath(foundMask.from, params)
438
- };
439
- maskedDest = foundMask;
440
- maskedNext = build(maskedDest);
441
- }
442
- }
443
- const nextMatches = matchRoutes(next.pathname, next.search);
444
- const maskedMatches = maskedNext ? matchRoutes(maskedNext.pathname, maskedNext.search) : undefined;
445
- const maskedFinal = maskedNext ? build(maskedDest, maskedMatches) : undefined;
446
- const final = build(dest, nextMatches);
447
- if (maskedFinal) {
448
- final.maskedLocation = maskedFinal;
449
- }
450
- return final;
451
- };
452
- if (opts.mask) {
453
- return buildWithMatches(opts, {
454
- ...utils.pick(opts, ['from']),
455
- ...opts.mask
456
- });
457
- }
458
- return buildWithMatches(opts);
459
- });
460
- const commitLocation = utils.useStableCallback(async ({
461
- startTransition,
462
- ...next
463
- }) => {
464
- if (navigateTimeoutRef.current) clearTimeout(navigateTimeoutRef.current);
465
- const isSameUrl = latestLocationRef.current.href === next.href;
466
-
467
- // If the next urls are the same and we're not replacing,
468
- // do nothing
469
- if (!isSameUrl || !next.replace) {
470
- let {
471
- maskedLocation,
472
- ...nextHistory
473
- } = next;
474
- if (maskedLocation) {
475
- nextHistory = {
476
- ...maskedLocation,
477
- state: {
478
- ...maskedLocation.state,
479
- __tempKey: undefined,
480
- __tempLocation: {
481
- ...nextHistory,
482
- search: nextHistory.searchStr,
483
- state: {
484
- ...nextHistory.state,
485
- __tempKey: undefined,
486
- __tempLocation: undefined,
487
- key: undefined
488
- }
489
- }
490
- }
491
- };
492
- if (nextHistory.unmaskOnReload ?? options.unmaskOnReload ?? false) {
493
- nextHistory.state.__tempKey = tempLocationKeyRef.current;
494
- }
495
- }
496
- const apply = () => {
497
- history$1[next.replace ? 'replace' : 'push'](nextHistory.href, nextHistory.state);
498
- };
499
- if (startTransition ?? true) {
500
- startReactTransition(apply);
501
- } else {
502
- apply();
503
- }
504
- }
505
- resetNextScrollRef.current = next.resetScroll ?? true;
506
- return latestLoadPromiseRef.current;
507
- });
508
- const buildAndCommitLocation = utils.useStableCallback(({
509
- replace,
510
- resetScroll,
511
- startTransition,
512
- ...rest
513
- } = {}) => {
514
- const location = buildLocation(rest);
515
- return commitLocation({
516
- ...location,
517
- startTransition,
518
- replace,
519
- resetScroll
520
- });
521
- });
522
- const navigate = utils.useStableCallback(({
523
- from,
524
- to = '',
525
- ...rest
526
- }) => {
527
- // If this link simply reloads the current route,
528
- // make sure it has a new key so it will trigger a data refresh
529
-
530
- // If this `to` is a valid external URL, return
531
- // null for LinkUtils
532
- const toString = String(to);
533
- const fromString = typeof from === 'undefined' ? from : String(from);
534
- let isExternal;
535
- try {
536
- new URL(`${toString}`);
537
- isExternal = true;
538
- } catch (e) {}
539
- invariant__default["default"](!isExternal, 'Attempting to navigate to external url with this.navigate!');
540
- return buildAndCommitLocation({
541
- ...rest,
542
- from: fromString,
543
- to: toString
544
- });
545
- });
546
- const loadMatches = utils.useStableCallback(async ({
547
- checkLatest,
548
- matches,
549
- preload
550
- }) => {
551
- let latestPromise;
552
- let firstBadMatchIndex;
553
-
554
- // Check each match middleware to see if the route can be accessed
555
- try {
556
- for (let [index, match] of matches.entries()) {
557
- const parentMatch = matches[index - 1];
558
- const route = looseRoutesById[match.routeId];
559
- const handleError = (err, code) => {
560
- err.routerCode = code;
561
- firstBadMatchIndex = firstBadMatchIndex ?? index;
562
- if (redirects.isRedirect(err)) {
563
- throw err;
564
- }
565
- try {
566
- route.options.onError?.(err);
567
- } catch (errorHandlerErr) {
568
- err = errorHandlerErr;
569
- if (redirects.isRedirect(errorHandlerErr)) {
570
- throw errorHandlerErr;
571
- }
572
- }
573
- matches[index] = match = {
574
- ...match,
575
- error: err,
576
- status: 'error',
577
- updatedAt: Date.now()
578
- };
579
- };
580
- try {
581
- if (match.paramsError) {
582
- handleError(match.paramsError, 'PARSE_PARAMS');
583
- }
584
- if (match.searchError) {
585
- handleError(match.searchError, 'VALIDATE_SEARCH');
586
- }
587
- const parentContext = parentMatch?.context ?? options.context ?? {};
588
- const beforeLoadContext = (await route.options.beforeLoad?.({
589
- search: match.search,
590
- abortController: match.abortController,
591
- params: match.params,
592
- preload: !!preload,
593
- context: parentContext,
594
- location: state.location,
595
- navigate: opts => navigate({
596
- ...opts,
597
- from: match.pathname
598
- }),
599
- buildLocation
600
- })) ?? {};
601
- const context = {
602
- ...parentContext,
603
- ...beforeLoadContext
604
- };
605
- matches[index] = match = {
606
- ...match,
607
- context: utils.replaceEqualDeep(match.context, context)
608
- };
609
- } catch (err) {
610
- handleError(err, 'BEFORE_LOAD');
611
- break;
612
- }
613
- }
614
- } catch (err) {
615
- if (redirects.isRedirect(err)) {
616
- if (!preload) navigate(err);
617
- return matches;
618
- }
619
- throw err;
620
- }
621
- const validResolvedMatches = matches.slice(0, firstBadMatchIndex);
622
- const matchPromises = [];
623
- validResolvedMatches.forEach((match, index) => {
624
- matchPromises.push((async () => {
625
- const parentMatchPromise = matchPromises[index - 1];
626
- const route = looseRoutesById[match.routeId];
627
- const handleIfRedirect = err => {
628
- if (redirects.isRedirect(err)) {
629
- if (!preload) {
630
- navigate(err);
631
- }
632
- return true;
633
- }
634
- return false;
635
- };
636
- let loadPromise;
637
- matches[index] = match = {
638
- ...match,
639
- fetchedAt: Date.now(),
640
- invalid: false
641
- };
642
- if (match.isFetching) {
643
- loadPromise = getRouteMatch(state, match.id)?.loadPromise;
644
- } else {
645
- const cause = state.matches.find(d => d.id === match.id) ? 'stay' : 'enter';
646
- const loaderContext = {
647
- params: match.params,
648
- search: match.search,
649
- preload: !!preload,
650
- parentMatchPromise,
651
- abortController: match.abortController,
652
- context: match.context,
653
- location: state.location,
654
- navigate: opts => navigate({
655
- ...opts,
656
- from: match.pathname
657
- }),
658
- cause
659
- };
660
-
661
- // Default to reloading the route all the time
662
- let shouldReload = true;
663
- let shouldReloadDeps = typeof route.options.shouldReload === 'function' ? route.options.shouldReload?.(loaderContext) : !!route.options.shouldReload;
664
- if (typeof shouldReloadDeps === 'object') {
665
- // compare the deps to see if they've changed
666
- shouldReload = !utils.deepEqual(shouldReloadDeps, match.shouldReloadDeps);
667
- match.shouldReloadDeps = shouldReloadDeps;
668
- } else {
669
- shouldReload = !!shouldReloadDeps;
670
- }
671
-
672
- // If the user doesn't want the route to reload, just
673
- // resolve with the existing loader data
674
-
675
- if (!shouldReload) {
676
- loadPromise = Promise.resolve(match.loaderData);
677
- } else {
678
- // Otherwise, load the route
679
- matches[index] = match = {
680
- ...match,
681
- isFetching: true
682
- };
683
- const componentsPromise = Promise.all(router.componentTypes.map(async type => {
684
- const component = route.options[type];
685
- if (component?.preload) {
686
- await component.preload();
687
- }
688
- }));
689
- const loaderPromise = route.options.loader?.(loaderContext);
690
- loadPromise = Promise.all([componentsPromise, loaderPromise]).then(d => d[1]);
691
- }
692
- }
693
- matches[index] = match = {
694
- ...match,
695
- loadPromise
696
- };
697
- if (!preload) {
698
- setState(s => ({
699
- ...s,
700
- matches: s.matches.map(d => d.id === match.id ? match : d)
701
- }));
702
- }
703
- try {
704
- const loaderData = await loadPromise;
705
- if (latestPromise = checkLatest()) return await latestPromise;
706
- matches[index] = match = {
707
- ...match,
708
- error: undefined,
709
- status: 'success',
710
- isFetching: false,
711
- updatedAt: Date.now(),
712
- loaderData,
713
- loadPromise: undefined
714
- };
715
- } catch (error) {
716
- if (latestPromise = checkLatest()) return await latestPromise;
717
- if (handleIfRedirect(error)) return;
718
- try {
719
- route.options.onError?.(error);
720
- } catch (onErrorError) {
721
- error = onErrorError;
722
- if (handleIfRedirect(onErrorError)) return;
723
- }
724
- matches[index] = match = {
725
- ...match,
726
- error,
727
- status: 'error',
728
- isFetching: false,
729
- updatedAt: Date.now()
730
- };
731
- }
732
- if (!preload) {
733
- setState(s => ({
734
- ...s,
735
- matches: s.matches.map(d => d.id === match.id ? match : d)
736
- }));
737
- }
738
- })());
739
- });
740
- await Promise.all(matchPromises);
741
- return matches;
742
- });
743
- const load = utils.useStableCallback(async () => {
744
- const promise = new Promise(async (resolve, reject) => {
745
- const next = latestLocationRef.current;
746
- const prevLocation = state.resolvedLocation;
747
- const pathDidChange = prevLocation.href !== next.href;
748
- let latestPromise;
749
-
750
- // Cancel any pending matches
751
- cancelMatches(state);
752
- router$1.emit({
753
- type: 'onBeforeLoad',
754
- fromLocation: prevLocation,
755
- toLocation: next,
756
- pathChanged: pathDidChange
757
- });
758
-
759
- // Match the routes
760
- let matches = matchRoutes(next.pathname, next.search, {
761
- debug: true
762
- });
763
- pendingMatchesRef.current = matches;
764
- const previousMatches = state.matches;
765
-
766
- // Ingest the new matches
767
- setState(s => ({
768
- ...s,
769
- status: 'pending',
770
- location: next,
771
- matches
772
- }));
773
- try {
774
- try {
775
- // Load the matches
776
- await loadMatches({
777
- matches,
778
- checkLatest: () => checkLatest(promise)
779
- });
780
- } catch (err) {
781
- // swallow this error, since we'll display the
782
- // errors on the route components
783
- }
784
-
785
- // Only apply the latest transition
786
- if (latestPromise = checkLatest(promise)) {
787
- return latestPromise;
788
- }
789
- const exitingMatchIds = previousMatches.filter(id => !pendingMatchesRef.current.includes(id));
790
- const enteringMatchIds = pendingMatchesRef.current.filter(id => !previousMatches.includes(id));
791
- const stayingMatchIds = previousMatches.filter(id => pendingMatchesRef.current.includes(id))
792
-
793
- // setState((s) => ({
794
- // ...s,
795
- // status: 'idle',
796
- // resolvedLocation: s.location,
797
- // }))
798
-
799
- //
800
- ;
801
- [[exitingMatchIds, 'onLeave'], [enteringMatchIds, 'onEnter'], [stayingMatchIds, 'onTransition']].forEach(([matches, hook]) => {
802
- matches.forEach(match => {
803
- looseRoutesById[match.routeId].options[hook]?.(match);
804
- });
805
- });
806
- router$1.emit({
807
- type: 'onLoad',
808
- fromLocation: prevLocation,
809
- toLocation: next,
810
- pathChanged: pathDidChange
811
- });
812
- resolve();
813
- } catch (err) {
814
- // Only apply the latest transition
815
- if (latestPromise = checkLatest(promise)) {
816
- return latestPromise;
817
- }
818
- reject(err);
819
- }
820
- });
821
- latestLoadPromiseRef.current = promise;
822
- return latestLoadPromiseRef.current;
823
- });
824
- const preloadRoute = utils.useStableCallback(async (navigateOpts = state.location) => {
825
- let next = buildLocation(navigateOpts);
826
- let matches = matchRoutes(next.pathname, next.search, {
827
- throwOnError: true
828
- });
829
- await loadMatches({
830
- matches,
831
- preload: true,
832
- checkLatest: () => undefined
833
- });
834
- return [utils.last(matches), matches];
835
- });
836
- const buildLink = utils.useStableCallback(dest => {
837
- // If this link simply reloads the current route,
838
- // make sure it has a new key so it will trigger a data refresh
839
-
840
- // If this `to` is a valid external URL, return
841
- // null for LinkUtils
842
-
843
- const {
844
- to,
845
- preload: userPreload,
846
- preloadDelay: userPreloadDelay,
847
- activeOptions,
848
- disabled,
849
- target,
850
- replace,
851
- resetScroll,
852
- startTransition
853
- } = dest;
854
- try {
855
- new URL(`${to}`);
856
- return {
857
- type: 'external',
858
- href: to
859
- };
860
- } catch (e) {}
861
- const nextOpts = dest;
862
- const next = buildLocation(nextOpts);
863
- const preload = userPreload ?? options.defaultPreload;
864
- const preloadDelay = userPreloadDelay ?? options.defaultPreloadDelay ?? 0;
865
-
866
- // Compare path/hash for matches
867
- const currentPathSplit = latestLocationRef.current.pathname.split('/');
868
- const nextPathSplit = next.pathname.split('/');
869
- const pathIsFuzzyEqual = nextPathSplit.every((d, i) => d === currentPathSplit[i]);
870
- // Combine the matches based on user options
871
- const pathTest = activeOptions?.exact ? latestLocationRef.current.pathname === next.pathname : pathIsFuzzyEqual;
872
- const hashTest = activeOptions?.includeHash ? latestLocationRef.current.hash === next.hash : true;
873
- const searchTest = activeOptions?.includeSearch ?? true ? utils.deepEqual(latestLocationRef.current.search, next.search, true) : true;
874
-
875
- // The final "active" test
876
- const isActive = pathTest && hashTest && searchTest;
877
-
878
- // The click handler
879
- const handleClick = e => {
880
- if (!disabled && !isCtrlEvent(e) && !e.defaultPrevented && (!target || target === '_self') && e.button === 0) {
881
- e.preventDefault();
882
-
883
- // All is well? Navigate!
884
- commitLocation({
885
- ...next,
886
- replace,
887
- resetScroll,
888
- startTransition
889
- });
890
- }
891
- };
892
-
893
- // The click handler
894
- const handleFocus = e => {
895
- if (preload) {
896
- preloadRoute(nextOpts).catch(err => {
897
- console.warn(err);
898
- console.warn(preloadWarning);
899
- });
900
- }
901
- };
902
- const handleTouchStart = e => {
903
- preloadRoute(nextOpts).catch(err => {
904
- console.warn(err);
905
- console.warn(preloadWarning);
906
- });
907
- };
908
- const handleEnter = e => {
909
- const target = e.target || {};
910
- if (preload) {
911
- if (target.preloadTimeout) {
912
- return;
913
- }
914
- target.preloadTimeout = setTimeout(() => {
915
- target.preloadTimeout = null;
916
- preloadRoute(nextOpts).catch(err => {
917
- console.warn(err);
918
- console.warn(preloadWarning);
919
- });
920
- }, preloadDelay);
921
- }
922
- };
923
- const handleLeave = e => {
924
- const target = e.target || {};
925
- if (target.preloadTimeout) {
926
- clearTimeout(target.preloadTimeout);
927
- target.preloadTimeout = null;
928
- }
929
- };
930
- return {
931
- type: 'internal',
932
- next,
933
- handleFocus,
934
- handleClick,
935
- handleEnter,
936
- handleLeave,
937
- handleTouchStart,
938
- isActive,
939
- disabled
940
- };
941
- });
942
- React__namespace.useLayoutEffect(() => {
943
- const unsub = history$1.subscribe(() => {
944
- latestLocationRef.current = parseLocation(latestLocationRef.current);
945
- if (state.location !== latestLocationRef.current) {
946
- startReactTransition(() => {
947
- try {
948
- load();
949
- } catch (err) {
950
- console.error(err);
951
- }
952
- });
953
- }
954
- });
955
- const nextLocation = buildLocation({
956
- search: true,
957
- params: true,
958
- hash: true,
959
- state: true
960
- });
961
- if (state.location.href !== nextLocation.href) {
962
- commitLocation({
963
- ...nextLocation,
964
- replace: true
965
- });
966
- }
967
- return () => {
968
- unsub();
969
- };
970
- }, [history$1]);
971
- React__namespace.useLayoutEffect(() => {
972
- startReactTransition(() => {
973
- try {
974
- load();
975
- } catch (err) {
976
- console.error(err);
977
- }
978
- });
979
- }, []);
980
- const matchRoute = utils.useStableCallback((location, opts) => {
981
- location = {
982
- ...location,
983
- to: location.to ? resolvePathWithBase(location.from || '', location.to) : undefined
984
- };
985
- const next = buildLocation(location);
986
- if (opts?.pending && state.status !== 'pending') {
987
- return false;
988
- }
989
- const baseLocation = opts?.pending ? latestLocationRef.current : state.resolvedLocation;
990
-
991
- // const baseLocation = state.resolvedLocation
992
-
993
- if (!baseLocation) {
994
- return false;
995
- }
996
- const match = path.matchPathname(basepath, baseLocation.pathname, {
997
- ...opts,
998
- to: next.pathname
999
- });
1000
- if (!match) {
1001
- return false;
1002
- }
1003
- if (match && (opts?.includeSearch ?? true)) {
1004
- return utils.deepEqual(baseLocation.search, next.search, true) ? match : false;
1005
- }
1006
- return match;
1007
- });
1008
- const routerContextValue = {
1009
- routeTree: router$1.routeTree,
1010
- navigate,
1011
- buildLink,
1012
- state,
1013
- matchRoute,
1014
- routesById,
1015
- options,
1016
- history: history$1,
1017
- load,
1018
- buildLocation,
1019
- subscribe: router$1.subscribe,
1020
- resetNextScrollRef
1021
- };
1022
- return /*#__PURE__*/React__namespace.createElement(routerContext.Provider, {
1023
- value: routerContextValue
1024
- }, /*#__PURE__*/React__namespace.createElement(Matches.Matches, null));
1025
- }
1026
- function getRouteMatch(state, id) {
1027
- return [...state.pendingMatches, ...state.matches].find(d => d.id === id);
1028
- }
1029
- function useRouterState(opts) {
1030
- const {
1031
- state
1032
- } = useRouter();
1033
- // return useStore(router.__store, opts?.select as any)
1034
- return opts?.select ? opts.select(state) : state;
1035
- }
1036
- function useRouter() {
1037
- const resolvedContext = window.__TSR_ROUTER_CONTEXT__ || routerContext;
1038
- const value = React__namespace.useContext(resolvedContext);
1039
- warning__default["default"](value, 'useRouter must be used inside a <RouterProvider> component!');
1040
- return value;
1041
- }
1042
-
1043
- exports.PathParamError = PathParamError;
1044
- exports.RouterProvider = RouterProvider;
1045
- exports.SearchParamError = SearchParamError;
1046
- exports.getInitialRouterState = getInitialRouterState;
1047
- exports.getRouteMatch = getRouteMatch;
1048
- exports.routerContext = routerContext;
1049
- exports.useRouter = useRouter;
1050
- exports.useRouterState = useRouterState;
1051
- //# sourceMappingURL=RouterProvider.js.map