Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Task Title Validation on Main Composer Text Change #52941

Merged
Show file tree
Hide file tree
Changes from 15 commits
Commits
Show all changes
27 commits
Select commit Hold shift + click to select a range
9c825da
Add task specific max length validation
wildan-m Nov 4, 2024
bd3a70e
remove unnecessary comment
wildan-m Nov 4, 2024
bee1a66
Merge branch 'main' of https://github.com/wildan-m/App into wildan/fi…
wildan-m Nov 6, 2024
faf4370
Merge branch 'main' of https://github.com/wildan-m/App into wildan/fi…
wildan-m Nov 21, 2024
bcbde08
put most logic to useHandleExceedMaxCommentLength
wildan-m Nov 21, 2024
0e5325d
Merge branch 'main' of https://github.com/wildan-m/App into wildan/fi…
wildan-m Nov 22, 2024
f90ce91
Use separate hooks to validate max title length
wildan-m Nov 22, 2024
a3bd4bf
add hasExceededMaxTitleLength dependency
wildan-m Nov 22, 2024
3d40a79
change debounce time to const
wildan-m Nov 22, 2024
dd65326
change exceededMaxLength to state
wildan-m Nov 22, 2024
cb37156
Merge branch 'main' of https://github.com/wildan-m/App into wildan/fi…
wildan-m Nov 23, 2024
2c3b86d
Update src/CONST.ts
wildan-m Nov 23, 2024
708adbf
Use separate text for task title validation message
wildan-m Nov 23, 2024
0c20987
Merge branch 'wildan/fix/50398-fix-max-length-validation-for-task' of…
wildan-m Nov 23, 2024
5c51ae8
Merge branch 'main' of https://github.com/wildan-m/App into wildan/fi…
wildan-m Nov 25, 2024
ed1b95d
Update src/pages/home/report/ReportActionCompose/ReportActionCompose.tsx
wildan-m Nov 26, 2024
867f77b
Merge branch 'main' of https://github.com/wildan-m/App into wildan/fi…
wildan-m Nov 26, 2024
c3c0796
Refactor
wildan-m Nov 26, 2024
58bbcbe
refactor for better readability
wildan-m Nov 26, 2024
36253a8
Merge branch 'main' of https://github.com/wildan-m/App into wildan/fi…
wildan-m Nov 27, 2024
41c3215
extract debounce, refactor
wildan-m Nov 27, 2024
3f08b65
Remove unnecessary state
wildan-m Nov 28, 2024
dc57914
Merge branch 'main' of https://github.com/wildan-m/App into wildan/fi…
wildan-m Nov 28, 2024
ad2272d
resolve performance issue
wildan-m Nov 28, 2024
e638474
Merge branch 'main' of https://github.com/wildan-m/App into wildan/fi…
wildan-m Dec 2, 2024
e63f27a
Merge branch 'main' of https://github.com/wildan-m/App into wildan/fi…
wildan-m Dec 3, 2024
36e4c3e
Add optional chain
wildan-m Dec 3, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions src/CONST.ts
Original file line number Diff line number Diff line change
Expand Up @@ -294,6 +294,9 @@ type OnboardingMessage = {
type?: string;
};

