Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

react-router-dom

Package Overview
Dependencies
Maintainers
0
Versions
507
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

react-router-dom - npm Package Compare versions

Comparing version 0.0.0-experimental-4286521e to 0.0.0-experimental-42a5853ef

dist/index.mjs

265

dist/index.d.ts

@@ -1,263 +0,2 @@

/**
* NOTE: If you refactor this to split up the modules into separate files,
* you'll need to update the rollup config for react-router-dom-v5-compat.
*/
import * as React from "react";
import type { FutureConfig, NavigateOptions, RelativeRoutingType, RouteObject, To } from "react-router";
import type { Fetcher, FormEncType, FormMethod, FutureConfig as RouterFutureConfig, GetScrollRestorationKeyFunction, History, HTMLFormMethod, HydrationState, Router as RemixRouter, V7_FormMethod } from "@remix-run/router";
import type { SubmitOptions, ParamKeyValuePair, URLSearchParamsInit, SubmitTarget } from "./dom";
import { createSearchParams } from "./dom";
export type { FormEncType, FormMethod, GetScrollRestorationKeyFunction, ParamKeyValuePair, SubmitOptions, URLSearchParamsInit, V7_FormMethod, };
export { createSearchParams };
export type { ActionFunction, ActionFunctionArgs, AwaitProps, unstable_Blocker, unstable_BlockerFunction, DataRouteMatch, DataRouteObject, Fetcher, Hash, IndexRouteObject, IndexRouteProps, JsonFunction, LazyRouteFunction, LayoutRouteProps, LoaderFunction, LoaderFunctionArgs, Location, MemoryRouterProps, NavigateFunction, NavigateOptions, NavigateProps, Navigation, Navigator, NonIndexRouteObject, OutletProps, Params, ParamParseKey, Path, PathMatch, Pathname, PathPattern, PathRouteProps, RedirectFunction, RelativeRoutingType, RouteMatch, RouteObject, RouteProps, RouterProps, RouterProviderProps, RoutesProps, Search, ShouldRevalidateFunction, To, } from "react-router";
export { AbortedDeferredError, Await, MemoryRouter, Navigate, NavigationType, Outlet, Route, Router, RouterProvider, Routes, createMemoryRouter, createPath, createRoutesFromChildren, createRoutesFromElements, defer, isRouteErrorResponse, generatePath, json, matchPath, matchRoutes, parsePath, redirect, redirectDocument, renderMatches, resolvePath, useActionData, useAsyncError, useAsyncValue, unstable_useBlocker, useHref, useInRouterContext, useLoaderData, useLocation, useMatch, useMatches, useNavigate, useNavigation, useNavigationType, useOutlet, useOutletContext, useParams, useResolvedPath, useRevalidator, useRouteError, useRouteLoaderData, useRoutes, } from "react-router";
/** @internal */
export { UNSAFE_DataRouterContext, UNSAFE_DataRouterStateContext, UNSAFE_NavigationContext, UNSAFE_LocationContext, UNSAFE_RouteContext, UNSAFE_useRouteId, } from "react-router";
declare global {
var __staticRouterHydrationData: HydrationState | undefined;
}
interface DOMRouterOpts {
basename?: string;
future?: Partial<Omit<RouterFutureConfig, "v7_prependBasename">>;
hydrationData?: HydrationState;
window?: Window;
}
export declare function createBrowserRouter(routes: RouteObject[], opts?: DOMRouterOpts): RemixRouter;
export declare function createHashRouter(routes: RouteObject[], opts?: DOMRouterOpts): RemixRouter;
export interface BrowserRouterProps {
basename?: string;
children?: React.ReactNode;
future?: FutureConfig;
window?: Window;
}
/**
* A `<Router>` for use in web browsers. Provides the cleanest URLs.
*/
export declare function BrowserRouter({ basename, children, future, window, }: BrowserRouterProps): React.JSX.Element;
export interface HashRouterProps {
basename?: string;
children?: React.ReactNode;
future?: FutureConfig;
window?: Window;
}
/**
* A `<Router>` for use in web browsers. Stores the location in the hash
* portion of the URL so it is not sent to the server.
*/
export declare function HashRouter({ basename, children, future, window, }: HashRouterProps): React.JSX.Element;
export interface HistoryRouterProps {
basename?: string;
children?: React.ReactNode;
future?: FutureConfig;
history: History;
}
/**
* A `<Router>` that accepts a pre-instantiated history object. It's important
* to note that using your own history object is highly discouraged and may add
* two versions of the history library to your bundles unless you use the same
* version of the history library that React Router uses internally.
*/
declare function HistoryRouter({ basename, children, future, history, }: HistoryRouterProps): React.JSX.Element;
declare namespace HistoryRouter {
var displayName: string;
}
export { HistoryRouter as unstable_HistoryRouter };
export interface LinkProps extends Omit<React.AnchorHTMLAttributes<HTMLAnchorElement>, "href"> {
reloadDocument?: boolean;
replace?: boolean;
state?: any;
preventScrollReset?: boolean;
relative?: RelativeRoutingType;
to: To;
}
/**
* The public API for rendering a history-aware <a>.
*/
export declare const Link: React.ForwardRefExoticComponent<LinkProps & React.RefAttributes<HTMLAnchorElement>>;
export interface NavLinkProps extends Omit<LinkProps, "className" | "style" | "children"> {
children?: React.ReactNode | ((props: {
isActive: boolean;
isPending: boolean;
}) => React.ReactNode);
caseSensitive?: boolean;
className?: string | ((props: {
isActive: boolean;
isPending: boolean;
}) => string | undefined);
end?: boolean;
style?: React.CSSProperties | ((props: {
isActive: boolean;
isPending: boolean;
}) => React.CSSProperties | undefined);
}
/**
* A <Link> wrapper that knows if it's "active" or not.
*/
export declare const NavLink: React.ForwardRefExoticComponent<NavLinkProps & React.RefAttributes<HTMLAnchorElement>>;
export interface FetcherFormProps extends React.FormHTMLAttributes<HTMLFormElement> {
/**
* The HTTP verb to use when the form is submit. Supports "get", "post",
* "put", "delete", "patch".
*/
method?: HTMLFormMethod;
/**
* `<form encType>` - enhancing beyond the normal string type and limiting
* to the built-in browser supported values
*/
encType?: "application/x-www-form-urlencoded" | "multipart/form-data" | "text/plain";
/**
* Normal `<form action>` but supports React Router's relative paths.
*/
action?: string;
/**
* Determines whether the form action is relative to the route hierarchy or
* the pathname. Use this if you want to opt out of navigating the route
* hierarchy and want to instead route based on /-delimited URL segments
*/
relative?: RelativeRoutingType;
/**
* Prevent the scroll position from resetting to the top of the viewport on
* completion of the navigation when using the <ScrollRestoration> component
*/
preventScrollReset?: boolean;
/**
* A function to call when the form is submitted. If you call
* `event.preventDefault()` then this form will not do anything.
*/
onSubmit?: React.FormEventHandler<HTMLFormElement>;
}
export interface FormProps extends FetcherFormProps {
/**
* Forces a full document navigation instead of a fetch.
*/
reloadDocument?: boolean;
/**
* Replaces the current entry in the browser history stack when the form
* navigates. Use this if you don't want the user to be able to click "back"
* to the page with the form on it.
*/
replace?: boolean;
/**
* State object to add to the history stack entry for this navigation
*/
state?: any;
}
/**
* A `@remix-run/router`-aware `<form>`. It behaves like a normal form except
* that the interaction with the server is with `fetch` instead of new document
* requests, allowing components to add nicer UX to the page as the form is
* submitted and returns with data.
*/
export declare const Form: React.ForwardRefExoticComponent<FormProps & React.RefAttributes<HTMLFormElement>>;
export interface ScrollRestorationProps {
getKey?: GetScrollRestorationKeyFunction;
storageKey?: string;
}
/**
* This component will emulate the browser's scroll restoration on location
* changes.
*/
export declare function ScrollRestoration({ getKey, storageKey, }: ScrollRestorationProps): null;
export declare namespace ScrollRestoration {
var displayName: string;
}
/**
* Handles the click behavior for router `<Link>` components. This is useful if
* you need to create custom `<Link>` components with the same click behavior we
* use in our exported `<Link>`.
*/
export declare function useLinkClickHandler<E extends Element = HTMLAnchorElement>(to: To, { target, replace: replaceProp, state, preventScrollReset, relative, }?: {
target?: React.HTMLAttributeAnchorTarget;
replace?: boolean;
state?: any;
preventScrollReset?: boolean;
relative?: RelativeRoutingType;
}): (event: React.MouseEvent<E, MouseEvent>) => void;
/**
* A convenient wrapper for reading and writing search parameters via the
* URLSearchParams interface.
*/
export declare function useSearchParams(defaultInit?: URLSearchParamsInit): [URLSearchParams, SetURLSearchParams];
export type SetURLSearchParams = (nextInit?: URLSearchParamsInit | ((prev: URLSearchParams) => URLSearchParamsInit), navigateOpts?: NavigateOptions) => void;
/**
* Submits a HTML `<form>` to the server without reloading the page.
*/
export interface SubmitFunction {
(
/**
* Specifies the `<form>` to be submitted to the server, a specific
* `<button>` or `<input type="submit">` to use to submit the form, or some
* arbitrary data to submit.
*
* Note: When using a `<button>` its `name` and `value` will also be
* included in the form data that is submitted.
*/
target: SubmitTarget,
/**
* Options that override the `<form>`'s own attributes. Required when
* submitting arbitrary data without a backing `<form>`.
*/
options?: SubmitOptions): void;
}
/**
* Submits a fetcher `<form>` to the server without reloading the page.
*/
export interface FetcherSubmitFunction {
(target: SubmitTarget, options?: Omit<SubmitOptions, "replace" | "state">): void;
}
/**
* Returns a function that may be used to programmatically submit a form (or
* some arbitrary data) to the server.
*/
export declare function useSubmit(): SubmitFunction;
export declare function useFormAction(action?: string, { relative }?: {
relative?: RelativeRoutingType;
}): string;
declare function createFetcherForm(fetcherKey: string, routeId: string): React.ForwardRefExoticComponent<FetcherFormProps & React.RefAttributes<HTMLFormElement>>;
export type FetcherWithComponents<TData> = Fetcher<TData> & {
Form: ReturnType<typeof createFetcherForm>;
submit: FetcherSubmitFunction;
load: (href: string) => void;
};
/**
* Interacts with route loaders and actions without causing a navigation. Great
* for any interaction that stays on the same page.
*/
export declare function useFetcher<TData = any>(): FetcherWithComponents<TData>;
/**
* Provides all fetchers currently on the page. Useful for layouts and parent
* routes that need to provide pending/optimistic UI regarding the fetch.
*/
export declare function useFetchers(): Fetcher[];
/**
* When rendered inside a RouterProvider, will restore scroll positions on navigations
*/
declare function useScrollRestoration({ getKey, storageKey, }?: {
getKey?: GetScrollRestorationKeyFunction;
storageKey?: string;
}): void;
export { useScrollRestoration as UNSAFE_useScrollRestoration };
/**
* Setup a callback to be fired on the window's `beforeunload` event. This is
* useful for saving some data to `window.localStorage` just before the page
* refreshes.
*
* Note: The `callback` argument should be a function created with
* `React.useCallback()`.
*/
export declare function useBeforeUnload(callback: (event: BeforeUnloadEvent) => any, options?: {
capture?: boolean;
}): void;
/**
* Wrapper around useBlocker to show a window.confirm prompt to users instead
* of building a custom UI with useBlocker.
*
* Warning: This has *a lot of rough edges* and behaves very differently (and
* very incorrectly in some cases) across browsers if user click addition
* back/forward navigations while the confirm is open. Use at your own risk.
*/
declare function usePrompt({ when, message }: {
when: boolean;
message: string;
}): void;
export { usePrompt as unstable_usePrompt };
export type * from "react-router";
export * from "react-router";
/**
* React Router DOM v0.0.0-experimental-4286521e
* React Router DOM v0.0.0-experimental-42a5853ef
*

@@ -4,0 +4,0 @@ * Copyright (c) Remix Software Inc.

/**
* React Router DOM v0.0.0-experimental-4286521e
* React Router DOM v0.0.0-experimental-42a5853ef
*

@@ -11,1089 +11,3 @@ * Copyright (c) Remix Software Inc.

*/
import * as React from 'react';
import { UNSAFE_mapRouteProperties, Router, UNSAFE_NavigationContext, useHref, useResolvedPath, useLocation, UNSAFE_DataRouterStateContext, useNavigate, createPath, UNSAFE_useRouteId, UNSAFE_RouteContext, useMatches, useNavigation, unstable_useBlocker, UNSAFE_DataRouterContext } from 'react-router';
export { AbortedDeferredError, Await, MemoryRouter, Navigate, NavigationType, Outlet, Route, Router, RouterProvider, Routes, UNSAFE_DataRouterContext, UNSAFE_DataRouterStateContext, UNSAFE_LocationContext, UNSAFE_NavigationContext, UNSAFE_RouteContext, UNSAFE_useRouteId, createMemoryRouter, createPath, createRoutesFromChildren, createRoutesFromElements, defer, generatePath, isRouteErrorResponse, json, matchPath, matchRoutes, parsePath, redirect, redirectDocument, renderMatches, resolvePath, unstable_useBlocker, useActionData, useAsyncError, useAsyncValue, useHref, useInRouterContext, useLoaderData, useLocation, useMatch, useMatches, useNavigate, useNavigation, useNavigationType, useOutlet, useOutletContext, useParams, useResolvedPath, useRevalidator, useRouteError, useRouteLoaderData, useRoutes } from 'react-router';
import { stripBasename, UNSAFE_warning, createRouter, createBrowserHistory, createHashHistory, ErrorResponse, UNSAFE_invariant, joinPaths } from '@remix-run/router';
const defaultMethod = "get";
const defaultEncType = "application/x-www-form-urlencoded";
function isHtmlElement(object) {
return object != null && typeof object.tagName === "string";
}
function isButtonElement(object) {
return isHtmlElement(object) && object.tagName.toLowerCase() === "button";
}
function isFormElement(object) {
return isHtmlElement(object) && object.tagName.toLowerCase() === "form";
}
function isInputElement(object) {
return isHtmlElement(object) && object.tagName.toLowerCase() === "input";
}
function isModifiedEvent(event) {
return !!(event.metaKey || event.altKey || event.ctrlKey || event.shiftKey);
}
function shouldProcessLinkClick(event, target) {
return event.button === 0 && (
// Ignore everything but left clicks
!target || target === "_self") &&
// Let browser handle "target=_blank" etc.
!isModifiedEvent(event) // Ignore clicks with modifier keys
;
}
/**
* Creates a URLSearchParams object using the given initializer.
*
* This is identical to `new URLSearchParams(init)` except it also
* supports arrays as values in the object form of the initializer
* instead of just strings. This is convenient when you need multiple
* values for a given key, but don't want to use an array initializer.
*
* For example, instead of:
*
* let searchParams = new URLSearchParams([
* ['sort', 'name'],
* ['sort', 'price']
* ]);
*
* you can do:
*
* let searchParams = createSearchParams({
* sort: ['name', 'price']
* });
*/
function createSearchParams(init = "") {
return new URLSearchParams(typeof init === "string" || Array.isArray(init) || init instanceof URLSearchParams ? init : Object.keys(init).reduce((memo, key) => {
let value = init[key];
return memo.concat(Array.isArray(value) ? value.map(v => [key, v]) : [[key, value]]);
}, []));
}
function getSearchParamsForLocation(locationSearch, defaultSearchParams) {
let searchParams = createSearchParams(locationSearch);
if (defaultSearchParams) {
// Use `defaultSearchParams.forEach(...)` here instead of iterating of
// `defaultSearchParams.keys()` to work-around a bug in Firefox related to
// web extensions. Relevant Bugzilla tickets:
// https://bugzilla.mozilla.org/show_bug.cgi?id=1414602
// https://bugzilla.mozilla.org/show_bug.cgi?id=1023984
defaultSearchParams.forEach((_, key) => {
if (!searchParams.has(key)) {
defaultSearchParams.getAll(key).forEach(value => {
searchParams.append(key, value);
});
}
});
}
return searchParams;
}
// Thanks https://github.com/sindresorhus/type-fest!
// One-time check for submitter support
let _formDataSupportsSubmitter = null;
function isFormDataSubmitterSupported() {
if (_formDataSupportsSubmitter === null) {
try {
new FormData(document.createElement("form"),
// @ts-expect-error if FormData supports the submitter parameter, this will throw
0);
_formDataSupportsSubmitter = false;
} catch (e) {
_formDataSupportsSubmitter = true;
}
}
return _formDataSupportsSubmitter;
}
const supportedFormEncTypes = new Set(["application/x-www-form-urlencoded", "multipart/form-data", "text/plain"]);
function getFormEncType(encType) {
if (encType != null && !supportedFormEncTypes.has(encType)) {
UNSAFE_warning(false, `"${encType}" is not a valid \`encType\` for \`<Form>\`/\`<fetcher.Form>\` ` + `and will default to "${defaultEncType}"`) ;
return null;
}
return encType;
}
function getFormSubmissionInfo(target, basename) {
let method;
let action;
let encType;
let formData;
let body;
if (isFormElement(target)) {
// When grabbing the action from the element, it will have had the basename
// prefixed to ensure non-JS scenarios work, so strip it since we'll
// re-prefix in the router
let attr = target.getAttribute("action");
action = attr ? stripBasename(attr, basename) : null;
method = target.getAttribute("method") || defaultMethod;
encType = getFormEncType(target.getAttribute("enctype")) || defaultEncType;
formData = new FormData(target);
} else if (isButtonElement(target) || isInputElement(target) && (target.type === "submit" || target.type === "image")) {
let form = target.form;
if (form == null) {
throw new Error(`Cannot submit a <button> or <input type="submit"> without a <form>`);
}
// <button>/<input type="submit"> may override attributes of <form>
// When grabbing the action from the element, it will have had the basename
// prefixed to ensure non-JS scenarios work, so strip it since we'll
// re-prefix in the router
let attr = target.getAttribute("formaction") || form.getAttribute("action");
action = attr ? stripBasename(attr, basename) : null;
method = target.getAttribute("formmethod") || form.getAttribute("method") || defaultMethod;
encType = getFormEncType(target.getAttribute("formenctype")) || getFormEncType(form.getAttribute("enctype")) || defaultEncType;
// Build a FormData object populated from a form and submitter
formData = new FormData(form, target);
// If this browser doesn't support the `FormData(el, submitter)` format,
// then tack on the submitter value at the end. This is a lightweight
// solution that is not 100% spec compliant. For complete support in older
// browsers, consider using the `formdata-submitter-polyfill` package
if (!isFormDataSubmitterSupported()) {
let {
name,
type,
value
} = target;
if (type === "image") {
let prefix = name ? `${name}.` : "";
formData.append(`${prefix}x`, "0");
formData.append(`${prefix}y`, "0");
} else if (name) {
formData.append(name, value);
}
}
} else if (isHtmlElement(target)) {
throw new Error(`Cannot submit element that is not <form>, <button>, or ` + `<input type="submit|image">`);
} else {
method = defaultMethod;
action = null;
encType = defaultEncType;
body = target;
}
// Send body for <Form encType="text/plain" so we encode it into text
if (formData && encType === "text/plain") {
body = formData;
formData = undefined;
}
return {
action,
method: method.toLowerCase(),
encType,
formData,
body
};
}
/**
* NOTE: If you refactor this to split up the modules into separate files,
* you'll need to update the rollup config for react-router-dom-v5-compat.
*/
//#endregion
////////////////////////////////////////////////////////////////////////////////
//#region Routers
////////////////////////////////////////////////////////////////////////////////
function createBrowserRouter(routes, opts) {
return createRouter({
basename: opts?.basename,
future: {
...opts?.future,
v7_prependBasename: true
},
history: createBrowserHistory({
window: opts?.window
}),
hydrationData: opts?.hydrationData || parseHydrationData(),
routes,
mapRouteProperties: UNSAFE_mapRouteProperties
}).initialize();
}
function createHashRouter(routes, opts) {
return createRouter({
basename: opts?.basename,
future: {
...opts?.future,
v7_prependBasename: true
},
history: createHashHistory({
window: opts?.window
}),
hydrationData: opts?.hydrationData || parseHydrationData(),
routes,
mapRouteProperties: UNSAFE_mapRouteProperties
}).initialize();
}
function parseHydrationData() {
let state = window?.__staticRouterHydrationData;
if (state && state.errors) {
state = {
...state,
errors: deserializeErrors(state.errors)
};
}
return state;
}
function deserializeErrors(errors) {
if (!errors) return null;
let entries = Object.entries(errors);
let serialized = {};
for (let [key, val] of entries) {
// Hey you! If you change this, please change the corresponding logic in
// serializeErrors in react-router-dom/server.tsx :)
if (val && val.__type === "RouteErrorResponse") {
serialized[key] = new ErrorResponse(val.status, val.statusText, val.data, val.internal === true);
} else if (val && val.__type === "Error") {
// Attempt to reconstruct the right type of Error (i.e., ReferenceError)
if (val.__subType) {
let ErrorConstructor = window[val.__subType];
if (typeof ErrorConstructor === "function") {
try {
// @ts-expect-error
let error = new ErrorConstructor(val.message);
// Wipe away the client-side stack trace. Nothing to fill it in with
// because we don't serialize SSR stack traces for security reasons
error.stack = "";
serialized[key] = error;
} catch (e) {
// no-op - fall through and create a normal Error
}
}
}
if (serialized[key] == null) {
let error = new Error(val.message);
// Wipe away the client-side stack trace. Nothing to fill it in with
// because we don't serialize SSR stack traces for security reasons
error.stack = "";
serialized[key] = error;
}
} else {
serialized[key] = val;
}
}
return serialized;
}
//#endregion
////////////////////////////////////////////////////////////////////////////////
//#region Components
////////////////////////////////////////////////////////////////////////////////
/**
Webpack + React 17 fails to compile on any of the following because webpack
complains that `startTransition` doesn't exist in `React`:
* import { startTransition } from "react"
* import * as React from from "react";
"startTransition" in React ? React.startTransition(() => setState()) : setState()
* import * as React from from "react";
"startTransition" in React ? React["startTransition"](() => setState()) : setState()
Moving it to a constant such as the following solves the Webpack/React 17 issue:
* import * as React from from "react";
const START_TRANSITION = "startTransition";
START_TRANSITION in React ? React[START_TRANSITION](() => setState()) : setState()
However, that introduces webpack/terser minification issues in production builds
in React 18 where minification/obfuscation ends up removing the call of
React.startTransition entirely from the first half of the ternary. Grabbing
this exported reference once up front resolves that issue.
See https://github.com/remix-run/react-router/issues/10579
*/
const START_TRANSITION = "startTransition";
const startTransitionImpl = React[START_TRANSITION];
/**
* A `<Router>` for use in web browsers. Provides the cleanest URLs.
*/
function BrowserRouter({
basename,
children,
future,
window
}) {
let historyRef = React.useRef();
if (historyRef.current == null) {
historyRef.current = createBrowserHistory({
window,
v5Compat: true
});
}
let history = historyRef.current;
let [state, setStateImpl] = React.useState({
action: history.action,
location: history.location
});
let {
v7_startTransition
} = future || {};
let setState = React.useCallback(newState => {
v7_startTransition && startTransitionImpl ? startTransitionImpl(() => setStateImpl(newState)) : setStateImpl(newState);
}, [setStateImpl, v7_startTransition]);
React.useLayoutEffect(() => history.listen(setState), [history, setState]);
return /*#__PURE__*/React.createElement(Router, {
basename: basename,
children: children,
location: state.location,
navigationType: state.action,
navigator: history
});
}
/**
* A `<Router>` for use in web browsers. Stores the location in the hash
* portion of the URL so it is not sent to the server.
*/
function HashRouter({
basename,
children,
future,
window
}) {
let historyRef = React.useRef();
if (historyRef.current == null) {
historyRef.current = createHashHistory({
window,
v5Compat: true
});
}
let history = historyRef.current;
let [state, setStateImpl] = React.useState({
action: history.action,
location: history.location
});
let {
v7_startTransition
} = future || {};
let setState = React.useCallback(newState => {
v7_startTransition && startTransitionImpl ? startTransitionImpl(() => setStateImpl(newState)) : setStateImpl(newState);
}, [setStateImpl, v7_startTransition]);
React.useLayoutEffect(() => history.listen(setState), [history, setState]);
return /*#__PURE__*/React.createElement(Router, {
basename: basename,
children: children,
location: state.location,
navigationType: state.action,
navigator: history
});
}
/**
* A `<Router>` that accepts a pre-instantiated history object. It's important
* to note that using your own history object is highly discouraged and may add
* two versions of the history library to your bundles unless you use the same
* version of the history library that React Router uses internally.
*/
function HistoryRouter({
basename,
children,
future,
history
}) {
let [state, setStateImpl] = React.useState({
action: history.action,
location: history.location
});
let {
v7_startTransition
} = future || {};
let setState = React.useCallback(newState => {
v7_startTransition && startTransitionImpl ? startTransitionImpl(() => setStateImpl(newState)) : setStateImpl(newState);
}, [setStateImpl, v7_startTransition]);
React.useLayoutEffect(() => history.listen(setState), [history, setState]);
return /*#__PURE__*/React.createElement(Router, {
basename: basename,
children: children,
location: state.location,
navigationType: state.action,
navigator: history
});
}
{
HistoryRouter.displayName = "unstable_HistoryRouter";
}
const isBrowser = typeof window !== "undefined" && typeof window.document !== "undefined" && typeof window.document.createElement !== "undefined";
const ABSOLUTE_URL_REGEX = /^(?:[a-z][a-z0-9+.-]*:|\/\/)/i;
/**
* The public API for rendering a history-aware <a>.
*/
const Link = /*#__PURE__*/React.forwardRef(function LinkWithRef({
onClick,
relative,
reloadDocument,
replace,
state,
target,
to,
preventScrollReset,
...rest
}, ref) {
let {
basename
} = React.useContext(UNSAFE_NavigationContext);
// Rendered into <a href> for absolute URLs
let absoluteHref;
let isExternal = false;
if (typeof to === "string" && ABSOLUTE_URL_REGEX.test(to)) {
// Render the absolute href server- and client-side
absoluteHref = to;
// Only check for external origins client-side
if (isBrowser) {
try {
let currentUrl = new URL(window.location.href);
let targetUrl = to.startsWith("//") ? new URL(currentUrl.protocol + to) : new URL(to);
let path = stripBasename(targetUrl.pathname, basename);
if (targetUrl.origin === currentUrl.origin && path != null) {
// Strip the protocol/origin/basename for same-origin absolute URLs
to = path + targetUrl.search + targetUrl.hash;
} else {
isExternal = true;
}
} catch (e) {
// We can't do external URL detection without a valid URL
UNSAFE_warning(false, `<Link to="${to}"> contains an invalid URL which will probably break ` + `when clicked - please update to a valid URL path.`) ;
}
}
}
// Rendered into <a href> for relative URLs
let href = useHref(to, {
relative
});
let internalOnClick = useLinkClickHandler(to, {
replace,
state,
target,
preventScrollReset,
relative
});
function handleClick(event) {
if (onClick) onClick(event);
if (!event.defaultPrevented) {
internalOnClick(event);
}
}
return (
/*#__PURE__*/
// eslint-disable-next-line jsx-a11y/anchor-has-content
React.createElement("a", Object.assign({}, rest, {
href: absoluteHref || href,
onClick: isExternal || reloadDocument ? onClick : handleClick,
ref: ref,
target: target
}))
);
});
{
Link.displayName = "Link";
}
/**
* A <Link> wrapper that knows if it's "active" or not.
*/
const NavLink = /*#__PURE__*/React.forwardRef(function NavLinkWithRef({
"aria-current": ariaCurrentProp = "page",
caseSensitive = false,
className: classNameProp = "",
end = false,
style: styleProp,
to,
children,
...rest
}, ref) {
let path = useResolvedPath(to, {
relative: rest.relative
});
let location = useLocation();
let routerState = React.useContext(UNSAFE_DataRouterStateContext);
let {
navigator
} = React.useContext(UNSAFE_NavigationContext);
let toPathname = navigator.encodeLocation ? navigator.encodeLocation(path).pathname : path.pathname;
let locationPathname = location.pathname;
let nextLocationPathname = routerState && routerState.navigation && routerState.navigation.location ? routerState.navigation.location.pathname : null;
if (!caseSensitive) {
locationPathname = locationPathname.toLowerCase();
nextLocationPathname = nextLocationPathname ? nextLocationPathname.toLowerCase() : null;
toPathname = toPathname.toLowerCase();
}
let isActive = locationPathname === toPathname || !end && locationPathname.startsWith(toPathname) && locationPathname.charAt(toPathname.length) === "/";
let isPending = nextLocationPathname != null && (nextLocationPathname === toPathname || !end && nextLocationPathname.startsWith(toPathname) && nextLocationPathname.charAt(toPathname.length) === "/");
let ariaCurrent = isActive ? ariaCurrentProp : undefined;
let className;
if (typeof classNameProp === "function") {
className = classNameProp({
isActive,
isPending
});
} else {
// If the className prop is not a function, we use a default `active`
// class for <NavLink />s that are active. In v5 `active` was the default
// value for `activeClassName`, but we are removing that API and can still
// use the old default behavior for a cleaner upgrade path and keep the
// simple styling rules working as they currently do.
className = [classNameProp, isActive ? "active" : null, isPending ? "pending" : null].filter(Boolean).join(" ");
}
let style = typeof styleProp === "function" ? styleProp({
isActive,
isPending
}) : styleProp;
return /*#__PURE__*/React.createElement(Link, Object.assign({}, rest, {
"aria-current": ariaCurrent,
className: className,
ref: ref,
style: style,
to: to
}), typeof children === "function" ? children({
isActive,
isPending
}) : children);
});
{
NavLink.displayName = "NavLink";
}
/**
* A `@remix-run/router`-aware `<form>`. It behaves like a normal form except
* that the interaction with the server is with `fetch` instead of new document
* requests, allowing components to add nicer UX to the page as the form is
* submitted and returns with data.
*/
const Form = /*#__PURE__*/React.forwardRef((props, ref) => {
let submit = useSubmit();
return /*#__PURE__*/React.createElement(FormImpl, Object.assign({}, props, {
submit: submit,
ref: ref
}));
});
{
Form.displayName = "Form";
}
const FormImpl = /*#__PURE__*/React.forwardRef(({
reloadDocument,
replace,
state,
method: _method = defaultMethod,
action,
onSubmit,
submit,
relative,
preventScrollReset,
...props
}, forwardedRef) => {
let formMethod = _method.toLowerCase() === "get" ? "get" : "post";
let formAction = useFormAction(action, {
relative
});
let submitHandler = event => {
onSubmit && onSubmit(event);
if (event.defaultPrevented) return;
event.preventDefault();
let submitter = event.nativeEvent.submitter;
let submitMethod = submitter?.getAttribute("formmethod") || _method;
submit(submitter || event.currentTarget, {
method: submitMethod,
replace,
state,
relative,
preventScrollReset
});
};
return /*#__PURE__*/React.createElement("form", Object.assign({
ref: forwardedRef,
method: formMethod,
action: formAction,
onSubmit: reloadDocument ? onSubmit : submitHandler
}, props));
});
{
FormImpl.displayName = "FormImpl";
}
/**
* This component will emulate the browser's scroll restoration on location
* changes.
*/
function ScrollRestoration({
getKey,
storageKey
}) {
useScrollRestoration({
getKey,
storageKey
});
return null;
}
{
ScrollRestoration.displayName = "ScrollRestoration";
}
//#endregion
////////////////////////////////////////////////////////////////////////////////
//#region Hooks
////////////////////////////////////////////////////////////////////////////////
var DataRouterHook = /*#__PURE__*/function (DataRouterHook) {
DataRouterHook["UseScrollRestoration"] = "useScrollRestoration";
DataRouterHook["UseSubmit"] = "useSubmit";
DataRouterHook["UseSubmitFetcher"] = "useSubmitFetcher";
DataRouterHook["UseFetcher"] = "useFetcher";
return DataRouterHook;
}(DataRouterHook || {});
var DataRouterStateHook = /*#__PURE__*/function (DataRouterStateHook) {
DataRouterStateHook["UseFetchers"] = "useFetchers";
DataRouterStateHook["UseScrollRestoration"] = "useScrollRestoration";
return DataRouterStateHook;
}(DataRouterStateHook || {});
function getDataRouterConsoleError(hookName) {
return `${hookName} must be used within a data router. See https://reactrouter.com/routers/picking-a-router.`;
}
function useDataRouterContext(hookName) {
let ctx = React.useContext(UNSAFE_DataRouterContext);
!ctx ? UNSAFE_invariant(false, getDataRouterConsoleError(hookName)) : void 0;
return ctx;
}
function useDataRouterState(hookName) {
let state = React.useContext(UNSAFE_DataRouterStateContext);
!state ? UNSAFE_invariant(false, getDataRouterConsoleError(hookName)) : void 0;
return state;
}
/**
* Handles the click behavior for router `<Link>` components. This is useful if
* you need to create custom `<Link>` components with the same click behavior we
* use in our exported `<Link>`.
*/
function useLinkClickHandler(to, {
target,
replace: replaceProp,
state,
preventScrollReset,
relative
} = {}) {
let navigate = useNavigate();
let location = useLocation();
let path = useResolvedPath(to, {
relative
});
return React.useCallback(event => {
if (shouldProcessLinkClick(event, target)) {
event.preventDefault();
// If the URL hasn't changed, a regular <a> will do a replace instead of
// a push, so do the same here unless the replace prop is explicitly set
let replace = replaceProp !== undefined ? replaceProp : createPath(location) === createPath(path);
navigate(to, {
replace,
state,
preventScrollReset,
relative
});
}
}, [location, navigate, path, replaceProp, state, target, to, preventScrollReset, relative]);
}
/**
* A convenient wrapper for reading and writing search parameters via the
* URLSearchParams interface.
*/
function useSearchParams(defaultInit) {
UNSAFE_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\n\n` + `If you're unsure how to load polyfills, we recommend you check out ` + `https://polyfill.io/v3/ which provides some recommendations about how ` + `to load polyfills only for users that need them, instead of for every ` + `user.`) ;
let defaultSearchParamsRef = React.useRef(createSearchParams(defaultInit));
let hasSetSearchParamsRef = React.useRef(false);
let location = useLocation();
let searchParams = React.useMemo(() =>
// Only merge in the defaults if we haven't yet called setSearchParams.
// Once we call that we want those to take precedence, otherwise you can't
// remove a param with setSearchParams({}) if it has an initial value
getSearchParamsForLocation(location.search, hasSetSearchParamsRef.current ? null : defaultSearchParamsRef.current), [location.search]);
let navigate = useNavigate();
let setSearchParams = React.useCallback((nextInit, navigateOptions) => {
const newSearchParams = createSearchParams(typeof nextInit === "function" ? nextInit(searchParams) : nextInit);
hasSetSearchParamsRef.current = true;
navigate("?" + newSearchParams, navigateOptions);
}, [navigate, searchParams]);
return [searchParams, setSearchParams];
}
/**
* Submits a HTML `<form>` to the server without reloading the page.
*/
/**
* Submits a fetcher `<form>` to the server without reloading the page.
*/
function validateClientSideSubmission() {
if (typeof document === "undefined") {
throw new Error("You are calling submit during the server render. " + "Try calling submit within a `useEffect` or callback instead.");
}
}
/**
* Returns a function that may be used to programmatically submit a form (or
* some arbitrary data) to the server.
*/
function useSubmit() {
let {
router
} = useDataRouterContext(DataRouterHook.UseSubmit);
let {
basename
} = React.useContext(UNSAFE_NavigationContext);
let currentRouteId = UNSAFE_useRouteId();
return React.useCallback((target, options = {}) => {
validateClientSideSubmission();
let {
action,
method,
encType,
formData,
body
} = getFormSubmissionInfo(target, basename);
router.navigate(options.action || action, {
preventScrollReset: options.preventScrollReset,
formData,
body,
formMethod: options.method || method,
formEncType: options.encType || encType,
replace: options.replace,
state: options.state,
fromRouteId: currentRouteId
});
}, [router, basename, currentRouteId]);
}
/**
* Returns the implementation for fetcher.submit
*/
function useSubmitFetcher(fetcherKey, fetcherRouteId) {
let {
router
} = useDataRouterContext(DataRouterHook.UseSubmitFetcher);
let {
basename
} = React.useContext(UNSAFE_NavigationContext);
return React.useCallback((target, options = {}) => {
validateClientSideSubmission();
let {
action,
method,
encType,
formData,
body
} = getFormSubmissionInfo(target, basename);
!(fetcherRouteId != null) ? UNSAFE_invariant(false, "No routeId available for useFetcher()") : void 0;
router.fetch(fetcherKey, fetcherRouteId, options.action || action, {
preventScrollReset: options.preventScrollReset,
formData,
body,
formMethod: options.method || method,
formEncType: options.encType || encType
});
}, [router, basename, fetcherKey, fetcherRouteId]);
}
// v7: Eventually we should deprecate this entirely in favor of using the
// router method directly?
function useFormAction(action, {
relative
} = {}) {
let {
basename
} = React.useContext(UNSAFE_NavigationContext);
let routeContext = React.useContext(UNSAFE_RouteContext);
!routeContext ? UNSAFE_invariant(false, "useFormAction must be used inside a RouteContext") : void 0;
let [match] = routeContext.matches.slice(-1);
// Shallow clone path so we can modify it below, otherwise we modify the
// object referenced by useMemo inside useResolvedPath
let path = {
...useResolvedPath(action ? action : ".", {
relative
})
};
// Previously we set the default action to ".". The problem with this is that
// `useResolvedPath(".")` excludes search params of the resolved URL. This is
// the intended behavior of when "." is specifically provided as
// the form action, but inconsistent w/ browsers when the action is omitted.
// https://github.com/remix-run/remix/issues/927
let location = useLocation();
if (action == null) {
// Safe to write to this directly here since if action was undefined, we
// would have called useResolvedPath(".") which will never include a search
path.search = location.search;
// When grabbing search params from the URL, remove the automatically
// inserted ?index param so we match the useResolvedPath search behavior
// which would not include ?index
if (match.route.index) {
let params = new URLSearchParams(path.search);
params.delete("index");
path.search = params.toString() ? `?${params.toString()}` : "";
}
}
if ((!action || action === ".") && match.route.index) {
path.search = path.search ? path.search.replace(/^\?/, "?index&") : "?index";
}
// If we're operating within a basename, prepend it to the pathname prior
// to creating the form action. If this is a root navigation, then just use
// the raw basename which allows the basename to have full control over the
// presence of a trailing slash on root actions
if (basename !== "/") {
path.pathname = path.pathname === "/" ? basename : joinPaths([basename, path.pathname]);
}
return createPath(path);
}
function createFetcherForm(fetcherKey, routeId) {
let FetcherForm = /*#__PURE__*/React.forwardRef((props, ref) => {
let submit = useSubmitFetcher(fetcherKey, routeId);
return /*#__PURE__*/React.createElement(FormImpl, Object.assign({}, props, {
ref: ref,
submit: submit
}));
});
{
FetcherForm.displayName = "fetcher.Form";
}
return FetcherForm;
}
let fetcherId = 0;
/**
* Interacts with route loaders and actions without causing a navigation. Great
* for any interaction that stays on the same page.
*/
function useFetcher() {
let {
router
} = useDataRouterContext(DataRouterHook.UseFetcher);
let route = React.useContext(UNSAFE_RouteContext);
!route ? UNSAFE_invariant(false, `useFetcher must be used inside a RouteContext`) : void 0;
let routeId = route.matches[route.matches.length - 1]?.route.id;
!(routeId != null) ? UNSAFE_invariant(false, `useFetcher can only be used on routes that contain a unique "id"`) : void 0;
let [fetcherKey] = React.useState(() => String(++fetcherId));
let [Form] = React.useState(() => {
!routeId ? UNSAFE_invariant(false, `No routeId available for fetcher.Form()`) : void 0;
return createFetcherForm(fetcherKey, routeId);
});
let [load] = React.useState(() => href => {
!router ? UNSAFE_invariant(false, "No router available for fetcher.load()") : void 0;
!routeId ? UNSAFE_invariant(false, "No routeId available for fetcher.load()") : void 0;
router.fetch(fetcherKey, routeId, href);
});
let submit = useSubmitFetcher(fetcherKey, routeId);
let fetcher = router.getFetcher(fetcherKey);
let fetcherWithComponents = React.useMemo(() => ({
Form,
submit,
load,
...fetcher
}), [fetcher, Form, submit, load]);
React.useEffect(() => {
// Is this busted when the React team gets real weird and calls effects
// twice on mount? We really just need to garbage collect here when this
// fetcher is no longer around.
return () => {
if (!router) {
console.warn(`No router available to clean up from useFetcher()`);
return;
}
router.deleteFetcher(fetcherKey);
};
}, [router, fetcherKey]);
return fetcherWithComponents;
}
/**
* Provides all fetchers currently on the page. Useful for layouts and parent
* routes that need to provide pending/optimistic UI regarding the fetch.
*/
function useFetchers() {
let state = useDataRouterState(DataRouterStateHook.UseFetchers);
return [...state.fetchers.values()];
}
const SCROLL_RESTORATION_STORAGE_KEY = "react-router-scroll-positions";
let savedScrollPositions = {};
/**
* When rendered inside a RouterProvider, will restore scroll positions on navigations
*/
function useScrollRestoration({
getKey,
storageKey
} = {}) {
let {
router
} = useDataRouterContext(DataRouterHook.UseScrollRestoration);
let {
restoreScrollPosition,
preventScrollReset
} = useDataRouterState(DataRouterStateHook.UseScrollRestoration);
let {
basename
} = React.useContext(UNSAFE_NavigationContext);
let location = useLocation();
let matches = useMatches();
let navigation = useNavigation();
// Trigger manual scroll restoration while we're active
React.useEffect(() => {
window.history.scrollRestoration = "manual";
return () => {
window.history.scrollRestoration = "auto";
};
}, []);
// Save positions on pagehide
usePageHide(React.useCallback(() => {
if (navigation.state === "idle") {
let key = (getKey ? getKey(location, matches) : null) || location.key;
savedScrollPositions[key] = window.scrollY;
}
sessionStorage.setItem(storageKey || SCROLL_RESTORATION_STORAGE_KEY, JSON.stringify(savedScrollPositions));
window.history.scrollRestoration = "auto";
}, [storageKey, getKey, navigation.state, location, matches]));
// Read in any saved scroll locations
if (typeof document !== "undefined") {
// eslint-disable-next-line react-hooks/rules-of-hooks
React.useLayoutEffect(() => {
try {
let sessionPositions = sessionStorage.getItem(storageKey || SCROLL_RESTORATION_STORAGE_KEY);
if (sessionPositions) {
savedScrollPositions = JSON.parse(sessionPositions);
}
} catch (e) {
// no-op, use default empty object
}
}, [storageKey]);
// Enable scroll restoration in the router
// eslint-disable-next-line react-hooks/rules-of-hooks
React.useLayoutEffect(() => {
let getKeyWithoutBasename = getKey && basename !== "/" ? (location, matches) => getKey(
// Strip the basename to match useLocation()
{
...location,
pathname: stripBasename(location.pathname, basename) || location.pathname
}, matches) : getKey;
let disableScrollRestoration = router?.enableScrollRestoration(savedScrollPositions, () => window.scrollY, getKeyWithoutBasename);
return () => disableScrollRestoration && disableScrollRestoration();
}, [router, basename, getKey]);
// Restore scrolling when state.restoreScrollPosition changes
// eslint-disable-next-line react-hooks/rules-of-hooks
React.useLayoutEffect(() => {
// Explicit false means don't do anything (used for submissions)
if (restoreScrollPosition === false) {
return;
}
// been here before, scroll to it
if (typeof restoreScrollPosition === "number") {
window.scrollTo(0, restoreScrollPosition);
return;
}
// try to scroll to the hash
if (location.hash) {
let el = document.getElementById(decodeURIComponent(location.hash.slice(1)));
if (el) {
el.scrollIntoView();
return;
}
}
// Don't reset if this navigation opted out
if (preventScrollReset === true) {
return;
}
// otherwise go to the top on new locations
window.scrollTo(0, 0);
}, [location, restoreScrollPosition, preventScrollReset]);
}
}
/**
* Setup a callback to be fired on the window's `beforeunload` event. This is
* useful for saving some data to `window.localStorage` just before the page
* refreshes.
*
* Note: The `callback` argument should be a function created with
* `React.useCallback()`.
*/
function useBeforeUnload(callback, options) {
let {
capture
} = options || {};
React.useEffect(() => {
let opts = capture != null ? {
capture
} : undefined;
window.addEventListener("beforeunload", callback, opts);
return () => {
window.removeEventListener("beforeunload", callback, opts);
};
}, [callback, capture]);
}
/**
* Setup a callback to be fired on the window's `pagehide` event. This is
* useful for saving some data to `window.localStorage` just before the page
* refreshes. This event is better supported than beforeunload across browsers.
*
* Note: The `callback` argument should be a function created with
* `React.useCallback()`.
*/
function usePageHide(callback, options) {
let {
capture
} = options || {};
React.useEffect(() => {
let opts = capture != null ? {
capture
} : undefined;
window.addEventListener("pagehide", callback, opts);
return () => {
window.removeEventListener("pagehide", callback, opts);
};
}, [callback, capture]);
}
/**
* Wrapper around useBlocker to show a window.confirm prompt to users instead
* of building a custom UI with useBlocker.
*
* Warning: This has *a lot of rough edges* and behaves very differently (and
* very incorrectly in some cases) across browsers if user click addition
* back/forward navigations while the confirm is open. Use at your own risk.
*/
function usePrompt({
when,
message
}) {
let blocker = unstable_useBlocker(when);
React.useEffect(() => {
if (blocker.state === "blocked") {
let proceed = window.confirm(message);
if (proceed) {
// This timeout is needed to avoid a weird "race" on POP navigations
// between the `window.history` revert navigation and the result of
// `window.confirm`
setTimeout(blocker.proceed, 0);
} else {
blocker.reset();
}
}
}, [blocker, message]);
React.useEffect(() => {
if (blocker.state === "blocked" && !when) {
blocker.reset();
}
}, [blocker, when]);
}
//#endregion
export { BrowserRouter, Form, HashRouter, Link, NavLink, ScrollRestoration, useScrollRestoration as UNSAFE_useScrollRestoration, createBrowserRouter, createHashRouter, createSearchParams, HistoryRouter as unstable_HistoryRouter, usePrompt as unstable_usePrompt, useBeforeUnload, useFetcher, useFetchers, useFormAction, useLinkClickHandler, useSearchParams, useSubmit };
export * from 'react-router';
//# sourceMappingURL=react-router-dom.development.js.map
/**
* React Router DOM v0.0.0-experimental-4286521e
* React Router DOM v0.0.0-experimental-42a5853ef
*

@@ -11,3 +11,3 @@ * Copyright (c) Remix Software Inc.

*/
import*as e from"react";import{UNSAFE_mapRouteProperties as t,Router as r,UNSAFE_NavigationContext as n,useHref as o,useResolvedPath as a,useLocation as i,UNSAFE_DataRouterStateContext as s,useNavigate as u,createPath as l,UNSAFE_useRouteId as c,UNSAFE_RouteContext as f,useMatches as m,useNavigation as d,unstable_useBlocker as p,UNSAFE_DataRouterContext as h}from"react-router";export{AbortedDeferredError,Await,MemoryRouter,Navigate,NavigationType,Outlet,Route,Router,RouterProvider,Routes,UNSAFE_DataRouterContext,UNSAFE_DataRouterStateContext,UNSAFE_LocationContext,UNSAFE_NavigationContext,UNSAFE_RouteContext,UNSAFE_useRouteId,createMemoryRouter,createPath,createRoutesFromChildren,createRoutesFromElements,defer,generatePath,isRouteErrorResponse,json,matchPath,matchRoutes,parsePath,redirect,redirectDocument,renderMatches,resolvePath,unstable_useBlocker,useActionData,useAsyncError,useAsyncValue,useHref,useInRouterContext,useLoaderData,useLocation,useMatch,useMatches,useNavigate,useNavigation,useNavigationType,useOutlet,useOutletContext,useParams,useResolvedPath,useRevalidator,useRouteError,useRouteLoaderData,useRoutes}from"react-router";import{stripBasename as w,createRouter as y,createBrowserHistory as g,createHashHistory as b,ErrorResponse as v,UNSAFE_invariant as R,joinPaths as S}from"@remix-run/router";const E="application/x-www-form-urlencoded";function C(e){return null!=e&&"string"==typeof e.tagName}function x(e=""){return new URLSearchParams("string"==typeof e||Array.isArray(e)||e instanceof URLSearchParams?e:Object.keys(e).reduce(((t,r)=>{let n=e[r];return t.concat(Array.isArray(n)?n.map((e=>[r,e])):[[r,n]])}),[]))}let A=null;const L=new Set(["application/x-www-form-urlencoded","multipart/form-data","text/plain"]);function U(e){return null==e||L.has(e)?e:null}function _(e,t){let r,n,o,a,i;if(C(s=e)&&"form"===s.tagName.toLowerCase()){let i=e.getAttribute("action");n=i?w(i,t):null,r=e.getAttribute("method")||"get",o=U(e.getAttribute("enctype"))||E,a=new FormData(e)}else if(function(e){return C(e)&&"button"===e.tagName.toLowerCase()}(e)||function(e){return C(e)&&"input"===e.tagName.toLowerCase()}(e)&&("submit"===e.type||"image"===e.type)){let i=e.form;if(null==i)throw new Error('Cannot submit a <button> or <input type="submit"> without a <form>');let s=e.getAttribute("formaction")||i.getAttribute("action");if(n=s?w(s,t):null,r=e.getAttribute("formmethod")||i.getAttribute("method")||"get",o=U(e.getAttribute("formenctype"))||U(i.getAttribute("enctype"))||E,a=new FormData(i,e),!function(){if(null===A)try{new FormData(document.createElement("form"),0),A=!1}catch(e){A=!0}return A}()){let{name:t,type:r,value:n}=e;if("image"===r){let e=t?`${t}.`:"";a.append(`${e}x`,"0"),a.append(`${e}y`,"0")}else t&&a.append(t,n)}}else{if(C(e))throw new Error('Cannot submit element that is not <form>, <button>, or <input type="submit|image">');r="get",n=null,o=E,i=e}var s;return a&&"text/plain"===o&&(i=a,a=void 0),{action:n,method:r.toLowerCase(),encType:o,formData:a,body:i}}function F(e,r){return y({basename:r?.basename,future:{...r?.future,v7_prependBasename:!0},history:g({window:r?.window}),hydrationData:r?.hydrationData||T(),routes:e,mapRouteProperties:t}).initialize()}function D(e,r){return y({basename:r?.basename,future:{...r?.future,v7_prependBasename:!0},history:b({window:r?.window}),hydrationData:r?.hydrationData||T(),routes:e,mapRouteProperties:t}).initialize()}function T(){let e=window?.__staticRouterHydrationData;return e&&e.errors&&(e={...e,errors:N(e.errors)}),e}function N(e){if(!e)return null;let t=Object.entries(e),r={};for(let[o,a]of t)if(a&&"RouteErrorResponse"===a.__type)r[o]=new v(a.status,a.statusText,a.data,!0===a.internal);else if(a&&"Error"===a.__type){if(a.__subType){let e=window[a.__subType];if("function"==typeof e)try{let t=new e(a.message);t.stack="",r[o]=t}catch(n){}}if(null==r[o]){let e=new Error(a.message);e.stack="",r[o]=e}}else r[o]=a;return r}const P=e.startTransition;function k({basename:t,children:n,future:o,window:a}){let i=e.useRef();null==i.current&&(i.current=g({window:a,v5Compat:!0}));let s=i.current,[u,l]=e.useState({action:s.action,location:s.location}),{v7_startTransition:c}=o||{},f=e.useCallback((e=>{c&&P?P((()=>l(e))):l(e)}),[l,c]);return e.useLayoutEffect((()=>s.listen(f)),[s,f]),e.createElement(r,{basename:t,children:n,location:u.location,navigationType:u.action,navigator:s})}function O({basename:t,children:n,future:o,window:a}){let i=e.useRef();null==i.current&&(i.current=b({window:a,v5Compat:!0}));let s=i.current,[u,l]=e.useState({action:s.action,location:s.location}),{v7_startTransition:c}=o||{},f=e.useCallback((e=>{c&&P?P((()=>l(e))):l(e)}),[l,c]);return e.useLayoutEffect((()=>s.listen(f)),[s,f]),e.createElement(r,{basename:t,children:n,location:u.location,navigationType:u.action,navigator:s})}function K({basename:t,children:n,future:o,history:a}){let[i,s]=e.useState({action:a.action,location:a.location}),{v7_startTransition:u}=o||{},l=e.useCallback((e=>{u&&P?P((()=>s(e))):s(e)}),[s,u]);return e.useLayoutEffect((()=>a.listen(l)),[a,l]),e.createElement(r,{basename:t,children:n,location:i.location,navigationType:i.action,navigator:a})}const j="undefined"!=typeof window&&void 0!==window.document&&void 0!==window.document.createElement,M=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i,I=e.forwardRef((function({onClick:t,relative:r,reloadDocument:a,replace:i,state:s,target:u,to:l,preventScrollReset:c,...f},m){let d,{basename:p}=e.useContext(n),h=!1;if("string"==typeof l&&M.test(l)&&(d=l,j))try{let e=new URL(window.location.href),t=l.startsWith("//")?new URL(e.protocol+l):new URL(l),r=w(t.pathname,p);t.origin===e.origin&&null!=r?l=r+t.search+t.hash:h=!0}catch(b){}let y=o(l,{relative:r}),g=q(l,{replace:i,state:s,target:u,preventScrollReset:c,relative:r});return e.createElement("a",Object.assign({},f,{href:d||y,onClick:h||a?t:function(e){t&&t(e),e.defaultPrevented||g(e)},ref:m,target:u}))})),B=e.forwardRef((function({"aria-current":t="page",caseSensitive:r=!1,className:o="",end:u=!1,style:l,to:c,children:f,...m},d){let p=a(c,{relative:m.relative}),h=i(),w=e.useContext(s),{navigator:y}=e.useContext(n),g=y.encodeLocation?y.encodeLocation(p).pathname:p.pathname,b=h.pathname,v=w&&w.navigation&&w.navigation.location?w.navigation.location.pathname:null;r||(b=b.toLowerCase(),v=v?v.toLowerCase():null,g=g.toLowerCase());let R,S=b===g||!u&&b.startsWith(g)&&"/"===b.charAt(g.length),E=null!=v&&(v===g||!u&&v.startsWith(g)&&"/"===v.charAt(g.length)),C=S?t:void 0;R="function"==typeof o?o({isActive:S,isPending:E}):[o,S?"active":null,E?"pending":null].filter(Boolean).join(" ");let x="function"==typeof l?l({isActive:S,isPending:E}):l;return e.createElement(I,Object.assign({},m,{"aria-current":C,className:R,ref:d,style:x,to:c}),"function"==typeof f?f({isActive:S,isPending:E}):f)})),z=e.forwardRef(((t,r)=>{let n=X();return e.createElement($,Object.assign({},t,{submit:n,ref:r}))})),$=e.forwardRef((({reloadDocument:t,replace:r,state:n,method:o="get",action:a,onSubmit:i,submit:s,relative:u,preventScrollReset:l,...c},f)=>{let m="get"===o.toLowerCase()?"get":"post",d=ee(a,{relative:u});return e.createElement("form",Object.assign({ref:f,method:m,action:d,onSubmit:t?i:e=>{if(i&&i(e),e.defaultPrevented)return;e.preventDefault();let t=e.nativeEvent.submitter,a=t?.getAttribute("formmethod")||o;s(t||e.currentTarget,{method:a,replace:r,state:n,relative:u,preventScrollReset:l})}},c))}));function H({getKey:e,storageKey:t}){return ae({getKey:e,storageKey:t}),null}var W=function(e){return e.UseScrollRestoration="useScrollRestoration",e.UseSubmit="useSubmit",e.UseSubmitFetcher="useSubmitFetcher",e.UseFetcher="useFetcher",e}(W||{}),Y=function(e){return e.UseFetchers="useFetchers",e.UseScrollRestoration="useScrollRestoration",e}(Y||{});function J(t){let r=e.useContext(h);return r||R(!1),r}function V(t){let r=e.useContext(s);return r||R(!1),r}function q(t,{target:r,replace:n,state:o,preventScrollReset:s,relative:c}={}){let f=u(),m=i(),d=a(t,{relative:c});return e.useCallback((e=>{if(function(e,t){return!(0!==e.button||t&&"_self"!==t||function(e){return!!(e.metaKey||e.altKey||e.ctrlKey||e.shiftKey)}(e))}(e,r)){e.preventDefault();let r=void 0!==n?n:l(m)===l(d);f(t,{replace:r,state:o,preventScrollReset:s,relative:c})}}),[m,f,d,n,o,r,t,s,c])}function G(t){let r=e.useRef(x(t)),n=e.useRef(!1),o=i(),a=e.useMemo((()=>function(e,t){let r=x(e);return t&&t.forEach(((e,n)=>{r.has(n)||t.getAll(n).forEach((e=>{r.append(n,e)}))})),r}(o.search,n.current?null:r.current)),[o.search]),s=u(),l=e.useCallback(((e,t)=>{const r=x("function"==typeof e?e(a):e);n.current=!0,s("?"+r,t)}),[s,a]);return[a,l]}function Q(){if("undefined"==typeof document)throw new Error("You are calling submit during the server render. Try calling submit within a `useEffect` or callback instead.")}function X(){let{router:t}=J(W.UseSubmit),{basename:r}=e.useContext(n),o=c();return e.useCallback(((e,n={})=>{Q();let{action:a,method:i,encType:s,formData:u,body:l}=_(e,r);t.navigate(n.action||a,{preventScrollReset:n.preventScrollReset,formData:u,body:l,formMethod:n.method||i,formEncType:n.encType||s,replace:n.replace,state:n.state,fromRouteId:o})}),[t,r,o])}function Z(t,r){let{router:o}=J(W.UseSubmitFetcher),{basename:a}=e.useContext(n);return e.useCallback(((e,n={})=>{Q();let{action:i,method:s,encType:u,formData:l,body:c}=_(e,a);null==r&&R(!1),o.fetch(t,r,n.action||i,{preventScrollReset:n.preventScrollReset,formData:l,body:c,formMethod:n.method||s,formEncType:n.encType||u})}),[o,a,t,r])}function ee(t,{relative:r}={}){let{basename:o}=e.useContext(n),s=e.useContext(f);s||R(!1);let[u]=s.matches.slice(-1),c={...a(t||".",{relative:r})},m=i();if(null==t&&(c.search=m.search,u.route.index)){let e=new URLSearchParams(c.search);e.delete("index"),c.search=e.toString()?`?${e.toString()}`:""}return t&&"."!==t||!u.route.index||(c.search=c.search?c.search.replace(/^\?/,"?index&"):"?index"),"/"!==o&&(c.pathname="/"===c.pathname?o:S([o,c.pathname])),l(c)}let te=0;function re(){let{router:t}=J(W.UseFetcher),r=e.useContext(f);r||R(!1);let n=r.matches[r.matches.length-1]?.route.id;null==n&&R(!1);let[o]=e.useState((()=>String(++te))),[a]=e.useState((()=>(n||R(!1),function(t,r){return e.forwardRef(((n,o)=>{let a=Z(t,r);return e.createElement($,Object.assign({},n,{ref:o,submit:a}))}))}(o,n)))),[i]=e.useState((()=>e=>{t||R(!1),n||R(!1),t.fetch(o,n,e)})),s=Z(o,n),u=t.getFetcher(o),l=e.useMemo((()=>({Form:a,submit:s,load:i,...u})),[u,a,s,i]);return e.useEffect((()=>()=>{t?t.deleteFetcher(o):console.warn("No router available to clean up from useFetcher()")}),[t,o]),l}function ne(){return[...V(Y.UseFetchers).fetchers.values()]}let oe={};function ae({getKey:t,storageKey:r}={}){let{router:o}=J(W.UseScrollRestoration),{restoreScrollPosition:a,preventScrollReset:s}=V(Y.UseScrollRestoration),{basename:u}=e.useContext(n),l=i(),c=m(),f=d();e.useEffect((()=>(window.history.scrollRestoration="manual",()=>{window.history.scrollRestoration="auto"})),[]),function(t,r){let{capture:n}=r||{};e.useEffect((()=>{let e=null!=n?{capture:n}:void 0;return window.addEventListener("pagehide",t,e),()=>{window.removeEventListener("pagehide",t,e)}}),[t,n])}(e.useCallback((()=>{if("idle"===f.state){let e=(t?t(l,c):null)||l.key;oe[e]=window.scrollY}sessionStorage.setItem(r||"react-router-scroll-positions",JSON.stringify(oe)),window.history.scrollRestoration="auto"}),[r,t,f.state,l,c])),"undefined"!=typeof document&&(e.useLayoutEffect((()=>{try{let e=sessionStorage.getItem(r||"react-router-scroll-positions");e&&(oe=JSON.parse(e))}catch(e){}}),[r]),e.useLayoutEffect((()=>{let e=t&&"/"!==u?(e,r)=>t({...e,pathname:w(e.pathname,u)||e.pathname},r):t,r=o?.enableScrollRestoration(oe,(()=>window.scrollY),e);return()=>r&&r()}),[o,u,t]),e.useLayoutEffect((()=>{if(!1!==a)if("number"!=typeof a){if(l.hash){let e=document.getElementById(decodeURIComponent(l.hash.slice(1)));if(e)return void e.scrollIntoView()}!0!==s&&window.scrollTo(0,0)}else window.scrollTo(0,a)}),[l,a,s]))}function ie(t,r){let{capture:n}=r||{};e.useEffect((()=>{let e=null!=n?{capture:n}:void 0;return window.addEventListener("beforeunload",t,e),()=>{window.removeEventListener("beforeunload",t,e)}}),[t,n])}function se({when:t,message:r}){let n=p(t);e.useEffect((()=>{if("blocked"===n.state){window.confirm(r)?setTimeout(n.proceed,0):n.reset()}}),[n,r]),e.useEffect((()=>{"blocked"!==n.state||t||n.reset()}),[n,t])}export{k as BrowserRouter,z as Form,O as HashRouter,I as Link,B as NavLink,H as ScrollRestoration,ae as UNSAFE_useScrollRestoration,F as createBrowserRouter,D as createHashRouter,x as createSearchParams,K as unstable_HistoryRouter,se as unstable_usePrompt,ie as useBeforeUnload,re as useFetcher,ne as useFetchers,ee as useFormAction,q as useLinkClickHandler,G as useSearchParams,X as useSubmit};
export*from"react-router";
//# sourceMappingURL=react-router-dom.production.min.js.map
/**
* React Router DOM v0.0.0-experimental-4286521e
* React Router DOM v0.0.0-experimental-42a5853ef
*

@@ -12,1379 +12,17 @@ * Copyright (c) Remix Software Inc.

(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('react'), require('react-router'), require('@remix-run/router')) :
typeof define === 'function' && define.amd ? define(['exports', 'react', 'react-router', '@remix-run/router'], factory) :
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.ReactRouterDOM = {}, global.React, global.ReactRouter, global.RemixRouter));
})(this, (function (exports, React, reactRouter, router) { 'use strict';
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('react-router')) :
typeof define === 'function' && define.amd ? define(['exports', 'react-router'], factory) :
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.ReactRouterDOM = {}, global.ReactRouter));
})(this, (function (exports, reactRouter) { 'use strict';
function _interopNamespace(e) {
if (e && e.__esModule) return e;
var n = Object.create(null);
if (e) {
Object.keys(e).forEach(function (k) {
if (k !== 'default') {
var d = Object.getOwnPropertyDescriptor(e, k);
Object.defineProperty(n, k, d.get ? d : {
enumerable: true,
get: function () { return e[k]; }
});
}
});
}
n["default"] = e;
return Object.freeze(n);
}
Object.keys(reactRouter).forEach(function (k) {
if (k !== 'default' && !exports.hasOwnProperty(k)) Object.defineProperty(exports, k, {
enumerable: true,
get: function () { return reactRouter[k]; }
});
});
var React__namespace = /*#__PURE__*/_interopNamespace(React);
Object.defineProperty(exports, '__esModule', { value: true });
function _extends() {
_extends = Object.assign ? Object.assign.bind() : function (target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i];
for (var key in source) {
if (Object.prototype.hasOwnProperty.call(source, key)) {
target[key] = source[key];
}
}
}
return target;
};
return _extends.apply(this, arguments);
}
function _objectWithoutPropertiesLoose(source, excluded) {
if (source == null) return {};
var target = {};
var sourceKeys = Object.keys(source);
var key, i;
for (i = 0; i < sourceKeys.length; i++) {
key = sourceKeys[i];
if (excluded.indexOf(key) >= 0) continue;
target[key] = source[key];
}
return target;
}
const defaultMethod = "get";
const defaultEncType = "application/x-www-form-urlencoded";
function isHtmlElement(object) {
return object != null && typeof object.tagName === "string";
}
function isButtonElement(object) {
return isHtmlElement(object) && object.tagName.toLowerCase() === "button";
}
function isFormElement(object) {
return isHtmlElement(object) && object.tagName.toLowerCase() === "form";
}
function isInputElement(object) {
return isHtmlElement(object) && object.tagName.toLowerCase() === "input";
}
function isModifiedEvent(event) {
return !!(event.metaKey || event.altKey || event.ctrlKey || event.shiftKey);
}
function shouldProcessLinkClick(event, target) {
return event.button === 0 && (
// Ignore everything but left clicks
!target || target === "_self") &&
// Let browser handle "target=_blank" etc.
!isModifiedEvent(event) // Ignore clicks with modifier keys
;
}
/**
* Creates a URLSearchParams object using the given initializer.
*
* This is identical to `new URLSearchParams(init)` except it also
* supports arrays as values in the object form of the initializer
* instead of just strings. This is convenient when you need multiple
* values for a given key, but don't want to use an array initializer.
*
* For example, instead of:
*
* let searchParams = new URLSearchParams([
* ['sort', 'name'],
* ['sort', 'price']
* ]);
*
* you can do:
*
* let searchParams = createSearchParams({
* sort: ['name', 'price']
* });
*/
function createSearchParams(init) {
if (init === void 0) {
init = "";
}
return new URLSearchParams(typeof init === "string" || Array.isArray(init) || init instanceof URLSearchParams ? init : Object.keys(init).reduce((memo, key) => {
let value = init[key];
return memo.concat(Array.isArray(value) ? value.map(v => [key, v]) : [[key, value]]);
}, []));
}
function getSearchParamsForLocation(locationSearch, defaultSearchParams) {
let searchParams = createSearchParams(locationSearch);
if (defaultSearchParams) {
// Use `defaultSearchParams.forEach(...)` here instead of iterating of
// `defaultSearchParams.keys()` to work-around a bug in Firefox related to
// web extensions. Relevant Bugzilla tickets:
// https://bugzilla.mozilla.org/show_bug.cgi?id=1414602
// https://bugzilla.mozilla.org/show_bug.cgi?id=1023984
defaultSearchParams.forEach((_, key) => {
if (!searchParams.has(key)) {
defaultSearchParams.getAll(key).forEach(value => {
searchParams.append(key, value);
});
}
});
}
return searchParams;
}
// Thanks https://github.com/sindresorhus/type-fest!
// One-time check for submitter support
let _formDataSupportsSubmitter = null;
function isFormDataSubmitterSupported() {
if (_formDataSupportsSubmitter === null) {
try {
new FormData(document.createElement("form"),
// @ts-expect-error if FormData supports the submitter parameter, this will throw
0);
_formDataSupportsSubmitter = false;
} catch (e) {
_formDataSupportsSubmitter = true;
}
}
return _formDataSupportsSubmitter;
}
const supportedFormEncTypes = new Set(["application/x-www-form-urlencoded", "multipart/form-data", "text/plain"]);
function getFormEncType(encType) {
if (encType != null && !supportedFormEncTypes.has(encType)) {
router.UNSAFE_warning(false, "\"" + encType + "\" is not a valid `encType` for `<Form>`/`<fetcher.Form>` " + ("and will default to \"" + defaultEncType + "\"")) ;
return null;
}
return encType;
}
function getFormSubmissionInfo(target, basename) {
let method;
let action;
let encType;
let formData;
let body;
if (isFormElement(target)) {
// When grabbing the action from the element, it will have had the basename
// prefixed to ensure non-JS scenarios work, so strip it since we'll
// re-prefix in the router
let attr = target.getAttribute("action");
action = attr ? router.stripBasename(attr, basename) : null;
method = target.getAttribute("method") || defaultMethod;
encType = getFormEncType(target.getAttribute("enctype")) || defaultEncType;
formData = new FormData(target);
} else if (isButtonElement(target) || isInputElement(target) && (target.type === "submit" || target.type === "image")) {
let form = target.form;
if (form == null) {
throw new Error("Cannot submit a <button> or <input type=\"submit\"> without a <form>");
}
// <button>/<input type="submit"> may override attributes of <form>
// When grabbing the action from the element, it will have had the basename
// prefixed to ensure non-JS scenarios work, so strip it since we'll
// re-prefix in the router
let attr = target.getAttribute("formaction") || form.getAttribute("action");
action = attr ? router.stripBasename(attr, basename) : null;
method = target.getAttribute("formmethod") || form.getAttribute("method") || defaultMethod;
encType = getFormEncType(target.getAttribute("formenctype")) || getFormEncType(form.getAttribute("enctype")) || defaultEncType;
// Build a FormData object populated from a form and submitter
formData = new FormData(form, target);
// If this browser doesn't support the `FormData(el, submitter)` format,
// then tack on the submitter value at the end. This is a lightweight
// solution that is not 100% spec compliant. For complete support in older
// browsers, consider using the `formdata-submitter-polyfill` package
if (!isFormDataSubmitterSupported()) {
let {
name,
type,
value
} = target;
if (type === "image") {
let prefix = name ? name + "." : "";
formData.append(prefix + "x", "0");
formData.append(prefix + "y", "0");
} else if (name) {
formData.append(name, value);
}
}
} else if (isHtmlElement(target)) {
throw new Error("Cannot submit element that is not <form>, <button>, or " + "<input type=\"submit|image\">");
} else {
method = defaultMethod;
action = null;
encType = defaultEncType;
body = target;
}
// Send body for <Form encType="text/plain" so we encode it into text
if (formData && encType === "text/plain") {
body = formData;
formData = undefined;
}
return {
action,
method: method.toLowerCase(),
encType,
formData,
body
};
}
const _excluded = ["onClick", "relative", "reloadDocument", "replace", "state", "target", "to", "preventScrollReset"],
_excluded2 = ["aria-current", "caseSensitive", "className", "end", "style", "to", "children"],
_excluded3 = ["reloadDocument", "replace", "state", "method", "action", "onSubmit", "submit", "relative", "preventScrollReset"];
//#endregion
////////////////////////////////////////////////////////////////////////////////
//#region Routers
////////////////////////////////////////////////////////////////////////////////
function createBrowserRouter(routes, opts) {
return router.createRouter({
basename: opts == null ? void 0 : opts.basename,
future: _extends({}, opts == null ? void 0 : opts.future, {
v7_prependBasename: true
}),
history: router.createBrowserHistory({
window: opts == null ? void 0 : opts.window
}),
hydrationData: (opts == null ? void 0 : opts.hydrationData) || parseHydrationData(),
routes,
mapRouteProperties: reactRouter.UNSAFE_mapRouteProperties
}).initialize();
}
function createHashRouter(routes, opts) {
return router.createRouter({
basename: opts == null ? void 0 : opts.basename,
future: _extends({}, opts == null ? void 0 : opts.future, {
v7_prependBasename: true
}),
history: router.createHashHistory({
window: opts == null ? void 0 : opts.window
}),
hydrationData: (opts == null ? void 0 : opts.hydrationData) || parseHydrationData(),
routes,
mapRouteProperties: reactRouter.UNSAFE_mapRouteProperties
}).initialize();
}
function parseHydrationData() {
var _window;
let state = (_window = window) == null ? void 0 : _window.__staticRouterHydrationData;
if (state && state.errors) {
state = _extends({}, state, {
errors: deserializeErrors(state.errors)
});
}
return state;
}
function deserializeErrors(errors) {
if (!errors) return null;
let entries = Object.entries(errors);
let serialized = {};
for (let [key, val] of entries) {
// Hey you! If you change this, please change the corresponding logic in
// serializeErrors in react-router-dom/server.tsx :)
if (val && val.__type === "RouteErrorResponse") {
serialized[key] = new router.ErrorResponse(val.status, val.statusText, val.data, val.internal === true);
} else if (val && val.__type === "Error") {
// Attempt to reconstruct the right type of Error (i.e., ReferenceError)
if (val.__subType) {
let ErrorConstructor = window[val.__subType];
if (typeof ErrorConstructor === "function") {
try {
// @ts-expect-error
let error = new ErrorConstructor(val.message);
// Wipe away the client-side stack trace. Nothing to fill it in with
// because we don't serialize SSR stack traces for security reasons
error.stack = "";
serialized[key] = error;
} catch (e) {
// no-op - fall through and create a normal Error
}
}
}
if (serialized[key] == null) {
let error = new Error(val.message);
// Wipe away the client-side stack trace. Nothing to fill it in with
// because we don't serialize SSR stack traces for security reasons
error.stack = "";
serialized[key] = error;
}
} else {
serialized[key] = val;
}
}
return serialized;
}
//#endregion
////////////////////////////////////////////////////////////////////////////////
//#region Components
////////////////////////////////////////////////////////////////////////////////
/**
Webpack + React 17 fails to compile on any of the following because webpack
complains that `startTransition` doesn't exist in `React`:
* import { startTransition } from "react"
* import * as React from from "react";
"startTransition" in React ? React.startTransition(() => setState()) : setState()
* import * as React from from "react";
"startTransition" in React ? React["startTransition"](() => setState()) : setState()
Moving it to a constant such as the following solves the Webpack/React 17 issue:
* import * as React from from "react";
const START_TRANSITION = "startTransition";
START_TRANSITION in React ? React[START_TRANSITION](() => setState()) : setState()
However, that introduces webpack/terser minification issues in production builds
in React 18 where minification/obfuscation ends up removing the call of
React.startTransition entirely from the first half of the ternary. Grabbing
this exported reference once up front resolves that issue.
See https://github.com/remix-run/react-router/issues/10579
*/
const START_TRANSITION = "startTransition";
const startTransitionImpl = React__namespace[START_TRANSITION];
/**
* A `<Router>` for use in web browsers. Provides the cleanest URLs.
*/
function BrowserRouter(_ref) {
let {
basename,
children,
future,
window
} = _ref;
let historyRef = React__namespace.useRef();
if (historyRef.current == null) {
historyRef.current = router.createBrowserHistory({
window,
v5Compat: true
});
}
let history = historyRef.current;
let [state, setStateImpl] = React__namespace.useState({
action: history.action,
location: history.location
});
let {
v7_startTransition
} = future || {};
let setState = React__namespace.useCallback(newState => {
v7_startTransition && startTransitionImpl ? startTransitionImpl(() => setStateImpl(newState)) : setStateImpl(newState);
}, [setStateImpl, v7_startTransition]);
React__namespace.useLayoutEffect(() => history.listen(setState), [history, setState]);
return /*#__PURE__*/React__namespace.createElement(reactRouter.Router, {
basename: basename,
children: children,
location: state.location,
navigationType: state.action,
navigator: history
});
}
/**
* A `<Router>` for use in web browsers. Stores the location in the hash
* portion of the URL so it is not sent to the server.
*/
function HashRouter(_ref2) {
let {
basename,
children,
future,
window
} = _ref2;
let historyRef = React__namespace.useRef();
if (historyRef.current == null) {
historyRef.current = router.createHashHistory({
window,
v5Compat: true
});
}
let history = historyRef.current;
let [state, setStateImpl] = React__namespace.useState({
action: history.action,
location: history.location
});
let {
v7_startTransition
} = future || {};
let setState = React__namespace.useCallback(newState => {
v7_startTransition && startTransitionImpl ? startTransitionImpl(() => setStateImpl(newState)) : setStateImpl(newState);
}, [setStateImpl, v7_startTransition]);
React__namespace.useLayoutEffect(() => history.listen(setState), [history, setState]);
return /*#__PURE__*/React__namespace.createElement(reactRouter.Router, {
basename: basename,
children: children,
location: state.location,
navigationType: state.action,
navigator: history
});
}
/**
* A `<Router>` that accepts a pre-instantiated history object. It's important
* to note that using your own history object is highly discouraged and may add
* two versions of the history library to your bundles unless you use the same
* version of the history library that React Router uses internally.
*/
function HistoryRouter(_ref3) {
let {
basename,
children,
future,
history
} = _ref3;
let [state, setStateImpl] = React__namespace.useState({
action: history.action,
location: history.location
});
let {
v7_startTransition
} = future || {};
let setState = React__namespace.useCallback(newState => {
v7_startTransition && startTransitionImpl ? startTransitionImpl(() => setStateImpl(newState)) : setStateImpl(newState);
}, [setStateImpl, v7_startTransition]);
React__namespace.useLayoutEffect(() => history.listen(setState), [history, setState]);
return /*#__PURE__*/React__namespace.createElement(reactRouter.Router, {
basename: basename,
children: children,
location: state.location,
navigationType: state.action,
navigator: history
});
}
{
HistoryRouter.displayName = "unstable_HistoryRouter";
}
const isBrowser = typeof window !== "undefined" && typeof window.document !== "undefined" && typeof window.document.createElement !== "undefined";
const ABSOLUTE_URL_REGEX = /^(?:[a-z][a-z0-9+.-]*:|\/\/)/i;
/**
* The public API for rendering a history-aware <a>.
*/
const Link = /*#__PURE__*/React__namespace.forwardRef(function LinkWithRef(_ref4, ref) {
let {
onClick,
relative,
reloadDocument,
replace,
state,
target,
to,
preventScrollReset
} = _ref4,
rest = _objectWithoutPropertiesLoose(_ref4, _excluded);
let {
basename
} = React__namespace.useContext(reactRouter.UNSAFE_NavigationContext);
// Rendered into <a href> for absolute URLs
let absoluteHref;
let isExternal = false;
if (typeof to === "string" && ABSOLUTE_URL_REGEX.test(to)) {
// Render the absolute href server- and client-side
absoluteHref = to;
// Only check for external origins client-side
if (isBrowser) {
try {
let currentUrl = new URL(window.location.href);
let targetUrl = to.startsWith("//") ? new URL(currentUrl.protocol + to) : new URL(to);
let path = router.stripBasename(targetUrl.pathname, basename);
if (targetUrl.origin === currentUrl.origin && path != null) {
// Strip the protocol/origin/basename for same-origin absolute URLs
to = path + targetUrl.search + targetUrl.hash;
} else {
isExternal = true;
}
} catch (e) {
// We can't do external URL detection without a valid URL
router.UNSAFE_warning(false, "<Link to=\"" + to + "\"> contains an invalid URL which will probably break " + "when clicked - please update to a valid URL path.") ;
}
}
}
// Rendered into <a href> for relative URLs
let href = reactRouter.useHref(to, {
relative
});
let internalOnClick = useLinkClickHandler(to, {
replace,
state,
target,
preventScrollReset,
relative
});
function handleClick(event) {
if (onClick) onClick(event);
if (!event.defaultPrevented) {
internalOnClick(event);
}
}
return (
/*#__PURE__*/
// eslint-disable-next-line jsx-a11y/anchor-has-content
React__namespace.createElement("a", _extends({}, rest, {
href: absoluteHref || href,
onClick: isExternal || reloadDocument ? onClick : handleClick,
ref: ref,
target: target
}))
);
});
{
Link.displayName = "Link";
}
/**
* A <Link> wrapper that knows if it's "active" or not.
*/
const NavLink = /*#__PURE__*/React__namespace.forwardRef(function NavLinkWithRef(_ref5, ref) {
let {
"aria-current": ariaCurrentProp = "page",
caseSensitive = false,
className: classNameProp = "",
end = false,
style: styleProp,
to,
children
} = _ref5,
rest = _objectWithoutPropertiesLoose(_ref5, _excluded2);
let path = reactRouter.useResolvedPath(to, {
relative: rest.relative
});
let location = reactRouter.useLocation();
let routerState = React__namespace.useContext(reactRouter.UNSAFE_DataRouterStateContext);
let {
navigator
} = React__namespace.useContext(reactRouter.UNSAFE_NavigationContext);
let toPathname = navigator.encodeLocation ? navigator.encodeLocation(path).pathname : path.pathname;
let locationPathname = location.pathname;
let nextLocationPathname = routerState && routerState.navigation && routerState.navigation.location ? routerState.navigation.location.pathname : null;
if (!caseSensitive) {
locationPathname = locationPathname.toLowerCase();
nextLocationPathname = nextLocationPathname ? nextLocationPathname.toLowerCase() : null;
toPathname = toPathname.toLowerCase();
}
let isActive = locationPathname === toPathname || !end && locationPathname.startsWith(toPathname) && locationPathname.charAt(toPathname.length) === "/";
let isPending = nextLocationPathname != null && (nextLocationPathname === toPathname || !end && nextLocationPathname.startsWith(toPathname) && nextLocationPathname.charAt(toPathname.length) === "/");
let ariaCurrent = isActive ? ariaCurrentProp : undefined;
let className;
if (typeof classNameProp === "function") {
className = classNameProp({
isActive,
isPending
});
} else {
// If the className prop is not a function, we use a default `active`
// class for <NavLink />s that are active. In v5 `active` was the default
// value for `activeClassName`, but we are removing that API and can still
// use the old default behavior for a cleaner upgrade path and keep the
// simple styling rules working as they currently do.
className = [classNameProp, isActive ? "active" : null, isPending ? "pending" : null].filter(Boolean).join(" ");
}
let style = typeof styleProp === "function" ? styleProp({
isActive,
isPending
}) : styleProp;
return /*#__PURE__*/React__namespace.createElement(Link, _extends({}, rest, {
"aria-current": ariaCurrent,
className: className,
ref: ref,
style: style,
to: to
}), typeof children === "function" ? children({
isActive,
isPending
}) : children);
});
{
NavLink.displayName = "NavLink";
}
/**
* A `@remix-run/router`-aware `<form>`. It behaves like a normal form except
* that the interaction with the server is with `fetch` instead of new document
* requests, allowing components to add nicer UX to the page as the form is
* submitted and returns with data.
*/
const Form = /*#__PURE__*/React__namespace.forwardRef((props, ref) => {
let submit = useSubmit();
return /*#__PURE__*/React__namespace.createElement(FormImpl, _extends({}, props, {
submit: submit,
ref: ref
}));
});
{
Form.displayName = "Form";
}
const FormImpl = /*#__PURE__*/React__namespace.forwardRef((_ref6, forwardedRef) => {
let {
reloadDocument,
replace,
state,
method = defaultMethod,
action,
onSubmit,
submit,
relative,
preventScrollReset
} = _ref6,
props = _objectWithoutPropertiesLoose(_ref6, _excluded3);
let formMethod = method.toLowerCase() === "get" ? "get" : "post";
let formAction = useFormAction(action, {
relative
});
let submitHandler = event => {
onSubmit && onSubmit(event);
if (event.defaultPrevented) return;
event.preventDefault();
let submitter = event.nativeEvent.submitter;
let submitMethod = (submitter == null ? void 0 : submitter.getAttribute("formmethod")) || method;
submit(submitter || event.currentTarget, {
method: submitMethod,
replace,
state,
relative,
preventScrollReset
});
};
return /*#__PURE__*/React__namespace.createElement("form", _extends({
ref: forwardedRef,
method: formMethod,
action: formAction,
onSubmit: reloadDocument ? onSubmit : submitHandler
}, props));
});
{
FormImpl.displayName = "FormImpl";
}
/**
* This component will emulate the browser's scroll restoration on location
* changes.
*/
function ScrollRestoration(_ref7) {
let {
getKey,
storageKey
} = _ref7;
useScrollRestoration({
getKey,
storageKey
});
return null;
}
{
ScrollRestoration.displayName = "ScrollRestoration";
}
//#endregion
////////////////////////////////////////////////////////////////////////////////
//#region Hooks
////////////////////////////////////////////////////////////////////////////////
var DataRouterHook = /*#__PURE__*/function (DataRouterHook) {
DataRouterHook["UseScrollRestoration"] = "useScrollRestoration";
DataRouterHook["UseSubmit"] = "useSubmit";
DataRouterHook["UseSubmitFetcher"] = "useSubmitFetcher";
DataRouterHook["UseFetcher"] = "useFetcher";
return DataRouterHook;
}(DataRouterHook || {});
var DataRouterStateHook = /*#__PURE__*/function (DataRouterStateHook) {
DataRouterStateHook["UseFetchers"] = "useFetchers";
DataRouterStateHook["UseScrollRestoration"] = "useScrollRestoration";
return DataRouterStateHook;
}(DataRouterStateHook || {});
function getDataRouterConsoleError(hookName) {
return hookName + " must be used within a data router. See https://reactrouter.com/routers/picking-a-router.";
}
function useDataRouterContext(hookName) {
let ctx = React__namespace.useContext(reactRouter.UNSAFE_DataRouterContext);
!ctx ? router.UNSAFE_invariant(false, getDataRouterConsoleError(hookName)) : void 0;
return ctx;
}
function useDataRouterState(hookName) {
let state = React__namespace.useContext(reactRouter.UNSAFE_DataRouterStateContext);
!state ? router.UNSAFE_invariant(false, getDataRouterConsoleError(hookName)) : void 0;
return state;
}
/**
* Handles the click behavior for router `<Link>` components. This is useful if
* you need to create custom `<Link>` components with the same click behavior we
* use in our exported `<Link>`.
*/
function useLinkClickHandler(to, _temp) {
let {
target,
replace: replaceProp,
state,
preventScrollReset,
relative
} = _temp === void 0 ? {} : _temp;
let navigate = reactRouter.useNavigate();
let location = reactRouter.useLocation();
let path = reactRouter.useResolvedPath(to, {
relative
});
return React__namespace.useCallback(event => {
if (shouldProcessLinkClick(event, target)) {
event.preventDefault();
// If the URL hasn't changed, a regular <a> will do a replace instead of
// a push, so do the same here unless the replace prop is explicitly set
let replace = replaceProp !== undefined ? replaceProp : reactRouter.createPath(location) === reactRouter.createPath(path);
navigate(to, {
replace,
state,
preventScrollReset,
relative
});
}
}, [location, navigate, path, replaceProp, state, target, to, preventScrollReset, relative]);
}
/**
* A convenient wrapper for reading and writing search parameters via the
* URLSearchParams interface.
*/
function useSearchParams(defaultInit) {
router.UNSAFE_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\n\n" + "If you're unsure how to load polyfills, we recommend you check out " + "https://polyfill.io/v3/ which provides some recommendations about how " + "to load polyfills only for users that need them, instead of for every " + "user.") ;
let defaultSearchParamsRef = React__namespace.useRef(createSearchParams(defaultInit));
let hasSetSearchParamsRef = React__namespace.useRef(false);
let location = reactRouter.useLocation();
let searchParams = React__namespace.useMemo(() =>
// Only merge in the defaults if we haven't yet called setSearchParams.
// Once we call that we want those to take precedence, otherwise you can't
// remove a param with setSearchParams({}) if it has an initial value
getSearchParamsForLocation(location.search, hasSetSearchParamsRef.current ? null : defaultSearchParamsRef.current), [location.search]);
let navigate = reactRouter.useNavigate();
let setSearchParams = React__namespace.useCallback((nextInit, navigateOptions) => {
const newSearchParams = createSearchParams(typeof nextInit === "function" ? nextInit(searchParams) : nextInit);
hasSetSearchParamsRef.current = true;
navigate("?" + newSearchParams, navigateOptions);
}, [navigate, searchParams]);
return [searchParams, setSearchParams];
}
/**
* Submits a HTML `<form>` to the server without reloading the page.
*/
/**
* Submits a fetcher `<form>` to the server without reloading the page.
*/
function validateClientSideSubmission() {
if (typeof document === "undefined") {
throw new Error("You are calling submit during the server render. " + "Try calling submit within a `useEffect` or callback instead.");
}
}
/**
* Returns a function that may be used to programmatically submit a form (or
* some arbitrary data) to the server.
*/
function useSubmit() {
let {
router
} = useDataRouterContext(DataRouterHook.UseSubmit);
let {
basename
} = React__namespace.useContext(reactRouter.UNSAFE_NavigationContext);
let currentRouteId = reactRouter.UNSAFE_useRouteId();
return React__namespace.useCallback(function (target, options) {
if (options === void 0) {
options = {};
}
validateClientSideSubmission();
let {
action,
method,
encType,
formData,
body
} = getFormSubmissionInfo(target, basename);
router.navigate(options.action || action, {
preventScrollReset: options.preventScrollReset,
formData,
body,
formMethod: options.method || method,
formEncType: options.encType || encType,
replace: options.replace,
state: options.state,
fromRouteId: currentRouteId
});
}, [router, basename, currentRouteId]);
}
/**
* Returns the implementation for fetcher.submit
*/
function useSubmitFetcher(fetcherKey, fetcherRouteId) {
let {
router: router$1
} = useDataRouterContext(DataRouterHook.UseSubmitFetcher);
let {
basename
} = React__namespace.useContext(reactRouter.UNSAFE_NavigationContext);
return React__namespace.useCallback(function (target, options) {
if (options === void 0) {
options = {};
}
validateClientSideSubmission();
let {
action,
method,
encType,
formData,
body
} = getFormSubmissionInfo(target, basename);
!(fetcherRouteId != null) ? router.UNSAFE_invariant(false, "No routeId available for useFetcher()") : void 0;
router$1.fetch(fetcherKey, fetcherRouteId, options.action || action, {
preventScrollReset: options.preventScrollReset,
formData,
body,
formMethod: options.method || method,
formEncType: options.encType || encType
});
}, [router$1, basename, fetcherKey, fetcherRouteId]);
}
// v7: Eventually we should deprecate this entirely in favor of using the
// router method directly?
function useFormAction(action, _temp2) {
let {
relative
} = _temp2 === void 0 ? {} : _temp2;
let {
basename
} = React__namespace.useContext(reactRouter.UNSAFE_NavigationContext);
let routeContext = React__namespace.useContext(reactRouter.UNSAFE_RouteContext);
!routeContext ? router.UNSAFE_invariant(false, "useFormAction must be used inside a RouteContext") : void 0;
let [match] = routeContext.matches.slice(-1);
// Shallow clone path so we can modify it below, otherwise we modify the
// object referenced by useMemo inside useResolvedPath
let path = _extends({}, reactRouter.useResolvedPath(action ? action : ".", {
relative
}));
// Previously we set the default action to ".". The problem with this is that
// `useResolvedPath(".")` excludes search params of the resolved URL. This is
// the intended behavior of when "." is specifically provided as
// the form action, but inconsistent w/ browsers when the action is omitted.
// https://github.com/remix-run/remix/issues/927
let location = reactRouter.useLocation();
if (action == null) {
// Safe to write to this directly here since if action was undefined, we
// would have called useResolvedPath(".") which will never include a search
path.search = location.search;
// When grabbing search params from the URL, remove the automatically
// inserted ?index param so we match the useResolvedPath search behavior
// which would not include ?index
if (match.route.index) {
let params = new URLSearchParams(path.search);
params.delete("index");
path.search = params.toString() ? "?" + params.toString() : "";
}
}
if ((!action || action === ".") && match.route.index) {
path.search = path.search ? path.search.replace(/^\?/, "?index&") : "?index";
}
// If we're operating within a basename, prepend it to the pathname prior
// to creating the form action. If this is a root navigation, then just use
// the raw basename which allows the basename to have full control over the
// presence of a trailing slash on root actions
if (basename !== "/") {
path.pathname = path.pathname === "/" ? basename : router.joinPaths([basename, path.pathname]);
}
return reactRouter.createPath(path);
}
function createFetcherForm(fetcherKey, routeId) {
let FetcherForm = /*#__PURE__*/React__namespace.forwardRef((props, ref) => {
let submit = useSubmitFetcher(fetcherKey, routeId);
return /*#__PURE__*/React__namespace.createElement(FormImpl, _extends({}, props, {
ref: ref,
submit: submit
}));
});
{
FetcherForm.displayName = "fetcher.Form";
}
return FetcherForm;
}
let fetcherId = 0;
/**
* Interacts with route loaders and actions without causing a navigation. Great
* for any interaction that stays on the same page.
*/
function useFetcher() {
var _route$matches;
let {
router: router$1
} = useDataRouterContext(DataRouterHook.UseFetcher);
let route = React__namespace.useContext(reactRouter.UNSAFE_RouteContext);
!route ? router.UNSAFE_invariant(false, "useFetcher must be used inside a RouteContext") : void 0;
let routeId = (_route$matches = route.matches[route.matches.length - 1]) == null ? void 0 : _route$matches.route.id;
!(routeId != null) ? router.UNSAFE_invariant(false, "useFetcher can only be used on routes that contain a unique \"id\"") : void 0;
let [fetcherKey] = React__namespace.useState(() => String(++fetcherId));
let [Form] = React__namespace.useState(() => {
!routeId ? router.UNSAFE_invariant(false, "No routeId available for fetcher.Form()") : void 0;
return createFetcherForm(fetcherKey, routeId);
});
let [load] = React__namespace.useState(() => href => {
!router$1 ? router.UNSAFE_invariant(false, "No router available for fetcher.load()") : void 0;
!routeId ? router.UNSAFE_invariant(false, "No routeId available for fetcher.load()") : void 0;
router$1.fetch(fetcherKey, routeId, href);
});
let submit = useSubmitFetcher(fetcherKey, routeId);
let fetcher = router$1.getFetcher(fetcherKey);
let fetcherWithComponents = React__namespace.useMemo(() => _extends({
Form,
submit,
load
}, fetcher), [fetcher, Form, submit, load]);
React__namespace.useEffect(() => {
// Is this busted when the React team gets real weird and calls effects
// twice on mount? We really just need to garbage collect here when this
// fetcher is no longer around.
return () => {
if (!router$1) {
console.warn("No router available to clean up from useFetcher()");
return;
}
router$1.deleteFetcher(fetcherKey);
};
}, [router$1, fetcherKey]);
return fetcherWithComponents;
}
/**
* Provides all fetchers currently on the page. Useful for layouts and parent
* routes that need to provide pending/optimistic UI regarding the fetch.
*/
function useFetchers() {
let state = useDataRouterState(DataRouterStateHook.UseFetchers);
return [...state.fetchers.values()];
}
const SCROLL_RESTORATION_STORAGE_KEY = "react-router-scroll-positions";
let savedScrollPositions = {};
/**
* When rendered inside a RouterProvider, will restore scroll positions on navigations
*/
function useScrollRestoration(_temp3) {
let {
getKey,
storageKey
} = _temp3 === void 0 ? {} : _temp3;
let {
router: router$1
} = useDataRouterContext(DataRouterHook.UseScrollRestoration);
let {
restoreScrollPosition,
preventScrollReset
} = useDataRouterState(DataRouterStateHook.UseScrollRestoration);
let {
basename
} = React__namespace.useContext(reactRouter.UNSAFE_NavigationContext);
let location = reactRouter.useLocation();
let matches = reactRouter.useMatches();
let navigation = reactRouter.useNavigation();
// Trigger manual scroll restoration while we're active
React__namespace.useEffect(() => {
window.history.scrollRestoration = "manual";
return () => {
window.history.scrollRestoration = "auto";
};
}, []);
// Save positions on pagehide
usePageHide(React__namespace.useCallback(() => {
if (navigation.state === "idle") {
let key = (getKey ? getKey(location, matches) : null) || location.key;
savedScrollPositions[key] = window.scrollY;
}
sessionStorage.setItem(storageKey || SCROLL_RESTORATION_STORAGE_KEY, JSON.stringify(savedScrollPositions));
window.history.scrollRestoration = "auto";
}, [storageKey, getKey, navigation.state, location, matches]));
// Read in any saved scroll locations
if (typeof document !== "undefined") {
// eslint-disable-next-line react-hooks/rules-of-hooks
React__namespace.useLayoutEffect(() => {
try {
let sessionPositions = sessionStorage.getItem(storageKey || SCROLL_RESTORATION_STORAGE_KEY);
if (sessionPositions) {
savedScrollPositions = JSON.parse(sessionPositions);
}
} catch (e) {
// no-op, use default empty object
}
}, [storageKey]);
// Enable scroll restoration in the router
// eslint-disable-next-line react-hooks/rules-of-hooks
React__namespace.useLayoutEffect(() => {
let getKeyWithoutBasename = getKey && basename !== "/" ? (location, matches) => getKey( // Strip the basename to match useLocation()
_extends({}, location, {
pathname: router.stripBasename(location.pathname, basename) || location.pathname
}), matches) : getKey;
let disableScrollRestoration = router$1 == null ? void 0 : router$1.enableScrollRestoration(savedScrollPositions, () => window.scrollY, getKeyWithoutBasename);
return () => disableScrollRestoration && disableScrollRestoration();
}, [router$1, basename, getKey]);
// Restore scrolling when state.restoreScrollPosition changes
// eslint-disable-next-line react-hooks/rules-of-hooks
React__namespace.useLayoutEffect(() => {
// Explicit false means don't do anything (used for submissions)
if (restoreScrollPosition === false) {
return;
}
// been here before, scroll to it
if (typeof restoreScrollPosition === "number") {
window.scrollTo(0, restoreScrollPosition);
return;
}
// try to scroll to the hash
if (location.hash) {
let el = document.getElementById(decodeURIComponent(location.hash.slice(1)));
if (el) {
el.scrollIntoView();
return;
}
}
// Don't reset if this navigation opted out
if (preventScrollReset === true) {
return;
}
// otherwise go to the top on new locations
window.scrollTo(0, 0);
}, [location, restoreScrollPosition, preventScrollReset]);
}
}
/**
* Setup a callback to be fired on the window's `beforeunload` event. This is
* useful for saving some data to `window.localStorage` just before the page
* refreshes.
*
* Note: The `callback` argument should be a function created with
* `React.useCallback()`.
*/
function useBeforeUnload(callback, options) {
let {
capture
} = options || {};
React__namespace.useEffect(() => {
let opts = capture != null ? {
capture
} : undefined;
window.addEventListener("beforeunload", callback, opts);
return () => {
window.removeEventListener("beforeunload", callback, opts);
};
}, [callback, capture]);
}
/**
* Setup a callback to be fired on the window's `pagehide` event. This is
* useful for saving some data to `window.localStorage` just before the page
* refreshes. This event is better supported than beforeunload across browsers.
*
* Note: The `callback` argument should be a function created with
* `React.useCallback()`.
*/
function usePageHide(callback, options) {
let {
capture
} = options || {};
React__namespace.useEffect(() => {
let opts = capture != null ? {
capture
} : undefined;
window.addEventListener("pagehide", callback, opts);
return () => {
window.removeEventListener("pagehide", callback, opts);
};
}, [callback, capture]);
}
/**
* Wrapper around useBlocker to show a window.confirm prompt to users instead
* of building a custom UI with useBlocker.
*
* Warning: This has *a lot of rough edges* and behaves very differently (and
* very incorrectly in some cases) across browsers if user click addition
* back/forward navigations while the confirm is open. Use at your own risk.
*/
function usePrompt(_ref8) {
let {
when,
message
} = _ref8;
let blocker = reactRouter.unstable_useBlocker(when);
React__namespace.useEffect(() => {
if (blocker.state === "blocked") {
let proceed = window.confirm(message);
if (proceed) {
// This timeout is needed to avoid a weird "race" on POP navigations
// between the `window.history` revert navigation and the result of
// `window.confirm`
setTimeout(blocker.proceed, 0);
} else {
blocker.reset();
}
}
}, [blocker, message]);
React__namespace.useEffect(() => {
if (blocker.state === "blocked" && !when) {
blocker.reset();
}
}, [blocker, when]);
}
//#endregion
Object.defineProperty(exports, 'AbortedDeferredError', {
enumerable: true,
get: function () { return reactRouter.AbortedDeferredError; }
});
Object.defineProperty(exports, 'Await', {
enumerable: true,
get: function () { return reactRouter.Await; }
});
Object.defineProperty(exports, 'MemoryRouter', {
enumerable: true,
get: function () { return reactRouter.MemoryRouter; }
});
Object.defineProperty(exports, 'Navigate', {
enumerable: true,
get: function () { return reactRouter.Navigate; }
});
Object.defineProperty(exports, 'NavigationType', {
enumerable: true,
get: function () { return reactRouter.NavigationType; }
});
Object.defineProperty(exports, 'Outlet', {
enumerable: true,
get: function () { return reactRouter.Outlet; }
});
Object.defineProperty(exports, 'Route', {
enumerable: true,
get: function () { return reactRouter.Route; }
});
Object.defineProperty(exports, 'Router', {
enumerable: true,
get: function () { return reactRouter.Router; }
});
Object.defineProperty(exports, 'RouterProvider', {
enumerable: true,
get: function () { return reactRouter.RouterProvider; }
});
Object.defineProperty(exports, 'Routes', {
enumerable: true,
get: function () { return reactRouter.Routes; }
});
Object.defineProperty(exports, 'UNSAFE_DataRouterContext', {
enumerable: true,
get: function () { return reactRouter.UNSAFE_DataRouterContext; }
});
Object.defineProperty(exports, 'UNSAFE_DataRouterStateContext', {
enumerable: true,
get: function () { return reactRouter.UNSAFE_DataRouterStateContext; }
});
Object.defineProperty(exports, 'UNSAFE_LocationContext', {
enumerable: true,
get: function () { return reactRouter.UNSAFE_LocationContext; }
});
Object.defineProperty(exports, 'UNSAFE_NavigationContext', {
enumerable: true,
get: function () { return reactRouter.UNSAFE_NavigationContext; }
});
Object.defineProperty(exports, 'UNSAFE_RouteContext', {
enumerable: true,
get: function () { return reactRouter.UNSAFE_RouteContext; }
});
Object.defineProperty(exports, 'UNSAFE_useRouteId', {
enumerable: true,
get: function () { return reactRouter.UNSAFE_useRouteId; }
});
Object.defineProperty(exports, 'createMemoryRouter', {
enumerable: true,
get: function () { return reactRouter.createMemoryRouter; }
});
Object.defineProperty(exports, 'createPath', {
enumerable: true,
get: function () { return reactRouter.createPath; }
});
Object.defineProperty(exports, 'createRoutesFromChildren', {
enumerable: true,
get: function () { return reactRouter.createRoutesFromChildren; }
});
Object.defineProperty(exports, 'createRoutesFromElements', {
enumerable: true,
get: function () { return reactRouter.createRoutesFromElements; }
});
Object.defineProperty(exports, 'defer', {
enumerable: true,
get: function () { return reactRouter.defer; }
});
Object.defineProperty(exports, 'generatePath', {
enumerable: true,
get: function () { return reactRouter.generatePath; }
});
Object.defineProperty(exports, 'isRouteErrorResponse', {
enumerable: true,
get: function () { return reactRouter.isRouteErrorResponse; }
});
Object.defineProperty(exports, 'json', {
enumerable: true,
get: function () { return reactRouter.json; }
});
Object.defineProperty(exports, 'matchPath', {
enumerable: true,
get: function () { return reactRouter.matchPath; }
});
Object.defineProperty(exports, 'matchRoutes', {
enumerable: true,
get: function () { return reactRouter.matchRoutes; }
});
Object.defineProperty(exports, 'parsePath', {
enumerable: true,
get: function () { return reactRouter.parsePath; }
});
Object.defineProperty(exports, 'redirect', {
enumerable: true,
get: function () { return reactRouter.redirect; }
});
Object.defineProperty(exports, 'redirectDocument', {
enumerable: true,
get: function () { return reactRouter.redirectDocument; }
});
Object.defineProperty(exports, 'renderMatches', {
enumerable: true,
get: function () { return reactRouter.renderMatches; }
});
Object.defineProperty(exports, 'resolvePath', {
enumerable: true,
get: function () { return reactRouter.resolvePath; }
});
Object.defineProperty(exports, 'unstable_useBlocker', {
enumerable: true,
get: function () { return reactRouter.unstable_useBlocker; }
});
Object.defineProperty(exports, 'useActionData', {
enumerable: true,
get: function () { return reactRouter.useActionData; }
});
Object.defineProperty(exports, 'useAsyncError', {
enumerable: true,
get: function () { return reactRouter.useAsyncError; }
});
Object.defineProperty(exports, 'useAsyncValue', {
enumerable: true,
get: function () { return reactRouter.useAsyncValue; }
});
Object.defineProperty(exports, 'useHref', {
enumerable: true,
get: function () { return reactRouter.useHref; }
});
Object.defineProperty(exports, 'useInRouterContext', {
enumerable: true,
get: function () { return reactRouter.useInRouterContext; }
});
Object.defineProperty(exports, 'useLoaderData', {
enumerable: true,
get: function () { return reactRouter.useLoaderData; }
});
Object.defineProperty(exports, 'useLocation', {
enumerable: true,
get: function () { return reactRouter.useLocation; }
});
Object.defineProperty(exports, 'useMatch', {
enumerable: true,
get: function () { return reactRouter.useMatch; }
});
Object.defineProperty(exports, 'useMatches', {
enumerable: true,
get: function () { return reactRouter.useMatches; }
});
Object.defineProperty(exports, 'useNavigate', {
enumerable: true,
get: function () { return reactRouter.useNavigate; }
});
Object.defineProperty(exports, 'useNavigation', {
enumerable: true,
get: function () { return reactRouter.useNavigation; }
});
Object.defineProperty(exports, 'useNavigationType', {
enumerable: true,
get: function () { return reactRouter.useNavigationType; }
});
Object.defineProperty(exports, 'useOutlet', {
enumerable: true,
get: function () { return reactRouter.useOutlet; }
});
Object.defineProperty(exports, 'useOutletContext', {
enumerable: true,
get: function () { return reactRouter.useOutletContext; }
});
Object.defineProperty(exports, 'useParams', {
enumerable: true,
get: function () { return reactRouter.useParams; }
});
Object.defineProperty(exports, 'useResolvedPath', {
enumerable: true,
get: function () { return reactRouter.useResolvedPath; }
});
Object.defineProperty(exports, 'useRevalidator', {
enumerable: true,
get: function () { return reactRouter.useRevalidator; }
});
Object.defineProperty(exports, 'useRouteError', {
enumerable: true,
get: function () { return reactRouter.useRouteError; }
});
Object.defineProperty(exports, 'useRouteLoaderData', {
enumerable: true,
get: function () { return reactRouter.useRouteLoaderData; }
});
Object.defineProperty(exports, 'useRoutes', {
enumerable: true,
get: function () { return reactRouter.useRoutes; }
});
exports.BrowserRouter = BrowserRouter;
exports.Form = Form;
exports.HashRouter = HashRouter;
exports.Link = Link;
exports.NavLink = NavLink;
exports.ScrollRestoration = ScrollRestoration;
exports.UNSAFE_useScrollRestoration = useScrollRestoration;
exports.createBrowserRouter = createBrowserRouter;
exports.createHashRouter = createHashRouter;
exports.createSearchParams = createSearchParams;
exports.unstable_HistoryRouter = HistoryRouter;
exports.unstable_usePrompt = usePrompt;
exports.useBeforeUnload = useBeforeUnload;
exports.useFetcher = useFetcher;
exports.useFetchers = useFetchers;
exports.useFormAction = useFormAction;
exports.useLinkClickHandler = useLinkClickHandler;
exports.useSearchParams = useSearchParams;
exports.useSubmit = useSubmit;
Object.defineProperty(exports, '__esModule', { value: true });
}));
//# sourceMappingURL=react-router-dom.development.js.map
/**
* React Router DOM v0.0.0-experimental-4286521e
* React Router v0.0.0-experimental-42a5853ef
*

@@ -11,3 +11,3 @@ * Copyright (c) Remix Software Inc.

*/
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("react"),require("react-router"),require("@remix-run/router")):"function"==typeof define&&define.amd?define(["exports","react","react-router","@remix-run/router"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).ReactRouterDOM={},e.React,e.ReactRouter,e.RemixRouter)}(this,(function(e,t,r,n){"use strict";function o(e){if(e&&e.__esModule)return e;var t=Object.create(null);return e&&Object.keys(e).forEach((function(r){if("default"!==r){var n=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,n.get?n:{enumerable:!0,get:function(){return e[r]}})}})),t.default=e,Object.freeze(t)}var a=o(t);function u(){return u=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},u.apply(this,arguments)}function i(e,t){if(null==e)return{};var r,n,o={},a=Object.keys(e);for(n=0;n<a.length;n++)r=a[n],t.indexOf(r)>=0||(o[r]=e[r]);return o}const c="get",s="application/x-www-form-urlencoded";function l(e){return null!=e&&"string"==typeof e.tagName}function f(e){return void 0===e&&(e=""),new URLSearchParams("string"==typeof e||Array.isArray(e)||e instanceof URLSearchParams?e:Object.keys(e).reduce(((t,r)=>{let n=e[r];return t.concat(Array.isArray(n)?n.map((e=>[r,e])):[[r,n]])}),[]))}let d=null;const m=new Set(["application/x-www-form-urlencoded","multipart/form-data","text/plain"]);function b(e){return null==e||m.has(e)?e:null}function p(e,t){let r,o,a,u,i;if(l(f=e)&&"form"===f.tagName.toLowerCase()){let i=e.getAttribute("action");o=i?n.stripBasename(i,t):null,r=e.getAttribute("method")||c,a=b(e.getAttribute("enctype"))||s,u=new FormData(e)}else if(function(e){return l(e)&&"button"===e.tagName.toLowerCase()}(e)||function(e){return l(e)&&"input"===e.tagName.toLowerCase()}(e)&&("submit"===e.type||"image"===e.type)){let i=e.form;if(null==i)throw new Error('Cannot submit a <button> or <input type="submit"> without a <form>');let l=e.getAttribute("formaction")||i.getAttribute("action");if(o=l?n.stripBasename(l,t):null,r=e.getAttribute("formmethod")||i.getAttribute("method")||c,a=b(e.getAttribute("formenctype"))||b(i.getAttribute("enctype"))||s,u=new FormData(i,e),!function(){if(null===d)try{new FormData(document.createElement("form"),0),d=!1}catch(e){d=!0}return d}()){let{name:t,type:r,value:n}=e;if("image"===r){let e=t?t+".":"";u.append(e+"x","0"),u.append(e+"y","0")}else t&&u.append(t,n)}}else{if(l(e))throw new Error('Cannot submit element that is not <form>, <button>, or <input type="submit|image">');r=c,o=null,a=s,i=e}var f;return u&&"text/plain"===a&&(i=u,u=void 0),{action:o,method:r.toLowerCase(),encType:a,formData:u,body:i}}const y=["onClick","relative","reloadDocument","replace","state","target","to","preventScrollReset"],g=["aria-current","caseSensitive","className","end","style","to","children"],h=["reloadDocument","replace","state","method","action","onSubmit","submit","relative","preventScrollReset"];function v(){var e;let t=null==(e=window)?void 0:e.__staticRouterHydrationData;return t&&t.errors&&(t=u({},t,{errors:R(t.errors)})),t}function R(e){if(!e)return null;let t=Object.entries(e),r={};for(let[e,o]of t)if(o&&"RouteErrorResponse"===o.__type)r[e]=new n.ErrorResponse(o.status,o.statusText,o.data,!0===o.internal);else if(o&&"Error"===o.__type){if(o.__subType){let t=window[o.__subType];if("function"==typeof t)try{let n=new t(o.message);n.stack="",r[e]=n}catch(e){}}if(null==r[e]){let t=new Error(o.message);t.stack="",r[e]=t}}else r[e]=o;return r}const w=a.startTransition;const P="undefined"!=typeof window&&void 0!==window.document&&void 0!==window.document.createElement,S=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i,E=a.forwardRef((function(e,t){let o,{onClick:c,relative:s,reloadDocument:l,replace:f,state:d,target:m,to:b,preventScrollReset:p}=e,g=i(e,y),{basename:h}=a.useContext(r.UNSAFE_NavigationContext),v=!1;if("string"==typeof b&&S.test(b)&&(o=b,P))try{let e=new URL(window.location.href),t=b.startsWith("//")?new URL(e.protocol+b):new URL(b),r=n.stripBasename(t.pathname,h);t.origin===e.origin&&null!=r?b=r+t.search+t.hash:v=!0}catch(e){}let R=r.useHref(b,{relative:s}),w=U(b,{replace:f,state:d,target:m,preventScrollReset:p,relative:s});return a.createElement("a",u({},g,{href:o||R,onClick:v||l?c:function(e){c&&c(e),e.defaultPrevented||w(e)},ref:t,target:m}))})),O=a.forwardRef((function(e,t){let{"aria-current":n="page",caseSensitive:o=!1,className:c="",end:s=!1,style:l,to:f,children:d}=e,m=i(e,g),b=r.useResolvedPath(f,{relative:m.relative}),p=r.useLocation(),y=a.useContext(r.UNSAFE_DataRouterStateContext),{navigator:h}=a.useContext(r.UNSAFE_NavigationContext),v=h.encodeLocation?h.encodeLocation(b).pathname:b.pathname,R=p.pathname,w=y&&y.navigation&&y.navigation.location?y.navigation.location.pathname:null;o||(R=R.toLowerCase(),w=w?w.toLowerCase():null,v=v.toLowerCase());let P,S=R===v||!s&&R.startsWith(v)&&"/"===R.charAt(v.length),O=null!=w&&(w===v||!s&&w.startsWith(v)&&"/"===w.charAt(v.length)),j=S?n:void 0;P="function"==typeof c?c({isActive:S,isPending:O}):[c,S?"active":null,O?"pending":null].filter(Boolean).join(" ");let N="function"==typeof l?l({isActive:S,isPending:O}):l;return a.createElement(E,u({},m,{"aria-current":j,className:P,ref:t,style:N,to:f}),"function"==typeof d?d({isActive:S,isPending:O}):d)})),j=a.forwardRef(((e,t)=>{let r=L();return a.createElement(N,u({},e,{submit:r,ref:t}))})),N=a.forwardRef(((e,t)=>{let{reloadDocument:r,replace:n,state:o,method:s=c,action:l,onSubmit:f,submit:d,relative:m,preventScrollReset:b}=e,p=i(e,h),y="get"===s.toLowerCase()?"get":"post",g=T(l,{relative:m});return a.createElement("form",u({ref:t,method:y,action:g,onSubmit:r?f:e=>{if(f&&f(e),e.defaultPrevented)return;e.preventDefault();let t=e.nativeEvent.submitter,r=(null==t?void 0:t.getAttribute("formmethod"))||s;d(t||e.currentTarget,{method:r,replace:n,state:o,relative:m,preventScrollReset:b})}},p))}));var A=function(e){return e.UseScrollRestoration="useScrollRestoration",e.UseSubmit="useSubmit",e.UseSubmitFetcher="useSubmitFetcher",e.UseFetcher="useFetcher",e}(A||{}),C=function(e){return e.UseFetchers="useFetchers",e.UseScrollRestoration="useScrollRestoration",e}(C||{});function _(e){let t=a.useContext(r.UNSAFE_DataRouterContext);return t||n.UNSAFE_invariant(!1),t}function F(e){let t=a.useContext(r.UNSAFE_DataRouterStateContext);return t||n.UNSAFE_invariant(!1),t}function U(e,t){let{target:n,replace:o,state:u,preventScrollReset:i,relative:c}=void 0===t?{}:t,s=r.useNavigate(),l=r.useLocation(),f=r.useResolvedPath(e,{relative:c});return a.useCallback((t=>{if(function(e,t){return!(0!==e.button||t&&"_self"!==t||function(e){return!!(e.metaKey||e.altKey||e.ctrlKey||e.shiftKey)}(e))}(t,n)){t.preventDefault();let n=void 0!==o?o:r.createPath(l)===r.createPath(f);s(e,{replace:n,state:u,preventScrollReset:i,relative:c})}}),[l,s,f,o,u,n,e,i,c])}function x(){if("undefined"==typeof document)throw new Error("You are calling submit during the server render. Try calling submit within a `useEffect` or callback instead.")}function L(){let{router:e}=_(A.UseSubmit),{basename:t}=a.useContext(r.UNSAFE_NavigationContext),n=r.UNSAFE_useRouteId();return a.useCallback((function(r,o){void 0===o&&(o={}),x();let{action:a,method:u,encType:i,formData:c,body:s}=p(r,t);e.navigate(o.action||a,{preventScrollReset:o.preventScrollReset,formData:c,body:s,formMethod:o.method||u,formEncType:o.encType||i,replace:o.replace,state:o.state,fromRouteId:n})}),[e,t,n])}function D(e,t){let{router:o}=_(A.UseSubmitFetcher),{basename:u}=a.useContext(r.UNSAFE_NavigationContext);return a.useCallback((function(r,a){void 0===a&&(a={}),x();let{action:i,method:c,encType:s,formData:l,body:f}=p(r,u);null==t&&n.UNSAFE_invariant(!1),o.fetch(e,t,a.action||i,{preventScrollReset:a.preventScrollReset,formData:l,body:f,formMethod:a.method||c,formEncType:a.encType||s})}),[o,u,e,t])}function T(e,t){let{relative:o}=void 0===t?{}:t,{basename:i}=a.useContext(r.UNSAFE_NavigationContext),c=a.useContext(r.UNSAFE_RouteContext);c||n.UNSAFE_invariant(!1);let[s]=c.matches.slice(-1),l=u({},r.useResolvedPath(e||".",{relative:o})),f=r.useLocation();if(null==e&&(l.search=f.search,s.route.index)){let e=new URLSearchParams(l.search);e.delete("index"),l.search=e.toString()?"?"+e.toString():""}return e&&"."!==e||!s.route.index||(l.search=l.search?l.search.replace(/^\?/,"?index&"):"?index"),"/"!==i&&(l.pathname="/"===l.pathname?i:n.joinPaths([i,l.pathname])),r.createPath(l)}let k=0;const M="react-router-scroll-positions";let B={};function H(e){let{getKey:t,storageKey:o}=void 0===e?{}:e,{router:i}=_(A.UseScrollRestoration),{restoreScrollPosition:c,preventScrollReset:s}=F(C.UseScrollRestoration),{basename:l}=a.useContext(r.UNSAFE_NavigationContext),f=r.useLocation(),d=r.useMatches(),m=r.useNavigation();a.useEffect((()=>(window.history.scrollRestoration="manual",()=>{window.history.scrollRestoration="auto"})),[]),function(e,t){let{capture:r}=t||{};a.useEffect((()=>{let t=null!=r?{capture:r}:void 0;return window.addEventListener("pagehide",e,t),()=>{window.removeEventListener("pagehide",e,t)}}),[e,r])}(a.useCallback((()=>{if("idle"===m.state){let e=(t?t(f,d):null)||f.key;B[e]=window.scrollY}sessionStorage.setItem(o||M,JSON.stringify(B)),window.history.scrollRestoration="auto"}),[o,t,m.state,f,d])),"undefined"!=typeof document&&(a.useLayoutEffect((()=>{try{let e=sessionStorage.getItem(o||M);e&&(B=JSON.parse(e))}catch(e){}}),[o]),a.useLayoutEffect((()=>{let e=t&&"/"!==l?(e,r)=>t(u({},e,{pathname:n.stripBasename(e.pathname,l)||e.pathname}),r):t,r=null==i?void 0:i.enableScrollRestoration(B,(()=>window.scrollY),e);return()=>r&&r()}),[i,l,t]),a.useLayoutEffect((()=>{if(!1!==c)if("number"!=typeof c){if(f.hash){let e=document.getElementById(decodeURIComponent(f.hash.slice(1)));if(e)return void e.scrollIntoView()}!0!==s&&window.scrollTo(0,0)}else window.scrollTo(0,c)}),[f,c,s]))}Object.defineProperty(e,"AbortedDeferredError",{enumerable:!0,get:function(){return r.AbortedDeferredError}}),Object.defineProperty(e,"Await",{enumerable:!0,get:function(){return r.Await}}),Object.defineProperty(e,"MemoryRouter",{enumerable:!0,get:function(){return r.MemoryRouter}}),Object.defineProperty(e,"Navigate",{enumerable:!0,get:function(){return r.Navigate}}),Object.defineProperty(e,"NavigationType",{enumerable:!0,get:function(){return r.NavigationType}}),Object.defineProperty(e,"Outlet",{enumerable:!0,get:function(){return r.Outlet}}),Object.defineProperty(e,"Route",{enumerable:!0,get:function(){return r.Route}}),Object.defineProperty(e,"Router",{enumerable:!0,get:function(){return r.Router}}),Object.defineProperty(e,"RouterProvider",{enumerable:!0,get:function(){return r.RouterProvider}}),Object.defineProperty(e,"Routes",{enumerable:!0,get:function(){return r.Routes}}),Object.defineProperty(e,"UNSAFE_DataRouterContext",{enumerable:!0,get:function(){return r.UNSAFE_DataRouterContext}}),Object.defineProperty(e,"UNSAFE_DataRouterStateContext",{enumerable:!0,get:function(){return r.UNSAFE_DataRouterStateContext}}),Object.defineProperty(e,"UNSAFE_LocationContext",{enumerable:!0,get:function(){return r.UNSAFE_LocationContext}}),Object.defineProperty(e,"UNSAFE_NavigationContext",{enumerable:!0,get:function(){return r.UNSAFE_NavigationContext}}),Object.defineProperty(e,"UNSAFE_RouteContext",{enumerable:!0,get:function(){return r.UNSAFE_RouteContext}}),Object.defineProperty(e,"UNSAFE_useRouteId",{enumerable:!0,get:function(){return r.UNSAFE_useRouteId}}),Object.defineProperty(e,"createMemoryRouter",{enumerable:!0,get:function(){return r.createMemoryRouter}}),Object.defineProperty(e,"createPath",{enumerable:!0,get:function(){return r.createPath}}),Object.defineProperty(e,"createRoutesFromChildren",{enumerable:!0,get:function(){return r.createRoutesFromChildren}}),Object.defineProperty(e,"createRoutesFromElements",{enumerable:!0,get:function(){return r.createRoutesFromElements}}),Object.defineProperty(e,"defer",{enumerable:!0,get:function(){return r.defer}}),Object.defineProperty(e,"generatePath",{enumerable:!0,get:function(){return r.generatePath}}),Object.defineProperty(e,"isRouteErrorResponse",{enumerable:!0,get:function(){return r.isRouteErrorResponse}}),Object.defineProperty(e,"json",{enumerable:!0,get:function(){return r.json}}),Object.defineProperty(e,"matchPath",{enumerable:!0,get:function(){return r.matchPath}}),Object.defineProperty(e,"matchRoutes",{enumerable:!0,get:function(){return r.matchRoutes}}),Object.defineProperty(e,"parsePath",{enumerable:!0,get:function(){return r.parsePath}}),Object.defineProperty(e,"redirect",{enumerable:!0,get:function(){return r.redirect}}),Object.defineProperty(e,"redirectDocument",{enumerable:!0,get:function(){return r.redirectDocument}}),Object.defineProperty(e,"renderMatches",{enumerable:!0,get:function(){return r.renderMatches}}),Object.defineProperty(e,"resolvePath",{enumerable:!0,get:function(){return r.resolvePath}}),Object.defineProperty(e,"unstable_useBlocker",{enumerable:!0,get:function(){return r.unstable_useBlocker}}),Object.defineProperty(e,"useActionData",{enumerable:!0,get:function(){return r.useActionData}}),Object.defineProperty(e,"useAsyncError",{enumerable:!0,get:function(){return r.useAsyncError}}),Object.defineProperty(e,"useAsyncValue",{enumerable:!0,get:function(){return r.useAsyncValue}}),Object.defineProperty(e,"useHref",{enumerable:!0,get:function(){return r.useHref}}),Object.defineProperty(e,"useInRouterContext",{enumerable:!0,get:function(){return r.useInRouterContext}}),Object.defineProperty(e,"useLoaderData",{enumerable:!0,get:function(){return r.useLoaderData}}),Object.defineProperty(e,"useLocation",{enumerable:!0,get:function(){return r.useLocation}}),Object.defineProperty(e,"useMatch",{enumerable:!0,get:function(){return r.useMatch}}),Object.defineProperty(e,"useMatches",{enumerable:!0,get:function(){return r.useMatches}}),Object.defineProperty(e,"useNavigate",{enumerable:!0,get:function(){return r.useNavigate}}),Object.defineProperty(e,"useNavigation",{enumerable:!0,get:function(){return r.useNavigation}}),Object.defineProperty(e,"useNavigationType",{enumerable:!0,get:function(){return r.useNavigationType}}),Object.defineProperty(e,"useOutlet",{enumerable:!0,get:function(){return r.useOutlet}}),Object.defineProperty(e,"useOutletContext",{enumerable:!0,get:function(){return r.useOutletContext}}),Object.defineProperty(e,"useParams",{enumerable:!0,get:function(){return r.useParams}}),Object.defineProperty(e,"useResolvedPath",{enumerable:!0,get:function(){return r.useResolvedPath}}),Object.defineProperty(e,"useRevalidator",{enumerable:!0,get:function(){return r.useRevalidator}}),Object.defineProperty(e,"useRouteError",{enumerable:!0,get:function(){return r.useRouteError}}),Object.defineProperty(e,"useRouteLoaderData",{enumerable:!0,get:function(){return r.useRouteLoaderData}}),Object.defineProperty(e,"useRoutes",{enumerable:!0,get:function(){return r.useRoutes}}),e.BrowserRouter=function(e){let{basename:t,children:o,future:u,window:i}=e,c=a.useRef();null==c.current&&(c.current=n.createBrowserHistory({window:i,v5Compat:!0}));let s=c.current,[l,f]=a.useState({action:s.action,location:s.location}),{v7_startTransition:d}=u||{},m=a.useCallback((e=>{d&&w?w((()=>f(e))):f(e)}),[f,d]);return a.useLayoutEffect((()=>s.listen(m)),[s,m]),a.createElement(r.Router,{basename:t,children:o,location:l.location,navigationType:l.action,navigator:s})},e.Form=j,e.HashRouter=function(e){let{basename:t,children:o,future:u,window:i}=e,c=a.useRef();null==c.current&&(c.current=n.createHashHistory({window:i,v5Compat:!0}));let s=c.current,[l,f]=a.useState({action:s.action,location:s.location}),{v7_startTransition:d}=u||{},m=a.useCallback((e=>{d&&w?w((()=>f(e))):f(e)}),[f,d]);return a.useLayoutEffect((()=>s.listen(m)),[s,m]),a.createElement(r.Router,{basename:t,children:o,location:l.location,navigationType:l.action,navigator:s})},e.Link=E,e.NavLink=O,e.ScrollRestoration=function(e){let{getKey:t,storageKey:r}=e;return H({getKey:t,storageKey:r}),null},e.UNSAFE_useScrollRestoration=H,e.createBrowserRouter=function(e,t){return n.createRouter({basename:null==t?void 0:t.basename,future:u({},null==t?void 0:t.future,{v7_prependBasename:!0}),history:n.createBrowserHistory({window:null==t?void 0:t.window}),hydrationData:(null==t?void 0:t.hydrationData)||v(),routes:e,mapRouteProperties:r.UNSAFE_mapRouteProperties}).initialize()},e.createHashRouter=function(e,t){return n.createRouter({basename:null==t?void 0:t.basename,future:u({},null==t?void 0:t.future,{v7_prependBasename:!0}),history:n.createHashHistory({window:null==t?void 0:t.window}),hydrationData:(null==t?void 0:t.hydrationData)||v(),routes:e,mapRouteProperties:r.UNSAFE_mapRouteProperties}).initialize()},e.createSearchParams=f,e.unstable_HistoryRouter=function(e){let{basename:t,children:n,future:o,history:u}=e,[i,c]=a.useState({action:u.action,location:u.location}),{v7_startTransition:s}=o||{},l=a.useCallback((e=>{s&&w?w((()=>c(e))):c(e)}),[c,s]);return a.useLayoutEffect((()=>u.listen(l)),[u,l]),a.createElement(r.Router,{basename:t,children:n,location:i.location,navigationType:i.action,navigator:u})},e.unstable_usePrompt=function(e){let{when:t,message:n}=e,o=r.unstable_useBlocker(t);a.useEffect((()=>{if("blocked"===o.state){window.confirm(n)?setTimeout(o.proceed,0):o.reset()}}),[o,n]),a.useEffect((()=>{"blocked"!==o.state||t||o.reset()}),[o,t])},e.useBeforeUnload=function(e,t){let{capture:r}=t||{};a.useEffect((()=>{let t=null!=r?{capture:r}:void 0;return window.addEventListener("beforeunload",e,t),()=>{window.removeEventListener("beforeunload",e,t)}}),[e,r])},e.useFetcher=function(){var e;let{router:t}=_(A.UseFetcher),o=a.useContext(r.UNSAFE_RouteContext);o||n.UNSAFE_invariant(!1);let i=null==(e=o.matches[o.matches.length-1])?void 0:e.route.id;null==i&&n.UNSAFE_invariant(!1);let[c]=a.useState((()=>String(++k))),[s]=a.useState((()=>(i||n.UNSAFE_invariant(!1),function(e,t){return a.forwardRef(((r,n)=>{let o=D(e,t);return a.createElement(N,u({},r,{ref:n,submit:o}))}))}(c,i)))),[l]=a.useState((()=>e=>{t||n.UNSAFE_invariant(!1),i||n.UNSAFE_invariant(!1),t.fetch(c,i,e)})),f=D(c,i),d=t.getFetcher(c),m=a.useMemo((()=>u({Form:s,submit:f,load:l},d)),[d,s,f,l]);return a.useEffect((()=>()=>{t?t.deleteFetcher(c):console.warn("No router available to clean up from useFetcher()")}),[t,c]),m},e.useFetchers=function(){return[...F(C.UseFetchers).fetchers.values()]},e.useFormAction=T,e.useLinkClickHandler=U,e.useSearchParams=function(e){let t=a.useRef(f(e)),n=a.useRef(!1),o=r.useLocation(),u=a.useMemo((()=>function(e,t){let r=f(e);return t&&t.forEach(((e,n)=>{r.has(n)||t.getAll(n).forEach((e=>{r.append(n,e)}))})),r}(o.search,n.current?null:t.current)),[o.search]),i=r.useNavigate(),c=a.useCallback(((e,t)=>{const r=f("function"==typeof e?e(u):e);n.current=!0,i("?"+r,t)}),[i,u]);return[u,c]},e.useSubmit=L,Object.defineProperty(e,"__esModule",{value:!0})}));
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("react-router")):"function"==typeof define&&define.amd?define(["exports","react-router"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).ReactRouterDOM={},e.ReactRouter)}(this,(function(e,t){"use strict";Object.keys(t).forEach((function(o){"default"===o||e.hasOwnProperty(o)||Object.defineProperty(e,o,{enumerable:!0,get:function(){return t[o]}})})),Object.defineProperty(e,"__esModule",{value:!0})}));
//# sourceMappingURL=react-router-dom.production.min.js.map
{
"name": "react-router-dom",
"version": "0.0.0-experimental-4286521e",
"version": "0.0.0-experimental-42a5853ef",
"description": "Declarative routing for React web applications",

@@ -23,7 +23,14 @@ "keywords": [

"unpkg": "./dist/umd/react-router-dom.production.min.js",
"module": "./dist/index.js",
"module": "./dist/index.mjs",
"types": "./dist/index.d.ts",
"exports": {
".": {
"types": "./dist/index.d.ts",
"import": "./dist/index.mjs",
"require": "./dist/main.js"
},
"./package.json": "./package.json"
},
"dependencies": {
"@remix-run/router": "0.0.0-experimental-4286521e",
"react-router": "0.0.0-experimental-4286521e"
"react-router": "0.0.0-experimental-42a5853ef"
},

@@ -35,17 +42,13 @@ "devDependencies": {

"peerDependencies": {
"react": ">=16.8",
"react-dom": ">=16.8"
"react": ">=18",
"react-dom": ">=18"
},
"files": [
"dist/",
"CHANGELOG.md",
"LICENSE.md",
"README.md",
"server.d.ts",
"server.js",
"server.mjs"
"README.md"
],
"engines": {
"node": ">=14.0.0"
"node": ">=18.0.0"
}
}
}
# React Router DOM
The `react-router-dom` package contains bindings for using [React
Router](https://github.com/remix-run/react-router) in web applications.
Please see [the Getting Started guide](https://reactrouter.com/en/main/start/tutorial) for more information on how to get started with React Router.
The `react-router-dom` package is deprecated and only kept around for backwards-compatibility. It re-exports everything from the `react-router` package - you should convert your applications to import everything from `react-router` in v7 and beyond.

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc