UNPKG

49.9 kB JavaScript View Raw
1/**
2 * react-router v8.5.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, DataRouterDataContext, DataRouterNavigationContext, DataRouterStateContext, FetchersContext, IsDataRouteContext, LocationContext, NavigationContext, RSCRouterContext, RouteContext, RouteErrorContext, RouteIdContext } 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`: **Deprecated.** Use React's [`<ViewTransition>`](https://react.dev/reference/react/ViewTransition) component instead. See the [migration guide](../../how-to/view-transitions).
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* To prevent {@link ScrollRestoration | `<ScrollRestoration>`} from resetting
216* the scroll position, use the `preventScrollReset` option.
217*
218* ```tsx
219* navigate("?some-tab=1", { preventScrollReset: true });
220* ```
221*
222* For example, if you have a tab interface connected to search params in the
223* middle of a page, and you don't want it to scroll to the top when a tab is
224* clicked.
225*
226* ### Return Type Augmentation
227*
228* Internally, `useNavigate` uses a separate implementation when you are in
229* Declarative mode versus Data/Framework mode - the primary difference being
230* that the latter is able to return a stable reference that does not change
231* identity across navigations. The implementation in Data/Framework mode also
232* returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)
233* that resolves when the navigation is completed. This means the return type of
234* `useNavigate` is `void | Promise<void>`. This is accurate, but can lead to
235* some red squigglies based on the union in the return value:
236*
237* - If you're using `typescript-eslint`, you may see errors from
238* [`@typescript-eslint/no-floating-promises`](https://typescript-eslint.io/rules/no-floating-promises)
239* - In Framework/Data mode, `React.use(navigate())` will show a false-positive
240* `Argument of type 'void | Promise<void>' is not assignable to parameter of
241* type 'Usable<void>'` error
242*
243* The easiest way to work around these issues is to augment the type based on the
244* router you're using:
245*
246* ```ts
247* // If using <BrowserRouter>
248* declare module "react-router" {
249* interface NavigateFunction {
250* (to: To, options?: NavigateOptions): void;
251* (delta: number): void;
252* }
253* }
254*
255* // If using <RouterProvider> or Framework mode
256* declare module "react-router" {
257* interface NavigateFunction {
258* (to: To, options?: NavigateOptions): Promise<void>;
259* (delta: number): Promise<void>;
260* }
261* }
262* ```
263*
264* @public
265* @category Hooks
266* @returns A navigate function for programmatic navigation
267*/
268function useNavigate() {
269 return React$1.useContext(IsDataRouteContext) ? useNavigateStable() : useNavigateUnstable();
270}
271function useNavigateUnstable() {
272 invariant(useInRouterContext(), `useNavigate() may be used only in the context of a <Router> component.`);
273 let dataRouterContext = React$1.useContext(DataRouterContext);
274 let { basename, navigator } = React$1.useContext(NavigationContext);
275 let { matches } = React$1.useContext(RouteContext);
276 let { pathname: locationPathname } = useLocation();
277 let routePathnamesJson = JSON.stringify(getResolveToMatches(matches));
278 let activeRef = React$1.useRef(false);
279 React$1.useLayoutEffect(() => {
280 activeRef.current = true;
281 });
282 return React$1.useCallback((to, options = {}) => {
283 warning(activeRef.current, navigateEffectWarning);
284 if (!activeRef.current) return;
285 if (typeof to === "number") {
286 navigator.go(to);
287 return;
288 }
289 let path = resolveTo(to, JSON.parse(routePathnamesJson), locationPathname, options.relative === "path");
290 if (dataRouterContext == null && basename !== "/") path.pathname = path.pathname === "/" ? basename : joinPaths([basename, path.pathname]);
291 validateNavigationTarget(typeof to === "string" ? to : createPath(to), navigator.createHref(path), getNavigatorCurrentUrl(navigator), "reject");
292 (!!options.replace ? navigator.replace : navigator.push)(path, options.state, options);
293 }, [
294 basename,
295 navigator,
296 routePathnamesJson,
297 locationPathname,
298 dataRouterContext
299 ]);
300}
301const OutletContext = React$1.createContext(null);
302/**
303* Returns the parent route {@link Outlet | `<Outlet context>`}.
304*
305* Often parent routes manage state or other values you want shared with child
306* routes. You can create your own [context provider](https://react.dev/learn/passing-data-deeply-with-context)
307* if you like, but this is such a common situation that it's built-into
308* {@link Outlet | `<Outlet>`}.
309*
310* ```tsx
311* // Parent route
312* function Parent() {
313* const [count, setCount] = React.useState(0);
314* return <Outlet context={[count, setCount]} />;
315* }
316* ```
317*
318* ```tsx
319* // Child route
320* import { useOutletContext } from "react-router";
321*
322* function Child() {
323* const [count, setCount] = useOutletContext();
324* const increment = () => setCount((c) => c + 1);
325* return <button onClick={increment}>{count}</button>;
326* }
327* ```
328*
329* If you're using TypeScript, we recommend the parent component provide a
330* custom hook for accessing the context value. This makes it easier for
331* consumers to get nice typings, control consumers, and know who's consuming
332* the context value.
333*
334* Here's a more realistic example:
335*
336* ```tsx filename=src/routes/dashboard.tsx lines=[14,20]
337* import { useState } from "react";
338* import { Outlet, useOutletContext } from "react-router";
339*
340* import type { User } from "./types";
341*
342* type ContextType = { user: User | null };
343*
344* export default function Dashboard() {
345* const [user, setUser] = useState<User | null>(null);
346*
347* return (
348* <div>
349* <h1>Dashboard</h1>
350* <Outlet context={{ user } satisfies ContextType} />
351* </div>
352* );
353* }
354*
355* export function useUser() {
356* return useOutletContext<ContextType>();
357* }
358* ```
359*
360* ```tsx filename=src/routes/dashboard/messages.tsx lines=[1,4]
361* import { useUser } from "../dashboard";
362*
363* export default function DashboardMessages() {
364* const { user } = useUser();
365* return (
366* <div>
367* <h2>Messages</h2>
368* <p>Hello, {user.name}!</p>
369* </div>
370* );
371* }
372* ```
373*
374* @public
375* @category Hooks
376* @returns The context value passed to the parent {@link Outlet} component
377*/
378function useOutletContext() {
379 return React$1.useContext(OutletContext);
380}
381/**
382* Returns the element for the child route at this level of the route
383* hierarchy. Used internally by {@link Outlet | `<Outlet>`} to render child
384* routes.
385*
386* @public
387* @category Hooks
388* @param context The context to pass to the outlet
389* @returns The child route element or `null` if no child routes match
390*/
391function useOutlet(context) {
392 let outlet = React$1.useContext(RouteContext).outlet;
393 return React$1.useMemo(() => outlet && /* @__PURE__ */ React$1.createElement(OutletContext.Provider, { value: context }, outlet), [outlet, context]);
394}
395/**
396* Returns an object of key/value-pairs of the dynamic params from the current
397* URL that were matched by the routes. Child routes inherit all params from
398* their parent routes.
399*
400* Assuming a route pattern like `/posts/:postId` is matched by `/posts/123`
401* then `params.postId` will be `"123"`.
402*
403* @example
404* import { useParams } from "react-router";
405*
406* function SomeComponent() {
407* let params = useParams();
408* params.postId;
409* }
410*
411* @additionalExamples
412* ### Basic Usage
413*
414* ```tsx
415* import { useParams } from "react-router";
416*
417* // given a route like:
418* <Route path="/posts/:postId" element={<Post />} />;
419*
420* // or a data route like:
421* createBrowserRouter([
422* {
423* path: "/posts/:postId",
424* component: Post,
425* },
426* ]);
427*
428* // or in routes.ts
429* route("/posts/:postId", "routes/post.tsx");
430* ```
431*
432* Access the params in a component:
433*
434* ```tsx
435* import { useParams } from "react-router";
436*
437* export default function Post() {
438* let params = useParams();
439* return <h1>Post: {params.postId}</h1>;
440* }
441* ```
442*
443* ### Multiple Params
444*
445* Patterns can have multiple params:
446*
447* ```tsx
448* "/posts/:postId/comments/:commentId";
449* ```
450*
451* All will be available in the params object:
452*
453* ```tsx
454* import { useParams } from "react-router";
455*
456* export default function Post() {
457* let params = useParams();
458* return (
459* <h1>
460* Post: {params.postId}, Comment: {params.commentId}
461* </h1>
462* );
463* }
464* ```
465*
466* ### Catchall Params
467*
468* Catchall params are defined with `*`:
469*
470* ```tsx
471* "/files/*";
472* ```
473*
474* The matched value will be available in the params object as follows:
475*
476* ```tsx
477* import { useParams } from "react-router";
478*
479* export default function File() {
480* let params = useParams();
481* let catchall = params["*"];
482* // ...
483* }
484* ```
485*
486* You can destructure the catchall param:
487*
488* ```tsx
489* export default function File() {
490* let { "*": catchall } = useParams();
491* console.log(catchall);
492* }
493* ```
494*
495* @public
496* @category Hooks
497* @returns An object containing the dynamic route parameters
498*/
499function useParams() {
500 let { matches } = React$1.useContext(RouteContext);
501 return matches[matches.length - 1]?.params ?? {};
502}
503/**
504* Resolves the pathname of the given `to` value against the current
505* {@link Location}. Similar to {@link useHref}, but returns a
506* {@link Path} instead of a string.
507*
508* @example
509* import { useResolvedPath } from "react-router";
510*
511* function SomeComponent() {
512* // if the user is at /dashboard/profile
513* let path = useResolvedPath("../accounts");
514* path.pathname; // "/dashboard/accounts"
515* path.search; // ""
516* path.hash; // ""
517* }
518*
519* @public
520* @category Hooks
521* @param to The path to resolve
522* @param options Options
523* @param options.relative Defaults to `"route"` so routing is relative to the route tree.
524* Set to `"path"` to make relative routing operate against path segments.
525* @returns The resolved {@link Path} object with `pathname`, `search`, and `hash`
526*/
527function useResolvedPath(to, { relative } = {}) {
528 let { matches } = React$1.useContext(RouteContext);
529 let { pathname: locationPathname } = useLocation();
530 let routePathnamesJson = JSON.stringify(getResolveToMatches(matches));
531 return React$1.useMemo(() => resolveTo(to, JSON.parse(routePathnamesJson), locationPathname, relative === "path"), [
532 to,
533 routePathnamesJson,
534 locationPathname,
535 relative
536 ]);
537}
538/**
539* Hook version of {@link Routes | `<Routes>`} that uses objects instead of
540* components. These objects have the same properties as the component props.
541* The return value of `useRoutes` is either a valid React element you can use
542* to render the route tree, or `null` if nothing matched.
543*
544* @example
545* import { useRoutes } from "react-router";
546*
547* function App() {
548* let element = useRoutes([
549* {
550* path: "/",
551* element: <Dashboard />,
552* children: [
553* {
554* path: "messages",
555* element: <DashboardMessages />,
556* },
557* { path: "tasks", element: <DashboardTasks /> },
558* ],
559* },
560* { path: "team", element: <AboutPage /> },
561* ]);
562*
563* return element;
564* }
565*
566* @public
567* @category Hooks
568* @param routes An array of {@link RouteObject}s that define the route hierarchy
569* @param locationArg An optional {@link Location} object or pathname string to
570* use instead of the current {@link Location}
571* @returns A React element to render the matched route, or `null` if no routes matched
572*/
573function useRoutes(routes, locationArg) {
574 return useRoutesImpl(routes, locationArg);
575}
576function useRoutesImpl(routes, locationArg, dataRouterOpts) {
577 invariant(useInRouterContext(), `useRoutes() may be used only in the context of a <Router> component.`);
578 let { navigator } = React$1.useContext(NavigationContext);
579 let { matches: parentMatches } = React$1.useContext(RouteContext);
580 let routeMatch = parentMatches[parentMatches.length - 1];
581 let parentParams = routeMatch ? routeMatch.params : {};
582 routeMatch && routeMatch.pathname;
583 let parentPathnameBase = routeMatch ? routeMatch.pathnameBase : "/";
584 routeMatch && routeMatch.route;
585 let locationFromContext = useLocation();
586 let location;
587 if (locationArg) {
588 let parsedLocationArg = typeof locationArg === "string" ? parsePath(locationArg) : locationArg;
589 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.`);
590 location = parsedLocationArg;
591 } else location = locationFromContext;
592 let pathname = location.pathname || "/";
593 let remainingPathname = pathname;
594 if (parentPathnameBase !== "/") {
595 let parentSegments = parentPathnameBase.replace(/^\//, "").split("/");
596 remainingPathname = "/" + pathname.replace(/^\//, "").split("/").slice(parentSegments.length).join("/");
597 }
598 let matches;
599 if (dataRouterOpts) if (dataRouterOpts.state.matches.length) matches = dataRouterOpts.state.matches.map((m) => Object.assign(m, { route: dataRouterOpts.manifest[m.route.id] || m.route }));
600 else matches = dataRouterOpts.router.match(dataRouterOpts.state.location);
601 else matches = matchRoutes(routes, { pathname: remainingPathname });
602 let renderedMatches = _renderMatches(matches && matches.map((match) => Object.assign({}, match, {
603 params: Object.assign({}, parentParams, match.params),
604 pathname: joinPaths([parentPathnameBase, navigator.encodeLocation ? navigator.encodeLocation(match.pathname.replace(/%/g, "%25").replace(/\?/g, "%3F").replace(/#/g, "%23")).pathname : match.pathname]),
605 pathnameBase: match.pathnameBase === "/" ? parentPathnameBase : joinPaths([parentPathnameBase, navigator.encodeLocation ? navigator.encodeLocation(match.pathnameBase.replace(/%/g, "%25").replace(/\?/g, "%3F").replace(/#/g, "%23")).pathname : match.pathnameBase])
606 })), parentMatches, dataRouterOpts);
607 if (locationArg && renderedMatches) return /* @__PURE__ */ React$1.createElement(LocationContext.Provider, { value: {
608 location: {
609 pathname: "/",
610 search: "",
611 hash: "",
612 state: null,
613 key: "default",
614 mask: void 0,
615 ...location
616 },
617 navigationType: "POP"
618 } }, renderedMatches);
619 return renderedMatches;
620}
621function DefaultErrorComponent() {
622 let error = useRouteError();
623 let message = isRouteErrorResponse(error) ? `${error.status} ${error.statusText}` : error instanceof Error ? error.message : JSON.stringify(error);
624 let stack = error instanceof Error ? error.stack : null;
625 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: {
626 padding: "0.5rem",
627 backgroundColor: "rgba(200,200,200, 0.5)"
628 } }, stack) : null, null);
629}
630const defaultErrorElement = /* @__PURE__ */ React$1.createElement(DefaultErrorComponent, null);
631var RenderErrorBoundary = class extends React$1.Component {
632 constructor(props) {
633 super(props);
634 this.state = {
635 location: props.location,
636 revalidation: props.revalidation,
637 error: props.error
638 };
639 }
640 static contextType = RSCRouterContext;
641 static getDerivedStateFromError(error) {
642 return { error };
643 }
644 static getDerivedStateFromProps(props, state) {
645 if (state.location !== props.location || state.revalidation !== "idle" && props.revalidation === "idle") return {
646 error: props.error,
647 location: props.location,
648 revalidation: props.revalidation
649 };
650 return {
651 error: props.error !== void 0 ? props.error : state.error,
652 location: state.location,
653 revalidation: props.revalidation || state.revalidation
654 };
655 }
656 componentDidCatch(error, errorInfo) {
657 if (this.props.onError) this.props.onError(error, errorInfo);
658 else console.error("React Router caught the following error during render", error);
659 }
660 render() {
661 let error = this.state.error;
662 if (this.context && typeof error === "object" && error && "digest" in error && typeof error.digest === "string") {
663 const decoded = decodeRouteErrorResponseDigest(error.digest);
664 if (decoded) error = decoded;
665 }
666 let result = error !== void 0 ? /* @__PURE__ */ React$1.createElement(RouteContext.Provider, { value: this.props.routeContext }, /* @__PURE__ */ React$1.createElement(IsDataRouteContext.Provider, { value: this.props.routeContext.isDataRoute }, /* @__PURE__ */ React$1.createElement(RouteIdContext.Provider, { value: this.props.routeContext.matches[this.props.routeContext.matches.length - 1]?.route.id }, /* @__PURE__ */ React$1.createElement(RouteErrorContext.Provider, {
667 value: error,
668 children: this.props.component
669 })))) : this.props.children;
670 if (this.context) return /* @__PURE__ */ React$1.createElement(RSCErrorHandler, { error }, result);
671 return result;
672 }
673};
674const errorRedirectHandledMap = /* @__PURE__ */ new WeakMap();
675function RSCErrorHandler({ children, error }) {
676 let { basename, navigator } = React$1.useContext(NavigationContext);
677 if (typeof error === "object" && error && "digest" in error && typeof error.digest === "string") {
678 let redirect = decodeRedirectErrorDigest(error.digest);
679 if (redirect) {
680 let existingRedirect = errorRedirectHandledMap.get(error);
681 if (existingRedirect) throw existingRedirect;
682 let parsed = parseToInfo(redirect.location, basename);
683 let target = parsed.absoluteURL || parsed.to;
684 validateNavigationTarget(redirect.location, target, getNavigatorCurrentUrl(navigator), "allow-explicit");
685 if (hasInvalidProtocol(target)) throw new Error("Invalid redirect location");
686 if (isBrowser && !errorRedirectHandledMap.get(error)) if (parsed.isExternal || redirect.reloadDocument) window.location.href = target;
687 else {
688 const redirectPromise = Promise.resolve().then(() => window.__reactRouterDataRouter.navigate(parsed.to, { replace: redirect.replace }));
689 errorRedirectHandledMap.set(error, redirectPromise);
690 throw redirectPromise;
691 }
692 return /* @__PURE__ */ React$1.createElement("meta", {
693 httpEquiv: "refresh",
694 content: `0;url=${target}`
695 });
696 }
697 }
698 return children;
699}
700function RenderedRoute({ routeContext, match, children }) {
701 let dataRouterContext = React$1.useContext(DataRouterContext);
702 if (dataRouterContext && dataRouterContext.static && dataRouterContext.staticContext && (match.route.errorElement || match.route.ErrorBoundary)) dataRouterContext.staticContext._deepestRenderedBoundaryId = match.route.id;
703 return /* @__PURE__ */ React$1.createElement(RouteContext.Provider, { value: routeContext }, /* @__PURE__ */ React$1.createElement(IsDataRouteContext.Provider, { value: routeContext.isDataRoute }, /* @__PURE__ */ React$1.createElement(RouteIdContext.Provider, { value: match.route.id }, children)));
704}
705function _renderMatches(matches, parentMatches = [], dataRouterOpts) {
706 let dataRouterState = dataRouterOpts?.state;
707 if (matches == null) {
708 if (!dataRouterState) return null;
709 if (dataRouterState.errors) matches = dataRouterState.matches;
710 else if (parentMatches.length === 0 && !dataRouterState.initialized && dataRouterState.matches.length > 0) matches = dataRouterState.matches;
711 else return null;
712 }
713 let renderedMatches = matches;
714 let errors = dataRouterState?.errors;
715 if (errors != null) {
716 let errorIndex = renderedMatches.findIndex((m) => m.route.id && errors?.[m.route.id] !== void 0);
717 invariant(errorIndex >= 0, `Could not find a matching route for errors on route IDs: ${Object.keys(errors).join(",")}`);
718 renderedMatches = renderedMatches.slice(0, Math.min(renderedMatches.length, errorIndex + 1));
719 }
720 let renderFallback = false;
721 let fallbackIndex = -1;
722 if (dataRouterOpts && dataRouterState) {
723 renderFallback = dataRouterState.renderFallback;
724 for (let i = 0; i < renderedMatches.length; i++) {
725 let match = renderedMatches[i];
726 if (match.route.HydrateFallback || match.route.hydrateFallbackElement) fallbackIndex = i;
727 if (match.route.id) {
728 let { loaderData, errors } = dataRouterState;
729 let needsToRunLoader = match.route.loader && !loaderData.hasOwnProperty(match.route.id) && (!errors || errors[match.route.id] === void 0);
730 if (match.route.lazy || needsToRunLoader) {
731 if (dataRouterOpts.isStatic) renderFallback = true;
732 if (fallbackIndex >= 0) renderedMatches = renderedMatches.slice(0, fallbackIndex + 1);
733 else renderedMatches = [renderedMatches[0]];
734 break;
735 }
736 }
737 }
738 }
739 let onErrorHandler = dataRouterOpts?.onError;
740 let onError = dataRouterState && onErrorHandler ? (error, errorInfo) => {
741 onErrorHandler(error, {
742 location: dataRouterState.location,
743 params: dataRouterState.matches?.[0]?.params ?? {},
744 pattern: getRoutePattern(dataRouterState.matches),
745 errorInfo
746 });
747 } : void 0;
748 return renderedMatches.reduceRight((outlet, match, index) => {
749 let error;
750 let shouldRenderHydrateFallback = false;
751 let errorElement = null;
752 let hydrateFallbackElement = null;
753 if (dataRouterState) {
754 error = errors && match.route.id ? errors[match.route.id] : void 0;
755 errorElement = match.route.errorElement || defaultErrorElement;
756 if (renderFallback) {
757 if (fallbackIndex < 0 && index === 0) {
758 warningOnce("route-fallback", false, "No `HydrateFallback` element provided to render during initial hydration");
759 shouldRenderHydrateFallback = true;
760 hydrateFallbackElement = null;
761 } else if (fallbackIndex === index) {
762 shouldRenderHydrateFallback = true;
763 hydrateFallbackElement = match.route.hydrateFallbackElement || null;
764 }
765 }
766 }
767 let matches = parentMatches.concat(renderedMatches.slice(0, index + 1));
768 let getChildren = () => {
769 let children;
770 if (error) children = errorElement;
771 else if (shouldRenderHydrateFallback) children = hydrateFallbackElement;
772 else if (match.route.Component) children = /* @__PURE__ */ React$1.createElement(match.route.Component, null);
773 else if (match.route.element) children = match.route.element;
774 else children = outlet;
775 return /* @__PURE__ */ React$1.createElement(RenderedRoute, {
776 match,
777 routeContext: {
778 outlet,
779 matches,
780 isDataRoute: dataRouterState != null
781 },
782 children
783 });
784 };
785 return dataRouterState && (match.route.ErrorBoundary || match.route.errorElement || index === 0) ? /* @__PURE__ */ React$1.createElement(RenderErrorBoundary, {
786 location: dataRouterState.location,
787 revalidation: dataRouterState.revalidation,
788 component: errorElement,
789 error,
790 children: getChildren(),
791 routeContext: {
792 outlet: null,
793 matches,
794 isDataRoute: true
795 },
796 onError
797 }) : getChildren();
798 }, null);
799}
800function getDataRouterConsoleError(hookName) {
801 return `${hookName} must be used within a data router. See https://reactrouter.com/en/main/routers/picking-a-router.`;
802}
803function useDataRouterContext(hookName) {
804 let ctx = React$1.useContext(DataRouterContext);
805 invariant(ctx, getDataRouterConsoleError(hookName));
806 return ctx;
807}
808function useDataRouterState(hookName) {
809 let state = React$1.useContext(DataRouterStateContext);
810 invariant(state, getDataRouterConsoleError(hookName));
811 return state;
812}
813function useDataRouterFetchers(hookName) {
814 let fetchers = React$1.useContext(FetchersContext);
815 invariant(fetchers, getDataRouterConsoleError(hookName));
816 return fetchers;
817}
818function useDataRouterData(hookName) {
819 let data = React$1.useContext(DataRouterDataContext);
820 invariant(data, getDataRouterConsoleError(hookName));
821 return data;
822}
823function useDataRouterNavigation(hookName) {
824 let navigation = React$1.useContext(DataRouterNavigationContext);
825 invariant(navigation, getDataRouterConsoleError(hookName));
826 return navigation;
827}
828function useCurrentRouteId(hookName) {
829 let routeId = React$1.useContext(RouteIdContext);
830 invariant(routeId, `${hookName} can only be used on routes that contain a unique "id"`);
831 return routeId;
832}
833/**
834* Returns the current {@link Navigation}, defaulting to an "idle" navigation
835* when no navigation is in progress. You can use this to render pending UI
836* (like a global spinner) or read [`FormData`](https://developer.mozilla.org/en-US/docs/Web/API/FormData)
837* from a form navigation.
838*
839* @example
840* import { useNavigation } from "react-router";
841*
842* function SomeComponent() {
843* let navigation = useNavigation();
844* navigation.state;
845* navigation.formData;
846* // etc.
847* }
848*
849* @public
850* @category Hooks
851* @mode framework
852* @mode data
853* @returns The current {@link Navigation} object
854*/
855function useNavigation() {
856 let { navigation } = useDataRouterNavigation("useNavigation");
857 return React$1.useMemo(() => {
858 let { matches, historyAction, ...rest } = navigation;
859 return rest;
860 }, [navigation]);
861}
862/**
863* Revalidate the data on the page for reasons outside of normal data mutations
864* like [`Window` focus](https://developer.mozilla.org/en-US/docs/Web/API/Window/focus_event)
865* or polling on an interval.
866*
867* Note that page data is already revalidated automatically after actions.
868* If you find yourself using this for normal CRUD operations on your data in
869* response to user interactions, you're probably not taking advantage of the
870* other APIs like {@link useFetcher}, {@link Form}, {@link useSubmit} that do
871* this automatically.
872*
873* @example
874* import { useRevalidator } from "react-router";
875*
876* function WindowFocusRevalidator() {
877* const revalidator = useRevalidator();
878*
879* useFakeWindowFocus(() => {
880* revalidator.revalidate();
881* });
882*
883* return (
884* <div hidden={revalidator.state === "idle"}>
885* Revalidating...
886* </div>
887* );
888* }
889*
890* @public
891* @category Hooks
892* @mode framework
893* @mode data
894* @returns An object with a `revalidate` function and the current revalidation
895* `state`
896*/
897function useRevalidator() {
898 let dataRouterContext = useDataRouterContext("useRevalidator");
899 let { revalidation } = useDataRouterNavigation("useRevalidator");
900 let revalidate = React$1.useCallback(async () => {
901 await dataRouterContext.router.revalidate();
902 }, [dataRouterContext.router]);
903 return React$1.useMemo(() => ({
904 revalidate,
905 state: revalidation
906 }), [revalidate, revalidation]);
907}
908/**
909* Returns the active route matches, useful for accessing `loaderData` for
910* parent/child routes or the route [`handle`](../../start/framework/route-module#handle)
911* property
912*
913* Pairing the route `handle` with `useMatches` gets very powerful since you can put
914* whatever you want on a route handle and have access to `useMatches` anywhere.
915* Please see the [handle](../../how-to/using-handle) documentation for an example
916* of breadcrumbs via `useMatches`/`handle`.
917*
918* ```tsx
919* import { useMatches } from "react-router";
920*
921* function SomeComponent() {
922* const matches = useMatches();
923* // matches[i].id // route id
924* // matches[i].pathname // the portion of the URL the route matched
925* // matches[i].params // the parsed params from the URL
926* // matches[i].loaderData // the data from the loader
927* // matches[i].handle // the route handle with any app specific data
928* }
929* ```
930*
931* <docs-info>useMatches only works with a data router like `createBrowserRouter`,
932* since they know the full route tree up front and can provide all of the current
933* matches. Additionally, `useMatches` will not match down into any descendant route
934* trees since the router isn't aware of the descendant routes.</docs-info>
935*
936* @public
937* @category Hooks
938* @mode framework
939* @mode data
940* @returns An array of {@link UIMatch | UI matches} for the current route hierarchy
941*/
942function useMatches() {
943 let { matches } = useDataRouterState("useMatches");
944 let { loaderData } = useDataRouterData("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 data = useDataRouterData("useLoaderData");
972 let routeId = useCurrentRouteId("useLoaderData");
973 return data.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 useDataRouterData("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 data = useDataRouterData("useActionData");
1044 let routeId = useCurrentRouteId("useActionData");
1045 return data.actionData ? data.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 data = useDataRouterData("useRouteError");
1070 let routeId = useCurrentRouteId("useRouteError");
1071 if (error !== void 0) return error;
1072 return data.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 let value = React$1.useContext(AwaitContext);
1096 return value && "status" in value && !("_tracked" in value) ? value.status === "fulfilled" ? value.value : void 0 : value?._data;
1097}
1098/**
1099* Returns the rejection value from the closest {@link Await | `<Await>`}.
1100*
1101* @example
1102* import { Await, useAsyncError } from "react-router";
1103*
1104* function ErrorElement() {
1105* const error = useAsyncError();
1106* return (
1107* <p>Uh Oh, something went wrong! {error.message}</p>
1108* );
1109* }
1110*
1111* // somewhere in your app
1112* <Await
1113* resolve={promiseThatRejects}
1114* errorElement={<ErrorElement />}
1115* />;
1116*
1117* @public
1118* @category Hooks
1119* @mode framework
1120* @mode data
1121* @returns The error that was thrown in the nearest {@link Await} component
1122*/
1123function useAsyncError() {
1124 let value = React$1.useContext(AwaitContext);
1125 return value && "status" in value && !("_tracked" in value) ? value.status === "rejected" ? value.reason : void 0 : value?._error;
1126}
1127let blockerId = 0;
1128/**
1129* Allow the application to block navigations within the SPA and present the
1130* user a confirmation dialog to confirm the navigation. Mostly used to avoid
1131* using half-filled form data. This does not handle hard-reloads or
1132* cross-origin navigations.
1133*
1134* The {@link Blocker} object returned by the hook has the following properties:
1135*
1136* - **`state`**
1137* - `unblocked` - the blocker is idle and has not prevented any navigation
1138* - `blocked` - the blocker has prevented a navigation
1139* - `proceeding` - the blocker is proceeding through from a blocked navigation
1140* - **`location`**
1141* - When in a `blocked` state, this represents the {@link Location} to which
1142* we blocked a navigation. When in a `proceeding` state, this is the
1143* location being navigated to after a `blocker.proceed()` call.
1144* - **`proceed()`**
1145* - When in a `blocked` state, you may call `blocker.proceed()` to proceed to
1146* the blocked location.
1147* - **`reset()`**
1148* - When in a `blocked` state, you may call `blocker.reset()` to return the
1149* blocker to an `unblocked` state and leave the user at the current
1150* location.
1151*
1152* @example
1153* // Boolean version
1154* let blocker = useBlocker(value !== "");
1155*
1156* // Function version
1157* let blocker = useBlocker(
1158* ({ currentLocation, nextLocation, historyAction }) =>
1159* value !== "" &&
1160* currentLocation.pathname !== nextLocation.pathname
1161* );
1162*
1163* @additionalExamples
1164* ```tsx
1165* import { useCallback, useState } from "react";
1166* import { BlockerFunction, useBlocker } from "react-router";
1167*
1168* export function ImportantForm() {
1169* const [value, setValue] = useState("");
1170*
1171* const shouldBlock = useCallback<BlockerFunction>(
1172* () => value !== "",
1173* [value]
1174* );
1175* const blocker = useBlocker(shouldBlock);
1176*
1177* return (
1178* <form
1179* onSubmit={(e) => {
1180* e.preventDefault();
1181* setValue("");
1182* if (blocker.state === "blocked") {
1183* blocker.proceed();
1184* }
1185* }}
1186* >
1187* <input
1188* name="data"
1189* value={value}
1190* onChange={(e) => setValue(e.target.value)}
1191* />
1192*
1193* <button type="submit">Save</button>
1194*
1195* {blocker.state === "blocked" ? (
1196* <>
1197* <p style={{ color: "red" }}>
1198* Blocked the last navigation to
1199* </p>
1200* <button
1201* type="button"
1202* onClick={() => blocker.proceed()}
1203* >
1204* Let me through
1205* </button>
1206* <button
1207* type="button"
1208* onClick={() => blocker.reset()}
1209* >
1210* Keep me here
1211* </button>
1212* </>
1213* ) : blocker.state === "proceeding" ? (
1214* <p style={{ color: "orange" }}>
1215* Proceeding through blocked navigation
1216* </p>
1217* ) : (
1218* <p style={{ color: "green" }}>
1219* Blocker is currently unblocked
1220* </p>
1221* )}
1222* </form>
1223* );
1224* }
1225* ```
1226*
1227* @public
1228* @category Hooks
1229* @mode framework
1230* @mode data
1231* @param shouldBlock Either a boolean or a function returning a boolean which
1232* indicates whether the navigation should be blocked. The function format
1233* receives a single object parameter containing the `currentLocation`,
1234* `nextLocation`, and `historyAction` of the potential navigation.
1235* @returns A {@link Blocker} object with state and reset functionality
1236*/
1237function useBlocker(shouldBlock) {
1238 let { router, basename } = useDataRouterContext("useBlocker");
1239 let state = useDataRouterState("useBlocker");
1240 let [blockerKey, setBlockerKey] = React$1.useState("");
1241 let blockerFunction = React$1.useCallback((arg) => {
1242 if (typeof shouldBlock !== "function") return !!shouldBlock;
1243 if (basename === "/") return shouldBlock(arg);
1244 let { currentLocation, nextLocation, historyAction } = arg;
1245 return shouldBlock({
1246 currentLocation: {
1247 ...currentLocation,
1248 pathname: stripBasename(currentLocation.pathname, basename) || currentLocation.pathname
1249 },
1250 nextLocation: {
1251 ...nextLocation,
1252 pathname: stripBasename(nextLocation.pathname, basename) || nextLocation.pathname
1253 },
1254 historyAction
1255 });
1256 }, [basename, shouldBlock]);
1257 React$1.useEffect(() => {
1258 let key = String(++blockerId);
1259 setBlockerKey(key);
1260 return () => router.deleteBlocker(key);
1261 }, [router]);
1262 React$1.useEffect(() => {
1263 if (blockerKey !== "") router.getBlocker(blockerKey, blockerFunction);
1264 }, [
1265 router,
1266 blockerKey,
1267 blockerFunction
1268 ]);
1269 return blockerKey && state.blockers.has(blockerKey) ? state.blockers.get(blockerKey) : IDLE_BLOCKER;
1270}
1271function useNavigateStable() {
1272 let { router } = useDataRouterContext("useNavigate");
1273 let id = useCurrentRouteId("useNavigate");
1274 let activeRef = React$1.useRef(false);
1275 React$1.useLayoutEffect(() => {
1276 activeRef.current = true;
1277 });
1278 return React$1.useCallback(async (to, options = {}) => {
1279 warning(activeRef.current, navigateEffectWarning);
1280 if (!activeRef.current) return;
1281 if (typeof to === "number") await router.navigate(to);
1282 else await router.navigate(to, {
1283 fromRouteId: id,
1284 ...options
1285 });
1286 }, [router, id]);
1287}
1288const alreadyWarned = {};
1289function warningOnce(key, cond, message) {
1290 if (!cond && !alreadyWarned[key]) {
1291 alreadyWarned[key] = true;
1292 warning(false, message);
1293 }
1294}
1295function useRoute(...args) {
1296 const currentRouteId = useCurrentRouteId("useRoute");
1297 const id = args[0] ?? currentRouteId;
1298 const state = useDataRouterState("useRoute");
1299 const data = useDataRouterData("useRoute");
1300 const route = state.matches.find(({ route }) => route.id === id);
1301 if (route === void 0) return void 0;
1302 return {
1303 handle: route.route.handle,
1304 loaderData: data.loaderData[id],
1305 actionData: data.actionData?.[id]
1306 };
1307}
1308function toRouterStateMatch(match) {
1309 return {
1310 id: match.route.id,
1311 pathname: match.pathname,
1312 params: match.params,
1313 handle: match.route.handle
1314 };
1315}
1316/**
1317* A unified hook for reading router state: current (`active`) and in-flight
1318* (`pending`) locations, search params, params, matches, and navigation type.
1319*
1320* This hook consolidates the information you used to get from {@link useLocation},
1321* {@link useSearchParams}, {@link useParams}, {@link useMatches}, {@link useNavigation},
1322* and {@link useNavigationType} into a single hook.
1323*
1324*
1325* @example
1326* import { unstable_useRouterState as useRouterState } from "react-router";
1327*
1328* let { active, pending } = useRouterState();
1329*
1330* // Active is always populated with the current location
1331* active.location; // replaces `useLocation()`
1332* active.searchParams; // replaces `useSearchParams()[0]`
1333* active.params; // replaces `useParams()`
1334* active.matches; // replaces `useMatches()`
1335* active.type; // replaces `useNavigationType()`
1336*
1337* // Pending is only populated during a navigation
1338* pending.location; // replaces `useNavigation().location`
1339* pending.searchParams; // equivalent to `new URLSearchParams(useNavigation().search)`
1340* pending.params; // Not directly accessible today
1341* pending.matches; // Not directly accessible today
1342* pending.type; // Not directly accessible today
1343* pending.state; // replaces `useNavigation().state`
1344* pending.formMethod; // replaces useNavigation().formMethod
1345* pending.formAction; // replaces useNavigation().formAction
1346* pending.formEncType; // replaces useNavigation().formEncType
1347* pending.formData; // replaces useNavigation().formData
1348* pending.json; // replaces useNavigation().json
1349* pending.text; // replaces useNavigation().text
1350*
1351* @name unstable_useRouterState
1352* @public
1353* @category Hooks
1354* @mode framework
1355* @mode data
1356* @returns The current router state with `active` and `pending` variants
1357*/
1358function useRouterState() {
1359 let { location, historyAction: type, matches } = useDataRouterState("unstable_useRouterState");
1360 let { navigation } = useDataRouterNavigation("unstable_useRouterState");
1361 let active = React$1.useMemo(() => ({
1362 type,
1363 location,
1364 searchParams: new URLSearchParams(location.search),
1365 params: matches[matches.length - 1]?.params ?? {},
1366 matches: matches.map((m) => toRouterStateMatch(m))
1367 }), [
1368 location,
1369 matches,
1370 type
1371 ]);
1372 let pending = React$1.useMemo(() => {
1373 if (navigation.state === "idle") return null;
1374 let shared = {
1375 type: navigation.historyAction,
1376 location: navigation.location,
1377 searchParams: new URLSearchParams(navigation.location.search),
1378 params: navigation.matches[navigation.matches.length - 1]?.params ?? {},
1379 matches: navigation.matches.map((m) => toRouterStateMatch(m))
1380 };
1381 return navigation.state === "loading" ? {
1382 ...shared,
1383 state: "loading",
1384 formMethod: navigation.formMethod,
1385 formAction: navigation.formAction,
1386 formEncType: navigation.formEncType,
1387 formData: navigation.formData,
1388 json: navigation.json,
1389 text: navigation.text
1390 } : {
1391 ...shared,
1392 state: "submitting",
1393 formMethod: navigation.formMethod,
1394 formAction: navigation.formAction,
1395 formEncType: navigation.formEncType,
1396 formData: navigation.formData,
1397 json: navigation.json,
1398 text: navigation.text
1399 };
1400 }, [navigation]);
1401 return React$1.useMemo(() => ({
1402 active,
1403 pending
1404 }), [active, pending]);
1405}
1406//#endregion
1407export { _renderMatches, useActionData, useAsyncError, useAsyncValue, useBlocker, useCurrentRouteId, useDataRouterContext, useDataRouterData, useDataRouterFetchers, useDataRouterState, useHref, useInRouterContext, useLoaderData, useLocation, useMatch, useMatches, useNavigate, useNavigation, useNavigationType, useOutlet, useOutletContext, useParams, useResolvedPath, useRevalidator, useRoute, useRouteError, useRouteLoaderData, useRouterState, useRoutes, useRoutesImpl };