UNPKG

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