react-router 6.2.2 → 6.4.0-pre.10

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