diff --git a/packages/core/src/api/blockManipulation/tables/tables.test.ts b/packages/core/src/api/blockManipulation/tables/tables.test.ts index 7e72e349a9..520a65327d 100644 --- a/packages/core/src/api/blockManipulation/tables/tables.test.ts +++ b/packages/core/src/api/blockManipulation/tables/tables.test.ts @@ -6,6 +6,7 @@ import { getCellsAtRowHandle, getRelativeTableCells, getAbsoluteTableCells, + getRelativeToAbsoluteTableCellMapping, moveColumn, moveRow, cropEmptyRowsOrColumns, @@ -1024,6 +1025,58 @@ describe("Test getAbsoluteTableCellIndices", () => { }); }); +describe("getRelativeToAbsoluteTableCellMapping", () => { + it.each([ + { + name: "simple table", + table: simpleTable, + expected: [ + [{ row: 0, col: 0 }, { row: 0, col: 1 }], + [{ row: 1, col: 0 }, { row: 1, col: 1 }], + ], + }, + { + name: "colspan", + table: tableWithColspan, + expected: [ + [{ row: 0, col: 0 }, { row: 0, col: 2 }], + [{ row: 1, col: 0 }, { row: 1, col: 1 }, { row: 1, col: 2 }], + ], + }, + { + name: "complex rowspans and colspans", + table: tableWithComplexRowspansAndColspans, + expected: [ + [{ row: 0, col: 0 }, { row: 0, col: 2 }, { row: 0, col: 3 }], + [{ row: 1, col: 2 }, { row: 1, col: 3 }], + [{ row: 2, col: 0 }, { row: 2, col: 1 }, { row: 2, col: 3 }], + ], + }, + ])("maps every cell in $name to its top-left position", ({ table, expected }) => { + const getAbsolute = getRelativeToAbsoluteTableCellMapping(table); + expect(expected).toHaveLength(table.content.rows.length); + table.content.rows.forEach(({ cells }, row) => { + expect(expected[row]).toHaveLength(cells.length); + cells.forEach((_, col) => { + expect(getAbsolute({ row, col })).toEqual(expected[row][col]); + }); + }); + }); + + it("throws for missing relative cell indices", () => { + const getAbsolute = getRelativeToAbsoluteTableCellMapping(simpleTable); + for (const { row, col } of [ + { row: 2, col: 0 }, + { row: 0, col: 2 }, + { row: -1, col: 0 }, + ]) { + expect(() => getAbsolute({ row, col })).toThrow( + `Unable to resolve relative table cell indices for table, cell at ${row},${col} is not occupied`, + ); + } + }); +}); + describe("Test getRelativeTableCellIndices", () => { it("should resolve absolute table cell indices to relative table cell indices", () => { expect(getRelativeTableCells({ row: 0, col: 0 }, simpleTable)).toEqual({ diff --git a/packages/core/src/api/blockManipulation/tables/tables.ts b/packages/core/src/api/blockManipulation/tables/tables.ts index 6e19d6f45e..d55d35f80c 100644 --- a/packages/core/src/api/blockManipulation/tables/tables.ts +++ b/packages/core/src/api/blockManipulation/tables/tables.ts @@ -321,6 +321,38 @@ export function getAbsoluteTableCells( ); } +/** + * Builds a lookup from relative cell indices to their top-left absolute position. + * Reuse the returned function for constant-time lookups within the same table. + */ +export function getRelativeToAbsoluteTableCellMapping( + block: BlockFromConfigNoChildren, +): (indices: RelativeCellIndices) => AbsoluteCellIndices { + const occupancyGrid = getTableCellOccupancyGrid(block); + const absoluteIndices: (AbsoluteCellIndices | undefined)[][] = []; + for (let row = 0; row < occupancyGrid.length; row++) { + const gridRow = occupancyGrid[row]; + for (let col = 0; col < gridRow.length; col++) { + const occupant = gridRow[col]; + if (!occupant) { + continue; + } + const rowIndices = (absoluteIndices[occupant.row] ??= []); + rowIndices[occupant.col] ??= { row, col }; + } + } + + return ({ row, col }) => { + const absolute = absoluteIndices[row]?.[col]; + if (absolute === undefined) { + throw new Error( + `Unable to resolve relative table cell indices for table, cell at ${row},${col} is not occupied`, + ); + } + return absolute; + }; +} + /** * This will get the dimensions of the table block. * @@ -430,9 +462,8 @@ export function getRelativeTableCells( export function getCellsAtRowHandle( block: BlockFromConfigNoChildren, relativeRowIndex: RelativeCellIndices["row"], + occupancyGrid: OccupancyGrid = getTableCellOccupancyGrid(block), ) { - const occupancyGrid = getTableCellOccupancyGrid(block); - if (relativeRowIndex < 0 || relativeRowIndex >= occupancyGrid.length) { return []; } @@ -468,10 +499,14 @@ export function getCellsAtRowHandle( ); // Filter out duplicates based on row and col properties - return cells.filter((cell, index) => { - return ( - cells.findIndex((c) => c.row === cell.row && c.col === cell.col) === index - ); + const seen = new Set(); + return cells.filter(({ row, col }) => { + const key = `${row},${col}`; + if (seen.has(key)) { + return false; + } + seen.add(key); + return true; }); } @@ -509,9 +544,8 @@ export function getCellsAtRowHandle( export function getCellsAtColumnHandle( block: BlockFromConfigNoChildren, relativeColumnIndex: RelativeCellIndices["col"], + occupancyGrid: OccupancyGrid = getTableCellOccupancyGrid(block), ) { - const occupancyGrid = getTableCellOccupancyGrid(block); - if ( relativeColumnIndex < 0 || relativeColumnIndex >= occupancyGrid[0].length @@ -550,10 +584,14 @@ export function getCellsAtColumnHandle( ); // Filter out duplicates based on row and col properties - return cells.filter((cell, index) => { - return ( - cells.findIndex((c) => c.row === cell.row && c.col === cell.col) === index - ); + const seen = new Set(); + return cells.filter(({ row, col }) => { + const key = `${row},${col}`; + if (seen.has(key)) { + return false; + } + seen.add(key); + return true; }); } @@ -803,10 +841,11 @@ export function canRowBeDraggedInto( block: BlockFromConfigNoChildren, draggingIndex: RelativeCellIndices["row"], targetRowIndex: RelativeCellIndices["row"], + targetCells: ReturnType = getCellsAtRowHandle( + block, + targetRowIndex, + ), ) { - // Check cells at the target row - const targetCells = getCellsAtRowHandle(block, targetRowIndex); - // If no cells have rowspans > 1, dragging is always allowed const hasMergedCells = targetCells.some((cell) => getRowspan(cell.cell) > 1); if (!hasMergedCells) { @@ -838,10 +877,11 @@ export function canColumnBeDraggedInto( block: BlockFromConfigNoChildren, draggingIndex: RelativeCellIndices["col"], targetColumnIndex: RelativeCellIndices["col"], + targetCells: ReturnType = getCellsAtColumnHandle( + block, + targetColumnIndex, + ), ) { - // Check cells at the target column - const targetCells = getCellsAtColumnHandle(block, targetColumnIndex); - // If no cells have colspans > 1, dragging is always allowed const hasMergedCells = targetCells.some((cell) => getColspan(cell.cell) > 1); if (!hasMergedCells) { @@ -876,12 +916,8 @@ export function areInSameColumn( to: RelativeCellIndices, block: BlockFromConfigNoChildren, ) { - // Table indices are relative to the table, so we need to resolve the absolute cell indices - const anchorAbsoluteCellIndices = getAbsoluteTableCells(from, block); - - // Table indices are relative to the table, so we need to resolve the absolute cell indices - const headAbsoluteCellIndices = getAbsoluteTableCells(to, block); - - // Compare the column indices to determine the merge direction - return anchorAbsoluteCellIndices.col === headAbsoluteCellIndices.col; + // Resolve both relative cell positions using a single occupancy grid. + const getAbsolute = getRelativeToAbsoluteTableCellMapping(block); + // Compare absolute columns to determine the merge direction. + return getAbsolute(from).col === getAbsolute(to).col; } diff --git a/packages/core/src/api/nodeConversions/blockToNode.test.ts b/packages/core/src/api/nodeConversions/blockToNode.test.ts index 8074e5fa0d..a2fa005557 100644 --- a/packages/core/src/api/nodeConversions/blockToNode.test.ts +++ b/packages/core/src/api/nodeConversions/blockToNode.test.ts @@ -111,3 +111,41 @@ describe("blockToNode: plain-block backwards compatibility (write path)", () => editor._tiptapEditor.destroy(); }); }); + +describe("blockToNode: tables", () => { + it("resolves column widths to absolute columns with colspans and rowspans", () => { + const editor = BlockNoteEditor.create(); + + /** + * | 1-1 (rowspan 2) | 1-2 (colspan 2) | + * | | 2-1 | 2-2 | + */ + const node = blockToNode( + { + type: "table", + content: { + type: "tableContent", + columnWidths: [100, 200, 300], + rows: [ + { + cells: [ + { type: "tableCell", props: { rowspan: 2 }, content: "1-1" }, + { type: "tableCell", props: { colspan: 2 }, content: "1-2" }, + ], + }, + { cells: ["2-1", "2-2"] }, + ], + }, + } as any, + editor.pmSchema, + ); + + const table = node.firstChild!; + expect(table.child(0).child(0).attrs.colwidth).toEqual([100]); + expect(table.child(0).child(1).attrs.colwidth).toEqual([200, 300]); + expect(table.child(1).child(0).attrs.colwidth).toEqual([200]); + expect(table.child(1).child(1).attrs.colwidth).toEqual([300]); + + editor._tiptapEditor.destroy(); + }); +}); diff --git a/packages/core/src/api/nodeConversions/blockToNode.ts b/packages/core/src/api/nodeConversions/blockToNode.ts index 7728ecf163..cf6fff3d50 100644 --- a/packages/core/src/api/nodeConversions/blockToNode.ts +++ b/packages/core/src/api/nodeConversions/blockToNode.ts @@ -22,7 +22,7 @@ import { } from "../../schema/blocks/children.js"; import { getColspan, isPartialTableCell } from "../../util/table.js"; import { UnreachableCaseError } from "../../util/typescript.js"; -import { getAbsoluteTableCells } from "../blockManipulation/tables/tables.js"; +import { getRelativeToAbsoluteTableCellMapping } from "../blockManipulation/tables/tables.js"; import { getStyleSchema, isPlainContentNodeType } from "../pmUtil.js"; /** @@ -211,6 +211,14 @@ export function tableContentToNodes< const columnWidths: (number | undefined)[] = tableContent.columnWidths ?? []; + // Colwidths are absolutely referenced to the table, so we need to resolve + // each cell's relative index to its absolute column index. The occupancy + // grid is built and scanned once per table, since doing so for every cell + // makes the conversion quadratic in the number of cells. + const getAbsolute = getRelativeToAbsoluteTableCellMapping( + { type: "table", content: tableContent } as any, + ); + for (let rowIndex = 0; rowIndex < tableContent.rows.length; rowIndex++) { const row = tableContent.rows[rowIndex]; const columnNodes: Node[] = []; @@ -227,20 +235,16 @@ export function tableContentToNodes< */ let content: Fragment | Node | readonly Node[] | null = null; - // Colwidths are absolutely referenced to the table, so we need to resolve the relative cell index to the absolute cell index - const absoluteCellIndex = getAbsoluteTableCells( - { - row: rowIndex, - col: cellIndex, - }, - { type: "table", content: tableContent } as any, - ); + const { col: absoluteColumnIndex } = getAbsolute({ + row: rowIndex, + col: cellIndex, + }); // Assume the column width is the width of the cell at the absolute cell index let colwidth: (number | undefined)[] | null = columnWidths[ - absoluteCellIndex.col + absoluteColumnIndex ] - ? [columnWidths[absoluteCellIndex.col]] + ? [columnWidths[absoluteColumnIndex]] : null; if (!cell) { @@ -262,7 +266,7 @@ export function tableContentToNodes< // If the cell has a > 1 colspan, we need to get the column width for each cell in the span colwidth = new Array(colspan).fill(false).map((_, i) => { // Starting from the absolute column index, get the column width for each cell in the span - return columnWidths[absoluteCellIndex.col + i] ?? undefined; + return columnWidths[absoluteColumnIndex + i] ?? undefined; }); } } else { diff --git a/packages/core/src/extensions/TableHandles/TableHandles.ts b/packages/core/src/extensions/TableHandles/TableHandles.ts index 5abdbfab8d..086b3609ff 100644 --- a/packages/core/src/extensions/TableHandles/TableHandles.ts +++ b/packages/core/src/extensions/TableHandles/TableHandles.ts @@ -22,6 +22,7 @@ import { getCellsAtColumnHandle, getCellsAtRowHandle, getDimensionsOfTable, + getTableCellOccupancyGrid, moveColumn, moveRow, } from "../../api/blockManipulation/tables/tables.js"; @@ -471,6 +472,7 @@ export class TableHandlesView implements PluginView { this.state.draggingState = undefined; const columnWidths = this.state.block.content.columnWidths; + const occupancyGrid = getTableCellOccupancyGrid(this.state.block); if (draggingState.draggedCellOrientation === "row") { if ( @@ -478,6 +480,7 @@ export class TableHandlesView implements PluginView { this.state.block, draggingState.originalIndex, rowIndex, + getCellsAtRowHandle(this.state.block, rowIndex, occupancyGrid), ) ) { // If the target row is invalid, don't move the row @@ -487,6 +490,7 @@ export class TableHandlesView implements PluginView { this.state.block, draggingState.originalIndex, rowIndex, + occupancyGrid, ); this.editor.updateBlock(this.state.block, { type: "table", @@ -501,6 +505,7 @@ export class TableHandlesView implements PluginView { this.state.block, draggingState.originalIndex, colIndex, + getCellsAtColumnHandle(this.state.block, colIndex, occupancyGrid), ) ) { // If the target column is invalid, don't move the column @@ -510,6 +515,7 @@ export class TableHandlesView implements PluginView { this.state.block, draggingState.originalIndex, colIndex, + occupancyGrid, ); const [columnWidth] = columnWidths.splice(draggingState.originalIndex, 1); columnWidths.splice(colIndex, 0, columnWidth); @@ -697,18 +703,36 @@ export const TableHandlesExtension = createExtension(({ editor }) => { const { block, draggingState } = view.state; const { originalIndex, draggedCellOrientation } = draggingState; + // Reuse the drop target's cells for validation and decorations. + // Skip the lookup when there is no block or the position is unchanged. + const cellsAtDropTarget = + block && newIndex !== originalIndex + ? draggedCellOrientation === "row" + ? getCellsAtRowHandle(block, newIndex) + : getCellsAtColumnHandle(block, newIndex) + : []; + // Return empty decorations if: - // - Dragging to same position + // - Dragging to the same position // - No block exists - // - Row drag not allowed - // - Column drag not allowed + // - The row or column drag would split merged cells if ( newIndex === originalIndex || !block || (draggedCellOrientation === "row" && - !canRowBeDraggedInto(block, originalIndex, newIndex)) || + !canRowBeDraggedInto( + block, + originalIndex, + newIndex, + cellsAtDropTarget, + )) || (draggedCellOrientation === "col" && - !canColumnBeDraggedInto(block, originalIndex, newIndex)) + !canColumnBeDraggedInto( + block, + originalIndex, + newIndex, + cellsAtDropTarget, + )) ) { return DecorationSet.create(state.doc, decorations); } @@ -717,12 +741,7 @@ export const TableHandlesExtension = createExtension(({ editor }) => { const tableResolvedPos = state.doc.resolve(tablePos + 1); if (view.state.draggingState.draggedCellOrientation === "row") { - const cellsInRow = getCellsAtRowHandle( - view.state.block, - newIndex, - ); - - cellsInRow.forEach(({ row, col }) => { + cellsAtDropTarget.forEach(({ row, col }) => { // Gets each row in the table. const rowResolvedPos = state.doc.resolve( tableResolvedPos.posAtIndex(row) + 1, @@ -763,12 +782,7 @@ export const TableHandlesExtension = createExtension(({ editor }) => { ); }); } else { - const cellsInColumn = getCellsAtColumnHandle( - view.state.block, - newIndex, - ); - - cellsInColumn.forEach(({ row, col }) => { + cellsAtDropTarget.forEach(({ row, col }) => { // Gets each row in the table. const rowResolvedPos = state.doc.resolve( tableResolvedPos.posAtIndex(row) + 1,