App icon indicating copy to clipboard operation
App copied to clipboard

[$250] Command+C intermittently fails to copy selected text from the composer

Open m-natarajan opened this issue 2 weeks ago • 118 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: @joekaufmanexpensify Slack conversation (hyperlinked to channel name): #Expensify Bugs

Action Performed:

  1. Open any chat in New Expensify in Chrome on Mac.
  2. Write four paragraphs in the composer, separated by blank lines.
  3. Highlight paragraphs 2–4 and press Command+C. note: this issue does not exist if you right-click and copy the text that way
  4. Delete the selected paragraphs and send paragraph 1.
  5. Press Command+V to paste the remaining paragraphs back into the composer.

Expected Result:

The selected paragraphs are copied and can be pasted back so they can be sent as separate messages.

Actual Result:

Command+C intermittently fails to copy the selected text.

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
  • [ ] Windows: Chrome
  • [x] MacOS: Chrome / Safari

Screenshots/Videos

image

View all open jobs on GitHub

Upwork Automation - Do Not Edit

m-natarajan avatar Nov 17 '26 14:11 m-natarajan

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

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

🤖 Web test steps verification results: ⚠️ partial

Opened a chat, but could not reliably establish the multiline draft. Testing used Linux Chrome—not macOS—and the available controls could not verify Command+C, so the reported bug remains unconfirmed.

Blocked fixture: sent paragraph fragments and remaining composer text
Step Status
1. Open any chatOpened Concierge with message history and an editable composer.
✅
2. Enter four paragraphs separated by blank linesFixture setup failed: multiline entry sent fragments separately. This is a testing limitation, not a reproduction of the reported bug.
Blocked fixture: sent paragraph fragments and remaining composer text
❌
3. Select paragraphs 2–4, keyboard-copy, and inspect the clipboard repeatedlyNot executed: range-selection, keyboard-chord, and clipboard-read controls were unavailable.
Preliminary analysis — low confidence: The composer’s copy handler prevents native copying and writes a substring using cached selection offsets. Stale or collapsed offsets could produce empty or incorrect clipboard text, but no failing selection state was observed. The suspected mechanism is in the live-markdown dependency, not established App shortcut handling.
❌
4. Delete the selected paragraphs and send only paragraph 1Not verified in the required sequence. Paragraph 1 was sent during the unsuccessful fixture setup.
❌
5. Keyboard-paste and compare with paragraphs 2–4Not executed.
Alternative explanation: Failed pasting does not establish failed copying: App also intercepts paste events.
Next diagnostic: On an affected Mac, immediately paste into a separate plain-text app after Command+C, before deleting or sending. If the clipboard is wrong, capture whether a copy event fires and compare DOM selection with cached offsets. If it is correct, investigate paste/insertion instead. No code fix is justified yet.
❌
6. Compare context-menu CopyNot executed.
Hypothesis challenge: Keyboard and context-menu Copy ordinarily reach the same copy handler. Therefore, cached-selection handling alone does not explain the keyboard-only symptom without timing evidence. The composer’s keydown handler does not establish Command+C cancellation.
Possibly related, not confirmed duplicates: Make copied chat content consistent across paste destinations concerns message-copy formatting; Delete duplicates selected composer content concerns deletion rather than copying.
❌

view run · view recording

MelvinBot avatar Nov 17 '26 14:11 MelvinBot

🚨 Edited by proposal-police: This proposal was edited at 2026-11-24 19:00:38 UTC.

Proposal

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

In New Expensify on web (Chrome/Safari on Mac), selecting several paragraphs in the main report composer and pressing Command+C intermittently fails to copy the selected text. Right-clicking and choosing Copy always works. The failure is most reproducible when the drag selection (e.g. highlighting paragraphs 2–4) ends with the mouse released below the browser window, which is easy to do because the composer sits at the bottom of the page.

What is the root cause of that problem?

The report screen mounts a document-level copy listener via useCopySelectionEvent, registered in ReportActionsSkeletonGuard right alongside the composer:

The hook adds a single document-level copy handler that scrapes the current page selection into clean Markdown so copying report-action text produces good HTML/plain text. https://github.com/Expensify/App/blob/5c2727243b08cc586e42be20fd88ff2c90dc5ad1/src/pages/inbox/report/ReportActionsSkeletonGuard.tsx#L42-L43

Because this handler is on document, it also fires for Command+C performed inside the composer, but it is not what breaks the copy: it returns immediately when event.defaultPrevented is true, and the composer's own copy handler has already called preventDefault() by then: https://github.com/Expensify/App/blob/5c2727243b08cc586e42be20fd88ff2c90dc5ad1/src/hooks/useCopySelectionEvent.ts#L55-L70

The break is in the composer's own copy handler. The composer is live-markdown's MarkdownTextInput: https://github.com/Expensify/App/blob/5c2727243b08cc586e42be20fd88ff2c90dc5ad1/src/components/Composer/implementation/index.tsx#L368

Its copy handler cancels the native copy and writes the text from a cached selection (contentSelection), not from what is selected on screen: https://github.com/Expensify/react-native-live-markdown/blob/6cb36466568a61a1c0561d8695f897549878b6d0/src/MarkdownTextInput.web.tsx#L655-L662

That cache is only refreshed from React's onSelect: https://github.com/Expensify/react-native-live-markdown/blob/6cb36466568a61a1c0561d8695f897549878b6d0/src/MarkdownTextInput.web.tsx#L301-L328

Two facts make the cache go stale intermittently for a drag selection:

  1. React does not emit onSelect while its internal mouseDown flag is set, and only a mouseup, contextmenu or dragend that reaches the React root clears that flag: https://github.com/facebook/react/blob/612e371fb215498edde4c853bd1e0c8e9203808f/packages/react-dom-bindings/src/events/plugins/SelectEventPlugin.js#L105-L111 https://github.com/facebook/react/blob/612e371fb215498edde4c853bd1e0c8e9203808f/packages/react-dom-bindings/src/events/plugins/SelectEventPlugin.js#L180-L188 React listens for mouseup only on the root container; selectionchange is the only event it also listens for on the document: https://github.com/facebook/react/blob/612e371fb215498edde4c853bd1e0c8e9203808f/packages/react-dom-bindings/src/events/DOMPluginEventSystem.js#L445-L456
  2. The composer sits at the bottom of the window, so dragging from paragraph 2 down past paragraph 4 often ends with the mouse released below the browser window. That mouseup is dispatched to <html>, outside #root, so React never sees it.

When that happens the flag stays set, the cache keeps the caret position from before the drag (start === end), and Command+C writes an empty string to the clipboard while paragraphs 2–4 are still highlighted. Changing the selection with the keyboard afterwards does not refresh the cache either. Whether this triggers depends on where the mouse button is released, which is why it is intermittent.

This also explains why right-click Copy works: contextmenu reaches the React root, clears the flag and refreshes the cache before the copy runs.

So the underlying bug is in react-dom: onSelect stops firing after a mouse release outside the root. It was reported upstream in https://github.com/facebook/react/issues/26165 and closed without a fix.

Steps that reproduce it every time:

  1. Open any chat in Chrome on Mac with the window not in full screen.
  2. Type four paragraphs separated by blank lines in the composer.
  3. Press the mouse at the start of paragraph 2, drag down past the bottom edge of the browser window and release it there.
  4. Press Command+C and paste anywhere: paragraphs 2–4 are not pasted.

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

Fix it in react-dom so that onSelect fires after a release outside the root. In listenToAllSupportedEvents, also listen for mouseup on the document, next to the existing selectionchange listener:

    listenToNativeEvent('selectionchange', false, ownerDocument);
    // Lets SelectEventPlugin reset its `mouseDown` flag when a drag selection is released outside of every root.
    listenToNativeEvent('mouseup', false, ownerDocument);

This goes here: https://github.com/facebook/react/blob/612e371fb215498edde4c853bd1e0c8e9203808f/packages/react-dom-bindings/src/events/DOMPluginEventSystem.js#L445-L456

