@tanstack/react-router 0.0.1-beta.23 → 0.0.1-beta.231

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