Repository navigation
Conversation
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
|
The fix looks right — |
| theme: {}, | ||
| }); | ||
| editor._headless = true; | ||
| }); |
There was a problem hiding this comment.
Nit: since this is a new describe block, it might be worth using buildEditorFromExtensions + using editor — handles cleanup automatically and the codebase is moving in this direction. The same package already uses it in TableImportExtension.test.ts. Something like:
const tableExtension = defineExtension({
name: 'test',
nodes: [TableNode, TableCellNode, TableRowNode],
});
test('inserts the new cell...', () => {
using editor = buildEditorFromExtensions(tableExtension);
editor.update(() => { /* setup */ }, { discrete: true });
editor.update(() => { /* action */ }, { discrete: true });
editor.read(() => { /* assertions */ });
});Not a blocker — the fix itself is correct.
etrepum
left a comment
There was a problem hiding this comment.
Here's a Claude review, it looks like there are some additional edge cases that could be addressed here (unedited claude output below)
Thanks for the fix — the reported case is real and the regression test genuinely fails on main and passes with this change (verified locally). However, the new $insertFirst branch relies on a leftward walk that is itself buggy, and that makes this fix a regression for a neighboring class of grids. Findings ranked by severity, all verified by running counterexamples against this PR's head:
1. 🔴 Regression: the prepend fires spuriously when the walk skips a real row-start cell (LexicalTableUtils.ts:569-576)
The walk above the changed branch decrements by a fixed stride:
prevCellIndex -= currentCell.__colSpan; // L563: always the ORIGINAL cell's spancurrentCell never changes inside the loop, so when the anchor cell has colSpan > 1, the walk steps by that width past cells it never inspected — including cells whose startRow === i. It can then fall off the left edge (prevCellIndex < 0) even though the row does own a cell left of the insertion column. The new comment ("Every cell to the left in this row is covered by a rowSpan") is not true in that case, and prepending corrupts the grid — while the old append happened to be correct there.
Verified repro (passes on main, fails with this PR):
row0: [P, A(rowSpan=2), C(rowSpan=2, colSpan=2)] → grid cols: P=0, A=1, C=2-3
row1: [B] → grid: B=0, cols 1-3 covered
$insertTableColumnAtNode(C, true) → insertAfterColumn = 3
Walk for row 1: index 3 (C) → 3 - 2 = 1 (A) → 1 - 2 = -1 — it skips B at column 0 because it subtracts C's colSpan (2) instead of A's (1). Result:
| before this PR | with this PR | |
|---|---|---|
| row1 grid | ['B', 'A', 'C', 'C', ''] ✅ |
['', 'A', 'C', 'C', 'B'] ❌ (new cell steals column 0, B pushed to column 4) |
2. 🔴 Root cause left unfixed: the walk lands on the wrong cell even when it doesn't hit −1 (LexicalTableUtils.ts:563)
The same fixed-stride bug misplaces the insertion without ever reaching the patched branch. Verified repro (fails identically before and after this PR):
row0: [A, B, V(rowSpan=2), X(rowSpan=2, colSpan=2)] → cols A=0, B=1, V=2, X=3-4
row1: [C0, C1] → cols 0, 1; cols 2-4 covered
$insertTableColumnAtNode(X, true) → insertAfterColumn = 4
Walk for row 1: 4 (X) → 4 - 2 = 2 (V) → 2 - 2 = 0 (C0) — skipping C1 at index 1. The new cell is inserted after C0, so row 1 becomes ['C0', '', 'V', 'X', 'X', 'C1'] instead of ['C0', 'C1', 'V', 'X', 'X', ''].
So fixing only the else branch patches one symptom of the walk while the walk itself still mis-traverses.
3. 🟡 Suggested fix: derive the insertion point from the map, like $unmergeCellNode already does
This exact problem — "find the rightmost cell owned by row i left of a column, or prepend if there is none" — is already solved correctly in the same file by $unmergeCellNode (~L1007-1035): scan rowMap[i] left-to-right below the target column, track the last entry with startRow === i as insertAfterCell, and use $insertFirst when it stays null, insertAfter otherwise. Rewriting this walk in that shape fixes #1 and #2 at once, makes the prepend/append distinction fall out naturally instead of being a special case, and removes the labeled continue rowLoop. Something like:
let insertAfterCell: null | TableCellNode = null;
for (let column = 0; column <= insertAfterColumn; column++) {
const entry = rowMap[column];
if (entry.startRow === i) {
insertAfterCell = entry.cell;
}
column += entry.cell.__colSpan - 1;
}
if (insertAfterCell === null) {
$insertFirst(loopRow, $createTableCellNodeForInsertTableColumn(headerState));
} else {
insertAfterCell.insertAfter($createTableCellNodeForInsertTableColumn(headerState));
}(modulo the existing currentStartColumn + colSpan - 1 > insertAfterColumn → setColSpan case, which stays as-is).
4. 🟡 Test coverage: add a colSpan > 1 covering-cell variant
The new test only exercises all-colSpan=1 grids, so it stays green while repro #1 fails. Adding the #1 grid (or any variant where the covering rowSpan cell has colSpan ≥ 2 and the spanned row still owns a cell) to the new describe block would have caught this.
5. 🔵 Heads-up: this test file was refactored on main and this PR will conflict
main commit 782b6e9 (#8833) rewrote LexicalTableUtils.test.ts to a single shared buildEditorFromExtensions(defineExtension({dependencies: [TableExtension], ...})) setup with afterEach(() => editor.dispose()) and $assertNodeType helpers. This PR (based on an older main) adds a fourth copy of the createEditor + editor._headless = true boilerplate and will conflict on rebase. After rebasing, the new describe block can drop its local beforeEach entirely and use the shared editor + $assertNodeType($getRoot().getFirstChild(), $isTableNode) like the rest of the file (as @mayrang also suggested).
Summary: the direction is right — prepending is correct when the row is genuinely fully covered — but as written the change trades one wrong-alignment case for another. Fixing the walk at L563 (ideally by adopting the $unmergeCellNode scan pattern) makes the prepend sound, and a colSpan > 1 test variant will lock it in.
… covered by a rowSpan $insertTableColumnAtNode walked leftwards from the insertion column with a fixed stride of the anchor cell's colSpan, so with colSpan > 1 it skipped grid positions it never inspected. It could land on the wrong cell, or fall off the left edge and append to the end of the row even when the row owned a cell to the left of the insertion column. Replace the walk with the same left-to-right map scan $unmergeCellNode uses: track the last row map entry with startRow === i at or before the insertion column, insertAfter it, or $insertFirst when there is none. This also removes the labeled continue.
b5b6791 to
110e1cc
Compare
|
@etrepum @mayrang — both repros were real, thanks for running them. Rebased onto main and replaced the leftward walk with the Both of your grids are now tests alongside the original one, and I retitled the PR since the fix is no longer just the prepend case. Teeth-checked by reverting only |
|
It looks like there are conflicts here again (another reason to prefer consolidated PRs) |
… grid indices, cell state and boundary selection ## Description Eleven small table bugs, consolidated into one branch per the review feedback on meta#9027 and meta#9035. They fall into three groups. ### 1. Grid geometry Code that uses a row's child index where the table *grid* column index is required, or that ignores a span. These agree only while every cell has `colSpan === 1`/`rowSpan === 1`, so they are invisible until a table has merged cells. - `$insertTableColumnAtNode` (`packages/lexical-table/src/LexicalTableUtils.ts`) walked leftwards from the insertion column looking for the cell to insert after. When every grid position at or before the insertion column is covered by a `rowSpan` from an earlier row, the walk fell off the left edge and appended the new cell to the *end* of the row, so the inserted column did not line up. Replaced with the same left-to-right map scan `$unmergeCellNode` uses: track the last row-map entry with `startRow === i` at or before the insertion column, `insertAfter` it, or `$insertFirst` when the row owns nothing to the left. This also removes the labeled `continue`. (meta#8836) - `toggleTableColumnIsHeader` (`packages/lexical-playground/src/plugins/TableActionMenuPlugin/index.tsx`) fed `$setTableColumnIsHeader`, which indexes `gridMap[row][columnIndex]`, the result of `$getTableColumnIndexFromTableCellNode` — the cell's index among its row's *children*. With an earlier spanning cell in the row, "Toggle column header" applied to a column left of the one clicked. It now reads `cellMap.startColumn` from `$computeTableMap`. (meta#9006) ### 2. Cell and table state Transforms that rebuild a cell or its paragraph and drop what it carried, plus the `dir` attribute being written onto an element that the export throws away. - `$insertTableIntoGrid` (`LexicalTableUtils.ts`) copies the template cell's `backgroundColor` onto the destination cell but not `verticalAlign`, which was added to `TableCellNode` after that loop (meta#7077). Pasting a table with vertically aligned cells over an existing table dropped the alignment. (meta#9015) - `$tableTransform` (`LexicalTablePluginHelpers.ts`) pads short rows out to the table width with `$createTableCellNode()` and no header state, so a short header row was repaired into a mix of `<th>` and `<td>`. The padding cells now inherit the `TableCellHeaderStates.ROW` bit from the row's last cell — the same reference `$insertTableColumnAtNode` uses when it appends a column. (meta#9023) - `$unmergeCellNode` (`LexicalTableUtils.ts`) recomputes the header state of the cells it splits off, correctly, but gives them nothing else, so a filled merged cell unmerged into one filled cell and a run of blank ones. The split cells now keep the original's `backgroundColor` and `verticalAlign`, which is the cell's own presentation and not a description of its row or column. (meta#9025) - `TableNode.exportDOM` (`LexicalTableNode.ts`) narrows the export to `element.querySelector('table')`. When scrollable tables are active `createDOM` returns the scroll wrapper `<div>`, which is where `ElementNode.exportDOM` writes `dir` — so the wrapper, and the direction with it, was thrown away. The direction is now re-applied to the `<table>`, which is where `$convertTableElement` reads it back. (meta#9029) - `TableObserver.$clearText` (`LexicalTableObserver.ts`) emptied each selected cell by constructing a fresh `ParagraphNode`, so Backspace over a multi-cell selection also reset the format, style, direction and indent of those cells. It now `$copyNode`s the cell's existing paragraph, which carries the element state and returns a childless copy. (meta#9041) ### 3. Selection and caret at the table boundary - The `KEY_ARROW_LEFT_COMMAND`/`KEY_ARROW_RIGHT_COMMAND` handlers in `registerRichText` (`packages/lexical-rich-text/src/index.ts`) had no equivalent of the `$isSelectionAtEndOfRoot`/`$isSelectionAtStartOfRoot` guards the up/down handlers already use. With a table as the last node of the document the key fell through to the native caret, which walks around the block cursor element, so the caret cycled: last cell → block cursor → root offset before the table → back into the last cell. A new `$isBlockCursorAtRootEdge` consumes the key when the collapsed element point sits at the root edge beside a child that needs a block cursor. Non-collapsed selections and block cursors that still have a sibling to move into are untouched. (meta#8949, fixes meta#7999) - `$handleArrowKey` (`LexicalTableSelectionHelpers.ts`) armed the Firefox scrollable-table workaround (`setShouldCheckSelectionForTable`) on every ArrowDown. From the block cursor below a trailing table ArrowDown moves nothing, so the flag survived to be consumed by the next selection change — an ArrowUp back into the table — which snapped the caret to the first cell. A new `$isSelectionBeforeTable` arms it only when the focus is before the table in document order, the only side ArrowDown can enter from. (meta#8963, fixes meta#6822) - `$deleteTableRowAtSelection` (`LexicalTableUtils.ts`) removes the table outright when the selection covers every row, but never moved the selection first, leaving a `TableSelection` anchored to detached nodes. Added the `grid.selectPrevious()` that `$deleteTableColumnAtSelection` and `TableObserver.$clearText` already do in their identical branches. (meta#9037) - `$adjustFocusInDirection` (`LexicalTableSelectionHelpers.ts`) called `getCornerOrThrow` on the rect from `$computeTableCellRectBoundary`, which *grows* the rect until it contains every merged cell straddling an edge — so the anchor is not guaranteed to be at a corner, and Shift+Arrow killed the editor update with an invariant. `getCornerOrThrow` is replaced by `getAnchorCorner`, which falls back the same way `$extractRectCorners` 24 lines below already does: to the corner opposite the focus, then to the top-left. (meta#9045) ## Test plan Unit tests cover ten of the eleven fixes, two browser tests cover the caret/arrow-key behaviour at the table boundary, and meta#9006 is a Playwright spec (`packages/lexical-playground/__tests__/regression/7266-column-header-merged-cells.spec.mjs`). ### Before Source fixes reverted, new tests kept: ``` $ npx vitest run --project unit packages/lexical-table packages/lexical-rich-text × pasting a table carries the cell backgroundColor and verticalAlign 6ms × a short header row is padded with header cells 5ms × extends the selection instead of throwing 73ms × keeps the paragraph format, style and direction of each cell 89ms × inserts the new cell in the correct column for rows spanned by a rowSpan cell 7ms × exports dir with scrollable tables active 31ms × leaves the selection outside the removed table 13ms × ArrowRight at the block cursor after the last block stays put 5ms × ArrowLeft at the block cursor before the first block stays put 1ms × the cells a merged cell splits into keep its backgroundColor and verticalAlign 13ms ⎯⎯⎯⎯⎯⎯⎯ Failed Tests 10 ⎯⎯⎯⎯⎯⎯⎯ Test Files 8 failed | 23 passed (31) Tests 10 failed | 291 passed (301) $ npx vitest run --project browser packages/lexical-table/src/__tests__/browser/TableTrailingCaret.test.ts packages/lexical-table/src/__tests__/browser/Issue6822BlockCursorArrowKeys.test.ts × the caret stops beneath a trailing table instead of cycling around it 172ms × ArrowUp from the block cursor below a trailing table returns to the last row 380ms × ArrowUp from the block cursor below a table that is the only root child returns to the last row 355ms Test Files 2 failed (2) Tests 3 failed | 2 passed (5) ``` The remaining new cases pass on both sides of the change — the unstyled-unmerge, short-body-row, non-wrapped-export, delete-every-column and still-owns-a-cell-to-the-left cases — which is what pins each asymmetry rather than the fix itself. ### After ``` $ npx vitest run --project unit packages/lexical-table packages/lexical-rich-text Test Files 31 passed (31) Tests 301 passed (301) $ npx vitest run --project browser packages/lexical-table/src/__tests__/browser/TableTrailingCaret.test.ts packages/lexical-table/src/__tests__/browser/Issue6822BlockCursorArrowKeys.test.ts Test Files 2 passed (2) Tests 5 passed (5) $ npx playwright test --project=chromium Tables.spec.mjs TablesHTMLCopyAndPaste.spec.mjs 7266-column-header-merged-cells.spec.mjs 99 passed, 1 skipped $ npx tsc --noEmit -p . (clean) ``` Supersedes meta#8836, meta#8949, meta#8963, meta#9006, meta#9015, meta#9023, meta#9025, meta#9029, meta#9037, meta#9041, meta#9045, consolidated per the review feedback on meta#9027 and meta#9035. meta#9000 and meta#9011 were part of an earlier revision of this PR and have been dropped, because each contradicted an existing e2e expectation rather than extending it: - meta#9000 imported `dir` in the `DOMImportExtension` table rules. Google Sheets emits `<table dir="ltr">` unconditionally, so `Copy + paste (Table - Google Sheets)` in `TablesHTMLCopyAndPaste.spec.mjs` went from `dir="auto"` to a pinned `dir="ltr"` on the table, and the rows below it stopped emitting `dir="auto"` at all. Honouring a pasted `dir` is a deliberate behaviour change for third-party HTML and needs its own PR. - meta#9011 made the right-edge resizer widen the *last* grid column a merged cell spans instead of its first. `Resize merged cells width (2)` in `Tables.spec.mjs` pins the existing behaviour, and both variants widen the merged cell identically — they differ only in which unmerged column absorbs the change, so this is a behaviour preference that needs a maintainer call.
Description
$insertTableColumnAtNodewalks left from the insertion column to find the cell in each row to insert after. The walk steps by a fixed stride:currentCellnever changes inside the loop, so it always steps by the anchor cell's colSpan. When that is greater than 1 the walk jumps over grid columns it never inspects, and lands on the wrong cell — or falls off the left edge and appends to the end of the row.Two failure modes, both reproducible:
The walk goes 4 → 2 → 0, skipping
C1, so row1 becomes['C0', '', 'V', 'X', 'X', 'C1']instead of['C0', 'C1', 'V', 'X', 'X', ''].The walk goes 3 → 1 → -1 and appends, even though row1 owns
Bat column 0.Fix
Derive the insertion point from the row map the way
$unmergeCellNodealready does in this file: scanrowMapfrom column 0 up toinsertAfterColumn, skipping by each entry'scolSpan, and keep the last entry whosestartRowis this row. That entry is the cell to insert after; when there is none, every column to the left is covered by arowSpanfrom an earlier row, so the new cell is the row's first child and is added with$insertFirst.The prepend/append distinction now falls out of the scan instead of being a special case, and the labeled
continue rowLoopis gone. ThesetColSpanbranch is unchanged.Test plan
Three tests in
LexicalTableUtils.test.ts, using the file's sharedbuildEditorFromExtensionseditor: the originalrowSpan=2alignment case plus both grids above.Teeth-checked by reverting only
LexicalTableUtils.ts:main$insertFirst-only version of this PRpackages/lexical-tableis 151/151; the full unit suite is 4969 passed / 1 skipped;tsc --noEmit, eslint and prettier clean.