App icon indicating copy to clipboard operation
App copied to clipboard

[$250] Pressing Delete while selecting text inside a composer duplicates the content instead of clearing it.

Open m-natarajan opened this issue 1 month ago • 140 comments

If you haven’t already, check out our contributing guidelines for onboarding. To join our Slack channel, fill out this form.


Version Number: Reproducible in staging?: Needs Reproduction (Unable to reproduce) Reproducible in production?: Needs Reproduction If this was caught during regression testing, add the test name, ID and link from BrowserStack: Email or phone of affected tester (no customers): Logs: https://stackoverflow.com/c/expensify/questions/4856 Expensify/Expensify Issue URL: Issue reported by: @FitseTLT Slack conversation (hyperlinked to channel name): #Expensify Bugs

Action Performed:

1. Navigate to workspace chat and open any expense report. 2.  Type text in the composer, for example "hello world". 3.  Select part or all of the text. 4.  Press Delete.

Expected Result:

Selected content deleted

Actual Result:

The content gets duplicated

Workaround:

Unknown

Platforms:

Select the officially supported platforms where the issue was reproduced:

  • [ ] Android: App
  • [ ] Android: mWeb Chrome
  • [ ] iOS: App
  • [ ] iOS: mWeb Safari
  • [ ] iOS: mWeb Chrome
  • [x] Windows: Chrome
  • [x] MacOS: Chrome / Safari

Screenshots/Videos

https://github.com/user-attachments/assets/f6732d30-0200-4012-9531-51925b1658e9

View all open jobs on GitHub

Upwork Automation - Do Not Edit
Issue OwnerCurrent Issue Owner: @FitseTLT

m-natarajan avatar Oct 13 '26 13:10 m-natarajan

If the C+ can't reproduce I can take over 👍

FitseTLT avatar Oct 13 '26 13:10 FitseTLT

⚠️ Preliminary analysis (low confidence) — treat as a starting point, not a conclusion.

I couldn't find any code that duplicates text when you delete a selection. My best guess is that something outside the App edits the composer's DOM during the delete, such as a browser extension (Grammarly, LanguageTool) or browser translation. That would explain why QA can't reproduce it.

Why no App or library code path fits:

  • The App's composer key handler has no Delete branch. Its Backspace branch returns early when text is selected: ComposerWithSuggestions.tsx:596-656.
  • The live-markdown web input (0.1.343) leaves Delete to the browser: MarkdownTextInput.web.tsx:500-566. It then re-reads the text from the DOM and replaces the editor's whole innerHTML. It never appends: parserUtils.ts:346-355. Duplicated text means the DOM already held it twice when the library read it.
  • None of the App's text rewrites in updateComment (paste-to-link, emoji, LTR marker) run on a deletion.
  • Expense reports use the same composer as other chats. There is no expense-report-only path.

I couldn't verify this in a browser because our web test tooling can't send Delete or select-all key presses.

To confirm, FitseTLT could check:

  1. Does it still happen in an incognito window with extensions turned off?
  2. Which browser version and extensions are installed?
  3. How was the text selected: mouse drag, double/triple-click, or Ctrl/Cmd+A?

If it reproduces in a clean profile, the fix likely belongs in react-native-live-markdown's web input handling, not in App.


Next Steps: Reply with @MelvinBot <your feedback> to refine this analysis.


view run · view recording

MelvinBot avatar Oct 13 '26 13:10 MelvinBot

Triggered auto assignment to Contributor-plus team member for initial proposal review - @TaduJR (External)

melvin-bot[bot] avatar Oct 13 '26 13:10 melvin-bot[bot]

Job added to Upwork: https://www.upwork.com/jobs/~022109996188665927295

melvin-bot[bot] avatar Oct 13 '26 13:10 melvin-bot[bot]

Proposal

Please re-state the problem that we are trying to solve in this issue.

