react-router-dom
Advanced tools
Comparing version 0.0.0-experimental-f728258d to 0.0.0-experimental-f7aa35148
402
CHANGELOG.md
# `react-router-dom` | ||
## 6.24.1 | ||
### Patch Changes | ||
- Remove `polyfill.io` reference from warning message because the domain was sold and has since been determined to serve malware ([#11741](https://github.com/remix-run/react-router/pull/11741)) | ||
- See <https://sansec.io/research/polyfill-supply-chain-attack> | ||
- Export `NavLinkRenderProps` type for easier typing of custom `NavLink` callback ([#11553](https://github.com/remix-run/react-router/pull/11553)) | ||
- Updated dependencies: | ||
- `@remix-run/router@1.17.1` | ||
- `react-router@6.24.1` | ||
## 6.24.0 | ||
### Minor Changes | ||
- Add support for Lazy Route Discovery (a.k.a. Fog of War) ([#11626](https://github.com/remix-run/react-router/pull/11626)) | ||
- RFC: <https://github.com/remix-run/react-router/discussions/11113> | ||
- `unstable_patchRoutesOnMiss` docs: <https://reactrouter.com/en/main/routers/create-browser-router> | ||
### Patch Changes | ||
- Fix `fetcher.submit` types - remove incorrect `navigate`/`fetcherKey`/`unstable_viewTransition` options because they are only relevant for `useSubmit` ([#11631](https://github.com/remix-run/react-router/pull/11631)) | ||
- Allow falsy `location.state` values passed to `<StaticRouter>` ([#11495](https://github.com/remix-run/react-router/pull/11495)) | ||
- Updated dependencies: | ||
- `react-router@6.24.0` | ||
- `@remix-run/router@1.17.0` | ||
## 6.23.1 | ||
### Patch Changes | ||
- Check for `document` existence when checking `startViewTransition` ([#11544](https://github.com/remix-run/react-router/pull/11544)) | ||
- Change the `react-router-dom/server` import back to `react-router-dom` instead of `index.ts` ([#11514](https://github.com/remix-run/react-router/pull/11514)) | ||
- Updated dependencies: | ||
- `@remix-run/router@1.16.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` | ||
## 6.22.3 | ||
### Patch Changes | ||
- Updated dependencies: | ||
- `@remix-run/router@1.15.3` | ||
- `react-router@6.22.3` | ||
## 6.22.2 | ||
### Patch Changes | ||
- Updated dependencies: | ||
- `@remix-run/router@1.15.2` | ||
- `react-router@6.22.2` | ||
## 6.22.1 | ||
### Patch Changes | ||
- Updated dependencies: | ||
- `react-router@6.22.1` | ||
- `@remix-run/router@1.15.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: | ||
- `@remix-run/router@1.15.0` | ||
- `react-router@6.22.0` | ||
## 6.21.3 | ||
### Patch Changes | ||
- Fix `NavLink` `isPending` when a `basename` is used ([#11195](https://github.com/remix-run/react-router/pull/11195)) | ||
- Remove leftover `unstable_` prefix from `Blocker`/`BlockerFunction` types ([#11187](https://github.com/remix-run/react-router/pull/11187)) | ||
- Updated dependencies: | ||
- `react-router@6.21.3` | ||
## 6.21.2 | ||
### Patch Changes | ||
- Leverage `useId` for internal fetcher keys when available ([#11166](https://github.com/remix-run/react-router/pull/11166)) | ||
- Updated dependencies: | ||
- `@remix-run/router@1.14.2` | ||
- `react-router@6.21.2` | ||
## 6.21.1 | ||
### Patch Changes | ||
- Updated dependencies: | ||
- `react-router@6.21.1` | ||
- `@remix-run/router@1.14.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: | ||
- `@remix-run/router@1.14.0` | ||
- `react-router@6.21.0` | ||
## 6.20.1 | ||
### Patch Changes | ||
- Revert the `useResolvedPath` fix for splat routes due to a large number of applications that were relying on the buggy behavior (see <https://github.com/remix-run/react-router/issues/11052#issuecomment-1836589329>). We plan to re-introduce this fix behind a future flag in the next minor version. ([#11078](https://github.com/remix-run/react-router/pull/11078)) | ||
- Updated dependencies: | ||
- `react-router@6.20.1` | ||
- `@remix-run/router@1.13.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@6.20.0` | ||
- `@remix-run/router@1.13.0` | ||
## 6.19.0 | ||
### Minor Changes | ||
- Add `unstable_flushSync` option to `useNavigate`/`useSumbit`/`fetcher.load`/`fetcher.submit` to opt-out of `React.startTransition` and into `ReactDOM.flushSync` for state updates ([#11005](https://github.com/remix-run/react-router/pull/11005)) | ||
- Allow `unstable_usePrompt` to accept a `BlockerFunction` in addition to a `boolean` ([#10991](https://github.com/remix-run/react-router/pull/10991)) | ||
### Patch Changes | ||
- Fix issue where a changing fetcher `key` in a `useFetcher` that remains mounted wasn't getting picked up ([#11009](https://github.com/remix-run/react-router/pull/11009)) | ||
- Fix `useFormAction` which was incorrectly inheriting the `?index` query param from child route `action` submissions ([#11025](https://github.com/remix-run/react-router/pull/11025)) | ||
- Fix `NavLink` `active` logic when `to` location has a trailing slash ([#10734](https://github.com/remix-run/react-router/pull/10734)) | ||
- Updated dependencies: | ||
- `react-router@6.19.0` | ||
- `@remix-run/router@1.12.0` | ||
## 6.18.0 | ||
### Minor Changes | ||
- Add support for manual fetcher key specification via `useFetcher({ key: string })` so you can access the same fetcher instance from different components in your application without prop-drilling ([RFC](https://github.com/remix-run/remix/discussions/7698)) ([#10960](https://github.com/remix-run/react-router/pull/10960)) | ||
- Fetcher keys are now also exposed on the fetchers returned from `useFetchers` so that they can be looked up by `key` | ||
- Add `navigate`/`fetcherKey` params/props to `useSumbit`/`Form` to support kicking off a fetcher submission under the hood with an optionally user-specified `key` ([#10960](https://github.com/remix-run/react-router/pull/10960)) | ||
- Invoking a fetcher in this way is ephemeral and stateless | ||
- If you need to access the state of one of these fetchers, you will need to leverage `useFetcher({ key })` to look it up elsewhere | ||
### Patch Changes | ||
- Adds a fetcher context to `RouterProvider` that holds completed fetcher data, in preparation for the upcoming future flag that will change the fetcher persistence/cleanup behavior ([#10961](https://github.com/remix-run/react-router/pull/10961)) | ||
- Fix the `future` prop on `BrowserRouter`, `HashRouter` and `MemoryRouter` so that it accepts a `Partial<FutureConfig>` instead of requiring all flags to be included. ([#10962](https://github.com/remix-run/react-router/pull/10962)) | ||
- Updated dependencies: | ||
- `@remix-run/router@1.11.0` | ||
- `react-router@6.18.0` | ||
## 6.17.0 | ||
### Minor Changes | ||
- Add experimental support for the [View Transitions API](https://developer.mozilla.org/en-US/docs/Web/API/ViewTransition) via `document.startViewTransition` to enable CSS animated transitions on SPA navigations in your application. ([#10916](https://github.com/remix-run/react-router/pull/10916)) | ||
The simplest approach to enabling a View Transition in your React Router app is via the new `<Link unstable_viewTransition>` prop. This will cause the navigation DOM update to be wrapped in `document.startViewTransition` which will enable transitions for the DOM update. Without any additional CSS styles, you'll get a basic cross-fade animation for your page. | ||
If you need to apply more fine-grained styles for your animations, you can leverage the `unstable_useViewTransitionState` hook which will tell you when a transition is in progress and you can use that to apply classes or styles: | ||
```jsx | ||
function ImageLink(to, src, alt) { | ||
let isTransitioning = unstable_useViewTransitionState(to); | ||
return ( | ||
<Link to={to} unstable_viewTransition> | ||
<img | ||
src={src} | ||
alt={alt} | ||
style={{ | ||
viewTransitionName: isTransitioning ? "image-expand" : "", | ||
}} | ||
/> | ||
</Link> | ||
); | ||
} | ||
``` | ||
You can also use the `<NavLink unstable_viewTransition>` shorthand which will manage the hook usage for you and automatically add a `transitioning` class to the `<a>` during the transition: | ||
```css | ||
a.transitioning img { | ||
view-transition-name: "image-expand"; | ||
} | ||
``` | ||
```jsx | ||
<NavLink to={to} unstable_viewTransition> | ||
<img src={src} alt={alt} /> | ||
</NavLink> | ||
``` | ||
For an example usage of View Transitions with React Router, check out [our fork](https://github.com/brophdawg11/react-router-records) of the [Astro Records](https://github.com/Charca/astro-records) demo. | ||
For more information on using the View Transitions API, please refer to the [Smooth and simple transitions with the View Transitions API](https://developer.chrome.com/docs/web-platform/view-transitions/) guide from the Google Chrome team. | ||
Please note, that because the `ViewTransition` API is a DOM API, we now export a specific `RouterProvider` from `react-router-dom` with this functionality. If you are importing `RouterProvider` from `react-router`, then it will not support view transitions. ([#10928](https://github.com/remix-run/react-router/pull/10928) | ||
### Patch Changes | ||
- Log a warning and fail gracefully in `ScrollRestoration` when `sessionStorage` is unavailable ([#10848](https://github.com/remix-run/react-router/pull/10848)) | ||
- Updated dependencies: | ||
- `@remix-run/router@1.10.0` | ||
- `react-router@6.17.0` | ||
## 6.16.0 | ||
### Minor Changes | ||
- Updated dependencies: | ||
- `@remix-run/router@1.9.0` | ||
- `react-router@6.16.0` | ||
### Patch Changes | ||
- Properly encode rendered URIs in server rendering to avoid hydration errors ([#10769](https://github.com/remix-run/react-router/pull/10769)) | ||
## 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 | ||
- Fixes an edge-case affecting web extensions in Firefox that use `URLSearchParams` and the `useSearchParams` hook. ([#10620](https://github.com/remix-run/react-router/pull/10620)) | ||
- Do not include hash in `useFormAction()` for unspecified actions since it cannot be determined on the server and causes hydration issues ([#10758](https://github.com/remix-run/react-router/pull/10758)) | ||
- Reorder effects in `unstable_usePrompt` to avoid throwing an exception if the prompt is unblocked and a navigation is performed synchronously ([#10687](https://github.com/remix-run/react-router/pull/10687), [#10718](https://github.com/remix-run/react-router/pull/10718)) | ||
- Updated dependencies: | ||
- `@remix-run/router@1.8.0` | ||
- `react-router@6.15.0` | ||
## 6.14.2 | ||
@@ -123,3 +517,3 @@ | ||
> **Warning** | ||
> \[!WARNING] | ||
> Please use version `6.13.0` or later instead of `6.12.1`. This version suffers from a `webpack`/`terser` minification issue resulting in invalid minified code in your resulting production bundles which can cause issues in your application. See [#10579](https://github.com/remix-run/react-router/issues/10579) for more details. | ||
@@ -459,3 +853,3 @@ | ||
Whoa this is a big one! `6.4.0` brings all the data loading and mutation APIs over from Remix. Here's a quick high level overview, but it's recommended you go check out the [docs][rr-docs], especially the [feature overview][rr-feature-overview] and the [tutorial][rr-tutorial]. | ||
Whoa this is a big one! `6.4.0` brings all the data loading and mutation APIs over from Remix. Here's a quick high level overview, but it's recommended you go check out the [docs](https://reactrouter.com), especially the [feature overview](https://reactrouter.com/start/overview) and the [tutorial](https://reactrouter.com/start/tutorial). | ||
@@ -486,5 +880,1 @@ **New APIs** | ||
- `react-router@6.4.0` | ||
[rr-docs]: https://reactrouter.com | ||
[rr-feature-overview]: https://reactrouter.com/start/overview | ||
[rr-tutorial]: https://reactrouter.com/start/tutorial |
@@ -43,3 +43,6 @@ import type { FormEncType, HTMLFormMethod, RelativeRoutingType } from "@remix-run/router"; | ||
export type SubmitTarget = HTMLFormElement | HTMLButtonElement | HTMLInputElement | FormData | URLSearchParams | JsonValue | null; | ||
export interface SubmitOptions { | ||
/** | ||
* Submit options shared by both navigations and fetchers | ||
*/ | ||
interface SharedSubmitOptions { | ||
/** | ||
@@ -61,2 +64,27 @@ * The HTTP method used to submit the form. Overrides `<form method>`. | ||
/** | ||
* Determines whether the form action is relative to the route hierarchy or | ||
* the pathname. Use this if you want to opt out of navigating the route | ||
* hierarchy and want to instead route based on /-delimited URL segments | ||
*/ | ||
relative?: RelativeRoutingType; | ||
/** | ||
* In browser-based environments, prevent resetting scroll after this | ||
* navigation when using the <ScrollRestoration> component | ||
*/ | ||
preventScrollReset?: boolean; | ||
/** | ||
* Enable flushSync for this submission's state updates | ||
*/ | ||
unstable_flushSync?: boolean; | ||
} | ||
/** | ||
* 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 | ||
@@ -72,12 +100,13 @@ * instead of creating a new one (i.e. stay on "the same page"). Defaults | ||
/** | ||
* Determines whether the form action is relative to the route hierarchy or | ||
* the pathname. Use this if you want to opt out of navigating the route | ||
* hierarchy and want to instead route based on /-delimited URL segments | ||
* Indicate a specific fetcherKey to use when using navigate=false | ||
*/ | ||
relative?: RelativeRoutingType; | ||
fetcherKey?: string; | ||
/** | ||
* In browser-based environments, prevent resetting scroll after this | ||
* navigation when using the <ScrollRestoration> component | ||
* navigate=false will use a fetcher instead of a navigation | ||
*/ | ||
preventScrollReset?: boolean; | ||
navigate?: boolean; | ||
/** | ||
* Enable view transitions on this submission navigation | ||
*/ | ||
unstable_viewTransition?: boolean; | ||
} | ||
@@ -84,0 +113,0 @@ export declare function getFormSubmissionInfo(target: SubmitTarget, basename: string): { |
@@ -6,10 +6,11 @@ /** | ||
import * as React from "react"; | ||
import type { FutureConfig, NavigateOptions, RelativeRoutingType, RouteObject, To } from "react-router"; | ||
import type { Fetcher, FormEncType, FormMethod, FutureConfig as RouterFutureConfig, GetScrollRestorationKeyFunction, History, HTMLFormMethod, HydrationState, Router as RemixRouter, V7_FormMethod } from "@remix-run/router"; | ||
import type { SubmitOptions, ParamKeyValuePair, URLSearchParamsInit, SubmitTarget } from "./dom"; | ||
import 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, V7_FormMethod, }; | ||
export { createSearchParams }; | ||
export type { ActionFunction, ActionFunctionArgs, AwaitProps, unstable_Blocker, unstable_BlockerFunction, DataRouteMatch, DataRouteObject, Fetcher, Hash, IndexRouteObject, IndexRouteProps, JsonFunction, LazyRouteFunction, LayoutRouteProps, LoaderFunction, LoaderFunctionArgs, Location, MemoryRouterProps, NavigateFunction, NavigateOptions, NavigateProps, Navigation, Navigator, NonIndexRouteObject, OutletProps, Params, ParamParseKey, Path, PathMatch, Pathname, PathPattern, PathRouteProps, RedirectFunction, RelativeRoutingType, RouteMatch, RouteObject, RouteProps, RouterProps, RouterProviderProps, RoutesProps, Search, ShouldRevalidateFunction, To, } from "react-router"; | ||
export { AbortedDeferredError, Await, MemoryRouter, Navigate, NavigationType, Outlet, Route, Router, RouterProvider, Routes, createMemoryRouter, createPath, createRoutesFromChildren, createRoutesFromElements, defer, isRouteErrorResponse, generatePath, json, matchPath, matchRoutes, parsePath, redirect, 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 */ | ||
@@ -19,2 +20,6 @@ export { UNSAFE_DataRouterContext, UNSAFE_DataRouterStateContext, UNSAFE_NavigationContext, UNSAFE_LocationContext, UNSAFE_RouteContext, UNSAFE_useRouteId, } from "react-router"; | ||
var __staticRouterHydrationData: HydrationState | undefined; | ||
var __reactRouterVersion: string; | ||
interface Document { | ||
startViewTransition(cb: () => Promise<void> | void): ViewTransition; | ||
} | ||
} | ||
@@ -25,2 +30,4 @@ interface DOMRouterOpts { | ||
hydrationData?: HydrationState; | ||
unstable_dataStrategy?: unstable_DataStrategyFunction; | ||
unstable_patchRoutesOnMiss?: unstable_PatchRoutesOnMissFunction; | ||
window?: Window; | ||
@@ -30,6 +37,29 @@ } | ||
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?: FutureConfig; | ||
future?: Partial<FutureConfig>; | ||
window?: Window; | ||
@@ -40,7 +70,7 @@ } | ||
*/ | ||
export declare function BrowserRouter({ basename, children, future, 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?: FutureConfig; | ||
future?: Partial<FutureConfig>; | ||
window?: Window; | ||
@@ -52,3 +82,3 @@ } | ||
*/ | ||
export declare function HashRouter({ basename, children, future, window, }: HashRouterProps): JSX.Element; | ||
export declare function HashRouter({ basename, children, future, window, }: HashRouterProps): React.JSX.Element; | ||
export interface HistoryRouterProps { | ||
@@ -66,3 +96,3 @@ basename?: string; | ||
*/ | ||
declare function HistoryRouter({ basename, children, future, history, }: HistoryRouterProps): JSX.Element; | ||
declare function HistoryRouter({ basename, children, future, history, }: HistoryRouterProps): React.JSX.Element; | ||
declare namespace HistoryRouter { | ||
@@ -79,28 +109,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 FetcherFormProps extends React.FormHTMLAttributes<HTMLFormElement> { | ||
/** | ||
* Form props shared by navigations and fetchers | ||
*/ | ||
interface SharedFormProps extends React.FormHTMLAttributes<HTMLFormElement> { | ||
/** | ||
@@ -137,4 +167,20 @@ * The HTTP verb to use when the form is submit. Supports "get", "post", | ||
} | ||
export interface FormProps extends FetcherFormProps { | ||
/** | ||
* 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. | ||
@@ -153,2 +199,6 @@ */ | ||
state?: any; | ||
/** | ||
* Enable view transitions on this Form navigation | ||
*/ | ||
unstable_viewTransition?: boolean; | ||
} | ||
@@ -179,3 +229,3 @@ /** | ||
*/ | ||
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; | ||
@@ -186,2 +236,3 @@ replace?: boolean; | ||
relative?: RelativeRoutingType; | ||
unstable_viewTransition?: boolean; | ||
}): (event: React.MouseEvent<E, MouseEvent>) => void; | ||
@@ -218,3 +269,3 @@ /** | ||
export interface FetcherSubmitFunction { | ||
(target: SubmitTarget, options?: Omit<SubmitOptions, "replace" | "state">): void; | ||
(target: SubmitTarget, options?: FetcherSubmitOptions): void; | ||
} | ||
@@ -229,7 +280,8 @@ /** | ||
}): string; | ||
declare function createFetcherForm(fetcherKey: string, routeId: string): React.ForwardRefExoticComponent<FetcherFormProps & React.RefAttributes<HTMLFormElement>>; | ||
export type FetcherWithComponents<TData> = Fetcher<TData> & { | ||
Form: ReturnType<typeof createFetcherForm>; | ||
Form: React.ForwardRefExoticComponent<FetcherFormProps & React.RefAttributes<HTMLFormElement>>; | ||
submit: FetcherSubmitFunction; | ||
load: (href: string) => void; | ||
load: (href: string, opts?: { | ||
unstable_flushSync?: boolean; | ||
}) => void; | ||
}; | ||
@@ -240,3 +292,5 @@ /** | ||
*/ | ||
export declare function useFetcher<TData = any>(): FetcherWithComponents<TData>; | ||
export declare function useFetcher<TData = any>({ key, }?: { | ||
key?: string; | ||
}): FetcherWithComponents<TData>; | ||
/** | ||
@@ -246,3 +300,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; | ||
})[]; | ||
/** | ||
@@ -275,6 +331,18 @@ * When rendered inside a RouterProvider, will restore scroll positions on navigations | ||
*/ | ||
declare function usePrompt({ when, message }: { | ||
when: boolean; | ||
declare function usePrompt({ when, message, }: { | ||
when: boolean | BlockerFunction; | ||
message: string; | ||
}): void; | ||
export { usePrompt as unstable_usePrompt }; | ||
/** | ||
* 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 v0.0.0-experimental-f728258d | ||
* React Router DOM v0.0.0-experimental-f7aa35148 | ||
* | ||
@@ -12,5 +12,7 @@ * Copyright (c) Remix Software Inc. | ||
import * as React from 'react'; | ||
import { UNSAFE_mapRouteProperties, Router, UNSAFE_NavigationContext, useHref, useResolvedPath, useLocation, UNSAFE_DataRouterStateContext, useNavigate, createPath, UNSAFE_useRouteId, UNSAFE_RouteContext, useMatches, useNavigation, unstable_useBlocker, UNSAFE_DataRouterContext } from 'react-router'; | ||
export { AbortedDeferredError, Await, MemoryRouter, Navigate, NavigationType, Outlet, Route, Router, RouterProvider, Routes, UNSAFE_DataRouterContext, UNSAFE_DataRouterStateContext, UNSAFE_LocationContext, UNSAFE_NavigationContext, UNSAFE_RouteContext, UNSAFE_useRouteId, createMemoryRouter, createPath, createRoutesFromChildren, createRoutesFromElements, defer, generatePath, isRouteErrorResponse, json, matchPath, matchRoutes, parsePath, redirect, renderMatches, resolvePath, unstable_useBlocker, useActionData, useAsyncError, useAsyncValue, useHref, useInRouterContext, useLoaderData, useLocation, useMatch, useMatches, useNavigate, useNavigation, useNavigationType, useOutlet, useOutletContext, useParams, useResolvedPath, useRevalidator, useRouteError, useRouteLoaderData, useRoutes } from 'react-router'; | ||
import { stripBasename, UNSAFE_warning, createRouter, createBrowserHistory, createHashHistory, ErrorResponse, UNSAFE_invariant, joinPaths } from '@remix-run/router'; | ||
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 } 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'; | ||
export { UNSAFE_ErrorResponseImpl } from '@remix-run/router'; | ||
@@ -210,5 +212,20 @@ function _extends() { | ||
const _excluded = ["onClick", "relative", "reloadDocument", "replace", "state", "target", "to", "preventScrollReset"], | ||
_excluded2 = ["aria-current", "caseSensitive", "className", "end", "style", "to", "children"], | ||
_excluded3 = ["reloadDocument", "replace", "state", "method", "action", "onSubmit", "submit", "relative", "preventScrollReset"]; | ||
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) { | ||
@@ -225,3 +242,6 @@ return createRouter({ | ||
routes, | ||
mapRouteProperties: UNSAFE_mapRouteProperties | ||
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(); | ||
@@ -240,3 +260,6 @@ } | ||
routes, | ||
mapRouteProperties: UNSAFE_mapRouteProperties | ||
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(); | ||
@@ -262,3 +285,3 @@ } | ||
if (val && val.__type === "RouteErrorResponse") { | ||
serialized[key] = new ErrorResponse(val.status, val.statusText, val.data, val.internal === true); | ||
serialized[key] = new UNSAFE_ErrorResponseImpl(val.status, val.statusText, val.data, val.internal === true); | ||
} else if (val && val.__type === "Error") { | ||
@@ -294,2 +317,12 @@ // Attempt to reconstruct the right type of Error (i.e., ReferenceError) | ||
} | ||
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 | ||
@@ -322,6 +355,270 @@ //////////////////////////////////////////////////////////////////////////////// | ||
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); | ||
} | ||
}; | ||
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]); | ||
let routerFuture = React.useMemo(() => ({ | ||
v7_relativeSplatPath: router.future.v7_relativeSplatPath | ||
}), [router.future.v7_relativeSplatPath]); | ||
// 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: routerFuture | ||
}, state.initialized || router.future.v7_partialHydration ? /*#__PURE__*/React.createElement(MemoizedDataRoutes, { | ||
routes: router.routes, | ||
future: router.future, | ||
state: state | ||
}) : fallbackElement))))), null); | ||
} | ||
// Memoize to avoid re-renders when updating `ViewTransitionContext` | ||
const MemoizedDataRoutes = /*#__PURE__*/React.memo(DataRoutes); | ||
function DataRoutes(_ref3) { | ||
let { | ||
routes, | ||
future, | ||
state | ||
} = _ref3; | ||
return UNSAFE_useRoutesImpl(routes, undefined, state, future); | ||
} | ||
/** | ||
* A `<Router>` for use in web browsers. Provides the cleanest URLs. | ||
*/ | ||
function BrowserRouter(_ref) { | ||
function BrowserRouter(_ref4) { | ||
let { | ||
@@ -332,3 +629,3 @@ basename, | ||
window | ||
} = _ref; | ||
} = _ref4; | ||
let historyRef = React.useRef(); | ||
@@ -358,3 +655,4 @@ if (historyRef.current == null) { | ||
navigationType: state.action, | ||
navigator: history | ||
navigator: history, | ||
future: future | ||
}); | ||
@@ -366,3 +664,3 @@ } | ||
*/ | ||
function HashRouter(_ref2) { | ||
function HashRouter(_ref5) { | ||
let { | ||
@@ -373,3 +671,3 @@ basename, | ||
window | ||
} = _ref2; | ||
} = _ref5; | ||
let historyRef = React.useRef(); | ||
@@ -399,3 +697,4 @@ if (historyRef.current == null) { | ||
navigationType: state.action, | ||
navigator: history | ||
navigator: history, | ||
future: future | ||
}); | ||
@@ -409,3 +708,3 @@ } | ||
*/ | ||
function HistoryRouter(_ref3) { | ||
function HistoryRouter(_ref6) { | ||
let { | ||
@@ -416,3 +715,3 @@ basename, | ||
history | ||
} = _ref3; | ||
} = _ref6; | ||
let [state, setStateImpl] = React.useState({ | ||
@@ -434,3 +733,4 @@ action: history.action, | ||
navigationType: state.action, | ||
navigator: history | ||
navigator: history, | ||
future: future | ||
}); | ||
@@ -444,5 +744,5 @@ } | ||
/** | ||
* 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 { | ||
@@ -456,5 +756,6 @@ onClick, | ||
to, | ||
preventScrollReset | ||
} = _ref4, | ||
rest = _objectWithoutPropertiesLoose(_ref4, _excluded); | ||
preventScrollReset, | ||
unstable_viewTransition | ||
} = _ref7, | ||
rest = _objectWithoutPropertiesLoose(_ref7, _excluded); | ||
let { | ||
@@ -496,3 +797,4 @@ basename | ||
preventScrollReset, | ||
relative | ||
relative, | ||
unstable_viewTransition | ||
}); | ||
@@ -520,5 +822,5 @@ function handleClick(event) { | ||
/** | ||
* 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 { | ||
@@ -531,5 +833,6 @@ "aria-current": ariaCurrentProp = "page", | ||
to, | ||
unstable_viewTransition, | ||
children | ||
} = _ref5, | ||
rest = _objectWithoutPropertiesLoose(_ref5, _excluded2); | ||
} = _ref8, | ||
rest = _objectWithoutPropertiesLoose(_ref8, _excluded2); | ||
let path = useResolvedPath(to, { | ||
@@ -541,4 +844,9 @@ 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; | ||
@@ -552,11 +860,22 @@ let locationPathname = location.pathname; | ||
} | ||
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 { | ||
@@ -568,8 +887,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, { | ||
@@ -580,7 +896,5 @@ "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); | ||
}); | ||
@@ -596,14 +910,6 @@ if (process.env.NODE_ENV !== "production") { | ||
*/ | ||
const Form = /*#__PURE__*/React.forwardRef((props, ref) => { | ||
let submit = useSubmit(); | ||
return /*#__PURE__*/React.createElement(FormImpl, _extends({}, props, { | ||
submit: submit, | ||
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 { | ||
fetcherKey, | ||
navigate, | ||
reloadDocument, | ||
@@ -615,11 +921,12 @@ replace, | ||
onSubmit, | ||
submit, | ||
relative, | ||
preventScrollReset | ||
} = _ref6, | ||
props = _objectWithoutPropertiesLoose(_ref6, _excluded3); | ||
let formMethod = method.toLowerCase() === "get" ? "get" : "post"; | ||
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 => { | ||
@@ -632,7 +939,10 @@ onSubmit && onSubmit(event); | ||
submit(submitter || event.currentTarget, { | ||
fetcherKey, | ||
method: submitMethod, | ||
navigate, | ||
replace, | ||
state, | ||
relative, | ||
preventScrollReset | ||
preventScrollReset, | ||
unstable_viewTransition | ||
}); | ||
@@ -648,3 +958,3 @@ }; | ||
if (process.env.NODE_ENV !== "production") { | ||
FormImpl.displayName = "FormImpl"; | ||
Form.displayName = "Form"; | ||
} | ||
@@ -655,7 +965,7 @@ /** | ||
*/ | ||
function ScrollRestoration(_ref7) { | ||
function ScrollRestoration(_ref10) { | ||
let { | ||
getKey, | ||
storageKey | ||
} = _ref7; | ||
} = _ref10; | ||
useScrollRestoration({ | ||
@@ -680,8 +990,11 @@ getKey, | ||
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) { | ||
@@ -700,2 +1013,3 @@ return hookName + " must be used within a data router. See https://reactrouter.com/routers/picking-a-router."; | ||
} | ||
// External hooks | ||
/** | ||
@@ -712,3 +1026,4 @@ * Handles the click behavior for router `<Link>` components. This is useful if | ||
preventScrollReset, | ||
relative | ||
relative, | ||
unstable_viewTransition | ||
} = _temp === void 0 ? {} : _temp; | ||
@@ -730,6 +1045,7 @@ let navigate = useNavigate(); | ||
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]); | ||
} | ||
@@ -741,3 +1057,3 @@ /** | ||
function useSearchParams(defaultInit) { | ||
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\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)); | ||
@@ -764,2 +1080,4 @@ let hasSetSearchParamsRef = React.useRef(false); | ||
} | ||
let fetcherId = 0; | ||
let getUniqueFetcherId = () => "__" + String(++fetcherId) + "__"; | ||
/** | ||
@@ -789,46 +1107,28 @@ * Returns a function that may be used to programmatically submit a form (or | ||
} = getFormSubmissionInfo(target, basename); | ||
router.navigate(options.action || action, { | ||
preventScrollReset: options.preventScrollReset, | ||
formData, | ||
body, | ||
formMethod: options.method || method, | ||
formEncType: options.encType || encType, | ||
replace: options.replace, | ||
state: options.state, | ||
fromRouteId: currentRouteId | ||
}); | ||
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(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 | ||
}); | ||
} | ||
}, [router, basename, currentRouteId]); | ||
} | ||
/** | ||
* Returns the implementation for fetcher.submit | ||
*/ | ||
function useSubmitFetcher(fetcherKey, fetcherRouteId) { | ||
let { | ||
router | ||
} = useDataRouterContext(DataRouterHook.UseSubmitFetcher); | ||
let { | ||
basename | ||
} = React.useContext(UNSAFE_NavigationContext); | ||
return React.useCallback(function (target, options) { | ||
if (options === void 0) { | ||
options = {}; | ||
} | ||
validateClientSideSubmission(); | ||
let { | ||
action, | ||
method, | ||
encType, | ||
formData, | ||
body | ||
} = getFormSubmissionInfo(target, basename); | ||
!(fetcherRouteId != null) ? process.env.NODE_ENV !== "production" ? UNSAFE_invariant(false, "No routeId available for useFetcher()") : UNSAFE_invariant(false) : void 0; | ||
router.fetch(fetcherKey, fetcherRouteId, options.action || action, { | ||
preventScrollReset: options.preventScrollReset, | ||
formData, | ||
body, | ||
formMethod: options.method || method, | ||
formEncType: options.encType || encType | ||
}); | ||
}, [router, basename, fetcherKey, fetcherRouteId]); | ||
} | ||
// v7: Eventually we should deprecate this entirely in favor of using the | ||
@@ -851,19 +1151,15 @@ // router method directly? | ||
})); | ||
// 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"); | ||
@@ -885,16 +1181,3 @@ path.search = params.toString() ? "?" + params.toString() : ""; | ||
} | ||
function createFetcherForm(fetcherKey, routeId) { | ||
let FetcherForm = /*#__PURE__*/React.forwardRef((props, ref) => { | ||
let submit = useSubmitFetcher(fetcherKey, routeId); | ||
return /*#__PURE__*/React.createElement(FormImpl, _extends({}, props, { | ||
ref: ref, | ||
submit: submit | ||
})); | ||
}); | ||
if (process.env.NODE_ENV !== "production") { | ||
FetcherForm.displayName = "fetcher.Form"; | ||
} | ||
return FetcherForm; | ||
} | ||
let fetcherId = 0; | ||
// TODO: (v7) Change the useFetcher generic default from `any` to `unknown` | ||
/** | ||
@@ -904,40 +1187,73 @@ * Interacts with route loaders and actions without causing a navigation. Great | ||
*/ | ||
function useFetcher() { | ||
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; | ||
let routeId = (_route$matches = route.matches[route.matches.length - 1]) == null ? void 0 : _route$matches.route.id; | ||
!(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; | ||
let [fetcherKey] = React.useState(() => String(++fetcherId)); | ||
let [Form] = React.useState(() => { | ||
!routeId ? process.env.NODE_ENV !== "production" ? UNSAFE_invariant(false, "No routeId available for fetcher.Form()") : UNSAFE_invariant(false) : void 0; | ||
return createFetcherForm(fetcherKey, routeId); | ||
}); | ||
let [load] = React.useState(() => href => { | ||
!router ? process.env.NODE_ENV !== "production" ? UNSAFE_invariant(false, "No router available for fetcher.load()") : UNSAFE_invariant(false) : void 0; | ||
!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); | ||
}); | ||
let submit = useSubmitFetcher(fetcherKey, routeId); | ||
let fetcher = router.getFetcher(fetcherKey); | ||
let fetcherWithComponents = React.useMemo(() => _extends({ | ||
Form, | ||
submit, | ||
load | ||
}, fetcher), [fetcher, Form, submit, load]); | ||
// 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(() => { | ||
// Is this busted when the React team gets real weird and calls effects | ||
// twice on mount? We really just need to garbage collect here when this | ||
// fetcher is no longer around. | ||
router.getFetcher(fetcherKey); | ||
return () => { | ||
if (!router) { | ||
console.warn("No router available to clean up from useFetcher()"); | ||
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; | ||
@@ -951,3 +1267,8 @@ } | ||
let state = useDataRouterState(DataRouterStateHook.UseFetchers); | ||
return [...state.fetchers.values()]; | ||
return Array.from(state.fetchers.entries()).map(_ref11 => { | ||
let [key, fetcher] = _ref11; | ||
return _extends({}, fetcher, { | ||
key | ||
}); | ||
}); | ||
} | ||
@@ -959,7 +1280,7 @@ const SCROLL_RESTORATION_STORAGE_KEY = "react-router-scroll-positions"; | ||
*/ | ||
function useScrollRestoration(_temp3) { | ||
function useScrollRestoration(_temp4) { | ||
let { | ||
getKey, | ||
storageKey | ||
} = _temp3 === void 0 ? {} : _temp3; | ||
} = _temp4 === void 0 ? {} : _temp4; | ||
let { | ||
@@ -991,3 +1312,7 @@ router | ||
} | ||
sessionStorage.setItem(storageKey || SCROLL_RESTORATION_STORAGE_KEY, JSON.stringify(savedScrollPositions)); | ||
try { | ||
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"; | ||
@@ -1099,8 +1424,8 @@ }, [storageKey, getKey, navigation.state, location, matches])); | ||
*/ | ||
function usePrompt(_ref8) { | ||
function usePrompt(_ref12) { | ||
let { | ||
when, | ||
message | ||
} = _ref8; | ||
let blocker = unstable_useBlocker(when); | ||
} = _ref12; | ||
let blocker = useBlocker(when); | ||
React.useEffect(() => { | ||
@@ -1110,3 +1435,6 @@ if (blocker.state === "blocked") { | ||
if (proceed) { | ||
blocker.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 { | ||
@@ -1123,5 +1451,45 @@ blocker.reset(); | ||
} | ||
/** | ||
* 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 | ||
export { BrowserRouter, Form, HashRouter, Link, NavLink, ScrollRestoration, useScrollRestoration as UNSAFE_useScrollRestoration, createBrowserRouter, createHashRouter, createSearchParams, HistoryRouter as unstable_HistoryRouter, usePrompt as unstable_usePrompt, useBeforeUnload, useFetcher, useFetchers, useFormAction, useLinkClickHandler, useSearchParams, useSubmit }; | ||
export { BrowserRouter, Form, HashRouter, Link, NavLink, RouterProvider, ScrollRestoration, FetchersContext as UNSAFE_FetchersContext, ViewTransitionContext as UNSAFE_ViewTransitionContext, useScrollRestoration as UNSAFE_useScrollRestoration, createBrowserRouter, createHashRouter, createSearchParams, HistoryRouter as unstable_HistoryRouter, usePrompt as unstable_usePrompt, useViewTransitionState as unstable_useViewTransitionState, useBeforeUnload, useFetcher, useFetchers, useFormAction, useLinkClickHandler, useSearchParams, useSubmit }; | ||
//# sourceMappingURL=index.js.map |
/** | ||
* React Router DOM v0.0.0-experimental-f728258d | ||
* React Router DOM v0.0.0-experimental-f7aa35148 | ||
* | ||
@@ -4,0 +4,0 @@ * Copyright (c) Remix Software Inc. |
/** | ||
* React Router DOM v0.0.0-experimental-f728258d | ||
* React Router DOM v0.0.0-experimental-f7aa35148 | ||
* | ||
@@ -12,5 +12,7 @@ * Copyright (c) Remix Software Inc. | ||
import * as React from 'react'; | ||
import { UNSAFE_mapRouteProperties, Router, UNSAFE_NavigationContext, useHref, useResolvedPath, useLocation, UNSAFE_DataRouterStateContext, useNavigate, createPath, UNSAFE_useRouteId, UNSAFE_RouteContext, useMatches, useNavigation, unstable_useBlocker, UNSAFE_DataRouterContext } from 'react-router'; | ||
export { AbortedDeferredError, Await, MemoryRouter, Navigate, NavigationType, Outlet, Route, Router, RouterProvider, Routes, UNSAFE_DataRouterContext, UNSAFE_DataRouterStateContext, UNSAFE_LocationContext, UNSAFE_NavigationContext, UNSAFE_RouteContext, UNSAFE_useRouteId, createMemoryRouter, createPath, createRoutesFromChildren, createRoutesFromElements, defer, generatePath, isRouteErrorResponse, json, matchPath, matchRoutes, parsePath, redirect, renderMatches, resolvePath, unstable_useBlocker, useActionData, useAsyncError, useAsyncValue, useHref, useInRouterContext, useLoaderData, useLocation, useMatch, useMatches, useNavigate, useNavigation, useNavigationType, useOutlet, useOutletContext, useParams, useResolvedPath, useRevalidator, useRouteError, useRouteLoaderData, useRoutes } from 'react-router'; | ||
import { stripBasename, UNSAFE_warning, createRouter, createBrowserHistory, createHashHistory, ErrorResponse, UNSAFE_invariant, joinPaths } from '@remix-run/router'; | ||
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 } 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'; | ||
export { UNSAFE_ErrorResponseImpl } from '@remix-run/router'; | ||
@@ -106,2 +108,15 @@ const defaultMethod = "get"; | ||
} | ||
/** | ||
* Submit options shared by both navigations and fetchers | ||
*/ | ||
/** | ||
* Submit options available to fetchers | ||
*/ | ||
/** | ||
* Submit options available to navigations | ||
*/ | ||
const supportedFormEncTypes = new Set(["application/x-www-form-urlencoded", "multipart/form-data", "text/plain"]); | ||
@@ -196,2 +211,18 @@ function getFormEncType(encType) { | ||
// 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 | ||
} | ||
//////////////////////////////////////////////////////////////////////////////// | ||
@@ -212,3 +243,6 @@ //#region Routers | ||
routes, | ||
mapRouteProperties: UNSAFE_mapRouteProperties | ||
mapRouteProperties: UNSAFE_mapRouteProperties, | ||
unstable_dataStrategy: opts?.unstable_dataStrategy, | ||
unstable_patchRoutesOnMiss: opts?.unstable_patchRoutesOnMiss, | ||
window: opts?.window | ||
}).initialize(); | ||
@@ -228,3 +262,6 @@ } | ||
routes, | ||
mapRouteProperties: UNSAFE_mapRouteProperties | ||
mapRouteProperties: UNSAFE_mapRouteProperties, | ||
unstable_dataStrategy: opts?.unstable_dataStrategy, | ||
unstable_patchRoutesOnMiss: opts?.unstable_patchRoutesOnMiss, | ||
window: opts?.window | ||
}).initialize(); | ||
@@ -250,3 +287,3 @@ } | ||
if (val && val.__type === "RouteErrorResponse") { | ||
serialized[key] = new ErrorResponse(val.status, val.statusText, val.data, val.internal === true); | ||
serialized[key] = new UNSAFE_ErrorResponseImpl(val.status, val.statusText, val.data, val.internal === true); | ||
} else if (val && val.__type === "Error") { | ||
@@ -286,2 +323,21 @@ // Attempt to reconstruct the right type of Error (i.e., ReferenceError) | ||
//////////////////////////////////////////////////////////////////////////////// | ||
//#region Contexts | ||
//////////////////////////////////////////////////////////////////////////////// | ||
const ViewTransitionContext = /*#__PURE__*/React.createContext({ | ||
isTransitioning: false | ||
}); | ||
{ | ||
ViewTransitionContext.displayName = "ViewTransition"; | ||
} | ||
// TODO: (v7) Change the useFetcher data from `any` to `unknown` | ||
const FetchersContext = /*#__PURE__*/React.createContext(new Map()); | ||
{ | ||
FetchersContext.displayName = "Fetchers"; | ||
} | ||
//#endregion | ||
//////////////////////////////////////////////////////////////////////////////// | ||
//#region Components | ||
@@ -313,3 +369,282 @@ //////////////////////////////////////////////////////////////////////////////// | ||
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 { | ||
status = "pending"; | ||
// @ts-expect-error - no initializer | ||
// @ts-expect-error - no initializer | ||
constructor() { | ||
this.promise = new Promise((resolve, reject) => { | ||
this.resolve = value => { | ||
if (this.status === "pending") { | ||
this.status = "resolved"; | ||
resolve(value); | ||
} | ||
}; | ||
this.reject = reason => { | ||
if (this.status === "pending") { | ||
this.status = "rejected"; | ||
reject(reason); | ||
} | ||
}; | ||
}); | ||
} | ||
} | ||
/** | ||
* Given a Remix Router instance, render the appropriate UI | ||
*/ | ||
function RouterProvider({ | ||
fallbackElement, | ||
router, | ||
future | ||
}) { | ||
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, { | ||
deletedFetchers, | ||
unstable_flushSync: flushSync, | ||
unstable_viewTransitionOpts: viewTransitionOpts | ||
}) => { | ||
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(() => { | ||
UNSAFE_warning(fallbackElement == null || !router.future.v7_partialHydration, "`<RouterProvider fallbackElement>` is deprecated when using " + "`v7_partialHydration`, use a `HydrateFallback` component instead") ; | ||
// 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?.preventScrollReset | ||
}), | ||
replace: (to, state, opts) => router.navigate(to, { | ||
replace: true, | ||
state, | ||
preventScrollReset: opts?.preventScrollReset | ||
}) | ||
}; | ||
}, [router]); | ||
let basename = router.basename || "/"; | ||
let dataRouterContext = React.useMemo(() => ({ | ||
router, | ||
navigator, | ||
static: false, | ||
basename | ||
}), [router, navigator, basename]); | ||
let routerFuture = React.useMemo(() => ({ | ||
v7_relativeSplatPath: router.future.v7_relativeSplatPath | ||
}), [router.future.v7_relativeSplatPath]); | ||
// 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: routerFuture | ||
}, state.initialized || router.future.v7_partialHydration ? /*#__PURE__*/React.createElement(MemoizedDataRoutes, { | ||
routes: router.routes, | ||
future: router.future, | ||
state: state | ||
}) : fallbackElement))))), null); | ||
} | ||
// Memoize to avoid re-renders when updating `ViewTransitionContext` | ||
const MemoizedDataRoutes = /*#__PURE__*/React.memo(DataRoutes); | ||
function DataRoutes({ | ||
routes, | ||
future, | ||
state | ||
}) { | ||
return UNSAFE_useRoutesImpl(routes, undefined, state, future); | ||
} | ||
/** | ||
* A `<Router>` for use in web browsers. Provides the cleanest URLs. | ||
@@ -347,3 +682,4 @@ */ | ||
navigationType: state.action, | ||
navigator: history | ||
navigator: history, | ||
future: future | ||
}); | ||
@@ -385,3 +721,4 @@ } | ||
navigationType: state.action, | ||
navigator: history | ||
navigator: history, | ||
future: future | ||
}); | ||
@@ -417,3 +754,4 @@ } | ||
navigationType: state.action, | ||
navigator: history | ||
navigator: history, | ||
future: future | ||
}); | ||
@@ -428,3 +766,3 @@ } | ||
/** | ||
* The public API for rendering a history-aware <a>. | ||
* The public API for rendering a history-aware `<a>`. | ||
*/ | ||
@@ -440,2 +778,3 @@ const Link = /*#__PURE__*/React.forwardRef(function LinkWithRef({ | ||
preventScrollReset, | ||
unstable_viewTransition, | ||
...rest | ||
@@ -482,3 +821,4 @@ }, ref) { | ||
preventScrollReset, | ||
relative | ||
relative, | ||
unstable_viewTransition | ||
}); | ||
@@ -506,3 +846,3 @@ function handleClick(event) { | ||
/** | ||
* A <Link> wrapper that knows if it's "active" or not. | ||
* A `<Link>` wrapper that knows if it's "active" or not. | ||
*/ | ||
@@ -516,2 +856,3 @@ const NavLink = /*#__PURE__*/React.forwardRef(function NavLinkWithRef({ | ||
to, | ||
unstable_viewTransition, | ||
children, | ||
@@ -526,4 +867,9 @@ ...rest | ||
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; | ||
@@ -537,11 +883,23 @@ let locationPathname = location.pathname; | ||
} | ||
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 { | ||
@@ -553,8 +911,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, Object.assign({}, rest, { | ||
@@ -565,7 +920,5 @@ "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); | ||
}); | ||
@@ -575,3 +928,16 @@ { | ||
} | ||
/** | ||
* Form props shared by navigations and fetchers | ||
*/ | ||
/** | ||
* Form props available to fetchers | ||
*/ | ||
/** | ||
* Form props available to navigations | ||
*/ | ||
/** | ||
* A `@remix-run/router`-aware `<form>`. It behaves like a normal form except | ||
@@ -582,13 +948,5 @@ * that the interaction with the server is with `fetch` instead of new document | ||
*/ | ||
const Form = /*#__PURE__*/React.forwardRef((props, ref) => { | ||
let submit = useSubmit(); | ||
return /*#__PURE__*/React.createElement(FormImpl, Object.assign({}, props, { | ||
submit: submit, | ||
ref: ref | ||
})); | ||
}); | ||
{ | ||
Form.displayName = "Form"; | ||
} | ||
const FormImpl = /*#__PURE__*/React.forwardRef(({ | ||
const Form = /*#__PURE__*/React.forwardRef(({ | ||
fetcherKey, | ||
navigate, | ||
reloadDocument, | ||
@@ -600,11 +958,12 @@ replace, | ||
onSubmit, | ||
submit, | ||
relative, | ||
preventScrollReset, | ||
unstable_viewTransition, | ||
...props | ||
}, forwardedRef) => { | ||
let formMethod = _method.toLowerCase() === "get" ? "get" : "post"; | ||
let submit = useSubmit(); | ||
let formAction = useFormAction(action, { | ||
relative | ||
}); | ||
let formMethod = _method.toLowerCase() === "get" ? "get" : "post"; | ||
let submitHandler = event => { | ||
@@ -617,7 +976,10 @@ onSubmit && onSubmit(event); | ||
submit(submitter || event.currentTarget, { | ||
fetcherKey, | ||
method: submitMethod, | ||
navigate, | ||
replace, | ||
state, | ||
relative, | ||
preventScrollReset | ||
preventScrollReset, | ||
unstable_viewTransition | ||
}); | ||
@@ -633,3 +995,3 @@ }; | ||
{ | ||
FormImpl.displayName = "FormImpl"; | ||
Form.displayName = "Form"; | ||
} | ||
@@ -658,4 +1020,3 @@ /** | ||
//////////////////////////////////////////////////////////////////////////////// | ||
var DataRouterHook; | ||
(function (DataRouterHook) { | ||
var DataRouterHook = /*#__PURE__*/function (DataRouterHook) { | ||
DataRouterHook["UseScrollRestoration"] = "useScrollRestoration"; | ||
@@ -665,8 +1026,11 @@ DataRouterHook["UseSubmit"] = "useSubmit"; | ||
DataRouterHook["UseFetcher"] = "useFetcher"; | ||
})(DataRouterHook || (DataRouterHook = {})); | ||
var DataRouterStateHook; | ||
(function (DataRouterStateHook) { | ||
DataRouterHook["useViewTransitionState"] = "useViewTransitionState"; | ||
return DataRouterHook; | ||
}(DataRouterHook || {}); | ||
var DataRouterStateHook = /*#__PURE__*/function (DataRouterStateHook) { | ||
DataRouterStateHook["UseFetcher"] = "useFetcher"; | ||
DataRouterStateHook["UseFetchers"] = "useFetchers"; | ||
DataRouterStateHook["UseScrollRestoration"] = "useScrollRestoration"; | ||
})(DataRouterStateHook || (DataRouterStateHook = {})); | ||
return DataRouterStateHook; | ||
}(DataRouterStateHook || {}); // Internal hooks | ||
function getDataRouterConsoleError(hookName) { | ||
@@ -686,2 +1050,4 @@ return `${hookName} must be used within a data router. See https://reactrouter.com/routers/picking-a-router.`; | ||
// External hooks | ||
/** | ||
@@ -697,3 +1063,4 @@ * Handles the click behavior for router `<Link>` components. This is useful if | ||
preventScrollReset, | ||
relative | ||
relative, | ||
unstable_viewTransition | ||
} = {}) { | ||
@@ -716,6 +1083,7 @@ let navigate = useNavigate(); | ||
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]); | ||
} | ||
@@ -728,3 +1096,3 @@ | ||
function useSearchParams(defaultInit) { | ||
UNSAFE_warning(typeof URLSearchParams !== "undefined", `You cannot use the \`useSearchParams\` hook in a browser that does not ` + `support the URLSearchParams API. If you need to support Internet ` + `Explorer 11, we recommend you load a polyfill such as ` + `https://github.com/ungap/url-search-params\n\n` + `If you're unsure how to load polyfills, we recommend you check out ` + `https://polyfill.io/v3/ which provides some recommendations about how ` + `to load polyfills only for users that need them, instead of for every ` + `user.`) ; | ||
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.`) ; | ||
let defaultSearchParamsRef = React.useRef(createSearchParams(defaultInit)); | ||
@@ -760,2 +1128,4 @@ let hasSetSearchParamsRef = React.useRef(false); | ||
} | ||
let fetcherId = 0; | ||
let getUniqueFetcherId = () => `__${String(++fetcherId)}__`; | ||
@@ -783,45 +1153,29 @@ /** | ||
} = getFormSubmissionInfo(target, basename); | ||
router.navigate(options.action || action, { | ||
preventScrollReset: options.preventScrollReset, | ||
formData, | ||
body, | ||
formMethod: options.method || method, | ||
formEncType: options.encType || encType, | ||
replace: options.replace, | ||
state: options.state, | ||
fromRouteId: currentRouteId | ||
}); | ||
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(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 | ||
}); | ||
} | ||
}, [router, basename, currentRouteId]); | ||
} | ||
/** | ||
* Returns the implementation for fetcher.submit | ||
*/ | ||
function useSubmitFetcher(fetcherKey, fetcherRouteId) { | ||
let { | ||
router | ||
} = useDataRouterContext(DataRouterHook.UseSubmitFetcher); | ||
let { | ||
basename | ||
} = React.useContext(UNSAFE_NavigationContext); | ||
return React.useCallback((target, options = {}) => { | ||
validateClientSideSubmission(); | ||
let { | ||
action, | ||
method, | ||
encType, | ||
formData, | ||
body | ||
} = getFormSubmissionInfo(target, basename); | ||
!(fetcherRouteId != null) ? UNSAFE_invariant(false, "No routeId available for useFetcher()") : void 0; | ||
router.fetch(fetcherKey, fetcherRouteId, options.action || action, { | ||
preventScrollReset: options.preventScrollReset, | ||
formData, | ||
body, | ||
formMethod: options.method || method, | ||
formEncType: options.encType || encType | ||
}); | ||
}, [router, basename, fetcherKey, fetcherRouteId]); | ||
} | ||
// v7: Eventually we should deprecate this entirely in favor of using the | ||
@@ -846,20 +1200,16 @@ // router method directly? | ||
// 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"); | ||
@@ -882,16 +1232,3 @@ path.search = params.toString() ? `?${params.toString()}` : ""; | ||
} | ||
function createFetcherForm(fetcherKey, routeId) { | ||
let FetcherForm = /*#__PURE__*/React.forwardRef((props, ref) => { | ||
let submit = useSubmitFetcher(fetcherKey, routeId); | ||
return /*#__PURE__*/React.createElement(FormImpl, Object.assign({}, props, { | ||
ref: ref, | ||
submit: submit | ||
})); | ||
}); | ||
{ | ||
FetcherForm.displayName = "fetcher.Form"; | ||
} | ||
return FetcherForm; | ||
} | ||
let fetcherId = 0; | ||
// TODO: (v7) Change the useFetcher generic default from `any` to `unknown` | ||
/** | ||
@@ -901,40 +1238,76 @@ * Interacts with route loaders and actions without causing a navigation. Great | ||
*/ | ||
function useFetcher() { | ||
function useFetcher({ | ||
key | ||
} = {}) { | ||
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.length - 1]?.route.id; | ||
!fetcherData ? UNSAFE_invariant(false, `useFetcher must be used inside a FetchersContext`) : void 0; | ||
!route ? UNSAFE_invariant(false, `useFetcher must be used inside a RouteContext`) : void 0; | ||
let routeId = route.matches[route.matches.length - 1]?.route.id; | ||
!(routeId != null) ? UNSAFE_invariant(false, `useFetcher can only be used on routes that contain a unique "id"`) : void 0; | ||
let [fetcherKey] = React.useState(() => String(++fetcherId)); | ||
let [Form] = React.useState(() => { | ||
!routeId ? UNSAFE_invariant(false, `No routeId available for fetcher.Form()`) : void 0; | ||
return createFetcherForm(fetcherKey, routeId); | ||
}); | ||
let [load] = React.useState(() => href => { | ||
!router ? UNSAFE_invariant(false, "No router available for fetcher.load()") : void 0; | ||
!routeId ? UNSAFE_invariant(false, "No routeId available for fetcher.load()") : void 0; | ||
router.fetch(fetcherKey, routeId, href); | ||
}); | ||
let submit = useSubmitFetcher(fetcherKey, routeId); | ||
let fetcher = router.getFetcher(fetcherKey); | ||
let fetcherWithComponents = React.useMemo(() => ({ | ||
Form, | ||
submit, | ||
load, | ||
...fetcher | ||
}), [fetcher, Form, submit, load]); | ||
// 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(() => { | ||
// Is this busted when the React team gets real weird and calls effects | ||
// twice on mount? We really just need to garbage collect here when this | ||
// fetcher is no longer around. | ||
router.getFetcher(fetcherKey); | ||
return () => { | ||
if (!router) { | ||
console.warn(`No router available to clean up from useFetcher()`); | ||
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 ? UNSAFE_invariant(false, "No routeId available for fetcher.load()") : void 0; | ||
router.fetch(fetcherKey, routeId, href, opts); | ||
}, [fetcherKey, routeId, router]); | ||
let submitImpl = useSubmit(); | ||
let submit = React.useCallback((target, opts) => { | ||
submitImpl(target, { | ||
...opts, | ||
navigate: false, | ||
fetcherKey | ||
}); | ||
}, [fetcherKey, submitImpl]); | ||
let FetcherForm = React.useMemo(() => { | ||
let FetcherForm = /*#__PURE__*/React.forwardRef((props, ref) => { | ||
return /*#__PURE__*/React.createElement(Form, Object.assign({}, props, { | ||
navigate: false, | ||
fetcherKey: fetcherKey, | ||
ref: ref | ||
})); | ||
}); | ||
{ | ||
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(() => ({ | ||
Form: FetcherForm, | ||
submit, | ||
load, | ||
...fetcher, | ||
data | ||
}), [FetcherForm, submit, load, fetcher, data]); | ||
return fetcherWithComponents; | ||
@@ -949,3 +1322,6 @@ } | ||
let state = useDataRouterState(DataRouterStateHook.UseFetchers); | ||
return [...state.fetchers.values()]; | ||
return Array.from(state.fetchers.entries()).map(([key, fetcher]) => ({ | ||
...fetcher, | ||
key | ||
})); | ||
} | ||
@@ -990,3 +1366,7 @@ const SCROLL_RESTORATION_STORAGE_KEY = "react-router-scroll-positions"; | ||
} | ||
sessionStorage.setItem(storageKey || SCROLL_RESTORATION_STORAGE_KEY, JSON.stringify(savedScrollPositions)); | ||
try { | ||
sessionStorage.setItem(storageKey || SCROLL_RESTORATION_STORAGE_KEY, JSON.stringify(savedScrollPositions)); | ||
} catch (error) { | ||
UNSAFE_warning(false, `Failed to save scroll positions in sessionStorage, <ScrollRestoration /> will not work properly (${error}).`) ; | ||
} | ||
window.history.scrollRestoration = "auto"; | ||
@@ -1114,3 +1494,3 @@ }, [storageKey, getKey, navigation.state, location, matches])); | ||
}) { | ||
let blocker = unstable_useBlocker(when); | ||
let blocker = useBlocker(when); | ||
React.useEffect(() => { | ||
@@ -1120,3 +1500,6 @@ if (blocker.state === "blocked") { | ||
if (proceed) { | ||
blocker.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 { | ||
@@ -1134,5 +1517,44 @@ blocker.reset(); | ||
/** | ||
* 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 = {}) { | ||
let vtContext = React.useContext(ViewTransitionContext); | ||
!(vtContext != null) ? UNSAFE_invariant(false, "`unstable_useViewTransitionState` must be used within `react-router-dom`'s `RouterProvider`. " + "Did you accidentally import `RouterProvider` from `react-router`?") : 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 | ||
export { BrowserRouter, Form, HashRouter, Link, NavLink, ScrollRestoration, useScrollRestoration as UNSAFE_useScrollRestoration, createBrowserRouter, createHashRouter, createSearchParams, HistoryRouter as unstable_HistoryRouter, usePrompt as unstable_usePrompt, useBeforeUnload, useFetcher, useFetchers, useFormAction, useLinkClickHandler, useSearchParams, useSubmit }; | ||
export { BrowserRouter, Form, HashRouter, Link, NavLink, RouterProvider, ScrollRestoration, FetchersContext as UNSAFE_FetchersContext, ViewTransitionContext as UNSAFE_ViewTransitionContext, useScrollRestoration as UNSAFE_useScrollRestoration, createBrowserRouter, createHashRouter, createSearchParams, HistoryRouter as unstable_HistoryRouter, usePrompt as unstable_usePrompt, useViewTransitionState as unstable_useViewTransitionState, useBeforeUnload, useFetcher, useFetchers, useFormAction, useLinkClickHandler, useSearchParams, useSubmit }; | ||
//# sourceMappingURL=react-router-dom.development.js.map |
/** | ||
* React Router DOM v0.0.0-experimental-f728258d | ||
* React Router DOM v0.0.0-experimental-f7aa35148 | ||
* | ||
@@ -11,3 +11,3 @@ * Copyright (c) Remix Software Inc. | ||
*/ | ||
import*as e from"react";import{UNSAFE_mapRouteProperties as t,Router as r,UNSAFE_NavigationContext as n,useHref as o,useResolvedPath as a,useLocation as i,UNSAFE_DataRouterStateContext as s,useNavigate as u,createPath as l,UNSAFE_useRouteId as c,UNSAFE_RouteContext as f,useMatches as m,useNavigation as d,unstable_useBlocker as h,UNSAFE_DataRouterContext as p}from"react-router";export{AbortedDeferredError,Await,MemoryRouter,Navigate,NavigationType,Outlet,Route,Router,RouterProvider,Routes,UNSAFE_DataRouterContext,UNSAFE_DataRouterStateContext,UNSAFE_LocationContext,UNSAFE_NavigationContext,UNSAFE_RouteContext,UNSAFE_useRouteId,createMemoryRouter,createPath,createRoutesFromChildren,createRoutesFromElements,defer,generatePath,isRouteErrorResponse,json,matchPath,matchRoutes,parsePath,redirect,renderMatches,resolvePath,unstable_useBlocker,useActionData,useAsyncError,useAsyncValue,useHref,useInRouterContext,useLoaderData,useLocation,useMatch,useMatches,useNavigate,useNavigation,useNavigationType,useOutlet,useOutletContext,useParams,useResolvedPath,useRevalidator,useRouteError,useRouteLoaderData,useRoutes}from"react-router";import{stripBasename as w,createRouter as y,createBrowserHistory as g,createHashHistory as b,ErrorResponse as v,UNSAFE_invariant as R,joinPaths as S}from"@remix-run/router";const E="application/x-www-form-urlencoded";function C(e){return null!=e&&"string"==typeof e.tagName}function x(e=""){return new URLSearchParams("string"==typeof e||Array.isArray(e)||e instanceof URLSearchParams?e:Object.keys(e).reduce(((t,r)=>{let n=e[r];return t.concat(Array.isArray(n)?n.map((e=>[r,e])):[[r,n]])}),[]))}let A=null;const L=new Set(["application/x-www-form-urlencoded","multipart/form-data","text/plain"]);function U(e){return null==e||L.has(e)?e:null}function _(e,t){let r,n,o,a,i;if(C(s=e)&&"form"===s.tagName.toLowerCase()){let i=e.getAttribute("action");n=i?w(i,t):null,r=e.getAttribute("method")||"get",o=U(e.getAttribute("enctype"))||E,a=new FormData(e)}else if(function(e){return C(e)&&"button"===e.tagName.toLowerCase()}(e)||function(e){return C(e)&&"input"===e.tagName.toLowerCase()}(e)&&("submit"===e.type||"image"===e.type)){let i=e.form;if(null==i)throw new Error('Cannot submit a <button> or <input type="submit"> without a <form>');let s=e.getAttribute("formaction")||i.getAttribute("action");if(n=s?w(s,t):null,r=e.getAttribute("formmethod")||i.getAttribute("method")||"get",o=U(e.getAttribute("formenctype"))||U(i.getAttribute("enctype"))||E,a=new FormData(i,e),!function(){if(null===A)try{new FormData(document.createElement("form"),0),A=!1}catch(e){A=!0}return A}()){let{name:t,type:r,value:n}=e;if("image"===r){let e=t?`${t}.`:"";a.append(`${e}x`,"0"),a.append(`${e}y`,"0")}else t&&a.append(t,n)}}else{if(C(e))throw new Error('Cannot submit element that is not <form>, <button>, or <input type="submit|image">');r="get",n=null,o=E,i=e}var s;return a&&"text/plain"===o&&(i=a,a=void 0),{action:n,method:r.toLowerCase(),encType:o,formData:a,body:i}}function F(e,r){return y({basename:r?.basename,future:{...r?.future,v7_prependBasename:!0},history:g({window:r?.window}),hydrationData:r?.hydrationData||T(),routes:e,mapRouteProperties:t}).initialize()}function D(e,r){return y({basename:r?.basename,future:{...r?.future,v7_prependBasename:!0},history:b({window:r?.window}),hydrationData:r?.hydrationData||T(),routes:e,mapRouteProperties:t}).initialize()}function T(){let e=window?.__staticRouterHydrationData;return e&&e.errors&&(e={...e,errors:N(e.errors)}),e}function N(e){if(!e)return null;let t=Object.entries(e),r={};for(let[o,a]of t)if(a&&"RouteErrorResponse"===a.__type)r[o]=new v(a.status,a.statusText,a.data,!0===a.internal);else if(a&&"Error"===a.__type){if(a.__subType){let e=window[a.__subType];if("function"==typeof e)try{let t=new e(a.message);t.stack="",r[o]=t}catch(n){}}if(null==r[o]){let e=new Error(a.message);e.stack="",r[o]=e}}else r[o]=a;return r}const P=e.startTransition;function k({basename:t,children:n,future:o,window:a}){let i=e.useRef();null==i.current&&(i.current=g({window:a,v5Compat:!0}));let s=i.current,[u,l]=e.useState({action:s.action,location:s.location}),{v7_startTransition:c}=o||{},f=e.useCallback((e=>{c&&P?P((()=>l(e))):l(e)}),[l,c]);return e.useLayoutEffect((()=>s.listen(f)),[s,f]),e.createElement(r,{basename:t,children:n,location:u.location,navigationType:u.action,navigator:s})}function O({basename:t,children:n,future:o,window:a}){let i=e.useRef();null==i.current&&(i.current=b({window:a,v5Compat:!0}));let s=i.current,[u,l]=e.useState({action:s.action,location:s.location}),{v7_startTransition:c}=o||{},f=e.useCallback((e=>{c&&P?P((()=>l(e))):l(e)}),[l,c]);return e.useLayoutEffect((()=>s.listen(f)),[s,f]),e.createElement(r,{basename:t,children:n,location:u.location,navigationType:u.action,navigator:s})}function K({basename:t,children:n,future:o,history:a}){let[i,s]=e.useState({action:a.action,location:a.location}),{v7_startTransition:u}=o||{},l=e.useCallback((e=>{u&&P?P((()=>s(e))):s(e)}),[s,u]);return e.useLayoutEffect((()=>a.listen(l)),[a,l]),e.createElement(r,{basename:t,children:n,location:i.location,navigationType:i.action,navigator:a})}const j="undefined"!=typeof window&&void 0!==window.document&&void 0!==window.document.createElement,M=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i,I=e.forwardRef((function({onClick:t,relative:r,reloadDocument:a,replace:i,state:s,target:u,to:l,preventScrollReset:c,...f},m){let d,{basename:h}=e.useContext(n),p=!1;if("string"==typeof l&&M.test(l)&&(d=l,j))try{let e=new URL(window.location.href),t=l.startsWith("//")?new URL(e.protocol+l):new URL(l),r=w(t.pathname,h);t.origin===e.origin&&null!=r?l=r+t.search+t.hash:p=!0}catch(b){}let y=o(l,{relative:r}),g=q(l,{replace:i,state:s,target:u,preventScrollReset:c,relative:r});return e.createElement("a",Object.assign({},f,{href:d||y,onClick:p||a?t:function(e){t&&t(e),e.defaultPrevented||g(e)},ref:m,target:u}))})),B=e.forwardRef((function({"aria-current":t="page",caseSensitive:r=!1,className:o="",end:u=!1,style:l,to:c,children:f,...m},d){let h=a(c,{relative:m.relative}),p=i(),w=e.useContext(s),{navigator:y}=e.useContext(n),g=y.encodeLocation?y.encodeLocation(h).pathname:h.pathname,b=p.pathname,v=w&&w.navigation&&w.navigation.location?w.navigation.location.pathname:null;r||(b=b.toLowerCase(),v=v?v.toLowerCase():null,g=g.toLowerCase());let R,S=b===g||!u&&b.startsWith(g)&&"/"===b.charAt(g.length),E=null!=v&&(v===g||!u&&v.startsWith(g)&&"/"===v.charAt(g.length)),C=S?t:void 0;R="function"==typeof o?o({isActive:S,isPending:E}):[o,S?"active":null,E?"pending":null].filter(Boolean).join(" ");let x="function"==typeof l?l({isActive:S,isPending:E}):l;return e.createElement(I,Object.assign({},m,{"aria-current":C,className:R,ref:d,style:x,to:c}),"function"==typeof f?f({isActive:S,isPending:E}):f)})),z=e.forwardRef(((t,r)=>{let n=X();return e.createElement($,Object.assign({},t,{submit:n,ref:r}))})),$=e.forwardRef((({reloadDocument:t,replace:r,state:n,method:o="get",action:a,onSubmit:i,submit:s,relative:u,preventScrollReset:l,...c},f)=>{let m="get"===o.toLowerCase()?"get":"post",d=ee(a,{relative:u});return e.createElement("form",Object.assign({ref:f,method:m,action:d,onSubmit:t?i:e=>{if(i&&i(e),e.defaultPrevented)return;e.preventDefault();let t=e.nativeEvent.submitter,a=t?.getAttribute("formmethod")||o;s(t||e.currentTarget,{method:a,replace:r,state:n,relative:u,preventScrollReset:l})}},c))}));function H({getKey:e,storageKey:t}){return ae({getKey:e,storageKey:t}),null}var W,Y;function J(t){let r=e.useContext(p);return r||R(!1),r}function V(t){let r=e.useContext(s);return r||R(!1),r}function q(t,{target:r,replace:n,state:o,preventScrollReset:s,relative:c}={}){let f=u(),m=i(),d=a(t,{relative:c});return e.useCallback((e=>{if(function(e,t){return!(0!==e.button||t&&"_self"!==t||function(e){return!!(e.metaKey||e.altKey||e.ctrlKey||e.shiftKey)}(e))}(e,r)){e.preventDefault();let r=void 0!==n?n:l(m)===l(d);f(t,{replace:r,state:o,preventScrollReset:s,relative:c})}}),[m,f,d,n,o,r,t,s,c])}function G(t){let r=e.useRef(x(t)),n=e.useRef(!1),o=i(),a=e.useMemo((()=>function(e,t){let r=x(e);return t&&t.forEach(((e,n)=>{r.has(n)||t.getAll(n).forEach((e=>{r.append(n,e)}))})),r}(o.search,n.current?null:r.current)),[o.search]),s=u(),l=e.useCallback(((e,t)=>{const r=x("function"==typeof e?e(a):e);n.current=!0,s("?"+r,t)}),[s,a]);return[a,l]}function Q(){if("undefined"==typeof document)throw new Error("You are calling submit during the server render. Try calling submit within a `useEffect` or callback instead.")}function X(){let{router:t}=J(W.UseSubmit),{basename:r}=e.useContext(n),o=c();return e.useCallback(((e,n={})=>{Q();let{action:a,method:i,encType:s,formData:u,body:l}=_(e,r);t.navigate(n.action||a,{preventScrollReset:n.preventScrollReset,formData:u,body:l,formMethod:n.method||i,formEncType:n.encType||s,replace:n.replace,state:n.state,fromRouteId:o})}),[t,r,o])}function Z(t,r){let{router:o}=J(W.UseSubmitFetcher),{basename:a}=e.useContext(n);return e.useCallback(((e,n={})=>{Q();let{action:i,method:s,encType:u,formData:l,body:c}=_(e,a);null==r&&R(!1),o.fetch(t,r,n.action||i,{preventScrollReset:n.preventScrollReset,formData:l,body:c,formMethod:n.method||s,formEncType:n.encType||u})}),[o,a,t,r])}function ee(t,{relative:r}={}){let{basename:o}=e.useContext(n),s=e.useContext(f);s||R(!1);let[u]=s.matches.slice(-1),c={...a(t||".",{relative:r})},m=i();if(null==t&&(c.search=m.search,c.hash=m.hash,u.route.index)){let e=new URLSearchParams(c.search);e.delete("index"),c.search=e.toString()?`?${e.toString()}`:""}return t&&"."!==t||!u.route.index||(c.search=c.search?c.search.replace(/^\?/,"?index&"):"?index"),"/"!==o&&(c.pathname="/"===c.pathname?o:S([o,c.pathname])),l(c)}!function(e){e.UseScrollRestoration="useScrollRestoration",e.UseSubmit="useSubmit",e.UseSubmitFetcher="useSubmitFetcher",e.UseFetcher="useFetcher"}(W||(W={})),function(e){e.UseFetchers="useFetchers",e.UseScrollRestoration="useScrollRestoration"}(Y||(Y={}));let te=0;function re(){let{router:t}=J(W.UseFetcher),r=e.useContext(f);r||R(!1);let n=r.matches[r.matches.length-1]?.route.id;null==n&&R(!1);let[o]=e.useState((()=>String(++te))),[a]=e.useState((()=>(n||R(!1),function(t,r){return e.forwardRef(((n,o)=>{let a=Z(t,r);return e.createElement($,Object.assign({},n,{ref:o,submit:a}))}))}(o,n)))),[i]=e.useState((()=>e=>{t||R(!1),n||R(!1),t.fetch(o,n,e)})),s=Z(o,n),u=t.getFetcher(o),l=e.useMemo((()=>({Form:a,submit:s,load:i,...u})),[u,a,s,i]);return e.useEffect((()=>()=>{t?t.deleteFetcher(o):console.warn("No router available to clean up from useFetcher()")}),[t,o]),l}function ne(){return[...V(Y.UseFetchers).fetchers.values()]}let oe={};function ae({getKey:t,storageKey:r}={}){let{router:o}=J(W.UseScrollRestoration),{restoreScrollPosition:a,preventScrollReset:s}=V(Y.UseScrollRestoration),{basename:u}=e.useContext(n),l=i(),c=m(),f=d();e.useEffect((()=>(window.history.scrollRestoration="manual",()=>{window.history.scrollRestoration="auto"})),[]),function(t,r){let{capture:n}=r||{};e.useEffect((()=>{let e=null!=n?{capture:n}:void 0;return window.addEventListener("pagehide",t,e),()=>{window.removeEventListener("pagehide",t,e)}}),[t,n])}(e.useCallback((()=>{if("idle"===f.state){let e=(t?t(l,c):null)||l.key;oe[e]=window.scrollY}sessionStorage.setItem(r||"react-router-scroll-positions",JSON.stringify(oe)),window.history.scrollRestoration="auto"}),[r,t,f.state,l,c])),"undefined"!=typeof document&&(e.useLayoutEffect((()=>{try{let e=sessionStorage.getItem(r||"react-router-scroll-positions");e&&(oe=JSON.parse(e))}catch(e){}}),[r]),e.useLayoutEffect((()=>{let e=t&&"/"!==u?(e,r)=>t({...e,pathname:w(e.pathname,u)||e.pathname},r):t,r=o?.enableScrollRestoration(oe,(()=>window.scrollY),e);return()=>r&&r()}),[o,u,t]),e.useLayoutEffect((()=>{if(!1!==a)if("number"!=typeof a){if(l.hash){let e=document.getElementById(decodeURIComponent(l.hash.slice(1)));if(e)return void e.scrollIntoView()}!0!==s&&window.scrollTo(0,0)}else window.scrollTo(0,a)}),[l,a,s]))}function ie(t,r){let{capture:n}=r||{};e.useEffect((()=>{let e=null!=n?{capture:n}:void 0;return window.addEventListener("beforeunload",t,e),()=>{window.removeEventListener("beforeunload",t,e)}}),[t,n])}function se({when:t,message:r}){let n=h(t);e.useEffect((()=>{if("blocked"===n.state){window.confirm(r)?n.proceed():n.reset()}}),[n,r]),e.useEffect((()=>{"blocked"!==n.state||t||n.reset()}),[n,t])}export{k as BrowserRouter,z as Form,O as HashRouter,I as Link,B as NavLink,H as ScrollRestoration,ae as UNSAFE_useScrollRestoration,F as createBrowserRouter,D as createHashRouter,x as createSearchParams,K as unstable_HistoryRouter,se as unstable_usePrompt,ie as useBeforeUnload,re as useFetcher,ne as useFetchers,ee as useFormAction,q as useLinkClickHandler,G as useSearchParams,X as useSubmit}; | ||
import*as e from"react";import*as t from"react-dom";import{UNSAFE_mapRouteProperties as n,UNSAFE_DataRouterContext as r,UNSAFE_DataRouterStateContext as a,Router as o,UNSAFE_useRoutesImpl as i,UNSAFE_NavigationContext as s,useHref as u,useResolvedPath as l,useLocation as c,useNavigate as f,createPath as d,UNSAFE_useRouteId as m,UNSAFE_RouteContext as h,useMatches as p,useNavigation as w,useBlocker as v}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 as g,createRouter as y,createBrowserHistory as b,createHashHistory as S,UNSAFE_ErrorResponseImpl as R,UNSAFE_invariant as E,joinPaths as _,IDLE_FETCHER as T,matchPath as L}from"@remix-run/router";export{UNSAFE_ErrorResponseImpl}from"@remix-run/router";const x="application/x-www-form-urlencoded";function C(e){return null!=e&&"string"==typeof e.tagName}function A(e=""){return 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 F=null;const U=new Set(["application/x-www-form-urlencoded","multipart/form-data","text/plain"]);function k(e){return null==e||U.has(e)?e:null}function P(e,t){let n,r,a,o,i;if(C(s=e)&&"form"===s.tagName.toLowerCase()){let i=e.getAttribute("action");r=i?g(i,t):null,n=e.getAttribute("method")||"get",a=k(e.getAttribute("enctype"))||x,o=new FormData(e)}else if(function(e){return C(e)&&"button"===e.tagName.toLowerCase()}(e)||function(e){return C(e)&&"input"===e.tagName.toLowerCase()}(e)&&("submit"===e.type||"image"===e.type)){let i=e.form;if(null==i)throw new Error('Cannot submit a <button> or <input type="submit"> without a <form>');let s=e.getAttribute("formaction")||i.getAttribute("action");if(r=s?g(s,t):null,n=e.getAttribute("formmethod")||i.getAttribute("method")||"get",a=k(e.getAttribute("formenctype"))||k(i.getAttribute("enctype"))||x,o=new FormData(i,e),!function(){if(null===F)try{new FormData(document.createElement("form"),0),F=!1}catch(e){F=!0}return F}()){let{name:t,type:n,value:r}=e;if("image"===n){let e=t?`${t}.`:"";o.append(`${e}x`,"0"),o.append(`${e}y`,"0")}else t&&o.append(t,r)}}else{if(C(e))throw new Error('Cannot submit element that is not <form>, <button>, or <input type="submit|image">');n="get",r=null,a=x,i=e}var s;return o&&"text/plain"===a&&(i=o,o=void 0),{action:r,method:n.toLowerCase(),encType:a,formData:o,body:i}}try{window.__reactRouterVersion="0"}catch(be){}function N(e,t){return y({basename:t?.basename,future:{...t?.future,v7_prependBasename:!0},history:b({window:t?.window}),hydrationData:t?.hydrationData||M(),routes:e,mapRouteProperties:n,unstable_dataStrategy:t?.unstable_dataStrategy,unstable_patchRoutesOnMiss:t?.unstable_patchRoutesOnMiss,window:t?.window}).initialize()}function D(e,t){return y({basename:t?.basename,future:{...t?.future,v7_prependBasename:!0},history:S({window:t?.window}),hydrationData:t?.hydrationData||M(),routes:e,mapRouteProperties:n,unstable_dataStrategy:t?.unstable_dataStrategy,unstable_patchRoutesOnMiss:t?.unstable_patchRoutesOnMiss,window:t?.window}).initialize()}function M(){let e=window?.__staticRouterHydrationData;return e&&e.errors&&(e={...e,errors:O(e.errors)}),e}function O(e){if(!e)return null;let t=Object.entries(e),n={};for(let[r,a]of t)if(a&&"RouteErrorResponse"===a.__type)n[r]=new R(a.status,a.statusText,a.data,!0===a.internal);else if(a&&"Error"===a.__type){if(a.__subType){let e=window[a.__subType];if("function"==typeof e)try{let t=new e(a.message);t.stack="",n[r]=t}catch(be){}}if(null==n[r]){let e=new Error(a.message);e.stack="",n[r]=e}}else n[r]=a;return n}const K=e.createContext({isTransitioning:!1}),V=e.createContext(new Map),j=e.startTransition,I=t.flushSync,H=e.useId;function z(e){I?I(e):e()}class B{status="pending";constructor(){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 $({fallbackElement:t,router:n,future:i}){let[s,u]=e.useState(n.state),[l,c]=e.useState(),[f,d]=e.useState({isTransitioning:!1}),[m,h]=e.useState(),[p,w]=e.useState(),[v,g]=e.useState(),y=e.useRef(new Map),{v7_startTransition:b}=i||{},S=e.useCallback((e=>{b?function(e){j?j(e):e()}(e):e()}),[b]),R=e.useCallback(((e,{deletedFetchers:t,unstable_flushSync:r,unstable_viewTransitionOpts:a})=>{t.forEach((e=>y.current.delete(e))),e.fetchers.forEach(((e,t)=>{void 0!==e.data&&y.current.set(t,e.data)}));let o=null==n.window||null==n.window.document||"function"!=typeof n.window.document.startViewTransition;if(a&&!o){if(r){z((()=>{p&&(m&&m.resolve(),p.skipTransition()),d({isTransitioning:!0,flushSync:!0,currentLocation:a.currentLocation,nextLocation:a.nextLocation})}));let t=n.window.document.startViewTransition((()=>{z((()=>u(e)))}));return t.finished.finally((()=>{z((()=>{h(void 0),w(void 0),c(void 0),d({isTransitioning:!1})}))})),void z((()=>w(t)))}p?(m&&m.resolve(),p.skipTransition(),g({state:e,currentLocation:a.currentLocation,nextLocation:a.nextLocation})):(c(e),d({isTransitioning:!0,flushSync:!1,currentLocation:a.currentLocation,nextLocation:a.nextLocation}))}else r?z((()=>u(e))):S((()=>u(e)))}),[n.window,p,m,y,S]);e.useLayoutEffect((()=>n.subscribe(R)),[n,R]),e.useEffect((()=>{f.isTransitioning&&!f.flushSync&&h(new B)}),[f]),e.useEffect((()=>{if(m&&l&&n.window){let e=l,t=m.promise,r=n.window.document.startViewTransition((async()=>{S((()=>u(e))),await t}));r.finished.finally((()=>{h(void 0),w(void 0),c(void 0),d({isTransitioning:!1})})),w(r)}}),[S,l,m,n.window]),e.useEffect((()=>{m&&l&&s.location.key===l.location.key&&m.resolve()}),[m,p,s.location,l]),e.useEffect((()=>{!f.isTransitioning&&v&&(c(v.state),d({isTransitioning:!0,flushSync:!1,currentLocation:v.currentLocation,nextLocation:v.nextLocation}),g(void 0))}),[f.isTransitioning,v]),e.useEffect((()=>{}),[]);let E=e.useMemo((()=>({createHref:n.createHref,encodeLocation:n.encodeLocation,go:e=>n.navigate(e),push:(e,t,r)=>n.navigate(e,{state:t,preventScrollReset:r?.preventScrollReset}),replace:(e,t,r)=>n.navigate(e,{replace:!0,state:t,preventScrollReset:r?.preventScrollReset})})),[n]),_=n.basename||"/",T=e.useMemo((()=>({router:n,navigator:E,static:!1,basename:_})),[n,E,_]),L=e.useMemo((()=>({v7_relativeSplatPath:n.future.v7_relativeSplatPath})),[n.future.v7_relativeSplatPath]);return e.createElement(e.Fragment,null,e.createElement(r.Provider,{value:T},e.createElement(a.Provider,{value:s},e.createElement(V.Provider,{value:y.current},e.createElement(K.Provider,{value:f},e.createElement(o,{basename:_,location:s.location,navigationType:s.historyAction,navigator:E,future:L},s.initialized||n.future.v7_partialHydration?e.createElement(W,{routes:n.routes,future:n.future,state:s}):t))))),null)}const W=e.memo(Y);function Y({routes:e,future:t,state:n}){return i(e,void 0,n,t)}function J({basename:t,children:n,future:r,window:a}){let i=e.useRef();null==i.current&&(i.current=b({window:a,v5Compat:!0}));let s=i.current,[u,l]=e.useState({action:s.action,location:s.location}),{v7_startTransition:c}=r||{},f=e.useCallback((e=>{c&&j?j((()=>l(e))):l(e)}),[l,c]);return e.useLayoutEffect((()=>s.listen(f)),[s,f]),e.createElement(o,{basename:t,children:n,location:u.location,navigationType:u.action,navigator:s,future:r})}function q({basename:t,children:n,future:r,window:a}){let i=e.useRef();null==i.current&&(i.current=S({window:a,v5Compat:!0}));let s=i.current,[u,l]=e.useState({action:s.action,location:s.location}),{v7_startTransition:c}=r||{},f=e.useCallback((e=>{c&&j?j((()=>l(e))):l(e)}),[l,c]);return e.useLayoutEffect((()=>s.listen(f)),[s,f]),e.createElement(o,{basename:t,children:n,location:u.location,navigationType:u.action,navigator:s,future:r})}function G({basename:t,children:n,future:r,history:a}){let[i,s]=e.useState({action:a.action,location:a.location}),{v7_startTransition:u}=r||{},l=e.useCallback((e=>{u&&j?j((()=>s(e))):s(e)}),[s,u]);return e.useLayoutEffect((()=>a.listen(l)),[a,l]),e.createElement(o,{basename:t,children:n,location:i.location,navigationType:i.action,navigator:a,future:r})}const Q="undefined"!=typeof window&&void 0!==window.document&&void 0!==window.document.createElement,X=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i,Z=e.forwardRef((function({onClick:t,relative:n,reloadDocument:r,replace:a,state:o,target:i,to:l,preventScrollReset:c,unstable_viewTransition:f,...d},m){let h,{basename:p}=e.useContext(s),w=!1;if("string"==typeof l&&X.test(l)&&(h=l,Q))try{let e=new URL(window.location.href),t=l.startsWith("//")?new URL(e.protocol+l):new URL(l),n=g(t.pathname,p);t.origin===e.origin&&null!=n?l=n+t.search+t.hash:w=!0}catch(be){}let v=u(l,{relative:n}),y=se(l,{replace:a,state:o,target:i,preventScrollReset:c,relative:n,unstable_viewTransition:f});return e.createElement("a",Object.assign({},d,{href:h||v,onClick:w||r?t:function(e){t&&t(e),e.defaultPrevented||y(e)},ref:m,target:i}))})),ee=e.forwardRef((function({"aria-current":t="page",caseSensitive:n=!1,className:r="",end:o=!1,style:i,to:u,unstable_viewTransition:f,children:d,...m},h){let p=l(u,{relative:m.relative}),w=c(),v=e.useContext(a),{navigator:y,basename:b}=e.useContext(s),S=null!=v&&ye(p)&&!0===f,R=y.encodeLocation?y.encodeLocation(p).pathname:p.pathname,E=w.pathname,_=v&&v.navigation&&v.navigation.location?v.navigation.location.pathname:null;n||(E=E.toLowerCase(),_=_?_.toLowerCase():null,R=R.toLowerCase()),_&&b&&(_=g(_,b)||_);const T="/"!==R&&R.endsWith("/")?R.length-1:R.length;let L,x=E===R||!o&&E.startsWith(R)&&"/"===E.charAt(T),C=null!=_&&(_===R||!o&&_.startsWith(R)&&"/"===_.charAt(R.length)),A={isActive:x,isPending:C,isTransitioning:S},F=x?t:void 0;L="function"==typeof r?r(A):[r,x?"active":null,C?"pending":null,S?"transitioning":null].filter(Boolean).join(" ");let U="function"==typeof i?i(A):i;return e.createElement(Z,Object.assign({},m,{"aria-current":F,className:L,ref:h,style:U,to:u,unstable_viewTransition:f}),"function"==typeof d?d(A):d)})),te=e.forwardRef((({fetcherKey:t,navigate:n,reloadDocument:r,replace:a,state:o,method:i="get",action:s,onSubmit:u,relative:l,preventScrollReset:c,unstable_viewTransition:f,...d},m)=>{let h=fe(),p=de(s,{relative:l}),w="get"===i.toLowerCase()?"get":"post";return e.createElement("form",Object.assign({ref:m,method:w,action:p,onSubmit:r?u:e=>{if(u&&u(e),e.defaultPrevented)return;e.preventDefault();let r=e.nativeEvent.submitter,s=r?.getAttribute("formmethod")||i;h(r||e.currentTarget,{fetcherKey:t,method:s,navigate:n,replace:a,state:o,relative:l,preventScrollReset:c,unstable_viewTransition:f})}},d))}));function ne({getKey:e,storageKey:t}){return we({getKey:e,storageKey:t}),null}var re=function(e){return e.UseScrollRestoration="useScrollRestoration",e.UseSubmit="useSubmit",e.UseSubmitFetcher="useSubmitFetcher",e.UseFetcher="useFetcher",e.useViewTransitionState="useViewTransitionState",e}(re||{}),ae=function(e){return e.UseFetcher="useFetcher",e.UseFetchers="useFetchers",e.UseScrollRestoration="useScrollRestoration",e}(ae||{});function oe(t){let n=e.useContext(r);return n||E(!1),n}function ie(t){let n=e.useContext(a);return n||E(!1),n}function se(t,{target:n,replace:r,state:a,preventScrollReset:o,relative:i,unstable_viewTransition:s}={}){let u=f(),m=c(),h=l(t,{relative:i});return e.useCallback((e=>{if(function(e,t){return!(0!==e.button||t&&"_self"!==t||function(e){return!!(e.metaKey||e.altKey||e.ctrlKey||e.shiftKey)}(e))}(e,n)){e.preventDefault();let n=void 0!==r?r:d(m)===d(h);u(t,{replace:n,state:a,preventScrollReset:o,relative:i,unstable_viewTransition:s})}}),[m,u,h,r,a,n,t,o,i,s])}function ue(t){let n=e.useRef(A(t)),r=e.useRef(!1),a=c(),o=e.useMemo((()=>function(e,t){let n=A(e);return t&&t.forEach(((e,r)=>{n.has(r)||t.getAll(r).forEach((e=>{n.append(r,e)}))})),n}(a.search,r.current?null:n.current)),[a.search]),i=f(),s=e.useCallback(((e,t)=>{const n=A("function"==typeof e?e(o):e);r.current=!0,i("?"+n,t)}),[i,o]);return[o,s]}let le=0,ce=()=>`__${String(++le)}__`;function fe(){let{router:t}=oe(re.UseSubmit),{basename:n}=e.useContext(s),r=m();return e.useCallback(((e,a={})=>{!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:o,method:i,encType:s,formData:u,body:l}=P(e,n);if(!1===a.navigate){let e=a.fetcherKey||ce();t.fetch(e,r,a.action||o,{preventScrollReset:a.preventScrollReset,formData:u,body:l,formMethod:a.method||i,formEncType:a.encType||s,unstable_flushSync:a.unstable_flushSync})}else t.navigate(a.action||o,{preventScrollReset:a.preventScrollReset,formData:u,body:l,formMethod:a.method||i,formEncType:a.encType||s,replace:a.replace,state:a.state,fromRouteId:r,unstable_flushSync:a.unstable_flushSync,unstable_viewTransition:a.unstable_viewTransition})}),[t,n,r])}function de(t,{relative:n}={}){let{basename:r}=e.useContext(s),a=e.useContext(h);a||E(!1);let[o]=a.matches.slice(-1),i={...l(t||".",{relative:n})},u=c();if(null==t){i.search=u.search;let e=new URLSearchParams(i.search);e.has("index")&&""===e.get("index")&&(e.delete("index"),i.search=e.toString()?`?${e.toString()}`:"")}return t&&"."!==t||!o.route.index||(i.search=i.search?i.search.replace(/^\?/,"?index&"):"?index"),"/"!==r&&(i.pathname="/"===i.pathname?r:_([r,i.pathname])),d(i)}function me({key:t}={}){let{router:n}=oe(re.UseFetcher),r=ie(ae.UseFetcher),a=e.useContext(V),o=e.useContext(h),i=o.matches[o.matches.length-1]?.route.id;a||E(!1),o||E(!1),null==i&&E(!1);let s=H?H():"",[u,l]=e.useState(t||s);t&&t!==u?l(t):u||l(ce()),e.useEffect((()=>(n.getFetcher(u),()=>{n.deleteFetcher(u)})),[n,u]);let c=e.useCallback(((e,t)=>{i||E(!1),n.fetch(u,i,e,t)}),[u,i,n]),f=fe(),d=e.useCallback(((e,t)=>{f(e,{...t,navigate:!1,fetcherKey:u})}),[u,f]),m=e.useMemo((()=>e.forwardRef(((t,n)=>e.createElement(te,Object.assign({},t,{navigate:!1,fetcherKey:u,ref:n}))))),[u]),p=r.fetchers.get(u)||T,w=a.get(u);return e.useMemo((()=>({Form:m,submit:d,load:c,...p,data:w})),[m,d,c,p,w])}function he(){let e=ie(ae.UseFetchers);return Array.from(e.fetchers.entries()).map((([e,t])=>({...t,key:e})))}let pe={};function we({getKey:t,storageKey:n}={}){let{router:r}=oe(re.UseScrollRestoration),{restoreScrollPosition:a,preventScrollReset:o}=ie(ae.UseScrollRestoration),{basename:i}=e.useContext(s),u=c(),l=p(),f=w();e.useEffect((()=>(window.history.scrollRestoration="manual",()=>{window.history.scrollRestoration="auto"})),[]),function(t,n){let{capture:r}=n||{};e.useEffect((()=>{let e=null!=r?{capture:r}:void 0;return window.addEventListener("pagehide",t,e),()=>{window.removeEventListener("pagehide",t,e)}}),[t,r])}(e.useCallback((()=>{if("idle"===f.state){let e=(t?t(u,l):null)||u.key;pe[e]=window.scrollY}try{sessionStorage.setItem(n||"react-router-scroll-positions",JSON.stringify(pe))}catch(e){}window.history.scrollRestoration="auto"}),[n,t,f.state,u,l])),"undefined"!=typeof document&&(e.useLayoutEffect((()=>{try{let e=sessionStorage.getItem(n||"react-router-scroll-positions");e&&(pe=JSON.parse(e))}catch(be){}}),[n]),e.useLayoutEffect((()=>{let e=t&&"/"!==i?(e,n)=>t({...e,pathname:g(e.pathname,i)||e.pathname},n):t,n=r?.enableScrollRestoration(pe,(()=>window.scrollY),e);return()=>n&&n()}),[r,i,t]),e.useLayoutEffect((()=>{if(!1!==a)if("number"!=typeof a){if(u.hash){let e=document.getElementById(decodeURIComponent(u.hash.slice(1)));if(e)return void e.scrollIntoView()}!0!==o&&window.scrollTo(0,0)}else window.scrollTo(0,a)}),[u,a,o]))}function ve(t,n){let{capture:r}=n||{};e.useEffect((()=>{let e=null!=r?{capture:r}:void 0;return window.addEventListener("beforeunload",t,e),()=>{window.removeEventListener("beforeunload",t,e)}}),[t,r])}function ge({when:t,message:n}){let r=v(t);e.useEffect((()=>{if("blocked"===r.state){window.confirm(n)?setTimeout(r.proceed,0):r.reset()}}),[r,n]),e.useEffect((()=>{"blocked"!==r.state||t||r.reset()}),[r,t])}function ye(t,n={}){let r=e.useContext(K);null==r&&E(!1);let{basename:a}=oe(re.useViewTransitionState),o=l(t,{relative:n.relative});if(!r.isTransitioning)return!1;let i=g(r.currentLocation.pathname,a)||r.currentLocation.pathname,s=g(r.nextLocation.pathname,a)||r.nextLocation.pathname;return null!=L(o.pathname,s)||null!=L(o.pathname,i)}export{J as BrowserRouter,te as Form,q as HashRouter,Z as Link,ee as NavLink,$ as RouterProvider,ne as ScrollRestoration,V as UNSAFE_FetchersContext,K as UNSAFE_ViewTransitionContext,we as UNSAFE_useScrollRestoration,N as createBrowserRouter,D as createHashRouter,A as createSearchParams,G as unstable_HistoryRouter,ge as unstable_usePrompt,ye as unstable_useViewTransitionState,ve as useBeforeUnload,me as useFetcher,he as useFetchers,de as useFormAction,se as useLinkClickHandler,ue as useSearchParams,fe as useSubmit}; | ||
//# sourceMappingURL=react-router-dom.production.min.js.map |
import * as React from "react"; | ||
import type { Router as RemixRouter, StaticHandlerContext, CreateStaticHandlerOptions as RouterCreateStaticHandlerOptions } from "@remix-run/router"; | ||
import type { Location, RouteObject } from "react-router-dom"; | ||
import type { Router as RemixRouter, StaticHandlerContext, CreateStaticHandlerOptions as RouterCreateStaticHandlerOptions, FutureConfig as RouterFutureConfig } from "@remix-run/router"; | ||
import type { FutureConfig, Location, RouteObject } from "react-router-dom"; | ||
export interface StaticRouterProps { | ||
@@ -8,8 +8,9 @@ basename?: string; | ||
location: Partial<Location> | string; | ||
future?: Partial<FutureConfig>; | ||
} | ||
/** | ||
* 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, future, }: StaticRouterProps): React.JSX.Element; | ||
export { StaticHandlerContext }; | ||
@@ -26,5 +27,7 @@ export interface StaticRouterProviderProps { | ||
*/ | ||
export declare function StaticRouterProvider({ context, router, hydrate, nonce, }: StaticRouterProviderProps): JSX.Element; | ||
export declare function StaticRouterProvider({ context, router, hydrate, nonce, }: StaticRouterProviderProps): React.JSX.Element; | ||
type CreateStaticHandlerOptions = Omit<RouterCreateStaticHandlerOptions, "detectErrorBoundary" | "mapRouteProperties">; | ||
export declare function createStaticHandler(routes: RouteObject[], opts?: CreateStaticHandlerOptions): import("@remix-run/router").StaticHandler; | ||
export declare function createStaticRouter(routes: RouteObject[], context: StaticHandlerContext): RemixRouter; | ||
export declare function createStaticRouter(routes: RouteObject[], context: StaticHandlerContext, opts?: { | ||
future?: Partial<Pick<RouterFutureConfig, "v7_partialHydration" | "v7_relativeSplatPath">>; | ||
}): RemixRouter; |
@@ -31,3 +31,3 @@ 'use strict'; | ||
/** | ||
* 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. | ||
@@ -38,3 +38,4 @@ */ | ||
children, | ||
location: locationProp = "/" | ||
location: locationProp = "/", | ||
future | ||
}) { | ||
@@ -49,3 +50,3 @@ if (typeof locationProp === "string") { | ||
hash: locationProp.hash || "", | ||
state: locationProp.state || null, | ||
state: locationProp.state != null ? locationProp.state : null, | ||
key: locationProp.key || "default" | ||
@@ -60,2 +61,3 @@ }; | ||
navigator: staticNavigator, | ||
future: future, | ||
static: true | ||
@@ -82,2 +84,3 @@ }); | ||
}; | ||
let fetchersContext = new Map(); | ||
let hydrateScript = ""; | ||
@@ -104,2 +107,8 @@ if (hydrate !== false) { | ||
value: state | ||
}, /*#__PURE__*/React__namespace.createElement(reactRouterDom.UNSAFE_FetchersContext.Provider, { | ||
value: fetchersContext | ||
}, /*#__PURE__*/React__namespace.createElement(reactRouterDom.UNSAFE_ViewTransitionContext.Provider, { | ||
value: { | ||
isTransitioning: false | ||
} | ||
}, /*#__PURE__*/React__namespace.createElement(reactRouterDom.Router, { | ||
@@ -110,7 +119,11 @@ basename: dataRouterContext.basename, | ||
navigator: dataRouterContext.navigator, | ||
static: dataRouterContext.static | ||
static: dataRouterContext.static, | ||
future: { | ||
v7_relativeSplatPath: router$1.future.v7_relativeSplatPath | ||
} | ||
}, /*#__PURE__*/React__namespace.createElement(DataRoutes, { | ||
routes: router$1.routes, | ||
future: router$1.future, | ||
state: state | ||
})))), hydrateScript ? /*#__PURE__*/React__namespace.createElement("script", { | ||
})))))), hydrateScript ? /*#__PURE__*/React__namespace.createElement("script", { | ||
suppressHydrationWarning: true, | ||
@@ -125,5 +138,6 @@ nonce: nonce, | ||
routes, | ||
future, | ||
state | ||
}) { | ||
return reactRouter.UNSAFE_useRoutesImpl(routes, undefined, state); | ||
return reactRouter.UNSAFE_useRoutesImpl(routes, undefined, state, future); | ||
} | ||
@@ -186,3 +200,3 @@ function serializeErrors(errors) { | ||
} | ||
function createStaticRouter(routes, context) { | ||
function createStaticRouter(routes, context, opts = {}) { | ||
let manifest = {}; | ||
@@ -205,2 +219,12 @@ let dataRoutes = router.UNSAFE_convertRoutesToDataRoutes(routes, reactRouter.UNSAFE_mapRouteProperties, undefined, manifest); | ||
}, | ||
get future() { | ||
return { | ||
v7_fetcherPersist: false, | ||
v7_normalizeFormMethod: false, | ||
v7_partialHydration: opts.future?.v7_partialHydration === true, | ||
v7_prependBasename: false, | ||
v7_relativeSplatPath: opts.future?.v7_relativeSplatPath === true, | ||
v7_skipActionErrorRevalidation: false | ||
}; | ||
}, | ||
get state() { | ||
@@ -226,2 +250,5 @@ return { | ||
}, | ||
get window() { | ||
return undefined; | ||
}, | ||
initialize() { | ||
@@ -262,2 +289,5 @@ throw msg("initialize"); | ||
}, | ||
patchRoutes() { | ||
throw msg("patchRoutes"); | ||
}, | ||
_internalFetchControllers: new Map(), | ||
@@ -274,10 +304,15 @@ _internalActiveDeferreds: new Map(), | ||
function encodeLocation(to) { | ||
// Locations should already be encoded on the server, so just return as-is | ||
let path = typeof to === "string" ? reactRouterDom.parsePath(to) : to; | ||
let href = typeof to === "string" ? to : reactRouterDom.createPath(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 | ||
}; | ||
} | ||
const ABSOLUTE_URL_REGEX = /^(?:[a-z][a-z0-9+.-]*:|\/\/)/i; | ||
// This utility is based on https://github.com/zertosh/htmlescape | ||
@@ -284,0 +319,0 @@ // License: https://github.com/zertosh/htmlescape/blob/0527ca7156a524d256101bb310a9f970f63078ad/LICENSE |
/** | ||
* React Router DOM v0.0.0-experimental-f728258d | ||
* React Router DOM v0.0.0-experimental-f7aa35148 | ||
* | ||
@@ -11,3 +11,3 @@ * Copyright (c) Remix Software Inc. | ||
*/ | ||
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("react"),require("react-router"),require("@remix-run/router")):"function"==typeof define&&define.amd?define(["exports","react","react-router","@remix-run/router"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).ReactRouterDOM={},e.React,e.ReactRouter,e.RemixRouter)}(this,(function(e,t,r,n){"use strict";function o(e){if(e&&e.__esModule)return e;var t=Object.create(null);return e&&Object.keys(e).forEach((function(r){if("default"!==r){var n=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,n.get?n:{enumerable:!0,get:function(){return e[r]}})}})),t.default=e,Object.freeze(t)}var a=o(t);function u(){return u=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},u.apply(this,arguments)}function i(e,t){if(null==e)return{};var r,n,o={},a=Object.keys(e);for(n=0;n<a.length;n++)r=a[n],t.indexOf(r)>=0||(o[r]=e[r]);return o}const c="get",s="application/x-www-form-urlencoded";function l(e){return null!=e&&"string"==typeof e.tagName}function f(e){return void 0===e&&(e=""),new URLSearchParams("string"==typeof e||Array.isArray(e)||e instanceof URLSearchParams?e:Object.keys(e).reduce(((t,r)=>{let n=e[r];return t.concat(Array.isArray(n)?n.map((e=>[r,e])):[[r,n]])}),[]))}let d=null;const m=new Set(["application/x-www-form-urlencoded","multipart/form-data","text/plain"]);function b(e){return null==e||m.has(e)?e:null}function p(e,t){let r,o,a,u,i;if(l(f=e)&&"form"===f.tagName.toLowerCase()){let i=e.getAttribute("action");o=i?n.stripBasename(i,t):null,r=e.getAttribute("method")||c,a=b(e.getAttribute("enctype"))||s,u=new FormData(e)}else if(function(e){return l(e)&&"button"===e.tagName.toLowerCase()}(e)||function(e){return l(e)&&"input"===e.tagName.toLowerCase()}(e)&&("submit"===e.type||"image"===e.type)){let i=e.form;if(null==i)throw new Error('Cannot submit a <button> or <input type="submit"> without a <form>');let l=e.getAttribute("formaction")||i.getAttribute("action");if(o=l?n.stripBasename(l,t):null,r=e.getAttribute("formmethod")||i.getAttribute("method")||c,a=b(e.getAttribute("formenctype"))||b(i.getAttribute("enctype"))||s,u=new FormData(i,e),!function(){if(null===d)try{new FormData(document.createElement("form"),0),d=!1}catch(e){d=!0}return d}()){let{name:t,type:r,value:n}=e;if("image"===r){let e=t?t+".":"";u.append(e+"x","0"),u.append(e+"y","0")}else t&&u.append(t,n)}}else{if(l(e))throw new Error('Cannot submit element that is not <form>, <button>, or <input type="submit|image">');r=c,o=null,a=s,i=e}var f;return u&&"text/plain"===a&&(i=u,u=void 0),{action:o,method:r.toLowerCase(),encType:a,formData:u,body:i}}const y=["onClick","relative","reloadDocument","replace","state","target","to","preventScrollReset"],h=["aria-current","caseSensitive","className","end","style","to","children"],g=["reloadDocument","replace","state","method","action","onSubmit","submit","relative","preventScrollReset"];function v(){var e;let t=null==(e=window)?void 0:e.__staticRouterHydrationData;return t&&t.errors&&(t=u({},t,{errors:R(t.errors)})),t}function R(e){if(!e)return null;let t=Object.entries(e),r={};for(let[e,o]of t)if(o&&"RouteErrorResponse"===o.__type)r[e]=new n.ErrorResponse(o.status,o.statusText,o.data,!0===o.internal);else if(o&&"Error"===o.__type){if(o.__subType){let t=window[o.__subType];if("function"==typeof t)try{let n=new t(o.message);n.stack="",r[e]=n}catch(e){}}if(null==r[e]){let t=new Error(o.message);t.stack="",r[e]=t}}else r[e]=o;return r}const w=a.startTransition;const P="undefined"!=typeof window&&void 0!==window.document&&void 0!==window.document.createElement,S=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i,E=a.forwardRef((function(e,t){let o,{onClick:c,relative:s,reloadDocument:l,replace:f,state:d,target:m,to:b,preventScrollReset:p}=e,h=i(e,y),{basename:g}=a.useContext(r.UNSAFE_NavigationContext),v=!1;if("string"==typeof b&&S.test(b)&&(o=b,P))try{let e=new URL(window.location.href),t=b.startsWith("//")?new URL(e.protocol+b):new URL(b),r=n.stripBasename(t.pathname,g);t.origin===e.origin&&null!=r?b=r+t.search+t.hash:v=!0}catch(e){}let R=r.useHref(b,{relative:s}),w=U(b,{replace:f,state:d,target:m,preventScrollReset:p,relative:s});return a.createElement("a",u({},h,{href:o||R,onClick:v||l?c:function(e){c&&c(e),e.defaultPrevented||w(e)},ref:t,target:m}))})),O=a.forwardRef((function(e,t){let{"aria-current":n="page",caseSensitive:o=!1,className:c="",end:s=!1,style:l,to:f,children:d}=e,m=i(e,h),b=r.useResolvedPath(f,{relative:m.relative}),p=r.useLocation(),y=a.useContext(r.UNSAFE_DataRouterStateContext),{navigator:g}=a.useContext(r.UNSAFE_NavigationContext),v=g.encodeLocation?g.encodeLocation(b).pathname:b.pathname,R=p.pathname,w=y&&y.navigation&&y.navigation.location?y.navigation.location.pathname:null;o||(R=R.toLowerCase(),w=w?w.toLowerCase():null,v=v.toLowerCase());let P,S=R===v||!s&&R.startsWith(v)&&"/"===R.charAt(v.length),O=null!=w&&(w===v||!s&&w.startsWith(v)&&"/"===w.charAt(v.length)),j=S?n:void 0;P="function"==typeof c?c({isActive:S,isPending:O}):[c,S?"active":null,O?"pending":null].filter(Boolean).join(" ");let N="function"==typeof l?l({isActive:S,isPending:O}):l;return a.createElement(E,u({},m,{"aria-current":j,className:P,ref:t,style:N,to:f}),"function"==typeof d?d({isActive:S,isPending:O}):d)})),j=a.forwardRef(((e,t)=>{let r=L();return a.createElement(N,u({},e,{submit:r,ref:t}))})),N=a.forwardRef(((e,t)=>{let{reloadDocument:r,replace:n,state:o,method:s=c,action:l,onSubmit:f,submit:d,relative:m,preventScrollReset:b}=e,p=i(e,g),y="get"===s.toLowerCase()?"get":"post",h=k(l,{relative:m});return a.createElement("form",u({ref:t,method:y,action:h,onSubmit:r?f:e=>{if(f&&f(e),e.defaultPrevented)return;e.preventDefault();let t=e.nativeEvent.submitter,r=(null==t?void 0:t.getAttribute("formmethod"))||s;d(t||e.currentTarget,{method:r,replace:n,state:o,relative:m,preventScrollReset:b})}},p))}));var A,C;function _(e){let t=a.useContext(r.UNSAFE_DataRouterContext);return t||n.UNSAFE_invariant(!1),t}function F(e){let t=a.useContext(r.UNSAFE_DataRouterStateContext);return t||n.UNSAFE_invariant(!1),t}function U(e,t){let{target:n,replace:o,state:u,preventScrollReset:i,relative:c}=void 0===t?{}:t,s=r.useNavigate(),l=r.useLocation(),f=r.useResolvedPath(e,{relative:c});return a.useCallback((t=>{if(function(e,t){return!(0!==e.button||t&&"_self"!==t||function(e){return!!(e.metaKey||e.altKey||e.ctrlKey||e.shiftKey)}(e))}(t,n)){t.preventDefault();let n=void 0!==o?o:r.createPath(l)===r.createPath(f);s(e,{replace:n,state:u,preventScrollReset:i,relative:c})}}),[l,s,f,o,u,n,e,i,c])}function x(){if("undefined"==typeof document)throw new Error("You are calling submit during the server render. Try calling submit within a `useEffect` or callback instead.")}function L(){let{router:e}=_(A.UseSubmit),{basename:t}=a.useContext(r.UNSAFE_NavigationContext),n=r.UNSAFE_useRouteId();return a.useCallback((function(r,o){void 0===o&&(o={}),x();let{action:a,method:u,encType:i,formData:c,body:s}=p(r,t);e.navigate(o.action||a,{preventScrollReset:o.preventScrollReset,formData:c,body:s,formMethod:o.method||u,formEncType:o.encType||i,replace:o.replace,state:o.state,fromRouteId:n})}),[e,t,n])}function D(e,t){let{router:o}=_(A.UseSubmitFetcher),{basename:u}=a.useContext(r.UNSAFE_NavigationContext);return a.useCallback((function(r,a){void 0===a&&(a={}),x();let{action:i,method:c,encType:s,formData:l,body:f}=p(r,u);null==t&&n.UNSAFE_invariant(!1),o.fetch(e,t,a.action||i,{preventScrollReset:a.preventScrollReset,formData:l,body:f,formMethod:a.method||c,formEncType:a.encType||s})}),[o,u,e,t])}function k(e,t){let{relative:o}=void 0===t?{}:t,{basename:i}=a.useContext(r.UNSAFE_NavigationContext),c=a.useContext(r.UNSAFE_RouteContext);c||n.UNSAFE_invariant(!1);let[s]=c.matches.slice(-1),l=u({},r.useResolvedPath(e||".",{relative:o})),f=r.useLocation();if(null==e&&(l.search=f.search,l.hash=f.hash,s.route.index)){let e=new URLSearchParams(l.search);e.delete("index"),l.search=e.toString()?"?"+e.toString():""}return e&&"."!==e||!s.route.index||(l.search=l.search?l.search.replace(/^\?/,"?index&"):"?index"),"/"!==i&&(l.pathname="/"===l.pathname?i:n.joinPaths([i,l.pathname])),r.createPath(l)}!function(e){e.UseScrollRestoration="useScrollRestoration",e.UseSubmit="useSubmit",e.UseSubmitFetcher="useSubmitFetcher",e.UseFetcher="useFetcher"}(A||(A={})),function(e){e.UseFetchers="useFetchers",e.UseScrollRestoration="useScrollRestoration"}(C||(C={}));let T=0;const M="react-router-scroll-positions";let B={};function H(e){let{getKey:t,storageKey:o}=void 0===e?{}:e,{router:i}=_(A.UseScrollRestoration),{restoreScrollPosition:c,preventScrollReset:s}=F(C.UseScrollRestoration),{basename:l}=a.useContext(r.UNSAFE_NavigationContext),f=r.useLocation(),d=r.useMatches(),m=r.useNavigation();a.useEffect((()=>(window.history.scrollRestoration="manual",()=>{window.history.scrollRestoration="auto"})),[]),function(e,t){let{capture:r}=t||{};a.useEffect((()=>{let t=null!=r?{capture:r}:void 0;return window.addEventListener("pagehide",e,t),()=>{window.removeEventListener("pagehide",e,t)}}),[e,r])}(a.useCallback((()=>{if("idle"===m.state){let e=(t?t(f,d):null)||f.key;B[e]=window.scrollY}sessionStorage.setItem(o||M,JSON.stringify(B)),window.history.scrollRestoration="auto"}),[o,t,m.state,f,d])),"undefined"!=typeof document&&(a.useLayoutEffect((()=>{try{let e=sessionStorage.getItem(o||M);e&&(B=JSON.parse(e))}catch(e){}}),[o]),a.useLayoutEffect((()=>{let e=t&&"/"!==l?(e,r)=>t(u({},e,{pathname:n.stripBasename(e.pathname,l)||e.pathname}),r):t,r=null==i?void 0:i.enableScrollRestoration(B,(()=>window.scrollY),e);return()=>r&&r()}),[i,l,t]),a.useLayoutEffect((()=>{if(!1!==c)if("number"!=typeof c){if(f.hash){let e=document.getElementById(decodeURIComponent(f.hash.slice(1)));if(e)return void e.scrollIntoView()}!0!==s&&window.scrollTo(0,0)}else window.scrollTo(0,c)}),[f,c,s]))}Object.defineProperty(e,"AbortedDeferredError",{enumerable:!0,get:function(){return r.AbortedDeferredError}}),Object.defineProperty(e,"Await",{enumerable:!0,get:function(){return r.Await}}),Object.defineProperty(e,"MemoryRouter",{enumerable:!0,get:function(){return r.MemoryRouter}}),Object.defineProperty(e,"Navigate",{enumerable:!0,get:function(){return r.Navigate}}),Object.defineProperty(e,"NavigationType",{enumerable:!0,get:function(){return r.NavigationType}}),Object.defineProperty(e,"Outlet",{enumerable:!0,get:function(){return r.Outlet}}),Object.defineProperty(e,"Route",{enumerable:!0,get:function(){return r.Route}}),Object.defineProperty(e,"Router",{enumerable:!0,get:function(){return r.Router}}),Object.defineProperty(e,"RouterProvider",{enumerable:!0,get:function(){return r.RouterProvider}}),Object.defineProperty(e,"Routes",{enumerable:!0,get:function(){return r.Routes}}),Object.defineProperty(e,"UNSAFE_DataRouterContext",{enumerable:!0,get:function(){return r.UNSAFE_DataRouterContext}}),Object.defineProperty(e,"UNSAFE_DataRouterStateContext",{enumerable:!0,get:function(){return r.UNSAFE_DataRouterStateContext}}),Object.defineProperty(e,"UNSAFE_LocationContext",{enumerable:!0,get:function(){return r.UNSAFE_LocationContext}}),Object.defineProperty(e,"UNSAFE_NavigationContext",{enumerable:!0,get:function(){return r.UNSAFE_NavigationContext}}),Object.defineProperty(e,"UNSAFE_RouteContext",{enumerable:!0,get:function(){return r.UNSAFE_RouteContext}}),Object.defineProperty(e,"UNSAFE_useRouteId",{enumerable:!0,get:function(){return r.UNSAFE_useRouteId}}),Object.defineProperty(e,"createMemoryRouter",{enumerable:!0,get:function(){return r.createMemoryRouter}}),Object.defineProperty(e,"createPath",{enumerable:!0,get:function(){return r.createPath}}),Object.defineProperty(e,"createRoutesFromChildren",{enumerable:!0,get:function(){return r.createRoutesFromChildren}}),Object.defineProperty(e,"createRoutesFromElements",{enumerable:!0,get:function(){return r.createRoutesFromElements}}),Object.defineProperty(e,"defer",{enumerable:!0,get:function(){return r.defer}}),Object.defineProperty(e,"generatePath",{enumerable:!0,get:function(){return r.generatePath}}),Object.defineProperty(e,"isRouteErrorResponse",{enumerable:!0,get:function(){return r.isRouteErrorResponse}}),Object.defineProperty(e,"json",{enumerable:!0,get:function(){return r.json}}),Object.defineProperty(e,"matchPath",{enumerable:!0,get:function(){return r.matchPath}}),Object.defineProperty(e,"matchRoutes",{enumerable:!0,get:function(){return r.matchRoutes}}),Object.defineProperty(e,"parsePath",{enumerable:!0,get:function(){return r.parsePath}}),Object.defineProperty(e,"redirect",{enumerable:!0,get:function(){return r.redirect}}),Object.defineProperty(e,"renderMatches",{enumerable:!0,get:function(){return r.renderMatches}}),Object.defineProperty(e,"resolvePath",{enumerable:!0,get:function(){return r.resolvePath}}),Object.defineProperty(e,"unstable_useBlocker",{enumerable:!0,get:function(){return r.unstable_useBlocker}}),Object.defineProperty(e,"useActionData",{enumerable:!0,get:function(){return r.useActionData}}),Object.defineProperty(e,"useAsyncError",{enumerable:!0,get:function(){return r.useAsyncError}}),Object.defineProperty(e,"useAsyncValue",{enumerable:!0,get:function(){return r.useAsyncValue}}),Object.defineProperty(e,"useHref",{enumerable:!0,get:function(){return r.useHref}}),Object.defineProperty(e,"useInRouterContext",{enumerable:!0,get:function(){return r.useInRouterContext}}),Object.defineProperty(e,"useLoaderData",{enumerable:!0,get:function(){return r.useLoaderData}}),Object.defineProperty(e,"useLocation",{enumerable:!0,get:function(){return r.useLocation}}),Object.defineProperty(e,"useMatch",{enumerable:!0,get:function(){return r.useMatch}}),Object.defineProperty(e,"useMatches",{enumerable:!0,get:function(){return r.useMatches}}),Object.defineProperty(e,"useNavigate",{enumerable:!0,get:function(){return r.useNavigate}}),Object.defineProperty(e,"useNavigation",{enumerable:!0,get:function(){return r.useNavigation}}),Object.defineProperty(e,"useNavigationType",{enumerable:!0,get:function(){return r.useNavigationType}}),Object.defineProperty(e,"useOutlet",{enumerable:!0,get:function(){return r.useOutlet}}),Object.defineProperty(e,"useOutletContext",{enumerable:!0,get:function(){return r.useOutletContext}}),Object.defineProperty(e,"useParams",{enumerable:!0,get:function(){return r.useParams}}),Object.defineProperty(e,"useResolvedPath",{enumerable:!0,get:function(){return r.useResolvedPath}}),Object.defineProperty(e,"useRevalidator",{enumerable:!0,get:function(){return r.useRevalidator}}),Object.defineProperty(e,"useRouteError",{enumerable:!0,get:function(){return r.useRouteError}}),Object.defineProperty(e,"useRouteLoaderData",{enumerable:!0,get:function(){return r.useRouteLoaderData}}),Object.defineProperty(e,"useRoutes",{enumerable:!0,get:function(){return r.useRoutes}}),e.BrowserRouter=function(e){let{basename:t,children:o,future:u,window:i}=e,c=a.useRef();null==c.current&&(c.current=n.createBrowserHistory({window:i,v5Compat:!0}));let s=c.current,[l,f]=a.useState({action:s.action,location:s.location}),{v7_startTransition:d}=u||{},m=a.useCallback((e=>{d&&w?w((()=>f(e))):f(e)}),[f,d]);return a.useLayoutEffect((()=>s.listen(m)),[s,m]),a.createElement(r.Router,{basename:t,children:o,location:l.location,navigationType:l.action,navigator:s})},e.Form=j,e.HashRouter=function(e){let{basename:t,children:o,future:u,window:i}=e,c=a.useRef();null==c.current&&(c.current=n.createHashHistory({window:i,v5Compat:!0}));let s=c.current,[l,f]=a.useState({action:s.action,location:s.location}),{v7_startTransition:d}=u||{},m=a.useCallback((e=>{d&&w?w((()=>f(e))):f(e)}),[f,d]);return a.useLayoutEffect((()=>s.listen(m)),[s,m]),a.createElement(r.Router,{basename:t,children:o,location:l.location,navigationType:l.action,navigator:s})},e.Link=E,e.NavLink=O,e.ScrollRestoration=function(e){let{getKey:t,storageKey:r}=e;return H({getKey:t,storageKey:r}),null},e.UNSAFE_useScrollRestoration=H,e.createBrowserRouter=function(e,t){return n.createRouter({basename:null==t?void 0:t.basename,future:u({},null==t?void 0:t.future,{v7_prependBasename:!0}),history:n.createBrowserHistory({window:null==t?void 0:t.window}),hydrationData:(null==t?void 0:t.hydrationData)||v(),routes:e,mapRouteProperties:r.UNSAFE_mapRouteProperties}).initialize()},e.createHashRouter=function(e,t){return n.createRouter({basename:null==t?void 0:t.basename,future:u({},null==t?void 0:t.future,{v7_prependBasename:!0}),history:n.createHashHistory({window:null==t?void 0:t.window}),hydrationData:(null==t?void 0:t.hydrationData)||v(),routes:e,mapRouteProperties:r.UNSAFE_mapRouteProperties}).initialize()},e.createSearchParams=f,e.unstable_HistoryRouter=function(e){let{basename:t,children:n,future:o,history:u}=e,[i,c]=a.useState({action:u.action,location:u.location}),{v7_startTransition:s}=o||{},l=a.useCallback((e=>{s&&w?w((()=>c(e))):c(e)}),[c,s]);return a.useLayoutEffect((()=>u.listen(l)),[u,l]),a.createElement(r.Router,{basename:t,children:n,location:i.location,navigationType:i.action,navigator:u})},e.unstable_usePrompt=function(e){let{when:t,message:n}=e,o=r.unstable_useBlocker(t);a.useEffect((()=>{if("blocked"===o.state){window.confirm(n)?o.proceed():o.reset()}}),[o,n]),a.useEffect((()=>{"blocked"!==o.state||t||o.reset()}),[o,t])},e.useBeforeUnload=function(e,t){let{capture:r}=t||{};a.useEffect((()=>{let t=null!=r?{capture:r}:void 0;return window.addEventListener("beforeunload",e,t),()=>{window.removeEventListener("beforeunload",e,t)}}),[e,r])},e.useFetcher=function(){var e;let{router:t}=_(A.UseFetcher),o=a.useContext(r.UNSAFE_RouteContext);o||n.UNSAFE_invariant(!1);let i=null==(e=o.matches[o.matches.length-1])?void 0:e.route.id;null==i&&n.UNSAFE_invariant(!1);let[c]=a.useState((()=>String(++T))),[s]=a.useState((()=>(i||n.UNSAFE_invariant(!1),function(e,t){return a.forwardRef(((r,n)=>{let o=D(e,t);return a.createElement(N,u({},r,{ref:n,submit:o}))}))}(c,i)))),[l]=a.useState((()=>e=>{t||n.UNSAFE_invariant(!1),i||n.UNSAFE_invariant(!1),t.fetch(c,i,e)})),f=D(c,i),d=t.getFetcher(c),m=a.useMemo((()=>u({Form:s,submit:f,load:l},d)),[d,s,f,l]);return a.useEffect((()=>()=>{t?t.deleteFetcher(c):console.warn("No router available to clean up from useFetcher()")}),[t,c]),m},e.useFetchers=function(){return[...F(C.UseFetchers).fetchers.values()]},e.useFormAction=k,e.useLinkClickHandler=U,e.useSearchParams=function(e){let t=a.useRef(f(e)),n=a.useRef(!1),o=r.useLocation(),u=a.useMemo((()=>function(e,t){let r=f(e);return t&&t.forEach(((e,n)=>{r.has(n)||t.getAll(n).forEach((e=>{r.append(n,e)}))})),r}(o.search,n.current?null:t.current)),[o.search]),i=r.useNavigate(),c=a.useCallback(((e,t)=>{const r=f("function"==typeof e?e(u):e);n.current=!0,i("?"+r,t)}),[i,u]);return[u,c]},e.useSubmit=L,Object.defineProperty(e,"__esModule",{value:!0})})); | ||
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("react"),require("react-dom"),require("react-router"),require("@remix-run/router")):"function"==typeof define&&define.amd?define(["exports","react","react-dom","react-router","@remix-run/router"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).ReactRouterDOM={},e.React,e.ReactDOM,e.ReactRouter,e.RemixRouter)}(this,(function(e,t,n,r,o){"use strict";function a(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 i=a(t),u=a(n);function s(){return s=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},s.apply(this,arguments)}function c(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 l="get",f="application/x-www-form-urlencoded";function d(e){return null!=e&&"string"==typeof e.tagName}function m(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 p=null;const b=new Set(["application/x-www-form-urlencoded","multipart/form-data","text/plain"]);function h(e){return null==e||b.has(e)?e:null}function v(e,t){let n,r,a,i,u;if(d(s=e)&&"form"===s.tagName.toLowerCase()){let u=e.getAttribute("action");r=u?o.stripBasename(u,t):null,n=e.getAttribute("method")||l,a=h(e.getAttribute("enctype"))||f,i=new FormData(e)}else if(function(e){return d(e)&&"button"===e.tagName.toLowerCase()}(e)||function(e){return d(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")||l,a=h(e.getAttribute("formenctype"))||h(u.getAttribute("enctype"))||f,i=new FormData(u,e),!function(){if(null===p)try{new FormData(document.createElement("form"),0),p=!1}catch(e){p=!0}return p}()){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(d(e))throw new Error('Cannot submit element that is not <form>, <button>, or <input type="submit|image">');n=l,r=null,a=f,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 y=["onClick","relative","reloadDocument","replace","state","target","to","preventScrollReset","unstable_viewTransition"],g=["aria-current","caseSensitive","className","end","style","to","unstable_viewTransition","children"],w=["fetcherKey","navigate","reloadDocument","replace","state","method","action","onSubmit","relative","preventScrollReset","unstable_viewTransition"];try{window.__reactRouterVersion="0"}catch(e){}function R(){var e;let t=null==(e=window)?void 0:e.__staticRouterHydrationData;return t&&t.errors&&(t=s({},t,{errors:S(t.errors)})),t}function S(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 E=i.createContext({isTransitioning:!1}),_=i.createContext(new Map),P=i.startTransition,O=u.flushSync,A=i.useId;function C(e){O?O(e):e()}class N{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))}}))}}const j=i.memo(x);function x(e){let{routes:t,future:n,state:o}=e;return r.UNSAFE_useRoutesImpl(t,void 0,o,n)}const F="undefined"!=typeof window&&void 0!==window.document&&void 0!==window.document.createElement,L=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i,T=i.forwardRef((function(e,t){let n,{onClick:a,relative:u,reloadDocument:l,replace:f,state:d,target:m,to:p,preventScrollReset:b,unstable_viewTransition:h}=e,v=c(e,y),{basename:g}=i.useContext(r.UNSAFE_NavigationContext),w=!1;if("string"==typeof p&&L.test(p)&&(n=p,F))try{let e=new URL(window.location.href),t=p.startsWith("//")?new URL(e.protocol+p):new URL(p),n=o.stripBasename(t.pathname,g);t.origin===e.origin&&null!=n?p=n+t.search+t.hash:w=!0}catch(e){}let R=r.useHref(p,{relative:u}),S=I(p,{replace:f,state:d,target:m,preventScrollReset:b,relative:u,unstable_viewTransition:h});return i.createElement("a",s({},v,{href:n||R,onClick:w||l?a:function(e){a&&a(e),e.defaultPrevented||S(e)},ref:t,target:m}))})),U=i.forwardRef((function(e,t){let{"aria-current":n="page",caseSensitive:a=!1,className:u="",end:l=!1,style:f,to:d,unstable_viewTransition:m,children:p}=e,b=c(e,g),h=r.useResolvedPath(d,{relative:b.relative}),v=r.useLocation(),y=i.useContext(r.UNSAFE_DataRouterStateContext),{navigator:w,basename:R}=i.useContext(r.UNSAFE_NavigationContext),S=null!=y&&G(h)&&!0===m,E=w.encodeLocation?w.encodeLocation(h).pathname:h.pathname,_=v.pathname,P=y&&y.navigation&&y.navigation.location?y.navigation.location.pathname:null;a||(_=_.toLowerCase(),P=P?P.toLowerCase():null,E=E.toLowerCase()),P&&R&&(P=o.stripBasename(P,R)||P);const O="/"!==E&&E.endsWith("/")?E.length-1:E.length;let A,C=_===E||!l&&_.startsWith(E)&&"/"===_.charAt(O),N=null!=P&&(P===E||!l&&P.startsWith(E)&&"/"===P.charAt(E.length)),j={isActive:C,isPending:N,isTransitioning:S},x=C?n:void 0;A="function"==typeof u?u(j):[u,C?"active":null,N?"pending":null,S?"transitioning":null].filter(Boolean).join(" ");let F="function"==typeof f?f(j):f;return i.createElement(T,s({},b,{"aria-current":x,className:A,ref:t,style:F,to:d,unstable_viewTransition:m}),"function"==typeof p?p(j):p)})),D=i.forwardRef(((e,t)=>{let{fetcherKey:n,navigate:r,reloadDocument:o,replace:a,state:u,method:f=l,action:d,onSubmit:m,relative:p,preventScrollReset:b,unstable_viewTransition:h}=e,v=c(e,w),y=z(),g=q(d,{relative:p}),R="get"===f.toLowerCase()?"get":"post";return i.createElement("form",s({ref:t,method:R,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"))||f;y(t||e.currentTarget,{fetcherKey:n,method:o,navigate:r,replace:a,state:u,relative:p,preventScrollReset:b,unstable_viewTransition:h})}},v))}));var k=function(e){return e.UseScrollRestoration="useScrollRestoration",e.UseSubmit="useSubmit",e.UseSubmitFetcher="useSubmitFetcher",e.UseFetcher="useFetcher",e.useViewTransitionState="useViewTransitionState",e}(k||{}),M=function(e){return e.UseFetcher="useFetcher",e.UseFetchers="useFetchers",e.UseScrollRestoration="useScrollRestoration",e}(M||{});function B(e){let t=i.useContext(r.UNSAFE_DataRouterContext);return t||o.UNSAFE_invariant(!1),t}function H(e){let t=i.useContext(r.UNSAFE_DataRouterStateContext);return t||o.UNSAFE_invariant(!1),t}function I(e,t){let{target:n,replace:o,state:a,preventScrollReset:u,relative:s,unstable_viewTransition:c}=void 0===t?{}:t,l=r.useNavigate(),f=r.useLocation(),d=r.useResolvedPath(e,{relative:s});return i.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:u,relative:s,unstable_viewTransition:c})}}),[f,l,d,o,a,n,e,u,s,c])}let K=0,V=()=>"__"+String(++K)+"__";function z(){let{router:e}=B(k.UseSubmit),{basename:t}=i.useContext(r.UNSAFE_NavigationContext),n=r.UNSAFE_useRouteId();return i.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}=v(r,t);if(!1===o.navigate){let t=o.fetcherKey||V();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}=i.useContext(r.UNSAFE_NavigationContext),u=i.useContext(r.UNSAFE_RouteContext);u||o.UNSAFE_invariant(!1);let[c]=u.matches.slice(-1),l=s({},r.useResolvedPath(e||".",{relative:n})),f=r.useLocation();if(null==e){l.search=f.search;let e=new URLSearchParams(l.search);e.has("index")&&""===e.get("index")&&(e.delete("index"),l.search=e.toString()?"?"+e.toString():"")}return e&&"."!==e||!c.route.index||(l.search=l.search?l.search.replace(/^\?/,"?index&"):"?index"),"/"!==a&&(l.pathname="/"===l.pathname?a:o.joinPaths([a,l.pathname])),r.createPath(l)}const W="react-router-scroll-positions";let Y={};function J(e){let{getKey:t,storageKey:n}=void 0===e?{}:e,{router:a}=B(k.UseScrollRestoration),{restoreScrollPosition:u,preventScrollReset:c}=H(M.UseScrollRestoration),{basename:l}=i.useContext(r.UNSAFE_NavigationContext),f=r.useLocation(),d=r.useMatches(),m=r.useNavigation();i.useEffect((()=>(window.history.scrollRestoration="manual",()=>{window.history.scrollRestoration="auto"})),[]),function(e,t){let{capture:n}=t||{};i.useEffect((()=>{let t=null!=n?{capture:n}:void 0;return window.addEventListener("pagehide",e,t),()=>{window.removeEventListener("pagehide",e,t)}}),[e,n])}(i.useCallback((()=>{if("idle"===m.state){let e=(t?t(f,d):null)||f.key;Y[e]=window.scrollY}try{sessionStorage.setItem(n||W,JSON.stringify(Y))}catch(e){}window.history.scrollRestoration="auto"}),[n,t,m.state,f,d])),"undefined"!=typeof document&&(i.useLayoutEffect((()=>{try{let e=sessionStorage.getItem(n||W);e&&(Y=JSON.parse(e))}catch(e){}}),[n]),i.useLayoutEffect((()=>{let e=t&&"/"!==l?(e,n)=>t(s({},e,{pathname:o.stripBasename(e.pathname,l)||e.pathname}),n):t,n=null==a?void 0:a.enableScrollRestoration(Y,(()=>window.scrollY),e);return()=>n&&n()}),[a,l,t]),i.useLayoutEffect((()=>{if(!1!==u)if("number"!=typeof u){if(f.hash){let e=document.getElementById(decodeURIComponent(f.hash.slice(1)));if(e)return void e.scrollIntoView()}!0!==c&&window.scrollTo(0,0)}else window.scrollTo(0,u)}),[f,u,c]))}function G(e,t){void 0===t&&(t={});let n=i.useContext(E);null==n&&o.UNSAFE_invariant(!1);let{basename:a}=B(k.useViewTransitionState),u=r.useResolvedPath(e,{relative:t.relative});if(!n.isTransitioning)return!1;let s=o.stripBasename(n.currentLocation.pathname,a)||n.currentLocation.pathname,c=o.stripBasename(n.nextLocation.pathname,a)||n.nextLocation.pathname;return null!=o.matchPath(u.pathname,c)||null!=o.matchPath(u.pathname,s)}Object.defineProperty(e,"AbortedDeferredError",{enumerable:!0,get:function(){return r.AbortedDeferredError}}),Object.defineProperty(e,"Await",{enumerable:!0,get:function(){return r.Await}}),Object.defineProperty(e,"MemoryRouter",{enumerable:!0,get:function(){return r.MemoryRouter}}),Object.defineProperty(e,"Navigate",{enumerable:!0,get:function(){return r.Navigate}}),Object.defineProperty(e,"NavigationType",{enumerable:!0,get:function(){return r.NavigationType}}),Object.defineProperty(e,"Outlet",{enumerable:!0,get:function(){return r.Outlet}}),Object.defineProperty(e,"Route",{enumerable:!0,get:function(){return r.Route}}),Object.defineProperty(e,"Router",{enumerable:!0,get:function(){return r.Router}}),Object.defineProperty(e,"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}}),Object.defineProperty(e,"UNSAFE_ErrorResponseImpl",{enumerable:!0,get:function(){return o.UNSAFE_ErrorResponseImpl}}),e.BrowserRouter=function(e){let{basename:t,children:n,future:a,window:u}=e,s=i.useRef();null==s.current&&(s.current=o.createBrowserHistory({window:u,v5Compat:!0}));let c=s.current,[l,f]=i.useState({action:c.action,location:c.location}),{v7_startTransition:d}=a||{},m=i.useCallback((e=>{d&&P?P((()=>f(e))):f(e)}),[f,d]);return i.useLayoutEffect((()=>c.listen(m)),[c,m]),i.createElement(r.Router,{basename:t,children:n,location:l.location,navigationType:l.action,navigator:c,future:a})},e.Form=D,e.HashRouter=function(e){let{basename:t,children:n,future:a,window:u}=e,s=i.useRef();null==s.current&&(s.current=o.createHashHistory({window:u,v5Compat:!0}));let c=s.current,[l,f]=i.useState({action:c.action,location:c.location}),{v7_startTransition:d}=a||{},m=i.useCallback((e=>{d&&P?P((()=>f(e))):f(e)}),[f,d]);return i.useLayoutEffect((()=>c.listen(m)),[c,m]),i.createElement(r.Router,{basename:t,children:n,location:l.location,navigationType:l.action,navigator:c,future:a})},e.Link=T,e.NavLink=U,e.RouterProvider=function(e){let{fallbackElement:t,router:n,future:o}=e,[a,u]=i.useState(n.state),[s,c]=i.useState(),[l,f]=i.useState({isTransitioning:!1}),[d,m]=i.useState(),[p,b]=i.useState(),[h,v]=i.useState(),y=i.useRef(new Map),{v7_startTransition:g}=o||{},w=i.useCallback((e=>{g?function(e){P?P(e):e()}(e):e()}),[g]),R=i.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 i=null==n.window||null==n.window.document||"function"!=typeof n.window.document.startViewTransition;if(a&&!i){if(o){C((()=>{p&&(d&&d.resolve(),p.skipTransition()),f({isTransitioning:!0,flushSync:!0,currentLocation:a.currentLocation,nextLocation:a.nextLocation})}));let t=n.window.document.startViewTransition((()=>{C((()=>u(e)))}));return t.finished.finally((()=>{C((()=>{m(void 0),b(void 0),c(void 0),f({isTransitioning:!1})}))})),void C((()=>b(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?C((()=>u(e))):w((()=>u(e)))}),[n.window,p,d,y,w]);i.useLayoutEffect((()=>n.subscribe(R)),[n,R]),i.useEffect((()=>{l.isTransitioning&&!l.flushSync&&m(new N)}),[l]),i.useEffect((()=>{if(d&&s&&n.window){let e=s,t=d.promise,r=n.window.document.startViewTransition((async()=>{w((()=>u(e))),await t}));r.finished.finally((()=>{m(void 0),b(void 0),c(void 0),f({isTransitioning:!1})})),b(r)}}),[w,s,d,n.window]),i.useEffect((()=>{d&&s&&a.location.key===s.location.key&&d.resolve()}),[d,p,a.location,s]),i.useEffect((()=>{!l.isTransitioning&&h&&(c(h.state),f({isTransitioning:!0,flushSync:!1,currentLocation:h.currentLocation,nextLocation:h.nextLocation}),v(void 0))}),[l.isTransitioning,h]),i.useEffect((()=>{}),[]);let S=i.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]),O=n.basename||"/",A=i.useMemo((()=>({router:n,navigator:S,static:!1,basename:O})),[n,S,O]),x=i.useMemo((()=>({v7_relativeSplatPath:n.future.v7_relativeSplatPath})),[n.future.v7_relativeSplatPath]);return i.createElement(i.Fragment,null,i.createElement(r.UNSAFE_DataRouterContext.Provider,{value:A},i.createElement(r.UNSAFE_DataRouterStateContext.Provider,{value:a},i.createElement(_.Provider,{value:y.current},i.createElement(E.Provider,{value:l},i.createElement(r.Router,{basename:O,location:a.location,navigationType:a.historyAction,navigator:S,future:x},a.initialized||n.future.v7_partialHydration?i.createElement(j,{routes:n.routes,future:n.future,state:a}):t))))),null)},e.ScrollRestoration=function(e){let{getKey:t,storageKey:n}=e;return J({getKey:t,storageKey:n}),null},e.UNSAFE_FetchersContext=_,e.UNSAFE_ViewTransitionContext=E,e.UNSAFE_useScrollRestoration=J,e.createBrowserRouter=function(e,t){return o.createRouter({basename:null==t?void 0:t.basename,future:s({},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)||R(),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:s({},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)||R(),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=m,e.unstable_HistoryRouter=function(e){let{basename:t,children:n,future:o,history:a}=e,[u,s]=i.useState({action:a.action,location:a.location}),{v7_startTransition:c}=o||{},l=i.useCallback((e=>{c&&P?P((()=>s(e))):s(e)}),[s,c]);return i.useLayoutEffect((()=>a.listen(l)),[a,l]),i.createElement(r.Router,{basename:t,children:n,location:u.location,navigationType:u.action,navigator:a,future:o})},e.unstable_usePrompt=function(e){let{when:t,message:n}=e,o=r.useBlocker(t);i.useEffect((()=>{if("blocked"===o.state){window.confirm(n)?setTimeout(o.proceed,0):o.reset()}}),[o,n]),i.useEffect((()=>{"blocked"!==o.state||t||o.reset()}),[o,t])},e.unstable_useViewTransitionState=G,e.useBeforeUnload=function(e,t){let{capture:n}=t||{};i.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(k.UseFetcher),u=H(M.UseFetcher),c=i.useContext(_),l=i.useContext(r.UNSAFE_RouteContext),f=null==(t=l.matches[l.matches.length-1])?void 0:t.route.id;c||o.UNSAFE_invariant(!1),l||o.UNSAFE_invariant(!1),null==f&&o.UNSAFE_invariant(!1);let d=A?A():"",[m,p]=i.useState(n||d);n&&n!==m?p(n):m||p(V()),i.useEffect((()=>(a.getFetcher(m),()=>{a.deleteFetcher(m)})),[a,m]);let b=i.useCallback(((e,t)=>{f||o.UNSAFE_invariant(!1),a.fetch(m,f,e,t)}),[m,f,a]),h=z(),v=i.useCallback(((e,t)=>{h(e,s({},t,{navigate:!1,fetcherKey:m}))}),[m,h]),y=i.useMemo((()=>i.forwardRef(((e,t)=>i.createElement(D,s({},e,{navigate:!1,fetcherKey:m,ref:t}))))),[m]),g=u.fetchers.get(m)||o.IDLE_FETCHER,w=c.get(m);return i.useMemo((()=>s({Form:y,submit:v,load:b},g,{data:w})),[y,v,b,g,w])},e.useFetchers=function(){let e=H(M.UseFetchers);return Array.from(e.fetchers.entries()).map((e=>{let[t,n]=e;return s({},n,{key:t})}))},e.useFormAction=q,e.useLinkClickHandler=I,e.useSearchParams=function(e){let t=i.useRef(m(e)),n=i.useRef(!1),o=r.useLocation(),a=i.useMemo((()=>function(e,t){let n=m(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]),u=r.useNavigate(),s=i.useCallback(((e,t)=>{const r=m("function"==typeof e?e(a):e);n.current=!0,u("?"+r,t)}),[u,a]);return[a,s]},e.useSubmit=z,Object.defineProperty(e,"__esModule",{value:!0})})); | ||
//# sourceMappingURL=react-router-dom.production.min.js.map |
{ | ||
"name": "react-router-dom", | ||
"version": "0.0.0-experimental-f728258d", | ||
"version": "0.0.0-experimental-f7aa35148", | ||
"description": "Declarative routing for React web applications", | ||
@@ -26,4 +26,4 @@ "keywords": [ | ||
"dependencies": { | ||
"@remix-run/router": "0.0.0-experimental-f728258d", | ||
"react-router": "0.0.0-experimental-f728258d" | ||
"@remix-run/router": "0.0.0-experimental-f7aa35148", | ||
"react-router": "0.0.0-experimental-f7aa35148" | ||
}, | ||
@@ -50,2 +50,2 @@ "devDependencies": { | ||
} | ||
} | ||
} |
import * as React from "react"; | ||
import type { Router as RemixRouter, StaticHandlerContext, CreateStaticHandlerOptions as RouterCreateStaticHandlerOptions } from "@remix-run/router"; | ||
import type { Location, RouteObject } from "react-router-dom"; | ||
import type { Router as RemixRouter, StaticHandlerContext, CreateStaticHandlerOptions as RouterCreateStaticHandlerOptions, FutureConfig as RouterFutureConfig } from "@remix-run/router"; | ||
import type { FutureConfig, Location, RouteObject } from "react-router-dom"; | ||
export interface StaticRouterProps { | ||
@@ -8,8 +8,9 @@ basename?: string; | ||
location: Partial<Location> | string; | ||
future?: Partial<FutureConfig>; | ||
} | ||
/** | ||
* 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, future, }: StaticRouterProps): React.JSX.Element; | ||
export { StaticHandlerContext }; | ||
@@ -26,5 +27,7 @@ export interface StaticRouterProviderProps { | ||
*/ | ||
export declare function StaticRouterProvider({ context, router, hydrate, nonce, }: StaticRouterProviderProps): JSX.Element; | ||
export declare function StaticRouterProvider({ context, router, hydrate, nonce, }: StaticRouterProviderProps): React.JSX.Element; | ||
type CreateStaticHandlerOptions = Omit<RouterCreateStaticHandlerOptions, "detectErrorBoundary" | "mapRouteProperties">; | ||
export declare function createStaticHandler(routes: RouteObject[], opts?: CreateStaticHandlerOptions): import("@remix-run/router").StaticHandler; | ||
export declare function createStaticRouter(routes: RouteObject[], context: StaticHandlerContext): RemixRouter; | ||
export declare function createStaticRouter(routes: RouteObject[], context: StaticHandlerContext, opts?: { | ||
future?: Partial<Pick<RouterFutureConfig, "v7_partialHydration" | "v7_relativeSplatPath">>; | ||
}): RemixRouter; |
@@ -31,3 +31,3 @@ 'use strict'; | ||
/** | ||
* 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. | ||
@@ -38,3 +38,4 @@ */ | ||
children, | ||
location: locationProp = "/" | ||
location: locationProp = "/", | ||
future | ||
}) { | ||
@@ -49,3 +50,3 @@ if (typeof locationProp === "string") { | ||
hash: locationProp.hash || "", | ||
state: locationProp.state || null, | ||
state: locationProp.state != null ? locationProp.state : null, | ||
key: locationProp.key || "default" | ||
@@ -60,2 +61,3 @@ }; | ||
navigator: staticNavigator, | ||
future: future, | ||
static: true | ||
@@ -82,2 +84,3 @@ }); | ||
}; | ||
let fetchersContext = new Map(); | ||
let hydrateScript = ""; | ||
@@ -104,2 +107,8 @@ if (hydrate !== false) { | ||
value: state | ||
}, /*#__PURE__*/React__namespace.createElement(reactRouterDom.UNSAFE_FetchersContext.Provider, { | ||
value: fetchersContext | ||
}, /*#__PURE__*/React__namespace.createElement(reactRouterDom.UNSAFE_ViewTransitionContext.Provider, { | ||
value: { | ||
isTransitioning: false | ||
} | ||
}, /*#__PURE__*/React__namespace.createElement(reactRouterDom.Router, { | ||
@@ -110,7 +119,11 @@ basename: dataRouterContext.basename, | ||
navigator: dataRouterContext.navigator, | ||
static: dataRouterContext.static | ||
static: dataRouterContext.static, | ||
future: { | ||
v7_relativeSplatPath: router$1.future.v7_relativeSplatPath | ||
} | ||
}, /*#__PURE__*/React__namespace.createElement(DataRoutes, { | ||
routes: router$1.routes, | ||
future: router$1.future, | ||
state: state | ||
})))), hydrateScript ? /*#__PURE__*/React__namespace.createElement("script", { | ||
})))))), hydrateScript ? /*#__PURE__*/React__namespace.createElement("script", { | ||
suppressHydrationWarning: true, | ||
@@ -125,5 +138,6 @@ nonce: nonce, | ||
routes, | ||
future, | ||
state | ||
}) { | ||
return reactRouter.UNSAFE_useRoutesImpl(routes, undefined, state); | ||
return reactRouter.UNSAFE_useRoutesImpl(routes, undefined, state, future); | ||
} | ||
@@ -186,3 +200,3 @@ function serializeErrors(errors) { | ||
} | ||
function createStaticRouter(routes, context) { | ||
function createStaticRouter(routes, context, opts = {}) { | ||
let manifest = {}; | ||
@@ -205,2 +219,12 @@ let dataRoutes = router.UNSAFE_convertRoutesToDataRoutes(routes, reactRouter.UNSAFE_mapRouteProperties, undefined, manifest); | ||
}, | ||
get future() { | ||
return { | ||
v7_fetcherPersist: false, | ||
v7_normalizeFormMethod: false, | ||
v7_partialHydration: opts.future?.v7_partialHydration === true, | ||
v7_prependBasename: false, | ||
v7_relativeSplatPath: opts.future?.v7_relativeSplatPath === true, | ||
v7_skipActionErrorRevalidation: false | ||
}; | ||
}, | ||
get state() { | ||
@@ -226,2 +250,5 @@ return { | ||
}, | ||
get window() { | ||
return undefined; | ||
}, | ||
initialize() { | ||
@@ -262,2 +289,5 @@ throw msg("initialize"); | ||
}, | ||
patchRoutes() { | ||
throw msg("patchRoutes"); | ||
}, | ||
_internalFetchControllers: new Map(), | ||
@@ -274,10 +304,15 @@ _internalActiveDeferreds: new Map(), | ||
function encodeLocation(to) { | ||
// Locations should already be encoded on the server, so just return as-is | ||
let path = typeof to === "string" ? reactRouterDom.parsePath(to) : to; | ||
let href = typeof to === "string" ? to : reactRouterDom.createPath(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 | ||
}; | ||
} | ||
const ABSOLUTE_URL_REGEX = /^(?:[a-z][a-z0-9+.-]*:|\/\/)/i; | ||
// This utility is based on https://github.com/zertosh/htmlescape | ||
@@ -284,0 +319,0 @@ // License: https://github.com/zertosh/htmlescape/blob/0527ca7156a524d256101bb310a9f970f63078ad/LICENSE |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
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
Sorry, the diff of this file is not supported yet
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
893349
6548
26
+ Added@remix-run/router@0.0.0-experimental-f7aa35148(transitive)
+ Addedreact-router@0.0.0-experimental-f7aa35148(transitive)
- Removed@remix-run/router@0.0.0-experimental-f728258d(transitive)
- Removedreact-router@0.0.0-experimental-f728258d(transitive)