UNPKG

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