@tanstack/react-router 0.0.1-beta.21 → 0.0.1-beta.211

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