@tanstack/react-router 0.0.1-beta.14 → 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,2815 +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
- const isFetching = router.state.status === 'loading' || router.state.matches.some(d => d.isFetching);
1751
- const isPreloading = Object.values(router.matchCache).some(d => d.match.isFetching && !router.state.matches.find(dd => dd.matchId === d.match.matchId));
1752
-
1753
- if (router.state.isFetching !== isFetching || router.state.isPreloading !== isPreloading) {
1754
- router.state = _extends({}, router.state, {
1755
- isFetching,
1756
- isPreloading
1757
- });
1758
- }
1759
-
1760
- cascadeLoaderData(router.state.matches);
1761
- router.listeners.forEach(listener => listener(router));
1762
- },
1763
- dehydrateState: () => {
1764
- return _extends({}, pick(router.state, ['status', 'location', 'lastUpdated']), {
1765
- matches: router.state.matches.map(match => pick(match, ['matchId', 'status', 'routeLoaderData', 'loaderData', 'isInvalid', 'invalidAt']))
1766
- });
1767
- },
1768
- hydrateState: dehydratedState => {
1769
- // Match the routes
1770
- const matches = router.matchRoutes(router.location.pathname, {
1771
- strictParseParams: true
1772
- });
1773
- matches.forEach((match, index) => {
1774
- const dehydratedMatch = dehydratedState.matches[index];
1775
- invariant(dehydratedMatch, 'Oh no! Dehydrated route matches did not match the active state of the router 😬');
1776
- Object.assign(match, dehydratedMatch);
1777
- });
1778
- matches.forEach(match => match.__.validate());
1779
- router.state = _extends({}, router.state, dehydratedState, {
1780
- matches
1781
- });
1782
- },
1783
- mount: () => {
1784
- const next = router.__.buildLocation({
1785
- to: '.',
1786
- search: true,
1787
- hash: true
1788
- }); // If the current location isn't updated, trigger a navigation
1789
- // to the current location. Otherwise, load the current location.
1790
-
1791
-
1792
- if (next.href !== router.location.href) {
1793
- router.__.commitLocation(next, true);
1794
- }
1795
-
1796
- if (!router.state.matches.length) {
1797
- router.load();
1798
- }
1799
-
1800
- const unsub = router.history.listen(event => {
1801
- router.load(router.__.parseLocation(event.location, router.location));
1802
- }); // addEventListener does not exist in React Native, but window does
1803
- // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
1804
-
1805
- if (!isServer && window.addEventListener) {
1806
- // Listen to visibillitychange and focus
1807
- window.addEventListener('visibilitychange', router.onFocus, false);
1808
- window.addEventListener('focus', router.onFocus, false);
1809
- }
1810
-
1811
- return () => {
1812
- unsub();
1813
-
1814
- if (!isServer && window.removeEventListener) {
1815
- // Be sure to unsubscribe if a new handler is set
1816
- window.removeEventListener('visibilitychange', router.onFocus);
1817
- window.removeEventListener('focus', router.onFocus);
1818
- }
1819
- };
1820
- },
1821
- onFocus: () => {
1822
- router.load();
1823
- },
1824
- update: opts => {
1825
- const newHistory = (opts == null ? void 0 : opts.history) !== router.history;
1826
-
1827
- if (!router.location || newHistory) {
1828
- if (opts != null && opts.history) {
1829
- router.history = opts.history;
1830
- }
1831
-
1832
- router.location = router.__.parseLocation(router.history.location);
1833
- router.state.location = router.location;
1834
- }
1835
-
1836
- Object.assign(router.options, opts);
1837
- const {
1838
- basepath,
1839
- routeConfig
1840
- } = router.options;
1841
- router.basepath = cleanPath("/" + (basepath != null ? basepath : ''));
1842
-
1843
- if (routeConfig) {
1844
- router.routesById = {};
1845
- router.routeTree = router.__.buildRouteTree(routeConfig);
1846
- }
1847
-
1848
- return router;
1849
- },
1850
- cancelMatches: () => {
1851
- var _router$state$pending, _router$state$pending2;
1852
- [...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 => {
1853
- match.cancel();
1854
- });
1855
- },
1856
- load: async next => {
1857
- const id = Math.random();
1858
- router.startedLoadingAt = id;
1859
-
1860
- if (next) {
1861
- // Ingest the new location
1862
- router.location = next;
1863
- } // Cancel any pending matches
1864
-
1865
-
1866
- router.cancelMatches(); // Match the routes
1867
-
1868
- const matches = router.matchRoutes(router.location.pathname, {
1869
- strictParseParams: true
1870
- });
1871
-
1872
- if (typeof document !== 'undefined') {
1873
- router.state = _extends({}, router.state, {
1874
- pending: {
1875
- matches: matches,
1876
- location: router.location
1877
- },
1878
- status: 'loading'
1879
- });
1880
- } else {
1881
- router.state = _extends({}, router.state, {
1882
- matches: matches,
1883
- location: router.location,
1884
- status: 'loading'
1885
- });
1886
- }
1887
-
1888
- router.notify(); // Load the matches
1889
-
1890
- await router.loadMatches(matches);
1891
-
1892
- if (router.startedLoadingAt !== id) {
1893
- // Ignore side-effects of match loading
1894
- return router.navigationPromise;
1895
- }
1896
-
1897
- const previousMatches = router.state.matches;
1898
- const exiting = [],
1899
- staying = [];
1900
- previousMatches.forEach(d => {
1901
- if (matches.find(dd => dd.matchId === d.matchId)) {
1902
- staying.push(d);
1903
- } else {
1904
- exiting.push(d);
1905
- }
1906
- });
1907
- const entering = matches.filter(d => {
1908
- return !previousMatches.find(dd => dd.matchId === d.matchId);
1909
- });
1910
- const now = Date.now();
1911
- exiting.forEach(d => {
1912
- var _ref, _d$options$loaderGcMa, _ref2, _d$options$loaderMaxA;
1913
-
1914
- d.__.onExit == null ? void 0 : d.__.onExit({
1915
- params: d.params,
1916
- search: d.routeSearch
1917
- }); // Clear idle error states when match leaves
1918
-
1919
- if (d.status === 'error' && !d.isFetching) {
1920
- d.status = 'idle';
1921
- d.error = undefined;
1922
- }
1923
-
1924
- 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);
1925
-
1926
- if (gc > 0) {
1927
- router.matchCache[d.matchId] = {
1928
- gc: gc == Infinity ? Number.MAX_SAFE_INTEGER : now + gc,
1929
- match: d
1930
- };
1931
- }
1932
- });
1933
- staying.forEach(d => {
1934
- d.options.onTransition == null ? void 0 : d.options.onTransition({
1935
- params: d.params,
1936
- search: d.routeSearch
1937
- });
1938
- });
1939
- entering.forEach(d => {
1940
- d.__.onExit = d.options.onMatch == null ? void 0 : d.options.onMatch({
1941
- params: d.params,
1942
- search: d.search
1943
- });
1944
- delete router.matchCache[d.matchId];
1945
- });
1946
-
1947
- if (router.startedLoadingAt !== id) {
1948
- // Ignore side-effects of match loading
1949
- return;
1950
- }
1951
-
1952
- matches.forEach(match => {
1953
- // Clear actions
1954
- if (match.action) {
1955
- match.action.current = undefined;
1956
- match.action.submissions = [];
1957
- }
1958
- });
1959
- router.state = _extends({}, router.state, {
1960
- location: router.location,
1961
- matches,
1962
- pending: undefined,
1963
- status: 'idle'
1964
- });
1965
- router.notify();
1966
- router.resolveNavigation();
1967
- },
1968
- cleanMatchCache: () => {
1969
- const now = Date.now();
1970
- Object.keys(router.matchCache).forEach(matchId => {
1971
- const entry = router.matchCache[matchId]; // Don't remove loading matches
1972
-
1973
- if (entry.match.status === 'loading') {
1974
- return;
1975
- } // Do not remove successful matches that are still valid
1976
-
1977
-
1978
- if (entry.gc > 0 && entry.gc > now) {
1979
- return;
1980
- } // Everything else gets removed
1981
-
1982
-
1983
- delete router.matchCache[matchId];
1984
- });
1985
- },
1986
- loadRoute: async function loadRoute(navigateOpts) {
1987
- if (navigateOpts === void 0) {
1988
- navigateOpts = router.location;
1989
- }
1990
-
1991
- const next = router.buildNext(navigateOpts);
1992
- const matches = router.matchRoutes(next.pathname, {
1993
- strictParseParams: true
1994
- });
1995
- await router.loadMatches(matches);
1996
- return matches;
1997
- },
1998
- preloadRoute: async function preloadRoute(navigateOpts, loaderOpts) {
1999
- var _ref3, _ref4, _loaderOpts$maxAge, _ref5, _ref6, _loaderOpts$gcMaxAge;
2000
-
2001
- if (navigateOpts === void 0) {
2002
- navigateOpts = router.location;
2003
- }
2004
-
2005
- const next = router.buildNext(navigateOpts);
2006
- const matches = router.matchRoutes(next.pathname, {
2007
- strictParseParams: true
2008
- });
2009
- await router.loadMatches(matches, {
2010
- preload: true,
2011
- maxAge: (_ref3 = (_ref4 = (_loaderOpts$maxAge = loaderOpts.maxAge) != null ? _loaderOpts$maxAge : router.options.defaultPreloadMaxAge) != null ? _ref4 : router.options.defaultLoaderMaxAge) != null ? _ref3 : 0,
2012
- gcMaxAge: (_ref5 = (_ref6 = (_loaderOpts$gcMaxAge = loaderOpts.gcMaxAge) != null ? _loaderOpts$gcMaxAge : router.options.defaultPreloadGcMaxAge) != null ? _ref6 : router.options.defaultLoaderGcMaxAge) != null ? _ref5 : 0
2013
- });
2014
- return matches;
2015
- },
2016
- matchRoutes: (pathname, opts) => {
2017
- var _router$state$pending3, _router$state$pending4;
2018
-
2019
- router.cleanMatchCache();
2020
- const matches = [];
2021
-
2022
- if (!router.routeTree) {
2023
- return matches;
2024
- }
2025
-
2026
- 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 : [])];
2027
-
2028
- const recurse = async routes => {
2029
- var _parentMatch$params, _router$options$filte, _foundRoute$childRout;
2030
-
2031
- const parentMatch = last(matches);
2032
- let params = (_parentMatch$params = parentMatch == null ? void 0 : parentMatch.params) != null ? _parentMatch$params : {};
2033
- const filteredRoutes = (_router$options$filte = router.options.filterRoutes == null ? void 0 : router.options.filterRoutes(routes)) != null ? _router$options$filte : routes;
2034
- let foundRoutes = [];
2035
-
2036
- const findMatchInRoutes = (parentRoutes, routes) => {
2037
- routes.some(route => {
2038
- var _route$childRoutes, _route$childRoutes2, _route$options$caseSe;
2039
-
2040
- if (!route.routePath && (_route$childRoutes = route.childRoutes) != null && _route$childRoutes.length) {
2041
- return findMatchInRoutes([...foundRoutes, route], route.childRoutes);
2042
- }
2043
-
2044
- const fuzzy = !!(route.routePath !== '/' || (_route$childRoutes2 = route.childRoutes) != null && _route$childRoutes2.length);
2045
- const matchParams = matchPathname(pathname, {
2046
- to: route.fullPath,
2047
- fuzzy,
2048
- caseSensitive: (_route$options$caseSe = route.options.caseSensitive) != null ? _route$options$caseSe : router.options.caseSensitive
2049
- });
2050
-
2051
- if (matchParams) {
2052
- let parsedParams;
2053
-
2054
- try {
2055
- var _route$options$parseP;
2056
-
2057
- parsedParams = (_route$options$parseP = route.options.parseParams == null ? void 0 : route.options.parseParams(matchParams)) != null ? _route$options$parseP : matchParams;
2058
- } catch (err) {
2059
- if (opts != null && opts.strictParseParams) {
2060
- throw err;
2061
- }
2062
- }
2063
-
2064
- params = _extends({}, params, parsedParams);
2065
- }
2066
-
2067
- if (!!matchParams) {
2068
- foundRoutes = [...parentRoutes, route];
2069
- }
2070
-
2071
- return !!foundRoutes.length;
2072
- });
2073
- return !!foundRoutes.length;
2074
- };
2075
-
2076
- findMatchInRoutes([], filteredRoutes);
2077
-
2078
- if (!foundRoutes.length) {
2079
- return;
2080
- }
2081
-
2082
- foundRoutes.forEach(foundRoute => {
2083
- var _router$matchCache$ma;
2084
-
2085
- const interpolatedPath = interpolatePath(foundRoute.routePath, params);
2086
- const matchId = interpolatePath(foundRoute.routeId, params, true);
2087
- const match = existingMatches.find(d => d.matchId === matchId) || ((_router$matchCache$ma = router.matchCache[matchId]) == null ? void 0 : _router$matchCache$ma.match) || createRouteMatch(router, foundRoute, {
2088
- matchId,
2089
- params,
2090
- pathname: joinPaths([pathname, interpolatedPath])
2091
- });
2092
- matches.push(match);
2093
- });
2094
- const foundRoute = last(foundRoutes);
2095
-
2096
- if ((_foundRoute$childRout = foundRoute.childRoutes) != null && _foundRoute$childRout.length) {
2097
- 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];
2098
26
  }
