From 936e86161b5f6e7662f6863480e5cde8b00dfb5c Mon Sep 17 00:00:00 2001 From: dukenv0307 Date: Mon, 18 Dec 2023 18:04:32 +0700 Subject: [PATCH 1/9] update logic to store last message text --- src/libs/ReportUtils.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/libs/ReportUtils.ts b/src/libs/ReportUtils.ts index 24e795919649..8c6402e09b03 100644 --- a/src/libs/ReportUtils.ts +++ b/src/libs/ReportUtils.ts @@ -1186,7 +1186,7 @@ function formatReportLastMessageText(lastMessageText: string, isModifiedExpenseM if (isModifiedExpenseMessage) { return String(lastMessageText).trim().replace(CONST.REGEX.LINE_BREAK, '').trim(); } - return String(lastMessageText).trim().replace(CONST.REGEX.AFTER_FIRST_LINE_BREAK, '').substring(0, CONST.REPORT.LAST_MESSAGE_TEXT_MAX_LENGTH).trim(); + return String(lastMessageText).trim().replace(CONST.REGEX.LINE_BREAK, ' ').substring(0, CONST.REPORT.LAST_MESSAGE_TEXT_MAX_LENGTH).trim(); } /** From ee93ba6a6e50b539f552648bbf68bdef3006b60a Mon Sep 17 00:00:00 2001 From: Bernhard Owen Josephus Date: Fri, 22 Dec 2023 16:40:32 +0800 Subject: [PATCH 2/9] don't focus if a popover is visible --- .../ComposerWithSuggestions/ComposerWithSuggestions.js | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/src/pages/home/report/ReportActionCompose/ComposerWithSuggestions/ComposerWithSuggestions.js b/src/pages/home/report/ReportActionCompose/ComposerWithSuggestions/ComposerWithSuggestions.js index 8def3a53ca0d..7d6c00ddaf6d 100644 --- a/src/pages/home/report/ReportActionCompose/ComposerWithSuggestions/ComposerWithSuggestions.js +++ b/src/pages/home/report/ReportActionCompose/ComposerWithSuggestions/ComposerWithSuggestions.js @@ -37,6 +37,7 @@ import * as User from '@userActions/User'; import CONST from '@src/CONST'; import ONYXKEYS from '@src/ONYXKEYS'; import {defaultProps, propTypes} from './composerWithSuggestionsProps'; +import { PopoverContext } from '@components/PopoverProvider'; const {RNTextInputReset} = NativeModules; @@ -103,6 +104,7 @@ function ComposerWithSuggestions({ // For testing children, }) { + const {isOpen: isPopoverOpen} = React.useContext(PopoverContext); const theme = useTheme(); const styles = useThemeStyles(); const StyleUtils = useStyleUtils(); @@ -399,8 +401,11 @@ function ComposerWithSuggestions({ * @memberof ReportActionCompose */ const focus = useCallback((shouldDelay = false) => { + if (isPopoverOpen) { + return; + } focusComposerWithDelay(textInputRef.current)(shouldDelay); - }, []); + }, [isPopoverOpen]); const setUpComposeFocusManager = useCallback(() => { // This callback is used in the contextMenuActions to manage giving focus back to the compose input. From 7c64b0fd1daa0fbb6e1dec784d50e355d097c4b0 Mon Sep 17 00:00:00 2001 From: Bernhard Owen Josephus Date: Fri, 22 Dec 2023 16:51:20 +0800 Subject: [PATCH 3/9] prettier --- .../ComposerWithSuggestions.js | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) diff --git a/src/pages/home/report/ReportActionCompose/ComposerWithSuggestions/ComposerWithSuggestions.js b/src/pages/home/report/ReportActionCompose/ComposerWithSuggestions/ComposerWithSuggestions.js index 7d6c00ddaf6d..4de6201d6f6e 100644 --- a/src/pages/home/report/ReportActionCompose/ComposerWithSuggestions/ComposerWithSuggestions.js +++ b/src/pages/home/report/ReportActionCompose/ComposerWithSuggestions/ComposerWithSuggestions.js @@ -5,6 +5,7 @@ import {findNodeHandle, NativeModules, View} from 'react-native'; import {withOnyx} from 'react-native-onyx'; import _ from 'underscore'; import Composer from '@components/Composer'; +import {PopoverContext} from '@components/PopoverProvider'; import withKeyboardState from '@components/withKeyboardState'; import useDebounce from '@hooks/useDebounce'; import useLocalize from '@hooks/useLocalize'; @@ -37,7 +38,6 @@ import * as User from '@userActions/User'; import CONST from '@src/CONST'; import ONYXKEYS from '@src/ONYXKEYS'; import {defaultProps, propTypes} from './composerWithSuggestionsProps'; -import { PopoverContext } from '@components/PopoverProvider'; const {RNTextInputReset} = NativeModules; @@ -400,12 +400,15 @@ function ComposerWithSuggestions({ * @param {Boolean} [shouldDelay=false] Impose delay before focusing the composer * @memberof ReportActionCompose */ - const focus = useCallback((shouldDelay = false) => { - if (isPopoverOpen) { - return; - } - focusComposerWithDelay(textInputRef.current)(shouldDelay); - }, [isPopoverOpen]); + const focus = useCallback( + (shouldDelay = false) => { + if (isPopoverOpen) { + return; + } + focusComposerWithDelay(textInputRef.current)(shouldDelay); + }, + [isPopoverOpen], + ); const setUpComposeFocusManager = useCallback(() => { // This callback is used in the contextMenuActions to manage giving focus back to the compose input. From d0d9d2af9a4cee024168a9b973f4f3ae23617564 Mon Sep 17 00:00:00 2001 From: Sam Hariri <137707942+samh-nl@users.noreply.github.com> Date: Fri, 22 Dec 2023 14:13:33 +0100 Subject: [PATCH 4/9] fix: allow empty draft messages --- src/components/LHNOptionsList/OptionRowLHN.js | 2 +- src/components/ShowContextMenuContext.js | 2 +- src/libs/actions/Report.ts | 9 ++++- .../report/ContextMenu/ContextMenuActions.js | 8 ++++- .../ContextMenu/ReportActionContextMenu.ts | 2 +- ...genericReportActionContextMenuPropTypes.js | 2 +- src/pages/home/report/ReportActionItem.js | 34 +++++++++---------- .../report/ReportActionItemMessageEdit.js | 12 ++----- src/types/onyx/ReportActionsDrafts.ts | 6 +++- 9 files changed, 44 insertions(+), 33 deletions(-) diff --git a/src/components/LHNOptionsList/OptionRowLHN.js b/src/components/LHNOptionsList/OptionRowLHN.js index 59a392ff4e67..a4f4d8246caf 100644 --- a/src/components/LHNOptionsList/OptionRowLHN.js +++ b/src/components/LHNOptionsList/OptionRowLHN.js @@ -135,7 +135,7 @@ function OptionRowLHN(props) { props.reportID, '0', props.reportID, - '', + undefined, () => {}, () => setIsContextMenuActive(false), false, diff --git a/src/components/ShowContextMenuContext.js b/src/components/ShowContextMenuContext.js index 28822451956d..04ccd5002b60 100644 --- a/src/components/ShowContextMenuContext.js +++ b/src/components/ShowContextMenuContext.js @@ -35,7 +35,7 @@ function showContextMenuForReport(event, anchor, reportID, action, checkIfContex reportID, action.reportActionID, ReportUtils.getOriginalReportID(reportID, action), - '', + undefined, checkIfContextMenuActive, checkIfContextMenuActive, isArchivedRoom, diff --git a/src/libs/actions/Report.ts b/src/libs/actions/Report.ts index 1ed54c826e40..6c9aacedaad4 100644 --- a/src/libs/actions/Report.ts +++ b/src/libs/actions/Report.ts @@ -1345,10 +1345,16 @@ function editReportComment(reportID: string, originalReportAction: OnyxEntry Report.saveReportActionDraft(reportID, reportAction, _.isEmpty(draftMessage) ? getActionText(reportAction) : ''); + const editAction = () => { + if (_.isUndefined(draftMessage)) { + Report.saveReportActionDraft(reportID, reportAction, getActionText(reportAction)); + } else { + Report.deleteReportActionDraft(reportID, reportAction); + } + }; if (closePopover) { // Hide popover, then call editAction diff --git a/src/pages/home/report/ContextMenu/ReportActionContextMenu.ts b/src/pages/home/report/ContextMenu/ReportActionContextMenu.ts index b269bc276b55..1e1fc700d8e0 100644 --- a/src/pages/home/report/ContextMenu/ReportActionContextMenu.ts +++ b/src/pages/home/report/ContextMenu/ReportActionContextMenu.ts @@ -98,7 +98,7 @@ function showContextMenu( reportID = '0', reportActionID = '0', originalReportID = '0', - draftMessage = '', + draftMessage = undefined, onShow = () => {}, onHide = () => {}, isArchivedRoom = false, diff --git a/src/pages/home/report/ContextMenu/genericReportActionContextMenuPropTypes.js b/src/pages/home/report/ContextMenu/genericReportActionContextMenuPropTypes.js index 3d8667e44e62..b9f892c1b9ff 100644 --- a/src/pages/home/report/ContextMenu/genericReportActionContextMenuPropTypes.js +++ b/src/pages/home/report/ContextMenu/genericReportActionContextMenuPropTypes.js @@ -28,7 +28,7 @@ const defaultProps = { isMini: false, isVisible: false, selection: '', - draftMessage: '', + draftMessage: undefined, }; export {propTypes, defaultProps}; diff --git a/src/pages/home/report/ReportActionItem.js b/src/pages/home/report/ReportActionItem.js index d37f84e0c908..73858da894e1 100644 --- a/src/pages/home/report/ReportActionItem.js +++ b/src/pages/home/report/ReportActionItem.js @@ -119,7 +119,7 @@ const propTypes = { }; const defaultProps = { - draftMessage: '', + draftMessage: undefined, preferredSkinTone: CONST.EMOJI_DEFAULT_SKIN_TONE, emojiReactions: {}, shouldShowSubscriptAvatar: false, @@ -202,7 +202,7 @@ function ReportActionItem(props) { }, [isDeletedParentAction, props.action.reportActionID]); useEffect(() => { - if (prevDraftMessage || !props.draftMessage) { + if (!_.isUndefined(prevDraftMessage) || _.isUndefined(props.draftMessage)) { return; } @@ -224,10 +224,10 @@ function ReportActionItem(props) { }, [props.action, props.report.reportID]); useEffect(() => { - if (!props.draftMessage || !ReportActionsUtils.isDeletedAction(props.action)) { + if (_.isUndefined(props.draftMessage) || !ReportActionsUtils.isDeletedAction(props.action)) { return; } - Report.saveReportActionDraft(props.report.reportID, props.action, ''); + Report.deleteReportActionDraft(props.report.reportID, props.action); }, [props.draftMessage, props.action, props.report.reportID]); // Hide the message if it is being moderated for a higher offense, or is hidden by a moderator @@ -265,7 +265,7 @@ function ReportActionItem(props) { const showPopover = useCallback( (event) => { // Block menu on the message being Edited or if the report action item has errors - if (props.draftMessage || !_.isEmpty(props.action.errors)) { + if (!_.isUndefined(props.draftMessage) || !_.isEmpty(props.action.errors)) { return; } @@ -428,7 +428,7 @@ function ReportActionItem(props) { const hasBeenFlagged = !_.contains([CONST.MODERATION.MODERATOR_DECISION_APPROVED, CONST.MODERATION.MODERATOR_DECISION_PENDING], moderationDecision); children = ( - {!props.draftMessage ? ( + {_.isUndefined(props.draftMessage) ? ( Number(accountID)); - const draftMessageRightAlign = props.draftMessage ? styles.chatItemReactionsDraftRight : {}; + const draftMessageRightAlign = !_.isUndefined(props.draftMessage) ? styles.chatItemReactionsDraftRight : {}; return ( <> {children} {Permissions.canUseLinkPreviews() && !isHidden && !_.isEmpty(props.action.linkMetadata) && ( - + !_.isEmpty(item))} /> )} @@ -544,7 +544,7 @@ function ReportActionItem(props) { const renderReportActionItem = (hovered, isWhisper, hasErrors) => { const content = renderItemContent(hovered || isContextMenuActive, isWhisper, hasErrors); - if (props.draftMessage) { + if (!_.isUndefined(props.draftMessage)) { return {content}; } @@ -552,7 +552,7 @@ function ReportActionItem(props) { return ( ${props.translate('parentReportAction.deletedTask')}`} /> @@ -666,13 +666,13 @@ function ReportActionItem(props) { onPressIn={() => props.isSmallScreenWidth && DeviceCapabilities.canUseTouchScreen() && ControlSelection.block()} onPressOut={() => ControlSelection.unblock()} onSecondaryInteraction={showPopover} - preventDefaultContextMenu={!props.draftMessage && !hasErrors} + preventDefaultContextMenu={_.isUndefined(props.draftMessage) && !hasErrors} withoutFocusOnSecondaryInteraction accessibilityLabel={props.translate('accessibilityHints.chatMessage')} > {(hovered) => ( @@ -683,14 +683,14 @@ function ReportActionItem(props) { originalReportID={originalReportID} isArchivedRoom={ReportUtils.isArchivedRoom(props.report)} displayAsGroup={props.displayAsGroup} - isVisible={hovered && !props.draftMessage && !hasErrors} + isVisible={hovered && _.isUndefined(props.draftMessage) && !hasErrors} draftMessage={props.draftMessage} isChronosReport={ReportUtils.chatIncludesChronos(originalReport)} /> - + ReportActions.clearReportActionErrors(props.report.reportID, props.action)} - pendingAction={props.draftMessage ? null : props.action.pendingAction} + pendingAction={!_.isUndefined(props.draftMessage) ? null : props.action.pendingAction} shouldHideOnDelete={!ReportActionsUtils.isThreadParentMessage(props.action, props.report.reportID)} errors={props.action.errors} errorRowStyles={[styles.ml10, styles.mr2]} @@ -745,7 +745,7 @@ export default compose( transformValue: (drafts, props) => { const originalReportID = ReportUtils.getOriginalReportID(props.report.reportID, props.action); const draftKey = `${ONYXKEYS.COLLECTION.REPORT_ACTIONS_DRAFTS}${originalReportID}`; - return lodashGet(drafts, [draftKey, props.action.reportActionID], ''); + return lodashGet(drafts, [draftKey, props.action.reportActionID, 'message']); }, }), withOnyx({ diff --git a/src/pages/home/report/ReportActionItemMessageEdit.js b/src/pages/home/report/ReportActionItemMessageEdit.js index 55b031c198e0..5cad80711bcb 100644 --- a/src/pages/home/report/ReportActionItemMessageEdit.js +++ b/src/pages/home/report/ReportActionItemMessageEdit.js @@ -270,14 +270,8 @@ function ReportActionItemMessageEdit(props) { draftRef.current = newDraft; - // This component is rendered only when draft is set to a non-empty string. In order to prevent component - // unmount when user deletes content of textarea, we set previous message instead of empty string. - if (newDraft.trim().length > 0) { - // We want to escape the draft message to differentiate the HTML from the report action and the HTML the user drafted. - debouncedSaveDraft(_.escape(newDraft)); - } else { - debouncedSaveDraft(props.action.message[0].html); - } + // We want to escape the draft message to differentiate the HTML from the report action and the HTML the user drafted. + debouncedSaveDraft(_.escape(newDraft)); }, [props.action.message, debouncedSaveDraft, debouncedUpdateFrequentlyUsedEmojis, props.preferredSkinTone, preferredLocale, selection.end], ); @@ -292,7 +286,7 @@ function ReportActionItemMessageEdit(props) { */ const deleteDraft = useCallback(() => { debouncedSaveDraft.cancel(); - Report.saveReportActionDraft(props.reportID, props.action, ''); + Report.deleteReportActionDraft(props.reportID, props.action); if (isActive()) { ReportActionComposeFocusManager.clear(); diff --git a/src/types/onyx/ReportActionsDrafts.ts b/src/types/onyx/ReportActionsDrafts.ts index e40007b6b47a..34ccc977ef48 100644 --- a/src/types/onyx/ReportActionsDrafts.ts +++ b/src/types/onyx/ReportActionsDrafts.ts @@ -1,3 +1,7 @@ -type ReportActionsDrafts = Record; +type ReportActionsDraft = { + message: string; +}; + +type ReportActionsDrafts = Record; export default ReportActionsDrafts; From e7c762a9c6b8dfe3b9effbe524183ba4e1c7e215 Mon Sep 17 00:00:00 2001 From: Sam Hariri <137707942+samh-nl@users.noreply.github.com> Date: Fri, 22 Dec 2023 14:21:13 +0100 Subject: [PATCH 5/9] fix: migrate empty report actions drafts --- src/libs/migrateOnyx.js | 3 +- .../RemoveEmptyReportActionsDrafts.js | 69 +++++++++++++++++++ 2 files changed, 71 insertions(+), 1 deletion(-) create mode 100644 src/libs/migrations/RemoveEmptyReportActionsDrafts.js diff --git a/src/libs/migrateOnyx.js b/src/libs/migrateOnyx.js index 5daba3686208..9b8b4056e3e5 100644 --- a/src/libs/migrateOnyx.js +++ b/src/libs/migrateOnyx.js @@ -2,6 +2,7 @@ import _ from 'underscore'; import Log from './Log'; import KeyReportActionsDraftByReportActionID from './migrations/KeyReportActionsDraftByReportActionID'; import PersonalDetailsByAccountID from './migrations/PersonalDetailsByAccountID'; +import RemoveEmptyReportActionsDrafts from './migrations/RemoveEmptyReportActionsDrafts'; import RenameReceiptFilename from './migrations/RenameReceiptFilename'; import TransactionBackupsToCollection from './migrations/TransactionBackupsToCollection'; @@ -11,7 +12,7 @@ export default function () { return new Promise((resolve) => { // Add all migrations to an array so they are executed in order - const migrationPromises = [PersonalDetailsByAccountID, RenameReceiptFilename, KeyReportActionsDraftByReportActionID, TransactionBackupsToCollection]; + const migrationPromises = [PersonalDetailsByAccountID, RenameReceiptFilename, KeyReportActionsDraftByReportActionID, TransactionBackupsToCollection, RemoveEmptyReportActionsDrafts]; // Reduce all promises down to a single promise. All promises run in a linear fashion, waiting for the // previous promise to finish before moving onto the next one. diff --git a/src/libs/migrations/RemoveEmptyReportActionsDrafts.js b/src/libs/migrations/RemoveEmptyReportActionsDrafts.js new file mode 100644 index 000000000000..586cca8ca1ed --- /dev/null +++ b/src/libs/migrations/RemoveEmptyReportActionsDrafts.js @@ -0,0 +1,69 @@ +import Onyx from 'react-native-onyx'; +import _ from 'underscore'; +import Log from '@libs/Log'; +import ONYXKEYS from '@src/ONYXKEYS'; + +/** + * This migration removes empty drafts from reportActionsDrafts, which was previously used to mark a draft as being non-existent (e.g. upon cancel). + * + * @returns {Promise} + */ +export default function () { + return new Promise((resolve) => { + const connectionID = Onyx.connect({ + key: ONYXKEYS.COLLECTION.REPORT_ACTIONS_DRAFTS, + waitForCollectionCallback: true, + callback: (allReportActionsDrafts) => { + Onyx.disconnect(connectionID); + + if (!allReportActionsDrafts) { + Log.info('[Migrate Onyx] Skipped migration RemoveEmptyReportActionsDrafts because there were no reportActionsDrafts'); + return resolve(); + } + + const newReportActionsDrafts = {}; + _.each(allReportActionsDrafts, (reportActionDrafts, onyxKey) => { + newReportActionsDrafts[onyxKey] = {}; + + // Whether there is at least one draft in this report that has to be migrated + let hasUnmigratedDraft = false; + + _.each(reportActionDrafts, (reportActionDraft, reportActionID) => { + // If the draft is a string, it means it hasn't been migrated yet + if (_.isString(reportActionDraft)) { + hasUnmigratedDraft = true; + Log.info(`[Migrate Onyx] Migrating draft for report action ${reportActionID}`); + + if (_.isEmpty(reportActionDraft)) { + Log.info(`[Migrate Onyx] Removing draft for report action ${reportActionID}`); + return; + } + + newReportActionsDrafts[onyxKey][reportActionID] = {message: reportActionDraft}; + } else { + // We've already migrated this draft, so keep the existing value + newReportActionsDrafts[onyxKey][reportActionID] = reportActionDraft; + } + }); + + if (_.isEmpty(newReportActionsDrafts[onyxKey])) { + // Clear if there are no drafts remaining + newReportActionsDrafts[onyxKey] = null; + } else if (!hasUnmigratedDraft) { + // All drafts for this report have already been migrated, there's no need to overwrite this onyx key with the same data + delete newReportActionsDrafts[onyxKey]; + } + }); + + if (_.isEmpty(newReportActionsDrafts)) { + Log.info('[Migrate Onyx] Skipped migration RemoveEmptyReportActionsDrafts because there are no actions drafts to migrate'); + return resolve(); + } + + Log.info(`[Migrate Onyx] Ran migration RemoveEmptyReportActionsDrafts and updated drafts for ${_.keys(newReportActionsDrafts).length} reports`); + // eslint-disable-next-line rulesdir/prefer-actions-set-data + return Onyx.multiSet(newReportActionsDrafts).then(resolve); + }, + }); + }); +} From 374dd6cdfcb3645d107a9cea1e1083c7bc718723 Mon Sep 17 00:00:00 2001 From: Sam Hariri <137707942+samh-nl@users.noreply.github.com> Date: Fri, 22 Dec 2023 16:46:59 +0100 Subject: [PATCH 6/9] fix: change empty string to undefined --- .../home/report/ContextMenu/PopoverReportActionContextMenu.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/pages/home/report/ContextMenu/PopoverReportActionContextMenu.js b/src/pages/home/report/ContextMenu/PopoverReportActionContextMenu.js index 7f60b9d9b4d5..2bae8227ffde 100644 --- a/src/pages/home/report/ContextMenu/PopoverReportActionContextMenu.js +++ b/src/pages/home/report/ContextMenu/PopoverReportActionContextMenu.js @@ -17,7 +17,7 @@ function PopoverReportActionContextMenu(_props, ref) { const reportActionIDRef = useRef('0'); const originalReportIDRef = useRef('0'); const selectionRef = useRef(''); - const reportActionDraftMessageRef = useRef(''); + const reportActionDraftMessageRef = useRef(undefined); const cursorRelativePosition = useRef({ horizontal: 0, @@ -226,7 +226,7 @@ function PopoverReportActionContextMenu(_props, ref) { } selectionRef.current = ''; - reportActionDraftMessageRef.current = ''; + reportActionDraftMessageRef.current = undefined; setIsPopoverVisible(false); }; From 285a312486f85ba4794a0b9a87fe80a00306bc6d Mon Sep 17 00:00:00 2001 From: Sam Hariri <137707942+samh-nl@users.noreply.github.com> Date: Fri, 22 Dec 2023 17:50:41 +0100 Subject: [PATCH 7/9] style: remove unnecessary dependency --- src/pages/home/report/ReportActionItemMessageEdit.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/pages/home/report/ReportActionItemMessageEdit.js b/src/pages/home/report/ReportActionItemMessageEdit.js index 5cad80711bcb..06cccc607461 100644 --- a/src/pages/home/report/ReportActionItemMessageEdit.js +++ b/src/pages/home/report/ReportActionItemMessageEdit.js @@ -273,7 +273,7 @@ function ReportActionItemMessageEdit(props) { // We want to escape the draft message to differentiate the HTML from the report action and the HTML the user drafted. debouncedSaveDraft(_.escape(newDraft)); }, - [props.action.message, debouncedSaveDraft, debouncedUpdateFrequentlyUsedEmojis, props.preferredSkinTone, preferredLocale, selection.end], + [debouncedSaveDraft, debouncedUpdateFrequentlyUsedEmojis, props.preferredSkinTone, preferredLocale, selection.end], ); useEffect(() => { From 97a1be4cfd33b4d64313f01e828d1c7299a1dc55 Mon Sep 17 00:00:00 2001 From: Sam Hariri <137707942+samh-nl@users.noreply.github.com> Date: Sat, 23 Dec 2023 11:27:15 +0100 Subject: [PATCH 8/9] refactor: migrate to typescript --- .../RemoveEmptyReportActionsDrafts.js | 69 ----------------- .../RemoveEmptyReportActionsDrafts.ts | 76 +++++++++++++++++++ src/types/onyx/ReportActionsDraft.ts | 7 ++ src/types/onyx/ReportActionsDrafts.ts | 4 +- src/types/onyx/index.ts | 2 + 5 files changed, 86 insertions(+), 72 deletions(-) delete mode 100644 src/libs/migrations/RemoveEmptyReportActionsDrafts.js create mode 100644 src/libs/migrations/RemoveEmptyReportActionsDrafts.ts create mode 100644 src/types/onyx/ReportActionsDraft.ts diff --git a/src/libs/migrations/RemoveEmptyReportActionsDrafts.js b/src/libs/migrations/RemoveEmptyReportActionsDrafts.js deleted file mode 100644 index 586cca8ca1ed..000000000000 --- a/src/libs/migrations/RemoveEmptyReportActionsDrafts.js +++ /dev/null @@ -1,69 +0,0 @@ -import Onyx from 'react-native-onyx'; -import _ from 'underscore'; -import Log from '@libs/Log'; -import ONYXKEYS from '@src/ONYXKEYS'; - -/** - * This migration removes empty drafts from reportActionsDrafts, which was previously used to mark a draft as being non-existent (e.g. upon cancel). - * - * @returns {Promise} - */ -export default function () { - return new Promise((resolve) => { - const connectionID = Onyx.connect({ - key: ONYXKEYS.COLLECTION.REPORT_ACTIONS_DRAFTS, - waitForCollectionCallback: true, - callback: (allReportActionsDrafts) => { - Onyx.disconnect(connectionID); - - if (!allReportActionsDrafts) { - Log.info('[Migrate Onyx] Skipped migration RemoveEmptyReportActionsDrafts because there were no reportActionsDrafts'); - return resolve(); - } - - const newReportActionsDrafts = {}; - _.each(allReportActionsDrafts, (reportActionDrafts, onyxKey) => { - newReportActionsDrafts[onyxKey] = {}; - - // Whether there is at least one draft in this report that has to be migrated - let hasUnmigratedDraft = false; - - _.each(reportActionDrafts, (reportActionDraft, reportActionID) => { - // If the draft is a string, it means it hasn't been migrated yet - if (_.isString(reportActionDraft)) { - hasUnmigratedDraft = true; - Log.info(`[Migrate Onyx] Migrating draft for report action ${reportActionID}`); - - if (_.isEmpty(reportActionDraft)) { - Log.info(`[Migrate Onyx] Removing draft for report action ${reportActionID}`); - return; - } - - newReportActionsDrafts[onyxKey][reportActionID] = {message: reportActionDraft}; - } else { - // We've already migrated this draft, so keep the existing value - newReportActionsDrafts[onyxKey][reportActionID] = reportActionDraft; - } - }); - - if (_.isEmpty(newReportActionsDrafts[onyxKey])) { - // Clear if there are no drafts remaining - newReportActionsDrafts[onyxKey] = null; - } else if (!hasUnmigratedDraft) { - // All drafts for this report have already been migrated, there's no need to overwrite this onyx key with the same data - delete newReportActionsDrafts[onyxKey]; - } - }); - - if (_.isEmpty(newReportActionsDrafts)) { - Log.info('[Migrate Onyx] Skipped migration RemoveEmptyReportActionsDrafts because there are no actions drafts to migrate'); - return resolve(); - } - - Log.info(`[Migrate Onyx] Ran migration RemoveEmptyReportActionsDrafts and updated drafts for ${_.keys(newReportActionsDrafts).length} reports`); - // eslint-disable-next-line rulesdir/prefer-actions-set-data - return Onyx.multiSet(newReportActionsDrafts).then(resolve); - }, - }); - }); -} diff --git a/src/libs/migrations/RemoveEmptyReportActionsDrafts.ts b/src/libs/migrations/RemoveEmptyReportActionsDrafts.ts new file mode 100644 index 000000000000..d8816198e537 --- /dev/null +++ b/src/libs/migrations/RemoveEmptyReportActionsDrafts.ts @@ -0,0 +1,76 @@ +import _ from 'lodash'; +import Onyx, {OnyxEntry} from 'react-native-onyx'; +import Log from '@libs/Log'; +import ONYXKEYS from '@src/ONYXKEYS'; +import {ReportActionsDraft, ReportActionsDrafts} from '@src/types/onyx'; +import {isEmptyObject} from '@src/types/utils/EmptyObject'; + +type ReportActionsDraftsKey = `${typeof ONYXKEYS.COLLECTION.REPORT_ACTIONS_DRAFTS}${string}`; + +/** + * This migration removes empty drafts from reportActionsDrafts, which was previously used to mark a draft as being non-existent (e.g. upon cancel). + */ +export default function (): Promise { + return new Promise((resolve) => { + const connectionID = Onyx.connect({ + key: ONYXKEYS.COLLECTION.REPORT_ACTIONS_DRAFTS, + waitForCollectionCallback: true, + callback: (allReportActionsDrafts) => { + Onyx.disconnect(connectionID); + + if (!allReportActionsDrafts) { + Log.info('[Migrate Onyx] Skipped migration RemoveEmptyReportActionsDrafts because there were no reportActionsDrafts'); + return resolve(); + } + + const newReportActionsDrafts: Record> = {}; + Object.entries(allReportActionsDrafts).forEach(([onyxKey, reportActionDrafts]) => { + const newReportActionsDraftsForReport: Record = {}; + + // Whether there is at least one draft in this report that has to be migrated + let hasUnmigratedDraft = false; + + if (reportActionDrafts) { + Object.entries(reportActionDrafts).forEach(([reportActionID, reportActionDraft]) => { + // If the draft is a string, it means it hasn't been migrated yet + if (typeof reportActionDraft === 'string') { + hasUnmigratedDraft = true; + Log.info(`[Migrate Onyx] Migrating draft for report action ${reportActionID}`); + + if (_.isEmpty(reportActionDraft)) { + Log.info(`[Migrate Onyx] Removing draft for report action ${reportActionID}`); + return; + } + + newReportActionsDraftsForReport[reportActionID] = {message: reportActionDraft}; + } else { + // We've already migrated this draft, so keep the existing value + newReportActionsDraftsForReport[reportActionID] = reportActionDraft; + } + }); + } + + if (isEmptyObject(newReportActionsDraftsForReport)) { + Log.info('[Migrate Onyx] NO REMAINING'); + // Clear if there are no drafts remaining + newReportActionsDrafts[onyxKey as ReportActionsDraftsKey] = null; + } else if (hasUnmigratedDraft) { + // Only migrate if there are unmigrated drafts, there's no need to overwrite this onyx key with the same data + newReportActionsDrafts[onyxKey as ReportActionsDraftsKey] = newReportActionsDraftsForReport; + } + }); + + if (isEmptyObject(newReportActionsDrafts)) { + Log.info('[Migrate Onyx] Skipped migration RemoveEmptyReportActionsDrafts because there are no actions drafts to migrate'); + return resolve(); + } + + Log.info(`[Migrate Onyx] Updating drafts for ${Object.keys(newReportActionsDrafts).length} reports`); + Onyx.multiSet(newReportActionsDrafts).then(() => { + Log.info('[Migrate Onyx] Ran migration RemoveEmptyReportActionsDrafts successfully'); + resolve(); + }); + }, + }); + }); +} diff --git a/src/types/onyx/ReportActionsDraft.ts b/src/types/onyx/ReportActionsDraft.ts new file mode 100644 index 000000000000..41a701f16e71 --- /dev/null +++ b/src/types/onyx/ReportActionsDraft.ts @@ -0,0 +1,7 @@ +type ReportActionsDraft = + | { + message: string; + } + | string; + +export default ReportActionsDraft; diff --git a/src/types/onyx/ReportActionsDrafts.ts b/src/types/onyx/ReportActionsDrafts.ts index 34ccc977ef48..ad2782111144 100644 --- a/src/types/onyx/ReportActionsDrafts.ts +++ b/src/types/onyx/ReportActionsDrafts.ts @@ -1,6 +1,4 @@ -type ReportActionsDraft = { - message: string; -}; +import ReportActionsDraft from './ReportActionsDraft'; type ReportActionsDrafts = Record; diff --git a/src/types/onyx/index.ts b/src/types/onyx/index.ts index 229fd0a53158..45c47793c458 100644 --- a/src/types/onyx/index.ts +++ b/src/types/onyx/index.ts @@ -37,6 +37,7 @@ import ReimbursementAccountDraft from './ReimbursementAccountDraft'; import Report from './Report'; import ReportAction, {ReportActions} from './ReportAction'; import ReportActionReactions from './ReportActionReactions'; +import ReportActionsDraft from './ReportActionsDraft'; import ReportActionsDrafts from './ReportActionsDrafts'; import ReportMetadata from './ReportMetadata'; import ReportNextStep from './ReportNextStep'; @@ -107,6 +108,7 @@ export type { ReportAction, ReportActionReactions, ReportActions, + ReportActionsDraft, ReportActionsDrafts, ReportMetadata, ReportNextStep, From 4678d774e8eade1a28944f16ce48250e33308e07 Mon Sep 17 00:00:00 2001 From: Shubham Agrawal Date: Tue, 2 Jan 2024 11:34:52 +0530 Subject: [PATCH 9/9] fixed calendar picker test --- tests/unit/CalendarPickerTest.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/unit/CalendarPickerTest.js b/tests/unit/CalendarPickerTest.js index 9c5ea4bc72f6..e1c11fbb8ca8 100644 --- a/tests/unit/CalendarPickerTest.js +++ b/tests/unit/CalendarPickerTest.js @@ -1,5 +1,5 @@ import {fireEvent, render, within} from '@testing-library/react-native'; -import {addMonths, addYears, subYears} from 'date-fns'; +import {addMonths, addYears, subMonths, subYears} from 'date-fns'; import CalendarPicker from '../../src/components/DatePicker/CalendarPicker'; import CONST from '../../src/CONST'; import DateUtils from '../../src/libs/DateUtils'; @@ -73,7 +73,7 @@ describe('CalendarPicker', () => { fireEvent.press(getByTestId('prev-month-arrow')); - const prevMonth = new Date().getMonth() - 1; + const prevMonth = subMonths(new Date(), 1).getMonth(); expect(getByText(monthNames[prevMonth])).toBeTruthy(); });