react-router-dom
Advanced tools
Comparing version 0.0.0-experimental-cf9637ce to 0.0.0-experimental-cffa549a1
729
CHANGELOG.md
# `react-router-dom` | ||
## 6.25.0 | ||
### Minor Changes | ||
- Stabilize `future.unstable_skipActionErrorRevalidation` as `future.v7_skipActionErrorRevalidation` ([#11769](https://github.com/remix-run/react-router/pull/11769)) | ||
- When this flag is enabled, actions will not automatically trigger a revalidation if they return/throw a `Response` with a `4xx`/`5xx` status code | ||
- You may still opt-into revalidation via `shouldRevalidate` | ||
- This also changes `shouldRevalidate`'s `unstable_actionStatus` parameter to `actionStatus` | ||
### Patch Changes | ||
- Updated dependencies: | ||
- `react-router@6.25.0` | ||
- `@remix-run/router@1.18.0` | ||
## 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 | ||
### Patch Changes | ||
- Properly decode element id when emulating hash scrolling via `<ScrollRestoration>` ([#10682](https://github.com/remix-run/react-router/pull/10682)) | ||
- Add missing `<Form state>` prop to populate `history.state` on submission navigations ([#10630](https://github.com/remix-run/react-router/pull/10630)) | ||
- Support proper hydration of `Error` subclasses such as `ReferenceError`/`TypeError` ([#10633](https://github.com/remix-run/react-router/pull/10633)) | ||
- Updated dependencies: | ||
- `@remix-run/router@1.7.2` | ||
- `react-router@6.14.2` | ||
## 6.14.1 | ||
### Patch Changes | ||
- Updated dependencies: | ||
- `react-router@6.14.1` | ||
- `@remix-run/router@1.7.1` | ||
## 6.14.0 | ||
### Minor Changes | ||
- Add support for `application/json` and `text/plain` encodings for `useSubmit`/`fetcher.submit`. To reflect these additional types, `useNavigation`/`useFetcher` now also contain `navigation.json`/`navigation.text` and `fetcher.json`/`fetcher.text` which include the json/text submission if applicable ([#10413](https://github.com/remix-run/react-router/pull/10413)) | ||
```jsx | ||
// The default behavior will still serialize as FormData | ||
function Component() { | ||
let navigation = useNavigation(); | ||
let submit = useSubmit(); | ||
submit({ key: "value" }, { method: "post" }); | ||
// navigation.formEncType => "application/x-www-form-urlencoded" | ||
// navigation.formData => FormData instance | ||
} | ||
async function action({ request }) { | ||
// request.headers.get("Content-Type") => "application/x-www-form-urlencoded" | ||
// await request.formData() => FormData instance | ||
} | ||
``` | ||
```js | ||
// Opt-into JSON encoding with `encType: "application/json"` | ||
function Component() { | ||
let navigation = useNavigation(); | ||
let submit = useSubmit(); | ||
submit({ key: "value" }, { method: "post", encType: "application/json" }); | ||
// navigation.formEncType => "application/json" | ||
// navigation.json => { key: "value" } | ||
} | ||
async function action({ request }) { | ||
// request.headers.get("Content-Type") => "application/json" | ||
// await request.json() => { key: "value" } | ||
} | ||
``` | ||
```js | ||
// Opt-into text encoding with `encType: "text/plain"` | ||
function Component() { | ||
let navigation = useNavigation(); | ||
let submit = useSubmit(); | ||
submit("Text submission", { method: "post", encType: "text/plain" }); | ||
// navigation.formEncType => "text/plain" | ||
// navigation.text => "Text submission" | ||
} | ||
async function action({ request }) { | ||
// request.headers.get("Content-Type") => "text/plain" | ||
// await request.text() => "Text submission" | ||
} | ||
``` | ||
### Patch Changes | ||
- When submitting a form from a `submitter` element, prefer the built-in `new FormData(form, submitter)` instead of the previous manual approach in modern browsers (those that support the new `submitter` parameter) ([#9865](https://github.com/remix-run/react-router/pull/9865), [#10627](https://github.com/remix-run/react-router/pull/10627)) | ||
- For browsers that don't support it, we continue to just append the submit button's entry to the end, and we also add rudimentary support for `type="image"` buttons | ||
- If developers want full spec-compliant support for legacy browsers, they can use the `formdata-submitter-polyfill` | ||
- Call `window.history.pushState/replaceState` before updating React Router state (instead of after) so that `window.location` matches `useLocation` during synchronous React 17 rendering ([#10448](https://github.com/remix-run/react-router/pull/10448)) | ||
- ⚠️ However, generally apps should not be relying on `window.location` and should always reference `useLocation` when possible, as `window.location` will not be in sync 100% of the time (due to `popstate` events, concurrent mode, etc.) | ||
- Fix `tsc --skipLibCheck:false` issues on React 17 ([#10622](https://github.com/remix-run/react-router/pull/10622)) | ||
- Upgrade `typescript` to 5.1 ([#10581](https://github.com/remix-run/react-router/pull/10581)) | ||
- Updated dependencies: | ||
- `react-router@6.14.0` | ||
- `@remix-run/router@1.7.0` | ||
## 6.13.0 | ||
### Minor Changes | ||
- Move [`React.startTransition`](https://react.dev/reference/react/startTransition) usage behind a [future flag](https://reactrouter.com/en/main/guides/api-development-strategy) to avoid issues with existing incompatible `Suspense` usages. We recommend folks adopting this flag to be better compatible with React concurrent mode, but if you run into issues you can continue without the use of `startTransition` until v7. Issues usually boils down to creating net-new promises during the render cycle, so if you run into issues you should either lift your promise creation out of the render cycle or put it behind a `useMemo`. ([#10596](https://github.com/remix-run/react-router/pull/10596)) | ||
Existing behavior will no longer include `React.startTransition`: | ||
```jsx | ||
<BrowserRouter> | ||
<Routes>{/*...*/}</Routes> | ||
</BrowserRouter> | ||
<RouterProvider router={router} /> | ||
``` | ||
If you wish to enable `React.startTransition`, pass the future flag to your component: | ||
```jsx | ||
<BrowserRouter future={{ v7_startTransition: true }}> | ||
<Routes>{/*...*/}</Routes> | ||
</BrowserRouter> | ||
<RouterProvider router={router} future={{ v7_startTransition: true }}/> | ||
``` | ||
### Patch Changes | ||
- Work around webpack/terser `React.startTransition` minification bug in production mode ([#10588](https://github.com/remix-run/react-router/pull/10588)) | ||
- Updated dependencies: | ||
- `react-router@6.13.0` | ||
## 6.12.1 | ||
> \[!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. | ||
### Patch Changes | ||
- Adjust feature detection of `React.startTransition` to fix webpack + react 17 compilation error ([#10569](https://github.com/remix-run/react-router/pull/10569)) | ||
- Updated dependencies: | ||
- `react-router@6.12.1` | ||
## 6.12.0 | ||
### Minor Changes | ||
- Wrap internal router state updates with `React.startTransition` if it exists ([#10438](https://github.com/remix-run/react-router/pull/10438)) | ||
### Patch Changes | ||
- Re-throw `DOMException` (`DataCloneError`) when attempting to perform a `PUSH` navigation with non-serializable state. ([#10427](https://github.com/remix-run/react-router/pull/10427)) | ||
- Updated dependencies: | ||
- `@remix-run/router@1.6.3` | ||
- `react-router@6.12.0` | ||
## 6.11.2 | ||
### Patch Changes | ||
- Export `SetURLSearchParams` type ([#10444](https://github.com/remix-run/react-router/pull/10444)) | ||
- Updated dependencies: | ||
- `react-router@6.11.2` | ||
- `@remix-run/router@1.6.2` | ||
## 6.11.1 | ||
### Patch Changes | ||
- Updated dependencies: | ||
- `react-router@6.11.1` | ||
- `@remix-run/router@1.6.1` | ||
## 6.11.0 | ||
### Minor Changes | ||
- Enable `basename` support in `useFetcher` ([#10336](https://github.com/remix-run/react-router/pull/10336)) | ||
- If you were previously working around this issue by manually prepending the `basename` then you will need to remove the manually prepended `basename` from your `fetcher` calls (`fetcher.load('/basename/route') -> fetcher.load('/route')`) | ||
### Patch Changes | ||
- Fix inadvertent re-renders when using `Component` instead of `element` on a route definition ([#10287](https://github.com/remix-run/react-router/pull/10287)) | ||
- Fail gracefully on `<Link to="//">` and other invalid URL values ([#10367](https://github.com/remix-run/react-router/pull/10367)) | ||
- Switched from `useSyncExternalStore` to `useState` for internal `@remix-run/router` router state syncing in `<RouterProvider>`. We found some [subtle bugs](https://codesandbox.io/s/use-sync-external-store-loop-9g7b81) where router state updates got propagated _before_ other normal `useState` updates, which could lead to footguns in `useEffect` calls. ([#10377](https://github.com/remix-run/react-router/pull/10377), [#10409](https://github.com/remix-run/react-router/pull/10409)) | ||
- Add static prop to `StaticRouterProvider`'s internal `Router` component ([#10401](https://github.com/remix-run/react-router/pull/10401)) | ||
- When using a `RouterProvider`, `useNavigate`/`useSubmit`/`fetcher.submit` are now stable across location changes, since we can handle relative routing via the `@remix-run/router` instance and get rid of our dependence on `useLocation()`. When using `BrowserRouter`, these hooks remain unstable across location changes because they still rely on `useLocation()`. ([#10336](https://github.com/remix-run/react-router/pull/10336)) | ||
- Updated dependencies: | ||
- `react-router@6.11.0` | ||
- `@remix-run/router@1.6.0` | ||
## 6.10.0 | ||
### Minor Changes | ||
- Added support for [**Future Flags**](https://reactrouter.com/en/main/guides/api-development-strategy) in React Router. The first flag being introduced is `future.v7_normalizeFormMethod` which will normalize the exposed `useNavigation()/useFetcher()` `formMethod` fields as uppercase HTTP methods to align with the `fetch()` behavior. ([#10207](https://github.com/remix-run/react-router/pull/10207)) | ||
- When `future.v7_normalizeFormMethod === false` (default v6 behavior), | ||
- `useNavigation().formMethod` is lowercase | ||
- `useFetcher().formMethod` is lowercase | ||
- When `future.v7_normalizeFormMethod === true`: | ||
- `useNavigation().formMethod` is uppercase | ||
- `useFetcher().formMethod` is uppercase | ||
### Patch Changes | ||
- Fix `createStaticHandler` to also check for `ErrorBoundary` on routes in addition to `errorElement` ([#10190](https://github.com/remix-run/react-router/pull/10190)) | ||
- Updated dependencies: | ||
- `@remix-run/router@1.5.0` | ||
- `react-router@6.10.0` | ||
## 6.9.0 | ||
### Minor Changes | ||
- React Router now supports an alternative way to define your route `element` and `errorElement` fields as React Components instead of React Elements. You can instead pass a React Component to the new `Component` and `ErrorBoundary` fields if you choose. There is no functional difference between the two, so use whichever approach you prefer 😀. You shouldn't be defining both, but if you do `Component`/`ErrorBoundary` will "win". ([#10045](https://github.com/remix-run/react-router/pull/10045)) | ||
**Example JSON Syntax** | ||
```jsx | ||
// Both of these work the same: | ||
const elementRoutes = [{ | ||
path: '/', | ||
element: <Home />, | ||
errorElement: <HomeError />, | ||
}] | ||
const componentRoutes = [{ | ||
path: '/', | ||
Component: Home, | ||
ErrorBoundary: HomeError, | ||
}] | ||
function Home() { ... } | ||
function HomeError() { ... } | ||
``` | ||
**Example JSX Syntax** | ||
```jsx | ||
// Both of these work the same: | ||
const elementRoutes = createRoutesFromElements( | ||
<Route path='/' element={<Home />} errorElement={<HomeError /> } /> | ||
); | ||
const componentRoutes = createRoutesFromElements( | ||
<Route path='/' Component={Home} ErrorBoundary={HomeError} /> | ||
); | ||
function Home() { ... } | ||
function HomeError() { ... } | ||
``` | ||
- **Introducing Lazy Route Modules!** ([#10045](https://github.com/remix-run/react-router/pull/10045)) | ||
In order to keep your application bundles small and support code-splitting of your routes, we've introduced a new `lazy()` route property. This is an async function that resolves the non-route-matching portions of your route definition (`loader`, `action`, `element`/`Component`, `errorElement`/`ErrorBoundary`, `shouldRevalidate`, `handle`). | ||
Lazy routes are resolved on initial load and during the `loading` or `submitting` phase of a navigation or fetcher call. You cannot lazily define route-matching properties (`path`, `index`, `children`) since we only execute your lazy route functions after we've matched known routes. | ||
Your `lazy` functions will typically return the result of a dynamic import. | ||
```jsx | ||
// In this example, we assume most folks land on the homepage so we include that | ||
// in our critical-path bundle, but then we lazily load modules for /a and /b so | ||
// they don't load until the user navigates to those routes | ||
let routes = createRoutesFromElements( | ||
<Route path="/" element={<Layout />}> | ||
<Route index element={<Home />} /> | ||
<Route path="a" lazy={() => import("./a")} /> | ||
<Route path="b" lazy={() => import("./b")} /> | ||
</Route> | ||
); | ||
``` | ||
Then in your lazy route modules, export the properties you want defined for the route: | ||
```jsx | ||
export async function loader({ request }) { | ||
let data = await fetchData(request); | ||
return json(data); | ||
} | ||
// Export a `Component` directly instead of needing to create a React Element from it | ||
export function Component() { | ||
let data = useLoaderData(); | ||
return ( | ||
<> | ||
<h1>You made it!</h1> | ||
<p>{data}</p> | ||
</> | ||
); | ||
} | ||
// Export an `ErrorBoundary` directly instead of needing to create a React Element from it | ||
export function ErrorBoundary() { | ||
let error = useRouteError(); | ||
return isRouteErrorResponse(error) ? ( | ||
<h1> | ||
{error.status} {error.statusText} | ||
</h1> | ||
) : ( | ||
<h1>{error.message || error}</h1> | ||
); | ||
} | ||
``` | ||
An example of this in action can be found in the [`examples/lazy-loading-router-provider`](https://github.com/remix-run/react-router/tree/main/examples/lazy-loading-router-provider) directory of the repository. | ||
🙌 Huge thanks to @rossipedia for the [Initial Proposal](https://github.com/remix-run/react-router/discussions/9826) and [POC Implementation](https://github.com/remix-run/react-router/pull/9830). | ||
- Updated dependencies: | ||
- `react-router@6.9.0` | ||
- `@remix-run/router@1.4.0` | ||
## 6.8.2 | ||
### Patch Changes | ||
- Treat same-origin absolute URLs in `<Link to>` as external if they are outside of the router `basename` ([#10135](https://github.com/remix-run/react-router/pull/10135)) | ||
- Fix `useBlocker` to return `IDLE_BLOCKER` during SSR ([#10046](https://github.com/remix-run/react-router/pull/10046)) | ||
- Fix SSR of absolute `<Link to>` urls ([#10112](https://github.com/remix-run/react-router/pull/10112)) | ||
- Properly escape HTML characters in `StaticRouterProvider` serialized hydration data ([#10068](https://github.com/remix-run/react-router/pull/10068)) | ||
- Updated dependencies: | ||
- `@remix-run/router@1.3.3` | ||
- `react-router@6.8.2` | ||
## 6.8.1 | ||
@@ -145,3 +868,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). | ||
@@ -172,5 +895,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 |
@@ -1,4 +0,3 @@ | ||
import type { FormEncType, FormMethod } from "@remix-run/router"; | ||
import type { RelativeRoutingType } from "react-router"; | ||
export declare const defaultMethod = "get"; | ||
import type { FormEncType, HTMLFormMethod, RelativeRoutingType } from "@remix-run/router"; | ||
export declare const defaultMethod: HTMLFormMethod; | ||
export declare function isHtmlElement(object: any): object is HTMLElement; | ||
@@ -8,6 +7,6 @@ export declare function isButtonElement(object: any): object is HTMLButtonElement; | ||
export declare function isInputElement(object: any): object is HTMLInputElement; | ||
declare type LimitedMouseEvent = Pick<MouseEvent, "button" | "metaKey" | "altKey" | "ctrlKey" | "shiftKey">; | ||
type LimitedMouseEvent = Pick<MouseEvent, "button" | "metaKey" | "altKey" | "ctrlKey" | "shiftKey">; | ||
export declare function shouldProcessLinkClick(event: LimitedMouseEvent, target?: string): boolean; | ||
export declare type ParamKeyValuePair = [string, string]; | ||
export declare type URLSearchParamsInit = string | ParamKeyValuePair[] | Record<string, string | string[]> | URLSearchParams; | ||
export type ParamKeyValuePair = [string, string]; | ||
export type URLSearchParamsInit = string | ParamKeyValuePair[] | Record<string, string | string[]> | URLSearchParams; | ||
/** | ||
@@ -36,3 +35,15 @@ * Creates a URLSearchParams object using the given initializer. | ||
export declare function getSearchParamsForLocation(locationSearch: string, defaultSearchParams: URLSearchParams | null): URLSearchParams; | ||
export interface SubmitOptions { | ||
type JsonObject = { | ||
[Key in string]: JsonValue; | ||
} & { | ||
[Key in string]?: JsonValue | undefined; | ||
}; | ||
type JsonArray = JsonValue[] | readonly JsonValue[]; | ||
type JsonPrimitive = string | number | boolean | null; | ||
type JsonValue = JsonPrimitive | JsonObject | JsonArray; | ||
export type SubmitTarget = HTMLFormElement | HTMLButtonElement | HTMLInputElement | FormData | URLSearchParams | JsonValue | null; | ||
/** | ||
* Submit options shared by both navigations and fetchers | ||
*/ | ||
interface SharedSubmitOptions { | ||
/** | ||
@@ -42,13 +53,10 @@ * The HTTP method used to submit the form. Overrides `<form method>`. | ||
*/ | ||
method?: FormMethod; | ||
method?: HTMLFormMethod; | ||
/** | ||
* The action URL path used to submit the form. Overrides `<form action>`. | ||
* Defaults to the path of the current route. | ||
* | ||
* Note: It is assumed the path is already resolved. If you need to resolve a | ||
* relative path, use `useFormAction`. | ||
*/ | ||
action?: string; | ||
/** | ||
* The action URL used to submit the form. Overrides `<form encType>`. | ||
* The encoding used to submit the form. Overrides `<form encType>`. | ||
* Defaults to "application/x-www-form-urlencoded". | ||
@@ -58,8 +66,2 @@ */ | ||
/** | ||
* Set `true` to replace the current entry in the browser's history stack | ||
* instead of creating a new one (i.e. stay on "the same page"). Defaults | ||
* to `false`. | ||
*/ | ||
replace?: boolean; | ||
/** | ||
* Determines whether the form action is relative to the route hierarchy or | ||
@@ -75,11 +77,46 @@ * the pathname. Use this if you want to opt out of navigating the route | ||
preventScrollReset?: boolean; | ||
/** | ||
* Enable flushSync for this submission's state updates | ||
*/ | ||
unstable_flushSync?: boolean; | ||
} | ||
export declare function getFormSubmissionInfo(target: HTMLFormElement | HTMLButtonElement | HTMLInputElement | FormData | URLSearchParams | { | ||
[name: string]: string; | ||
} | null, defaultAction: string, options: SubmitOptions): { | ||
url: URL; | ||
/** | ||
* Submit options available to fetchers | ||
*/ | ||
export interface FetcherSubmitOptions extends SharedSubmitOptions { | ||
} | ||
/** | ||
* Submit options available to navigations | ||
*/ | ||
export interface SubmitOptions extends FetcherSubmitOptions { | ||
/** | ||
* Set `true` to replace the current entry in the browser's history stack | ||
* instead of creating a new one (i.e. stay on "the same page"). Defaults | ||
* to `false`. | ||
*/ | ||
replace?: boolean; | ||
/** | ||
* State object to add to the history stack entry for this navigation | ||
*/ | ||
state?: any; | ||
/** | ||
* Indicate a specific fetcherKey to use when using navigate=false | ||
*/ | ||
fetcherKey?: string; | ||
/** | ||
* navigate=false will use a fetcher instead of a navigation | ||
*/ | ||
navigate?: boolean; | ||
/** | ||
* Enable view transitions on this submission navigation | ||
*/ | ||
unstable_viewTransition?: boolean; | ||
} | ||
export declare function getFormSubmissionInfo(target: SubmitTarget, basename: string): { | ||
action: string | null; | ||
method: string; | ||
encType: string; | ||
formData: FormData; | ||
formData: FormData | undefined; | ||
body: any; | ||
}; | ||
export {}; |
@@ -6,28 +6,57 @@ /** | ||
import * as React from "react"; | ||
import type { NavigateOptions, RelativeRoutingType, RouteObject, To } from "react-router"; | ||
import type { Fetcher, FormEncType, FormMethod, GetScrollRestorationKeyFunction, History, HydrationState, Router as RemixRouter } from "@remix-run/router"; | ||
import type { SubmitOptions, ParamKeyValuePair, URLSearchParamsInit } from "./dom"; | ||
import type { FutureConfig, Location, NavigateOptions, RelativeRoutingType, RouteObject, RouterProviderProps, To, unstable_PatchRoutesOnMissFunction } from "react-router"; | ||
import type { unstable_DataStrategyFunction, unstable_DataStrategyFunctionArgs, unstable_DataStrategyMatch, Fetcher, FormEncType, FormMethod, FutureConfig as RouterFutureConfig, GetScrollRestorationKeyFunction, History, HTMLFormMethod, HydrationState, Router as RemixRouter, V7_FormMethod, BlockerFunction } from "@remix-run/router"; | ||
import { UNSAFE_ErrorResponseImpl as ErrorResponseImpl } from "@remix-run/router"; | ||
import type { SubmitOptions, ParamKeyValuePair, URLSearchParamsInit, SubmitTarget, FetcherSubmitOptions } from "./dom"; | ||
import { createSearchParams } from "./dom"; | ||
export type { FormEncType, FormMethod, GetScrollRestorationKeyFunction, ParamKeyValuePair, SubmitOptions, URLSearchParamsInit, }; | ||
export { createSearchParams }; | ||
export type { ActionFunction, ActionFunctionArgs, AwaitProps, unstable_Blocker, unstable_BlockerFunction, DataRouteMatch, DataRouteObject, Fetcher, Hash, IndexRouteObject, IndexRouteProps, JsonFunction, LayoutRouteProps, LoaderFunction, LoaderFunctionArgs, Location, MemoryRouterProps, NavigateFunction, NavigateOptions, NavigateProps, Navigation, Navigator, NonIndexRouteObject, OutletProps, Params, ParamParseKey, Path, PathMatch, Pathname, PathPattern, PathRouteProps, RedirectFunction, RelativeRoutingType, RouteMatch, RouteObject, RouteProps, RouterProps, RouterProviderProps, RoutesProps, Search, ShouldRevalidateFunction, To, } from "react-router"; | ||
export { AbortedDeferredError, Await, MemoryRouter, Navigate, NavigationType, Outlet, Route, Router, RouterProvider, Routes, createMemoryRouter, createPath, createRoutesFromChildren, createRoutesFromElements, defer, isRouteErrorResponse, generatePath, json, matchPath, matchRoutes, parsePath, redirect, renderMatches, resolvePath, useActionData, useAsyncError, useAsyncValue, unstable_useBlocker, useHref, useInRouterContext, useLoaderData, useLocation, useMatch, useMatches, useNavigate, useNavigation, useNavigationType, useOutlet, useOutletContext, useParams, useResolvedPath, useRevalidator, useRouteError, useRouteLoaderData, useRoutes, } from "react-router"; | ||
export type { unstable_DataStrategyFunction, unstable_DataStrategyFunctionArgs, unstable_DataStrategyMatch, FormEncType, FormMethod, GetScrollRestorationKeyFunction, ParamKeyValuePair, SubmitOptions, URLSearchParamsInit, V7_FormMethod, }; | ||
export { createSearchParams, ErrorResponseImpl as UNSAFE_ErrorResponseImpl }; | ||
export type { ActionFunction, ActionFunctionArgs, AwaitProps, Blocker, BlockerFunction, DataRouteMatch, DataRouteObject, ErrorResponse, Fetcher, FutureConfig, Hash, IndexRouteObject, IndexRouteProps, JsonFunction, LazyRouteFunction, LayoutRouteProps, LoaderFunction, LoaderFunctionArgs, Location, MemoryRouterProps, NavigateFunction, NavigateOptions, NavigateProps, Navigation, Navigator, NonIndexRouteObject, OutletProps, Params, ParamParseKey, Path, PathMatch, Pathname, PathParam, PathPattern, PathRouteProps, RedirectFunction, RelativeRoutingType, RouteMatch, RouteObject, RouteProps, RouterProps, RouterProviderProps, RoutesProps, Search, ShouldRevalidateFunction, ShouldRevalidateFunctionArgs, To, UIMatch, unstable_HandlerResult, unstable_PatchRoutesOnMissFunction, } from "react-router"; | ||
export { AbortedDeferredError, Await, MemoryRouter, Navigate, NavigationType, Outlet, Route, Router, Routes, createMemoryRouter, createPath, createRoutesFromChildren, createRoutesFromElements, defer, isRouteErrorResponse, generatePath, json, matchPath, matchRoutes, parsePath, redirect, redirectDocument, renderMatches, resolvePath, useActionData, useAsyncError, useAsyncValue, useBlocker, useHref, useInRouterContext, useLoaderData, useLocation, useMatch, useMatches, useNavigate, useNavigation, useNavigationType, useOutlet, useOutletContext, useParams, useResolvedPath, useRevalidator, useRouteError, useRouteLoaderData, useRoutes, } from "react-router"; | ||
/** @internal */ | ||
export { UNSAFE_DataRouterContext, UNSAFE_DataRouterStateContext, UNSAFE_NavigationContext, UNSAFE_LocationContext, UNSAFE_RouteContext, UNSAFE_enhanceManualRouteObjects, } from "react-router"; | ||
export { UNSAFE_DataRouterContext, UNSAFE_DataRouterStateContext, UNSAFE_NavigationContext, UNSAFE_LocationContext, UNSAFE_RouteContext, UNSAFE_useRouteId, } from "react-router"; | ||
declare global { | ||
var __staticRouterHydrationData: HydrationState | undefined; | ||
var __reactRouterVersion: string; | ||
interface Document { | ||
startViewTransition(cb: () => Promise<void> | void): ViewTransition; | ||
} | ||
} | ||
export declare function createBrowserRouter(routes: RouteObject[], opts?: { | ||
interface DOMRouterOpts { | ||
basename?: string; | ||
future?: Partial<Omit<RouterFutureConfig, "v7_prependBasename">>; | ||
hydrationData?: HydrationState; | ||
unstable_dataStrategy?: unstable_DataStrategyFunction; | ||
unstable_patchRoutesOnMiss?: unstable_PatchRoutesOnMissFunction; | ||
window?: Window; | ||
}): RemixRouter; | ||
export declare function createHashRouter(routes: RouteObject[], opts?: { | ||
basename?: string; | ||
hydrationData?: HydrationState; | ||
window?: Window; | ||
}): RemixRouter; | ||
} | ||
export declare function createBrowserRouter(routes: RouteObject[], opts?: DOMRouterOpts): RemixRouter; | ||
export declare function createHashRouter(routes: RouteObject[], opts?: DOMRouterOpts): RemixRouter; | ||
type ViewTransitionContextObject = { | ||
isTransitioning: false; | ||
} | { | ||
isTransitioning: true; | ||
flushSync: boolean; | ||
currentLocation: Location; | ||
nextLocation: Location; | ||
}; | ||
declare const ViewTransitionContext: React.Context<ViewTransitionContextObject>; | ||
export { ViewTransitionContext as UNSAFE_ViewTransitionContext }; | ||
type FetchersContextObject = Map<string, any>; | ||
declare const FetchersContext: React.Context<FetchersContextObject>; | ||
export { FetchersContext as UNSAFE_FetchersContext }; | ||
interface ViewTransition { | ||
finished: Promise<void>; | ||
ready: Promise<void>; | ||
updateCallbackDone: Promise<void>; | ||
skipTransition(): void; | ||
} | ||
/** | ||
* Given a Remix Router instance, render the appropriate UI | ||
*/ | ||
export declare function RouterProvider({ fallbackElement, router, future, }: RouterProviderProps): React.ReactElement; | ||
export interface BrowserRouterProps { | ||
basename?: string; | ||
children?: React.ReactNode; | ||
future?: Partial<FutureConfig>; | ||
window?: Window; | ||
@@ -38,6 +67,7 @@ } | ||
*/ | ||
export declare function BrowserRouter({ basename, children, window, }: BrowserRouterProps): JSX.Element; | ||
export declare function BrowserRouter({ basename, children, future, window, }: BrowserRouterProps): React.JSX.Element; | ||
export interface HashRouterProps { | ||
basename?: string; | ||
children?: React.ReactNode; | ||
future?: Partial<FutureConfig>; | ||
window?: Window; | ||
@@ -49,6 +79,7 @@ } | ||
*/ | ||
export declare function HashRouter({ basename, children, window }: HashRouterProps): JSX.Element; | ||
export declare function HashRouter({ basename, children, future, window, }: HashRouterProps): React.JSX.Element; | ||
export interface HistoryRouterProps { | ||
basename?: string; | ||
children?: React.ReactNode; | ||
future?: FutureConfig; | ||
history: History; | ||
@@ -62,3 +93,3 @@ } | ||
*/ | ||
declare function HistoryRouter({ basename, children, history }: HistoryRouterProps): JSX.Element; | ||
declare function HistoryRouter({ basename, children, future, history, }: HistoryRouterProps): React.JSX.Element; | ||
declare namespace HistoryRouter { | ||
@@ -75,28 +106,28 @@ var displayName: string; | ||
to: To; | ||
unstable_viewTransition?: boolean; | ||
} | ||
/** | ||
* The public API for rendering a history-aware <a>. | ||
* The public API for rendering a history-aware `<a>`. | ||
*/ | ||
export declare const Link: React.ForwardRefExoticComponent<LinkProps & React.RefAttributes<HTMLAnchorElement>>; | ||
export type NavLinkRenderProps = { | ||
isActive: boolean; | ||
isPending: boolean; | ||
isTransitioning: boolean; | ||
}; | ||
export interface NavLinkProps extends Omit<LinkProps, "className" | "style" | "children"> { | ||
children?: React.ReactNode | ((props: { | ||
isActive: boolean; | ||
isPending: boolean; | ||
}) => React.ReactNode); | ||
children?: React.ReactNode | ((props: NavLinkRenderProps) => React.ReactNode); | ||
caseSensitive?: boolean; | ||
className?: string | ((props: { | ||
isActive: boolean; | ||
isPending: boolean; | ||
}) => string | undefined); | ||
className?: string | ((props: NavLinkRenderProps) => string | undefined); | ||
end?: boolean; | ||
style?: React.CSSProperties | ((props: { | ||
isActive: boolean; | ||
isPending: boolean; | ||
}) => React.CSSProperties | undefined); | ||
style?: React.CSSProperties | ((props: NavLinkRenderProps) => React.CSSProperties | undefined); | ||
} | ||
/** | ||
* A <Link> wrapper that knows if it's "active" or not. | ||
* A `<Link>` wrapper that knows if it's "active" or not. | ||
*/ | ||
export declare const NavLink: React.ForwardRefExoticComponent<NavLinkProps & React.RefAttributes<HTMLAnchorElement>>; | ||
export interface FormProps extends React.FormHTMLAttributes<HTMLFormElement> { | ||
/** | ||
* Form props shared by navigations and fetchers | ||
*/ | ||
interface SharedFormProps extends React.FormHTMLAttributes<HTMLFormElement> { | ||
/** | ||
@@ -106,4 +137,9 @@ * The HTTP verb to use when the form is submit. Supports "get", "post", | ||
*/ | ||
method?: FormMethod; | ||
method?: HTMLFormMethod; | ||
/** | ||
* `<form encType>` - enhancing beyond the normal string type and limiting | ||
* to the built-in browser supported values | ||
*/ | ||
encType?: "application/x-www-form-urlencoded" | "multipart/form-data" | "text/plain"; | ||
/** | ||
* Normal `<form action>` but supports React Router's relative paths. | ||
@@ -113,12 +149,2 @@ */ | ||
/** | ||
* Forces a full document navigation instead of a fetch. | ||
*/ | ||
reloadDocument?: boolean; | ||
/** | ||
* Replaces the current entry in the browser history stack when the form | ||
* navigates. Use this if you don't want the user to be able to click "back" | ||
* to the page with the form on it. | ||
*/ | ||
replace?: boolean; | ||
/** | ||
* Determines whether the form action is relative to the route hierarchy or | ||
@@ -141,2 +167,38 @@ * the pathname. Use this if you want to opt out of navigating the route | ||
/** | ||
* Form props available to fetchers | ||
*/ | ||
export interface FetcherFormProps extends SharedFormProps { | ||
} | ||
/** | ||
* Form props available to navigations | ||
*/ | ||
export interface FormProps extends SharedFormProps { | ||
/** | ||
* Indicate a specific fetcherKey to use when using navigate=false | ||
*/ | ||
fetcherKey?: string; | ||
/** | ||
* navigate=false will use a fetcher instead of a navigation | ||
*/ | ||
navigate?: boolean; | ||
/** | ||
* Forces a full document navigation instead of a fetch. | ||
*/ | ||
reloadDocument?: boolean; | ||
/** | ||
* Replaces the current entry in the browser history stack when the form | ||
* navigates. Use this if you don't want the user to be able to click "back" | ||
* to the page with the form on it. | ||
*/ | ||
replace?: boolean; | ||
/** | ||
* State object to add to the history stack entry for this navigation | ||
*/ | ||
state?: any; | ||
/** | ||
* Enable view transitions on this Form navigation | ||
*/ | ||
unstable_viewTransition?: boolean; | ||
} | ||
/** | ||
* A `@remix-run/router`-aware `<form>`. It behaves like a normal form except | ||
@@ -165,3 +227,3 @@ * that the interaction with the server is with `fetch` instead of new document | ||
*/ | ||
export declare function useLinkClickHandler<E extends Element = HTMLAnchorElement>(to: To, { target, replace: replaceProp, state, preventScrollReset, relative, }?: { | ||
export declare function useLinkClickHandler<E extends Element = HTMLAnchorElement>(to: To, { target, replace: replaceProp, state, preventScrollReset, relative, unstable_viewTransition, }?: { | ||
target?: React.HTMLAttributeAnchorTarget; | ||
@@ -172,2 +234,3 @@ replace?: boolean; | ||
relative?: RelativeRoutingType; | ||
unstable_viewTransition?: boolean; | ||
}): (event: React.MouseEvent<E, MouseEvent>) => void; | ||
@@ -179,6 +242,3 @@ /** | ||
export declare function useSearchParams(defaultInit?: URLSearchParamsInit): [URLSearchParams, SetURLSearchParams]; | ||
declare type SetURLSearchParams = (nextInit?: URLSearchParamsInit | ((prev: URLSearchParams) => URLSearchParamsInit), navigateOpts?: NavigateOptions) => void; | ||
declare type SubmitTarget = HTMLFormElement | HTMLButtonElement | HTMLInputElement | FormData | URLSearchParams | { | ||
[name: string]: string; | ||
} | null; | ||
export type SetURLSearchParams = (nextInit?: URLSearchParamsInit | ((prev: URLSearchParams) => URLSearchParamsInit), navigateOpts?: NavigateOptions) => void; | ||
/** | ||
@@ -205,2 +265,8 @@ * Submits a HTML `<form>` to the server without reloading the page. | ||
/** | ||
* Submits a fetcher `<form>` to the server without reloading the page. | ||
*/ | ||
export interface FetcherSubmitFunction { | ||
(target: SubmitTarget, options?: FetcherSubmitOptions): void; | ||
} | ||
/** | ||
* Returns a function that may be used to programmatically submit a form (or | ||
@@ -213,7 +279,8 @@ * some arbitrary data) to the server. | ||
}): string; | ||
declare function createFetcherForm(fetcherKey: string, routeId: string): React.ForwardRefExoticComponent<FormProps & React.RefAttributes<HTMLFormElement>>; | ||
export declare type FetcherWithComponents<TData> = Fetcher<TData> & { | ||
Form: ReturnType<typeof createFetcherForm>; | ||
submit: (target: SubmitTarget, options?: Omit<SubmitOptions, "replace" | "preventScrollReset">) => void; | ||
load: (href: string) => void; | ||
export type FetcherWithComponents<TData> = Fetcher<TData> & { | ||
Form: React.ForwardRefExoticComponent<FetcherFormProps & React.RefAttributes<HTMLFormElement>>; | ||
submit: FetcherSubmitFunction; | ||
load: (href: string, opts?: { | ||
unstable_flushSync?: boolean; | ||
}) => void; | ||
}; | ||
@@ -224,3 +291,5 @@ /** | ||
*/ | ||
export declare function useFetcher<TData = any>(): FetcherWithComponents<TData>; | ||
export declare function useFetcher<TData = any>({ key, }?: { | ||
key?: string; | ||
}): FetcherWithComponents<TData>; | ||
/** | ||
@@ -230,3 +299,5 @@ * Provides all fetchers currently on the page. Useful for layouts and parent | ||
*/ | ||
export declare function useFetchers(): Fetcher[]; | ||
export declare function useFetchers(): (Fetcher & { | ||
key: string; | ||
})[]; | ||
/** | ||
@@ -239,2 +310,3 @@ * When rendered inside a RouterProvider, will restore scroll positions on navigations | ||
}): void; | ||
export { useScrollRestoration as UNSAFE_useScrollRestoration }; | ||
/** | ||
@@ -259,7 +331,18 @@ * Setup a callback to be fired on the window's `beforeunload` event. This is | ||
*/ | ||
declare function usePrompt({ when, message }: { | ||
when: boolean; | ||
declare function usePrompt({ when, message, }: { | ||
when: boolean | BlockerFunction; | ||
message: string; | ||
}): void; | ||
export { usePrompt as unstable_usePrompt }; | ||
export { useScrollRestoration as UNSAFE_useScrollRestoration }; | ||
/** | ||
* Return a boolean indicating if there is an active view transition to the | ||
* given href. You can use this value to render CSS classes or viewTransitionName | ||
* styles onto your elements | ||
* | ||
* @param href The destination href | ||
* @param [opts.relative] Relative routing type ("route" | "path") | ||
*/ | ||
declare function useViewTransitionState(to: To, opts?: { | ||
relative?: RelativeRoutingType; | ||
}): boolean; | ||
export { useViewTransitionState as unstable_useViewTransitionState }; |
1222
dist/index.js
/** | ||
* React Router DOM v0.0.0-experimental-cf9637ce | ||
* React Router DOM v0.0.0-experimental-cffa549a1 | ||
* | ||
@@ -12,5 +12,7 @@ * Copyright (c) Remix Software Inc. | ||
import * as React from 'react'; | ||
import { UNSAFE_enhanceManualRouteObjects, Router, useHref, useResolvedPath, useLocation, UNSAFE_DataRouterStateContext, UNSAFE_NavigationContext, useNavigate, createPath, 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_enhanceManualRouteObjects, 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 { createRouter, createBrowserHistory, createHashHistory, ErrorResponse, 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'; | ||
@@ -21,3 +23,2 @@ function _extends() { | ||
var source = arguments[i]; | ||
for (var key in source) { | ||
@@ -29,3 +30,2 @@ if (Object.prototype.hasOwnProperty.call(source, key)) { | ||
} | ||
return target; | ||
@@ -35,3 +35,2 @@ }; | ||
} | ||
function _objectWithoutPropertiesLoose(source, excluded) { | ||
@@ -42,3 +41,2 @@ if (source == null) return {}; | ||
var key, i; | ||
for (i = 0; i < sourceKeys.length; i++) { | ||
@@ -49,3 +47,2 @@ key = sourceKeys[i]; | ||
} | ||
return target; | ||
@@ -68,10 +65,10 @@ } | ||
} | ||
function isModifiedEvent(event) { | ||
return !!(event.metaKey || event.altKey || event.ctrlKey || event.shiftKey); | ||
} | ||
function shouldProcessLinkClick(event, target) { | ||
return event.button === 0 && ( // Ignore everything but left clicks | ||
!target || target === "_self") && // Let browser handle "target=_blank" etc. | ||
return event.button === 0 && ( | ||
// Ignore everything but left clicks | ||
!target || target === "_self") && | ||
// Let browser handle "target=_blank" etc. | ||
!isModifiedEvent(event) // Ignore clicks with modifier keys | ||
@@ -101,3 +98,2 @@ ; | ||
*/ | ||
function createSearchParams(init) { | ||
@@ -107,3 +103,2 @@ if (init === void 0) { | ||
} | ||
return new URLSearchParams(typeof init === "string" || Array.isArray(init) || init instanceof URLSearchParams ? init : Object.keys(init).reduce((memo, key) => { | ||
@@ -116,5 +111,9 @@ let value = init[key]; | ||
let searchParams = createSearchParams(locationSearch); | ||
if (defaultSearchParams) { | ||
for (let key of defaultSearchParams.keys()) { | ||
// Use `defaultSearchParams.forEach(...)` here instead of iterating of | ||
// `defaultSearchParams.keys()` to work-around a bug in Firefox related to | ||
// web extensions. Relevant Bugzilla tickets: | ||
// https://bugzilla.mozilla.org/show_bug.cgi?id=1414602 | ||
// https://bugzilla.mozilla.org/show_bug.cgi?id=1023984 | ||
defaultSearchParams.forEach((_, key) => { | ||
if (!searchParams.has(key)) { | ||
@@ -125,8 +124,30 @@ defaultSearchParams.getAll(key).forEach(value => { | ||
} | ||
} | ||
}); | ||
} | ||
return searchParams; | ||
} | ||
function getFormSubmissionInfo(target, defaultAction, options) { | ||
// One-time check for submitter support | ||
let _formDataSupportsSubmitter = null; | ||
function isFormDataSubmitterSupported() { | ||
if (_formDataSupportsSubmitter === null) { | ||
try { | ||
new FormData(document.createElement("form"), | ||
// @ts-expect-error if FormData supports the submitter parameter, this will throw | ||
0); | ||
_formDataSupportsSubmitter = false; | ||
} catch (e) { | ||
_formDataSupportsSubmitter = true; | ||
} | ||
} | ||
return _formDataSupportsSubmitter; | ||
} | ||
const supportedFormEncTypes = new Set(["application/x-www-form-urlencoded", "multipart/form-data", "text/plain"]); | ||
function getFormEncType(encType) { | ||
if (encType != null && !supportedFormEncTypes.has(encType)) { | ||
process.env.NODE_ENV !== "production" ? UNSAFE_warning(false, "\"" + encType + "\" is not a valid `encType` for `<Form>`/`<fetcher.Form>` " + ("and will default to \"" + defaultEncType + "\"")) : void 0; | ||
return null; | ||
} | ||
return encType; | ||
} | ||
function getFormSubmissionInfo(target, basename) { | ||
let method; | ||
@@ -136,76 +157,91 @@ let action; | ||
let formData; | ||
let body; | ||
if (isFormElement(target)) { | ||
let submissionTrigger = options.submissionTrigger; | ||
method = options.method || target.getAttribute("method") || defaultMethod; | ||
action = options.action || target.getAttribute("action") || defaultAction; | ||
encType = options.encType || target.getAttribute("enctype") || defaultEncType; | ||
// When grabbing the action from the element, it will have had the basename | ||
// prefixed to ensure non-JS scenarios work, so strip it since we'll | ||
// re-prefix in the router | ||
let attr = target.getAttribute("action"); | ||
action = attr ? stripBasename(attr, basename) : null; | ||
method = target.getAttribute("method") || defaultMethod; | ||
encType = getFormEncType(target.getAttribute("enctype")) || defaultEncType; | ||
formData = new FormData(target); | ||
if (submissionTrigger && submissionTrigger.name) { | ||
formData.append(submissionTrigger.name, submissionTrigger.value); | ||
} | ||
} else if (isButtonElement(target) || isInputElement(target) && (target.type === "submit" || target.type === "image")) { | ||
let form = target.form; | ||
if (form == null) { | ||
throw new Error("Cannot submit a <button> or <input type=\"submit\"> without a <form>"); | ||
} // <button>/<input type="submit"> may override attributes of <form> | ||
method = options.method || target.getAttribute("formmethod") || form.getAttribute("method") || defaultMethod; | ||
action = options.action || target.getAttribute("formaction") || form.getAttribute("action") || defaultAction; | ||
encType = options.encType || target.getAttribute("formenctype") || form.getAttribute("enctype") || defaultEncType; | ||
formData = new FormData(form); // Include name + value from a <button>, appending in case the button name | ||
// matches an existing input name | ||
if (target.name) { | ||
formData.append(target.name, target.value); | ||
} | ||
// <button>/<input type="submit"> may override attributes of <form> | ||
// When grabbing the action from the element, it will have had the basename | ||
// prefixed to ensure non-JS scenarios work, so strip it since we'll | ||
// re-prefix in the router | ||
let attr = target.getAttribute("formaction") || form.getAttribute("action"); | ||
action = attr ? stripBasename(attr, basename) : null; | ||
method = target.getAttribute("formmethod") || form.getAttribute("method") || defaultMethod; | ||
encType = getFormEncType(target.getAttribute("formenctype")) || getFormEncType(form.getAttribute("enctype")) || defaultEncType; | ||
// Build a FormData object populated from a form and submitter | ||
formData = new FormData(form, target); | ||
// If this browser doesn't support the `FormData(el, submitter)` format, | ||
// then tack on the submitter value at the end. This is a lightweight | ||
// solution that is not 100% spec compliant. For complete support in older | ||
// browsers, consider using the `formdata-submitter-polyfill` package | ||
if (!isFormDataSubmitterSupported()) { | ||
let { | ||
name, | ||
type, | ||
value | ||
} = target; | ||
if (type === "image") { | ||
let prefix = name ? name + "." : ""; | ||
formData.append(prefix + "x", "0"); | ||
formData.append(prefix + "y", "0"); | ||
} else if (name) { | ||
formData.append(name, value); | ||
} | ||
} | ||
} else if (isHtmlElement(target)) { | ||
throw new Error("Cannot submit element that is not <form>, <button>, or " + "<input type=\"submit|image\">"); | ||
} else { | ||
method = options.method || defaultMethod; | ||
action = options.action || defaultAction; | ||
encType = options.encType || defaultEncType; | ||
if (target instanceof FormData) { | ||
formData = target; | ||
} else { | ||
formData = new FormData(); | ||
if (target instanceof URLSearchParams) { | ||
for (let [name, value] of target) { | ||
formData.append(name, value); | ||
} | ||
} else if (target != null) { | ||
for (let name of Object.keys(target)) { | ||
formData.append(name, target[name]); | ||
} | ||
} | ||
} | ||
method = defaultMethod; | ||
action = null; | ||
encType = defaultEncType; | ||
body = target; | ||
} | ||
let { | ||
protocol, | ||
host | ||
} = window.location; | ||
let url = new URL(action, protocol + "//" + host); | ||
// Send body for <Form encType="text/plain" so we encode it into text | ||
if (formData && encType === "text/plain") { | ||
body = formData; | ||
formData = undefined; | ||
} | ||
return { | ||
url, | ||
action, | ||
method: method.toLowerCase(), | ||
encType, | ||
formData | ||
formData, | ||
body | ||
}; | ||
} | ||
const _excluded = ["onClick", "relative", "reloadDocument", "replace", "state", "target", "to", "preventScrollReset"], | ||
_excluded2 = ["aria-current", "caseSensitive", "className", "end", "style", "to", "children"], | ||
_excluded3 = ["reloadDocument", "replace", "method", "action", "onSubmit", "fetcherKey", "routeId", "relative", "preventScrollReset"]; | ||
//#region Routers | ||
//////////////////////////////////////////////////////////////////////////////// | ||
const _excluded = ["onClick", "relative", "reloadDocument", "replace", "state", "target", "to", "preventScrollReset", "unstable_viewTransition"], | ||
_excluded2 = ["aria-current", "caseSensitive", "className", "end", "style", "to", "unstable_viewTransition", "children"], | ||
_excluded3 = ["fetcherKey", "navigate", "reloadDocument", "replace", "state", "method", "action", "onSubmit", "relative", "preventScrollReset", "unstable_viewTransition"]; | ||
// HEY YOU! DON'T TOUCH THIS VARIABLE! | ||
// | ||
// It is replaced with the proper version at build time via a babel plugin in | ||
// the rollup config. | ||
// | ||
// Export a global property onto the window for React Router detection by the | ||
// Core Web Vitals Technology Report. This way they can configure the `wappalyzer` | ||
// to detect and properly classify live websites as being built with React Router: | ||
// https://github.com/HTTPArchive/wappalyzer/blob/main/src/technologies/r.json | ||
const REACT_ROUTER_VERSION = "0"; | ||
try { | ||
window.__reactRouterVersion = REACT_ROUTER_VERSION; | ||
} catch (e) { | ||
// no-op | ||
} | ||
function createBrowserRouter(routes, opts) { | ||
return createRouter({ | ||
basename: opts == null ? void 0 : opts.basename, | ||
future: _extends({}, opts == null ? void 0 : opts.future, { | ||
v7_prependBasename: true | ||
}), | ||
history: createBrowserHistory({ | ||
@@ -215,3 +251,7 @@ window: opts == null ? void 0 : opts.window | ||
hydrationData: (opts == null ? void 0 : opts.hydrationData) || parseHydrationData(), | ||
routes: UNSAFE_enhanceManualRouteObjects(routes) | ||
routes, | ||
mapRouteProperties: UNSAFE_mapRouteProperties, | ||
unstable_dataStrategy: opts == null ? void 0 : opts.unstable_dataStrategy, | ||
unstable_patchRoutesOnMiss: opts == null ? void 0 : opts.unstable_patchRoutesOnMiss, | ||
window: opts == null ? void 0 : opts.window | ||
}).initialize(); | ||
@@ -222,2 +262,5 @@ } | ||
basename: opts == null ? void 0 : opts.basename, | ||
future: _extends({}, opts == null ? void 0 : opts.future, { | ||
v7_prependBasename: true | ||
}), | ||
history: createHashHistory({ | ||
@@ -227,11 +270,12 @@ window: opts == null ? void 0 : opts.window | ||
hydrationData: (opts == null ? void 0 : opts.hydrationData) || parseHydrationData(), | ||
routes: UNSAFE_enhanceManualRouteObjects(routes) | ||
routes, | ||
mapRouteProperties: UNSAFE_mapRouteProperties, | ||
unstable_dataStrategy: opts == null ? void 0 : opts.unstable_dataStrategy, | ||
unstable_patchRoutesOnMiss: opts == null ? void 0 : opts.unstable_patchRoutesOnMiss, | ||
window: opts == null ? void 0 : opts.window | ||
}).initialize(); | ||
} | ||
function parseHydrationData() { | ||
var _window; | ||
let state = (_window = window) == null ? void 0 : _window.__staticRouterHydrationData; | ||
if (state && state.errors) { | ||
@@ -242,6 +286,4 @@ state = _extends({}, state, { | ||
} | ||
return state; | ||
} | ||
function deserializeErrors(errors) { | ||
@@ -251,3 +293,2 @@ if (!errors) return null; | ||
let serialized = {}; | ||
for (let [key, val] of entries) { | ||
@@ -257,9 +298,27 @@ // Hey you! If you change this, please change the corresponding logic in | ||
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") { | ||
let error = new Error(val.message); // Wipe away the client-side stack trace. Nothing to fill it in with | ||
// because we don't serialize SSR stack traces for security reasons | ||
error.stack = ""; | ||
serialized[key] = error; | ||
// Attempt to reconstruct the right type of Error (i.e., ReferenceError) | ||
if (val.__subType) { | ||
let ErrorConstructor = window[val.__subType]; | ||
if (typeof ErrorConstructor === "function") { | ||
try { | ||
// @ts-expect-error | ||
let error = new ErrorConstructor(val.message); | ||
// Wipe away the client-side stack trace. Nothing to fill it in with | ||
// because we don't serialize SSR stack traces for security reasons | ||
error.stack = ""; | ||
serialized[key] = error; | ||
} catch (e) { | ||
// no-op - fall through and create a normal Error | ||
} | ||
} | ||
} | ||
if (serialized[key] == null) { | ||
let error = new Error(val.message); | ||
// Wipe away the client-side stack trace. Nothing to fill it in with | ||
// because we don't serialize SSR stack traces for security reasons | ||
error.stack = ""; | ||
serialized[key] = error; | ||
} | ||
} else { | ||
@@ -269,18 +328,313 @@ serialized[key] = val; | ||
} | ||
return serialized; | ||
} | ||
const ViewTransitionContext = /*#__PURE__*/React.createContext({ | ||
isTransitioning: false | ||
}); | ||
if (process.env.NODE_ENV !== "production") { | ||
ViewTransitionContext.displayName = "ViewTransition"; | ||
} | ||
const FetchersContext = /*#__PURE__*/React.createContext(new Map()); | ||
if (process.env.NODE_ENV !== "production") { | ||
FetchersContext.displayName = "Fetchers"; | ||
} | ||
//#endregion | ||
//////////////////////////////////////////////////////////////////////////////// | ||
//#region Components | ||
//////////////////////////////////////////////////////////////////////////////// | ||
/** | ||
* A `<Router>` for use in web browsers. Provides the cleanest URLs. | ||
*/ | ||
Webpack + React 17 fails to compile on any of the following because webpack | ||
complains that `startTransition` doesn't exist in `React`: | ||
* import { startTransition } from "react" | ||
* import * as React from from "react"; | ||
"startTransition" in React ? React.startTransition(() => setState()) : setState() | ||
* import * as React from from "react"; | ||
"startTransition" in React ? React["startTransition"](() => setState()) : setState() | ||
Moving it to a constant such as the following solves the Webpack/React 17 issue: | ||
* import * as React from from "react"; | ||
const START_TRANSITION = "startTransition"; | ||
START_TRANSITION in React ? React[START_TRANSITION](() => setState()) : setState() | ||
function BrowserRouter(_ref) { | ||
However, that introduces webpack/terser minification issues in production builds | ||
in React 18 where minification/obfuscation ends up removing the call of | ||
React.startTransition entirely from the first half of the ternary. Grabbing | ||
this exported reference once up front resolves that issue. | ||
See https://github.com/remix-run/react-router/issues/10579 | ||
*/ | ||
const START_TRANSITION = "startTransition"; | ||
const startTransitionImpl = React[START_TRANSITION]; | ||
const FLUSH_SYNC = "flushSync"; | ||
const flushSyncImpl = ReactDOM[FLUSH_SYNC]; | ||
const USE_ID = "useId"; | ||
const useIdImpl = React[USE_ID]; | ||
function startTransitionSafe(cb) { | ||
if (startTransitionImpl) { | ||
startTransitionImpl(cb); | ||
} else { | ||
cb(); | ||
} | ||
} | ||
function flushSyncSafe(cb) { | ||
if (flushSyncImpl) { | ||
flushSyncImpl(cb); | ||
} else { | ||
cb(); | ||
} | ||
} | ||
class Deferred { | ||
constructor() { | ||
this.status = "pending"; | ||
this.promise = new Promise((resolve, reject) => { | ||
this.resolve = value => { | ||
if (this.status === "pending") { | ||
this.status = "resolved"; | ||
resolve(value); | ||
} | ||
}; | ||
this.reject = reason => { | ||
if (this.status === "pending") { | ||
this.status = "rejected"; | ||
reject(reason); | ||
} | ||
}; | ||
}); | ||
} | ||
} | ||
/** | ||
* Given a Remix Router instance, render the appropriate UI | ||
*/ | ||
function RouterProvider(_ref) { | ||
let { | ||
fallbackElement, | ||
router, | ||
future | ||
} = _ref; | ||
let [state, setStateImpl] = React.useState(router.state); | ||
let [pendingState, setPendingState] = React.useState(); | ||
let [vtContext, setVtContext] = React.useState({ | ||
isTransitioning: false | ||
}); | ||
let [renderDfd, setRenderDfd] = React.useState(); | ||
let [transition, setTransition] = React.useState(); | ||
let [interruption, setInterruption] = React.useState(); | ||
let fetcherData = React.useRef(new Map()); | ||
let { | ||
v7_startTransition | ||
} = future || {}; | ||
let optInStartTransition = React.useCallback(cb => { | ||
if (v7_startTransition) { | ||
startTransitionSafe(cb); | ||
} else { | ||
cb(); | ||
} | ||
}, [v7_startTransition]); | ||
let setState = React.useCallback((newState, _ref2) => { | ||
let { | ||
deletedFetchers, | ||
unstable_flushSync: flushSync, | ||
unstable_viewTransitionOpts: viewTransitionOpts | ||
} = _ref2; | ||
deletedFetchers.forEach(key => fetcherData.current.delete(key)); | ||
newState.fetchers.forEach((fetcher, key) => { | ||
if (fetcher.data !== undefined) { | ||
fetcherData.current.set(key, fetcher.data); | ||
} | ||
}); | ||
let isViewTransitionUnavailable = router.window == null || router.window.document == null || typeof router.window.document.startViewTransition !== "function"; | ||
// If this isn't a view transition or it's not available in this browser, | ||
// just update and be done with it | ||
if (!viewTransitionOpts || isViewTransitionUnavailable) { | ||
if (flushSync) { | ||
flushSyncSafe(() => setStateImpl(newState)); | ||
} else { | ||
optInStartTransition(() => setStateImpl(newState)); | ||
} | ||
return; | ||
} | ||
// flushSync + startViewTransition | ||
if (flushSync) { | ||
// Flush through the context to mark DOM elements as transition=ing | ||
flushSyncSafe(() => { | ||
// Cancel any pending transitions | ||
if (transition) { | ||
renderDfd && renderDfd.resolve(); | ||
transition.skipTransition(); | ||
} | ||
setVtContext({ | ||
isTransitioning: true, | ||
flushSync: true, | ||
currentLocation: viewTransitionOpts.currentLocation, | ||
nextLocation: viewTransitionOpts.nextLocation | ||
}); | ||
}); | ||
// Update the DOM | ||
let t = router.window.document.startViewTransition(() => { | ||
flushSyncSafe(() => setStateImpl(newState)); | ||
}); | ||
// Clean up after the animation completes | ||
t.finished.finally(() => { | ||
flushSyncSafe(() => { | ||
setRenderDfd(undefined); | ||
setTransition(undefined); | ||
setPendingState(undefined); | ||
setVtContext({ | ||
isTransitioning: false | ||
}); | ||
}); | ||
}); | ||
flushSyncSafe(() => setTransition(t)); | ||
return; | ||
} | ||
// startTransition + startViewTransition | ||
if (transition) { | ||
// Interrupting an in-progress transition, cancel and let everything flush | ||
// out, and then kick off a new transition from the interruption state | ||
renderDfd && renderDfd.resolve(); | ||
transition.skipTransition(); | ||
setInterruption({ | ||
state: newState, | ||
currentLocation: viewTransitionOpts.currentLocation, | ||
nextLocation: viewTransitionOpts.nextLocation | ||
}); | ||
} else { | ||
// Completed navigation update with opted-in view transitions, let 'er rip | ||
setPendingState(newState); | ||
setVtContext({ | ||
isTransitioning: true, | ||
flushSync: false, | ||
currentLocation: viewTransitionOpts.currentLocation, | ||
nextLocation: viewTransitionOpts.nextLocation | ||
}); | ||
} | ||
}, [router.window, transition, renderDfd, fetcherData, optInStartTransition]); | ||
// Need to use a layout effect here so we are subscribed early enough to | ||
// pick up on any render-driven redirects/navigations (useEffect/<Navigate>) | ||
React.useLayoutEffect(() => router.subscribe(setState), [router, setState]); | ||
// When we start a view transition, create a Deferred we can use for the | ||
// eventual "completed" render | ||
React.useEffect(() => { | ||
if (vtContext.isTransitioning && !vtContext.flushSync) { | ||
setRenderDfd(new Deferred()); | ||
} | ||
}, [vtContext]); | ||
// Once the deferred is created, kick off startViewTransition() to update the | ||
// DOM and then wait on the Deferred to resolve (indicating the DOM update has | ||
// happened) | ||
React.useEffect(() => { | ||
if (renderDfd && pendingState && router.window) { | ||
let newState = pendingState; | ||
let renderPromise = renderDfd.promise; | ||
let transition = router.window.document.startViewTransition(async () => { | ||
optInStartTransition(() => setStateImpl(newState)); | ||
await renderPromise; | ||
}); | ||
transition.finished.finally(() => { | ||
setRenderDfd(undefined); | ||
setTransition(undefined); | ||
setPendingState(undefined); | ||
setVtContext({ | ||
isTransitioning: false | ||
}); | ||
}); | ||
setTransition(transition); | ||
} | ||
}, [optInStartTransition, pendingState, renderDfd, router.window]); | ||
// When the new location finally renders and is committed to the DOM, this | ||
// effect will run to resolve the transition | ||
React.useEffect(() => { | ||
if (renderDfd && pendingState && state.location.key === pendingState.location.key) { | ||
renderDfd.resolve(); | ||
} | ||
}, [renderDfd, transition, state.location, pendingState]); | ||
// If we get interrupted with a new navigation during a transition, we skip | ||
// the active transition, let it cleanup, then kick it off again here | ||
React.useEffect(() => { | ||
if (!vtContext.isTransitioning && interruption) { | ||
setPendingState(interruption.state); | ||
setVtContext({ | ||
isTransitioning: true, | ||
flushSync: false, | ||
currentLocation: interruption.currentLocation, | ||
nextLocation: interruption.nextLocation | ||
}); | ||
setInterruption(undefined); | ||
} | ||
}, [vtContext.isTransitioning, interruption]); | ||
React.useEffect(() => { | ||
process.env.NODE_ENV !== "production" ? UNSAFE_warning(fallbackElement == null || !router.future.v7_partialHydration, "`<RouterProvider fallbackElement>` is deprecated when using " + "`v7_partialHydration`, use a `HydrateFallback` component instead") : void 0; | ||
// Only log this once on initial mount | ||
// eslint-disable-next-line react-hooks/exhaustive-deps | ||
}, []); | ||
let navigator = React.useMemo(() => { | ||
return { | ||
createHref: router.createHref, | ||
encodeLocation: router.encodeLocation, | ||
go: n => router.navigate(n), | ||
push: (to, state, opts) => router.navigate(to, { | ||
state, | ||
preventScrollReset: opts == null ? void 0 : opts.preventScrollReset | ||
}), | ||
replace: (to, state, opts) => router.navigate(to, { | ||
replace: true, | ||
state, | ||
preventScrollReset: opts == null ? void 0 : opts.preventScrollReset | ||
}) | ||
}; | ||
}, [router]); | ||
let basename = router.basename || "/"; | ||
let dataRouterContext = React.useMemo(() => ({ | ||
router, | ||
navigator, | ||
static: false, | ||
basename | ||
}), [router, navigator, basename]); | ||
// The fragment and {null} here are important! We need them to keep React 18's | ||
// useId happy when we are server-rendering since we may have a <script> here | ||
// containing the hydrated server-side staticContext (from StaticRouterProvider). | ||
// useId relies on the component tree structure to generate deterministic id's | ||
// so we need to ensure it remains the same on the client even though | ||
// we don't need the <script> tag | ||
return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(UNSAFE_DataRouterContext.Provider, { | ||
value: dataRouterContext | ||
}, /*#__PURE__*/React.createElement(UNSAFE_DataRouterStateContext.Provider, { | ||
value: state | ||
}, /*#__PURE__*/React.createElement(FetchersContext.Provider, { | ||
value: fetcherData.current | ||
}, /*#__PURE__*/React.createElement(ViewTransitionContext.Provider, { | ||
value: vtContext | ||
}, /*#__PURE__*/React.createElement(Router, { | ||
basename: basename, | ||
location: state.location, | ||
navigationType: state.historyAction, | ||
navigator: navigator, | ||
future: { | ||
v7_relativeSplatPath: router.future.v7_relativeSplatPath | ||
} | ||
}, state.initialized || router.future.v7_partialHydration ? /*#__PURE__*/React.createElement(DataRoutes, { | ||
routes: router.routes, | ||
future: router.future, | ||
state: state | ||
}) : fallbackElement))))), null); | ||
} | ||
function DataRoutes(_ref3) { | ||
let { | ||
routes, | ||
future, | ||
state | ||
} = _ref3; | ||
return UNSAFE_useRoutesImpl(routes, undefined, state, future); | ||
} | ||
/** | ||
* A `<Router>` for use in web browsers. Provides the cleanest URLs. | ||
*/ | ||
function BrowserRouter(_ref4) { | ||
let { | ||
basename, | ||
children, | ||
future, | ||
window | ||
} = _ref; | ||
} = _ref4; | ||
let historyRef = React.useRef(); | ||
if (historyRef.current == null) { | ||
@@ -292,9 +646,14 @@ historyRef.current = createBrowserHistory({ | ||
} | ||
let history = historyRef.current; | ||
let [state, setState] = React.useState({ | ||
let [state, setStateImpl] = React.useState({ | ||
action: history.action, | ||
location: history.location | ||
}); | ||
React.useLayoutEffect(() => history.listen(setState), [history]); | ||
let { | ||
v7_startTransition | ||
} = future || {}; | ||
let setState = React.useCallback(newState => { | ||
v7_startTransition && startTransitionImpl ? startTransitionImpl(() => setStateImpl(newState)) : setStateImpl(newState); | ||
}, [setStateImpl, v7_startTransition]); | ||
React.useLayoutEffect(() => history.listen(setState), [history, setState]); | ||
return /*#__PURE__*/React.createElement(Router, { | ||
@@ -305,3 +664,4 @@ basename: basename, | ||
navigationType: state.action, | ||
navigator: history | ||
navigator: history, | ||
future: future | ||
}); | ||
@@ -313,11 +673,10 @@ } | ||
*/ | ||
function HashRouter(_ref2) { | ||
function HashRouter(_ref5) { | ||
let { | ||
basename, | ||
children, | ||
future, | ||
window | ||
} = _ref2; | ||
} = _ref5; | ||
let historyRef = React.useRef(); | ||
if (historyRef.current == null) { | ||
@@ -329,9 +688,14 @@ historyRef.current = createHashHistory({ | ||
} | ||
let history = historyRef.current; | ||
let [state, setState] = React.useState({ | ||
let [state, setStateImpl] = React.useState({ | ||
action: history.action, | ||
location: history.location | ||
}); | ||
React.useLayoutEffect(() => history.listen(setState), [history]); | ||
let { | ||
v7_startTransition | ||
} = future || {}; | ||
let setState = React.useCallback(newState => { | ||
v7_startTransition && startTransitionImpl ? startTransitionImpl(() => setStateImpl(newState)) : setStateImpl(newState); | ||
}, [setStateImpl, v7_startTransition]); | ||
React.useLayoutEffect(() => history.listen(setState), [history, setState]); | ||
return /*#__PURE__*/React.createElement(Router, { | ||
@@ -342,3 +706,4 @@ basename: basename, | ||
navigationType: state.action, | ||
navigator: history | ||
navigator: history, | ||
future: future | ||
}); | ||
@@ -352,14 +717,20 @@ } | ||
*/ | ||
function HistoryRouter(_ref3) { | ||
function HistoryRouter(_ref6) { | ||
let { | ||
basename, | ||
children, | ||
future, | ||
history | ||
} = _ref3; | ||
const [state, setState] = React.useState({ | ||
} = _ref6; | ||
let [state, setStateImpl] = React.useState({ | ||
action: history.action, | ||
location: history.location | ||
}); | ||
React.useLayoutEffect(() => history.listen(setState), [history]); | ||
let { | ||
v7_startTransition | ||
} = future || {}; | ||
let setState = React.useCallback(newState => { | ||
v7_startTransition && startTransitionImpl ? startTransitionImpl(() => setStateImpl(newState)) : setStateImpl(newState); | ||
}, [setStateImpl, v7_startTransition]); | ||
React.useLayoutEffect(() => history.listen(setState), [history, setState]); | ||
return /*#__PURE__*/React.createElement(Router, { | ||
@@ -370,6 +741,6 @@ basename: basename, | ||
navigationType: state.action, | ||
navigator: history | ||
navigator: history, | ||
future: future | ||
}); | ||
} | ||
if (process.env.NODE_ENV !== "production") { | ||
@@ -379,37 +750,47 @@ HistoryRouter.displayName = "unstable_HistoryRouter"; | ||
const isBrowser = typeof window !== "undefined" && typeof window.document !== "undefined" && typeof window.document.createElement !== "undefined"; | ||
const ABSOLUTE_URL_REGEX = /^(?:[a-z][a-z0-9+.-]*:|\/\/)/i; | ||
/** | ||
* The public API for rendering a history-aware <a>. | ||
* The public API for rendering a history-aware `<a>`. | ||
*/ | ||
const Link = /*#__PURE__*/React.forwardRef(function LinkWithRef(_ref4, ref) { | ||
const Link = /*#__PURE__*/React.forwardRef(function LinkWithRef(_ref7, ref) { | ||
let { | ||
onClick, | ||
relative, | ||
reloadDocument, | ||
replace, | ||
state, | ||
target, | ||
to, | ||
preventScrollReset | ||
} = _ref4, | ||
rest = _objectWithoutPropertiesLoose(_ref4, _excluded); | ||
onClick, | ||
relative, | ||
reloadDocument, | ||
replace, | ||
state, | ||
target, | ||
to, | ||
preventScrollReset, | ||
unstable_viewTransition | ||
} = _ref7, | ||
rest = _objectWithoutPropertiesLoose(_ref7, _excluded); | ||
let { | ||
basename | ||
} = React.useContext(UNSAFE_NavigationContext); | ||
// Rendered into <a href> for absolute URLs | ||
let absoluteHref; | ||
let isExternal = false; | ||
if (isBrowser && typeof to === "string" && /^(?:[a-z][a-z0-9+.-]*:|\/\/)/i.test(to)) { | ||
if (typeof to === "string" && ABSOLUTE_URL_REGEX.test(to)) { | ||
// Render the absolute href server- and client-side | ||
absoluteHref = to; | ||
let currentUrl = new URL(window.location.href); | ||
let targetUrl = to.startsWith("//") ? new URL(currentUrl.protocol + to) : new URL(to); | ||
if (targetUrl.origin === currentUrl.origin) { | ||
// Strip the protocol/origin for same-origin absolute URLs | ||
to = targetUrl.pathname + targetUrl.search + targetUrl.hash; | ||
} else { | ||
isExternal = true; | ||
// Only check for external origins client-side | ||
if (isBrowser) { | ||
try { | ||
let currentUrl = new URL(window.location.href); | ||
let targetUrl = to.startsWith("//") ? new URL(currentUrl.protocol + to) : new URL(to); | ||
let path = stripBasename(targetUrl.pathname, basename); | ||
if (targetUrl.origin === currentUrl.origin && path != null) { | ||
// Strip the protocol/origin/basename for same-origin absolute URLs | ||
to = path + targetUrl.search + targetUrl.hash; | ||
} else { | ||
isExternal = true; | ||
} | ||
} catch (e) { | ||
// We can't do external URL detection without a valid URL | ||
process.env.NODE_ENV !== "production" ? UNSAFE_warning(false, "<Link to=\"" + to + "\"> contains an invalid URL which will probably break " + "when clicked - please update to a valid URL path.") : void 0; | ||
} | ||
} | ||
} // Rendered into <a href> for relative URLs | ||
} | ||
// Rendered into <a href> for relative URLs | ||
let href = useHref(to, { | ||
@@ -423,8 +804,7 @@ relative | ||
preventScrollReset, | ||
relative | ||
relative, | ||
unstable_viewTransition | ||
}); | ||
function handleClick(event) { | ||
if (onClick) onClick(event); | ||
if (!event.defaultPrevented) { | ||
@@ -434,3 +814,2 @@ internalOnClick(event); | ||
} | ||
return ( | ||
@@ -447,3 +826,2 @@ /*#__PURE__*/ | ||
}); | ||
if (process.env.NODE_ENV !== "production") { | ||
@@ -453,18 +831,16 @@ Link.displayName = "Link"; | ||
/** | ||
* A <Link> wrapper that knows if it's "active" or not. | ||
* A `<Link>` wrapper that knows if it's "active" or not. | ||
*/ | ||
const NavLink = /*#__PURE__*/React.forwardRef(function NavLinkWithRef(_ref5, ref) { | ||
const NavLink = /*#__PURE__*/React.forwardRef(function NavLinkWithRef(_ref8, ref) { | ||
let { | ||
"aria-current": ariaCurrentProp = "page", | ||
caseSensitive = false, | ||
className: classNameProp = "", | ||
end = false, | ||
style: styleProp, | ||
to, | ||
children | ||
} = _ref5, | ||
rest = _objectWithoutPropertiesLoose(_ref5, _excluded2); | ||
"aria-current": ariaCurrentProp = "page", | ||
caseSensitive = false, | ||
className: classNameProp = "", | ||
end = false, | ||
style: styleProp, | ||
to, | ||
unstable_viewTransition, | ||
children | ||
} = _ref8, | ||
rest = _objectWithoutPropertiesLoose(_ref8, _excluded2); | ||
let path = useResolvedPath(to, { | ||
@@ -476,8 +852,12 @@ relative: rest.relative | ||
let { | ||
navigator | ||
navigator, | ||
basename | ||
} = React.useContext(UNSAFE_NavigationContext); | ||
let isTransitioning = routerState != null && | ||
// Conditional usage is OK here because the usage of a data router is static | ||
// eslint-disable-next-line react-hooks/rules-of-hooks | ||
useViewTransitionState(path) && unstable_viewTransition === true; | ||
let toPathname = navigator.encodeLocation ? navigator.encodeLocation(path).pathname : path.pathname; | ||
let locationPathname = location.pathname; | ||
let nextLocationPathname = routerState && routerState.navigation && routerState.navigation.location ? routerState.navigation.location.pathname : null; | ||
if (!caseSensitive) { | ||
@@ -488,13 +868,22 @@ locationPathname = locationPathname.toLowerCase(); | ||
} | ||
let isActive = locationPathname === toPathname || !end && locationPathname.startsWith(toPathname) && locationPathname.charAt(toPathname.length) === "/"; | ||
if (nextLocationPathname && basename) { | ||
nextLocationPathname = stripBasename(nextLocationPathname, basename) || nextLocationPathname; | ||
} | ||
// If the `to` has a trailing slash, look at that exact spot. Otherwise, | ||
// we're looking for a slash _after_ what's in `to`. For example: | ||
// | ||
// <NavLink to="/users"> and <NavLink to="/users/"> | ||
// both want to look for a / at index 6 to match URL `/users/matt` | ||
const endSlashPosition = toPathname !== "/" && toPathname.endsWith("/") ? toPathname.length - 1 : toPathname.length; | ||
let isActive = locationPathname === toPathname || !end && locationPathname.startsWith(toPathname) && locationPathname.charAt(endSlashPosition) === "/"; | ||
let isPending = nextLocationPathname != null && (nextLocationPathname === toPathname || !end && nextLocationPathname.startsWith(toPathname) && nextLocationPathname.charAt(toPathname.length) === "/"); | ||
let renderProps = { | ||
isActive, | ||
isPending, | ||
isTransitioning | ||
}; | ||
let ariaCurrent = isActive ? ariaCurrentProp : undefined; | ||
let className; | ||
if (typeof classNameProp === "function") { | ||
className = classNameProp({ | ||
isActive, | ||
isPending | ||
}); | ||
className = classNameProp(renderProps); | ||
} else { | ||
@@ -506,9 +895,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, { | ||
@@ -519,9 +904,6 @@ "aria-current": ariaCurrent, | ||
style: style, | ||
to: to | ||
}), typeof children === "function" ? children({ | ||
isActive, | ||
isPending | ||
}) : children); | ||
to: to, | ||
unstable_viewTransition: unstable_viewTransition | ||
}), typeof children === "function" ? children(renderProps) : children); | ||
}); | ||
if (process.env.NODE_ENV !== "production") { | ||
@@ -536,34 +918,22 @@ NavLink.displayName = "NavLink"; | ||
*/ | ||
const Form = /*#__PURE__*/React.forwardRef((props, ref) => { | ||
return /*#__PURE__*/React.createElement(FormImpl, _extends({}, props, { | ||
ref: ref | ||
})); | ||
}); | ||
if (process.env.NODE_ENV !== "production") { | ||
Form.displayName = "Form"; | ||
} | ||
const FormImpl = /*#__PURE__*/React.forwardRef((_ref6, forwardedRef) => { | ||
const Form = /*#__PURE__*/React.forwardRef((_ref9, forwardedRef) => { | ||
let { | ||
reloadDocument, | ||
replace, | ||
method = defaultMethod, | ||
action, | ||
onSubmit, | ||
fetcherKey, | ||
routeId, | ||
relative, | ||
preventScrollReset | ||
} = _ref6, | ||
props = _objectWithoutPropertiesLoose(_ref6, _excluded3); | ||
let submit = useSubmitImpl(fetcherKey, routeId); | ||
let formMethod = method.toLowerCase() === "get" ? "get" : "post"; | ||
fetcherKey, | ||
navigate, | ||
reloadDocument, | ||
replace, | ||
state, | ||
method = defaultMethod, | ||
action, | ||
onSubmit, | ||
relative, | ||
preventScrollReset, | ||
unstable_viewTransition | ||
} = _ref9, | ||
props = _objectWithoutPropertiesLoose(_ref9, _excluded3); | ||
let submit = useSubmit(); | ||
let formAction = useFormAction(action, { | ||
relative | ||
}); | ||
let formMethod = method.toLowerCase() === "get" ? "get" : "post"; | ||
let submitHandler = event => { | ||
@@ -576,9 +946,12 @@ onSubmit && onSubmit(event); | ||
submit(submitter || event.currentTarget, { | ||
fetcherKey, | ||
method: submitMethod, | ||
navigate, | ||
replace, | ||
state, | ||
relative, | ||
preventScrollReset | ||
preventScrollReset, | ||
unstable_viewTransition | ||
}); | ||
}; | ||
return /*#__PURE__*/React.createElement("form", _extends({ | ||
@@ -591,5 +964,4 @@ ref: forwardedRef, | ||
}); | ||
if (process.env.NODE_ENV !== "production") { | ||
FormImpl.displayName = "FormImpl"; | ||
Form.displayName = "Form"; | ||
} | ||
@@ -600,9 +972,7 @@ /** | ||
*/ | ||
function ScrollRestoration(_ref7) { | ||
function ScrollRestoration(_ref10) { | ||
let { | ||
getKey, | ||
storageKey | ||
} = _ref7; | ||
} = _ref10; | ||
useScrollRestoration({ | ||
@@ -614,41 +984,38 @@ getKey, | ||
} | ||
if (process.env.NODE_ENV !== "production") { | ||
ScrollRestoration.displayName = "ScrollRestoration"; | ||
} //#endregion | ||
} | ||
//#endregion | ||
//////////////////////////////////////////////////////////////////////////////// | ||
//#region Hooks | ||
//////////////////////////////////////////////////////////////////////////////// | ||
var DataRouterHook; | ||
(function (DataRouterHook) { | ||
DataRouterHook["UseScrollRestoration"] = "useScrollRestoration"; | ||
DataRouterHook["UseSubmitImpl"] = "useSubmitImpl"; | ||
DataRouterHook["UseSubmit"] = "useSubmit"; | ||
DataRouterHook["UseSubmitFetcher"] = "useSubmitFetcher"; | ||
DataRouterHook["UseFetcher"] = "useFetcher"; | ||
DataRouterHook["useViewTransitionState"] = "useViewTransitionState"; | ||
})(DataRouterHook || (DataRouterHook = {})); | ||
var DataRouterStateHook; | ||
(function (DataRouterStateHook) { | ||
DataRouterStateHook["UseFetcher"] = "useFetcher"; | ||
DataRouterStateHook["UseFetchers"] = "useFetchers"; | ||
DataRouterStateHook["UseScrollRestoration"] = "useScrollRestoration"; | ||
})(DataRouterStateHook || (DataRouterStateHook = {})); | ||
// Internal hooks | ||
function getDataRouterConsoleError(hookName) { | ||
return hookName + " must be used within a data router. See https://reactrouter.com/routers/picking-a-router."; | ||
} | ||
function useDataRouterContext(hookName) { | ||
let ctx = React.useContext(UNSAFE_DataRouterContext); | ||
!ctx ? process.env.NODE_ENV !== "production" ? invariant(false, getDataRouterConsoleError(hookName)) : invariant(false) : void 0; | ||
!ctx ? process.env.NODE_ENV !== "production" ? UNSAFE_invariant(false, getDataRouterConsoleError(hookName)) : UNSAFE_invariant(false) : void 0; | ||
return ctx; | ||
} | ||
function useDataRouterState(hookName) { | ||
let state = React.useContext(UNSAFE_DataRouterStateContext); | ||
!state ? process.env.NODE_ENV !== "production" ? invariant(false, getDataRouterConsoleError(hookName)) : invariant(false) : void 0; | ||
!state ? process.env.NODE_ENV !== "production" ? UNSAFE_invariant(false, getDataRouterConsoleError(hookName)) : UNSAFE_invariant(false) : void 0; | ||
return state; | ||
} | ||
// External hooks | ||
/** | ||
@@ -659,4 +1026,2 @@ * Handles the click behavior for router `<Link>` components. This is useful if | ||
*/ | ||
function useLinkClickHandler(to, _temp) { | ||
@@ -668,3 +1033,4 @@ let { | ||
preventScrollReset, | ||
relative | ||
relative, | ||
unstable_viewTransition | ||
} = _temp === void 0 ? {} : _temp; | ||
@@ -678,5 +1044,5 @@ let navigate = useNavigate(); | ||
if (shouldProcessLinkClick(event, target)) { | ||
event.preventDefault(); // If the URL hasn't changed, a regular <a> will do a replace instead of | ||
event.preventDefault(); | ||
// If the URL hasn't changed, a regular <a> will do a replace instead of | ||
// a push, so do the same here unless the replace prop is explicitly set | ||
let replace = replaceProp !== undefined ? replaceProp : createPath(location) === createPath(path); | ||
@@ -687,6 +1053,7 @@ navigate(to, { | ||
preventScrollReset, | ||
relative | ||
relative, | ||
unstable_viewTransition | ||
}); | ||
} | ||
}, [location, navigate, path, replaceProp, state, target, to, preventScrollReset, relative]); | ||
}, [location, navigate, path, replaceProp, state, target, to, preventScrollReset, relative, unstable_viewTransition]); | ||
} | ||
@@ -697,9 +1064,9 @@ /** | ||
*/ | ||
function useSearchParams(defaultInit) { | ||
process.env.NODE_ENV !== "production" ? warning(typeof URLSearchParams !== "undefined", "You cannot use the `useSearchParams` hook in a browser that does not " + "support the URLSearchParams API. If you need to support Internet " + "Explorer 11, we recommend you load a polyfill such as " + "https://github.com/ungap/url-search-params\n\n" + "If you're unsure how to load polyfills, we recommend you check out " + "https://polyfill.io/v3/ which provides some recommendations about how " + "to load polyfills only for users that need them, instead of for every " + "user.") : void 0; | ||
process.env.NODE_ENV !== "production" ? UNSAFE_warning(typeof URLSearchParams !== "undefined", "You cannot use the `useSearchParams` hook in a browser that does not " + "support the URLSearchParams API. If you need to support Internet " + "Explorer 11, we recommend you load a polyfill such as " + "https://github.com/ungap/url-search-params.") : void 0; | ||
let defaultSearchParamsRef = React.useRef(createSearchParams(defaultInit)); | ||
let hasSetSearchParamsRef = React.useRef(false); | ||
let location = useLocation(); | ||
let searchParams = React.useMemo(() => // Only merge in the defaults if we haven't yet called setSearchParams. | ||
let searchParams = React.useMemo(() => | ||
// Only merge in the defaults if we haven't yet called setSearchParams. | ||
// Once we call that we want those to take precedence, otherwise you can't | ||
@@ -716,2 +1083,9 @@ // remove a param with setSearchParams({}) if it has an initial value | ||
} | ||
function validateClientSideSubmission() { | ||
if (typeof document === "undefined") { | ||
throw new Error("You are calling submit during the server render. " + "Try calling submit within a `useEffect` or callback instead."); | ||
} | ||
} | ||
let fetcherId = 0; | ||
let getUniqueFetcherId = () => "__" + String(++fetcherId) + "__"; | ||
/** | ||
@@ -721,12 +1095,10 @@ * Returns a function that may be used to programmatically submit a form (or | ||
*/ | ||
function useSubmit() { | ||
return useSubmitImpl(); | ||
} | ||
function useSubmitImpl(fetcherKey, routeId) { | ||
let { | ||
router | ||
} = useDataRouterContext(DataRouterHook.UseSubmitImpl); | ||
let defaultAction = useFormAction(); | ||
} = useDataRouterContext(DataRouterHook.UseSubmit); | ||
let { | ||
basename | ||
} = React.useContext(UNSAFE_NavigationContext); | ||
let currentRouteId = UNSAFE_useRouteId(); | ||
return React.useCallback(function (target, options) { | ||
@@ -736,31 +1108,38 @@ if (options === void 0) { | ||
} | ||
if (typeof document === "undefined") { | ||
throw new Error("You are calling submit during the server render. " + "Try calling submit within a `useEffect` or callback instead."); | ||
} | ||
validateClientSideSubmission(); | ||
let { | ||
action, | ||
method, | ||
encType, | ||
formData, | ||
url | ||
} = getFormSubmissionInfo(target, defaultAction, options); | ||
let href = url.pathname + url.search; | ||
let opts = { | ||
replace: options.replace, | ||
preventScrollReset: options.preventScrollReset, | ||
formData, | ||
formMethod: method, | ||
formEncType: encType | ||
}; | ||
if (fetcherKey) { | ||
!(routeId != null) ? process.env.NODE_ENV !== "production" ? invariant(false, "No routeId available for useFetcher()") : invariant(false) : void 0; | ||
router.fetch(fetcherKey, routeId, href, opts); | ||
body | ||
} = getFormSubmissionInfo(target, basename); | ||
if (options.navigate === false) { | ||
let key = options.fetcherKey || getUniqueFetcherId(); | ||
router.fetch(key, currentRouteId, options.action || action, { | ||
preventScrollReset: options.preventScrollReset, | ||
formData, | ||
body, | ||
formMethod: options.method || method, | ||
formEncType: options.encType || encType, | ||
unstable_flushSync: options.unstable_flushSync | ||
}); | ||
} else { | ||
router.navigate(href, opts); | ||
router.navigate(options.action || action, { | ||
preventScrollReset: options.preventScrollReset, | ||
formData, | ||
body, | ||
formMethod: options.method || method, | ||
formEncType: options.encType || encType, | ||
replace: options.replace, | ||
state: options.state, | ||
fromRouteId: currentRouteId, | ||
unstable_flushSync: options.unstable_flushSync, | ||
unstable_viewTransition: options.unstable_viewTransition | ||
}); | ||
} | ||
}, [defaultAction, router, fetcherKey, routeId]); | ||
}, [router, basename, currentRouteId]); | ||
} | ||
// v7: Eventually we should deprecate this entirely in favor of using the | ||
// router method directly? | ||
function useFormAction(action, _temp2) { | ||
@@ -774,28 +1153,22 @@ let { | ||
let routeContext = React.useContext(UNSAFE_RouteContext); | ||
!routeContext ? process.env.NODE_ENV !== "production" ? invariant(false, "useFormAction must be used inside a RouteContext") : invariant(false) : void 0; | ||
let [match] = routeContext.matches.slice(-1); // Shallow clone path so we can modify it below, otherwise we modify the | ||
!routeContext ? process.env.NODE_ENV !== "production" ? UNSAFE_invariant(false, "useFormAction must be used inside a RouteContext") : UNSAFE_invariant(false) : void 0; | ||
let [match] = routeContext.matches.slice(-1); | ||
// Shallow clone path so we can modify it below, otherwise we modify the | ||
// object referenced by useMemo inside useResolvedPath | ||
let path = _extends({}, useResolvedPath(action ? action : ".", { | ||
relative | ||
})); // Previously we set the default action to ".". The problem with this is that | ||
// `useResolvedPath(".")` excludes search params and the hash of the resolved | ||
// URL. This is the intended behavior of when "." is specifically provided as | ||
// the form action, but inconsistent w/ browsers when the action is omitted. | ||
})); | ||
// If no action was specified, browsers will persist current search params | ||
// when determining the path, so match that behavior | ||
// https://github.com/remix-run/remix/issues/927 | ||
let location = useLocation(); | ||
if (action == null) { | ||
// Safe to write to these directly here since if action was undefined, we | ||
// Safe to write to this directly here since if action was undefined, we | ||
// would have called useResolvedPath(".") which will never include a search | ||
// or hash | ||
path.search = location.search; | ||
path.hash = location.hash; // When grabbing search params from the URL, remove the automatically | ||
// inserted ?index param so we match the useResolvedPath search behavior | ||
// which would not include ?index | ||
if (match.route.index) { | ||
let params = new URLSearchParams(path.search); | ||
// When grabbing search params from the URL, remove any included ?index param | ||
// since it might not apply to our contextual route. We add it back based | ||
// on match.route.index below | ||
let params = new URLSearchParams(path.search); | ||
if (params.has("index") && params.get("index") === "") { | ||
params.delete("index"); | ||
@@ -805,35 +1178,15 @@ path.search = params.toString() ? "?" + params.toString() : ""; | ||
} | ||
if ((!action || action === ".") && match.route.index) { | ||
path.search = path.search ? path.search.replace(/^\?/, "?index&") : "?index"; | ||
} // If we're operating within a basename, prepend it to the pathname prior | ||
} | ||
// If we're operating within a basename, prepend it to the pathname prior | ||
// to creating the form action. If this is a root navigation, then just use | ||
// the raw basename which allows the basename to have full control over the | ||
// presence of a trailing slash on root actions | ||
if (basename !== "/") { | ||
path.pathname = path.pathname === "/" ? basename : joinPaths([basename, path.pathname]); | ||
} | ||
return createPath(path); | ||
} | ||
function createFetcherForm(fetcherKey, routeId) { | ||
let FetcherForm = /*#__PURE__*/React.forwardRef((props, ref) => { | ||
return /*#__PURE__*/React.createElement(FormImpl, _extends({}, props, { | ||
ref: ref, | ||
fetcherKey: fetcherKey, | ||
routeId: routeId | ||
})); | ||
}); | ||
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` | ||
/** | ||
@@ -843,43 +1196,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); | ||
!route ? process.env.NODE_ENV !== "production" ? invariant(false, "useFetcher must be used inside a RouteContext") : 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" ? invariant(false, "useFetcher can only be used on routes that contain a unique \"id\"") : invariant(false) : void 0; | ||
let [fetcherKey] = React.useState(() => String(++fetcherId)); | ||
let [Form] = React.useState(() => { | ||
!routeId ? process.env.NODE_ENV !== "production" ? invariant(false, "No routeId available for fetcher.Form()") : invariant(false) : void 0; | ||
return createFetcherForm(fetcherKey, routeId); | ||
}); | ||
let [load] = React.useState(() => href => { | ||
!router ? process.env.NODE_ENV !== "production" ? invariant(false, "No router available for fetcher.load()") : invariant(false) : void 0; | ||
!routeId ? process.env.NODE_ENV !== "production" ? invariant(false, "No routeId available for fetcher.load()") : invariant(false) : void 0; | ||
router.fetch(fetcherKey, routeId, href); | ||
}); | ||
let submit = useSubmitImpl(fetcherKey, routeId); | ||
let fetcher = router.getFetcher(fetcherKey); | ||
let fetcherWithComponents = React.useMemo(() => _extends({ | ||
Form, | ||
submit, | ||
load | ||
}, fetcher), [fetcher, Form, submit, load]); | ||
!fetcherData ? process.env.NODE_ENV !== "production" ? UNSAFE_invariant(false, "useFetcher must be used inside a FetchersContext") : UNSAFE_invariant(false) : void 0; | ||
!route ? process.env.NODE_ENV !== "production" ? UNSAFE_invariant(false, "useFetcher must be used inside a RouteContext") : UNSAFE_invariant(false) : void 0; | ||
!(routeId != null) ? process.env.NODE_ENV !== "production" ? UNSAFE_invariant(false, "useFetcher can only be used on routes that contain a unique \"id\"") : UNSAFE_invariant(false) : void 0; | ||
// Fetcher key handling | ||
// OK to call conditionally to feature detect `useId` | ||
// eslint-disable-next-line react-hooks/rules-of-hooks | ||
let defaultKey = useIdImpl ? useIdImpl() : ""; | ||
let [fetcherKey, setFetcherKey] = React.useState(key || defaultKey); | ||
if (key && key !== fetcherKey) { | ||
setFetcherKey(key); | ||
} else if (!fetcherKey) { | ||
// We will only fall through here when `useId` is not available | ||
setFetcherKey(getUniqueFetcherId()); | ||
} | ||
// Registration/cleanup | ||
React.useEffect(() => { | ||
// 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 fetcher 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; | ||
@@ -891,6 +1274,10 @@ } | ||
*/ | ||
function useFetchers() { | ||
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 | ||
}); | ||
}); | ||
} | ||
@@ -902,8 +1289,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 { | ||
@@ -916,6 +1302,9 @@ router | ||
} = useDataRouterState(DataRouterStateHook.UseScrollRestoration); | ||
let { | ||
basename | ||
} = React.useContext(UNSAFE_NavigationContext); | ||
let location = useLocation(); | ||
let matches = useMatches(); | ||
let navigation = useNavigation(); // Trigger manual scroll restoration while we're active | ||
let navigation = useNavigation(); | ||
// Trigger manual scroll restoration while we're active | ||
React.useEffect(() => { | ||
@@ -926,4 +1315,4 @@ window.history.scrollRestoration = "manual"; | ||
}; | ||
}, []); // Save positions on pagehide | ||
}, []); | ||
// Save positions on pagehide | ||
usePageHide(React.useCallback(() => { | ||
@@ -934,7 +1323,10 @@ if (navigation.state === "idle") { | ||
} | ||
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"; | ||
}, [storageKey, getKey, navigation.state, location, matches])); // Read in any saved scroll locations | ||
}, [storageKey, getKey, navigation.state, location, matches])); | ||
// Read in any saved scroll locations | ||
if (typeof document !== "undefined") { | ||
@@ -945,17 +1337,21 @@ // eslint-disable-next-line react-hooks/rules-of-hooks | ||
let sessionPositions = sessionStorage.getItem(storageKey || SCROLL_RESTORATION_STORAGE_KEY); | ||
if (sessionPositions) { | ||
savedScrollPositions = JSON.parse(sessionPositions); | ||
} | ||
} catch (e) {// no-op, use default empty object | ||
} catch (e) { | ||
// no-op, use default empty object | ||
} | ||
}, [storageKey]); // Enable scroll restoration in the router | ||
}, [storageKey]); | ||
// Enable scroll restoration in the router | ||
// eslint-disable-next-line react-hooks/rules-of-hooks | ||
React.useLayoutEffect(() => { | ||
let disableScrollRestoration = router == null ? void 0 : router.enableScrollRestoration(savedScrollPositions, () => window.scrollY, getKey); | ||
let getKeyWithoutBasename = getKey && basename !== "/" ? (location, matches) => getKey( // Strip the basename to match useLocation() | ||
_extends({}, location, { | ||
pathname: stripBasename(location.pathname, basename) || location.pathname | ||
}), matches) : getKey; | ||
let disableScrollRestoration = router == null ? void 0 : router.enableScrollRestoration(savedScrollPositions, () => window.scrollY, getKeyWithoutBasename); | ||
return () => disableScrollRestoration && disableScrollRestoration(); | ||
}, [router, getKey]); // Restore scrolling when state.restoreScrollPosition changes | ||
}, [router, basename, getKey]); | ||
// Restore scrolling when state.restoreScrollPosition changes | ||
// eslint-disable-next-line react-hooks/rules-of-hooks | ||
React.useLayoutEffect(() => { | ||
@@ -965,14 +1361,11 @@ // Explicit false means don't do anything (used for submissions) | ||
return; | ||
} // been here before, scroll to it | ||
} | ||
// been here before, scroll to it | ||
if (typeof restoreScrollPosition === "number") { | ||
window.scrollTo(0, restoreScrollPosition); | ||
return; | ||
} // try to scroll to the hash | ||
} | ||
// try to scroll to the hash | ||
if (location.hash) { | ||
let el = document.getElementById(location.hash.slice(1)); | ||
let el = document.getElementById(decodeURIComponent(location.hash.slice(1))); | ||
if (el) { | ||
@@ -982,10 +1375,8 @@ el.scrollIntoView(); | ||
} | ||
} // Don't reset if this navigation opted out | ||
} | ||
// Don't reset if this navigation opted out | ||
if (preventScrollReset === true) { | ||
return; | ||
} // otherwise go to the top on new locations | ||
} | ||
// otherwise go to the top on new locations | ||
window.scrollTo(0, 0); | ||
@@ -1003,4 +1394,2 @@ }, [location, restoreScrollPosition, preventScrollReset]); | ||
*/ | ||
function useBeforeUnload(callback, options) { | ||
@@ -1028,3 +1417,2 @@ let { | ||
*/ | ||
function usePageHide(callback, options) { | ||
@@ -1052,20 +1440,15 @@ let { | ||
*/ | ||
function usePrompt(_ref8) { | ||
function usePrompt(_ref12) { | ||
let { | ||
when, | ||
message | ||
} = _ref8; | ||
let blocker = unstable_useBlocker(when); | ||
} = _ref12; | ||
let blocker = useBlocker(when); | ||
React.useEffect(() => { | ||
if (blocker.state === "blocked" && !when) { | ||
blocker.reset(); | ||
} | ||
}, [blocker, when]); | ||
React.useEffect(() => { | ||
if (blocker.state === "blocked") { | ||
let proceed = window.confirm(message); | ||
if (proceed) { | ||
// This timeout is needed to avoid a weird "race" on POP navigations | ||
// between the `window.history` revert navigation and the result of | ||
// `window.confirm` | ||
setTimeout(blocker.proceed, 0); | ||
@@ -1077,24 +1460,51 @@ } else { | ||
}, [blocker, message]); | ||
React.useEffect(() => { | ||
if (blocker.state === "blocked" && !when) { | ||
blocker.reset(); | ||
} | ||
}, [blocker, when]); | ||
} | ||
//////////////////////////////////////////////////////////////////////////////// | ||
//#region Utils | ||
//////////////////////////////////////////////////////////////////////////////// | ||
function warning(cond, message) { | ||
if (!cond) { | ||
// eslint-disable-next-line no-console | ||
if (typeof console !== "undefined") console.warn(message); | ||
try { | ||
// Welcome to debugging React Router! | ||
// | ||
// This error is thrown as a convenience so you can more easily | ||
// find the source for a warning that appears in the console by | ||
// enabling "pause on exceptions" in your JavaScript debugger. | ||
throw new Error(message); // eslint-disable-next-line no-empty | ||
} catch (e) {} | ||
/** | ||
* 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 = {}; | ||
} | ||
} //#endregion | ||
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-cf9637ce | ||
* React Router DOM v0.0.0-experimental-cffa549a1 | ||
* | ||
@@ -4,0 +4,0 @@ * Copyright (c) Remix Software Inc. |
/** | ||
* React Router DOM v0.0.0-experimental-cf9637ce | ||
* React Router DOM v0.0.0-experimental-cffa549a1 | ||
* | ||
@@ -12,5 +12,7 @@ * Copyright (c) Remix Software Inc. | ||
import * as React from 'react'; | ||
import { UNSAFE_enhanceManualRouteObjects, Router, useHref, useResolvedPath, useLocation, UNSAFE_DataRouterStateContext, UNSAFE_NavigationContext, useNavigate, createPath, 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_enhanceManualRouteObjects, 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 { createRouter, createBrowserHistory, createHashHistory, ErrorResponse, 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'; | ||
@@ -31,10 +33,10 @@ const defaultMethod = "get"; | ||
} | ||
function isModifiedEvent(event) { | ||
return !!(event.metaKey || event.altKey || event.ctrlKey || event.shiftKey); | ||
} | ||
function shouldProcessLinkClick(event, target) { | ||
return event.button === 0 && ( // Ignore everything but left clicks | ||
!target || target === "_self") && // Let browser handle "target=_blank" etc. | ||
return event.button === 0 && ( | ||
// Ignore everything but left clicks | ||
!target || target === "_self") && | ||
// Let browser handle "target=_blank" etc. | ||
!isModifiedEvent(event) // Ignore clicks with modifier keys | ||
@@ -73,5 +75,9 @@ ; | ||
let searchParams = createSearchParams(locationSearch); | ||
if (defaultSearchParams) { | ||
for (let key of defaultSearchParams.keys()) { | ||
// Use `defaultSearchParams.forEach(...)` here instead of iterating of | ||
// `defaultSearchParams.keys()` to work-around a bug in Firefox related to | ||
// web extensions. Relevant Bugzilla tickets: | ||
// https://bugzilla.mozilla.org/show_bug.cgi?id=1414602 | ||
// https://bugzilla.mozilla.org/show_bug.cgi?id=1023984 | ||
defaultSearchParams.forEach((_, key) => { | ||
if (!searchParams.has(key)) { | ||
@@ -82,8 +88,46 @@ defaultSearchParams.getAll(key).forEach(value => { | ||
} | ||
}); | ||
} | ||
return searchParams; | ||
} | ||
// Thanks https://github.com/sindresorhus/type-fest! | ||
// One-time check for submitter support | ||
let _formDataSupportsSubmitter = null; | ||
function isFormDataSubmitterSupported() { | ||
if (_formDataSupportsSubmitter === null) { | ||
try { | ||
new FormData(document.createElement("form"), | ||
// @ts-expect-error if FormData supports the submitter parameter, this will throw | ||
0); | ||
_formDataSupportsSubmitter = false; | ||
} catch (e) { | ||
_formDataSupportsSubmitter = true; | ||
} | ||
} | ||
return _formDataSupportsSubmitter; | ||
} | ||
return searchParams; | ||
/** | ||
* 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"]); | ||
function getFormEncType(encType) { | ||
if (encType != null && !supportedFormEncTypes.has(encType)) { | ||
UNSAFE_warning(false, `"${encType}" is not a valid \`encType\` for \`<Form>\`/\`<fetcher.Form>\` ` + `and will default to "${defaultEncType}"`) ; | ||
return null; | ||
} | ||
return encType; | ||
} | ||
function getFormSubmissionInfo(target, defaultAction, options) { | ||
function getFormSubmissionInfo(target, basename) { | ||
let method; | ||
@@ -93,29 +137,48 @@ let action; | ||
let formData; | ||
let body; | ||
if (isFormElement(target)) { | ||
let submissionTrigger = options.submissionTrigger; | ||
method = options.method || target.getAttribute("method") || defaultMethod; | ||
action = options.action || target.getAttribute("action") || defaultAction; | ||
encType = options.encType || target.getAttribute("enctype") || defaultEncType; | ||
// When grabbing the action from the element, it will have had the basename | ||
// prefixed to ensure non-JS scenarios work, so strip it since we'll | ||
// re-prefix in the router | ||
let attr = target.getAttribute("action"); | ||
action = attr ? stripBasename(attr, basename) : null; | ||
method = target.getAttribute("method") || defaultMethod; | ||
encType = getFormEncType(target.getAttribute("enctype")) || defaultEncType; | ||
formData = new FormData(target); | ||
if (submissionTrigger && submissionTrigger.name) { | ||
formData.append(submissionTrigger.name, submissionTrigger.value); | ||
} | ||
} else if (isButtonElement(target) || isInputElement(target) && (target.type === "submit" || target.type === "image")) { | ||
let form = target.form; | ||
if (form == null) { | ||
throw new Error(`Cannot submit a <button> or <input type="submit"> without a <form>`); | ||
} // <button>/<input type="submit"> may override attributes of <form> | ||
} | ||
// <button>/<input type="submit"> may override attributes of <form> | ||
method = options.method || target.getAttribute("formmethod") || form.getAttribute("method") || defaultMethod; | ||
action = options.action || target.getAttribute("formaction") || form.getAttribute("action") || defaultAction; | ||
encType = options.encType || target.getAttribute("formenctype") || form.getAttribute("enctype") || defaultEncType; | ||
formData = new FormData(form); // Include name + value from a <button>, appending in case the button name | ||
// matches an existing input name | ||
// When grabbing the action from the element, it will have had the basename | ||
// prefixed to ensure non-JS scenarios work, so strip it since we'll | ||
// re-prefix in the router | ||
let attr = target.getAttribute("formaction") || form.getAttribute("action"); | ||
action = attr ? stripBasename(attr, basename) : null; | ||
method = target.getAttribute("formmethod") || form.getAttribute("method") || defaultMethod; | ||
encType = getFormEncType(target.getAttribute("formenctype")) || getFormEncType(form.getAttribute("enctype")) || defaultEncType; | ||
if (target.name) { | ||
formData.append(target.name, target.value); | ||
// Build a FormData object populated from a form and submitter | ||
formData = new FormData(form, target); | ||
// If this browser doesn't support the `FormData(el, submitter)` format, | ||
// then tack on the submitter value at the end. This is a lightweight | ||
// solution that is not 100% spec compliant. For complete support in older | ||
// browsers, consider using the `formdata-submitter-polyfill` package | ||
if (!isFormDataSubmitterSupported()) { | ||
let { | ||
name, | ||
type, | ||
value | ||
} = target; | ||
if (type === "image") { | ||
let prefix = name ? `${name}.` : ""; | ||
formData.append(`${prefix}x`, "0"); | ||
formData.append(`${prefix}y`, "0"); | ||
} else if (name) { | ||
formData.append(name, value); | ||
} | ||
} | ||
@@ -125,33 +188,19 @@ } else if (isHtmlElement(target)) { | ||
} else { | ||
method = options.method || defaultMethod; | ||
action = options.action || defaultAction; | ||
encType = options.encType || defaultEncType; | ||
method = defaultMethod; | ||
action = null; | ||
encType = defaultEncType; | ||
body = target; | ||
} | ||
if (target instanceof FormData) { | ||
formData = target; | ||
} else { | ||
formData = new FormData(); | ||
if (target instanceof URLSearchParams) { | ||
for (let [name, value] of target) { | ||
formData.append(name, value); | ||
} | ||
} else if (target != null) { | ||
for (let name of Object.keys(target)) { | ||
formData.append(name, target[name]); | ||
} | ||
} | ||
} | ||
// Send body for <Form encType="text/plain" so we encode it into text | ||
if (formData && encType === "text/plain") { | ||
body = formData; | ||
formData = undefined; | ||
} | ||
let { | ||
protocol, | ||
host | ||
} = window.location; | ||
let url = new URL(action, `${protocol}//${host}`); | ||
return { | ||
url, | ||
action, | ||
method: method.toLowerCase(), | ||
encType, | ||
formData | ||
formData, | ||
body | ||
}; | ||
@@ -164,3 +213,20 @@ } | ||
*/ | ||
//#endregion | ||
// 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 | ||
} | ||
//////////////////////////////////////////////////////////////////////////////// | ||
@@ -172,2 +238,6 @@ //#region Routers | ||
basename: opts?.basename, | ||
future: { | ||
...opts?.future, | ||
v7_prependBasename: true | ||
}, | ||
history: createBrowserHistory({ | ||
@@ -177,3 +247,7 @@ window: opts?.window | ||
hydrationData: opts?.hydrationData || parseHydrationData(), | ||
routes: UNSAFE_enhanceManualRouteObjects(routes) | ||
routes, | ||
mapRouteProperties: UNSAFE_mapRouteProperties, | ||
unstable_dataStrategy: opts?.unstable_dataStrategy, | ||
unstable_patchRoutesOnMiss: opts?.unstable_patchRoutesOnMiss, | ||
window: opts?.window | ||
}).initialize(); | ||
@@ -184,2 +258,6 @@ } | ||
basename: opts?.basename, | ||
future: { | ||
...opts?.future, | ||
v7_prependBasename: true | ||
}, | ||
history: createHashHistory({ | ||
@@ -189,18 +267,19 @@ window: opts?.window | ||
hydrationData: opts?.hydrationData || parseHydrationData(), | ||
routes: UNSAFE_enhanceManualRouteObjects(routes) | ||
routes, | ||
mapRouteProperties: UNSAFE_mapRouteProperties, | ||
unstable_dataStrategy: opts?.unstable_dataStrategy, | ||
unstable_patchRoutesOnMiss: opts?.unstable_patchRoutesOnMiss, | ||
window: opts?.window | ||
}).initialize(); | ||
} | ||
function parseHydrationData() { | ||
let state = window?.__staticRouterHydrationData; | ||
if (state && state.errors) { | ||
state = { ...state, | ||
state = { | ||
...state, | ||
errors: deserializeErrors(state.errors) | ||
}; | ||
} | ||
return state; | ||
} | ||
function deserializeErrors(errors) { | ||
@@ -210,3 +289,2 @@ if (!errors) return null; | ||
let serialized = {}; | ||
for (let [key, val] of entries) { | ||
@@ -216,9 +294,27 @@ // Hey you! If you change this, please change the corresponding logic in | ||
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") { | ||
let error = new Error(val.message); // Wipe away the client-side stack trace. Nothing to fill it in with | ||
// because we don't serialize SSR stack traces for security reasons | ||
error.stack = ""; | ||
serialized[key] = error; | ||
// Attempt to reconstruct the right type of Error (i.e., ReferenceError) | ||
if (val.__subType) { | ||
let ErrorConstructor = window[val.__subType]; | ||
if (typeof ErrorConstructor === "function") { | ||
try { | ||
// @ts-expect-error | ||
let error = new ErrorConstructor(val.message); | ||
// Wipe away the client-side stack trace. Nothing to fill it in with | ||
// because we don't serialize SSR stack traces for security reasons | ||
error.stack = ""; | ||
serialized[key] = error; | ||
} catch (e) { | ||
// no-op - fall through and create a normal Error | ||
} | ||
} | ||
} | ||
if (serialized[key] == null) { | ||
let error = new Error(val.message); | ||
// Wipe away the client-side stack trace. Nothing to fill it in with | ||
// because we don't serialize SSR stack traces for security reasons | ||
error.stack = ""; | ||
serialized[key] = error; | ||
} | ||
} else { | ||
@@ -228,11 +324,329 @@ serialized[key] = val; | ||
} | ||
return serialized; | ||
} | ||
return serialized; | ||
} //#endregion | ||
//#endregion | ||
//////////////////////////////////////////////////////////////////////////////// | ||
//#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 | ||
//////////////////////////////////////////////////////////////////////////////// | ||
/** | ||
Webpack + React 17 fails to compile on any of the following because webpack | ||
complains that `startTransition` doesn't exist in `React`: | ||
* import { startTransition } from "react" | ||
* import * as React from from "react"; | ||
"startTransition" in React ? React.startTransition(() => setState()) : setState() | ||
* import * as React from from "react"; | ||
"startTransition" in React ? React["startTransition"](() => setState()) : setState() | ||
Moving it to a constant such as the following solves the Webpack/React 17 issue: | ||
* import * as React from from "react"; | ||
const START_TRANSITION = "startTransition"; | ||
START_TRANSITION in React ? React[START_TRANSITION](() => setState()) : setState() | ||
However, that introduces webpack/terser minification issues in production builds | ||
in React 18 where minification/obfuscation ends up removing the call of | ||
React.startTransition entirely from the first half of the ternary. Grabbing | ||
this exported reference once up front resolves that issue. | ||
See https://github.com/remix-run/react-router/issues/10579 | ||
*/ | ||
const START_TRANSITION = "startTransition"; | ||
const startTransitionImpl = React[START_TRANSITION]; | ||
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]); | ||
// The fragment and {null} here are important! We need them to keep React 18's | ||
// useId happy when we are server-rendering since we may have a <script> here | ||
// containing the hydrated server-side staticContext (from StaticRouterProvider). | ||
// useId relies on the component tree structure to generate deterministic id's | ||
// so we need to ensure it remains the same on the client even though | ||
// we don't need the <script> tag | ||
return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(UNSAFE_DataRouterContext.Provider, { | ||
value: dataRouterContext | ||
}, /*#__PURE__*/React.createElement(UNSAFE_DataRouterStateContext.Provider, { | ||
value: state | ||
}, /*#__PURE__*/React.createElement(FetchersContext.Provider, { | ||
value: fetcherData.current | ||
}, /*#__PURE__*/React.createElement(ViewTransitionContext.Provider, { | ||
value: vtContext | ||
}, /*#__PURE__*/React.createElement(Router, { | ||
basename: basename, | ||
location: state.location, | ||
navigationType: state.historyAction, | ||
navigator: navigator, | ||
future: { | ||
v7_relativeSplatPath: router.future.v7_relativeSplatPath | ||
} | ||
}, state.initialized || router.future.v7_partialHydration ? /*#__PURE__*/React.createElement(DataRoutes, { | ||
routes: router.routes, | ||
future: router.future, | ||
state: state | ||
}) : fallbackElement))))), null); | ||
} | ||
function DataRoutes({ | ||
routes, | ||
future, | ||
state | ||
}) { | ||
return UNSAFE_useRoutesImpl(routes, undefined, state, future); | ||
} | ||
/** | ||
* A `<Router>` for use in web browsers. Provides the cleanest URLs. | ||
@@ -243,6 +657,6 @@ */ | ||
children, | ||
future, | ||
window | ||
}) { | ||
let historyRef = React.useRef(); | ||
if (historyRef.current == null) { | ||
@@ -254,9 +668,14 @@ historyRef.current = createBrowserHistory({ | ||
} | ||
let history = historyRef.current; | ||
let [state, setState] = React.useState({ | ||
let [state, setStateImpl] = React.useState({ | ||
action: history.action, | ||
location: history.location | ||
}); | ||
React.useLayoutEffect(() => history.listen(setState), [history]); | ||
let { | ||
v7_startTransition | ||
} = future || {}; | ||
let setState = React.useCallback(newState => { | ||
v7_startTransition && startTransitionImpl ? startTransitionImpl(() => setStateImpl(newState)) : setStateImpl(newState); | ||
}, [setStateImpl, v7_startTransition]); | ||
React.useLayoutEffect(() => history.listen(setState), [history, setState]); | ||
return /*#__PURE__*/React.createElement(Router, { | ||
@@ -267,6 +686,6 @@ basename: basename, | ||
navigationType: state.action, | ||
navigator: history | ||
navigator: history, | ||
future: future | ||
}); | ||
} | ||
/** | ||
@@ -279,6 +698,6 @@ * A `<Router>` for use in web browsers. Stores the location in the hash | ||
children, | ||
future, | ||
window | ||
}) { | ||
let historyRef = React.useRef(); | ||
if (historyRef.current == null) { | ||
@@ -290,9 +709,14 @@ historyRef.current = createHashHistory({ | ||
} | ||
let history = historyRef.current; | ||
let [state, setState] = React.useState({ | ||
let [state, setStateImpl] = React.useState({ | ||
action: history.action, | ||
location: history.location | ||
}); | ||
React.useLayoutEffect(() => history.listen(setState), [history]); | ||
let { | ||
v7_startTransition | ||
} = future || {}; | ||
let setState = React.useCallback(newState => { | ||
v7_startTransition && startTransitionImpl ? startTransitionImpl(() => setStateImpl(newState)) : setStateImpl(newState); | ||
}, [setStateImpl, v7_startTransition]); | ||
React.useLayoutEffect(() => history.listen(setState), [history, setState]); | ||
return /*#__PURE__*/React.createElement(Router, { | ||
@@ -303,6 +727,6 @@ basename: basename, | ||
navigationType: state.action, | ||
navigator: history | ||
navigator: history, | ||
future: future | ||
}); | ||
} | ||
/** | ||
@@ -317,9 +741,16 @@ * A `<Router>` that accepts a pre-instantiated history object. It's important | ||
children, | ||
future, | ||
history | ||
}) { | ||
const [state, setState] = React.useState({ | ||
let [state, setStateImpl] = React.useState({ | ||
action: history.action, | ||
location: history.location | ||
}); | ||
React.useLayoutEffect(() => history.listen(setState), [history]); | ||
let { | ||
v7_startTransition | ||
} = future || {}; | ||
let setState = React.useCallback(newState => { | ||
v7_startTransition && startTransitionImpl ? startTransitionImpl(() => setStateImpl(newState)) : setStateImpl(newState); | ||
}, [setStateImpl, v7_startTransition]); | ||
React.useLayoutEffect(() => history.listen(setState), [history, setState]); | ||
return /*#__PURE__*/React.createElement(Router, { | ||
@@ -330,6 +761,6 @@ basename: basename, | ||
navigationType: state.action, | ||
navigator: history | ||
navigator: history, | ||
future: future | ||
}); | ||
} | ||
{ | ||
@@ -339,6 +770,7 @@ HistoryRouter.displayName = "unstable_HistoryRouter"; | ||
const isBrowser = typeof window !== "undefined" && typeof window.document !== "undefined" && typeof window.document.createElement !== "undefined"; | ||
const ABSOLUTE_URL_REGEX = /^(?:[a-z][a-z0-9+.-]*:|\/\/)/i; | ||
/** | ||
* The public API for rendering a history-aware <a>. | ||
* The public API for rendering a history-aware `<a>`. | ||
*/ | ||
const Link = /*#__PURE__*/React.forwardRef(function LinkWithRef({ | ||
@@ -353,22 +785,36 @@ onClick, | ||
preventScrollReset, | ||
unstable_viewTransition, | ||
...rest | ||
}, ref) { | ||
let { | ||
basename | ||
} = React.useContext(UNSAFE_NavigationContext); | ||
// Rendered into <a href> for absolute URLs | ||
let absoluteHref; | ||
let isExternal = false; | ||
if (isBrowser && typeof to === "string" && /^(?:[a-z][a-z0-9+.-]*:|\/\/)/i.test(to)) { | ||
if (typeof to === "string" && ABSOLUTE_URL_REGEX.test(to)) { | ||
// Render the absolute href server- and client-side | ||
absoluteHref = to; | ||
let currentUrl = new URL(window.location.href); | ||
let targetUrl = to.startsWith("//") ? new URL(currentUrl.protocol + to) : new URL(to); | ||
if (targetUrl.origin === currentUrl.origin) { | ||
// Strip the protocol/origin for same-origin absolute URLs | ||
to = targetUrl.pathname + targetUrl.search + targetUrl.hash; | ||
} else { | ||
isExternal = true; | ||
// Only check for external origins client-side | ||
if (isBrowser) { | ||
try { | ||
let currentUrl = new URL(window.location.href); | ||
let targetUrl = to.startsWith("//") ? new URL(currentUrl.protocol + to) : new URL(to); | ||
let path = stripBasename(targetUrl.pathname, basename); | ||
if (targetUrl.origin === currentUrl.origin && path != null) { | ||
// Strip the protocol/origin/basename for same-origin absolute URLs | ||
to = path + targetUrl.search + targetUrl.hash; | ||
} else { | ||
isExternal = true; | ||
} | ||
} catch (e) { | ||
// We can't do external URL detection without a valid URL | ||
UNSAFE_warning(false, `<Link to="${to}"> contains an invalid URL which will probably break ` + `when clicked - please update to a valid URL path.`) ; | ||
} | ||
} | ||
} // Rendered into <a href> for relative URLs | ||
} | ||
// Rendered into <a href> for relative URLs | ||
let href = useHref(to, { | ||
@@ -382,8 +828,7 @@ relative | ||
preventScrollReset, | ||
relative | ||
relative, | ||
unstable_viewTransition | ||
}); | ||
function handleClick(event) { | ||
if (onClick) onClick(event); | ||
if (!event.defaultPrevented) { | ||
@@ -393,3 +838,2 @@ internalOnClick(event); | ||
} | ||
return ( | ||
@@ -406,9 +850,7 @@ /*#__PURE__*/ | ||
}); | ||
{ | ||
Link.displayName = "Link"; | ||
} | ||
/** | ||
* A <Link> wrapper that knows if it's "active" or not. | ||
* A `<Link>` wrapper that knows if it's "active" or not. | ||
*/ | ||
@@ -422,2 +864,3 @@ const NavLink = /*#__PURE__*/React.forwardRef(function NavLinkWithRef({ | ||
to, | ||
unstable_viewTransition, | ||
children, | ||
@@ -432,8 +875,12 @@ ...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; | ||
let locationPathname = location.pathname; | ||
let nextLocationPathname = routerState && routerState.navigation && routerState.navigation.location ? routerState.navigation.location.pathname : null; | ||
if (!caseSensitive) { | ||
@@ -444,13 +891,23 @@ locationPathname = locationPathname.toLowerCase(); | ||
} | ||
if (nextLocationPathname && basename) { | ||
nextLocationPathname = stripBasename(nextLocationPathname, basename) || nextLocationPathname; | ||
} | ||
let isActive = locationPathname === toPathname || !end && locationPathname.startsWith(toPathname) && locationPathname.charAt(toPathname.length) === "/"; | ||
// 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 { | ||
@@ -462,9 +919,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, { | ||
@@ -475,9 +928,6 @@ "aria-current": ariaCurrent, | ||
style: style, | ||
to: to | ||
}), typeof children === "function" ? children({ | ||
isActive, | ||
isPending | ||
}) : children); | ||
to: to, | ||
unstable_viewTransition: unstable_viewTransition | ||
}), typeof children === "function" ? children(renderProps) : children); | ||
}); | ||
{ | ||
@@ -488,2 +938,14 @@ NavLink.displayName = "NavLink"; | ||
/** | ||
* 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 | ||
@@ -494,30 +956,21 @@ * that the interaction with the server is with `fetch` instead of new document | ||
*/ | ||
const Form = /*#__PURE__*/React.forwardRef((props, ref) => { | ||
return /*#__PURE__*/React.createElement(FormImpl, Object.assign({}, props, { | ||
ref: ref | ||
})); | ||
}); | ||
{ | ||
Form.displayName = "Form"; | ||
} | ||
const FormImpl = /*#__PURE__*/React.forwardRef(({ | ||
const Form = /*#__PURE__*/React.forwardRef(({ | ||
fetcherKey, | ||
navigate, | ||
reloadDocument, | ||
replace, | ||
state, | ||
method: _method = defaultMethod, | ||
action, | ||
onSubmit, | ||
fetcherKey, | ||
routeId, | ||
relative, | ||
preventScrollReset, | ||
unstable_viewTransition, | ||
...props | ||
}, forwardedRef) => { | ||
let submit = useSubmitImpl(fetcherKey, routeId); | ||
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 => { | ||
@@ -528,13 +981,14 @@ onSubmit && onSubmit(event); | ||
let submitter = event.nativeEvent.submitter; | ||
let submitMethod = submitter?.getAttribute("formmethod") || _method; | ||
submit(submitter || event.currentTarget, { | ||
fetcherKey, | ||
method: submitMethod, | ||
navigate, | ||
replace, | ||
state, | ||
relative, | ||
preventScrollReset | ||
preventScrollReset, | ||
unstable_viewTransition | ||
}); | ||
}; | ||
return /*#__PURE__*/React.createElement("form", Object.assign({ | ||
@@ -547,7 +1001,5 @@ ref: forwardedRef, | ||
}); | ||
{ | ||
FormImpl.displayName = "FormImpl"; | ||
Form.displayName = "Form"; | ||
} | ||
/** | ||
@@ -567,41 +1019,40 @@ * This component will emulate the browser's scroll restoration on location | ||
} | ||
{ | ||
ScrollRestoration.displayName = "ScrollRestoration"; | ||
} //#endregion | ||
} | ||
//#endregion | ||
//////////////////////////////////////////////////////////////////////////////// | ||
//#region Hooks | ||
//////////////////////////////////////////////////////////////////////////////// | ||
var DataRouterHook; | ||
(function (DataRouterHook) { | ||
var DataRouterHook = /*#__PURE__*/function (DataRouterHook) { | ||
DataRouterHook["UseScrollRestoration"] = "useScrollRestoration"; | ||
DataRouterHook["UseSubmitImpl"] = "useSubmitImpl"; | ||
DataRouterHook["UseSubmit"] = "useSubmit"; | ||
DataRouterHook["UseSubmitFetcher"] = "useSubmitFetcher"; | ||
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) { | ||
return `${hookName} must be used within a data router. See https://reactrouter.com/routers/picking-a-router.`; | ||
} | ||
function useDataRouterContext(hookName) { | ||
let ctx = React.useContext(UNSAFE_DataRouterContext); | ||
!ctx ? invariant(false, getDataRouterConsoleError(hookName)) : void 0; | ||
!ctx ? UNSAFE_invariant(false, getDataRouterConsoleError(hookName)) : void 0; | ||
return ctx; | ||
} | ||
function useDataRouterState(hookName) { | ||
let state = React.useContext(UNSAFE_DataRouterStateContext); | ||
!state ? invariant(false, getDataRouterConsoleError(hookName)) : void 0; | ||
!state ? UNSAFE_invariant(false, getDataRouterConsoleError(hookName)) : void 0; | ||
return state; | ||
} | ||
// External hooks | ||
/** | ||
@@ -612,4 +1063,2 @@ * Handles the click behavior for router `<Link>` components. This is useful if | ||
*/ | ||
function useLinkClickHandler(to, { | ||
@@ -620,3 +1069,4 @@ target, | ||
preventScrollReset, | ||
relative | ||
relative, | ||
unstable_viewTransition | ||
} = {}) { | ||
@@ -630,5 +1080,6 @@ let navigate = useNavigate(); | ||
if (shouldProcessLinkClick(event, target)) { | ||
event.preventDefault(); // If the URL hasn't changed, a regular <a> will do a replace instead of | ||
event.preventDefault(); | ||
// If the URL hasn't changed, a regular <a> will do a replace instead of | ||
// a push, so do the same here unless the replace prop is explicitly set | ||
let replace = replaceProp !== undefined ? replaceProp : createPath(location) === createPath(path); | ||
@@ -639,7 +1090,9 @@ navigate(to, { | ||
preventScrollReset, | ||
relative | ||
relative, | ||
unstable_viewTransition | ||
}); | ||
} | ||
}, [location, navigate, path, replaceProp, state, target, to, preventScrollReset, relative]); | ||
}, [location, navigate, path, replaceProp, state, target, to, preventScrollReset, relative, unstable_viewTransition]); | ||
} | ||
/** | ||
@@ -649,9 +1102,9 @@ * A convenient wrapper for reading and writing search parameters via the | ||
*/ | ||
function useSearchParams(defaultInit) { | ||
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)); | ||
let hasSetSearchParamsRef = React.useRef(false); | ||
let location = useLocation(); | ||
let searchParams = React.useMemo(() => // Only merge in the defaults if we haven't yet called setSearchParams. | ||
let searchParams = React.useMemo(() => | ||
// Only merge in the defaults if we haven't yet called setSearchParams. | ||
// Once we call that we want those to take precedence, otherwise you can't | ||
@@ -670,2 +1123,18 @@ // remove a param with setSearchParams({}) if it has an initial value | ||
/** | ||
* Submits a HTML `<form>` to the server without reloading the page. | ||
*/ | ||
/** | ||
* Submits a fetcher `<form>` to the server without reloading the page. | ||
*/ | ||
function validateClientSideSubmission() { | ||
if (typeof document === "undefined") { | ||
throw new Error("You are calling submit during the server render. " + "Try calling submit within a `useEffect` or callback instead."); | ||
} | ||
} | ||
let fetcherId = 0; | ||
let getUniqueFetcherId = () => `__${String(++fetcherId)}__`; | ||
/** | ||
* Returns a function that may be used to programmatically submit a form (or | ||
@@ -675,39 +1144,47 @@ * some arbitrary data) to the server. | ||
function useSubmit() { | ||
return useSubmitImpl(); | ||
} | ||
function useSubmitImpl(fetcherKey, routeId) { | ||
let { | ||
router | ||
} = useDataRouterContext(DataRouterHook.UseSubmitImpl); | ||
let defaultAction = useFormAction(); | ||
} = useDataRouterContext(DataRouterHook.UseSubmit); | ||
let { | ||
basename | ||
} = React.useContext(UNSAFE_NavigationContext); | ||
let currentRouteId = UNSAFE_useRouteId(); | ||
return React.useCallback((target, options = {}) => { | ||
if (typeof document === "undefined") { | ||
throw new Error("You are calling submit during the server render. " + "Try calling submit within a `useEffect` or callback instead."); | ||
} | ||
validateClientSideSubmission(); | ||
let { | ||
action, | ||
method, | ||
encType, | ||
formData, | ||
url | ||
} = getFormSubmissionInfo(target, defaultAction, options); | ||
let href = url.pathname + url.search; | ||
let opts = { | ||
replace: options.replace, | ||
preventScrollReset: options.preventScrollReset, | ||
formData, | ||
formMethod: method, | ||
formEncType: encType | ||
}; | ||
if (fetcherKey) { | ||
!(routeId != null) ? invariant(false, "No routeId available for useFetcher()") : void 0; | ||
router.fetch(fetcherKey, routeId, href, opts); | ||
body | ||
} = getFormSubmissionInfo(target, basename); | ||
if (options.navigate === false) { | ||
let key = options.fetcherKey || getUniqueFetcherId(); | ||
router.fetch(key, currentRouteId, options.action || action, { | ||
preventScrollReset: options.preventScrollReset, | ||
formData, | ||
body, | ||
formMethod: options.method || method, | ||
formEncType: options.encType || encType, | ||
unstable_flushSync: options.unstable_flushSync | ||
}); | ||
} else { | ||
router.navigate(href, opts); | ||
router.navigate(options.action || action, { | ||
preventScrollReset: options.preventScrollReset, | ||
formData, | ||
body, | ||
formMethod: options.method || method, | ||
formEncType: options.encType || encType, | ||
replace: options.replace, | ||
state: options.state, | ||
fromRouteId: currentRouteId, | ||
unstable_flushSync: options.unstable_flushSync, | ||
unstable_viewTransition: options.unstable_viewTransition | ||
}); | ||
} | ||
}, [defaultAction, router, fetcherKey, routeId]); | ||
}, [router, basename, currentRouteId]); | ||
} | ||
// v7: Eventually we should deprecate this entirely in favor of using the | ||
// router method directly? | ||
function useFormAction(action, { | ||
@@ -720,28 +1197,26 @@ relative | ||
let routeContext = React.useContext(UNSAFE_RouteContext); | ||
!routeContext ? invariant(false, "useFormAction must be used inside a RouteContext") : void 0; | ||
let [match] = routeContext.matches.slice(-1); // Shallow clone path so we can modify it below, otherwise we modify the | ||
!routeContext ? UNSAFE_invariant(false, "useFormAction must be used inside a RouteContext") : void 0; | ||
let [match] = routeContext.matches.slice(-1); | ||
// Shallow clone path so we can modify it below, otherwise we modify the | ||
// object referenced by useMemo inside useResolvedPath | ||
let path = { ...useResolvedPath(action ? action : ".", { | ||
let path = { | ||
...useResolvedPath(action ? action : ".", { | ||
relative | ||
}) | ||
}; // Previously we set the default action to ".". The problem with this is that | ||
// `useResolvedPath(".")` excludes search params and the hash of the resolved | ||
// URL. This is the intended behavior of when "." is specifically provided as | ||
// the form action, but inconsistent w/ browsers when the action is omitted. | ||
}; | ||
// If no action was specified, browsers will persist current search params | ||
// when determining the path, so match that behavior | ||
// https://github.com/remix-run/remix/issues/927 | ||
let location = useLocation(); | ||
if (action == null) { | ||
// Safe to write to these directly here since if action was undefined, we | ||
// Safe to write to this directly here since if action was undefined, we | ||
// would have called useResolvedPath(".") which will never include a search | ||
// or hash | ||
path.search = location.search; | ||
path.hash = location.hash; // When grabbing search params from the URL, remove the automatically | ||
// inserted ?index param so we match the useResolvedPath search behavior | ||
// which would not include ?index | ||
if (match.route.index) { | ||
let params = new URLSearchParams(path.search); | ||
// When grabbing search params from the URL, remove any included ?index param | ||
// since it might not apply to our contextual route. We add it back based | ||
// on match.route.index below | ||
let params = new URLSearchParams(path.search); | ||
if (params.has("index") && params.get("index") === "") { | ||
params.delete("index"); | ||
@@ -751,36 +1226,16 @@ path.search = params.toString() ? `?${params.toString()}` : ""; | ||
} | ||
if ((!action || action === ".") && match.route.index) { | ||
path.search = path.search ? path.search.replace(/^\?/, "?index&") : "?index"; | ||
} // If we're operating within a basename, prepend it to the pathname prior | ||
} | ||
// If we're operating within a basename, prepend it to the pathname prior | ||
// to creating the form action. If this is a root navigation, then just use | ||
// the raw basename which allows the basename to have full control over the | ||
// presence of a trailing slash on root actions | ||
if (basename !== "/") { | ||
path.pathname = path.pathname === "/" ? basename : joinPaths([basename, path.pathname]); | ||
} | ||
return createPath(path); | ||
} | ||
function createFetcherForm(fetcherKey, routeId) { | ||
let FetcherForm = /*#__PURE__*/React.forwardRef((props, ref) => { | ||
return /*#__PURE__*/React.createElement(FormImpl, Object.assign({}, props, { | ||
ref: ref, | ||
fetcherKey: fetcherKey, | ||
routeId: routeId | ||
})); | ||
}); | ||
{ | ||
FetcherForm.displayName = "fetcher.Form"; | ||
} | ||
return FetcherForm; | ||
} | ||
let fetcherId = 0; | ||
// TODO: (v7) Change the useFetcher generic default from `any` to `unknown` | ||
/** | ||
@@ -790,43 +1245,79 @@ * 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); | ||
!route ? invariant(false, `useFetcher must be used inside a RouteContext`) : void 0; | ||
let routeId = route.matches[route.matches.length - 1]?.route.id; | ||
!(routeId != null) ? 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 ? invariant(false, `No routeId available for fetcher.Form()`) : void 0; | ||
return createFetcherForm(fetcherKey, routeId); | ||
}); | ||
let [load] = React.useState(() => href => { | ||
!router ? invariant(false, "No router available for fetcher.load()") : void 0; | ||
!routeId ? invariant(false, "No routeId available for fetcher.load()") : void 0; | ||
router.fetch(fetcherKey, routeId, href); | ||
}); | ||
let submit = useSubmitImpl(fetcherKey, routeId); | ||
let fetcher = router.getFetcher(fetcherKey); | ||
let fetcherWithComponents = React.useMemo(() => ({ | ||
Form, | ||
submit, | ||
load, | ||
...fetcher | ||
}), [fetcher, Form, submit, load]); | ||
!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; | ||
!(routeId != null) ? UNSAFE_invariant(false, `useFetcher can only be used on routes that contain a unique "id"`) : void 0; | ||
// Fetcher key handling | ||
// OK to call conditionally to feature detect `useId` | ||
// eslint-disable-next-line react-hooks/rules-of-hooks | ||
let defaultKey = useIdImpl ? useIdImpl() : ""; | ||
let [fetcherKey, setFetcherKey] = React.useState(key || defaultKey); | ||
if (key && key !== fetcherKey) { | ||
setFetcherKey(key); | ||
} else if (!fetcherKey) { | ||
// We will only fall through here when `useId` is not available | ||
setFetcherKey(getUniqueFetcherId()); | ||
} | ||
// Registration/cleanup | ||
React.useEffect(() => { | ||
// 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 fetcher 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; | ||
} | ||
/** | ||
@@ -836,13 +1327,15 @@ * Provides all fetchers currently on the page. Useful for layouts and parent | ||
*/ | ||
function useFetchers() { | ||
let state = useDataRouterState(DataRouterStateHook.UseFetchers); | ||
return [...state.fetchers.values()]; | ||
return Array.from(state.fetchers.entries()).map(([key, fetcher]) => ({ | ||
...fetcher, | ||
key | ||
})); | ||
} | ||
const SCROLL_RESTORATION_STORAGE_KEY = "react-router-scroll-positions"; | ||
let savedScrollPositions = {}; | ||
/** | ||
* When rendered inside a RouterProvider, will restore scroll positions on navigations | ||
*/ | ||
function useScrollRestoration({ | ||
@@ -859,6 +1352,10 @@ getKey, | ||
} = useDataRouterState(DataRouterStateHook.UseScrollRestoration); | ||
let { | ||
basename | ||
} = React.useContext(UNSAFE_NavigationContext); | ||
let location = useLocation(); | ||
let matches = useMatches(); | ||
let navigation = useNavigation(); // Trigger manual scroll restoration while we're active | ||
let navigation = useNavigation(); | ||
// Trigger manual scroll restoration while we're active | ||
React.useEffect(() => { | ||
@@ -869,4 +1366,5 @@ window.history.scrollRestoration = "manual"; | ||
}; | ||
}, []); // Save positions on pagehide | ||
}, []); | ||
// Save positions on pagehide | ||
usePageHide(React.useCallback(() => { | ||
@@ -877,7 +1375,11 @@ if (navigation.state === "idle") { | ||
} | ||
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"; | ||
}, [storageKey, getKey, navigation.state, location, matches])); // Read in any saved scroll locations | ||
}, [storageKey, getKey, navigation.state, location, matches])); | ||
// Read in any saved scroll locations | ||
if (typeof document !== "undefined") { | ||
@@ -888,17 +1390,25 @@ // eslint-disable-next-line react-hooks/rules-of-hooks | ||
let sessionPositions = sessionStorage.getItem(storageKey || SCROLL_RESTORATION_STORAGE_KEY); | ||
if (sessionPositions) { | ||
savedScrollPositions = JSON.parse(sessionPositions); | ||
} | ||
} catch (e) {// no-op, use default empty object | ||
} catch (e) { | ||
// no-op, use default empty object | ||
} | ||
}, [storageKey]); // Enable scroll restoration in the router | ||
}, [storageKey]); | ||
// Enable scroll restoration in the router | ||
// eslint-disable-next-line react-hooks/rules-of-hooks | ||
React.useLayoutEffect(() => { | ||
let disableScrollRestoration = router?.enableScrollRestoration(savedScrollPositions, () => window.scrollY, getKey); | ||
let getKeyWithoutBasename = getKey && basename !== "/" ? (location, matches) => getKey( | ||
// Strip the basename to match useLocation() | ||
{ | ||
...location, | ||
pathname: stripBasename(location.pathname, basename) || location.pathname | ||
}, matches) : getKey; | ||
let disableScrollRestoration = router?.enableScrollRestoration(savedScrollPositions, () => window.scrollY, getKeyWithoutBasename); | ||
return () => disableScrollRestoration && disableScrollRestoration(); | ||
}, [router, getKey]); // Restore scrolling when state.restoreScrollPosition changes | ||
}, [router, basename, getKey]); | ||
// Restore scrolling when state.restoreScrollPosition changes | ||
// eslint-disable-next-line react-hooks/rules-of-hooks | ||
React.useLayoutEffect(() => { | ||
@@ -908,14 +1418,13 @@ // Explicit false means don't do anything (used for submissions) | ||
return; | ||
} // been here before, scroll to it | ||
} | ||
// been here before, scroll to it | ||
if (typeof restoreScrollPosition === "number") { | ||
window.scrollTo(0, restoreScrollPosition); | ||
return; | ||
} // try to scroll to the hash | ||
} | ||
// try to scroll to the hash | ||
if (location.hash) { | ||
let el = document.getElementById(location.hash.slice(1)); | ||
let el = document.getElementById(decodeURIComponent(location.hash.slice(1))); | ||
if (el) { | ||
@@ -925,10 +1434,10 @@ el.scrollIntoView(); | ||
} | ||
} // Don't reset if this navigation opted out | ||
} | ||
// Don't reset if this navigation opted out | ||
if (preventScrollReset === true) { | ||
return; | ||
} // otherwise go to the top on new locations | ||
} | ||
// otherwise go to the top on new locations | ||
window.scrollTo(0, 0); | ||
@@ -938,2 +1447,3 @@ }, [location, restoreScrollPosition, preventScrollReset]); | ||
} | ||
/** | ||
@@ -947,4 +1457,2 @@ * Setup a callback to be fired on the window's `beforeunload` event. This is | ||
*/ | ||
function useBeforeUnload(callback, options) { | ||
@@ -964,2 +1472,3 @@ let { | ||
} | ||
/** | ||
@@ -973,3 +1482,2 @@ * Setup a callback to be fired on the window's `pagehide` event. This is | ||
*/ | ||
function usePageHide(callback, options) { | ||
@@ -989,2 +1497,3 @@ let { | ||
} | ||
/** | ||
@@ -998,4 +1507,2 @@ * Wrapper around useBlocker to show a window.confirm prompt to users instead | ||
*/ | ||
function usePrompt({ | ||
@@ -1005,13 +1512,10 @@ when, | ||
}) { | ||
let blocker = unstable_useBlocker(when); | ||
let blocker = useBlocker(when); | ||
React.useEffect(() => { | ||
if (blocker.state === "blocked" && !when) { | ||
blocker.reset(); | ||
} | ||
}, [blocker, when]); | ||
React.useEffect(() => { | ||
if (blocker.state === "blocked") { | ||
let proceed = window.confirm(message); | ||
if (proceed) { | ||
// This timeout is needed to avoid a weird "race" on POP navigations | ||
// between the `window.history` revert navigation and the result of | ||
// `window.confirm` | ||
setTimeout(blocker.proceed, 0); | ||
@@ -1023,24 +1527,51 @@ } else { | ||
}, [blocker, message]); | ||
React.useEffect(() => { | ||
if (blocker.state === "blocked" && !when) { | ||
blocker.reset(); | ||
} | ||
}, [blocker, when]); | ||
} | ||
//////////////////////////////////////////////////////////////////////////////// | ||
//#region Utils | ||
//////////////////////////////////////////////////////////////////////////////// | ||
function warning(cond, message) { | ||
if (!cond) { | ||
// eslint-disable-next-line no-console | ||
if (typeof console !== "undefined") console.warn(message); | ||
try { | ||
// Welcome to debugging React Router! | ||
// | ||
// This error is thrown as a convenience so you can more easily | ||
// find the source for a warning that appears in the console by | ||
// enabling "pause on exceptions" in your JavaScript debugger. | ||
throw new Error(message); // eslint-disable-next-line no-empty | ||
} catch (e) {} | ||
/** | ||
* 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; | ||
} | ||
} //#endregion | ||
let currentPath = stripBasename(vtContext.currentLocation.pathname, basename) || vtContext.currentLocation.pathname; | ||
let nextPath = stripBasename(vtContext.nextLocation.pathname, basename) || vtContext.nextLocation.pathname; | ||
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 }; | ||
// 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, 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-cf9637ce | ||
* React Router DOM v0.0.0-experimental-cffa549a1 | ||
* | ||
@@ -11,3 +11,3 @@ * Copyright (c) Remix Software Inc. | ||
*/ | ||
import*as e from"react";import{UNSAFE_enhanceManualRouteObjects as t,Router as r,useHref as n,useResolvedPath as o,useLocation as a,UNSAFE_DataRouterStateContext as i,UNSAFE_NavigationContext as s,useNavigate as u,createPath as l,UNSAFE_RouteContext as c,useMatches as f,useNavigation as m,unstable_useBlocker as d,UNSAFE_DataRouterContext as h}from"react-router";export{AbortedDeferredError,Await,MemoryRouter,Navigate,NavigationType,Outlet,Route,Router,RouterProvider,Routes,UNSAFE_DataRouterContext,UNSAFE_DataRouterStateContext,UNSAFE_LocationContext,UNSAFE_NavigationContext,UNSAFE_RouteContext,UNSAFE_enhanceManualRouteObjects,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{createRouter as p,createBrowserHistory as w,createHashHistory as g,ErrorResponse as y,invariant as v,joinPaths as b}from"@remix-run/router";const R="application/x-www-form-urlencoded";function S(e){return null!=e&&"string"==typeof e.tagName}function E(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]])}),[]))}function C(e,t,r){let n,o,a,i;if(S(s=e)&&"form"===s.tagName.toLowerCase()){let s=r.submissionTrigger;n=r.method||e.getAttribute("method")||"get",o=r.action||e.getAttribute("action")||t,a=r.encType||e.getAttribute("enctype")||R,i=new FormData(e),s&&s.name&&i.append(s.name,s.value)}else if(function(e){return S(e)&&"button"===e.tagName.toLowerCase()}(e)||function(e){return S(e)&&"input"===e.tagName.toLowerCase()}(e)&&("submit"===e.type||"image"===e.type)){let s=e.form;if(null==s)throw new Error('Cannot submit a <button> or <input type="submit"> without a <form>');n=r.method||e.getAttribute("formmethod")||s.getAttribute("method")||"get",o=r.action||e.getAttribute("formaction")||s.getAttribute("action")||t,a=r.encType||e.getAttribute("formenctype")||s.getAttribute("enctype")||R,i=new FormData(s),e.name&&i.append(e.name,e.value)}else{if(S(e))throw new Error('Cannot submit element that is not <form>, <button>, or <input type="submit|image">');if(n=r.method||"get",o=r.action||t,a=r.encType||R,e instanceof FormData)i=e;else if(i=new FormData,e instanceof URLSearchParams)for(let[t,r]of e)i.append(t,r);else if(null!=e)for(let t of Object.keys(e))i.append(t,e[t])}var s;let{protocol:u,host:l}=window.location;return{url:new URL(o,`${u}//${l}`),method:n.toLowerCase(),encType:a,formData:i}}function A(e,r){return p({basename:r?.basename,history:w({window:r?.window}),hydrationData:r?.hydrationData||U(),routes:t(e)}).initialize()}function L(e,r){return p({basename:r?.basename,history:g({window:r?.window}),hydrationData:r?.hydrationData||U(),routes:t(e)}).initialize()}function U(){let e=window?.__staticRouterHydrationData;return e&&e.errors&&(e={...e,errors:x(e.errors)}),e}function x(e){if(!e)return null;let t=Object.entries(e),r={};for(let[n,o]of t)if(o&&"RouteErrorResponse"===o.__type)r[n]=new y(o.status,o.statusText,o.data,!0===o.internal);else if(o&&"Error"===o.__type){let e=new Error(o.message);e.stack="",r[n]=e}else r[n]=o;return r}function F({basename:t,children:n,window:o}){let a=e.useRef();null==a.current&&(a.current=w({window:o,v5Compat:!0}));let i=a.current,[s,u]=e.useState({action:i.action,location:i.location});return e.useLayoutEffect((()=>i.listen(u)),[i]),e.createElement(r,{basename:t,children:n,location:s.location,navigationType:s.action,navigator:i})}function D({basename:t,children:n,window:o}){let a=e.useRef();null==a.current&&(a.current=g({window:o,v5Compat:!0}));let i=a.current,[s,u]=e.useState({action:i.action,location:i.location});return e.useLayoutEffect((()=>i.listen(u)),[i]),e.createElement(r,{basename:t,children:n,location:s.location,navigationType:s.action,navigator:i})}function N({basename:t,children:n,history:o}){const[a,i]=e.useState({action:o.action,location:o.location});return e.useLayoutEffect((()=>o.listen(i)),[o]),e.createElement(r,{basename:t,children:n,location:a.location,navigationType:a.action,navigator:o})}const P="undefined"!=typeof window&&void 0!==window.document&&void 0!==window.document.createElement,T=e.forwardRef((function({onClick:t,relative:r,reloadDocument:o,replace:a,state:i,target:s,to:u,preventScrollReset:l,...c},f){let m,d=!1;if(P&&"string"==typeof u&&/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i.test(u)){m=u;let e=new URL(window.location.href),t=u.startsWith("//")?new URL(e.protocol+u):new URL(u);t.origin===e.origin?u=t.pathname+t.search+t.hash:d=!0}let h=n(u,{relative:r}),p=B(u,{replace:a,state:i,target:s,preventScrollReset:l,relative:r});return e.createElement("a",Object.assign({},c,{href:m||h,onClick:d||o?t:function(e){t&&t(e),e.defaultPrevented||p(e)},ref:f,target:s}))})),_=e.forwardRef((function({"aria-current":t="page",caseSensitive:r=!1,className:n="",end:u=!1,style:l,to:c,children:f,...m},d){let h=o(c,{relative:m.relative}),p=a(),w=e.useContext(i),{navigator:g}=e.useContext(s),y=g.encodeLocation?g.encodeLocation(h).pathname:h.pathname,v=p.pathname,b=w&&w.navigation&&w.navigation.location?w.navigation.location.pathname:null;r||(v=v.toLowerCase(),b=b?b.toLowerCase():null,y=y.toLowerCase());let R,S=v===y||!u&&v.startsWith(y)&&"/"===v.charAt(y.length),E=null!=b&&(b===y||!u&&b.startsWith(y)&&"/"===b.charAt(y.length)),C=S?t:void 0;R="function"==typeof n?n({isActive:S,isPending:E}):[n,S?"active":null,E?"pending":null].filter(Boolean).join(" ");let A="function"==typeof l?l({isActive:S,isPending:E}):l;return e.createElement(T,Object.assign({},m,{"aria-current":C,className:R,ref:d,style:A,to:c}),"function"==typeof f?f({isActive:S,isPending:E}):f)})),k=e.forwardRef(((t,r)=>e.createElement(O,Object.assign({},t,{ref:r})))),O=e.forwardRef((({reloadDocument:t,replace:r,method:n="get",action:o,onSubmit:a,fetcherKey:i,routeId:s,relative:u,preventScrollReset:l,...c},f)=>{let m=Y(i,s),d="get"===n.toLowerCase()?"get":"post",h=$(o,{relative:u});return e.createElement("form",Object.assign({ref:f,method:d,action:h,onSubmit:t?a:e=>{if(a&&a(e),e.defaultPrevented)return;e.preventDefault();let t=e.nativeEvent.submitter,o=t?.getAttribute("formmethod")||n;m(t||e.currentTarget,{method:o,replace:r,relative:u,preventScrollReset:l})}},c))}));function K({getKey:e,storageKey:t}){return Q({getKey:e,storageKey:t}),null}var j,I;function M(t){let r=e.useContext(h);return r||v(!1),r}function z(t){let r=e.useContext(i);return r||v(!1),r}function B(t,{target:r,replace:n,state:i,preventScrollReset:s,relative:c}={}){let f=u(),m=a(),d=o(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:i,preventScrollReset:s,relative:c})}}),[m,f,d,n,i,r,t,s,c])}function H(t){let r=e.useRef(E(t)),n=e.useRef(!1),o=a(),i=e.useMemo((()=>function(e,t){let r=E(e);if(t)for(let n of t.keys())r.has(n)||t.getAll(n).forEach((e=>{r.append(n,e)}));return r}(o.search,n.current?null:r.current)),[o.search]),s=u(),l=e.useCallback(((e,t)=>{const r=E("function"==typeof e?e(i):e);n.current=!0,s("?"+r,t)}),[s,i]);return[i,l]}function W(){return Y()}function Y(t,r){let{router:n}=M(j.UseSubmitImpl),o=$();return e.useCallback(((e,a={})=>{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{method:i,encType:s,formData:u,url:l}=C(e,o,a),c=l.pathname+l.search,f={replace:a.replace,preventScrollReset:a.preventScrollReset,formData:u,formMethod:i,formEncType:s};t?(null==r&&v(!1),n.fetch(t,r,c,f)):n.navigate(c,f)}),[o,n,t,r])}function $(t,{relative:r}={}){let{basename:n}=e.useContext(s),i=e.useContext(c);i||v(!1);let[u]=i.matches.slice(-1),f={...o(t||".",{relative:r})},m=a();if(null==t&&(f.search=m.search,f.hash=m.hash,u.route.index)){let e=new URLSearchParams(f.search);e.delete("index"),f.search=e.toString()?`?${e.toString()}`:""}return t&&"."!==t||!u.route.index||(f.search=f.search?f.search.replace(/^\?/,"?index&"):"?index"),"/"!==n&&(f.pathname="/"===f.pathname?n:b([n,f.pathname])),l(f)}!function(e){e.UseScrollRestoration="useScrollRestoration",e.UseSubmitImpl="useSubmitImpl",e.UseFetcher="useFetcher"}(j||(j={})),function(e){e.UseFetchers="useFetchers",e.UseScrollRestoration="useScrollRestoration"}(I||(I={}));let J=0;function V(){let{router:t}=M(j.UseFetcher),r=e.useContext(c);r||v(!1);let n=r.matches[r.matches.length-1]?.route.id;null==n&&v(!1);let[o]=e.useState((()=>String(++J))),[a]=e.useState((()=>(n||v(!1),function(t,r){return e.forwardRef(((n,o)=>e.createElement(O,Object.assign({},n,{ref:o,fetcherKey:t,routeId:r}))))}(o,n)))),[i]=e.useState((()=>e=>{t||v(!1),n||v(!1),t.fetch(o,n,e)})),s=Y(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 fetcher available to clean up from useFetcher()")}),[t,o]),l}function q(){return[...z(I.UseFetchers).fetchers.values()]}let G={};function Q({getKey:t,storageKey:r}={}){let{router:n}=M(j.UseScrollRestoration),{restoreScrollPosition:o,preventScrollReset:i}=z(I.UseScrollRestoration),s=a(),u=f(),l=m();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"===l.state){let e=(t?t(s,u):null)||s.key;G[e]=window.scrollY}sessionStorage.setItem(r||"react-router-scroll-positions",JSON.stringify(G)),window.history.scrollRestoration="auto"}),[r,t,l.state,s,u])),"undefined"!=typeof document&&(e.useLayoutEffect((()=>{try{let e=sessionStorage.getItem(r||"react-router-scroll-positions");e&&(G=JSON.parse(e))}catch(e){}}),[r]),e.useLayoutEffect((()=>{let e=n?.enableScrollRestoration(G,(()=>window.scrollY),t);return()=>e&&e()}),[n,t]),e.useLayoutEffect((()=>{if(!1!==o)if("number"!=typeof o){if(s.hash){let e=document.getElementById(s.hash.slice(1));if(e)return void e.scrollIntoView()}!0!==i&&window.scrollTo(0,0)}else window.scrollTo(0,o)}),[s,o,i]))}function X(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 Z({when:t,message:r}){let n=d(t);e.useEffect((()=>{"blocked"!==n.state||t||n.reset()}),[n,t]),e.useEffect((()=>{if("blocked"===n.state){window.confirm(r)?setTimeout(n.proceed,0):n.reset()}}),[n,r])}export{F as BrowserRouter,k as Form,D as HashRouter,T as Link,_ as NavLink,K as ScrollRestoration,Q as UNSAFE_useScrollRestoration,A as createBrowserRouter,L as createHashRouter,E as createSearchParams,N as unstable_HistoryRouter,Z as unstable_usePrompt,X as useBeforeUnload,V as useFetcher,q as useFetchers,$ as useFormAction,B as useLinkClickHandler,H as useSearchParams,W 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 N(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(ye){}function P(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(ye){}}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,_]);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:{v7_relativeSplatPath:n.future.v7_relativeSplatPath}},s.initialized||n.future.v7_partialHydration?e.createElement(W,{routes:n.routes,future:n.future,state:s}):t))))),null)}function W({routes:e,future:t,state:n}){return i(e,void 0,n,t)}function Y({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 J({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 q({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 G="undefined"!=typeof window&&void 0!==window.document&&void 0!==window.document.createElement,Q=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i,X=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&&Q.test(l)&&(h=l,G))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(ye){}let v=u(l,{relative:n}),y=ie(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}))})),Z=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&&ge(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(X,Object.assign({},m,{"aria-current":F,className:L,ref:h,style:U,to:u,unstable_viewTransition:f}),"function"==typeof d?d(A):d)})),ee=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=ce(),p=fe(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 te({getKey:e,storageKey:t}){return pe({getKey:e,storageKey:t}),null}var ne=function(e){return e.UseScrollRestoration="useScrollRestoration",e.UseSubmit="useSubmit",e.UseSubmitFetcher="useSubmitFetcher",e.UseFetcher="useFetcher",e.useViewTransitionState="useViewTransitionState",e}(ne||{}),re=function(e){return e.UseFetcher="useFetcher",e.UseFetchers="useFetchers",e.UseScrollRestoration="useScrollRestoration",e}(re||{});function ae(t){let n=e.useContext(r);return n||E(!1),n}function oe(t){let n=e.useContext(a);return n||E(!1),n}function ie(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 se(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 ue=0,le=()=>`__${String(++ue)}__`;function ce(){let{router:t}=ae(ne.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}=N(e,n);if(!1===a.navigate){let e=a.fetcherKey||le();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 fe(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 de({key:t}={}){let{router:n}=ae(ne.UseFetcher),r=oe(re.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(le()),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=ce(),d=e.useCallback(((e,t)=>{f(e,{...t,navigate:!1,fetcherKey:u})}),[u,f]),m=e.useMemo((()=>e.forwardRef(((t,n)=>e.createElement(ee,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 me(){let e=oe(re.UseFetchers);return Array.from(e.fetchers.entries()).map((([e,t])=>({...t,key:e})))}let he={};function pe({getKey:t,storageKey:n}={}){let{router:r}=ae(ne.UseScrollRestoration),{restoreScrollPosition:a,preventScrollReset:o}=oe(re.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;he[e]=window.scrollY}try{sessionStorage.setItem(n||"react-router-scroll-positions",JSON.stringify(he))}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&&(he=JSON.parse(e))}catch(ye){}}),[n]),e.useLayoutEffect((()=>{let e=t&&"/"!==i?(e,n)=>t({...e,pathname:g(e.pathname,i)||e.pathname},n):t,n=r?.enableScrollRestoration(he,(()=>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 we(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 ve({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 ge(t,n={}){let r=e.useContext(K);null==r&&E(!1);let{basename:a}=ae(ne.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{Y as BrowserRouter,ee as Form,J as HashRouter,X as Link,Z as NavLink,$ as RouterProvider,te as ScrollRestoration,V as UNSAFE_FetchersContext,K as UNSAFE_ViewTransitionContext,pe as UNSAFE_useScrollRestoration,P as createBrowserRouter,D as createHashRouter,A as createSearchParams,q as unstable_HistoryRouter,ve as unstable_usePrompt,ge as unstable_useViewTransitionState,we as useBeforeUnload,de as useFetcher,me as useFetchers,fe as useFormAction,ie as useLinkClickHandler,se as useSearchParams,ce as useSubmit}; | ||
//# sourceMappingURL=react-router-dom.production.min.js.map |
import * as React from "react"; | ||
import type { Router as RemixRouter, StaticHandlerContext } 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,10 @@ 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 }; | ||
export interface StaticRouterProviderProps { | ||
@@ -25,3 +27,7 @@ context: StaticHandlerContext; | ||
*/ | ||
export declare function StaticRouterProvider({ context, router, hydrate, nonce, }: StaticRouterProviderProps): JSX.Element; | ||
export declare function createStaticRouter(routes: RouteObject[], context: StaticHandlerContext): RemixRouter; | ||
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, opts?: { | ||
future?: Partial<Pick<RouterFutureConfig, "v7_partialHydration" | "v7_relativeSplatPath">>; | ||
}): RemixRouter; |
@@ -7,2 +7,3 @@ 'use strict'; | ||
var router = require('@remix-run/router'); | ||
var reactRouter = require('react-router'); | ||
var reactRouterDom = require('react-router-dom'); | ||
@@ -31,10 +32,10 @@ | ||
/** | ||
* A <Router> that may not navigate to any other location. This is useful | ||
* A `<Router>` that may not navigate to any other location. This is useful | ||
* on the server where there is no stateful UI. | ||
*/ | ||
function StaticRouter({ | ||
basename, | ||
children, | ||
location: locationProp = "/" | ||
location: locationProp = "/", | ||
future | ||
}) { | ||
@@ -44,3 +45,2 @@ if (typeof locationProp === "string") { | ||
} | ||
let action = router.Action.Pop; | ||
@@ -51,3 +51,3 @@ let location = { | ||
hash: locationProp.hash || "", | ||
state: locationProp.state || null, | ||
state: locationProp.state != null ? locationProp.state : null, | ||
key: locationProp.key || "default" | ||
@@ -62,2 +62,3 @@ }; | ||
navigator: staticNavigator, | ||
future: future, | ||
static: true | ||
@@ -70,3 +71,2 @@ }); | ||
*/ | ||
function StaticRouterProvider({ | ||
@@ -78,3 +78,3 @@ context, | ||
}) { | ||
!(router$1 && context) ? process.env.NODE_ENV !== "production" ? router.invariant(false, "You must provide `router` and `context` to <StaticRouterProvider>") : router.invariant(false) : void 0; | ||
!(router$1 && context) ? process.env.NODE_ENV !== "production" ? router.UNSAFE_invariant(false, "You must provide `router` and `context` to <StaticRouterProvider>") : router.UNSAFE_invariant(false) : void 0; | ||
let dataRouterContext = { | ||
@@ -87,4 +87,4 @@ router: router$1, | ||
}; | ||
let fetchersContext = new Map(); | ||
let hydrateScript = ""; | ||
if (hydrate !== false) { | ||
@@ -95,21 +95,37 @@ let data = { | ||
errors: serializeErrors(context.errors) | ||
}; // Use JSON.parse here instead of embedding a raw JS object here to speed | ||
}; | ||
// Use JSON.parse here instead of embedding a raw JS object here to speed | ||
// up parsing on the client. Dual-stringify is needed to ensure all quotes | ||
// are properly escaped in the resulting string. See: | ||
// https://v8.dev/blog/cost-of-javascript-2019#json | ||
let json = JSON.stringify(JSON.stringify(data)); | ||
let json = htmlEscape(JSON.stringify(JSON.stringify(data))); | ||
hydrateScript = `window.__staticRouterHydrationData = JSON.parse(${json});`; | ||
} | ||
let { | ||
state | ||
} = dataRouterContext.router; | ||
return /*#__PURE__*/React__namespace.createElement(React__namespace.Fragment, null, /*#__PURE__*/React__namespace.createElement(reactRouterDom.UNSAFE_DataRouterContext.Provider, { | ||
value: dataRouterContext | ||
}, /*#__PURE__*/React__namespace.createElement(reactRouterDom.UNSAFE_DataRouterStateContext.Provider, { | ||
value: dataRouterContext.router.state | ||
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, { | ||
basename: dataRouterContext.basename, | ||
location: dataRouterContext.router.state.location, | ||
navigationType: dataRouterContext.router.state.historyAction, | ||
navigator: dataRouterContext.navigator | ||
}, /*#__PURE__*/React__namespace.createElement(reactRouterDom.Routes, null)))), hydrateScript ? /*#__PURE__*/React__namespace.createElement("script", { | ||
location: state.location, | ||
navigationType: state.historyAction, | ||
navigator: dataRouterContext.navigator, | ||
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", { | ||
suppressHydrationWarning: true, | ||
@@ -122,3 +138,9 @@ nonce: nonce, | ||
} | ||
function DataRoutes({ | ||
routes, | ||
future, | ||
state | ||
}) { | ||
return reactRouter.UNSAFE_useRoutesImpl(routes, undefined, state, future); | ||
} | ||
function serializeErrors(errors) { | ||
@@ -128,3 +150,2 @@ if (!errors) return null; | ||
let serialized = {}; | ||
for (let [key, val] of entries) { | ||
@@ -134,3 +155,4 @@ // Hey you! If you change this, please change the corresponding logic in | ||
if (router.isRouteErrorResponse(val)) { | ||
serialized[key] = { ...val, | ||
serialized[key] = { | ||
...val, | ||
__type: "RouteErrorResponse" | ||
@@ -142,3 +164,8 @@ }; | ||
message: val.message, | ||
__type: "Error" | ||
__type: "Error", | ||
// If this is a subclass (i.e., ReferenceError), send up the type so we | ||
// can re-create the same type during hydration. | ||
...(val.name !== "Error" ? { | ||
__subType: val.name | ||
} : {}) | ||
}; | ||
@@ -149,6 +176,4 @@ } else { | ||
} | ||
return serialized; | ||
} | ||
function getStatelessNavigator() { | ||
@@ -158,56 +183,39 @@ return { | ||
encodeLocation, | ||
push(to) { | ||
throw new Error(`You cannot use navigator.push() on the server because it is a stateless ` + `environment. This error was probably triggered when you did a ` + `\`navigate(${JSON.stringify(to)})\` somewhere in your app.`); | ||
}, | ||
replace(to) { | ||
throw new Error(`You cannot use navigator.replace() on the server because it is a stateless ` + `environment. This error was probably triggered when you did a ` + `\`navigate(${JSON.stringify(to)}, { replace: true })\` somewhere ` + `in your app.`); | ||
}, | ||
go(delta) { | ||
throw new Error(`You cannot use navigator.go() on the server because it is a stateless ` + `environment. This error was probably triggered when you did a ` + `\`navigate(${delta})\` somewhere in your app.`); | ||
}, | ||
back() { | ||
throw new Error(`You cannot use navigator.back() on the server because it is a stateless ` + `environment.`); | ||
}, | ||
forward() { | ||
throw new Error(`You cannot use navigator.forward() on the server because it is a stateless ` + `environment.`); | ||
} | ||
}; | ||
} // Temporary manifest generation - we should optimize this by combining the | ||
// tree-walks between convertRoutesToDataRoutes, enhanceManualRouteObjects, | ||
// and generateManifest. | ||
// Also look into getting rid of `route as AgnosticDataRouteObject` down below? | ||
function generateManifest(routes, manifest = new Map()) { | ||
routes.forEach(route => { | ||
manifest.set(route.id, route); | ||
if (route.children) { | ||
generateManifest(route.children, manifest); | ||
} | ||
} | ||
function createStaticHandler(routes, opts) { | ||
return router.createStaticHandler(routes, { | ||
...opts, | ||
mapRouteProperties: reactRouter.UNSAFE_mapRouteProperties | ||
}); | ||
return manifest; | ||
} | ||
function createStaticRouter(routes, context) { | ||
let dataRoutes = router.UNSAFE_convertRoutesToDataRoutes(reactRouterDom.UNSAFE_enhanceManualRouteObjects(routes)); | ||
let manifest = generateManifest(dataRoutes); // Because our context matches may be from a framework-agnostic set of | ||
function createStaticRouter(routes, context, opts = {}) { | ||
let manifest = {}; | ||
let dataRoutes = router.UNSAFE_convertRoutesToDataRoutes(routes, reactRouter.UNSAFE_mapRouteProperties, undefined, manifest); | ||
// Because our context matches may be from a framework-agnostic set of | ||
// routes passed to createStaticHandler(), we update them here with our | ||
// newly created/enhanced data routes | ||
let matches = context.matches.map(match => { | ||
let route = manifest.get(match.route.id) || match.route; | ||
return { ...match, | ||
route: route | ||
let route = manifest[match.route.id] || match.route; | ||
return { | ||
...match, | ||
route | ||
}; | ||
}); | ||
let msg = method => `You cannot use router.${method}() on the server because it is a stateless environment`; | ||
return { | ||
@@ -217,3 +225,12 @@ get basename() { | ||
}, | ||
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() { | ||
@@ -236,80 +253,87 @@ return { | ||
}, | ||
get routes() { | ||
return dataRoutes; | ||
}, | ||
get window() { | ||
return undefined; | ||
}, | ||
initialize() { | ||
throw msg("initialize"); | ||
}, | ||
subscribe() { | ||
throw msg("subscribe"); | ||
}, | ||
enableScrollRestoration() { | ||
throw msg("enableScrollRestoration"); | ||
}, | ||
navigate() { | ||
throw msg("navigate"); | ||
}, | ||
fetch() { | ||
throw msg("fetch"); | ||
}, | ||
revalidate() { | ||
throw msg("revalidate"); | ||
}, | ||
createHref, | ||
encodeLocation, | ||
getFetcher() { | ||
return router.IDLE_FETCHER; | ||
}, | ||
deleteFetcher() { | ||
throw msg("deleteFetcher"); | ||
}, | ||
dispose() { | ||
throw msg("dispose"); | ||
}, | ||
getBlocker() { | ||
return router.IDLE_BLOCKER; | ||
}, | ||
deleteBlocker() { | ||
throw msg("deleteBlocker"); | ||
}, | ||
patchRoutes() { | ||
throw msg("patchRoutes"); | ||
}, | ||
_internalFetchControllers: new Map(), | ||
_internalActiveDeferreds: new Map(), | ||
_internalSetRoutes() { | ||
throw msg("_internalSetRoutes"); | ||
} | ||
}; | ||
} | ||
function createHref(to) { | ||
return typeof to === "string" ? to : reactRouterDom.createPath(to); | ||
} | ||
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 | ||
// License: https://github.com/zertosh/htmlescape/blob/0527ca7156a524d256101bb310a9f970f63078ad/LICENSE | ||
const ESCAPE_LOOKUP = { | ||
"&": "\\u0026", | ||
">": "\\u003e", | ||
"<": "\\u003c", | ||
"\u2028": "\\u2028", | ||
"\u2029": "\\u2029" | ||
}; | ||
const ESCAPE_REGEX = /[&><\u2028\u2029]/g; | ||
function htmlEscape(str) { | ||
return str.replace(ESCAPE_REGEX, match => ESCAPE_LOOKUP[match]); | ||
} | ||
exports.StaticRouter = StaticRouter; | ||
exports.StaticRouterProvider = StaticRouterProvider; | ||
exports.createStaticHandler = createStaticHandler; | ||
exports.createStaticRouter = createStaticRouter; |
/** | ||
* React Router DOM v0.0.0-experimental-cf9637ce | ||
* React Router DOM v0.0.0-experimental-cffa549a1 | ||
* | ||
@@ -11,3 +11,3 @@ * Copyright (c) Remix Software Inc. | ||
*/ | ||
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("react"),require("react-router"),require("@remix-run/router")):"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",l="application/x-www-form-urlencoded";function s(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]])}),[]))}function d(e,t,r){let n,o,a,u;if(s(i=e)&&"form"===i.tagName.toLowerCase()){let i=r.submissionTrigger;n=r.method||e.getAttribute("method")||c,o=r.action||e.getAttribute("action")||t,a=r.encType||e.getAttribute("enctype")||l,u=new FormData(e),i&&i.name&&u.append(i.name,i.value)}else if(function(e){return s(e)&&"button"===e.tagName.toLowerCase()}(e)||function(e){return s(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>');n=r.method||e.getAttribute("formmethod")||i.getAttribute("method")||c,o=r.action||e.getAttribute("formaction")||i.getAttribute("action")||t,a=r.encType||e.getAttribute("formenctype")||i.getAttribute("enctype")||l,u=new FormData(i),e.name&&u.append(e.name,e.value)}else{if(s(e))throw new Error('Cannot submit element that is not <form>, <button>, or <input type="submit|image">');if(n=r.method||c,o=r.action||t,a=r.encType||l,e instanceof FormData)u=e;else if(u=new FormData,e instanceof URLSearchParams)for(let[t,r]of e)u.append(t,r);else if(null!=e)for(let t of Object.keys(e))u.append(t,e[t])}var i;let{protocol:f,host:d}=window.location;return{url:new URL(o,f+"//"+d),method:n.toLowerCase(),encType:a,formData:u}}const m=["onClick","relative","reloadDocument","replace","state","target","to","preventScrollReset"],b=["aria-current","caseSensitive","className","end","style","to","children"],p=["reloadDocument","replace","method","action","onSubmit","fetcherKey","routeId","relative","preventScrollReset"];function h(){var e;let t=null==(e=window)?void 0:e.__staticRouterHydrationData;return t&&t.errors&&(t=u({},t,{errors:y(t.errors)})),t}function y(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){let t=new Error(o.message);t.stack="",r[e]=t}else r[e]=o;return r}const g="undefined"!=typeof window&&void 0!==window.document&&void 0!==window.document.createElement,v=a.forwardRef((function(e,t){let n,{onClick:o,relative:c,reloadDocument:l,replace:s,state:f,target:d,to:b,preventScrollReset:p}=e,h=i(e,m),y=!1;if(g&&"string"==typeof b&&/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i.test(b)){n=b;let e=new URL(window.location.href),t=b.startsWith("//")?new URL(e.protocol+b):new URL(b);t.origin===e.origin?b=t.pathname+t.search+t.hash:y=!0}let v=r.useHref(b,{relative:c}),R=A(b,{replace:s,state:f,target:d,preventScrollReset:p,relative:c});return a.createElement("a",u({},h,{href:n||v,onClick:y||l?o:function(e){o&&o(e),e.defaultPrevented||R(e)},ref:t,target:d}))})),R=a.forwardRef((function(e,t){let{"aria-current":n="page",caseSensitive:o=!1,className:c="",end:l=!1,style:s,to:f,children:d}=e,m=i(e,b),p=r.useResolvedPath(f,{relative:m.relative}),h=r.useLocation(),y=a.useContext(r.UNSAFE_DataRouterStateContext),{navigator:g}=a.useContext(r.UNSAFE_NavigationContext),R=g.encodeLocation?g.encodeLocation(p).pathname:p.pathname,w=h.pathname,P=y&&y.navigation&&y.navigation.location?y.navigation.location.pathname:null;o||(w=w.toLowerCase(),P=P?P.toLowerCase():null,R=R.toLowerCase());let O,S=w===R||!l&&w.startsWith(R)&&"/"===w.charAt(R.length),j=null!=P&&(P===R||!l&&P.startsWith(R)&&"/"===P.charAt(R.length)),E=S?n:void 0;O="function"==typeof c?c({isActive:S,isPending:j}):[c,S?"active":null,j?"pending":null].filter(Boolean).join(" ");let A="function"==typeof s?s({isActive:S,isPending:j}):s;return a.createElement(v,u({},m,{"aria-current":E,className:O,ref:t,style:A,to:f}),"function"==typeof d?d({isActive:S,isPending:j}):d)})),w=a.forwardRef(((e,t)=>a.createElement(P,u({},e,{ref:t})))),P=a.forwardRef(((e,t)=>{let{reloadDocument:r,replace:n,method:o=c,action:l,onSubmit:s,fetcherKey:f,routeId:d,relative:m,preventScrollReset:b}=e,h=i(e,p),y=C(f,d),g="get"===o.toLowerCase()?"get":"post",v=N(l,{relative:m});return a.createElement("form",u({ref:t,method:g,action:v,onSubmit:r?s:e=>{if(s&&s(e),e.defaultPrevented)return;e.preventDefault();let t=e.nativeEvent.submitter,r=(null==t?void 0:t.getAttribute("formmethod"))||o;y(t||e.currentTarget,{method:r,replace:n,relative:m,preventScrollReset:b})}},h))}));var O,S;function j(e){let t=a.useContext(r.UNSAFE_DataRouterContext);return t||n.invariant(!1),t}function E(e){let t=a.useContext(r.UNSAFE_DataRouterStateContext);return t||n.invariant(!1),t}function A(e,t){let{target:n,replace:o,state:u,preventScrollReset:i,relative:c}=void 0===t?{}:t,l=r.useNavigate(),s=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(s)===r.createPath(f);l(e,{replace:n,state:u,preventScrollReset:i,relative:c})}}),[s,l,f,o,u,n,e,i,c])}function C(e,t){let{router:r}=j(O.UseSubmitImpl),o=N();return a.useCallback((function(a,u){if(void 0===u&&(u={}),"undefined"==typeof document)throw new Error("You are calling submit during the server render. Try calling submit within a `useEffect` or callback instead.");let{method:i,encType:c,formData:l,url:s}=d(a,o,u),f=s.pathname+s.search,m={replace:u.replace,preventScrollReset:u.preventScrollReset,formData:l,formMethod:i,formEncType:c};e?(null==t&&n.invariant(!1),r.fetch(e,t,f,m)):r.navigate(f,m)}),[o,r,e,t])}function N(e,t){let{relative:o}=void 0===t?{}:t,{basename:i}=a.useContext(r.UNSAFE_NavigationContext),c=a.useContext(r.UNSAFE_RouteContext);c||n.invariant(!1);let[l]=c.matches.slice(-1),s=u({},r.useResolvedPath(e||".",{relative:o})),f=r.useLocation();if(null==e&&(s.search=f.search,s.hash=f.hash,l.route.index)){let e=new URLSearchParams(s.search);e.delete("index"),s.search=e.toString()?"?"+e.toString():""}return e&&"."!==e||!l.route.index||(s.search=s.search?s.search.replace(/^\?/,"?index&"):"?index"),"/"!==i&&(s.pathname="/"===s.pathname?i:n.joinPaths([i,s.pathname])),r.createPath(s)}!function(e){e.UseScrollRestoration="useScrollRestoration",e.UseSubmitImpl="useSubmitImpl",e.UseFetcher="useFetcher"}(O||(O={})),function(e){e.UseFetchers="useFetchers",e.UseScrollRestoration="useScrollRestoration"}(S||(S={}));let F=0;const L="react-router-scroll-positions";let x={};function U(e){let{getKey:t,storageKey:n}=void 0===e?{}:e,{router:o}=j(O.UseScrollRestoration),{restoreScrollPosition:u,preventScrollReset:i}=E(S.UseScrollRestoration),c=r.useLocation(),l=r.useMatches(),s=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"===s.state){let e=(t?t(c,l):null)||c.key;x[e]=window.scrollY}sessionStorage.setItem(n||L,JSON.stringify(x)),window.history.scrollRestoration="auto"}),[n,t,s.state,c,l])),"undefined"!=typeof document&&(a.useLayoutEffect((()=>{try{let e=sessionStorage.getItem(n||L);e&&(x=JSON.parse(e))}catch(e){}}),[n]),a.useLayoutEffect((()=>{let e=null==o?void 0:o.enableScrollRestoration(x,(()=>window.scrollY),t);return()=>e&&e()}),[o,t]),a.useLayoutEffect((()=>{if(!1!==u)if("number"!=typeof u){if(c.hash){let e=document.getElementById(c.hash.slice(1));if(e)return void e.scrollIntoView()}!0!==i&&window.scrollTo(0,0)}else window.scrollTo(0,u)}),[c,u,i]))}Object.defineProperty(e,"AbortedDeferredError",{enumerable:!0,get:function(){return r.AbortedDeferredError}}),Object.defineProperty(e,"Await",{enumerable:!0,get:function(){return r.Await}}),Object.defineProperty(e,"MemoryRouter",{enumerable:!0,get:function(){return r.MemoryRouter}}),Object.defineProperty(e,"Navigate",{enumerable:!0,get:function(){return r.Navigate}}),Object.defineProperty(e,"NavigationType",{enumerable:!0,get:function(){return r.NavigationType}}),Object.defineProperty(e,"Outlet",{enumerable:!0,get:function(){return r.Outlet}}),Object.defineProperty(e,"Route",{enumerable:!0,get:function(){return r.Route}}),Object.defineProperty(e,"Router",{enumerable:!0,get:function(){return r.Router}}),Object.defineProperty(e,"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_enhanceManualRouteObjects",{enumerable:!0,get:function(){return r.UNSAFE_enhanceManualRouteObjects}}),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,window:u}=e,i=a.useRef();null==i.current&&(i.current=n.createBrowserHistory({window:u,v5Compat:!0}));let c=i.current,[l,s]=a.useState({action:c.action,location:c.location});return a.useLayoutEffect((()=>c.listen(s)),[c]),a.createElement(r.Router,{basename:t,children:o,location:l.location,navigationType:l.action,navigator:c})},e.Form=w,e.HashRouter=function(e){let{basename:t,children:o,window:u}=e,i=a.useRef();null==i.current&&(i.current=n.createHashHistory({window:u,v5Compat:!0}));let c=i.current,[l,s]=a.useState({action:c.action,location:c.location});return a.useLayoutEffect((()=>c.listen(s)),[c]),a.createElement(r.Router,{basename:t,children:o,location:l.location,navigationType:l.action,navigator:c})},e.Link=v,e.NavLink=R,e.ScrollRestoration=function(e){let{getKey:t,storageKey:r}=e;return U({getKey:t,storageKey:r}),null},e.UNSAFE_useScrollRestoration=U,e.createBrowserRouter=function(e,t){return n.createRouter({basename:null==t?void 0:t.basename,history:n.createBrowserHistory({window:null==t?void 0:t.window}),hydrationData:(null==t?void 0:t.hydrationData)||h(),routes:r.UNSAFE_enhanceManualRouteObjects(e)}).initialize()},e.createHashRouter=function(e,t){return n.createRouter({basename:null==t?void 0:t.basename,history:n.createHashHistory({window:null==t?void 0:t.window}),hydrationData:(null==t?void 0:t.hydrationData)||h(),routes:r.UNSAFE_enhanceManualRouteObjects(e)}).initialize()},e.createSearchParams=f,e.unstable_HistoryRouter=function(e){let{basename:t,children:n,history:o}=e;const[u,i]=a.useState({action:o.action,location:o.location});return a.useLayoutEffect((()=>o.listen(i)),[o]),a.createElement(r.Router,{basename:t,children:n,location:u.location,navigationType:u.action,navigator:o})},e.unstable_usePrompt=function(e){let{when:t,message:n}=e,o=r.unstable_useBlocker(t);a.useEffect((()=>{"blocked"!==o.state||t||o.reset()}),[o,t]),a.useEffect((()=>{if("blocked"===o.state){window.confirm(n)?setTimeout(o.proceed,0):o.reset()}}),[o,n])},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}=j(O.UseFetcher),o=a.useContext(r.UNSAFE_RouteContext);o||n.invariant(!1);let i=null==(e=o.matches[o.matches.length-1])?void 0:e.route.id;null==i&&n.invariant(!1);let[c]=a.useState((()=>String(++F))),[l]=a.useState((()=>(i||n.invariant(!1),function(e,t){return a.forwardRef(((r,n)=>a.createElement(P,u({},r,{ref:n,fetcherKey:e,routeId:t}))))}(c,i)))),[s]=a.useState((()=>e=>{t||n.invariant(!1),i||n.invariant(!1),t.fetch(c,i,e)})),f=C(c,i),d=t.getFetcher(c),m=a.useMemo((()=>u({Form:l,submit:f,load:s},d)),[d,l,f,s]);return a.useEffect((()=>()=>{t?t.deleteFetcher(c):console.warn("No fetcher available to clean up from useFetcher()")}),[t,c]),m},e.useFetchers=function(){return[...E(S.UseFetchers).fetchers.values()]},e.useFormAction=N,e.useLinkClickHandler=A,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);if(t)for(let e of t.keys())r.has(e)||t.getAll(e).forEach((t=>{r.append(e,t)}));return r}(o.search,n.current?null:t.current)),[o.search]),i=r.useNavigate(),c=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=function(){return C()},Object.defineProperty(e,"__esModule",{value:!0})})); | ||
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("react"),require("react-dom"),require("react-router"),require("@remix-run/router")):"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))}}))}}function j(e){let{routes:t,future:n,state:o}=e;return r.UNSAFE_useRoutesImpl(t,void 0,o,n)}const x="undefined"!=typeof window&&void 0!==window.document&&void 0!==window.document.createElement,F=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i,L=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&&F.test(p)&&(n=p,x))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=H(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}))})),T=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&&J(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(L,s({},b,{"aria-current":x,className:A,ref:t,style:F,to:d,unstable_viewTransition:m}),"function"==typeof p?p(j):p)})),U=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=V(),g=z(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 D=function(e){return e.UseScrollRestoration="useScrollRestoration",e.UseSubmit="useSubmit",e.UseSubmitFetcher="useSubmitFetcher",e.UseFetcher="useFetcher",e.useViewTransitionState="useViewTransitionState",e}(D||{}),k=function(e){return e.UseFetcher="useFetcher",e.UseFetchers="useFetchers",e.UseScrollRestoration="useScrollRestoration",e}(k||{});function M(e){let t=i.useContext(r.UNSAFE_DataRouterContext);return t||o.UNSAFE_invariant(!1),t}function B(e){let t=i.useContext(r.UNSAFE_DataRouterStateContext);return t||o.UNSAFE_invariant(!1),t}function H(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 I=0,K=()=>"__"+String(++I)+"__";function V(){let{router:e}=M(D.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||K();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 z(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 q="react-router-scroll-positions";let W={};function Y(e){let{getKey:t,storageKey:n}=void 0===e?{}:e,{router:a}=M(D.UseScrollRestoration),{restoreScrollPosition:u,preventScrollReset:c}=B(k.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;W[e]=window.scrollY}try{sessionStorage.setItem(n||q,JSON.stringify(W))}catch(e){}window.history.scrollRestoration="auto"}),[n,t,m.state,f,d])),"undefined"!=typeof document&&(i.useLayoutEffect((()=>{try{let e=sessionStorage.getItem(n||q);e&&(W=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(W,(()=>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 J(e,t){void 0===t&&(t={});let n=i.useContext(E);null==n&&o.UNSAFE_invariant(!1);let{basename:a}=M(D.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=U,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=L,e.NavLink=T,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]);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:{v7_relativeSplatPath:n.future.v7_relativeSplatPath}},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 Y({getKey:t,storageKey:n}),null},e.UNSAFE_FetchersContext=_,e.UNSAFE_ViewTransitionContext=E,e.UNSAFE_useScrollRestoration=Y,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=J,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}=M(D.UseFetcher),u=B(k.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(K()),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=V(),v=i.useCallback(((e,t)=>{h(e,s({},t,{navigate:!1,fetcherKey:m}))}),[m,h]),y=i.useMemo((()=>i.forwardRef(((e,t)=>i.createElement(U,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=B(k.UseFetchers);return Array.from(e.fetchers.entries()).map((e=>{let[t,n]=e;return s({},n,{key:t})}))},e.useFormAction=z,e.useLinkClickHandler=H,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=V,Object.defineProperty(e,"__esModule",{value:!0})})); | ||
//# sourceMappingURL=react-router-dom.production.min.js.map |
MIT License | ||
Copyright (c) React Training 2015-2019 | ||
Copyright (c) Remix Software 2020-2022 | ||
Copyright (c) React Training LLC 2015-2019 | ||
Copyright (c) Remix Software Inc. 2020-2021 | ||
Copyright (c) Shopify Inc. 2022-2023 | ||
@@ -6,0 +7,0 @@ Permission is hereby granted, free of charge, to any person obtaining a copy |
{ | ||
"name": "react-router-dom", | ||
"version": "0.0.0-experimental-cf9637ce", | ||
"version": "0.0.0-experimental-cffa549a1", | ||
"description": "Declarative routing for React web applications", | ||
@@ -26,4 +26,4 @@ "keywords": [ | ||
"dependencies": { | ||
"@remix-run/router": "0.0.0-experimental-cf9637ce", | ||
"react-router": "0.0.0-experimental-cf9637ce" | ||
"@remix-run/router": "0.0.0-experimental-cffa549a1", | ||
"react-router": "0.0.0-experimental-cffa549a1" | ||
}, | ||
@@ -48,4 +48,4 @@ "devDependencies": { | ||
"engines": { | ||
"node": ">=14" | ||
"node": ">=14.0.0" | ||
} | ||
} | ||
} |
import * as React from "react"; | ||
import type { Router as RemixRouter, StaticHandlerContext } 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,10 @@ 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 }; | ||
export interface StaticRouterProviderProps { | ||
@@ -25,3 +27,7 @@ context: StaticHandlerContext; | ||
*/ | ||
export declare function StaticRouterProvider({ context, router, hydrate, nonce, }: StaticRouterProviderProps): JSX.Element; | ||
export declare function createStaticRouter(routes: RouteObject[], context: StaticHandlerContext): RemixRouter; | ||
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, opts?: { | ||
future?: Partial<Pick<RouterFutureConfig, "v7_partialHydration" | "v7_relativeSplatPath">>; | ||
}): RemixRouter; |
178
server.js
@@ -7,2 +7,3 @@ 'use strict'; | ||
var router = require('@remix-run/router'); | ||
var reactRouter = require('react-router'); | ||
var reactRouterDom = require('react-router-dom'); | ||
@@ -31,10 +32,10 @@ | ||
/** | ||
* A <Router> that may not navigate to any other location. This is useful | ||
* A `<Router>` that may not navigate to any other location. This is useful | ||
* on the server where there is no stateful UI. | ||
*/ | ||
function StaticRouter({ | ||
basename, | ||
children, | ||
location: locationProp = "/" | ||
location: locationProp = "/", | ||
future | ||
}) { | ||
@@ -44,3 +45,2 @@ if (typeof locationProp === "string") { | ||
} | ||
let action = router.Action.Pop; | ||
@@ -51,3 +51,3 @@ let location = { | ||
hash: locationProp.hash || "", | ||
state: locationProp.state || null, | ||
state: locationProp.state != null ? locationProp.state : null, | ||
key: locationProp.key || "default" | ||
@@ -62,2 +62,3 @@ }; | ||
navigator: staticNavigator, | ||
future: future, | ||
static: true | ||
@@ -70,3 +71,2 @@ }); | ||
*/ | ||
function StaticRouterProvider({ | ||
@@ -78,3 +78,3 @@ context, | ||
}) { | ||
!(router$1 && context) ? process.env.NODE_ENV !== "production" ? router.invariant(false, "You must provide `router` and `context` to <StaticRouterProvider>") : router.invariant(false) : void 0; | ||
!(router$1 && context) ? process.env.NODE_ENV !== "production" ? router.UNSAFE_invariant(false, "You must provide `router` and `context` to <StaticRouterProvider>") : router.UNSAFE_invariant(false) : void 0; | ||
let dataRouterContext = { | ||
@@ -87,4 +87,4 @@ router: router$1, | ||
}; | ||
let fetchersContext = new Map(); | ||
let hydrateScript = ""; | ||
if (hydrate !== false) { | ||
@@ -95,21 +95,37 @@ let data = { | ||
errors: serializeErrors(context.errors) | ||
}; // Use JSON.parse here instead of embedding a raw JS object here to speed | ||
}; | ||
// Use JSON.parse here instead of embedding a raw JS object here to speed | ||
// up parsing on the client. Dual-stringify is needed to ensure all quotes | ||
// are properly escaped in the resulting string. See: | ||
// https://v8.dev/blog/cost-of-javascript-2019#json | ||
let json = JSON.stringify(JSON.stringify(data)); | ||
let json = htmlEscape(JSON.stringify(JSON.stringify(data))); | ||
hydrateScript = `window.__staticRouterHydrationData = JSON.parse(${json});`; | ||
} | ||
let { | ||
state | ||
} = dataRouterContext.router; | ||
return /*#__PURE__*/React__namespace.createElement(React__namespace.Fragment, null, /*#__PURE__*/React__namespace.createElement(reactRouterDom.UNSAFE_DataRouterContext.Provider, { | ||
value: dataRouterContext | ||
}, /*#__PURE__*/React__namespace.createElement(reactRouterDom.UNSAFE_DataRouterStateContext.Provider, { | ||
value: dataRouterContext.router.state | ||
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, { | ||
basename: dataRouterContext.basename, | ||
location: dataRouterContext.router.state.location, | ||
navigationType: dataRouterContext.router.state.historyAction, | ||
navigator: dataRouterContext.navigator | ||
}, /*#__PURE__*/React__namespace.createElement(reactRouterDom.Routes, null)))), hydrateScript ? /*#__PURE__*/React__namespace.createElement("script", { | ||
location: state.location, | ||
navigationType: state.historyAction, | ||
navigator: dataRouterContext.navigator, | ||
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", { | ||
suppressHydrationWarning: true, | ||
@@ -122,3 +138,9 @@ nonce: nonce, | ||
} | ||
function DataRoutes({ | ||
routes, | ||
future, | ||
state | ||
}) { | ||
return reactRouter.UNSAFE_useRoutesImpl(routes, undefined, state, future); | ||
} | ||
function serializeErrors(errors) { | ||
@@ -128,3 +150,2 @@ if (!errors) return null; | ||
let serialized = {}; | ||
for (let [key, val] of entries) { | ||
@@ -134,3 +155,4 @@ // Hey you! If you change this, please change the corresponding logic in | ||
if (router.isRouteErrorResponse(val)) { | ||
serialized[key] = { ...val, | ||
serialized[key] = { | ||
...val, | ||
__type: "RouteErrorResponse" | ||
@@ -142,3 +164,8 @@ }; | ||
message: val.message, | ||
__type: "Error" | ||
__type: "Error", | ||
// If this is a subclass (i.e., ReferenceError), send up the type so we | ||
// can re-create the same type during hydration. | ||
...(val.name !== "Error" ? { | ||
__subType: val.name | ||
} : {}) | ||
}; | ||
@@ -149,6 +176,4 @@ } else { | ||
} | ||
return serialized; | ||
} | ||
function getStatelessNavigator() { | ||
@@ -158,56 +183,39 @@ return { | ||
encodeLocation, | ||
push(to) { | ||
throw new Error(`You cannot use navigator.push() on the server because it is a stateless ` + `environment. This error was probably triggered when you did a ` + `\`navigate(${JSON.stringify(to)})\` somewhere in your app.`); | ||
}, | ||
replace(to) { | ||
throw new Error(`You cannot use navigator.replace() on the server because it is a stateless ` + `environment. This error was probably triggered when you did a ` + `\`navigate(${JSON.stringify(to)}, { replace: true })\` somewhere ` + `in your app.`); | ||
}, | ||
go(delta) { | ||
throw new Error(`You cannot use navigator.go() on the server because it is a stateless ` + `environment. This error was probably triggered when you did a ` + `\`navigate(${delta})\` somewhere in your app.`); | ||
}, | ||
back() { | ||
throw new Error(`You cannot use navigator.back() on the server because it is a stateless ` + `environment.`); | ||
}, | ||
forward() { | ||
throw new Error(`You cannot use navigator.forward() on the server because it is a stateless ` + `environment.`); | ||
} | ||
}; | ||
} // Temporary manifest generation - we should optimize this by combining the | ||
// tree-walks between convertRoutesToDataRoutes, enhanceManualRouteObjects, | ||
// and generateManifest. | ||
// Also look into getting rid of `route as AgnosticDataRouteObject` down below? | ||
function generateManifest(routes, manifest = new Map()) { | ||
routes.forEach(route => { | ||
manifest.set(route.id, route); | ||
if (route.children) { | ||
generateManifest(route.children, manifest); | ||
} | ||
} | ||
function createStaticHandler(routes, opts) { | ||
return router.createStaticHandler(routes, { | ||
...opts, | ||
mapRouteProperties: reactRouter.UNSAFE_mapRouteProperties | ||
}); | ||
return manifest; | ||
} | ||
function createStaticRouter(routes, context) { | ||
let dataRoutes = router.UNSAFE_convertRoutesToDataRoutes(reactRouterDom.UNSAFE_enhanceManualRouteObjects(routes)); | ||
let manifest = generateManifest(dataRoutes); // Because our context matches may be from a framework-agnostic set of | ||
function createStaticRouter(routes, context, opts = {}) { | ||
let manifest = {}; | ||
let dataRoutes = router.UNSAFE_convertRoutesToDataRoutes(routes, reactRouter.UNSAFE_mapRouteProperties, undefined, manifest); | ||
// Because our context matches may be from a framework-agnostic set of | ||
// routes passed to createStaticHandler(), we update them here with our | ||
// newly created/enhanced data routes | ||
let matches = context.matches.map(match => { | ||
let route = manifest.get(match.route.id) || match.route; | ||
return { ...match, | ||
route: route | ||
let route = manifest[match.route.id] || match.route; | ||
return { | ||
...match, | ||
route | ||
}; | ||
}); | ||
let msg = method => `You cannot use router.${method}() on the server because it is a stateless environment`; | ||
return { | ||
@@ -217,3 +225,12 @@ get basename() { | ||
}, | ||
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() { | ||
@@ -236,80 +253,87 @@ return { | ||
}, | ||
get routes() { | ||
return dataRoutes; | ||
}, | ||
get window() { | ||
return undefined; | ||
}, | ||
initialize() { | ||
throw msg("initialize"); | ||
}, | ||
subscribe() { | ||
throw msg("subscribe"); | ||
}, | ||
enableScrollRestoration() { | ||
throw msg("enableScrollRestoration"); | ||
}, | ||
navigate() { | ||
throw msg("navigate"); | ||
}, | ||
fetch() { | ||
throw msg("fetch"); | ||
}, | ||
revalidate() { | ||
throw msg("revalidate"); | ||
}, | ||
createHref, | ||
encodeLocation, | ||
getFetcher() { | ||
return router.IDLE_FETCHER; | ||
}, | ||
deleteFetcher() { | ||
throw msg("deleteFetcher"); | ||
}, | ||
dispose() { | ||
throw msg("dispose"); | ||
}, | ||
getBlocker() { | ||
return router.IDLE_BLOCKER; | ||
}, | ||
deleteBlocker() { | ||
throw msg("deleteBlocker"); | ||
}, | ||
patchRoutes() { | ||
throw msg("patchRoutes"); | ||
}, | ||
_internalFetchControllers: new Map(), | ||
_internalActiveDeferreds: new Map(), | ||
_internalSetRoutes() { | ||
throw msg("_internalSetRoutes"); | ||
} | ||
}; | ||
} | ||
function createHref(to) { | ||
return typeof to === "string" ? to : reactRouterDom.createPath(to); | ||
} | ||
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 | ||
// License: https://github.com/zertosh/htmlescape/blob/0527ca7156a524d256101bb310a9f970f63078ad/LICENSE | ||
const ESCAPE_LOOKUP = { | ||
"&": "\\u0026", | ||
">": "\\u003e", | ||
"<": "\\u003c", | ||
"\u2028": "\\u2028", | ||
"\u2029": "\\u2029" | ||
}; | ||
const ESCAPE_REGEX = /[&><\u2028\u2029]/g; | ||
function htmlEscape(str) { | ||
return str.replace(ESCAPE_REGEX, match => ESCAPE_LOOKUP[match]); | ||
} | ||
exports.StaticRouter = StaticRouter; | ||
exports.StaticRouterProvider = StaticRouterProvider; | ||
exports.createStaticHandler = createStaticHandler; | ||
exports.createStaticRouter = createStaticRouter; |
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
Major refactor
Supply chain riskPackage has recently undergone a major refactor. It may be unstable or indicate significant internal changes. Use caution when updating to versions that include significant changes.
Found 1 instance in 1 package
890781
6538
0
26
+ Added@remix-run/router@0.0.0-experimental-cffa549a1(transitive)
+ Addedreact-router@0.0.0-experimental-cffa549a1(transitive)
- Removed@remix-run/router@0.0.0-experimental-cf9637ce(transitive)
- Removedreact-router@0.0.0-experimental-cf9637ce(transitive)