UNPKG

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