UNPKG

47.5 kBJavaScriptView Raw
1/**
2 * React Router v6.7.0
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 DataRouterContext = /*#__PURE__*/React.createContext(null);
194
195{
196 DataRouterContext.displayName = "DataRouter";
197}
198
199const DataRouterStateContext = /*#__PURE__*/React.createContext(null);
200
201{
202 DataRouterStateContext.displayName = "DataRouterState";
203}
204
205const AwaitContext = /*#__PURE__*/React.createContext(null);
206
207{
208 AwaitContext.displayName = "Await";
209}
210
211const NavigationContext = /*#__PURE__*/React.createContext(null);
212
213{
214 NavigationContext.displayName = "Navigation";
215}
216
217const LocationContext = /*#__PURE__*/React.createContext(null);
218
219{
220 LocationContext.displayName = "Location";
221}
222
223const RouteContext = /*#__PURE__*/React.createContext({
224 outlet: null,
225 matches: []
226});
227
228{
229 RouteContext.displayName = "Route";
230}
231
232const RouteErrorContext = /*#__PURE__*/React.createContext(null);
233
234{
235 RouteErrorContext.displayName = "RouteError";
236}
237
238/**
239 * Returns the full href for the given "to" value. This is useful for building
240 * custom links that are also accessible and preserve right-click behavior.
241 *
242 * @see https://reactrouter.com/hooks/use-href
243 */
244
245function useHref(to, {
246 relative
247} = {}) {
248 !useInRouterContext() ? invariant(false, // TODO: This error is probably because they somehow have 2 versions of the
249 // router loaded. We can help them understand how to avoid that.
250 `useHref() may be used only in the context of a <Router> component.`) : void 0;
251 let {
252 basename,
253 navigator
254 } = React.useContext(NavigationContext);
255 let {
256 hash,
257 pathname,
258 search
259 } = useResolvedPath(to, {
260 relative
261 });
262 let joinedPathname = pathname; // If we're operating within a basename, prepend it to the pathname prior
263 // to creating the href. If this is a root navigation, then just use the raw
264 // basename which allows the basename to have full control over the presence
265 // of a trailing slash on root links
266
267 if (basename !== "/") {
268 joinedPathname = pathname === "/" ? basename : joinPaths([basename, pathname]);
269 }
270
271 return navigator.createHref({
272 pathname: joinedPathname,
273 search,
274 hash
275 });
276}
277/**
278 * Returns true if this component is a descendant of a <Router>.
279 *
280 * @see https://reactrouter.com/hooks/use-in-router-context
281 */
282
283function useInRouterContext() {
284 return React.useContext(LocationContext) != null;
285}
286/**
287 * Returns the current location object, which represents the current URL in web
288 * browsers.
289 *
290 * Note: If you're using this it may mean you're doing some of your own
291 * "routing" in your app, and we'd like to know what your use case is. We may
292 * be able to provide something higher-level to better suit your needs.
293 *
294 * @see https://reactrouter.com/hooks/use-location
295 */
296
297function useLocation() {
298 !useInRouterContext() ? invariant(false, // TODO: This error is probably because they somehow have 2 versions of the
299 // router loaded. We can help them understand how to avoid that.
300 `useLocation() may be used only in the context of a <Router> component.`) : void 0;
301 return React.useContext(LocationContext).location;
302}
303/**
304 * Returns the current navigation action which describes how the router came to
305 * the current location, either by a pop, push, or replace on the history stack.
306 *
307 * @see https://reactrouter.com/hooks/use-navigation-type
308 */
309
310function useNavigationType() {
311 return React.useContext(LocationContext).navigationType;
312}
313/**
314 * Returns a PathMatch object if the given pattern matches the current URL.
315 * This is useful for components that need to know "active" state, e.g.
316 * <NavLink>.
317 *
318 * @see https://reactrouter.com/hooks/use-match
319 */
320
321function useMatch(pattern) {
322 !useInRouterContext() ? invariant(false, // TODO: This error is probably because they somehow have 2 versions of the
323 // router loaded. We can help them understand how to avoid that.
324 `useMatch() may be used only in the context of a <Router> component.`) : void 0;
325 let {
326 pathname
327 } = useLocation();
328 return React.useMemo(() => matchPath(pattern, pathname), [pathname, pattern]);
329}
330/**
331 * Returns an imperative method for changing the location. Used by <Link>s, but
332 * may also be used by other elements to change the location.
333 *
334 * @see https://reactrouter.com/hooks/use-navigate
335 */
336
337function useNavigate() {
338 !useInRouterContext() ? invariant(false, // TODO: This error is probably because they somehow have 2 versions of the
339 // router loaded. We can help them understand how to avoid that.
340 `useNavigate() may be used only in the context of a <Router> component.`) : void 0;
341 let {
342 basename,
343 navigator
344 } = React.useContext(NavigationContext);
345 let {
346 matches
347 } = React.useContext(RouteContext);
348 let {
349 pathname: locationPathname
350 } = useLocation();
351 let routePathnamesJson = JSON.stringify(UNSAFE_getPathContributingMatches(matches).map(match => match.pathnameBase));
352 let activeRef = React.useRef(false);
353 React.useEffect(() => {
354 activeRef.current = true;
355 });
356 let navigate = React.useCallback((to, options = {}) => {
357 warning(activeRef.current, `You should call navigate() in a React.useEffect(), not when ` + `your component is first rendered.`) ;
358 if (!activeRef.current) return;
359
360 if (typeof to === "number") {
361 navigator.go(to);
362 return;
363 }
364
365 let path = resolveTo(to, JSON.parse(routePathnamesJson), locationPathname, options.relative === "path"); // If we're operating within a basename, prepend it to the pathname prior
366 // to handing off to history. If this is a root navigation, then we
367 // navigate to the raw basename which allows the basename to have full
368 // control over the presence of a trailing slash on root links
369
370 if (basename !== "/") {
371 path.pathname = path.pathname === "/" ? basename : joinPaths([basename, path.pathname]);
372 }
373
374 (!!options.replace ? navigator.replace : navigator.push)(path, options.state, options);
375 }, [basename, navigator, routePathnamesJson, locationPathname]);
376 return navigate;
377}
378const OutletContext = /*#__PURE__*/React.createContext(null);
379/**
380 * Returns the context (if provided) for the child route at this level of the route
381 * hierarchy.
382 * @see https://reactrouter.com/hooks/use-outlet-context
383 */
384
385function useOutletContext() {
386 return React.useContext(OutletContext);
387}
388/**
389 * Returns the element for the child route at this level of the route
390 * hierarchy. Used internally by <Outlet> to render child routes.
391 *
392 * @see https://reactrouter.com/hooks/use-outlet
393 */
394
395function useOutlet(context) {
396 let outlet = React.useContext(RouteContext).outlet;
397
398 if (outlet) {
399 return /*#__PURE__*/React.createElement(OutletContext.Provider, {
400 value: context
401 }, outlet);
402 }
403
404 return outlet;
405}
406/**
407 * Returns an object of key/value pairs of the dynamic params from the current
408 * URL that were matched by the route path.
409 *
410 * @see https://reactrouter.com/hooks/use-params
411 */
412
413function useParams() {
414 let {
415 matches
416 } = React.useContext(RouteContext);
417 let routeMatch = matches[matches.length - 1];
418 return routeMatch ? routeMatch.params : {};
419}
420/**
421 * Resolves the pathname of the given `to` value against the current location.
422 *
423 * @see https://reactrouter.com/hooks/use-resolved-path
424 */
425
426function useResolvedPath(to, {
427 relative
428} = {}) {
429 let {
430 matches
431 } = React.useContext(RouteContext);
432 let {
433 pathname: locationPathname
434 } = useLocation();
435 let routePathnamesJson = JSON.stringify(UNSAFE_getPathContributingMatches(matches).map(match => match.pathnameBase));
436 return React.useMemo(() => resolveTo(to, JSON.parse(routePathnamesJson), locationPathname, relative === "path"), [to, routePathnamesJson, locationPathname, relative]);
437}
438/**
439 * Returns the element of the route that matched the current location, prepared
440 * with the correct context to render the remainder of the route tree. Route
441 * elements in the tree must render an <Outlet> to render their child route's
442 * element.
443 *
444 * @see https://reactrouter.com/hooks/use-routes
445 */
446
447function useRoutes(routes, locationArg) {
448 !useInRouterContext() ? invariant(false, // TODO: This error is probably because they somehow have 2 versions of the
449 // router loaded. We can help them understand how to avoid that.
450 `useRoutes() may be used only in the context of a <Router> component.`) : void 0;
451 let {
452 navigator
453 } = React.useContext(NavigationContext);
454 let dataRouterStateContext = React.useContext(DataRouterStateContext);
455 let {
456 matches: parentMatches
457 } = React.useContext(RouteContext);
458 let routeMatch = parentMatches[parentMatches.length - 1];
459 let parentParams = routeMatch ? routeMatch.params : {};
460 let parentPathname = routeMatch ? routeMatch.pathname : "/";
461 let parentPathnameBase = routeMatch ? routeMatch.pathnameBase : "/";
462 let parentRoute = routeMatch && routeMatch.route;
463
464 {
465 // You won't get a warning about 2 different <Routes> under a <Route>
466 // without a trailing *, but this is a best-effort warning anyway since we
467 // cannot even give the warning unless they land at the parent route.
468 //
469 // Example:
470 //
471 // <Routes>
472 // {/* This route path MUST end with /* because otherwise
473 // it will never match /blog/post/123 */}
474 // <Route path="blog" element={<Blog />} />
475 // <Route path="blog/feed" element={<BlogFeed />} />
476 // </Routes>
477 //
478 // function Blog() {
479 // return (
480 // <Routes>
481 // <Route path="post/:id" element={<Post />} />
482 // </Routes>
483 // );
484 // }
485 let parentPath = parentRoute && parentRoute.path || "";
486 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}/*`}">.`);
487 }
488
489 let locationFromContext = useLocation();
490 let location;
491
492 if (locationArg) {
493 let parsedLocationArg = typeof locationArg === "string" ? parsePath(locationArg) : locationArg;
494 !(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;
495 location = parsedLocationArg;
496 } else {
497 location = locationFromContext;
498 }
499
500 let pathname = location.pathname || "/";
501 let remainingPathname = parentPathnameBase === "/" ? pathname : pathname.slice(parentPathnameBase.length) || "/";
502 let matches = matchRoutes(routes, {
503 pathname: remainingPathname
504 });
505
506 {
507 warning(parentRoute || matches != null, `No routes matched location "${location.pathname}${location.search}${location.hash}" `) ;
508 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.`) ;
509 }
510
511 let renderedMatches = _renderMatches(matches && matches.map(match => Object.assign({}, match, {
512 params: Object.assign({}, parentParams, match.params),
513 pathname: joinPaths([parentPathnameBase, // Re-encode pathnames that were decoded inside matchRoutes
514 navigator.encodeLocation ? navigator.encodeLocation(match.pathname).pathname : match.pathname]),
515 pathnameBase: match.pathnameBase === "/" ? parentPathnameBase : joinPaths([parentPathnameBase, // Re-encode pathnames that were decoded inside matchRoutes
516 navigator.encodeLocation ? navigator.encodeLocation(match.pathnameBase).pathname : match.pathnameBase])
517 })), parentMatches, dataRouterStateContext || undefined); // When a user passes in a `locationArg`, the associated routes need to
518 // be wrapped in a new `LocationContext.Provider` in order for `useLocation`
519 // to use the scoped location instead of the global location.
520
521
522 if (locationArg && renderedMatches) {
523 return /*#__PURE__*/React.createElement(LocationContext.Provider, {
524 value: {
525 location: {
526 pathname: "/",
527 search: "",
528 hash: "",
529 state: null,
530 key: "default",
531 ...location
532 },
533 navigationType: Action.Pop
534 }
535 }, renderedMatches);
536 }
537
538 return renderedMatches;
539}
540
541function DefaultErrorElement() {
542 let error = useRouteError();
543 let message = isRouteErrorResponse(error) ? `${error.status} ${error.statusText}` : error instanceof Error ? error.message : JSON.stringify(error);
544 let stack = error instanceof Error ? error.stack : null;
545 let lightgrey = "rgba(200,200,200, 0.5)";
546 let preStyles = {
547 padding: "0.5rem",
548 backgroundColor: lightgrey
549 };
550 let codeStyles = {
551 padding: "2px 4px",
552 backgroundColor: lightgrey
553 };
554 return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement("h2", null, "Unhandled Thrown Error!"), /*#__PURE__*/React.createElement("h3", {
555 style: {
556 fontStyle: "italic"
557 }
558 }, message), stack ? /*#__PURE__*/React.createElement("pre", {
559 style: preStyles
560 }, 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", {
561 style: codeStyles
562 }, "errorElement"), " props on\u00A0", /*#__PURE__*/React.createElement("code", {
563 style: codeStyles
564 }, "<Route>")));
565}
566
567class RenderErrorBoundary extends React.Component {
568 constructor(props) {
569 super(props);
570 this.state = {
571 location: props.location,
572 error: props.error
573 };
574 }
575
576 static getDerivedStateFromError(error) {
577 return {
578 error: error
579 };
580 }
581
582 static getDerivedStateFromProps(props, state) {
583 // When we get into an error state, the user will likely click "back" to the
584 // previous page that didn't have an error. Because this wraps the entire
585 // application, that will have no effect--the error page continues to display.
586 // This gives us a mechanism to recover from the error when the location changes.
587 //
588 // Whether we're in an error state or not, we update the location in state
589 // so that when we are in an error state, it gets reset when a new location
590 // comes in and the user recovers from the error.
591 if (state.location !== props.location) {
592 return {
593 error: props.error,
594 location: props.location
595 };
596 } // If we're not changing locations, preserve the location but still surface
597 // any new errors that may come through. We retain the existing error, we do
598 // this because the error provided from the app state may be cleared without
599 // the location changing.
600
601
602 return {
603 error: props.error || state.error,
604 location: state.location
605 };
606 }
607
608 componentDidCatch(error, errorInfo) {
609 console.error("React Router caught the following error during render", error, errorInfo);
610 }
611
612 render() {
613 return this.state.error ? /*#__PURE__*/React.createElement(RouteContext.Provider, {
614 value: this.props.routeContext
615 }, /*#__PURE__*/React.createElement(RouteErrorContext.Provider, {
616 value: this.state.error,
617 children: this.props.component
618 })) : this.props.children;
619 }
620
621}
622
623function RenderedRoute({
624 routeContext,
625 match,
626 children
627}) {
628 let dataRouterContext = React.useContext(DataRouterContext); // Track how deep we got in our render pass to emulate SSR componentDidCatch
629 // in a DataStaticRouter
630
631 if (dataRouterContext && dataRouterContext.static && dataRouterContext.staticContext && match.route.errorElement) {
632 dataRouterContext.staticContext._deepestRenderedBoundaryId = match.route.id;
633 }
634
635 return /*#__PURE__*/React.createElement(RouteContext.Provider, {
636 value: routeContext
637 }, children);
638}
639
640function _renderMatches(matches, parentMatches = [], dataRouterState) {
641 if (matches == null) {
642 if (dataRouterState?.errors) {
643 // Don't bail if we have data router errors so we can render them in the
644 // boundary. Use the pre-matched (or shimmed) matches
645 matches = dataRouterState.matches;
646 } else {
647 return null;
648 }
649 }
650
651 let renderedMatches = matches; // If we have data errors, trim matches to the highest error boundary
652
653 let errors = dataRouterState?.errors;
654
655 if (errors != null) {
656 let errorIndex = renderedMatches.findIndex(m => m.route.id && errors?.[m.route.id]);
657 !(errorIndex >= 0) ? invariant(false, `Could not find a matching route for the current errors: ${errors}`) : void 0;
658 renderedMatches = renderedMatches.slice(0, Math.min(renderedMatches.length, errorIndex + 1));
659 }
660
661 return renderedMatches.reduceRight((outlet, match, index) => {
662 let error = match.route.id ? errors?.[match.route.id] : null; // Only data routers handle errors
663
664 let errorElement = dataRouterState ? match.route.errorElement || /*#__PURE__*/React.createElement(DefaultErrorElement, null) : null;
665 let matches = parentMatches.concat(renderedMatches.slice(0, index + 1));
666
667 let getChildren = () => /*#__PURE__*/React.createElement(RenderedRoute, {
668 match: match,
669 routeContext: {
670 outlet,
671 matches
672 }
673 }, error ? errorElement : match.route.element !== undefined ? match.route.element : outlet); // Only wrap in an error boundary within data router usages when we have an
674 // errorElement on this route. Otherwise let it bubble up to an ancestor
675 // errorElement
676
677
678 return dataRouterState && (match.route.errorElement || index === 0) ? /*#__PURE__*/React.createElement(RenderErrorBoundary, {
679 location: dataRouterState.location,
680 component: errorElement,
681 error: error,
682 children: getChildren(),
683 routeContext: {
684 outlet: null,
685 matches
686 }
687 }) : getChildren();
688 }, null);
689}
690var DataRouterHook;
691
692(function (DataRouterHook) {
693 DataRouterHook["UseBlocker"] = "useBlocker";
694 DataRouterHook["UseRevalidator"] = "useRevalidator";
695})(DataRouterHook || (DataRouterHook = {}));
696
697var DataRouterStateHook;
698
699(function (DataRouterStateHook) {
700 DataRouterStateHook["UseLoaderData"] = "useLoaderData";
701 DataRouterStateHook["UseActionData"] = "useActionData";
702 DataRouterStateHook["UseRouteError"] = "useRouteError";
703 DataRouterStateHook["UseNavigation"] = "useNavigation";
704 DataRouterStateHook["UseRouteLoaderData"] = "useRouteLoaderData";
705 DataRouterStateHook["UseMatches"] = "useMatches";
706 DataRouterStateHook["UseRevalidator"] = "useRevalidator";
707})(DataRouterStateHook || (DataRouterStateHook = {}));
708
709function getDataRouterConsoleError(hookName) {
710 return `${hookName} must be used within a data router. See https://reactrouter.com/routers/picking-a-router.`;
711}
712
713function useDataRouterContext(hookName) {
714 let ctx = React.useContext(DataRouterContext);
715 !ctx ? invariant(false, getDataRouterConsoleError(hookName)) : void 0;
716 return ctx;
717}
718
719function useDataRouterState(hookName) {
720 let state = React.useContext(DataRouterStateContext);
721 !state ? invariant(false, getDataRouterConsoleError(hookName)) : void 0;
722 return state;
723}
724
725function useRouteContext(hookName) {
726 let route = React.useContext(RouteContext);
727 !route ? invariant(false, getDataRouterConsoleError(hookName)) : void 0;
728 return route;
729}
730
731function useCurrentRouteId(hookName) {
732 let route = useRouteContext(hookName);
733 let thisRoute = route.matches[route.matches.length - 1];
734 !thisRoute.route.id ? invariant(false, `${hookName} can only be used on routes that contain a unique "id"`) : void 0;
735 return thisRoute.route.id;
736}
737/**
738 * Returns the current navigation, defaulting to an "idle" navigation when
739 * no navigation is in progress
740 */
741
742
743function useNavigation() {
744 let state = useDataRouterState(DataRouterStateHook.UseNavigation);
745 return state.navigation;
746}
747/**
748 * Returns a revalidate function for manually triggering revalidation, as well
749 * as the current state of any manual revalidations
750 */
751
752function useRevalidator() {
753 let dataRouterContext = useDataRouterContext(DataRouterHook.UseRevalidator);
754 let state = useDataRouterState(DataRouterStateHook.UseRevalidator);
755 return {
756 revalidate: dataRouterContext.router.revalidate,
757 state: state.revalidation
758 };
759}
760/**
761 * Returns the active route matches, useful for accessing loaderData for
762 * parent/child routes or the route "handle" property
763 */
764
765function useMatches() {
766 let {
767 matches,
768 loaderData
769 } = useDataRouterState(DataRouterStateHook.UseMatches);
770 return React.useMemo(() => matches.map(match => {
771 let {
772 pathname,
773 params
774 } = match; // Note: This structure matches that created by createUseMatchesMatch
775 // in the @remix-run/router , so if you change this please also change
776 // that :) Eventually we'll DRY this up
777
778 return {
779 id: match.route.id,
780 pathname,
781 params,
782 data: loaderData[match.route.id],
783 handle: match.route.handle
784 };
785 }), [matches, loaderData]);
786}
787/**
788 * Returns the loader data for the nearest ancestor Route loader
789 */
790
791function useLoaderData() {
792 let state = useDataRouterState(DataRouterStateHook.UseLoaderData);
793 let routeId = useCurrentRouteId(DataRouterStateHook.UseLoaderData);
794
795 if (state.errors && state.errors[routeId] != null) {
796 console.error(`You cannot \`useLoaderData\` in an errorElement (routeId: ${routeId})`);
797 return undefined;
798 }
799
800 return state.loaderData[routeId];
801}
802/**
803 * Returns the loaderData for the given routeId
804 */
805
806function useRouteLoaderData(routeId) {
807 let state = useDataRouterState(DataRouterStateHook.UseRouteLoaderData);
808 return state.loaderData[routeId];
809}
810/**
811 * Returns the action data for the nearest ancestor Route action
812 */
813
814function useActionData() {
815 let state = useDataRouterState(DataRouterStateHook.UseActionData);
816 let route = React.useContext(RouteContext);
817 !route ? invariant(false, `useActionData must be used inside a RouteContext`) : void 0;
818 return Object.values(state?.actionData || {})[0];
819}
820/**
821 * Returns the nearest ancestor Route error, which could be a loader/action
822 * error or a render error. This is intended to be called from your
823 * errorElement to display a proper error message.
824 */
825
826function useRouteError() {
827 let error = React.useContext(RouteErrorContext);
828 let state = useDataRouterState(DataRouterStateHook.UseRouteError);
829 let routeId = useCurrentRouteId(DataRouterStateHook.UseRouteError); // If this was a render error, we put it in a RouteError context inside
830 // of RenderErrorBoundary
831
832 if (error) {
833 return error;
834 } // Otherwise look for errors from our data router state
835
836
837 return state.errors?.[routeId];
838}
839/**
840 * Returns the happy-path data from the nearest ancestor <Await /> value
841 */
842
843function useAsyncValue() {
844 let value = React.useContext(AwaitContext);
845 return value?._data;
846}
847/**
848 * Returns the error from the nearest ancestor <Await /> value
849 */
850
851function useAsyncError() {
852 let value = React.useContext(AwaitContext);
853 return value?._error;
854} // useBlocker() is a singleton for now since we don't have any compelling use
855// cases for multi-blocker yet
856
857let blockerKey = "blocker-singleton";
858/**
859 * Allow the application to block navigations within the SPA and present the
860 * user a confirmation dialog to confirm the navigation. Mostly used to avoid
861 * using half-filled form data. This does not handle hard-reloads or
862 * cross-origin navigations.
863 */
864
865function useBlocker(shouldBlock) {
866 let {
867 router
868 } = useDataRouterContext(DataRouterHook.UseBlocker);
869 let blockerFunction = React.useCallback(args => {
870 return typeof shouldBlock === "function" ? !!shouldBlock(args) : !!shouldBlock;
871 }, [shouldBlock]);
872 let blocker = router.getBlocker(blockerKey, blockerFunction); // Cleanup on unmount
873
874 React.useEffect(() => () => router.deleteBlocker(blockerKey), [router]);
875 return blocker;
876}
877const alreadyWarned = {};
878
879function warningOnce(key, cond, message) {
880 if (!cond && !alreadyWarned[key]) {
881 alreadyWarned[key] = true;
882 warning(false, message) ;
883 }
884}
885
886/**
887 * Given a Remix Router instance, render the appropriate UI
888 */
889
890function RouterProvider({
891 fallbackElement,
892 router
893}) {
894 // Sync router state to our component state to force re-renders
895 let state = useSyncExternalStore(router.subscribe, () => router.state, // We have to provide this so React@18 doesn't complain during hydration,
896 // but we pass our serialized hydration data into the router so state here
897 // is already synced with what the server saw
898 () => router.state);
899 let navigator = React.useMemo(() => {
900 return {
901 createHref: router.createHref,
902 encodeLocation: router.encodeLocation,
903 go: n => router.navigate(n),
904 push: (to, state, opts) => router.navigate(to, {
905 state,
906 preventScrollReset: opts?.preventScrollReset
907 }),
908 replace: (to, state, opts) => router.navigate(to, {
909 replace: true,
910 state,
911 preventScrollReset: opts?.preventScrollReset
912 })
913 };
914 }, [router]);
915 let basename = router.basename || "/"; // The fragment and {null} here are important! We need them to keep React 18's
916 // useId happy when we are server-rendering since we may have a <script> here
917 // containing the hydrated server-side staticContext (from StaticRouterProvider).
918 // useId relies on the component tree structure to generate deterministic id's
919 // so we need to ensure it remains the same on the client even though
920 // we don't need the <script> tag
921
922 return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(DataRouterContext.Provider, {
923 value: {
924 router,
925 navigator,
926 static: false,
927 // Do we need this?
928 basename
929 }
930 }, /*#__PURE__*/React.createElement(DataRouterStateContext.Provider, {
931 value: state
932 }, /*#__PURE__*/React.createElement(Router, {
933 basename: router.basename,
934 location: router.state.location,
935 navigationType: router.state.historyAction,
936 navigator: navigator
937 }, router.state.initialized ? /*#__PURE__*/React.createElement(Routes, null) : fallbackElement))), null);
938}
939/**
940 * A <Router> that stores all entries in memory.
941 *
942 * @see https://reactrouter.com/router-components/memory-router
943 */
944
945function MemoryRouter({
946 basename,
947 children,
948 initialEntries,
949 initialIndex
950}) {
951 let historyRef = React.useRef();
952
953 if (historyRef.current == null) {
954 historyRef.current = createMemoryHistory({
955 initialEntries,
956 initialIndex,
957 v5Compat: true
958 });
959 }
960
961 let history = historyRef.current;
962 let [state, setState] = React.useState({
963 action: history.action,
964 location: history.location
965 });
966 React.useLayoutEffect(() => history.listen(setState), [history]);
967 return /*#__PURE__*/React.createElement(Router, {
968 basename: basename,
969 children: children,
970 location: state.location,
971 navigationType: state.action,
972 navigator: history
973 });
974}
975/**
976 * Changes the current location.
977 *
978 * Note: This API is mostly useful in React.Component subclasses that are not
979 * able to use hooks. In functional components, we recommend you use the
980 * `useNavigate` hook instead.
981 *
982 * @see https://reactrouter.com/components/navigate
983 */
984
985function Navigate({
986 to,
987 replace,
988 state,
989 relative
990}) {
991 !useInRouterContext() ? invariant(false, // TODO: This error is probably because they somehow have 2 versions of
992 // the router loaded. We can help them understand how to avoid that.
993 `<Navigate> may be used only in the context of a <Router> component.`) : void 0;
994 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.`) ;
995 let dataRouterState = React.useContext(DataRouterStateContext);
996 let navigate = useNavigate();
997 React.useEffect(() => {
998 // Avoid kicking off multiple navigations if we're in the middle of a
999 // data-router navigation, since components get re-rendered when we enter
1000 // a submitting/loading state
1001 if (dataRouterState && dataRouterState.navigation.state !== "idle") {
1002 return;
1003 }
1004
1005 navigate(to, {
1006 replace,
1007 state,
1008 relative
1009 });
1010 });
1011 return null;
1012}
1013/**
1014 * Renders the child route's element, if there is one.
1015 *
1016 * @see https://reactrouter.com/components/outlet
1017 */
1018
1019function Outlet(props) {
1020 return useOutlet(props.context);
1021}
1022/**
1023 * Declares an element that should be rendered at a certain URL path.
1024 *
1025 * @see https://reactrouter.com/components/route
1026 */
1027
1028function Route(_props) {
1029 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>.`) ;
1030}
1031/**
1032 * Provides location context for the rest of the app.
1033 *
1034 * Note: You usually won't render a <Router> directly. Instead, you'll render a
1035 * router that is more specific to your environment such as a <BrowserRouter>
1036 * in web browsers or a <StaticRouter> for server rendering.
1037 *
1038 * @see https://reactrouter.com/router-components/router
1039 */
1040
1041function Router({
1042 basename: basenameProp = "/",
1043 children = null,
1044 location: locationProp,
1045 navigationType = Action.Pop,
1046 navigator,
1047 static: staticProp = false
1048}) {
1049 !!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
1050 // the enforcement of trailing slashes throughout the app
1051
1052 let basename = basenameProp.replace(/^\/*/, "/");
1053 let navigationContext = React.useMemo(() => ({
1054 basename,
1055 navigator,
1056 static: staticProp
1057 }), [basename, navigator, staticProp]);
1058
1059 if (typeof locationProp === "string") {
1060 locationProp = parsePath(locationProp);
1061 }
1062
1063 let {
1064 pathname = "/",
1065 search = "",
1066 hash = "",
1067 state = null,
1068 key = "default"
1069 } = locationProp;
1070 let location = React.useMemo(() => {
1071 let trailingPathname = stripBasename(pathname, basename);
1072
1073 if (trailingPathname == null) {
1074 return null;
1075 }
1076
1077 return {
1078 pathname: trailingPathname,
1079 search,
1080 hash,
1081 state,
1082 key
1083 };
1084 }, [basename, pathname, search, hash, state, key]);
1085 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.`) ;
1086
1087 if (location == null) {
1088 return null;
1089 }
1090
1091 return /*#__PURE__*/React.createElement(NavigationContext.Provider, {
1092 value: navigationContext
1093 }, /*#__PURE__*/React.createElement(LocationContext.Provider, {
1094 children: children,
1095 value: {
1096 location,
1097 navigationType
1098 }
1099 }));
1100}
1101/**
1102 * A container for a nested tree of <Route> elements that renders the branch
1103 * that best matches the current location.
1104 *
1105 * @see https://reactrouter.com/components/routes
1106 */
1107
1108function Routes({
1109 children,
1110 location
1111}) {
1112 let dataRouterContext = React.useContext(DataRouterContext); // When in a DataRouterContext _without_ children, we use the router routes
1113 // directly. If we have children, then we're in a descendant tree and we
1114 // need to use child routes.
1115
1116 let routes = dataRouterContext && !children ? dataRouterContext.router.routes : createRoutesFromChildren(children);
1117 return useRoutes(routes, location);
1118}
1119/**
1120 * Component to use for rendering lazily loaded data from returning defer()
1121 * in a loader function
1122 */
1123
1124function Await({
1125 children,
1126 errorElement,
1127 resolve
1128}) {
1129 return /*#__PURE__*/React.createElement(AwaitErrorBoundary, {
1130 resolve: resolve,
1131 errorElement: errorElement
1132 }, /*#__PURE__*/React.createElement(ResolveAwait, null, children));
1133}
1134var AwaitRenderStatus;
1135
1136(function (AwaitRenderStatus) {
1137 AwaitRenderStatus[AwaitRenderStatus["pending"] = 0] = "pending";
1138 AwaitRenderStatus[AwaitRenderStatus["success"] = 1] = "success";
1139 AwaitRenderStatus[AwaitRenderStatus["error"] = 2] = "error";
1140})(AwaitRenderStatus || (AwaitRenderStatus = {}));
1141
1142const neverSettledPromise = new Promise(() => {});
1143
1144class AwaitErrorBoundary extends React.Component {
1145 constructor(props) {
1146 super(props);
1147 this.state = {
1148 error: null
1149 };
1150 }
1151
1152 static getDerivedStateFromError(error) {
1153 return {
1154 error
1155 };
1156 }
1157
1158 componentDidCatch(error, errorInfo) {
1159 console.error("<Await> caught the following error during render", error, errorInfo);
1160 }
1161
1162 render() {
1163 let {
1164 children,
1165 errorElement,
1166 resolve
1167 } = this.props;
1168 let promise = null;
1169 let status = AwaitRenderStatus.pending;
1170
1171 if (!(resolve instanceof Promise)) {
1172 // Didn't get a promise - provide as a resolved promise
1173 status = AwaitRenderStatus.success;
1174 promise = Promise.resolve();
1175 Object.defineProperty(promise, "_tracked", {
1176 get: () => true
1177 });
1178 Object.defineProperty(promise, "_data", {
1179 get: () => resolve
1180 });
1181 } else if (this.state.error) {
1182 // Caught a render error, provide it as a rejected promise
1183 status = AwaitRenderStatus.error;
1184 let renderError = this.state.error;
1185 promise = Promise.reject().catch(() => {}); // Avoid unhandled rejection warnings
1186
1187 Object.defineProperty(promise, "_tracked", {
1188 get: () => true
1189 });
1190 Object.defineProperty(promise, "_error", {
1191 get: () => renderError
1192 });
1193 } else if (resolve._tracked) {
1194 // Already tracked promise - check contents
1195 promise = resolve;
1196 status = promise._error !== undefined ? AwaitRenderStatus.error : promise._data !== undefined ? AwaitRenderStatus.success : AwaitRenderStatus.pending;
1197 } else {
1198 // Raw (untracked) promise - track it
1199 status = AwaitRenderStatus.pending;
1200 Object.defineProperty(resolve, "_tracked", {
1201 get: () => true
1202 });
1203 promise = resolve.then(data => Object.defineProperty(resolve, "_data", {
1204 get: () => data
1205 }), error => Object.defineProperty(resolve, "_error", {
1206 get: () => error
1207 }));
1208 }
1209
1210 if (status === AwaitRenderStatus.error && promise._error instanceof AbortedDeferredError) {
1211 // Freeze the UI by throwing a never resolved promise
1212 throw neverSettledPromise;
1213 }
1214
1215 if (status === AwaitRenderStatus.error && !errorElement) {
1216 // No errorElement, throw to the nearest route-level error boundary
1217 throw promise._error;
1218 }
1219
1220 if (status === AwaitRenderStatus.error) {
1221 // Render via our errorElement
1222 return /*#__PURE__*/React.createElement(AwaitContext.Provider, {
1223 value: promise,
1224 children: errorElement
1225 });
1226 }
1227
1228 if (status === AwaitRenderStatus.success) {
1229 // Render children with resolved value
1230 return /*#__PURE__*/React.createElement(AwaitContext.Provider, {
1231 value: promise,
1232 children: children
1233 });
1234 } // Throw to the suspense boundary
1235
1236
1237 throw promise;
1238 }
1239
1240}
1241/**
1242 * @private
1243 * Indirection to leverage useAsyncValue for a render-prop API on <Await>
1244 */
1245
1246
1247function ResolveAwait({
1248 children
1249}) {
1250 let data = useAsyncValue();
1251 let toRender = typeof children === "function" ? children(data) : children;
1252 return /*#__PURE__*/React.createElement(React.Fragment, null, toRender);
1253} ///////////////////////////////////////////////////////////////////////////////
1254// UTILS
1255///////////////////////////////////////////////////////////////////////////////
1256
1257/**
1258 * Creates a route config from a React "children" object, which is usually
1259 * either a `<Route>` element or an array of them. Used internally by
1260 * `<Routes>` to create a route config from its children.
1261 *
1262 * @see https://reactrouter.com/utils/create-routes-from-children
1263 */
1264
1265
1266function createRoutesFromChildren(children, parentPath = []) {
1267 let routes = [];
1268 React.Children.forEach(children, (element, index) => {
1269 if (! /*#__PURE__*/React.isValidElement(element)) {
1270 // Ignore non-elements. This allows people to more easily inline
1271 // conditionals in their route config.
1272 return;
1273 }
1274
1275 if (element.type === React.Fragment) {
1276 // Transparently support React.Fragment and its children.
1277 routes.push.apply(routes, createRoutesFromChildren(element.props.children, parentPath));
1278 return;
1279 }
1280
1281 !(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;
1282 !(!element.props.index || !element.props.children) ? invariant(false, "An index route cannot have child routes.") : void 0;
1283 let treePath = [...parentPath, index];
1284 let route = {
1285 id: element.props.id || treePath.join("-"),
1286 caseSensitive: element.props.caseSensitive,
1287 element: element.props.element,
1288 index: element.props.index,
1289 path: element.props.path,
1290 loader: element.props.loader,
1291 action: element.props.action,
1292 errorElement: element.props.errorElement,
1293 hasErrorBoundary: element.props.errorElement != null,
1294 shouldRevalidate: element.props.shouldRevalidate,
1295 handle: element.props.handle
1296 };
1297
1298 if (element.props.children) {
1299 route.children = createRoutesFromChildren(element.props.children, treePath);
1300 }
1301
1302 routes.push(route);
1303 });
1304 return routes;
1305}
1306/**
1307 * Renders the result of `matchRoutes()` into a React element.
1308 */
1309
1310function renderMatches(matches) {
1311 return _renderMatches(matches);
1312}
1313/**
1314 * @private
1315 * Walk the route tree and add hasErrorBoundary if it's not provided, so that
1316 * users providing manual route arrays can just specify errorElement
1317 */
1318
1319function enhanceManualRouteObjects(routes) {
1320 return routes.map(route => {
1321 let routeClone = { ...route
1322 };
1323
1324 if (routeClone.hasErrorBoundary == null) {
1325 routeClone.hasErrorBoundary = routeClone.errorElement != null;
1326 }
1327
1328 if (routeClone.children) {
1329 routeClone.children = enhanceManualRouteObjects(routeClone.children);
1330 }
1331
1332 return routeClone;
1333 });
1334}
1335
1336function createMemoryRouter(routes, opts) {
1337 return createRouter({
1338 basename: opts?.basename,
1339 history: createMemoryHistory({
1340 initialEntries: opts?.initialEntries,
1341 initialIndex: opts?.initialIndex
1342 }),
1343 hydrationData: opts?.hydrationData,
1344 routes: enhanceManualRouteObjects(routes)
1345 }).initialize();
1346} ///////////////////////////////////////////////////////////////////////////////
1347
1348export { Await, MemoryRouter, Navigate, Outlet, Route, Router, RouterProvider, Routes, DataRouterContext as UNSAFE_DataRouterContext, DataRouterStateContext as UNSAFE_DataRouterStateContext, LocationContext as UNSAFE_LocationContext, NavigationContext as UNSAFE_NavigationContext, RouteContext as UNSAFE_RouteContext, enhanceManualRouteObjects as UNSAFE_enhanceManualRouteObjects, createMemoryRouter, createRoutesFromChildren, createRoutesFromChildren as createRoutesFromElements, renderMatches, useBlocker as unstable_useBlocker, useActionData, useAsyncError, useAsyncValue, useHref, useInRouterContext, useLoaderData, useLocation, useMatch, useMatches, useNavigate, useNavigation, useNavigationType, useOutlet, useOutletContext, useParams, useResolvedPath, useRevalidator, useRouteError, useRouteLoaderData, useRoutes };
1349//# sourceMappingURL=react-router.development.js.map