2099
- };
2100
-
2101
- recurse([router.routeTree]);
2102
- cascadeLoaderData(matches);
2103
- return matches;
2104
- },
2105
- loadMatches: async (resolvedMatches, loaderOpts) => {
2106
- const matchPromises = resolvedMatches.map(async match => {
2107
- // Validate the match (loads search params etc)
2108
- match.__.validate();
2109
-
2110
- match.load(loaderOpts);
27
+ }
28
+ }
29
+ return target;
30
+ };
31
+ return _extends.apply(this, arguments);
32
+ }
2111
33
 
2112
- if (match.__.loadPromise) {
2113
- // Wait for the first sign of activity from the match
2114
- await match.__.loadPromise;
2115
- }
34
+ Route.__onInit = route => {
35
+ Object.assign(route, {
36
+ useMatch: (opts = {}) => {
37
+ return useMatch({
38
+ ...opts,
39
+ from: route.id
2116
40
  });
2117
- router.notify();
2118
- await Promise.all(matchPromises);
2119
41
  },
2120
- invalidateRoute: opts => {
2121
- var _router$state$pending5, _router$state$pending6;
2122
-
2123
- const next = router.buildNext(opts);
2124
- const unloadedMatchIds = router.matchRoutes(next.pathname).map(d => d.matchId);
2125
- [...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 => {
2126
- if (unloadedMatchIds.includes(match.matchId)) {
2127
- match.invalidate();
2128
- }
42
+ useLoader: (opts = {}) => {
43
+ return useLoader({
44
+ ...opts,
45
+ from: route.id
2129
46
  });
2130
47
  },
2131
- reload: () => router.__.navigate({
2132
- fromCurrent: true,
2133
- replace: true,
2134
- search: true
2135
- }),
2136
- resolvePath: (from, path) => {
2137
- return resolvePath(router.basepath, from, cleanPath(path));
2138
- },
2139
- matchRoute: (location, opts) => {
2140
- var _location$from;
2141
-
2142
- // const location = router.buildNext(opts)
2143
- location = _extends({}, location, {
2144
- 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
2145
53
  });
2146
- const next = router.buildNext(location);
2147
-
2148
- if (opts != null && opts.pending) {
2149
- var _router$state$pending7;
2150
-
2151
- if (!((_router$state$pending7 = router.state.pending) != null && _router$state$pending7.location)) {
2152
- return false;
2153
- }
2154
-
2155
- return !!matchPathname(router.state.pending.location.pathname, _extends({}, opts, {
2156
- to: next.pathname
2157
- }));
2158
- }
2159
-
2160
- return !!matchPathname(router.state.location.pathname, _extends({}, opts, {
2161
- to: next.pathname
2162
- }));
2163
54
  },
2164
- navigate: async _ref7 => {
2165
- let {
2166
- from,
2167
- to = '.',
2168
- search,
2169
- hash,
2170
- replace,
2171
- params
2172
- } = _ref7;
2173
- // If this link simply reloads the current route,
2174
- // make sure it has a new key so it will trigger a data refresh
2175
- // If this `to` is a valid external URL, return
2176
- // null for LinkUtils
2177
- const toString = String(to);
2178
- const fromString = String(from);
2179
- let isExternal;
2180
-
2181
- try {
2182
- new URL("" + toString);
2183
- isExternal = true;
2184
- } catch (e) {}
2185
-
2186
- invariant(!isExternal, 'Attempting to navigate to external url with router.navigate!');
2187
- return router.__.navigate({
2188
- from: fromString,
2189
- to: toString,
2190
- search,
2191
- hash,
2192
- replace,
2193
- params
55
+ useRouteContext: (opts = {}) => {
56
+ return useMatch({
57
+ ...opts,
58
+ from: route.id,
59
+ select: d => opts?.select?.(d.routeContext) ?? d.routeContext
2194
60
  });
2195
61
  },
2196
- buildLink: _ref8 => {
2197
- var _preload, _ref9;
2198
-
2199
- let {
2200
- from,
2201
- to = '.',
2202
- search,
2203
- params,
2204
- hash,
2205
- target,
2206
- replace,
2207
- activeOptions,
2208
- preload,
2209
- preloadMaxAge: userPreloadMaxAge,
2210
- preloadGcMaxAge: userPreloadGcMaxAge,
2211
- preloadDelay: userPreloadDelay,
2212
- disabled
2213
- } = _ref8;
2214
-
2215
- // If this link simply reloads the current route,
2216
- // make sure it has a new key so it will trigger a data refresh
2217
- // If this `to` is a valid external URL, return
2218
- // null for LinkUtils
2219
- try {
2220
- new URL("" + to);
2221
- return {
2222
- type: 'external',
2223
- href: to
2224
- };
2225
- } catch (e) {}
2226
-
2227
- const nextOpts = {
2228
- from,
2229
- to,
2230
- search,
2231
- params,
2232
- hash,
2233
- replace
2234
- };
2235
- const next = router.buildNext(nextOpts);
2236
- preload = (_preload = preload) != null ? _preload : router.options.defaultPreload;
2237
- const preloadDelay = (_ref9 = userPreloadDelay != null ? userPreloadDelay : router.options.defaultPreloadDelay) != null ? _ref9 : 0; // Compare path/hash for matches
2238
-
2239
- const pathIsEqual = router.state.location.pathname === next.pathname;
2240
- const currentPathSplit = router.state.location.pathname.split('/');
2241
- const nextPathSplit = next.pathname.split('/');
2242
- const pathIsFuzzyEqual = nextPathSplit.every((d, i) => d === currentPathSplit[i]);
2243
- const hashIsEqual = router.state.location.hash === next.hash; // Combine the matches based on user options
2244
-
2245
- const pathTest = activeOptions != null && activeOptions.exact ? pathIsEqual : pathIsFuzzyEqual;
2246
- const hashTest = activeOptions != null && activeOptions.includeHash ? hashIsEqual : true; // The final "active" test
2247
-
2248
- const isActive = pathTest && hashTest; // The click handler
2249
-
2250
- const handleClick = e => {
2251
- if (!disabled && !isCtrlEvent(e) && !e.defaultPrevented && (!target || target === '_self') && e.button === 0) {
2252
- e.preventDefault();
2253
-
2254
- if (pathIsEqual && !search && !hash) {
2255
- router.invalidateRoute(nextOpts);
2256
- } // All is well? Navigate!)
2257
-
2258
-
2259
- router.__.navigate(nextOpts);
2260
- }
2261
- }; // The click handler
2262
-
2263
-
2264
- const handleFocus = e => {
2265
- if (preload) {
2266
- router.preloadRoute(nextOpts, {
2267
- maxAge: userPreloadMaxAge,
2268
- gcMaxAge: userPreloadGcMaxAge
2269
- });
2270
- }
2271
- };
2272
-
2273
- const handleEnter = e => {
2274
- const target = e.target || {};
2275
-
2276
- if (preload) {
2277
- if (target.preloadTimeout) {
2278
- return;
2279
- }
2280
-
2281
- target.preloadTimeout = setTimeout(() => {
2282
- target.preloadTimeout = null;
2283
- router.preloadRoute(nextOpts, {
2284
- maxAge: userPreloadMaxAge,
2285
- gcMaxAge: userPreloadGcMaxAge
2286
- });
2287
- }, preloadDelay);
2288
- }
2289
- };
2290
-
2291
- const handleLeave = e => {
2292
- const target = e.target || {};
2293
-
2294
- if (target.preloadTimeout) {
2295
- clearTimeout(target.preloadTimeout);
2296
- target.preloadTimeout = null;
2297
- }
2298
- };
2299
-
2300
- return {
2301
- type: 'internal',
2302
- next,
2303
- handleFocus,
2304
- handleClick,
2305
- handleEnter,
2306
- handleLeave,
2307
- isActive,
2308
- disabled
2309
- };
2310
- },
2311
- buildNext: opts => {
2312
- const next = router.__.buildLocation(opts);
2313
-
2314
- const matches = router.matchRoutes(next.pathname);
2315
-
2316
- const __preSearchFilters = matches.map(match => {
2317
- var _match$options$preSea;
2318
-
2319
- return (_match$options$preSea = match.options.preSearchFilters) != null ? _match$options$preSea : [];
2320
- }).flat().filter(Boolean);
2321
-
2322
- const __postSearchFilters = matches.map(match => {
2323
- var _match$options$postSe;
2324
-
2325
- return (_match$options$postSe = match.options.postSearchFilters) != null ? _match$options$postSe : [];
2326
- }).flat().filter(Boolean);
2327
-
2328
- return router.__.buildLocation(_extends({}, opts, {
2329
- __preSearchFilters,
2330
- __postSearchFilters
2331
- }));
62
+ useSearch: (opts = {}) => {
63
+ return useSearch({
64
+ ...opts,
65
+ from: route.id
66
+ });
2332
67
  },
2333
- __: {
2334
- buildRouteTree: rootRouteConfig => {
2335
- const recurseRoutes = (routeConfigs, parent) => {
2336
- return routeConfigs.map(routeConfig => {
2337
- const routeOptions = routeConfig.options;
2338
- const route = createRoute(routeConfig, routeOptions, parent, router);
2339
- const existingRoute = router.routesById[route.routeId];
2340
-
2341
- if (existingRoute) {
2342
- if (process.env.NODE_ENV !== 'production') {
2343
- console.warn("Duplicate routes found with id: " + String(route.routeId), router.routesById, route);
2344
- }
2345
-
2346
- throw new Error();
2347
- }
2348
- router.routesById[route.routeId] = route;
2349
- const children = routeConfig.children;
2350
- route.childRoutes = children != null && children.length ? recurseRoutes(children, route) : undefined;
2351
- return route;
2352
- });
2353
- };
2354
-
2355
- const routes = recurseRoutes([rootRouteConfig]);
2356
- return routes[0];
2357
- },
2358
- parseLocation: (location, previousLocation) => {
2359
- var _location$hash$split$;
2360
-
2361
- const parsedSearch = router.options.parseSearch(location.search);
2362
- return {
2363
- pathname: location.pathname,
2364
- searchStr: location.search,
2365
- search: replaceEqualDeep(previousLocation == null ? void 0 : previousLocation.search, parsedSearch),
2366
- hash: (_location$hash$split$ = location.hash.split('#').reverse()[0]) != null ? _location$hash$split$ : '',
2367
- href: "" + location.pathname + location.search + location.hash,
2368
- state: location.state,
2369
- key: location.key
2370
- };
2371
- },
2372
- navigate: location => {
2373
- const next = router.buildNext(location);
2374
- return router.__.commitLocation(next, location.replace);
2375
- },
2376
- buildLocation: function buildLocation(dest) {
2377
- var _dest$from, _router$basepath, _dest$to, _last, _dest$params, _dest$__preSearchFilt, _functionalUpdate, _dest$__preSearchFilt2, _dest$__postSearchFil;
2378
-
2379
- if (dest === void 0) {
2380
- dest = {};
2381
- }
2382
-
2383
- // const resolvedFrom: Location = {
2384
- // ...router.location,
2385
- const fromPathname = dest.fromCurrent ? router.location.pathname : (_dest$from = dest.from) != null ? _dest$from : router.location.pathname;
2386
-
2387
- let pathname = resolvePath((_router$basepath = router.basepath) != null ? _router$basepath : '/', fromPathname, "" + ((_dest$to = dest.to) != null ? _dest$to : '.'));
2388
-
2389
- const fromMatches = router.matchRoutes(router.location.pathname, {
2390
- strictParseParams: true
2391
- });
2392
- const toMatches = router.matchRoutes(pathname);
2393
-
2394
- const prevParams = _extends({}, (_last = last(fromMatches)) == null ? void 0 : _last.params);
2395
-
2396
- let nextParams = ((_dest$params = dest.params) != null ? _dest$params : true) === true ? prevParams : functionalUpdate(dest.params, prevParams);
2397
-
2398
- if (nextParams) {
2399
- toMatches.map(d => d.options.stringifyParams).filter(Boolean).forEach(fn => {
2400
- Object.assign({}, nextParams, fn(nextParams));
2401
- });
2402
- }
2403
-
2404
- pathname = interpolatePath(pathname, nextParams != null ? nextParams : {}); // Pre filters first
2405
-
2406
- 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
2407
-
2408
- const destSearch = dest.search === true ? preFilteredSearch // Preserve resolvedFrom true
2409
- : dest.search ? (_functionalUpdate = functionalUpdate(dest.search, preFilteredSearch)) != null ? _functionalUpdate : {} // Updater
2410
- : (_dest$__preSearchFilt2 = dest.__preSearchFilters) != null && _dest$__preSearchFilt2.length ? preFilteredSearch // Preserve resolvedFrom filters
2411
- : {}; // Then post filters
2412
-
2413
- const postFilteredSearch = (_dest$__postSearchFil = dest.__postSearchFilters) != null && _dest$__postSearchFil.length ? dest.__postSearchFilters.reduce((prev, next) => next(prev), destSearch) : destSearch;
2414
- const search = replaceEqualDeep(router.location.search, postFilteredSearch);
2415
- const searchStr = router.options.stringifySearch(search);
2416
- let hash = dest.hash === true ? router.location.hash : functionalUpdate(dest.hash, router.location.hash);
2417
- hash = hash ? "#" + hash : '';
2418
- return {
2419
- pathname,
2420
- search,
2421
- searchStr,
2422
- state: router.location.state,
2423
- hash,
2424
- href: "" + pathname + searchStr + hash,
2425
- key: dest.key
2426
- };
2427
- },
2428
- commitLocation: (next, replace) => {
2429
- const id = '' + Date.now() + Math.random();
2430
- if (router.navigateTimeout) clearTimeout(router.navigateTimeout);
2431
- let nextAction = 'replace';
2432
-
2433
- if (!replace) {
2434
- nextAction = 'push';
2435
- }
2436
-
2437
- const isSameUrl = router.__.parseLocation(history.location).href === next.href;
2438
-
2439
- if (isSameUrl && !next.key) {
2440
- nextAction = 'replace';
2441
- }
2442
-
2443
- if (nextAction === 'replace') {
2444
- history.replace({
2445
- pathname: next.pathname,
2446
- hash: next.hash,
2447
- search: next.searchStr
2448
- }, {
2449
- id
2450
- });
2451
- } else {
2452
- history.push({
2453
- pathname: next.pathname,
2454
- hash: next.hash,
2455
- search: next.searchStr
2456
- }, {
2457
- id
2458
- });
2459
- }
2460
-
2461
- router.navigationPromise = new Promise(resolve => {
2462
- const previousNavigationResolve = router.resolveNavigation;
2463
-
2464
- router.resolveNavigation = () => {
2465
- previousNavigationResolve();
2466
- resolve();
2467
- };
2468
- });
2469
- return router.navigationPromise;
2470
- }
68
+ useParams: (opts = {}) => {
69
+ return useParams({
70
+ ...opts,
71
+ from: route.id
72
+ });
2471
73
  }
2472
- };
2473
- router.update(userOptions); // Allow frameworks to hook into the router creation
2474
-
2475
- router.options.createRouter == null ? void 0 : router.options.createRouter(router);
2476
- return router;
2477
- }
2478
-
2479
- function isCtrlEvent(e) {
2480
- return !!(e.metaKey || e.altKey || e.ctrlKey || e.shiftKey);
2481
- }
74
+ });
75
+ };
2482
76
 
2483
- function cascadeLoaderData(matches) {
2484
- matches.forEach((match, index) => {
2485
- const parent = matches[index - 1];
77
+ //
2486
78
 
2487
- if (parent) {
2488
- 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();
2489
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
+ };
2490
93
  });
94
+ lazyComp.preload = load;
95
+ return lazyComp;
2491
96
  }
2492
-
2493
- 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"],
2494
- _excluded2 = ["pending", "caseSensitive", "children"],
2495
- _excluded3 = ["children", "router"];
2496
97
  //
2497
- const matchesContext = /*#__PURE__*/React.createContext(null);
2498
- const routerContext = /*#__PURE__*/React.createContext(null); // Detect if we're in the DOM
2499
- function MatchesProvider(props) {
2500
- return /*#__PURE__*/React.createElement(matchesContext.Provider, props);
2501
- }
2502
-
2503
- const useRouterSubscription = router => {
2504
- useSyncExternalStore(cb => router.subscribe(() => cb()), () => router.state, () => router.state);
2505
- };
2506
98
 
2507
- function createReactRouter(opts) {
2508
- 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;
2509
135
  return {
2510
- useRoute: function useRoute(subRouteId) {
2511
- if (subRouteId === void 0) {
2512
- subRouteId = '.';
2513
- }
2514
-
2515
- const resolvedRouteId = router.resolvePath(route.routeId, subRouteId);
2516
- const resolvedRoute = router.getRoute(resolvedRouteId);
2517
- useRouterSubscription(router);
2518
- invariant(resolvedRoute, "Could not find a route for route \"" + resolvedRouteId + "\"! Did you forget to add it to your route config?");
2519
- return resolvedRoute;
2520
- },
2521
- linkProps: options => {
2522
- var _functionalUpdate, _functionalUpdate2;
2523
-
2524
- const {
2525
- // custom props
2526
- target,
2527
- activeProps = () => ({
2528
- className: 'active'
2529
- }),
2530
- inactiveProps = () => ({}),
2531
- disabled,
2532
- // element props
2533
- style,
2534
- className,
2535
- onClick,
2536
- onFocus,
2537
- onMouseEnter,
2538
- onMouseLeave
2539
- } = options,
2540
- rest = _objectWithoutPropertiesLoose(options, _excluded);
2541
-
2542
- const linkInfo = route.buildLink(options);
2543
-
2544
- if (linkInfo.type === 'external') {
2545
- const {
2546
- href
2547
- } = linkInfo;
2548
- return {
2549
- href
2550
- };
2551
- }
2552
-
2553
- const {
2554
- handleClick,
2555
- handleFocus,
2556
- handleEnter,
2557
- handleLeave,
2558
- isActive,
2559
- next
2560
- } = linkInfo;
2561
-
2562
- const reactHandleClick = e => {
2563
- React.startTransition(() => {
2564
- handleClick(e);
2565
- });
2566
- };
2567
-
2568
- const composeHandlers = handlers => e => {
2569
- e.persist();
2570
- handlers.forEach(handler => {
2571
- if (handler) handler(e);
2572
- });
2573
- }; // Get the active props
2574
-
2575
-
2576
- const resolvedActiveProps = isActive ? (_functionalUpdate = functionalUpdate(activeProps, {})) != null ? _functionalUpdate : {} : {}; // Get the inactive props
2577
-
2578
- const resolvedInactiveProps = isActive ? {} : (_functionalUpdate2 = functionalUpdate(inactiveProps, {})) != null ? _functionalUpdate2 : {};
2579
- return _extends$2({}, resolvedActiveProps, resolvedInactiveProps, rest, {
2580
- href: disabled ? undefined : next.href,
2581
- onClick: composeHandlers([reactHandleClick, onClick]),
2582
- onFocus: composeHandlers([handleFocus, onFocus]),
2583
- onMouseEnter: composeHandlers([handleEnter, onMouseEnter]),
2584
- onMouseLeave: composeHandlers([handleLeave, onMouseLeave]),
2585
- target,
2586
- style: _extends$2({}, style, resolvedActiveProps.style, resolvedInactiveProps.style),
2587
- className: [className, resolvedActiveProps.className, resolvedInactiveProps.className].filter(Boolean).join(' ') || undefined
2588
- }, disabled ? {
2589
- role: 'link',
2590
- 'aria-disabled': true
2591
- } : undefined, {
2592
- ['data-status']: isActive ? 'active' : undefined
2593
- });
2594
- },
2595
- Link: /*#__PURE__*/React.forwardRef((props, ref) => {
2596
- const linkProps = route.linkProps(props);
2597
- useRouterSubscription(router);
2598
- return /*#__PURE__*/React.createElement("a", _extends$2({
2599
- ref: ref
2600
- }, linkProps, {
2601
- children: typeof props.children === 'function' ? props.children({
2602
- isActive: linkProps['data-status'] === 'active'
2603
- }) : props.children
2604
- }));
2605
- }),
2606
- MatchRoute: opts => {
2607
- const {
2608
- pending,
2609
- caseSensitive
2610
- } = opts,
2611
- rest = _objectWithoutPropertiesLoose(opts, _excluded2);
2612
-
2613
- const params = route.matchRoute(rest, {
2614
- pending,
2615
- caseSensitive
2616
- });
2617
-
2618
- if (!params) {
2619
- return null;
2620
- }
2621
-
2622
- return typeof opts.children === 'function' ? opts.children(params) : opts.children;
2623
- }
136
+ href
2624
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
+ });
2625
161
  };
2626
162
 
2627
- const coreRouter = createRouter(_extends$2({}, opts, {
2628
- createRouter: router => {
2629
- const routerExt = {
2630
- useState: () => {
2631
- useRouterSubscription(router);
2632
- return router.state;
2633
- },
2634
- useMatch: (routeId, opts) => {
2635
- var _useMatches, _opts$strict;
2636
-
2637
- useRouterSubscription(router);
2638
- invariant(routeId !== rootRouteId, "\"" + rootRouteId + "\" cannot be used with useMatch! Did you mean to useRoute(\"" + rootRouteId + "\")?");
2639
- const runtimeMatch = (_useMatches = useMatches()) == null ? void 0 : _useMatches[0];
2640
- const match = router.state.matches.find(d => d.routeId === routeId);
2641
-
2642
- if ((_opts$strict = opts == null ? void 0 : opts.strict) != null ? _opts$strict : true) {
2643
- invariant(match, "Could not find an active match for \"" + routeId + "\"!");
2644
- 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?");
2645
- }
2646
-
2647
- return match;
2648
- }
2649
- };
2650
- const routeExt = makeRouteExt(router.getRoute('/'), router);
2651
- Object.assign(router, routerExt, routeExt);
2652
- },
2653
- createRoute: _ref => {
2654
- let {
2655
- router,
2656
- route
2657
- } = _ref;
2658
- const routeExt = makeRouteExt(route, router);
2659
- Object.assign(route, routeExt);
2660
- },
2661
- loadComponent: async component => {
2662
- if (component.preload && typeof document !== 'undefined') {
2663
- component.preload(); // return await component.preload()
2664
- }
163
+ // Get the active props
164
+ const resolvedActiveProps = isActive ? functionalUpdate(activeProps, {}) ?? {} : {};
2665
165
 
2666
- return component;
2667
- }
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
2668
200
  }));
2669
- 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);
2670
214
  }
2671
- function RouterProvider(_ref2) {
2672
- let {
2673
- children,
2674
- router
2675
- } = _ref2,
2676
- rest = _objectWithoutPropertiesLoose(_ref2, _excluded3);
2677
-
215
+ function RouterProvider({
216
+ router,
217
+ ...rest
218
+ }) {
2678
219
  router.update(rest);
2679
- useRouterSubscription(router);
2680
220
  React.useEffect(() => {
2681
- return router.mount();
221
+ let unsub;
222
+ React.startTransition(() => {
223
+ unsub = router.mount();
224
+ });
225
+ return unsub;
2682
226
  }, [router]);
2683
- return /*#__PURE__*/React.createElement(routerContext.Provider, {
2684
- value: {
2685
- 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! 👍`);
2686
255
  }
2687
- }, /*#__PURE__*/React.createElement(MatchesProvider, {
2688
- value: router.state.matches
2689
- }, children != null ? children : /*#__PURE__*/React.createElement(Outlet, null)));
256
+ }, /*#__PURE__*/React.createElement(Outlet, null)));
2690
257
  }
2691
258
  function useRouter() {
2692
259
  const value = React.useContext(routerContext);
2693
- warning(!value, 'useRouter must be used inside a <Router> component!');
2694
- useRouterSubscription(value.router);
2695
- return value.router;
260
+ warning(value, 'useRouter must be used inside a <Router> component!');
261
+ return value;
2696
262
  }
2697
- function useMatches() {
2698
- 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
+ });
2699
271
  }
2700
- function Outlet() {
2701
- var _ref3, _match$__$pendingComp, _match$__$errorCompon;
2702
-
272
+ function useMatch(opts) {
2703
273
  const router = useRouter();
2704
- const matches = useMatches().slice(1);
2705
- const match = matches[0];
2706
- const defaultPending = React.useCallback(() => null, []);
2707
-
2708
- if (!match) {
2709
- 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?`);
2710
285
  }
2711
-
2712
- const PendingComponent = (_ref3 = (_match$__$pendingComp = match.__.pendingComponent) != null ? _match$__$pendingComp : router.options.defaultPendingComponent) != null ? _ref3 : defaultPending;
2713
- const errorComponent = (_match$__$errorCompon = match.__.errorComponent) != null ? _match$__$errorCompon : router.options.defaultErrorComponent;
2714
- return /*#__PURE__*/React.createElement(MatchesProvider, {
2715
- value: matches
2716
- }, /*#__PURE__*/React.createElement(React.Suspense, {
2717
- fallback: /*#__PURE__*/React.createElement(PendingComponent, null)
2718
- }, /*#__PURE__*/React.createElement(CatchBoundary, {
2719
- errorComponent: errorComponent
2720
- }, (() => {
2721
- if (match.status === 'error') {
2722
- 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;
2723
292
  }
2724
-
2725
- if (match.status === 'success') {
2726
- var _ref4, _ref5;
2727
-
2728
- 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;
2729
319
  }
2730
-
2731
- if (match.__.loadPromise) {
2732
- console.log(match.matchId, 'suspend');
2733
- 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;
2734
327
  }
2735
-
2736
- invariant(false, 'This should never happen!');
2737
- })())));
328
+ });
2738
329
  }
2739
-
2740
- class CatchBoundary extends React.Component {
2741
- constructor() {
2742
- super(...arguments);
2743
- this.state = {
2744
- error: false
2745
- };
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
+ });
2746
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
+ }
2747
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
+ };
2748
476
  componentDidCatch(error, info) {
2749
- console.error(error);
477
+ this.props.onCatch(error, info);
2750
478
  this.setState({
2751
479
  error,
2752
480
  info
2753
481
  });
2754
482
  }
2755
-
2756
483
  render() {
2757
- var _this$props$errorComp;
2758
-
2759
- const errorComponent = (_this$props$errorComp = this.props.errorComponent) != null ? _this$props$errorComp : DefaultErrorBoundary;
2760
-
2761
- if (this.state.error) {
2762
- 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
+ }
2763
502
  }
2764
-
2765
- 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);
2766
513
  }
