Skip to content

[lexical-table] Bug Fix: Fix unreliable text cursor placement when tapping table cells on touch devices - #8827

Merged
etrepum merged 5 commits into
meta:mainfrom
Arman-Luthra:fix-table-touch-tap-selection
Aug 31, 2026
Merged

etrepum merged 5 commits into
meta:mainfrom
Arman-Luthra:fix-table-touch-tap-selection

Conversation

@Arman-Luthra

Copy link
Copy Markdown
Contributor

Description

Current behavior: when a table is the sole content of the editor, placing the text cursor by tapping table cells on a touch device fails intermittently (#8538) — instead of a caret, a multi-cell table selection is created (which the next tap then clears, so to the user taps appear to do nothing).

Root cause: $handleTableClick deliberately skips $setAnchorCellForSelection for pointerType === 'touch' ("Touch taps should not initiate table selection mode", from #7309/#7656). However, #8081 later added a fallback in createPointerHandlers that sets the anchor cell unconditionally at pointerdown, which silently defeated that guard:

  1. A touch tap on cell A now sets tableObserver.anchorCell = A and initializes tableObserver.tableSelection, and this state persists after pointerup — nothing clears it for a plain tap.
  2. Real-world taps commonly include micro pointermove events between pointerdown and pointerup. On the next tap, on cell B, that micro-move resolves focusCell = B, and $handleTableSelectionChangeCommand sees anchorCell (A) !== focusCell (B) with an initialized tableSelection, so it calls $setFocusCellForSelection(B, true) — turning a simple tap into a TableSelection from A to B and preventing the caret from being placed.
  3. The same stale anchor also corrupts genuine touch drags: after tapping A, dragging from B to C selects A..C instead of B..C.

This PR (all new logic is gated on pointerType === 'touch'; mouse paths are unchanged):

Closes #8538

Test plan

Added regression tests in packages/lexical-table/src/__tests__/unit/LexicalTableMobileSelection.test.tsx that register the real registerTableSelectionObserver pointer handlers and simulate touch gestures (including the micro pointermove) against a 3x3 empty table as the sole document content.

Before

On main, the two new regression tests fail (verified across 3 consecutive runs):

× touch taps on different cells should not create a table selection
  (a TableSelection from the previously tapped cell is created)
× touch drag after a previous tap should anchor at the cell where the drag started
  (the selection is anchored at the stale cell from the previous tap)

After

pnpm vitest run --project unit packages/lexical-table — all 127 tests pass (new test file verified across 3 consecutive runs):

✓ a single touch tap with micro pointermove should not create a table selection
✓ touch taps on different cells should not create a table selection
✓ touch drag across cells should still create a table selection
✓ touch drag after a previous tap should anchor at the cell where the drag started

Also ran locally: packages/lexical-react unit tests (169 passed), packages/lexical unit tests (1199 tests; one unrelated fuzz-test timeout on a slow machine that behaves the same on main and passes in isolation), and ESLint/Prettier on the changed files.

Note: I was not able to run the Playwright e2e suite in my local environment, so this is verified at the unit level; happy to iterate if CI surfaces anything.

@vercel

vercel Bot commented Jul 11, 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 Aug 31, 2026 1:21am
lexical-playground Ready Ready Preview Aug 31, 2026 1:21am

Request Review

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Facebook bot. Authors need to sign the CLA before a PR can be reviewed. label Jul 11, 2026
@etrepum etrepum added the extended-tests Run extended e2e tests on a PR label Jul 11, 2026

@etrepum etrepum left a comment •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Here's some feedback from claude on the approach here, on a cursory read most of this seems accurate. Might also be worth noting that even if flushUpdates was necessary, the setTimeout stuff is superfluous. Any await at all will cause the resume to happen after the microtask that performs update reconciliation (that's what the old await editor.update(…) convention is for, from before {discrete: true} or editor.read('force-commit', …) were available)


Review notes on the approach

Ran the new tests against the reverted source change first: 2 of the 4 new tests fail without the fix (touch taps on different cells… and touch drag after a previous tap…), so they genuinely reproduce #8538. The fix is real, but verification turned up some gaps — the same symptom is still reachable through paths the tests don't cover, plus one behavioral regression.

Correctness

  1. No pointercancel/lostpointercapture handling (LexicalTableSelectionHelpers.ts:373). Cleanup is bound only to pointerup. A touch-scroll takeover fires pointercancel (no pointerup follows), leaving isSelecting=true and the stale closure installed. The next tap on a different cell early-returns at the isSelecting guard, its micro pointermove runs the stale closure, defeats the same-cell guard (different cell), and anchors at the old startingCell — recreating the exact #8538 selection the PR fixes.

  2. The untouched selectionchange branch (:1121) still converts tap→tap into a table selection. If the browser commits the caret while the finger is down (long-press caret placement, iOS Safari caret-on-touch in a focused editor), the branch sees collapsed selections in two different cells and builds an unwanted table selection regardless of the new anchor deferral. Reproduced with a unit-level test against this PR's code.

  3. Regression: the new (isTouch && !hasAnchorForGesture) re-anchor clause (:351) can clobber anchors legitimately set earlier in the same gesture. The old anchorCell === null guard made overwriting impossible. Victims: the selectionchange conversion handler (anchor A1 gets replaced by startingCell B1 on the next cross-cell move → B1→C1 instead of A1→C1) and the IS_FIREFOX shift-extend branch (X→C snaps to A→C).

  4. Same-cell guard has no pixel slop (:342). A tap near a cell border whose micro-move hit-tests into the neighboring cell bypasses focusCell.elem === startingCell.elem and produces a two-cell selection. Reproduced deterministically in this PR's own test harness.

  5. No pointerId filtering in onPointerMove (:297, pre-existing). A second finger's moves drive the first gesture's closure (anchoring at the first finger's cell → unwanted selection); a buttons=0 mouse hover during a touch drag tears the gesture down.

Design

The root cause of #8538 is gesture-scoped observer state (anchorCell, pointerType) never being reset at gesture end; the fix adds touch-only masks on top rather than fixing the lifecycle. A conditioned reset at pointerup/pointercancel — always reset pointerType; clear anchorCell/focusCell only when no table selection was established (they must persist for a live selection) — would make all four new tests pass by construction and also fixes items 1 and 3.

Tests

  • Stubbing document.elementsFromPoint in a jsdom unit test conflicts with AGENTS.md's testing strategy ("use browser tests … instead of stubbing the missing jsdom functionality"); it also hard-codes exactly the hit-testing geometry the bug involves. Consider __tests__/browser/.
  • flushUpdates (setTimeout) + await editor.read('latest', …) can be a single synchronous editor.read(cb) — default mode is 'force-commit', which flushes pending updates inline; read returns synchronously so the awaits are dead.
  • simulateTouchTap is a verbatim copy of simulateTouchDrag(cell, cell); dispatchPointerEvent duplicates the existing simulatePointerEvent in the same file; the hand-rolled 3×3 table is $createTableNodeWithDimensions(3, 3, false).

Minor

  • Every read of hasAnchorForGesture is behind isTouch &&, so the !isTouch && … initializer (:277) and the write at :288 are dead — let hasAnchorForGesture = false; is behavior-identical.
  • The new startingCell !== null guards (:341, :354) protect an impossible case (single call site always passes non-null); on that hypothetical path the tap suppression silently disables. Narrowing the param type to TableDOMCell removes them.

Checked and found not to be problems: pen input (eager re-anchor + the same-cell guard in $handleTableSelectionChangeCommand close every entry point, so pen matches mouse), and reordering the tap guard before the hit-test (implicit touch pointer capture pins moveEvent.target, so a target-based pre-check would break drag selection — the coordinate hit-test must run first).

…rag to select cells

## Description

Builds on the previous commit, which stops a touch pointerdown from
anchoring a table selection so that a tap can place a caret (meta#8538). That
closes the anchor-deferral half of the bug; four gaps in the pointer gesture
state machine remain, and any one of them still turns taps into multi-cell
selections.

- A gesture only ends on `pointerup`. A touch the browser takes away — one
  that turned into a scroll — fires `pointercancel` and no `pointerup`, so
  the observer stays in selecting mode indefinitely: the stale `pointermove`
  listener keeps driving selections from the abandoned gesture's starting
  cell, and `createPointerHandlers` refuses to start any later gesture
  because `isSelecting` is still set. Every subsequent tap then selects
  cells, and the previous commit's guards never run at all, because that
  early return sits ahead of them. This ends a gesture on `pointercancel`
  and `lostpointercapture` as well, and resets the gesture-scoped state
  there rather than masking stale state at each read.
- Any `pointermove` counted as a drag, so a tap whose contact jitters by a
  pixel or two across a cell border read as a move into the neighbouring
  cell. A touch gesture now has to travel beyond a 10px tap slop *and* cross
  into another cell before it anchors.
- Move and up events were not filtered by `pointerId`, so a second contact
  drove the first one's gesture.
- The `selectionchange` branch that converts two consecutive collapsed
  selections into a table selection keyed off `isSelecting` alone, which is
  true for the whole of a plain tap. It now also requires the new
  `TableObserver.isPointerDrag`.

Non-touch input is unaffected: mouse and pen gestures anchor at pointerdown
as before, so `hasAnchorForGesture` starts out true for them and every guard
here is inert. That also lets the previous commit's `isTouch &&` conditions
collapse, since the flag alone now carries the distinction.

Two cleanups fall out of the above. `maybeStartAutoScroll` read
`tableObserver.pointerType`, which the `selectionchange` branch can null out
mid-gesture, and now uses the gesture's own value; and
`createPointerHandlers` takes a non-null `TableDOMCell`, which is all its
only caller ever passed, so the `startingCell !== null` tests it had grown
are gone.

The test file shadowed the shared jsdom `PointerEvent` mock with a local
`Event` subclass carrying neither coordinates nor `pointerId`, so none of
this was observable from a test: every gesture was a same-cell hit-test at
`undefined, undefined`, and no coordinate- or pointer-dependent behaviour
could be written down at all. It now uses the shared mock, which gains
`pointerId` alongside the `MouseEvent` coordinates it already had, and the
previous commit's four cases are restated over a synthetic cell grid with
real coordinates, alongside four new ones for the gaps above.

Verifying that a tap leaves a *caret* in the tapped cell needs real touch
input; the repository has no mobile emulation lane (no `hasTouch` or
`touchscreen` use in the Playwright suite), so these tests assert the
absence of a table selection and the state machine around it, and the caret
itself is unverified here.

## Test plan

`npx vitest run --project unit packages/lexical-table/`.

### Before

At the parent commit, with this commit's tests in place:

```
     × a tap near a cell border does not create a table selection 23ms
     × a gesture ended by pointercancel does not leak into the next tap 11ms
     × a gesture ended by lostpointercapture does not leak into the next tap 11ms
     × a gesture ended by pointercancel does not wedge later gestures 11ms
     × a second finger does not drive the first finger gesture 7ms
 Test Files  1 failed (1)
      Tests  5 failed | 11 passed (16)
```

### After

```
 Test Files  10 passed (10)
      Tests  158 passed (158)
```

Full unit suite (`npx vitest run --project unit`):

```
 Test Files  221 passed (221)
      Tests  4022 passed | 1 skipped (4023)
```

`pnpm run ci-check` (tsc, Flow, Prettier, ESLint) passes.

E2E was not exercised: the Playwright matrix has no touch-enabled project,
so there is nothing there that drives these paths.

Co-Authored-By: Claude <[email protected]>
…eaving the starting cell

## Description

Two follow-ups to the touch gesture state machine.

`$fixRangeSelectionForSelectedTable` converts two consecutive collapsed
selections into a table selection, and gained an `isPointerDrag` guard so a
tap could not trigger it. Being a drag is not enough: the gesture also has
to have left the cell it started on. A drag that stays inside one cell is
selecting text there, and the caret the browser moves along with it was
still being paired with whatever cell the previous gesture left in the range
selection — tap cell 0, then press in cell 4 and drag within it, and the
result is a table selection anchored on cell 0, which is the meta#8538 symptom
the guard was added to prevent. `applyFocusCell` already applies the
equivalent check on the pointer path (`focusCell.elem ===
startingCell.elem`); this path had no counterpart because it works from the
caret rather than from a hit-test, so the observer now records the gesture's
starting cell in `pointerStartCell` and the branch compares against that.

`maybeStartAutoScroll` gated on the gesture-constant `isTouch`, which
disabled drag auto-scroll for touch outright — including for the genuine
touch drag-selections this branch enables, which is a regression against
reading `tableObserver.pointerType` as it used to. The comment's intent is
that touch *taps* should not scroll, so it now gates on the tap:
`isTouch && !tableObserver.isPointerDrag`. That is also independent of the
`pointerType = null` side effect the previous behaviour leaned on, so a
touch drag can reach the columns past the edge of a scrollable table from
the first cross-cell move rather than only after a conversion.

## Test plan

`npx vitest run --project unit packages/lexical-table/`, with four new cases
in `LexicalTableMobileSelection.test.tsx`. Two of them drive
SELECTION_CHANGE_COMMAND with a caret moved by hand, which is what a touch
device does natively as a finger drags; the pointer-driven cases could not
reach that handler because jsdom moves no caret of its own. The other two
count the animation frames a single pointermove schedules, which is how
auto-scroll starts.

### Before

Reverting the `$fixRangeSelectionForSelectedTable` change:

```
     × a drag inside one cell does not convert the caret into a table selection 24ms
AssertionError: expected true to be false // Object.is equality
      Tests  1 failed | 17 passed (18)
```

Reverting the `maybeStartAutoScroll` change:

```
     × a touch drag near a scroll edge starts auto-scroll 13ms
AssertionError: expected 0 to be greater than 0
      Tests  1 failed | 19 passed (20)
```

The two companion cases — a drag that *does* leave its starting cell still
converting, and a tap near a scroll edge still not scrolling — pass either
way, so they hold the behaviour these guards must not break.

### After

```
 Test Files  19 passed (19)
      Tests  197 passed (197)
```

Full unit suite (`npx vitest run --project unit`):

```
 Test Files  310 passed (310)
      Tests  4756 passed | 1 skipped (4757)
```

`pnpm run ci-check` (tsc, Flow, Prettier, ESLint) passes.

Co-Authored-By: Claude <[email protected]>
…and batch the pointer listeners

## Description

Two follow-ups to the touch gesture work, no behaviour change.

`createPointerHandlers` registered its four window listeners with four
`addEventListener` calls and tore them down with four matching
`removeEventListener` calls, which has to be kept in step by hand and only
worked because `removeEventListener` ignores the options object the
registrations pass. `registerEventListeners` is the batch form of the
`registerEventListener` this module already imports: it takes the
`{type: listener}` map, shares one options value, and returns a single
disposer, so `stopSelecting` calls that instead of naming each listener
again.

The `meta#8538` test suite built its editor with `initializeUnitTest` and
registered the table selection observer by hand. It now builds one from
`TableExtension` via `buildEditorFromExtensions`, matching
`LexicalTableObserver.test.ts` in the same directory and wiring up the
handlers under test the way an application wires them — the observer comes
from the extension rather than from a call the test makes itself. Building
the table with `$createTableNodeWithDimensions` and committing with
`{discrete: true}` drops the hand-rolled node construction, and asserting
through `editor.read()` force-commits the updates the pointer handlers
queued, so the `setTimeout(0)` flush and every `async`/`await` in the suite
are gone.

## Test plan

`npx vitest run --project unit packages/lexical-table/`.

A refactor can quietly turn tests into ones that pass no matter what, so
each guard was reverted in turn against the rewritten suite to confirm it
still fails:

```
pointercancel + lostpointercapture registration → 3 failed | 17 passed (20)
pointerId filter                                → 1 failed | 19 passed (20)
tap slop / cross-cell guard                     → 1 failed | 19 passed (20)
selectionchange start-cell gate                 → 1 failed | 19 passed (20)
auto-scroll tap gate                            → 1 failed | 19 passed (20)
```

Reverting the touch anchor deferral alone fails nothing, but that is not a
loss from this change: the pre-refactor suite behaves the same way, because
the deferral and the `applyFocusCell` guard overlap and either one alone
covers those cases.

### Before

```
 Test Files  19 passed (19)
      Tests  197 passed (197)
```

### After

```
 Test Files  19 passed (19)
      Tests  197 passed (197)
```

Full unit suite (`npx vitest run --project unit`):

```
 Test Files  310 passed (310)
      Tests  4756 passed | 1 skipped (4757)
```

`pnpm run ci-check` (tsc, Flow, Prettier, ESLint) passes.

Co-Authored-By: Claude <[email protected]>
@etrepum
etrepum added this pull request to the merge queue Aug 31, 2026
Merged via the queue into meta:main with commit e935443 Aug 31, 2026
44 checks passed
@etrepum etrepum mentioned this pull request Aug 31, 2026

This branch was successfully deployed

2 active deployments
Preview – lexical — 77bf3941 Deployed Aug 31, 2026 by vercel[bot]
Preview – lexical-playground — 77bf3941 Deployed Aug 31, 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: Setting text cursor by tapping on a table cell within a single table as the whole content doesn't work reliably on mobile

3 participants