@tanstack/react-router 0.0.1-beta.18 → 0.0.1-beta.181

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.
@@ -1,5 +1,5 @@
1
1
  /**
2
- * react-router
2
+ * @tanstack/react-router/src/index.tsx
3
3
  *
4
4
  * Copyright (c) TanStack
5
5
  *
@@ -8,2822 +8,639 @@
8
8
  *
9
9
  * @license MIT
10
10
  */
11
+ import { useStore } from '@tanstack/react-store';
12
+ export { useStore } from '@tanstack/react-store';
13
+ import { Route, functionalUpdate, rootRouteId, last, pick, watchScrollPositions, restoreScrollPositions, isDehydratedDeferred } from '@tanstack/router-core';
14
+ export * from '@tanstack/router-core';
11
15
  import * as React from 'react';
12
- import { useSyncExternalStore } from 'use-sync-external-store/shim';
13
- export { lazyWithPreload as lazy } from 'react-lazy-with-preload/lib/index';
16
+ import invariant from 'tiny-invariant';
17
+ import warning from 'tiny-warning';
14
18
 
15
- function _extends$2() {
16
- _extends$2 = Object.assign ? Object.assign.bind() : function (target) {
17
- for (var i = 1; i < arguments.length; i++) {
18
- var source = arguments[i];
19
-
20
- for (var key in source) {
21
- if (Object.prototype.hasOwnProperty.call(source, key)) {
22
- target[key] = source[key];
23
- }
24
- }
25
- }
26
-
27
- return target;
28
- };
29
- return _extends$2.apply(this, arguments);
30
- }
31
-
32
- function _objectWithoutPropertiesLoose(source, excluded) {
33
- if (source == null) return {};
34
- var target = {};
35
- var sourceKeys = Object.keys(source);
36
- var key, i;
37
-
38
- for (i = 0; i < sourceKeys.length; i++) {
39
- key = sourceKeys[i];
40
- if (excluded.indexOf(key) >= 0) continue;
41
- target[key] = source[key];
42
- }
43
-
44
- return target;
45
- }
46
-
47
- /**
48
- * router-core
49
- *
50
- * Copyright (c) TanStack
51
- *
52
- * This source code is licensed under the MIT license found in the
53
- * LICENSE.md file in the root directory of this source tree.
54
- *
55
- * @license MIT
56
- */
57
- function _extends$1() {
58
- _extends$1 = Object.assign ? Object.assign.bind() : function (target) {
59
- for (var i = 1; i < arguments.length; i++) {
60
- var source = arguments[i];
61
-
62
- for (var key in source) {
63
- if (Object.prototype.hasOwnProperty.call(source, key)) {
64
- target[key] = source[key];
65
- }
66
- }
67
- }
68
-
69
- return target;
70
- };
71
- return _extends$1.apply(this, arguments);
72
- }
73
-
74
- /**
75
- * Actions represent the type of change to a location value.
76
- *
77
- * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#action
78
- */
79
- var Action;
80
-
81
- (function (Action) {
82
- /**
83
- * A POP indicates a change to an arbitrary index in the history stack, such
84
- * as a back or forward navigation. It does not describe the direction of the
85
- * navigation, only that the current index changed.
86
- *
87
- * Note: This is the default action for newly created history objects.
88
- */
89
- Action["Pop"] = "POP";
90
- /**
91
- * A PUSH indicates a new entry being added to the history stack, such as when
92
- * a link is clicked and a new page loads. When this happens, all subsequent
93
- * entries in the stack are lost.
94
- */
95
-
96
- Action["Push"] = "PUSH";
97
- /**
98
- * A REPLACE indicates the entry at the current index in the history stack
99
- * being replaced by a new one.
100
- */
101
-
102
- Action["Replace"] = "REPLACE";
103
- })(Action || (Action = {}));
104
-
105
- var readOnly = process.env.NODE_ENV !== "production" ? function (obj) {
106
- return Object.freeze(obj);
107
- } : function (obj) {
108
- return obj;
109
- };
110
-
111
- function warning$1(cond, message) {
112
- if (!cond) {
113
- // eslint-disable-next-line no-console
114
- if (typeof console !== 'undefined') console.warn(message);
115
-
116
- try {
117
- // Welcome to debugging history!
118
- //
119
- // This error is thrown as a convenience so you can more easily
120
- // find the source for a warning that appears in the console by
121
- // enabling "pause on exceptions" in your JavaScript debugger.
122
- throw new Error(message); // eslint-disable-next-line no-empty
123
- } catch (e) {}
124
- }
125
- }
126
-
127
- var BeforeUnloadEventType = 'beforeunload';
128
- var HashChangeEventType = 'hashchange';
129
- var PopStateEventType = 'popstate';
130
- /**
131
- * Browser history stores the location in regular URLs. This is the standard for
132
- * most web apps, but it requires some configuration on the server to ensure you
133
- * serve the same app at multiple URLs.
134
- *
135
- * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#createbrowserhistory
136
- */
137
-
138
- function createBrowserHistory(options) {
139
- if (options === void 0) {
140
- options = {};
141
- }
142
-
143
- var _options = options,
144
- _options$window = _options.window,
145
- window = _options$window === void 0 ? document.defaultView : _options$window;
146
- var globalHistory = window.history;
147
-
148
- function getIndexAndLocation() {
149
- var _window$location = window.location,
150
- pathname = _window$location.pathname,
151
- search = _window$location.search,
152
- hash = _window$location.hash;
153
- var state = globalHistory.state || {};
154
- return [state.idx, readOnly({
155
- pathname: pathname,
156
- search: search,
157
- hash: hash,
158
- state: state.usr || null,
159
- key: state.key || 'default'
160
- })];
161
- }
162
-
163
- var blockedPopTx = null;
164
-
165
- function handlePop() {
166
- if (blockedPopTx) {
167
- blockers.call(blockedPopTx);
168
- blockedPopTx = null;
169
- } else {
170
- var nextAction = Action.Pop;
171
-
172
- var _getIndexAndLocation = getIndexAndLocation(),
173
- nextIndex = _getIndexAndLocation[0],
174
- nextLocation = _getIndexAndLocation[1];
175
-
176
- if (blockers.length) {
177
- if (nextIndex != null) {
178
- var delta = index - nextIndex;
179
-
180
- if (delta) {
181
- // Revert the POP
182
- blockedPopTx = {
183
- action: nextAction,
184
- location: nextLocation,
185
- retry: function retry() {
186
- go(delta * -1);
187
- }
188
- };
189
- go(delta);
190
- }
191
- } else {
192
- // Trying to POP to a location with no index. We did not create
193
- // this location, so we can't effectively block the navigation.
194
- process.env.NODE_ENV !== "production" ? warning$1(false, // TODO: Write up a doc that explains our blocking strategy in
195
- // detail and link to it here so people can understand better what
196
- // is going on and how to avoid it.
197
- "You are trying to block a POP navigation to a location that was not " + "created by the history library. The block will fail silently in " + "production, but in general you should do all navigation with the " + "history library (instead of using window.history.pushState directly) " + "to avoid this situation.") : void 0;
198
- }
199
- } else {
200
- applyTx(nextAction);
201
- }
202
- }
203
- }
204
-
205
- window.addEventListener(PopStateEventType, handlePop);
206
- var action = Action.Pop;
207
-
208
- var _getIndexAndLocation2 = getIndexAndLocation(),
209
- index = _getIndexAndLocation2[0],
210
- location = _getIndexAndLocation2[1];
211
-
212
- var listeners = createEvents();
213
- var blockers = createEvents();
214
-
215
- if (index == null) {
216
- index = 0;
217
- globalHistory.replaceState(_extends$1({}, globalHistory.state, {
218
- idx: index
219
- }), '');
220
- }
221
-
222
- function createHref(to) {
223
- return typeof to === 'string' ? to : createPath(to);
224
- } // state defaults to `null` because `window.history.state` does
225
-
226
-
227
- function getNextLocation(to, state) {
228
- if (state === void 0) {
229
- state = null;
230
- }
231
-
232
- return readOnly(_extends$1({
233
- pathname: location.pathname,
234
- hash: '',
235
- search: ''
236
- }, typeof to === 'string' ? parsePath(to) : to, {
237
- state: state,
238
- key: createKey()
239
- }));
240
- }
241
-
242
- function getHistoryStateAndUrl(nextLocation, index) {
243
- return [{
244
- usr: nextLocation.state,
245
- key: nextLocation.key,
246
- idx: index
247
- }, createHref(nextLocation)];
248
- }
249
-
250
- function allowTx(action, location, retry) {
251
- return !blockers.length || (blockers.call({
252
- action: action,
253
- location: location,
254
- retry: retry
255
- }), false);
256
- }
257
-
258
- function applyTx(nextAction) {
259
- action = nextAction;
260
-
261
- var _getIndexAndLocation3 = getIndexAndLocation();
262
-
263
- index = _getIndexAndLocation3[0];
264
- location = _getIndexAndLocation3[1];
265
- listeners.call({
266
- action: action,
267
- location: location
268
- });
269
- }
270
-
271
- function push(to, state) {
272
- var nextAction = Action.Push;
273
- var nextLocation = getNextLocation(to, state);
274
-
275
- function retry() {
276
- push(to, state);
277
- }
278
-
279
- if (allowTx(nextAction, nextLocation, retry)) {
280
- var _getHistoryStateAndUr = getHistoryStateAndUrl(nextLocation, index + 1),
281
- historyState = _getHistoryStateAndUr[0],
282
- url = _getHistoryStateAndUr[1]; // TODO: Support forced reloading
283
- // try...catch because iOS limits us to 100 pushState calls :/
284
-
285
-
286
- try {
287
- globalHistory.pushState(historyState, '', url);
288
- } catch (error) {
289
- // They are going to lose state here, but there is no real
290
- // way to warn them about it since the page will refresh...
291
- window.location.assign(url);
292
- }
293
-
294
- applyTx(nextAction);
295
- }
296
- }
297
-
298
- function replace(to, state) {
299
- var nextAction = Action.Replace;
300
- var nextLocation = getNextLocation(to, state);
301
-
302
- function retry() {
303
- replace(to, state);
304
- }
305
-
306
- if (allowTx(nextAction, nextLocation, retry)) {
307
- var _getHistoryStateAndUr2 = getHistoryStateAndUrl(nextLocation, index),
308
- historyState = _getHistoryStateAndUr2[0],
309
- url = _getHistoryStateAndUr2[1]; // TODO: Support forced reloading
310
-
311
-
312
- globalHistory.replaceState(historyState, '', url);
313
- applyTx(nextAction);
314
- }
315
- }
316
-
317
- function go(delta) {
318
- globalHistory.go(delta);
319
- }
320
-
321
- var history = {
322
- get action() {
323
- return action;
324
- },
325
-
326
- get location() {
327
- return location;
328
- },
329
-
330
- createHref: createHref,
331
- push: push,
332
- replace: replace,
333
- go: go,
334
- back: function back() {
335
- go(-1);
336
- },
337
- forward: function forward() {
338
- go(1);
339
- },
340
- listen: function listen(listener) {
341
- return listeners.push(listener);
342
- },
343
- block: function block(blocker) {
344
- var unblock = blockers.push(blocker);
345
-
346
- if (blockers.length === 1) {
347
- window.addEventListener(BeforeUnloadEventType, promptBeforeUnload);
348
- }
349
-
350
- return function () {
351
- unblock(); // Remove the beforeunload listener so the document may
352
- // still be salvageable in the pagehide event.
353
- // See https://html.spec.whatwg.org/#unloading-documents
354
-
355
- if (!blockers.length) {
356
- window.removeEventListener(BeforeUnloadEventType, promptBeforeUnload);
357
- }
358
- };
359
- }
360
- };
361
- return history;
362
- }
363
- /**
364
- * Hash history stores the location in window.location.hash. This makes it ideal
365
- * for situations where you don't want to send the location to the server for
366
- * some reason, either because you do cannot configure it or the URL space is
367
- * reserved for something else.
368
- *
369
- * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#createhashhistory
370
- */
371
-
372
- function createHashHistory(options) {
373
- if (options === void 0) {
374
- options = {};
375
- }
376
-
377
- var _options2 = options,
378
- _options2$window = _options2.window,
379
- window = _options2$window === void 0 ? document.defaultView : _options2$window;
380
- var globalHistory = window.history;
381
-
382
- function getIndexAndLocation() {
383
- var _parsePath = parsePath(window.location.hash.substr(1)),
384
- _parsePath$pathname = _parsePath.pathname,
385
- pathname = _parsePath$pathname === void 0 ? '/' : _parsePath$pathname,
386
- _parsePath$search = _parsePath.search,
387
- search = _parsePath$search === void 0 ? '' : _parsePath$search,
388
- _parsePath$hash = _parsePath.hash,
389
- hash = _parsePath$hash === void 0 ? '' : _parsePath$hash;
390
-
391
- var state = globalHistory.state || {};
392
- return [state.idx, readOnly({
393
- pathname: pathname,
394
- search: search,
395
- hash: hash,
396
- state: state.usr || null,
397
- key: state.key || 'default'
398
- })];
399
- }
400
-
401
- var blockedPopTx = null;
402
-
403
- function handlePop() {
404
- if (blockedPopTx) {
405
- blockers.call(blockedPopTx);
406
- blockedPopTx = null;
407
- } else {
408
- var nextAction = Action.Pop;
409
-
410
- var _getIndexAndLocation4 = getIndexAndLocation(),
411
- nextIndex = _getIndexAndLocation4[0],
412
- nextLocation = _getIndexAndLocation4[1];
413
-
414
- if (blockers.length) {
415
- if (nextIndex != null) {
416
- var delta = index - nextIndex;
417
-
418
- if (delta) {
419
- // Revert the POP
420
- blockedPopTx = {
421
- action: nextAction,
422
- location: nextLocation,
423
- retry: function retry() {
424
- go(delta * -1);
425
- }
426
- };
427
- go(delta);
428
- }
429
- } else {
430
- // Trying to POP to a location with no index. We did not create
431
- // this location, so we can't effectively block the navigation.
432
- process.env.NODE_ENV !== "production" ? warning$1(false, // TODO: Write up a doc that explains our blocking strategy in
433
- // detail and link to it here so people can understand better
434
- // what is going on and how to avoid it.
435
- "You are trying to block a POP navigation to a location that was not " + "created by the history library. The block will fail silently in " + "production, but in general you should do all navigation with the " + "history library (instead of using window.history.pushState directly) " + "to avoid this situation.") : void 0;
436
- }
437
- } else {
438
- applyTx(nextAction);
439
- }
440
- }
441
- }
442
-
443
- window.addEventListener(PopStateEventType, handlePop); // popstate does not fire on hashchange in IE 11 and old (trident) Edge
444
- // https://developer.mozilla.org/de/docs/Web/API/Window/popstate_event
445
-
446
- window.addEventListener(HashChangeEventType, function () {
447
- var _getIndexAndLocation5 = getIndexAndLocation(),
448
- nextLocation = _getIndexAndLocation5[1]; // Ignore extraneous hashchange events.
449
-
450
-
451
- if (createPath(nextLocation) !== createPath(location)) {
452
- handlePop();
453
- }
454
- });
455
- var action = Action.Pop;
456
-
457
- var _getIndexAndLocation6 = getIndexAndLocation(),
458
- index = _getIndexAndLocation6[0],
459
- location = _getIndexAndLocation6[1];
460
-
461
- var listeners = createEvents();
462
- var blockers = createEvents();
463
-
464
- if (index == null) {
465
- index = 0;
466
- globalHistory.replaceState(_extends$1({}, globalHistory.state, {
467
- idx: index
468
- }), '');
469
- }
470
-
471
- function getBaseHref() {
472
- var base = document.querySelector('base');
473
- var href = '';
474
-
475
- if (base && base.getAttribute('href')) {
476
- var url = window.location.href;
477
- var hashIndex = url.indexOf('#');
478
- href = hashIndex === -1 ? url : url.slice(0, hashIndex);
479
- }
480
-
481
- return href;
482
- }
483
-
484
- function createHref(to) {
485
- return getBaseHref() + '#' + (typeof to === 'string' ? to : createPath(to));
486
- }
487
-
488
- function getNextLocation(to, state) {
489
- if (state === void 0) {
490
- state = null;
491
- }
492
-
493
- return readOnly(_extends$1({
494
- pathname: location.pathname,
495
- hash: '',
496
- search: ''
497
- }, typeof to === 'string' ? parsePath(to) : to, {
498
- state: state,
499
- key: createKey()
500
- }));
501
- }
502
-
503
- function getHistoryStateAndUrl(nextLocation, index) {
504
- return [{
505
- usr: nextLocation.state,
506
- key: nextLocation.key,
507
- idx: index
508
- }, createHref(nextLocation)];
509
- }
510
-
511
- function allowTx(action, location, retry) {
512
- return !blockers.length || (blockers.call({
513
- action: action,
514
- location: location,
515
- retry: retry
516
- }), false);
517
- }
518
-
519
- function applyTx(nextAction) {
520
- action = nextAction;
521
-
522
- var _getIndexAndLocation7 = getIndexAndLocation();
523
-
524
- index = _getIndexAndLocation7[0];
525
- location = _getIndexAndLocation7[1];
526
- listeners.call({
527
- action: action,
528
- location: location
529
- });
530
- }
531
-
532
- function push(to, state) {
533
- var nextAction = Action.Push;
534
- var nextLocation = getNextLocation(to, state);
535
-
536
- function retry() {
537
- push(to, state);
538
- }
539
-
540
- process.env.NODE_ENV !== "production" ? warning$1(nextLocation.pathname.charAt(0) === '/', "Relative pathnames are not supported in hash history.push(" + JSON.stringify(to) + ")") : void 0;
541
-
542
- if (allowTx(nextAction, nextLocation, retry)) {
543
- var _getHistoryStateAndUr3 = getHistoryStateAndUrl(nextLocation, index + 1),
544
- historyState = _getHistoryStateAndUr3[0],
545
- url = _getHistoryStateAndUr3[1]; // TODO: Support forced reloading
546
- // try...catch because iOS limits us to 100 pushState calls :/
547
-
548
-
549
- try {
550
- globalHistory.pushState(historyState, '', url);
551
- } catch (error) {
552
- // They are going to lose state here, but there is no real
553
- // way to warn them about it since the page will refresh...
554
- window.location.assign(url);
555
- }
556
-
557
- applyTx(nextAction);
558
- }
559
- }
560
-
561
- function replace(to, state) {
562
- var nextAction = Action.Replace;
563
- var nextLocation = getNextLocation(to, state);
564
-
565
- function retry() {
566
- replace(to, state);
567
- }
568
-
569
- process.env.NODE_ENV !== "production" ? warning$1(nextLocation.pathname.charAt(0) === '/', "Relative pathnames are not supported in hash history.replace(" + JSON.stringify(to) + ")") : void 0;
570
-
571
- if (allowTx(nextAction, nextLocation, retry)) {
572
- var _getHistoryStateAndUr4 = getHistoryStateAndUrl(nextLocation, index),
573
- historyState = _getHistoryStateAndUr4[0],
574
- url = _getHistoryStateAndUr4[1]; // TODO: Support forced reloading
575
-
576
-
577
- globalHistory.replaceState(historyState, '', url);
578
- applyTx(nextAction);
579
- }
580
- }
581
-
582
- function go(delta) {
583
- globalHistory.go(delta);
584
- }
585
-
586
- var history = {
587
- get action() {
588
- return action;
589
- },
590
-
591
- get location() {
592
- return location;
593
- },
594
-
595
- createHref: createHref,
596
- push: push,
597
- replace: replace,
598
- go: go,
599
- back: function back() {
600
- go(-1);
601
- },
602
- forward: function forward() {
603
- go(1);
604
- },
605
- listen: function listen(listener) {
606
- return listeners.push(listener);
607
- },
608
- block: function block(blocker) {
609
- var unblock = blockers.push(blocker);
610
-
611
- if (blockers.length === 1) {
612
- window.addEventListener(BeforeUnloadEventType, promptBeforeUnload);
613
- }
614
-
615
- return function () {
616
- unblock(); // Remove the beforeunload listener so the document may
617
- // still be salvageable in the pagehide event.
618
- // See https://html.spec.whatwg.org/#unloading-documents
619
-
620
- if (!blockers.length) {
621
- window.removeEventListener(BeforeUnloadEventType, promptBeforeUnload);
622
- }
623
- };
624
- }
625
- };
626
- return history;
627
- }
628
- /**
629
- * Memory history stores the current location in memory. It is designed for use
630
- * in stateful non-browser environments like tests and React Native.
631
- *
632
- * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#creatememoryhistory
633
- */
634
-
635
- function createMemoryHistory(options) {
636
- if (options === void 0) {
637
- options = {};
638
- }
639
-
640
- var _options3 = options,
641
- _options3$initialEntr = _options3.initialEntries,
642
- initialEntries = _options3$initialEntr === void 0 ? ['/'] : _options3$initialEntr,
643
- initialIndex = _options3.initialIndex;
644
- var entries = initialEntries.map(function (entry) {
645
- var location = readOnly(_extends$1({
646
- pathname: '/',
647
- search: '',
648
- hash: '',
649
- state: null,
650
- key: createKey()
651
- }, typeof entry === 'string' ? parsePath(entry) : entry));
652
- process.env.NODE_ENV !== "production" ? warning$1(location.pathname.charAt(0) === '/', "Relative pathnames are not supported in createMemoryHistory({ initialEntries }) (invalid entry: " + JSON.stringify(entry) + ")") : void 0;
653
- return location;
654
- });
655
- var index = clamp(initialIndex == null ? entries.length - 1 : initialIndex, 0, entries.length - 1);
656
- var action = Action.Pop;
657
- var location = entries[index];
658
- var listeners = createEvents();
659
- var blockers = createEvents();
660
-
661
- function createHref(to) {
662
- return typeof to === 'string' ? to : createPath(to);
663
- }
664
-
665
- function getNextLocation(to, state) {
666
- if (state === void 0) {
667
- state = null;
668
- }
669
-
670
- return readOnly(_extends$1({
671
- pathname: location.pathname,
672
- search: '',
673
- hash: ''
674
- }, typeof to === 'string' ? parsePath(to) : to, {
675
- state: state,
676
- key: createKey()
677
- }));
678
- }
679
-
680
- function allowTx(action, location, retry) {
681
- return !blockers.length || (blockers.call({
682
- action: action,
683
- location: location,
684
- retry: retry
685
- }), false);
686
- }
687
-
688
- function applyTx(nextAction, nextLocation) {
689
- action = nextAction;
690
- location = nextLocation;
691
- listeners.call({
692
- action: action,
693
- location: location
694
- });
695
- }
696
-
697
- function push(to, state) {
698
- var nextAction = Action.Push;
699
- var nextLocation = getNextLocation(to, state);
700
-
701
- function retry() {
702
- push(to, state);
703
- }
704
-
705
- process.env.NODE_ENV !== "production" ? warning$1(location.pathname.charAt(0) === '/', "Relative pathnames are not supported in memory history.push(" + JSON.stringify(to) + ")") : void 0;
706
-
707
- if (allowTx(nextAction, nextLocation, retry)) {
708
- index += 1;
709
- entries.splice(index, entries.length, nextLocation);
710
- applyTx(nextAction, nextLocation);
711
- }
712
- }
713
-
714
- function replace(to, state) {
715
- var nextAction = Action.Replace;
716
- var nextLocation = getNextLocation(to, state);
717
-
718
- function retry() {
719
- replace(to, state);
720
- }
721
-
722
- process.env.NODE_ENV !== "production" ? warning$1(location.pathname.charAt(0) === '/', "Relative pathnames are not supported in memory history.replace(" + JSON.stringify(to) + ")") : void 0;
723
-
724
- if (allowTx(nextAction, nextLocation, retry)) {
725
- entries[index] = nextLocation;
726
- applyTx(nextAction, nextLocation);
727
- }
728
- }
729
-
730
- function go(delta) {
731
- var nextIndex = clamp(index + delta, 0, entries.length - 1);
732
- var nextAction = Action.Pop;
733
- var nextLocation = entries[nextIndex];
734
-
735
- function retry() {
736
- go(delta);
737
- }
738
-
739
- if (allowTx(nextAction, nextLocation, retry)) {
740
- index = nextIndex;
741
- applyTx(nextAction, nextLocation);
742
- }
743
- }
744
-
745
- var history = {
746
- get index() {
747
- return index;
748
- },
749
-
750
- get action() {
751
- return action;
752
- },
753
-
754
- get location() {
755
- return location;
756
- },
757
-
758
- createHref: createHref,
759
- push: push,
760
- replace: replace,
761
- go: go,
762
- back: function back() {
763
- go(-1);
764
- },
765
- forward: function forward() {
766
- go(1);
767
- },
768
- listen: function listen(listener) {
769
- return listeners.push(listener);
770
- },
771
- block: function block(blocker) {
772
- return blockers.push(blocker);
773
- }
774
- };
775
- return history;
776
- } ////////////////////////////////////////////////////////////////////////////////
777
- // UTILS
778
- ////////////////////////////////////////////////////////////////////////////////
779
-
780
- function clamp(n, lowerBound, upperBound) {
781
- return Math.min(Math.max(n, lowerBound), upperBound);
782
- }
783
-
784
- function promptBeforeUnload(event) {
785
- // Cancel the event.
786
- event.preventDefault(); // Chrome (and legacy IE) requires returnValue to be set.
787
-
788
- event.returnValue = '';
789
- }
790
-
791
- function createEvents() {
792
- var handlers = [];
793
- return {
794
- get length() {
795
- return handlers.length;
796
- },
797
-
798
- push: function push(fn) {
799
- handlers.push(fn);
800
- return function () {
801
- handlers = handlers.filter(function (handler) {
802
- return handler !== fn;
803
- });
804
- };
805
- },
806
- call: function call(arg) {
807
- handlers.forEach(function (fn) {
808
- return fn && fn(arg);
809
- });
810
- }
811
- };
812
- }
813
-
814
- function createKey() {
815
- return Math.random().toString(36).substr(2, 8);
816
- }
817
- /**
818
- * Creates a string URL path from the given pathname, search, and hash components.
819
- *
820
- * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#createpath
821
- */
822
-
823
-
824
- function createPath(_ref) {
825
- var _ref$pathname = _ref.pathname,
826
- pathname = _ref$pathname === void 0 ? '/' : _ref$pathname,
827
- _ref$search = _ref.search,
828
- search = _ref$search === void 0 ? '' : _ref$search,
829
- _ref$hash = _ref.hash,
830
- hash = _ref$hash === void 0 ? '' : _ref$hash;
831
- if (search && search !== '?') pathname += search.charAt(0) === '?' ? search : '?' + search;
832
- if (hash && hash !== '#') pathname += hash.charAt(0) === '#' ? hash : '#' + hash;
833
- return pathname;
834
- }
835
- /**
836
- * Parses a string URL path into its separate pathname, search, and hash components.
837
- *
838
- * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#parsepath
839
- */
840
-
841
- function parsePath(path) {
842
- var parsedPath = {};
843
-
844
- if (path) {
845
- var hashIndex = path.indexOf('#');
846
-
847
- if (hashIndex >= 0) {
848
- parsedPath.hash = path.substr(hashIndex);
849
- path = path.substr(0, hashIndex);
850
- }
851
-
852
- var searchIndex = path.indexOf('?');
853
-
854
- if (searchIndex >= 0) {
855
- parsedPath.search = path.substr(searchIndex);
856
- path = path.substr(0, searchIndex);
857
- }
858
-
859
- if (path) {
860
- parsedPath.pathname = path;
861
- }
862
- }
863
-
864
- return parsedPath;
865
- }
866
-
867
- var isProduction = process.env.NODE_ENV === 'production';
868
- var prefix = 'Invariant failed';
869
- function invariant(condition, message) {
870
- if (condition) {
871
- return;
872
- }
873
- if (isProduction) {
874
- throw new Error(prefix);
875
- }
876
- var provided = typeof message === 'function' ? message() : message;
877
- var value = provided ? "".concat(prefix, ": ").concat(provided) : prefix;
878
- throw new Error(value);
879
- }
880
-
881
- // type UnionToIntersection<U> = (U extends any ? (k: U) => void : never) extends (
882
- // k: infer I,
883
- // ) => any
884
- // ? I
885
- // : never
886
-
887
- /**
888
- * This function returns `a` if `b` is deeply equal.
889
- * If not, it will replace any deeply equal children of `b` with those of `a`.
890
- * This can be used for structural sharing between JSON values for example.
891
- */
892
- function replaceEqualDeep(prev, next) {
893
- if (prev === next) {
894
- return prev;
895
- }
896
-
897
- const array = Array.isArray(prev) && Array.isArray(next);
898
-
899
- if (array || isPlainObject(prev) && isPlainObject(next)) {
900
- const aSize = array ? prev.length : Object.keys(prev).length;
901
- const bItems = array ? next : Object.keys(next);
902
- const bSize = bItems.length;
903
- const copy = array ? [] : {};
904
- let equalItems = 0;
905
-
906
- for (let i = 0; i < bSize; i++) {
907
- const key = array ? i : bItems[i];
908
- copy[key] = replaceEqualDeep(prev[key], next[key]);
909
-
910
- if (copy[key] === prev[key]) {
911
- equalItems++;
912
- }
913
- }
914
-
915
- return aSize === bSize && equalItems === aSize ? prev : copy;
916
- }
917
-
918
- return next;
919
- } // Copied from: https://github.com/jonschlinkert/is-plain-object
920
-
921
- function isPlainObject(o) {
922
- if (!hasObjectPrototype(o)) {
923
- return false;
924
- } // If has modified constructor
925
-
926
-
927
- const ctor = o.constructor;
928
-
929
- if (typeof ctor === 'undefined') {
930
- return true;
931
- } // If has modified prototype
932
-
933
-
934
- const prot = ctor.prototype;
935
-
936
- if (!hasObjectPrototype(prot)) {
937
- return false;
938
- } // If constructor does not have an Object-specific method
939
-
940
-
941
- if (!prot.hasOwnProperty('isPrototypeOf')) {
942
- return false;
943
- } // Most likely a plain Object
944
-
945
-
946
- return true;
947
- }
948
-
949
- function hasObjectPrototype(o) {
950
- return Object.prototype.toString.call(o) === '[object Object]';
951
- }
952
-
953
- function last(arr) {
954
- return arr[arr.length - 1];
955
- }
956
- function warning(cond, message) {
957
- if (cond) {
958
- if (typeof console !== 'undefined') console.warn(message);
959
-
960
- try {
961
- throw new Error(message);
962
- } catch (_unused) {}
963
- }
964
-
965
- return true;
966
- }
967
-
968
- function isFunction(d) {
969
- return typeof d === 'function';
970
- }
971
-
972
- function functionalUpdate(updater, previous) {
973
- if (isFunction(updater)) {
974
- return updater(previous);
975
- }
976
-
977
- return updater;
978
- }
979
- function pick(parent, keys) {
980
- return keys.reduce((obj, key) => {
981
- obj[key] = parent[key];
982
- return obj;
983
- }, {});
984
- }
985
-
986
- function joinPaths(paths) {
987
- return cleanPath(paths.filter(Boolean).join('/'));
988
- }
989
- function cleanPath(path) {
990
- // remove double slashes
991
- return path.replace(/\/{2,}/g, '/');
992
- }
993
- function trimPathLeft(path) {
994
- return path === '/' ? path : path.replace(/^\/{1,}/, '');
995
- }
996
- function trimPathRight(path) {
997
- return path === '/' ? path : path.replace(/\/{1,}$/, '');
998
- }
999
- function trimPath(path) {
1000
- return trimPathRight(trimPathLeft(path));
1001
- }
1002
- function resolvePath(basepath, base, to) {
1003
- base = base.replace(new RegExp("^" + basepath), '/');
1004
- to = to.replace(new RegExp("^" + basepath), '/');
1005
- let baseSegments = parsePathname(base);
1006
- const toSegments = parsePathname(to);
1007
- toSegments.forEach((toSegment, index) => {
1008
- if (toSegment.value === '/') {
1009
- if (!index) {
1010
- // Leading slash
1011
- baseSegments = [toSegment];
1012
- } else if (index === toSegments.length - 1) {
1013
- // Trailing Slash
1014
- baseSegments.push(toSegment);
1015
- } else ;
1016
- } else if (toSegment.value === '..') {
1017
- var _last;
1018
-
1019
- // Extra trailing slash? pop it off
1020
- if (baseSegments.length > 1 && ((_last = last(baseSegments)) == null ? void 0 : _last.value) === '/') {
1021
- baseSegments.pop();
1022
- }
1023
-
1024
- baseSegments.pop();
1025
- } else if (toSegment.value === '.') {
1026
- return;
1027
- } else {
1028
- baseSegments.push(toSegment);
1029
- }
1030
- });
1031
- const joined = joinPaths([basepath, ...baseSegments.map(d => d.value)]);
1032
- return cleanPath(joined);
1033
- }
1034
- function parsePathname(pathname) {
1035
- if (!pathname) {
1036
- return [];
1037
- }
1038
-
1039
- pathname = cleanPath(pathname);
1040
- const segments = [];
1041
-
1042
- if (pathname.slice(0, 1) === '/') {
1043
- pathname = pathname.substring(1);
1044
- segments.push({
1045
- type: 'pathname',
1046
- value: '/'
1047
- });
1048
- }
1049
-
1050
- if (!pathname) {
1051
- return segments;
1052
- } // Remove empty segments and '.' segments
1053
-
1054
-
1055
- const split = pathname.split('/').filter(Boolean);
1056
- segments.push(...split.map(part => {
1057
- if (part.startsWith('*')) {
1058
- return {
1059
- type: 'wildcard',
1060
- value: part
1061
- };
1062
- }
1063
-
1064
- if (part.charAt(0) === ':') {
1065
- return {
1066
- type: 'param',
1067
- value: part
1068
- };
1069
- }
1070
-
1071
- return {
1072
- type: 'pathname',
1073
- value: part
1074
- };
1075
- }));
1076
-
1077
- if (pathname.slice(-1) === '/') {
1078
- pathname = pathname.substring(1);
1079
- segments.push({
1080
- type: 'pathname',
1081
- value: '/'
1082
- });
1083
- }
1084
-
1085
- return segments;
1086
- }
1087
- function interpolatePath(path, params, leaveWildcard) {
1088
- const interpolatedPathSegments = parsePathname(path);
1089
- return joinPaths(interpolatedPathSegments.map(segment => {
1090
- if (segment.value === '*' && !leaveWildcard) {
1091
- return '';
1092
- }
1093
-
1094
- if (segment.type === 'param') {
1095
- var _segment$value$substr;
1096
-
1097
- return (_segment$value$substr = params[segment.value.substring(1)]) != null ? _segment$value$substr : '';
1098
- }
1099
-
1100
- return segment.value;
1101
- }));
1102
- }
1103
- function matchPathname(currentPathname, matchLocation) {
1104
- const pathParams = matchByPath(currentPathname, matchLocation); // const searchMatched = matchBySearch(currentLocation.search, matchLocation)
1105
-
1106
- if (matchLocation.to && !pathParams) {
1107
- return;
1108
- } // if (matchLocation.search && !searchMatched) {
1109
- // return
1110
- // }
1111
-
1112
-
1113
- return pathParams != null ? pathParams : {};
1114
- }
1115
- function matchByPath(from, matchLocation) {
1116
- var _matchLocation$to;
1117
-
1118
- const baseSegments = parsePathname(from);
1119
- const routeSegments = parsePathname("" + ((_matchLocation$to = matchLocation.to) != null ? _matchLocation$to : '*'));
1120
- const params = {};
1121
-
1122
- let isMatch = (() => {
1123
- for (let i = 0; i < Math.max(baseSegments.length, routeSegments.length); i++) {
1124
- const baseSegment = baseSegments[i];
1125
- const routeSegment = routeSegments[i];
1126
- const isLastRouteSegment = i === routeSegments.length - 1;
1127
- const isLastBaseSegment = i === baseSegments.length - 1;
1128
-
1129
- if (routeSegment) {
1130
- if (routeSegment.type === 'wildcard') {
1131
- if (baseSegment != null && baseSegment.value) {
1132
- params['*'] = joinPaths(baseSegments.slice(i).map(d => d.value));
1133
- return true;
1134
- }
1135
-
1136
- return false;
1137
- }
1138
-
1139
- if (routeSegment.type === 'pathname') {
1140
- if (routeSegment.value === '/' && !(baseSegment != null && baseSegment.value)) {
1141
- return true;
1142
- }
1143
-
1144
- if (baseSegment) {
1145
- if (matchLocation.caseSensitive) {
1146
- if (routeSegment.value !== baseSegment.value) {
1147
- return false;
1148
- }
1149
- } else if (routeSegment.value.toLowerCase() !== baseSegment.value.toLowerCase()) {
1150
- return false;
1151
- }
1152
- }
1153
- }
1154
-
1155
- if (!baseSegment) {
1156
- return false;
1157
- }
1158
-
1159
- if (routeSegment.type === 'param') {
1160
- if ((baseSegment == null ? void 0 : baseSegment.value) === '/') {
1161
- return false;
1162
- }
1163
-
1164
- if (!baseSegment.value.startsWith(':')) {
1165
- params[routeSegment.value.substring(1)] = baseSegment.value;
1166
- }
1167
- }
1168
- }
1169
-
1170
- if (isLastRouteSegment && !isLastBaseSegment) {
1171
- return !!matchLocation.fuzzy;
1172
- }
1173
- }
1174
-
1175
- return true;
1176
- })();
1177
-
1178
- return isMatch ? params : undefined;
1179
- }
1180
-
1181
- // @ts-nocheck
1182
- // qss has been slightly modified and inlined here for our use cases (and compression's sake). We've included it as a hard dependency for MIT license attribution.
1183
- function encode(obj, pfx) {
1184
- var k,
1185
- i,
1186
- tmp,
1187
- str = '';
1188
-
1189
- for (k in obj) {
1190
- if ((tmp = obj[k]) !== void 0) {
1191
- if (Array.isArray(tmp)) {
1192
- for (i = 0; i < tmp.length; i++) {
1193
- str && (str += '&');
1194
- str += encodeURIComponent(k) + '=' + encodeURIComponent(tmp[i]);
1195
- }
1196
- } else {
1197
- str && (str += '&');
1198
- str += encodeURIComponent(k) + '=' + encodeURIComponent(tmp);
1199
- }
1200
- }
1201
- }
1202
-
1203
- return (pfx || '') + str;
1204
- }
1205
-
1206
- function toValue(mix) {
1207
- if (!mix) return '';
1208
- var str = decodeURIComponent(mix);
1209
- if (str === 'false') return false;
1210
- if (str === 'true') return true;
1211
- if (str.charAt(0) === '0') return str;
1212
- return +str * 0 === 0 ? +str : str;
1213
- }
1214
-
1215
- function decode(str) {
1216
- var tmp,
1217
- k,
1218
- out = {},
1219
- arr = str.split('&');
1220
-
1221
- while (tmp = arr.shift()) {
1222
- tmp = tmp.split('=');
1223
- k = tmp.shift();
1224
-
1225
- if (out[k] !== void 0) {
1226
- out[k] = [].concat(out[k], toValue(tmp.shift()));
1227
- } else {
1228
- out[k] = toValue(tmp.shift());
1229
- }
1230
- }
1231
-
1232
- return out;
1233
- }
1234
-
1235
- function _extends() {
1236
- _extends = Object.assign ? Object.assign.bind() : function (target) {
1237
- for (var i = 1; i < arguments.length; i++) {
1238
- var source = arguments[i];
1239
-
1240
- for (var key in source) {
1241
- if (Object.prototype.hasOwnProperty.call(source, key)) {
1242
- target[key] = source[key];
1243
- }
1244
- }
1245
- }
1246
-
1247
- return target;
1248
- };
1249
- return _extends.apply(this, arguments);
1250
- }
1251
-
1252
- function createRoute(routeConfig, options, parent, router) {
1253
- const {
1254
- id,
1255
- routeId,
1256
- path: routePath,
1257
- fullPath
1258
- } = routeConfig;
1259
-
1260
- const action = router.state.actions[id] || (() => {
1261
- router.state.actions[id] = {
1262
- submissions: [],
1263
- submit: async (submission, actionOpts) => {
1264
- var _actionOpts$invalidat;
1265
-
1266
- if (!route) {
1267
- return;
1268
- }
1269
-
1270
- const invalidate = (_actionOpts$invalidat = actionOpts == null ? void 0 : actionOpts.invalidate) != null ? _actionOpts$invalidat : true;
1271
-
1272
- if (!(actionOpts != null && actionOpts.multi)) {
1273
- action.submissions = action.submissions.filter(d => d.isMulti);
1274
- }
1275
-
1276
- const actionState = {
1277
- submittedAt: Date.now(),
1278
- status: 'pending',
1279
- submission,
1280
- isMulti: !!(actionOpts != null && actionOpts.multi)
1281
- };
1282
- action.current = actionState;
1283
- action.latest = actionState;
1284
- action.submissions.push(actionState);
1285
- router.notify();
1286
-
1287
- try {
1288
- const res = await (route.options.action == null ? void 0 : route.options.action(submission));
1289
- actionState.data = res;
1290
-
1291
- if (invalidate) {
1292
- router.invalidateRoute({
1293
- to: '.',
1294
- fromCurrent: true
1295
- });
1296
- await router.reload();
1297
- }
1298
-
1299
- actionState.status = 'success';
1300
- return res;
1301
- } catch (err) {
1302
- console.error(err);
1303
- actionState.error = err;
1304
- actionState.status = 'error';
1305
- } finally {
1306
- router.notify();
1307
- }
1308
- }
1309
- };
1310
- return router.state.actions[id];
1311
- })();
1312
-
1313
- const loader = router.state.loaders[id] || (() => {
1314
- router.state.loaders[id] = {
1315
- pending: [],
1316
- fetch: async loaderContext => {
1317
- if (!route) {
1318
- return;
1319
- }
1320
-
1321
- const loaderState = {
1322
- loadedAt: Date.now(),
1323
- loaderContext
1324
- };
1325
- loader.current = loaderState;
1326
- loader.latest = loaderState;
1327
- loader.pending.push(loaderState); // router.state = {
1328
- // ...router.state,
1329
- // currentAction: loaderState,
1330
- // latestAction: loaderState,
1331
- // }
1332
-
1333
- router.notify();
1334
-
1335
- try {
1336
- return await (route.options.loader == null ? void 0 : route.options.loader(loaderContext));
1337
- } finally {
1338
- loader.pending = loader.pending.filter(d => d !== loaderState); // router.removeActionQueue.push({ loader, loaderState })
1339
-
1340
- router.notify();
1341
- }
1342
- }
1343
- };
1344
- return router.state.loaders[id];
1345
- })();
1346
-
1347
- let route = {
1348
- routeId: id,
1349
- routeRouteId: routeId,
1350
- routePath,
1351
- fullPath,
1352
- options,
1353
- router,
1354
- childRoutes: undefined,
1355
- parentRoute: parent,
1356
- action,
1357
- loader: loader,
1358
- buildLink: options => {
1359
- return router.buildLink(_extends({}, options, {
1360
- from: fullPath
1361
- }));
1362
- },
1363
- navigate: options => {
1364
- return router.navigate(_extends({}, options, {
1365
- from: fullPath
1366
- }));
1367
- },
1368
- matchRoute: (matchLocation, opts) => {
1369
- return router.matchRoute(_extends({}, matchLocation, {
1370
- from: fullPath
1371
- }), opts);
1372
- }
1373
- };
1374
- router.options.createRoute == null ? void 0 : router.options.createRoute({
1375
- router,
1376
- route
1377
- });
1378
- return route;
1379
- }
1380
-
1381
- const rootRouteId = '__root__';
1382
- const createRouteConfig = function createRouteConfig(options, children, isRoot, parentId, parentPath) {
1383
- if (options === void 0) {
1384
- options = {};
1385
- }
1386
-
1387
- if (isRoot === void 0) {
1388
- isRoot = true;
1389
- }
1390
-
1391
- if (isRoot) {
1392
- options.path = rootRouteId;
1393
- } // Strip the root from parentIds
1394
-
1395
-
1396
- if (parentId === rootRouteId) {
1397
- parentId = '';
1398
- }
1399
-
1400
- let path = isRoot ? rootRouteId : options.path; // If the path is anything other than an index path, trim it up
1401
-
1402
- if (path && path !== '/') {
1403
- path = trimPath(path);
1404
- }
1405
-
1406
- const routeId = path || options.id;
1407
- let id = joinPaths([parentId, routeId]);
1408
-
1409
- if (path === rootRouteId) {
1410
- path = '/';
1411
- }
1412
-
1413
- if (id !== rootRouteId) {
1414
- id = joinPaths(['/', id]);
1415
- }
1416
-
1417
- const fullPath = id === rootRouteId ? '/' : trimPathRight(joinPaths([parentPath, path]));
1418
- return {
1419
- id: id,
1420
- routeId: routeId,
1421
- path: path,
1422
- fullPath: fullPath,
1423
- options: options,
1424
- children,
1425
- createChildren: cb => createRouteConfig(options, cb(childOptions => createRouteConfig(childOptions, undefined, false, id, fullPath)), false, parentId, parentPath),
1426
- addChildren: children => createRouteConfig(options, children, false, parentId, parentPath),
1427
- createRoute: childOptions => createRouteConfig(childOptions, undefined, false, id, fullPath)
1428
- };
1429
- };
1430
-
1431
- const componentTypes = ['component', 'errorComponent', 'pendingComponent'];
1432
- function createRouteMatch(router, route, opts) {
1433
- const routeMatch = _extends({}, route, opts, {
1434
- router,
1435
- routeSearch: {},
1436
- search: {},
1437
- childMatches: [],
1438
- status: 'idle',
1439
- routeLoaderData: {},
1440
- loaderData: {},
1441
- isFetching: false,
1442
- isInvalid: false,
1443
- invalidAt: Infinity,
1444
- // pendingActions: [],
1445
- getIsInvalid: () => {
1446
- const now = Date.now();
1447
- return routeMatch.isInvalid || routeMatch.invalidAt < now;
1448
- },
1449
- __: {
1450
- abortController: new AbortController(),
1451
- latestId: '',
1452
- resolve: () => {},
1453
- notify: () => {
1454
- routeMatch.__.resolve();
1455
-
1456
- routeMatch.router.notify();
1457
- },
1458
- validate: () => {
1459
- var _routeMatch$parentMat, _routeMatch$parentMat2;
1460
-
1461
- // Validate the search params and stabilize them
1462
- const parentSearch = (_routeMatch$parentMat = (_routeMatch$parentMat2 = routeMatch.parentMatch) == null ? void 0 : _routeMatch$parentMat2.search) != null ? _routeMatch$parentMat : router.location.search;
1463
-
1464
- try {
1465
- var _validator;
1466
-
1467
- const prevSearch = routeMatch.routeSearch;
1468
- const validator = typeof routeMatch.options.validateSearch === 'object' ? routeMatch.options.validateSearch.parse : routeMatch.options.validateSearch;
1469
- let nextSearch = replaceEqualDeep(prevSearch, (_validator = validator == null ? void 0 : validator(parentSearch)) != null ? _validator : {}); // Invalidate route matches when search param stability changes
1470
-
1471
- if (prevSearch !== nextSearch) {
1472
- routeMatch.isInvalid = true;
1473
- }
1474
-
1475
- routeMatch.routeSearch = nextSearch;
1476
- routeMatch.search = replaceEqualDeep(parentSearch, _extends({}, parentSearch, nextSearch));
1477
- componentTypes.map(async type => {
1478
- const component = routeMatch.options[type];
1479
-
1480
- if (typeof routeMatch.__[type] !== 'function') {
1481
- routeMatch.__[type] = component;
1482
- }
1483
- });
1484
- } catch (err) {
1485
- console.error(err);
1486
- const error = new Error('Invalid search params found', {
1487
- cause: err
1488
- });
1489
- error.code = 'INVALID_SEARCH_PARAMS';
1490
- routeMatch.status = 'error';
1491
- routeMatch.error = error; // Do not proceed with loading the route
1492
-
1493
- return;
1494
- }
1495
- }
1496
- },
1497
- cancel: () => {
1498
- var _routeMatch$__$abortC;
1499
-
1500
- (_routeMatch$__$abortC = routeMatch.__.abortController) == null ? void 0 : _routeMatch$__$abortC.abort();
1501
- },
1502
- invalidate: () => {
1503
- routeMatch.isInvalid = true;
1504
- },
1505
- hasLoaders: () => {
1506
- return !!(route.options.loader || componentTypes.some(d => {
1507
- var _route$options$d;
1508
-
1509
- return (_route$options$d = route.options[d]) == null ? void 0 : _route$options$d.preload;
1510
- }));
1511
- },
1512
- load: async loaderOpts => {
1513
- const now = Date.now();
1514
- const minMaxAge = loaderOpts != null && loaderOpts.preload ? Math.max(loaderOpts == null ? void 0 : loaderOpts.maxAge, loaderOpts == null ? void 0 : loaderOpts.gcMaxAge) : 0; // If this is a preload, add it to the preload cache
1515
-
1516
- if (loaderOpts != null && loaderOpts.preload && minMaxAge > 0) {
1517
- // If the match is currently active, don't preload it
1518
- if (router.state.matches.find(d => d.matchId === routeMatch.matchId)) {
1519
- return;
1520
- }
1521
-
1522
- router.matchCache[routeMatch.matchId] = {
1523
- gc: now + loaderOpts.gcMaxAge,
1524
- match: routeMatch
1525
- };
1526
- } // If the match is invalid, errored or idle, trigger it to load
1527
-
1528
-
1529
- if (routeMatch.status === 'success' && routeMatch.getIsInvalid() || routeMatch.status === 'error' || routeMatch.status === 'idle') {
1530
- const maxAge = loaderOpts != null && loaderOpts.preload ? loaderOpts == null ? void 0 : loaderOpts.maxAge : undefined;
1531
- await routeMatch.fetch({
1532
- maxAge
1533
- });
1534
- }
1535
- },
1536
- fetch: async opts => {
1537
- const id = '' + Date.now() + Math.random();
1538
- routeMatch.__.latestId = id; // If the match was in an error state, set it
1539
- // to a loading state again. Otherwise, keep it
1540
- // as loading or resolved
1541
-
1542
- if (routeMatch.status === 'idle') {
1543
- routeMatch.status = 'loading';
1544
- } // We started loading the route, so it's no longer invalid
1545
-
1546
-
1547
- routeMatch.isInvalid = false;
1548
- routeMatch.__.loadPromise = new Promise(async resolve => {
1549
- // We are now fetching, even if it's in the background of a
1550
- // resolved state
1551
- routeMatch.isFetching = true;
1552
- routeMatch.__.resolve = resolve;
1553
-
1554
- routeMatch.__.componentsPromise = (async () => {
1555
- // then run all component and data loaders in parallel
1556
- // For each component type, potentially load it asynchronously
1557
- await Promise.all(componentTypes.map(async type => {
1558
- var _routeMatch$__$type;
1559
-
1560
- const component = routeMatch.options[type];
1561
-
1562
- if ((_routeMatch$__$type = routeMatch.__[type]) != null && _routeMatch$__$type.preload) {
1563
- routeMatch.__[type] = await router.options.loadComponent(component);
1564
- }
1565
- }));
1566
- })();
1567
-
1568
- routeMatch.__.dataPromise = Promise.resolve().then(async () => {
1569
- try {
1570
- var _ref, _ref2, _opts$maxAge;
1571
-
1572
- if (routeMatch.options.loader) {
1573
- var _routeMatch$parentMat3;
1574
-
1575
- const data = await routeMatch.options.loader({
1576
- parentLoaderPromise: (_routeMatch$parentMat3 = routeMatch.parentMatch) == null ? void 0 : _routeMatch$parentMat3.__.dataPromise,
1577
- params: routeMatch.params,
1578
- search: routeMatch.routeSearch,
1579
- signal: routeMatch.__.abortController.signal
1580
- });
1581
-
1582
- if (id !== routeMatch.__.latestId) {
1583
- return routeMatch.__.loadPromise;
1584
- }
1585
-
1586
- routeMatch.routeLoaderData = replaceEqualDeep(routeMatch.routeLoaderData, data);
1587
- }
1588
-
1589
- routeMatch.error = undefined;
1590
- routeMatch.status = 'success';
1591
- routeMatch.updatedAt = Date.now();
1592
- routeMatch.invalidAt = routeMatch.updatedAt + ((_ref = (_ref2 = (_opts$maxAge = opts == null ? void 0 : opts.maxAge) != null ? _opts$maxAge : routeMatch.options.loaderMaxAge) != null ? _ref2 : router.options.defaultLoaderMaxAge) != null ? _ref : 0);
1593
- return routeMatch.routeLoaderData;
1594
- } catch (err) {
1595
- if (id !== routeMatch.__.latestId) {
1596
- return routeMatch.__.loadPromise;
1597
- }
1598
-
1599
- if (process.env.NODE_ENV !== 'production') {
1600
- console.error(err);
1601
- }
1602
-
1603
- routeMatch.error = err;
1604
- routeMatch.status = 'error';
1605
- routeMatch.updatedAt = Date.now();
1606
- throw err;
1607
- }
1608
- });
1609
-
1610
- try {
1611
- await Promise.all([routeMatch.__.componentsPromise, routeMatch.__.dataPromise.catch(() => {})]);
1612
-
1613
- if (id !== routeMatch.__.latestId) {
1614
- return routeMatch.__.loadPromise;
1615
- }
1616
- } finally {
1617
- if (id !== routeMatch.__.latestId) {
1618
- return routeMatch.__.loadPromise;
1619
- }
1620
-
1621
- routeMatch.isFetching = false;
1622
-
1623
- routeMatch.__.notify();
1624
- }
1625
- });
1626
- await routeMatch.__.loadPromise;
1627
-
1628
- if (id !== routeMatch.__.latestId) {
1629
- return routeMatch.__.loadPromise;
1630
- }
1631
-
1632
- delete routeMatch.__.loadPromise;
1633
- }
1634
- });
1635
-
1636
- if (!routeMatch.hasLoaders()) {
1637
- routeMatch.status = 'success';
1638
- }
1639
-
1640
- return routeMatch;
1641
- }
1642
-
1643
- const defaultParseSearch = parseSearchWith(JSON.parse);
1644
- const defaultStringifySearch = stringifySearchWith(JSON.stringify);
1645
- function parseSearchWith(parser) {
1646
- return searchStr => {
1647
- if (searchStr.substring(0, 1) === '?') {
1648
- searchStr = searchStr.substring(1);
1649
- }
1650
-
1651
- let query = decode(searchStr); // Try to parse any query params that might be json
1652
-
1653
- for (let key in query) {
1654
- const value = query[key];
1655
-
1656
- if (typeof value === 'string') {
1657
- try {
1658
- query[key] = parser(value);
1659
- } catch (err) {//
1660
- }
1661
- }
1662
- }
1663
-
1664
- return query;
1665
- };
1666
- }
1667
- function stringifySearchWith(stringify) {
1668
- return search => {
1669
- search = _extends({}, search);
1670
-
1671
- if (search) {
1672
- Object.keys(search).forEach(key => {
1673
- const val = search[key];
1674
-
1675
- if (typeof val === 'undefined' || val === undefined) {
1676
- delete search[key];
1677
- } else if (val && typeof val === 'object' && val !== null) {
1678
- try {
1679
- search[key] = stringify(val);
1680
- } catch (err) {// silent
1681
- }
1682
- }
1683
- });
1684
- }
1685
-
1686
- const searchStr = encode(search).toString();
1687
- return searchStr ? "?" + searchStr : '';
1688
- };
1689
- }
1690
-
1691
- var _window$document;
1692
- // Detect if we're in the DOM
1693
- const isServer = typeof window === 'undefined' || !((_window$document = window.document) != null && _window$document.createElement); // This is the default history object if none is defined
1694
-
1695
- const createDefaultHistory = () => isServer ? createMemoryHistory() : createBrowserHistory();
1696
-
1697
- function getInitialRouterState() {
1698
- return {
1699
- status: 'idle',
1700
- location: null,
1701
- matches: [],
1702
- actions: {},
1703
- loaders: {},
1704
- lastUpdated: Date.now(),
1705
- isFetching: false,
1706
- isPreloading: false
1707
- };
1708
- }
1709
-
1710
- function createRouter(userOptions) {
1711
- var _userOptions$stringif, _userOptions$parseSea;
1712
-
1713
- const history = (userOptions == null ? void 0 : userOptions.history) || createDefaultHistory();
1714
-
1715
- const originalOptions = _extends({
1716
- defaultLoaderGcMaxAge: 5 * 60 * 1000,
1717
- defaultLoaderMaxAge: 0,
1718
- defaultPreloadMaxAge: 2000,
1719
- defaultPreloadDelay: 50
1720
- }, userOptions, {
1721
- stringifySearch: (_userOptions$stringif = userOptions == null ? void 0 : userOptions.stringifySearch) != null ? _userOptions$stringif : defaultStringifySearch,
1722
- parseSearch: (_userOptions$parseSea = userOptions == null ? void 0 : userOptions.parseSearch) != null ? _userOptions$parseSea : defaultParseSearch
1723
- });
1724
-
1725
- let router = {
1726
- history,
1727
- options: originalOptions,
1728
- listeners: [],
1729
- // Resolved after construction
1730
- basepath: '',
1731
- routeTree: undefined,
1732
- routesById: {},
1733
- location: undefined,
1734
- allRouteInfo: undefined,
1735
- //
1736
- navigationPromise: Promise.resolve(),
1737
- resolveNavigation: () => {},
1738
- matchCache: {},
1739
- state: getInitialRouterState(),
1740
- reset: () => {
1741
- router.state = getInitialRouterState();
1742
- router.notify();
1743
- },
1744
- startedLoadingAt: Date.now(),
1745
- subscribe: listener => {
1746
- router.listeners.push(listener);
1747
- return () => {
1748
- router.listeners = router.listeners.filter(x => x !== listener);
1749
- };
1750
- },
1751
- getRoute: id => {
1752
- return router.routesById[id];
1753
- },
1754
- notify: () => {
1755
- const isFetching = router.state.status === 'loading' || router.state.matches.some(d => d.isFetching);
1756
- const isPreloading = Object.values(router.matchCache).some(d => d.match.isFetching && !router.state.matches.find(dd => dd.matchId === d.match.matchId));
1757
-
1758
- if (router.state.isFetching !== isFetching || router.state.isPreloading !== isPreloading) {
1759
- router.state = _extends({}, router.state, {
1760
- isFetching,
1761
- isPreloading
1762
- });
1763
- }
1764
-
1765
- cascadeLoaderData(router.state.matches);
1766
- router.listeners.forEach(listener => listener(router));
1767
- },
1768
- dehydrateState: () => {
1769
- return _extends({}, pick(router.state, ['status', 'location', 'lastUpdated']), {
1770
- matches: router.state.matches.map(match => pick(match, ['matchId', 'status', 'routeLoaderData', 'loaderData', 'isInvalid', 'invalidAt']))
1771
- });
1772
- },
1773
- hydrateState: dehydratedState => {
1774
- // Match the routes
1775
- const matches = router.matchRoutes(router.location.pathname, {
1776
- strictParseParams: true
1777
- });
1778
- matches.forEach((match, index) => {
1779
- const dehydratedMatch = dehydratedState.matches[index];
1780
- invariant(dehydratedMatch, 'Oh no! Dehydrated route matches did not match the active state of the router 😬');
1781
- Object.assign(match, dehydratedMatch);
1782
- });
1783
- matches.forEach(match => match.__.validate());
1784
- router.state = _extends({}, router.state, dehydratedState, {
1785
- matches
1786
- });
1787
- },
1788
- mount: () => {
1789
- const next = router.__.buildLocation({
1790
- to: '.',
1791
- search: true,
1792
- hash: true
1793
- }); // If the current location isn't updated, trigger a navigation
1794
- // to the current location. Otherwise, load the current location.
1795
-
1796
-
1797
- if (next.href !== router.location.href) {
1798
- router.__.commitLocation(next, true);
1799
- }
1800
-
1801
- if (!router.state.matches.length) {
1802
- router.load();
1803
- }
1804
-
1805
- const unsub = router.history.listen(event => {
1806
- router.load(router.__.parseLocation(event.location, router.location));
1807
- }); // addEventListener does not exist in React Native, but window does
1808
- // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
1809
-
1810
- if (!isServer && window.addEventListener) {
1811
- // Listen to visibillitychange and focus
1812
- window.addEventListener('visibilitychange', router.onFocus, false);
1813
- window.addEventListener('focus', router.onFocus, false);
1814
- }
1815
-
1816
- return () => {
1817
- unsub();
1818
-
1819
- if (!isServer && window.removeEventListener) {
1820
- // Be sure to unsubscribe if a new handler is set
1821
- window.removeEventListener('visibilitychange', router.onFocus);
1822
- window.removeEventListener('focus', router.onFocus);
1823
- }
1824
- };
1825
- },
1826
- onFocus: () => {
1827
- router.load();
1828
- },
1829
- update: opts => {
1830
- const newHistory = (opts == null ? void 0 : opts.history) !== router.history;
1831
-
1832
- if (!router.location || newHistory) {
1833
- if (opts != null && opts.history) {
1834
- router.history = opts.history;
1835
- }
1836
-
1837
- router.location = router.__.parseLocation(router.history.location);
1838
- router.state.location = router.location;
1839
- }
1840
-
1841
- Object.assign(router.options, opts);
1842
- const {
1843
- basepath,
1844
- routeConfig
1845
- } = router.options;
1846
- router.basepath = cleanPath("/" + (basepath != null ? basepath : ''));
1847
-
1848
- if (routeConfig) {
1849
- router.routesById = {};
1850
- router.routeTree = router.__.buildRouteTree(routeConfig);
1851
- }
1852
-
1853
- return router;
1854
- },
1855
- cancelMatches: () => {
1856
- var _router$state$pending, _router$state$pending2;
1857
- [...router.state.matches, ...((_router$state$pending = (_router$state$pending2 = router.state.pending) == null ? void 0 : _router$state$pending2.matches) != null ? _router$state$pending : [])].forEach(match => {
1858
- match.cancel();
1859
- });
1860
- },
1861
- load: async next => {
1862
- const id = Math.random();
1863
- router.startedLoadingAt = id;
1864
-
1865
- if (next) {
1866
- // Ingest the new location
1867
- router.location = next;
1868
- } // Cancel any pending matches
1869
-
1870
-
1871
- router.cancelMatches(); // Match the routes
1872
-
1873
- const matches = router.matchRoutes(router.location.pathname, {
1874
- strictParseParams: true
1875
- });
1876
-
1877
- if (typeof document !== 'undefined') {
1878
- router.state = _extends({}, router.state, {
1879
- pending: {
1880
- matches: matches,
1881
- location: router.location
1882
- },
1883
- status: 'loading'
1884
- });
1885
- } else {
1886
- router.state = _extends({}, router.state, {
1887
- matches: matches,
1888
- location: router.location,
1889
- status: 'loading'
1890
- });
1891
- }
1892
-
1893
- router.notify(); // Load the matches
1894
-
1895
- await router.loadMatches(matches);
1896
-
1897
- if (router.startedLoadingAt !== id) {
1898
- // Ignore side-effects of match loading
1899
- return router.navigationPromise;
1900
- }
1901
-
1902
- const previousMatches = router.state.matches;
1903
- const exiting = [],
1904
- staying = [];
1905
- previousMatches.forEach(d => {
1906
- if (matches.find(dd => dd.matchId === d.matchId)) {
1907
- staying.push(d);
1908
- } else {
1909
- exiting.push(d);
1910
- }
1911
- });
1912
- const entering = matches.filter(d => {
1913
- return !previousMatches.find(dd => dd.matchId === d.matchId);
1914
- });
1915
- const now = Date.now();
1916
- exiting.forEach(d => {
1917
- var _ref, _d$options$loaderGcMa, _ref2, _d$options$loaderMaxA;
1918
-
1919
- d.__.onExit == null ? void 0 : d.__.onExit({
1920
- params: d.params,
1921
- search: d.routeSearch
1922
- }); // Clear idle error states when match leaves
1923
-
1924
- if (d.status === 'error' && !d.isFetching) {
1925
- d.status = 'idle';
1926
- d.error = undefined;
1927
- }
1928
-
1929
- const gc = Math.max((_ref = (_d$options$loaderGcMa = d.options.loaderGcMaxAge) != null ? _d$options$loaderGcMa : router.options.defaultLoaderGcMaxAge) != null ? _ref : 0, (_ref2 = (_d$options$loaderMaxA = d.options.loaderMaxAge) != null ? _d$options$loaderMaxA : router.options.defaultLoaderMaxAge) != null ? _ref2 : 0);
1930
-
1931
- if (gc > 0) {
1932
- router.matchCache[d.matchId] = {
1933
- gc: gc == Infinity ? Number.MAX_SAFE_INTEGER : now + gc,
1934
- match: d
1935
- };
1936
- }
1937
- });
1938
- staying.forEach(d => {
1939
- d.options.onTransition == null ? void 0 : d.options.onTransition({
1940
- params: d.params,
1941
- search: d.routeSearch
1942
- });
1943
- });
1944
- entering.forEach(d => {
1945
- d.__.onExit = d.options.onMatch == null ? void 0 : d.options.onMatch({
1946
- params: d.params,
1947
- search: d.search
1948
- });
1949
- delete router.matchCache[d.matchId];
1950
- });
1951
-
1952
- if (router.startedLoadingAt !== id) {
1953
- // Ignore side-effects of match loading
1954
- return;
1955
- }
1956
-
1957
- matches.forEach(match => {
1958
- // Clear actions
1959
- if (match.action) {
1960
- match.action.current = undefined;
1961
- match.action.submissions = [];
1962
- }
1963
- });
1964
- router.state = _extends({}, router.state, {
1965
- location: router.location,
1966
- matches,
1967
- pending: undefined,
1968
- status: 'idle'
1969
- });
1970
- router.notify();
1971
- router.resolveNavigation();
1972
- },
1973
- cleanMatchCache: () => {
1974
- const now = Date.now();
1975
- Object.keys(router.matchCache).forEach(matchId => {
1976
- const entry = router.matchCache[matchId]; // Don't remove loading matches
1977
-
1978
- if (entry.match.status === 'loading') {
1979
- return;
1980
- } // Do not remove successful matches that are still valid
1981
-
1982
-
1983
- if (entry.gc > 0 && entry.gc > now) {
1984
- return;
1985
- } // Everything else gets removed
1986
-
1987
-
1988
- delete router.matchCache[matchId];
1989
- });
1990
- },
1991
- loadRoute: async function loadRoute(navigateOpts) {
1992
- if (navigateOpts === void 0) {
1993
- navigateOpts = router.location;
1994
- }
1995
-
1996
- const next = router.buildNext(navigateOpts);
1997
- const matches = router.matchRoutes(next.pathname, {
1998
- strictParseParams: true
1999
- });
2000
- await router.loadMatches(matches);
2001
- return matches;
2002
- },
2003
- preloadRoute: async function preloadRoute(navigateOpts, loaderOpts) {
2004
- var _ref3, _ref4, _loaderOpts$maxAge, _ref5, _ref6, _loaderOpts$gcMaxAge;
2005
-
2006
- if (navigateOpts === void 0) {
2007
- navigateOpts = router.location;
2008
- }
2009
-
2010
- const next = router.buildNext(navigateOpts);
2011
- const matches = router.matchRoutes(next.pathname, {
2012
- strictParseParams: true
2013
- });
2014
- await router.loadMatches(matches, {
2015
- preload: true,
2016
- maxAge: (_ref3 = (_ref4 = (_loaderOpts$maxAge = loaderOpts.maxAge) != null ? _loaderOpts$maxAge : router.options.defaultPreloadMaxAge) != null ? _ref4 : router.options.defaultLoaderMaxAge) != null ? _ref3 : 0,
2017
- gcMaxAge: (_ref5 = (_ref6 = (_loaderOpts$gcMaxAge = loaderOpts.gcMaxAge) != null ? _loaderOpts$gcMaxAge : router.options.defaultPreloadGcMaxAge) != null ? _ref6 : router.options.defaultLoaderGcMaxAge) != null ? _ref5 : 0
2018
- });
2019
- return matches;
2020
- },
2021
- matchRoutes: (pathname, opts) => {
2022
- var _router$state$pending3, _router$state$pending4;
2023
-
2024
- router.cleanMatchCache();
2025
- const matches = [];
2026
-
2027
- if (!router.routeTree) {
2028
- return matches;
2029
- }
2030
-
2031
- const existingMatches = [...router.state.matches, ...((_router$state$pending3 = (_router$state$pending4 = router.state.pending) == null ? void 0 : _router$state$pending4.matches) != null ? _router$state$pending3 : [])];
2032
-
2033
- const recurse = async routes => {
2034
- var _parentMatch$params, _router$options$filte, _foundRoute$childRout;
2035
-
2036
- const parentMatch = last(matches);
2037
- let params = (_parentMatch$params = parentMatch == null ? void 0 : parentMatch.params) != null ? _parentMatch$params : {};
2038
- const filteredRoutes = (_router$options$filte = router.options.filterRoutes == null ? void 0 : router.options.filterRoutes(routes)) != null ? _router$options$filte : routes;
2039
- let foundRoutes = [];
2040
-
2041
- const findMatchInRoutes = (parentRoutes, routes) => {
2042
- routes.some(route => {
2043
- var _route$childRoutes, _route$childRoutes2, _route$options$caseSe;
2044
-
2045
- if (!route.routePath && (_route$childRoutes = route.childRoutes) != null && _route$childRoutes.length) {
2046
- return findMatchInRoutes([...foundRoutes, route], route.childRoutes);
2047
- }
2048
-
2049
- const fuzzy = !!(route.routePath !== '/' || (_route$childRoutes2 = route.childRoutes) != null && _route$childRoutes2.length);
2050
- const matchParams = matchPathname(pathname, {
2051
- to: route.fullPath,
2052
- fuzzy,
2053
- caseSensitive: (_route$options$caseSe = route.options.caseSensitive) != null ? _route$options$caseSe : router.options.caseSensitive
2054
- });
2055
-
2056
- if (matchParams) {
2057
- let parsedParams;
2058
-
2059
- try {
2060
- var _route$options$parseP;
2061
-
2062
- parsedParams = (_route$options$parseP = route.options.parseParams == null ? void 0 : route.options.parseParams(matchParams)) != null ? _route$options$parseP : matchParams;
2063
- } catch (err) {
2064
- if (opts != null && opts.strictParseParams) {
2065
- throw err;
2066
- }
2067
- }
2068
-
2069
- params = _extends({}, params, parsedParams);
2070
- }
2071
-
2072
- if (!!matchParams) {
2073
- foundRoutes = [...parentRoutes, route];
2074
- }
2075
-
2076
- return !!foundRoutes.length;
2077
- });
2078
- return !!foundRoutes.length;
2079
- };
2080
-
2081
- findMatchInRoutes([], filteredRoutes);
2082
-
2083
- if (!foundRoutes.length) {
2084
- return;
2085
- }
2086
-
2087
- foundRoutes.forEach(foundRoute => {
2088
- var _router$matchCache$ma;
2089
-
2090
- const interpolatedPath = interpolatePath(foundRoute.routePath, params);
2091
- const matchId = interpolatePath(foundRoute.routeId, params, true);
2092
- const match = existingMatches.find(d => d.matchId === matchId) || ((_router$matchCache$ma = router.matchCache[matchId]) == null ? void 0 : _router$matchCache$ma.match) || createRouteMatch(router, foundRoute, {
2093
- parentMatch,
2094
- matchId,
2095
- params,
2096
- pathname: joinPaths([pathname, interpolatedPath])
2097
- });
2098
- matches.push(match);
2099
- });
2100
- const foundRoute = last(foundRoutes);
2101
-
2102
- if ((_foundRoute$childRout = foundRoute.childRoutes) != null && _foundRoute$childRout.length) {
2103
- recurse(foundRoute.childRoutes);
19
+ function _extends() {
20
+ _extends = Object.assign ? Object.assign.bind() : function (target) {
21
+ for (var i = 1; i < arguments.length; i++) {
22
+ var source = arguments[i];
23
+ for (var key in source) {
24
+ if (Object.prototype.hasOwnProperty.call(source, key)) {
25
+ target[key] = source[key];
2104
26
  }
2105
- };
2106
-
2107
- recurse([router.routeTree]);
2108
- cascadeLoaderData(matches);
2109
- return matches;
2110
- },
2111
- loadMatches: async (resolvedMatches, loaderOpts) => {
2112
- const matchPromises = resolvedMatches.map(async match => {
2113
- // Validate the match (loads search params etc)
2114
- match.__.validate();
2115
-
2116
- match.load(loaderOpts);
27
+ }
28
+ }
29
+ return target;
30
+ };
31
+ return _extends.apply(this, arguments);
32
+ }
2117
33
 
2118
- if (match.__.loadPromise) {
2119
- // Wait for the first sign of activity from the match
2120
- await match.__.loadPromise;
2121
- }
34
+ Route.__onInit = route => {
35
+ Object.assign(route, {
36
+ useMatch: (opts = {}) => {
37
+ return useMatch({
38
+ ...opts,
39
+ from: route.id
2122
40
  });
2123
- router.notify();
2124
- await Promise.all(matchPromises);
2125
41
  },
2126
- invalidateRoute: opts => {
2127
- var _router$state$pending5, _router$state$pending6;
2128
-
2129
- const next = router.buildNext(opts);
2130
- const unloadedMatchIds = router.matchRoutes(next.pathname).map(d => d.matchId);
2131
- [...router.state.matches, ...((_router$state$pending5 = (_router$state$pending6 = router.state.pending) == null ? void 0 : _router$state$pending6.matches) != null ? _router$state$pending5 : [])].forEach(match => {
2132
- if (unloadedMatchIds.includes(match.matchId)) {
2133
- match.invalidate();
2134
- }
42
+ useLoader: (opts = {}) => {
43
+ return useLoader({
44
+ ...opts,
45
+ from: route.id
2135
46
  });
2136
47
  },
2137
- reload: () => router.__.navigate({
2138
- fromCurrent: true,
2139
- replace: true,
2140
- search: true
2141
- }),
2142
- resolvePath: (from, path) => {
2143
- return resolvePath(router.basepath, from, cleanPath(path));
2144
- },
2145
- matchRoute: (location, opts) => {
2146
- var _location$from;
2147
-
2148
- // const location = router.buildNext(opts)
2149
- location = _extends({}, location, {
2150
- to: location.to ? router.resolvePath((_location$from = location.from) != null ? _location$from : '', location.to) : undefined
48
+ useContext: (opts = {}) => {
49
+ return useMatch({
50
+ ...opts,
51
+ from: route.id,
52
+ select: d => opts?.select ? opts.select(d.context) : d.context
2151
53
  });
2152
- const next = router.buildNext(location);
2153
-
2154
- if (opts != null && opts.pending) {
2155
- var _router$state$pending7;
2156
-
2157
- if (!((_router$state$pending7 = router.state.pending) != null && _router$state$pending7.location)) {
2158
- return false;
2159
- }
2160
-
2161
- return !!matchPathname(router.state.pending.location.pathname, _extends({}, opts, {
2162
- to: next.pathname
2163
- }));
2164
- }
2165
-
2166
- return !!matchPathname(router.state.location.pathname, _extends({}, opts, {
2167
- to: next.pathname
2168
- }));
2169
54
  },
2170
- navigate: async _ref7 => {
2171
- let {
2172
- from,
2173
- to = '.',
2174
- search,
2175
- hash,
2176
- replace,
2177
- params
2178
- } = _ref7;
2179
- // If this link simply reloads the current route,
2180
- // make sure it has a new key so it will trigger a data refresh
2181
- // If this `to` is a valid external URL, return
2182
- // null for LinkUtils
2183
- const toString = String(to);
2184
- const fromString = String(from);
2185
- let isExternal;
2186
-
2187
- try {
2188
- new URL("" + toString);
2189
- isExternal = true;
2190
- } catch (e) {}
2191
-
2192
- invariant(!isExternal, 'Attempting to navigate to external url with router.navigate!');
2193
- return router.__.navigate({
2194
- from: fromString,
2195
- to: toString,
2196
- search,
2197
- hash,
2198
- replace,
2199
- params
55
+ useRouteContext: (opts = {}) => {
56
+ return useMatch({
57
+ ...opts,
58
+ from: route.id,
59
+ select: d => opts?.select ? opts.select(d.routeContext) : d.routeContext
2200
60
  });
2201
61
  },
2202
- buildLink: _ref8 => {
2203
- var _preload, _ref9;
2204
-
2205
- let {
2206
- from,
2207
- to = '.',
2208
- search,
2209
- params,
2210
- hash,
2211
- target,
2212
- replace,
2213
- activeOptions,
2214
- preload,
2215
- preloadMaxAge: userPreloadMaxAge,
2216
- preloadGcMaxAge: userPreloadGcMaxAge,
2217
- preloadDelay: userPreloadDelay,
2218
- disabled
2219
- } = _ref8;
2220
-
2221
- // If this link simply reloads the current route,
2222
- // make sure it has a new key so it will trigger a data refresh
2223
- // If this `to` is a valid external URL, return
2224
- // null for LinkUtils
2225
- try {
2226
- new URL("" + to);
2227
- return {
2228
- type: 'external',
2229
- href: to
2230
- };
2231
- } catch (e) {}
2232
-
2233
- const nextOpts = {
2234
- from,
2235
- to,
2236
- search,
2237
- params,
2238
- hash,
2239
- replace
2240
- };
2241
- const next = router.buildNext(nextOpts);
2242
- preload = (_preload = preload) != null ? _preload : router.options.defaultPreload;
2243
- const preloadDelay = (_ref9 = userPreloadDelay != null ? userPreloadDelay : router.options.defaultPreloadDelay) != null ? _ref9 : 0; // Compare path/hash for matches
2244
-
2245
- const pathIsEqual = router.state.location.pathname === next.pathname;
2246
- const currentPathSplit = router.state.location.pathname.split('/');
2247
- const nextPathSplit = next.pathname.split('/');
2248
- const pathIsFuzzyEqual = nextPathSplit.every((d, i) => d === currentPathSplit[i]);
2249
- const hashIsEqual = router.state.location.hash === next.hash; // Combine the matches based on user options
2250
-
2251
- const pathTest = activeOptions != null && activeOptions.exact ? pathIsEqual : pathIsFuzzyEqual;
2252
- const hashTest = activeOptions != null && activeOptions.includeHash ? hashIsEqual : true; // The final "active" test
2253
-
2254
- const isActive = pathTest && hashTest; // The click handler
2255
-
2256
- const handleClick = e => {
2257
- if (!disabled && !isCtrlEvent(e) && !e.defaultPrevented && (!target || target === '_self') && e.button === 0) {
2258
- e.preventDefault();
2259
-
2260
- if (pathIsEqual && !search && !hash) {
2261
- router.invalidateRoute(nextOpts);
2262
- } // All is well? Navigate!)
2263
-
2264
-
2265
- router.__.navigate(nextOpts);
2266
- }
2267
- }; // The click handler
2268
-
2269
-
2270
- const handleFocus = e => {
2271
- if (preload) {
2272
- router.preloadRoute(nextOpts, {
2273
- maxAge: userPreloadMaxAge,
2274
- gcMaxAge: userPreloadGcMaxAge
2275
- });
2276
- }
2277
- };
2278
-
2279
- const handleEnter = e => {
2280
- const target = e.target || {};
2281
-
2282
- if (preload) {
2283
- if (target.preloadTimeout) {
2284
- return;
2285
- }
2286
-
2287
- target.preloadTimeout = setTimeout(() => {
2288
- target.preloadTimeout = null;
2289
- router.preloadRoute(nextOpts, {
2290
- maxAge: userPreloadMaxAge,
2291
- gcMaxAge: userPreloadGcMaxAge
2292
- });
2293
- }, preloadDelay);
2294
- }
2295
- };
2296
-
2297
- const handleLeave = e => {
2298
- const target = e.target || {};
2299
-
2300
- if (target.preloadTimeout) {
2301
- clearTimeout(target.preloadTimeout);
2302
- target.preloadTimeout = null;
2303
- }
2304
- };
2305
-
2306
- return {
2307
- type: 'internal',
2308
- next,
2309
- handleFocus,
2310
- handleClick,
2311
- handleEnter,
2312
- handleLeave,
2313
- isActive,
2314
- disabled
2315
- };
2316
- },
2317
- buildNext: opts => {
2318
- const next = router.__.buildLocation(opts);
2319
-
2320
- const matches = router.matchRoutes(next.pathname);
2321
-
2322
- const __preSearchFilters = matches.map(match => {
2323
- var _match$options$preSea;
2324
-
2325
- return (_match$options$preSea = match.options.preSearchFilters) != null ? _match$options$preSea : [];
2326
- }).flat().filter(Boolean);
2327
-
2328
- const __postSearchFilters = matches.map(match => {
2329
- var _match$options$postSe;
2330
-
2331
- return (_match$options$postSe = match.options.postSearchFilters) != null ? _match$options$postSe : [];
2332
- }).flat().filter(Boolean);
2333
-
2334
- return router.__.buildLocation(_extends({}, opts, {
2335
- __preSearchFilters,
2336
- __postSearchFilters
2337
- }));
62
+ useSearch: (opts = {}) => {
63
+ return useSearch({
64
+ ...opts,
65
+ from: route.id
66
+ });
2338
67
  },
2339
- __: {
2340
- buildRouteTree: rootRouteConfig => {
2341
- const recurseRoutes = (routeConfigs, parent) => {
2342
- return routeConfigs.map(routeConfig => {
2343
- const routeOptions = routeConfig.options;
2344
- const route = createRoute(routeConfig, routeOptions, parent, router);
2345
- const existingRoute = router.routesById[route.routeId];
2346
-
2347
- if (existingRoute) {
2348
- if (process.env.NODE_ENV !== 'production') {
2349
- console.warn("Duplicate routes found with id: " + String(route.routeId), router.routesById, route);
2350
- }
2351
-
2352
- throw new Error();
2353
- }
2354
- router.routesById[route.routeId] = route;
2355
- const children = routeConfig.children;
2356
- route.childRoutes = children != null && children.length ? recurseRoutes(children, route) : undefined;
2357
- return route;
2358
- });
2359
- };
2360
-
2361
- const routes = recurseRoutes([rootRouteConfig]);
2362
- return routes[0];
2363
- },
2364
- parseLocation: (location, previousLocation) => {
2365
- var _location$hash$split$;
2366
-
2367
- const parsedSearch = router.options.parseSearch(location.search);
2368
- return {
2369
- pathname: location.pathname,
2370
- searchStr: location.search,
2371
- search: replaceEqualDeep(previousLocation == null ? void 0 : previousLocation.search, parsedSearch),
2372
- hash: (_location$hash$split$ = location.hash.split('#').reverse()[0]) != null ? _location$hash$split$ : '',
2373
- href: "" + location.pathname + location.search + location.hash,
2374
- state: location.state,
2375
- key: location.key
2376
- };
2377
- },
2378
- navigate: location => {
2379
- const next = router.buildNext(location);
2380
- return router.__.commitLocation(next, location.replace);
2381
- },
2382
- buildLocation: function buildLocation(dest) {
2383
- var _dest$from, _router$basepath, _dest$to, _last, _dest$params, _dest$__preSearchFilt, _functionalUpdate, _dest$__preSearchFilt2, _dest$__postSearchFil;
2384
-
2385
- if (dest === void 0) {
2386
- dest = {};
2387
- }
2388
-
2389
- // const resolvedFrom: Location = {
2390
- // ...router.location,
2391
- const fromPathname = dest.fromCurrent ? router.location.pathname : (_dest$from = dest.from) != null ? _dest$from : router.location.pathname;
2392
-
2393
- let pathname = resolvePath((_router$basepath = router.basepath) != null ? _router$basepath : '/', fromPathname, "" + ((_dest$to = dest.to) != null ? _dest$to : '.'));
2394
-
2395
- const fromMatches = router.matchRoutes(router.location.pathname, {
2396
- strictParseParams: true
2397
- });
2398
- const toMatches = router.matchRoutes(pathname);
2399
-
2400
- const prevParams = _extends({}, (_last = last(fromMatches)) == null ? void 0 : _last.params);
2401
-
2402
- let nextParams = ((_dest$params = dest.params) != null ? _dest$params : true) === true ? prevParams : functionalUpdate(dest.params, prevParams);
2403
-
2404
- if (nextParams) {
2405
- toMatches.map(d => d.options.stringifyParams).filter(Boolean).forEach(fn => {
2406
- Object.assign({}, nextParams, fn(nextParams));
2407
- });
2408
- }
2409
-
2410
- pathname = interpolatePath(pathname, nextParams != null ? nextParams : {}); // Pre filters first
2411
-
2412
- const preFilteredSearch = (_dest$__preSearchFilt = dest.__preSearchFilters) != null && _dest$__preSearchFilt.length ? dest.__preSearchFilters.reduce((prev, next) => next(prev), router.location.search) : router.location.search; // Then the link/navigate function
2413
-
2414
- const destSearch = dest.search === true ? preFilteredSearch // Preserve resolvedFrom true
2415
- : dest.search ? (_functionalUpdate = functionalUpdate(dest.search, preFilteredSearch)) != null ? _functionalUpdate : {} // Updater
2416
- : (_dest$__preSearchFilt2 = dest.__preSearchFilters) != null && _dest$__preSearchFilt2.length ? preFilteredSearch // Preserve resolvedFrom filters
2417
- : {}; // Then post filters
2418
-
2419
- const postFilteredSearch = (_dest$__postSearchFil = dest.__postSearchFilters) != null && _dest$__postSearchFil.length ? dest.__postSearchFilters.reduce((prev, next) => next(prev), destSearch) : destSearch;
2420
- const search = replaceEqualDeep(router.location.search, postFilteredSearch);
2421
- const searchStr = router.options.stringifySearch(search);
2422
- let hash = dest.hash === true ? router.location.hash : functionalUpdate(dest.hash, router.location.hash);
2423
- hash = hash ? "#" + hash : '';
2424
- return {
2425
- pathname,
2426
- search,
2427
- searchStr,
2428
- state: router.location.state,
2429
- hash,
2430
- href: "" + pathname + searchStr + hash,
2431
- key: dest.key
2432
- };
2433
- },
2434
- commitLocation: (next, replace) => {
2435
- const id = '' + Date.now() + Math.random();
2436
- if (router.navigateTimeout) clearTimeout(router.navigateTimeout);
2437
- let nextAction = 'replace';
2438
-
2439
- if (!replace) {
2440
- nextAction = 'push';
2441
- }
2442
-
2443
- const isSameUrl = router.__.parseLocation(history.location).href === next.href;
2444
-
2445
- if (isSameUrl && !next.key) {
2446
- nextAction = 'replace';
2447
- }
2448
-
2449
- if (nextAction === 'replace') {
2450
- history.replace({
2451
- pathname: next.pathname,
2452
- hash: next.hash,
2453
- search: next.searchStr
2454
- }, _extends({
2455
- id
2456
- }, next.state));
2457
- } else {
2458
- history.push({
2459
- pathname: next.pathname,
2460
- hash: next.hash,
2461
- search: next.searchStr
2462
- }, {
2463
- id
2464
- });
2465
- }
2466
-
2467
- router.navigationPromise = new Promise(resolve => {
2468
- const previousNavigationResolve = router.resolveNavigation;
2469
-
2470
- router.resolveNavigation = () => {
2471
- previousNavigationResolve();
2472
- resolve();
2473
- };
2474
- });
2475
- return router.navigationPromise;
2476
- }
68
+ useParams: (opts = {}) => {
69
+ return useParams({
70
+ ...opts,
71
+ from: route.id
72
+ });
2477
73
  }
2478
- };
2479
- router.update(userOptions); // Allow frameworks to hook into the router creation
2480
-
2481
- router.options.createRouter == null ? void 0 : router.options.createRouter(router);
2482
- return router;
2483
- }
2484
-
2485
- function isCtrlEvent(e) {
2486
- return !!(e.metaKey || e.altKey || e.ctrlKey || e.shiftKey);
2487
- }
74
+ });
75
+ };
2488
76
 
2489
- function cascadeLoaderData(matches) {
2490
- matches.forEach((match, index) => {
2491
- const parent = matches[index - 1];
77
+ //
2492
78
 
2493
- if (parent) {
2494
- match.loaderData = replaceEqualDeep(match.loaderData, _extends({}, parent.loaderData, match.routeLoaderData));
79
+ function lazyRouteComponent(importer, exportName) {
80
+ let loadPromise;
81
+ const load = () => {
82
+ if (!loadPromise) {
83
+ loadPromise = importer();
2495
84
  }
85
+ return loadPromise;
86
+ };
87
+ const lazyComp = /*#__PURE__*/React.lazy(async () => {
88
+ const moduleExports = await load();
89
+ const comp = moduleExports[exportName ?? 'default'];
90
+ return {
91
+ default: comp
92
+ };
2496
93
  });
94
+ lazyComp.preload = load;
95
+ return lazyComp;
2497
96
  }
2498
-
2499
- const _excluded = ["type", "children", "target", "activeProps", "inactiveProps", "activeOptions", "disabled", "hash", "search", "params", "to", "preload", "preloadDelay", "preloadMaxAge", "replace", "style", "className", "onClick", "onFocus", "onMouseEnter", "onMouseLeave", "onTouchStart", "onTouchEnd"],
2500
- _excluded2 = ["pending", "caseSensitive", "children"],
2501
- _excluded3 = ["children", "router"];
2502
97
  //
2503
- const matchesContext = /*#__PURE__*/React.createContext(null);
2504
- const routerContext = /*#__PURE__*/React.createContext(null); // Detect if we're in the DOM
2505
- function MatchesProvider(props) {
2506
- return /*#__PURE__*/React.createElement(matchesContext.Provider, props);
2507
- }
2508
-
2509
- const useRouterSubscription = router => {
2510
- useSyncExternalStore(cb => router.subscribe(() => cb()), () => router.state, () => router.state);
2511
- };
2512
98
 
2513
- function createReactRouter(opts) {
2514
- const makeRouteExt = (route, router) => {
99
+ function useLinkProps(options) {
100
+ const router = useRouter();
101
+ const {
102
+ // custom props
103
+ type,
104
+ children,
105
+ target,
106
+ activeProps = () => ({
107
+ className: 'active'
108
+ }),
109
+ inactiveProps = () => ({}),
110
+ activeOptions,
111
+ disabled,
112
+ // fromCurrent,
113
+ hash,
114
+ search,
115
+ params,
116
+ to = '.',
117
+ preload,
118
+ preloadDelay,
119
+ replace,
120
+ // element props
121
+ style,
122
+ className,
123
+ onClick,
124
+ onFocus,
125
+ onMouseEnter,
126
+ onMouseLeave,
127
+ onTouchStart,
128
+ ...rest
129
+ } = options;
130
+ const linkInfo = router.buildLink(options);
131
+ if (linkInfo.type === 'external') {
132
+ const {
133
+ href
134
+ } = linkInfo;
2515
135
  return {
2516
- useRoute: function useRoute(subRouteId) {
2517
- if (subRouteId === void 0) {
2518
- subRouteId = '.';
2519
- }
2520
-
2521
- const resolvedRouteId = router.resolvePath(route.routeId, subRouteId);
2522
- const resolvedRoute = router.getRoute(resolvedRouteId);
2523
- useRouterSubscription(router);
2524
- invariant(resolvedRoute, "Could not find a route for route \"" + resolvedRouteId + "\"! Did you forget to add it to your route config?");
2525
- return resolvedRoute;
2526
- },
2527
- linkProps: options => {
2528
- var _functionalUpdate, _functionalUpdate2;
2529
-
2530
- const {
2531
- // custom props
2532
- target,
2533
- activeProps = () => ({
2534
- className: 'active'
2535
- }),
2536
- inactiveProps = () => ({}),
2537
- disabled,
2538
- // element props
2539
- style,
2540
- className,
2541
- onClick,
2542
- onFocus,
2543
- onMouseEnter,
2544
- onMouseLeave
2545
- } = options,
2546
- rest = _objectWithoutPropertiesLoose(options, _excluded);
2547
-
2548
- const linkInfo = route.buildLink(options);
2549
-
2550
- if (linkInfo.type === 'external') {
2551
- const {
2552
- href
2553
- } = linkInfo;
2554
- return {
2555
- href
2556
- };
2557
- }
2558
-
2559
- const {
2560
- handleClick,
2561
- handleFocus,
2562
- handleEnter,
2563
- handleLeave,
2564
- isActive,
2565
- next
2566
- } = linkInfo;
2567
-
2568
- const reactHandleClick = e => {
2569
- React.startTransition(() => {
2570
- handleClick(e);
2571
- });
2572
- };
2573
-
2574
- const composeHandlers = handlers => e => {
2575
- e.persist();
2576
- handlers.forEach(handler => {
2577
- if (handler) handler(e);
2578
- });
2579
- }; // Get the active props
2580
-
2581
-
2582
- const resolvedActiveProps = isActive ? (_functionalUpdate = functionalUpdate(activeProps, {})) != null ? _functionalUpdate : {} : {}; // Get the inactive props
2583
-
2584
- const resolvedInactiveProps = isActive ? {} : (_functionalUpdate2 = functionalUpdate(inactiveProps, {})) != null ? _functionalUpdate2 : {};
2585
- return _extends$2({}, resolvedActiveProps, resolvedInactiveProps, rest, {
2586
- href: disabled ? undefined : next.href,
2587
- onClick: composeHandlers([reactHandleClick, onClick]),
2588
- onFocus: composeHandlers([handleFocus, onFocus]),
2589
- onMouseEnter: composeHandlers([handleEnter, onMouseEnter]),
2590
- onMouseLeave: composeHandlers([handleLeave, onMouseLeave]),
2591
- target,
2592
- style: _extends$2({}, style, resolvedActiveProps.style, resolvedInactiveProps.style),
2593
- className: [className, resolvedActiveProps.className, resolvedInactiveProps.className].filter(Boolean).join(' ') || undefined
2594
- }, disabled ? {
2595
- role: 'link',
2596
- 'aria-disabled': true
2597
- } : undefined, {
2598
- ['data-status']: isActive ? 'active' : undefined
2599
- });
2600
- },
2601
- Link: /*#__PURE__*/React.forwardRef((props, ref) => {
2602
- const linkProps = route.linkProps(props);
2603
- useRouterSubscription(router);
2604
- return /*#__PURE__*/React.createElement("a", _extends$2({
2605
- ref: ref
2606
- }, linkProps, {
2607
- children: typeof props.children === 'function' ? props.children({
2608
- isActive: linkProps['data-status'] === 'active'
2609
- }) : props.children
2610
- }));
2611
- }),
2612
- MatchRoute: opts => {
2613
- const {
2614
- pending,
2615
- caseSensitive
2616
- } = opts,
2617
- rest = _objectWithoutPropertiesLoose(opts, _excluded2);
2618
-
2619
- const params = route.matchRoute(rest, {
2620
- pending,
2621
- caseSensitive
2622
- });
2623
-
2624
- if (!params) {
2625
- return null;
2626
- }
2627
-
2628
- return typeof opts.children === 'function' ? opts.children(params) : opts.children;
2629
- }
136
+ href
2630
137
  };
138
+ }
139
+ const {
140
+ handleClick,
141
+ handleFocus,
142
+ handleEnter,
143
+ handleLeave,
144
+ handleTouchStart,
145
+ isActive,
146
+ next
147
+ } = linkInfo;
148
+ const handleReactClick = e => {
149
+ if (options.startTransition ?? true) {
150
+ (React.startTransition || (d => d))(() => {
151
+ handleClick(e);
152
+ });
153
+ }
154
+ };
155
+ const composeHandlers = handlers => e => {
156
+ if (e.persist) e.persist();
157
+ handlers.filter(Boolean).forEach(handler => {
158
+ if (e.defaultPrevented) return;
159
+ handler(e);
160
+ });
2631
161
  };
2632
162
 
2633
- const coreRouter = createRouter(_extends$2({}, opts, {
2634
- createRouter: router => {
2635
- const routerExt = {
2636
- useState: () => {
2637
- useRouterSubscription(router);
2638
- return router.state;
2639
- },
2640
- useMatch: (routeId, opts) => {
2641
- var _useMatches, _opts$strict;
2642
-
2643
- useRouterSubscription(router);
2644
- invariant(routeId !== rootRouteId, "\"" + rootRouteId + "\" cannot be used with useMatch! Did you mean to useRoute(\"" + rootRouteId + "\")?");
2645
- const runtimeMatch = (_useMatches = useMatches()) == null ? void 0 : _useMatches[0];
2646
- const match = router.state.matches.find(d => d.routeId === routeId);
2647
-
2648
- if ((_opts$strict = opts == null ? void 0 : opts.strict) != null ? _opts$strict : true) {
2649
- invariant(match, "Could not find an active match for \"" + routeId + "\"!");
2650
- invariant(runtimeMatch.routeId == (match == null ? void 0 : match.routeId), "useMatch(\"" + (match == null ? void 0 : match.routeId) + "\") is being called in a component that is meant to render the '" + runtimeMatch.routeId + "' route. Did you mean to 'useMatch(\"" + (match == null ? void 0 : match.routeId) + "\", { strict: false })' or 'useRoute(\"" + (match == null ? void 0 : match.routeId) + "\")' instead?");
2651
- }
2652
-
2653
- return match;
2654
- }
2655
- };
2656
- const routeExt = makeRouteExt(router.getRoute('/'), router);
2657
- Object.assign(router, routerExt, routeExt);
2658
- },
2659
- createRoute: _ref => {
2660
- let {
2661
- router,
2662
- route
2663
- } = _ref;
2664
- const routeExt = makeRouteExt(route, router);
2665
- Object.assign(route, routeExt);
2666
- },
2667
- loadComponent: async component => {
2668
- if (component.preload && typeof document !== 'undefined') {
2669
- component.preload(); // return await component.preload()
2670
- }
163
+ // Get the active props
164
+ const resolvedActiveProps = isActive ? functionalUpdate(activeProps, {}) ?? {} : {};
2671
165
 
2672
- return component;
2673
- }
166
+ // Get the inactive props
167
+ const resolvedInactiveProps = isActive ? {} : functionalUpdate(inactiveProps, {}) ?? {};
168
+ return {
169
+ ...resolvedActiveProps,
170
+ ...resolvedInactiveProps,
171
+ ...rest,
172
+ href: disabled ? undefined : next.href,
173
+ onClick: composeHandlers([onClick, handleReactClick]),
174
+ onFocus: composeHandlers([onFocus, handleFocus]),
175
+ onMouseEnter: composeHandlers([onMouseEnter, handleEnter]),
176
+ onMouseLeave: composeHandlers([onMouseLeave, handleLeave]),
177
+ onTouchStart: composeHandlers([onTouchStart, handleTouchStart]),
178
+ target,
179
+ style: {
180
+ ...style,
181
+ ...resolvedActiveProps.style,
182
+ ...resolvedInactiveProps.style
183
+ },
184
+ className: [className, resolvedActiveProps.className, resolvedInactiveProps.className].filter(Boolean).join(' ') || undefined,
185
+ ...(disabled ? {
186
+ role: 'link',
187
+ 'aria-disabled': true
188
+ } : undefined),
189
+ ['data-status']: isActive ? 'active' : undefined
190
+ };
191
+ }
192
+ const Link = /*#__PURE__*/React.forwardRef((props, ref) => {
193
+ const linkProps = useLinkProps(props);
194
+ return /*#__PURE__*/React.createElement("a", _extends({
195
+ ref: ref
196
+ }, linkProps, {
197
+ children: typeof props.children === 'function' ? props.children({
198
+ isActive: linkProps['data-status'] === 'active'
199
+ }) : props.children
2674
200
  }));
2675
- return coreRouter;
201
+ });
202
+ function Navigate(props) {
203
+ const router = useRouter();
204
+ React.useLayoutEffect(() => {
205
+ router.navigate(props);
206
+ }, []);
207
+ return null;
208
+ }
209
+ const matchIdsContext = /*#__PURE__*/React.createContext(null);
210
+ const routerContext = /*#__PURE__*/React.createContext(null);
211
+ function useRouterState(opts) {
212
+ const router = useRouter();
213
+ return useStore(router.__store, opts?.select);
2676
214
  }
2677
- function RouterProvider(_ref2) {
2678
- let {
2679
- children,
2680
- router
2681
- } = _ref2,
2682
- rest = _objectWithoutPropertiesLoose(_ref2, _excluded3);
2683
-
215
+ function RouterProvider({
216
+ router,
217
+ ...rest
218
+ }) {
2684
219
  router.update(rest);
2685
- useRouterSubscription(router);
2686
220
  React.useEffect(() => {
2687
- return router.mount();
221
+ let unsub;
222
+ React.startTransition(() => {
223
+ unsub = router.mount();
224
+ });
225
+ return unsub;
2688
226
  }, [router]);
2689
- return /*#__PURE__*/React.createElement(routerContext.Provider, {
2690
- value: {
2691
- router
227
+ const Wrap = router.options.Wrap || React.Fragment;
228
+ return /*#__PURE__*/React.createElement(Wrap, null, /*#__PURE__*/React.createElement(routerContext.Provider, {
229
+ value: router
230
+ }, /*#__PURE__*/React.createElement(Matches, null)));
231
+ }
232
+ function Matches() {
233
+ const router = useRouter();
234
+ const matchIds = useRouterState({
235
+ select: state => {
236
+ const hasPendingComponent = state.pendingMatches.some(d => {
237
+ const route = router.getRoute(d.routeId);
238
+ return !!route?.options.pendingComponent;
239
+ });
240
+ if (hasPendingComponent) {
241
+ return state.pendingMatchIds;
242
+ }
243
+ return state.matchIds;
244
+ }
245
+ });
246
+ return /*#__PURE__*/React.createElement(matchIdsContext.Provider, {
247
+ value: [undefined, ...matchIds]
248
+ }, /*#__PURE__*/React.createElement(CatchBoundary, {
249
+ errorComponent: ErrorComponent,
250
+ route: router.getRoute(rootRouteId),
251
+ onCatch: () => {
252
+ warning(false, `Error in router! Consider setting an 'errorComponent' in your RootRoute! 👍`);
2692
253
  }
2693
- }, /*#__PURE__*/React.createElement(MatchesProvider, {
2694
- value: router.state.matches
2695
- }, children != null ? children : /*#__PURE__*/React.createElement(Outlet, null)));
254
+ }, /*#__PURE__*/React.createElement(Outlet, null)));
2696
255
  }
2697
256
  function useRouter() {
2698
257
  const value = React.useContext(routerContext);
2699
- warning(!value, 'useRouter must be used inside a <Router> component!');
2700
- useRouterSubscription(value.router);
2701
- return value.router;
258
+ warning(value, 'useRouter must be used inside a <Router> component!');
259
+ return value;
2702
260
  }
2703
- function useMatches() {
2704
- return React.useContext(matchesContext);
261
+ function useMatches(opts) {
262
+ const matchIds = React.useContext(matchIdsContext);
263
+ return useRouterState({
264
+ select: state => {
265
+ const matches = state.matches.slice(state.matches.findIndex(d => d.id === matchIds[0]));
266
+ return opts?.select ? opts.select(matches) : matches;
267
+ }
268
+ });
2705
269
  }
2706
- function Outlet() {
2707
- var _ref3, _match$__$pendingComp, _match$__$errorCompon;
2708
-
270
+ function useMatch(opts) {
2709
271
  const router = useRouter();
2710
- const matches = useMatches().slice(1);
2711
- const match = matches[0];
2712
- const defaultPending = React.useCallback(() => null, []);
2713
-
2714
- if (!match) {
2715
- return null;
272
+ const nearestMatchId = React.useContext(matchIdsContext)[0];
273
+ const nearestMatchRouteId = router.getRouteMatch(nearestMatchId)?.routeId;
274
+ const matchRouteId = useRouterState({
275
+ select: state => {
276
+ const matches = state.status === 'pending' ? state.pendingMatches : state.matches;
277
+ const match = opts?.from ? matches.find(d => d.routeId === opts?.from) : matches.find(d => d.id === nearestMatchId);
278
+ return match.routeId;
279
+ }
280
+ });
281
+ if (opts?.strict ?? true) {
282
+ invariant(nearestMatchRouteId == matchRouteId, `useMatch("${matchRouteId}") is being called in a component that is meant to render the '${nearestMatchRouteId}' route. Did you mean to 'useMatch("${matchRouteId}", { strict: false })' or 'useRoute("${matchRouteId}")' instead?`);
2716
283
  }
2717
-
2718
- const PendingComponent = (_ref3 = (_match$__$pendingComp = match.__.pendingComponent) != null ? _match$__$pendingComp : router.options.defaultPendingComponent) != null ? _ref3 : defaultPending;
2719
- const errorComponent = (_match$__$errorCompon = match.__.errorComponent) != null ? _match$__$errorCompon : router.options.defaultErrorComponent;
2720
- return /*#__PURE__*/React.createElement(MatchesProvider, {
2721
- value: matches
2722
- }, /*#__PURE__*/React.createElement(React.Suspense, {
2723
- fallback: /*#__PURE__*/React.createElement(PendingComponent, null)
2724
- }, /*#__PURE__*/React.createElement(CatchBoundary, {
2725
- errorComponent: errorComponent
2726
- }, (() => {
2727
- if (match.status === 'error') {
2728
- throw match.error;
284
+ const matchSelection = useRouterState({
285
+ select: state => {
286
+ const matches = state.status === 'pending' ? state.pendingMatches : state.matches;
287
+ const match = opts?.from ? matches.find(d => d.routeId === opts?.from) : matches.find(d => d.id === nearestMatchId);
288
+ invariant(match, `Could not find ${opts?.from ? `an active match from "${opts.from}"` : 'a nearest match!'}`);
289
+ return opts?.select ? opts.select(match) : match;
2729
290
  }
2730
-
2731
- if (match.status === 'success') {
2732
- var _ref4, _ref5;
2733
-
2734
- return /*#__PURE__*/React.createElement((_ref4 = (_ref5 = match.__.component) != null ? _ref5 : router.options.defaultComponent) != null ? _ref4 : Outlet);
291
+ });
292
+ return matchSelection;
293
+ }
294
+ function useLoader(opts) {
295
+ return useMatch({
296
+ ...opts,
297
+ select: match => opts?.select ? opts?.select(match.loaderData) : match.loaderData
298
+ });
299
+ }
300
+ function useRouterContext(opts) {
301
+ return useMatch({
302
+ ...opts,
303
+ select: match => opts?.select ? opts.select(match.context) : match.context
304
+ });
305
+ }
306
+ function useRouteContext(opts) {
307
+ return useMatch({
308
+ ...opts,
309
+ select: match => opts?.select ? opts.select(match.routeContext) : match.routeContext
310
+ });
311
+ }
312
+ function useSearch(opts) {
313
+ return useMatch({
314
+ ...opts,
315
+ select: match => {
316
+ return opts?.select ? opts.select(match.search) : match.search;
2735
317
  }
2736
-
2737
- if (match.__.loadPromise) {
2738
- console.log(match.matchId, 'suspend');
2739
- throw match.__.loadPromise;
318
+ });
319
+ }
320
+ function useParams(opts) {
321
+ return useRouterState({
322
+ select: state => {
323
+ const params = last(state.matches)?.params;
324
+ return opts?.select ? opts.select(params) : params;
2740
325
  }
2741
-
2742
- invariant(false, 'This should never happen!');
2743
- })())));
326
+ });
2744
327
  }
2745
-
2746
- class CatchBoundary extends React.Component {
2747
- constructor() {
2748
- super(...arguments);
2749
- this.state = {
2750
- error: false
2751
- };
328
+ function useNavigate(defaultOpts) {
329
+ const router = useRouter();
330
+ return React.useCallback(opts => {
331
+ return router.navigate({
332
+ ...defaultOpts,
333
+ ...opts
334
+ });
335
+ }, []);
336
+ }
337
+ function useMatchRoute() {
338
+ const router = useRouter();
339
+ return React.useCallback(opts => {
340
+ const {
341
+ pending,
342
+ caseSensitive,
343
+ ...rest
344
+ } = opts;
345
+ return router.matchRoute(rest, {
346
+ pending,
347
+ caseSensitive
348
+ });
349
+ }, []);
350
+ }
351
+ function MatchRoute(props) {
352
+ const matchRoute = useMatchRoute();
353
+ const params = matchRoute(props);
354
+ if (typeof props.children === 'function') {
355
+ return props.children(params);
356
+ }
357
+ return !!params ? props.children : null;
358
+ }
359
+ function Outlet() {
360
+ const matchIds = React.useContext(matchIdsContext).slice(1);
361
+ if (!matchIds[0]) {
362
+ return null;
2752
363
  }
364
+ return /*#__PURE__*/React.createElement(Match, {
365
+ matchIds: matchIds
366
+ });
367
+ }
368
+ const defaultPending = () => null;
369
+ function Match({
370
+ matchIds
371
+ }) {
372
+ const router = useRouter();
373
+ const matchId = matchIds[0];
374
+ const routeId = router.getRouteMatch(matchId).routeId;
375
+ const route = router.getRoute(routeId);
376
+ const PendingComponent = route.options.pendingComponent ?? router.options.defaultPendingComponent ?? defaultPending;
377
+ const errorComponent = route.options.errorComponent ?? router.options.defaultErrorComponent ?? ErrorComponent;
378
+ const ResolvedSuspenseBoundary = route.options.wrapInSuspense ?? !route.isRoot ? React.Suspense : SafeFragment;
379
+ const ResolvedCatchBoundary = !!errorComponent ? CatchBoundary : SafeFragment;
380
+ return /*#__PURE__*/React.createElement(matchIdsContext.Provider, {
381
+ value: matchIds
382
+ }, /*#__PURE__*/React.createElement(ResolvedSuspenseBoundary, {
383
+ fallback: /*#__PURE__*/React.createElement(PendingComponent, {
384
+ useMatch: route.useMatch,
385
+ useContext: route.useContext,
386
+ useRouteContext: route.useRouteContext,
387
+ useSearch: route.useSearch,
388
+ useParams: route.useParams
389
+ })
390
+ }, /*#__PURE__*/React.createElement(ResolvedCatchBoundary, {
391
+ key: route.id,
392
+ errorComponent: errorComponent,
393
+ route: route,
394
+ onCatch: () => {
395
+ warning(false, `Error in route match: ${matchId}`);
396
+ }
397
+ }, /*#__PURE__*/React.createElement(MatchInner, {
398
+ matchId: matchId,
399
+ PendingComponent: PendingComponent
400
+ }))));
401
+ }
402
+ function MatchInner({
403
+ matchId,
404
+ PendingComponent
405
+ }) {
406
+ const router = useRouter();
407
+ const match = useRouterState({
408
+ select: d => {
409
+ const match = d.matchesById[matchId];
410
+ return pick(match, ['status', 'loadPromise', 'routeId', 'error']);
411
+ }
412
+ });
413
+ const route = router.getRoute(match.routeId);
414
+ if (match.status === 'error') {
415
+ throw match.error;
416
+ }
417
+ if (match.status === 'pending') {
418
+ return /*#__PURE__*/React.createElement(PendingComponent, {
419
+ useLoader: route.useLoader,
420
+ useMatch: route.useMatch,
421
+ useContext: route.useContext,
422
+ useRouteContext: route.useRouteContext,
423
+ useSearch: route.useSearch,
424
+ useParams: route.useParams
425
+ });
426
+ }
427
+ if (match.status === 'success') {
428
+ let comp = route.options.component ?? router.options.defaultComponent;
429
+ if (comp) {
430
+ return /*#__PURE__*/React.createElement(comp, {
431
+ useLoader: route.useLoader,
432
+ useMatch: route.useMatch,
433
+ useContext: route.useContext,
434
+ useRouteContext: route.useRouteContext,
435
+ useSearch: route.useSearch,
436
+ useParams: route.useParams
437
+ });
438
+ }
439
+ return /*#__PURE__*/React.createElement(Outlet, null);
440
+ }
441
+ invariant(false, 'Idle routeMatch status encountered during rendering! You should never see this. File an issue!');
442
+ }
443
+ function SafeFragment(props) {
444
+ return /*#__PURE__*/React.createElement(React.Fragment, null, props.children);
445
+ }
446
+ function useInjectHtml() {
447
+ const router = useRouter();
448
+ return React.useCallback(html => {
449
+ router.injectHtml(html);
450
+ }, []);
451
+ }
452
+ function useDehydrate() {
453
+ const router = useRouter();
454
+ return React.useCallback(function dehydrate(key, data) {
455
+ return router.dehydrateData(key, data);
456
+ }, []);
457
+ }
458
+ function useHydrate() {
459
+ const router = useRouter();
460
+ return function hydrate(key) {
461
+ return router.hydrateData(key);
462
+ };
463
+ }
2753
464
 
465
+ // This is the messiest thing ever... I'm either seriously tired (likely) or
466
+ // there has to be a better way to reset error boundaries when the
467
+ // router's location key changes.
468
+
469
+ class CatchBoundary extends React.Component {
470
+ state = {
471
+ error: false,
472
+ info: undefined
473
+ };
2754
474
  componentDidCatch(error, info) {
2755
- console.error(error);
475
+ this.props.onCatch(error, info);
2756
476
  this.setState({
2757
477
  error,
2758
478
  info
2759
479
  });
2760
480
  }
2761
-
2762
481
  render() {
2763
- var _this$props$errorComp;
2764
-
2765
- const errorComponent = (_this$props$errorComp = this.props.errorComponent) != null ? _this$props$errorComp : DefaultErrorBoundary;
2766
-
2767
- if (this.state.error) {
2768
- return /*#__PURE__*/React.createElement(errorComponent, this.state);
482
+ return /*#__PURE__*/React.createElement(CatchBoundaryInner, _extends({}, this.props, {
483
+ errorState: this.state,
484
+ reset: () => this.setState({})
485
+ }));
486
+ }
487
+ }
488
+ function CatchBoundaryInner(props) {
489
+ const locationKey = useRouterState({
490
+ select: d => d.resolvedLocation.key
491
+ });
492
+ const [activeErrorState, setActiveErrorState] = React.useState(props.errorState);
493
+ const errorComponent = props.errorComponent ?? ErrorComponent;
494
+ const prevKeyRef = React.useRef('');
495
+ React.useEffect(() => {
496
+ if (activeErrorState) {
497
+ if (locationKey !== prevKeyRef.current) {
498
+ setActiveErrorState({});
499
+ }
2769
500
  }
2770
-
2771
- return this.props.children;
501
+ prevKeyRef.current = locationKey;
502
+ }, [activeErrorState, locationKey]);
503
+ React.useEffect(() => {
504
+ if (props.errorState.error) {
505
+ setActiveErrorState(props.errorState);
506
+ }
507
+ // props.reset()
508
+ }, [props.errorState.error]);
509
+ if (props.errorState.error && activeErrorState.error) {
510
+ return /*#__PURE__*/React.createElement(errorComponent, {
511
+ ...activeErrorState,
512
+ useMatch: props.route.useMatch,
513
+ useContext: props.route.useContext,
514
+ useRouteContext: props.route.useRouteContext,
515
+ useSearch: props.route.useSearch,
516
+ useParams: props.route.useParams
517
+ });
2772
518
  }
2773
-
519
+ return props.children;
2774
520
  }
2775
-
2776
- function DefaultErrorBoundary(_ref6) {
2777
- let {
2778
- error
2779
- } = _ref6;
521
+ function ErrorComponent({
522
+ error
523
+ }) {
524
+ const [show, setShow] = React.useState(process.env.NODE_ENV !== 'production');
2780
525
  return /*#__PURE__*/React.createElement("div", {
2781
526
  style: {
2782
527
  padding: '.5rem',
2783
528
  maxWidth: '100%'
2784
529
  }
530
+ }, /*#__PURE__*/React.createElement("div", {
531
+ style: {
532
+ display: 'flex',
533
+ alignItems: 'center',
534
+ gap: '.5rem'
535
+ }
2785
536
  }, /*#__PURE__*/React.createElement("strong", {
2786
537
  style: {
2787
- fontSize: '1.2rem'
538
+ fontSize: '1rem'
2788
539
  }
2789
- }, "Something went wrong!"), /*#__PURE__*/React.createElement("div", {
540
+ }, "Something went wrong!"), /*#__PURE__*/React.createElement("button", {
541
+ style: {
542
+ appearance: 'none',
543
+ fontSize: '.6em',
544
+ border: '1px solid currentColor',
545
+ padding: '.1rem .2rem',
546
+ fontWeight: 'bold',
547
+ borderRadius: '.25rem'
548
+ },
549
+ onClick: () => setShow(d => !d)
550
+ }, show ? 'Hide Error' : 'Show Error')), /*#__PURE__*/React.createElement("div", {
2790
551
  style: {
2791
- height: '.5rem'
552
+ height: '.25rem'
2792
553
  }
2793
- }), /*#__PURE__*/React.createElement("div", null, /*#__PURE__*/React.createElement("pre", null, error.message ? /*#__PURE__*/React.createElement("code", {
554
+ }), show ? /*#__PURE__*/React.createElement("div", null, /*#__PURE__*/React.createElement("pre", {
2794
555
  style: {
2795
556
  fontSize: '.7em',
2796
557
  border: '1px solid red',
2797
558
  borderRadius: '.25rem',
2798
- padding: '.5rem',
2799
- color: 'red'
559
+ padding: '.3rem',
560
+ color: 'red',
561
+ overflow: 'auto'
2800
562
  }
2801
- }, error.message) : null)));
563
+ }, error.message ? /*#__PURE__*/React.createElement("code", null, error.message) : null)) : null);
2802
564
  }
2803
- function usePrompt(message, when) {
565
+ function useBlocker(message, condition = true) {
2804
566
  const router = useRouter();
2805
567
  React.useEffect(() => {
2806
- if (!when) return;
2807
- let unblock = router.history.block(transition => {
568
+ if (!condition) return;
569
+ let unblock = router.history.block((retry, cancel) => {
2808
570
  if (window.confirm(message)) {
2809
571
  unblock();
2810
- transition.retry();
2811
- } else {
2812
- router.location.pathname = window.location.pathname;
572
+ retry();
2813
573
  }
2814
574
  });
2815
575
  return unblock;
2816
- }, [when, location, message]);
576
+ });
577
+ }
578
+ function Block({
579
+ message,
580
+ condition,
581
+ children
582
+ }) {
583
+ useBlocker(message, condition);
584
+ return children ?? null;
585
+ }
586
+ function shallow(objA, objB) {
587
+ if (Object.is(objA, objB)) {
588
+ return true;
589
+ }
590
+ if (typeof objA !== 'object' || objA === null || typeof objB !== 'object' || objB === null) {
591
+ return false;
592
+ }
593
+ const keysA = Object.keys(objA);
594
+ if (keysA.length !== Object.keys(objB).length) {
595
+ return false;
596
+ }
597
+ for (let i = 0; i < keysA.length; i++) {
598
+ if (!Object.prototype.hasOwnProperty.call(objB, keysA[i]) || !Object.is(objA[keysA[i]], objB[keysA[i]])) {
599
+ return false;
600
+ }
601
+ }
602
+ return true;
603
+ }
604
+
605
+ const useLayoutEffect = typeof window !== 'undefined' ? React.useLayoutEffect : React.useEffect;
606
+ function useScrollRestoration(options) {
607
+ const router = useRouter();
608
+ useLayoutEffect(() => {
609
+ return watchScrollPositions(router, options);
610
+ }, []);
611
+ useLayoutEffect(() => {
612
+ restoreScrollPositions(router, options);
613
+ });
614
+ }
615
+ function ScrollRestoration(props) {
616
+ useScrollRestoration(props);
617
+ return null;
618
+ }
619
+
620
+ function useAwaited({
621
+ promise
622
+ }) {
623
+ const router = useRouter();
624
+ let state = promise.__deferredState;
625
+ const key = `__TSR__DEFERRED__${state.uid}`;
626
+ if (isDehydratedDeferred(promise)) {
627
+ state = router.hydrateData(key);
628
+ promise = Promise.resolve(state.data);
629
+ promise.__deferredState = state;
630
+ }
631
+ if (state.status === 'pending') {
632
+ throw promise;
633
+ }
634
+ if (state.status === 'error') {
635
+ throw state.error;
636
+ }
637
+ router.dehydrateData(key, state);
638
+ return [state.data];
2817
639
  }
2818
- function Prompt(_ref7) {
2819
- let {
2820
- message,
2821
- when,
2822
- children
2823
- } = _ref7;
2824
- usePrompt(message, when != null ? when : true);
2825
- return children != null ? children : null;
640
+ function Await(props) {
641
+ const awaited = useAwaited(props);
642
+ return props.children(...awaited);
2826
643
  }
2827
644
 
2828
- export { DefaultErrorBoundary, MatchesProvider, Outlet, Prompt, RouterProvider, cleanPath, createBrowserHistory, createHashHistory, createMemoryHistory, createReactRouter, createRoute, createRouteConfig, createRouteMatch, createRouter, decode, defaultParseSearch, defaultStringifySearch, encode, functionalUpdate, interpolatePath, invariant, joinPaths, last, matchByPath, matchPathname, parsePathname, parseSearchWith, pick, replaceEqualDeep, resolvePath, rootRouteId, stringifySearchWith, trimPath, trimPathLeft, trimPathRight, useMatches, usePrompt, useRouter, warning };
645
+ export { Await, Block, ErrorComponent, Link, MatchRoute, Navigate, Outlet, RouterProvider, ScrollRestoration, lazyRouteComponent, matchIdsContext, routerContext, shallow, useAwaited, useBlocker, useDehydrate, useHydrate, useInjectHtml, useLinkProps, useLoader, useMatch, useMatchRoute, useMatches, useNavigate, useParams, useRouteContext, useRouter, useRouterContext, useRouterState, useScrollRestoration, useSearch };
2829
646
  //# sourceMappingURL=index.js.map