UNPKG

21.6 kBTypeScriptView Raw
1import { e as RouteObject, f as History, g as MaybePromise, c as RouterContextProvider, h as MapRoutePropertiesFunction, i as Action, L as Location, D as DataRouteMatch, j as Submission, k as RouteData, l as DataStrategyFunction, m as PatchRoutesOnNavigationFunction, n as DataRouteObject, U as UIMatch, T as To, o as HTMLFormMethod, F as FormEncType, p as Path, q as LoaderFunctionArgs, r as MiddlewareEnabled, s as AppLoadContext } from './routeModules-CM_clkdE.js';
2
3/**
4 * A Router instance manages all navigation and data loading/mutations
5 */
6interface Router {
7 /**
8 * @private
9 * PRIVATE - DO NOT USE
10 *
11 * Return the basename for the router
12 */
13 get basename(): RouterInit["basename"];
14 /**
15 * @private
16 * PRIVATE - DO NOT USE
17 *
18 * Return the future config for the router
19 */
20 get future(): FutureConfig;
21 /**
22 * @private
23 * PRIVATE - DO NOT USE
24 *
25 * Return the current state of the router
26 */
27 get state(): RouterState;
28 /**
29 * @private
30 * PRIVATE - DO NOT USE
31 *
32 * Return the routes for this router instance
33 */
34 get routes(): DataRouteObject[];
35 /**
36 * @private
37 * PRIVATE - DO NOT USE
38 *
39 * Return the window associated with the router
40 */
41 get window(): RouterInit["window"];
42 /**
43 * @private
44 * PRIVATE - DO NOT USE
45 *
46 * Initialize the router, including adding history listeners and kicking off
47 * initial data fetches. Returns a function to cleanup listeners and abort
48 * any in-progress loads
49 */
50 initialize(): Router;
51 /**
52 * @private
53 * PRIVATE - DO NOT USE
54 *
55 * Subscribe to router.state updates
56 *
57 * @param fn function to call with the new state
58 */
59 subscribe(fn: RouterSubscriber): () => void;
60 /**
61 * @private
62 * PRIVATE - DO NOT USE
63 *
64 * Enable scroll restoration behavior in the router
65 *
66 * @param savedScrollPositions Object that will manage positions, in case
67 * it's being restored from sessionStorage
68 * @param getScrollPosition Function to get the active Y scroll position
69 * @param getKey Function to get the key to use for restoration
70 */
71 enableScrollRestoration(savedScrollPositions: Record<string, number>, getScrollPosition: GetScrollPositionFunction, getKey?: GetScrollRestorationKeyFunction): () => void;
72 /**
73 * @private
74 * PRIVATE - DO NOT USE
75 *
76 * Navigate forward/backward in the history stack
77 * @param to Delta to move in the history stack
78 */
79 navigate(to: number): Promise<void>;
80 /**
81 * Navigate to the given path
82 * @param to Path to navigate to
83 * @param opts Navigation options (method, submission, etc.)
84 */
85 navigate(to: To | null, opts?: RouterNavigateOptions): Promise<void>;
86 /**
87 * @private
88 * PRIVATE - DO NOT USE
89 *
90 * Trigger a fetcher load/submission
91 *
92 * @param key Fetcher key
93 * @param routeId Route that owns the fetcher
94 * @param href href to fetch
95 * @param opts Fetcher options, (method, submission, etc.)
96 */
97 fetch(key: string, routeId: string, href: string | null, opts?: RouterFetchOptions): Promise<void>;
98 /**
99 * @private
100 * PRIVATE - DO NOT USE
101 *
102 * Trigger a revalidation of all current route loaders and fetcher loads
103 */
104 revalidate(): Promise<void>;
105 /**
106 * @private
107 * PRIVATE - DO NOT USE
108 *
109 * Utility function to create an href for the given location
110 * @param location
111 */
112 createHref(location: Location | URL): string;
113 /**
114 * @private
115 * PRIVATE - DO NOT USE
116 *
117 * Utility function to URL encode a destination path according to the internal
118 * history implementation
119 * @param to
120 */
121 encodeLocation(to: To): Path;
122 /**
123 * @private
124 * PRIVATE - DO NOT USE
125 *
126 * Get/create a fetcher for the given key
127 * @param key
128 */
129 getFetcher<TData = any>(key: string): Fetcher<TData>;
130 /**
131 * @internal
132 * PRIVATE - DO NOT USE
133 *
134 * Reset the fetcher for a given key
135 * @param key
136 */
137 resetFetcher(key: string, opts?: {
138 reason?: unknown;
139 }): void;
140 /**
141 * @private
142 * PRIVATE - DO NOT USE
143 *
144 * Delete the fetcher for a given key
145 * @param key
146 */
147 deleteFetcher(key: string): void;
148 /**
149 * @private
150 * PRIVATE - DO NOT USE
151 *
152 * Cleanup listeners and abort any in-progress loads
153 */
154 dispose(): void;
155 /**
156 * @private
157 * PRIVATE - DO NOT USE
158 *
159 * Get a navigation blocker
160 * @param key The identifier for the blocker
161 * @param fn The blocker function implementation
162 */
163 getBlocker(key: string, fn: BlockerFunction): Blocker;
164 /**
165 * @private
166 * PRIVATE - DO NOT USE
167 *
168 * Delete a navigation blocker
169 * @param key The identifier for the blocker
170 */
171 deleteBlocker(key: string): void;
172 /**
173 * @private
174 * PRIVATE DO NOT USE
175 *
176 * Patch additional children routes into an existing parent route
177 * @param routeId The parent route id or a callback function accepting `patch`
178 * to perform batch patching
179 * @param children The additional children routes
180 * @param unstable_allowElementMutations Allow mutation or route elements on
181 * existing routes. Intended for RSC-usage
182 * only.
183 */
184 patchRoutes(routeId: string | null, children: RouteObject[], unstable_allowElementMutations?: boolean): void;
185 /**
186 * @private
187 * PRIVATE - DO NOT USE
188 *
189 * HMR needs to pass in-flight route updates to React Router
190 * TODO: Replace this with granular route update APIs (addRoute, updateRoute, deleteRoute)
191 */
192 _internalSetRoutes(routes: RouteObject[]): void;
193 /**
194 * @private
195 * PRIVATE - DO NOT USE
196 *
197 * Cause subscribers to re-render. This is used to force a re-render.
198 */
199 _internalSetStateDoNotUseOrYouWillBreakYourApp(state: Partial<RouterState>): void;
200 /**
201 * @private
202 * PRIVATE - DO NOT USE
203 *
204 * Internal fetch AbortControllers accessed by unit tests
205 */
206 _internalFetchControllers: Map<string, AbortController>;
207}
208/**
209 * State maintained internally by the router. During a navigation, all states
210 * reflect the "old" location unless otherwise noted.
211 */
212interface RouterState {
213 /**
214 * The action of the most recent navigation
215 */
216 historyAction: Action;
217 /**
218 * The current location reflected by the router
219 */
220 location: Location;
221 /**
222 * The current set of route matches
223 */
224 matches: DataRouteMatch[];
225 /**
226 * Tracks whether we've completed our initial data load
227 */
228 initialized: boolean;
229 /**
230 * Tracks whether we should be rendering a HydrateFallback during hydration
231 */
232 renderFallback: boolean;
233 /**
234 * Current scroll position we should start at for a new view
235 * - number -> scroll position to restore to
236 * - false -> do not restore scroll at all (used during submissions/revalidations)
237 * - null -> don't have a saved position, scroll to hash or top of page
238 */
239 restoreScrollPosition: number | false | null;
240 /**
241 * Indicate whether this navigation should skip resetting the scroll position
242 * if we are unable to restore the scroll position
243 */
244 preventScrollReset: boolean;
245 /**
246 * Tracks the state of the current navigation
247 */
248 navigation: Navigation;
249 /**
250 * Tracks any in-progress revalidations
251 */
252 revalidation: RevalidationState;
253 /**
254 * Data from the loaders for the current matches
255 */
256 loaderData: RouteData;
257 /**
258 * Data from the action for the current matches
259 */
260 actionData: RouteData | null;
261 /**
262 * Errors caught from loaders for the current matches
263 */
264 errors: RouteData | null;
265 /**
266 * Map of current fetchers
267 */
268 fetchers: Map<string, Fetcher>;
269 /**
270 * Map of current blockers
271 */
272 blockers: Map<string, Blocker>;
273}
274/**
275 * Data that can be passed into hydrate a Router from SSR
276 */
277type HydrationState = Partial<Pick<RouterState, "loaderData" | "actionData" | "errors">>;
278/**
279 * Future flags to toggle new feature behavior
280 */
281interface FutureConfig {
282 unstable_passThroughRequests: boolean;
283}
284/**
285 * Initialization options for createRouter
286 */
287interface RouterInit {
288 routes: RouteObject[];
289 history: History;
290 basename?: string;
291 getContext?: () => MaybePromise<RouterContextProvider>;
292 unstable_instrumentations?: unstable_ClientInstrumentation[];
293 mapRouteProperties?: MapRoutePropertiesFunction;
294 future?: Partial<FutureConfig>;
295 hydrationRouteProperties?: string[];
296 hydrationData?: HydrationState;
297 window?: Window;
298 dataStrategy?: DataStrategyFunction;
299 patchRoutesOnNavigation?: PatchRoutesOnNavigationFunction;
300}
301/**
302 * State returned from a server-side query() call
303 */
304interface StaticHandlerContext {
305 basename: Router["basename"];
306 location: RouterState["location"];
307 matches: RouterState["matches"];
308 loaderData: RouterState["loaderData"];
309 actionData: RouterState["actionData"];
310 errors: RouterState["errors"];
311 statusCode: number;
312 loaderHeaders: Record<string, Headers>;
313 actionHeaders: Record<string, Headers>;
314 _deepestRenderedBoundaryId?: string | null;
315}
316/**
317 * A StaticHandler instance manages a singular SSR navigation/fetch event
318 */
319interface StaticHandler {
320 dataRoutes: DataRouteObject[];
321 query(request: Request, opts?: {
322 requestContext?: unknown;
323 filterMatchesToLoad?: (match: DataRouteMatch) => boolean;
324 skipLoaderErrorBubbling?: boolean;
325 skipRevalidation?: boolean;
326 dataStrategy?: DataStrategyFunction<unknown>;
327 generateMiddlewareResponse?: (query: (r: Request, args?: {
328 filterMatchesToLoad?: (match: DataRouteMatch) => boolean;
329 }) => Promise<StaticHandlerContext | Response>) => MaybePromise<Response>;
330 unstable_normalizePath?: (request: Request) => Path;
331 }): Promise<StaticHandlerContext | Response>;
332 queryRoute(request: Request, opts?: {
333 routeId?: string;
334 requestContext?: unknown;
335 dataStrategy?: DataStrategyFunction<unknown>;
336 generateMiddlewareResponse?: (queryRoute: (r: Request) => Promise<Response>) => MaybePromise<Response>;
337 unstable_normalizePath?: (request: Request) => Path;
338 }): Promise<any>;
339}
340type ViewTransitionOpts = {
341 currentLocation: Location;
342 nextLocation: Location;
343};
344/**
345 * Subscriber function signature for changes to router state
346 */
347interface RouterSubscriber {
348 (state: RouterState, opts: {
349 deletedFetchers: string[];
350 newErrors: RouteData | null;
351 viewTransitionOpts?: ViewTransitionOpts;
352 flushSync: boolean;
353 }): void;
354}
355/**
356 * Function signature for determining the key to be used in scroll restoration
357 * for a given location
358 */
359interface GetScrollRestorationKeyFunction {
360 (location: Location, matches: UIMatch[]): string | null;
361}
362/**
363 * Function signature for determining the current scroll position
364 */
365interface GetScrollPositionFunction {
366 (): number;
367}
368/**
369 * - "route": relative to the route hierarchy so `..` means remove all segments
370 * of the current route even if it has many. For example, a `route("posts/:id")`
371 * would have both `:id` and `posts` removed from the url.
372 * - "path": relative to the pathname so `..` means remove one segment of the
373 * pathname. For example, a `route("posts/:id")` would have only `:id` removed
374 * from the url.
375 */
376type RelativeRoutingType = "route" | "path";
377type BaseNavigateOrFetchOptions = {
378 preventScrollReset?: boolean;
379 relative?: RelativeRoutingType;
380 flushSync?: boolean;
381 unstable_defaultShouldRevalidate?: boolean;
382};
383type BaseNavigateOptions = BaseNavigateOrFetchOptions & {
384 replace?: boolean;
385 state?: any;
386 fromRouteId?: string;
387 viewTransition?: boolean;
388 unstable_mask?: To;
389};
390type BaseSubmissionOptions = {
391 formMethod?: HTMLFormMethod;
392 formEncType?: FormEncType;
393} & ({
394 formData: FormData;
395 body?: undefined;
396} | {
397 formData?: undefined;
398 body: any;
399});
400/**
401 * Options for a navigate() call for a normal (non-submission) navigation
402 */
403type LinkNavigateOptions = BaseNavigateOptions;
404/**
405 * Options for a navigate() call for a submission navigation
406 */
407type SubmissionNavigateOptions = BaseNavigateOptions & BaseSubmissionOptions;
408/**
409 * Options to pass to navigate() for a navigation
410 */
411type RouterNavigateOptions = LinkNavigateOptions | SubmissionNavigateOptions;
412/**
413 * Options for a fetch() load
414 */
415type LoadFetchOptions = BaseNavigateOrFetchOptions;
416/**
417 * Options for a fetch() submission
418 */
419type SubmitFetchOptions = BaseNavigateOrFetchOptions & BaseSubmissionOptions;
420/**
421 * Options to pass to fetch()
422 */
423type RouterFetchOptions = LoadFetchOptions | SubmitFetchOptions;
424/**
425 * Potential states for state.navigation
426 */
427type NavigationStates = {
428 Idle: {
429 state: "idle";
430 location: undefined;
431 formMethod: undefined;
432 formAction: undefined;
433 formEncType: undefined;
434 formData: undefined;
435 json: undefined;
436 text: undefined;
437 };
438 Loading: {
439 state: "loading";
440 location: Location;
441 formMethod: Submission["formMethod"] | undefined;
442 formAction: Submission["formAction"] | undefined;
443 formEncType: Submission["formEncType"] | undefined;
444 formData: Submission["formData"] | undefined;
445 json: Submission["json"] | undefined;
446 text: Submission["text"] | undefined;
447 };
448 Submitting: {
449 state: "submitting";
450 location: Location;
451 formMethod: Submission["formMethod"];
452 formAction: Submission["formAction"];
453 formEncType: Submission["formEncType"];
454 formData: Submission["formData"];
455 json: Submission["json"];
456 text: Submission["text"];
457 };
458};
459type Navigation = NavigationStates[keyof NavigationStates];
460type RevalidationState = "idle" | "loading";
461/**
462 * Potential states for fetchers
463 */
464type FetcherStates<TData = any> = {
465 /**
466 * The fetcher is not calling a loader or action
467 *
468 * ```tsx
469 * fetcher.state === "idle"
470 * ```
471 */
472 Idle: {
473 state: "idle";
474 formMethod: undefined;
475 formAction: undefined;
476 formEncType: undefined;
477 text: undefined;
478 formData: undefined;
479 json: undefined;
480 /**
481 * If the fetcher has never been called, this will be undefined.
482 */
483 data: TData | undefined;
484 };
485 /**
486 * The fetcher is loading data from a {@link LoaderFunction | loader} from a
487 * call to {@link FetcherWithComponents.load | `fetcher.load`}.
488 *
489 * ```tsx
490 * // somewhere
491 * <button onClick={() => fetcher.load("/some/route") }>Load</button>
492 *
493 * // the state will update
494 * fetcher.state === "loading"
495 * ```
496 */
497 Loading: {
498 state: "loading";
499 formMethod: Submission["formMethod"] | undefined;
500 formAction: Submission["formAction"] | undefined;
501 formEncType: Submission["formEncType"] | undefined;
502 text: Submission["text"] | undefined;
503 formData: Submission["formData"] | undefined;
504 json: Submission["json"] | undefined;
505 data: TData | undefined;
506 };
507 /**
508 The fetcher is submitting to a {@link LoaderFunction} (GET) or {@link ActionFunction} (POST) from a {@link FetcherWithComponents.Form | `fetcher.Form`} or {@link FetcherWithComponents.submit | `fetcher.submit`}.
509
510 ```tsx
511 // somewhere
512 <input
513 onChange={e => {
514 fetcher.submit(event.currentTarget.form, { method: "post" });
515 }}
516 />
517
518 // the state will update
519 fetcher.state === "submitting"
520
521 // and formData will be available
522 fetcher.formData
523 ```
524 */
525 Submitting: {
526 state: "submitting";
527 formMethod: Submission["formMethod"];
528 formAction: Submission["formAction"];
529 formEncType: Submission["formEncType"];
530 text: Submission["text"];
531 formData: Submission["formData"];
532 json: Submission["json"];
533 data: TData | undefined;
534 };
535};
536type Fetcher<TData = any> = FetcherStates<TData>[keyof FetcherStates<TData>];
537interface BlockerBlocked {
538 state: "blocked";
539 reset: () => void;
540 proceed: () => void;
541 location: Location;
542}
543interface BlockerUnblocked {
544 state: "unblocked";
545 reset: undefined;
546 proceed: undefined;
547 location: undefined;
548}
549interface BlockerProceeding {
550 state: "proceeding";
551 reset: undefined;
552 proceed: undefined;
553 location: Location;
554}
555type Blocker = BlockerUnblocked | BlockerBlocked | BlockerProceeding;
556type BlockerFunction = (args: {
557 currentLocation: Location;
558 nextLocation: Location;
559 historyAction: Action;
560}) => boolean;
561declare const IDLE_NAVIGATION: NavigationStates["Idle"];
562declare const IDLE_FETCHER: FetcherStates["Idle"];
563declare const IDLE_BLOCKER: BlockerUnblocked;
564/**
565 * Create a router and listen to history POP navigations
566 */
567declare function createRouter(init: RouterInit): Router;
568interface CreateStaticHandlerOptions {
569 basename?: string;
570 mapRouteProperties?: MapRoutePropertiesFunction;
571 unstable_instrumentations?: Pick<unstable_ServerInstrumentation, "route">[];
572 future?: Partial<FutureConfig>;
573}
574
575type unstable_ServerInstrumentation = {
576 handler?: unstable_InstrumentRequestHandlerFunction;
577 route?: unstable_InstrumentRouteFunction;
578};
579type unstable_ClientInstrumentation = {
580 router?: unstable_InstrumentRouterFunction;
581 route?: unstable_InstrumentRouteFunction;
582};
583type unstable_InstrumentRequestHandlerFunction = (handler: InstrumentableRequestHandler) => void;
584type unstable_InstrumentRouterFunction = (router: InstrumentableRouter) => void;
585type unstable_InstrumentRouteFunction = (route: InstrumentableRoute) => void;
586type unstable_InstrumentationHandlerResult = {
587 status: "success";
588 error: undefined;
589} | {
590 status: "error";
591 error: Error;
592};
593type InstrumentFunction<T> = (handler: () => Promise<unstable_InstrumentationHandlerResult>, info: T) => Promise<void>;
594type ReadonlyRequest = {
595 method: string;
596 url: string;
597 headers: Pick<Headers, "get">;
598};
599type ReadonlyContext = MiddlewareEnabled extends true ? Pick<RouterContextProvider, "get"> : Readonly<AppLoadContext>;
600type InstrumentableRoute = {
601 id: string;
602 index: boolean | undefined;
603 path: string | undefined;
604 instrument(instrumentations: RouteInstrumentations): void;
605};
606type RouteInstrumentations = {
607 lazy?: InstrumentFunction<RouteLazyInstrumentationInfo>;
608 "lazy.loader"?: InstrumentFunction<RouteLazyInstrumentationInfo>;
609 "lazy.action"?: InstrumentFunction<RouteLazyInstrumentationInfo>;
610 "lazy.middleware"?: InstrumentFunction<RouteLazyInstrumentationInfo>;
611 middleware?: InstrumentFunction<RouteHandlerInstrumentationInfo>;
612 loader?: InstrumentFunction<RouteHandlerInstrumentationInfo>;
613 action?: InstrumentFunction<RouteHandlerInstrumentationInfo>;
614};
615type RouteLazyInstrumentationInfo = undefined;
616type RouteHandlerInstrumentationInfo = Readonly<{
617 request: ReadonlyRequest;
618 params: LoaderFunctionArgs["params"];
619 unstable_pattern: string;
620 context: ReadonlyContext;
621}>;
622type InstrumentableRouter = {
623 instrument(instrumentations: RouterInstrumentations): void;
624};
625type RouterInstrumentations = {
626 navigate?: InstrumentFunction<RouterNavigationInstrumentationInfo>;
627 fetch?: InstrumentFunction<RouterFetchInstrumentationInfo>;
628};
629type RouterNavigationInstrumentationInfo = Readonly<{
630 to: string | number;
631 currentUrl: string;
632 formMethod?: HTMLFormMethod;
633 formEncType?: FormEncType;
634 formData?: FormData;
635 body?: any;
636}>;
637type RouterFetchInstrumentationInfo = Readonly<{
638 href: string;
639 currentUrl: string;
640 fetcherKey: string;
641 formMethod?: HTMLFormMethod;
642 formEncType?: FormEncType;
643 formData?: FormData;
644 body?: any;
645}>;
646type InstrumentableRequestHandler = {
647 instrument(instrumentations: RequestHandlerInstrumentations): void;
648};
649type RequestHandlerInstrumentations = {
650 request?: InstrumentFunction<RequestHandlerInstrumentationInfo>;
651};
652type RequestHandlerInstrumentationInfo = Readonly<{
653 request: ReadonlyRequest;
654 context: ReadonlyContext | undefined;
655}>;
656
657export { type BlockerFunction as B, type CreateStaticHandlerOptions as C, type Fetcher as F, type GetScrollPositionFunction as G, type HydrationState as H, IDLE_NAVIGATION as I, type Navigation as N, type RouterInit as R, type StaticHandler as S, type Router as a, type Blocker as b, type RelativeRoutingType as c, type RouterState as d, type GetScrollRestorationKeyFunction as e, type StaticHandlerContext as f, type NavigationStates as g, type RouterSubscriber as h, type RouterNavigateOptions as i, type RouterFetchOptions as j, type RevalidationState as k, type unstable_ServerInstrumentation as l, type unstable_InstrumentRequestHandlerFunction as m, type unstable_InstrumentRouterFunction as n, type unstable_InstrumentRouteFunction as o, type unstable_InstrumentationHandlerResult as p, IDLE_FETCHER as q, IDLE_BLOCKER as r, createRouter as s, type FutureConfig as t, type unstable_ClientInstrumentation as u };