diff --git a/packages/xl-docx-exporter/src/docx/__snapshots__/basic/document.xml b/packages/xl-docx-exporter/src/docx/__snapshots__/basic/document.xml index b146762b2e..fdd91c13d4 100644 --- a/packages/xl-docx-exporter/src/docx/__snapshots__/basic/document.xml +++ b/packages/xl-docx-exporter/src/docx/__snapshots__/basic/document.xml @@ -565,7 +565,7 @@ - + diff --git a/packages/xl-docx-exporter/src/docx/defaultSchema/blocks.ts b/packages/xl-docx-exporter/src/docx/defaultSchema/blocks.ts index 109ed5efe9..6db6a2e6b0 100644 --- a/packages/xl-docx-exporter/src/docx/defaultSchema/blocks.ts +++ b/packages/xl-docx-exporter/src/docx/defaultSchema/blocks.ts @@ -25,6 +25,11 @@ import { TextRun, } from "docx"; import { clampListLevel } from "../listLevels.js"; +import { + createDOCXParagraph, + DOCXBlockResult, + docxContent, +} from "../mapping.js"; import { Table } from "../util/Table.js"; type BSchema = DefaultBlockSchema & { @@ -103,10 +108,7 @@ export const docxBlockMappingForDefaultSchema: BlockMapping< BSchema, any, any, - | Promise - | Paragraph[] - | Paragraph - | DocxTable, + DOCXBlockResult, ParagraphChild > = { paragraph: (block, exporter) => { @@ -127,7 +129,7 @@ export const docxBlockMappingForDefaultSchema: BlockMapping< }); }, numberedListItem: (block, exporter, nestingLevel, numberingInstance) => { - return new Paragraph({ + return createDOCXParagraph({ ...blockPropsToStyles(block.props, exporter.options.colors), children: exporter.transformInlineContent(block.content), numbering: { @@ -140,7 +142,7 @@ export const docxBlockMappingForDefaultSchema: BlockMapping< }); }, bulletListItem: (block, exporter, nestingLevel, numberingInstance) => { - return new Paragraph({ + return createDOCXParagraph({ ...blockPropsToStyles(block.props, exporter.options.colors), children: exporter.transformInlineContent(block.content), numbering: { @@ -235,19 +237,11 @@ export const docxBlockMappingForDefaultSchema: BlockMapping< _numberedListIndex, children, ) => { - return new TableCell({ - width: { - size: `${block.props.width * 100}%`, - type: "pct", - }, - children: (children || []).flatMap((child) => { - if (Array.isArray(child)) { - return child; - } - - return [child]; - }), - }) as any; + return { + type: "column", + width: block.props.width, + children: docxContent(children.flat(), "column"), + }; }, }, columnList: { @@ -258,6 +252,16 @@ export const docxBlockMappingForDefaultSchema: BlockMapping< _numberedListIndex, children, ) => { + const columns = children.flat().map((child) => { + if ( + child instanceof Paragraph || + child instanceof DocxTable || + child.type !== "column" + ) { + throw new Error("DOCX columnList children must be columns."); + } + return child; + }); return new DocxTable({ layout: "autofit", borders: { @@ -270,17 +274,15 @@ export const docxBlockMappingForDefaultSchema: BlockMapping< }, rows: [ new TableRow({ - children: (children as unknown as TableCell[]).map( - (cell, _index, children) => { - return new TableCell({ - width: { - size: `${(parseFloat(`${cell.options.width?.size || "100%"}`) / (children.length * 100)) * 100}%`, - type: "pct", - }, - children: cell.options.children, - }); - }, - ), + children: columns.map((column) => { + return new TableCell({ + width: { + size: `${(column.width * 100) / columns.length}%`, + type: "pct", + }, + children: column.children, + }); + }), }), ], }); diff --git a/packages/xl-docx-exporter/src/docx/docxExporter.test.ts b/packages/xl-docx-exporter/src/docx/docxExporter.test.ts index 8cfe741b51..c67efc8bc2 100644 --- a/packages/xl-docx-exporter/src/docx/docxExporter.test.ts +++ b/packages/xl-docx-exporter/src/docx/docxExporter.test.ts @@ -13,11 +13,12 @@ import { TextWriter, ZipReader, } from "@zip.js/zip.js"; -import { Packer, Paragraph, TextRun } from "docx"; +import { Packer, Paragraph, Table, TableCell, TableRow, TextRun } from "docx"; import { describe, expect, it } from "vite-plus/test"; import xmlFormat from "xml-formatter"; import { docxDefaultSchemaMappings } from "./defaultSchema/index.js"; import { DOCXExporter } from "./docxExporter.js"; +import { createDOCXParagraph } from "./mapping.js"; import { ColumnBlock, ColumnListBlock } from "@blocknote/xl-multi-column"; import { partialBlocksToBlocksForTesting } from "@shared/formatConversionTestUtil.js"; import { testResolveFileUrl } from "@shared/util/testFileResolver.js"; @@ -138,6 +139,206 @@ describe("exporter", () => { }, ); + it("should indent nested paragraphs but not list items", async () => { + const schema = BlockNoteSchema.create(); + const exporter = new DOCXExporter(schema, docxDefaultSchemaMappings, { + resolveFileUrl: testResolveFileUrl, + }); + const doc = await exporter.toDocxJsDocument( + partialBlocksToBlocksForTesting(schema, [ + { + type: "paragraph", + content: "root", + children: [ + { + type: "paragraph", + content: "child", + children: [{ type: "paragraph", content: "grandchild" }], + }, + { + type: "numberedListItem", + content: "numbered", + children: [ + { + type: "bulletListItem", + content: "bullet", + children: [{ type: "paragraph", content: "under-list" }], + }, + ], + }, + ], + }, + ]), + { sectionOptions: {}, documentOptions: {}, locale: "en-US" }, + ); + const zip = new ZipReader(new BlobReader(await Packer.toBlob(doc))); + const xml = await getZIPEntryContent( + await zip.getEntries(), + "word/document.xml", + ); + const paragraphs = xml.match(/][\s\S]*?<\/w:p>/g) ?? []; + + expect( + paragraphs.map((paragraph) => ({ + text: [...paragraph.matchAll(/]*)?>(.*?)<\/w:t>/g)] + .map((match) => match[1]) + .join(""), + tabs: (paragraph.match(//g) ?? []).length, + numbered: paragraph.includes(""), + })), + ).toEqual([ + { text: "root", tabs: 0, numbered: false }, + { text: "child", tabs: 1, numbered: false }, + { text: "grandchild", tabs: 2, numbered: false }, + { text: "numbered", tabs: 0, numbered: true }, + { text: "bullet", tabs: 0, numbered: true }, + { text: "under-list", tabs: 3, numbered: false }, + ]); + }); + + it("should use mapping-declared indentation instead of block names", async () => { + const schema = BlockNoteSchema.create(); + const exporter = new DOCXExporter(schema, { + ...docxDefaultSchemaMappings, + blockMapping: { + ...docxDefaultSchemaMappings.blockMapping, + paragraph: (block, exporter, level) => + createDOCXParagraph({ + children: exporter.transformInlineContent(block.content), + numbering: { reference: "blocknote-numbered-list", level }, + }), + // Replacing a built-in list mapping with a plain paragraph must not + // silently retain the built-in mapping's indentation behavior. + numberedListItem: () => new Paragraph("plain replacement"), + // Raw custom paragraphs still work, but must opt into the helper to + // declare numbering indentation without relying on private docx fields. + heading: () => + new Paragraph({ + text: "raw numbered paragraph", + numbering: { reference: "blocknote-numbered-list", level: 2 }, + }), + }, + }); + const doc = await exporter.toDocxJsDocument( + partialBlocksToBlocksForTesting(schema, [ + { + type: "numberedListItem", + children: [ + { + type: "paragraph", + content: "custom numbered paragraph", + children: [{ type: "numberedListItem" }, { type: "heading" }], + }, + ], + }, + ]), + ); + const zip = new ZipReader(new BlobReader(await Packer.toBlob(doc))); + const xml = await getZIPEntryContent( + await zip.getEntries(), + "word/document.xml", + ); + const paragraphs = xml.match(/][\s\S]*?<\/w:p>/g) ?? []; + expect( + paragraphs.map((paragraph) => ({ + tabs: (paragraph.match(//g) ?? []).length, + numbered: paragraph.includes(""), + })), + ).toEqual([ + { tabs: 0, numbered: false }, + { tabs: 0, numbered: true }, + { tabs: 2, numbered: false }, + { tabs: 2, numbered: true }, + ]); + }); + + it("should pass real paragraphs to custom child-placement mappings", async () => { + const schema = BlockNoteSchema.create(); + const exporter = new DOCXExporter(schema, { + ...docxDefaultSchemaMappings, + blockMapping: { + ...docxDefaultSchemaMappings.blockMapping, + paragraph: { + withChildren: (_block, _exporter, _level, _index, children) => + new Table({ + rows: [ + new TableRow({ + children: [ + new TableCell({ + children: children.flat().map((child) => { + expect(child).toBeInstanceOf(Paragraph); + if (!(child instanceof Paragraph)) { + throw new Error("Expected a docx paragraph"); + } + return child; + }), + }), + ], + }), + ], + }), + }, + }, + }); + const doc = await exporter.toDocxJsDocument( + partialBlocksToBlocksForTesting(schema, [ + { + type: "paragraph", + children: [ + { type: "bulletListItem", content: "bullet" }, + { type: "numberedListItem", content: "numbered" }, + ], + }, + ]), + ); + const zip = new ZipReader(new BlobReader(await Packer.toBlob(doc))); + const xml = await getZIPEntryContent( + await zip.getEntries(), + "word/document.xml", + ); + expect((xml.match(//g) ?? []).length).toBe(2); + }); + + it.each(["document", "columnList", "column"] as const)( + "should reject invalid layout results in a %s", + async (context) => { + const schema = BlockNoteSchema.create({ + blockSpecs: { + ...defaultBlockSpecs, + column: ColumnBlock, + columnList: ColumnListBlock, + }, + }); + const exporter = new DOCXExporter(schema, docxDefaultSchemaMappings); + const blocks: PartialBlock< + typeof schema.blockSchema, + typeof schema.inlineContentSchema, + typeof schema.styleSchema + >[] = + context === "document" + ? [{ type: "column", children: [{ type: "paragraph" }] }] + : context === "columnList" + ? [{ type: "columnList", children: [{ type: "paragraph" }] }] + : [ + { + type: "columnList", + children: [ + { type: "column", children: [{ type: "column" }] }, + ], + }, + ]; + const error = + context === "columnList" + ? "DOCX columnList children must be columns" + : `DOCX ${context} cannot contain a column directly`; + await expect( + exporter.transformBlocks( + partialBlocksToBlocksForTesting(schema, blocks), + ), + ).rejects.toThrow(error); + }, + ); + it( "should clamp list nesting deeper than DOCX supports", { timeout: 10000 }, @@ -425,6 +626,11 @@ function prettify(sourceXml: string) { // Image relationship IDs are internal to docx and can change between releases. ret = ret.replace(/r:embed="[a-zA-Z0-9_-]*"/g, 'r:embed="FAKE-ID"'); + // docx 9.13 omits empty optional drawing metadata; it means the same as "". + ret = ret.replace(/]*>/g, (tag) => + tag.replace(/ (?:descr|title)=""/g, ""), + ); + // replace random ids like Id="rIdll8_ocxarmodcwrnsavfb" ret = ret.replace(/ Id="[a-zA-Z0-9_-]*"/g, ' Id="FAKE-ID"'); diff --git a/packages/xl-docx-exporter/src/docx/docxExporter.ts b/packages/xl-docx-exporter/src/docx/docxExporter.ts index 98512d0fdb..d5b6537d98 100644 --- a/packages/xl-docx-exporter/src/docx/docxExporter.ts +++ b/packages/xl-docx-exporter/src/docx/docxExporter.ts @@ -26,6 +26,12 @@ import { Exporter, ExporterOptions } from "@blocknote/core"; import { corsProxyResolveFileUrl } from "@shared/api/corsProxy.js"; import { loadFileBuffer } from "@shared/util/fileUtil.js"; import { DOCX_LIST_LEVEL_COUNT } from "./listLevels.js"; +import { + DOCXBlock, + DOCXBlockResult, + docxContent, + isTabIndentedParagraph, +} from "./mapping.js"; // get constructor arg type from Document type DocumentOptions = Partial[0]>; @@ -47,7 +53,7 @@ export class DOCXExporter< B, I, S, - Promise | Paragraph[] | Paragraph | Table, + DOCXBlockResult, ParagraphChild, IRunPropertiesOptions, TextRun @@ -65,10 +71,7 @@ export class DOCXExporter< NoInfer, NoInfer, NoInfer, - | Promise - | Paragraph[] - | Paragraph - | Table, + DOCXBlockResult, ParagraphChild, IRunPropertiesOptions, TextRun @@ -130,7 +133,17 @@ export class DOCXExporter< blocks: Block[], nestingLevel = 0, ): Promise> { - const ret: Array = []; + return docxContent( + await this.transformBlockResults(blocks, nestingLevel), + "document", + ); + } + + private async transformBlockResults( + blocks: Block[], + nestingLevel: number, + ): Promise { + const ret: DOCXBlock[] = []; // The top-level call starts a fresh document, so restart instance numbering. if (nestingLevel === 0) { @@ -156,23 +169,23 @@ export class DOCXExporter< runListType = undefined; } - let children = await this.transformBlocks(b.children, nestingLevel + 1); + const children = await this.transformBlockResults( + b.children, + nestingLevel + 1, + ); - if (!this.placesChildren(b)) { - children = children.map((c, _i) => { + const placesChildren = this.placesChildren(b); + if (!placesChildren) { + for (const child of children) { // NOTE: nested tables not supported (we can't insert the new Tab before a table) - if ( - c instanceof Paragraph && - !(c as any).properties.numberingReferences.length - ) { - c.addRunToFront( + if (isTabIndentedParagraph(child)) { + child.addRunToFront( new TextRun({ children: [new Tab()], }), ); } - return c; - }); + } } // The `numberedListIndex` slot carries the numbering instance for the docx @@ -183,10 +196,11 @@ export class DOCXExporter< numberingInstance, children, ); - ret.push(...(Array.isArray(self) ? self : [self])); + const mapped = Array.isArray(self) ? self : [self]; + ret.push(...mapped); // A layout block's mapping is handed its children and places them itself, // so they must not be appended after it as well. - if (!this.placesChildren(b)) { + if (!placesChildren) { ret.push(...children); } } diff --git a/packages/xl-docx-exporter/src/docx/index.ts b/packages/xl-docx-exporter/src/docx/index.ts index dc7791a300..aa57d877d6 100644 --- a/packages/xl-docx-exporter/src/docx/index.ts +++ b/packages/xl-docx-exporter/src/docx/index.ts @@ -1,2 +1,4 @@ export * from "./defaultSchema/index.js"; export * from "./docxExporter.js"; +export { createDOCXParagraph } from "./mapping.js"; +export type { DOCXBlock, DOCXBlockResult, DOCXColumn } from "./mapping.js"; diff --git a/packages/xl-docx-exporter/src/docx/mapping.ts b/packages/xl-docx-exporter/src/docx/mapping.ts new file mode 100644 index 0000000000..b8013afd1d --- /dev/null +++ b/packages/xl-docx-exporter/src/docx/mapping.ts @@ -0,0 +1,50 @@ +import { IParagraphOptions, Paragraph, Table } from "docx"; + +const numberedParagraphs = new WeakSet(); + +/** Intermediate layout content. A columnList consumes these; a document cannot. */ +export type DOCXColumn = { + type: "column"; + width: number; + children: Array; +}; + +// Plain docx objects remain supported for existing custom mappings. Use +// createDOCXParagraph for paragraphs with numbering/bullets of their own. +export type DOCXBlock = Paragraph | Table | DOCXColumn; +export type DOCXBlockResult = DOCXBlock | DOCXBlock[]; + +/** + * Creates a paragraph with explicit nesting behavior. Numbered/bulleted + * paragraphs use docx's numbering indentation; others receive nesting tabs. + * Custom numbered/bulleted mappings must use this instead of new Paragraph to + * avoid extra nesting tabs. Raw Paragraph instances receive nesting tabs because + * docx does not expose their numbering settings through a public getter. + * Returns an ordinary docx Paragraph, including when passed to withChildren. + */ +export function createDOCXParagraph(options: IParagraphOptions): Paragraph { + const paragraph = new Paragraph(options); + if (options.bullet || options.numbering) { + numberedParagraphs.add(paragraph); + } + return paragraph; +} + +export function isTabIndentedParagraph(block: DOCXBlock): block is Paragraph { + return block instanceof Paragraph && !numberedParagraphs.has(block); +} + +/** Validate mapping results at a document or table-cell boundary. */ +export function docxContent( + blocks: DOCXBlock[], + context: string, +): Array { + return blocks.map((block) => { + if (block instanceof Paragraph || block instanceof Table) { + return block; + } + throw new Error( + `DOCX ${context} cannot contain a column directly; place columns inside a columnList.`, + ); + }); +}