UNPKG

46.1 kBJavaScriptView Raw
1/**
2 * React Router v6.4.4
3 *
4 * Copyright (c) Remix Software Inc.
5 *
6 * This source code is licensed under the MIT license found in the
7 * LICENSE.md file in the root directory of this source tree.
8 *
9 * @license MIT
10 */
11import { invariant, joinPaths, matchPath, UNSAFE_getPathContributingMatches, warning, resolveTo, parsePath, matchRoutes, Action, isRouteErrorResponse, createMemoryHistory, stripBasename, AbortedDeferredError, createRouter } from '@remix-run/router';
12export { AbortedDeferredError, Action as NavigationType, createPath, defer, generatePath, isRouteErrorResponse, json, matchPath, matchRoutes, parsePath, redirect, resolvePath } from '@remix-run/router';
13import * as React from 'react';
14
15/**
16 * Copyright (c) Facebook, Inc. and its affiliates.
17 *
18 * This source code is licensed under the MIT license found in the
19 * LICENSE file in the root directory of this source tree.
20 */
21/**
22 * inlined Object.is polyfill to avoid requiring consumers ship their own
23 * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is
24 */
25
26function isPolyfill(x, y) {
27 return x === y && (x !== 0 || 1 / x === 1 / y) || x !== x && y !== y // eslint-disable-line no-self-compare
28 ;
29}
30
31const is = typeof Object.is === "function" ? Object.is : isPolyfill; // Intentionally not using named imports because Rollup uses dynamic
32// dispatch for CommonJS interop named imports.
33
34const {
35 useState,
36 useEffect,
37 useLayoutEffect,
38 useDebugValue
39} = React;
40let didWarnOld18Alpha = false;
41let didWarnUncachedGetSnapshot = false; // Disclaimer: This shim breaks many of the rules of React, and only works
42// because of a very particular set of implementation details and assumptions
43// -- change any one of them and it will break. The most important assumption
44// is that updates are always synchronous, because concurrent rendering is
45// only available in versions of React that also have a built-in
46// useSyncExternalStore API. And we only use this shim when the built-in API
47// does not exist.
48//
49// Do not assume that the clever hacks used by this hook also work in general.
50// The point of this shim is to replace the need for hacks by other libraries.
51
52function useSyncExternalStore$2(subscribe, getSnapshot, // Note: The shim does not use getServerSnapshot, because pre-18 versions of
53// React do not expose a way to check if we're hydrating. So users of the shim
54// will need to track that themselves and return the correct value
55// from `getSnapshot`.
56getServerSnapshot) {
57 {
58 if (!didWarnOld18Alpha) {
59 if ("startTransition" in React) {
60 didWarnOld18Alpha = true;
61 console.error("You are using an outdated, pre-release alpha of React 18 that " + "does not support useSyncExternalStore. The " + "use-sync-external-store shim will not work correctly. Upgrade " + "to a newer pre-release.");
62 }
63 }
64 } // Read the current snapshot from the store on every render. Again, this
65 // breaks the rules of React, and only works here because of specific
66 // implementation details, most importantly that updates are
67 // always synchronous.
68
69
70 const value = getSnapshot();
71
72 {
73 if (!didWarnUncachedGetSnapshot) {
74 const cachedValue = getSnapshot();
75
76 if (!is(value, cachedValue)) {
77 console.error("The result of getSnapshot should be cached to avoid an infinite loop");
78 didWarnUncachedGetSnapshot = true;
79 }
80 }
81 } // Because updates are synchronous, we don't queue them. Instead we force a
82 // re-render whenever the subscribed state changes by updating an some
83 // arbitrary useState hook. Then, during render, we call getSnapshot to read
84 // the current value.
85 //
86 // Because we don't actually use the state returned by the useState hook, we
87 // can save a bit of memory by storing other stuff in that slot.
88 //
89 // To implement the early bailout, we need to track some things on a mutable
90 // object. Usually, we would put that in a useRef hook, but we can stash it in
91 // our useState hook instead.
92 //
93 // To force a re-render, we call forceUpdate({inst}). That works because the
94 // new object always fails an equality check.
95
96
97 const [{
98 inst
99 }, forceUpdate] = useState({
100 inst: {
101 value,
102 getSnapshot
103 }
104 }); // Track the latest getSnapshot function with a ref. This needs to be updated
105 // in the layout phase so we can access it during the tearing check that
106 // happens on subscribe.
107
108 useLayoutEffect(() => {
109 inst.value = value;
110 inst.getSnapshot = getSnapshot; // Whenever getSnapshot or subscribe changes, we need to check in the
111 // commit phase if there was an interleaved mutation. In concurrent mode
112 // this can happen all the time, but even in synchronous mode, an earlier
113 // effect may have mutated the store.
114
115 if (checkIfSnapshotChanged(inst)) {
116 // Force a re-render.
117 forceUpdate({
118 inst
119 });
120 } // eslint-disable-next-line react-hooks/exhaustive-deps
121
122 }, [subscribe, value, getSnapshot]);
123 useEffect(() => {
124 // Check for changes right before subscribing. Subsequent changes will be
125 // detected in the subscription handler.
126 if (checkIfSnapshotChanged(inst)) {
127 // Force a re-render.
128 forceUpdate({
129 inst
130 });
131 }
132
133 const handleStoreChange = () => {
134 // TODO: Because there is no cross-renderer API for batching updates, it's
135 // up to the consumer of this library to wrap their subscription event
136 // with unstable_batchedUpdates. Should we try to detect when this isn't
137 // the case and print a warning in development?
138 // The store changed. Check if the snapshot changed since the last time we
139 // read from the store.
140 if (checkIfSnapshotChanged(inst)) {
141 // Force a re-render.
142 forceUpdate({
143 inst
144 });
145 }
146 }; // Subscribe to the store and return a clean-up function.
147
148
149 return subscribe(handleStoreChange); // eslint-disable-next-line react-hooks/exhaustive-deps
150 }, [subscribe]);
151 useDebugValue(value);
152 return value;
153}
154
155function checkIfSnapshotChanged(inst) {
156 const latestGetSnapshot = inst.getSnapshot;
157 const prevValue = inst.value;
158
159 try {
160 const nextValue = latestGetSnapshot();
161 return !is(prevValue, nextValue);
162 } catch (error) {
163 return true;
164 }
165}
166
167/**
168 * Copyright (c) Facebook, Inc. and its affiliates.
169 *
170 * This source code is licensed under the MIT license found in the
171 * LICENSE file in the root directory of this source tree.
172 *
173 * @flow
174 */
175function useSyncExternalStore$1(subscribe, getSnapshot, getServerSnapshot) {
176 // Note: The shim does not use getServerSnapshot, because pre-18 versions of
177 // React do not expose a way to check if we're hydrating. So users of the shim
178 // will need to track that themselves and return the correct value
179 // from `getSnapshot`.
180 return getSnapshot();
181}
182
183/**
184 * Inlined into the react-router repo since use-sync-external-store does not
185 * provide a UMD-compatible package, so we need this to be able to distribute
186 * UMD react-router bundles
187 */
188const canUseDOM = !!(typeof window !== "undefined" && typeof window.document !== "undefined" && typeof window.document.createElement !== "undefined");
189const isServerEnvironment = !canUseDOM;
190const shim = isServerEnvironment ? useSyncExternalStore$1 : useSyncExternalStore$2;
191const useSyncExternalStore = "useSyncExternalStore" in React ? (module => module.useSyncExternalStore)(React) : shim;
192
193const DataStaticRouterContext = /*#__PURE__*/React.createContext(null);
194
195{
196 DataStaticRouterContext.displayName = "DataStaticRouterContext";
197}
198
199const DataRouterContext = /*#__PURE__*/React.createContext(null);
200
201{
202 DataRouterContext.displayName = "DataRouter";
203}
204
205const DataRouterStateContext = /*#__PURE__*/React.createContext(null);
206
207{
208 DataRouterStateContext.displayName = "DataRouterState";
209}
210
211const AwaitContext = /*#__PURE__*/React.createContext(null);
212
213{
214 AwaitContext.displayName = "Await";
215}
216
217const NavigationContext = /*#__PURE__*/React.createContext(null);
218
219{
220 NavigationContext.displayName = "Navigation";
221}
222
223const LocationContext = /*#__PURE__*/React.createContext(null);
224
225{
226 LocationContext.displayName = "Location";
227}
228
229const RouteContext = /*#__PURE__*/React.createContext({
230 outlet: null,
231 matches: []
232});
233
234{
235 RouteContext.displayName = "Route";
236}
237
238const RouteErrorContext = /*#__PURE__*/React.createContext(null);
239
240{
241 RouteErrorContext.displayName = "RouteError";
242}
243
244/**
245 * Returns the full href for the given "to" value. This is useful for building
246 * custom links that are also accessible and preserve right-click behavior.
247 *
248 * @see https://reactrouter.com/docs/en/v6/hooks/use-href
249 */
250
251function useHref(to, {
252 relative
253} = {}) {
254 !useInRouterContext() ? invariant(false, // TODO: This error is probably because they somehow have 2 versions of the
255 // router loaded. We can help them understand how to avoid that.
256 `useHref() may be used only in the context of a <Router> component.`) : void 0;
257 let {
258 basename,
259 navigator
260 } = React.useContext(NavigationContext);
261 let {
262 hash,
263 pathname,
264 search
265 } = useResolvedPath(to, {
266 relative
267 });
268 let joinedPathname = pathname; // If we're operating within a basename, prepend it to the pathname prior
269 // to creating the href. If this is a root navigation, then just use the raw
270 // basename which allows the basename to have full control over the presence
271 // of a trailing slash on root links
272
273 if (basename !== "/") {
274 joinedPathname = pathname === "/" ? basename : joinPaths([basename, pathname]);
275 }
276
277 return navigator.createHref({
278 pathname: joinedPathname,
279 search,
280 hash
281 });
282}
283/**
284 * Returns true if this component is a descendant of a <Router>.
285 *
286 * @see https://reactrouter.com/docs/en/v6/hooks/use-in-router-context
287 */
288
289function useInRouterContext() {
290 return React.useContext(LocationContext) != null;
291}
292/**
293 * Returns the current location object, which represents the current URL in web
294 * browsers.
295 *
296 * Note: If you're using this it may mean you're doing some of your own
297 * "routing" in your app, and we'd like to know what your use case is. We may
298 * be able to provide something higher-level to better suit your needs.
299 *
300 * @see https://reactrouter.com/docs/en/v6/hooks/use-location
301 */
302
303function useLocation() {
304 !useInRouterContext() ? invariant(false, // TODO: This error is probably because they somehow have 2 versions of the
305 // router loaded. We can help them understand how to avoid that.
306 `useLocation() may be used only in the context of a <Router> component.`) : void 0;
307 return React.useContext(LocationContext).location;
308}
309/**
310 * Returns the current navigation action which describes how the router came to
311 * the current location, either by a pop, push, or replace on the history stack.
312 *
313 * @see https://reactrouter.com/docs/en/v6/hooks/use-navigation-type
314 */
315
316function useNavigationType() {
317 return React.useContext(LocationContext).navigationType;
318}
319/**
320 * Returns a PathMatch object if the given pattern matches the current URL.
321 * This is useful for components that need to know "active" state, e.g.
322 * <NavLink>.
323 *
324 * @see https://reactrouter.com/docs/en/v6/hooks/use-match
325 */
326
327function useMatch(pattern) {
328 !useInRouterContext() ? invariant(false, // TODO: This error is probably because they somehow have 2 versions of the
329 // router loaded. We can help them understand how to avoid that.
330 `useMatch() may be used only in the context of a <Router> component.`) : void 0;
331 let {
332 pathname
333 } = useLocation();
334 return React.useMemo(() => matchPath(pattern, pathname), [pathname, pattern]);
335}
336/**
337 * Returns an imperative method for changing the location. Used by <Link>s, but
338 * may also be used by other elements to change the location.
339 *
340 * @see https://reactrouter.com/docs/en/v6/hooks/use-navigate
341 */
342
343function useNavigate() {
344 !useInRouterContext() ? invariant(false, // TODO: This error is probably because they somehow have 2 versions of the
345 // router loaded. We can help them understand how to avoid that.
346 `useNavigate() may be used only in the context of a <Router> component.`) : void 0;
347 let {
348 basename,
349 navigator
350 } = React.useContext(NavigationContext);
351 let {
352 matches
353 } = React.useContext(RouteContext);
354 let {
355 pathname: locationPathname
356 } = useLocation();
357 let routePathnamesJson = JSON.stringify(UNSAFE_getPathContributingMatches(matches).map(match => match.pathnameBase));
358 let activeRef = React.useRef(false);
359 React.useEffect(() => {
360 activeRef.current = true;
361 });
362 let navigate = React.useCallback((to, options = {}) => {
363 warning(activeRef.current, `You should call navigate() in a React.useEffect(), not when ` + `your component is first rendered.`) ;
364 if (!activeRef.current) return;
365
366 if (typeof to === "number") {
367 navigator.go(to);
368 return;
369 }
370
371 let path = resolveTo(to, JSON.parse(routePathnamesJson), locationPathname, options.relative === "path"); // If we're operating within a basename, prepend it to the pathname prior
372 // to handing off to history. If this is a root navigation, then we
373 // navigate to the raw basename which allows the basename to have full
374 // control over the presence of a trailing slash on root links
375
376 if (basename !== "/") {
377 path.pathname = path.pathname === "/" ? basename : joinPaths([basename, path.pathname]);
378 }
379
380 (!!options.replace ? navigator.replace : navigator.push)(path, options.state, options);
381 }, [basename, navigator, routePathnamesJson, locationPathname]);
382 return navigate;
383}
384const OutletContext = /*#__PURE__*/React.createContext(null);
385/**
386 * Returns the context (if provided) for the child route at this level of the route
387 * hierarchy.
388 * @see https://reactrouter.com/docs/en/v6/hooks/use-outlet-context
389 */
390
391function useOutletContext() {
392 return React.useContext(OutletContext);
393}
394/**
395 * Returns the element for the child route at this level of the route
396 * hierarchy. Used internally by <Outlet> to render child routes.
397 *
398 * @see https://reactrouter.com/docs/en/v6/hooks/use-outlet
399 */
400
401function useOutlet(context) {
402 let outlet = React.useContext(RouteContext).outlet;
403
404 if (outlet) {
405 return /*#__PURE__*/React.createElement(OutletContext.Provider, {
406 value: context
407 }, outlet);
408 }
409
410 return outlet;
411}
412/**
413 * Returns an object of key/value pairs of the dynamic params from the current
414 * URL that were matched by the route path.
415 *
416 * @see https://reactrouter.com/docs/en/v6/hooks/use-params
417 */
418
419function useParams() {
420 let {
421 matches
422 } = React.useContext(RouteContext);
423 let routeMatch = matches[matches.length - 1];
424 return routeMatch ? routeMatch.params : {};
425}
426/**
427 * Resolves the pathname of the given `to` value against the current location.
428 *
429 * @see https://reactrouter.com/docs/en/v6/hooks/use-resolved-path
430 */
431
432function useResolvedPath(to, {
433 relative
434} = {}) {
435 let {
436 matches
437 } = React.useContext(RouteContext);
438 let {
439 pathname: locationPathname
440 } = useLocation();
441 let routePathnamesJson = JSON.stringify(UNSAFE_getPathContributingMatches(matches).map(match => match.pathnameBase));
442 return React.useMemo(() => resolveTo(to, JSON.parse(routePathnamesJson), locationPathname, relative === "path"), [to, routePathnamesJson, locationPathname, relative]);
443}
444/**
445 * Returns the element of the route that matched the current location, prepared
446 * with the correct context to render the remainder of the route tree. Route
447 * elements in the tree must render an <Outlet> to render their child route's
448 * element.
449 *
450 * @see https://reactrouter.com/docs/en/v6/hooks/use-routes
451 */
452
453function useRoutes(routes, locationArg) {
454 !useInRouterContext() ? invariant(false, // TODO: This error is probably because they somehow have 2 versions of the
455 // router loaded. We can help them understand how to avoid that.
456 `useRoutes() may be used only in the context of a <Router> component.`) : void 0;
457 let {
458 navigator
459 } = React.useContext(NavigationContext);
460 let dataRouterStateContext = React.useContext(DataRouterStateContext);
461 let {
462 matches: parentMatches
463 } = React.useContext(RouteContext);
464 let routeMatch = parentMatches[parentMatches.length - 1];
465 let parentParams = routeMatch ? routeMatch.params : {};
466 let parentPathname = routeMatch ? routeMatch.pathname : "/";
467 let parentPathnameBase = routeMatch ? routeMatch.pathnameBase : "/";
468 let parentRoute = routeMatch && routeMatch.route;
469
470 {
471 // You won't get a warning about 2 different <Routes> under a <Route>
472 // without a trailing *, but this is a best-effort warning anyway since we
473 // cannot even give the warning unless they land at the parent route.
474 //
475 // Example:
476 //
477 // <Routes>
478 // {/* This route path MUST end with /* because otherwise
479 // it will never match /blog/post/123 */}
480 // <Route path="blog" element={<Blog />} />
481 // <Route path="blog/feed" element={<BlogFeed />} />
482 // </Routes>
483 //
484 // function Blog() {
485 // return (
486 // <Routes>
487 // <Route path="post/:id" element={<Post />} />
488 // </Routes>
489 // );
490 // }
491 let parentPath = parentRoute && parentRoute.path || "";
492 warningOnce(parentPathname, !parentRoute || parentPath.endsWith("*"), `You rendered descendant <Routes> (or called \`useRoutes()\`) at ` + `"${parentPathname}" (under <Route path="${parentPath}">) but the ` + `parent route path has no trailing "*". This means if you navigate ` + `deeper, the parent won't match anymore and therefore the child ` + `routes will never render.\n\n` + `Please change the parent <Route path="${parentPath}"> to <Route ` + `path="${parentPath === "/" ? "*" : `${parentPath}/*`}">.`);
493 }
494
495 let locationFromContext = useLocation();
496 let location;
497
498 if (locationArg) {
499 let parsedLocationArg = typeof locationArg === "string" ? parsePath(locationArg) : locationArg;
500 !(parentPathnameBase === "/" || parsedLocationArg.pathname?.startsWith(parentPathnameBase)) ? invariant(false, `When overriding the location using \`<Routes location>\` or \`useRoutes(routes, location)\`, ` + `the location pathname must begin with the portion of the URL pathname that was ` + `matched by all parent routes. The current pathname base is "${parentPathnameBase}" ` + `but pathname "${parsedLocationArg.pathname}" was given in the \`location\` prop.`) : void 0;
501 location = parsedLocationArg;
502 } else {
503 location = locationFromContext;
504 }
505
506 let pathname = location.pathname || "/";
507 let remainingPathname = parentPathnameBase === "/" ? pathname : pathname.slice(parentPathnameBase.length) || "/";
508 let matches = matchRoutes(routes, {
509 pathname: remainingPathname
510 });
511
512 {
513 warning(parentRoute || matches != null, `No routes matched location "${location.pathname}${location.search}${location.hash}" `) ;
514 warning(matches == null || matches[matches.length - 1].route.element !== undefined, `Matched leaf route at location "${location.pathname}${location.search}${location.hash}" does not have an element. ` + `This means it will render an <Outlet /> with a null value by default resulting in an "empty" page.`) ;
515 }
516
517 let renderedMatches = _renderMatches(matches && matches.map(match => Object.assign({}, match, {
518 params: Object.assign({}, parentParams, match.params),
519 pathname: joinPaths([parentPathnameBase, // Re-encode pathnames that were decoded inside matchRoutes
520 navigator.encodeLocation ? navigator.encodeLocation(match.pathname).pathname : match.pathname]),
521 pathnameBase: match.pathnameBase === "/" ? parentPathnameBase : joinPaths([parentPathnameBase, // Re-encode pathnames that were decoded inside matchRoutes
522 navigator.encodeLocation ? navigator.encodeLocation(match.pathnameBase).pathname : match.pathnameBase])
523 })), parentMatches, dataRouterStateContext || undefined); // When a user passes in a `locationArg`, the associated routes need to
524 // be wrapped in a new `LocationContext.Provider` in order for `useLocation`
525 // to use the scoped location instead of the global location.
526
527
528 if (locationArg && renderedMatches) {
529 return /*#__PURE__*/React.createElement(LocationContext.Provider, {
530 value: {
531 location: {
532 pathname: "/",
533 search: "",
534 hash: "",
535 state: null,
536 key: "default",
537 ...location
538 },
539 navigationType: Action.Pop
540 }
541 }, renderedMatches);
542 }
543
544 return renderedMatches;
545}
546
547function DefaultErrorElement() {
548 let error = useRouteError();
549 let message = isRouteErrorResponse(error) ? `${error.status} ${error.statusText}` : error instanceof Error ? error.message : JSON.stringify(error);
550 let stack = error instanceof Error ? error.stack : null;
551 let lightgrey = "rgba(200,200,200, 0.5)";
552 let preStyles = {
553 padding: "0.5rem",
554 backgroundColor: lightgrey
555 };
556 let codeStyles = {
557 padding: "2px 4px",
558 backgroundColor: lightgrey
559 };
560 return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement("h2", null, "Unhandled Thrown Error!"), /*#__PURE__*/React.createElement("h3", {
561 style: {
562 fontStyle: "italic"
563 }
564 }, message), stack ? /*#__PURE__*/React.createElement("pre", {
565 style: preStyles
566 }, stack) : null, /*#__PURE__*/React.createElement("p", null, "\uD83D\uDCBF Hey developer \uD83D\uDC4B"), /*#__PURE__*/React.createElement("p", null, "You can provide a way better UX than this when your app throws errors by providing your own\u00A0", /*#__PURE__*/React.createElement("code", {
567 style: codeStyles
568 }, "errorElement"), " props on\u00A0", /*#__PURE__*/React.createElement("code", {
569 style: codeStyles
570 }, "<Route>")));
571}
572
573class RenderErrorBoundary extends React.Component {
574 constructor(props) {
575 super(props);
576 this.state = {
577 location: props.location,
578 error: props.error
579 };
580 }
581
582 static getDerivedStateFromError(error) {
583 return {
584 error: error
585 };
586 }
587
588 static getDerivedStateFromProps(props, state) {
589 // When we get into an error state, the user will likely click "back" to the
590 // previous page that didn't have an error. Because this wraps the entire
591 // application, that will have no effect--the error page continues to display.
592 // This gives us a mechanism to recover from the error when the location changes.
593 //
594 // Whether we're in an error state or not, we update the location in state
595 // so that when we are in an error state, it gets reset when a new location
596 // comes in and the user recovers from the error.
597 if (state.location !== props.location) {
598 return {
599 error: props.error,
600 location: props.location
601 };
602 } // If we're not changing locations, preserve the location but still surface
603 // any new errors that may come through. We retain the existing error, we do
604 // this because the error provided from the app state may be cleared without
605 // the location changing.
606
607
608 return {
609 error: props.error || state.error,
610 location: state.location
611 };
612 }
613
614 componentDidCatch(error, errorInfo) {
615 console.error("React Router caught the following error during render", error, errorInfo);
616 }
617
618 render() {
619 return this.state.error ? /*#__PURE__*/React.createElement(RouteErrorContext.Provider, {
620 value: this.state.error,
621 children: this.props.component
622 }) : this.props.children;
623 }
624
625}
626
627function RenderedRoute({
628 routeContext,
629 match,
630 children
631}) {
632 let dataStaticRouterContext = React.useContext(DataStaticRouterContext); // Track how deep we got in our render pass to emulate SSR componentDidCatch
633 // in a DataStaticRouter
634
635 if (dataStaticRouterContext && match.route.errorElement) {
636 dataStaticRouterContext._deepestRenderedBoundaryId = match.route.id;
637 }
638
639 return /*#__PURE__*/React.createElement(RouteContext.Provider, {
640 value: routeContext
641 }, children);
642}
643
644function _renderMatches(matches, parentMatches = [], dataRouterState) {
645 if (matches == null) {
646 if (dataRouterState?.errors) {
647 // Don't bail if we have data router errors so we can render them in the
648 // boundary. Use the pre-matched (or shimmed) matches
649 matches = dataRouterState.matches;
650 } else {
651 return null;
652 }
653 }
654
655 let renderedMatches = matches; // If we have data errors, trim matches to the highest error boundary
656
657 let errors = dataRouterState?.errors;
658
659 if (errors != null) {
660 let errorIndex = renderedMatches.findIndex(m => m.route.id && errors?.[m.route.id]);
661 !(errorIndex >= 0) ? invariant(false, `Could not find a matching route for the current errors: ${errors}`) : void 0;
662 renderedMatches = renderedMatches.slice(0, Math.min(renderedMatches.length, errorIndex + 1));
663 }
664
665 return renderedMatches.reduceRight((outlet, match, index) => {
666 let error = match.route.id ? errors?.[match.route.id] : null; // Only data routers handle errors
667
668 let errorElement = dataRouterState ? match.route.errorElement || /*#__PURE__*/React.createElement(DefaultErrorElement, null) : null;
669
670 let getChildren = () => /*#__PURE__*/React.createElement(RenderedRoute, {
671 match: match,
672 routeContext: {
673 outlet,
674 matches: parentMatches.concat(renderedMatches.slice(0, index + 1))
675 }
676 }, error ? errorElement : match.route.element !== undefined ? match.route.element : outlet); // Only wrap in an error boundary within data router usages when we have an
677 // errorElement on this route. Otherwise let it bubble up to an ancestor
678 // errorElement
679
680
681 return dataRouterState && (match.route.errorElement || index === 0) ? /*#__PURE__*/React.createElement(RenderErrorBoundary, {
682 location: dataRouterState.location,
683 component: errorElement,
684 error: error,
685 children: getChildren()
686 }) : getChildren();
687 }, null);
688}
689var DataRouterHook;
690
691(function (DataRouterHook) {
692 DataRouterHook["UseRevalidator"] = "useRevalidator";
693})(DataRouterHook || (DataRouterHook = {}));
694
695var DataRouterStateHook;
696
697(function (DataRouterStateHook) {
698 DataRouterStateHook["UseLoaderData"] = "useLoaderData";
699 DataRouterStateHook["UseActionData"] = "useActionData";
700 DataRouterStateHook["UseRouteError"] = "useRouteError";
701 DataRouterStateHook["UseNavigation"] = "useNavigation";
702 DataRouterStateHook["UseRouteLoaderData"] = "useRouteLoaderData";
703 DataRouterStateHook["UseMatches"] = "useMatches";
704 DataRouterStateHook["UseRevalidator"] = "useRevalidator";
705})(DataRouterStateHook || (DataRouterStateHook = {}));
706
707function getDataRouterConsoleError(hookName) {
708 return `${hookName} must be used within a data router. See https://reactrouter.com/en/main/routers/picking-a-router.`;
709}
710
711function useDataRouterContext(hookName) {
712 let ctx = React.useContext(DataRouterContext);
713 !ctx ? invariant(false, getDataRouterConsoleError(hookName)) : void 0;
714 return ctx;
715}
716
717function useDataRouterState(hookName) {
718 let state = React.useContext(DataRouterStateContext);
719 !state ? invariant(false, getDataRouterConsoleError(hookName)) : void 0;
720 return state;
721}
722/**
723 * Returns the current navigation, defaulting to an "idle" navigation when
724 * no navigation is in progress
725 */
726
727
728function useNavigation() {
729 let state = useDataRouterState(DataRouterStateHook.UseNavigation);
730 return state.navigation;
731}
732/**
733 * Returns a revalidate function for manually triggering revalidation, as well
734 * as the current state of any manual revalidations
735 */
736
737function useRevalidator() {
738 let dataRouterContext = useDataRouterContext(DataRouterHook.UseRevalidator);
739 let state = useDataRouterState(DataRouterStateHook.UseRevalidator);
740 return {
741 revalidate: dataRouterContext.router.revalidate,
742 state: state.revalidation
743 };
744}
745/**
746 * Returns the active route matches, useful for accessing loaderData for
747 * parent/child routes or the route "handle" property
748 */
749
750function useMatches() {
751 let {
752 matches,
753 loaderData
754 } = useDataRouterState(DataRouterStateHook.UseMatches);
755 return React.useMemo(() => matches.map(match => {
756 let {
757 pathname,
758 params
759 } = match; // Note: This structure matches that created by createUseMatchesMatch
760 // in the @remix-run/router , so if you change this please also change
761 // that :) Eventually we'll DRY this up
762
763 return {
764 id: match.route.id,
765 pathname,
766 params,
767 data: loaderData[match.route.id],
768 handle: match.route.handle
769 };
770 }), [matches, loaderData]);
771}
772/**
773 * Returns the loader data for the nearest ancestor Route loader
774 */
775
776function useLoaderData() {
777 let state = useDataRouterState(DataRouterStateHook.UseLoaderData);
778 let route = React.useContext(RouteContext);
779 !route ? invariant(false, `useLoaderData must be used inside a RouteContext`) : void 0;
780 let thisRoute = route.matches[route.matches.length - 1];
781 !thisRoute.route.id ? invariant(false, `useLoaderData can only be used on routes that contain a unique "id"`) : void 0;
782 return state.loaderData[thisRoute.route.id];
783}
784/**
785 * Returns the loaderData for the given routeId
786 */
787
788function useRouteLoaderData(routeId) {
789 let state = useDataRouterState(DataRouterStateHook.UseRouteLoaderData);
790 return state.loaderData[routeId];
791}
792/**
793 * Returns the action data for the nearest ancestor Route action
794 */
795
796function useActionData() {
797 let state = useDataRouterState(DataRouterStateHook.UseActionData);
798 let route = React.useContext(RouteContext);
799 !route ? invariant(false, `useActionData must be used inside a RouteContext`) : void 0;
800 return Object.values(state?.actionData || {})[0];
801}
802/**
803 * Returns the nearest ancestor Route error, which could be a loader/action
804 * error or a render error. This is intended to be called from your
805 * errorElement to display a proper error message.
806 */
807
808function useRouteError() {
809 let error = React.useContext(RouteErrorContext);
810 let state = useDataRouterState(DataRouterStateHook.UseRouteError);
811 let route = React.useContext(RouteContext);
812 let thisRoute = route.matches[route.matches.length - 1]; // If this was a render error, we put it in a RouteError context inside
813 // of RenderErrorBoundary
814
815 if (error) {
816 return error;
817 }
818
819 !route ? invariant(false, `useRouteError must be used inside a RouteContext`) : void 0;
820 !thisRoute.route.id ? invariant(false, `useRouteError can only be used on routes that contain a unique "id"`) : void 0; // Otherwise look for errors from our data router state
821
822 return state.errors?.[thisRoute.route.id];
823}
824/**
825 * Returns the happy-path data from the nearest ancestor <Await /> value
826 */
827
828function useAsyncValue() {
829 let value = React.useContext(AwaitContext);
830 return value?._data;
831}
832/**
833 * Returns the error from the nearest ancestor <Await /> value
834 */
835
836function useAsyncError() {
837 let value = React.useContext(AwaitContext);
838 return value?._error;
839}
840const alreadyWarned = {};
841
842function warningOnce(key, cond, message) {
843 if (!cond && !alreadyWarned[key]) {
844 alreadyWarned[key] = true;
845 warning(false, message) ;
846 }
847}
848
849/**
850 * Given a Remix Router instance, render the appropriate UI
851 */
852
853function RouterProvider({
854 fallbackElement,
855 router
856}) {
857 // Sync router state to our component state to force re-renders
858 let state = useSyncExternalStore(router.subscribe, () => router.state, // We have to provide this so React@18 doesn't complain during hydration,
859 // but we pass our serialized hydration data into the router so state here
860 // is already synced with what the server saw
861 () => router.state);
862 let navigator = React.useMemo(() => {
863 return {
864 createHref: router.createHref,
865 encodeLocation: router.encodeLocation,
866 go: n => router.navigate(n),
867 push: (to, state, opts) => router.navigate(to, {
868 state,
869 preventScrollReset: opts?.preventScrollReset
870 }),
871 replace: (to, state, opts) => router.navigate(to, {
872 replace: true,
873 state,
874 preventScrollReset: opts?.preventScrollReset
875 })
876 };
877 }, [router]);
878 let basename = router.basename || "/";
879 return /*#__PURE__*/React.createElement(DataRouterContext.Provider, {
880 value: {
881 router,
882 navigator,
883 static: false,
884 // Do we need this?
885 basename
886 }
887 }, /*#__PURE__*/React.createElement(DataRouterStateContext.Provider, {
888 value: state
889 }, /*#__PURE__*/React.createElement(Router, {
890 basename: router.basename,
891 location: router.state.location,
892 navigationType: router.state.historyAction,
893 navigator: navigator
894 }, router.state.initialized ? /*#__PURE__*/React.createElement(Routes, null) : fallbackElement)));
895}
896/**
897 * A <Router> that stores all entries in memory.
898 *
899 * @see https://reactrouter.com/docs/en/v6/routers/memory-router
900 */
901
902function MemoryRouter({
903 basename,
904 children,
905 initialEntries,
906 initialIndex
907}) {
908 let historyRef = React.useRef();
909
910 if (historyRef.current == null) {
911 historyRef.current = createMemoryHistory({
912 initialEntries,
913 initialIndex,
914 v5Compat: true
915 });
916 }
917
918 let history = historyRef.current;
919 let [state, setState] = React.useState({
920 action: history.action,
921 location: history.location
922 });
923 React.useLayoutEffect(() => history.listen(setState), [history]);
924 return /*#__PURE__*/React.createElement(Router, {
925 basename: basename,
926 children: children,
927 location: state.location,
928 navigationType: state.action,
929 navigator: history
930 });
931}
932/**
933 * Changes the current location.
934 *
935 * Note: This API is mostly useful in React.Component subclasses that are not
936 * able to use hooks. In functional components, we recommend you use the
937 * `useNavigate` hook instead.
938 *
939 * @see https://reactrouter.com/docs/en/v6/components/navigate
940 */
941
942function Navigate({
943 to,
944 replace,
945 state,
946 relative
947}) {
948 !useInRouterContext() ? invariant(false, // TODO: This error is probably because they somehow have 2 versions of
949 // the router loaded. We can help them understand how to avoid that.
950 `<Navigate> may be used only in the context of a <Router> component.`) : void 0;
951 warning(!React.useContext(NavigationContext).static, `<Navigate> must not be used on the initial render in a <StaticRouter>. ` + `This is a no-op, but you should modify your code so the <Navigate> is ` + `only ever rendered in response to some user interaction or state change.`) ;
952 let dataRouterState = React.useContext(DataRouterStateContext);
953 let navigate = useNavigate();
954 React.useEffect(() => {
955 // Avoid kicking off multiple navigations if we're in the middle of a
956 // data-router navigation, since components get re-rendered when we enter
957 // a submitting/loading state
958 if (dataRouterState && dataRouterState.navigation.state !== "idle") {
959 return;
960 }
961
962 navigate(to, {
963 replace,
964 state,
965 relative
966 });
967 });
968 return null;
969}
970/**
971 * Renders the child route's element, if there is one.
972 *
973 * @see https://reactrouter.com/docs/en/v6/components/outlet
974 */
975
976function Outlet(props) {
977 return useOutlet(props.context);
978}
979/**
980 * Declares an element that should be rendered at a certain URL path.
981 *
982 * @see https://reactrouter.com/docs/en/v6/components/route
983 */
984
985function Route(_props) {
986 invariant(false, `A <Route> is only ever to be used as the child of <Routes> element, ` + `never rendered directly. Please wrap your <Route> in a <Routes>.`) ;
987}
988/**
989 * Provides location context for the rest of the app.
990 *
991 * Note: You usually won't render a <Router> directly. Instead, you'll render a
992 * router that is more specific to your environment such as a <BrowserRouter>
993 * in web browsers or a <StaticRouter> for server rendering.
994 *
995 * @see https://reactrouter.com/docs/en/v6/routers/router
996 */
997
998function Router({
999 basename: basenameProp = "/",
1000 children = null,
1001 location: locationProp,
1002 navigationType = Action.Pop,
1003 navigator,
1004 static: staticProp = false
1005}) {
1006 !!useInRouterContext() ? invariant(false, `You cannot render a <Router> inside another <Router>.` + ` You should never have more than one in your app.`) : void 0; // Preserve trailing slashes on basename, so we can let the user control
1007 // the enforcement of trailing slashes throughout the app
1008
1009 let basename = basenameProp.replace(/^\/*/, "/");
1010 let navigationContext = React.useMemo(() => ({
1011 basename,
1012 navigator,
1013 static: staticProp
1014 }), [basename, navigator, staticProp]);
1015
1016 if (typeof locationProp === "string") {
1017 locationProp = parsePath(locationProp);
1018 }
1019
1020 let {
1021 pathname = "/",
1022 search = "",
1023 hash = "",
1024 state = null,
1025 key = "default"
1026 } = locationProp;
1027 let location = React.useMemo(() => {
1028 let trailingPathname = stripBasename(pathname, basename);
1029
1030 if (trailingPathname == null) {
1031 return null;
1032 }
1033
1034 return {
1035 pathname: trailingPathname,
1036 search,
1037 hash,
1038 state,
1039 key
1040 };
1041 }, [basename, pathname, search, hash, state, key]);
1042 warning(location != null, `<Router basename="${basename}"> is not able to match the URL ` + `"${pathname}${search}${hash}" because it does not start with the ` + `basename, so the <Router> won't render anything.`) ;
1043
1044 if (location == null) {
1045 return null;
1046 }
1047
1048 return /*#__PURE__*/React.createElement(NavigationContext.Provider, {
1049 value: navigationContext
1050 }, /*#__PURE__*/React.createElement(LocationContext.Provider, {
1051 children: children,
1052 value: {
1053 location,
1054 navigationType
1055 }
1056 }));
1057}
1058/**
1059 * A container for a nested tree of <Route> elements that renders the branch
1060 * that best matches the current location.
1061 *
1062 * @see https://reactrouter.com/docs/en/v6/components/routes
1063 */
1064
1065function Routes({
1066 children,
1067 location
1068}) {
1069 let dataRouterContext = React.useContext(DataRouterContext); // When in a DataRouterContext _without_ children, we use the router routes
1070 // directly. If we have children, then we're in a descendant tree and we
1071 // need to use child routes.
1072
1073 let routes = dataRouterContext && !children ? dataRouterContext.router.routes : createRoutesFromChildren(children);
1074 return useRoutes(routes, location);
1075}
1076/**
1077 * Component to use for rendering lazily loaded data from returning defer()
1078 * in a loader function
1079 */
1080
1081function Await({
1082 children,
1083 errorElement,
1084 resolve
1085}) {
1086 return /*#__PURE__*/React.createElement(AwaitErrorBoundary, {
1087 resolve: resolve,
1088 errorElement: errorElement
1089 }, /*#__PURE__*/React.createElement(ResolveAwait, null, children));
1090}
1091var AwaitRenderStatus;
1092
1093(function (AwaitRenderStatus) {
1094 AwaitRenderStatus[AwaitRenderStatus["pending"] = 0] = "pending";
1095 AwaitRenderStatus[AwaitRenderStatus["success"] = 1] = "success";
1096 AwaitRenderStatus[AwaitRenderStatus["error"] = 2] = "error";
1097})(AwaitRenderStatus || (AwaitRenderStatus = {}));
1098
1099const neverSettledPromise = new Promise(() => {});
1100
1101class AwaitErrorBoundary extends React.Component {
1102 constructor(props) {
1103 super(props);
1104 this.state = {
1105 error: null
1106 };
1107 }
1108
1109 static getDerivedStateFromError(error) {
1110 return {
1111 error
1112 };
1113 }
1114
1115 componentDidCatch(error, errorInfo) {
1116 console.error("<Await> caught the following error during render", error, errorInfo);
1117 }
1118
1119 render() {
1120 let {
1121 children,
1122 errorElement,
1123 resolve
1124 } = this.props;
1125 let promise = null;
1126 let status = AwaitRenderStatus.pending;
1127
1128 if (!(resolve instanceof Promise)) {
1129 // Didn't get a promise - provide as a resolved promise
1130 status = AwaitRenderStatus.success;
1131 promise = Promise.resolve();
1132 Object.defineProperty(promise, "_tracked", {
1133 get: () => true
1134 });
1135 Object.defineProperty(promise, "_data", {
1136 get: () => resolve
1137 });
1138 } else if (this.state.error) {
1139 // Caught a render error, provide it as a rejected promise
1140 status = AwaitRenderStatus.error;
1141 let renderError = this.state.error;
1142 promise = Promise.reject().catch(() => {}); // Avoid unhandled rejection warnings
1143
1144 Object.defineProperty(promise, "_tracked", {
1145 get: () => true
1146 });
1147 Object.defineProperty(promise, "_error", {
1148 get: () => renderError
1149 });
1150 } else if (resolve._tracked) {
1151 // Already tracked promise - check contents
1152 promise = resolve;
1153 status = promise._error !== undefined ? AwaitRenderStatus.error : promise._data !== undefined ? AwaitRenderStatus.success : AwaitRenderStatus.pending;
1154 } else {
1155 // Raw (untracked) promise - track it
1156 status = AwaitRenderStatus.pending;
1157 Object.defineProperty(resolve, "_tracked", {
1158 get: () => true
1159 });
1160 promise = resolve.then(data => Object.defineProperty(resolve, "_data", {
1161 get: () => data
1162 }), error => Object.defineProperty(resolve, "_error", {
1163 get: () => error
1164 }));
1165 }
1166
1167 if (status === AwaitRenderStatus.error && promise._error instanceof AbortedDeferredError) {
1168 // Freeze the UI by throwing a never resolved promise
1169 throw neverSettledPromise;
1170 }
1171
1172 if (status === AwaitRenderStatus.error && !errorElement) {
1173 // No errorElement, throw to the nearest route-level error boundary
1174 throw promise._error;
1175 }
1176
1177 if (status === AwaitRenderStatus.error) {
1178 // Render via our errorElement
1179 return /*#__PURE__*/React.createElement(AwaitContext.Provider, {
1180 value: promise,
1181 children: errorElement
1182 });
1183 }
1184
1185 if (status === AwaitRenderStatus.success) {
1186 // Render children with resolved value
1187 return /*#__PURE__*/React.createElement(AwaitContext.Provider, {
1188 value: promise,
1189 children: children
1190 });
1191 } // Throw to the suspense boundary
1192
1193
1194 throw promise;
1195 }
1196
1197}
1198/**
1199 * @private
1200 * Indirection to leverage useAsyncValue for a render-prop API on <Await>
1201 */
1202
1203
1204function ResolveAwait({
1205 children
1206}) {
1207 let data = useAsyncValue();
1208
1209 if (typeof children === "function") {
1210 return children(data);
1211 }
1212
1213 return /*#__PURE__*/React.createElement(React.Fragment, null, children);
1214} ///////////////////////////////////////////////////////////////////////////////
1215// UTILS
1216///////////////////////////////////////////////////////////////////////////////
1217
1218/**
1219 * Creates a route config from a React "children" object, which is usually
1220 * either a `<Route>` element or an array of them. Used internally by
1221 * `<Routes>` to create a route config from its children.
1222 *
1223 * @see https://reactrouter.com/docs/en/v6/utils/create-routes-from-children
1224 */
1225
1226
1227function createRoutesFromChildren(children, parentPath = []) {
1228 let routes = [];
1229 React.Children.forEach(children, (element, index) => {
1230 if (! /*#__PURE__*/React.isValidElement(element)) {
1231 // Ignore non-elements. This allows people to more easily inline
1232 // conditionals in their route config.
1233 return;
1234 }
1235
1236 if (element.type === React.Fragment) {
1237 // Transparently support React.Fragment and its children.
1238 routes.push.apply(routes, createRoutesFromChildren(element.props.children, parentPath));
1239 return;
1240 }
1241
1242 !(element.type === Route) ? invariant(false, `[${typeof element.type === "string" ? element.type : element.type.name}] is not a <Route> component. All component children of <Routes> must be a <Route> or <React.Fragment>`) : void 0;
1243 !(!element.props.index || !element.props.children) ? invariant(false, "An index route cannot have child routes.") : void 0;
1244 let treePath = [...parentPath, index];
1245 let route = {
1246 id: element.props.id || treePath.join("-"),
1247 caseSensitive: element.props.caseSensitive,
1248 element: element.props.element,
1249 index: element.props.index,
1250 path: element.props.path,
1251 loader: element.props.loader,
1252 action: element.props.action,
1253 errorElement: element.props.errorElement,
1254 hasErrorBoundary: element.props.errorElement != null,
1255 shouldRevalidate: element.props.shouldRevalidate,
1256 handle: element.props.handle
1257 };
1258
1259 if (element.props.children) {
1260 route.children = createRoutesFromChildren(element.props.children, treePath);
1261 }
1262
1263 routes.push(route);
1264 });
1265 return routes;
1266}
1267/**
1268 * Renders the result of `matchRoutes()` into a React element.
1269 */
1270
1271function renderMatches(matches) {
1272 return _renderMatches(matches);
1273}
1274/**
1275 * @private
1276 * Walk the route tree and add hasErrorBoundary if it's not provided, so that
1277 * users providing manual route arrays can just specify errorElement
1278 */
1279
1280function enhanceManualRouteObjects(routes) {
1281 return routes.map(route => {
1282 let routeClone = { ...route
1283 };
1284
1285 if (routeClone.hasErrorBoundary == null) {
1286 routeClone.hasErrorBoundary = routeClone.errorElement != null;
1287 }
1288
1289 if (routeClone.children) {
1290 routeClone.children = enhanceManualRouteObjects(routeClone.children);
1291 }
1292
1293 return routeClone;
1294 });
1295}
1296
1297function createMemoryRouter(routes, opts) {
1298 return createRouter({
1299 basename: opts?.basename,
1300 history: createMemoryHistory({
1301 initialEntries: opts?.initialEntries,
1302 initialIndex: opts?.initialIndex
1303 }),
1304 hydrationData: opts?.hydrationData,
1305 routes: enhanceManualRouteObjects(routes)
1306 }).initialize();
1307} ///////////////////////////////////////////////////////////////////////////////
1308
1309export { Await, MemoryRouter, Navigate, Outlet, Route, Router, RouterProvider, Routes, DataRouterContext as UNSAFE_DataRouterContext, DataRouterStateContext as UNSAFE_DataRouterStateContext, DataStaticRouterContext as UNSAFE_DataStaticRouterContext, LocationContext as UNSAFE_LocationContext, NavigationContext as UNSAFE_NavigationContext, RouteContext as UNSAFE_RouteContext, enhanceManualRouteObjects as UNSAFE_enhanceManualRouteObjects, createMemoryRouter, createRoutesFromChildren, createRoutesFromChildren as createRoutesFromElements, renderMatches, useActionData, useAsyncError, useAsyncValue, useHref, useInRouterContext, useLoaderData, useLocation, useMatch, useMatches, useNavigate, useNavigation, useNavigationType, useOutlet, useOutletContext, useParams, useResolvedPath, useRevalidator, useRouteError, useRouteLoaderData, useRoutes };
1310//# sourceMappingURL=react-router.development.js.map