UNPKG

58.2 kBJavaScriptView Raw
1/**
2 * React Router v6.16.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 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 route = React__namespace.useContext(RouteContext);
724 !route ? router.UNSAFE_invariant(false, "useActionData must be used inside a RouteContext") : void 0;
725 return Object.values((state == null ? void 0 : state.actionData) || {})[0];
726 }
727
728 /**
729 * Returns the nearest ancestor Route error, which could be a loader/action
730 * error or a render error. This is intended to be called from your
731 * ErrorBoundary/errorElement to display a proper error message.
732 */
733 function useRouteError() {
734 var _state$errors;
735 let error = React__namespace.useContext(RouteErrorContext);
736 let state = useDataRouterState(DataRouterStateHook.UseRouteError);
737 let routeId = useCurrentRouteId(DataRouterStateHook.UseRouteError);
738
739 // If this was a render error, we put it in a RouteError context inside
740 // of RenderErrorBoundary
741 if (error) {
742 return error;
743 }
744
745 // Otherwise look for errors from our data router state
746 return (_state$errors = state.errors) == null ? void 0 : _state$errors[routeId];
747 }
748
749 /**
750 * Returns the happy-path data from the nearest ancestor <Await /> value
751 */
752 function useAsyncValue() {
753 let value = React__namespace.useContext(AwaitContext);
754 return value == null ? void 0 : value._data;
755 }
756
757 /**
758 * Returns the error from the nearest ancestor <Await /> value
759 */
760 function useAsyncError() {
761 let value = React__namespace.useContext(AwaitContext);
762 return value == null ? void 0 : value._error;
763 }
764 let blockerId = 0;
765
766 /**
767 * Allow the application to block navigations within the SPA and present the
768 * user a confirmation dialog to confirm the navigation. Mostly used to avoid
769 * using half-filled form data. This does not handle hard-reloads or
770 * cross-origin navigations.
771 */
772 function useBlocker(shouldBlock) {
773 let {
774 router: router$1,
775 basename
776 } = useDataRouterContext(DataRouterHook.UseBlocker);
777 let state = useDataRouterState(DataRouterStateHook.UseBlocker);
778 let [blockerKey, setBlockerKey] = React__namespace.useState("");
779 let blockerFunction = React__namespace.useCallback(arg => {
780 if (typeof shouldBlock !== "function") {
781 return !!shouldBlock;
782 }
783 if (basename === "/") {
784 return shouldBlock(arg);
785 }
786
787 // If they provided us a function and we've got an active basename, strip
788 // it from the locations we expose to the user to match the behavior of
789 // useLocation
790 let {
791 currentLocation,
792 nextLocation,
793 historyAction
794 } = arg;
795 return shouldBlock({
796 currentLocation: _extends({}, currentLocation, {
797 pathname: router.stripBasename(currentLocation.pathname, basename) || currentLocation.pathname
798 }),
799 nextLocation: _extends({}, nextLocation, {
800 pathname: router.stripBasename(nextLocation.pathname, basename) || nextLocation.pathname
801 }),
802 historyAction
803 });
804 }, [basename, shouldBlock]);
805
806 // This effect is in charge of blocker key assignment and deletion (which is
807 // tightly coupled to the key)
808 React__namespace.useEffect(() => {
809 let key = String(++blockerId);
810 setBlockerKey(key);
811 return () => router$1.deleteBlocker(key);
812 }, [router$1]);
813
814 // This effect handles assigning the blockerFunction. This is to handle
815 // unstable blocker function identities, and happens only after the prior
816 // effect so we don't get an orphaned blockerFunction in the router with a
817 // key of "". Until then we just have the IDLE_BLOCKER.
818 React__namespace.useEffect(() => {
819 if (blockerKey !== "") {
820 router$1.getBlocker(blockerKey, blockerFunction);
821 }
822 }, [router$1, blockerKey, blockerFunction]);
823
824 // Prefer the blocker from `state` not `router.state` since DataRouterContext
825 // is memoized so this ensures we update on blocker state updates
826 return blockerKey && state.blockers.has(blockerKey) ? state.blockers.get(blockerKey) : router.IDLE_BLOCKER;
827 }
828
829 /**
830 * Stable version of useNavigate that is used when we are in the context of
831 * a RouterProvider.
832 */
833 function useNavigateStable() {
834 let {
835 router: router$1
836 } = useDataRouterContext(DataRouterHook.UseNavigateStable);
837 let id = useCurrentRouteId(DataRouterStateHook.UseNavigateStable);
838 let activeRef = React__namespace.useRef(false);
839 useIsomorphicLayoutEffect(() => {
840 activeRef.current = true;
841 });
842 let navigate = React__namespace.useCallback(function (to, options) {
843 if (options === void 0) {
844 options = {};
845 }
846 router.UNSAFE_warning(activeRef.current, navigateEffectWarning) ;
847
848 // Short circuit here since if this happens on first render the navigate
849 // is useless because we haven't wired up our router subscriber yet
850 if (!activeRef.current) return;
851 if (typeof to === "number") {
852 router$1.navigate(to);
853 } else {
854 router$1.navigate(to, _extends({
855 fromRouteId: id
856 }, options));
857 }
858 }, [router$1, id]);
859 return navigate;
860 }
861 const alreadyWarned = {};
862 function warningOnce(key, cond, message) {
863 if (!cond && !alreadyWarned[key]) {
864 alreadyWarned[key] = true;
865 router.UNSAFE_warning(false, message) ;
866 }
867 }
868
869 /**
870 Webpack + React 17 fails to compile on any of the following because webpack
871 complains that `startTransition` doesn't exist in `React`:
872 * import { startTransition } from "react"
873 * import * as React from from "react";
874 "startTransition" in React ? React.startTransition(() => setState()) : setState()
875 * import * as React from from "react";
876 "startTransition" in React ? React["startTransition"](() => setState()) : setState()
877
878 Moving it to a constant such as the following solves the Webpack/React 17 issue:
879 * import * as React from from "react";
880 const START_TRANSITION = "startTransition";
881 START_TRANSITION in React ? React[START_TRANSITION](() => setState()) : setState()
882
883 However, that introduces webpack/terser minification issues in production builds
884 in React 18 where minification/obfuscation ends up removing the call of
885 React.startTransition entirely from the first half of the ternary. Grabbing
886 this exported reference once up front resolves that issue.
887
888 See https://github.com/remix-run/react-router/issues/10579
889 */
890 const START_TRANSITION = "startTransition";
891 const startTransitionImpl = React__namespace[START_TRANSITION];
892
893 /**
894 * Given a Remix Router instance, render the appropriate UI
895 */
896 function RouterProvider(_ref) {
897 let {
898 fallbackElement,
899 router,
900 future
901 } = _ref;
902 // Need to use a layout effect here so we are subscribed early enough to
903 // pick up on any render-driven redirects/navigations (useEffect/<Navigate>)
904 let [state, setStateImpl] = React__namespace.useState(router.state);
905 let {
906 v7_startTransition
907 } = future || {};
908 let setState = React__namespace.useCallback(newState => {
909 v7_startTransition && startTransitionImpl ? startTransitionImpl(() => setStateImpl(newState)) : setStateImpl(newState);
910 }, [setStateImpl, v7_startTransition]);
911 React__namespace.useLayoutEffect(() => router.subscribe(setState), [router, setState]);
912 let navigator = React__namespace.useMemo(() => {
913 return {
914 createHref: router.createHref,
915 encodeLocation: router.encodeLocation,
916 go: n => router.navigate(n),
917 push: (to, state, opts) => router.navigate(to, {
918 state,
919 preventScrollReset: opts == null ? void 0 : opts.preventScrollReset
920 }),
921 replace: (to, state, opts) => router.navigate(to, {
922 replace: true,
923 state,
924 preventScrollReset: opts == null ? void 0 : opts.preventScrollReset
925 })
926 };
927 }, [router]);
928 let basename = router.basename || "/";
929 let dataRouterContext = React__namespace.useMemo(() => ({
930 router,
931 navigator,
932 static: false,
933 basename
934 }), [router, navigator, basename]);
935
936 // The fragment and {null} here are important! We need them to keep React 18's
937 // useId happy when we are server-rendering since we may have a <script> here
938 // containing the hydrated server-side staticContext (from StaticRouterProvider).
939 // useId relies on the component tree structure to generate deterministic id's
940 // so we need to ensure it remains the same on the client even though
941 // we don't need the <script> tag
942 return /*#__PURE__*/React__namespace.createElement(React__namespace.Fragment, null, /*#__PURE__*/React__namespace.createElement(DataRouterContext.Provider, {
943 value: dataRouterContext
944 }, /*#__PURE__*/React__namespace.createElement(DataRouterStateContext.Provider, {
945 value: state
946 }, /*#__PURE__*/React__namespace.createElement(Router, {
947 basename: basename,
948 location: state.location,
949 navigationType: state.historyAction,
950 navigator: navigator
951 }, state.initialized ? /*#__PURE__*/React__namespace.createElement(DataRoutes, {
952 routes: router.routes,
953 state: state
954 }) : fallbackElement))), null);
955 }
956 function DataRoutes(_ref2) {
957 let {
958 routes,
959 state
960 } = _ref2;
961 return useRoutesImpl(routes, undefined, state);
962 }
963 /**
964 * A <Router> that stores all entries in memory.
965 *
966 * @see https://reactrouter.com/router-components/memory-router
967 */
968 function MemoryRouter(_ref3) {
969 let {
970 basename,
971 children,
972 initialEntries,
973 initialIndex,
974 future
975 } = _ref3;
976 let historyRef = React__namespace.useRef();
977 if (historyRef.current == null) {
978 historyRef.current = router.createMemoryHistory({
979 initialEntries,
980 initialIndex,
981 v5Compat: true
982 });
983 }
984 let history = historyRef.current;
985 let [state, setStateImpl] = React__namespace.useState({
986 action: history.action,
987 location: history.location
988 });
989 let {
990 v7_startTransition
991 } = future || {};
992 let setState = React__namespace.useCallback(newState => {
993 v7_startTransition && startTransitionImpl ? startTransitionImpl(() => setStateImpl(newState)) : setStateImpl(newState);
994 }, [setStateImpl, v7_startTransition]);
995 React__namespace.useLayoutEffect(() => history.listen(setState), [history, setState]);
996 return /*#__PURE__*/React__namespace.createElement(Router, {
997 basename: basename,
998 children: children,
999 location: state.location,
1000 navigationType: state.action,
1001 navigator: history
1002 });
1003 }
1004 /**
1005 * Changes the current location.
1006 *
1007 * Note: This API is mostly useful in React.Component subclasses that are not
1008 * able to use hooks. In functional components, we recommend you use the
1009 * `useNavigate` hook instead.
1010 *
1011 * @see https://reactrouter.com/components/navigate
1012 */
1013 function Navigate(_ref4) {
1014 let {
1015 to,
1016 replace,
1017 state,
1018 relative
1019 } = _ref4;
1020 !useInRouterContext() ? router.UNSAFE_invariant(false, // TODO: This error is probably because they somehow have 2 versions of
1021 // the router loaded. We can help them understand how to avoid that.
1022 "<Navigate> may be used only in the context of a <Router> component.") : void 0;
1023 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.") ;
1024 let {
1025 matches
1026 } = React__namespace.useContext(RouteContext);
1027 let {
1028 pathname: locationPathname
1029 } = useLocation();
1030 let navigate = useNavigate();
1031
1032 // Resolve the path outside of the effect so that when effects run twice in
1033 // StrictMode they navigate to the same place
1034 let path = router.resolveTo(to, router.UNSAFE_getPathContributingMatches(matches).map(match => match.pathnameBase), locationPathname, relative === "path");
1035 let jsonPath = JSON.stringify(path);
1036 React__namespace.useEffect(() => navigate(JSON.parse(jsonPath), {
1037 replace,
1038 state,
1039 relative
1040 }), [navigate, jsonPath, relative, replace, state]);
1041 return null;
1042 }
1043 /**
1044 * Renders the child route's element, if there is one.
1045 *
1046 * @see https://reactrouter.com/components/outlet
1047 */
1048 function Outlet(props) {
1049 return useOutlet(props.context);
1050 }
1051 /**
1052 * Declares an element that should be rendered at a certain URL path.
1053 *
1054 * @see https://reactrouter.com/components/route
1055 */
1056 function Route(_props) {
1057 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>.") ;
1058 }
1059 /**
1060 * Provides location context for the rest of the app.
1061 *
1062 * Note: You usually won't render a <Router> directly. Instead, you'll render a
1063 * router that is more specific to your environment such as a <BrowserRouter>
1064 * in web browsers or a <StaticRouter> for server rendering.
1065 *
1066 * @see https://reactrouter.com/router-components/router
1067 */
1068 function Router(_ref5) {
1069 let {
1070 basename: basenameProp = "/",
1071 children = null,
1072 location: locationProp,
1073 navigationType = router.Action.Pop,
1074 navigator,
1075 static: staticProp = false
1076 } = _ref5;
1077 !!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;
1078
1079 // Preserve trailing slashes on basename, so we can let the user control
1080 // the enforcement of trailing slashes throughout the app
1081 let basename = basenameProp.replace(/^\/*/, "/");
1082 let navigationContext = React__namespace.useMemo(() => ({
1083 basename,
1084 navigator,
1085 static: staticProp
1086 }), [basename, navigator, staticProp]);
1087 if (typeof locationProp === "string") {
1088 locationProp = router.parsePath(locationProp);
1089 }
1090 let {
1091 pathname = "/",
1092 search = "",
1093 hash = "",
1094 state = null,
1095 key = "default"
1096 } = locationProp;
1097 let locationContext = React__namespace.useMemo(() => {
1098 let trailingPathname = router.stripBasename(pathname, basename);
1099 if (trailingPathname == null) {
1100 return null;
1101 }
1102 return {
1103 location: {
1104 pathname: trailingPathname,
1105 search,
1106 hash,
1107 state,
1108 key
1109 },
1110 navigationType
1111 };
1112 }, [basename, pathname, search, hash, state, key, navigationType]);
1113 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.") ;
1114 if (locationContext == null) {
1115 return null;
1116 }
1117 return /*#__PURE__*/React__namespace.createElement(NavigationContext.Provider, {
1118 value: navigationContext
1119 }, /*#__PURE__*/React__namespace.createElement(LocationContext.Provider, {
1120 children: children,
1121 value: locationContext
1122 }));
1123 }
1124 /**
1125 * A container for a nested tree of <Route> elements that renders the branch
1126 * that best matches the current location.
1127 *
1128 * @see https://reactrouter.com/components/routes
1129 */
1130 function Routes(_ref6) {
1131 let {
1132 children,
1133 location
1134 } = _ref6;
1135 return useRoutes(createRoutesFromChildren(children), location);
1136 }
1137 /**
1138 * Component to use for rendering lazily loaded data from returning defer()
1139 * in a loader function
1140 */
1141 function Await(_ref7) {
1142 let {
1143 children,
1144 errorElement,
1145 resolve
1146 } = _ref7;
1147 return /*#__PURE__*/React__namespace.createElement(AwaitErrorBoundary, {
1148 resolve: resolve,
1149 errorElement: errorElement
1150 }, /*#__PURE__*/React__namespace.createElement(ResolveAwait, null, children));
1151 }
1152 var AwaitRenderStatus = /*#__PURE__*/function (AwaitRenderStatus) {
1153 AwaitRenderStatus[AwaitRenderStatus["pending"] = 0] = "pending";
1154 AwaitRenderStatus[AwaitRenderStatus["success"] = 1] = "success";
1155 AwaitRenderStatus[AwaitRenderStatus["error"] = 2] = "error";
1156 return AwaitRenderStatus;
1157 }(AwaitRenderStatus || {});
1158 const neverSettledPromise = new Promise(() => {});
1159 class AwaitErrorBoundary extends React__namespace.Component {
1160 constructor(props) {
1161 super(props);
1162 this.state = {
1163 error: null
1164 };
1165 }
1166 static getDerivedStateFromError(error) {
1167 return {
1168 error
1169 };
1170 }
1171 componentDidCatch(error, errorInfo) {
1172 console.error("<Await> caught the following error during render", error, errorInfo);
1173 }
1174 render() {
1175 let {
1176 children,
1177 errorElement,
1178 resolve
1179 } = this.props;
1180 let promise = null;
1181 let status = AwaitRenderStatus.pending;
1182 if (!(resolve instanceof Promise)) {
1183 // Didn't get a promise - provide as a resolved promise
1184 status = AwaitRenderStatus.success;
1185 promise = Promise.resolve();
1186 Object.defineProperty(promise, "_tracked", {
1187 get: () => true
1188 });
1189 Object.defineProperty(promise, "_data", {
1190 get: () => resolve
1191 });
1192 } else if (this.state.error) {
1193 // Caught a render error, provide it as a rejected promise
1194 status = AwaitRenderStatus.error;
1195 let renderError = this.state.error;
1196 promise = Promise.reject().catch(() => {}); // Avoid unhandled rejection warnings
1197 Object.defineProperty(promise, "_tracked", {
1198 get: () => true
1199 });
1200 Object.defineProperty(promise, "_error", {
1201 get: () => renderError
1202 });
1203 } else if (resolve._tracked) {
1204 // Already tracked promise - check contents
1205 promise = resolve;
1206 status = promise._error !== undefined ? AwaitRenderStatus.error : promise._data !== undefined ? AwaitRenderStatus.success : AwaitRenderStatus.pending;
1207 } else {
1208 // Raw (untracked) promise - track it
1209 status = AwaitRenderStatus.pending;
1210 Object.defineProperty(resolve, "_tracked", {
1211 get: () => true
1212 });
1213 promise = resolve.then(data => Object.defineProperty(resolve, "_data", {
1214 get: () => data
1215 }), error => Object.defineProperty(resolve, "_error", {
1216 get: () => error
1217 }));
1218 }
1219 if (status === AwaitRenderStatus.error && promise._error instanceof router.AbortedDeferredError) {
1220 // Freeze the UI by throwing a never resolved promise
1221 throw neverSettledPromise;
1222 }
1223 if (status === AwaitRenderStatus.error && !errorElement) {
1224 // No errorElement, throw to the nearest route-level error boundary
1225 throw promise._error;
1226 }
1227 if (status === AwaitRenderStatus.error) {
1228 // Render via our errorElement
1229 return /*#__PURE__*/React__namespace.createElement(AwaitContext.Provider, {
1230 value: promise,
1231 children: errorElement
1232 });
1233 }
1234 if (status === AwaitRenderStatus.success) {
1235 // Render children with resolved value
1236 return /*#__PURE__*/React__namespace.createElement(AwaitContext.Provider, {
1237 value: promise,
1238 children: children
1239 });
1240 }
1241
1242 // Throw to the suspense boundary
1243 throw promise;
1244 }
1245 }
1246
1247 /**
1248 * @private
1249 * Indirection to leverage useAsyncValue for a render-prop API on <Await>
1250 */
1251 function ResolveAwait(_ref8) {
1252 let {
1253 children
1254 } = _ref8;
1255 let data = useAsyncValue();
1256 let toRender = typeof children === "function" ? children(data) : children;
1257 return /*#__PURE__*/React__namespace.createElement(React__namespace.Fragment, null, toRender);
1258 }
1259
1260 ///////////////////////////////////////////////////////////////////////////////
1261 // UTILS
1262 ///////////////////////////////////////////////////////////////////////////////
1263
1264 /**
1265 * Creates a route config from a React "children" object, which is usually
1266 * either a `<Route>` element or an array of them. Used internally by
1267 * `<Routes>` to create a route config from its children.
1268 *
1269 * @see https://reactrouter.com/utils/create-routes-from-children
1270 */
1271 function createRoutesFromChildren(children, parentPath) {
1272 if (parentPath === void 0) {
1273 parentPath = [];
1274 }
1275 let routes = [];
1276 React__namespace.Children.forEach(children, (element, index) => {
1277 if (! /*#__PURE__*/React__namespace.isValidElement(element)) {
1278 // Ignore non-elements. This allows people to more easily inline
1279 // conditionals in their route config.
1280 return;
1281 }
1282 let treePath = [...parentPath, index];
1283 if (element.type === React__namespace.Fragment) {
1284 // Transparently support React.Fragment and its children.
1285 routes.push.apply(routes, createRoutesFromChildren(element.props.children, treePath));
1286 return;
1287 }
1288 !(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;
1289 !(!element.props.index || !element.props.children) ? router.UNSAFE_invariant(false, "An index route cannot have child routes.") : void 0;
1290 let route = {
1291 id: element.props.id || treePath.join("-"),
1292 caseSensitive: element.props.caseSensitive,
1293 element: element.props.element,
1294 Component: element.props.Component,
1295 index: element.props.index,
1296 path: element.props.path,
1297 loader: element.props.loader,
1298 action: element.props.action,
1299 errorElement: element.props.errorElement,
1300 ErrorBoundary: element.props.ErrorBoundary,
1301 hasErrorBoundary: element.props.ErrorBoundary != null || element.props.errorElement != null,
1302 shouldRevalidate: element.props.shouldRevalidate,
1303 handle: element.props.handle,
1304 lazy: element.props.lazy
1305 };
1306 if (element.props.children) {
1307 route.children = createRoutesFromChildren(element.props.children, treePath);
1308 }
1309 routes.push(route);
1310 });
1311 return routes;
1312 }
1313
1314 /**
1315 * Renders the result of `matchRoutes()` into a React element.
1316 */
1317 function renderMatches(matches) {
1318 return _renderMatches(matches);
1319 }
1320
1321 function mapRouteProperties(route) {
1322 let updates = {
1323 // Note: this check also occurs in createRoutesFromChildren so update
1324 // there if you change this -- please and thank you!
1325 hasErrorBoundary: route.ErrorBoundary != null || route.errorElement != null
1326 };
1327 if (route.Component) {
1328 {
1329 if (route.element) {
1330 router.UNSAFE_warning(false, "You should not include both `Component` and `element` on your route - " + "`Component` will be used.") ;
1331 }
1332 }
1333 Object.assign(updates, {
1334 element: /*#__PURE__*/React__namespace.createElement(route.Component),
1335 Component: undefined
1336 });
1337 }
1338 if (route.ErrorBoundary) {
1339 {
1340 if (route.errorElement) {
1341 router.UNSAFE_warning(false, "You should not include both `ErrorBoundary` and `errorElement` on your route - " + "`ErrorBoundary` will be used.") ;
1342 }
1343 }
1344 Object.assign(updates, {
1345 errorElement: /*#__PURE__*/React__namespace.createElement(route.ErrorBoundary),
1346 ErrorBoundary: undefined
1347 });
1348 }
1349 return updates;
1350 }
1351 function createMemoryRouter(routes, opts) {
1352 return router.createRouter({
1353 basename: opts == null ? void 0 : opts.basename,
1354 future: _extends({}, opts == null ? void 0 : opts.future, {
1355 v7_prependBasename: true
1356 }),
1357 history: router.createMemoryHistory({
1358 initialEntries: opts == null ? void 0 : opts.initialEntries,
1359 initialIndex: opts == null ? void 0 : opts.initialIndex
1360 }),
1361 hydrationData: opts == null ? void 0 : opts.hydrationData,
1362 routes,
1363 mapRouteProperties
1364 }).initialize();
1365 }
1366
1367 Object.defineProperty(exports, 'AbortedDeferredError', {
1368 enumerable: true,
1369 get: function () { return router.AbortedDeferredError; }
1370 });
1371 Object.defineProperty(exports, 'NavigationType', {
1372 enumerable: true,
1373 get: function () { return router.Action; }
1374 });
1375 Object.defineProperty(exports, 'createPath', {
1376 enumerable: true,
1377 get: function () { return router.createPath; }
1378 });
1379 Object.defineProperty(exports, 'defer', {
1380 enumerable: true,
1381 get: function () { return router.defer; }
1382 });
1383 Object.defineProperty(exports, 'generatePath', {
1384 enumerable: true,
1385 get: function () { return router.generatePath; }
1386 });
1387 Object.defineProperty(exports, 'isRouteErrorResponse', {
1388 enumerable: true,
1389 get: function () { return router.isRouteErrorResponse; }
1390 });
1391 Object.defineProperty(exports, 'json', {
1392 enumerable: true,
1393 get: function () { return router.json; }
1394 });
1395 Object.defineProperty(exports, 'matchPath', {
1396 enumerable: true,
1397 get: function () { return router.matchPath; }
1398 });
1399 Object.defineProperty(exports, 'matchRoutes', {
1400 enumerable: true,
1401 get: function () { return router.matchRoutes; }
1402 });
1403 Object.defineProperty(exports, 'parsePath', {
1404 enumerable: true,
1405 get: function () { return router.parsePath; }
1406 });
1407 Object.defineProperty(exports, 'redirect', {
1408 enumerable: true,
1409 get: function () { return router.redirect; }
1410 });
1411 Object.defineProperty(exports, 'redirectDocument', {
1412 enumerable: true,
1413 get: function () { return router.redirectDocument; }
1414 });
1415 Object.defineProperty(exports, 'resolvePath', {
1416 enumerable: true,
1417 get: function () { return router.resolvePath; }
1418 });
1419 exports.Await = Await;
1420 exports.MemoryRouter = MemoryRouter;
1421 exports.Navigate = Navigate;
1422 exports.Outlet = Outlet;
1423 exports.Route = Route;
1424 exports.Router = Router;
1425 exports.RouterProvider = RouterProvider;
1426 exports.Routes = Routes;
1427 exports.UNSAFE_DataRouterContext = DataRouterContext;
1428 exports.UNSAFE_DataRouterStateContext = DataRouterStateContext;
1429 exports.UNSAFE_LocationContext = LocationContext;
1430 exports.UNSAFE_NavigationContext = NavigationContext;
1431 exports.UNSAFE_RouteContext = RouteContext;
1432 exports.UNSAFE_mapRouteProperties = mapRouteProperties;
1433 exports.UNSAFE_useRouteId = useRouteId;
1434 exports.UNSAFE_useRoutesImpl = useRoutesImpl;
1435 exports.createMemoryRouter = createMemoryRouter;
1436 exports.createRoutesFromChildren = createRoutesFromChildren;
1437 exports.createRoutesFromElements = createRoutesFromChildren;
1438 exports.renderMatches = renderMatches;
1439 exports.unstable_useBlocker = useBlocker;
1440 exports.useActionData = useActionData;
1441 exports.useAsyncError = useAsyncError;
1442 exports.useAsyncValue = useAsyncValue;
1443 exports.useHref = useHref;
1444 exports.useInRouterContext = useInRouterContext;
1445 exports.useLoaderData = useLoaderData;
1446 exports.useLocation = useLocation;
1447 exports.useMatch = useMatch;
1448 exports.useMatches = useMatches;
1449 exports.useNavigate = useNavigate;
1450 exports.useNavigation = useNavigation;
1451 exports.useNavigationType = useNavigationType;
1452 exports.useOutlet = useOutlet;
1453 exports.useOutletContext = useOutletContext;
1454 exports.useParams = useParams;
1455 exports.useResolvedPath = useResolvedPath;
1456 exports.useRevalidator = useRevalidator;
1457 exports.useRouteError = useRouteError;
1458 exports.useRouteLoaderData = useRouteLoaderData;
1459 exports.useRoutes = useRoutes;
1460
1461 Object.defineProperty(exports, '__esModule', { value: true });
1462
1463}));
1464//# sourceMappingURL=react-router.development.js.map