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