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
Original file line number Diff line number Diff line change
Expand Up @@ -565,7 +565,7 @@
<wp:inline distT="0" distB="0" distL="0" distR="0">
<wp:extent cx="1905000" cy="1847620"/>
<wp:effectExtent t="0" r="0" b="0" l="0"/>
<wp:docPr id="2" name="" descr="" title=""/>
<wp:docPr id="2" name=""/>
<wp:cNvGraphicFramePr>
<a:graphicFrameLocks xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" noChangeAspect="1"/>
</wp:cNvGraphicFramePr>
Expand Down
62 changes: 32 additions & 30 deletions packages/xl-docx-exporter/src/docx/defaultSchema/blocks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 & {
Expand Down Expand Up @@ -103,10 +108,7 @@ export const docxBlockMappingForDefaultSchema: BlockMapping<
BSchema,
any,
any,
| Promise<Paragraph[] | Paragraph | DocxTable>
| Paragraph[]
| Paragraph
| DocxTable,
DOCXBlockResult,
ParagraphChild
> = {
paragraph: (block, exporter) => {
Expand All @@ -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: {
Expand All @@ -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: {
Expand Down Expand Up @@ -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: {
Expand All @@ -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: {
Expand All @@ -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,
});
}),
}),
],
});
Expand Down
208 changes: 207 additions & 1 deletion packages/xl-docx-exporter/src/docx/docxExporter.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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(/<w:p[ >][\s\S]*?<\/w:p>/g) ?? [];

expect(
paragraphs.map((paragraph) => ({
text: [...paragraph.matchAll(/<w:t(?: [^>]*)?>(.*?)<\/w:t>/g)]
.map((match) => match[1])
.join(""),
tabs: (paragraph.match(/<w:tab\/>/g) ?? []).length,
numbered: paragraph.includes("<w:numPr>"),
})),
).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(/<w:p[ >][\s\S]*?<\/w:p>/g) ?? [];
expect(
paragraphs.map((paragraph) => ({
tabs: (paragraph.match(/<w:tab\/>/g) ?? []).length,
numbered: paragraph.includes("<w:numPr>"),
})),
).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(/<w:numPr>/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 },
Expand Down Expand Up @@ -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(/<wp:docPr\b[^>]*>/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"');

Expand Down
Loading
Loading