1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
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 |
|
17 |
|
18 |
|
19 |
|
20 |
|
21 |
|
22 |
|
23 |
|
24 |
|
25 |
|
26 | function isPolyfill(x, y) {
|
27 | return x === y && (x !== 0 || 1 / x === 1 / y) || x !== x && y !== y
|
28 | ;
|
29 | }
|
30 |
|
31 | const is = typeof Object.is === "function" ? Object.is : isPolyfill;
|
32 |
|
33 |
|
34 | const {
|
35 | useState,
|
36 | useEffect,
|
37 | useLayoutEffect,
|
38 | useDebugValue
|
39 | } = React;
|
40 | let didWarnOld18Alpha = false;
|
41 | let didWarnUncachedGetSnapshot = false;
|
42 |
|
43 |
|
44 |
|
45 |
|
46 |
|
47 |
|
48 |
|
49 |
|
50 |
|
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 |
|
55 |
|
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 | }
|
65 |
|
66 |
|
67 |
|
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 | }
|
82 |
|
83 |
|
84 |
|
85 |
|
86 |
|
87 |
|
88 |
|
89 |
|
90 |
|
91 |
|
92 |
|
93 |
|
94 |
|
95 |
|
96 |
|
97 | const [{
|
98 | inst
|
99 | }, forceUpdate] = useState({
|
100 | inst: {
|
101 | value,
|
102 | getSnapshot
|
103 | }
|
104 | });
|
105 |
|
106 |
|
107 |
|
108 | useLayoutEffect(() => {
|
109 | inst.value = value;
|
110 | inst.getSnapshot = getSnapshot;
|
111 |
|
112 |
|
113 |
|
114 |
|
115 | if (checkIfSnapshotChanged(inst)) {
|
116 |
|
117 | forceUpdate({
|
118 | inst
|
119 | });
|
120 | }
|
121 |
|
122 | }, [subscribe, value, getSnapshot]);
|
123 | useEffect(() => {
|
124 |
|
125 |
|
126 | if (checkIfSnapshotChanged(inst)) {
|
127 |
|
128 | forceUpdate({
|
129 | inst
|
130 | });
|
131 | }
|
132 |
|
133 | const handleStoreChange = () => {
|
134 |
|
135 |
|
136 |
|
137 |
|
138 |
|
139 |
|
140 | if (checkIfSnapshotChanged(inst)) {
|
141 |
|
142 | forceUpdate({
|
143 | inst
|
144 | });
|
145 | }
|
146 | };
|
147 |
|
148 |
|
149 | return subscribe(handleStoreChange);
|
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 |
|
169 |
|
170 |
|
171 |
|
172 |
|
173 |
|
174 |
|
175 | function useSyncExternalStore$1(subscribe, getSnapshot, getServerSnapshot) {
|
176 |
|
177 |
|
178 |
|
179 |
|
180 | return getSnapshot();
|
181 | }
|
182 |
|
183 |
|
184 |
|
185 |
|
186 |
|
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 = React.createContext(null);
|
194 |
|
195 | {
|
196 | DataRouterContext.displayName = "DataRouter";
|
197 | }
|
198 |
|
199 | const DataRouterStateContext = React.createContext(null);
|
200 |
|
201 | {
|
202 | DataRouterStateContext.displayName = "DataRouterState";
|
203 | }
|
204 |
|
205 | const AwaitContext = React.createContext(null);
|
206 |
|
207 | {
|
208 | AwaitContext.displayName = "Await";
|
209 | }
|
210 |
|
211 | const NavigationContext = React.createContext(null);
|
212 |
|
213 | {
|
214 | NavigationContext.displayName = "Navigation";
|
215 | }
|
216 |
|
217 | const LocationContext = React.createContext(null);
|
218 |
|
219 | {
|
220 | LocationContext.displayName = "Location";
|
221 | }
|
222 |
|
223 | const RouteContext = React.createContext({
|
224 | outlet: null,
|
225 | matches: []
|
226 | });
|
227 |
|
228 | {
|
229 | RouteContext.displayName = "Route";
|
230 | }
|
231 |
|
232 | const RouteErrorContext = React.createContext(null);
|
233 |
|
234 | {
|
235 | RouteErrorContext.displayName = "RouteError";
|
236 | }
|
237 |
|
238 |
|
239 |
|
240 |
|
241 |
|
242 |
|
243 |
|
244 |
|
245 | function useHref(to, {
|
246 | relative
|
247 | } = {}) {
|
248 | !useInRouterContext() ? invariant(false,
|
249 |
|
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;
|
263 |
|
264 |
|
265 |
|
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 |
|
279 |
|
280 |
|
281 |
|
282 |
|
283 | function useInRouterContext() {
|
284 | return React.useContext(LocationContext) != null;
|
285 | }
|
286 |
|
287 |
|
288 |
|
289 |
|
290 |
|
291 |
|
292 |
|
293 |
|
294 |
|
295 |
|
296 |
|
297 | function useLocation() {
|
298 | !useInRouterContext() ? invariant(false,
|
299 |
|
300 | `useLocation() may be used only in the context of a <Router> component.`) : void 0;
|
301 | return React.useContext(LocationContext).location;
|
302 | }
|
303 |
|
304 |
|
305 |
|
306 |
|
307 |
|
308 |
|
309 |
|
310 | function useNavigationType() {
|
311 | return React.useContext(LocationContext).navigationType;
|
312 | }
|
313 |
|
314 |
|
315 |
|
316 |
|
317 |
|
318 |
|
319 |
|
320 |
|
321 | function useMatch(pattern) {
|
322 | !useInRouterContext() ? invariant(false,
|
323 |
|
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 |
|
332 |
|
333 |
|
334 |
|
335 |
|
336 |
|
337 | function useNavigate() {
|
338 | !useInRouterContext() ? invariant(false,
|
339 |
|
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");
|
366 |
|
367 |
|
368 |
|
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 = React.createContext(null);
|
379 |
|
380 |
|
381 |
|
382 |
|
383 |
|
384 |
|
385 | function useOutletContext() {
|
386 | return React.useContext(OutletContext);
|
387 | }
|
388 |
|
389 |
|
390 |
|
391 |
|
392 |
|
393 |
|
394 |
|
395 | function useOutlet(context) {
|
396 | let outlet = React.useContext(RouteContext).outlet;
|
397 |
|
398 | if (outlet) {
|
399 | return React.createElement(OutletContext.Provider, {
|
400 | value: context
|
401 | }, outlet);
|
402 | }
|
403 |
|
404 | return outlet;
|
405 | }
|
406 |
|
407 |
|
408 |
|
409 |
|
410 |
|
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 |
|
422 |
|
423 |
|
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 |
|
440 |
|
441 |
|
442 |
|
443 |
|
444 |
|
445 |
|
446 |
|
447 | function useRoutes(routes, locationArg) {
|
448 | !useInRouterContext() ? invariant(false,
|
449 |
|
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 |
|
466 |
|
467 |
|
468 |
|
469 |
|
470 |
|
471 |
|
472 |
|
473 |
|
474 |
|
475 |
|
476 |
|
477 |
|
478 |
|
479 |
|
480 |
|
481 |
|
482 |
|
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,
|
514 | navigator.encodeLocation ? navigator.encodeLocation(match.pathname).pathname : match.pathname]),
|
515 | pathnameBase: match.pathnameBase === "/" ? parentPathnameBase : joinPaths([parentPathnameBase,
|
516 | navigator.encodeLocation ? navigator.encodeLocation(match.pathnameBase).pathname : match.pathnameBase])
|
517 | })), parentMatches, dataRouterStateContext || undefined);
|
518 |
|
519 |
|
520 |
|
521 |
|
522 | if (locationArg && renderedMatches) {
|
523 | return 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 | return React.createElement(React.Fragment, null, React.createElement("h2", null, "Unhandled Thrown Error!"), React.createElement("h3", {
|
555 | style: {
|
556 | fontStyle: "italic"
|
557 | }
|
558 | }, message), stack ? React.createElement("pre", {
|
559 | style: preStyles
|
560 | }, stack) : null, React.createElement("p", null, "\uD83D\uDCBF Hey developer \uD83D\uDC4B"), React.createElement("p", null, "You can provide a way better UX than this when your app throws errors by providing your own\u00A0", React.createElement("code", {
|
561 | style: codeStyles
|
562 | }, "errorElement"), " props on\u00A0", React.createElement("code", {
|
563 | style: codeStyles
|
564 | }, "<Route>")));
|
565 | }
|
566 |
|
567 | class RenderErrorBoundary extends React.Component {
|
568 | constructor(props) {
|
569 | super(props);
|
570 | this.state = {
|
571 | location: props.location,
|
572 | error: props.error
|
573 | };
|
574 | }
|
575 |
|
576 | static getDerivedStateFromError(error) {
|
577 | return {
|
578 | error: error
|
579 | };
|
580 | }
|
581 |
|
582 | static getDerivedStateFromProps(props, state) {
|
583 |
|
584 |
|
585 |
|
586 |
|
587 |
|
588 |
|
589 |
|
590 |
|
591 | if (state.location !== props.location) {
|
592 | return {
|
593 | error: props.error,
|
594 | location: props.location
|
595 | };
|
596 | }
|
597 |
|
598 |
|
599 |
|
600 |
|
601 |
|
602 | return {
|
603 | error: props.error || state.error,
|
604 | location: state.location
|
605 | };
|
606 | }
|
607 |
|
608 | componentDidCatch(error, errorInfo) {
|
609 | console.error("React Router caught the following error during render", error, errorInfo);
|
610 | }
|
611 |
|
612 | render() {
|
613 | return this.state.error ? React.createElement(RouteContext.Provider, {
|
614 | value: this.props.routeContext
|
615 | }, React.createElement(RouteErrorContext.Provider, {
|
616 | value: this.state.error,
|
617 | children: this.props.component
|
618 | })) : this.props.children;
|
619 | }
|
620 |
|
621 | }
|
622 |
|
623 | function RenderedRoute({
|
624 | routeContext,
|
625 | match,
|
626 | children
|
627 | }) {
|
628 | let dataRouterContext = React.useContext(DataRouterContext);
|
629 |
|
630 |
|
631 | if (dataRouterContext && dataRouterContext.static && dataRouterContext.staticContext && match.route.errorElement) {
|
632 | dataRouterContext.staticContext._deepestRenderedBoundaryId = match.route.id;
|
633 | }
|
634 |
|
635 | return React.createElement(RouteContext.Provider, {
|
636 | value: routeContext
|
637 | }, children);
|
638 | }
|
639 |
|
640 | function _renderMatches(matches, parentMatches = [], dataRouterState) {
|
641 | if (matches == null) {
|
642 | if (dataRouterState?.errors) {
|
643 |
|
644 |
|
645 | matches = dataRouterState.matches;
|
646 | } else {
|
647 | return null;
|
648 | }
|
649 | }
|
650 |
|
651 | let renderedMatches = matches;
|
652 |
|
653 | let errors = dataRouterState?.errors;
|
654 |
|
655 | if (errors != null) {
|
656 | let errorIndex = renderedMatches.findIndex(m => m.route.id && errors?.[m.route.id]);
|
657 | !(errorIndex >= 0) ? invariant(false, `Could not find a matching route for the current errors: ${errors}`) : void 0;
|
658 | renderedMatches = renderedMatches.slice(0, Math.min(renderedMatches.length, errorIndex + 1));
|
659 | }
|
660 |
|
661 | return renderedMatches.reduceRight((outlet, match, index) => {
|
662 | let error = match.route.id ? errors?.[match.route.id] : null;
|
663 |
|
664 | let errorElement = dataRouterState ? match.route.errorElement || React.createElement(DefaultErrorElement, null) : null;
|
665 | let matches = parentMatches.concat(renderedMatches.slice(0, index + 1));
|
666 |
|
667 | let getChildren = () => React.createElement(RenderedRoute, {
|
668 | match: match,
|
669 | routeContext: {
|
670 | outlet,
|
671 | matches
|
672 | }
|
673 | }, error ? errorElement : match.route.element !== undefined ? match.route.element : outlet);
|
674 |
|
675 |
|
676 |
|
677 |
|
678 | return dataRouterState && (match.route.errorElement || index === 0) ? React.createElement(RenderErrorBoundary, {
|
679 | location: dataRouterState.location,
|
680 | component: errorElement,
|
681 | error: error,
|
682 | children: getChildren(),
|
683 | routeContext: {
|
684 | outlet: null,
|
685 | matches
|
686 | }
|
687 | }) : getChildren();
|
688 | }, null);
|
689 | }
|
690 | var DataRouterHook;
|
691 |
|
692 | (function (DataRouterHook) {
|
693 | DataRouterHook["UseBlocker"] = "useBlocker";
|
694 | DataRouterHook["UseRevalidator"] = "useRevalidator";
|
695 | })(DataRouterHook || (DataRouterHook = {}));
|
696 |
|
697 | var DataRouterStateHook;
|
698 |
|
699 | (function (DataRouterStateHook) {
|
700 | DataRouterStateHook["UseLoaderData"] = "useLoaderData";
|
701 | DataRouterStateHook["UseActionData"] = "useActionData";
|
702 | DataRouterStateHook["UseRouteError"] = "useRouteError";
|
703 | DataRouterStateHook["UseNavigation"] = "useNavigation";
|
704 | DataRouterStateHook["UseRouteLoaderData"] = "useRouteLoaderData";
|
705 | DataRouterStateHook["UseMatches"] = "useMatches";
|
706 | DataRouterStateHook["UseRevalidator"] = "useRevalidator";
|
707 | })(DataRouterStateHook || (DataRouterStateHook = {}));
|
708 |
|
709 | function getDataRouterConsoleError(hookName) {
|
710 | return `${hookName} must be used within a data router. See https://reactrouter.com/routers/picking-a-router.`;
|
711 | }
|
712 |
|
713 | function useDataRouterContext(hookName) {
|
714 | let ctx = React.useContext(DataRouterContext);
|
715 | !ctx ? invariant(false, getDataRouterConsoleError(hookName)) : void 0;
|
716 | return ctx;
|
717 | }
|
718 |
|
719 | function useDataRouterState(hookName) {
|
720 | let state = React.useContext(DataRouterStateContext);
|
721 | !state ? invariant(false, getDataRouterConsoleError(hookName)) : void 0;
|
722 | return state;
|
723 | }
|
724 |
|
725 | function useRouteContext(hookName) {
|
726 | let route = React.useContext(RouteContext);
|
727 | !route ? invariant(false, getDataRouterConsoleError(hookName)) : void 0;
|
728 | return route;
|
729 | }
|
730 |
|
731 | function useCurrentRouteId(hookName) {
|
732 | let route = useRouteContext(hookName);
|
733 | let thisRoute = route.matches[route.matches.length - 1];
|
734 | !thisRoute.route.id ? invariant(false, `${hookName} can only be used on routes that contain a unique "id"`) : void 0;
|
735 | return thisRoute.route.id;
|
736 | }
|
737 |
|
738 |
|
739 |
|
740 |
|
741 |
|
742 |
|
743 | function useNavigation() {
|
744 | let state = useDataRouterState(DataRouterStateHook.UseNavigation);
|
745 | return state.navigation;
|
746 | }
|
747 |
|
748 |
|
749 |
|
750 |
|
751 |
|
752 | function useRevalidator() {
|
753 | let dataRouterContext = useDataRouterContext(DataRouterHook.UseRevalidator);
|
754 | let state = useDataRouterState(DataRouterStateHook.UseRevalidator);
|
755 | return {
|
756 | revalidate: dataRouterContext.router.revalidate,
|
757 | state: state.revalidation
|
758 | };
|
759 | }
|
760 |
|
761 |
|
762 |
|
763 |
|
764 |
|
765 | function useMatches() {
|
766 | let {
|
767 | matches,
|
768 | loaderData
|
769 | } = useDataRouterState(DataRouterStateHook.UseMatches);
|
770 | return React.useMemo(() => matches.map(match => {
|
771 | let {
|
772 | pathname,
|
773 | params
|
774 | } = match;
|
775 |
|
776 |
|
777 |
|
778 | return {
|
779 | id: match.route.id,
|
780 | pathname,
|
781 | params,
|
782 | data: loaderData[match.route.id],
|
783 | handle: match.route.handle
|
784 | };
|
785 | }), [matches, loaderData]);
|
786 | }
|
787 |
|
788 |
|
789 |
|
790 |
|
791 | function useLoaderData() {
|
792 | let state = useDataRouterState(DataRouterStateHook.UseLoaderData);
|
793 | let routeId = useCurrentRouteId(DataRouterStateHook.UseLoaderData);
|
794 |
|
795 | if (state.errors && state.errors[routeId] != null) {
|
796 | console.error(`You cannot \`useLoaderData\` in an errorElement (routeId: ${routeId})`);
|
797 | return undefined;
|
798 | }
|
799 |
|
800 | return state.loaderData[routeId];
|
801 | }
|
802 |
|
803 |
|
804 |
|
805 |
|
806 | function useRouteLoaderData(routeId) {
|
807 | let state = useDataRouterState(DataRouterStateHook.UseRouteLoaderData);
|
808 | return state.loaderData[routeId];
|
809 | }
|
810 |
|
811 |
|
812 |
|
813 |
|
814 | function useActionData() {
|
815 | let state = useDataRouterState(DataRouterStateHook.UseActionData);
|
816 | let route = React.useContext(RouteContext);
|
817 | !route ? invariant(false, `useActionData must be used inside a RouteContext`) : void 0;
|
818 | return Object.values(state?.actionData || {})[0];
|
819 | }
|
820 |
|
821 |
|
822 |
|
823 |
|
824 |
|
825 |
|
826 | function useRouteError() {
|
827 | let error = React.useContext(RouteErrorContext);
|
828 | let state = useDataRouterState(DataRouterStateHook.UseRouteError);
|
829 | let routeId = useCurrentRouteId(DataRouterStateHook.UseRouteError);
|
830 |
|
831 |
|
832 | if (error) {
|
833 | return error;
|
834 | }
|
835 |
|
836 |
|
837 | return state.errors?.[routeId];
|
838 | }
|
839 |
|
840 |
|
841 |
|
842 |
|
843 | function useAsyncValue() {
|
844 | let value = React.useContext(AwaitContext);
|
845 | return value?._data;
|
846 | }
|
847 |
|
848 |
|
849 |
|
850 |
|
851 | function useAsyncError() {
|
852 | let value = React.useContext(AwaitContext);
|
853 | return value?._error;
|
854 | }
|
855 |
|
856 |
|
857 | let blockerKey = "blocker-singleton";
|
858 |
|
859 |
|
860 |
|
861 |
|
862 |
|
863 |
|
864 |
|
865 | function useBlocker(shouldBlock) {
|
866 | let {
|
867 | router
|
868 | } = useDataRouterContext(DataRouterHook.UseBlocker);
|
869 | let blockerFunction = React.useCallback(args => {
|
870 | return typeof shouldBlock === "function" ? !!shouldBlock(args) : !!shouldBlock;
|
871 | }, [shouldBlock]);
|
872 | let blocker = router.getBlocker(blockerKey, blockerFunction);
|
873 |
|
874 | React.useEffect(() => () => router.deleteBlocker(blockerKey), [router]);
|
875 | return blocker;
|
876 | }
|
877 | const alreadyWarned = {};
|
878 |
|
879 | function warningOnce(key, cond, message) {
|
880 | if (!cond && !alreadyWarned[key]) {
|
881 | alreadyWarned[key] = true;
|
882 | warning(false, message) ;
|
883 | }
|
884 | }
|
885 |
|
886 |
|
887 |
|
888 |
|
889 |
|
890 | function RouterProvider({
|
891 | fallbackElement,
|
892 | router
|
893 | }) {
|
894 |
|
895 | let state = useSyncExternalStore(router.subscribe, () => router.state,
|
896 |
|
897 |
|
898 | () => router.state);
|
899 | let navigator = React.useMemo(() => {
|
900 | return {
|
901 | createHref: router.createHref,
|
902 | encodeLocation: router.encodeLocation,
|
903 | go: n => router.navigate(n),
|
904 | push: (to, state, opts) => router.navigate(to, {
|
905 | state,
|
906 | preventScrollReset: opts?.preventScrollReset
|
907 | }),
|
908 | replace: (to, state, opts) => router.navigate(to, {
|
909 | replace: true,
|
910 | state,
|
911 | preventScrollReset: opts?.preventScrollReset
|
912 | })
|
913 | };
|
914 | }, [router]);
|
915 | let basename = router.basename || "/";
|
916 |
|
917 |
|
918 |
|
919 |
|
920 |
|
921 |
|
922 | return React.createElement(React.Fragment, null, React.createElement(DataRouterContext.Provider, {
|
923 | value: {
|
924 | router,
|
925 | navigator,
|
926 | static: false,
|
927 |
|
928 | basename
|
929 | }
|
930 | }, React.createElement(DataRouterStateContext.Provider, {
|
931 | value: state
|
932 | }, React.createElement(Router, {
|
933 | basename: router.basename,
|
934 | location: router.state.location,
|
935 | navigationType: router.state.historyAction,
|
936 | navigator: navigator
|
937 | }, router.state.initialized ? React.createElement(Routes, null) : fallbackElement))), null);
|
938 | }
|
939 |
|
940 |
|
941 |
|
942 |
|
943 |
|
944 |
|
945 | function MemoryRouter({
|
946 | basename,
|
947 | children,
|
948 | initialEntries,
|
949 | initialIndex
|
950 | }) {
|
951 | let historyRef = React.useRef();
|
952 |
|
953 | if (historyRef.current == null) {
|
954 | historyRef.current = createMemoryHistory({
|
955 | initialEntries,
|
956 | initialIndex,
|
957 | v5Compat: true
|
958 | });
|
959 | }
|
960 |
|
961 | let history = historyRef.current;
|
962 | let [state, setState] = React.useState({
|
963 | action: history.action,
|
964 | location: history.location
|
965 | });
|
966 | React.useLayoutEffect(() => history.listen(setState), [history]);
|
967 | return React.createElement(Router, {
|
968 | basename: basename,
|
969 | children: children,
|
970 | location: state.location,
|
971 | navigationType: state.action,
|
972 | navigator: history
|
973 | });
|
974 | }
|
975 |
|
976 |
|
977 |
|
978 |
|
979 |
|
980 |
|
981 |
|
982 |
|
983 |
|
984 |
|
985 | function Navigate({
|
986 | to,
|
987 | replace,
|
988 | state,
|
989 | relative
|
990 | }) {
|
991 | !useInRouterContext() ? invariant(false,
|
992 |
|
993 | `<Navigate> may be used only in the context of a <Router> component.`) : void 0;
|
994 | 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.`) ;
|
995 | let dataRouterState = React.useContext(DataRouterStateContext);
|
996 | let navigate = useNavigate();
|
997 | React.useEffect(() => {
|
998 |
|
999 |
|
1000 |
|
1001 | if (dataRouterState && dataRouterState.navigation.state !== "idle") {
|
1002 | return;
|
1003 | }
|
1004 |
|
1005 | navigate(to, {
|
1006 | replace,
|
1007 | state,
|
1008 | relative
|
1009 | });
|
1010 | });
|
1011 | return null;
|
1012 | }
|
1013 |
|
1014 |
|
1015 |
|
1016 |
|
1017 |
|
1018 |
|
1019 | function Outlet(props) {
|
1020 | return useOutlet(props.context);
|
1021 | }
|
1022 |
|
1023 |
|
1024 |
|
1025 |
|
1026 |
|
1027 |
|
1028 | function Route(_props) {
|
1029 | 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>.`) ;
|
1030 | }
|
1031 |
|
1032 |
|
1033 |
|
1034 |
|
1035 |
|
1036 |
|
1037 |
|
1038 |
|
1039 |
|
1040 |
|
1041 | function Router({
|
1042 | basename: basenameProp = "/",
|
1043 | children = null,
|
1044 | location: locationProp,
|
1045 | navigationType = Action.Pop,
|
1046 | navigator,
|
1047 | static: staticProp = false
|
1048 | }) {
|
1049 | !!useInRouterContext() ? invariant(false, `You cannot render a <Router> inside another <Router>.` + ` You should never have more than one in your app.`) : void 0;
|
1050 |
|
1051 |
|
1052 | let basename = basenameProp.replace(/^\/*/, "/");
|
1053 | let navigationContext = React.useMemo(() => ({
|
1054 | basename,
|
1055 | navigator,
|
1056 | static: staticProp
|
1057 | }), [basename, navigator, staticProp]);
|
1058 |
|
1059 | if (typeof locationProp === "string") {
|
1060 | locationProp = parsePath(locationProp);
|
1061 | }
|
1062 |
|
1063 | let {
|
1064 | pathname = "/",
|
1065 | search = "",
|
1066 | hash = "",
|
1067 | state = null,
|
1068 | key = "default"
|
1069 | } = locationProp;
|
1070 | let location = React.useMemo(() => {
|
1071 | let trailingPathname = stripBasename(pathname, basename);
|
1072 |
|
1073 | if (trailingPathname == null) {
|
1074 | return null;
|
1075 | }
|
1076 |
|
1077 | return {
|
1078 | pathname: trailingPathname,
|
1079 | search,
|
1080 | hash,
|
1081 | state,
|
1082 | key
|
1083 | };
|
1084 | }, [basename, pathname, search, hash, state, key]);
|
1085 | 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.`) ;
|
1086 |
|
1087 | if (location == null) {
|
1088 | return null;
|
1089 | }
|
1090 |
|
1091 | return React.createElement(NavigationContext.Provider, {
|
1092 | value: navigationContext
|
1093 | }, React.createElement(LocationContext.Provider, {
|
1094 | children: children,
|
1095 | value: {
|
1096 | location,
|
1097 | navigationType
|
1098 | }
|
1099 | }));
|
1100 | }
|
1101 |
|
1102 |
|
1103 |
|
1104 |
|
1105 |
|
1106 |
|
1107 |
|
1108 | function Routes({
|
1109 | children,
|
1110 | location
|
1111 | }) {
|
1112 | let dataRouterContext = React.useContext(DataRouterContext);
|
1113 |
|
1114 |
|
1115 |
|
1116 | let routes = dataRouterContext && !children ? dataRouterContext.router.routes : createRoutesFromChildren(children);
|
1117 | return useRoutes(routes, location);
|
1118 | }
|
1119 |
|
1120 |
|
1121 |
|
1122 |
|
1123 |
|
1124 | function Await({
|
1125 | children,
|
1126 | errorElement,
|
1127 | resolve
|
1128 | }) {
|
1129 | return React.createElement(AwaitErrorBoundary, {
|
1130 | resolve: resolve,
|
1131 | errorElement: errorElement
|
1132 | }, React.createElement(ResolveAwait, null, children));
|
1133 | }
|
1134 | var AwaitRenderStatus;
|
1135 |
|
1136 | (function (AwaitRenderStatus) {
|
1137 | AwaitRenderStatus[AwaitRenderStatus["pending"] = 0] = "pending";
|
1138 | AwaitRenderStatus[AwaitRenderStatus["success"] = 1] = "success";
|
1139 | AwaitRenderStatus[AwaitRenderStatus["error"] = 2] = "error";
|
1140 | })(AwaitRenderStatus || (AwaitRenderStatus = {}));
|
1141 |
|
1142 | const neverSettledPromise = new Promise(() => {});
|
1143 |
|
1144 | class AwaitErrorBoundary extends React.Component {
|
1145 | constructor(props) {
|
1146 | super(props);
|
1147 | this.state = {
|
1148 | error: null
|
1149 | };
|
1150 | }
|
1151 |
|
1152 | static getDerivedStateFromError(error) {
|
1153 | return {
|
1154 | error
|
1155 | };
|
1156 | }
|
1157 |
|
1158 | componentDidCatch(error, errorInfo) {
|
1159 | console.error("<Await> caught the following error during render", error, errorInfo);
|
1160 | }
|
1161 |
|
1162 | render() {
|
1163 | let {
|
1164 | children,
|
1165 | errorElement,
|
1166 | resolve
|
1167 | } = this.props;
|
1168 | let promise = null;
|
1169 | let status = AwaitRenderStatus.pending;
|
1170 |
|
1171 | if (!(resolve instanceof Promise)) {
|
1172 |
|
1173 | status = AwaitRenderStatus.success;
|
1174 | promise = Promise.resolve();
|
1175 | Object.defineProperty(promise, "_tracked", {
|
1176 | get: () => true
|
1177 | });
|
1178 | Object.defineProperty(promise, "_data", {
|
1179 | get: () => resolve
|
1180 | });
|
1181 | } else if (this.state.error) {
|
1182 |
|
1183 | status = AwaitRenderStatus.error;
|
1184 | let renderError = this.state.error;
|
1185 | promise = Promise.reject().catch(() => {});
|
1186 |
|
1187 | Object.defineProperty(promise, "_tracked", {
|
1188 | get: () => true
|
1189 | });
|
1190 | Object.defineProperty(promise, "_error", {
|
1191 | get: () => renderError
|
1192 | });
|
1193 | } else if (resolve._tracked) {
|
1194 |
|
1195 | promise = resolve;
|
1196 | status = promise._error !== undefined ? AwaitRenderStatus.error : promise._data !== undefined ? AwaitRenderStatus.success : AwaitRenderStatus.pending;
|
1197 | } else {
|
1198 |
|
1199 | status = AwaitRenderStatus.pending;
|
1200 | Object.defineProperty(resolve, "_tracked", {
|
1201 | get: () => true
|
1202 | });
|
1203 | promise = resolve.then(data => Object.defineProperty(resolve, "_data", {
|
1204 | get: () => data
|
1205 | }), error => Object.defineProperty(resolve, "_error", {
|
1206 | get: () => error
|
1207 | }));
|
1208 | }
|
1209 |
|
1210 | if (status === AwaitRenderStatus.error && promise._error instanceof AbortedDeferredError) {
|
1211 |
|
1212 | throw neverSettledPromise;
|
1213 | }
|
1214 |
|
1215 | if (status === AwaitRenderStatus.error && !errorElement) {
|
1216 |
|
1217 | throw promise._error;
|
1218 | }
|
1219 |
|
1220 | if (status === AwaitRenderStatus.error) {
|
1221 |
|
1222 | return React.createElement(AwaitContext.Provider, {
|
1223 | value: promise,
|
1224 | children: errorElement
|
1225 | });
|
1226 | }
|
1227 |
|
1228 | if (status === AwaitRenderStatus.success) {
|
1229 |
|
1230 | return React.createElement(AwaitContext.Provider, {
|
1231 | value: promise,
|
1232 | children: children
|
1233 | });
|
1234 | }
|
1235 |
|
1236 |
|
1237 | throw promise;
|
1238 | }
|
1239 |
|
1240 | }
|
1241 |
|
1242 |
|
1243 |
|
1244 |
|
1245 |
|
1246 |
|
1247 | function ResolveAwait({
|
1248 | children
|
1249 | }) {
|
1250 | let data = useAsyncValue();
|
1251 | let toRender = typeof children === "function" ? children(data) : children;
|
1252 | return React.createElement(React.Fragment, null, toRender);
|
1253 | }
|
1254 |
|
1255 |
|
1256 |
|
1257 |
|
1258 |
|
1259 |
|
1260 |
|
1261 |
|
1262 |
|
1263 |
|
1264 |
|
1265 |
|
1266 | function createRoutesFromChildren(children, parentPath = []) {
|
1267 | let routes = [];
|
1268 | React.Children.forEach(children, (element, index) => {
|
1269 | if (! React.isValidElement(element)) {
|
1270 |
|
1271 |
|
1272 | return;
|
1273 | }
|
1274 |
|
1275 | if (element.type === React.Fragment) {
|
1276 |
|
1277 | routes.push.apply(routes, createRoutesFromChildren(element.props.children, parentPath));
|
1278 | return;
|
1279 | }
|
1280 |
|
1281 | !(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;
|
1282 | !(!element.props.index || !element.props.children) ? invariant(false, "An index route cannot have child routes.") : void 0;
|
1283 | let treePath = [...parentPath, index];
|
1284 | let route = {
|
1285 | id: element.props.id || treePath.join("-"),
|
1286 | caseSensitive: element.props.caseSensitive,
|
1287 | element: element.props.element,
|
1288 | index: element.props.index,
|
1289 | path: element.props.path,
|
1290 | loader: element.props.loader,
|
1291 | action: element.props.action,
|
1292 | errorElement: element.props.errorElement,
|
1293 | hasErrorBoundary: element.props.errorElement != null,
|
1294 | shouldRevalidate: element.props.shouldRevalidate,
|
1295 | handle: element.props.handle
|
1296 | };
|
1297 |
|
1298 | if (element.props.children) {
|
1299 | route.children = createRoutesFromChildren(element.props.children, treePath);
|
1300 | }
|
1301 |
|
1302 | routes.push(route);
|
1303 | });
|
1304 | return routes;
|
1305 | }
|
1306 |
|
1307 |
|
1308 |
|
1309 |
|
1310 | function renderMatches(matches) {
|
1311 | return _renderMatches(matches);
|
1312 | }
|
1313 |
|
1314 |
|
1315 |
|
1316 |
|
1317 |
|
1318 |
|
1319 | function enhanceManualRouteObjects(routes) {
|
1320 | return routes.map(route => {
|
1321 | let routeClone = { ...route
|
1322 | };
|
1323 |
|
1324 | if (routeClone.hasErrorBoundary == null) {
|
1325 | routeClone.hasErrorBoundary = routeClone.errorElement != null;
|
1326 | }
|
1327 |
|
1328 | if (routeClone.children) {
|
1329 | routeClone.children = enhanceManualRouteObjects(routeClone.children);
|
1330 | }
|
1331 |
|
1332 | return routeClone;
|
1333 | });
|
1334 | }
|
1335 |
|
1336 | function createMemoryRouter(routes, opts) {
|
1337 | return createRouter({
|
1338 | basename: opts?.basename,
|
1339 | history: createMemoryHistory({
|
1340 | initialEntries: opts?.initialEntries,
|
1341 | initialIndex: opts?.initialIndex
|
1342 | }),
|
1343 | hydrationData: opts?.hydrationData,
|
1344 | routes: enhanceManualRouteObjects(routes)
|
1345 | }).initialize();
|
1346 | }
|
1347 |
|
1348 | 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 };
|
1349 |
|