Skip to content

[lexical] Bug Fix: deleteCharacter overwrites X11 PRIMARY selection via Selection.modify - #8774

Merged
etrepum merged 10 commits into
meta:mainfrom
etrepum:claude/lexical-issue-8766-2q841r
Jul 6, 2026
Merged

etrepum merged 10 commits into
meta:mainfrom
etrepum:claude/lexical-issue-8766-2q841r

Conversation

@etrepum

@etrepum etrepum commented Jul 2, 2026 •

Copy link
Copy Markdown
Collaborator

Description

On Linux/X11, browsers propagate any non-collapsed DOM selection made during
a user gesture to the PRIMARY selection (the middle-click paste buffer).
RangeSelection.deleteCharacter, deleteWord, and deleteLine extended the
DOM selection with the native Selection.modify('extend', …) before removing
text, so every Backspace/Delete/Ctrl+Backspace silently overwrote the user's
PRIMARY buffer with the deleted content.

Deletion no longer creates a non-collapsed DOM selection at all. A shared
$extendSelectionForDeletion helper replaces the three modify('extend', …)
calls:

  • The DOM caret is synced collapsed from the model, then moved with the
    native modify('move', …, granularity) to measure the engine's
    character/word/line boundary — collapsed carets never take PRIMARY
    ownership.
  • The [original .. landed] range a native extend would have produced is
    reconstructed and read into the Lexical model via applyDOMRange, which
    never touches the DOM selection. modify()'s decorator/block handling,
    shadow-root shrink validation, and anchor/focus orientation are preserved.
  • For character granularity, a boundary landing is clamped into the
    anchor's own text node, since 'move' reports boundary carets in the
    adjacent node while 'extend' keeps the focus in the extended node — a
    difference that would otherwise change how a later insertion resolves at
    keyword/format boundaries.

Because the engine's own caret movement defines the boundary, grapheme
behavior is unchanged and no Intl.Segmenter is required. Without a DOM
selection or Selection.modify implementation the deletion is a no-op;
headless environments can polyfill modify (the shared test utils already
do, which is how the jsdom suites exercise this path).

Also included: .claude/settings.json (tracked via a .gitignore exception)
sets attribution.sessionUrl: false, and AGENTS.md documents the policy, so
coding agents don't embed private session URLs in commits or PRs.

Closes #8766

Test plan

Before

Reproduced in full Chromium under Xvfb driving the playground, with xsel
watching X11 PRIMARY: seed PRIMARY, click into the editor, type, press
Backspace → PRIMARY is overwritten with the deleted character (and on every
subsequent press; Ctrl+Backspace overwrites it with the deleted word). A
control harness isolated the mechanism: gesture-driven modify('extend')
clobbers PRIMARY; a collapsed modify('move') does not.

After

Same real-X11 harness: PRIMARY is preserved for Backspace, forward Delete,
Backspace across a Shift+Enter linebreak, and Ctrl+Backspace — while
mouse-drag and Shift+Arrow selections still take PRIMARY ownership, the
expected platform behavior.

Backspace behavior is verified identical to a raw contenteditable with no JS
(11/11 cases, code point by code point, real keyboard events in Chromium):
combining marks (n+U+0303, Arabic shadda) and complex scripts (Hangul jamo,
Tamil, Devanagari) delete one code point per press; emoji clusters (astral,
ZWJ family, skin tone, variation selectors, keycap, flag) delete whole
clusters in one press.

New browser-mode tests
(packages/lexical/src/__tests__/browser/Issue8766DeleteCharacter.test.ts)
assert the invariant directly — deletion never calls modify('extend'),
never makes a ranged setBaseAndExtent, never uses Selection.extend or a
non-collapsed addRange — plus differential emoji-boundary checks against
the engine and coverage for RTL Hebrew/Arabic, mixed bidi, token, segmented,
linebreak, and format-run cases.

All suites passing: browser (60), unit (1086), e2e in real Chromium
(7163-graphemes, Keywords, Hashtags, Mentions, ShadowDOM, Emoticons,
AutoLinks, Selection), tsc and eslint clean. deleteLine has no
cross-platform e2e binding (macOS-only shortcut) but shares the same helper
and is covered by the unit suites.

