UNPKG

47.7 kBJavaScriptView Raw
1/**
2 * React Router v6.8.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 */
11import { UNSAFE_invariant, joinPaths, matchPath, UNSAFE_getPathContributingMatches, warning, resolveTo, parsePath, matchRoutes, Action, isRouteErrorResponse, createMemoryHistory, stripBasename, AbortedDeferredError, createRouter } from '@remix-run/router';
12export { AbortedDeferredError, Action as NavigationType, createPath, defer, generatePath, isRouteErrorResponse, json, matchPath, matchRoutes, parsePath, redirect, resolvePath } from '@remix-run/router';
13import * as React from 'react';
14
15/**
16 * Copyright (c) Facebook, Inc. and its affiliates.
17 *
18 * This source code is licensed under the MIT license found in the
19 * LICENSE file in the root directory of this source tree.
20 */
21/**
22 * inlined Object.is polyfill to avoid requiring consumers ship their own
23 * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is
24 */
25
26function isPolyfill(x, y) {
27 return x === y && (x !== 0 || 1 / x === 1 / y) || x !== x && y !== y // eslint-disable-line no-self-compare
28 ;
29}
30
31const is = typeof Object.is === "function" ? Object.is : isPolyfill; // Intentionally not using named imports because Rollup uses dynamic
32// dispatch for CommonJS interop named imports.
33
34const {
35 useState,
36 useEffect,
37 useLayoutEffect,
38 useDebugValue
39} = React;
40let didWarnOld18Alpha = false;
41let didWarnUncachedGetSnapshot = false; // Disclaimer: This shim breaks many of the rules of React, and only works
42// because of a very particular set of implementation details and assumptions
43// -- change any one of them and it will break. The most important assumption
44// is that updates are always synchronous, because concurrent rendering is
45// only available in versions of React that also have a built-in
46// useSyncExternalStore API. And we only use this shim when the built-in API
47// does not exist.
48//
49// Do not assume that the clever hacks used by this hook also work in general.
50// The point of this shim is to replace the need for hacks by other libraries.
51
52function useSyncExternalStore$2(subscribe, getSnapshot, // Note: The shim does not use getServerSnapshot, because pre-18 versions of
53// React do not expose a way to check if we're hydrating. So users of the shim
54// will need to track that themselves and return the correct value
55// from `getSnapshot`.
56getServerSnapshot) {
57 {
58 if (!didWarnOld18Alpha) {
59 if ("startTransition" in React) {
60 didWarnOld18Alpha = true;
61 console.error("You are using an outdated, pre-release alpha of React 18 that " + "does not support useSyncExternalStore. The " + "use-sync-external-store shim will not work correctly. Upgrade " + "to a newer pre-release.");
62 }
63 }
64 } // Read the current snapshot from the store on every render. Again, this
65 // breaks the rules of React, and only works here because of specific
66 // implementation details, most importantly that updates are
67 // always synchronous.
68
69
70 const value = getSnapshot();
71
72 {
73 if (!didWarnUncachedGetSnapshot) {
74 const cachedValue = getSnapshot();
75
76 if (!is(value, cachedValue)) {
77 console.error("The result of getSnapshot should be cached to avoid an infinite loop");
78 didWarnUncachedGetSnapshot = true;
79 }
80 }
81 } // Because updates are synchronous, we don't queue them. Instead we force a
82 // re-render whenever the subscribed state changes by updating an some
83 // arbitrary useState hook. Then, during render, we call getSnapshot to read
84 // the current value.
85 //
86 // Because we don't actually use the state returned by the useState hook, we
87 // can save a bit of memory by storing other stuff in that slot.
88 //
89 // To implement the early bailout, we need to track some things on a mutable
90 // object. Usually, we would put that in a useRef hook, but we can stash it in
91 // our useState hook instead.
92 //
93 // To force a re-render, we call forceUpdate({inst}). That works because the
94 // new object always fails an equality check.
95
96
97 const [{
98 inst
99 }, forceUpdate] = useState({
100 inst: {
101 value,
102 getSnapshot
103 }
104 }); // Track the latest getSnapshot function with a ref. This needs to be updated
105 // in the layout phase so we can access it during the tearing check that
106 // happens on subscribe.
107
108 useLayoutEffect(() => {
109 inst.value = value;
110 inst.getSnapshot = getSnapshot; // Whenever getSnapshot or subscribe changes, we need to check in the
111 // commit phase if there was an interleaved mutation. In concurrent mode
112 // this can happen all the time, but even in synchronous mode, an earlier
113 // effect may have mutated the store.
114
115 if (checkIfSnapshotChanged(inst)) {
116 // Force a re-render.
117 forceUpdate({
118 inst
119 });
120 } // eslint-disable-next-line react-hooks/exhaustive-deps
121
122 }, [subscribe, value, getSnapshot]);
123 useEffect(() => {
124 // Check for changes right before subscribing. Subsequent changes will be
125 // detected in the subscription handler.
126 if (checkIfSnapshotChanged(inst)) {
127 // Force a re-render.
128 forceUpdate({
129 inst
130 });
131 }
132
133 const handleStoreChange = () => {
134 // TODO: Because there is no cross-renderer API for batching updates, it's
135 // up to the consumer of this library to wrap their subscription event
136 // with unstable_batchedUpdates. Should we try to detect when this isn't
137 // the case and print a warning in development?
138 // The store changed. Check if the snapshot changed since the last time we
139 // read from the store.
140 if (checkIfSnapshotChanged(inst)) {
141 // Force a re-render.
142 forceUpdate({
143 inst
144 });
145 }
146 }; // Subscribe to the store and return a clean-up function.
147
148
149 return subscribe(handleStoreChange); // eslint-disable-next-line react-hooks/exhaustive-deps
150 }, [subscribe]);
151 useDebugValue(value);
152 return value;
153}
154
155function checkIfSnapshotChanged(inst) {
156 const latestGetSnapshot = inst.getSnapshot;
157 const prevValue = inst.value;
158
159 try {
160 const nextValue = latestGetSnapshot();
161 return !is(prevValue, nextValue);
162 } catch (error) {
163 return true;
164 }
165}
166
167/**
168 * Copyright (c) Facebook, Inc. and its affiliates.
169 *
170 * This source code is licensed under the MIT license found in the
171 * LICENSE file in the root directory of this source tree.
172 *
173 * @flow
174 */
175function useSyncExternalStore$1(subscribe, getSnapshot, getServerSnapshot) {
176 // Note: The shim does not use getServerSnapshot, because pre-18 versions of
177 // React do not expose a way to check if we're hydrating. So users of the shim
178 // will need to track that themselves and return the correct value
179 // from `getSnapshot`.
180 return getSnapshot();
181}
182
183/**
184 * Inlined into the react-router repo since use-sync-external-store does not
185 * provide a UMD-compatible package, so we need this to be able to distribute
186 * UMD react-router bundles
187 */
188const canUseDOM = !!(typeof window !== "undefined" && typeof window.document !== "undefined" && typeof window.document.createElement !== "undefined");
189const isServerEnvironment = !canUseDOM;
190const shim = isServerEnvironment ? useSyncExternalStore$1 : useSyncExternalStore$2;
191const useSyncExternalStore = "useSyncExternalStore" in React ? (module => module.useSyncExternalStore)(React) : shim;
192
193const DataRouterContext = /*#__PURE__*/React.createContext(null);
194
195{
196 DataRouterContext.displayName = "DataRouter";
197}
198
199const DataRouterStateContext = /*#__PURE__*/React.createContext(null);
200
201{
202 DataRouterStateContext.displayName = "DataRouterState";
203}
204
205const AwaitContext = /*#__PURE__*/React.createContext(null);
206
207{
208 AwaitContext.displayName = "Await";
209}
210
211const NavigationContext = /*#__PURE__*/React.createContext(null);
212
213{
214 NavigationContext.displayName = "Navigation";
215}
216
217const LocationContext = /*#__PURE__*/React.createContext(null);
218
219{
220 LocationContext.displayName = "Location";
221}
222
223const RouteContext = /*#__PURE__*/React.createContext({
224 outlet: null,
225 matches: []
226});
227
228{
229 RouteContext.displayName = "Route";
230}
231
232const RouteErrorContext = /*#__PURE__*/React.createContext(null);
233
234{
235 RouteErrorContext.displayName = "RouteError";
236}
237
238/**
239 * Returns the full href for the given "to" value. This is useful for building
240 * custom links that are also accessible and preserve right-click behavior.
241 *
242 * @see https://reactrouter.com/hooks/use-href
243 */
244
245function useHref(to, {
246 relative
247} = {}) {
248 !useInRouterContext() ? UNSAFE_invariant(false, // TODO: This error is probably because they somehow have 2 versions of the
249 // router loaded. We can help them understand how to avoid that.
250 `useHref() may be used only in the context of a <Router> component.`) : void 0;
251 let {
252 basename,
253 navigator
254 } = React.useContext(NavigationContext);
255 let {
256 hash,
257 pathname,
258 search
259 } = useResolvedPath(to, {
260 relative
261 });
262 let joinedPathname = pathname; // If we're operating within a basename, prepend it to the pathname prior
263 // to creating the href. If this is a root navigation, then just use the raw
264 // basename which allows the basename to have full control over the presence
265 // of a trailing slash on root links
266
267 if (basename !== "/") {
268 joinedPathname = pathname === "/" ? basename : joinPaths([basename, pathname]);
269 }
270
271 return navigator.createHref({
272 pathname: joinedPathname,
273 search,
274 hash
275 });
276}
277/**
278 * Returns true if this component is a descendant of a <Router>.
279 *
280 * @see https://reactrouter.com/hooks/use-in-router-context
281 */
282
283function useInRouterContext() {
284 return React.useContext(LocationContext) != null;
285}
286/**
287 * Returns the current location object, which represents the current URL in web
288 * browsers.
289 *
290 * Note: If you're using this it may mean you're doing some of your own
291 * "routing" in your app, and we'd like to know what your use case is. We may
292 * be able to provide something higher-level to better suit your needs.
293 *
294 * @see https://reactrouter.com/hooks/use-location
295 */
296
297function useLocation() {
298 !useInRouterContext() ? UNSAFE_invariant(false, // TODO: This error is probably because they somehow have 2 versions of the
299 // router loaded. We can help them understand how to avoid that.
300 `useLocation() may be used only in the context of a <Router> component.`) : void 0;
301 return React.useContext(LocationContext).location;
302}
303/**
304 * Returns the current navigation action which describes how the router came to
305 * the current location, either by a pop, push, or replace on the history stack.
306 *
307 * @see https://reactrouter.com/hooks/use-navigation-type
308 */
309
310function useNavigationType() {
311 return React.useContext(LocationContext).navigationType;
312}
313/**
314 * Returns a PathMatch object if the given pattern matches the current URL.
315 * This is useful for components that need to know "active" state, e.g.
316 * <NavLink>.
317 *
318 * @see https://reactrouter.com/hooks/use-match
319 */
320
321function useMatch(pattern) {
322 !useInRouterContext() ? UNSAFE_invariant(false, // TODO: This error is probably because they somehow have 2 versions of the
323 // router loaded. We can help them understand how to avoid that.
324 `useMatch() may be used only in the context of a <Router> component.`) : void 0;
325 let {
326 pathname
327 } = useLocation();
328 return React.useMemo(() => matchPath(pattern, pathname), [pathname, pattern]);
329}
330/**
331 * Returns an imperative method for changing the location. Used by <Link>s, but
332 * may also be used by other elements to change the location.
333 *
334 * @see https://reactrouter.com/hooks/use-navigate
335 */
336
337function useNavigate() {
338 !useInRouterContext() ? UNSAFE_invariant(false, // TODO: This error is probably because they somehow have 2 versions of the
339 // router loaded. We can help them understand how to avoid that.
340 `useNavigate() may be used only in the context of a <Router> component.`) : void 0;
341 let {
342 basename,
343 navigator
344 } = React.useContext(NavigationContext);
345 let {
346 matches
347 } = React.useContext(RouteContext);
348 let {
349 pathname: locationPathname
350 } = useLocation();
351 let routePathnamesJson = JSON.stringify(UNSAFE_getPathContributingMatches(matches).map(match => match.pathnameBase));
352 let activeRef = React.useRef(false);
353 React.useEffect(() => {
354 activeRef.current = true;
355 });
356 let navigate = React.useCallback((to, options = {}) => {
357 warning(activeRef.current, `You should call navigate() in a React.useEffect(), not when ` + `your component is first rendered.`) ;
358 if (!activeRef.current) return;
359
360 if (typeof to === "number") {
361 navigator.go(to);
362 return;
363 }
364
365 let path = resolveTo(to, JSON.parse(routePathnamesJson), locationPathname, options.relative === "path"); // If we're operating within a basename, prepend it to the pathname prior
366 // to handing off to history. If this is a root navigation, then we
367 // navigate to the raw basename which allows the basename to have full
368 // control over the presence of a trailing slash on root links
369
370 if (basename !== "/") {
371 path.pathname = path.pathname === "/" ? basename : joinPaths([basename, path.pathname]);
372 }
373
374 (!!options.replace ? navigator.replace : navigator.push)(path, options.state, options);
375 }, [basename, navigator, routePathnamesJson, locationPathname]);
376 return navigate;
377}
378const OutletContext = /*#__PURE__*/React.createContext(null);
379/**
380 * Returns the context (if provided) for the child route at this level of the route
381 * hierarchy.
382 * @see https://reactrouter.com/hooks/use-outlet-context
383 */
384
385function useOutletContext() {
386 return React.useContext(OutletContext);
387}
388/**
389 * Returns the element for the child route at this level of the route
390 * hierarchy. Used internally by <Outlet> to render child routes.
391 *
392 * @see https://reactrouter.com/hooks/use-outlet
393 */
394
395function useOutlet(context) {
396 let outlet = React.useContext(RouteContext).outlet;
397
398 if (outlet) {
399 return /*#__PURE__*/React.createElement(OutletContext.Provider, {
400 value: context
401 }, outlet);
402 }
403
404 return outlet;
405}
406/**
407 * Returns an object of key/value pairs of the dynamic params from the current
408 * URL that were matched by the route path.
409 *
410 * @see https://reactrouter.com/hooks/use-params
411 */
412
413function useParams() {
414 let {
415 matches
416 } = React.useContext(RouteContext);
417 let routeMatch = matches[matches.length - 1];
418 return routeMatch ? routeMatch.params : {};
419}
420/**
421 * Resolves the pathname of the given `to` value against the current location.
422 *
423 * @see https://reactrouter.com/hooks/use-resolved-path
424 */
425
426function useResolvedPath(to, {
427 relative
428} = {}) {
429 let {
430 matches
431 } = React.useContext(RouteContext);
432 let {
433 pathname: locationPathname
434 } = useLocation();
435 let routePathnamesJson = JSON.stringify(UNSAFE_getPathContributingMatches(matches).map(match => match.pathnameBase));
436 return React.useMemo(() => resolveTo(to, JSON.parse(routePathnamesJson), locationPathname, relative === "path"), [to, routePathnamesJson, locationPathname, relative]);
437}
438/**
439 * Returns the element of the route that matched the current location, prepared
440 * with the correct context to render the remainder of the route tree. Route
441 * elements in the tree must render an <Outlet> to render their child route's
442 * element.
443 *
444 * @see https://reactrouter.com/hooks/use-routes
445 */
446
447function useRoutes(routes, locationArg) {
448 !useInRouterContext() ? UNSAFE_invariant(false, // TODO: This error is probably because they somehow have 2 versions of the
449 // router loaded. We can help them understand how to avoid that.
450 `useRoutes() may be used only in the context of a <Router> component.`) : void 0;
451 let {
452 navigator
453 } = React.useContext(NavigationContext);
454 let dataRouterStateContext = React.useContext(DataRouterStateContext);
455 let {
456 matches: parentMatches
457 } = React.useContext(RouteContext);
458 let routeMatch = parentMatches[parentMatches.length - 1];
459 let parentParams = routeMatch ? routeMatch.params : {};
460 let parentPathname = routeMatch ? routeMatch.pathname : "/";
461 let parentPathnameBase = routeMatch ? routeMatch.pathnameBase : "/";
462 let parentRoute = routeMatch && routeMatch.route;
463
464 {
465 // You won't get a warning about 2 different <Routes> under a <Route>
466 // without a trailing *, but this is a best-effort warning anyway since we
467 // cannot even give the warning unless they land at the parent route.
468 //
469 // Example:
470 //
471 // <Routes>
472 // {/* This route path MUST end with /* because otherwise
473 // it will never match /blog/post/123 */}
474 // <Route path="blog" element={<Blog />} />
475 // <Route path="blog/feed" element={<BlogFeed />} />
476 // </Routes>
477 //
478 // function Blog() {
479 // return (
480 // <Routes>
481 // <Route path="post/:id" element={<Post />} />
482 // </Routes>
483 // );
484 // }
485 let parentPath = parentRoute && parentRoute.path || "";
486 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}/*`}">.`);
487 }
488
489 let locationFromContext = useLocation();
490 let location;
491
492 if (locationArg) {
493 let parsedLocationArg = typeof locationArg === "string" ? parsePath(locationArg) : locationArg;
494 !(parentPathnameBase === "/" || parsedLocationArg.pathname?.startsWith(parentPathnameBase)) ? 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;
495 location = parsedLocationArg;
496 } else {
497 location = locationFromContext;
498 }
499
500 let pathname = location.pathname || "/";
501 let remainingPathname = parentPathnameBase === "/" ? pathname : pathname.slice(parentPathnameBase.length) || "/";
502 let matches = matchRoutes(routes, {
503 pathname: remainingPathname
504 });
505
506 {
507 warning(parentRoute || matches != null, `No routes matched location "${location.pathname}${location.search}${location.hash}" `) ;
508 warning(matches == null || matches[matches.length - 1].route.element !== undefined, `Matched leaf route at location "${location.pathname}${location.search}${location.hash}" does not have an element. ` + `This means it will render an <Outlet /> with a null value by default resulting in an "empty" page.`) ;
509 }
510
511 let renderedMatches = _renderMatches(matches && matches.map(match => Object.assign({}, match, {
512 params: Object.assign({}, parentParams, match.params),
513 pathname: joinPaths([parentPathnameBase, // Re-encode pathnames that were decoded inside matchRoutes
514 navigator.encodeLocation ? navigator.encodeLocation(match.pathname).pathname : match.pathname]),
515 pathnameBase: match.pathnameBase === "/" ? parentPathnameBase : joinPaths([parentPathnameBase, // Re-encode pathnames that were decoded inside matchRoutes
516 navigator.encodeLocation ? navigator.encodeLocation(match.pathnameBase).pathname : match.pathnameBase])
517 })), parentMatches, dataRouterStateContext || undefined); // When a user passes in a `locationArg`, the associated routes need to
518 // be wrapped in a new `LocationContext.Provider` in order for `useLocation`
519 // to use the scoped location instead of the global location.
520
521
522 if (locationArg && renderedMatches) {
523 return /*#__PURE__*/React.createElement(LocationContext.Provider, {
524 value: {
525 location: {
526 pathname: "/",
527 search: "",
528 hash: "",
529 state: null,
530 key: "default",
531 ...location
532 },
533 navigationType: Action.Pop
534 }
535 }, renderedMatches);
536 }
537
538 return renderedMatches;
539}
540
541function DefaultErrorElement() {
542 let error = useRouteError();
543 let message = isRouteErrorResponse(error) ? `${error.status} ${error.statusText}` : error instanceof Error ? error.message : JSON.stringify(error);
544 let stack = error instanceof Error ? error.stack : null;
545 let lightgrey = "rgba(200,200,200, 0.5)";
546 let preStyles = {
547 padding: "0.5rem",
548 backgroundColor: lightgrey
549 };
550 let codeStyles = {
551 padding: "2px 4px",
552 backgroundColor: lightgrey
553 };
554 let devInfo = null;
555
556 {
557 devInfo = /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement("p", null, "\uD83D\uDCBF Hey developer \uD83D\uDC4B"), /*#__PURE__*/React.createElement("p", null, "You can provide a way better UX than this when your app throws errors by providing your own\u00A0", /*#__PURE__*/React.createElement("code", {
558 style: codeStyles
559 }, "errorElement"), " props on\u00A0", /*#__PURE__*/React.createElement("code", {
560 style: codeStyles
561 }, "<Route>")));
562 }
563
564 return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement("h2", null, "Unexpected Application Error!"), /*#__PURE__*/React.createElement("h3", {
565 style: {
566 fontStyle: "italic"
567 }
568 }, message), stack ? /*#__PURE__*/React.createElement("pre", {
569 style: preStyles
570 }, stack) : null, devInfo);
571}
572
573class RenderErrorBoundary extends React.Component {
574 constructor(props) {
575 super(props);
576 this.state = {
577 location: props.location,
578 error: props.error
579 };
580 }
581
582 static getDerivedStateFromError(error) {
583 return {
584 error: error
585 };
586 }
587
588 static getDerivedStateFromProps(props, state) {
589 // When we get into an error state, the user will likely click "back" to the
590 // previous page that didn't have an error. Because this wraps the entire
591 // application, that will have no effect--the error page continues to display.
592 // This gives us a mechanism to recover from the error when the location changes.
593 //
594 // Whether we're in an error state or not, we update the location in state
595 // so that when we are in an error state, it gets reset when a new location
596 // comes in and the user recovers from the error.
597 if (state.location !== props.location) {
598 return {
599 error: props.error,
600 location: props.location
601 };
602 } // If we're not changing locations, preserve the location but still surface
603 // any new errors that may come through. We retain the existing error, we do
604 // this because the error provided from the app state may be cleared without
605 // the location changing.
606
607
608 return {
609 error: props.error || state.error,
610 location: state.location
611 };
612 }
613
614 componentDidCatch(error, errorInfo) {
615 console.error("React Router caught the following error during render", error, errorInfo);
616 }
617
618 render() {
619 return this.state.error ? /*#__PURE__*/React.createElement(RouteContext.Provider, {
620 value: this.props.routeContext
621 }, /*#__PURE__*/React.createElement(RouteErrorContext.Provider, {
622 value: this.state.error,
623 children: this.props.component
624 })) : this.props.children;
625 }
626
627}
628
629function RenderedRoute({
630 routeContext,
631 match,
632 children
633}) {
634 let dataRouterContext = React.useContext(DataRouterContext); // Track how deep we got in our render pass to emulate SSR componentDidCatch
635 // in a DataStaticRouter
636
637 if (dataRouterContext && dataRouterContext.static && dataRouterContext.staticContext && match.route.errorElement) {
638 dataRouterContext.staticContext._deepestRenderedBoundaryId = match.route.id;
639 }
640
641 return /*#__PURE__*/React.createElement(RouteContext.Provider, {
642 value: routeContext
643 }, children);
644}
645
646function _renderMatches(matches, parentMatches = [], dataRouterState) {
647 if (matches == null) {
648 if (dataRouterState?.errors) {
649 // Don't bail if we have data router errors so we can render them in the
650 // boundary. Use the pre-matched (or shimmed) matches
651 matches = dataRouterState.matches;
652 } else {
653 return null;
654 }
655 }
656
657 let renderedMatches = matches; // If we have data errors, trim matches to the highest error boundary
658
659 let errors = dataRouterState?.errors;
660
661 if (errors != null) {
662 let errorIndex = renderedMatches.findIndex(m => m.route.id && errors?.[m.route.id]);
663 !(errorIndex >= 0) ? UNSAFE_invariant(false, `Could not find a matching route for the current errors: ${errors}`) : void 0;
664 renderedMatches = renderedMatches.slice(0, Math.min(renderedMatches.length, errorIndex + 1));
665 }
666
667 return renderedMatches.reduceRight((outlet, match, index) => {
668 let error = match.route.id ? errors?.[match.route.id] : null; // Only data routers handle errors
669
670 let errorElement = dataRouterState ? match.route.errorElement || /*#__PURE__*/React.createElement(DefaultErrorElement, null) : null;
671 let matches = parentMatches.concat(renderedMatches.slice(0, index + 1));
672
673 let getChildren = () => /*#__PURE__*/React.createElement(RenderedRoute, {
674 match: match,
675 routeContext: {
676 outlet,
677 matches
678 }
679 }, error ? errorElement : match.route.element !== undefined ? match.route.element : outlet); // Only wrap in an error boundary within data router usages when we have an
680 // errorElement on this route. Otherwise let it bubble up to an ancestor
681 // errorElement
682
683
684 return dataRouterState && (match.route.errorElement || index === 0) ? /*#__PURE__*/React.createElement(RenderErrorBoundary, {
685 location: dataRouterState.location,
686 component: errorElement,
687 error: error,
688 children: getChildren(),
689 routeContext: {
690 outlet: null,
691 matches
692 }
693 }) : getChildren();
694 }, null);
695}
696var DataRouterHook;
697
698(function (DataRouterHook) {
699 DataRouterHook["UseBlocker"] = "useBlocker";
700 DataRouterHook["UseRevalidator"] = "useRevalidator";
701})(DataRouterHook || (DataRouterHook = {}));
702
703var DataRouterStateHook;
704
705(function (DataRouterStateHook) {
706 DataRouterStateHook["UseLoaderData"] = "useLoaderData";
707 DataRouterStateHook["UseActionData"] = "useActionData";
708 DataRouterStateHook["UseRouteError"] = "useRouteError";
709 DataRouterStateHook["UseNavigation"] = "useNavigation";
710 DataRouterStateHook["UseRouteLoaderData"] = "useRouteLoaderData";
711 DataRouterStateHook["UseMatches"] = "useMatches";
712 DataRouterStateHook["UseRevalidator"] = "useRevalidator";
713})(DataRouterStateHook || (DataRouterStateHook = {}));
714
715function getDataRouterConsoleError(hookName) {
716 return `${hookName} must be used within a data router. See https://reactrouter.com/routers/picking-a-router.`;
717}
718
719function useDataRouterContext(hookName) {
720 let ctx = React.useContext(DataRouterContext);
721 !ctx ? UNSAFE_invariant(false, getDataRouterConsoleError(hookName)) : void 0;
722 return ctx;
723}
724
725function useDataRouterState(hookName) {
726 let state = React.useContext(DataRouterStateContext);
727 !state ? UNSAFE_invariant(false, getDataRouterConsoleError(hookName)) : void 0;
728 return state;
729}
730
731function useRouteContext(hookName) {
732 let route = React.useContext(RouteContext);
733 !route ? UNSAFE_invariant(false, getDataRouterConsoleError(hookName)) : void 0;
734 return route;
735}
736
737function useCurrentRouteId(hookName) {
738 let route = useRouteContext(hookName);
739 let thisRoute = route.matches[route.matches.length - 1];
740 !thisRoute.route.id ? UNSAFE_invariant(false, `${hookName} can only be used on routes that contain a unique "id"`) : void 0;
741 return thisRoute.route.id;
742}
743/**
744 * Returns the current navigation, defaulting to an "idle" navigation when
745 * no navigation is in progress
746 */
747
748
749function useNavigation() {
750 let state = useDataRouterState(DataRouterStateHook.UseNavigation);
751 return state.navigation;
752}
753/**
754 * Returns a revalidate function for manually triggering revalidation, as well
755 * as the current state of any manual revalidations
756 */
757
758function useRevalidator() {
759 let dataRouterContext = useDataRouterContext(DataRouterHook.UseRevalidator);
760 let state = useDataRouterState(DataRouterStateHook.UseRevalidator);
761 return {
762 revalidate: dataRouterContext.router.revalidate,
763 state: state.revalidation
764 };
765}
766/**
767 * Returns the active route matches, useful for accessing loaderData for
768 * parent/child routes or the route "handle" property
769 */
770
771function useMatches() {
772 let {
773 matches,
774 loaderData
775 } = useDataRouterState(DataRouterStateHook.UseMatches);
776 return React.useMemo(() => matches.map(match => {
777 let {
778 pathname,
779 params
780 } = match; // Note: This structure matches that created by createUseMatchesMatch
781 // in the @remix-run/router , so if you change this please also change
782 // that :) Eventually we'll DRY this up
783
784 return {
785 id: match.route.id,
786 pathname,
787 params,
788 data: loaderData[match.route.id],
789 handle: match.route.handle
790 };
791 }), [matches, loaderData]);
792}
793/**
794 * Returns the loader data for the nearest ancestor Route loader
795 */
796
797function useLoaderData() {
798 let state = useDataRouterState(DataRouterStateHook.UseLoaderData);
799 let routeId = useCurrentRouteId(DataRouterStateHook.UseLoaderData);
800
801 if (state.errors && state.errors[routeId] != null) {
802 console.error(`You cannot \`useLoaderData\` in an errorElement (routeId: ${routeId})`);
803 return undefined;
804 }
805
806 return state.loaderData[routeId];
807}
808/**
809 * Returns the loaderData for the given routeId
810 */
811
812function useRouteLoaderData(routeId) {
813 let state = useDataRouterState(DataRouterStateHook.UseRouteLoaderData);
814 return state.loaderData[routeId];
815}
816/**
817 * Returns the action data for the nearest ancestor Route action
818 */
819
820function useActionData() {
821 let state = useDataRouterState(DataRouterStateHook.UseActionData);
822 let route = React.useContext(RouteContext);
823 !route ? UNSAFE_invariant(false, `useActionData must be used inside a RouteContext`) : void 0;
824 return Object.values(state?.actionData || {})[0];
825}
826/**
827 * Returns the nearest ancestor Route error, which could be a loader/action
828 * error or a render error. This is intended to be called from your
829 * errorElement to display a proper error message.
830 */
831
832function useRouteError() {
833 let error = React.useContext(RouteErrorContext);
834 let state = useDataRouterState(DataRouterStateHook.UseRouteError);
835 let routeId = useCurrentRouteId(DataRouterStateHook.UseRouteError); // If this was a render error, we put it in a RouteError context inside
836 // of RenderErrorBoundary
837
838 if (error) {
839 return error;
840 } // Otherwise look for errors from our data router state
841
842
843 return state.errors?.[routeId];
844}
845/**
846 * Returns the happy-path data from the nearest ancestor <Await /> value
847 */
848
849function useAsyncValue() {
850 let value = React.useContext(AwaitContext);
851 return value?._data;
852}
853/**
854 * Returns the error from the nearest ancestor <Await /> value
855 */
856
857function useAsyncError() {
858 let value = React.useContext(AwaitContext);
859 return value?._error;
860}
861let blockerId = 0;
862/**
863 * Allow the application to block navigations within the SPA and present the
864 * user a confirmation dialog to confirm the navigation. Mostly used to avoid
865 * using half-filled form data. This does not handle hard-reloads or
866 * cross-origin navigations.
867 */
868
869function useBlocker(shouldBlock) {
870 let {
871 router
872 } = useDataRouterContext(DataRouterHook.UseBlocker);
873 let [blockerKey] = React.useState(() => String(++blockerId));
874 let blockerFunction = React.useCallback(args => {
875 return typeof shouldBlock === "function" ? !!shouldBlock(args) : !!shouldBlock;
876 }, [shouldBlock]);
877 let blocker = router.getBlocker(blockerKey, blockerFunction); // Cleanup on unmount
878
879 React.useEffect(() => () => router.deleteBlocker(blockerKey), [router, blockerKey]);
880 return blocker;
881}
882const alreadyWarned = {};
883
884function warningOnce(key, cond, message) {
885 if (!cond && !alreadyWarned[key]) {
886 alreadyWarned[key] = true;
887 warning(false, message) ;
888 }
889}
890
891/**
892 * Given a Remix Router instance, render the appropriate UI
893 */
894
895function RouterProvider({
896 fallbackElement,
897 router
898}) {
899 // Sync router state to our component state to force re-renders
900 let state = useSyncExternalStore(router.subscribe, () => router.state, // We have to provide this so React@18 doesn't complain during hydration,
901 // but we pass our serialized hydration data into the router so state here
902 // is already synced with what the server saw
903 () => router.state);
904 let navigator = React.useMemo(() => {
905 return {
906 createHref: router.createHref,
907 encodeLocation: router.encodeLocation,
908 go: n => router.navigate(n),
909 push: (to, state, opts) => router.navigate(to, {
910 state,
911 preventScrollReset: opts?.preventScrollReset
912 }),
913 replace: (to, state, opts) => router.navigate(to, {
914 replace: true,
915 state,
916 preventScrollReset: opts?.preventScrollReset
917 })
918 };
919 }, [router]);
920 let basename = router.basename || "/"; // The fragment and {null} here are important! We need them to keep React 18's
921 // useId happy when we are server-rendering since we may have a <script> here
922 // containing the hydrated server-side staticContext (from StaticRouterProvider).
923 // useId relies on the component tree structure to generate deterministic id's
924 // so we need to ensure it remains the same on the client even though
925 // we don't need the <script> tag
926
927 return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(DataRouterContext.Provider, {
928 value: {
929 router,
930 navigator,
931 static: false,
932 // Do we need this?
933 basename
934 }
935 }, /*#__PURE__*/React.createElement(DataRouterStateContext.Provider, {
936 value: state
937 }, /*#__PURE__*/React.createElement(Router, {
938 basename: router.basename,
939 location: router.state.location,
940 navigationType: router.state.historyAction,
941 navigator: navigator
942 }, router.state.initialized ? /*#__PURE__*/React.createElement(Routes, null) : fallbackElement))), null);
943}
944/**
945 * A <Router> that stores all entries in memory.
946 *
947 * @see https://reactrouter.com/router-components/memory-router
948 */
949
950function MemoryRouter({
951 basename,
952 children,
953 initialEntries,
954 initialIndex
955}) {
956 let historyRef = React.useRef();
957
958 if (historyRef.current == null) {
959 historyRef.current = createMemoryHistory({
960 initialEntries,
961 initialIndex,
962 v5Compat: true
963 });
964 }
965
966 let history = historyRef.current;
967 let [state, setState] = React.useState({
968 action: history.action,
969 location: history.location
970 });
971 React.useLayoutEffect(() => history.listen(setState), [history]);
972 return /*#__PURE__*/React.createElement(Router, {
973 basename: basename,
974 children: children,
975 location: state.location,
976 navigationType: state.action,
977 navigator: history
978 });
979}
980/**
981 * Changes the current location.
982 *
983 * Note: This API is mostly useful in React.Component subclasses that are not
984 * able to use hooks. In functional components, we recommend you use the
985 * `useNavigate` hook instead.
986 *
987 * @see https://reactrouter.com/components/navigate
988 */
989
990function Navigate({
991 to,
992 replace,
993 state,
994 relative
995}) {
996 !useInRouterContext() ? UNSAFE_invariant(false, // TODO: This error is probably because they somehow have 2 versions of
997 // the router loaded. We can help them understand how to avoid that.
998 `<Navigate> may be used only in the context of a <Router> component.`) : void 0;
999 warning(!React.useContext(NavigationContext).static, `<Navigate> must not be used on the initial render in a <StaticRouter>. ` + `This is a no-op, but you should modify your code so the <Navigate> is ` + `only ever rendered in response to some user interaction or state change.`) ;
1000 let dataRouterState = React.useContext(DataRouterStateContext);
1001 let navigate = useNavigate();
1002 React.useEffect(() => {
1003 // Avoid kicking off multiple navigations if we're in the middle of a
1004 // data-router navigation, since components get re-rendered when we enter
1005 // a submitting/loading state
1006 if (dataRouterState && dataRouterState.navigation.state !== "idle") {
1007 return;
1008 }
1009
1010 navigate(to, {
1011 replace,
1012 state,
1013 relative
1014 });
1015 });
1016 return null;
1017}
1018/**
1019 * Renders the child route's element, if there is one.
1020 *
1021 * @see https://reactrouter.com/components/outlet
1022 */
1023
1024function Outlet(props) {
1025 return useOutlet(props.context);
1026}
1027/**
1028 * Declares an element that should be rendered at a certain URL path.
1029 *
1030 * @see https://reactrouter.com/components/route
1031 */
1032
1033function Route(_props) {
1034 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>.`) ;
1035}
1036/**
1037 * Provides location context for the rest of the app.
1038 *
1039 * Note: You usually won't render a <Router> directly. Instead, you'll render a
1040 * router that is more specific to your environment such as a <BrowserRouter>
1041 * in web browsers or a <StaticRouter> for server rendering.
1042 *
1043 * @see https://reactrouter.com/router-components/router
1044 */
1045
1046function Router({
1047 basename: basenameProp = "/",
1048 children = null,
1049 location: locationProp,
1050 navigationType = Action.Pop,
1051 navigator,
1052 static: staticProp = false
1053}) {
1054 !!useInRouterContext() ? UNSAFE_invariant(false, `You cannot render a <Router> inside another <Router>.` + ` You should never have more than one in your app.`) : void 0; // Preserve trailing slashes on basename, so we can let the user control
1055 // the enforcement of trailing slashes throughout the app
1056
1057 let basename = basenameProp.replace(/^\/*/, "/");
1058 let navigationContext = React.useMemo(() => ({
1059 basename,
1060 navigator,
1061 static: staticProp
1062 }), [basename, navigator, staticProp]);
1063
1064 if (typeof locationProp === "string") {
1065 locationProp = parsePath(locationProp);
1066 }
1067
1068 let {
1069 pathname = "/",
1070 search = "",
1071 hash = "",
1072 state = null,
1073 key = "default"
1074 } = locationProp;
1075 let location = React.useMemo(() => {
1076 let trailingPathname = stripBasename(pathname, basename);
1077
1078 if (trailingPathname == null) {
1079 return null;
1080 }
1081
1082 return {
1083 pathname: trailingPathname,
1084 search,
1085 hash,
1086 state,
1087 key
1088 };
1089 }, [basename, pathname, search, hash, state, key]);
1090 warning(location != 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.`) ;
1091
1092 if (location == null) {
1093 return null;
1094 }
1095
1096 return /*#__PURE__*/React.createElement(NavigationContext.Provider, {
1097 value: navigationContext
1098 }, /*#__PURE__*/React.createElement(LocationContext.Provider, {
1099 children: children,
1100 value: {
1101 location,
1102 navigationType
1103 }
1104 }));
1105}
1106/**
1107 * A container for a nested tree of <Route> elements that renders the branch
1108 * that best matches the current location.
1109 *
1110 * @see https://reactrouter.com/components/routes
1111 */
1112
1113function Routes({
1114 children,
1115 location
1116}) {
1117 let dataRouterContext = React.useContext(DataRouterContext); // When in a DataRouterContext _without_ children, we use the router routes
1118 // directly. If we have children, then we're in a descendant tree and we
1119 // need to use child routes.
1120
1121 let routes = dataRouterContext && !children ? dataRouterContext.router.routes : createRoutesFromChildren(children);
1122 return useRoutes(routes, location);
1123}
1124/**
1125 * Component to use for rendering lazily loaded data from returning defer()
1126 * in a loader function
1127 */
1128
1129function Await({
1130 children,
1131 errorElement,
1132 resolve
1133}) {
1134 return /*#__PURE__*/React.createElement(AwaitErrorBoundary, {
1135 resolve: resolve,
1136 errorElement: errorElement
1137 }, /*#__PURE__*/React.createElement(ResolveAwait, null, children));
1138}
1139var AwaitRenderStatus;
1140
1141(function (AwaitRenderStatus) {
1142 AwaitRenderStatus[AwaitRenderStatus["pending"] = 0] = "pending";
1143 AwaitRenderStatus[AwaitRenderStatus["success"] = 1] = "success";
1144 AwaitRenderStatus[AwaitRenderStatus["error"] = 2] = "error";
1145})(AwaitRenderStatus || (AwaitRenderStatus = {}));
1146
1147const neverSettledPromise = new Promise(() => {});
1148
1149class AwaitErrorBoundary extends React.Component {
1150 constructor(props) {
1151 super(props);
1152 this.state = {
1153 error: null
1154 };
1155 }
1156
1157 static getDerivedStateFromError(error) {
1158 return {
1159 error
1160 };
1161 }
1162
1163 componentDidCatch(error, errorInfo) {
1164 console.error("<Await> caught the following error during render", error, errorInfo);
1165 }
1166
1167 render() {
1168 let {
1169 children,
1170 errorElement,
1171 resolve
1172 } = this.props;
1173 let promise = null;
1174 let status = AwaitRenderStatus.pending;
1175
1176 if (!(resolve instanceof Promise)) {
1177 // Didn't get a promise - provide as a resolved promise
1178 status = AwaitRenderStatus.success;
1179 promise = Promise.resolve();
1180 Object.defineProperty(promise, "_tracked", {
1181 get: () => true
1182 });
1183 Object.defineProperty(promise, "_data", {
1184 get: () => resolve
1185 });
1186 } else if (this.state.error) {
1187 // Caught a render error, provide it as a rejected promise
1188 status = AwaitRenderStatus.error;
1189 let renderError = this.state.error;
1190 promise = Promise.reject().catch(() => {}); // Avoid unhandled rejection warnings
1191
1192 Object.defineProperty(promise, "_tracked", {
1193 get: () => true
1194 });
1195 Object.defineProperty(promise, "_error", {
1196 get: () => renderError
1197 });
1198 } else if (resolve._tracked) {
1199 // Already tracked promise - check contents
1200 promise = resolve;
1201 status = promise._error !== undefined ? AwaitRenderStatus.error : promise._data !== undefined ? AwaitRenderStatus.success : AwaitRenderStatus.pending;
1202 } else {
1203 // Raw (untracked) promise - track it
1204 status = AwaitRenderStatus.pending;
1205 Object.defineProperty(resolve, "_tracked", {
1206 get: () => true
1207 });
1208 promise = resolve.then(data => Object.defineProperty(resolve, "_data", {
1209 get: () => data
1210 }), error => Object.defineProperty(resolve, "_error", {
1211 get: () => error
1212 }));
1213 }
1214
1215 if (status === AwaitRenderStatus.error && promise._error instanceof AbortedDeferredError) {
1216 // Freeze the UI by throwing a never resolved promise
1217 throw neverSettledPromise;
1218 }
1219
1220 if (status === AwaitRenderStatus.error && !errorElement) {
1221 // No errorElement, throw to the nearest route-level error boundary
1222 throw promise._error;
1223 }
1224
1225 if (status === AwaitRenderStatus.error) {
1226 // Render via our errorElement
1227 return /*#__PURE__*/React.createElement(AwaitContext.Provider, {
1228 value: promise,
1229 children: errorElement
1230 });
1231 }
1232
1233 if (status === AwaitRenderStatus.success) {
1234 // Render children with resolved value
1235 return /*#__PURE__*/React.createElement(AwaitContext.Provider, {
1236 value: promise,
1237 children: children
1238 });
1239 } // Throw to the suspense boundary
1240
1241
1242 throw promise;
1243 }
1244
1245}
1246/**
1247 * @private
1248 * Indirection to leverage useAsyncValue for a render-prop API on <Await>
1249 */
1250
1251
1252function ResolveAwait({
1253 children
1254}) {
1255 let data = useAsyncValue();
1256 let toRender = typeof children === "function" ? children(data) : children;
1257 return /*#__PURE__*/React.createElement(React.Fragment, null, toRender);
1258} ///////////////////////////////////////////////////////////////////////////////
1259// UTILS
1260///////////////////////////////////////////////////////////////////////////////
1261
1262/**
1263 * Creates a route config from a React "children" object, which is usually
1264 * either a `<Route>` element or an array of them. Used internally by
1265 * `<Routes>` to create a route config from its children.
1266 *
1267 * @see https://reactrouter.com/utils/create-routes-from-children
1268 */
1269
1270
1271function createRoutesFromChildren(children, parentPath = []) {
1272 let routes = [];
1273 React.Children.forEach(children, (element, index) => {
1274 if (! /*#__PURE__*/React.isValidElement(element)) {
1275 // Ignore non-elements. This allows people to more easily inline
1276 // conditionals in their route config.
1277 return;
1278 }
1279
1280 if (element.type === React.Fragment) {
1281 // Transparently support React.Fragment and its children.
1282 routes.push.apply(routes, createRoutesFromChildren(element.props.children, parentPath));
1283 return;
1284 }
1285
1286 !(element.type === Route) ? 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;
1287 !(!element.props.index || !element.props.children) ? UNSAFE_invariant(false, "An index route cannot have child routes.") : void 0;
1288 let treePath = [...parentPath, index];
1289 let route = {
1290 id: element.props.id || treePath.join("-"),
1291 caseSensitive: element.props.caseSensitive,
1292 element: element.props.element,
1293 index: element.props.index,
1294 path: element.props.path,
1295 loader: element.props.loader,
1296 action: element.props.action,
1297 errorElement: element.props.errorElement,
1298 hasErrorBoundary: element.props.errorElement != null,
1299 shouldRevalidate: element.props.shouldRevalidate,
1300 handle: element.props.handle
1301 };
1302
1303 if (element.props.children) {
1304 route.children = createRoutesFromChildren(element.props.children, treePath);
1305 }
1306
1307 routes.push(route);
1308 });
1309 return routes;
1310}
1311/**
1312 * Renders the result of `matchRoutes()` into a React element.
1313 */
1314
1315function renderMatches(matches) {
1316 return _renderMatches(matches);
1317}
1318/**
1319 * @private
1320 * Walk the route tree and add hasErrorBoundary if it's not provided, so that
1321 * users providing manual route arrays can just specify errorElement
1322 */
1323
1324function enhanceManualRouteObjects(routes) {
1325 return routes.map(route => {
1326 let routeClone = { ...route
1327 };
1328
1329 if (routeClone.hasErrorBoundary == null) {
1330 routeClone.hasErrorBoundary = routeClone.errorElement != null;
1331 }
1332
1333 if (routeClone.children) {
1334 routeClone.children = enhanceManualRouteObjects(routeClone.children);
1335 }
1336
1337 return routeClone;
1338 });
1339}
1340
1341function createMemoryRouter(routes, opts) {
1342 return createRouter({
1343 basename: opts?.basename,
1344 history: createMemoryHistory({
1345 initialEntries: opts?.initialEntries,
1346 initialIndex: opts?.initialIndex
1347 }),
1348 hydrationData: opts?.hydrationData,
1349 routes: enhanceManualRouteObjects(routes)
1350 }).initialize();
1351} ///////////////////////////////////////////////////////////////////////////////
1352
1353export { Await, MemoryRouter, Navigate, Outlet, Route, Router, RouterProvider, Routes, DataRouterContext as UNSAFE_DataRouterContext, DataRouterStateContext as UNSAFE_DataRouterStateContext, LocationContext as UNSAFE_LocationContext, NavigationContext as UNSAFE_NavigationContext, RouteContext as UNSAFE_RouteContext, enhanceManualRouteObjects as UNSAFE_enhanceManualRouteObjects, createMemoryRouter, createRoutesFromChildren, createRoutesFromChildren as createRoutesFromElements, renderMatches, useBlocker as unstable_useBlocker, useActionData, useAsyncError, useAsyncValue, useHref, useInRouterContext, useLoaderData, useLocation, useMatch, useMatches, useNavigate, useNavigation, useNavigationType, useOutlet, useOutletContext, useParams, useResolvedPath, useRevalidator, useRouteError, useRouteLoaderData, useRoutes };
1354//# sourceMappingURL=react-router.development.js.map