react-router-dom-v5-compat
Advanced tools
Comparing version 0.0.0-experimental-cf9637ce to 0.0.0-experimental-cffa549a1
419
CHANGELOG.md
# `react-router-dom-v5-compat` | ||
## 6.25.0 | ||
### Patch Changes | ||
- Updated dependencies: | ||
- `react-router@6.25.0` | ||
- `@remix-run/router@1.18.0` | ||
- `react-router-dom@6.25.0` | ||
## 6.24.1 | ||
### Patch Changes | ||
- Updated dependencies: | ||
- `react-router-dom@6.24.1` | ||
- `@remix-run/router@1.17.1` | ||
- `react-router@6.24.1` | ||
## 6.24.0 | ||
### Patch Changes | ||
- Allow falsy `location.state` values passed to `<StaticRouter>` ([#11495](https://github.com/remix-run/react-router/pull/11495)) | ||
- Updated dependencies: | ||
- `react-router-dom@6.24.0` | ||
- `react-router@6.24.0` | ||
- `@remix-run/router@1.17.0` | ||
## 6.23.1 | ||
### Patch Changes | ||
- Updated dependencies: | ||
- `@remix-run/router@1.16.1` | ||
- `react-router-dom@6.23.1` | ||
- `react-router@6.23.1` | ||
## 6.23.0 | ||
### Minor Changes | ||
- Add a new `unstable_dataStrategy` configuration option ([#11098](https://github.com/remix-run/react-router/pull/11098)) | ||
- This option allows Data Router applications to take control over the approach for executing route loaders and actions | ||
- The default implementation is today's behavior, to fetch all loaders in parallel, but this option allows users to implement more advanced data flows including Remix single-fetch, middleware/context APIs, automatic loader caching, and more | ||
### Patch Changes | ||
- Updated dependencies: | ||
- `@remix-run/router@1.16.0` | ||
- `react-router@6.23.0` | ||
- `react-router-dom@6.23.0` | ||
## 6.22.3 | ||
### Patch Changes | ||
- Updated dependencies: | ||
- `react-router@6.22.3` | ||
- `react-router-dom@6.22.3` | ||
## 6.22.2 | ||
### Patch Changes | ||
- Updated dependencies: | ||
- `react-router@6.22.2` | ||
- `react-router-dom@6.22.2` | ||
## 6.22.1 | ||
### Patch Changes | ||
- Updated dependencies: | ||
- `react-router@6.22.1` | ||
- `react-router-dom@6.22.1` | ||
## 6.22.0 | ||
### Minor Changes | ||
- Include a `window__reactRouterVersion` tag for CWV Report detection ([#11222](https://github.com/remix-run/react-router/pull/11222)) | ||
### Patch Changes | ||
- Updated dependencies: | ||
- `react-router-dom@6.22.0` | ||
- `react-router@6.22.0` | ||
## 6.21.3 | ||
### Patch Changes | ||
- Remove leftover `unstable_` prefix from `Blocker`/`BlockerFunction` types ([#11187](https://github.com/remix-run/react-router/pull/11187)) | ||
- Updated dependencies: | ||
- `react-router-dom@6.21.3` | ||
- `react-router@6.21.3` | ||
## 6.21.2 | ||
### Patch Changes | ||
- Updated dependencies: | ||
- `react-router-dom@6.21.2` | ||
- `react-router@6.21.2` | ||
## 6.21.1 | ||
### Patch Changes | ||
- Updated dependencies: | ||
- `react-router@6.21.1` | ||
- `react-router-dom@6.21.1` | ||
## 6.21.0 | ||
### Minor Changes | ||
- Add a new `future.v7_relativeSplatPath` flag to implement a breaking bug fix to relative routing when inside a splat route. ([#11087](https://github.com/remix-run/react-router/pull/11087)) | ||
This fix was originally added in [#10983](https://github.com/remix-run/react-router/issues/10983) and was later reverted in [#11078](https://github.com/remix-run/react-router/pull/11078) because it was determined that a large number of existing applications were relying on the buggy behavior (see [#11052](https://github.com/remix-run/react-router/issues/11052)) | ||
**The Bug** | ||
The buggy behavior is that without this flag, the default behavior when resolving relative paths is to _ignore_ any splat (`*`) portion of the current route path. | ||
**The Background** | ||
This decision was originally made thinking that it would make the concept of nested different sections of your apps in `<Routes>` easier if relative routing would _replace_ the current splat: | ||
```jsx | ||
<BrowserRouter> | ||
<Routes> | ||
<Route path="/" element={<Home />} /> | ||
<Route path="dashboard/*" element={<Dashboard />} /> | ||
</Routes> | ||
</BrowserRouter> | ||
``` | ||
Any paths like `/dashboard`, `/dashboard/team`, `/dashboard/projects` will match the `Dashboard` route. The dashboard component itself can then render nested `<Routes>`: | ||
```jsx | ||
function Dashboard() { | ||
return ( | ||
<div> | ||
<h2>Dashboard</h2> | ||
<nav> | ||
<Link to="/">Dashboard Home</Link> | ||
<Link to="team">Team</Link> | ||
<Link to="projects">Projects</Link> | ||
</nav> | ||
<Routes> | ||
<Route path="/" element={<DashboardHome />} /> | ||
<Route path="team" element={<DashboardTeam />} /> | ||
<Route path="projects" element={<DashboardProjects />} /> | ||
</Routes> | ||
</div> | ||
); | ||
} | ||
``` | ||
Now, all links and route paths are relative to the router above them. This makes code splitting and compartmentalizing your app really easy. You could render the `Dashboard` as its own independent app, or embed it into your large app without making any changes to it. | ||
**The Problem** | ||
The problem is that this concept of ignoring part of a path breaks a lot of other assumptions in React Router - namely that `"."` always means the current location pathname for that route. When we ignore the splat portion, we start getting invalid paths when using `"."`: | ||
```jsx | ||
// If we are on URL /dashboard/team, and we want to link to /dashboard/team: | ||
function DashboardTeam() { | ||
// ❌ This is broken and results in <a href="/dashboard"> | ||
return <Link to=".">A broken link to the Current URL</Link>; | ||
// ✅ This is fixed but super unintuitive since we're already at /dashboard/team! | ||
return <Link to="./team">A broken link to the Current URL</Link>; | ||
} | ||
``` | ||
We've also introduced an issue that we can no longer move our `DashboardTeam` component around our route hierarchy easily - since it behaves differently if we're underneath a non-splat route, such as `/dashboard/:widget`. Now, our `"."` links will, properly point to ourself _inclusive of the dynamic param value_ so behavior will break from it's corresponding usage in a `/dashboard/*` route. | ||
Even worse, consider a nested splat route configuration: | ||
```jsx | ||
<BrowserRouter> | ||
<Routes> | ||
<Route path="dashboard"> | ||
<Route path="*" element={<Dashboard />} /> | ||
</Route> | ||
</Routes> | ||
</BrowserRouter> | ||
``` | ||
Now, a `<Link to=".">` and a `<Link to="..">` inside the `Dashboard` component go to the same place! That is definitely not correct! | ||
Another common issue arose in Data Routers (and Remix) where any `<Form>` should post to it's own route `action` if you the user doesn't specify a form action: | ||
```jsx | ||
let router = createBrowserRouter({ | ||
path: "/dashboard", | ||
children: [ | ||
{ | ||
path: "*", | ||
action: dashboardAction, | ||
Component() { | ||
// ❌ This form is broken! It throws a 405 error when it submits because | ||
// it tries to submit to /dashboard (without the splat value) and the parent | ||
// `/dashboard` route doesn't have an action | ||
return <Form method="post">...</Form>; | ||
}, | ||
}, | ||
], | ||
}); | ||
``` | ||
This is just a compounded issue from the above because the default location for a `Form` to submit to is itself (`"."`) - and if we ignore the splat portion, that now resolves to the parent route. | ||
**The Solution** | ||
If you are leveraging this behavior, it's recommended to enable the future flag, move your splat to it's own route, and leverage `../` for any links to "sibling" pages: | ||
```jsx | ||
<BrowserRouter> | ||
<Routes> | ||
<Route path="dashboard"> | ||
<Route index path="*" element={<Dashboard />} /> | ||
</Route> | ||
</Routes> | ||
</BrowserRouter> | ||
function Dashboard() { | ||
return ( | ||
<div> | ||
<h2>Dashboard</h2> | ||
<nav> | ||
<Link to="..">Dashboard Home</Link> | ||
<Link to="../team">Team</Link> | ||
<Link to="../projects">Projects</Link> | ||
</nav> | ||
<Routes> | ||
<Route path="/" element={<DashboardHome />} /> | ||
<Route path="team" element={<DashboardTeam />} /> | ||
<Route path="projects" element={<DashboardProjects />} /> | ||
</Router> | ||
</div> | ||
); | ||
} | ||
``` | ||
This way, `.` means "the full current pathname for my route" in all cases (including static, dynamic, and splat routes) and `..` always means "my parents pathname". | ||
### Patch Changes | ||
- Updated dependencies: | ||
- `react-router-dom@6.21.0` | ||
- `react-router@6.21.0` | ||
## 6.20.1 | ||
### Patch Changes | ||
- Updated dependencies: | ||
- `react-router-dom@6.20.1` | ||
- `react-router@6.20.1` | ||
## 6.20.0 | ||
### Minor Changes | ||
- Export the `PathParam` type from the public API ([#10719](https://github.com/remix-run/react-router/pull/10719)) | ||
### Patch Changes | ||
- Updated dependencies: | ||
- `react-router-dom@6.20.0` | ||
- `react-router@6.20.0` | ||
## 6.19.0 | ||
### Patch Changes | ||
- Updated dependencies: | ||
- `react-router-dom@6.19.0` | ||
- `react-router@6.19.0` | ||
## 6.18.0 | ||
### Patch Changes | ||
- Updated dependencies: | ||
- `react-router-dom@6.18.0` | ||
- `react-router@6.18.0` | ||
## 6.17.0 | ||
### Patch Changes | ||
- Updated dependencies: | ||
- `react-router-dom@6.17.0` | ||
- `react-router@6.17.0` | ||
## 6.16.0 | ||
### Minor Changes | ||
- Updated dependencies: | ||
- `react-router-dom@6.16.0` | ||
- `react-router@6.16.0` | ||
## 6.15.0 | ||
### Minor Changes | ||
- Add's a new `redirectDocument()` function which allows users to specify that a redirect from a `loader`/`action` should trigger a document reload (via `window.location`) instead of attempting to navigate to the redirected location via React Router ([#10705](https://github.com/remix-run/react-router/pull/10705)) | ||
### Patch Changes | ||
- Updated dependencies: | ||
- `react-router-dom@6.15.0` | ||
- `react-router@6.15.0` | ||
## 6.14.2 | ||
### Patch Changes | ||
- Updated dependencies: | ||
- `react-router-dom@6.14.2` | ||
- `react-router@6.14.2` | ||
## 6.14.1 | ||
### Patch Changes | ||
- Updated dependencies: | ||
- `react-router@6.14.1` | ||
- `react-router-dom@6.14.1` | ||
## 6.14.0 | ||
### Patch Changes | ||
- Upgrade `typescript` to 5.1 ([#10581](https://github.com/remix-run/react-router/pull/10581)) | ||
- Updated dependencies: | ||
- `react-router@6.14.0` | ||
- `react-router-dom@6.14.0` | ||
## 6.13.0 | ||
### Patch Changes | ||
- Updated dependencies: | ||
- `react-router@6.13.0` | ||
- `react-router-dom@6.13.0` | ||
## 6.12.1 | ||
### Patch Changes | ||
- Updated dependencies: | ||
- `react-router@6.12.1` | ||
- `react-router-dom@6.12.1` | ||
## 6.12.0 | ||
### Patch Changes | ||
- Updated dependencies: | ||
- `react-router-dom@6.12.0` | ||
- `react-router@6.12.0` | ||
## 6.11.2 | ||
### Patch Changes | ||
- Updated dependencies: | ||
- `react-router@6.11.2` | ||
- `react-router-dom@6.11.2` | ||
## 6.11.1 | ||
### Patch Changes | ||
- Updated dependencies: | ||
- `react-router@6.11.1` | ||
- `react-router-dom@6.11.1` | ||
## 6.11.0 | ||
### Patch Changes | ||
- Updated dependencies: | ||
- `react-router@6.11.0` | ||
- `react-router-dom@6.11.0` | ||
## 6.10.0 | ||
### Patch Changes | ||
- Updated dependencies: | ||
- `react-router@6.10.0` | ||
- `react-router-dom@6.10.0` | ||
## 6.9.0 | ||
### Minor Changes | ||
- Updated dependencies: | ||
- `react-router@6.9.0` | ||
- `react-router-dom@6.9.0` | ||
### Patch Changes | ||
- Add missed data router API re-exports ([#10171](https://github.com/remix-run/react-router/pull/10171)) | ||
## 6.8.2 | ||
### Patch Changes | ||
- Updated dependencies: | ||
- `react-router-dom@6.8.2` | ||
- `react-router@6.8.2` | ||
## 6.8.1 | ||
@@ -4,0 +423,0 @@ |
@@ -49,5 +49,5 @@ /** | ||
*/ | ||
export type { Hash, Location, Path, To, MemoryRouterProps, NavigateFunction, NavigateOptions, NavigateProps, Navigator, OutletProps, Params, ParamParseKey, PathMatch, RouteMatch, RouteObject, RouteProps, PathRouteProps, LayoutRouteProps, IndexRouteProps, RouterProps, Pathname, Search, RoutesProps, } from "./react-router-dom"; | ||
export { BrowserRouter, HashRouter, Link, MemoryRouter, NavLink, Navigate, NavigationType, Outlet, Route, Router, Routes, UNSAFE_LocationContext, UNSAFE_NavigationContext, UNSAFE_RouteContext, createPath, createRoutesFromChildren, createSearchParams, generatePath, matchPath, matchRoutes, parsePath, renderMatches, resolvePath, unstable_HistoryRouter, useHref, useInRouterContext, useLinkClickHandler, useLocation, useMatch, useNavigate, useNavigationType, useOutlet, useOutletContext, useParams, useResolvedPath, useRoutes, useSearchParams, } from "./react-router-dom"; | ||
export type { ActionFunction, ActionFunctionArgs, AwaitProps, BrowserRouterProps, unstable_DataStrategyFunction, unstable_DataStrategyFunctionArgs, unstable_DataStrategyMatch, DataRouteMatch, DataRouteObject, ErrorResponse, Fetcher, FetcherWithComponents, FormEncType, FormMethod, FormProps, FutureConfig, GetScrollRestorationKeyFunction, Hash, HashRouterProps, HistoryRouterProps, IndexRouteObject, IndexRouteProps, JsonFunction, LayoutRouteProps, LinkProps, LoaderFunction, LoaderFunctionArgs, Location, MemoryRouterProps, NavLinkProps, NavigateFunction, NavigateOptions, NavigateProps, Navigation, Navigator, NonIndexRouteObject, OutletProps, ParamKeyValuePair, ParamParseKey, Params, Path, PathMatch, PathParam, PathPattern, PathRouteProps, Pathname, RedirectFunction, RelativeRoutingType, RouteMatch, RouteObject, RouteProps, RouterProps, RouterProviderProps, RoutesProps, ScrollRestorationProps, Search, ShouldRevalidateFunction, ShouldRevalidateFunctionArgs, SubmitFunction, SubmitOptions, To, URLSearchParamsInit, UIMatch, Blocker, BlockerFunction, unstable_HandlerResult, } from "./react-router-dom"; | ||
export { AbortedDeferredError, Await, BrowserRouter, Form, HashRouter, Link, MemoryRouter, NavLink, Navigate, NavigationType, Outlet, Route, Router, RouterProvider, Routes, ScrollRestoration, UNSAFE_DataRouterContext, UNSAFE_DataRouterStateContext, UNSAFE_LocationContext, UNSAFE_NavigationContext, UNSAFE_RouteContext, UNSAFE_useRouteId, UNSAFE_useScrollRestoration, createBrowserRouter, createHashRouter, createMemoryRouter, createPath, createRoutesFromChildren, createRoutesFromElements, createSearchParams, defer, generatePath, isRouteErrorResponse, json, matchPath, matchRoutes, parsePath, redirect, redirectDocument, renderMatches, resolvePath, unstable_HistoryRouter, useBlocker, unstable_usePrompt, useActionData, useAsyncError, useAsyncValue, useBeforeUnload, useFetcher, useFetchers, useFormAction, useHref, useInRouterContext, useLinkClickHandler, useLoaderData, useLocation, useMatch, useMatches, useNavigate, useNavigation, useNavigationType, useOutlet, useOutletContext, useParams, useResolvedPath, useRevalidator, useRouteError, useRouteLoaderData, useRoutes, useSearchParams, useSubmit, } from "./react-router-dom"; | ||
export type { StaticRouterProps } from "./lib/components"; | ||
export { CompatRouter, CompatRoute, StaticRouter } from "./lib/components"; | ||
export { CompatRoute, CompatRouter, StaticRouter } from "./lib/components"; |
1342
dist/index.js
/** | ||
* React Router DOM v5 Compat v0.0.0-experimental-cf9637ce | ||
* React Router DOM v5 Compat v0.0.0-experimental-cffa549a1 | ||
* | ||
@@ -12,5 +12,6 @@ * Copyright (c) Remix Software Inc. | ||
import * as React from 'react'; | ||
import { Router, useHref, useResolvedPath, useLocation, UNSAFE_DataRouterStateContext, UNSAFE_NavigationContext, useNavigate, createPath, UNSAFE_RouteContext, UNSAFE_DataRouterContext, Routes, Route } from 'react-router'; | ||
export { MemoryRouter, Navigate, NavigationType, Outlet, Route, Router, Routes, UNSAFE_LocationContext, UNSAFE_NavigationContext, UNSAFE_RouteContext, createPath, createRoutesFromChildren, generatePath, matchPath, matchRoutes, parsePath, renderMatches, resolvePath, useHref, useInRouterContext, useLocation, useMatch, useNavigate, useNavigationType, useOutlet, useOutletContext, useParams, useResolvedPath, useRoutes } from 'react-router'; | ||
import { createBrowserHistory, createHashHistory, invariant, joinPaths } from '@remix-run/router'; | ||
import * as ReactDOM from 'react-dom'; | ||
import { UNSAFE_mapRouteProperties, UNSAFE_DataRouterContext, UNSAFE_DataRouterStateContext, Router, UNSAFE_useRoutesImpl, UNSAFE_NavigationContext, useHref, useResolvedPath, useLocation, useNavigate, createPath, UNSAFE_useRouteId, UNSAFE_RouteContext, useMatches, useNavigation, useBlocker, Routes, Route } from 'react-router'; | ||
export { AbortedDeferredError, Await, MemoryRouter, Navigate, NavigationType, Outlet, Route, Router, 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, useActionData, useAsyncError, useAsyncValue, useBlocker, 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, UNSAFE_ErrorResponseImpl, UNSAFE_invariant, joinPaths, IDLE_FETCHER, matchPath } from '@remix-run/router'; | ||
import { parsePath, Action, createPath as createPath$1 } from 'history'; | ||
@@ -23,3 +24,2 @@ import { Route as Route$1, useHistory } from 'react-router-dom'; | ||
var source = arguments[i]; | ||
for (var key in source) { | ||
@@ -31,3 +31,2 @@ if (Object.prototype.hasOwnProperty.call(source, key)) { | ||
} | ||
return target; | ||
@@ -37,3 +36,2 @@ }; | ||
} | ||
function _objectWithoutPropertiesLoose(source, excluded) { | ||
@@ -44,3 +42,2 @@ if (source == null) return {}; | ||
var key, i; | ||
for (i = 0; i < sourceKeys.length; i++) { | ||
@@ -51,3 +48,2 @@ key = sourceKeys[i]; | ||
} | ||
return target; | ||
@@ -70,10 +66,10 @@ } | ||
} | ||
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. | ||
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 | ||
@@ -103,3 +99,2 @@ ; | ||
*/ | ||
function createSearchParams(init) { | ||
@@ -109,3 +104,2 @@ if (init === void 0) { | ||
} | ||
return new URLSearchParams(typeof init === "string" || Array.isArray(init) || init instanceof URLSearchParams ? init : Object.keys(init).reduce((memo, key) => { | ||
@@ -118,5 +112,9 @@ let value = init[key]; | ||
let searchParams = createSearchParams(locationSearch); | ||
if (defaultSearchParams) { | ||
for (let key of defaultSearchParams.keys()) { | ||
// 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)) { | ||
@@ -127,8 +125,30 @@ defaultSearchParams.getAll(key).forEach(value => { | ||
} | ||
} | ||
}); | ||
} | ||
return searchParams; | ||
} | ||
function getFormSubmissionInfo(target, defaultAction, options) { | ||
// 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)) { | ||
process.env.NODE_ENV !== "production" ? UNSAFE_warning(false, "\"" + encType + "\" is not a valid `encType` for `<Form>`/`<fetcher.Form>` " + ("and will default to \"" + defaultEncType + "\"")) : void 0; | ||
return null; | ||
} | ||
return encType; | ||
} | ||
function getFormSubmissionInfo(target, basename) { | ||
let method; | ||
@@ -138,83 +158,477 @@ let action; | ||
let formData; | ||
let body; | ||
if (isFormElement(target)) { | ||
let submissionTrigger = options.submissionTrigger; | ||
method = options.method || target.getAttribute("method") || defaultMethod; | ||
action = options.action || target.getAttribute("action") || defaultAction; | ||
encType = options.encType || target.getAttribute("enctype") || defaultEncType; | ||
// 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); | ||
if (submissionTrigger && submissionTrigger.name) { | ||
formData.append(submissionTrigger.name, submissionTrigger.value); | ||
} | ||
} 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> | ||
method = options.method || target.getAttribute("formmethod") || form.getAttribute("method") || defaultMethod; | ||
action = options.action || target.getAttribute("formaction") || form.getAttribute("action") || defaultAction; | ||
encType = options.encType || target.getAttribute("formenctype") || form.getAttribute("enctype") || defaultEncType; | ||
formData = new FormData(form); // Include name + value from a <button>, appending in case the button name | ||
// matches an existing input name | ||
if (target.name) { | ||
formData.append(target.name, target.value); | ||
} | ||
// <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 = options.method || defaultMethod; | ||
action = options.action || defaultAction; | ||
encType = options.encType || defaultEncType; | ||
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 | ||
}; | ||
} | ||
if (target instanceof FormData) { | ||
formData = target; | ||
const _excluded = ["onClick", "relative", "reloadDocument", "replace", "state", "target", "to", "preventScrollReset", "unstable_viewTransition"], | ||
_excluded2 = ["aria-current", "caseSensitive", "className", "end", "style", "to", "unstable_viewTransition", "children"], | ||
_excluded3 = ["fetcherKey", "navigate", "reloadDocument", "replace", "state", "method", "action", "onSubmit", "relative", "preventScrollReset", "unstable_viewTransition"]; | ||
// HEY YOU! DON'T TOUCH THIS VARIABLE! | ||
// | ||
// It is replaced with the proper version at build time via a babel plugin in | ||
// the rollup config. | ||
// | ||
// Export a global property onto the window for React Router detection by the | ||
// Core Web Vitals Technology Report. This way they can configure the `wappalyzer` | ||
// to detect and properly classify live websites as being built with React Router: | ||
// https://github.com/HTTPArchive/wappalyzer/blob/main/src/technologies/r.json | ||
const REACT_ROUTER_VERSION = "0"; | ||
try { | ||
window.__reactRouterVersion = REACT_ROUTER_VERSION; | ||
} catch (e) { | ||
// no-op | ||
} | ||
function createBrowserRouter(routes, opts) { | ||
return createRouter({ | ||
basename: opts == null ? void 0 : opts.basename, | ||
future: _extends({}, opts == null ? void 0 : opts.future, { | ||
v7_prependBasename: true | ||
}), | ||
history: createBrowserHistory({ | ||
window: opts == null ? void 0 : opts.window | ||
}), | ||
hydrationData: (opts == null ? void 0 : opts.hydrationData) || parseHydrationData(), | ||
routes, | ||
mapRouteProperties: UNSAFE_mapRouteProperties, | ||
unstable_dataStrategy: opts == null ? void 0 : opts.unstable_dataStrategy, | ||
unstable_patchRoutesOnMiss: opts == null ? void 0 : opts.unstable_patchRoutesOnMiss, | ||
window: opts == null ? void 0 : opts.window | ||
}).initialize(); | ||
} | ||
function createHashRouter(routes, opts) { | ||
return createRouter({ | ||
basename: opts == null ? void 0 : opts.basename, | ||
future: _extends({}, opts == null ? void 0 : opts.future, { | ||
v7_prependBasename: true | ||
}), | ||
history: createHashHistory({ | ||
window: opts == null ? void 0 : opts.window | ||
}), | ||
hydrationData: (opts == null ? void 0 : opts.hydrationData) || parseHydrationData(), | ||
routes, | ||
mapRouteProperties: UNSAFE_mapRouteProperties, | ||
unstable_dataStrategy: opts == null ? void 0 : opts.unstable_dataStrategy, | ||
unstable_patchRoutesOnMiss: opts == null ? void 0 : opts.unstable_patchRoutesOnMiss, | ||
window: opts == null ? void 0 : opts.window | ||
}).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 UNSAFE_ErrorResponseImpl(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 { | ||
formData = new FormData(); | ||
serialized[key] = val; | ||
} | ||
} | ||
return serialized; | ||
} | ||
const ViewTransitionContext = /*#__PURE__*/React.createContext({ | ||
isTransitioning: false | ||
}); | ||
if (process.env.NODE_ENV !== "production") { | ||
ViewTransitionContext.displayName = "ViewTransition"; | ||
} | ||
const FetchersContext = /*#__PURE__*/React.createContext(new Map()); | ||
if (process.env.NODE_ENV !== "production") { | ||
FetchersContext.displayName = "Fetchers"; | ||
} | ||
//#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() | ||
if (target instanceof URLSearchParams) { | ||
for (let [name, value] of target) { | ||
formData.append(name, value); | ||
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]; | ||
const FLUSH_SYNC = "flushSync"; | ||
const flushSyncImpl = ReactDOM[FLUSH_SYNC]; | ||
const USE_ID = "useId"; | ||
const useIdImpl = React[USE_ID]; | ||
function startTransitionSafe(cb) { | ||
if (startTransitionImpl) { | ||
startTransitionImpl(cb); | ||
} else { | ||
cb(); | ||
} | ||
} | ||
function flushSyncSafe(cb) { | ||
if (flushSyncImpl) { | ||
flushSyncImpl(cb); | ||
} else { | ||
cb(); | ||
} | ||
} | ||
class Deferred { | ||
constructor() { | ||
this.status = "pending"; | ||
this.promise = new Promise((resolve, reject) => { | ||
this.resolve = value => { | ||
if (this.status === "pending") { | ||
this.status = "resolved"; | ||
resolve(value); | ||
} | ||
} else if (target != null) { | ||
for (let name of Object.keys(target)) { | ||
formData.append(name, target[name]); | ||
}; | ||
this.reject = reason => { | ||
if (this.status === "pending") { | ||
this.status = "rejected"; | ||
reject(reason); | ||
} | ||
}; | ||
}); | ||
} | ||
} | ||
/** | ||
* Given a Remix Router instance, render the appropriate UI | ||
*/ | ||
function RouterProvider(_ref) { | ||
let { | ||
fallbackElement, | ||
router, | ||
future | ||
} = _ref; | ||
let [state, setStateImpl] = React.useState(router.state); | ||
let [pendingState, setPendingState] = React.useState(); | ||
let [vtContext, setVtContext] = React.useState({ | ||
isTransitioning: false | ||
}); | ||
let [renderDfd, setRenderDfd] = React.useState(); | ||
let [transition, setTransition] = React.useState(); | ||
let [interruption, setInterruption] = React.useState(); | ||
let fetcherData = React.useRef(new Map()); | ||
let { | ||
v7_startTransition | ||
} = future || {}; | ||
let optInStartTransition = React.useCallback(cb => { | ||
if (v7_startTransition) { | ||
startTransitionSafe(cb); | ||
} else { | ||
cb(); | ||
} | ||
}, [v7_startTransition]); | ||
let setState = React.useCallback((newState, _ref2) => { | ||
let { | ||
deletedFetchers, | ||
unstable_flushSync: flushSync, | ||
unstable_viewTransitionOpts: viewTransitionOpts | ||
} = _ref2; | ||
deletedFetchers.forEach(key => fetcherData.current.delete(key)); | ||
newState.fetchers.forEach((fetcher, key) => { | ||
if (fetcher.data !== undefined) { | ||
fetcherData.current.set(key, fetcher.data); | ||
} | ||
}); | ||
let isViewTransitionUnavailable = router.window == null || router.window.document == null || typeof router.window.document.startViewTransition !== "function"; | ||
// If this isn't a view transition or it's not available in this browser, | ||
// just update and be done with it | ||
if (!viewTransitionOpts || isViewTransitionUnavailable) { | ||
if (flushSync) { | ||
flushSyncSafe(() => setStateImpl(newState)); | ||
} else { | ||
optInStartTransition(() => setStateImpl(newState)); | ||
} | ||
return; | ||
} | ||
} | ||
// flushSync + startViewTransition | ||
if (flushSync) { | ||
// Flush through the context to mark DOM elements as transition=ing | ||
flushSyncSafe(() => { | ||
// Cancel any pending transitions | ||
if (transition) { | ||
renderDfd && renderDfd.resolve(); | ||
transition.skipTransition(); | ||
} | ||
setVtContext({ | ||
isTransitioning: true, | ||
flushSync: true, | ||
currentLocation: viewTransitionOpts.currentLocation, | ||
nextLocation: viewTransitionOpts.nextLocation | ||
}); | ||
}); | ||
// Update the DOM | ||
let t = router.window.document.startViewTransition(() => { | ||
flushSyncSafe(() => setStateImpl(newState)); | ||
}); | ||
// Clean up after the animation completes | ||
t.finished.finally(() => { | ||
flushSyncSafe(() => { | ||
setRenderDfd(undefined); | ||
setTransition(undefined); | ||
setPendingState(undefined); | ||
setVtContext({ | ||
isTransitioning: false | ||
}); | ||
}); | ||
}); | ||
flushSyncSafe(() => setTransition(t)); | ||
return; | ||
} | ||
// startTransition + startViewTransition | ||
if (transition) { | ||
// Interrupting an in-progress transition, cancel and let everything flush | ||
// out, and then kick off a new transition from the interruption state | ||
renderDfd && renderDfd.resolve(); | ||
transition.skipTransition(); | ||
setInterruption({ | ||
state: newState, | ||
currentLocation: viewTransitionOpts.currentLocation, | ||
nextLocation: viewTransitionOpts.nextLocation | ||
}); | ||
} else { | ||
// Completed navigation update with opted-in view transitions, let 'er rip | ||
setPendingState(newState); | ||
setVtContext({ | ||
isTransitioning: true, | ||
flushSync: false, | ||
currentLocation: viewTransitionOpts.currentLocation, | ||
nextLocation: viewTransitionOpts.nextLocation | ||
}); | ||
} | ||
}, [router.window, transition, renderDfd, fetcherData, optInStartTransition]); | ||
// Need to use a layout effect here so we are subscribed early enough to | ||
// pick up on any render-driven redirects/navigations (useEffect/<Navigate>) | ||
React.useLayoutEffect(() => router.subscribe(setState), [router, setState]); | ||
// When we start a view transition, create a Deferred we can use for the | ||
// eventual "completed" render | ||
React.useEffect(() => { | ||
if (vtContext.isTransitioning && !vtContext.flushSync) { | ||
setRenderDfd(new Deferred()); | ||
} | ||
}, [vtContext]); | ||
// Once the deferred is created, kick off startViewTransition() to update the | ||
// DOM and then wait on the Deferred to resolve (indicating the DOM update has | ||
// happened) | ||
React.useEffect(() => { | ||
if (renderDfd && pendingState && router.window) { | ||
let newState = pendingState; | ||
let renderPromise = renderDfd.promise; | ||
let transition = router.window.document.startViewTransition(async () => { | ||
optInStartTransition(() => setStateImpl(newState)); | ||
await renderPromise; | ||
}); | ||
transition.finished.finally(() => { | ||
setRenderDfd(undefined); | ||
setTransition(undefined); | ||
setPendingState(undefined); | ||
setVtContext({ | ||
isTransitioning: false | ||
}); | ||
}); | ||
setTransition(transition); | ||
} | ||
}, [optInStartTransition, pendingState, renderDfd, router.window]); | ||
// When the new location finally renders and is committed to the DOM, this | ||
// effect will run to resolve the transition | ||
React.useEffect(() => { | ||
if (renderDfd && pendingState && state.location.key === pendingState.location.key) { | ||
renderDfd.resolve(); | ||
} | ||
}, [renderDfd, transition, state.location, pendingState]); | ||
// If we get interrupted with a new navigation during a transition, we skip | ||
// the active transition, let it cleanup, then kick it off again here | ||
React.useEffect(() => { | ||
if (!vtContext.isTransitioning && interruption) { | ||
setPendingState(interruption.state); | ||
setVtContext({ | ||
isTransitioning: true, | ||
flushSync: false, | ||
currentLocation: interruption.currentLocation, | ||
nextLocation: interruption.nextLocation | ||
}); | ||
setInterruption(undefined); | ||
} | ||
}, [vtContext.isTransitioning, interruption]); | ||
React.useEffect(() => { | ||
process.env.NODE_ENV !== "production" ? UNSAFE_warning(fallbackElement == null || !router.future.v7_partialHydration, "`<RouterProvider fallbackElement>` is deprecated when using " + "`v7_partialHydration`, use a `HydrateFallback` component instead") : void 0; | ||
// Only log this once on initial mount | ||
// eslint-disable-next-line react-hooks/exhaustive-deps | ||
}, []); | ||
let navigator = React.useMemo(() => { | ||
return { | ||
createHref: router.createHref, | ||
encodeLocation: router.encodeLocation, | ||
go: n => router.navigate(n), | ||
push: (to, state, opts) => router.navigate(to, { | ||
state, | ||
preventScrollReset: opts == null ? void 0 : opts.preventScrollReset | ||
}), | ||
replace: (to, state, opts) => router.navigate(to, { | ||
replace: true, | ||
state, | ||
preventScrollReset: opts == null ? void 0 : opts.preventScrollReset | ||
}) | ||
}; | ||
}, [router]); | ||
let basename = router.basename || "/"; | ||
let dataRouterContext = React.useMemo(() => ({ | ||
router, | ||
navigator, | ||
static: false, | ||
basename | ||
}), [router, navigator, basename]); | ||
// The fragment and {null} here are important! We need them to keep React 18's | ||
// useId happy when we are server-rendering since we may have a <script> here | ||
// containing the hydrated server-side staticContext (from StaticRouterProvider). | ||
// useId relies on the component tree structure to generate deterministic id's | ||
// so we need to ensure it remains the same on the client even though | ||
// we don't need the <script> tag | ||
return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(UNSAFE_DataRouterContext.Provider, { | ||
value: dataRouterContext | ||
}, /*#__PURE__*/React.createElement(UNSAFE_DataRouterStateContext.Provider, { | ||
value: state | ||
}, /*#__PURE__*/React.createElement(FetchersContext.Provider, { | ||
value: fetcherData.current | ||
}, /*#__PURE__*/React.createElement(ViewTransitionContext.Provider, { | ||
value: vtContext | ||
}, /*#__PURE__*/React.createElement(Router, { | ||
basename: basename, | ||
location: state.location, | ||
navigationType: state.historyAction, | ||
navigator: navigator, | ||
future: { | ||
v7_relativeSplatPath: router.future.v7_relativeSplatPath | ||
} | ||
}, state.initialized || router.future.v7_partialHydration ? /*#__PURE__*/React.createElement(DataRoutes, { | ||
routes: router.routes, | ||
future: router.future, | ||
state: state | ||
}) : fallbackElement))))), null); | ||
} | ||
function DataRoutes(_ref3) { | ||
let { | ||
protocol, | ||
host | ||
} = window.location; | ||
let url = new URL(action, protocol + "//" + host); | ||
return { | ||
url, | ||
method: method.toLowerCase(), | ||
encType, | ||
formData | ||
}; | ||
routes, | ||
future, | ||
state | ||
} = _ref3; | ||
return UNSAFE_useRoutesImpl(routes, undefined, state, future); | ||
} | ||
const _excluded = ["onClick", "relative", "reloadDocument", "replace", "state", "target", "to", "preventScrollReset"], | ||
_excluded2 = ["aria-current", "caseSensitive", "className", "end", "style", "to", "children"], | ||
_excluded3 = ["reloadDocument", "replace", "method", "action", "onSubmit", "fetcherKey", "routeId", "relative", "preventScrollReset"]; | ||
/** | ||
* A `<Router>` for use in web browsers. Provides the cleanest URLs. | ||
*/ | ||
function BrowserRouter(_ref) { | ||
function BrowserRouter(_ref4) { | ||
let { | ||
basename, | ||
children, | ||
future, | ||
window | ||
} = _ref; | ||
} = _ref4; | ||
let historyRef = React.useRef(); | ||
if (historyRef.current == null) { | ||
@@ -226,9 +640,14 @@ historyRef.current = createBrowserHistory({ | ||
} | ||
let history = historyRef.current; | ||
let [state, setState] = React.useState({ | ||
let [state, setStateImpl] = React.useState({ | ||
action: history.action, | ||
location: history.location | ||
}); | ||
React.useLayoutEffect(() => history.listen(setState), [history]); | ||
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, { | ||
@@ -239,3 +658,4 @@ basename: basename, | ||
navigationType: state.action, | ||
navigator: history | ||
navigator: history, | ||
future: future | ||
}); | ||
@@ -247,11 +667,10 @@ } | ||
*/ | ||
function HashRouter(_ref2) { | ||
function HashRouter(_ref5) { | ||
let { | ||
basename, | ||
children, | ||
future, | ||
window | ||
} = _ref2; | ||
} = _ref5; | ||
let historyRef = React.useRef(); | ||
if (historyRef.current == null) { | ||
@@ -263,9 +682,14 @@ historyRef.current = createHashHistory({ | ||
} | ||
let history = historyRef.current; | ||
let [state, setState] = React.useState({ | ||
let [state, setStateImpl] = React.useState({ | ||
action: history.action, | ||
location: history.location | ||
}); | ||
React.useLayoutEffect(() => history.listen(setState), [history]); | ||
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, { | ||
@@ -276,3 +700,4 @@ basename: basename, | ||
navigationType: state.action, | ||
navigator: history | ||
navigator: history, | ||
future: future | ||
}); | ||
@@ -286,14 +711,20 @@ } | ||
*/ | ||
function HistoryRouter(_ref3) { | ||
function HistoryRouter(_ref6) { | ||
let { | ||
basename, | ||
children, | ||
future, | ||
history | ||
} = _ref3; | ||
const [state, setState] = React.useState({ | ||
} = _ref6; | ||
let [state, setStateImpl] = React.useState({ | ||
action: history.action, | ||
location: history.location | ||
}); | ||
React.useLayoutEffect(() => history.listen(setState), [history]); | ||
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, { | ||
@@ -304,6 +735,6 @@ basename: basename, | ||
navigationType: state.action, | ||
navigator: history | ||
navigator: history, | ||
future: future | ||
}); | ||
} | ||
if (process.env.NODE_ENV !== "production") { | ||
@@ -313,37 +744,47 @@ HistoryRouter.displayName = "unstable_HistoryRouter"; | ||
const isBrowser = typeof window !== "undefined" && typeof window.document !== "undefined" && typeof window.document.createElement !== "undefined"; | ||
const ABSOLUTE_URL_REGEX$1 = /^(?:[a-z][a-z0-9+.-]*:|\/\/)/i; | ||
/** | ||
* The public API for rendering a history-aware <a>. | ||
* The public API for rendering a history-aware `<a>`. | ||
*/ | ||
const Link = /*#__PURE__*/React.forwardRef(function LinkWithRef(_ref4, ref) { | ||
const Link = /*#__PURE__*/React.forwardRef(function LinkWithRef(_ref7, ref) { | ||
let { | ||
onClick, | ||
relative, | ||
reloadDocument, | ||
replace, | ||
state, | ||
target, | ||
to, | ||
preventScrollReset | ||
} = _ref4, | ||
rest = _objectWithoutPropertiesLoose(_ref4, _excluded); | ||
onClick, | ||
relative, | ||
reloadDocument, | ||
replace, | ||
state, | ||
target, | ||
to, | ||
preventScrollReset, | ||
unstable_viewTransition | ||
} = _ref7, | ||
rest = _objectWithoutPropertiesLoose(_ref7, _excluded); | ||
let { | ||
basename | ||
} = React.useContext(UNSAFE_NavigationContext); | ||
// Rendered into <a href> for absolute URLs | ||
let absoluteHref; | ||
let isExternal = false; | ||
if (isBrowser && typeof to === "string" && /^(?:[a-z][a-z0-9+.-]*:|\/\/)/i.test(to)) { | ||
if (typeof to === "string" && ABSOLUTE_URL_REGEX$1.test(to)) { | ||
// Render the absolute href server- and client-side | ||
absoluteHref = to; | ||
let currentUrl = new URL(window.location.href); | ||
let targetUrl = to.startsWith("//") ? new URL(currentUrl.protocol + to) : new URL(to); | ||
if (targetUrl.origin === currentUrl.origin) { | ||
// Strip the protocol/origin for same-origin absolute URLs | ||
to = targetUrl.pathname + targetUrl.search + targetUrl.hash; | ||
} else { | ||
isExternal = true; | ||
// 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 | ||
process.env.NODE_ENV !== "production" ? UNSAFE_warning(false, "<Link to=\"" + to + "\"> contains an invalid URL which will probably break " + "when clicked - please update to a valid URL path.") : void 0; | ||
} | ||
} | ||
} // Rendered into <a href> for relative URLs | ||
} | ||
// Rendered into <a href> for relative URLs | ||
let href = useHref(to, { | ||
@@ -357,8 +798,7 @@ relative | ||
preventScrollReset, | ||
relative | ||
relative, | ||
unstable_viewTransition | ||
}); | ||
function handleClick(event) { | ||
if (onClick) onClick(event); | ||
if (!event.defaultPrevented) { | ||
@@ -368,3 +808,2 @@ internalOnClick(event); | ||
} | ||
return ( | ||
@@ -381,3 +820,2 @@ /*#__PURE__*/ | ||
}); | ||
if (process.env.NODE_ENV !== "production") { | ||
@@ -387,18 +825,16 @@ Link.displayName = "Link"; | ||
/** | ||
* A <Link> wrapper that knows if it's "active" or not. | ||
* A `<Link>` wrapper that knows if it's "active" or not. | ||
*/ | ||
const NavLink = /*#__PURE__*/React.forwardRef(function NavLinkWithRef(_ref5, ref) { | ||
const NavLink = /*#__PURE__*/React.forwardRef(function NavLinkWithRef(_ref8, ref) { | ||
let { | ||
"aria-current": ariaCurrentProp = "page", | ||
caseSensitive = false, | ||
className: classNameProp = "", | ||
end = false, | ||
style: styleProp, | ||
to, | ||
children | ||
} = _ref5, | ||
rest = _objectWithoutPropertiesLoose(_ref5, _excluded2); | ||
"aria-current": ariaCurrentProp = "page", | ||
caseSensitive = false, | ||
className: classNameProp = "", | ||
end = false, | ||
style: styleProp, | ||
to, | ||
unstable_viewTransition, | ||
children | ||
} = _ref8, | ||
rest = _objectWithoutPropertiesLoose(_ref8, _excluded2); | ||
let path = useResolvedPath(to, { | ||
@@ -410,8 +846,12 @@ relative: rest.relative | ||
let { | ||
navigator | ||
navigator, | ||
basename | ||
} = React.useContext(UNSAFE_NavigationContext); | ||
let isTransitioning = routerState != null && | ||
// Conditional usage is OK here because the usage of a data router is static | ||
// eslint-disable-next-line react-hooks/rules-of-hooks | ||
useViewTransitionState(path) && unstable_viewTransition === true; | ||
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) { | ||
@@ -422,13 +862,22 @@ locationPathname = locationPathname.toLowerCase(); | ||
} | ||
let isActive = locationPathname === toPathname || !end && locationPathname.startsWith(toPathname) && locationPathname.charAt(toPathname.length) === "/"; | ||
if (nextLocationPathname && basename) { | ||
nextLocationPathname = stripBasename(nextLocationPathname, basename) || nextLocationPathname; | ||
} | ||
// If the `to` has a trailing slash, look at that exact spot. Otherwise, | ||
// we're looking for a slash _after_ what's in `to`. For example: | ||
// | ||
// <NavLink to="/users"> and <NavLink to="/users/"> | ||
// both want to look for a / at index 6 to match URL `/users/matt` | ||
const endSlashPosition = toPathname !== "/" && toPathname.endsWith("/") ? toPathname.length - 1 : toPathname.length; | ||
let isActive = locationPathname === toPathname || !end && locationPathname.startsWith(toPathname) && locationPathname.charAt(endSlashPosition) === "/"; | ||
let isPending = nextLocationPathname != null && (nextLocationPathname === toPathname || !end && nextLocationPathname.startsWith(toPathname) && nextLocationPathname.charAt(toPathname.length) === "/"); | ||
let renderProps = { | ||
isActive, | ||
isPending, | ||
isTransitioning | ||
}; | ||
let ariaCurrent = isActive ? ariaCurrentProp : undefined; | ||
let className; | ||
if (typeof classNameProp === "function") { | ||
className = classNameProp({ | ||
isActive, | ||
isPending | ||
}); | ||
className = classNameProp(renderProps); | ||
} else { | ||
@@ -440,9 +889,5 @@ // If the className prop is not a function, we use a default `active` | ||
// simple styling rules working as they currently do. | ||
className = [classNameProp, isActive ? "active" : null, isPending ? "pending" : null].filter(Boolean).join(" "); | ||
className = [classNameProp, isActive ? "active" : null, isPending ? "pending" : null, isTransitioning ? "transitioning" : null].filter(Boolean).join(" "); | ||
} | ||
let style = typeof styleProp === "function" ? styleProp({ | ||
isActive, | ||
isPending | ||
}) : styleProp; | ||
let style = typeof styleProp === "function" ? styleProp(renderProps) : styleProp; | ||
return /*#__PURE__*/React.createElement(Link, _extends({}, rest, { | ||
@@ -453,9 +898,6 @@ "aria-current": ariaCurrent, | ||
style: style, | ||
to: to | ||
}), typeof children === "function" ? children({ | ||
isActive, | ||
isPending | ||
}) : children); | ||
to: to, | ||
unstable_viewTransition: unstable_viewTransition | ||
}), typeof children === "function" ? children(renderProps) : children); | ||
}); | ||
if (process.env.NODE_ENV !== "production") { | ||
@@ -470,34 +912,22 @@ NavLink.displayName = "NavLink"; | ||
*/ | ||
const Form = /*#__PURE__*/React.forwardRef((props, ref) => { | ||
return /*#__PURE__*/React.createElement(FormImpl, _extends({}, props, { | ||
ref: ref | ||
})); | ||
}); | ||
if (process.env.NODE_ENV !== "production") { | ||
Form.displayName = "Form"; | ||
} | ||
const FormImpl = /*#__PURE__*/React.forwardRef((_ref6, forwardedRef) => { | ||
const Form = /*#__PURE__*/React.forwardRef((_ref9, forwardedRef) => { | ||
let { | ||
reloadDocument, | ||
replace, | ||
method = defaultMethod, | ||
action, | ||
onSubmit, | ||
fetcherKey, | ||
routeId, | ||
relative, | ||
preventScrollReset | ||
} = _ref6, | ||
props = _objectWithoutPropertiesLoose(_ref6, _excluded3); | ||
let submit = useSubmitImpl(fetcherKey, routeId); | ||
let formMethod = method.toLowerCase() === "get" ? "get" : "post"; | ||
fetcherKey, | ||
navigate, | ||
reloadDocument, | ||
replace, | ||
state, | ||
method = defaultMethod, | ||
action, | ||
onSubmit, | ||
relative, | ||
preventScrollReset, | ||
unstable_viewTransition | ||
} = _ref9, | ||
props = _objectWithoutPropertiesLoose(_ref9, _excluded3); | ||
let submit = useSubmit(); | ||
let formAction = useFormAction(action, { | ||
relative | ||
}); | ||
let formMethod = method.toLowerCase() === "get" ? "get" : "post"; | ||
let submitHandler = event => { | ||
@@ -510,9 +940,12 @@ onSubmit && onSubmit(event); | ||
submit(submitter || event.currentTarget, { | ||
fetcherKey, | ||
method: submitMethod, | ||
navigate, | ||
replace, | ||
state, | ||
relative, | ||
preventScrollReset | ||
preventScrollReset, | ||
unstable_viewTransition | ||
}); | ||
}; | ||
return /*#__PURE__*/React.createElement("form", _extends({ | ||
@@ -525,37 +958,56 @@ ref: forwardedRef, | ||
}); | ||
if (process.env.NODE_ENV !== "production") { | ||
FormImpl.displayName = "FormImpl"; | ||
Form.displayName = "Form"; | ||
} | ||
if (process.env.NODE_ENV !== "production") ; //#endregion | ||
/** | ||
* This component will emulate the browser's scroll restoration on location | ||
* changes. | ||
*/ | ||
function ScrollRestoration(_ref10) { | ||
let { | ||
getKey, | ||
storageKey | ||
} = _ref10; | ||
useScrollRestoration({ | ||
getKey, | ||
storageKey | ||
}); | ||
return null; | ||
} | ||
if (process.env.NODE_ENV !== "production") { | ||
ScrollRestoration.displayName = "ScrollRestoration"; | ||
} | ||
//#endregion | ||
//////////////////////////////////////////////////////////////////////////////// | ||
//#region Hooks | ||
//////////////////////////////////////////////////////////////////////////////// | ||
var DataRouterHook; | ||
(function (DataRouterHook) { | ||
DataRouterHook["UseScrollRestoration"] = "useScrollRestoration"; | ||
DataRouterHook["UseSubmitImpl"] = "useSubmitImpl"; | ||
DataRouterHook["UseSubmit"] = "useSubmit"; | ||
DataRouterHook["UseSubmitFetcher"] = "useSubmitFetcher"; | ||
DataRouterHook["UseFetcher"] = "useFetcher"; | ||
DataRouterHook["useViewTransitionState"] = "useViewTransitionState"; | ||
})(DataRouterHook || (DataRouterHook = {})); | ||
var DataRouterStateHook; | ||
(function (DataRouterStateHook) { | ||
DataRouterStateHook["UseFetcher"] = "useFetcher"; | ||
DataRouterStateHook["UseFetchers"] = "useFetchers"; | ||
DataRouterStateHook["UseScrollRestoration"] = "useScrollRestoration"; | ||
})(DataRouterStateHook || (DataRouterStateHook = {})); | ||
// Internal hooks | ||
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 ? process.env.NODE_ENV !== "production" ? invariant(false, getDataRouterConsoleError(hookName)) : invariant(false) : void 0; | ||
!ctx ? process.env.NODE_ENV !== "production" ? UNSAFE_invariant(false, getDataRouterConsoleError(hookName)) : UNSAFE_invariant(false) : void 0; | ||
return ctx; | ||
} | ||
function useDataRouterState(hookName) { | ||
let state = React.useContext(UNSAFE_DataRouterStateContext); | ||
!state ? process.env.NODE_ENV !== "production" ? UNSAFE_invariant(false, getDataRouterConsoleError(hookName)) : UNSAFE_invariant(false) : void 0; | ||
return state; | ||
} | ||
// External hooks | ||
/** | ||
@@ -566,4 +1018,2 @@ * Handles the click behavior for router `<Link>` components. This is useful if | ||
*/ | ||
function useLinkClickHandler(to, _temp) { | ||
@@ -575,3 +1025,4 @@ let { | ||
preventScrollReset, | ||
relative | ||
relative, | ||
unstable_viewTransition | ||
} = _temp === void 0 ? {} : _temp; | ||
@@ -585,5 +1036,5 @@ let navigate = useNavigate(); | ||
if (shouldProcessLinkClick(event, target)) { | ||
event.preventDefault(); // If the URL hasn't changed, a regular <a> will do a replace instead of | ||
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); | ||
@@ -594,6 +1045,7 @@ navigate(to, { | ||
preventScrollReset, | ||
relative | ||
relative, | ||
unstable_viewTransition | ||
}); | ||
} | ||
}, [location, navigate, path, replaceProp, state, target, to, preventScrollReset, relative]); | ||
}, [location, navigate, path, replaceProp, state, target, to, preventScrollReset, relative, unstable_viewTransition]); | ||
} | ||
@@ -604,9 +1056,9 @@ /** | ||
*/ | ||
function useSearchParams(defaultInit) { | ||
process.env.NODE_ENV !== "production" ? 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.") : void 0; | ||
process.env.NODE_ENV !== "production" ? 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.") : void 0; | ||
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. | ||
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 | ||
@@ -623,8 +1075,21 @@ // remove a param with setSearchParams({}) if it has an initial value | ||
} | ||
function useSubmitImpl(fetcherKey, routeId) { | ||
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."); | ||
} | ||
} | ||
let fetcherId = 0; | ||
let getUniqueFetcherId = () => "__" + String(++fetcherId) + "__"; | ||
/** | ||
* 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.UseSubmitImpl); | ||
let defaultAction = useFormAction(); | ||
} = useDataRouterContext(DataRouterHook.UseSubmit); | ||
let { | ||
basename | ||
} = React.useContext(UNSAFE_NavigationContext); | ||
let currentRouteId = UNSAFE_useRouteId(); | ||
return React.useCallback(function (target, options) { | ||
@@ -634,31 +1099,38 @@ if (options === void 0) { | ||
} | ||
if (typeof document === "undefined") { | ||
throw new Error("You are calling submit during the server render. " + "Try calling submit within a `useEffect` or callback instead."); | ||
} | ||
validateClientSideSubmission(); | ||
let { | ||
action, | ||
method, | ||
encType, | ||
formData, | ||
url | ||
} = getFormSubmissionInfo(target, defaultAction, options); | ||
let href = url.pathname + url.search; | ||
let opts = { | ||
replace: options.replace, | ||
preventScrollReset: options.preventScrollReset, | ||
formData, | ||
formMethod: method, | ||
formEncType: encType | ||
}; | ||
if (fetcherKey) { | ||
!(routeId != null) ? process.env.NODE_ENV !== "production" ? invariant(false, "No routeId available for useFetcher()") : invariant(false) : void 0; | ||
router.fetch(fetcherKey, routeId, href, opts); | ||
body | ||
} = getFormSubmissionInfo(target, basename); | ||
if (options.navigate === false) { | ||
let key = options.fetcherKey || getUniqueFetcherId(); | ||
router.fetch(key, currentRouteId, options.action || action, { | ||
preventScrollReset: options.preventScrollReset, | ||
formData, | ||
body, | ||
formMethod: options.method || method, | ||
formEncType: options.encType || encType, | ||
unstable_flushSync: options.unstable_flushSync | ||
}); | ||
} else { | ||
router.navigate(href, opts); | ||
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, | ||
unstable_flushSync: options.unstable_flushSync, | ||
unstable_viewTransition: options.unstable_viewTransition | ||
}); | ||
} | ||
}, [defaultAction, router, fetcherKey, routeId]); | ||
}, [router, basename, currentRouteId]); | ||
} | ||
// v7: Eventually we should deprecate this entirely in favor of using the | ||
// router method directly? | ||
function useFormAction(action, _temp2) { | ||
@@ -672,28 +1144,22 @@ let { | ||
let routeContext = React.useContext(UNSAFE_RouteContext); | ||
!routeContext ? process.env.NODE_ENV !== "production" ? invariant(false, "useFormAction must be used inside a RouteContext") : invariant(false) : void 0; | ||
let [match] = routeContext.matches.slice(-1); // Shallow clone path so we can modify it below, otherwise we modify the | ||
!routeContext ? process.env.NODE_ENV !== "production" ? UNSAFE_invariant(false, "useFormAction must be used inside a RouteContext") : UNSAFE_invariant(false) : 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({}, useResolvedPath(action ? action : ".", { | ||
relative | ||
})); // Previously we set the default action to ".". The problem with this is that | ||
// `useResolvedPath(".")` excludes search params and the hash 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. | ||
})); | ||
// If no action was specified, browsers will persist current search params | ||
// when determining the path, so match that behavior | ||
// https://github.com/remix-run/remix/issues/927 | ||
let location = useLocation(); | ||
if (action == null) { | ||
// Safe to write to these directly here since if action was undefined, we | ||
// Safe to write to this directly here since if action was undefined, we | ||
// would have called useResolvedPath(".") which will never include a search | ||
// or hash | ||
path.search = location.search; | ||
path.hash = location.hash; // 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); | ||
// When grabbing search params from the URL, remove any included ?index param | ||
// since it might not apply to our contextual route. We add it back based | ||
// on match.route.index below | ||
let params = new URLSearchParams(path.search); | ||
if (params.has("index") && params.get("index") === "") { | ||
params.delete("index"); | ||
@@ -703,39 +1169,321 @@ 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 | ||
} | ||
// 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); | ||
} | ||
//////////////////////////////////////////////////////////////////////////////// | ||
//#region Utils | ||
//////////////////////////////////////////////////////////////////////////////// | ||
function warning(cond, message) { | ||
if (!cond) { | ||
// eslint-disable-next-line no-console | ||
if (typeof console !== "undefined") console.warn(message); | ||
// TODO: (v7) Change the useFetcher generic default from `any` to `unknown` | ||
/** | ||
* Interacts with route loaders and actions without causing a navigation. Great | ||
* for any interaction that stays on the same page. | ||
*/ | ||
function useFetcher(_temp3) { | ||
var _route$matches; | ||
let { | ||
key | ||
} = _temp3 === void 0 ? {} : _temp3; | ||
let { | ||
router | ||
} = useDataRouterContext(DataRouterHook.UseFetcher); | ||
let state = useDataRouterState(DataRouterStateHook.UseFetcher); | ||
let fetcherData = React.useContext(FetchersContext); | ||
let route = React.useContext(UNSAFE_RouteContext); | ||
let routeId = (_route$matches = route.matches[route.matches.length - 1]) == null ? void 0 : _route$matches.route.id; | ||
!fetcherData ? process.env.NODE_ENV !== "production" ? UNSAFE_invariant(false, "useFetcher must be used inside a FetchersContext") : UNSAFE_invariant(false) : void 0; | ||
!route ? process.env.NODE_ENV !== "production" ? UNSAFE_invariant(false, "useFetcher must be used inside a RouteContext") : UNSAFE_invariant(false) : void 0; | ||
!(routeId != null) ? process.env.NODE_ENV !== "production" ? UNSAFE_invariant(false, "useFetcher can only be used on routes that contain a unique \"id\"") : UNSAFE_invariant(false) : void 0; | ||
// Fetcher key handling | ||
// OK to call conditionally to feature detect `useId` | ||
// eslint-disable-next-line react-hooks/rules-of-hooks | ||
let defaultKey = useIdImpl ? useIdImpl() : ""; | ||
let [fetcherKey, setFetcherKey] = React.useState(key || defaultKey); | ||
if (key && key !== fetcherKey) { | ||
setFetcherKey(key); | ||
} else if (!fetcherKey) { | ||
// We will only fall through here when `useId` is not available | ||
setFetcherKey(getUniqueFetcherId()); | ||
} | ||
// Registration/cleanup | ||
React.useEffect(() => { | ||
router.getFetcher(fetcherKey); | ||
return () => { | ||
// Tell the router we've unmounted - if v7_fetcherPersist is enabled this | ||
// will not delete immediately but instead queue up a delete after the | ||
// fetcher returns to an `idle` state | ||
router.deleteFetcher(fetcherKey); | ||
}; | ||
}, [router, fetcherKey]); | ||
// Fetcher additions | ||
let load = React.useCallback((href, opts) => { | ||
!routeId ? process.env.NODE_ENV !== "production" ? UNSAFE_invariant(false, "No routeId available for fetcher.load()") : UNSAFE_invariant(false) : void 0; | ||
router.fetch(fetcherKey, routeId, href, opts); | ||
}, [fetcherKey, routeId, router]); | ||
let submitImpl = useSubmit(); | ||
let submit = React.useCallback((target, opts) => { | ||
submitImpl(target, _extends({}, opts, { | ||
navigate: false, | ||
fetcherKey | ||
})); | ||
}, [fetcherKey, submitImpl]); | ||
let FetcherForm = React.useMemo(() => { | ||
let FetcherForm = /*#__PURE__*/React.forwardRef((props, ref) => { | ||
return /*#__PURE__*/React.createElement(Form, _extends({}, props, { | ||
navigate: false, | ||
fetcherKey: fetcherKey, | ||
ref: ref | ||
})); | ||
}); | ||
if (process.env.NODE_ENV !== "production") { | ||
FetcherForm.displayName = "fetcher.Form"; | ||
} | ||
return FetcherForm; | ||
}, [fetcherKey]); | ||
// Exposed FetcherWithComponents | ||
let fetcher = state.fetchers.get(fetcherKey) || IDLE_FETCHER; | ||
let data = fetcherData.get(fetcherKey); | ||
let fetcherWithComponents = React.useMemo(() => _extends({ | ||
Form: FetcherForm, | ||
submit, | ||
load | ||
}, fetcher, { | ||
data | ||
}), [FetcherForm, submit, load, fetcher, data]); | ||
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 Array.from(state.fetchers.entries()).map(_ref11 => { | ||
let [key, fetcher] = _ref11; | ||
return _extends({}, fetcher, { | ||
key | ||
}); | ||
}); | ||
} | ||
const SCROLL_RESTORATION_STORAGE_KEY = "react-router-scroll-positions"; | ||
let savedScrollPositions = {}; | ||
/** | ||
* When rendered inside a RouterProvider, will restore scroll positions on navigations | ||
*/ | ||
function useScrollRestoration(_temp4) { | ||
let { | ||
getKey, | ||
storageKey | ||
} = _temp4 === void 0 ? {} : _temp4; | ||
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; | ||
} | ||
try { | ||
// Welcome to debugging React Router! | ||
// | ||
// This error is thrown as a convenience so you can more easily | ||
// find the source for a warning that appears in the console by | ||
// enabling "pause on exceptions" in your JavaScript debugger. | ||
throw new Error(message); // eslint-disable-next-line no-empty | ||
} catch (e) {} | ||
sessionStorage.setItem(storageKey || SCROLL_RESTORATION_STORAGE_KEY, JSON.stringify(savedScrollPositions)); | ||
} catch (error) { | ||
process.env.NODE_ENV !== "production" ? UNSAFE_warning(false, "Failed to save scroll positions in sessionStorage, <ScrollRestoration /> will not work properly (" + error + ").") : void 0; | ||
} | ||
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() | ||
_extends({}, location, { | ||
pathname: stripBasename(location.pathname, basename) || location.pathname | ||
}), matches) : getKey; | ||
let disableScrollRestoration = router == null ? void 0 : 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]); | ||
} | ||
} //#endregion | ||
} | ||
/** | ||
* 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(_ref12) { | ||
let { | ||
when, | ||
message | ||
} = _ref12; | ||
let blocker = 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]); | ||
} | ||
/** | ||
* Return a boolean indicating if there is an active view transition to the | ||
* given href. You can use this value to render CSS classes or viewTransitionName | ||
* styles onto your elements | ||
* | ||
* @param href The destination href | ||
* @param [opts.relative] Relative routing type ("route" | "path") | ||
*/ | ||
function useViewTransitionState(to, opts) { | ||
if (opts === void 0) { | ||
opts = {}; | ||
} | ||
let vtContext = React.useContext(ViewTransitionContext); | ||
!(vtContext != null) ? process.env.NODE_ENV !== "production" ? UNSAFE_invariant(false, "`unstable_useViewTransitionState` must be used within `react-router-dom`'s `RouterProvider`. " + "Did you accidentally import `RouterProvider` from `react-router`?") : UNSAFE_invariant(false) : void 0; | ||
let { | ||
basename | ||
} = useDataRouterContext(DataRouterHook.useViewTransitionState); | ||
let path = useResolvedPath(to, { | ||
relative: opts.relative | ||
}); | ||
if (!vtContext.isTransitioning) { | ||
return false; | ||
} | ||
let currentPath = stripBasename(vtContext.currentLocation.pathname, basename) || vtContext.currentLocation.pathname; | ||
let nextPath = stripBasename(vtContext.nextLocation.pathname, basename) || vtContext.nextLocation.pathname; | ||
// Transition is active if we're going to or coming from the indicated | ||
// destination. This ensures that other PUSH navigations that reverse | ||
// an indicated transition apply. I.e., on the list view you have: | ||
// | ||
// <NavLink to="/details/1" unstable_viewTransition> | ||
// | ||
// If you click the breadcrumb back to the list view: | ||
// | ||
// <NavLink to="/list" unstable_viewTransition> | ||
// | ||
// We should apply the transition because it's indicated as active going | ||
// from /list -> /details/1 and therefore should be active on the reverse | ||
// (even though this isn't strictly a POP reverse) | ||
return matchPath(path.pathname, nextPath) != null || matchPath(path.pathname, currentPath) != null; | ||
} | ||
//#endregion | ||
// v5 isn't in TypeScript, they'll also lose the @types/react-router with this | ||
// but not worried about that for now. | ||
function CompatRoute(props) { | ||
@@ -753,4 +1501,4 @@ let { | ||
})); | ||
} // Copied with 💜 from https://github.com/bvaughn/react-resizable-panels/blob/main/packages/react-resizable-panels/src/hooks/useIsomorphicEffect.ts | ||
} | ||
// Copied with 💜 from https://github.com/bvaughn/react-resizable-panels/blob/main/packages/react-resizable-panels/src/hooks/useIsomorphicEffect.ts | ||
const canUseEffectHooks = !!(typeof window !== "undefined" && typeof window.document !== "undefined" && typeof window.document.createElement !== "undefined"); | ||
@@ -782,7 +1530,7 @@ const useIsomorphicLayoutEffect = canUseEffectHooks ? React.useLayoutEffect : () => {}; | ||
} | ||
const ABSOLUTE_URL_REGEX = /^(?:[a-z][a-z0-9+.-]*:|\/\/)/i; | ||
/** | ||
* A <Router> that may not navigate to any other location. This is useful | ||
* A `<Router>` that may not navigate to any other location. This is useful | ||
* on the server where there is no stateful UI. | ||
*/ | ||
function StaticRouter(_ref2) { | ||
@@ -794,7 +1542,5 @@ let { | ||
} = _ref2; | ||
if (typeof locationProp === "string") { | ||
locationProp = parsePath(locationProp); | ||
} | ||
let action = Action.Pop; | ||
@@ -805,3 +1551,3 @@ let location = { | ||
hash: locationProp.hash || "", | ||
state: locationProp.state || null, | ||
state: locationProp.state != null ? locationProp.state : null, | ||
key: locationProp.key || "default" | ||
@@ -813,32 +1559,30 @@ }; | ||
}, | ||
encodeLocation(to) { | ||
let path = typeof to === "string" ? parsePath(to) : to; | ||
let href = typeof to === "string" ? to : createPath$1(to); | ||
// Treating this as a full URL will strip any trailing spaces so we need to | ||
// pre-encode them since they might be part of a matching splat param from | ||
// an ancestor route | ||
href = href.replace(/ $/, "%20"); | ||
let encoded = ABSOLUTE_URL_REGEX.test(href) ? new URL(href) : new URL(href, "http://localhost"); | ||
return { | ||
pathname: path.pathname || "", | ||
search: path.search || "", | ||
hash: path.hash || "" | ||
pathname: encoded.pathname, | ||
search: encoded.search, | ||
hash: encoded.hash | ||
}; | ||
}, | ||
push(to) { | ||
throw new Error("You cannot use navigator.push() on the server because it is a stateless " + "environment. This error was probably triggered when you did a " + ("`navigate(" + JSON.stringify(to) + ")` somewhere in your app.")); | ||
}, | ||
replace(to) { | ||
throw new Error("You cannot use navigator.replace() on the server because it is a stateless " + "environment. This error was probably triggered when you did a " + ("`navigate(" + JSON.stringify(to) + ", { replace: true })` somewhere ") + "in your app."); | ||
}, | ||
go(delta) { | ||
throw new Error("You cannot use navigator.go() on the server because it is a stateless " + "environment. This error was probably triggered when you did a " + ("`navigate(" + delta + ")` somewhere in your app.")); | ||
}, | ||
back() { | ||
throw new Error("You cannot use navigator.back() on the server because it is a stateless " + "environment."); | ||
}, | ||
forward() { | ||
throw new Error("You cannot use navigator.forward() on the server because it is a stateless " + "environment."); | ||
} | ||
}; | ||
@@ -855,3 +1599,3 @@ return /*#__PURE__*/React.createElement(Router, { | ||
export { BrowserRouter, CompatRoute, CompatRouter, HashRouter, Link, NavLink, StaticRouter, createSearchParams, HistoryRouter as unstable_HistoryRouter, useLinkClickHandler, useSearchParams }; | ||
export { BrowserRouter, CompatRoute, CompatRouter, Form, HashRouter, Link, NavLink, RouterProvider, ScrollRestoration, StaticRouter, useScrollRestoration as UNSAFE_useScrollRestoration, createBrowserRouter, createHashRouter, createSearchParams, HistoryRouter as unstable_HistoryRouter, usePrompt as unstable_usePrompt, useBeforeUnload, useFetcher, useFetchers, useFormAction, useLinkClickHandler, useSearchParams, useSubmit }; | ||
//# sourceMappingURL=index.js.map |
import * as React from "react"; | ||
import type { Location } from "history"; | ||
export declare function CompatRoute(props: any): JSX.Element; | ||
export declare function CompatRoute(props: any): React.JSX.Element; | ||
export declare function CompatRouter({ children }: { | ||
children: React.ReactNode; | ||
}): JSX.Element; | ||
}): React.JSX.Element; | ||
export interface StaticRouterProps { | ||
@@ -13,5 +13,5 @@ basename?: string; | ||
/** | ||
* A <Router> that may not navigate to any other location. This is useful | ||
* A `<Router>` that may not navigate to any other location. This is useful | ||
* on the server where there is no stateful UI. | ||
*/ | ||
export declare function StaticRouter({ basename, children, location: locationProp, }: StaticRouterProps): JSX.Element; | ||
export declare function StaticRouter({ basename, children, location: locationProp, }: StaticRouterProps): React.JSX.Element; |
/** | ||
* React Router DOM v5 Compat v0.0.0-experimental-cf9637ce | ||
* React Router DOM v5 Compat v0.0.0-experimental-cffa549a1 | ||
* | ||
@@ -4,0 +4,0 @@ * Copyright (c) Remix Software Inc. |
@@ -1,4 +0,3 @@ | ||
import type { FormEncType, FormMethod } from "@remix-run/router"; | ||
import type { RelativeRoutingType } from "react-router"; | ||
export declare const defaultMethod = "get"; | ||
import type { FormEncType, HTMLFormMethod, RelativeRoutingType } from "@remix-run/router"; | ||
export declare const defaultMethod: HTMLFormMethod; | ||
export declare function isHtmlElement(object: any): object is HTMLElement; | ||
@@ -8,6 +7,6 @@ export declare function isButtonElement(object: any): object is HTMLButtonElement; | ||
export declare function isInputElement(object: any): object is HTMLInputElement; | ||
declare type LimitedMouseEvent = Pick<MouseEvent, "button" | "metaKey" | "altKey" | "ctrlKey" | "shiftKey">; | ||
type LimitedMouseEvent = Pick<MouseEvent, "button" | "metaKey" | "altKey" | "ctrlKey" | "shiftKey">; | ||
export declare function shouldProcessLinkClick(event: LimitedMouseEvent, target?: string): boolean; | ||
export declare type ParamKeyValuePair = [string, string]; | ||
export declare type URLSearchParamsInit = string | ParamKeyValuePair[] | Record<string, string | string[]> | URLSearchParams; | ||
export type ParamKeyValuePair = [string, string]; | ||
export type URLSearchParamsInit = string | ParamKeyValuePair[] | Record<string, string | string[]> | URLSearchParams; | ||
/** | ||
@@ -36,3 +35,15 @@ * Creates a URLSearchParams object using the given initializer. | ||
export declare function getSearchParamsForLocation(locationSearch: string, defaultSearchParams: URLSearchParams | null): URLSearchParams; | ||
export interface SubmitOptions { | ||
type JsonObject = { | ||
[Key in string]: JsonValue; | ||
} & { | ||
[Key in string]?: JsonValue | undefined; | ||
}; | ||
type JsonArray = JsonValue[] | readonly JsonValue[]; | ||
type JsonPrimitive = string | number | boolean | null; | ||
type JsonValue = JsonPrimitive | JsonObject | JsonArray; | ||
export type SubmitTarget = HTMLFormElement | HTMLButtonElement | HTMLInputElement | FormData | URLSearchParams | JsonValue | null; | ||
/** | ||
* Submit options shared by both navigations and fetchers | ||
*/ | ||
interface SharedSubmitOptions { | ||
/** | ||
@@ -42,13 +53,10 @@ * The HTTP method used to submit the form. Overrides `<form method>`. | ||
*/ | ||
method?: FormMethod; | ||
method?: HTMLFormMethod; | ||
/** | ||
* The action URL path used to submit the form. Overrides `<form action>`. | ||
* Defaults to the path of the current route. | ||
* | ||
* Note: It is assumed the path is already resolved. If you need to resolve a | ||
* relative path, use `useFormAction`. | ||
*/ | ||
action?: string; | ||
/** | ||
* The action URL used to submit the form. Overrides `<form encType>`. | ||
* The encoding used to submit the form. Overrides `<form encType>`. | ||
* Defaults to "application/x-www-form-urlencoded". | ||
@@ -58,8 +66,2 @@ */ | ||
/** | ||
* Set `true` to replace the current entry in the browser's history stack | ||
* instead of creating a new one (i.e. stay on "the same page"). Defaults | ||
* to `false`. | ||
*/ | ||
replace?: boolean; | ||
/** | ||
* Determines whether the form action is relative to the route hierarchy or | ||
@@ -75,11 +77,46 @@ * the pathname. Use this if you want to opt out of navigating the route | ||
preventScrollReset?: boolean; | ||
/** | ||
* Enable flushSync for this submission's state updates | ||
*/ | ||
unstable_flushSync?: boolean; | ||
} | ||
export declare function getFormSubmissionInfo(target: HTMLFormElement | HTMLButtonElement | HTMLInputElement | FormData | URLSearchParams | { | ||
[name: string]: string; | ||
} | null, defaultAction: string, options: SubmitOptions): { | ||
url: URL; | ||
/** | ||
* Submit options available to fetchers | ||
*/ | ||
export interface FetcherSubmitOptions extends SharedSubmitOptions { | ||
} | ||
/** | ||
* Submit options available to navigations | ||
*/ | ||
export interface SubmitOptions extends FetcherSubmitOptions { | ||
/** | ||
* Set `true` to replace the current entry in the browser's history stack | ||
* instead of creating a new one (i.e. stay on "the same page"). Defaults | ||
* to `false`. | ||
*/ | ||
replace?: boolean; | ||
/** | ||
* State object to add to the history stack entry for this navigation | ||
*/ | ||
state?: any; | ||
/** | ||
* Indicate a specific fetcherKey to use when using navigate=false | ||
*/ | ||
fetcherKey?: string; | ||
/** | ||
* navigate=false will use a fetcher instead of a navigation | ||
*/ | ||
navigate?: boolean; | ||
/** | ||
* Enable view transitions on this submission navigation | ||
*/ | ||
unstable_viewTransition?: boolean; | ||
} | ||
export declare function getFormSubmissionInfo(target: SubmitTarget, basename: string): { | ||
action: string | null; | ||
method: string; | ||
encType: string; | ||
formData: FormData; | ||
formData: FormData | undefined; | ||
body: any; | ||
}; | ||
export {}; |
@@ -6,28 +6,57 @@ /** | ||
import * as React from "react"; | ||
import type { NavigateOptions, RelativeRoutingType, RouteObject, To } from "react-router"; | ||
import type { Fetcher, FormEncType, FormMethod, GetScrollRestorationKeyFunction, History, HydrationState, Router as RemixRouter } from "@remix-run/router"; | ||
import type { SubmitOptions, ParamKeyValuePair, URLSearchParamsInit } from "./dom"; | ||
import type { FutureConfig, Location, NavigateOptions, RelativeRoutingType, RouteObject, RouterProviderProps, To, unstable_PatchRoutesOnMissFunction } from "react-router"; | ||
import type { unstable_DataStrategyFunction, unstable_DataStrategyFunctionArgs, unstable_DataStrategyMatch, Fetcher, FormEncType, FormMethod, FutureConfig as RouterFutureConfig, GetScrollRestorationKeyFunction, History, HTMLFormMethod, HydrationState, Router as RemixRouter, V7_FormMethod, BlockerFunction } from "@remix-run/router"; | ||
import { UNSAFE_ErrorResponseImpl as ErrorResponseImpl } from "@remix-run/router"; | ||
import type { SubmitOptions, ParamKeyValuePair, URLSearchParamsInit, SubmitTarget, FetcherSubmitOptions } from "./dom"; | ||
import { createSearchParams } from "./dom"; | ||
export type { FormEncType, FormMethod, GetScrollRestorationKeyFunction, ParamKeyValuePair, SubmitOptions, URLSearchParamsInit, }; | ||
export { createSearchParams }; | ||
export type { ActionFunction, ActionFunctionArgs, AwaitProps, unstable_Blocker, unstable_BlockerFunction, DataRouteMatch, DataRouteObject, Fetcher, Hash, IndexRouteObject, IndexRouteProps, JsonFunction, 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, 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"; | ||
export type { unstable_DataStrategyFunction, unstable_DataStrategyFunctionArgs, unstable_DataStrategyMatch, FormEncType, FormMethod, GetScrollRestorationKeyFunction, ParamKeyValuePair, SubmitOptions, URLSearchParamsInit, V7_FormMethod, }; | ||
export { createSearchParams, ErrorResponseImpl as UNSAFE_ErrorResponseImpl }; | ||
export type { ActionFunction, ActionFunctionArgs, AwaitProps, Blocker, BlockerFunction, DataRouteMatch, DataRouteObject, ErrorResponse, Fetcher, FutureConfig, Hash, IndexRouteObject, IndexRouteProps, JsonFunction, LazyRouteFunction, LayoutRouteProps, LoaderFunction, LoaderFunctionArgs, Location, MemoryRouterProps, NavigateFunction, NavigateOptions, NavigateProps, Navigation, Navigator, NonIndexRouteObject, OutletProps, Params, ParamParseKey, Path, PathMatch, Pathname, PathParam, PathPattern, PathRouteProps, RedirectFunction, RelativeRoutingType, RouteMatch, RouteObject, RouteProps, RouterProps, RouterProviderProps, RoutesProps, Search, ShouldRevalidateFunction, ShouldRevalidateFunctionArgs, To, UIMatch, unstable_HandlerResult, unstable_PatchRoutesOnMissFunction, } from "react-router"; | ||
export { AbortedDeferredError, Await, MemoryRouter, Navigate, NavigationType, Outlet, Route, Router, Routes, createMemoryRouter, createPath, createRoutesFromChildren, createRoutesFromElements, defer, isRouteErrorResponse, generatePath, json, matchPath, matchRoutes, parsePath, redirect, redirectDocument, renderMatches, resolvePath, useActionData, useAsyncError, useAsyncValue, 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_enhanceManualRouteObjects, } from "react-router"; | ||
export { UNSAFE_DataRouterContext, UNSAFE_DataRouterStateContext, UNSAFE_NavigationContext, UNSAFE_LocationContext, UNSAFE_RouteContext, UNSAFE_useRouteId, } from "react-router"; | ||
declare global { | ||
var __staticRouterHydrationData: HydrationState | undefined; | ||
var __reactRouterVersion: string; | ||
interface Document { | ||
startViewTransition(cb: () => Promise<void> | void): ViewTransition; | ||
} | ||
} | ||
export declare function createBrowserRouter(routes: RouteObject[], opts?: { | ||
interface DOMRouterOpts { | ||
basename?: string; | ||
future?: Partial<Omit<RouterFutureConfig, "v7_prependBasename">>; | ||
hydrationData?: HydrationState; | ||
unstable_dataStrategy?: unstable_DataStrategyFunction; | ||
unstable_patchRoutesOnMiss?: unstable_PatchRoutesOnMissFunction; | ||
window?: Window; | ||
}): RemixRouter; | ||
export declare function createHashRouter(routes: RouteObject[], opts?: { | ||
basename?: string; | ||
hydrationData?: HydrationState; | ||
window?: Window; | ||
}): RemixRouter; | ||
} | ||
export declare function createBrowserRouter(routes: RouteObject[], opts?: DOMRouterOpts): RemixRouter; | ||
export declare function createHashRouter(routes: RouteObject[], opts?: DOMRouterOpts): RemixRouter; | ||
type ViewTransitionContextObject = { | ||
isTransitioning: false; | ||
} | { | ||
isTransitioning: true; | ||
flushSync: boolean; | ||
currentLocation: Location; | ||
nextLocation: Location; | ||
}; | ||
declare const ViewTransitionContext: React.Context<ViewTransitionContextObject>; | ||
export { ViewTransitionContext as UNSAFE_ViewTransitionContext }; | ||
type FetchersContextObject = Map<string, any>; | ||
declare const FetchersContext: React.Context<FetchersContextObject>; | ||
export { FetchersContext as UNSAFE_FetchersContext }; | ||
interface ViewTransition { | ||
finished: Promise<void>; | ||
ready: Promise<void>; | ||
updateCallbackDone: Promise<void>; | ||
skipTransition(): void; | ||
} | ||
/** | ||
* Given a Remix Router instance, render the appropriate UI | ||
*/ | ||
export declare function RouterProvider({ fallbackElement, router, future, }: RouterProviderProps): React.ReactElement; | ||
export interface BrowserRouterProps { | ||
basename?: string; | ||
children?: React.ReactNode; | ||
future?: Partial<FutureConfig>; | ||
window?: Window; | ||
@@ -38,6 +67,7 @@ } | ||
*/ | ||
export declare function BrowserRouter({ basename, children, window, }: BrowserRouterProps): JSX.Element; | ||
export declare function BrowserRouter({ basename, children, future, window, }: BrowserRouterProps): React.JSX.Element; | ||
export interface HashRouterProps { | ||
basename?: string; | ||
children?: React.ReactNode; | ||
future?: Partial<FutureConfig>; | ||
window?: Window; | ||
@@ -49,6 +79,7 @@ } | ||
*/ | ||
export declare function HashRouter({ basename, children, window }: HashRouterProps): JSX.Element; | ||
export declare function HashRouter({ basename, children, future, window, }: HashRouterProps): React.JSX.Element; | ||
export interface HistoryRouterProps { | ||
basename?: string; | ||
children?: React.ReactNode; | ||
future?: FutureConfig; | ||
history: History; | ||
@@ -62,3 +93,3 @@ } | ||
*/ | ||
declare function HistoryRouter({ basename, children, history }: HistoryRouterProps): JSX.Element; | ||
declare function HistoryRouter({ basename, children, future, history, }: HistoryRouterProps): React.JSX.Element; | ||
declare namespace HistoryRouter { | ||
@@ -75,28 +106,28 @@ var displayName: string; | ||
to: To; | ||
unstable_viewTransition?: boolean; | ||
} | ||
/** | ||
* The public API for rendering a history-aware <a>. | ||
* The public API for rendering a history-aware `<a>`. | ||
*/ | ||
export declare const Link: React.ForwardRefExoticComponent<LinkProps & React.RefAttributes<HTMLAnchorElement>>; | ||
export type NavLinkRenderProps = { | ||
isActive: boolean; | ||
isPending: boolean; | ||
isTransitioning: boolean; | ||
}; | ||
export interface NavLinkProps extends Omit<LinkProps, "className" | "style" | "children"> { | ||
children?: React.ReactNode | ((props: { | ||
isActive: boolean; | ||
isPending: boolean; | ||
}) => React.ReactNode); | ||
children?: React.ReactNode | ((props: NavLinkRenderProps) => React.ReactNode); | ||
caseSensitive?: boolean; | ||
className?: string | ((props: { | ||
isActive: boolean; | ||
isPending: boolean; | ||
}) => string | undefined); | ||
className?: string | ((props: NavLinkRenderProps) => string | undefined); | ||
end?: boolean; | ||
style?: React.CSSProperties | ((props: { | ||
isActive: boolean; | ||
isPending: boolean; | ||
}) => React.CSSProperties | undefined); | ||
style?: React.CSSProperties | ((props: NavLinkRenderProps) => React.CSSProperties | undefined); | ||
} | ||
/** | ||
* A <Link> wrapper that knows if it's "active" or not. | ||
* A `<Link>` wrapper that knows if it's "active" or not. | ||
*/ | ||
export declare const NavLink: React.ForwardRefExoticComponent<NavLinkProps & React.RefAttributes<HTMLAnchorElement>>; | ||
export interface FormProps extends React.FormHTMLAttributes<HTMLFormElement> { | ||
/** | ||
* Form props shared by navigations and fetchers | ||
*/ | ||
interface SharedFormProps extends React.FormHTMLAttributes<HTMLFormElement> { | ||
/** | ||
@@ -106,4 +137,9 @@ * The HTTP verb to use when the form is submit. Supports "get", "post", | ||
*/ | ||
method?: FormMethod; | ||
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. | ||
@@ -113,12 +149,2 @@ */ | ||
/** | ||
* 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; | ||
/** | ||
* Determines whether the form action is relative to the route hierarchy or | ||
@@ -141,2 +167,38 @@ * the pathname. Use this if you want to opt out of navigating the route | ||
/** | ||
* Form props available to fetchers | ||
*/ | ||
export interface FetcherFormProps extends SharedFormProps { | ||
} | ||
/** | ||
* Form props available to navigations | ||
*/ | ||
export interface FormProps extends SharedFormProps { | ||
/** | ||
* Indicate a specific fetcherKey to use when using navigate=false | ||
*/ | ||
fetcherKey?: string; | ||
/** | ||
* navigate=false will use a fetcher instead of a navigation | ||
*/ | ||
navigate?: boolean; | ||
/** | ||
* 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; | ||
/** | ||
* Enable view transitions on this Form navigation | ||
*/ | ||
unstable_viewTransition?: boolean; | ||
} | ||
/** | ||
* A `@remix-run/router`-aware `<form>`. It behaves like a normal form except | ||
@@ -165,3 +227,3 @@ * that the interaction with the server is with `fetch` instead of new document | ||
*/ | ||
export declare function useLinkClickHandler<E extends Element = HTMLAnchorElement>(to: To, { target, replace: replaceProp, state, preventScrollReset, relative, }?: { | ||
export declare function useLinkClickHandler<E extends Element = HTMLAnchorElement>(to: To, { target, replace: replaceProp, state, preventScrollReset, relative, unstable_viewTransition, }?: { | ||
target?: React.HTMLAttributeAnchorTarget; | ||
@@ -172,2 +234,3 @@ replace?: boolean; | ||
relative?: RelativeRoutingType; | ||
unstable_viewTransition?: boolean; | ||
}): (event: React.MouseEvent<E, MouseEvent>) => void; | ||
@@ -179,6 +242,3 @@ /** | ||
export declare function useSearchParams(defaultInit?: URLSearchParamsInit): [URLSearchParams, SetURLSearchParams]; | ||
declare type SetURLSearchParams = (nextInit?: URLSearchParamsInit | ((prev: URLSearchParams) => URLSearchParamsInit), navigateOpts?: NavigateOptions) => void; | ||
declare type SubmitTarget = HTMLFormElement | HTMLButtonElement | HTMLInputElement | FormData | URLSearchParams | { | ||
[name: string]: string; | ||
} | null; | ||
export type SetURLSearchParams = (nextInit?: URLSearchParamsInit | ((prev: URLSearchParams) => URLSearchParamsInit), navigateOpts?: NavigateOptions) => void; | ||
/** | ||
@@ -205,2 +265,8 @@ * Submits a HTML `<form>` to the server without reloading the page. | ||
/** | ||
* Submits a fetcher `<form>` to the server without reloading the page. | ||
*/ | ||
export interface FetcherSubmitFunction { | ||
(target: SubmitTarget, options?: FetcherSubmitOptions): void; | ||
} | ||
/** | ||
* Returns a function that may be used to programmatically submit a form (or | ||
@@ -213,7 +279,8 @@ * some arbitrary data) to the server. | ||
}): string; | ||
declare function createFetcherForm(fetcherKey: string, routeId: string): React.ForwardRefExoticComponent<FormProps & React.RefAttributes<HTMLFormElement>>; | ||
export declare type FetcherWithComponents<TData> = Fetcher<TData> & { | ||
Form: ReturnType<typeof createFetcherForm>; | ||
submit: (target: SubmitTarget, options?: Omit<SubmitOptions, "replace" | "preventScrollReset">) => void; | ||
load: (href: string) => void; | ||
export type FetcherWithComponents<TData> = Fetcher<TData> & { | ||
Form: React.ForwardRefExoticComponent<FetcherFormProps & React.RefAttributes<HTMLFormElement>>; | ||
submit: FetcherSubmitFunction; | ||
load: (href: string, opts?: { | ||
unstable_flushSync?: boolean; | ||
}) => void; | ||
}; | ||
@@ -224,3 +291,5 @@ /** | ||
*/ | ||
export declare function useFetcher<TData = any>(): FetcherWithComponents<TData>; | ||
export declare function useFetcher<TData = any>({ key, }?: { | ||
key?: string; | ||
}): FetcherWithComponents<TData>; | ||
/** | ||
@@ -230,3 +299,5 @@ * Provides all fetchers currently on the page. Useful for layouts and parent | ||
*/ | ||
export declare function useFetchers(): Fetcher[]; | ||
export declare function useFetchers(): (Fetcher & { | ||
key: string; | ||
})[]; | ||
/** | ||
@@ -239,2 +310,3 @@ * When rendered inside a RouterProvider, will restore scroll positions on navigations | ||
}): void; | ||
export { useScrollRestoration as UNSAFE_useScrollRestoration }; | ||
/** | ||
@@ -259,7 +331,18 @@ * Setup a callback to be fired on the window's `beforeunload` event. This is | ||
*/ | ||
declare function usePrompt({ when, message }: { | ||
when: boolean; | ||
declare function usePrompt({ when, message, }: { | ||
when: boolean | BlockerFunction; | ||
message: string; | ||
}): void; | ||
export { usePrompt as unstable_usePrompt }; | ||
export { useScrollRestoration as UNSAFE_useScrollRestoration }; | ||
/** | ||
* Return a boolean indicating if there is an active view transition to the | ||
* given href. You can use this value to render CSS classes or viewTransitionName | ||
* styles onto your elements | ||
* | ||
* @param href The destination href | ||
* @param [opts.relative] Relative routing type ("route" | "path") | ||
*/ | ||
declare function useViewTransitionState(to: To, opts?: { | ||
relative?: RelativeRoutingType; | ||
}): boolean; | ||
export { useViewTransitionState as unstable_useViewTransitionState }; |
/** | ||
* React Router DOM v5 Compat v0.0.0-experimental-cf9637ce | ||
* React Router DOM v5 Compat v0.0.0-experimental-cffa549a1 | ||
* | ||
@@ -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"),require("history"),require("react-router-dom")):"function"==typeof define&&define.amd?define(["exports","react","react-router","@remix-run/router","history","react-router-dom"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).ReactRouterDOMv5Compat={},e.React,e.ReactRouter,e.RemixRouter,e.HistoryLibrary,e.ReactRouterDOM)}(this,(function(e,t,r,n,o,a){"use strict";function i(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 u=i(t);function c(){return c=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},c.apply(this,arguments)}function s(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}function l(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]])}),[]))}const f=["onClick","relative","reloadDocument","replace","state","target","to","preventScrollReset"],d=["aria-current","caseSensitive","className","end","style","to","children"];const h="undefined"!=typeof window&&void 0!==window.document&&void 0!==window.document.createElement,p=u.forwardRef((function(e,t){let n,{onClick:o,relative:a,reloadDocument:i,replace:l,state:d,target:p,to:m,preventScrollReset:g}=e,b=s(e,f),v=!1;if(h&&"string"==typeof m&&/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i.test(m)){n=m;let e=new URL(window.location.href),t=m.startsWith("//")?new URL(e.protocol+m):new URL(m);t.origin===e.origin?m=t.pathname+t.search+t.hash:v=!0}let R=r.useHref(m,{relative:a}),P=y(m,{replace:l,state:d,target:p,preventScrollReset:g,relative:a});return u.createElement("a",c({},b,{href:n||R,onClick:v||i?o:function(e){o&&o(e),e.defaultPrevented||P(e)},ref:t,target:p}))})),m=u.forwardRef((function(e,t){let{"aria-current":n="page",caseSensitive:o=!1,className:a="",end:i=!1,style:l,to:f,children:h}=e,m=s(e,d),g=r.useResolvedPath(f,{relative:m.relative}),b=r.useLocation(),y=u.useContext(r.UNSAFE_DataRouterStateContext),{navigator:v}=u.useContext(r.UNSAFE_NavigationContext),R=v.encodeLocation?v.encodeLocation(g).pathname:g.pathname,P=b.pathname,w=y&&y.navigation&&y.navigation.location?y.navigation.location.pathname:null;o||(P=P.toLowerCase(),w=w?w.toLowerCase():null,R=R.toLowerCase());let O,j=P===R||!i&&P.startsWith(R)&&"/"===P.charAt(R.length),E=null!=w&&(w===R||!i&&w.startsWith(R)&&"/"===w.charAt(R.length)),S=j?n:void 0;O="function"==typeof a?a({isActive:j,isPending:E}):[a,j?"active":null,E?"pending":null].filter(Boolean).join(" ");let C="function"==typeof l?l({isActive:j,isPending:E}):l;return u.createElement(p,c({},m,{"aria-current":S,className:O,ref:t,style:C,to:f}),"function"==typeof h?h({isActive:j,isPending:E}):h)}));var g,b;function y(e,t){let{target:n,replace:o,state:a,preventScrollReset:i,relative:c}=void 0===t?{}:t,s=r.useNavigate(),l=r.useLocation(),f=r.useResolvedPath(e,{relative:c});return u.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:a,preventScrollReset:i,relative:c})}}),[l,s,f,o,a,n,e,i,c])}!function(e){e.UseScrollRestoration="useScrollRestoration",e.UseSubmitImpl="useSubmitImpl",e.UseFetcher="useFetcher"}(g||(g={})),function(e){e.UseFetchers="useFetchers",e.UseScrollRestoration="useScrollRestoration"}(b||(b={}));const v=!("undefined"==typeof window||void 0===window.document||void 0===window.document.createElement)?u.useLayoutEffect:()=>{};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,"Routes",{enumerable:!0,get:function(){return r.Routes}}),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,"createPath",{enumerable:!0,get:function(){return r.createPath}}),Object.defineProperty(e,"createRoutesFromChildren",{enumerable:!0,get:function(){return r.createRoutesFromChildren}}),Object.defineProperty(e,"generatePath",{enumerable:!0,get:function(){return r.generatePath}}),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,"renderMatches",{enumerable:!0,get:function(){return r.renderMatches}}),Object.defineProperty(e,"resolvePath",{enumerable:!0,get:function(){return r.resolvePath}}),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,"useLocation",{enumerable:!0,get:function(){return r.useLocation}}),Object.defineProperty(e,"useMatch",{enumerable:!0,get:function(){return r.useMatch}}),Object.defineProperty(e,"useNavigate",{enumerable:!0,get:function(){return r.useNavigate}}),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,"useRoutes",{enumerable:!0,get:function(){return r.useRoutes}}),e.BrowserRouter=function(e){let{basename:t,children:o,window:a}=e,i=u.useRef();null==i.current&&(i.current=n.createBrowserHistory({window:a,v5Compat:!0}));let c=i.current,[s,l]=u.useState({action:c.action,location:c.location});return u.useLayoutEffect((()=>c.listen(l)),[c]),u.createElement(r.Router,{basename:t,children:o,location:s.location,navigationType:s.action,navigator:c})},e.CompatRoute=function(e){let{location:t,path:n}=e;return e.exact||(n+="/*"),u.createElement(r.Routes,{location:t},u.createElement(r.Route,{path:n,element:u.createElement(a.Route,e)}))},e.CompatRouter=function(e){let{children:t}=e,n=a.useHistory(),[o,i]=u.useState((()=>({location:n.location,action:n.action})));return v((()=>{n.listen(((e,t)=>i({location:e,action:t})))}),[n]),u.createElement(r.Router,{navigationType:o.action,location:o.location,navigator:n},u.createElement(r.Routes,null,u.createElement(r.Route,{path:"*",element:t})))},e.HashRouter=function(e){let{basename:t,children:o,window:a}=e,i=u.useRef();null==i.current&&(i.current=n.createHashHistory({window:a,v5Compat:!0}));let c=i.current,[s,l]=u.useState({action:c.action,location:c.location});return u.useLayoutEffect((()=>c.listen(l)),[c]),u.createElement(r.Router,{basename:t,children:o,location:s.location,navigationType:s.action,navigator:c})},e.Link=p,e.NavLink=m,e.StaticRouter=function(e){let{basename:t,children:n,location:a="/"}=e;"string"==typeof a&&(a=o.parsePath(a));let i=o.Action.Pop,c={pathname:a.pathname||"/",search:a.search||"",hash:a.hash||"",state:a.state||null,key:a.key||"default"},s={createHref:e=>"string"==typeof e?e:o.createPath(e),encodeLocation(e){let t="string"==typeof e?o.parsePath(e):e;return{pathname:t.pathname||"",search:t.search||"",hash:t.hash||""}},push(e){throw new Error("You cannot use navigator.push() on the server because it is a stateless environment. This error was probably triggered when you did a `navigate("+JSON.stringify(e)+")` somewhere in your app.")},replace(e){throw new Error("You cannot use navigator.replace() on the server because it is a stateless environment. This error was probably triggered when you did a `navigate("+JSON.stringify(e)+", { replace: true })` somewhere in your app.")},go(e){throw new Error("You cannot use navigator.go() on the server because it is a stateless environment. This error was probably triggered when you did a `navigate("+e+")` somewhere in your app.")},back(){throw new Error("You cannot use navigator.back() on the server because it is a stateless environment.")},forward(){throw new Error("You cannot use navigator.forward() on the server because it is a stateless environment.")}};return u.createElement(r.Router,{basename:t,children:n,location:c,navigationType:i,navigator:s,static:!0})},e.createSearchParams=l,e.unstable_HistoryRouter=function(e){let{basename:t,children:n,history:o}=e;const[a,i]=u.useState({action:o.action,location:o.location});return u.useLayoutEffect((()=>o.listen(i)),[o]),u.createElement(r.Router,{basename:t,children:n,location:a.location,navigationType:a.action,navigator:o})},e.useLinkClickHandler=y,e.useSearchParams=function(e){let t=u.useRef(l(e)),n=u.useRef(!1),o=r.useLocation(),a=u.useMemo((()=>function(e,t){let r=l(e);if(t)for(let e of t.keys())r.has(e)||t.getAll(e).forEach((t=>{r.append(e,t)}));return r}(o.search,n.current?null:t.current)),[o.search]),i=r.useNavigate(),c=u.useCallback(((e,t)=>{const r=l("function"==typeof e?e(a):e);n.current=!0,i("?"+r,t)}),[i,a]);return[a,c]},Object.defineProperty(e,"__esModule",{value:!0})})); | ||
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("react"),require("react-dom"),require("react-router"),require("@remix-run/router"),require("history"),require("react-router-dom")):"function"==typeof define&&define.amd?define(["exports","react","react-dom","react-router","@remix-run/router","history","react-router-dom"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).ReactRouterDOMv5Compat={},e.React,e.ReactDOM,e.ReactRouter,e.RemixRouter,e.HistoryLibrary,e.ReactRouterDOM)}(this,(function(e,t,n,r,o,a,i){"use strict";function u(e){if(e&&e.__esModule)return e;var t=Object.create(null);return e&&Object.keys(e).forEach((function(n){if("default"!==n){var r=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,r.get?r:{enumerable:!0,get:function(){return e[n]}})}})),t.default=e,Object.freeze(t)}var s=u(t),c=u(n);function l(){return l=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},l.apply(this,arguments)}function f(e,t){if(null==e)return{};var n,r,o={},a=Object.keys(e);for(r=0;r<a.length;r++)n=a[r],t.indexOf(n)>=0||(o[n]=e[n]);return o}const d="get",m="application/x-www-form-urlencoded";function p(e){return null!=e&&"string"==typeof e.tagName}function h(e){return void 0===e&&(e=""),new URLSearchParams("string"==typeof e||Array.isArray(e)||e instanceof URLSearchParams?e:Object.keys(e).reduce(((t,n)=>{let r=e[n];return t.concat(Array.isArray(r)?r.map((e=>[n,e])):[[n,r]])}),[]))}let b=null;const v=new Set(["application/x-www-form-urlencoded","multipart/form-data","text/plain"]);function y(e){return null==e||v.has(e)?e:null}function g(e,t){let n,r,a,i,u;if(p(s=e)&&"form"===s.tagName.toLowerCase()){let u=e.getAttribute("action");r=u?o.stripBasename(u,t):null,n=e.getAttribute("method")||d,a=y(e.getAttribute("enctype"))||m,i=new FormData(e)}else if(function(e){return p(e)&&"button"===e.tagName.toLowerCase()}(e)||function(e){return p(e)&&"input"===e.tagName.toLowerCase()}(e)&&("submit"===e.type||"image"===e.type)){let u=e.form;if(null==u)throw new Error('Cannot submit a <button> or <input type="submit"> without a <form>');let s=e.getAttribute("formaction")||u.getAttribute("action");if(r=s?o.stripBasename(s,t):null,n=e.getAttribute("formmethod")||u.getAttribute("method")||d,a=y(e.getAttribute("formenctype"))||y(u.getAttribute("enctype"))||m,i=new FormData(u,e),!function(){if(null===b)try{new FormData(document.createElement("form"),0),b=!1}catch(e){b=!0}return b}()){let{name:t,type:n,value:r}=e;if("image"===n){let e=t?t+".":"";i.append(e+"x","0"),i.append(e+"y","0")}else t&&i.append(t,r)}}else{if(p(e))throw new Error('Cannot submit element that is not <form>, <button>, or <input type="submit|image">');n=d,r=null,a=m,u=e}var s;return i&&"text/plain"===a&&(u=i,i=void 0),{action:r,method:n.toLowerCase(),encType:a,formData:i,body:u}}const w=["onClick","relative","reloadDocument","replace","state","target","to","preventScrollReset","unstable_viewTransition"],R=["aria-current","caseSensitive","className","end","style","to","unstable_viewTransition","children"],S=["fetcherKey","navigate","reloadDocument","replace","state","method","action","onSubmit","relative","preventScrollReset","unstable_viewTransition"];try{window.__reactRouterVersion="0"}catch(e){}function E(){var e;let t=null==(e=window)?void 0:e.__staticRouterHydrationData;return t&&t.errors&&(t=l({},t,{errors:P(t.errors)})),t}function P(e){if(!e)return null;let t=Object.entries(e),n={};for(let[e,r]of t)if(r&&"RouteErrorResponse"===r.__type)n[e]=new o.UNSAFE_ErrorResponseImpl(r.status,r.statusText,r.data,!0===r.internal);else if(r&&"Error"===r.__type){if(r.__subType){let t=window[r.__subType];if("function"==typeof t)try{let o=new t(r.message);o.stack="",n[e]=o}catch(e){}}if(null==n[e]){let t=new Error(r.message);t.stack="",n[e]=t}}else n[e]=r;return n}const _=s.createContext({isTransitioning:!1}),O=s.createContext(new Map),C=s.startTransition,L=c.flushSync,j=s.useId;function x(e){L?L(e):e()}class A{constructor(){this.status="pending",this.promise=new Promise(((e,t)=>{this.resolve=t=>{"pending"===this.status&&(this.status="resolved",e(t))},this.reject=e=>{"pending"===this.status&&(this.status="rejected",t(e))}}))}}function N(e){let{routes:t,future:n,state:o}=e;return r.UNSAFE_useRoutesImpl(t,void 0,o,n)}const T="undefined"!=typeof window&&void 0!==window.document&&void 0!==window.document.createElement,F=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i,U=s.forwardRef((function(e,t){let n,{onClick:a,relative:i,reloadDocument:u,replace:c,state:d,target:m,to:p,preventScrollReset:h,unstable_viewTransition:b}=e,v=f(e,w),{basename:y}=s.useContext(r.UNSAFE_NavigationContext),g=!1;if("string"==typeof p&&F.test(p)&&(n=p,T))try{let e=new URL(window.location.href),t=p.startsWith("//")?new URL(e.protocol+p):new URL(p),n=o.stripBasename(t.pathname,y);t.origin===e.origin&&null!=n?p=n+t.search+t.hash:g=!0}catch(e){}let R=r.useHref(p,{relative:i}),S=I(p,{replace:c,state:d,target:m,preventScrollReset:h,relative:i,unstable_viewTransition:b});return s.createElement("a",l({},v,{href:n||R,onClick:g||u?a:function(e){a&&a(e),e.defaultPrevented||S(e)},ref:t,target:m}))})),D=s.forwardRef((function(e,t){let{"aria-current":n="page",caseSensitive:a=!1,className:i="",end:u=!1,style:c,to:d,unstable_viewTransition:m,children:p}=e,h=f(e,R),b=r.useResolvedPath(d,{relative:h.relative}),v=r.useLocation(),y=s.useContext(r.UNSAFE_DataRouterStateContext),{navigator:g,basename:w}=s.useContext(r.UNSAFE_NavigationContext),S=null!=y&&function(e,t){void 0===t&&(t={});let n=s.useContext(_);null==n&&o.UNSAFE_invariant(!1);let{basename:a}=B(M.useViewTransitionState),i=r.useResolvedPath(e,{relative:t.relative});if(!n.isTransitioning)return!1;let u=o.stripBasename(n.currentLocation.pathname,a)||n.currentLocation.pathname,c=o.stripBasename(n.nextLocation.pathname,a)||n.nextLocation.pathname;return null!=o.matchPath(i.pathname,c)||null!=o.matchPath(i.pathname,u)}(b)&&!0===m,E=g.encodeLocation?g.encodeLocation(b).pathname:b.pathname,P=v.pathname,O=y&&y.navigation&&y.navigation.location?y.navigation.location.pathname:null;a||(P=P.toLowerCase(),O=O?O.toLowerCase():null,E=E.toLowerCase()),O&&w&&(O=o.stripBasename(O,w)||O);const C="/"!==E&&E.endsWith("/")?E.length-1:E.length;let L,j=P===E||!u&&P.startsWith(E)&&"/"===P.charAt(C),x=null!=O&&(O===E||!u&&O.startsWith(E)&&"/"===O.charAt(E.length)),A={isActive:j,isPending:x,isTransitioning:S},N=j?n:void 0;L="function"==typeof i?i(A):[i,j?"active":null,x?"pending":null,S?"transitioning":null].filter(Boolean).join(" ");let T="function"==typeof c?c(A):c;return s.createElement(U,l({},h,{"aria-current":N,className:L,ref:t,style:T,to:d,unstable_viewTransition:m}),"function"==typeof p?p(A):p)})),k=s.forwardRef(((e,t)=>{let{fetcherKey:n,navigate:r,reloadDocument:o,replace:a,state:i,method:u=d,action:c,onSubmit:m,relative:p,preventScrollReset:h,unstable_viewTransition:b}=e,v=f(e,S),y=Y(),g=q(c,{relative:p}),w="get"===u.toLowerCase()?"get":"post";return s.createElement("form",l({ref:t,method:w,action:g,onSubmit:o?m:e=>{if(m&&m(e),e.defaultPrevented)return;e.preventDefault();let t=e.nativeEvent.submitter,o=(null==t?void 0:t.getAttribute("formmethod"))||u;y(t||e.currentTarget,{fetcherKey:n,method:o,navigate:r,replace:a,state:i,relative:p,preventScrollReset:h,unstable_viewTransition:b})}},v))}));var M=function(e){return e.UseScrollRestoration="useScrollRestoration",e.UseSubmit="useSubmit",e.UseSubmitFetcher="useSubmitFetcher",e.UseFetcher="useFetcher",e.useViewTransitionState="useViewTransitionState",e}(M||{}),H=function(e){return e.UseFetcher="useFetcher",e.UseFetchers="useFetchers",e.UseScrollRestoration="useScrollRestoration",e}(H||{});function B(e){let t=s.useContext(r.UNSAFE_DataRouterContext);return t||o.UNSAFE_invariant(!1),t}function K(e){let t=s.useContext(r.UNSAFE_DataRouterStateContext);return t||o.UNSAFE_invariant(!1),t}function I(e,t){let{target:n,replace:o,state:a,preventScrollReset:i,relative:u,unstable_viewTransition:c}=void 0===t?{}:t,l=r.useNavigate(),f=r.useLocation(),d=r.useResolvedPath(e,{relative:u});return s.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(f)===r.createPath(d);l(e,{replace:n,state:a,preventScrollReset:i,relative:u,unstable_viewTransition:c})}}),[f,l,d,o,a,n,e,i,u,c])}let V=0,z=()=>"__"+String(++V)+"__";function Y(){let{router:e}=B(M.UseSubmit),{basename:t}=s.useContext(r.UNSAFE_NavigationContext),n=r.UNSAFE_useRouteId();return s.useCallback((function(r,o){void 0===o&&(o={}),function(){if("undefined"==typeof document)throw new Error("You are calling submit during the server render. Try calling submit within a `useEffect` or callback instead.")}();let{action:a,method:i,encType:u,formData:s,body:c}=g(r,t);if(!1===o.navigate){let t=o.fetcherKey||z();e.fetch(t,n,o.action||a,{preventScrollReset:o.preventScrollReset,formData:s,body:c,formMethod:o.method||i,formEncType:o.encType||u,unstable_flushSync:o.unstable_flushSync})}else e.navigate(o.action||a,{preventScrollReset:o.preventScrollReset,formData:s,body:c,formMethod:o.method||i,formEncType:o.encType||u,replace:o.replace,state:o.state,fromRouteId:n,unstable_flushSync:o.unstable_flushSync,unstable_viewTransition:o.unstable_viewTransition})}),[e,t,n])}function q(e,t){let{relative:n}=void 0===t?{}:t,{basename:a}=s.useContext(r.UNSAFE_NavigationContext),i=s.useContext(r.UNSAFE_RouteContext);i||o.UNSAFE_invariant(!1);let[u]=i.matches.slice(-1),c=l({},r.useResolvedPath(e||".",{relative:n})),f=r.useLocation();if(null==e){c.search=f.search;let e=new URLSearchParams(c.search);e.has("index")&&""===e.get("index")&&(e.delete("index"),c.search=e.toString()?"?"+e.toString():"")}return e&&"."!==e||!u.route.index||(c.search=c.search?c.search.replace(/^\?/,"?index&"):"?index"),"/"!==a&&(c.pathname="/"===c.pathname?a:o.joinPaths([a,c.pathname])),r.createPath(c)}const J="react-router-scroll-positions";let W={};function $(e){let{getKey:t,storageKey:n}=void 0===e?{}:e,{router:a}=B(M.UseScrollRestoration),{restoreScrollPosition:i,preventScrollReset:u}=K(H.UseScrollRestoration),{basename:c}=s.useContext(r.UNSAFE_NavigationContext),f=r.useLocation(),d=r.useMatches(),m=r.useNavigation();s.useEffect((()=>(window.history.scrollRestoration="manual",()=>{window.history.scrollRestoration="auto"})),[]),function(e,t){let{capture:n}=t||{};s.useEffect((()=>{let t=null!=n?{capture:n}:void 0;return window.addEventListener("pagehide",e,t),()=>{window.removeEventListener("pagehide",e,t)}}),[e,n])}(s.useCallback((()=>{if("idle"===m.state){let e=(t?t(f,d):null)||f.key;W[e]=window.scrollY}try{sessionStorage.setItem(n||J,JSON.stringify(W))}catch(e){}window.history.scrollRestoration="auto"}),[n,t,m.state,f,d])),"undefined"!=typeof document&&(s.useLayoutEffect((()=>{try{let e=sessionStorage.getItem(n||J);e&&(W=JSON.parse(e))}catch(e){}}),[n]),s.useLayoutEffect((()=>{let e=t&&"/"!==c?(e,n)=>t(l({},e,{pathname:o.stripBasename(e.pathname,c)||e.pathname}),n):t,n=null==a?void 0:a.enableScrollRestoration(W,(()=>window.scrollY),e);return()=>n&&n()}),[a,c,t]),s.useLayoutEffect((()=>{if(!1!==i)if("number"!=typeof i){if(f.hash){let e=document.getElementById(decodeURIComponent(f.hash.slice(1)));if(e)return void e.scrollIntoView()}!0!==u&&window.scrollTo(0,0)}else window.scrollTo(0,i)}),[f,i,u]))}const G=!("undefined"==typeof window||void 0===window.document||void 0===window.document.createElement)?s.useLayoutEffect:()=>{};const Q=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i;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,"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,"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,"useBlocker",{enumerable:!0,get:function(){return r.useBlocker}}),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:n,future:a,window:i}=e,u=s.useRef();null==u.current&&(u.current=o.createBrowserHistory({window:i,v5Compat:!0}));let c=u.current,[l,f]=s.useState({action:c.action,location:c.location}),{v7_startTransition:d}=a||{},m=s.useCallback((e=>{d&&C?C((()=>f(e))):f(e)}),[f,d]);return s.useLayoutEffect((()=>c.listen(m)),[c,m]),s.createElement(r.Router,{basename:t,children:n,location:l.location,navigationType:l.action,navigator:c,future:a})},e.CompatRoute=function(e){let{location:t,path:n}=e;return e.exact||(n+="/*"),s.createElement(r.Routes,{location:t},s.createElement(r.Route,{path:n,element:s.createElement(i.Route,e)}))},e.CompatRouter=function(e){let{children:t}=e,n=i.useHistory(),[o,a]=s.useState((()=>({location:n.location,action:n.action})));return G((()=>{n.listen(((e,t)=>a({location:e,action:t})))}),[n]),s.createElement(r.Router,{navigationType:o.action,location:o.location,navigator:n},s.createElement(r.Routes,null,s.createElement(r.Route,{path:"*",element:t})))},e.Form=k,e.HashRouter=function(e){let{basename:t,children:n,future:a,window:i}=e,u=s.useRef();null==u.current&&(u.current=o.createHashHistory({window:i,v5Compat:!0}));let c=u.current,[l,f]=s.useState({action:c.action,location:c.location}),{v7_startTransition:d}=a||{},m=s.useCallback((e=>{d&&C?C((()=>f(e))):f(e)}),[f,d]);return s.useLayoutEffect((()=>c.listen(m)),[c,m]),s.createElement(r.Router,{basename:t,children:n,location:l.location,navigationType:l.action,navigator:c,future:a})},e.Link=U,e.NavLink=D,e.RouterProvider=function(e){let{fallbackElement:t,router:n,future:o}=e,[a,i]=s.useState(n.state),[u,c]=s.useState(),[l,f]=s.useState({isTransitioning:!1}),[d,m]=s.useState(),[p,h]=s.useState(),[b,v]=s.useState(),y=s.useRef(new Map),{v7_startTransition:g}=o||{},w=s.useCallback((e=>{g?function(e){C?C(e):e()}(e):e()}),[g]),R=s.useCallback(((e,t)=>{let{deletedFetchers:r,unstable_flushSync:o,unstable_viewTransitionOpts:a}=t;r.forEach((e=>y.current.delete(e))),e.fetchers.forEach(((e,t)=>{void 0!==e.data&&y.current.set(t,e.data)}));let u=null==n.window||null==n.window.document||"function"!=typeof n.window.document.startViewTransition;if(a&&!u){if(o){x((()=>{p&&(d&&d.resolve(),p.skipTransition()),f({isTransitioning:!0,flushSync:!0,currentLocation:a.currentLocation,nextLocation:a.nextLocation})}));let t=n.window.document.startViewTransition((()=>{x((()=>i(e)))}));return t.finished.finally((()=>{x((()=>{m(void 0),h(void 0),c(void 0),f({isTransitioning:!1})}))})),void x((()=>h(t)))}p?(d&&d.resolve(),p.skipTransition(),v({state:e,currentLocation:a.currentLocation,nextLocation:a.nextLocation})):(c(e),f({isTransitioning:!0,flushSync:!1,currentLocation:a.currentLocation,nextLocation:a.nextLocation}))}else o?x((()=>i(e))):w((()=>i(e)))}),[n.window,p,d,y,w]);s.useLayoutEffect((()=>n.subscribe(R)),[n,R]),s.useEffect((()=>{l.isTransitioning&&!l.flushSync&&m(new A)}),[l]),s.useEffect((()=>{if(d&&u&&n.window){let e=u,t=d.promise,r=n.window.document.startViewTransition((async()=>{w((()=>i(e))),await t}));r.finished.finally((()=>{m(void 0),h(void 0),c(void 0),f({isTransitioning:!1})})),h(r)}}),[w,u,d,n.window]),s.useEffect((()=>{d&&u&&a.location.key===u.location.key&&d.resolve()}),[d,p,a.location,u]),s.useEffect((()=>{!l.isTransitioning&&b&&(c(b.state),f({isTransitioning:!0,flushSync:!1,currentLocation:b.currentLocation,nextLocation:b.nextLocation}),v(void 0))}),[l.isTransitioning,b]),s.useEffect((()=>{}),[]);let S=s.useMemo((()=>({createHref:n.createHref,encodeLocation:n.encodeLocation,go:e=>n.navigate(e),push:(e,t,r)=>n.navigate(e,{state:t,preventScrollReset:null==r?void 0:r.preventScrollReset}),replace:(e,t,r)=>n.navigate(e,{replace:!0,state:t,preventScrollReset:null==r?void 0:r.preventScrollReset})})),[n]),E=n.basename||"/",P=s.useMemo((()=>({router:n,navigator:S,static:!1,basename:E})),[n,S,E]);return s.createElement(s.Fragment,null,s.createElement(r.UNSAFE_DataRouterContext.Provider,{value:P},s.createElement(r.UNSAFE_DataRouterStateContext.Provider,{value:a},s.createElement(O.Provider,{value:y.current},s.createElement(_.Provider,{value:l},s.createElement(r.Router,{basename:E,location:a.location,navigationType:a.historyAction,navigator:S,future:{v7_relativeSplatPath:n.future.v7_relativeSplatPath}},a.initialized||n.future.v7_partialHydration?s.createElement(N,{routes:n.routes,future:n.future,state:a}):t))))),null)},e.ScrollRestoration=function(e){let{getKey:t,storageKey:n}=e;return $({getKey:t,storageKey:n}),null},e.StaticRouter=function(e){let{basename:t,children:n,location:o="/"}=e;"string"==typeof o&&(o=a.parsePath(o));let i=a.Action.Pop,u={pathname:o.pathname||"/",search:o.search||"",hash:o.hash||"",state:null!=o.state?o.state:null,key:o.key||"default"},c={createHref:e=>"string"==typeof e?e:a.createPath(e),encodeLocation(e){let t="string"==typeof e?e:a.createPath(e);t=t.replace(/ $/,"%20");let n=Q.test(t)?new URL(t):new URL(t,"http://localhost");return{pathname:n.pathname,search:n.search,hash:n.hash}},push(e){throw new Error("You cannot use navigator.push() on the server because it is a stateless environment. This error was probably triggered when you did a `navigate("+JSON.stringify(e)+")` somewhere in your app.")},replace(e){throw new Error("You cannot use navigator.replace() on the server because it is a stateless environment. This error was probably triggered when you did a `navigate("+JSON.stringify(e)+", { replace: true })` somewhere in your app.")},go(e){throw new Error("You cannot use navigator.go() on the server because it is a stateless environment. This error was probably triggered when you did a `navigate("+e+")` somewhere in your app.")},back(){throw new Error("You cannot use navigator.back() on the server because it is a stateless environment.")},forward(){throw new Error("You cannot use navigator.forward() on the server because it is a stateless environment.")}};return s.createElement(r.Router,{basename:t,children:n,location:u,navigationType:i,navigator:c,static:!0})},e.UNSAFE_useScrollRestoration=$,e.createBrowserRouter=function(e,t){return o.createRouter({basename:null==t?void 0:t.basename,future:l({},null==t?void 0:t.future,{v7_prependBasename:!0}),history:o.createBrowserHistory({window:null==t?void 0:t.window}),hydrationData:(null==t?void 0:t.hydrationData)||E(),routes:e,mapRouteProperties:r.UNSAFE_mapRouteProperties,unstable_dataStrategy:null==t?void 0:t.unstable_dataStrategy,unstable_patchRoutesOnMiss:null==t?void 0:t.unstable_patchRoutesOnMiss,window:null==t?void 0:t.window}).initialize()},e.createHashRouter=function(e,t){return o.createRouter({basename:null==t?void 0:t.basename,future:l({},null==t?void 0:t.future,{v7_prependBasename:!0}),history:o.createHashHistory({window:null==t?void 0:t.window}),hydrationData:(null==t?void 0:t.hydrationData)||E(),routes:e,mapRouteProperties:r.UNSAFE_mapRouteProperties,unstable_dataStrategy:null==t?void 0:t.unstable_dataStrategy,unstable_patchRoutesOnMiss:null==t?void 0:t.unstable_patchRoutesOnMiss,window:null==t?void 0:t.window}).initialize()},e.createSearchParams=h,e.unstable_HistoryRouter=function(e){let{basename:t,children:n,future:o,history:a}=e,[i,u]=s.useState({action:a.action,location:a.location}),{v7_startTransition:c}=o||{},l=s.useCallback((e=>{c&&C?C((()=>u(e))):u(e)}),[u,c]);return s.useLayoutEffect((()=>a.listen(l)),[a,l]),s.createElement(r.Router,{basename:t,children:n,location:i.location,navigationType:i.action,navigator:a,future:o})},e.unstable_usePrompt=function(e){let{when:t,message:n}=e,o=r.useBlocker(t);s.useEffect((()=>{if("blocked"===o.state){window.confirm(n)?setTimeout(o.proceed,0):o.reset()}}),[o,n]),s.useEffect((()=>{"blocked"!==o.state||t||o.reset()}),[o,t])},e.useBeforeUnload=function(e,t){let{capture:n}=t||{};s.useEffect((()=>{let t=null!=n?{capture:n}:void 0;return window.addEventListener("beforeunload",e,t),()=>{window.removeEventListener("beforeunload",e,t)}}),[e,n])},e.useFetcher=function(e){var t;let{key:n}=void 0===e?{}:e,{router:a}=B(M.UseFetcher),i=K(H.UseFetcher),u=s.useContext(O),c=s.useContext(r.UNSAFE_RouteContext),f=null==(t=c.matches[c.matches.length-1])?void 0:t.route.id;u||o.UNSAFE_invariant(!1),c||o.UNSAFE_invariant(!1),null==f&&o.UNSAFE_invariant(!1);let d=j?j():"",[m,p]=s.useState(n||d);n&&n!==m?p(n):m||p(z()),s.useEffect((()=>(a.getFetcher(m),()=>{a.deleteFetcher(m)})),[a,m]);let h=s.useCallback(((e,t)=>{f||o.UNSAFE_invariant(!1),a.fetch(m,f,e,t)}),[m,f,a]),b=Y(),v=s.useCallback(((e,t)=>{b(e,l({},t,{navigate:!1,fetcherKey:m}))}),[m,b]),y=s.useMemo((()=>s.forwardRef(((e,t)=>s.createElement(k,l({},e,{navigate:!1,fetcherKey:m,ref:t}))))),[m]),g=i.fetchers.get(m)||o.IDLE_FETCHER,w=u.get(m);return s.useMemo((()=>l({Form:y,submit:v,load:h},g,{data:w})),[y,v,h,g,w])},e.useFetchers=function(){let e=K(H.UseFetchers);return Array.from(e.fetchers.entries()).map((e=>{let[t,n]=e;return l({},n,{key:t})}))},e.useFormAction=q,e.useLinkClickHandler=I,e.useSearchParams=function(e){let t=s.useRef(h(e)),n=s.useRef(!1),o=r.useLocation(),a=s.useMemo((()=>function(e,t){let n=h(e);return t&&t.forEach(((e,r)=>{n.has(r)||t.getAll(r).forEach((e=>{n.append(r,e)}))})),n}(o.search,n.current?null:t.current)),[o.search]),i=r.useNavigate(),u=s.useCallback(((e,t)=>{const r=h("function"==typeof e?e(a):e);n.current=!0,i("?"+r,t)}),[i,a]);return[a,u]},e.useSubmit=Y,Object.defineProperty(e,"__esModule",{value:!0})})); | ||
//# sourceMappingURL=react-router-dom-v5-compat.production.min.js.map |
MIT License | ||
Copyright (c) React Training 2015-2019 | ||
Copyright (c) Remix Software 2020-2022 | ||
Copyright (c) React Training LLC 2015-2019 | ||
Copyright (c) Remix Software Inc. 2020-2021 | ||
Copyright (c) Shopify Inc. 2022-2023 | ||
@@ -6,0 +7,0 @@ Permission is hereby granted, free of charge, to any person obtaining a copy |
{ | ||
"name": "react-router-dom-v5-compat", | ||
"version": "0.0.0-experimental-cf9637ce", | ||
"version": "0.0.0-experimental-cffa549a1", | ||
"description": "Migration path to React Router v6 from v4/5", | ||
@@ -27,3 +27,4 @@ "keywords": [ | ||
"history": "^5.3.0", | ||
"react-router": "0.0.0-experimental-cf9637ce" | ||
"react-router": "0.0.0-experimental-cffa549a1", | ||
"@remix-run/router": "0.0.0-experimental-cffa549a1" | ||
}, | ||
@@ -42,4 +43,4 @@ "peerDependencies": { | ||
"engines": { | ||
"node": ">=14" | ||
"node": ">=14.0.0" | ||
} | ||
} | ||
} |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
585142
4038
6
22
+ Added@remix-run/router@0.0.0-experimental-cffa549a1(transitive)
+ Addedreact-router@0.0.0-experimental-cffa549a1(transitive)
- Removed@remix-run/router@0.0.0-experimental-cf9637ce(transitive)
- Removedreact-router@0.0.0-experimental-cf9637ce(transitive)