UNPKG

33.9 kBJavaScriptView Raw
1/**
2 * React Router v6.0.2
3 *
4 * Copyright (c) Remix Software Inc.
5 *
6 * This source code is licensed under the MIT license found in the
7 * LICENSE.md file in the root directory of this source tree.
8 *
9 * @license MIT
10 */
11import { createContext, useRef, useState, useLayoutEffect, createElement, useContext, useEffect, useMemo, useCallback, Children, isValidElement, Fragment } from 'react';
12import { createMemoryHistory, Action, parsePath } from 'history';
13
14function invariant(cond, message) {
15 if (!cond) throw new Error(message);
16}
17
18function warning(cond, message) {
19 if (!cond) {
20 // eslint-disable-next-line no-console
21 if (typeof console !== "undefined") console.warn(message);
22
23 try {
24 // Welcome to debugging React Router!
25 //
26 // This error is thrown as a convenience so you can more easily
27 // find the source for a warning that appears in the console by
28 // enabling "pause on exceptions" in your JavaScript debugger.
29 throw new Error(message); // eslint-disable-next-line no-empty
30 } catch (e) {}
31 }
32}
33
34const alreadyWarned = {};
35
36function warningOnce(key, cond, message) {
37 if (!cond && !alreadyWarned[key]) {
38 alreadyWarned[key] = true;
39 process.env.NODE_ENV !== "production" ? warning(false, message) : void 0;
40 }
41} ///////////////////////////////////////////////////////////////////////////////
42// CONTEXT
43///////////////////////////////////////////////////////////////////////////////
44
45/**
46 * A Navigator is a "location changer"; it's how you get to different locations.
47 *
48 * Every history instance conforms to the Navigator interface, but the
49 * distinction is useful primarily when it comes to the low-level <Router> API
50 * where both the location and a navigator must be provided separately in order
51 * to avoid "tearing" that may occur in a suspense-enabled app if the action
52 * and/or location were to be read directly from the history instance.
53 */
54
55
56const NavigationContext = /*#__PURE__*/createContext(null);
57
58if (process.env.NODE_ENV !== "production") {
59 NavigationContext.displayName = "Navigation";
60}
61
62const LocationContext = /*#__PURE__*/createContext(null);
63
64if (process.env.NODE_ENV !== "production") {
65 LocationContext.displayName = "Location";
66}
67
68const RouteContext = /*#__PURE__*/createContext({
69 outlet: null,
70 matches: []
71});
72
73if (process.env.NODE_ENV !== "production") {
74 RouteContext.displayName = "Route";
75} ///////////////////////////////////////////////////////////////////////////////
76// COMPONENTS
77///////////////////////////////////////////////////////////////////////////////
78
79
80/**
81 * A <Router> that stores all entries in memory.
82 *
83 * @see https://reactrouter.com/docs/en/v6/api#memoryrouter
84 */
85function MemoryRouter(_ref) {
86 let {
87 basename,
88 children,
89 initialEntries,
90 initialIndex
91 } = _ref;
92 let historyRef = useRef();
93
94 if (historyRef.current == null) {
95 historyRef.current = createMemoryHistory({
96 initialEntries,
97 initialIndex
98 });
99 }
100
101 let history = historyRef.current;
102 let [state, setState] = useState({
103 action: history.action,
104 location: history.location
105 });
106 useLayoutEffect(() => history.listen(setState), [history]);
107 return /*#__PURE__*/createElement(Router, {
108 basename: basename,
109 children: children,
110 location: state.location,
111 navigationType: state.action,
112 navigator: history
113 });
114}
115
116/**
117 * Changes the current location.
118 *
119 * Note: This API is mostly useful in React.Component subclasses that are not
120 * able to use hooks. In functional components, we recommend you use the
121 * `useNavigate` hook instead.
122 *
123 * @see https://reactrouter.com/docs/en/v6/api#navigate
124 */
125function Navigate(_ref2) {
126 let {
127 to,
128 replace,
129 state
130 } = _ref2;
131 !useInRouterContext() ? process.env.NODE_ENV !== "production" ? invariant(false, // TODO: This error is probably because they somehow have 2 versions of
132 // the router loaded. We can help them understand how to avoid that.
133 "<Navigate> may be used only in the context of a <Router> component.") : invariant(false) : void 0;
134 process.env.NODE_ENV !== "production" ? 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.") : void 0;
135 let navigate = useNavigate();
136 useEffect(() => {
137 navigate(to, {
138 replace,
139 state
140 });
141 });
142 return null;
143}
144
145/**
146 * Renders the child route's element, if there is one.
147 *
148 * @see https://reactrouter.com/docs/en/v6/api#outlet
149 */
150function Outlet(_props) {
151 return useOutlet();
152}
153
154/**
155 * Declares an element that should be rendered at a certain URL path.
156 *
157 * @see https://reactrouter.com/docs/en/v6/api#route
158 */
159function Route(_props) {
160 process.env.NODE_ENV !== "production" ? 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>.") : invariant(false) ;
161}
162
163/**
164 * Provides location context for the rest of the app.
165 *
166 * Note: You usually won't render a <Router> directly. Instead, you'll render a
167 * router that is more specific to your environment such as a <BrowserRouter>
168 * in web browsers or a <StaticRouter> for server rendering.
169 *
170 * @see https://reactrouter.com/docs/en/v6/api#router
171 */
172function Router(_ref3) {
173 let {
174 basename: basenameProp = "/",
175 children = null,
176 location: locationProp,
177 navigationType = Action.Pop,
178 navigator,
179 static: staticProp = false
180 } = _ref3;
181 !!useInRouterContext() ? process.env.NODE_ENV !== "production" ? invariant(false, "You cannot render a <Router> inside another <Router>." + " You should never have more than one in your app.") : invariant(false) : void 0;
182 let basename = normalizePathname(basenameProp);
183 let navigationContext = useMemo(() => ({
184 basename,
185 navigator,
186 static: staticProp
187 }), [basename, navigator, staticProp]);
188
189 if (typeof locationProp === "string") {
190 locationProp = parsePath(locationProp);
191 }
192
193 let {
194 pathname = "/",
195 search = "",
196 hash = "",
197 state = null,
198 key = "default"
199 } = locationProp;
200 let location = useMemo(() => {
201 let trailingPathname = stripBasename(pathname, basename);
202
203 if (trailingPathname == null) {
204 return null;
205 }
206
207 return {
208 pathname: trailingPathname,
209 search,
210 hash,
211 state,
212 key
213 };
214 }, [basename, pathname, search, hash, state, key]);
215 process.env.NODE_ENV !== "production" ? 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.") : void 0;
216
217 if (location == null) {
218 return null;
219 }
220
221 return /*#__PURE__*/createElement(NavigationContext.Provider, {
222 value: navigationContext
223 }, /*#__PURE__*/createElement(LocationContext.Provider, {
224 children: children,
225 value: {
226 location,
227 navigationType
228 }
229 }));
230}
231
232/**
233 * A container for a nested tree of <Route> elements that renders the branch
234 * that best matches the current location.
235 *
236 * @see https://reactrouter.com/docs/en/v6/api#routes
237 */
238function Routes(_ref4) {
239 let {
240 children,
241 location
242 } = _ref4;
243 return useRoutes(createRoutesFromChildren(children), location);
244} ///////////////////////////////////////////////////////////////////////////////
245// HOOKS
246///////////////////////////////////////////////////////////////////////////////
247
248/**
249 * Returns the full href for the given "to" value. This is useful for building
250 * custom links that are also accessible and preserve right-click behavior.
251 *
252 * @see https://reactrouter.com/docs/en/v6/api#usehref
253 */
254
255function useHref(to) {
256 !useInRouterContext() ? process.env.NODE_ENV !== "production" ? invariant(false, // TODO: This error is probably because they somehow have 2 versions of the
257 // router loaded. We can help them understand how to avoid that.
258 "useHref() may be used only in the context of a <Router> component.") : invariant(false) : void 0;
259 let {
260 basename,
261 navigator
262 } = useContext(NavigationContext);
263 let {
264 hash,
265 pathname,
266 search
267 } = useResolvedPath(to);
268 let joinedPathname = pathname;
269
270 if (basename !== "/") {
271 let toPathname = getToPathname(to);
272 let endsWithSlash = toPathname != null && toPathname.endsWith("/");
273 joinedPathname = pathname === "/" ? basename + (endsWithSlash ? "/" : "") : joinPaths([basename, pathname]);
274 }
275
276 return navigator.createHref({
277 pathname: joinedPathname,
278 search,
279 hash
280 });
281}
282/**
283 * Returns true if this component is a descendant of a <Router>.
284 *
285 * @see https://reactrouter.com/docs/en/v6/api#useinroutercontext
286 */
287
288function useInRouterContext() {
289 return useContext(LocationContext) != null;
290}
291/**
292 * Returns the current location object, which represents the current URL in web
293 * browsers.
294 *
295 * Note: If you're using this it may mean you're doing some of your own
296 * "routing" in your app, and we'd like to know what your use case is. We may
297 * be able to provide something higher-level to better suit your needs.
298 *
299 * @see https://reactrouter.com/docs/en/v6/api#uselocation
300 */
301
302function useLocation() {
303 !useInRouterContext() ? process.env.NODE_ENV !== "production" ? invariant(false, // TODO: This error is probably because they somehow have 2 versions of the
304 // router loaded. We can help them understand how to avoid that.
305 "useLocation() may be used only in the context of a <Router> component.") : invariant(false) : void 0;
306 return useContext(LocationContext).location;
307}
308/**
309 * Returns the current navigation action which describes how the router came to
310 * the current location, either by a pop, push, or replace on the history stack.
311 *
312 * @see https://reactrouter.com/docs/en/v6/api#usenavigationtype
313 */
314
315function useNavigationType() {
316 return useContext(LocationContext).navigationType;
317}
318/**
319 * Returns true if the URL for the given "to" value matches the current URL.
320 * This is useful for components that need to know "active" state, e.g.
321 * <NavLink>.
322 *
323 * @see https://reactrouter.com/docs/en/v6/api#usematch
324 */
325
326function useMatch(pattern) {
327 !useInRouterContext() ? process.env.NODE_ENV !== "production" ? invariant(false, // TODO: This error is probably because they somehow have 2 versions of the
328 // router loaded. We can help them understand how to avoid that.
329 "useMatch() may be used only in the context of a <Router> component.") : invariant(false) : void 0;
330 return matchPath(pattern, useLocation().pathname);
331}
332/**
333 * The interface for the navigate() function returned from useNavigate().
334 */
335
336/**
337 * Returns an imperative method for changing the location. Used by <Link>s, but
338 * may also be used by other elements to change the location.
339 *
340 * @see https://reactrouter.com/docs/en/v6/api#usenavigate
341 */
342function useNavigate() {
343 !useInRouterContext() ? process.env.NODE_ENV !== "production" ? invariant(false, // TODO: This error is probably because they somehow have 2 versions of the
344 // router loaded. We can help them understand how to avoid that.
345 "useNavigate() may be used only in the context of a <Router> component.") : invariant(false) : void 0;
346 let {
347 basename,
348 navigator
349 } = useContext(NavigationContext);
350 let {
351 matches
352 } = useContext(RouteContext);
353 let {
354 pathname: locationPathname
355 } = useLocation();
356 let routePathnamesJson = JSON.stringify(matches.map(match => match.pathnameBase));
357 let activeRef = useRef(false);
358 useEffect(() => {
359 activeRef.current = true;
360 });
361 let navigate = useCallback(function (to, options) {
362 if (options === void 0) {
363 options = {};
364 }
365
366 process.env.NODE_ENV !== "production" ? warning(activeRef.current, "You should call navigate() in a React.useEffect(), not when " + "your component is first rendered.") : void 0;
367 if (!activeRef.current) return;
368
369 if (typeof to === "number") {
370 navigator.go(to);
371 return;
372 }
373
374 let path = resolveTo(to, JSON.parse(routePathnamesJson), locationPathname);
375
376 if (basename !== "/") {
377 path.pathname = joinPaths([basename, path.pathname]);
378 }
379
380 (!!options.replace ? navigator.replace : navigator.push)(path, options.state);
381 }, [basename, navigator, routePathnamesJson, locationPathname]);
382 return navigate;
383}
384/**
385 * Returns the element for the child route at this level of the route
386 * hierarchy. Used internally by <Outlet> to render child routes.
387 *
388 * @see https://reactrouter.com/docs/en/v6/api#useoutlet
389 */
390
391function useOutlet() {
392 return useContext(RouteContext).outlet;
393}
394/**
395 * Returns an object of key/value pairs of the dynamic params from the current
396 * URL that were matched by the route path.
397 *
398 * @see https://reactrouter.com/docs/en/v6/api#useparams
399 */
400
401function useParams() {
402 let {
403 matches
404 } = useContext(RouteContext);
405 let routeMatch = matches[matches.length - 1];
406 return routeMatch ? routeMatch.params : {};
407}
408/**
409 * Resolves the pathname of the given `to` value against the current location.
410 *
411 * @see https://reactrouter.com/docs/en/v6/api#useresolvedpath
412 */
413
414function useResolvedPath(to) {
415 let {
416 matches
417 } = useContext(RouteContext);
418 let {
419 pathname: locationPathname
420 } = useLocation();
421 let routePathnamesJson = JSON.stringify(matches.map(match => match.pathnameBase));
422 return useMemo(() => resolveTo(to, JSON.parse(routePathnamesJson), locationPathname), [to, routePathnamesJson, locationPathname]);
423}
424/**
425 * Returns the element of the route that matched the current location, prepared
426 * with the correct context to render the remainder of the route tree. Route
427 * elements in the tree must render an <Outlet> to render their child route's
428 * element.
429 *
430 * @see https://reactrouter.com/docs/en/v6/api#useroutes
431 */
432
433function useRoutes(routes, locationArg) {
434 !useInRouterContext() ? process.env.NODE_ENV !== "production" ? invariant(false, // TODO: This error is probably because they somehow have 2 versions of the
435 // router loaded. We can help them understand how to avoid that.
436 "useRoutes() may be used only in the context of a <Router> component.") : invariant(false) : void 0;
437 let {
438 matches: parentMatches
439 } = useContext(RouteContext);
440 let routeMatch = parentMatches[parentMatches.length - 1];
441 let parentParams = routeMatch ? routeMatch.params : {};
442 let parentPathname = routeMatch ? routeMatch.pathname : "/";
443 let parentPathnameBase = routeMatch ? routeMatch.pathnameBase : "/";
444 let parentRoute = routeMatch && routeMatch.route;
445
446 if (process.env.NODE_ENV !== "production") {
447 // You won't get a warning about 2 different <Routes> under a <Route>
448 // without a trailing *, but this is a best-effort warning anyway since we
449 // cannot even give the warning unless they land at the parent route.
450 //
451 // Example:
452 //
453 // <Routes>
454 // {/* This route path MUST end with /* because otherwise
455 // it will never match /blog/post/123 */}
456 // <Route path="blog" element={<Blog />} />
457 // <Route path="blog/feed" element={<BlogFeed />} />
458 // </Routes>
459 //
460 // function Blog() {
461 // return (
462 // <Routes>
463 // <Route path="post/:id" element={<Post />} />
464 // </Routes>
465 // );
466 // }
467 let parentPath = parentRoute && parentRoute.path || "";
468 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 + "/*\">."));
469 }
470
471 let locationFromContext = useLocation();
472 let location;
473
474 if (locationArg) {
475 var _parsedLocationArg$pa;
476
477 let parsedLocationArg = typeof locationArg === "string" ? parsePath(locationArg) : locationArg;
478 !(parentPathnameBase === "/" || ((_parsedLocationArg$pa = parsedLocationArg.pathname) == null ? void 0 : _parsedLocationArg$pa.startsWith(parentPathnameBase))) ? process.env.NODE_ENV !== "production" ? 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.")) : invariant(false) : void 0;
479 location = parsedLocationArg;
480 } else {
481 location = locationFromContext;
482 }
483
484 let pathname = location.pathname || "/";
485 let remainingPathname = parentPathnameBase === "/" ? pathname : pathname.slice(parentPathnameBase.length) || "/";
486 let matches = matchRoutes(routes, {
487 pathname: remainingPathname
488 });
489
490 if (process.env.NODE_ENV !== "production") {
491 process.env.NODE_ENV !== "production" ? warning(parentRoute || matches != null, "No routes matched location \"" + location.pathname + location.search + location.hash + "\" ") : void 0;
492 process.env.NODE_ENV !== "production" ? 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.") : void 0;
493 }
494
495 return _renderMatches(matches && matches.map(match => Object.assign({}, match, {
496 params: Object.assign({}, parentParams, match.params),
497 pathname: joinPaths([parentPathnameBase, match.pathname]),
498 pathnameBase: match.pathnameBase === "/" ? parentPathnameBase : joinPaths([parentPathnameBase, match.pathnameBase])
499 })), parentMatches);
500} ///////////////////////////////////////////////////////////////////////////////
501// UTILS
502///////////////////////////////////////////////////////////////////////////////
503
504/**
505 * Creates a route config from a React "children" object, which is usually
506 * either a `<Route>` element or an array of them. Used internally by
507 * `<Routes>` to create a route config from its children.
508 *
509 * @see https://reactrouter.com/docs/en/v6/api#createroutesfromchildren
510 */
511
512function createRoutesFromChildren(children) {
513 let routes = [];
514 Children.forEach(children, element => {
515 if (! /*#__PURE__*/isValidElement(element)) {
516 // Ignore non-elements. This allows people to more easily inline
517 // conditionals in their route config.
518 return;
519 }
520
521 if (element.type === Fragment) {
522 // Transparently support React.Fragment and its children.
523 routes.push.apply(routes, createRoutesFromChildren(element.props.children));
524 return;
525 }
526
527 !(element.type === Route) ? process.env.NODE_ENV !== "production" ? 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>") : invariant(false) : void 0;
528 let route = {
529 caseSensitive: element.props.caseSensitive,
530 element: element.props.element,
531 index: element.props.index,
532 path: element.props.path
533 };
534
535 if (element.props.children) {
536 route.children = createRoutesFromChildren(element.props.children);
537 }
538
539 routes.push(route);
540 });
541 return routes;
542}
543/**
544 * The parameters that were parsed from the URL path.
545 */
546
547/**
548 * Returns a path with params interpolated.
549 *
550 * @see https://reactrouter.com/docs/en/v6/api#generatepath
551 */
552function generatePath(path, params) {
553 if (params === void 0) {
554 params = {};
555 }
556
557 return path.replace(/:(\w+)/g, (_, key) => {
558 !(params[key] != null) ? process.env.NODE_ENV !== "production" ? invariant(false, "Missing \":" + key + "\" param") : invariant(false) : void 0;
559 return params[key];
560 }).replace(/\/*\*$/, _ => params["*"] == null ? "" : params["*"].replace(/^\/*/, "/"));
561}
562/**
563 * A RouteMatch contains info about how a route matched a URL.
564 */
565
566/**
567 * Matches the given routes to a location and returns the match data.
568 *
569 * @see https://reactrouter.com/docs/en/v6/api#matchroutes
570 */
571function matchRoutes(routes, locationArg, basename) {
572 if (basename === void 0) {
573 basename = "/";
574 }
575
576 let location = typeof locationArg === "string" ? parsePath(locationArg) : locationArg;
577 let pathname = stripBasename(location.pathname || "/", basename);
578
579 if (pathname == null) {
580 return null;
581 }
582
583 let branches = flattenRoutes(routes);
584 rankRouteBranches(branches);
585 let matches = null;
586
587 for (let i = 0; matches == null && i < branches.length; ++i) {
588 matches = matchRouteBranch(branches[i], routes, pathname);
589 }
590
591 return matches;
592}
593
594function flattenRoutes(routes, branches, parentsMeta, parentPath) {
595 if (branches === void 0) {
596 branches = [];
597 }
598
599 if (parentsMeta === void 0) {
600 parentsMeta = [];
601 }
602
603 if (parentPath === void 0) {
604 parentPath = "";
605 }
606
607 routes.forEach((route, index) => {
608 let meta = {
609 relativePath: route.path || "",
610 caseSensitive: route.caseSensitive === true,
611 childrenIndex: index
612 };
613
614 if (meta.relativePath.startsWith("/")) {
615 !meta.relativePath.startsWith(parentPath) ? process.env.NODE_ENV !== "production" ? 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.") : invariant(false) : void 0;
616 meta.relativePath = meta.relativePath.slice(parentPath.length);
617 }
618
619 let path = joinPaths([parentPath, meta.relativePath]);
620 let routesMeta = parentsMeta.concat(meta); // Add the children before adding this route to the array so we traverse the
621 // route tree depth-first and child routes appear before their parents in
622 // the "flattened" version.
623
624 if (route.children && route.children.length > 0) {
625 !(route.index !== true) ? process.env.NODE_ENV !== "production" ? invariant(false, "Index routes must not have child routes. Please remove " + ("all child routes from route path \"" + path + "\".")) : invariant(false) : void 0;
626 flattenRoutes(route.children, branches, routesMeta, path);
627 } // Routes without a path shouldn't ever match by themselves unless they are
628 // index routes, so don't add them to the list of possible branches.
629
630
631 if (route.path == null && !route.index) {
632 return;
633 }
634
635 branches.push({
636 path,
637 score: computeScore(path, route.index),
638 routesMeta
639 });
640 });
641 return branches;
642}
643
644function rankRouteBranches(branches) {
645 branches.sort((a, b) => a.score !== b.score ? b.score - a.score // Higher score first
646 : compareIndexes(a.routesMeta.map(meta => meta.childrenIndex), b.routesMeta.map(meta => meta.childrenIndex)));
647}
648
649const paramRe = /^:\w+$/;
650const dynamicSegmentValue = 3;
651const indexRouteValue = 2;
652const emptySegmentValue = 1;
653const staticSegmentValue = 10;
654const splatPenalty = -2;
655
656const isSplat = s => s === "*";
657
658function computeScore(path, index) {
659 let segments = path.split("/");
660 let initialScore = segments.length;
661
662 if (segments.some(isSplat)) {
663 initialScore += splatPenalty;
664 }
665
666 if (index) {
667 initialScore += indexRouteValue;
668 }
669
670 return segments.filter(s => !isSplat(s)).reduce((score, segment) => score + (paramRe.test(segment) ? dynamicSegmentValue : segment === "" ? emptySegmentValue : staticSegmentValue), initialScore);
671}
672
673function compareIndexes(a, b) {
674 let siblings = a.length === b.length && a.slice(0, -1).every((n, i) => n === b[i]);
675 return siblings ? // If two routes are siblings, we should try to match the earlier sibling
676 // first. This allows people to have fine-grained control over the matching
677 // behavior by simply putting routes with identical paths in the order they
678 // want them tried.
679 a[a.length - 1] - b[b.length - 1] : // Otherwise, it doesn't really make sense to rank non-siblings by index,
680 // so they sort equally.
681 0;
682}
683
684function matchRouteBranch(branch, // TODO: attach original route object inside routesMeta so we don't need this arg
685routesArg, pathname) {
686 let routes = routesArg;
687 let {
688 routesMeta
689 } = branch;
690 let matchedParams = {};
691 let matchedPathname = "/";
692 let matches = [];
693
694 for (let i = 0; i < routesMeta.length; ++i) {
695 let meta = routesMeta[i];
696 let end = i === routesMeta.length - 1;
697 let remainingPathname = matchedPathname === "/" ? pathname : pathname.slice(matchedPathname.length) || "/";
698 let match = matchPath({
699 path: meta.relativePath,
700 caseSensitive: meta.caseSensitive,
701 end
702 }, remainingPathname);
703 if (!match) return null;
704 Object.assign(matchedParams, match.params);
705 let route = routes[meta.childrenIndex];
706 matches.push({
707 params: matchedParams,
708 pathname: joinPaths([matchedPathname, match.pathname]),
709 pathnameBase: joinPaths([matchedPathname, match.pathnameBase]),
710 route
711 });
712
713 if (match.pathnameBase !== "/") {
714 matchedPathname = joinPaths([matchedPathname, match.pathnameBase]);
715 }
716
717 routes = route.children;
718 }
719
720 return matches;
721}
722/**
723 * Renders the result of `matchRoutes()` into a React element.
724 */
725
726
727function renderMatches(matches) {
728 return _renderMatches(matches);
729}
730
731function _renderMatches(matches, parentMatches) {
732 if (parentMatches === void 0) {
733 parentMatches = [];
734 }
735
736 if (matches == null) return null;
737 return matches.reduceRight((outlet, match, index) => {
738 return /*#__PURE__*/createElement(RouteContext.Provider, {
739 children: match.route.element !== undefined ? match.route.element : /*#__PURE__*/createElement(Outlet, null),
740 value: {
741 outlet,
742 matches: parentMatches.concat(matches.slice(0, index + 1))
743 }
744 });
745 }, null);
746}
747/**
748 * A PathPattern is used to match on some portion of a URL pathname.
749 */
750
751
752/**
753 * Performs pattern matching on a URL pathname and returns information about
754 * the match.
755 *
756 * @see https://reactrouter.com/docs/en/v6/api#matchpath
757 */
758function matchPath(pattern, pathname) {
759 if (typeof pattern === "string") {
760 pattern = {
761 path: pattern,
762 caseSensitive: false,
763 end: true
764 };
765 }
766
767 let [matcher, paramNames] = compilePath(pattern.path, pattern.caseSensitive, pattern.end);
768 let match = pathname.match(matcher);
769 if (!match) return null;
770 let matchedPathname = match[0];
771 let pathnameBase = matchedPathname.replace(/(.)\/+$/, "$1");
772 let captureGroups = match.slice(1);
773 let params = paramNames.reduce((memo, paramName, index) => {
774 // We need to compute the pathnameBase here using the raw splat value
775 // instead of using params["*"] later because it will be decoded then
776 if (paramName === "*") {
777 let splatValue = captureGroups[index] || "";
778 pathnameBase = matchedPathname.slice(0, matchedPathname.length - splatValue.length).replace(/(.)\/+$/, "$1");
779 }
780
781 memo[paramName] = safelyDecodeURIComponent(captureGroups[index] || "", paramName);
782 return memo;
783 }, {});
784 return {
785 params,
786 pathname: matchedPathname,
787 pathnameBase,
788 pattern
789 };
790}
791
792function compilePath(path, caseSensitive, end) {
793 if (caseSensitive === void 0) {
794 caseSensitive = false;
795 }
796
797 if (end === void 0) {
798 end = true;
799 }
800
801 process.env.NODE_ENV !== "production" ? 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(/\*$/, "/*") + "\".")) : void 0;
802 let paramNames = [];
803 let regexpSource = "^" + path.replace(/\/*\*?$/, "") // Ignore trailing / and /*, we'll handle it below
804 .replace(/^\/*/, "/") // Make sure it has a leading /
805 .replace(/[\\.*+^$?{}|()[\]]/g, "\\$&") // Escape special regex chars
806 .replace(/:(\w+)/g, (_, paramName) => {
807 paramNames.push(paramName);
808 return "([^\\/]+)";
809 });
810
811 if (path.endsWith("*")) {
812 paramNames.push("*");
813 regexpSource += path === "*" || path === "/*" ? "(.*)$" // Already matched the initial /, just match the rest
814 : "(?:\\/(.+)|\\/*)$"; // Don't include the / in params["*"]
815 } else {
816 regexpSource += end ? "\\/*$" // When matching to the end, ignore trailing slashes
817 : // Otherwise, at least match a word boundary. This restricts parent
818 // routes to matching only their own words and nothing more, e.g. parent
819 // route "/home" should not match "/home2".
820 "(?:\\b|$)";
821 }
822
823 let matcher = new RegExp(regexpSource, caseSensitive ? undefined : "i");
824 return [matcher, paramNames];
825}
826
827function safelyDecodeURIComponent(value, paramName) {
828 try {
829 return decodeURIComponent(value);
830 } catch (error) {
831 process.env.NODE_ENV !== "production" ? 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 + ").")) : void 0;
832 return value;
833 }
834}
835/**
836 * Returns a resolved path object relative to the given pathname.
837 *
838 * @see https://reactrouter.com/docs/en/v6/api#resolvepath
839 */
840
841
842function resolvePath(to, fromPathname) {
843 if (fromPathname === void 0) {
844 fromPathname = "/";
845 }
846
847 let {
848 pathname: toPathname,
849 search = "",
850 hash = ""
851 } = typeof to === "string" ? parsePath(to) : to;
852 let pathname = toPathname ? toPathname.startsWith("/") ? toPathname : resolvePathname(toPathname, fromPathname) : fromPathname;
853 return {
854 pathname,
855 search: normalizeSearch(search),
856 hash: normalizeHash(hash)
857 };
858}
859
860function resolvePathname(relativePath, fromPathname) {
861 let segments = fromPathname.replace(/\/+$/, "").split("/");
862 let relativeSegments = relativePath.split("/");
863 relativeSegments.forEach(segment => {
864 if (segment === "..") {
865 // Keep the root "" segment so the pathname starts at /
866 if (segments.length > 1) segments.pop();
867 } else if (segment !== ".") {
868 segments.push(segment);
869 }
870 });
871 return segments.length > 1 ? segments.join("/") : "/";
872}
873
874function resolveTo(toArg, routePathnames, locationPathname) {
875 let to = typeof toArg === "string" ? parsePath(toArg) : toArg;
876 let toPathname = toArg === "" || to.pathname === "" ? "/" : to.pathname; // If a pathname is explicitly provided in `to`, it should be relative to the
877 // route context. This is explained in `Note on `<Link to>` values` in our
878 // migration guide from v5 as a means of disambiguation between `to` values
879 // that begin with `/` and those that do not. However, this is problematic for
880 // `to` values that do not provide a pathname. `to` can simply be a search or
881 // hash string, in which case we should assume that the navigation is relative
882 // to the current location's pathname and *not* the route pathname.
883
884 let from;
885
886 if (toPathname == null) {
887 from = locationPathname;
888 } else {
889 let routePathnameIndex = routePathnames.length - 1;
890
891 if (toPathname.startsWith("..")) {
892 let toSegments = toPathname.split("/"); // Each leading .. segment means "go up one route" instead of "go up one
893 // URL segment". This is a key difference from how <a href> works and a
894 // major reason we call this a "to" value instead of a "href".
895
896 while (toSegments[0] === "..") {
897 toSegments.shift();
898 routePathnameIndex -= 1;
899 }
900
901 to.pathname = toSegments.join("/");
902 } // If there are more ".." segments than parent routes, resolve relative to
903 // the root / URL.
904
905
906 from = routePathnameIndex >= 0 ? routePathnames[routePathnameIndex] : "/";
907 }
908
909 let path = resolvePath(to, from); // Ensure the pathname has a trailing slash if the original to value had one.
910
911 if (toPathname && toPathname !== "/" && toPathname.endsWith("/") && !path.pathname.endsWith("/")) {
912 path.pathname += "/";
913 }
914
915 return path;
916}
917
918function getToPathname(to) {
919 // Empty strings should be treated the same as / paths
920 return to === "" || to.pathname === "" ? "/" : typeof to === "string" ? parsePath(to).pathname : to.pathname;
921}
922
923function stripBasename(pathname, basename) {
924 if (basename === "/") return pathname;
925
926 if (!pathname.toLowerCase().startsWith(basename.toLowerCase())) {
927 return null;
928 }
929
930 let nextChar = pathname.charAt(basename.length);
931
932 if (nextChar && nextChar !== "/") {
933 // pathname does not start with basename/
934 return null;
935 }
936
937 return pathname.slice(basename.length) || "/";
938}
939
940const joinPaths = paths => paths.join("/").replace(/\/\/+/g, "/");
941
942const normalizePathname = pathname => pathname.replace(/\/+$/, "").replace(/^\/*/, "/");
943
944const normalizeSearch = search => !search || search === "?" ? "" : search.startsWith("?") ? search : "?" + search;
945
946const normalizeHash = hash => !hash || hash === "#" ? "" : hash.startsWith("#") ? hash : "#" + hash; ///////////////////////////////////////////////////////////////////////////////
947
948export { 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, useParams, useResolvedPath, useRoutes };
949//# sourceMappingURL=index.js.map