In the chat / expense report composer on web (Chrome / Safari), when a user selects a range of text (or all text) and presses the Delete key (forward delete), the selected content gets duplicated instead of being deleted or cleared.

What is the root cause of that problem?

The composer web implementation uses react-native-live-markdown (MarkdownTextInput.web.tsx), which renders an HTML contenteditable element styled with live markdown parser spans.

  1. Unchecked deleteContentForward with active selection:
    • When the user presses the Delete key with a range of text selected, the browser triggers a deleteContentForward input event.
    • In MarkdownTextInput.web.tsx, handleOnChangeText checks:
      const newCursorPosition =
        inputType === 'deleteContentForward' && contentSelection.current.start === contentSelection.current.end
          ? Math.max(contentSelection.current.start, 0)
          : calculateNewCursorPosition(...);
      
      This assumes deleteContentForward only occurs when there is a collapsed cursor (start === end). When there is an active selection (start !== end), the calculation falls back to calculateNewCursorPosition.
  2. DOM node fragmentation & parseInnerHTMLToText out-of-sync reconciliation:
    • In Chromium / WebKit browsers, pressing Delete on selected text across multiple inline formatted markdown spans within a contenteditable element can cause the browser to fragment or clone adjacent DOM nodes rather than cleanly removing the selection range.
    • When parseInnerHTMLToText scans the mutated childNodes stack on the input event, it reads both the retained cloned fragment and the existing text, normalizing it to duplicate content.
    • Additionally, when updateComment in ComposerWithSuggestions.tsx receives this parsed text and passes the updated value prop back down, MarkdownTextInput.web.tsx reconciles value and reparses the entire innerHTML, locking the duplicated string into the composer draft.

What changes do you think we should make in order to solve the problem?

  1. In MarkdownTextInput.web.tsx:
    • In handleKeyPress, intercept the Delete key when a non-collapsed selection exists (contentSelection.current.start !== contentSelection.current.end):
      if (e.key === 'Delete' && contentSelection.current && contentSelection.current.start !== contentSelection.current.end) {
          e.preventDefault();
          insertText(e, '');
          return;
      }
      
      Using insertText(e, '') cleanly replaces the selected text range [start, end] with an empty string, correctly updating prefix and suffix without relying on browser-specific DOM deletion quirks across live-markdown spans.
  2. In ComposerWithSuggestions.tsx:
    • Ensure the handleKeyPress callback consistently handles the Delete key similarly to Backspace when selection is active, preventing duplicate synthetic event updates from propagating to the draft.

What alternative solutions did you explore? (Optional)

Handling this solely inside inputUtils.ts via parseInnerHTMLToText was explored. However, preventing the default browser forward-delete on active selections and explicitly applying insertText(e, '') is much cleaner and eliminates browser-level contenteditable span duplication entirely across Chrome, Edge, and Safari.

janiya2 avatar Oct 13 '26 13:10 janiya2

Contributor details Your Expensify account email: [email protected] Upwork Profile Link: https://www.upwork.com/freelancers/~01af851c9a7f771775

Proposal

Please re-state the problem that we are trying to solve in this issue.

On Web and Desktop platforms, when text is selected inside the composer and the user presses the Delete key (Forward Delete), the selected content duplicates itself in the input field instead of being deleted.

What is the root cause of that problem?

The root cause is an unhandled Forward Delete event in the composer keyboard handler coupled with browser contenteditable range manipulation:

  1. In src/pages/inbox/report/ReportActionCompose/ComposerWithSuggestions.tsx (lines 596-656), handleKeyPress intercepts Enter, ArrowUp, and Backspace, but contains zero handling for the Delete key (webEvent.key === 'Delete').
  2. When the user selects text (selection.start !== selection.end) and presses Delete, the event is not intercepted and falls through to the native browser contenteditable element in react-native-live-markdown (MarkdownTextInput.web.tsx).
  3. In Chromium-based browsers, executing native Forward Delete on a selected range spanning styled inline nodes (such as <span data-type="text"> or markdown formatting containers) triggers an internal DOM reconciler quirk where the selected text nodes are cloned and appended rather than cleared before firing beforeinput/input.
  4. When MarkdownTextInput.web.tsx executes handleOnChangeText, parseInnerHTMLToText reads the already-duplicated DOM content from e.target and passes it up to ComposerWithSuggestions.tsx via onChangeText (updateComment), permanently updating the controlled React state with duplicated text. In contrast, Backspace avoids this because Chromium's backward delete engine uses a different native path.

