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

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 +1021 -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 +1895 -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 +2132 -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,1021 @@
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
+ // TODO: This might need to be latestLocationRef.current...?
584
+ navigate: opts => navigate({
585
+ ...opts,
586
+ from: match.pathname
587
+ }),
588
+ buildLocation
589
+ })) ?? {};
590
+ const context = {
591
+ ...parentContext,
592
+ ...beforeLoadContext
593
+ };
594
+ matches[index] = match = {
595
+ ...match,
596
+ context: utils.replaceEqualDeep(match.context, context)
597
+ };
598
+ } catch (err) {
599
+ handleError(err, 'BEFORE_LOAD');
600
+ break;
601
+ }
602
+ }
603
+ } catch (err) {
604
+ if (redirects.isRedirect(err)) {
605
+ if (!preload) navigate(err);
606
+ return matches;
607
+ }
608
+ throw err;
609
+ }
610
+ const validResolvedMatches = matches.slice(0, firstBadMatchIndex);
611
+ const matchPromises = [];
612
+ validResolvedMatches.forEach((match, index) => {
613
+ matchPromises.push((async () => {
614
+ const parentMatchPromise = matchPromises[index - 1];
615
+ const route = looseRoutesById[match.routeId];
616
+ if (match.isFetching) {
617
+ return getRouteMatch(state, match.id)?.loadPromise;
618
+ }
619
+ const handleIfRedirect = err => {
620
+ if (redirects.isRedirect(err)) {
621
+ if (!preload) {
622
+ navigate(err);
623
+ }
624
+ return true;
625
+ }
626
+ return false;
627
+ };
628
+ const load = async () => {
629
+ try {
630
+ const componentsPromise = Promise.all(router.componentTypes.map(async type => {
631
+ const component = route.options[type];
632
+ if (component?.preload) {
633
+ await component.preload();
634
+ }
635
+ }));
636
+ const loaderPromise = route.options.load?.({
637
+ params: match.params,
638
+ search: match.search,
639
+ preload: !!preload,
640
+ parentMatchPromise,
641
+ abortController: match.abortController,
642
+ context: match.context,
643
+ location: state.location,
644
+ navigate: opts => navigate({
645
+ ...opts,
646
+ from: match.pathname
647
+ })
648
+ });
649
+ const [_, loaderContext] = await Promise.all([componentsPromise, loaderPromise]);
650
+ if (latestPromise = checkLatest()) return await latestPromise;
651
+ matches[index] = match = {
652
+ ...match,
653
+ error: undefined,
654
+ status: 'success',
655
+ isFetching: false,
656
+ updatedAt: Date.now()
657
+ };
658
+ } catch (error) {
659
+ if (latestPromise = checkLatest()) return await latestPromise;
660
+ if (handleIfRedirect(error)) return;
661
+ try {
662
+ route.options.onError?.(error);
663
+ } catch (onErrorError) {
664
+ error = onErrorError;
665
+ if (handleIfRedirect(onErrorError)) return;
666
+ }
667
+ matches[index] = match = {
668
+ ...match,
669
+ error,
670
+ status: 'error',
671
+ isFetching: false,
672
+ updatedAt: Date.now()
673
+ };
674
+ }
675
+ if (!preload) {
676
+ setState(s => ({
677
+ ...s,
678
+ matches: s.matches.map(d => d.id === match.id ? match : d)
679
+ }));
680
+ }
681
+ };
682
+ let loadPromise;
683
+ matches[index] = match = {
684
+ ...match,
685
+ isFetching: true,
686
+ fetchedAt: Date.now(),
687
+ invalid: false
688
+ };
689
+ loadPromise = load();
690
+ matches[index] = match = {
691
+ ...match,
692
+ loadPromise
693
+ };
694
+ await loadPromise;
695
+ })());
696
+ });
697
+ await Promise.all(matchPromises);
698
+ return matches;
699
+ });
700
+ const load = utils.useStableCallback(async () => {
701
+ const promise = new Promise(async (resolve, reject) => {
702
+ const next = latestLocationRef.current;
703
+ const prevLocation = state.resolvedLocation || state.location;
704
+ const pathDidChange = !!(next && prevLocation.href !== next.href);
705
+ let latestPromise;
706
+
707
+ // Cancel any pending matches
708
+ cancelMatches(state);
709
+ router$1.emit({
710
+ type: 'onBeforeLoad',
711
+ from: prevLocation,
712
+ to: next ?? state.location,
713
+ pathChanged: pathDidChange
714
+ });
715
+
716
+ // Match the routes
717
+ let matches = matchRoutes(next.pathname, next.search, {
718
+ debug: true
719
+ });
720
+
721
+ // Ingest the new matches
722
+ setState(s => ({
723
+ ...s,
724
+ matches
725
+ }));
726
+ try {
727
+ try {
728
+ // Load the matches
729
+ await loadMatches({
730
+ matches,
731
+ checkLatest: () => checkLatest(promise)
732
+ });
733
+ } catch (err) {
734
+ // swallow this error, since we'll display the
735
+ // errors on the route components
736
+ }
737
+
738
+ // Only apply the latest transition
739
+ if (latestPromise = checkLatest(promise)) {
740
+ return latestPromise;
741
+ }
742
+
743
+ // TODO:
744
+ // const exitingMatchIds = previousMatches.filter(
745
+ // (id) => !state.pendingMatches.includes(id),
746
+ // )
747
+ // const enteringMatchIds = state.pendingMatches.filter(
748
+ // (id) => !previousMatches.includes(id),
749
+ // )
750
+ // const stayingMatchIds = previousMatches.filter((id) =>
751
+ // state.pendingMatches.includes(id),
752
+ // )
753
+
754
+ // setState((s) => ({
755
+ // ...s,
756
+ // status: 'idle',
757
+ // resolvedLocation: s.location,
758
+ // }))
759
+
760
+ // TODO:
761
+ // ;(
762
+ // [
763
+ // [exitingMatchIds, 'onLeave'],
764
+ // [enteringMatchIds, 'onEnter'],
765
+ // [stayingMatchIds, 'onTransition'],
766
+ // ] as const
767
+ // ).forEach(([matches, hook]) => {
768
+ // matches.forEach((match) => {
769
+ // const route = this.getRoute(match.routeId)
770
+ // route.options[hook]?.(match)
771
+ // })
772
+ // })
773
+ router$1.emit({
774
+ type: 'onLoad',
775
+ from: prevLocation,
776
+ to: next,
777
+ pathChanged: pathDidChange
778
+ });
779
+ resolve();
780
+ } catch (err) {
781
+ // Only apply the latest transition
782
+ if (latestPromise = checkLatest(promise)) {
783
+ return latestPromise;
784
+ }
785
+ reject(err);
786
+ }
787
+ });
788
+ latestLoadPromiseRef.current = promise;
789
+ return latestLoadPromiseRef.current;
790
+ });
791
+ const preloadRoute = utils.useStableCallback(async (navigateOpts = state.location) => {
792
+ let next = buildLocation(navigateOpts);
793
+ let matches = matchRoutes(next.pathname, next.search, {
794
+ throwOnError: true
795
+ });
796
+ await loadMatches({
797
+ matches,
798
+ preload: true,
799
+ checkLatest: () => undefined
800
+ });
801
+ return [utils.last(matches), matches];
802
+ });
803
+ const buildLink = utils.useStableCallback(dest => {
804
+ // If this link simply reloads the current route,
805
+ // make sure it has a new key so it will trigger a data refresh
806
+
807
+ // If this `to` is a valid external URL, return
808
+ // null for LinkUtils
809
+
810
+ const {
811
+ to,
812
+ preload: userPreload,
813
+ preloadDelay: userPreloadDelay,
814
+ activeOptions,
815
+ disabled,
816
+ target,
817
+ replace,
818
+ resetScroll,
819
+ startTransition
820
+ } = dest;
821
+ try {
822
+ new URL(`${to}`);
823
+ return {
824
+ type: 'external',
825
+ href: to
826
+ };
827
+ } catch (e) {}
828
+ const nextOpts = dest;
829
+ const next = buildLocation(nextOpts);
830
+ const preload = userPreload ?? options.defaultPreload;
831
+ const preloadDelay = userPreloadDelay ?? options.defaultPreloadDelay ?? 0;
832
+
833
+ // Compare path/hash for matches
834
+ const currentPathSplit = latestLocationRef.current.pathname.split('/');
835
+ const nextPathSplit = next.pathname.split('/');
836
+ const pathIsFuzzyEqual = nextPathSplit.every((d, i) => d === currentPathSplit[i]);
837
+ // Combine the matches based on user options
838
+ const pathTest = activeOptions?.exact ? latestLocationRef.current.pathname === next.pathname : pathIsFuzzyEqual;
839
+ const hashTest = activeOptions?.includeHash ? latestLocationRef.current.hash === next.hash : true;
840
+ const searchTest = activeOptions?.includeSearch ?? true ? utils.partialDeepEqual(latestLocationRef.current.search, next.search) : true;
841
+
842
+ // The final "active" test
843
+ const isActive = pathTest && hashTest && searchTest;
844
+
845
+ // The click handler
846
+ const handleClick = e => {
847
+ if (!disabled && !isCtrlEvent(e) && !e.defaultPrevented && (!target || target === '_self') && e.button === 0) {
848
+ e.preventDefault();
849
+
850
+ // All is well? Navigate!
851
+ commitLocation({
852
+ ...next,
853
+ replace,
854
+ resetScroll,
855
+ startTransition
856
+ });
857
+ }
858
+ };
859
+
860
+ // The click handler
861
+ const handleFocus = e => {
862
+ if (preload) {
863
+ preloadRoute(nextOpts).catch(err => {
864
+ console.warn(err);
865
+ console.warn(preloadWarning);
866
+ });
867
+ }
868
+ };
869
+ const handleTouchStart = e => {
870
+ preloadRoute(nextOpts).catch(err => {
871
+ console.warn(err);
872
+ console.warn(preloadWarning);
873
+ });
874
+ };
875
+ const handleEnter = e => {
876
+ const target = e.target || {};
877
+ if (preload) {
878
+ if (target.preloadTimeout) {
879
+ return;
880
+ }
881
+ target.preloadTimeout = setTimeout(() => {
882
+ target.preloadTimeout = null;
883
+ preloadRoute(nextOpts).catch(err => {
884
+ console.warn(err);
885
+ console.warn(preloadWarning);
886
+ });
887
+ }, preloadDelay);
888
+ }
889
+ };
890
+ const handleLeave = e => {
891
+ const target = e.target || {};
892
+ if (target.preloadTimeout) {
893
+ clearTimeout(target.preloadTimeout);
894
+ target.preloadTimeout = null;
895
+ }
896
+ };
897
+ return {
898
+ type: 'internal',
899
+ next,
900
+ handleFocus,
901
+ handleClick,
902
+ handleEnter,
903
+ handleLeave,
904
+ handleTouchStart,
905
+ isActive,
906
+ disabled
907
+ };
908
+ });
909
+ const latestLocationRef = React__namespace.useRef(state.location);
910
+ React__namespace.useLayoutEffect(() => {
911
+ const unsub = history$1.subscribe(() => {
912
+ latestLocationRef.current = parseLocation(latestLocationRef.current);
913
+ setState(s => ({
914
+ ...s,
915
+ status: 'pending'
916
+ }));
917
+ if (state.location !== latestLocationRef.current) {
918
+ try {
919
+ load();
920
+ } catch (err) {
921
+ console.error(err);
922
+ }
923
+ }
924
+ });
925
+ const nextLocation = buildLocation({
926
+ search: true,
927
+ params: true,
928
+ hash: true,
929
+ state: true
930
+ });
931
+ if (state.location.href !== nextLocation.href) {
932
+ commitLocation({
933
+ ...nextLocation,
934
+ replace: true
935
+ });
936
+ }
937
+ return () => {
938
+ unsub();
939
+ };
940
+ }, [history$1]);
941
+ const initialLoad = React__namespace.useRef(true);
942
+ if (initialLoad.current) {
943
+ initialLoad.current = false;
944
+ startReactTransition(() => {
945
+ try {
946
+ load();
947
+ } catch (err) {
948
+ console.error(err);
949
+ }
950
+ });
951
+ }
952
+ const matchRoute = utils.useStableCallback((location, opts) => {
953
+ location = {
954
+ ...location,
955
+ to: location.to ? resolvePathWithBase(location.from || '', location.to) : undefined
956
+ };
957
+ const next = buildLocation(location);
958
+ if (opts?.pending && state.status !== 'pending') {
959
+ return false;
960
+ }
961
+ const baseLocation = opts?.pending ? latestLocationRef.current : state.resolvedLocation;
962
+
963
+ // const baseLocation = state.resolvedLocation
964
+
965
+ if (!baseLocation) {
966
+ return false;
967
+ }
968
+ const match = path.matchPathname(basepath, baseLocation.pathname, {
969
+ ...opts,
970
+ to: next.pathname
971
+ });
972
+ if (!match) {
973
+ return false;
974
+ }
975
+ if (match && (opts?.includeSearch ?? true)) {
976
+ return utils.partialDeepEqual(baseLocation.search, next.search) ? match : false;
977
+ }
978
+ return match;
979
+ });
980
+ const routerContextValue = {
981
+ routeTree: router$1.routeTree,
982
+ navigate,
983
+ buildLink,
984
+ state,
985
+ matchRoute,
986
+ routesById,
987
+ options,
988
+ history: history$1,
989
+ load,
990
+ buildLocation
991
+ };
992
+ return /*#__PURE__*/React__namespace.createElement(routerContext.Provider, {
993
+ value: routerContextValue
994
+ }, /*#__PURE__*/React__namespace.createElement(Matches.Matches, null));
995
+ }
996
+ function getRouteMatch(state, id) {
997
+ return [...state.pendingMatches, ...state.matches].find(d => d.id === id);
998
+ }
999
+ function useRouterState(opts) {
1000
+ const {
1001
+ state
1002
+ } = useRouter();
1003
+ // return useStore(router.__store, opts?.select as any)
1004
+ return opts?.select ? opts.select(state) : state;
1005
+ }
1006
+ function useRouter() {
1007
+ const resolvedContext = window.__TSR_ROUTER_CONTEXT__ || routerContext;
1008
+ const value = React__namespace.useContext(resolvedContext);
1009
+ warning__default["default"](value, 'useRouter must be used inside a <RouterProvider> component!');
1010
+ return value;
1011
+ }
1012
+
1013
+ exports.PathParamError = PathParamError;
1014
+ exports.RouterProvider = RouterProvider;
1015
+ exports.SearchParamError = SearchParamError;
1016
+ exports.getInitialRouterState = getInitialRouterState;
1017
+ exports.getRouteMatch = getRouteMatch;
1018
+ exports.routerContext = routerContext;
1019
+ exports.useRouter = useRouter;
1020
+ exports.useRouterState = useRouterState;
1021
+ //# sourceMappingURL=RouterProvider.js.map