Preserve QWord bookmarks in DOCX
This commit is contained in:
@@ -29,6 +29,15 @@ describe("wordOffice helpers", () => {
|
||||
]);
|
||||
});
|
||||
|
||||
it("сохраняет HTML id абзацев и заголовков как закладки DOCX", () => {
|
||||
const blocks = htmlToWordBlocks('<h1 id="Section1">Раздел</h1><p id="Summary">Итог</p>');
|
||||
|
||||
expect(blocks).toEqual([
|
||||
{ type: "heading", level: 1, text: "Раздел", runs: [{ text: "Раздел" }], bookmark: "Section1" },
|
||||
{ type: "paragraph", text: "Итог", runs: [{ text: "Итог" }], bookmark: "Summary" }
|
||||
]);
|
||||
});
|
||||
|
||||
it("сохраняет базовое inline-форматирование текста для DOCX", () => {
|
||||
const blocks = htmlToWordBlocks(`
|
||||
<p>Обычный <strong>полужирный</strong> <em>курсив</em> <u>подчеркнутый</u> <span style="font-weight: 700; font-style: italic; text-decoration-line: underline; color: #0f5fae; background-color: rgb(255, 242, 204);">все стили</span></p>
|
||||
@@ -237,6 +246,16 @@ describe("wordOffice helpers", () => {
|
||||
expect(relationshipsXml).not.toContain('Target="#Section1"');
|
||||
});
|
||||
|
||||
it("записывает HTML id как DOCX bookmarkStart/bookmarkEnd", async () => {
|
||||
const blob = await exportDocxBlob("Закладка.docx", '<h1 id="Section1">Раздел</h1><p><a href="#Section1">К разделу</a></p>');
|
||||
const zip = await JSZip.loadAsync(await blob.arrayBuffer());
|
||||
const documentXml = await zip.file("word/document.xml")?.async("string");
|
||||
|
||||
expect(documentXml).toMatch(/<w:bookmarkStart\b[^>]*w:name="Section1"[^>]*\/>/);
|
||||
expect(documentXml).toContain("<w:bookmarkEnd");
|
||||
expect(documentXml).toMatch(/<w:hyperlink\b[^>]*w:anchor="Section1"[^>]*>/);
|
||||
});
|
||||
|
||||
it("записывает data URI изображения в DOCX media relationships", async () => {
|
||||
const blob = await exportDocxBlob("Изображение.docx", `<p>Логотип</p><img src="${tinyPngDataUri}" alt="Логотип" width="32" height="32">`);
|
||||
const zip = await JSZip.loadAsync(await blob.arrayBuffer());
|
||||
|
||||
+50
-8
@@ -34,8 +34,8 @@ export interface WordImageBlock {
|
||||
export type WordParagraphAlignment = "left" | "center" | "right" | "both";
|
||||
|
||||
export type WordBlock =
|
||||
| { type: "heading"; level: 1 | 2; text: string; runs: WordInlineRun[]; alignment?: WordParagraphAlignment }
|
||||
| { type: "paragraph"; text: string; runs: WordInlineRun[]; alignment?: WordParagraphAlignment }
|
||||
| { type: "heading"; level: 1 | 2; text: string; runs: WordInlineRun[]; alignment?: WordParagraphAlignment; bookmark?: string }
|
||||
| { type: "paragraph"; text: string; runs: WordInlineRun[]; alignment?: WordParagraphAlignment; bookmark?: string }
|
||||
| { type: "list"; ordered: boolean; items: WordListItem[] }
|
||||
| { type: "table"; rows: string[][] }
|
||||
| WordImageBlock;
|
||||
@@ -82,6 +82,7 @@ type DocxModule = {
|
||||
};
|
||||
Paragraph: new (options: Record<string, unknown>) => unknown;
|
||||
PageBreak?: new () => unknown;
|
||||
Bookmark?: new (options: { id: string; children: unknown[] }) => unknown;
|
||||
Table: new (options: Record<string, unknown>) => unknown;
|
||||
TableCell: new (options: Record<string, unknown>) => unknown;
|
||||
TableRow: new (options: Record<string, unknown>) => unknown;
|
||||
@@ -233,8 +234,16 @@ export function htmlToWordBlocks(html: string): WordBlock[] {
|
||||
const runs = elementInlineRuns(node);
|
||||
const text = inlineRunsText(runs);
|
||||
const alignment = paragraphAlignmentFromElement(node);
|
||||
const bookmark = bookmarkFromElement(node);
|
||||
if (text) {
|
||||
blocks.push({ type: "heading", level: tagName === "h1" ? 1 : 2, text, runs, ...(alignment ? { alignment } : {}) });
|
||||
blocks.push({
|
||||
type: "heading",
|
||||
level: tagName === "h1" ? 1 : 2,
|
||||
text,
|
||||
runs,
|
||||
...(alignment ? { alignment } : {}),
|
||||
...(bookmark ? { bookmark } : {})
|
||||
});
|
||||
}
|
||||
return;
|
||||
}
|
||||
@@ -277,22 +286,24 @@ export function htmlToWordBlocks(html: string): WordBlock[] {
|
||||
|
||||
function wordBlockToDocxChildren(block: WordBlock, docx: DocxModule) {
|
||||
if (block.type === "heading") {
|
||||
const children = wordInlineRunsToTextRuns(block.runs, docx);
|
||||
return [
|
||||
new docx.Paragraph({
|
||||
heading: block.level === 1 ? docx.HeadingLevel.HEADING_1 : docx.HeadingLevel.HEADING_2,
|
||||
spacing: { after: 160 },
|
||||
...docxAlignmentOption(block.alignment, docx),
|
||||
children: wordInlineRunsToTextRuns(block.runs, docx)
|
||||
children: bookmarkDocxChildren(block.bookmark, children, docx)
|
||||
})
|
||||
];
|
||||
}
|
||||
|
||||
if (block.type === "paragraph") {
|
||||
const children = wordInlineRunsToTextRuns(block.runs, docx);
|
||||
return [
|
||||
new docx.Paragraph({
|
||||
spacing: { after: 160 },
|
||||
...docxAlignmentOption(block.alignment, docx),
|
||||
children: wordInlineRunsToTextRuns(block.runs, docx)
|
||||
children: bookmarkDocxChildren(block.bookmark, children, docx)
|
||||
})
|
||||
];
|
||||
}
|
||||
@@ -416,6 +427,10 @@ function wordInlineRunsToTextRuns(runs: WordInlineRun[], docx: DocxModule) {
|
||||
});
|
||||
}
|
||||
|
||||
function bookmarkDocxChildren(bookmark: string | undefined, children: unknown[], docx: DocxModule) {
|
||||
return bookmark && docx.Bookmark ? [new docx.Bookmark({ id: bookmark, children })] : children;
|
||||
}
|
||||
|
||||
function wordInlineRunToTextRunsForRun(run: WordInlineRun, docx: DocxModule, optionOverrides: Record<string, unknown> = {}) {
|
||||
const option = { ...wordInlineRunToTextRunOption(run), ...optionOverrides };
|
||||
const text = String(option.text ?? "");
|
||||
@@ -531,15 +546,24 @@ function tableRows(table: Element) {
|
||||
function paragraphElementToBlocks(element: Element): WordBlock[] {
|
||||
const segments = collectInlineSegments(Array.from(element.childNodes), {});
|
||||
const alignment = paragraphAlignmentFromElement(element);
|
||||
const bookmark = bookmarkFromElement(element);
|
||||
const blocks: WordBlock[] = [];
|
||||
let pendingRuns: WordInlineRun[] = [];
|
||||
let bookmarkApplied = false;
|
||||
|
||||
const flushParagraph = () => {
|
||||
const runs = normalizeInlineRuns(pendingRuns);
|
||||
const text = inlineRunsText(runs);
|
||||
const hasPageBreak = runs.some((run) => run.text.includes(pageBreakMarker));
|
||||
if (text || hasPageBreak) {
|
||||
blocks.push({ type: "paragraph", text, runs, ...(alignment ? { alignment } : {}) });
|
||||
blocks.push({
|
||||
type: "paragraph",
|
||||
text,
|
||||
runs,
|
||||
...(alignment ? { alignment } : {}),
|
||||
...(bookmark && !bookmarkApplied ? { bookmark } : {})
|
||||
});
|
||||
bookmarkApplied = true;
|
||||
}
|
||||
pendingRuns = [];
|
||||
};
|
||||
@@ -572,6 +596,10 @@ function paragraphAlignmentFromElement(element: Element): WordParagraphAlignment
|
||||
return normalized === "justify" ? "both" : undefined;
|
||||
}
|
||||
|
||||
function bookmarkFromElement(element: Element) {
|
||||
return normalizedDocxAnchor(element.getAttribute("id") || element.getAttribute("name"));
|
||||
}
|
||||
|
||||
function cssTextAlignValue(style: string) {
|
||||
return /(?:^|;)\s*text-align\s*:\s*([^;]+)/i.exec(style)?.[1] ?? "";
|
||||
}
|
||||
@@ -674,6 +702,7 @@ async function styledDocxHtmlFromArrayBuffer(arrayBuffer: ArrayBuffer) {
|
||||
const result = orderedDocxDocumentToHtml(orderedParser.parse(documentXml), relationshipTargets.hyperlinks, imageDataByRelationshipId);
|
||||
return result.hasInlineColorOrHighlight ||
|
||||
result.hasParagraphAlignment ||
|
||||
result.hasBookmark ||
|
||||
result.hasTable ||
|
||||
result.hasImage ||
|
||||
result.hasLineBreak ||
|
||||
@@ -699,6 +728,7 @@ function orderedDocxDocumentToHtml(
|
||||
const body = firstOrderedElement(orderedElementChildren(document), "w:body");
|
||||
let hasInlineColorOrHighlight = false;
|
||||
let hasParagraphAlignment = false;
|
||||
let hasBookmark = false;
|
||||
let hasTable = false;
|
||||
let hasImage = false;
|
||||
let hasLineBreak = false;
|
||||
@@ -711,6 +741,7 @@ function orderedDocxDocumentToHtml(
|
||||
const result = orderedDocxParagraphToHtml(block, hyperlinkTargets, imageDataByRelationshipId);
|
||||
hasInlineColorOrHighlight = hasInlineColorOrHighlight || result.hasInlineColorOrHighlight;
|
||||
hasParagraphAlignment = hasParagraphAlignment || result.hasParagraphAlignment;
|
||||
hasBookmark = hasBookmark || result.hasBookmark;
|
||||
hasImage = hasImage || result.hasImage;
|
||||
hasLineBreak = hasLineBreak || result.hasLineBreak;
|
||||
hasPageBreak = hasPageBreak || result.hasPageBreak;
|
||||
@@ -734,6 +765,7 @@ function orderedDocxDocumentToHtml(
|
||||
html: blocks.join(""),
|
||||
hasInlineColorOrHighlight,
|
||||
hasParagraphAlignment,
|
||||
hasBookmark,
|
||||
hasTable,
|
||||
hasImage,
|
||||
hasLineBreak,
|
||||
@@ -750,7 +782,9 @@ function orderedDocxParagraphToHtml(
|
||||
const properties = orderedElementToRecord(firstOrderedElement(orderedElementChildren(paragraph), "w:pPr"));
|
||||
const tagName = docxParagraphTagName(properties);
|
||||
const style = docxParagraphStyleAttribute(properties);
|
||||
const bookmark = orderedDocxParagraphBookmark(paragraph);
|
||||
const hasParagraphAlignment = Boolean(style);
|
||||
const hasBookmark = Boolean(bookmark);
|
||||
let hasInlineColorOrHighlight = false;
|
||||
let hasImage = false;
|
||||
let hasLineBreak = false;
|
||||
@@ -768,13 +802,16 @@ function orderedDocxParagraphToHtml(
|
||||
const content = runs.join("");
|
||||
|
||||
if (!content.trim()) {
|
||||
return { html: "", hasInlineColorOrHighlight, hasParagraphAlignment, hasImage, hasLineBreak, hasPageBreak, hasTab };
|
||||
return { html: "", hasInlineColorOrHighlight, hasParagraphAlignment, hasBookmark, hasImage, hasLineBreak, hasPageBreak, hasTab };
|
||||
}
|
||||
|
||||
const attributes = [style ? `style="${style}"` : "", bookmark ? `id="${escapeHtml(bookmark)}"` : ""].filter(Boolean).join(" ");
|
||||
|
||||
return {
|
||||
html: `<${tagName}${style ? ` style="${style}"` : ""}>${content}</${tagName}>`,
|
||||
html: `<${tagName}${attributes ? ` ${attributes}` : ""}>${content}</${tagName}>`,
|
||||
hasInlineColorOrHighlight,
|
||||
hasParagraphAlignment,
|
||||
hasBookmark,
|
||||
hasImage,
|
||||
hasLineBreak,
|
||||
hasPageBreak,
|
||||
@@ -843,6 +880,11 @@ function docxParagraphStyleAttribute(properties: XmlRecord) {
|
||||
return ["left", "center", "right", "justify"].includes(htmlAlignment) ? `text-align: ${htmlAlignment};` : "";
|
||||
}
|
||||
|
||||
function orderedDocxParagraphBookmark(paragraph: unknown) {
|
||||
const bookmarkStart = firstOrderedElement(orderedElementChildren(paragraph), "w:bookmarkStart");
|
||||
return normalizedDocxAnchor(docxAttribute(orderedElementAttributes(bookmarkStart), "w:name") || docxAttribute(orderedElementAttributes(bookmarkStart), "name"));
|
||||
}
|
||||
|
||||
function orderedDocxParagraphInlineRecords(paragraph: unknown, hyperlinkTargets: Record<string, string>) {
|
||||
return orderedElementChildren(paragraph).flatMap<DocxInlineRecord>((child) => {
|
||||
const name = orderedElementName(child);
|
||||
|
||||
@@ -184,6 +184,21 @@ describe("wordOffice DOCX import", () => {
|
||||
]);
|
||||
});
|
||||
|
||||
it("imports DOCX bookmarks as HTML ids", async () => {
|
||||
const blob = await exportDocxBlob("Bookmark.docx", '<h1 id="Section1">Section</h1><p><a href="#Section1">Open section</a></p>');
|
||||
const file = new File([blob], "Bookmark.docx", {
|
||||
type: "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
|
||||
});
|
||||
const imported = await importDocxFile(file);
|
||||
|
||||
expect(imported.html).toContain('<h1 id="Section1">Section</h1>');
|
||||
expect(imported.html).toContain('<a href="#Section1">Open section</a>');
|
||||
expect(htmlToWordBlocks(imported.html)).toEqual([
|
||||
{ type: "heading", level: 1, text: "Section", runs: [{ text: "Section" }], bookmark: "Section1" },
|
||||
{ type: "paragraph", text: "Open section", runs: [{ text: "Open section", href: "#Section1" }] }
|
||||
]);
|
||||
});
|
||||
|
||||
it("imports simple DOCX tables from OOXML", async () => {
|
||||
const blob = await exportDocxBlob(
|
||||
"Table.docx",
|
||||
|
||||
Reference in New Issue
Block a user