@tanstack/react-router 0.0.1-beta.13 → 0.0.1-beta.145

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
  *
@@ -9,2811 +9,593 @@
9
9
  * @license MIT
10
10
  */
11
11
  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';
12
+ import { useStore } from '@tanstack/react-store';
13
+ export { useStore } from '@tanstack/react-store';
14
+ import invariant from 'tiny-invariant';
15
+ import warning from 'tiny-warning';
16
+ import { Route, functionalUpdate, last, pick } from '@tanstack/router-core';
17
+ export * from '@tanstack/router-core';
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
- const data = await routeMatch.options.loader({
1574
- params: routeMatch.params,
1575
- search: routeMatch.routeSearch,
1576
- signal: routeMatch.__.abortController.signal
1577
- });
1578
-
1579
- if (id !== routeMatch.__.latestId) {
1580
- return routeMatch.__.loadPromise;
1581
- }
1582
-
1583
- routeMatch.routeLoaderData = replaceEqualDeep(routeMatch.routeLoaderData, data);
1584
- }
1585
-
1586
- routeMatch.error = undefined;
1587
- routeMatch.status = 'success';
1588
- routeMatch.updatedAt = Date.now();
1589
- 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);
1590
- } catch (err) {
1591
- if (id !== routeMatch.__.latestId) {
1592
- return routeMatch.__.loadPromise;
1593
- }
1594
-
1595
- if (process.env.NODE_ENV !== 'production') {
1596
- console.error(err);
1597
- }
1598
-
1599
- routeMatch.error = err;
1600
- routeMatch.status = 'error';
1601
- routeMatch.updatedAt = Date.now();
1602
- }
1603
- });
1604
-
1605
- try {
1606
- await Promise.all([routeMatch.__.componentsPromise, routeMatch.__.dataPromise]);
1607
-
1608
- if (id !== routeMatch.__.latestId) {
1609
- return routeMatch.__.loadPromise;
1610
- }
1611
- } finally {
1612
- if (id !== routeMatch.__.latestId) {
1613
- return routeMatch.__.loadPromise;
1614
- }
1615
-
1616
- routeMatch.isFetching = false;
1617
-
1618
- routeMatch.__.notify();
1619
- }
1620
- });
1621
- await routeMatch.__.loadPromise;
1622
-
1623
- if (id !== routeMatch.__.latestId) {
1624
- return routeMatch.__.loadPromise;
1625
- }
1626
-
1627
- delete routeMatch.__.loadPromise;
1628
- }
1629
- });
1630
-
1631
- if (!routeMatch.hasLoaders()) {
1632
- routeMatch.status = 'success';
1633
- }
1634
-
1635
- return routeMatch;
1636
- }
1637
-
1638
- const defaultParseSearch = parseSearchWith(JSON.parse);
1639
- const defaultStringifySearch = stringifySearchWith(JSON.stringify);
1640
- function parseSearchWith(parser) {
1641
- return searchStr => {
1642
- if (searchStr.substring(0, 1) === '?') {
1643
- searchStr = searchStr.substring(1);
1644
- }
1645
-
1646
- let query = decode(searchStr); // Try to parse any query params that might be json
1647
-
1648
- for (let key in query) {
1649
- const value = query[key];
1650
-
1651
- if (typeof value === 'string') {
1652
- try {
1653
- query[key] = parser(value);
1654
- } catch (err) {//
1655
- }
1656
- }
1657
- }
1658
-
1659
- return query;
1660
- };
1661
- }
1662
- function stringifySearchWith(stringify) {
1663
- return search => {
1664
- search = _extends({}, search);
1665
-
1666
- if (search) {
1667
- Object.keys(search).forEach(key => {
1668
- const val = search[key];
1669
-
1670
- if (typeof val === 'undefined' || val === undefined) {
1671
- delete search[key];
1672
- } else if (val && typeof val === 'object' && val !== null) {
1673
- try {
1674
- search[key] = stringify(val);
1675
- } catch (err) {// silent
1676
- }
1677
- }
1678
- });
1679
- }
1680
-
1681
- const searchStr = encode(search).toString();
1682
- return searchStr ? "?" + searchStr : '';
1683
- };
1684
- }
1685
-
1686
- var _window$document;
1687
- // Detect if we're in the DOM
1688
- const isServer = typeof window === 'undefined' || !((_window$document = window.document) != null && _window$document.createElement); // This is the default history object if none is defined
1689
-
1690
- const createDefaultHistory = () => isServer ? createMemoryHistory() : createBrowserHistory();
1691
-
1692
- function getInitialRouterState() {
1693
- return {
1694
- status: 'idle',
1695
- location: null,
1696
- matches: [],
1697
- actions: {},
1698
- loaders: {},
1699
- lastUpdated: Date.now(),
1700
- isFetching: false,
1701
- isPreloading: false
1702
- };
1703
- }
1704
-
1705
- function createRouter(userOptions) {
1706
- var _userOptions$stringif, _userOptions$parseSea;
1707
-
1708
- const history = (userOptions == null ? void 0 : userOptions.history) || createDefaultHistory();
1709
-
1710
- const originalOptions = _extends({
1711
- defaultLoaderGcMaxAge: 5 * 60 * 1000,
1712
- defaultLoaderMaxAge: 0,
1713
- defaultPreloadMaxAge: 2000,
1714
- defaultPreloadDelay: 50
1715
- }, userOptions, {
1716
- stringifySearch: (_userOptions$stringif = userOptions == null ? void 0 : userOptions.stringifySearch) != null ? _userOptions$stringif : defaultStringifySearch,
1717
- parseSearch: (_userOptions$parseSea = userOptions == null ? void 0 : userOptions.parseSearch) != null ? _userOptions$parseSea : defaultParseSearch
1718
- });
1719
-
1720
- let router = {
1721
- history,
1722
- options: originalOptions,
1723
- listeners: [],
1724
- // Resolved after construction
1725
- basepath: '',
1726
- routeTree: undefined,
1727
- routesById: {},
1728
- location: undefined,
1729
- allRouteInfo: undefined,
1730
- //
1731
- navigationPromise: Promise.resolve(),
1732
- resolveNavigation: () => {},
1733
- matchCache: {},
1734
- state: getInitialRouterState(),
1735
- reset: () => {
1736
- router.state = getInitialRouterState();
1737
- router.notify();
1738
- },
1739
- startedLoadingAt: Date.now(),
1740
- subscribe: listener => {
1741
- router.listeners.push(listener);
1742
- return () => {
1743
- router.listeners = router.listeners.filter(x => x !== listener);
1744
- };
1745
- },
1746
- getRoute: id => {
1747
- return router.routesById[id];
1748
- },
1749
- notify: () => {
1750
- router.state = _extends({}, router.state, {
1751
- isFetching: router.state.status === 'loading' || router.state.matches.some(d => d.isFetching),
1752
- isPreloading: Object.values(router.matchCache).some(d => d.match.isFetching && !router.state.matches.find(dd => dd.matchId === d.match.matchId))
1753
- });
1754
- cascadeLoaderData(router.state.matches);
1755
- router.listeners.forEach(listener => listener(router));
1756
- },
1757
- dehydrateState: () => {
1758
- return _extends({}, pick(router.state, ['status', 'location', 'lastUpdated']), {
1759
- matches: router.state.matches.map(match => pick(match, ['matchId', 'status', 'routeLoaderData', 'loaderData', 'isInvalid', 'invalidAt']))
1760
- });
1761
- },
1762
- hydrateState: dehydratedState => {
1763
- // Match the routes
1764
- const matches = router.matchRoutes(router.location.pathname, {
1765
- strictParseParams: true
1766
- });
1767
- matches.forEach((match, index) => {
1768
- const dehydratedMatch = dehydratedState.matches[index];
1769
- invariant(dehydratedMatch, 'Oh no! Dehydrated route matches did not match the active state of the router 😬');
1770
- Object.assign(match, dehydratedMatch);
1771
- });
1772
- router.loadMatches(matches);
1773
- router.state = _extends({}, router.state, dehydratedState, {
1774
- matches
1775
- });
1776
- },
1777
- mount: () => {
1778
- const next = router.__.buildLocation({
1779
- to: '.',
1780
- search: true,
1781
- hash: true
1782
- }); // If the current location isn't updated, trigger a navigation
1783
- // to the current location. Otherwise, load the current location.
1784
-
1785
-
1786
- if (next.href !== router.location.href) {
1787
- router.__.commitLocation(next, true);
1788
- } // router.load()
1789
-
1790
-
1791
- const unsub = router.history.listen(event => {
1792
- router.load(router.__.parseLocation(event.location, router.location));
1793
- }); // addEventListener does not exist in React Native, but window does
1794
- // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
1795
-
1796
- if (!isServer && window.addEventListener) {
1797
- // Listen to visibillitychange and focus
1798
- window.addEventListener('visibilitychange', router.onFocus, false);
1799
- window.addEventListener('focus', router.onFocus, false);
1800
- }
1801
-
1802
- return () => {
1803
- unsub();
1804
-
1805
- if (!isServer && window.removeEventListener) {
1806
- // Be sure to unsubscribe if a new handler is set
1807
- window.removeEventListener('visibilitychange', router.onFocus);
1808
- window.removeEventListener('focus', router.onFocus);
1809
- }
1810
- };
1811
- },
1812
- onFocus: () => {
1813
- router.load();
1814
- },
1815
- update: opts => {
1816
- const newHistory = (opts == null ? void 0 : opts.history) !== router.history;
1817
-
1818
- if (!router.location || newHistory) {
1819
- if (opts != null && opts.history) {
1820
- router.history = opts.history;
1821
- }
1822
-
1823
- router.location = router.__.parseLocation(router.history.location);
1824
- router.state.location = router.location;
1825
- }
1826
-
1827
- Object.assign(router.options, opts);
1828
- const {
1829
- basepath,
1830
- routeConfig
1831
- } = router.options;
1832
- router.basepath = cleanPath("/" + (basepath != null ? basepath : ''));
1833
-
1834
- if (routeConfig) {
1835
- router.routesById = {};
1836
- router.routeTree = router.__.buildRouteTree(routeConfig);
1837
- }
1838
-
1839
- return router;
1840
- },
1841
- cancelMatches: () => {
1842
- var _router$state$pending, _router$state$pending2;
1843
- [...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 => {
1844
- match.cancel();
1845
- });
1846
- },
1847
- load: async next => {
1848
- const id = Math.random();
1849
- router.startedLoadingAt = id;
1850
-
1851
- if (next) {
1852
- // Ingest the new location
1853
- router.location = next;
1854
- } // Cancel any pending matches
1855
-
1856
-
1857
- router.cancelMatches(); // Match the routes
1858
-
1859
- const matches = router.matchRoutes(router.location.pathname, {
1860
- strictParseParams: true
1861
- });
1862
-
1863
- if (typeof document !== 'undefined') {
1864
- router.state = _extends({}, router.state, {
1865
- pending: {
1866
- matches: matches,
1867
- location: router.location
1868
- },
1869
- status: 'loading'
1870
- });
1871
- } else {
1872
- router.state = _extends({}, router.state, {
1873
- matches: matches,
1874
- location: router.location,
1875
- status: 'loading'
1876
- });
1877
- }
1878
-
1879
- router.notify(); // Load the matches
1880
-
1881
- await router.loadMatches(matches);
1882
-
1883
- if (router.startedLoadingAt !== id) {
1884
- // Ignore side-effects of match loading
1885
- return router.navigationPromise;
1886
- }
1887
-
1888
- const previousMatches = router.state.matches;
1889
- const exiting = [],
1890
- staying = [];
1891
- previousMatches.forEach(d => {
1892
- if (matches.find(dd => dd.matchId === d.matchId)) {
1893
- staying.push(d);
1894
- } else {
1895
- exiting.push(d);
1896
- }
1897
- });
1898
- const entering = matches.filter(d => {
1899
- return !previousMatches.find(dd => dd.matchId === d.matchId);
1900
- });
1901
- const now = Date.now();
1902
- exiting.forEach(d => {
1903
- var _ref, _d$options$loaderGcMa, _ref2, _d$options$loaderMaxA;
1904
-
1905
- d.__.onExit == null ? void 0 : d.__.onExit({
1906
- params: d.params,
1907
- search: d.routeSearch
1908
- }); // Clear idle error states when match leaves
1909
-
1910
- if (d.status === 'error' && !d.isFetching) {
1911
- d.status = 'idle';
1912
- d.error = undefined;
1913
- }
1914
-
1915
- 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);
1916
-
1917
- if (gc > 0) {
1918
- router.matchCache[d.matchId] = {
1919
- gc: gc == Infinity ? Number.MAX_SAFE_INTEGER : now + gc,
1920
- match: d
1921
- };
1922
- }
1923
- });
1924
- staying.forEach(d => {
1925
- d.options.onTransition == null ? void 0 : d.options.onTransition({
1926
- params: d.params,
1927
- search: d.routeSearch
1928
- });
1929
- });
1930
- entering.forEach(d => {
1931
- d.__.onExit = d.options.onMatch == null ? void 0 : d.options.onMatch({
1932
- params: d.params,
1933
- search: d.search
1934
- });
1935
- delete router.matchCache[d.matchId];
1936
- });
1937
-
1938
- if (router.startedLoadingAt !== id) {
1939
- // Ignore side-effects of match loading
1940
- return;
1941
- }
1942
-
1943
- matches.forEach(match => {
1944
- // Clear actions
1945
- if (match.action) {
1946
- match.action.current = undefined;
1947
- match.action.submissions = [];
1948
- }
1949
- });
1950
- router.state = _extends({}, router.state, {
1951
- location: router.location,
1952
- matches,
1953
- pending: undefined,
1954
- status: 'idle'
1955
- });
1956
- router.notify();
1957
- router.resolveNavigation();
1958
- },
1959
- cleanMatchCache: () => {
1960
- const now = Date.now();
1961
- Object.keys(router.matchCache).forEach(matchId => {
1962
- const entry = router.matchCache[matchId]; // Don't remove loading matches
1963
-
1964
- if (entry.match.status === 'loading') {
1965
- return;
1966
- } // Do not remove successful matches that are still valid
1967
-
1968
-
1969
- if (entry.gc > 0 && entry.gc > now) {
1970
- return;
1971
- } // Everything else gets removed
1972
-
1973
-
1974
- delete router.matchCache[matchId];
1975
- });
1976
- },
1977
- loadRoute: async function loadRoute(navigateOpts) {
1978
- if (navigateOpts === void 0) {
1979
- navigateOpts = router.location;
1980
- }
1981
-
1982
- const next = router.buildNext(navigateOpts);
1983
- const matches = router.matchRoutes(next.pathname, {
1984
- strictParseParams: true
1985
- });
1986
- await router.loadMatches(matches);
1987
- return matches;
1988
- },
1989
- preloadRoute: async function preloadRoute(navigateOpts, loaderOpts) {
1990
- var _ref3, _ref4, _loaderOpts$maxAge, _ref5, _ref6, _loaderOpts$gcMaxAge;
1991
-
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
- preload: true,
2002
- maxAge: (_ref3 = (_ref4 = (_loaderOpts$maxAge = loaderOpts.maxAge) != null ? _loaderOpts$maxAge : router.options.defaultPreloadMaxAge) != null ? _ref4 : router.options.defaultLoaderMaxAge) != null ? _ref3 : 0,
2003
- gcMaxAge: (_ref5 = (_ref6 = (_loaderOpts$gcMaxAge = loaderOpts.gcMaxAge) != null ? _loaderOpts$gcMaxAge : router.options.defaultPreloadGcMaxAge) != null ? _ref6 : router.options.defaultLoaderGcMaxAge) != null ? _ref5 : 0
2004
- });
2005
- return matches;
2006
- },
2007
- matchRoutes: (pathname, opts) => {
2008
- var _router$state$pending3, _router$state$pending4;
2009
-
2010
- router.cleanMatchCache();
2011
- const matches = [];
2012
-
2013
- if (!router.routeTree) {
2014
- return matches;
2015
- }
2016
-
2017
- 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 : [])];
2018
-
2019
- const recurse = async routes => {
2020
- var _parentMatch$params, _router$options$filte, _foundRoute$childRout;
2021
-
2022
- const parentMatch = last(matches);
2023
- let params = (_parentMatch$params = parentMatch == null ? void 0 : parentMatch.params) != null ? _parentMatch$params : {};
2024
- const filteredRoutes = (_router$options$filte = router.options.filterRoutes == null ? void 0 : router.options.filterRoutes(routes)) != null ? _router$options$filte : routes;
2025
- let foundRoutes = [];
2026
-
2027
- const findMatchInRoutes = (parentRoutes, routes) => {
2028
- routes.some(route => {
2029
- var _route$childRoutes, _route$childRoutes2, _route$options$caseSe;
2030
-
2031
- if (!route.routePath && (_route$childRoutes = route.childRoutes) != null && _route$childRoutes.length) {
2032
- return findMatchInRoutes([...foundRoutes, route], route.childRoutes);
2033
- }
2034
-
2035
- const fuzzy = !!(route.routePath !== '/' || (_route$childRoutes2 = route.childRoutes) != null && _route$childRoutes2.length);
2036
- const matchParams = matchPathname(pathname, {
2037
- to: route.fullPath,
2038
- fuzzy,
2039
- caseSensitive: (_route$options$caseSe = route.options.caseSensitive) != null ? _route$options$caseSe : router.options.caseSensitive
2040
- });
2041
-
2042
- if (matchParams) {
2043
- let parsedParams;
2044
-
2045
- try {
2046
- var _route$options$parseP;
2047
-
2048
- parsedParams = (_route$options$parseP = route.options.parseParams == null ? void 0 : route.options.parseParams(matchParams)) != null ? _route$options$parseP : matchParams;
2049
- } catch (err) {
2050
- if (opts != null && opts.strictParseParams) {
2051
- throw err;
2052
- }
2053
- }
2054
-
2055
- params = _extends({}, params, parsedParams);
2056
- }
2057
-
2058
- if (!!matchParams) {
2059
- foundRoutes = [...parentRoutes, route];
2060
- }
2061
-
2062
- return !!foundRoutes.length;
2063
- });
2064
- return !!foundRoutes.length;
2065
- };
2066
-
2067
- findMatchInRoutes([], filteredRoutes);
2068
-
2069
- if (!foundRoutes.length) {
2070
- return;
2071
- }
2072
-
2073
- foundRoutes.forEach(foundRoute => {
2074
- var _router$matchCache$ma;
2075
-
2076
- const interpolatedPath = interpolatePath(foundRoute.routePath, params);
2077
- const matchId = interpolatePath(foundRoute.routeId, params, true);
2078
- const match = existingMatches.find(d => d.matchId === matchId) || ((_router$matchCache$ma = router.matchCache[matchId]) == null ? void 0 : _router$matchCache$ma.match) || createRouteMatch(router, foundRoute, {
2079
- matchId,
2080
- params,
2081
- pathname: joinPaths([pathname, interpolatedPath])
2082
- });
2083
- matches.push(match);
2084
- });
2085
- const foundRoute = last(foundRoutes);
2086
-
2087
- if ((_foundRoute$childRout = foundRoute.childRoutes) != null && _foundRoute$childRout.length) {
2088
- 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];
2089
26
  }
