UNPKG

48.6 kB JavaScript View Raw
1/**
2 * react-router v8.3.1
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 { createPath, invariant, parsePath, warning } from "./router/history.js";
12import { convertRouteMatchToUiMatch, decodePath, getResolveToMatches, getRoutePattern, isBrowser, isRouteErrorResponse, joinPaths, matchPath, matchRoutes, parseToInfo, resolveTo, stripBasename } from "./router/utils.js";
13import { getNavigatorCurrentUrl, validateNavigationTarget } from "./router/navigation.js";
14import { IDLE_BLOCKER, hasInvalidProtocol } from "./router/router.js";
15import { AwaitContext, DataRouterContext, DataRouterStateContext, LocationContext, NavigationContext, RSCRouterContext, RouteContext, RouteErrorContext } from "./context.js";
16import { decodeRedirectErrorDigest, decodeRouteErrorResponseDigest } from "./errors.js";
17import * as React$1 from "react";
18//#region lib/hooks.tsx
19/**
20* Resolves a URL against the current {@link Location}.
21*
22* @example
23* import { useHref } from "react-router";
24*
25* function SomeComponent() {
26* let href = useHref("some/where");
27* // "/resolved/some/where"
28* }
29*
30* @public
31* @category Hooks
32* @param to The path to resolve
33* @param options Options
34* @param options.relative Defaults to `"route"` so routing is relative to the
35* route tree.
36* Set to `"path"` to make relative routing operate against path segments.
37* @returns The resolved href string
38*/
39function useHref(to, { relative } = {}) {
40 invariant(useInRouterContext(), `useHref() may be used only in the context of a <Router> component.`);
41 let { basename, navigator } = React$1.useContext(NavigationContext);
42 let { hash, pathname, search } = useResolvedPath(to, { relative });
43 let joinedPathname = pathname;
44 if (basename !== "/") joinedPathname = pathname === "/" ? basename : joinPaths([basename, pathname]);
45 return navigator.createHref({
46 pathname: joinedPathname,
47 search,
48 hash
49 });
50}
51/**
52* Returns `true` if this component is a descendant of a {@link Router}, useful
53* to ensure a component is used within a {@link Router}.
54*
55* @public
56* @category Hooks
57* @mode framework
58* @mode data
59* @returns Whether the component is within a {@link Router} context
60*/
61function useInRouterContext() {
62 return React$1.useContext(LocationContext) != null;
63}
64/**
65* Returns the current {@link Location}. This can be useful if you'd like to
66* perform some side effect whenever it changes.
67*
68* @example
69* import * as React from 'react'
70* import { useLocation } from 'react-router'
71*
72* function SomeComponent() {
73* let location = useLocation()
74*
75* React.useEffect(() => {
76* // Google Analytics
77* ga('send', 'pageview')
78* }, [location]);
79*
80* return (
81* // ...
82* );
83* }
84*
85* @public
86* @category Hooks
87* @returns The current {@link Location} object
88*/
89function useLocation() {
90 invariant(useInRouterContext(), `useLocation() may be used only in the context of a <Router> component.`);
91 return React$1.useContext(LocationContext).location;
92}
93/**
94* Returns the current {@link Navigation} action which describes how the router
95* came to the current {@link Location}, either by a pop, push, or replace on
96* the [`History`](https://developer.mozilla.org/en-US/docs/Web/API/History) stack.
97*
98* @public
99* @category Hooks
100* @returns The current {@link NavigationType} (`"POP"`, `"PUSH"`, or `"REPLACE"`)
101*/
102function useNavigationType() {
103 return React$1.useContext(LocationContext).navigationType;
104}
105/**
106* Returns a {@link PathMatch} object if the given pattern matches the current URL.
107* This is useful for components that need to know "active" state, e.g.
108* {@link NavLink | `<NavLink>`}.
109*
110* @public
111* @category Hooks
112* @param pattern The pattern to match against the current {@link Location}
113* @returns The path match object if the pattern matches, `null` otherwise
114*/
115function useMatch(pattern) {
116 invariant(useInRouterContext(), `useMatch() may be used only in the context of a <Router> component.`);
117 let { pathname } = useLocation();
118 return React$1.useMemo(() => matchPath(pattern, decodePath(pathname)), [pathname, pattern]);
119}
120const navigateEffectWarning = "You should call navigate() in a React.useEffect(), not when your component is first rendered.";
121/**
122* Returns a function that lets you navigate programmatically in the browser in
123* response to user interactions or effects.
124*
125* It's often better to use {@link redirect} in [`action`](../../start/framework/route-module#action)/[`loader`](../../start/framework/route-module#loader)
126* functions than this hook.
127*
128* The returned function signature is `navigate(to, options?)`/`navigate(delta)` where:
129*
130* * `to` can be a string path, a {@link To} object, or a number (delta)
131* * `options` contains options for modifying the navigation
132* * These options work in all modes (Framework, Data, and Declarative):
133* * `relative`: `"route"` or `"path"` to control relative routing logic
134* * `replace`: Replace the current entry in the [`History`](https://developer.mozilla.org/en-US/docs/Web/API/History) stack
135* * `state`: Optional [`history.state`](https://developer.mozilla.org/en-US/docs/Web/API/History/state) to include with the new {@link Location}
136* * These options only work in Framework and Data modes:
137* * `flushSync`: Wrap the DOM updates in [`ReactDom.flushSync`](https://react.dev/reference/react-dom/flushSync)
138* * `preventScrollReset`: Do not scroll back to the top of the page after navigation
139* * `viewTransition`: Enable [`document.startViewTransition`](https://developer.mozilla.org/en-US/docs/Web/API/Document/startViewTransition) for this navigation
140*
141* @example
142* import { useNavigate } from "react-router";
143*
144* function SomeComponent() {
145* let navigate = useNavigate();
146* return (
147* <button onClick={() => navigate(-1)}>
148* Go Back
149* </button>
150* );
151* }
152*
153* @additionalExamples
154* ### Navigate to another path
155*
156* ```tsx
157* navigate("/some/route");
158* navigate("/some/route?search=param");
159* ```
160*
161* ### Navigate with a {@link To} object
162*
163* All properties are optional.
164*
165* ```tsx
166* navigate(
167* {
168* pathname: "/some/route",
169* search: "?search=param",
170* hash: "#hash",
171* },
172* {
173* state: { some: "state" },
174* },
175* );
176* ```
177*
178* If you use `state`, that will be available on the {@link Location} object on
179* the next page. Access it with `useLocation().state` (see {@link useLocation}).
180*
181* ### Navigate back or forward in the history stack
182*
183* ```tsx
184* // back
185* // often used to close modals
186* navigate(-1);
187*
188* // forward
189* // often used in a multistep wizard workflows
190* navigate(1);
191* ```
192*
193* Be cautious with `navigate(number)`. If your application can load up to a
194* route that has a button that tries to navigate forward/back, there may not be
195* a [`History`](https://developer.mozilla.org/en-US/docs/Web/API/History)
196* entry to go back or forward to, or it can go somewhere you don't expect
197* (like a different domain).
198*
199* Only use this if you're sure they will have an entry in the [`History`](https://developer.mozilla.org/en-US/docs/Web/API/History)
200* stack to navigate to.
201*
202* ### Replace the current entry in the history stack
203*
204* This will remove the current entry in the [`History`](https://developer.mozilla.org/en-US/docs/Web/API/History)
205* stack, replacing it with a new one, similar to a server side redirect.
206*
207* ```tsx
208* navigate("/some/route", { replace: true });
209* ```
210*
211* ### Prevent Scroll Reset
212*
213* [MODES: framework, data]
214*
215* <br/>
216* <br/>
217*
218* To prevent {@link ScrollRestoration | `<ScrollRestoration>`} from resetting
219* the scroll position, use the `preventScrollReset` option.
220*
221* ```tsx
222* navigate("?some-tab=1", { preventScrollReset: true });
223* ```
224*
225* For example, if you have a tab interface connected to search params in the
226* middle of a page, and you don't want it to scroll to the top when a tab is
227* clicked.
228*
229* ### Return Type Augmentation
230*
231* Internally, `useNavigate` uses a separate implementation when you are in
232* Declarative mode versus Data/Framework mode - the primary difference being
233* that the latter is able to return a stable reference that does not change
234* identity across navigations. The implementation in Data/Framework mode also
235* returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)
236* that resolves when the navigation is completed. This means the return type of
237* `useNavigate` is `void | Promise<void>`. This is accurate, but can lead to
238* some red squigglies based on the union in the return value:
239*
240* - If you're using `typescript-eslint`, you may see errors from
241* [`@typescript-eslint/no-floating-promises`](https://typescript-eslint.io/rules/no-floating-promises)
242* - In Framework/Data mode, `React.use(navigate())` will show a false-positive
243* `Argument of type 'void | Promise<void>' is not assignable to parameter of
244* type 'Usable<void>'` error
245*
246* The easiest way to work around these issues is to augment the type based on the
247* router you're using:
248*
249* ```ts
250* // If using <BrowserRouter>
251* declare module "react-router" {
252* interface NavigateFunction {
253* (to: To, options?: NavigateOptions): void;
254* (delta: number): void;
255* }
256* }
257*
258* // If using <RouterProvider> or Framework mode
259* declare module "react-router" {
260* interface NavigateFunction {
261* (to: To, options?: NavigateOptions): Promise<void>;
262* (delta: number): Promise<void>;
263* }
264* }
265* ```
266*
267* @public
268* @category Hooks
269* @returns A navigate function for programmatic navigation
270*/
271function useNavigate() {
272 let { isDataRoute } = React$1.useContext(RouteContext);
273 return isDataRoute ? useNavigateStable() : useNavigateUnstable();
274}
275function useNavigateUnstable() {
276 invariant(useInRouterContext(), `useNavigate() may be used only in the context of a <Router> component.`);
277 let dataRouterContext = React$1.useContext(DataRouterContext);
278 let { basename, navigator } = React$1.useContext(NavigationContext);
279 let { matches } = React$1.useContext(RouteContext);
280 let { pathname: locationPathname } = useLocation();
281 let routePathnamesJson = JSON.stringify(getResolveToMatches(matches));
282 let activeRef = React$1.useRef(false);
283 React$1.useLayoutEffect(() => {
284 activeRef.current = true;
285 });
286 return React$1.useCallback((to, options = {}) => {
287 warning(activeRef.current, navigateEffectWarning);
288 if (!activeRef.current) return;
289 if (typeof to === "number") {
290 navigator.go(to);
291 return;
292 }
293 let path = resolveTo(to, JSON.parse(routePathnamesJson), locationPathname, options.relative === "path");
294 if (dataRouterContext == null && basename !== "/") path.pathname = path.pathname === "/" ? basename : joinPaths([basename, path.pathname]);
295 validateNavigationTarget(typeof to === "string" ? to : createPath(to), navigator.createHref(path), getNavigatorCurrentUrl(navigator), "reject");
296 (!!options.replace ? navigator.replace : navigator.push)(path, options.state, options);
297 }, [
298 basename,
299 navigator,
300 routePathnamesJson,
301 locationPathname,
302 dataRouterContext
303 ]);
304}
305const OutletContext = React$1.createContext(null);
306/**
307* Returns the parent route {@link Outlet | `<Outlet context>`}.
308*
309* Often parent routes manage state or other values you want shared with child
310* routes. You can create your own [context provider](https://react.dev/learn/passing-data-deeply-with-context)
311* if you like, but this is such a common situation that it's built-into
312* {@link Outlet | `<Outlet>`}.
313*
314* ```tsx
315* // Parent route
316* function Parent() {
317* const [count, setCount] = React.useState(0);
318* return <Outlet context={[count, setCount]} />;
319* }
320* ```
321*
322* ```tsx
323* // Child route
324* import { useOutletContext } from "react-router";
325*
326* function Child() {
327* const [count, setCount] = useOutletContext();
328* const increment = () => setCount((c) => c + 1);
329* return <button onClick={increment}>{count}</button>;
330* }
331* ```
332*
333* If you're using TypeScript, we recommend the parent component provide a
334* custom hook for accessing the context value. This makes it easier for
335* consumers to get nice typings, control consumers, and know who's consuming
336* the context value.
337*
338* Here's a more realistic example:
339*
340* ```tsx filename=src/routes/dashboard.tsx lines=[14,20]
341* import { useState } from "react";
342* import { Outlet, useOutletContext } from "react-router";
343*
344* import type { User } from "./types";
345*
346* type ContextType = { user: User | null };
347*
348* export default function Dashboard() {
349* const [user, setUser] = useState<User | null>(null);
350*
351* return (
352* <div>
353* <h1>Dashboard</h1>
354* <Outlet context={{ user } satisfies ContextType} />
355* </div>
356* );
357* }
358*
359* export function useUser() {
360* return useOutletContext<ContextType>();
361* }
362* ```
363*
364* ```tsx filename=src/routes/dashboard/messages.tsx lines=[1,4]
365* import { useUser } from "../dashboard";
366*
367* export default function DashboardMessages() {
368* const { user } = useUser();
369* return (
370* <div>
371* <h2>Messages</h2>
372* <p>Hello, {user.name}!</p>
373* </div>
374* );
375* }
376* ```
377*
378* @public
379* @category Hooks
380* @returns The context value passed to the parent {@link Outlet} component
381*/
382function useOutletContext() {
383 return React$1.useContext(OutletContext);
384}
385/**
386* Returns the element for the child route at this level of the route
387* hierarchy. Used internally by {@link Outlet | `<Outlet>`} to render child
388* routes.
389*
390* @public
391* @category Hooks
392* @param context The context to pass to the outlet
393* @returns The child route element or `null` if no child routes match
394*/
395function useOutlet(context) {
396 let outlet = React$1.useContext(RouteContext).outlet;
397 return React$1.useMemo(() => outlet && /* @__PURE__ */ React$1.createElement(OutletContext.Provider, { value: context }, outlet), [outlet, context]);
398}
399/**
400* Returns an object of key/value-pairs of the dynamic params from the current
401* URL that were matched by the routes. Child routes inherit all params from
402* their parent routes.
403*
404* Assuming a route pattern like `/posts/:postId` is matched by `/posts/123`
405* then `params.postId` will be `"123"`.
406*
407* @example
408* import { useParams } from "react-router";
409*
410* function SomeComponent() {
411* let params = useParams();
412* params.postId;
413* }
414*
415* @additionalExamples
416* ### Basic Usage
417*
418* ```tsx
419* import { useParams } from "react-router";
420*
421* // given a route like:
422* <Route path="/posts/:postId" element={<Post />} />;
423*
424* // or a data route like:
425* createBrowserRouter([
426* {
427* path: "/posts/:postId",
428* component: Post,
429* },
430* ]);
431*
432* // or in routes.ts
433* route("/posts/:postId", "routes/post.tsx");
434* ```
435*
436* Access the params in a component:
437*
438* ```tsx
439* import { useParams } from "react-router";
440*
441* export default function Post() {
442* let params = useParams();
443* return <h1>Post: {params.postId}</h1>;
444* }
445* ```
446*
447* ### Multiple Params
448*
449* Patterns can have multiple params:
450*
451* ```tsx
452* "/posts/:postId/comments/:commentId";
453* ```
454*
455* All will be available in the params object:
456*
457* ```tsx
458* import { useParams } from "react-router";
459*
460* export default function Post() {
461* let params = useParams();
462* return (
463* <h1>
464* Post: {params.postId}, Comment: {params.commentId}
465* </h1>
466* );
467* }
468* ```
469*
470* ### Catchall Params
471*
472* Catchall params are defined with `*`:
473*
474* ```tsx
475* "/files/*";
476* ```
477*
478* The matched value will be available in the params object as follows:
479*
480* ```tsx
481* import { useParams } from "react-router";
482*
483* export default function File() {
484* let params = useParams();
485* let catchall = params["*"];
486* // ...
487* }
488* ```
489*
490* You can destructure the catchall param:
491*
492* ```tsx
493* export default function File() {
494* let { "*": catchall } = useParams();
495* console.log(catchall);
496* }
497* ```
498*
499* @public
500* @category Hooks
501* @returns An object containing the dynamic route parameters
502*/
503function useParams() {
504 let { matches } = React$1.useContext(RouteContext);
505 return matches[matches.length - 1]?.params ?? {};
506}
507/**
508* Resolves the pathname of the given `to` value against the current
509* {@link Location}. Similar to {@link useHref}, but returns a
510* {@link Path} instead of a string.
511*
512* @example
513* import { useResolvedPath } from "react-router";
514*
515* function SomeComponent() {
516* // if the user is at /dashboard/profile
517* let path = useResolvedPath("../accounts");
518* path.pathname; // "/dashboard/accounts"
519* path.search; // ""
520* path.hash; // ""
521* }
522*
523* @public
524* @category Hooks
525* @param to The path to resolve
526* @param options Options
527* @param options.relative Defaults to `"route"` so routing is relative to the route tree.
528* Set to `"path"` to make relative routing operate against path segments.
529* @returns The resolved {@link Path} object with `pathname`, `search`, and `hash`
530*/
531function useResolvedPath(to, { relative } = {}) {
532 let { matches } = React$1.useContext(RouteContext);
533 let { pathname: locationPathname } = useLocation();
534 let routePathnamesJson = JSON.stringify(getResolveToMatches(matches));
535 return React$1.useMemo(() => resolveTo(to, JSON.parse(routePathnamesJson), locationPathname, relative === "path"), [
536 to,
537 routePathnamesJson,
538 locationPathname,
539 relative
540 ]);
541}
542/**
543* Hook version of {@link Routes | `<Routes>`} that uses objects instead of
544* components. These objects have the same properties as the component props.
545* The return value of `useRoutes` is either a valid React element you can use
546* to render the route tree, or `null` if nothing matched.
547*
548* @example
549* import { useRoutes } from "react-router";
550*
551* function App() {
552* let element = useRoutes([
553* {
554* path: "/",
555* element: <Dashboard />,
556* children: [
557* {
558* path: "messages",
559* element: <DashboardMessages />,
560* },
561* { path: "tasks", element: <DashboardTasks /> },
562* ],
563* },
564* { path: "team", element: <AboutPage /> },
565* ]);
566*
567* return element;
568* }
569*
570* @public
571* @category Hooks
572* @param routes An array of {@link RouteObject}s that define the route hierarchy
573* @param locationArg An optional {@link Location} object or pathname string to
574* use instead of the current {@link Location}
575* @returns A React element to render the matched route, or `null` if no routes matched
576*/
577function useRoutes(routes, locationArg) {
578 return useRoutesImpl(routes, locationArg);
579}
580function useRoutesImpl(routes, locationArg, dataRouterOpts) {
581 invariant(useInRouterContext(), `useRoutes() may be used only in the context of a <Router> component.`);
582 let { navigator } = React$1.useContext(NavigationContext);
583 let { matches: parentMatches } = React$1.useContext(RouteContext);
584 let routeMatch = parentMatches[parentMatches.length - 1];
585 let parentParams = routeMatch ? routeMatch.params : {};
586 routeMatch && routeMatch.pathname;
587 let parentPathnameBase = routeMatch ? routeMatch.pathnameBase : "/";
588 routeMatch && routeMatch.route;
589 let locationFromContext = useLocation();
590 let location;
591 if (locationArg) {
592 let parsedLocationArg = typeof locationArg === "string" ? parsePath(locationArg) : locationArg;
593 invariant(parentPathnameBase === "/" || parsedLocationArg.pathname?.startsWith(parentPathnameBase), `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.`);
594 location = parsedLocationArg;
595 } else location = locationFromContext;
596 let pathname = location.pathname || "/";
597 let remainingPathname = pathname;
598 if (parentPathnameBase !== "/") {
599 let parentSegments = parentPathnameBase.replace(/^\//, "").split("/");
600 remainingPathname = "/" + pathname.replace(/^\//, "").split("/").slice(parentSegments.length).join("/");
601 }
602 let matches = dataRouterOpts && dataRouterOpts.state.matches.length ? dataRouterOpts.state.matches.map((m) => Object.assign(m, { route: dataRouterOpts.manifest[m.route.id] || m.route })) : matchRoutes(routes, { pathname: remainingPathname });
603 let renderedMatches = _renderMatches(matches && matches.map((match) => Object.assign({}, match, {
604 params: Object.assign({}, parentParams, match.params),
605 pathname: joinPaths([parentPathnameBase, navigator.encodeLocation ? navigator.encodeLocation(match.pathname.replace(/%/g, "%25").replace(/\?/g, "%3F").replace(/#/g, "%23")).pathname : match.pathname]),
606 pathnameBase: match.pathnameBase === "/" ? parentPathnameBase : joinPaths([parentPathnameBase, navigator.encodeLocation ? navigator.encodeLocation(match.pathnameBase.replace(/%/g, "%25").replace(/\?/g, "%3F").replace(/#/g, "%23")).pathname : match.pathnameBase])
607 })), parentMatches, dataRouterOpts);
608 if (locationArg && renderedMatches) return /* @__PURE__ */ React$1.createElement(LocationContext.Provider, { value: {
609 location: {
610 pathname: "/",
611 search: "",
612 hash: "",
613 state: null,
614 key: "default",
615 mask: void 0,
616 ...location
617 },
618 navigationType: "POP"
619 } }, renderedMatches);
620 return renderedMatches;
621}
622function DefaultErrorComponent() {
623 let error = useRouteError();
624 let message = isRouteErrorResponse(error) ? `${error.status} ${error.statusText}` : error instanceof Error ? error.message : JSON.stringify(error);
625 let stack = error instanceof Error ? error.stack : null;
626 return /* @__PURE__ */ React$1.createElement(React$1.Fragment, null, /* @__PURE__ */ React$1.createElement("h2", null, "Unexpected Application Error!"), /* @__PURE__ */ React$1.createElement("h3", { style: { fontStyle: "italic" } }, message), stack ? /* @__PURE__ */ React$1.createElement("pre", { style: {
627 padding: "0.5rem",
628 backgroundColor: "rgba(200,200,200, 0.5)"
629 } }, stack) : null, null);
630}
631const defaultErrorElement = /* @__PURE__ */ React$1.createElement(DefaultErrorComponent, null);
632var RenderErrorBoundary = class extends React$1.Component {
633 constructor(props) {
634 super(props);
635 this.state = {
636 location: props.location,
637 revalidation: props.revalidation,
638 error: props.error
639 };
640 }
641 static contextType = RSCRouterContext;
642 static getDerivedStateFromError(error) {
643 return { error };
644 }
645 static getDerivedStateFromProps(props, state) {
646 if (state.location !== props.location || state.revalidation !== "idle" && props.revalidation === "idle") return {
647 error: props.error,
648 location: props.location,
649 revalidation: props.revalidation
650 };
651 return {
652 error: props.error !== void 0 ? props.error : state.error,
653 location: state.location,
654 revalidation: props.revalidation || state.revalidation
655 };
656 }
657 componentDidCatch(error, errorInfo) {
658 if (this.props.onError) this.props.onError(error, errorInfo);
659 else console.error("React Router caught the following error during render", error);
660 }
661 render() {
662 let error = this.state.error;
663 if (this.context && typeof error === "object" && error && "digest" in error && typeof error.digest === "string") {
664 const decoded = decodeRouteErrorResponseDigest(error.digest);
665 if (decoded) error = decoded;
666 }
667 let result = error !== void 0 ? /* @__PURE__ */ React$1.createElement(RouteContext.Provider, { value: this.props.routeContext }, /* @__PURE__ */ React$1.createElement(RouteErrorContext.Provider, {
668 value: error,
669 children: this.props.component
670 })) : this.props.children;
671 if (this.context) return /* @__PURE__ */ React$1.createElement(RSCErrorHandler, { error }, result);
672 return result;
673 }
674};
675const errorRedirectHandledMap = /* @__PURE__ */ new WeakMap();
676function RSCErrorHandler({ children, error }) {
677 let { basename, navigator } = React$1.useContext(NavigationContext);
678 if (typeof error === "object" && error && "digest" in error && typeof error.digest === "string") {
679 let redirect = decodeRedirectErrorDigest(error.digest);
680 if (redirect) {
681 let existingRedirect = errorRedirectHandledMap.get(error);
682 if (existingRedirect) throw existingRedirect;
683 let parsed = parseToInfo(redirect.location, basename);
684 let target = parsed.absoluteURL || parsed.to;
685 validateNavigationTarget(redirect.location, target, getNavigatorCurrentUrl(navigator), "allow-explicit");
686 if (hasInvalidProtocol(target)) throw new Error("Invalid redirect location");
687 if (isBrowser && !errorRedirectHandledMap.get(error)) if (parsed.isExternal || redirect.reloadDocument) window.location.href = target;
688 else {
689 const redirectPromise = Promise.resolve().then(() => window.__reactRouterDataRouter.navigate(parsed.to, { replace: redirect.replace }));
690 errorRedirectHandledMap.set(error, redirectPromise);
691 throw redirectPromise;
692 }
693 return /* @__PURE__ */ React$1.createElement("meta", {
694 httpEquiv: "refresh",
695 content: `0;url=${target}`
696 });
697 }
698 }
699 return children;
700}
701function RenderedRoute({ routeContext, match, children }) {
702 let dataRouterContext = React$1.useContext(DataRouterContext);
703 if (dataRouterContext && dataRouterContext.static && dataRouterContext.staticContext && (match.route.errorElement || match.route.ErrorBoundary)) dataRouterContext.staticContext._deepestRenderedBoundaryId = match.route.id;
704 return /* @__PURE__ */ React$1.createElement(RouteContext.Provider, { value: routeContext }, children);
705}
706function _renderMatches(matches, parentMatches = [], dataRouterOpts) {
707 let dataRouterState = dataRouterOpts?.state;
708 if (matches == null) {
709 if (!dataRouterState) return null;
710 if (dataRouterState.errors) matches = dataRouterState.matches;
711 else if (parentMatches.length === 0 && !dataRouterState.initialized && dataRouterState.matches.length > 0) matches = dataRouterState.matches;
712 else return null;
713 }
714 let renderedMatches = matches;
715 let errors = dataRouterState?.errors;
716 if (errors != null) {
717 let errorIndex = renderedMatches.findIndex((m) => m.route.id && errors?.[m.route.id] !== void 0);
718 invariant(errorIndex >= 0, `Could not find a matching route for errors on route IDs: ${Object.keys(errors).join(",")}`);
719 renderedMatches = renderedMatches.slice(0, Math.min(renderedMatches.length, errorIndex + 1));
720 }
721 let renderFallback = false;
722 let fallbackIndex = -1;
723 if (dataRouterOpts && dataRouterState) {
724 renderFallback = dataRouterState.renderFallback;
725 for (let i = 0; i < renderedMatches.length; i++) {
726 let match = renderedMatches[i];
727 if (match.route.HydrateFallback || match.route.hydrateFallbackElement) fallbackIndex = i;
728 if (match.route.id) {
729 let { loaderData, errors } = dataRouterState;
730 let needsToRunLoader = match.route.loader && !loaderData.hasOwnProperty(match.route.id) && (!errors || errors[match.route.id] === void 0);
731 if (match.route.lazy || needsToRunLoader) {
732 if (dataRouterOpts.isStatic) renderFallback = true;
733 if (fallbackIndex >= 0) renderedMatches = renderedMatches.slice(0, fallbackIndex + 1);
734 else renderedMatches = [renderedMatches[0]];
735 break;
736 }
737 }
738 }
739 }
740 let onErrorHandler = dataRouterOpts?.onError;
741 let onError = dataRouterState && onErrorHandler ? (error, errorInfo) => {
742 onErrorHandler(error, {
743 location: dataRouterState.location,
744 params: dataRouterState.matches?.[0]?.params ?? {},
745 pattern: getRoutePattern(dataRouterState.matches),
746 errorInfo
747 });
748 } : void 0;
749 return renderedMatches.reduceRight((outlet, match, index) => {
750 let error;
751 let shouldRenderHydrateFallback = false;
752 let errorElement = null;
753 let hydrateFallbackElement = null;
754 if (dataRouterState) {
755 error = errors && match.route.id ? errors[match.route.id] : void 0;
756 errorElement = match.route.errorElement || defaultErrorElement;
757 if (renderFallback) {
758 if (fallbackIndex < 0 && index === 0) {
759 warningOnce("route-fallback", false, "No `HydrateFallback` element provided to render during initial hydration");
760 shouldRenderHydrateFallback = true;
761 hydrateFallbackElement = null;
762 } else if (fallbackIndex === index) {
763 shouldRenderHydrateFallback = true;
764 hydrateFallbackElement = match.route.hydrateFallbackElement || null;
765 }
766 }
767 }
768 let matches = parentMatches.concat(renderedMatches.slice(0, index + 1));
769 let getChildren = () => {
770 let children;
771 if (error) children = errorElement;
772 else if (shouldRenderHydrateFallback) children = hydrateFallbackElement;
773 else if (match.route.Component) children = /* @__PURE__ */ React$1.createElement(match.route.Component, null);
774 else if (match.route.element) children = match.route.element;
775 else children = outlet;
776 return /* @__PURE__ */ React$1.createElement(RenderedRoute, {
777 match,
778 routeContext: {
779 outlet,
780 matches,
781 isDataRoute: dataRouterState != null
782 },
783 children
784 });
785 };
786 return dataRouterState && (match.route.ErrorBoundary || match.route.errorElement || index === 0) ? /* @__PURE__ */ React$1.createElement(RenderErrorBoundary, {
787 location: dataRouterState.location,
788 revalidation: dataRouterState.revalidation,
789 component: errorElement,
790 error,
791 children: getChildren(),
792 routeContext: {
793 outlet: null,
794 matches,
795 isDataRoute: true
796 },
797 onError
798 }) : getChildren();
799 }, null);
800}
801function getDataRouterConsoleError(hookName) {
802 return `${hookName} must be used within a data router. See https://reactrouter.com/en/main/routers/picking-a-router.`;
803}
804function useDataRouterContext(hookName) {
805 let ctx = React$1.useContext(DataRouterContext);
806 invariant(ctx, getDataRouterConsoleError(hookName));
807 return ctx;
808}
809function useDataRouterState(hookName) {
810 let state = React$1.useContext(DataRouterStateContext);
811 invariant(state, getDataRouterConsoleError(hookName));
812 return state;
813}
814function useRouteContext(hookName) {
815 let route = React$1.useContext(RouteContext);
816 invariant(route, getDataRouterConsoleError(hookName));
817 return route;
818}
819function useCurrentRouteId(hookName) {
820 let route = useRouteContext(hookName);
821 let thisRoute = route.matches[route.matches.length - 1];
822 invariant(thisRoute.route.id, `${hookName} can only be used on routes that contain a unique "id"`);
823 return thisRoute.route.id;
824}
825/**
826* Returns the ID for the nearest contextual route
827*
828* @category Hooks
829* @returns The ID of the nearest contextual route
830*/
831function useRouteId() {
832 return useCurrentRouteId("useRouteId");
833}
834/**
835* Returns the current {@link Navigation}, defaulting to an "idle" navigation
836* when no navigation is in progress. You can use this to render pending UI
837* (like a global spinner) or read [`FormData`](https://developer.mozilla.org/en-US/docs/Web/API/FormData)
838* from a form navigation.
839*
840* @example
841* import { useNavigation } from "react-router";
842*
843* function SomeComponent() {
844* let navigation = useNavigation();
845* navigation.state;
846* navigation.formData;
847* // etc.
848* }
849*
850* @public
851* @category Hooks
852* @mode framework
853* @mode data
854* @returns The current {@link Navigation} object
855*/
856function useNavigation() {
857 let state = useDataRouterState("useNavigation");
858 return React$1.useMemo(() => {
859 let { matches, historyAction, ...rest } = state.navigation;
860 return rest;
861 }, [state.navigation]);
862}
863/**
864* Revalidate the data on the page for reasons outside of normal data mutations
865* like [`Window` focus](https://developer.mozilla.org/en-US/docs/Web/API/Window/focus_event)
866* or polling on an interval.
867*
868* Note that page data is already revalidated automatically after actions.
869* If you find yourself using this for normal CRUD operations on your data in
870* response to user interactions, you're probably not taking advantage of the
871* other APIs like {@link useFetcher}, {@link Form}, {@link useSubmit} that do
872* this automatically.
873*
874* @example
875* import { useRevalidator } from "react-router";
876*
877* function WindowFocusRevalidator() {
878* const revalidator = useRevalidator();
879*
880* useFakeWindowFocus(() => {
881* revalidator.revalidate();
882* });
883*
884* return (
885* <div hidden={revalidator.state === "idle"}>
886* Revalidating...
887* </div>
888* );
889* }
890*
891* @public
892* @category Hooks
893* @mode framework
894* @mode data
895* @returns An object with a `revalidate` function and the current revalidation
896* `state`
897*/
898function useRevalidator() {
899 let dataRouterContext = useDataRouterContext("useRevalidator");
900 let state = useDataRouterState("useRevalidator");
901 let revalidate = React$1.useCallback(async () => {
902 await dataRouterContext.router.revalidate();
903 }, [dataRouterContext.router]);
904 return React$1.useMemo(() => ({
905 revalidate,
906 state: state.revalidation
907 }), [revalidate, state.revalidation]);
908}
909/**
910* Returns the active route matches, useful for accessing `loaderData` for
911* parent/child routes or the route [`handle`](../../start/framework/route-module#handle)
912* property
913*
914* Pairing the route `handle` with `useMatches` gets very powerful since you can put
915* whatever you want on a route handle and have access to `useMatches` anywhere.
916* Please see the [handle](../../how-to/using-handle) documentation for an example
917* of breadcrumbs via `useMatches`/`handle`.
918*
919* ```tsx
920* import { useMatches } from "react-router";
921*
922* function SomeComponent() {
923* const matches = useMatches();
924* // matches[i].id // route id
925* // matches[i].pathname // the portion of the URL the route matched
926* // matches[i].params // the parsed params from the URL
927* // matches[i].loaderData // the data from the loader
928* // matches[i].handle // the route handle with any app specific data
929* }
930* ```
931*
932* <docs-info>useMatches only works with a data router like `createBrowserRouter`,
933* since they know the full route tree up front and can provide all of the current
934* matches. Additionally, `useMatches` will not match down into any descendant route
935* trees since the router isn't aware of the descendant routes.</docs-info>
936*
937* @public
938* @category Hooks
939* @mode framework
940* @mode data
941* @returns An array of {@link UIMatch | UI matches} for the current route hierarchy
942*/
943function useMatches() {
944 let { matches, loaderData } = useDataRouterState("useMatches");
945 return React$1.useMemo(() => matches.map((m) => convertRouteMatchToUiMatch(m, loaderData)), [matches, loaderData]);
946}
947/**
948* Returns the data from the closest route
949* [`loader`](../../start/framework/route-module#loader) or
950* [`clientLoader`](../../start/framework/route-module#clientloader).
951*
952* @example
953* import { useLoaderData } from "react-router";
954*
955* export async function loader() {
956* return await fakeDb.invoices.findAll();
957* }
958*
959* export default function Invoices() {
960* let invoices = useLoaderData<typeof loader>();
961* // ...
962* }
963*
964* @public
965* @category Hooks
966* @mode framework
967* @mode data
968* @returns The data returned from the route's [`loader`](../../start/framework/route-module#loader) or [`clientLoader`](../../start/framework/route-module#clientloader) function
969*/
970function useLoaderData() {
971 let state = useDataRouterState("useLoaderData");
972 let routeId = useCurrentRouteId("useLoaderData");
973 return state.loaderData[routeId];
974}
975/**
976* Returns the [`loader`](../../start/framework/route-module#loader) data for a
977* given route by route ID.
978*
979* Route IDs are created automatically. They are simply the path of the route file
980* relative to the app folder without the extension.
981*
982* | Route Filename | Route ID |
983* | ---------------------------- | ---------------------- |
984* | `app/root.tsx` | `"root"` |
985* | `app/routes/teams.tsx` | `"routes/teams"` |
986* | `app/whatever/teams.$id.tsx` | `"whatever/teams.$id"` |
987*
988* @example
989* import { useRouteLoaderData } from "react-router";
990*
991* function SomeComponent() {
992* const { user } = useRouteLoaderData("root");
993* }
994*
995* // You can also specify your own route ID's manually in your routes.ts file:
996* route("/", "containers/app.tsx", { id: "app" })
997* useRouteLoaderData("app");
998*
999* @public
1000* @category Hooks
1001* @mode framework
1002* @mode data
1003* @param routeId The ID of the route to return loader data from
1004* @returns The data returned from the specified route's [`loader`](../../start/framework/route-module#loader)
1005* function, or `undefined` if not found
1006*/
1007function useRouteLoaderData(routeId) {
1008 return useDataRouterState("useRouteLoaderData").loaderData[routeId];
1009}
1010/**
1011* Returns the [`action`](../../start/framework/route-module#action) data from
1012* the most recent `POST` navigation form submission or `undefined` if there
1013* hasn't been one.
1014*
1015* @example
1016* import { Form, useActionData } from "react-router";
1017*
1018* export async function action({ request }) {
1019* const body = await request.formData();
1020* const name = body.get("visitorsName");
1021* return { message: `Hello, ${name}` };
1022* }
1023*
1024* export default function Invoices() {
1025* const data = useActionData();
1026* return (
1027* <Form method="post">
1028* <input type="text" name="visitorsName" />
1029* {data ? data.message : "Waiting..."}
1030* </Form>
1031* );
1032* }
1033*
1034* @public
1035* @category Hooks
1036* @mode framework
1037* @mode data
1038* @returns The data returned from the route's [`action`](../../start/framework/route-module#action)
1039* function, or `undefined` if no [`action`](../../start/framework/route-module#action)
1040* has been called
1041*/
1042function useActionData() {
1043 let state = useDataRouterState("useActionData");
1044 let routeId = useCurrentRouteId("useLoaderData");
1045 return state.actionData ? state.actionData[routeId] : void 0;
1046}
1047/**
1048* Accesses the error thrown during an
1049* [`action`](../../start/framework/route-module#action),
1050* [`loader`](../../start/framework/route-module#loader),
1051* or component render to be used in a route module
1052* [`ErrorBoundary`](../../start/framework/route-module#errorboundary).
1053*
1054* @example
1055* export function ErrorBoundary() {
1056* const error = useRouteError();
1057* return <div>{error.message}</div>;
1058* }
1059*
1060* @public
1061* @category Hooks
1062* @mode framework
1063* @mode data
1064* @returns The error that was thrown during route [loading](../../start/framework/route-module#loader),
1065* [`action`](../../start/framework/route-module#action) execution, or rendering
1066*/
1067function useRouteError() {
1068 let error = React$1.useContext(RouteErrorContext);
1069 let state = useDataRouterState("useRouteError");
1070 let routeId = useCurrentRouteId("useRouteError");
1071 if (error !== void 0) return error;
1072 return state.errors?.[routeId];
1073}
1074/**
1075* Returns the resolved promise value from the closest {@link Await | `<Await>`}.
1076*
1077* @example
1078* function SomeDescendant() {
1079* const value = useAsyncValue();
1080* // ...
1081* }
1082*
1083* // somewhere in your app
1084* <Await resolve={somePromise}>
1085* <SomeDescendant />
1086* </Await>;
1087*
1088* @public
1089* @category Hooks
1090* @mode framework
1091* @mode data
1092* @returns The resolved value from the nearest {@link Await} component
1093*/
1094function useAsyncValue() {
1095 return React$1.useContext(AwaitContext)?._data;
1096}
1097/**
1098* Returns the rejection value from the closest {@link Await | `<Await>`}.
1099*
1100* @example
1101* import { Await, useAsyncError } from "react-router";
1102*
1103* function ErrorElement() {
1104* const error = useAsyncError();
1105* return (
1106* <p>Uh Oh, something went wrong! {error.message}</p>
1107* );
1108* }
1109*
1110* // somewhere in your app
1111* <Await
1112* resolve={promiseThatRejects}
1113* errorElement={<ErrorElement />}
1114* />;
1115*
1116* @public
1117* @category Hooks
1118* @mode framework
1119* @mode data
1120* @returns The error that was thrown in the nearest {@link Await} component
1121*/
1122function useAsyncError() {
1123 return React$1.useContext(AwaitContext)?._error;
1124}
1125let blockerId = 0;
1126/**
1127* Allow the application to block navigations within the SPA and present the
1128* user a confirmation dialog to confirm the navigation. Mostly used to avoid
1129* using half-filled form data. This does not handle hard-reloads or
1130* cross-origin navigations.
1131*
1132* The {@link Blocker} object returned by the hook has the following properties:
1133*
1134* - **`state`**
1135* - `unblocked` - the blocker is idle and has not prevented any navigation
1136* - `blocked` - the blocker has prevented a navigation
1137* - `proceeding` - the blocker is proceeding through from a blocked navigation
1138* - **`location`**
1139* - When in a `blocked` state, this represents the {@link Location} to which
1140* we blocked a navigation. When in a `proceeding` state, this is the
1141* location being navigated to after a `blocker.proceed()` call.
1142* - **`proceed()`**
1143* - When in a `blocked` state, you may call `blocker.proceed()` to proceed to
1144* the blocked location.
1145* - **`reset()`**
1146* - When in a `blocked` state, you may call `blocker.reset()` to return the
1147* blocker to an `unblocked` state and leave the user at the current
1148* location.
1149*
1150* @example
1151* // Boolean version
1152* let blocker = useBlocker(value !== "");
1153*
1154* // Function version
1155* let blocker = useBlocker(
1156* ({ currentLocation, nextLocation, historyAction }) =>
1157* value !== "" &&
1158* currentLocation.pathname !== nextLocation.pathname
1159* );
1160*
1161* @additionalExamples
1162* ```tsx
1163* import { useCallback, useState } from "react";
1164* import { BlockerFunction, useBlocker } from "react-router";
1165*
1166* export function ImportantForm() {
1167* const [value, setValue] = useState("");
1168*
1169* const shouldBlock = useCallback<BlockerFunction>(
1170* () => value !== "",
1171* [value]
1172* );
1173* const blocker = useBlocker(shouldBlock);
1174*
1175* return (
1176* <form
1177* onSubmit={(e) => {
1178* e.preventDefault();
1179* setValue("");
1180* if (blocker.state === "blocked") {
1181* blocker.proceed();
1182* }
1183* }}
1184* >
1185* <input
1186* name="data"
1187* value={value}
1188* onChange={(e) => setValue(e.target.value)}
1189* />
1190*
1191* <button type="submit">Save</button>
1192*
1193* {blocker.state === "blocked" ? (
1194* <>
1195* <p style={{ color: "red" }}>
1196* Blocked the last navigation to
1197* </p>
1198* <button
1199* type="button"
1200* onClick={() => blocker.proceed()}
1201* >
1202* Let me through
1203* </button>
1204* <button
1205* type="button"
1206* onClick={() => blocker.reset()}
1207* >
1208* Keep me here
1209* </button>
1210* </>
1211* ) : blocker.state === "proceeding" ? (
1212* <p style={{ color: "orange" }}>
1213* Proceeding through blocked navigation
1214* </p>
1215* ) : (
1216* <p style={{ color: "green" }}>
1217* Blocker is currently unblocked
1218* </p>
1219* )}
1220* </form>
1221* );
1222* }
1223* ```
1224*
1225* @public
1226* @category Hooks
1227* @mode framework
1228* @mode data
1229* @param shouldBlock Either a boolean or a function returning a boolean which
1230* indicates whether the navigation should be blocked. The function format
1231* receives a single object parameter containing the `currentLocation`,
1232* `nextLocation`, and `historyAction` of the potential navigation.
1233* @returns A {@link Blocker} object with state and reset functionality
1234*/
1235function useBlocker(shouldBlock) {
1236 let { router, basename } = useDataRouterContext("useBlocker");
1237 let state = useDataRouterState("useBlocker");
1238 let [blockerKey, setBlockerKey] = React$1.useState("");
1239 let blockerFunction = React$1.useCallback((arg) => {
1240 if (typeof shouldBlock !== "function") return !!shouldBlock;
1241 if (basename === "/") return shouldBlock(arg);
1242 let { currentLocation, nextLocation, historyAction } = arg;
1243 return shouldBlock({
1244 currentLocation: {
1245 ...currentLocation,
1246 pathname: stripBasename(currentLocation.pathname, basename) || currentLocation.pathname
1247 },
1248 nextLocation: {
1249 ...nextLocation,
1250 pathname: stripBasename(nextLocation.pathname, basename) || nextLocation.pathname
1251 },
1252 historyAction
1253 });
1254 }, [basename, shouldBlock]);
1255 React$1.useEffect(() => {
1256 let key = String(++blockerId);
1257 setBlockerKey(key);
1258 return () => router.deleteBlocker(key);
1259 }, [router]);
1260 React$1.useEffect(() => {
1261 if (blockerKey !== "") router.getBlocker(blockerKey, blockerFunction);
1262 }, [
1263 router,
1264 blockerKey,
1265 blockerFunction
1266 ]);
1267 return blockerKey && state.blockers.has(blockerKey) ? state.blockers.get(blockerKey) : IDLE_BLOCKER;
1268}
1269function useNavigateStable() {
1270 let { router } = useDataRouterContext("useNavigate");
1271 let id = useCurrentRouteId("useNavigate");
1272 let activeRef = React$1.useRef(false);
1273 React$1.useLayoutEffect(() => {
1274 activeRef.current = true;
1275 });
1276 return React$1.useCallback(async (to, options = {}) => {
1277 warning(activeRef.current, navigateEffectWarning);
1278 if (!activeRef.current) return;
1279 if (typeof to === "number") await router.navigate(to);
1280 else await router.navigate(to, {
1281 fromRouteId: id,
1282 ...options
1283 });
1284 }, [router, id]);
1285}
1286const alreadyWarned = {};
1287function warningOnce(key, cond, message) {
1288 if (!cond && !alreadyWarned[key]) {
1289 alreadyWarned[key] = true;
1290 warning(false, message);
1291 }
1292}
1293function useRoute(...args) {
1294 const currentRouteId = useCurrentRouteId("useRoute");
1295 const id = args[0] ?? currentRouteId;
1296 const state = useDataRouterState("useRoute");
1297 const route = state.matches.find(({ route }) => route.id === id);
1298 if (route === void 0) return void 0;
1299 return {
1300 handle: route.route.handle,
1301 loaderData: state.loaderData[id],
1302 actionData: state.actionData?.[id]
1303 };
1304}
1305function toRouterStateMatch(match) {
1306 return {
1307 id: match.route.id,
1308 pathname: match.pathname,
1309 params: match.params,
1310 handle: match.route.handle
1311 };
1312}
1313/**
1314* A unified hook for reading router state: current (`active`) and in-flight
1315* (`pending`) locations, search params, params, matches, and navigation type.
1316*
1317* This hook consolidates the information you used to get from {@link useLocation},
1318* {@link useSearchParams}, {@link useParams}, {@link useMatches}, {@link useNavigation},
1319* and {@link useNavigationType} into a single hook.
1320*
1321*
1322* @example
1323* import { unstable_useRouterState as useRouterState } from "react-router";
1324*
1325* let { active, pending } = unstable_useRouterState();
1326*
1327* // Active is always populated with the current location
1328* active.location; // replaces `useLocation()`
1329* active.searchParams; // replaces `useSearchParams()[0]`
1330* active.params; // replaces `useParams()`
1331* active.matches; // replaces `useMatches()`
1332* active.type; // replaces `useNavigationType()`
1333*
1334* // Pending is only populated during a navigation
1335* pending.location; // replaces `useNavigation().location`
1336* pending.searchParams; // equivalent to `new URLSearchParams(useNavigation().search)`
1337* pending.params; // Not directly accessible today
1338* pending.matches; // Not directly accessible today
1339* pending.type; // Not directly accessible today
1340* pending.state; // replaces `useNavigation().state`
1341* pending.formMethod; // replaces useNavigation().formMethod
1342* pending.formAction; // replaces useNavigation().formAction
1343* pending.formEncType; // replaces useNavigation().formEncType
1344* pending.formData; // replaces useNavigation().formData
1345* pending.json; // replaces useNavigation().json
1346* pending.text; // replaces useNavigation().text
1347*
1348* @name unstable_useRouterState
1349* @public
1350* @category Hooks
1351* @mode framework
1352* @mode data
1353* @returns The current router state with `active` and `pending` variants
1354*/
1355function useRouterState() {
1356 let { location, historyAction: type, matches, navigation } = useDataRouterState("unstable_useRouterState");
1357 let active = React$1.useMemo(() => ({
1358 type,
1359 location,
1360 searchParams: new URLSearchParams(location.search),
1361 params: matches[matches.length - 1]?.params ?? {},
1362 matches: matches.map((m) => toRouterStateMatch(m))
1363 }), [
1364 location,
1365 matches,
1366 type
1367 ]);
1368 let pending = React$1.useMemo(() => {
1369 if (navigation.state === "idle") return null;
1370 let shared = {
1371 type: navigation.historyAction,
1372 location: navigation.location,
1373 searchParams: new URLSearchParams(navigation.location.search),
1374 params: navigation.matches[navigation.matches.length - 1]?.params ?? {},
1375 matches: navigation.matches.map((m) => toRouterStateMatch(m))
1376 };
1377 return navigation.state === "loading" ? {
1378 ...shared,
1379 state: "loading",
1380 formMethod: navigation.formMethod,
1381 formAction: navigation.formAction,
1382 formEncType: navigation.formEncType,
1383 formData: navigation.formData,
1384 json: navigation.json,
1385 text: navigation.text
1386 } : {
1387 ...shared,
1388 state: "submitting",
1389 formMethod: navigation.formMethod,
1390 formAction: navigation.formAction,
1391 formEncType: navigation.formEncType,
1392 formData: navigation.formData,
1393 json: navigation.json,
1394 text: navigation.text
1395 };
1396 }, [navigation]);
1397 return React$1.useMemo(() => ({
1398 active,
1399 pending
1400 }), [active, pending]);
1401}
1402//#endregion
1403export { _renderMatches, useActionData, useAsyncError, useAsyncValue, useBlocker, useHref, useInRouterContext, useLoaderData, useLocation, useMatch, useMatches, useNavigate, useNavigation, useNavigationType, useOutlet, useOutletContext, useParams, useResolvedPath, useRevalidator, useRoute, useRouteError, useRouteId, useRouteLoaderData, useRouterState, useRoutes, useRoutesImpl };