Import QWord DOCX lists from numbering
This commit is contained in:
+154
-34
@@ -104,6 +104,8 @@ type InlineFormat = Omit<WordInlineRun, "text">;
|
||||
type InlineSegment = { type: "runs"; runs: WordInlineRun[] } | { type: "image"; image: WordImageBlock };
|
||||
type DocxInlineRecord = { run: unknown; text: string; href?: string };
|
||||
type DocxImageDataByRelationshipId = Record<string, string>;
|
||||
type DocxNumberingDefinitions = Record<string, { ordered: boolean }>;
|
||||
type DocxListInfo = { ordered: boolean; level: number; key: string };
|
||||
|
||||
const mammothStyleMap = [
|
||||
"p[style-name='Title'] => h1:fresh",
|
||||
@@ -772,8 +774,10 @@ async function styledDocxHtmlFromArrayBuffer(arrayBuffer: ArrayBuffer) {
|
||||
const orderedParser = new XMLParser({ ...xmlParserOptions, preserveOrder: true });
|
||||
const relationshipsXml = await zip.file("word/_rels/document.xml.rels")?.async("string");
|
||||
const relationshipTargets = relationshipsXml ? docxRelationshipTargetsById(parser.parse(relationshipsXml)) : emptyDocxRelationshipTargets;
|
||||
const numberingXml = await zip.file("word/numbering.xml")?.async("string");
|
||||
const numberingDefinitions = numberingXml ? docxNumberingDefinitions(parser.parse(numberingXml)) : {};
|
||||
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, numberingDefinitions);
|
||||
return result.hasInlineColorOrHighlight ||
|
||||
result.hasParagraphAlignment ||
|
||||
result.hasBookmark ||
|
||||
@@ -781,7 +785,8 @@ async function styledDocxHtmlFromArrayBuffer(arrayBuffer: ArrayBuffer) {
|
||||
result.hasImage ||
|
||||
result.hasLineBreak ||
|
||||
result.hasPageBreak ||
|
||||
result.hasTab
|
||||
result.hasTab ||
|
||||
result.hasList
|
||||
? result.html
|
||||
: "";
|
||||
} catch {
|
||||
@@ -790,13 +795,14 @@ async function styledDocxHtmlFromArrayBuffer(arrayBuffer: ArrayBuffer) {
|
||||
}
|
||||
|
||||
function isSimpleStyledDocxDocument(documentXml: string) {
|
||||
return !/<w:(pict|numPr|sdt)\b/i.test(documentXml);
|
||||
return !/<w:(pict|sdt)\b/i.test(documentXml);
|
||||
}
|
||||
|
||||
function orderedDocxDocumentToHtml(
|
||||
documentXml: unknown,
|
||||
hyperlinkTargets: Record<string, string> = {},
|
||||
imageDataByRelationshipId: DocxImageDataByRelationshipId = {}
|
||||
imageDataByRelationshipId: DocxImageDataByRelationshipId = {},
|
||||
numberingDefinitions: DocxNumberingDefinitions = {}
|
||||
) {
|
||||
const document = firstOrderedElement(toArray(documentXml), "w:document");
|
||||
const body = firstOrderedElement(orderedElementChildren(document), "w:body");
|
||||
@@ -808,32 +814,69 @@ function orderedDocxDocumentToHtml(
|
||||
let hasLineBreak = false;
|
||||
let hasPageBreak = false;
|
||||
let hasTab = false;
|
||||
const blocks = orderedElementChildren(body)
|
||||
.flatMap((block) => {
|
||||
const name = orderedElementName(block);
|
||||
if (name === "w:p") {
|
||||
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;
|
||||
hasTab = hasTab || result.hasTab;
|
||||
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;
|
||||
hasPageBreak = hasPageBreak || result.hasPageBreak;
|
||||
hasTab = hasTab || result.hasTab;
|
||||
return result.html ? [result.html] : [];
|
||||
let hasList = false;
|
||||
const blocks: string[] = [];
|
||||
let openList: DocxListInfo | null = null;
|
||||
let listItems: string[] = [];
|
||||
|
||||
const flushList = () => {
|
||||
if (!openList || listItems.length === 0) {
|
||||
openList = null;
|
||||
listItems = [];
|
||||
return;
|
||||
}
|
||||
|
||||
const tagName = openList.ordered ? "ol" : "ul";
|
||||
blocks.push(`<${tagName}>${listItems.join("")}</${tagName}>`);
|
||||
openList = null;
|
||||
listItems = [];
|
||||
};
|
||||
|
||||
orderedElementChildren(body).forEach((block) => {
|
||||
const name = orderedElementName(block);
|
||||
if (name === "w:p") {
|
||||
const result = orderedDocxParagraphToHtml(block, hyperlinkTargets, imageDataByRelationshipId, numberingDefinitions);
|
||||
hasInlineColorOrHighlight = hasInlineColorOrHighlight || result.hasInlineColorOrHighlight;
|
||||
hasParagraphAlignment = hasParagraphAlignment || result.hasParagraphAlignment;
|
||||
hasBookmark = hasBookmark || result.hasBookmark;
|
||||
hasImage = hasImage || result.hasImage;
|
||||
hasLineBreak = hasLineBreak || result.hasLineBreak;
|
||||
hasPageBreak = hasPageBreak || result.hasPageBreak;
|
||||
hasTab = hasTab || result.hasTab;
|
||||
hasList = hasList || Boolean(result.list);
|
||||
|
||||
if (!result.html) {
|
||||
return;
|
||||
}
|
||||
|
||||
return [];
|
||||
});
|
||||
if (result.list) {
|
||||
if (!openList || openList.key !== result.list.key) {
|
||||
flushList();
|
||||
openList = result.list;
|
||||
}
|
||||
listItems.push(result.html);
|
||||
return;
|
||||
}
|
||||
|
||||
flushList();
|
||||
blocks.push(result.html);
|
||||
return;
|
||||
}
|
||||
|
||||
if (name === "w:tbl") {
|
||||
flushList();
|
||||
const result = orderedDocxTableToHtml(block, hyperlinkTargets, imageDataByRelationshipId, numberingDefinitions);
|
||||
hasTable = hasTable || Boolean(result.html);
|
||||
hasImage = hasImage || result.hasImage;
|
||||
hasLineBreak = hasLineBreak || result.hasLineBreak;
|
||||
hasPageBreak = hasPageBreak || result.hasPageBreak;
|
||||
hasTab = hasTab || result.hasTab;
|
||||
if (result.html) {
|
||||
blocks.push(result.html);
|
||||
}
|
||||
}
|
||||
});
|
||||
flushList();
|
||||
|
||||
return {
|
||||
html: blocks.join(""),
|
||||
@@ -844,19 +887,22 @@ function orderedDocxDocumentToHtml(
|
||||
hasImage,
|
||||
hasLineBreak,
|
||||
hasPageBreak,
|
||||
hasTab
|
||||
hasTab,
|
||||
hasList
|
||||
};
|
||||
}
|
||||
|
||||
function orderedDocxParagraphToHtml(
|
||||
paragraph: unknown,
|
||||
hyperlinkTargets: Record<string, string>,
|
||||
imageDataByRelationshipId: DocxImageDataByRelationshipId = {}
|
||||
imageDataByRelationshipId: DocxImageDataByRelationshipId = {},
|
||||
numberingDefinitions: DocxNumberingDefinitions = {}
|
||||
) {
|
||||
const properties = orderedElementToRecord(firstOrderedElement(orderedElementChildren(paragraph), "w:pPr"));
|
||||
const tagName = docxParagraphTagName(properties);
|
||||
const style = docxParagraphStyleAttribute(properties);
|
||||
const bookmark = orderedDocxParagraphBookmark(paragraph);
|
||||
const list = docxParagraphListInfo(properties, numberingDefinitions);
|
||||
const hasParagraphAlignment = Boolean(style);
|
||||
const hasBookmark = Boolean(bookmark);
|
||||
let hasInlineColorOrHighlight = false;
|
||||
@@ -876,10 +922,23 @@ function orderedDocxParagraphToHtml(
|
||||
const content = runs.join("");
|
||||
|
||||
if (!content.trim()) {
|
||||
return { html: "", hasInlineColorOrHighlight, hasParagraphAlignment, hasBookmark, hasImage, hasLineBreak, hasPageBreak, hasTab };
|
||||
return { html: "", hasInlineColorOrHighlight, hasParagraphAlignment, hasBookmark, hasImage, hasLineBreak, hasPageBreak, hasTab, list };
|
||||
}
|
||||
|
||||
const attributes = [style ? `style="${style}"` : "", bookmark ? `id="${escapeHtml(bookmark)}"` : ""].filter(Boolean).join(" ");
|
||||
if (list) {
|
||||
return {
|
||||
html: `<li${attributes ? ` ${attributes}` : ""}>${content}</li>`,
|
||||
hasInlineColorOrHighlight,
|
||||
hasParagraphAlignment,
|
||||
hasBookmark,
|
||||
hasImage,
|
||||
hasLineBreak,
|
||||
hasPageBreak,
|
||||
hasTab,
|
||||
list
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
html: `<${tagName}${attributes ? ` ${attributes}` : ""}>${content}</${tagName}>`,
|
||||
@@ -889,14 +948,16 @@ function orderedDocxParagraphToHtml(
|
||||
hasImage,
|
||||
hasLineBreak,
|
||||
hasPageBreak,
|
||||
hasTab
|
||||
hasTab,
|
||||
list
|
||||
};
|
||||
}
|
||||
|
||||
function orderedDocxTableToHtml(
|
||||
table: unknown,
|
||||
hyperlinkTargets: Record<string, string>,
|
||||
imageDataByRelationshipId: DocxImageDataByRelationshipId = {}
|
||||
imageDataByRelationshipId: DocxImageDataByRelationshipId = {},
|
||||
numberingDefinitions: DocxNumberingDefinitions = {}
|
||||
) {
|
||||
let hasImage = false;
|
||||
let hasLineBreak = false;
|
||||
@@ -908,7 +969,7 @@ function orderedDocxTableToHtml(
|
||||
.map((cell) => {
|
||||
const paragraphs = orderedDirectElements(cell, "w:p")
|
||||
.map((paragraph) => {
|
||||
const result = orderedDocxParagraphToHtml(paragraph, hyperlinkTargets, imageDataByRelationshipId);
|
||||
const result = orderedDocxParagraphToHtml(paragraph, hyperlinkTargets, imageDataByRelationshipId, numberingDefinitions);
|
||||
hasImage = hasImage || result.hasImage;
|
||||
hasLineBreak = hasLineBreak || result.hasLineBreak;
|
||||
hasPageBreak = hasPageBreak || result.hasPageBreak;
|
||||
@@ -970,6 +1031,65 @@ function docxParagraphIndentStyles(properties: XmlRecord) {
|
||||
].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");
|
||||
if (!numId) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const level = normalizedNumberingLevel(docxAttribute(childRecord(numbering, "w:ilvl"), "w:val"));
|
||||
const definition = numberingDefinitions[`${numId}:${level}`] ?? numberingDefinitions[`${numId}:0`];
|
||||
const ordered = definition?.ordered ?? false;
|
||||
return {
|
||||
ordered,
|
||||
level,
|
||||
key: `${ordered ? "ol" : "ul"}:${numId}:${level}`
|
||||
};
|
||||
}
|
||||
|
||||
function docxNumberingDefinitions(numberingXml: unknown): DocxNumberingDefinitions {
|
||||
const numbering = childRecord(numberingXml, "w:numbering");
|
||||
const abstractFormats: Record<string, Record<number, { ordered: boolean }>> = {};
|
||||
|
||||
toArray(numbering["w:abstractNum"]).forEach((abstractNumbering) => {
|
||||
const abstractRecord = asRecord(abstractNumbering);
|
||||
const abstractId = docxAttribute(abstractRecord, "w:abstractNumId");
|
||||
if (!abstractId) {
|
||||
return;
|
||||
}
|
||||
|
||||
const levels = toArray(abstractRecord["w:lvl"]).reduce<Record<number, { ordered: boolean }>>((formats, levelRecord) => {
|
||||
const level = asRecord(levelRecord);
|
||||
const levelIndex = normalizedNumberingLevel(docxAttribute(level, "w:ilvl"));
|
||||
const format = docxAttribute(childRecord(level, "w:numFmt"), "w:val").toLowerCase();
|
||||
formats[levelIndex] = { ordered: format !== "bullet" };
|
||||
return formats;
|
||||
}, {});
|
||||
|
||||
abstractFormats[abstractId] = levels;
|
||||
});
|
||||
|
||||
return toArray(numbering["w:num"]).reduce<DocxNumberingDefinitions>((definitions, numRecord) => {
|
||||
const numberingRecord = asRecord(numRecord);
|
||||
const numId = docxAttribute(numberingRecord, "w:numId");
|
||||
const abstractId = docxAttribute(childRecord(numberingRecord, "w:abstractNumId"), "w:val");
|
||||
if (!numId || !abstractId) {
|
||||
return definitions;
|
||||
}
|
||||
|
||||
Object.entries(abstractFormats[abstractId] ?? {}).forEach(([level, definition]) => {
|
||||
definitions[`${numId}:${level}`] = definition;
|
||||
});
|
||||
return definitions;
|
||||
}, {});
|
||||
}
|
||||
|
||||
function normalizedNumberingLevel(value: unknown) {
|
||||
const level = Number.parseInt(String(value ?? ""), 10);
|
||||
return Number.isFinite(level) && level >= 0 ? Math.min(level, 8) : 0;
|
||||
}
|
||||
|
||||
function orderedDocxParagraphBookmark(paragraph: unknown) {
|
||||
const bookmarkStart = firstOrderedElement(orderedElementChildren(paragraph), "w:bookmarkStart");
|
||||
return normalizedDocxAnchor(docxAttribute(orderedElementAttributes(bookmarkStart), "w:name") || docxAttribute(orderedElementAttributes(bookmarkStart), "name"));
|
||||
|
||||
Reference in New Issue
Block a user