[lexical-table] Bug Fix: Odd selection behavior with table as last element in document
Description
- Prevent event propagation when navigating forward from root or shadow root in table selection.
- The cursor goes beneath the table when pressing the right arrow from the last cell. And then stay there rather than cycle back up in the case when no other element is present below the table and table is the last element.
https://github.com/user-attachments/assets/d952a65d-78c5-4dd6-ad6b-b85395712156
Closes #7999
The latest updates on your projects. Learn more about Vercel for GitHub.
| Project | Deployment | Actions | Updated (UTC) |
|---|---|---|---|
| lexical | Preview | Jul 21, 2026 7:38am | |
| lexical-playground | Preview | Jul 21, 2026 7:38am |
offset > 0 catches too much. Consider two tables back-to-back: [Table1][Table2]. The cursor between them is at root offset 1. Table1's handler sees offset > 0, stops the event, and now you can't arrow into Table2. I verified this with a unit test — placing selection at root offset 1 between two tables and dispatching KEY_ARROW_RIGHT_COMMAND returns handled = true with your code (event swallowed), vs false without it.
The fix should confirm we're at a dead end after this table:
if (direction === 'forward') {
const focusNode = selection.focus.getNode();
if (
$isRootOrShadowRoot(focusNode) &&
selection.focus.offset === focusNode.getChildrenSize() &&
focusNode.getLastChild() === tableNode
) {
stopEvent(event);
return true;
}
}
offset === getChildrenSize() = past the last child (actual dead end). getLastChild() === tableNode = this handler's table is the thing we're stuck after.
Aside from that — the feedback on #8030 wasn't just about moving to the table plugin. The inline comments showed a precision pattern: the backward case right below checks $getBlockParentIfFirstNode → getPreviousSibling() → $isTableNode(siblingNode) before acting. The new forward code skips that kind of validation entirely. Moving to the right file was necessary but the level of rigor should match what the rest of the function does.
Some other things:
- The backward case (line 2183) branches on
event.shiftKeyto extend selection. The forward case blocks shift+right too without extending anything. - Every other
return truein this function actively places the cursor (selectEnd(),selection.focus.set(...), etc). This one just stops the event. - No tests — a multi-table scenario would catch the regression.
The cursor geometry here is different from the backward case (root-level element selection vs cursor inside a paragraph), but the principle is the same: verify the table relationship before stopping the event.
offset > 0catches too much. Consider two tables back-to-back:[Table1][Table2]. The cursor between them is at root offset 1. Table1's handler seesoffset > 0, stops the event, and now you can't arrow into Table2. I verified this with a unit test — placing selection at root offset 1 between two tables and dispatchingKEY_ARROW_RIGHT_COMMANDreturnshandled = truewith your code (event swallowed), vsfalsewithout it.The fix should confirm we're at a dead end after this table:
if (direction === 'forward') { const focusNode = selection.focus.getNode(); if ( $isRootOrShadowRoot(focusNode) && selection.focus.offset === focusNode.getChildrenSize() && focusNode.getLastChild() === tableNode ) { stopEvent(event); return true; } }
offset === getChildrenSize()= past the last child (actual dead end).getLastChild() === tableNode= this handler's table is the thing we're stuck after.Aside from that — the feedback on #8030 wasn't just about moving to the table plugin. The inline comments showed a precision pattern: the backward case right below checks
$getBlockParentIfFirstNode→getPreviousSibling()→$isTableNode(siblingNode)before acting. The new forward code skips that kind of validation entirely. Moving to the right file was necessary but the level of rigor should match what the rest of the function does.Some other things:
- The backward case (line 2183) branches on
event.shiftKeyto extend selection. The forward case blocks shift+right too without extending anything.- Every other
return truein this function actively places the cursor (selectEnd(),selection.focus.set(...), etc). This one just stops the event.- No tests — a multi-table scenario would catch the regression.
The cursor geometry here is different from the backward case (root-level element selection vs cursor inside a paragraph), but the principle is the same: verify the table relationship before stopping the event.
Hey @mayrang i think the code you wrote is more reliable . Just one thing is that getLastChild function is deprecated so if we remove that condition i think it still works fine with the first 2 conditions to check the dead end.
getLastChild(): null | LexicalNode is not deprecated, what is deprecated is the form with a generic type argument.
getLastChild(): null | LexicalNodeis not deprecated, what is deprecated is the form with a generic type argument.
(focusNode as ElementNode).__last === tableNode.__key
Hey @etrepum . Is this a better condition ?
Absolutely not. getLastChild() is the correct method to call. It is not deprecated. Calling getLastChild<UnsafeCast>() is the only deprecation.
Absolutely not.
getLastChild()is the correct method to call. It is not deprecated. CallinggetLastChild<UnsafeCast>()is the only deprecation.
if (direction === 'forward') {
const focusNode = selection.focus.getNode();
const focusNodeLastChild = $isElementNode(focusNode)
? focusNode.getLastChild()
: null;
if (
$isRootOrShadowRoot(focusNode) &&
selection.focus.offset === focusNode.getChildrenSize() &&
focusNodeLastChild?.getKey() === tableNode.getKey()
) {
stopEvent(event);
return true;
}
}
The issue with directly comparing the focusNodeLastChild and tableNode is their __next values are different so the comparision always returns false . So in that case comparing keys seems more reliable.
The is method is used to determine if two node instances refer to the same logical node. You’re correct that === will be false when comparing different versions of the same node.
This PR still needs tests before it can be considered for merge. There is nothing that shows what it's supposed to do or tests that it works.
Will add some tests to confirm the behavior
This PR still needs tests before it can be considered for merge. There is nothing that shows what it's supposed to do or tests that it works.
Added added a test case to check the expected behavior
Here are some notes from Claude on the implementation and current approach, overall it looks pretty good but a few things can be tightened up
Review: PR #8858 — Odd selection behavior with table as last element
✅ Verification: tests fail without the fix
I applied the PR's two files and ran the new test both ways:
State Result Fix + test applied 8/8 pass Test applied, source fix reverted 1 fail — ArrowRight at root end after a table…fails atexpect(secondHandled).toBe(true)(receivedfalse)The test genuinely exercises the change. One nuance: only the second ArrowRight assertion depends on the fix — the first
firstHandledreturnstruefrom pre-existing code even without the change, so the new branch's coverage rests entirely on thesecondHandledassertion.The fix itself is narrow and correct: when a range selection's focus is at the root/shadow-root end (
offset === childrenSize) and the last child is thistableNode, forward navigation is swallowed so the caret stays beneath the table — matching the expected behavior in #7999. UsingtableNode.is(...)(key comparison) is the right choice for node versioning.Findings (all minor — none blocks the fix)
1. Missing
isCollapsed()guard on the forward branch —LexicalTableSelectionHelpers.ts:2142(correctness) The new block returnstrue/stopEventwhenever focus is at the root end after the table, without checking the selection is collapsed. A non-collapsed range selection (anchor before the table, focus at rootoffset === childrenSize) would normally collapse to its edge on ArrowRight; now it's swallowed. Shift+ArrowRight is likewise blocked from extending. Narrow, but reachable via block/table-level range selections. Consider gating onselection.isCollapsed().2. Test placed under the wrong
describe—LexicalTableSelectionHelpers.test.ts:372(test organization) The new test is nested insidedescribe('DELETE_LINE_COMMAND in table cells'), so it reports under an unrelated heading. Suggest moving it to its own block, e.g.describe('regression #7999').3. Forward-only fix —
LexicalTableSelectionHelpers.ts:2136(altitude/completeness) Onlydirection === 'forward'is handled. The issue repro is right-arrow-specific so scope is defensible, but ArrowDown out of the last cell reaches the same root-end position with no equivalent stop. Generalizing "caret at root end after last-child table" would be a deeper fix than a forward-only special case.4. Redundant guard / eager computation —
LexicalTableSelectionHelpers.ts:2138(simplification)$isRootOrShadowRoot(focusNode)in the guard already impliesfocusNodeis anElementNode, so the$isElementNode(...) ? getLastChild() : nullternary is dead on the meaningful path and evaluatesgetLastChild()even for non-root focus nodes. ComputegetLastChild()after confirming root:if (direction === 'forward' && $isRootOrShadowRoot(focusNode)) { const focusNode = selection.focus.getNode(); if ( $isRootOrShadowRoot(focusNode) && selection.focus.offset === focusNode.getChildrenSize() && tableNode.is(focusNode.getLastChild()) ) { stopEvent(event); return true; } }
Sure Will take a look at this
Findings (all minor — none blocks the fix)
1. Missing
isCollapsed()guard on the forward branch —LexicalTableSelectionHelpers.ts:2142(correctness) The new block returnstrue/stopEventwhenever focus is at the root end after the table, without checking the selection is collapsed. A non-collapsed range selection (anchor before the table, focus at rootoffset === childrenSize) would normally collapse to its edge on ArrowRight; now it's swallowed. Shift+ArrowRight is likewise blocked from extending. Narrow, but reachable via block/table-level range selections. Consider gating onselection.isCollapsed().2. Test placed under the wrong
describe—LexicalTableSelectionHelpers.test.ts:372(test organization) The new test is nested insidedescribe('DELETE_LINE_COMMAND in table cells'), so it reports under an unrelated heading. Suggest moving it to its own block, e.g.describe('regression #7999').3. Forward-only fix —
LexicalTableSelectionHelpers.ts:2136(altitude/completeness) Onlydirection === 'forward'is handled. The issue repro is right-arrow-specific so scope is defensible, but ArrowDown out of the last cell reaches the same root-end position with no equivalent stop. Generalizing "caret at root end after last-child table" would be a deeper fix than a forward-only special case.4. Redundant guard / eager computation —
LexicalTableSelectionHelpers.ts:2138(simplification)$isRootOrShadowRoot(focusNode)in the guard already impliesfocusNodeis anElementNode, so the$isElementNode(...) ? getLastChild() : nullternary is dead on the meaningful path and evaluatesgetLastChild()even for non-root focus nodes. ComputegetLastChild()after confirming root:
I have fixed 1st and 2nd issues . Regarding the 3rd point , here we are facing the issue only in the case of right arrow command and no other command . So this issue limits to only forward direction.
There is a similar quirk with arrow down that we should also fix here, if you press down from the end of the document and then left or up then the selection does not land in the last table cell
There is a similar quirk with arrow down that we should also fix here, if you press down from the end of the document and then left or up then the selection does not land in the last table cell
I think this issue lies in the below code snippet D:\Lexical\lexical\packages\lexical-table\src\LexicalTableSelectionHelpers.ts Line no. 2303 -
if (direction === 'down' && $isScrollableTablesActive(editor)) {
// Enable Firefox workaround
tableObservers.setShouldCheckSelectionForTable(tableNode.getKey());
}
This makes SELECTION_CHANGE_COMMAND run two times on chromium as well where it should only run on firefox . It must be guarded by using IS_FIREFOX
Updated code -
if (IS_FIREFOX && direction === 'down' && $isScrollableTablesActive(editor)) {
tableObservers.setShouldCheckSelectionForTable(tableNode.getKey());
}
This fixes the issue . Would it be possible if i make a seperate PR for this issue ?
It would be better to consolidate all of the known arrow key workarounds into one PR
Superseded by #9054