1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 | import { createContext, useRef, useState, useLayoutEffect, createElement, useContext, useEffect, useMemo, useCallback, Children, isValidElement, Fragment } from 'react';
|
12 | import { createMemoryHistory, Action, parsePath } from 'history';
|
13 |
|
14 | function invariant(cond, message) {
|
15 | if (!cond) throw new Error(message);
|
16 | }
|
17 |
|
18 | function warning(cond, message) {
|
19 | if (!cond) {
|
20 |
|
21 | if (typeof console !== "undefined") console.warn(message);
|
22 |
|
23 | try {
|
24 |
|
25 |
|
26 |
|
27 |
|
28 |
|
29 | throw new Error(message);
|
30 | } catch (e) {}
|
31 | }
|
32 | }
|
33 |
|
34 | const alreadyWarned = {};
|
35 |
|
36 | function warningOnce(key, cond, message) {
|
37 | if (!cond && !alreadyWarned[key]) {
|
38 | alreadyWarned[key] = true;
|
39 | warning(false, message) ;
|
40 | }
|
41 | }
|
42 |
|
43 |
|
44 |
|
45 |
|
46 |
|
47 |
|
48 |
|
49 |
|
50 |
|
51 |
|
52 |
|
53 |
|
54 |
|
55 |
|
56 | const NavigationContext = createContext(null);
|
57 |
|
58 | {
|
59 | NavigationContext.displayName = "Navigation";
|
60 | }
|
61 |
|
62 | const LocationContext = createContext(null);
|
63 |
|
64 | {
|
65 | LocationContext.displayName = "Location";
|
66 | }
|
67 |
|
68 | const RouteContext = createContext({
|
69 | outlet: null,
|
70 | matches: []
|
71 | });
|
72 |
|
73 | {
|
74 | RouteContext.displayName = "Route";
|
75 | }
|
76 |
|
77 |
|
78 |
|
79 |
|
80 |
|
81 |
|
82 |
|
83 |
|
84 |
|
85 | function MemoryRouter({
|
86 | basename,
|
87 | children,
|
88 | initialEntries,
|
89 | initialIndex
|
90 | }) {
|
91 | let historyRef = useRef();
|
92 |
|
93 | if (historyRef.current == null) {
|
94 | historyRef.current = createMemoryHistory({
|
95 | initialEntries,
|
96 | initialIndex
|
97 | });
|
98 | }
|
99 |
|
100 | let history = historyRef.current;
|
101 | let [state, setState] = useState({
|
102 | action: history.action,
|
103 | location: history.location
|
104 | });
|
105 | useLayoutEffect(() => history.listen(setState), [history]);
|
106 | return createElement(Router, {
|
107 | basename: basename,
|
108 | children: children,
|
109 | location: state.location,
|
110 | navigationType: state.action,
|
111 | navigator: history
|
112 | });
|
113 | }
|
114 |
|
115 |
|
116 |
|
117 |
|
118 |
|
119 |
|
120 |
|
121 |
|
122 |
|
123 |
|
124 | function Navigate({
|
125 | to,
|
126 | replace,
|
127 | state
|
128 | }) {
|
129 | !useInRouterContext() ? invariant(false,
|
130 |
|
131 | `<Navigate> may be used only in the context of a <Router> component.`) : void 0;
|
132 | warning(!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.`) ;
|
133 | let navigate = useNavigate();
|
134 | useEffect(() => {
|
135 | navigate(to, {
|
136 | replace,
|
137 | state
|
138 | });
|
139 | });
|
140 | return null;
|
141 | }
|
142 |
|
143 |
|
144 |
|
145 |
|
146 |
|
147 |
|
148 | function Outlet(props) {
|
149 | return useOutlet(props.context);
|
150 | }
|
151 |
|
152 |
|
153 |
|
154 |
|
155 |
|
156 |
|
157 | function Route(_props) {
|
158 | 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>.`) ;
|
159 | }
|
160 |
|
161 |
|
162 |
|
163 |
|
164 |
|
165 |
|
166 |
|
167 |
|
168 |
|
169 |
|
170 | function Router({
|
171 | basename: basenameProp = "/",
|
172 | children = null,
|
173 | location: locationProp,
|
174 | navigationType = Action.Pop,
|
175 | navigator,
|
176 | static: staticProp = false
|
177 | }) {
|
178 | !!useInRouterContext() ? invariant(false, `You cannot render a <Router> inside another <Router>.` + ` You should never have more than one in your app.`) : void 0;
|
179 | let basename = normalizePathname(basenameProp);
|
180 | let navigationContext = useMemo(() => ({
|
181 | basename,
|
182 | navigator,
|
183 | static: staticProp
|
184 | }), [basename, navigator, staticProp]);
|
185 |
|
186 | if (typeof locationProp === "string") {
|
187 | locationProp = parsePath(locationProp);
|
188 | }
|
189 |
|
190 | let {
|
191 | pathname = "/",
|
192 | search = "",
|
193 | hash = "",
|
194 | state = null,
|
195 | key = "default"
|
196 | } = locationProp;
|
197 | let location = useMemo(() => {
|
198 | let trailingPathname = stripBasename(pathname, basename);
|
199 |
|
200 | if (trailingPathname == null) {
|
201 | return null;
|
202 | }
|
203 |
|
204 | return {
|
205 | pathname: trailingPathname,
|
206 | search,
|
207 | hash,
|
208 | state,
|
209 | key
|
210 | };
|
211 | }, [basename, pathname, search, hash, state, key]);
|
212 | 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.`) ;
|
213 |
|
214 | if (location == null) {
|
215 | return null;
|
216 | }
|
217 |
|
218 | return createElement(NavigationContext.Provider, {
|
219 | value: navigationContext
|
220 | }, createElement(LocationContext.Provider, {
|
221 | children: children,
|
222 | value: {
|
223 | location,
|
224 | navigationType
|
225 | }
|
226 | }));
|
227 | }
|
228 |
|
229 |
|
230 |
|
231 |
|
232 |
|
233 |
|
234 |
|
235 | function Routes({
|
236 | children,
|
237 | location
|
238 | }) {
|
239 | return useRoutes(createRoutesFromChildren(children), location);
|
240 | }
|
241 |
|
242 |
|
243 |
|
244 |
|
245 |
|
246 |
|
247 |
|
248 |
|
249 |
|
250 |
|
251 | function useHref(to) {
|
252 | !useInRouterContext() ? invariant(false,
|
253 |
|
254 | `useHref() may be used only in the context of a <Router> component.`) : void 0;
|
255 | let {
|
256 | basename,
|
257 | navigator
|
258 | } = useContext(NavigationContext);
|
259 | let {
|
260 | hash,
|
261 | pathname,
|
262 | search
|
263 | } = useResolvedPath(to);
|
264 | let joinedPathname = pathname;
|
265 |
|
266 | if (basename !== "/") {
|
267 | let toPathname = getToPathname(to);
|
268 | let endsWithSlash = toPathname != null && toPathname.endsWith("/");
|
269 | joinedPathname = pathname === "/" ? basename + (endsWithSlash ? "/" : "") : joinPaths([basename, pathname]);
|
270 | }
|
271 |
|
272 | return navigator.createHref({
|
273 | pathname: joinedPathname,
|
274 | search,
|
275 | hash
|
276 | });
|
277 | }
|
278 |
|
279 |
|
280 |
|
281 |
|
282 |
|
283 |
|
284 | function useInRouterContext() {
|
285 | return useContext(LocationContext) != null;
|
286 | }
|
287 |
|
288 |
|
289 |
|
290 |
|
291 |
|
292 |
|
293 |
|
294 |
|
295 |
|
296 |
|
297 |
|
298 | function useLocation() {
|
299 | !useInRouterContext() ? invariant(false,
|
300 |
|
301 | `useLocation() may be used only in the context of a <Router> component.`) : void 0;
|
302 | return useContext(LocationContext).location;
|
303 | }
|
304 |
|
305 |
|
306 |
|
307 |
|
308 |
|
309 |
|
310 |
|
311 | function useNavigationType() {
|
312 | return useContext(LocationContext).navigationType;
|
313 | }
|
314 |
|
315 |
|
316 |
|
317 |
|
318 |
|
319 |
|
320 |
|
321 |
|
322 | function useMatch(pattern) {
|
323 | !useInRouterContext() ? invariant(false,
|
324 |
|
325 | `useMatch() may be used only in the context of a <Router> component.`) : void 0;
|
326 | let {
|
327 | pathname
|
328 | } = useLocation();
|
329 | return useMemo(() => matchPath(pattern, pathname), [pathname, pattern]);
|
330 | }
|
331 |
|
332 |
|
333 |
|
334 |
|
335 |
|
336 |
|
337 |
|
338 |
|
339 |
|
340 |
|
341 | function useNavigate() {
|
342 | !useInRouterContext() ? invariant(false,
|
343 |
|
344 | `useNavigate() may be used only in the context of a <Router> component.`) : void 0;
|
345 | let {
|
346 | basename,
|
347 | navigator
|
348 | } = useContext(NavigationContext);
|
349 | let {
|
350 | matches
|
351 | } = useContext(RouteContext);
|
352 | let {
|
353 | pathname: locationPathname
|
354 | } = useLocation();
|
355 | let routePathnamesJson = JSON.stringify(matches.map(match => match.pathnameBase));
|
356 | let activeRef = useRef(false);
|
357 | useEffect(() => {
|
358 | activeRef.current = true;
|
359 | });
|
360 | let navigate = useCallback((to, options = {}) => {
|
361 | warning(activeRef.current, `You should call navigate() in a React.useEffect(), not when ` + `your component is first rendered.`) ;
|
362 | if (!activeRef.current) return;
|
363 |
|
364 | if (typeof to === "number") {
|
365 | navigator.go(to);
|
366 | return;
|
367 | }
|
368 |
|
369 | let path = resolveTo(to, JSON.parse(routePathnamesJson), locationPathname);
|
370 |
|
371 | if (basename !== "/") {
|
372 | path.pathname = joinPaths([basename, path.pathname]);
|
373 | }
|
374 |
|
375 | (!!options.replace ? navigator.replace : navigator.push)(path, options.state);
|
376 | }, [basename, navigator, routePathnamesJson, locationPathname]);
|
377 | return navigate;
|
378 | }
|
379 | const OutletContext = createContext(null);
|
380 |
|
381 |
|
382 |
|
383 |
|
384 |
|
385 |
|
386 | function useOutletContext() {
|
387 | return useContext(OutletContext);
|
388 | }
|
389 |
|
390 |
|
391 |
|
392 |
|
393 |
|
394 |
|
395 |
|
396 | function useOutlet(context) {
|
397 | let outlet = useContext(RouteContext).outlet;
|
398 |
|
399 | if (outlet) {
|
400 | return createElement(OutletContext.Provider, {
|
401 | value: context
|
402 | }, outlet);
|
403 | }
|
404 |
|
405 | return outlet;
|
406 | }
|
407 |
|
408 |
|
409 |
|
410 |
|
411 |
|
412 |
|
413 |
|
414 | function useParams() {
|
415 | let {
|
416 | matches
|
417 | } = useContext(RouteContext);
|
418 | let routeMatch = matches[matches.length - 1];
|
419 | return routeMatch ? routeMatch.params : {};
|
420 | }
|
421 |
|
422 |
|
423 |
|
424 |
|
425 |
|
426 |
|
427 | function useResolvedPath(to) {
|
428 | let {
|
429 | matches
|
430 | } = useContext(RouteContext);
|
431 | let {
|
432 | pathname: locationPathname
|
433 | } = useLocation();
|
434 | let routePathnamesJson = JSON.stringify(matches.map(match => match.pathnameBase));
|
435 | return useMemo(() => resolveTo(to, JSON.parse(routePathnamesJson), locationPathname), [to, routePathnamesJson, locationPathname]);
|
436 | }
|
437 |
|
438 |
|
439 |
|
440 |
|
441 |
|
442 |
|
443 |
|
444 |
|
445 |
|
446 | function useRoutes(routes, locationArg) {
|
447 | !useInRouterContext() ? invariant(false,
|
448 |
|
449 | `useRoutes() may be used only in the context of a <Router> component.`) : void 0;
|
450 | let {
|
451 | matches: parentMatches
|
452 | } = useContext(RouteContext);
|
453 | let routeMatch = parentMatches[parentMatches.length - 1];
|
454 | let parentParams = routeMatch ? routeMatch.params : {};
|
455 | let parentPathname = routeMatch ? routeMatch.pathname : "/";
|
456 | let parentPathnameBase = routeMatch ? routeMatch.pathnameBase : "/";
|
457 | let parentRoute = routeMatch && routeMatch.route;
|
458 |
|
459 | {
|
460 |
|
461 |
|
462 |
|
463 |
|
464 |
|
465 |
|
466 |
|
467 |
|
468 |
|
469 |
|
470 |
|
471 |
|
472 |
|
473 |
|
474 |
|
475 |
|
476 |
|
477 |
|
478 |
|
479 |
|
480 | let parentPath = parentRoute && parentRoute.path || "";
|
481 | 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}/*`}">.`);
|
482 | }
|
483 |
|
484 | let locationFromContext = useLocation();
|
485 | let location;
|
486 |
|
487 | if (locationArg) {
|
488 | let parsedLocationArg = typeof locationArg === "string" ? parsePath(locationArg) : locationArg;
|
489 | !(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;
|
490 | location = parsedLocationArg;
|
491 | } else {
|
492 | location = locationFromContext;
|
493 | }
|
494 |
|
495 | let pathname = location.pathname || "/";
|
496 | let remainingPathname = parentPathnameBase === "/" ? pathname : pathname.slice(parentPathnameBase.length) || "/";
|
497 | let matches = matchRoutes(routes, {
|
498 | pathname: remainingPathname
|
499 | });
|
500 |
|
501 | {
|
502 | warning(parentRoute || matches != null, `No routes matched location "${location.pathname}${location.search}${location.hash}" `) ;
|
503 | 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.`) ;
|
504 | }
|
505 |
|
506 | return _renderMatches(matches && matches.map(match => Object.assign({}, match, {
|
507 | params: Object.assign({}, parentParams, match.params),
|
508 | pathname: joinPaths([parentPathnameBase, match.pathname]),
|
509 | pathnameBase: match.pathnameBase === "/" ? parentPathnameBase : joinPaths([parentPathnameBase, match.pathnameBase])
|
510 | })), parentMatches);
|
511 | }
|
512 |
|
513 |
|
514 |
|
515 |
|
516 |
|
517 |
|
518 |
|
519 |
|
520 |
|
521 |
|
522 |
|
523 | function createRoutesFromChildren(children) {
|
524 | let routes = [];
|
525 | Children.forEach(children, element => {
|
526 | if (! isValidElement(element)) {
|
527 |
|
528 |
|
529 | return;
|
530 | }
|
531 |
|
532 | if (element.type === Fragment) {
|
533 |
|
534 | routes.push.apply(routes, createRoutesFromChildren(element.props.children));
|
535 | return;
|
536 | }
|
537 |
|
538 | !(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;
|
539 | let route = {
|
540 | caseSensitive: element.props.caseSensitive,
|
541 | element: element.props.element,
|
542 | index: element.props.index,
|
543 | path: element.props.path
|
544 | };
|
545 |
|
546 | if (element.props.children) {
|
547 | route.children = createRoutesFromChildren(element.props.children);
|
548 | }
|
549 |
|
550 | routes.push(route);
|
551 | });
|
552 | return routes;
|
553 | }
|
554 |
|
555 |
|
556 |
|
557 |
|
558 |
|
559 |
|
560 |
|
561 |
|
562 |
|
563 | function generatePath(path, params = {}) {
|
564 | return path.replace(/:(\w+)/g, (_, key) => {
|
565 | !(params[key] != null) ? invariant(false, `Missing ":${key}" param`) : void 0;
|
566 | return params[key];
|
567 | }).replace(/\/*\*$/, _ => params["*"] == null ? "" : params["*"].replace(/^\/*/, "/"));
|
568 | }
|
569 |
|
570 |
|
571 |
|
572 |
|
573 |
|
574 |
|
575 |
|
576 |
|
577 |
|
578 | function matchRoutes(routes, locationArg, basename = "/") {
|
579 | let location = typeof locationArg === "string" ? parsePath(locationArg) : locationArg;
|
580 | let pathname = stripBasename(location.pathname || "/", basename);
|
581 |
|
582 | if (pathname == null) {
|
583 | return null;
|
584 | }
|
585 |
|
586 | let branches = flattenRoutes(routes);
|
587 | rankRouteBranches(branches);
|
588 | let matches = null;
|
589 |
|
590 | for (let i = 0; matches == null && i < branches.length; ++i) {
|
591 | matches = matchRouteBranch(branches[i], pathname);
|
592 | }
|
593 |
|
594 | return matches;
|
595 | }
|
596 |
|
597 | function flattenRoutes(routes, branches = [], parentsMeta = [], parentPath = "") {
|
598 | routes.forEach((route, index) => {
|
599 | let meta = {
|
600 | relativePath: route.path || "",
|
601 | caseSensitive: route.caseSensitive === true,
|
602 | childrenIndex: index,
|
603 | route
|
604 | };
|
605 |
|
606 | if (meta.relativePath.startsWith("/")) {
|
607 | !meta.relativePath.startsWith(parentPath) ? invariant(false, `Absolute route path "${meta.relativePath}" nested under path ` + `"${parentPath}" is not valid. An absolute child route path ` + `must start with the combined path of all its parent routes.`) : void 0;
|
608 | meta.relativePath = meta.relativePath.slice(parentPath.length);
|
609 | }
|
610 |
|
611 | let path = joinPaths([parentPath, meta.relativePath]);
|
612 | let routesMeta = parentsMeta.concat(meta);
|
613 |
|
614 |
|
615 |
|
616 | if (route.children && route.children.length > 0) {
|
617 | !(route.index !== true) ? invariant(false, `Index routes must not have child routes. Please remove ` + `all child routes from route path "${path}".`) : void 0;
|
618 | flattenRoutes(route.children, branches, routesMeta, path);
|
619 | }
|
620 |
|
621 |
|
622 |
|
623 | if (route.path == null && !route.index) {
|
624 | return;
|
625 | }
|
626 |
|
627 | branches.push({
|
628 | path,
|
629 | score: computeScore(path, route.index),
|
630 | routesMeta
|
631 | });
|
632 | });
|
633 | return branches;
|
634 | }
|
635 |
|
636 | function rankRouteBranches(branches) {
|
637 | branches.sort((a, b) => a.score !== b.score ? b.score - a.score
|
638 | : compareIndexes(a.routesMeta.map(meta => meta.childrenIndex), b.routesMeta.map(meta => meta.childrenIndex)));
|
639 | }
|
640 |
|
641 | const paramRe = /^:\w+$/;
|
642 | const dynamicSegmentValue = 3;
|
643 | const indexRouteValue = 2;
|
644 | const emptySegmentValue = 1;
|
645 | const staticSegmentValue = 10;
|
646 | const splatPenalty = -2;
|
647 |
|
648 | const isSplat = s => s === "*";
|
649 |
|
650 | function computeScore(path, index) {
|
651 | let segments = path.split("/");
|
652 | let initialScore = segments.length;
|
653 |
|
654 | if (segments.some(isSplat)) {
|
655 | initialScore += splatPenalty;
|
656 | }
|
657 |
|
658 | if (index) {
|
659 | initialScore += indexRouteValue;
|
660 | }
|
661 |
|
662 | return segments.filter(s => !isSplat(s)).reduce((score, segment) => score + (paramRe.test(segment) ? dynamicSegmentValue : segment === "" ? emptySegmentValue : staticSegmentValue), initialScore);
|
663 | }
|
664 |
|
665 | function compareIndexes(a, b) {
|
666 | let siblings = a.length === b.length && a.slice(0, -1).every((n, i) => n === b[i]);
|
667 | return siblings ?
|
668 |
|
669 |
|
670 |
|
671 | a[a.length - 1] - b[b.length - 1] :
|
672 |
|
673 | 0;
|
674 | }
|
675 |
|
676 | function matchRouteBranch(branch, pathname) {
|
677 | let {
|
678 | routesMeta
|
679 | } = branch;
|
680 | let matchedParams = {};
|
681 | let matchedPathname = "/";
|
682 | let matches = [];
|
683 |
|
684 | for (let i = 0; i < routesMeta.length; ++i) {
|
685 | let meta = routesMeta[i];
|
686 | let end = i === routesMeta.length - 1;
|
687 | let remainingPathname = matchedPathname === "/" ? pathname : pathname.slice(matchedPathname.length) || "/";
|
688 | let match = matchPath({
|
689 | path: meta.relativePath,
|
690 | caseSensitive: meta.caseSensitive,
|
691 | end
|
692 | }, remainingPathname);
|
693 | if (!match) return null;
|
694 | Object.assign(matchedParams, match.params);
|
695 | let route = meta.route;
|
696 | matches.push({
|
697 | params: matchedParams,
|
698 | pathname: joinPaths([matchedPathname, match.pathname]),
|
699 | pathnameBase: joinPaths([matchedPathname, match.pathnameBase]),
|
700 | route
|
701 | });
|
702 |
|
703 | if (match.pathnameBase !== "/") {
|
704 | matchedPathname = joinPaths([matchedPathname, match.pathnameBase]);
|
705 | }
|
706 | }
|
707 |
|
708 | return matches;
|
709 | }
|
710 |
|
711 |
|
712 |
|
713 |
|
714 |
|
715 | function renderMatches(matches) {
|
716 | return _renderMatches(matches);
|
717 | }
|
718 |
|
719 | function _renderMatches(matches, parentMatches = []) {
|
720 | if (matches == null) return null;
|
721 | return matches.reduceRight((outlet, match, index) => {
|
722 | return createElement(RouteContext.Provider, {
|
723 | children: match.route.element !== undefined ? match.route.element : createElement(Outlet, null),
|
724 | value: {
|
725 | outlet,
|
726 | matches: parentMatches.concat(matches.slice(0, index + 1))
|
727 | }
|
728 | });
|
729 | }, null);
|
730 | }
|
731 |
|
732 |
|
733 |
|
734 |
|
735 |
|
736 |
|
737 |
|
738 |
|
739 |
|
740 |
|
741 |
|
742 | function matchPath(pattern, pathname) {
|
743 | if (typeof pattern === "string") {
|
744 | pattern = {
|
745 | path: pattern,
|
746 | caseSensitive: false,
|
747 | end: true
|
748 | };
|
749 | }
|
750 |
|
751 | let [matcher, paramNames] = compilePath(pattern.path, pattern.caseSensitive, pattern.end);
|
752 | let match = pathname.match(matcher);
|
753 | if (!match) return null;
|
754 | let matchedPathname = match[0];
|
755 | let pathnameBase = matchedPathname.replace(/(.)\/+$/, "$1");
|
756 | let captureGroups = match.slice(1);
|
757 | let params = paramNames.reduce((memo, paramName, index) => {
|
758 |
|
759 |
|
760 | if (paramName === "*") {
|
761 | let splatValue = captureGroups[index] || "";
|
762 | pathnameBase = matchedPathname.slice(0, matchedPathname.length - splatValue.length).replace(/(.)\/+$/, "$1");
|
763 | }
|
764 |
|
765 | memo[paramName] = safelyDecodeURIComponent(captureGroups[index] || "", paramName);
|
766 | return memo;
|
767 | }, {});
|
768 | return {
|
769 | params,
|
770 | pathname: matchedPathname,
|
771 | pathnameBase,
|
772 | pattern
|
773 | };
|
774 | }
|
775 |
|
776 | function compilePath(path, caseSensitive = false, end = true) {
|
777 | warning(path === "*" || !path.endsWith("*") || path.endsWith("/*"), `Route path "${path}" will be treated as if it were ` + `"${path.replace(/\*$/, "/*")}" because the \`*\` character must ` + `always follow a \`/\` in the pattern. To get rid of this warning, ` + `please change the route path to "${path.replace(/\*$/, "/*")}".`) ;
|
778 | let paramNames = [];
|
779 | let regexpSource = "^" + path.replace(/\/*\*?$/, "")
|
780 | .replace(/^\/*/, "/")
|
781 | .replace(/[\\.*+^$?{}|()[\]]/g, "\\$&")
|
782 | .replace(/:(\w+)/g, (_, paramName) => {
|
783 | paramNames.push(paramName);
|
784 | return "([^\\/]+)";
|
785 | });
|
786 |
|
787 | if (path.endsWith("*")) {
|
788 | paramNames.push("*");
|
789 | regexpSource += path === "*" || path === "/*" ? "(.*)$"
|
790 | : "(?:\\/(.+)|\\/*)$";
|
791 | } else {
|
792 | regexpSource += end ? "\\/*$"
|
793 | :
|
794 |
|
795 |
|
796 | "(?:\\b|\\/|$)";
|
797 | }
|
798 |
|
799 | let matcher = new RegExp(regexpSource, caseSensitive ? undefined : "i");
|
800 | return [matcher, paramNames];
|
801 | }
|
802 |
|
803 | function safelyDecodeURIComponent(value, paramName) {
|
804 | try {
|
805 | return decodeURIComponent(value);
|
806 | } catch (error) {
|
807 | warning(false, `The value for the URL param "${paramName}" will not be decoded because` + ` the string "${value}" is a malformed URL segment. This is probably` + ` due to a bad percent encoding (${error}).`) ;
|
808 | return value;
|
809 | }
|
810 | }
|
811 |
|
812 |
|
813 |
|
814 |
|
815 |
|
816 |
|
817 |
|
818 | function resolvePath(to, fromPathname = "/") {
|
819 | let {
|
820 | pathname: toPathname,
|
821 | search = "",
|
822 | hash = ""
|
823 | } = typeof to === "string" ? parsePath(to) : to;
|
824 | let pathname = toPathname ? toPathname.startsWith("/") ? toPathname : resolvePathname(toPathname, fromPathname) : fromPathname;
|
825 | return {
|
826 | pathname,
|
827 | search: normalizeSearch(search),
|
828 | hash: normalizeHash(hash)
|
829 | };
|
830 | }
|
831 |
|
832 | function resolvePathname(relativePath, fromPathname) {
|
833 | let segments = fromPathname.replace(/\/+$/, "").split("/");
|
834 | let relativeSegments = relativePath.split("/");
|
835 | relativeSegments.forEach(segment => {
|
836 | if (segment === "..") {
|
837 |
|
838 | if (segments.length > 1) segments.pop();
|
839 | } else if (segment !== ".") {
|
840 | segments.push(segment);
|
841 | }
|
842 | });
|
843 | return segments.length > 1 ? segments.join("/") : "/";
|
844 | }
|
845 |
|
846 | function resolveTo(toArg, routePathnames, locationPathname) {
|
847 | let to = typeof toArg === "string" ? parsePath(toArg) : toArg;
|
848 | let toPathname = toArg === "" || to.pathname === "" ? "/" : to.pathname;
|
849 |
|
850 |
|
851 |
|
852 |
|
853 |
|
854 |
|
855 |
|
856 | let from;
|
857 |
|
858 | if (toPathname == null) {
|
859 | from = locationPathname;
|
860 | } else {
|
861 | let routePathnameIndex = routePathnames.length - 1;
|
862 |
|
863 | if (toPathname.startsWith("..")) {
|
864 | let toSegments = toPathname.split("/");
|
865 |
|
866 |
|
867 |
|
868 | while (toSegments[0] === "..") {
|
869 | toSegments.shift();
|
870 | routePathnameIndex -= 1;
|
871 | }
|
872 |
|
873 | to.pathname = toSegments.join("/");
|
874 | }
|
875 |
|
876 |
|
877 |
|
878 | from = routePathnameIndex >= 0 ? routePathnames[routePathnameIndex] : "/";
|
879 | }
|
880 |
|
881 | let path = resolvePath(to, from);
|
882 |
|
883 | if (toPathname && toPathname !== "/" && toPathname.endsWith("/") && !path.pathname.endsWith("/")) {
|
884 | path.pathname += "/";
|
885 | }
|
886 |
|
887 | return path;
|
888 | }
|
889 |
|
890 | function getToPathname(to) {
|
891 |
|
892 | return to === "" || to.pathname === "" ? "/" : typeof to === "string" ? parsePath(to).pathname : to.pathname;
|
893 | }
|
894 |
|
895 | function stripBasename(pathname, basename) {
|
896 | if (basename === "/") return pathname;
|
897 |
|
898 | if (!pathname.toLowerCase().startsWith(basename.toLowerCase())) {
|
899 | return null;
|
900 | }
|
901 |
|
902 | let nextChar = pathname.charAt(basename.length);
|
903 |
|
904 | if (nextChar && nextChar !== "/") {
|
905 |
|
906 | return null;
|
907 | }
|
908 |
|
909 | return pathname.slice(basename.length) || "/";
|
910 | }
|
911 |
|
912 | const joinPaths = paths => paths.join("/").replace(/\/\/+/g, "/");
|
913 |
|
914 | const normalizePathname = pathname => pathname.replace(/\/+$/, "").replace(/^\/*/, "/");
|
915 |
|
916 | const normalizeSearch = search => !search || search === "?" ? "" : search.startsWith("?") ? search : "?" + search;
|
917 |
|
918 | const normalizeHash = hash => !hash || hash === "#" ? "" : hash.startsWith("#") ? hash : "#" + hash;
|
919 |
|
920 | export { MemoryRouter, Navigate, Outlet, Route, Router, Routes, LocationContext as UNSAFE_LocationContext, NavigationContext as UNSAFE_NavigationContext, RouteContext as UNSAFE_RouteContext, createRoutesFromChildren, generatePath, matchPath, matchRoutes, renderMatches, resolvePath, useHref, useInRouterContext, useLocation, useMatch, useNavigate, useNavigationType, useOutlet, useOutletContext, useParams, useResolvedPath, useRoutes };
|
921 |
|