UNPKG

65.9 kBJavaScriptView Raw
1"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { newObj[key] = obj[key]; } } } newObj.default = obj; return newObj; } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }/**
2 * react-router v7.7.1
3 *
4 * Copyright (c) Remix Software Inc.
5 *
6 * This source code is licensed under the MIT license found in the
7 * LICENSE.md file in the root directory of this source tree.
8 *
9 * @license MIT
10 */
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64var _chunk7OQROU2Djs = require('./chunk-7OQROU2D.js');
65
66// lib/components.tsx
67var _react = require('react'); var React = _interopRequireWildcard(_react); var React2 = _interopRequireWildcard(_react); var React3 = _interopRequireWildcard(_react);
68function mapRouteProperties(route) {
69 let updates = {
70 // Note: this check also occurs in createRoutesFromChildren so update
71 // there if you change this -- please and thank you!
72 hasErrorBoundary: route.hasErrorBoundary || route.ErrorBoundary != null || route.errorElement != null
73 };
74 if (route.Component) {
75 if (_chunk7OQROU2Djs.ENABLE_DEV_WARNINGS) {
76 if (route.element) {
77 _chunk7OQROU2Djs.warning.call(void 0,
78 false,
79 "You should not include both `Component` and `element` on your route - `Component` will be used."
80 );
81 }
82 }
83 Object.assign(updates, {
84 element: React.createElement(route.Component),
85 Component: void 0
86 });
87 }
88 if (route.HydrateFallback) {
89 if (_chunk7OQROU2Djs.ENABLE_DEV_WARNINGS) {
90 if (route.hydrateFallbackElement) {
91 _chunk7OQROU2Djs.warning.call(void 0,
92 false,
93 "You should not include both `HydrateFallback` and `hydrateFallbackElement` on your route - `HydrateFallback` will be used."
94 );
95 }
96 }
97 Object.assign(updates, {
98 hydrateFallbackElement: React.createElement(route.HydrateFallback),
99 HydrateFallback: void 0
100 });
101 }
102 if (route.ErrorBoundary) {
103 if (_chunk7OQROU2Djs.ENABLE_DEV_WARNINGS) {
104 if (route.errorElement) {
105 _chunk7OQROU2Djs.warning.call(void 0,
106 false,
107 "You should not include both `ErrorBoundary` and `errorElement` on your route - `ErrorBoundary` will be used."
108 );
109 }
110 }
111 Object.assign(updates, {
112 errorElement: React.createElement(route.ErrorBoundary),
113 ErrorBoundary: void 0
114 });
115 }
116 return updates;
117}
118var hydrationRouteProperties = [
119 "HydrateFallback",
120 "hydrateFallbackElement"
121];
122function createMemoryRouter(routes, opts) {
123 return _chunk7OQROU2Djs.createRouter.call(void 0, {
124 basename: _optionalChain([opts, 'optionalAccess', _2 => _2.basename]),
125 unstable_getContext: _optionalChain([opts, 'optionalAccess', _3 => _3.unstable_getContext]),
126 future: _optionalChain([opts, 'optionalAccess', _4 => _4.future]),
127 history: _chunk7OQROU2Djs.createMemoryHistory.call(void 0, {
128 initialEntries: _optionalChain([opts, 'optionalAccess', _5 => _5.initialEntries]),
129 initialIndex: _optionalChain([opts, 'optionalAccess', _6 => _6.initialIndex])
130 }),
131 hydrationData: _optionalChain([opts, 'optionalAccess', _7 => _7.hydrationData]),
132 routes,
133 hydrationRouteProperties,
134 mapRouteProperties,
135 dataStrategy: _optionalChain([opts, 'optionalAccess', _8 => _8.dataStrategy]),
136 patchRoutesOnNavigation: _optionalChain([opts, 'optionalAccess', _9 => _9.patchRoutesOnNavigation])
137 }).initialize();
138}
139var Deferred = class {
140 constructor() {
141 this.status = "pending";
142 this.promise = new Promise((resolve, reject) => {
143 this.resolve = (value) => {
144 if (this.status === "pending") {
145 this.status = "resolved";
146 resolve(value);
147 }
148 };
149 this.reject = (reason) => {
150 if (this.status === "pending") {
151 this.status = "rejected";
152 reject(reason);
153 }
154 };
155 });
156 }
157};
158function RouterProvider({
159 router,
160 flushSync: reactDomFlushSyncImpl
161}) {
162 let [state, setStateImpl] = React.useState(router.state);
163 let [pendingState, setPendingState] = React.useState();
164 let [vtContext, setVtContext] = React.useState({
165 isTransitioning: false
166 });
167 let [renderDfd, setRenderDfd] = React.useState();
168 let [transition, setTransition] = React.useState();
169 let [interruption, setInterruption] = React.useState();
170 let fetcherData = React.useRef(/* @__PURE__ */ new Map());
171 let setState = React.useCallback(
172 (newState, { deletedFetchers, flushSync, viewTransitionOpts }) => {
173 newState.fetchers.forEach((fetcher, key) => {
174 if (fetcher.data !== void 0) {
175 fetcherData.current.set(key, fetcher.data);
176 }
177 });
178 deletedFetchers.forEach((key) => fetcherData.current.delete(key));
179 _chunk7OQROU2Djs.warnOnce.call(void 0,
180 flushSync === false || reactDomFlushSyncImpl != null,
181 'You provided the `flushSync` option to a router update, but you are not using the `<RouterProvider>` from `react-router/dom` so `ReactDOM.flushSync()` is unavailable. Please update your app to `import { RouterProvider } from "react-router/dom"` and ensure you have `react-dom` installed as a dependency to use the `flushSync` option.'
182 );
183 let isViewTransitionAvailable = router.window != null && router.window.document != null && typeof router.window.document.startViewTransition === "function";
184 _chunk7OQROU2Djs.warnOnce.call(void 0,
185 viewTransitionOpts == null || isViewTransitionAvailable,
186 "You provided the `viewTransition` option to a router update, but you do not appear to be running in a DOM environment as `window.startViewTransition` is not available."
187 );
188 if (!viewTransitionOpts || !isViewTransitionAvailable) {
189 if (reactDomFlushSyncImpl && flushSync) {
190 reactDomFlushSyncImpl(() => setStateImpl(newState));
191 } else {
192 React.startTransition(() => setStateImpl(newState));
193 }
194 return;
195 }
196 if (reactDomFlushSyncImpl && flushSync) {
197 reactDomFlushSyncImpl(() => {
198 if (transition) {
199 renderDfd && renderDfd.resolve();
200 transition.skipTransition();
201 }
202 setVtContext({
203 isTransitioning: true,
204 flushSync: true,
205 currentLocation: viewTransitionOpts.currentLocation,
206 nextLocation: viewTransitionOpts.nextLocation
207 });
208 });
209 let t = router.window.document.startViewTransition(() => {
210 reactDomFlushSyncImpl(() => setStateImpl(newState));
211 });
212 t.finished.finally(() => {
213 reactDomFlushSyncImpl(() => {
214 setRenderDfd(void 0);
215 setTransition(void 0);
216 setPendingState(void 0);
217 setVtContext({ isTransitioning: false });
218 });
219 });
220 reactDomFlushSyncImpl(() => setTransition(t));
221 return;
222 }
223 if (transition) {
224 renderDfd && renderDfd.resolve();
225 transition.skipTransition();
226 setInterruption({
227 state: newState,
228 currentLocation: viewTransitionOpts.currentLocation,
229 nextLocation: viewTransitionOpts.nextLocation
230 });
231 } else {
232 setPendingState(newState);
233 setVtContext({
234 isTransitioning: true,
235 flushSync: false,
236 currentLocation: viewTransitionOpts.currentLocation,
237 nextLocation: viewTransitionOpts.nextLocation
238 });
239 }
240 },
241 [router.window, reactDomFlushSyncImpl, transition, renderDfd]
242 );
243 React.useLayoutEffect(() => router.subscribe(setState), [router, setState]);
244 React.useEffect(() => {
245 if (vtContext.isTransitioning && !vtContext.flushSync) {
246 setRenderDfd(new Deferred());
247 }
248 }, [vtContext]);
249 React.useEffect(() => {
250 if (renderDfd && pendingState && router.window) {
251 let newState = pendingState;
252 let renderPromise = renderDfd.promise;
253 let transition2 = router.window.document.startViewTransition(async () => {
254 React.startTransition(() => setStateImpl(newState));
255 await renderPromise;
256 });
257 transition2.finished.finally(() => {
258 setRenderDfd(void 0);
259 setTransition(void 0);
260 setPendingState(void 0);
261 setVtContext({ isTransitioning: false });
262 });
263 setTransition(transition2);
264 }
265 }, [pendingState, renderDfd, router.window]);
266 React.useEffect(() => {
267 if (renderDfd && pendingState && state.location.key === pendingState.location.key) {
268 renderDfd.resolve();
269 }
270 }, [renderDfd, transition, state.location, pendingState]);
271 React.useEffect(() => {
272 if (!vtContext.isTransitioning && interruption) {
273 setPendingState(interruption.state);
274 setVtContext({
275 isTransitioning: true,
276 flushSync: false,
277 currentLocation: interruption.currentLocation,
278 nextLocation: interruption.nextLocation
279 });
280 setInterruption(void 0);
281 }
282 }, [vtContext.isTransitioning, interruption]);
283 let navigator = React.useMemo(() => {
284 return {
285 createHref: router.createHref,
286 encodeLocation: router.encodeLocation,
287 go: (n) => router.navigate(n),
288 push: (to, state2, opts) => router.navigate(to, {
289 state: state2,
290 preventScrollReset: _optionalChain([opts, 'optionalAccess', _10 => _10.preventScrollReset])
291 }),
292 replace: (to, state2, opts) => router.navigate(to, {
293 replace: true,
294 state: state2,
295 preventScrollReset: _optionalChain([opts, 'optionalAccess', _11 => _11.preventScrollReset])
296 })
297 };
298 }, [router]);
299 let basename = router.basename || "/";
300 let dataRouterContext = React.useMemo(
301 () => ({
302 router,
303 navigator,
304 static: false,
305 basename
306 }),
307 [router, navigator, basename]
308 );
309 return /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(_chunk7OQROU2Djs.DataRouterContext.Provider, { value: dataRouterContext }, /* @__PURE__ */ React.createElement(_chunk7OQROU2Djs.DataRouterStateContext.Provider, { value: state }, /* @__PURE__ */ React.createElement(_chunk7OQROU2Djs.FetchersContext.Provider, { value: fetcherData.current }, /* @__PURE__ */ React.createElement(_chunk7OQROU2Djs.ViewTransitionContext.Provider, { value: vtContext }, /* @__PURE__ */ React.createElement(
310 Router,
311 {
312 basename,
313 location: state.location,
314 navigationType: state.historyAction,
315 navigator
316 },
317 /* @__PURE__ */ React.createElement(
318 MemoizedDataRoutes,
319 {
320 routes: router.routes,
321 future: router.future,
322 state
323 }
324 )
325 ))))), null);
326}
327var MemoizedDataRoutes = React.memo(DataRoutes);
328function DataRoutes({
329 routes,
330 future,
331 state
332}) {
333 return _chunk7OQROU2Djs.useRoutesImpl.call(void 0, routes, void 0, state, future);
334}
335function MemoryRouter({
336 basename,
337 children,
338 initialEntries,
339 initialIndex
340}) {
341 let historyRef = React.useRef();
342 if (historyRef.current == null) {
343 historyRef.current = _chunk7OQROU2Djs.createMemoryHistory.call(void 0, {
344 initialEntries,
345 initialIndex,
346 v5Compat: true
347 });
348 }
349 let history = historyRef.current;
350 let [state, setStateImpl] = React.useState({
351 action: history.action,
352 location: history.location
353 });
354 let setState = React.useCallback(
355 (newState) => {
356 React.startTransition(() => setStateImpl(newState));
357 },
358 [setStateImpl]
359 );
360 React.useLayoutEffect(() => history.listen(setState), [history, setState]);
361 return /* @__PURE__ */ React.createElement(
362 Router,
363 {
364 basename,
365 children,
366 location: state.location,
367 navigationType: state.action,
368 navigator: history
369 }
370 );
371}
372function Navigate({
373 to,
374 replace,
375 state,
376 relative
377}) {
378 _chunk7OQROU2Djs.invariant.call(void 0,
379 _chunk7OQROU2Djs.useInRouterContext.call(void 0, ),
380 // TODO: This error is probably because they somehow have 2 versions of
381 // the router loaded. We can help them understand how to avoid that.
382 `<Navigate> may be used only in the context of a <Router> component.`
383 );
384 let { static: isStatic } = React.useContext(_chunk7OQROU2Djs.NavigationContext);
385 _chunk7OQROU2Djs.warning.call(void 0,
386 !isStatic,
387 `<Navigate> must not be used on the initial render in a <StaticRouter>. This is a no-op, but you should modify your code so the <Navigate> is only ever rendered in response to some user interaction or state change.`
388 );
389 let { matches } = React.useContext(_chunk7OQROU2Djs.RouteContext);
390 let { pathname: locationPathname } = _chunk7OQROU2Djs.useLocation.call(void 0, );
391 let navigate = _chunk7OQROU2Djs.useNavigate.call(void 0, );
392 let path = _chunk7OQROU2Djs.resolveTo.call(void 0,
393 to,
394 _chunk7OQROU2Djs.getResolveToMatches.call(void 0, matches),
395 locationPathname,
396 relative === "path"
397 );
398 let jsonPath = JSON.stringify(path);
399 React.useEffect(() => {
400 navigate(JSON.parse(jsonPath), { replace, state, relative });
401 }, [navigate, jsonPath, relative, replace, state]);
402 return null;
403}
404function Outlet(props) {
405 return _chunk7OQROU2Djs.useOutlet.call(void 0, props.context);
406}
407function Route(props) {
408 _chunk7OQROU2Djs.invariant.call(void 0,
409 false,
410 `A <Route> is only ever to be used as the child of <Routes> element, never rendered directly. Please wrap your <Route> in a <Routes>.`
411 );
412}
413function Router({
414 basename: basenameProp = "/",
415 children = null,
416 location: locationProp,
417 navigationType = "POP" /* Pop */,
418 navigator,
419 static: staticProp = false
420}) {
421 _chunk7OQROU2Djs.invariant.call(void 0,
422 !_chunk7OQROU2Djs.useInRouterContext.call(void 0, ),
423 `You cannot render a <Router> inside another <Router>. You should never have more than one in your app.`
424 );
425 let basename = basenameProp.replace(/^\/*/, "/");
426 let navigationContext = React.useMemo(
427 () => ({
428 basename,
429 navigator,
430 static: staticProp,
431 future: {}
432 }),
433 [basename, navigator, staticProp]
434 );
435 if (typeof locationProp === "string") {
436 locationProp = _chunk7OQROU2Djs.parsePath.call(void 0, locationProp);
437 }
438 let {
439 pathname = "/",
440 search = "",
441 hash = "",
442 state = null,
443 key = "default"
444 } = locationProp;
445 let locationContext = React.useMemo(() => {
446 let trailingPathname = _chunk7OQROU2Djs.stripBasename.call(void 0, pathname, basename);
447 if (trailingPathname == null) {
448 return null;
449 }
450 return {
451 location: {
452 pathname: trailingPathname,
453 search,
454 hash,
455 state,
456 key
457 },
458 navigationType
459 };
460 }, [basename, pathname, search, hash, state, key, navigationType]);
461 _chunk7OQROU2Djs.warning.call(void 0,
462 locationContext != null,
463 `<Router basename="${basename}"> is not able to match the URL "${pathname}${search}${hash}" because it does not start with the basename, so the <Router> won't render anything.`
464 );
465 if (locationContext == null) {
466 return null;
467 }
468 return /* @__PURE__ */ React.createElement(_chunk7OQROU2Djs.NavigationContext.Provider, { value: navigationContext }, /* @__PURE__ */ React.createElement(_chunk7OQROU2Djs.LocationContext.Provider, { children, value: locationContext }));
469}
470function Routes({
471 children,
472 location
473}) {
474 return _chunk7OQROU2Djs.useRoutes.call(void 0, createRoutesFromChildren(children), location);
475}
476function Await({
477 children,
478 errorElement,
479 resolve
480}) {
481 return /* @__PURE__ */ React.createElement(AwaitErrorBoundary, { resolve, errorElement }, /* @__PURE__ */ React.createElement(ResolveAwait, null, children));
482}
483var AwaitErrorBoundary = class extends React.Component {
484 constructor(props) {
485 super(props);
486 this.state = { error: null };
487 }
488 static getDerivedStateFromError(error) {
489 return { error };
490 }
491 componentDidCatch(error, errorInfo) {
492 console.error(
493 "<Await> caught the following error during render",
494 error,
495 errorInfo
496 );
497 }
498 render() {
499 let { children, errorElement, resolve } = this.props;
500 let promise = null;
501 let status = 0 /* pending */;
502 if (!(resolve instanceof Promise)) {
503 status = 1 /* success */;
504 promise = Promise.resolve();
505 Object.defineProperty(promise, "_tracked", { get: () => true });
506 Object.defineProperty(promise, "_data", { get: () => resolve });
507 } else if (this.state.error) {
508 status = 2 /* error */;
509 let renderError = this.state.error;
510 promise = Promise.reject().catch(() => {
511 });
512 Object.defineProperty(promise, "_tracked", { get: () => true });
513 Object.defineProperty(promise, "_error", { get: () => renderError });
514 } else if (resolve._tracked) {
515 promise = resolve;
516 status = "_error" in promise ? 2 /* error */ : "_data" in promise ? 1 /* success */ : 0 /* pending */;
517 } else {
518 status = 0 /* pending */;
519 Object.defineProperty(resolve, "_tracked", { get: () => true });
520 promise = resolve.then(
521 (data) => Object.defineProperty(resolve, "_data", { get: () => data }),
522 (error) => Object.defineProperty(resolve, "_error", { get: () => error })
523 );
524 }
525 if (status === 2 /* error */ && !errorElement) {
526 throw promise._error;
527 }
528 if (status === 2 /* error */) {
529 return /* @__PURE__ */ React.createElement(_chunk7OQROU2Djs.AwaitContext.Provider, { value: promise, children: errorElement });
530 }
531 if (status === 1 /* success */) {
532 return /* @__PURE__ */ React.createElement(_chunk7OQROU2Djs.AwaitContext.Provider, { value: promise, children });
533 }
534 throw promise;
535 }
536};
537function ResolveAwait({
538 children
539}) {
540 let data = _chunk7OQROU2Djs.useAsyncValue.call(void 0, );
541 let toRender = typeof children === "function" ? children(data) : children;
542 return /* @__PURE__ */ React.createElement(React.Fragment, null, toRender);
543}
544function createRoutesFromChildren(children, parentPath = []) {
545 let routes = [];
546 React.Children.forEach(children, (element, index) => {
547 if (!React.isValidElement(element)) {
548 return;
549 }
550 let treePath = [...parentPath, index];
551 if (element.type === React.Fragment) {
552 routes.push.apply(
553 routes,
554 createRoutesFromChildren(element.props.children, treePath)
555 );
556 return;
557 }
558 _chunk7OQROU2Djs.invariant.call(void 0,
559 element.type === Route,
560 `[${typeof element.type === "string" ? element.type : element.type.name}] is not a <Route> component. All component children of <Routes> must be a <Route> or <React.Fragment>`
561 );
562 _chunk7OQROU2Djs.invariant.call(void 0,
563 !element.props.index || !element.props.children,
564 "An index route cannot have child routes."
565 );
566 let route = {
567 id: element.props.id || treePath.join("-"),
568 caseSensitive: element.props.caseSensitive,
569 element: element.props.element,
570 Component: element.props.Component,
571 index: element.props.index,
572 path: element.props.path,
573 loader: element.props.loader,
574 action: element.props.action,
575 hydrateFallbackElement: element.props.hydrateFallbackElement,
576 HydrateFallback: element.props.HydrateFallback,
577 errorElement: element.props.errorElement,
578 ErrorBoundary: element.props.ErrorBoundary,
579 hasErrorBoundary: element.props.hasErrorBoundary === true || element.props.ErrorBoundary != null || element.props.errorElement != null,
580 shouldRevalidate: element.props.shouldRevalidate,
581 handle: element.props.handle,
582 lazy: element.props.lazy
583 };
584 if (element.props.children) {
585 route.children = createRoutesFromChildren(
586 element.props.children,
587 treePath
588 );
589 }
590 routes.push(route);
591 });
592 return routes;
593}
594var createRoutesFromElements = createRoutesFromChildren;
595function renderMatches(matches) {
596 return _chunk7OQROU2Djs._renderMatches.call(void 0, matches);
597}
598function useRouteComponentProps() {
599 return {
600 params: _chunk7OQROU2Djs.useParams.call(void 0, ),
601 loaderData: _chunk7OQROU2Djs.useLoaderData.call(void 0, ),
602 actionData: _chunk7OQROU2Djs.useActionData.call(void 0, ),
603 matches: _chunk7OQROU2Djs.useMatches.call(void 0, )
604 };
605}
606function WithComponentProps({
607 children
608}) {
609 const props = useRouteComponentProps();
610 return React.cloneElement(children, props);
611}
612function withComponentProps(Component2) {
613 return function WithComponentProps2() {
614 const props = useRouteComponentProps();
615 return React.createElement(Component2, props);
616 };
617}
618function useHydrateFallbackProps() {
619 return {
620 params: _chunk7OQROU2Djs.useParams.call(void 0, ),
621 loaderData: _chunk7OQROU2Djs.useLoaderData.call(void 0, ),
622 actionData: _chunk7OQROU2Djs.useActionData.call(void 0, )
623 };
624}
625function WithHydrateFallbackProps({
626 children
627}) {
628 const props = useHydrateFallbackProps();
629 return React.cloneElement(children, props);
630}
631function withHydrateFallbackProps(HydrateFallback) {
632 return function WithHydrateFallbackProps2() {
633 const props = useHydrateFallbackProps();
634 return React.createElement(HydrateFallback, props);
635 };
636}
637function useErrorBoundaryProps() {
638 return {
639 params: _chunk7OQROU2Djs.useParams.call(void 0, ),
640 loaderData: _chunk7OQROU2Djs.useLoaderData.call(void 0, ),
641 actionData: _chunk7OQROU2Djs.useActionData.call(void 0, ),
642 error: _chunk7OQROU2Djs.useRouteError.call(void 0, )
643 };
644}
645function WithErrorBoundaryProps({
646 children
647}) {
648 const props = useErrorBoundaryProps();
649 return React.cloneElement(children, props);
650}
651function withErrorBoundaryProps(ErrorBoundary) {
652 return function WithErrorBoundaryProps2() {
653 const props = useErrorBoundaryProps();
654 return React.createElement(ErrorBoundary, props);
655 };
656}
657
658// lib/dom/dom.ts
659var defaultMethod = "get";
660var defaultEncType = "application/x-www-form-urlencoded";
661function isHtmlElement(object) {
662 return object != null && typeof object.tagName === "string";
663}
664function isButtonElement(object) {
665 return isHtmlElement(object) && object.tagName.toLowerCase() === "button";
666}
667function isFormElement(object) {
668 return isHtmlElement(object) && object.tagName.toLowerCase() === "form";
669}
670function isInputElement(object) {
671 return isHtmlElement(object) && object.tagName.toLowerCase() === "input";
672}
673function isModifiedEvent(event) {
674 return !!(event.metaKey || event.altKey || event.ctrlKey || event.shiftKey);
675}
676function shouldProcessLinkClick(event, target) {
677 return event.button === 0 && // Ignore everything but left clicks
678 (!target || target === "_self") && // Let browser handle "target=_blank" etc.
679 !isModifiedEvent(event);
680}
681function createSearchParams(init = "") {
682 return new URLSearchParams(
683 typeof init === "string" || Array.isArray(init) || init instanceof URLSearchParams ? init : Object.keys(init).reduce((memo2, key) => {
684 let value = init[key];
685 return memo2.concat(
686 Array.isArray(value) ? value.map((v) => [key, v]) : [[key, value]]
687 );
688 }, [])
689 );
690}
691function getSearchParamsForLocation(locationSearch, defaultSearchParams) {
692 let searchParams = createSearchParams(locationSearch);
693 if (defaultSearchParams) {
694 defaultSearchParams.forEach((_, key) => {
695 if (!searchParams.has(key)) {
696 defaultSearchParams.getAll(key).forEach((value) => {
697 searchParams.append(key, value);
698 });
699 }
700 });
701 }
702 return searchParams;
703}
704var _formDataSupportsSubmitter = null;
705function isFormDataSubmitterSupported() {
706 if (_formDataSupportsSubmitter === null) {
707 try {
708 new FormData(
709 document.createElement("form"),
710 // @ts-expect-error if FormData supports the submitter parameter, this will throw
711 0
712 );
713 _formDataSupportsSubmitter = false;
714 } catch (e) {
715 _formDataSupportsSubmitter = true;
716 }
717 }
718 return _formDataSupportsSubmitter;
719}
720var supportedFormEncTypes = /* @__PURE__ */ new Set([
721 "application/x-www-form-urlencoded",
722 "multipart/form-data",
723 "text/plain"
724]);
725function getFormEncType(encType) {
726 if (encType != null && !supportedFormEncTypes.has(encType)) {
727 _chunk7OQROU2Djs.warning.call(void 0,
728 false,
729 `"${encType}" is not a valid \`encType\` for \`<Form>\`/\`<fetcher.Form>\` and will default to "${defaultEncType}"`
730 );
731 return null;
732 }
733 return encType;
734}
735function getFormSubmissionInfo(target, basename) {
736 let method;
737 let action;
738 let encType;
739 let formData;
740 let body;
741 if (isFormElement(target)) {
742 let attr = target.getAttribute("action");
743 action = attr ? _chunk7OQROU2Djs.stripBasename.call(void 0, attr, basename) : null;
744 method = target.getAttribute("method") || defaultMethod;
745 encType = getFormEncType(target.getAttribute("enctype")) || defaultEncType;
746 formData = new FormData(target);
747 } else if (isButtonElement(target) || isInputElement(target) && (target.type === "submit" || target.type === "image")) {
748 let form = target.form;
749 if (form == null) {
750 throw new Error(
751 `Cannot submit a <button> or <input type="submit"> without a <form>`
752 );
753 }
754 let attr = target.getAttribute("formaction") || form.getAttribute("action");
755 action = attr ? _chunk7OQROU2Djs.stripBasename.call(void 0, attr, basename) : null;
756 method = target.getAttribute("formmethod") || form.getAttribute("method") || defaultMethod;
757 encType = getFormEncType(target.getAttribute("formenctype")) || getFormEncType(form.getAttribute("enctype")) || defaultEncType;
758 formData = new FormData(form, target);
759 if (!isFormDataSubmitterSupported()) {
760 let { name, type, value } = target;
761 if (type === "image") {
762 let prefix = name ? `${name}.` : "";
763 formData.append(`${prefix}x`, "0");
764 formData.append(`${prefix}y`, "0");
765 } else if (name) {
766 formData.append(name, value);
767 }
768 }
769 } else if (isHtmlElement(target)) {
770 throw new Error(
771 `Cannot submit element that is not <form>, <button>, or <input type="submit|image">`
772 );
773 } else {
774 method = defaultMethod;
775 action = null;
776 encType = defaultEncType;
777 body = target;
778 }
779 if (formData && encType === "text/plain") {
780 body = formData;
781 formData = void 0;
782 }
783 return { action, method: method.toLowerCase(), encType, formData, body };
784}
785
786// lib/dom/lib.tsx
787
788var isBrowser = typeof window !== "undefined" && typeof window.document !== "undefined" && typeof window.document.createElement !== "undefined";
789try {
790 if (isBrowser) {
791 window.__reactRouterVersion = // @ts-expect-error
792 "7.7.1";
793 }
794} catch (e) {
795}
796function createBrowserRouter(routes, opts) {
797 return _chunk7OQROU2Djs.createRouter.call(void 0, {
798 basename: _optionalChain([opts, 'optionalAccess', _12 => _12.basename]),
799 unstable_getContext: _optionalChain([opts, 'optionalAccess', _13 => _13.unstable_getContext]),
800 future: _optionalChain([opts, 'optionalAccess', _14 => _14.future]),
801 history: _chunk7OQROU2Djs.createBrowserHistory.call(void 0, { window: _optionalChain([opts, 'optionalAccess', _15 => _15.window]) }),
802 hydrationData: _optionalChain([opts, 'optionalAccess', _16 => _16.hydrationData]) || parseHydrationData(),
803 routes,
804 mapRouteProperties,
805 hydrationRouteProperties,
806 dataStrategy: _optionalChain([opts, 'optionalAccess', _17 => _17.dataStrategy]),
807 patchRoutesOnNavigation: _optionalChain([opts, 'optionalAccess', _18 => _18.patchRoutesOnNavigation]),
808 window: _optionalChain([opts, 'optionalAccess', _19 => _19.window])
809 }).initialize();
810}
811function createHashRouter(routes, opts) {
812 return _chunk7OQROU2Djs.createRouter.call(void 0, {
813 basename: _optionalChain([opts, 'optionalAccess', _20 => _20.basename]),
814 unstable_getContext: _optionalChain([opts, 'optionalAccess', _21 => _21.unstable_getContext]),
815 future: _optionalChain([opts, 'optionalAccess', _22 => _22.future]),
816 history: _chunk7OQROU2Djs.createHashHistory.call(void 0, { window: _optionalChain([opts, 'optionalAccess', _23 => _23.window]) }),
817 hydrationData: _optionalChain([opts, 'optionalAccess', _24 => _24.hydrationData]) || parseHydrationData(),
818 routes,
819 mapRouteProperties,
820 hydrationRouteProperties,
821 dataStrategy: _optionalChain([opts, 'optionalAccess', _25 => _25.dataStrategy]),
822 patchRoutesOnNavigation: _optionalChain([opts, 'optionalAccess', _26 => _26.patchRoutesOnNavigation]),
823 window: _optionalChain([opts, 'optionalAccess', _27 => _27.window])
824 }).initialize();
825}
826function parseHydrationData() {
827 let state = _optionalChain([window, 'optionalAccess', _28 => _28.__staticRouterHydrationData]);
828 if (state && state.errors) {
829 state = {
830 ...state,
831 errors: deserializeErrors(state.errors)
832 };
833 }
834 return state;
835}
836function deserializeErrors(errors) {
837 if (!errors) return null;
838 let entries = Object.entries(errors);
839 let serialized = {};
840 for (let [key, val] of entries) {
841 if (val && val.__type === "RouteErrorResponse") {
842 serialized[key] = new (0, _chunk7OQROU2Djs.ErrorResponseImpl)(
843 val.status,
844 val.statusText,
845 val.data,
846 val.internal === true
847 );
848 } else if (val && val.__type === "Error") {
849 if (val.__subType) {
850 let ErrorConstructor = window[val.__subType];
851 if (typeof ErrorConstructor === "function") {
852 try {
853 let error = new ErrorConstructor(val.message);
854 error.stack = "";
855 serialized[key] = error;
856 } catch (e) {
857 }
858 }
859 }
860 if (serialized[key] == null) {
861 let error = new Error(val.message);
862 error.stack = "";
863 serialized[key] = error;
864 }
865 } else {
866 serialized[key] = val;
867 }
868 }
869 return serialized;
870}
871function BrowserRouter({
872 basename,
873 children,
874 window: window2
875}) {
876 let historyRef = React2.useRef();
877 if (historyRef.current == null) {
878 historyRef.current = _chunk7OQROU2Djs.createBrowserHistory.call(void 0, { window: window2, v5Compat: true });
879 }
880 let history = historyRef.current;
881 let [state, setStateImpl] = React2.useState({
882 action: history.action,
883 location: history.location
884 });
885 let setState = React2.useCallback(
886 (newState) => {
887 React2.startTransition(() => setStateImpl(newState));
888 },
889 [setStateImpl]
890 );
891 React2.useLayoutEffect(() => history.listen(setState), [history, setState]);
892 return /* @__PURE__ */ React2.createElement(
893 Router,
894 {
895 basename,
896 children,
897 location: state.location,
898 navigationType: state.action,
899 navigator: history
900 }
901 );
902}
903function HashRouter({ basename, children, window: window2 }) {
904 let historyRef = React2.useRef();
905 if (historyRef.current == null) {
906 historyRef.current = _chunk7OQROU2Djs.createHashHistory.call(void 0, { window: window2, v5Compat: true });
907 }
908 let history = historyRef.current;
909 let [state, setStateImpl] = React2.useState({
910 action: history.action,
911 location: history.location
912 });
913 let setState = React2.useCallback(
914 (newState) => {
915 React2.startTransition(() => setStateImpl(newState));
916 },
917 [setStateImpl]
918 );
919 React2.useLayoutEffect(() => history.listen(setState), [history, setState]);
920 return /* @__PURE__ */ React2.createElement(
921 Router,
922 {
923 basename,
924 children,
925 location: state.location,
926 navigationType: state.action,
927 navigator: history
928 }
929 );
930}
931function HistoryRouter({
932 basename,
933 children,
934 history
935}) {
936 let [state, setStateImpl] = React2.useState({
937 action: history.action,
938 location: history.location
939 });
940 let setState = React2.useCallback(
941 (newState) => {
942 React2.startTransition(() => setStateImpl(newState));
943 },
944 [setStateImpl]
945 );
946 React2.useLayoutEffect(() => history.listen(setState), [history, setState]);
947 return /* @__PURE__ */ React2.createElement(
948 Router,
949 {
950 basename,
951 children,
952 location: state.location,
953 navigationType: state.action,
954 navigator: history
955 }
956 );
957}
958HistoryRouter.displayName = "unstable_HistoryRouter";
959var ABSOLUTE_URL_REGEX = /^(?:[a-z][a-z0-9+.-]*:|\/\/)/i;
960var Link = React2.forwardRef(
961 function LinkWithRef({
962 onClick,
963 discover = "render",
964 prefetch = "none",
965 relative,
966 reloadDocument,
967 replace,
968 state,
969 target,
970 to,
971 preventScrollReset,
972 viewTransition,
973 ...rest
974 }, forwardedRef) {
975 let { basename } = React2.useContext(_chunk7OQROU2Djs.NavigationContext);
976 let isAbsolute = typeof to === "string" && ABSOLUTE_URL_REGEX.test(to);
977 let absoluteHref;
978 let isExternal = false;
979 if (typeof to === "string" && isAbsolute) {
980 absoluteHref = to;
981 if (isBrowser) {
982 try {
983 let currentUrl = new URL(window.location.href);
984 let targetUrl = to.startsWith("//") ? new URL(currentUrl.protocol + to) : new URL(to);
985 let path = _chunk7OQROU2Djs.stripBasename.call(void 0, targetUrl.pathname, basename);
986 if (targetUrl.origin === currentUrl.origin && path != null) {
987 to = path + targetUrl.search + targetUrl.hash;
988 } else {
989 isExternal = true;
990 }
991 } catch (e) {
992 _chunk7OQROU2Djs.warning.call(void 0,
993 false,
994 `<Link to="${to}"> contains an invalid URL which will probably break when clicked - please update to a valid URL path.`
995 );
996 }
997 }
998 }
999 let href = _chunk7OQROU2Djs.useHref.call(void 0, to, { relative });
1000 let [shouldPrefetch, prefetchRef, prefetchHandlers] = _chunk7OQROU2Djs.usePrefetchBehavior.call(void 0,
1001 prefetch,
1002 rest
1003 );
1004 let internalOnClick = useLinkClickHandler(to, {
1005 replace,
1006 state,
1007 target,
1008 preventScrollReset,
1009 relative,
1010 viewTransition
1011 });
1012 function handleClick(event) {
1013 if (onClick) onClick(event);
1014 if (!event.defaultPrevented) {
1015 internalOnClick(event);
1016 }
1017 }
1018 let link = (
1019 // eslint-disable-next-line jsx-a11y/anchor-has-content
1020 /* @__PURE__ */ React2.createElement(
1021 "a",
1022 {
1023 ...rest,
1024 ...prefetchHandlers,
1025 href: absoluteHref || href,
1026 onClick: isExternal || reloadDocument ? onClick : handleClick,
1027 ref: _chunk7OQROU2Djs.mergeRefs.call(void 0, forwardedRef, prefetchRef),
1028 target,
1029 "data-discover": !isAbsolute && discover === "render" ? "true" : void 0
1030 }
1031 )
1032 );
1033 return shouldPrefetch && !isAbsolute ? /* @__PURE__ */ React2.createElement(React2.Fragment, null, link, /* @__PURE__ */ React2.createElement(_chunk7OQROU2Djs.PrefetchPageLinks, { page: href })) : link;
1034 }
1035);
1036Link.displayName = "Link";
1037var NavLink = React2.forwardRef(
1038 function NavLinkWithRef({
1039 "aria-current": ariaCurrentProp = "page",
1040 caseSensitive = false,
1041 className: classNameProp = "",
1042 end = false,
1043 style: styleProp,
1044 to,
1045 viewTransition,
1046 children,
1047 ...rest
1048 }, ref) {
1049 let path = _chunk7OQROU2Djs.useResolvedPath.call(void 0, to, { relative: rest.relative });
1050 let location = _chunk7OQROU2Djs.useLocation.call(void 0, );
1051 let routerState = React2.useContext(_chunk7OQROU2Djs.DataRouterStateContext);
1052 let { navigator, basename } = React2.useContext(_chunk7OQROU2Djs.NavigationContext);
1053 let isTransitioning = routerState != null && // Conditional usage is OK here because the usage of a data router is static
1054 // eslint-disable-next-line react-hooks/rules-of-hooks
1055 useViewTransitionState(path) && viewTransition === true;
1056 let toPathname = navigator.encodeLocation ? navigator.encodeLocation(path).pathname : path.pathname;
1057 let locationPathname = location.pathname;
1058 let nextLocationPathname = routerState && routerState.navigation && routerState.navigation.location ? routerState.navigation.location.pathname : null;
1059 if (!caseSensitive) {
1060 locationPathname = locationPathname.toLowerCase();
1061 nextLocationPathname = nextLocationPathname ? nextLocationPathname.toLowerCase() : null;
1062 toPathname = toPathname.toLowerCase();
1063 }
1064 if (nextLocationPathname && basename) {
1065 nextLocationPathname = _chunk7OQROU2Djs.stripBasename.call(void 0, nextLocationPathname, basename) || nextLocationPathname;
1066 }
1067 const endSlashPosition = toPathname !== "/" && toPathname.endsWith("/") ? toPathname.length - 1 : toPathname.length;
1068 let isActive = locationPathname === toPathname || !end && locationPathname.startsWith(toPathname) && locationPathname.charAt(endSlashPosition) === "/";
1069 let isPending = nextLocationPathname != null && (nextLocationPathname === toPathname || !end && nextLocationPathname.startsWith(toPathname) && nextLocationPathname.charAt(toPathname.length) === "/");
1070 let renderProps = {
1071 isActive,
1072 isPending,
1073 isTransitioning
1074 };
1075 let ariaCurrent = isActive ? ariaCurrentProp : void 0;
1076 let className;
1077 if (typeof classNameProp === "function") {
1078 className = classNameProp(renderProps);
1079 } else {
1080 className = [
1081 classNameProp,
1082 isActive ? "active" : null,
1083 isPending ? "pending" : null,
1084 isTransitioning ? "transitioning" : null
1085 ].filter(Boolean).join(" ");
1086 }
1087 let style = typeof styleProp === "function" ? styleProp(renderProps) : styleProp;
1088 return /* @__PURE__ */ React2.createElement(
1089 Link,
1090 {
1091 ...rest,
1092 "aria-current": ariaCurrent,
1093 className,
1094 ref,
1095 style,
1096 to,
1097 viewTransition
1098 },
1099 typeof children === "function" ? children(renderProps) : children
1100 );
1101 }
1102);
1103NavLink.displayName = "NavLink";
1104var Form = React2.forwardRef(
1105 ({
1106 discover = "render",
1107 fetcherKey,
1108 navigate,
1109 reloadDocument,
1110 replace,
1111 state,
1112 method = defaultMethod,
1113 action,
1114 onSubmit,
1115 relative,
1116 preventScrollReset,
1117 viewTransition,
1118 ...props
1119 }, forwardedRef) => {
1120 let submit = useSubmit();
1121 let formAction = useFormAction(action, { relative });
1122 let formMethod = method.toLowerCase() === "get" ? "get" : "post";
1123 let isAbsolute = typeof action === "string" && ABSOLUTE_URL_REGEX.test(action);
1124 let submitHandler = (event) => {
1125 onSubmit && onSubmit(event);
1126 if (event.defaultPrevented) return;
1127 event.preventDefault();
1128 let submitter = event.nativeEvent.submitter;
1129 let submitMethod = _optionalChain([submitter, 'optionalAccess', _29 => _29.getAttribute, 'call', _30 => _30("formmethod")]) || method;
1130 submit(submitter || event.currentTarget, {
1131 fetcherKey,
1132 method: submitMethod,
1133 navigate,
1134 replace,
1135 state,
1136 relative,
1137 preventScrollReset,
1138 viewTransition
1139 });
1140 };
1141 return /* @__PURE__ */ React2.createElement(
1142 "form",
1143 {
1144 ref: forwardedRef,
1145 method: formMethod,
1146 action: formAction,
1147 onSubmit: reloadDocument ? onSubmit : submitHandler,
1148 ...props,
1149 "data-discover": !isAbsolute && discover === "render" ? "true" : void 0
1150 }
1151 );
1152 }
1153);
1154Form.displayName = "Form";
1155function ScrollRestoration({
1156 getKey,
1157 storageKey,
1158 ...props
1159}) {
1160 let remixContext = React2.useContext(_chunk7OQROU2Djs.FrameworkContext);
1161 let { basename } = React2.useContext(_chunk7OQROU2Djs.NavigationContext);
1162 let location = _chunk7OQROU2Djs.useLocation.call(void 0, );
1163 let matches = _chunk7OQROU2Djs.useMatches.call(void 0, );
1164 useScrollRestoration({ getKey, storageKey });
1165 let ssrKey = React2.useMemo(
1166 () => {
1167 if (!remixContext || !getKey) return null;
1168 let userKey = getScrollRestorationKey(
1169 location,
1170 matches,
1171 basename,
1172 getKey
1173 );
1174 return userKey !== location.key ? userKey : null;
1175 },
1176 // Nah, we only need this the first time for the SSR render
1177 // eslint-disable-next-line react-hooks/exhaustive-deps
1178 []
1179 );
1180 if (!remixContext || remixContext.isSpaMode) {
1181 return null;
1182 }
1183 let restoreScroll = ((storageKey2, restoreKey) => {
1184 if (!window.history.state || !window.history.state.key) {
1185 let key = Math.random().toString(32).slice(2);
1186 window.history.replaceState({ key }, "");
1187 }
1188 try {
1189 let positions = JSON.parse(sessionStorage.getItem(storageKey2) || "{}");
1190 let storedY = positions[restoreKey || window.history.state.key];
1191 if (typeof storedY === "number") {
1192 window.scrollTo(0, storedY);
1193 }
1194 } catch (error) {
1195 console.error(error);
1196 sessionStorage.removeItem(storageKey2);
1197 }
1198 }).toString();
1199 return /* @__PURE__ */ React2.createElement(
1200 "script",
1201 {
1202 ...props,
1203 suppressHydrationWarning: true,
1204 dangerouslySetInnerHTML: {
1205 __html: `(${restoreScroll})(${JSON.stringify(
1206 storageKey || SCROLL_RESTORATION_STORAGE_KEY
1207 )}, ${JSON.stringify(ssrKey)})`
1208 }
1209 }
1210 );
1211}
1212ScrollRestoration.displayName = "ScrollRestoration";
1213function getDataRouterConsoleError(hookName) {
1214 return `${hookName} must be used within a data router. See https://reactrouter.com/en/main/routers/picking-a-router.`;
1215}
1216function useDataRouterContext(hookName) {
1217 let ctx = React2.useContext(_chunk7OQROU2Djs.DataRouterContext);
1218 _chunk7OQROU2Djs.invariant.call(void 0, ctx, getDataRouterConsoleError(hookName));
1219 return ctx;
1220}
1221function useDataRouterState(hookName) {
1222 let state = React2.useContext(_chunk7OQROU2Djs.DataRouterStateContext);
1223 _chunk7OQROU2Djs.invariant.call(void 0, state, getDataRouterConsoleError(hookName));
1224 return state;
1225}
1226function useLinkClickHandler(to, {
1227 target,
1228 replace: replaceProp,
1229 state,
1230 preventScrollReset,
1231 relative,
1232 viewTransition
1233} = {}) {
1234 let navigate = _chunk7OQROU2Djs.useNavigate.call(void 0, );
1235 let location = _chunk7OQROU2Djs.useLocation.call(void 0, );
1236 let path = _chunk7OQROU2Djs.useResolvedPath.call(void 0, to, { relative });
1237 return React2.useCallback(
1238 (event) => {
1239 if (shouldProcessLinkClick(event, target)) {
1240 event.preventDefault();
1241 let replace = replaceProp !== void 0 ? replaceProp : _chunk7OQROU2Djs.createPath.call(void 0, location) === _chunk7OQROU2Djs.createPath.call(void 0, path);
1242 navigate(to, {
1243 replace,
1244 state,
1245 preventScrollReset,
1246 relative,
1247 viewTransition
1248 });
1249 }
1250 },
1251 [
1252 location,
1253 navigate,
1254 path,
1255 replaceProp,
1256 state,
1257 target,
1258 to,
1259 preventScrollReset,
1260 relative,
1261 viewTransition
1262 ]
1263 );
1264}
1265function useSearchParams(defaultInit) {
1266 _chunk7OQROU2Djs.warning.call(void 0,
1267 typeof URLSearchParams !== "undefined",
1268 `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.`
1269 );
1270 let defaultSearchParamsRef = React2.useRef(createSearchParams(defaultInit));
1271 let hasSetSearchParamsRef = React2.useRef(false);
1272 let location = _chunk7OQROU2Djs.useLocation.call(void 0, );
1273 let searchParams = React2.useMemo(
1274 () => (
1275 // Only merge in the defaults if we haven't yet called setSearchParams.
1276 // Once we call that we want those to take precedence, otherwise you can't
1277 // remove a param with setSearchParams({}) if it has an initial value
1278 getSearchParamsForLocation(
1279 location.search,
1280 hasSetSearchParamsRef.current ? null : defaultSearchParamsRef.current
1281 )
1282 ),
1283 [location.search]
1284 );
1285 let navigate = _chunk7OQROU2Djs.useNavigate.call(void 0, );
1286 let setSearchParams = React2.useCallback(
1287 (nextInit, navigateOptions) => {
1288 const newSearchParams = createSearchParams(
1289 typeof nextInit === "function" ? nextInit(new URLSearchParams(searchParams)) : nextInit
1290 );
1291 hasSetSearchParamsRef.current = true;
1292 navigate("?" + newSearchParams, navigateOptions);
1293 },
1294 [navigate, searchParams]
1295 );
1296 return [searchParams, setSearchParams];
1297}
1298var fetcherId = 0;
1299var getUniqueFetcherId = () => `__${String(++fetcherId)}__`;
1300function useSubmit() {
1301 let { router } = useDataRouterContext("useSubmit" /* UseSubmit */);
1302 let { basename } = React2.useContext(_chunk7OQROU2Djs.NavigationContext);
1303 let currentRouteId = _chunk7OQROU2Djs.useRouteId.call(void 0, );
1304 return React2.useCallback(
1305 async (target, options = {}) => {
1306 let { action, method, encType, formData, body } = getFormSubmissionInfo(
1307 target,
1308 basename
1309 );
1310 if (options.navigate === false) {
1311 let key = options.fetcherKey || getUniqueFetcherId();
1312 await router.fetch(key, currentRouteId, options.action || action, {
1313 preventScrollReset: options.preventScrollReset,
1314 formData,
1315 body,
1316 formMethod: options.method || method,
1317 formEncType: options.encType || encType,
1318 flushSync: options.flushSync
1319 });
1320 } else {
1321 await router.navigate(options.action || action, {
1322 preventScrollReset: options.preventScrollReset,
1323 formData,
1324 body,
1325 formMethod: options.method || method,
1326 formEncType: options.encType || encType,
1327 replace: options.replace,
1328 state: options.state,
1329 fromRouteId: currentRouteId,
1330 flushSync: options.flushSync,
1331 viewTransition: options.viewTransition
1332 });
1333 }
1334 },
1335 [router, basename, currentRouteId]
1336 );
1337}
1338function useFormAction(action, { relative } = {}) {
1339 let { basename } = React2.useContext(_chunk7OQROU2Djs.NavigationContext);
1340 let routeContext = React2.useContext(_chunk7OQROU2Djs.RouteContext);
1341 _chunk7OQROU2Djs.invariant.call(void 0, routeContext, "useFormAction must be used inside a RouteContext");
1342 let [match] = routeContext.matches.slice(-1);
1343 let path = { ..._chunk7OQROU2Djs.useResolvedPath.call(void 0, action ? action : ".", { relative }) };
1344 let location = _chunk7OQROU2Djs.useLocation.call(void 0, );
1345 if (action == null) {
1346 path.search = location.search;
1347 let params = new URLSearchParams(path.search);
1348 let indexValues = params.getAll("index");
1349 let hasNakedIndexParam = indexValues.some((v) => v === "");
1350 if (hasNakedIndexParam) {
1351 params.delete("index");
1352 indexValues.filter((v) => v).forEach((v) => params.append("index", v));
1353 let qs = params.toString();
1354 path.search = qs ? `?${qs}` : "";
1355 }
1356 }
1357 if ((!action || action === ".") && match.route.index) {
1358 path.search = path.search ? path.search.replace(/^\?/, "?index&") : "?index";
1359 }
1360 if (basename !== "/") {
1361 path.pathname = path.pathname === "/" ? basename : _chunk7OQROU2Djs.joinPaths.call(void 0, [basename, path.pathname]);
1362 }
1363 return _chunk7OQROU2Djs.createPath.call(void 0, path);
1364}
1365function useFetcher({
1366 key
1367} = {}) {
1368 let { router } = useDataRouterContext("useFetcher" /* UseFetcher */);
1369 let state = useDataRouterState("useFetcher" /* UseFetcher */);
1370 let fetcherData = React2.useContext(_chunk7OQROU2Djs.FetchersContext);
1371 let route = React2.useContext(_chunk7OQROU2Djs.RouteContext);
1372 let routeId = _optionalChain([route, 'access', _31 => _31.matches, 'access', _32 => _32[route.matches.length - 1], 'optionalAccess', _33 => _33.route, 'access', _34 => _34.id]);
1373 _chunk7OQROU2Djs.invariant.call(void 0, fetcherData, `useFetcher must be used inside a FetchersContext`);
1374 _chunk7OQROU2Djs.invariant.call(void 0, route, `useFetcher must be used inside a RouteContext`);
1375 _chunk7OQROU2Djs.invariant.call(void 0,
1376 routeId != null,
1377 `useFetcher can only be used on routes that contain a unique "id"`
1378 );
1379 let defaultKey = React2.useId();
1380 let [fetcherKey, setFetcherKey] = React2.useState(key || defaultKey);
1381 if (key && key !== fetcherKey) {
1382 setFetcherKey(key);
1383 }
1384 React2.useEffect(() => {
1385 router.getFetcher(fetcherKey);
1386 return () => router.deleteFetcher(fetcherKey);
1387 }, [router, fetcherKey]);
1388 let load = React2.useCallback(
1389 async (href, opts) => {
1390 _chunk7OQROU2Djs.invariant.call(void 0, routeId, "No routeId available for fetcher.load()");
1391 await router.fetch(fetcherKey, routeId, href, opts);
1392 },
1393 [fetcherKey, routeId, router]
1394 );
1395 let submitImpl = useSubmit();
1396 let submit = React2.useCallback(
1397 async (target, opts) => {
1398 await submitImpl(target, {
1399 ...opts,
1400 navigate: false,
1401 fetcherKey
1402 });
1403 },
1404 [fetcherKey, submitImpl]
1405 );
1406 let FetcherForm = React2.useMemo(() => {
1407 let FetcherForm2 = React2.forwardRef(
1408 (props, ref) => {
1409 return /* @__PURE__ */ React2.createElement(Form, { ...props, navigate: false, fetcherKey, ref });
1410 }
1411 );
1412 FetcherForm2.displayName = "fetcher.Form";
1413 return FetcherForm2;
1414 }, [fetcherKey]);
1415 let fetcher = state.fetchers.get(fetcherKey) || _chunk7OQROU2Djs.IDLE_FETCHER;
1416 let data = fetcherData.get(fetcherKey);
1417 let fetcherWithComponents = React2.useMemo(
1418 () => ({
1419 Form: FetcherForm,
1420 submit,
1421 load,
1422 ...fetcher,
1423 data
1424 }),
1425 [FetcherForm, submit, load, fetcher, data]
1426 );
1427 return fetcherWithComponents;
1428}
1429function useFetchers() {
1430 let state = useDataRouterState("useFetchers" /* UseFetchers */);
1431 return Array.from(state.fetchers.entries()).map(([key, fetcher]) => ({
1432 ...fetcher,
1433 key
1434 }));
1435}
1436var SCROLL_RESTORATION_STORAGE_KEY = "react-router-scroll-positions";
1437var savedScrollPositions = {};
1438function getScrollRestorationKey(location, matches, basename, getKey) {
1439 let key = null;
1440 if (getKey) {
1441 if (basename !== "/") {
1442 key = getKey(
1443 {
1444 ...location,
1445 pathname: _chunk7OQROU2Djs.stripBasename.call(void 0, location.pathname, basename) || location.pathname
1446 },
1447 matches
1448 );
1449 } else {
1450 key = getKey(location, matches);
1451 }
1452 }
1453 if (key == null) {
1454 key = location.key;
1455 }
1456 return key;
1457}
1458function useScrollRestoration({
1459 getKey,
1460 storageKey
1461} = {}) {
1462 let { router } = useDataRouterContext("useScrollRestoration" /* UseScrollRestoration */);
1463 let { restoreScrollPosition, preventScrollReset } = useDataRouterState(
1464 "useScrollRestoration" /* UseScrollRestoration */
1465 );
1466 let { basename } = React2.useContext(_chunk7OQROU2Djs.NavigationContext);
1467 let location = _chunk7OQROU2Djs.useLocation.call(void 0, );
1468 let matches = _chunk7OQROU2Djs.useMatches.call(void 0, );
1469 let navigation = _chunk7OQROU2Djs.useNavigation.call(void 0, );
1470 React2.useEffect(() => {
1471 window.history.scrollRestoration = "manual";
1472 return () => {
1473 window.history.scrollRestoration = "auto";
1474 };
1475 }, []);
1476 usePageHide(
1477 React2.useCallback(() => {
1478 if (navigation.state === "idle") {
1479 let key = getScrollRestorationKey(location, matches, basename, getKey);
1480 savedScrollPositions[key] = window.scrollY;
1481 }
1482 try {
1483 sessionStorage.setItem(
1484 storageKey || SCROLL_RESTORATION_STORAGE_KEY,
1485 JSON.stringify(savedScrollPositions)
1486 );
1487 } catch (error) {
1488 _chunk7OQROU2Djs.warning.call(void 0,
1489 false,
1490 `Failed to save scroll positions in sessionStorage, <ScrollRestoration /> will not work properly (${error}).`
1491 );
1492 }
1493 window.history.scrollRestoration = "auto";
1494 }, [navigation.state, getKey, basename, location, matches, storageKey])
1495 );
1496 if (typeof document !== "undefined") {
1497 React2.useLayoutEffect(() => {
1498 try {
1499 let sessionPositions = sessionStorage.getItem(
1500 storageKey || SCROLL_RESTORATION_STORAGE_KEY
1501 );
1502 if (sessionPositions) {
1503 savedScrollPositions = JSON.parse(sessionPositions);
1504 }
1505 } catch (e) {
1506 }
1507 }, [storageKey]);
1508 React2.useLayoutEffect(() => {
1509 let disableScrollRestoration = _optionalChain([router, 'optionalAccess', _35 => _35.enableScrollRestoration, 'call', _36 => _36(
1510 savedScrollPositions,
1511 () => window.scrollY,
1512 getKey ? (location2, matches2) => getScrollRestorationKey(location2, matches2, basename, getKey) : void 0
1513 )]);
1514 return () => disableScrollRestoration && disableScrollRestoration();
1515 }, [router, basename, getKey]);
1516 React2.useLayoutEffect(() => {
1517 if (restoreScrollPosition === false) {
1518 return;
1519 }
1520 if (typeof restoreScrollPosition === "number") {
1521 window.scrollTo(0, restoreScrollPosition);
1522 return;
1523 }
1524 try {
1525 if (location.hash) {
1526 let el = document.getElementById(
1527 decodeURIComponent(location.hash.slice(1))
1528 );
1529 if (el) {
1530 el.scrollIntoView();
1531 return;
1532 }
1533 }
1534 } catch (e2) {
1535 _chunk7OQROU2Djs.warning.call(void 0,
1536 false,
1537 `"${location.hash.slice(
1538 1
1539 )}" is not a decodable element ID. The view will not scroll to it.`
1540 );
1541 }
1542 if (preventScrollReset === true) {
1543 return;
1544 }
1545 window.scrollTo(0, 0);
1546 }, [location, restoreScrollPosition, preventScrollReset]);
1547 }
1548}
1549function useBeforeUnload(callback, options) {
1550 let { capture } = options || {};
1551 React2.useEffect(() => {
1552 let opts = capture != null ? { capture } : void 0;
1553 window.addEventListener("beforeunload", callback, opts);
1554 return () => {
1555 window.removeEventListener("beforeunload", callback, opts);
1556 };
1557 }, [callback, capture]);
1558}
1559function usePageHide(callback, options) {
1560 let { capture } = options || {};
1561 React2.useEffect(() => {
1562 let opts = capture != null ? { capture } : void 0;
1563 window.addEventListener("pagehide", callback, opts);
1564 return () => {
1565 window.removeEventListener("pagehide", callback, opts);
1566 };
1567 }, [callback, capture]);
1568}
1569function usePrompt({
1570 when,
1571 message
1572}) {
1573 let blocker = _chunk7OQROU2Djs.useBlocker.call(void 0, when);
1574 React2.useEffect(() => {
1575 if (blocker.state === "blocked") {
1576 let proceed = window.confirm(message);
1577 if (proceed) {
1578 setTimeout(blocker.proceed, 0);
1579 } else {
1580 blocker.reset();
1581 }
1582 }
1583 }, [blocker, message]);
1584 React2.useEffect(() => {
1585 if (blocker.state === "blocked" && !when) {
1586 blocker.reset();
1587 }
1588 }, [blocker, when]);
1589}
1590function useViewTransitionState(to, { relative } = {}) {
1591 let vtContext = React2.useContext(_chunk7OQROU2Djs.ViewTransitionContext);
1592 _chunk7OQROU2Djs.invariant.call(void 0,
1593 vtContext != null,
1594 "`useViewTransitionState` must be used within `react-router-dom`'s `RouterProvider`. Did you accidentally import `RouterProvider` from `react-router`?"
1595 );
1596 let { basename } = useDataRouterContext(
1597 "useViewTransitionState" /* useViewTransitionState */
1598 );
1599 let path = _chunk7OQROU2Djs.useResolvedPath.call(void 0, to, { relative });
1600 if (!vtContext.isTransitioning) {
1601 return false;
1602 }
1603 let currentPath = _chunk7OQROU2Djs.stripBasename.call(void 0, vtContext.currentLocation.pathname, basename) || vtContext.currentLocation.pathname;
1604 let nextPath = _chunk7OQROU2Djs.stripBasename.call(void 0, vtContext.nextLocation.pathname, basename) || vtContext.nextLocation.pathname;
1605 return _chunk7OQROU2Djs.matchPath.call(void 0, path.pathname, nextPath) != null || _chunk7OQROU2Djs.matchPath.call(void 0, path.pathname, currentPath) != null;
1606}
1607
1608// lib/dom/server.tsx
1609
1610function StaticRouter({
1611 basename,
1612 children,
1613 location: locationProp = "/"
1614}) {
1615 if (typeof locationProp === "string") {
1616 locationProp = _chunk7OQROU2Djs.parsePath.call(void 0, locationProp);
1617 }
1618 let action = "POP" /* Pop */;
1619 let location = {
1620 pathname: locationProp.pathname || "/",
1621 search: locationProp.search || "",
1622 hash: locationProp.hash || "",
1623 state: locationProp.state != null ? locationProp.state : null,
1624 key: locationProp.key || "default"
1625 };
1626 let staticNavigator = getStatelessNavigator();
1627 return /* @__PURE__ */ React3.createElement(
1628 Router,
1629 {
1630 basename,
1631 children,
1632 location,
1633 navigationType: action,
1634 navigator: staticNavigator,
1635 static: true
1636 }
1637 );
1638}
1639function StaticRouterProvider({
1640 context,
1641 router,
1642 hydrate = true,
1643 nonce
1644}) {
1645 _chunk7OQROU2Djs.invariant.call(void 0,
1646 router && context,
1647 "You must provide `router` and `context` to <StaticRouterProvider>"
1648 );
1649 let dataRouterContext = {
1650 router,
1651 navigator: getStatelessNavigator(),
1652 static: true,
1653 staticContext: context,
1654 basename: context.basename || "/"
1655 };
1656 let fetchersContext = /* @__PURE__ */ new Map();
1657 let hydrateScript = "";
1658 if (hydrate !== false) {
1659 let data = {
1660 loaderData: context.loaderData,
1661 actionData: context.actionData,
1662 errors: serializeErrors(context.errors)
1663 };
1664 let json = htmlEscape(JSON.stringify(JSON.stringify(data)));
1665 hydrateScript = `window.__staticRouterHydrationData = JSON.parse(${json});`;
1666 }
1667 let { state } = dataRouterContext.router;
1668 return /* @__PURE__ */ React3.createElement(React3.Fragment, null, /* @__PURE__ */ React3.createElement(_chunk7OQROU2Djs.DataRouterContext.Provider, { value: dataRouterContext }, /* @__PURE__ */ React3.createElement(_chunk7OQROU2Djs.DataRouterStateContext.Provider, { value: state }, /* @__PURE__ */ React3.createElement(_chunk7OQROU2Djs.FetchersContext.Provider, { value: fetchersContext }, /* @__PURE__ */ React3.createElement(_chunk7OQROU2Djs.ViewTransitionContext.Provider, { value: { isTransitioning: false } }, /* @__PURE__ */ React3.createElement(
1669 Router,
1670 {
1671 basename: dataRouterContext.basename,
1672 location: state.location,
1673 navigationType: state.historyAction,
1674 navigator: dataRouterContext.navigator,
1675 static: dataRouterContext.static
1676 },
1677 /* @__PURE__ */ React3.createElement(
1678 DataRoutes2,
1679 {
1680 routes: router.routes,
1681 future: router.future,
1682 state
1683 }
1684 )
1685 ))))), hydrateScript ? /* @__PURE__ */ React3.createElement(
1686 "script",
1687 {
1688 suppressHydrationWarning: true,
1689 nonce,
1690 dangerouslySetInnerHTML: { __html: hydrateScript }
1691 }
1692 ) : null);
1693}
1694function DataRoutes2({
1695 routes,
1696 future,
1697 state
1698}) {
1699 return _chunk7OQROU2Djs.useRoutesImpl.call(void 0, routes, void 0, state, future);
1700}
1701function serializeErrors(errors) {
1702 if (!errors) return null;
1703 let entries = Object.entries(errors);
1704 let serialized = {};
1705 for (let [key, val] of entries) {
1706 if (_chunk7OQROU2Djs.isRouteErrorResponse.call(void 0, val)) {
1707 serialized[key] = { ...val, __type: "RouteErrorResponse" };
1708 } else if (val instanceof Error) {
1709 serialized[key] = {
1710 message: val.message,
1711 __type: "Error",
1712 // If this is a subclass (i.e., ReferenceError), send up the type so we
1713 // can re-create the same type during hydration.
1714 ...val.name !== "Error" ? {
1715 __subType: val.name
1716 } : {}
1717 };
1718 } else {
1719 serialized[key] = val;
1720 }
1721 }
1722 return serialized;
1723}
1724function getStatelessNavigator() {
1725 return {
1726 createHref,
1727 encodeLocation,
1728 push(to) {
1729 throw new Error(
1730 `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.`
1731 );
1732 },
1733 replace(to) {
1734 throw new Error(
1735 `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.`
1736 );
1737 },
1738 go(delta) {
1739 throw new Error(
1740 `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.`
1741 );
1742 },
1743 back() {
1744 throw new Error(
1745 `You cannot use navigator.back() on the server because it is a stateless environment.`
1746 );
1747 },
1748 forward() {
1749 throw new Error(
1750 `You cannot use navigator.forward() on the server because it is a stateless environment.`
1751 );
1752 }
1753 };
1754}
1755function createStaticHandler2(routes, opts) {
1756 return _chunk7OQROU2Djs.createStaticHandler.call(void 0, routes, {
1757 ...opts,
1758 mapRouteProperties
1759 });
1760}
1761function createStaticRouter(routes, context, opts = {}) {
1762 let manifest = {};
1763 let dataRoutes = _chunk7OQROU2Djs.convertRoutesToDataRoutes.call(void 0,
1764 routes,
1765 mapRouteProperties,
1766 void 0,
1767 manifest
1768 );
1769 let matches = context.matches.map((match) => {
1770 let route = manifest[match.route.id] || match.route;
1771 return {
1772 ...match,
1773 route
1774 };
1775 });
1776 let msg = (method) => `You cannot use router.${method}() on the server because it is a stateless environment`;
1777 return {
1778 get basename() {
1779 return context.basename;
1780 },
1781 get future() {
1782 return {
1783 unstable_middleware: false,
1784 ..._optionalChain([opts, 'optionalAccess', _37 => _37.future])
1785 };
1786 },
1787 get state() {
1788 return {
1789 historyAction: "POP" /* Pop */,
1790 location: context.location,
1791 matches,
1792 loaderData: context.loaderData,
1793 actionData: context.actionData,
1794 errors: context.errors,
1795 initialized: true,
1796 navigation: _chunk7OQROU2Djs.IDLE_NAVIGATION,
1797 restoreScrollPosition: null,
1798 preventScrollReset: false,
1799 revalidation: "idle",
1800 fetchers: /* @__PURE__ */ new Map(),
1801 blockers: /* @__PURE__ */ new Map()
1802 };
1803 },
1804 get routes() {
1805 return dataRoutes;
1806 },
1807 get window() {
1808 return void 0;
1809 },
1810 initialize() {
1811 throw msg("initialize");
1812 },
1813 subscribe() {
1814 throw msg("subscribe");
1815 },
1816 enableScrollRestoration() {
1817 throw msg("enableScrollRestoration");
1818 },
1819 navigate() {
1820 throw msg("navigate");
1821 },
1822 fetch() {
1823 throw msg("fetch");
1824 },
1825 revalidate() {
1826 throw msg("revalidate");
1827 },
1828 createHref,
1829 encodeLocation,
1830 getFetcher() {
1831 return _chunk7OQROU2Djs.IDLE_FETCHER;
1832 },
1833 deleteFetcher() {
1834 throw msg("deleteFetcher");
1835 },
1836 dispose() {
1837 throw msg("dispose");
1838 },
1839 getBlocker() {
1840 return _chunk7OQROU2Djs.IDLE_BLOCKER;
1841 },
1842 deleteBlocker() {
1843 throw msg("deleteBlocker");
1844 },
1845 patchRoutes() {
1846 throw msg("patchRoutes");
1847 },
1848 _internalFetchControllers: /* @__PURE__ */ new Map(),
1849 _internalSetRoutes() {
1850 throw msg("_internalSetRoutes");
1851 },
1852 _internalSetStateDoNotUseOrYouWillBreakYourApp() {
1853 throw msg("_internalSetStateDoNotUseOrYouWillBreakYourApp");
1854 }
1855 };
1856}
1857function createHref(to) {
1858 return typeof to === "string" ? to : _chunk7OQROU2Djs.createPath.call(void 0, to);
1859}
1860function encodeLocation(to) {
1861 let href = typeof to === "string" ? to : _chunk7OQROU2Djs.createPath.call(void 0, to);
1862 href = href.replace(/ $/, "%20");
1863 let encoded = ABSOLUTE_URL_REGEX2.test(href) ? new URL(href) : new URL(href, "http://localhost");
1864 return {
1865 pathname: encoded.pathname,
1866 search: encoded.search,
1867 hash: encoded.hash
1868 };
1869}
1870var ABSOLUTE_URL_REGEX2 = /^(?:[a-z][a-z0-9+.-]*:|\/\/)/i;
1871var ESCAPE_LOOKUP = {
1872 "&": "\\u0026",
1873 ">": "\\u003e",
1874 "<": "\\u003c",
1875 "\u2028": "\\u2028",
1876 "\u2029": "\\u2029"
1877};
1878var ESCAPE_REGEX = /[&><\u2028\u2029]/g;
1879function htmlEscape(str) {
1880 return str.replace(ESCAPE_REGEX, (match) => ESCAPE_LOOKUP[match]);
1881}
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928exports.mapRouteProperties = mapRouteProperties; exports.hydrationRouteProperties = hydrationRouteProperties; exports.createMemoryRouter = createMemoryRouter; exports.RouterProvider = RouterProvider; exports.MemoryRouter = MemoryRouter; exports.Navigate = Navigate; exports.Outlet = Outlet; exports.Route = Route; exports.Router = Router; exports.Routes = Routes; exports.Await = Await; exports.createRoutesFromChildren = createRoutesFromChildren; exports.createRoutesFromElements = createRoutesFromElements; exports.renderMatches = renderMatches; exports.WithComponentProps = WithComponentProps; exports.withComponentProps = withComponentProps; exports.WithHydrateFallbackProps = WithHydrateFallbackProps; exports.withHydrateFallbackProps = withHydrateFallbackProps; exports.WithErrorBoundaryProps = WithErrorBoundaryProps; exports.withErrorBoundaryProps = withErrorBoundaryProps; exports.createSearchParams = createSearchParams; exports.createBrowserRouter = createBrowserRouter; exports.createHashRouter = createHashRouter; exports.BrowserRouter = BrowserRouter; exports.HashRouter = HashRouter; exports.HistoryRouter = HistoryRouter; exports.Link = Link; exports.NavLink = NavLink; exports.Form = Form; exports.ScrollRestoration = ScrollRestoration; exports.useLinkClickHandler = useLinkClickHandler; exports.useSearchParams = useSearchParams; exports.useSubmit = useSubmit; exports.useFormAction = useFormAction; exports.useFetcher = useFetcher; exports.useFetchers = useFetchers; exports.useScrollRestoration = useScrollRestoration; exports.useBeforeUnload = useBeforeUnload; exports.usePrompt = usePrompt; exports.useViewTransitionState = useViewTransitionState; exports.StaticRouter = StaticRouter; exports.StaticRouterProvider = StaticRouterProvider; exports.createStaticHandler = createStaticHandler2; exports.createStaticRouter = createStaticRouter;