@tanstack/react-router 0.0.1-beta.7 → 0.0.1-beta.71

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