UNPKG

45.7 kBJavaScriptView Raw
1/**
2 * React Router v6.4.3
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 true if the URL for the given "to" value 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 dataRouterStateContext = React.useContext(DataRouterStateContext);
458 let {
459 matches: parentMatches
460 } = React.useContext(RouteContext);
461 let routeMatch = parentMatches[parentMatches.length - 1];
462 let parentParams = routeMatch ? routeMatch.params : {};
463 let parentPathname = routeMatch ? routeMatch.pathname : "/";
464 let parentPathnameBase = routeMatch ? routeMatch.pathnameBase : "/";
465 let parentRoute = routeMatch && routeMatch.route;
466
467 {
468 // You won't get a warning about 2 different <Routes> under a <Route>
469 // without a trailing *, but this is a best-effort warning anyway since we
470 // cannot even give the warning unless they land at the parent route.
471 //
472 // Example:
473 //
474 // <Routes>
475 // {/* This route path MUST end with /* because otherwise
476 // it will never match /blog/post/123 */}
477 // <Route path="blog" element={<Blog />} />
478 // <Route path="blog/feed" element={<BlogFeed />} />
479 // </Routes>
480 //
481 // function Blog() {
482 // return (
483 // <Routes>
484 // <Route path="post/:id" element={<Post />} />
485 // </Routes>
486 // );
487 // }
488 let parentPath = parentRoute && parentRoute.path || "";
489 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}/*`}">.`);
490 }
491
492 let locationFromContext = useLocation();
493 let location;
494
495 if (locationArg) {
496 let parsedLocationArg = typeof locationArg === "string" ? parsePath(locationArg) : locationArg;
497 !(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;
498 location = parsedLocationArg;
499 } else {
500 location = locationFromContext;
501 }
502
503 let pathname = location.pathname || "/";
504 let remainingPathname = parentPathnameBase === "/" ? pathname : pathname.slice(parentPathnameBase.length) || "/";
505 let matches = matchRoutes(routes, {
506 pathname: remainingPathname
507 });
508
509 {
510 warning(parentRoute || matches != null, `No routes matched location "${location.pathname}${location.search}${location.hash}" `) ;
511 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.`) ;
512 }
513
514 let renderedMatches = _renderMatches(matches && matches.map(match => Object.assign({}, match, {
515 params: Object.assign({}, parentParams, match.params),
516 pathname: joinPaths([parentPathnameBase, match.pathname]),
517 pathnameBase: match.pathnameBase === "/" ? parentPathnameBase : joinPaths([parentPathnameBase, match.pathnameBase])
518 })), parentMatches, dataRouterStateContext || undefined); // When a user passes in a `locationArg`, the associated routes need to
519 // be wrapped in a new `LocationContext.Provider` in order for `useLocation`
520 // to use the scoped location instead of the global location.
521
522
523 if (locationArg && renderedMatches) {
524 return /*#__PURE__*/React.createElement(LocationContext.Provider, {
525 value: {
526 location: {
527 pathname: "/",
528 search: "",
529 hash: "",
530 state: null,
531 key: "default",
532 ...location
533 },
534 navigationType: Action.Pop
535 }
536 }, renderedMatches);
537 }
538
539 return renderedMatches;
540}
541
542function DefaultErrorElement() {
543 let error = useRouteError();
544 let message = isRouteErrorResponse(error) ? `${error.status} ${error.statusText}` : error instanceof Error ? error.message : JSON.stringify(error);
545 let stack = error instanceof Error ? error.stack : null;
546 let lightgrey = "rgba(200,200,200, 0.5)";
547 let preStyles = {
548 padding: "0.5rem",
549 backgroundColor: lightgrey
550 };
551 let codeStyles = {
552 padding: "2px 4px",
553 backgroundColor: lightgrey
554 };
555 return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement("h2", null, "Unhandled Thrown Error!"), /*#__PURE__*/React.createElement("h3", {
556 style: {
557 fontStyle: "italic"
558 }
559 }, message), stack ? /*#__PURE__*/React.createElement("pre", {
560 style: preStyles
561 }, 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", {
562 style: codeStyles
563 }, "errorElement"), " props on\u00A0", /*#__PURE__*/React.createElement("code", {
564 style: codeStyles
565 }, "<Route>")));
566}
567
568class RenderErrorBoundary extends React.Component {
569 constructor(props) {
570 super(props);
571 this.state = {
572 location: props.location,
573 error: props.error
574 };
575 }
576
577 static getDerivedStateFromError(error) {
578 return {
579 error: error
580 };
581 }
582
583 static getDerivedStateFromProps(props, state) {
584 // When we get into an error state, the user will likely click "back" to the
585 // previous page that didn't have an error. Because this wraps the entire
586 // application, that will have no effect--the error page continues to display.
587 // This gives us a mechanism to recover from the error when the location changes.
588 //
589 // Whether we're in an error state or not, we update the location in state
590 // so that when we are in an error state, it gets reset when a new location
591 // comes in and the user recovers from the error.
592 if (state.location !== props.location) {
593 return {
594 error: props.error,
595 location: props.location
596 };
597 } // If we're not changing locations, preserve the location but still surface
598 // any new errors that may come through. We retain the existing error, we do
599 // this because the error provided from the app state may be cleared without
600 // the location changing.
601
602
603 return {
604 error: props.error || state.error,
605 location: state.location
606 };
607 }
608
609 componentDidCatch(error, errorInfo) {
610 console.error("React Router caught the following error during render", error, errorInfo);
611 }
612
613 render() {
614 return this.state.error ? /*#__PURE__*/React.createElement(RouteErrorContext.Provider, {
615 value: this.state.error,
616 children: this.props.component
617 }) : this.props.children;
618 }
619
620}
621
622function RenderedRoute({
623 routeContext,
624 match,
625 children
626}) {
627 let dataStaticRouterContext = React.useContext(DataStaticRouterContext); // Track how deep we got in our render pass to emulate SSR componentDidCatch
628 // in a DataStaticRouter
629
630 if (dataStaticRouterContext && match.route.errorElement) {
631 dataStaticRouterContext._deepestRenderedBoundaryId = match.route.id;
632 }
633
634 return /*#__PURE__*/React.createElement(RouteContext.Provider, {
635 value: routeContext
636 }, children);
637}
638
639function _renderMatches(matches, parentMatches = [], dataRouterState) {
640 if (matches == null) {
641 if (dataRouterState?.errors) {
642 // Don't bail if we have data router errors so we can render them in the
643 // boundary. Use the pre-matched (or shimmed) matches
644 matches = dataRouterState.matches;
645 } else {
646 return null;
647 }
648 }
649
650 let renderedMatches = matches; // If we have data errors, trim matches to the highest error boundary
651
652 let errors = dataRouterState?.errors;
653
654 if (errors != null) {
655 let errorIndex = renderedMatches.findIndex(m => m.route.id && errors?.[m.route.id]);
656 !(errorIndex >= 0) ? invariant(false, `Could not find a matching route for the current errors: ${errors}`) : void 0;
657 renderedMatches = renderedMatches.slice(0, Math.min(renderedMatches.length, errorIndex + 1));
658 }
659
660 return renderedMatches.reduceRight((outlet, match, index) => {
661 let error = match.route.id ? errors?.[match.route.id] : null; // Only data routers handle errors
662
663 let errorElement = dataRouterState ? match.route.errorElement || /*#__PURE__*/React.createElement(DefaultErrorElement, null) : null;
664
665 let getChildren = () => /*#__PURE__*/React.createElement(RenderedRoute, {
666 match: match,
667 routeContext: {
668 outlet,
669 matches: parentMatches.concat(renderedMatches.slice(0, index + 1))
670 }
671 }, error ? errorElement : match.route.element !== undefined ? match.route.element : outlet); // Only wrap in an error boundary within data router usages when we have an
672 // errorElement on this route. Otherwise let it bubble up to an ancestor
673 // errorElement
674
675
676 return dataRouterState && (match.route.errorElement || index === 0) ? /*#__PURE__*/React.createElement(RenderErrorBoundary, {
677 location: dataRouterState.location,
678 component: errorElement,
679 error: error,
680 children: getChildren()
681 }) : getChildren();
682 }, null);
683}
684var DataRouterHook;
685
686(function (DataRouterHook) {
687 DataRouterHook["UseRevalidator"] = "useRevalidator";
688})(DataRouterHook || (DataRouterHook = {}));
689
690var DataRouterStateHook;
691
692(function (DataRouterStateHook) {
693 DataRouterStateHook["UseLoaderData"] = "useLoaderData";
694 DataRouterStateHook["UseActionData"] = "useActionData";
695 DataRouterStateHook["UseRouteError"] = "useRouteError";
696 DataRouterStateHook["UseNavigation"] = "useNavigation";
697 DataRouterStateHook["UseRouteLoaderData"] = "useRouteLoaderData";
698 DataRouterStateHook["UseMatches"] = "useMatches";
699 DataRouterStateHook["UseRevalidator"] = "useRevalidator";
700})(DataRouterStateHook || (DataRouterStateHook = {}));
701
702function getDataRouterConsoleError(hookName) {
703 return `${hookName} must be used within a data router. See https://reactrouter.com/en/main/routers/picking-a-router.`;
704}
705
706function useDataRouterContext(hookName) {
707 let ctx = React.useContext(DataRouterContext);
708 !ctx ? invariant(false, getDataRouterConsoleError(hookName)) : void 0;
709 return ctx;
710}
711
712function useDataRouterState(hookName) {
713 let state = React.useContext(DataRouterStateContext);
714 !state ? invariant(false, getDataRouterConsoleError(hookName)) : void 0;
715 return state;
716}
717/**
718 * Returns the current navigation, defaulting to an "idle" navigation when
719 * no navigation is in progress
720 */
721
722
723function useNavigation() {
724 let state = useDataRouterState(DataRouterStateHook.UseNavigation);
725 return state.navigation;
726}
727/**
728 * Returns a revalidate function for manually triggering revalidation, as well
729 * as the current state of any manual revalidations
730 */
731
732function useRevalidator() {
733 let dataRouterContext = useDataRouterContext(DataRouterHook.UseRevalidator);
734 let state = useDataRouterState(DataRouterStateHook.UseRevalidator);
735 return {
736 revalidate: dataRouterContext.router.revalidate,
737 state: state.revalidation
738 };
739}
740/**
741 * Returns the active route matches, useful for accessing loaderData for
742 * parent/child routes or the route "handle" property
743 */
744
745function useMatches() {
746 let {
747 matches,
748 loaderData
749 } = useDataRouterState(DataRouterStateHook.UseMatches);
750 return React.useMemo(() => matches.map(match => {
751 let {
752 pathname,
753 params
754 } = match; // Note: This structure matches that created by createUseMatchesMatch
755 // in the @remix-run/router , so if you change this please also change
756 // that :) Eventually we'll DRY this up
757
758 return {
759 id: match.route.id,
760 pathname,
761 params,
762 data: loaderData[match.route.id],
763 handle: match.route.handle
764 };
765 }), [matches, loaderData]);
766}
767/**
768 * Returns the loader data for the nearest ancestor Route loader
769 */
770
771function useLoaderData() {
772 let state = useDataRouterState(DataRouterStateHook.UseLoaderData);
773 let route = React.useContext(RouteContext);
774 !route ? invariant(false, `useLoaderData must be used inside a RouteContext`) : void 0;
775 let thisRoute = route.matches[route.matches.length - 1];
776 !thisRoute.route.id ? invariant(false, `useLoaderData can only be used on routes that contain a unique "id"`) : void 0;
777 return state.loaderData[thisRoute.route.id];
778}
779/**
780 * Returns the loaderData for the given routeId
781 */
782
783function useRouteLoaderData(routeId) {
784 let state = useDataRouterState(DataRouterStateHook.UseRouteLoaderData);
785 return state.loaderData[routeId];
786}
787/**
788 * Returns the action data for the nearest ancestor Route action
789 */
790
791function useActionData() {
792 let state = useDataRouterState(DataRouterStateHook.UseActionData);
793 let route = React.useContext(RouteContext);
794 !route ? invariant(false, `useActionData must be used inside a RouteContext`) : void 0;
795 return Object.values(state?.actionData || {})[0];
796}
797/**
798 * Returns the nearest ancestor Route error, which could be a loader/action
799 * error or a render error. This is intended to be called from your
800 * errorElement to display a proper error message.
801 */
802
803function useRouteError() {
804 let error = React.useContext(RouteErrorContext);
805 let state = useDataRouterState(DataRouterStateHook.UseRouteError);
806 let route = React.useContext(RouteContext);
807 let thisRoute = route.matches[route.matches.length - 1]; // If this was a render error, we put it in a RouteError context inside
808 // of RenderErrorBoundary
809
810 if (error) {
811 return error;
812 }
813
814 !route ? invariant(false, `useRouteError must be used inside a RouteContext`) : void 0;
815 !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
816
817 return state.errors?.[thisRoute.route.id];
818}
819/**
820 * Returns the happy-path data from the nearest ancestor <Await /> value
821 */
822
823function useAsyncValue() {
824 let value = React.useContext(AwaitContext);
825 return value?._data;
826}
827/**
828 * Returns the error from the nearest ancestor <Await /> value
829 */
830
831function useAsyncError() {
832 let value = React.useContext(AwaitContext);
833 return value?._error;
834}
835const alreadyWarned = {};
836
837function warningOnce(key, cond, message) {
838 if (!cond && !alreadyWarned[key]) {
839 alreadyWarned[key] = true;
840 warning(false, message) ;
841 }
842}
843
844/**
845 * Given a Remix Router instance, render the appropriate UI
846 */
847
848function RouterProvider({
849 fallbackElement,
850 router
851}) {
852 // Sync router state to our component state to force re-renders
853 let state = useSyncExternalStore(router.subscribe, () => router.state, // We have to provide this so React@18 doesn't complain during hydration,
854 // but we pass our serialized hydration data into the router so state here
855 // is already synced with what the server saw
856 () => router.state);
857 let navigator = React.useMemo(() => {
858 return {
859 createHref: router.createHref,
860 go: n => router.navigate(n),
861 push: (to, state, opts) => router.navigate(to, {
862 state,
863 preventScrollReset: opts?.preventScrollReset
864 }),
865 replace: (to, state, opts) => router.navigate(to, {
866 replace: true,
867 state,
868 preventScrollReset: opts?.preventScrollReset
869 })
870 };
871 }, [router]);
872 let basename = router.basename || "/";
873 return /*#__PURE__*/React.createElement(DataRouterContext.Provider, {
874 value: {
875 router,
876 navigator,
877 static: false,
878 // Do we need this?
879 basename
880 }
881 }, /*#__PURE__*/React.createElement(DataRouterStateContext.Provider, {
882 value: state
883 }, /*#__PURE__*/React.createElement(Router, {
884 basename: router.basename,
885 location: router.state.location,
886 navigationType: router.state.historyAction,
887 navigator: navigator
888 }, router.state.initialized ? /*#__PURE__*/React.createElement(Routes, null) : fallbackElement)));
889}
890/**
891 * A <Router> that stores all entries in memory.
892 *
893 * @see https://reactrouter.com/docs/en/v6/routers/memory-router
894 */
895
896function MemoryRouter({
897 basename,
898 children,
899 initialEntries,
900 initialIndex
901}) {
902 let historyRef = React.useRef();
903
904 if (historyRef.current == null) {
905 historyRef.current = createMemoryHistory({
906 initialEntries,
907 initialIndex,
908 v5Compat: true
909 });
910 }
911
912 let history = historyRef.current;
913 let [state, setState] = React.useState({
914 action: history.action,
915 location: history.location
916 });
917 React.useLayoutEffect(() => history.listen(setState), [history]);
918 return /*#__PURE__*/React.createElement(Router, {
919 basename: basename,
920 children: children,
921 location: state.location,
922 navigationType: state.action,
923 navigator: history
924 });
925}
926/**
927 * Changes the current location.
928 *
929 * Note: This API is mostly useful in React.Component subclasses that are not
930 * able to use hooks. In functional components, we recommend you use the
931 * `useNavigate` hook instead.
932 *
933 * @see https://reactrouter.com/docs/en/v6/components/navigate
934 */
935
936function Navigate({
937 to,
938 replace,
939 state,
940 relative
941}) {
942 !useInRouterContext() ? invariant(false, // TODO: This error is probably because they somehow have 2 versions of
943 // the router loaded. We can help them understand how to avoid that.
944 `<Navigate> may be used only in the context of a <Router> component.`) : void 0;
945 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.`) ;
946 let dataRouterState = React.useContext(DataRouterStateContext);
947 let navigate = useNavigate();
948 React.useEffect(() => {
949 // Avoid kicking off multiple navigations if we're in the middle of a
950 // data-router navigation, since components get re-rendered when we enter
951 // a submitting/loading state
952 if (dataRouterState && dataRouterState.navigation.state !== "idle") {
953 return;
954 }
955
956 navigate(to, {
957 replace,
958 state,
959 relative
960 });
961 });
962 return null;
963}
964/**
965 * Renders the child route's element, if there is one.
966 *
967 * @see https://reactrouter.com/docs/en/v6/components/outlet
968 */
969
970function Outlet(props) {
971 return useOutlet(props.context);
972}
973/**
974 * Declares an element that should be rendered at a certain URL path.
975 *
976 * @see https://reactrouter.com/docs/en/v6/components/route
977 */
978
979function Route(_props) {
980 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>.`) ;
981}
982/**
983 * Provides location context for the rest of the app.
984 *
985 * Note: You usually won't render a <Router> directly. Instead, you'll render a
986 * router that is more specific to your environment such as a <BrowserRouter>
987 * in web browsers or a <StaticRouter> for server rendering.
988 *
989 * @see https://reactrouter.com/docs/en/v6/routers/router
990 */
991
992function Router({
993 basename: basenameProp = "/",
994 children = null,
995 location: locationProp,
996 navigationType = Action.Pop,
997 navigator,
998 static: staticProp = false
999}) {
1000 !!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
1001 // the enforcement of trailing slashes throughout the app
1002
1003 let basename = basenameProp.replace(/^\/*/, "/");
1004 let navigationContext = React.useMemo(() => ({
1005 basename,
1006 navigator,
1007 static: staticProp
1008 }), [basename, navigator, staticProp]);
1009
1010 if (typeof locationProp === "string") {
1011 locationProp = parsePath(locationProp);
1012 }
1013
1014 let {
1015 pathname = "/",
1016 search = "",
1017 hash = "",
1018 state = null,
1019 key = "default"
1020 } = locationProp;
1021 let location = React.useMemo(() => {
1022 let trailingPathname = stripBasename(pathname, basename);
1023
1024 if (trailingPathname == null) {
1025 return null;
1026 }
1027
1028 return {
1029 pathname: trailingPathname,
1030 search,
1031 hash,
1032 state,
1033 key
1034 };
1035 }, [basename, pathname, search, hash, state, key]);
1036 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.`) ;
1037
1038 if (location == null) {
1039 return null;
1040 }
1041
1042 return /*#__PURE__*/React.createElement(NavigationContext.Provider, {
1043 value: navigationContext
1044 }, /*#__PURE__*/React.createElement(LocationContext.Provider, {
1045 children: children,
1046 value: {
1047 location,
1048 navigationType
1049 }
1050 }));
1051}
1052/**
1053 * A container for a nested tree of <Route> elements that renders the branch
1054 * that best matches the current location.
1055 *
1056 * @see https://reactrouter.com/docs/en/v6/components/routes
1057 */
1058
1059function Routes({
1060 children,
1061 location
1062}) {
1063 let dataRouterContext = React.useContext(DataRouterContext); // When in a DataRouterContext _without_ children, we use the router routes
1064 // directly. If we have children, then we're in a descendant tree and we
1065 // need to use child routes.
1066
1067 let routes = dataRouterContext && !children ? dataRouterContext.router.routes : createRoutesFromChildren(children);
1068 return useRoutes(routes, location);
1069}
1070/**
1071 * Component to use for rendering lazily loaded data from returning defer()
1072 * in a loader function
1073 */
1074
1075function Await({
1076 children,
1077 errorElement,
1078 resolve
1079}) {
1080 return /*#__PURE__*/React.createElement(AwaitErrorBoundary, {
1081 resolve: resolve,
1082 errorElement: errorElement
1083 }, /*#__PURE__*/React.createElement(ResolveAwait, null, children));
1084}
1085var AwaitRenderStatus;
1086
1087(function (AwaitRenderStatus) {
1088 AwaitRenderStatus[AwaitRenderStatus["pending"] = 0] = "pending";
1089 AwaitRenderStatus[AwaitRenderStatus["success"] = 1] = "success";
1090 AwaitRenderStatus[AwaitRenderStatus["error"] = 2] = "error";
1091})(AwaitRenderStatus || (AwaitRenderStatus = {}));
1092
1093const neverSettledPromise = new Promise(() => {});
1094
1095class AwaitErrorBoundary extends React.Component {
1096 constructor(props) {
1097 super(props);
1098 this.state = {
1099 error: null
1100 };
1101 }
1102
1103 static getDerivedStateFromError(error) {
1104 return {
1105 error
1106 };
1107 }
1108
1109 componentDidCatch(error, errorInfo) {
1110 console.error("<Await> caught the following error during render", error, errorInfo);
1111 }
1112
1113 render() {
1114 let {
1115 children,
1116 errorElement,
1117 resolve
1118 } = this.props;
1119 let promise = null;
1120 let status = AwaitRenderStatus.pending;
1121
1122 if (!(resolve instanceof Promise)) {
1123 // Didn't get a promise - provide as a resolved promise
1124 status = AwaitRenderStatus.success;
1125 promise = Promise.resolve();
1126 Object.defineProperty(promise, "_tracked", {
1127 get: () => true
1128 });
1129 Object.defineProperty(promise, "_data", {
1130 get: () => resolve
1131 });
1132 } else if (this.state.error) {
1133 // Caught a render error, provide it as a rejected promise
1134 status = AwaitRenderStatus.error;
1135 let renderError = this.state.error;
1136 promise = Promise.reject().catch(() => {}); // Avoid unhandled rejection warnings
1137
1138 Object.defineProperty(promise, "_tracked", {
1139 get: () => true
1140 });
1141 Object.defineProperty(promise, "_error", {
1142 get: () => renderError
1143 });
1144 } else if (resolve._tracked) {
1145 // Already tracked promise - check contents
1146 promise = resolve;
1147 status = promise._error !== undefined ? AwaitRenderStatus.error : promise._data !== undefined ? AwaitRenderStatus.success : AwaitRenderStatus.pending;
1148 } else {
1149 // Raw (untracked) promise - track it
1150 status = AwaitRenderStatus.pending;
1151 Object.defineProperty(resolve, "_tracked", {
1152 get: () => true
1153 });
1154 promise = resolve.then(data => Object.defineProperty(resolve, "_data", {
1155 get: () => data
1156 }), error => Object.defineProperty(resolve, "_error", {
1157 get: () => error
1158 }));
1159 }
1160
1161 if (status === AwaitRenderStatus.error && promise._error instanceof AbortedDeferredError) {
1162 // Freeze the UI by throwing a never resolved promise
1163 throw neverSettledPromise;
1164 }
1165
1166 if (status === AwaitRenderStatus.error && !errorElement) {
1167 // No errorElement, throw to the nearest route-level error boundary
1168 throw promise._error;
1169 }
1170
1171 if (status === AwaitRenderStatus.error) {
1172 // Render via our errorElement
1173 return /*#__PURE__*/React.createElement(AwaitContext.Provider, {
1174 value: promise,
1175 children: errorElement
1176 });
1177 }
1178
1179 if (status === AwaitRenderStatus.success) {
1180 // Render children with resolved value
1181 return /*#__PURE__*/React.createElement(AwaitContext.Provider, {
1182 value: promise,
1183 children: children
1184 });
1185 } // Throw to the suspense boundary
1186
1187
1188 throw promise;
1189 }
1190
1191}
1192/**
1193 * @private
1194 * Indirection to leverage useAsyncValue for a render-prop API on <Await>
1195 */
1196
1197
1198function ResolveAwait({
1199 children
1200}) {
1201 let data = useAsyncValue();
1202
1203 if (typeof children === "function") {
1204 return children(data);
1205 }
1206
1207 return /*#__PURE__*/React.createElement(React.Fragment, null, children);
1208} ///////////////////////////////////////////////////////////////////////////////
1209// UTILS
1210///////////////////////////////////////////////////////////////////////////////
1211
1212/**
1213 * Creates a route config from a React "children" object, which is usually
1214 * either a `<Route>` element or an array of them. Used internally by
1215 * `<Routes>` to create a route config from its children.
1216 *
1217 * @see https://reactrouter.com/docs/en/v6/utils/create-routes-from-children
1218 */
1219
1220
1221function createRoutesFromChildren(children, parentPath = []) {
1222 let routes = [];
1223 React.Children.forEach(children, (element, index) => {
1224 if (! /*#__PURE__*/React.isValidElement(element)) {
1225 // Ignore non-elements. This allows people to more easily inline
1226 // conditionals in their route config.
1227 return;
1228 }
1229
1230 if (element.type === React.Fragment) {
1231 // Transparently support React.Fragment and its children.
1232 routes.push.apply(routes, createRoutesFromChildren(element.props.children, parentPath));
1233 return;
1234 }
1235
1236 !(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;
1237 !(!element.props.index || !element.props.children) ? invariant(false, "An index route cannot have child routes.") : void 0;
1238 let treePath = [...parentPath, index];
1239 let route = {
1240 id: element.props.id || treePath.join("-"),
1241 caseSensitive: element.props.caseSensitive,
1242 element: element.props.element,
1243 index: element.props.index,
1244 path: element.props.path,
1245 loader: element.props.loader,
1246 action: element.props.action,
1247 errorElement: element.props.errorElement,
1248 hasErrorBoundary: element.props.errorElement != null,
1249 shouldRevalidate: element.props.shouldRevalidate,
1250 handle: element.props.handle
1251 };
1252
1253 if (element.props.children) {
1254 route.children = createRoutesFromChildren(element.props.children, treePath);
1255 }
1256
1257 routes.push(route);
1258 });
1259 return routes;
1260}
1261/**
1262 * Renders the result of `matchRoutes()` into a React element.
1263 */
1264
1265function renderMatches(matches) {
1266 return _renderMatches(matches);
1267}
1268/**
1269 * @private
1270 * Walk the route tree and add hasErrorBoundary if it's not provided, so that
1271 * users providing manual route arrays can just specify errorElement
1272 */
1273
1274function enhanceManualRouteObjects(routes) {
1275 return routes.map(route => {
1276 let routeClone = { ...route
1277 };
1278
1279 if (routeClone.hasErrorBoundary == null) {
1280 routeClone.hasErrorBoundary = routeClone.errorElement != null;
1281 }
1282
1283 if (routeClone.children) {
1284 routeClone.children = enhanceManualRouteObjects(routeClone.children);
1285 }
1286
1287 return routeClone;
1288 });
1289}
1290
1291function createMemoryRouter(routes, opts) {
1292 return createRouter({
1293 basename: opts?.basename,
1294 history: createMemoryHistory({
1295 initialEntries: opts?.initialEntries,
1296 initialIndex: opts?.initialIndex
1297 }),
1298 hydrationData: opts?.hydrationData,
1299 routes: enhanceManualRouteObjects(routes)
1300 }).initialize();
1301} ///////////////////////////////////////////////////////////////////////////////
1302
1303export { 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 };
1304//# sourceMappingURL=react-router.development.js.map