@vercel

vercel Bot commented Jul 2, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
lexical Ready Ready Preview Jul 3, 2026 3:03pm
lexical-playground Ready Ready Preview Jul 3, 2026 3:03pm

Request Review

claude added 2 commits July 2, 2026 17:48
…ia Selection.modify

## Description

On Linux/X11, browsers propagate any non-collapsed DOM selection made
during a user gesture to the PRIMARY selection (the middle-click paste
buffer). `RangeSelection.deleteCharacter` extended the DOM selection with
the native `Selection.modify('extend', ..., 'character')` before removing
text, so every Backspace/Delete silently overwrote the user's PRIMARY
buffer with the deleted character.

Character deletion no longer creates a non-collapsed DOM selection at all.
A collapsed DOM caret is synced from the model, moved with the native
`Selection.modify('move', ..., 'character')` — collapsed carets never take
PRIMARY ownership — and the landing position is measured (resolved through
`applyDOMRange` and normalized to prefer text points, since engines may
report a caret at a text node boundary as an element position). The
`[original .. landed]` range is then constructed only in the Lexical model
for the shared deletion logic (token, tab, segmented, and unicode
code-unit handling) to consume, and the DOM selection is reconciled from
the model at the end of the update, by which point the deletion has
collapsed it again.

Because the engine's own caret movement defines the boundary, grapheme
cluster behavior is identical to the previous extend-based path (the engine
lands `move` and `extend` at the same positions), no `Intl.Segmenter`
support is required, and deletions across node boundaries (linebreaks,
format runs, inline edges) are covered by the same mechanism. When the
measurement is not possible — no DOM selection or no `Selection.modify`
implementation (headless environments can polyfill it, as the shared test
utils already do), or a caret move that cannot be resolved or that escapes
the nearest root or shadow root — the selection is left collapsed and the
deletion is a no-op for that keystroke.

`deleteWord` and `deleteLine` still use the native extend and remain a
follow-up.

Closes meta#8766

## Test plan

### Before

Reproduced in full Chromium under Xvfb driving the real playground, with
`xsel` monitoring the X11 PRIMARY buffer:

- Seed PRIMARY from another application, click into the editor, type, then
  Backspace → PRIMARY is CLOBBERED with the deleted character (the bug).

The pre-existing meta#7163 grapheme e2e suite documents the required
grapheme-cluster deletion behavior that must be preserved.

### After

Same real-X11 harness, with the fix:

- Backspace ×3 (issue repro): PRIMARY PRESERVED
- Delete (forward): PRIMARY PRESERVED
- Backspace over a Shift+Enter linebreak: PRIMARY PRESERVED
- Mouse-drag and Shift+Arrow selections still take PRIMARY ownership (the
  expected platform behavior — confirms the harness detects clobbering)

New browser-mode unit tests (`packages/lexical/src/__tests__/browser/
Issue8766DeleteCharacter.test.ts`) run in a real engine and assert the
PRIMARY-safety invariant directly: character deletion never calls
`modify('extend')`, never makes a ranged `setBaseAndExtent`, and never uses
`Selection.extend` or a non-collapsed `addRange`. Differential tests
compare emoji-class grapheme deletion boundaries against the boundary the
engine's own native extension produces, with coverage for RTL
Hebrew/Arabic, mixed bidi, decomposed combining marks, token, segmented,
linebreak, and format-run cases.

- Browser project: 60 passed
- Unit (lexical, lexical-selection, tab node): 1086 passed
- e2e in real Chromium: 7163 graphemes (15), Mentions (9), Selection (36)
- tsc and eslint clean

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_01RYawykRGUEVX9wnA1YjGFP
Set attribution.sessionUrl to false in project settings so agents working
on this repository do not append the private claude.ai session link (the
Claude-Session trailer on commits and the session link in PR bodies).
Those URLs are private to the individual or team and should not appear in
this open-source project's history.

The file is force-added because .claude is gitignored; only settings.json
is tracked, so personal overrides in .claude/settings.local.json stay
ignored.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
…on URL policy

