react-router-dom 5.2.0 → 6.11.2

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.
Files changed (70) hide show
  1. package/CHANGELOG.md +345 -0
  2. package/{LICENSE → LICENSE.md} +3 -1
  3. package/README.md +4 -36
  4. package/dist/dom.d.ts +76 -0
  5. package/dist/index.d.ts +246 -0
  6. package/dist/index.js +1058 -0
  7. package/dist/index.js.map +1 -0
  8. package/dist/main.js +19 -0
  9. package/dist/react-router-dom.development.js +1005 -0
  10. package/dist/react-router-dom.development.js.map +1 -0
  11. package/dist/react-router-dom.production.min.js +12 -0
  12. package/dist/react-router-dom.production.min.js.map +1 -0
  13. package/dist/server.d.ts +28 -0
  14. package/dist/server.js +319 -0
  15. package/dist/server.mjs +291 -0
  16. package/dist/umd/react-router-dom.development.js +1306 -0
  17. package/dist/umd/react-router-dom.development.js.map +1 -0
  18. package/dist/umd/react-router-dom.production.min.js +12 -0
  19. package/dist/umd/react-router-dom.production.min.js.map +1 -0
  20. package/package.json +38 -54
  21. package/server.d.ts +28 -0
  22. package/server.js +319 -0
  23. package/server.mjs +291 -0
  24. package/BrowserRouter.js +0 -3
  25. package/HashRouter.js +0 -3
  26. package/Link.js +0 -3
  27. package/MemoryRouter.js +0 -3
  28. package/NavLink.js +0 -3
  29. package/Prompt.js +0 -3
  30. package/Redirect.js +0 -3
  31. package/Route.js +0 -3
  32. package/Router.js +0 -3
  33. package/StaticRouter.js +0 -3
  34. package/Switch.js +0 -3
  35. package/cjs/react-router-dom.js +0 -443
  36. package/cjs/react-router-dom.js.map +0 -1
  37. package/cjs/react-router-dom.min.js +0 -2
  38. package/cjs/react-router-dom.min.js.map +0 -1
  39. package/es/BrowserRouter.js +0 -5
  40. package/es/HashRouter.js +0 -5
  41. package/es/Link.js +0 -5
  42. package/es/MemoryRouter.js +0 -5
  43. package/es/NavLink.js +0 -5
  44. package/es/Prompt.js +0 -5
  45. package/es/Redirect.js +0 -5
  46. package/es/Route.js +0 -5
  47. package/es/Router.js +0 -5
  48. package/es/StaticRouter.js +0 -5
  49. package/es/Switch.js +0 -5
  50. package/es/generatePath.js +0 -5
  51. package/es/matchPath.js +0 -5
  52. package/es/warnAboutDeprecatedESMImport.js +0 -34
  53. package/es/withRouter.js +0 -5
  54. package/esm/react-router-dom.js +0 -317
  55. package/esm/react-router-dom.js.map +0 -1
  56. package/generatePath.js +0 -3
  57. package/index.js +0 -7
  58. package/matchPath.js +0 -3
  59. package/modules/BrowserRouter.js +0 -36
  60. package/modules/HashRouter.js +0 -35
  61. package/modules/Link.js +0 -146
  62. package/modules/NavLink.js +0 -125
  63. package/modules/index.js +0 -21
  64. package/modules/utils/locationUtils.js +0 -10
  65. package/umd/react-router-dom.js +0 -3969
  66. package/umd/react-router-dom.js.map +0 -1
  67. package/umd/react-router-dom.min.js +0 -2
  68. package/umd/react-router-dom.min.js.map +0 -1
  69. package/warnAboutDeprecatedCJSRequire.js +0 -36
  70. package/withRouter.js +0 -3
