Skip to content

Commit 6b74214

Browse files
authored
chore: remove 1.52kb of optional chaining (#9248)
* chore: remove 1.52kb of optional chaining * chore: add jacob-ebey to contributors
1 parent 3557667 commit 6b74214

File tree

4 files changed

+76
-59
lines changed

4 files changed

+76
-59
lines changed

contributors.yml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -84,3 +84,4 @@
8484
- KostiantynPopovych
8585
- CanRau
8686
- dokeet
87+
- jacob-ebey

packages/router/history.ts

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -325,8 +325,8 @@ export function createBrowserHistory(
325325
"",
326326
{ pathname, search, hash },
327327
// state defaults to `null` because `window.history.state` does
328-
globalHistory.state?.usr || null,
329-
globalHistory.state?.key || "default"
328+
(globalHistory.state && globalHistory.state.usr) || null,
329+
(globalHistory.state && globalHistory.state.key) || "default"
330330
);
331331
}
332332

@@ -386,8 +386,8 @@ export function createHashHistory(
386386
"",
387387
{ pathname, search, hash },
388388
// state defaults to `null` because `window.history.state` does
389-
globalHistory.state?.usr || null,
390-
globalHistory.state?.key || "default"
389+
(globalHistory.state && globalHistory.state.usr) || null,
390+
(globalHistory.state && globalHistory.state.key) || "default"
391391
);
392392
}
393393

