@tanstack/react-router 0.0.1-beta.285 → 0.0.1-beta.286

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.
@@ -303,472 +303,114 @@ function escapeJSON(jsonString) {
303
303
  .replace(/"/g, '\\"'); // Escape double quotes
304
304
  }
305
305
 
306
- const matchContext = /*#__PURE__*/React.createContext(undefined);
307
- function Matches() {
308
- const router = useRouter();
309
- const matchId = useRouterState({
310
- select: s => {
311
- return getRenderedMatches(s)[0]?.id;
312
- }
313
- });
314
- return /*#__PURE__*/React.createElement(matchContext.Provider, {
315
- value: matchId
316
- }, /*#__PURE__*/React.createElement(CatchBoundary, {
317
- getResetKey: () => router.state.resolvedLocation.state?.key,
318
- errorComponent: ErrorComponent,
319
- onCatch: () => {
320
- warning(false, `Error in router! Consider setting an 'errorComponent' in your RootRoute! 👍`);
321
- }
322
- }, matchId ? /*#__PURE__*/React.createElement(Match, {
323
- matchId: matchId
324
- }) : null));
306
+ function joinPaths(paths) {
307
+ return cleanPath(paths.filter(Boolean).join('/'));
325
308
  }
326
- function SafeFragment(props) {
327
- return /*#__PURE__*/React.createElement(React.Fragment, null, props.children);
309
+ function cleanPath(path) {
310
+ // remove double slashes
311
+ return path.replace(/\/{2,}/g, '/');
328
312
  }
329
- function Match({
330
- matchId
331
- }) {
332
- const router = useRouter();
333
- const routeId = useRouterState({
334
- select: s => getRenderedMatches(s).find(d => d.id === matchId)?.routeId
335
- });
336
- invariant(routeId, `Could not find routeId for matchId "${matchId}". Please file an issue!`);
337
- const route = router.routesById[routeId];
338
- const PendingComponent = route.options.pendingComponent ?? router.options.defaultPendingComponent;
339
- const pendingElement = PendingComponent ? /*#__PURE__*/React.createElement(PendingComponent, null) : null;
340
- const routeErrorComponent = route.options.errorComponent ?? router.options.defaultErrorComponent ?? ErrorComponent;
341
- const ResolvedSuspenseBoundary = route.options.wrapInSuspense ?? PendingComponent ?? route.options.component?.preload ?? route.options.pendingComponent?.preload ?? route.options.errorComponent?.preload ? React.Suspense : SafeFragment;
342
- const ResolvedCatchBoundary = routeErrorComponent ? CatchBoundary : SafeFragment;
343
- return /*#__PURE__*/React.createElement(matchContext.Provider, {
344
- value: matchId
345
- }, /*#__PURE__*/React.createElement(ResolvedSuspenseBoundary, {
346
- fallback: pendingElement
347
- }, /*#__PURE__*/React.createElement(ResolvedCatchBoundary, {
348
- getResetKey: () => router.state.resolvedLocation.state?.key,
349
- errorComponent: routeErrorComponent,
350
- onCatch: () => {
351
- warning(false, `Error in route match: ${matchId}`);
352
- }
353
- }, /*#__PURE__*/React.createElement(MatchInner, {
354
- matchId: matchId,
355
- pendingElement: pendingElement
356
- }))));
313
+ function trimPathLeft(path) {
314
+ return path === '/' ? path : path.replace(/^\/{1,}/, '');
357
315
  }
358
- function MatchInner({
359
- matchId,
360
- pendingElement
361
- }) {
362
- const router = useRouter();
363
- const routeId = useRouterState({
364
- select: s => getRenderedMatches(s).find(d => d.id === matchId)?.routeId
365
- });
366
- const route = router.routesById[routeId];
367
- const match = useRouterState({
368
- select: s => pick(getRenderedMatches(s).find(d => d.id === matchId), ['status', 'error', 'showPending', 'loadPromise'])
369
- });
370
- if (match.status === 'error') {
371
- throw match.error;
372
- }
373
- if (match.status === 'pending') {
374
- if (match.showPending) {
375
- return pendingElement;
376
- }
377
- throw match.loadPromise;
378
- }
379
- if (match.status === 'success') {
380
- let Comp = route.options.component ?? router.options.defaultComponent;
381
- if (Comp) {
382
- return /*#__PURE__*/React.createElement(Comp, null);
383
- }
384
- return /*#__PURE__*/React.createElement(Outlet, null);
385
- }
386
- invariant(false, 'Idle routeMatch status encountered during rendering! You should never see this. File an issue!');
316
+ function trimPathRight(path) {
317
+ return path === '/' ? path : path.replace(/\/{1,}$/, '');
387
318
  }
388
- const Outlet = /*#__PURE__*/React.memo(function Outlet() {
389
- const matchId = React.useContext(matchContext);
390
- const childMatchId = useRouterState({
391
- select: s => {
392
- const matches = getRenderedMatches(s);
393
- const index = matches.findIndex(d => d.id === matchId);
394
- return matches[index + 1]?.id;
319
+ function trimPath(path) {
320
+ return trimPathRight(trimPathLeft(path));
321
+ }
322
+ function resolvePath(basepath, base, to) {
323
+ base = base.replace(new RegExp(`^${basepath}`), '/');
324
+ to = to.replace(new RegExp(`^${basepath}`), '/');
325
+ let baseSegments = parsePathname(base);
326
+ const toSegments = parsePathname(to);
327
+ toSegments.forEach((toSegment, index) => {
328
+ if (toSegment.value === '/') {
329
+ if (!index) {
330
+ // Leading slash
331
+ baseSegments = [toSegment];
332
+ } else if (index === toSegments.length - 1) {
333
+ // Trailing Slash
334
+ baseSegments.push(toSegment);
335
+ } else ;
336
+ } else if (toSegment.value === '..') {
337
+ // Extra trailing slash? pop it off
338
+ if (baseSegments.length > 1 && last(baseSegments)?.value === '/') {
339
+ baseSegments.pop();
340
+ }
341
+ baseSegments.pop();
342
+ } else if (toSegment.value === '.') {
343
+ return;
344
+ } else {
345
+ baseSegments.push(toSegment);
395
346
  }
396
347
  });
397
- if (!childMatchId) {
398
- return null;
348
+ const joined = joinPaths([basepath, ...baseSegments.map(d => d.value)]);
349
+ return cleanPath(joined);
350
+ }
351
+ function parsePathname(pathname) {
352
+ if (!pathname) {
353
+ return [];
399
354
  }
400
- return /*#__PURE__*/React.createElement(Match, {
401
- matchId: childMatchId
402
- });
403
- });
404
- function useMatchRoute() {
405
- useRouterState({
406
- select: s => [s.location, s.resolvedLocation]
407
- });
408
- const {
409
- matchRoute
410
- } = useRouter();
411
- return React.useCallback(opts => {
412
- const {
413
- pending,
414
- caseSensitive,
415
- ...rest
416
- } = opts;
417
- return matchRoute(rest, {
418
- pending,
419
- caseSensitive
355
+ pathname = cleanPath(pathname);
356
+ const segments = [];
357
+ if (pathname.slice(0, 1) === '/') {
358
+ pathname = pathname.substring(1);
359
+ segments.push({
360
+ type: 'pathname',
361
+ value: '/'
420
362
  });
421
- }, []);
422
- }
423
- function MatchRoute(props) {
424
- const matchRoute = useMatchRoute();
425
- const params = matchRoute(props);
426
- if (typeof props.children === 'function') {
427
- return props.children(params);
428
363
  }
429
- return !!params ? props.children : null;
430
- }
431
- function getRenderedMatches(state) {
432
- return state.pendingMatches?.some(d => d.showPending) ? state.pendingMatches : state.matches;
433
- }
434
- function useMatch(opts) {
435
- const router = useRouter();
436
- const nearestMatchId = React.useContext(matchContext);
437
- const nearestMatchRouteId = getRenderedMatches(router.state).find(d => d.id === nearestMatchId)?.routeId;
438
- const matchRouteId = (() => {
439
- const matches = getRenderedMatches(router.state);
440
- const match = opts?.from ? matches.find(d => d.routeId === opts?.from) : matches.find(d => d.id === nearestMatchId);
441
- return match.routeId;
442
- })();
443
- if (opts?.strict ?? true) {
444
- invariant(nearestMatchRouteId == matchRouteId, `useMatch("${matchRouteId}") is being called in a component that is meant to render the '${nearestMatchRouteId}' route. Did you mean to 'useMatch("${matchRouteId}", { strict: false })' or 'useRoute("${matchRouteId}")' instead?`);
364
+ if (!pathname) {
365
+ return segments;
445
366
  }
446
- const matchSelection = useRouterState({
447
- select: state => {
448
- const match = getRenderedMatches(state).find(d => d.id === nearestMatchId);
449
- invariant(match, `Could not find ${opts?.from ? `an active match from "${opts.from}"` : 'a nearest match!'}`);
450
- return opts?.select ? opts.select(match) : match;
451
- }
452
- });
453
- return matchSelection;
454
- }
455
- function useMatches(opts) {
456
- return useRouterState({
457
- select: state => {
458
- let matches = getRenderedMatches(state);
459
- return opts?.select ? opts.select(matches) : matches;
367
+
368
+ // Remove empty segments and '.' segments
369
+ const split = pathname.split('/').filter(Boolean);
370
+ segments.push(...split.map(part => {
371
+ if (part === '$' || part === '*') {
372
+ return {
373
+ type: 'wildcard',
374
+ value: part
375
+ };
460
376
  }
461
- });
462
- }
463
- function useParentMatches(opts) {
464
- const contextMatchId = React.useContext(matchContext);
465
- return useMatches({
466
- select: matches => {
467
- matches = matches.slice(matches.findIndex(d => d.id === contextMatchId));
468
- return opts?.select ? opts.select(matches) : matches;
377
+ if (part.charAt(0) === '$') {
378
+ return {
379
+ type: 'param',
380
+ value: part
381
+ };
469
382
  }
470
- });
383
+ return {
384
+ type: 'pathname',
385
+ value: part
386
+ };
387
+ }));
388
+ if (pathname.slice(-1) === '/') {
389
+ pathname = pathname.substring(1);
390
+ segments.push({
391
+ type: 'pathname',
392
+ value: '/'
393
+ });
394
+ }
395
+ return segments;
471
396
  }
472
- function useLoaderDeps(opts) {
473
- return useMatch({
474
- ...opts,
475
- select: s => {
476
- return typeof opts.select === 'function' ? opts.select(s?.loaderDeps) : s?.loaderDeps;
397
+ function interpolatePath(path, params, leaveWildcards = false) {
398
+ const interpolatedPathSegments = parsePathname(path);
399
+ return joinPaths(interpolatedPathSegments.map(segment => {
400
+ if (segment.type === 'wildcard') {
401
+ const value = params[segment.value];
402
+ if (leaveWildcards) return `${segment.value}${value ?? ''}`;
403
+ return value;
477
404
  }
478
- });
479
- }
480
- function useLoaderData(opts) {
481
- return useMatch({
482
- ...opts,
483
- select: s => {
484
- return typeof opts.select === 'function' ? opts.select(s?.loaderData) : s?.loaderData;
405
+ if (segment.type === 'param') {
406
+ return params[segment.value.substring(1)] ?? 'undefined';
485
407
  }
486
- });
408
+ return segment.value;
409
+ }));
487
410
  }
488
-
489
- let routerContext = /*#__PURE__*/React.createContext(null);
490
- if (typeof document !== 'undefined') {
491
- if (window.__TSR_ROUTER_CONTEXT__) {
492
- routerContext = window.__TSR_ROUTER_CONTEXT__;
493
- } else {
494
- window.__TSR_ROUTER_CONTEXT__ = routerContext;
495
- }
496
- }
497
- function RouterProvider({
498
- router,
499
- ...rest
500
- }) {
501
- // Allow the router to update options on the router instance
502
- router.update({
503
- ...router.options,
504
- ...rest,
505
- context: {
506
- ...router.options.context,
507
- ...rest?.context
508
- }
509
- });
510
- const matches = router.options.InnerWrap ? /*#__PURE__*/React.createElement(router.options.InnerWrap, null, /*#__PURE__*/React.createElement(Matches, null)) : /*#__PURE__*/React.createElement(Matches, null);
511
- const provider = /*#__PURE__*/React.createElement(routerContext.Provider, {
512
- value: router
513
- }, matches, /*#__PURE__*/React.createElement(Transitioner, null));
514
- if (router.options.Wrap) {
515
- return /*#__PURE__*/React.createElement(router.options.Wrap, null, provider);
516
- }
517
- return provider;
518
- }
519
- function Transitioner() {
520
- const router = useRouter();
521
- const routerState = useRouterState({
522
- select: s => pick(s, ['isLoading', 'location', 'resolvedLocation', 'isTransitioning'])
523
- });
524
- const [isTransitioning, startReactTransition] = React.useTransition();
525
- router.startReactTransition = startReactTransition;
526
- React.useEffect(() => {
527
- if (isTransitioning) {
528
- router.__store.setState(s => ({
529
- ...s,
530
- isTransitioning
531
- }));
532
- }
533
- }, [isTransitioning]);
534
- const tryLoad = () => {
535
- const apply = cb => {
536
- if (!routerState.isTransitioning) {
537
- startReactTransition(() => cb());
538
- } else {
539
- cb();
540
- }
541
- };
542
- apply(() => {
543
- try {
544
- router.load();
545
- } catch (err) {
546
- console.error(err);
547
- }
548
- });
549
- };
550
- useLayoutEffect$1(() => {
551
- const unsub = router.history.subscribe(() => {
552
- router.latestLocation = router.parseLocation(router.latestLocation);
553
- if (routerState.location !== router.latestLocation) {
554
- tryLoad();
555
- }
556
- });
557
- const nextLocation = router.buildLocation({
558
- search: true,
559
- params: true,
560
- hash: true,
561
- state: true
562
- });
563
- if (routerState.location.href !== nextLocation.href) {
564
- router.commitLocation({
565
- ...nextLocation,
566
- replace: true
567
- });
568
- }
569
- return () => {
570
- unsub();
571
- };
572
- }, [router.history]);
573
- useLayoutEffect$1(() => {
574
- if (routerState.isTransitioning && !isTransitioning && !routerState.isLoading && routerState.resolvedLocation !== routerState.location) {
575
- router.emit({
576
- type: 'onResolved',
577
- fromLocation: routerState.resolvedLocation,
578
- toLocation: routerState.location,
579
- pathChanged: routerState.location.href !== routerState.resolvedLocation?.href
580
- });
581
- if (document.querySelector) {
582
- if (routerState.location.hash !== '') {
583
- const el = document.getElementById(routerState.location.hash);
584
- if (el) {
585
- el.scrollIntoView();
586
- }
587
- }
588
- }
589
- router.__store.setState(s => ({
590
- ...s,
591
- isTransitioning: false,
592
- resolvedLocation: s.location
593
- }));
594
- }
595
- }, [routerState.isTransitioning, isTransitioning, routerState.isLoading, routerState.resolvedLocation, routerState.location]);
596
- useLayoutEffect$1(() => {
597
- if (!window.__TSR_DEHYDRATED__) {
598
- tryLoad();
599
- }
600
- }, []);
601
- return null;
602
- }
603
- function getRouteMatch(state, id) {
604
- return [...state.cachedMatches, ...(state.pendingMatches ?? []), ...state.matches].find(d => d.id === id);
605
- }
606
- function useRouterState(opts) {
607
- const router = useRouter();
608
- return useStore(router.__store, opts?.select);
609
- }
610
- function useRouter() {
611
- const resolvedContext = typeof document !== 'undefined' ? window.__TSR_ROUTER_CONTEXT__ || routerContext : routerContext;
612
- const value = React.useContext(resolvedContext);
613
- warning(value, 'useRouter must be used inside a <RouterProvider> component!');
614
- return value;
615
- }
616
-
617
- function defer(_promise) {
618
- const promise = _promise;
619
- if (!promise.__deferredState) {
620
- promise.__deferredState = {
621
- uid: Math.random().toString(36).slice(2),
622
- status: 'pending'
623
- };
624
- const state = promise.__deferredState;
625
- promise.then(data => {
626
- state.status = 'success';
627
- state.data = data;
628
- }).catch(error => {
629
- state.status = 'error';
630
- state.error = error;
631
- });
632
- }
633
- return promise;
634
- }
635
- function isDehydratedDeferred(obj) {
636
- return typeof obj === 'object' && obj !== null && !(obj instanceof Promise) && !obj.then && '__deferredState' in obj;
637
- }
638
-
639
- function useAwaited({
640
- promise
641
- }) {
642
- const router = useRouter();
643
- let state = promise.__deferredState;
644
- const key = `__TSR__DEFERRED__${state.uid}`;
645
- if (isDehydratedDeferred(promise)) {
646
- state = router.hydrateData(key);
647
- promise = Promise.resolve(state.data);
648
- promise.__deferredState = state;
649
- }
650
- if (state.status === 'pending') {
651
- throw new Promise(r => setTimeout(r, 1)).then(() => promise);
652
- }
653
- if (state.status === 'error') {
654
- throw state.error;
655
- }
656
- router.dehydrateData(key, state);
657
- return [state.data];
658
- }
659
- function Await(props) {
660
- const awaited = useAwaited(props);
661
- return props.children(...awaited);
662
- }
663
-
664
- function joinPaths(paths) {
665
- return cleanPath(paths.filter(Boolean).join('/'));
666
- }
667
- function cleanPath(path) {
668
- // remove double slashes
669
- return path.replace(/\/{2,}/g, '/');
670
- }
671
- function trimPathLeft(path) {
672
- return path === '/' ? path : path.replace(/^\/{1,}/, '');
673
- }
674
- function trimPathRight(path) {
675
- return path === '/' ? path : path.replace(/\/{1,}$/, '');
676
- }
677
- function trimPath(path) {
678
- return trimPathRight(trimPathLeft(path));
679
- }
680
- function resolvePath(basepath, base, to) {
681
- base = base.replace(new RegExp(`^${basepath}`), '/');
682
- to = to.replace(new RegExp(`^${basepath}`), '/');
683
- let baseSegments = parsePathname(base);
684
- const toSegments = parsePathname(to);
685
- toSegments.forEach((toSegment, index) => {
686
- if (toSegment.value === '/') {
687
- if (!index) {
688
- // Leading slash
689
- baseSegments = [toSegment];
690
- } else if (index === toSegments.length - 1) {
691
- // Trailing Slash
692
- baseSegments.push(toSegment);
693
- } else ;
694
- } else if (toSegment.value === '..') {
695
- // Extra trailing slash? pop it off
696
- if (baseSegments.length > 1 && last(baseSegments)?.value === '/') {
697
- baseSegments.pop();
698
- }
699
- baseSegments.pop();
700
- } else if (toSegment.value === '.') {
701
- return;
702
- } else {
703
- baseSegments.push(toSegment);
704
- }
705
- });
706
- const joined = joinPaths([basepath, ...baseSegments.map(d => d.value)]);
707
- return cleanPath(joined);
708
- }
709
- function parsePathname(pathname) {
710
- if (!pathname) {
711
- return [];
712
- }
713
- pathname = cleanPath(pathname);
714
- const segments = [];
715
- if (pathname.slice(0, 1) === '/') {
716
- pathname = pathname.substring(1);
717
- segments.push({
718
- type: 'pathname',
719
- value: '/'
720
- });
721
- }
722
- if (!pathname) {
723
- return segments;
724
- }
725
-
726
- // Remove empty segments and '.' segments
727
- const split = pathname.split('/').filter(Boolean);
728
- segments.push(...split.map(part => {
729
- if (part === '$' || part === '*') {
730
- return {
731
- type: 'wildcard',
732
- value: part
733
- };
734
- }
735
- if (part.charAt(0) === '$') {
736
- return {
737
- type: 'param',
738
- value: part
739
- };
740
- }
741
- return {
742
- type: 'pathname',
743
- value: part
744
- };
745
- }));
746
- if (pathname.slice(-1) === '/') {
747
- pathname = pathname.substring(1);
748
- segments.push({
749
- type: 'pathname',
750
- value: '/'
751
- });
752
- }
753
- return segments;
754
- }
755
- function interpolatePath(path, params, leaveWildcards = false) {
756
- const interpolatedPathSegments = parsePathname(path);
757
- return joinPaths(interpolatedPathSegments.map(segment => {
758
- if (segment.type === 'wildcard') {
759
- const value = params[segment.value];
760
- if (leaveWildcards) return `${segment.value}${value ?? ''}`;
761
- return value;
762
- }
763
- if (segment.type === 'param') {
764
- return params[segment.value.substring(1)] ?? 'undefined';
765
- }
766
- return segment.value;
767
- }));
768
- }
769
- function matchPathname(basepath, currentPathname, matchLocation) {
770
- const pathParams = matchByPath(basepath, currentPathname, matchLocation);
771
- // const searchMatched = matchBySearch(location.search, matchLocation)
411
+ function matchPathname(basepath, currentPathname, matchLocation) {
412
+ const pathParams = matchByPath(basepath, currentPathname, matchLocation);
413
+ // const searchMatched = matchBySearch(location.search, matchLocation)
772
414
 
773
415
  if (matchLocation.to && !pathParams) {
774
416
  return;
@@ -938,98 +580,463 @@ class Route {
938
580
  } else {
939
581
  invariant(this.parentRoute, `Child Route instances must pass a 'getParentRoute: () => ParentRoute' option that returns a Route instance.`);
940
582
  }
941
- let path = isRoot ? rootRouteId : options.path;
942
-
943
- // If the path is anything other than an index path, trim it up
944
- if (path && path !== '/') {
945
- path = trimPath(path);
583
+ let path = isRoot ? rootRouteId : options.path;
584
+
585
+ // If the path is anything other than an index path, trim it up
586
+ if (path && path !== '/') {
587
+ path = trimPath(path);
588
+ }
589
+ const customId = options?.id || path;
590
+
591
+ // Strip the parentId prefix from the first level of children
592
+ let id = isRoot ? rootRouteId : joinPaths([this.parentRoute.id === rootRouteId ? '' : this.parentRoute.id, customId]);
593
+ if (path === rootRouteId) {
594
+ path = '/';
595
+ }
596
+ if (id !== rootRouteId) {
597
+ id = joinPaths(['/', id]);
598
+ }
599
+ const fullPath = id === rootRouteId ? '/' : joinPaths([this.parentRoute.fullPath, path]);
600
+ this.path = path;
601
+ this.id = id;
602
+ // this.customId = customId as TCustomId
603
+ this.fullPath = fullPath;
604
+ this.to = fullPath;
605
+ };
606
+ addChildren = children => {
607
+ this.children = children;
608
+ return this;
609
+ };
610
+ update = options => {
611
+ Object.assign(this.options, options);
612
+ return this;
613
+ };
614
+ useMatch = opts => {
615
+ return useMatch({
616
+ ...opts,
617
+ from: this.id
618
+ });
619
+ };
620
+ useRouteContext = opts => {
621
+ return useMatch({
622
+ ...opts,
623
+ from: this.id,
624
+ select: d => opts?.select ? opts.select(d.context) : d.context
625
+ });
626
+ };
627
+ useSearch = opts => {
628
+ return useSearch({
629
+ ...opts,
630
+ from: this.id
631
+ });
632
+ };
633
+ useParams = opts => {
634
+ return useParams({
635
+ ...opts,
636
+ from: this.id
637
+ });
638
+ };
639
+ useLoaderDeps = opts => {
640
+ return useLoaderDeps({
641
+ ...opts,
642
+ from: this.id
643
+ });
644
+ };
645
+ useLoaderData = opts => {
646
+ return useLoaderData({
647
+ ...opts,
648
+ from: this.id
649
+ });
650
+ };
651
+ }
652
+ function rootRouteWithContext() {
653
+ return options => {
654
+ return new RootRoute(options);
655
+ };
656
+ }
657
+ class RootRoute extends Route {
658
+ constructor(options) {
659
+ super(options);
660
+ }
661
+ }
662
+ function createRouteMask(opts) {
663
+ return opts;
664
+ }
665
+
666
+ //
667
+
668
+ class NotFoundRoute extends Route {
669
+ constructor(options) {
670
+ super({
671
+ ...options,
672
+ id: '404'
673
+ });
674
+ }
675
+ }
676
+
677
+ const matchContext = /*#__PURE__*/React.createContext(undefined);
678
+ function Matches() {
679
+ const router = useRouter();
680
+ const matchId = useRouterState({
681
+ select: s => {
682
+ return getRenderedMatches(s)[0]?.id;
683
+ }
684
+ });
685
+ return /*#__PURE__*/React.createElement(matchContext.Provider, {
686
+ value: matchId
687
+ }, /*#__PURE__*/React.createElement(CatchBoundary, {
688
+ getResetKey: () => router.state.resolvedLocation.state?.key,
689
+ errorComponent: ErrorComponent,
690
+ onCatch: () => {
691
+ warning(false, `Error in router! Consider setting an 'errorComponent' in your RootRoute! 👍`);
692
+ }
693
+ }, matchId ? /*#__PURE__*/React.createElement(Match, {
694
+ matchId: matchId
695
+ }) : null));
696
+ }
697
+ function SafeFragment(props) {
698
+ return /*#__PURE__*/React.createElement(React.Fragment, null, props.children);
699
+ }
700
+ function Match({
701
+ matchId
702
+ }) {
703
+ const router = useRouter();
704
+ const routeId = useRouterState({
705
+ select: s => getRenderedMatches(s).find(d => d.id === matchId)?.routeId
706
+ });
707
+ invariant(routeId, `Could not find routeId for matchId "${matchId}". Please file an issue!`);
708
+ const route = router.routesById[routeId];
709
+ const PendingComponent = route.options.pendingComponent ?? router.options.defaultPendingComponent;
710
+ const pendingElement = PendingComponent ? /*#__PURE__*/React.createElement(PendingComponent, null) : null;
711
+ const routeErrorComponent = route.options.errorComponent ?? router.options.defaultErrorComponent ?? ErrorComponent;
712
+ const ResolvedSuspenseBoundary = route.options.wrapInSuspense ?? PendingComponent ?? route.options.component?.preload ?? route.options.pendingComponent?.preload ?? route.options.errorComponent?.preload ? React.Suspense : SafeFragment;
713
+ const ResolvedCatchBoundary = routeErrorComponent ? CatchBoundary : SafeFragment;
714
+ return /*#__PURE__*/React.createElement(matchContext.Provider, {
715
+ value: matchId
716
+ }, /*#__PURE__*/React.createElement(ResolvedSuspenseBoundary, {
717
+ fallback: pendingElement
718
+ }, /*#__PURE__*/React.createElement(ResolvedCatchBoundary, {
719
+ getResetKey: () => router.state.resolvedLocation.state?.key,
720
+ errorComponent: routeErrorComponent,
721
+ onCatch: () => {
722
+ warning(false, `Error in route match: ${matchId}`);
723
+ }
724
+ }, /*#__PURE__*/React.createElement(MatchInner, {
725
+ matchId: matchId,
726
+ pendingElement: pendingElement
727
+ }))));
728
+ }
729
+ function MatchInner({
730
+ matchId,
731
+ pendingElement
732
+ }) {
733
+ const router = useRouter();
734
+ const routeId = useRouterState({
735
+ select: s => getRenderedMatches(s).find(d => d.id === matchId)?.routeId
736
+ });
737
+ const route = router.routesById[routeId];
738
+ const match = useRouterState({
739
+ select: s => pick(getRenderedMatches(s).find(d => d.id === matchId), ['status', 'error', 'showPending', 'loadPromise'])
740
+ });
741
+ if (match.status === 'error') {
742
+ throw match.error;
743
+ }
744
+ if (match.status === 'pending') {
745
+ if (match.showPending) {
746
+ return pendingElement;
747
+ }
748
+ throw match.loadPromise;
749
+ }
750
+ if (match.status === 'success') {
751
+ let Comp = route.options.component ?? router.options.defaultComponent;
752
+ if (Comp) {
753
+ return /*#__PURE__*/React.createElement(Comp, null);
754
+ }
755
+ return /*#__PURE__*/React.createElement(Outlet, null);
756
+ }
757
+ invariant(false, 'Idle routeMatch status encountered during rendering! You should never see this. File an issue!');
758
+ }
759
+ const Outlet = /*#__PURE__*/React.memo(function Outlet() {
760
+ const matchId = React.useContext(matchContext);
761
+ const childMatchId = useRouterState({
762
+ select: s => {
763
+ const matches = getRenderedMatches(s);
764
+ const index = matches.findIndex(d => d.id === matchId);
765
+ return matches[index + 1]?.id;
766
+ }
767
+ });
768
+ if (!childMatchId) {
769
+ return null;
770
+ }
771
+ return /*#__PURE__*/React.createElement(Match, {
772
+ matchId: childMatchId
773
+ });
774
+ });
775
+ function useMatchRoute() {
776
+ useRouterState({
777
+ select: s => [s.location, s.resolvedLocation]
778
+ });
779
+ const {
780
+ matchRoute
781
+ } = useRouter();
782
+ return React.useCallback(opts => {
783
+ const {
784
+ pending,
785
+ caseSensitive,
786
+ ...rest
787
+ } = opts;
788
+ return matchRoute(rest, {
789
+ pending,
790
+ caseSensitive
791
+ });
792
+ }, []);
793
+ }
794
+ function MatchRoute(props) {
795
+ const matchRoute = useMatchRoute();
796
+ const params = matchRoute(props);
797
+ if (typeof props.children === 'function') {
798
+ return props.children(params);
799
+ }
800
+ return !!params ? props.children : null;
801
+ }
802
+ function getRenderedMatches(state) {
803
+ return state.pendingMatches?.some(d => d.showPending) ? state.pendingMatches : state.matches;
804
+ }
805
+ function removeUnderscores(s) {
806
+ if (s === rootRouteId) return s;
807
+ return s?.replace(/(^_|_$)/, '').replace(/(\/_|_\/)/, '/');
808
+ }
809
+ function useMatch(opts) {
810
+ const router = useRouter();
811
+ const nearestMatchId = React.useContext(matchContext);
812
+ const nearestMatchRouteId = getRenderedMatches(router.state).find(d => d.id === nearestMatchId)?.routeId;
813
+ const matchRouteId = (() => {
814
+ const matches = getRenderedMatches(router.state);
815
+ if (!opts.from) {
816
+ return matches.find(d => d.id === nearestMatchId);
817
+ }
818
+ const from = removeUnderscores(opts.from);
819
+ return matches.find(d => d.routeId === from) ?? matches.find(d => d.routeId === from?.replace(/\/$/, ''));
820
+ })()?.routeId;
821
+ if (opts?.strict ?? true) {
822
+ invariant(nearestMatchRouteId == matchRouteId, `useMatch("${matchRouteId}") is being called in a component that is meant to render the '${nearestMatchRouteId}' route. Did you mean to 'useMatch("${matchRouteId}", { strict: false })' or 'useRoute("${matchRouteId}")' instead?`);
823
+ }
824
+ const matchSelection = useRouterState({
825
+ select: state => {
826
+ const match = getRenderedMatches(state).find(d => d.id === nearestMatchId);
827
+ invariant(match, `Could not find ${opts?.from ? `an active match from "${opts.from}"` : 'a nearest match!'}`);
828
+ return opts?.select ? opts.select(match) : match;
829
+ }
830
+ });
831
+ return matchSelection;
832
+ }
833
+ function useMatches(opts) {
834
+ return useRouterState({
835
+ select: state => {
836
+ let matches = getRenderedMatches(state);
837
+ return opts?.select ? opts.select(matches) : matches;
838
+ }
839
+ });
840
+ }
841
+ function useParentMatches(opts) {
842
+ const contextMatchId = React.useContext(matchContext);
843
+ return useMatches({
844
+ select: matches => {
845
+ matches = matches.slice(matches.findIndex(d => d.id === contextMatchId));
846
+ return opts?.select ? opts.select(matches) : matches;
847
+ }
848
+ });
849
+ }
850
+ function useLoaderDeps(opts) {
851
+ return useMatch({
852
+ ...opts,
853
+ select: s => {
854
+ return typeof opts.select === 'function' ? opts.select(s?.loaderDeps) : s?.loaderDeps;
946
855
  }
947
- const customId = options?.id || path;
856
+ });
857
+ }
858
+ function useLoaderData(opts) {
859
+ return useMatch({
860
+ ...opts,
861
+ select: s => {
862
+ return typeof opts.select === 'function' ? opts.select(s?.loaderData) : s?.loaderData;
863
+ }
864
+ });
865
+ }
948
866
 
949
- // Strip the parentId prefix from the first level of children
950
- let id = isRoot ? rootRouteId : joinPaths([this.parentRoute.id === rootRouteId ? '' : this.parentRoute.id, customId]);
951
- if (path === rootRouteId) {
952
- path = '/';
867
+ let routerContext = /*#__PURE__*/React.createContext(null);
868
+ if (typeof document !== 'undefined') {
869
+ if (window.__TSR_ROUTER_CONTEXT__) {
870
+ routerContext = window.__TSR_ROUTER_CONTEXT__;
871
+ } else {
872
+ window.__TSR_ROUTER_CONTEXT__ = routerContext;
873
+ }
874
+ }
875
+ function RouterProvider({
876
+ router,
877
+ ...rest
878
+ }) {
879
+ // Allow the router to update options on the router instance
880
+ router.update({
881
+ ...router.options,
882
+ ...rest,
883
+ context: {
884
+ ...router.options.context,
885
+ ...rest?.context
953
886
  }
954
- if (id !== rootRouteId) {
955
- id = joinPaths(['/', id]);
887
+ });
888
+ const matches = router.options.InnerWrap ? /*#__PURE__*/React.createElement(router.options.InnerWrap, null, /*#__PURE__*/React.createElement(Matches, null)) : /*#__PURE__*/React.createElement(Matches, null);
889
+ const provider = /*#__PURE__*/React.createElement(routerContext.Provider, {
890
+ value: router
891
+ }, matches, /*#__PURE__*/React.createElement(Transitioner, null));
892
+ if (router.options.Wrap) {
893
+ return /*#__PURE__*/React.createElement(router.options.Wrap, null, provider);
894
+ }
895
+ return provider;
896
+ }
897
+ function Transitioner() {
898
+ const router = useRouter();
899
+ const routerState = useRouterState({
900
+ select: s => pick(s, ['isLoading', 'location', 'resolvedLocation', 'isTransitioning'])
901
+ });
902
+ const [isTransitioning, startReactTransition] = React.useTransition();
903
+ router.startReactTransition = startReactTransition;
904
+ React.useEffect(() => {
905
+ if (isTransitioning) {
906
+ router.__store.setState(s => ({
907
+ ...s,
908
+ isTransitioning
909
+ }));
956
910
  }
957
- const fullPath = id === rootRouteId ? '/' : joinPaths([this.parentRoute.fullPath, path]);
958
- this.path = path;
959
- this.id = id;
960
- // this.customId = customId as TCustomId
961
- this.fullPath = fullPath;
962
- this.to = fullPath;
963
- };
964
- addChildren = children => {
965
- this.children = children;
966
- return this;
967
- };
968
- update = options => {
969
- Object.assign(this.options, options);
970
- return this;
971
- };
972
- useMatch = opts => {
973
- return useMatch({
974
- ...opts,
975
- from: this.id
976
- });
977
- };
978
- useRouteContext = opts => {
979
- return useMatch({
980
- ...opts,
981
- from: this.id,
982
- select: d => opts?.select ? opts.select(d.context) : d.context
983
- });
984
- };
985
- useSearch = opts => {
986
- return useSearch({
987
- ...opts,
988
- from: this.id
989
- });
990
- };
991
- useParams = opts => {
992
- return useParams({
993
- ...opts,
994
- from: this.id
911
+ }, [isTransitioning]);
912
+ const tryLoad = () => {
913
+ const apply = cb => {
914
+ if (!routerState.isTransitioning) {
915
+ startReactTransition(() => cb());
916
+ } else {
917
+ cb();
918
+ }
919
+ };
920
+ apply(() => {
921
+ try {
922
+ router.load();
923
+ } catch (err) {
924
+ console.error(err);
925
+ }
995
926
  });
996
927
  };
997
- useLoaderDeps = opts => {
998
- return useLoaderDeps({
999
- ...opts,
1000
- from: this.id
928
+ useLayoutEffect$1(() => {
929
+ const unsub = router.history.subscribe(() => {
930
+ router.latestLocation = router.parseLocation(router.latestLocation);
931
+ if (routerState.location !== router.latestLocation) {
932
+ tryLoad();
933
+ }
1001
934
  });
1002
- };
1003
- useLoaderData = opts => {
1004
- return useLoaderData({
1005
- ...opts,
1006
- from: this.id
935
+ const nextLocation = router.buildLocation({
936
+ search: true,
937
+ params: true,
938
+ hash: true,
939
+ state: true
1007
940
  });
1008
- };
941
+ if (routerState.location.href !== nextLocation.href) {
942
+ router.commitLocation({
943
+ ...nextLocation,
944
+ replace: true
945
+ });
946
+ }
947
+ return () => {
948
+ unsub();
949
+ };
950
+ }, [router.history]);
951
+ useLayoutEffect$1(() => {
952
+ if (routerState.isTransitioning && !isTransitioning && !routerState.isLoading && routerState.resolvedLocation !== routerState.location) {
953
+ router.emit({
954
+ type: 'onResolved',
955
+ fromLocation: routerState.resolvedLocation,
956
+ toLocation: routerState.location,
957
+ pathChanged: routerState.location.href !== routerState.resolvedLocation?.href
958
+ });
959
+ if (document.querySelector) {
960
+ if (routerState.location.hash !== '') {
961
+ const el = document.getElementById(routerState.location.hash);
962
+ if (el) {
963
+ el.scrollIntoView();
964
+ }
965
+ }
966
+ }
967
+ router.__store.setState(s => ({
968
+ ...s,
969
+ isTransitioning: false,
970
+ resolvedLocation: s.location
971
+ }));
972
+ }
973
+ }, [routerState.isTransitioning, isTransitioning, routerState.isLoading, routerState.resolvedLocation, routerState.location]);
974
+ useLayoutEffect$1(() => {
975
+ if (!window.__TSR_DEHYDRATED__) {
976
+ tryLoad();
977
+ }
978
+ }, []);
979
+ return null;
1009
980
  }
1010
- function rootRouteWithContext() {
1011
- return options => {
1012
- return new RootRoute(options);
1013
- };
981
+ function getRouteMatch(state, id) {
982
+ return [...state.cachedMatches, ...(state.pendingMatches ?? []), ...state.matches].find(d => d.id === id);
1014
983
  }
1015
- class RootRoute extends Route {
1016
- constructor(options) {
1017
- super(options);
1018
- }
984
+ function useRouterState(opts) {
985
+ const router = useRouter();
986
+ return useStore(router.__store, opts?.select);
1019
987
  }
1020
- function createRouteMask(opts) {
1021
- return opts;
988
+ function useRouter() {
989
+ const resolvedContext = typeof document !== 'undefined' ? window.__TSR_ROUTER_CONTEXT__ || routerContext : routerContext;
990
+ const value = React.useContext(resolvedContext);
991
+ warning(value, 'useRouter must be used inside a <RouterProvider> component!');
992
+ return value;
1022
993
  }
1023
994
 
1024
- //
1025
-
1026
- class NotFoundRoute extends Route {
1027
- constructor(options) {
1028
- super({
1029
- ...options,
1030
- id: '404'
995
+ function defer(_promise) {
996
+ const promise = _promise;
997
+ if (!promise.__deferredState) {
998
+ promise.__deferredState = {
999
+ uid: Math.random().toString(36).slice(2),
1000
+ status: 'pending'
1001
+ };
1002
+ const state = promise.__deferredState;
1003
+ promise.then(data => {
1004
+ state.status = 'success';
1005
+ state.data = data;
1006
+ }).catch(error => {
1007
+ state.status = 'error';
1008
+ state.error = error;
1031
1009
  });
1032
1010
  }
1011
+ return promise;
1012
+ }
1013
+ function isDehydratedDeferred(obj) {
1014
+ return typeof obj === 'object' && obj !== null && !(obj instanceof Promise) && !obj.then && '__deferredState' in obj;
1015
+ }
1016
+
1017
+ function useAwaited({
1018
+ promise
1019
+ }) {
1020
+ const router = useRouter();
1021
+ let state = promise.__deferredState;
1022
+ const key = `__TSR__DEFERRED__${state.uid}`;
1023
+ if (isDehydratedDeferred(promise)) {
1024
+ state = router.hydrateData(key);
1025
+ promise = Promise.resolve(state.data);
1026
+ promise.__deferredState = state;
1027
+ }
1028
+ if (state.status === 'pending') {
1029
+ throw new Promise(r => setTimeout(r, 1)).then(() => promise);
1030
+ }
1031
+ if (state.status === 'error') {
1032
+ throw state.error;
1033
+ }
1034
+ router.dehydrateData(key, state);
1035
+ return [state.data];
1036
+ }
1037
+ function Await(props) {
1038
+ const awaited = useAwaited(props);
1039
+ return props.children(...awaited);
1033
1040
  }
1034
1041
 
1035
1042
  class FileRoute {