@@ -0,0 +1,1005 @@
1
+ /**
2
+ * React Router DOM v6.11.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 * as React from 'react';
12
+ import { UNSAFE_mapRouteProperties, Router, UNSAFE_NavigationContext, useHref, useResolvedPath, useLocation, UNSAFE_DataRouterStateContext, useNavigate, createPath, UNSAFE_useRouteId, UNSAFE_RouteContext, useMatches, useNavigation, unstable_useBlocker, UNSAFE_DataRouterContext } from 'react-router';
13
+ export { AbortedDeferredError, Await, MemoryRouter, Navigate, NavigationType, Outlet, Route, Router, RouterProvider, Routes, UNSAFE_DataRouterContext, UNSAFE_DataRouterStateContext, UNSAFE_LocationContext, UNSAFE_NavigationContext, UNSAFE_RouteContext, UNSAFE_useRouteId, createMemoryRouter, createPath, createRoutesFromChildren, createRoutesFromElements, defer, generatePath, isRouteErrorResponse, json, matchPath, matchRoutes, parsePath, redirect, renderMatches, resolvePath, unstable_useBlocker, useActionData, useAsyncError, useAsyncValue, useHref, useInRouterContext, useLoaderData, useLocation, useMatch, useMatches, useNavigate, useNavigation, useNavigationType, useOutlet, useOutletContext, useParams, useResolvedPath, useRevalidator, useRouteError, useRouteLoaderData, useRoutes } from 'react-router';
14
+ import { stripBasename, createRouter, createBrowserHistory, createHashHistory, ErrorResponse, UNSAFE_warning, UNSAFE_invariant, joinPaths } from '@remix-run/router';
15
+
16
+ const defaultMethod = "get";
17
+ const defaultEncType = "application/x-www-form-urlencoded";
18
+ function isHtmlElement(object) {
19
+ return object != null && typeof object.tagName === "string";
20
+ }
21
+ function isButtonElement(object) {
22
+ return isHtmlElement(object) && object.tagName.toLowerCase() === "button";
23
+ }
24
+ function isFormElement(object) {
25
+ return isHtmlElement(object) && object.tagName.toLowerCase() === "form";
26
+ }
27
+ function isInputElement(object) {
28
+ return isHtmlElement(object) && object.tagName.toLowerCase() === "input";
29
+ }
30
+
31
+ function isModifiedEvent(event) {
32
+ return !!(event.metaKey || event.altKey || event.ctrlKey || event.shiftKey);
33
+ }
34
+
35
+ function shouldProcessLinkClick(event, target) {
36
+ return event.button === 0 && ( // Ignore everything but left clicks
37
+ !target || target === "_self") && // Let browser handle "target=_blank" etc.
38
+ !isModifiedEvent(event) // Ignore clicks with modifier keys
39
+ ;
40
+ }
41
+
42
+ /**
43
+ * Creates a URLSearchParams object using the given initializer.
44
+ *
45
+ * This is identical to `new URLSearchParams(init)` except it also
46
+ * supports arrays as values in the object form of the initializer
47
+ * instead of just strings. This is convenient when you need multiple
48
+ * values for a given key, but don't want to use an array initializer.
49
+ *
50
+ * For example, instead of:
51
+ *
52
+ * let searchParams = new URLSearchParams([
53
+ * ['sort', 'name'],
54
+ * ['sort', 'price']
55
+ * ]);
56
+ *
57
+ * you can do:
58
+ *
59
+ * let searchParams = createSearchParams({
60
+ * sort: ['name', 'price']
61
+ * });
62
+ */
63
+ function createSearchParams(init = "") {
64
+ return new URLSearchParams(typeof init === "string" || Array.isArray(init) || init instanceof URLSearchParams ? init : Object.keys(init).reduce((memo, key) => {
65
+ let value = init[key];
66
+ return memo.concat(Array.isArray(value) ? value.map(v => [key, v]) : [[key, value]]);
67
+ }, []));
68
+ }
69
+ function getSearchParamsForLocation(locationSearch, defaultSearchParams) {
70
+ let searchParams = createSearchParams(locationSearch);
71
+
72
+ if (defaultSearchParams) {
73
+ for (let key of defaultSearchParams.keys()) {
74
+ if (!searchParams.has(key)) {
75
+ defaultSearchParams.getAll(key).forEach(value => {
76
+ searchParams.append(key, value);
77
+ });
78
+ }
79
+ }
80
+ }
81
+
82
+ return searchParams;
83
+ }
84
+ function getFormSubmissionInfo(target, options, basename) {
85
+ let method;
86
+ let action = null;
87
+ let encType;
88
+ let formData;
89
+
90
+ if (isFormElement(target)) {
91
+ let submissionTrigger = options.submissionTrigger;
92
+
93
+ if (options.action) {
94
+ action = options.action;
95
+ } else {
96
+ // When grabbing the action from the element, it will have had the basename
97
+ // prefixed to ensure non-JS scenarios work, so strip it since we'll
98
+ // re-prefix in the router
99
+ let attr = target.getAttribute("action");
100
+ action = attr ? stripBasename(attr, basename) : null;
101
+ }
102
+
103
+ method = options.method || target.getAttribute("method") || defaultMethod;
104
+ encType = options.encType || target.getAttribute("enctype") || defaultEncType;
105
+ formData = new FormData(target);
106
+
107
+ if (submissionTrigger && submissionTrigger.name) {
108
+ formData.append(submissionTrigger.name, submissionTrigger.value);
109
+ }
110
+ } else if (isButtonElement(target) || isInputElement(target) && (target.type === "submit" || target.type === "image")) {
111
+ let form = target.form;
112
+
113
+ if (form == null) {
114
+ throw new Error(`Cannot submit a <button> or <input type="submit"> without a <form>`);
115
+ } // <button>/<input type="submit"> may override attributes of <form>
116
+
117
+
118
+ if (options.action) {
119
+ action = options.action;
120
+ } else {
121
+ // When grabbing the action from the element, it will have had the basename
122
+ // prefixed to ensure non-JS scenarios work, so strip it since we'll
123
+ // re-prefix in the router
124
+ let attr = target.getAttribute("formaction") || form.getAttribute("action");
125
+ action = attr ? stripBasename(attr, basename) : null;
126
+ }
127
+
128
+ method = options.method || target.getAttribute("formmethod") || form.getAttribute("method") || defaultMethod;
129
+ encType = options.encType || target.getAttribute("formenctype") || form.getAttribute("enctype") || defaultEncType;
130
+ formData = new FormData(form); // Include name + value from a <button>, appending in case the button name
131
+ // matches an existing input name
132
+
133
+ if (target.name) {
134
+ formData.append(target.name, target.value);
135
+ }
136
+ } else if (isHtmlElement(target)) {
137
+ throw new Error(`Cannot submit element that is not <form>, <button>, or ` + `<input type="submit|image">`);
138
+ } else {
139
+ method = options.method || defaultMethod;
140
+ action = options.action || null;
141
+ encType = options.encType || defaultEncType;
142
+
143
+ if (target instanceof FormData) {
144
+ formData = target;
145
+ } else {
146
+ formData = new FormData();
147
+
148
+ if (target instanceof URLSearchParams) {
149
+ for (let [name, value] of target) {
150
+ formData.append(name, value);
151
+ }
152
+ } else if (target != null) {
153
+ for (let name of Object.keys(target)) {
154
+ formData.append(name, target[name]);
155
+ }
156
+ }
157
+ }
158
+ }
159
+
160
+ return {
161
+ action,
162
+ method: method.toLowerCase(),
163
+ encType,
164
+ formData
165
+ };
166
+ }
167
+
168
+ /**
169
+ * NOTE: If you refactor this to split up the modules into separate files,
170
+ * you'll need to update the rollup config for react-router-dom-v5-compat.
171
+ */
172
+
173
+ function createBrowserRouter(routes, opts) {
174
+ return createRouter({
175
+ basename: opts?.basename,
176
+ future: { ...opts?.future,
177
+ v7_prependBasename: true
178
+ },
179
+ history: createBrowserHistory({
180
+ window: opts?.window
181
+ }),
182
+ hydrationData: opts?.hydrationData || parseHydrationData(),
183
+ routes,
184
+ mapRouteProperties: UNSAFE_mapRouteProperties
185
+ }).initialize();
186
+ }
187
+ function createHashRouter(routes, opts) {
188
+ return createRouter({
189
+ basename: opts?.basename,
190
+ future: { ...opts?.future,
191
+ v7_prependBasename: true
192
+ },
193
+ history: createHashHistory({
194
+ window: opts?.window
195
+ }),
196
+ hydrationData: opts?.hydrationData || parseHydrationData(),
197
+ routes,
198
+ mapRouteProperties: UNSAFE_mapRouteProperties
199
+ }).initialize();
200
+ }
201
+
202
+ function parseHydrationData() {
203
+ let state = window?.__staticRouterHydrationData;
204
+
205
+ if (state && state.errors) {
206
+ state = { ...state,
207
+ errors: deserializeErrors(state.errors)
208
+ };
209
+ }
210
+
211
+ return state;
212
+ }
213
+
214
+ function deserializeErrors(errors) {
215
+ if (!errors) return null;
216
+ let entries = Object.entries(errors);
217
+ let serialized = {};
218
+
219
+ for (let [key, val] of entries) {
220
+ // Hey you! If you change this, please change the corresponding logic in
221
+ // serializeErrors in react-router-dom/server.tsx :)
222
+ if (val && val.__type === "RouteErrorResponse") {
223
+ serialized[key] = new ErrorResponse(val.status, val.statusText, val.data, val.internal === true);
224
+ } else if (val && val.__type === "Error") {
225
+ let error = new Error(val.message); // Wipe away the client-side stack trace. Nothing to fill it in with
226
+ // because we don't serialize SSR stack traces for security reasons
227
+
228
+ error.stack = "";
229
+ serialized[key] = error;
230
+ } else {
231
+ serialized[key] = val;
232
+ }
233
+ }
234
+
235
+ return serialized;
236
+ } //#endregion
237
+ ////////////////////////////////////////////////////////////////////////////////
238
+ //#region Components
239
+ ////////////////////////////////////////////////////////////////////////////////
240
+
241
+
242
+ /**
243
+ * A `<Router>` for use in web browsers. Provides the cleanest URLs.
244
+ */
245
+ function BrowserRouter({
246
+ basename,
247
+ children,
248
+ window
249
+ }) {
250
+ let historyRef = React.useRef();
251
+
252
+ if (historyRef.current == null) {
253
+ historyRef.current = createBrowserHistory({
254
+ window,
255
+ v5Compat: true
256
+ });
257
+ }
258
+
259
+ let history = historyRef.current;
260
+ let [state, setState] = React.useState({
261
+ action: history.action,
262
+ location: history.location
263
+ });
264
+ React.useLayoutEffect(() => history.listen(setState), [history]);
265
+ return /*#__PURE__*/React.createElement(Router, {
266
+ basename: basename,
267
+ children: children,
268
+ location: state.location,
269
+ navigationType: state.action,
270
+ navigator: history
271
+ });
272
+ }
273
+
274
+ /**
275
+ * A `<Router>` for use in web browsers. Stores the location in the hash
276
+ * portion of the URL so it is not sent to the server.
277
+ */
278
+ function HashRouter({
279
+ basename,
280
+ children,
281
+ window
282
+ }) {
283
+ let historyRef = React.useRef();
284
+
285
+ if (historyRef.current == null) {
286
+ historyRef.current = createHashHistory({
287
+ window,
288
+ v5Compat: true
289
+ });
290
+ }
291
+
292
+ let history = historyRef.current;
293
+ let [state, setState] = React.useState({
294
+ action: history.action,
295
+ location: history.location
296
+ });
297
+ React.useLayoutEffect(() => history.listen(setState), [history]);
298
+ return /*#__PURE__*/React.createElement(Router, {
299
+ basename: basename,
300
+ children: children,
301
+ location: state.location,
302
+ navigationType: state.action,
303
+ navigator: history
304
+ });
305
+ }
306
+
307
+ /**
308
+ * A `<Router>` that accepts a pre-instantiated history object. It's important
309
+ * to note that using your own history object is highly discouraged and may add
310
+ * two versions of the history library to your bundles unless you use the same
311
+ * version of the history library that React Router uses internally.
312
+ */
313
+ function HistoryRouter({
314
+ basename,
315
+ children,
316
+ history
317
+ }) {
318
+ const [state, setState] = React.useState({
319
+ action: history.action,
320
+ location: history.location
321
+ });
322
+ React.useLayoutEffect(() => history.listen(setState), [history]);
323
+ return /*#__PURE__*/React.createElement(Router, {
324
+ basename: basename,
325
+ children: children,
326
+ location: state.location,
327
+ navigationType: state.action,
328
+ navigator: history
329
+ });
330
+ }
331
+
332
+ {
333
+ HistoryRouter.displayName = "unstable_HistoryRouter";
334
+ }
335
+ const isBrowser = typeof window !== "undefined" && typeof window.document !== "undefined" && typeof window.document.createElement !== "undefined";
336
+ const ABSOLUTE_URL_REGEX = /^(?:[a-z][a-z0-9+.-]*:|\/\/)/i;
337
+ /**
338
+ * The public API for rendering a history-aware <a>.
339
+ */
340
+
341
+ const Link = /*#__PURE__*/React.forwardRef(function LinkWithRef({
342
+ onClick,
343
+ relative,
344
+ reloadDocument,
345
+ replace,
346
+ state,
347
+ target,
348
+ to,
349
+ preventScrollReset,
350
+ ...rest
351
+ }, ref) {
352
+ let {
353
+ basename
354
+ } = React.useContext(UNSAFE_NavigationContext); // Rendered into <a href> for absolute URLs
355
+
356
+ let absoluteHref;
357
+ let isExternal = false;
358
+
359
+ if (typeof to === "string" && ABSOLUTE_URL_REGEX.test(to)) {
360
+ // Render the absolute href server- and client-side
361
+ absoluteHref = to; // Only check for external origins client-side
362
+
363
+ if (isBrowser) {
364
+ try {
365
+ let currentUrl = new URL(window.location.href);
366
+ let targetUrl = to.startsWith("//") ? new URL(currentUrl.protocol + to) : new URL(to);
367
+ let path = stripBasename(targetUrl.pathname, basename);
368
+
369
+ if (targetUrl.origin === currentUrl.origin && path != null) {
370
+ // Strip the protocol/origin/basename for same-origin absolute URLs
371
+ to = path + targetUrl.search + targetUrl.hash;
372
+ } else {
373
+ isExternal = true;
374
+ }
375
+ } catch (e) {
376
+ // We can't do external URL detection without a valid URL
377
+ UNSAFE_warning(false, `<Link to="${to}"> contains an invalid URL which will probably break ` + `when clicked - please update to a valid URL path.`) ;
378
+ }
379
+ }
380
+ } // Rendered into <a href> for relative URLs
381
+
382
+
383
+ let href = useHref(to, {
384
+ relative
385
+ });
386
+ let internalOnClick = useLinkClickHandler(to, {
387
+ replace,
388
+ state,
389
+ target,
390
+ preventScrollReset,
391
+ relative
392
+ });
393
+
394
+ function handleClick(event) {
395
+ if (onClick) onClick(event);
396
+
397
+ if (!event.defaultPrevented) {
398
+ internalOnClick(event);
399
+ }
400
+ }
401
+
402
+ return (
403
+ /*#__PURE__*/
404
+ // eslint-disable-next-line jsx-a11y/anchor-has-content
405
+ React.createElement("a", Object.assign({}, rest, {
406
+ href: absoluteHref || href,
407
+ onClick: isExternal || reloadDocument ? onClick : handleClick,
408
+ ref: ref,
409
+ target: target
410
+ }))
411
+ );
412
+ });
413
+
414
+ {
415
+ Link.displayName = "Link";
416
+ }
417
+
418
+ /**
419
+ * A <Link> wrapper that knows if it's "active" or not.
420
+ */
421
+ const NavLink = /*#__PURE__*/React.forwardRef(function NavLinkWithRef({
422
+ "aria-current": ariaCurrentProp = "page",
423
+ caseSensitive = false,
424
+ className: classNameProp = "",
425
+ end = false,
426
+ style: styleProp,
427
+ to,
428
+ children,
429
+ ...rest
430
+ }, ref) {
431
+ let path = useResolvedPath(to, {
432
+ relative: rest.relative
433
+ });
434
+ let location = useLocation();
435
+ let routerState = React.useContext(UNSAFE_DataRouterStateContext);
436
+ let {
437
+ navigator
438
+ } = React.useContext(UNSAFE_NavigationContext);
439
+ let toPathname = navigator.encodeLocation ? navigator.encodeLocation(path).pathname : path.pathname;
440
+ let locationPathname = location.pathname;
441
+ let nextLocationPathname = routerState && routerState.navigation && routerState.navigation.location ? routerState.navigation.location.pathname : null;
442
+
443
+ if (!caseSensitive) {
444
+ locationPathname = locationPathname.toLowerCase();
445
+ nextLocationPathname = nextLocationPathname ? nextLocationPathname.toLowerCase() : null;
446
+ toPathname = toPathname.toLowerCase();
447
+ }
448
+
449
+ let isActive = locationPathname === toPathname || !end && locationPathname.startsWith(toPathname) && locationPathname.charAt(toPathname.length) === "/";
450
+ let isPending = nextLocationPathname != null && (nextLocationPathname === toPathname || !end && nextLocationPathname.startsWith(toPathname) && nextLocationPathname.charAt(toPathname.length) === "/");
451
+ let ariaCurrent = isActive ? ariaCurrentProp : undefined;
452
+ let className;
453
+
454
+ if (typeof classNameProp === "function") {
455
+ className = classNameProp({
456
+ isActive,
457
+ isPending
458
+ });
459
+ } else {
460
+ // If the className prop is not a function, we use a default `active`
461
+ // class for <NavLink />s that are active. In v5 `active` was the default
462
+ // value for `activeClassName`, but we are removing that API and can still
463
+ // use the old default behavior for a cleaner upgrade path and keep the
464
+ // simple styling rules working as they currently do.
465
+ className = [classNameProp, isActive ? "active" : null, isPending ? "pending" : null].filter(Boolean).join(" ");
466
+ }
467
+
468
+ let style = typeof styleProp === "function" ? styleProp({
469
+ isActive,
470
+ isPending
471
+ }) : styleProp;
472
+ return /*#__PURE__*/React.createElement(Link, Object.assign({}, rest, {
473
+ "aria-current": ariaCurrent,
474
+ className: className,
475
+ ref: ref,
476
+ style: style,
477
+ to: to
478
+ }), typeof children === "function" ? children({
479
+ isActive,
480
+ isPending
481
+ }) : children);
482
+ });
483
+
484
+ {
485
+ NavLink.displayName = "NavLink";
486
+ }
487
+
488
+ /**
489
+ * A `@remix-run/router`-aware `<form>`. It behaves like a normal form except
490
+ * that the interaction with the server is with `fetch` instead of new document
491
+ * requests, allowing components to add nicer UX to the page as the form is
492
+ * submitted and returns with data.
493
+ */
494
+ const Form = /*#__PURE__*/React.forwardRef((props, ref) => {
495
+ return /*#__PURE__*/React.createElement(FormImpl, Object.assign({}, props, {
496
+ ref: ref
497
+ }));
498
+ });
499
+
500
+ {
501
+ Form.displayName = "Form";
502
+ }
503
+
504
+ const FormImpl = /*#__PURE__*/React.forwardRef(({
505
+ reloadDocument,
506
+ replace,
507
+ method: _method = defaultMethod,
508
+ action,
509
+ onSubmit,
510
+ fetcherKey,
511
+ routeId,
512
+ relative,
513
+ preventScrollReset,
514
+ ...props
515
+ }, forwardedRef) => {
516
+ let submit = useSubmitImpl(fetcherKey, routeId);
517
+ let formMethod = _method.toLowerCase() === "get" ? "get" : "post";
518
+ let formAction = useFormAction(action, {
519
+ relative
520
+ });
521
+
522
+ let submitHandler = event => {
523
+ onSubmit && onSubmit(event);
524
+ if (event.defaultPrevented) return;
525
+ event.preventDefault();
526
+ let submitter = event.nativeEvent.submitter;
527
+
528
+ let submitMethod = submitter?.getAttribute("formmethod") || _method;
529
+
530
+ submit(submitter || event.currentTarget, {
531
+ method: submitMethod,
532
+ replace,
533
+ relative,
534
+ preventScrollReset
535
+ });
536
+ };
537
+
538
+ return /*#__PURE__*/React.createElement("form", Object.assign({
539
+ ref: forwardedRef,
540
+ method: formMethod,
541
+ action: formAction,
542
+ onSubmit: reloadDocument ? onSubmit : submitHandler
543
+ }, props));
544
+ });
545
+
546
+ {
547
+ FormImpl.displayName = "FormImpl";
548
+ }
549
+
550
+ /**
551
+ * This component will emulate the browser's scroll restoration on location
552
+ * changes.
553
+ */
554
+ function ScrollRestoration({
555
+ getKey,
556
+ storageKey
557
+ }) {
558
+ useScrollRestoration({
559
+ getKey,
560
+ storageKey
561
+ });
562
+ return null;
563
+ }
564
+
565
+ {
566
+ ScrollRestoration.displayName = "ScrollRestoration";
567
+ } //#endregion
568
+ ////////////////////////////////////////////////////////////////////////////////
569
+ //#region Hooks
570
+ ////////////////////////////////////////////////////////////////////////////////
571
+
572
+
573
+ var DataRouterHook;
574
+
575
+ (function (DataRouterHook) {
576
+ DataRouterHook["UseScrollRestoration"] = "useScrollRestoration";
577
+ DataRouterHook["UseSubmitImpl"] = "useSubmitImpl";
578
+ DataRouterHook["UseFetcher"] = "useFetcher";
579
+ })(DataRouterHook || (DataRouterHook = {}));
580
+
581
+ var DataRouterStateHook;
582
+
583
+ (function (DataRouterStateHook) {
584
+ DataRouterStateHook["UseFetchers"] = "useFetchers";
585
+ DataRouterStateHook["UseScrollRestoration"] = "useScrollRestoration";
586
+ })(DataRouterStateHook || (DataRouterStateHook = {}));
587
+
588
+ function getDataRouterConsoleError(hookName) {
589
+ return `${hookName} must be used within a data router. See https://reactrouter.com/routers/picking-a-router.`;
590
+ }
591
+
592
+ function useDataRouterContext(hookName) {
593
+ let ctx = React.useContext(UNSAFE_DataRouterContext);
594
+ !ctx ? UNSAFE_invariant(false, getDataRouterConsoleError(hookName)) : void 0;
595
+ return ctx;
596
+ }
597
+
598
+ function useDataRouterState(hookName) {
599
+ let state = React.useContext(UNSAFE_DataRouterStateContext);
600
+ !state ? UNSAFE_invariant(false, getDataRouterConsoleError(hookName)) : void 0;
601
+ return state;
602
+ }
603
+ /**
604
+ * Handles the click behavior for router `<Link>` components. This is useful if
605
+ * you need to create custom `<Link>` components with the same click behavior we
606
+ * use in our exported `<Link>`.
607
+ */
608
+
609
+
610
+ function useLinkClickHandler(to, {
611
+ target,
612
+ replace: replaceProp,
613
+ state,
614
+ preventScrollReset,
615
+ relative
616
+ } = {}) {
617
+ let navigate = useNavigate();
618
+ let location = useLocation();
619
+ let path = useResolvedPath(to, {
620
+ relative
621
+ });
622
+ return React.useCallback(event => {
623
+ if (shouldProcessLinkClick(event, target)) {
624
+ event.preventDefault(); // If the URL hasn't changed, a regular <a> will do a replace instead of
625
+ // a push, so do the same here unless the replace prop is explicitly set
626
+
627
+ let replace = replaceProp !== undefined ? replaceProp : createPath(location) === createPath(path);
628
+ navigate(to, {
629
+ replace,
630
+ state,
631
+ preventScrollReset,
632
+ relative
633
+ });
634
+ }
635
+ }, [location, navigate, path, replaceProp, state, target, to, preventScrollReset, relative]);
636
+ }
637
+ /**
638
+ * A convenient wrapper for reading and writing search parameters via the
639
+ * URLSearchParams interface.
640
+ */
641
+
642
+ function useSearchParams(defaultInit) {
643
+ UNSAFE_warning(typeof URLSearchParams !== "undefined", `You cannot use the \`useSearchParams\` hook in a browser that does not ` + `support the URLSearchParams API. If you need to support Internet ` + `Explorer 11, we recommend you load a polyfill such as ` + `https://github.com/ungap/url-search-params\n\n` + `If you're unsure how to load polyfills, we recommend you check out ` + `https://polyfill.io/v3/ which provides some recommendations about how ` + `to load polyfills only for users that need them, instead of for every ` + `user.`) ;
644
+ let defaultSearchParamsRef = React.useRef(createSearchParams(defaultInit));
645
+ let hasSetSearchParamsRef = React.useRef(false);
646
+ let location = useLocation();
647
+ let searchParams = React.useMemo(() => // Only merge in the defaults if we haven't yet called setSearchParams.
648
+ // Once we call that we want those to take precedence, otherwise you can't
649
+ // remove a param with setSearchParams({}) if it has an initial value
650
+ getSearchParamsForLocation(location.search, hasSetSearchParamsRef.current ? null : defaultSearchParamsRef.current), [location.search]);
651
+ let navigate = useNavigate();
652
+ let setSearchParams = React.useCallback((nextInit, navigateOptions) => {
653
+ const newSearchParams = createSearchParams(typeof nextInit === "function" ? nextInit(searchParams) : nextInit);
654
+ hasSetSearchParamsRef.current = true;
655
+ navigate("?" + newSearchParams, navigateOptions);
656
+ }, [navigate, searchParams]);
657
+ return [searchParams, setSearchParams];
658
+ }
659
+
660
+ /**
661
+ * Returns a function that may be used to programmatically submit a form (or
662
+ * some arbitrary data) to the server.
663
+ */
664
+ function useSubmit() {
665
+ return useSubmitImpl();
666
+ }
667
+
668
+ function useSubmitImpl(fetcherKey, fetcherRouteId) {
669
+ let {
670
+ router
671
+ } = useDataRouterContext(DataRouterHook.UseSubmitImpl);
672
+ let {
673
+ basename
674
+ } = React.useContext(UNSAFE_NavigationContext);
675
+ let currentRouteId = UNSAFE_useRouteId();
676
+ return React.useCallback((target, options = {}) => {
677
+ if (typeof document === "undefined") {
678
+ throw new Error("You are calling submit during the server render. " + "Try calling submit within a `useEffect` or callback instead.");
679
+ }
680
+
681
+ let {
682
+ action,
683
+ method,
684
+ encType,
685
+ formData
686
+ } = getFormSubmissionInfo(target, options, basename); // Base options shared between fetch() and navigate()
687
+
688
+ let opts = {
689
+ preventScrollReset: options.preventScrollReset,
690
+ formData,
691
+ formMethod: method,
692
+ formEncType: encType
693
+ };
694
+
695
+ if (fetcherKey) {
696
+ !(fetcherRouteId != null) ? UNSAFE_invariant(false, "No routeId available for useFetcher()") : void 0;
697
+ router.fetch(fetcherKey, fetcherRouteId, action, opts);
698
+ } else {
699
+ router.navigate(action, { ...opts,
700
+ replace: options.replace,
701
+ fromRouteId: currentRouteId
702
+ });
703
+ }
704
+ }, [router, basename, fetcherKey, fetcherRouteId, currentRouteId]);
705
+ } // v7: Eventually we should deprecate this entirely in favor of using the
706
+ // router method directly?
707
+
708
+
709
+ function useFormAction(action, {
710
+ relative
711
+ } = {}) {
712
+ let {
713
+ basename
714
+ } = React.useContext(UNSAFE_NavigationContext);
715
+ let routeContext = React.useContext(UNSAFE_RouteContext);
716
+ !routeContext ? UNSAFE_invariant(false, "useFormAction must be used inside a RouteContext") : void 0;
717
+ let [match] = routeContext.matches.slice(-1); // Shallow clone path so we can modify it below, otherwise we modify the
718
+ // object referenced by useMemo inside useResolvedPath
719
+
720
+ let path = { ...useResolvedPath(action ? action : ".", {
721
+ relative
722
+ })
723
+ }; // Previously we set the default action to ".". The problem with this is that
724
+ // `useResolvedPath(".")` excludes search params and the hash of the resolved
725
+ // URL. This is the intended behavior of when "." is specifically provided as
726
+ // the form action, but inconsistent w/ browsers when the action is omitted.
727
+ // https://github.com/remix-run/remix/issues/927
728
+
729
+ let location = useLocation();
730
+
731
+ if (action == null) {
732
+ // Safe to write to these directly here since if action was undefined, we
733
+ // would have called useResolvedPath(".") which will never include a search
734
+ // or hash
735
+ path.search = location.search;
736
+ path.hash = location.hash; // When grabbing search params from the URL, remove the automatically
737
+ // inserted ?index param so we match the useResolvedPath search behavior
738
+ // which would not include ?index
739
+
740
+ if (match.route.index) {
741
+ let params = new URLSearchParams(path.search);
742
+ params.delete("index");
743
+ path.search = params.toString() ? `?${params.toString()}` : "";
744
+ }
745
+ }
746
+
747
+ if ((!action || action === ".") && match.route.index) {
748
+ path.search = path.search ? path.search.replace(/^\?/, "?index&") : "?index";
749
+ } // If we're operating within a basename, prepend it to the pathname prior
750
+ // to creating the form action. If this is a root navigation, then just use
751
+ // the raw basename which allows the basename to have full control over the
752
+ // presence of a trailing slash on root actions
753
+
754
+
755
+ if (basename !== "/") {
756
+ path.pathname = path.pathname === "/" ? basename : joinPaths([basename, path.pathname]);
757
+ }
758
+
759
+ return createPath(path);
760
+ }
761
+
762
+ function createFetcherForm(fetcherKey, routeId) {
763
+ let FetcherForm = /*#__PURE__*/React.forwardRef((props, ref) => {
764
+ return /*#__PURE__*/React.createElement(FormImpl, Object.assign({}, props, {
765
+ ref: ref,
766
+ fetcherKey: fetcherKey,
767
+ routeId: routeId
768
+ }));
769
+ });
770
+
771
+ {
772
+ FetcherForm.displayName = "fetcher.Form";
773
+ }
774
+
775
+ return FetcherForm;
776
+ }
777
+
778
+ let fetcherId = 0;
779
+
780
+ /**
781
+ * Interacts with route loaders and actions without causing a navigation. Great
782
+ * for any interaction that stays on the same page.
783
+ */
784
+ function useFetcher() {
785
+ let {
786
+ router
787
+ } = useDataRouterContext(DataRouterHook.UseFetcher);
788
+ let route = React.useContext(UNSAFE_RouteContext);
789
+ !route ? UNSAFE_invariant(false, `useFetcher must be used inside a RouteContext`) : void 0;
790
+ let routeId = route.matches[route.matches.length - 1]?.route.id;
791
+ !(routeId != null) ? UNSAFE_invariant(false, `useFetcher can only be used on routes that contain a unique "id"`) : void 0;
792
+ let [fetcherKey] = React.useState(() => String(++fetcherId));
793
+ let [Form] = React.useState(() => {
794
+ !routeId ? UNSAFE_invariant(false, `No routeId available for fetcher.Form()`) : void 0;
795
+ return createFetcherForm(fetcherKey, routeId);
796
+ });
797
+ let [load] = React.useState(() => href => {
798
+ !router ? UNSAFE_invariant(false, "No router available for fetcher.load()") : void 0;
799
+ !routeId ? UNSAFE_invariant(false, "No routeId available for fetcher.load()") : void 0;
800
+ router.fetch(fetcherKey, routeId, href);
801
+ });
802
+ let submit = useSubmitImpl(fetcherKey, routeId);
803
+ let fetcher = router.getFetcher(fetcherKey);
804
+ let fetcherWithComponents = React.useMemo(() => ({
805
+ Form,
806
+ submit,
807
+ load,
808
+ ...fetcher
809
+ }), [fetcher, Form, submit, load]);
810
+ React.useEffect(() => {
811
+ // Is this busted when the React team gets real weird and calls effects
812
+ // twice on mount? We really just need to garbage collect here when this
813
+ // fetcher is no longer around.
814
+ return () => {
815
+ if (!router) {
816
+ console.warn(`No router available to clean up from useFetcher()`);
817
+ return;
818
+ }
819
+
820
+ router.deleteFetcher(fetcherKey);
821
+ };
822
+ }, [router, fetcherKey]);
823
+ return fetcherWithComponents;
824
+ }
825
+ /**
826
+ * Provides all fetchers currently on the page. Useful for layouts and parent
827
+ * routes that need to provide pending/optimistic UI regarding the fetch.
828
+ */
829
+
830
+ function useFetchers() {
831
+ let state = useDataRouterState(DataRouterStateHook.UseFetchers);
832
+ return [...state.fetchers.values()];
833
+ }
834
+ const SCROLL_RESTORATION_STORAGE_KEY = "react-router-scroll-positions";
835
+ let savedScrollPositions = {};
836
+ /**
837
+ * When rendered inside a RouterProvider, will restore scroll positions on navigations
838
+ */
839
+
840
+ function useScrollRestoration({
841
+ getKey,
842
+ storageKey
843
+ } = {}) {
844
+ let {
845
+ router
846
+ } = useDataRouterContext(DataRouterHook.UseScrollRestoration);
847
+ let {
848
+ restoreScrollPosition,
849
+ preventScrollReset
850
+ } = useDataRouterState(DataRouterStateHook.UseScrollRestoration);
851
+ let location = useLocation();
852
+ let matches = useMatches();
853
+ let navigation = useNavigation(); // Trigger manual scroll restoration while we're active
854
+
855
+ React.useEffect(() => {
856
+ window.history.scrollRestoration = "manual";
857
+ return () => {
858
+ window.history.scrollRestoration = "auto";
859
+ };
860
+ }, []); // Save positions on pagehide
861
+
862
+ usePageHide(React.useCallback(() => {
863
+ if (navigation.state === "idle") {
864
+ let key = (getKey ? getKey(location, matches) : null) || location.key;
865
+ savedScrollPositions[key] = window.scrollY;
866
+ }
867
+
868
+ sessionStorage.setItem(storageKey || SCROLL_RESTORATION_STORAGE_KEY, JSON.stringify(savedScrollPositions));
869
+ window.history.scrollRestoration = "auto";
870
+ }, [storageKey, getKey, navigation.state, location, matches])); // Read in any saved scroll locations
871
+
872
+ if (typeof document !== "undefined") {
873
+ // eslint-disable-next-line react-hooks/rules-of-hooks
874
+ React.useLayoutEffect(() => {
875
+ try {
876
+ let sessionPositions = sessionStorage.getItem(storageKey || SCROLL_RESTORATION_STORAGE_KEY);
877
+
878
+ if (sessionPositions) {
879
+ savedScrollPositions = JSON.parse(sessionPositions);
880
+ }
881
+ } catch (e) {// no-op, use default empty object
882
+ }
883
+ }, [storageKey]); // Enable scroll restoration in the router
884
+ // eslint-disable-next-line react-hooks/rules-of-hooks
885
+
886
+ React.useLayoutEffect(() => {
887
+ let disableScrollRestoration = router?.enableScrollRestoration(savedScrollPositions, () => window.scrollY, getKey);
888
+ return () => disableScrollRestoration && disableScrollRestoration();
889
+ }, [router, getKey]); // Restore scrolling when state.restoreScrollPosition changes
890
+ // eslint-disable-next-line react-hooks/rules-of-hooks
891
+
892
+ React.useLayoutEffect(() => {
893
+ // Explicit false means don't do anything (used for submissions)
894
+ if (restoreScrollPosition === false) {
895
+ return;
896
+ } // been here before, scroll to it
897
+
898
+
899
+ if (typeof restoreScrollPosition === "number") {
900
+ window.scrollTo(0, restoreScrollPosition);
901
+ return;
902
+ } // try to scroll to the hash
903
+
904
+
905
+ if (location.hash) {
906
+ let el = document.getElementById(location.hash.slice(1));
907
+
908
+ if (el) {
909
+ el.scrollIntoView();
910
+ return;
911
+ }
912
+ } // Don't reset if this navigation opted out
913
+
914
+
915
+ if (preventScrollReset === true) {
916
+ return;
917
+ } // otherwise go to the top on new locations
918
+
919
+
920
+ window.scrollTo(0, 0);
921
+ }, [location, restoreScrollPosition, preventScrollReset]);
922
+ }
923
+ }
924
+ /**
925
+ * Setup a callback to be fired on the window's `beforeunload` event. This is
926
+ * useful for saving some data to `window.localStorage` just before the page
927
+ * refreshes.
928
+ *
929
+ * Note: The `callback` argument should be a function created with
930
+ * `React.useCallback()`.
931
+ */
932
+
933
+ function useBeforeUnload(callback, options) {
934
+ let {
935
+ capture
936
+ } = options || {};
937
+ React.useEffect(() => {
938
+ let opts = capture != null ? {
939
+ capture
940
+ } : undefined;
941
+ window.addEventListener("beforeunload", callback, opts);
942
+ return () => {
943
+ window.removeEventListener("beforeunload", callback, opts);
944
+ };
945
+ }, [callback, capture]);
946
+ }
947
+ /**
948
+ * Setup a callback to be fired on the window's `pagehide` event. This is
949
+ * useful for saving some data to `window.localStorage` just before the page
950
+ * refreshes. This event is better supported than beforeunload across browsers.
951
+ *
952
+ * Note: The `callback` argument should be a function created with
953
+ * `React.useCallback()`.
954
+ */
955
+
956
+ function usePageHide(callback, options) {
957
+ let {
958
+ capture
959
+ } = options || {};
960
+ React.useEffect(() => {
961
+ let opts = capture != null ? {
962
+ capture
963
+ } : undefined;
964
+ window.addEventListener("pagehide", callback, opts);
965
+ return () => {
966
+ window.removeEventListener("pagehide", callback, opts);
967
+ };
968
+ }, [callback, capture]);
969
+ }
970
+ /**
971
+ * Wrapper around useBlocker to show a window.confirm prompt to users instead
972
+ * of building a custom UI with useBlocker.
973
+ *
974
+ * Warning: This has *a lot of rough edges* and behaves very differently (and
975
+ * very incorrectly in some cases) across browsers if user click addition
976
+ * back/forward navigations while the confirm is open. Use at your own risk.
977
+ */
978
+
979
+
980
+ function usePrompt({
981
+ when,
982
+ message
983
+ }) {
984
+ let blocker = unstable_useBlocker(when);
985
+ React.useEffect(() => {
986
+ if (blocker.state === "blocked" && !when) {
987
+ blocker.reset();
988
+ }
989
+ }, [blocker, when]);
990
+ React.useEffect(() => {
991
+ if (blocker.state === "blocked") {
992
+ let proceed = window.confirm(message);
993
+
994
+ if (proceed) {
995
+ setTimeout(blocker.proceed, 0);
996
+ } else {
997
+ blocker.reset();
998
+ }
999
+ }
1000
+ }, [blocker, message]);
1001
+ }
1002
+ //#endregion
1003
+
1004
+ export { BrowserRouter, Form, HashRouter, Link, NavLink, ScrollRestoration, useScrollRestoration as UNSAFE_useScrollRestoration, createBrowserRouter, createHashRouter, createSearchParams, HistoryRouter as unstable_HistoryRouter, usePrompt as unstable_usePrompt, useBeforeUnload, useFetcher, useFetchers, useFormAction, useLinkClickHandler, useSearchParams, useSubmit };
1005
+ //# sourceMappingURL=react-router-dom.development.js.map