2090
- };
2091
-
2092
- recurse([router.routeTree]);
2093
- cascadeLoaderData(matches);
2094
- return matches;
2095
- },
2096
- loadMatches: async (resolvedMatches, loaderOpts) => {
2097
- const matchPromises = resolvedMatches.map(async match => {
2098
- // Validate the match (loads search params etc)
2099
- match.__.validate();
2100
-
2101
- match.load(loaderOpts);
27
+ }
28
+ }
29
+ return target;
30
+ };
31
+ return _extends.apply(this, arguments);
32
+ }
2102
33
 
2103
- if (match.__.loadPromise) {
2104
- // Wait for the first sign of activity from the match
2105
- await match.__.loadPromise;
2106
- }
34
+ Route.__onInit = route => {
35
+ Object.assign(route, {
36
+ useMatch: (opts = {}) => {
37
+ return useMatch({
38
+ ...opts,
39
+ from: route.id
2107
40
  });
2108
- router.notify();
2109
- await Promise.all(matchPromises);
2110
41
  },
2111
- invalidateRoute: opts => {
2112
- var _router$state$pending5, _router$state$pending6;
2113
-
2114
- const next = router.buildNext(opts);
2115
- const unloadedMatchIds = router.matchRoutes(next.pathname).map(d => d.matchId);
2116
- [...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 => {
2117
- if (unloadedMatchIds.includes(match.matchId)) {
2118
- match.invalidate();
2119
- }
42
+ useLoader: (opts = {}) => {
43
+ return useLoader({
44
+ ...opts,
45
+ from: route.id
2120
46
  });
2121
47
  },
2122
- reload: () => router.__.navigate({
2123
- fromCurrent: true,
2124
- replace: true,
2125
- search: true
2126
- }),
2127
- resolvePath: (from, path) => {
2128
- return resolvePath(router.basepath, from, cleanPath(path));
2129
- },
2130
- matchRoute: (location, opts) => {
2131
- var _location$from;
2132
-
2133
- // const location = router.buildNext(opts)
2134
- location = _extends({}, location, {
2135
- 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?.(d.context) ?? d.context
2136
53
  });
2137
- const next = router.buildNext(location);
2138
-
2139
- if (opts != null && opts.pending) {
2140
- var _router$state$pending7;
2141
-
2142
- if (!((_router$state$pending7 = router.state.pending) != null && _router$state$pending7.location)) {
2143
- return false;
2144
- }
2145
-
2146
- return !!matchPathname(router.state.pending.location.pathname, _extends({}, opts, {
2147
- to: next.pathname
2148
- }));
2149
- }
2150
-
2151
- return !!matchPathname(router.state.location.pathname, _extends({}, opts, {
2152
- to: next.pathname
2153
- }));
2154
54
  },
2155
- navigate: async _ref7 => {
2156
- let {
2157
- from,
2158
- to = '.',
2159
- search,
2160
- hash,
2161
- replace,
2162
- params
2163
- } = _ref7;
2164
- // If this link simply reloads the current route,
2165
- // make sure it has a new key so it will trigger a data refresh
2166
- // If this `to` is a valid external URL, return
2167
- // null for LinkUtils
2168
- const toString = String(to);
2169
- const fromString = String(from);
2170
- let isExternal;
2171
-
2172
- try {
2173
- new URL("" + toString);
2174
- isExternal = true;
2175
- } catch (e) {}
2176
-
2177
- invariant(!isExternal, 'Attempting to navigate to external url with router.navigate!');
2178
- return router.__.navigate({
2179
- from: fromString,
2180
- to: toString,
2181
- search,
2182
- hash,
2183
- replace,
2184
- params
55
+ useRouteContext: (opts = {}) => {
56
+ return useMatch({
57
+ ...opts,
58
+ from: route.id,
59
+ select: d => opts?.select?.(d.routeContext) ?? d.routeContext
2185
60
  });
2186
61
  },
2187
- buildLink: _ref8 => {
2188
- var _preload, _ref9;
2189
-
2190
- let {
2191
- from,
2192
- to = '.',
2193
- search,
2194
- params,
2195
- hash,
2196
- target,
2197
- replace,
2198
- activeOptions,
2199
- preload,
2200
- preloadMaxAge: userPreloadMaxAge,
2201
- preloadGcMaxAge: userPreloadGcMaxAge,
2202
- preloadDelay: userPreloadDelay,
2203
- disabled
2204
- } = _ref8;
2205
-
2206
- // If this link simply reloads the current route,
2207
- // make sure it has a new key so it will trigger a data refresh
2208
- // If this `to` is a valid external URL, return
2209
- // null for LinkUtils
2210
- try {
2211
- new URL("" + to);
2212
- return {
2213
- type: 'external',
2214
- href: to
2215
- };
2216
- } catch (e) {}
2217
-
2218
- const nextOpts = {
2219
- from,
2220
- to,
2221
- search,
2222
- params,
2223
- hash,
2224
- replace
2225
- };
2226
- const next = router.buildNext(nextOpts);
2227
- preload = (_preload = preload) != null ? _preload : router.options.defaultPreload;
2228
- const preloadDelay = (_ref9 = userPreloadDelay != null ? userPreloadDelay : router.options.defaultPreloadDelay) != null ? _ref9 : 0; // Compare path/hash for matches
2229
-
2230
- const pathIsEqual = router.state.location.pathname === next.pathname;
2231
- const currentPathSplit = router.state.location.pathname.split('/');
2232
- const nextPathSplit = next.pathname.split('/');
2233
- const pathIsFuzzyEqual = nextPathSplit.every((d, i) => d === currentPathSplit[i]);
2234
- const hashIsEqual = router.state.location.hash === next.hash; // Combine the matches based on user options
2235
-
2236
- const pathTest = activeOptions != null && activeOptions.exact ? pathIsEqual : pathIsFuzzyEqual;
2237
- const hashTest = activeOptions != null && activeOptions.includeHash ? hashIsEqual : true; // The final "active" test
2238
-
2239
- const isActive = pathTest && hashTest; // The click handler
2240
-
2241
- const handleClick = e => {
2242
- if (!disabled && !isCtrlEvent(e) && !e.defaultPrevented && (!target || target === '_self') && e.button === 0) {
2243
- e.preventDefault();
2244
-
2245
- if (pathIsEqual && !search && !hash) {
2246
- router.invalidateRoute(nextOpts);
2247
- } // All is well? Navigate!)
2248
-
2249
-
2250
- router.__.navigate(nextOpts);
2251
- }
2252
- }; // The click handler
2253
-
2254
-
2255
- const handleFocus = e => {
2256
- if (preload) {
2257
- router.preloadRoute(nextOpts, {
2258
- maxAge: userPreloadMaxAge,
2259
- gcMaxAge: userPreloadGcMaxAge
2260
- });
2261
- }
2262
- };
2263
-
2264
- const handleEnter = e => {
2265
- const target = e.target || {};
2266
-
2267
- if (preload) {
2268
- if (target.preloadTimeout) {
2269
- return;
2270
- }
2271
-
2272
- target.preloadTimeout = setTimeout(() => {
2273
- target.preloadTimeout = null;
2274
- router.preloadRoute(nextOpts, {
2275
- maxAge: userPreloadMaxAge,
2276
- gcMaxAge: userPreloadGcMaxAge
2277
- });
2278
- }, preloadDelay);
2279
- }
2280
- };
2281
-
2282
- const handleLeave = e => {
2283
- const target = e.target || {};
2284
-
2285
- if (target.preloadTimeout) {
2286
- clearTimeout(target.preloadTimeout);
2287
- target.preloadTimeout = null;
2288
- }
2289
- };
2290
-
2291
- return {
2292
- type: 'internal',
2293
- next,
2294
- handleFocus,
2295
- handleClick,
2296
- handleEnter,
2297
- handleLeave,
2298
- isActive,
2299
- disabled
2300
- };
2301
- },
2302
- buildNext: opts => {
2303
- const next = router.__.buildLocation(opts);
2304
-
2305
- const matches = router.matchRoutes(next.pathname);
2306
-
2307
- const __preSearchFilters = matches.map(match => {
2308
- var _match$options$preSea;
2309
-
2310
- return (_match$options$preSea = match.options.preSearchFilters) != null ? _match$options$preSea : [];
2311
- }).flat().filter(Boolean);
2312
-
2313
- const __postSearchFilters = matches.map(match => {
2314
- var _match$options$postSe;
2315
-
2316
- return (_match$options$postSe = match.options.postSearchFilters) != null ? _match$options$postSe : [];
2317
- }).flat().filter(Boolean);
2318
-
2319
- return router.__.buildLocation(_extends({}, opts, {
2320
- __preSearchFilters,
2321
- __postSearchFilters
2322
- }));
62
+ useSearch: (opts = {}) => {
63
+ return useSearch({
64
+ ...opts,
65
+ from: route.id
66
+ });
2323
67
  },
2324
- __: {
2325
- buildRouteTree: rootRouteConfig => {
2326
- const recurseRoutes = (routeConfigs, parent) => {
2327
- return routeConfigs.map(routeConfig => {
2328
- const routeOptions = routeConfig.options;
2329
- const route = createRoute(routeConfig, routeOptions, parent, router);
2330
- const existingRoute = router.routesById[route.routeId];
2331
-
2332
- if (existingRoute) {
2333
- if (process.env.NODE_ENV !== 'production') {
2334
- console.warn("Duplicate routes found with id: " + String(route.routeId), router.routesById, route);
2335
- }
2336
-
2337
- throw new Error();
2338
- }
2339
- router.routesById[route.routeId] = route;
2340
- const children = routeConfig.children;
2341
- route.childRoutes = children != null && children.length ? recurseRoutes(children, route) : undefined;
2342
- return route;
2343
- });
2344
- };
2345
-
2346
- const routes = recurseRoutes([rootRouteConfig]);
2347
- return routes[0];
2348
- },
2349
- parseLocation: (location, previousLocation) => {
2350
- var _location$hash$split$;
2351
-
2352
- const parsedSearch = router.options.parseSearch(location.search);
2353
- return {
2354
- pathname: location.pathname,
2355
- searchStr: location.search,
2356
- search: replaceEqualDeep(previousLocation == null ? void 0 : previousLocation.search, parsedSearch),
2357
- hash: (_location$hash$split$ = location.hash.split('#').reverse()[0]) != null ? _location$hash$split$ : '',
2358
- href: "" + location.pathname + location.search + location.hash,
2359
- state: location.state,
2360
- key: location.key
2361
- };
2362
- },
2363
- navigate: location => {
2364
- const next = router.buildNext(location);
2365
- return router.__.commitLocation(next, location.replace);
2366
- },
2367
- buildLocation: function buildLocation(dest) {
2368
- var _dest$from, _router$basepath, _dest$to, _last, _dest$params, _dest$__preSearchFilt, _functionalUpdate, _dest$__preSearchFilt2, _dest$__postSearchFil;
2369
-
2370
- if (dest === void 0) {
2371
- dest = {};
2372
- }
2373
-
2374
- // const resolvedFrom: Location = {
2375
- // ...router.location,
2376
- const fromPathname = dest.fromCurrent ? router.location.pathname : (_dest$from = dest.from) != null ? _dest$from : router.location.pathname;
2377
-
2378
- let pathname = resolvePath((_router$basepath = router.basepath) != null ? _router$basepath : '/', fromPathname, "" + ((_dest$to = dest.to) != null ? _dest$to : '.'));
2379
-
2380
- const fromMatches = router.matchRoutes(router.location.pathname, {
2381
- strictParseParams: true
2382
- });
2383
- const toMatches = router.matchRoutes(pathname);
2384
-
2385
- const prevParams = _extends({}, (_last = last(fromMatches)) == null ? void 0 : _last.params);
2386
-
2387
- let nextParams = ((_dest$params = dest.params) != null ? _dest$params : true) === true ? prevParams : functionalUpdate(dest.params, prevParams);
2388
-
2389
- if (nextParams) {
2390
- toMatches.map(d => d.options.stringifyParams).filter(Boolean).forEach(fn => {
2391
- Object.assign({}, nextParams, fn(nextParams));
2392
- });
2393
- }
2394
-
2395
- pathname = interpolatePath(pathname, nextParams != null ? nextParams : {}); // Pre filters first
2396
-
2397
- 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
2398
-
2399
- const destSearch = dest.search === true ? preFilteredSearch // Preserve resolvedFrom true
2400
- : dest.search ? (_functionalUpdate = functionalUpdate(dest.search, preFilteredSearch)) != null ? _functionalUpdate : {} // Updater
2401
- : (_dest$__preSearchFilt2 = dest.__preSearchFilters) != null && _dest$__preSearchFilt2.length ? preFilteredSearch // Preserve resolvedFrom filters
2402
- : {}; // Then post filters
2403
-
2404
- const postFilteredSearch = (_dest$__postSearchFil = dest.__postSearchFilters) != null && _dest$__postSearchFil.length ? dest.__postSearchFilters.reduce((prev, next) => next(prev), destSearch) : destSearch;
2405
- const search = replaceEqualDeep(router.location.search, postFilteredSearch);
2406
- const searchStr = router.options.stringifySearch(search);
2407
- let hash = dest.hash === true ? router.location.hash : functionalUpdate(dest.hash, router.location.hash);
2408
- hash = hash ? "#" + hash : '';
2409
- return {
2410
- pathname,
2411
- search,
2412
- searchStr,
2413
- state: router.location.state,
2414
- hash,
2415
- href: "" + pathname + searchStr + hash,
2416
- key: dest.key
2417
- };
2418
- },
2419
- commitLocation: (next, replace) => {
2420
- const id = '' + Date.now() + Math.random();
2421
- if (router.navigateTimeout) clearTimeout(router.navigateTimeout);
2422
- let nextAction = 'replace';
2423
-
2424
- if (!replace) {
2425
- nextAction = 'push';
2426
- }
2427
-
2428
- const isSameUrl = router.__.parseLocation(history.location).href === next.href;
2429
-
2430
- if (isSameUrl && !next.key) {
2431
- nextAction = 'replace';
2432
- }
2433
-
2434
- if (nextAction === 'replace') {
2435
- history.replace({
2436
- pathname: next.pathname,
2437
- hash: next.hash,
2438
- search: next.searchStr
2439
- }, {
2440
- id
2441
- });
2442
- } else {
2443
- history.push({
2444
- pathname: next.pathname,
2445
- hash: next.hash,
2446
- search: next.searchStr
2447
- }, {
2448
- id
2449
- });
2450
- }
2451
-
2452
- router.navigationPromise = new Promise(resolve => {
2453
- const previousNavigationResolve = router.resolveNavigation;
2454
-
2455
- router.resolveNavigation = () => {
2456
- previousNavigationResolve();
2457
- resolve();
2458
- };
2459
- });
2460
- return router.navigationPromise;
2461
- }
68
+ useParams: (opts = {}) => {
69
+ return useParams({
70
+ ...opts,
71
+ from: route.id
72
+ });
2462
73
  }
2463
- };
2464
- router.update(userOptions); // Allow frameworks to hook into the router creation
2465
-
2466
- router.options.createRouter == null ? void 0 : router.options.createRouter(router);
2467
- return router;
2468
- }
2469
-
2470
- function isCtrlEvent(e) {
2471
- return !!(e.metaKey || e.altKey || e.ctrlKey || e.shiftKey);
2472
- }
74
+ });
75
+ };
2473
76
 
2474
- function cascadeLoaderData(matches) {
2475
- matches.forEach((match, index) => {
2476
- const parent = matches[index - 1];
77
+ //
2477
78
 
2478
- if (parent) {
2479
- 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();
2480
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
+ };
2481
93
  });
94
+ lazyComp.preload = load;
95
+ return lazyComp;
2482
96
  }
2483
-
2484
- 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"],
2485
- _excluded2 = ["pending", "caseSensitive", "children"],
2486
- _excluded3 = ["children", "router"];
2487
97
  //
2488
- const matchesContext = /*#__PURE__*/React.createContext(null);
2489
- const routerContext = /*#__PURE__*/React.createContext(null); // Detect if we're in the DOM
2490
-
2491
- const isDOM = Boolean(typeof window !== 'undefined' && window.document && window.document.createElement);
2492
- const useLayoutEffect = isDOM ? React.useLayoutEffect : React.useEffect;
2493
- function MatchesProvider(props) {
2494
- return /*#__PURE__*/React.createElement(matchesContext.Provider, props);
2495
- }
2496
-
2497
- const useRouterSubscription = router => {
2498
- useSyncExternalStore(cb => router.subscribe(() => cb()), () => router.state, () => router.state);
2499
- };
2500
98
 
2501
- function createReactRouter(opts) {
2502
- 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;
2503
135
  return {
2504
- useRoute: function useRoute(subRouteId) {
2505
- if (subRouteId === void 0) {
2506
- subRouteId = '.';
2507
- }
2508
-
2509
- const resolvedRouteId = router.resolvePath(route.routeId, subRouteId);
2510
- const resolvedRoute = router.getRoute(resolvedRouteId);
2511
- useRouterSubscription(router);
2512
- invariant(resolvedRoute, "Could not find a route for route \"" + resolvedRouteId + "\"! Did you forget to add it to your route config?");
2513
- return resolvedRoute;
2514
- },
2515
- linkProps: options => {
2516
- var _functionalUpdate, _functionalUpdate2;
2517
-
2518
- const {
2519
- // custom props
2520
- target,
2521
- activeProps = () => ({
2522
- className: 'active'
2523
- }),
2524
- inactiveProps = () => ({}),
2525
- disabled,
2526
- // element props
2527
- style,
2528
- className,
2529
- onClick,
2530
- onFocus,
2531
- onMouseEnter,
2532
- onMouseLeave
2533
- } = options,
2534
- rest = _objectWithoutPropertiesLoose(options, _excluded);
2535
-
2536
- const linkInfo = route.buildLink(options);
2537
-
2538
- if (linkInfo.type === 'external') {
2539
- const {
2540
- href
2541
- } = linkInfo;
2542
- return {
2543
- href
2544
- };
2545
- }
2546
-
2547
- const {
2548
- handleClick,
2549
- handleFocus,
2550
- handleEnter,
2551
- handleLeave,
2552
- isActive,
2553
- next
2554
- } = linkInfo;
2555
-
2556
- const reactHandleClick = e => {
2557
- React.startTransition(() => {
2558
- handleClick(e);
2559
- });
2560
- };
2561
-
2562
- const composeHandlers = handlers => e => {
2563
- e.persist();
2564
- handlers.forEach(handler => {
2565
- if (handler) handler(e);
2566
- });
2567
- }; // Get the active props
2568
-
2569
-
2570
- const resolvedActiveProps = isActive ? (_functionalUpdate = functionalUpdate(activeProps, {})) != null ? _functionalUpdate : {} : {}; // Get the inactive props
2571
-
2572
- const resolvedInactiveProps = isActive ? {} : (_functionalUpdate2 = functionalUpdate(inactiveProps, {})) != null ? _functionalUpdate2 : {};
2573
- return _extends$2({}, resolvedActiveProps, resolvedInactiveProps, rest, {
2574
- href: disabled ? undefined : next.href,
2575
- onClick: composeHandlers([reactHandleClick, onClick]),
2576
- onFocus: composeHandlers([handleFocus, onFocus]),
2577
- onMouseEnter: composeHandlers([handleEnter, onMouseEnter]),
2578
- onMouseLeave: composeHandlers([handleLeave, onMouseLeave]),
2579
- target,
2580
- style: _extends$2({}, style, resolvedActiveProps.style, resolvedInactiveProps.style),
2581
- className: [className, resolvedActiveProps.className, resolvedInactiveProps.className].filter(Boolean).join(' ') || undefined
2582
- }, disabled ? {
2583
- role: 'link',
2584
- 'aria-disabled': true
2585
- } : undefined, {
2586
- ['data-status']: isActive ? 'active' : undefined
2587
- });
2588
- },
2589
- Link: /*#__PURE__*/React.forwardRef((props, ref) => {
2590
- const linkProps = route.linkProps(props);
2591
- useRouterSubscription(router);
2592
- return /*#__PURE__*/React.createElement("a", _extends$2({
2593
- ref: ref
2594
- }, linkProps, {
2595
- children: typeof props.children === 'function' ? props.children({
2596
- isActive: linkProps['data-status'] === 'active'
2597
- }) : props.children
2598
- }));
2599
- }),
2600
- MatchRoute: opts => {
2601
- const {
2602
- pending,
2603
- caseSensitive
2604
- } = opts,
2605
- rest = _objectWithoutPropertiesLoose(opts, _excluded2);
2606
-
2607
- const params = route.matchRoute(rest, {
2608
- pending,
2609
- caseSensitive
2610
- });
2611
-
2612
- if (!params) {
2613
- return null;
2614
- }
2615
-
2616
- return typeof opts.children === 'function' ? opts.children(params) : opts.children;
2617
- }
136
+ href
2618
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
+ });
2619
161
  };
2620
162
 
2621
- const coreRouter = createRouter(_extends$2({}, opts, {
2622
- createRouter: router => {
2623
- const routerExt = {
2624
- useState: () => {
2625
- useRouterSubscription(router);
2626
- return router.state;
2627
- },
2628
- useMatch: (routeId, opts) => {
2629
- var _useMatches, _opts$strict;
2630
-
2631
- useRouterSubscription(router);
2632
- invariant(routeId !== rootRouteId, "\"" + rootRouteId + "\" cannot be used with useMatch! Did you mean to useRoute(\"" + rootRouteId + "\")?");
2633
- const runtimeMatch = (_useMatches = useMatches()) == null ? void 0 : _useMatches[0];
2634
- const match = router.state.matches.find(d => d.routeId === routeId);
2635
-
2636
- if ((_opts$strict = opts == null ? void 0 : opts.strict) != null ? _opts$strict : true) {
2637
- invariant(match, "Could not find an active match for \"" + routeId + "\"!");
2638
- 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?");
2639
- }
2640
-
2641
- return match;
2642
- }
2643
- };
2644
- const routeExt = makeRouteExt(router.getRoute('/'), router);
2645
- Object.assign(router, routerExt, routeExt);
2646
- },
2647
- createRoute: _ref => {
2648
- let {
2649
- router,
2650
- route
2651
- } = _ref;
2652
- const routeExt = makeRouteExt(route, router);
2653
- Object.assign(route, routeExt);
2654
- },
2655
- loadComponent: async component => {
2656
- if (component.preload && typeof document !== 'undefined') {
2657
- component.preload(); // return await component.preload()
2658
- }
163
+ // Get the active props
164
+ const resolvedActiveProps = isActive ? functionalUpdate(activeProps, {}) ?? {} : {};
2659
165
 
2660
- return component;
2661
- }
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
2662
200
  }));
2663
- 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);
2664
214
  }
2665
- function RouterProvider(_ref2) {
2666
- let {
2667
- children,
2668
- router
2669
- } = _ref2,
2670
- rest = _objectWithoutPropertiesLoose(_ref2, _excluded3);
2671
-
215
+ function RouterProvider({
216
+ router,
217
+ ...rest
218
+ }) {
2672
219
  router.update(rest);
2673
- useRouterSubscription(router);
2674
- useLayoutEffect(() => {
2675
- const unsub = router.mount();
2676
- router.load();
220
+ React.useEffect(() => {
221
+ let unsub;
222
+ React.startTransition(() => {
223
+ unsub = router.mount();
224
+ });
2677
225
  return unsub;
2678
226
  }, [router]);
2679
- return /*#__PURE__*/React.createElement(routerContext.Provider, {
2680
- value: {
2681
- router
227
+ const Wrap = router.options.Wrap || React.Fragment;
228
+ return /*#__PURE__*/React.createElement(React.Suspense, {
229
+ fallback: null
230
+ }, /*#__PURE__*/React.createElement(Wrap, null, /*#__PURE__*/React.createElement(routerContext.Provider, {
231
+ value: router
232
+ }, /*#__PURE__*/React.createElement(Matches, null))));
233
+ }
234
+ function Matches() {
235
+ const router = useRouter();
236
+ const matchIds = useRouterState({
237
+ select: state => {
238
+ const hasPendingComponent = state.pendingMatches.some(d => {
239
+ const route = router.getRoute(d.routeId);
240
+ return !!route?.options.pendingComponent;
241
+ });
242
+ if (hasPendingComponent) {
243
+ console.log('hasPending');
244
+ return state.pendingMatchIds;
245
+ }
246
+ return state.matchIds;
247
+ }
248
+ });
249
+ return /*#__PURE__*/React.createElement(matchIdsContext.Provider, {
250
+ value: [undefined, ...matchIds]
251
+ }, /*#__PURE__*/React.createElement(CatchBoundary, {
252
+ errorComponent: ErrorComponent,
253
+ onCatch: () => {
254
+ warning(false, `Error in router! Consider setting an 'errorComponent' in your RootRoute! 👍`);
2682
255
  }
2683
- }, /*#__PURE__*/React.createElement(MatchesProvider, {
2684
- value: router.state.matches
2685
- }, children != null ? children : /*#__PURE__*/React.createElement(Outlet, null)));
256
+ }, /*#__PURE__*/React.createElement(Outlet, null)));
2686
257
  }
2687
258
  function useRouter() {
2688
259
  const value = React.useContext(routerContext);
2689
- warning(!value, 'useRouter must be used inside a <Router> component!');
2690
- useRouterSubscription(value.router);
2691
- return value.router;
260
+ warning(value, 'useRouter must be used inside a <Router> component!');
261
+ return value;
2692
262
  }
2693
- function useMatches() {
2694
- return React.useContext(matchesContext);
263
+ function useMatches(opts) {
264
+ const matchIds = React.useContext(matchIdsContext);
265
+ return useRouterState({
266
+ select: state => {
267
+ const matches = state.matches.slice(state.matches.findIndex(d => d.id === matchIds[0]));
268
+ return opts?.select?.(matches) ?? matches;
269
+ }
270
+ });
2695
271
  }
2696
- function Outlet() {
2697
- var _ref3, _match$__$pendingComp, _match$__$errorCompon;
2698
-
272
+ function useMatch(opts) {
2699
273
  const router = useRouter();
2700
- const matches = useMatches().slice(1);
2701
- const match = matches[0];
2702
- const defaultPending = React.useCallback(() => null, []);
2703
-
2704
- if (!match) {
2705
- return null;
274
+ const nearestMatchId = React.useContext(matchIdsContext)[0];
275
+ const nearestMatchRouteId = router.getRouteMatch(nearestMatchId)?.routeId;
276
+ const matchRouteId = useRouterState({
277
+ select: state => {
278
+ const matches = state.matches;
279
+ const match = opts?.from ? matches.find(d => d.routeId === opts?.from) : matches.find(d => d.id === nearestMatchId);
280
+ return match.routeId;
281
+ }
282
+ });
283
+ if (opts?.strict ?? true) {
284
+ 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?`);
2706
285
  }
2707
-
2708
- const PendingComponent = (_ref3 = (_match$__$pendingComp = match.__.pendingComponent) != null ? _match$__$pendingComp : router.options.defaultPendingComponent) != null ? _ref3 : defaultPending;
2709
- const errorComponent = (_match$__$errorCompon = match.__.errorComponent) != null ? _match$__$errorCompon : router.options.defaultErrorComponent;
2710
- return /*#__PURE__*/React.createElement(MatchesProvider, {
2711
- value: matches
2712
- }, /*#__PURE__*/React.createElement(React.Suspense, {
2713
- fallback: /*#__PURE__*/React.createElement(PendingComponent, null)
2714
- }, /*#__PURE__*/React.createElement(CatchBoundary, {
2715
- errorComponent: errorComponent
2716
- }, (() => {
2717
- if (match.status === 'error') {
2718
- throw match.error;
286
+ const match = useRouterState({
287
+ select: state => {
288
+ const matches = state.matches;
289
+ const match = opts?.from ? matches.find(d => d.routeId === opts?.from) : matches.find(d => d.id === nearestMatchId);
290
+ invariant(match, `Could not find ${opts?.from ? `an active match from "${opts.from}"` : 'a nearest match!'}`);
291
+ return opts?.select?.(match) ?? match;
2719
292
  }
2720
-
2721
- if (match.status === 'success') {
2722
- var _ref4, _ref5;
2723
-
2724
- return /*#__PURE__*/React.createElement((_ref4 = (_ref5 = match.__.component) != null ? _ref5 : router.options.defaultComponent) != null ? _ref4 : Outlet);
293
+ });
294
+ return match;
295
+ }
296
+ function useLoader(opts) {
297
+ return useMatch({
298
+ ...opts,
299
+ select: match => opts?.select?.(match.loaderData) ?? match.loaderData
300
+ });
301
+ }
302
+ function useRouterContext(opts) {
303
+ return useMatch({
304
+ ...opts,
305
+ select: match => opts?.select?.(match.context) ?? match.context
306
+ });
307
+ }
308
+ function useRouteContext(opts) {
309
+ return useMatch({
310
+ ...opts,
311
+ select: match => opts?.select?.(match.routeContext) ?? match.routeContext
312
+ });
313
+ }
314
+ function useSearch(opts) {
315
+ return useMatch({
316
+ ...opts,
317
+ select: match => {
318
+ return opts?.select?.(match.search) ?? match.search;
2725
319
  }
2726
-
2727
- if (match.__.loadPromise) {
2728
- console.log(match.matchId, 'suspend');
2729
- throw match.__.loadPromise;
320
+ });
321
+ }
322
+ function useParams(opts) {
323
+ return useRouterState({
324
+ select: state => {
325
+ const params = last(state.matches)?.params;
326
+ return opts?.select?.(params) ?? params;
2730
327
  }
2731
-
2732
- invariant(false, 'This should never happen!');
2733
- })())));
328
+ });
2734
329
  }
2735
-
2736
- class CatchBoundary extends React.Component {
2737
- constructor() {
2738
- super(...arguments);
2739
- this.state = {
2740
- error: false
2741
- };
330
+ function useNavigate(defaultOpts) {
331
+ const router = useRouter();
332
+ return React.useCallback(opts => {
333
+ return router.navigate({
334
+ ...defaultOpts,
335
+ ...opts
336
+ });
337
+ }, []);
338
+ }
339
+ function useMatchRoute() {
340
+ const router = useRouter();
341
+ return React.useCallback(opts => {
342
+ const {
343
+ pending,
344
+ caseSensitive,
345
+ ...rest
346
+ } = opts;
347
+ return router.matchRoute(rest, {
348
+ pending,
349
+ caseSensitive
350
+ });
351
+ }, []);
352
+ }
353
+ function MatchRoute(props) {
354
+ const matchRoute = useMatchRoute();
355
+ const params = matchRoute(props);
356
+ if (typeof props.children === 'function') {
357
+ return props.children(params);
358
+ }
359
+ return !!params ? props.children : null;
360
+ }
361
+ function Outlet() {
362
+ const matchIds = React.useContext(matchIdsContext).slice(1);
363
+ if (!matchIds[0]) {
364
+ return null;
365
+ }
366
+ return /*#__PURE__*/React.createElement(Match, {
367
+ matchIds: matchIds
368
+ });
369
+ }
370
+ const defaultPending = () => null;
371
+ function Match({
372
+ matchIds
373
+ }) {
374
+ const router = useRouter();
375
+ const matchId = matchIds[0];
376
+ const routeId = router.getRouteMatch(matchId).routeId;
377
+ const route = router.getRoute(routeId);
378
+ const PendingComponent = route.options.pendingComponent ?? router.options.defaultPendingComponent ?? defaultPending;
379
+ const errorComponent = route.options.errorComponent ?? router.options.defaultErrorComponent ?? ErrorComponent;
380
+ const ResolvedSuspenseBoundary = route.options.wrapInSuspense ?? !route.isRoot ? React.Suspense : SafeFragment;
381
+ const ResolvedCatchBoundary = !!errorComponent ? CatchBoundary : SafeFragment;
382
+ return /*#__PURE__*/React.createElement(matchIdsContext.Provider, {
383
+ value: matchIds
384
+ }, /*#__PURE__*/React.createElement(ResolvedSuspenseBoundary, {
385
+ fallback: /*#__PURE__*/React.createElement(PendingComponent, {
386
+ useLoader: route.useLoader,
387
+ useMatch: route.useMatch,
388
+ useContext: route.useContext,
389
+ useRouteContext: route.useRouteContext,
390
+ useSearch: route.useSearch,
391
+ useParams: route.useParams
392
+ })
393
+ }, /*#__PURE__*/React.createElement(ResolvedCatchBoundary, {
394
+ key: route.id,
395
+ errorComponent: errorComponent,
396
+ onCatch: () => {
397
+ warning(false, `Error in route match: ${matchId}`);
398
+ }
399
+ }, /*#__PURE__*/React.createElement(MatchInner, {
400
+ matchId: matchId,
401
+ PendingComponent: PendingComponent
402
+ }))));
403
+ }
404
+ function MatchInner({
405
+ matchId,
406
+ PendingComponent
407
+ }) {
408
+ const router = useRouter();
409
+ const match = useRouterState({
410
+ select: d => {
411
+ const match = d.matchesById[matchId];
412
+ return pick(match, ['status', 'loadPromise', 'routeId', 'error']);
413
+ }
414
+ });
415
+ const route = router.getRoute(match.routeId);
416
+ if (match.status === 'error') {
417
+ throw match.error;
418
+ }
419
+ if (match.status === 'pending') {
420
+ return /*#__PURE__*/React.createElement(PendingComponent, {
421
+ useLoader: route.useLoader,
422
+ useMatch: route.useMatch,
423
+ useContext: route.useContext,
424
+ useRouteContext: route.useRouteContext,
425
+ useSearch: route.useSearch,
426
+ useParams: route.useParams
427
+ });
2742
428
  }
429
+ if (match.status === 'success') {
430
+ let comp = route.options.component ?? router.options.defaultComponent;
431
+ if (comp) {
432
+ return /*#__PURE__*/React.createElement(comp, {
433
+ useLoader: route.useLoader,
434
+ useMatch: route.useMatch,
435
+ useContext: route.useContext,
436
+ useRouteContext: route.useRouteContext,
437
+ useSearch: route.useSearch,
438
+ useParams: route.useParams
439
+ });
440
+ }
441
+ return /*#__PURE__*/React.createElement(Outlet, null);
442
+ }
443
+ invariant(false, 'Idle routeMatch status encountered during rendering! You should never see this. File an issue!');
444
+ }
445
+ function SafeFragment(props) {
446
+ return /*#__PURE__*/React.createElement(React.Fragment, null, props.children);
447
+ }
448
+ function useInjectHtml() {
449
+ const router = useRouter();
450
+ return React.useCallback(html => {
451
+ router.injectHtml(html);
452
+ }, []);
453
+ }
454
+ function useDehydrate() {
455
+ const router = useRouter();
456
+ return React.useCallback(function dehydrate(key, data) {
457
+ return router.dehydrateData(key, data);
458
+ }, []);
459
+ }
460
+ function useHydrate() {
461
+ const router = useRouter();
462
+ return function hydrate(key) {
463
+ return router.hydrateData(key);
464
+ };
465
+ }
2743
466
 
467
+ // This is the messiest thing ever... I'm either seriously tired (likely) or
468
+ // there has to be a better way to reset error boundaries when the
469
+ // router's location key changes.
470
+
471
+ class CatchBoundary extends React.Component {
472
+ state = {
473
+ error: false,
474
+ info: undefined
475
+ };
2744
476
  componentDidCatch(error, info) {
2745
- console.error(error);
477
+ this.props.onCatch(error, info);
2746
478
  this.setState({
2747
479
  error,
2748
480
  info
2749
481
  });
2750
482
  }
2751
-
2752
483
  render() {
2753
- var _this$props$errorComp;
2754
-
2755
- const errorComponent = (_this$props$errorComp = this.props.errorComponent) != null ? _this$props$errorComp : DefaultErrorBoundary;
2756
-
2757
- if (this.state.error) {
2758
- return /*#__PURE__*/React.createElement(errorComponent, this.state);
484
+ return /*#__PURE__*/React.createElement(CatchBoundaryInner, _extends({}, this.props, {
485
+ errorState: this.state,
486
+ reset: () => this.setState({})
487
+ }));
488
+ }
489
+ }
490
+ function CatchBoundaryInner(props) {
491
+ const locationKey = useRouterState({
492
+ select: d => d.resolvedLocation.key
493
+ });
494
+ const [activeErrorState, setActiveErrorState] = React.useState(props.errorState);
495
+ const errorComponent = props.errorComponent ?? ErrorComponent;
496
+ const prevKeyRef = React.useRef('');
497
+ React.useEffect(() => {
498
+ if (activeErrorState) {
499
+ if (locationKey !== prevKeyRef.current) {
500
+ setActiveErrorState({});
501
+ }
2759
502
  }
2760
-
2761
- return this.props.children;
503
+ prevKeyRef.current = locationKey;
504
+ }, [activeErrorState, locationKey]);
505
+ React.useEffect(() => {
506
+ if (props.errorState.error) {
507
+ setActiveErrorState(props.errorState);
508
+ }
509
+ // props.reset()
510
+ }, [props.errorState.error]);
511
+ if (props.errorState.error && activeErrorState.error) {
512
+ return /*#__PURE__*/React.createElement(errorComponent, activeErrorState);
2762
513
  }
2763
-
514
+ return props.children;
2764
515
  }
2765
-
2766
- function DefaultErrorBoundary(_ref6) {
2767
- let {
2768
- error
2769
- } = _ref6;
516
+ function ErrorComponent({
517
+ error
518
+ }) {
519
+ const [show, setShow] = React.useState(process.env.NODE_ENV !== 'production');
2770
520
  return /*#__PURE__*/React.createElement("div", {
2771
521
  style: {
2772
522
  padding: '.5rem',
2773
523
  maxWidth: '100%'
2774
524
  }
525
+ }, /*#__PURE__*/React.createElement("div", {
526
+ style: {
527
+ display: 'flex',
528
+ alignItems: 'center',
529
+ gap: '.5rem'
530
+ }
2775
531
  }, /*#__PURE__*/React.createElement("strong", {
2776
532
  style: {
2777
- fontSize: '1.2rem'
533
+ fontSize: '1rem'
2778
534
  }
2779
- }, "Something went wrong!"), /*#__PURE__*/React.createElement("div", {
535
+ }, "Something went wrong!"), /*#__PURE__*/React.createElement("button", {
536
+ style: {
537
+ appearance: 'none',
538
+ fontSize: '.6em',
539
+ border: '1px solid currentColor',
540
+ padding: '.1rem .2rem',
541
+ fontWeight: 'bold',
542
+ borderRadius: '.25rem'
543
+ },
544
+ onClick: () => setShow(d => !d)
545
+ }, show ? 'Hide Error' : 'Show Error')), /*#__PURE__*/React.createElement("div", {
2780
546
  style: {
2781
- height: '.5rem'
547
+ height: '.25rem'
2782
548
  }
2783
- }), /*#__PURE__*/React.createElement("div", null, /*#__PURE__*/React.createElement("pre", null, error.message ? /*#__PURE__*/React.createElement("code", {
549
+ }), show ? /*#__PURE__*/React.createElement("div", null, /*#__PURE__*/React.createElement("pre", {
2784
550
  style: {
2785
551
  fontSize: '.7em',
2786
552
  border: '1px solid red',
2787
553
  borderRadius: '.25rem',
2788
- padding: '.5rem',
2789
- color: 'red'
554
+ padding: '.3rem',
555
+ color: 'red',
556
+ overflow: 'auto'
2790
557
  }
2791
- }, error.message) : null)));
558
+ }, error.message ? /*#__PURE__*/React.createElement("code", null, error.message) : null)) : null);
2792
559
  }
2793
- function usePrompt(message, when) {
560
+ function useBlocker(message, condition = true) {
2794
561
  const router = useRouter();
2795
562
  React.useEffect(() => {
2796
- if (!when) return;
2797
- let unblock = router.history.block(transition => {
563
+ if (!condition) return;
564
+ let unblock = router.history.block((retry, cancel) => {
2798
565
  if (window.confirm(message)) {
2799
566
  unblock();
2800
- transition.retry();
2801
- } else {
2802
- router.location.pathname = window.location.pathname;
567
+ retry();
2803
568
  }
2804
569
  });
2805
570
  return unblock;
2806
- }, [when, location, message]);
571
+ });
2807
572
  }
2808
- function Prompt(_ref7) {
2809
- let {
2810
- message,
2811
- when,
2812
- children
2813
- } = _ref7;
2814
- usePrompt(message, when != null ? when : true);
2815
- return children != null ? children : null;
573
+ function Block({
574
+ message,
575
+ condition,
576
+ children
577
+ }) {
578
+ useBlocker(message, condition);
579
+ return children ?? null;
580
+ }
581
+ function shallow(objA, objB) {
582
+ if (Object.is(objA, objB)) {
583
+ return true;
584
+ }
585
+ if (typeof objA !== 'object' || objA === null || typeof objB !== 'object' || objB === null) {
586
+ return false;
587
+ }
588
+ const keysA = Object.keys(objA);
589
+ if (keysA.length !== Object.keys(objB).length) {
590
+ return false;
591
+ }
592
+ for (let i = 0; i < keysA.length; i++) {
593
+ if (!Object.prototype.hasOwnProperty.call(objB, keysA[i]) || !Object.is(objA[keysA[i]], objB[keysA[i]])) {
594
+ return false;
595
+ }
596
+ }
597
+ return true;
2816
598
  }
2817
599
 
2818
- 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 };
600
+ export { Block, ErrorComponent, Link, MatchRoute, Navigate, Outlet, RouterProvider, lazyRouteComponent, matchIdsContext, routerContext, shallow, useBlocker, useDehydrate, useHydrate, useInjectHtml, useLinkProps, useLoader, useMatch, useMatchRoute, useMatches, useNavigate, useParams, useRouteContext, useRouter, useRouterContext, useRouterState, useSearch };
2819
601
  //# sourceMappingURL=index.js.map