react-router-dom 0.0.0-experimental-e56aa53bc → 0.0.0-experimental-e6fb6e074

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.
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  /**
2
- * react-router-dom v0.0.0-experimental-e56aa53bc
2
+ * React Router DOM v0.0.0-experimental-e6fb6e074
3
3
  *
4
4
  * Copyright (c) Remix Software Inc.
5
5
  *
@@ -8,38 +8,1469 @@
8
8
  *
9
9
  * @license MIT
10
10
  */
11
- "use strict";
12
- var __defProp = Object.defineProperty;
13
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
14
- var __getOwnPropNames = Object.getOwnPropertyNames;
15
- var __hasOwnProp = Object.prototype.hasOwnProperty;
16
- var __export = (target, all) => {
17
- for (var name in all)
18
- __defProp(target, name, { get: all[name], enumerable: true });
19
- };
20
- var __copyProps = (to, from, except, desc) => {
21
- if (from && typeof from === "object" || typeof from === "function") {
22
- for (let key of __getOwnPropNames(from))
23
- if (!__hasOwnProp.call(to, key) && key !== except)
24
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
25
- }
26
- return to;
27
- };
28
- var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
29
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
11
+ import * as React from 'react';
12
+ import * as ReactDOM from 'react-dom';
13
+ import { UNSAFE_mapRouteProperties, UNSAFE_logV6DeprecationWarnings, UNSAFE_DataRouterContext, UNSAFE_DataRouterStateContext, Router, UNSAFE_useRoutesImpl, UNSAFE_NavigationContext, useHref, useResolvedPath, useLocation, useNavigate, createPath, UNSAFE_useRouteId, UNSAFE_RouteContext, useMatches, useNavigation, useBlocker } from 'react-router';
14
+ export { AbortedDeferredError, Await, MemoryRouter, Navigate, NavigationType, Outlet, Route, Router, 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, redirectDocument, renderMatches, replace, resolvePath, useActionData, useAsyncError, useAsyncValue, useBlocker, useHref, useInRouterContext, useLoaderData, useLocation, useMatch, useMatches, useNavigate, useNavigation, useNavigationType, useOutlet, useOutletContext, useParams, useResolvedPath, useRevalidator, useRouteError, useRouteLoaderData, useRoutes } from 'react-router';
15
+ import { stripBasename, UNSAFE_warning, createRouter, createBrowserHistory, createHashHistory, UNSAFE_ErrorResponseImpl, UNSAFE_invariant, joinPaths, IDLE_FETCHER, matchPath } from '@remix-run/router';
16
+ export { UNSAFE_ErrorResponseImpl } from '@remix-run/router';
30
17
 
