-
-
Notifications
You must be signed in to change notification settings - Fork 10.3k
/
index.tsx
2049 lines (1855 loc) · 59 KB
/
index.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* NOTE: If you refactor this to split up the modules into separate files,
* you'll need to update the rollup config for react-router-dom-v5-compat.
*/
import * as React from "react";
import * as ReactDOM from "react-dom";
import type {
DataRouteObject,
FutureConfig,
Location,
NavigateOptions,
NavigationType,
Navigator,
RelativeRoutingType,
RouteObject,
RouterProps,
RouterProviderProps,
To,
unstable_DataStrategyFunction,
unstable_PatchRoutesOnNavigationFunction,
} from "react-router";
import {
Router,
createPath,
useHref,
useLocation,
useMatches,
useNavigate,
useNavigation,
useResolvedPath,
useBlocker,
UNSAFE_DataRouterContext as DataRouterContext,
UNSAFE_DataRouterStateContext as DataRouterStateContext,
UNSAFE_NavigationContext as NavigationContext,
UNSAFE_RouteContext as RouteContext,
UNSAFE_mapRouteProperties as mapRouteProperties,
UNSAFE_useRouteId as useRouteId,
UNSAFE_useRoutesImpl as useRoutesImpl,
} from "react-router";
import type {
BrowserHistory,
Fetcher,
FormEncType,
FormMethod,
FutureConfig as RouterFutureConfig,
GetScrollRestorationKeyFunction,
HashHistory,
History,
HTMLFormMethod,
HydrationState,
Router as RemixRouter,
V7_FormMethod,
RouterState,
RouterSubscriber,
BlockerFunction,
} from "@remix-run/router";
import {
createRouter,
createBrowserHistory,
createHashHistory,
joinPaths,
stripBasename,
UNSAFE_ErrorResponseImpl as ErrorResponseImpl,
UNSAFE_invariant as invariant,
UNSAFE_warning as warning,
matchPath,
IDLE_FETCHER,
} from "@remix-run/router";
import type {
SubmitOptions,
ParamKeyValuePair,
URLSearchParamsInit,
SubmitTarget,
FetcherSubmitOptions,
} from "./dom";
import {
createSearchParams,
defaultMethod,
getFormSubmissionInfo,
getSearchParamsForLocation,
shouldProcessLinkClick,
} from "./dom";
////////////////////////////////////////////////////////////////////////////////
//#region Re-exports
////////////////////////////////////////////////////////////////////////////////
export type {
FormEncType,
FormMethod,
GetScrollRestorationKeyFunction,
ParamKeyValuePair,
SubmitOptions,
URLSearchParamsInit,
V7_FormMethod,
};
export { createSearchParams, ErrorResponseImpl as UNSAFE_ErrorResponseImpl };
// Note: Keep in sync with react-router exports!
export type {
ActionFunction,
ActionFunctionArgs,
AwaitProps,
Blocker,
BlockerFunction,
DataRouteMatch,
DataRouteObject,
unstable_DataStrategyFunction,
unstable_DataStrategyFunctionArgs,
unstable_DataStrategyMatch,
unstable_DataStrategyResult,
ErrorResponse,
Fetcher,
FutureConfig,
Hash,
IndexRouteObject,
IndexRouteProps,
JsonFunction,
LazyRouteFunction,
LayoutRouteProps,
LoaderFunction,
LoaderFunctionArgs,
Location,
MemoryRouterProps,
NavigateFunction,
NavigateOptions,
NavigateProps,
Navigation,
Navigator,
NonIndexRouteObject,
OutletProps,
Params,
ParamParseKey,
Path,
PathMatch,
Pathname,
PathParam,
PathPattern,
PathRouteProps,
RedirectFunction,
RelativeRoutingType,
RouteMatch,
RouteObject,
RouteProps,
RouterProps,
RouterProviderProps,
RoutesProps,
Search,
ShouldRevalidateFunction,
ShouldRevalidateFunctionArgs,
To,
UIMatch,
unstable_PatchRoutesOnNavigationFunction,
} from "react-router";
export {
AbortedDeferredError,
Await,
MemoryRouter,
Navigate,
NavigationType,
Outlet,
Route,
Router,
Routes,
createMemoryRouter,
createPath,
createRoutesFromChildren,
createRoutesFromElements,
defer,
isRouteErrorResponse,
generatePath,
json,
matchPath,
matchRoutes,
parsePath,
redirect,
redirectDocument,
replace,
renderMatches,
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";
///////////////////////////////////////////////////////////////////////////////
// DANGER! PLEASE READ ME!
// We provide these exports as an escape hatch in the event that you need any
// routing data that we don't provide an explicit API for. With that said, we
// want to cover your use case if we can, so if you feel the need to use these
// we want to hear from you. Let us know what you're building and we'll do our
// best to make sure we can support you!
//
// We consider these exports an implementation detail and do not guarantee
// against any breaking changes, regardless of the semver release. Use with
// extreme caution and only if you understand the consequences. Godspeed.
///////////////////////////////////////////////////////////////////////////////
/** @internal */
export {
UNSAFE_DataRouterContext,
UNSAFE_DataRouterStateContext,
UNSAFE_NavigationContext,
UNSAFE_LocationContext,
UNSAFE_RouteContext,
UNSAFE_useRouteId,
} from "react-router";
//#endregion
declare global {
var __staticRouterHydrationData: HydrationState | undefined;
var __reactRouterVersion: string;
interface Document {
startViewTransition(cb: () => Promise<void> | void): ViewTransition;
}
}
// HEY YOU! DON'T TOUCH THIS VARIABLE!
//
// It is replaced with the proper version at build time via a babel plugin in
// the rollup config.
//
// Export a global property onto the window for React Router detection by the
// Core Web Vitals Technology Report. This way they can configure the `wappalyzer`
// to detect and properly classify live websites as being built with React Router:
// https://github.com/HTTPArchive/wappalyzer/blob/main/src/technologies/r.json
const REACT_ROUTER_VERSION = "0";
try {
window.__reactRouterVersion = REACT_ROUTER_VERSION;
} catch (e) {
// no-op
}
////////////////////////////////////////////////////////////////////////////////
//#region Routers
////////////////////////////////////////////////////////////////////////////////
interface DOMRouterOpts {
basename?: string;
future?: Partial<Omit<RouterFutureConfig, "v7_prependBasename">>;
hydrationData?: HydrationState;
unstable_dataStrategy?: unstable_DataStrategyFunction;
unstable_patchRoutesOnNavigation?: unstable_PatchRoutesOnNavigationFunction;
window?: Window;
}
export function createBrowserRouter(
routes: RouteObject[],
opts?: DOMRouterOpts
): RemixRouter {
return createRouter({
basename: opts?.basename,
future: {
...opts?.future,
v7_prependBasename: true,
},
history: createBrowserHistory({ window: opts?.window }),
hydrationData: opts?.hydrationData || parseHydrationData(),
routes,
mapRouteProperties,
unstable_dataStrategy: opts?.unstable_dataStrategy,
unstable_patchRoutesOnNavigation: opts?.unstable_patchRoutesOnNavigation,
window: opts?.window,
}).initialize();
}
export function createHashRouter(
routes: RouteObject[],
opts?: DOMRouterOpts
): RemixRouter {
return createRouter({
basename: opts?.basename,
future: {
...opts?.future,
v7_prependBasename: true,
},
history: createHashHistory({ window: opts?.window }),
hydrationData: opts?.hydrationData || parseHydrationData(),
routes,
mapRouteProperties,
unstable_dataStrategy: opts?.unstable_dataStrategy,
unstable_patchRoutesOnNavigation: opts?.unstable_patchRoutesOnNavigation,
window: opts?.window,
}).initialize();
}
function parseHydrationData(): HydrationState | undefined {
let state = window?.__staticRouterHydrationData;
if (state && state.errors) {
state = {
...state,
errors: deserializeErrors(state.errors),
};
}
return state;
}
function deserializeErrors(
errors: RemixRouter["state"]["errors"]
): RemixRouter["state"]["errors"] {
if (!errors) return null;
let entries = Object.entries(errors);
let serialized: RemixRouter["state"]["errors"] = {};
for (let [key, val] of entries) {
// Hey you! If you change this, please change the corresponding logic in
// serializeErrors in react-router-dom/server.tsx :)
if (val && val.__type === "RouteErrorResponse") {
serialized[key] = new ErrorResponseImpl(
val.status,
val.statusText,
val.data,
val.internal === true
);
} else if (val && val.__type === "Error") {
// Attempt to reconstruct the right type of Error (i.e., ReferenceError)
if (val.__subType) {
let ErrorConstructor = window[val.__subType];
if (typeof ErrorConstructor === "function") {
try {
// @ts-expect-error
let error = new ErrorConstructor(val.message);
// Wipe away the client-side stack trace. Nothing to fill it in with
// because we don't serialize SSR stack traces for security reasons
error.stack = "";
serialized[key] = error;
} catch (e) {
// no-op - fall through and create a normal Error
}
}
}
if (serialized[key] == null) {
let error = new Error(val.message);
// Wipe away the client-side stack trace. Nothing to fill it in with
// because we don't serialize SSR stack traces for security reasons
error.stack = "";
serialized[key] = error;
}
} else {
serialized[key] = val;
}
}
return serialized;
}
//#endregion
////////////////////////////////////////////////////////////////////////////////
//#region Contexts
////////////////////////////////////////////////////////////////////////////////
type ViewTransitionContextObject =
| {
isTransitioning: false;
}
| {
isTransitioning: true;
flushSync: boolean;
currentLocation: Location;
nextLocation: Location;
};
const ViewTransitionContext = React.createContext<ViewTransitionContextObject>({
isTransitioning: false,
});
if (__DEV__) {
ViewTransitionContext.displayName = "ViewTransition";
}
export { ViewTransitionContext as UNSAFE_ViewTransitionContext };
// TODO: (v7) Change the useFetcher data from `any` to `unknown`
type FetchersContextObject = Map<string, any>;
const FetchersContext = React.createContext<FetchersContextObject>(new Map());
if (__DEV__) {
FetchersContext.displayName = "Fetchers";
}
export { FetchersContext as UNSAFE_FetchersContext };
//#endregion
////////////////////////////////////////////////////////////////////////////////
//#region Components
////////////////////////////////////////////////////////////////////////////////
/**
Webpack + React 17 fails to compile on any of the following because webpack
complains that `startTransition` doesn't exist in `React`:
* import { startTransition } from "react"
* import * as React from from "react";
"startTransition" in React ? React.startTransition(() => setState()) : setState()
* import * as React from from "react";
"startTransition" in React ? React["startTransition"](() => setState()) : setState()
Moving it to a constant such as the following solves the Webpack/React 17 issue:
* import * as React from from "react";
const START_TRANSITION = "startTransition";
START_TRANSITION in React ? React[START_TRANSITION](() => setState()) : setState()
However, that introduces webpack/terser minification issues in production builds
in React 18 where minification/obfuscation ends up removing the call of
React.startTransition entirely from the first half of the ternary. Grabbing
this exported reference once up front resolves that issue.
See https://github.com/remix-run/react-router/issues/10579
*/
const START_TRANSITION = "startTransition";
const startTransitionImpl = React[START_TRANSITION];
const FLUSH_SYNC = "flushSync";
const flushSyncImpl = ReactDOM[FLUSH_SYNC];
const USE_ID = "useId";
const useIdImpl = React[USE_ID];
function startTransitionSafe(cb: () => void) {
if (startTransitionImpl) {
startTransitionImpl(cb);
} else {
cb();
}
}
function flushSyncSafe(cb: () => void) {
if (flushSyncImpl) {
flushSyncImpl(cb);
} else {
cb();
}
}
interface ViewTransition {
finished: Promise<void>;
ready: Promise<void>;
updateCallbackDone: Promise<void>;
skipTransition(): void;
}
class Deferred<T> {
status: "pending" | "resolved" | "rejected" = "pending";
promise: Promise<T>;
// @ts-expect-error - no initializer
resolve: (value: T) => void;
// @ts-expect-error - no initializer
reject: (reason?: unknown) => void;
constructor() {
this.promise = new Promise((resolve, reject) => {
this.resolve = (value) => {
if (this.status === "pending") {
this.status = "resolved";
resolve(value);
}
};
this.reject = (reason) => {
if (this.status === "pending") {
this.status = "rejected";
reject(reason);
}
};
});
}
}
/**
* Given a Remix Router instance, render the appropriate UI
*/
export function RouterProvider({
fallbackElement,
router,
future,
}: RouterProviderProps): React.ReactElement {
let [state, setStateImpl] = React.useState(router.state);
let [pendingState, setPendingState] = React.useState<RouterState>();
let [vtContext, setVtContext] = React.useState<ViewTransitionContextObject>({
isTransitioning: false,
});
let [renderDfd, setRenderDfd] = React.useState<Deferred<void>>();
let [transition, setTransition] = React.useState<ViewTransition>();
let [interruption, setInterruption] = React.useState<{
state: RouterState;
currentLocation: Location;
nextLocation: Location;
}>();
let fetcherData = React.useRef<Map<string, any>>(new Map());
let { v7_startTransition } = future || {};
let optInStartTransition = React.useCallback(
(cb: () => void) => {
if (v7_startTransition) {
startTransitionSafe(cb);
} else {
cb();
}
},
[v7_startTransition]
);
let setState = React.useCallback<RouterSubscriber>(
(
newState: RouterState,
{
deletedFetchers,
unstable_flushSync: flushSync,
unstable_viewTransitionOpts: viewTransitionOpts,
}
) => {
deletedFetchers.forEach((key) => fetcherData.current.delete(key));
newState.fetchers.forEach((fetcher, key) => {
if (fetcher.data !== undefined) {
fetcherData.current.set(key, fetcher.data);
}
});
let isViewTransitionUnavailable =
router.window == null ||
router.window.document == null ||
typeof router.window.document.startViewTransition !== "function";
// If this isn't a view transition or it's not available in this browser,
// just update and be done with it
if (!viewTransitionOpts || isViewTransitionUnavailable) {
if (flushSync) {
flushSyncSafe(() => setStateImpl(newState));
} else {
optInStartTransition(() => setStateImpl(newState));
}
return;
}
// flushSync + startViewTransition
if (flushSync) {
// Flush through the context to mark DOM elements as transition=ing
flushSyncSafe(() => {
// Cancel any pending transitions
if (transition) {
renderDfd && renderDfd.resolve();
transition.skipTransition();
}
setVtContext({
isTransitioning: true,
flushSync: true,
currentLocation: viewTransitionOpts.currentLocation,
nextLocation: viewTransitionOpts.nextLocation,
});
});
// Update the DOM
let t = router.window!.document.startViewTransition(() => {
flushSyncSafe(() => setStateImpl(newState));
});
// Clean up after the animation completes
t.finished.finally(() => {
flushSyncSafe(() => {
setRenderDfd(undefined);
setTransition(undefined);
setPendingState(undefined);
setVtContext({ isTransitioning: false });
});
});
flushSyncSafe(() => setTransition(t));
return;
}
// startTransition + startViewTransition
if (transition) {
// Interrupting an in-progress transition, cancel and let everything flush
// out, and then kick off a new transition from the interruption state
renderDfd && renderDfd.resolve();
transition.skipTransition();
setInterruption({
state: newState,
currentLocation: viewTransitionOpts.currentLocation,
nextLocation: viewTransitionOpts.nextLocation,
});
} else {
// Completed navigation update with opted-in view transitions, let 'er rip
setPendingState(newState);
setVtContext({
isTransitioning: true,
flushSync: false,
currentLocation: viewTransitionOpts.currentLocation,
nextLocation: viewTransitionOpts.nextLocation,
});
}
},
[router.window, transition, renderDfd, fetcherData, optInStartTransition]
);
// Need to use a layout effect here so we are subscribed early enough to
// pick up on any render-driven redirects/navigations (useEffect/<Navigate>)
React.useLayoutEffect(() => router.subscribe(setState), [router, setState]);
// When we start a view transition, create a Deferred we can use for the
// eventual "completed" render
React.useEffect(() => {
if (vtContext.isTransitioning && !vtContext.flushSync) {
setRenderDfd(new Deferred<void>());
}
}, [vtContext]);
// Once the deferred is created, kick off startViewTransition() to update the
// DOM and then wait on the Deferred to resolve (indicating the DOM update has
// happened)
React.useEffect(() => {
if (renderDfd && pendingState && router.window) {
let newState = pendingState;
let renderPromise = renderDfd.promise;
let transition = router.window.document.startViewTransition(async () => {
optInStartTransition(() => setStateImpl(newState));
await renderPromise;
});
transition.finished.finally(() => {
setRenderDfd(undefined);
setTransition(undefined);
setPendingState(undefined);
setVtContext({ isTransitioning: false });
});
setTransition(transition);
}
}, [optInStartTransition, pendingState, renderDfd, router.window]);
// When the new location finally renders and is committed to the DOM, this
// effect will run to resolve the transition
React.useEffect(() => {
if (
renderDfd &&
pendingState &&
state.location.key === pendingState.location.key
) {
renderDfd.resolve();
}
}, [renderDfd, transition, state.location, pendingState]);
// If we get interrupted with a new navigation during a transition, we skip
// the active transition, let it cleanup, then kick it off again here
React.useEffect(() => {
if (!vtContext.isTransitioning && interruption) {
setPendingState(interruption.state);
setVtContext({
isTransitioning: true,
flushSync: false,
currentLocation: interruption.currentLocation,
nextLocation: interruption.nextLocation,
});
setInterruption(undefined);
}
}, [vtContext.isTransitioning, interruption]);
React.useEffect(() => {
warning(
fallbackElement == null || !router.future.v7_partialHydration,
"`<RouterProvider fallbackElement>` is deprecated when using " +
"`v7_partialHydration`, use a `HydrateFallback` component instead"
);
// Only log this once on initial mount
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
let navigator = React.useMemo((): Navigator => {
return {
createHref: router.createHref,
encodeLocation: router.encodeLocation,
go: (n) => router.navigate(n),
push: (to, state, opts) =>
router.navigate(to, {
state,
preventScrollReset: opts?.preventScrollReset,
}),
replace: (to, state, opts) =>
router.navigate(to, {
replace: true,
state,
preventScrollReset: opts?.preventScrollReset,
}),
};
}, [router]);
let basename = router.basename || "/";
let dataRouterContext = React.useMemo(
() => ({
router,
navigator,
static: false,
basename,
}),
[router, navigator, basename]
);
let routerFuture = React.useMemo<RouterProps["future"]>(
() => ({
v7_relativeSplatPath: router.future.v7_relativeSplatPath,
}),
[router.future.v7_relativeSplatPath]
);
// The fragment and {null} here are important! We need them to keep React 18's
// useId happy when we are server-rendering since we may have a <script> here
// containing the hydrated server-side staticContext (from StaticRouterProvider).
// useId relies on the component tree structure to generate deterministic id's
// so we need to ensure it remains the same on the client even though
// we don't need the <script> tag
return (
<>
<DataRouterContext.Provider value={dataRouterContext}>
<DataRouterStateContext.Provider value={state}>
<FetchersContext.Provider value={fetcherData.current}>
<ViewTransitionContext.Provider value={vtContext}>
<Router
basename={basename}
location={state.location}
navigationType={state.historyAction}
navigator={navigator}
future={routerFuture}
>
{state.initialized || router.future.v7_partialHydration ? (
<MemoizedDataRoutes
routes={router.routes}
future={router.future}
state={state}
/>
) : (
fallbackElement
)}
</Router>
</ViewTransitionContext.Provider>
</FetchersContext.Provider>
</DataRouterStateContext.Provider>
</DataRouterContext.Provider>
{null}
</>
);
}
// Memoize to avoid re-renders when updating `ViewTransitionContext`
const MemoizedDataRoutes = React.memo(DataRoutes);
function DataRoutes({
routes,
future,
state,
}: {
routes: DataRouteObject[];
future: RemixRouter["future"];
state: RouterState;
}): React.ReactElement | null {
return useRoutesImpl(routes, undefined, state, future);
}
export interface BrowserRouterProps {
basename?: string;
children?: React.ReactNode;
future?: Partial<FutureConfig>;
window?: Window;
}
/**
* A `<Router>` for use in web browsers. Provides the cleanest URLs.
*/
export function BrowserRouter({
basename,
children,
future,
window,
}: BrowserRouterProps) {
let historyRef = React.useRef<BrowserHistory>();
if (historyRef.current == null) {
historyRef.current = createBrowserHistory({ window, v5Compat: true });
}
let history = historyRef.current;
let [state, setStateImpl] = React.useState({
action: history.action,
location: history.location,
});
let { v7_startTransition } = future || {};
let setState = React.useCallback(
(newState: { action: NavigationType; location: Location }) => {
v7_startTransition && startTransitionImpl
? startTransitionImpl(() => setStateImpl(newState))
: setStateImpl(newState);
},
[setStateImpl, v7_startTransition]
);
React.useLayoutEffect(() => history.listen(setState), [history, setState]);
return (
<Router
basename={basename}
children={children}
location={state.location}
navigationType={state.action}
navigator={history}
future={future}
/>
);
}
export interface HashRouterProps {
basename?: string;
children?: React.ReactNode;
future?: Partial<FutureConfig>;
window?: Window;
}
/**
* A `<Router>` for use in web browsers. Stores the location in the hash
* portion of the URL so it is not sent to the server.
*/
export function HashRouter({
basename,
children,
future,
window,
}: HashRouterProps) {
let historyRef = React.useRef<HashHistory>();
if (historyRef.current == null) {
historyRef.current = createHashHistory({ window, v5Compat: true });
}
let history = historyRef.current;
let [state, setStateImpl] = React.useState({
action: history.action,
location: history.location,
});
let { v7_startTransition } = future || {};
let setState = React.useCallback(
(newState: { action: NavigationType; location: Location }) => {
v7_startTransition && startTransitionImpl
? startTransitionImpl(() => setStateImpl(newState))
: setStateImpl(newState);
},
[setStateImpl, v7_startTransition]
);
React.useLayoutEffect(() => history.listen(setState), [history, setState]);
return (
<Router
basename={basename}
children={children}
location={state.location}
navigationType={state.action}
navigator={history}
future={future}
/>
);
}
export interface HistoryRouterProps {
basename?: string;
children?: React.ReactNode;
future?: FutureConfig;
history: History;
}
/**
* A `<Router>` that accepts a pre-instantiated history object. It's important
* to note that using your own history object is highly discouraged and may add
* two versions of the history library to your bundles unless you use the same
* version of the history library that React Router uses internally.
*/
function HistoryRouter({
basename,
children,
future,
history,
}: HistoryRouterProps) {
let [state, setStateImpl] = React.useState({
action: history.action,
location: history.location,
});
let { v7_startTransition } = future || {};
let setState = React.useCallback(
(newState: { action: NavigationType; location: Location }) => {
v7_startTransition && startTransitionImpl
? startTransitionImpl(() => setStateImpl(newState))
: setStateImpl(newState);
},
[setStateImpl, v7_startTransition]
);
React.useLayoutEffect(() => history.listen(setState), [history, setState]);
return (
<Router
basename={basename}
children={children}
location={state.location}
navigationType={state.action}
navigator={history}
future={future}
/>
);
}
if (__DEV__) {
HistoryRouter.displayName = "unstable_HistoryRouter";
}
export { HistoryRouter as unstable_HistoryRouter };
export interface LinkProps
extends Omit<React.AnchorHTMLAttributes<HTMLAnchorElement>, "href"> {
reloadDocument?: boolean;
replace?: boolean;
state?: any;
preventScrollReset?: boolean;
relative?: RelativeRoutingType;
to: To;
unstable_viewTransition?: boolean;
}
const isBrowser =
typeof window !== "undefined" &&
typeof window.document !== "undefined" &&
typeof window.document.createElement !== "undefined";
const ABSOLUTE_URL_REGEX = /^(?:[a-z][a-z0-9+.-]*:|\/\/)/i;
/**
* The public API for rendering a history-aware `<a>`.
*/
export const Link = React.forwardRef<HTMLAnchorElement, LinkProps>(
function LinkWithRef(
{
onClick,
relative,
reloadDocument,
replace,
state,
target,
to,
preventScrollReset,
unstable_viewTransition,
...rest
},
ref
) {
let { basename } = React.useContext(NavigationContext);
// Rendered into <a href> for absolute URLs
let absoluteHref;
let isExternal = false;
if (typeof to === "string" && ABSOLUTE_URL_REGEX.test(to)) {
// Render the absolute href server- and client-side
absoluteHref = to;
// Only check for external origins client-side
if (isBrowser) {
try {
let currentUrl = new URL(window.location.href);
let targetUrl = to.startsWith("//")
? new URL(currentUrl.protocol + to)
: new URL(to);
let path = stripBasename(targetUrl.pathname, basename);
if (targetUrl.origin === currentUrl.origin && path != null) {
// Strip the protocol/origin/basename for same-origin absolute URLs
to = path + targetUrl.search + targetUrl.hash;
} else {
isExternal = true;
}
} catch (e) {
// We can't do external URL detection without a valid URL
warning(
false,
`<Link to="${to}"> contains an invalid URL which will probably break ` +
`when clicked - please update to a valid URL path.`
);
}
}
}
// Rendered into <a href> for relative URLs
let href = useHref(to, { relative });