const EMAIL_WITH_OPTIONAL_DOMAIN =
/(?=((?=[\w'#%+-]+(?:\.[\w'#%+-]+)*@?)[\w.'#%+-]{1,64}(?:@(?:(?=[a-z\d]+(?:-+[a-z\d]+)*\.)(?:[a-z\d-]{1,63}\.)+[a-z]{2,63}))?(?= |_|\b))(?<end>.*))\S{3,254}(?=\k<end>$)/;

const CONST = {
HEIC_SIGNATURES: [
'6674797068656963', // 'ftypheic' - Indicates standard HEIC file
Expand Down Expand Up @@ -3036,6 +3039,14 @@ const CONST = {
get EXPENSIFY_POLICY_DOMAIN_NAME() {
return new RegExp(`${EXPENSIFY_POLICY_DOMAIN}([a-zA-Z0-9]+)\\${EXPENSIFY_POLICY_DOMAIN_EXTENSION}`);
},

/**
* Matching task rule by group
* Group 1: Start task rule with []
* Group 2: Optional email group between \s+....\s* start rule with @+valid email or short mention
* Group 3: Title is remaining characters
*/
TASK_TITLE_WITH_OPTONAL_SHORT_MENTION: `^\\[\\]\\s+(?:@(?:${EMAIL_WITH_OPTIONAL_DOMAIN}))?\\s*([\\s\\S]*)`,
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

},

PRONOUNS: {
Expand Down
12 changes: 9 additions & 3 deletions src/components/ExceededCommentLength.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,20 +4,26 @@ import useThemeStyles from '@hooks/useThemeStyles';
import CONST from '@src/CONST';
import Text from './Text';

function ExceededCommentLength() {
type ExceededCommentLengthProps = {
maxCommentLength?: number;
isTaskTitle?: boolean;
};

function ExceededCommentLength({maxCommentLength = CONST.MAX_COMMENT_LENGTH, isTaskTitle}: ExceededCommentLengthProps) {
const styles = useThemeStyles();
const {numberFormat, translate} = useLocalize();

const translationKey = isTaskTitle ? 'composer.taskTitleExceededMaxLength' : 'composer.commentExceededMaxLength';

return (
<Text
style={[styles.textMicro, styles.textDanger, styles.chatItemComposeSecondaryRow, styles.mlAuto, styles.pl2]}
numberOfLines={1}
>
{translate('composer.commentExceededMaxLength', {formattedMaxLength: numberFormat(CONST.MAX_COMMENT_LENGTH)})}
{translate(translationKey, {formattedMaxLength: numberFormat(maxCommentLength)})}
</Text>
);
}

ExceededCommentLength.displayName = 'ExceededCommentLength';

export default memo(ExceededCommentLength);
25 changes: 25 additions & 0 deletions src/hooks/useHandleExceedMaxTaskTitleLength.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import debounce from 'lodash/debounce';
import {useCallback, useMemo, useState} from 'react';
import CONST from '@src/CONST';

const useHandleExceedMaxTaskTitleLength = () => {
const [hasExceededMaxTitleLength, setHasExceededMaxTitleLength] = useState(false);

const handleValueChange = useCallback((value: string) => {
const match = value.match(CONST.REGEX.TASK_TITLE_WITH_OPTONAL_SHORT_MENTION);
if (match) {
const title = match[3] ? match[3].trim().replace(/\n/g, ' ') : undefined;
const exceeded = title ? title.length > CONST.TITLE_CHARACTER_LIMIT : false;
setHasExceededMaxTitleLength(exceeded);
return true;
}
setHasExceededMaxTitleLength(false);
return false;
}, []);

const validateTitleMaxLength = useMemo(() => debounce(handleValueChange, CONST.TIMING.COMMENT_LENGTH_DEBOUNCE_TIME, {leading: true}), [handleValueChange]);

return {hasExceededMaxTitleLength, validateTitleMaxLength};
};

export default useHandleExceedMaxTaskTitleLength;
1 change: 1 addition & 0 deletions src/languages/en.ts
Original file line number Diff line number Diff line change
Expand Up @@ -524,6 +524,7 @@ const translations = {
noExtensionFoundForMimeType: 'No extension found for mime type',
problemGettingImageYouPasted: 'There was a problem getting the image you pasted',
commentExceededMaxLength: ({formattedMaxLength}: FormattedMaxLengthParams) => `The maximum comment length is ${formattedMaxLength} characters.`,
taskTitleExceededMaxLength: ({formattedMaxLength}: FormattedMaxLengthParams) => `The maximum task title length is ${formattedMaxLength} characters.`,
},
baseUpdateAppModal: {
updateApp: 'Update app',
Expand Down
1 change: 1 addition & 0 deletions src/languages/es.ts
Original file line number Diff line number Diff line change
Expand Up @@ -515,6 +515,7 @@ const translations = {
noExtensionFoundForMimeType: 'No se encontró una extension para este tipo de contenido',
problemGettingImageYouPasted: 'Ha ocurrido un problema al obtener la imagen que has pegado',
commentExceededMaxLength: ({formattedMaxLength}: FormattedMaxLengthParams) => `El comentario debe tener máximo ${formattedMaxLength} caracteres.`,
taskTitleExceededMaxLength: ({formattedMaxLength}: FormattedMaxLengthParams) => `La longitud máxima del título de una tarea es de ${formattedMaxLength} caracteres.`,
},
baseUpdateAppModal: {
updateApp: 'Actualizar app',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import EducationalTooltip from '@components/Tooltip/EducationalTooltip';
import useCurrentUserPersonalDetails from '@hooks/useCurrentUserPersonalDetails';
import useDebounce from '@hooks/useDebounce';
import useHandleExceedMaxCommentLength from '@hooks/useHandleExceedMaxCommentLength';
import useHandleExceedMaxTaskTitleLength from '@hooks/useHandleExceedMaxTaskTitleLength';
import useLocalize from '@hooks/useLocalize';
import useNetwork from '@hooks/useNetwork';
import useResponsiveLayout from '@hooks/useResponsiveLayout';
Expand Down Expand Up @@ -172,6 +173,8 @@ function ReportActionCompose({
* Shows red borders and prevents the comment from being sent
*/
const {hasExceededMaxCommentLength, validateCommentMaxLength} = useHandleExceedMaxCommentLength();
const {hasExceededMaxTitleLength, validateTitleMaxLength} = useHandleExceedMaxTaskTitleLength();
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
const {hasExceededMaxTitleLength, validateTitleMaxLength} = useHandleExceedMaxTaskTitleLength();
const {hasExceededMaxTaskTitleLength, validateTaskTitleMaxLength} = useHandleExceedMaxTaskTitleLength();

Can we name it more specific to task title? 🤔

Copy link
Contributor Author

@wildan-m wildan-m Nov 26, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we name it more specific to task title?

sure

Copy link
Contributor Author

@wildan-m wildan-m Nov 26, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think it's a good idea to check conditions based on result of a debounce function. It's better if we detect comment format and use properly validation function here

@hoangzinh In my opinion using a separate variable like isCreatingTaskComment would be redundant as we already perform regex matching in useHandleExceedMaxTaskTitleLength. If we implement leading true, it should be safe. But let me know if we still need to do that.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we can move regrex matching out of useHandleExceedMaxTaskTitleLength hook. And add another wrapper debounce for validation methods like this. I think it works better. What do you think?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@hoangzinh after test it might looks like this

src/pages/home/report/ReportActionCompose/ReportActionCompose.tsx

    const onValueChange = useCallback(
        (value: string) => {
            if (value.length === 0 && isComposerFullSize) {
                Report.setIsComposerFullSize(reportID, false);
            }

            const taskCommentMatch = value.match(CONST.REGEX.TASK_TITLE_WITH_OPTONAL_SHORT_MENTION);
            if (taskCommentMatch) {
                const title = taskCommentMatch?.[3] ? taskCommentMatch[3].trim().replace(/\n/g, ' ') : '';
                validateTaskTitleMaxLength(title);
            } else {
                validateCommentMaxLength(value, {reportID});
            }
        },
        [isComposerFullSize, reportID, validateCommentMaxLength, validateTaskTitleMaxLength],
    );

src/hooks/useHandleExceedMaxTaskTitleLength.ts

const useHandleExceedMaxTaskTitleLength = () => {
    const [hasExceededMaxTaskTitleLength, setHasExceededMaxTitleLength] = useState(false);

    const handleValueChange = useCallback((title: string) => {
        const exceeded = title ? title.length > CONST.TITLE_CHARACTER_LIMIT : false;
        setHasExceededMaxTitleLength(exceeded);
    }, []);

    const validateTaskTitleMaxLength = useMemo(() => debounce(handleValueChange, CONST.TIMING.COMMENT_LENGTH_DEBOUNCE_TIME, {leading: true}), [handleValueChange]);

    return {hasExceededMaxTaskTitleLength, validateTaskTitleMaxLength};
};

proceed with the above change? or alternatively we can keep current useHandleExceedMaxTaskTitleLength logic but no need to debounce it?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

you're right @wildan-m . Hmm, what do you think if we refactor it a bit:

  1. Move 1500 as a constant
  2. Remove debounce in 2 above hooks
  3. Add a debounce where it's used.

So in main-composer, we will use 1500 as a debounce time for both plain function validations above. And in edit composer, we will have another debounce with 1500ms.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@hoangzinh if we're going to extract the debounce and not need faster debounce specific for task title, how about keeping the regex matching inside the hook?

const useHandleExceedMaxTaskTitleLength = () => {
    const [hasExceededMaxTaskTitleLength, setHasExceededMaxTitleLength] = useState(false);

    const validateTaskTitleMaxLength = useCallback((value: string) => {
        const match = value.match(CONST.REGEX.TASK_TITLE_WITH_OPTONAL_SHORT_MENTION);
        if (match) {
            const title = match[3] ? match[3].trim().replace(/\n/g, ' ') : undefined;
            const exceeded = title ? title.length > CONST.TITLE_CHARACTER_LIMIT : false;
            setHasExceededMaxTitleLength(exceeded);
            return true;
        }
        setHasExceededMaxTitleLength(false);
        return false;
    }, []);

    return {hasExceededMaxTaskTitleLength, validateTaskTitleMaxLength};
};

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We can @wildan-m, but it's kind of wrong in a case, let's say validateTaskTitleMaxLength returns false. It also means it's a task creating comment, however, the length is still in capacity. But then we have to use another validation of validateCommentMaxLength, which is unnecessary and incorrect because it's a task creating comment but we use a standard max length validation on it. Kind of double validations.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Another option we can consider refactoring existing validateCommentMaxLength by passing max_length.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@hoangzinh the code has been updated. I use and modify COMMENT_LENGTH_DEBOUNCE_TIME since it is not being used anywhere.

const [exceededMaxLength, setExceededMaxLength] = useState<number | null>(null);

const suggestionsRef = useRef<SuggestionsRef>(null);
const composerRef = useRef<ComposerRef>();
Expand Down Expand Up @@ -306,6 +309,18 @@ function ReportActionCompose({
onComposerFocus?.();
}, [onComposerFocus]);

useEffect(() => {
if (hasExceededMaxTitleLength) {
setExceededMaxLength(CONST.TITLE_CHARACTER_LIMIT);
return;
}
if (hasExceededMaxCommentLength) {
setExceededMaxLength(CONST.MAX_COMMENT_LENGTH);
return;
}
setExceededMaxLength(null);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
if (hasExceededMaxTitleLength) {
setExceededMaxLength(CONST.TITLE_CHARACTER_LIMIT);
return;
}
if (hasExceededMaxCommentLength) {
setExceededMaxLength(CONST.MAX_COMMENT_LENGTH);
return;
}
setExceededMaxLength(null);
if (hasExceededMaxTitleLength) {
setExceededMaxLength(CONST.TITLE_CHARACTER_LIMIT);
} else if (hasExceededMaxCommentLength) {
setExceededMaxLength(CONST.MAX_COMMENT_LENGTH);
} else {
setExceededMaxLength(null);
}

I think we can use nested if/else to read code easier here. What do you think?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@hoangzinh Although the lint check will pass, I believe we may prefer an early return?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We prefer an early return if it's only 1 if. For example

if (true) {
   // then do something
}

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ah, I see, updated

}, [hasExceededMaxTitleLength, hasExceededMaxCommentLength]);

// We are returning a callback here as we want to incoke the method on unmount only
useEffect(
() => () => {
Expand Down Expand Up @@ -333,7 +348,7 @@ function ReportActionCompose({

const hasReportRecipient = !isEmptyObject(reportRecipient);

const isSendDisabled = isCommentEmpty || isBlockedFromConcierge || !!disabled || hasExceededMaxCommentLength;
const isSendDisabled = isCommentEmpty || isBlockedFromConcierge || !!disabled || !!exceededMaxLength;

// 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.
Expand Down Expand Up @@ -399,9 +414,12 @@ function ReportActionCompose({
if (value.length === 0 && isComposerFullSize) {
Report.setIsComposerFullSize(reportID, false);
}
if (validateTitleMaxLength(value)) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

it's a debounce function, can we trust it to return true/false value here?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

https://www.geeksforgeeks.org/lodash-_-debounce-method/

We set leading true, it will immediately executed at the initial attempt

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oops, I missed this comment. Hmm. I don't think it's a good idea to check conditions based on result of a debounce function. It's better if we detect comment format and use properly validation function here. For example:

const isCreatingTaskComment = value.match(CONST.REGEX.TASK_TITLE_WITH_OPTONAL_SHORT_MENTION);
if (isCreatingTaskComment) {
   validateTitleMaxLength(value)
} else {
   validateCommentMaxLength(value, {reportID});
}

what do you think?

return;
}
validateCommentMaxLength(value, {reportID});
},
[isComposerFullSize, reportID, validateCommentMaxLength],
[isComposerFullSize, reportID, validateCommentMaxLength, validateTitleMaxLength],
);

return (
Expand Down Expand Up @@ -436,15 +454,15 @@ function ReportActionCompose({
styles.flexRow,
styles.chatItemComposeBox,
isComposerFullSize && styles.chatItemFullComposeBox,
hasExceededMaxCommentLength && styles.borderColorDanger,
!!exceededMaxLength && styles.borderColorDanger,
]}
>
<AttachmentModal
headerTitle={translate('reportActionCompose.sendAttachment')}
onConfirm={addAttachment}
onModalShow={() => setIsAttachmentPreviewActive(true)}
onModalHide={onAttachmentPreviewClose}
shouldDisableSendButton={hasExceededMaxCommentLength}
shouldDisableSendButton={!!exceededMaxLength}
>
{({displayFileInModal}) => (
<>
Expand All @@ -463,7 +481,7 @@ function ReportActionCompose({
onAddActionPressed={onAddActionPressed}
onItemSelected={onItemSelected}
actionButtonRef={actionButtonRef}
shouldDisableAttachmentItem={hasExceededMaxCommentLength}
shouldDisableAttachmentItem={!!exceededMaxLength}
/>
<ComposerWithSuggestions
ref={(ref) => {
Expand Down Expand Up @@ -549,7 +567,12 @@ function ReportActionCompose({
>
{!shouldUseNarrowLayout && <OfflineIndicator containerStyles={[styles.chatItemComposeSecondaryRow]} />}
<ReportTypingIndicator reportID={reportID} />
{hasExceededMaxCommentLength && <ExceededCommentLength />}
{!!exceededMaxLength && (
<ExceededCommentLength
maxCommentLength={exceededMaxLength}
isTaskTitle={hasExceededMaxTitleLength}
/>
)}
</View>
</OfflineWithFeedback>
{!isSmallScreenWidth && (
Expand Down
13 changes: 1 addition & 12 deletions src/pages/home/report/ReportFooter.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -124,18 +124,7 @@ function ReportFooter({

const handleCreateTask = useCallback(
(text: string): boolean => {
/**
* Matching task rule by group
* Group 1: Start task rule with []
* Group 2: Optional email group between \s+....\s* start rule with @+valid email or short mention
* Group 3: Title is remaining characters
*/
// The regex is copied from the expensify-common CONST file, but the domain is optional to accept short mention
const emailWithOptionalDomainRegex =
/(?=((?=[\w'#%+-]+(?:\.[\w'#%+-]+)*@?)[\w.'#%+-]{1,64}(?:@(?:(?=[a-z\d]+(?:-+[a-z\d]+)*\.)(?:[a-z\d-]{1,63}\.)+[a-z]{2,63}))?(?= |_|\b))(?<end>.*))\S{3,254}(?=\k<end>$)/;
const taskRegex = `^\\[\\]\\s+(?:@(?:${emailWithOptionalDomainRegex.source}))?\\s*([\\s\\S]*)`;

const match = text.match(taskRegex);
const match = text.match(CONST.REGEX.TASK_TITLE_WITH_OPTONAL_SHORT_MENTION);
if (!match) {
return false;
}
Expand Down
Loading