diff --git a/src/pages/home/report/ReportActionCompose/SuggestionMention.tsx b/src/pages/home/report/ReportActionCompose/SuggestionMention.tsx index 5f07dc66ea4d..e447bed67514 100644 --- a/src/pages/home/report/ReportActionCompose/SuggestionMention.tsx +++ b/src/pages/home/report/ReportActionCompose/SuggestionMention.tsx @@ -56,6 +56,16 @@ function SuggestionMention( shouldExcludeTextAreaNodes: false, }); + // Used to store the selection index of the last inserted mention + const suggestionInsertionIndexRef = useRef(null); + + // Used to detect if the selection has changed since the last suggestion insertion + // If so, we reset the suggestionInsertionIndexRef + const hasSelectionChanged = !(selection.end === selection.start && selection.start === suggestionInsertionIndexRef.current); + if (hasSelectionChanged) { + suggestionInsertionIndexRef.current = null; + } + // Used to decide whether to block the suggestions list from showing to prevent flickering const shouldBlockCalc = useRef(false); @@ -89,10 +99,12 @@ function SuggestionMention( const commentAfterMention = value.slice(suggestionValues.atSignIndex + suggestionValues.mentionPrefix.length + 1); updateComment(`${commentBeforeAtSign}${mentionCode} ${SuggestionsUtils.trimLeadingSpace(commentAfterMention)}`, true); + const selectionPosition = suggestionValues.atSignIndex + mentionCode.length + CONST.SPACE_LENGTH; setSelection({ - start: suggestionValues.atSignIndex + mentionCode.length + CONST.SPACE_LENGTH, - end: suggestionValues.atSignIndex + mentionCode.length + CONST.SPACE_LENGTH, + start: selectionPosition, + end: selectionPosition, }); + suggestionInsertionIndexRef.current = selectionPosition; setSuggestionValues((prevState) => ({ ...prevState, suggestedMentions: [], @@ -167,6 +179,14 @@ function SuggestionMention( if (searchValue && !displayText.toLowerCase().includes(searchValue.toLowerCase())) { return false; } + + // Given the mention is inserted by user, we don't want to show the mention options unless the + // selection index changes. In that case, suggestionInsertionIndexRef.current will be null. + // See https://github.com/Expensify/App/issues/38358 for more context + if (suggestionInsertionIndexRef.current) { + return false; + } + return true; }); @@ -247,7 +267,6 @@ function SuggestionMention( if (!isCursorBeforeTheMention && isMentionCode(suggestionWord)) { const suggestions = getMentionOptions(personalDetails, prefix); - nextState.suggestedMentions = suggestions; nextState.shouldShowSuggestionMenu = !!suggestions.length; } @@ -268,7 +287,6 @@ function SuggestionMention( // See: https://github.com/facebook/react-native/pull/36930#issuecomment-1593028467 return; } - calculateMentionSuggestion(selection.end); }, [selection, value, previousValue, calculateMentionSuggestion]);