Replace the blanket .claude gitignore entry with .claude/* plus a negation
for settings.json, so the shared project settings are tracked without
force-adds (which broke lint-staged's re-stage step) while agent state and
personal overrides like settings.local.json stay ignored.

Add a Commit and PR Hygiene section to AGENTS.md stating the policy for
all agents, not just Claude Code: no private agent-session URLs in commits
or PRs. Claude Code enforces this mechanically via attribution.sessionUrl
in the tracked settings; other vendors' agents follow the written rule.

Co-Authored-By: Claude Fable 5 <[email protected]>
…m the focus after the decorator pre-pass

Fixes the macOS e2e failures on the meta#8766 branch (Selection "can delete
line which starts with element forwards with opt+CMD+delete" on chromium
and webkit, Keywords "congrats Bob!" on webkit collab).

$modifySelectionAroundDecoratorsAndBlocks can hop the model focus past an
inline decorator and return false, expecting the native operation to
continue from that hopped extent — which is what modify('extend') did.
$extendSelectionForDeletion instead measured the native caret move from
the anchor, an element position adjacent to contenteditable=false content
where macOS engines refuse to move the caret, so the measurement landed
where it started and deleteLine degraded to deleteCharacter. Measure from
the focus (identical to the anchor when the pre-pass did not run), keep
the anchor as the fixed end of the reconstructed range, and gate the
in-node character clamp on the selection having been collapsed.

The Keywords webkit expectation is unified with the other browsers: the
post-backspace selection state is now built in the model and is
engine-uniform, so the space insertion produces the same DOM everywhere;
the webkit fork asserted the divergent state the native extension used to
leave behind.

Adds browser-mode coverage for forward deleteLine and deleteWord at a
caret before an inline decorator (the e2e scenario is macOS-only by
keyboard binding, so it is pinned here for all platforms).

Co-Authored-By: Claude Fable 5 <[email protected]>
…tests

Create the test inline decorator via $create so node replacement is
applied, and register the scratch contenteditable cleanup with
onTestFinished instead of try/finally. The removeAllRanges call stays
inline since a selection left in the scratch element would interfere
with the editor deletion measured next.

Co-Authored-By: Claude Fable 5 <[email protected]>
…eta#8766 tests

Editor content setup belongs in the extension's $initialEditorState rather
than a separate post-mount discrete update, so mountEditor now takes the
init callback (the body of the former setup helper) and each test passes
its own document/selection shape.

Co-Authored-By: Claude Fable 5 <[email protected]>
…tense rationale

Comments describing what the implementation used to do belong in commit
messages and PR descriptions; the code documents only why the current
behavior works the way it does (the X11 PRIMARY invariant, the collapsed
measurement, node-boundary clamping, and engine-uniform expectations).

Co-Authored-By: Claude Fable 5 <[email protected]>
Extract the shadow-root shrink validation shared verbatim between
RangeSelection.modify and $extendSelectionForDeletion into
$shrinkSelectionToRoot, and express the in-node character clamp in terms
of the deletion-side edge offset instead of a per-direction branch chain.

In the browser tests, fold the repeated mount/delete/assert bodies into a
data-driven expectDeletionSequence helper, generalize the deletion runner
so deleteLine/deleteWord tests share it, and use vi.restoreAllMocks /
vi.clearAllMocks in place of per-spy calls.

Co-Authored-By: Claude Fable 5 <[email protected]>
@etrepum
etrepum added this pull request to the merge queue Jul 6, 2026
Merged via the queue into meta:main with commit 69abb09 Jul 6, 2026
44 checks passed
@etrepum etrepum mentioned this pull request Jul 9, 2026

This branch was successfully deployed

2 active deployments
Preview – lexical — d571b8fd Deployed Jul 3, 2026 by vercel[bot]
Preview – lexical-playground — d571b8fd Deployed Jul 3, 2026 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

CLA Signed This label is managed by the Facebook bot. Authors need to sign the CLA before a PR can be reviewed. extended-tests Run extended e2e tests on a PR

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Bug: deleteCharacter() overwrites X11 PRIMARY selection via Selection.modify()

3 participants