UNPKG

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