What changes do you think we should make in order to solve the problem?

In src/pages/inbox/report/ReportActionCompose/ComposerWithSuggestions.tsx:

  • In handleKeyPress, add a dedicated handler for webEvent.key === 'Delete'.
  • Skip processing if the input is composing or if Shift is pressed (preserving native Shift+Delete Cut): if (webEvent.isComposing || webEvent.shiftKey) return;.
  • Normalize and guard selection bounds to guarantee null safety (selection.end is optional in Composer/types.ts):
    • const start = selection.start ?? 0;
    • const end = selection.end ?? start;
  • When text is selected (start !== end):
    • Call webEvent.preventDefault() to stop the browser from executing the native contenteditable Forward Delete operation and prevent DOM duplication.
    • Compute the clamped slice bounds:
      • const textLength = lastTextRef.current.length;
      • const minIndex = Math.min(textLength, Math.max(0, Math.min(start, end)));
      • const maxIndex = Math.min(textLength, Math.max(0, Math.max(start, end)));
    • Construct the new text by slicing out the selected range: lastTextRef.current.slice(0, minIndex) + lastTextRef.current.slice(maxIndex).
    • Reset selection cleanly to minIndex:
      • Update local state: setSelection({start: minIndex, end: minIndex}).
      • Update edit selection state: setCurrentEditMessageSelection((prevSelection) => ({...prevSelection, start: minIndex, end: minIndex})).
    • Call updateComment(newText, true) to synchronize the controlled text value.

What alternative solutions did you explore? (Optional)

I explored patching MarkdownTextInput.web.tsx in the upstream @expensify/react-native-live-markdown library to suppress native deleteContentForward events. However, handling Delete directly within ComposerWithSuggestions.tsx solves the issue immediately in this repository, provides 100% parity with the existing Backspace emoji handling, and guarantees that React controlled state and native selection remain synchronized across all web browsers without waiting for an upstream package release.

Test Plan

Preconditions:

  1. Workspace chat or 1:1 chat open on Web or Desktop (Chrome, Safari, or Desktop App).
  2. Composer input focused.

