react-router 6.2.2 → 6.3.0

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,5 +1,5 @@
1
1
  /**
2
- * React Router v6.2.2
2
+ * React Router v6.3.0
3
3
  *
4
4
  * Copyright (c) Remix Software Inc.
5
5
  *
@@ -8,14 +8,34 @@
8
8
  *
9
9
  * @license MIT
10
10
  */
11
- import { createContext, useRef, useState, useLayoutEffect, createElement, useContext, useEffect, useMemo, useCallback, Children, isValidElement, Fragment } from 'react';
12
- import { createMemoryHistory, Action, parsePath } from 'history';
11
+ import { parsePath, createMemoryHistory, Action } from 'history';
13
12
  export { Action as NavigationType, createPath, parsePath } from 'history';
13
+ import { createContext, useContext, useMemo, useRef, useEffect, useCallback, createElement, useState, useLayoutEffect, Children, isValidElement, Fragment } from 'react';
14
+
15
+ const NavigationContext = /*#__PURE__*/createContext(null);
16
+
17
+ {
18
+ NavigationContext.displayName = "Navigation";
19
+ }
20
+
21
+ const LocationContext = /*#__PURE__*/createContext(null);
22
+
23
+ {
24
+ LocationContext.displayName = "Location";
25
+ }
26
+
27
+ const RouteContext = /*#__PURE__*/createContext({
28
+ outlet: null,
29
+ matches: []
30
+ });
31
+
32
+ {
33
+ RouteContext.displayName = "Route";
34
+ }
14
35
 
15
36
  function invariant(cond, message) {
16
37
  if (!cond) throw new Error(message);
17
38
  }
18
-
19
39
  function warning(cond, message) {
20
40
  if (!cond) {
21
41
  // eslint-disable-next-line no-console
@@ -31,216 +51,353 @@ function warning(cond, message) {
31
51
  } catch (e) {}
32
52
  }
33
53
  }
34
-
35
54
  const alreadyWarned = {};
36
-
37
55
  function warningOnce(key, cond, message) {
38
56
  if (!cond && !alreadyWarned[key]) {
39
57
  alreadyWarned[key] = true;
40
58
  warning(false, message) ;
41
59
  }
42
- } ///////////////////////////////////////////////////////////////////////////////
43
- // CONTEXT
44
- ///////////////////////////////////////////////////////////////////////////////
60
+ }
45
61
 
46
62
  /**
47
- * A Navigator is a "location changer"; it's how you get to different locations.
63
+ * Returns a path with params interpolated.
48
64
  *
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.
65
+ * @see https://reactrouter.com/docs/en/v6/api#generatepath
66
+ */
67
+ function generatePath(path, params = {}) {
68
+ return path.replace(/:(\w+)/g, (_, key) => {
69
+ !(params[key] != null) ? invariant(false, `Missing ":${key}" param`) : void 0;
70
+ return params[key];
71
+ }).replace(/\/*\*$/, _ => params["*"] == null ? "" : params["*"].replace(/^\/*/, "/"));
72
+ }
73
+ /**
74
+ * A RouteMatch contains info about how a route matched a URL.
54
75
  */
55
76
 
