From 4a53da4ded5676027fb20e54a89cfc087c191243 Mon Sep 17 00:00:00 2001 From: Nick the Sick Date: Tue, 3 Nov 2026 13:22:49 +0100 Subject: [PATCH 1/4] fix(core): normalize imported tables before block conversion --- .../core/src/api/parsers/html/parseHTML.ts | 4 +- packages/core/src/blocks/Table/block.ts | 18 +- .../blocks/Table/normalizeImportedTables.ts | 44 +++ .../core/src/blocks/Table/parseTable.test.ts | 289 ++++++++++++++++-- 4 files changed, 328 insertions(+), 27 deletions(-) create mode 100644 packages/core/src/blocks/Table/normalizeImportedTables.ts diff --git a/packages/core/src/api/parsers/html/parseHTML.ts b/packages/core/src/api/parsers/html/parseHTML.ts index 86243d5be9..fe8de75969 100644 --- a/packages/core/src/api/parsers/html/parseHTML.ts +++ b/packages/core/src/api/parsers/html/parseHTML.ts @@ -1,4 +1,5 @@ import { DOMParser, Schema } from "prosemirror-model"; +import { normalizeImportedTables } from "../../../blocks/Table/normalizeImportedTables.js"; import { BlockSchema, InlineContentSchema, @@ -64,9 +65,10 @@ export function HTMLToBlocks< // const doc = pmSchema.nodes["doc"].createAndFill()!; // and context: doc.resolve(3), - const parentNode = parser.parse(htmlNode, { + const parsedNode = parser.parse(htmlNode, { topNode: pmSchema.nodes["blockGroup"].create(), }); + const parentNode = normalizeImportedTables(parsedNode); const blocks: Block[] = []; diff --git a/packages/core/src/blocks/Table/block.ts b/packages/core/src/blocks/Table/block.ts index 85b81bc31f..0109685546 100644 --- a/packages/core/src/blocks/Table/block.ts +++ b/packages/core/src/blocks/Table/block.ts @@ -21,21 +21,29 @@ export const tablePropSchema = { }; /** - * Reads HTML cell spans, keeping rowspans within the containing table. + * Reads HTML cell spans, keeping rowspans within the containing row group. */ function parseTableSpan( element: HTMLElement, attribute: "colspan" | "rowspan", ): number { const raw = element.getAttribute(attribute) ?? ""; - const value = /^[0-9]+$/.test(raw) ? Number(raw) : 1; + const parsed = /^[0-9]+$/.test(raw) ? Number(raw) : 1; + const value = Number.isSafeInteger(parsed) && parsed > 0 ? parsed : 1; if (attribute === "colspan") { - return value; + // HTML caps colspans at 1000; bound allocation before building a TableMap. + return Math.min(value, 1000); } const row = element.closest("tr"); - const table = row?.closest("table"); - return row && table ? Math.min(value, table.rows.length - row.rowIndex) : 1; + const group = row?.parentElement; + if (!row || !group) { + return 1; + } + const rows = Array.from(group.children).filter( + (child) => child.tagName === "TR", + ); + return Math.min(value, rows.length - rows.indexOf(row)); } const TiptapTableHeader = Node.create<{ diff --git a/packages/core/src/blocks/Table/normalizeImportedTables.ts b/packages/core/src/blocks/Table/normalizeImportedTables.ts new file mode 100644 index 0000000000..75d756a360 --- /dev/null +++ b/packages/core/src/blocks/Table/normalizeImportedTables.ts @@ -0,0 +1,44 @@ +import { Node } from "prosemirror-model"; +import { EditorState, Transaction } from "prosemirror-state"; +import { fixTables, TableMap } from "prosemirror-tables"; + +/** Repair imported ProseMirror tables before projecting them to BlockNote JSON. */ +export function normalizeImportedTables(doc: Node): Node { + let state: EditorState | undefined; + let transaction: Transaction | undefined; + doc.descendants((node, pos) => { + if (node.type.spec.tableRole !== "table") { + return; + } + const map = TableMap.get(node); + if (map.problems) { + state ??= EditorState.create({ doc }); + transaction ??= state.tr; + // Keep a wholly empty table editable. fixTables would delete the table + // and leave its enclosing BlockNote block container without content. + if (map.width === 0) { + const { tableRow, tableCell } = doc.type.schema.nodes; + transaction.replaceWith( + transaction.mapping.map(pos), + transaction.mapping.map(pos + node.nodeSize), + node.type.create( + node.attrs, + tableRow.create(null, tableCell.createAndFill()), + node.marks, + ), + ); + } + } + return false; + }); + if (!state || !transaction) { + return doc; + } + state = state.apply(transaction); + // Collision repair can expose missing cells: one upstream pass is not + // always sufficient. This state has no live editor plugins or side effects. + for (let repair = fixTables(state); repair; repair = fixTables(state)) { + state = state.apply(repair); + } + return state.doc; +} diff --git a/packages/core/src/blocks/Table/parseTable.test.ts b/packages/core/src/blocks/Table/parseTable.test.ts index 6acc929664..d2461881c8 100644 --- a/packages/core/src/blocks/Table/parseTable.test.ts +++ b/packages/core/src/blocks/Table/parseTable.test.ts @@ -1,4 +1,5 @@ import { DOMParser } from "prosemirror-model"; +import { TableMap } from "prosemirror-tables"; import { afterEach, describe, expect, it } from "vite-plus/test"; import { BlockNoteEditor } from "../../editor/BlockNoteEditor.js"; @@ -11,6 +12,250 @@ describe.each(["td", "th"])("pasting HTML table spans on %s", (tag) => { }); it.each([ + ["zero rowspan", `<${tag} rowspan="0">a`, ["a"]], + ["zero colspan", `<${tag} colspan="0">a`, ["a"]], + [ + "fully spanned empty row", + `<${tag} rowspan="2">a`, + ["a"], + ], + [ + "rowspan across row groups", + `<${tag} rowspan="2">a<${tag}>b`, + ["a", "b"], + ], + [ + "overlapping colspan", + `<${tag}>a<${tag} rowspan="2">b<${tag} colspan="2">c`, + ["a", "b", "c"], + ], + ])("pastes %s without losing surrounding paragraphs", (name, rows, texts) => { + editor = BlockNoteEditor.create(); + editor.mount(document.createElement("div")); + + const problems: unknown[] = []; + editor.onChange(() => { + editor!.prosemirrorState.doc.descendants((node) => { + if (node.type.spec.tableRole === "table") { + problems.push(TableMap.get(node).problems); + } + }); + }); + editor.pasteHTML(`

Before

${rows}

After

`); + + expect(problems.length).toBeGreaterThan(0); + expect(problems.every((problem) => problem === null)).toBe(true); + expect(() => editor!.blocksToFullHTML()).not.toThrow(); + const table = editor.document.find((block) => block.type === "table"); + expect(table).toBeDefined(); + const cellTexts = table?.content.rows.flatMap((row) => + row.cells.flatMap((cell) => { + const content = "content" in cell ? cell.content : cell; + return content.flatMap((inline) => + inline.type === "text" ? [inline.text] : [], + ); + }), + ); + expect(cellTexts).toEqual(texts); + if (name === "fully spanned empty row") { + expect(table?.content.rows.map((row) => row.cells.length)).toEqual([ + 1, 0, + ]); + expect(table?.content.rows[0].cells[0]).toMatchObject({ + props: { colspan: 1, rowspan: 2 }, + }); + } + if (name === "rowspan across row groups") { + expect(table?.content.rows[0].cells[0]).toMatchObject({ + props: { rowspan: 1 }, + }); + } + if (name === "overlapping colspan") { + expect(table?.content.rows[1].cells.at(-1)).toMatchObject({ + props: { colspan: 1 }, + content: [{ text: "c" }], + }); + } + expect(editor.document).toEqual( + expect.arrayContaining([ + expect.objectContaining({ + type: "paragraph", + content: [expect.objectContaining({ text: "Before" })], + }), + expect.objectContaining({ + type: "paragraph", + content: [expect.objectContaining({ text: "After" })], + }), + ]), + ); + + // Standalone imports use the same repair without touching the live editor. + const imported = editor.tryParseHTMLToBlocks(`${rows}
`); + const serialized = editor.blocksToFullHTML(imported); + expect(editor.tryParseHTMLToBlocks(serialized)).toMatchObject( + imported.map(({ id: _id, ...block }) => block), + ); + }); + + it.each(["", "", ""])( + "imports a zero-width table %j as one editable cell", + (rows) => { + editor = BlockNoteEditor.create(); + const imported = editor.tryParseHTMLToBlocks(`${rows}
`); + expect(imported).toMatchObject([ + { + type: "table", + content: { + rows: [ + { cells: [{ content: [], props: { colspan: 1, rowspan: 1 } }] }, + ], + }, + }, + ]); + expect(() => editor!.blocksToFullHTML(imported)).not.toThrow(); + }, + ); + + it("keeps cell attributes and inline marks while repairing a collision", () => { + editor = BlockNoteEditor.create(); + const container = document.createElement("div"); + container.innerHTML = `<${tag}>a<${tag} rowspan="2">b<${tag} colspan="2" colwidth="120,160">c
`; + const imported = editor.tryParseHTMLToBlocks(container.innerHTML); + container.innerHTML = editor.blocksToFullHTML(imported); + const parsed = DOMParser.fromSchema(editor.pmSchema).parse(container); + parsed.check(); + const cells: { + colspan: number; + colwidth: number[]; + marks: string[]; + type: string; + }[] = []; + parsed.descendants((node) => { + if (node.type.spec.tableRole === "table") { + expect(TableMap.get(node).problems).toBeNull(); + } + if ( + node.type.spec.tableRole === "cell" || + node.type.spec.tableRole === "header_cell" + ) { + if (node.textContent === "c") { + cells.push({ + colspan: node.attrs.colspan, + colwidth: node.attrs.colwidth, + marks: node.firstChild!.firstChild!.marks.map( + (mark) => mark.type.name, + ), + type: node.type.name, + }); + } + } + }); + expect(cells).toEqual([ + { + colspan: 1, + colwidth: [120], + marks: ["bold"], + type: tag === "th" ? "tableHeader" : "tableCell", + }, + ]); + }); + + it.each([ + `<${tag}>a
`, + `
<${tag}>a
`, + ])("preserves inherited formatting for %s", (html) => { + editor = BlockNoteEditor.create(); + editor.mount(document.createElement("div")); + const imported = editor.tryParseHTMLToBlocks(html); + expect(imported[0]).toMatchObject({ + type: "table", + content: { + rows: [ + { cells: [{ content: [{ text: "a", styles: { bold: true } }] }] }, + ], + }, + }); + editor.pasteHTML(html); + expect(editor.document[0]).toMatchObject({ + type: "table", + content: { + rows: [ + { cells: [{ content: [{ text: "a", styles: { bold: true } }] }] }, + ], + }, + }); + }); + + it("preserves a covered row followed by a populated row", () => { + editor = BlockNoteEditor.create(); + const html = `<${tag} rowspan="2">a<${tag}>b
`; + const imported = editor.tryParseHTMLToBlocks(html); + const table = imported.find((block) => block.type === "table")!; + expect(table.content.rows.map((row) => row.cells.length)).toEqual([ + 1, 0, 1, + ]); + expect( + editor.tryParseHTMLToBlocks(editor.blocksToFullHTML(imported)), + ).toMatchObject(imported.map(({ id: _id, ...block }) => block)); + const container = document.createElement("div"); + container.innerHTML = editor.blocksToFullHTML(imported); + DOMParser.fromSchema(editor.pmSchema).parse(container).check(); + }); + + it("repairs multiple tables without changing their order or surrounding text", () => { + editor = BlockNoteEditor.create(); + const imported = editor.tryParseHTMLToBlocks( + `

Before

<${tag}>a<${tag} rowspan="2">b<${tag} colspan="2">c

After

`, + ); + expect(imported).toMatchObject([ + { type: "paragraph", content: [{ text: "Before" }] }, + { type: "table", content: { rows: [{ cells: [{ content: [] }] }] } }, + { type: "table" }, + { type: "table", content: { rows: [{ cells: [{ content: [] }] }] } }, + { type: "paragraph", content: [{ text: "After" }] }, + ]); + const tables = imported.filter((block) => block.type === "table"); + expect( + tables.flatMap((table) => + table.content.rows.flatMap((row) => + row.cells.flatMap((cell) => { + const content = "content" in cell ? cell.content : cell; + return content.flatMap((inline) => + inline.type === "text" ? [inline.text] : [], + ); + }), + ), + ), + ).toEqual(["a", "b", "c"]); + const container = document.createElement("div"); + container.innerHTML = editor.blocksToFullHTML(imported); + const parsed = DOMParser.fromSchema(editor.pmSchema).parse(container); + parsed.check(); + const problems: unknown[] = []; + parsed.descendants((node) => { + if (node.type.spec.tableRole === "table") { + problems.push(TableMap.get(node).problems); + } + }); + expect(problems).toEqual([null, null, null]); + }); + + it("preserves text around a nested malformed table", () => { + editor = BlockNoteEditor.create(); + const imported = editor.tryParseHTMLToBlocks( + `<${tag}>Before
ab
c
After`, + ); + expect(imported[0]).toMatchObject({ + type: "table", + content: { + rows: [{ cells: [{ content: [{ text: "BeforeabcAfter" }] }] }], + }, + }); + expect(() => editor!.blocksToFullHTML(imported)).not.toThrow(); + }); + + it.each([ + "0", "1.5", "-1", "", @@ -21,7 +266,7 @@ describe.each(["td", "th"])("pasting HTML table spans on %s", (tag) => { "0x2", " 2", "2 ", - ])("defaults non-digit span %j to 1", (span) => { + ])("defaults invalid span %j to 1", (span) => { editor = BlockNoteEditor.create(); editor.mount(document.createElement("div")); editor.pasteHTML( @@ -35,26 +280,28 @@ describe.each(["td", "th"])("pasting HTML table spans on %s", (tag) => { }); }); - it.each(["0", "4294967296"])( - "accepts digit-only span %j without range validation", - (span) => { - editor = BlockNoteEditor.create(); - const container = document.createElement("div"); - container.innerHTML = `<${tag} colspan="${span}">Cell
`; - const colspans: number[] = []; - DOMParser.fromSchema(editor.pmSchema) - .parse(container) - .descendants((node) => { - if ( - node.type.name === "tableCell" || - node.type.name === "tableHeader" - ) { - colspans.push(node.attrs.colspan); - } - }); - expect(colspans).toEqual([Number(span)]); - }, - ); + it.each([ + ["0", 1], + ["9007199254740992", 1], + ["1001", 1000], + ["4294967296", 1000], + ])("parses numeric colspan %j as %j", (span, expected) => { + editor = BlockNoteEditor.create(); + const container = document.createElement("div"); + container.innerHTML = `<${tag} colspan="${span}">Cell
`; + const colspans: number[] = []; + DOMParser.fromSchema(editor.pmSchema) + .parse(container) + .descendants((node) => { + if ( + node.type.name === "tableCell" || + node.type.name === "tableHeader" + ) { + colspans.push(node.attrs.colspan); + } + }); + expect(colspans).toEqual([expected]); + }); it.each(["100", "00100"])( "clamps rowspan %j to the remaining table height", From 16a7cc0fe340aea5111797a18425f2e5628ab1df Mon Sep 17 00:00:00 2001 From: Nick the Sick Date: Wed, 11 Nov 2026 15:05:57 +0100 Subject: [PATCH 2/4] fix(core): align imported table widths with normalized spans --- packages/core/src/blocks/Table/block.ts | 10 ++++-- .../core/src/blocks/Table/parseTable.test.ts | 32 ++++++++++++------- 2 files changed, 28 insertions(+), 14 deletions(-) diff --git a/packages/core/src/blocks/Table/block.ts b/packages/core/src/blocks/Table/block.ts index 0109685546..a1328df485 100644 --- a/packages/core/src/blocks/Table/block.ts +++ b/packages/core/src/blocks/Table/block.ts @@ -85,7 +85,10 @@ const TiptapTableHeader = Node.create<{ parseHTML: (element) => { const colwidth = element.getAttribute("colwidth"); const value = colwidth - ? colwidth.split(",").map((width) => parseInt(width, 10)) + ? colwidth + .split(",") + .slice(0, parseTableSpan(element, "colspan")) + .map((width) => parseInt(width, 10)) : null; return value; @@ -151,7 +154,10 @@ const TiptapTableCell = Node.create<{ parseHTML: (element) => { const colwidth = element.getAttribute("colwidth"); const value = colwidth - ? colwidth.split(",").map((width) => parseInt(width, 10)) + ? colwidth + .split(",") + .slice(0, parseTableSpan(element, "colspan")) + .map((width) => parseInt(width, 10)) : null; return value; diff --git a/packages/core/src/blocks/Table/parseTable.test.ts b/packages/core/src/blocks/Table/parseTable.test.ts index d2461881c8..26b54ced78 100644 --- a/packages/core/src/blocks/Table/parseTable.test.ts +++ b/packages/core/src/blocks/Table/parseTable.test.ts @@ -76,18 +76,11 @@ describe.each(["td", "th"])("pasting HTML table spans on %s", (tag) => { content: [{ text: "c" }], }); } - expect(editor.document).toEqual( - expect.arrayContaining([ - expect.objectContaining({ - type: "paragraph", - content: [expect.objectContaining({ text: "Before" })], - }), - expect.objectContaining({ - type: "paragraph", - content: [expect.objectContaining({ text: "After" })], - }), - ]), - ); + expect(editor.document.slice(0, 3)).toMatchObject([ + { type: "paragraph", content: [{ text: "Before" }] }, + { type: "table" }, + { type: "paragraph", content: [{ text: "After" }] }, + ]); // Standalone imports use the same repair without touching the live editor. const imported = editor.tryParseHTMLToBlocks(`${rows}
`); @@ -411,4 +404,19 @@ describe.each(["td", "th"])("pasting HTML table spans on %s", (tag) => { }); }, ); + + it.each([ + ["0", [120, 200]], + ["1", [120, 200]], + ["2", [120, 160, 200]], + ])("keeps column widths aligned with colspan %j", (span, columnWidths) => { + editor = BlockNoteEditor.create(); + const imported = editor.tryParseHTMLToBlocks( + `<${tag} colspan="${span}" colwidth="120,160">a<${tag} colwidth="200">b
`, + ); + expect(imported[0]).toMatchObject({ + type: "table", + content: { columnWidths }, + }); + }); }); From 98cd83664fd6333d295eadfa9c85fb55feb23bf1 Mon Sep 17 00:00:00 2001 From: Nick the Sick Date: Wed, 11 Nov 2026 18:52:22 +0100 Subject: [PATCH 3/4] fix(core): limit imported table headers and simplify tests --- .../core/src/api/parsers/html/parseHTML.ts | 15 +- .../core/src/blocks/Table/parseTable.test.ts | 676 +++++++++--------- 2 files changed, 339 insertions(+), 352 deletions(-) diff --git a/packages/core/src/api/parsers/html/parseHTML.ts b/packages/core/src/api/parsers/html/parseHTML.ts index fe8de75969..998eece3a0 100644 --- a/packages/core/src/api/parsers/html/parseHTML.ts +++ b/packages/core/src/api/parsers/html/parseHTML.ts @@ -41,13 +41,22 @@ function stripEmptyBlockPlaceholder(content: any[]): any[] { return stripped; } -function stripEmptyBlockPlaceholderFromBlocks(blocks: Block[]) { +function normalizeImportedBlockContent(blocks: Block[]) { for (const block of blocks) { if (Array.isArray(block.content)) { (block as any).content = stripEmptyBlockPlaceholder(block.content); + } else if (block.content?.type === "tableContent") { + // Match the table UI: only the first row/column can be headers. + // Keep every cell, but import additional headers as ordinary cells. + if (block.content.headerRows !== undefined) { + block.content.headerRows = Math.min(block.content.headerRows, 1); + } + if (block.content.headerCols !== undefined) { + block.content.headerCols = Math.min(block.content.headerCols, 1); + } } if (block.children.length > 0) { - stripEmptyBlockPlaceholderFromBlocks(block.children); + normalizeImportedBlockContent(block.children); } } } @@ -76,7 +85,7 @@ export function HTMLToBlocks< blocks.push(nodeToBlock(parentNode.child(i), parentNode)); } - stripEmptyBlockPlaceholderFromBlocks(blocks); + normalizeImportedBlockContent(blocks); return blocks; } diff --git a/packages/core/src/blocks/Table/parseTable.test.ts b/packages/core/src/blocks/Table/parseTable.test.ts index 26b54ced78..b6b3da726c 100644 --- a/packages/core/src/blocks/Table/parseTable.test.ts +++ b/packages/core/src/blocks/Table/parseTable.test.ts @@ -1,422 +1,400 @@ import { DOMParser } from "prosemirror-model"; -import { TableMap } from "prosemirror-tables"; import { afterEach, describe, expect, it } from "vite-plus/test"; import { BlockNoteEditor } from "../../editor/BlockNoteEditor.js"; -describe.each(["td", "th"])("pasting HTML table spans on %s", (tag) => { - let editor: BlockNoteEditor | undefined; +describe("importing HTML tables", () => { + let editor: BlockNoteEditor; afterEach(() => { editor?.unmount(); }); - it.each([ - ["zero rowspan", `<${tag} rowspan="0">a`, ["a"]], - ["zero colspan", `<${tag} colspan="0">a`, ["a"]], - [ - "fully spanned empty row", - `<${tag} rowspan="2">a`, - ["a"], - ], - [ - "rowspan across row groups", - `<${tag} rowspan="2">a<${tag}>b`, - ["a", "b"], - ], - [ - "overlapping colspan", - `<${tag}>a<${tag} rowspan="2">b<${tag} colspan="2">c`, - ["a", "b", "c"], - ], - ])("pastes %s without losing surrounding paragraphs", (name, rows, texts) => { - editor = BlockNoteEditor.create(); - editor.mount(document.createElement("div")); - - const problems: unknown[] = []; - editor.onChange(() => { - editor!.prosemirrorState.doc.descendants((node) => { - if (node.type.spec.tableRole === "table") { - problems.push(TableMap.get(node).problems); - } - }); - }); - editor.pasteHTML(`

Before

${rows}

After

`); - - expect(problems.length).toBeGreaterThan(0); - expect(problems.every((problem) => problem === null)).toBe(true); - expect(() => editor!.blocksToFullHTML()).not.toThrow(); - const table = editor.document.find((block) => block.type === "table"); - expect(table).toBeDefined(); - const cellTexts = table?.content.rows.flatMap((row) => - row.cells.flatMap((cell) => { - const content = "content" in cell ? cell.content : cell; - return content.flatMap((inline) => - inline.type === "text" ? [inline.text] : [], - ); - }), - ); - expect(cellTexts).toEqual(texts); - if (name === "fully spanned empty row") { - expect(table?.content.rows.map((row) => row.cells.length)).toEqual([ - 1, 0, - ]); - expect(table?.content.rows[0].cells[0]).toMatchObject({ - props: { colspan: 1, rowspan: 2 }, - }); - } - if (name === "rowspan across row groups") { - expect(table?.content.rows[0].cells[0]).toMatchObject({ - props: { rowspan: 1 }, - }); - } - if (name === "overlapping colspan") { - expect(table?.content.rows[1].cells.at(-1)).toMatchObject({ - props: { colspan: 1 }, - content: [{ text: "c" }], - }); - } - expect(editor.document.slice(0, 3)).toMatchObject([ - { type: "paragraph", content: [{ text: "Before" }] }, - { type: "table" }, - { type: "paragraph", content: [{ text: "After" }] }, - ]); - - // Standalone imports use the same repair without touching the live editor. - const imported = editor.tryParseHTMLToBlocks(`${rows}
`); - const serialized = editor.blocksToFullHTML(imported); - expect(editor.tryParseHTMLToBlocks(serialized)).toMatchObject( - imported.map(({ id: _id, ...block }) => block), - ); - }); - - it.each(["", "", ""])( - "imports a zero-width table %j as one editable cell", - (rows) => { - editor = BlockNoteEditor.create(); - const imported = editor.tryParseHTMLToBlocks(`${rows}
`); - expect(imported).toMatchObject([ - { - type: "table", - content: { - rows: [ - { cells: [{ content: [], props: { colspan: 1, rowspan: 1 } }] }, - ], - }, - }, - ]); - expect(() => editor!.blocksToFullHTML(imported)).not.toThrow(); - }, - ); - - it("keeps cell attributes and inline marks while repairing a collision", () => { - editor = BlockNoteEditor.create(); - const container = document.createElement("div"); - container.innerHTML = `<${tag}>a<${tag} rowspan="2">b<${tag} colspan="2" colwidth="120,160">c
`; - const imported = editor.tryParseHTMLToBlocks(container.innerHTML); - container.innerHTML = editor.blocksToFullHTML(imported); - const parsed = DOMParser.fromSchema(editor.pmSchema).parse(container); - parsed.check(); - const cells: { - colspan: number; - colwidth: number[]; - marks: string[]; - type: string; - }[] = []; - parsed.descendants((node) => { - if (node.type.spec.tableRole === "table") { - expect(TableMap.get(node).problems).toBeNull(); - } - if ( - node.type.spec.tableRole === "cell" || - node.type.spec.tableRole === "header_cell" - ) { - if (node.textContent === "c") { - cells.push({ - colspan: node.attrs.colspan, - colwidth: node.attrs.colwidth, - marks: node.firstChild!.firstChild!.marks.map( - (mark) => mark.type.name, + // The five malformed tables reported in #3289 must not discard the paste. + describe.each(["td", "th"])("pasting spans on %s", (tag) => { + it.each([ + ["zero rowspan", `<${tag} rowspan="0">a`, ["a"]], + ["zero colspan", `<${tag} colspan="0">a`, ["a"]], + [ + "fully covered row", + `<${tag} rowspan="2">a`, + ["a"], + ], + [ + "rowspan crossing row groups", + `<${tag} rowspan="2">ab`, + ["a", "b"], + ], + [ + "overlapping colspan", + `<${tag}>a<${tag} rowspan="2">b<${tag} colspan="2">c`, + ["a", "b", "c"], + ], + ])( + "repairs %s and preserves surrounding paragraphs", + (name, rows, texts) => { + editor = BlockNoteEditor.create(); + editor.mount(document.createElement("div")); + const html = `

Before

${rows}

After

`; + const imported = editor.tryParseHTMLToBlocks(html); + editor.pasteHTML(html); + for (const blocks of [imported, editor.document]) { + expect(blocks.slice(0, 3)).toMatchObject([ + { type: "paragraph", content: [{ text: "Before" }] }, + { type: "table" }, + { type: "paragraph", content: [{ text: "After" }] }, + ]); + const table = blocks.find((block) => block.type === "table")!; + expect( + table.content.rows.flatMap((row) => + row.cells.flatMap((cell) => { + const content = "content" in cell ? cell.content : cell; + return content.flatMap((inline) => + inline.type === "text" ? [inline.text] : [], + ); + }), ), - type: node.type.name, - }); + ).toEqual(texts); + + if (name === "fully covered row") { + expect(table.content.rows.map((row) => row.cells.length)).toEqual([ + 1, 0, + ]); + expect(table.content.rows[0].cells[0]).toMatchObject({ + props: { rowspan: 2 }, + }); + } else if (name === "overlapping colspan") { + expect(table.content.rows[1].cells.at(-1)).toMatchObject({ + props: { colspan: 1 }, + content: [{ text: "c" }], + }); + } else { + expect(table.content.rows[0].cells[0]).toMatchObject({ + props: { rowspan: 1, colspan: 1 }, + }); + } } - } - }); - expect(cells).toEqual([ - { - colspan: 1, - colwidth: [120], - marks: ["bold"], - type: tag === "th" ? "tableHeader" : "tableCell", }, - ]); + ); }); - it.each([ - `<${tag}>a
`, - `
<${tag}>a
`, - ])("preserves inherited formatting for %s", (html) => { + it("preserves valid merged cells, including a covered row before more content", () => { editor = BlockNoteEditor.create(); - editor.mount(document.createElement("div")); - const imported = editor.tryParseHTMLToBlocks(html); - expect(imported[0]).toMatchObject({ - type: "table", - content: { - rows: [ - { cells: [{ content: [{ text: "a", styles: { bold: true } }] }] }, - ], - }, - }); - editor.pasteHTML(html); - expect(editor.document[0]).toMatchObject({ - type: "table", - content: { - rows: [ - { cells: [{ content: [{ text: "a", styles: { bold: true } }] }] }, - ], + const imported = editor.tryParseHTMLToBlocks(` + + + + +
Merged
LeftRight
+ `); + expect(imported).toMatchObject([ + { + type: "table", + content: { + rows: [ + { + cells: [ + { + props: { colspan: 2, rowspan: 2 }, + content: [{ text: "Merged", styles: { bold: true } }], + }, + ], + }, + { cells: [] }, + { + cells: [ + { content: [{ text: "Left" }] }, + { content: [{ text: "Right" }] }, + ], + }, + ], + }, }, - }); - }); - - it("preserves a covered row followed by a populated row", () => { - editor = BlockNoteEditor.create(); - const html = `<${tag} rowspan="2">a<${tag}>b
`; - const imported = editor.tryParseHTMLToBlocks(html); - const table = imported.find((block) => block.type === "table")!; - expect(table.content.rows.map((row) => row.cells.length)).toEqual([ - 1, 0, 1, ]); expect( editor.tryParseHTMLToBlocks(editor.blocksToFullHTML(imported)), ).toMatchObject(imported.map(({ id: _id, ...block }) => block)); - const container = document.createElement("div"); - container.innerHTML = editor.blocksToFullHTML(imported); - DOMParser.fromSchema(editor.pmSchema).parse(container).check(); }); - it("repairs multiple tables without changing their order or surrounding text", () => { + it("repairs multiple empty and malformed tables without reordering content", () => { editor = BlockNoteEditor.create(); - const imported = editor.tryParseHTMLToBlocks( - `

Before

<${tag}>a<${tag} rowspan="2">b<${tag} colspan="2">c

After

`, - ); - expect(imported).toMatchObject([ + expect( + editor.tryParseHTMLToBlocks(` +

Before

+
+
Middle
+
+

After

+ `), + ).toMatchObject([ { type: "paragraph", content: [{ text: "Before" }] }, - { type: "table", content: { rows: [{ cells: [{ content: [] }] }] } }, - { type: "table" }, - { type: "table", content: { rows: [{ cells: [{ content: [] }] }] } }, + { + type: "table", + content: { + rows: [ + { cells: [{ content: [], props: { colspan: 1, rowspan: 1 } }] }, + ], + }, + }, + { + type: "table", + content: { rows: [{ cells: [{ content: [{ text: "Middle" }] }] }] }, + }, + { + type: "table", + content: { + rows: [ + { cells: [{ content: [], props: { colspan: 1, rowspan: 1 } }] }, + ], + }, + }, { type: "paragraph", content: [{ text: "After" }] }, ]); - const tables = imported.filter((block) => block.type === "table"); - expect( - tables.flatMap((table) => - table.content.rows.flatMap((row) => - row.cells.flatMap((cell) => { - const content = "content" in cell ? cell.content : cell; - return content.flatMap((inline) => - inline.type === "text" ? [inline.text] : [], - ); - }), - ), - ), - ).toEqual(["a", "b", "c"]); - const container = document.createElement("div"); - container.innerHTML = editor.blocksToFullHTML(imported); - const parsed = DOMParser.fromSchema(editor.pmSchema).parse(container); - parsed.check(); - const problems: unknown[] = []; - parsed.descendants((node) => { - if (node.type.spec.tableRole === "table") { - problems.push(TableMap.get(node).problems); - } - }); - expect(problems).toEqual([null, null, null]); }); - it("preserves text around a nested malformed table", () => { + it("preserves inherited formatting through import and paste", () => { editor = BlockNoteEditor.create(); - const imported = editor.tryParseHTMLToBlocks( - `<${tag}>Before
ab
c
After`, - ); - expect(imported[0]).toMatchObject({ + editor.mount(document.createElement("div")); + const html = `
Bold
`; + const expected = { type: "table", content: { - rows: [{ cells: [{ content: [{ text: "BeforeabcAfter" }] }] }], + rows: [ + { cells: [{ content: [{ text: "Bold", styles: { bold: true } }] }] }, + ], }, - }); - expect(() => editor!.blocksToFullHTML(imported)).not.toThrow(); + }; + expect(editor.tryParseHTMLToBlocks(html)[0]).toMatchObject(expected); + editor.pasteHTML(html); + expect(editor.document[0]).toMatchObject(expected); }); - it.each([ - "0", - "1.5", - "-1", - "", - "invalid", - "NaN", - "Infinity", - "2e0", - "0x2", - " 2", - "2 ", - ])("defaults invalid span %j to 1", (span) => { + it("preserves cell formatting and column widths when shrinking an overlap", () => { editor = BlockNoteEditor.create(); - editor.mount(document.createElement("div")); - editor.pasteHTML( - `<${tag} colspan="${span}" rowspan="${span}">First<${tag}>Second
`, - ); - - const table = editor.document.find((block) => block.type === "table"); - expect(table?.content.rows[0].cells[0]).toMatchObject({ - props: { colspan: 1, rowspan: 1 }, - content: [{ type: "text", text: "First" }], - }); + const imported = editor.tryParseHTMLToBlocks(` + + + +
ab
c
+ `); + const container = document.createElement("div"); + container.innerHTML = editor.blocksToFullHTML(imported); + const cell = Array.from(container.querySelectorAll("td")).find( + (cell) => cell.textContent === "c", + )!; + expect(cell.getAttribute("colspan")).toBe("1"); + expect(cell.getAttribute("colwidth")).toBe("120"); + expect(cell.querySelector("strong")?.textContent).toBe("c"); }); + it.each(["-1", "1.5", "", "invalid", "Infinity", "2e0", "0x2", " 2"])( + "defaults invalid span %j to one", + (span) => { + editor = BlockNoteEditor.create(); + expect( + editor.tryParseHTMLToBlocks(` +
FirstOther
SecondLast
+ `)[0], + ).toMatchObject({ + content: { + rows: [ + { + cells: [ + { + props: { colspan: 1, rowspan: 1 }, + content: [{ text: "First" }], + }, + {}, + ], + }, + { + cells: [ + { content: [{ text: "Second" }] }, + { content: [{ text: "Last" }] }, + ], + }, + ], + }, + }); + }, + ); + + // Import repair can shrink an oversized colspan again; inspect parsing to + // distinguish the HTML limit (1000) from integer overflow or invalid input. it.each([ - ["0", 1], ["9007199254740992", 1], ["1001", 1000], ["4294967296", 1000], - ])("parses numeric colspan %j as %j", (span, expected) => { + ])("sanitizes colspan %s to %s before table repair", (span, expected) => { editor = BlockNoteEditor.create(); const container = document.createElement("div"); - container.innerHTML = `<${tag} colspan="${span}">Cell
`; + container.innerHTML = `
Cell
`; const colspans: number[] = []; DOMParser.fromSchema(editor.pmSchema) .parse(container) .descendants((node) => { - if ( - node.type.name === "tableCell" || - node.type.name === "tableHeader" - ) { + if (node.type.spec.tableRole === "cell") { colspans.push(node.attrs.colspan); } }); expect(colspans).toEqual([expected]); }); - it.each(["100", "00100"])( - "clamps rowspan %j to the remaining table height", - (span) => { - editor = BlockNoteEditor.create(); - editor.mount(document.createElement("div")); - - editor.pasteHTML( - `<${tag}>First<${tag}>Other<${tag} rowspan="${span}">Merged<${tag}>Middle<${tag} rowspan="${span}">Last
`, - ); - - const table = editor.document.find((block) => block.type === "table"); - expect(table?.content.rows).toHaveLength(3); - expect(table?.content.rows[1].cells[0]).toMatchObject({ - props: { rowspan: 2 }, - content: [{ type: "text", text: "Merged" }], - }); - expect(table?.content.rows[2].cells).toHaveLength(1); - expect(table?.content.rows[2].cells[0]).toMatchObject({ - props: { rowspan: 1 }, - content: [{ type: "text", text: "Last" }], - }); - }, - ); - - it("clamps a rowspan in a single-row table", () => { + it("clamps rowspans to the remaining row-group height", () => { editor = BlockNoteEditor.create(); - editor.mount(document.createElement("div")); - - editor.pasteHTML( - `<${tag} rowspan="100">Only
`, - ); - - const table = editor.document.find((block) => block.type === "table"); - expect(table?.content.rows).toHaveLength(1); - expect(table?.content.rows[0].cells[0]).toMatchObject({ - props: { rowspan: 1 }, - content: [{ type: "text", text: "Only" }], + expect( + editor.tryParseHTMLToBlocks(` + + + + + + +
FirstOther
MergedMiddle
Last
+ `)[0], + ).toMatchObject({ + content: { + rows: [ + { + cells: [ + { content: [{ text: "First" }] }, + { content: [{ text: "Other" }] }, + ], + }, + { + cells: [ + { props: { rowspan: 2 }, content: [{ text: "Merged" }] }, + { content: [{ text: "Middle" }] }, + ], + }, + { cells: [{ props: { rowspan: 1 }, content: [{ text: "Last" }] }] }, + ], + }, }); }); - it("does not count nested table rows toward the remaining height", () => { + it("does not count nested rows toward the outer rowspan or lose surrounding cell text", () => { editor = BlockNoteEditor.create(); - editor.mount(document.createElement("div")); - - editor.pasteHTML( - `<${tag} rowspan="100">Outer
Nested
Nested
`, - ); - - const table = editor.document.find((block) => block.type === "table"); - expect(table?.content.rows).toHaveLength(1); - expect(table?.content.rows[0].cells[0]).toMatchObject({ - props: { rowspan: 1 }, + expect( + editor.tryParseHTMLToBlocks(` +
Before + + +
ab
c
After
+ `)[0], + ).toMatchObject({ + content: { + rows: [ + { + cells: [ + { props: { rowspan: 1 }, content: [{ text: "BeforeabcAfter" }] }, + ], + }, + ], + }, }); }); - it("uses the current table height when reparsing edited DOM", () => { - editor = BlockNoteEditor.create(); - const container = document.createElement("div"); - container.innerHTML = `<${tag} rowspan="100">Merged<${tag} rowspan="1">Top<${tag} rowspan="1">Bottom
`; - const table = container.querySelector("table")!; - const parser = DOMParser.fromSchema(editor.pmSchema); - - function parseRowspans() { - const rowspans: number[] = []; - parser.parse(container).descendants((node) => { - if ( - node.type.name === "tableCell" || - node.type.name === "tableHeader" - ) { - rowspans.push(node.attrs.rowspan); - } - }); - return rowspans; - } - - expect(parseRowspans()).toEqual([2, 1, 1]); - - table - .querySelector("tbody")! - .insertAdjacentHTML( - "beforeend", - `<${tag} rowspan="1">Added`, - ); - expect(parseRowspans()).toEqual([3, 1, 1, 1]); - }); + it.each([ + ["0", [120, 200]], + ["2", [120, 160, 200]], + ])( + "aligns column widths after sanitizing colspan %s", + (span, columnWidths) => { + editor = BlockNoteEditor.create(); + expect( + editor.tryParseHTMLToBlocks(` +
ab
+ `)[0], + ).toMatchObject({ content: { columnWidths } }); + }, + ); - it.each(["2", "002"])( - "preserves merged cells with span %j and their content", - (span) => { + it.each([ + [ + "rows", + `ABCDEF`, + { headerRows: 1, headerCols: undefined }, + [ + ["A", "B"], + ["C", "D"], + ["E", "F"], + ], + ], + [ + "columns", + `ABCDEF`, + { headerRows: undefined, headerCols: 1 }, + [ + ["A", "B", "C"], + ["D", "E", "F"], + ], + ], + [ + "rows and columns", + `ABCDEFGHI`, + { headerRows: 1, headerCols: 1 }, + [ + ["A", "B", "C"], + ["D", "E", "F"], + ["G", "H", "I"], + ], + ], + ])( + "limits imported header %s to the first without losing content or formatting", + (_name, rows, headers, texts) => { editor = BlockNoteEditor.create(); editor.mount(document.createElement("div")); - - editor.pasteHTML( - `<${tag} colspan="${span}" rowspan="${span}">Merged<${tag}>Top<${tag}>Bottom
`, - ); - - const table = editor.document.find((block) => block.type === "table"); - expect(table?.content.rows).toHaveLength(2); - expect(table?.content.rows[0].cells[0]).toMatchObject({ - props: { colspan: 2, rowspan: 2 }, - content: [{ type: "text", text: "Merged" }], + const html = `${rows}
`; + const imported = editor.tryParseHTMLToBlocks(html); + expect(imported[0]).toMatchObject({ content: headers }); + expect(imported[0]).toMatchObject({ + content: { + rows: texts.map((row) => ({ + cells: row.map((text) => ({ content: [{ text }] })), + })), + }, + }); + const table = imported.find((block) => block.type === "table")!; + expect(table.content.rows[0].cells[0]).toMatchObject({ + content: [{ styles: { bold: true } }], + }); + expect(table.content.rows[0].cells[1]).toMatchObject({ + content: [{ styles: { bold: true } }], }); - expect(table?.content.rows[1].cells).toHaveLength(1); - expect(table?.content.rows[1].cells[0]).toMatchObject({ - content: [{ type: "text", text: "Bottom" }], + expect(table.content.rows[1].cells[0]).toMatchObject({ + content: [{ styles: { italic: true } }], }); + editor.pasteHTML(html); + expect(editor.document[0]).toMatchObject({ + content: imported[0].content, + }); + expect( + editor.tryParseHTMLToBlocks(editor.blocksToFullHTML(imported))[0], + ).toMatchObject({ content: { ...headers, rows: table.content.rows } }); }, ); - it.each([ - ["0", [120, 200]], - ["1", [120, 200]], - ["2", [120, 160, 200]], - ])("keeps column widths aligned with colspan %j", (span, columnWidths) => { - editor = BlockNoteEditor.create(); - const imported = editor.tryParseHTMLToBlocks( - `<${tag} colspan="${span}" colwidth="120,160">a<${tag} colwidth="200">b
`, - ); - expect(imported[0]).toMatchObject({ - type: "table", - content: { columnWidths }, + it("does not limit programmatically created table headers", () => { + editor = BlockNoteEditor.create({ + initialContent: [ + { + type: "table", + content: { + type: "tableContent", + headerRows: 2, + headerCols: 2, + rows: [ + { cells: ["a", "b", "c"] }, + { cells: ["d", "e", "f"] }, + { cells: ["g", "h", "i"] }, + ], + }, + }, + ], + }); + expect(editor.document[0]).toMatchObject({ + content: { headerRows: 2, headerCols: 2 }, }); }); }); From af4715e4f9c230b47d4aa4a5dc80bad4364bc7d2 Mon Sep 17 00:00:00 2001 From: Nick the Sick Date: Thu, 12 Nov 2026 13:53:24 +0100 Subject: [PATCH 4/4] docs(core): document HTML import normalization --- packages/core/src/api/parsers/html/parseHTML.ts | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/packages/core/src/api/parsers/html/parseHTML.ts b/packages/core/src/api/parsers/html/parseHTML.ts index 998eece3a0..cfe1a49ba3 100644 --- a/packages/core/src/api/parsers/html/parseHTML.ts +++ b/packages/core/src/api/parsers/html/parseHTML.ts @@ -41,6 +41,10 @@ function stripEmptyBlockPlaceholder(content: any[]): any[] { return stripped; } +/** + * Recursively removes export placeholders and limits imported table headers to + * the first row and column, mutating the parsed blocks in place. + */ function normalizeImportedBlockContent(blocks: Block[]) { for (const block of blocks) { if (Array.isArray(block.content)) { @@ -61,6 +65,10 @@ function normalizeImportedBlockContent(blocks: Block[]) { } } +/** + * Parses HTML into BlockNote blocks using the supplied schema, repairing table + * structure before block conversion and normalizing imported content afterward. + */ export function HTMLToBlocks< BSchema extends BlockSchema, I extends InlineContentSchema,