UNPKG

49.7 kBJavaScriptView Raw
1/**
2 * react-router v8.5.2
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 { ABSOLUTE_URL_REGEX } from "../router/url.js";
12import { createBrowserHistory, createHashHistory, createPath, invariant, warning } from "../router/history.js";
13import { validateDocumentNavigationTarget } from "../router/navigation.js";
14import { ErrorResponseImpl, SUPPORTED_ERROR_TYPES, defaultMapRouteProperties, joinPaths, matchPath, parseToInfo, resolveTo, stripBasename } from "../router/utils.js";
15import { IDLE_FETCHER, createRouter } from "../router/router.js";
16import { DataRouterNavigationContext, NavigationContext, RouteContext, ViewTransitionContext } from "../context.js";
17import { useBlocker, useCurrentRouteId, useDataRouterContext, useDataRouterFetchers, useDataRouterState, useHref, useLocation, useMatches, useNavigate, useNavigation, useResolvedPath } from "../hooks.js";
18import { escapeHtml } from "./ssr/markup.js";
19import { FrameworkContext, PrefetchPageLinks, mergeRefs, usePrefetchBehavior } from "./ssr/components.js";
20import { Router, hydrationRouteProperties } from "../components.js";
21import { createSearchParams, getFormSubmissionInfo, getSearchParamsForLocation, shouldProcessLinkClick } from "./dom.js";
22import * as React$1 from "react";
23//#region lib/dom/lib.tsx
24const isBrowser = typeof window !== "undefined" && typeof window.document !== "undefined" && typeof window.document.createElement !== "undefined";
25try {
26 if (isBrowser) window.__reactRouterVersion = "8";
27} catch {}
28/**
29* Create a new {@link DataRouter| data router} that manages the application
30* path via [`history.pushState`](https://developer.mozilla.org/en-US/docs/Web/API/History/pushState)
31* and [`history.replaceState`](https://developer.mozilla.org/en-US/docs/Web/API/History/replaceState).
32*
33* Data Routers should not be held in React state. You should create your router
34* once outside of the React tree and pass it to {@link RouterProvider | `<RouterProvider>`}.
35* You can use `patchRoutesOnNavigation` to add additional routes programmatically.
36*
37* @public
38* @category Data Routers
39* @mode data
40* @param routes Application routes
41* @param opts Options
42* @param {DOMRouterOpts.basename} opts.basename n/a
43* @param {DOMRouterOpts.dataStrategy} opts.dataStrategy n/a
44* @param {DOMRouterOpts.future} opts.future n/a
45* @param {DOMRouterOpts.getContext} opts.getContext n/a
46* @param {DOMRouterOpts.hydrationData} opts.hydrationData n/a
47* @param {DOMRouterOpts.instrumentations} opts.instrumentations n/a
48* @param {DOMRouterOpts.patchRoutesOnNavigation} opts.patchRoutesOnNavigation n/a
49* @param {DOMRouterOpts.window} opts.window n/a
50* @returns An initialized {@link DataRouter| data router} to pass to {@link RouterProvider | `<RouterProvider>`}
51*/
52function createBrowserRouter(routes, opts) {
53 return createRouter({
54 basename: opts?.basename,
55 getContext: opts?.getContext,
56 future: opts?.future,
57 history: createBrowserHistory({ window: opts?.window }),
58 hydrationData: opts?.hydrationData || parseHydrationData(),
59 routes,
60 mapRouteProperties: defaultMapRouteProperties,
61 hydrationRouteProperties,
62 dataStrategy: opts?.dataStrategy,
63 patchRoutesOnNavigation: opts?.patchRoutesOnNavigation,
64 window: opts?.window,
65 instrumentations: opts?.instrumentations
66 }).initialize();
67}
68/**
69* Create a new {@link DataRouter| data router} that manages the application
70* path via the URL [`hash`](https://developer.mozilla.org/en-US/docs/Web/API/URL/hash).
71*
72* Data Routers should not be held in React state. You should create your router
73* once outside of the React tree and pass it to {@link RouterProvider | `<RouterProvider>`}.
74* You can use `patchRoutesOnNavigation` to add additional routes programmatically.
75*
76* @public
77* @category Data Routers
78* @mode data
79* @param routes Application routes
80* @param opts Options
81* @param {DOMRouterOpts.basename} opts.basename n/a
82* @param {DOMRouterOpts.future} opts.future n/a
83* @param {DOMRouterOpts.getContext} opts.getContext n/a
84* @param {DOMRouterOpts.hydrationData} opts.hydrationData n/a
85* @param {DOMRouterOpts.instrumentations} opts.instrumentations n/a
86* @param {DOMRouterOpts.dataStrategy} opts.dataStrategy n/a
87* @param {DOMRouterOpts.patchRoutesOnNavigation} opts.patchRoutesOnNavigation n/a
88* @param {DOMRouterOpts.window} opts.window n/a
89* @returns An initialized {@link DataRouter| data router} to pass to {@link RouterProvider | `<RouterProvider>`}
90*/
91function createHashRouter(routes, opts) {
92 return createRouter({
93 basename: opts?.basename,
94 getContext: opts?.getContext,
95 future: opts?.future,
96 history: createHashHistory({ window: opts?.window }),
97 hydrationData: opts?.hydrationData || parseHydrationData(),
98 routes,
99 mapRouteProperties: defaultMapRouteProperties,
100 hydrationRouteProperties,
101 dataStrategy: opts?.dataStrategy,
102 patchRoutesOnNavigation: opts?.patchRoutesOnNavigation,
103 window: opts?.window,
104 instrumentations: opts?.instrumentations
105 }).initialize();
106}
107function parseHydrationData() {
108 let state = window?.__staticRouterHydrationData;
109 if (state && state.errors) state = {
110 ...state,
111 errors: deserializeErrors(state.errors)
112 };
113 return state;
114}
115function deserializeErrors(errors) {
116 if (!errors) return null;
117 let entries = Object.entries(errors);
118 let serialized = {};
119 for (let [key, val] of entries) if (val && val.__type === "RouteErrorResponse") serialized[key] = new ErrorResponseImpl(val.status, val.statusText, val.data, val.internal === true);
120 else if (val && val.__type === "Error") {
121 if (typeof val.__subType === "string" && SUPPORTED_ERROR_TYPES.includes(val.__subType)) {
122 let ErrorConstructor = window[val.__subType];
123 if (typeof ErrorConstructor === "function") try {
124 let error = new ErrorConstructor(val.message);
125 error.stack = "";
126 serialized[key] = error;
127 } catch {}
128 }
129 if (serialized[key] == null) {
130 let error = new Error(val.message);
131 error.stack = "";
132 serialized[key] = error;
133 }
134 } else serialized[key] = val;
135 return serialized;
136}
137/**
138* A declarative {@link Router | `<Router>`} using the browser [`History`](https://developer.mozilla.org/en-US/docs/Web/API/History)
139* API for client-side routing.
140*
141* @public
142* @category Declarative Routers
143* @mode declarative
144* @param props Props
145* @param {BrowserRouterProps.basename} props.basename n/a
146* @param {BrowserRouterProps.children} props.children n/a
147* @param {BrowserRouterProps.useTransitions} props.useTransitions n/a
148* @param {BrowserRouterProps.window} props.window n/a
149* @returns A declarative {@link Router | `<Router>`} using the browser [`History`](https://developer.mozilla.org/en-US/docs/Web/API/History)
150* API for client-side routing.
151*/
152function BrowserRouter({ basename, children, useTransitions, window }) {
153 let historyRef = React$1.useRef(null);
154 if (historyRef.current == null) historyRef.current = createBrowserHistory({
155 window,
156 v5Compat: true
157 });
158 let history = historyRef.current;
159 let [state, setStateImpl] = React$1.useState({
160 action: history.action,
161 location: history.location
162 });
163 let setState = React$1.useCallback((newState) => {
164 if (useTransitions === false) setStateImpl(newState);
165 else React$1.startTransition(() => setStateImpl(newState));
166 }, [useTransitions]);
167 React$1.useLayoutEffect(() => history.listen(setState), [history, setState]);
168 return /* @__PURE__ */ React$1.createElement(Router, {
169 basename,
170 children,
171 location: state.location,
172 navigationType: state.action,
173 navigator: history,
174 useTransitions
175 });
176}
177/**
178* A declarative {@link Router | `<Router>`} that stores the location in the
179* [`hash`](https://developer.mozilla.org/en-US/docs/Web/API/URL/hash) portion
180* of the URL so it is not sent to the server.
181*
182* @public
183* @category Declarative Routers
184* @mode declarative
185* @param props Props
186* @param {HashRouterProps.basename} props.basename n/a
187* @param {HashRouterProps.children} props.children n/a
188* @param {HashRouterProps.useTransitions} props.useTransitions n/a
189* @param {HashRouterProps.window} props.window n/a
190* @returns A declarative {@link Router | `<Router>`} using the URL [`hash`](https://developer.mozilla.org/en-US/docs/Web/API/URL/hash)
191* for client-side routing.
192*/
193function HashRouter({ basename, children, useTransitions, window }) {
194 let historyRef = React$1.useRef(null);
195 if (historyRef.current == null) historyRef.current = createHashHistory({
196 window,
197 v5Compat: true
198 });
199 let history = historyRef.current;
200 let [state, setStateImpl] = React$1.useState({
201 action: history.action,
202 location: history.location
203 });
204 let setState = React$1.useCallback((newState) => {
205 if (useTransitions === false) setStateImpl(newState);
206 else React$1.startTransition(() => setStateImpl(newState));
207 }, [useTransitions]);
208 React$1.useLayoutEffect(() => history.listen(setState), [history, setState]);
209 return /* @__PURE__ */ React$1.createElement(Router, {
210 basename,
211 children,
212 location: state.location,
213 navigationType: state.action,
214 navigator: history,
215 useTransitions
216 });
217}
218/**
219* A declarative {@link Router | `<Router>`} that accepts a pre-instantiated
220* `history` object.
221* It's important to note that using your own `history` object is highly discouraged
222* and may add two versions of the `history` library to your bundles unless you use
223* the same version of the `history` library that React Router uses internally.
224*
225* @name unstable_HistoryRouter
226* @public
227* @category Declarative Routers
228* @mode declarative
229* @param props Props
230* @param {HistoryRouterProps.basename} props.basename n/a
231* @param {HistoryRouterProps.children} props.children n/a
232* @param {HistoryRouterProps.history} props.history n/a
233* @param {HistoryRouterProps.useTransitions} props.useTransitions n/a
234* @returns A declarative {@link Router | `<Router>`} using the provided history
235* implementation for client-side routing.
236*/
237function HistoryRouter({ basename, children, history, useTransitions }) {
238 let [state, setStateImpl] = React$1.useState({
239 action: history.action,
240 location: history.location
241 });
242 let setState = React$1.useCallback((newState) => {
243 if (useTransitions === false) setStateImpl(newState);
244 else React$1.startTransition(() => setStateImpl(newState));
245 }, [useTransitions]);
246 React$1.useLayoutEffect(() => history.listen(setState), [history, setState]);
247 return /* @__PURE__ */ React$1.createElement(Router, {
248 basename,
249 children,
250 location: state.location,
251 navigationType: state.action,
252 navigator: history,
253 useTransitions
254 });
255}
256HistoryRouter.displayName = "unstable_HistoryRouter";
257/**
258* A progressively enhanced [`<a href>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a)
259* wrapper to enable navigation with client-side routing.
260*
261* @example
262* import { Link } from "react-router";
263*
264* <Link to="/dashboard">Dashboard</Link>;
265*
266* <Link
267* to={{
268* pathname: "/some/path",
269* search: "?query=string",
270* hash: "#hash",
271* }}
272* />;
273*
274* @public
275* @category Components
276* @param {LinkProps.discover} props.discover [modes: framework] n/a
277* @param {LinkProps.prefetch} props.prefetch [modes: framework] n/a
278* @param {LinkProps.preventScrollReset} props.preventScrollReset [modes: framework, data] n/a
279* @param {LinkProps.relative} props.relative n/a
280* @param {LinkProps.reloadDocument} props.reloadDocument n/a
281* @param {LinkProps.replace} props.replace n/a
282* @param {LinkProps.state} props.state n/a
283* @param {LinkProps.to} props.to n/a
284* @param {LinkProps.viewTransition} props.viewTransition [modes: framework, data] n/a
285* @param {LinkProps.defaultShouldRevalidate} props.defaultShouldRevalidate n/a
286* @param {LinkProps.mask} props.mask [modes: framework, data] n/a
287*/
288const Link = React$1.forwardRef(function LinkWithRef({ onClick, discover = "render", prefetch = "none", relative, reloadDocument, replace, mask, state, target, to, preventScrollReset, viewTransition, defaultShouldRevalidate, ...rest }, forwardedRef) {
289 let { basename, navigator, useTransitions } = React$1.useContext(NavigationContext);
290 let isAbsolute = typeof to === "string" && ABSOLUTE_URL_REGEX.test(to);
291 let parsed = parseToInfo(to, basename);
292 to = parsed.to;
293 let href = useHref(to, { relative });
294 let location = useLocation();
295 let maskedHref = null;
296 if (mask) {
297 let resolved = resolveTo(mask, [], location.mask ? location.mask.pathname : "/", true);
298 if (basename !== "/") resolved.pathname = resolved.pathname === "/" ? basename : joinPaths([basename, resolved.pathname]);
299 maskedHref = navigator.createHref(resolved);
300 }
301 let [shouldPrefetch, prefetchRef, prefetchHandlers] = usePrefetchBehavior(prefetch, rest);
302 let internalOnClick = useLinkClickHandler(to, {
303 replace,
304 mask,
305 state,
306 target,
307 preventScrollReset,
308 relative,
309 viewTransition,
310 defaultShouldRevalidate,
311 useTransitions
312 });
313 function handleClick(event) {
314 if (onClick) onClick(event);
315 if (!event.defaultPrevented) internalOnClick(event);
316 }
317 let isSpaLink = !(parsed.isExternal || reloadDocument);
318 let renderedHref = (isSpaLink ? maskedHref : void 0) || parsed.absoluteURL || href;
319 validateDocumentNavigationTarget(renderedHref);
320 let link = /* @__PURE__ */ React$1.createElement("a", {
321 ...rest,
322 ...prefetchHandlers,
323 href: renderedHref,
324 onClick: isSpaLink ? handleClick : onClick,
325 ref: mergeRefs(forwardedRef, prefetchRef),
326 target,
327 "data-discover": !isAbsolute && discover === "render" ? "true" : void 0
328 });
329 return shouldPrefetch && !isAbsolute ? /* @__PURE__ */ React$1.createElement(React$1.Fragment, null, link, /* @__PURE__ */ React$1.createElement(PrefetchPageLinks, { page: href })) : link;
330});
331Link.displayName = "Link";
332/**
333* Wraps {@link Link | `<Link>`} with additional props for styling active and
334* pending states.
335*
336* - Automatically applies classes to the link based on its `active` and `pending`
337* states, see {@link NavLinkProps.className}
338* - Note that `pending` is only available with Framework and Data modes.
339* - Automatically applies `aria-current="page"` to the link when the link is active.
340* See [`aria-current`](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-current)
341* on MDN.
342* - States are additionally available through the className, style, and children
343* render props. See {@link NavLinkRenderProps}.
344*
345* @example
346* <NavLink to="/message">Messages</NavLink>
347*
348* // Using render props
349* <NavLink
350* to="/messages"
351* className={({ isActive, isPending }) =>
352* isPending ? "pending" : isActive ? "active" : ""
353* }
354* >
355* Messages
356* </NavLink>
357*
358* @public
359* @category Components
360* @param {NavLinkProps.caseSensitive} props.caseSensitive n/a
361* @param {NavLinkProps.children} props.children n/a
362* @param {NavLinkProps.className} props.className n/a
363* @param {NavLinkProps.discover} props.discover [modes: framework] n/a
364* @param {NavLinkProps.end} props.end n/a
365* @param {NavLinkProps.prefetch} props.prefetch [modes: framework] n/a
366* @param {NavLinkProps.preventScrollReset} props.preventScrollReset [modes: framework, data] n/a
367* @param {NavLinkProps.relative} props.relative n/a
368* @param {NavLinkProps.reloadDocument} props.reloadDocument n/a
369* @param {NavLinkProps.replace} props.replace n/a
370* @param {NavLinkProps.state} props.state n/a
371* @param {NavLinkProps.style} props.style n/a
372* @param {NavLinkProps.to} props.to n/a
373* @param {NavLinkProps.viewTransition} props.viewTransition [modes: framework, data] n/a
374*/
375const NavLink = React$1.forwardRef(function NavLinkWithRef({ "aria-current": ariaCurrentProp = "page", caseSensitive = false, className: classNameProp = "", end = false, style: styleProp, to, viewTransition, children, ...rest }, ref) {
376 let path = useResolvedPath(to, { relative: rest.relative });
377 let location = useLocation();
378 let routerNavigation = React$1.useContext(DataRouterNavigationContext);
379 let { navigator, basename } = React$1.useContext(NavigationContext);
380 let isTransitioning = routerNavigation != null && useViewTransitionState(path) && viewTransition === true;
381 let toPathname = navigator.encodeLocation ? navigator.encodeLocation(path).pathname : path.pathname;
382 let locationPathname = location.pathname;
383 let nextLocationPathname = routerNavigation?.navigation.location ? routerNavigation.navigation.location.pathname : null;
384 if (!caseSensitive) {
385 locationPathname = locationPathname.toLowerCase();
386 nextLocationPathname = nextLocationPathname ? nextLocationPathname.toLowerCase() : null;
387 toPathname = toPathname.toLowerCase();
388 }
389 if (nextLocationPathname && basename) nextLocationPathname = stripBasename(nextLocationPathname, basename) || nextLocationPathname;
390 const endSlashPosition = toPathname !== "/" && toPathname.endsWith("/") ? toPathname.length - 1 : toPathname.length;
391 let isActive = locationPathname === toPathname || !end && locationPathname.startsWith(toPathname) && locationPathname.charAt(endSlashPosition) === "/";
392 let isPending = nextLocationPathname != null && (nextLocationPathname === toPathname || !end && nextLocationPathname.startsWith(toPathname) && nextLocationPathname.charAt(endSlashPosition) === "/");
393 let renderProps = {
394 isActive,
395 isPending,
396 isTransitioning
397 };
398 let ariaCurrent = isActive ? ariaCurrentProp : void 0;
399 let className;
400 if (typeof classNameProp === "function") className = classNameProp(renderProps);
401 else className = [
402 classNameProp,
403 isActive ? "active" : null,
404 isPending ? "pending" : null,
405 isTransitioning ? "transitioning" : null
406 ].filter(Boolean).join(" ");
407 let style = typeof styleProp === "function" ? styleProp(renderProps) : styleProp;
408 return /* @__PURE__ */ React$1.createElement(Link, {
409 ...rest,
410 "aria-current": ariaCurrent,
411 className,
412 ref,
413 style,
414 to,
415 viewTransition
416 }, typeof children === "function" ? children(renderProps) : children);
417});
418NavLink.displayName = "NavLink";
419/**
420* A progressively enhanced HTML [`<form>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form)
421* that submits data to actions via [`fetch`](https://developer.mozilla.org/en-US/docs/Web/API/fetch),
422* activating pending states in {@link useNavigation} which enables advanced
423* user interfaces beyond a basic HTML [`<form>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form).
424* After a form's `action` completes, all data on the page is automatically
425* revalidated to keep the UI in sync with the data.
426*
427* Because it uses the HTML form API, server rendered pages are interactive at a
428* basic level before JavaScript loads. Instead of React Router managing the
429* submission, the browser manages the submission as well as the pending states
430* (like the spinning favicon). After JavaScript loads, React Router takes over
431* enabling web application user experiences.
432*
433* `Form` is most useful for submissions that should also change the URL or
434* otherwise add an entry to the browser history stack. For forms that shouldn't
435* manipulate the browser [`History`](https://developer.mozilla.org/en-US/docs/Web/API/History)
436* stack, use {@link FetcherWithComponents.Form | `<fetcher.Form>`}.
437*
438* @example
439* import { Form } from "react-router";
440*
441* function NewEvent() {
442* return (
443* <Form action="/events" method="post">
444* <input name="title" type="text" />
445* <input name="description" type="text" />
446* </Form>
447* );
448* }
449*
450* @public
451* @category Components
452* @mode framework
453* @mode data
454* @param {FormProps.action} action n/a
455* @param {FormProps.discover} discover n/a
456* @param {FormProps.encType} encType n/a
457* @param {FormProps.fetcherKey} fetcherKey n/a
458* @param {FormProps.method} method n/a
459* @param {FormProps.navigate} navigate n/a
460* @param {FormProps.preventScrollReset} preventScrollReset n/a
461* @param {FormProps.relative} relative n/a
462* @param {FormProps.reloadDocument} reloadDocument n/a
463* @param {FormProps.replace} replace n/a
464* @param {FormProps.state} state n/a
465* @param {FormProps.viewTransition} viewTransition n/a
466* @param {FormProps.defaultShouldRevalidate} defaultShouldRevalidate n/a
467* @returns A progressively enhanced [`<form>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form) component
468*/
469const Form = React$1.forwardRef(({ discover = "render", fetcherKey, navigate, reloadDocument, replace, state, method = "get", action, onSubmit, relative, preventScrollReset, viewTransition, defaultShouldRevalidate, ...props }, forwardedRef) => {
470 let { useTransitions } = React$1.useContext(NavigationContext);
471 let submit = useSubmit();
472 let formAction = useFormAction(action, { relative });
473 let formMethod = method.toLowerCase() === "get" ? "get" : "post";
474 let isAbsolute = typeof action === "string" && ABSOLUTE_URL_REGEX.test(action);
475 let submitHandler = (event) => {
476 onSubmit && onSubmit(event);
477 if (event.defaultPrevented) return;
478 event.preventDefault();
479 let submitter = event.nativeEvent.submitter;
480 let submitMethod = submitter?.getAttribute("formmethod") || method;
481 let doSubmit = () => submit(submitter || event.currentTarget, {
482 fetcherKey,
483 method: submitMethod,
484 navigate,
485 replace,
486 state,
487 relative,
488 preventScrollReset,
489 viewTransition,
490 defaultShouldRevalidate
491 });
492 if (useTransitions && navigate !== false) React$1.startTransition(() => doSubmit());
493 else doSubmit();
494 };
495 return /* @__PURE__ */ React$1.createElement("form", {
496 ref: forwardedRef,
497 method: formMethod,
498 action: formAction,
499 onSubmit: reloadDocument ? onSubmit : submitHandler,
500 ...props,
501 "data-discover": !isAbsolute && discover === "render" ? "true" : void 0
502 });
503});
504Form.displayName = "Form";
505/**
506* Emulates the browser's scroll restoration on location changes. Apps should only render one of these, right before the {@link Scripts} component.
507*
508* ```tsx
509* import { ScrollRestoration } from "react-router";
510*
511* export default function Root() {
512* return (
513* <html>
514* <body>
515* <ScrollRestoration />
516* <Scripts />
517* </body>
518* </html>
519* );
520* }
521* ```
522*
523* This component renders an inline `<script>` to prevent scroll flashing. The
524* `nonce` prop will be passed down to the script tag to allow CSP nonce usage.
525* If not provided in Framework Mode, it will default to any
526* {@link ServerRouter | `<ServerRouter nonce>`} prop.
527*
528* ```tsx
529* <ScrollRestoration nonce={cspNonce} />
530* ```
531*
532* @public
533* @category Components
534* @mode framework
535* @mode data
536* @param props Props
537* @param {ScrollRestorationProps.getKey} props.getKey n/a
538* @param {ScriptsProps.nonce} props.nonce n/a
539* @param {ScrollRestorationProps.storageKey} props.storageKey n/a
540* @returns A [`<script>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script)
541* tag that restores scroll positions on navigation.
542*/
543function ScrollRestoration({ getKey, storageKey, ...props }) {
544 let remixContext = React$1.useContext(FrameworkContext);
545 let { basename } = React$1.useContext(NavigationContext);
546 let location = useLocation();
547 let matches = useMatches();
548 useScrollRestoration({
549 getKey,
550 storageKey
551 });
552 let ssrKey = React$1.useMemo(() => {
553 if (!remixContext || !getKey) return null;
554 let userKey = getScrollRestorationKey(location, matches, basename, getKey);
555 return userKey !== location.key ? userKey : null;
556 }, []);
557 if (!remixContext || remixContext.isSpaMode) return null;
558 let restoreScroll = ((storageKey, restoreKey) => {
559 if (!window.history.state || !window.history.state.key) {
560 let key = Math.random().toString(32).slice(2);
561 window.history.replaceState({ key }, "");
562 }
563 try {
564 let storedY = JSON.parse(sessionStorage.getItem(storageKey) || "{}")[restoreKey || window.history.state.key];
565 if (typeof storedY === "number") window.scrollTo(0, storedY);
566 } catch (error) {
567 console.error(error);
568 try {
569 sessionStorage.removeItem(storageKey);
570 } catch {}
571 }
572 }).toString();
573 if (props.nonce == null && remixContext?.nonce) props.nonce = remixContext.nonce;
574 return /* @__PURE__ */ React$1.createElement("script", {
575 ...props,
576 suppressHydrationWarning: true,
577 dangerouslySetInnerHTML: { __html: `(${restoreScroll})(${escapeHtml(JSON.stringify(storageKey || SCROLL_RESTORATION_STORAGE_KEY))}, ${escapeHtml(JSON.stringify(ssrKey))})` }
578 });
579}
580ScrollRestoration.displayName = "ScrollRestoration";
581/**
582* Handles the click behavior for router {@link Link | `<Link>`} components.This
583* is useful if you need to create custom {@link Link | `<Link>`} components with
584* the same click behavior we use in our exported {@link Link | `<Link>`}.
585*
586* @public
587* @category Hooks
588* @param to The URL to navigate to, can be a string or a partial {@link Path}.
589* @param options Options
590* @param options.preventScrollReset Whether to prevent the scroll position from
591* being reset to the top of the viewport on completion of the navigation when
592* using the {@link ScrollRestoration} component. Defaults to `false`.
593* @param options.relative The {@link RelativeRoutingType | relative routing type}
594* to use for the link. Defaults to `"route"`.
595* @param options.replace Whether to replace the current [`History`](https://developer.mozilla.org/en-US/docs/Web/API/History)
596* entry instead of pushing a new one. Defaults to `false`.
597* @param options.state The state to add to the [`History`](https://developer.mozilla.org/en-US/docs/Web/API/History)
598* entry for this navigation. Defaults to `undefined`.
599* @param options.target The target attribute for the link. Defaults to `undefined`.
600* @param options.viewTransition **Deprecated.** Use React's
601* [`<ViewTransition>`](https://react.dev/reference/react/ViewTransition) component
602* instead. See the [migration guide](../../how-to/view-transitions).
603* @param options.defaultShouldRevalidate Specify the default revalidation
604* behavior for the navigation. When not specified, loaders revalidate
605* according to the router's standard revalidation behavior.
606* @param options.mask Masked location to display in the browser instead
607* of the router location. Defaults to `undefined`.
608* @param options.useTransitions Wraps the navigation in
609* [`React.startTransition`](https://react.dev/reference/react/startTransition)
610* for concurrent rendering. Defaults to `false`.
611* @returns A click handler function that can be used in a custom {@link Link} component.
612*/
613function useLinkClickHandler(to, { target, replace: replaceProp, mask, state, preventScrollReset, relative, viewTransition, defaultShouldRevalidate, useTransitions } = {}) {
614 let navigate = useNavigate();
615 let location = useLocation();
616 let path = useResolvedPath(to, { relative });
617 return React$1.useCallback((event) => {
618 if (shouldProcessLinkClick(event, target)) {
619 event.preventDefault();
620 let replace = replaceProp !== void 0 ? replaceProp : createPath(location) === createPath(path);
621 let doNavigate = () => navigate(to, {
622 replace,
623 mask,
624 state,
625 preventScrollReset,
626 relative,
627 viewTransition,
628 defaultShouldRevalidate
629 });
630 if (useTransitions) React$1.startTransition(() => doNavigate());
631 else doNavigate();
632 }
633 }, [
634 location,
635 navigate,
636 path,
637 replaceProp,
638 mask,
639 state,
640 target,
641 to,
642 preventScrollReset,
643 relative,
644 viewTransition,
645 defaultShouldRevalidate,
646 useTransitions
647 ]);
648}
649/**
650* Returns a tuple of the current URL's [`URLSearchParams`](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams)
651* and a function to update them. Setting the search params causes a navigation.
652*
653* ```tsx
654* import { useSearchParams } from "react-router";
655*
656* export function SomeComponent() {
657* const [searchParams, setSearchParams] = useSearchParams();
658* // ...
659* }
660* ```
661*
662* ### `setSearchParams` function
663*
664* The second element of the tuple is a function that can be used to update the
665* search params. It accepts the same types as `defaultInit` and will cause a
666* navigation to the new URL.
667*
668* ```tsx
669* let [searchParams, setSearchParams] = useSearchParams();
670*
671* // a search param string
672* setSearchParams("?tab=1");
673*
674* // a shorthand object
675* setSearchParams({ tab: "1" });
676*
677* // object keys can be arrays for multiple values on the key
678* setSearchParams({ brand: ["nike", "reebok"] });
679*
680* // an array of tuples
681* setSearchParams([["tab", "1"]]);
682*
683* // a `URLSearchParams` object
684* setSearchParams(new URLSearchParams("?tab=1"));
685* ```
686*
687* It also supports a function callback like React's
688* [`setState`](https://react.dev/reference/react/useState#setstate):
689*
690* ```tsx
691* setSearchParams((searchParams) => {
692* searchParams.set("tab", "2");
693* return searchParams;
694* });
695* ```
696*
697* <docs-warning>The function callback version of `setSearchParams` does not support
698* the [queueing](https://react.dev/reference/react/useState#setstate-parameters)
699* logic that React's `setState` implements. Multiple calls to `setSearchParams`
700* in the same tick will not build on the prior value. If you need this behavior,
701* you can use `setState` manually.</docs-warning>
702*
703* ### Notes
704*
705* Note that `searchParams` is a stable reference, so you can reliably use it
706* as a dependency in React's [`useEffect`](https://react.dev/reference/react/useEffect)
707* hooks.
708*
709* ```tsx
710* useEffect(() => {
711* console.log(searchParams.get("tab"));
712* }, [searchParams]);
713* ```
714*
715* However, this also means it's mutable. If you change the object without
716* calling `setSearchParams`, its values will change between renders if some
717* other state causes the component to re-render and URL will not reflect the
718* values.
719*
720* @public
721* @category Hooks
722* @param defaultInit
723* You can initialize the search params with a default value, though it **will
724* not** change the URL on the first render.
725*
726* ```tsx
727* // a search param string
728* useSearchParams("?tab=1");
729*
730* // a shorthand object
731* useSearchParams({ tab: "1" });
732*
733* // object keys can be arrays for multiple values on the key
734* useSearchParams({ brand: ["nike", "reebok"] });
735*
736* // an array of tuples
737* useSearchParams([["tab", "1"]]);
738*
739* // a `URLSearchParams` object
740* useSearchParams(new URLSearchParams("?tab=1"));
741* ```
742* @returns A tuple of the current [`URLSearchParams`](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams)
743* and a function to update them.
744*/
745function useSearchParams(defaultInit) {
746 warning(typeof URLSearchParams !== "undefined", "You cannot use the `useSearchParams` hook in a browser that does not support the URLSearchParams API. If you need to support Internet Explorer 11, we recommend you load a polyfill such as https://github.com/ungap/url-search-params.");
747 let defaultSearchParamsRef = React$1.useRef(createSearchParams(defaultInit));
748 let hasSetSearchParamsRef = React$1.useRef(false);
749 let location = useLocation();
750 let searchParams = React$1.useMemo(() => getSearchParamsForLocation(location.search, hasSetSearchParamsRef.current ? null : defaultSearchParamsRef.current), [location.search]);
751 let navigate = useNavigate();
752 return [searchParams, React$1.useCallback((nextInit, navigateOptions) => {
753 const newSearchParams = createSearchParams(typeof nextInit === "function" ? nextInit(new URLSearchParams(searchParams)) : nextInit);
754 hasSetSearchParamsRef.current = true;
755 navigate("?" + newSearchParams, navigateOptions);
756 }, [navigate, searchParams])];
757}
758let fetcherId = 0;
759let getUniqueFetcherId = () => `__${String(++fetcherId)}__`;
760/**
761* The imperative version of {@link Form | `<Form>`} that lets you submit a form
762* from code instead of a user interaction.
763*
764* The `viewTransition` submission option is deprecated. Use React's
765* [`<ViewTransition>`](https://react.dev/reference/react/ViewTransition) component
766* instead. See the [migration guide](../../how-to/view-transitions).
767*
768* @example
769* import { useSubmit } from "react-router";
770*
771* function SomeComponent() {
772* const submit = useSubmit();
773* return (
774* <Form onChange={(event) => submit(event.currentTarget)} />
775* );
776* }
777*
778* @public
779* @category Hooks
780* @mode framework
781* @mode data
782* @returns A function that can be called to submit a {@link Form} imperatively.
783*/
784function useSubmit() {
785 let { router } = useDataRouterContext("useSubmit");
786 let { basename } = React$1.useContext(NavigationContext);
787 let currentRouteId = useCurrentRouteId("useSubmit");
788 let routerFetch = router.fetch;
789 let routerNavigate = router.navigate;
790 return React$1.useCallback(async (target, options = {}) => {
791 let { action, method, encType, formData, body } = getFormSubmissionInfo(target, basename);
792 if (options.navigate === false) await routerFetch(options.fetcherKey || getUniqueFetcherId(), currentRouteId, options.action || action, {
793 defaultShouldRevalidate: options.defaultShouldRevalidate,
794 preventScrollReset: options.preventScrollReset,
795 relative: options.relative,
796 formData,
797 body,
798 formMethod: options.method || method,
799 formEncType: options.encType || encType,
800 flushSync: options.flushSync
801 });
802 else await routerNavigate(options.action || action, {
803 defaultShouldRevalidate: options.defaultShouldRevalidate,
804 preventScrollReset: options.preventScrollReset,
805 relative: options.relative,
806 formData,
807 body,
808 formMethod: options.method || method,
809 formEncType: options.encType || encType,
810 replace: options.replace,
811 state: options.state,
812 fromRouteId: currentRouteId,
813 flushSync: options.flushSync,
814 viewTransition: options.viewTransition
815 });
816 }, [
817 routerFetch,
818 routerNavigate,
819 basename,
820 currentRouteId
821 ]);
822}
823/**
824* Resolves the URL to the closest route in the component hierarchy instead of
825* the current URL of the app.
826*
827* This is used internally by {@link Form} to resolve the `action` to the closest
828* route, but can be used generically as well.
829*
830* ```ts
831* import { useFormAction } from "react-router";
832*
833* function SomeComponent() {
834* // closest route URL
835* let action = useFormAction();
836*
837* // closest route URL + "destroy"
838* let destroyAction = useFormAction("destroy");
839* }
840* ```
841*
842* <docs-info>This hook adds a `basename` if your app specifies one, so that it
843* can be used with raw `<form>` elements in a progressively enhanced way. If
844* you are using this to provide an `action` to `<Form>` or `fetcher.submit`, you
845* will need to remove the `basename` since both of those will prepend it
846* internally.</docs-info>
847*
848*
849* @public
850* @category Hooks
851* @mode framework
852* @mode data
853* @param action The action to append to the closest route URL. Defaults to the
854* closest route URL.
855* @param options Options
856* @param options.relative The relative routing type to use when resolving the
857* action. Defaults to `"route"`.
858* @returns The resolved action URL.
859*/
860function useFormAction(action, { relative } = {}) {
861 let { basename } = React$1.useContext(NavigationContext);
862 let routeContext = React$1.useContext(RouteContext);
863 invariant(routeContext, "useFormAction must be used inside a RouteContext");
864 let [match] = routeContext.matches.slice(-1);
865 let path = { ...useResolvedPath(action ? action : ".", { relative }) };
866 let location = useLocation();
867 if (action == null) {
868 path.search = location.search;
869 let params = new URLSearchParams(path.search);
870 let indexValues = params.getAll("index");
871 if (indexValues.some((v) => v === "")) {
872 params.delete("index");
873 indexValues.filter((v) => v).forEach((v) => params.append("index", v));
874 let qs = params.toString();
875 path.search = qs ? `?${qs}` : "";
876 }
877 }
878 if ((!action || action === ".") && match.route.index) path.search = path.search ? path.search.replace(/^\?/, "?index&") : "?index";
879 if (basename !== "/") path.pathname = path.pathname === "/" ? basename : joinPaths([basename, path.pathname]);
880 let formAction = createPath(path);
881 validateDocumentNavigationTarget(formAction);
882 return formAction;
883}
884/**
885* Useful for creating complex, dynamic user interfaces that require multiple,
886* concurrent data interactions without causing a navigation.
887*
888* Fetchers track their own, independent state and can be used to load data, submit
889* forms, and generally interact with [`action`](../../start/framework/route-module#action)
890* and [`loader`](../../start/framework/route-module#loader) functions.
891*
892* @example
893* import { useFetcher } from "react-router"
894*
895* function SomeComponent() {
896* let fetcher = useFetcher()
897*
898* // states are available on the fetcher
899* fetcher.state // "idle" | "loading" | "submitting"
900* fetcher.data // the data returned from the action or loader
901*
902* // render a form
903* <fetcher.Form method="post" />
904*
905* // load data
906* fetcher.load("/some/route")
907*
908* // submit data
909* fetcher.submit(someFormRef, { method: "post" })
910* fetcher.submit(someData, {
911* method: "post",
912* encType: "application/json"
913* })
914*
915* // reset fetcher
916* fetcher.reset()
917* }
918*
919* @public
920* @category Hooks
921* @mode framework
922* @mode data
923* @param options Options
924* @param options.key A unique key to identify the fetcher.
925*
926*
927* By default, `useFetcher` generates a unique fetcher scoped to that component.
928* If you want to identify a fetcher with your own key such that you can access
929* it from elsewhere in your app, you can do that with the `key` option:
930*
931* ```tsx
932* function SomeComp() {
933* let fetcher = useFetcher({ key: "my-key" })
934* // ...
935* }
936*
937* // Somewhere else
938* function AnotherComp() {
939* // this will be the same fetcher, sharing the state across the app
940* let fetcher = useFetcher({ key: "my-key" });
941* // ...
942* }
943* ```
944* @returns A {@link FetcherWithComponents} object that contains the fetcher's state, data, and components for submitting forms and loading data.
945*/
946function useFetcher({ key } = {}) {
947 let { router } = useDataRouterContext("useFetcher");
948 let fetchersContext = useDataRouterFetchers("useFetcher");
949 let routeId = useCurrentRouteId("useFetcher");
950 let defaultKey = React$1.useId();
951 let [fetcherKey, setFetcherKey] = React$1.useState(key || defaultKey);
952 if (key && key !== fetcherKey) setFetcherKey(key);
953 let { deleteFetcher, getFetcher, resetFetcher, fetch: routerFetch } = router;
954 React$1.useEffect(() => {
955 getFetcher(fetcherKey);
956 return () => deleteFetcher(fetcherKey);
957 }, [
958 deleteFetcher,
959 getFetcher,
960 fetcherKey
961 ]);
962 let load = React$1.useCallback(async (href, opts) => {
963 invariant(routeId, "No routeId available for fetcher.load()");
964 await routerFetch(fetcherKey, routeId, href, opts);
965 }, [
966 fetcherKey,
967 routeId,
968 routerFetch
969 ]);
970 let submitImpl = useSubmit();
971 let submit = React$1.useCallback(async (target, opts) => {
972 await submitImpl(target, {
973 ...opts,
974 navigate: false,
975 fetcherKey
976 });
977 }, [fetcherKey, submitImpl]);
978 let reset = React$1.useCallback((opts) => resetFetcher(fetcherKey, opts), [resetFetcher, fetcherKey]);
979 let FetcherForm = React$1.useMemo(() => {
980 let FetcherForm = React$1.forwardRef((props, ref) => {
981 return /* @__PURE__ */ React$1.createElement(Form, {
982 ...props,
983 navigate: false,
984 fetcherKey,
985 ref
986 });
987 });
988 FetcherForm.displayName = "fetcher.Form";
989 return FetcherForm;
990 }, [fetcherKey]);
991 let fetcher = fetchersContext.fetchers.get(fetcherKey) || IDLE_FETCHER;
992 let data = fetchersContext.fetcherData.get(fetcherKey);
993 return React$1.useMemo(() => ({
994 Form: FetcherForm,
995 submit,
996 load,
997 reset,
998 ...fetcher,
999 data
1000 }), [
1001 FetcherForm,
1002 submit,
1003 load,
1004 reset,
1005 fetcher,
1006 data
1007 ]);
1008}
1009/**
1010* Returns an array of all in-flight {@link Fetcher}s. This is useful for components
1011* throughout the app that didn't create the fetchers but want to use their submissions
1012* to participate in optimistic UI.
1013*
1014* @example
1015* import { useFetchers } from "react-router";
1016*
1017* function SomeComponent() {
1018* const fetchers = useFetchers();
1019* fetchers[0].formData; // FormData
1020* fetchers[0].state; // etc.
1021* // ...
1022* }
1023*
1024* @public
1025* @category Hooks
1026* @mode framework
1027* @mode data
1028* @returns An array of all in-flight {@link Fetcher}s, each with a unique `key`
1029* property.
1030*/
1031function useFetchers() {
1032 let { fetchers } = useDataRouterFetchers("useFetchers");
1033 return React$1.useMemo(() => Array.from(fetchers.entries()).map(([key, fetcher]) => ({
1034 ...fetcher,
1035 key
1036 })), [fetchers]);
1037}
1038const SCROLL_RESTORATION_STORAGE_KEY = "react-router-scroll-positions";
1039let savedScrollPositions = {};
1040function getScrollRestorationKey(location, matches, basename, getKey) {
1041 let key = null;
1042 if (getKey) if (basename !== "/") key = getKey({
1043 ...location,
1044 pathname: stripBasename(location.pathname, basename) || location.pathname
1045 }, matches);
1046 else key = getKey(location, matches);
1047 if (key == null) key = location.key;
1048 return key;
1049}
1050/**
1051* When rendered inside a {@link RouterProvider}, will restore scroll positions
1052* on navigations
1053*
1054* <!--
1055* Not marked `@public` because we only export as UNSAFE_ and therefore we don't
1056* maintain an .md file for this hook
1057* -->
1058*
1059* @name UNSAFE_useScrollRestoration
1060* @category Hooks
1061* @mode framework
1062* @mode data
1063* @param options Options
1064* @param options.getKey A function that returns a key to use for scroll restoration.
1065* This is useful for custom scroll restoration logic, such as using only the pathname
1066* so that subsequent navigations to prior paths will restore the scroll. Defaults
1067* to `location.key`.
1068* @param options.storageKey The key to use for storing scroll positions in
1069* `sessionStorage`. Defaults to `"react-router-scroll-positions"`.
1070* @returns {void}
1071*/
1072function useScrollRestoration({ getKey, storageKey } = {}) {
1073 let { router } = useDataRouterContext("useScrollRestoration");
1074 let { restoreScrollPosition, preventScrollReset } = useDataRouterState("useScrollRestoration");
1075 let { basename } = React$1.useContext(NavigationContext);
1076 let location = useLocation();
1077 let matches = useMatches();
1078 let navigation = useNavigation();
1079 React$1.useEffect(() => {
1080 window.history.scrollRestoration = "manual";
1081 return () => {
1082 window.history.scrollRestoration = "auto";
1083 };
1084 }, []);
1085 usePageShow(React$1.useCallback((event) => {
1086 if (event.persisted) window.history.scrollRestoration = "manual";
1087 }, []));
1088 usePageHide(React$1.useCallback(() => {
1089 if (navigation.state === "idle") {
1090 let key = getScrollRestorationKey(location, matches, basename, getKey);
1091 savedScrollPositions[key] = window.scrollY;
1092 }
1093 try {
1094 sessionStorage.setItem(storageKey || SCROLL_RESTORATION_STORAGE_KEY, JSON.stringify(savedScrollPositions));
1095 } catch (error) {
1096 warning(false, `Failed to save scroll positions in sessionStorage, <ScrollRestoration /> will not work properly (${error}).`);
1097 }
1098 window.history.scrollRestoration = "auto";
1099 }, [
1100 navigation.state,
1101 getKey,
1102 basename,
1103 location,
1104 matches,
1105 storageKey
1106 ]));
1107 if (typeof document !== "undefined") {
1108 React$1.useLayoutEffect(() => {
1109 try {
1110 let sessionPositions = sessionStorage.getItem(storageKey || SCROLL_RESTORATION_STORAGE_KEY);
1111 if (sessionPositions) savedScrollPositions = JSON.parse(sessionPositions);
1112 } catch {}
1113 }, [storageKey]);
1114 React$1.useLayoutEffect(() => {
1115 let disableScrollRestoration = router?.enableScrollRestoration(savedScrollPositions, () => window.scrollY, getKey ? (location, matches) => getScrollRestorationKey(location, matches, basename, getKey) : void 0);
1116 return () => disableScrollRestoration && disableScrollRestoration();
1117 }, [
1118 router,
1119 basename,
1120 getKey
1121 ]);
1122 React$1.useLayoutEffect(() => {
1123 if (restoreScrollPosition === false) return;
1124 if (typeof restoreScrollPosition === "number") {
1125 window.scrollTo(0, restoreScrollPosition);
1126 return;
1127 }
1128 try {
1129 if (location.hash) {
1130 let el = document.getElementById(decodeURIComponent(location.hash.slice(1)));
1131 if (el) {
1132 el.scrollIntoView();
1133 return;
1134 }
1135 }
1136 } catch {
1137 warning(false, `"${location.hash.slice(1)}" is not a decodable element ID. The view will not scroll to it.`);
1138 }
1139 if (preventScrollReset === true) return;
1140 window.scrollTo(0, 0);
1141 }, [
1142 location,
1143 restoreScrollPosition,
1144 preventScrollReset
1145 ]);
1146 }
1147}
1148/**
1149* Set up a callback to be fired on [Window's `beforeunload` event](https://developer.mozilla.org/en-US/docs/Web/API/Window/beforeunload_event).
1150*
1151* @public
1152* @category Hooks
1153* @param callback The callback to be called when the [`beforeunload` event](https://developer.mozilla.org/en-US/docs/Web/API/Window/beforeunload_event)
1154* is fired.
1155* @param options Options
1156* @param options.capture If `true`, the event will be captured during the capture
1157* phase. Defaults to `false`.
1158* @returns {void}
1159*/
1160function useBeforeUnload(callback, options) {
1161 let { capture } = options || {};
1162 React$1.useEffect(() => {
1163 let opts = capture != null ? { capture } : void 0;
1164 window.addEventListener("beforeunload", callback, opts);
1165 return () => {
1166 window.removeEventListener("beforeunload", callback, opts);
1167 };
1168 }, [callback, capture]);
1169}
1170function usePageHide(callback, options) {
1171 let { capture } = options || {};
1172 React$1.useEffect(() => {
1173 let opts = capture != null ? { capture } : void 0;
1174 window.addEventListener("pagehide", callback, opts);
1175 return () => {
1176 window.removeEventListener("pagehide", callback, opts);
1177 };
1178 }, [callback, capture]);
1179}
1180function usePageShow(callback, options) {
1181 let { capture } = options || {};
1182 React$1.useEffect(() => {
1183 let opts = capture != null ? { capture } : void 0;
1184 window.addEventListener("pageshow", callback, opts);
1185 return () => {
1186 window.removeEventListener("pageshow", callback, opts);
1187 };
1188 }, [callback, capture]);
1189}
1190/**
1191* Wrapper around {@link useBlocker} to show a [`window.confirm`](https://developer.mozilla.org/en-US/docs/Web/API/Window/confirm)
1192* prompt to users instead of building a custom UI with {@link useBlocker}.
1193*
1194* The `unstable_` flag will not be removed because this technique has a lot of
1195* rough edges and behaves very differently (and incorrectly sometimes) across
1196* browsers if users click addition back/forward navigations while the
1197* confirmation is open. Use at your own risk.
1198*
1199* @example
1200* function ImportantForm() {
1201* let [value, setValue] = React.useState("");
1202*
1203* // Block navigating elsewhere when data has been entered into the input
1204* unstable_usePrompt({
1205* message: "Are you sure?",
1206* when: ({ currentLocation, nextLocation }) =>
1207* value !== "" &&
1208* currentLocation.pathname !== nextLocation.pathname,
1209* });
1210*
1211* return (
1212* <Form method="post">
1213* <label>
1214* Enter some important data:
1215* <input
1216* name="data"
1217* value={value}
1218* onChange={(e) => setValue(e.target.value)}
1219* />
1220* </label>
1221* <button type="submit">Save</button>
1222* </Form>
1223* );
1224* }
1225*
1226* @name unstable_usePrompt
1227* @public
1228* @category Hooks
1229* @mode framework
1230* @mode data
1231* @param options Options
1232* @param options.message The message to show in the confirmation dialog.
1233* @param options.when A boolean or a function that returns a boolean indicating
1234* whether to block the navigation. If a function is provided, it will receive an
1235* object with `currentLocation` and `nextLocation` properties.
1236* @returns {void}
1237*/
1238function usePrompt({ when, message }) {
1239 let blocker = useBlocker(when);
1240 React$1.useEffect(() => {
1241 if (blocker.state === "blocked") if (window.confirm(message)) setTimeout(blocker.proceed, 0);
1242 else blocker.reset();
1243 }, [blocker, message]);
1244 React$1.useEffect(() => {
1245 if (blocker.state === "blocked" && !when) blocker.reset();
1246 }, [blocker, when]);
1247}
1248/**
1249* **Deprecated.** Use React's [`<ViewTransition>`](https://react.dev/reference/react/ViewTransition)
1250* component to style transitions instead. This hook only tracks React Router's
1251* legacy view transitions, not transitions started by React. See the
1252* [migration guide](../../how-to/view-transitions).
1253*
1254* This hook returns `true` when there is an active [View Transition](https://developer.mozilla.org/en-US/docs/Web/API/View_Transitions_API)
1255* and the specified location matches either side of the navigation (the URL you are
1256* navigating **to** or the URL you are navigating **from**). This can be used to apply finer-grained styles to
1257* elements to further customize the view transition. This requires that view
1258* transitions have been enabled for the given navigation via {@link LinkProps.viewTransition}
1259* (or the `Form`, `submit`, or `navigate` call)
1260*
1261* @public
1262* @category Hooks
1263* @mode framework
1264* @mode data
1265* @param to The {@link To} location to compare against the active transition's current
1266* and next URLs.
1267* @param options Options
1268* @param options.relative The relative routing type to use when resolving the
1269* `to` location, defaults to `"route"`. See {@link RelativeRoutingType} for
1270* more details.
1271* @returns `true` if there is an active [View Transition](https://developer.mozilla.org/en-US/docs/Web/API/View_Transitions_API)
1272* and the resolved path matches the transition's destination or source pathname, otherwise `false`.
1273*
1274* @deprecated Use React's `<ViewTransition>` component instead.
1275*/
1276function useViewTransitionState(to, { relative } = {}) {
1277 let vtContext = React$1.useContext(ViewTransitionContext);
1278 invariant(vtContext != null, "`useViewTransitionState` must be used within `react-router/dom`'s `RouterProvider`. Did you accidentally import `RouterProvider` from `react-router`?");
1279 let { basename } = useDataRouterContext("useViewTransitionState");
1280 let path = useResolvedPath(to, { relative });
1281 if (!vtContext.isTransitioning) return false;
1282 let currentPath = stripBasename(vtContext.currentLocation.pathname, basename) || vtContext.currentLocation.pathname;
1283 let nextPath = stripBasename(vtContext.nextLocation.pathname, basename) || vtContext.nextLocation.pathname;
1284 return matchPath(path.pathname, nextPath) != null || matchPath(path.pathname, currentPath) != null;
1285}
1286//#endregion
1287export { BrowserRouter, Form, HashRouter, HistoryRouter, Link, NavLink, ScrollRestoration, createBrowserRouter, createHashRouter, useBeforeUnload, useFetcher, useFetchers, useFormAction, useLinkClickHandler, usePrompt, useScrollRestoration, useSearchParams, useSubmit, useViewTransitionState };