Skip to content

Commit

Permalink
Merge pull request #42634 from kubabutkiewicz/ts-migration/Define-con…
Browse files Browse the repository at this point in the history
…cise-way-to-access-or-default-to-an-inexistent-record
  • Loading branch information
blimpich authored Jun 13, 2024
2 parents 28672ce + 8c5e2e3 commit d2af463
Show file tree
Hide file tree
Showing 212 changed files with 633 additions and 609 deletions.
19 changes: 19 additions & 0 deletions contributingGuides/STYLE.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
- [Type imports/exports](#type-importsexports)
- [Refs](#refs)
- [Other Expensify Resources on TypeScript](#other-expensify-resources-on-typescript)
- [Default value for inexistent IDs](#default-value-for-inexistent-IDs)
- [Naming Conventions](#naming-conventions)
- [Type names](#type-names)
- [Prop callbacks](#prop-callbacks)
Expand Down Expand Up @@ -471,6 +472,24 @@ if (ref.current && 'getBoundingClientRect' in ref.current) {

- [Expensify TypeScript React Native CheatSheet](./TS_CHEATSHEET.md)

### Default value for inexistent IDs

Use `'-1'` or `-1` when there is a possibility that the ID property of an Onyx value could be `null` or `undefined`.

``` ts
// BAD
const foo = report?.reportID ?? '';
const bar = report?.reportID ?? '0';

report ? report.reportID : '0';
report ? report.reportID : '';

// GOOD
const foo = report?.reportID ?? '-1';

report ? report.reportID : '-1';
```

## Naming Conventions

### Type names
Expand Down
2 changes: 1 addition & 1 deletion src/components/AddPaymentMethodMenu.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ function AddPaymentMethodMenu({
// which then starts a bottom up flow and creates a Collect workspace where the payer is an admin and payee is an employee.
const isIOUReport = ReportUtils.isIOUReport(iouReport ?? {});
const canUseBusinessBankAccount =
ReportUtils.isExpenseReport(iouReport ?? {}) || (isIOUReport && !ReportActionsUtils.hasRequestFromCurrentAccount(iouReport?.reportID ?? '', session?.accountID ?? 0));
ReportUtils.isExpenseReport(iouReport ?? {}) || (isIOUReport && !ReportActionsUtils.hasRequestFromCurrentAccount(iouReport?.reportID ?? '-1', session?.accountID ?? -1));

const canUsePersonalBankAccount = shouldShowPersonalBankAccountOption || isIOUReport;

Expand Down
2 changes: 1 addition & 1 deletion src/components/AddPlaidBankAccount.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ function AddPlaidBankAccount({
const styles = useThemeStyles();
const plaidBankAccounts = plaidData?.bankAccounts ?? [];
const defaultSelectedPlaidAccount = plaidBankAccounts.find((account) => account.plaidAccountID === selectedPlaidAccountID);
const defaultSelectedPlaidAccountID = defaultSelectedPlaidAccount?.plaidAccountID ?? '';
const defaultSelectedPlaidAccountID = defaultSelectedPlaidAccount?.plaidAccountID ?? '-1';
const defaultSelectedPlaidAccountMask = plaidBankAccounts.find((account) => account.plaidAccountID === selectedPlaidAccountID)?.mask ?? '';
const subscribedKeyboardShortcuts = useRef<Array<() => void>>([]);
const previousNetworkState = useRef<boolean | undefined>();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ function BaseAnchorForAttachmentsOnly({style, source = '', displayName = '', dow
}}
onPressIn={onPressIn}
onPressOut={onPressOut}
onLongPress={(event) => showContextMenuForReport(event, anchor, report?.reportID ?? '', action, checkIfContextMenuActive, ReportUtils.isArchivedRoom(report))}
onLongPress={(event) => showContextMenuForReport(event, anchor, report?.reportID ?? '-1', action, checkIfContextMenuActive, ReportUtils.isArchivedRoom(report))}
shouldUseHapticsOnLongPress
accessibilityLabel={displayName}
role={CONST.ROLE.BUTTON}
Expand Down
6 changes: 3 additions & 3 deletions src/components/ArchivedReportFooter.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -32,15 +32,15 @@ function ArchivedReportFooter({report, reportClosedAction, personalDetails = {}}

const originalMessage = reportClosedAction?.actionName === CONST.REPORT.ACTIONS.TYPE.CLOSED ? reportClosedAction.originalMessage : null;
const archiveReason = originalMessage?.reason ?? CONST.REPORT.ARCHIVE_REASON.DEFAULT;
const actorPersonalDetails = personalDetails?.[reportClosedAction?.actorAccountID ?? 0];
const actorPersonalDetails = personalDetails?.[reportClosedAction?.actorAccountID ?? -1];
let displayName = PersonalDetailsUtils.getDisplayNameOrDefault(actorPersonalDetails);

let oldDisplayName: string | undefined;
if (archiveReason === CONST.REPORT.ARCHIVE_REASON.ACCOUNT_MERGED) {
const newAccountID = originalMessage?.newAccountID;
const oldAccountID = originalMessage?.oldAccountID;
displayName = PersonalDetailsUtils.getDisplayNameOrDefault(personalDetails?.[newAccountID ?? 0]);
oldDisplayName = PersonalDetailsUtils.getDisplayNameOrDefault(personalDetails?.[oldAccountID ?? 0]);
displayName = PersonalDetailsUtils.getDisplayNameOrDefault(personalDetails?.[newAccountID ?? -1]);
oldDisplayName = PersonalDetailsUtils.getDisplayNameOrDefault(personalDetails?.[oldAccountID ?? -1]);
}

const shouldRenderHTML = archiveReason !== CONST.REPORT.ARCHIVE_REASON.DEFAULT;
Expand Down
12 changes: 6 additions & 6 deletions src/components/AttachmentModal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -282,9 +282,9 @@ function AttachmentModal({
* Detach the receipt and close the modal.
*/
const deleteAndCloseModal = useCallback(() => {
IOU.detachReceipt(transaction?.transactionID ?? '');
IOU.detachReceipt(transaction?.transactionID ?? '-1');
setIsDeleteReceiptConfirmModalVisible(false);
Navigation.goBack(ROUTES.REPORT_WITH_ID_DETAILS.getRoute(report?.reportID ?? ''));
Navigation.goBack(ROUTES.REPORT_WITH_ID_DETAILS.getRoute(report?.reportID ?? '-1'));
}, [transaction, report]);

const isValidFile = useCallback((fileObject: FileObject) => {
Expand Down Expand Up @@ -427,8 +427,8 @@ function AttachmentModal({
ROUTES.MONEY_REQUEST_STEP_SCAN.getRoute(
CONST.IOU.ACTION.EDIT,
iouType,
transaction?.transactionID ?? '',
report?.reportID ?? '',
transaction?.transactionID ?? '-1',
report?.reportID ?? '-1',
Navigation.getActiveRouteWithoutParams(),
),
);
Expand Down Expand Up @@ -616,8 +616,8 @@ AttachmentModal.displayName = 'AttachmentModal';
export default withOnyx<AttachmentModalProps, AttachmentModalOnyxProps>({
transaction: {
key: ({report}) => {
const parentReportAction = ReportActionsUtils.getReportAction(report?.parentReportID ?? '', report?.parentReportActionID ?? '');
const transactionID = parentReportAction?.actionName === CONST.REPORT.ACTIONS.TYPE.IOU ? parentReportAction?.originalMessage.IOUTransactionID ?? '0' : '0';
const parentReportAction = ReportActionsUtils.getReportAction(report?.parentReportID ?? '-1', report?.parentReportActionID ?? '-1');
const transactionID = parentReportAction?.actionName === CONST.REPORT.ACTIONS.TYPE.IOU ? parentReportAction?.originalMessage.IOUTransactionID ?? '-1' : '-1';
return `${ONYXKEYS.COLLECTION.TRANSACTION}${transactionID}`;
},
},
Expand Down
4 changes: 2 additions & 2 deletions src/components/AvatarWithDisplayName.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ function AvatarWithDisplayName({

const actorAccountID = useRef<number | null>(null);
useEffect(() => {
const parentReportAction = parentReportActions?.[report?.parentReportActionID ?? ''];
const parentReportAction = parentReportActions?.[report?.parentReportActionID ?? '-1'];
actorAccountID.current = parentReportAction?.actorAccountID ?? -1;
}, [parentReportActions, report]);

Expand Down Expand Up @@ -182,7 +182,7 @@ AvatarWithDisplayName.displayName = 'AvatarWithDisplayName';

export default withOnyx<AvatarWithDisplayNameProps, AvatarWithDisplayNamePropsWithOnyx>({
parentReportActions: {
key: ({report}) => `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${report ? report.parentReportID : '0'}`,
key: ({report}) => `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${report ? report.parentReportID : '-1'}`,
canEvict: false,
},
personalDetails: {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ function ImageRenderer({tnode}: ImageRendererProps) {
Navigation.navigate(route);
}
}}
onLongPress={(event) => showContextMenuForReport(event, anchor, report?.reportID ?? '', action, checkIfContextMenuActive, ReportUtils.isArchivedRoom(report))}
onLongPress={(event) => showContextMenuForReport(event, anchor, report?.reportID ?? '-1', action, checkIfContextMenuActive, ReportUtils.isArchivedRoom(report))}
shouldUseHapticsOnLongPress
accessibilityRole={CONST.ACCESSIBILITY_ROLE.IMAGEBUTTON}
accessibilityLabel={translate('accessibilityHints.viewAttachment')}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ function MentionUserRenderer({style, tnode, TDefaultRenderer, currentUserPersona
{({anchor, report, action, checkIfContextMenuActive}) => (
<Text
suppressHighlighting
onLongPress={(event) => showContextMenuForReport(event, anchor, report?.reportID ?? '', action, checkIfContextMenuActive, ReportUtils.isArchivedRoom(report))}
onLongPress={(event) => showContextMenuForReport(event, anchor, report?.reportID ?? '-1', action, checkIfContextMenuActive, ReportUtils.isArchivedRoom(report))}
onPress={(event) => {
event.preventDefault();
Navigation.navigate(navigationRoute);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ function PreRenderer({TDefaultRenderer, onPressIn, onPressOut, onLongPress, ...d
onPress={onPressIn ?? (() => {})}
onPressIn={onPressIn}
onPressOut={onPressOut}
onLongPress={(event) => showContextMenuForReport(event, anchor, report?.reportID ?? '', action, checkIfContextMenuActive, ReportUtils.isArchivedRoom(report))}
onLongPress={(event) => showContextMenuForReport(event, anchor, report?.reportID ?? '-1', action, checkIfContextMenuActive, ReportUtils.isArchivedRoom(report))}
shouldUseHapticsOnLongPress
role={CONST.ROLE.PRESENTATION}
accessibilityLabel={translate('accessibilityHints.prestyledText')}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,13 +29,13 @@ function VideoRenderer({tnode, key}: VideoRendererProps) {
<VideoPlayerPreview
key={key}
videoUrl={sourceURL}
reportID={report?.reportID ?? ''}
reportID={report?.reportID ?? '-1'}
fileName={fileName}
thumbnailUrl={thumbnailUrl}
videoDimensions={{width, height}}
videoDuration={duration}
onShowModalPress={() => {
const route = ROUTES.ATTACHMENTS.getRoute(report?.reportID ?? '', CONST.ATTACHMENT_TYPE.REPORT, sourceURL);
const route = ROUTES.ATTACHMENTS.getRoute(report?.reportID ?? '-1', CONST.ATTACHMENT_TYPE.REPORT, sourceURL);
Navigation.navigate(route);
}}
/>
Expand Down
6 changes: 3 additions & 3 deletions src/components/LHNOptionsList/LHNOptionsList.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -101,9 +101,9 @@ function LHNOptionsList({style, contentContainerStyles, data, onSelectRow, optio
const itemFullReport = reports?.[`${ONYXKEYS.COLLECTION.REPORT}${reportID}`];
const itemReportActions = reportActions?.[`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${reportID}`];
const itemParentReportActions = reportActions?.[`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${itemFullReport?.parentReportID}`];
const itemParentReportAction = itemParentReportActions?.[itemFullReport?.parentReportActionID ?? ''];
const itemParentReportAction = itemParentReportActions?.[itemFullReport?.parentReportActionID ?? '-1'];
const itemPolicy = policy?.[`${ONYXKEYS.COLLECTION.POLICY}${itemFullReport?.policyID}`];
const transactionID = itemParentReportAction?.actionName === CONST.REPORT.ACTIONS.TYPE.IOU ? itemParentReportAction.originalMessage.IOUTransactionID ?? '' : '';
const transactionID = itemParentReportAction?.actionName === CONST.REPORT.ACTIONS.TYPE.IOU ? itemParentReportAction.originalMessage.IOUTransactionID ?? '-1' : '-1';
const itemTransaction = transactions?.[`${ONYXKEYS.COLLECTION.TRANSACTION}${transactionID}`];
const hasDraftComment = DraftCommentUtils.isValidDraftComment(draftComments?.[`${ONYXKEYS.COLLECTION.REPORT_DRAFT_COMMENT}${reportID}`]);
const sortedReportActions = ReportActionsUtils.getSortedReportActionsForDisplay(itemReportActions);
Expand All @@ -113,7 +113,7 @@ function LHNOptionsList({style, contentContainerStyles, data, onSelectRow, optio
let lastReportActionTransactionID = '';

if (lastReportAction?.actionName === CONST.REPORT.ACTIONS.TYPE.IOU) {
lastReportActionTransactionID = lastReportAction.originalMessage?.IOUTransactionID ?? '';
lastReportActionTransactionID = lastReportAction.originalMessage?.IOUTransactionID ?? '-1';
}
const lastReportActionTransaction = transactions?.[`${ONYXKEYS.COLLECTION.TRANSACTION}${lastReportActionTransactionID}`] ?? {};

Expand Down
6 changes: 3 additions & 3 deletions src/components/LHNOptionsList/OptionRowLHN.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ function OptionRowLHN({reportID, isFocused = false, onSelectRow = () => {}, opti
'',
popoverAnchor.current,
reportID,
'0',
'-1',
reportID,
undefined,
() => {},
Expand All @@ -122,12 +122,12 @@ function OptionRowLHN({reportID, isFocused = false, onSelectRow = () => {}, opti
const statusClearAfterDate = optionItem.status?.clearAfter ?? '';
const formattedDate = DateUtils.getStatusUntilDate(statusClearAfterDate);
const statusContent = formattedDate ? `${statusText ? `${statusText} ` : ''}(${formattedDate})` : statusText;
const report = ReportUtils.getReport(optionItem.reportID ?? '');
const report = ReportUtils.getReport(optionItem.reportID ?? '-1');
const isStatusVisible = !!emojiCode && ReportUtils.isOneOnOneChat(!isEmptyObject(report) ? report : undefined);

const isGroupChat = ReportUtils.isGroupChat(optionItem) || ReportUtils.isDeprecatedGroupDM(optionItem);

const fullTitle = isGroupChat ? ReportUtils.getGroupChatName(undefined, false, optionItem.reportID ?? '') : optionItem.text;
const fullTitle = isGroupChat ? ReportUtils.getGroupChatName(undefined, false, optionItem.reportID ?? '-1') : optionItem.text;
const subscriptAvatarBorderColor = isFocused ? focusedBackgroundColor : theme.sidebar;
return (
<OfflineWithFeedback
Expand Down
8 changes: 4 additions & 4 deletions src/components/MoneyReportHeader.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -149,9 +149,9 @@ function MoneyReportHeader({policy, report: moneyRequestReport, transactionThrea

const deleteTransaction = useCallback(() => {
if (requestParentReportAction) {
const iouTransactionID = requestParentReportAction.actionName === CONST.REPORT.ACTIONS.TYPE.IOU ? requestParentReportAction.originalMessage?.IOUTransactionID ?? '' : '';
const iouTransactionID = requestParentReportAction.actionName === CONST.REPORT.ACTIONS.TYPE.IOU ? requestParentReportAction.originalMessage?.IOUTransactionID ?? '-1' : '-1';
if (ReportActionsUtils.isTrackExpenseAction(requestParentReportAction)) {
navigateBackToAfterDelete.current = IOU.deleteTrackExpense(moneyRequestReport?.reportID ?? '', iouTransactionID, requestParentReportAction, true);
navigateBackToAfterDelete.current = IOU.deleteTrackExpense(moneyRequestReport?.reportID ?? '-1', iouTransactionID, requestParentReportAction, true);
} else {
navigateBackToAfterDelete.current = IOU.deleteMoneyRequest(iouTransactionID, requestParentReportAction, true);
}
Expand All @@ -164,8 +164,8 @@ function MoneyReportHeader({policy, report: moneyRequestReport, transactionThrea
if (!requestParentReportAction) {
return;
}
const iouTransactionID = requestParentReportAction.actionName === CONST.REPORT.ACTIONS.TYPE.IOU ? requestParentReportAction.originalMessage?.IOUTransactionID ?? '' : '';
const reportID = transactionThreadReport?.reportID ?? '';
const iouTransactionID = requestParentReportAction.actionName === CONST.REPORT.ACTIONS.TYPE.IOU ? requestParentReportAction.originalMessage?.IOUTransactionID ?? '-1' : '-1';
const reportID = transactionThreadReport?.reportID ?? '-1';

TransactionActions.markAsCash(iouTransactionID, reportID);
}, [requestParentReportAction, transactionThreadReport?.reportID]);
Expand Down
12 changes: 7 additions & 5 deletions src/components/MoneyRequestConfirmationList.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -240,8 +240,8 @@ function MoneyRequestConfirmationList({
const isTypeInvoice = iouType === CONST.IOU.TYPE.INVOICE;
const isScanRequest = useMemo(() => TransactionUtils.isScanRequest(transaction), [transaction]);

const transactionID = transaction?.transactionID ?? '';
const customUnitRateID = TransactionUtils.getRateID(transaction) ?? '';
const transactionID = transaction?.transactionID ?? '-1';
const customUnitRateID = TransactionUtils.getRateID(transaction) ?? '-1';

useEffect(() => {
if (customUnitRateID || !canUseP2PDistanceRequests) {
Expand Down Expand Up @@ -510,7 +510,7 @@ function MoneyRequestConfirmationList({
rightElement: (
<MoneyRequestAmountInput
autoGrow={false}
amount={transaction?.splitShares?.[participantOption.accountID ?? 0]?.amount}
amount={transaction?.splitShares?.[participantOption.accountID ?? -1]?.amount}
currency={iouCurrencyCode}
prefixCharacter={currencySymbol}
disableKeyboard={false}
Expand All @@ -523,7 +523,7 @@ function MoneyRequestConfirmationList({
containerStyle={[styles.textInputContainer, amountWidth]}
touchableInputWrapperStyle={[styles.ml3]}
onFormatAmount={CurrencyUtils.convertToDisplayStringWithoutCurrency}
onAmountChange={(value: string) => onSplitShareChange(participantOption.accountID ?? 0, Number(value))}
onAmountChange={(value: string) => onSplitShareChange(participantOption.accountID ?? -1, Number(value))}
maxLength={formattedTotalAmount.length}
/>
),
Expand Down Expand Up @@ -1186,7 +1186,9 @@ function MoneyRequestConfirmationList({
isLabelHoverable={false}
interactive={!isReadOnly && canUpdateSenderWorkspace}
onPress={() => {
Navigation.navigate(ROUTES.MONEY_REQUEST_STEP_SEND_FROM.getRoute(iouType, transaction?.transactionID ?? '', reportID, Navigation.getActiveRouteWithoutParams()));
Navigation.navigate(
ROUTES.MONEY_REQUEST_STEP_SEND_FROM.getRoute(iouType, transaction?.transactionID ?? '-1', reportID, Navigation.getActiveRouteWithoutParams()),
);
}}
style={styles.moneyRequestMenuItem}
labelStyle={styles.mt2}
Expand Down
Loading

0 comments on commit d2af463

Please sign in to comment.