[$250] Pressing Delete while selecting text inside a composer duplicates the content instead of clearing it.
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
Upwork Automation - Do Not Edit
- Upwork Job URL: https://www.upwork.com/jobs/~022109996188665927295
- Upwork Job ID: 2109996188665927295
- Last Price Increase: 2026-11-27
Issue Owner
Current Issue Owner: @FitseTLT
If the C+ can't reproduce I can take over 👍
⚠️ 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
Deletebranch. ItsBackspacebranch 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:
- Does it still happen in an incognito window with extensions turned off?
- Which browser version and extensions are installed?
- 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.
Triggered auto assignment to Contributor-plus team member for initial proposal review - @TaduJR (External)
Job added to Upwork: https://www.upwork.com/jobs/~022109996188665927295
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.
- Unchecked
deleteContentForwardwith active selection:- When the user presses the
Deletekey with a range of text selected, the browser triggers adeleteContentForwardinput event. - In
MarkdownTextInput.web.tsx,handleOnChangeTextchecks:
This assumesconst newCursorPosition = inputType === 'deleteContentForward' && contentSelection.current.start === contentSelection.current.end ? Math.max(contentSelection.current.start, 0) : calculateNewCursorPosition(...);deleteContentForwardonly occurs when there is a collapsed cursor (start === end). When there is an active selection (start !== end), the calculation falls back tocalculateNewCursorPosition.
- When the user presses the
- DOM node fragmentation &
parseInnerHTMLToTextout-of-sync reconciliation:- In Chromium / WebKit browsers, pressing
Deleteon selected text across multiple inline formatted markdown spans within acontenteditableelement can cause the browser to fragment or clone adjacent DOM nodes rather than cleanly removing the selection range. - When
parseInnerHTMLToTextscans the mutatedchildNodesstack on theinputevent, it reads both the retained cloned fragment and the existing text, normalizing it to duplicate content. - Additionally, when
updateCommentinComposerWithSuggestions.tsxreceives this parsed text and passes the updatedvalueprop back down,MarkdownTextInput.web.tsxreconcilesvalueand reparses the entire innerHTML, locking the duplicated string into the composer draft.
- In Chromium / WebKit browsers, pressing
What changes do you think we should make in order to solve the problem?
- In
MarkdownTextInput.web.tsx:- In
handleKeyPress, intercept theDeletekey when a non-collapsed selection exists (contentSelection.current.start !== contentSelection.current.end):
Usingif (e.key === 'Delete' && contentSelection.current && contentSelection.current.start !== contentSelection.current.end) { e.preventDefault(); insertText(e, ''); return; }insertText(e, '')cleanly replaces the selected text range[start, end]with an empty string, correctly updatingprefixandsuffixwithout relying on browser-specific DOM deletion quirks across live-markdown spans.
- In
- In
ComposerWithSuggestions.tsx:- Ensure the
handleKeyPresscallback consistently handles theDeletekey similarly toBackspacewhen selection is active, preventing duplicate synthetic event updates from propagating to the draft.
- Ensure the
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.
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:
- In
src/pages/inbox/report/ReportActionCompose/ComposerWithSuggestions.tsx(lines 596-656),handleKeyPressinterceptsEnter,ArrowUp, andBackspace, but contains zero handling for theDeletekey (webEvent.key === 'Delete'). - When the user selects text (
selection.start !== selection.end) and pressesDelete, the event is not intercepted and falls through to the native browser contenteditable element inreact-native-live-markdown(MarkdownTextInput.web.tsx). - 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 firingbeforeinput/input. - When
MarkdownTextInput.web.tsxexecuteshandleOnChangeText,parseInnerHTMLToTextreads the already-duplicated DOM content frome.targetand passes it up toComposerWithSuggestions.tsxviaonChangeText(updateComment), permanently updating the controlled React state with duplicated text. In contrast,Backspaceavoids 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 forwebEvent.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.endis optional inComposer/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})).
- Update local state:
- Call
updateComment(newText, true)to synchronize the controlled text value.
- Call
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:
- Workspace chat or 1:1 chat open on Web or Desktop (Chrome, Safari, or Desktop App).
- Composer input focused.
Manual QA Steps:
- Type a sample string into the composer (e.g.
hello worldorhhhhhhhhhhhhhhhhhi). - Select part of the text (e.g.
world) using mouse drag, keyboard shift-selection, or double click. - Press
Deletekey on the keyboard. - Verify that the selected text is cleanly removed from the composer (e.g.
helloremains) without duplication. - Select all remaining text (
Cmd+A/Ctrl+A) and pressDelete. - Verify that the composer input clears completely without text duplicating.
- Type text containing formatted markdown (e.g.
*bold* textor a link[example](https://expensify.com)). - Select part of the formatted text spanning across styled elements and press
Delete. - Verify that the selected range is cleanly removed and remaining markdown syntax parses correctly.
Regression Verification:
- Verify that pressing
Backspacewith and without selected text continues to function as expected. - Verify that
Shift+Delete(Windows Cut) continues to cut selected text to the clipboard. - Verify that typing with an active IME composition continues to handle
Deletewithout premature cancellation. - Verify that pressing
Entersubmits or creates newlines as configured. - Verify that
ArrowUpto edit the last sent message functions when the composer is empty. - Verify that mobile web and native platforms continue normal composer input behavior without side effects.
✅ Contributor details stored successfully. Thank you for contributing to Expensify!
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:
- The unhandled event falls through to the native contenteditable DOM element in
@expensify/react-native-live-markdown(MarkdownTextInput.web.tsx). - 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/inputfires. MarkdownTextInput.web.tsxexecuteshandleOnChangeText, whereparseInnerHTMLToTextreads the duplicated DOM string frome.targetand forwards it viaonChangeText(updateComment), updating the controlled React state with duplicated text. In contrast,Backspacehandles 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?
- In
src/pages/inbox/report/ReportActionCompose/ComposerWithSuggestions.tsx: InsidehandleKeyPress, add a dedicated case forwebEvent.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); } } - By intercepting
Deletewhen text is selected, callingpreventDefault()prevents the browser's faulty contenteditable DOM cloning and updates the controlled state cleanly. - When no text is selected (
start === end), default forward delete behavior is preserved for standard caret deletion. - Add unit test in
tests/unit/ComposerWithSuggestionsTest.tsxvalidating that selecting text and dispatching aDeletekey 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
@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!
https://github.com/user-attachments/assets/83db3ba3-eeda-469e-8560-fbe565d55089
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').
- Native ContentEditable Reconciler Flaw:
When text is selected (
selection.start !== selection.end) and the user pressesDelete, the event is not captured and falls through to the nativecontenteditablecontainer managed by@expensify/react-native-live-markdown(MarkdownTextInput.web.tsx). - 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 beforebeforeinput/inputfires. MarkdownTextInput.web.tsxexecuteshandleOnChangeText, reads the duplicated inner DOM tree viaparseInnerHTMLToText, and passes the duplicated string toupdateComment, overwriting the React state with duplicate text.- Additionally, if the caret is positioned immediately before a composite emoji (e.g., flag emojis or ZWJ sequences) with no text selected, native forward
Deleteslices 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
Deletewhen a selection exists callswebEvent.preventDefault(), stopping the faulty DOM contenteditable replication in its tracks. - Controlled state and cursor selection are updated synchronously and cleanly via
updateComment(newText, true)andsetSelection. - Provides full symmetry with the existing
Backspacehandler 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:
- Navigate to any chat on Web or Desktop (Chrome, Safari, Edge, Desktop App).
- Type a test message into the composer (e.g.
hello world). - Select a portion of the text (e.g.
world) via mouse or Shift+Arrow. - Press
Delete. - Verify: The selected text is cleanly removed (e.g. leaving
hello) without duplicating any text. - Select the entire remaining string (
Ctrl+A/Cmd+A) and pressDelete. - Verify: The composer input clears completely.
- Type text with markdown formatting (e.g.
*bold* text) and select part of it across boundaries. - Press
Delete. - Verify: The selection is cleanly deleted and remaining markdown parses normally.
- Insert a composite emoji (e.g. 🏴 Wales flag), place the caret right before it, and press
Delete. - Verify: The entire composite emoji is deleted forward without leaving orphaned code units.
Regression Verification:
- Verify pressing
Backspacewith and without selection continues to work normally. - Verify typing while IME composition is active is not interrupted.
- Verify
Enterto send message andArrowUpto edit previous message continue to function as expected.
Contributor details Your Expensify account email: [email protected] Upwork Profile Link: https://www.upwork.com/freelancers/janithad
✅ Contributor details stored successfully. Thank you for contributing to Expensify!
@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.
@FitseTLT Uh oh! This issue is overdue by 2 days. Don't forget to update your issues!
@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.
Not overdue
@FitseTLT Whoops! This issue is 2 days overdue. Let's get this updated quick!
@FitseTLT 6 days overdue. This is scarier than being forced to listen to Vogon poetry!
Not overdue