31
- // index.ts
32
- var react_router_dom_exports = {};
33
- __export(react_router_dom_exports, {
34
- HydratedRouter: () => import_dom.HydratedRouter,
35
- RouterProvider: () => import_dom.RouterProvider
18
+ function _extends() {
19
+ _extends = Object.assign ? Object.assign.bind() : function (target) {
20
+ for (var i = 1; i < arguments.length; i++) {
21
+ var source = arguments[i];
22
+ for (var key in source) {
23
+ if (Object.prototype.hasOwnProperty.call(source, key)) {
24
+ target[key] = source[key];
25
+ }
26
+ }
27
+ }
28
+ return target;
29
+ };
30
+ return _extends.apply(this, arguments);
31
+ }
32
+ function _objectWithoutPropertiesLoose(source, excluded) {
33
+ if (source == null) return {};
34
+ var target = {};
35
+ var sourceKeys = Object.keys(source);
36
+ var key, i;
37
+ for (i = 0; i < sourceKeys.length; i++) {
38
+ key = sourceKeys[i];
39
+ if (excluded.indexOf(key) >= 0) continue;
40
+ target[key] = source[key];
41
+ }
42
+ return target;
43
+ }
44
+
45
+ const defaultMethod = "get";
46
+ const defaultEncType = "application/x-www-form-urlencoded";
47
+ function isHtmlElement(object) {
48
+ return object != null && typeof object.tagName === "string";
49
+ }
50
+ function isButtonElement(object) {
51
+ return isHtmlElement(object) && object.tagName.toLowerCase() === "button";
52
+ }
53
+ function isFormElement(object) {
54
+ return isHtmlElement(object) && object.tagName.toLowerCase() === "form";
55
+ }
56
+ function isInputElement(object) {
57
+ return isHtmlElement(object) && object.tagName.toLowerCase() === "input";
58
+ }
59
+ function isModifiedEvent(event) {
60
+ return !!(event.metaKey || event.altKey || event.ctrlKey || event.shiftKey);
61
+ }
62
+ function shouldProcessLinkClick(event, target) {
63
+ return event.button === 0 && (
64
+ // Ignore everything but left clicks
65
+ !target || target === "_self") &&
66
+ // Let browser handle "target=_blank" etc.
67
+ !isModifiedEvent(event) // Ignore clicks with modifier keys
68
+ ;
69
+ }
70
+ /**
71
+ * Creates a URLSearchParams object using the given initializer.
72
+ *
73
+ * This is identical to `new URLSearchParams(init)` except it also
74
+ * supports arrays as values in the object form of the initializer
75
+ * instead of just strings. This is convenient when you need multiple
76
+ * values for a given key, but don't want to use an array initializer.
77
+ *
78
+ * For example, instead of:
79
+ *
80
+ * let searchParams = new URLSearchParams([
81
+ * ['sort', 'name'],
82
+ * ['sort', 'price']
83
+ * ]);
84
+ *
85
+ * you can do:
86
+ *
87
+ * let searchParams = createSearchParams({
88
+ * sort: ['name', 'price']
89
+ * });
90
+ */
91
+ function createSearchParams(init) {
92
+ if (init === void 0) {
93
+ init = "";
94
+ }
95
+ return new URLSearchParams(typeof init === "string" || Array.isArray(init) || init instanceof URLSearchParams ? init : Object.keys(init).reduce((memo, key) => {
96
+ let value = init[key];
97
+ return memo.concat(Array.isArray(value) ? value.map(v => [key, v]) : [[key, value]]);
98
+ }, []));
99
+ }
100
+ function getSearchParamsForLocation(locationSearch, defaultSearchParams) {
101
+ let searchParams = createSearchParams(locationSearch);
102
+ if (defaultSearchParams) {
103
+ // Use `defaultSearchParams.forEach(...)` here instead of iterating of
104
+ // `defaultSearchParams.keys()` to work-around a bug in Firefox related to
105
+ // web extensions. Relevant Bugzilla tickets:
106
+ // https://bugzilla.mozilla.org/show_bug.cgi?id=1414602
107
+ // https://bugzilla.mozilla.org/show_bug.cgi?id=1023984
108
+ defaultSearchParams.forEach((_, key) => {
109
+ if (!searchParams.has(key)) {
110
+ defaultSearchParams.getAll(key).forEach(value => {
111
+ searchParams.append(key, value);
112
+ });
113
+ }
114
+ });
115
+ }
116
+ return searchParams;
117
+ }
118
+ // One-time check for submitter support
119
+ let _formDataSupportsSubmitter = null;
120
+ function isFormDataSubmitterSupported() {
121
+ if (_formDataSupportsSubmitter === null) {
122
+ try {
123
+ new FormData(document.createElement("form"),
124
+ // @ts-expect-error if FormData supports the submitter parameter, this will throw
125
+ 0);
126
+ _formDataSupportsSubmitter = false;
127
+ } catch (e) {
128
+ _formDataSupportsSubmitter = true;
129
+ }
130
+ }
131
+ return _formDataSupportsSubmitter;
132
+ }
133
+ const supportedFormEncTypes = new Set(["application/x-www-form-urlencoded", "multipart/form-data", "text/plain"]);
134
+ function getFormEncType(encType) {
135
+ if (encType != null && !supportedFormEncTypes.has(encType)) {
136
+ process.env.NODE_ENV !== "production" ? UNSAFE_warning(false, "\"" + encType + "\" is not a valid `encType` for `<Form>`/`<fetcher.Form>` " + ("and will default to \"" + defaultEncType + "\"")) : void 0;
137
+ return null;
138
+ }
139
+ return encType;
140
+ }
141
+ function getFormSubmissionInfo(target, basename) {
142
+ let method;
143
+ let action;
144
+ let encType;
145
+ let formData;
146
+ let body;
147
+ if (isFormElement(target)) {
148
+ // When grabbing the action from the element, it will have had the basename
149
+ // prefixed to ensure non-JS scenarios work, so strip it since we'll
150
+ // re-prefix in the router
151
+ let attr = target.getAttribute("action");
152
+ action = attr ? stripBasename(attr, basename) : null;
153
+ method = target.getAttribute("method") || defaultMethod;
154
+ encType = getFormEncType(target.getAttribute("enctype")) || defaultEncType;
155
+ formData = new FormData(target);
156
+ } else if (isButtonElement(target) || isInputElement(target) && (target.type === "submit" || target.type === "image")) {
157
+ let form = target.form;
158
+ if (form == null) {
159
+ throw new Error("Cannot submit a <button> or <input type=\"submit\"> without a <form>");
160
+ }
161
+ // <button>/<input type="submit"> may override attributes of <form>
162
+ // When grabbing the action from the element, it will have had the basename
163
+ // prefixed to ensure non-JS scenarios work, so strip it since we'll
164
+ // re-prefix in the router
165
+ let attr = target.getAttribute("formaction") || form.getAttribute("action");
166
+ action = attr ? stripBasename(attr, basename) : null;
167
+ method = target.getAttribute("formmethod") || form.getAttribute("method") || defaultMethod;
168
+ encType = getFormEncType(target.getAttribute("formenctype")) || getFormEncType(form.getAttribute("enctype")) || defaultEncType;
169
+ // Build a FormData object populated from a form and submitter
170
+ formData = new FormData(form, target);
171
+ // If this browser doesn't support the `FormData(el, submitter)` format,
172
+ // then tack on the submitter value at the end. This is a lightweight
173
+ // solution that is not 100% spec compliant. For complete support in older
174
+ // browsers, consider using the `formdata-submitter-polyfill` package
175
+ if (!isFormDataSubmitterSupported()) {
176
+ let {
177
+ name,
178
+ type,
179
+ value
180
+ } = target;
181
+ if (type === "image") {
182
+ let prefix = name ? name + "." : "";
183
+ formData.append(prefix + "x", "0");
184
+ formData.append(prefix + "y", "0");
185
+ } else if (name) {
186
+ formData.append(name, value);
187
+ }
188
+ }
189
+ } else if (isHtmlElement(target)) {
190
+ throw new Error("Cannot submit element that is not <form>, <button>, or " + "<input type=\"submit|image\">");
191
+ } else {
192
+ method = defaultMethod;
193
+ action = null;
194
+ encType = defaultEncType;
195
+ body = target;
196
+ }
197
+ // Send body for <Form encType="text/plain" so we encode it into text
198
+ if (formData && encType === "text/plain") {
199
+ body = formData;
200
+ formData = undefined;
201
+ }
202
+ return {
203
+ action,
204
+ method: method.toLowerCase(),
205
+ encType,
206
+ formData,
207
+ body
208
+ };
209
+ }
210
+
211
+ const _excluded = ["onClick", "relative", "reloadDocument", "replace", "state", "target", "to", "preventScrollReset", "viewTransition"],
212
+ _excluded2 = ["aria-current", "caseSensitive", "className", "end", "style", "to", "viewTransition", "children"],
213
+ _excluded3 = ["fetcherKey", "navigate", "reloadDocument", "replace", "state", "method", "action", "onSubmit", "relative", "preventScrollReset", "viewTransition"];
214
+ // HEY YOU! DON'T TOUCH THIS VARIABLE!
215
+ //
216
+ // It is replaced with the proper version at build time via a babel plugin in
217
+ // the rollup config.
218
+ //
219
+ // Export a global property onto the window for React Router detection by the
220
+ // Core Web Vitals Technology Report. This way they can configure the `wappalyzer`
221
+ // to detect and properly classify live websites as being built with React Router:
222
+ // https://github.com/HTTPArchive/wappalyzer/blob/main/src/technologies/r.json
223
+ const REACT_ROUTER_VERSION = "0";
224
+ try {
225
+ window.__reactRouterVersion = REACT_ROUTER_VERSION;
226
+ } catch (e) {
227
+ // no-op
228
+ }
229
+ function createBrowserRouter(routes, opts) {
230
+ return createRouter({
231
+ basename: opts == null ? void 0 : opts.basename,
232
+ future: _extends({}, opts == null ? void 0 : opts.future, {
233
+ v7_prependBasename: true
234
+ }),
235
+ history: createBrowserHistory({
236
+ window: opts == null ? void 0 : opts.window
237
+ }),
238
+ hydrationData: (opts == null ? void 0 : opts.hydrationData) || parseHydrationData(),
239
+ routes,
240
+ mapRouteProperties: UNSAFE_mapRouteProperties,
241
+ dataStrategy: opts == null ? void 0 : opts.dataStrategy,
242
+ patchRoutesOnNavigation: opts == null ? void 0 : opts.patchRoutesOnNavigation,
243
+ window: opts == null ? void 0 : opts.window
244
+ }).initialize();
245
+ }
246
+ function createHashRouter(routes, opts) {
247
+ return createRouter({
248
+ basename: opts == null ? void 0 : opts.basename,
249
+ future: _extends({}, opts == null ? void 0 : opts.future, {
250
+ v7_prependBasename: true
251
+ }),
252
+ history: createHashHistory({
253
+ window: opts == null ? void 0 : opts.window
254
+ }),
255
+ hydrationData: (opts == null ? void 0 : opts.hydrationData) || parseHydrationData(),
256
+ routes,
257
+ mapRouteProperties: UNSAFE_mapRouteProperties,
258
+ dataStrategy: opts == null ? void 0 : opts.dataStrategy,
259
+ patchRoutesOnNavigation: opts == null ? void 0 : opts.patchRoutesOnNavigation,
260
+ window: opts == null ? void 0 : opts.window
261
+ }).initialize();
262
+ }
263
+ function parseHydrationData() {
264
+ var _window;
265
+ let state = (_window = window) == null ? void 0 : _window.__staticRouterHydrationData;
266
+ if (state && state.errors) {
267
+ state = _extends({}, state, {
268
+ errors: deserializeErrors(state.errors)
269
+ });
270
+ }
271
+ return state;
272
+ }
273
+ function deserializeErrors(errors) {
274
+ if (!errors) return null;
275
+ let entries = Object.entries(errors);
276
+ let serialized = {};
277
+ for (let [key, val] of entries) {
278
+ // Hey you! If you change this, please change the corresponding logic in
279
+ // serializeErrors in react-router-dom/server.tsx :)
280
+ if (val && val.__type === "RouteErrorResponse") {
281
+ serialized[key] = new UNSAFE_ErrorResponseImpl(val.status, val.statusText, val.data, val.internal === true);
282
+ } else if (val && val.__type === "Error") {
283
+ // Attempt to reconstruct the right type of Error (i.e., ReferenceError)
284
+ if (val.__subType) {
285
+ let ErrorConstructor = window[val.__subType];
286
+ if (typeof ErrorConstructor === "function") {
287
+ try {
288
+ // @ts-expect-error
289
+ let error = new ErrorConstructor(val.message);
290
+ // Wipe away the client-side stack trace. Nothing to fill it in with
291
+ // because we don't serialize SSR stack traces for security reasons
292
+ error.stack = "";
293
+ serialized[key] = error;
294
+ } catch (e) {
295
+ // no-op - fall through and create a normal Error
296
+ }
297
+ }
298
+ }
299
+ if (serialized[key] == null) {
300
+ let error = new Error(val.message);
301
+ // Wipe away the client-side stack trace. Nothing to fill it in with
302
+ // because we don't serialize SSR stack traces for security reasons
303
+ error.stack = "";
304
+ serialized[key] = error;
305
+ }
306
+ } else {
307
+ serialized[key] = val;
308
+ }
309
+ }
310
+ return serialized;
311
+ }
312
+ const ViewTransitionContext = /*#__PURE__*/React.createContext({
313
+ isTransitioning: false
36
314
  });
37
- module.exports = __toCommonJS(react_router_dom_exports);
38
- var import_dom = require("react-router/dom");
39
- __reExport(react_router_dom_exports, require("react-router"), module.exports);
40
- // Annotate the CommonJS export names for ESM import in node:
41
- 0 && (module.exports = {
42
- HydratedRouter,
43
- RouterProvider,
44
- ...require("react-router")
315
+ if (process.env.NODE_ENV !== "production") {
316
+ ViewTransitionContext.displayName = "ViewTransition";
317
+ }
318
+ const FetchersContext = /*#__PURE__*/React.createContext(new Map());
319
+ if (process.env.NODE_ENV !== "production") {
320
+ FetchersContext.displayName = "Fetchers";
321
+ }
322
+ //#endregion
323
+ ////////////////////////////////////////////////////////////////////////////////
324
+ //#region Components
325
+ ////////////////////////////////////////////////////////////////////////////////
326
+ /**
327
+ Webpack + React 17 fails to compile on any of the following because webpack
328
+ complains that `startTransition` doesn't exist in `React`:
329
+ * import { startTransition } from "react"
330
+ * import * as React from from "react";
331
+ "startTransition" in React ? React.startTransition(() => setState()) : setState()
332
+ * import * as React from from "react";
333
+ "startTransition" in React ? React["startTransition"](() => setState()) : setState()
334
+
335
+ Moving it to a constant such as the following solves the Webpack/React 17 issue:
336
+ * import * as React from from "react";
337
+ const START_TRANSITION = "startTransition";
338
+ START_TRANSITION in React ? React[START_TRANSITION](() => setState()) : setState()
339
+
340
+ However, that introduces webpack/terser minification issues in production builds
341
+ in React 18 where minification/obfuscation ends up removing the call of
342
+ React.startTransition entirely from the first half of the ternary. Grabbing
343
+ this exported reference once up front resolves that issue.
344
+
345
+ See https://github.com/remix-run/react-router/issues/10579
346
+ */
347
+ const START_TRANSITION = "startTransition";
348
+ const startTransitionImpl = React[START_TRANSITION];
349
+ const FLUSH_SYNC = "flushSync";
350
+ const flushSyncImpl = ReactDOM[FLUSH_SYNC];
351
+ const USE_ID = "useId";
352
+ const useIdImpl = React[USE_ID];
353
+ function startTransitionSafe(cb) {
354
+ if (startTransitionImpl) {
355
+ startTransitionImpl(cb);
356
+ } else {
357
+ cb();
358
+ }
359
+ }
360
+ function flushSyncSafe(cb) {
361
+ if (flushSyncImpl) {
362
+ flushSyncImpl(cb);
363
+ } else {
364
+ cb();
365
+ }
366
+ }
367
+ class Deferred {
368
+ constructor() {
369
+ this.status = "pending";
370
+ this.promise = new Promise((resolve, reject) => {
371
+ this.resolve = value => {
372
+ if (this.status === "pending") {
373
+ this.status = "resolved";
374
+ resolve(value);
375
+ }
376
+ };
377
+ this.reject = reason => {
378
+ if (this.status === "pending") {
379
+ this.status = "rejected";
380
+ reject(reason);
381
+ }
382
+ };
383
+ });
384
+ }
385
+ }
386
+ /**
387
+ * Given a Remix Router instance, render the appropriate UI
388
+ */
389
+ function RouterProvider(_ref) {
390
+ let {
391
+ fallbackElement,
392
+ router,
393
+ future
394
+ } = _ref;
395
+ let [state, setStateImpl] = React.useState(router.state);
396
+ let [pendingState, setPendingState] = React.useState();
397
+ let [vtContext, setVtContext] = React.useState({
398
+ isTransitioning: false
399
+ });
400
+ let [renderDfd, setRenderDfd] = React.useState();
401
+ let [transition, setTransition] = React.useState();
402
+ let [interruption, setInterruption] = React.useState();
403
+ let fetcherData = React.useRef(new Map());
404
+ let {
405
+ v7_startTransition
406
+ } = future || {};
407
+ let optInStartTransition = React.useCallback(cb => {
408
+ if (v7_startTransition) {
409
+ startTransitionSafe(cb);
410
+ } else {
411
+ cb();
412
+ }
413
+ }, [v7_startTransition]);
414
+ let setState = React.useCallback((newState, _ref2) => {
415
+ let {
416
+ deletedFetchers,
417
+ flushSync,
418
+ viewTransitionOpts
419
+ } = _ref2;
420
+ newState.fetchers.forEach((fetcher, key) => {
421
+ if (fetcher.data !== undefined) {
422
+ fetcherData.current.set(key, fetcher.data);
423
+ }
424
+ });
425
+ deletedFetchers.forEach(key => fetcherData.current.delete(key));
426
+ let isViewTransitionUnavailable = router.window == null || router.window.document == null || typeof router.window.document.startViewTransition !== "function";
427
+ // If this isn't a view transition or it's not available in this browser,
428
+ // just update and be done with it
429
+ if (!viewTransitionOpts || isViewTransitionUnavailable) {
430
+ renderDfd == null ? void 0 : renderDfd.resolve();
431
+ transition == null ? void 0 : transition.skipTransition();
432
+ if (flushSync) {
433
+ flushSyncSafe(() => {
434
+ setStateImpl(newState);
435
+ setRenderDfd(undefined);
436
+ setTransition(undefined);
437
+ setPendingState(undefined);
438
+ setVtContext({
439
+ isTransitioning: false
440
+ });
441
+ });
442
+ } else {
443
+ optInStartTransition(() => {
444
+ setStateImpl(newState);
445
+ setRenderDfd(undefined);
446
+ setTransition(undefined);
447
+ setPendingState(undefined);
448
+ setVtContext({
449
+ isTransitioning: false
450
+ });
451
+ });
452
+ }
453
+ return;
454
+ }
455
+ // flushSync + startViewTransition
456
+ if (flushSync) {
457
+ // Flush through the context to mark DOM elements as transition=ing
458
+ flushSyncSafe(() => {
459
+ // Cancel any pending transitions
460
+ if (transition) {
461
+ renderDfd && renderDfd.resolve();
462
+ transition.skipTransition();
463
+ }
464
+ setVtContext({
465
+ isTransitioning: true,
466
+ flushSync: true,
467
+ currentLocation: viewTransitionOpts.currentLocation,
468
+ nextLocation: viewTransitionOpts.nextLocation
469
+ });
470
+ });
471
+ // Update the DOM
472
+ let t = router.window.document.startViewTransition(() => {
473
+ flushSyncSafe(() => setStateImpl(newState));
474
+ });
475
+ // Clean up after the animation completes
476
+ t.finished.finally(() => {
477
+ flushSyncSafe(() => {
478
+ setRenderDfd(undefined);
479
+ setTransition(undefined);
480
+ setPendingState(undefined);
481
+ setVtContext({
482
+ isTransitioning: false
483
+ });
484
+ });
485
+ });
486
+ flushSyncSafe(() => setTransition(t));
487
+ return;
488
+ }
489
+ // startTransition + startViewTransition
490
+ if (transition) {
491
+ // Interrupting an in-progress transition, cancel and let everything flush
492
+ // out, and then kick off a new transition from the interruption state
493
+ renderDfd && renderDfd.resolve();
494
+ transition.skipTransition();
495
+ setInterruption({
496
+ state: newState,
497
+ currentLocation: viewTransitionOpts.currentLocation,
498
+ nextLocation: viewTransitionOpts.nextLocation
499
+ });
500
+ } else {
501
+ // Completed navigation update with opted-in view transitions, let 'er rip
502
+ setPendingState(newState);
503
+ setVtContext({
504
+ isTransitioning: true,
505
+ flushSync: false,
506
+ currentLocation: viewTransitionOpts.currentLocation,
507
+ nextLocation: viewTransitionOpts.nextLocation
508
+ });
509
+ }
510
+ }, [router.window, transition, renderDfd, optInStartTransition]);
511
+ // Need to use a layout effect here so we are subscribed early enough to
512
+ // pick up on any render-driven redirects/navigations (useEffect/<Navigate>)
513
+ React.useLayoutEffect(() => router.subscribe(setState), [router, setState]);
514
+ // When we start a view transition, create a Deferred we can use for the
515
+ // eventual "completed" render
516
+ React.useEffect(() => {
517
+ if (vtContext.isTransitioning && !vtContext.flushSync) {
518
+ setRenderDfd(new Deferred());
519
+ }
520
+ }, [vtContext]);
521
+ // Once the deferred is created, kick off startViewTransition() to update the
522
+ // DOM and then wait on the Deferred to resolve (indicating the DOM update has
523
+ // happened)
524
+ React.useEffect(() => {
525
+ if (renderDfd && pendingState && router.window) {
526
+ let newState = pendingState;
527
+ let renderPromise = renderDfd.promise;
528
+ let transition = router.window.document.startViewTransition(async () => {
529
+ optInStartTransition(() => setStateImpl(newState));
530
+ await renderPromise;
531
+ });
532
+ transition.finished.finally(() => {
533
+ setRenderDfd(undefined);
534
+ setTransition(undefined);
535
+ setPendingState(undefined);
536
+ setVtContext({
537
+ isTransitioning: false
538
+ });
539
+ });
540
+ setTransition(transition);
541
+ }
542
+ }, [optInStartTransition, pendingState, renderDfd, router.window]);
543
+ // When the new location finally renders and is committed to the DOM, this
544
+ // effect will run to resolve the transition
545
+ React.useEffect(() => {
546
+ if (renderDfd && pendingState && state.location.key === pendingState.location.key) {
547
+ renderDfd.resolve();
548
+ }
549
+ }, [renderDfd, transition, state.location, pendingState]);
550
+ // If we get interrupted with a new navigation during a transition, we skip
551
+ // the active transition, let it cleanup, then kick it off again here
552
+ React.useEffect(() => {
553
+ if (!vtContext.isTransitioning && interruption) {
554
+ setPendingState(interruption.state);
555
+ setVtContext({
556
+ isTransitioning: true,
557
+ flushSync: false,
558
+ currentLocation: interruption.currentLocation,
559
+ nextLocation: interruption.nextLocation
560
+ });
561
+ setInterruption(undefined);
562
+ }
563
+ }, [vtContext.isTransitioning, interruption]);
564
+ React.useEffect(() => {
565
+ process.env.NODE_ENV !== "production" ? UNSAFE_warning(fallbackElement == null || !router.future.v7_partialHydration, "`<RouterProvider fallbackElement>` is deprecated when using " + "`v7_partialHydration`, use a `HydrateFallback` component instead") : void 0;
566
+ // Only log this once on initial mount
567
+ // eslint-disable-next-line react-hooks/exhaustive-deps
568
+ }, []);
569
+ let navigator = React.useMemo(() => {
570
+ return {
571
+ createHref: router.createHref,
572
+ encodeLocation: router.encodeLocation,
573
+ go: n => router.navigate(n),
574
+ push: (to, state, opts) => router.navigate(to, {
575
+ state,
576
+ preventScrollReset: opts == null ? void 0 : opts.preventScrollReset
577
+ }),
578
+ replace: (to, state, opts) => router.navigate(to, {
579
+ replace: true,
580
+ state,
581
+ preventScrollReset: opts == null ? void 0 : opts.preventScrollReset
582
+ })
583
+ };
584
+ }, [router]);
585
+ let basename = router.basename || "/";
586
+ let dataRouterContext = React.useMemo(() => ({
587
+ router,
588
+ navigator,
589
+ static: false,
590
+ basename
591
+ }), [router, navigator, basename]);
592
+ let routerFuture = React.useMemo(() => ({
593
+ v7_relativeSplatPath: router.future.v7_relativeSplatPath
594
+ }), [router.future.v7_relativeSplatPath]);
595
+ React.useEffect(() => UNSAFE_logV6DeprecationWarnings(future, router.future), [future, router.future]);
596
+ // The fragment and {null} here are important! We need them to keep React 18's
597
+ // useId happy when we are server-rendering since we may have a <script> here
598
+ // containing the hydrated server-side staticContext (from StaticRouterProvider).
599
+ // useId relies on the component tree structure to generate deterministic id's
600
+ // so we need to ensure it remains the same on the client even though
601
+ // we don't need the <script> tag
602
+ return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(UNSAFE_DataRouterContext.Provider, {
603
+ value: dataRouterContext
604
+ }, /*#__PURE__*/React.createElement(UNSAFE_DataRouterStateContext.Provider, {
605
+ value: state
606
+ }, /*#__PURE__*/React.createElement(FetchersContext.Provider, {
607
+ value: fetcherData.current
608
+ }, /*#__PURE__*/React.createElement(ViewTransitionContext.Provider, {
609
+ value: vtContext
610
+ }, /*#__PURE__*/React.createElement(Router, {
611
+ basename: basename,
612
+ location: state.location,
613
+ navigationType: state.historyAction,
614
+ navigator: navigator,
615
+ future: routerFuture
616
+ }, state.initialized || router.future.v7_partialHydration ? /*#__PURE__*/React.createElement(MemoizedDataRoutes, {
617
+ routes: router.routes,
618
+ future: router.future,
619
+ state: state
620
+ }) : fallbackElement))))), null);
621
+ }
622
+ // Memoize to avoid re-renders when updating `ViewTransitionContext`
623
+ const MemoizedDataRoutes = /*#__PURE__*/React.memo(DataRoutes);
624
+ function DataRoutes(_ref3) {
625
+ let {
626
+ routes,
627
+ future,
628
+ state
629
+ } = _ref3;
630
+ return UNSAFE_useRoutesImpl(routes, undefined, state, future);
631
+ }
632
+ /**
633
+ * A `<Router>` for use in web browsers. Provides the cleanest URLs.
634
+ */
635
+ function BrowserRouter(_ref4) {
636
+ let {
637
+ basename,
638
+ children,
639
+ future,
640
+ window
641
+ } = _ref4;
642
+ let historyRef = React.useRef();
643
+ if (historyRef.current == null) {
644
+ historyRef.current = createBrowserHistory({
645
+ window,
646
+ v5Compat: true
647
+ });
648
+ }
649
+ let history = historyRef.current;
650
+ let [state, setStateImpl] = React.useState({
651
+ action: history.action,
652
+ location: history.location
653
+ });
654
+ let {
655
+ v7_startTransition
656
+ } = future || {};
657
+ let setState = React.useCallback(newState => {
658
+ v7_startTransition && startTransitionImpl ? startTransitionImpl(() => setStateImpl(newState)) : setStateImpl(newState);
659
+ }, [setStateImpl, v7_startTransition]);
660
+ React.useLayoutEffect(() => history.listen(setState), [history, setState]);
661
+ React.useEffect(() => UNSAFE_logV6DeprecationWarnings(future), [future]);
662
+ return /*#__PURE__*/React.createElement(Router, {
663
+ basename: basename,
664
+ children: children,
665
+ location: state.location,
666
+ navigationType: state.action,
667
+ navigator: history,
668
+ future: future
669
+ });
670
+ }
671
+ /**
672
+ * A `<Router>` for use in web browsers. Stores the location in the hash
673
+ * portion of the URL so it is not sent to the server.
674
+ */
675
+ function HashRouter(_ref5) {
676
+ let {
677
+ basename,
678
+ children,
679
+ future,
680
+ window
681
+ } = _ref5;
682
+ let historyRef = React.useRef();
683
+ if (historyRef.current == null) {
684
+ historyRef.current = createHashHistory({
685
+ window,
686
+ v5Compat: true
687
+ });
688
+ }
689
+ let history = historyRef.current;
690
+ let [state, setStateImpl] = React.useState({
691
+ action: history.action,
692
+ location: history.location
693
+ });
694
+ let {
695
+ v7_startTransition
696
+ } = future || {};
697
+ let setState = React.useCallback(newState => {
698
+ v7_startTransition && startTransitionImpl ? startTransitionImpl(() => setStateImpl(newState)) : setStateImpl(newState);
699
+ }, [setStateImpl, v7_startTransition]);
700
+ React.useLayoutEffect(() => history.listen(setState), [history, setState]);
701
+ React.useEffect(() => UNSAFE_logV6DeprecationWarnings(future), [future]);
702
+ return /*#__PURE__*/React.createElement(Router, {
703
+ basename: basename,
704
+ children: children,
705
+ location: state.location,
706
+ navigationType: state.action,
707
+ navigator: history,
708
+ future: future
709
+ });
710
+ }
711
+ /**
712
+ * A `<Router>` that accepts a pre-instantiated history object. It's important
713
+ * to note that using your own history object is highly discouraged and may add
714
+ * two versions of the history library to your bundles unless you use the same
715
+ * version of the history library that React Router uses internally.
716
+ */
717
+ function HistoryRouter(_ref6) {
718
+ let {
719
+ basename,
720
+ children,
721
+ future,
722
+ history
723
+ } = _ref6;
724
+ let [state, setStateImpl] = React.useState({
725
+ action: history.action,
726
+ location: history.location
727
+ });
728
+ let {
729
+ v7_startTransition
730
+ } = future || {};
731
+ let setState = React.useCallback(newState => {
732
+ v7_startTransition && startTransitionImpl ? startTransitionImpl(() => setStateImpl(newState)) : setStateImpl(newState);
733
+ }, [setStateImpl, v7_startTransition]);
734
+ React.useLayoutEffect(() => history.listen(setState), [history, setState]);
735
+ React.useEffect(() => UNSAFE_logV6DeprecationWarnings(future), [future]);
736
+ return /*#__PURE__*/React.createElement(Router, {
737
+ basename: basename,
738
+ children: children,
739
+ location: state.location,
740
+ navigationType: state.action,
741
+ navigator: history,
742
+ future: future
743
+ });
744
+ }
745
+ if (process.env.NODE_ENV !== "production") {
746
+ HistoryRouter.displayName = "unstable_HistoryRouter";
747
+ }
748
+ const isBrowser = typeof window !== "undefined" && typeof window.document !== "undefined" && typeof window.document.createElement !== "undefined";
749
+ const ABSOLUTE_URL_REGEX = /^(?:[a-z][a-z0-9+.-]*:|\/\/)/i;
750
+ /**
751
+ * The public API for rendering a history-aware `<a>`.
752
+ */
753
+ const Link = /*#__PURE__*/React.forwardRef(function LinkWithRef(_ref7, ref) {
754
+ let {
755
+ onClick,
756
+ relative,
757
+ reloadDocument,
758
+ replace,
759
+ state,
760
+ target,
761
+ to,
762
+ preventScrollReset,
763
+ viewTransition
764
+ } = _ref7,
765
+ rest = _objectWithoutPropertiesLoose(_ref7, _excluded);
766
+ let {
767
+ basename
768
+ } = React.useContext(UNSAFE_NavigationContext);
769
+ // Rendered into <a href> for absolute URLs
770
+ let absoluteHref;
771
+ let isExternal = false;
772
+ if (typeof to === "string" && ABSOLUTE_URL_REGEX.test(to)) {
773
+ // Render the absolute href server- and client-side
774
+ absoluteHref = to;
775
+ // Only check for external origins client-side
776
+ if (isBrowser) {
777
+ try {
778
+ let currentUrl = new URL(window.location.href);
779
+ let targetUrl = to.startsWith("//") ? new URL(currentUrl.protocol + to) : new URL(to);
780
+ let path = stripBasename(targetUrl.pathname, basename);
781
+ if (targetUrl.origin === currentUrl.origin && path != null) {
782
+ // Strip the protocol/origin/basename for same-origin absolute URLs
783
+ to = path + targetUrl.search + targetUrl.hash;
784
+ } else {
785
+ isExternal = true;
786
+ }
787
+ } catch (e) {
788
+ // We can't do external URL detection without a valid URL
789
+ 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;
790
+ }
791
+ }
792
+ }
793
+ // Rendered into <a href> for relative URLs
794
+ let href = useHref(to, {
795
+ relative
796
+ });
797
+ let internalOnClick = useLinkClickHandler(to, {
798
+ replace,
799
+ state,
800
+ target,
801
+ preventScrollReset,
802
+ relative,
803
+ viewTransition
804
+ });
805
+ function handleClick(event) {
806
+ if (onClick) onClick(event);
807
+ if (!event.defaultPrevented) {
808
+ internalOnClick(event);
809
+ }
810
+ }
811
+ return (
812
+ /*#__PURE__*/
813
+ // eslint-disable-next-line jsx-a11y/anchor-has-content
814
+ React.createElement("a", _extends({}, rest, {
815
+ href: absoluteHref || href,
816
+ onClick: isExternal || reloadDocument ? onClick : handleClick,
817
+ ref: ref,
818
+ target: target
819
+ }))
820
+ );
45
821
  });
822
+ if (process.env.NODE_ENV !== "production") {
823
+ Link.displayName = "Link";
824
+ }
825
+ /**
826
+ * A `<Link>` wrapper that knows if it's "active" or not.
827
+ */
828
+ const NavLink = /*#__PURE__*/React.forwardRef(function NavLinkWithRef(_ref8, ref) {
829
+ let {
830
+ "aria-current": ariaCurrentProp = "page",
831
+ caseSensitive = false,
832
+ className: classNameProp = "",
833
+ end = false,
834
+ style: styleProp,
835
+ to,
836
+ viewTransition,
837
+ children
838
+ } = _ref8,
839
+ rest = _objectWithoutPropertiesLoose(_ref8, _excluded2);
840
+ let path = useResolvedPath(to, {
841
+ relative: rest.relative
842
+ });
843
+ let location = useLocation();
844
+ let routerState = React.useContext(UNSAFE_DataRouterStateContext);
845
+ let {
846
+ navigator,
847
+ basename
848
+ } = React.useContext(UNSAFE_NavigationContext);
849
+ let isTransitioning = routerState != null &&
850
+ // Conditional usage is OK here because the usage of a data router is static
851
+ // eslint-disable-next-line react-hooks/rules-of-hooks
852
+ useViewTransitionState(path) && viewTransition === true;
853
+ let toPathname = navigator.encodeLocation ? navigator.encodeLocation(path).pathname : path.pathname;
854
+ let locationPathname = location.pathname;
855
+ let nextLocationPathname = routerState && routerState.navigation && routerState.navigation.location ? routerState.navigation.location.pathname : null;
856
+ if (!caseSensitive) {
857
+ locationPathname = locationPathname.toLowerCase();
858
+ nextLocationPathname = nextLocationPathname ? nextLocationPathname.toLowerCase() : null;
859
+ toPathname = toPathname.toLowerCase();
860
+ }
861
+ if (nextLocationPathname && basename) {
862
+ nextLocationPathname = stripBasename(nextLocationPathname, basename) || nextLocationPathname;
863
+ }
864
+ // If the `to` has a trailing slash, look at that exact spot. Otherwise,
865
+ // we're looking for a slash _after_ what's in `to`. For example:
866
+ //
867
+ // <NavLink to="/users"> and <NavLink to="/users/">
868
+ // both want to look for a / at index 6 to match URL `/users/matt`
869
+ const endSlashPosition = toPathname !== "/" && toPathname.endsWith("/") ? toPathname.length - 1 : toPathname.length;
870
+ let isActive = locationPathname === toPathname || !end && locationPathname.startsWith(toPathname) && locationPathname.charAt(endSlashPosition) === "/";
871
+ let isPending = nextLocationPathname != null && (nextLocationPathname === toPathname || !end && nextLocationPathname.startsWith(toPathname) && nextLocationPathname.charAt(toPathname.length) === "/");
872
+ let renderProps = {
873
+ isActive,
874
+ isPending,
875
+ isTransitioning
876
+ };
877
+ let ariaCurrent = isActive ? ariaCurrentProp : undefined;
878
+ let className;
879
+ if (typeof classNameProp === "function") {
880
+ className = classNameProp(renderProps);
881
+ } else {
882
+ // If the className prop is not a function, we use a default `active`
883
+ // class for <NavLink />s that are active. In v5 `active` was the default
884
+ // value for `activeClassName`, but we are removing that API and can still
885
+ // use the old default behavior for a cleaner upgrade path and keep the
886
+ // simple styling rules working as they currently do.
887
+ className = [classNameProp, isActive ? "active" : null, isPending ? "pending" : null, isTransitioning ? "transitioning" : null].filter(Boolean).join(" ");
888
+ }
889
+ let style = typeof styleProp === "function" ? styleProp(renderProps) : styleProp;
890
+ return /*#__PURE__*/React.createElement(Link, _extends({}, rest, {
891
+ "aria-current": ariaCurrent,
892
+ className: className,
893
+ ref: ref,
894
+ style: style,
895
+ to: to,
896
+ viewTransition: viewTransition
897
+ }), typeof children === "function" ? children(renderProps) : children);
898
+ });
899
+ if (process.env.NODE_ENV !== "production") {
900
+ NavLink.displayName = "NavLink";
901
+ }
902
+ /**
903
+ * A `@remix-run/router`-aware `<form>`. It behaves like a normal form except
904
+ * that the interaction with the server is with `fetch` instead of new document
905
+ * requests, allowing components to add nicer UX to the page as the form is
906
+ * submitted and returns with data.
907
+ */
908
+ const Form = /*#__PURE__*/React.forwardRef((_ref9, forwardedRef) => {
909
+ let {
910
+ fetcherKey,
911
+ navigate,
912
+ reloadDocument,
913
+ replace,
914
+ state,
915
+ method = defaultMethod,
916
+ action,
917
+ onSubmit,
918
+ relative,
919
+ preventScrollReset,
920
+ viewTransition
921
+ } = _ref9,
922
+ props = _objectWithoutPropertiesLoose(_ref9, _excluded3);
923
+ let submit = useSubmit();
924
+ let formAction = useFormAction(action, {
925
+ relative
926
+ });
927
+ let formMethod = method.toLowerCase() === "get" ? "get" : "post";
928
+ let submitHandler = event => {
929
+ onSubmit && onSubmit(event);
930
+ if (event.defaultPrevented) return;
931
+ event.preventDefault();
932
+ let submitter = event.nativeEvent.submitter;
933
+ let submitMethod = (submitter == null ? void 0 : submitter.getAttribute("formmethod")) || method;
934
+ submit(submitter || event.currentTarget, {
935
+ fetcherKey,
936
+ method: submitMethod,
937
+ navigate,
938
+ replace,
939
+ state,
940
+ relative,
941
+ preventScrollReset,
942
+ viewTransition
943
+ });
944
+ };
945
+ return /*#__PURE__*/React.createElement("form", _extends({
946
+ ref: forwardedRef,
947
+ method: formMethod,
948
+ action: formAction,
949
+ onSubmit: reloadDocument ? onSubmit : submitHandler
950
+ }, props));
951
+ });
952
+ if (process.env.NODE_ENV !== "production") {
953
+ Form.displayName = "Form";
954
+ }
955
+ /**
956
+ * This component will emulate the browser's scroll restoration on location
957
+ * changes.
958
+ */
959
+ function ScrollRestoration(_ref10) {
960
+ let {
961
+ getKey,
962
+ storageKey
963
+ } = _ref10;
964
+ useScrollRestoration({
965
+ getKey,
966
+ storageKey
967
+ });
968
+ return null;
969
+ }
970
+ if (process.env.NODE_ENV !== "production") {
971
+ ScrollRestoration.displayName = "ScrollRestoration";
972
+ }
973
+ //#endregion
974
+ ////////////////////////////////////////////////////////////////////////////////
975
+ //#region Hooks
976
+ ////////////////////////////////////////////////////////////////////////////////
977
+ var DataRouterHook;
978
+ (function (DataRouterHook) {
979
+ DataRouterHook["UseScrollRestoration"] = "useScrollRestoration";
980
+ DataRouterHook["UseSubmit"] = "useSubmit";
981
+ DataRouterHook["UseSubmitFetcher"] = "useSubmitFetcher";
982
+ DataRouterHook["UseFetcher"] = "useFetcher";
983
+ DataRouterHook["useViewTransitionState"] = "useViewTransitionState";
984
+ })(DataRouterHook || (DataRouterHook = {}));
985
+ var DataRouterStateHook;
986
+ (function (DataRouterStateHook) {
987
+ DataRouterStateHook["UseFetcher"] = "useFetcher";
988
+ DataRouterStateHook["UseFetchers"] = "useFetchers";
989
+ DataRouterStateHook["UseScrollRestoration"] = "useScrollRestoration";
990
+ })(DataRouterStateHook || (DataRouterStateHook = {}));
991
+ // Internal hooks
992
+ function getDataRouterConsoleError(hookName) {
993
+ return hookName + " must be used within a data router. See https://reactrouter.com/v6/routers/picking-a-router.";
994
+ }
995
+ function useDataRouterContext(hookName) {
996
+ let ctx = React.useContext(UNSAFE_DataRouterContext);
997
+ !ctx ? process.env.NODE_ENV !== "production" ? UNSAFE_invariant(false, getDataRouterConsoleError(hookName)) : UNSAFE_invariant(false) : void 0;
998
+ return ctx;
999
+ }
1000
+ function useDataRouterState(hookName) {
1001
+ let state = React.useContext(UNSAFE_DataRouterStateContext);
1002
+ !state ? process.env.NODE_ENV !== "production" ? UNSAFE_invariant(false, getDataRouterConsoleError(hookName)) : UNSAFE_invariant(false) : void 0;
1003
+ return state;
1004
+ }
1005
+ // External hooks
1006
+ /**
1007
+ * Handles the click behavior for router `<Link>` components. This is useful if
1008
+ * you need to create custom `<Link>` components with the same click behavior we
1009
+ * use in our exported `<Link>`.
1010
+ */
1011
+ function useLinkClickHandler(to, _temp) {
1012
+ let {
1013
+ target,
1014
+ replace: replaceProp,
1015
+ state,
1016
+ preventScrollReset,
1017
+ relative,
1018
+ viewTransition
1019
+ } = _temp === void 0 ? {} : _temp;
1020
+ let navigate = useNavigate();
1021
+ let location = useLocation();
1022
+ let path = useResolvedPath(to, {
1023
+ relative
1024
+ });
1025
+ return React.useCallback(event => {
1026
+ if (shouldProcessLinkClick(event, target)) {
1027
+ event.preventDefault();
1028
+ // If the URL hasn't changed, a regular <a> will do a replace instead of
1029
+ // a push, so do the same here unless the replace prop is explicitly set
1030
+ let replace = replaceProp !== undefined ? replaceProp : createPath(location) === createPath(path);
1031
+ navigate(to, {
1032
+ replace,
1033
+ state,
1034
+ preventScrollReset,
1035
+ relative,
1036
+ viewTransition
1037
+ });
1038
+ }
1039
+ }, [location, navigate, path, replaceProp, state, target, to, preventScrollReset, relative, viewTransition]);
1040
+ }
1041
+ /**
1042
+ * A convenient wrapper for reading and writing search parameters via the
1043
+ * URLSearchParams interface.
1044
+ */
1045
+ function useSearchParams(defaultInit) {
1046
+ 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.") : void 0;
1047
+ let defaultSearchParamsRef = React.useRef(createSearchParams(defaultInit));
1048
+ let hasSetSearchParamsRef = React.useRef(false);
1049
+ let location = useLocation();
1050
+ let searchParams = React.useMemo(() =>
1051
+ // Only merge in the defaults if we haven't yet called setSearchParams.
1052
+ // Once we call that we want those to take precedence, otherwise you can't
1053
+ // remove a param with setSearchParams({}) if it has an initial value
1054
+ getSearchParamsForLocation(location.search, hasSetSearchParamsRef.current ? null : defaultSearchParamsRef.current), [location.search]);
1055
+ let navigate = useNavigate();
1056
+ let setSearchParams = React.useCallback((nextInit, navigateOptions) => {
1057
+ const newSearchParams = createSearchParams(typeof nextInit === "function" ? nextInit(searchParams) : nextInit);
1058
+ hasSetSearchParamsRef.current = true;
1059
+ navigate("?" + newSearchParams, navigateOptions);
1060
+ }, [navigate, searchParams]);
1061
+ return [searchParams, setSearchParams];
1062
+ }
1063
+ function validateClientSideSubmission() {
1064
+ if (typeof document === "undefined") {
1065
+ throw new Error("You are calling submit during the server render. " + "Try calling submit within a `useEffect` or callback instead.");
1066
+ }
1067
+ }
1068
+ let fetcherId = 0;
1069
+ let getUniqueFetcherId = () => "__" + String(++fetcherId) + "__";
1070
+ /**
1071
+ * Returns a function that may be used to programmatically submit a form (or
1072
+ * some arbitrary data) to the server.
1073
+ */
1074
+ function useSubmit() {
1075
+ let {
1076
+ router
1077
+ } = useDataRouterContext(DataRouterHook.UseSubmit);
1078
+ let {
1079
+ basename
1080
+ } = React.useContext(UNSAFE_NavigationContext);
1081
+ let currentRouteId = UNSAFE_useRouteId();
1082
+ return React.useCallback(function (target, options) {
1083
+ if (options === void 0) {
1084
+ options = {};
1085
+ }
1086
+ validateClientSideSubmission();
1087
+ let {
1088
+ action,
1089
+ method,
1090
+ encType,
1091
+ formData,
1092
+ body
1093
+ } = getFormSubmissionInfo(target, basename);
1094
+ if (options.navigate === false) {
1095
+ let key = options.fetcherKey || getUniqueFetcherId();
1096
+ router.fetch(key, currentRouteId, options.action || action, {
1097
+ preventScrollReset: options.preventScrollReset,
1098
+ formData,
1099
+ body,
1100
+ formMethod: options.method || method,
1101
+ formEncType: options.encType || encType,
1102
+ flushSync: options.flushSync
1103
+ });
1104
+ } else {
1105
+ router.navigate(options.action || action, {
1106
+ preventScrollReset: options.preventScrollReset,
1107
+ formData,
1108
+ body,
1109
+ formMethod: options.method || method,
1110
+ formEncType: options.encType || encType,
1111
+ replace: options.replace,
1112
+ state: options.state,
1113
+ fromRouteId: currentRouteId,
1114
+ flushSync: options.flushSync,
1115
+ viewTransition: options.viewTransition
1116
+ });
1117
+ }
1118
+ }, [router, basename, currentRouteId]);
1119
+ }
1120
+ // v7: Eventually we should deprecate this entirely in favor of using the
1121
+ // router method directly?
1122
+ function useFormAction(action, _temp2) {
1123
+ let {
1124
+ relative
1125
+ } = _temp2 === void 0 ? {} : _temp2;
1126
+ let {
1127
+ basename
1128
+ } = React.useContext(UNSAFE_NavigationContext);
1129
+ let routeContext = React.useContext(UNSAFE_RouteContext);
1130
+ !routeContext ? process.env.NODE_ENV !== "production" ? UNSAFE_invariant(false, "useFormAction must be used inside a RouteContext") : UNSAFE_invariant(false) : void 0;
1131
+ let [match] = routeContext.matches.slice(-1);
1132
+ // Shallow clone path so we can modify it below, otherwise we modify the
1133
+ // object referenced by useMemo inside useResolvedPath
1134
+ let path = _extends({}, useResolvedPath(action ? action : ".", {
1135
+ relative
1136
+ }));
1137
+ // If no action was specified, browsers will persist current search params
1138
+ // when determining the path, so match that behavior
1139
+ // https://github.com/remix-run/remix/issues/927
1140
+ let location = useLocation();
1141
+ if (action == null) {
1142
+ // Safe to write to this directly here since if action was undefined, we
1143
+ // would have called useResolvedPath(".") which will never include a search
1144
+ path.search = location.search;
1145
+ // When grabbing search params from the URL, remove any included ?index param
1146
+ // since it might not apply to our contextual route. We add it back based
1147
+ // on match.route.index below
1148
+ let params = new URLSearchParams(path.search);
1149
+ let indexValues = params.getAll("index");
1150
+ let hasNakedIndexParam = indexValues.some(v => v === "");
1151
+ if (hasNakedIndexParam) {
1152
+ params.delete("index");
1153
+ indexValues.filter(v => v).forEach(v => params.append("index", v));
1154
+ let qs = params.toString();
1155
+ path.search = qs ? "?" + qs : "";
1156
+ }
1157
+ }
1158
+ if ((!action || action === ".") && match.route.index) {
1159
+ path.search = path.search ? path.search.replace(/^\?/, "?index&") : "?index";
1160
+ }
1161
+ // If we're operating within a basename, prepend it to the pathname prior
1162
+ // to creating the form action. If this is a root navigation, then just use
1163
+ // the raw basename which allows the basename to have full control over the
1164
+ // presence of a trailing slash on root actions
1165
+ if (basename !== "/") {
1166
+ path.pathname = path.pathname === "/" ? basename : joinPaths([basename, path.pathname]);
1167
+ }
1168
+ return createPath(path);
1169
+ }
1170
+ // TODO: (v7) Change the useFetcher generic default from `any` to `unknown`
1171
+ /**
1172
+ * Interacts with route loaders and actions without causing a navigation. Great
1173
+ * for any interaction that stays on the same page.
1174
+ */
1175
+ function useFetcher(_temp3) {
1176
+ var _route$matches;
1177
+ let {
1178
+ key
1179
+ } = _temp3 === void 0 ? {} : _temp3;
1180
+ let {
1181
+ router
1182
+ } = useDataRouterContext(DataRouterHook.UseFetcher);
1183
+ let state = useDataRouterState(DataRouterStateHook.UseFetcher);
1184
+ let fetcherData = React.useContext(FetchersContext);
1185
+ let route = React.useContext(UNSAFE_RouteContext);
1186
+ let routeId = (_route$matches = route.matches[route.matches.length - 1]) == null ? void 0 : _route$matches.route.id;
1187
+ !fetcherData ? process.env.NODE_ENV !== "production" ? UNSAFE_invariant(false, "useFetcher must be used inside a FetchersContext") : UNSAFE_invariant(false) : void 0;
1188
+ !route ? process.env.NODE_ENV !== "production" ? UNSAFE_invariant(false, "useFetcher must be used inside a RouteContext") : UNSAFE_invariant(false) : void 0;
1189
+ !(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;
1190
+ // Fetcher key handling
1191
+ // OK to call conditionally to feature detect `useId`
1192
+ // eslint-disable-next-line react-hooks/rules-of-hooks
1193
+ let defaultKey = useIdImpl ? useIdImpl() : "";
1194
+ let [fetcherKey, setFetcherKey] = React.useState(key || defaultKey);
1195
+ if (key && key !== fetcherKey) {
1196
+ setFetcherKey(key);
1197
+ } else if (!fetcherKey) {
1198
+ // We will only fall through here when `useId` is not available
1199
+ setFetcherKey(getUniqueFetcherId());
1200
+ }
1201
+ // Registration/cleanup
1202
+ React.useEffect(() => {
1203
+ router.getFetcher(fetcherKey);
1204
+ return () => {
1205
+ // Tell the router we've unmounted - if v7_fetcherPersist is enabled this
1206
+ // will not delete immediately but instead queue up a delete after the
1207
+ // fetcher returns to an `idle` state
1208
+ router.deleteFetcher(fetcherKey);
1209
+ };
1210
+ }, [router, fetcherKey]);
1211
+ // Fetcher additions
1212
+ let load = React.useCallback((href, opts) => {
1213
+ !routeId ? process.env.NODE_ENV !== "production" ? UNSAFE_invariant(false, "No routeId available for fetcher.load()") : UNSAFE_invariant(false) : void 0;
1214
+ router.fetch(fetcherKey, routeId, href, opts);
1215
+ }, [fetcherKey, routeId, router]);
1216
+ let submitImpl = useSubmit();
1217
+ let submit = React.useCallback((target, opts) => {
1218
+ submitImpl(target, _extends({}, opts, {
1219
+ navigate: false,
1220
+ fetcherKey
1221
+ }));
1222
+ }, [fetcherKey, submitImpl]);
1223
+ let FetcherForm = React.useMemo(() => {
1224
+ let FetcherForm = /*#__PURE__*/React.forwardRef((props, ref) => {
1225
+ return /*#__PURE__*/React.createElement(Form, _extends({}, props, {
1226
+ navigate: false,
1227
+ fetcherKey: fetcherKey,
1228
+ ref: ref
1229
+ }));
1230
+ });
1231
+ if (process.env.NODE_ENV !== "production") {
1232
+ FetcherForm.displayName = "fetcher.Form";
1233
+ }
1234
+ return FetcherForm;
1235
+ }, [fetcherKey]);
1236
+ // Exposed FetcherWithComponents
1237
+ let fetcher = state.fetchers.get(fetcherKey) || IDLE_FETCHER;
1238
+ let data = fetcherData.get(fetcherKey);
1239
+ let fetcherWithComponents = React.useMemo(() => _extends({
1240
+ Form: FetcherForm,
1241
+ submit,
1242
+ load
1243
+ }, fetcher, {
1244
+ data
1245
+ }), [FetcherForm, submit, load, fetcher, data]);
1246
+ return fetcherWithComponents;
1247
+ }
1248
+ /**
1249
+ * Provides all fetchers currently on the page. Useful for layouts and parent
1250
+ * routes that need to provide pending/optimistic UI regarding the fetch.
1251
+ */
1252
+ function useFetchers() {
1253
+ let state = useDataRouterState(DataRouterStateHook.UseFetchers);
1254
+ return Array.from(state.fetchers.entries()).map(_ref11 => {
1255
+ let [key, fetcher] = _ref11;
1256
+ return _extends({}, fetcher, {
1257
+ key
1258
+ });
1259
+ });
1260
+ }
1261
+ const SCROLL_RESTORATION_STORAGE_KEY = "react-router-scroll-positions";
1262
+ let savedScrollPositions = {};
1263
+ /**
1264
+ * When rendered inside a RouterProvider, will restore scroll positions on navigations
1265
+ */
1266
+ function useScrollRestoration(_temp4) {
1267
+ let {
1268
+ getKey,
1269
+ storageKey
1270
+ } = _temp4 === void 0 ? {} : _temp4;
1271
+ let {
1272
+ router
1273
+ } = useDataRouterContext(DataRouterHook.UseScrollRestoration);
1274
+ let {
1275
+ restoreScrollPosition,
1276
+ preventScrollReset
1277
+ } = useDataRouterState(DataRouterStateHook.UseScrollRestoration);
1278
+ let {
1279
+ basename
1280
+ } = React.useContext(UNSAFE_NavigationContext);
1281
+ let location = useLocation();
1282
+ let matches = useMatches();
1283
+ let navigation = useNavigation();
1284
+ // Trigger manual scroll restoration while we're active
1285
+ React.useEffect(() => {
1286
+ window.history.scrollRestoration = "manual";
1287
+ return () => {
1288
+ window.history.scrollRestoration = "auto";
1289
+ };
1290
+ }, []);
1291
+ // Save positions on pagehide
1292
+ usePageHide(React.useCallback(() => {
1293
+ if (navigation.state === "idle") {
1294
+ let key = (getKey ? getKey(location, matches) : null) || location.key;
1295
+ savedScrollPositions[key] = window.scrollY;
1296
+ }
1297
+ try {
1298
+ sessionStorage.setItem(storageKey || SCROLL_RESTORATION_STORAGE_KEY, JSON.stringify(savedScrollPositions));
1299
+ } catch (error) {
1300
+ process.env.NODE_ENV !== "production" ? UNSAFE_warning(false, "Failed to save scroll positions in sessionStorage, <ScrollRestoration /> will not work properly (" + error + ").") : void 0;
1301
+ }
1302
+ window.history.scrollRestoration = "auto";
1303
+ }, [storageKey, getKey, navigation.state, location, matches]));
1304
+ // Read in any saved scroll locations
1305
+ if (typeof document !== "undefined") {
1306
+ // eslint-disable-next-line react-hooks/rules-of-hooks
1307
+ React.useLayoutEffect(() => {
1308
+ try {
1309
+ let sessionPositions = sessionStorage.getItem(storageKey || SCROLL_RESTORATION_STORAGE_KEY);
1310
+ if (sessionPositions) {
1311
+ savedScrollPositions = JSON.parse(sessionPositions);
1312
+ }
1313
+ } catch (e) {
1314
+ // no-op, use default empty object
1315
+ }
1316
+ }, [storageKey]);
1317
+ // Enable scroll restoration in the router
1318
+ // eslint-disable-next-line react-hooks/rules-of-hooks
1319
+ React.useLayoutEffect(() => {
1320
+ let getKeyWithoutBasename = getKey && basename !== "/" ? (location, matches) => getKey( // Strip the basename to match useLocation()
1321
+ _extends({}, location, {
1322
+ pathname: stripBasename(location.pathname, basename) || location.pathname
1323
+ }), matches) : getKey;
1324
+ let disableScrollRestoration = router == null ? void 0 : router.enableScrollRestoration(savedScrollPositions, () => window.scrollY, getKeyWithoutBasename);
1325
+ return () => disableScrollRestoration && disableScrollRestoration();
1326
+ }, [router, basename, getKey]);
1327
+ // Restore scrolling when state.restoreScrollPosition changes
1328
+ // eslint-disable-next-line react-hooks/rules-of-hooks
1329
+ React.useLayoutEffect(() => {
1330
+ // Explicit false means don't do anything (used for submissions)
1331
+ if (restoreScrollPosition === false) {
1332
+ return;
1333
+ }
1334
+ // been here before, scroll to it
1335
+ if (typeof restoreScrollPosition === "number") {
1336
+ window.scrollTo(0, restoreScrollPosition);
1337
+ return;
1338
+ }
1339
+ // try to scroll to the hash
1340
+ if (location.hash) {
1341
+ let el = document.getElementById(decodeURIComponent(location.hash.slice(1)));
1342
+ if (el) {
1343
+ el.scrollIntoView();
1344
+ return;
1345
+ }
1346
+ }
1347
+ // Don't reset if this navigation opted out
1348
+ if (preventScrollReset === true) {
1349
+ return;
1350
+ }
1351
+ // otherwise go to the top on new locations
1352
+ window.scrollTo(0, 0);
1353
+ }, [location, restoreScrollPosition, preventScrollReset]);
1354
+ }
1355
+ }
1356
+ /**
1357
+ * Setup a callback to be fired on the window's `beforeunload` event. This is
1358
+ * useful for saving some data to `window.localStorage` just before the page
1359
+ * refreshes.
1360
+ *
1361
+ * Note: The `callback` argument should be a function created with
1362
+ * `React.useCallback()`.
1363
+ */
1364
+ function useBeforeUnload(callback, options) {
1365
+ let {
1366
+ capture
1367
+ } = options || {};
1368
+ React.useEffect(() => {
1369
+ let opts = capture != null ? {
1370
+ capture
1371
+ } : undefined;
1372
+ window.addEventListener("beforeunload", callback, opts);
1373
+ return () => {
1374
+ window.removeEventListener("beforeunload", callback, opts);
1375
+ };
1376
+ }, [callback, capture]);
1377
+ }
1378
+ /**
1379
+ * Setup a callback to be fired on the window's `pagehide` event. This is
1380
+ * useful for saving some data to `window.localStorage` just before the page
1381
+ * refreshes. This event is better supported than beforeunload across browsers.
1382
+ *
1383
+ * Note: The `callback` argument should be a function created with
1384
+ * `React.useCallback()`.
1385
+ */
1386
+ function usePageHide(callback, options) {
1387
+ let {
1388
+ capture
1389
+ } = options || {};
1390
+ React.useEffect(() => {
1391
+ let opts = capture != null ? {
1392
+ capture
1393
+ } : undefined;
1394
+ window.addEventListener("pagehide", callback, opts);
1395
+ return () => {
1396
+ window.removeEventListener("pagehide", callback, opts);
1397
+ };
1398
+ }, [callback, capture]);
1399
+ }
1400
+ /**
1401
+ * Wrapper around useBlocker to show a window.confirm prompt to users instead
1402
+ * of building a custom UI with useBlocker.
1403
+ *
1404
+ * Warning: This has *a lot of rough edges* and behaves very differently (and
1405
+ * very incorrectly in some cases) across browsers if user click addition
1406
+ * back/forward navigations while the confirm is open. Use at your own risk.
1407
+ */
1408
+ function usePrompt(_ref12) {
1409
+ let {
1410
+ when,
1411
+ message
1412
+ } = _ref12;
1413
+ let blocker = useBlocker(when);
1414
+ React.useEffect(() => {
1415
+ if (blocker.state === "blocked") {
1416
+ let proceed = window.confirm(message);
1417
+ if (proceed) {
1418
+ // This timeout is needed to avoid a weird "race" on POP navigations
1419
+ // between the `window.history` revert navigation and the result of
1420
+ // `window.confirm`
1421
+ setTimeout(blocker.proceed, 0);
1422
+ } else {
1423
+ blocker.reset();
1424
+ }
1425
+ }
1426
+ }, [blocker, message]);
1427
+ React.useEffect(() => {
1428
+ if (blocker.state === "blocked" && !when) {
1429
+ blocker.reset();
1430
+ }
1431
+ }, [blocker, when]);
1432
+ }
1433
+ /**
1434
+ * Return a boolean indicating if there is an active view transition to the
1435
+ * given href. You can use this value to render CSS classes or viewTransitionName
1436
+ * styles onto your elements
1437
+ *
1438
+ * @param href The destination href
1439
+ * @param [opts.relative] Relative routing type ("route" | "path")
1440
+ */
1441
+ function useViewTransitionState(to, opts) {
1442
+ if (opts === void 0) {
1443
+ opts = {};
1444
+ }
1445
+ let vtContext = React.useContext(ViewTransitionContext);
1446
+ !(vtContext != null) ? process.env.NODE_ENV !== "production" ? UNSAFE_invariant(false, "`useViewTransitionState` must be used within `react-router-dom`'s `RouterProvider`. " + "Did you accidentally import `RouterProvider` from `react-router`?") : UNSAFE_invariant(false) : void 0;
1447
+ let {
1448
+ basename
1449
+ } = useDataRouterContext(DataRouterHook.useViewTransitionState);
1450
+ let path = useResolvedPath(to, {
1451
+ relative: opts.relative
1452
+ });
1453
+ if (!vtContext.isTransitioning) {
1454
+ return false;
1455
+ }
1456
+ let currentPath = stripBasename(vtContext.currentLocation.pathname, basename) || vtContext.currentLocation.pathname;
1457
+ let nextPath = stripBasename(vtContext.nextLocation.pathname, basename) || vtContext.nextLocation.pathname;
1458
+ // Transition is active if we're going to or coming from the indicated
1459
+ // destination. This ensures that other PUSH navigations that reverse
1460
+ // an indicated transition apply. I.e., on the list view you have:
1461
+ //
1462
+ // <NavLink to="/details/1" viewTransition>
1463
+ //
1464
+ // If you click the breadcrumb back to the list view:
1465
+ //
1466
+ // <NavLink to="/list" viewTransition>
1467
+ //
1468
+ // We should apply the transition because it's indicated as active going
1469
+ // from /list -> /details/1 and therefore should be active on the reverse
1470
+ // (even though this isn't strictly a POP reverse)
1471
+ return matchPath(path.pathname, nextPath) != null || matchPath(path.pathname, currentPath) != null;
1472
+ }
1473
+ //#endregion
1474
+
1475
+ export { BrowserRouter, Form, HashRouter, Link, NavLink, RouterProvider, ScrollRestoration, FetchersContext as UNSAFE_FetchersContext, ViewTransitionContext as UNSAFE_ViewTransitionContext, useScrollRestoration as UNSAFE_useScrollRestoration, createBrowserRouter, createHashRouter, createSearchParams, HistoryRouter as unstable_HistoryRouter, usePrompt as unstable_usePrompt, useBeforeUnload, useFetcher, useFetchers, useFormAction, useLinkClickHandler, useSearchParams, useSubmit, useViewTransitionState };
1476
+ //# sourceMappingURL=index.js.map