-
-
Notifications
You must be signed in to change notification settings - Fork 10.2k
/
components.tsx
738 lines (658 loc) · 20.8 KB
/
components.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
import type {
InitialEntry,
LazyRouteFunction,
Location,
MemoryHistory,
RelativeRoutingType,
Router as RemixRouter,
RouterState,
RouterSubscriber,
To,
TrackedPromise,
} from "@remix-run/router";
import {
AbortedDeferredError,
Action as NavigationType,
createMemoryHistory,
UNSAFE_getResolveToMatches as getResolveToMatches,
UNSAFE_invariant as invariant,
parsePath,
resolveTo,
stripBasename,
UNSAFE_warning as warning,
} from "@remix-run/router";
import * as React from "react";
import type {
DataRouteObject,
IndexRouteObject,
Navigator,
NonIndexRouteObject,
RouteMatch,
RouteObject,
} from "./context";
import {
AwaitContext,
DataRouterContext,
DataRouterStateContext,
LocationContext,
NavigationContext,
RouteContext,
} from "./context";
import {
_renderMatches,
useAsyncValue,
useInRouterContext,
useLocation,
useNavigate,
useOutlet,
useRoutes,
useRoutesImpl,
} from "./hooks";
export interface FutureConfig {
v7_relativeSplatPath: boolean;
v7_startTransition: boolean;
}
export interface RouterProviderProps {
fallbackElement?: React.ReactNode;
router: RemixRouter;
// Only accept future flags relevant to rendering behavior
// routing flags should be accessed via router.future
future?: Partial<Pick<FutureConfig, "v7_startTransition">>;
}
/**
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];
/**
* 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 { v7_startTransition } = future || {};
let setState = React.useCallback<RouterSubscriber>(
(newState: RouterState) => {
if (v7_startTransition && startTransitionImpl) {
startTransitionImpl(() => setStateImpl(newState));
} else {
setStateImpl(newState);
}
},
[setStateImpl, v7_startTransition]
);
// 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]);
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]
);
// 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}>
<Router
basename={basename}
location={state.location}
navigationType={state.historyAction}
navigator={navigator}
future={{
v7_relativeSplatPath: router.future.v7_relativeSplatPath,
}}
>
{state.initialized || router.future.v7_partialHydration ? (
<DataRoutes
routes={router.routes}
future={router.future}
state={state}
/>
) : (
fallbackElement
)}
</Router>
</DataRouterStateContext.Provider>
</DataRouterContext.Provider>
{null}
</>
);
}
function DataRoutes({
routes,
future,
state,
}: {
routes: DataRouteObject[];
future: RemixRouter["future"];
state: RouterState;
}): React.ReactElement | null {
return useRoutesImpl(routes, undefined, state, future);
}
export interface MemoryRouterProps {
basename?: string;
children?: React.ReactNode;
initialEntries?: InitialEntry[];
initialIndex?: number;
future?: Partial<FutureConfig>;
}
/**
* A `<Router>` that stores all entries in memory.
*
* @see https://reactrouter.com/router-components/memory-router
*/
export function MemoryRouter({
basename,
children,
initialEntries,
initialIndex,
future,
}: MemoryRouterProps): React.ReactElement {
let historyRef = React.useRef<MemoryHistory>();
if (historyRef.current == null) {
historyRef.current = createMemoryHistory({
initialEntries,
initialIndex,
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 NavigateProps {
to: To;
replace?: boolean;
state?: any;
relative?: RelativeRoutingType;
}
/**
* Changes the current location.
*
* Note: This API is mostly useful in React.Component subclasses that are not
* able to use hooks. In functional components, we recommend you use the
* `useNavigate` hook instead.
*
* @see https://reactrouter.com/components/navigate
*/
export function Navigate({
to,
replace,
state,
relative,
}: NavigateProps): null {
invariant(
useInRouterContext(),
// TODO: This error is probably because they somehow have 2 versions of
// the router loaded. We can help them understand how to avoid that.
`<Navigate> may be used only in the context of a <Router> component.`
);
let { future, static: isStatic } = React.useContext(NavigationContext);
warning(
!isStatic,
`<Navigate> must not be used on the initial render in a <StaticRouter>. ` +
`This is a no-op, but you should modify your code so the <Navigate> is ` +
`only ever rendered in response to some user interaction or state change.`
);
let { matches } = React.useContext(RouteContext);
let { pathname: locationPathname } = useLocation();
let navigate = useNavigate();
// Resolve the path outside of the effect so that when effects run twice in
// StrictMode they navigate to the same place
let path = resolveTo(
to,
getResolveToMatches(matches, future.v7_relativeSplatPath),
locationPathname,
relative === "path"
);
let jsonPath = JSON.stringify(path);
React.useEffect(
() => navigate(JSON.parse(jsonPath), { replace, state, relative }),
[navigate, jsonPath, relative, replace, state]
);
return null;
}
export interface OutletProps {
context?: unknown;
}
/**
* Renders the child route's element, if there is one.
*
* @see https://reactrouter.com/components/outlet
*/
export function Outlet(props: OutletProps): React.ReactElement | null {
return useOutlet(props.context);
}
export interface PathRouteProps {
caseSensitive?: NonIndexRouteObject["caseSensitive"];
path?: NonIndexRouteObject["path"];
id?: NonIndexRouteObject["id"];
lazy?: LazyRouteFunction<NonIndexRouteObject>;
loader?: NonIndexRouteObject["loader"];
action?: NonIndexRouteObject["action"];
hasErrorBoundary?: NonIndexRouteObject["hasErrorBoundary"];
shouldRevalidate?: NonIndexRouteObject["shouldRevalidate"];
handle?: NonIndexRouteObject["handle"];
index?: false;
children?: React.ReactNode;
element?: React.ReactNode | null;
hydrateFallbackElement?: React.ReactNode | null;
errorElement?: React.ReactNode | null;
Component?: React.ComponentType | null;
HydrateFallback?: React.ComponentType | null;
ErrorBoundary?: React.ComponentType | null;
}
export interface LayoutRouteProps extends PathRouteProps {}
export interface IndexRouteProps {
caseSensitive?: IndexRouteObject["caseSensitive"];
path?: IndexRouteObject["path"];
id?: IndexRouteObject["id"];
lazy?: LazyRouteFunction<IndexRouteObject>;
loader?: IndexRouteObject["loader"];
action?: IndexRouteObject["action"];
hasErrorBoundary?: IndexRouteObject["hasErrorBoundary"];
shouldRevalidate?: IndexRouteObject["shouldRevalidate"];
handle?: IndexRouteObject["handle"];
index: true;
children?: undefined;
element?: React.ReactNode | null;
hydrateFallbackElement?: React.ReactNode | null;
errorElement?: React.ReactNode | null;
Component?: React.ComponentType | null;
HydrateFallback?: React.ComponentType | null;
ErrorBoundary?: React.ComponentType | null;
}
export type RouteProps = PathRouteProps | LayoutRouteProps | IndexRouteProps;
/**
* Declares an element that should be rendered at a certain URL path.
*
* @see https://reactrouter.com/components/route
*/
export function Route(_props: RouteProps): React.ReactElement | null {
invariant(
false,
`A <Route> is only ever to be used as the child of <Routes> element, ` +
`never rendered directly. Please wrap your <Route> in a <Routes>.`
);
}
export interface RouterProps {
basename?: string;
children?: React.ReactNode;
location: Partial<Location> | string;
navigationType?: NavigationType;
navigator: Navigator;
static?: boolean;
future?: Partial<Pick<FutureConfig, "v7_relativeSplatPath">>;
}
/**
* Provides location context for the rest of the app.
*
* Note: You usually won't render a `<Router>` directly. Instead, you'll render a
* router that is more specific to your environment such as a `<BrowserRouter>`
* in web browsers or a `<StaticRouter>` for server rendering.
*
* @see https://reactrouter.com/router-components/router
*/
export function Router({
basename: basenameProp = "/",
children = null,
location: locationProp,
navigationType = NavigationType.Pop,
navigator,
static: staticProp = false,
future,
}: RouterProps): React.ReactElement | null {
invariant(
!useInRouterContext(),
`You cannot render a <Router> inside another <Router>.` +
` You should never have more than one in your app.`
);
// Preserve trailing slashes on basename, so we can let the user control
// the enforcement of trailing slashes throughout the app
let basename = basenameProp.replace(/^\/*/, "/");
let navigationContext = React.useMemo(
() => ({
basename,
navigator,
static: staticProp,
future: {
v7_relativeSplatPath: false,
...future,
},
}),
[basename, future, navigator, staticProp]
);
if (typeof locationProp === "string") {
locationProp = parsePath(locationProp) as Partial<Location>;
}
let {
pathname = "/",
search = "",
hash = "",
state = null,
key = "default",
} = locationProp;
let locationContext = React.useMemo(() => {
let trailingPathname = stripBasename(pathname, basename);
if (trailingPathname == null) {
return null;
}
return {
location: {
pathname: trailingPathname as Location["pathname"],
search,
hash,
state,
key,
},
navigationType,
};
}, [basename, pathname, search, hash, state, key, navigationType]);
warning(
locationContext != null,
`<Router basename="${basename}"> is not able to match the URL ` +
`"${pathname}${search}${hash}" because it does not start with the ` +
`basename, so the <Router> won't render anything.`
);
if (locationContext == null) {
return null;
}
return (
<NavigationContext.Provider value={navigationContext}>
<LocationContext.Provider children={children} value={locationContext} />
</NavigationContext.Provider>
);
}
export interface RoutesProps {
children?: React.ReactNode;
location?: Partial<Location> | string;
}
/**
* A container for a nested tree of `<Route>` elements that renders the branch
* that best matches the current location.
*
* @see https://reactrouter.com/components/routes
*/
export function Routes({
children,
location,
}: RoutesProps): React.ReactElement | null {
return useRoutes(createRoutesFromChildren(children), location);
}
export interface AwaitResolveRenderFunction {
(data: Awaited<any>): React.ReactNode;
}
export interface AwaitProps {
children: React.ReactNode | AwaitResolveRenderFunction;
errorElement?: React.ReactNode;
resolve: TrackedPromise | any;
}
/**
* Component to use for rendering lazily loaded data from returning defer()
* in a loader function
*/
export function Await({ children, errorElement, resolve }: AwaitProps) {
return (
<AwaitErrorBoundary resolve={resolve} errorElement={errorElement}>
<ResolveAwait>{children}</ResolveAwait>
</AwaitErrorBoundary>
);
}
type AwaitErrorBoundaryProps = React.PropsWithChildren<{
errorElement?: React.ReactNode;
resolve: TrackedPromise | any;
}>;
type AwaitErrorBoundaryState = {
error: any;
};
enum AwaitRenderStatus {
pending,
success,
error,
}
const neverSettledPromise = new Promise(() => {});
class AwaitErrorBoundary extends React.Component<
AwaitErrorBoundaryProps,
AwaitErrorBoundaryState
> {
constructor(props: AwaitErrorBoundaryProps) {
super(props);
this.state = { error: null };
}
static getDerivedStateFromError(error: any) {
return { error };
}
componentDidCatch(error: any, errorInfo: any) {
console.error(
"<Await> caught the following error during render",
error,
errorInfo
);
}
render() {
let { children, errorElement, resolve } = this.props;
let promise: TrackedPromise | null = null;
let status: AwaitRenderStatus = AwaitRenderStatus.pending;
if (!(resolve instanceof Promise)) {
// Didn't get a promise - provide as a resolved promise
status = AwaitRenderStatus.success;
promise = Promise.resolve();
Object.defineProperty(promise, "_tracked", { get: () => true });
Object.defineProperty(promise, "_data", { get: () => resolve });
} else if (this.state.error) {
// Caught a render error, provide it as a rejected promise
status = AwaitRenderStatus.error;
let renderError = this.state.error;
promise = Promise.reject().catch(() => {}); // Avoid unhandled rejection warnings
Object.defineProperty(promise, "_tracked", { get: () => true });
Object.defineProperty(promise, "_error", { get: () => renderError });
} else if ((resolve as TrackedPromise)._tracked) {
// Already tracked promise - check contents
promise = resolve;
status =
promise._error !== undefined
? AwaitRenderStatus.error
: promise._data !== undefined
? AwaitRenderStatus.success
: AwaitRenderStatus.pending;
} else {
// Raw (untracked) promise - track it
status = AwaitRenderStatus.pending;
Object.defineProperty(resolve, "_tracked", { get: () => true });
promise = resolve.then(
(data: any) =>
Object.defineProperty(resolve, "_data", { get: () => data }),
(error: any) =>
Object.defineProperty(resolve, "_error", { get: () => error })
);
}
if (
status === AwaitRenderStatus.error &&
promise._error instanceof AbortedDeferredError
) {
// Freeze the UI by throwing a never resolved promise
throw neverSettledPromise;
}
if (status === AwaitRenderStatus.error && !errorElement) {
// No errorElement, throw to the nearest route-level error boundary
throw promise._error;
}
if (status === AwaitRenderStatus.error) {
// Render via our errorElement
return <AwaitContext.Provider value={promise} children={errorElement} />;
}
if (status === AwaitRenderStatus.success) {
// Render children with resolved value
return <AwaitContext.Provider value={promise} children={children} />;
}
// Throw to the suspense boundary
throw promise;
}
}
/**
* @private
* Indirection to leverage useAsyncValue for a render-prop API on `<Await>`
*/
function ResolveAwait({
children,
}: {
children: React.ReactNode | AwaitResolveRenderFunction;
}) {
let data = useAsyncValue();
let toRender = typeof children === "function" ? children(data) : children;
return <>{toRender}</>;
}
///////////////////////////////////////////////////////////////////////////////
// UTILS
///////////////////////////////////////////////////////////////////////////////
/**
* Creates a route config from a React "children" object, which is usually
* either a `<Route>` element or an array of them. Used internally by
* `<Routes>` to create a route config from its children.
*
* @see https://reactrouter.com/utils/create-routes-from-children
*/
export function createRoutesFromChildren(
children: React.ReactNode,
parentPath: number[] = []
): RouteObject[] {
let routes: RouteObject[] = [];
React.Children.forEach(children, (element, index) => {
if (!React.isValidElement(element)) {
// Ignore non-elements. This allows people to more easily inline
// conditionals in their route config.
return;
}
let treePath = [...parentPath, index];
if (element.type === React.Fragment) {
// Transparently support React.Fragment and its children.
routes.push.apply(
routes,
createRoutesFromChildren(element.props.children, treePath)
);
return;
}
invariant(
element.type === Route,
`[${
typeof element.type === "string" ? element.type : element.type.name
}] is not a <Route> component. All component children of <Routes> must be a <Route> or <React.Fragment>`
);
invariant(
!element.props.index || !element.props.children,
"An index route cannot have child routes."
);
let route: RouteObject = {
id: element.props.id || treePath.join("-"),
caseSensitive: element.props.caseSensitive,
element: element.props.element,
Component: element.props.Component,
index: element.props.index,
path: element.props.path,
loader: element.props.loader,
action: element.props.action,
errorElement: element.props.errorElement,
ErrorBoundary: element.props.ErrorBoundary,
hasErrorBoundary:
element.props.ErrorBoundary != null ||
element.props.errorElement != null,
shouldRevalidate: element.props.shouldRevalidate,
handle: element.props.handle,
lazy: element.props.lazy,
};
if (element.props.children) {
route.children = createRoutesFromChildren(
element.props.children,
treePath
);
}
routes.push(route);
});
return routes;
}
/**
* Renders the result of `matchRoutes()` into a React element.
*/
export function renderMatches(
matches: RouteMatch[] | null
): React.ReactElement | null {
return _renderMatches(matches);
}