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