UNPKG

50.2 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 { 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";
332const subscribeToNothing = () => () => {};
333const getClientSpaFallback = () => false;
334/**
335* Wraps {@link Link | `<Link>`} with additional props for styling active and
336* pending states.
337*
338* - Automatically applies classes to the link based on its `active` and `pending`
339* states, see {@link NavLinkProps.className}
340* - Note that `pending` is only available with Framework and Data modes.
341* - Automatically applies `aria-current="page"` to the link when the link is active.
342* See [`aria-current`](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-current)
343* on MDN.
344* - States are additionally available through the className, style, and children
345* render props. See {@link NavLinkRenderProps}.
346*
347* @example
348* <NavLink to="/message">Messages</NavLink>
349*
350* // Using render props
351* <NavLink
352* to="/messages"
353* className={({ isActive, isPending }) =>
354* isPending ? "pending" : isActive ? "active" : ""
355* }
356* >
357* Messages
358* </NavLink>
359*
360* @public
361* @category Components
362* @param {NavLinkProps.caseSensitive} props.caseSensitive n/a
363* @param {NavLinkProps.children} props.children n/a
364* @param {NavLinkProps.className} props.className n/a
365* @param {NavLinkProps.discover} props.discover [modes: framework] n/a
366* @param {NavLinkProps.end} props.end n/a
367* @param {NavLinkProps.prefetch} props.prefetch [modes: framework] n/a
368* @param {NavLinkProps.preventScrollReset} props.preventScrollReset [modes: framework, data] n/a
369* @param {NavLinkProps.relative} props.relative n/a
370* @param {NavLinkProps.reloadDocument} props.reloadDocument n/a
371* @param {NavLinkProps.replace} props.replace n/a
372* @param {NavLinkProps.state} props.state n/a
373* @param {NavLinkProps.style} props.style n/a
374* @param {NavLinkProps.to} props.to n/a
375* @param {NavLinkProps.viewTransition} props.viewTransition [modes: framework, data] n/a
376*/
377const NavLink = React$1.forwardRef(function NavLinkWithRef({ "aria-current": ariaCurrentProp = "page", caseSensitive = false, className: classNameProp = "", end = false, style: styleProp, to, viewTransition, children, ...rest }, ref) {
378 let path = useResolvedPath(to, { relative: rest.relative });
379 let location = useLocation();
380 let routerNavigation = React$1.useContext(DataRouterNavigationContext);
381 let { navigator, basename } = React$1.useContext(NavigationContext);
382 let isSpaMode = React$1.useContext(FrameworkContext)?.isSpaMode === true;
383 let isSpaFallback = React$1.useSyncExternalStore(subscribeToNothing, getClientSpaFallback, () => isSpaMode);
384 let isTransitioning = routerNavigation != null && useViewTransitionState(path) && viewTransition === true && !isSpaFallback;
385 let toPathname = navigator.encodeLocation ? navigator.encodeLocation(path).pathname : path.pathname;
386 let locationPathname = location.pathname;
387 let nextLocationPathname = routerNavigation?.navigation.location ? routerNavigation.navigation.location.pathname : null;
388 if (!caseSensitive) {
389 locationPathname = locationPathname.toLowerCase();
390 nextLocationPathname = nextLocationPathname ? nextLocationPathname.toLowerCase() : null;
391 toPathname = toPathname.toLowerCase();
392 }
393 if (nextLocationPathname && basename) nextLocationPathname = stripBasename(nextLocationPathname, basename) || nextLocationPathname;
394 const endSlashPosition = toPathname !== "/" && toPathname.endsWith("/") ? toPathname.length - 1 : toPathname.length;
395 let isActive = !isSpaFallback && (locationPathname === toPathname || !end && locationPathname.startsWith(toPathname) && locationPathname.charAt(endSlashPosition) === "/");
396 let isPending = !isSpaFallback && nextLocationPathname != null && (nextLocationPathname === toPathname || !end && nextLocationPathname.startsWith(toPathname) && nextLocationPathname.charAt(endSlashPosition) === "/");
397 let renderProps = {
398 isActive,
399 isPending,
400 isTransitioning
401 };
402 let ariaCurrent = isActive ? ariaCurrentProp : void 0;
403 let className;
404 if (typeof classNameProp === "function") className = classNameProp(renderProps);
405 else className = [
406 classNameProp,
407 isActive ? "active" : null,
408 isPending ? "pending" : null,
409 isTransitioning ? "transitioning" : null
410 ].filter(Boolean).join(" ");
411 let style = typeof styleProp === "function" ? styleProp(renderProps) : styleProp;
412 return /* @__PURE__ */ React$1.createElement(Link, {
413 ...rest,
414 "aria-current": ariaCurrent,
415 className,
416 ref,
417 style,
418 to,
419 viewTransition
420 }, typeof children === "function" ? children(renderProps) : children);
421});
422NavLink.displayName = "NavLink";
423/**
424* A progressively enhanced HTML [`<form>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form)
425* that submits data to actions via [`fetch`](https://developer.mozilla.org/en-US/docs/Web/API/fetch),
426* activating pending states in {@link useNavigation} which enables advanced
427* user interfaces beyond a basic HTML [`<form>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form).
428* After a form's `action` completes, all data on the page is automatically
429* revalidated to keep the UI in sync with the data.
430*
431* Because it uses the HTML form API, server rendered pages are interactive at a
432* basic level before JavaScript loads. Instead of React Router managing the
433* submission, the browser manages the submission as well as the pending states
434* (like the spinning favicon). After JavaScript loads, React Router takes over
435* enabling web application user experiences.
436*
437* `Form` is most useful for submissions that should also change the URL or
438* otherwise add an entry to the browser history stack. For forms that shouldn't
439* manipulate the browser [`History`](https://developer.mozilla.org/en-US/docs/Web/API/History)
440* stack, use {@link FetcherWithComponents.Form | `<fetcher.Form>`}.
441*
442* @example
443* import { Form } from "react-router";
444*
445* function NewEvent() {
446* return (
447* <Form action="/events" method="post">
448* <input name="title" type="text" />
449* <input name="description" type="text" />
450* </Form>
451* );
452* }
453*
454* @public
455* @category Components
456* @mode framework
457* @mode data
458* @param {FormProps.action} action n/a
459* @param {FormProps.discover} discover n/a
460* @param {FormProps.encType} encType n/a
461* @param {FormProps.fetcherKey} fetcherKey n/a
462* @param {FormProps.method} method n/a
463* @param {FormProps.navigate} navigate n/a
464* @param {FormProps.preventScrollReset} preventScrollReset n/a
465* @param {FormProps.relative} relative n/a
466* @param {FormProps.reloadDocument} reloadDocument n/a
467* @param {FormProps.replace} replace n/a
468* @param {FormProps.state} state n/a
469* @param {FormProps.viewTransition} viewTransition n/a
470* @param {FormProps.defaultShouldRevalidate} defaultShouldRevalidate n/a
471* @returns A progressively enhanced [`<form>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form) component
472*/
473const Form = React$1.forwardRef(({ discover = "render", fetcherKey, navigate, reloadDocument, replace, state, method = "get", action, onSubmit, relative, preventScrollReset, viewTransition, defaultShouldRevalidate, ...props }, forwardedRef) => {
474 let { useTransitions } = React$1.useContext(NavigationContext);
475 let submit = useSubmit();
476 let formAction = useFormAction(action, { relative });
477 let formMethod = method.toLowerCase() === "get" ? "get" : "post";
478 let isAbsolute = typeof action === "string" && ABSOLUTE_URL_REGEX.test(action);
479 let submitHandler = (event) => {
480 onSubmit && onSubmit(event);
481 if (event.defaultPrevented) return;
482 event.preventDefault();
483 let submitter = event.nativeEvent.submitter;
484 let submitMethod = submitter?.getAttribute("formmethod") || method;
485 let doSubmit = () => submit(submitter || event.currentTarget, {
486 fetcherKey,
487 method: submitMethod,
488 navigate,
489 replace,
490 state,
491 relative,
492 preventScrollReset,
493 viewTransition,
494 defaultShouldRevalidate
495 });
496 if (useTransitions && navigate !== false) React$1.startTransition(() => doSubmit());
497 else doSubmit();
498 };
499 return /* @__PURE__ */ React$1.createElement("form", {
500 ref: forwardedRef,
501 method: formMethod,
502 action: formAction,
503 onSubmit: reloadDocument ? onSubmit : submitHandler,
504 ...props,
505 "data-discover": !isAbsolute && discover === "render" ? "true" : void 0
506 });
507});
508Form.displayName = "Form";
509/**
510* Emulates the browser's scroll restoration on location changes. Apps should only render one of these, right before the {@link Scripts} component.
511*
512* ```tsx
513* import { ScrollRestoration } from "react-router";
514*
515* export default function Root() {
516* return (
517* <html>
518* <body>
519* <ScrollRestoration />
520* <Scripts />
521* </body>
522* </html>
523* );
524* }
525* ```
526*
527* This component renders an inline `<script>` to prevent scroll flashing. The
528* `nonce` prop will be passed down to the script tag to allow CSP nonce usage.
529* If not provided in Framework Mode, it will default to any
530* {@link ServerRouter | `<ServerRouter nonce>`} prop.
531*
532* ```tsx
533* <ScrollRestoration nonce={cspNonce} />
534* ```
535*
536* @public
537* @category Components
538* @mode framework
539* @mode data
540* @param props Props
541* @param {ScrollRestorationProps.getKey} props.getKey n/a
542* @param {ScriptsProps.nonce} props.nonce n/a
543* @param {ScrollRestorationProps.storageKey} props.storageKey n/a
544* @returns A [`<script>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script)
545* tag that restores scroll positions on navigation.
546*/
547function ScrollRestoration({ getKey, storageKey, ...props }) {
548 let remixContext = React$1.useContext(FrameworkContext);
549 let { basename } = React$1.useContext(NavigationContext);
550 let location = useLocation();
551 let matches = useMatches();
552 useScrollRestoration({
553 getKey,
554 storageKey
555 });
556 let ssrKey = React$1.useMemo(() => {
557 if (!remixContext || !getKey) return null;
558 let userKey = getScrollRestorationKey(location, matches, basename, getKey);
559 return userKey !== location.key ? userKey : null;
560 }, []);
561 if (!remixContext || remixContext.isSpaMode) return null;
562 let restoreScroll = ((storageKey, restoreKey) => {
563 if (!window.history.state || !window.history.state.key) {
564 let key = Math.random().toString(32).slice(2);
565 window.history.replaceState({ key }, "");
566 }
567 try {
568 let storedY = JSON.parse(sessionStorage.getItem(storageKey) || "{}")[restoreKey || window.history.state.key];
569 if (typeof storedY === "number") window.scrollTo(0, storedY);
570 } catch (error) {
571 console.error(error);
572 try {
573 sessionStorage.removeItem(storageKey);
574 } catch {}
575 }
576 }).toString();
577 if (props.nonce == null && remixContext?.nonce) props.nonce = remixContext.nonce;
578 return /* @__PURE__ */ React$1.createElement("script", {
579 ...props,
580 suppressHydrationWarning: true,
581 dangerouslySetInnerHTML: { __html: `(${restoreScroll})(${escapeHtml(JSON.stringify(storageKey || SCROLL_RESTORATION_STORAGE_KEY))}, ${escapeHtml(JSON.stringify(ssrKey))})` }
582 });
583}
584ScrollRestoration.displayName = "ScrollRestoration";
585/**
586* Handles the click behavior for router {@link Link | `<Link>`} components.This
587* is useful if you need to create custom {@link Link | `<Link>`} components with
588* the same click behavior we use in our exported {@link Link | `<Link>`}.
589*
590* @public
591* @category Hooks
592* @param to The URL to navigate to, can be a string or a partial {@link Path}.
593* @param options Options
594* @param options.preventScrollReset Whether to prevent the scroll position from
595* being reset to the top of the viewport on completion of the navigation when
596* using the {@link ScrollRestoration} component. Defaults to `false`.
597* @param options.relative The {@link RelativeRoutingType | relative routing type}
598* to use for the link. Defaults to `"route"`.
599* @param options.replace Whether to replace the current [`History`](https://developer.mozilla.org/en-US/docs/Web/API/History)
600* entry instead of pushing a new one. Defaults to `false`.
601* @param options.state The state to add to the [`History`](https://developer.mozilla.org/en-US/docs/Web/API/History)
602* entry for this navigation. Defaults to `undefined`.
603* @param options.target The target attribute for the link. Defaults to `undefined`.
604* @param options.viewTransition **Deprecated.** Use React's
605* [`<ViewTransition>`](https://react.dev/reference/react/ViewTransition) component
606* instead. See the [migration guide](../../how-to/view-transitions).
607* @param options.defaultShouldRevalidate Specify the default revalidation
608* behavior for the navigation. When not specified, loaders revalidate
609* according to the router's standard revalidation behavior.
610* @param options.mask Masked location to display in the browser instead
611* of the router location. Defaults to `undefined`.
612* @param options.useTransitions Wraps the navigation in
613* [`React.startTransition`](https://react.dev/reference/react/startTransition)
614* for concurrent rendering. Defaults to `false`.
615* @returns A click handler function that can be used in a custom {@link Link} component.
616*/
617function useLinkClickHandler(to, { target, replace: replaceProp, mask, state, preventScrollReset, relative, viewTransition, defaultShouldRevalidate, useTransitions } = {}) {
618 let navigate = useNavigate();
619 let location = useLocation();
620 let path = useResolvedPath(to, { relative });
621 return React$1.useCallback((event) => {
622 if (shouldProcessLinkClick(event, target)) {
623 event.preventDefault();
624 let replace = replaceProp !== void 0 ? replaceProp : createPath(location) === createPath(path);
625 let doNavigate = () => navigate(to, {
626 replace,
627 mask,
628 state,
629 preventScrollReset,
630 relative,
631 viewTransition,
632 defaultShouldRevalidate
633 });
634 if (useTransitions) React$1.startTransition(() => doNavigate());
635 else doNavigate();
636 }
637 }, [
638 location,
639 navigate,
640 path,
641 replaceProp,
642 mask,
643 state,
644 target,
645 to,
646 preventScrollReset,
647 relative,
648 viewTransition,
649 defaultShouldRevalidate,
650 useTransitions
651 ]);
652}
653/**
654* Returns a tuple of the current URL's [`URLSearchParams`](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams)
655* and a function to update them. Setting the search params causes a navigation.
656*
657* ```tsx
658* import { useSearchParams } from "react-router";
659*
660* export function SomeComponent() {
661* const [searchParams, setSearchParams] = useSearchParams();
662* // ...
663* }
664* ```
665*
666* ### `setSearchParams` function
667*
668* The second element of the tuple is a function that can be used to update the
669* search params. It accepts the same types as `defaultInit` and will cause a
670* navigation to the new URL.
671*
672* ```tsx
673* let [searchParams, setSearchParams] = useSearchParams();
674*
675* // a search param string
676* setSearchParams("?tab=1");
677*
678* // a shorthand object
679* setSearchParams({ tab: "1" });
680*
681* // object keys can be arrays for multiple values on the key
682* setSearchParams({ brand: ["nike", "reebok"] });
683*
684* // an array of tuples
685* setSearchParams([["tab", "1"]]);
686*
687* // a `URLSearchParams` object
688* setSearchParams(new URLSearchParams("?tab=1"));
689* ```
690*
691* It also supports a function callback like React's
692* [`setState`](https://react.dev/reference/react/useState#setstate):
693*
694* ```tsx
695* setSearchParams((searchParams) => {
696* searchParams.set("tab", "2");
697* return searchParams;
698* });
699* ```
700*
701* <docs-warning>The function callback version of `setSearchParams` does not support
702* the [queueing](https://react.dev/reference/react/useState#setstate-parameters)
703* logic that React's `setState` implements. Multiple calls to `setSearchParams`
704* in the same tick will not build on the prior value. If you need this behavior,
705* you can use `setState` manually.</docs-warning>
706*
707* ### Notes
708*
709* Note that `searchParams` is a stable reference, so you can reliably use it
710* as a dependency in React's [`useEffect`](https://react.dev/reference/react/useEffect)
711* hooks.
712*
713* ```tsx
714* useEffect(() => {
715* console.log(searchParams.get("tab"));
716* }, [searchParams]);
717* ```
718*
719* However, this also means it's mutable. If you change the object without
720* calling `setSearchParams`, its values will change between renders if some
721* other state causes the component to re-render and URL will not reflect the
722* values.
723*
724* @public
725* @category Hooks
726* @param defaultInit
727* You can initialize the search params with a default value, though it **will
728* not** change the URL on the first render.
729*
730* ```tsx
731* // a search param string
732* useSearchParams("?tab=1");
733*
734* // a shorthand object
735* useSearchParams({ tab: "1" });
736*
737* // object keys can be arrays for multiple values on the key
738* useSearchParams({ brand: ["nike", "reebok"] });
739*
740* // an array of tuples
741* useSearchParams([["tab", "1"]]);
742*
743* // a `URLSearchParams` object
744* useSearchParams(new URLSearchParams("?tab=1"));
745* ```
746* @returns A tuple of the current [`URLSearchParams`](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams)
747* and a function to update them.
748*/
749function useSearchParams(defaultInit) {
750 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.");
751 let defaultSearchParamsRef = React$1.useRef(createSearchParams(defaultInit));
752 let hasSetSearchParamsRef = React$1.useRef(false);
753 let location = useLocation();
754 let searchParams = React$1.useMemo(() => getSearchParamsForLocation(location.search, hasSetSearchParamsRef.current ? null : defaultSearchParamsRef.current), [location.search]);
755 let navigate = useNavigate();
756 return [searchParams, React$1.useCallback((nextInit, navigateOptions) => {
757 const newSearchParams = createSearchParams(typeof nextInit === "function" ? nextInit(new URLSearchParams(searchParams)) : nextInit);
758 hasSetSearchParamsRef.current = true;
759 navigate("?" + newSearchParams, navigateOptions);
760 }, [navigate, searchParams])];
761}
762let fetcherId = 0;
763let getUniqueFetcherId = () => `__${String(++fetcherId)}__`;
764/**
765* The imperative version of {@link Form | `<Form>`} that lets you submit a form
766* from code instead of a user interaction.
767*
768* The `viewTransition` submission option is deprecated. Use React's
769* [`<ViewTransition>`](https://react.dev/reference/react/ViewTransition) component
770* instead. See the [migration guide](../../how-to/view-transitions).
771*
772* @example
773* import { useSubmit } from "react-router";
774*
775* function SomeComponent() {
776* const submit = useSubmit();
777* return (
778* <Form onChange={(event) => submit(event.currentTarget)} />
779* );
780* }
781*
782* @public
783* @category Hooks
784* @mode framework
785* @mode data
786* @returns A function that can be called to submit a {@link Form} imperatively.
787*/
788function useSubmit() {
789 let { router } = useDataRouterContext("useSubmit");
790 let { basename } = React$1.useContext(NavigationContext);
791 let currentRouteId = useCurrentRouteId("useSubmit");
792 let routerFetch = router.fetch;
793 let routerNavigate = router.navigate;
794 return React$1.useCallback(async (target, options = {}) => {
795 let { action, method, encType, formData, body } = getFormSubmissionInfo(target, basename);
796 if (options.navigate === false) await routerFetch(options.fetcherKey || getUniqueFetcherId(), currentRouteId, options.action || action, {
797 defaultShouldRevalidate: options.defaultShouldRevalidate,
798 preventScrollReset: options.preventScrollReset,
799 relative: options.relative,
800 formData,
801 body,
802 formMethod: options.method || method,
803 formEncType: options.encType || encType,
804 flushSync: options.flushSync
805 });
806 else await routerNavigate(options.action || action, {
807 defaultShouldRevalidate: options.defaultShouldRevalidate,
808 preventScrollReset: options.preventScrollReset,
809 relative: options.relative,
810 formData,
811 body,
812 formMethod: options.method || method,
813 formEncType: options.encType || encType,
814 replace: options.replace,
815 state: options.state,
816 fromRouteId: currentRouteId,
817 flushSync: options.flushSync,
818 viewTransition: options.viewTransition
819 });
820 }, [
821 routerFetch,
822 routerNavigate,
823 basename,
824 currentRouteId
825 ]);
826}
827/**
828* Resolves the URL to the closest route in the component hierarchy instead of
829* the current URL of the app.
830*
831* This is used internally by {@link Form} to resolve the `action` to the closest
832* route, but can be used generically as well.
833*
834* ```ts
835* import { useFormAction } from "react-router";
836*
837* function SomeComponent() {
838* // closest route URL
839* let action = useFormAction();
840*
841* // closest route URL + "destroy"
842* let destroyAction = useFormAction("destroy");
843* }
844* ```
845*
846* <docs-info>This hook adds a `basename` if your app specifies one, so that it
847* can be used with raw `<form>` elements in a progressively enhanced way. If
848* you are using this to provide an `action` to `<Form>` or `fetcher.submit`, you
849* will need to remove the `basename` since both of those will prepend it
850* internally.</docs-info>
851*
852*
853* @public
854* @category Hooks
855* @mode framework
856* @mode data
857* @param action The action to append to the closest route URL. Defaults to the
858* closest route URL.
859* @param options Options
860* @param options.relative The relative routing type to use when resolving the
861* action. Defaults to `"route"`.
862* @returns The resolved action URL.
863*/
864function useFormAction(action, { relative } = {}) {
865 let { basename } = React$1.useContext(NavigationContext);
866 let routeContext = React$1.useContext(RouteContext);
867 invariant(routeContext, "useFormAction must be used inside a RouteContext");
868 let [match] = routeContext.matches.slice(-1);
869 let path = { ...useResolvedPath(action ? action : ".", { relative }) };
870 let location = useLocation();
871 if (action == null) {
872 path.search = location.search;
873 let params = new URLSearchParams(path.search);
874 let indexValues = params.getAll("index");
875 if (indexValues.some((v) => v === "")) {
876 params.delete("index");
877 indexValues.filter((v) => v).forEach((v) => params.append("index", v));
878 let qs = params.toString();
879 path.search = qs ? `?${qs}` : "";
880 }
881 }
882 if ((!action || action === ".") && match.route.index) path.search = path.search ? path.search.replace(/^\?/, "?index&") : "?index";
883 if (basename !== "/") path.pathname = path.pathname === "/" ? basename : joinPaths([basename, path.pathname]);
884 let formAction = createPath(path);
885 validateDocumentNavigationTarget(formAction);
886 return formAction;
887}
888/**
889* Useful for creating complex, dynamic user interfaces that require multiple,
890* concurrent data interactions without causing a navigation.
891*
892* Fetchers track their own, independent state and can be used to load data, submit
893* forms, and generally interact with [`action`](../../start/framework/route-module#action)
894* and [`loader`](../../start/framework/route-module#loader) functions.
895*
896* @example
897* import { useFetcher } from "react-router"
898*
899* function SomeComponent() {
900* let fetcher = useFetcher()
901*
902* // states are available on the fetcher
903* fetcher.state // "idle" | "loading" | "submitting"
904* fetcher.data // the data returned from the action or loader
905*
906* // render a form
907* <fetcher.Form method="post" />
908*
909* // load data
910* fetcher.load("/some/route")
911*
912* // submit data
913* fetcher.submit(someFormRef, { method: "post" })
914* fetcher.submit(someData, {
915* method: "post",
916* encType: "application/json"
917* })
918*
919* // reset fetcher
920* fetcher.reset()
921* }
922*
923* @public
924* @category Hooks
925* @mode framework
926* @mode data
927* @param options Options
928* @param options.key A unique key to identify the fetcher.
929*
930*
931* By default, `useFetcher` generates a unique fetcher scoped to that component.
932* If you want to identify a fetcher with your own key such that you can access
933* it from elsewhere in your app, you can do that with the `key` option:
934*
935* ```tsx
936* function SomeComp() {
937* let fetcher = useFetcher({ key: "my-key" })
938* // ...
939* }
940*
941* // Somewhere else
942* function AnotherComp() {
943* // this will be the same fetcher, sharing the state across the app
944* let fetcher = useFetcher({ key: "my-key" });
945* // ...
946* }
947* ```
948* @returns A {@link FetcherWithComponents} object that contains the fetcher's state, data, and components for submitting forms and loading data.
949*/
950function useFetcher({ key } = {}) {
951 let { router } = useDataRouterContext("useFetcher");
952 let fetchersContext = useDataRouterFetchers("useFetcher");
953 let routeId = useCurrentRouteId("useFetcher");
954 let defaultKey = React$1.useId();
955 let [fetcherKey, setFetcherKey] = React$1.useState(key || defaultKey);
956 if (key && key !== fetcherKey) setFetcherKey(key);
957 let { deleteFetcher, getFetcher, resetFetcher, fetch: routerFetch } = router;
958 React$1.useEffect(() => {
959 getFetcher(fetcherKey);
960 return () => deleteFetcher(fetcherKey);
961 }, [
962 deleteFetcher,
963 getFetcher,
964 fetcherKey
965 ]);
966 let load = React$1.useCallback(async (href, opts) => {
967 invariant(routeId, "No routeId available for fetcher.load()");
968 await routerFetch(fetcherKey, routeId, href, opts);
969 }, [
970 fetcherKey,
971 routeId,
972 routerFetch
973 ]);
974 let submitImpl = useSubmit();
975 let submit = React$1.useCallback(async (target, opts) => {
976 await submitImpl(target, {
977 ...opts,
978 navigate: false,
979 fetcherKey
980 });
981 }, [fetcherKey, submitImpl]);
982 let reset = React$1.useCallback((opts) => resetFetcher(fetcherKey, opts), [resetFetcher, fetcherKey]);
983 let FetcherForm = React$1.useMemo(() => {
984 let FetcherForm = React$1.forwardRef((props, ref) => {
985 return /* @__PURE__ */ React$1.createElement(Form, {
986 ...props,
987 navigate: false,
988 fetcherKey,
989 ref
990 });
991 });
992 FetcherForm.displayName = "fetcher.Form";
993 return FetcherForm;
994 }, [fetcherKey]);
995 let fetcher = fetchersContext.fetchers.get(fetcherKey) || IDLE_FETCHER;
996 let data = fetchersContext.fetcherData.get(fetcherKey);
997 return React$1.useMemo(() => ({
998 Form: FetcherForm,
999 submit,
1000 load,
1001 reset,
1002 ...fetcher,
1003 data
1004 }), [
1005 FetcherForm,
1006 submit,
1007 load,
1008 reset,
1009 fetcher,
1010 data
1011 ]);
1012}
1013/**
1014* Returns an array of all in-flight {@link Fetcher}s. This is useful for components
1015* throughout the app that didn't create the fetchers but want to use their submissions
1016* to participate in optimistic UI.
1017*
1018* @example
1019* import { useFetchers } from "react-router";
1020*
1021* function SomeComponent() {
1022* const fetchers = useFetchers();
1023* fetchers[0].formData; // FormData
1024* fetchers[0].state; // etc.
1025* // ...
1026* }
1027*
1028* @public
1029* @category Hooks
1030* @mode framework
1031* @mode data
1032* @returns An array of all in-flight {@link Fetcher}s, each with a unique `key`
1033* property.
1034*/
1035function useFetchers() {
1036 let { fetchers } = useDataRouterFetchers("useFetchers");
1037 return React$1.useMemo(() => Array.from(fetchers.entries()).map(([key, fetcher]) => ({
1038 ...fetcher,
1039 key
1040 })), [fetchers]);
1041}
1042const SCROLL_RESTORATION_STORAGE_KEY = "react-router-scroll-positions";
1043let savedScrollPositions = {};
1044function getScrollRestorationKey(location, matches, basename, getKey) {
1045 let key = null;
1046 if (getKey) if (basename !== "/") key = getKey({
1047 ...location,
1048 pathname: stripBasename(location.pathname, basename) || location.pathname
1049 }, matches);
1050 else key = getKey(location, matches);
1051 if (key == null) key = location.key;
1052 return key;
1053}
1054/**
1055* When rendered inside a {@link RouterProvider}, will restore scroll positions
1056* on navigations
1057*
1058* <!--
1059* Not marked `@public` because we only export as UNSAFE_ and therefore we don't
1060* maintain an .md file for this hook
1061* -->
1062*
1063* @name UNSAFE_useScrollRestoration
1064* @category Hooks
1065* @mode framework
1066* @mode data
1067* @param options Options
1068* @param options.getKey A function that returns a key to use for scroll restoration.
1069* This is useful for custom scroll restoration logic, such as using only the pathname
1070* so that subsequent navigations to prior paths will restore the scroll. Defaults
1071* to `location.key`.
1072* @param options.storageKey The key to use for storing scroll positions in
1073* `sessionStorage`. Defaults to `"react-router-scroll-positions"`.
1074* @returns {void}
1075*/
1076function useScrollRestoration({ getKey, storageKey } = {}) {
1077 let { router } = useDataRouterContext("useScrollRestoration");
1078 let { restoreScrollPosition, preventScrollReset } = useDataRouterState("useScrollRestoration");
1079 let { basename } = React$1.useContext(NavigationContext);
1080 let location = useLocation();
1081 let matches = useMatches();
1082 let navigation = useNavigation();
1083 React$1.useEffect(() => {
1084 window.history.scrollRestoration = "manual";
1085 return () => {
1086 window.history.scrollRestoration = "auto";
1087 };
1088 }, []);
1089 usePageShow(React$1.useCallback((event) => {
1090 if (event.persisted) window.history.scrollRestoration = "manual";
1091 }, []));
1092 usePageHide(React$1.useCallback(() => {
1093 if (navigation.state === "idle") {
1094 let key = getScrollRestorationKey(location, matches, basename, getKey);
1095 savedScrollPositions[key] = window.scrollY;
1096 }
1097 try {
1098 sessionStorage.setItem(storageKey || SCROLL_RESTORATION_STORAGE_KEY, JSON.stringify(savedScrollPositions));
1099 } catch (error) {
1100 warning(false, `Failed to save scroll positions in sessionStorage, <ScrollRestoration /> will not work properly (${error}).`);
1101 }
1102 window.history.scrollRestoration = "auto";
1103 }, [
1104 navigation.state,
1105 getKey,
1106 basename,
1107 location,
1108 matches,
1109 storageKey
1110 ]));
1111 if (typeof document !== "undefined") {
1112 React$1.useLayoutEffect(() => {
1113 try {
1114 let sessionPositions = sessionStorage.getItem(storageKey || SCROLL_RESTORATION_STORAGE_KEY);
1115 if (sessionPositions) {
1116 let parsedPositions = JSON.parse(sessionPositions);
1117 savedScrollPositions = parsedPositions && typeof parsedPositions === "object" && !Array.isArray(parsedPositions) ? parsedPositions : {};
1118 }
1119 } catch {}
1120 }, [storageKey]);
1121 React$1.useLayoutEffect(() => {
1122 let disableScrollRestoration = router?.enableScrollRestoration(savedScrollPositions, () => window.scrollY, getKey ? (location, matches) => getScrollRestorationKey(location, matches, basename, getKey) : void 0);
1123 return () => disableScrollRestoration && disableScrollRestoration();
1124 }, [
1125 router,
1126 basename,
1127 getKey
1128 ]);
1129 React$1.useLayoutEffect(() => {
1130 if (restoreScrollPosition === false) return;
1131 if (typeof restoreScrollPosition === "number") {
1132 window.scrollTo(0, restoreScrollPosition);
1133 return;
1134 }
1135 try {
1136 if (location.hash) {
1137 let el = document.getElementById(decodeURIComponent(location.hash.slice(1)));
1138 if (el) {
1139 el.scrollIntoView();
1140 return;
1141 }
1142 }
1143 } catch {
1144 warning(false, `"${location.hash.slice(1)}" is not a decodable element ID. The view will not scroll to it.`);
1145 }
1146 if (preventScrollReset === true) return;
1147 window.scrollTo(0, 0);
1148 }, [
1149 location,
1150 restoreScrollPosition,
1151 preventScrollReset
1152 ]);
1153 }
1154}
1155/**
1156* Set up a callback to be fired on [Window's `beforeunload` event](https://developer.mozilla.org/en-US/docs/Web/API/Window/beforeunload_event).
1157*
1158* @public
1159* @category Hooks
1160* @param callback The callback to be called when the [`beforeunload` event](https://developer.mozilla.org/en-US/docs/Web/API/Window/beforeunload_event)
1161* is fired.
1162* @param options Options
1163* @param options.capture If `true`, the event will be captured during the capture
1164* phase. Defaults to `false`.
1165* @returns {void}
1166*/
1167function useBeforeUnload(callback, options) {
1168 let { capture } = options || {};
1169 React$1.useEffect(() => {
1170 let opts = capture != null ? { capture } : void 0;
1171 window.addEventListener("beforeunload", callback, opts);
1172 return () => {
1173 window.removeEventListener("beforeunload", callback, opts);
1174 };
1175 }, [callback, capture]);
1176}
1177function usePageHide(callback, options) {
1178 let { capture } = options || {};
1179 React$1.useEffect(() => {
1180 let opts = capture != null ? { capture } : void 0;
1181 window.addEventListener("pagehide", callback, opts);
1182 return () => {
1183 window.removeEventListener("pagehide", callback, opts);
1184 };
1185 }, [callback, capture]);
1186}
1187function usePageShow(callback, options) {
1188 let { capture } = options || {};
1189 React$1.useEffect(() => {
1190 let opts = capture != null ? { capture } : void 0;
1191 window.addEventListener("pageshow", callback, opts);
1192 return () => {
1193 window.removeEventListener("pageshow", callback, opts);
1194 };
1195 }, [callback, capture]);
1196}
1197/**
1198* Wrapper around {@link useBlocker} to show a [`window.confirm`](https://developer.mozilla.org/en-US/docs/Web/API/Window/confirm)
1199* prompt to users instead of building a custom UI with {@link useBlocker}.
1200*
1201* The `unstable_` flag will not be removed because this technique has a lot of
1202* rough edges and behaves very differently (and incorrectly sometimes) across
1203* browsers if users click addition back/forward navigations while the
1204* confirmation is open. Use at your own risk.
1205*
1206* @example
1207* function ImportantForm() {
1208* let [value, setValue] = React.useState("");
1209*
1210* // Block navigating elsewhere when data has been entered into the input
1211* unstable_usePrompt({
1212* message: "Are you sure?",
1213* when: ({ currentLocation, nextLocation }) =>
1214* value !== "" &&
1215* currentLocation.pathname !== nextLocation.pathname,
1216* });
1217*
1218* return (
1219* <Form method="post">
1220* <label>
1221* Enter some important data:
1222* <input
1223* name="data"
1224* value={value}
1225* onChange={(e) => setValue(e.target.value)}
1226* />
1227* </label>
1228* <button type="submit">Save</button>
1229* </Form>
1230* );
1231* }
1232*
1233* @name unstable_usePrompt
1234* @public
1235* @category Hooks
1236* @mode framework
1237* @mode data
1238* @param options Options
1239* @param options.message The message to show in the confirmation dialog.
1240* @param options.when A boolean or a function that returns a boolean indicating
1241* whether to block the navigation. If a function is provided, it will receive an
1242* object with `currentLocation` and `nextLocation` properties.
1243* @returns {void}
1244*/
1245function usePrompt({ when, message }) {
1246 let blocker = useBlocker(when);
1247 React$1.useEffect(() => {
1248 if (blocker.state === "blocked") if (window.confirm(message)) setTimeout(blocker.proceed, 0);
1249 else blocker.reset();
1250 }, [blocker, message]);
1251 React$1.useEffect(() => {
1252 if (blocker.state === "blocked" && !when) blocker.reset();
1253 }, [blocker, when]);
1254}
1255/**
1256* **Deprecated.** Use React's [`<ViewTransition>`](https://react.dev/reference/react/ViewTransition)
1257* component to style transitions instead. This hook only tracks React Router's
1258* legacy view transitions, not transitions started by React. See the
1259* [migration guide](../../how-to/view-transitions).
1260*
1261* This hook returns `true` when there is an active [View Transition](https://developer.mozilla.org/en-US/docs/Web/API/View_Transitions_API)
1262* and the specified location matches either side of the navigation (the URL you are
1263* navigating **to** or the URL you are navigating **from**). This can be used to apply finer-grained styles to
1264* elements to further customize the view transition. This requires that view
1265* transitions have been enabled for the given navigation via {@link LinkProps.viewTransition}
1266* (or the `Form`, `submit`, or `navigate` call)
1267*
1268* @public
1269* @category Hooks
1270* @mode framework
1271* @mode data
1272* @param to The {@link To} location to compare against the active transition's current
1273* and next URLs.
1274* @param options Options
1275* @param options.relative The relative routing type to use when resolving the
1276* `to` location, defaults to `"route"`. See {@link RelativeRoutingType} for
1277* more details.
1278* @returns `true` if there is an active [View Transition](https://developer.mozilla.org/en-US/docs/Web/API/View_Transitions_API)
1279* and the resolved path matches the transition's destination or source pathname, otherwise `false`.
1280*
1281* @deprecated Use React's `<ViewTransition>` component instead.
1282*/
1283function useViewTransitionState(to, { relative } = {}) {
1284 let vtContext = React$1.useContext(ViewTransitionContext);
1285 invariant(vtContext != null, "`useViewTransitionState` must be used within `react-router/dom`'s `RouterProvider`. Did you accidentally import `RouterProvider` from `react-router`?");
1286 let { basename } = useDataRouterContext("useViewTransitionState");
1287 let path = useResolvedPath(to, { relative });
1288 if (!vtContext.isTransitioning) return false;
1289 let currentPath = stripBasename(vtContext.currentLocation.pathname, basename) || vtContext.currentLocation.pathname;
1290 let nextPath = stripBasename(vtContext.nextLocation.pathname, basename) || vtContext.nextLocation.pathname;
1291 return matchPath(path.pathname, nextPath) != null || matchPath(path.pathname, currentPath) != null;
1292}
1293//#endregion
1294export { BrowserRouter, Form, HashRouter, HistoryRouter, Link, NavLink, ScrollRestoration, createBrowserRouter, createHashRouter, useBeforeUnload, useFetcher, useFetchers, useFormAction, useLinkClickHandler, usePrompt, useScrollRestoration, useSearchParams, useSubmit, useViewTransitionState };