Manual QA Steps:

  1. Type a sample string into the composer (e.g. hello world or hhhhhhhhhhhhhhhhhi).
  2. Select part of the text (e.g. world) using mouse drag, keyboard shift-selection, or double click.
  3. Press Delete key on the keyboard.
  4. Verify that the selected text is cleanly removed from the composer (e.g. hello remains) without duplication.
  5. Select all remaining text (Cmd+A / Ctrl+A) and press Delete.
  6. Verify that the composer input clears completely without text duplicating.
  7. Type text containing formatted markdown (e.g. *bold* text or a link [example](https://expensify.com)).
  8. Select part of the formatted text spanning across styled elements and press Delete.
  9. Verify that the selected range is cleanly removed and remaining markdown syntax parses correctly.

Regression Verification:

  1. Verify that pressing Backspace with and without selected text continues to function as expected.
  2. Verify that Shift+Delete (Windows Cut) continues to cut selected text to the clipboard.
  3. Verify that typing with an active IME composition continues to handle Delete without premature cancellation.
  4. Verify that pressing Enter submits or creates newlines as configured.
  5. Verify that ArrowUp to edit the last sent message functions when the composer is empty.
  6. Verify that mobile web and native platforms continue normal composer input behavior without side effects.

taieddie avatar Oct 13 '26 13:10 taieddie

✅ Contributor details stored successfully. Thank you for contributing to Expensify!

melvin-bot[bot] avatar Oct 13 '26 13:10 melvin-bot[bot]

Proposal

Please re-state the problem that we are trying to solve in this issue.

On Web/Desktop, when selecting text inside the message composer and pressing the Delete key (forward delete), the selected content duplicates itself in the input field instead of clearing/deleting the selected range.

What is the root cause of that problem?

In src/pages/inbox/report/ReportActionCompose/ComposerWithSuggestions.tsx (around lines 596-656), handleKeyPress intercepts keyboard shortcuts and specific navigation keys (Enter, ArrowUp, Backspace), but does not intercept the Delete key (webEvent.key === 'Delete').

When text is selected (selection.start !== selection.end) and the user presses Delete:

  1. The unhandled event falls through to the native contenteditable DOM element in @expensify/react-native-live-markdown (MarkdownTextInput.web.tsx).
  2. In Chromium and Safari engines, executing native Forward Delete across a selected range spanning styled markdown spans or paragraph boundaries causes the DOM selection reconciler to clone and duplicate text nodes instead of collapsing and removing them before beforeinput/input fires.
  3. MarkdownTextInput.web.tsx executes handleOnChangeText, where parseInnerHTMLToText reads the duplicated DOM string from e.target and forwards it via onChangeText (updateComment), updating the controlled React state with duplicated text. In contrast, Backspace handles this cleanly because its backward deletion execution path is handled separately.

What changes do you think we should make in order to solve the problem?

  1. In src/pages/inbox/report/ReportActionCompose/ComposerWithSuggestions.tsx: Inside handleKeyPress, add a dedicated case for webEvent.key === 'Delete':
    if (webEvent.key === 'Delete') {
        if (webEvent.isComposing || webEvent.shiftKey) {
            return;
        }
        const start = selection.start ?? 0;
        const end = selection.end ?? start;
        if (start !== end) {
            webEvent.preventDefault();
            const textLength = lastTextRef.current.length;
            const minIndex = Math.min(textLength, Math.max(0, Math.min(start, end)));
            const maxIndex = Math.min(textLength, Math.max(0, Math.max(start, end)));
            const newText = lastTextRef.current.slice(0, minIndex) + lastTextRef.current.slice(maxIndex);
    
            setSelection({start: minIndex, end: minIndex});
            setCurrentEditMessageSelection((prevSelection) => ({
                ...prevSelection,
                start: minIndex,
                end: minIndex,
            }));
            updateComment(newText, true);
        }
    }
    
  2. By intercepting Delete when text is selected, calling preventDefault() prevents the browser's faulty contenteditable DOM cloning and updates the controlled state cleanly.
  3. When no text is selected (start === end), default forward delete behavior is preserved for standard caret deletion.
  4. Add unit test in tests/unit/ComposerWithSuggestionsTest.tsx validating that selecting text and dispatching a Delete key event removes the selected slice and resets selection without content duplication.

What alternative solutions did you explore? (Optional)

Patching upstream @expensify/react-native-live-markdown. Rejected because handling the key event directly in ComposerWithSuggestions.tsx mirrors the existing Backspace selection pattern, solves the issue immediately in the App repository, and requires zero external dependency bumps.

Contributor details Your Expensify account email: [email protected] Upwork Profile link: https://www.upwork.com/freelancers/~0170d6b02e9440e604

camesenin avatar Oct 13 '26 13:10 camesenin

@FitseTLT

Hmm The video and steps are a bit out of sync. Could you re-record with "Keyboard Viewer" opened and the report closed when starting?

Thanks!

TaduJR avatar Oct 13 '26 13:10 TaduJR

https://github.com/user-attachments/assets/83db3ba3-eeda-469e-8560-fbe565d55089

FitseTLT avatar Oct 13 '26 14:10 FitseTLT

Proposal

Please re-state the problem that we are trying to solve in this issue.

On Web and Desktop platforms, selecting text inside the message composer and pressing the Delete key (forward delete) duplicates the content in the input field instead of deleting the selected text range.

What is the root cause of that problem?

In src/pages/inbox/report/ReportActionCompose/ComposerWithSuggestions.tsx (around lines 594–655), handleKeyPress intercepts keyboard shortcuts and specific navigation keys (Enter, ArrowUp, Backspace), but does not intercept the Delete key (webEvent.key === 'Delete').

  1. Native ContentEditable Reconciler Flaw: When text is selected (selection.start !== selection.end) and the user presses Delete, the event is not captured and falls through to the native contenteditable container managed by @expensify/react-native-live-markdown (MarkdownTextInput.web.tsx).
  2. Because live markdown parses formatting into styled DOM elements (<span class="syntax">...</span>), dispatching a native forward deletion (deleteContentForward) across styled nodes causes Chromium and WebKit DOM selection reconcilers to duplicate text nodes rather than collapsing and slicing them before beforeinput/input fires.
  3. MarkdownTextInput.web.tsx executes handleOnChangeText, reads the duplicated inner DOM tree via parseInnerHTMLToText, and passes the duplicated string to updateComment, overwriting the React state with duplicate text.
  4. Additionally, if the caret is positioned immediately before a composite emoji (e.g., flag emojis or ZWJ sequences) with no text selected, native forward Delete slices a single UTF-16 code unit rather than the full grapheme cluster, leaving dangling surrogates.

What changes do you think we should make in order to solve the problem?

In src/pages/inbox/report/ReportActionCompose/ComposerWithSuggestions.tsx: Inside handleKeyPress, add an explicit branch for webEvent.key === 'Delete':

if (webEvent.key === 'Delete') {
    if (webEvent.isComposing || webEvent.shiftKey) {
        return;
    }
    const start = selection.start ?? 0;
    const end = selection.end ?? start;

    // 1. Handle selected range deletion deterministically
    if (start !== end) {
        webEvent.preventDefault();
        const textLength = lastTextRef.current.length;
        const minIndex = Math.min(textLength, Math.max(0, Math.min(start, end)));
        const maxIndex = Math.min(textLength, Math.max(0, Math.max(start, end)));
        const newText = lastTextRef.current.slice(0, minIndex) + lastTextRef.current.slice(maxIndex);

        setSelection({start: minIndex, end: minIndex});
        setCurrentEditMessageSelection((prevSelection) => ({
            ...prevSelection,
            start: minIndex,
            end: minIndex,
        }));
        updateComment(newText, true);
        return;
    }

    // 2. Handle forward grapheme cluster deletion (multi-codepoint emojis)
    const splitter = new Intl.Segmenter(CONST.LOCALES.EN, {granularity: 'grapheme'});
    const graphemes = Array.from(splitter.segment(lastTextRef.current.substring(start, start + 14)));
    const firstGrapheme = graphemes.at(0);
    const firstGraphemeLength = firstGrapheme?.segment.length ?? 0;
    if (firstGraphemeLength > 1) {
        webEvent.preventDefault();
        const newText = lastTextRef.current.slice(0, start) + lastTextRef.current.slice(start + firstGraphemeLength);

        setSelection({start, end: start});
        setCurrentEditMessageSelection((prevSelection) => ({
            ...prevSelection,
            start,
            end: start,
        }));
        updateComment(newText, true);
    }
}

Why this completely fixes the issue:

  • Intercepting Delete when a selection exists calls webEvent.preventDefault(), stopping the faulty DOM contenteditable replication in its tracks.
  • Controlled state and cursor selection are updated synchronously and cleanly via updateComment(newText, true) and setSelection.
  • Provides full symmetry with the existing Backspace handler at lines 620–654, protecting both selected text deletion and multi-codepoint forward grapheme deletion.

What alternative solutions did you explore? (Optional)

Patching upstream @expensify/react-native-live-markdown. Handling this within ComposerWithSuggestions.tsx is superior because it mirrors our established Backspace emoji handling, prevents DOM reconciliation defects directly at the composer boundary, and avoids waiting for upstream release cycles.

Test Plan

Manual QA Steps:

  1. Navigate to any chat on Web or Desktop (Chrome, Safari, Edge, Desktop App).
  2. Type a test message into the composer (e.g. hello world).
  3. Select a portion of the text (e.g. world) via mouse or Shift+Arrow.
  4. Press Delete.
  5. Verify: The selected text is cleanly removed (e.g. leaving hello ) without duplicating any text.
  6. Select the entire remaining string (Ctrl+A / Cmd+A) and press Delete.
  7. Verify: The composer input clears completely.
  8. Type text with markdown formatting (e.g. *bold* text) and select part of it across boundaries.
  9. Press Delete.
  10. Verify: The selection is cleanly deleted and remaining markdown parses normally.
  11. Insert a composite emoji (e.g. 🏴󠁧󠁢󠁷󠁬󠁳󠁿 Wales flag), place the caret right before it, and press Delete.
  12. Verify: The entire composite emoji is deleted forward without leaving orphaned code units.

Regression Verification:

  1. Verify pressing Backspace with and without selection continues to work normally.
  2. Verify typing while IME composition is active is not interrupted.
  3. Verify Enter to send message and ArrowUp to edit previous message continue to function as expected.

jloa-dev avatar Oct 13 '26 14:10 jloa-dev

Contributor details Your Expensify account email: [email protected] Upwork Profile Link: https://www.upwork.com/freelancers/janithad

janiya2 avatar Oct 13 '26 14:10 janiya2

✅ Contributor details stored successfully. Thank you for contributing to Expensify!

melvin-bot[bot] avatar Oct 13 '26 14:10 melvin-bot[bot]

@FitseTLT

I got confused wether the select came from mouse double click or cmd + a. Anyways I couldn't reproduce. Please feel free to take over.

Thanks.

TaduJR avatar Oct 13 '26 14:10 TaduJR

@FitseTLT Uh oh! This issue is overdue by 2 days. Don't forget to update your issues!

melvin-bot[bot] avatar Oct 16 '26 21:10 melvin-bot[bot]

@FitseTLT I tried to reproduce this on Windows Chrome, which the issue lists, and it doesn't happen there. In case it helps narrow it down:

Setup: staging, Windows Chrome, a workspace chat composer containing hello world.

Selection Delete Backspace
Double-click "world" hello hello
Drag over "world" hello hello
Triple-click the line empty empty
Ctrl+A empty empty

No duplication in any of the 8 cases. Screenshots: left is the selection, right is the result; rows 1 to 4 use Delete and rows 5 to 8 use Backspace, each in the order of the table.

Your second recording is on a Mac, where the "delete" key is Backspace. Could you share the browser and version, whether it still happens in a window with extensions turned off, and how the text was selected (double-click, drag or Cmd+A)?

Not tested yet: macOS, Safari, and an expense report thread.

crazydev-king avatar Oct 19 '26 11:10 crazydev-king

Not overdue

FitseTLT avatar Oct 19 '26 12:10 FitseTLT

@FitseTLT Whoops! This issue is 2 days overdue. Let's get this updated quick!

melvin-bot[bot] avatar Oct 22 '26 21:10 melvin-bot[bot]

@FitseTLT 6 days overdue. This is scarier than being forced to listen to Vogon poetry!

melvin-bot[bot] avatar Oct 26 '26 21:10 melvin-bot[bot]

Not overdue

FitseTLT avatar Oct 26 '26 21:10 FitseTLT