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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 53 additions & 0 deletions packages/core/src/api/blockManipulation/tables/tables.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {
getCellsAtRowHandle,
getRelativeTableCells,
getAbsoluteTableCells,
getRelativeToAbsoluteTableCellMapping,
moveColumn,
moveRow,
cropEmptyRowsOrColumns,
Expand Down Expand Up @@ -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({
Expand Down
88 changes: 62 additions & 26 deletions packages/core/src/api/blockManipulation/tables/tables.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<DefaultBlockSchema["table"], any, any>,
): (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.
*
Expand Down Expand Up @@ -430,9 +462,8 @@ export function getRelativeTableCells(
export function getCellsAtRowHandle(
block: BlockFromConfigNoChildren<DefaultBlockSchema["table"], any, any>,
relativeRowIndex: RelativeCellIndices["row"],
occupancyGrid: OccupancyGrid = getTableCellOccupancyGrid(block),
) {
const occupancyGrid = getTableCellOccupancyGrid(block);

if (relativeRowIndex < 0 || relativeRowIndex >= occupancyGrid.length) {
return [];
}
Expand Down Expand Up @@ -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<string>();
return cells.filter(({ row, col }) => {
const key = `${row},${col}`;
if (seen.has(key)) {
return false;
}
seen.add(key);
return true;
});
}

Expand Down Expand Up @@ -509,9 +544,8 @@ export function getCellsAtRowHandle(
export function getCellsAtColumnHandle(
block: BlockFromConfigNoChildren<DefaultBlockSchema["table"], any, any>,
relativeColumnIndex: RelativeCellIndices["col"],
occupancyGrid: OccupancyGrid = getTableCellOccupancyGrid(block),
) {
const occupancyGrid = getTableCellOccupancyGrid(block);

if (
relativeColumnIndex < 0 ||
relativeColumnIndex >= occupancyGrid[0].length
Expand Down Expand Up @@ -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<string>();
return cells.filter(({ row, col }) => {
const key = `${row},${col}`;
if (seen.has(key)) {
return false;
}
seen.add(key);
return true;
});
}

Expand Down Expand Up @@ -803,10 +841,11 @@ export function canRowBeDraggedInto(
block: BlockFromConfigNoChildren<DefaultBlockSchema["table"], any, any>,
draggingIndex: RelativeCellIndices["row"],
targetRowIndex: RelativeCellIndices["row"],
targetCells: ReturnType<typeof getCellsAtRowHandle> = 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) {
Expand Down Expand Up @@ -838,10 +877,11 @@ export function canColumnBeDraggedInto(
block: BlockFromConfigNoChildren<DefaultBlockSchema["table"], any, any>,
draggingIndex: RelativeCellIndices["col"],
targetColumnIndex: RelativeCellIndices["col"],
targetCells: ReturnType<typeof getCellsAtColumnHandle> = 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) {
Expand Down Expand Up @@ -876,12 +916,8 @@ export function areInSameColumn(
to: RelativeCellIndices,
block: BlockFromConfigNoChildren<DefaultBlockSchema["table"], any, any>,
) {
// 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;
}
38 changes: 38 additions & 0 deletions packages/core/src/api/nodeConversions/blockToNode.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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();
});
});
28 changes: 16 additions & 12 deletions packages/core/src/api/nodeConversions/blockToNode.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";

/**
Expand Down Expand Up @@ -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[] = [];
Expand All @@ -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) {
Expand All @@ -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 {
Expand Down
Loading
Loading