77
+ /**
78
+ * Matches the given routes to a location and returns the match data.
79
+ *
80
+ * @see https://reactrouter.com/docs/en/v6/api#matchroutes
81
+ */
82
+ function matchRoutes(routes, locationArg, basename = "/") {
83
+ let location = typeof locationArg === "string" ? parsePath(locationArg) : locationArg;
84
+ let pathname = stripBasename(location.pathname || "/", basename);
56
85
 
57
- const NavigationContext = /*#__PURE__*/createContext(null);
86
+ if (pathname == null) {
87
+ return null;
88
+ }
58
89
 
59
- {
60
- NavigationContext.displayName = "Navigation";
61
- }
90
+ let branches = flattenRoutes(routes);
91
+ rankRouteBranches(branches);
92
+ let matches = null;
62
93
 
63
- const LocationContext = /*#__PURE__*/createContext(null);
94
+ for (let i = 0; matches == null && i < branches.length; ++i) {
95
+ matches = matchRouteBranch(branches[i], pathname);
96
+ }
64
97
 
65
- {
66
- LocationContext.displayName = "Location";
98
+ return matches;
67
99
  }
68
100
 
69
- const RouteContext = /*#__PURE__*/createContext({
70
- outlet: null,
71
- matches: []
72
- });
101
+ function flattenRoutes(routes, branches = [], parentsMeta = [], parentPath = "") {
102
+ routes.forEach((route, index) => {
103
+ let meta = {
104
+ relativePath: route.path || "",
105
+ caseSensitive: route.caseSensitive === true,
106
+ childrenIndex: index,
107
+ route
108
+ };
73
109
 
74
- {
75
- RouteContext.displayName = "Route";
76
- } ///////////////////////////////////////////////////////////////////////////////
77
- // COMPONENTS
78
- ///////////////////////////////////////////////////////////////////////////////
110
+ if (meta.relativePath.startsWith("/")) {
111
+ !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;
112
+ meta.relativePath = meta.relativePath.slice(parentPath.length);
113
+ }
79
114
 
115
+ let path = joinPaths([parentPath, meta.relativePath]);
116
+ let routesMeta = parentsMeta.concat(meta); // Add the children before adding this route to the array so we traverse the
117
+ // route tree depth-first and child routes appear before their parents in
118
+ // the "flattened" version.
80
119
 
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();
120
+ if (route.children && route.children.length > 0) {
121
+ !(route.index !== true) ? invariant(false, `Index routes must not have child routes. Please remove ` + `all child routes from route path "${path}".`) : void 0;
122
+ flattenRoutes(route.children, branches, routesMeta, path);
123
+ } // Routes without a path shouldn't ever match by themselves unless they are
124
+ // index routes, so don't add them to the list of possible branches.
93
125
 
94
- if (historyRef.current == null) {
95
- historyRef.current = createMemoryHistory({
96
- initialEntries,
97
- initialIndex
98
- });
99
- }
100
126
 
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
- }
127
+ if (route.path == null && !route.index) {
128
+ return;
129
+ }
115
130
 
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
131
+ branches.push({
132
+ path,
133
+ score: computeScore(path, route.index),
134
+ routesMeta
139
135
  });
140
136
  });
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);
137
+ return branches;
151
138
  }
152
139
 
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>.`) ;
140
+ function rankRouteBranches(branches) {
141
+ branches.sort((a, b) => a.score !== b.score ? b.score - a.score // Higher score first
142
+ : compareIndexes(a.routesMeta.map(meta => meta.childrenIndex), b.routesMeta.map(meta => meta.childrenIndex)));
160
143
  }
161
144
 
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
- }
145
+ const paramRe = /^:\w+$/;
146
+ const dynamicSegmentValue = 3;
147
+ const indexRouteValue = 2;
148
+ const emptySegmentValue = 1;
149
+ const staticSegmentValue = 10;
150
+ const splatPenalty = -2;
190
151
 
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);
152
+ const isSplat = s => s === "*";
200
153
 
201
- if (trailingPathname == null) {
202
- return null;
203
- }
154
+ function computeScore(path, index) {
155
+ let segments = path.split("/");
156
+ let initialScore = segments.length;
204
157
 
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.`) ;
158
+ if (segments.some(isSplat)) {
159
+ initialScore += splatPenalty;
160
+ }
214
161
 
215
- if (location == null) {
216
- return null;
162
+ if (index) {
163
+ initialScore += indexRouteValue;
217
164
  }
218
165
 
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
- }));
166
+ return segments.filter(s => !isSplat(s)).reduce((score, segment) => score + (paramRe.test(segment) ? dynamicSegmentValue : segment === "" ? emptySegmentValue : staticSegmentValue), initialScore);
228
167
  }