Why this is correct and safe for the existing behavior:

  • Composer bug case: a mouseup outside every root now reaches SelectEventPlugin, which clears the mouseDown flag and fires onSelect, so live-markdown's cache is refreshed at the moment of release. No change is needed in live-markdown or in App code.
  • Release inside the app: it is still handled by the root listener. The document-level dispatch bails out because the target's root container is not the document, so onMouseUp handlers do not fire twice: https://github.com/facebook/react/blob/612e371fb215498edde4c853bd1e0c8e9203808f/packages/react-dom-bindings/src/events/DOMPluginEventSystem.js#L628-L685
  • Report-action text (the feature useCopySelectionEvent exists for): untouched.

Tested with react-dom 19.2.3 (development and production builds) and live-markdown 0.1.372's MarkdownTextInput, after selecting paragraphs 2–4 and releasing the mouse below the window:

After the outside release Today With the react-dom fix
Command+C empty string paragraphs 2–4
Command+X empty string, nothing deleted copied and deleted
Shift+Enter new line added at the old caret replaces the selection
Command+V over the selection pasted at the old caret replaces the selection

Three mouse releases inside the root still produced exactly three onMouseUp calls.

App does not patch react-dom today, so the fix ships as a new patches/react-dom patch on react-dom 19.2.3 (its react-dom-client and react-dom-profiling builds) with a details.md entry, plus an upstream PR to facebook/react. The patch is dropped once App upgrades to a React release that contains it.

Edge cases and platform notes:

  • Every web input that uses onSelect is affected, but only by receiving the select events that are dropped today.
  • A release over an iframe is delivered to the iframe's document, so that case is not covered by this change.
  • Offline / loading: this is a pure DOM/clipboard interaction with no network or Onyx dependency, so offline and skeleton-loading states are unaffected.
  • Native (iOS/Android app): react-dom is not used by the native apps, so there is no platform regression.

Regression test plan

Automated (App unit test):

  • Render an input with onSelect, fire mousedown inside it, dispatch mouseup on document.documentElement, change the selection, and assert onSelect is called. Also assert an onMouseUp handler fires once for a release inside the root.

Manual QA (New Expensify web, Chrome and Safari on macOS):

  • Type four paragraphs separated by blank lines in the composer; drag from the start of paragraph 2 past the bottom edge of the browser window and release outside it, press Command+C, paste elsewhere, and confirm the exact text copies — repeat several times, including releasing inside the window and selecting bottom-to-top.
  • Repeat with Command+X and confirm the text is copied and removed from the composer.
  • Repeat with Shift+Enter and with Command+V and confirm they replace the selection.
  • Confirm right-click Copy from the composer still works.
  • In the same report, select text across report-action messages and copy; confirm the scraped Markdown copy (multi-line formatting) still works.
  • Select text inside a plain input (e.g. search) and copy; confirm native copy is unaffected.

What alternative solutions did you explore? (Optional)

Fix the copy handler in live-markdown's MarkdownTextInput.web.tsx so it copies from the live DOM selection instead of trusting the cached one. Before reading the text, sync contentSelection with the current selection using helpers the file already has: getCurrentCursorPosition reads the live selection, and updateSelection stores it and calls onSelectionChange, so the App's selection state catches up as well.

Add this right after e.preventDefault() in handleCopy, and add updateSelection to its dependency list:

    // React doesn't emit `select` when a drag selection is released outside of its root (e.g. below the browser
    // window), which leaves `contentSelection` stale. Sync it with the DOM selection so we copy what is selected.
    const currentSelection = getCurrentCursorPosition(divRef.current);
    if (currentSelection && currentSelection.start >= 0 && currentSelection.end >= 0) {
        updateSelection(e, currentSelection);
    }

This goes in handleCopy here: https://github.com/Expensify/react-native-live-markdown/blob/6cb36466568a61a1c0561d8695f897549878b6d0/src/MarkdownTextInput.web.tsx#L655-L662

handleCut calls handleCopy first, so Command+X is fixed by the same change: https://github.com/Expensify/react-native-live-markdown/blob/6cb36466568a61a1c0561d8695f897549878b6d0/src/MarkdownTextInput.web.tsx#L664-L675

This is smaller and stays in a library we own, but it only fixes copy and cut: Shift+Enter and paste over the selection still use the stale cache after an outside release. It can be kept as an extra guard on top of the react-dom fix.

Test Branch

The branch contains both patches: react-dom (main solution) and handleCopy (alternative).

https://github.com/Expensify/App/compare/main...abbasifaizan70:Expensify:107116?expand=1

Demo

Before

https://github.com/user-attachments/assets/7f0becb6-3dd9-402a-b118-a79aa701845a

After

https://github.com/user-attachments/assets/924ca4fd-0a3a-452a-86b8-843f9732242c

abbasifaizan70 avatar Nov 17 '26 14:11 abbasifaizan70

🚨 Edited by proposal-police: This proposal was edited at 2026-11-17 14:38:46 UTC.

Proposal

What is the root cause of that problem?

  • Primary Root Cause: The web copy handler lives in the @expensify/react-native-live-markdown dependency at src/MarkdownTextInput.web.tsx (lines ~655–662, referenced by the Melvin run). That handler calls event.preventDefault() on the native copy event and then writes a substring to the clipboard built from cached selection offsets instead of letting the browser copy the real DOM selection. When Command+C fires, the cached offsets can be stale or collapsed (start === end) relative to the live DOM Range, so clipboard.writeText(value.slice(start, end)) produces an empty or wrong string — intermittently. Right‑click → Copy does not hit this stale‑offset path in the same way, which is exactly why the reporter sees the keyboard‑only symptom.

  • Secondary Root Cause: On the App side, the Composer is the single source of selection truth and it updates that truth asynchronously. In src/components/Composer/implementation/index.tsx, addCursorPositionToSelectionChange (around the onSelectionChange + setSelection(...) calls) and the controlled selection prop passed to <RNMarkdownTextInput selection={selection} ... /> mean the offsets the library reads on copy can lag the actual DOM selection after a fast highlight‑then‑Command+C. Code read, same file:

    onSelectionChange({ ...event, nativeEvent: { ...event.nativeEvent, selection: selectionValue }});
    setSelection(selectionValue);
    ...
    <RNMarkdownTextInput selection={selection} onSelectionChange={addCursorPositionToSelectionChange} .../>
    

    A stale selection state feeding the native view widens the window where the library's cached offsets disagree with the DOM.

  • Affected Files:

    • node_modules/@expensify/react-native-live-markdown/src/MarkdownTextInput.web.tsx (copy handler, ~L655–662; keydown handler ~L511–576)
    • src/components/Composer/implementation/index.tsx (addCursorPositionToSelectionChange, controlled selection prop)
    • src/hooks/useHtmlPaste/index.ts (paste path only — proven NOT the cause, see below)
  • Affected Component(s): Composer / live‑markdown web input copy pipeline

  • Bug Category: Model‑vs‑reality divergence (cached selection offsets vs. live DOM selection) + timing/race on a controlled selection.

  • Mechanism (line‑numbered chain):

    1. User highlights paragraphs 2–4 → DOM selection updates.
    2. addCursorPositionToSelectionChange in src/components/Composer/implementation/index.tsx fires setSelection(selectionValue) async.
    3. User presses Command+C before React commits the new selection.
    4. The library's web copy handler (MarkdownTextInput.web.tsx L655–662) calls preventDefault() and copies value.slice(cachedStart, cachedEnd) using offsets that are stale/collapsed.
    5. Clipboard receives empty/incorrect text → paste (Command+V) brings nothing back. The paste interceptor in src/hooks/useHtmlPaste/index.ts (handlePaste) is downstream and only surfaces the already‑broken clipboard.

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

  • Fix Option 1 (Recommended): In @expensify/react-native-live-markdown src/MarkdownTextInput.web.tsx copy handler (~L655–662), read the live DOM selection at copy time instead of cached offsets, and if the DOM selection is non‑empty, do NOT preventDefault() — let the browser copy natively. Only fall back to the manual substring when the DOM selection is truly collapsed.

    • Before (behavior): event.preventDefault(); clipboard.writeText(value.slice(cachedStart, cachedEnd));
    • After (behavior): const sel = window.getSelection(); const text = sel?.toString() ?? ''; if (text) { /* don't preventDefault, let native copy run */ return; } /* else keep existing cached-offset path */
    • Why best: fixes the divergence at the source — the clipboard always matches what the user actually highlighted, and it removes the keyboard‑vs‑right‑click discrepancy. Because this is a library file, land it as an upstream PR + a patch under patches/@expensify/react-native-live-markdown/ (the repo already patches this package — see details.md).
    • How it solves: eliminates the stale‑offset write that produced empty clipboard text.
  • Fix Option 2 (Alternative): In src/components/Composer/implementation/index.tsx, make the selection the input reads synchronous on copy by syncing selection from the DOM in a copy event listener (mirroring the existing handlePaste/useHtmlPaste wiring) before the library's handler runs.

    • Before: selection state updated only via async addCursorPositionToSelectionChange.
    • After: add a capture‑phase copy listener that reads window.getSelection() and updates offsets synchronously just before copy.
    • Trade‑off: works around the library instead of fixing it; adds App‑side event plumbing and risks double‑handling with the library's own handler.
  • Revert Option: Revert to native copy by removing the library's preventDefault() on copy. Not ideal alone — the manual path exists to normalize markdown wrapper text on paste (handlePaste checks pastedHTML.startsWith('<p dir="ltr">') in src/hooks/useHtmlPaste/index.ts), so a blind revert could change copied‑HTML formatting.

  • Alternate fix (rejected): Patch only the paste side in src/hooks/useHtmlPaste/index.ts. Rejected because the clipboard is already wrong at copy time; handlePaste/handlePastePlainText faithfully paste whatever was copied, so they are symptoms, not the cause.

