@tanstack/react-router 0.0.1-beta.223 → 0.0.1-beta.225

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