UNPKG

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