UNPKG

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