diff --git a/.changeset/table-selection-ragged-rows.md b/.changeset/table-selection-ragged-rows.md new file mode 100644 index 000000000000..dab91f7c7b92 --- /dev/null +++ b/.changeset/table-selection-ragged-rows.md @@ -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. diff --git a/packages/lexical-table/src/LexicalTableNode.ts b/packages/lexical-table/src/LexicalTableNode.ts index 5ad3c0e7efd7..b37dd8cb0db1 100644 --- a/packages/lexical-table/src/LexicalTableNode.ts +++ b/packages/lexical-table/src/LexicalTableNode.ts @@ -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, { diff --git a/packages/lexical-table/src/LexicalTableObserver.ts b/packages/lexical-table/src/LexicalTableObserver.ts index bace5eb2a728..0476818e07ab 100644 --- a/packages/lexical-table/src/LexicalTableObserver.ts +++ b/packages/lexical-table/src/LexicalTableObserver.ts @@ -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(); diff --git a/packages/lexical-table/src/LexicalTableSelection.ts b/packages/lexical-table/src/LexicalTableSelection.ts index 37b995011a81..9dbad14a5997 100644 --- a/packages/lexical-table/src/LexicalTableSelection.ts +++ b/packages/lexical-table/src/LexicalTableSelection.ts @@ -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)) { + 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), @@ -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; } diff --git a/packages/lexical-table/src/LexicalTableSelectionHelpers.ts b/packages/lexical-table/src/LexicalTableSelectionHelpers.ts index b2233c7362e3..56a7721dde89 100644 --- a/packages/lexical-table/src/LexicalTableSelectionHelpers.ts +++ b/packages/lexical-table/src/LexicalTableSelectionHelpers.ts @@ -1111,7 +1111,12 @@ export function applyTableHandlers( const visited = new Set(); 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; } diff --git a/packages/lexical-table/src/LexicalTableUtils.ts b/packages/lexical-table/src/LexicalTableUtils.ts index 5c3c25430921..cc216eff34ba 100644 --- a/packages/lexical-table/src/LexicalTableUtils.ts +++ b/packages/lexical-table/src/LexicalTableUtils.ts @@ -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; @@ -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( @@ -1621,6 +1626,13 @@ export function $insertTableIntoGrid( const unmergedKeys = new Set(); 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 @@ -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 diff --git a/packages/lexical-table/src/__tests__/unit/RaggedTableSelection.test.ts b/packages/lexical-table/src/__tests__/unit/RaggedTableSelection.test.ts new file mode 100644 index 000000000000..c3c8b43b0ed8 --- /dev/null +++ b/packages/lexical-table/src/__tests__/unit/RaggedTableSelection.test.ts @@ -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 `rc`; `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(); + } + } + }); + } +}); diff --git a/packages/lexical-table/src/__tests__/unit/RaggedTableSelectionClipboard.test.ts b/packages/lexical-table/src/__tests__/unit/RaggedTableSelectionClipboard.test.ts new file mode 100644 index 000000000000..a4b00115f09d --- /dev/null +++ b/packages/lexical-table/src/__tests__/unit/RaggedTableSelectionClipboard.test.ts @@ -0,0 +1,398 @@ +/** + * 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, + $insertDataTransferForRichText, +} from '@lexical/clipboard'; +import {buildEditorFromExtensions} from '@lexical/extension'; +import { + $computeTableMapSkipCellCheck, + $createTableCellNode, + $createTableNode, + $createTableRowNode, + $createTableSelectionFrom, + $isTableCellNode, + $isTableNode, + TableCellHeaderStates, + TableExtension, + type TableRowNode, +} from '@lexical/table'; +import { + $createParagraphNode, + $createTextNode, + $getRoot, + $getSelection, + $setSelection, + configExtension, + defineExtension, + KEY_DELETE_COMMAND, + type LexicalEditor, +} from 'lexical'; +import {assert, expect, test} from 'vitest'; + +import {$computeTableCellRectBoundary} from '../../LexicalTableUtils'; + +// A table whose rows have different numbers of cells, as collaborators' +// concurrent row and column inserts can leave it (remote updates skip the +// table transform). Cells are their text, or [text, colSpan, rowSpan]. +type Spec = (string | [string, number, number])[][]; + +function build(rows: Spec) { + const editor = buildEditorFromExtensions( + defineExtension({ + afterRegistration(ed) { + // The table selection observer, which handles the commands below, + // needs the editor to have a root element. + const root = document.createElement('div'); + document.body.append(root); + ed.setRootElement(root); + return () => root.remove(); + }, + dependencies: [configExtension(TableExtension, {hasNestedTables: true})], + name: '[ragged-table-selection-clipboard]', + // Lexical clipboard data pastes into an editor of the same namespace. + namespace: 'ragged-table-selection-clipboard', + onError: (error: Error) => { + throw error; + }, + theme: {tableScrollableWrapper: 'table-scrollable-wrapper'}, + }), + ); + editor.update( + () => { + const table = $createTableNode(); + for (const specs of rows) { + const row = $createTableRowNode(); + for (const spec of specs) { + const [text, colSpan, rowSpan] = + typeof spec === 'string' ? [spec, 1, 1] : spec; + row.append( + $createTableCellNode() + .setColSpan(colSpan) + .setRowSpan(rowSpan) + .append($createParagraphNode().append($createTextNode(text))), + ); + } + table.append(row); + } + $getRoot().clear().append(table, $createParagraphNode()); + }, + {discrete: true, skipTransforms: true}, + ); + return editor; +} + +function $table() { + const table = $getRoot().getChildren().find($isTableNode); + assert(table !== undefined, 'expected a table'); + return table; +} + +function $cell(name: string) { + const cell = $table() + .getChildren() + .flatMap(row => (row as TableRowNode).getChildren()) + .find(node => node.getTextContent() === name); + assert($isTableCellNode(cell), `expected a cell ${name}`); + return cell; +} + +function select(editor: LexicalEditor, anchor: string, focus: string) { + editor.update( + () => + $setSelection( + $createTableSelectionFrom($table(), $cell(anchor), $cell(focus)), + ), + {discrete: true}, + ); +} + +function $texts() { + return $table() + .getChildren() + .map(row => + (row as TableRowNode).getChildren().map(cell => cell.getTextContent()), + ); +} +function paste( + source: LexicalEditor, + target: LexicalEditor, + a: string, + f: string, + targetA: string, + targetF?: string, + mime = 'application/x-lexical-editor', +) { + select(source, a, f); + const copied = source.read(() => + $getClipboardDataFromSelection($getSelection()!), + ); + const data = new DataTransfer(); + data.setData(mime, copied[mime as keyof typeof copied]!); + target.update( + () => { + const selection = targetF + ? $createTableSelectionFrom($table(), $cell(targetA), $cell(targetF)) + : $cell(targetA).selectStart(); + $setSelection(selection); + $insertDataTransferForRichText(data, selection); + }, + {discrete: true}, + ); +} + +for (const [label, rows, a, f] of [ + [ + 'rectangular', + [ + ['A', 'B'], + ['C', 'D'], + ], + 'A', + 'D', + ], + ['colspan', [[['A', 2, 1]], ['B', 'C']], 'A', 'C'], + ['rowspan at the right edge', [['A', ['B', 1, 2]], ['C']], 'A', 'B'], + ['one merged cell', [[['A', 2, 2]], []], 'A', 'A'], +] as [string, Spec, string, string][]) { + test(`full ${label} selection removes the table, including header cells`, () => { + using editor = build(rows); + editor.update( + () => { + for (const row of $table().getChildren()) { + for (const cell of (row as TableRowNode).getChildren()) { + if ($isTableCellNode(cell)) + cell.setHeaderStyles(TableCellHeaderStates.BOTH); + } + } + }, + {discrete: true, skipTransforms: true}, + ); + select(editor, a, f); + editor.update( + () => + editor.dispatchCommand( + KEY_DELETE_COMMAND, + new KeyboardEvent('keydown'), + ), + {discrete: true}, + ); + expect(editor.read(() => $getRoot().getChildren().some($isTableNode))).toBe( + false, + ); + }); +} + +test('a partial outer selection containing a whole inner table does not remove the outer table', () => { + using editor = build([ + ['A', 'B'], + ['C', 'D'], + ]); + editor.update( + () => { + const nested = $createTableNode(); + nested.append( + $createTableRowNode().append( + $createTableCellNode().append( + $createParagraphNode().append($createTextNode('INNER')), + ), + ), + ); + $cell('A').append(nested); + const first = ( + $table().getFirstChildOrThrow() as TableRowNode + ).getFirstChildOrThrow(); + assert($isTableCellNode(first)); + $setSelection($createTableSelectionFrom($table(), first, $cell('B'))); + }, + {discrete: true}, + ); + editor.update( + () => + editor.dispatchCommand(KEY_DELETE_COMMAND, new KeyboardEvent('keydown')), + {discrete: true}, + ); + expect(editor.read($texts)).toEqual([ + ['', ''], + ['C', 'D'], + ]); +}); + +for (const mime of ['application/x-lexical-editor', 'text/html']) { + test(`copy/paste keeps an entirely uncovered middle row at its original position (${mime})`, () => { + using source = build([['A', 'B', 'C'], ['D'], ['E', 'F', 'G']]); + using target = build([['T0'], ['KEEP'], ['T2']]); + paste(source, target, 'B', 'F', 'T0', undefined, mime); + expect(target.read($texts)).toEqual([['B'], ['KEEP'], ['F']]); + }); +} + +test('pasting a ragged merged template next to holes preserves hole texts and resets a reversed selection', () => { + using source = build([[['M', 2, 1]], ['X'], ['Y', 'Z']]); + using target = build([ + ['A', 'B', 'OUT0'], + ['C', 'KEEP', 'OUT1'], + ['D', 'E', 'OUT2'], + ]); + paste(source, target, 'M', 'Z', 'E', 'A'); + expect(target.read($texts)).toEqual([ + ['M', 'OUT0'], + ['X', 'KEEP', 'OUT1'], + ['Y', 'Z', 'OUT2'], + ]); + expect( + target.read(() => + $getSelection()! + .getNodes() + .every(n => n.isAttached()), + ), + ).toBe(true); +}); + +test('wider later rows grow the destination in both dimensions without duplicating text', () => { + using source = build([['X'], ['Y', 'Z', 'W'], ['Q', 'R', 'S']]); + using target = build([ + ['KEEP0', 'KEEP1'], + ['KEEP2', 'START'], + ]); + paste(source, target, 'X', 'S', 'START'); + expect(target.read($texts)).toEqual([ + ['KEEP0', 'KEEP1', '', ''], + ['KEEP2', 'X', '', ''], + ['', 'Y', 'Z', 'W'], + ['', 'Q', 'R', 'S'], + ]); +}); + +test('a table selection smaller than a ragged merged template clips it and keeps every outside cell', () => { + using source = build([[['M', 3, 1]], ['X'], ['Y', 'Z', 'W']]); + using target = build([ + ['A', 'B', 'OUT0'], + ['C', 'KEEP', 'OUT1'], + ['OUT2', 'OUT3', 'OUT4'], + ]); + paste(source, target, 'M', 'W', 'A', 'KEEP'); + expect(target.read($texts)).toEqual([ + ['M', 'OUT0'], + ['X', 'KEEP', 'OUT1'], + ['OUT2', 'OUT3', 'OUT4'], + ]); +}); + +test('an interior widest row pulled into the selection by a merge is fully pasted', () => { + using source = build([ + ['X', 'Y'], + ['Z', ['M', 2, 1]], + ['Q', 'R'], + ]); + using target = build([ + ['A', 'B', 'KEEP0'], + ['C', 'D', 'E'], + ['F', 'G', 'KEEP2'], + ]); + paste(source, target, 'X', 'R', 'A'); + expect(target.read($texts)).toEqual([ + ['X', 'Y', 'KEEP0'], + ['Z', 'M'], + ['Q', 'R', 'KEEP2'], + ]); +}); + +test('rect boundary expands through a finite chain of overlapping merges and stops before unrelated cells', () => { + using editor = build([ + ['A'], + ['B', 'C', ['M', 2, 1], 'OUT'], + ['D', 'E', 'F', ['N', 2, 1]], + ['G', 'H', 'I', 'J', 'K', 'OUT2'], + ]); + editor.read(() => { + const [map] = $computeTableMapSkipCellCheck($table(), null, null); + const boundary = $computeTableCellRectBoundary(map, map[1][1], map[3][2]); + expect(boundary).toEqual({ + maxColumn: 4, + maxRow: 3, + minColumn: 1, + minRow: 1, + }); + }); +}); + +test('a destination merge covered only by source holes keeps its cells and spans', () => { + using source = build([['X', 'Y', 'Z'], ['Q'], ['R']]); + using target = build([['A', 'B', 'C'], ['D', ['KEEP', 2, 2]], ['E']]); + paste(source, target, 'Z', 'R', 'A', 'KEEP'); + expect( + target.read(() => [$cell('KEEP').getColSpan(), $cell('KEEP').getRowSpan()]), + ).toEqual([2, 2]); + expect(target.read($texts)).toEqual([['X', 'Y', 'Z'], ['Q', 'KEEP'], ['R']]); +}); + +// The old first/last-node test incorrectly removed this rectangular grid: +// A and C are its first and last physical cells, but B spans the other column. +test('selecting first and last physical cells leaves an unselected rowspan cell intact', () => { + using editor = build([['A', ['B', 1, 2]], ['C']]); + select(editor, 'A', 'C'); + editor.update( + () => + editor.dispatchCommand(KEY_DELETE_COMMAND, new KeyboardEvent('keydown')), + {discrete: true}, + ); + expect(editor.read($texts)).toEqual([['', 'B'], ['']]); +}); + +test('a full outer selection still removes the table when its last cell contains a nested table', () => { + using editor = build([ + ['A', 'B'], + ['C', 'D'], + ]); + editor.update( + () => { + const last = $cell('D'); + last.append( + $createTableNode().append( + $createTableRowNode().append( + $createTableCellNode().append( + $createParagraphNode().append($createTextNode('INNER')), + ), + ), + ), + ); + $setSelection($createTableSelectionFrom($table(), $cell('A'), last)); + }, + {discrete: true}, + ); + editor.update( + () => + editor.dispatchCommand(KEY_DELETE_COMMAND, new KeyboardEvent('keydown')), + {discrete: true}, + ); + expect(editor.read(() => $getRoot().getChildren().some($isTableNode))).toBe( + false, + ); +}); + +for (const mime of ['application/x-lexical-editor', 'text/html']) { + test(`copying a table with a row covered by row spans pastes it in place (${mime})`, () => { + using source = build([ + [ + ['A', 1, 2], + ['B', 1, 2], + ], + [], + ['E', 'F'], + ]); + using target = build([ + ['T0', 'T1'], + ['T2', 'T3'], + ['T4', 'T5'], + ]); + paste(source, target, 'A', 'F', 'T0', undefined, mime); + expect(target.read($texts)).toEqual([['A', 'B'], [], ['E', 'F']]); + }); +} diff --git a/packages/lexical-table/src/__tests__/unit/RaggedTableSelectionCommands.test.ts b/packages/lexical-table/src/__tests__/unit/RaggedTableSelectionCommands.test.ts new file mode 100644 index 000000000000..1c60367ae6ab --- /dev/null +++ b/packages/lexical-table/src/__tests__/unit/RaggedTableSelectionCommands.test.ts @@ -0,0 +1,279 @@ +/** + * 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, + $insertDataTransferForRichText, +} from '@lexical/clipboard'; +import {buildEditorFromExtensions} from '@lexical/extension'; +import { + $createTableCellNode, + $createTableNode, + $createTableNodeWithDimensions, + $createTableRowNode, + $createTableSelectionFrom, + $isTableCellNode, + $isTableNode, + TableExtension, + type TableRowNode, +} from '@lexical/table'; +import { + $createParagraphNode, + $createTextNode, + $getRoot, + $getSelection, + $setSelection, + CUT_COMMAND, + defineExtension, + FORMAT_ELEMENT_COMMAND, + KEY_BACKSPACE_COMMAND, + KEY_DELETE_COMMAND, + type LexicalEditor, +} from 'lexical'; +import {assert, describe, expect, test} from 'vitest'; + +// A table whose rows have different numbers of cells, as collaborators' +// concurrent row and column inserts can leave it (remote updates skip the +// table transform). Cells are their text, or [text, colSpan, rowSpan]. +type Spec = (string | [string, number, number])[][]; + +function build(rows: Spec) { + const editor = buildEditorFromExtensions( + defineExtension({ + afterRegistration(ed) { + // The table selection observer, which handles the commands below, + // needs the editor to have a root element. + const root = document.createElement('div'); + document.body.append(root); + ed.setRootElement(root); + return () => root.remove(); + }, + dependencies: [TableExtension], + name: '[ragged-table-selection-commands]', + // Lexical clipboard data pastes into an editor of the same namespace. + namespace: 'ragged-table-selection-commands', + onError: (error: Error) => { + throw error; + }, + theme: {tableScrollableWrapper: 'table-scrollable-wrapper'}, + }), + ); + editor.update( + () => { + const table = $createTableNode(); + for (const specs of rows) { + const row = $createTableRowNode(); + for (const spec of specs) { + const [text, colSpan, rowSpan] = + typeof spec === 'string' ? [spec, 1, 1] : spec; + row.append( + $createTableCellNode() + .setColSpan(colSpan) + .setRowSpan(rowSpan) + .append($createParagraphNode().append($createTextNode(text))), + ); + } + table.append(row); + } + $getRoot().clear().append(table, $createParagraphNode()); + }, + {discrete: true, skipTransforms: true}, + ); + return editor; +} + +function $table() { + const table = $getRoot().getChildren().find($isTableNode); + assert(table !== undefined, 'expected a table'); + return table; +} + +function $cell(name: string) { + const cell = $table() + .getChildren() + .flatMap(row => (row as TableRowNode).getChildren()) + .find(node => node.getTextContent() === name); + assert($isTableCellNode(cell), `expected a cell ${name}`); + return cell; +} + +function select(editor: LexicalEditor, anchor: string, focus: string) { + editor.update( + () => + $setSelection( + $createTableSelectionFrom($table(), $cell(anchor), $cell(focus)), + ), + {discrete: true}, + ); +} + +const $selectedCells = () => + $getSelection()! + .getNodes() + .filter($isTableCellNode) + .map(cell => cell.getTextContent()); + +// A to G holds every row's first two cells, but not KEEP. +const HOLE_ROWS: Spec = [['A', 'B'], ['C'], ['D', 'E', 'KEEP'], ['F', 'G']]; + +describe('commands on a table selection in a ragged table', () => { + for (const [label, command] of [ + ['delete', KEY_DELETE_COMMAND], + ['backspace', KEY_BACKSPACE_COMMAND], + ] as const) { + test(`${label} clears the selected cells and keeps a cell outside the selection`, () => { + using editor = build(HOLE_ROWS); + select(editor, 'A', 'G'); + editor.update( + () => editor.dispatchCommand(command, new KeyboardEvent('keydown')), + {discrete: true}, + ); + expect( + editor.read(() => + $table() + .getAllTextNodes() + .map(node => node.getTextContent()) + .filter(text => text !== ''), + ), + ).toEqual(['KEEP']); + }); + } + + test('cut copies the selected cells and keeps a cell outside the selection', () => { + using editor = build(HOLE_ROWS); + select(editor, 'A', 'G'); + const data = new DataTransfer(); + editor.update( + () => + editor.dispatchCommand( + CUT_COMMAND, + new ClipboardEvent('cut', {clipboardData: data}), + ), + {discrete: true}, + ); + for (const mime of [ + 'text/plain', + 'text/html', + 'application/x-lexical-editor', + ]) { + expect(data.getData(mime)).toContain('G'); + expect(data.getData(mime)).not.toContain('KEEP'); + } + expect(editor.read(() => $getRoot().getTextContent())).toContain('KEEP'); + }); + + test('delete removes the table when the selection holds every cell', () => { + using editor = build([['A', 'B'], ['C'], ['D', 'E']]); + select(editor, 'A', 'E'); + editor.update( + () => + editor.dispatchCommand( + KEY_DELETE_COMMAND, + new KeyboardEvent('keydown'), + ), + {discrete: true}, + ); + expect(editor.read(() => $getRoot().getChildren().some($isTableNode))).toBe( + false, + ); + }); + + test('delete removes a table with a nested table when the selection holds every cell', () => { + using editor = build([ + ['A', 'B'], + ['C', 'D'], + ]); + editor.update( + () => { + $cell('B').append($createTableNodeWithDimensions(2, 2, false)); + }, + {discrete: true}, + ); + select(editor, 'A', 'D'); + editor.update( + () => + editor.dispatchCommand( + KEY_DELETE_COMMAND, + new KeyboardEvent('keydown'), + ), + {discrete: true}, + ); + expect(editor.read(() => $getRoot().getChildren().some($isTableNode))).toBe( + false, + ); + }); + + test('a merged cell beyond a short first row is held whole', () => { + using editor = build([ + ['A'], + ['B', 'C', ['M', 2, 1]], + ['D', 'E', 'F', 'G'], + ]); + select(editor, 'C', 'F'); + expect(editor.read($selectedCells)).toEqual(['C', 'M', 'E', 'F', 'G']); + editor.update( + () => editor.dispatchCommand(FORMAT_ELEMENT_COMMAND, 'center'), + {discrete: true}, + ); + expect(editor.read(() => $cell('G').getFormatType())).toBe('center'); + }); + + function copyAndPaste( + source: LexicalEditor, + target: LexicalEditor, + anchor: string, + focus: string, + ) { + select(source, anchor, focus); + const copied = source.read(() => + $getClipboardDataFromSelection($getSelection()!), + ); + const data = new DataTransfer(); + data.setData( + 'application/x-lexical-editor', + copied['application/x-lexical-editor']!, + ); + target.update( + () => $insertDataTransferForRichText(data, $cell('A').selectStart()), + {discrete: true}, + ); + } + + test('pasting a copied ragged selection leaves the cell at its missing position alone', () => { + using source = build([['X', 'Y'], ['Z'], ['Q', 'R']]); + using target = build([ + ['A', 'B'], + ['C', 'D'], + ['E', 'F'], + ]); + copyAndPaste(source, target, 'X', 'R'); + expect( + target.read(() => + $table() + .getAllTextNodes() + .map(node => node.getTextContent()), + ), + ).toEqual(['X', 'Y', 'Z', 'D', 'Q', 'R']); + }); + + test('pasting a copied selection with a short first row pastes the longer rows whole', () => { + using source = build([['X'], ['Y', 'Z']]); + using target = build([ + ['A', 'B'], + ['C', 'D'], + ]); + copyAndPaste(source, target, 'X', 'Z'); + expect( + target.read(() => + $table() + .getAllTextNodes() + .map(node => node.getTextContent()), + ), + ).toEqual(['X', 'B', 'Y', 'Z']); + }); +}); diff --git a/packages/lexical-table/src/__tests__/unit/RaggedTableSelectionCoveredRows.test.ts b/packages/lexical-table/src/__tests__/unit/RaggedTableSelectionCoveredRows.test.ts new file mode 100644 index 000000000000..0954dc51f717 --- /dev/null +++ b/packages/lexical-table/src/__tests__/unit/RaggedTableSelectionCoveredRows.test.ts @@ -0,0 +1,275 @@ +/** + * 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, + $insertDataTransferForRichText, +} from '@lexical/clipboard'; +import {buildEditorFromExtensions} from '@lexical/extension'; +import { + $createTableCellNode, + $createTableNode, + $createTableRowNode, + $createTableSelectionFrom, + $isTableCellNode, + $isTableNode, + TableCellHeaderStates, + TableExtension, + type TableRowNode, +} from '@lexical/table'; +import { + $createParagraphNode, + $createTextNode, + $getRoot, + $getSelection, + $setSelection, + configExtension, + CUT_COMMAND, + defineExtension, + type LexicalEditor, +} from 'lexical'; +import {assert, expect, test} from 'vitest'; + +// A table whose rows have different numbers of cells, as collaborators' +// concurrent row and column inserts can leave it (remote updates skip the +// table transform). Cells are their text, or [text, colSpan, rowSpan]. +type Spec = (string | [string, number, number])[][]; + +function build(rows: Spec) { + const editor = buildEditorFromExtensions( + defineExtension({ + afterRegistration(ed) { + // The table selection observer, which handles the commands below, + // needs the editor to have a root element. + const root = document.createElement('div'); + document.body.append(root); + ed.setRootElement(root); + return () => root.remove(); + }, + dependencies: [configExtension(TableExtension, {hasNestedTables: true})], + name: '[ragged-table-selection-covered-rows]', + // Lexical clipboard data pastes into an editor of the same namespace. + namespace: 'ragged-table-selection-covered-rows', + onError: (error: Error) => { + throw error; + }, + theme: { + tableCellSelected: 'selected', + tableScrollableWrapper: 'table-scrollable-wrapper', + }, + }), + ); + editor.update( + () => { + const table = $createTableNode(); + for (const specs of rows) { + const row = $createTableRowNode(); + for (const spec of specs) { + const [text, colSpan, rowSpan] = + typeof spec === 'string' ? [spec, 1, 1] : spec; + row.append( + $createTableCellNode() + .setColSpan(colSpan) + .setRowSpan(rowSpan) + .append($createParagraphNode().append($createTextNode(text))), + ); + } + table.append(row); + } + $getRoot().clear().append(table, $createParagraphNode()); + }, + {discrete: true, skipTransforms: true}, + ); + return editor; +} + +function $table() { + const table = $getRoot().getChildren().find($isTableNode); + assert(table !== undefined, 'expected a table'); + return table; +} + +function $cell(name: string) { + const cell = $table() + .getChildren() + .flatMap(row => (row as TableRowNode).getChildren()) + .find(node => node.getTextContent() === name); + assert($isTableCellNode(cell), `expected a cell ${name}`); + return cell; +} + +function select(editor: LexicalEditor, anchor: string, focus: string) { + editor.update( + () => + $setSelection( + $createTableSelectionFrom($table(), $cell(anchor), $cell(focus)), + ), + {discrete: true}, + ); +} + +function $texts() { + return $table() + .getChildren() + .map(row => + (row as TableRowNode).getChildren().map(cell => cell.getTextContent()), + ); +} +function paste( + source: LexicalEditor, + target: LexicalEditor, + a: string, + f: string, + targetA: string, + targetF?: string, + mime = 'application/x-lexical-editor', +) { + select(source, a, f); + const copied = source.read(() => + $getClipboardDataFromSelection($getSelection()!), + ); + const data = new DataTransfer(); + data.setData(mime, copied[mime as keyof typeof copied]!); + target.update( + () => { + const selection = targetF + ? $createTableSelectionFrom($table(), $cell(targetA), $cell(targetF)) + : $cell(targetA).selectStart(); + $setSelection(selection); + $insertDataTransferForRichText(data, selection); + }, + {discrete: true}, + ); +} + +// Valid source spans end at row 1, within the four physical rows. +// Column 1: B, B, hole, E. The copy must keep all four positions. +const OMITTED_COVERED_ROW: Spec = [['A', ['B', 1, 2]], [], ['C'], ['D', 'E']]; + +for (const mime of ['application/x-lexical-editor', 'text/html']) { + test(`copying a covered row before a hole retains all physical rows (${mime})`, () => { + using source = build(OMITTED_COVERED_ROW); + select(source, 'B', 'E'); + source.read(() => { + expect( + $getSelection()! + .getNodes() + .filter($isTableCellNode) + .map(c => c.getTextContent()), + ).toEqual(['B', 'E']); + const data = $getClipboardDataFromSelection($getSelection()!); + const counts = + mime === 'application/x-lexical-editor' + ? JSON.parse(data[mime]!).nodes[0].children.map( + (row: {children: unknown[]}) => row.children.length, + ) + : [ + ...new DOMParser() + .parseFromString(data[mime]!, 'text/html') + .querySelectorAll('tr'), + ].map(r => r.querySelectorAll('td,th').length); + expect(counts).toEqual([1, 0, 0, 1]); + }); + }); + + for (const header of [false, true]) { + test(`paste keeps E below the hole and preserves KEEP (${mime}, header=${header})`, () => { + using source = build(OMITTED_COVERED_ROW); + if (header) + source.update( + () => { + $cell('B').setHeaderStyles(TableCellHeaderStates.BOTH); + $cell('E').setHeaderStyles(TableCellHeaderStates.BOTH); + }, + {discrete: true, skipTransforms: true}, + ); + using target = build([['T0'], ['T1'], ['KEEP'], ['T3']]); + paste(source, target, 'B', 'E', 'T0', undefined, mime); + expect(target.read($texts)).toEqual([['B'], [], ['KEEP'], ['E']]); + }); + } + + test(`cut followed by paste does not overwrite text at the hole (${mime})`, () => { + using source = build(OMITTED_COVERED_ROW); + select(source, 'B', 'E'); + const data = new DataTransfer(); + source.update( + () => + source.dispatchCommand( + CUT_COMMAND, + new ClipboardEvent('cut', {clipboardData: data}), + ), + {discrete: true}, + ); + expect(source.read($texts)).toEqual([['A', ''], [], ['C'], ['D', '']]); + const onlyMime = new DataTransfer(); + onlyMime.setData(mime, data.getData(mime)); + using target = build([['T0'], ['T1'], ['KEEP'], ['T3']]); + target.update( + () => { + const selection = $cell('T0').selectStart(); + $insertDataTransferForRichText(onlyMime, selection); + }, + {discrete: true}, + ); + expect(target.read($texts)).toEqual([['B'], [], ['KEEP'], ['E']]); + }); +} + +for (const mime of ['application/x-lexical-editor', 'text/html']) { + test(`cutting the whole ragged table and pasting into a table selection keeps D (${mime})`, () => { + using source = build([ + [ + ['A', 1, 3], + ['B', 1, 2], + ], + [], + [], + ['C', 'D'], + ]); + select(source, 'A', 'D'); + const data = new DataTransfer(); + source.update( + () => + source.dispatchCommand( + CUT_COMMAND, + new ClipboardEvent('cut', {clipboardData: data}), + ), + {discrete: true}, + ); + expect(source.read(() => $getRoot().getChildren().some($isTableNode))).toBe( + false, + ); + using target = build([ + ['T00', 'T01'], + ['T10', 'T11'], + ['KEEP0', 'KEEP1'], + ['T30', 'T31'], + ]); + const onlyMime = new DataTransfer(); + onlyMime.setData(mime, data.getData(mime)); + target.update( + () => { + const selection = $createTableSelectionFrom( + $table(), + $cell('T00'), + $cell('T31'), + ); + $setSelection(selection); + $insertDataTransferForRichText(onlyMime, selection); + }, + {discrete: true}, + ); + expect(target.read($texts)).toEqual([ + ['A', 'B'], + [], + ['KEEP1'], + ['C', 'D'], + ]); + }); +} diff --git a/packages/lexical-table/src/__tests__/unit/RaggedTableSelectionRowSpans.test.ts b/packages/lexical-table/src/__tests__/unit/RaggedTableSelectionRowSpans.test.ts new file mode 100644 index 000000000000..a02b7cdc2bde --- /dev/null +++ b/packages/lexical-table/src/__tests__/unit/RaggedTableSelectionRowSpans.test.ts @@ -0,0 +1,239 @@ +/** + * 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 { + $generateJSONFromSelectedNodes, + $getClipboardDataFromSelection, + $insertDataTransferForRichText, +} from '@lexical/clipboard'; +import {buildEditorFromExtensions} from '@lexical/extension'; +import { + $createTableCellNode, + $createTableNode, + $createTableRowNode, + $createTableSelectionFrom, + $isTableCellNode, + $isTableNode, + TableExtension, + type TableRowNode, +} from '@lexical/table'; +import { + $createParagraphNode, + $createTextNode, + $getRoot, + $getSelection, + $setSelection, + configExtension, + defineExtension, + FORMAT_ELEMENT_COMMAND, + KEY_DELETE_COMMAND, + type LexicalEditor, +} from 'lexical'; +import {assert, expect, test} from 'vitest'; + +// A table whose rows have different numbers of cells, as collaborators' +// concurrent row and column inserts can leave it (remote updates skip the +// table transform). Cells are their text, or [text, colSpan, rowSpan]. +type Spec = (string | [string, number, number])[][]; + +function build(rows: Spec) { + const editor = buildEditorFromExtensions( + defineExtension({ + afterRegistration(ed) { + // The table selection observer, which handles the commands below, + // needs the editor to have a root element. + const root = document.createElement('div'); + document.body.append(root); + ed.setRootElement(root); + return () => root.remove(); + }, + dependencies: [configExtension(TableExtension, {hasNestedTables: true})], + name: '[ragged-table-selection-row-spans]', + // Lexical clipboard data pastes into an editor of the same namespace. + namespace: 'ragged-table-selection-row-spans', + onError: (error: Error) => { + throw error; + }, + theme: { + tableCellSelected: 'selected', + tableScrollableWrapper: 'table-scrollable-wrapper', + }, + }), + ); + editor.update( + () => { + const table = $createTableNode(); + for (const specs of rows) { + const row = $createTableRowNode(); + for (const spec of specs) { + const [text, colSpan, rowSpan] = + typeof spec === 'string' ? [spec, 1, 1] : spec; + row.append( + $createTableCellNode() + .setColSpan(colSpan) + .setRowSpan(rowSpan) + .append($createParagraphNode().append($createTextNode(text))), + ); + } + table.append(row); + } + $getRoot().clear().append(table, $createParagraphNode()); + }, + {discrete: true, skipTransforms: true}, + ); + return editor; +} + +function $table() { + const table = $getRoot().getChildren().find($isTableNode); + assert(table !== undefined, 'expected a table'); + return table; +} + +function $cell(name: string) { + const cell = $table() + .getChildren() + .flatMap(row => (row as TableRowNode).getChildren()) + .find(node => node.getTextContent() === name); + assert($isTableCellNode(cell), `expected a cell ${name}`); + return cell; +} + +function select(editor: LexicalEditor, anchor: string, focus: string) { + editor.update( + () => + $setSelection( + $createTableSelectionFrom($table(), $cell(anchor), $cell(focus)), + ), + {discrete: true}, + ); +} + +function $texts() { + return $table() + .getChildren() + .map(row => + (row as TableRowNode).getChildren().map(cell => cell.getTextContent()), + ); +} +function paste( + source: LexicalEditor, + target: LexicalEditor, + a: string, + f: string, + targetA: string, + targetF?: string, + mime = 'application/x-lexical-editor', +) { + select(source, a, f); + const copied = source.read(() => + $getClipboardDataFromSelection($getSelection()!), + ); + const data = new DataTransfer(); + data.setData(mime, copied[mime as keyof typeof copied]!); + target.update( + () => { + const selection = targetF + ? $createTableSelectionFrom($table(), $cell(targetA), $cell(targetF)) + : $cell(targetA).selectStart(); + $setSelection(selection); + $insertDataTransferForRichText(data, selection); + }, + {discrete: true}, + ); +} + +for (const mime of ['application/x-lexical-editor', 'text/html']) { + test(`an interior-hole row crossed by a selected rowspan keeps its position (${mime})`, () => { + using source = build([['X', 'Y', ['SPAN', 1, 3]], ['KEEP'], ['Q', 'R']]); + select(source, 'Y', 'SPAN'); + source.read(() => { + const selection = $getSelection()!; + expect( + selection + .getNodes() + .filter($isTableCellNode) + .map(c => c.getTextContent()), + ).toEqual(['Y', 'SPAN', 'R']); + if (mime === 'application/x-lexical-editor') { + const json = $generateJSONFromSelectedNodes(source, selection); + expect(json.nodes[0].children!.map(r => r.children!.length)).toEqual([ + 2, 0, 1, + ]); + return; + } + const data = $getClipboardDataFromSelection(selection); + const html = new DOMParser().parseFromString( + data['text/html']!, + 'text/html', + ); + expect( + [...html.querySelectorAll('tr')].map( + r => r.querySelectorAll('td,th').length, + ), + ).toEqual([2, 0, 1]); + }); + }); +} + +for (const mime of ['application/x-lexical-editor', 'text/html']) { + test(`copy/paste does not move R into a hole beside a rowspan (${mime})`, () => { + using source = build([['X', 'Y', ['SPAN', 1, 3]], ['KEEP'], ['Q', 'R']]); + using target = build([ + ['A', 'B'], + ['HOLE', 'D'], + ['E', 'F'], + ]); + paste(source, target, 'Y', 'SPAN', 'A', undefined, mime); + expect(target.read($texts)).toEqual([['Y', 'SPAN'], ['HOLE'], ['R']]); + }); +} + +for (const mime of ['application/x-lexical-editor', 'text/html']) { + test(`an uncovered interior hole row with an unselected rowspan farther right survives (${mime})`, () => { + using source = build([['X', 'Y', ['SPAN', 1, 3]], ['KEEP'], ['Q', 'R']]); + using target = build([['A'], ['HOLE'], ['E']]); + paste(source, target, 'Y', 'R', 'A', undefined, mime); + expect(target.read($texts)).toEqual([['Y'], ['HOLE'], ['R']]); + }); +} + +test('ragged selected cell texts, DOM highlight, alignment and deletion agree beside a rowspan', () => { + using editor = build([['X', 'Y', ['SPAN', 1, 3]], ['KEEP'], ['Q', 'R']]); + select(editor, 'Y', 'R'); + editor.read(() => { + expect($getSelection()!.getTextContent()).toBe('Y\n\nR\n'); + expect( + $getSelection()! + .getNodes() + .filter($isTableCellNode) + .map(c => c.getTextContent()), + ).toEqual(['Y', 'R']); + }); + expect( + [...editor.getRootElement()!.querySelectorAll('td.selected')].map( + c => c.textContent, + ), + ).toEqual(['Y', 'R']); + editor.update( + () => editor.dispatchCommand(FORMAT_ELEMENT_COMMAND, 'center'), + {discrete: true}, + ); + editor.read(() => { + expect($cell('Y').getFormatType()).toBe('center'); + expect($cell('R').getFormatType()).toBe('center'); + expect($cell('SPAN').getFormatType()).toBe(''); + expect($cell('KEEP').getFormatType()).toBe(''); + }); + editor.update( + () => + editor.dispatchCommand(KEY_DELETE_COMMAND, new KeyboardEvent('keydown')), + {discrete: true}, + ); + expect(editor.read($texts)).toEqual([['X', '', 'SPAN'], ['KEEP'], ['Q', '']]); +}); diff --git a/packages/lexical-table/src/__tests__/unit/RaggedTableSelectionRows.test.ts b/packages/lexical-table/src/__tests__/unit/RaggedTableSelectionRows.test.ts new file mode 100644 index 000000000000..610f33d7d6c4 --- /dev/null +++ b/packages/lexical-table/src/__tests__/unit/RaggedTableSelectionRows.test.ts @@ -0,0 +1,466 @@ +/** + * 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 { + $generateJSONFromSelectedNodes, + $getClipboardDataFromSelection, + $insertDataTransferForRichText, +} from '@lexical/clipboard'; +import {buildEditorFromExtensions} from '@lexical/extension'; +import { + $computeTableMapSkipCellCheck, + $createTableCellNode, + $createTableNode, + $createTableRowNode, + $createTableSelectionFrom, + $isTableCellNode, + $isTableNode, + $isTableRowNode, + TableExtension, + type TableRowNode, +} from '@lexical/table'; +import { + $createParagraphNode, + $createTextNode, + $getRoot, + $getSelection, + $isElementNode, + $setSelection, + configExtension, + defineExtension, + KEY_DELETE_COMMAND, + type LexicalEditor, + type LexicalNode, +} from 'lexical'; +import {assert, expect, test} from 'vitest'; + +import {$computeTableCellRectBoundary} from '../../LexicalTableUtils'; + +// A table whose rows have different numbers of cells, as collaborators' +// concurrent row and column inserts can leave it (remote updates skip the +// table transform). Cells are their text, or [text, colSpan, rowSpan]. +type Spec = (string | [string, number, number])[][]; + +function build(rows: Spec) { + const editor = buildEditorFromExtensions( + defineExtension({ + afterRegistration(ed) { + // The table selection observer, which handles the commands below, + // needs the editor to have a root element. + const root = document.createElement('div'); + document.body.append(root); + ed.setRootElement(root); + return () => root.remove(); + }, + dependencies: [configExtension(TableExtension, {hasNestedTables: true})], + name: '[ragged-table-selection-rows]', + // Lexical clipboard data pastes into an editor of the same namespace. + namespace: 'ragged-table-selection-rows', + onError: (error: Error) => { + throw error; + }, + theme: { + tableCellSelected: 'selected', + tableScrollableWrapper: 'table-scrollable-wrapper', + }, + }), + ); + editor.update( + () => { + const table = $createTableNode(); + for (const specs of rows) { + const row = $createTableRowNode(); + for (const spec of specs) { + const [text, colSpan, rowSpan] = + typeof spec === 'string' ? [spec, 1, 1] : spec; + row.append( + $createTableCellNode() + .setColSpan(colSpan) + .setRowSpan(rowSpan) + .append($createParagraphNode().append($createTextNode(text))), + ); + } + table.append(row); + } + $getRoot().clear().append(table, $createParagraphNode()); + }, + {discrete: true, skipTransforms: true}, + ); + return editor; +} + +function $table() { + const table = $getRoot().getChildren().find($isTableNode); + assert(table !== undefined, 'expected a table'); + return table; +} + +function $cell(name: string) { + const cell = $table() + .getChildren() + .flatMap(row => (row as TableRowNode).getChildren()) + .find(node => node.getTextContent() === name); + assert($isTableCellNode(cell), `expected a cell ${name}`); + return cell; +} + +function select(editor: LexicalEditor, anchor: string, focus: string) { + editor.update( + () => + $setSelection( + $createTableSelectionFrom($table(), $cell(anchor), $cell(focus)), + ), + {discrete: true}, + ); +} + +function $texts() { + return $table() + .getChildren() + .map(row => + (row as TableRowNode).getChildren().map(cell => cell.getTextContent()), + ); +} +function paste( + source: LexicalEditor, + target: LexicalEditor, + a: string, + f: string, + targetA: string, + targetF?: string, + mime = 'application/x-lexical-editor', +) { + select(source, a, f); + const copied = source.read(() => + $getClipboardDataFromSelection($getSelection()!), + ); + const data = new DataTransfer(); + data.setData(mime, copied[mime as keyof typeof copied]!); + target.update( + () => { + const selection = targetF + ? $createTableSelectionFrom($table(), $cell(targetA), $cell(targetF)) + : $cell(targetA).selectStart(); + $setSelection(selection); + $insertDataTransferForRichText(data, selection); + }, + {discrete: true}, + ); +} + +// Unlike an uncovered row, this empty physical row has map entries from above. +test('a row fully covered by row spans belongs to the selection', () => { + using editor = build([ + [ + ['A', 1, 2], + ['B', 1, 2], + ], + [], + ['C', 'D'], + ]); + select(editor, 'A', 'D'); + editor.read(() => { + const rows = $table().getChildren(); + const nodes = $getSelection()!.getNodes(); + expect(nodes.filter($isTableRowNode)).toEqual(rows); + expect(new Set(nodes.map(n => n.getKey())).size).toBe(nodes.length); + expect(nodes.filter($isTableCellNode).map(n => n.getTextContent())).toEqual( + ['A', 'B', 'C', 'D'], + ); + }); +}); + +test('multiple uncovered rows export in order without leaking their unselected cells', () => { + using editor = build([ + ['A', 'B'], + ['KEEP1'], + ['KEEP2'], + ['C', 'D'], + ['KEEP3'], + ['E', 'F'], + ]); + select(editor, 'B', 'F'); + editor.read(() => { + const nodes = $getSelection()!.getNodes(); + expect(nodes.filter($isTableRowNode)).toEqual($table().getChildren()); + expect(new Set(nodes.map(n => n.getKey())).size).toBe(nodes.length); + expect(nodes.filter($isTableCellNode).map(n => n.getTextContent())).toEqual( + ['B', 'D', 'F'], + ); + const json = $generateJSONFromSelectedNodes(editor, $getSelection()); + expect(json.nodes[0].children!.map(r => r.children!.length)).toEqual([ + 1, 0, 0, 1, 0, 1, + ]); + const copied = $getClipboardDataFromSelection($getSelection()); + const dom = new DOMParser().parseFromString( + copied['text/html']!, + 'text/html', + ); + expect( + [...dom.querySelectorAll('tr')].map( + r => r.querySelectorAll('td,th').length, + ), + ).toEqual([1, 0, 0, 1, 0, 1]); + expect(copied['application/x-lexical-editor']).not.toContain('KEEP'); + expect(copied['text/html']).not.toContain('KEEP'); + expect($getSelection()!.getTextContent()).toBe('B\n\n\nD\n\nF\n'); + }); + expect(editor.getRootElement()!.querySelectorAll('td.selected')).toHaveLength( + 3, + ); + editor.update( + () => + editor.dispatchCommand(KEY_DELETE_COMMAND, new KeyboardEvent('keydown')), + {discrete: true}, + ); + expect(editor.read($texts)).toEqual([ + ['A', ''], + ['KEEP1'], + ['KEEP2'], + ['C', ''], + ['KEEP3'], + ['E', ''], + ]); +}); + +test('insertNodes still uses the focus cell when uncovered rows are selected', () => { + using editor = build([['A', 'B'], ['KEEP'], ['C', 'D']]); + select(editor, 'B', 'D'); + editor.update( + () => + $getSelection()!.insertNodes([ + $createParagraphNode().append($createTextNode('NEW')), + ]), + {discrete: true}, + ); + expect(editor.read($texts)).toEqual([['A', 'B'], ['KEEP'], ['C', 'NEW']]); +}); + +for (const mime of ['application/x-lexical-editor', 'text/html']) { + for (const [label, sourceRows, targetRows, a, f, targetA, expected] of [ + [ + 'colspan covered only by holes', + [['X', 'Y', 'Z'], ['Q'], ['R', 'S', 'T']], + [ + ['A', 'B', 'C'], + ['D', ['KEEP', 2, 1]], + ['E', 'F', 'G'], + ], + 'X', + 'T', + 'A', + [ + ['X', 'Y', 'Z'], + ['Q', 'KEEP'], + ['R', 'S', 'T'], + ], + ], + [ + 'colspan starts on a cell, ends on a hole', + [ + ['X', 'Y', 'Z'], + ['Q', 'R'], + ['S', 'T', 'U'], + ], + [ + ['A', 'B', 'C'], + ['D', ['OLD', 2, 1]], + ['E', 'F', 'G'], + ], + 'X', + 'U', + 'A', + [ + ['X', 'Y', 'Z'], + ['Q', 'R', ''], + ['S', 'T', 'U'], + ], + ], + [ + 'rowspan starts on a hole, ends on a cell', + [['X', 'Y'], ['Q'], ['R', 'S']], + [['A', 'B'], ['C', ['KEEP', 1, 2]], ['D']], + 'X', + 'S', + 'A', + [ + ['X', 'Y'], + ['Q', 'KEEP'], + ['R', 'S'], + ], + ], + [ + 'rowspan starts on a cell, ends on a hole', + [['X', 'Y'], ['Q', 'R'], ['S']], + [['A', 'B'], ['C', ['OLD', 1, 2]], ['D']], + 'Y', + 'S', + 'A', + [ + ['X', 'Y'], + ['Q', 'R'], + ['S', ''], + ], + ], + [ + 'two-dimensional merge touches one pasted corner', + [['X', 'Y', 'Z'], ['Q'], ['R', 'S']], + [['A', 'B', 'C'], ['D', ['KEEP', 2, 2]], ['E']], + 'Z', + 'R', + 'A', + [ + ['X', 'Y', 'Z'], + ['Q', 'KEEP', ''], + ['R', 'S', ''], + ], + ], + ] as [string, Spec, Spec, string, string, string, string[][]][]) { + test(`mixed overlap: ${label} (${mime})`, () => { + using source = build(sourceRows); + using target = build(targetRows); + paste(source, target, a, f, targetA, undefined, mime); + expect(target.read($texts)).toEqual(expected); + target.read(() => { + const [map] = $computeTableMapSkipCellCheck($table(), null, null); + const keys = $table() + .getChildren() + .flatMap(r => (r as TableRowNode).getChildren().map(c => c.getKey())); + expect(new Set(keys).size).toBe(keys.length); + for (const row of map) + for (const value of row) { + expect(value.cell.isAttached()).toBe(true); + expect(value.cell.getColSpan()).toBe( + label === 'colspan covered only by holes' && + value.cell.getTextContent() === 'KEEP' + ? 2 + : 1, + ); + expect(value.cell.getRowSpan()).toBe(1); + } + }); + }); + } +} + +test('copying a selection with an interior hole beside a rowspan does not throw', () => { + using editor = build([['X', 'Y', ['SPAN', 1, 2]], ['Q']]); + select(editor, 'X', 'SPAN'); + editor.read(() => { + expect( + $getSelection()! + .getNodes() + .filter($isTableCellNode) + .map(n => n.getTextContent()), + ).toEqual(['X', 'Y', 'SPAN', 'Q']); + expect( + $generateJSONFromSelectedNodes( + editor, + $getSelection(), + ).nodes[0].children!.map(row => row.children!.length), + ).toEqual([3, 1]); + expect(() => $getClipboardDataFromSelection($getSelection())).not.toThrow(); + }); +}); + +for (const mime of ['application/x-lexical-editor', 'text/html']) { + test(`a truly empty physical row is retained by copy and paste (${mime})`, () => { + using source = build([['A', 'B'], [], ['C', 'D']]); + using target = build([ + ['T0', 'T1'], + ['KEEP0', 'KEEP1'], + ['T2', 'T3'], + ]); + paste(source, target, 'A', 'D', 'T0', undefined, mime); + expect(target.read($texts)).toEqual([ + ['A', 'B'], + ['KEEP0', 'KEEP1'], + ['C', 'D'], + ]); + }); +} + +for (const [label, shape] of [ + [ + 'ordinary rectangle', + [ + ['A', 'B'], + ['C', 'D'], + ], + ], + [ + 'mixed row and column spans', + [ + ['A', ['B', 2, 2], 'C'], + ['D', 'E'], + ['F', 'G', 'H', 'I'], + ], + ], + [ + 'entire row spanned from above', + [ + [ + ['A', 2, 2], + ['B', 2, 2], + ], + [], + ['C', 'D', 'E', 'F'], + ], + ], +] as [string, Spec][]) { + test(`all anchor/focus pairs give the spanned rows and the cells in grid order: ${label}`, () => { + using editor = build(shape); + editor.read(() => { + const table = $table(); + const cells = table + .getChildren() + .flatMap(r => (r as TableRowNode).getChildren()) + .filter($isTableCellNode); + const [map] = $computeTableMapSkipCellCheck(table, null, null); + const visit = (node: LexicalNode, out: Map) => { + out.set(node.getKey(), node); + if ($isElementNode(node)) + for (const child of node.getChildren()) visit(child, out); + }; + for (const anchor of cells) + for (const focus of cells) { + const selection = $createTableSelectionFrom(table, anchor, focus); + const am = map.flat().find(v => v.cell.is(anchor))!; + const fm = map.flat().find(v => v.cell.is(focus))!; + const boundary = $computeTableCellRectBoundary(map, am, fm); + // Parents and cell subtrees in grid scan order. + const expected = new Map([ + [table.getKey(), table], + ]); + // Every row up to the last one with a cell of its own in the + // selection, also one covered only by cells spanning from above. + let lastRow = boundary.minRow; + for (let r = boundary.minRow; r <= boundary.maxRow; r++) { + for (let c = boundary.minColumn; c <= boundary.maxColumn; c++) { + if (map[r][c].startRow === r) { + lastRow = r; + } + } + } + for (let r = boundary.minRow; r <= boundary.maxRow; r++) { + if (r <= lastRow) { + const rowNode = table.getChildAtIndex(r)!; + expected.set(rowNode.getKey(), rowNode); + } + for (let c = boundary.minColumn; c <= boundary.maxColumn; c++) { + const cell = map[r][c].cell; + const row = cell.getParentOrThrow(); + expected.set(row.getKey(), row); + visit(cell, expected); + } + } + expect(selection.getNodes()).toEqual([...expected.values()]); + } + }); + }); +} diff --git a/packages/lexical-table/src/__tests__/unit/RaggedTableSelectionTrailingRows.test.ts b/packages/lexical-table/src/__tests__/unit/RaggedTableSelectionTrailingRows.test.ts new file mode 100644 index 000000000000..1979cac466c1 --- /dev/null +++ b/packages/lexical-table/src/__tests__/unit/RaggedTableSelectionTrailingRows.test.ts @@ -0,0 +1,162 @@ +/** + * 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, + $insertDataTransferForRichText, +} from '@lexical/clipboard'; +import {buildEditorFromExtensions} from '@lexical/extension'; +import { + $createTableCellNode, + $createTableNode, + $createTableRowNode, + $createTableSelectionFrom, + $isTableCellNode, + $isTableNode, + TableExtension, + type TableRowNode, +} from '@lexical/table'; +import { + $createParagraphNode, + $createTextNode, + $getRoot, + $getSelection, + $setSelection, + configExtension, + defineExtension, + type LexicalEditor, +} from 'lexical'; +import {assert, expect, test} from 'vitest'; + +// A table whose rows have different numbers of cells, as collaborators' +// concurrent row and column inserts can leave it (remote updates skip the +// table transform). Cells are their text, or [text, colSpan, rowSpan]. +type Spec = (string | [string, number, number])[][]; + +function build(rows: Spec) { + const editor = buildEditorFromExtensions( + defineExtension({ + afterRegistration(ed) { + // The table selection observer, which handles the commands below, + // needs the editor to have a root element. + const root = document.createElement('div'); + document.body.append(root); + ed.setRootElement(root); + return () => root.remove(); + }, + dependencies: [configExtension(TableExtension, {hasNestedTables: true})], + name: '[ragged-table-selection-trailing-rows]', + // Lexical clipboard data pastes into an editor of the same namespace. + namespace: 'ragged-table-selection-trailing-rows', + onError: (error: Error) => { + throw error; + }, + theme: {tableScrollableWrapper: 'table-scrollable-wrapper'}, + }), + ); + editor.update( + () => { + const table = $createTableNode(); + for (const specs of rows) { + const row = $createTableRowNode(); + for (const spec of specs) { + const [text, colSpan, rowSpan] = + typeof spec === 'string' ? [spec, 1, 1] : spec; + row.append( + $createTableCellNode() + .setColSpan(colSpan) + .setRowSpan(rowSpan) + .append($createParagraphNode().append($createTextNode(text))), + ); + } + table.append(row); + } + $getRoot().clear().append(table, $createParagraphNode()); + }, + {discrete: true, skipTransforms: true}, + ); + return editor; +} + +function $table() { + const table = $getRoot().getChildren().find($isTableNode); + assert(table !== undefined, 'expected a table'); + return table; +} + +function $cell(name: string) { + const cell = $table() + .getChildren() + .flatMap(row => (row as TableRowNode).getChildren()) + .find(node => node.getTextContent() === name); + assert($isTableCellNode(cell), `expected a cell ${name}`); + return cell; +} + +function select(editor: LexicalEditor, anchor: string, focus: string) { + editor.update( + () => + $setSelection( + $createTableSelectionFrom($table(), $cell(anchor), $cell(focus)), + ), + {discrete: true}, + ); +} + +function $texts() { + return $table() + .getChildren() + .map(row => + (row as TableRowNode).getChildren().map(cell => cell.getTextContent()), + ); +} +function paste( + source: LexicalEditor, + target: LexicalEditor, + a: string, + f: string, + targetA: string, + targetF?: string, + mime = 'application/x-lexical-editor', +) { + select(source, a, f); + const copied = source.read(() => + $getClipboardDataFromSelection($getSelection()!), + ); + const data = new DataTransfer(); + data.setData(mime, copied[mime as keyof typeof copied]!); + target.update( + () => { + const selection = targetF + ? $createTableSelectionFrom($table(), $cell(targetA), $cell(targetF)) + : $cell(targetA).selectStart(); + $setSelection(selection); + $insertDataTransferForRichText(data, selection); + }, + {discrete: true}, + ); +} + +for (const mime of ['application/x-lexical-editor', 'text/html']) { + test(`a trailing hole beside a selected rowspan retains the pasted span (${mime})`, () => { + using source = build([['OUT', ['A', 1, 2], 'B'], ['OUT2']]); + using target = build([ + ['X', 'Y'], + ['OLD', 'KEEP'], + ]); + paste(source, target, 'A', 'B', 'X', undefined, mime); + expect(target.read($texts)).toEqual([['A', 'B'], ['KEEP']]); + }); +} + +test('plain-text copy and paste keeps B in its source row', () => { + using source = build([['OUT0', 'A'], ['OUT1'], ['OUT2', 'B']]); + using target = build([['X'], ['KEEP'], ['Y']]); + paste(source, target, 'A', 'B', 'X', 'Y', 'text/plain'); + expect(target.read($texts)[2]).toEqual(['B']); +}); diff --git a/packages/lexical-table/src/__tests__/unit/RectangularTableSelection.test.ts b/packages/lexical-table/src/__tests__/unit/RectangularTableSelection.test.ts new file mode 100644 index 000000000000..0a1b1154ca69 --- /dev/null +++ b/packages/lexical-table/src/__tests__/unit/RectangularTableSelection.test.ts @@ -0,0 +1,273 @@ +/** + * 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, + $insertDataTransferForRichText, +} from '@lexical/clipboard'; +import {buildEditorFromExtensions} from '@lexical/extension'; +import { + $createTableCellNode, + $createTableNode, + $createTableRowNode, + $createTableSelectionFrom, + $isTableCellNode, + $isTableNode, + TableExtension, + type TableRowNode, +} from '@lexical/table'; +import { + $createParagraphNode, + $createTextNode, + $getRoot, + $getSelection, + $setSelection, + configExtension, + defineExtension, + KEY_DELETE_COMMAND, + type LexicalEditor, +} from 'lexical'; +import {assert, expect, test} from 'vitest'; + +// A table whose rows have different numbers of cells, as collaborators' +// concurrent row and column inserts can leave it (remote updates skip the +// table transform). Cells are their text, or [text, colSpan, rowSpan]. +type Spec = (string | [string, number, number])[][]; + +function build(rows: Spec) { + const editor = buildEditorFromExtensions( + defineExtension({ + afterRegistration(ed) { + // The table selection observer, which handles the commands below, + // needs the editor to have a root element. + const root = document.createElement('div'); + document.body.append(root); + ed.setRootElement(root); + return () => root.remove(); + }, + dependencies: [configExtension(TableExtension, {hasNestedTables: true})], + name: '[rectangular-table-selection]', + // Lexical clipboard data pastes into an editor of the same namespace. + namespace: 'rectangular-table-selection', + onError: (error: Error) => { + throw error; + }, + theme: {tableScrollableWrapper: 'table-scrollable-wrapper'}, + }), + ); + editor.update( + () => { + const table = $createTableNode(); + for (const specs of rows) { + const row = $createTableRowNode(); + for (const spec of specs) { + const [text, colSpan, rowSpan] = + typeof spec === 'string' ? [spec, 1, 1] : spec; + row.append( + $createTableCellNode() + .setColSpan(colSpan) + .setRowSpan(rowSpan) + .append($createParagraphNode().append($createTextNode(text))), + ); + } + table.append(row); + } + $getRoot().clear().append(table, $createParagraphNode()); + }, + {discrete: true, skipTransforms: true}, + ); + return editor; +} + +function $table() { + const table = $getRoot().getChildren().find($isTableNode); + assert(table !== undefined, 'expected a table'); + return table; +} + +function $cell(name: string) { + const cell = $table() + .getChildren() + .flatMap(row => (row as TableRowNode).getChildren()) + .find(node => node.getTextContent() === name); + assert($isTableCellNode(cell), `expected a cell ${name}`); + return cell; +} + +function select(editor: LexicalEditor, anchor: string, focus: string) { + editor.update( + () => + $setSelection( + $createTableSelectionFrom($table(), $cell(anchor), $cell(focus)), + ), + {discrete: true}, + ); +} + +function $texts() { + return $table() + .getChildren() + .map(row => + (row as TableRowNode).getChildren().map(cell => cell.getTextContent()), + ); +} +function paste( + source: LexicalEditor, + target: LexicalEditor, + a: string, + f: string, + targetA: string, + targetF?: string, + mime = 'application/x-lexical-editor', +) { + select(source, a, f); + const copied = source.read(() => + $getClipboardDataFromSelection($getSelection()!), + ); + const data = new DataTransfer(); + data.setData(mime, copied[mime as keyof typeof copied]!); + target.update( + () => { + const selection = targetF + ? $createTableSelectionFrom($table(), $cell(targetA), $cell(targetF)) + : $cell(targetA).selectStart(); + $setSelection(selection); + $insertDataTransferForRichText(data, selection); + }, + {discrete: true}, + ); +} + +// Tables without holes: copying, deleting and pasting every selection gives +// exactly what it gave before the ragged-table changes, except where main +// dropped a copied cell (checked separately below). EXPECTED is the +// fingerprint of those outputs on main before the changes, apart from that +// row-span table. +function fingerprint(text: string): string { + // FNV-1a, 32 bit + let hash = 0x811c9dc5; + for (let i = 0; i < text.length; i++) { + hash ^= text.charCodeAt(i); + hash = Math.imul(hash, 0x01000193) >>> 0; + } + return hash.toString(16); +} + +const RECTANGULAR: [string, Spec][] = [ + [ + 'plain', + [ + ['A', 'B', 'C'], + ['D', 'E', 'F'], + ['G', 'H', 'I'], + ], + ], + [ + 'column span', + [ + [['A', 2, 1], 'C'], + ['D', 'E', 'F'], + ['G', 'H', 'I'], + ], + ], + [ + 'row span', + [ + [['A', 1, 2], 'B', 'C'], + ['E', 'F'], + ['G', 'H', 'I'], + ], + ], +]; + +const EXPECTED: Record = { + 'column span': '447f760f', + plain: 'b62cb6f7', + // Main: 'b47ff14b'. It differs only in the copy and paste of A with G (both + // directions), checked below. + 'row span': '33c3a3eb', +}; + +for (const [label, rows] of RECTANGULAR) { + test(`copy, delete and paste of every selection are unchanged: ${label}`, () => { + const names = rows + .flat() + .map(spec => (typeof spec === 'string' ? spec : spec[0])); + const outputs: string[] = []; + for (const anchor of names) { + for (const focus of names) { + using source = build(rows); + select(source, anchor, focus); + const copied = source.read(() => + $getClipboardDataFromSelection($getSelection()!), + ); + outputs.push(JSON.stringify(copied)); + for (const mime of ['application/x-lexical-editor', 'text/html']) { + using target = build([ + ['T0', 'T1', 'T2'], + ['T3', 'T4', 'T5'], + ['T6', 'T7', 'T8'], + ]); + paste(source, target, anchor, focus, 'T0', undefined, mime); + outputs.push(JSON.stringify(target.getEditorState().toJSON())); + } + source.update( + () => + source.dispatchCommand( + KEY_DELETE_COMMAND, + new KeyboardEvent('keydown'), + ), + {discrete: true}, + ); + outputs.push(JSON.stringify(source.getEditorState().toJSON())); + } + } + const print = fingerprint(outputs.join('\n')); + expect(print).toBe(EXPECTED[label]); + }); +} + +// The row-span table: the row under A is covered within a selection from A +// to G only by A's row span. Main left it out of the copy, so the paste +// dropped G; the copy now keeps it. A copied alone still pastes into one +// cell. +const ROW_SPAN: Spec = [ + [['A', 1, 2], 'B', 'C'], + ['E', 'F'], + ['G', 'H', 'I'], +]; +const TARGET: Spec = [ + ['T0', 'T1', 'T2'], + ['T3', 'T4', 'T5'], + ['T6', 'T7', 'T8'], +]; + +for (const mime of ['application/x-lexical-editor', 'text/html']) { + test(`pasting a copy of A and G puts G in its row (${mime})`, () => { + using source = build(ROW_SPAN); + using target = build(TARGET); + paste(source, target, 'A', 'G', 'T0', undefined, mime); + // Main dropped G: [['A', 'T1', 'T2'], ['T4', 'T5'], ['T6', 'T7', 'T8']]. + expect(target.read($texts)).toEqual([ + ['A', 'T1', 'T2'], + ['T4', 'T5'], + ['G', 'T7', 'T8'], + ]); + }); + + test(`pasting a copy of A alone pastes it into one cell, as before (${mime})`, () => { + using source = build(ROW_SPAN); + using target = build(TARGET); + paste(source, target, 'A', 'A', 'T0', undefined, mime); + expect(target.read($texts)).toEqual([ + ['A', 'T1', 'T2'], + ['T3', 'T4', 'T5'], + ['T6', 'T7', 'T8'], + ]); + }); +} diff --git a/packages/lexical-table/src/__tests__/unit/TableSelectionCoveredRows.test.ts b/packages/lexical-table/src/__tests__/unit/TableSelectionCoveredRows.test.ts new file mode 100644 index 000000000000..85b957e5286a --- /dev/null +++ b/packages/lexical-table/src/__tests__/unit/TableSelectionCoveredRows.test.ts @@ -0,0 +1,541 @@ +/** + * 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 { + $generateNodesFromSerializedNodes, + $getClipboardDataFromSelection, + $insertDataTransferForRichText, +} from '@lexical/clipboard'; +import {buildEditorFromExtensions} from '@lexical/extension'; +import { + $computeTableMapSkipCellCheck, + $createTableCellNode, + $createTableNode, + $createTableRowNode, + $createTableSelectionFrom, + $isTableCellNode, + $isTableNode, + $isTableRowNode, + getTableObserverFromTableElement, + TableExtension, + type TableRowNode, +} from '@lexical/table'; +import { + $createParagraphNode, + $createTextNode, + $getRoot, + $getSelection, + $setSelection, + configExtension, + CUT_COMMAND, + defineExtension, + type ElementNode, + FORMAT_ELEMENT_COMMAND, + type LexicalEditor, +} from 'lexical'; +import {assert, expect, test} from 'vitest'; + +import { + $computeTableCellRectBoundary, + $insertTableIntoGrid, +} from '../../LexicalTableUtils'; + +// A table whose rows have different numbers of cells, as collaborators' +// concurrent row and column inserts can leave it (remote updates skip the +// table transform). Cells are their text, or [text, colSpan, rowSpan]. +type Spec = (string | [string, number, number])[][]; + +function build(rows: Spec) { + const editor = buildEditorFromExtensions( + defineExtension({ + afterRegistration(ed) { + // The table selection observer, which handles the commands below, + // needs the editor to have a root element. + const root = document.createElement('div'); + document.body.append(root); + ed.setRootElement(root); + return () => root.remove(); + }, + dependencies: [configExtension(TableExtension, {hasNestedTables: true})], + name: '[table-selection-covered-rows]', + // Lexical clipboard data pastes into an editor of the same namespace. + namespace: 'table-selection-covered-rows', + onError: (error: Error) => { + throw error; + }, + theme: { + tableCellSelected: 'selected', + tableScrollableWrapper: 'table-scrollable-wrapper', + }, + }), + ); + editor.update( + () => { + const table = $createTableNode(); + for (const specs of rows) { + const row = $createTableRowNode(); + for (const spec of specs) { + const [text, colSpan, rowSpan] = + typeof spec === 'string' ? [spec, 1, 1] : spec; + row.append( + $createTableCellNode() + .setColSpan(colSpan) + .setRowSpan(rowSpan) + .append($createParagraphNode().append($createTextNode(text))), + ); + } + table.append(row); + } + $getRoot().clear().append(table, $createParagraphNode()); + }, + {discrete: true, skipTransforms: true}, + ); + return editor; +} + +function $table() { + const table = $getRoot().getChildren().find($isTableNode); + assert(table !== undefined, 'expected a table'); + return table; +} + +function $cell(name: string) { + const cell = $table() + .getChildren() + .flatMap(row => (row as TableRowNode).getChildren()) + .find(node => node.getTextContent() === name); + assert($isTableCellNode(cell), `expected a cell ${name}`); + return cell; +} + +function select(editor: LexicalEditor, anchor: string, focus: string) { + editor.update( + () => + $setSelection( + $createTableSelectionFrom($table(), $cell(anchor), $cell(focus)), + ), + {discrete: true}, + ); +} + +function paste( + source: LexicalEditor, + target: LexicalEditor, + a: string, + f: string, + targetA: string, + targetF?: string, + mime = 'application/x-lexical-editor', +) { + select(source, a, f); + const copied = source.read(() => + $getClipboardDataFromSelection($getSelection()!), + ); + const data = new DataTransfer(); + data.setData(mime, copied[mime as keyof typeof copied]!); + target.update( + () => { + const selection = targetF + ? $createTableSelectionFrom($table(), $cell(targetA), $cell(targetF)) + : $cell(targetA).selectStart(); + $setSelection(selection); + $insertDataTransferForRichText(data, selection); + }, + {discrete: true}, + ); +} + +const $texts = () => + $table() + .getChildren() + .map(row => + (row as TableRowNode).getChildren().map(cell => cell.getTextContent()), + ); + +const COVERED: Spec = [ + [ + ['A', 1, 2], + ['B', 1, 2], + ], + [], + ['E', 'F'], +]; + +for (const mime of ['application/x-lexical-editor', 'text/html']) { + for (const [label, spec, anchor, focus, rowCounts] of [ + ['middle row', COVERED, 'A', 'F', [2, 0, 2]], + [ + 'partial column with unselected physical cells', + [['KEEP0', ['B', 1, 3]], ['KEEP1'], ['KEEP2'], ['KEEP3', 'F']], + 'B', + 'F', + [1, 0, 0, 1], + ], + ] as [string, Spec, string, string, number[]][]) { + test(`${label} survives standalone copy and paste (${mime})`, () => { + using source = build(spec); + using target = build([['DISCARD']]); + select(source, anchor, focus); + const copied = source.read(() => + $getClipboardDataFromSelection($getSelection()!), + ); + const counts = + mime === 'application/x-lexical-editor' + ? JSON.parse(copied[mime]!).nodes[0].children.map( + (r: {children: unknown[]}) => r.children.length, + ) + : [ + ...new DOMParser() + .parseFromString(copied[mime]!, 'text/html') + .querySelectorAll('tr'), + ].map(r => r.querySelectorAll('td,th').length); + expect(counts).toEqual(rowCounts); + target.update( + () => { + $getRoot().clear().append($createParagraphNode()); + const selection = ( + $getRoot().getFirstChildOrThrow() as ElementNode + ).selectStart(); + const data = new DataTransfer(); + data.setData(mime, copied[mime as keyof typeof copied]!); + $insertDataTransferForRichText(data, selection); + }, + {discrete: true}, + ); + target.read(() => { + expect( + $table() + .getChildren() + .map(r => (r as TableRowNode).getChildrenSize()), + ).toEqual(rowCounts); + expect( + $table() + .getAllTextNodes() + .map(t => t.getTextContent()), + ).toEqual( + source.read(() => + $getSelection()! + .getNodes() + .filter($isTableCellNode) + .flatMap(c => c.getAllTextNodes().map(t => t.getTextContent())), + ), + ); + }); + }); + } + + test(`cut whole covered-row rectangle and paste into a growing target (${mime})`, () => { + using source = build(COVERED); + using target = build([['KEEP', 'START']]); + select(source, 'A', 'F'); + const data = new DataTransfer(); + source.update( + () => + source.dispatchCommand( + CUT_COMMAND, + new ClipboardEvent('cut', {clipboardData: data}), + ), + {discrete: true}, + ); + expect(source.read(() => $getRoot().getChildren().some($isTableNode))).toBe( + false, + ); + target.update( + () => { + const only = new DataTransfer(); + only.setData(mime, data.getData(mime)); + $insertDataTransferForRichText(only, $cell('START').selectStart()); + }, + {discrete: true}, + ); + expect(target.read($texts)).toEqual([ + ['KEEP', 'A', 'B'], + [''], + ['', 'E', 'F'], + ]); + }); +} + +test('covered rows do not add cells to highlight, text, alignment or clearText', () => { + using editor = build([ + ['KEEP0', ['B', 1, 3]], + ['KEEP1'], + ['KEEP2'], + ['KEEP3', 'F'], + ]); + select(editor, 'F', 'B'); + editor.read(() => { + const selection = $getSelection()!; + expect(selection.getTextContent()).toBe('B\n\n\nF\n'); + expect(selection.getNodes().filter($isTableRowNode)).toEqual( + $table().getChildren(), + ); + expect(new Set(selection.getNodes().map(n => n.getKey())).size).toBe( + selection.getNodes().length, + ); + }); + expect( + [...editor.getRootElement()!.querySelectorAll('td.selected')].map( + c => c.textContent, + ), + ).toEqual(['B', 'F']); + editor.update(() => editor.dispatchCommand(FORMAT_ELEMENT_COMMAND, 'right'), { + discrete: true, + }); + editor.read(() => { + expect($cell('B').getFormatType()).toBe('right'); + expect($cell('F').getFormatType()).toBe('right'); + for (const name of ['KEEP0', 'KEEP1', 'KEEP2', 'KEEP3']) { + expect($cell(name).getFormatType()).toBe(''); + } + }); + editor.update( + () => { + const element = editor.getRootElement()!.querySelector('table')!; + const observer = getTableObserverFromTableElement(element); + assert(observer); + observer.$clearText(); + }, + {discrete: true}, + ); + expect(editor.read($texts)).toEqual([ + ['KEEP0', ''], + ['KEEP1'], + ['KEEP2'], + ['KEEP3', ''], + ]); +}); + +for (const reversed of [false, true]) { + test(`insertNodes uses focus despite a trailing covered row (reversed=${reversed})`, () => { + using editor = build(COVERED); + select(editor, reversed ? 'F' : 'A', reversed ? 'A' : 'F'); + editor.update( + () => + $getSelection()!.insertNodes([ + $createParagraphNode().append($createTextNode('NEW')), + ]), + {discrete: true}, + ); + expect(editor.read($texts)).toEqual( + reversed + ? [['NEW', 'B'], [], ['E', 'F']] + : [['A', 'B'], [], ['E', 'NEW']], + ); + }); +} + +test('insertTableIntoGrid with a physically empty template row preserves its target', () => { + using template = build([['X', 'Y'], [], ['Z', 'W']]); + using target = build([['A', 'B'], ['KEEP0', ['KEEP1', 1, 2]], ['C']]); + const json = template.getEditorState().toJSON().root.children[0]; + target.update( + () => { + const [node] = $generateNodesFromSerializedNodes([json]); + assert($isTableNode(node)); + expect($insertTableIntoGrid(node, $cell('A').selectStart())).toBe(true); + }, + {discrete: true}, + ); + expect(target.read($texts)).toEqual([ + ['X', 'Y'], + ['KEEP0', 'KEEP1'], + ['Z', 'W'], + ]); +}); + +// Fill a rectangular grid with valid, nonoverlapping merges. Some physical +// rows have no cells, although every grid position is covered. +function rectangle(seed: number): Spec { + let state = seed + 1; + const random = (n: number) => { + state = (Math.imul(state, 1664525) + 1013904223) >>> 0; + return state % n; + }; + const height = 5; + const width = 5; + const used = Array.from({length: height}, () => Array(width).fill(false)); + const rows: Spec = []; + for (let r = 0; r < height; r++) { + const cells: Spec[number] = []; + for (let c = 0; c < width; c++) { + if (used[r][c]) continue; + let cs = Math.min(1 + random(4), width - c); + let rs = Math.min(1 + random(4), height - r); + const free = () => { + for (let y = r; y < r + rs; y++) + for (let x = c; x < c + cs; x++) if (used[y][x]) return false; + return true; + }; + while (!free()) { + if (cs > 1) cs--; + else rs--; + } + cells.push([`S${seed}R${r}C${c}`, cs, rs]); + for (let y = r; y < r + rs; y++) + for (let x = c; x < c + cs; x++) used[y][x] = true; + } + rows.push(cells); + } + return rows; +} + +for (const mime of ['application/x-lexical-editor', 'text/html']) { + test(`generated rectangular merged selections keep coordinates when pasted or grown (${mime})`, () => { + let covered = 0; + for (let seed = 0; seed < 80; seed++) { + const spec = rectangle(seed); + const names = spec.flat().map(s => (typeof s === 'string' ? s : s[0])); + using source = build(spec); + for (let pair = 0; pair < 3; pair++) { + const a = names[(seed + pair) % names.length]; + const f = names[(names.length - 1 + pair * 3) % names.length]; + select(source, a, f); + const expected = source.read(() => { + const [map, am, fm] = $computeTableMapSkipCellCheck( + $table(), + $cell(a), + $cell(f), + ); + assert(am && fm); + const b = $computeTableCellRectBoundary(map, am, fm); + // Trailing rows covered only by row spans stay out of a copy, as + // before: the copy ends at the last row with a cell of its own. + let lastRow = b.minRow; + for (let r = b.minRow; r <= b.maxRow; r++) { + for (let c = b.minColumn; c <= b.maxColumn; c++) { + if (map[r][c].startRow === r) { + lastRow = r; + } + } + } + const grid: string[][] = []; + for (let r = b.minRow; r <= lastRow; r++) { + grid.push( + Array.from({length: b.maxColumn - b.minColumn + 1}, (_, c) => + map[r][c + b.minColumn].cell.getTextContent(), + ), + ); + if (!spec[r].length) covered++; + } + return grid; + }); + using target = build( + pair === 0 + ? [['KEEP0', 'START']] + : Array.from({length: 7}, (_, r) => + Array.from({length: 7}, (_column, c) => `KEEP${r}:${c}`), + ), + ); + paste( + source, + target, + a, + f, + pair === 0 ? 'START' : 'KEEP1:1', + undefined, + mime, + ); + target.read(() => { + const [map] = $computeTableMapSkipCellCheck($table(), null, null); + const startRow = pair === 0 ? 0 : 1; + for (let r = 0; r < map.length; r++) + for (let c = 0; c < map[r].length; c++) { + const wanted = + expected[r - startRow]?.[c - 1] ?? + (pair === 0 + ? r === 0 && c === 0 + ? 'KEEP0' + : '' + : `KEEP${r}:${c}`); + expect( + map[r][c].cell.getTextContent(), + JSON.stringify({a, c, f, pair, r, seed, spec}), + ).toBe(wanted); + } + expect(map.length).toBe(pair === 0 ? expected.length : 7); + expect(map[0].length).toBe(pair === 0 ? expected[0].length + 1 : 7); + }); + } + } + expect(covered).toBeGreaterThan(0); + }, 30000); +} + +for (const mime of ['application/x-lexical-editor', 'text/html']) { + test(`covered row height and direction survive selected DOM/JSON export (${mime})`, () => { + using editor = build(COVERED); + editor.update( + () => { + const row = $table().getChildAtIndex(1) as TableRowNode; + row.setHeight(47); + row.setDirection('rtl'); + }, + {discrete: true}, + ); + select(editor, 'A', 'F'); + editor.read(() => { + const data = $getClipboardDataFromSelection($getSelection()!); + if (mime === 'application/x-lexical-editor') { + const rows = JSON.parse(data[mime]!).nodes[0].children; + expect(rows).toHaveLength(3); + expect(rows[1]).toMatchObject({ + children: [], + direction: 'rtl', + height: 47, + }); + } else { + const rows = new DOMParser() + .parseFromString(data[mime]!, 'text/html') + .querySelectorAll('tr'); + expect(rows).toHaveLength(3); + expect(rows[1].style.height).toBe('47px'); + expect(rows[1].dir).toBe('rtl'); + expect(rows[1].children).toHaveLength(0); + } + }); + }); +} + +for (const mime of ['application/x-lexical-editor', 'text/html']) { + for (const tableSelection of [false, true]) { + test(`covered-row rectangle replaces a merged target without touching its neighbors (${mime}, tableSelection=${tableSelection})`, () => { + using source = build(COVERED); + using target = build([ + ['K00', 'K01', 'K02', 'K03'], + ['K10', ['OLD', 2, 3], 'K13'], + ['K20', 'K23'], + ['K30', 'K33'], + ['K40', 'K41', 'K42', 'K43'], + ]); + paste( + source, + target, + 'A', + 'F', + 'OLD', + tableSelection ? 'OLD' : undefined, + mime, + ); + expect(target.read($texts)).toEqual([ + ['K00', 'K01', 'K02', 'K03'], + ['K10', 'A', 'B', 'K13'], + ['K20', 'K23'], + ['K30', 'E', 'F', 'K33'], + ['K40', 'K41', 'K42', 'K43'], + ]); + target.read(() => + expect( + $getSelection()! + .getNodes() + .every(node => node.isAttached()), + ).toBe(true), + ); + }); + } +} diff --git a/packages/lexical-y/src/__tests__/unit/regressions/RaggedTableSelection.test.ts b/packages/lexical-y/src/__tests__/unit/regressions/RaggedTableSelection.test.ts new file mode 100644 index 000000000000..b78589bd8abe --- /dev/null +++ b/packages/lexical-y/src/__tests__/unit/regressions/RaggedTableSelection.test.ts @@ -0,0 +1,180 @@ +/** + * 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. + * + */ +// @vitest-environment node + +import { + $createTableNodeWithDimensions, + $createTableSelection, + $insertTableColumnAtSelection, + $insertTableRowAtSelection, + $isTableNode, +} from '@lexical/table'; +import * as Y from '@y/y'; +import { + $createParagraphNode, + $getRoot, + $getSelection, + $setSelection, + createEditor, + type ElementNode, +} from 'lexical'; +import {expect, test} from 'vitest'; + +import {createYDoc, YBinding} from '../../..'; +import {NODES} from '../../utils/harness'; + +const GC = process.env.LEXICAL_Y_GC === '1'; + +type P = { + doc: Y.Doc; + editor: ReturnType; + binding: YBinding; +}; + +function peer(id: number, state?: Uint8Array): P { + const doc = createYDoc(null, {gc: GC}); + doc.clientID = id; + if (state !== undefined) { + Y.applyUpdate(doc, state, 'load'); + } + const editor = createEditor({ + namespace: 'ragged-table-selection', + nodes: NODES, + onError: e => { + throw e; + }, + }); + const binding = new YBinding(editor, doc, { + schemaVersion: 1, + selfCheck: true, + }); + binding.start(); + return {binding, doc, editor}; +} + +const update = (p: P, fn: () => void) => { + p.binding.undoManager?.stopCapturing(); + p.editor.update(fn, {discrete: true}); +}; + +function exchange(peers: P[]): void { + for (let round = 0; round < 3; round++) { + for (const a of peers) { + for (const b of peers) { + if (a !== b) { + Y.applyUpdate( + b.doc, + Y.encodeStateAsUpdate(a.doc, Y.encodeStateVector(b.doc)), + 'net', + ); + } + } + } + } +} + +const $table = () => $getRoot().getChildren().find($isTableNode) as ElementNode; +const $cell = (r: number, c: number) => + ($table().getChildAtIndex(r) as ElementNode).getChildAtIndex( + c, + ) as ElementNode; +const shape = (p: P) => + p.editor.getEditorState().read(() => + $table() + .getChildren() + .map(r => (r as ElementNode).getChildrenSize()), + ); + +function selectAll(p: P): {tried: number; crashes: string[]} { + const cells: [number, number][] = []; + p.editor.getEditorState().read(() => { + $table() + .getChildren() + .forEach((r, i) => { + for (let j = 0; j < (r as ElementNode).getChildrenSize(); j++) + cells.push([i, j]); + }); + }); + const crashes: string[] = []; + let tried = 0; + for (const a of cells) { + for (const f of cells) { + tried++; + try { + p.editor.update( + () => { + const sel = $createTableSelection(); + sel.set( + $table().getKey(), + $cell(a[0], a[1]).getKey(), + $cell(f[0], f[1]).getKey(), + ); + $setSelection(sel); + $getSelection()!.getNodes(); + }, + {discrete: true}, + ); + } catch (e) { + crashes.push( + `${JSON.stringify(a)}->${JSON.stringify(f)}: ${String(e).slice(0, 120)}`, + ); + } + } + } + return {crashes, tried}; +} + +test('a table selection in a table made ragged by concurrent row and column inserts holds its cells', () => { + const a = peer(1); + update(a, () => { + $getRoot().append( + $createTableNodeWithDimensions(2, 2, false), + $createParagraphNode(), + ); + }); + a.binding.initialize(); + const s = Y.encodeStateAsUpdate(a.doc); + const [b, c, d] = [2, 3, 4].map(id => { + const p = peer(id, s); + p.binding.initialize(); + return p; + }); + // Offline from the same state: one peer inserts a column, one a row, one + // another column. + update(b, () => { + ($cell(0, 0).getFirstChild() as ElementNode).selectEnd(); + $insertTableColumnAtSelection(true); + }); + update(d, () => { + ($cell(0, 0).getFirstChild() as ElementNode).selectEnd(); + $insertTableRowAtSelection(true); + }); + update(c, () => { + ($cell(1, 1).getFirstChild() as ElementNode).selectEnd(); + $insertTableColumnAtSelection(true); + }); + exchange([a, b, c, d]); + const f = peer(99, Y.encodeStateAsUpdate(a.doc)); + f.binding.initialize(); + const shapes = [a, b, c, d, f].map(shape); + // Every peer has the same table, ragged: the table transform leaves the + // rows that the merged updates changed to their authors. + expect(shapes[0].some(n => n !== shapes[0][0])).toBe(true); + let all: string[] = []; + let tried = 0; + for (const p of [a, b, c, d, f]) { + const r = selectAll(p); + all = all.concat(r.crashes); + tried += r.tried; + } + expect(tried).toBeGreaterThan(0); + expect( + shapes.every(x => JSON.stringify(x) === JSON.stringify(shapes[0])), + ).toBe(true); + expect(all).toEqual([]); +}); diff --git a/packages/lexical-y/src/__tests__/unit/regressions/RaggedTableSelectionCommit.test.ts b/packages/lexical-y/src/__tests__/unit/regressions/RaggedTableSelectionCommit.test.ts new file mode 100644 index 000000000000..fdc00c20605c --- /dev/null +++ b/packages/lexical-y/src/__tests__/unit/regressions/RaggedTableSelectionCommit.test.ts @@ -0,0 +1,143 @@ +/** + * 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. + * + */ + +// A table selection across a short row of a ragged table, with TableExtension +// registered before the binding: the table's update listener reads the +// selection's nodes on every commit. When that threw, Lexical stopped calling +// the later listeners, so the binding never stored the commit (a comment the +// editor showed and the document did not). + +import { + buildEditorFromExtensions, + getExtensionDependencyFromEditor, +} from '@lexical/extension'; +import {$addMarkID, MarkStateExtension} from '@lexical/mark'; +import {RichTextExtension} from '@lexical/rich-text'; +import { + $createTableCellNode, + $createTableNode, + $createTableRowNode, + $createTableSelectionFrom, + $isTableNode, + type TableCellNode, + TableExtension, + type TableNode, +} from '@lexical/table'; +import * as Y from '@y/y'; +import { + $createParagraphNode, + $createRangeSelection, + $createTextNode, + $getEditor, + $getRoot, + $setSelection, + configExtension, + defineExtension, + type ElementNode, + type TextNode, +} from 'lexical'; +import {expect, test} from 'vitest'; + +import {createYDoc, YCollabExtension} from '../../..'; +import {readYState} from '../../../headless'; +import {flush} from '../../utils/harness'; + +test('a commit while a table selection spans a short row is stored', async () => { + const doc = createYDoc(null); + doc.clientID = 31; + const errors: unknown[] = []; + const editor = buildEditorFromExtensions( + defineExtension({ + dependencies: [ + RichTextExtension, + TableExtension, + MarkStateExtension, + configExtension(YCollabExtension, {doc, schemaVersion: 1}), + ], + name: 'ragged-table-selection-commit', + onError: (e: Error) => { + errors.push(e); + }, + }), + ); + const root = document.createElement('div'); + root.contentEditable = 'true'; + document.body.appendChild(root); + editor.setRootElement(root); + const $cell = (text: string) => + $createTableCellNode().append( + $createParagraphNode().append($createTextNode(text)), + ); + editor.update( + () => { + $getRoot() + .clear() + .append( + $createTableNode().append( + $createTableRowNode().append($cell('a1'), $cell('b1'), $cell('c1')), + $createTableRowNode().append($cell('a2'), $cell('b2')), + $createTableRowNode().append($cell('a3'), $cell('b3'), $cell('c3')), + ), + $createParagraphNode().append($createTextNode('alpha beta')), + ); + }, + // As a remote update leaves it: the table transform does not pad it. + {discrete: true, skipTransforms: true}, + ); + getExtensionDependencyFromEditor( + editor, + YCollabExtension, + ).output.binding.initialize(); + await flush(); + editor.update( + () => { + const table = $getRoot().getChildren().find($isTableNode) as TableNode; + const rows = table.getChildren() as ElementNode[]; + $setSelection( + $createTableSelectionFrom( + table, + rows[0].getFirstChildOrThrow() as TableCellNode, + rows[2].getLastChildOrThrow() as TableCellNode, + ), + ); + }, + {discrete: true}, + ); + await flush(); + let thrown: unknown = null; + try { + editor.update( + () => { + // The table selection stays the editor's selection. + const paragraph = $getRoot().getLastChildOrThrow() as ElementNode; + const text = paragraph.getFirstChildOrThrow() as TextNode; + const range = $createRangeSelection(); + range.anchor.set(text.getKey(), 0, 'text'); + range.focus.set(text.getKey(), 5, 'text'); + $addMarkID('c7', range); + }, + {discrete: true}, + ); + } catch (e) { + thrown = e; + } + await flush(); + const mine = JSON.stringify(editor.getEditorState().toJSON()); + const fresh = JSON.stringify( + readYState( + Y.encodeStateAsUpdate(doc), + {extensions: [MarkStateExtension, TableExtension], schemaVersion: 1}, + () => $getEditor().getEditorState().toJSON(), + ), + ); + expect(thrown).toBe(null); + expect(mine.includes('"c7"')).toBe(true); + expect(fresh.includes('"c7"')).toBe(true); + editor.dispose(); + root.remove(); +});