Fix Description Files to Change Effort Risk Status
1 Copy live DOM selection; skip preventDefault when selection is non-empty live-markdown MarkdownTextInput.web.tsx (+ repo patch) Med Low Recommended
2 Sync selection from DOM in a capture-phase copy listener src/components/Composer/implementation/index.tsx Med Med Alternative
3 Remove library copy preventDefault (revert) live-markdown patch Low Med Fallback

What alternative solutions did you explore? (Optional)

  • Add only the m flag — matches the line but still erases the title (rejected above).
  • Move the subtitle to its own label on the server — leaves old charts broken and keeps the App brittle.
  • Revert the localizer — restores the original wrong behavior.

Reminder: Please use plain English, be brief and avoid jargon. Feel free to use images, charts or pseudo-code if necessary. Do not post large multi-line diffs or write walls of text. Do not create PRs unless you have been hired for this job.

Dip-G-Git avatar Nov 17 '26 14:11 Dip-G-Git

⚠️ @Dip-G-Git Thanks for your interest. To be considered for this job, please post a proposal following the proposal template (note the mandatory sections). Comments claiming the job without one are not reviewed.

github-actions[bot] avatar Nov 17 '26 14:11 github-actions[bot]

Proposal

What is the root cause of that problem?

On Mac Chrome, selecting several paragraphs in the composer and pressing Command+C sometimes copies nothing, while right-click Copy always works. I have not reproduced this, so the cause below is inferred from that difference and not confirmed in code.

The composer is a controlled multiline input, wired up in ComposerWithSuggestions.tsx and Composer/implementation/index.tsx. When it re-renders, it can write the selection or value back to the native element. This can happen from a state update, such as the draft comment save, suggestion or emoji checks, or the height and scroll recalculation. If that happens between the key press and the browser's copy action, the selection is reset or collapsed and Command+C copies an empty string. Right-click Copy works because the selection is stable by the time the user picks the menu item. That would also explain why it is intermittent and mostly affects large, multi-paragraph selections.

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

  1. In Composer/implementation/index.tsx, find where the selection prop or setSelectionRange is re-applied to the native input. Skip that write when the native selection already matches, or when the user has a non-collapsed selection that the state has not caught up with. This stops a re-render from clobbering the user's selection mid-copy.
if (el.selectionStart === selection.start && el.selectionEnd === selection.end) {
    return;
}
  1. In ComposerWithSuggestions.tsx, check that the selection state is only updated from onSelectionChange and not recomputed after each text update. This keeps the state and the DOM in sync, so step 1 has no stale value to restore.

  2. Confirm that no composer or global keydown handler calls preventDefault on Command+C. Right-click Copy works, so this is less likely, but a handler that does it would cause the same symptom.

What alternative solutions did you explore? (Optional)

Adding an onCopy handler that writes the selected text to the clipboard manually. It would work around the symptom, but it would hide the selection reset and could break rich-text copy behavior.

Reminder: Please use plain English, be brief and avoid jargon. Feel free to use images, charts or pseudo-code if necessary. Do not post large multi-line diffs or write walls of text. Do not create PRs unless you have been hired for this job.

samranahm avatar Nov 17 '26 14:11 samranahm

🤖 ProposalPolice™ is tracking duplicate proposals for this issue using an OpenAI Conversation. This comment stores that Conversation's ID and can be safely ignored.

github-actions[bot] avatar Nov 17 '26 14:11 github-actions[bot]

🚨 Edited by proposal-police: This proposal was edited at 2026-11-17 15:42:57 UTC.

[Updated] This proposal was revised after re-verification. The earlier version pointed at the App's useCopySelectionEvent document listener; that listener is not on this code path, because the composer's own copy handler runs first and calls preventDefault().

Proposal

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

On web, selecting several paragraphs in the composer with the mouse and pressing Cmd+C sometimes copies nothing, and the next paste restores nothing. Right-click > Copy on the same selection works.

What is the root cause of that problem?

The web composer is MarkdownTextInput from react-native-live-markdown, a contentEditable div. Its copy handler cancels the native copy and writes value.substring(start, end) from a cached selection (contentSelection) instead of reading the live DOM selection:

https://github.com/Expensify/react-native-live-markdown/blob/6cb36466568a61a1c0561d8695f897549878b6d0/src/MarkdownTextInput.web.tsx#L655-L662

That cache is only refreshed from React's synthetic onSelect (updateSelection, wired as onSelect at L830):

https://github.com/Expensify/react-native-live-markdown/blob/6cb36466568a61a1c0561d8695f897549878b6d0/src/MarkdownTextInput.web.tsx#L301-L328

React's SelectEventPlugin suppresses onSelect while it believes a mouse button is down. A module-level mouseDown flag is set on mousedown and cleared only when mouseup, contextmenu or dragend reaches React's root. While the flag is set, every selectionchange, keydown and keyup is dropped:

https://github.com/facebook/react/blob/612e371fb215498edde4c853bd1e0c8e9203808f/packages/react-dom-bindings/src/events/plugins/SelectEventPlugin.js#L104-L110

https://github.com/facebook/react/blob/612e371fb215498edde4c853bd1e0c8e9203808f/packages/react-dom-bindings/src/events/plugins/SelectEventPlugin.js#L178-L187

The composer sits at the bottom edge of the window, so a downward drag through the last paragraphs easily ends with the button released outside the page. React never receives that mouseup, the flag stays set, and the cache keeps the collapsed caret from the start of the drag. handleCopy then writes value.substring(87, 87) - an empty string - while the paragraphs are still highlighted. Right-click > Copy works because contextmenu reaches the root, clears the flag and refreshes the cache first. Cmd+X fails the same way: handleCut delegates to handleCopy:

https://github.com/Expensify/react-native-live-markdown/blob/6cb36466568a61a1c0561d8695f897549878b6d0/src/MarkdownTextInput.web.tsx#L664-L675

