source: imaps-frontend/node_modules/react-router-dom/dist/umd/react-router-dom.development.js@ 0c6b92a

main
Last change on this file since 0c6b92a was 0c6b92a, checked in by stefan toskovski <stefantoska84@…>, 5 weeks ago

Pred finalna verzija

  • Property mode set to 100644
File size: 67.6 KB
Line 
1/**
2 * React Router DOM v6.28.0
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(function (global, factory) {
12 typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('react'), require('react-dom'), require('react-router'), require('@remix-run/router')) :
13 typeof define === 'function' && define.amd ? define(['exports', 'react', 'react-dom', 'react-router', '@remix-run/router'], factory) :
14 (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.ReactRouterDOM = {}, global.React, global.ReactDOM, global.ReactRouter, global.RemixRouter));
15})(this, (function (exports, React, ReactDOM, reactRouter, router) { 'use strict';
16
17 function _interopNamespace(e) {
18 if (e && e.__esModule) return e;
19 var n = Object.create(null);
20 if (e) {
21 Object.keys(e).forEach(function (k) {
22 if (k !== 'default') {
23 var d = Object.getOwnPropertyDescriptor(e, k);
24 Object.defineProperty(n, k, d.get ? d : {
25 enumerable: true,
26 get: function () { return e[k]; }
27 });
28 }
29 });
30 }
31 n["default"] = e;
32 return Object.freeze(n);
33 }
34
35 var React__namespace = /*#__PURE__*/_interopNamespace(React);
36 var ReactDOM__namespace = /*#__PURE__*/_interopNamespace(ReactDOM);
37
38 function _extends() {
39 _extends = Object.assign ? Object.assign.bind() : function (target) {
40 for (var i = 1; i < arguments.length; i++) {
41 var source = arguments[i];
42 for (var key in source) {
43 if (Object.prototype.hasOwnProperty.call(source, key)) {
44 target[key] = source[key];
45 }
46 }
47 }
48 return target;
49 };
50 return _extends.apply(this, arguments);
51 }
52 function _objectWithoutPropertiesLoose(source, excluded) {
53 if (source == null) return {};
54 var target = {};
55 var sourceKeys = Object.keys(source);
56 var key, i;
57 for (i = 0; i < sourceKeys.length; i++) {
58 key = sourceKeys[i];
59 if (excluded.indexOf(key) >= 0) continue;
60 target[key] = source[key];
61 }
62 return target;
63 }
64
65 const defaultMethod = "get";
66 const defaultEncType = "application/x-www-form-urlencoded";
67 function isHtmlElement(object) {
68 return object != null && typeof object.tagName === "string";
69 }
70 function isButtonElement(object) {
71 return isHtmlElement(object) && object.tagName.toLowerCase() === "button";
72 }
73 function isFormElement(object) {
74 return isHtmlElement(object) && object.tagName.toLowerCase() === "form";
75 }
76 function isInputElement(object) {
77 return isHtmlElement(object) && object.tagName.toLowerCase() === "input";
78 }
79 function isModifiedEvent(event) {
80 return !!(event.metaKey || event.altKey || event.ctrlKey || event.shiftKey);
81 }
82 function shouldProcessLinkClick(event, target) {
83 return event.button === 0 && (
84 // Ignore everything but left clicks
85 !target || target === "_self") &&
86 // Let browser handle "target=_blank" etc.
87 !isModifiedEvent(event) // Ignore clicks with modifier keys
88 ;
89 }
90
91 /**
92 * Creates a URLSearchParams object using the given initializer.
93 *
94 * This is identical to `new URLSearchParams(init)` except it also
95 * supports arrays as values in the object form of the initializer
96 * instead of just strings. This is convenient when you need multiple
97 * values for a given key, but don't want to use an array initializer.
98 *
99 * For example, instead of:
100 *
101 * let searchParams = new URLSearchParams([
102 * ['sort', 'name'],
103 * ['sort', 'price']
104 * ]);
105 *
106 * you can do:
107 *
108 * let searchParams = createSearchParams({
109 * sort: ['name', 'price']
110 * });
111 */
112 function createSearchParams(init) {
113 if (init === void 0) {
114 init = "";
115 }
116 return new URLSearchParams(typeof init === "string" || Array.isArray(init) || init instanceof URLSearchParams ? init : Object.keys(init).reduce((memo, key) => {
117 let value = init[key];
118 return memo.concat(Array.isArray(value) ? value.map(v => [key, v]) : [[key, value]]);
119 }, []));
120 }
121 function getSearchParamsForLocation(locationSearch, defaultSearchParams) {
122 let searchParams = createSearchParams(locationSearch);
123 if (defaultSearchParams) {
124 // Use `defaultSearchParams.forEach(...)` here instead of iterating of
125 // `defaultSearchParams.keys()` to work-around a bug in Firefox related to
126 // web extensions. Relevant Bugzilla tickets:
127 // https://bugzilla.mozilla.org/show_bug.cgi?id=1414602
128 // https://bugzilla.mozilla.org/show_bug.cgi?id=1023984
129 defaultSearchParams.forEach((_, key) => {
130 if (!searchParams.has(key)) {
131 defaultSearchParams.getAll(key).forEach(value => {
132 searchParams.append(key, value);
133 });
134 }
135 });
136 }
137 return searchParams;
138 }
139
140 // Thanks https://github.com/sindresorhus/type-fest!
141
142 // One-time check for submitter support
143 let _formDataSupportsSubmitter = null;
144 function isFormDataSubmitterSupported() {
145 if (_formDataSupportsSubmitter === null) {
146 try {
147 new FormData(document.createElement("form"),
148 // @ts-expect-error if FormData supports the submitter parameter, this will throw
149 0);
150 _formDataSupportsSubmitter = false;
151 } catch (e) {
152 _formDataSupportsSubmitter = true;
153 }
154 }
155 return _formDataSupportsSubmitter;
156 }
157
158 /**
159 * Submit options shared by both navigations and fetchers
160 */
161
162 /**
163 * Submit options available to fetchers
164 */
165
166 /**
167 * Submit options available to navigations
168 */
169
170 const supportedFormEncTypes = new Set(["application/x-www-form-urlencoded", "multipart/form-data", "text/plain"]);
171 function getFormEncType(encType) {
172 if (encType != null && !supportedFormEncTypes.has(encType)) {
173 router.UNSAFE_warning(false, "\"" + encType + "\" is not a valid `encType` for `<Form>`/`<fetcher.Form>` " + ("and will default to \"" + defaultEncType + "\"")) ;
174 return null;
175 }
176 return encType;
177 }
178 function getFormSubmissionInfo(target, basename) {
179 let method;
180 let action;
181 let encType;
182 let formData;
183 let body;
184 if (isFormElement(target)) {
185 // When grabbing the action from the element, it will have had the basename
186 // prefixed to ensure non-JS scenarios work, so strip it since we'll
187 // re-prefix in the router
188 let attr = target.getAttribute("action");
189 action = attr ? router.stripBasename(attr, basename) : null;
190 method = target.getAttribute("method") || defaultMethod;
191 encType = getFormEncType(target.getAttribute("enctype")) || defaultEncType;
192 formData = new FormData(target);
193 } else if (isButtonElement(target) || isInputElement(target) && (target.type === "submit" || target.type === "image")) {
194 let form = target.form;
195 if (form == null) {
196 throw new Error("Cannot submit a <button> or <input type=\"submit\"> without a <form>");
197 }
198
199 // <button>/<input type="submit"> may override attributes of <form>
200
201 // When grabbing the action from the element, it will have had the basename
202 // prefixed to ensure non-JS scenarios work, so strip it since we'll
203 // re-prefix in the router
204 let attr = target.getAttribute("formaction") || form.getAttribute("action");
205 action = attr ? router.stripBasename(attr, basename) : null;
206 method = target.getAttribute("formmethod") || form.getAttribute("method") || defaultMethod;
207 encType = getFormEncType(target.getAttribute("formenctype")) || getFormEncType(form.getAttribute("enctype")) || defaultEncType;
208
209 // Build a FormData object populated from a form and submitter
210 formData = new FormData(form, target);
211
212 // If this browser doesn't support the `FormData(el, submitter)` format,
213 // then tack on the submitter value at the end. This is a lightweight
214 // solution that is not 100% spec compliant. For complete support in older
215 // browsers, consider using the `formdata-submitter-polyfill` package
216 if (!isFormDataSubmitterSupported()) {
217 let {
218 name,
219 type,
220 value
221 } = target;
222 if (type === "image") {
223 let prefix = name ? name + "." : "";
224 formData.append(prefix + "x", "0");
225 formData.append(prefix + "y", "0");
226 } else if (name) {
227 formData.append(name, value);
228 }
229 }
230 } else if (isHtmlElement(target)) {
231 throw new Error("Cannot submit element that is not <form>, <button>, or " + "<input type=\"submit|image\">");
232 } else {
233 method = defaultMethod;
234 action = null;
235 encType = defaultEncType;
236 body = target;
237 }
238
239 // Send body for <Form encType="text/plain" so we encode it into text
240 if (formData && encType === "text/plain") {
241 body = formData;
242 formData = undefined;
243 }
244 return {
245 action,
246 method: method.toLowerCase(),
247 encType,
248 formData,
249 body
250 };
251 }
252
253 const _excluded = ["onClick", "relative", "reloadDocument", "replace", "state", "target", "to", "preventScrollReset", "viewTransition"],
254 _excluded2 = ["aria-current", "caseSensitive", "className", "end", "style", "to", "viewTransition", "children"],
255 _excluded3 = ["fetcherKey", "navigate", "reloadDocument", "replace", "state", "method", "action", "onSubmit", "relative", "preventScrollReset", "viewTransition"];
256 //#endregion
257 // HEY YOU! DON'T TOUCH THIS VARIABLE!
258 //
259 // It is replaced with the proper version at build time via a babel plugin in
260 // the rollup config.
261 //
262 // Export a global property onto the window for React Router detection by the
263 // Core Web Vitals Technology Report. This way they can configure the `wappalyzer`
264 // to detect and properly classify live websites as being built with React Router:
265 // https://github.com/HTTPArchive/wappalyzer/blob/main/src/technologies/r.json
266 const REACT_ROUTER_VERSION = "6";
267 try {
268 window.__reactRouterVersion = REACT_ROUTER_VERSION;
269 } catch (e) {
270 // no-op
271 }
272
273 ////////////////////////////////////////////////////////////////////////////////
274 //#region Routers
275 ////////////////////////////////////////////////////////////////////////////////
276 function createBrowserRouter(routes, opts) {
277 return router.createRouter({
278 basename: opts == null ? void 0 : opts.basename,
279 future: _extends({}, opts == null ? void 0 : opts.future, {
280 v7_prependBasename: true
281 }),
282 history: router.createBrowserHistory({
283 window: opts == null ? void 0 : opts.window
284 }),
285 hydrationData: (opts == null ? void 0 : opts.hydrationData) || parseHydrationData(),
286 routes,
287 mapRouteProperties: reactRouter.UNSAFE_mapRouteProperties,
288 dataStrategy: opts == null ? void 0 : opts.dataStrategy,
289 patchRoutesOnNavigation: opts == null ? void 0 : opts.patchRoutesOnNavigation,
290 window: opts == null ? void 0 : opts.window
291 }).initialize();
292 }
293 function createHashRouter(routes, opts) {
294 return router.createRouter({
295 basename: opts == null ? void 0 : opts.basename,
296 future: _extends({}, opts == null ? void 0 : opts.future, {
297 v7_prependBasename: true
298 }),
299 history: router.createHashHistory({
300 window: opts == null ? void 0 : opts.window
301 }),
302 hydrationData: (opts == null ? void 0 : opts.hydrationData) || parseHydrationData(),
303 routes,
304 mapRouteProperties: reactRouter.UNSAFE_mapRouteProperties,
305 dataStrategy: opts == null ? void 0 : opts.dataStrategy,
306 patchRoutesOnNavigation: opts == null ? void 0 : opts.patchRoutesOnNavigation,
307 window: opts == null ? void 0 : opts.window
308 }).initialize();
309 }
310 function parseHydrationData() {
311 var _window;
312 let state = (_window = window) == null ? void 0 : _window.__staticRouterHydrationData;
313 if (state && state.errors) {
314 state = _extends({}, state, {
315 errors: deserializeErrors(state.errors)
316 });
317 }
318 return state;
319 }
320 function deserializeErrors(errors) {
321 if (!errors) return null;
322 let entries = Object.entries(errors);
323 let serialized = {};
324 for (let [key, val] of entries) {
325 // Hey you! If you change this, please change the corresponding logic in
326 // serializeErrors in react-router-dom/server.tsx :)
327 if (val && val.__type === "RouteErrorResponse") {
328 serialized[key] = new router.UNSAFE_ErrorResponseImpl(val.status, val.statusText, val.data, val.internal === true);
329 } else if (val && val.__type === "Error") {
330 // Attempt to reconstruct the right type of Error (i.e., ReferenceError)
331 if (val.__subType) {
332 let ErrorConstructor = window[val.__subType];
333 if (typeof ErrorConstructor === "function") {
334 try {
335 // @ts-expect-error
336 let error = new ErrorConstructor(val.message);
337 // Wipe away the client-side stack trace. Nothing to fill it in with
338 // because we don't serialize SSR stack traces for security reasons
339 error.stack = "";
340 serialized[key] = error;
341 } catch (e) {
342 // no-op - fall through and create a normal Error
343 }
344 }
345 }
346 if (serialized[key] == null) {
347 let error = new Error(val.message);
348 // Wipe away the client-side stack trace. Nothing to fill it in with
349 // because we don't serialize SSR stack traces for security reasons
350 error.stack = "";
351 serialized[key] = error;
352 }
353 } else {
354 serialized[key] = val;
355 }
356 }
357 return serialized;
358 }
359
360 //#endregion
361
362 ////////////////////////////////////////////////////////////////////////////////
363 //#region Contexts
364 ////////////////////////////////////////////////////////////////////////////////
365 const ViewTransitionContext = /*#__PURE__*/React__namespace.createContext({
366 isTransitioning: false
367 });
368 {
369 ViewTransitionContext.displayName = "ViewTransition";
370 }
371
372 // TODO: (v7) Change the useFetcher data from `any` to `unknown`
373
374 const FetchersContext = /*#__PURE__*/React__namespace.createContext(new Map());
375 {
376 FetchersContext.displayName = "Fetchers";
377 }
378
379 //#endregion
380
381 ////////////////////////////////////////////////////////////////////////////////
382 //#region Components
383 ////////////////////////////////////////////////////////////////////////////////
384
385 /**
386 Webpack + React 17 fails to compile on any of the following because webpack
387 complains that `startTransition` doesn't exist in `React`:
388 * import { startTransition } from "react"
389 * import * as React from from "react";
390 "startTransition" in React ? React.startTransition(() => setState()) : setState()
391 * import * as React from from "react";
392 "startTransition" in React ? React["startTransition"](() => setState()) : setState()
393
394 Moving it to a constant such as the following solves the Webpack/React 17 issue:
395 * import * as React from from "react";
396 const START_TRANSITION = "startTransition";
397 START_TRANSITION in React ? React[START_TRANSITION](() => setState()) : setState()
398
399 However, that introduces webpack/terser minification issues in production builds
400 in React 18 where minification/obfuscation ends up removing the call of
401 React.startTransition entirely from the first half of the ternary. Grabbing
402 this exported reference once up front resolves that issue.
403
404 See https://github.com/remix-run/react-router/issues/10579
405 */
406 const START_TRANSITION = "startTransition";
407 const startTransitionImpl = React__namespace[START_TRANSITION];
408 const FLUSH_SYNC = "flushSync";
409 const flushSyncImpl = ReactDOM__namespace[FLUSH_SYNC];
410 const USE_ID = "useId";
411 const useIdImpl = React__namespace[USE_ID];
412 function startTransitionSafe(cb) {
413 if (startTransitionImpl) {
414 startTransitionImpl(cb);
415 } else {
416 cb();
417 }
418 }
419 function flushSyncSafe(cb) {
420 if (flushSyncImpl) {
421 flushSyncImpl(cb);
422 } else {
423 cb();
424 }
425 }
426 class Deferred {
427 // @ts-expect-error - no initializer
428
429 // @ts-expect-error - no initializer
430
431 constructor() {
432 this.status = "pending";
433 this.promise = new Promise((resolve, reject) => {
434 this.resolve = value => {
435 if (this.status === "pending") {
436 this.status = "resolved";
437 resolve(value);
438 }
439 };
440 this.reject = reason => {
441 if (this.status === "pending") {
442 this.status = "rejected";
443 reject(reason);
444 }
445 };
446 });
447 }
448 }
449
450 /**
451 * Given a Remix Router instance, render the appropriate UI
452 */
453 function RouterProvider(_ref) {
454 let {
455 fallbackElement,
456 router: router$1,
457 future
458 } = _ref;
459 let [state, setStateImpl] = React__namespace.useState(router$1.state);
460 let [pendingState, setPendingState] = React__namespace.useState();
461 let [vtContext, setVtContext] = React__namespace.useState({
462 isTransitioning: false
463 });
464 let [renderDfd, setRenderDfd] = React__namespace.useState();
465 let [transition, setTransition] = React__namespace.useState();
466 let [interruption, setInterruption] = React__namespace.useState();
467 let fetcherData = React__namespace.useRef(new Map());
468 let {
469 v7_startTransition
470 } = future || {};
471 let optInStartTransition = React__namespace.useCallback(cb => {
472 if (v7_startTransition) {
473 startTransitionSafe(cb);
474 } else {
475 cb();
476 }
477 }, [v7_startTransition]);
478 let setState = React__namespace.useCallback((newState, _ref2) => {
479 let {
480 deletedFetchers,
481 flushSync: flushSync,
482 viewTransitionOpts: viewTransitionOpts
483 } = _ref2;
484 deletedFetchers.forEach(key => fetcherData.current.delete(key));
485 newState.fetchers.forEach((fetcher, key) => {
486 if (fetcher.data !== undefined) {
487 fetcherData.current.set(key, fetcher.data);
488 }
489 });
490 let isViewTransitionUnavailable = router$1.window == null || router$1.window.document == null || typeof router$1.window.document.startViewTransition !== "function";
491
492 // If this isn't a view transition or it's not available in this browser,
493 // just update and be done with it
494 if (!viewTransitionOpts || isViewTransitionUnavailable) {
495 if (flushSync) {
496 flushSyncSafe(() => setStateImpl(newState));
497 } else {
498 optInStartTransition(() => setStateImpl(newState));
499 }
500 return;
501 }
502
503 // flushSync + startViewTransition
504 if (flushSync) {
505 // Flush through the context to mark DOM elements as transition=ing
506 flushSyncSafe(() => {
507 // Cancel any pending transitions
508 if (transition) {
509 renderDfd && renderDfd.resolve();
510 transition.skipTransition();
511 }
512 setVtContext({
513 isTransitioning: true,
514 flushSync: true,
515 currentLocation: viewTransitionOpts.currentLocation,
516 nextLocation: viewTransitionOpts.nextLocation
517 });
518 });
519
520 // Update the DOM
521 let t = router$1.window.document.startViewTransition(() => {
522 flushSyncSafe(() => setStateImpl(newState));
523 });
524
525 // Clean up after the animation completes
526 t.finished.finally(() => {
527 flushSyncSafe(() => {
528 setRenderDfd(undefined);
529 setTransition(undefined);
530 setPendingState(undefined);
531 setVtContext({
532 isTransitioning: false
533 });
534 });
535 });
536 flushSyncSafe(() => setTransition(t));
537 return;
538 }
539
540 // startTransition + startViewTransition
541 if (transition) {
542 // Interrupting an in-progress transition, cancel and let everything flush
543 // out, and then kick off a new transition from the interruption state
544 renderDfd && renderDfd.resolve();
545 transition.skipTransition();
546 setInterruption({
547 state: newState,
548 currentLocation: viewTransitionOpts.currentLocation,
549 nextLocation: viewTransitionOpts.nextLocation
550 });
551 } else {
552 // Completed navigation update with opted-in view transitions, let 'er rip
553 setPendingState(newState);
554 setVtContext({
555 isTransitioning: true,
556 flushSync: false,
557 currentLocation: viewTransitionOpts.currentLocation,
558 nextLocation: viewTransitionOpts.nextLocation
559 });
560 }
561 }, [router$1.window, transition, renderDfd, fetcherData, optInStartTransition]);
562
563 // Need to use a layout effect here so we are subscribed early enough to
564 // pick up on any render-driven redirects/navigations (useEffect/<Navigate>)
565 React__namespace.useLayoutEffect(() => router$1.subscribe(setState), [router$1, setState]);
566
567 // When we start a view transition, create a Deferred we can use for the
568 // eventual "completed" render
569 React__namespace.useEffect(() => {
570 if (vtContext.isTransitioning && !vtContext.flushSync) {
571 setRenderDfd(new Deferred());
572 }
573 }, [vtContext]);
574
575 // Once the deferred is created, kick off startViewTransition() to update the
576 // DOM and then wait on the Deferred to resolve (indicating the DOM update has
577 // happened)
578 React__namespace.useEffect(() => {
579 if (renderDfd && pendingState && router$1.window) {
580 let newState = pendingState;
581 let renderPromise = renderDfd.promise;
582 let transition = router$1.window.document.startViewTransition(async () => {
583 optInStartTransition(() => setStateImpl(newState));
584 await renderPromise;
585 });
586 transition.finished.finally(() => {
587 setRenderDfd(undefined);
588 setTransition(undefined);
589 setPendingState(undefined);
590 setVtContext({
591 isTransitioning: false
592 });
593 });
594 setTransition(transition);
595 }
596 }, [optInStartTransition, pendingState, renderDfd, router$1.window]);
597
598 // When the new location finally renders and is committed to the DOM, this
599 // effect will run to resolve the transition
600 React__namespace.useEffect(() => {
601 if (renderDfd && pendingState && state.location.key === pendingState.location.key) {
602 renderDfd.resolve();
603 }
604 }, [renderDfd, transition, state.location, pendingState]);
605
606 // If we get interrupted with a new navigation during a transition, we skip
607 // the active transition, let it cleanup, then kick it off again here
608 React__namespace.useEffect(() => {
609 if (!vtContext.isTransitioning && interruption) {
610 setPendingState(interruption.state);
611 setVtContext({
612 isTransitioning: true,
613 flushSync: false,
614 currentLocation: interruption.currentLocation,
615 nextLocation: interruption.nextLocation
616 });
617 setInterruption(undefined);
618 }
619 }, [vtContext.isTransitioning, interruption]);
620 React__namespace.useEffect(() => {
621 router.UNSAFE_warning(fallbackElement == null || !router$1.future.v7_partialHydration, "`<RouterProvider fallbackElement>` is deprecated when using " + "`v7_partialHydration`, use a `HydrateFallback` component instead") ;
622 // Only log this once on initial mount
623 // eslint-disable-next-line react-hooks/exhaustive-deps
624 }, []);
625 let navigator = React__namespace.useMemo(() => {
626 return {
627 createHref: router$1.createHref,
628 encodeLocation: router$1.encodeLocation,
629 go: n => router$1.navigate(n),
630 push: (to, state, opts) => router$1.navigate(to, {
631 state,
632 preventScrollReset: opts == null ? void 0 : opts.preventScrollReset
633 }),
634 replace: (to, state, opts) => router$1.navigate(to, {
635 replace: true,
636 state,
637 preventScrollReset: opts == null ? void 0 : opts.preventScrollReset
638 })
639 };
640 }, [router$1]);
641 let basename = router$1.basename || "/";
642 let dataRouterContext = React__namespace.useMemo(() => ({
643 router: router$1,
644 navigator,
645 static: false,
646 basename
647 }), [router$1, navigator, basename]);
648 let routerFuture = React__namespace.useMemo(() => ({
649 v7_relativeSplatPath: router$1.future.v7_relativeSplatPath
650 }), [router$1.future.v7_relativeSplatPath]);
651 React__namespace.useEffect(() => reactRouter.UNSAFE_logV6DeprecationWarnings(future, router$1.future), [future, router$1.future]);
652
653 // The fragment and {null} here are important! We need them to keep React 18's
654 // useId happy when we are server-rendering since we may have a <script> here
655 // containing the hydrated server-side staticContext (from StaticRouterProvider).
656 // useId relies on the component tree structure to generate deterministic id's
657 // so we need to ensure it remains the same on the client even though
658 // we don't need the <script> tag
659 return /*#__PURE__*/React__namespace.createElement(React__namespace.Fragment, null, /*#__PURE__*/React__namespace.createElement(reactRouter.UNSAFE_DataRouterContext.Provider, {
660 value: dataRouterContext
661 }, /*#__PURE__*/React__namespace.createElement(reactRouter.UNSAFE_DataRouterStateContext.Provider, {
662 value: state
663 }, /*#__PURE__*/React__namespace.createElement(FetchersContext.Provider, {
664 value: fetcherData.current
665 }, /*#__PURE__*/React__namespace.createElement(ViewTransitionContext.Provider, {
666 value: vtContext
667 }, /*#__PURE__*/React__namespace.createElement(reactRouter.Router, {
668 basename: basename,
669 location: state.location,
670 navigationType: state.historyAction,
671 navigator: navigator,
672 future: routerFuture
673 }, state.initialized || router$1.future.v7_partialHydration ? /*#__PURE__*/React__namespace.createElement(MemoizedDataRoutes, {
674 routes: router$1.routes,
675 future: router$1.future,
676 state: state
677 }) : fallbackElement))))), null);
678 }
679
680 // Memoize to avoid re-renders when updating `ViewTransitionContext`
681 const MemoizedDataRoutes = /*#__PURE__*/React__namespace.memo(DataRoutes);
682 function DataRoutes(_ref3) {
683 let {
684 routes,
685 future,
686 state
687 } = _ref3;
688 return reactRouter.UNSAFE_useRoutesImpl(routes, undefined, state, future);
689 }
690 /**
691 * A `<Router>` for use in web browsers. Provides the cleanest URLs.
692 */
693 function BrowserRouter(_ref4) {
694 let {
695 basename,
696 children,
697 future,
698 window
699 } = _ref4;
700 let historyRef = React__namespace.useRef();
701 if (historyRef.current == null) {
702 historyRef.current = router.createBrowserHistory({
703 window,
704 v5Compat: true
705 });
706 }
707 let history = historyRef.current;
708 let [state, setStateImpl] = React__namespace.useState({
709 action: history.action,
710 location: history.location
711 });
712 let {
713 v7_startTransition
714 } = future || {};
715 let setState = React__namespace.useCallback(newState => {
716 v7_startTransition && startTransitionImpl ? startTransitionImpl(() => setStateImpl(newState)) : setStateImpl(newState);
717 }, [setStateImpl, v7_startTransition]);
718 React__namespace.useLayoutEffect(() => history.listen(setState), [history, setState]);
719 React__namespace.useEffect(() => reactRouter.UNSAFE_logV6DeprecationWarnings(future), [future]);
720 return /*#__PURE__*/React__namespace.createElement(reactRouter.Router, {
721 basename: basename,
722 children: children,
723 location: state.location,
724 navigationType: state.action,
725 navigator: history,
726 future: future
727 });
728 }
729 /**
730 * A `<Router>` for use in web browsers. Stores the location in the hash
731 * portion of the URL so it is not sent to the server.
732 */
733 function HashRouter(_ref5) {
734 let {
735 basename,
736 children,
737 future,
738 window
739 } = _ref5;
740 let historyRef = React__namespace.useRef();
741 if (historyRef.current == null) {
742 historyRef.current = router.createHashHistory({
743 window,
744 v5Compat: true
745 });
746 }
747 let history = historyRef.current;
748 let [state, setStateImpl] = React__namespace.useState({
749 action: history.action,
750 location: history.location
751 });
752 let {
753 v7_startTransition
754 } = future || {};
755 let setState = React__namespace.useCallback(newState => {
756 v7_startTransition && startTransitionImpl ? startTransitionImpl(() => setStateImpl(newState)) : setStateImpl(newState);
757 }, [setStateImpl, v7_startTransition]);
758 React__namespace.useLayoutEffect(() => history.listen(setState), [history, setState]);
759 React__namespace.useEffect(() => reactRouter.UNSAFE_logV6DeprecationWarnings(future), [future]);
760 return /*#__PURE__*/React__namespace.createElement(reactRouter.Router, {
761 basename: basename,
762 children: children,
763 location: state.location,
764 navigationType: state.action,
765 navigator: history,
766 future: future
767 });
768 }
769 /**
770 * A `<Router>` that accepts a pre-instantiated history object. It's important
771 * to note that using your own history object is highly discouraged and may add
772 * two versions of the history library to your bundles unless you use the same
773 * version of the history library that React Router uses internally.
774 */
775 function HistoryRouter(_ref6) {
776 let {
777 basename,
778 children,
779 future,
780 history
781 } = _ref6;
782 let [state, setStateImpl] = React__namespace.useState({
783 action: history.action,
784 location: history.location
785 });
786 let {
787 v7_startTransition
788 } = future || {};
789 let setState = React__namespace.useCallback(newState => {
790 v7_startTransition && startTransitionImpl ? startTransitionImpl(() => setStateImpl(newState)) : setStateImpl(newState);
791 }, [setStateImpl, v7_startTransition]);
792 React__namespace.useLayoutEffect(() => history.listen(setState), [history, setState]);
793 React__namespace.useEffect(() => reactRouter.UNSAFE_logV6DeprecationWarnings(future), [future]);
794 return /*#__PURE__*/React__namespace.createElement(reactRouter.Router, {
795 basename: basename,
796 children: children,
797 location: state.location,
798 navigationType: state.action,
799 navigator: history,
800 future: future
801 });
802 }
803 {
804 HistoryRouter.displayName = "unstable_HistoryRouter";
805 }
806 const isBrowser = typeof window !== "undefined" && typeof window.document !== "undefined" && typeof window.document.createElement !== "undefined";
807 const ABSOLUTE_URL_REGEX = /^(?:[a-z][a-z0-9+.-]*:|\/\/)/i;
808
809 /**
810 * The public API for rendering a history-aware `<a>`.
811 */
812 const Link = /*#__PURE__*/React__namespace.forwardRef(function LinkWithRef(_ref7, ref) {
813 let {
814 onClick,
815 relative,
816 reloadDocument,
817 replace,
818 state,
819 target,
820 to,
821 preventScrollReset,
822 viewTransition
823 } = _ref7,
824 rest = _objectWithoutPropertiesLoose(_ref7, _excluded);
825 let {
826 basename
827 } = React__namespace.useContext(reactRouter.UNSAFE_NavigationContext);
828
829 // Rendered into <a href> for absolute URLs
830 let absoluteHref;
831 let isExternal = false;
832 if (typeof to === "string" && ABSOLUTE_URL_REGEX.test(to)) {
833 // Render the absolute href server- and client-side
834 absoluteHref = to;
835
836 // Only check for external origins client-side
837 if (isBrowser) {
838 try {
839 let currentUrl = new URL(window.location.href);
840 let targetUrl = to.startsWith("//") ? new URL(currentUrl.protocol + to) : new URL(to);
841 let path = router.stripBasename(targetUrl.pathname, basename);
842 if (targetUrl.origin === currentUrl.origin && path != null) {
843 // Strip the protocol/origin/basename for same-origin absolute URLs
844 to = path + targetUrl.search + targetUrl.hash;
845 } else {
846 isExternal = true;
847 }
848 } catch (e) {
849 // We can't do external URL detection without a valid URL
850 router.UNSAFE_warning(false, "<Link to=\"" + to + "\"> contains an invalid URL which will probably break " + "when clicked - please update to a valid URL path.") ;
851 }
852 }
853 }
854
855 // Rendered into <a href> for relative URLs
856 let href = reactRouter.useHref(to, {
857 relative
858 });
859 let internalOnClick = useLinkClickHandler(to, {
860 replace,
861 state,
862 target,
863 preventScrollReset,
864 relative,
865 viewTransition
866 });
867 function handleClick(event) {
868 if (onClick) onClick(event);
869 if (!event.defaultPrevented) {
870 internalOnClick(event);
871 }
872 }
873 return (
874 /*#__PURE__*/
875 // eslint-disable-next-line jsx-a11y/anchor-has-content
876 React__namespace.createElement("a", _extends({}, rest, {
877 href: absoluteHref || href,
878 onClick: isExternal || reloadDocument ? onClick : handleClick,
879 ref: ref,
880 target: target
881 }))
882 );
883 });
884 {
885 Link.displayName = "Link";
886 }
887 /**
888 * A `<Link>` wrapper that knows if it's "active" or not.
889 */
890 const NavLink = /*#__PURE__*/React__namespace.forwardRef(function NavLinkWithRef(_ref8, ref) {
891 let {
892 "aria-current": ariaCurrentProp = "page",
893 caseSensitive = false,
894 className: classNameProp = "",
895 end = false,
896 style: styleProp,
897 to,
898 viewTransition,
899 children
900 } = _ref8,
901 rest = _objectWithoutPropertiesLoose(_ref8, _excluded2);
902 let path = reactRouter.useResolvedPath(to, {
903 relative: rest.relative
904 });
905 let location = reactRouter.useLocation();
906 let routerState = React__namespace.useContext(reactRouter.UNSAFE_DataRouterStateContext);
907 let {
908 navigator,
909 basename
910 } = React__namespace.useContext(reactRouter.UNSAFE_NavigationContext);
911 let isTransitioning = routerState != null &&
912 // Conditional usage is OK here because the usage of a data router is static
913 // eslint-disable-next-line react-hooks/rules-of-hooks
914 useViewTransitionState(path) && viewTransition === true;
915 let toPathname = navigator.encodeLocation ? navigator.encodeLocation(path).pathname : path.pathname;
916 let locationPathname = location.pathname;
917 let nextLocationPathname = routerState && routerState.navigation && routerState.navigation.location ? routerState.navigation.location.pathname : null;
918 if (!caseSensitive) {
919 locationPathname = locationPathname.toLowerCase();
920 nextLocationPathname = nextLocationPathname ? nextLocationPathname.toLowerCase() : null;
921 toPathname = toPathname.toLowerCase();
922 }
923 if (nextLocationPathname && basename) {
924 nextLocationPathname = router.stripBasename(nextLocationPathname, basename) || nextLocationPathname;
925 }
926
927 // If the `to` has a trailing slash, look at that exact spot. Otherwise,
928 // we're looking for a slash _after_ what's in `to`. For example:
929 //
930 // <NavLink to="/users"> and <NavLink to="/users/">
931 // both want to look for a / at index 6 to match URL `/users/matt`
932 const endSlashPosition = toPathname !== "/" && toPathname.endsWith("/") ? toPathname.length - 1 : toPathname.length;
933 let isActive = locationPathname === toPathname || !end && locationPathname.startsWith(toPathname) && locationPathname.charAt(endSlashPosition) === "/";
934 let isPending = nextLocationPathname != null && (nextLocationPathname === toPathname || !end && nextLocationPathname.startsWith(toPathname) && nextLocationPathname.charAt(toPathname.length) === "/");
935 let renderProps = {
936 isActive,
937 isPending,
938 isTransitioning
939 };
940 let ariaCurrent = isActive ? ariaCurrentProp : undefined;
941 let className;
942 if (typeof classNameProp === "function") {
943 className = classNameProp(renderProps);
944 } else {
945 // If the className prop is not a function, we use a default `active`
946 // class for <NavLink />s that are active. In v5 `active` was the default
947 // value for `activeClassName`, but we are removing that API and can still
948 // use the old default behavior for a cleaner upgrade path and keep the
949 // simple styling rules working as they currently do.
950 className = [classNameProp, isActive ? "active" : null, isPending ? "pending" : null, isTransitioning ? "transitioning" : null].filter(Boolean).join(" ");
951 }
952 let style = typeof styleProp === "function" ? styleProp(renderProps) : styleProp;
953 return /*#__PURE__*/React__namespace.createElement(Link, _extends({}, rest, {
954 "aria-current": ariaCurrent,
955 className: className,
956 ref: ref,
957 style: style,
958 to: to,
959 viewTransition: viewTransition
960 }), typeof children === "function" ? children(renderProps) : children);
961 });
962 {
963 NavLink.displayName = "NavLink";
964 }
965
966 /**
967 * Form props shared by navigations and fetchers
968 */
969
970 /**
971 * Form props available to fetchers
972 */
973
974 /**
975 * Form props available to navigations
976 */
977
978 /**
979 * A `@remix-run/router`-aware `<form>`. It behaves like a normal form except
980 * that the interaction with the server is with `fetch` instead of new document
981 * requests, allowing components to add nicer UX to the page as the form is
982 * submitted and returns with data.
983 */
984 const Form = /*#__PURE__*/React__namespace.forwardRef((_ref9, forwardedRef) => {
985 let {
986 fetcherKey,
987 navigate,
988 reloadDocument,
989 replace,
990 state,
991 method = defaultMethod,
992 action,
993 onSubmit,
994 relative,
995 preventScrollReset,
996 viewTransition
997 } = _ref9,
998 props = _objectWithoutPropertiesLoose(_ref9, _excluded3);
999 let submit = useSubmit();
1000 let formAction = useFormAction(action, {
1001 relative
1002 });
1003 let formMethod = method.toLowerCase() === "get" ? "get" : "post";
1004 let submitHandler = event => {
1005 onSubmit && onSubmit(event);
1006 if (event.defaultPrevented) return;
1007 event.preventDefault();
1008 let submitter = event.nativeEvent.submitter;
1009 let submitMethod = (submitter == null ? void 0 : submitter.getAttribute("formmethod")) || method;
1010 submit(submitter || event.currentTarget, {
1011 fetcherKey,
1012 method: submitMethod,
1013 navigate,
1014 replace,
1015 state,
1016 relative,
1017 preventScrollReset,
1018 viewTransition
1019 });
1020 };
1021 return /*#__PURE__*/React__namespace.createElement("form", _extends({
1022 ref: forwardedRef,
1023 method: formMethod,
1024 action: formAction,
1025 onSubmit: reloadDocument ? onSubmit : submitHandler
1026 }, props));
1027 });
1028 {
1029 Form.displayName = "Form";
1030 }
1031 /**
1032 * This component will emulate the browser's scroll restoration on location
1033 * changes.
1034 */
1035 function ScrollRestoration(_ref10) {
1036 let {
1037 getKey,
1038 storageKey
1039 } = _ref10;
1040 useScrollRestoration({
1041 getKey,
1042 storageKey
1043 });
1044 return null;
1045 }
1046 {
1047 ScrollRestoration.displayName = "ScrollRestoration";
1048 }
1049 //#endregion
1050
1051 ////////////////////////////////////////////////////////////////////////////////
1052 //#region Hooks
1053 ////////////////////////////////////////////////////////////////////////////////
1054 var DataRouterHook = /*#__PURE__*/function (DataRouterHook) {
1055 DataRouterHook["UseScrollRestoration"] = "useScrollRestoration";
1056 DataRouterHook["UseSubmit"] = "useSubmit";
1057 DataRouterHook["UseSubmitFetcher"] = "useSubmitFetcher";
1058 DataRouterHook["UseFetcher"] = "useFetcher";
1059 DataRouterHook["useViewTransitionState"] = "useViewTransitionState";
1060 return DataRouterHook;
1061 }(DataRouterHook || {});
1062 var DataRouterStateHook = /*#__PURE__*/function (DataRouterStateHook) {
1063 DataRouterStateHook["UseFetcher"] = "useFetcher";
1064 DataRouterStateHook["UseFetchers"] = "useFetchers";
1065 DataRouterStateHook["UseScrollRestoration"] = "useScrollRestoration";
1066 return DataRouterStateHook;
1067 }(DataRouterStateHook || {}); // Internal hooks
1068 function getDataRouterConsoleError(hookName) {
1069 return hookName + " must be used within a data router. See https://reactrouter.com/v6/routers/picking-a-router.";
1070 }
1071 function useDataRouterContext(hookName) {
1072 let ctx = React__namespace.useContext(reactRouter.UNSAFE_DataRouterContext);
1073 !ctx ? router.UNSAFE_invariant(false, getDataRouterConsoleError(hookName)) : void 0;
1074 return ctx;
1075 }
1076 function useDataRouterState(hookName) {
1077 let state = React__namespace.useContext(reactRouter.UNSAFE_DataRouterStateContext);
1078 !state ? router.UNSAFE_invariant(false, getDataRouterConsoleError(hookName)) : void 0;
1079 return state;
1080 }
1081
1082 // External hooks
1083
1084 /**
1085 * Handles the click behavior for router `<Link>` components. This is useful if
1086 * you need to create custom `<Link>` components with the same click behavior we
1087 * use in our exported `<Link>`.
1088 */
1089 function useLinkClickHandler(to, _temp) {
1090 let {
1091 target,
1092 replace: replaceProp,
1093 state,
1094 preventScrollReset,
1095 relative,
1096 viewTransition
1097 } = _temp === void 0 ? {} : _temp;
1098 let navigate = reactRouter.useNavigate();
1099 let location = reactRouter.useLocation();
1100 let path = reactRouter.useResolvedPath(to, {
1101 relative
1102 });
1103 return React__namespace.useCallback(event => {
1104 if (shouldProcessLinkClick(event, target)) {
1105 event.preventDefault();
1106
1107 // If the URL hasn't changed, a regular <a> will do a replace instead of
1108 // a push, so do the same here unless the replace prop is explicitly set
1109 let replace = replaceProp !== undefined ? replaceProp : reactRouter.createPath(location) === reactRouter.createPath(path);
1110 navigate(to, {
1111 replace,
1112 state,
1113 preventScrollReset,
1114 relative,
1115 viewTransition
1116 });
1117 }
1118 }, [location, navigate, path, replaceProp, state, target, to, preventScrollReset, relative, viewTransition]);
1119 }
1120
1121 /**
1122 * A convenient wrapper for reading and writing search parameters via the
1123 * URLSearchParams interface.
1124 */
1125 function useSearchParams(defaultInit) {
1126 router.UNSAFE_warning(typeof URLSearchParams !== "undefined", "You cannot use the `useSearchParams` hook in a browser that does not " + "support the URLSearchParams API. If you need to support Internet " + "Explorer 11, we recommend you load a polyfill such as " + "https://github.com/ungap/url-search-params.") ;
1127 let defaultSearchParamsRef = React__namespace.useRef(createSearchParams(defaultInit));
1128 let hasSetSearchParamsRef = React__namespace.useRef(false);
1129 let location = reactRouter.useLocation();
1130 let searchParams = React__namespace.useMemo(() =>
1131 // Only merge in the defaults if we haven't yet called setSearchParams.
1132 // Once we call that we want those to take precedence, otherwise you can't
1133 // remove a param with setSearchParams({}) if it has an initial value
1134 getSearchParamsForLocation(location.search, hasSetSearchParamsRef.current ? null : defaultSearchParamsRef.current), [location.search]);
1135 let navigate = reactRouter.useNavigate();
1136 let setSearchParams = React__namespace.useCallback((nextInit, navigateOptions) => {
1137 const newSearchParams = createSearchParams(typeof nextInit === "function" ? nextInit(searchParams) : nextInit);
1138 hasSetSearchParamsRef.current = true;
1139 navigate("?" + newSearchParams, navigateOptions);
1140 }, [navigate, searchParams]);
1141 return [searchParams, setSearchParams];
1142 }
1143
1144 /**
1145 * Submits a HTML `<form>` to the server without reloading the page.
1146 */
1147
1148 /**
1149 * Submits a fetcher `<form>` to the server without reloading the page.
1150 */
1151
1152 function validateClientSideSubmission() {
1153 if (typeof document === "undefined") {
1154 throw new Error("You are calling submit during the server render. " + "Try calling submit within a `useEffect` or callback instead.");
1155 }
1156 }
1157 let fetcherId = 0;
1158 let getUniqueFetcherId = () => "__" + String(++fetcherId) + "__";
1159
1160 /**
1161 * Returns a function that may be used to programmatically submit a form (or
1162 * some arbitrary data) to the server.
1163 */
1164 function useSubmit() {
1165 let {
1166 router
1167 } = useDataRouterContext(DataRouterHook.UseSubmit);
1168 let {
1169 basename
1170 } = React__namespace.useContext(reactRouter.UNSAFE_NavigationContext);
1171 let currentRouteId = reactRouter.UNSAFE_useRouteId();
1172 return React__namespace.useCallback(function (target, options) {
1173 if (options === void 0) {
1174 options = {};
1175 }
1176 validateClientSideSubmission();
1177 let {
1178 action,
1179 method,
1180 encType,
1181 formData,
1182 body
1183 } = getFormSubmissionInfo(target, basename);
1184 if (options.navigate === false) {
1185 let key = options.fetcherKey || getUniqueFetcherId();
1186 router.fetch(key, currentRouteId, options.action || action, {
1187 preventScrollReset: options.preventScrollReset,
1188 formData,
1189 body,
1190 formMethod: options.method || method,
1191 formEncType: options.encType || encType,
1192 flushSync: options.flushSync
1193 });
1194 } else {
1195 router.navigate(options.action || action, {
1196 preventScrollReset: options.preventScrollReset,
1197 formData,
1198 body,
1199 formMethod: options.method || method,
1200 formEncType: options.encType || encType,
1201 replace: options.replace,
1202 state: options.state,
1203 fromRouteId: currentRouteId,
1204 flushSync: options.flushSync,
1205 viewTransition: options.viewTransition
1206 });
1207 }
1208 }, [router, basename, currentRouteId]);
1209 }
1210
1211 // v7: Eventually we should deprecate this entirely in favor of using the
1212 // router method directly?
1213 function useFormAction(action, _temp2) {
1214 let {
1215 relative
1216 } = _temp2 === void 0 ? {} : _temp2;
1217 let {
1218 basename
1219 } = React__namespace.useContext(reactRouter.UNSAFE_NavigationContext);
1220 let routeContext = React__namespace.useContext(reactRouter.UNSAFE_RouteContext);
1221 !routeContext ? router.UNSAFE_invariant(false, "useFormAction must be used inside a RouteContext") : void 0;
1222 let [match] = routeContext.matches.slice(-1);
1223 // Shallow clone path so we can modify it below, otherwise we modify the
1224 // object referenced by useMemo inside useResolvedPath
1225 let path = _extends({}, reactRouter.useResolvedPath(action ? action : ".", {
1226 relative
1227 }));
1228
1229 // If no action was specified, browsers will persist current search params
1230 // when determining the path, so match that behavior
1231 // https://github.com/remix-run/remix/issues/927
1232 let location = reactRouter.useLocation();
1233 if (action == null) {
1234 // Safe to write to this directly here since if action was undefined, we
1235 // would have called useResolvedPath(".") which will never include a search
1236 path.search = location.search;
1237
1238 // When grabbing search params from the URL, remove any included ?index param
1239 // since it might not apply to our contextual route. We add it back based
1240 // on match.route.index below
1241 let params = new URLSearchParams(path.search);
1242 let indexValues = params.getAll("index");
1243 let hasNakedIndexParam = indexValues.some(v => v === "");
1244 if (hasNakedIndexParam) {
1245 params.delete("index");
1246 indexValues.filter(v => v).forEach(v => params.append("index", v));
1247 let qs = params.toString();
1248 path.search = qs ? "?" + qs : "";
1249 }
1250 }
1251 if ((!action || action === ".") && match.route.index) {
1252 path.search = path.search ? path.search.replace(/^\?/, "?index&") : "?index";
1253 }
1254
1255 // If we're operating within a basename, prepend it to the pathname prior
1256 // to creating the form action. If this is a root navigation, then just use
1257 // the raw basename which allows the basename to have full control over the
1258 // presence of a trailing slash on root actions
1259 if (basename !== "/") {
1260 path.pathname = path.pathname === "/" ? basename : router.joinPaths([basename, path.pathname]);
1261 }
1262 return reactRouter.createPath(path);
1263 }
1264 // TODO: (v7) Change the useFetcher generic default from `any` to `unknown`
1265 /**
1266 * Interacts with route loaders and actions without causing a navigation. Great
1267 * for any interaction that stays on the same page.
1268 */
1269 function useFetcher(_temp3) {
1270 var _route$matches;
1271 let {
1272 key
1273 } = _temp3 === void 0 ? {} : _temp3;
1274 let {
1275 router: router$1
1276 } = useDataRouterContext(DataRouterHook.UseFetcher);
1277 let state = useDataRouterState(DataRouterStateHook.UseFetcher);
1278 let fetcherData = React__namespace.useContext(FetchersContext);
1279 let route = React__namespace.useContext(reactRouter.UNSAFE_RouteContext);
1280 let routeId = (_route$matches = route.matches[route.matches.length - 1]) == null ? void 0 : _route$matches.route.id;
1281 !fetcherData ? router.UNSAFE_invariant(false, "useFetcher must be used inside a FetchersContext") : void 0;
1282 !route ? router.UNSAFE_invariant(false, "useFetcher must be used inside a RouteContext") : void 0;
1283 !(routeId != null) ? router.UNSAFE_invariant(false, "useFetcher can only be used on routes that contain a unique \"id\"") : void 0;
1284
1285 // Fetcher key handling
1286 // OK to call conditionally to feature detect `useId`
1287 // eslint-disable-next-line react-hooks/rules-of-hooks
1288 let defaultKey = useIdImpl ? useIdImpl() : "";
1289 let [fetcherKey, setFetcherKey] = React__namespace.useState(key || defaultKey);
1290 if (key && key !== fetcherKey) {
1291 setFetcherKey(key);
1292 } else if (!fetcherKey) {
1293 // We will only fall through here when `useId` is not available
1294 setFetcherKey(getUniqueFetcherId());
1295 }
1296
1297 // Registration/cleanup
1298 React__namespace.useEffect(() => {
1299 router$1.getFetcher(fetcherKey);
1300 return () => {
1301 // Tell the router we've unmounted - if v7_fetcherPersist is enabled this
1302 // will not delete immediately but instead queue up a delete after the
1303 // fetcher returns to an `idle` state
1304 router$1.deleteFetcher(fetcherKey);
1305 };
1306 }, [router$1, fetcherKey]);
1307
1308 // Fetcher additions
1309 let load = React__namespace.useCallback((href, opts) => {
1310 !routeId ? router.UNSAFE_invariant(false, "No routeId available for fetcher.load()") : void 0;
1311 router$1.fetch(fetcherKey, routeId, href, opts);
1312 }, [fetcherKey, routeId, router$1]);
1313 let submitImpl = useSubmit();
1314 let submit = React__namespace.useCallback((target, opts) => {
1315 submitImpl(target, _extends({}, opts, {
1316 navigate: false,
1317 fetcherKey
1318 }));
1319 }, [fetcherKey, submitImpl]);
1320 let FetcherForm = React__namespace.useMemo(() => {
1321 let FetcherForm = /*#__PURE__*/React__namespace.forwardRef((props, ref) => {
1322 return /*#__PURE__*/React__namespace.createElement(Form, _extends({}, props, {
1323 navigate: false,
1324 fetcherKey: fetcherKey,
1325 ref: ref
1326 }));
1327 });
1328 {
1329 FetcherForm.displayName = "fetcher.Form";
1330 }
1331 return FetcherForm;
1332 }, [fetcherKey]);
1333
1334 // Exposed FetcherWithComponents
1335 let fetcher = state.fetchers.get(fetcherKey) || router.IDLE_FETCHER;
1336 let data = fetcherData.get(fetcherKey);
1337 let fetcherWithComponents = React__namespace.useMemo(() => _extends({
1338 Form: FetcherForm,
1339 submit,
1340 load
1341 }, fetcher, {
1342 data
1343 }), [FetcherForm, submit, load, fetcher, data]);
1344 return fetcherWithComponents;
1345 }
1346
1347 /**
1348 * Provides all fetchers currently on the page. Useful for layouts and parent
1349 * routes that need to provide pending/optimistic UI regarding the fetch.
1350 */
1351 function useFetchers() {
1352 let state = useDataRouterState(DataRouterStateHook.UseFetchers);
1353 return Array.from(state.fetchers.entries()).map(_ref11 => {
1354 let [key, fetcher] = _ref11;
1355 return _extends({}, fetcher, {
1356 key
1357 });
1358 });
1359 }
1360 const SCROLL_RESTORATION_STORAGE_KEY = "react-router-scroll-positions";
1361 let savedScrollPositions = {};
1362
1363 /**
1364 * When rendered inside a RouterProvider, will restore scroll positions on navigations
1365 */
1366 function useScrollRestoration(_temp4) {
1367 let {
1368 getKey,
1369 storageKey
1370 } = _temp4 === void 0 ? {} : _temp4;
1371 let {
1372 router: router$1
1373 } = useDataRouterContext(DataRouterHook.UseScrollRestoration);
1374 let {
1375 restoreScrollPosition,
1376 preventScrollReset
1377 } = useDataRouterState(DataRouterStateHook.UseScrollRestoration);
1378 let {
1379 basename
1380 } = React__namespace.useContext(reactRouter.UNSAFE_NavigationContext);
1381 let location = reactRouter.useLocation();
1382 let matches = reactRouter.useMatches();
1383 let navigation = reactRouter.useNavigation();
1384
1385 // Trigger manual scroll restoration while we're active
1386 React__namespace.useEffect(() => {
1387 window.history.scrollRestoration = "manual";
1388 return () => {
1389 window.history.scrollRestoration = "auto";
1390 };
1391 }, []);
1392
1393 // Save positions on pagehide
1394 usePageHide(React__namespace.useCallback(() => {
1395 if (navigation.state === "idle") {
1396 let key = (getKey ? getKey(location, matches) : null) || location.key;
1397 savedScrollPositions[key] = window.scrollY;
1398 }
1399 try {
1400 sessionStorage.setItem(storageKey || SCROLL_RESTORATION_STORAGE_KEY, JSON.stringify(savedScrollPositions));
1401 } catch (error) {
1402 router.UNSAFE_warning(false, "Failed to save scroll positions in sessionStorage, <ScrollRestoration /> will not work properly (" + error + ").") ;
1403 }
1404 window.history.scrollRestoration = "auto";
1405 }, [storageKey, getKey, navigation.state, location, matches]));
1406
1407 // Read in any saved scroll locations
1408 if (typeof document !== "undefined") {
1409 // eslint-disable-next-line react-hooks/rules-of-hooks
1410 React__namespace.useLayoutEffect(() => {
1411 try {
1412 let sessionPositions = sessionStorage.getItem(storageKey || SCROLL_RESTORATION_STORAGE_KEY);
1413 if (sessionPositions) {
1414 savedScrollPositions = JSON.parse(sessionPositions);
1415 }
1416 } catch (e) {
1417 // no-op, use default empty object
1418 }
1419 }, [storageKey]);
1420
1421 // Enable scroll restoration in the router
1422 // eslint-disable-next-line react-hooks/rules-of-hooks
1423 React__namespace.useLayoutEffect(() => {
1424 let getKeyWithoutBasename = getKey && basename !== "/" ? (location, matches) => getKey( // Strip the basename to match useLocation()
1425 _extends({}, location, {
1426 pathname: router.stripBasename(location.pathname, basename) || location.pathname
1427 }), matches) : getKey;
1428 let disableScrollRestoration = router$1 == null ? void 0 : router$1.enableScrollRestoration(savedScrollPositions, () => window.scrollY, getKeyWithoutBasename);
1429 return () => disableScrollRestoration && disableScrollRestoration();
1430 }, [router$1, basename, getKey]);
1431
1432 // Restore scrolling when state.restoreScrollPosition changes
1433 // eslint-disable-next-line react-hooks/rules-of-hooks
1434 React__namespace.useLayoutEffect(() => {
1435 // Explicit false means don't do anything (used for submissions)
1436 if (restoreScrollPosition === false) {
1437 return;
1438 }
1439
1440 // been here before, scroll to it
1441 if (typeof restoreScrollPosition === "number") {
1442 window.scrollTo(0, restoreScrollPosition);
1443 return;
1444 }
1445
1446 // try to scroll to the hash
1447 if (location.hash) {
1448 let el = document.getElementById(decodeURIComponent(location.hash.slice(1)));
1449 if (el) {
1450 el.scrollIntoView();
1451 return;
1452 }
1453 }
1454
1455 // Don't reset if this navigation opted out
1456 if (preventScrollReset === true) {
1457 return;
1458 }
1459
1460 // otherwise go to the top on new locations
1461 window.scrollTo(0, 0);
1462 }, [location, restoreScrollPosition, preventScrollReset]);
1463 }
1464 }
1465
1466 /**
1467 * Setup a callback to be fired on the window's `beforeunload` event. This is
1468 * useful for saving some data to `window.localStorage` just before the page
1469 * refreshes.
1470 *
1471 * Note: The `callback` argument should be a function created with
1472 * `React.useCallback()`.
1473 */
1474 function useBeforeUnload(callback, options) {
1475 let {
1476 capture
1477 } = options || {};
1478 React__namespace.useEffect(() => {
1479 let opts = capture != null ? {
1480 capture
1481 } : undefined;
1482 window.addEventListener("beforeunload", callback, opts);
1483 return () => {
1484 window.removeEventListener("beforeunload", callback, opts);
1485 };
1486 }, [callback, capture]);
1487 }
1488
1489 /**
1490 * Setup a callback to be fired on the window's `pagehide` event. This is
1491 * useful for saving some data to `window.localStorage` just before the page
1492 * refreshes. This event is better supported than beforeunload across browsers.
1493 *
1494 * Note: The `callback` argument should be a function created with
1495 * `React.useCallback()`.
1496 */
1497 function usePageHide(callback, options) {
1498 let {
1499 capture
1500 } = options || {};
1501 React__namespace.useEffect(() => {
1502 let opts = capture != null ? {
1503 capture
1504 } : undefined;
1505 window.addEventListener("pagehide", callback, opts);
1506 return () => {
1507 window.removeEventListener("pagehide", callback, opts);
1508 };
1509 }, [callback, capture]);
1510 }
1511
1512 /**
1513 * Wrapper around useBlocker to show a window.confirm prompt to users instead
1514 * of building a custom UI with useBlocker.
1515 *
1516 * Warning: This has *a lot of rough edges* and behaves very differently (and
1517 * very incorrectly in some cases) across browsers if user click addition
1518 * back/forward navigations while the confirm is open. Use at your own risk.
1519 */
1520 function usePrompt(_ref12) {
1521 let {
1522 when,
1523 message
1524 } = _ref12;
1525 let blocker = reactRouter.useBlocker(when);
1526 React__namespace.useEffect(() => {
1527 if (blocker.state === "blocked") {
1528 let proceed = window.confirm(message);
1529 if (proceed) {
1530 // This timeout is needed to avoid a weird "race" on POP navigations
1531 // between the `window.history` revert navigation and the result of
1532 // `window.confirm`
1533 setTimeout(blocker.proceed, 0);
1534 } else {
1535 blocker.reset();
1536 }
1537 }
1538 }, [blocker, message]);
1539 React__namespace.useEffect(() => {
1540 if (blocker.state === "blocked" && !when) {
1541 blocker.reset();
1542 }
1543 }, [blocker, when]);
1544 }
1545
1546 /**
1547 * Return a boolean indicating if there is an active view transition to the
1548 * given href. You can use this value to render CSS classes or viewTransitionName
1549 * styles onto your elements
1550 *
1551 * @param href The destination href
1552 * @param [opts.relative] Relative routing type ("route" | "path")
1553 */
1554 function useViewTransitionState(to, opts) {
1555 if (opts === void 0) {
1556 opts = {};
1557 }
1558 let vtContext = React__namespace.useContext(ViewTransitionContext);
1559 !(vtContext != null) ? router.UNSAFE_invariant(false, "`useViewTransitionState` must be used within `react-router-dom`'s `RouterProvider`. " + "Did you accidentally import `RouterProvider` from `react-router`?") : void 0;
1560 let {
1561 basename
1562 } = useDataRouterContext(DataRouterHook.useViewTransitionState);
1563 let path = reactRouter.useResolvedPath(to, {
1564 relative: opts.relative
1565 });
1566 if (!vtContext.isTransitioning) {
1567 return false;
1568 }
1569 let currentPath = router.stripBasename(vtContext.currentLocation.pathname, basename) || vtContext.currentLocation.pathname;
1570 let nextPath = router.stripBasename(vtContext.nextLocation.pathname, basename) || vtContext.nextLocation.pathname;
1571
1572 // Transition is active if we're going to or coming from the indicated
1573 // destination. This ensures that other PUSH navigations that reverse
1574 // an indicated transition apply. I.e., on the list view you have:
1575 //
1576 // <NavLink to="/details/1" viewTransition>
1577 //
1578 // If you click the breadcrumb back to the list view:
1579 //
1580 // <NavLink to="/list" viewTransition>
1581 //
1582 // We should apply the transition because it's indicated as active going
1583 // from /list -> /details/1 and therefore should be active on the reverse
1584 // (even though this isn't strictly a POP reverse)
1585 return router.matchPath(path.pathname, nextPath) != null || router.matchPath(path.pathname, currentPath) != null;
1586 }
1587
1588 //#endregion
1589
1590 Object.defineProperty(exports, 'AbortedDeferredError', {
1591 enumerable: true,
1592 get: function () { return reactRouter.AbortedDeferredError; }
1593 });
1594 Object.defineProperty(exports, 'Await', {
1595 enumerable: true,
1596 get: function () { return reactRouter.Await; }
1597 });
1598 Object.defineProperty(exports, 'MemoryRouter', {
1599 enumerable: true,
1600 get: function () { return reactRouter.MemoryRouter; }
1601 });
1602 Object.defineProperty(exports, 'Navigate', {
1603 enumerable: true,
1604 get: function () { return reactRouter.Navigate; }
1605 });
1606 Object.defineProperty(exports, 'NavigationType', {
1607 enumerable: true,
1608 get: function () { return reactRouter.NavigationType; }
1609 });
1610 Object.defineProperty(exports, 'Outlet', {
1611 enumerable: true,
1612 get: function () { return reactRouter.Outlet; }
1613 });
1614 Object.defineProperty(exports, 'Route', {
1615 enumerable: true,
1616 get: function () { return reactRouter.Route; }
1617 });
1618 Object.defineProperty(exports, 'Router', {
1619 enumerable: true,
1620 get: function () { return reactRouter.Router; }
1621 });
1622 Object.defineProperty(exports, 'Routes', {
1623 enumerable: true,
1624 get: function () { return reactRouter.Routes; }
1625 });
1626 Object.defineProperty(exports, 'UNSAFE_DataRouterContext', {
1627 enumerable: true,
1628 get: function () { return reactRouter.UNSAFE_DataRouterContext; }
1629 });
1630 Object.defineProperty(exports, 'UNSAFE_DataRouterStateContext', {
1631 enumerable: true,
1632 get: function () { return reactRouter.UNSAFE_DataRouterStateContext; }
1633 });
1634 Object.defineProperty(exports, 'UNSAFE_LocationContext', {
1635 enumerable: true,
1636 get: function () { return reactRouter.UNSAFE_LocationContext; }
1637 });
1638 Object.defineProperty(exports, 'UNSAFE_NavigationContext', {
1639 enumerable: true,
1640 get: function () { return reactRouter.UNSAFE_NavigationContext; }
1641 });
1642 Object.defineProperty(exports, 'UNSAFE_RouteContext', {
1643 enumerable: true,
1644 get: function () { return reactRouter.UNSAFE_RouteContext; }
1645 });
1646 Object.defineProperty(exports, 'UNSAFE_useRouteId', {
1647 enumerable: true,
1648 get: function () { return reactRouter.UNSAFE_useRouteId; }
1649 });
1650 Object.defineProperty(exports, 'createMemoryRouter', {
1651 enumerable: true,
1652 get: function () { return reactRouter.createMemoryRouter; }
1653 });
1654 Object.defineProperty(exports, 'createPath', {
1655 enumerable: true,
1656 get: function () { return reactRouter.createPath; }
1657 });
1658 Object.defineProperty(exports, 'createRoutesFromChildren', {
1659 enumerable: true,
1660 get: function () { return reactRouter.createRoutesFromChildren; }
1661 });
1662 Object.defineProperty(exports, 'createRoutesFromElements', {
1663 enumerable: true,
1664 get: function () { return reactRouter.createRoutesFromElements; }
1665 });
1666 Object.defineProperty(exports, 'defer', {
1667 enumerable: true,
1668 get: function () { return reactRouter.defer; }
1669 });
1670 Object.defineProperty(exports, 'generatePath', {
1671 enumerable: true,
1672 get: function () { return reactRouter.generatePath; }
1673 });
1674 Object.defineProperty(exports, 'isRouteErrorResponse', {
1675 enumerable: true,
1676 get: function () { return reactRouter.isRouteErrorResponse; }
1677 });
1678 Object.defineProperty(exports, 'json', {
1679 enumerable: true,
1680 get: function () { return reactRouter.json; }
1681 });
1682 Object.defineProperty(exports, 'matchPath', {
1683 enumerable: true,
1684 get: function () { return reactRouter.matchPath; }
1685 });
1686 Object.defineProperty(exports, 'matchRoutes', {
1687 enumerable: true,
1688 get: function () { return reactRouter.matchRoutes; }
1689 });
1690 Object.defineProperty(exports, 'parsePath', {
1691 enumerable: true,
1692 get: function () { return reactRouter.parsePath; }
1693 });
1694 Object.defineProperty(exports, 'redirect', {
1695 enumerable: true,
1696 get: function () { return reactRouter.redirect; }
1697 });
1698 Object.defineProperty(exports, 'redirectDocument', {
1699 enumerable: true,
1700 get: function () { return reactRouter.redirectDocument; }
1701 });
1702 Object.defineProperty(exports, 'renderMatches', {
1703 enumerable: true,
1704 get: function () { return reactRouter.renderMatches; }
1705 });
1706 Object.defineProperty(exports, 'replace', {
1707 enumerable: true,
1708 get: function () { return reactRouter.replace; }
1709 });
1710 Object.defineProperty(exports, 'resolvePath', {
1711 enumerable: true,
1712 get: function () { return reactRouter.resolvePath; }
1713 });
1714 Object.defineProperty(exports, 'useActionData', {
1715 enumerable: true,
1716 get: function () { return reactRouter.useActionData; }
1717 });
1718 Object.defineProperty(exports, 'useAsyncError', {
1719 enumerable: true,
1720 get: function () { return reactRouter.useAsyncError; }
1721 });
1722 Object.defineProperty(exports, 'useAsyncValue', {
1723 enumerable: true,
1724 get: function () { return reactRouter.useAsyncValue; }
1725 });
1726 Object.defineProperty(exports, 'useBlocker', {
1727 enumerable: true,
1728 get: function () { return reactRouter.useBlocker; }
1729 });
1730 Object.defineProperty(exports, 'useHref', {
1731 enumerable: true,
1732 get: function () { return reactRouter.useHref; }
1733 });
1734 Object.defineProperty(exports, 'useInRouterContext', {
1735 enumerable: true,
1736 get: function () { return reactRouter.useInRouterContext; }
1737 });
1738 Object.defineProperty(exports, 'useLoaderData', {
1739 enumerable: true,
1740 get: function () { return reactRouter.useLoaderData; }
1741 });
1742 Object.defineProperty(exports, 'useLocation', {
1743 enumerable: true,
1744 get: function () { return reactRouter.useLocation; }
1745 });
1746 Object.defineProperty(exports, 'useMatch', {
1747 enumerable: true,
1748 get: function () { return reactRouter.useMatch; }
1749 });
1750 Object.defineProperty(exports, 'useMatches', {
1751 enumerable: true,
1752 get: function () { return reactRouter.useMatches; }
1753 });
1754 Object.defineProperty(exports, 'useNavigate', {
1755 enumerable: true,
1756 get: function () { return reactRouter.useNavigate; }
1757 });
1758 Object.defineProperty(exports, 'useNavigation', {
1759 enumerable: true,
1760 get: function () { return reactRouter.useNavigation; }
1761 });
1762 Object.defineProperty(exports, 'useNavigationType', {
1763 enumerable: true,
1764 get: function () { return reactRouter.useNavigationType; }
1765 });
1766 Object.defineProperty(exports, 'useOutlet', {
1767 enumerable: true,
1768 get: function () { return reactRouter.useOutlet; }
1769 });
1770 Object.defineProperty(exports, 'useOutletContext', {
1771 enumerable: true,
1772 get: function () { return reactRouter.useOutletContext; }
1773 });
1774 Object.defineProperty(exports, 'useParams', {
1775 enumerable: true,
1776 get: function () { return reactRouter.useParams; }
1777 });
1778 Object.defineProperty(exports, 'useResolvedPath', {
1779 enumerable: true,
1780 get: function () { return reactRouter.useResolvedPath; }
1781 });
1782 Object.defineProperty(exports, 'useRevalidator', {
1783 enumerable: true,
1784 get: function () { return reactRouter.useRevalidator; }
1785 });
1786 Object.defineProperty(exports, 'useRouteError', {
1787 enumerable: true,
1788 get: function () { return reactRouter.useRouteError; }
1789 });
1790 Object.defineProperty(exports, 'useRouteLoaderData', {
1791 enumerable: true,
1792 get: function () { return reactRouter.useRouteLoaderData; }
1793 });
1794 Object.defineProperty(exports, 'useRoutes', {
1795 enumerable: true,
1796 get: function () { return reactRouter.useRoutes; }
1797 });
1798 Object.defineProperty(exports, 'UNSAFE_ErrorResponseImpl', {
1799 enumerable: true,
1800 get: function () { return router.UNSAFE_ErrorResponseImpl; }
1801 });
1802 exports.BrowserRouter = BrowserRouter;
1803 exports.Form = Form;
1804 exports.HashRouter = HashRouter;
1805 exports.Link = Link;
1806 exports.NavLink = NavLink;
1807 exports.RouterProvider = RouterProvider;
1808 exports.ScrollRestoration = ScrollRestoration;
1809 exports.UNSAFE_FetchersContext = FetchersContext;
1810 exports.UNSAFE_ViewTransitionContext = ViewTransitionContext;
1811 exports.UNSAFE_useScrollRestoration = useScrollRestoration;
1812 exports.createBrowserRouter = createBrowserRouter;
1813 exports.createHashRouter = createHashRouter;
1814 exports.createSearchParams = createSearchParams;
1815 exports.unstable_HistoryRouter = HistoryRouter;
1816 exports.unstable_usePrompt = usePrompt;
1817 exports.useBeforeUnload = useBeforeUnload;
1818 exports.useFetcher = useFetcher;
1819 exports.useFetchers = useFetchers;
1820 exports.useFormAction = useFormAction;
1821 exports.useLinkClickHandler = useLinkClickHandler;
1822 exports.useSearchParams = useSearchParams;
1823 exports.useSubmit = useSubmit;
1824 exports.useViewTransitionState = useViewTransitionState;
1825
1826 Object.defineProperty(exports, '__esModule', { value: true });
1827
1828}));
1829//# sourceMappingURL=react-router-dom.development.js.map
Note: See TracBrowser for help on using the repository browser.