Repository navigation
[lexical-table] Bug Fix: Fix unreliable text cursor placement when tapping table cells on touch devices - #8827
Conversation
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
There was a problem hiding this comment.
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
-
No
pointercancel/lostpointercapturehandling (LexicalTableSelectionHelpers.ts:373). Cleanup is bound only topointerup. A touch-scroll takeover firespointercancel(nopointerupfollows), leavingisSelecting=trueand the stale closure installed. The next tap on a different cell early-returns at theisSelectingguard, its micro pointermove runs the stale closure, defeats the same-cell guard (different cell), and anchors at the oldstartingCell— recreating the exact #8538 selection the PR fixes. -
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. -
Regression: the new
(isTouch && !hasAnchorForGesture)re-anchor clause (:351) can clobber anchors legitimately set earlier in the same gesture. The oldanchorCell === nullguard made overwriting impossible. Victims: the selectionchange conversion handler (anchor A1 gets replaced bystartingCellB1 on the next cross-cell move → B1→C1 instead of A1→C1) and theIS_FIREFOXshift-extend branch (X→C snaps to A→C). -
Same-cell guard has no pixel slop (
:342). A tap near a cell border whose micro-move hit-tests into the neighboring cell bypassesfocusCell.elem === startingCell.elemand produces a two-cell selection. Reproduced deterministically in this PR's own test harness. -
No
pointerIdfiltering inonPointerMove(:297, pre-existing). A second finger's moves drive the first gesture's closure (anchoring at the first finger's cell → unwanted selection); abuttons=0mouse 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.elementsFromPointin 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 synchronouseditor.read(cb)— default mode is'force-commit', which flushes pending updates inline;readreturns synchronously so theawaits are dead.simulateTouchTapis a verbatim copy ofsimulateTouchDrag(cell, cell);dispatchPointerEventduplicates the existingsimulatePointerEventin the same file; the hand-rolled 3×3 table is$createTableNodeWithDimensions(3, 3, false).
Minor
- Every read of
hasAnchorForGestureis behindisTouch &&, so the!isTouch && …initializer (:277) and the write at:288are dead —let hasAnchorForGesture = false;is behavior-identical. - The new
startingCell !== nullguards (: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 toTableDOMCellremoves 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).
…pping table cells on touch devices
3e84b78 to
05bbfad
Compare
…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]>
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:
$handleTableClickdeliberately skips$setAnchorCellForSelectionforpointerType === 'touch'("Touch taps should not initiate table selection mode", from #7309/#7656). However, #8081 later added a fallback increatePointerHandlersthat sets the anchor cell unconditionally atpointerdown, which silently defeated that guard:tableObserver.anchorCell = Aand initializestableObserver.tableSelection, and this state persists afterpointerup— nothing clears it for a plain tap.pointermoveevents betweenpointerdownandpointerup. On the next tap, on cell B, that micro-move resolvesfocusCell = B, and$handleTableSelectionChangeCommandseesanchorCell (A) !== focusCell (B)with an initializedtableSelection, so it calls$setFocusCellForSelection(B, true)— turning a simple tap into aTableSelectionfrom A to B and preventing the caret from being placed.This PR (all new logic is gated on
pointerType === 'touch'; mouse paths are unchanged):pointerdownfor touch, restoring the [lexical-table] Bug Fix: Fix table selection for touch devices #7656 guarantee while keeping the [lexical][@lexical/table] Bug Fix: Fix inconsistent multi-cell selection in 2x2 tables #8081 fallback for mouse (the bug [lexical][@lexical/table] Bug Fix: Fix inconsistent multi-cell selection in 2x2 tables #8081 fixed was mouse drag selection).onPointerMove, ignores movement that stays within the cell the touch gesture started on, so taps with micro-moves no longer dispatch a next-focus off stale state.Closes #8538
Test plan
Added regression tests in
packages/lexical-table/src/__tests__/unit/LexicalTableMobileSelection.test.tsxthat register the realregisterTableSelectionObserverpointer 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):After
pnpm vitest run --project unit packages/lexical-table— all 127 tests pass (new test file verified across 3 consecutive runs):Also ran locally:
packages/lexical-reactunit tests (169 passed),packages/lexicalunit tests (1199 tests; one unrelated fuzz-test timeout on a slow machine that behaves the same onmainand 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.