Preserve QWord tabs in DOCX

This commit is contained in:
Курнат Андрей
2026-06-01 12:40:37 +03:00
parent 3700a39434
commit 8517bd6391
4 changed files with 93 additions and 16 deletions
+53 -14
View File
@@ -84,6 +84,7 @@ type DocxModule = {
Table: new (options: Record<string, unknown>) => unknown;
TableCell: new (options: Record<string, unknown>) => unknown;
TableRow: new (options: Record<string, unknown>) => unknown;
Tab?: new () => unknown;
TextRun: new (options: string | Record<string, unknown>) => unknown;
WidthType?: Record<string, string>;
ExternalHyperlink?: new (options: { children: unknown[]; link: string }) => unknown;
@@ -401,21 +402,39 @@ function wordInlineRunToTextRunsForRun(run: WordInlineRun, docx: DocxModule, opt
const text = String(option.text ?? "");
const baseOption = { ...option };
delete baseOption.text;
const parts = text.split("\n");
const lines = text.split("\n");
const textRuns: unknown[] = [];
parts.forEach((part, index) => {
lines.forEach((line, 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 }));
if (line || lines.length === 1) {
textRuns.push(wordInlineTextRunForSegment(line, docx, baseOption));
}
});
return textRuns;
}
function wordInlineTextRunForSegment(text: string, docx: DocxModule, baseOption: Record<string, unknown>) {
if (!text.includes("\t") || !docx.Tab) {
return new docx.TextRun({ ...baseOption, text });
}
const children: unknown[] = [];
text.split("\t").forEach((part, index) => {
if (index > 0 && docx.Tab) {
children.push(new docx.Tab());
}
if (part) {
children.push(part);
}
});
return new docx.TextRun({ ...baseOption, children });
}
function docxAlignmentOption(alignment: WordParagraphAlignment | undefined, docx: DocxModule) {
const value = docxAlignmentValue(alignment, docx);
return value ? { alignment: value } : {};
@@ -626,7 +645,12 @@ 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.hasLineBreak
return result.hasInlineColorOrHighlight ||
result.hasParagraphAlignment ||
result.hasTable ||
result.hasImage ||
result.hasLineBreak ||
result.hasTab
? result.html
: "";
} catch {
@@ -650,6 +674,7 @@ function orderedDocxDocumentToHtml(
let hasTable = false;
let hasImage = false;
let hasLineBreak = false;
let hasTab = false;
const blocks = orderedElementChildren(body)
.flatMap((block) => {
const name = orderedElementName(block);
@@ -659,6 +684,7 @@ function orderedDocxDocumentToHtml(
hasParagraphAlignment = hasParagraphAlignment || result.hasParagraphAlignment;
hasImage = hasImage || result.hasImage;
hasLineBreak = hasLineBreak || result.hasLineBreak;
hasTab = hasTab || result.hasTab;
return result.html ? [result.html] : [];
}
if (name === "w:tbl") {
@@ -666,6 +692,7 @@ function orderedDocxDocumentToHtml(
hasTable = hasTable || Boolean(result.html);
hasImage = hasImage || result.hasImage;
hasLineBreak = hasLineBreak || result.hasLineBreak;
hasTab = hasTab || result.hasTab;
return result.html ? [result.html] : [];
}
@@ -678,7 +705,8 @@ function orderedDocxDocumentToHtml(
hasParagraphAlignment,
hasTable,
hasImage,
hasLineBreak
hasLineBreak,
hasTab
};
}
@@ -694,17 +722,19 @@ function orderedDocxParagraphToHtml(
let hasInlineColorOrHighlight = false;
let hasImage = false;
let hasLineBreak = false;
let hasTab = false;
const runs = orderedDocxParagraphInlineRecords(paragraph, hyperlinkTargets).map((inline) => {
const result = docxRunToHtml(inline.run, imageDataByRelationshipId, inline.text);
hasInlineColorOrHighlight = hasInlineColorOrHighlight || result.hasInlineColorOrHighlight || Boolean(inline.href);
hasImage = hasImage || result.hasImage;
hasLineBreak = hasLineBreak || result.hasLineBreak;
hasTab = hasTab || result.hasTab;
return inline.href && result.html ? `<a href="${escapeHtml(inline.href)}">${result.html}</a>` : result.html;
});
const content = runs.join("");
if (!content.trim()) {
return { html: "", hasInlineColorOrHighlight, hasParagraphAlignment, hasImage, hasLineBreak };
return { html: "", hasInlineColorOrHighlight, hasParagraphAlignment, hasImage, hasLineBreak, hasTab };
}
return {
@@ -712,7 +742,8 @@ function orderedDocxParagraphToHtml(
hasInlineColorOrHighlight,
hasParagraphAlignment,
hasImage,
hasLineBreak
hasLineBreak,
hasTab
};
}
@@ -723,6 +754,7 @@ function orderedDocxTableToHtml(
) {
let hasImage = false;
let hasLineBreak = false;
let hasTab = false;
const rows = orderedDirectElements(table, "w:tr")
.map((row) => {
const cells = orderedDirectElements(row, "w:tc")
@@ -732,6 +764,7 @@ function orderedDocxTableToHtml(
const result = orderedDocxParagraphToHtml(paragraph, hyperlinkTargets, imageDataByRelationshipId);
hasImage = hasImage || result.hasImage;
hasLineBreak = hasLineBreak || result.hasLineBreak;
hasTab = hasTab || result.hasTab;
return result.html;
})
.filter(Boolean);
@@ -744,7 +777,7 @@ function orderedDocxTableToHtml(
})
.filter(Boolean);
return { html: rows.length > 0 ? `<table><tbody>${rows.join("")}</tbody></table>` : "", hasImage, hasLineBreak };
return { html: rows.length > 0 ? `<table><tbody>${rows.join("")}</tbody></table>` : "", hasImage, hasLineBreak, hasTab };
}
function orderedDocxCellText(cell: unknown) {
@@ -961,10 +994,11 @@ function docxRunToHtml(run: unknown, imageDataByRelationshipId: DocxImageDataByR
const hasStrike = hasDocxBoolean(properties, "w:strike") || hasDocxBoolean(properties, "w:dstrike");
const hasInlineColorOrHighlight = Boolean(color || highlightColor || fontSize || fontFamily || hasStrike);
const hasLineBreak = text.includes("\n");
const hasTab = text.includes("\t");
let html = escapeHtmlDocxText(text);
if (!text && !imageHtml) {
return { html: "", hasInlineColorOrHighlight, hasImage: false, hasLineBreak };
return { html: "", hasInlineColorOrHighlight, hasImage: false, hasLineBreak, hasTab };
}
if (text) {
@@ -993,7 +1027,7 @@ function docxRunToHtml(run: unknown, imageDataByRelationshipId: DocxImageDataByR
}
}
return { html: `${imageHtml}${text ? html : ""}`, hasInlineColorOrHighlight, hasImage: Boolean(imageHtml), hasLineBreak };
return { html: `${imageHtml}${text ? html : ""}`, hasInlineColorOrHighlight, hasImage: Boolean(imageHtml), hasLineBreak, hasTab };
}
function docxRunImageHtml(run: XmlRecord, imageDataByRelationshipId: DocxImageDataByRelationshipId) {
@@ -1220,7 +1254,7 @@ function escapeHtml(value: string) {
}
function escapeHtmlDocxText(value: string) {
return escapeHtml(value).replace(/\n/g, "<br>");
return escapeHtml(value).replace(/\t/g, '<span data-qoffice-tab="true" style="white-space: pre;">\t</span>').replace(/\n/g, "<br>");
}
function collectInlineRuns(nodes: ChildNode[], format: InlineFormat): WordInlineRun[] {
@@ -1242,6 +1276,10 @@ function collectInlineSegments(nodes: ChildNode[], format: InlineFormat): Inline
return [{ type: "runs", runs: [{ text: "\n", ...format }] }];
}
if (node.getAttribute("data-qoffice-tab") === "true") {
return [{ type: "runs", runs: [{ text: "\t", ...format }] }];
}
if (node.tagName.toLowerCase() === "img") {
return [{ type: "image", image: imageBlockFromElement(node) }];
}
@@ -1548,8 +1586,9 @@ function normalizeInlineWhitespace(value: string) {
function normalizeInlineRunText(value: string) {
return value
.replace(/\u00a0/g, " ")
.replace(/[^\S\n]+/g, " ")
.replace(/ *\n */g, "\n");
.replace(/[^\S\n\t]+/g, " ")
.replace(/ *\n */g, "\n")
.replace(/ *\t */g, "\t");
}
async function loadMammoth() {