229
168
 
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
169
+ function compareIndexes(a, b) {
170
+ let siblings = a.length === b.length && a.slice(0, -1).every((n, i) => n === b[i]);
171
+ return siblings ? // If two routes are siblings, we should try to match the earlier sibling
172
+ // first. This allows people to have fine-grained control over the matching
173
+ // behavior by simply putting routes with identical paths in the order they
174
+ // want them tried.
175
+ a[a.length - 1] - b[b.length - 1] : // Otherwise, it doesn't really make sense to rank non-siblings by index,
176
+ // so they sort equally.
177
+ 0;
178
+ }
179
+
180
+ function matchRouteBranch(branch, pathname) {
181
+ let {
182
+ routesMeta
183
+ } = branch;
184
+ let matchedParams = {};
185
+ let matchedPathname = "/";
186
+ let matches = [];
187
+
188
+ for (let i = 0; i < routesMeta.length; ++i) {
189
+ let meta = routesMeta[i];
190
+ let end = i === routesMeta.length - 1;
191
+ let remainingPathname = matchedPathname === "/" ? pathname : pathname.slice(matchedPathname.length) || "/";
192
+ let match = matchPath({
193
+ path: meta.relativePath,
194
+ caseSensitive: meta.caseSensitive,
195
+ end
196
+ }, remainingPathname);
197
+ if (!match) return null;
198
+ Object.assign(matchedParams, match.params);
199
+ let route = meta.route;
200
+ matches.push({
201
+ params: matchedParams,
202
+ pathname: joinPaths([matchedPathname, match.pathname]),
203
+ pathnameBase: normalizePathname(joinPaths([matchedPathname, match.pathnameBase])),
204
+ route
205
+ });
206
+
207
+ if (match.pathnameBase !== "/") {
208
+ matchedPathname = joinPaths([matchedPathname, match.pathnameBase]);
209
+ }
210
+ }
211
+
212
+ return matches;
213
+ }
214
+ /**
215
+ * A PathPattern is used to match on some portion of a URL pathname.
235
216
  */
