From 14ecf9b69e4745fffd6d4bb54c6b33ec370954a7 Mon Sep 17 00:00:00 2001 From: lqtdys Date: Tue, 15 Sep 2026 01:42:57 +0800 Subject: [PATCH] =?UTF-8?q?fix(docx):=20=E4=BF=AE=E5=A4=8D=20docx=20?= =?UTF-8?q?=E5=AF=BC=E5=87=BA=E7=AC=AC=E4=BA=8C=E8=BD=AE=208=20=E9=A1=B9?= =?UTF-8?q?=E8=B4=A8=E9=87=8F=E9=97=AE=E9=A2=98=EF=BC=88=E5=8D=95=E5=85=83?= =?UTF-8?q?=E6=A0=BC=E8=A1=8C=E5=86=85=E4=B8=A2=E5=A4=B1/=E5=88=97?= =?UTF-8?q?=E5=AE=BD/=E7=8B=AC=E7=AB=8B=E7=BC=96=E5=8F=B7/emoji/=E9=97=B4?= =?UTF-8?q?=E8=B7=9D/=E9=97=B4=E9=9A=94=E7=BA=BF/callout=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 表格数据单元格:行内子节点统一「单段落 + inlineChildren」序列化,修复 **P0** 纯粗体单元格空白与 text+inlineCode 拆段 - 列宽:extractCellText 补采 inlineCode/math/image-alt 文本;分配算法改为 内容×120+220 起步、min 800、总和恒 9026;超页宽按 min+超出等比压缩;列数≥12 负预算退化为比例缩放 - 编号:每个有序列表独占 abstractNum(id==numId),WPS 不再跨列表续计数;start≠1 保留 startOverride - emoji:docx 文本 run 清除 astral emoji(1F000–1FAFF)+ FE0E/FE0F + ZWJ,保留 BMP 符号;无 emoji 文本不受影响 - 单元格段落显式 before=0/after=0/单倍行距;表头 tcPr 顺序修正 tcW→shd→vAlign;tblPr 顺序修正 tblBorders→tblLayout - 删除 --- 水平线输出(thematicBreak 不产出) - callout:标题与正文分段落(标题加粗、正文常规);头段 pPr 顺序修正 spacing " ') */ function esc(s: string): string { - return s.replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c]!); + return s.replace( + /[&<>"']/g, + (c) => + ({ + '&': '&', + '<': '<', + '>': '>', + '"': '"', + "'": ''', + })[c]! + ); } /** raw HTML 降级:script/style 元素整体丢弃,其余输出字面量文本(无执行面) */ @@ -188,20 +202,53 @@ function splitMathInInline(node: { type: string; children: unknown[] }): void { * 未知键 → 保持 blockquote 原样。 */ const CALLOUT_TYPES = new Set([ - 'NOTE', 'TIP', 'INFO', 'WARNING', 'CAUTION', 'IMPORTANT', 'DANGER', 'SUCCESS', 'HELP', 'FAQ', - 'ABSTRACT', 'SUMMARY', 'TLDR', 'TODO', 'QUOTE', 'CITATION', 'EXAMPLE', - 'FAILURE', 'ERROR', 'BUG', 'QUESTION', 'HINT', + 'NOTE', + 'TIP', + 'INFO', + 'WARNING', + 'CAUTION', + 'IMPORTANT', + 'DANGER', + 'SUCCESS', + 'HELP', + 'FAQ', + 'ABSTRACT', + 'SUMMARY', + 'TLDR', + 'TODO', + 'QUOTE', + 'CITATION', + 'EXAMPLE', + 'FAILURE', + 'ERROR', + 'BUG', + 'QUESTION', + 'HINT', ]); // Callout 类型 → [背景色, 左边框色](GFM alert + Obsidian 主题近似色) const CALLOUT_COLORS: Record = { - NOTE: ['F0F7FA', '6C9DBF'], INFO: ['F0F7FA', '6C9DBF'], ABSTRACT: ['F0F7FA', '6C9DBF'], - SUMMARY: ['F0F7FA', '6C9DBF'], TLDR: ['F0F7FA', '6C9DBF'], - TIP: ['ECF7EC', '5F9B5F'], HINT: ['ECF7EC', '5F9B5F'], SUCCESS: ['ECF7EC', '5F9B5F'], - WARNING: ['FCF8E8', 'C2A053'], CAUTION: ['FCF8E8', 'C2A053'], - DANGER: ['FBEDEB', 'BB5B4C'], FAILURE: ['FBEDEB', 'BB5B4C'], ERROR: ['FBEDEB', 'BB5B4C'], BUG: ['FBEDEB', 'BB5B4C'], - IMPORTANT: ['F3EFFA', '7A6CB0'], QUESTION: ['F0F0FA', '6B6BC0'], HELP: ['F0F0FA', '6B6BC0'], FAQ: ['F0F0FA', '6B6BC0'], - EXAMPLE: ['F6F0FA', '9660B8'], QUOTE: ['F5F5F5', '808080'], CITATION: ['F5F5F5', '808080'], + NOTE: ['F0F7FA', '6C9DBF'], + INFO: ['F0F7FA', '6C9DBF'], + ABSTRACT: ['F0F7FA', '6C9DBF'], + SUMMARY: ['F0F7FA', '6C9DBF'], + TLDR: ['F0F7FA', '6C9DBF'], + TIP: ['ECF7EC', '5F9B5F'], + HINT: ['ECF7EC', '5F9B5F'], + SUCCESS: ['ECF7EC', '5F9B5F'], + WARNING: ['FCF8E8', 'C2A053'], + CAUTION: ['FCF8E8', 'C2A053'], + DANGER: ['FBEDEB', 'BB5B4C'], + FAILURE: ['FBEDEB', 'BB5B4C'], + ERROR: ['FBEDEB', 'BB5B4C'], + BUG: ['FBEDEB', 'BB5B4C'], + IMPORTANT: ['F3EFFA', '7A6CB0'], + QUESTION: ['F0F0FA', '6B6BC0'], + HELP: ['F0F0FA', '6B6BC0'], + FAQ: ['F0F0FA', '6B6BC0'], + EXAMPLE: ['F6F0FA', '9660B8'], + QUOTE: ['F5F5F5', '808080'], + CITATION: ['F5F5F5', '808080'], TODO: ['EFF7F3', '5F9B8A'], }; const CALLOUT_DEFAULT: [string, string] = ['F0F7FA', '6C9DBF']; @@ -211,15 +258,21 @@ function extractCallouts(tree: { type: string; children?: unknown[] }): void { for (let i = 0; i < tree.children.length; i++) { const node = tree.children[i] as { type: string; children?: unknown[] }; if (node.type !== 'blockquote' || !node.children || node.children.length === 0) continue; - const firstChild = node.children[0] as { type: string; children?: unknown[] }; + const firstChild = node.children[0] as { + type: string; + children?: unknown[]; + }; if (firstChild.type !== 'paragraph' || !firstChild.children) continue; - const firstText = firstChild.children[0] as { type: string; value?: string }; + const firstText = firstChild.children[0] as { + type: string; + value?: string; + }; if (firstText.type !== 'text' || typeof firstText.value !== 'string') continue; - const m = firstText.value.match(/^\[!([A-Za-z]+)\]\s*/); + const m = firstText.value.match(/^\[!([A-Za-z]+)\][ \t]*/); if (!m) continue; const tag = m[1].toUpperCase(); if (!CALLOUT_TYPES.has(tag)) continue; - // 剩余内容 = 标识之后的全部文本(同行标题 + 换行后的正文),slice 保留 \n 分隔 + // 剩余内容 = 标识之后的全部文本(同行标题 + 换行后的正文),保留 \n 以支持标题/正文分段 const remainingText = firstText.value.slice(m[0].length); if (remainingText) { firstText.value = remainingText; @@ -232,6 +285,26 @@ function extractCallouts(tree: { type: string; children?: unknown[] }): void { } } +/** docx 文本 run 后处理:清除 astral emoji(U+1F000–U+1FAFF)+ 变体选择符 + ZWJ;BMP 符号保留 */ +function stripEmoji(s: string): string { + let out = ''; + let removed = false; + for (const ch of s) { + const cp = ch.codePointAt(0) ?? 0; + if (cp >= 0x1f000 && cp <= 0x1faff) { + removed = true; + continue; + } + if (cp === 0xfe0e || cp === 0xfe0f || cp === 0x200d) { + removed = true; + continue; + } + out += ch; + } + if (!removed) return s; + return out.replace(/ {2,}/g, ' ').trim(); +} + /** 行内子节点序列化(段落/标题内容),fmt 逐层传递(strong/em/link 等嵌套格式) */ function inlineChildren(children: unknown[], ctx: Ctx, fmt: RunFmt = {}): string { return children.map((c) => inlineToXml(c as never, ctx, fmt)).join(''); @@ -248,18 +321,34 @@ function inlineToXml(node: { type: string; [k: string]: unknown }, ctx: Ctx, fmt case 'text': { let text = String(node.value ?? ''); if (ctx.symbols) text = unguard(replaceSymbols(text)); // 哨兵还原 + 符号转换 + text = stripEmoji(text); // docx 文本 run 清除 astral emoji(BMP 符号保留) return textToRuns(text, fmt); } - case 'strong': return inlineChildren(node.children as never[], ctx, { ...fmt, b: true }); - case 'emphasis': return inlineChildren(node.children as never[], ctx, { ...fmt, i: true }); - case 'delete': return inlineChildren(node.children as never[], ctx, { ...fmt, strike: true }); - case 'inlineCode': return codeRun(String(node.value ?? ''), fmt); + case 'strong': + return inlineChildren(node.children as never[], ctx, { ...fmt, b: true }); + case 'emphasis': + return inlineChildren(node.children as never[], ctx, { ...fmt, i: true }); + case 'delete': + return inlineChildren(node.children as never[], ctx, { + ...fmt, + strike: true, + }); + case 'inlineCode': + return codeRun(String(node.value ?? ''), fmt); case 'link': { const url = String(node.url ?? ''); if (isExternal(url)) { const rId = `rId${ctx.nextRid++}`; - ctx.rels.push({ id: rId, type: 'hyperlink', target: url, external: true }); - return inlineChildren(node.children as never[], ctx, { ...fmt, link: rId }); + ctx.rels.push({ + id: rId, + type: 'hyperlink', + target: url, + external: true, + }); + return inlineChildren(node.children as never[], ctx, { + ...fmt, + link: rId, + }); } // 内部锚点/相对链接:无关系可建,按普通文本输出(保留字面目标) return inlineChildren(node.children as never[], ctx, fmt); @@ -269,10 +358,14 @@ function inlineToXml(node: { type: string; [k: string]: unknown }, ctx: Ctx, fmt if (mathNode.display) return ''; return textToRuns(String(mathNode.value ?? ''), fmt); } - case 'image': return imageToXml(node as never, ctx, fmt); - case 'break': return `${rPrXml(fmt)}`; - case 'html': return textToRuns(degradeHtml(String(node.value ?? '')), fmt); - case 'footnoteReference': return textToRuns(`[^${String(node.identifier ?? '')}]`, fmt); + case 'image': + return imageToXml(node as never, ctx, fmt); + case 'break': + return `${rPrXml(fmt)}`; + case 'html': + return textToRuns(degradeHtml(String(node.value ?? '')), fmt); + case 'footnoteReference': + return textToRuns(`[^${String(node.identifier ?? '')}]`, fmt); default: { // 未知行内节点:尽力输出其文本内容,避免内容丢失 const v = (node as { value?: unknown }).value; @@ -312,7 +405,11 @@ function imageToXml(node: { url?: unknown; alt?: unknown }, ctx: Ctx, fmt: RunFm const rId = `rId${ctx.nextRid++}`; // 关系 Target 以 word/_rels/document.xml.rels 为基准(相对 word/),必须写 media/img-1.png; // 写 word/media/… 会被解析为 word/word/media/…,图片显示空白占位。 - ctx.rels.push({ id: rId, type: 'image', target: mediaPath.replace(/^word\//, '') }); + ctx.rels.push({ + id: rId, + type: 'image', + target: mediaPath.replace(/^word\//, ''), + }); // 固有尺寸换算:EMU = px * 9525(96dpi);保持宽高比缩放进 imageWidthEmu const EMU_PER_PX = 9525; const intrinsic = readImageSize(data); @@ -326,9 +423,7 @@ function imageToXml(node: { url?: unknown; alt?: unknown }, ctx: Ctx, fmt: RunFm } else { const fullW = intrinsic.width * EMU_PER_PX; w = Math.min(fullW, ctx.imageWidthEmu); - h = ctx.explicitImageHeight - ? ctx.imageHeightEmu - : Math.round(w * (intrinsic.height / intrinsic.width)); + h = ctx.explicitImageHeight ? ctx.imageHeightEmu : Math.round(w * (intrinsic.height / intrinsic.width)); } } else { w = ctx.imageWidthEmu; @@ -372,7 +467,11 @@ function serializeList(node: { ordered?: unknown; start?: unknown; children?: un } let out = ''; (node.children ?? []).forEach((item) => { - const it = item as { type?: string; checked?: unknown; children?: unknown[] }; + const it = item as { + type?: string; + checked?: unknown; + children?: unknown[]; + }; if (it.type !== 'listItem') return; const checked = typeof it.checked === 'boolean' ? (it.checked ? '☑ ' : '☐ ') : ''; const numPr = ``; @@ -382,7 +481,10 @@ function serializeList(node: { ordered?: unknown; start?: unknown; children?: un out += serializeList(child as never, ctx, ilvl + 1); continue; } - out += blockToXml(child as never, ctx, { numPr, prefix: first ? checked : undefined }); + out += blockToXml(child as never, ctx, { + numPr, + prefix: first ? checked : undefined, + }); first = false; } }); @@ -393,7 +495,12 @@ function serializeList(node: { ordered?: unknown; start?: unknown; children?: un function splitParagraphAtBlockMath( node: { children: unknown[] }, ctx: Ctx, - extra?: { numPr?: string; prefix?: string; style?: string; headerBold?: boolean }, + extra?: { + numPr?: string; + prefix?: string; + style?: string; + headerBold?: boolean; + } ): string { const pStyle = extra?.style ?? (extra?.numPr ? 'ListParagraph' : ''); const pPr = `${pStyle ? `` : ''}${extra?.numPr ?? ''}`; @@ -421,49 +528,71 @@ function splitParagraphAtBlockMath( return out || `${pPr ? `${pPr}` : ''}${prefix}`; } -/** callout 注入片段:左边框 + 背景色 + 左缩进(pBdr/shd/ind 顺序符合 pPr schema) */ -function calloutPPr(extra?: { callout?: { fill: string; border: string } }): string { +/** callout 注入片段:左边框 + 背景色 + 可选 spacing + 缩进(pBdr/shd/spacing/ind 顺序符合 pPr schema) */ +function calloutPPr(extra?: { callout?: { fill: string; border: string }; headSpacing?: boolean }): string { if (!extra?.callout) return ''; const { fill, border } = extra.callout; - return ``; + const spacing = extra.headSpacing ? '' : ''; + return `${spacing}`; } -/** callout 首段:首个 \n 前为标题(加粗),其后正文保持常规格式 */ -function calloutHeadXml(children: unknown[], ctx: Ctx): string { - let out = ''; - let headDone = false; +/** + * callout 首段拆分:在第一个含 \n 的 text 节点处切分为 [headNodes, bodyNodes]。 + * 若无 \n:全部作为 headNodes(加粗),bodyNodes 为空。 + * 返回 { head, body } 两个 inline 节点数组。 + */ +function splitCalloutHead(children: unknown[], ctx: Ctx): { head: unknown[]; body: unknown[] } { + const head: unknown[] = []; + const body: unknown[] = []; + let splitDone = false; for (const c of children) { const n = c as { type?: string; value?: string }; - if (n.type === 'text' && typeof n.value === 'string' && !headDone) { + if (!splitDone && n.type === 'text' && typeof n.value === 'string') { const nl = n.value.indexOf('\n'); - if (nl === -1) { - out += textToRuns(n.value, { b: true }); - headDone = true; - } else { - const head = n.value.slice(0, nl); - const tail = n.value.slice(nl + 1); - if (head) out += textToRuns(head, { b: true }); - if (tail) out += textToRuns(tail, {}); - headDone = true; + if (nl !== -1) { + const headText = n.value.slice(0, nl); + const bodyText = n.value.slice(nl + 1); + if (headText) head.push({ type: 'text', value: headText }); + if (bodyText) body.push({ type: 'text', value: bodyText }); + splitDone = true; + continue; } + // 无 \n:整段作为 head + head.push(c); + continue; + } + if (splitDone) { + body.push(c); } else { - out += inlineToXml(c as never, ctx, headDone ? {} : { b: true }); + head.push(c); } } - return out; + return { head, body }; } /** 块级节点 → OOXML 段落/表格 XML */ -function blockToXml(node: { type: string; [k: string]: unknown }, ctx: Ctx, extra?: { numPr?: string; prefix?: string; style?: string; headerBold?: boolean; callout?: { fill: string; border: string } }): string { +function blockToXml( + node: { type: string; [k: string]: unknown }, + ctx: Ctx, + extra?: { + numPr?: string; + prefix?: string; + style?: string; + headerBold?: boolean; + callout?: { fill: string; border: string }; + } +): string { switch (node.type) { case 'heading': { const depth = Math.min(6, Math.max(1, Number(node.depth) || 1)); const style = `Heading${depth}`; const hasBlockMath = (node.children as unknown[])?.some( - (c) => (c as { type?: string }).type === 'math' && (c as { display?: boolean }).display, + (c) => (c as { type?: string }).type === 'math' && (c as { display?: boolean }).display ); if (hasBlockMath) { - return splitParagraphAtBlockMath(node as { children: unknown[] }, ctx, { style }); + return splitParagraphAtBlockMath(node as { children: unknown[] }, ctx, { + style, + }); } return `${calloutPPr(extra)}${inlineChildren(node.children as never[], ctx)}`; } @@ -473,12 +602,15 @@ function blockToXml(node: { type: string; [k: string]: unknown }, ctx: Ctx, extr const prefix = extra?.prefix ? plainRun(extra.prefix, {}) : ''; const headerFmt = extra?.headerBold ? headerBoldFmt({}) : {}; const hasBlockMath = (node.children as unknown[])?.some( - (c) => (c as { type?: string }).type === 'math' && (c as { display?: boolean }).display, + (c) => (c as { type?: string }).type === 'math' && (c as { display?: boolean }).display ); if (!hasBlockMath) { return `${pPr ? `${pPr}` : ''}${prefix}${inlineChildren(node.children as never[], ctx, headerFmt)}`; } - return splitParagraphAtBlockMath(node as { children: unknown[] }, ctx, { ...extra, style: pStyle }); + return splitParagraphAtBlockMath(node as { children: unknown[] }, ctx, { + ...extra, + style: pStyle, + }); } case 'code': { // 块级代码:每行一段(CodeBlock 样式,浅灰背景),保留空白;语言标注 [lang] 不作为文字输出 @@ -487,7 +619,8 @@ function blockToXml(node: { type: string; [k: string]: unknown }, ctx: Ctx, extr .map((line) => `${esc(line)}`) .join(''); } - case 'list': return serializeList(node as never, ctx, 0); + case 'list': + return serializeList(node as never, ctx, 0); case 'blockquote': { return (node.children as never[]).map((c) => blockToXml(c as never, ctx, { style: 'Quote' })).join(''); } @@ -497,20 +630,34 @@ function blockToXml(node: { type: string; [k: string]: unknown }, ctx: Ctx, extr const children = (node.children as never[]) ?? []; const first = children[0] as { type?: string; children?: unknown[] } | undefined; const rest = first && first.type === 'paragraph' ? children.slice(1) : children; + const pPr = calloutPPr({ callout: { fill, border } }); let out = ''; if (first && first.type === 'paragraph' && (first.children?.length ?? 0) > 0) { - out += `${calloutPPr({ callout: { fill, border } })}${calloutHeadXml(first.children, ctx)}`; + const { head, body } = splitCalloutHead(first.children, ctx); + if (head.length > 0) { + const headPPr = calloutPPr({ + callout: { fill, border }, + headSpacing: true, + }); + out += `${headPPr}${inlineChildren(head, ctx, { b: true })}`; + } + if (body.length > 0) { + out += `${pPr}${inlineChildren(body, ctx, {})}`; + } } out += rest.map((c) => blockToXml(c as never, ctx, { callout: { fill, border } })).join(''); return out; } case 'thematicBreak': { - // 水平线:段落底部边框 - return ''; + // 水平线:v1 不输出(--- 不产生任何内容) + return ''; } - case 'table': return tableToXml(node as never, ctx); - case 'html': return textToRuns(degradeHtml(String(node.value ?? '')), {}); - case 'footnoteDefinition': return ''; // 脚注定义不输出(引用已降级为 [^label] 文本) + case 'table': + return tableToXml(node as never, ctx); + case 'html': + return textToRuns(degradeHtml(String(node.value ?? '')), {}); + case 'footnoteDefinition': + return ''; // 脚注定义不输出(引用已降级为 [^label] 文本) default: { // 未知块节点:尽力输出其文本内容,避免内容丢失 const v = (node as { value?: unknown }).value; @@ -524,29 +671,52 @@ function tableToXml(node: { children?: unknown[] }, ctx: Ctx): string { const rows = (node.children ?? []).filter((r) => (r as { type?: string }).type === 'tableRow'); const colCount = Math.max(1, ...rows.map((r) => (r as { children?: unknown[] }).children?.length ?? 0)); const colWidths = computeTableColumnWidths(rows as never, colCount); - let out = ''; - out += '' + ['top', 'left', 'bottom', 'right', 'insideH', 'insideV'] - .map((b) => ``).join('') + ''; - out += ''; + const borders = ['top', 'left', 'bottom', 'right', 'insideH', 'insideV']; + const tblBorders = + '' + borders.map((b) => ``).join('') + ''; + let out = '' + tblBorders + ''; + out += + ''; out += ''; - out += `${colWidths.map((w) => ``).join('')}`; + let gridCols = ''; + for (let gi = 0; gi < colWidths.length; gi++) { + gridCols += ''; + } + out += '' + gridCols + ''; rows.forEach((row, ri) => { out += ''; (row as { children?: unknown[] }).children?.forEach((cell, ci) => { const isHeader = ri === 0; out += ''; - out += ``; - out += ''; + out += ''; if (isHeader) out += ''; + out += ''; out += ''; const blocks = (cell as { children?: unknown[] }).children ?? []; if (blocks.length === 0) { out += ''; - } else if (isHeader) { - // 表头单元格:行内子节点序列化时注入 b:true,保留段落/行内结构(strong/em/inlineCode 嵌套格式) - out += `${inlineChildren(blocks, ctx, { b: true })}`; } else { - out += blocks.map((b) => blockToXml(b as never, ctx, { style: 'Table' })).join(''); + const hasBlock = blocks.some((b) => { + const t = (b as { type?: string }).type; + return ( + t === 'paragraph' || + t === 'list' || + t === 'table' || + t === 'code' || + t === 'heading' || + t === 'blockquote' || + t === 'callout' || + t === 'thematicBreak' + ); + }); + if (!hasBlock) { + const cellFmt = isHeader ? { b: true } : {}; + out += '' + SPACING + '' + inlineChildren(blocks, ctx, cellFmt) + ''; + } else if (isHeader) { + out += '' + SPACING + '' + inlineChildren(blocks, ctx, { b: true }) + ''; + } else { + out += blocks.map((b) => blockToXml(b as never, ctx, { style: 'Table' })).join(''); + } } out += ''; }); @@ -555,12 +725,13 @@ function tableToXml(node: { children?: unknown[] }, ctx: Ctx): string { return out + ''; } -/** 内容宽度启发式:CJK 计 2 / ASCII 计 1,×120 DXA,min 800,总宽超表宽 9026 等比压缩,全空列等分兜底 */ +/** 内容宽度启发式:CJK 计 2 / ASCII 计 1,×DXA_PER_UNIT,min 800,总宽精确等于 9026 */ function computeTableColumnWidths(rows: { children?: unknown[] }[], colCount: number): number[] { const DXA_PER_UNIT = 120; + const CELL_PADDING = 220; const MIN_COL_W = 800; const MAX_TOTAL = 9026; // 页宽 11906 - 左右页边距 1440×2 - const widths: number[] = new Array(colCount).fill(0); + const desired: number[] = new Array(colCount).fill(0); let hasContent = false; for (let ci = 0; ci < colCount; ci++) { let maxUnits = 0; @@ -573,51 +744,78 @@ function computeTableColumnWidths(rows: { children?: unknown[] }[], colCount: nu const units = textWidthUnits(text); if (units > maxUnits) maxUnits = units; } - widths[ci] = Math.max(MIN_COL_W, maxUnits * DXA_PER_UNIT); + desired[ci] = Math.max(MIN_COL_W, maxUnits * DXA_PER_UNIT + CELL_PADDING); } if (!hasContent) { const eq = Math.floor(MAX_TOTAL / colCount); return new Array(colCount).fill(eq); } - const total = widths.reduce((a, b) => a + b, 0); - if (total > MAX_TOTAL) { - const scale = MAX_TOTAL / total; - const scaled = widths.map((w) => Math.max(MIN_COL_W, Math.floor(w * scale))); - let sum = scaled.reduce((a, b) => a + b, 0); - // 精确修正:若取整后总和仍 > MAX_TOTAL,从最宽列逐次 -1 - while (sum > MAX_TOTAL) { - let best = -1; - for (let i = 0; i < scaled.length; i++) { - if (scaled[i] > MIN_COL_W && (best === -1 || scaled[i] > scaled[best])) best = i; - } - if (best === -1) break; // 全列触底 800,无法再减 - scaled[best]--; - sum--; + const totalDesired = desired.reduce((a, b) => a + b, 0); + if (totalDesired <= MAX_TOTAL) { + // 内容不足页宽:按比例放大至满宽 + const scale = MAX_TOTAL / totalDesired; + const scaled = desired.map((w) => Math.round(w * scale)); + // 取整残差加到最宽列 + const diff = MAX_TOTAL - scaled.reduce((a, b) => a + b, 0); + let widest = 0; + for (let i = 1; i < scaled.length; i++) { + if (desired[i] > desired[widest]) widest = i; } - // 取整导致总和 < MAX_TOTAL,差值加到首列 - if (sum < MAX_TOTAL) scaled[0] += MAX_TOTAL - sum; + scaled[widest] += diff; return scaled; } - if (total < MAX_TOTAL) { - // 内容宽度不足页宽时,按比例放大至满宽(fixed 布局按 gridCol 渲染,不满宽会留白) - const scale = MAX_TOTAL / total; - const scaled = widths.map((w) => Math.round(w * scale)); - // 修正取整误差,使总和精确等于 MAX_TOTAL(差值加到首列) - const diff = MAX_TOTAL - scaled.reduce((a, b) => a + b, 0); - scaled[0] += diff; + // 内容超页宽:仅压缩超出 min 的部分 + const aboveMinTotal = totalDesired - colCount * MIN_COL_W; + const budget = MAX_TOTAL - colCount * MIN_COL_W; + if (budget <= 0) { + // 列数过多导致 min*colCount 超过页宽:退化为按内容比例缩放(保证总和 9026、宽度为正) + const scaled = desired.map((w) => Math.max(1, Math.round((w * MAX_TOTAL) / totalDesired))); + const diff2 = MAX_TOTAL - scaled.reduce((a, b) => a + b, 0); + let widest2 = 0; + for (let i = 1; i < scaled.length; i++) { + if (desired[i] > desired[widest2]) widest2 = i; + } + scaled[widest2] += diff2; return scaled; } - return widths; + if (aboveMinTotal <= 0) { + // 所有列已触底 min:等分,残差加到首列 + const eq = Math.floor(MAX_TOTAL / colCount); + const result = new Array(colCount).fill(eq); + result[0] += MAX_TOTAL - eq * colCount; + return result; + } + const scaled = desired.map((w) => MIN_COL_W + Math.round(((w - MIN_COL_W) * budget) / aboveMinTotal)); + // 取整残差加到最宽列 + const diff = MAX_TOTAL - scaled.reduce((a, b) => a + b, 0); + let widest = 0; + for (let i = 1; i < scaled.length; i++) { + if (desired[i] > desired[widest]) widest = i; + } + scaled[widest] += diff; + return scaled; } -/** 提取单元格内所有文本(递归) */ +/** 提取单元格内所有文本(递归):text 节点 + value 类型(inlineCode/math/image-alt) */ function extractCellText(children: unknown[]): string { let out = ''; for (const child of children) { - const n = child as { type?: string; value?: unknown; children?: unknown[] }; + const n = child as { + type?: string; + value?: unknown; + children?: unknown[]; + alt?: unknown; + }; if (n.type === 'text' && typeof n.value === 'string') { out += n.value; - } else if (n.children) { + } else if (n.type === 'inlineCode' && typeof n.value === 'string') { + out += n.value; + } else if (n.type === 'math' && typeof n.value === 'string') { + out += n.value; + } else if (n.type === 'image' && typeof n.alt === 'string') { + out += n.alt; + } + if (n.children) { out += extractCellText(n.children); } } @@ -659,17 +857,22 @@ const EXT_CONTENT_TYPE = new Map([ /** [Content_Types].xml:声明全部部件类型(含实际用到的图片扩展名) */ function contentTypesXml(ctx: Ctx): string { const usedExt = new Set(ctx.media.map((m) => m.path.split('.').pop()!.toLowerCase())); - const defaults = ['rels', 'xml', ...usedExt].map((ext) => { - const ct = EXT_CONTENT_TYPE.get(ext) ?? 'application/octet-stream'; - return ``; - }).join(''); - return ` - -${defaults} - - - -`; + const defaults = ['rels', 'xml', ...usedExt] + .map((ext) => { + const ct = EXT_CONTENT_TYPE.get(ext) ?? 'application/octet-stream'; + return ''; + }) + .join(''); + return ( + '\n' + + '\n' + + defaults + + '\n' + + '\n' + + '\n' + + '\n' + + '' + ); } function documentXml(bodyXml: string): string { @@ -695,11 +898,13 @@ function documentRelsXml(ctx: Ctx): string { { id: 'rId2', type: 'numbering', target: 'numbering.xml' }, ...ctx.rels, ]; - const items = rels.map((r) => { - const type = REL_TYPE_URI.get(r.type) ?? 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink'; - const mode = r.external ? ' TargetMode="External"' : ''; - return ``; - }).join(''); + const items = rels + .map((r) => { + const type = REL_TYPE_URI.get(r.type) ?? 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink'; + const mode = r.external ? ' TargetMode="External"' : ''; + return ``; + }) + .join(''); return ` ${items} @@ -732,35 +937,38 @@ const STYLES_XML = ` `; -// 编号定义:abstractNum 0 = 项目符号(ul),abstractNum 1 = 十进制(ol),各 8 级嵌套 -// numId 1 固定绑定 abstractNum 0;每个 ol 列表实例独占 numId(≥2,经 ctx.numList 声明),互不连续计数; -// 自定义起始号经 lvlOverride/startOverride 表达(段落 numPr 内无 startOverride 元素,放置无效)。 +// 编号定义:abstractNum 0 = 项目符号(ul,numId 1);每个 ol 独占 abstractNum(id == numId ≥2) +// WPS 对共用 abstractNum 的 numId 会跨实例续计数,故每个 ol 必须拥有独立 abstractNum。 function numberingXml(ctx: Ctx): string { - const nums = [ - '', - ...ctx.numList.map(({ numId, start }) => - start !== 1 - ? `` - : ``), - ]; - return ` - - - -${[0, 1, 2, 3, 4, 5, 6, 7].map((lvl) => { - const bullet = ['•', '◦', '▪', '•', '◦', '▪', '•', '◦'][lvl]; - const left = 720 + lvl * 720; - return ``; - }).join('')} - - - -${[0, 1, 2, 3, 4, 5, 6, 7].map((lvl) => { + const decimalLvl = (lvl: number): string => { const lvlText = Array.from({ length: lvl + 1 }, (_, i) => `%${i + 1}`).join('.') + '.'; const left = 720 + lvl * 720; return ``; - }).join('')} - + }; + const abstractNums = [ + '' + + [0, 1, 2, 3, 4, 5, 6, 7] + .map((lvl) => { + const bullet = ['•', '◦', '▪', '•', '◦', '▪', '•', '◦'][lvl]; + const left = 720 + lvl * 720; + return ``; + }) + .join('') + + '', + ...ctx.numList.map( + ({ numId }) => + `${[0, 1, 2, 3, 4, 5, 6, 7].map(decimalLvl).join('')}` + ), + ]; + const nums = ctx.numList.map(({ numId, start }) => + start !== 1 + ? `` + : `` + ); + return ` + +${abstractNums.join('\n')} + ${nums.join('\n')} `; } @@ -776,9 +984,16 @@ ${nums.join('\n')} export function toDocx(files: Map, opts: DocxOptions = {}, onWarning?: (msg: string) => void): Uint8Array { // 入口解析与 render.ts 完全一致(manifest.entrypoint 优先,否则 lenient 推断) const manifestRaw = files.get('manifest.json'); - let manifest: { entrypoint?: string; extensions?: { include?: boolean; symbols?: 'off' | 'core' | 'extended' }; [k: string]: unknown }; - try { manifest = manifestRaw ? JSON.parse(new TextDecoder().decode(manifestRaw)) : {}; } - catch (e) { throw new MdeError(E.E302, `manifest.json 不是合法 JSON: ${(e as Error).message}`); } + let manifest: { + entrypoint?: string; + extensions?: { include?: boolean; symbols?: 'off' | 'core' | 'extended' }; + [k: string]: unknown; + }; + try { + manifest = manifestRaw ? JSON.parse(new TextDecoder().decode(manifestRaw)) : {}; + } catch (e) { + throw new MdeError(E.E302, `manifest.json 不是合法 JSON: ${(e as Error).message}`); + } const hasManifest = manifestRaw !== undefined; const entry: string = hasManifest && manifest.entrypoint ? manifest.entrypoint : inferEntrypoint(files); assertMarkdownEntrypoint(entry); // 非 Markdown 入口在此拒绝(E303),与 render.ts 对齐 @@ -793,6 +1008,8 @@ export function toDocx(files: Map, opts: DocxOptions = {}, o // 管线顺序与 render.ts 一致:include 展开(解析前)→ <<< 降级 → 哨兵保护 → 解析 const raw = new TextDecoder().decode(body); let expanded = manifest.extensions?.include === false ? raw : expand(files, entry).text; + // 文档头部 YAML frontmatter 剥离(先于 <<< 降级,与 render.ts 同顺序) + expanded = expanded.replace(FRONTMATTER_RE, ''); // 未被展开的指令(缩进的、或 include 关闭时)必须作为可见文本降级(与 render.ts 相同处理) expanded = expanded.replace(/^(\s*)<<, opts: DocxOptions = {}, o const bytes = packRaw(out); if (onWarning) for (const w of ctx.warnings) onWarning(w); return bytes; -} \ No newline at end of file +} diff --git a/packages/mdpkg/src/render.ts b/packages/mdpkg/src/render.ts index c35aeeb..4b85307 100644 --- a/packages/mdpkg/src/render.ts +++ b/packages/mdpkg/src/render.ts @@ -38,7 +38,7 @@ export interface RenderResult { const isExternal = (src: string) => /^(https?:)?\/\//i.test(src); // YAML frontmatter 剥离:只匹配文档头部的 --- 块(容忍 BOM),防 --- 被渲染为
与正文并列 -const FRONTMATTER_RE = /^\uFEFF?---\s*\n([\s\S]*?)\n---(?:\n|$)/; +export const FRONTMATTER_RE = /^\uFEFF?---\s*\n([\s\S]*?)\n---(?:\n|$)/; // CJK 间距守卫:累计 text 超过阈值后不再处理(超大文档性能保护) const MAX_CJK_PAD_CHARS = 200_000; diff --git a/packages/mdpkg/test/docx.test.ts b/packages/mdpkg/test/docx.test.ts index 9438c41..57710aa 100644 --- a/packages/mdpkg/test/docx.test.ts +++ b/packages/mdpkg/test/docx.test.ts @@ -106,18 +106,9 @@ test('4.1 引用与代码块:Quote/CodeBlock 样式', async () => { }); test('4.1 列表:ul/ol 编号、嵌套 ilvl、任务列表前缀', async () => { - const body = [ - '- 项目一', - '- 项目二', - ' - 嵌套一', - ' - 嵌套二', - '', - '1. 第一', - '2. 第二', - '', - '- [x] 已完成', - '- [ ] 未完成', - ].join('\n'); + const body = ['- 项目一', '- 项目二', ' - 嵌套一', ' - 嵌套二', '', '1. 第一', '2. 第二', '', '- [x] 已完成', '- [ ] 未完成'].join( + '\n' + ); const out = await unpackDocx(toDocx(pkg(body))); const doc = dec.decode(out.get('word/document.xml')!); assert.ok(doc.includes(''), 'ul 应使用 numId 1(项目符号)'); @@ -134,12 +125,12 @@ test('4.1 列表:ul/ol 编号、嵌套 ilvl、任务列表前缀', async () => } }); -test('4.1 表格与水平线:tbl 单元格文本与 pBdr', async () => { +test('4.1 表格与水平线:tbl 单元格文本保真 + --- 无输出', async () => { const body = '| 列A | 列B |\n| --- | --- |\n| 甲 | 乙 |\n\n---\n'; const out = await unpackDocx(toDocx(pkg(body))); const doc = dec.decode(out.get('word/document.xml')!); assert.ok(doc.includes(''), '表格应输出 w:tbl'); - assert.ok(doc.includes(''), '水平线应输出段落边框'); + assert.ok(!doc.includes(' { - const files = new Map([ - ['docs/doc.md', enc('![图](../../x.png)\n')], - ]); + const files = new Map([['docs/doc.md', enc('![图](../../x.png)\n')]]); const out = await unpackDocx(toDocx(files)); const doc = dec.decode(out.get('word/document.xml')!); assert.ok(!doc.includes(''), '越根引用不应嵌入'); @@ -255,7 +244,14 @@ test('4.4 unzip -l:标准 OOXML 条目可列', async () => { writeFileSync(docxPath, toDocx(pkg('# 标题\n'))); const r = spawnSync('unzip', ['-l', docxPath], { encoding: 'utf8' }); assert.equal(r.status, 0, `unzip -l 应成功: ${r.stderr}`); - for (const entry of ['[Content_Types].xml', '_rels/.rels', 'word/document.xml', 'word/styles.xml', 'word/numbering.xml', 'word/_rels/document.xml.rels']) { + for (const entry of [ + '[Content_Types].xml', + '_rels/.rels', + 'word/document.xml', + 'word/styles.xml', + 'word/numbering.xml', + 'word/_rels/document.xml.rels', + ]) { assert.ok(r.stdout.includes(entry), `应列出标准条目: ${entry}`); } rmSync(tmp, { recursive: true, force: true }); @@ -325,10 +321,13 @@ test('4.5 CLI:非法 --format → 退出码 2', () => { test('4.5 CLI:SVG 图片 → 退出码 0 + stderr 含 SVG 警告', () => { const tmp = join(__dirname, '.test-docx-cli-svg'); - const pkgPath = makeCliPkg(tmp, new Map([ - ['document.md', enc('# 标题\n\n![svg](assets/a.svg)\n')], - ['assets/a.svg', enc('')], - ])); + const pkgPath = makeCliPkg( + tmp, + new Map([ + ['document.md', enc('# 标题\n\n![svg](assets/a.svg)\n')], + ['assets/a.svg', enc('')], + ]) + ); const outPath = join(tmp, 'out.docx'); const r = spawnSync(process.execPath, [CLI, 'render', pkgPath, '--format', 'docx', '-o', outPath], { encoding: 'utf8' }); assert.equal(r.status, 0, 'SVG 降级不应失败(退出码 0)'); @@ -513,9 +512,18 @@ test('Wave 2.2 宽图:保持宽高比缩放(1920×1080 → 宽优先)', as const png = new Uint8Array(24); png.set([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a], 0); png[11] = 13; - png[12] = 0x49; png[13] = 0x48; png[14] = 0x44; png[15] = 0x52; - png[16] = 0x00; png[17] = 0x00; png[18] = 0x07; png[19] = 0x80; - png[20] = 0x00; png[21] = 0x00; png[22] = 0x04; png[23] = 0x38; + png[12] = 0x49; + png[13] = 0x48; + png[14] = 0x44; + png[15] = 0x52; + png[16] = 0x00; + png[17] = 0x00; + png[18] = 0x07; + png[19] = 0x80; + png[20] = 0x00; + png[21] = 0x00; + png[22] = 0x04; + png[23] = 0x38; const body = '![宽图](assets/wide.png)\n'; const out = await unpackDocx(toDocx(pkg(body, { 'assets/wide.png': png }))); const doc = dec.decode(out.get('word/document.xml')!); @@ -527,9 +535,18 @@ test('Wave 2.2 高图:保持宽高比缩放(窄高图)', async () => { const png = new Uint8Array(24); png.set([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a], 0); png[11] = 13; - png[12] = 0x49; png[13] = 0x48; png[14] = 0x44; png[15] = 0x52; - png[16] = 0x00; png[17] = 0x00; png[18] = 0x02; png[19] = 0x58; - png[20] = 0x00; png[21] = 0x00; png[22] = 0x04; png[23] = 0xb0; + png[12] = 0x49; + png[13] = 0x48; + png[14] = 0x44; + png[15] = 0x52; + png[16] = 0x00; + png[17] = 0x00; + png[18] = 0x02; + png[19] = 0x58; + png[20] = 0x00; + png[21] = 0x00; + png[22] = 0x04; + png[23] = 0xb0; const body = '![高图](assets/tall.png)\n'; const out = await unpackDocx(toDocx(pkg(body, { 'assets/tall.png': png }))); const doc = dec.decode(out.get('word/document.xml')!); @@ -554,9 +571,18 @@ test('Wave 2.2 零宽图片:回退缺省尺寸 + 不产生 NaN', async () => { const png = new Uint8Array(24); png.set([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a], 0); png[11] = 13; - png[12] = 0x49; png[13] = 0x48; png[14] = 0x44; png[15] = 0x52; - png[16] = 0x00; png[17] = 0x00; png[18] = 0x00; png[19] = 0x00; // width=0 - png[20] = 0x00; png[21] = 0x00; png[22] = 0x00; png[23] = 0x64; // height=100 + png[12] = 0x49; + png[13] = 0x48; + png[14] = 0x44; + png[15] = 0x52; + png[16] = 0x00; + png[17] = 0x00; + png[18] = 0x00; + png[19] = 0x00; // width=0 + png[20] = 0x00; + png[21] = 0x00; + png[22] = 0x00; + png[23] = 0x64; // height=100 const body = '![零宽](assets/zero.png)\n'; const warnings: string[] = []; const out = await unpackDocx(toDocx(pkg(body, { 'assets/zero.png': png }), {}, (w) => warnings.push(w))); @@ -601,7 +627,10 @@ test('Wave 2.3 全空列:等分兜底', async () => { assert.ok(gridMatch, '应有 tblGrid'); const cols = [...gridMatch![1].matchAll(/w:w="(\d+)"/g)].map((m) => Number(m[1])); assert.ok(cols.length === 3, '应有 3 列'); - assert.ok(cols.every((w) => w === cols[0]), '全空列应等分'); + assert.ok( + cols.every((w) => w === cols[0]), + '全空列应等分' + ); }); test('Wave 2.3 表头加粗不影响数据行', async () => { @@ -722,13 +751,26 @@ test('Review 修复 显式 imageHeightEmu 等于默认值时优先使用显式 const png = new Uint8Array(24); png.set([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a], 0); png[11] = 13; - png[12] = 0x49; png[13] = 0x48; png[14] = 0x44; png[15] = 0x52; - png[16] = 0x00; png[17] = 0x00; png[18] = 0x00; png[19] = 0x64; // width=100 - png[20] = 0x00; png[21] = 0x00; png[22] = 0x00; png[23] = 0x64; // height=100 + png[12] = 0x49; + png[13] = 0x48; + png[14] = 0x44; + png[15] = 0x52; + png[16] = 0x00; + png[17] = 0x00; + png[18] = 0x00; + png[19] = 0x64; // width=100 + png[20] = 0x00; + png[21] = 0x00; + png[22] = 0x00; + png[23] = 0x64; // height=100 const body = '![图](assets/square.png)\n'; // 显式传入 imageHeightEmu = 4114800(= 默认 4.5 英寸),此时应直接使用该值而非按宽高比计算 const DEFAULT_IMAGE_HEIGHT_EMU = Math.round(6 * 914400 * 0.75); // 4114800 - const out = await unpackDocx(toDocx(pkg(body, { 'assets/square.png': png }), { imageHeightEmu: DEFAULT_IMAGE_HEIGHT_EMU })); + const out = await unpackDocx( + toDocx(pkg(body, { 'assets/square.png': png }), { + imageHeightEmu: DEFAULT_IMAGE_HEIGHT_EMU, + }) + ); const doc = dec.decode(out.get('word/document.xml')!); // 100px * 9525 = 952500 EMU(< 6 英寸上限),所以宽 = 952500 // 若按宽高比计算:h = 952500 * (100/100) = 952500 @@ -802,7 +844,12 @@ test('回归#9-6 表格:单元格垂直居中 + 内边距', async () => { const out = await unpackDocx(toDocx(pkg(body))); const doc = dec.decode(out.get('word/document.xml')!); assert.ok(doc.includes(''), '单元格应垂直居中'); - assert.ok(doc.includes(''), '应声明单元格内边距'); + assert.ok( + doc.includes( + '' + ), + '应声明单元格内边距' + ); }); test('回归#9-7 callout 同行标题:> [!tip] 实用提示 → 去标识、标题加粗、类型背景色', async () => { @@ -904,18 +951,207 @@ test('回归#13-4 混合文档:短表格+长表格各一,每个 gridCol 总 assert.equal(idx, 2, `应有 2 个表格,实际 ${idx}`); }); -// 回归#13-5 触底保护:12 列极短内容表格,每列 ≥800 且总和不被扣破 -test('回归#13-5 触底保护:12 列极短内容表格,每列 ≥800 且总和不被扣破', async () => { - const body = '| A | B | C | D | E | F | G | H | I | J | K | L |\n' - + '| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |\n' - + '| 甲 | 乙 | 丙 | 丁 | 戊 | 己 | 庚 | 辛 | 壬 | 癸 | 子 | 丑 |\n'; +// 回归#13-5 触底保护:12 列极短内容表格,总和精确等于 9026(12*800>9026,min 约束无法全部满足) +test('回归#13-5 触底保护:12 列极短内容表格,总和精确等于 9026', async () => { + const body = + '| A | B | C | D | E | F | G | H | I | J | K | L |\n' + + '| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |\n' + + '| 甲 | 乙 | 丙 | 丁 | 戊 | 己 | 庚 | 辛 | 壬 | 癸 | 子 | 丑 |\n'; const out = await unpackDocx(toDocx(pkg(body))); const doc = dec.decode(out.get('word/document.xml')!); const cols = gridColValues(doc); assert.equal(cols.length, 12, `应有 12 列,实际 ${cols.length}`); + const sum = cols.reduce((a, b) => a + b, 0); + assert.equal(sum, 9026, `总和应精确等于 9026,实际 ${sum}`); +}); + +// ============ 回归#16:docx 导出第二轮 8 项质量修复 ============ + +test('回归#16-a 表格数据单元格:**P0** 加粗且仅一个段落', async () => { + const body = '| 优先级 | 说明 |\n| --- | --- |\n| **P0** | 最高 |\n'; + const out = await unpackDocx(toDocx(pkg(body))); + const doc = dec.decode(out.get('word/document.xml')!); + const rows = doc.match(/[\s\S]*?<\/w:tr>/g); + assert.ok(rows && rows.length === 2, '应有 2 行'); + // 提取第一个数据单元格 + const cells = rows![1].match(/[\s\S]*?<\/w:tc>/g); + assert.ok(cells && cells.length === 2, '数据行应有 2 个单元格'); + const p0Cell = cells![0]; + // 数据单元格应含 (来自 strong) + assert.ok(p0Cell.includes(''), '数据单元格 **P0** 应含粗体'); + // 文本 P0 保真 + assert.ok(p0Cell.includes('P0'), '数据单元格应含文本 P0'); + // 仅一个 + const pCount = (p0Cell.match(//g) || []).length; + assert.equal(pCount, 1, '数据单元格应仅一个段落'); +}); + +test('回归#16-b 表格数据单元格:**50%** 内容不丢失', async () => { + const body = '| 列 | 值 |\n| --- | --- |\n| a | **50%** |\n'; + const out = await unpackDocx(toDocx(pkg(body))); + const doc = dec.decode(out.get('word/document.xml')!); + const rows = doc.match(/[\s\S]*?<\/w:tr>/g); + const dataRow = rows![1]; + assert.ok(dataRow.includes('50%'), '数据单元格应含 50%(不应为空)'); +}); + +test('回归#16-c 表格数据单元格:text+inlineCode+text 仅一个段落', async () => { + const body = '| 列 | 值 |\n| --- | --- |\n| x | text `code` text |\n'; + const out = await unpackDocx(toDocx(pkg(body))); + const doc = dec.decode(out.get('word/document.xml')!); + const rows = doc.match(/[\s\S]*?<\/w:tr>/g); + const cells = rows![1].match(/[\s\S]*?<\/w:tc>/g); + const secondCell = cells![1]; + const pCount = (secondCell.match(//g) || []).length; + assert.equal(pCount, 1, 'text+inlineCode+text 应仅一个段落(不应拆成 3 段)'); + assert.ok(secondCell.includes('text'), '应含 text'); + assert.ok(secondCell.includes('code'), '应含 code'); +}); + +test('回归#16-d 列宽:文件名列 ≥2500 且总和 === 9026', async () => { + const body = '| 编号 | `04_智能合同2.0优势价值销售策略.txt` | 主题 |\n' + '| --- | --- | --- |\n' + '| 1 | 策略文档 | 销售 |\n'; + const out = await unpackDocx(toDocx(pkg(body))); + const doc = dec.decode(out.get('word/document.xml')!); + const cols = gridColValues(doc); + assert.equal(cols.length, 3, '应有 3 列'); + assert.ok(cols[1] >= 2500, `文件名列应 ≥2500,实际 ${cols[1]}`); + const sum = cols.reduce((a, b) => a + b, 0); + assert.equal(sum, 9026, `总和应精确等于 9026,实际 ${sum}`); +}); + +test('回归#16-e 编号:两个有序列表各自独立 abstractNum', async () => { + const body = '1. 甲\n2. 乙\n\n分隔\n\n1. 丙\n2. 丁\n'; + const out = await unpackDocx(toDocx(pkg(body))); + const numbering = dec.decode(out.get('word/numbering.xml')!); + // 每个 ol 应有独立的 abstractNum(id == numId) + assert.ok(numbering.includes(''), '第一个 ol 应有独立 abstractNum 2'); + assert.ok(numbering.includes(''), '第二个 ol 应有独立 abstractNum 3'); + assert.ok(numbering.includes(''), 'numId 2 应绑定 abstractNum 2'); + assert.ok(numbering.includes(''), 'numId 3 应绑定 abstractNum 3'); + // 项目符号仍为 abstractNum 0 + assert.ok(numbering.includes(''), '项目符号应绑定 abstractNum 0'); +}); + +test('回归#16-eb 编号:自定义起始号仍发 startOverride', async () => { + const body = '3. 丙\n4. 丁\n'; + const out = await unpackDocx(toDocx(pkg(body))); + const numbering = dec.decode(out.get('word/numbering.xml')!); + assert.ok(numbering.includes(''), '起始号 3 应写入 startOverride'); +}); + +test('回归#16-f emoji:astral emoji 清除,BMP 符号保留', async () => { + const body = '🛑 标题 🔢\n\n⚠️ 注意 ❌ 错误\n'; + const out = await unpackDocx(toDocx(pkg(body))); + const doc = dec.decode(out.get('word/document.xml')!); + // astral emoji 应被清除 + assert.ok(!doc.includes('🛑'), '🛑 应被清除'); + assert.ok(!doc.includes('🔢'), '🔢 应被清除'); + // BMP 符号保留 + assert.ok(doc.includes('⚠'), '⚠ 应保留'); + assert.ok(doc.includes('❌'), '❌ 应保留'); + // FE0F 应被清除(⚠️ → ⚠) + assert.ok(!doc.includes('️'), 'FE0F 变体选择符应被清除'); +}); + +test('回归#16-g 单元格间距 + tcPr 顺序', async () => { + const body = '| 列A | 列B |\n| --- | --- |\n| 甲 | 乙 |\n'; + const out = await unpackDocx(toDocx(pkg(body))); + const doc = dec.decode(out.get('word/document.xml')!); + // 数据单元格 pPr 含 before=0/after=0 + const rows = doc.match(/[\s\S]*?<\/w:tr>/g); + const dataRow = rows![1]; + assert.ok(dataRow.includes('w:before="0" w:after="0"'), '数据单元格段落应有 before=0/after=0'); + // 表头 tcPr 顺序:tcW → shd → vAlign + const headerRow = rows![0]; + const tcPrMatch = headerRow.match(/([\s\S]*?)<\/w:tcPr>/); + assert.ok(tcPrMatch, '表头单元格应有 tcPr'); + const tcPr = tcPrMatch![1]; + const tcWIdx = tcPr.indexOf(' { + const body = '上文\n\n---\n\n下文\n'; + const out = await unpackDocx(toDocx(pkg(body))); + const doc = dec.decode(out.get('word/document.xml')!); + assert.ok(!doc.includes(' { + const body = '> [!tip] 实用提示\n> Markdown 是最通用的文档格式。\n'; + const out = await unpackDocx(toDocx(pkg(body))); + const doc = dec.decode(out.get('word/document.xml')!); + const text = docxText(doc); + assert.ok(text.includes('实用提示'), '标题应保真'); + assert.ok(text.includes('Markdown 是最通用的文档格式'), '正文应保真'); + // 标题加粗 + assert.ok( + doc.includes('实用提示') || + doc.includes('实用提示'), + '标题 run 应加粗' + ); + // 正文不应加粗:找到 Markdown 所在的 run,确认不在 后 + const markdownRun = doc.match(/]*>Markdown/); + assert.ok(markdownRun, '正文应含 Markdown'); + // 确认 Markdown run 不在 bold run 内 + const markdownIdx = doc.indexOf('Markdown'); + // 往前找最近的 或 + const prevRPrBold = doc.lastIndexOf('', markdownIdx); + const prevRClose = doc.lastIndexOf('', markdownIdx); + assert.ok(prevRClose > prevRPrBold || prevRPrBold === -1, '正文 run 不应在 bold 格式内'); + // 标题段 pPr schema 顺序:w:spacing 在 w:ind 之前 + const headPP = doc.match(/[\s\S]*?<\/w:pPr>/); + assert.ok(headPP, '应有标题段 pPr'); + const headPPContent = headPP![0]; + assert.ok(headPPContent.indexOf(' { + const body = '> [!warning]\n> 打包为单文件\n'; + const out = await unpackDocx(toDocx(pkg(body))); + const doc = dec.decode(out.get('word/document.xml')!); + const text = docxText(doc); + assert.ok(text.includes('打包为单文件'), '正文应保真'); + // 正文不应加粗 + const contentIdx = doc.indexOf('打包为单文件'); + const prevRPrBold = doc.lastIndexOf('', contentIdx); + const prevRClose = doc.lastIndexOf('', contentIdx); + assert.ok(prevRClose > prevRPrBold || prevRPrBold === -1, '无标题 callout 正文不应加粗'); +}); + +test('回归#16-j frontmatter:剥离 frontmatter 文本', async () => { + const body = '---\nname: x\n---\n# H\n'; + const out = await unpackDocx(toDocx(pkg(body))); + const doc = dec.decode(out.get('word/document.xml')!); + const text = docxText(doc); + assert.ok(!text.includes('name: x'), '不应含 frontmatter 文本'); + assert.ok(text.includes('H'), '标题 H 应保真'); + assert.ok(!doc.includes(' { + const body = '`A9_exam_key.json` 或 `V11_exam_key.json`\n'; + const out = await unpackDocx(toDocx(pkg(body))); + const doc = dec.decode(out.get('word/document.xml')!); + assert.ok(doc.includes('xml:space="preserve"> 或 '), '或 两侧空格应保留'); +}); + +test('回归#16-l 12列含长内容:总和 9026 且每列 ≥400', async () => { + const body = + '| x | x | x | x | x | x | x | x | x | x | x | 智能合同2.0优势价值销售策略一表 |\n' + + '| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |\n'; + const out = await unpackDocx(toDocx(pkg(body))); + const doc = dec.decode(out.get('word/document.xml')!); + const cols = gridColValues(doc); + assert.equal(cols.length, 12, `应有 12 列,实际 ${cols.length}`); + const sum = cols.reduce((a, b) => a + b, 0); + assert.equal(sum, 9026, `总和应精确等于 9026,实际 ${sum}`); for (const w of cols) { - assert.ok(w >= 800, `每列应 ≥800(MIN_COL_W),实际 ${w}`); + assert.ok(w >= 400, `每列应 ≥400,实际 ${w}`); } - const sum = cols.reduce((a, b) => a + b, 0); - assert.ok(sum >= 9026, `总和应 ≥9026(触底保护生效,宁可超宽也不扣破 min),实际 ${sum}`); -}); \ No newline at end of file +}); diff --git a/packages/mdpkg/web/mdpkg-web.iife.js b/packages/mdpkg/web/mdpkg-web.iife.js index c97c94b..a53b5eb 100644 --- a/packages/mdpkg/web/mdpkg-web.iife.js +++ b/packages/mdpkg/web/mdpkg-web.iife.js @@ -23502,12 +23502,22 @@ ${bodyHtml} a: "http://schemas.openxmlformats.org/drawingml/2006/main", pic: "http://schemas.openxmlformats.org/drawingml/2006/picture" }; + var SPACING = ''; var EMU_PER_INCH = 914400; var DEFAULT_IMAGE_WIDTH_EMU = 6 * EMU_PER_INCH; var DEFAULT_IMAGE_HEIGHT_EMU = Math.round(DEFAULT_IMAGE_WIDTH_EMU * 0.75); var BITMAP_EXT = /* @__PURE__ */ new Set(["png", "jpg", "jpeg", "gif", "webp"]); function esc(s) { - return s.replace(/[&<>"']/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[c]); + return s.replace( + /[&<>"']/g, + (c) => ({ + "&": "&", + "<": "<", + ">": ">", + '"': """, + "'": "'" + })[c] + ); } function degradeHtml(raw2) { return raw2.replace(/<\s*(script|style)\b[\s\S]*?<\s*\/\s*(script|style)\s*>/gi, ""); @@ -23648,7 +23658,7 @@ ${bodyHtml} if (firstChild.type !== "paragraph" || !firstChild.children) continue; const firstText = firstChild.children[0]; if (firstText.type !== "text" || typeof firstText.value !== "string") continue; - const m = firstText.value.match(/^\[!([A-Za-z]+)\]\s*/); + const m = firstText.value.match(/^\[!([A-Za-z]+)\][ \t]*/); if (!m) continue; const tag = m[1].toUpperCase(); if (!CALLOUT_TYPES.has(tag)) continue; @@ -23663,6 +23673,24 @@ ${bodyHtml} node2.tag = tag; } } + function stripEmoji(s) { + let out = ""; + let removed = false; + for (const ch of s) { + const cp = ch.codePointAt(0) ?? 0; + if (cp >= 126976 && cp <= 129791) { + removed = true; + continue; + } + if (cp === 65038 || cp === 65039 || cp === 8205) { + removed = true; + continue; + } + out += ch; + } + if (!removed) return s; + return out.replace(/ {2,}/g, " ").trim(); + } function inlineChildren(children2, ctx, fmt = {}) { return children2.map((c) => inlineToXml(c, ctx, fmt)).join(""); } @@ -23674,6 +23702,7 @@ ${bodyHtml} case "text": { let text8 = String(node2.value ?? ""); if (ctx.symbols) text8 = unguard(replaceSymbols(text8)); + text8 = stripEmoji(text8); return textToRuns(text8, fmt); } case "strong": @@ -23681,15 +23710,26 @@ ${bodyHtml} case "emphasis": return inlineChildren(node2.children, ctx, { ...fmt, i: true }); case "delete": - return inlineChildren(node2.children, ctx, { ...fmt, strike: true }); + return inlineChildren(node2.children, ctx, { + ...fmt, + strike: true + }); case "inlineCode": return codeRun(String(node2.value ?? ""), fmt); case "link": { const url = String(node2.url ?? ""); if (isExternal2(url)) { const rId = `rId${ctx.nextRid++}`; - ctx.rels.push({ id: rId, type: "hyperlink", target: url, external: true }); - return inlineChildren(node2.children, ctx, { ...fmt, link: rId }); + ctx.rels.push({ + id: rId, + type: "hyperlink", + target: url, + external: true + }); + return inlineChildren(node2.children, ctx, { + ...fmt, + link: rId + }); } return inlineChildren(node2.children, ctx, fmt); } @@ -23737,7 +23777,11 @@ ${bodyHtml} const mediaPath = `word/media/img-${id}.${ext}`; ctx.media.push({ path: mediaPath, data }); const rId = `rId${ctx.nextRid++}`; - ctx.rels.push({ id: rId, type: "image", target: mediaPath.replace(/^word\//, "") }); + ctx.rels.push({ + id: rId, + type: "image", + target: mediaPath.replace(/^word\//, "") + }); const EMU_PER_PX = 9525; const intrinsic = readImageSize(data); let w; @@ -23802,7 +23846,10 @@ ${bodyHtml} out += serializeList(child, ctx, ilvl + 1); continue; } - out += blockToXml(child, ctx, { numPr, prefix: first ? checked : void 0 }); + out += blockToXml(child, ctx, { + numPr, + prefix: first ? checked : void 0 + }); first = false; } }); @@ -23837,30 +23884,35 @@ ${bodyHtml} function calloutPPr(extra) { if (!extra?.callout) return ""; const { fill, border } = extra.callout; - return ``; + const spacing = extra.headSpacing ? '' : ""; + return `${spacing}`; } - function calloutHeadXml(children2, ctx) { - let out = ""; - let headDone = false; + function splitCalloutHead(children2, ctx) { + const head2 = []; + const body3 = []; + let splitDone = false; for (const c of children2) { const n = c; - if (n.type === "text" && typeof n.value === "string" && !headDone) { + if (!splitDone && n.type === "text" && typeof n.value === "string") { const nl = n.value.indexOf("\n"); - if (nl === -1) { - out += textToRuns(n.value, { b: true }); - headDone = true; - } else { - const head2 = n.value.slice(0, nl); - const tail = n.value.slice(nl + 1); - if (head2) out += textToRuns(head2, { b: true }); - if (tail) out += textToRuns(tail, {}); - headDone = true; + if (nl !== -1) { + const headText = n.value.slice(0, nl); + const bodyText = n.value.slice(nl + 1); + if (headText) head2.push({ type: "text", value: headText }); + if (bodyText) body3.push({ type: "text", value: bodyText }); + splitDone = true; + continue; } + head2.push(c); + continue; + } + if (splitDone) { + body3.push(c); } else { - out += inlineToXml(c, ctx, headDone ? {} : { b: true }); + head2.push(c); } } - return out; + return { head: head2, body: body3 }; } function blockToXml(node2, ctx, extra) { switch (node2.type) { @@ -23871,7 +23923,9 @@ ${bodyHtml} (c) => c.type === "math" && c.display ); if (hasBlockMath) { - return splitParagraphAtBlockMath(node2, ctx, { style }); + return splitParagraphAtBlockMath(node2, ctx, { + style + }); } return `${calloutPPr(extra)}${inlineChildren(node2.children, ctx)}`; } @@ -23886,7 +23940,10 @@ ${bodyHtml} if (!hasBlockMath) { return `${pPr ? `${pPr}` : ""}${prefix}${inlineChildren(node2.children, ctx, headerFmt)}`; } - return splitParagraphAtBlockMath(node2, ctx, { ...extra, style: pStyle }); + return splitParagraphAtBlockMath(node2, ctx, { + ...extra, + style: pStyle + }); } case "code": { const lines = String(node2.value ?? "").split("\n"); @@ -23903,15 +23960,26 @@ ${bodyHtml} const children2 = node2.children ?? []; const first = children2[0]; const rest = first && first.type === "paragraph" ? children2.slice(1) : children2; + const pPr = calloutPPr({ callout: { fill, border } }); let out = ""; if (first && first.type === "paragraph" && (first.children?.length ?? 0) > 0) { - out += `${calloutPPr({ callout: { fill, border } })}${calloutHeadXml(first.children, ctx)}`; + const { head: head2, body: body3 } = splitCalloutHead(first.children, ctx); + if (head2.length > 0) { + const headPPr = calloutPPr({ + callout: { fill, border }, + headSpacing: true + }); + out += `${headPPr}${inlineChildren(head2, ctx, { b: true })}`; + } + if (body3.length > 0) { + out += `${pPr}${inlineChildren(body3, ctx, {})}`; + } } out += rest.map((c) => blockToXml(c, ctx, { callout: { fill, border } })).join(""); return out; } case "thematicBreak": { - return ''; + return ""; } case "table": return tableToXml(node2, ctx); @@ -23930,27 +23998,41 @@ ${bodyHtml} const rows = (node2.children ?? []).filter((r) => r.type === "tableRow"); const colCount = Math.max(1, ...rows.map((r) => r.children?.length ?? 0)); const colWidths = computeTableColumnWidths(rows, colCount); - let out = ''; - out += "" + ["top", "left", "bottom", "right", "insideH", "insideV"].map((b) => ``).join("") + ""; + const borders = ["top", "left", "bottom", "right", "insideH", "insideV"]; + const tblBorders = "" + borders.map((b) => ``).join("") + ""; + let out = '' + tblBorders + ''; out += ''; out += ''; - out += `${colWidths.map((w) => ``).join("")}`; + let gridCols = ""; + for (let gi = 0; gi < colWidths.length; gi++) { + gridCols += ''; + } + out += "" + gridCols + ""; rows.forEach((row, ri) => { out += ""; row.children?.forEach((cell, ci) => { const isHeader = ri === 0; out += ""; - out += ``; - out += ''; + out += ''; if (isHeader) out += ''; + out += ''; out += ""; const blocks2 = cell.children ?? []; if (blocks2.length === 0) { out += ""; - } else if (isHeader) { - out += `${inlineChildren(blocks2, ctx, { b: true })}`; } else { - out += blocks2.map((b) => blockToXml(b, ctx, { style: "Table" })).join(""); + const hasBlock = blocks2.some((b) => { + const t = b.type; + return t === "paragraph" || t === "list" || t === "table" || t === "code" || t === "heading" || t === "blockquote" || t === "callout" || t === "thematicBreak"; + }); + if (!hasBlock) { + const cellFmt = isHeader ? { b: true } : {}; + out += '' + SPACING + "" + inlineChildren(blocks2, ctx, cellFmt) + ""; + } else if (isHeader) { + out += '' + SPACING + "" + inlineChildren(blocks2, ctx, { b: true }) + ""; + } else { + out += blocks2.map((b) => blockToXml(b, ctx, { style: "Table" })).join(""); + } } out += ""; }); @@ -23960,9 +24042,10 @@ ${bodyHtml} } function computeTableColumnWidths(rows, colCount) { const DXA_PER_UNIT = 120; + const CELL_PADDING = 220; const MIN_COL_W = 800; const MAX_TOTAL = 9026; - const widths = new Array(colCount).fill(0); + const desired = new Array(colCount).fill(0); let hasContent = false; for (let ci = 0; ci < colCount; ci++) { let maxUnits = 0; @@ -23975,37 +24058,50 @@ ${bodyHtml} const units = textWidthUnits(text8); if (units > maxUnits) maxUnits = units; } - widths[ci] = Math.max(MIN_COL_W, maxUnits * DXA_PER_UNIT); + desired[ci] = Math.max(MIN_COL_W, maxUnits * DXA_PER_UNIT + CELL_PADDING); } if (!hasContent) { const eq = Math.floor(MAX_TOTAL / colCount); return new Array(colCount).fill(eq); } - const total = widths.reduce((a, b) => a + b, 0); - if (total > MAX_TOTAL) { - const scale = MAX_TOTAL / total; - const scaled = widths.map((w) => Math.max(MIN_COL_W, Math.floor(w * scale))); - let sum = scaled.reduce((a, b) => a + b, 0); - while (sum > MAX_TOTAL) { - let best = -1; - for (let i2 = 0; i2 < scaled.length; i2++) { - if (scaled[i2] > MIN_COL_W && (best === -1 || scaled[i2] > scaled[best])) best = i2; - } - if (best === -1) break; - scaled[best]--; - sum--; - } - if (sum < MAX_TOTAL) scaled[0] += MAX_TOTAL - sum; - return scaled; + const totalDesired = desired.reduce((a, b) => a + b, 0); + if (totalDesired <= MAX_TOTAL) { + const scale = MAX_TOTAL / totalDesired; + const scaled2 = desired.map((w) => Math.round(w * scale)); + const diff2 = MAX_TOTAL - scaled2.reduce((a, b) => a + b, 0); + let widest2 = 0; + for (let i2 = 1; i2 < scaled2.length; i2++) { + if (desired[i2] > desired[widest2]) widest2 = i2; + } + scaled2[widest2] += diff2; + return scaled2; + } + const aboveMinTotal = totalDesired - colCount * MIN_COL_W; + const budget = MAX_TOTAL - colCount * MIN_COL_W; + if (budget <= 0) { + const scaled2 = desired.map((w) => Math.max(1, Math.round(w * MAX_TOTAL / totalDesired))); + const diff2 = MAX_TOTAL - scaled2.reduce((a, b) => a + b, 0); + let widest2 = 0; + for (let i2 = 1; i2 < scaled2.length; i2++) { + if (desired[i2] > desired[widest2]) widest2 = i2; + } + scaled2[widest2] += diff2; + return scaled2; + } + if (aboveMinTotal <= 0) { + const eq = Math.floor(MAX_TOTAL / colCount); + const result = new Array(colCount).fill(eq); + result[0] += MAX_TOTAL - eq * colCount; + return result; } - if (total < MAX_TOTAL) { - const scale = MAX_TOTAL / total; - const scaled = widths.map((w) => Math.round(w * scale)); - const diff = MAX_TOTAL - scaled.reduce((a, b) => a + b, 0); - scaled[0] += diff; - return scaled; + const scaled = desired.map((w) => MIN_COL_W + Math.round((w - MIN_COL_W) * budget / aboveMinTotal)); + const diff = MAX_TOTAL - scaled.reduce((a, b) => a + b, 0); + let widest = 0; + for (let i2 = 1; i2 < scaled.length; i2++) { + if (desired[i2] > desired[widest]) widest = i2; } - return widths; + scaled[widest] += diff; + return scaled; } function extractCellText(children2) { let out = ""; @@ -24013,7 +24109,14 @@ ${bodyHtml} const n = child; if (n.type === "text" && typeof n.value === "string") { out += n.value; - } else if (n.children) { + } else if (n.type === "inlineCode" && typeof n.value === "string") { + out += n.value; + } else if (n.type === "math" && typeof n.value === "string") { + out += n.value; + } else if (n.type === "image" && typeof n.alt === "string") { + out += n.alt; + } + if (n.children) { out += extractCellText(n.children); } } @@ -24044,15 +24147,9 @@ ${bodyHtml} const usedExt = new Set(ctx.media.map((m) => m.path.split(".").pop().toLowerCase())); const defaults = ["rels", "xml", ...usedExt].map((ext) => { const ct = EXT_CONTENT_TYPE.get(ext) ?? "application/octet-stream"; - return ``; + return ''; }).join(""); - return ` - -${defaults} - - - -`; + return '\n\n' + defaults + '\n\n\n\n'; } function documentXml(bodyXml) { return ` @@ -24108,28 +24205,28 @@ ${items} `; function numberingXml(ctx) { - const nums = [ - '', - ...ctx.numList.map(({ numId, start }) => start !== 1 ? `` : ``) - ]; - return ` - - - -${[0, 1, 2, 3, 4, 5, 6, 7].map((lvl) => { - const bullet = ["\u2022", "\u25E6", "\u25AA", "\u2022", "\u25E6", "\u25AA", "\u2022", "\u25E6"][lvl]; - const left = 720 + lvl * 720; - return ``; - }).join("")} - - - -${[0, 1, 2, 3, 4, 5, 6, 7].map((lvl) => { + const decimalLvl = (lvl) => { const lvlText = Array.from({ length: lvl + 1 }, (_, i2) => `%${i2 + 1}`).join(".") + "."; const left = 720 + lvl * 720; return ``; - }).join("")} - + }; + const abstractNums = [ + '' + [0, 1, 2, 3, 4, 5, 6, 7].map((lvl) => { + const bullet = ["\u2022", "\u25E6", "\u25AA", "\u2022", "\u25E6", "\u25AA", "\u2022", "\u25E6"][lvl]; + const left = 720 + lvl * 720; + return ``; + }).join("") + "", + ...ctx.numList.map( + ({ numId }) => `${[0, 1, 2, 3, 4, 5, 6, 7].map(decimalLvl).join("")}` + ) + ]; + const nums = ctx.numList.map( + ({ numId, start }) => start !== 1 ? `` : `` + ); + return ` + +${abstractNums.join("\n")} + ${nums.join("\n")} `; } @@ -24151,6 +24248,7 @@ ${nums.join("\n")} const entryDir = i2 === -1 ? "" : entry.slice(0, i2); const raw2 = new TextDecoder().decode(body3); let expanded = manifest.extensions?.include === false ? raw2 : expand(files, entry).text; + expanded = expanded.replace(FRONTMATTER_RE, ""); expanded = expanded.replace(/^(\s*)<<"']/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[c]); + return s.replace( + /[&<>"']/g, + (c) => ({ + "&": "&", + "<": "<", + ">": ">", + '"': """, + "'": "'" + })[c] + ); } function degradeHtml(raw2) { return raw2.replace(/<\s*(script|style)\b[\s\S]*?<\s*\/\s*(script|style)\s*>/gi, ""); @@ -23628,7 +23638,7 @@ function extractCallouts(tree) { if (firstChild.type !== "paragraph" || !firstChild.children) continue; const firstText = firstChild.children[0]; if (firstText.type !== "text" || typeof firstText.value !== "string") continue; - const m = firstText.value.match(/^\[!([A-Za-z]+)\]\s*/); + const m = firstText.value.match(/^\[!([A-Za-z]+)\][ \t]*/); if (!m) continue; const tag = m[1].toUpperCase(); if (!CALLOUT_TYPES.has(tag)) continue; @@ -23643,6 +23653,24 @@ function extractCallouts(tree) { node2.tag = tag; } } +function stripEmoji(s) { + let out = ""; + let removed = false; + for (const ch of s) { + const cp = ch.codePointAt(0) ?? 0; + if (cp >= 126976 && cp <= 129791) { + removed = true; + continue; + } + if (cp === 65038 || cp === 65039 || cp === 8205) { + removed = true; + continue; + } + out += ch; + } + if (!removed) return s; + return out.replace(/ {2,}/g, " ").trim(); +} function inlineChildren(children2, ctx, fmt = {}) { return children2.map((c) => inlineToXml(c, ctx, fmt)).join(""); } @@ -23654,6 +23682,7 @@ function inlineToXml(node2, ctx, fmt) { case "text": { let text8 = String(node2.value ?? ""); if (ctx.symbols) text8 = unguard(replaceSymbols(text8)); + text8 = stripEmoji(text8); return textToRuns(text8, fmt); } case "strong": @@ -23661,15 +23690,26 @@ function inlineToXml(node2, ctx, fmt) { case "emphasis": return inlineChildren(node2.children, ctx, { ...fmt, i: true }); case "delete": - return inlineChildren(node2.children, ctx, { ...fmt, strike: true }); + return inlineChildren(node2.children, ctx, { + ...fmt, + strike: true + }); case "inlineCode": return codeRun(String(node2.value ?? ""), fmt); case "link": { const url = String(node2.url ?? ""); if (isExternal2(url)) { const rId = `rId${ctx.nextRid++}`; - ctx.rels.push({ id: rId, type: "hyperlink", target: url, external: true }); - return inlineChildren(node2.children, ctx, { ...fmt, link: rId }); + ctx.rels.push({ + id: rId, + type: "hyperlink", + target: url, + external: true + }); + return inlineChildren(node2.children, ctx, { + ...fmt, + link: rId + }); } return inlineChildren(node2.children, ctx, fmt); } @@ -23717,7 +23757,11 @@ function imageToXml(node2, ctx, fmt) { const mediaPath = `word/media/img-${id}.${ext}`; ctx.media.push({ path: mediaPath, data }); const rId = `rId${ctx.nextRid++}`; - ctx.rels.push({ id: rId, type: "image", target: mediaPath.replace(/^word\//, "") }); + ctx.rels.push({ + id: rId, + type: "image", + target: mediaPath.replace(/^word\//, "") + }); const EMU_PER_PX = 9525; const intrinsic = readImageSize(data); let w; @@ -23782,7 +23826,10 @@ function serializeList(node2, ctx, ilvl) { out += serializeList(child, ctx, ilvl + 1); continue; } - out += blockToXml(child, ctx, { numPr, prefix: first ? checked : void 0 }); + out += blockToXml(child, ctx, { + numPr, + prefix: first ? checked : void 0 + }); first = false; } }); @@ -23817,30 +23864,35 @@ function splitParagraphAtBlockMath(node2, ctx, extra) { function calloutPPr(extra) { if (!extra?.callout) return ""; const { fill, border } = extra.callout; - return ``; + const spacing = extra.headSpacing ? '' : ""; + return `${spacing}`; } -function calloutHeadXml(children2, ctx) { - let out = ""; - let headDone = false; +function splitCalloutHead(children2, ctx) { + const head2 = []; + const body3 = []; + let splitDone = false; for (const c of children2) { const n = c; - if (n.type === "text" && typeof n.value === "string" && !headDone) { + if (!splitDone && n.type === "text" && typeof n.value === "string") { const nl = n.value.indexOf("\n"); - if (nl === -1) { - out += textToRuns(n.value, { b: true }); - headDone = true; - } else { - const head2 = n.value.slice(0, nl); - const tail = n.value.slice(nl + 1); - if (head2) out += textToRuns(head2, { b: true }); - if (tail) out += textToRuns(tail, {}); - headDone = true; + if (nl !== -1) { + const headText = n.value.slice(0, nl); + const bodyText = n.value.slice(nl + 1); + if (headText) head2.push({ type: "text", value: headText }); + if (bodyText) body3.push({ type: "text", value: bodyText }); + splitDone = true; + continue; } + head2.push(c); + continue; + } + if (splitDone) { + body3.push(c); } else { - out += inlineToXml(c, ctx, headDone ? {} : { b: true }); + head2.push(c); } } - return out; + return { head: head2, body: body3 }; } function blockToXml(node2, ctx, extra) { switch (node2.type) { @@ -23851,7 +23903,9 @@ function blockToXml(node2, ctx, extra) { (c) => c.type === "math" && c.display ); if (hasBlockMath) { - return splitParagraphAtBlockMath(node2, ctx, { style }); + return splitParagraphAtBlockMath(node2, ctx, { + style + }); } return `${calloutPPr(extra)}${inlineChildren(node2.children, ctx)}`; } @@ -23866,7 +23920,10 @@ function blockToXml(node2, ctx, extra) { if (!hasBlockMath) { return `${pPr ? `${pPr}` : ""}${prefix}${inlineChildren(node2.children, ctx, headerFmt)}`; } - return splitParagraphAtBlockMath(node2, ctx, { ...extra, style: pStyle }); + return splitParagraphAtBlockMath(node2, ctx, { + ...extra, + style: pStyle + }); } case "code": { const lines = String(node2.value ?? "").split("\n"); @@ -23883,15 +23940,26 @@ function blockToXml(node2, ctx, extra) { const children2 = node2.children ?? []; const first = children2[0]; const rest = first && first.type === "paragraph" ? children2.slice(1) : children2; + const pPr = calloutPPr({ callout: { fill, border } }); let out = ""; if (first && first.type === "paragraph" && (first.children?.length ?? 0) > 0) { - out += `${calloutPPr({ callout: { fill, border } })}${calloutHeadXml(first.children, ctx)}`; + const { head: head2, body: body3 } = splitCalloutHead(first.children, ctx); + if (head2.length > 0) { + const headPPr = calloutPPr({ + callout: { fill, border }, + headSpacing: true + }); + out += `${headPPr}${inlineChildren(head2, ctx, { b: true })}`; + } + if (body3.length > 0) { + out += `${pPr}${inlineChildren(body3, ctx, {})}`; + } } out += rest.map((c) => blockToXml(c, ctx, { callout: { fill, border } })).join(""); return out; } case "thematicBreak": { - return ''; + return ""; } case "table": return tableToXml(node2, ctx); @@ -23910,27 +23978,41 @@ function tableToXml(node2, ctx) { const rows = (node2.children ?? []).filter((r) => r.type === "tableRow"); const colCount = Math.max(1, ...rows.map((r) => r.children?.length ?? 0)); const colWidths = computeTableColumnWidths(rows, colCount); - let out = ''; - out += "" + ["top", "left", "bottom", "right", "insideH", "insideV"].map((b) => ``).join("") + ""; + const borders = ["top", "left", "bottom", "right", "insideH", "insideV"]; + const tblBorders = "" + borders.map((b) => ``).join("") + ""; + let out = '' + tblBorders + ''; out += ''; out += ''; - out += `${colWidths.map((w) => ``).join("")}`; + let gridCols = ""; + for (let gi = 0; gi < colWidths.length; gi++) { + gridCols += ''; + } + out += "" + gridCols + ""; rows.forEach((row, ri) => { out += ""; row.children?.forEach((cell, ci) => { const isHeader = ri === 0; out += ""; - out += ``; - out += ''; + out += ''; if (isHeader) out += ''; + out += ''; out += ""; const blocks2 = cell.children ?? []; if (blocks2.length === 0) { out += ""; - } else if (isHeader) { - out += `${inlineChildren(blocks2, ctx, { b: true })}`; } else { - out += blocks2.map((b) => blockToXml(b, ctx, { style: "Table" })).join(""); + const hasBlock = blocks2.some((b) => { + const t = b.type; + return t === "paragraph" || t === "list" || t === "table" || t === "code" || t === "heading" || t === "blockquote" || t === "callout" || t === "thematicBreak"; + }); + if (!hasBlock) { + const cellFmt = isHeader ? { b: true } : {}; + out += '' + SPACING + "" + inlineChildren(blocks2, ctx, cellFmt) + ""; + } else if (isHeader) { + out += '' + SPACING + "" + inlineChildren(blocks2, ctx, { b: true }) + ""; + } else { + out += blocks2.map((b) => blockToXml(b, ctx, { style: "Table" })).join(""); + } } out += ""; }); @@ -23940,9 +24022,10 @@ function tableToXml(node2, ctx) { } function computeTableColumnWidths(rows, colCount) { const DXA_PER_UNIT = 120; + const CELL_PADDING = 220; const MIN_COL_W = 800; const MAX_TOTAL = 9026; - const widths = new Array(colCount).fill(0); + const desired = new Array(colCount).fill(0); let hasContent = false; for (let ci = 0; ci < colCount; ci++) { let maxUnits = 0; @@ -23955,37 +24038,50 @@ function computeTableColumnWidths(rows, colCount) { const units = textWidthUnits(text8); if (units > maxUnits) maxUnits = units; } - widths[ci] = Math.max(MIN_COL_W, maxUnits * DXA_PER_UNIT); + desired[ci] = Math.max(MIN_COL_W, maxUnits * DXA_PER_UNIT + CELL_PADDING); } if (!hasContent) { const eq = Math.floor(MAX_TOTAL / colCount); return new Array(colCount).fill(eq); } - const total = widths.reduce((a, b) => a + b, 0); - if (total > MAX_TOTAL) { - const scale = MAX_TOTAL / total; - const scaled = widths.map((w) => Math.max(MIN_COL_W, Math.floor(w * scale))); - let sum = scaled.reduce((a, b) => a + b, 0); - while (sum > MAX_TOTAL) { - let best = -1; - for (let i2 = 0; i2 < scaled.length; i2++) { - if (scaled[i2] > MIN_COL_W && (best === -1 || scaled[i2] > scaled[best])) best = i2; - } - if (best === -1) break; - scaled[best]--; - sum--; - } - if (sum < MAX_TOTAL) scaled[0] += MAX_TOTAL - sum; - return scaled; + const totalDesired = desired.reduce((a, b) => a + b, 0); + if (totalDesired <= MAX_TOTAL) { + const scale = MAX_TOTAL / totalDesired; + const scaled2 = desired.map((w) => Math.round(w * scale)); + const diff2 = MAX_TOTAL - scaled2.reduce((a, b) => a + b, 0); + let widest2 = 0; + for (let i2 = 1; i2 < scaled2.length; i2++) { + if (desired[i2] > desired[widest2]) widest2 = i2; + } + scaled2[widest2] += diff2; + return scaled2; + } + const aboveMinTotal = totalDesired - colCount * MIN_COL_W; + const budget = MAX_TOTAL - colCount * MIN_COL_W; + if (budget <= 0) { + const scaled2 = desired.map((w) => Math.max(1, Math.round(w * MAX_TOTAL / totalDesired))); + const diff2 = MAX_TOTAL - scaled2.reduce((a, b) => a + b, 0); + let widest2 = 0; + for (let i2 = 1; i2 < scaled2.length; i2++) { + if (desired[i2] > desired[widest2]) widest2 = i2; + } + scaled2[widest2] += diff2; + return scaled2; + } + if (aboveMinTotal <= 0) { + const eq = Math.floor(MAX_TOTAL / colCount); + const result = new Array(colCount).fill(eq); + result[0] += MAX_TOTAL - eq * colCount; + return result; } - if (total < MAX_TOTAL) { - const scale = MAX_TOTAL / total; - const scaled = widths.map((w) => Math.round(w * scale)); - const diff = MAX_TOTAL - scaled.reduce((a, b) => a + b, 0); - scaled[0] += diff; - return scaled; + const scaled = desired.map((w) => MIN_COL_W + Math.round((w - MIN_COL_W) * budget / aboveMinTotal)); + const diff = MAX_TOTAL - scaled.reduce((a, b) => a + b, 0); + let widest = 0; + for (let i2 = 1; i2 < scaled.length; i2++) { + if (desired[i2] > desired[widest]) widest = i2; } - return widths; + scaled[widest] += diff; + return scaled; } function extractCellText(children2) { let out = ""; @@ -23993,7 +24089,14 @@ function extractCellText(children2) { const n = child; if (n.type === "text" && typeof n.value === "string") { out += n.value; - } else if (n.children) { + } else if (n.type === "inlineCode" && typeof n.value === "string") { + out += n.value; + } else if (n.type === "math" && typeof n.value === "string") { + out += n.value; + } else if (n.type === "image" && typeof n.alt === "string") { + out += n.alt; + } + if (n.children) { out += extractCellText(n.children); } } @@ -24024,15 +24127,9 @@ function contentTypesXml(ctx) { const usedExt = new Set(ctx.media.map((m) => m.path.split(".").pop().toLowerCase())); const defaults = ["rels", "xml", ...usedExt].map((ext) => { const ct = EXT_CONTENT_TYPE.get(ext) ?? "application/octet-stream"; - return ``; + return ''; }).join(""); - return ` - -${defaults} - - - -`; + return '\n\n' + defaults + '\n\n\n\n'; } function documentXml(bodyXml) { return ` @@ -24088,28 +24185,28 @@ var STYLES_XML = ` `; function numberingXml(ctx) { - const nums = [ - '', - ...ctx.numList.map(({ numId, start }) => start !== 1 ? `` : ``) - ]; - return ` - - - -${[0, 1, 2, 3, 4, 5, 6, 7].map((lvl) => { - const bullet = ["\u2022", "\u25E6", "\u25AA", "\u2022", "\u25E6", "\u25AA", "\u2022", "\u25E6"][lvl]; - const left = 720 + lvl * 720; - return ``; - }).join("")} - - - -${[0, 1, 2, 3, 4, 5, 6, 7].map((lvl) => { + const decimalLvl = (lvl) => { const lvlText = Array.from({ length: lvl + 1 }, (_, i2) => `%${i2 + 1}`).join(".") + "."; const left = 720 + lvl * 720; return ``; - }).join("")} - + }; + const abstractNums = [ + '' + [0, 1, 2, 3, 4, 5, 6, 7].map((lvl) => { + const bullet = ["\u2022", "\u25E6", "\u25AA", "\u2022", "\u25E6", "\u25AA", "\u2022", "\u25E6"][lvl]; + const left = 720 + lvl * 720; + return ``; + }).join("") + "", + ...ctx.numList.map( + ({ numId }) => `${[0, 1, 2, 3, 4, 5, 6, 7].map(decimalLvl).join("")}` + ) + ]; + const nums = ctx.numList.map( + ({ numId, start }) => start !== 1 ? `` : `` + ); + return ` + +${abstractNums.join("\n")} + ${nums.join("\n")} `; } @@ -24131,6 +24228,7 @@ function toDocx(files, opts = {}, onWarning) { const entryDir = i2 === -1 ? "" : entry.slice(0, i2); const raw2 = new TextDecoder().decode(body3); let expanded = manifest.extensions?.include === false ? raw2 : expand(files, entry).text; + expanded = expanded.replace(FRONTMATTER_RE, ""); expanded = expanded.replace(/^(\s*)<<