bc518174
王天杨
提交两个项目文件
|
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
|
import { n as Router, o as RouteModules, p as DataStrategyFunction, q as MiddlewareEnabled, c as RouterContextProvider, r as AppLoadContext, T as To, s as NavigateOptions, B as BlockerFunction, t as Blocker, v as SerializeFrom, w as RelativeRoutingType, L as Location, x as ParamParseKey, y as Path, z as PathPattern, E as PathMatch, U as UIMatch, I as Navigation, J as Action, P as Params, K as RouteObject, G as GetLoaderData, m as GetActionData, O as InitialEntry, Q as HydrationState, V as IndexRouteObject, W as RouteComponentType, X as HydrateFallbackType, Y as ErrorBoundaryType, d as LoaderFunction, A as ActionFunction, M as MetaFunction, b as LinksFunction, Z as NonIndexRouteObject, _ as Equal, $ as RouterState, a0 as PatchRoutesOnNavigationFunction, a1 as DataRouteObject, a as ClientLoaderFunction } from './instrumentation-DvHY1sgY.js';
export { ac as ActionFunctionArgs, b1 as Await, aQ as AwaitProps, C as ClientActionFunction, bd as ClientActionFunctionArgs, be as ClientLoaderFunctionArgs, aS as ClientOnErrorFunction, aL as DataRouteMatch, ad as DataStrategyFunctionArgs, ae as DataStrategyMatch, D as DataStrategyResult, ag as ErrorResponse, a6 as Fetcher, ah as FormEncType, ai as FormMethod, bj as Future, a3 as GetScrollPositionFunction, a4 as GetScrollRestorationKeyFunction, aj as HTMLFormMethod, bf as HeadersArgs, H as HeadersFunction, bi as HtmlLinkDescriptor, aB as IDLE_BLOCKER, aA as IDLE_FETCHER, az as IDLE_NAVIGATION, aR as IndexRouteProps, aT as LayoutRouteProps, ak as LazyRouteFunction, f as LinkDescriptor, al as LoaderFunctionArgs, b2 as MemoryRouter, aU as MemoryRouterOpts, aV as MemoryRouterProps, bg as MetaArgs, h as MetaDescriptor, am as MiddlewareFunction, b3 as Navigate, aW as NavigateProps, a7 as NavigationStates, aM as Navigator, b4 as Outlet, aX as OutletProps, bh as PageLinkDescriptor, aN as PatchRoutesOnNavigationFunctionArgs, an as PathParam, aY as PathRouteProps, ao as RedirectFunction, ab as RevalidationState, b5 as Route, aO as RouteMatch, aZ as RouteProps, b6 as Router, ap as RouterContext, aa as RouterFetchOptions, e as RouterInit, a9 as RouterNavigateOptions, a_ as RouterProps, b7 as RouterProvider, a$ as RouterProviderProps, a8 as RouterSubscriber, b8 as Routes, b0 as RoutesProps, S as ShouldRevalidateFunction, aq as ShouldRevalidateFunctionArgs, a2 as StaticHandler, a5 as StaticHandlerContext, aP as UNSAFE_AwaitContextProvider, br as UNSAFE_DataRouterContext, bs as UNSAFE_DataRouterStateContext, af as UNSAFE_DataWithResponseInit, bq as UNSAFE_ErrorResponseImpl, bt as UNSAFE_FetchersContext, bu as UNSAFE_LocationContext, bv as UNSAFE_NavigationContext, bw as UNSAFE_RouteContext, bx as UNSAFE_ViewTransitionContext, bA as UNSAFE_WithComponentProps, bE as UNSAFE_WithErrorBoundaryProps, bC as UNSAFE_WithHydrateFallbackProps, bm as UNSAFE_createBrowserHistory, bn as UNSAFE_createHashHistory, bl as UNSAFE_createMemoryHistory, bp as UNSAFE_createRouter, by as UNSAFE_hydrationRouteProperties, bo as UNSAFE_invariant, bz as UNSAFE_mapRouteProperties, bB as UNSAFE_withComponentProps, bF as UNSAFE_withErrorBoundaryProps, bD as UNSAFE_withHydrateFallbackProps, ar as createContext, b9 as createMemoryRouter, as as createPath, ba as createRoutesFromChildren, bb as createRoutesFromElements, aC as data, aD as generatePath, aE as isRouteErrorResponse, aF as matchPath, aG as matchRoutes, at as parsePath, aH as redirect, aI as redirectDocument, bc as renderMatches, aJ as replace, aK as resolvePath, u as unstable_ClientInstrumentation, av as unstable_InstrumentRequestHandlerFunction, ax as unstable_InstrumentRouteFunction, aw as unstable_InstrumentRouterFunction, ay as unstable_InstrumentationHandlerResult, bk as unstable_SerializesTo, au as unstable_ServerInstrumentation } from './instrumentation-DvHY1sgY.js';
import * as React from 'react';
import React__default, { ReactElement } from 'react';
import { a as RouteModules$1, P as Pages } from './register-Bm80E9qL.js';
export { b as Register } from './register-Bm80E9qL.js';
import { A as AssetsManifest, S as ServerBuild, E as EntryContext, F as FutureConfig } from './index-react-server-client-1TI9M9o1.js';
export { l as BrowserRouter, B as BrowserRouterProps, D as DOMRouterOpts, a1 as DiscoverBehavior, c as FetcherFormProps, h as FetcherSubmitFunction, G as FetcherSubmitOptions, i as FetcherWithComponents, q as Form, d as FormProps, a2 as HandleDataRequestFunction, a3 as HandleDocumentRequestFunction, a4 as HandleErrorFunction, m as HashRouter, H as HashRouterProps, a as HistoryRouterProps, n as Link, L as LinkProps, X as Links, _ as LinksProps, W as Meta, p as NavLink, N as NavLinkProps, b as NavLinkRenderProps, P as ParamKeyValuePair, a0 as PrefetchBehavior, Z as PrefetchPageLinks, Y as Scripts, $ as ScriptsProps, r as ScrollRestoration, e as ScrollRestorationProps, a5 as ServerEntryModule, f as SetURLSearchParams, T as StaticRouter, M as StaticRouterProps, V as StaticRouterProvider, O as StaticRouterProviderProps, g as SubmitFunction, I as SubmitOptions, J as SubmitTarget, a6 as UNSAFE_FrameworkContext, a7 as UNSAFE_createClientRoutes, a8 as UNSAFE_createClientRoutesWithHMRRevalidationOptOut, a9 as UNSAFE_shouldHydrateRouteLoader, aa as UNSAFE_useScrollRestoration, U as URLSearchParamsInit, j as createBrowserRouter, k as createHashRouter, K as createSearchParams, Q as createStaticHandler, R as createStaticRouter, o as unstable_HistoryRouter, z as unstable_usePrompt, y as useBeforeUnload, w as useFetcher, x as useFetchers, v as useFormAction, u as useLinkClickHandler, s as useSearchParams, t as useSubmit, C as useViewTransitionState } from './index-react-server-client-1TI9M9o1.js';
import { ParseOptions, SerializeOptions } from 'cookie';
export { ParseOptions as CookieParseOptions, SerializeOptions as CookieSerializeOptions } from 'cookie';
import { e as RSCPayload, m as matchRSCServerRequest } from './browser-CJ9_du-U.js';
export { B as unstable_BrowserCreateFromReadableStreamFunction, D as unstable_DecodeActionFunction, a as unstable_DecodeFormStateFunction, b as unstable_DecodeReplyFunction, E as unstable_EncodeReplyFunction, L as unstable_LoadServerActionFunction, g as unstable_RSCHydratedRouterProps, d as unstable_RSCManifestPayload, h as unstable_RSCMatch, f as unstable_RSCRenderPayload, l as unstable_RSCRouteConfig, k as unstable_RSCRouteConfigEntry, i as unstable_RSCRouteManifest, j as unstable_RSCRouteMatch } from './browser-CJ9_du-U.js';
declare const SingleFetchRedirectSymbol: unique symbol;
declare function getTurboStreamSingleFetchDataStrategy(getRouter: () => Router, manifest: AssetsManifest, routeModules: RouteModules, ssr: boolean, basename: string | undefined, trailingSlashAware: boolean): DataStrategyFunction;
declare function decodeViaTurboStream(body: ReadableStream<Uint8Array>, global: Window | typeof globalThis): Promise<{
done: Promise<undefined>;
value: unknown;
}>;
/**
* The mode to use when running the server.
*/
declare enum ServerMode {
Development = "development",
Production = "production",
Test = "test"
}
type RequestHandler = (request: Request, loadContext?: MiddlewareEnabled extends true ? RouterContextProvider : AppLoadContext) => Promise<Response>;
type CreateRequestHandlerFunction = (build: ServerBuild | (() => ServerBuild | Promise<ServerBuild>), mode?: string) => RequestHandler;
declare const createRequestHandler: CreateRequestHandlerFunction;
/**
* Resolves a URL against the current {@link Location}.
*
* @example
* import { useHref } from "react-router";
*
* function SomeComponent() {
* let href = useHref("some/where");
* // "/resolved/some/where"
* }
*
* @public
* @category Hooks
* @param to The path to resolve
* @param options Options
* @param options.relative Defaults to `"route"` so routing is relative to the
* route tree.
* Set to `"path"` to make relative routing operate against path segments.
* @returns The resolved href string
*/
declare function useHref(to: To, { relative }?: {
relative?: RelativeRoutingType;
}): string;
/**
* Returns `true` if this component is a descendant of a {@link Router}, useful
* to ensure a component is used within a {@link Router}.
*
* @public
* @category Hooks
* @mode framework
* @mode data
* @returns Whether the component is within a {@link Router} context
*/
declare function useInRouterContext(): boolean;
/**
* Returns the current {@link Location}. This can be useful if you'd like to
* perform some side effect whenever it changes.
*
* @example
* import * as React from 'react'
* import { useLocation } from 'react-router'
*
* function SomeComponent() {
* let location = useLocation()
*
* React.useEffect(() => {
* // Google Analytics
* ga('send', 'pageview')
* }, [location]);
*
* return (
* // ...
* );
* }
*
* @public
* @category Hooks
* @returns The current {@link Location} object
*/
declare function useLocation(): Location;
/**
* Returns the current {@link Navigation} action which describes how the router
* came to the current {@link Location}, either by a pop, push, or replace on
* the [`History`](https://developer.mozilla.org/en-US/docs/Web/API/History) stack.
*
* @public
* @category Hooks
* @returns The current {@link NavigationType} (`"POP"`, `"PUSH"`, or `"REPLACE"`)
*/
declare function useNavigationType(): Action;
/**
* Returns a {@link PathMatch} object if the given pattern matches the current URL.
* This is useful for components that need to know "active" state, e.g.
* {@link NavLink | `<NavLink>`}.
*
* @public
* @category Hooks
* @param pattern The pattern to match against the current {@link Location}
* @returns The path match object if the pattern matches, `null` otherwise
*/
declare function useMatch<ParamKey extends ParamParseKey<Path>, Path extends string>(pattern: PathPattern<Path> | Path): PathMatch<ParamKey> | null;
/**
* The interface for the `navigate` function returned from {@link useNavigate}.
*/
interface NavigateFunction {
(to: To, options?: NavigateOptions): void | Promise<void>;
(delta: number): void | Promise<void>;
}
/**
* Returns a function that lets you navigate programmatically in the browser in
* response to user interactions or effects.
*
* It's often better to use {@link redirect} in [`action`](../../start/framework/route-module#action)/[`loader`](../../start/framework/route-module#loader)
* functions than this hook.
*
* The returned function signature is `navigate(to, options?)`/`navigate(delta)` where:
*
* * `to` can be a string path, a {@link To} object, or a number (delta)
* * `options` contains options for modifying the navigation
* * These options work in all modes (Framework, Data, and Declarative):
* * `relative`: `"route"` or `"path"` to control relative routing logic
* * `replace`: Replace the current entry in the [`History`](https://developer.mozilla.org/en-US/docs/Web/API/History) stack
* * `state`: Optional [`history.state`](https://developer.mozilla.org/en-US/docs/Web/API/History/state) to include with the new {@link Location}
* * These options only work in Framework and Data modes:
* * `flushSync`: Wrap the DOM updates in [`ReactDom.flushSync`](https://react.dev/reference/react-dom/flushSync)
* * `preventScrollReset`: Do not scroll back to the top of the page after navigation
* * `viewTransition`: Enable [`document.startViewTransition`](https://developer.mozilla.org/en-US/docs/Web/API/Document/startViewTransition) for this navigation
*
* @example
* import { useNavigate } from "react-router";
*
* function SomeComponent() {
* let navigate = useNavigate();
* return (
* <button onClick={() => navigate(-1)}>
* Go Back
* </button>
* );
* }
*
* @additionalExamples
* ### Navigate to another path
*
* ```tsx
* navigate("/some/route");
* navigate("/some/route?search=param");
* ```
*
* ### Navigate with a {@link To} object
*
* All properties are optional.
*
* ```tsx
* navigate({
* pathname: "/some/route",
* search: "?search=param",
* hash: "#hash",
* state: { some: "state" },
* });
* ```
*
* If you use `state`, that will be available on the {@link Location} object on
* the next page. Access it with `useLocation().state` (see {@link useLocation}).
*
* ### Navigate back or forward in the history stack
*
* ```tsx
* // back
* // often used to close modals
* navigate(-1);
*
* // forward
* // often used in a multistep wizard workflows
* navigate(1);
* ```
*
* Be cautious with `navigate(number)`. If your application can load up to a
* route that has a button that tries to navigate forward/back, there may not be
* a `[`History`](https://developer.mozilla.org/en-US/docs/Web/API/History)
* entry to go back or forward to, or it can go somewhere you don't expect
* (like a different domain).
*
* Only use this if you're sure they will have an entry in the [`History`](https://developer.mozilla.org/en-US/docs/Web/API/History)
* stack to navigate to.
*
* ### Replace the current entry in the history stack
*
* This will remove the current entry in the [`History`](https://developer.mozilla.org/en-US/docs/Web/API/History)
* stack, replacing it with a new one, similar to a server side redirect.
*
* ```tsx
* navigate("/some/route", { replace: true });
* ```
*
* ### Prevent Scroll Reset
*
* [MODES: framework, data]
*
* <br/>
* <br/>
*
* To prevent {@link ScrollRestoration | `<ScrollRestoration>`} from resetting
* the scroll position, use the `preventScrollReset` option.
*
* ```tsx
* navigate("?some-tab=1", { preventScrollReset: true });
* ```
*
* For example, if you have a tab interface connected to search params in the
* middle of a page, and you don't want it to scroll to the top when a tab is
* clicked.
*
* ### Return Type Augmentation
*
* Internally, `useNavigate` uses a separate implementation when you are in
* Declarative mode versus Data/Framework mode - the primary difference being
* that the latter is able to return a stable reference that does not change
* identity across navigations. The implementation in Data/Framework mode also
* returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)
* that resolves when the navigation is completed. This means the return type of
* `useNavigate` is `void | Promise<void>`. This is accurate, but can lead to
* some red squigglies based on the union in the return value:
*
* - If you're using `typescript-eslint`, you may see errors from
* [`@typescript-eslint/no-floating-promises`](https://typescript-eslint.io/rules/no-floating-promises)
* - In Framework/Data mode, `React.use(navigate())` will show a false-positive
* `Argument of type 'void | Promise<void>' is not assignable to parameter of
* type 'Usable<void>'` error
*
* The easiest way to work around these issues is to augment the type based on the
* router you're using:
*
* ```ts
* // If using <BrowserRouter>
* declare module "react-router" {
* interface NavigateFunction {
* (to: To, options?: NavigateOptions): void;
* (delta: number): void;
* }
* }
*
* // If using <RouterProvider> or Framework mode
* declare module "react-router" {
* interface NavigateFunction {
* (to: To, options?: NavigateOptions): Promise<void>;
* (delta: number): Promise<void>;
* }
* }
* ```
*
* @public
* @category Hooks
* @returns A navigate function for programmatic navigation
*/
declare function useNavigate(): NavigateFunction;
/**
* Returns the parent route {@link Outlet | `<Outlet context>`}.
*
* Often parent routes manage state or other values you want shared with child
* routes. You can create your own [context provider](https://react.dev/learn/passing-data-deeply-with-context)
* if you like, but this is such a common situation that it's built-into
* {@link Outlet | `<Outlet>`}.
*
* ```tsx
* // Parent route
* function Parent() {
* const [count, setCount] = React.useState(0);
* return <Outlet context={[count, setCount]} />;
* }
* ```
*
* ```tsx
* // Child route
* import { useOutletContext } from "react-router";
*
* function Child() {
* const [count, setCount] = useOutletContext();
* const increment = () => setCount((c) => c + 1);
* return <button onClick={increment}>{count}</button>;
* }
* ```
*
* If you're using TypeScript, we recommend the parent component provide a
* custom hook for accessing the context value. This makes it easier for
* consumers to get nice typings, control consumers, and know who's consuming
* the context value.
*
* Here's a more realistic example:
*
* ```tsx filename=src/routes/dashboard.tsx lines=[14,20]
* import { useState } from "react";
* import { Outlet, useOutletContext } from "react-router";
*
* import type { User } from "./types";
*
* type ContextType = { user: User | null };
*
* export default function Dashboard() {
* const [user, setUser] = useState<User | null>(null);
*
* return (
* <div>
* <h1>Dashboard</h1>
* <Outlet context={{ user } satisfies ContextType} />
* </div>
* );
* }
*
* export function useUser() {
* return useOutletContext<ContextType>();
* }
* ```
*
* ```tsx filename=src/routes/dashboard/messages.tsx lines=[1,4]
* import { useUser } from "../dashboard";
*
* export default function DashboardMessages() {
* const { user } = useUser();
* return (
* <div>
* <h2>Messages</h2>
* <p>Hello, {user.name}!</p>
* </div>
* );
* }
* ```
*
* @public
* @category Hooks
* @returns The context value passed to the parent {@link Outlet} component
*/
declare function useOutletContext<Context = unknown>(): Context;
/**
* Returns the element for the child route at this level of the route
* hierarchy. Used internally by {@link Outlet | `<Outlet>`} to render child
* routes.
*
* @public
* @category Hooks
* @param context The context to pass to the outlet
* @returns The child route element or `null` if no child routes match
*/
declare function useOutlet(context?: unknown): React.ReactElement | null;
/**
* Returns an object of key/value-pairs of the dynamic params from the current
* URL that were matched by the routes. Child routes inherit all params from
* their parent routes.
*
* Assuming a route pattern like `/posts/:postId` is matched by `/posts/123`
* then `params.postId` will be `"123"`.
*
* @example
* import { useParams } from "react-router";
*
* function SomeComponent() {
* let params = useParams();
* params.postId;
* }
*
* @additionalExamples
* ### Basic Usage
*
* ```tsx
* import { useParams } from "react-router";
*
* // given a route like:
* <Route path="/posts/:postId" element={<Post />} />;
*
* // or a data route like:
* createBrowserRouter([
* {
* path: "/posts/:postId",
* component: Post,
* },
* ]);
*
* // or in routes.ts
* route("/posts/:postId", "routes/post.tsx");
* ```
*
* Access the params in a component:
*
* ```tsx
* import { useParams } from "react-router";
*
* export default function Post() {
* let params = useParams();
* return <h1>Post: {params.postId}</h1>;
* }
* ```
*
* ### Multiple Params
*
* Patterns can have multiple params:
*
* ```tsx
* "/posts/:postId/comments/:commentId";
* ```
*
* All will be available in the params object:
*
* ```tsx
* import { useParams } from "react-router";
*
* export default function Post() {
* let params = useParams();
* return (
* <h1>
* Post: {params.postId}, Comment: {params.commentId}
* </h1>
* );
* }
* ```
*
* ### Catchall Params
*
* Catchall params are defined with `*`:
*
* ```tsx
* "/files/*";
* ```
*
* The matched value will be available in the params object as follows:
*
* ```tsx
* import { useParams } from "react-router";
*
* export default function File() {
* let params = useParams();
* let catchall = params["*"];
* // ...
* }
* ```
*
* You can destructure the catchall param:
*
* ```tsx
* export default function File() {
* let { "*": catchall } = useParams();
* console.log(catchall);
* }
* ```
*
* @public
* @category Hooks
* @returns An object containing the dynamic route parameters
*/
declare function useParams<ParamsOrKey extends string | Record<string, string | undefined> = string>(): Readonly<[
ParamsOrKey
] extends [string] ? Params<ParamsOrKey> : Partial<ParamsOrKey>>;
/**
* Resolves the pathname of the given `to` value against the current
* {@link Location}. Similar to {@link useHref}, but returns a
* {@link Path} instead of a string.
*
* @example
* import { useResolvedPath } from "react-router";
*
* function SomeComponent() {
* // if the user is at /dashboard/profile
* let path = useResolvedPath("../accounts");
* path.pathname; // "/dashboard/accounts"
* path.search; // ""
* path.hash; // ""
* }
*
* @public
* @category Hooks
* @param to The path to resolve
* @param options Options
* @param options.relative Defaults to `"route"` so routing is relative to the route tree.
* Set to `"path"` to make relative routing operate against path segments.
* @returns The resolved {@link Path} object with `pathname`, `search`, and `hash`
*/
declare function useResolvedPath(to: To, { relative }?: {
relative?: RelativeRoutingType;
}): Path;
/**
* Hook version of {@link Routes | `<Routes>`} that uses objects instead of
* components. These objects have the same properties as the component props.
* The return value of `useRoutes` is either a valid React element you can use
* to render the route tree, or `null` if nothing matched.
*
* @example
* import { useRoutes } from "react-router";
*
* function App() {
* let element = useRoutes([
* {
* path: "/",
* element: <Dashboard />,
* children: [
* {
* path: "messages",
* element: <DashboardMessages />,
* },
* { path: "tasks", element: <DashboardTasks /> },
* ],
* },
* { path: "team", element: <AboutPage /> },
* ]);
*
* return element;
* }
*
* @public
* @category Hooks
* @param routes An array of {@link RouteObject}s that define the route hierarchy
* @param locationArg An optional {@link Location} object or pathname string to
* use instead of the current {@link Location}
* @returns A React element to render the matched route, or `null` if no routes matched
*/
declare function useRoutes(routes: RouteObject[], locationArg?: Partial<Location> | string): React.ReactElement | null;
/**
* Returns the current {@link Navigation}, defaulting to an "idle" navigation
* when no navigation is in progress. You can use this to render pending UI
* (like a global spinner) or read [`FormData`](https://developer.mozilla.org/en-US/docs/Web/API/FormData)
* from a form navigation.
*
* @example
* import { useNavigation } from "react-router";
*
* function SomeComponent() {
* let navigation = useNavigation();
* navigation.state;
* navigation.formData;
* // etc.
* }
*
* @public
* @category Hooks
* @mode framework
* @mode data
* @returns The current {@link Navigation} object
*/
declare function useNavigation(): Navigation;
/**
* Revalidate the data on the page for reasons outside of normal data mutations
* like [`Window` focus](https://developer.mozilla.org/en-US/docs/Web/API/Window/focus_event)
* or polling on an interval.
*
* Note that page data is already revalidated automatically after actions.
* If you find yourself using this for normal CRUD operations on your data in
* response to user interactions, you're probably not taking advantage of the
* other APIs like {@link useFetcher}, {@link Form}, {@link useSubmit} that do
* this automatically.
*
* @example
* import { useRevalidator } from "react-router";
*
* function WindowFocusRevalidator() {
* const revalidator = useRevalidator();
*
* useFakeWindowFocus(() => {
* revalidator.revalidate();
* });
*
* return (
* <div hidden={revalidator.state === "idle"}>
* Revalidating...
* </div>
* );
* }
*
* @public
* @category Hooks
* @mode framework
* @mode data
* @returns An object with a `revalidate` function and the current revalidation
* `state`
*/
declare function useRevalidator(): {
revalidate: () => Promise<void>;
state: Router["state"]["revalidation"];
};
/**
* Returns the active route matches, useful for accessing `loaderData` for
* parent/child routes or the route [`handle`](../../start/framework/route-module#handle)
* property
*
* @public
* @category Hooks
* @mode framework
* @mode data
* @returns An array of {@link UIMatch | UI matches} for the current route hierarchy
*/
declare function useMatches(): UIMatch[];
/**
* Returns the data from the closest route
* [`loader`](../../start/framework/route-module#loader) or
* [`clientLoader`](../../start/framework/route-module#clientloader).
*
* @example
* import { useLoaderData } from "react-router";
*
* export async function loader() {
* return await fakeDb.invoices.findAll();
* }
*
* export default function Invoices() {
* let invoices = useLoaderData<typeof loader>();
* // ...
* }
*
* @public
* @category Hooks
* @mode framework
* @mode data
* @returns The data returned from the route's [`loader`](../../start/framework/route-module#loader) or [`clientLoader`](../../start/framework/route-module#clientloader) function
*/
declare function useLoaderData<T = any>(): SerializeFrom<T>;
/**
* Returns the [`loader`](../../start/framework/route-module#loader) data for a
* given route by route ID.
*
* Route IDs are created automatically. They are simply the path of the route file
* relative to the app folder without the extension.
*
* | Route Filename | Route ID |
* | ---------------------------- | ---------------------- |
* | `app/root.tsx` | `"root"` |
* | `app/routes/teams.tsx` | `"routes/teams"` |
* | `app/whatever/teams.$id.tsx` | `"whatever/teams.$id"` |
*
* @example
* import { useRouteLoaderData } from "react-router";
*
* function SomeComponent() {
* const { user } = useRouteLoaderData("root");
* }
*
* // You can also specify your own route ID's manually in your routes.ts file:
* route("/", "containers/app.tsx", { id: "app" })
* useRouteLoaderData("app");
*
* @public
* @category Hooks
* @mode framework
* @mode data
* @param routeId The ID of the route to return loader data from
* @returns The data returned from the specified route's [`loader`](../../start/framework/route-module#loader)
* function, or `undefined` if not found
*/
declare function useRouteLoaderData<T = any>(routeId: string): SerializeFrom<T> | undefined;
/**
* Returns the [`action`](../../start/framework/route-module#action) data from
* the most recent `POST` navigation form submission or `undefined` if there
* hasn't been one.
*
* @example
* import { Form, useActionData } from "react-router";
*
* export async function action({ request }) {
* const body = await request.formData();
* const name = body.get("visitorsName");
* return { message: `Hello, ${name}` };
* }
*
* export default function Invoices() {
* const data = useActionData();
* return (
* <Form method="post">
* <input type="text" name="visitorsName" />
* {data ? data.message : "Waiting..."}
* </Form>
* );
* }
*
* @public
* @category Hooks
* @mode framework
* @mode data
* @returns The data returned from the route's [`action`](../../start/framework/route-module#action)
* function, or `undefined` if no [`action`](../../start/framework/route-module#action)
* has been called
*/
declare function useActionData<T = any>(): SerializeFrom<T> | undefined;
/**
* Accesses the error thrown during an
* [`action`](../../start/framework/route-module#action),
* [`loader`](../../start/framework/route-module#loader),
* or component render to be used in a route module
* [`ErrorBoundary`](../../start/framework/route-module#errorboundary).
*
* @example
* export function ErrorBoundary() {
* const error = useRouteError();
* return <div>{error.message}</div>;
* }
*
* @public
* @category Hooks
* @mode framework
* @mode data
* @returns The error that was thrown during route [loading](../../start/framework/route-module#loader),
* [`action`](../../start/framework/route-module#action) execution, or rendering
*/
declare function useRouteError(): unknown;
/**
* Returns the resolved promise value from the closest {@link Await | `<Await>`}.
*
* @example
* function SomeDescendant() {
* const value = useAsyncValue();
* // ...
* }
*
* // somewhere in your app
* <Await resolve={somePromise}>
* <SomeDescendant />
* </Await>;
*
* @public
* @category Hooks
* @mode framework
* @mode data
* @returns The resolved value from the nearest {@link Await} component
*/
declare function useAsyncValue(): unknown;
/**
* Returns the rejection value from the closest {@link Await | `<Await>`}.
*
* @example
* import { Await, useAsyncError } from "react-router";
*
* function ErrorElement() {
* const error = useAsyncError();
* return (
* <p>Uh Oh, something went wrong! {error.message}</p>
* );
* }
*
* // somewhere in your app
* <Await
* resolve={promiseThatRejects}
* errorElement={<ErrorElement />}
* />;
*
* @public
* @category Hooks
* @mode framework
* @mode data
* @returns The error that was thrown in the nearest {@link Await} component
*/
declare function useAsyncError(): unknown;
/**
* Allow the application to block navigations within the SPA and present the
* user a confirmation dialog to confirm the navigation. Mostly used to avoid
* using half-filled form data. This does not handle hard-reloads or
* cross-origin navigations.
*
* The {@link Blocker} object returned by the hook has the following properties:
*
* - **`state`**
* - `unblocked` - the blocker is idle and has not prevented any navigation
* - `blocked` - the blocker has prevented a navigation
* - `proceeding` - the blocker is proceeding through from a blocked navigation
* - **`location`**
* - When in a `blocked` state, this represents the {@link Location} to which
* we blocked a navigation. When in a `proceeding` state, this is the
* location being navigated to after a `blocker.proceed()` call.
* - **`proceed()`**
* - When in a `blocked` state, you may call `blocker.proceed()` to proceed to
* the blocked location.
* - **`reset()`**
* - When in a `blocked` state, you may call `blocker.reset()` to return the
* blocker to an `unblocked` state and leave the user at the current
* location.
*
* @example
* // Boolean version
* let blocker = useBlocker(value !== "");
*
* // Function version
* let blocker = useBlocker(
* ({ currentLocation, nextLocation, historyAction }) =>
* value !== "" &&
* currentLocation.pathname !== nextLocation.pathname
* );
*
* @additionalExamples
* ```tsx
* import { useCallback, useState } from "react";
* import { BlockerFunction, useBlocker } from "react-router";
*
* export function ImportantForm() {
* const [value, setValue] = useState("");
*
* const shouldBlock = useCallback<BlockerFunction>(
* () => value !== "",
* [value]
* );
* const blocker = useBlocker(shouldBlock);
*
* return (
* <form
* onSubmit={(e) => {
* e.preventDefault();
* setValue("");
* if (blocker.state === "blocked") {
* blocker.proceed();
* }
* }}
* >
* <input
* name="data"
* value={value}
* onChange={(e) => setValue(e.target.value)}
* />
*
* <button type="submit">Save</button>
*
* {blocker.state === "blocked" ? (
* <>
* <p style={{ color: "red" }}>
* Blocked the last navigation to
* </p>
* <button
* type="button"
* onClick={() => blocker.proceed()}
* >
* Let me through
* </button>
* <button
* type="button"
* onClick={() => blocker.reset()}
* >
* Keep me here
* </button>
* </>
* ) : blocker.state === "proceeding" ? (
* <p style={{ color: "orange" }}>
* Proceeding through blocked navigation
* </p>
* ) : (
* <p style={{ color: "green" }}>
* Blocker is currently unblocked
* </p>
* )}
* </form>
* );
* }
* ```
*
* @public
* @category Hooks
* @mode framework
* @mode data
* @param shouldBlock Either a boolean or a function returning a boolean which
* indicates whether the navigation should be blocked. The function format
* receives a single object parameter containing the `currentLocation`,
* `nextLocation`, and `historyAction` of the potential navigation.
* @returns A {@link Blocker} object with state and reset functionality
*/
declare function useBlocker(shouldBlock: boolean | BlockerFunction): Blocker;
type UseRouteArgs = [] | [routeId: keyof RouteModules$1];
type UseRouteResult<Args extends UseRouteArgs> = Args extends [] ? UseRoute<unknown> : Args extends ["root"] ? UseRoute<"root"> : Args extends [infer RouteId extends keyof RouteModules$1] ? UseRoute<RouteId> | undefined : never;
type UseRoute<RouteId extends keyof RouteModules$1 | unknown> = {
handle: RouteId extends keyof RouteModules$1 ? RouteModules$1[RouteId] extends {
handle: infer handle;
} ? handle : unknown : unknown;
loaderData: RouteId extends keyof RouteModules$1 ? GetLoaderData<RouteModules$1[RouteId]> | undefined : unknown;
actionData: RouteId extends keyof RouteModules$1 ? GetActionData<RouteModules$1[RouteId]> | undefined : unknown;
};
declare function useRoute<Args extends UseRouteArgs>(...args: Args): UseRouteResult<Args>;
/**
* @category Types
*/
interface ServerRouterProps {
/**
* The entry context containing the manifest, route modules, and other data
* needed for rendering.
*/
context: EntryContext;
/**
* The URL of the request being handled.
*/
url: string | URL;
/**
* An optional `nonce` for [Content Security Policy (CSP)](https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/CSP)
* compliance, used to allow inline scripts to run safely.
*/
nonce?: string;
}
/**
* The server entry point for a React Router app in Framework Mode. This
* component is used to generate the HTML in the response from the server. See
* [`entry.server.tsx`](../framework-conventions/entry.server.tsx).
*
* @public
* @category Framework Routers
* @mode framework
* @param props Props
* @param {ServerRouterProps.context} props.context n/a
* @param {ServerRouterProps.nonce} props.nonce n/a
* @param {ServerRouterProps.url} props.url n/a
* @returns A React element that represents the server-rendered application.
*/
declare function ServerRouter({ context, url, nonce, }: ServerRouterProps): ReactElement;
interface StubRouteExtensions {
Component?: RouteComponentType;
HydrateFallback?: HydrateFallbackType;
ErrorBoundary?: ErrorBoundaryType;
loader?: LoaderFunction;
action?: ActionFunction;
children?: StubRouteObject[];
meta?: MetaFunction;
links?: LinksFunction;
}
interface StubIndexRouteObject extends Omit<IndexRouteObject, "Component" | "HydrateFallback" | "ErrorBoundary" | "loader" | "action" | "element" | "errorElement" | "children">, StubRouteExtensions {
}
interface StubNonIndexRouteObject extends Omit<NonIndexRouteObject, "Component" | "HydrateFallback" | "ErrorBoundary" | "loader" | "action" | "element" | "errorElement" | "children">, StubRouteExtensions {
}
type StubRouteObject = StubIndexRouteObject | StubNonIndexRouteObject;
interface RoutesTestStubProps {
/**
* The initial entries in the history stack. This allows you to start a test with
* multiple locations already in the history stack (for testing a back navigation, etc.)
* The test will default to the last entry in initialEntries if no initialIndex is provided.
* e.g. initialEntries={["/home", "/about", "/contact"]}
*/
initialEntries?: InitialEntry[];
/**
* The initial index in the history stack to render. This allows you to start a test at a specific entry.
* It defaults to the last entry in initialEntries.
* e.g.
* initialEntries: ["/", "/events/123"]
* initialIndex: 1 // start at "/events/123"
*/
initialIndex?: number;
/**
* Used to set the route's initial loader and action data.
* e.g. hydrationData={{
* loaderData: { "/contact": { locale: "en-US" } },
* actionData: { "/login": { errors: { email: "invalid email" } }}
* }}
*/
hydrationData?: HydrationState;
/**
* Future flags mimicking the settings in react-router.config.ts
*/
future?: Partial<FutureConfig>;
}
/**
* @category Utils
*/
declare function createRoutesStub(routes: StubRouteObject[], _context?: AppLoadContext | RouterContextProvider): ({ initialEntries, initialIndex, hydrationData, future, }: RoutesTestStubProps) => React.JSX.Element;
interface CookieSignatureOptions {
/**
* An array of secrets that may be used to sign/unsign the value of a cookie.
*
* The array makes it easy to rotate secrets. New secrets should be added to
* the beginning of the array. `cookie.serialize()` will always use the first
* value in the array, but `cookie.parse()` may use any of them so that
* cookies that were signed with older secrets still work.
*/
secrets?: string[];
}
type CookieOptions = ParseOptions & SerializeOptions & CookieSignatureOptions;
/**
* A HTTP cookie.
*
* A Cookie is a logical container for metadata about a HTTP cookie; its name
* and options. But it doesn't contain a value. Instead, it has `parse()` and
* `serialize()` methods that allow a single instance to be reused for
* parsing/encoding multiple different values.
*
* @see https://remix.run/utils/cookies#cookie-api
*/
interface Cookie {
/**
* The name of the cookie, used in the `Cookie` and `Set-Cookie` headers.
*/
readonly name: string;
/**
* True if this cookie uses one or more secrets for verification.
*/
readonly isSigned: boolean;
/**
* The Date this cookie expires.
*
* Note: This is calculated at access time using `maxAge` when no `expires`
* option is provided to `createCookie()`.
*/
readonly expires?: Date;
/**
* Parses a raw `Cookie` header and returns the value of this cookie or
* `null` if it's not present.
*/
parse(cookieHeader: string | null, options?: ParseOptions): Promise<any>;
/**
* Serializes the given value to a string and returns the `Set-Cookie`
* header.
*/
serialize(value: any, options?: SerializeOptions): Promise<string>;
}
/**
* Creates a logical container for managing a browser cookie from the server.
*/
declare const createCookie: (name: string, cookieOptions?: CookieOptions) => Cookie;
type IsCookieFunction = (object: any) => object is Cookie;
/**
* Returns true if an object is a Remix cookie container.
*
* @see https://remix.run/utils/cookies#iscookie
*/
declare const isCookie: IsCookieFunction;
/**
* An object of name/value pairs to be used in the session.
*/
interface SessionData {
[name: string]: any;
}
/**
* Session persists data across HTTP requests.
*
* @see https://reactrouter.com/explanation/sessions-and-cookies#sessions
*/
interface Session<Data = SessionData, FlashData = Data> {
/**
* A unique identifier for this session.
*
* Note: This will be the empty string for newly created sessions and
* sessions that are not backed by a database (i.e. cookie-based sessions).
*/
readonly id: string;
/**
* The raw data contained in this session.
*
* This is useful mostly for SessionStorage internally to access the raw
* session data to persist.
*/
readonly data: FlashSessionData<Data, FlashData>;
/**
* Returns `true` if the session has a value for the given `name`, `false`
* otherwise.
*/
has(name: (keyof Data | keyof FlashData) & string): boolean;
/**
* Returns the value for the given `name` in this session.
*/
get<Key extends (keyof Data | keyof FlashData) & string>(name: Key): (Key extends keyof Data ? Data[Key] : undefined) | (Key extends keyof FlashData ? FlashData[Key] : undefined) | undefined;
/**
* Sets a value in the session for the given `name`.
*/
set<Key extends keyof Data & string>(name: Key, value: Data[Key]): void;
/**
* Sets a value in the session that is only valid until the next `get()`.
* This can be useful for temporary values, like error messages.
*/
flash<Key extends keyof FlashData & string>(name: Key, value: FlashData[Key]): void;
/**
* Removes a value from the session.
*/
unset(name: keyof Data & string): void;
}
type FlashSessionData<Data, FlashData> = Partial<Data & {
[Key in keyof FlashData as FlashDataKey<Key & string>]: FlashData[Key];
}>;
type FlashDataKey<Key extends string> = `__flash_${Key}__`;
type CreateSessionFunction = <Data = SessionData, FlashData = Data>(initialData?: Data, id?: string) => Session<Data, FlashData>;
/**
* Creates a new Session object.
*
* Note: This function is typically not invoked directly by application code.
* Instead, use a `SessionStorage` object's `getSession` method.
*/
declare const createSession: CreateSessionFunction;
type IsSessionFunction = (object: any) => object is Session;
/**
* Returns true if an object is a React Router session.
*
* @see https://reactrouter.com/api/utils/isSession
*/
declare const isSession: IsSessionFunction;
/**
* SessionStorage stores session data between HTTP requests and knows how to
* parse and create cookies.
*
* A SessionStorage creates Session objects using a `Cookie` header as input.
* Then, later it generates the `Set-Cookie` header to be used in the response.
*/
interface SessionStorage<Data = SessionData, FlashData = Data> {
/**
* Parses a Cookie header from a HTTP request and returns the associated
* Session. If there is no session associated with the cookie, this will
* return a new Session with no data.
*/
getSession: (cookieHeader?: string | null, options?: ParseOptions) => Promise<Session<Data, FlashData>>;
/**
* Stores all data in the Session and returns the Set-Cookie header to be
* used in the HTTP response.
*/
commitSession: (session: Session<Data, FlashData>, options?: SerializeOptions) => Promise<string>;
/**
* Deletes all data associated with the Session and returns the Set-Cookie
* header to be used in the HTTP response.
*/
destroySession: (session: Session<Data, FlashData>, options?: SerializeOptions) => Promise<string>;
}
/**
* SessionIdStorageStrategy is designed to allow anyone to easily build their
* own SessionStorage using `createSessionStorage(strategy)`.
*
* This strategy describes a common scenario where the session id is stored in
* a cookie but the actual session data is stored elsewhere, usually in a
* database or on disk. A set of create, read, update, and delete operations
* are provided for managing the session data.
*/
interface SessionIdStorageStrategy<Data = SessionData, FlashData = Data> {
/**
* The Cookie used to store the session id, or options used to automatically
* create one.
*/
cookie?: Cookie | (CookieOptions & {
name?: string;
});
/**
* Creates a new record with the given data and returns the session id.
*/
createData: (data: FlashSessionData<Data, FlashData>, expires?: Date) => Promise<string>;
/**
* Returns data for a given session id, or `null` if there isn't any.
*/
readData: (id: string) => Promise<FlashSessionData<Data, FlashData> | null>;
/**
* Updates data for the given session id.
*/
updateData: (id: string, data: FlashSessionData<Data, FlashData>, expires?: Date) => Promise<void>;
/**
* Deletes data for a given session id from the data store.
*/
deleteData: (id: string) => Promise<void>;
}
/**
* Creates a SessionStorage object using a SessionIdStorageStrategy.
*
* Note: This is a low-level API that should only be used if none of the
* existing session storage options meet your requirements.
*/
declare function createSessionStorage<Data = SessionData, FlashData = Data>({ cookie: cookieArg, createData, readData, updateData, deleteData, }: SessionIdStorageStrategy<Data, FlashData>): SessionStorage<Data, FlashData>;
interface CookieSessionStorageOptions {
/**
* The Cookie used to store the session data on the client, or options used
* to automatically create one.
*/
cookie?: SessionIdStorageStrategy["cookie"];
}
/**
* Creates and returns a SessionStorage object that stores all session data
* directly in the session cookie itself.
*
* This has the advantage that no database or other backend services are
* needed, and can help to simplify some load-balanced scenarios. However, it
* also has the limitation that serialized session data may not exceed the
* browser's maximum cookie size. Trade-offs!
*/
declare function createCookieSessionStorage<Data = SessionData, FlashData = Data>({ cookie: cookieArg }?: CookieSessionStorageOptions): SessionStorage<Data, FlashData>;
interface MemorySessionStorageOptions {
/**
* The Cookie used to store the session id on the client, or options used
* to automatically create one.
*/
cookie?: SessionIdStorageStrategy["cookie"];
}
/**
* Creates and returns a simple in-memory SessionStorage object, mostly useful
* for testing and as a reference implementation.
*
* Note: This storage does not scale beyond a single process, so it is not
* suitable for most production scenarios.
*/
declare function createMemorySessionStorage<Data = SessionData, FlashData = Data>({ cookie }?: MemorySessionStorageOptions): SessionStorage<Data, FlashData>;
type DevServerHooks = {
getCriticalCss?: (pathname: string) => Promise<string | undefined>;
processRequestError?: (error: unknown) => void;
};
declare function setDevServerHooks(devServerHooks: DevServerHooks): void;
type Args = {
[K in keyof Pages]: ToArgs<Pages[K]["params"]>;
};
type ToArgs<Params extends Record<string, string | undefined>> = Equal<Params, {}> extends true ? [] : Partial<Params> extends Params ? [Params] | [] : [
Params
];
/**
Returns a resolved URL path for the specified route.
```tsx
const h = href("/:lang?/about", { lang: "en" })
// -> `/en/about`
<Link to={href("/products/:id", { id: "abc123" })} />
```
*/
declare function href<Path extends keyof Args>(path: Path, ...args: Args[Path]): string;
type DecodedPayload = Promise<RSCPayload> & {
_deepestRenderedBoundaryId?: string | null;
formState: Promise<any>;
};
type SSRCreateFromReadableStreamFunction = (body: ReadableStream<Uint8Array>) => Promise<unknown>;
/**
* Routes the incoming [`Request`](https://developer.mozilla.org/en-US/docs/Web/API/Request)
* to the [RSC](https://react.dev/reference/rsc/server-components) server and
* appropriately proxies the server response for data / resource requests, or
* renders to HTML for a document request.
*
* @example
* import { createFromReadableStream } from "@vitejs/plugin-rsc/ssr";
* import * as ReactDomServer from "react-dom/server.edge";
* import {
* unstable_RSCStaticRouter as RSCStaticRouter,
* unstable_routeRSCServerRequest as routeRSCServerRequest,
* } from "react-router";
*
* routeRSCServerRequest({
* request,
* serverResponse,
* createFromReadableStream,
* async renderHTML(getPayload) {
* const payload = getPayload();
*
* return await renderHTMLToReadableStream(
* <RSCStaticRouter getPayload={getPayload} />,
* {
* bootstrapScriptContent,
* formState: await payload.formState,
* }
* );
* },
* });
*
* @name unstable_routeRSCServerRequest
* @public
* @category RSC
* @mode data
* @param opts Options
* @param opts.createFromReadableStream Your `react-server-dom-xyz/client`'s
* `createFromReadableStream` function, used to decode payloads from the server.
* @param opts.serverResponse A Response or partial response generated by the [RSC](https://react.dev/reference/rsc/server-components) handler containing a serialized {@link unstable_RSCPayload}.
* @param opts.hydrate Whether to hydrate the server response with the RSC payload.
* Defaults to `true`.
* @param opts.renderHTML A function that renders the {@link unstable_RSCPayload} to
* HTML, usually using a {@link unstable_RSCStaticRouter | `<RSCStaticRouter>`}.
* @param opts.request The request to route.
* @returns A [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
* that either contains the [RSC](https://react.dev/reference/rsc/server-components)
* payload for data requests, or renders the HTML for document requests.
*/
declare function routeRSCServerRequest({ request, serverResponse, createFromReadableStream, renderHTML, hydrate, }: {
request: Request;
serverResponse: Response;
createFromReadableStream: SSRCreateFromReadableStreamFunction;
renderHTML: (getPayload: () => DecodedPayload, options: {
onError(error: unknown): string | undefined;
onHeaders(headers: Headers): void;
}) => ReadableStream<Uint8Array> | Promise<ReadableStream<Uint8Array>>;
hydrate?: boolean;
}): Promise<Response>;
/**
* Props for the {@link unstable_RSCStaticRouter} component.
*
* @name unstable_RSCStaticRouterProps
* @category Types
*/
interface RSCStaticRouterProps {
/**
* A function that starts decoding of the {@link unstable_RSCPayload}. Usually passed
* through from {@link unstable_routeRSCServerRequest}'s `renderHTML`.
*/
getPayload: () => DecodedPayload;
}
/**
* Pre-renders an {@link unstable_RSCPayload} to HTML. Usually used in
* {@link unstable_routeRSCServerRequest}'s `renderHTML` callback.
*
* @example
* import { createFromReadableStream } from "@vitejs/plugin-rsc/ssr";
* import * as ReactDomServer from "react-dom/server.edge";
* import {
* unstable_RSCStaticRouter as RSCStaticRouter,
* unstable_routeRSCServerRequest as routeRSCServerRequest,
* } from "react-router";
*
* routeRSCServerRequest({
* request,
* serverResponse,
* createFromReadableStream,
* async renderHTML(getPayload) {
* const payload = getPayload();
*
* return await renderHTMLToReadableStream(
* <RSCStaticRouter getPayload={getPayload} />,
* {
* bootstrapScriptContent,
* formState: await payload.formState,
* }
* );
* },
* });
*
* @name unstable_RSCStaticRouter
* @public
* @category RSC
* @mode data
* @param props Props
* @param {unstable_RSCStaticRouterProps.getPayload} props.getPayload n/a
* @returns A React component that renders the {@link unstable_RSCPayload} as HTML.
*/
declare function RSCStaticRouter({ getPayload }: RSCStaticRouterProps): React.JSX.Element | null;
declare function RSCDefaultRootErrorBoundary({ hasRootLayout, }: {
hasRootLayout: boolean;
}): React__default.JSX.Element;
declare function deserializeErrors(errors: RouterState["errors"]): RouterState["errors"];
type RemixErrorBoundaryProps = React.PropsWithChildren<{
location: Location;
isOutsideRemixApp?: boolean;
error?: Error;
}>;
type RemixErrorBoundaryState = {
error: null | Error;
location: Location;
};
declare class RemixErrorBoundary extends React.Component<RemixErrorBoundaryProps, RemixErrorBoundaryState> {
constructor(props: RemixErrorBoundaryProps);
static getDerivedStateFromError(error: Error): {
error: Error;
};
static getDerivedStateFromProps(props: RemixErrorBoundaryProps, state: RemixErrorBoundaryState): {
error: Error | null;
location: Location<any>;
};
render(): string | number | boolean | React.JSX.Element | Iterable<React.ReactNode> | null | undefined;
}
declare function getPatchRoutesOnNavigationFunction(manifest: AssetsManifest, routeModules: RouteModules, ssr: boolean, routeDiscovery: ServerBuild["routeDiscovery"], isSpaMode: boolean, basename: string | undefined): PatchRoutesOnNavigationFunction | undefined;
declare function useFogOFWarDiscovery(router: Router, manifest: AssetsManifest, routeModules: RouteModules, ssr: boolean, routeDiscovery: ServerBuild["routeDiscovery"], isSpaMode: boolean): void;
declare function getHydrationData({ state, routes, getRouteInfo, location, basename, isSpaMode, }: {
state: {
loaderData?: Router["state"]["loaderData"];
actionData?: Router["state"]["actionData"];
errors?: Router["state"]["errors"];
};
routes: DataRouteObject[];
getRouteInfo: (routeId: string) => {
clientLoader: ClientLoaderFunction | undefined;
hasLoader: boolean;
hasHydrateFallback: boolean;
};
location: Path;
basename: string | undefined;
isSpaMode: boolean;
}): HydrationState;
/**
* @module index
* @mergeModuleWith react-router
*/
declare const unstable_matchRSCServerRequest: typeof matchRSCServerRequest;
export { ActionFunction, AppLoadContext, Blocker, BlockerFunction, ClientLoaderFunction, type Cookie, type CookieOptions, type CookieSignatureOptions, type CreateRequestHandlerFunction, DataRouteObject, Router as DataRouter, DataStrategyFunction, EntryContext, type FlashSessionData, HydrationState, IndexRouteObject, InitialEntry, type IsCookieFunction, type IsSessionFunction, LinksFunction, LoaderFunction, Location, MetaFunction, type NavigateFunction, NavigateOptions, Navigation, Action as NavigationType, NonIndexRouteObject, ParamParseKey, Params, PatchRoutesOnNavigationFunction, Path, PathMatch, PathPattern, RelativeRoutingType, type RequestHandler, RouteObject, RouterContextProvider, RouterState, type RoutesTestStubProps, ServerBuild, ServerRouter, type ServerRouterProps, type Session, type SessionData, type SessionIdStorageStrategy, type SessionStorage, To, UIMatch, AssetsManifest as UNSAFE_AssetsManifest, MiddlewareEnabled as UNSAFE_MiddlewareEnabled, RSCDefaultRootErrorBoundary as UNSAFE_RSCDefaultRootErrorBoundary, RemixErrorBoundary as UNSAFE_RemixErrorBoundary, RouteModules as UNSAFE_RouteModules, ServerMode as UNSAFE_ServerMode, SingleFetchRedirectSymbol as UNSAFE_SingleFetchRedirectSymbol, decodeViaTurboStream as UNSAFE_decodeViaTurboStream, deserializeErrors as UNSAFE_deserializeErrors, getHydrationData as UNSAFE_getHydrationData, getPatchRoutesOnNavigationFunction as UNSAFE_getPatchRoutesOnNavigationFunction, getTurboStreamSingleFetchDataStrategy as UNSAFE_getTurboStreamSingleFetchDataStrategy, useFogOFWarDiscovery as UNSAFE_useFogOFWarDiscovery, createCookie, createCookieSessionStorage, createMemorySessionStorage, createRequestHandler, createRoutesStub, createSession, createSessionStorage, href, isCookie, isSession, RSCPayload as unstable_RSCPayload, RSCStaticRouter as unstable_RSCStaticRouter, type RSCStaticRouterProps as unstable_RSCStaticRouterProps, type SSRCreateFromReadableStreamFunction as unstable_SSRCreateFromReadableStreamFunction, unstable_matchRSCServerRequest, routeRSCServerRequest as unstable_routeRSCServerRequest, setDevServerHooks as unstable_setDevServerHooks, useRoute as unstable_useRoute, useActionData, useAsyncError, useAsyncValue, useBlocker, useHref, useInRouterContext, useLoaderData, useLocation, useMatch, useMatches, useNavigate, useNavigation, useNavigationType, useOutlet, useOutletContext, useParams, useResolvedPath, useRevalidator, useRouteError, useRouteLoaderData, useRoutes };
|