@@ -476,7 +476,7 @@ export function createLocation(
476476
// full Locations now and avoid the need to run through this flow at all
477477
// But that's a pretty big refactor to the current test suite so going to
478478
// keep as is for the time being and just let any incoming keys take precedence
479-
key: (to as Location)?.key || key || createKey(),
479+
key: (to && (to as Location).key) || key || createKey(),
480480
};
481481
return location;
482482
}
@@ -551,7 +551,7 @@ function getUrlBasedHistory(
551551
function push(to: To, state?: any) {
552552
action = Action.Push;
553553
let location = createLocation(history.location, to, state);
554-
validateLocation?.(location, to);
554+
if (validateLocation) validateLocation(location, to);
555555

556556
let historyState = getHistoryState(location);
557557
let url = history.createHref(location);
@@ -573,7 +573,7 @@ function getUrlBasedHistory(
573573
function replace(to: To, state?: any) {
574574
action = Action.Replace;
575575
let location = createLocation(history.location, to, state);
576-
validateLocation?.(location, to);
576+
if (validateLocation) validateLocation(location, to);
577577

578578
let historyState = getHistoryState(location);
579579
let url = history.createHref(location);

packages/router/router.ts

Lines changed: 63 additions & 49 deletions
Original file line numberDiff line numberDiff line change
@@ -555,9 +555,9 @@ export function createRouter(init: RouterInit): Router {
555555
restoreScrollPosition: null,
556556
preventScrollReset: false,
557557
revalidation: "idle",
558-
loaderData: init.hydrationData?.loaderData || {},
559-
actionData: init.hydrationData?.actionData || null,
560-
errors: init.hydrationData?.errors || initialErrors,
558+
loaderData: (init.hydrationData && init.hydrationData.loaderData) || {},
559+
actionData: (init.hydrationData && init.hydrationData.actionData) || null,
560+
errors: (init.hydrationData && init.hydrationData.errors) || initialErrors,
561561
fetchers: new Map(),
562562
};
563563

@@ -628,7 +628,7 @@ export function createRouter(init: RouterInit): Router {
628628
unlistenHistory();
629629
}
630630
subscribers.clear();
631-
pendingNavigationController?.abort();
631+
pendingNavigationController && pendingNavigationController.abort();
632632
state.fetchers.forEach((_, key) => deleteFetcher(key));
633633
}
634634

@@ -731,9 +731,9 @@ export function createRouter(init: RouterInit): Router {
731731

732732
let { path, submission, error } = normalizeNavigateOptions(to, opts);
733733

734-
let location = createLocation(state.location, path, opts?.state);
734+
let location = createLocation(state.location, path, opts && opts.state);
735735
let historyAction =
736-
opts?.replace === true || submission != null
736+
(opts && opts.replace) === true || submission != null
737737
? HistoryAction.Replace
738738
: HistoryAction.Push;
739739
let preventScrollReset =
@@ -747,7 +747,7 @@ export function createRouter(init: RouterInit): Router {
747747
// render at the right error boundary after we match routes
748748
pendingError: error,
749749
preventScrollReset,
750-
replace: opts?.replace,
750+
replace: opts && opts.replace,
751751
});
752752
}
753753

@@ -802,17 +802,18 @@ export function createRouter(init: RouterInit): Router {
802802
// Abort any in-progress navigations and start a new one. Unset any ongoing
803803
// uninterrupted revalidations unless told otherwise, since we want this
804804
// new navigation to update history normally
805-
pendingNavigationController?.abort();
805+
pendingNavigationController && pendingNavigationController.abort();
806806
pendingNavigationController = null;
807807
pendingAction = historyAction;
808-
isUninterruptedRevalidation = opts?.startUninterruptedRevalidation === true;
808+
isUninterruptedRevalidation =
809+
(opts && opts.startUninterruptedRevalidation) === true;
809810

810811
// Save the current scroll position every time we start a new navigation,
811812
// and track whether we should reset scroll on completion
812813
saveScrollPosition(state.location, state.matches);
813-
pendingPreventScrollReset = opts?.preventScrollReset === true;
814+
pendingPreventScrollReset = (opts && opts.preventScrollReset) === true;
814815

815-
let loadingNavigation = opts?.overrideNavigation;
816+
let loadingNavigation = opts && opts.overrideNavigation;
816817
let matches = matchRoutes(dataRoutes, location, init.basename);
817818

818819
// Short circuit with a 404 on the root error boundary if we match nothing
@@ -845,20 +846,20 @@ export function createRouter(init: RouterInit): Router {
845846
let request = createRequest(
846847
location,
847848
pendingNavigationController.signal,
848-
opts?.submission
849+
opts && opts.submission
849850
);
850851
let pendingActionData: RouteData | undefined;
851852
let pendingError: RouteData | undefined;
852853

853-
if (opts?.pendingError) {
854+
if (opts && opts.pendingError) {
854855
// If we have a pendingError, it means the user attempted a GET submission
855856
// with binary FormData so assign here and skip to handleLoaders. That
856857
// way we handle calling loaders above the boundary etc. It's not really
857858
// different from an actionError in that sense.
858859
pendingError = {
859860
[findNearestBoundary(matches).route.id]: opts.pendingError,
860861
};
861-
} else if (opts?.submission) {
862+
} else if (opts && opts.submission) {
862863
// Call action if we received an action submission
863864
let actionOutput = await handleAction(
864865
request,
@@ -889,8 +890,8 @@ export function createRouter(init: RouterInit): Router {
889890
location,
890891
matches,
891892
loadingNavigation,
892-
opts?.submission,
893-
opts?.replace,
893+
opts && opts.submission,
894+
opts && opts.replace,
894895
pendingActionData,
895896
pendingError
896897
);
@@ -950,7 +951,11 @@ export function createRouter(init: RouterInit): Router {
950951
location: createLocation(state.location, result.location),
951952
...submission,
952953
};
953-
await startRedirectNavigation(result, redirectNavigation, opts?.replace);
954+
await startRedirectNavigation(
955+
result,
956+
redirectNavigation,
957+
opts && opts.replace
958+
);
954959
return { shortCircuited: true };
955960
}
956961

@@ -963,7 +968,7 @@ export function createRouter(init: RouterInit): Router {
963968
// action threw an error that'll be rendered in an errorElement, we fall
964969
// back to PUSH so that the user can use the back button to get back to
965970
// the pre-submission form location to try again
966-
if (opts?.replace !== true) {
971+
if ((opts && opts.replace) !== true) {
967972
pendingAction = HistoryAction.Push;
968973
}
969974

@@ -1025,8 +1030,8 @@ export function createRouter(init: RouterInit): Router {
10251030
// already cancelled all pending deferreds so this would be a no-op
10261031
cancelActiveDeferreds(
10271032
(routeId) =>
1028-
!matches?.some((m) => m.route.id === routeId) ||
1029-
matchesToLoad?.some((m) => m.route.id === routeId)
1033+
!(matches && matches.some((m) => m.route.id === routeId)) ||
1034+
(matchesToLoad && matchesToLoad.some((m) => m.route.id === routeId))
10301035
);
10311036

10321037
// Short circuit if we have no loaders to run
@@ -1047,9 +1052,10 @@ export function createRouter(init: RouterInit): Router {
10471052
// a revalidation interrupting an actionReload)
10481053
if (!isUninterruptedRevalidation) {
10491054
revalidatingFetchers.forEach(([key]) => {
1055+
const fetcher = state.fetchers.get(key);
10501056
let revalidatingFetcher: FetcherStates["Loading"] = {
10511057
state: "loading",
1052-
data: state.fetchers.get(key)?.data,
1058+
data: fetcher && fetcher.data,
10531059
formMethod: undefined,
10541060
formAction: undefined,
10551061
formEncType: undefined,
@@ -1192,10 +1198,11 @@ export function createRouter(init: RouterInit): Router {
11921198
}
11931199

11941200
// Put this fetcher into it's submitting state
1201+
let existingFetcher = state.fetchers.get(key);
11951202
let fetcher: FetcherStates["Submitting"] = {
11961203
state: "submitting",
11971204
...submission,
1198-
data: state.fetchers.get(key)?.data || undefined,
1205+
data: existingFetcher && existingFetcher.data,
11991206
};
12001207
state.fetchers.set(key, fetcher);
12011208
updateState({ fetchers: new Map(state.fetchers) });
@@ -1289,9 +1296,10 @@ export function createRouter(init: RouterInit): Router {
12891296
revalidatingFetchers
12901297
.filter(([staleKey]) => staleKey !== key)
12911298
.forEach(([staleKey]) => {
1299+
let existingFetcher = state.fetchers.get(staleKey);
12921300
let revalidatingFetcher: FetcherStates["Loading"] = {
12931301
state: "loading",
1294-
data: state.fetchers.get(staleKey)?.data,
1302+
data: existingFetcher && existingFetcher.data,
12951303
formMethod: undefined,
12961304
formAction: undefined,
12971305
formEncType: undefined,
@@ -1360,7 +1368,7 @@ export function createRouter(init: RouterInit): Router {
13601368
loadId > pendingNavigationLoadId
13611369
) {
13621370
invariant(pendingAction, "Expected pending action");
1363-
pendingNavigationController?.abort();
1371+
pendingNavigationController && pendingNavigationController.abort();
13641372

13651373
completeNavigation(state.navigation.location, {
13661374
matches,
@@ -1388,14 +1396,15 @@ export function createRouter(init: RouterInit): Router {
13881396
path: string,
13891397
match: AgnosticDataRouteMatch
13901398
) {
1399+
let existingFetcher = state.fetchers.get(key);
13911400
// Put this fetcher into it's loading state
13921401
let loadingFetcher: FetcherStates["Loading"] = {
13931402
state: "loading",
13941403
formMethod: undefined,
13951404
formAction: undefined,
13961405
formEncType: undefined,
13971406
formData: undefined,
1398-
data: state.fetchers.get(key)?.data || undefined,
1407+
data: existingFetcher && existingFetcher.data,
13991408
};
14001409
state.fetchers.set(key, loadingFetcher);
14011410
updateState({ fetchers: new Map(state.fetchers) });
@@ -2109,7 +2118,8 @@ function normalizeNavigateOptions(
21092118
submission: {
21102119
formMethod: opts.formMethod,
21112120
formAction: createHref(parsePath(path)),
2112-
formEncType: opts?.formEncType || "application/x-www-form-urlencoded",
2121+
formEncType:
2122+
(opts && opts.formEncType) || "application/x-www-form-urlencoded",
21132123
formData: opts.formData,
21142124
},
21152125
};
@@ -2211,25 +2221,26 @@ function getMatchesToLoad(
22112221

22122222
// Pick fetcher.loads that need to be revalidated
22132223
let revalidatingFetchers: RevalidatingFetcher[] = [];
2214-
fetchLoadMatches?.forEach(([href, match], key) => {
2215-
// This fetcher was cancelled from a prior action submission - force reload
2216-
if (cancelledFetcherLoads.includes(key)) {
2217-
revalidatingFetchers.push([key, href, match]);
2218-
} else if (isRevalidationRequired) {
2219-
let shouldRevalidate = shouldRevalidateLoader(
2220-
href,
2221-
match,
2222-
submission,
2223-
href,
2224-
match,
2225-
isRevalidationRequired,
2226-
actionResult
2227-
);
2228-
if (shouldRevalidate) {
2224+
fetchLoadMatches &&
2225+
fetchLoadMatches.forEach(([href, match], key) => {
2226+
// This fetcher was cancelled from a prior action submission - force reload
2227+
if (cancelledFetcherLoads.includes(key)) {
22292228
revalidatingFetchers.push([key, href, match]);
2229+
} else if (isRevalidationRequired) {
2230+
let shouldRevalidate = shouldRevalidateLoader(
2231+
href,
2232+
match,
2233+
submission,
2234+
href,
2235+
match,
2236+
isRevalidationRequired,
2237+
actionResult
2238+
);
2239+
if (shouldRevalidate) {
2240+
revalidatingFetchers.push([key, href, match]);
2241+
}
22302242
}
2231-
}
2232-
});
2243+
});
22332244

22342245
return [navigationMatches, revalidatingFetchers];
22352246
}
@@ -2257,12 +2268,14 @@ function isNewRouteInstance(
22572268
currentMatch: AgnosticDataRouteMatch,
22582269
match: AgnosticDataRouteMatch
22592270
) {
2271+
let currentPath = currentMatch.route.path;
22602272
return (
22612273
// param change for this match, /users/123 -> /users/456
22622274
currentMatch.pathname !== match.pathname ||
22632275
// splat param changed, which is not present in match.path
22642276
// e.g. /files/images/avatar.jpg -> files/finances.xls
2265-
(currentMatch.route.path?.endsWith("*") &&
2277+
(currentPath &&
2278+
currentPath.endsWith("*") &&
22662279
currentMatch.params["*"] !== match.params["*"])
22672280
);
22682281
}
@@ -2375,7 +2388,8 @@ async function callLoaderOrAction(
23752388
}
23762389

23772390
let data: any;
2378-
if (result.headers.get("Content-Type")?.startsWith("application/json")) {
2391+
let contentType = result.headers.get("Content-Type");
2392+
if (contentType && contentType.startsWith("application/json")) {
23792393
data = await result.json();
23802394
} else {
23812395
data = await result.text();
@@ -2497,7 +2511,7 @@ function processRouteLoaderData(
24972511
loaderHeaders[id] = result.headers;
24982512
}
24992513
} else if (isDeferredResult(result)) {
2500-
activeDeferreds?.set(id, result.deferredData);
2514+
activeDeferreds && activeDeferreds.set(id, result.deferredData);
25012515
loaderData[id] = result.deferredData.data;
25022516
// TODO: Add statusCode/headers once we wire up streaming in Remix
25032517
} else {
@@ -2560,7 +2574,7 @@ function processLoaderData(
25602574
// Process fetcher non-redirect errors
25612575
if (isErrorResult(result)) {
25622576
let boundaryMatch = findNearestBoundary(state.matches, match.route.id);
2563-
if (!errors?.[boundaryMatch.route.id]) {
2577+
if (!(errors && errors[boundaryMatch.route.id])) {
25642578
errors = {
25652579
...errors,
25662580
[boundaryMatch.route.id]: result.error,
@@ -2695,7 +2709,7 @@ function isErrorResult(result: DataResult): result is ErrorResult {
26952709
}
26962710

26972711
function isRedirectResult(result?: DataResult): result is RedirectResult {
2698-
return result?.type === ResultType.redirect;
2712+
return (result && result.type) === ResultType.redirect;
26992713
}
27002714

27012715
async function resolveDeferredResults(
@@ -2715,7 +2729,7 @@ async function resolveDeferredResults(
27152729
let isRevalidatingLoader =
27162730
currentMatch != null &&
27172731
!isNewRouteInstance(currentMatch, match) &&
2718-
currentLoaderData?.[match.route.id] !== undefined;
2732+
(currentLoaderData && currentLoaderData[match.route.id]) !== undefined;
27192733

27202734
if (isDeferredResult(result) && (isFetcher || isRevalidatingLoader)) {
27212735
// Note: we do not have to touch activeDeferreds here since we race them

packages/router/utils.ts

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -986,14 +986,15 @@ export class DeferredData {
986986
this.unlistenAbortSignal();
987987
}
988988

989+
const subscriber = this.subscriber;
989990
if (error) {
990991
Object.defineProperty(promise, "_error", { get: () => error });
991-
this.subscriber?.(false);
992+
subscriber && subscriber(false);
992993
return Promise.reject(error);
993994
}
994995

995996
Object.defineProperty(promise, "_data", { get: () => data });
996-
this.subscriber?.(false);
997+
subscriber && subscriber(false);
997998
return data;
998999
}
9991000

@@ -1004,7 +1005,8 @@ export class DeferredData {
10041005
cancel() {
10051006
this.controller.abort();
10061007
this.pendingKeys.forEach((v, k) => this.pendingKeys.delete(k));
1007-
this.subscriber?.(true);
1008+
let subscriber = this.subscriber;
1009+
subscriber && subscriber(true);
10081010
}
10091011

10101012
async resolveData(signal: AbortSignal) {

0 commit comments

Comments
 (0)