-
-
Notifications
You must be signed in to change notification settings - Fork 10.4k
/
components.tsx
630 lines (562 loc) · 17 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
import * as React from "react";
import type {
TrackedPromise,
InitialEntry,
Location,
MemoryHistory,
Router as RemixRouter,
RouterState,
To,
} from "@remix-run/router";
import {
Action as NavigationType,
AbortedDeferredError,
createMemoryHistory,
invariant,
parsePath,
stripBasename,
warning,
} from "@remix-run/router";
import { useSyncExternalStore as useSyncExternalStoreShim } from "./use-sync-external-store-shim";
import type {
DataRouteObject,
IndexRouteObject,
RouteMatch,
RouteObject,
Navigator,
NonIndexRouteObject,
RelativeRoutingType,
} from "./context";
import {
LocationContext,
NavigationContext,
DataRouterContext,
DataRouterStateContext,
AwaitContext,
} from "./context";
import {
useAsyncValue,
useInRouterContext,
useNavigate,
useOutlet,
useRoutes,
_renderMatches,
} from "./hooks";
export interface RouterProviderProps {
fallbackElement?: React.ReactNode;
router: RemixRouter;
}
/**
* Given a Remix Router instance, render the appropriate UI
*/
export function RouterProvider({
fallbackElement,
router,
}: RouterProviderProps): React.ReactElement {
// Sync router state to our component state to force re-renders
let state: RouterState = useSyncExternalStoreShim(
router.subscribe,
() => router.state,
// We have to provide this so React@18 doesn't complain during hydration,
// but we pass our serialized hydration data into the router so state here
// is already synced with what the server saw
() => router.state
);
let navigator = React.useMemo((): Navigator => {
return {
createHref: router.createHref,
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 || "/";
return (
<DataRouterContext.Provider
value={{
router,
navigator,
static: false,
// Do we need this?
basename,
}}
>
<DataRouterStateContext.Provider value={state}>
<Router
basename={router.basename}
location={router.state.location}
navigationType={router.state.historyAction}
navigator={navigator}
>
{router.state.initialized ? <Routes /> : fallbackElement}
</Router>
</DataRouterStateContext.Provider>
</DataRouterContext.Provider>
);
}
export interface MemoryRouterProps {
basename?: string;
children?: React.ReactNode;
initialEntries?: InitialEntry[];
initialIndex?: number;
}
/**
* A <Router> that stores all entries in memory.
*
* @see https://reactrouter.com/docs/en/v6/routers/memory-router
*/
export function MemoryRouter({
basename,
children,
initialEntries,
initialIndex,
}: 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, setState] = React.useState({
action: history.action,
location: history.location,
});
React.useLayoutEffect(() => history.listen(setState), [history]);
return (
<Router
basename={basename}
children={children}
location={state.location}
navigationType={state.action}
navigator={history}
/>
);
}
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/docs/en/v6/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.`
);
warning(
!React.useContext(NavigationContext).static,
`<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 dataRouterState = React.useContext(DataRouterStateContext);
let navigate = useNavigate();
React.useEffect(() => {
// Avoid kicking off multiple navigations if we're in the middle of a
// data-router navigation, since components get re-rendered when we enter
// a submitting/loading state
if (dataRouterState && dataRouterState.navigation.state !== "idle") {
return;
}
navigate(to, { replace, state, relative });
});
return null;
}
export interface OutletProps {
context?: unknown;
}
/**
* Renders the child route's element, if there is one.
*
* @see https://reactrouter.com/docs/en/v6/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"];
loader?: NonIndexRouteObject["loader"];
action?: NonIndexRouteObject["action"];
hasErrorBoundary?: NonIndexRouteObject["hasErrorBoundary"];
shouldRevalidate?: NonIndexRouteObject["shouldRevalidate"];
handle?: NonIndexRouteObject["handle"];
index?: false;
children?: React.ReactNode;
element?: React.ReactNode | null;
errorElement?: React.ReactNode | null;
}
export interface LayoutRouteProps extends PathRouteProps {}
export interface IndexRouteProps {
caseSensitive?: IndexRouteObject["caseSensitive"];
path?: IndexRouteObject["path"];
id?: IndexRouteObject["id"];
loader?: IndexRouteObject["loader"];
action?: IndexRouteObject["action"];
hasErrorBoundary?: IndexRouteObject["hasErrorBoundary"];
shouldRevalidate?: IndexRouteObject["shouldRevalidate"];
handle?: IndexRouteObject["handle"];
index: true;
children?: undefined;
element?: React.ReactNode | null;
errorElement?: React.ReactNode | null;
}
export type RouteProps = PathRouteProps | LayoutRouteProps | IndexRouteProps;
/**
* Declares an element that should be rendered at a certain URL path.
*
* @see https://reactrouter.com/docs/en/v6/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;
}
/**
* 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/docs/en/v6/routers/router
*/
export function Router({
basename: basenameProp = "/",
children = null,
location: locationProp,
navigationType = NavigationType.Pop,
navigator,
static: staticProp = false,
}: 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 }),
[basename, navigator, staticProp]
);
if (typeof locationProp === "string") {
locationProp = parsePath(locationProp);
}
let {
pathname = "/",
search = "",
hash = "",
state = null,
key = "default",
} = locationProp;
let location = React.useMemo(() => {
let trailingPathname = stripBasename(pathname, basename);
if (trailingPathname == null) {
return null;
}
return {
pathname: trailingPathname,
search,
hash,
state,
key,
};
}, [basename, pathname, search, hash, state, key]);
warning(
location != 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 (location == null) {
return null;
}
return (
<NavigationContext.Provider value={navigationContext}>
<LocationContext.Provider
children={children}
value={{ location, navigationType }}
/>
</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/docs/en/v6/components/routes
*/
export function Routes({
children,
location,
}: RoutesProps): React.ReactElement | null {
let dataRouterContext = React.useContext(DataRouterContext);
// When in a DataRouterContext _without_ children, we use the router routes
// directly. If we have children, then we're in a descendant tree and we
// need to use child routes.
let routes =
dataRouterContext && !children
? (dataRouterContext.router.routes as DataRouteObject[])
: createRoutesFromChildren(children);
return useRoutes(routes, location);
}
export interface AwaitResolveRenderFunction {
(data: Awaited<any>): React.ReactElement;
}
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();
if (typeof children === "function") {
return children(data);
}
return <>{children}</>;
}
///////////////////////////////////////////////////////////////////////////////
// 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/docs/en/v6/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;
}
if (element.type === React.Fragment) {
// Transparently support React.Fragment and its children.
routes.push.apply(
routes,
createRoutesFromChildren(element.props.children, parentPath)
);
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 treePath = [...parentPath, index];
let route: RouteObject = {
id: element.props.id || treePath.join("-"),
caseSensitive: element.props.caseSensitive,
element: element.props.element,
index: element.props.index,
path: element.props.path,
loader: element.props.loader,
action: element.props.action,
errorElement: element.props.errorElement,
hasErrorBoundary: element.props.errorElement != null,
shouldRevalidate: element.props.shouldRevalidate,
handle: element.props.handle,
};
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);
}
/**
* @private
* Walk the route tree and add hasErrorBoundary if it's not provided, so that
* users providing manual route arrays can just specify errorElement
*/
export function enhanceManualRouteObjects(
routes: RouteObject[]
): RouteObject[] {
return routes.map((route) => {
let routeClone = { ...route };
if (routeClone.hasErrorBoundary == null) {
routeClone.hasErrorBoundary = routeClone.errorElement != null;
}
if (routeClone.children) {
routeClone.children = enhanceManualRouteObjects(routeClone.children);
}
return routeClone;
});
}