From 070da0b22e13296a49508eae2a01cc7cc2448747 Mon Sep 17 00:00:00 2001 From: Andrii Vitiv Date: Sat, 18 Oct 2025 16:17:21 +0300 Subject: [PATCH 1/4] Validate message right before sending --- src/hooks/useHandleExceedMaxCommentLength.ts | 19 +++++----------- .../useHandleExceedMaxTaskTitleLength.ts | 1 + .../ReportActionCompose.tsx | 22 ++++++++++--------- .../report/ReportActionItemMessageEdit.tsx | 6 ++--- 4 files changed, 22 insertions(+), 26 deletions(-) diff --git a/src/hooks/useHandleExceedMaxCommentLength.ts b/src/hooks/useHandleExceedMaxCommentLength.ts index 2c4fa1fd1886..cec96b4ca8f6 100644 --- a/src/hooks/useHandleExceedMaxCommentLength.ts +++ b/src/hooks/useHandleExceedMaxCommentLength.ts @@ -1,23 +1,16 @@ import {useCallback, useState} from 'react'; -import * as ReportUtils from '@libs/ReportUtils'; +import {getCommentLength} from '@libs/ReportUtils'; import type {ParsingDetails} from '@libs/ReportUtils'; import CONST from '@src/CONST'; const useHandleExceedMaxCommentLength = () => { const [hasExceededMaxCommentLength, setHasExceededMaxCommentLength] = useState(false); - const validateCommentMaxLength = useCallback( - (value: string, parsingDetails?: ParsingDetails) => { - if (ReportUtils.getCommentLength(value, parsingDetails) <= CONST.MAX_COMMENT_LENGTH) { - if (hasExceededMaxCommentLength) { - setHasExceededMaxCommentLength(false); - } - return; - } - setHasExceededMaxCommentLength(true); - }, - [hasExceededMaxCommentLength], - ); + const validateCommentMaxLength = useCallback((value: string, parsingDetails?: ParsingDetails) => { + const exceeded = getCommentLength(value, parsingDetails) > CONST.MAX_COMMENT_LENGTH; + setHasExceededMaxCommentLength(exceeded); + return !exceeded; + }, []); return {hasExceededMaxCommentLength, validateCommentMaxLength, setHasExceededMaxCommentLength}; }; diff --git a/src/hooks/useHandleExceedMaxTaskTitleLength.ts b/src/hooks/useHandleExceedMaxTaskTitleLength.ts index bb792a5da8b4..75acd73280a4 100644 --- a/src/hooks/useHandleExceedMaxTaskTitleLength.ts +++ b/src/hooks/useHandleExceedMaxTaskTitleLength.ts @@ -7,6 +7,7 @@ const useHandleExceedMaxTaskTitleLength = () => { const validateTaskTitleMaxLength = useCallback((title: string) => { const exceeded = title ? title.length > CONST.TITLE_CHARACTER_LIMIT : false; setHasExceededMaxTitleLength(exceeded); + return !exceeded; }, []); return {hasExceededMaxTaskTitleLength, validateTaskTitleMaxLength, setHasExceededMaxTitleLength}; diff --git a/src/pages/home/report/ReportActionCompose/ReportActionCompose.tsx b/src/pages/home/report/ReportActionCompose/ReportActionCompose.tsx index 43abfdf3baf1..e831caaf81a1 100644 --- a/src/pages/home/report/ReportActionCompose/ReportActionCompose.tsx +++ b/src/pages/home/report/ReportActionCompose/ReportActionCompose.tsx @@ -377,22 +377,24 @@ function ReportActionCompose({ // useSharedValue on web doesn't support functions, so we need to wrap it in an object. const composerRefShared = useSharedValue<{ clear: (() => void) | undefined; - }>({clear: undefined}); + validate: (() => boolean) | undefined; + }>({clear: undefined, validate: undefined}); const handleSendMessage = useCallback(() => { 'worklet'; - const clearComposer = composerRefShared.get().clear; - if (!clearComposer) { - throw new Error('The composerRefShared.clear function is not set yet. This should never happen, and indicates a developer error.'); + const {clear, validate} = composerRefShared.get(); + + if (!clear || !validate) { + throw new Error('The composerRefShared.clear or composerRefShared.validate function is not set yet. This should never happen, and indicates a developer error.'); } - if (isSendDisabled) { + if (isSendDisabled || !validate()) { return; } // This will cause onCleared to be triggered where we actually send the message - clearComposer(); + clear(); }, [isSendDisabled, composerRefShared]); const measureComposer = useCallback( @@ -440,11 +442,10 @@ function ReportActionCompose({ if (taskCommentMatch) { const title = taskCommentMatch?.[3] ? taskCommentMatch[3].trim().replace(/\n/g, ' ') : ''; setHasExceededMaxCommentLength(false); - validateTaskTitleMaxLength(title); - } else { - setHasExceededMaxTitleLength(false); - validateCommentMaxLength(value, {reportID}); + return validateTaskTitleMaxLength(title); } + setHasExceededMaxTitleLength(false); + return validateCommentMaxLength(value, {reportID}); }, [setHasExceededMaxCommentLength, setHasExceededMaxTitleLength, validateTaskTitleMaxLength, validateCommentMaxLength, reportID], ); @@ -532,6 +533,7 @@ function ReportActionCompose({ composerRef.current = ref ?? undefined; composerRefShared.set({ clear: ref?.clear, + validate: debouncedValidate.flush.bind(debouncedValidate), }); }} suggestionsRef={suggestionsRef} diff --git a/src/pages/home/report/ReportActionItemMessageEdit.tsx b/src/pages/home/report/ReportActionItemMessageEdit.tsx index 1a138ef8bef9..2169d00c0163 100644 --- a/src/pages/home/report/ReportActionItemMessageEdit.tsx +++ b/src/pages/home/report/ReportActionItemMessageEdit.tsx @@ -43,7 +43,7 @@ import Parser from '@libs/Parser'; import ReportActionComposeFocusManager from '@libs/ReportActionComposeFocusManager'; import reportActionItemEventHandler from '@libs/ReportActionItemEventHandler'; import {getReportActionHtml, isDeletedAction} from '@libs/ReportActionsUtils'; -import {getCommentLength, getOriginalReportID} from '@libs/ReportUtils'; +import {getOriginalReportID} from '@libs/ReportUtils'; import setShouldShowComposeInputKeyboardAware from '@libs/setShouldShowComposeInputKeyboardAware'; import CONST from '@src/CONST'; import ONYXKEYS from '@src/ONYXKEYS'; @@ -297,7 +297,7 @@ function ReportActionItemMessageEdit({ */ const publishDraft = useCallback(() => { // Do nothing if draft exceed the character limit - if (getCommentLength(draft, {reportID}) > CONST.MAX_COMMENT_LENGTH) { + if (!debouncedValidateCommentMaxLength.flush()) { return; } @@ -311,7 +311,7 @@ function ReportActionItemMessageEdit({ } editReportComment(originalReport, action, trimmedNewDraft, Object.fromEntries(draftMessageVideoAttributeCache), isOriginalReportArchived, isOriginalParentReportArchived); deleteDraft(); - }, [reportID, action, deleteDraft, draft, originalReportID, isOriginalReportArchived, originalReport, isOriginalParentReportArchived]); + }, [reportID, action, deleteDraft, draft, originalReportID, isOriginalReportArchived, originalReport, isOriginalParentReportArchived, debouncedValidateCommentMaxLength]); /** * @param emoji From b16d297a956437708cc2cca9dc24620bf1d8ec82 Mon Sep 17 00:00:00 2001 From: Andrii Vitiv Date: Sun, 19 Oct 2025 12:28:38 +0300 Subject: [PATCH 2/4] Add tests for message length validation --- .../ReportActionCompose.tsx | 2 +- .../report/ReportActionItemMessageEdit.tsx | 2 + tests/ui/ReportActionComposeTest.tsx | 181 +++++++----------- tests/ui/ReportActionItemMessageEditTest.tsx | 124 ++++++++++++ 4 files changed, 197 insertions(+), 112 deletions(-) create mode 100644 tests/ui/ReportActionItemMessageEditTest.tsx diff --git a/src/pages/home/report/ReportActionCompose/ReportActionCompose.tsx b/src/pages/home/report/ReportActionCompose/ReportActionCompose.tsx index e831caaf81a1..db7afd596a97 100644 --- a/src/pages/home/report/ReportActionCompose/ReportActionCompose.tsx +++ b/src/pages/home/report/ReportActionCompose/ReportActionCompose.tsx @@ -637,4 +637,4 @@ ReportActionCompose.displayName = 'ReportActionCompose'; export default memo(ReportActionCompose); export {onSubmitAction}; -export type {SuggestionsRef, ComposerRef}; +export type {SuggestionsRef, ComposerRef, ReportActionComposeProps}; diff --git a/src/pages/home/report/ReportActionItemMessageEdit.tsx b/src/pages/home/report/ReportActionItemMessageEdit.tsx index 2169d00c0163..3e210ceb70c6 100644 --- a/src/pages/home/report/ReportActionItemMessageEdit.tsx +++ b/src/pages/home/report/ReportActionItemMessageEdit.tsx @@ -551,6 +551,7 @@ function ReportActionItemMessageEdit({ isGroupPolicyReport={isGroupPolicyReport} shouldCalculateCaretPosition onScroll={onSaveScrollAndHideSuggestionMenu} + testID="composer" /> @@ -613,3 +614,4 @@ function ReportActionItemMessageEdit({ ReportActionItemMessageEdit.displayName = 'ReportActionItemMessageEdit'; export default ReportActionItemMessageEdit; +export type {ReportActionItemMessageEditProps}; diff --git a/tests/ui/ReportActionComposeTest.tsx b/tests/ui/ReportActionComposeTest.tsx index 583cfe027ef5..097ae67fc414 100644 --- a/tests/ui/ReportActionComposeTest.tsx +++ b/tests/ui/ReportActionComposeTest.tsx @@ -1,5 +1,3 @@ -import {PortalProvider} from '@gorhom/portal'; -import {NavigationContainer} from '@react-navigation/native'; import type * as NativeNavigation from '@react-navigation/native'; import {act, fireEvent, render, screen, waitFor} from '@testing-library/react-native'; import React from 'react'; @@ -7,56 +5,28 @@ import Onyx from 'react-native-onyx'; import ComposeProviders from '@components/ComposeProviders'; import {LocaleContextProvider} from '@components/LocaleContextProvider'; import OnyxListItemProvider from '@components/OnyxListItemProvider'; -import {CurrentReportIDContextProvider} from '@hooks/useCurrentReportID'; -import createPlatformStackNavigator from '@libs/Navigation/PlatformStackNavigation/createPlatformStackNavigator'; -import type {ReportsSplitNavigatorParamList} from '@libs/Navigation/types'; -import ReportScreen from '@pages/home/ReportScreen'; +import {forceClearInput} from '@libs/ComponentUtils'; +import type {ReportActionComposeProps} from '@pages/home/report/ReportActionCompose/ReportActionCompose'; +import ReportActionCompose, {onSubmitAction} from '@pages/home/report/ReportActionCompose/ReportActionCompose'; import CONST from '@src/CONST'; import ONYXKEYS from '@src/ONYXKEYS'; -import SCREENS from '@src/SCREENS'; +import * as LHNTestUtils from '../utils/LHNTestUtils'; import * as TestHelper from '../utils/TestHelper'; import waitForBatchedUpdatesWithAct from '../utils/waitForBatchedUpdatesWithAct'; -jest.mock('expo-image-manipulator', () => ({ - manipulateAsync: jest.fn(), -})); +const mockForceClearInput = jest.mocked(forceClearInput); -jest.mock('expo-image', () => ({ - Image: () => null, +jest.mock('@libs/ComponentUtils', () => ({ + forceClearInput: jest.fn(), })); -jest.mock('expo-av', () => ({ - Video: () => null, - ResizeMode: {COVER: 'cover'}, - VideoFullscreenUpdate: {}, -})); -jest.mock('pusher-js', () => ({ - Pusher: { - subscribe: jest.fn(() => ({ - bind: jest.fn(), - unbind: jest.fn(), - })), - unsubscribe: jest.fn(), - }, -})); +jest.mock('@hooks/useLocalize', () => + jest.fn(() => ({ + translate: jest.fn((key: string) => key), + numberFormat: jest.fn((num: number) => num.toString()), + })), +); -// Mock dependencies -jest.mock('@libs/ReportUtils', () => ({ - // eslint-disable-next-line @typescript-eslint/consistent-type-imports - ...((): typeof import('@libs/ReportUtils') => { - return jest.requireActual('@libs/ReportUtils'); - })(), - canUserPerformWriteAction: jest.fn(() => true), - isChatRoom: jest.fn(() => false), - isGroupChat: jest.fn(() => false), - isSettled: jest.fn(() => false), - isReportApproved: jest.fn(() => false), - isMoneyRequestAction: jest.fn(() => false), - isSentMoneyReportAction: jest.fn(() => false), - isSelfDM: jest.fn(() => false), - getParentReport: jest.fn(() => ({})), - temporaryGetMoneyRequestOptions: jest.fn(() => []), -})); jest.mock('@react-navigation/native', () => ({ ...((): typeof NativeNavigation => { return jest.requireActual('@react-navigation/native'); @@ -71,57 +41,23 @@ jest.mock('@react-navigation/native', () => ({ TestHelper.setupGlobalFetchMock(); -const Stack = createPlatformStackNavigator(); - -// Constants for test data -const REPORT_ID = '1'; -const POLICY_ID = 'policy1'; -const USER_EMAIL = 'user1@example.com'; -const mockReport = { - reportID: REPORT_ID, - policyID: POLICY_ID, - participants: {}, - type: CONST.REPORT.TYPE.CHAT, -}; - -const mockPersonalDetailsList = { - [USER_EMAIL]: { - login: USER_EMAIL, - displayName: 'User One', - firstName: 'User', - lastName: 'One', - }, -}; -const mockReportActions = { - [REPORT_ID]: {}, +const defaultReport = LHNTestUtils.getFakeReport(); +const defaultProps: ReportActionComposeProps = { + onSubmit: jest.fn(), + isComposerFullSize: false, + reportID: defaultReport.reportID, + report: defaultReport, }; -// Helper function to set up Onyx data -const setupOnyxData = async () => { - await act(async () => { - await Onyx.merge(ONYXKEYS.SHOULD_SHOW_COMPOSE_INPUT, true); - await Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT}${REPORT_ID}`, mockReport); - await Onyx.merge(`${ONYXKEYS.COLLECTION.POLICY}${POLICY_ID}`, null); - await Onyx.merge(ONYXKEYS.PERSONAL_DETAILS_LIST, mockPersonalDetailsList); - await Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${REPORT_ID}`, mockReportActions[REPORT_ID]); - }); -}; - -// Helper function to render the page -const renderPage = (initialRouteName: typeof SCREENS.REPORT, initialParams: {reportID: string; onSubmit: () => void}) => { +const renderReportActionCompose = (props?: Partial) => { return render( - - - - - - - - + + , ); }; @@ -141,10 +77,6 @@ describe('ReportActionCompose Integration Tests', () => { }); }); - beforeEach(async () => { - await setupOnyxData(); - }); - afterEach(async () => { await act(async () => { await Onyx.clear(); @@ -154,8 +86,7 @@ describe('ReportActionCompose Integration Tests', () => { describe('Paste Behavior with Selection updateComment logic', () => { it('should format pasted URL as Markdown link when text is selected', async () => { - const onSubmit = jest.fn(); - const {unmount} = renderPage(SCREENS.REPORT, {reportID: REPORT_ID, onSubmit}); + const {unmount} = renderReportActionCompose(); await waitForBatchedUpdatesWithAct(); const composer = screen.getByTestId('composer'); @@ -172,8 +103,7 @@ describe('ReportActionCompose Integration Tests', () => { }); it('should insert raw URL when no text is selected', async () => { - const onSubmit = jest.fn(); - const {unmount} = renderPage(SCREENS.REPORT, {reportID: REPORT_ID, onSubmit}); + const {unmount} = renderReportActionCompose(); await waitForBatchedUpdatesWithAct(); const composer = screen.getByTestId('composer'); @@ -189,8 +119,7 @@ describe('ReportActionCompose Integration Tests', () => { }); it('should insert raw text when non-URL text is pasted', async () => { - const onSubmit = jest.fn(); - const {unmount} = renderPage(SCREENS.REPORT, {reportID: REPORT_ID, onSubmit}); + const {unmount} = renderReportActionCompose(); await waitForBatchedUpdatesWithAct(); const composer = screen.getByTestId('composer'); @@ -210,8 +139,7 @@ describe('ReportActionCompose Integration Tests', () => { }); it('should format pasted URL as Markdown link when replacing entire selected text', async () => { - const onSubmit = jest.fn(); - const {unmount} = renderPage(SCREENS.REPORT, {reportID: REPORT_ID, onSubmit}); + const {unmount} = renderReportActionCompose(); await waitForBatchedUpdatesWithAct(); const composer = screen.getByTestId('composer'); @@ -228,8 +156,7 @@ describe('ReportActionCompose Integration Tests', () => { }); it('should insert raw URL with emoji when pasted with selection', async () => { - const onSubmit = jest.fn(); - const {unmount} = renderPage(SCREENS.REPORT, {reportID: REPORT_ID, onSubmit}); + const {unmount} = renderReportActionCompose(); await waitForBatchedUpdatesWithAct(); const composer = screen.getByTestId('composer'); @@ -249,8 +176,7 @@ describe('ReportActionCompose Integration Tests', () => { }); it('should format pasted URL as Markdown link when selected text contains square brackets', async () => { - const onSubmit = jest.fn(); - const {unmount} = renderPage(SCREENS.REPORT, {reportID: REPORT_ID, onSubmit}); + const {unmount} = renderReportActionCompose(); await waitForBatchedUpdatesWithAct(); const composer = screen.getByTestId('composer'); @@ -267,8 +193,7 @@ describe('ReportActionCompose Integration Tests', () => { }); it('should format pasted URL as Markdown link when selected text contains parentheses', async () => { - const onSubmit = jest.fn(); - const {unmount} = renderPage(SCREENS.REPORT, {reportID: REPORT_ID, onSubmit}); + const {unmount} = renderReportActionCompose(); await waitForBatchedUpdatesWithAct(); const composer = screen.getByTestId('composer'); @@ -285,8 +210,7 @@ describe('ReportActionCompose Integration Tests', () => { }); it('should format pasted URL as Markdown link when selected text contains curly braces', async () => { - const onSubmit = jest.fn(); - const {unmount} = renderPage(SCREENS.REPORT, {reportID: REPORT_ID, onSubmit}); + const {unmount} = renderReportActionCompose(); await waitForBatchedUpdatesWithAct(); const composer = screen.getByTestId('composer'); @@ -302,4 +226,39 @@ describe('ReportActionCompose Integration Tests', () => { await waitForBatchedUpdatesWithAct(); }); }); + + describe('Message validation', () => { + it('should send when length is within the limit', async () => { + renderReportActionCompose(); + const composer = screen.getByTestId('composer'); + + // Given a message that is within the length limit + const validMessage = 'x'.repeat(CONST.MAX_COMMENT_LENGTH); + fireEvent.changeText(composer, validMessage); + + // When the message is submitted + act(onSubmitAction); + + // Then the message should be sent + expect(mockForceClearInput).toHaveBeenCalledTimes(1); + }); + + it('should not send when length exceeds the limit', async () => { + renderReportActionCompose(); + const composer = screen.getByTestId('composer'); + + // Given a message that is over the length limit + const invalidMessage = 'x'.repeat(CONST.MAX_COMMENT_LENGTH + 1); + fireEvent.changeText(composer, invalidMessage); + + // When the message is submitted + act(onSubmitAction); + + // Then the message should NOT be sent + expect(mockForceClearInput).toHaveBeenCalledTimes(0); + + // And the error should be displayed + expect(screen.getByText('composer.commentExceededMaxLength')).toBeOnTheScreen(); + }); + }); }); diff --git a/tests/ui/ReportActionItemMessageEditTest.tsx b/tests/ui/ReportActionItemMessageEditTest.tsx new file mode 100644 index 000000000000..13e76bf49e65 --- /dev/null +++ b/tests/ui/ReportActionItemMessageEditTest.tsx @@ -0,0 +1,124 @@ +import type * as NativeNavigation from '@react-navigation/native'; +import {act, fireEvent, render, screen} from '@testing-library/react-native'; +import React from 'react'; +import Onyx from 'react-native-onyx'; +import ComposeProviders from '@components/ComposeProviders'; +import {LocaleContextProvider} from '@components/LocaleContextProvider'; +import OnyxListItemProvider from '@components/OnyxListItemProvider'; +import {editReportComment} from '@libs/actions/Report'; +import {translateLocal} from '@libs/Localize'; +import ReportActionItemMessageEdit from '@pages/home/report/ReportActionItemMessageEdit'; +import type {ReportActionItemMessageEditProps} from '@pages/home/report/ReportActionItemMessageEdit'; +import CONST from '@src/CONST'; +import ONYXKEYS from '@src/ONYXKEYS'; +import * as LHNTestUtils from '../utils/LHNTestUtils'; +import * as TestHelper from '../utils/TestHelper'; + +const mockEditReportComment = jest.mocked(editReportComment); + +jest.mock('@libs/actions/Report', () => { + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + const actual = jest.requireActual('@libs/actions/Report'); + // eslint-disable-next-line @typescript-eslint/no-unsafe-return + return { + ...actual, + editReportComment: jest.fn(), + }; +}); + +jest.mock('@hooks/useLocalize', () => + jest.fn(() => ({ + translate: jest.fn((key: string) => key), + numberFormat: jest.fn((num: number) => num.toString()), + })), +); + +jest.mock('@react-navigation/native', () => ({ + ...((): typeof NativeNavigation => { + return jest.requireActual('@react-navigation/native'); + })(), + useNavigation: jest.fn(() => ({ + navigate: jest.fn(), + addListener: jest.fn(() => jest.fn()), + })), + useIsFocused: jest.fn(() => true), + useRoute: jest.fn(() => ({key: '', name: '', params: {reportID: '1'}})), +})); + +TestHelper.setupGlobalFetchMock(); + +const defaultReport = LHNTestUtils.getFakeReport(); +const defaultProps: ReportActionItemMessageEditProps = { + action: LHNTestUtils.getFakeReportAction(), + draftMessage: '', + reportID: defaultReport.reportID, + originalReportID: defaultReport.reportID, + index: 0, + isGroupPolicyReport: false, +}; + +const renderReportActionItemMessageEdit = (props?: Partial) => { + return render( + + + , + ); +}; + +describe('ReportActionCompose Integration Tests', () => { + beforeAll(() => { + Onyx.init({ + keys: ONYXKEYS, + evictableKeys: [ONYXKEYS.COLLECTION.REPORT_ACTIONS], + }); + }); + + afterEach(async () => { + await act(async () => { + await Onyx.clear(); + }); + jest.clearAllMocks(); + }); + + describe('Message validation', () => { + it('should edit when length is within the limit', async () => { + renderReportActionItemMessageEdit(); + const composer = screen.getByTestId('composer'); + const saveChangesButton = screen.getByLabelText(translateLocal('common.saveChanges')); + + // Given a message that is within the length limit + const validMessage = 'x'.repeat(CONST.MAX_COMMENT_LENGTH); + fireEvent.changeText(composer, validMessage); + + // When the message is saved + fireEvent.press(saveChangesButton); + + // Then the message should be edited + expect(mockEditReportComment).toHaveBeenCalledTimes(1); + }); + + it('should not edit when length exceeds the limit', async () => { + renderReportActionItemMessageEdit(); + const composer = screen.getByTestId('composer'); + const saveChangesButton = screen.getByLabelText('common.saveChanges'); + + // Given a message that is over the length limit + const invalidMessage = 'x'.repeat(CONST.MAX_COMMENT_LENGTH + 1); + fireEvent.changeText(composer, invalidMessage); + + // When the message is saved + fireEvent.press(saveChangesButton); + + // Then the message should NOT be edited + expect(mockEditReportComment).toHaveBeenCalledTimes(0); + + // And the error should be displayed + expect(screen.getByText('composer.commentExceededMaxLength')).toBeOnTheScreen(); + }); + }); +}); From 8fb5ac1ddee65a8147b49f6fa24270a22086c399 Mon Sep 17 00:00:00 2001 From: Andrii Vitiv Date: Sun, 19 Oct 2025 16:55:58 +0300 Subject: [PATCH 3/4] Fix flush is called on non-js thread --- .../ReportActionCompose.tsx | 60 +++++++++---------- .../report/ReportActionCompose/SendButton.tsx | 8 ++- 2 files changed, 35 insertions(+), 33 deletions(-) diff --git a/src/pages/home/report/ReportActionCompose/ReportActionCompose.tsx b/src/pages/home/report/ReportActionCompose/ReportActionCompose.tsx index db7afd596a97..d20636205969 100644 --- a/src/pages/home/report/ReportActionCompose/ReportActionCompose.tsx +++ b/src/pages/home/report/ReportActionCompose/ReportActionCompose.tsx @@ -373,29 +373,46 @@ function ReportActionCompose({ const isSendDisabled = isCommentEmpty || isBlockedFromConcierge || !!exceededMaxLength; + const validateMaxLength = useCallback( + (value: string) => { + const taskCommentMatch = value?.match(CONST.REGEX.TASK_TITLE_WITH_OPTIONAL_SHORT_MENTION); + if (taskCommentMatch) { + const title = taskCommentMatch?.[3] ? taskCommentMatch[3].trim().replace(/\n/g, ' ') : ''; + setHasExceededMaxCommentLength(false); + return validateTaskTitleMaxLength(title); + } + setHasExceededMaxTitleLength(false); + return validateCommentMaxLength(value, {reportID}); + }, + [setHasExceededMaxCommentLength, setHasExceededMaxTitleLength, validateTaskTitleMaxLength, validateCommentMaxLength, reportID], + ); + + const debouncedValidate = useMemo(() => lodashDebounce(validateMaxLength, CONST.TIMING.COMMENT_LENGTH_DEBOUNCE_TIME, {leading: true}), [validateMaxLength]); + // Note: using JS refs is not well supported in reanimated, thus we need to store the function in a shared value // useSharedValue on web doesn't support functions, so we need to wrap it in an object. const composerRefShared = useSharedValue<{ clear: (() => void) | undefined; - validate: (() => boolean) | undefined; - }>({clear: undefined, validate: undefined}); + }>({clear: undefined}); const handleSendMessage = useCallback(() => { - 'worklet'; + if (isSendDisabled || !debouncedValidate.flush()) { + return; + } - const {clear, validate} = composerRefShared.get(); + runOnUI(() => { + 'worklet'; - if (!clear || !validate) { - throw new Error('The composerRefShared.clear or composerRefShared.validate function is not set yet. This should never happen, and indicates a developer error.'); - } + const {clear: clearComposer} = composerRefShared.get(); - if (isSendDisabled || !validate()) { - return; - } + if (!clearComposer) { + throw new Error('The composerRefShared.clear function is not set yet. This should never happen, and indicates a developer error.'); + } - // This will cause onCleared to be triggered where we actually send the message - clear(); - }, [isSendDisabled, composerRefShared]); + // This will cause onCleared to be triggered where we actually send the message + clearComposer?.(); + })(); + }, [isSendDisabled, debouncedValidate, composerRefShared]); const measureComposer = useCallback( (e: LayoutChangeEvent) => { @@ -436,22 +453,6 @@ function ReportActionCompose({ return reportActionComposeHeight - emojiOffsetWithComposeBox - CONST.MENU_POSITION_REPORT_ACTION_COMPOSE_BOTTOM; }, [emojiPositionValues]); - const validateMaxLength = useCallback( - (value: string) => { - const taskCommentMatch = value?.match(CONST.REGEX.TASK_TITLE_WITH_OPTIONAL_SHORT_MENTION); - if (taskCommentMatch) { - const title = taskCommentMatch?.[3] ? taskCommentMatch[3].trim().replace(/\n/g, ' ') : ''; - setHasExceededMaxCommentLength(false); - return validateTaskTitleMaxLength(title); - } - setHasExceededMaxTitleLength(false); - return validateCommentMaxLength(value, {reportID}); - }, - [setHasExceededMaxCommentLength, setHasExceededMaxTitleLength, validateTaskTitleMaxLength, validateCommentMaxLength, reportID], - ); - - const debouncedValidate = useMemo(() => lodashDebounce(validateMaxLength, CONST.TIMING.COMMENT_LENGTH_DEBOUNCE_TIME, {leading: true}), [validateMaxLength]); - const onValueChange = useCallback( (value: string) => { if (value.length === 0 && isComposerFullSize) { @@ -533,7 +534,6 @@ function ReportActionCompose({ composerRef.current = ref ?? undefined; composerRefShared.set({ clear: ref?.clear, - validate: debouncedValidate.flush.bind(debouncedValidate), }); }} suggestionsRef={suggestionsRef} diff --git a/src/pages/home/report/ReportActionCompose/SendButton.tsx b/src/pages/home/report/ReportActionCompose/SendButton.tsx index 0056a024f549..9505d28ef4fa 100644 --- a/src/pages/home/report/ReportActionCompose/SendButton.tsx +++ b/src/pages/home/report/ReportActionCompose/SendButton.tsx @@ -26,9 +26,11 @@ function SendButton({isDisabled: isDisabledProp, handleSendMessage}: SendButtonP // We need to use isSmallScreenWidth instead of shouldUseNarrowLayout to manage GestureDetector correctly // eslint-disable-next-line rulesdir/prefer-shouldUseNarrowLayout-instead-of-isSmallScreenWidth const {isSmallScreenWidth} = useResponsiveLayout(); - const Tap = Gesture.Tap().onEnd(() => { - handleSendMessage(); - }); + const Tap = Gesture.Tap() + .onEnd(() => { + handleSendMessage(); + }) + .runOnJS(true); return ( Date: Wed, 22 Oct 2025 19:15:29 +0300 Subject: [PATCH 4/4] Remove deprecated translateLocal Not needed anyway because we have a mock --- tests/ui/ReportActionItemMessageEditTest.tsx | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/tests/ui/ReportActionItemMessageEditTest.tsx b/tests/ui/ReportActionItemMessageEditTest.tsx index 13e76bf49e65..868b555d35f7 100644 --- a/tests/ui/ReportActionItemMessageEditTest.tsx +++ b/tests/ui/ReportActionItemMessageEditTest.tsx @@ -6,7 +6,6 @@ import ComposeProviders from '@components/ComposeProviders'; import {LocaleContextProvider} from '@components/LocaleContextProvider'; import OnyxListItemProvider from '@components/OnyxListItemProvider'; import {editReportComment} from '@libs/actions/Report'; -import {translateLocal} from '@libs/Localize'; import ReportActionItemMessageEdit from '@pages/home/report/ReportActionItemMessageEdit'; import type {ReportActionItemMessageEditProps} from '@pages/home/report/ReportActionItemMessageEdit'; import CONST from '@src/CONST'; @@ -89,7 +88,7 @@ describe('ReportActionCompose Integration Tests', () => { it('should edit when length is within the limit', async () => { renderReportActionItemMessageEdit(); const composer = screen.getByTestId('composer'); - const saveChangesButton = screen.getByLabelText(translateLocal('common.saveChanges')); + const saveChangesButton = screen.getByLabelText('common.saveChanges'); // Given a message that is within the length limit const validMessage = 'x'.repeat(CONST.MAX_COMMENT_LENGTH);