2767
-
514
+ return props.children;
2768
515
  }
2769
-
2770
- function DefaultErrorBoundary(_ref6) {
2771
- let {
2772
- error
2773
- } = _ref6;
516
+ function ErrorComponent({
517
+ error
518
+ }) {
519
+ const [show, setShow] = React.useState(process.env.NODE_ENV !== 'production');
2774
520
  return /*#__PURE__*/React.createElement("div", {
2775
521
  style: {
2776
522
  padding: '.5rem',
2777
523
  maxWidth: '100%'
2778
524
  }
525
+ }, /*#__PURE__*/React.createElement("div", {
526
+ style: {
527
+ display: 'flex',
528
+ alignItems: 'center',
529
+ gap: '.5rem'
530
+ }
2779
531
  }, /*#__PURE__*/React.createElement("strong", {
2780
532
  style: {
2781
- fontSize: '1.2rem'
533
+ fontSize: '1rem'
2782
534
  }
2783
- }, "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", {
2784
546
  style: {
2785
- height: '.5rem'
547
+ height: '.25rem'
2786
548
  }
2787
- }), /*#__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", {
2788
550
  style: {
2789
551
  fontSize: '.7em',
2790
552
  border: '1px solid red',
2791
553
  borderRadius: '.25rem',
2792
- padding: '.5rem',
2793
- color: 'red'
554
+ padding: '.3rem',
555
+ color: 'red',
556
+ overflow: 'auto'
2794
557
  }
2795
- }, error.message) : null)));
558
+ }, error.message ? /*#__PURE__*/React.createElement("code", null, error.message) : null)) : null);
2796
559
  }
2797
- function usePrompt(message, when) {
560
+ function useBlocker(message, condition = true) {
2798
561
  const router = useRouter();
2799
562
  React.useEffect(() => {
2800
- if (!when) return;
2801
- let unblock = router.history.block(transition => {
563
+ if (!condition) return;
564
+ let unblock = router.history.block((retry, cancel) => {
2802
565
  if (window.confirm(message)) {
2803
566
  unblock();
2804
- transition.retry();
2805
- } else {
2806
- router.location.pathname = window.location.pathname;
567
+ retry();
2807
568
  }
2808
569
  });
2809
570
  return unblock;
2810
- }, [when, location, message]);
571
+ });
2811
572
  }
2812
- function Prompt(_ref7) {
2813
- let {
2814
- message,
2815
- when,
2816
- children
2817
- } = _ref7;
2818
- usePrompt(message, when != null ? when : true);
2819
- 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;
2820
598
  }
2821
599
 
2822
- 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 };
2823
601
  //# sourceMappingURL=index.js.map