Skip to content

Commit

Permalink
Fix all lint and typecheck issues
Browse files Browse the repository at this point in the history
  • Loading branch information
ShridharGoel committed Aug 26, 2024
1 parent b86d968 commit 9aaf7c0
Show file tree
Hide file tree
Showing 123 changed files with 654 additions and 422 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ function partitionWithChecklist(body: string): string[] {
async function getNumberOfItemsFromAuthorChecklist(): Promise<number> {
const response = await fetch(pathToAuthorChecklist);
const fileContents = await response.text();
const checklist = partitionWithChecklist(fileContents).at(1);
const checklist = partitionWithChecklist(fileContents).at(1) ?? '';
const numberOfChecklistItems = (checklist.match(/\[ \]/g) ?? []).length;
return numberOfChecklistItems;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,11 @@ async function run(): Promise<IssuesCreateResponse | void> {
// Look at the state of the most recent StagingDeployCash,
// if it is open then we'll update the existing one, otherwise, we'll create a new one.
const mostRecentChecklist = recentDeployChecklists.at(0);

if (!mostRecentChecklist) {
return;
}

const shouldCreateNewDeployChecklist = mostRecentChecklist.state !== 'open';
const previousChecklist = shouldCreateNewDeployChecklist ? mostRecentChecklist : recentDeployChecklists.at(1);
if (shouldCreateNewDeployChecklist) {
Expand All @@ -38,6 +43,10 @@ async function run(): Promise<IssuesCreateResponse | void> {
console.log('Latest StagingDeployCash is open, updating it instead of creating a new one.', 'Current:', mostRecentChecklist, 'Previous:', previousChecklist);
}

if (!previousChecklist) {
return;
}

// Parse the data from the previous and current checklists into the format used to generate the checklist
const previousChecklistData = GithubUtils.getStagingDeployCashData(previousChecklist);
const currentChecklistData: StagingDeployCashData | undefined = shouldCreateNewDeployChecklist ? undefined : GithubUtils.getStagingDeployCashData(mostRecentChecklist);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ async function run() {
labels: CONST.LABELS.STAGING_DEPLOY,
state: 'closed',
});
const previousChecklistID = deployChecklists.at(0).number;
const previousChecklistID = deployChecklists.at(0)?.number ?? 0;

// who closed the last deploy checklist?
const deployer = await GithubUtils.getActorWhoClosedIssue(previousChecklistID);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -55,16 +55,16 @@ function checkIssueForCompletedChecklist(numberOfChecklistItems: number) {
}

const whitespace = /([\n\r])/gm;
const comment = combinedComments.at(i).replace(whitespace, '');
const comment = combinedComments.at(i)?.replace(whitespace, '');

console.log(`Comment ${i} starts with: ${comment.slice(0, 20)}...`);
console.log(`Comment ${i} starts with: ${comment?.slice(0, 20)}...`);

// Found the reviewer checklist, so count how many completed checklist items there are
if (comment.indexOf(reviewerChecklistContains) !== -1) {
if (comment?.indexOf(reviewerChecklistContains) !== -1) {
console.log('Found the reviewer checklist!');
foundReviewerChecklist = true;
numberOfFinishedChecklistItems = (comment.match(/- \[x\]/gi) ?? []).length;
numberOfUnfinishedChecklistItems = (comment.match(/- \[ \]/g) ?? []).length;
numberOfFinishedChecklistItems = (comment?.match(/- \[x\]/gi) ?? []).length;
numberOfUnfinishedChecklistItems = (comment?.match(/- \[ \]/g) ?? []).length;
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,11 @@ const run = (): boolean => {

for (let i = 0; i < regressionOutput.countChanged.length; i++) {
const measurement = regressionOutput.countChanged.at(i);

if (!measurement) {
continue;
}

const baseline: PerformanceEntry = measurement.baseline;
const current: PerformanceEntry = measurement.current;

Expand Down
12 changes: 9 additions & 3 deletions .github/libs/GithubUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -168,7 +168,13 @@ class GithubUtils {
throw new Error(`Found more than one ${CONST.LABELS.STAGING_DEPLOY} issue.`);
}

return this.getStagingDeployCashData(data.at(0));
const issue = data.at(0);

if (!issue) {
throw new Error(`Found an undefined ${CONST.LABELS.STAGING_DEPLOY} issue.`);
}

return this.getStagingDeployCashData(issue);
});
}

Expand Down Expand Up @@ -254,7 +260,7 @@ class GithubUtils {
}
internalQASection = internalQASection[1];
const internalQAPRs = [...internalQASection.matchAll(new RegExp(`- \\[([ x])]\\s(${CONST.PULL_REQUEST_REGEX.source})`, 'g'))].map((match) => ({
url: match[2].split('-').at(0).trim(),
url: match[2].split('-').at(0)?.trim() ?? '',
number: Number.parseInt(match[3], 10),
isResolved: match[1] === 'x',
}));
Expand Down Expand Up @@ -459,7 +465,7 @@ class GithubUtils {
repo: CONST.APP_REPO,
workflow_id: workflow,
})
.then((response) => response.data.workflow_runs.at(0)?.id);
.then((response) => response.data.workflow_runs.at(0)?.id ?? -1);
}

/**
Expand Down
2 changes: 1 addition & 1 deletion .github/scripts/createDocsRoutes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ function pushOrCreateEntry<TKey extends HubEntriesKey>(hubs: Hub[], hub: string,

function getOrderFromArticleFrontMatter(path: string): number | undefined {
const frontmatter = fs.readFileSync(path, 'utf8').split('---').at(1);
const frontmatterObject = yaml.load(frontmatter) as Record<string, unknown>;
const frontmatterObject = yaml.load(frontmatter ?? '') as Record<string, unknown>;
return frontmatterObject.order as number | undefined;
}

Expand Down
2 changes: 1 addition & 1 deletion jest/setup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ jest.mock('react-native/Libraries/LogBox/LogBox', () => ({

// Turn off the console logs for timing events. They are not relevant for unit tests and create a lot of noise
jest.spyOn(console, 'debug').mockImplementation((...params: string[]) => {
if (params.at(0).startsWith('Timing:')) {
if (params.at(0)?.startsWith('Timing:')) {
return;
}

Expand Down
7 changes: 5 additions & 2 deletions src/components/AttachmentPicker/index.native.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -366,8 +366,11 @@ function AttachmentPicker({type = CONST.ATTACHMENT_PICKER_TYPE.FILE, children, s
if (focusedIndex === -1) {
return;
}
selectItem(menuItemData.at(focusedIndex));
setFocusedIndex(-1); // Reset the focusedIndex on selecting any menu
const item = menuItemData.at(focusedIndex);
if (item) {
selectItem(item);
setFocusedIndex(-1); // Reset the focusedIndex on selecting any menu
}
},
{
isActive: isVisible,
Expand Down
12 changes: 8 additions & 4 deletions src/components/Attachments/AttachmentCarousel/index.native.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -52,9 +52,11 @@ function AttachmentCarousel({report, reportActions, parentReportActions, source,
setDownloadButtonVisibility(initialPage !== -1);
}

const attachment = targetAttachments.at(initialPage);

// Update the parent modal's state with the source and name from the mapped attachments
if (targetAttachments.at(initialPage) !== undefined && onNavigate) {
onNavigate(targetAttachments.at(initialPage));
if (attachment !== undefined && onNavigate) {
onNavigate(attachment);
}
}
// eslint-disable-next-line react-compiler/react-compiler, react-hooks/exhaustive-deps
Expand All @@ -69,9 +71,11 @@ function AttachmentCarousel({report, reportActions, parentReportActions, source,
const item = attachments.at(newPageIndex);

setPage(newPageIndex);
setActiveSource(item.source);
if (item) {
setActiveSource(item.source);
}

if (onNavigate) {
if (onNavigate && item) {
onNavigate(item);
}
},
Expand Down
5 changes: 3 additions & 2 deletions src/components/Attachments/AttachmentCarousel/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -100,9 +100,10 @@ function AttachmentCarousel({report, reportActions, parentReportActions, source,
setDownloadButtonVisibility(initialPage !== -1);
}

const attachment = targetAttachments.at(initialPage);
// Update the parent modal's state with the source and name from the mapped attachments
if (targetAttachments.at(initialPage) !== undefined && onNavigate) {
onNavigate(targetAttachments.at(initialPage));
if (attachment !== undefined && onNavigate) {
onNavigate(attachment);
}
}
}, [report.privateNotes, reportActions, parentReportActions, compareImage, report.parentReportActionID, attachments, setDownloadButtonVisibility, onNavigate, accountID, type]);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,8 @@ function AttachmentViewPdf(props: AttachmentViewPdfProps) {
.manualActivation(true)
.onTouchesMove((evt) => {
if (offsetX.value !== 0 && offsetY.value !== 0 && isScrollEnabled) {
const translateX = Math.abs(evt.allTouches.at(0).absoluteX - offsetX.value);
const translateY = Math.abs(evt.allTouches.at(0).absoluteY - offsetY.value);
const translateX = Math.abs((evt.allTouches.at(0)?.absoluteX ?? 0) - offsetX.value);
const translateY = Math.abs((evt.allTouches.at(0)?.absoluteY ?? 0) - offsetY.value);
const allowEnablingScroll = !isPanGestureActive.value || isScrollEnabled.value;

// if the value of X is greater than Y and the pdf is not zoomed in,
Expand All @@ -49,8 +49,8 @@ function AttachmentViewPdf(props: AttachmentViewPdfProps) {
}

isPanGestureActive.value = true;
offsetX.value = evt.allTouches.at(0).absoluteX;
offsetY.value = evt.allTouches.at(0).absoluteY;
offsetX.value = evt.allTouches.at(0)?.absoluteX ?? 0;
offsetY.value = evt.allTouches.at(0)?.absoluteY ?? 0;
})
.onTouchesUp(() => {
isPanGestureActive.value = false;
Expand Down
3 changes: 2 additions & 1 deletion src/components/AvatarWithDisplayName.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import CONST from '@src/CONST';
import ONYXKEYS from '@src/ONYXKEYS';
import ROUTES from '@src/ROUTES';
import type {PersonalDetails, PersonalDetailsList, Policy, Report, ReportActions} from '@src/types/onyx';
import fallbackIcon from '@src/utils/getDefaultIcon';
import CaretWrapper from './CaretWrapper';
import DisplayNames from './DisplayNames';
import MultipleAvatars from './MultipleAvatars';
Expand Down Expand Up @@ -121,7 +122,7 @@ function AvatarWithDisplayName({
{shouldShowSubscriptAvatar ? (
<SubscriptAvatar
backgroundColor={avatarBorderColor}
mainAvatar={icons.at(0)}
mainAvatar={icons.at(0) ?? fallbackIcon}
secondaryAvatar={icons.at(1)}
size={size}
/>
Expand Down
23 changes: 16 additions & 7 deletions src/components/ButtonWithDropdownMenu/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -83,9 +83,14 @@ function ButtonWithDropdownMenu<IValueType>({
setIsMenuVisible(!isMenuVisible);
return;
}
onPress(e, selectedItem?.value);
if (selectedItem?.value) {
onPress(e, selectedItem?.value);
}
} else {
onPress(e, options.at(0)?.value);
const option = options.at(0);
if (option?.value) {
onPress(e, option?.value);
}
}
},
{
Expand All @@ -103,8 +108,9 @@ function ButtonWithDropdownMenu<IValueType>({
success={success}
pressOnEnter={pressOnEnter}
ref={dropdownButtonRef}
onPress={(event) => (!isSplitButton ? setIsMenuVisible(!isMenuVisible) : onPress(event, selectedItem.value))}
text={customText ?? selectedItem.text}
// eslint-disable-next-line no-nested-ternary
onPress={(event) => (!isSplitButton ? setIsMenuVisible(!isMenuVisible) : selectedItem?.value ? onPress(event, selectedItem?.value) : undefined)}
text={customText ?? selectedItem?.text ?? ''}
isDisabled={isDisabled || !!selectedItem?.disabled}
isLoading={isLoading}
shouldRemoveRightBorderRadius
Expand Down Expand Up @@ -150,11 +156,14 @@ function ButtonWithDropdownMenu<IValueType>({
success={success}
ref={buttonRef}
pressOnEnter={pressOnEnter}
isDisabled={isDisabled || !!options.at(0).disabled}
isDisabled={isDisabled || !!options.at(0)?.disabled}
style={[styles.w100, style]}
isLoading={isLoading}
text={selectedItem.text}
onPress={(event) => onPress(event, options.at(0).value)}
text={selectedItem?.text}
onPress={(event) => {
const option = options.at(0);
return option ? onPress(event, option.value) : undefined;
}}
large={isButtonSizeLarge}
medium={!isButtonSizeLarge}
innerStyles={[innerStyleDropButton]}
Expand Down
6 changes: 3 additions & 3 deletions src/components/Composer/index.native.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -94,9 +94,9 @@ function Composer(
if (clipboardContent?.type === 'text/plain') {
return;
}
const mimeType = clipboardContent.type;
const fileURI = clipboardContent.data;
const baseFileName = fileURI.split('/').pop() ?? 'file';
const mimeType = clipboardContent?.type;
const fileURI = clipboardContent?.data;
const baseFileName = fileURI?.split('/').pop() ?? 'file';
const {fileName: stem, fileExtension: originalFileExtension} = FileUtils.splitExtensionFromFileName(baseFileName);
const fileExtension = originalFileExtension || (mimeDb[mimeType].extensions?.[0] ?? 'bin');

Check failure on line 101 in src/components/Composer/index.native.tsx

View workflow job for this annotation

GitHub Actions / typecheck

Type 'undefined' cannot be used as an index type.

Check failure on line 101 in src/components/Composer/index.native.tsx

View workflow job for this annotation

GitHub Actions / Run ESLint

Unsafe assignment of an `any` value

Check failure on line 101 in src/components/Composer/index.native.tsx

View workflow job for this annotation

GitHub Actions / Run ESLint

Unsafe member access .extensions on an `error` typed value
const fileName = `${stem}.${fileExtension}`;
Expand Down
10 changes: 8 additions & 2 deletions src/components/DatePicker/CalendarPicker/generateMonthMatrix.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,9 +50,15 @@ export default function generateMonthMatrix(year: number, month: number) {
matrix.push(currentWeek);
}

const initial = matrix.at(0);

if (!initial) {
return;
}

// Add null values for days before the first day of the month
for (let i = matrix.at(0).length; i < 7; i++) {
matrix.at(0).unshift(undefined);
for (let i = initial.length; i < 7; i++) {
initial.unshift(undefined);
}

return matrix;
Expand Down
2 changes: 1 addition & 1 deletion src/components/DatePicker/CalendarPicker/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -208,7 +208,7 @@ function CalendarPicker({
</View>
))}
</View>
{calendarDaysMatrix.map((week) => (
{calendarDaysMatrix?.map((week) => (
<View
key={`week-${week.toString()}`}
style={themeStyles.flexRow}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@ function EmojiPickerMenu({onEmojiSelected, activeEmoji}: EmojiPickerMenuProps, r
}
onEmojiSelected(emoji, item);
})}
emoji={emojiCode}
emoji={emojiCode ?? ''}
isHighlighted={shouldEmojiBeHighlighted}
/>
);
Expand Down
4 changes: 2 additions & 2 deletions src/components/EmojiPicker/EmojiPickerMenu/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -154,7 +154,7 @@ function EmojiPickerMenu({onEmojiSelected, activeEmoji}: EmojiPickerMenuProps, r
}
if ('types' in item || 'name' in item) {
const emoji = typeof preferredSkinTone === 'number' && item?.types?.[preferredSkinTone] ? item?.types?.at(preferredSkinTone) : item.code;
onEmojiSelected(emoji, item);
onEmojiSelected(emoji ?? '', item);
}
// On web, avoid this Enter default input action; otherwise, it will add a new line in the subsequently focused composer.
keyBoardEvent.preventDefault();
Expand Down Expand Up @@ -280,7 +280,7 @@ function EmojiPickerMenu({onEmojiSelected, activeEmoji}: EmojiPickerMenuProps, r
}
setIsUsingKeyboardMovement(false);
}}
emoji={emojiCode}
emoji={emojiCode ?? ''}
onFocus={() => setFocusedIndex(index)}
isFocused={isEmojiFocused}
isHighlighted={shouldFirstEmojiBeHighlighted || shouldEmojiBeHighlighted}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -60,15 +60,15 @@ function MentionUserRenderer({style, tnode, TDefaultRenderer, currentUserPersona
const user = personalDetails[htmlAttribAccountID];
accountID = parseInt(htmlAttribAccountID, 10);
mentionDisplayText = LocalePhoneNumber.formatPhoneNumber(user?.login ?? '') || PersonalDetailsUtils.getDisplayNameOrDefault(user);
mentionDisplayText = getShortMentionIfFound(mentionDisplayText, htmlAttributeAccountID, user?.login ?? '');
mentionDisplayText = getShortMentionIfFound(mentionDisplayText, htmlAttributeAccountID, user?.login ?? '') ?? '';
navigationRoute = ROUTES.PROFILE.getRoute(htmlAttribAccountID);
} else if ('data' in tnodeClone && !isEmptyObject(tnodeClone.data)) {
// We need to remove the LTR unicode and leading @ from data as it is not part of the login
mentionDisplayText = tnodeClone.data.replace(CONST.UNICODE.LTR, '').slice(1);
// We need to replace tnode.data here because we will pass it to TNodeChildrenRenderer below
asMutable(tnodeClone).data = tnodeClone.data.replace(mentionDisplayText, Str.removeSMSDomain(getShortMentionIfFound(mentionDisplayText, htmlAttributeAccountID)));
asMutable(tnodeClone).data = tnodeClone.data.replace(mentionDisplayText, Str.removeSMSDomain(getShortMentionIfFound(mentionDisplayText, htmlAttributeAccountID) ?? ''));

accountID = PersonalDetailsUtils.getAccountIDsByLogins([mentionDisplayText])?.at(0);
accountID = PersonalDetailsUtils.getAccountIDsByLogins([mentionDisplayText])?.at(0) ?? -1;
navigationRoute = ROUTES.PROFILE.getRoute(accountID, undefined, mentionDisplayText);
mentionDisplayText = Str.removeSMSDomain(mentionDisplayText);
} else {
Expand Down
5 changes: 4 additions & 1 deletion src/components/InteractiveStepSubHeader.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,10 @@ function InteractiveStepSubHeader({stepNames, startStepIndex = 0, onStepSelected
return;
}
setCurrentStep(index);
onStepSelected(stepNames.at(index));
const step = stepNames.at(index);
if (step) {
onStepSelected(step);
}
};

return (
Expand Down
3 changes: 2 additions & 1 deletion src/components/LHNOptionsList/OptionRowLHN.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ import * as ReportActionContextMenu from '@pages/home/report/ContextMenu/ReportA
import CONST from '@src/CONST';
import ONYXKEYS from '@src/ONYXKEYS';
import {isEmptyObject} from '@src/types/utils/EmptyObject';
import fallbackIcon from '@src/utils/getDefaultIcon';
import type {OptionRowLHNProps} from './types';

function OptionRowLHN({reportID, isFocused = false, onSelectRow = () => {}, optionItem, viewMode = 'default', style, onLayout = () => {}, hasDraftComment}: OptionRowLHNProps) {
Expand Down Expand Up @@ -192,7 +193,7 @@ function OptionRowLHN({reportID, isFocused = false, onSelectRow = () => {}, opti
(optionItem.shouldShowSubscript ? (
<SubscriptAvatar
backgroundColor={hovered && !isFocused ? hoveredBackgroundColor : subscriptAvatarBorderColor}
mainAvatar={optionItem.icons.at(0)}
mainAvatar={optionItem.icons.at(0) ?? fallbackIcon}
secondaryAvatar={optionItem.icons.at(1)}
size={isInFocusMode ? CONST.AVATAR_SIZE.SMALL : CONST.AVATAR_SIZE.DEFAULT}
/>
Expand Down
Loading

0 comments on commit 9aaf7c0

Please sign in to comment.