-
Notifications
You must be signed in to change notification settings - Fork 2.6k
/
Copy pathcomponents.tsx
1575 lines (1398 loc) · 45.4 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
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
// TODO: We eventually might not want to import anything directly from `history`
// and leverage `react-router` here instead
import type { Action, Location } from "history";
import type {
FocusEventHandler,
FormHTMLAttributes,
MouseEventHandler,
TouchEventHandler,
} from "react";
import * as React from "react";
import type { Navigator, Params } from "react-router";
import {
Router,
Link as RouterLink,
NavLink as RouterNavLink,
useLocation,
useRoutes,
useNavigate,
useHref,
useResolvedPath,
} from "react-router-dom";
import type { LinkProps, NavLinkProps } from "react-router-dom";
import { createPath } from "history";
import type { SerializeFrom } from "@remix-run/server-runtime";
import type { AppData, FormEncType, FormMethod } from "./data";
import type { EntryContext, AssetsManifest } from "./entry";
import type { AppState, SerializedError } from "./errors";
import {
RemixRootDefaultErrorBoundary,
RemixErrorBoundary,
RemixRootDefaultCatchBoundary,
RemixCatchBoundary,
} from "./errorBoundaries";
import invariant from "./invariant";
import {
getDataLinkHrefs,
getLinksForMatches,
getModuleLinkHrefs,
getNewMatchesForLinks,
getStylesheetPrefetchLinks,
isPageLinkDescriptor,
} from "./links";
import type { HtmlLinkDescriptor, PrefetchPageDescriptor } from "./links";
import { createHtml } from "./markup";
import type { ClientRoute } from "./routes";
import { createClientRoutes } from "./routes";
import type { RouteData } from "./routeData";
import type { RouteMatch as BaseRouteMatch } from "./routeMatching";
import { matchClientRoutes } from "./routeMatching";
import type { RouteModules, HtmlMetaDescriptor } from "./routeModules";
import { createTransitionManager } from "./transition";
import type {
Transition,
TransitionManagerState,
Fetcher,
Submission,
} from "./transition";
////////////////////////////////////////////////////////////////////////////////
// RemixEntry
interface RemixEntryContextType {
manifest: AssetsManifest;
matches: BaseRouteMatch<ClientRoute>[];
routeData: RouteData;
actionData?: RouteData;
pendingLocation?: Location;
appState: AppState;
routeModules: RouteModules;
serverHandoffString?: string;
clientRoutes: ClientRoute[];
transitionManager: ReturnType<typeof createTransitionManager>;
}
export const RemixEntryContext = React.createContext<
RemixEntryContextType | undefined
>(undefined);
function useRemixEntryContext(): RemixEntryContextType {
let context = React.useContext(RemixEntryContext);
invariant(context, "You must render this element inside a <Remix> element");
return context;
}
export function RemixEntry({
context: entryContext,
action,
location: historyLocation,
navigator: _navigator,
static: staticProp = false,
}: {
context: EntryContext;
action: Action;
location: Location;
navigator: Navigator;
static?: boolean;
}) {
let {
manifest,
routeData: documentLoaderData,
actionData: documentActionData,
routeModules,
serverHandoffString,
appState: entryComponentDidCatchEmulator,
} = entryContext;
let clientRoutes = React.useMemo(
() => createClientRoutes(manifest.routes, routeModules, RemixRoute),
[manifest, routeModules]
);
let [clientState, setClientState] = React.useState(
entryComponentDidCatchEmulator
);
let [transitionManager] = React.useState(() => {
return createTransitionManager({
routes: clientRoutes,
actionData: documentActionData,
loaderData: documentLoaderData,
location: historyLocation,
catch: entryComponentDidCatchEmulator.catch,
catchBoundaryId: entryComponentDidCatchEmulator.catchBoundaryRouteId,
onRedirect: _navigator.replace,
});
});
React.useEffect(() => {
let subscriber = (state: TransitionManagerState) => {
setClientState({
catch: state.catch,
error: state.error,
catchBoundaryRouteId: state.catchBoundaryId,
loaderBoundaryRouteId: state.errorBoundaryId,
renderBoundaryRouteId: null,
trackBoundaries: false,
trackCatchBoundaries: false,
});
};
return transitionManager.subscribe(subscriber);
}, [transitionManager]);
// Ensures pushes interrupting pending navigations use replace
// TODO: Move this to React Router
let navigator: Navigator = React.useMemo(() => {
let push: Navigator["push"] = (to, state) => {
return transitionManager.getState().transition.state !== "idle"
? _navigator.replace(to, state)
: _navigator.push(to, state);
};
return { ..._navigator, push };
}, [_navigator, transitionManager]);
let { location, matches, loaderData, actionData } =
transitionManager.getState();
// Send new location to the transition manager
React.useEffect(() => {
let { location } = transitionManager.getState();
if (historyLocation === location) return;
transitionManager.send({
type: "navigation",
location: historyLocation,
submission: consumeNextNavigationSubmission(),
action,
});
}, [transitionManager, historyLocation, action]);
// If we tried to render and failed, and the app threw before rendering any
// routes, get the error and pass it to the ErrorBoundary to emulate
// `componentDidCatch`
let ssrErrorBeforeRoutesRendered =
clientState.error &&
clientState.renderBoundaryRouteId === null &&
clientState.loaderBoundaryRouteId === null
? deserializeError(clientState.error)
: undefined;
let ssrCatchBeforeRoutesRendered =
clientState.catch && clientState.catchBoundaryRouteId === null
? clientState.catch
: undefined;
return (
<RemixEntryContext.Provider
value={{
matches,
manifest,
appState: clientState,
routeModules,
serverHandoffString,
clientRoutes,
routeData: loaderData,
actionData,
transitionManager,
}}
>
<RemixErrorBoundary
location={location}
component={RemixRootDefaultErrorBoundary}
error={ssrErrorBeforeRoutesRendered}
>
<RemixCatchBoundary
location={location}
component={RemixRootDefaultCatchBoundary}
catch={ssrCatchBeforeRoutesRendered}
>
<Router
navigationType={action}
location={location}
navigator={navigator}
static={staticProp}
>
<Routes />
</Router>
</RemixCatchBoundary>
</RemixErrorBoundary>
</RemixEntryContext.Provider>
);
}
function deserializeError(data: SerializedError): Error {
let error = new Error(data.message);
error.stack = data.stack;
return error;
}
function Routes() {
// TODO: Add `renderMatches` function to RR that we can use and then we don't
// need this component, we can just `renderMatches` from RemixEntry
let { clientRoutes } = useRemixEntryContext();
// fallback to the root if we don't have a match
let element = useRoutes(clientRoutes) || (clientRoutes[0].element as any);
return element;
}
////////////////////////////////////////////////////////////////////////////////
// RemixRoute
interface RemixRouteContextType {
data: AppData;
id: string;
}
const RemixRouteContext = React.createContext<
RemixRouteContextType | undefined
>(undefined);
function useRemixRouteContext(): RemixRouteContextType {
let context = React.useContext(RemixRouteContext);
invariant(context, "You must render this element in a remix route element");
return context;
}
function DefaultRouteComponent({ id }: { id: string }): React.ReactElement {
throw new Error(
`Route "${id}" has no component! Please go add a \`default\` export in the route module file.\n` +
"If you were trying to navigate or submit to a resource route, use `<a>` instead of `<Link>` or `<Form reloadDocument>`."
);
}
export function RemixRoute({ id }: { id: string }) {
let location = useLocation();
let { routeData, routeModules, appState } = useRemixEntryContext();
// This checks prevent cryptic error messages such as: 'Cannot read properties of undefined (reading 'root')'
invariant(
routeData,
"Cannot initialize 'routeData'. This normally occurs when you have server code in your client modules.\n" +
"Check this link for more details:\nhttps://remix.run/pages/gotchas#server-code-in-client-bundles"
);
invariant(
routeModules,
"Cannot initialize 'routeModules'. This normally occurs when you have server code in your client modules.\n" +
"Check this link for more details:\nhttps://remix.run/pages/gotchas#server-code-in-client-bundles"
);
let data = routeData[id];
let { default: Component, CatchBoundary, ErrorBoundary } = routeModules[id];
let element = Component ? <Component /> : <DefaultRouteComponent id={id} />;
let context: RemixRouteContextType = { data, id };
if (CatchBoundary) {
// If we tried to render and failed, and this route threw the error, find it
// and pass it to the ErrorBoundary to emulate `componentDidCatch`
let maybeServerCaught =
appState.catch && appState.catchBoundaryRouteId === id
? appState.catch
: undefined;
// This needs to run after we check for the error from a previous render,
// otherwise we will incorrectly render this boundary for a loader error
// deeper in the tree.
if (appState.trackCatchBoundaries) {
appState.catchBoundaryRouteId = id;
}
context = maybeServerCaught
? {
id,
get data() {
console.error("You cannot `useLoaderData` in a catch boundary.");
return undefined;
},
}
: { id, data };
element = (
<RemixCatchBoundary
location={location}
component={CatchBoundary}
catch={maybeServerCaught}
>
{element}
</RemixCatchBoundary>
);
}
// Only wrap in error boundary if the route defined one, otherwise let the
// error bubble to the parent boundary. We could default to using error
// boundaries around every route, but now if the app doesn't want users
// seeing the default Remix ErrorBoundary component, they *must* define an
// error boundary for *every* route and that would be annoying. Might as
// well make it required at that point.
//
// By conditionally wrapping like this, we allow apps to define a top level
// ErrorBoundary component and be done with it. Then, if they want to, they
// can add more specific boundaries by exporting ErrorBoundary components
// for whichever routes they please.
//
// NOTE: this kind of logic will move into React Router
if (ErrorBoundary) {
// If we tried to render and failed, and this route threw the error, find it
// and pass it to the ErrorBoundary to emulate `componentDidCatch`
let maybeServerRenderError =
appState.error &&
(appState.renderBoundaryRouteId === id ||
appState.loaderBoundaryRouteId === id)
? deserializeError(appState.error)
: undefined;
// This needs to run after we check for the error from a previous render,
// otherwise we will incorrectly render this boundary for a loader error
// deeper in the tree.
if (appState.trackBoundaries) {
appState.renderBoundaryRouteId = id;
}
context = maybeServerRenderError
? {
id,
get data() {
console.error("You cannot `useLoaderData` in an error boundary.");
return undefined;
},
}
: { id, data };
element = (
<RemixErrorBoundary
location={location}
component={ErrorBoundary}
error={maybeServerRenderError}
>
{element}
</RemixErrorBoundary>
);
}
// It's important for the route context to be above the error boundary so that
// a call to `useLoaderData` doesn't accidentally get the parents route's data.
return (
<RemixRouteContext.Provider value={context}>
{element}
</RemixRouteContext.Provider>
);
}
////////////////////////////////////////////////////////////////////////////////
// Public API
/**
* Defines the prefetching behavior of the link:
*
* - "intent": Fetched when the user focuses or hovers the link
* - "render": Fetched when the link is rendered
* - "none": Never fetched
*/
type PrefetchBehavior = "intent" | "render" | "none";
export interface RemixLinkProps extends LinkProps {
prefetch?: PrefetchBehavior;
}
export interface RemixNavLinkProps extends NavLinkProps {
prefetch?: PrefetchBehavior;
}
interface PrefetchHandlers {
onFocus?: FocusEventHandler<Element>;
onBlur?: FocusEventHandler<Element>;
onMouseEnter?: MouseEventHandler<Element>;
onMouseLeave?: MouseEventHandler<Element>;
onTouchStart?: TouchEventHandler<Element>;
}
function usePrefetchBehavior(
prefetch: PrefetchBehavior,
theirElementProps: PrefetchHandlers
): [boolean, Required<PrefetchHandlers>] {
let [maybePrefetch, setMaybePrefetch] = React.useState(false);
let [shouldPrefetch, setShouldPrefetch] = React.useState(false);
let { onFocus, onBlur, onMouseEnter, onMouseLeave, onTouchStart } =
theirElementProps;
React.useEffect(() => {
if (prefetch === "render") {
setShouldPrefetch(true);
}
}, [prefetch]);
let setIntent = () => {
if (prefetch === "intent") {
setMaybePrefetch(true);
}
};
let cancelIntent = () => {
if (prefetch === "intent") {
setMaybePrefetch(false);
setShouldPrefetch(false);
}
};
React.useEffect(() => {
if (maybePrefetch) {
let id = setTimeout(() => {
setShouldPrefetch(true);
}, 100);
return () => {
clearTimeout(id);
};
}
}, [maybePrefetch]);
return [
shouldPrefetch,
{
onFocus: composeEventHandlers(onFocus, setIntent),
onBlur: composeEventHandlers(onBlur, cancelIntent),
onMouseEnter: composeEventHandlers(onMouseEnter, setIntent),
onMouseLeave: composeEventHandlers(onMouseLeave, cancelIntent),
onTouchStart: composeEventHandlers(onTouchStart, setIntent),
},
];
}
/**
* A special kind of `<Link>` that knows whether or not it is "active".
*
* @see https://remix.run/api/remix#navlink
*/
let NavLink = React.forwardRef<HTMLAnchorElement, RemixNavLinkProps>(
({ to, prefetch = "none", ...props }, forwardedRef) => {
let href = useHref(to);
let [shouldPrefetch, prefetchHandlers] = usePrefetchBehavior(
prefetch,
props
);
return (
<>
<RouterNavLink
ref={forwardedRef}
to={to}
{...props}
{...prefetchHandlers}
/>
{shouldPrefetch ? <PrefetchPageLinks page={href} /> : null}
</>
);
}
);
NavLink.displayName = "NavLink";
export { NavLink };
/**
* This component renders an anchor tag and is the primary way the user will
* navigate around your website.
*
* @see https://remix.run/api/remix#link
*/
let Link = React.forwardRef<HTMLAnchorElement, RemixLinkProps>(
({ to, prefetch = "none", ...props }, forwardedRef) => {
let href = useHref(to);
let [shouldPrefetch, prefetchHandlers] = usePrefetchBehavior(
prefetch,
props
);
return (
<>
<RouterLink
ref={forwardedRef}
to={to}
{...props}
{...prefetchHandlers}
/>
{shouldPrefetch ? <PrefetchPageLinks page={href} /> : null}
</>
);
}
);
Link.displayName = "Link";
export { Link };
export function composeEventHandlers<
EventType extends React.SyntheticEvent | Event
>(
theirHandler: ((event: EventType) => any) | undefined,
ourHandler: (event: EventType) => any
): (event: EventType) => any {
return (event) => {
theirHandler && theirHandler(event);
if (!event.defaultPrevented) {
ourHandler(event);
}
};
}
/**
* Renders the `<link>` tags for the current routes.
*
* @see https://remix.run/api/remix#meta-links-scripts
*/
export function Links() {
let { matches, routeModules, manifest } = useRemixEntryContext();
let links = React.useMemo(
() => getLinksForMatches(matches, routeModules, manifest),
[matches, routeModules, manifest]
);
return (
<>
{links.map((link) => {
if (isPageLinkDescriptor(link)) {
return <PrefetchPageLinks key={link.page} {...link} />;
}
let imageSrcSet: string | null = null;
// In React 17, <link imageSrcSet> and <link imageSizes> will warn
// because the DOM attributes aren't recognized, so users need to pass
// them in all lowercase to forward the attributes to the node without a
// warning. Normalize so that either property can be used in Remix.
if ("useId" in React) {
if (link.imagesrcset) {
link.imageSrcSet = imageSrcSet = link.imagesrcset;
delete link.imagesrcset;
}
if (link.imagesizes) {
link.imageSizes = link.imagesizes;
delete link.imagesizes;
}
} else {
if (link.imageSrcSet) {
link.imagesrcset = imageSrcSet = link.imageSrcSet;
delete link.imageSrcSet;
}
if (link.imageSizes) {
link.imagesizes = link.imageSizes;
delete link.imageSizes;
}
}
return (
<link
key={link.rel + (link.href || "") + (imageSrcSet || "")}
{...link}
/>
);
})}
</>
);
}
/**
* This component renders all of the `<link rel="prefetch">` and
* `<link rel="modulepreload"/>` tags for all the assets (data, modules, css) of
* a given page.
*
* @param props
* @param props.page
* @see https://remix.run/api/remix#prefetchpagelinks-
*/
export function PrefetchPageLinks({
page,
...dataLinkProps
}: PrefetchPageDescriptor) {
let { clientRoutes } = useRemixEntryContext();
let matches = React.useMemo(
() => matchClientRoutes(clientRoutes, page),
[clientRoutes, page]
);
if (!matches) {
console.warn(`Tried to prefetch ${page} but no routes matched.`);
return null;
}
return (
<PrefetchPageLinksImpl page={page} matches={matches} {...dataLinkProps} />
);
}
function usePrefetchedStylesheets(matches: BaseRouteMatch<ClientRoute>[]) {
let { routeModules } = useRemixEntryContext();
let [styleLinks, setStyleLinks] = React.useState<HtmlLinkDescriptor[]>([]);
React.useEffect(() => {
let interrupted: boolean = false;
getStylesheetPrefetchLinks(matches, routeModules).then((links) => {
if (!interrupted) setStyleLinks(links);
});
return () => {
interrupted = true;
};
}, [matches, routeModules]);
return styleLinks;
}
function PrefetchPageLinksImpl({
page,
matches: nextMatches,
...linkProps
}: PrefetchPageDescriptor & {
matches: BaseRouteMatch<ClientRoute>[];
}) {
let location = useLocation();
let { matches, manifest } = useRemixEntryContext();
let newMatchesForData = React.useMemo(
() => getNewMatchesForLinks(page, nextMatches, matches, location, "data"),
[page, nextMatches, matches, location]
);
let newMatchesForAssets = React.useMemo(
() => getNewMatchesForLinks(page, nextMatches, matches, location, "assets"),
[page, nextMatches, matches, location]
);
let dataHrefs = React.useMemo(
() => getDataLinkHrefs(page, newMatchesForData, manifest),
[newMatchesForData, page, manifest]
);
let moduleHrefs = React.useMemo(
() => getModuleLinkHrefs(newMatchesForAssets, manifest),
[newMatchesForAssets, manifest]
);
// needs to be a hook with async behavior because we need the modules, not
// just the manifest like the other links in here.
let styleLinks = usePrefetchedStylesheets(newMatchesForAssets);
return (
<>
{dataHrefs.map((href) => (
<link key={href} rel="prefetch" as="fetch" href={href} {...linkProps} />
))}
{moduleHrefs.map((href) => (
<link key={href} rel="modulepreload" href={href} {...linkProps} />
))}
{styleLinks.map((link) => (
// these don't spread `linkProps` because they are full link descriptors
// already with their own props
<link key={link.href} {...link} />
))}
</>
);
}
/**
* Renders the `<title>` and `<meta>` tags for the current routes.
*
* @see https://remix.run/api/remix#meta-links-scripts
*/
export function Meta() {
let { matches, routeData, routeModules } = useRemixEntryContext();
let location = useLocation();
let meta: HtmlMetaDescriptor = {};
let parentsData: { [routeId: string]: AppData } = {};
for (let match of matches) {
let routeId = match.route.id;
let data = routeData[routeId];
let params = match.params;
let routeModule = routeModules[routeId];
if (routeModule.meta) {
let routeMeta =
typeof routeModule.meta === "function"
? routeModule.meta({ data, parentsData, params, location })
: routeModule.meta;
Object.assign(meta, routeMeta);
}
parentsData[routeId] = data;
}
return (
<>
{Object.entries(meta).map(([name, value]) => {
if (!value) {
return null;
}
if (["charset", "charSet"].includes(name)) {
return <meta key="charset" charSet={value as string} />;
}
if (name === "title") {
return <title key="title">{String(value)}</title>;
}
// Open Graph tags use the `property` attribute, while other meta tags
// use `name`. See https://ogp.me/
//
// Namespaced attributes:
// - https://ogp.me/#type_music
// - https://ogp.me/#type_video
// - https://ogp.me/#type_article
// - https://ogp.me/#type_book
// - https://ogp.me/#type_profile
//
// Facebook specific tags begin with `fb:` and also use the `property`
// attribute.
//
// Twitter specific tags begin with `twitter:` but they use `name`, so
// they are excluded.
let isOpenGraphTag =
/^(og|music|video|article|book|profile|fb):.+$/.test(name);
return [value].flat().map((content) => {
if (isOpenGraphTag) {
return (
<meta
property={name}
content={content as string}
key={name + content}
/>
);
}
if (typeof content === "string") {
return <meta name={name} content={content} key={name + content} />;
}
return <meta key={name + JSON.stringify(content)} {...content} />;
});
})}
</>
);
}
/**
* Tracks whether Remix has finished hydrating or not, so scripts can be skipped
* during client-side updates.
*/
let isHydrated = false;
type ScriptProps = Omit<
React.HTMLProps<HTMLScriptElement>,
| "children"
| "async"
| "defer"
| "src"
| "type"
| "noModule"
| "dangerouslySetInnerHTML"
| "suppressHydrationWarning"
>;
/**
* Renders the `<script>` tags needed for the initial render. Bundles for
* additional routes are loaded later as needed.
*
* @param props Additional properties to add to each script tag that is rendered.
* In addition to scripts, \<link rel="modulepreload"> tags receive the crossOrigin
* property if provided.
*
* @see https://remix.run/api/remix#meta-links-scripts
*/
export function Scripts(props: ScriptProps) {
let {
manifest,
matches,
pendingLocation,
clientRoutes,
serverHandoffString,
} = useRemixEntryContext();
React.useEffect(() => {
isHydrated = true;
}, []);
let initialScripts = React.useMemo(() => {
let contextScript = serverHandoffString
? `window.__remixContext = ${serverHandoffString};`
: "";
let routeModulesScript = `${matches
.map(
(match, index) =>
`import ${JSON.stringify(manifest.url)};
import * as route${index} from ${JSON.stringify(
manifest.routes[match.route.id].module
)};`
)
.join("\n")}
window.__remixRouteModules = {${matches
.map((match, index) => `${JSON.stringify(match.route.id)}:route${index}`)
.join(",")}};
import(${JSON.stringify(manifest.entry.module)});`;
return (
<>
<script
{...props}
suppressHydrationWarning
dangerouslySetInnerHTML={createHtml(contextScript)}
type={undefined}
/>
<script
{...props}
dangerouslySetInnerHTML={createHtml(routeModulesScript)}
type="module"
async
/>
</>
);
// disabled deps array because we are purposefully only rendering this once
// for hydration, after that we want to just continue rendering the initial
// scripts as they were when the page first loaded
// eslint-disable-next-line
}, []);
// avoid waterfall when importing the next route module
let nextMatches = React.useMemo(() => {
if (pendingLocation) {
// FIXME: can probably use transitionManager `nextMatches`
let matches = matchClientRoutes(clientRoutes, pendingLocation);
invariant(matches, `No routes match path "${pendingLocation.pathname}"`);
return matches;
}
return [];
}, [pendingLocation, clientRoutes]);
let routePreloads = matches
.concat(nextMatches)
.map((match) => {
let route = manifest.routes[match.route.id];
return (route.imports || []).concat([route.module]);
})
.flat(1);
let preloads = manifest.entry.imports.concat(routePreloads);
return (
<>
<link
rel="modulepreload"
href={manifest.url}
crossOrigin={props.crossOrigin}
/>
<link
rel="modulepreload"
href={manifest.entry.module}
crossOrigin={props.crossOrigin}
/>
{dedupe(preloads).map((path) => (
<link
key={path}
rel="modulepreload"
href={path}
crossOrigin={props.crossOrigin}
/>
))}
{isHydrated ? null : initialScripts}
</>
);
}
function dedupe(array: any[]) {
return [...new Set(array)];
}
export interface FormProps extends FormHTMLAttributes<HTMLFormElement> {
/**
* The HTTP verb to use when the form is submit. Supports "get", "post",
* "put", "delete", "patch".
*
* Note: If JavaScript is disabled, you'll need to implement your own "method
* override" to support more than just GET and POST.
*/
method?: FormMethod;
/**
* Normal `<form action>` but supports React Router's relative paths.
*/
action?: string;
/**
* Normal `<form encType>`.
*
* Note: Remix defaults to `application/x-www-form-urlencoded` and also
* supports `multipart/form-data`.
*/
encType?: FormEncType;
/**
* Forces a full document navigation instead of a fetch.
*/
reloadDocument?: boolean;
/**
* Replaces the current entry in the browser history stack when the form
* navigates. Use this if you don't want the user to be able to click "back"
* to the page with the form on it.
*/
replace?: boolean;
/**
* A function to call when the form is submitted. If you call
* `event.preventDefault()` then this form will not do anything.
*/
onSubmit?: React.FormEventHandler<HTMLFormElement>;
}
/**
* A Remix-aware `<form>`. It behaves like a normal form except that the
* interaction with the server is with `fetch` instead of new document
* requests, allowing components to add nicer UX to the page as the form is
* submitted and returns with data.
*
* @see https://remix.run/api/remix#form
*/
let Form = React.forwardRef<HTMLFormElement, FormProps>((props, ref) => {
return <FormImpl {...props} ref={ref} />;
});
Form.displayName = "Form";
export { Form };
interface FormImplProps extends FormProps {
fetchKey?: string;
}
let FormImpl = React.forwardRef<HTMLFormElement, FormImplProps>(
(
{
reloadDocument = false,
replace = false,
method = "get",
action,
encType = "application/x-www-form-urlencoded",
fetchKey,
onSubmit,
...props
},
forwardedRef
) => {
let submit = useSubmitImpl(fetchKey);
let formMethod: FormMethod =
method.toLowerCase() === "get" ? "get" : "post";
let formAction = useFormAction(action);
return (
<form
ref={forwardedRef}
method={formMethod}
action={formAction}
encType={encType}
onSubmit={
reloadDocument
? undefined
: (event) => {
onSubmit && onSubmit(event);
if (event.defaultPrevented) return;