1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 | import * as React from 'react';
|
12 | import { UNSAFE_invariant, joinPaths, matchPath, UNSAFE_getPathContributingMatches, UNSAFE_warning, resolveTo, parsePath, matchRoutes, Action, isRouteErrorResponse, createMemoryHistory, stripBasename, AbortedDeferredError, createRouter } from '@remix-run/router';
|
13 | export { AbortedDeferredError, Action as NavigationType, createPath, defer, generatePath, isRouteErrorResponse, json, matchPath, matchRoutes, parsePath, redirect, resolvePath } from '@remix-run/router';
|
14 |
|
15 | const DataRouterContext = React.createContext(null);
|
16 |
|
17 | {
|
18 | DataRouterContext.displayName = "DataRouter";
|
19 | }
|
20 |
|
21 | const DataRouterStateContext = React.createContext(null);
|
22 |
|
23 | {
|
24 | DataRouterStateContext.displayName = "DataRouterState";
|
25 | }
|
26 |
|
27 | const AwaitContext = React.createContext(null);
|
28 |
|
29 | {
|
30 | AwaitContext.displayName = "Await";
|
31 | }
|
32 |
|
33 | const NavigationContext = React.createContext(null);
|
34 |
|
35 | {
|
36 | NavigationContext.displayName = "Navigation";
|
37 | }
|
38 |
|
39 | const LocationContext = React.createContext(null);
|
40 |
|
41 | {
|
42 | LocationContext.displayName = "Location";
|
43 | }
|
44 |
|
45 | const RouteContext = React.createContext({
|
46 | outlet: null,
|
47 | matches: [],
|
48 | isDataRoute: false
|
49 | });
|
50 |
|
51 | {
|
52 | RouteContext.displayName = "Route";
|
53 | }
|
54 |
|
55 | const RouteErrorContext = React.createContext(null);
|
56 |
|
57 | {
|
58 | RouteErrorContext.displayName = "RouteError";
|
59 | }
|
60 |
|
61 |
|
62 |
|
63 |
|
64 |
|
65 |
|
66 |
|
67 |
|
68 | function useHref(to, {
|
69 | relative
|
70 | } = {}) {
|
71 | !useInRouterContext() ? UNSAFE_invariant(false,
|
72 |
|
73 | `useHref() may be used only in the context of a <Router> component.`) : void 0;
|
74 | let {
|
75 | basename,
|
76 | navigator
|
77 | } = React.useContext(NavigationContext);
|
78 | let {
|
79 | hash,
|
80 | pathname,
|
81 | search
|
82 | } = useResolvedPath(to, {
|
83 | relative
|
84 | });
|
85 | let joinedPathname = pathname;
|
86 |
|
87 |
|
88 |
|
89 |
|
90 | if (basename !== "/") {
|
91 | joinedPathname = pathname === "/" ? basename : joinPaths([basename, pathname]);
|
92 | }
|
93 |
|
94 | return navigator.createHref({
|
95 | pathname: joinedPathname,
|
96 | search,
|
97 | hash
|
98 | });
|
99 | }
|
100 |
|
101 |
|
102 |
|
103 |
|
104 |
|
105 |
|
106 | function useInRouterContext() {
|
107 | return React.useContext(LocationContext) != null;
|
108 | }
|
109 |
|
110 |
|
111 |
|
112 |
|
113 |
|
114 |
|
115 |
|
116 |
|
117 |
|
118 |
|
119 |
|
120 | function useLocation() {
|
121 | !useInRouterContext() ? UNSAFE_invariant(false,
|
122 |
|
123 | `useLocation() may be used only in the context of a <Router> component.`) : void 0;
|
124 | return React.useContext(LocationContext).location;
|
125 | }
|
126 |
|
127 |
|
128 |
|
129 |
|
130 |
|
131 |
|
132 |
|
133 | function useNavigationType() {
|
134 | return React.useContext(LocationContext).navigationType;
|
135 | }
|
136 |
|
137 |
|
138 |
|
139 |
|
140 |
|
141 |
|
142 |
|
143 |
|
144 | function useMatch(pattern) {
|
145 | !useInRouterContext() ? UNSAFE_invariant(false,
|
146 |
|
147 | `useMatch() may be used only in the context of a <Router> component.`) : void 0;
|
148 | let {
|
149 | pathname
|
150 | } = useLocation();
|
151 | return React.useMemo(() => matchPath(pattern, pathname), [pathname, pattern]);
|
152 | }
|
153 | const navigateEffectWarning = `You should call navigate() in a React.useEffect(), not when ` + `your component is first rendered.`;
|
154 |
|
155 | function useIsomorphicLayoutEffect(cb) {
|
156 | let isStatic = React.useContext(NavigationContext).static;
|
157 |
|
158 | if (!isStatic) {
|
159 |
|
160 |
|
161 |
|
162 | React.useLayoutEffect(cb);
|
163 | }
|
164 | }
|
165 |
|
166 |
|
167 |
|
168 |
|
169 |
|
170 |
|
171 |
|
172 |
|
173 | function useNavigate() {
|
174 | let {
|
175 | isDataRoute
|
176 | } = React.useContext(RouteContext);
|
177 |
|
178 |
|
179 | return isDataRoute ? useNavigateStable() : useNavigateUnstable();
|
180 | }
|
181 |
|
182 | function useNavigateUnstable() {
|
183 | !useInRouterContext() ? UNSAFE_invariant(false,
|
184 |
|
185 | `useNavigate() may be used only in the context of a <Router> component.`) : void 0;
|
186 | let dataRouterContext = React.useContext(DataRouterContext);
|
187 | let {
|
188 | basename,
|
189 | navigator
|
190 | } = React.useContext(NavigationContext);
|
191 | let {
|
192 | matches
|
193 | } = React.useContext(RouteContext);
|
194 | let {
|
195 | pathname: locationPathname
|
196 | } = useLocation();
|
197 | let routePathnamesJson = JSON.stringify(UNSAFE_getPathContributingMatches(matches).map(match => match.pathnameBase));
|
198 | let activeRef = React.useRef(false);
|
199 | useIsomorphicLayoutEffect(() => {
|
200 | activeRef.current = true;
|
201 | });
|
202 | let navigate = React.useCallback((to, options = {}) => {
|
203 | UNSAFE_warning(activeRef.current, navigateEffectWarning) ;
|
204 |
|
205 |
|
206 | if (!activeRef.current) return;
|
207 |
|
208 | if (typeof to === "number") {
|
209 | navigator.go(to);
|
210 | return;
|
211 | }
|
212 |
|
213 | let path = resolveTo(to, JSON.parse(routePathnamesJson), locationPathname, options.relative === "path");
|
214 |
|
215 |
|
216 |
|
217 |
|
218 |
|
219 |
|
220 | if (dataRouterContext == null && basename !== "/") {
|
221 | path.pathname = path.pathname === "/" ? basename : joinPaths([basename, path.pathname]);
|
222 | }
|
223 |
|
224 | (!!options.replace ? navigator.replace : navigator.push)(path, options.state, options);
|
225 | }, [basename, navigator, routePathnamesJson, locationPathname, dataRouterContext]);
|
226 | return navigate;
|
227 | }
|
228 |
|
229 | const OutletContext = React.createContext(null);
|
230 |
|
231 |
|
232 |
|
233 |
|
234 |
|
235 |
|
236 | function useOutletContext() {
|
237 | return React.useContext(OutletContext);
|
238 | }
|
239 |
|
240 |
|
241 |
|
242 |
|
243 |
|
244 |
|
245 |
|
246 | function useOutlet(context) {
|
247 | let outlet = React.useContext(RouteContext).outlet;
|
248 |
|
249 | if (outlet) {
|
250 | return React.createElement(OutletContext.Provider, {
|
251 | value: context
|
252 | }, outlet);
|
253 | }
|
254 |
|
255 | return outlet;
|
256 | }
|
257 |
|
258 |
|
259 |
|
260 |
|
261 |
|
262 |
|
263 |
|
264 | function useParams() {
|
265 | let {
|
266 | matches
|
267 | } = React.useContext(RouteContext);
|
268 | let routeMatch = matches[matches.length - 1];
|
269 | return routeMatch ? routeMatch.params : {};
|
270 | }
|
271 |
|
272 |
|
273 |
|
274 |
|
275 |
|
276 |
|
277 | function useResolvedPath(to, {
|
278 | relative
|
279 | } = {}) {
|
280 | let {
|
281 | matches
|
282 | } = React.useContext(RouteContext);
|
283 | let {
|
284 | pathname: locationPathname
|
285 | } = useLocation();
|
286 | let routePathnamesJson = JSON.stringify(UNSAFE_getPathContributingMatches(matches).map(match => match.pathnameBase));
|
287 | return React.useMemo(() => resolveTo(to, JSON.parse(routePathnamesJson), locationPathname, relative === "path"), [to, routePathnamesJson, locationPathname, relative]);
|
288 | }
|
289 |
|
290 |
|
291 |
|
292 |
|
293 |
|
294 |
|
295 |
|
296 |
|
297 |
|
298 | function useRoutes(routes, locationArg) {
|
299 | return useRoutesImpl(routes, locationArg);
|
300 | }
|
301 |
|
302 | function useRoutesImpl(routes, locationArg, dataRouterState) {
|
303 | !useInRouterContext() ? UNSAFE_invariant(false,
|
304 |
|
305 | `useRoutes() may be used only in the context of a <Router> component.`) : void 0;
|
306 | let {
|
307 | navigator
|
308 | } = React.useContext(NavigationContext);
|
309 | let {
|
310 | matches: parentMatches
|
311 | } = React.useContext(RouteContext);
|
312 | let routeMatch = parentMatches[parentMatches.length - 1];
|
313 | let parentParams = routeMatch ? routeMatch.params : {};
|
314 | let parentPathname = routeMatch ? routeMatch.pathname : "/";
|
315 | let parentPathnameBase = routeMatch ? routeMatch.pathnameBase : "/";
|
316 | let parentRoute = routeMatch && routeMatch.route;
|
317 |
|
318 | {
|
319 |
|
320 |
|
321 |
|
322 |
|
323 |
|
324 |
|
325 |
|
326 |
|
327 |
|
328 |
|
329 |
|
330 |
|
331 |
|
332 |
|
333 |
|
334 |
|
335 |
|
336 |
|
337 |
|
338 |
|
339 | let parentPath = parentRoute && parentRoute.path || "";
|
340 | 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}/*`}">.`);
|
341 | }
|
342 |
|
343 | let locationFromContext = useLocation();
|
344 | let location;
|
345 |
|
346 | if (locationArg) {
|
347 | let parsedLocationArg = typeof locationArg === "string" ? parsePath(locationArg) : locationArg;
|
348 | !(parentPathnameBase === "/" || parsedLocationArg.pathname?.startsWith(parentPathnameBase)) ? UNSAFE_invariant(false, `When overriding the location using \`<Routes location>\` or \`useRoutes(routes, location)\`, ` + `the location pathname must begin with the portion of the URL pathname that was ` + `matched by all parent routes. The current pathname base is "${parentPathnameBase}" ` + `but pathname "${parsedLocationArg.pathname}" was given in the \`location\` prop.`) : void 0;
|
349 | location = parsedLocationArg;
|
350 | } else {
|
351 | location = locationFromContext;
|
352 | }
|
353 |
|
354 | let pathname = location.pathname || "/";
|
355 | let remainingPathname = parentPathnameBase === "/" ? pathname : pathname.slice(parentPathnameBase.length) || "/";
|
356 | let matches = matchRoutes(routes, {
|
357 | pathname: remainingPathname
|
358 | });
|
359 |
|
360 | {
|
361 | UNSAFE_warning(parentRoute || matches != null, `No routes matched location "${location.pathname}${location.search}${location.hash}" `) ;
|
362 | UNSAFE_warning(matches == null || matches[matches.length - 1].route.element !== undefined || matches[matches.length - 1].route.Component !== undefined, `Matched leaf route at location "${location.pathname}${location.search}${location.hash}" ` + `does not have an element or Component. This means it will render an <Outlet /> with a ` + `null value by default resulting in an "empty" page.`) ;
|
363 | }
|
364 |
|
365 | let renderedMatches = _renderMatches(matches && matches.map(match => Object.assign({}, match, {
|
366 | params: Object.assign({}, parentParams, match.params),
|
367 | pathname: joinPaths([parentPathnameBase,
|
368 | navigator.encodeLocation ? navigator.encodeLocation(match.pathname).pathname : match.pathname]),
|
369 | pathnameBase: match.pathnameBase === "/" ? parentPathnameBase : joinPaths([parentPathnameBase,
|
370 | navigator.encodeLocation ? navigator.encodeLocation(match.pathnameBase).pathname : match.pathnameBase])
|
371 | })), parentMatches, dataRouterState);
|
372 |
|
373 |
|
374 |
|
375 |
|
376 | if (locationArg && renderedMatches) {
|
377 | return React.createElement(LocationContext.Provider, {
|
378 | value: {
|
379 | location: {
|
380 | pathname: "/",
|
381 | search: "",
|
382 | hash: "",
|
383 | state: null,
|
384 | key: "default",
|
385 | ...location
|
386 | },
|
387 | navigationType: Action.Pop
|
388 | }
|
389 | }, renderedMatches);
|
390 | }
|
391 |
|
392 | return renderedMatches;
|
393 | }
|
394 |
|
395 | function DefaultErrorComponent() {
|
396 | let error = useRouteError();
|
397 | let message = isRouteErrorResponse(error) ? `${error.status} ${error.statusText}` : error instanceof Error ? error.message : JSON.stringify(error);
|
398 | let stack = error instanceof Error ? error.stack : null;
|
399 | let lightgrey = "rgba(200,200,200, 0.5)";
|
400 | let preStyles = {
|
401 | padding: "0.5rem",
|
402 | backgroundColor: lightgrey
|
403 | };
|
404 | let codeStyles = {
|
405 | padding: "2px 4px",
|
406 | backgroundColor: lightgrey
|
407 | };
|
408 | let devInfo = null;
|
409 |
|
410 | {
|
411 | console.error("Error handled by React Router default ErrorBoundary:", error);
|
412 | devInfo = React.createElement(React.Fragment, 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 ", React.createElement("code", {
|
413 | style: codeStyles
|
414 | }, "ErrorBoundary"), " or", " ", React.createElement("code", {
|
415 | style: codeStyles
|
416 | }, "errorElement"), " prop on your route."));
|
417 | }
|
418 |
|
419 | return React.createElement(React.Fragment, null, React.createElement("h2", null, "Unexpected Application Error!"), React.createElement("h3", {
|
420 | style: {
|
421 | fontStyle: "italic"
|
422 | }
|
423 | }, message), stack ? React.createElement("pre", {
|
424 | style: preStyles
|
425 | }, stack) : null, devInfo);
|
426 | }
|
427 |
|
428 | const defaultErrorElement = React.createElement(DefaultErrorComponent, null);
|
429 | class RenderErrorBoundary extends React.Component {
|
430 | constructor(props) {
|
431 | super(props);
|
432 | this.state = {
|
433 | location: props.location,
|
434 | revalidation: props.revalidation,
|
435 | error: props.error
|
436 | };
|
437 | }
|
438 |
|
439 | static getDerivedStateFromError(error) {
|
440 | return {
|
441 | error: error
|
442 | };
|
443 | }
|
444 |
|
445 | static getDerivedStateFromProps(props, state) {
|
446 |
|
447 |
|
448 |
|
449 |
|
450 |
|
451 |
|
452 |
|
453 |
|
454 | if (state.location !== props.location || state.revalidation !== "idle" && props.revalidation === "idle") {
|
455 | return {
|
456 | error: props.error,
|
457 | location: props.location,
|
458 | revalidation: props.revalidation
|
459 | };
|
460 | }
|
461 |
|
462 |
|
463 |
|
464 |
|
465 |
|
466 | return {
|
467 | error: props.error || state.error,
|
468 | location: state.location,
|
469 | revalidation: props.revalidation || state.revalidation
|
470 | };
|
471 | }
|
472 |
|
473 | componentDidCatch(error, errorInfo) {
|
474 | console.error("React Router caught the following error during render", error, errorInfo);
|
475 | }
|
476 |
|
477 | render() {
|
478 | return this.state.error ? React.createElement(RouteContext.Provider, {
|
479 | value: this.props.routeContext
|
480 | }, React.createElement(RouteErrorContext.Provider, {
|
481 | value: this.state.error,
|
482 | children: this.props.component
|
483 | })) : this.props.children;
|
484 | }
|
485 |
|
486 | }
|
487 |
|
488 | function RenderedRoute({
|
489 | routeContext,
|
490 | match,
|
491 | children
|
492 | }) {
|
493 | let dataRouterContext = React.useContext(DataRouterContext);
|
494 |
|
495 |
|
496 | if (dataRouterContext && dataRouterContext.static && dataRouterContext.staticContext && (match.route.errorElement || match.route.ErrorBoundary)) {
|
497 | dataRouterContext.staticContext._deepestRenderedBoundaryId = match.route.id;
|
498 | }
|
499 |
|
500 | return React.createElement(RouteContext.Provider, {
|
501 | value: routeContext
|
502 | }, children);
|
503 | }
|
504 |
|
505 | function _renderMatches(matches, parentMatches = [], dataRouterState = null) {
|
506 | if (matches == null) {
|
507 | if (dataRouterState?.errors) {
|
508 |
|
509 |
|
510 | matches = dataRouterState.matches;
|
511 | } else {
|
512 | return null;
|
513 | }
|
514 | }
|
515 |
|
516 | let renderedMatches = matches;
|
517 |
|
518 | let errors = dataRouterState?.errors;
|
519 |
|
520 | if (errors != null) {
|
521 | let errorIndex = renderedMatches.findIndex(m => m.route.id && errors?.[m.route.id]);
|
522 | !(errorIndex >= 0) ? UNSAFE_invariant(false, `Could not find a matching route for errors on route IDs: ${Object.keys(errors).join(",")}`) : void 0;
|
523 | renderedMatches = renderedMatches.slice(0, Math.min(renderedMatches.length, errorIndex + 1));
|
524 | }
|
525 |
|
526 | return renderedMatches.reduceRight((outlet, match, index) => {
|
527 | let error = match.route.id ? errors?.[match.route.id] : null;
|
528 |
|
529 | let errorElement = null;
|
530 |
|
531 | if (dataRouterState) {
|
532 | errorElement = match.route.errorElement || defaultErrorElement;
|
533 | }
|
534 |
|
535 | let matches = parentMatches.concat(renderedMatches.slice(0, index + 1));
|
536 |
|
537 | let getChildren = () => {
|
538 | let children;
|
539 |
|
540 | if (error) {
|
541 | children = errorElement;
|
542 | } else if (match.route.Component) {
|
543 |
|
544 |
|
545 |
|
546 |
|
547 |
|
548 |
|
549 | children = React.createElement(match.route.Component, null);
|
550 | } else if (match.route.element) {
|
551 | children = match.route.element;
|
552 | } else {
|
553 | children = outlet;
|
554 | }
|
555 |
|
556 | return React.createElement(RenderedRoute, {
|
557 | match: match,
|
558 | routeContext: {
|
559 | outlet,
|
560 | matches,
|
561 | isDataRoute: dataRouterState != null
|
562 | },
|
563 | children: children
|
564 | });
|
565 | };
|
566 |
|
567 |
|
568 |
|
569 |
|
570 | return dataRouterState && (match.route.ErrorBoundary || match.route.errorElement || index === 0) ? React.createElement(RenderErrorBoundary, {
|
571 | location: dataRouterState.location,
|
572 | revalidation: dataRouterState.revalidation,
|
573 | component: errorElement,
|
574 | error: error,
|
575 | children: getChildren(),
|
576 | routeContext: {
|
577 | outlet: null,
|
578 | matches,
|
579 | isDataRoute: true
|
580 | }
|
581 | }) : getChildren();
|
582 | }, null);
|
583 | }
|
584 | var DataRouterHook;
|
585 |
|
586 | (function (DataRouterHook) {
|
587 | DataRouterHook["UseBlocker"] = "useBlocker";
|
588 | DataRouterHook["UseRevalidator"] = "useRevalidator";
|
589 | DataRouterHook["UseNavigateStable"] = "useNavigate";
|
590 | })(DataRouterHook || (DataRouterHook = {}));
|
591 |
|
592 | var DataRouterStateHook;
|
593 |
|
594 | (function (DataRouterStateHook) {
|
595 | DataRouterStateHook["UseBlocker"] = "useBlocker";
|
596 | DataRouterStateHook["UseLoaderData"] = "useLoaderData";
|
597 | DataRouterStateHook["UseActionData"] = "useActionData";
|
598 | DataRouterStateHook["UseRouteError"] = "useRouteError";
|
599 | DataRouterStateHook["UseNavigation"] = "useNavigation";
|
600 | DataRouterStateHook["UseRouteLoaderData"] = "useRouteLoaderData";
|
601 | DataRouterStateHook["UseMatches"] = "useMatches";
|
602 | DataRouterStateHook["UseRevalidator"] = "useRevalidator";
|
603 | DataRouterStateHook["UseNavigateStable"] = "useNavigate";
|
604 | DataRouterStateHook["UseRouteId"] = "useRouteId";
|
605 | })(DataRouterStateHook || (DataRouterStateHook = {}));
|
606 |
|
607 | function getDataRouterConsoleError(hookName) {
|
608 | return `${hookName} must be used within a data router. See https://reactrouter.com/routers/picking-a-router.`;
|
609 | }
|
610 |
|
611 | function useDataRouterContext(hookName) {
|
612 | let ctx = React.useContext(DataRouterContext);
|
613 | !ctx ? UNSAFE_invariant(false, getDataRouterConsoleError(hookName)) : void 0;
|
614 | return ctx;
|
615 | }
|
616 |
|
617 | function useDataRouterState(hookName) {
|
618 | let state = React.useContext(DataRouterStateContext);
|
619 | !state ? UNSAFE_invariant(false, getDataRouterConsoleError(hookName)) : void 0;
|
620 | return state;
|
621 | }
|
622 |
|
623 | function useRouteContext(hookName) {
|
624 | let route = React.useContext(RouteContext);
|
625 | !route ? UNSAFE_invariant(false, getDataRouterConsoleError(hookName)) : void 0;
|
626 | return route;
|
627 | }
|
628 |
|
629 |
|
630 | function useCurrentRouteId(hookName) {
|
631 | let route = useRouteContext(hookName);
|
632 | let thisRoute = route.matches[route.matches.length - 1];
|
633 | !thisRoute.route.id ? UNSAFE_invariant(false, `${hookName} can only be used on routes that contain a unique "id"`) : void 0;
|
634 | return thisRoute.route.id;
|
635 | }
|
636 |
|
637 |
|
638 |
|
639 |
|
640 |
|
641 | function useRouteId() {
|
642 | return useCurrentRouteId(DataRouterStateHook.UseRouteId);
|
643 | }
|
644 |
|
645 |
|
646 |
|
647 |
|
648 |
|
649 | function useNavigation() {
|
650 | let state = useDataRouterState(DataRouterStateHook.UseNavigation);
|
651 | return state.navigation;
|
652 | }
|
653 |
|
654 |
|
655 |
|
656 |
|
657 |
|
658 | function useRevalidator() {
|
659 | let dataRouterContext = useDataRouterContext(DataRouterHook.UseRevalidator);
|
660 | let state = useDataRouterState(DataRouterStateHook.UseRevalidator);
|
661 | return {
|
662 | revalidate: dataRouterContext.router.revalidate,
|
663 | state: state.revalidation
|
664 | };
|
665 | }
|
666 |
|
667 |
|
668 |
|
669 |
|
670 |
|
671 | function useMatches() {
|
672 | let {
|
673 | matches,
|
674 | loaderData
|
675 | } = useDataRouterState(DataRouterStateHook.UseMatches);
|
676 | return React.useMemo(() => matches.map(match => {
|
677 | let {
|
678 | pathname,
|
679 | params
|
680 | } = match;
|
681 |
|
682 |
|
683 |
|
684 | return {
|
685 | id: match.route.id,
|
686 | pathname,
|
687 | params,
|
688 | data: loaderData[match.route.id],
|
689 | handle: match.route.handle
|
690 | };
|
691 | }), [matches, loaderData]);
|
692 | }
|
693 |
|
694 |
|
695 |
|
696 |
|
697 | function useLoaderData() {
|
698 | let state = useDataRouterState(DataRouterStateHook.UseLoaderData);
|
699 | let routeId = useCurrentRouteId(DataRouterStateHook.UseLoaderData);
|
700 |
|
701 | if (state.errors && state.errors[routeId] != null) {
|
702 | console.error(`You cannot \`useLoaderData\` in an errorElement (routeId: ${routeId})`);
|
703 | return undefined;
|
704 | }
|
705 |
|
706 | return state.loaderData[routeId];
|
707 | }
|
708 |
|
709 |
|
710 |
|
711 |
|
712 | function useRouteLoaderData(routeId) {
|
713 | let state = useDataRouterState(DataRouterStateHook.UseRouteLoaderData);
|
714 | return state.loaderData[routeId];
|
715 | }
|
716 |
|
717 |
|
718 |
|
719 |
|
720 | function useActionData() {
|
721 | let state = useDataRouterState(DataRouterStateHook.UseActionData);
|
722 | let route = React.useContext(RouteContext);
|
723 | !route ? UNSAFE_invariant(false, `useActionData must be used inside a RouteContext`) : void 0;
|
724 | return Object.values(state?.actionData || {})[0];
|
725 | }
|
726 |
|
727 |
|
728 |
|
729 |
|
730 |
|
731 |
|
732 | function useRouteError() {
|
733 | let error = React.useContext(RouteErrorContext);
|
734 | let state = useDataRouterState(DataRouterStateHook.UseRouteError);
|
735 | let routeId = useCurrentRouteId(DataRouterStateHook.UseRouteError);
|
736 |
|
737 |
|
738 | if (error) {
|
739 | return error;
|
740 | }
|
741 |
|
742 |
|
743 | return state.errors?.[routeId];
|
744 | }
|
745 |
|
746 |
|
747 |
|
748 |
|
749 | function useAsyncValue() {
|
750 | let value = React.useContext(AwaitContext);
|
751 | return value?._data;
|
752 | }
|
753 |
|
754 |
|
755 |
|
756 |
|
757 | function useAsyncError() {
|
758 | let value = React.useContext(AwaitContext);
|
759 | return value?._error;
|
760 | }
|
761 | let blockerId = 0;
|
762 |
|
763 |
|
764 |
|
765 |
|
766 |
|
767 |
|
768 |
|
769 | function useBlocker(shouldBlock) {
|
770 | let {
|
771 | router
|
772 | } = useDataRouterContext(DataRouterHook.UseBlocker);
|
773 | let state = useDataRouterState(DataRouterStateHook.UseBlocker);
|
774 | let [blockerKey] = React.useState(() => String(++blockerId));
|
775 | let blockerFunction = React.useCallback(args => {
|
776 | return typeof shouldBlock === "function" ? !!shouldBlock(args) : !!shouldBlock;
|
777 | }, [shouldBlock]);
|
778 | let blocker = router.getBlocker(blockerKey, blockerFunction);
|
779 |
|
780 | React.useEffect(() => () => router.deleteBlocker(blockerKey), [router, blockerKey]);
|
781 |
|
782 |
|
783 | return state.blockers.get(blockerKey) || blocker;
|
784 | }
|
785 |
|
786 |
|
787 |
|
788 |
|
789 |
|
790 | function useNavigateStable() {
|
791 | let {
|
792 | router
|
793 | } = useDataRouterContext(DataRouterHook.UseNavigateStable);
|
794 | let id = useCurrentRouteId(DataRouterStateHook.UseNavigateStable);
|
795 | let activeRef = React.useRef(false);
|
796 | useIsomorphicLayoutEffect(() => {
|
797 | activeRef.current = true;
|
798 | });
|
799 | let navigate = React.useCallback((to, options = {}) => {
|
800 | UNSAFE_warning(activeRef.current, navigateEffectWarning) ;
|
801 |
|
802 |
|
803 | if (!activeRef.current) return;
|
804 |
|
805 | if (typeof to === "number") {
|
806 | router.navigate(to);
|
807 | } else {
|
808 | router.navigate(to, {
|
809 | fromRouteId: id,
|
810 | ...options
|
811 | });
|
812 | }
|
813 | }, [router, id]);
|
814 | return navigate;
|
815 | }
|
816 |
|
817 | const alreadyWarned = {};
|
818 |
|
819 | function warningOnce(key, cond, message) {
|
820 | if (!cond && !alreadyWarned[key]) {
|
821 | alreadyWarned[key] = true;
|
822 | UNSAFE_warning(false, message) ;
|
823 | }
|
824 | }
|
825 |
|
826 |
|
827 |
|
828 |
|
829 |
|
830 | function RouterProvider({
|
831 | fallbackElement,
|
832 | router
|
833 | }) {
|
834 |
|
835 |
|
836 | let [state, setState] = React.useState(router.state);
|
837 | React.useLayoutEffect(() => router.subscribe(setState), [router, setState]);
|
838 | let navigator = React.useMemo(() => {
|
839 | return {
|
840 | createHref: router.createHref,
|
841 | encodeLocation: router.encodeLocation,
|
842 | go: n => router.navigate(n),
|
843 | push: (to, state, opts) => router.navigate(to, {
|
844 | state,
|
845 | preventScrollReset: opts?.preventScrollReset
|
846 | }),
|
847 | replace: (to, state, opts) => router.navigate(to, {
|
848 | replace: true,
|
849 | state,
|
850 | preventScrollReset: opts?.preventScrollReset
|
851 | })
|
852 | };
|
853 | }, [router]);
|
854 | let basename = router.basename || "/";
|
855 | let dataRouterContext = React.useMemo(() => ({
|
856 | router,
|
857 | navigator,
|
858 | static: false,
|
859 | basename
|
860 | }), [router, navigator, basename]);
|
861 |
|
862 |
|
863 |
|
864 |
|
865 |
|
866 |
|
867 | return React.createElement(React.Fragment, null, React.createElement(DataRouterContext.Provider, {
|
868 | value: dataRouterContext
|
869 | }, React.createElement(DataRouterStateContext.Provider, {
|
870 | value: state
|
871 | }, React.createElement(Router, {
|
872 | basename: router.basename,
|
873 | location: router.state.location,
|
874 | navigationType: router.state.historyAction,
|
875 | navigator: navigator
|
876 | }, router.state.initialized ? React.createElement(DataRoutes, {
|
877 | routes: router.routes,
|
878 | state: state
|
879 | }) : fallbackElement))), null);
|
880 | }
|
881 |
|
882 | function DataRoutes({
|
883 | routes,
|
884 | state
|
885 | }) {
|
886 | return useRoutesImpl(routes, undefined, state);
|
887 | }
|
888 |
|
889 |
|
890 |
|
891 |
|
892 |
|
893 |
|
894 |
|
895 | function MemoryRouter({
|
896 | basename,
|
897 | children,
|
898 | initialEntries,
|
899 | initialIndex
|
900 | }) {
|
901 | let historyRef = React.useRef();
|
902 |
|
903 | if (historyRef.current == null) {
|
904 | historyRef.current = createMemoryHistory({
|
905 | initialEntries,
|
906 | initialIndex,
|
907 | v5Compat: true
|
908 | });
|
909 | }
|
910 |
|
911 | let history = historyRef.current;
|
912 | let [state, setState] = React.useState({
|
913 | action: history.action,
|
914 | location: history.location
|
915 | });
|
916 | React.useLayoutEffect(() => history.listen(setState), [history]);
|
917 | return React.createElement(Router, {
|
918 | basename: basename,
|
919 | children: children,
|
920 | location: state.location,
|
921 | navigationType: state.action,
|
922 | navigator: history
|
923 | });
|
924 | }
|
925 |
|
926 |
|
927 |
|
928 |
|
929 |
|
930 |
|
931 |
|
932 |
|
933 |
|
934 |
|
935 | function Navigate({
|
936 | to,
|
937 | replace,
|
938 | state,
|
939 | relative
|
940 | }) {
|
941 | !useInRouterContext() ? UNSAFE_invariant(false,
|
942 |
|
943 | `<Navigate> may be used only in the context of a <Router> component.`) : void 0;
|
944 | UNSAFE_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.`) ;
|
945 | let {
|
946 | matches
|
947 | } = React.useContext(RouteContext);
|
948 | let {
|
949 | pathname: locationPathname
|
950 | } = useLocation();
|
951 | let navigate = useNavigate();
|
952 |
|
953 |
|
954 | let path = resolveTo(to, UNSAFE_getPathContributingMatches(matches).map(match => match.pathnameBase), locationPathname, relative === "path");
|
955 | let jsonPath = JSON.stringify(path);
|
956 | React.useEffect(() => navigate(JSON.parse(jsonPath), {
|
957 | replace,
|
958 | state,
|
959 | relative
|
960 | }), [navigate, jsonPath, relative, replace, state]);
|
961 | return null;
|
962 | }
|
963 |
|
964 |
|
965 |
|
966 |
|
967 |
|
968 |
|
969 | function Outlet(props) {
|
970 | return useOutlet(props.context);
|
971 | }
|
972 |
|
973 |
|
974 |
|
975 |
|
976 |
|
977 |
|
978 | function Route(_props) {
|
979 | UNSAFE_invariant(false, `A <Route> is only ever to be used as the child of <Routes> element, ` + `never rendered directly. Please wrap your <Route> in a <Routes>.`) ;
|
980 | }
|
981 |
|
982 |
|
983 |
|
984 |
|
985 |
|
986 |
|
987 |
|
988 |
|
989 |
|
990 |
|
991 | function Router({
|
992 | basename: basenameProp = "/",
|
993 | children = null,
|
994 | location: locationProp,
|
995 | navigationType = Action.Pop,
|
996 | navigator,
|
997 | static: staticProp = false
|
998 | }) {
|
999 | !!useInRouterContext() ? UNSAFE_invariant(false, `You cannot render a <Router> inside another <Router>.` + ` You should never have more than one in your app.`) : void 0;
|
1000 |
|
1001 |
|
1002 | let basename = basenameProp.replace(/^\/*/, "/");
|
1003 | let navigationContext = React.useMemo(() => ({
|
1004 | basename,
|
1005 | navigator,
|
1006 | static: staticProp
|
1007 | }), [basename, navigator, staticProp]);
|
1008 |
|
1009 | if (typeof locationProp === "string") {
|
1010 | locationProp = parsePath(locationProp);
|
1011 | }
|
1012 |
|
1013 | let {
|
1014 | pathname = "/",
|
1015 | search = "",
|
1016 | hash = "",
|
1017 | state = null,
|
1018 | key = "default"
|
1019 | } = locationProp;
|
1020 | let locationContext = React.useMemo(() => {
|
1021 | let trailingPathname = stripBasename(pathname, basename);
|
1022 |
|
1023 | if (trailingPathname == null) {
|
1024 | return null;
|
1025 | }
|
1026 |
|
1027 | return {
|
1028 | location: {
|
1029 | pathname: trailingPathname,
|
1030 | search,
|
1031 | hash,
|
1032 | state,
|
1033 | key
|
1034 | },
|
1035 | navigationType
|
1036 | };
|
1037 | }, [basename, pathname, search, hash, state, key, navigationType]);
|
1038 | UNSAFE_warning(locationContext != null, `<Router basename="${basename}"> is not able to match the URL ` + `"${pathname}${search}${hash}" because it does not start with the ` + `basename, so the <Router> won't render anything.`) ;
|
1039 |
|
1040 | if (locationContext == null) {
|
1041 | return null;
|
1042 | }
|
1043 |
|
1044 | return React.createElement(NavigationContext.Provider, {
|
1045 | value: navigationContext
|
1046 | }, React.createElement(LocationContext.Provider, {
|
1047 | children: children,
|
1048 | value: locationContext
|
1049 | }));
|
1050 | }
|
1051 |
|
1052 |
|
1053 |
|
1054 |
|
1055 |
|
1056 |
|
1057 |
|
1058 | function Routes({
|
1059 | children,
|
1060 | location
|
1061 | }) {
|
1062 | return useRoutes(createRoutesFromChildren(children), location);
|
1063 | }
|
1064 |
|
1065 |
|
1066 |
|
1067 |
|
1068 |
|
1069 | function Await({
|
1070 | children,
|
1071 | errorElement,
|
1072 | resolve
|
1073 | }) {
|
1074 | return React.createElement(AwaitErrorBoundary, {
|
1075 | resolve: resolve,
|
1076 | errorElement: errorElement
|
1077 | }, React.createElement(ResolveAwait, null, children));
|
1078 | }
|
1079 | var AwaitRenderStatus;
|
1080 |
|
1081 | (function (AwaitRenderStatus) {
|
1082 | AwaitRenderStatus[AwaitRenderStatus["pending"] = 0] = "pending";
|
1083 | AwaitRenderStatus[AwaitRenderStatus["success"] = 1] = "success";
|
1084 | AwaitRenderStatus[AwaitRenderStatus["error"] = 2] = "error";
|
1085 | })(AwaitRenderStatus || (AwaitRenderStatus = {}));
|
1086 |
|
1087 | const neverSettledPromise = new Promise(() => {});
|
1088 |
|
1089 | class AwaitErrorBoundary extends React.Component {
|
1090 | constructor(props) {
|
1091 | super(props);
|
1092 | this.state = {
|
1093 | error: null
|
1094 | };
|
1095 | }
|
1096 |
|
1097 | static getDerivedStateFromError(error) {
|
1098 | return {
|
1099 | error
|
1100 | };
|
1101 | }
|
1102 |
|
1103 | componentDidCatch(error, errorInfo) {
|
1104 | console.error("<Await> caught the following error during render", error, errorInfo);
|
1105 | }
|
1106 |
|
1107 | render() {
|
1108 | let {
|
1109 | children,
|
1110 | errorElement,
|
1111 | resolve
|
1112 | } = this.props;
|
1113 | let promise = null;
|
1114 | let status = AwaitRenderStatus.pending;
|
1115 |
|
1116 | if (!(resolve instanceof Promise)) {
|
1117 |
|
1118 | status = AwaitRenderStatus.success;
|
1119 | promise = Promise.resolve();
|
1120 | Object.defineProperty(promise, "_tracked", {
|
1121 | get: () => true
|
1122 | });
|
1123 | Object.defineProperty(promise, "_data", {
|
1124 | get: () => resolve
|
1125 | });
|
1126 | } else if (this.state.error) {
|
1127 |
|
1128 | status = AwaitRenderStatus.error;
|
1129 | let renderError = this.state.error;
|
1130 | promise = Promise.reject().catch(() => {});
|
1131 |
|
1132 | Object.defineProperty(promise, "_tracked", {
|
1133 | get: () => true
|
1134 | });
|
1135 | Object.defineProperty(promise, "_error", {
|
1136 | get: () => renderError
|
1137 | });
|
1138 | } else if (resolve._tracked) {
|
1139 |
|
1140 | promise = resolve;
|
1141 | status = promise._error !== undefined ? AwaitRenderStatus.error : promise._data !== undefined ? AwaitRenderStatus.success : AwaitRenderStatus.pending;
|
1142 | } else {
|
1143 |
|
1144 | status = AwaitRenderStatus.pending;
|
1145 | Object.defineProperty(resolve, "_tracked", {
|
1146 | get: () => true
|
1147 | });
|
1148 | promise = resolve.then(data => Object.defineProperty(resolve, "_data", {
|
1149 | get: () => data
|
1150 | }), error => Object.defineProperty(resolve, "_error", {
|
1151 | get: () => error
|
1152 | }));
|
1153 | }
|
1154 |
|
1155 | if (status === AwaitRenderStatus.error && promise._error instanceof AbortedDeferredError) {
|
1156 |
|
1157 | throw neverSettledPromise;
|
1158 | }
|
1159 |
|
1160 | if (status === AwaitRenderStatus.error && !errorElement) {
|
1161 |
|
1162 | throw promise._error;
|
1163 | }
|
1164 |
|
1165 | if (status === AwaitRenderStatus.error) {
|
1166 |
|
1167 | return React.createElement(AwaitContext.Provider, {
|
1168 | value: promise,
|
1169 | children: errorElement
|
1170 | });
|
1171 | }
|
1172 |
|
1173 | if (status === AwaitRenderStatus.success) {
|
1174 |
|
1175 | return React.createElement(AwaitContext.Provider, {
|
1176 | value: promise,
|
1177 | children: children
|
1178 | });
|
1179 | }
|
1180 |
|
1181 |
|
1182 | throw promise;
|
1183 | }
|
1184 |
|
1185 | }
|
1186 |
|
1187 |
|
1188 |
|
1189 |
|
1190 |
|
1191 |
|
1192 | function ResolveAwait({
|
1193 | children
|
1194 | }) {
|
1195 | let data = useAsyncValue();
|
1196 | let toRender = typeof children === "function" ? children(data) : children;
|
1197 | return React.createElement(React.Fragment, null, toRender);
|
1198 | }
|
1199 |
|
1200 |
|
1201 |
|
1202 |
|
1203 |
|
1204 |
|
1205 |
|
1206 |
|
1207 |
|
1208 |
|
1209 |
|
1210 |
|
1211 | function createRoutesFromChildren(children, parentPath = []) {
|
1212 | let routes = [];
|
1213 | React.Children.forEach(children, (element, index) => {
|
1214 | if (! React.isValidElement(element)) {
|
1215 |
|
1216 |
|
1217 | return;
|
1218 | }
|
1219 |
|
1220 | let treePath = [...parentPath, index];
|
1221 |
|
1222 | if (element.type === React.Fragment) {
|
1223 |
|
1224 | routes.push.apply(routes, createRoutesFromChildren(element.props.children, treePath));
|
1225 | return;
|
1226 | }
|
1227 |
|
1228 | !(element.type === Route) ? UNSAFE_invariant(false, `[${typeof element.type === "string" ? element.type : element.type.name}] is not a <Route> component. All component children of <Routes> must be a <Route> or <React.Fragment>`) : void 0;
|
1229 | !(!element.props.index || !element.props.children) ? UNSAFE_invariant(false, "An index route cannot have child routes.") : void 0;
|
1230 | let route = {
|
1231 | id: element.props.id || treePath.join("-"),
|
1232 | caseSensitive: element.props.caseSensitive,
|
1233 | element: element.props.element,
|
1234 | Component: element.props.Component,
|
1235 | index: element.props.index,
|
1236 | path: element.props.path,
|
1237 | loader: element.props.loader,
|
1238 | action: element.props.action,
|
1239 | errorElement: element.props.errorElement,
|
1240 | ErrorBoundary: element.props.ErrorBoundary,
|
1241 | hasErrorBoundary: element.props.ErrorBoundary != null || element.props.errorElement != null,
|
1242 | shouldRevalidate: element.props.shouldRevalidate,
|
1243 | handle: element.props.handle,
|
1244 | lazy: element.props.lazy
|
1245 | };
|
1246 |
|
1247 | if (element.props.children) {
|
1248 | route.children = createRoutesFromChildren(element.props.children, treePath);
|
1249 | }
|
1250 |
|
1251 | routes.push(route);
|
1252 | });
|
1253 | return routes;
|
1254 | }
|
1255 |
|
1256 |
|
1257 |
|
1258 |
|
1259 | function renderMatches(matches) {
|
1260 | return _renderMatches(matches);
|
1261 | }
|
1262 |
|
1263 | function mapRouteProperties(route) {
|
1264 | let updates = {
|
1265 |
|
1266 |
|
1267 | hasErrorBoundary: route.ErrorBoundary != null || route.errorElement != null
|
1268 | };
|
1269 |
|
1270 | if (route.Component) {
|
1271 | {
|
1272 | if (route.element) {
|
1273 | UNSAFE_warning(false, "You should not include both `Component` and `element` on your route - " + "`Component` will be used.") ;
|
1274 | }
|
1275 | }
|
1276 |
|
1277 | Object.assign(updates, {
|
1278 | element: React.createElement(route.Component),
|
1279 | Component: undefined
|
1280 | });
|
1281 | }
|
1282 |
|
1283 | if (route.ErrorBoundary) {
|
1284 | {
|
1285 | if (route.errorElement) {
|
1286 | UNSAFE_warning(false, "You should not include both `ErrorBoundary` and `errorElement` on your route - " + "`ErrorBoundary` will be used.") ;
|
1287 | }
|
1288 | }
|
1289 |
|
1290 | Object.assign(updates, {
|
1291 | errorElement: React.createElement(route.ErrorBoundary),
|
1292 | ErrorBoundary: undefined
|
1293 | });
|
1294 | }
|
1295 |
|
1296 | return updates;
|
1297 | }
|
1298 |
|
1299 | function createMemoryRouter(routes, opts) {
|
1300 | return createRouter({
|
1301 | basename: opts?.basename,
|
1302 | future: { ...opts?.future,
|
1303 | v7_prependBasename: true
|
1304 | },
|
1305 | history: createMemoryHistory({
|
1306 | initialEntries: opts?.initialEntries,
|
1307 | initialIndex: opts?.initialIndex
|
1308 | }),
|
1309 | hydrationData: opts?.hydrationData,
|
1310 | routes,
|
1311 | mapRouteProperties
|
1312 | }).initialize();
|
1313 | }
|
1314 |
|
1315 | 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, mapRouteProperties as UNSAFE_mapRouteProperties, useRouteId as UNSAFE_useRouteId, useRoutesImpl as UNSAFE_useRoutesImpl, 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 };
|
1316 |
|