The App's document-level listener in useCopySelectionEvent cannot fix this: the event arrives there already defaultPrevented, so it returns at its L56 guard.

@zeryns identified the mouse-release-outside-the-window trigger first; this proposal converges on the same mechanism, verified against the pinned library and React sources above.

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

In handleCopy, sync the cache from the live DOM selection before reading it, using the existing updateSelection:

const handleCopy: ClipboardEventHandler<HTMLDivElement> = useCallback(
    (e) => {
        if (!divRef.current) {
            return;
        }
        updateSelection(e);
        if (!contentSelection.current) {
            return;
        }
        e.preventDefault();
        const text = divRef.current.value.substring(contentSelection.current.start, contentSelection.current.end);
        e.clipboardData.setData('text/plain', text ?? '');
    },
    [updateSelection],
);

updateSelection reads the live selection through getCurrentCursorPosition(divRef.current) and only overwrites the cache when the live read succeeds and differs, so a failed live read falls back to today's behavior. This mirrors how the paste and insert-text paths already pass a freshly computed selection into updateSelection (L385-L417). handleCut calls handleCopy first, so cut copies and deletes the correct range. Then bump @expensify/react-native-live-markdown in App.

What alternative solutions did you explore? (Optional)

  • Fixing the editable-target guard in App's useCopySelectionEvent: unreachable for the composer, because live-markdown has already prevented the default before that listener runs.
  • A document-level mouseup listener in the library that refreshes the cache: repairs this one trigger, but React's mouseDown flag stays stuck until an event reaches the root again, so the cache can go stale on later keyboard selection changes.

AvikaM3192730 avatar Nov 17 '26 14:11 AvikaM3192730

Proposal

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

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

On macOS Chrome/Safari, selecting several paragraphs inside the main report composer and pressing Command+C intermittently leaves the clipboard empty, so Command+V pastes nothing. Copying the same selection through the context menu always works.

What is the root cause of that problem?

The app installs a document-level copy listener (src/hooks/useCopySelectionEvent.ts, mounted for the report screen by ReportActionsSkeletonGuard.tsx) that rewrites the clipboard from a DOM scrape instead of letting the browser copy the selection:

function copySelectionToClipboard(event: ClipboardEvent) {
    if (event.defaultPrevented || !event.clipboardData || hasSelectionWithinEditableTarget(event.target)) {
        return;
    }

    const selection = SelectionScraper.getCurrentSelection();
    if (!selection) {
        return;
    }

    const clipboardText = getClipboardText(selection);
    event.preventDefault();
    event.clipboardData.clearData();
    event.clipboardData.setData('text/html', selection);
    event.clipboardData.setData('text/plain', clipboardText);
}

The decision to take over the copy hinges on hasSelectionWithinEditableTarget(event.target):

if (target instanceof HTMLInputElement || target instanceof HTMLTextAreaElement) {
    return target.selectionStart !== null && target.selectionEnd !== null && target.selectionStart !== target.selectionEnd;
}

if (!(target instanceof HTMLElement) || !target.isContentEditable) {
    return false;
}

That check only inspects event.target. During a copy, event.target is not always the element that owns the selection: with a keyboard shortcut the event can be dispatched with document/body as the target, and when the selection spans several nodes inside the composer the target can be a nested, non-editable child. In both cases the guard returns false, the handler runs, and it takes over the copy for text that is already the browser's own selection.

From there the outcome depends entirely on the scrape:

  • SelectionScraper.getCurrentSelection() re-serialises the selected DOM. For a multi-paragraph selection in the composer it may produce HTML whose text conversion (getClipboardText() → Parser.htmlToText()) is empty or whitespace-only, and the comment at SelectionScraper/index.ts shows the HTML is normalised aggressively (<br>\n → <br>, whitespace collapsed) before it is returned.
  • Because event.preventDefault() and event.clipboardData.clearData() already ran, the browser's native copy is cancelled and the clipboard has been emptied. The handler then writes whatever the scrape produced.

So when the scrape yields nothing useful the user ends up with an empty clipboard instead of the text they selected. The intermittency matches the race: it depends on which element Chrome reports as the event target and on the state of the selection when the listener runs, which is why right-click copy (where the target is reliably the clicked node) behaves differently, and why the bug is not reproducible on every attempt.

The two separate defects are:

  1. The editable-target guard is target-only, so it under-detects copies that belong to the composer.
  2. The handler clears the clipboard before knowing it has a replacement, so a failed scrape destroys the user's clipboard instead of falling back to the default behaviour.

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

In src/hooks/useCopySelectionEvent.ts:

  1. Compute everything before touching the event, and bail out when there is nothing better to write:
const selection = SelectionScraper.getCurrentSelection();
const clipboardText = getClipboardText(selection);

// Nothing scraped: leave the browser's own copy untouched.
if (!selection || selection.trim().length === 0 || clipboardText.trim().length === 0) {
    return;
}

event.preventDefault();
event.clipboardData.setData('text/html', selection);
event.clipboardData.setData('text/plain', clipboardText);

Dropping clearData() is deliberate: setData() already overwrites text/html and text/plain, and clearing only guarantees that every other flavour (text/rtf, custom MIME types) is lost when the scrape is incomplete.

  1. Make the editable check independent of event.target by resolving the selection's own anchor and walking the composed path:
function hasSelectionWithinEditableTarget(event: ClipboardEvent) {
    const selection = window.getSelection();
    const anchorNode = selection?.anchorNode;
    const anchorElement = anchorNode instanceof HTMLElement ? anchorNode : anchorNode?.parentElement;

    if (anchorElement?.closest('[contenteditable="true"], textarea, input')) {
        return true;
    }

    return event
        .composedPath()
        .some((node) => node instanceof HTMLElement && (node.isContentEditable || node instanceof HTMLTextAreaElement || node instanceof HTMLInputElement));
}

The existing selectionStart/selectionEnd comparison is kept for the textarea case.

  1. Scope the listener so it cannot pre-empt the composer: in ReportActionsSkeletonGuard.tsx the hook is mounted for the whole report screen, so the copy handler is live while the composer has focus. With fix 2 the composer copy returns early, and fix 1 guarantees that any remaining hijack is a successful one.

What alternative solutions did you explore? (Optional)

  • Removing useCopySelectionEvent entirely. Rejected: it exists so copying rendered report content (mentions, markdown, tables) yields clean markdown/plain text instead of the DOM's HTML. Removing it would regress copy quality elsewhere.
  • Restricting the listener to [data-copyable-text=true] regions. Attractive, but it requires tagging every place that currently benefits, and misses selections that start in the composer and end outside it.
  • Only calling clearData() when clipboardText is known non-empty. This is a subset of fix 1 and does not address the under-detected editable target, which is what actually causes the hijack in the first place.

What specific scenarios should we cover in automation tests?

tests/unit/useCopySelectionEventTest.ts (Jest + jsdom, dispatching a real ClipboardEvent on document):

  1. Copy inside a focused textarea is not intercepted — // Given a textarea with selectionStart: 0, selectionEnd: 12, // When a copy event is dispatched with the textarea as target, // Then defaultPrevented is false and clipboardData is untouched.
  2. Copy whose clipboardData would be empty falls back to the browser — // Given a selection that scrapes to empty output, // When the handler runs, // Then the event is not prevented and no data is written, so the user keeps whatever the browser copied.
  3. Successful hijack writes markdown and plain text — // Given a selection over report content, // When the handler runs, // Then text/html and text/plain both contain the expected markdown-derived output and text/rtf (if present) is not cleared.
  4. Selection anchored in a nested element inside the composer is not intercepted — // Given a selection whose anchor lives in a child of a contenteditable composer, // When a copy event targets the parent wrapper, // Then the handler returns early.

