-
-
Notifications
You must be signed in to change notification settings - Fork 10.4k
/
router.ts
4229 lines (3807 loc) · 128 KB
/
router.ts
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
import type { History, Location, Path, To } from "./history";
import {
Action as HistoryAction,
createLocation,
createPath,
invariant,
parsePath,
warning,
} from "./history";
import type {
DataResult,
DeferredData,
AgnosticDataRouteMatch,
AgnosticDataRouteObject,
DeferredResult,
ErrorResult,
FormEncType,
FormMethod,
DetectErrorBoundaryFunction,
RedirectResult,
RouteData,
AgnosticRouteObject,
Submission,
SuccessResult,
AgnosticRouteMatch,
ShouldRevalidateFunction,
RouteManifest,
ImmutableRouteKey,
ActionFunction,
LoaderFunction,
V7_MutationFormMethod,
V7_FormMethod,
HTMLFormMethod,
MutationFormMethod,
MapRoutePropertiesFunction,
} from "./utils";
import {
ErrorResponse,
ResultType,
convertRoutesToDataRoutes,
getPathContributingMatches,
immutableRouteKeys,
isRouteErrorResponse,
joinPaths,
matchRoutes,
resolveTo,
stripBasename,
} from "./utils";
////////////////////////////////////////////////////////////////////////////////
//#region Types and Constants
////////////////////////////////////////////////////////////////////////////////
/**
* A Router instance manages all navigation and data loading/mutations
*/
export interface Router {
/**
* @internal
* PRIVATE - DO NOT USE
*
* Return the basename for the router
*/
get basename(): RouterInit["basename"];
/**
* @internal
* PRIVATE - DO NOT USE
*
* Return the current state of the router
*/
get state(): RouterState;
/**
* @internal
* PRIVATE - DO NOT USE
*
* Return the routes for this router instance
*/
get routes(): AgnosticDataRouteObject[];
/**
* @internal
* PRIVATE - DO NOT USE
*
* Initialize the router, including adding history listeners and kicking off
* initial data fetches. Returns a function to cleanup listeners and abort
* any in-progress loads
*/
initialize(): Router;
/**
* @internal
* PRIVATE - DO NOT USE
*
* Subscribe to router.state updates
*
* @param fn function to call with the new state
*/
subscribe(fn: RouterSubscriber): () => void;
/**
* @internal
* PRIVATE - DO NOT USE
*
* Enable scroll restoration behavior in the router
*
* @param savedScrollPositions Object that will manage positions, in case
* it's being restored from sessionStorage
* @param getScrollPosition Function to get the active Y scroll position
* @param getKey Function to get the key to use for restoration
*/
enableScrollRestoration(
savedScrollPositions: Record<string, number>,
getScrollPosition: GetScrollPositionFunction,
getKey?: GetScrollRestorationKeyFunction
): () => void;
/**
* @internal
* PRIVATE - DO NOT USE
*
* Navigate forward/backward in the history stack
* @param to Delta to move in the history stack
*/
navigate(to: number): Promise<void>;
/**
* Navigate to the given path
* @param to Path to navigate to
* @param opts Navigation options (method, submission, etc.)
*/
navigate(to: To | null, opts?: RouterNavigateOptions): Promise<void>;
/**
* @internal
* PRIVATE - DO NOT USE
*
* Trigger a fetcher load/submission
*
* @param key Fetcher key
* @param routeId Route that owns the fetcher
* @param href href to fetch
* @param opts Fetcher options, (method, submission, etc.)
*/
fetch(
key: string,
routeId: string,
href: string | null,
opts?: RouterNavigateOptions
): void;
/**
* @internal
* PRIVATE - DO NOT USE
*
* Trigger a revalidation of all current route loaders and fetcher loads
*/
revalidate(): void;
/**
* @internal
* PRIVATE - DO NOT USE
*
* Utility function to create an href for the given location
* @param location
*/
createHref(location: Location | URL): string;
/**
* @internal
* PRIVATE - DO NOT USE
*
* Utility function to URL encode a destination path according to the internal
* history implementation
* @param to
*/
encodeLocation(to: To): Path;
/**
* @internal
* PRIVATE - DO NOT USE
*
* Get/create a fetcher for the given key
* @param key
*/
getFetcher<TData = any>(key?: string): Fetcher<TData>;
/**
* @internal
* PRIVATE - DO NOT USE
*
* Delete the fetcher for a given key
* @param key
*/
deleteFetcher(key?: string): void;
/**
* @internal
* PRIVATE - DO NOT USE
*
* Cleanup listeners and abort any in-progress loads
*/
dispose(): void;
/**
* @internal
* PRIVATE - DO NOT USE
*
* Get a navigation blocker
* @param key The identifier for the blocker
* @param fn The blocker function implementation
*/
getBlocker(key: string, fn: BlockerFunction): Blocker;
/**
* @internal
* PRIVATE - DO NOT USE
*
* Delete a navigation blocker
* @param key The identifier for the blocker
*/
deleteBlocker(key: string): void;
/**
* @internal
* PRIVATE - DO NOT USE
*
* HMR needs to pass in-flight route updates to React Router
* TODO: Replace this with granular route update APIs (addRoute, updateRoute, deleteRoute)
*/
_internalSetRoutes(routes: AgnosticRouteObject[]): void;
/**
* @internal
* PRIVATE - DO NOT USE
*
* Internal fetch AbortControllers accessed by unit tests
*/
_internalFetchControllers: Map<string, AbortController>;
/**
* @internal
* PRIVATE - DO NOT USE
*
* Internal pending DeferredData instances accessed by unit tests
*/
_internalActiveDeferreds: Map<string, DeferredData>;
}
/**
* State maintained internally by the router. During a navigation, all states
* reflect the the "old" location unless otherwise noted.
*/
export interface RouterState {
/**
* The action of the most recent navigation
*/
historyAction: HistoryAction;
/**
* The current location reflected by the router
*/
location: Location;
/**
* The current set of route matches
*/
matches: AgnosticDataRouteMatch[];
/**
* Tracks whether we've completed our initial data load
*/
initialized: boolean;
/**
* Current scroll position we should start at for a new view
* - number -> scroll position to restore to
* - false -> do not restore scroll at all (used during submissions)
* - null -> don't have a saved position, scroll to hash or top of page
*/
restoreScrollPosition: number | false | null;
/**
* Indicate whether this navigation should skip resetting the scroll position
* if we are unable to restore the scroll position
*/
preventScrollReset: boolean;
/**
* Tracks the state of the current navigation
*/
navigation: Navigation;
/**
* Tracks any in-progress revalidations
*/
revalidation: RevalidationState;
/**
* Data from the loaders for the current matches
*/
loaderData: RouteData;
/**
* Data from the action for the current matches
*/
actionData: RouteData | null;
/**
* Errors caught from loaders for the current matches
*/
errors: RouteData | null;
/**
* Map of current fetchers
*/
fetchers: Map<string, Fetcher>;
/**
* Map of current blockers
*/
blockers: Map<string, Blocker>;
}
/**
* Data that can be passed into hydrate a Router from SSR
*/
export type HydrationState = Partial<
Pick<RouterState, "loaderData" | "actionData" | "errors">
>;
/**
* Future flags to toggle new feature behavior
*/
export interface FutureConfig {
v7_normalizeFormMethod: boolean;
v7_prependBasename: boolean;
}
/**
* Initialization options for createRouter
*/
export interface RouterInit {
routes: AgnosticRouteObject[];
history: History;
basename?: string;
/**
* @deprecated Use `mapRouteProperties` instead
*/
detectErrorBoundary?: DetectErrorBoundaryFunction;
mapRouteProperties?: MapRoutePropertiesFunction;
future?: Partial<FutureConfig>;
hydrationData?: HydrationState;
window?: Window;
}
/**
* State returned from a server-side query() call
*/
export interface StaticHandlerContext {
basename: Router["basename"];
location: RouterState["location"];
matches: RouterState["matches"];
loaderData: RouterState["loaderData"];
actionData: RouterState["actionData"];
errors: RouterState["errors"];
statusCode: number;
loaderHeaders: Record<string, Headers>;
actionHeaders: Record<string, Headers>;
activeDeferreds: Record<string, DeferredData> | null;
_deepestRenderedBoundaryId?: string | null;
}
/**
* A StaticHandler instance manages a singular SSR navigation/fetch event
*/
export interface StaticHandler {
dataRoutes: AgnosticDataRouteObject[];
query(
request: Request,
opts?: { requestContext?: unknown }
): Promise<StaticHandlerContext | Response>;
queryRoute(
request: Request,
opts?: { routeId?: string; requestContext?: unknown }
): Promise<any>;
}
/**
* Subscriber function signature for changes to router state
*/
export interface RouterSubscriber {
(state: RouterState): void;
}
interface UseMatchesMatch {
id: string;
pathname: string;
params: AgnosticRouteMatch["params"];
data: unknown;
handle: unknown;
}
/**
* Function signature for determining the key to be used in scroll restoration
* for a given location
*/
export interface GetScrollRestorationKeyFunction {
(location: Location, matches: UseMatchesMatch[]): string | null;
}
/**
* Function signature for determining the current scroll position
*/
export interface GetScrollPositionFunction {
(): number;
}
export type RelativeRoutingType = "route" | "path";
type BaseNavigateOptions = {
replace?: boolean;
state?: any;
preventScrollReset?: boolean;
relative?: RelativeRoutingType;
fromRouteId?: string;
};
/**
* Options for a navigate() call for a Link navigation
*/
type LinkNavigateOptions = BaseNavigateOptions;
/**
* Options for a navigate() call for a Form navigation
*/
type SubmissionNavigateOptions = BaseNavigateOptions & {
formMethod?: HTMLFormMethod;
formEncType?: FormEncType;
formData: FormData;
};
/**
* Options to pass to navigate() for either a Link or Form navigation
*/
export type RouterNavigateOptions =
| LinkNavigateOptions
| SubmissionNavigateOptions;
/**
* Options to pass to fetch()
*/
export type RouterFetchOptions =
| Omit<LinkNavigateOptions, "replace">
| Omit<SubmissionNavigateOptions, "replace">;
/**
* Potential states for state.navigation
*/
export type NavigationStates = {
Idle: {
state: "idle";
location: undefined;
formMethod: undefined;
formAction: undefined;
formEncType: undefined;
formData: undefined;
};
Loading: {
state: "loading";
location: Location;
formMethod: FormMethod | V7_FormMethod | undefined;
formAction: string | undefined;
formEncType: FormEncType | undefined;
formData: FormData | undefined;
};
Submitting: {
state: "submitting";
location: Location;
formMethod: FormMethod | V7_FormMethod;
formAction: string;
formEncType: FormEncType;
formData: FormData;
};
};
export type Navigation = NavigationStates[keyof NavigationStates];
export type RevalidationState = "idle" | "loading";
/**
* Potential states for fetchers
*/
type FetcherStates<TData = any> = {
Idle: {
state: "idle";
formMethod: undefined;
formAction: undefined;
formEncType: undefined;
formData: undefined;
data: TData | undefined;
" _hasFetcherDoneAnything "?: boolean;
};
Loading: {
state: "loading";
formMethod: FormMethod | V7_FormMethod | undefined;
formAction: string | undefined;
formEncType: FormEncType | undefined;
formData: FormData | undefined;
data: TData | undefined;
" _hasFetcherDoneAnything "?: boolean;
};
Submitting: {
state: "submitting";
formMethod: FormMethod | V7_FormMethod;
formAction: string;
formEncType: FormEncType;
formData: FormData;
data: TData | undefined;
" _hasFetcherDoneAnything "?: boolean;
};
};
export type Fetcher<TData = any> =
FetcherStates<TData>[keyof FetcherStates<TData>];
interface BlockerBlocked {
state: "blocked";
reset(): void;
proceed(): void;
location: Location;
}
interface BlockerUnblocked {
state: "unblocked";
reset: undefined;
proceed: undefined;
location: undefined;
}
interface BlockerProceeding {
state: "proceeding";
reset: undefined;
proceed: undefined;
location: Location;
}
export type Blocker = BlockerUnblocked | BlockerBlocked | BlockerProceeding;
export type BlockerFunction = (args: {
currentLocation: Location;
nextLocation: Location;
historyAction: HistoryAction;
}) => boolean;
interface ShortCircuitable {
/**
* startNavigation does not need to complete the navigation because we
* redirected or got interrupted
*/
shortCircuited?: boolean;
}
interface HandleActionResult extends ShortCircuitable {
/**
* Error thrown from the current action, keyed by the route containing the
* error boundary to render the error. To be committed to the state after
* loaders have completed
*/
pendingActionError?: RouteData;
/**
* Data returned from the current action, keyed by the route owning the action.
* To be committed to the state after loaders have completed
*/
pendingActionData?: RouteData;
}
interface HandleLoadersResult extends ShortCircuitable {
/**
* loaderData returned from the current set of loaders
*/
loaderData?: RouterState["loaderData"];
/**
* errors thrown from the current set of loaders
*/
errors?: RouterState["errors"];
}
/**
* Cached info for active fetcher.load() instances so they can participate
* in revalidation
*/
interface FetchLoadMatch {
routeId: string;
path: string;
}
/**
* Identified fetcher.load() calls that need to be revalidated
*/
interface RevalidatingFetcher extends FetchLoadMatch {
key: string;
match: AgnosticDataRouteMatch | null;
matches: AgnosticDataRouteMatch[] | null;
controller: AbortController | null;
}
/**
* Wrapper object to allow us to throw any response out from callLoaderOrAction
* for queryRouter while preserving whether or not it was thrown or returned
* from the loader/action
*/
interface QueryRouteResponse {
type: ResultType.data | ResultType.error;
response: Response;
}
const validMutationMethodsArr: MutationFormMethod[] = [
"post",
"put",
"patch",
"delete",
];
const validMutationMethods = new Set<MutationFormMethod>(
validMutationMethodsArr
);
const validRequestMethodsArr: FormMethod[] = [
"get",
...validMutationMethodsArr,
];
const validRequestMethods = new Set<FormMethod>(validRequestMethodsArr);
const redirectStatusCodes = new Set([301, 302, 303, 307, 308]);
const redirectPreserveMethodStatusCodes = new Set([307, 308]);
export const IDLE_NAVIGATION: NavigationStates["Idle"] = {
state: "idle",
location: undefined,
formMethod: undefined,
formAction: undefined,
formEncType: undefined,
formData: undefined,
};
export const IDLE_FETCHER: FetcherStates["Idle"] = {
state: "idle",
data: undefined,
formMethod: undefined,
formAction: undefined,
formEncType: undefined,
formData: undefined,
};
export const IDLE_BLOCKER: BlockerUnblocked = {
state: "unblocked",
proceed: undefined,
reset: undefined,
location: undefined,
};
const ABSOLUTE_URL_REGEX = /^(?:[a-z][a-z0-9+.-]*:|\/\/)/i;
const defaultMapRouteProperties: MapRoutePropertiesFunction = (route) => ({
hasErrorBoundary: Boolean(route.hasErrorBoundary),
});
//#endregion
////////////////////////////////////////////////////////////////////////////////
//#region createRouter
////////////////////////////////////////////////////////////////////////////////
/**
* Create a router and listen to history POP navigations
*/
export function createRouter(init: RouterInit): Router {
const routerWindow = init.window
? init.window
: typeof window !== "undefined"
? window
: undefined;
const isBrowser =
typeof routerWindow !== "undefined" &&
typeof routerWindow.document !== "undefined" &&
typeof routerWindow.document.createElement !== "undefined";
const isServer = !isBrowser;
invariant(
init.routes.length > 0,
"You must provide a non-empty routes array to createRouter"
);
let mapRouteProperties: MapRoutePropertiesFunction;
if (init.mapRouteProperties) {
mapRouteProperties = init.mapRouteProperties;
} else if (init.detectErrorBoundary) {
// If they are still using the deprecated version, wrap it with the new API
let detectErrorBoundary = init.detectErrorBoundary;
mapRouteProperties = (route) => ({
hasErrorBoundary: detectErrorBoundary(route),
});
} else {
mapRouteProperties = defaultMapRouteProperties;
}
// Routes keyed by ID
let manifest: RouteManifest = {};
// Routes in tree format for matching
let dataRoutes = convertRoutesToDataRoutes(
init.routes,
mapRouteProperties,
undefined,
manifest
);
let inFlightDataRoutes: AgnosticDataRouteObject[] | undefined;
let basename = init.basename || "/";
// Config driven behavior flags
let future: FutureConfig = {
v7_normalizeFormMethod: false,
v7_prependBasename: false,
...init.future,
};
// Cleanup function for history
let unlistenHistory: (() => void) | null = null;
// Externally-provided functions to call on all state changes
let subscribers = new Set<RouterSubscriber>();
// Externally-provided object to hold scroll restoration locations during routing
let savedScrollPositions: Record<string, number> | null = null;
// Externally-provided function to get scroll restoration keys
let getScrollRestorationKey: GetScrollRestorationKeyFunction | null = null;
// Externally-provided function to get current scroll position
let getScrollPosition: GetScrollPositionFunction | null = null;
// One-time flag to control the initial hydration scroll restoration. Because
// we don't get the saved positions from <ScrollRestoration /> until _after_
// the initial render, we need to manually trigger a separate updateState to
// send along the restoreScrollPosition
// Set to true if we have `hydrationData` since we assume we were SSR'd and that
// SSR did the initial scroll restoration.
let initialScrollRestored = init.hydrationData != null;
let initialMatches = matchRoutes(dataRoutes, init.history.location, basename);
let initialErrors: RouteData | null = null;
if (initialMatches == null) {
// If we do not match a user-provided-route, fall back to the root
// to allow the error boundary to take over
let error = getInternalRouterError(404, {
pathname: init.history.location.pathname,
});
let { matches, route } = getShortCircuitMatches(dataRoutes);
initialMatches = matches;
initialErrors = { [route.id]: error };
}
let initialized =
// All initialMatches need to be loaded before we're ready. If we have lazy
// functions around still then we'll need to run them in initialize()
!initialMatches.some((m) => m.route.lazy) &&
// And we have to either have no loaders or have been provided hydrationData
(!initialMatches.some((m) => m.route.loader) || init.hydrationData != null);
let router: Router;
let state: RouterState = {
historyAction: init.history.action,
location: init.history.location,
matches: initialMatches,
initialized,
navigation: IDLE_NAVIGATION,
// Don't restore on initial updateState() if we were SSR'd
restoreScrollPosition: init.hydrationData != null ? false : null,
preventScrollReset: false,
revalidation: "idle",
loaderData: (init.hydrationData && init.hydrationData.loaderData) || {},
actionData: (init.hydrationData && init.hydrationData.actionData) || null,
errors: (init.hydrationData && init.hydrationData.errors) || initialErrors,
fetchers: new Map(),
blockers: new Map(),
};
// -- Stateful internal variables to manage navigations --
// Current navigation in progress (to be committed in completeNavigation)
let pendingAction: HistoryAction = HistoryAction.Pop;
// Should the current navigation prevent the scroll reset if scroll cannot
// be restored?
let pendingPreventScrollReset = false;
// AbortController for the active navigation
let pendingNavigationController: AbortController | null;
// We use this to avoid touching history in completeNavigation if a
// revalidation is entirely uninterrupted
let isUninterruptedRevalidation = false;
// Use this internal flag to force revalidation of all loaders:
// - submissions (completed or interrupted)
// - useRevalidator()
// - X-Remix-Revalidate (from redirect)
let isRevalidationRequired = false;
// Use this internal array to capture routes that require revalidation due
// to a cancelled deferred on action submission
let cancelledDeferredRoutes: string[] = [];
// Use this internal array to capture fetcher loads that were cancelled by an
// action navigation and require revalidation
let cancelledFetcherLoads: string[] = [];
// AbortControllers for any in-flight fetchers
let fetchControllers = new Map<string, AbortController>();
// Track loads based on the order in which they started
let incrementingLoadId = 0;
// Track the outstanding pending navigation data load to be compared against
// the globally incrementing load when a fetcher load lands after a completed
// navigation
let pendingNavigationLoadId = -1;
// Fetchers that triggered data reloads as a result of their actions
let fetchReloadIds = new Map<string, number>();
// Fetchers that triggered redirect navigations
let fetchRedirectIds = new Set<string>();
// Most recent href/match for fetcher.load calls for fetchers
let fetchLoadMatches = new Map<string, FetchLoadMatch>();
// Store DeferredData instances for active route matches. When a
// route loader returns defer() we stick one in here. Then, when a nested
// promise resolves we update loaderData. If a new navigation starts we
// cancel active deferreds for eliminated routes.
let activeDeferreds = new Map<string, DeferredData>();
// Store blocker functions in a separate Map outside of router state since
// we don't need to update UI state if they change
let blockerFunctions = new Map<string, BlockerFunction>();
// Flag to ignore the next history update, so we can revert the URL change on
// a POP navigation that was blocked by the user without touching router state
let ignoreNextHistoryUpdate = false;
// Initialize the router, all side effects should be kicked off from here.
// Implemented as a Fluent API for ease of:
// let router = createRouter(init).initialize();
function initialize() {
// If history informs us of a POP navigation, start the navigation but do not update
// state. We'll update our own state once the navigation completes
unlistenHistory = init.history.listen(
({ action: historyAction, location, delta }) => {
// Ignore this event if it was just us resetting the URL from a
// blocked POP navigation
if (ignoreNextHistoryUpdate) {
ignoreNextHistoryUpdate = false;
return;
}
warning(
blockerFunctions.size === 0 || delta != null,
"You are trying to use a blocker on a POP navigation to a location " +
"that was not created by @remix-run/router. This will fail silently in " +
"production. This can happen if you are navigating outside the router " +
"via `window.history.pushState`/`window.location.hash` instead of using " +
"router navigation APIs. This can also happen if you are using " +
"createHashRouter and the user manually changes the URL."
);
let blockerKey = shouldBlockNavigation({
currentLocation: state.location,
nextLocation: location,
historyAction,
});
if (blockerKey && delta != null) {
// Restore the URL to match the current UI, but don't update router state
ignoreNextHistoryUpdate = true;
init.history.go(delta * -1);
// Put the blocker into a blocked state
updateBlocker(blockerKey, {
state: "blocked",
location,
proceed() {
updateBlocker(blockerKey!, {
state: "proceeding",
proceed: undefined,
reset: undefined,
location,
});
// Re-do the same POP navigation we just blocked
init.history.go(delta);
},
reset() {
deleteBlocker(blockerKey!);
updateState({ blockers: new Map(router.state.blockers) });
},
});
return;
}
return startNavigation(historyAction, location);
}
);
// Kick off initial data load if needed. Use Pop to avoid modifying history
// Note we don't do any handling of lazy here. For SPA's it'll get handled
// in the normal navigation flow. For SSR it's expected that lazy modules are
// resolved prior to router creation since we can't go into a fallbackElement
// UI for SSR'd apps
if (!state.initialized) {
startNavigation(HistoryAction.Pop, state.location);
}
return router;
}
// Clean up a router and it's side effects
function dispose() {
if (unlistenHistory) {
unlistenHistory();
}
subscribers.clear();
pendingNavigationController && pendingNavigationController.abort();
state.fetchers.forEach((_, key) => deleteFetcher(key));
state.blockers.forEach((_, key) => deleteBlocker(key));
}
// Subscribe to state updates for the router
function subscribe(fn: RouterSubscriber) {
subscribers.add(fn);
return () => subscribers.delete(fn);
}
// Update our state and notify the calling context of the change
function updateState(newState: Partial<RouterState>): void {
state = {
...state,
...newState,
};
subscribers.forEach((subscriber) => subscriber(state));
}
// Complete a navigation returning the state.navigation back to the IDLE_NAVIGATION
// and setting state.[historyAction/location/matches] to the new route.
// - Location is a required param
// - Navigation will always be set to IDLE_NAVIGATION
// - Can pass any other state in newState
function completeNavigation(
location: Location,
newState: Partial<Omit<RouterState, "action" | "location" | "navigation">>
): void {
// Deduce if we're in a loading/actionReload state:
// - We have committed actionData in the store
// - The current navigation was a mutation submission
// - We're past the submitting state and into the loading state
// - The location being loaded is not the result of a redirect
let isActionReload =
state.actionData != null &&
state.navigation.formMethod != null &&
isMutationMethod(state.navigation.formMethod) &&
state.navigation.state === "loading" &&
location.state?._isRedirect !== true;
let actionData: RouteData | null;
if (newState.actionData) {
if (Object.keys(newState.actionData).length > 0) {
actionData = newState.actionData;
} else {
// Empty actionData -> clear prior actionData due to an action error
actionData = null;
}
} else if (isActionReload) {
// Keep the current data if we're wrapping up the action reload
actionData = state.actionData;
} else {
// Clear actionData on any other completed navigations
actionData = null;
}
// Always preserve any existing loaderData from re-used routes
let loaderData = newState.loaderData
? mergeLoaderData(
state.loaderData,
newState.loaderData,
newState.matches || [],
newState.errors
)
: state.loaderData;
// On a successful navigation we can assume we got through all blockers
// so we can start fresh
for (let [key] of blockerFunctions) {
deleteBlocker(key);
}
// Always respect the user flag. Otherwise don't reset on mutation
// submission navigations unless they redirect
let preventScrollReset =