Preserve QWord line breaks in DOCX
This commit is contained in:
@@ -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 для дат, процентов, денежных и дробных значений.
|
- QExcell открывает `.xlsx` и сохраняет `.xlsx`; сетка расширяется по фактически заполненным ячейкам, поддерживает несколько листов, формулы за пределами стартового диапазона A-H, shared formulas XLSX с относительными ссылками, базовые merged cells, внешние и внутренние гиперссылки ячеек, базовые диаграммы листа и базовое форматирование ячеек: полужирный, курсив, подчеркивание, зачеркивание, размер и семейство шрифта, прямые RGB/theme/indexed цвета текста с учетом `xl/theme/theme1.xml`, заливку, горизонтальное и вертикальное выравнивание, перенос текста, границы и цвет границ ячеек, числовые форматы XLSX для дат, процентов, денежных и дробных значений.
|
||||||
- QPowerPoint открывает `.pptx` и сохраняет `.pptx`; импорт учитывает порядок слайдов из `presentation.xml`, переносы абзацев внутри текстовых блоков и заметки докладчика через relationships слайда, сохраняет заметки докладчика, базовые растровые изображения слайдов, пользовательский цвет фона слайда, а также цвет, размер и семейство шрифта текста заголовка/подзаголовка.
|
- 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` пока не реализованы.
|
- 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+Shift+E`: экспортировать текущую рабочую область в PDF.
|
||||||
- `Ctrl/Cmd+P`: печать текущей рабочей области.
|
- `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 в текущем инкременте не заявлены.
|
||||||
|
|
||||||
## Сборка пакета
|
## Сборка пакета
|
||||||
|
|
||||||
|
|||||||
@@ -52,6 +52,18 @@ describe("wordOffice helpers", () => {
|
|||||||
]);
|
]);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("сохраняет HTML-переносы строк как inline runs для DOCX", () => {
|
||||||
|
const blocks = htmlToWordBlocks("<p>Line 1<br>Line 2<br><strong>Line 3</strong></p>");
|
||||||
|
|
||||||
|
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", () => {
|
it("сохраняет выравнивание абзацев и заголовков для DOCX", () => {
|
||||||
const blocks = htmlToWordBlocks(`
|
const blocks = htmlToWordBlocks(`
|
||||||
<h1 align="right">Итоги</h1>
|
<h1 align="right">Итоги</h1>
|
||||||
@@ -123,6 +135,15 @@ describe("wordOffice helpers", () => {
|
|||||||
expect(documentXml).toContain("<w:u");
|
expect(documentXml).toContain("<w:u");
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("записывает HTML-переносы строк как w:br в XML экспортированного DOCX", async () => {
|
||||||
|
const blob = await exportDocxBlob("Переносы.docx", "<p>Line 1<br>Line 2</p>");
|
||||||
|
const zip = await JSZip.loadAsync(await blob.arrayBuffer());
|
||||||
|
const documentXml = await zip.file("word/document.xml")?.async("string");
|
||||||
|
|
||||||
|
expect(documentXml).toContain("<w:br/>");
|
||||||
|
expect(documentXml).toMatch(/<w:t[^>]*>Line 1<\/w:t>[\s\S]*<w:br\/>[\s\S]*<w:t[^>]*>Line 2<\/w:t>/);
|
||||||
|
});
|
||||||
|
|
||||||
it("записывает цвет текста и подсветку в XML экспортированного DOCX", async () => {
|
it("записывает цвет текста и подсветку в XML экспортированного DOCX", async () => {
|
||||||
const blob = await exportDocxBlob(
|
const blob = await exportDocxBlob(
|
||||||
"Цвет.docx",
|
"Цвет.docx",
|
||||||
|
|||||||
+91
-24
@@ -92,7 +92,7 @@ type DocxModule = {
|
|||||||
|
|
||||||
type InlineFormat = Omit<WordInlineRun, "text">;
|
type InlineFormat = Omit<WordInlineRun, "text">;
|
||||||
type InlineSegment = { type: "runs"; runs: WordInlineRun[] } | { type: "image"; image: WordImageBlock };
|
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<string, string>;
|
type DocxImageDataByRelationshipId = Record<string, string>;
|
||||||
|
|
||||||
const mammothStyleMap = [
|
const mammothStyleMap = [
|
||||||
@@ -381,20 +381,41 @@ function wordInlineRunToTextRunOption(run: WordInlineRun) {
|
|||||||
|
|
||||||
function wordInlineRunsToTextRuns(runs: WordInlineRun[], docx: DocxModule) {
|
function wordInlineRunsToTextRuns(runs: WordInlineRun[], docx: DocxModule) {
|
||||||
const normalizedRuns = runs.length > 0 ? runs : [{ text: "" }];
|
const normalizedRuns = runs.length > 0 ? runs : [{ text: "" }];
|
||||||
return normalizedRuns.map((run) => {
|
return normalizedRuns.flatMap((run) => {
|
||||||
const option = wordInlineRunToTextRunOption(run);
|
|
||||||
const href = normalizedHyperlinkTarget(run.href);
|
const href = normalizedHyperlinkTarget(run.href);
|
||||||
if (href && docx.ExternalHyperlink) {
|
if (href && docx.ExternalHyperlink) {
|
||||||
return new docx.ExternalHyperlink({
|
return [
|
||||||
link: href,
|
new docx.ExternalHyperlink({
|
||||||
children: [new docx.TextRun({ ...option, style: "Hyperlink" })]
|
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<string, unknown> = {}) {
|
||||||
|
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) {
|
function docxAlignmentOption(alignment: WordParagraphAlignment | undefined, docx: DocxModule) {
|
||||||
const value = docxAlignmentValue(alignment, docx);
|
const value = docxAlignmentValue(alignment, docx);
|
||||||
return value ? { alignment: value } : {};
|
return value ? { alignment: value } : {};
|
||||||
@@ -605,7 +626,9 @@ async function styledDocxHtmlFromArrayBuffer(arrayBuffer: ArrayBuffer) {
|
|||||||
const relationshipTargets = relationshipsXml ? docxRelationshipTargetsById(parser.parse(relationshipsXml)) : emptyDocxRelationshipTargets;
|
const relationshipTargets = relationshipsXml ? docxRelationshipTargetsById(parser.parse(relationshipsXml)) : emptyDocxRelationshipTargets;
|
||||||
const imageDataByRelationshipId = await docxImageDataByRelationshipId(zip, relationshipTargets.images);
|
const imageDataByRelationshipId = await docxImageDataByRelationshipId(zip, relationshipTargets.images);
|
||||||
const result = orderedDocxDocumentToHtml(orderedParser.parse(documentXml), relationshipTargets.hyperlinks, imageDataByRelationshipId);
|
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 {
|
} catch {
|
||||||
return "";
|
return "";
|
||||||
}
|
}
|
||||||
@@ -626,6 +649,7 @@ function orderedDocxDocumentToHtml(
|
|||||||
let hasParagraphAlignment = false;
|
let hasParagraphAlignment = false;
|
||||||
let hasTable = false;
|
let hasTable = false;
|
||||||
let hasImage = false;
|
let hasImage = false;
|
||||||
|
let hasLineBreak = false;
|
||||||
const blocks = orderedElementChildren(body)
|
const blocks = orderedElementChildren(body)
|
||||||
.flatMap((block) => {
|
.flatMap((block) => {
|
||||||
const name = orderedElementName(block);
|
const name = orderedElementName(block);
|
||||||
@@ -634,12 +658,14 @@ function orderedDocxDocumentToHtml(
|
|||||||
hasInlineColorOrHighlight = hasInlineColorOrHighlight || result.hasInlineColorOrHighlight;
|
hasInlineColorOrHighlight = hasInlineColorOrHighlight || result.hasInlineColorOrHighlight;
|
||||||
hasParagraphAlignment = hasParagraphAlignment || result.hasParagraphAlignment;
|
hasParagraphAlignment = hasParagraphAlignment || result.hasParagraphAlignment;
|
||||||
hasImage = hasImage || result.hasImage;
|
hasImage = hasImage || result.hasImage;
|
||||||
|
hasLineBreak = hasLineBreak || result.hasLineBreak;
|
||||||
return result.html ? [result.html] : [];
|
return result.html ? [result.html] : [];
|
||||||
}
|
}
|
||||||
if (name === "w:tbl") {
|
if (name === "w:tbl") {
|
||||||
const result = orderedDocxTableToHtml(block, hyperlinkTargets, imageDataByRelationshipId);
|
const result = orderedDocxTableToHtml(block, hyperlinkTargets, imageDataByRelationshipId);
|
||||||
hasTable = hasTable || Boolean(result.html);
|
hasTable = hasTable || Boolean(result.html);
|
||||||
hasImage = hasImage || result.hasImage;
|
hasImage = hasImage || result.hasImage;
|
||||||
|
hasLineBreak = hasLineBreak || result.hasLineBreak;
|
||||||
return result.html ? [result.html] : [];
|
return result.html ? [result.html] : [];
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -651,7 +677,8 @@ function orderedDocxDocumentToHtml(
|
|||||||
hasInlineColorOrHighlight,
|
hasInlineColorOrHighlight,
|
||||||
hasParagraphAlignment,
|
hasParagraphAlignment,
|
||||||
hasTable,
|
hasTable,
|
||||||
hasImage
|
hasImage,
|
||||||
|
hasLineBreak
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -666,23 +693,26 @@ function orderedDocxParagraphToHtml(
|
|||||||
const hasParagraphAlignment = Boolean(style);
|
const hasParagraphAlignment = Boolean(style);
|
||||||
let hasInlineColorOrHighlight = false;
|
let hasInlineColorOrHighlight = false;
|
||||||
let hasImage = false;
|
let hasImage = false;
|
||||||
|
let hasLineBreak = false;
|
||||||
const runs = orderedDocxParagraphInlineRecords(paragraph, hyperlinkTargets).map((inline) => {
|
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);
|
hasInlineColorOrHighlight = hasInlineColorOrHighlight || result.hasInlineColorOrHighlight || Boolean(inline.href);
|
||||||
hasImage = hasImage || result.hasImage;
|
hasImage = hasImage || result.hasImage;
|
||||||
|
hasLineBreak = hasLineBreak || result.hasLineBreak;
|
||||||
return inline.href && result.html ? `<a href="${escapeHtml(inline.href)}">${result.html}</a>` : result.html;
|
return inline.href && result.html ? `<a href="${escapeHtml(inline.href)}">${result.html}</a>` : result.html;
|
||||||
});
|
});
|
||||||
const content = runs.join("");
|
const content = runs.join("");
|
||||||
|
|
||||||
if (!content.trim()) {
|
if (!content.trim()) {
|
||||||
return { html: "", hasInlineColorOrHighlight, hasParagraphAlignment, hasImage };
|
return { html: "", hasInlineColorOrHighlight, hasParagraphAlignment, hasImage, hasLineBreak };
|
||||||
}
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
html: `<${tagName}${style ? ` style="${style}"` : ""}>${content}</${tagName}>`,
|
html: `<${tagName}${style ? ` style="${style}"` : ""}>${content}</${tagName}>`,
|
||||||
hasInlineColorOrHighlight,
|
hasInlineColorOrHighlight,
|
||||||
hasParagraphAlignment,
|
hasParagraphAlignment,
|
||||||
hasImage
|
hasImage,
|
||||||
|
hasLineBreak
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -692,6 +722,7 @@ function orderedDocxTableToHtml(
|
|||||||
imageDataByRelationshipId: DocxImageDataByRelationshipId = {}
|
imageDataByRelationshipId: DocxImageDataByRelationshipId = {}
|
||||||
) {
|
) {
|
||||||
let hasImage = false;
|
let hasImage = false;
|
||||||
|
let hasLineBreak = false;
|
||||||
const rows = orderedDirectElements(table, "w:tr")
|
const rows = orderedDirectElements(table, "w:tr")
|
||||||
.map((row) => {
|
.map((row) => {
|
||||||
const cells = orderedDirectElements(row, "w:tc")
|
const cells = orderedDirectElements(row, "w:tc")
|
||||||
@@ -700,6 +731,7 @@ function orderedDocxTableToHtml(
|
|||||||
.map((paragraph) => {
|
.map((paragraph) => {
|
||||||
const result = orderedDocxParagraphToHtml(paragraph, hyperlinkTargets, imageDataByRelationshipId);
|
const result = orderedDocxParagraphToHtml(paragraph, hyperlinkTargets, imageDataByRelationshipId);
|
||||||
hasImage = hasImage || result.hasImage;
|
hasImage = hasImage || result.hasImage;
|
||||||
|
hasLineBreak = hasLineBreak || result.hasLineBreak;
|
||||||
return result.html;
|
return result.html;
|
||||||
})
|
})
|
||||||
.filter(Boolean);
|
.filter(Boolean);
|
||||||
@@ -712,13 +744,13 @@ function orderedDocxTableToHtml(
|
|||||||
})
|
})
|
||||||
.filter(Boolean);
|
.filter(Boolean);
|
||||||
|
|
||||||
return { html: rows.length > 0 ? `<table><tbody>${rows.join("")}</tbody></table>` : "", hasImage };
|
return { html: rows.length > 0 ? `<table><tbody>${rows.join("")}</tbody></table>` : "", hasImage, hasLineBreak };
|
||||||
}
|
}
|
||||||
|
|
||||||
function orderedDocxCellText(cell: unknown) {
|
function orderedDocxCellText(cell: unknown) {
|
||||||
return orderedDirectElements(cell, "w:p")
|
return orderedDirectElements(cell, "w:p")
|
||||||
.flatMap((paragraph) => orderedDocxParagraphInlineRecords(paragraph, {}))
|
.flatMap((paragraph) => orderedDocxParagraphInlineRecords(paragraph, {}))
|
||||||
.map((inline) => docxRunText(asRecord(inline.run)))
|
.map((inline) => inline.text)
|
||||||
.join(" ")
|
.join(" ")
|
||||||
.trim();
|
.trim();
|
||||||
}
|
}
|
||||||
@@ -745,7 +777,7 @@ function orderedDocxParagraphInlineRecords(paragraph: unknown, hyperlinkTargets:
|
|||||||
return orderedElementChildren(paragraph).flatMap<DocxInlineRecord>((child) => {
|
return orderedElementChildren(paragraph).flatMap<DocxInlineRecord>((child) => {
|
||||||
const name = orderedElementName(child);
|
const name = orderedElementName(child);
|
||||||
if (name === "w:r") {
|
if (name === "w:r") {
|
||||||
return [{ run: orderedElementToRecord(child) }];
|
return [{ run: orderedElementToRecord(child), text: orderedDocxRunText(child) }];
|
||||||
}
|
}
|
||||||
if (name !== "w:hyperlink") {
|
if (name !== "w:hyperlink") {
|
||||||
return [];
|
return [];
|
||||||
@@ -753,10 +785,33 @@ function orderedDocxParagraphInlineRecords(paragraph: unknown, hyperlinkTargets:
|
|||||||
|
|
||||||
const relationshipId = docxAttribute(orderedElementAttributes(child), "r:id") || docxAttribute(orderedElementAttributes(child), "id");
|
const relationshipId = docxAttribute(orderedElementAttributes(child), "r:id") || docxAttribute(orderedElementAttributes(child), "id");
|
||||||
const href = normalizedHyperlinkTarget(hyperlinkTargets[relationshipId]);
|
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) {
|
function docxRelationshipTargetsById(relationshipsXml: unknown) {
|
||||||
const relationships = childRecord(relationshipsXml, "Relationships");
|
const relationships = childRecord(relationshipsXml, "Relationships");
|
||||||
const targets: { hyperlinks: Record<string, string>; images: Record<string, string> } = { hyperlinks: {}, images: {} };
|
const targets: { hyperlinks: Record<string, string>; images: Record<string, string> } = { hyperlinks: {}, images: {} };
|
||||||
@@ -894,10 +949,10 @@ function appendXmlChild(record: XmlRecord, key: string, value: XmlRecord) {
|
|||||||
record[key] = Array.isArray(existing) ? [...existing, value] : [existing, value];
|
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 record = asRecord(run);
|
||||||
const properties = childRecord(record, "w:rPr");
|
const properties = childRecord(record, "w:rPr");
|
||||||
const text = docxRunText(record);
|
const text = orderedText ?? docxRunText(record);
|
||||||
const imageHtml = docxRunImageHtml(record, imageDataByRelationshipId);
|
const imageHtml = docxRunImageHtml(record, imageDataByRelationshipId);
|
||||||
const color = docxRunColor(properties);
|
const color = docxRunColor(properties);
|
||||||
const highlightColor = docxRunHighlightColor(properties);
|
const highlightColor = docxRunHighlightColor(properties);
|
||||||
@@ -905,10 +960,11 @@ function docxRunToHtml(run: unknown, imageDataByRelationshipId: DocxImageDataByR
|
|||||||
const fontFamily = docxRunFontFamily(properties);
|
const fontFamily = docxRunFontFamily(properties);
|
||||||
const hasStrike = hasDocxBoolean(properties, "w:strike") || hasDocxBoolean(properties, "w:dstrike");
|
const hasStrike = hasDocxBoolean(properties, "w:strike") || hasDocxBoolean(properties, "w:dstrike");
|
||||||
const hasInlineColorOrHighlight = Boolean(color || highlightColor || fontSize || fontFamily || hasStrike);
|
const hasInlineColorOrHighlight = Boolean(color || highlightColor || fontSize || fontFamily || hasStrike);
|
||||||
let html = escapeHtml(text);
|
const hasLineBreak = text.includes("\n");
|
||||||
|
let html = escapeHtmlDocxText(text);
|
||||||
|
|
||||||
if (!text && !imageHtml) {
|
if (!text && !imageHtml) {
|
||||||
return { html: "", hasInlineColorOrHighlight, hasImage: false };
|
return { html: "", hasInlineColorOrHighlight, hasImage: false, hasLineBreak };
|
||||||
}
|
}
|
||||||
|
|
||||||
if (text) {
|
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) {
|
function docxRunImageHtml(run: XmlRecord, imageDataByRelationshipId: DocxImageDataByRelationshipId) {
|
||||||
@@ -1163,6 +1219,10 @@ function escapeHtml(value: string) {
|
|||||||
.replace(/"/g, """);
|
.replace(/"/g, """);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function escapeHtmlDocxText(value: string) {
|
||||||
|
return escapeHtml(value).replace(/\n/g, "<br>");
|
||||||
|
}
|
||||||
|
|
||||||
function collectInlineRuns(nodes: ChildNode[], format: InlineFormat): WordInlineRun[] {
|
function collectInlineRuns(nodes: ChildNode[], format: InlineFormat): WordInlineRun[] {
|
||||||
return collectInlineSegments(nodes, format).flatMap((segment) => (segment.type === "runs" ? segment.runs : []));
|
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") {
|
if (node.tagName.toLowerCase() === "br") {
|
||||||
return [{ type: "runs", runs: [{ text: " ", ...format }] }];
|
return [{ type: "runs", runs: [{ text: "\n", ...format }] }];
|
||||||
}
|
}
|
||||||
|
|
||||||
if (node.tagName.toLowerCase() === "img") {
|
if (node.tagName.toLowerCase() === "img") {
|
||||||
@@ -1215,7 +1275,7 @@ function formatForElement(element: Element, inherited: InlineFormat): InlineForm
|
|||||||
|
|
||||||
function normalizeInlineRuns(runs: WordInlineRun[]) {
|
function normalizeInlineRuns(runs: WordInlineRun[]) {
|
||||||
const normalized = runs
|
const normalized = runs
|
||||||
.map((run) => ({ ...run, text: normalizeInlineWhitespace(run.text) }))
|
.map((run) => ({ ...run, text: normalizeInlineRunText(run.text) }))
|
||||||
.filter((run) => run.text.length > 0);
|
.filter((run) => run.text.length > 0);
|
||||||
|
|
||||||
if (normalized.length === 0) {
|
if (normalized.length === 0) {
|
||||||
@@ -1485,6 +1545,13 @@ function normalizeInlineWhitespace(value: string) {
|
|||||||
return value.replace(/\u00a0/g, " ").replace(/\s+/g, " ");
|
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() {
|
async function loadMammoth() {
|
||||||
const module = (await import("mammoth")) as { default?: MammothModule } & MammothModule;
|
const module = (await import("mammoth")) as { default?: MammothModule } & MammothModule;
|
||||||
return module.default ?? module;
|
return module.default ?? module;
|
||||||
|
|||||||
@@ -95,6 +95,23 @@ describe("wordOffice DOCX import", () => {
|
|||||||
]);
|
]);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("imports DOCX line breaks from OOXML", async () => {
|
||||||
|
const blob = await exportDocxBlob("LineBreak.docx", "<p>Line 1<br>Line 2</p>");
|
||||||
|
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<br>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 () => {
|
it("imports DOCX external hyperlinks from OOXML relationships", async () => {
|
||||||
const blob = await exportDocxBlob("Hyperlink.docx", '<p>Open <a href="https://example.com/report"><strong>report</strong></a>.</p>');
|
const blob = await exportDocxBlob("Hyperlink.docx", '<p>Open <a href="https://example.com/report"><strong>report</strong></a>.</p>');
|
||||||
const file = new File([blob], "Hyperlink.docx", {
|
const file = new File([blob], "Hyperlink.docx", {
|
||||||
|
|||||||
Reference in New Issue
Block a user