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