236
- function Routes({
237
- children,
238
- location
239
- }) {
240
- return useRoutes(createRoutesFromChildren(children), location);
241
- } ///////////////////////////////////////////////////////////////////////////////
242
- // HOOKS
243
- ///////////////////////////////////////////////////////////////////////////////
217
+
218
+
219
+ /**
220
+ * Performs pattern matching on a URL pathname and returns information about
221
+ * the match.
222
+ *
223
+ * @see https://reactrouter.com/docs/en/v6/api#matchpath
224
+ */
225
+ function matchPath(pattern, pathname) {
226
+ if (typeof pattern === "string") {
227
+ pattern = {
228
+ path: pattern,
229
+ caseSensitive: false,
230
+ end: true
231
+ };
232
+ }
233
+
234
+ let [matcher, paramNames] = compilePath(pattern.path, pattern.caseSensitive, pattern.end);
235
+ let match = pathname.match(matcher);
236
+ if (!match) return null;
237
+ let matchedPathname = match[0];
238
+ let pathnameBase = matchedPathname.replace(/(.)\/+$/, "$1");
239
+ let captureGroups = match.slice(1);
240
+ let params = paramNames.reduce((memo, paramName, index) => {
241
+ // We need to compute the pathnameBase here using the raw splat value
242
+ // instead of using params["*"] later because it will be decoded then
243
+ if (paramName === "*") {
244
+ let splatValue = captureGroups[index] || "";
245
+ pathnameBase = matchedPathname.slice(0, matchedPathname.length - splatValue.length).replace(/(.)\/+$/, "$1");
246
+ }
247
+
248
+ memo[paramName] = safelyDecodeURIComponent(captureGroups[index] || "", paramName);
249
+ return memo;
250
+ }, {});
251
+ return {
252
+ params,
253
+ pathname: matchedPathname,
254
+ pathnameBase,
255
+ pattern
256
+ };
257
+ }
258
+
259
+ function compilePath(path, caseSensitive = false, end = true) {
260
+ 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(/\*$/, "/*")}".`) ;
261
+ let paramNames = [];
262
+ let regexpSource = "^" + path.replace(/\/*\*?$/, "") // Ignore trailing / and /*, we'll handle it below
263
+ .replace(/^\/*/, "/") // Make sure it has a leading /
264
+ .replace(/[\\.*+^$?{}|()[\]]/g, "\\$&") // Escape special regex chars
265
+ .replace(/:(\w+)/g, (_, paramName) => {
266
+ paramNames.push(paramName);
267
+ return "([^\\/]+)";
268
+ });
269
+
270
+ if (path.endsWith("*")) {
271
+ paramNames.push("*");
272
+ regexpSource += path === "*" || path === "/*" ? "(.*)$" // Already matched the initial /, just match the rest
273
+ : "(?:\\/(.+)|\\/*)$"; // Don't include the / in params["*"]
274
+ } else {
275
+ regexpSource += end ? "\\/*$" // When matching to the end, ignore trailing slashes
276
+ : // Otherwise, match a word boundary or a proceeding /. The word boundary restricts
277
+ // parent routes to matching only their own words and nothing more, e.g. parent
278
+ // route "/home" should not match "/home2".
279
+ // Additionally, allow paths starting with `.`, `-`, `~`, and url-encoded entities,
280
+ // but do not consume the character in the matched path so they can match against
281
+ // nested paths.
282
+ "(?:(?=[.~-]|%[0-9A-F]{2})|\\b|\\/|$)";
283
+ }
284
+
285
+ let matcher = new RegExp(regexpSource, caseSensitive ? undefined : "i");
286
+ return [matcher, paramNames];
287
+ }
288
+
289
+ function safelyDecodeURIComponent(value, paramName) {
290
+ try {
291
+ return decodeURIComponent(value);
292
+ } catch (error) {
293
+ 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}).`) ;
294
+ return value;
295
+ }
296
+ }
297
+ /**
298
+ * Returns a resolved path object relative to the given pathname.
299
+ *
300
+ * @see https://reactrouter.com/docs/en/v6/api#resolvepath
301
+ */
302
+
303
+
304
+ function resolvePath(to, fromPathname = "/") {
305
+ let {
306
+ pathname: toPathname,
307
+ search = "",
308
+ hash = ""
309
+ } = typeof to === "string" ? parsePath(to) : to;
310
+ let pathname = toPathname ? toPathname.startsWith("/") ? toPathname : resolvePathname(toPathname, fromPathname) : fromPathname;
311
+ return {
312
+ pathname,
313
+ search: normalizeSearch(search),
314
+ hash: normalizeHash(hash)
315
+ };
316
+ }
317
+
318
+ function resolvePathname(relativePath, fromPathname) {
319
+ let segments = fromPathname.replace(/\/+$/, "").split("/");
320
+ let relativeSegments = relativePath.split("/");
321
+ relativeSegments.forEach(segment => {
322
+ if (segment === "..") {
323
+ // Keep the root "" segment so the pathname starts at /
324
+ if (segments.length > 1) segments.pop();
325
+ } else if (segment !== ".") {
326
+ segments.push(segment);
327
+ }
328
+ });
329
+ return segments.length > 1 ? segments.join("/") : "/";
330
+ }
331
+
332
+ function resolveTo(toArg, routePathnames, locationPathname) {
333
+ let to = typeof toArg === "string" ? parsePath(toArg) : toArg;
334
+ let toPathname = toArg === "" || to.pathname === "" ? "/" : to.pathname; // If a pathname is explicitly provided in `to`, it should be relative to the
335
+ // route context. This is explained in `Note on `<Link to>` values` in our
336
+ // migration guide from v5 as a means of disambiguation between `to` values
337
+ // that begin with `/` and those that do not. However, this is problematic for
338
+ // `to` values that do not provide a pathname. `to` can simply be a search or
339
+ // hash string, in which case we should assume that the navigation is relative
340
+ // to the current location's pathname and *not* the route pathname.
341
+
342
+ let from;
343
+
344
+ if (toPathname == null) {
345
+ from = locationPathname;
346
+ } else {
347
+ let routePathnameIndex = routePathnames.length - 1;
348
+
349
+ if (toPathname.startsWith("..")) {
350
+ let toSegments = toPathname.split("/"); // Each leading .. segment means "go up one route" instead of "go up one
351
+ // URL segment". This is a key difference from how <a href> works and a
352
+ // major reason we call this a "to" value instead of a "href".
353
+
354
+ while (toSegments[0] === "..") {
355
+ toSegments.shift();
356
+ routePathnameIndex -= 1;
357
+ }
358
+
359
+ to.pathname = toSegments.join("/");
360
+ } // If there are more ".." segments than parent routes, resolve relative to
361
+ // the root / URL.
362
+
363
+
364
+ from = routePathnameIndex >= 0 ? routePathnames[routePathnameIndex] : "/";
365
+ }
366
+
367
+ let path = resolvePath(to, from); // Ensure the pathname has a trailing slash if the original to value had one.
368
+
369
+ if (toPathname && toPathname !== "/" && toPathname.endsWith("/") && !path.pathname.endsWith("/")) {
370
+ path.pathname += "/";
371
+ }
372
+
373
+ return path;
374
+ }
375
+ function getToPathname(to) {
376
+ // Empty strings should be treated the same as / paths
377
+ return to === "" || to.pathname === "" ? "/" : typeof to === "string" ? parsePath(to).pathname : to.pathname;
378
+ }
379
+ function stripBasename(pathname, basename) {
380
+ if (basename === "/") return pathname;
381
+
382
+ if (!pathname.toLowerCase().startsWith(basename.toLowerCase())) {
383
+ return null;
384
+ }
385
+
386
+ let nextChar = pathname.charAt(basename.length);
387
+
388
+ if (nextChar && nextChar !== "/") {
389
+ // pathname does not start with basename/
390
+ return null;
391
+ }
392
+
393
+ return pathname.slice(basename.length) || "/";
394
+ }
395
+ const joinPaths = paths => paths.join("/").replace(/\/\/+/g, "/");
396
+ const normalizePathname = pathname => pathname.replace(/\/+$/, "").replace(/^\/*/, "/");
397
+
398
+ const normalizeSearch = search => !search || search === "?" ? "" : search.startsWith("?") ? search : "?" + search;
399
+
400
+ const normalizeHash = hash => !hash || hash === "#" ? "" : hash.startsWith("#") ? hash : "#" + hash;
244
401
 
245
402
  /**
246
403
  * Returns the full href for the given "to" value. This is useful for building
@@ -302,13 +459,13 @@ function useLocation() {
302
459
  `useLocation() may be used only in the context of a <Router> component.`) : void 0;
303
460
  return useContext(LocationContext).location;
304
461
  }
305
-
306
462
  /**
307
463
  * Returns the current navigation action which describes how the router came to
308
464
  * the current location, either by a pop, push, or replace on the history stack.
309
465
  *
310
466
  * @see https://reactrouter.com/docs/en/v6/api#usenavigationtype
311
467
  */
468
+
312
469
  function useNavigationType() {
313
470
  return useContext(LocationContext).navigationType;
314
471
  }
@@ -509,12 +666,186 @@ function useRoutes(routes, locationArg) {
509
666
  pathname: joinPaths([parentPathnameBase, match.pathname]),
510
667
  pathnameBase: match.pathnameBase === "/" ? parentPathnameBase : joinPaths([parentPathnameBase, match.pathnameBase])
511
668
  })), parentMatches);
512
- } ///////////////////////////////////////////////////////////////////////////////
513
- // UTILS
514
- ///////////////////////////////////////////////////////////////////////////////
669
+ }
670
+ function _renderMatches(matches, parentMatches = []) {
671
+ if (matches == null) return null;
672
+ return matches.reduceRight((outlet, match, index) => {
673
+ return /*#__PURE__*/createElement(RouteContext.Provider, {
674
+ children: match.route.element !== undefined ? match.route.element : outlet,
675
+ value: {
676
+ outlet,
677
+ matches: parentMatches.concat(matches.slice(0, index + 1))
678
+ }
679
+ });
680
+ }, null);
681
+ }
515
682
 
516
683
  /**
517
- * Creates a route config from a React "children" object, which is usually
684
+ * A <Router> that stores all entries in memory.
685
+ *
686
+ * @see https://reactrouter.com/docs/en/v6/api#memoryrouter
687
+ */
688
+ function MemoryRouter({
689
+ basename,
690
+ children,
691
+ initialEntries,
692
+ initialIndex
693
+ }) {
694
+ let historyRef = useRef();
695
+
696
+ if (historyRef.current == null) {
697
+ historyRef.current = createMemoryHistory({
698
+ initialEntries,
699
+ initialIndex
700
+ });
701
+ }
702
+
703
+ let history = historyRef.current;
704
+ let [state, setState] = useState({
705
+ action: history.action,
706
+ location: history.location
707
+ });
708
+ useLayoutEffect(() => history.listen(setState), [history]);
709
+ return /*#__PURE__*/createElement(Router, {
710
+ basename: basename,
711
+ children: children,
712
+ location: state.location,
713
+ navigationType: state.action,
714
+ navigator: history
715
+ });
716
+ }
717
+
718
+ /**
719
+ * Changes the current location.
720
+ *
721
+ * Note: This API is mostly useful in React.Component subclasses that are not
722
+ * able to use hooks. In functional components, we recommend you use the
723
+ * `useNavigate` hook instead.
724
+ *
725
+ * @see https://reactrouter.com/docs/en/v6/api#navigate
726
+ */
727
+ function Navigate({
728
+ to,
729
+ replace,
730
+ state
731
+ }) {
732
+ !useInRouterContext() ? invariant(false, // TODO: This error is probably because they somehow have 2 versions of
733
+ // the router loaded. We can help them understand how to avoid that.
734
+ `<Navigate> may be used only in the context of a <Router> component.`) : void 0;
735
+ 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.`) ;
736
+ let navigate = useNavigate();
737
+ useEffect(() => {
738
+ navigate(to, {
739
+ replace,
740
+ state
741
+ });
742
+ });
743
+ return null;
744
+ }
745
+
746
+ /**
747
+ * Renders the child route's element, if there is one.
748
+ *
749
+ * @see https://reactrouter.com/docs/en/v6/api#outlet
750
+ */
751
+ function Outlet(props) {
752
+ return useOutlet(props.context);
753
+ }
754
+
755
+ /**
756
+ * Declares an element that should be rendered at a certain URL path.
757
+ *
758
+ * @see https://reactrouter.com/docs/en/v6/api#route
759
+ */
760
+ function Route(_props) {
761
+ 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>.`) ;
762
+ }
763
+
764
+ /**
765
+ * Provides location context for the rest of the app.
766
+ *
767
+ * Note: You usually won't render a <Router> directly. Instead, you'll render a
768
+ * router that is more specific to your environment such as a <BrowserRouter>
769
+ * in web browsers or a <StaticRouter> for server rendering.
770
+ *
771
+ * @see https://reactrouter.com/docs/en/v6/api#router
772
+ */
773
+ function Router({
774
+ basename: basenameProp = "/",
775
+ children = null,
776
+ location: locationProp,
777
+ navigationType = Action.Pop,
778
+ navigator,
779
+ static: staticProp = false
780
+ }) {
781
+ !!useInRouterContext() ? invariant(false, `You cannot render a <Router> inside another <Router>.` + ` You should never have more than one in your app.`) : void 0;
782
+ let basename = normalizePathname(basenameProp);
783
+ let navigationContext = useMemo(() => ({
784
+ basename,
785
+ navigator,
786
+ static: staticProp
787
+ }), [basename, navigator, staticProp]);
788
+
789
+ if (typeof locationProp === "string") {
790
+ locationProp = parsePath(locationProp);
791
+ }
792
+
793
+ let {
794
+ pathname = "/",
795
+ search = "",
796
+ hash = "",
797
+ state = null,
798
+ key = "default"
799
+ } = locationProp;
800
+ let location = useMemo(() => {
801
+ let trailingPathname = stripBasename(pathname, basename);
802
+
803
+ if (trailingPathname == null) {
804
+ return null;
805
+ }
806
+
807
+ return {
808
+ pathname: trailingPathname,
809
+ search,
810
+ hash,
811
+ state,
812
+ key
813
+ };
814
+ }, [basename, pathname, search, hash, state, key]);
815
+ 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.`) ;
816
+
817
+ if (location == null) {
818
+ return null;
819
+ }
820
+
821
+ return /*#__PURE__*/createElement(NavigationContext.Provider, {
822
+ value: navigationContext
823
+ }, /*#__PURE__*/createElement(LocationContext.Provider, {
824
+ children: children,
825
+ value: {
826
+ location,
827
+ navigationType
828
+ }
829
+ }));
830
+ }
831
+
832
+ /**
833
+ * A container for a nested tree of <Route> elements that renders the branch
834
+ * that best matches the current location.
835
+ *
836
+ * @see https://reactrouter.com/docs/en/v6/api#routes
837
+ */
838
+ function Routes({
839
+ children,
840
+ location
841
+ }) {
842
+ return useRoutes(createRoutesFromChildren(children), location);
843
+ } ///////////////////////////////////////////////////////////////////////////////
844
+ // UTILS
845
+ ///////////////////////////////////////////////////////////////////////////////
846
+
847
+ /**
848
+ * Creates a route config from a React "children" object, which is usually
518
849
  * either a `<Route>` element or an array of them. Used internally by
519
850
  * `<Routes>` to create a route config from its children.
520
851
  *
@@ -553,373 +884,12 @@ function createRoutesFromChildren(children) {
553
884
  return routes;
554
885
  }
555
886
  /**
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
887
+ * Renders the result of `matchRoutes()` into a React element.
578
888
  */
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
889
 
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)));
890
+ function renderMatches(matches) {
891
+ return _renderMatches(matches);
640
892
  }
641
893
 
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
894
  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
895
  //# sourceMappingURL=react-router.development.js.map