Preserve QWord paragraph spacing in DOCX
This commit is contained in:
@@ -465,6 +465,18 @@ describe("wordOffice helpers", () => {
|
||||
]);
|
||||
});
|
||||
|
||||
it("сохраняет HTML-интервалы абзацев и заголовков для DOCX", () => {
|
||||
const blocks = htmlToWordBlocks(`
|
||||
<h2 style="margin-top: 6pt; margin-bottom: 10pt;">Title spacing</h2>
|
||||
<p style="margin-top: 12pt; margin-bottom: 18pt;">Paragraph spacing</p>
|
||||
`);
|
||||
|
||||
expect(blocks).toEqual([
|
||||
{ type: "heading", level: 2, text: "Title spacing", runs: [{ text: "Title spacing" }], spacing: { before: 120, after: 200 } },
|
||||
{ type: "paragraph", text: "Paragraph spacing", runs: [{ text: "Paragraph spacing" }], spacing: { before: 240, after: 360 } }
|
||||
]);
|
||||
});
|
||||
|
||||
it("записывает отступы абзацев в w:ind экспортированного DOCX", async () => {
|
||||
const blob = await exportDocxBlob(
|
||||
"Indent.docx",
|
||||
@@ -477,6 +489,18 @@ describe("wordOffice helpers", () => {
|
||||
expect(documentXml).toMatch(/<w:ind\b(?=[^>]*w:left="720")(?=[^>]*w:hanging="240")[^>]*\/>/);
|
||||
});
|
||||
|
||||
it("записывает интервалы абзацев в w:spacing экспортированного DOCX", async () => {
|
||||
const blob = await exportDocxBlob(
|
||||
"Spacing.docx",
|
||||
'<h2 style="margin-top: 6pt; margin-bottom: 10pt;">Title spacing</h2><p style="margin-top: 12pt; margin-bottom: 18pt;">Paragraph spacing</p>'
|
||||
);
|
||||
const zip = await JSZip.loadAsync(await blob.arrayBuffer());
|
||||
const documentXml = await zip.file("word/document.xml")?.async("string");
|
||||
|
||||
expect(documentXml).toMatch(/<w:spacing\b(?=[^>]*w:before="120")(?=[^>]*w:after="200")[^>]*\/>/);
|
||||
expect(documentXml).toMatch(/<w:spacing\b(?=[^>]*w:before="240")(?=[^>]*w:after="360")[^>]*\/>/);
|
||||
});
|
||||
|
||||
it("нормализует HTML после импорта DOCX", () => {
|
||||
expect(normalizeImportedDocxHtml(" <p>Готово</p>\n")).toBe("<p>Готово</p>");
|
||||
});
|
||||
|
||||
+74
-6
@@ -41,11 +41,34 @@ export interface WordParagraphIndent {
|
||||
hanging?: number;
|
||||
}
|
||||
|
||||
export interface WordParagraphSpacing {
|
||||
before?: number;
|
||||
after?: number;
|
||||
}
|
||||
|
||||
export type WordHeadingLevel = 1 | 2 | 3 | 4 | 5 | 6;
|
||||
|
||||
export type WordBlock =
|
||||
| { type: "heading"; level: WordHeadingLevel; text: string; runs: WordInlineRun[]; alignment?: WordParagraphAlignment; indent?: WordParagraphIndent; bookmark?: string }
|
||||
| { type: "paragraph"; text: string; runs: WordInlineRun[]; alignment?: WordParagraphAlignment; indent?: WordParagraphIndent; bookmark?: string; quote?: boolean }
|
||||
| {
|
||||
type: "heading";
|
||||
level: WordHeadingLevel;
|
||||
text: string;
|
||||
runs: WordInlineRun[];
|
||||
alignment?: WordParagraphAlignment;
|
||||
indent?: WordParagraphIndent;
|
||||
spacing?: WordParagraphSpacing;
|
||||
bookmark?: string;
|
||||
}
|
||||
| {
|
||||
type: "paragraph";
|
||||
text: string;
|
||||
runs: WordInlineRun[];
|
||||
alignment?: WordParagraphAlignment;
|
||||
indent?: WordParagraphIndent;
|
||||
spacing?: WordParagraphSpacing;
|
||||
bookmark?: string;
|
||||
quote?: boolean;
|
||||
}
|
||||
| { type: "list"; ordered: boolean; items: WordListItem[] }
|
||||
| { type: "table"; rows: string[][] }
|
||||
| WordImageBlock;
|
||||
@@ -104,6 +127,8 @@ type DocxModule = {
|
||||
ImageRun?: new (options: Record<string, unknown>) => unknown;
|
||||
};
|
||||
|
||||
const defaultParagraphSpacingAfterTwips = 160;
|
||||
|
||||
type InlineFormat = Omit<WordInlineRun, "text">;
|
||||
type InlineSegment = { type: "runs"; runs: WordInlineRun[] } | { type: "image"; image: WordImageBlock };
|
||||
type DocxInlineRecord = { run: unknown; text: string; href?: string };
|
||||
@@ -251,6 +276,7 @@ export function htmlToWordBlocks(html: string): WordBlock[] {
|
||||
const text = inlineRunsText(runs);
|
||||
const alignment = paragraphAlignmentFromElement(node);
|
||||
const indent = paragraphIndentFromElement(node);
|
||||
const spacing = paragraphSpacingFromElement(node);
|
||||
const bookmark = bookmarkFromElement(node);
|
||||
if (text) {
|
||||
blocks.push({
|
||||
@@ -260,6 +286,7 @@ export function htmlToWordBlocks(html: string): WordBlock[] {
|
||||
runs,
|
||||
...(alignment ? { alignment } : {}),
|
||||
...(indent ? { indent } : {}),
|
||||
...(spacing ? { spacing } : {}),
|
||||
...(bookmark ? { bookmark } : {})
|
||||
});
|
||||
}
|
||||
@@ -308,7 +335,7 @@ function wordBlockToDocxChildren(block: WordBlock, docx: DocxModule) {
|
||||
return [
|
||||
new docx.Paragraph({
|
||||
heading: docxHeadingLevel(block.level, docx),
|
||||
spacing: { after: 160 },
|
||||
spacing: docxParagraphSpacing(block.spacing, defaultParagraphSpacingAfterTwips),
|
||||
...docxAlignmentOption(block.alignment, docx),
|
||||
...docxIndentOption(block.indent),
|
||||
children: bookmarkDocxChildren(block.bookmark, children, docx)
|
||||
@@ -321,7 +348,7 @@ function wordBlockToDocxChildren(block: WordBlock, docx: DocxModule) {
|
||||
return [
|
||||
new docx.Paragraph({
|
||||
...(block.quote ? { style: "Quote" } : {}),
|
||||
spacing: { after: 160 },
|
||||
spacing: docxParagraphSpacing(block.spacing, defaultParagraphSpacingAfterTwips),
|
||||
...docxAlignmentOption(block.alignment, docx),
|
||||
...docxIndentOption(block.indent),
|
||||
children: bookmarkDocxChildren(block.bookmark, children, docx)
|
||||
@@ -525,6 +552,23 @@ function docxIndentOption(indent: WordParagraphIndent | undefined) {
|
||||
return Object.keys(normalized).length > 0 ? { indent: normalized } : {};
|
||||
}
|
||||
|
||||
function docxParagraphSpacing(spacing: WordParagraphSpacing | undefined, defaultAfter: number) {
|
||||
const normalized = normalizedParagraphSpacing(spacing);
|
||||
return {
|
||||
after: normalized.after ?? defaultAfter,
|
||||
...(normalized.before ? { before: normalized.before } : {})
|
||||
};
|
||||
}
|
||||
|
||||
function normalizedParagraphSpacing(spacing: WordParagraphSpacing | undefined) {
|
||||
const before = normalizedTwips(spacing?.before);
|
||||
const after = normalizedTwips(spacing?.after);
|
||||
return {
|
||||
...(before ? { before } : {}),
|
||||
...(after !== undefined ? { after } : {})
|
||||
};
|
||||
}
|
||||
|
||||
function normalizedParagraphIndent(indent: WordParagraphIndent | undefined) {
|
||||
const left = normalizedTwips(indent?.left);
|
||||
const firstLine = normalizedTwips(indent?.firstLine);
|
||||
@@ -602,6 +646,7 @@ function paragraphElementToBlocks(element: Element, options: { quote?: boolean }
|
||||
const segments = collectInlineSegments(Array.from(element.childNodes), {});
|
||||
const alignment = paragraphAlignmentFromElement(element);
|
||||
const indent = paragraphIndentFromElement(element);
|
||||
const spacing = paragraphSpacingFromElement(element);
|
||||
const bookmark = bookmarkFromElement(element);
|
||||
const blocks: WordBlock[] = [];
|
||||
let pendingRuns: WordInlineRun[] = [];
|
||||
@@ -618,6 +663,7 @@ function paragraphElementToBlocks(element: Element, options: { quote?: boolean }
|
||||
runs,
|
||||
...(alignment ? { alignment } : {}),
|
||||
...(indent ? { indent } : {}),
|
||||
...(spacing ? { spacing } : {}),
|
||||
...(bookmark && !bookmarkApplied ? { bookmark } : {}),
|
||||
...(options.quote ? { quote: true } : {})
|
||||
});
|
||||
@@ -666,6 +712,17 @@ function paragraphIndentFromElement(element: Element): WordParagraphIndent | und
|
||||
return Object.keys(indent).length > 0 ? indent : undefined;
|
||||
}
|
||||
|
||||
function paragraphSpacingFromElement(element: Element): WordParagraphSpacing | undefined {
|
||||
const style = element.getAttribute("style") ?? "";
|
||||
const before = cssTwipsValue(style, "margin-top");
|
||||
const after = cssTwipsValue(style, "margin-bottom");
|
||||
const spacing = {
|
||||
...(before && before > 0 ? { before } : {}),
|
||||
...(after && after > 0 ? { after } : {})
|
||||
};
|
||||
return Object.keys(spacing).length > 0 ? spacing : undefined;
|
||||
}
|
||||
|
||||
function bookmarkFromElement(element: Element) {
|
||||
return normalizedDocxAnchor(element.getAttribute("id") || element.getAttribute("name"));
|
||||
}
|
||||
@@ -674,7 +731,7 @@ function cssTextAlignValue(style: string) {
|
||||
return /(?:^|;)\s*text-align\s*:\s*([^;]+)/i.exec(style)?.[1] ?? "";
|
||||
}
|
||||
|
||||
function cssTwipsValue(style: string, property: "margin-left" | "text-indent") {
|
||||
function cssTwipsValue(style: string, property: "margin-left" | "margin-top" | "margin-bottom" | "text-indent") {
|
||||
const raw = new RegExp(`(?:^|;)\\s*${property}\\s*:\\s*([^;]+)`, "i").exec(style)?.[1]?.trim().toLowerCase() ?? "";
|
||||
return cssLengthToTwips(raw);
|
||||
}
|
||||
@@ -1069,7 +1126,8 @@ function docxParagraphStyleAttribute(properties: XmlRecord) {
|
||||
const htmlAlignment = alignment === "both" ? "justify" : alignment;
|
||||
const styles = [
|
||||
["left", "center", "right", "justify"].includes(htmlAlignment) ? `text-align: ${htmlAlignment};` : "",
|
||||
...docxParagraphIndentStyles(properties)
|
||||
...docxParagraphIndentStyles(properties),
|
||||
...docxParagraphSpacingStyles(properties)
|
||||
].filter(Boolean);
|
||||
return styles.join(" ");
|
||||
}
|
||||
@@ -1086,6 +1144,16 @@ function docxParagraphIndentStyles(properties: XmlRecord) {
|
||||
].filter(Boolean);
|
||||
}
|
||||
|
||||
function docxParagraphSpacingStyles(properties: XmlRecord) {
|
||||
const spacing = childRecord(properties, "w:spacing");
|
||||
const before = docxTwipsAttribute(spacing, ["w:before"]);
|
||||
const after = docxTwipsAttribute(spacing, ["w:after"]);
|
||||
return [
|
||||
before ? `margin-top: ${formatPointSize(before / 20)}pt;` : "",
|
||||
after && after !== defaultParagraphSpacingAfterTwips ? `margin-bottom: ${formatPointSize(after / 20)}pt;` : ""
|
||||
].filter(Boolean);
|
||||
}
|
||||
|
||||
function docxParagraphListInfo(properties: XmlRecord, numberingDefinitions: DocxNumberingDefinitions): DocxListInfo | undefined {
|
||||
const numbering = childRecord(properties, "w:numPr");
|
||||
const numId = docxAttribute(childRecord(numbering, "w:numId"), "w:val");
|
||||
|
||||
@@ -363,4 +363,22 @@ describe("wordOffice DOCX import", () => {
|
||||
{ type: "paragraph", text: "Hanging", runs: [{ text: "Hanging" }], indent: { left: 720, hanging: 240 } }
|
||||
]);
|
||||
});
|
||||
|
||||
it("imports DOCX paragraph spacing from OOXML", async () => {
|
||||
const blob = await exportDocxBlob(
|
||||
"Spacing.docx",
|
||||
'<h2 style="margin-top: 6pt; margin-bottom: 10pt;">Title spacing</h2><p style="margin-top: 12pt; margin-bottom: 18pt;">Paragraph spacing</p>'
|
||||
);
|
||||
const file = new File([blob], "Spacing.docx", {
|
||||
type: "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
|
||||
});
|
||||
const imported = await importDocxFile(file);
|
||||
|
||||
expect(imported.html).toContain("margin-top: 6pt; margin-bottom: 10pt;");
|
||||
expect(imported.html).toContain("margin-top: 12pt; margin-bottom: 18pt;");
|
||||
expect(htmlToWordBlocks(imported.html)).toEqual([
|
||||
{ type: "heading", level: 2, text: "Title spacing", runs: [{ text: "Title spacing" }], spacing: { before: 120, after: 200 } },
|
||||
{ type: "paragraph", text: "Paragraph spacing", runs: [{ text: "Paragraph spacing" }], spacing: { before: 240, after: 360 } }
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user