UNPKG

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