From 3098e4367f28d6d6e88384461b0cc98986e0b672 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=9A=D1=83=D1=80=D0=BD=D0=B0=D1=82=20=D0=90=D0=BD=D0=B4?= =?UTF-8?q?=D1=80=D0=B5=D0=B9?= Date: Mon, 1 Jun 2026 12:16:52 +0300 Subject: [PATCH] Preserve QWord line breaks in DOCX --- README.md | 4 +- src/io/wordOffice.test.ts | 21 ++++++ src/io/wordOffice.ts | 115 +++++++++++++++++++++++++------- src/io/wordOfficeImport.test.ts | 17 +++++ 4 files changed, 131 insertions(+), 26 deletions(-) diff --git a/README.md b/README.md index d7d6ca2..7accb44 100644 --- a/README.md +++ b/README.md @@ -31,7 +31,7 @@ npm run build ## Поддержка форматов -- QWord открывает `.docx` и сохраняет `.docx`; при импорте базовых DOCX-абзацев читает выравнивание, внешние гиперссылки, простые таблицы, базовые растровые изображения, явные цвета текста, подсветку, размер и семейство шрифта из OOXML, а при экспорте DOCX сохраняются заголовки, абзацы, выравнивание абзацев, списки, простые таблицы, внешние гиперссылки, базовые растровые изображения и базовое inline-форматирование текста: полужирный, курсив, подчеркивание, зачеркивание, цвет текста, подсветка, размер и семейство шрифта. +- QWord открывает `.docx` и сохраняет `.docx`; при импорте базовых DOCX-абзацев читает выравнивание, переносы строк, внешние гиперссылки, простые таблицы, базовые растровые изображения, явные цвета текста, подсветку, размер и семейство шрифта из OOXML, а при экспорте DOCX сохраняются заголовки, абзацы, переносы строк, выравнивание абзацев, списки, простые таблицы, внешние гиперссылки, базовые растровые изображения и базовое inline-форматирование текста: полужирный, курсив, подчеркивание, зачеркивание, цвет текста, подсветка, размер и семейство шрифта. - QExcell открывает `.xlsx` и сохраняет `.xlsx`; сетка расширяется по фактически заполненным ячейкам, поддерживает несколько листов, формулы за пределами стартового диапазона A-H, shared formulas XLSX с относительными ссылками, базовые merged cells, внешние и внутренние гиперссылки ячеек, базовые диаграммы листа и базовое форматирование ячеек: полужирный, курсив, подчеркивание, зачеркивание, размер и семейство шрифта, прямые RGB/theme/indexed цвета текста с учетом `xl/theme/theme1.xml`, заливку, горизонтальное и вертикальное выравнивание, перенос текста, границы и цвет границ ячеек, числовые форматы XLSX для дат, процентов, денежных и дробных значений. - QPowerPoint открывает `.pptx` и сохраняет `.pptx`; импорт учитывает порядок слайдов из `presentation.xml`, переносы абзацев внутри текстовых блоков и заметки докладчика через relationships слайда, сохраняет заметки докладчика, базовые растровые изображения слайдов, пользовательский цвет фона слайда, а также цвет, размер и семейство шрифта текста заголовка/подзаголовка. - QOutlook открывает `.eml` и одиночные сообщения Outlook `.msg`, сохраняет письма в `.eml`; импорт EML поддерживает простые текстовые письма, `multipart/alternative`, `multipart/mixed`, `multipart/related`, `text/plain`, fallback из `text/html` в читаемый текст, base64, quoted-printable, MIME encoded-word заголовки UTF-8/windows-1251, MIME-вложения и inline-вложения с `Content-ID`, `To`, `Cc` и `Bcc`. Импорт MSG читает тему, отправителя, получателей `To/Cc/Bcc`, текст/HTML body и вложения, если эти поля доступны в MSG-файле. Новые письма можно адресовать через `To/Cc/Bcc` и сохранять в EML вместе с добавленными файлами. `.pst` и экспорт в `.msg` пока не реализованы. @@ -46,7 +46,7 @@ Desktop-меню поддерживает системные команды дл - `Ctrl/Cmd+Shift+E`: экспортировать текущую рабочую область в PDF. - `Ctrl/Cmd+P`: печать текущей рабочей области. -Импорт и экспорт реализуют базовую совместимость с Office Open XML, EML и чтением MSG: текст, базовое inline-форматирование, явные `w:color`, `w:shd`, `w:highlight`, `w:sz`, `w:rFonts` и `w:strike` для цвета/подсветки/размера/семейства/зачеркивания текста DOCX, выравнивание абзацев DOCX, внешние гиперссылки DOCX, внешние и внутренние гиперссылки XLSX, базовые растровые изображения DOCX/PPTX, простые таблицы, несколько листов XLSX, ячейки, формулы, shared formulas XLSX с относительными ссылками, базовые merged cells, базовые стили, RGB/theme/indexed цвета XLSX с учетом `xl/theme/theme1.xml`, размеры и семейства шрифта, зачеркивание ячеек, горизонтальное и вертикальное выравнивание, перенос текста, границы и цвет границ ячеек, числовые форматы и простые bar/line/pie диаграммы ячеек XLSX, текстовые слайды PPTX с переносами абзацев при импорте, пользовательский фон слайдов PPTX, цвет, размер и семейство шрифта текста заголовка/подзаголовка PPTX, импорт и экспорт заметок докладчика, адресацию `To/Cc/Bcc`, MIME encoded-word заголовки UTF-8/windows-1251, MIME-вложения EML, inline-вложения EML с `Content-ID` и базовые поля одиночных MSG-писем. Сложные стили, макросы, сложные диаграммы, сложное позиционирование и обтекание изображений, PST, экспорт MSG и полная fidelity документов Microsoft Office в текущем инкременте не заявлены. +Импорт и экспорт реализуют базовую совместимость с Office Open XML, EML и чтением MSG: текст, базовое inline-форматирование, явные `w:br`, `w:color`, `w:shd`, `w:highlight`, `w:sz`, `w:rFonts` и `w:strike` для переносов строк/цвета/подсветки/размера/семейства/зачеркивания текста DOCX, выравнивание абзацев DOCX, внешние гиперссылки DOCX, внешние и внутренние гиперссылки XLSX, базовые растровые изображения DOCX/PPTX, простые таблицы, несколько листов XLSX, ячейки, формулы, shared formulas XLSX с относительными ссылками, базовые merged cells, базовые стили, RGB/theme/indexed цвета XLSX с учетом `xl/theme/theme1.xml`, размеры и семейства шрифта, зачеркивание ячеек, горизонтальное и вертикальное выравнивание, перенос текста, границы и цвет границ ячеек, числовые форматы и простые bar/line/pie диаграммы ячеек XLSX, текстовые слайды PPTX с переносами абзацев при импорте, пользовательский фон слайдов PPTX, цвет, размер и семейство шрифта текста заголовка/подзаголовка PPTX, импорт и экспорт заметок докладчика, адресацию `To/Cc/Bcc`, MIME encoded-word заголовки UTF-8/windows-1251, MIME-вложения EML, inline-вложения EML с `Content-ID` и базовые поля одиночных MSG-писем. Сложные стили, макросы, сложные диаграммы, сложное позиционирование и обтекание изображений, PST, экспорт MSG и полная fidelity документов Microsoft Office в текущем инкременте не заявлены. ## Сборка пакета diff --git a/src/io/wordOffice.test.ts b/src/io/wordOffice.test.ts index 45df595..2bcdfda 100644 --- a/src/io/wordOffice.test.ts +++ b/src/io/wordOffice.test.ts @@ -52,6 +52,18 @@ describe("wordOffice helpers", () => { ]); }); + it("сохраняет HTML-переносы строк как inline runs для DOCX", () => { + const blocks = htmlToWordBlocks("