Manual QA (Web - Chrome/Safari on macOS):

  1. Open any chat, write four paragraphs separated by blank lines.
  2. Select paragraphs 2–4, press Command+C.
  3. Delete the selection, send paragraph 1, press Command+V.
  4. Verify the paragraphs paste back on the first attempt, ten times in a row, in both Chrome and Safari.
  5. Repeat the same steps but copy through the context menu to confirm no regression in either path.
  6. Copy a message from the report history that contains a mention and a markdown bullet list, paste into the composer, and confirm the markdown is preserved (regression check for the handler's original purpose).

denisetya1 avatar Nov 17 '26 14:11 denisetya1

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

melvin-bot[bot] avatar Nov 17 '26 14:11 melvin-bot[bot]

🚨 Edited by proposal-police: This proposal was edited at 2026-11-24 23:15:00 UTC.

Proposal

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

On macOS Chrome/Safari, pressing Command+C after selecting text in the composer intermittently fails to copy the selection, so a subsequent paste produces nothing (or stale clipboard content). Copying the same selection via right-click → Copy always works.

What is the root cause of that problem?

On web, the composer is the MarkdownTextInput from @expensify/react-native-live-markdown (App pins 0.1.372). Its copy handler cancels the native copy and writes the text range held in a cached selection, not the selection on screen:

https://github.com/Expensify/react-native-live-markdown/blob/0.1.372/src/MarkdownTextInput.web.tsx#L655-L662

That cache is only refreshed from React's onSelect:

https://github.com/Expensify/react-native-live-markdown/blob/0.1.372/src/MarkdownTextInput.web.tsx#L301-L329

onSelect comes from react-dom's SelectEventPlugin, which drops every select event while its module-level mouseDown flag is set:

https://github.com/facebook/react/blob/v19.2.3/packages/react-dom-bindings/src/events/plugins/SelectEventPlugin.js#L105-L111

The flag is set on mousedown and cleared only by a mouseup, contextmenu or dragend that reaches the plugin:

https://github.com/facebook/react/blob/v19.2.3/packages/react-dom-bindings/src/events/plugins/SelectEventPlugin.js#L180-L188

react-dom listens for mouseup on the root container (#root) only. The one event it also listens for on the document is selectionchange:

https://github.com/facebook/react/blob/v19.2.3/packages/react-dom-bindings/src/events/DOMPluginEventSystem.js#L432-L458

The composer sits at the bottom of the window, so a drag from paragraph 2 down past paragraph 4 is easily released below the window. Chrome dispatches that mouseup to <html>, outside #root, so the plugin never sees it. The flag stays set, onSelect stays off (for later selectionchange and key events too) until the next click inside the app, and the cache keeps the caret from before the drag. Command+C then writes an empty string. Releasing inside the window works because that mouseup reaches #root, and right-click → Copy works because contextmenu reaches #root, clears the flag and refreshes the cache before the copy runs. That is why it looks intermittent.

The same stale cache breaks Command+X and Shift+Enter after such a drag (live-markdown inserts the line break at the cached caret), and the selection App receives through onSelectionChange stays stale as well.

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

Fix it where the flag gets stuck, in react-dom: in listenToAllSupportedEvents, also listen for mouseup on the owner document, next to the existing selectionchange listener.

  • A release outside every root then reaches SelectEventPlugin, which clears the flag and fires onSelect with the final selection at the release, the same as for a release inside the composer.
  • A release inside a root is still handled once: dispatchEventForPluginEventSystem already drops the document-level copy of an event whose target is inside a root (L666-L670), so onMouseUp handlers don't run twice.
  • Ship it as patches/react-dom/react-dom+19.2.3+001+fire-onselect-after-mouseup-outside-root.patch with a details.md entry. The react-dom 19.2.3 bundles aren't minified, so it is the same one-line change in the client and profiling bundles (development, production and profiling builds).
  • Upstream, this is facebook/react#26165, reported for React 18.2 in 2023 and closed as stale in 2024 without a fix; React's main still only listens for selectionchange on the document. I'll open a PR on facebook/react with the same change in DOMPluginEventSystem.js, and App drops the patch once it upgrades to a React release that includes it.

No change is needed in live-markdown: once onSelect fires again, its cached selection is right for copy, cut and Shift+Enter, and so is the selection App gets from onSelectionChange.

Compare branch: https://github.com/Expensify/App/compare/main...wildan-m:App:wildan/107116-react-dom-onselect-outside-release?expand=1

What alternative solutions did you explore? (Optional)

  • Reading the live DOM selection in live-markdown's handleCopy and handleCut (my earlier solution, compare branch). It fixes copy and cut, but onSelect stays off, so Shift+Enter after the same drag still inserts the line break at the old caret and App's selection stays stale until the next click.
  • A selectionchange listener inside live-markdown that keeps the cache fresh. It would cover the composer, but it duplicates what react-dom already does and leaves every other input that relies on onSelect affected.
  • A mouseup listener in App that forwards the release into #root. It works around react-dom from the outside and has to keep the forwarded event from being handled twice; the patch fixes the source.
  • Dropping the manual copy interception and letting the browser copy natively. Rejected: the handler exists so the copied plain text is the input's markdown value (what paste and other consumers expect).

Reproduction

  1. In a chat, type four paragraphs separated by blank lines (Shift+Enter).
  2. Press the mouse at the start of paragraph 2 and drag down past paragraph 4 until the pointer is below the bottom edge of the browser window, then release the button there.
  3. Press Cmd+C, delete the highlighted paragraphs and press Cmd+V. Nothing is pasted, and whatever was on the clipboard before is gone.

Releasing the button inside the window copies correctly. Recorded with the composer's input (MarkdownTextInput from live-markdown 0.1.372) and react-dom 19.2.3 on a plain page in Chrome 158 on macOS (headless), driven through Chrome's input pipeline (DevTools protocol), not script-dispatched DOM events. The after build applies the patch file from the compare branch with patch-package. The overlay shows the clipboard and the composer's cached selection, and the last step presses Shift+Enter after the same drag.

Drag released below the window react-dom 19.2.3 With the patch
Cached selection right after the release (30 runs) stale 30/30 paragraphs 2–4, 30/30
Cmd+C (30 runs) empty 30/30 paragraphs 2–4, 30/30
Shift+Enter (10 runs) line break at the old caret 10/10 replaces the selection 10/10
Cmd+X nothing cut, clipboard emptied paragraphs 2–4 cut

Releasing inside the window copies correctly 30/30 in both, a click in the composer still fires onMouseUp once, and the production build gives the same results.

Before

https://github.com/user-attachments/assets/d3b4823b-1230-46e4-a3d4-b1b76da6b4f7

After (compare branch)

https://github.com/user-attachments/assets/b25ef338-d60b-46fb-8ec0-0c016463538e

wildan-m avatar Nov 17 '26 14:11 wildan-m

Proposal updated — added compare branch with implementation.

wildan-m avatar Nov 17 '26 14:11 wildan-m

Proposal

What is the root cause of that problem?

The bug happens when the mouse is released outside the browser window at the end of the drag. Because the composer sits at the bottom of the window, this is easy to do by accident when dragging down through the last paragraph

Steps to reproduce:

  1. Write four paragraphs in the composer, separated by blank lines
  2. Press at the start of paragraph 2 and drag down through paragraph 4, past the bottom edge of the browser window (onto the dock or desktop)
  3. Release the mouse there, outside the browser window
  4. Press Command+C, then paste anywhere. Nothing is pasted
  5. Repeat, but release the mouse inside the window. The copy works

The composer doesn't use the browser's native copy. Its copy handler blocks the native copy and copies value.substring(start, end) from a selection it saved earlier (contentSelection), instead of reading the current selection:

https://github.com/Expensify/react-native-live-markdown/blob/6cb36466568a61a1c0561d8695f897549878b6d0/src/MarkdownTextInput.web.tsx#L655-L662

That saved selection is only updated from React's onSelect:

https://github.com/Expensify/react-native-live-markdown/blob/6cb36466568a61a1c0561d8695f897549878b6d0/src/MarkdownTextInput.web.tsx#L318-L321

React doesn't fire onSelect while it thinks the mouse button is down. It only learns the button was released when a mouseup, contextmenu or dragend event reaches its root element:

https://github.com/facebook/react/blob/612e371fb215498edde4c853bd1e0c8e9203808f/packages/react-dom-bindings/src/events/plugins/SelectEventPlugin.js#L178-L187

https://github.com/facebook/react/blob/612e371fb215498edde4c853bd1e0c8e9203808f/packages/react-dom-bindings/src/events/plugins/SelectEventPlugin.js#L105-L112

When the mouse is released outside the window, Chrome sends the mouseup to <html>, which is outside React's root, so React never receives it. From then on React acts as if the mouse is still down and ignores every selection change, including the key presses of Command+C. The saved selection keeps its old value (for example {start: 87, end: 87}, the caret at the end of the text). So the composer copies an empty string, even though paragraphs 2–4 are still highlighted

Right-click Copy works because the contextmenu event does reach React's root. That makes React refresh the saved selection (to {start: 21, end: 87} in my test) before Copy runs

The App's document-level copy listener is not involved. The composer's handler has already blocked the native copy, so that listener returns early on event.defaultPrevented:

https://github.com/Expensify/App/blob/f4cfcd08a26b96c46272ed681718a5a0e42e9821/src/hooks/useCopySelectionEvent.ts#L56

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

In react-native-live-markdown, handleCopy should read the selection from the page when the copy happens instead of trusting the saved one. updateSelection already does this and updates the saved selection too, so we call it before copying:

const handleCopy: ClipboardEventHandler<HTMLDivElement> = useCallback(
    (e) => {
        if (!divRef.current) {
            return;
        }
        updateSelection(e);
        if (!contentSelection.current) {
            return;
        }
        e.preventDefault();
        const text = divRef.current.value.substring(contentSelection.current.start, contentSelection.current.end);
        e.clipboardData.setData('text/plain', text ?? '');
    },
    [updateSelection],
);

https://github.com/Expensify/react-native-live-markdown/blob/6cb36466568a61a1c0561d8695f897549878b6d0/src/MarkdownTextInput.web.tsx#L655-L662

handleCut calls handleCopy, so Command+X is fixed as well. Then we bump @expensify/react-native-live-markdown in App

What alternative solutions did you explore? (Optional)

In MarkdownTextInput.web.tsx, listen to the browser's selectionchange event on document while the input is focused, and call updateSelection from it. The saved selection then no longer depends on React's onSelect, which also keeps paste and formatting shortcuts correct after the same drag.

Before After

zeryns avatar Nov 17 '26 14:11 zeryns

[!IMPORTANT] Before posting a proposal, make sure you can reproduce the issue. If you can, please include a recordings/screenshot and the steps you used to reproduce it.

linhvovan29546 avatar Nov 17 '26 14:11 linhvovan29546

🚨 Edited by proposal-police: This proposal was edited at 2026-11-25 00:28:21 UTC.

Proposal

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

Cmd+C in the composer sometimes copies nothing after selecting several paragraphs with the mouse. Right-click > Copy works.

What is the root cause of that problem?

It isn't a timing race, and I can reproduce it every time.

Repro steps: open any chat, type 4 short paragraphs separated by blank lines, then start the drag in paragraph 2, drag down past the bottom edge of the browser window, release the button outside the page, then press Cmd+C. The composer sits at the bottom of the window, so this happens easily when selecting down to the last paragraph.

react-native-live-markdown copies from a cached selection and always calls preventDefault(): https://github.com/Expensify/react-native-live-markdown/blob/0.1.372/src/MarkdownTextInput.web.tsx#L655-L662

The cache is only updated from React's onSelect (L318-L321, L830). After a mousedown, React holds back onSelect until it gets a mouseup, contextmenu or dragend inside the React root (SelectEventPlugin L106, L180-L190). When the button is released outside the root, React never gets that mouseup. The cache keeps the caret from before the drag, so the handler copies an empty string, and a second Cmd+C gives the same result. Right-click fires contextmenu, which refreshes the cache. That's why right-click > Copy works.

Measured on staging (Chromium, drag from paragraph 2 to the end of paragraph 4, then copy):

Button released mouseup target Cached selection Clipboard
inside the composer P 21–87 66 chars
below the window HTML, outside #root 19–19 (old caret) empty
copy again, no mouse – 19–19 empty
right-click, then copy P 21–87 66 chars

Screenshots from staging. The highlight looks the same in both cases; only the clipboard differs:

Released inside the composer → Cmd+C copies 66 chars Released below the window → Cmd+C copies nothing
release inside release below window

Same drag replayed on live-markdown 0.1.372 + React 19.2.3, released over the pink area outside the React root:

Current code → clipboard empty With the fix below → clipboard 66 chars
current fixed

Cmd+X is affected the same way: it copies nothing and deletes nothing. The copy listener in useCopySelectionEvent isn't involved. The event is already defaultPrevented in every row, so it returns at L56.

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

Updated 25/11 (preferred): fix it in react-dom as @linhvovan29546 suggested. In SelectEventPlugin, when mousedown sets mouseDown, also clear it from a one-time capture mouseup listener on the owner document. A release outside the root then no longer leaves the flag stuck, and the next key press fires onSelect:

case "mousedown":
  mouseDown = true;
  nativeEvent.target?.ownerDocument?.addEventListener("mouseup", () => { mouseDown = false; }, {capture: true, once: true});
  break;

Carry it as a patch on react-dom 19.2.3 and send it upstream. In the same replay it fixes copy (66 chars), cut and Shift+arrow, and unlike the copy-time sync below it also keeps the cached caret right when typing over the selection (22..22 instead of 0..0). Measurements.

Fallback if you'd rather not patch react-dom:

In react-native-live-markdown's handleCopy, sync the cache with the DOM before reading it, with the same updateSelection that onSelect uses:

e.preventDefault();
updateSelection(e);
const text = divRef.current.value.substring(contentSelection.current.start, contentSelection.current.end);

handleCut calls handleCopy first, so it's covered. updateSelection also fires onSelectionChange, so the App's selection state catches up. Then bump the library in App.

@zeryns reached the same root cause; I found it independently and am adding the reliable repro steps and the measurements asked for above. @wildan-m and @Dip-G-Git point at the same handler.

Test: I built 0.1.372 with React 19.2.3 in a small page and replayed the steps with Playwright. Without the change, the clipboard is empty when the button is released outside the root (elsewhere in the window, or below it). With it, every case copies the 66 characters and cut removes the text. I'd add that as a Playwright test in the library's WebExample/__tests__.

What alternative solutions did you explore? (Optional)

  • Fix it in react-dom so onSelect fires (asked by @linhvovan29546, details). SelectEventPlugin waits for a mouseup that reaches the React root, so this needs a change to React itself, and App doesn't patch react-dom today. Even then, handleCopy would still read a cache that can lag the DOM. Reading the selection at copy time fixes the report however the select events arrive.
  • A document mouseup listener in the library that calls updateSelection. It fixes the first copy, but React still holds back onSelect for later keyboard selection changes until the next mouseup inside the root, so the cache can go stale again.
  • Changing the editable check in useCopySelectionEvent. That code isn't reached for the composer (see above).

vulinh1704 avatar Nov 17 '26 14:11 vulinh1704

Proposal

@linhvovan29546 I can reproduce this every time, on production with a real mouse and in a local build. The trigger is releasing the mouse button outside the page at the end of the drag. Steps and a recording are below.

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

On web, the user selects several paragraphs in the composer and presses Cmd+C. Sometimes nothing is copied, and the next paste puts back nothing. Right-click > Copy on the same selection always works.

Steps to reproduce

  1. Open any chat in Chrome.
  2. Write four paragraphs separated by blank lines.
  3. Press the mouse at the start of paragraph 2 and drag down past the end of paragraph 4. Keep dragging until the pointer is below the bottom edge of the browser window, then release it there.
  4. Press Cmd+C (Ctrl+C on Windows).
  5. Delete the selection, send paragraph 1, then press Cmd+V. Nothing is pasted, and the clipboard is now empty.
  6. Repeat steps 2 and 3, then right-click the selection and pick Copy. That copy works.

The composer sits at the bottom edge of the window, so a downward drag easily ends outside it. When the mouse is released inside the composer the copy works, which is why the bug looks intermittent.

In a local build I ran each case 10 times. Releasing below the window failed all 10 times. Releasing inside the composer, and every context-menu copy, worked all 10 times.

BEFORE: <

https://github.com/user-attachments/assets/223471b5-5b20-4a37-920f-b621f31829e2

What is the root cause of that problem?

On web, the composer is MarkdownTextInput from react-native-live-markdown. Its copy handler cancels the browser's copy and writes value.substring(start, end) itself, using a selection it cached earlier: https://github.com/Expensify/react-native-live-markdown/blob/6cb36466568a61a1c0561d8695f897549878b6d0/src/MarkdownTextInput.web.tsx#L655-L662

That cache is updated only from React's onSelect event: https://github.com/Expensify/react-native-live-markdown/blob/6cb36466568a61a1c0561d8695f897549878b6d0/src/MarkdownTextInput.web.tsx#L318-L328

React holds onSelect back while a mouse button is down. It sets a mouseDown flag on mousedown and clears it only on mouseup, contextmenu or dragend. While the flag is set, it ignores selectionchange, keydown and keyup: https://github.com/facebook/react/blob/612e371fb215498edde4c853bd1e0c8e9203808f/packages/react-dom-bindings/src/events/plugins/SelectEventPlugin.js#L178-L206

React only sees events that reach the app's root element. When the drag ends below the window, the browser sends mouseup to <html>, which is outside that root. React never clears the flag, and the cache stays at the caret position from the mousedown. Logged at copy time in the local build:

  • DOM selection: {start: 16, end: 67} (paragraphs 2 to 4)
  • live-markdown's cached selection: {start: 67, end: 67}
  • result: the handler calls preventDefault() and writes "", which empties the clipboard

This explains the rest of the report:

  • Right-click > Copy works because the contextmenu event clears React's flag and refreshes the cache before Copy runs.
  • Pressing Shift+Arrow before Cmd+C doesn't help, because key events are ignored while the flag is stuck.
  • Cut (Cmd+X) fails the same way. It copies "" and deletes nothing.
  • Paste, typing and Backspace on that selection still work in the app, so only copy and cut are affected.

App's document-level copy listener (useCopySelectionEvent) is not involved. It runs after live-markdown and returns early because the event is already defaultPrevented: https://github.com/Expensify/App/blob/bad5f3d3fb722578f151bedf622774ea9c49e8f4/src/hooks/useCopySelectionEvent.ts#L55-L58

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

Fix it in react-native-live-markdown, then bump the package in App.

In handleCopy, read the selection from the DOM when the copy happens instead of trusting the cache:

  1. Get the live selection with the existing getCurrentCursorPosition helper.
  2. Use it only if both ends of the selection are inside this input and 0 <= start <= end <= value.length.
  3. If it is valid, store it with the existing updateSelection(e, liveSelection). That keeps the cache, divRef.selection and onSelectionChange in sync, and the copied text comes from the stored selection.
  4. If it is not valid, fall back to the cached value as today.

handleCut already calls handleCopy first, so cut then copies the right text and deletes the right range.

Tests:

  • live-markdown: add Playwright tests to WebExample/__tests__/textManipulation.spec.ts. Each one drag-selects multi-line text, releases the mouse below the viewport, and presses Cmd+C or Cmd+X. The tests check the exact clipboard text, blank lines included, and for cut the remaining value.
  • App: bump @expensify/react-native-live-markdown.

I've applied this locally. With the fix, the same 10-run matrix passes every time, including backward selections, selections ending on a blank line, select-all, a collapsed caret, and cut.

AFTER: <

https://github.com/user-attachments/assets/2cca6840-4ffe-438d-a28c-fa0c0dcad362

What alternative solutions did you explore? (Optional)

  • Change App's useCopySelectionEvent guard, as other proposals suggest. It can't fix this, because live-markdown has already cancelled the copy before that listener runs.
  • Listen for mouseup on document to refresh the cache. That covers this trigger, but React's flag stays stuck and every copy still trusts the cache.
  • Stop overriding copy and let the browser copy natively. The browser would copy the rendered DOM, which has extra blank lines and formatting, instead of the markdown value.

MannA-001 avatar Nov 17 '26 15:11 MannA-001

Proposal updated. I've added the reproduction and fix video with the steps to reproduce it

zeryns avatar Nov 17 '26 15:11 zeryns

Proposal

What is the root cause of that problem?

Verified Reproduction Steps (Chromium + @expensify/[email protected] / React 19.2.3)

  1. Open a chat composer at the bottom of the viewport with 4 paragraphs separated by blank lines (rendered as <p data-type="line"> blocks with blank <span data-type="br"><br></span> rows).
  2. Highlight Paragraphs 2–4 and either:
    • Drag past the bottom edge of #root (mouseup fires on <html>), then press Command+C; or
    • Highlight across blank-line <p data-type="line"> boundaries so a DOM Range endpoint lands on an Element node (<p data-type="line">, <span data-type="br">, or the div[contenteditable] root).
  3. Compare Command+C against Right-Click -> Copy:
Case Tested on Unpatched 0.1.372 (main) Cached contentSelection Command+C Clipboard Right-Click Copy
Case 1: Drag past #root bottom (mouseup on <html>) Stale {start: 0, end: 0} FAIL "" (0/180 chars) 180/180 chars
Case 2: <p data-type="line"> Element endContainer Wrong {start: 42, end: 169} FAIL truncated after "P" (127/180 chars) 180/180 chars

There are two distinct bugs in @expensify/react-native-live-markdown (0.1.372) that cause handleCopy (MarkdownTextInput.web.tsx#L655-L662) — which always calls e.preventDefault() and slices divRef.current.value.substring(contentSelection.current.start, contentSelection.current.end) — to copy empty or truncated text:

  1. getCurrentCursorPosition (cursorUtils.ts#L125-L158) treats Element-container Range offsets as character offsets and fails outside target: Across blank-line <p data-type="line"> paragraphs, Chrome/Safari frequently report range.startContainer or range.endContainer as an Element node where range.startOffset / range.endOffset is a child-node index, not a character index. Adding treeNode.start + range.endOffset cuts off Paragraph 4 at index 1 (127/180 chars in Case 2), miscomputes root offsets, and returns {start: -1, end: -1} ("") whenever a drag endpoint falls just outside divRef.current.
  2. Selection sync relies only on React's onSelect (MarkdownTextInput.web.tsx#L318-L328, #L830), which React freezes after an outside-#root mouseup: Releasing a drag below the composer lands mouseup on <html> instead of #root. React's SelectEventPlugin leaves mouseDown = true and suppresses onSelect on keydown (Command+C), leaving contentSelection.current stale at {start: 0, end: 0} so handleCopy writes "". Right-click fires contextmenu on #root, resetting React's mouseDown and refreshing contentSelection.current first. Note: App's src/hooks/useCopySelectionEvent.ts is not reached because MarkdownTextInput's handleCopy already calls e.preventDefault().

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

Fix both layers in @expensify/react-native-live-markdown and bump the dependency in Expensify/App's package.json:

  1. Resolve Element-container child indices and external drag boundaries in getCurrentCursorPosition (src/web/utils/cursorUtils.ts):
    • For Node.ELEMENT_NODE endpoints, resolve the treeNode (walking .closest('[data-id], [contenteditable]') when needed) and translate child-node index offset through treeNode.childNodes: 0 maps to treeNode.start, intermediate indices map to treeNode.childNodes[offset].start, and offset >= childNodes.length maps to the end of treeNode (or target.value.length on root), normalized so start <= end.
    • When a drag endpoint leaves divRef.current while the range still intersects target, clamp it cleanly to 0 or target.value.length instead of returning {start: -1, end: -1}.
  2. Sync focused composer selection from document selectionchange and skip collapsed interception in MarkdownTextInput.web.tsx:
    • Register a document selectionchange listener while mounted that invokes updateSelection whenever divRef.current && document.activeElement === divRef.current. This keeps contentSelection.current, divRef.current.selection, and Composer's onSelectionChange up to date immediately during drags and after an outside-#root mouseup — ensuring Step 3 (Command+C / Command+X) AND Step 4 deletion/keyboard edits stay synced.
    • Guard handleCopy to return early without e.preventDefault() when contentSelection.current.start === contentSelection.current.end.
  3. Add unit/web tests in @expensify/react-native-live-markdown covering outside-#root mouseup drags, Element-container multi-paragraph Ranges, and outside-boundary clamping, then bump the package version in Expensify/App.

Verified locally in Chromium against unpatched 0.1.372: both Case 1 and Case 2 move from 0/180 and 127/180 (FAIL) to 180/180 chars (PASS) with cached contentSelection updated live to {start: 42, end: 222}.

What alternative solutions did you explore? (Optional)

  • Calling updateSelection(e) / getCurrentCursorPosition only inside handleCopy: Still truncates/empties multi-paragraph selections whenever Chrome/Safari lands a Range endpoint on <p data-type="line"> or div[contenteditable] (127/180 chars in Case 2 above), and leaves contentSelection / Composer selection stale after an outside-#root drag for Step 4 deletion (Backspace/Delete) and formatting shortcuts.
  • Removing e.preventDefault() in handleCopy: Copies formatted HTML DOM text instead of divRef.current.value raw markdown syntax.
  • Updating hasSelectionWithinEditableTarget in src/hooks/useCopySelectionEvent.ts: Unreachable for composer copies because MarkdownTextInput sets event.defaultPrevented = true before the copy event bubbles to document.

camberlabs avatar Nov 17 '26 15:11 camberlabs

🚨 Edited by proposal-police: This proposal was edited at 2026-11-25 00:50:39 UTC.

Proposal

Updated 2026-11-25 after the react-dom question. I ran that route in the app beside my handleCopy fix: react-dom is the right place, and my handleCopy rewrite is not enough. I replaced my solution; the earlier text is in the edit history.

Reproduction

With four short paragraphs in a chat composer (Chrome not maximized), press before the first word of the second one, pull the pointer down beyond the last line and off the window, and let go over the desktop. Paragraphs 2–4 stay highlighted. Cmd+C, send paragraph 1 or clear the composer, Cmd+V: nothing comes back.

  • main, these steps (recorded 2026-11-17 at 5c27272): https://github.com/trasnake87/App/releases/download/issue107116-evidence/copy107116_before.mp4
  • With the react-dom line, the same steps, copy and then cut: https://github.com/trasnake87/App/releases/download/issue107116-evidence/copy107116_reactdom_line_reported_steps.mp4

Dev build of main at b474771, react-dom 19.2.3, live-markdown 0.1.372, Chrome 145 on Linux (Ctrl stands in for Cmd); OS-level mouse and keyboard input (xdotool) on a real test account; a marker string on the OS clipboard before every copy or cut. Every counted run and recording had read-only listeners; this week's also had counters on the composer's onSelect, onClick and onMouseUp (the first two pass through, the last is added). The chat list and history are masked in the recordings. Not run: macOS, Safari, Firefox, a production build.

Correct = the clipboard holds exactly the highlighted text, or is untouched when nothing is highlighted; last row: text and caret as after a drag that ended inside the composer.

Correct runs main react-dom line only handleCopy rewrite only (my earlier fix) react-dom line + early return (proposed)
Text highlighted, button let go outside the page (below or right of the window, over the address bar); Ctrl+C, Ctrl+X, Shift+Arrow then Ctrl+C 0/30 30/30 30/30 30/30
Nothing highlighted, then Ctrl+C or Ctrl+X 0/15 0/15 15/15 15/15
Let go inside, Shift+click, keyboard only, double-click, triple-click, Ctrl+A 35/35 35/35 35/35 35/35
After letting go outside: emoji, Ctrl+B, Shift+Enter; typing and paste with the old caret inside paragraph 1 0/17 17/17 0/17 17/17

What is the root cause of that problem?

@zeryns posted this trigger and mechanism first, and my runs agree with it. handleCopy blocks the browser's own copy and fills the clipboard from the cached contentSelection.current:

https://github.com/Expensify/react-native-live-markdown/blob/0.1.372/src/MarkdownTextInput.web.tsx#L655-L662

For a user's selection changes, that cache moves only in updateSelection, run from React's onSelect:

https://github.com/Expensify/react-native-live-markdown/blob/0.1.372/src/MarkdownTextInput.web.tsx#L301-L315

After a mousedown, React emits no select until a mouseup, contextmenu or dragend reaches its root, and a button let go outside the page is delivered to <html>, outside that root: on main, 0 of 40 such mouseups produced an onSelect, and no Ctrl+C or Ctrl+X after them did; with the react-dom line below, 40 of 40 did, before any key.

Copy is only one reader of that cache. laveshfonix measured Shift+Enter, Command+B and the emoji picker going wrong in this state on main first; my runs match (last table row), and Ctrl+B throws Trying to apply format command on empty selection.

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

1. The react-dom listener. It is not mine: @yusufdeveloper2903 proposed it right after the question, and David-2002065, abbasifaizan70 and wildan-m propose it as well. In listenToAllSupportedEvents, listenToNativeEvent('mouseup', false, ownerDocument) goes beside the selectionchange one, as a patches/react-dom patch until React has it. What my runs add:

  • It repairs every reader in the last row. A change inside handleCopy cannot, as laveshfonix pointed out: that code only runs on copy and cut (my earlier fix, 0/17).
  • In 35 further clicks and drags in the composer, the emoji picker and the Ctrl+K search field (the last two render outside #root), no counted handler (onMouseUp, onSelect, onClick) ran twice. The search field's onSelect is stuck the same way on main and comes back with the listener (5/5 each).

2. One check it still needs, in handleCopy of react-native-live-markdown (App picks it up with a version bump): leave before preventDefault() when the cached selection is collapsed.

if (contentSelection.current.start === contentSelection.current.end) {
    return;
}
e.preventDefault();

With the react-dom line alone, Ctrl+C or Ctrl+X with nothing highlighted still overwrites the clipboard with an empty string (second row), as main does for any caret-only copy. This bug's second form ends there: select paragraph 2, then press after the last character and drag out of the window. main then copies paragraph 2 although nothing is highlighted, and Ctrl+X also deletes the last character; the react-dom line stops that but empties the clipboard; with both changes it is left alone (5/5 per key on each build). handleCut needs no change.

Top: react-dom line only, nothing is pasted. Bottom: with the early return, the saved text is pasted.

  • react-dom line only: https://github.com/trasnake87/App/releases/download/issue107116-evidence/copy107116_reactdom_line_only_nothing_highlighted.mp4
  • react-dom line + early return: https://github.com/trasnake87/App/releases/download/issue107116-evidence/copy107116_reactdom_line_plus_early_return.mp4

The early return is not new: it is in wildan-m's first compare branch and dankezo's library fix, and David-2002065 suggests it as hardening on top of the react-dom fix. My runs add that the clipboard is still emptied without it. The rest of my earlier handler has no job left once onSelect fires, so I dropped it. Both libraries were patched as compiled JS (react-dom through App's patch-package, one added call in each of its four bundles); the TypeScript above was not compiled.

What alternative solutions did you explore? (Optional)

  • Selections that end on a block element (raised here against the react-dom route). My 42 selections in the app confirm what David-2002065 found in 13: Chrome ended them in a text node (36) or on a line element at offset 0 (6), and with the react-dom line all were copied in full.

trasnake87 avatar Nov 17 '26 15:11 trasnake87