1 | /**
|
2 | * React Router v6.8.0
|
3 | *
|
4 | * Copyright (c) Remix Software Inc.
|
5 | *
|
6 | * This source code is licensed under the MIT license found in the
|
7 | * LICENSE.md file in the root directory of this source tree.
|
8 | *
|
9 | * @license MIT
|
10 | */
|
11 | import { invariant, joinPaths, matchPath, UNSAFE_getPathContributingMatches, warning, resolveTo, parsePath, matchRoutes, Action, isRouteErrorResponse, createMemoryHistory, stripBasename, AbortedDeferredError, createRouter } from '@remix-run/router';
|
12 | export { AbortedDeferredError, Action as NavigationType, createPath, defer, generatePath, isRouteErrorResponse, json, matchPath, matchRoutes, parsePath, redirect, resolvePath } from '@remix-run/router';
|
13 | import * 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 |
|
26 | function 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 |
|
31 | const 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 |
|
34 | const {
|
35 | useState,
|
36 | useEffect,
|
37 | useLayoutEffect,
|
38 | useDebugValue
|
39 | } = React;
|
40 | let didWarnOld18Alpha = false;
|
41 | let 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 |
|
52 | function 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`.
|
56 | getServerSnapshot) {
|
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 |
|
155 | function 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 | */
|
175 | function 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 | */
|
188 | const canUseDOM = !!(typeof window !== "undefined" && typeof window.document !== "undefined" && typeof window.document.createElement !== "undefined");
|
189 | const isServerEnvironment = !canUseDOM;
|
190 | const shim = isServerEnvironment ? useSyncExternalStore$1 : useSyncExternalStore$2;
|
191 | const useSyncExternalStore = "useSyncExternalStore" in React ? (module => module.useSyncExternalStore)(React) : shim;
|
192 |
|
193 | const DataRouterContext = /*#__PURE__*/React.createContext(null);
|
194 |
|
195 | {
|
196 | DataRouterContext.displayName = "DataRouter";
|
197 | }
|
198 |
|
199 | const DataRouterStateContext = /*#__PURE__*/React.createContext(null);
|
200 |
|
201 | {
|
202 | DataRouterStateContext.displayName = "DataRouterState";
|
203 | }
|
204 |
|
205 | const AwaitContext = /*#__PURE__*/React.createContext(null);
|
206 |
|
207 | {
|
208 | AwaitContext.displayName = "Await";
|
209 | }
|
210 |
|
211 | const NavigationContext = /*#__PURE__*/React.createContext(null);
|
212 |
|
213 | {
|
214 | NavigationContext.displayName = "Navigation";
|
215 | }
|
216 |
|
217 | const LocationContext = /*#__PURE__*/React.createContext(null);
|
218 |
|
219 | {
|
220 | LocationContext.displayName = "Location";
|
221 | }
|
222 |
|
223 | const RouteContext = /*#__PURE__*/React.createContext({
|
224 | outlet: null,
|
225 | matches: []
|
226 | });
|
227 |
|
228 | {
|
229 | RouteContext.displayName = "Route";
|
230 | }
|
231 |
|
232 | const 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 |
|
245 | function useHref(to, {
|
246 | relative
|
247 | } = {}) {
|
248 | !useInRouterContext() ? 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 |
|
283 | function 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 |
|
297 | function useLocation() {
|
298 | !useInRouterContext() ? 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 |
|
310 | function 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 |
|
321 | function useMatch(pattern) {
|
322 | !useInRouterContext() ? 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 |
|
337 | function useNavigate() {
|
338 | !useInRouterContext() ? 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 | }
|
378 | const 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 |
|
385 | function 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 |
|
395 | function 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 |
|
413 | function 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 |
|
426 | function 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 |
|
447 | function useRoutes(routes, locationArg) {
|
448 | !useInRouterContext() ? 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)) ? 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 |
|
541 | function 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 |
|
573 | class 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 |
|
629 | function 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 |
|
646 | function _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) ? 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 | }
|
696 | var DataRouterHook;
|
697 |
|
698 | (function (DataRouterHook) {
|
699 | DataRouterHook["UseBlocker"] = "useBlocker";
|
700 | DataRouterHook["UseRevalidator"] = "useRevalidator";
|
701 | })(DataRouterHook || (DataRouterHook = {}));
|
702 |
|
703 | var 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 |
|
715 | function getDataRouterConsoleError(hookName) {
|
716 | return `${hookName} must be used within a data router. See https://reactrouter.com/routers/picking-a-router.`;
|
717 | }
|
718 |
|
719 | function useDataRouterContext(hookName) {
|
720 | let ctx = React.useContext(DataRouterContext);
|
721 | !ctx ? invariant(false, getDataRouterConsoleError(hookName)) : void 0;
|
722 | return ctx;
|
723 | }
|
724 |
|
725 | function useDataRouterState(hookName) {
|
726 | let state = React.useContext(DataRouterStateContext);
|
727 | !state ? invariant(false, getDataRouterConsoleError(hookName)) : void 0;
|
728 | return state;
|
729 | }
|
730 |
|
731 | function useRouteContext(hookName) {
|
732 | let route = React.useContext(RouteContext);
|
733 | !route ? invariant(false, getDataRouterConsoleError(hookName)) : void 0;
|
734 | return route;
|
735 | }
|
736 |
|
737 | function useCurrentRouteId(hookName) {
|
738 | let route = useRouteContext(hookName);
|
739 | let thisRoute = route.matches[route.matches.length - 1];
|
740 | !thisRoute.route.id ? 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 |
|
749 | function 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 |
|
758 | function 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 |
|
771 | function 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 |
|
797 | function 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 |
|
812 | function 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 |
|
820 | function useActionData() {
|
821 | let state = useDataRouterState(DataRouterStateHook.UseActionData);
|
822 | let route = React.useContext(RouteContext);
|
823 | !route ? 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 |
|
832 | function 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 |
|
849 | function 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 |
|
857 | function useAsyncError() {
|
858 | let value = React.useContext(AwaitContext);
|
859 | return value?._error;
|
860 | } // useBlocker() is a singleton for now since we don't have any compelling use
|
861 | // cases for multi-blocker yet
|
862 |
|
863 | let blockerKey = "blocker-singleton";
|
864 | /**
|
865 | * Allow the application to block navigations within the SPA and present the
|
866 | * user a confirmation dialog to confirm the navigation. Mostly used to avoid
|
867 | * using half-filled form data. This does not handle hard-reloads or
|
868 | * cross-origin navigations.
|
869 | */
|
870 |
|
871 | function useBlocker(shouldBlock) {
|
872 | let {
|
873 | router
|
874 | } = useDataRouterContext(DataRouterHook.UseBlocker);
|
875 | let blockerFunction = React.useCallback(args => {
|
876 | return typeof shouldBlock === "function" ? !!shouldBlock(args) : !!shouldBlock;
|
877 | }, [shouldBlock]);
|
878 | let blocker = router.getBlocker(blockerKey, blockerFunction); // Cleanup on unmount
|
879 |
|
880 | React.useEffect(() => () => router.deleteBlocker(blockerKey), [router]);
|
881 | return blocker;
|
882 | }
|
883 | const alreadyWarned = {};
|
884 |
|
885 | function warningOnce(key, cond, message) {
|
886 | if (!cond && !alreadyWarned[key]) {
|
887 | alreadyWarned[key] = true;
|
888 | warning(false, message) ;
|
889 | }
|
890 | }
|
891 |
|
892 | /**
|
893 | * Given a Remix Router instance, render the appropriate UI
|
894 | */
|
895 |
|
896 | function RouterProvider({
|
897 | fallbackElement,
|
898 | router
|
899 | }) {
|
900 | // Sync router state to our component state to force re-renders
|
901 | let state = useSyncExternalStore(router.subscribe, () => router.state, // We have to provide this so React@18 doesn't complain during hydration,
|
902 | // but we pass our serialized hydration data into the router so state here
|
903 | // is already synced with what the server saw
|
904 | () => router.state);
|
905 | let navigator = React.useMemo(() => {
|
906 | return {
|
907 | createHref: router.createHref,
|
908 | encodeLocation: router.encodeLocation,
|
909 | go: n => router.navigate(n),
|
910 | push: (to, state, opts) => router.navigate(to, {
|
911 | state,
|
912 | preventScrollReset: opts?.preventScrollReset
|
913 | }),
|
914 | replace: (to, state, opts) => router.navigate(to, {
|
915 | replace: true,
|
916 | state,
|
917 | preventScrollReset: opts?.preventScrollReset
|
918 | })
|
919 | };
|
920 | }, [router]);
|
921 | let basename = router.basename || "/"; // The fragment and {null} here are important! We need them to keep React 18's
|
922 | // useId happy when we are server-rendering since we may have a <script> here
|
923 | // containing the hydrated server-side staticContext (from StaticRouterProvider).
|
924 | // useId relies on the component tree structure to generate deterministic id's
|
925 | // so we need to ensure it remains the same on the client even though
|
926 | // we don't need the <script> tag
|
927 |
|
928 | return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(DataRouterContext.Provider, {
|
929 | value: {
|
930 | router,
|
931 | navigator,
|
932 | static: false,
|
933 | // Do we need this?
|
934 | basename
|
935 | }
|
936 | }, /*#__PURE__*/React.createElement(DataRouterStateContext.Provider, {
|
937 | value: state
|
938 | }, /*#__PURE__*/React.createElement(Router, {
|
939 | basename: router.basename,
|
940 | location: router.state.location,
|
941 | navigationType: router.state.historyAction,
|
942 | navigator: navigator
|
943 | }, router.state.initialized ? /*#__PURE__*/React.createElement(Routes, null) : fallbackElement))), null);
|
944 | }
|
945 | /**
|
946 | * A <Router> that stores all entries in memory.
|
947 | *
|
948 | * @see https://reactrouter.com/router-components/memory-router
|
949 | */
|
950 |
|
951 | function MemoryRouter({
|
952 | basename,
|
953 | children,
|
954 | initialEntries,
|
955 | initialIndex
|
956 | }) {
|
957 | let historyRef = React.useRef();
|
958 |
|
959 | if (historyRef.current == null) {
|
960 | historyRef.current = createMemoryHistory({
|
961 | initialEntries,
|
962 | initialIndex,
|
963 | v5Compat: true
|
964 | });
|
965 | }
|
966 |
|
967 | let history = historyRef.current;
|
968 | let [state, setState] = React.useState({
|
969 | action: history.action,
|
970 | location: history.location
|
971 | });
|
972 | React.useLayoutEffect(() => history.listen(setState), [history]);
|
973 | return /*#__PURE__*/React.createElement(Router, {
|
974 | basename: basename,
|
975 | children: children,
|
976 | location: state.location,
|
977 | navigationType: state.action,
|
978 | navigator: history
|
979 | });
|
980 | }
|
981 | /**
|
982 | * Changes the current location.
|
983 | *
|
984 | * Note: This API is mostly useful in React.Component subclasses that are not
|
985 | * able to use hooks. In functional components, we recommend you use the
|
986 | * `useNavigate` hook instead.
|
987 | *
|
988 | * @see https://reactrouter.com/components/navigate
|
989 | */
|
990 |
|
991 | function Navigate({
|
992 | to,
|
993 | replace,
|
994 | state,
|
995 | relative
|
996 | }) {
|
997 | !useInRouterContext() ? invariant(false, // TODO: This error is probably because they somehow have 2 versions of
|
998 | // the router loaded. We can help them understand how to avoid that.
|
999 | `<Navigate> may be used only in the context of a <Router> component.`) : void 0;
|
1000 | 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.`) ;
|
1001 | let dataRouterState = React.useContext(DataRouterStateContext);
|
1002 | let navigate = useNavigate();
|
1003 | React.useEffect(() => {
|
1004 | // Avoid kicking off multiple navigations if we're in the middle of a
|
1005 | // data-router navigation, since components get re-rendered when we enter
|
1006 | // a submitting/loading state
|
1007 | if (dataRouterState && dataRouterState.navigation.state !== "idle") {
|
1008 | return;
|
1009 | }
|
1010 |
|
1011 | navigate(to, {
|
1012 | replace,
|
1013 | state,
|
1014 | relative
|
1015 | });
|
1016 | });
|
1017 | return null;
|
1018 | }
|
1019 | /**
|
1020 | * Renders the child route's element, if there is one.
|
1021 | *
|
1022 | * @see https://reactrouter.com/components/outlet
|
1023 | */
|
1024 |
|
1025 | function Outlet(props) {
|
1026 | return useOutlet(props.context);
|
1027 | }
|
1028 | /**
|
1029 | * Declares an element that should be rendered at a certain URL path.
|
1030 | *
|
1031 | * @see https://reactrouter.com/components/route
|
1032 | */
|
1033 |
|
1034 | function Route(_props) {
|
1035 | 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>.`) ;
|
1036 | }
|
1037 | /**
|
1038 | * Provides location context for the rest of the app.
|
1039 | *
|
1040 | * Note: You usually won't render a <Router> directly. Instead, you'll render a
|
1041 | * router that is more specific to your environment such as a <BrowserRouter>
|
1042 | * in web browsers or a <StaticRouter> for server rendering.
|
1043 | *
|
1044 | * @see https://reactrouter.com/router-components/router
|
1045 | */
|
1046 |
|
1047 | function Router({
|
1048 | basename: basenameProp = "/",
|
1049 | children = null,
|
1050 | location: locationProp,
|
1051 | navigationType = Action.Pop,
|
1052 | navigator,
|
1053 | static: staticProp = false
|
1054 | }) {
|
1055 | !!useInRouterContext() ? 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
|
1056 | // the enforcement of trailing slashes throughout the app
|
1057 |
|
1058 | let basename = basenameProp.replace(/^\/*/, "/");
|
1059 | let navigationContext = React.useMemo(() => ({
|
1060 | basename,
|
1061 | navigator,
|
1062 | static: staticProp
|
1063 | }), [basename, navigator, staticProp]);
|
1064 |
|
1065 | if (typeof locationProp === "string") {
|
1066 | locationProp = parsePath(locationProp);
|
1067 | }
|
1068 |
|
1069 | let {
|
1070 | pathname = "/",
|
1071 | search = "",
|
1072 | hash = "",
|
1073 | state = null,
|
1074 | key = "default"
|
1075 | } = locationProp;
|
1076 | let location = React.useMemo(() => {
|
1077 | let trailingPathname = stripBasename(pathname, basename);
|
1078 |
|
1079 | if (trailingPathname == null) {
|
1080 | return null;
|
1081 | }
|
1082 |
|
1083 | return {
|
1084 | pathname: trailingPathname,
|
1085 | search,
|
1086 | hash,
|
1087 | state,
|
1088 | key
|
1089 | };
|
1090 | }, [basename, pathname, search, hash, state, key]);
|
1091 | 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.`) ;
|
1092 |
|
1093 | if (location == null) {
|
1094 | return null;
|
1095 | }
|
1096 |
|
1097 | return /*#__PURE__*/React.createElement(NavigationContext.Provider, {
|
1098 | value: navigationContext
|
1099 | }, /*#__PURE__*/React.createElement(LocationContext.Provider, {
|
1100 | children: children,
|
1101 | value: {
|
1102 | location,
|
1103 | navigationType
|
1104 | }
|
1105 | }));
|
1106 | }
|
1107 | /**
|
1108 | * A container for a nested tree of <Route> elements that renders the branch
|
1109 | * that best matches the current location.
|
1110 | *
|
1111 | * @see https://reactrouter.com/components/routes
|
1112 | */
|
1113 |
|
1114 | function Routes({
|
1115 | children,
|
1116 | location
|
1117 | }) {
|
1118 | let dataRouterContext = React.useContext(DataRouterContext); // When in a DataRouterContext _without_ children, we use the router routes
|
1119 | // directly. If we have children, then we're in a descendant tree and we
|
1120 | // need to use child routes.
|
1121 |
|
1122 | let routes = dataRouterContext && !children ? dataRouterContext.router.routes : createRoutesFromChildren(children);
|
1123 | return useRoutes(routes, location);
|
1124 | }
|
1125 | /**
|
1126 | * Component to use for rendering lazily loaded data from returning defer()
|
1127 | * in a loader function
|
1128 | */
|
1129 |
|
1130 | function Await({
|
1131 | children,
|
1132 | errorElement,
|
1133 | resolve
|
1134 | }) {
|
1135 | return /*#__PURE__*/React.createElement(AwaitErrorBoundary, {
|
1136 | resolve: resolve,
|
1137 | errorElement: errorElement
|
1138 | }, /*#__PURE__*/React.createElement(ResolveAwait, null, children));
|
1139 | }
|
1140 | var AwaitRenderStatus;
|
1141 |
|
1142 | (function (AwaitRenderStatus) {
|
1143 | AwaitRenderStatus[AwaitRenderStatus["pending"] = 0] = "pending";
|
1144 | AwaitRenderStatus[AwaitRenderStatus["success"] = 1] = "success";
|
1145 | AwaitRenderStatus[AwaitRenderStatus["error"] = 2] = "error";
|
1146 | })(AwaitRenderStatus || (AwaitRenderStatus = {}));
|
1147 |
|
1148 | const neverSettledPromise = new Promise(() => {});
|
1149 |
|
1150 | class AwaitErrorBoundary extends React.Component {
|
1151 | constructor(props) {
|
1152 | super(props);
|
1153 | this.state = {
|
1154 | error: null
|
1155 | };
|
1156 | }
|
1157 |
|
1158 | static getDerivedStateFromError(error) {
|
1159 | return {
|
1160 | error
|
1161 | };
|
1162 | }
|
1163 |
|
1164 | componentDidCatch(error, errorInfo) {
|
1165 | console.error("<Await> caught the following error during render", error, errorInfo);
|
1166 | }
|
1167 |
|
1168 | render() {
|
1169 | let {
|
1170 | children,
|
1171 | errorElement,
|
1172 | resolve
|
1173 | } = this.props;
|
1174 | let promise = null;
|
1175 | let status = AwaitRenderStatus.pending;
|
1176 |
|
1177 | if (!(resolve instanceof Promise)) {
|
1178 | // Didn't get a promise - provide as a resolved promise
|
1179 | status = AwaitRenderStatus.success;
|
1180 | promise = Promise.resolve();
|
1181 | Object.defineProperty(promise, "_tracked", {
|
1182 | get: () => true
|
1183 | });
|
1184 | Object.defineProperty(promise, "_data", {
|
1185 | get: () => resolve
|
1186 | });
|
1187 | } else if (this.state.error) {
|
1188 | // Caught a render error, provide it as a rejected promise
|
1189 | status = AwaitRenderStatus.error;
|
1190 | let renderError = this.state.error;
|
1191 | promise = Promise.reject().catch(() => {}); // Avoid unhandled rejection warnings
|
1192 |
|
1193 | Object.defineProperty(promise, "_tracked", {
|
1194 | get: () => true
|
1195 | });
|
1196 | Object.defineProperty(promise, "_error", {
|
1197 | get: () => renderError
|
1198 | });
|
1199 | } else if (resolve._tracked) {
|
1200 | // Already tracked promise - check contents
|
1201 | promise = resolve;
|
1202 | status = promise._error !== undefined ? AwaitRenderStatus.error : promise._data !== undefined ? AwaitRenderStatus.success : AwaitRenderStatus.pending;
|
1203 | } else {
|
1204 | // Raw (untracked) promise - track it
|
1205 | status = AwaitRenderStatus.pending;
|
1206 | Object.defineProperty(resolve, "_tracked", {
|
1207 | get: () => true
|
1208 | });
|
1209 | promise = resolve.then(data => Object.defineProperty(resolve, "_data", {
|
1210 | get: () => data
|
1211 | }), error => Object.defineProperty(resolve, "_error", {
|
1212 | get: () => error
|
1213 | }));
|
1214 | }
|
1215 |
|
1216 | if (status === AwaitRenderStatus.error && promise._error instanceof AbortedDeferredError) {
|
1217 | // Freeze the UI by throwing a never resolved promise
|
1218 | throw neverSettledPromise;
|
1219 | }
|
1220 |
|
1221 | if (status === AwaitRenderStatus.error && !errorElement) {
|
1222 | // No errorElement, throw to the nearest route-level error boundary
|
1223 | throw promise._error;
|
1224 | }
|
1225 |
|
1226 | if (status === AwaitRenderStatus.error) {
|
1227 | // Render via our errorElement
|
1228 | return /*#__PURE__*/React.createElement(AwaitContext.Provider, {
|
1229 | value: promise,
|
1230 | children: errorElement
|
1231 | });
|
1232 | }
|
1233 |
|
1234 | if (status === AwaitRenderStatus.success) {
|
1235 | // Render children with resolved value
|
1236 | return /*#__PURE__*/React.createElement(AwaitContext.Provider, {
|
1237 | value: promise,
|
1238 | children: children
|
1239 | });
|
1240 | } // Throw to the suspense boundary
|
1241 |
|
1242 |
|
1243 | throw promise;
|
1244 | }
|
1245 |
|
1246 | }
|
1247 | /**
|
1248 | * @private
|
1249 | * Indirection to leverage useAsyncValue for a render-prop API on <Await>
|
1250 | */
|
1251 |
|
1252 |
|
1253 | function ResolveAwait({
|
1254 | children
|
1255 | }) {
|
1256 | let data = useAsyncValue();
|
1257 | let toRender = typeof children === "function" ? children(data) : children;
|
1258 | return /*#__PURE__*/React.createElement(React.Fragment, null, toRender);
|
1259 | } ///////////////////////////////////////////////////////////////////////////////
|
1260 | // UTILS
|
1261 | ///////////////////////////////////////////////////////////////////////////////
|
1262 |
|
1263 | /**
|
1264 | * Creates a route config from a React "children" object, which is usually
|
1265 | * either a `<Route>` element or an array of them. Used internally by
|
1266 | * `<Routes>` to create a route config from its children.
|
1267 | *
|
1268 | * @see https://reactrouter.com/utils/create-routes-from-children
|
1269 | */
|
1270 |
|
1271 |
|
1272 | function createRoutesFromChildren(children, parentPath = []) {
|
1273 | let routes = [];
|
1274 | React.Children.forEach(children, (element, index) => {
|
1275 | if (! /*#__PURE__*/React.isValidElement(element)) {
|
1276 | // Ignore non-elements. This allows people to more easily inline
|
1277 | // conditionals in their route config.
|
1278 | return;
|
1279 | }
|
1280 |
|
1281 | if (element.type === React.Fragment) {
|
1282 | // Transparently support React.Fragment and its children.
|
1283 | routes.push.apply(routes, createRoutesFromChildren(element.props.children, parentPath));
|
1284 | return;
|
1285 | }
|
1286 |
|
1287 | !(element.type === Route) ? 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;
|
1288 | !(!element.props.index || !element.props.children) ? invariant(false, "An index route cannot have child routes.") : void 0;
|
1289 | let treePath = [...parentPath, index];
|
1290 | let route = {
|
1291 | id: element.props.id || treePath.join("-"),
|
1292 | caseSensitive: element.props.caseSensitive,
|
1293 | element: element.props.element,
|
1294 | index: element.props.index,
|
1295 | path: element.props.path,
|
1296 | loader: element.props.loader,
|
1297 | action: element.props.action,
|
1298 | errorElement: element.props.errorElement,
|
1299 | hasErrorBoundary: element.props.errorElement != null,
|
1300 | shouldRevalidate: element.props.shouldRevalidate,
|
1301 | handle: element.props.handle
|
1302 | };
|
1303 |
|
1304 | if (element.props.children) {
|
1305 | route.children = createRoutesFromChildren(element.props.children, treePath);
|
1306 | }
|
1307 |
|
1308 | routes.push(route);
|
1309 | });
|
1310 | return routes;
|
1311 | }
|
1312 | /**
|
1313 | * Renders the result of `matchRoutes()` into a React element.
|
1314 | */
|
1315 |
|
1316 | function renderMatches(matches) {
|
1317 | return _renderMatches(matches);
|
1318 | }
|
1319 | /**
|
1320 | * @private
|
1321 | * Walk the route tree and add hasErrorBoundary if it's not provided, so that
|
1322 | * users providing manual route arrays can just specify errorElement
|
1323 | */
|
1324 |
|
1325 | function enhanceManualRouteObjects(routes) {
|
1326 | return routes.map(route => {
|
1327 | let routeClone = { ...route
|
1328 | };
|
1329 |
|
1330 | if (routeClone.hasErrorBoundary == null) {
|
1331 | routeClone.hasErrorBoundary = routeClone.errorElement != null;
|
1332 | }
|
1333 |
|
1334 | if (routeClone.children) {
|
1335 | routeClone.children = enhanceManualRouteObjects(routeClone.children);
|
1336 | }
|
1337 |
|
1338 | return routeClone;
|
1339 | });
|
1340 | }
|
1341 |
|
1342 | function createMemoryRouter(routes, opts) {
|
1343 | return createRouter({
|
1344 | basename: opts?.basename,
|
1345 | history: createMemoryHistory({
|
1346 | initialEntries: opts?.initialEntries,
|
1347 | initialIndex: opts?.initialIndex
|
1348 | }),
|
1349 | hydrationData: opts?.hydrationData,
|
1350 | routes: enhanceManualRouteObjects(routes)
|
1351 | }).initialize();
|
1352 | } ///////////////////////////////////////////////////////////////////////////////
|
1353 |
|
1354 | export { 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 };
|
1355 | //# sourceMappingURL=react-router.development.js.map
|