UNPKG

57.4 kBJavaScriptView Raw
1/**
2 * React Router v6.9.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('@remix-run/router'), require('react')) :
13 typeof define === 'function' && define.amd ? define(['exports', '@remix-run/router', 'react'], factory) :
14 (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.ReactRouter = {}, global.RemixRouter, global.React));
15})(this, (function (exports, router, React) { '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
37 /**
38 * Copyright (c) Facebook, Inc. and its affiliates.
39 *
40 * This source code is licensed under the MIT license found in the
41 * LICENSE file in the root directory of this source tree.
42 */
43 /**
44 * inlined Object.is polyfill to avoid requiring consumers ship their own
45 * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is
46 */
47
48 function isPolyfill(x, y) {
49 return x === y && (x !== 0 || 1 / x === 1 / y) || x !== x && y !== y // eslint-disable-line no-self-compare
50 ;
51 }
52
53 const is = typeof Object.is === "function" ? Object.is : isPolyfill; // Intentionally not using named imports because Rollup uses dynamic
54 // dispatch for CommonJS interop named imports.
55
56 const {
57 useState,
58 useEffect,
59 useLayoutEffect,
60 useDebugValue
61 } = React__namespace;
62 let didWarnOld18Alpha = false;
63 let didWarnUncachedGetSnapshot = false; // Disclaimer: This shim breaks many of the rules of React, and only works
64 // because of a very particular set of implementation details and assumptions
65 // -- change any one of them and it will break. The most important assumption
66 // is that updates are always synchronous, because concurrent rendering is
67 // only available in versions of React that also have a built-in
68 // useSyncExternalStore API. And we only use this shim when the built-in API
69 // does not exist.
70 //
71 // Do not assume that the clever hacks used by this hook also work in general.
72 // The point of this shim is to replace the need for hacks by other libraries.
73
74 function useSyncExternalStore$2(subscribe, getSnapshot, // Note: The shim does not use getServerSnapshot, because pre-18 versions of
75 // React do not expose a way to check if we're hydrating. So users of the shim
76 // will need to track that themselves and return the correct value
77 // from `getSnapshot`.
78 getServerSnapshot) {
79 {
80 if (!didWarnOld18Alpha) {
81 if ("startTransition" in React__namespace) {
82 didWarnOld18Alpha = true;
83 console.error("You are using an outdated, pre-release alpha of React 18 that " + "does not support useSyncExternalStore. The " + "use-sync-external-store shim will not work correctly. Upgrade " + "to a newer pre-release.");
84 }
85 }
86 } // Read the current snapshot from the store on every render. Again, this
87 // breaks the rules of React, and only works here because of specific
88 // implementation details, most importantly that updates are
89 // always synchronous.
90
91
92 const value = getSnapshot();
93
94 {
95 if (!didWarnUncachedGetSnapshot) {
96 const cachedValue = getSnapshot();
97
98 if (!is(value, cachedValue)) {
99 console.error("The result of getSnapshot should be cached to avoid an infinite loop");
100 didWarnUncachedGetSnapshot = true;
101 }
102 }
103 } // Because updates are synchronous, we don't queue them. Instead we force a
104 // re-render whenever the subscribed state changes by updating an some
105 // arbitrary useState hook. Then, during render, we call getSnapshot to read
106 // the current value.
107 //
108 // Because we don't actually use the state returned by the useState hook, we
109 // can save a bit of memory by storing other stuff in that slot.
110 //
111 // To implement the early bailout, we need to track some things on a mutable
112 // object. Usually, we would put that in a useRef hook, but we can stash it in
113 // our useState hook instead.
114 //
115 // To force a re-render, we call forceUpdate({inst}). That works because the
116 // new object always fails an equality check.
117
118
119 const [{
120 inst
121 }, forceUpdate] = useState({
122 inst: {
123 value,
124 getSnapshot
125 }
126 }); // Track the latest getSnapshot function with a ref. This needs to be updated
127 // in the layout phase so we can access it during the tearing check that
128 // happens on subscribe.
129
130 useLayoutEffect(() => {
131 inst.value = value;
132 inst.getSnapshot = getSnapshot; // Whenever getSnapshot or subscribe changes, we need to check in the
133 // commit phase if there was an interleaved mutation. In concurrent mode
134 // this can happen all the time, but even in synchronous mode, an earlier
135 // effect may have mutated the store.
136
137 if (checkIfSnapshotChanged(inst)) {
138 // Force a re-render.
139 forceUpdate({
140 inst
141 });
142 } // eslint-disable-next-line react-hooks/exhaustive-deps
143
144 }, [subscribe, value, getSnapshot]);
145 useEffect(() => {
146 // Check for changes right before subscribing. Subsequent changes will be
147 // detected in the subscription handler.
148 if (checkIfSnapshotChanged(inst)) {
149 // Force a re-render.
150 forceUpdate({
151 inst
152 });
153 }
154
155 const handleStoreChange = () => {
156 // TODO: Because there is no cross-renderer API for batching updates, it's
157 // up to the consumer of this library to wrap their subscription event
158 // with unstable_batchedUpdates. Should we try to detect when this isn't
159 // the case and print a warning in development?
160 // The store changed. Check if the snapshot changed since the last time we
161 // read from the store.
162 if (checkIfSnapshotChanged(inst)) {
163 // Force a re-render.
164 forceUpdate({
165 inst
166 });
167 }
168 }; // Subscribe to the store and return a clean-up function.
169
170
171 return subscribe(handleStoreChange); // eslint-disable-next-line react-hooks/exhaustive-deps
172 }, [subscribe]);
173 useDebugValue(value);
174 return value;
175 }
176
177 function checkIfSnapshotChanged(inst) {
178 const latestGetSnapshot = inst.getSnapshot;
179 const prevValue = inst.value;
180
181 try {
182 const nextValue = latestGetSnapshot();
183 return !is(prevValue, nextValue);
184 } catch (error) {
185 return true;
186 }
187 }
188
189 /**
190 * Copyright (c) Facebook, Inc. and its affiliates.
191 *
192 * This source code is licensed under the MIT license found in the
193 * LICENSE file in the root directory of this source tree.
194 *
195 * @flow
196 */
197 function useSyncExternalStore$1(subscribe, getSnapshot, getServerSnapshot) {
198 // Note: The shim does not use getServerSnapshot, because pre-18 versions of
199 // React do not expose a way to check if we're hydrating. So users of the shim
200 // will need to track that themselves and return the correct value
201 // from `getSnapshot`.
202 return getSnapshot();
203 }
204
205 /**
206 * Inlined into the react-router repo since use-sync-external-store does not
207 * provide a UMD-compatible package, so we need this to be able to distribute
208 * UMD react-router bundles
209 */
210 const canUseDOM = !!(typeof window !== "undefined" && typeof window.document !== "undefined" && typeof window.document.createElement !== "undefined");
211 const isServerEnvironment = !canUseDOM;
212 const shim = isServerEnvironment ? useSyncExternalStore$1 : useSyncExternalStore$2;
213 const useSyncExternalStore = "useSyncExternalStore" in React__namespace ? (module => module.useSyncExternalStore)(React__namespace) : shim;
214
215 const DataRouterContext = /*#__PURE__*/React__namespace.createContext(null);
216
217 {
218 DataRouterContext.displayName = "DataRouter";
219 }
220
221 const DataRouterStateContext = /*#__PURE__*/React__namespace.createContext(null);
222
223 {
224 DataRouterStateContext.displayName = "DataRouterState";
225 }
226
227 const AwaitContext = /*#__PURE__*/React__namespace.createContext(null);
228
229 {
230 AwaitContext.displayName = "Await";
231 }
232
233 const NavigationContext = /*#__PURE__*/React__namespace.createContext(null);
234
235 {
236 NavigationContext.displayName = "Navigation";
237 }
238
239 const LocationContext = /*#__PURE__*/React__namespace.createContext(null);
240
241 {
242 LocationContext.displayName = "Location";
243 }
244
245 const RouteContext = /*#__PURE__*/React__namespace.createContext({
246 outlet: null,
247 matches: []
248 });
249
250 {
251 RouteContext.displayName = "Route";
252 }
253
254 const RouteErrorContext = /*#__PURE__*/React__namespace.createContext(null);
255
256 {
257 RouteErrorContext.displayName = "RouteError";
258 }
259
260 function _extends() {
261 _extends = Object.assign ? Object.assign.bind() : function (target) {
262 for (var i = 1; i < arguments.length; i++) {
263 var source = arguments[i];
264
265 for (var key in source) {
266 if (Object.prototype.hasOwnProperty.call(source, key)) {
267 target[key] = source[key];
268 }
269 }
270 }
271
272 return target;
273 };
274 return _extends.apply(this, arguments);
275 }
276
277 /**
278 * Returns the full href for the given "to" value. This is useful for building
279 * custom links that are also accessible and preserve right-click behavior.
280 *
281 * @see https://reactrouter.com/hooks/use-href
282 */
283
284 function useHref(to, _temp) {
285 let {
286 relative
287 } = _temp === void 0 ? {} : _temp;
288 !useInRouterContext() ? router.UNSAFE_invariant(false, // TODO: This error is probably because they somehow have 2 versions of the
289 // router loaded. We can help them understand how to avoid that.
290 "useHref() may be used only in the context of a <Router> component.") : void 0;
291 let {
292 basename,
293 navigator
294 } = React__namespace.useContext(NavigationContext);
295 let {
296 hash,
297 pathname,
298 search
299 } = useResolvedPath(to, {
300 relative
301 });
302 let joinedPathname = pathname; // If we're operating within a basename, prepend it to the pathname prior
303 // to creating the href. If this is a root navigation, then just use the raw
304 // basename which allows the basename to have full control over the presence
305 // of a trailing slash on root links
306
307 if (basename !== "/") {
308 joinedPathname = pathname === "/" ? basename : router.joinPaths([basename, pathname]);
309 }
310
311 return navigator.createHref({
312 pathname: joinedPathname,
313 search,
314 hash
315 });
316 }
317 /**
318 * Returns true if this component is a descendant of a <Router>.
319 *
320 * @see https://reactrouter.com/hooks/use-in-router-context
321 */
322
323 function useInRouterContext() {
324 return React__namespace.useContext(LocationContext) != null;
325 }
326 /**
327 * Returns the current location object, which represents the current URL in web
328 * browsers.
329 *
330 * Note: If you're using this it may mean you're doing some of your own
331 * "routing" in your app, and we'd like to know what your use case is. We may
332 * be able to provide something higher-level to better suit your needs.
333 *
334 * @see https://reactrouter.com/hooks/use-location
335 */
336
337 function useLocation() {
338 !useInRouterContext() ? router.UNSAFE_invariant(false, // TODO: This error is probably because they somehow have 2 versions of the
339 // router loaded. We can help them understand how to avoid that.
340 "useLocation() may be used only in the context of a <Router> component.") : void 0;
341 return React__namespace.useContext(LocationContext).location;
342 }
343 /**
344 * Returns the current navigation action which describes how the router came to
345 * the current location, either by a pop, push, or replace on the history stack.
346 *
347 * @see https://reactrouter.com/hooks/use-navigation-type
348 */
349
350 function useNavigationType() {
351 return React__namespace.useContext(LocationContext).navigationType;
352 }
353 /**
354 * Returns a PathMatch object if the given pattern matches the current URL.
355 * This is useful for components that need to know "active" state, e.g.
356 * <NavLink>.
357 *
358 * @see https://reactrouter.com/hooks/use-match
359 */
360
361 function useMatch(pattern) {
362 !useInRouterContext() ? router.UNSAFE_invariant(false, // TODO: This error is probably because they somehow have 2 versions of the
363 // router loaded. We can help them understand how to avoid that.
364 "useMatch() may be used only in the context of a <Router> component.") : void 0;
365 let {
366 pathname
367 } = useLocation();
368 return React__namespace.useMemo(() => router.matchPath(pattern, pathname), [pathname, pattern]);
369 }
370 /**
371 * The interface for the navigate() function returned from useNavigate().
372 */
373
374 /**
375 * Returns an imperative method for changing the location. Used by <Link>s, but
376 * may also be used by other elements to change the location.
377 *
378 * @see https://reactrouter.com/hooks/use-navigate
379 */
380 function useNavigate() {
381 !useInRouterContext() ? router.UNSAFE_invariant(false, // TODO: This error is probably because they somehow have 2 versions of the
382 // router loaded. We can help them understand how to avoid that.
383 "useNavigate() may be used only in the context of a <Router> component.") : void 0;
384 let {
385 basename,
386 navigator
387 } = React__namespace.useContext(NavigationContext);
388 let {
389 matches
390 } = React__namespace.useContext(RouteContext);
391 let {
392 pathname: locationPathname
393 } = useLocation();
394 let routePathnamesJson = JSON.stringify(router.UNSAFE_getPathContributingMatches(matches).map(match => match.pathnameBase));
395 let activeRef = React__namespace.useRef(false);
396 React__namespace.useEffect(() => {
397 activeRef.current = true;
398 });
399 let navigate = React__namespace.useCallback(function (to, options) {
400 if (options === void 0) {
401 options = {};
402 }
403
404 router.UNSAFE_warning(activeRef.current, "You should call navigate() in a React.useEffect(), not when " + "your component is first rendered.") ;
405 if (!activeRef.current) return;
406
407 if (typeof to === "number") {
408 navigator.go(to);
409 return;
410 }
411
412 let path = router.resolveTo(to, JSON.parse(routePathnamesJson), locationPathname, options.relative === "path"); // If we're operating within a basename, prepend it to the pathname prior
413 // to handing off to history. If this is a root navigation, then we
414 // navigate to the raw basename which allows the basename to have full
415 // control over the presence of a trailing slash on root links
416
417 if (basename !== "/") {
418 path.pathname = path.pathname === "/" ? basename : router.joinPaths([basename, path.pathname]);
419 }
420
421 (!!options.replace ? navigator.replace : navigator.push)(path, options.state, options);
422 }, [basename, navigator, routePathnamesJson, locationPathname]);
423 return navigate;
424 }
425 const OutletContext = /*#__PURE__*/React__namespace.createContext(null);
426 /**
427 * Returns the context (if provided) for the child route at this level of the route
428 * hierarchy.
429 * @see https://reactrouter.com/hooks/use-outlet-context
430 */
431
432 function useOutletContext() {
433 return React__namespace.useContext(OutletContext);
434 }
435 /**
436 * Returns the element for the child route at this level of the route
437 * hierarchy. Used internally by <Outlet> to render child routes.
438 *
439 * @see https://reactrouter.com/hooks/use-outlet
440 */
441
442 function useOutlet(context) {
443 let outlet = React__namespace.useContext(RouteContext).outlet;
444
445 if (outlet) {
446 return /*#__PURE__*/React__namespace.createElement(OutletContext.Provider, {
447 value: context
448 }, outlet);
449 }
450
451 return outlet;
452 }
453 /**
454 * Returns an object of key/value pairs of the dynamic params from the current
455 * URL that were matched by the route path.
456 *
457 * @see https://reactrouter.com/hooks/use-params
458 */
459
460 function useParams() {
461 let {
462 matches
463 } = React__namespace.useContext(RouteContext);
464 let routeMatch = matches[matches.length - 1];
465 return routeMatch ? routeMatch.params : {};
466 }
467 /**
468 * Resolves the pathname of the given `to` value against the current location.
469 *
470 * @see https://reactrouter.com/hooks/use-resolved-path
471 */
472
473 function useResolvedPath(to, _temp2) {
474 let {
475 relative
476 } = _temp2 === void 0 ? {} : _temp2;
477 let {
478 matches
479 } = React__namespace.useContext(RouteContext);
480 let {
481 pathname: locationPathname
482 } = useLocation();
483 let routePathnamesJson = JSON.stringify(router.UNSAFE_getPathContributingMatches(matches).map(match => match.pathnameBase));
484 return React__namespace.useMemo(() => router.resolveTo(to, JSON.parse(routePathnamesJson), locationPathname, relative === "path"), [to, routePathnamesJson, locationPathname, relative]);
485 }
486 /**
487 * Returns the element of the route that matched the current location, prepared
488 * with the correct context to render the remainder of the route tree. Route
489 * elements in the tree must render an <Outlet> to render their child route's
490 * element.
491 *
492 * @see https://reactrouter.com/hooks/use-routes
493 */
494
495 function useRoutes(routes, locationArg) {
496 !useInRouterContext() ? router.UNSAFE_invariant(false, // TODO: This error is probably because they somehow have 2 versions of the
497 // router loaded. We can help them understand how to avoid that.
498 "useRoutes() may be used only in the context of a <Router> component.") : void 0;
499 let {
500 navigator
501 } = React__namespace.useContext(NavigationContext);
502 let dataRouterStateContext = React__namespace.useContext(DataRouterStateContext);
503 let {
504 matches: parentMatches
505 } = React__namespace.useContext(RouteContext);
506 let routeMatch = parentMatches[parentMatches.length - 1];
507 let parentParams = routeMatch ? routeMatch.params : {};
508 let parentPathname = routeMatch ? routeMatch.pathname : "/";
509 let parentPathnameBase = routeMatch ? routeMatch.pathnameBase : "/";
510 let parentRoute = routeMatch && routeMatch.route;
511
512 {
513 // You won't get a warning about 2 different <Routes> under a <Route>
514 // without a trailing *, but this is a best-effort warning anyway since we
515 // cannot even give the warning unless they land at the parent route.
516 //
517 // Example:
518 //
519 // <Routes>
520 // {/* This route path MUST end with /* because otherwise
521 // it will never match /blog/post/123 */}
522 // <Route path="blog" element={<Blog />} />
523 // <Route path="blog/feed" element={<BlogFeed />} />
524 // </Routes>
525 //
526 // function Blog() {
527 // return (
528 // <Routes>
529 // <Route path="post/:id" element={<Post />} />
530 // </Routes>
531 // );
532 // }
533 let parentPath = parentRoute && parentRoute.path || "";
534 warningOnce(parentPathname, !parentRoute || parentPath.endsWith("*"), "You rendered descendant <Routes> (or called `useRoutes()`) at " + ("\"" + parentPathname + "\" (under <Route path=\"" + parentPath + "\">) but the ") + "parent route path has no trailing \"*\". This means if you navigate " + "deeper, the parent won't match anymore and therefore the child " + "routes will never render.\n\n" + ("Please change the parent <Route path=\"" + parentPath + "\"> to <Route ") + ("path=\"" + (parentPath === "/" ? "*" : parentPath + "/*") + "\">."));
535 }
536
537 let locationFromContext = useLocation();
538 let location;
539
540 if (locationArg) {
541 var _parsedLocationArg$pa;
542
543 let parsedLocationArg = typeof locationArg === "string" ? router.parsePath(locationArg) : locationArg;
544 !(parentPathnameBase === "/" || ((_parsedLocationArg$pa = parsedLocationArg.pathname) == null ? void 0 : _parsedLocationArg$pa.startsWith(parentPathnameBase))) ? router.UNSAFE_invariant(false, "When overriding the location using `<Routes location>` or `useRoutes(routes, location)`, " + "the location pathname must begin with the portion of the URL pathname that was " + ("matched by all parent routes. The current pathname base is \"" + parentPathnameBase + "\" ") + ("but pathname \"" + parsedLocationArg.pathname + "\" was given in the `location` prop.")) : void 0;
545 location = parsedLocationArg;
546 } else {
547 location = locationFromContext;
548 }
549
550 let pathname = location.pathname || "/";
551 let remainingPathname = parentPathnameBase === "/" ? pathname : pathname.slice(parentPathnameBase.length) || "/";
552 let matches = router.matchRoutes(routes, {
553 pathname: remainingPathname
554 });
555
556 {
557 router.UNSAFE_warning(parentRoute || matches != null, "No routes matched location \"" + location.pathname + location.search + location.hash + "\" ") ;
558 router.UNSAFE_warning(matches == null || matches[matches.length - 1].route.element !== undefined || matches[matches.length - 1].route.Component !== undefined, "Matched leaf route at location \"" + location.pathname + location.search + location.hash + "\" " + "does not have an element or Component. This means it will render an <Outlet /> with a " + "null value by default resulting in an \"empty\" page.") ;
559 }
560
561 let renderedMatches = _renderMatches(matches && matches.map(match => Object.assign({}, match, {
562 params: Object.assign({}, parentParams, match.params),
563 pathname: router.joinPaths([parentPathnameBase, // Re-encode pathnames that were decoded inside matchRoutes
564 navigator.encodeLocation ? navigator.encodeLocation(match.pathname).pathname : match.pathname]),
565 pathnameBase: match.pathnameBase === "/" ? parentPathnameBase : router.joinPaths([parentPathnameBase, // Re-encode pathnames that were decoded inside matchRoutes
566 navigator.encodeLocation ? navigator.encodeLocation(match.pathnameBase).pathname : match.pathnameBase])
567 })), parentMatches, dataRouterStateContext || undefined); // When a user passes in a `locationArg`, the associated routes need to
568 // be wrapped in a new `LocationContext.Provider` in order for `useLocation`
569 // to use the scoped location instead of the global location.
570
571
572 if (locationArg && renderedMatches) {
573 return /*#__PURE__*/React__namespace.createElement(LocationContext.Provider, {
574 value: {
575 location: _extends({
576 pathname: "/",
577 search: "",
578 hash: "",
579 state: null,
580 key: "default"
581 }, location),
582 navigationType: router.Action.Pop
583 }
584 }, renderedMatches);
585 }
586
587 return renderedMatches;
588 }
589
590 function DefaultErrorComponent() {
591 let error = useRouteError();
592 let message = router.isRouteErrorResponse(error) ? error.status + " " + error.statusText : error instanceof Error ? error.message : JSON.stringify(error);
593 let stack = error instanceof Error ? error.stack : null;
594 let lightgrey = "rgba(200,200,200, 0.5)";
595 let preStyles = {
596 padding: "0.5rem",
597 backgroundColor: lightgrey
598 };
599 let codeStyles = {
600 padding: "2px 4px",
601 backgroundColor: lightgrey
602 };
603 let devInfo = null;
604
605 {
606 devInfo = /*#__PURE__*/React__namespace.createElement(React__namespace.Fragment, null, /*#__PURE__*/React__namespace.createElement("p", null, "\uD83D\uDCBF Hey developer \uD83D\uDC4B"), /*#__PURE__*/React__namespace.createElement("p", null, "You can provide a way better UX than this when your app throws errors by providing your own\xA0", /*#__PURE__*/React__namespace.createElement("code", {
607 style: codeStyles
608 }, "ErrorBoundary"), " prop on\xA0", /*#__PURE__*/React__namespace.createElement("code", {
609 style: codeStyles
610 }, "<Route>")));
611 }
612
613 return /*#__PURE__*/React__namespace.createElement(React__namespace.Fragment, null, /*#__PURE__*/React__namespace.createElement("h2", null, "Unexpected Application Error!"), /*#__PURE__*/React__namespace.createElement("h3", {
614 style: {
615 fontStyle: "italic"
616 }
617 }, message), stack ? /*#__PURE__*/React__namespace.createElement("pre", {
618 style: preStyles
619 }, stack) : null, devInfo);
620 }
621
622 class RenderErrorBoundary extends React__namespace.Component {
623 constructor(props) {
624 super(props);
625 this.state = {
626 location: props.location,
627 error: props.error
628 };
629 }
630
631 static getDerivedStateFromError(error) {
632 return {
633 error: error
634 };
635 }
636
637 static getDerivedStateFromProps(props, state) {
638 // When we get into an error state, the user will likely click "back" to the
639 // previous page that didn't have an error. Because this wraps the entire
640 // application, that will have no effect--the error page continues to display.
641 // This gives us a mechanism to recover from the error when the location changes.
642 //
643 // Whether we're in an error state or not, we update the location in state
644 // so that when we are in an error state, it gets reset when a new location
645 // comes in and the user recovers from the error.
646 if (state.location !== props.location) {
647 return {
648 error: props.error,
649 location: props.location
650 };
651 } // If we're not changing locations, preserve the location but still surface
652 // any new errors that may come through. We retain the existing error, we do
653 // this because the error provided from the app state may be cleared without
654 // the location changing.
655
656
657 return {
658 error: props.error || state.error,
659 location: state.location
660 };
661 }
662
663 componentDidCatch(error, errorInfo) {
664 console.error("React Router caught the following error during render", error, errorInfo);
665 }
666
667 render() {
668 return this.state.error ? /*#__PURE__*/React__namespace.createElement(RouteContext.Provider, {
669 value: this.props.routeContext
670 }, /*#__PURE__*/React__namespace.createElement(RouteErrorContext.Provider, {
671 value: this.state.error,
672 children: this.props.component
673 })) : this.props.children;
674 }
675
676 }
677
678 function RenderedRoute(_ref) {
679 let {
680 routeContext,
681 match,
682 children
683 } = _ref;
684 let dataRouterContext = React__namespace.useContext(DataRouterContext); // Track how deep we got in our render pass to emulate SSR componentDidCatch
685 // in a DataStaticRouter
686
687 if (dataRouterContext && dataRouterContext.static && dataRouterContext.staticContext && (match.route.errorElement || match.route.ErrorBoundary)) {
688 dataRouterContext.staticContext._deepestRenderedBoundaryId = match.route.id;
689 }
690
691 return /*#__PURE__*/React__namespace.createElement(RouteContext.Provider, {
692 value: routeContext
693 }, children);
694 }
695
696 function _renderMatches(matches, parentMatches, dataRouterState) {
697 if (parentMatches === void 0) {
698 parentMatches = [];
699 }
700
701 if (matches == null) {
702 if (dataRouterState != null && dataRouterState.errors) {
703 // Don't bail if we have data router errors so we can render them in the
704 // boundary. Use the pre-matched (or shimmed) matches
705 matches = dataRouterState.matches;
706 } else {
707 return null;
708 }
709 }
710
711 let renderedMatches = matches; // If we have data errors, trim matches to the highest error boundary
712
713 let errors = dataRouterState == null ? void 0 : dataRouterState.errors;
714
715 if (errors != null) {
716 let errorIndex = renderedMatches.findIndex(m => m.route.id && (errors == null ? void 0 : errors[m.route.id]));
717 !(errorIndex >= 0) ? router.UNSAFE_invariant(false, "Could not find a matching route for the current errors: " + errors) : void 0;
718 renderedMatches = renderedMatches.slice(0, Math.min(renderedMatches.length, errorIndex + 1));
719 }
720
721 return renderedMatches.reduceRight((outlet, match, index) => {
722 let error = match.route.id ? errors == null ? void 0 : errors[match.route.id] : null; // Only data routers handle errors
723
724 let errorElement = null;
725
726 if (dataRouterState) {
727 if (match.route.ErrorBoundary) {
728 errorElement = /*#__PURE__*/React__namespace.createElement(match.route.ErrorBoundary, null);
729 } else if (match.route.errorElement) {
730 errorElement = match.route.errorElement;
731 } else {
732 errorElement = /*#__PURE__*/React__namespace.createElement(DefaultErrorComponent, null);
733 }
734 }
735
736 let matches = parentMatches.concat(renderedMatches.slice(0, index + 1));
737
738 let getChildren = () => {
739 let children = outlet;
740
741 if (error) {
742 children = errorElement;
743 } else if (match.route.Component) {
744 children = /*#__PURE__*/React__namespace.createElement(match.route.Component, null);
745 } else if (match.route.element) {
746 children = match.route.element;
747 }
748
749 return /*#__PURE__*/React__namespace.createElement(RenderedRoute, {
750 match: match,
751 routeContext: {
752 outlet,
753 matches
754 },
755 children: children
756 });
757 }; // Only wrap in an error boundary within data router usages when we have an
758 // ErrorBoundary/errorElement on this route. Otherwise let it bubble up to
759 // an ancestor ErrorBoundary/errorElement
760
761
762 return dataRouterState && (match.route.ErrorBoundary || match.route.errorElement || index === 0) ? /*#__PURE__*/React__namespace.createElement(RenderErrorBoundary, {
763 location: dataRouterState.location,
764 component: errorElement,
765 error: error,
766 children: getChildren(),
767 routeContext: {
768 outlet: null,
769 matches
770 }
771 }) : getChildren();
772 }, null);
773 }
774 var DataRouterHook;
775
776 (function (DataRouterHook) {
777 DataRouterHook["UseBlocker"] = "useBlocker";
778 DataRouterHook["UseRevalidator"] = "useRevalidator";
779 })(DataRouterHook || (DataRouterHook = {}));
780
781 var DataRouterStateHook;
782
783 (function (DataRouterStateHook) {
784 DataRouterStateHook["UseBlocker"] = "useBlocker";
785 DataRouterStateHook["UseLoaderData"] = "useLoaderData";
786 DataRouterStateHook["UseActionData"] = "useActionData";
787 DataRouterStateHook["UseRouteError"] = "useRouteError";
788 DataRouterStateHook["UseNavigation"] = "useNavigation";
789 DataRouterStateHook["UseRouteLoaderData"] = "useRouteLoaderData";
790 DataRouterStateHook["UseMatches"] = "useMatches";
791 DataRouterStateHook["UseRevalidator"] = "useRevalidator";
792 })(DataRouterStateHook || (DataRouterStateHook = {}));
793
794 function getDataRouterConsoleError(hookName) {
795 return hookName + " must be used within a data router. See https://reactrouter.com/routers/picking-a-router.";
796 }
797
798 function useDataRouterContext(hookName) {
799 let ctx = React__namespace.useContext(DataRouterContext);
800 !ctx ? router.UNSAFE_invariant(false, getDataRouterConsoleError(hookName)) : void 0;
801 return ctx;
802 }
803
804 function useDataRouterState(hookName) {
805 let state = React__namespace.useContext(DataRouterStateContext);
806 !state ? router.UNSAFE_invariant(false, getDataRouterConsoleError(hookName)) : void 0;
807 return state;
808 }
809
810 function useRouteContext(hookName) {
811 let route = React__namespace.useContext(RouteContext);
812 !route ? router.UNSAFE_invariant(false, getDataRouterConsoleError(hookName)) : void 0;
813 return route;
814 }
815
816 function useCurrentRouteId(hookName) {
817 let route = useRouteContext(hookName);
818 let thisRoute = route.matches[route.matches.length - 1];
819 !thisRoute.route.id ? router.UNSAFE_invariant(false, hookName + " can only be used on routes that contain a unique \"id\"") : void 0;
820 return thisRoute.route.id;
821 }
822 /**
823 * Returns the current navigation, defaulting to an "idle" navigation when
824 * no navigation is in progress
825 */
826
827
828 function useNavigation() {
829 let state = useDataRouterState(DataRouterStateHook.UseNavigation);
830 return state.navigation;
831 }
832 /**
833 * Returns a revalidate function for manually triggering revalidation, as well
834 * as the current state of any manual revalidations
835 */
836
837 function useRevalidator() {
838 let dataRouterContext = useDataRouterContext(DataRouterHook.UseRevalidator);
839 let state = useDataRouterState(DataRouterStateHook.UseRevalidator);
840 return {
841 revalidate: dataRouterContext.router.revalidate,
842 state: state.revalidation
843 };
844 }
845 /**
846 * Returns the active route matches, useful for accessing loaderData for
847 * parent/child routes or the route "handle" property
848 */
849
850 function useMatches() {
851 let {
852 matches,
853 loaderData
854 } = useDataRouterState(DataRouterStateHook.UseMatches);
855 return React__namespace.useMemo(() => matches.map(match => {
856 let {
857 pathname,
858 params
859 } = match; // Note: This structure matches that created by createUseMatchesMatch
860 // in the @remix-run/router , so if you change this please also change
861 // that :) Eventually we'll DRY this up
862
863 return {
864 id: match.route.id,
865 pathname,
866 params,
867 data: loaderData[match.route.id],
868 handle: match.route.handle
869 };
870 }), [matches, loaderData]);
871 }
872 /**
873 * Returns the loader data for the nearest ancestor Route loader
874 */
875
876 function useLoaderData() {
877 let state = useDataRouterState(DataRouterStateHook.UseLoaderData);
878 let routeId = useCurrentRouteId(DataRouterStateHook.UseLoaderData);
879
880 if (state.errors && state.errors[routeId] != null) {
881 console.error("You cannot `useLoaderData` in an errorElement (routeId: " + routeId + ")");
882 return undefined;
883 }
884
885 return state.loaderData[routeId];
886 }
887 /**
888 * Returns the loaderData for the given routeId
889 */
890
891 function useRouteLoaderData(routeId) {
892 let state = useDataRouterState(DataRouterStateHook.UseRouteLoaderData);
893 return state.loaderData[routeId];
894 }
895 /**
896 * Returns the action data for the nearest ancestor Route action
897 */
898
899 function useActionData() {
900 let state = useDataRouterState(DataRouterStateHook.UseActionData);
901 let route = React__namespace.useContext(RouteContext);
902 !route ? router.UNSAFE_invariant(false, "useActionData must be used inside a RouteContext") : void 0;
903 return Object.values((state == null ? void 0 : state.actionData) || {})[0];
904 }
905 /**
906 * Returns the nearest ancestor Route error, which could be a loader/action
907 * error or a render error. This is intended to be called from your
908 * ErrorBoundary/errorElement to display a proper error message.
909 */
910
911 function useRouteError() {
912 var _state$errors;
913
914 let error = React__namespace.useContext(RouteErrorContext);
915 let state = useDataRouterState(DataRouterStateHook.UseRouteError);
916 let routeId = useCurrentRouteId(DataRouterStateHook.UseRouteError); // If this was a render error, we put it in a RouteError context inside
917 // of RenderErrorBoundary
918
919 if (error) {
920 return error;
921 } // Otherwise look for errors from our data router state
922
923
924 return (_state$errors = state.errors) == null ? void 0 : _state$errors[routeId];
925 }
926 /**
927 * Returns the happy-path data from the nearest ancestor <Await /> value
928 */
929
930 function useAsyncValue() {
931 let value = React__namespace.useContext(AwaitContext);
932 return value == null ? void 0 : value._data;
933 }
934 /**
935 * Returns the error from the nearest ancestor <Await /> value
936 */
937
938 function useAsyncError() {
939 let value = React__namespace.useContext(AwaitContext);
940 return value == null ? void 0 : value._error;
941 }
942 let blockerId = 0;
943 /**
944 * Allow the application to block navigations within the SPA and present the
945 * user a confirmation dialog to confirm the navigation. Mostly used to avoid
946 * using half-filled form data. This does not handle hard-reloads or
947 * cross-origin navigations.
948 */
949
950 function useBlocker(shouldBlock) {
951 let {
952 router
953 } = useDataRouterContext(DataRouterHook.UseBlocker);
954 let state = useDataRouterState(DataRouterStateHook.UseBlocker);
955 let [blockerKey] = React__namespace.useState(() => String(++blockerId));
956 let blockerFunction = React__namespace.useCallback(args => {
957 return typeof shouldBlock === "function" ? !!shouldBlock(args) : !!shouldBlock;
958 }, [shouldBlock]);
959 let blocker = router.getBlocker(blockerKey, blockerFunction); // Cleanup on unmount
960
961 React__namespace.useEffect(() => () => router.deleteBlocker(blockerKey), [router, blockerKey]); // Prefer the blocker from state since DataRouterContext is memoized so this
962 // ensures we update on blocker state updates
963
964 return state.blockers.get(blockerKey) || blocker;
965 }
966 const alreadyWarned = {};
967
968 function warningOnce(key, cond, message) {
969 if (!cond && !alreadyWarned[key]) {
970 alreadyWarned[key] = true;
971 router.UNSAFE_warning(false, message) ;
972 }
973 }
974
975 /**
976 * Given a Remix Router instance, render the appropriate UI
977 */
978 function RouterProvider(_ref) {
979 let {
980 fallbackElement,
981 router
982 } = _ref;
983 let getState = React__namespace.useCallback(() => router.state, [router]); // Sync router state to our component state to force re-renders
984
985 let state = useSyncExternalStore(router.subscribe, getState, // We have to provide this so React@18 doesn't complain during hydration,
986 // but we pass our serialized hydration data into the router so state here
987 // is already synced with what the server saw
988 getState);
989 let navigator = React__namespace.useMemo(() => {
990 return {
991 createHref: router.createHref,
992 encodeLocation: router.encodeLocation,
993 go: n => router.navigate(n),
994 push: (to, state, opts) => router.navigate(to, {
995 state,
996 preventScrollReset: opts == null ? void 0 : opts.preventScrollReset
997 }),
998 replace: (to, state, opts) => router.navigate(to, {
999 replace: true,
1000 state,
1001 preventScrollReset: opts == null ? void 0 : opts.preventScrollReset
1002 })
1003 };
1004 }, [router]);
1005 let basename = router.basename || "/";
1006 let dataRouterContext = React__namespace.useMemo(() => ({
1007 router,
1008 navigator,
1009 static: false,
1010 basename
1011 }), [router, navigator, basename]); // The fragment and {null} here are important! We need them to keep React 18's
1012 // useId happy when we are server-rendering since we may have a <script> here
1013 // containing the hydrated server-side staticContext (from StaticRouterProvider).
1014 // useId relies on the component tree structure to generate deterministic id's
1015 // so we need to ensure it remains the same on the client even though
1016 // we don't need the <script> tag
1017
1018 return /*#__PURE__*/React__namespace.createElement(React__namespace.Fragment, null, /*#__PURE__*/React__namespace.createElement(DataRouterContext.Provider, {
1019 value: dataRouterContext
1020 }, /*#__PURE__*/React__namespace.createElement(DataRouterStateContext.Provider, {
1021 value: state
1022 }, /*#__PURE__*/React__namespace.createElement(Router, {
1023 basename: router.basename,
1024 location: router.state.location,
1025 navigationType: router.state.historyAction,
1026 navigator: navigator
1027 }, router.state.initialized ? /*#__PURE__*/React__namespace.createElement(Routes, null) : fallbackElement))), null);
1028 }
1029
1030 /**
1031 * A <Router> that stores all entries in memory.
1032 *
1033 * @see https://reactrouter.com/router-components/memory-router
1034 */
1035 function MemoryRouter(_ref2) {
1036 let {
1037 basename,
1038 children,
1039 initialEntries,
1040 initialIndex
1041 } = _ref2;
1042 let historyRef = React__namespace.useRef();
1043
1044 if (historyRef.current == null) {
1045 historyRef.current = router.createMemoryHistory({
1046 initialEntries,
1047 initialIndex,
1048 v5Compat: true
1049 });
1050 }
1051
1052 let history = historyRef.current;
1053 let [state, setState] = React__namespace.useState({
1054 action: history.action,
1055 location: history.location
1056 });
1057 React__namespace.useLayoutEffect(() => history.listen(setState), [history]);
1058 return /*#__PURE__*/React__namespace.createElement(Router, {
1059 basename: basename,
1060 children: children,
1061 location: state.location,
1062 navigationType: state.action,
1063 navigator: history
1064 });
1065 }
1066
1067 /**
1068 * Changes the current location.
1069 *
1070 * Note: This API is mostly useful in React.Component subclasses that are not
1071 * able to use hooks. In functional components, we recommend you use the
1072 * `useNavigate` hook instead.
1073 *
1074 * @see https://reactrouter.com/components/navigate
1075 */
1076 function Navigate(_ref3) {
1077 let {
1078 to,
1079 replace,
1080 state,
1081 relative
1082 } = _ref3;
1083 !useInRouterContext() ? router.UNSAFE_invariant(false, // TODO: This error is probably because they somehow have 2 versions of
1084 // the router loaded. We can help them understand how to avoid that.
1085 "<Navigate> may be used only in the context of a <Router> component.") : void 0;
1086 router.UNSAFE_warning(!React__namespace.useContext(NavigationContext).static, "<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.") ;
1087 let dataRouterState = React__namespace.useContext(DataRouterStateContext);
1088 let navigate = useNavigate();
1089 React__namespace.useEffect(() => {
1090 // Avoid kicking off multiple navigations if we're in the middle of a
1091 // data-router navigation, since components get re-rendered when we enter
1092 // a submitting/loading state
1093 if (dataRouterState && dataRouterState.navigation.state !== "idle") {
1094 return;
1095 }
1096
1097 navigate(to, {
1098 replace,
1099 state,
1100 relative
1101 });
1102 });
1103 return null;
1104 }
1105
1106 /**
1107 * Renders the child route's element, if there is one.
1108 *
1109 * @see https://reactrouter.com/components/outlet
1110 */
1111 function Outlet(props) {
1112 return useOutlet(props.context);
1113 }
1114
1115 /**
1116 * Declares an element that should be rendered at a certain URL path.
1117 *
1118 * @see https://reactrouter.com/components/route
1119 */
1120 function Route(_props) {
1121 router.UNSAFE_invariant(false, "A <Route> is only ever to be used as the child of <Routes> element, " + "never rendered directly. Please wrap your <Route> in a <Routes>.") ;
1122 }
1123
1124 /**
1125 * Provides location context for the rest of the app.
1126 *
1127 * Note: You usually won't render a <Router> directly. Instead, you'll render a
1128 * router that is more specific to your environment such as a <BrowserRouter>
1129 * in web browsers or a <StaticRouter> for server rendering.
1130 *
1131 * @see https://reactrouter.com/router-components/router
1132 */
1133 function Router(_ref4) {
1134 let {
1135 basename: basenameProp = "/",
1136 children = null,
1137 location: locationProp,
1138 navigationType = router.Action.Pop,
1139 navigator,
1140 static: staticProp = false
1141 } = _ref4;
1142 !!useInRouterContext() ? router.UNSAFE_invariant(false, "You cannot render a <Router> inside another <Router>." + " You should never have more than one in your app.") : void 0; // Preserve trailing slashes on basename, so we can let the user control
1143 // the enforcement of trailing slashes throughout the app
1144
1145 let basename = basenameProp.replace(/^\/*/, "/");
1146 let navigationContext = React__namespace.useMemo(() => ({
1147 basename,
1148 navigator,
1149 static: staticProp
1150 }), [basename, navigator, staticProp]);
1151
1152 if (typeof locationProp === "string") {
1153 locationProp = router.parsePath(locationProp);
1154 }
1155
1156 let {
1157 pathname = "/",
1158 search = "",
1159 hash = "",
1160 state = null,
1161 key = "default"
1162 } = locationProp;
1163 let locationContext = React__namespace.useMemo(() => {
1164 let trailingPathname = router.stripBasename(pathname, basename);
1165
1166 if (trailingPathname == null) {
1167 return null;
1168 }
1169
1170 return {
1171 location: {
1172 pathname: trailingPathname,
1173 search,
1174 hash,
1175 state,
1176 key
1177 },
1178 navigationType
1179 };
1180 }, [basename, pathname, search, hash, state, key, navigationType]);
1181 router.UNSAFE_warning(locationContext != null, "<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.") ;
1182
1183 if (locationContext == null) {
1184 return null;
1185 }
1186
1187 return /*#__PURE__*/React__namespace.createElement(NavigationContext.Provider, {
1188 value: navigationContext
1189 }, /*#__PURE__*/React__namespace.createElement(LocationContext.Provider, {
1190 children: children,
1191 value: locationContext
1192 }));
1193 }
1194
1195 /**
1196 * A container for a nested tree of <Route> elements that renders the branch
1197 * that best matches the current location.
1198 *
1199 * @see https://reactrouter.com/components/routes
1200 */
1201 function Routes(_ref5) {
1202 let {
1203 children,
1204 location
1205 } = _ref5;
1206 let dataRouterContext = React__namespace.useContext(DataRouterContext); // When in a DataRouterContext _without_ children, we use the router routes
1207 // directly. If we have children, then we're in a descendant tree and we
1208 // need to use child routes.
1209
1210 let routes = dataRouterContext && !children ? dataRouterContext.router.routes : createRoutesFromChildren(children);
1211 return useRoutes(routes, location);
1212 }
1213
1214 /**
1215 * Component to use for rendering lazily loaded data from returning defer()
1216 * in a loader function
1217 */
1218 function Await(_ref6) {
1219 let {
1220 children,
1221 errorElement,
1222 resolve
1223 } = _ref6;
1224 return /*#__PURE__*/React__namespace.createElement(AwaitErrorBoundary, {
1225 resolve: resolve,
1226 errorElement: errorElement
1227 }, /*#__PURE__*/React__namespace.createElement(ResolveAwait, null, children));
1228 }
1229 var AwaitRenderStatus;
1230
1231 (function (AwaitRenderStatus) {
1232 AwaitRenderStatus[AwaitRenderStatus["pending"] = 0] = "pending";
1233 AwaitRenderStatus[AwaitRenderStatus["success"] = 1] = "success";
1234 AwaitRenderStatus[AwaitRenderStatus["error"] = 2] = "error";
1235 })(AwaitRenderStatus || (AwaitRenderStatus = {}));
1236
1237 const neverSettledPromise = new Promise(() => {});
1238
1239 class AwaitErrorBoundary extends React__namespace.Component {
1240 constructor(props) {
1241 super(props);
1242 this.state = {
1243 error: null
1244 };
1245 }
1246
1247 static getDerivedStateFromError(error) {
1248 return {
1249 error
1250 };
1251 }
1252
1253 componentDidCatch(error, errorInfo) {
1254 console.error("<Await> caught the following error during render", error, errorInfo);
1255 }
1256
1257 render() {
1258 let {
1259 children,
1260 errorElement,
1261 resolve
1262 } = this.props;
1263 let promise = null;
1264 let status = AwaitRenderStatus.pending;
1265
1266 if (!(resolve instanceof Promise)) {
1267 // Didn't get a promise - provide as a resolved promise
1268 status = AwaitRenderStatus.success;
1269 promise = Promise.resolve();
1270 Object.defineProperty(promise, "_tracked", {
1271 get: () => true
1272 });
1273 Object.defineProperty(promise, "_data", {
1274 get: () => resolve
1275 });
1276 } else if (this.state.error) {
1277 // Caught a render error, provide it as a rejected promise
1278 status = AwaitRenderStatus.error;
1279 let renderError = this.state.error;
1280 promise = Promise.reject().catch(() => {}); // Avoid unhandled rejection warnings
1281
1282 Object.defineProperty(promise, "_tracked", {
1283 get: () => true
1284 });
1285 Object.defineProperty(promise, "_error", {
1286 get: () => renderError
1287 });
1288 } else if (resolve._tracked) {
1289 // Already tracked promise - check contents
1290 promise = resolve;
1291 status = promise._error !== undefined ? AwaitRenderStatus.error : promise._data !== undefined ? AwaitRenderStatus.success : AwaitRenderStatus.pending;
1292 } else {
1293 // Raw (untracked) promise - track it
1294 status = AwaitRenderStatus.pending;
1295 Object.defineProperty(resolve, "_tracked", {
1296 get: () => true
1297 });
1298 promise = resolve.then(data => Object.defineProperty(resolve, "_data", {
1299 get: () => data
1300 }), error => Object.defineProperty(resolve, "_error", {
1301 get: () => error
1302 }));
1303 }
1304
1305 if (status === AwaitRenderStatus.error && promise._error instanceof router.AbortedDeferredError) {
1306 // Freeze the UI by throwing a never resolved promise
1307 throw neverSettledPromise;
1308 }
1309
1310 if (status === AwaitRenderStatus.error && !errorElement) {
1311 // No errorElement, throw to the nearest route-level error boundary
1312 throw promise._error;
1313 }
1314
1315 if (status === AwaitRenderStatus.error) {
1316 // Render via our errorElement
1317 return /*#__PURE__*/React__namespace.createElement(AwaitContext.Provider, {
1318 value: promise,
1319 children: errorElement
1320 });
1321 }
1322
1323 if (status === AwaitRenderStatus.success) {
1324 // Render children with resolved value
1325 return /*#__PURE__*/React__namespace.createElement(AwaitContext.Provider, {
1326 value: promise,
1327 children: children
1328 });
1329 } // Throw to the suspense boundary
1330
1331
1332 throw promise;
1333 }
1334
1335 }
1336 /**
1337 * @private
1338 * Indirection to leverage useAsyncValue for a render-prop API on <Await>
1339 */
1340
1341
1342 function ResolveAwait(_ref7) {
1343 let {
1344 children
1345 } = _ref7;
1346 let data = useAsyncValue();
1347 let toRender = typeof children === "function" ? children(data) : children;
1348 return /*#__PURE__*/React__namespace.createElement(React__namespace.Fragment, null, toRender);
1349 } ///////////////////////////////////////////////////////////////////////////////
1350 // UTILS
1351 ///////////////////////////////////////////////////////////////////////////////
1352
1353 /**
1354 * Creates a route config from a React "children" object, which is usually
1355 * either a `<Route>` element or an array of them. Used internally by
1356 * `<Routes>` to create a route config from its children.
1357 *
1358 * @see https://reactrouter.com/utils/create-routes-from-children
1359 */
1360
1361
1362 function createRoutesFromChildren(children, parentPath) {
1363 if (parentPath === void 0) {
1364 parentPath = [];
1365 }
1366
1367 let routes = [];
1368 React__namespace.Children.forEach(children, (element, index) => {
1369 if (! /*#__PURE__*/React__namespace.isValidElement(element)) {
1370 // Ignore non-elements. This allows people to more easily inline
1371 // conditionals in their route config.
1372 return;
1373 }
1374
1375 if (element.type === React__namespace.Fragment) {
1376 // Transparently support React.Fragment and its children.
1377 routes.push.apply(routes, createRoutesFromChildren(element.props.children, parentPath));
1378 return;
1379 }
1380
1381 !(element.type === Route) ? router.UNSAFE_invariant(false, "[" + (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>") : void 0;
1382 !(!element.props.index || !element.props.children) ? router.UNSAFE_invariant(false, "An index route cannot have child routes.") : void 0;
1383 let treePath = [...parentPath, index];
1384 let route = {
1385 id: element.props.id || treePath.join("-"),
1386 caseSensitive: element.props.caseSensitive,
1387 element: element.props.element,
1388 Component: element.props.Component,
1389 index: element.props.index,
1390 path: element.props.path,
1391 loader: element.props.loader,
1392 action: element.props.action,
1393 errorElement: element.props.errorElement,
1394 ErrorBoundary: element.props.ErrorBoundary,
1395 hasErrorBoundary: element.props.ErrorBoundary != null || element.props.errorElement != null,
1396 shouldRevalidate: element.props.shouldRevalidate,
1397 handle: element.props.handle,
1398 lazy: element.props.lazy
1399 };
1400
1401 if (element.props.children) {
1402 route.children = createRoutesFromChildren(element.props.children, treePath);
1403 }
1404
1405 routes.push(route);
1406 });
1407 return routes;
1408 }
1409 /**
1410 * Renders the result of `matchRoutes()` into a React element.
1411 */
1412
1413 function renderMatches(matches) {
1414 return _renderMatches(matches);
1415 }
1416
1417 function detectErrorBoundary(route) {
1418 {
1419 if (route.Component && route.element) {
1420 router.UNSAFE_warning(false, "You should not include both `Component` and `element` on your route - " + "`element` will be ignored.") ;
1421 }
1422
1423 if (route.ErrorBoundary && route.errorElement) {
1424 router.UNSAFE_warning(false, "You should not include both `ErrorBoundary` and `errorElement` on your route - " + "`errorElement` will be ignored.") ;
1425 }
1426 } // Note: this check also occurs in createRoutesFromChildren so update
1427 // there if you change this
1428
1429
1430 return Boolean(route.ErrorBoundary) || Boolean(route.errorElement);
1431 }
1432
1433 function createMemoryRouter(routes, opts) {
1434 return router.createRouter({
1435 basename: opts == null ? void 0 : opts.basename,
1436 history: router.createMemoryHistory({
1437 initialEntries: opts == null ? void 0 : opts.initialEntries,
1438 initialIndex: opts == null ? void 0 : opts.initialIndex
1439 }),
1440 hydrationData: opts == null ? void 0 : opts.hydrationData,
1441 routes,
1442 detectErrorBoundary
1443 }).initialize();
1444 } ///////////////////////////////////////////////////////////////////////////////
1445
1446 Object.defineProperty(exports, 'AbortedDeferredError', {
1447 enumerable: true,
1448 get: function () { return router.AbortedDeferredError; }
1449 });
1450 Object.defineProperty(exports, 'NavigationType', {
1451 enumerable: true,
1452 get: function () { return router.Action; }
1453 });
1454 Object.defineProperty(exports, 'createPath', {
1455 enumerable: true,
1456 get: function () { return router.createPath; }
1457 });
1458 Object.defineProperty(exports, 'defer', {
1459 enumerable: true,
1460 get: function () { return router.defer; }
1461 });
1462 Object.defineProperty(exports, 'generatePath', {
1463 enumerable: true,
1464 get: function () { return router.generatePath; }
1465 });
1466 Object.defineProperty(exports, 'isRouteErrorResponse', {
1467 enumerable: true,
1468 get: function () { return router.isRouteErrorResponse; }
1469 });
1470 Object.defineProperty(exports, 'json', {
1471 enumerable: true,
1472 get: function () { return router.json; }
1473 });
1474 Object.defineProperty(exports, 'matchPath', {
1475 enumerable: true,
1476 get: function () { return router.matchPath; }
1477 });
1478 Object.defineProperty(exports, 'matchRoutes', {
1479 enumerable: true,
1480 get: function () { return router.matchRoutes; }
1481 });
1482 Object.defineProperty(exports, 'parsePath', {
1483 enumerable: true,
1484 get: function () { return router.parsePath; }
1485 });
1486 Object.defineProperty(exports, 'redirect', {
1487 enumerable: true,
1488 get: function () { return router.redirect; }
1489 });
1490 Object.defineProperty(exports, 'resolvePath', {
1491 enumerable: true,
1492 get: function () { return router.resolvePath; }
1493 });
1494 exports.Await = Await;
1495 exports.MemoryRouter = MemoryRouter;
1496 exports.Navigate = Navigate;
1497 exports.Outlet = Outlet;
1498 exports.Route = Route;
1499 exports.Router = Router;
1500 exports.RouterProvider = RouterProvider;
1501 exports.Routes = Routes;
1502 exports.UNSAFE_DataRouterContext = DataRouterContext;
1503 exports.UNSAFE_DataRouterStateContext = DataRouterStateContext;
1504 exports.UNSAFE_LocationContext = LocationContext;
1505 exports.UNSAFE_NavigationContext = NavigationContext;
1506 exports.UNSAFE_RouteContext = RouteContext;
1507 exports.UNSAFE_detectErrorBoundary = detectErrorBoundary;
1508 exports.createMemoryRouter = createMemoryRouter;
1509 exports.createRoutesFromChildren = createRoutesFromChildren;
1510 exports.createRoutesFromElements = createRoutesFromChildren;
1511 exports.renderMatches = renderMatches;
1512 exports.unstable_useBlocker = useBlocker;
1513 exports.useActionData = useActionData;
1514 exports.useAsyncError = useAsyncError;
1515 exports.useAsyncValue = useAsyncValue;
1516 exports.useHref = useHref;
1517 exports.useInRouterContext = useInRouterContext;
1518 exports.useLoaderData = useLoaderData;
1519 exports.useLocation = useLocation;
1520 exports.useMatch = useMatch;
1521 exports.useMatches = useMatches;
1522 exports.useNavigate = useNavigate;
1523 exports.useNavigation = useNavigation;
1524 exports.useNavigationType = useNavigationType;
1525 exports.useOutlet = useOutlet;
1526 exports.useOutletContext = useOutletContext;
1527 exports.useParams = useParams;
1528 exports.useResolvedPath = useResolvedPath;
1529 exports.useRevalidator = useRevalidator;
1530 exports.useRouteError = useRouteError;
1531 exports.useRouteLoaderData = useRouteLoaderData;
1532 exports.useRoutes = useRoutes;
1533
1534 Object.defineProperty(exports, '__esModule', { value: true });
1535
1536}));
1537//# sourceMappingURL=react-router.development.js.map