Line 1
Line 2
Line 3

"); + + expect(blocks).toEqual([ + { + type: "paragraph", + text: "Line 1 Line 2 Line 3", + runs: [{ text: "Line 1\nLine 2\n" }, { text: "Line 3", bold: true }] + } + ]); + }); + it("сохраняет выравнивание абзацев и заголовков для DOCX", () => { const blocks = htmlToWordBlocks(`

Итоги

@@ -123,6 +135,15 @@ describe("wordOffice helpers", () => { expect(documentXml).toContain(" { + const blob = await exportDocxBlob("Переносы.docx", "

Line 1
Line 2

"); + const zip = await JSZip.loadAsync(await blob.arrayBuffer()); + const documentXml = await zip.file("word/document.xml")?.async("string"); + + expect(documentXml).toContain(""); + expect(documentXml).toMatch(/]*>Line 1<\/w:t>[\s\S]*[\s\S]*]*>Line 2<\/w:t>/); + }); + it("записывает цвет текста и подсветку в XML экспортированного DOCX", async () => { const blob = await exportDocxBlob( "Цвет.docx", diff --git a/src/io/wordOffice.ts b/src/io/wordOffice.ts index a44c07b..41e64a1 100644 --- a/src/io/wordOffice.ts +++ b/src/io/wordOffice.ts @@ -92,7 +92,7 @@ type DocxModule = { type InlineFormat = Omit; type InlineSegment = { type: "runs"; runs: WordInlineRun[] } | { type: "image"; image: WordImageBlock }; -type DocxInlineRecord = { run: unknown; href?: string }; +type DocxInlineRecord = { run: unknown; text: string; href?: string }; type DocxImageDataByRelationshipId = Record; const mammothStyleMap = [ @@ -381,20 +381,41 @@ function wordInlineRunToTextRunOption(run: WordInlineRun) { function wordInlineRunsToTextRuns(runs: WordInlineRun[], docx: DocxModule) { const normalizedRuns = runs.length > 0 ? runs : [{ text: "" }]; - return normalizedRuns.map((run) => { - const option = wordInlineRunToTextRunOption(run); + return normalizedRuns.flatMap((run) => { const href = normalizedHyperlinkTarget(run.href); if (href && docx.ExternalHyperlink) { - return new docx.ExternalHyperlink({ - link: href, - children: [new docx.TextRun({ ...option, style: "Hyperlink" })] - }); + return [ + new docx.ExternalHyperlink({ + link: href, + children: wordInlineRunToTextRunsForRun(run, docx, { style: "Hyperlink" }) + }) + ]; } - return new docx.TextRun(option); + return wordInlineRunToTextRunsForRun(run, docx); }); } +function wordInlineRunToTextRunsForRun(run: WordInlineRun, docx: DocxModule, optionOverrides: Record = {}) { + const option = { ...wordInlineRunToTextRunOption(run), ...optionOverrides }; + const text = String(option.text ?? ""); + const baseOption = { ...option }; + delete baseOption.text; + const parts = text.split("\n"); + const textRuns: unknown[] = []; + + parts.forEach((part, index) => { + if (index > 0) { + textRuns.push(new docx.TextRun({ ...baseOption, break: 1 })); + } + if (part || parts.length === 1) { + textRuns.push(new docx.TextRun({ ...baseOption, text: part })); + } + }); + + return textRuns; +} + function docxAlignmentOption(alignment: WordParagraphAlignment | undefined, docx: DocxModule) { const value = docxAlignmentValue(alignment, docx); return value ? { alignment: value } : {}; @@ -605,7 +626,9 @@ async function styledDocxHtmlFromArrayBuffer(arrayBuffer: ArrayBuffer) { const relationshipTargets = relationshipsXml ? docxRelationshipTargetsById(parser.parse(relationshipsXml)) : emptyDocxRelationshipTargets; const imageDataByRelationshipId = await docxImageDataByRelationshipId(zip, relationshipTargets.images); const result = orderedDocxDocumentToHtml(orderedParser.parse(documentXml), relationshipTargets.hyperlinks, imageDataByRelationshipId); - return result.hasInlineColorOrHighlight || result.hasParagraphAlignment || result.hasTable || result.hasImage ? result.html : ""; + return result.hasInlineColorOrHighlight || result.hasParagraphAlignment || result.hasTable || result.hasImage || result.hasLineBreak + ? result.html + : ""; } catch { return ""; } @@ -626,6 +649,7 @@ function orderedDocxDocumentToHtml( let hasParagraphAlignment = false; let hasTable = false; let hasImage = false; + let hasLineBreak = false; const blocks = orderedElementChildren(body) .flatMap((block) => { const name = orderedElementName(block); @@ -634,12 +658,14 @@ function orderedDocxDocumentToHtml( hasInlineColorOrHighlight = hasInlineColorOrHighlight || result.hasInlineColorOrHighlight; hasParagraphAlignment = hasParagraphAlignment || result.hasParagraphAlignment; hasImage = hasImage || result.hasImage; + hasLineBreak = hasLineBreak || result.hasLineBreak; return result.html ? [result.html] : []; } if (name === "w:tbl") { const result = orderedDocxTableToHtml(block, hyperlinkTargets, imageDataByRelationshipId); hasTable = hasTable || Boolean(result.html); hasImage = hasImage || result.hasImage; + hasLineBreak = hasLineBreak || result.hasLineBreak; return result.html ? [result.html] : []; } @@ -651,7 +677,8 @@ function orderedDocxDocumentToHtml( hasInlineColorOrHighlight, hasParagraphAlignment, hasTable, - hasImage + hasImage, + hasLineBreak }; } @@ -666,23 +693,26 @@ function orderedDocxParagraphToHtml( const hasParagraphAlignment = Boolean(style); let hasInlineColorOrHighlight = false; let hasImage = false; + let hasLineBreak = false; const runs = orderedDocxParagraphInlineRecords(paragraph, hyperlinkTargets).map((inline) => { - const result = docxRunToHtml(inline.run, imageDataByRelationshipId); + const result = docxRunToHtml(inline.run, imageDataByRelationshipId, inline.text); hasInlineColorOrHighlight = hasInlineColorOrHighlight || result.hasInlineColorOrHighlight || Boolean(inline.href); hasImage = hasImage || result.hasImage; + hasLineBreak = hasLineBreak || result.hasLineBreak; return inline.href && result.html ? `${result.html}` : result.html; }); const content = runs.join(""); if (!content.trim()) { - return { html: "", hasInlineColorOrHighlight, hasParagraphAlignment, hasImage }; + return { html: "", hasInlineColorOrHighlight, hasParagraphAlignment, hasImage, hasLineBreak }; } return { html: `<${tagName}${style ? ` style="${style}"` : ""}>${content}`, hasInlineColorOrHighlight, hasParagraphAlignment, - hasImage + hasImage, + hasLineBreak }; } @@ -692,6 +722,7 @@ function orderedDocxTableToHtml( imageDataByRelationshipId: DocxImageDataByRelationshipId = {} ) { let hasImage = false; + let hasLineBreak = false; const rows = orderedDirectElements(table, "w:tr") .map((row) => { const cells = orderedDirectElements(row, "w:tc") @@ -700,6 +731,7 @@ function orderedDocxTableToHtml( .map((paragraph) => { const result = orderedDocxParagraphToHtml(paragraph, hyperlinkTargets, imageDataByRelationshipId); hasImage = hasImage || result.hasImage; + hasLineBreak = hasLineBreak || result.hasLineBreak; return result.html; }) .filter(Boolean); @@ -712,13 +744,13 @@ function orderedDocxTableToHtml( }) .filter(Boolean); - return { html: rows.length > 0 ? `${rows.join("")}
` : "", hasImage }; + return { html: rows.length > 0 ? `${rows.join("")}
` : "", hasImage, hasLineBreak }; } function orderedDocxCellText(cell: unknown) { return orderedDirectElements(cell, "w:p") .flatMap((paragraph) => orderedDocxParagraphInlineRecords(paragraph, {})) - .map((inline) => docxRunText(asRecord(inline.run))) + .map((inline) => inline.text) .join(" ") .trim(); } @@ -745,7 +777,7 @@ function orderedDocxParagraphInlineRecords(paragraph: unknown, hyperlinkTargets: return orderedElementChildren(paragraph).flatMap((child) => { const name = orderedElementName(child); if (name === "w:r") { - return [{ run: orderedElementToRecord(child) }]; + return [{ run: orderedElementToRecord(child), text: orderedDocxRunText(child) }]; } if (name !== "w:hyperlink") { return []; @@ -753,10 +785,33 @@ function orderedDocxParagraphInlineRecords(paragraph: unknown, hyperlinkTargets: const relationshipId = docxAttribute(orderedElementAttributes(child), "r:id") || docxAttribute(orderedElementAttributes(child), "id"); const href = normalizedHyperlinkTarget(hyperlinkTargets[relationshipId]); - return orderedDirectElements(child, "w:r").map((run) => ({ run: orderedElementToRecord(run), ...(href ? { href } : {}) })); + return orderedDirectElements(child, "w:r").map((run) => ({ + run: orderedElementToRecord(run), + text: orderedDocxRunText(run), + ...(href ? { href } : {}) + })); }); } +function orderedDocxRunText(run: unknown) { + return orderedElementChildren(run) + .map((child) => { + const name = orderedElementName(child); + if (name === "w:t") { + return xmlNodeText(orderedElementToRecord(child)); + } + if (name === "w:tab") { + return "\t"; + } + if (name === "w:br") { + return "\n"; + } + + return ""; + }) + .join(""); +} + function docxRelationshipTargetsById(relationshipsXml: unknown) { const relationships = childRecord(relationshipsXml, "Relationships"); const targets: { hyperlinks: Record; images: Record } = { hyperlinks: {}, images: {} }; @@ -894,10 +949,10 @@ function appendXmlChild(record: XmlRecord, key: string, value: XmlRecord) { record[key] = Array.isArray(existing) ? [...existing, value] : [existing, value]; } -function docxRunToHtml(run: unknown, imageDataByRelationshipId: DocxImageDataByRelationshipId = {}) { +function docxRunToHtml(run: unknown, imageDataByRelationshipId: DocxImageDataByRelationshipId = {}, orderedText?: string) { const record = asRecord(run); const properties = childRecord(record, "w:rPr"); - const text = docxRunText(record); + const text = orderedText ?? docxRunText(record); const imageHtml = docxRunImageHtml(record, imageDataByRelationshipId); const color = docxRunColor(properties); const highlightColor = docxRunHighlightColor(properties); @@ -905,10 +960,11 @@ function docxRunToHtml(run: unknown, imageDataByRelationshipId: DocxImageDataByR const fontFamily = docxRunFontFamily(properties); const hasStrike = hasDocxBoolean(properties, "w:strike") || hasDocxBoolean(properties, "w:dstrike"); const hasInlineColorOrHighlight = Boolean(color || highlightColor || fontSize || fontFamily || hasStrike); - let html = escapeHtml(text); + const hasLineBreak = text.includes("\n"); + let html = escapeHtmlDocxText(text); if (!text && !imageHtml) { - return { html: "", hasInlineColorOrHighlight, hasImage: false }; + return { html: "", hasInlineColorOrHighlight, hasImage: false, hasLineBreak }; } if (text) { @@ -937,7 +993,7 @@ function docxRunToHtml(run: unknown, imageDataByRelationshipId: DocxImageDataByR } } - return { html: `${imageHtml}${text ? html : ""}`, hasInlineColorOrHighlight, hasImage: Boolean(imageHtml) }; + return { html: `${imageHtml}${text ? html : ""}`, hasInlineColorOrHighlight, hasImage: Boolean(imageHtml), hasLineBreak }; } function docxRunImageHtml(run: XmlRecord, imageDataByRelationshipId: DocxImageDataByRelationshipId) { @@ -1163,6 +1219,10 @@ function escapeHtml(value: string) { .replace(/"/g, """); } +function escapeHtmlDocxText(value: string) { + return escapeHtml(value).replace(/\n/g, "
"); +} + function collectInlineRuns(nodes: ChildNode[], format: InlineFormat): WordInlineRun[] { return collectInlineSegments(nodes, format).flatMap((segment) => (segment.type === "runs" ? segment.runs : [])); } @@ -1179,7 +1239,7 @@ function collectInlineSegments(nodes: ChildNode[], format: InlineFormat): Inline } if (node.tagName.toLowerCase() === "br") { - return [{ type: "runs", runs: [{ text: " ", ...format }] }]; + return [{ type: "runs", runs: [{ text: "\n", ...format }] }]; } if (node.tagName.toLowerCase() === "img") { @@ -1215,7 +1275,7 @@ function formatForElement(element: Element, inherited: InlineFormat): InlineForm function normalizeInlineRuns(runs: WordInlineRun[]) { const normalized = runs - .map((run) => ({ ...run, text: normalizeInlineWhitespace(run.text) })) + .map((run) => ({ ...run, text: normalizeInlineRunText(run.text) })) .filter((run) => run.text.length > 0); if (normalized.length === 0) { @@ -1485,6 +1545,13 @@ function normalizeInlineWhitespace(value: string) { return value.replace(/\u00a0/g, " ").replace(/\s+/g, " "); } +function normalizeInlineRunText(value: string) { + return value + .replace(/\u00a0/g, " ") + .replace(/[^\S\n]+/g, " ") + .replace(/ *\n */g, "\n"); +} + async function loadMammoth() { const module = (await import("mammoth")) as { default?: MammothModule } & MammothModule; return module.default ?? module; diff --git a/src/io/wordOfficeImport.test.ts b/src/io/wordOfficeImport.test.ts index 05011c2..8de4767 100644 --- a/src/io/wordOfficeImport.test.ts +++ b/src/io/wordOfficeImport.test.ts @@ -95,6 +95,23 @@ describe("wordOffice DOCX import", () => { ]); }); + it("imports DOCX line breaks from OOXML", async () => { + const blob = await exportDocxBlob("LineBreak.docx", "

Line 1
Line 2

"); + const file = new File([blob], "LineBreak.docx", { + type: "application/vnd.openxmlformats-officedocument.wordprocessingml.document" + }); + const imported = await importDocxFile(file); + + expect(imported.html).toContain("Line 1
Line 2"); + expect(htmlToWordBlocks(imported.html)).toEqual([ + { + type: "paragraph", + text: "Line 1 Line 2", + runs: [{ text: "Line 1\nLine 2" }] + } + ]); + }); + it("imports DOCX external hyperlinks from OOXML relationships", async () => { const blob = await exportDocxBlob("Hyperlink.docx", '

Open report.

'); const file = new File([blob], "Hyperlink.docx", {