UNPKG

53.3 kBJavaScriptView Raw
1/**
2 * react-router v8.5.3
3 *
4 * Copyright (c) Remix Software Inc.
5 *
6 * This source code is licensed under the MIT license found in the
7 * LICENSE.md file in the root directory of this source tree.
8 *
9 * @license MIT
10 */
11import { createPath, invariant, parsePath, warning } from "./router/history.js";
12import { getNavigatorCurrentUrl, validateNavigationTarget } from "./router/navigation.js";
13import { convertRouteMatchToUiMatch, decodePath, getResolveToMatches, getRoutePattern, isBrowser, isRouteErrorResponse, joinPaths, matchPath, matchRoutes, parseToInfo, resolveTo, stripBasename } from "./router/utils.js";
14import { IDLE_BLOCKER, hasInvalidProtocol } from "./router/router.js";
15import { AwaitContext, DataRouterContext, DataRouterDataContext, DataRouterNavigationContext, DataRouterStateContext, FetchersContext, IsDataRouteContext, LocationContext, NavigationContext, RSCErrorAlreadyReportedContext, 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 let parentPathname = routeMatch ? routeMatch.pathname : "/";
583 let parentPathnameBase = routeMatch ? routeMatch.pathnameBase : "/";
584 let parentRoute = routeMatch && routeMatch.route;
585 {
586 let parentPath = parentRoute && parentRoute.path || "";
587 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}/*`}\">.`);
588 }
589 let locationFromContext = useLocation();
590 let location;
591 if (locationArg) {
592 let parsedLocationArg = typeof locationArg === "string" ? parsePath(locationArg) : locationArg;
593 invariant(parentPathnameBase === "/" || parsedLocationArg.pathname?.startsWith(parentPathnameBase), `When overriding the location using \`<Routes location>\` or \`useRoutes(routes, location)\`, the location pathname must begin with the portion of the URL pathname that was matched by all parent routes. The current pathname base is "${parentPathnameBase}" but pathname "${parsedLocationArg.pathname}" was given in the \`location\` prop.`);
594 location = parsedLocationArg;
595 } else location = locationFromContext;
596 let pathname = location.pathname || "/";
597 let remainingPathname = pathname;
598 if (parentPathnameBase !== "/") {
599 let parentSegments = parentPathnameBase.replace(/^\//, "").split("/");
600 remainingPathname = "/" + pathname.replace(/^\//, "").split("/").slice(parentSegments.length).join("/");
601 }
602 let matches;
603 if (dataRouterOpts) if (dataRouterOpts.state.matches.length) matches = dataRouterOpts.state.matches.map((m) => Object.assign(m, { route: dataRouterOpts.manifest[m.route.id] || m.route }));
604 else matches = dataRouterOpts.router.match(dataRouterOpts.state.location);
605 else matches = matchRoutes(routes, { pathname: remainingPathname });
606 warning(parentRoute || matches != null, `No routes matched location "${location.pathname}${location.search}${location.hash}" `);
607 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.`);
608 let renderedMatches = _renderMatches(matches && matches.map((match) => Object.assign({}, match, {
609 params: Object.assign({}, parentParams, match.params),
610 pathname: joinPaths([parentPathnameBase, navigator.encodeLocation ? navigator.encodeLocation(match.pathname.replace(/%/g, "%25").replace(/\?/g, "%3F").replace(/#/g, "%23")).pathname : match.pathname]),
611 pathnameBase: match.pathnameBase === "/" ? parentPathnameBase : joinPaths([parentPathnameBase, navigator.encodeLocation ? navigator.encodeLocation(match.pathnameBase.replace(/%/g, "%25").replace(/\?/g, "%3F").replace(/#/g, "%23")).pathname : match.pathnameBase])
612 })), parentMatches, dataRouterOpts);
613 if (locationArg && renderedMatches) return /* @__PURE__ */ React$1.createElement(LocationContext.Provider, { value: {
614 location: {
615 pathname: "/",
616 search: "",
617 hash: "",
618 state: null,
619 key: "default",
620 mask: void 0,
621 ...location
622 },
623 navigationType: "POP"
624 } }, renderedMatches);
625 return renderedMatches;
626}
627function DefaultErrorComponent() {
628 let error = useRouteError();
629 let alreadyReported = React$1.useContext(RSCErrorAlreadyReportedContext);
630 let message = isRouteErrorResponse(error) ? `${error.status} ${error.statusText}` : error instanceof Error ? error.message : JSON.stringify(error);
631 let stack = error instanceof Error ? error.stack : null;
632 let lightgrey = "rgba(200,200,200, 0.5)";
633 let preStyles = {
634 padding: "0.5rem",
635 backgroundColor: lightgrey
636 };
637 let codeStyles = {
638 padding: "2px 4px",
639 backgroundColor: lightgrey
640 };
641 let devInfo = null;
642 if (!alreadyReported) console.error("Error handled by React Router default ErrorBoundary:", error);
643 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."));
644 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);
645}
646const defaultErrorElement = /* @__PURE__ */ React$1.createElement(DefaultErrorComponent, null);
647var RenderErrorBoundary = class extends React$1.Component {
648 constructor(props) {
649 super(props);
650 this.state = {
651 location: props.location,
652 revalidation: props.revalidation,
653 error: props.error
654 };
655 }
656 static contextType = RSCRouterContext;
657 static getDerivedStateFromError(error) {
658 return { error };
659 }
660 static getDerivedStateFromProps(props, state) {
661 if (state.location !== props.location || state.revalidation !== "idle" && props.revalidation === "idle") return {
662 error: props.error,
663 location: props.location,
664 revalidation: props.revalidation
665 };
666 return {
667 error: props.error !== void 0 ? props.error : state.error,
668 location: state.location,
669 revalidation: props.revalidation || state.revalidation
670 };
671 }
672 componentDidCatch(error, errorInfo) {
673 if (this.props.onError) this.props.onError(error, errorInfo);
674 else console.error("React Router caught the following error during render", error);
675 }
676 render() {
677 let error = this.state.error;
678 if (this.context && typeof error === "object" && error && "digest" in error && typeof error.digest === "string") {
679 const decoded = decodeRouteErrorResponseDigest(error.digest);
680 if (decoded) error = decoded;
681 }
682 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, {
683 value: error,
684 children: this.props.component
685 })))) : this.props.children;
686 if (this.context) return /* @__PURE__ */ React$1.createElement(RSCErrorHandler, { error }, result);
687 return result;
688 }
689};
690const errorRedirectHandledMap = /* @__PURE__ */ new WeakMap();
691function RSCErrorHandler({ children, error }) {
692 let { basename, navigator } = React$1.useContext(NavigationContext);
693 if (typeof error === "object" && error && "digest" in error && typeof error.digest === "string") {
694 let redirect = decodeRedirectErrorDigest(error.digest);
695 if (redirect) {
696 let existingRedirect = errorRedirectHandledMap.get(error);
697 if (existingRedirect) throw existingRedirect;
698 let parsed = parseToInfo(redirect.location, basename);
699 let target = parsed.absoluteURL || parsed.to;
700 validateNavigationTarget(redirect.location, target, getNavigatorCurrentUrl(navigator), "allow-explicit");
701 if (hasInvalidProtocol(target)) throw new Error("Invalid redirect location");
702 if (isBrowser && !errorRedirectHandledMap.get(error)) if (parsed.isExternal || redirect.reloadDocument) window.location.href = target;
703 else {
704 const redirectPromise = Promise.resolve().then(() => window.__reactRouterDataRouter.navigate(parsed.to, { replace: redirect.replace }));
705 errorRedirectHandledMap.set(error, redirectPromise);
706 throw redirectPromise;
707 }
708 return /* @__PURE__ */ React$1.createElement("meta", {
709 httpEquiv: "refresh",
710 content: `0;url=${target}`
711 });
712 }
713 }
714 return children;
715}
716function RenderedRoute({ routeContext, match, children }) {
717 let dataRouterContext = React$1.useContext(DataRouterContext);
718 if (dataRouterContext && dataRouterContext.static && dataRouterContext.staticContext && (match.route.errorElement || match.route.ErrorBoundary)) dataRouterContext.staticContext._deepestRenderedBoundaryId = match.route.id;
719 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)));
720}
721function _renderMatches(matches, parentMatches = [], dataRouterOpts) {
722 let dataRouterState = dataRouterOpts?.state;
723 if (matches == null) {
724 if (!dataRouterState) return null;
725 if (dataRouterState.errors) matches = dataRouterState.matches;
726 else if (parentMatches.length === 0 && !dataRouterState.initialized && dataRouterState.matches.length > 0) matches = dataRouterState.matches;
727 else return null;
728 }
729 let renderedMatches = matches;
730 let errors = dataRouterState?.errors;
731 if (errors != null) {
732 let errorIndex = renderedMatches.findIndex((m) => m.route.id && errors?.[m.route.id] !== void 0);
733 invariant(errorIndex >= 0, `Could not find a matching route for errors on route IDs: ${Object.keys(errors).join(",")}`);
734 renderedMatches = renderedMatches.slice(0, Math.min(renderedMatches.length, errorIndex + 1));
735 }
736 let renderFallback = false;
737 let fallbackIndex = -1;
738 if (dataRouterOpts && dataRouterState) {
739 renderFallback = dataRouterState.renderFallback;
740 for (let i = 0; i < renderedMatches.length; i++) {
741 let match = renderedMatches[i];
742 if (match.route.HydrateFallback || match.route.hydrateFallbackElement) fallbackIndex = i;
743 if (match.route.id) {
744 let { loaderData, errors } = dataRouterState;
745 let needsToRunLoader = match.route.loader && !loaderData.hasOwnProperty(match.route.id) && (!errors || errors[match.route.id] === void 0);
746 if (match.route.lazy || needsToRunLoader) {
747 if (dataRouterOpts.isStatic) renderFallback = true;
748 if (fallbackIndex >= 0) renderedMatches = renderedMatches.slice(0, fallbackIndex + 1);
749 else renderedMatches = [renderedMatches[0]];
750 break;
751 }
752 }
753 }
754 }
755 let onErrorHandler = dataRouterOpts?.onError;
756 let onError = dataRouterState && onErrorHandler ? (error, errorInfo) => {
757 onErrorHandler(error, {
758 location: dataRouterState.location,
759 params: dataRouterState.matches?.[0]?.params ?? {},
760 pattern: getRoutePattern(dataRouterState.matches),
761 errorInfo
762 });
763 } : void 0;
764 return renderedMatches.reduceRight((outlet, match, index) => {
765 let error;
766 let shouldRenderHydrateFallback = false;
767 let errorElement = null;
768 let hydrateFallbackElement = null;
769 if (dataRouterState) {
770 error = errors && match.route.id ? errors[match.route.id] : void 0;
771 errorElement = match.route.errorElement || defaultErrorElement;
772 if (renderFallback) {
773 if (fallbackIndex < 0 && index === 0) {
774 warningOnce("route-fallback", false, "No `HydrateFallback` element provided to render during initial hydration");
775 shouldRenderHydrateFallback = true;
776 hydrateFallbackElement = null;
777 } else if (fallbackIndex === index) {
778 shouldRenderHydrateFallback = true;
779 hydrateFallbackElement = match.route.hydrateFallbackElement || null;
780 }
781 }
782 }
783 let matches = parentMatches.concat(renderedMatches.slice(0, index + 1));
784 let getChildren = () => {
785 let children;
786 if (error) children = errorElement;
787 else if (shouldRenderHydrateFallback) children = hydrateFallbackElement;
788 else if (match.route.Component) children = /* @__PURE__ */ React$1.createElement(match.route.Component, null);
789 else if (match.route.element) children = match.route.element;
790 else children = outlet;
791 return /* @__PURE__ */ React$1.createElement(RenderedRoute, {
792 match,
793 routeContext: {
794 outlet,
795 matches,
796 isDataRoute: dataRouterState != null
797 },
798 children
799 });
800 };
801 return dataRouterState && (match.route.ErrorBoundary || match.route.errorElement || index === 0) ? /* @__PURE__ */ React$1.createElement(RenderErrorBoundary, {
802 location: dataRouterState.location,
803 revalidation: dataRouterState.revalidation,
804 component: errorElement,
805 error,
806 children: getChildren(),
807 routeContext: {
808 outlet: null,
809 matches,
810 isDataRoute: true
811 },
812 onError
813 }) : getChildren();
814 }, null);
815}
816function getDataRouterConsoleError(hookName) {
817 return `${hookName} must be used within a data router. See https://reactrouter.com/en/main/routers/picking-a-router.`;
818}
819function useDataRouterContext(hookName) {
820 let ctx = React$1.useContext(DataRouterContext);
821 invariant(ctx, getDataRouterConsoleError(hookName));
822 return ctx;
823}
824function useDataRouterState(hookName) {
825 let state = React$1.useContext(DataRouterStateContext);
826 invariant(state, getDataRouterConsoleError(hookName));
827 return state;
828}
829function useDataRouterFetchers(hookName) {
830 let fetchers = React$1.useContext(FetchersContext);
831 invariant(fetchers, getDataRouterConsoleError(hookName));
832 return fetchers;
833}
834function useDataRouterData(hookName) {
835 let data = React$1.useContext(DataRouterDataContext);
836 invariant(data, getDataRouterConsoleError(hookName));
837 return data;
838}
839function useDataRouterNavigation(hookName) {
840 let navigation = React$1.useContext(DataRouterNavigationContext);
841 invariant(navigation, getDataRouterConsoleError(hookName));
842 return navigation;
843}
844function useCurrentRouteId(hookName) {
845 let routeId = React$1.useContext(RouteIdContext);
846 invariant(routeId, `${hookName} can only be used on routes that contain a unique "id"`);
847 return routeId;
848}
849/**
850* Returns the current {@link Navigation}, defaulting to an "idle" navigation
851* when no navigation is in progress. You can use this to render pending UI
852* (like a global spinner) or read [`FormData`](https://developer.mozilla.org/en-US/docs/Web/API/FormData)
853* from a form navigation.
854*
855* @example
856* import { useNavigation } from "react-router";
857*
858* function SomeComponent() {
859* let navigation = useNavigation();
860* navigation.state;
861* navigation.formData;
862* // etc.
863* }
864*
865* @public
866* @category Hooks
867* @mode framework
868* @mode data
869* @returns The current {@link Navigation} object
870*/
871function useNavigation() {
872 let { navigation } = useDataRouterNavigation("useNavigation");
873 return React$1.useMemo(() => {
874 let { matches, historyAction, ...rest } = navigation;
875 return rest;
876 }, [navigation]);
877}
878/**
879* Revalidate the data on the page for reasons outside of normal data mutations
880* like [`Window` focus](https://developer.mozilla.org/en-US/docs/Web/API/Window/focus_event)
881* or polling on an interval.
882*
883* Note that page data is already revalidated automatically after actions.
884* If you find yourself using this for normal CRUD operations on your data in
885* response to user interactions, you're probably not taking advantage of the
886* other APIs like {@link useFetcher}, {@link Form}, {@link useSubmit} that do
887* this automatically.
888*
889* @example
890* import { useRevalidator } from "react-router";
891*
892* function WindowFocusRevalidator() {
893* const revalidator = useRevalidator();
894*
895* useFakeWindowFocus(() => {
896* revalidator.revalidate();
897* });
898*
899* return (
900* <div hidden={revalidator.state === "idle"}>
901* Revalidating...
902* </div>
903* );
904* }
905*
906* @public
907* @category Hooks
908* @mode framework
909* @mode data
910* @returns An object with a `revalidate` function and the current revalidation
911* `state`
912*/
913function useRevalidator() {
914 let dataRouterContext = useDataRouterContext("useRevalidator");
915 let { revalidation } = useDataRouterNavigation("useRevalidator");
916 let revalidate = React$1.useCallback(async () => {
917 await dataRouterContext.router.revalidate();
918 }, [dataRouterContext.router]);
919 return React$1.useMemo(() => ({
920 revalidate,
921 state: revalidation
922 }), [revalidate, revalidation]);
923}
924/**
925* Returns the active route matches, useful for accessing `loaderData` for
926* parent/child routes or the route [`handle`](../../start/framework/route-module#handle)
927* property
928*
929* Pairing the route `handle` with `useMatches` gets very powerful since you can put
930* whatever you want on a route handle and have access to `useMatches` anywhere.
931* Please see the [handle](../../how-to/using-handle) documentation for an example
932* of breadcrumbs via `useMatches`/`handle`.
933*
934* ```tsx
935* import { useMatches } from "react-router";
936*
937* function SomeComponent() {
938* const matches = useMatches();
939* // matches[i].id // route id
940* // matches[i].pathname // the portion of the URL the route matched
941* // matches[i].params // the parsed params from the URL
942* // matches[i].loaderData // the data from the loader
943* // matches[i].handle // the route handle with any app specific data
944* }
945* ```
946*
947* <docs-info>useMatches only works with a data router like `createBrowserRouter`,
948* since they know the full route tree up front and can provide all of the current
949* matches. Additionally, `useMatches` will not match down into any descendant route
950* trees since the router isn't aware of the descendant routes.</docs-info>
951*
952* @public
953* @category Hooks
954* @mode framework
955* @mode data
956* @returns An array of {@link UIMatch | UI matches} for the current route hierarchy
957*/
958function useMatches() {
959 let { matches } = useDataRouterState("useMatches");
960 let { loaderData } = useDataRouterData("useMatches");
961 return React$1.useMemo(() => matches.map((m) => convertRouteMatchToUiMatch(m, loaderData)), [matches, loaderData]);
962}
963/**
964* Returns the data from the closest route
965* [`loader`](../../start/framework/route-module#loader) or
966* [`clientLoader`](../../start/framework/route-module#clientloader).
967*
968* @example
969* import { useLoaderData } from "react-router";
970*
971* export async function loader() {
972* return await fakeDb.invoices.findAll();
973* }
974*
975* export default function Invoices() {
976* let invoices = useLoaderData<typeof loader>();
977* // ...
978* }
979*
980* @public
981* @category Hooks
982* @mode framework
983* @mode data
984* @returns The data returned from the route's [`loader`](../../start/framework/route-module#loader) or [`clientLoader`](../../start/framework/route-module#clientloader) function
985*/
986function useLoaderData() {
987 let data = useDataRouterData("useLoaderData");
988 let routeId = useCurrentRouteId("useLoaderData");
989 return data.loaderData[routeId];
990}
991/**
992* Returns the [`loader`](../../start/framework/route-module#loader) data for a
993* given route by route ID.
994*
995* Route IDs are created automatically. They are simply the path of the route file
996* relative to the app folder without the extension.
997*
998* | Route Filename | Route ID |
999* | ---------------------------- | ---------------------- |
1000* | `app/root.tsx` | `"root"` |
1001* | `app/routes/teams.tsx` | `"routes/teams"` |
1002* | `app/whatever/teams.$id.tsx` | `"whatever/teams.$id"` |
1003*
1004* @example
1005* import { useRouteLoaderData } from "react-router";
1006*
1007* function SomeComponent() {
1008* const { user } = useRouteLoaderData("root");
1009* }
1010*
1011* // You can also specify your own route ID's manually in your routes.ts file:
1012* route("/", "containers/app.tsx", { id: "app" })
1013* useRouteLoaderData("app");
1014*
1015* @public
1016* @category Hooks
1017* @mode framework
1018* @mode data
1019* @param routeId The ID of the route to return loader data from
1020* @returns The data returned from the specified route's [`loader`](../../start/framework/route-module#loader)
1021* function, or `undefined` if not found
1022*/
1023function useRouteLoaderData(routeId) {
1024 return useDataRouterData("useRouteLoaderData").loaderData[routeId];
1025}
1026/**
1027* Returns the [`action`](../../start/framework/route-module#action) data from
1028* the most recent `POST` navigation form submission or `undefined` if there
1029* hasn't been one.
1030*
1031* @example
1032* import { Form, useActionData } from "react-router";
1033*
1034* export async function action({ request }) {
1035* const body = await request.formData();
1036* const name = body.get("visitorsName");
1037* return { message: `Hello, ${name}` };
1038* }
1039*
1040* export default function Invoices() {
1041* const data = useActionData();
1042* return (
1043* <Form method="post">
1044* <input type="text" name="visitorsName" />
1045* {data ? data.message : "Waiting..."}
1046* </Form>
1047* );
1048* }
1049*
1050* @public
1051* @category Hooks
1052* @mode framework
1053* @mode data
1054* @returns The data returned from the route's [`action`](../../start/framework/route-module#action)
1055* function, or `undefined` if no [`action`](../../start/framework/route-module#action)
1056* has been called
1057*/
1058function useActionData() {
1059 let data = useDataRouterData("useActionData");
1060 let routeId = useCurrentRouteId("useActionData");
1061 return data.actionData ? data.actionData[routeId] : void 0;
1062}
1063/**
1064* Accesses the error thrown during an
1065* [`action`](../../start/framework/route-module#action),
1066* [`loader`](../../start/framework/route-module#loader),
1067* or component render to be used in a route module
1068* [`ErrorBoundary`](../../start/framework/route-module#errorboundary).
1069*
1070* @example
1071* export function ErrorBoundary() {
1072* const error = useRouteError();
1073* return <div>{error.message}</div>;
1074* }
1075*
1076* @public
1077* @category Hooks
1078* @mode framework
1079* @mode data
1080* @returns The error that was thrown during route [loading](../../start/framework/route-module#loader),
1081* [`action`](../../start/framework/route-module#action) execution, or rendering
1082*/
1083function useRouteError() {
1084 let error = React$1.useContext(RouteErrorContext);
1085 let data = useDataRouterData("useRouteError");
1086 let routeId = useCurrentRouteId("useRouteError");
1087 if (error !== void 0) return error;
1088 return data.errors?.[routeId];
1089}
1090/**
1091* Returns the resolved promise value from the closest {@link Await | `<Await>`}.
1092*
1093* @example
1094* function SomeDescendant() {
1095* const value = useAsyncValue();
1096* // ...
1097* }
1098*
1099* // somewhere in your app
1100* <Await resolve={somePromise}>
1101* <SomeDescendant />
1102* </Await>;
1103*
1104* @public
1105* @category Hooks
1106* @mode framework
1107* @mode data
1108* @returns The resolved value from the nearest {@link Await} component
1109*/
1110function useAsyncValue() {
1111 let value = React$1.useContext(AwaitContext);
1112 return value && "status" in value && !("_tracked" in value) ? value.status === "fulfilled" ? value.value : void 0 : value?._data;
1113}
1114/**
1115* Returns the rejection value from the closest {@link Await | `<Await>`}.
1116*
1117* @example
1118* import { Await, useAsyncError } from "react-router";
1119*
1120* function ErrorElement() {
1121* const error = useAsyncError();
1122* return (
1123* <p>Uh Oh, something went wrong! {error.message}</p>
1124* );
1125* }
1126*
1127* // somewhere in your app
1128* <Await
1129* resolve={promiseThatRejects}
1130* errorElement={<ErrorElement />}
1131* />;
1132*
1133* @public
1134* @category Hooks
1135* @mode framework
1136* @mode data
1137* @returns The error that was thrown in the nearest {@link Await} component
1138*/
1139function useAsyncError() {
1140 let value = React$1.useContext(AwaitContext);
1141 return value && "status" in value && !("_tracked" in value) ? value.status === "rejected" ? value.reason : void 0 : value?._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 let activeBlockerKey = React$1.useRef("");
1274 let activeBlockerRouter = React$1.useRef(null);
1275 React$1.useEffect(() => {
1276 let key = String(++blockerId);
1277 activeBlockerKey.current = key;
1278 activeBlockerRouter.current = router;
1279 setBlockerKey(key);
1280 return () => {
1281 activeBlockerKey.current = "";
1282 activeBlockerRouter.current = null;
1283 router.deleteBlocker(key);
1284 };
1285 }, [router]);
1286 React$1.useLayoutEffect(() => {
1287 if (blockerKey !== "" && blockerKey === activeBlockerKey.current && router === activeBlockerRouter.current) router.getBlocker(blockerKey, blockerFunction);
1288 }, [
1289 router,
1290 blockerKey,
1291 blockerFunction
1292 ]);
1293 return blockerKey && state.blockers.has(blockerKey) ? state.blockers.get(blockerKey) : IDLE_BLOCKER;
1294}
1295function useNavigateStable() {
1296 let { router } = useDataRouterContext("useNavigate");
1297 let id = useCurrentRouteId("useNavigate");
1298 let activeRef = React$1.useRef(false);
1299 React$1.useLayoutEffect(() => {
1300 activeRef.current = true;
1301 });
1302 return React$1.useCallback(async (to, options = {}) => {
1303 warning(activeRef.current, navigateEffectWarning);
1304 if (!activeRef.current) return;
1305 if (typeof to === "number") await router.navigate(to);
1306 else await router.navigate(to, {
1307 fromRouteId: id,
1308 ...options
1309 });
1310 }, [router, id]);
1311}
1312const alreadyWarned = {};
1313function warningOnce(key, cond, message) {
1314 if (!cond && !alreadyWarned[key]) {
1315 alreadyWarned[key] = true;
1316 warning(false, message);
1317 }
1318}
1319/**
1320* Returns the current route's `handle`, `loaderData`, and `actionData`, or
1321* those of a matched route identified by `routeId`.
1322*
1323* Omit `routeId` to read the current route. Pass a route ID to infer the
1324* fields from registered route module types. Without an ID, the fields
1325* are typed as `unknown`.
1326*
1327* @example
1328* import { unstable_useRoute as useRoute } from "react-router";
1329*
1330* let currentRoute = useRoute();
1331* let rootRoute = useRoute("root");
1332*
1333* // A registered non-root route may not currently be matched:
1334* let dashboard = useRoute("routes/dashboard");
1335* if (dashboard) {
1336* console.log(dashboard.handle, dashboard.loaderData);
1337* }
1338*
1339* @name unstable_useRoute
1340* @public
1341* @category Hooks
1342* @mode framework
1343* @mode data
1344* @param args An optional route ID. Omit it to read the current route.
1345* @returns An object with the route's `handle`, `loaderData`, and
1346* `actionData`, or `undefined` if the specified route is not matched.
1347* Individual fields can be `undefined` when the handle or data is unavailable.
1348*/
1349function useRoute(...args) {
1350 const currentRouteId = useCurrentRouteId("useRoute");
1351 const id = args[0] ?? currentRouteId;
1352 const state = useDataRouterState("useRoute");
1353 const data = useDataRouterData("useRoute");
1354 const route = state.matches.find(({ route }) => route.id === id);
1355 if (route === void 0) return void 0;
1356 return {
1357 handle: route.route.handle,
1358 loaderData: data.loaderData[id],
1359 actionData: data.actionData?.[id]
1360 };
1361}
1362function toRouterStateMatch(match) {
1363 return {
1364 id: match.route.id,
1365 pathname: match.pathname,
1366 params: match.params,
1367 handle: match.route.handle
1368 };
1369}
1370/**
1371* A unified hook for reading router state: current (`active`) and in-flight
1372* (`pending`) locations, search params, params, matches, and navigation type.
1373*
1374* This hook consolidates the information you used to get from {@link useLocation},
1375* {@link useSearchParams}, {@link useParams}, {@link useMatches}, {@link useNavigation},
1376* and {@link useNavigationType} into a single hook.
1377*
1378*
1379* @example
1380* import { unstable_useRouterState as useRouterState } from "react-router";
1381*
1382* let { active, pending } = useRouterState();
1383*
1384* // Active is always populated with the current location
1385* active.location; // replaces `useLocation()`
1386* active.searchParams; // replaces `useSearchParams()[0]`
1387* active.params; // replaces `useParams()`
1388* active.matches; // replaces `useMatches()`
1389* active.type; // replaces `useNavigationType()`
1390*
1391* // Pending is only populated during a navigation
1392* pending.location; // replaces `useNavigation().location`
1393* pending.searchParams; // equivalent to `new URLSearchParams(useNavigation().search)`
1394* pending.params; // Not directly accessible today
1395* pending.matches; // Not directly accessible today
1396* pending.type; // Not directly accessible today
1397* pending.state; // replaces `useNavigation().state`
1398* pending.formMethod; // replaces useNavigation().formMethod
1399* pending.formAction; // replaces useNavigation().formAction
1400* pending.formEncType; // replaces useNavigation().formEncType
1401* pending.formData; // replaces useNavigation().formData
1402* pending.json; // replaces useNavigation().json
1403* pending.text; // replaces useNavigation().text
1404*
1405* @name unstable_useRouterState
1406* @public
1407* @category Hooks
1408* @mode framework
1409* @mode data
1410* @returns The current router state with `active` and `pending` variants
1411*/
1412function useRouterState() {
1413 let { location, historyAction: type, matches } = useDataRouterState("unstable_useRouterState");
1414 let { navigation } = useDataRouterNavigation("unstable_useRouterState");
1415 let active = React$1.useMemo(() => ({
1416 type,
1417 location,
1418 searchParams: new URLSearchParams(location.search),
1419 params: matches[matches.length - 1]?.params ?? {},
1420 matches: matches.map((m) => toRouterStateMatch(m))
1421 }), [
1422 location,
1423 matches,
1424 type
1425 ]);
1426 let pending = React$1.useMemo(() => {
1427 if (navigation.state === "idle") return null;
1428 let shared = {
1429 type: navigation.historyAction,
1430 location: navigation.location,
1431 searchParams: new URLSearchParams(navigation.location.search),
1432 params: navigation.matches[navigation.matches.length - 1]?.params ?? {},
1433 matches: navigation.matches.map((m) => toRouterStateMatch(m))
1434 };
1435 return navigation.state === "loading" ? {
1436 ...shared,
1437 state: "loading",
1438 formMethod: navigation.formMethod,
1439 formAction: navigation.formAction,
1440 formEncType: navigation.formEncType,
1441 formData: navigation.formData,
1442 json: navigation.json,
1443 text: navigation.text
1444 } : {
1445 ...shared,
1446 state: "submitting",
1447 formMethod: navigation.formMethod,
1448 formAction: navigation.formAction,
1449 formEncType: navigation.formEncType,
1450 formData: navigation.formData,
1451 json: navigation.json,
1452 text: navigation.text
1453 };
1454 }, [navigation]);
1455 return React$1.useMemo(() => ({
1456 active,
1457 pending
1458 }), [active, pending]);
1459}
1460//#endregion
1461export { _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 };