react-router-dom 0.0.0-experimental-bcda00aaf → 0.0.0-experimental-a26b992a1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,5 @@
1
1
  /**
2
- * React Router DOM v0.0.0-experimental-bcda00aaf
2
+ * React Router DOM v0.0.0-experimental-a26b992a1
3
3
  *
4
4
  * Copyright (c) Remix Software Inc.
5
5
  *
@@ -8,1512 +8,5 @@
8
8
  *
9
9
  * @license MIT
10
10
  */
11
- import * as React from 'react';
12
- import * as ReactDOM from 'react-dom';
13
- import { UNSAFE_mapRouteProperties, 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: flushSync,
435
- viewTransitionOpts: viewTransitionOpts
436
- }) => {
437
- deletedFetchers.forEach(key => fetcherData.current.delete(key));
438
- newState.fetchers.forEach((fetcher, key) => {
439
- if (fetcher.data !== undefined) {
440
- fetcherData.current.set(key, fetcher.data);
441
- }
442
- });
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
- if (flushSync) {
449
- flushSyncSafe(() => setStateImpl(newState));
450
- } else {
451
- optInStartTransition(() => setStateImpl(newState));
452
- }
453
- return;
454
- }
455
-
456
- // flushSync + startViewTransition
457
- if (flushSync) {
458
- // Flush through the context to mark DOM elements as transition=ing
459
- flushSyncSafe(() => {
460
- // Cancel any pending transitions
461
- if (transition) {
462
- renderDfd && renderDfd.resolve();
463
- transition.skipTransition();
464
- }
465
- setVtContext({
466
- isTransitioning: true,
467
- flushSync: true,
468
- currentLocation: viewTransitionOpts.currentLocation,
469
- nextLocation: viewTransitionOpts.nextLocation
470
- });
471
- });
472
-
473
- // Update the DOM
474
- let t = router.window.document.startViewTransition(() => {
475
- flushSyncSafe(() => setStateImpl(newState));
476
- });
477
-
478
- // Clean up after the animation completes
479
- t.finished.finally(() => {
480
- flushSyncSafe(() => {
481
- setRenderDfd(undefined);
482
- setTransition(undefined);
483
- setPendingState(undefined);
484
- setVtContext({
485
- isTransitioning: false
486
- });
487
- });
488
- });
489
- flushSyncSafe(() => setTransition(t));
490
- return;
491
- }
492
-
493
- // startTransition + startViewTransition
494
- if (transition) {
495
- // Interrupting an in-progress transition, cancel and let everything flush
496
- // out, and then kick off a new transition from the interruption state
497
- renderDfd && renderDfd.resolve();
498
- transition.skipTransition();
499
- setInterruption({
500
- state: newState,
501
- currentLocation: viewTransitionOpts.currentLocation,
502
- nextLocation: viewTransitionOpts.nextLocation
503
- });
504
- } else {
505
- // Completed navigation update with opted-in view transitions, let 'er rip
506
- setPendingState(newState);
507
- setVtContext({
508
- isTransitioning: true,
509
- flushSync: false,
510
- currentLocation: viewTransitionOpts.currentLocation,
511
- nextLocation: viewTransitionOpts.nextLocation
512
- });
513
- }
514
- }, [router.window, transition, renderDfd, fetcherData, optInStartTransition]);
515
-
516
- // Need to use a layout effect here so we are subscribed early enough to
517
- // pick up on any render-driven redirects/navigations (useEffect/<Navigate>)
518
- React.useLayoutEffect(() => router.subscribe(setState), [router, setState]);
519
-
520
- // When we start a view transition, create a Deferred we can use for the
521
- // eventual "completed" render
522
- React.useEffect(() => {
523
- if (vtContext.isTransitioning && !vtContext.flushSync) {
524
- setRenderDfd(new Deferred());
525
- }
526
- }, [vtContext]);
527
-
528
- // Once the deferred is created, kick off startViewTransition() to update the
529
- // DOM and then wait on the Deferred to resolve (indicating the DOM update has
530
- // happened)
531
- React.useEffect(() => {
532
- if (renderDfd && pendingState && router.window) {
533
- let newState = pendingState;
534
- let renderPromise = renderDfd.promise;
535
- let transition = router.window.document.startViewTransition(async () => {
536
- optInStartTransition(() => setStateImpl(newState));
537
- await renderPromise;
538
- });
539
- transition.finished.finally(() => {
540
- setRenderDfd(undefined);
541
- setTransition(undefined);
542
- setPendingState(undefined);
543
- setVtContext({
544
- isTransitioning: false
545
- });
546
- });
547
- setTransition(transition);
548
- }
549
- }, [optInStartTransition, pendingState, renderDfd, router.window]);
550
-
551
- // When the new location finally renders and is committed to the DOM, this
552
- // effect will run to resolve the transition
553
- React.useEffect(() => {
554
- if (renderDfd && pendingState && state.location.key === pendingState.location.key) {
555
- renderDfd.resolve();
556
- }
557
- }, [renderDfd, transition, state.location, pendingState]);
558
-
559
- // If we get interrupted with a new navigation during a transition, we skip
560
- // the active transition, let it cleanup, then kick it off again here
561
- React.useEffect(() => {
562
- if (!vtContext.isTransitioning && interruption) {
563
- setPendingState(interruption.state);
564
- setVtContext({
565
- isTransitioning: true,
566
- flushSync: false,
567
- currentLocation: interruption.currentLocation,
568
- nextLocation: interruption.nextLocation
569
- });
570
- setInterruption(undefined);
571
- }
572
- }, [vtContext.isTransitioning, interruption]);
573
- React.useEffect(() => {
574
- UNSAFE_warning(fallbackElement == null || !router.future.v7_partialHydration, "`<RouterProvider fallbackElement>` is deprecated when using " + "`v7_partialHydration`, use a `HydrateFallback` component instead") ;
575
- // Only log this once on initial mount
576
- // eslint-disable-next-line react-hooks/exhaustive-deps
577
- }, []);
578
- let navigator = React.useMemo(() => {
579
- return {
580
- createHref: router.createHref,
581
- encodeLocation: router.encodeLocation,
582
- go: n => router.navigate(n),
583
- push: (to, state, opts) => router.navigate(to, {
584
- state,
585
- preventScrollReset: opts?.preventScrollReset
586
- }),
587
- replace: (to, state, opts) => router.navigate(to, {
588
- replace: true,
589
- state,
590
- preventScrollReset: opts?.preventScrollReset
591
- })
592
- };
593
- }, [router]);
594
- let basename = router.basename || "/";
595
- let dataRouterContext = React.useMemo(() => ({
596
- router,
597
- navigator,
598
- static: false,
599
- basename
600
- }), [router, navigator, basename]);
601
- let routerFuture = React.useMemo(() => ({
602
- v7_relativeSplatPath: router.future.v7_relativeSplatPath
603
- }), [router.future.v7_relativeSplatPath]);
604
-
605
- // The fragment and {null} here are important! We need them to keep React 18's
606
- // useId happy when we are server-rendering since we may have a <script> here
607
- // containing the hydrated server-side staticContext (from StaticRouterProvider).
608
- // useId relies on the component tree structure to generate deterministic id's
609
- // so we need to ensure it remains the same on the client even though
610
- // we don't need the <script> tag
611
- return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(UNSAFE_DataRouterContext.Provider, {
612
- value: dataRouterContext
613
- }, /*#__PURE__*/React.createElement(UNSAFE_DataRouterStateContext.Provider, {
614
- value: state
615
- }, /*#__PURE__*/React.createElement(FetchersContext.Provider, {
616
- value: fetcherData.current
617
- }, /*#__PURE__*/React.createElement(ViewTransitionContext.Provider, {
618
- value: vtContext
619
- }, /*#__PURE__*/React.createElement(Router, {
620
- basename: basename,
621
- location: state.location,
622
- navigationType: state.historyAction,
623
- navigator: navigator,
624
- future: routerFuture
625
- }, state.initialized || router.future.v7_partialHydration ? /*#__PURE__*/React.createElement(MemoizedDataRoutes, {
626
- routes: router.routes,
627
- future: router.future,
628
- state: state
629
- }) : fallbackElement))))), null);
630
- }
631
-
632
- // Memoize to avoid re-renders when updating `ViewTransitionContext`
633
- const MemoizedDataRoutes = /*#__PURE__*/React.memo(DataRoutes);
634
- function DataRoutes({
635
- routes,
636
- future,
637
- state
638
- }) {
639
- return UNSAFE_useRoutesImpl(routes, undefined, state, future);
640
- }
641
- /**
642
- * A `<Router>` for use in web browsers. Provides the cleanest URLs.
643
- */
644
- function BrowserRouter({
645
- basename,
646
- children,
647
- future,
648
- window
649
- }) {
650
- let historyRef = React.useRef();
651
- if (historyRef.current == null) {
652
- historyRef.current = createBrowserHistory({
653
- window,
654
- v5Compat: true
655
- });
656
- }
657
- let history = historyRef.current;
658
- let [state, setStateImpl] = React.useState({
659
- action: history.action,
660
- location: history.location
661
- });
662
- let {
663
- v7_startTransition
664
- } = future || {};
665
- let setState = React.useCallback(newState => {
666
- v7_startTransition && startTransitionImpl ? startTransitionImpl(() => setStateImpl(newState)) : setStateImpl(newState);
667
- }, [setStateImpl, v7_startTransition]);
668
- React.useLayoutEffect(() => history.listen(setState), [history, setState]);
669
- return /*#__PURE__*/React.createElement(Router, {
670
- basename: basename,
671
- children: children,
672
- location: state.location,
673
- navigationType: state.action,
674
- navigator: history,
675
- future: future
676
- });
677
- }
678
- /**
679
- * A `<Router>` for use in web browsers. Stores the location in the hash
680
- * portion of the URL so it is not sent to the server.
681
- */
682
- function HashRouter({
683
- basename,
684
- children,
685
- future,
686
- window
687
- }) {
688
- let historyRef = React.useRef();
689
- if (historyRef.current == null) {
690
- historyRef.current = createHashHistory({
691
- window,
692
- v5Compat: true
693
- });
694
- }
695
- let history = historyRef.current;
696
- let [state, setStateImpl] = React.useState({
697
- action: history.action,
698
- location: history.location
699
- });
700
- let {
701
- v7_startTransition
702
- } = future || {};
703
- let setState = React.useCallback(newState => {
704
- v7_startTransition && startTransitionImpl ? startTransitionImpl(() => setStateImpl(newState)) : setStateImpl(newState);
705
- }, [setStateImpl, v7_startTransition]);
706
- React.useLayoutEffect(() => history.listen(setState), [history, setState]);
707
- return /*#__PURE__*/React.createElement(Router, {
708
- basename: basename,
709
- children: children,
710
- location: state.location,
711
- navigationType: state.action,
712
- navigator: history,
713
- future: future
714
- });
715
- }
716
- /**
717
- * A `<Router>` that accepts a pre-instantiated history object. It's important
718
- * to note that using your own history object is highly discouraged and may add
719
- * two versions of the history library to your bundles unless you use the same
720
- * version of the history library that React Router uses internally.
721
- */
722
- function HistoryRouter({
723
- basename,
724
- children,
725
- future,
726
- history
727
- }) {
728
- let [state, setStateImpl] = React.useState({
729
- action: history.action,
730
- location: history.location
731
- });
732
- let {
733
- v7_startTransition
734
- } = future || {};
735
- let setState = React.useCallback(newState => {
736
- v7_startTransition && startTransitionImpl ? startTransitionImpl(() => setStateImpl(newState)) : setStateImpl(newState);
737
- }, [setStateImpl, v7_startTransition]);
738
- React.useLayoutEffect(() => history.listen(setState), [history, setState]);
739
- return /*#__PURE__*/React.createElement(Router, {
740
- basename: basename,
741
- children: children,
742
- location: state.location,
743
- navigationType: state.action,
744
- navigator: history,
745
- future: future
746
- });
747
- }
748
- {
749
- HistoryRouter.displayName = "unstable_HistoryRouter";
750
- }
751
- const isBrowser = typeof window !== "undefined" && typeof window.document !== "undefined" && typeof window.document.createElement !== "undefined";
752
- const ABSOLUTE_URL_REGEX = /^(?:[a-z][a-z0-9+.-]*:|\/\/)/i;
753
-
754
- /**
755
- * The public API for rendering a history-aware `<a>`.
756
- */
757
- const Link = /*#__PURE__*/React.forwardRef(function LinkWithRef({
758
- onClick,
759
- relative,
760
- reloadDocument,
761
- replace,
762
- state,
763
- target,
764
- to,
765
- preventScrollReset,
766
- viewTransition,
767
- ...rest
768
- }, ref) {
769
- let {
770
- basename
771
- } = React.useContext(UNSAFE_NavigationContext);
772
-
773
- // Rendered into <a href> for absolute URLs
774
- let absoluteHref;
775
- let isExternal = false;
776
- if (typeof to === "string" && ABSOLUTE_URL_REGEX.test(to)) {
777
- // Render the absolute href server- and client-side
778
- absoluteHref = to;
779
-
780
- // Only check for external origins client-side
781
- if (isBrowser) {
782
- try {
783
- let currentUrl = new URL(window.location.href);
784
- let targetUrl = to.startsWith("//") ? new URL(currentUrl.protocol + to) : new URL(to);
785
- let path = stripBasename(targetUrl.pathname, basename);
786
- if (targetUrl.origin === currentUrl.origin && path != null) {
787
- // Strip the protocol/origin/basename for same-origin absolute URLs
788
- to = path + targetUrl.search + targetUrl.hash;
789
- } else {
790
- isExternal = true;
791
- }
792
- } catch (e) {
793
- // We can't do external URL detection without a valid URL
794
- UNSAFE_warning(false, `<Link to="${to}"> contains an invalid URL which will probably break ` + `when clicked - please update to a valid URL path.`) ;
795
- }
796
- }
797
- }
798
-
799
- // Rendered into <a href> for relative URLs
800
- let href = useHref(to, {
801
- relative
802
- });
803
- let internalOnClick = useLinkClickHandler(to, {
804
- replace,
805
- state,
806
- target,
807
- preventScrollReset,
808
- relative,
809
- viewTransition
810
- });
811
- function handleClick(event) {
812
- if (onClick) onClick(event);
813
- if (!event.defaultPrevented) {
814
- internalOnClick(event);
815
- }
816
- }
817
- return (
818
- /*#__PURE__*/
819
- // eslint-disable-next-line jsx-a11y/anchor-has-content
820
- React.createElement("a", Object.assign({}, rest, {
821
- href: absoluteHref || href,
822
- onClick: isExternal || reloadDocument ? onClick : handleClick,
823
- ref: ref,
824
- target: target
825
- }))
826
- );
827
- });
828
- {
829
- Link.displayName = "Link";
830
- }
831
- /**
832
- * A `<Link>` wrapper that knows if it's "active" or not.
833
- */
834
- const NavLink = /*#__PURE__*/React.forwardRef(function NavLinkWithRef({
835
- "aria-current": ariaCurrentProp = "page",
836
- caseSensitive = false,
837
- className: classNameProp = "",
838
- end = false,
839
- style: styleProp,
840
- to,
841
- viewTransition,
842
- children,
843
- ...rest
844
- }, ref) {
845
- let path = useResolvedPath(to, {
846
- relative: rest.relative
847
- });
848
- let location = useLocation();
849
- let routerState = React.useContext(UNSAFE_DataRouterStateContext);
850
- let {
851
- navigator,
852
- basename
853
- } = React.useContext(UNSAFE_NavigationContext);
854
- let isTransitioning = routerState != null &&
855
- // Conditional usage is OK here because the usage of a data router is static
856
- // eslint-disable-next-line react-hooks/rules-of-hooks
857
- useViewTransitionState(path) && viewTransition === true;
858
- let toPathname = navigator.encodeLocation ? navigator.encodeLocation(path).pathname : path.pathname;
859
- let locationPathname = location.pathname;
860
- let nextLocationPathname = routerState && routerState.navigation && routerState.navigation.location ? routerState.navigation.location.pathname : null;
861
- if (!caseSensitive) {
862
- locationPathname = locationPathname.toLowerCase();
863
- nextLocationPathname = nextLocationPathname ? nextLocationPathname.toLowerCase() : null;
864
- toPathname = toPathname.toLowerCase();
865
- }
866
- if (nextLocationPathname && basename) {
867
- nextLocationPathname = stripBasename(nextLocationPathname, basename) || nextLocationPathname;
868
- }
869
-
870
- // If the `to` has a trailing slash, look at that exact spot. Otherwise,
871
- // we're looking for a slash _after_ what's in `to`. For example:
872
- //
873
- // <NavLink to="/users"> and <NavLink to="/users/">
874
- // both want to look for a / at index 6 to match URL `/users/matt`
875
- const endSlashPosition = toPathname !== "/" && toPathname.endsWith("/") ? toPathname.length - 1 : toPathname.length;
876
- let isActive = locationPathname === toPathname || !end && locationPathname.startsWith(toPathname) && locationPathname.charAt(endSlashPosition) === "/";
877
- let isPending = nextLocationPathname != null && (nextLocationPathname === toPathname || !end && nextLocationPathname.startsWith(toPathname) && nextLocationPathname.charAt(toPathname.length) === "/");
878
- let renderProps = {
879
- isActive,
880
- isPending,
881
- isTransitioning
882
- };
883
- let ariaCurrent = isActive ? ariaCurrentProp : undefined;
884
- let className;
885
- if (typeof classNameProp === "function") {
886
- className = classNameProp(renderProps);
887
- } else {
888
- // If the className prop is not a function, we use a default `active`
889
- // class for <NavLink />s that are active. In v5 `active` was the default
890
- // value for `activeClassName`, but we are removing that API and can still
891
- // use the old default behavior for a cleaner upgrade path and keep the
892
- // simple styling rules working as they currently do.
893
- className = [classNameProp, isActive ? "active" : null, isPending ? "pending" : null, isTransitioning ? "transitioning" : null].filter(Boolean).join(" ");
894
- }
895
- let style = typeof styleProp === "function" ? styleProp(renderProps) : styleProp;
896
- return /*#__PURE__*/React.createElement(Link, Object.assign({}, rest, {
897
- "aria-current": ariaCurrent,
898
- className: className,
899
- ref: ref,
900
- style: style,
901
- to: to,
902
- viewTransition: viewTransition
903
- }), typeof children === "function" ? children(renderProps) : children);
904
- });
905
- {
906
- NavLink.displayName = "NavLink";
907
- }
908
-
909
- /**
910
- * Form props shared by navigations and fetchers
911
- */
912
-
913
- /**
914
- * Form props available to fetchers
915
- */
916
-
917
- /**
918
- * Form props available to navigations
919
- */
920
-
921
- /**
922
- * A `@remix-run/router`-aware `<form>`. It behaves like a normal form except
923
- * that the interaction with the server is with `fetch` instead of new document
924
- * requests, allowing components to add nicer UX to the page as the form is
925
- * submitted and returns with data.
926
- */
927
- const Form = /*#__PURE__*/React.forwardRef(({
928
- fetcherKey,
929
- navigate,
930
- reloadDocument,
931
- replace,
932
- state,
933
- method: _method = defaultMethod,
934
- action,
935
- onSubmit,
936
- relative,
937
- preventScrollReset,
938
- viewTransition,
939
- ...props
940
- }, forwardedRef) => {
941
- let submit = useSubmit();
942
- let formAction = useFormAction(action, {
943
- relative
944
- });
945
- let formMethod = _method.toLowerCase() === "get" ? "get" : "post";
946
- let submitHandler = event => {
947
- onSubmit && onSubmit(event);
948
- if (event.defaultPrevented) return;
949
- event.preventDefault();
950
- let submitter = event.nativeEvent.submitter;
951
- let submitMethod = submitter?.getAttribute("formmethod") || _method;
952
- submit(submitter || event.currentTarget, {
953
- fetcherKey,
954
- method: submitMethod,
955
- navigate,
956
- replace,
957
- state,
958
- relative,
959
- preventScrollReset,
960
- viewTransition
961
- });
962
- };
963
- return /*#__PURE__*/React.createElement("form", Object.assign({
964
- ref: forwardedRef,
965
- method: formMethod,
966
- action: formAction,
967
- onSubmit: reloadDocument ? onSubmit : submitHandler
968
- }, props));
969
- });
970
- {
971
- Form.displayName = "Form";
972
- }
973
- /**
974
- * This component will emulate the browser's scroll restoration on location
975
- * changes.
976
- */
977
- function ScrollRestoration({
978
- getKey,
979
- storageKey
980
- }) {
981
- useScrollRestoration({
982
- getKey,
983
- storageKey
984
- });
985
- return null;
986
- }
987
- {
988
- ScrollRestoration.displayName = "ScrollRestoration";
989
- }
990
- //#endregion
991
-
992
- ////////////////////////////////////////////////////////////////////////////////
993
- //#region Hooks
994
- ////////////////////////////////////////////////////////////////////////////////
995
- var DataRouterHook = /*#__PURE__*/function (DataRouterHook) {
996
- DataRouterHook["UseScrollRestoration"] = "useScrollRestoration";
997
- DataRouterHook["UseSubmit"] = "useSubmit";
998
- DataRouterHook["UseSubmitFetcher"] = "useSubmitFetcher";
999
- DataRouterHook["UseFetcher"] = "useFetcher";
1000
- DataRouterHook["useViewTransitionState"] = "useViewTransitionState";
1001
- return DataRouterHook;
1002
- }(DataRouterHook || {});
1003
- var DataRouterStateHook = /*#__PURE__*/function (DataRouterStateHook) {
1004
- DataRouterStateHook["UseFetcher"] = "useFetcher";
1005
- DataRouterStateHook["UseFetchers"] = "useFetchers";
1006
- DataRouterStateHook["UseScrollRestoration"] = "useScrollRestoration";
1007
- return DataRouterStateHook;
1008
- }(DataRouterStateHook || {}); // Internal hooks
1009
- function getDataRouterConsoleError(hookName) {
1010
- return `${hookName} must be used within a data router. See https://reactrouter.com/routers/picking-a-router.`;
1011
- }
1012
- function useDataRouterContext(hookName) {
1013
- let ctx = React.useContext(UNSAFE_DataRouterContext);
1014
- !ctx ? UNSAFE_invariant(false, getDataRouterConsoleError(hookName)) : void 0;
1015
- return ctx;
1016
- }
1017
- function useDataRouterState(hookName) {
1018
- let state = React.useContext(UNSAFE_DataRouterStateContext);
1019
- !state ? UNSAFE_invariant(false, getDataRouterConsoleError(hookName)) : void 0;
1020
- return state;
1021
- }
1022
-
1023
- // External hooks
1024
-
1025
- /**
1026
- * Handles the click behavior for router `<Link>` components. This is useful if
1027
- * you need to create custom `<Link>` components with the same click behavior we
1028
- * use in our exported `<Link>`.
1029
- */
1030
- function useLinkClickHandler(to, {
1031
- target,
1032
- replace: replaceProp,
1033
- state,
1034
- preventScrollReset,
1035
- relative,
1036
- viewTransition
1037
- } = {}) {
1038
- let navigate = useNavigate();
1039
- let location = useLocation();
1040
- let path = useResolvedPath(to, {
1041
- relative
1042
- });
1043
- return React.useCallback(event => {
1044
- if (shouldProcessLinkClick(event, target)) {
1045
- event.preventDefault();
1046
-
1047
- // If the URL hasn't changed, a regular <a> will do a replace instead of
1048
- // a push, so do the same here unless the replace prop is explicitly set
1049
- let replace = replaceProp !== undefined ? replaceProp : createPath(location) === createPath(path);
1050
- navigate(to, {
1051
- replace,
1052
- state,
1053
- preventScrollReset,
1054
- relative,
1055
- viewTransition
1056
- });
1057
- }
1058
- }, [location, navigate, path, replaceProp, state, target, to, preventScrollReset, relative, viewTransition]);
1059
- }
1060
-
1061
- /**
1062
- * A convenient wrapper for reading and writing search parameters via the
1063
- * URLSearchParams interface.
1064
- */
1065
- function useSearchParams(defaultInit) {
1066
- 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.`) ;
1067
- let defaultSearchParamsRef = React.useRef(createSearchParams(defaultInit));
1068
- let hasSetSearchParamsRef = React.useRef(false);
1069
- let location = useLocation();
1070
- let searchParams = React.useMemo(() =>
1071
- // Only merge in the defaults if we haven't yet called setSearchParams.
1072
- // Once we call that we want those to take precedence, otherwise you can't
1073
- // remove a param with setSearchParams({}) if it has an initial value
1074
- getSearchParamsForLocation(location.search, hasSetSearchParamsRef.current ? null : defaultSearchParamsRef.current), [location.search]);
1075
- let navigate = useNavigate();
1076
- let setSearchParams = React.useCallback((nextInit, navigateOptions) => {
1077
- const newSearchParams = createSearchParams(typeof nextInit === "function" ? nextInit(searchParams) : nextInit);
1078
- hasSetSearchParamsRef.current = true;
1079
- navigate("?" + newSearchParams, navigateOptions);
1080
- }, [navigate, searchParams]);
1081
- return [searchParams, setSearchParams];
1082
- }
1083
-
1084
- /**
1085
- * Submits a HTML `<form>` to the server without reloading the page.
1086
- */
1087
-
1088
- /**
1089
- * Submits a fetcher `<form>` to the server without reloading the page.
1090
- */
1091
-
1092
- function validateClientSideSubmission() {
1093
- if (typeof document === "undefined") {
1094
- throw new Error("You are calling submit during the server render. " + "Try calling submit within a `useEffect` or callback instead.");
1095
- }
1096
- }
1097
- let fetcherId = 0;
1098
- let getUniqueFetcherId = () => `__${String(++fetcherId)}__`;
1099
-
1100
- /**
1101
- * Returns a function that may be used to programmatically submit a form (or
1102
- * some arbitrary data) to the server.
1103
- */
1104
- function useSubmit() {
1105
- let {
1106
- router
1107
- } = useDataRouterContext(DataRouterHook.UseSubmit);
1108
- let {
1109
- basename
1110
- } = React.useContext(UNSAFE_NavigationContext);
1111
- let currentRouteId = UNSAFE_useRouteId();
1112
- return React.useCallback((target, options = {}) => {
1113
- validateClientSideSubmission();
1114
- let {
1115
- action,
1116
- method,
1117
- encType,
1118
- formData,
1119
- body
1120
- } = getFormSubmissionInfo(target, basename);
1121
- if (options.navigate === false) {
1122
- let key = options.fetcherKey || getUniqueFetcherId();
1123
- router.fetch(key, currentRouteId, options.action || action, {
1124
- preventScrollReset: options.preventScrollReset,
1125
- formData,
1126
- body,
1127
- formMethod: options.method || method,
1128
- formEncType: options.encType || encType,
1129
- flushSync: options.flushSync
1130
- });
1131
- } else {
1132
- router.navigate(options.action || action, {
1133
- preventScrollReset: options.preventScrollReset,
1134
- formData,
1135
- body,
1136
- formMethod: options.method || method,
1137
- formEncType: options.encType || encType,
1138
- replace: options.replace,
1139
- state: options.state,
1140
- fromRouteId: currentRouteId,
1141
- flushSync: options.flushSync,
1142
- viewTransition: options.viewTransition
1143
- });
1144
- }
1145
- }, [router, basename, currentRouteId]);
1146
- }
1147
-
1148
- // v7: Eventually we should deprecate this entirely in favor of using the
1149
- // router method directly?
1150
- function useFormAction(action, {
1151
- relative
1152
- } = {}) {
1153
- let {
1154
- basename
1155
- } = React.useContext(UNSAFE_NavigationContext);
1156
- let routeContext = React.useContext(UNSAFE_RouteContext);
1157
- !routeContext ? UNSAFE_invariant(false, "useFormAction must be used inside a RouteContext") : void 0;
1158
- let [match] = routeContext.matches.slice(-1);
1159
- // Shallow clone path so we can modify it below, otherwise we modify the
1160
- // object referenced by useMemo inside useResolvedPath
1161
- let path = {
1162
- ...useResolvedPath(action ? action : ".", {
1163
- relative
1164
- })
1165
- };
1166
-
1167
- // If no action was specified, browsers will persist current search params
1168
- // when determining the path, so match that behavior
1169
- // https://github.com/remix-run/remix/issues/927
1170
- let location = useLocation();
1171
- if (action == null) {
1172
- // Safe to write to this directly here since if action was undefined, we
1173
- // would have called useResolvedPath(".") which will never include a search
1174
- path.search = location.search;
1175
-
1176
- // When grabbing search params from the URL, remove any included ?index param
1177
- // since it might not apply to our contextual route. We add it back based
1178
- // on match.route.index below
1179
- let params = new URLSearchParams(path.search);
1180
- if (params.has("index") && params.get("index") === "") {
1181
- params.delete("index");
1182
- path.search = params.toString() ? `?${params.toString()}` : "";
1183
- }
1184
- }
1185
- if ((!action || action === ".") && match.route.index) {
1186
- path.search = path.search ? path.search.replace(/^\?/, "?index&") : "?index";
1187
- }
1188
-
1189
- // If we're operating within a basename, prepend it to the pathname prior
1190
- // to creating the form action. If this is a root navigation, then just use
1191
- // the raw basename which allows the basename to have full control over the
1192
- // presence of a trailing slash on root actions
1193
- if (basename !== "/") {
1194
- path.pathname = path.pathname === "/" ? basename : joinPaths([basename, path.pathname]);
1195
- }
1196
- return createPath(path);
1197
- }
1198
- // TODO: (v7) Change the useFetcher generic default from `any` to `unknown`
1199
- /**
1200
- * Interacts with route loaders and actions without causing a navigation. Great
1201
- * for any interaction that stays on the same page.
1202
- */
1203
- function useFetcher({
1204
- key
1205
- } = {}) {
1206
- let {
1207
- router
1208
- } = useDataRouterContext(DataRouterHook.UseFetcher);
1209
- let state = useDataRouterState(DataRouterStateHook.UseFetcher);
1210
- let fetcherData = React.useContext(FetchersContext);
1211
- let route = React.useContext(UNSAFE_RouteContext);
1212
- let routeId = route.matches[route.matches.length - 1]?.route.id;
1213
- !fetcherData ? UNSAFE_invariant(false, `useFetcher must be used inside a FetchersContext`) : void 0;
1214
- !route ? UNSAFE_invariant(false, `useFetcher must be used inside a RouteContext`) : void 0;
1215
- !(routeId != null) ? UNSAFE_invariant(false, `useFetcher can only be used on routes that contain a unique "id"`) : void 0;
1216
-
1217
- // Fetcher key handling
1218
- // OK to call conditionally to feature detect `useId`
1219
- // eslint-disable-next-line react-hooks/rules-of-hooks
1220
- let defaultKey = useIdImpl ? useIdImpl() : "";
1221
- let [fetcherKey, setFetcherKey] = React.useState(key || defaultKey);
1222
- if (key && key !== fetcherKey) {
1223
- setFetcherKey(key);
1224
- } else if (!fetcherKey) {
1225
- // We will only fall through here when `useId` is not available
1226
- setFetcherKey(getUniqueFetcherId());
1227
- }
1228
-
1229
- // Registration/cleanup
1230
- React.useEffect(() => {
1231
- router.getFetcher(fetcherKey);
1232
- return () => {
1233
- // Tell the router we've unmounted - if v7_fetcherPersist is enabled this
1234
- // will not delete immediately but instead queue up a delete after the
1235
- // fetcher returns to an `idle` state
1236
- router.deleteFetcher(fetcherKey);
1237
- };
1238
- }, [router, fetcherKey]);
1239
-
1240
- // Fetcher additions
1241
- let load = React.useCallback((href, opts) => {
1242
- !routeId ? UNSAFE_invariant(false, "No routeId available for fetcher.load()") : void 0;
1243
- router.fetch(fetcherKey, routeId, href, opts);
1244
- }, [fetcherKey, routeId, router]);
1245
- let submitImpl = useSubmit();
1246
- let submit = React.useCallback((target, opts) => {
1247
- submitImpl(target, {
1248
- ...opts,
1249
- navigate: false,
1250
- fetcherKey
1251
- });
1252
- }, [fetcherKey, submitImpl]);
1253
- let FetcherForm = React.useMemo(() => {
1254
- let FetcherForm = /*#__PURE__*/React.forwardRef((props, ref) => {
1255
- return /*#__PURE__*/React.createElement(Form, Object.assign({}, props, {
1256
- navigate: false,
1257
- fetcherKey: fetcherKey,
1258
- ref: ref
1259
- }));
1260
- });
1261
- {
1262
- FetcherForm.displayName = "fetcher.Form";
1263
- }
1264
- return FetcherForm;
1265
- }, [fetcherKey]);
1266
-
1267
- // Exposed FetcherWithComponents
1268
- let fetcher = state.fetchers.get(fetcherKey) || IDLE_FETCHER;
1269
- let data = fetcherData.get(fetcherKey);
1270
- let fetcherWithComponents = React.useMemo(() => ({
1271
- Form: FetcherForm,
1272
- submit,
1273
- load,
1274
- ...fetcher,
1275
- data
1276
- }), [FetcherForm, submit, load, fetcher, data]);
1277
- return fetcherWithComponents;
1278
- }
1279
-
1280
- /**
1281
- * Provides all fetchers currently on the page. Useful for layouts and parent
1282
- * routes that need to provide pending/optimistic UI regarding the fetch.
1283
- */
1284
- function useFetchers() {
1285
- let state = useDataRouterState(DataRouterStateHook.UseFetchers);
1286
- return Array.from(state.fetchers.entries()).map(([key, fetcher]) => ({
1287
- ...fetcher,
1288
- key
1289
- }));
1290
- }
1291
- const SCROLL_RESTORATION_STORAGE_KEY = "react-router-scroll-positions";
1292
- let savedScrollPositions = {};
1293
-
1294
- /**
1295
- * When rendered inside a RouterProvider, will restore scroll positions on navigations
1296
- */
1297
- function useScrollRestoration({
1298
- getKey,
1299
- storageKey
1300
- } = {}) {
1301
- let {
1302
- router
1303
- } = useDataRouterContext(DataRouterHook.UseScrollRestoration);
1304
- let {
1305
- restoreScrollPosition,
1306
- preventScrollReset
1307
- } = useDataRouterState(DataRouterStateHook.UseScrollRestoration);
1308
- let {
1309
- basename
1310
- } = React.useContext(UNSAFE_NavigationContext);
1311
- let location = useLocation();
1312
- let matches = useMatches();
1313
- let navigation = useNavigation();
1314
-
1315
- // Trigger manual scroll restoration while we're active
1316
- React.useEffect(() => {
1317
- window.history.scrollRestoration = "manual";
1318
- return () => {
1319
- window.history.scrollRestoration = "auto";
1320
- };
1321
- }, []);
1322
-
1323
- // Save positions on pagehide
1324
- usePageHide(React.useCallback(() => {
1325
- if (navigation.state === "idle") {
1326
- let key = (getKey ? getKey(location, matches) : null) || location.key;
1327
- savedScrollPositions[key] = window.scrollY;
1328
- }
1329
- try {
1330
- sessionStorage.setItem(storageKey || SCROLL_RESTORATION_STORAGE_KEY, JSON.stringify(savedScrollPositions));
1331
- } catch (error) {
1332
- UNSAFE_warning(false, `Failed to save scroll positions in sessionStorage, <ScrollRestoration /> will not work properly (${error}).`) ;
1333
- }
1334
- window.history.scrollRestoration = "auto";
1335
- }, [storageKey, getKey, navigation.state, location, matches]));
1336
-
1337
- // Read in any saved scroll locations
1338
- if (typeof document !== "undefined") {
1339
- // eslint-disable-next-line react-hooks/rules-of-hooks
1340
- React.useLayoutEffect(() => {
1341
- try {
1342
- let sessionPositions = sessionStorage.getItem(storageKey || SCROLL_RESTORATION_STORAGE_KEY);
1343
- if (sessionPositions) {
1344
- savedScrollPositions = JSON.parse(sessionPositions);
1345
- }
1346
- } catch (e) {
1347
- // no-op, use default empty object
1348
- }
1349
- }, [storageKey]);
1350
-
1351
- // Enable scroll restoration in the router
1352
- // eslint-disable-next-line react-hooks/rules-of-hooks
1353
- React.useLayoutEffect(() => {
1354
- let getKeyWithoutBasename = getKey && basename !== "/" ? (location, matches) => getKey(
1355
- // Strip the basename to match useLocation()
1356
- {
1357
- ...location,
1358
- pathname: stripBasename(location.pathname, basename) || location.pathname
1359
- }, matches) : getKey;
1360
- let disableScrollRestoration = router?.enableScrollRestoration(savedScrollPositions, () => window.scrollY, getKeyWithoutBasename);
1361
- return () => disableScrollRestoration && disableScrollRestoration();
1362
- }, [router, basename, getKey]);
1363
-
1364
- // Restore scrolling when state.restoreScrollPosition changes
1365
- // eslint-disable-next-line react-hooks/rules-of-hooks
1366
- React.useLayoutEffect(() => {
1367
- // Explicit false means don't do anything (used for submissions)
1368
- if (restoreScrollPosition === false) {
1369
- return;
1370
- }
1371
-
1372
- // been here before, scroll to it
1373
- if (typeof restoreScrollPosition === "number") {
1374
- window.scrollTo(0, restoreScrollPosition);
1375
- return;
1376
- }
1377
-
1378
- // try to scroll to the hash
1379
- if (location.hash) {
1380
- let el = document.getElementById(decodeURIComponent(location.hash.slice(1)));
1381
- if (el) {
1382
- el.scrollIntoView();
1383
- return;
1384
- }
1385
- }
1386
-
1387
- // Don't reset if this navigation opted out
1388
- if (preventScrollReset === true) {
1389
- return;
1390
- }
1391
-
1392
- // otherwise go to the top on new locations
1393
- window.scrollTo(0, 0);
1394
- }, [location, restoreScrollPosition, preventScrollReset]);
1395
- }
1396
- }
1397
-
1398
- /**
1399
- * Setup a callback to be fired on the window's `beforeunload` event. This is
1400
- * useful for saving some data to `window.localStorage` just before the page
1401
- * refreshes.
1402
- *
1403
- * Note: The `callback` argument should be a function created with
1404
- * `React.useCallback()`.
1405
- */
1406
- function useBeforeUnload(callback, options) {
1407
- let {
1408
- capture
1409
- } = options || {};
1410
- React.useEffect(() => {
1411
- let opts = capture != null ? {
1412
- capture
1413
- } : undefined;
1414
- window.addEventListener("beforeunload", callback, opts);
1415
- return () => {
1416
- window.removeEventListener("beforeunload", callback, opts);
1417
- };
1418
- }, [callback, capture]);
1419
- }
1420
-
1421
- /**
1422
- * Setup a callback to be fired on the window's `pagehide` event. This is
1423
- * useful for saving some data to `window.localStorage` just before the page
1424
- * refreshes. This event is better supported than beforeunload across browsers.
1425
- *
1426
- * Note: The `callback` argument should be a function created with
1427
- * `React.useCallback()`.
1428
- */
1429
- function usePageHide(callback, options) {
1430
- let {
1431
- capture
1432
- } = options || {};
1433
- React.useEffect(() => {
1434
- let opts = capture != null ? {
1435
- capture
1436
- } : undefined;
1437
- window.addEventListener("pagehide", callback, opts);
1438
- return () => {
1439
- window.removeEventListener("pagehide", callback, opts);
1440
- };
1441
- }, [callback, capture]);
1442
- }
1443
-
1444
- /**
1445
- * Wrapper around useBlocker to show a window.confirm prompt to users instead
1446
- * of building a custom UI with useBlocker.
1447
- *
1448
- * Warning: This has *a lot of rough edges* and behaves very differently (and
1449
- * very incorrectly in some cases) across browsers if user click addition
1450
- * back/forward navigations while the confirm is open. Use at your own risk.
1451
- */
1452
- function usePrompt({
1453
- when,
1454
- message
1455
- }) {
1456
- let blocker = useBlocker(when);
1457
- React.useEffect(() => {
1458
- if (blocker.state === "blocked") {
1459
- let proceed = window.confirm(message);
1460
- if (proceed) {
1461
- // This timeout is needed to avoid a weird "race" on POP navigations
1462
- // between the `window.history` revert navigation and the result of
1463
- // `window.confirm`
1464
- setTimeout(blocker.proceed, 0);
1465
- } else {
1466
- blocker.reset();
1467
- }
1468
- }
1469
- }, [blocker, message]);
1470
- React.useEffect(() => {
1471
- if (blocker.state === "blocked" && !when) {
1472
- blocker.reset();
1473
- }
1474
- }, [blocker, when]);
1475
- }
1476
-
1477
- /**
1478
- * Return a boolean indicating if there is an active view transition to the
1479
- * given href. You can use this value to render CSS classes or viewTransitionName
1480
- * styles onto your elements
1481
- *
1482
- * @param href The destination href
1483
- * @param [opts.relative] Relative routing type ("route" | "path")
1484
- */
1485
- function useViewTransitionState(to, opts = {}) {
1486
- let vtContext = React.useContext(ViewTransitionContext);
1487
- !(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;
1488
- let {
1489
- basename
1490
- } = useDataRouterContext(DataRouterHook.useViewTransitionState);
1491
- let path = useResolvedPath(to, {
1492
- relative: opts.relative
1493
- });
1494
- if (!vtContext.isTransitioning) {
1495
- return false;
1496
- }
1497
- let currentPath = stripBasename(vtContext.currentLocation.pathname, basename) || vtContext.currentLocation.pathname;
1498
- let nextPath = stripBasename(vtContext.nextLocation.pathname, basename) || vtContext.nextLocation.pathname;
1499
-
1500
- // Transition is active if we're going to or coming from the indicated
1501
- // destination. This ensures that other PUSH navigations that reverse
1502
- // an indicated transition apply. I.e., on the list view you have:
1503
- //
1504
- // <NavLink to="/details/1" viewTransition>
1505
- //
1506
- // If you click the breadcrumb back to the list view:
1507
- //
1508
- // <NavLink to="/list" viewTransition>
1509
- //
1510
- // We should apply the transition because it's indicated as active going
1511
- // from /list -> /details/1 and therefore should be active on the reverse
1512
- // (even though this isn't strictly a POP reverse)
1513
- return matchPath(path.pathname, nextPath) != null || matchPath(path.pathname, currentPath) != null;
1514
- }
1515
-
1516
- //#endregion
1517
-
1518
- 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 };
11
+ export * from 'react-router';
1519
12
  //# sourceMappingURL=react-router-dom.development.js.map