-
-
Notifications
You must be signed in to change notification settings - Fork 10.3k
/
index.tsx
1270 lines (1140 loc) · 34.3 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 type {
NavigateOptions,
RelativeRoutingType,
RouteObject,
To,
} from "react-router";
import {
Router,
createPath,
useHref,
useLocation,
useMatches,
useNavigate,
useNavigation,
useResolvedPath,
unstable_useBlocker as useBlocker,
UNSAFE_DataRouterContext as DataRouterContext,
UNSAFE_DataRouterStateContext as DataRouterStateContext,
UNSAFE_NavigationContext as NavigationContext,
UNSAFE_RouteContext as RouteContext,
UNSAFE_enhanceManualRouteObjects as enhanceManualRouteObjects,
} from "react-router";
import type {
BrowserHistory,
Fetcher,
FormEncType,
FormMethod,
GetScrollRestorationKeyFunction,
HashHistory,
History,
HydrationState,
Router as RemixRouter,
} from "@remix-run/router";
import {
createRouter,
createBrowserHistory,
createHashHistory,
invariant,
joinPaths,
ErrorResponse,
} from "@remix-run/router";
import type {
SubmitOptions,
ParamKeyValuePair,
URLSearchParamsInit,
} from "./dom";
import {
createSearchParams,
defaultMethod,
getFormSubmissionInfo,
getSearchParamsForLocation,
shouldProcessLinkClick,
} from "./dom";
////////////////////////////////////////////////////////////////////////////////
//#region Re-exports
////////////////////////////////////////////////////////////////////////////////
export type {
FormEncType,
FormMethod,
GetScrollRestorationKeyFunction,
ParamKeyValuePair,
SubmitOptions,
URLSearchParamsInit,
};
export { createSearchParams };
// Note: Keep in sync with react-router exports!
export type {
ActionFunction,
ActionFunctionArgs,
AwaitProps,
unstable_Blocker,
unstable_BlockerFunction,
DataRouteMatch,
DataRouteObject,
Fetcher,
Hash,
IndexRouteObject,
IndexRouteProps,
JsonFunction,
LayoutRouteProps,
LoaderFunction,
LoaderFunctionArgs,
Location,
MemoryRouterProps,
NavigateFunction,
NavigateOptions,
NavigateProps,
Navigation,
Navigator,
NonIndexRouteObject,
OutletProps,
Params,
ParamParseKey,
Path,
PathMatch,
Pathname,
PathPattern,
PathRouteProps,
RedirectFunction,
RelativeRoutingType,
RouteMatch,
RouteObject,
RouteProps,
RouterProps,
RouterProviderProps,
RoutesProps,
Search,
ShouldRevalidateFunction,
To,
} from "react-router";
export {
AbortedDeferredError,
Await,
MemoryRouter,
Navigate,
NavigationType,
Outlet,
Route,
Router,
RouterProvider,
Routes,
createMemoryRouter,
createPath,
createRoutesFromChildren,
createRoutesFromElements,
defer,
isRouteErrorResponse,
generatePath,
json,
matchPath,
matchRoutes,
parsePath,
redirect,
renderMatches,
resolvePath,
useActionData,
useAsyncError,
useAsyncValue,
unstable_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_enhanceManualRouteObjects,
} from "react-router";
//#endregion
declare global {
var __staticRouterHydrationData: HydrationState | undefined;
}
////////////////////////////////////////////////////////////////////////////////
//#region Routers
////////////////////////////////////////////////////////////////////////////////
export function createBrowserRouter(
routes: RouteObject[],
opts?: {
basename?: string;
hydrationData?: HydrationState;
window?: Window;
}
): RemixRouter {
return createRouter({
basename: opts?.basename,
history: createBrowserHistory({ window: opts?.window }),
hydrationData: opts?.hydrationData || parseHydrationData(),
routes: enhanceManualRouteObjects(routes),
}).initialize();
}
export function createHashRouter(
routes: RouteObject[],
opts?: {
basename?: string;
hydrationData?: HydrationState;
window?: Window;
}
): RemixRouter {
return createRouter({
basename: opts?.basename,
history: createHashHistory({ window: opts?.window }),
hydrationData: opts?.hydrationData || parseHydrationData(),
routes: enhanceManualRouteObjects(routes),
}).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 ErrorResponse(
val.status,
val.statusText,
val.data,
val.internal === true
);
} else if (val && val.__type === "Error") {
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 Components
////////////////////////////////////////////////////////////////////////////////
export interface BrowserRouterProps {
basename?: string;
children?: React.ReactNode;
window?: Window;
}
/**
* A `<Router>` for use in web browsers. Provides the cleanest URLs.
*/
export function BrowserRouter({
basename,
children,
window,
}: BrowserRouterProps) {
let historyRef = React.useRef<BrowserHistory>();
if (historyRef.current == null) {
historyRef.current = createBrowserHistory({ window, 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 HashRouterProps {
basename?: string;
children?: React.ReactNode;
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, window }: HashRouterProps) {
let historyRef = React.useRef<HashHistory>();
if (historyRef.current == null) {
historyRef.current = createHashHistory({ window, 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 HistoryRouterProps {
basename?: string;
children?: React.ReactNode;
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, history }: HistoryRouterProps) {
const [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}
/>
);
}
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;
}
/**
* 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,
...rest
},
ref
) {
let href = useHref(to, { relative });
let internalOnClick = useLinkClickHandler(to, {
replace,
state,
target,
preventScrollReset,
relative,
});
function handleClick(
event: React.MouseEvent<HTMLAnchorElement, MouseEvent>
) {
if (onClick) onClick(event);
if (!event.defaultPrevented) {
internalOnClick(event);
}
}
return (
// eslint-disable-next-line jsx-a11y/anchor-has-content
<a
{...rest}
href={href}
onClick={reloadDocument ? onClick : handleClick}
ref={ref}
target={target}
/>
);
}
);
if (__DEV__) {
Link.displayName = "Link";
}
export interface NavLinkProps
extends Omit<LinkProps, "className" | "style" | "children"> {
children?:
| React.ReactNode
| ((props: { isActive: boolean; isPending: boolean }) => React.ReactNode);
caseSensitive?: boolean;
className?:
| string
| ((props: {
isActive: boolean;
isPending: boolean;
}) => string | undefined);
end?: boolean;
style?:
| React.CSSProperties
| ((props: {
isActive: boolean;
isPending: boolean;
}) => React.CSSProperties | undefined);
}
/**
* A <Link> wrapper that knows if it's "active" or not.
*/
export const NavLink = React.forwardRef<HTMLAnchorElement, NavLinkProps>(
function NavLinkWithRef(
{
"aria-current": ariaCurrentProp = "page",
caseSensitive = false,
className: classNameProp = "",
end = false,
style: styleProp,
to,
children,
...rest
},
ref
) {
let path = useResolvedPath(to, { relative: rest.relative });
let location = useLocation();
let routerState = React.useContext(DataRouterStateContext);
let { navigator } = React.useContext(NavigationContext);
let toPathname = navigator.encodeLocation
? navigator.encodeLocation(path).pathname
: path.pathname;
let locationPathname = location.pathname;
let nextLocationPathname =
routerState && routerState.navigation && routerState.navigation.location
? routerState.navigation.location.pathname
: null;
if (!caseSensitive) {
locationPathname = locationPathname.toLowerCase();
nextLocationPathname = nextLocationPathname
? nextLocationPathname.toLowerCase()
: null;
toPathname = toPathname.toLowerCase();
}
let isActive =
locationPathname === toPathname ||
(!end &&
locationPathname.startsWith(toPathname) &&
locationPathname.charAt(toPathname.length) === "/");
let isPending =
nextLocationPathname != null &&
(nextLocationPathname === toPathname ||
(!end &&
nextLocationPathname.startsWith(toPathname) &&
nextLocationPathname.charAt(toPathname.length) === "/"));
let ariaCurrent = isActive ? ariaCurrentProp : undefined;
let className: string | undefined;
if (typeof classNameProp === "function") {
className = classNameProp({ isActive, isPending });
} else {
// If the className prop is not a function, we use a default `active`
// class for <NavLink />s that are active. In v5 `active` was the default
// value for `activeClassName`, but we are removing that API and can still
// use the old default behavior for a cleaner upgrade path and keep the
// simple styling rules working as they currently do.
className = [
classNameProp,
isActive ? "active" : null,
isPending ? "pending" : null,
]
.filter(Boolean)
.join(" ");
}
let style =
typeof styleProp === "function"
? styleProp({ isActive, isPending })
: styleProp;
return (
<Link
{...rest}
aria-current={ariaCurrent}
className={className}
ref={ref}
style={style}
to={to}
>
{typeof children === "function"
? children({ isActive, isPending })
: children}
</Link>
);
}
);
if (__DEV__) {
NavLink.displayName = "NavLink";
}
export interface FormProps extends React.FormHTMLAttributes<HTMLFormElement> {
/**
* The HTTP verb to use when the form is submit. Supports "get", "post",
* "put", "delete", "patch".
*/
method?: FormMethod;
/**
* Normal `<form action>` but supports React Router's relative paths.
*/
action?: string;
/**
* 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;
/**
* Determines whether the form action is relative to the route hierarchy or
* the pathname. Use this if you want to opt out of navigating the route
* hierarchy and want to instead route based on /-delimited URL segments
*/
relative?: RelativeRoutingType;
/**
* Prevent the scroll position from resetting to the top of the viewport on
* completion of the navigation when using the <ScrollRestoration> component
*/
preventScrollReset?: 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-run/router`-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.
*/
export const Form = React.forwardRef<HTMLFormElement, FormProps>(
(props, ref) => {
return <FormImpl {...props} ref={ref} />;
}
);
if (__DEV__) {
Form.displayName = "Form";
}
type HTMLSubmitEvent = React.BaseSyntheticEvent<
SubmitEvent,
Event,
HTMLFormElement
>;
type HTMLFormSubmitter = HTMLButtonElement | HTMLInputElement;
interface FormImplProps extends FormProps {
fetcherKey?: string;
routeId?: string;
}
const FormImpl = React.forwardRef<HTMLFormElement, FormImplProps>(
(
{
reloadDocument,
replace,
method = defaultMethod,
action,
onSubmit,
fetcherKey,
routeId,
relative,
preventScrollReset,
...props
},
forwardedRef
) => {
let submit = useSubmitImpl(fetcherKey, routeId);
let formMethod: FormMethod =
method.toLowerCase() === "get" ? "get" : "post";
let formAction = useFormAction(action, { relative });
let submitHandler: React.FormEventHandler<HTMLFormElement> = (event) => {
onSubmit && onSubmit(event);
if (event.defaultPrevented) return;
event.preventDefault();
let submitter = (event as unknown as HTMLSubmitEvent).nativeEvent
.submitter as HTMLFormSubmitter | null;
let submitMethod =
(submitter?.getAttribute("formmethod") as FormMethod | undefined) ||
method;
submit(submitter || event.currentTarget, {
method: submitMethod,
replace,
relative,
preventScrollReset,
});
};
return (
<form
ref={forwardedRef}
method={formMethod}
action={formAction}
onSubmit={reloadDocument ? onSubmit : submitHandler}
{...props}
/>
);
}
);
if (__DEV__) {
FormImpl.displayName = "FormImpl";
}
export interface ScrollRestorationProps {
getKey?: GetScrollRestorationKeyFunction;
storageKey?: string;
}
/**
* This component will emulate the browser's scroll restoration on location
* changes.
*/
export function ScrollRestoration({
getKey,
storageKey,
}: ScrollRestorationProps) {
useScrollRestoration({ getKey, storageKey });
return null;
}
if (__DEV__) {
ScrollRestoration.displayName = "ScrollRestoration";
}
//#endregion
////////////////////////////////////////////////////////////////////////////////
//#region Hooks
////////////////////////////////////////////////////////////////////////////////
enum DataRouterHook {
UseScrollRestoration = "useScrollRestoration",
UseSubmitImpl = "useSubmitImpl",
UseFetcher = "useFetcher",
}
enum DataRouterStateHook {
UseFetchers = "useFetchers",
UseScrollRestoration = "useScrollRestoration",
}
function getDataRouterConsoleError(
hookName: DataRouterHook | DataRouterStateHook
) {
return `${hookName} must be used within a data router. See https://reactrouter.com/routers/picking-a-router.`;
}
function useDataRouterContext(hookName: DataRouterHook) {
let ctx = React.useContext(DataRouterContext);
invariant(ctx, getDataRouterConsoleError(hookName));
return ctx;
}
function useDataRouterState(hookName: DataRouterStateHook) {
let state = React.useContext(DataRouterStateContext);
invariant(state, getDataRouterConsoleError(hookName));
return state;
}
/**
* Handles the click behavior for router `<Link>` components. This is useful if
* you need to create custom `<Link>` components with the same click behavior we
* use in our exported `<Link>`.
*/
export function useLinkClickHandler<E extends Element = HTMLAnchorElement>(
to: To,
{
target,
replace: replaceProp,
state,
preventScrollReset,
relative,
}: {
target?: React.HTMLAttributeAnchorTarget;
replace?: boolean;
state?: any;
preventScrollReset?: boolean;
relative?: RelativeRoutingType;
} = {}
): (event: React.MouseEvent<E, MouseEvent>) => void {
let navigate = useNavigate();
let location = useLocation();
let path = useResolvedPath(to, { relative });
return React.useCallback(
(event: React.MouseEvent<E, MouseEvent>) => {
if (shouldProcessLinkClick(event, target)) {
event.preventDefault();
// If the URL hasn't changed, a regular <a> will do a replace instead of
// a push, so do the same here unless the replace prop is explicitly set
let replace =
replaceProp !== undefined
? replaceProp
: createPath(location) === createPath(path);
navigate(to, { replace, state, preventScrollReset, relative });
}
},
[
location,
navigate,
path,
replaceProp,
state,
target,
to,
preventScrollReset,
relative,
]
);
}
/**
* A convenient wrapper for reading and writing search parameters via the
* URLSearchParams interface.
*/
export function useSearchParams(
defaultInit?: URLSearchParamsInit
): [URLSearchParams, SetURLSearchParams] {
warning(
typeof URLSearchParams !== "undefined",
`You cannot use the \`useSearchParams\` hook in a browser that does not ` +
`support the URLSearchParams API. If you need to support Internet ` +
`Explorer 11, we recommend you load a polyfill such as ` +
`https://github.com/ungap/url-search-params\n\n` +
`If you're unsure how to load polyfills, we recommend you check out ` +
`https://polyfill.io/v3/ which provides some recommendations about how ` +
`to load polyfills only for users that need them, instead of for every ` +
`user.`
);
let defaultSearchParamsRef = React.useRef(createSearchParams(defaultInit));
let location = useLocation();
let searchParams = React.useMemo(
() =>
getSearchParamsForLocation(
location.search,
defaultSearchParamsRef.current
),
[location.search]
);
let navigate = useNavigate();
let setSearchParams = React.useCallback<SetURLSearchParams>(
(nextInit, navigateOptions) => {
const newSearchParams = createSearchParams(
typeof nextInit === "function" ? nextInit(searchParams) : nextInit
);
navigate("?" + newSearchParams, navigateOptions);
},
[navigate, searchParams]
);
return [searchParams, setSearchParams];
}
type SetURLSearchParams = (
nextInit?:
| URLSearchParamsInit
| ((prev: URLSearchParams) => URLSearchParamsInit),
navigateOpts?: NavigateOptions
) => void;
type SubmitTarget =
| HTMLFormElement
| HTMLButtonElement
| HTMLInputElement
| FormData
| URLSearchParams
| { [name: string]: string }
| null;
/**
* Submits a HTML `<form>` to the server without reloading the page.
*/
export interface SubmitFunction {
(
/**
* Specifies the `<form>` to be submitted to the server, a specific
* `<button>` or `<input type="submit">` to use to submit the form, or some
* arbitrary data to submit.
*
* Note: When using a `<button>` its `name` and `value` will also be
* included in the form data that is submitted.
*/
target: SubmitTarget,
/**
* Options that override the `<form>`'s own attributes. Required when
* submitting arbitrary data without a backing `<form>`.
*/
options?: SubmitOptions
): void;
}
/**
* Returns a function that may be used to programmatically submit a form (or
* some arbitrary data) to the server.
*/
export function useSubmit(): SubmitFunction {
return useSubmitImpl();
}
function useSubmitImpl(fetcherKey?: string, routeId?: string): SubmitFunction {
let { router } = useDataRouterContext(DataRouterHook.UseSubmitImpl);
let defaultAction = useFormAction();
return React.useCallback(
(target, options = {}) => {
if (typeof document === "undefined") {
throw new Error(
"You are calling submit during the server render. " +
"Try calling submit within a `useEffect` or callback instead."
);
}
let { method, encType, formData, url } = getFormSubmissionInfo(
target,
defaultAction,
options
);
let href = url.pathname + url.search;
let opts = {
replace: options.replace,
preventScrollReset: options.preventScrollReset,
formData,
formMethod: method as FormMethod,
formEncType: encType as FormEncType,
};
if (fetcherKey) {
invariant(routeId != null, "No routeId available for useFetcher()");
router.fetch(fetcherKey, routeId, href, opts);
} else {
router.navigate(href, opts);
}
},
[defaultAction, router, fetcherKey, routeId]
);
}
export function useFormAction(
action?: string,
{ relative }: { relative?: RelativeRoutingType } = {}
): string {
let { basename } = React.useContext(NavigationContext);
let routeContext = React.useContext(RouteContext);
invariant(routeContext, "useFormAction must be used inside a RouteContext");
let [match] = routeContext.matches.slice(-1);
// Shallow clone path so we can modify it below, otherwise we modify the
// object referenced by useMemo inside useResolvedPath
let path = { ...useResolvedPath(action ? action : ".", { relative }) };
// Previously we set the default action to ".". The problem with this is that
// `useResolvedPath(".")` excludes search params and the hash of the resolved
// URL. This is the intended behavior of when "." is specifically provided as
// the form action, but inconsistent w/ browsers when the action is omitted.
// https://github.com/remix-run/remix/issues/927
let location = useLocation();
if (action == null) {
// Safe to write to these directly here since if action was undefined, we
// would have called useResolvedPath(".") which will never include a search
// or hash
path.search = location.search;
path.hash = location.hash;
// When grabbing search params from the URL, remove the automatically
// inserted ?index param so we match the useResolvedPath search behavior
// which would not include ?index
if (match.route.index) {
let params = new URLSearchParams(path.search);
params.delete("index");
path.search = params.toString() ? `?${params.toString()}` : "";
}
}
if ((!action || action === ".") && match.route.index) {
path.search = path.search
? path.search.replace(/^\?/, "?index&")
: "?index";
}
// If we're operating within a basename, prepend it to the pathname prior
// to creating the form action. If this is a root navigation, then just use
// the raw basename which allows the basename to have full control over the
// presence of a trailing slash on root actions
if (basename !== "/") {
path.pathname =
path.pathname === "/" ? basename : joinPaths([basename, path.pathname]);
}
return createPath(path);
}
function createFetcherForm(fetcherKey: string, routeId: string) {
let FetcherForm = React.forwardRef<HTMLFormElement, FormProps>(
(props, ref) => {
return (
<FormImpl
{...props}
ref={ref}
fetcherKey={fetcherKey}
routeId={routeId}
/>