Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions .changeset/table-selection-ragged-rows.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
---
'@lexical/table': patch
---

[fix] A table selection in a table whose rows have different numbers of cells no longer throws (`Cannot destructure property 'cell' of 'map[i][j]'`), and deleting, copying or pasting it keeps the cells it does not hold

Such a ragged table can stay that way after collaborators insert a row and a column at the same time, or after loading JSON that has it. `TableSelection.getNodes()`, aligning a table selection and exporting a table to HTML now skip the grid positions that no cell covers, and a selected row with no cell of its own stays in the copy (a blank line in its plain text) when a later selected row has one, so rows keep their places when it is pasted. Deleting a table selection removes the table only when it holds every cell of the table, not whenever it holds the first and last cells, which also stops a rectangular table from being removed when a cell spanning rows in another column is not selected. A selection with a short first row holds a merged cell further right whole. Pasting a copied ragged selection takes the widest row and leaves a target cell at a position the pasted table has no cell for as it is.

Verify: in a table with rows of 2, 1, 3 and 2 cells, select from the first cell to the last, press Delete and check that the third cell of the third row keeps its text; copy and paste the selection into another table and check that nothing throws and the rows keep their places.
3 changes: 3 additions & 0 deletions packages/lexical-table/src/LexicalTableNode.ts
Original file line number Diff line number Diff line change
Expand Up @@ -667,6 +667,9 @@ export class TableNode extends ElementNode {
>();
for (const mapRow of tableMap) {
for (const mapValue of mapRow) {
if (mapValue === undefined) {
continue; // no cell here in a ragged table
}
const key = mapValue.cell.getKey();
if (!cellValues.has(key)) {
cellValues.set(key, {
Expand Down
25 changes: 14 additions & 11 deletions packages/lexical-table/src/LexicalTableObserver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -599,18 +599,21 @@ export class TableObserver {

const selectedNodes = selection.getNodes().filter($isTableCellNode);

// Check if the entire table is selected by verifying first and last cells
const firstRow = tableNode.getFirstChild();
const lastRow = tableNode.getLastChild();

// The entire table is selected when the selection holds every cell. (In
// a table whose rows have different numbers of cells, a selection from
// the first cell to the last can leave out cells of a longer row.)
let cellCount = 0;
for (const row of tableNode.getChildren()) {
if ($isTableRowNode(row)) {
cellCount += row.getChildrenSize();
}
}
const isEntireTableSelected =
selectedNodes.length > 0 &&
firstRow !== null &&
lastRow !== null &&
$isTableRowNode(firstRow) &&
$isTableRowNode(lastRow) &&
selectedNodes[0] === firstRow.getFirstChild() &&
selectedNodes[selectedNodes.length - 1] === lastRow.getLastChild();
cellCount > 0 &&
selectedNodes.filter(cell => {
const row = cell.getParent();
return row !== null && row.getParent() === tableNode;
}).length === cellCount;

if (isEntireTableSelected) {
tableNode.selectPrevious();
Expand Down
55 changes: 48 additions & 7 deletions packages/lexical-table/src/LexicalTableSelection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -377,9 +377,36 @@ export class TableSelection implements BaseSelection {
[tableNode.getKey(), tableNode],
]);
let lastRow: null | TableRowNode = null;
// A row the selection spans with no cell of its own in it (only cells
// spanning from above, or holes in a ragged table) belongs to it when a
// later row has a cell of its own or a hole there, so that a copy keeps
// the later rows in place. Trailing rows covered only by spans are left
// out, as before.
let lastRowNeeded = minRow - 1;
for (let i = minRow; i <= maxRow; i++) {
for (let j = minColumn; j <= maxColumn; j++) {
const {cell} = map[i][j];
const value = map[i][j];
if (value === undefined || value.startRow === i) {
lastRowNeeded = i;
break;
}
}
}
const rowNodes = tableNode.getChildren();
for (let i = minRow; i <= maxRow; i++) {
const rowNode = rowNodes[i];
if (i <= lastRowNeeded && $isTableRowNode(rowNode)) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Optional, non-blocking: when the last row the selection spans has only a hole and row-spanned cells in the rectangle, this row is added after every cell, so getNodes() ends on a TableRowNode. $insertNodeToNearestRoot starts from the last node (packages/lexical-utils/src/index.ts:750-753), and the node it inserts never reaches the document. Repro: [['OUT', A (rowSpan 2), 'B'], ['OUT2']], select A→B, insert a paragraph. main threw here, so this is not a regression, but a follow-up could keep the last node inside a cell or give $insertNodeToNearestRoot a focus-cell path for TableSelection.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Not worse than main: there the same selection throws in getNodes(), so the insert is lost with an error. The trailing row is kept on purpose (a copy needs it so that a pasted row span is not cut short). Filed as #9756 to fix in $insertNodeToNearestRoot or getNodes() separately; listed under still open in the description.

nodeMap.set(rowNode.getKey(), rowNode);
lastRow = rowNode;
}
for (let j = minColumn; j <= maxColumn; j++) {
const value = map[i][j];
if (value === undefined) {
// A ragged table (rows of different lengths, e.g. after concurrent
// row and column inserts) has no cell here.
continue;
}
const {cell} = value;
const currentRow = cell.getParent();
invariant(
$isTableRowNode(currentRow),
Expand All @@ -405,13 +432,27 @@ export class TableSelection implements BaseSelection {
}

getTextContent(): string {
const nodes = this.getNodes().filter(node => $isTableCellNode(node));
const allNodes = this.getNodes();
const nodes = allNodes.filter(node => $isTableCellNode(node));
// The rows of the table that hold no selected cell of their own (rows a
// ragged table or a row span leaves empty within the selection) are
// blank lines, so that the lines keep their rows.
const rowsWithCells = new Set(nodes.map(node => node.__parent));
let textContent = '';
for (let i = 0; i < nodes.length; i++) {
const node = nodes[i];
const row = node.__parent;
const nextRow = (nodes[i + 1] || {}).__parent;
textContent += node.getTextContent() + (nextRow !== row ? '\n' : '\t');
let cellIndex = 0;
for (const node of allNodes) {
if ($isTableCellNode(node)) {
const row = node.__parent;
const nextRow = (nodes[cellIndex + 1] || {}).__parent;
textContent += node.getTextContent() + (nextRow !== row ? '\n' : '\t');
cellIndex++;
} else if (
$isTableRowNode(node) &&
node.__parent === this.tableKey &&
!rowsWithCells.has(node.__key)
) {
textContent += '\n';
}
}
return textContent;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1111,7 +1111,12 @@ export function applyTableHandlers(
const visited = new Set<TableCellNode>();
for (let i = minRow; i <= maxRow; i++) {
for (let j = minColumn; j <= maxColumn; j++) {
const cell = tableMap[i][j].cell;
const value = tableMap[i][j];
if (value === undefined) {
// No cell here in a ragged table.
continue;
}
const cell = value.cell;
if (visited.has(cell)) {
continue;
}
Expand Down
19 changes: 17 additions & 2 deletions packages/lexical-table/src/LexicalTableUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1330,7 +1330,8 @@ export function $computeTableCellRectBoundary(

// Check all cells in the table
for (let row = 0; row < map.length; row++) {
for (let col = 0; col < map[0].length; col++) {
// Rows can have different lengths in a ragged table.
for (let col = 0; col < map[row].length; col++) {
const cell = map[row][col];
if (!cell) {
continue;
Expand Down Expand Up @@ -1594,7 +1595,11 @@ export function $insertTableIntoGrid(
let startRow = anchorCellMap.startRow;
let startCol = anchorCellMap.startColumn;
let affectedRowCount = templateGridMap.length;
let affectedColCount = affectedRowCount > 0 ? templateGridMap[0].length : 0;
// The widest row: the pasted table's rows can have different lengths.
let affectedColCount = templateGridMap.reduce(
(width, row) => Math.max(width, row.length),
0,
);

if (isTableSel) {
const selectionBoundary = $computeTableCellRectBoundary(
Expand All @@ -1621,6 +1626,13 @@ export function $insertTableIntoGrid(
const unmergedKeys = new Set<NodeKey>();
for (let row = startRow; row <= lastRowForUnmerge; row++) {
for (let col = startCol; col <= lastColForUnmerge; col++) {
const templateRowMap = templateGridMap[row - startRow];
if (
templateRowMap === undefined ||
templateRowMap[col - startCol] === undefined
) {
continue; // the pasted table has no cell here: leave this one be
}
const cellMap = initialGridMap[row][col];
if (unmergedKeys.has(cellMap.cell.getKey())) {
continue; // cell was a merged cell that was already handled
Expand Down Expand Up @@ -1664,6 +1676,9 @@ export function $insertTableIntoGrid(
const templateRow = row - startRow;
const templateCol = col - startCol;
const templateCellMap = templateGridMap[templateRow][templateCol];
if (templateCellMap === undefined) {
continue; // no cell here in a ragged pasted table: leave this one be
}
if (
templateCellMap.startRow !== templateRow ||
templateCellMap.startColumn !== templateCol
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,200 @@
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*/

import {$getClipboardDataFromSelection} from '@lexical/clipboard';
import {buildEditorFromExtensions} from '@lexical/extension';
import {
$createTableCellNode,
$createTableNode,
$createTableRowNode,
$createTableSelection,
$isTableCellNode,
$isTableNode,
$padTableRows,
TableExtension,
type TableNode,
} from '@lexical/table';
import {
$createParagraphNode,
$createTextNode,
$getRoot,
$getSelection,
$setSelection,
defineExtension,
type ElementNode,
FORMAT_ELEMENT_COMMAND,
type LexicalEditor,
} from 'lexical';
import {describe, expect, test} from 'vitest';

// A table whose rows have different lengths, as a merge of concurrent row and
// column inserts by collaborators can leave it (remote updates skip the table
// transform, and the transform leaves rows it did not change alone). Cells
// are named `r<row>c<index>`; `rowSpan` cells are `[text, rowSpan]`.
type Spec = (string | [string, number])[][];

function buildEditor(rows: Spec) {
const built = buildEditorFromExtensions(
defineExtension({
afterRegistration(editor) {
// The table selection observer, which handles FORMAT_ELEMENT_COMMAND,
// needs the editor to have a root element.
const container = document.createElement('div');
document.body.appendChild(container);
editor.setRootElement(container);
return () => document.body.removeChild(container);
},
dependencies: [TableExtension],
name: '[ragged-table-selection]',
onError: (error: Error) => {
throw error;
},
}),
);
built.update(
() => {
const table = $createTableNode();
for (const cells of rows) {
const row = $createTableRowNode();
for (const spec of cells) {
const [text, rowSpan] = typeof spec === 'string' ? [spec, 1] : spec;
row.append(
$createTableCellNode()
.setRowSpan(rowSpan)
.append($createParagraphNode().append($createTextNode(text))),
);
}
table.append(row);
}
$getRoot().clear().append(table, $createParagraphNode());
},
// As a remote update applies it: without the table transform.
{discrete: true, skipTransforms: true},
);
return built;
}

const $table = () => $getRoot().getChildren().find($isTableNode) as TableNode;
const $cellNamed = (name: string) =>
$table()
.getAllTextNodes()
.find(node => node.getTextContent() === name)!
.getParentOrThrow()
.getParentOrThrow();
const names = (rows: Spec) =>
rows.flat().map(spec => (typeof spec === 'string' ? spec : spec[0]));

// The texts of the cells a table selection from `anchor` to `focus` holds.
function selectedCells(
editor: LexicalEditor,
anchor: string,
focus: string,
): string[] {
let cells: string[] = [];
editor.update(
() => {
const selection = $createTableSelection();
selection.set(
$table().getKey(),
$cellNamed(anchor).getKey(),
$cellNamed(focus).getKey(),
);
$setSelection(selection);
const tableSelection = $getSelection()!;
cells = tableSelection
.getNodes()
.filter($isTableCellNode)
.map(cell => cell.getTextContent());
// Copying it reads the same nodes.
const copied = $getClipboardDataFromSelection(tableSelection);
expect(Object.keys(copied).length).toBeGreaterThan(0);
},
{discrete: true},
);
return cells;
}

const SHAPES: [string, Spec][] = [
[
'a short middle row',
[
['r0c0', 'r0c1', 'r0c2', 'r0c3'],
['r1c0', 'r1c1'],
['r2c0', 'r2c1', 'r2c2', 'r2c3'],
],
],
[
'a short first row',
[
['r0c0', 'r0c1'],
['r1c0', 'r1c1', 'r1c2', 'r1c3'],
['r2c0', 'r2c1', 'r2c2'],
],
],
[
'a short last row under a row span',
[['r0c0', ['r0c1', 2], 'r0c2'], ['r1c0', 'r1c1'], ['r2c0']],
],
];

describe('a table selection in a ragged table', () => {
for (const [label, rows] of SHAPES) {
test(`holds the cells it holds once the table is padded: ${label}`, () => {
const ragged = buildEditor(rows);
const padded = buildEditor(rows);
padded.update(() => $padTableRows($table()), {discrete: true});
for (const anchor of names(rows)) {
for (const focus of names(rows)) {
const expected = selectedCells(padded, anchor, focus).filter(
text => text !== '',
);
expect(selectedCells(ragged, anchor, focus)).toEqual(expected);
}
}
ragged.dispose();
padded.dispose();
});

test(`aligns every cell it holds: ${label}`, () => {
for (const anchor of names(rows)) {
for (const focus of names(rows)) {
const editor = buildEditor(rows);
const cells = selectedCells(editor, anchor, focus);
editor.update(
() => {
editor.dispatchCommand(FORMAT_ELEMENT_COMMAND, 'center');
},
{discrete: true},
);
const centered = editor.read(() =>
$table()
.getAllTextNodes()
.filter(node => {
const paragraph = node.getParentOrThrow();
const cell = paragraph.getParentOrThrow() as ElementNode;
// The cell and the paragraph in it are both aligned.
return (
cell.getFormatType() === 'center' &&
paragraph.getFormatType() === 'center'
);
})
.map(node => node.getTextContent()),
);
if (editor.read(() => $table().getFormatType()) === 'center') {
// A selection spanning the table's first row and every row
// formats the table itself.
expect(centered).toEqual([]);
} else {
expect(centered.sort()).toEqual([...cells].sort());
}
editor.dispose();
}
}
});
}
});
Loading
Loading