source: node_modules/react-router/dist/umd/react-router.development.js@ 65b6638

main
Last change on this file since 65b6638 was d24f17c, checked in by Aleksandar Panovski <apano77@…>, 15 months ago

Initial commit

  • Property mode set to 100644
File size: 61.3 KB
Line 
1/**
2 * React Router v6.22.1
3 *
4 * Copyright (c) Remix Software Inc.
5 *
6 * This source code is licensed under the MIT license found in the
7 * LICENSE.md file in the root directory of this source tree.
8 *
9 * @license MIT
10 */
11(function (global, factory) {
12 typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('react'), require('@remix-run/router')) :
13 typeof define === 'function' && define.amd ? define(['exports', 'react', '@remix-run/router'], factory) :
14 (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.ReactRouter = {}, global.React, global.RemixRouter));
15})(this, (function (exports, React, router) { 'use strict';
16
17 function _interopNamespace(e) {
18 if (e && e.__esModule) return e;
19 var n = Object.create(null);
20 if (e) {
21 Object.keys(e).forEach(function (k) {
22 if (k !== 'default') {
23 var d = Object.getOwnPropertyDescriptor(e, k);
24 Object.defineProperty(n, k, d.get ? d : {
25 enumerable: true,
26 get: function () { return e[k]; }
27 });
28 }
29 });
30 }
31 n["default"] = e;
32 return Object.freeze(n);
33 }
34
35 var React__namespace = /*#__PURE__*/_interopNamespace(React);
36
37 function _extends() {
38 _extends = Object.assign ? Object.assign.bind() : function (target) {
39 for (var i = 1; i < arguments.length; i++) {
40 var source = arguments[i];
41 for (var key in source) {
42 if (Object.prototype.hasOwnProperty.call(source, key)) {
43 target[key] = source[key];
44 }
45 }
46 }
47 return target;
48 };
49 return _extends.apply(this, arguments);
50 }
51
52 // Create react-specific types from the agnostic types in @remix-run/router to
53 // export from react-router
54 const DataRouterContext = /*#__PURE__*/React__namespace.createContext(null);
55 {
56 DataRouterContext.displayName = "DataRouter";
57 }
58 const DataRouterStateContext = /*#__PURE__*/React__namespace.createContext(null);
59 {
60 DataRouterStateContext.displayName = "DataRouterState";
61 }
62 const AwaitContext = /*#__PURE__*/React__namespace.createContext(null);
63 {
64 AwaitContext.displayName = "Await";
65 }
66
67 /**
68 * A Navigator is a "location changer"; it's how you get to different locations.
69 *
70 * Every history instance conforms to the Navigator interface, but the
71 * distinction is useful primarily when it comes to the low-level `<Router>` API
72 * where both the location and a navigator must be provided separately in order
73 * to avoid "tearing" that may occur in a suspense-enabled app if the action
74 * and/or location were to be read directly from the history instance.
75 */
76
77 const NavigationContext = /*#__PURE__*/React__namespace.createContext(null);
78 {
79 NavigationContext.displayName = "Navigation";
80 }
81 const LocationContext = /*#__PURE__*/React__namespace.createContext(null);
82 {
83 LocationContext.displayName = "Location";
84 }
85 const RouteContext = /*#__PURE__*/React__namespace.createContext({
86 outlet: null,
87 matches: [],
88 isDataRoute: false
89 });
90 {
91 RouteContext.displayName = "Route";
92 }
93 const RouteErrorContext = /*#__PURE__*/React__namespace.createContext(null);
94 {
95 RouteErrorContext.displayName = "RouteError";
96 }
97
98 /**
99 * Returns the full href for the given "to" value. This is useful for building
100 * custom links that are also accessible and preserve right-click behavior.
101 *
102 * @see https://reactrouter.com/hooks/use-href
103 */
104 function useHref(to, _temp) {
105 let {
106 relative
107 } = _temp === void 0 ? {} : _temp;
108 !useInRouterContext() ? router.UNSAFE_invariant(false, // TODO: This error is probably because they somehow have 2 versions of the
109 // router loaded. We can help them understand how to avoid that.
110 "useHref() may be used only in the context of a <Router> component.") : void 0;
111 let {
112 basename,
113 navigator
114 } = React__namespace.useContext(NavigationContext);
115 let {
116 hash,
117 pathname,
118 search
119 } = useResolvedPath(to, {
120 relative
121 });
122 let joinedPathname = pathname;
123
124 // If we're operating within a basename, prepend it to the pathname prior
125 // to creating the href. If this is a root navigation, then just use the raw
126 // basename which allows the basename to have full control over the presence
127 // of a trailing slash on root links
128 if (basename !== "/") {
129 joinedPathname = pathname === "/" ? basename : router.joinPaths([basename, pathname]);
130 }
131 return navigator.createHref({
132 pathname: joinedPathname,
133 search,
134 hash
135 });
136 }
137
138 /**
139 * Returns true if this component is a descendant of a `<Router>`.
140 *
141 * @see https://reactrouter.com/hooks/use-in-router-context
142 */
143 function useInRouterContext() {
144 return React__namespace.useContext(LocationContext) != null;
145 }
146
147 /**
148 * Returns the current location object, which represents the current URL in web
149 * browsers.
150 *
151 * Note: If you're using this it may mean you're doing some of your own
152 * "routing" in your app, and we'd like to know what your use case is. We may
153 * be able to provide something higher-level to better suit your needs.
154 *
155 * @see https://reactrouter.com/hooks/use-location
156 */
157 function useLocation() {
158 !useInRouterContext() ? router.UNSAFE_invariant(false, // TODO: This error is probably because they somehow have 2 versions of the
159 // router loaded. We can help them understand how to avoid that.
160 "useLocation() may be used only in the context of a <Router> component.") : void 0;
161 return React__namespace.useContext(LocationContext).location;
162 }
163
164 /**
165 * Returns the current navigation action which describes how the router came to
166 * the current location, either by a pop, push, or replace on the history stack.
167 *
168 * @see https://reactrouter.com/hooks/use-navigation-type
169 */
170 function useNavigationType() {
171 return React__namespace.useContext(LocationContext).navigationType;
172 }
173
174 /**
175 * Returns a PathMatch object if the given pattern matches the current URL.
176 * This is useful for components that need to know "active" state, e.g.
177 * `<NavLink>`.
178 *
179 * @see https://reactrouter.com/hooks/use-match
180 */
181 function useMatch(pattern) {
182 !useInRouterContext() ? router.UNSAFE_invariant(false, // TODO: This error is probably because they somehow have 2 versions of the
183 // router loaded. We can help them understand how to avoid that.
184 "useMatch() may be used only in the context of a <Router> component.") : void 0;
185 let {
186 pathname
187 } = useLocation();
188 return React__namespace.useMemo(() => router.matchPath(pattern, pathname), [pathname, pattern]);
189 }
190
191 /**
192 * The interface for the navigate() function returned from useNavigate().
193 */
194
195 const navigateEffectWarning = "You should call navigate() in a React.useEffect(), not when " + "your component is first rendered.";
196
197 // Mute warnings for calls to useNavigate in SSR environments
198 function useIsomorphicLayoutEffect(cb) {
199 let isStatic = React__namespace.useContext(NavigationContext).static;
200 if (!isStatic) {
201 // We should be able to get rid of this once react 18.3 is released
202 // See: https://github.com/facebook/react/pull/26395
203 // eslint-disable-next-line react-hooks/rules-of-hooks
204 React__namespace.useLayoutEffect(cb);
205 }
206 }
207
208 /**
209 * Returns an imperative method for changing the location. Used by `<Link>`s, but
210 * may also be used by other elements to change the location.
211 *
212 * @see https://reactrouter.com/hooks/use-navigate
213 */
214 function useNavigate() {
215 let {
216 isDataRoute
217 } = React__namespace.useContext(RouteContext);
218 // Conditional usage is OK here because the usage of a data router is static
219 // eslint-disable-next-line react-hooks/rules-of-hooks
220 return isDataRoute ? useNavigateStable() : useNavigateUnstable();
221 }
222 function useNavigateUnstable() {
223 !useInRouterContext() ? router.UNSAFE_invariant(false, // TODO: This error is probably because they somehow have 2 versions of the
224 // router loaded. We can help them understand how to avoid that.
225 "useNavigate() may be used only in the context of a <Router> component.") : void 0;
226 let dataRouterContext = React__namespace.useContext(DataRouterContext);
227 let {
228 basename,
229 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 _dataRouterState2;
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 _dataRouterState;
567 if ((_dataRouterState = dataRouterState) != null && _dataRouterState.errors) {
568 // Don't bail if we have data router errors so we can render them in the
569 // boundary. Use the pre-matched (or shimmed) matches
570 matches = dataRouterState.matches;
571 } else {
572 return null;
573 }
574 }
575 let renderedMatches = matches;
576
577 // If we have data errors, trim matches to the highest error boundary
578 let errors = (_dataRouterState2 = dataRouterState) == null ? void 0 : _dataRouterState2.errors;
579 if (errors != null) {
580 let errorIndex = renderedMatches.findIndex(m => m.route.id && (errors == null ? void 0 : errors[m.route.id]));
581 !(errorIndex >= 0) ? router.UNSAFE_invariant(false, "Could not find a matching route for errors on route IDs: " + Object.keys(errors).join(",")) : void 0;
582 renderedMatches = renderedMatches.slice(0, Math.min(renderedMatches.length, errorIndex + 1));
583 }
584
585 // If we're in a partial hydration mode, detect if we need to render down to
586 // a given HydrateFallback while we load the rest of the hydration data
587 let renderFallback = false;
588 let fallbackIndex = -1;
589 if (dataRouterState && future && future.v7_partialHydration) {
590 for (let i = 0; i < renderedMatches.length; i++) {
591 let match = renderedMatches[i];
592 // Track the deepest fallback up until the first route without data
593 if (match.route.HydrateFallback || match.route.hydrateFallbackElement) {
594 fallbackIndex = i;
595 }
596 if (match.route.id) {
597 let {
598 loaderData,
599 errors
600 } = dataRouterState;
601 let needsToRunLoader = match.route.loader && loaderData[match.route.id] === undefined && (!errors || errors[match.route.id] === undefined);
602 if (match.route.lazy || needsToRunLoader) {
603 // We found the first route that's not ready to render (waiting on
604 // lazy, or has a loader that hasn't run yet). Flag that we need to
605 // render a fallback and render up until the appropriate fallback
606 renderFallback = true;
607 if (fallbackIndex >= 0) {
608 renderedMatches = renderedMatches.slice(0, fallbackIndex + 1);
609 } else {
610 renderedMatches = [renderedMatches[0]];
611 }
612 break;
613 }
614 }
615 }
616 }
617 return renderedMatches.reduceRight((outlet, match, index) => {
618 // Only data routers handle errors/fallbacks
619 let error;
620 let shouldRenderHydrateFallback = false;
621 let errorElement = null;
622 let hydrateFallbackElement = null;
623 if (dataRouterState) {
624 error = errors && match.route.id ? errors[match.route.id] : undefined;
625 errorElement = match.route.errorElement || defaultErrorElement;
626 if (renderFallback) {
627 if (fallbackIndex < 0 && index === 0) {
628 warningOnce("route-fallback", false, "No `HydrateFallback` element provided to render during initial hydration");
629 shouldRenderHydrateFallback = true;
630 hydrateFallbackElement = null;
631 } else if (fallbackIndex === index) {
632 shouldRenderHydrateFallback = true;
633 hydrateFallbackElement = match.route.hydrateFallbackElement || null;
634 }
635 }
636 }
637 let matches = parentMatches.concat(renderedMatches.slice(0, index + 1));
638 let getChildren = () => {
639 let children;
640 if (error) {
641 children = errorElement;
642 } else if (shouldRenderHydrateFallback) {
643 children = hydrateFallbackElement;
644 } else if (match.route.Component) {
645 // Note: This is a de-optimized path since React won't re-use the
646 // ReactElement since it's identity changes with each new
647 // React.createElement call. We keep this so folks can use
648 // `<Route Component={...}>` in `<Routes>` but generally `Component`
649 // usage is only advised in `RouterProvider` when we can convert it to
650 // `element` ahead of time.
651 children = /*#__PURE__*/React__namespace.createElement(match.route.Component, null);
652 } else if (match.route.element) {
653 children = match.route.element;
654 } else {
655 children = outlet;
656 }
657 return /*#__PURE__*/React__namespace.createElement(RenderedRoute, {
658 match: match,
659 routeContext: {
660 outlet,
661 matches,
662 isDataRoute: dataRouterState != null
663 },
664 children: children
665 });
666 };
667 // Only wrap in an error boundary within data router usages when we have an
668 // ErrorBoundary/errorElement on this route. Otherwise let it bubble up to
669 // an ancestor ErrorBoundary/errorElement
670 return dataRouterState && (match.route.ErrorBoundary || match.route.errorElement || index === 0) ? /*#__PURE__*/React__namespace.createElement(RenderErrorBoundary, {
671 location: dataRouterState.location,
672 revalidation: dataRouterState.revalidation,
673 component: errorElement,
674 error: error,
675 children: getChildren(),
676 routeContext: {
677 outlet: null,
678 matches,
679 isDataRoute: true
680 }
681 }) : getChildren();
682 }, null);
683 }
684 var DataRouterHook = /*#__PURE__*/function (DataRouterHook) {
685 DataRouterHook["UseBlocker"] = "useBlocker";
686 DataRouterHook["UseRevalidator"] = "useRevalidator";
687 DataRouterHook["UseNavigateStable"] = "useNavigate";
688 return DataRouterHook;
689 }(DataRouterHook || {});
690 var DataRouterStateHook = /*#__PURE__*/function (DataRouterStateHook) {
691 DataRouterStateHook["UseBlocker"] = "useBlocker";
692 DataRouterStateHook["UseLoaderData"] = "useLoaderData";
693 DataRouterStateHook["UseActionData"] = "useActionData";
694 DataRouterStateHook["UseRouteError"] = "useRouteError";
695 DataRouterStateHook["UseNavigation"] = "useNavigation";
696 DataRouterStateHook["UseRouteLoaderData"] = "useRouteLoaderData";
697 DataRouterStateHook["UseMatches"] = "useMatches";
698 DataRouterStateHook["UseRevalidator"] = "useRevalidator";
699 DataRouterStateHook["UseNavigateStable"] = "useNavigate";
700 DataRouterStateHook["UseRouteId"] = "useRouteId";
701 return DataRouterStateHook;
702 }(DataRouterStateHook || {});
703 function getDataRouterConsoleError(hookName) {
704 return hookName + " must be used within a data router. See https://reactrouter.com/routers/picking-a-router.";
705 }
706 function useDataRouterContext(hookName) {
707 let ctx = React__namespace.useContext(DataRouterContext);
708 !ctx ? router.UNSAFE_invariant(false, getDataRouterConsoleError(hookName)) : void 0;
709 return ctx;
710 }
711 function useDataRouterState(hookName) {
712 let state = React__namespace.useContext(DataRouterStateContext);
713 !state ? router.UNSAFE_invariant(false, getDataRouterConsoleError(hookName)) : void 0;
714 return state;
715 }
716 function useRouteContext(hookName) {
717 let route = React__namespace.useContext(RouteContext);
718 !route ? router.UNSAFE_invariant(false, getDataRouterConsoleError(hookName)) : void 0;
719 return route;
720 }
721
722 // Internal version with hookName-aware debugging
723 function useCurrentRouteId(hookName) {
724 let route = useRouteContext(hookName);
725 let thisRoute = route.matches[route.matches.length - 1];
726 !thisRoute.route.id ? router.UNSAFE_invariant(false, hookName + " can only be used on routes that contain a unique \"id\"") : void 0;
727 return thisRoute.route.id;
728 }
729
730 /**
731 * Returns the ID for the nearest contextual route
732 */
733 function useRouteId() {
734 return useCurrentRouteId(DataRouterStateHook.UseRouteId);
735 }
736
737 /**
738 * Returns the current navigation, defaulting to an "idle" navigation when
739 * no navigation is in progress
740 */
741 function useNavigation() {
742 let state = useDataRouterState(DataRouterStateHook.UseNavigation);
743 return state.navigation;
744 }
745
746 /**
747 * Returns a revalidate function for manually triggering revalidation, as well
748 * as the current state of any manual revalidations
749 */
750 function useRevalidator() {
751 let dataRouterContext = useDataRouterContext(DataRouterHook.UseRevalidator);
752 let state = useDataRouterState(DataRouterStateHook.UseRevalidator);
753 return React__namespace.useMemo(() => ({
754 revalidate: dataRouterContext.router.revalidate,
755 state: state.revalidation
756 }), [dataRouterContext.router.revalidate, state.revalidation]);
757 }
758
759 /**
760 * Returns the active route matches, useful for accessing loaderData for
761 * parent/child routes or the route "handle" property
762 */
763 function useMatches() {
764 let {
765 matches,
766 loaderData
767 } = useDataRouterState(DataRouterStateHook.UseMatches);
768 return React__namespace.useMemo(() => matches.map(m => router.UNSAFE_convertRouteMatchToUiMatch(m, loaderData)), [matches, loaderData]);
769 }
770
771 /**
772 * Returns the loader data for the nearest ancestor Route loader
773 */
774 function useLoaderData() {
775 let state = useDataRouterState(DataRouterStateHook.UseLoaderData);
776 let routeId = useCurrentRouteId(DataRouterStateHook.UseLoaderData);
777 if (state.errors && state.errors[routeId] != null) {
778 console.error("You cannot `useLoaderData` in an errorElement (routeId: " + routeId + ")");
779 return undefined;
780 }
781 return state.loaderData[routeId];
782 }
783
784 /**
785 * Returns the loaderData for the given routeId
786 */
787 function useRouteLoaderData(routeId) {
788 let state = useDataRouterState(DataRouterStateHook.UseRouteLoaderData);
789 return state.loaderData[routeId];
790 }
791
792 /**
793 * Returns the action data for the nearest ancestor Route action
794 */
795 function useActionData() {
796 let state = useDataRouterState(DataRouterStateHook.UseActionData);
797 let routeId = useCurrentRouteId(DataRouterStateHook.UseLoaderData);
798 return state.actionData ? state.actionData[routeId] : undefined;
799 }
800
801 /**
802 * Returns the nearest ancestor Route error, which could be a loader/action
803 * error or a render error. This is intended to be called from your
804 * ErrorBoundary/errorElement to display a proper error message.
805 */
806 function useRouteError() {
807 var _state$errors;
808 let error = React__namespace.useContext(RouteErrorContext);
809 let state = useDataRouterState(DataRouterStateHook.UseRouteError);
810 let routeId = useCurrentRouteId(DataRouterStateHook.UseRouteError);
811
812 // If this was a render error, we put it in a RouteError context inside
813 // of RenderErrorBoundary
814 if (error !== undefined) {
815 return error;
816 }
817
818 // Otherwise look for errors from our data router state
819 return (_state$errors = state.errors) == null ? void 0 : _state$errors[routeId];
820 }
821
822 /**
823 * Returns the happy-path data from the nearest ancestor `<Await />` value
824 */
825 function useAsyncValue() {
826 let value = React__namespace.useContext(AwaitContext);
827 return value == null ? void 0 : value._data;
828 }
829
830 /**
831 * Returns the error from the nearest ancestor `<Await />` value
832 */
833 function useAsyncError() {
834 let value = React__namespace.useContext(AwaitContext);
835 return value == null ? void 0 : value._error;
836 }
837 let blockerId = 0;
838
839 /**
840 * Allow the application to block navigations within the SPA and present the
841 * user a confirmation dialog to confirm the navigation. Mostly used to avoid
842 * using half-filled form data. This does not handle hard-reloads or
843 * cross-origin navigations.
844 */
845 function useBlocker(shouldBlock) {
846 let {
847 router: router$1,
848 basename
849 } = useDataRouterContext(DataRouterHook.UseBlocker);
850 let state = useDataRouterState(DataRouterStateHook.UseBlocker);
851 let [blockerKey, setBlockerKey] = React__namespace.useState("");
852 let blockerFunction = React__namespace.useCallback(arg => {
853 if (typeof shouldBlock !== "function") {
854 return !!shouldBlock;
855 }
856 if (basename === "/") {
857 return shouldBlock(arg);
858 }
859
860 // If they provided us a function and we've got an active basename, strip
861 // it from the locations we expose to the user to match the behavior of
862 // useLocation
863 let {
864 currentLocation,
865 nextLocation,
866 historyAction
867 } = arg;
868 return shouldBlock({
869 currentLocation: _extends({}, currentLocation, {
870 pathname: router.stripBasename(currentLocation.pathname, basename) || currentLocation.pathname
871 }),
872 nextLocation: _extends({}, nextLocation, {
873 pathname: router.stripBasename(nextLocation.pathname, basename) || nextLocation.pathname
874 }),
875 historyAction
876 });
877 }, [basename, shouldBlock]);
878
879 // This effect is in charge of blocker key assignment and deletion (which is
880 // tightly coupled to the key)
881 React__namespace.useEffect(() => {
882 let key = String(++blockerId);
883 setBlockerKey(key);
884 return () => router$1.deleteBlocker(key);
885 }, [router$1]);
886
887 // This effect handles assigning the blockerFunction. This is to handle
888 // unstable blocker function identities, and happens only after the prior
889 // effect so we don't get an orphaned blockerFunction in the router with a
890 // key of "". Until then we just have the IDLE_BLOCKER.
891 React__namespace.useEffect(() => {
892 if (blockerKey !== "") {
893 router$1.getBlocker(blockerKey, blockerFunction);
894 }
895 }, [router$1, blockerKey, blockerFunction]);
896
897 // Prefer the blocker from `state` not `router.state` since DataRouterContext
898 // is memoized so this ensures we update on blocker state updates
899 return blockerKey && state.blockers.has(blockerKey) ? state.blockers.get(blockerKey) : router.IDLE_BLOCKER;
900 }
901
902 /**
903 * Stable version of useNavigate that is used when we are in the context of
904 * a RouterProvider.
905 */
906 function useNavigateStable() {
907 let {
908 router: router$1
909 } = useDataRouterContext(DataRouterHook.UseNavigateStable);
910 let id = useCurrentRouteId(DataRouterStateHook.UseNavigateStable);
911 let activeRef = React__namespace.useRef(false);
912 useIsomorphicLayoutEffect(() => {
913 activeRef.current = true;
914 });
915 let navigate = React__namespace.useCallback(function (to, options) {
916 if (options === void 0) {
917 options = {};
918 }
919 router.UNSAFE_warning(activeRef.current, navigateEffectWarning) ;
920
921 // Short circuit here since if this happens on first render the navigate
922 // is useless because we haven't wired up our router subscriber yet
923 if (!activeRef.current) return;
924 if (typeof to === "number") {
925 router$1.navigate(to);
926 } else {
927 router$1.navigate(to, _extends({
928 fromRouteId: id
929 }, options));
930 }
931 }, [router$1, id]);
932 return navigate;
933 }
934 const alreadyWarned = {};
935 function warningOnce(key, cond, message) {
936 if (!cond && !alreadyWarned[key]) {
937 alreadyWarned[key] = true;
938 router.UNSAFE_warning(false, message) ;
939 }
940 }
941
942 /**
943 Webpack + React 17 fails to compile on any of the following because webpack
944 complains that `startTransition` doesn't exist in `React`:
945 * import { startTransition } from "react"
946 * import * as React from from "react";
947 "startTransition" in React ? React.startTransition(() => setState()) : setState()
948 * import * as React from from "react";
949 "startTransition" in React ? React["startTransition"](() => setState()) : setState()
950
951 Moving it to a constant such as the following solves the Webpack/React 17 issue:
952 * import * as React from from "react";
953 const START_TRANSITION = "startTransition";
954 START_TRANSITION in React ? React[START_TRANSITION](() => setState()) : setState()
955
956 However, that introduces webpack/terser minification issues in production builds
957 in React 18 where minification/obfuscation ends up removing the call of
958 React.startTransition entirely from the first half of the ternary. Grabbing
959 this exported reference once up front resolves that issue.
960
961 See https://github.com/remix-run/react-router/issues/10579
962 */
963 const START_TRANSITION = "startTransition";
964 const startTransitionImpl = React__namespace[START_TRANSITION];
965
966 /**
967 * Given a Remix Router instance, render the appropriate UI
968 */
969 function RouterProvider(_ref) {
970 let {
971 fallbackElement,
972 router: router$1,
973 future
974 } = _ref;
975 let [state, setStateImpl] = React__namespace.useState(router$1.state);
976 let {
977 v7_startTransition
978 } = future || {};
979 let setState = React__namespace.useCallback(newState => {
980 if (v7_startTransition && startTransitionImpl) {
981 startTransitionImpl(() => setStateImpl(newState));
982 } else {
983 setStateImpl(newState);
984 }
985 }, [setStateImpl, v7_startTransition]);
986
987 // Need to use a layout effect here so we are subscribed early enough to
988 // pick up on any render-driven redirects/navigations (useEffect/<Navigate>)
989 React__namespace.useLayoutEffect(() => router$1.subscribe(setState), [router$1, setState]);
990 React__namespace.useEffect(() => {
991 router.UNSAFE_warning(fallbackElement == null || !router$1.future.v7_partialHydration, "`<RouterProvider fallbackElement>` is deprecated when using " + "`v7_partialHydration`, use a `HydrateFallback` component instead") ;
992 // Only log this once on initial mount
993 // eslint-disable-next-line react-hooks/exhaustive-deps
994 }, []);
995 let navigator = React__namespace.useMemo(() => {
996 return {
997 createHref: router$1.createHref,
998 encodeLocation: router$1.encodeLocation,
999 go: n => router$1.navigate(n),
1000 push: (to, state, opts) => router$1.navigate(to, {
1001 state,
1002 preventScrollReset: opts == null ? void 0 : opts.preventScrollReset
1003 }),
1004 replace: (to, state, opts) => router$1.navigate(to, {
1005 replace: true,
1006 state,
1007 preventScrollReset: opts == null ? void 0 : opts.preventScrollReset
1008 })
1009 };
1010 }, [router$1]);
1011 let basename = router$1.basename || "/";
1012 let dataRouterContext = React__namespace.useMemo(() => ({
1013 router: router$1,
1014 navigator,
1015 static: false,
1016 basename
1017 }), [router$1, navigator, basename]);
1018
1019 // The fragment and {null} here are important! We need them to keep React 18's
1020 // useId happy when we are server-rendering since we may have a <script> here
1021 // containing the hydrated server-side staticContext (from StaticRouterProvider).
1022 // useId relies on the component tree structure to generate deterministic id's
1023 // so we need to ensure it remains the same on the client even though
1024 // we don't need the <script> tag
1025 return /*#__PURE__*/React__namespace.createElement(React__namespace.Fragment, null, /*#__PURE__*/React__namespace.createElement(DataRouterContext.Provider, {
1026 value: dataRouterContext
1027 }, /*#__PURE__*/React__namespace.createElement(DataRouterStateContext.Provider, {
1028 value: state
1029 }, /*#__PURE__*/React__namespace.createElement(Router, {
1030 basename: basename,
1031 location: state.location,
1032 navigationType: state.historyAction,
1033 navigator: navigator,
1034 future: {
1035 v7_relativeSplatPath: router$1.future.v7_relativeSplatPath
1036 }
1037 }, state.initialized || router$1.future.v7_partialHydration ? /*#__PURE__*/React__namespace.createElement(DataRoutes, {
1038 routes: router$1.routes,
1039 future: router$1.future,
1040 state: state
1041 }) : fallbackElement))), null);
1042 }
1043 function DataRoutes(_ref2) {
1044 let {
1045 routes,
1046 future,
1047 state
1048 } = _ref2;
1049 return useRoutesImpl(routes, undefined, state, future);
1050 }
1051 /**
1052 * A `<Router>` that stores all entries in memory.
1053 *
1054 * @see https://reactrouter.com/router-components/memory-router
1055 */
1056 function MemoryRouter(_ref3) {
1057 let {
1058 basename,
1059 children,
1060 initialEntries,
1061 initialIndex,
1062 future
1063 } = _ref3;
1064 let historyRef = React__namespace.useRef();
1065 if (historyRef.current == null) {
1066 historyRef.current = router.createMemoryHistory({
1067 initialEntries,
1068 initialIndex,
1069 v5Compat: true
1070 });
1071 }
1072 let history = historyRef.current;
1073 let [state, setStateImpl] = React__namespace.useState({
1074 action: history.action,
1075 location: history.location
1076 });
1077 let {
1078 v7_startTransition
1079 } = future || {};
1080 let setState = React__namespace.useCallback(newState => {
1081 v7_startTransition && startTransitionImpl ? startTransitionImpl(() => setStateImpl(newState)) : setStateImpl(newState);
1082 }, [setStateImpl, v7_startTransition]);
1083 React__namespace.useLayoutEffect(() => history.listen(setState), [history, setState]);
1084 return /*#__PURE__*/React__namespace.createElement(Router, {
1085 basename: basename,
1086 children: children,
1087 location: state.location,
1088 navigationType: state.action,
1089 navigator: history,
1090 future: future
1091 });
1092 }
1093 /**
1094 * Changes the current location.
1095 *
1096 * Note: This API is mostly useful in React.Component subclasses that are not
1097 * able to use hooks. In functional components, we recommend you use the
1098 * `useNavigate` hook instead.
1099 *
1100 * @see https://reactrouter.com/components/navigate
1101 */
1102 function Navigate(_ref4) {
1103 let {
1104 to,
1105 replace,
1106 state,
1107 relative
1108 } = _ref4;
1109 !useInRouterContext() ? router.UNSAFE_invariant(false, // TODO: This error is probably because they somehow have 2 versions of
1110 // the router loaded. We can help them understand how to avoid that.
1111 "<Navigate> may be used only in the context of a <Router> component.") : void 0;
1112 let {
1113 future,
1114 static: isStatic
1115 } = React__namespace.useContext(NavigationContext);
1116 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.") ;
1117 let {
1118 matches
1119 } = React__namespace.useContext(RouteContext);
1120 let {
1121 pathname: locationPathname
1122 } = useLocation();
1123 let navigate = useNavigate();
1124
1125 // Resolve the path outside of the effect so that when effects run twice in
1126 // StrictMode they navigate to the same place
1127 let path = router.resolveTo(to, router.UNSAFE_getResolveToMatches(matches, future.v7_relativeSplatPath), locationPathname, relative === "path");
1128 let jsonPath = JSON.stringify(path);
1129 React__namespace.useEffect(() => navigate(JSON.parse(jsonPath), {
1130 replace,
1131 state,
1132 relative
1133 }), [navigate, jsonPath, relative, replace, state]);
1134 return null;
1135 }
1136 /**
1137 * Renders the child route's element, if there is one.
1138 *
1139 * @see https://reactrouter.com/components/outlet
1140 */
1141 function Outlet(props) {
1142 return useOutlet(props.context);
1143 }
1144 /**
1145 * Declares an element that should be rendered at a certain URL path.
1146 *
1147 * @see https://reactrouter.com/components/route
1148 */
1149 function Route(_props) {
1150 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>.") ;
1151 }
1152 /**
1153 * Provides location context for the rest of the app.
1154 *
1155 * Note: You usually won't render a `<Router>` directly. Instead, you'll render a
1156 * router that is more specific to your environment such as a `<BrowserRouter>`
1157 * in web browsers or a `<StaticRouter>` for server rendering.
1158 *
1159 * @see https://reactrouter.com/router-components/router
1160 */
1161 function Router(_ref5) {
1162 let {
1163 basename: basenameProp = "/",
1164 children = null,
1165 location: locationProp,
1166 navigationType = router.Action.Pop,
1167 navigator,
1168 static: staticProp = false,
1169 future
1170 } = _ref5;
1171 !!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;
1172
1173 // Preserve trailing slashes on basename, so we can let the user control
1174 // the enforcement of trailing slashes throughout the app
1175 let basename = basenameProp.replace(/^\/*/, "/");
1176 let navigationContext = React__namespace.useMemo(() => ({
1177 basename,
1178 navigator,
1179 static: staticProp,
1180 future: _extends({
1181 v7_relativeSplatPath: false
1182 }, future)
1183 }), [basename, future, navigator, staticProp]);
1184 if (typeof locationProp === "string") {
1185 locationProp = router.parsePath(locationProp);
1186 }
1187 let {
1188 pathname = "/",
1189 search = "",
1190 hash = "",
1191 state = null,
1192 key = "default"
1193 } = locationProp;
1194 let locationContext = React__namespace.useMemo(() => {
1195 let trailingPathname = router.stripBasename(pathname, basename);
1196 if (trailingPathname == null) {
1197 return null;
1198 }
1199 return {
1200 location: {
1201 pathname: trailingPathname,
1202 search,
1203 hash,
1204 state,
1205 key
1206 },
1207 navigationType
1208 };
1209 }, [basename, pathname, search, hash, state, key, navigationType]);
1210 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.") ;
1211 if (locationContext == null) {
1212 return null;
1213 }
1214 return /*#__PURE__*/React__namespace.createElement(NavigationContext.Provider, {
1215 value: navigationContext
1216 }, /*#__PURE__*/React__namespace.createElement(LocationContext.Provider, {
1217 children: children,
1218 value: locationContext
1219 }));
1220 }
1221 /**
1222 * A container for a nested tree of `<Route>` elements that renders the branch
1223 * that best matches the current location.
1224 *
1225 * @see https://reactrouter.com/components/routes
1226 */
1227 function Routes(_ref6) {
1228 let {
1229 children,
1230 location
1231 } = _ref6;
1232 return useRoutes(createRoutesFromChildren(children), location);
1233 }
1234 /**
1235 * Component to use for rendering lazily loaded data from returning defer()
1236 * in a loader function
1237 */
1238 function Await(_ref7) {
1239 let {
1240 children,
1241 errorElement,
1242 resolve
1243 } = _ref7;
1244 return /*#__PURE__*/React__namespace.createElement(AwaitErrorBoundary, {
1245 resolve: resolve,
1246 errorElement: errorElement
1247 }, /*#__PURE__*/React__namespace.createElement(ResolveAwait, null, children));
1248 }
1249 var AwaitRenderStatus = /*#__PURE__*/function (AwaitRenderStatus) {
1250 AwaitRenderStatus[AwaitRenderStatus["pending"] = 0] = "pending";
1251 AwaitRenderStatus[AwaitRenderStatus["success"] = 1] = "success";
1252 AwaitRenderStatus[AwaitRenderStatus["error"] = 2] = "error";
1253 return AwaitRenderStatus;
1254 }(AwaitRenderStatus || {});
1255 const neverSettledPromise = new Promise(() => {});
1256 class AwaitErrorBoundary extends React__namespace.Component {
1257 constructor(props) {
1258 super(props);
1259 this.state = {
1260 error: null
1261 };
1262 }
1263 static getDerivedStateFromError(error) {
1264 return {
1265 error
1266 };
1267 }
1268 componentDidCatch(error, errorInfo) {
1269 console.error("<Await> caught the following error during render", error, errorInfo);
1270 }
1271 render() {
1272 let {
1273 children,
1274 errorElement,
1275 resolve
1276 } = this.props;
1277 let promise = null;
1278 let status = AwaitRenderStatus.pending;
1279 if (!(resolve instanceof Promise)) {
1280 // Didn't get a promise - provide as a resolved promise
1281 status = AwaitRenderStatus.success;
1282 promise = Promise.resolve();
1283 Object.defineProperty(promise, "_tracked", {
1284 get: () => true
1285 });
1286 Object.defineProperty(promise, "_data", {
1287 get: () => resolve
1288 });
1289 } else if (this.state.error) {
1290 // Caught a render error, provide it as a rejected promise
1291 status = AwaitRenderStatus.error;
1292 let renderError = this.state.error;
1293 promise = Promise.reject().catch(() => {}); // Avoid unhandled rejection warnings
1294 Object.defineProperty(promise, "_tracked", {
1295 get: () => true
1296 });
1297 Object.defineProperty(promise, "_error", {
1298 get: () => renderError
1299 });
1300 } else if (resolve._tracked) {
1301 // Already tracked promise - check contents
1302 promise = resolve;
1303 status = promise._error !== undefined ? AwaitRenderStatus.error : promise._data !== undefined ? AwaitRenderStatus.success : AwaitRenderStatus.pending;
1304 } else {
1305 // Raw (untracked) promise - track it
1306 status = AwaitRenderStatus.pending;
1307 Object.defineProperty(resolve, "_tracked", {
1308 get: () => true
1309 });
1310 promise = resolve.then(data => Object.defineProperty(resolve, "_data", {
1311 get: () => data
1312 }), error => Object.defineProperty(resolve, "_error", {
1313 get: () => error
1314 }));
1315 }
1316 if (status === AwaitRenderStatus.error && promise._error instanceof router.AbortedDeferredError) {
1317 // Freeze the UI by throwing a never resolved promise
1318 throw neverSettledPromise;
1319 }
1320 if (status === AwaitRenderStatus.error && !errorElement) {
1321 // No errorElement, throw to the nearest route-level error boundary
1322 throw promise._error;
1323 }
1324 if (status === AwaitRenderStatus.error) {
1325 // Render via our errorElement
1326 return /*#__PURE__*/React__namespace.createElement(AwaitContext.Provider, {
1327 value: promise,
1328 children: errorElement
1329 });
1330 }
1331 if (status === AwaitRenderStatus.success) {
1332 // Render children with resolved value
1333 return /*#__PURE__*/React__namespace.createElement(AwaitContext.Provider, {
1334 value: promise,
1335 children: children
1336 });
1337 }
1338
1339 // Throw to the suspense boundary
1340 throw promise;
1341 }
1342 }
1343
1344 /**
1345 * @private
1346 * Indirection to leverage useAsyncValue for a render-prop API on `<Await>`
1347 */
1348 function ResolveAwait(_ref8) {
1349 let {
1350 children
1351 } = _ref8;
1352 let data = useAsyncValue();
1353 let toRender = typeof children === "function" ? children(data) : children;
1354 return /*#__PURE__*/React__namespace.createElement(React__namespace.Fragment, null, toRender);
1355 }
1356
1357 ///////////////////////////////////////////////////////////////////////////////
1358 // UTILS
1359 ///////////////////////////////////////////////////////////////////////////////
1360
1361 /**
1362 * Creates a route config from a React "children" object, which is usually
1363 * either a `<Route>` element or an array of them. Used internally by
1364 * `<Routes>` to create a route config from its children.
1365 *
1366 * @see https://reactrouter.com/utils/create-routes-from-children
1367 */
1368 function createRoutesFromChildren(children, parentPath) {
1369 if (parentPath === void 0) {
1370 parentPath = [];
1371 }
1372 let routes = [];
1373 React__namespace.Children.forEach(children, (element, index) => {
1374 if (! /*#__PURE__*/React__namespace.isValidElement(element)) {
1375 // Ignore non-elements. This allows people to more easily inline
1376 // conditionals in their route config.
1377 return;
1378 }
1379 let treePath = [...parentPath, index];
1380 if (element.type === React__namespace.Fragment) {
1381 // Transparently support React.Fragment and its children.
1382 routes.push.apply(routes, createRoutesFromChildren(element.props.children, treePath));
1383 return;
1384 }
1385 !(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;
1386 !(!element.props.index || !element.props.children) ? router.UNSAFE_invariant(false, "An index route cannot have child routes.") : void 0;
1387 let route = {
1388 id: element.props.id || treePath.join("-"),
1389 caseSensitive: element.props.caseSensitive,
1390 element: element.props.element,
1391 Component: element.props.Component,
1392 index: element.props.index,
1393 path: element.props.path,
1394 loader: element.props.loader,
1395 action: element.props.action,
1396 errorElement: element.props.errorElement,
1397 ErrorBoundary: element.props.ErrorBoundary,
1398 hasErrorBoundary: element.props.ErrorBoundary != null || element.props.errorElement != null,
1399 shouldRevalidate: element.props.shouldRevalidate,
1400 handle: element.props.handle,
1401 lazy: element.props.lazy
1402 };
1403 if (element.props.children) {
1404 route.children = createRoutesFromChildren(element.props.children, treePath);
1405 }
1406 routes.push(route);
1407 });
1408 return routes;
1409 }
1410
1411 /**
1412 * Renders the result of `matchRoutes()` into a React element.
1413 */
1414 function renderMatches(matches) {
1415 return _renderMatches(matches);
1416 }
1417
1418 function mapRouteProperties(route) {
1419 let updates = {
1420 // Note: this check also occurs in createRoutesFromChildren so update
1421 // there if you change this -- please and thank you!
1422 hasErrorBoundary: route.ErrorBoundary != null || route.errorElement != null
1423 };
1424 if (route.Component) {
1425 {
1426 if (route.element) {
1427 router.UNSAFE_warning(false, "You should not include both `Component` and `element` on your route - " + "`Component` will be used.") ;
1428 }
1429 }
1430 Object.assign(updates, {
1431 element: /*#__PURE__*/React__namespace.createElement(route.Component),
1432 Component: undefined
1433 });
1434 }
1435 if (route.HydrateFallback) {
1436 {
1437 if (route.hydrateFallbackElement) {
1438 router.UNSAFE_warning(false, "You should not include both `HydrateFallback` and `hydrateFallbackElement` on your route - " + "`HydrateFallback` will be used.") ;
1439 }
1440 }
1441 Object.assign(updates, {
1442 hydrateFallbackElement: /*#__PURE__*/React__namespace.createElement(route.HydrateFallback),
1443 HydrateFallback: undefined
1444 });
1445 }
1446 if (route.ErrorBoundary) {
1447 {
1448 if (route.errorElement) {
1449 router.UNSAFE_warning(false, "You should not include both `ErrorBoundary` and `errorElement` on your route - " + "`ErrorBoundary` will be used.") ;
1450 }
1451 }
1452 Object.assign(updates, {
1453 errorElement: /*#__PURE__*/React__namespace.createElement(route.ErrorBoundary),
1454 ErrorBoundary: undefined
1455 });
1456 }
1457 return updates;
1458 }
1459 function createMemoryRouter(routes, opts) {
1460 return router.createRouter({
1461 basename: opts == null ? void 0 : opts.basename,
1462 future: _extends({}, opts == null ? void 0 : opts.future, {
1463 v7_prependBasename: true
1464 }),
1465 history: router.createMemoryHistory({
1466 initialEntries: opts == null ? void 0 : opts.initialEntries,
1467 initialIndex: opts == null ? void 0 : opts.initialIndex
1468 }),
1469 hydrationData: opts == null ? void 0 : opts.hydrationData,
1470 routes,
1471 mapRouteProperties
1472 }).initialize();
1473 }
1474
1475 Object.defineProperty(exports, 'AbortedDeferredError', {
1476 enumerable: true,
1477 get: function () { return router.AbortedDeferredError; }
1478 });
1479 Object.defineProperty(exports, 'NavigationType', {
1480 enumerable: true,
1481 get: function () { return router.Action; }
1482 });
1483 Object.defineProperty(exports, 'createPath', {
1484 enumerable: true,
1485 get: function () { return router.createPath; }
1486 });
1487 Object.defineProperty(exports, 'defer', {
1488 enumerable: true,
1489 get: function () { return router.defer; }
1490 });
1491 Object.defineProperty(exports, 'generatePath', {
1492 enumerable: true,
1493 get: function () { return router.generatePath; }
1494 });
1495 Object.defineProperty(exports, 'isRouteErrorResponse', {
1496 enumerable: true,
1497 get: function () { return router.isRouteErrorResponse; }
1498 });
1499 Object.defineProperty(exports, 'json', {
1500 enumerable: true,
1501 get: function () { return router.json; }
1502 });
1503 Object.defineProperty(exports, 'matchPath', {
1504 enumerable: true,
1505 get: function () { return router.matchPath; }
1506 });
1507 Object.defineProperty(exports, 'matchRoutes', {
1508 enumerable: true,
1509 get: function () { return router.matchRoutes; }
1510 });
1511 Object.defineProperty(exports, 'parsePath', {
1512 enumerable: true,
1513 get: function () { return router.parsePath; }
1514 });
1515 Object.defineProperty(exports, 'redirect', {
1516 enumerable: true,
1517 get: function () { return router.redirect; }
1518 });
1519 Object.defineProperty(exports, 'redirectDocument', {
1520 enumerable: true,
1521 get: function () { return router.redirectDocument; }
1522 });
1523 Object.defineProperty(exports, 'resolvePath', {
1524 enumerable: true,
1525 get: function () { return router.resolvePath; }
1526 });
1527 exports.Await = Await;
1528 exports.MemoryRouter = MemoryRouter;
1529 exports.Navigate = Navigate;
1530 exports.Outlet = Outlet;
1531 exports.Route = Route;
1532 exports.Router = Router;
1533 exports.RouterProvider = RouterProvider;
1534 exports.Routes = Routes;
1535 exports.UNSAFE_DataRouterContext = DataRouterContext;
1536 exports.UNSAFE_DataRouterStateContext = DataRouterStateContext;
1537 exports.UNSAFE_LocationContext = LocationContext;
1538 exports.UNSAFE_NavigationContext = NavigationContext;
1539 exports.UNSAFE_RouteContext = RouteContext;
1540 exports.UNSAFE_mapRouteProperties = mapRouteProperties;
1541 exports.UNSAFE_useRouteId = useRouteId;
1542 exports.UNSAFE_useRoutesImpl = useRoutesImpl;
1543 exports.createMemoryRouter = createMemoryRouter;
1544 exports.createRoutesFromChildren = createRoutesFromChildren;
1545 exports.createRoutesFromElements = createRoutesFromChildren;
1546 exports.renderMatches = renderMatches;
1547 exports.useActionData = useActionData;
1548 exports.useAsyncError = useAsyncError;
1549 exports.useAsyncValue = useAsyncValue;
1550 exports.useBlocker = useBlocker;
1551 exports.useHref = useHref;
1552 exports.useInRouterContext = useInRouterContext;
1553 exports.useLoaderData = useLoaderData;
1554 exports.useLocation = useLocation;
1555 exports.useMatch = useMatch;
1556 exports.useMatches = useMatches;
1557 exports.useNavigate = useNavigate;
1558 exports.useNavigation = useNavigation;
1559 exports.useNavigationType = useNavigationType;
1560 exports.useOutlet = useOutlet;
1561 exports.useOutletContext = useOutletContext;
1562 exports.useParams = useParams;
1563 exports.useResolvedPath = useResolvedPath;
1564 exports.useRevalidator = useRevalidator;
1565 exports.useRouteError = useRouteError;
1566 exports.useRouteLoaderData = useRouteLoaderData;
1567 exports.useRoutes = useRoutes;
1568
1569 Object.defineProperty(exports, '__esModule', { value: true });
1570
1571}));
1572//# sourceMappingURL=react-router.development.js.map
Note: See TracBrowser for help on using the repository browser.