From 5fefb996c54ba959acf69a87b63744f4e9c7248e Mon Sep 17 00:00:00 2001 From: lqtdys Date: Mon, 14 Sep 2026 19:44:46 +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=208=20=E9=A1=B9=E7=BC=BA=E9=99=B7=EF=BC=88?= =?UTF-8?q?=E5=9B=BE=E7=89=87=E7=A9=BA=E7=99=BD/=E7=BC=96=E5=8F=B7?= =?UTF-8?q?=E7=8B=AC=E7=AB=8B/=E5=8D=95=E5=80=8D=E8=A1=8C=E8=B7=9D/?= =?UTF-8?q?=E8=A1=A8=E6=A0=BC=E6=BB=A1=E5=AE=BD=E8=BE=B9=E8=B7=9D=E5=B1=85?= =?UTF-8?q?=E4=B8=AD/callout=20=E4=B8=8E=E4=BB=A3=E7=A0=81=E6=A0=87?= =?UTF-8?q?=E6=B3=A8=E5=8E=BB=E9=99=A4=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 图片关系 Target 相对 word/(media/img-1.png),修复位图空白占位 - 每个有序列表分配独立 numId(numbering.xml 动态 num 实例),自定义起始号经 lvlOverride - docDefaults 行距 line=360→240(单倍) - 软换行 \n 并入空格(与 HTML 语义一致),硬换行 break 保留 w:br - 表格 tblW=9026 dxa + tblLayout fixed 满宽,tblCellMar 内边距 + vAlign center - callout 识别(含同行标题)去标识、按类型背景色、标题加粗 - 代码块 [lang] 语言标注不再输出(保留 CodeBlock 背景色) - 回归测试 + Wave 1.2/2.1 断言按新行为更新 fixes #9 --- packages/mdpkg/src/docx.ts | 137 ++++++++++++++------ packages/mdpkg/test/docx.test.ts | 114 ++++++++++++++-- packages/mdpkg/web/mdpkg-web.iife.js | 186 ++++++++++++++++++++------- packages/mdpkg/web/mdpkg-web.js | 186 ++++++++++++++++++++------- 4 files changed, 484 insertions(+), 139 deletions(-) diff --git a/packages/mdpkg/src/docx.ts b/packages/mdpkg/src/docx.ts index 44d287a..5e7efb7 100644 --- a/packages/mdpkg/src/docx.ts +++ b/packages/mdpkg/src/docx.ts @@ -57,6 +57,8 @@ interface Ctx { warnings: string[]; nextRid: number; // 关系编号(rId1=styles、rId2=numbering 已占用) docPrId: number; // 图片 docPr 自增 id + nextNumId: number; // 有序列表编号实例分配器(从 2 起;numId 1 固定为项目符号) + numList: { numId: number; start: number }[]; // 分配的 ol 编号实例(含自定义起始号),供 numbering.xml 声明 } /** XML 文本转义(& < > " ') */ @@ -101,12 +103,12 @@ function plainRun(text: string, fmt: RunFmt): string { return fmt.link ? `${run}` : run; } -/** 文本 → run 序列(\n 软换行转 w:br,保留行结构) */ +/** 文本 → run 序列(软换行 \n 并入空格,与 HTML 路径空白合并语义一致;硬换行 break 节点仍输出 w:br) */ function textToRuns(text: string, fmt: RunFmt): string { const parts = text.split('\n'); let out = ''; for (let i = 0; i < parts.length; i++) { - if (i > 0) out += `${rPrXml(fmt)}`; + if (i > 0 && parts[i]) out += plainRun(' ', fmt); if (parts[i]) out += plainRun(parts[i], fmt); } return out; @@ -188,8 +190,22 @@ function splitMathInInline(node: { type: string; children: unknown[] }): void { 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', ]); +// 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'], + TODO: ['EFF7F3', '5F9B8A'], +}; +const CALLOUT_DEFAULT: [string, string] = ['F0F7FA', '6C9DBF']; + function extractCallouts(tree: { type: string; children?: unknown[] }): void { if (!tree.children) return; for (let i = 0; i < tree.children.length; i++) { @@ -199,11 +215,12 @@ function extractCallouts(tree: { type: string; children?: unknown[] }): void { if (firstChild.type !== 'paragraph' || !firstChild.children) continue; 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*(?:\n|$)/); + const m = firstText.value.match(/^\[!([A-Za-z]+)\]\s*/); if (!m) continue; const tag = m[1].toUpperCase(); if (!CALLOUT_TYPES.has(tag)) continue; - const remainingText = firstText.value.replace(/^\[!([A-Za-z]+)\]\s*/, ''); + // 剩余内容 = 标识之后的全部文本(同行标题 + 换行后的正文),slice 保留 \n 分隔 + const remainingText = firstText.value.slice(m[0].length); if (remainingText) { firstText.value = remainingText; } else { @@ -293,7 +310,9 @@ function imageToXml(node: { url?: unknown; alt?: unknown }, ctx: Ctx, fmt: RunFm 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 }); + // 关系 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\//, '') }); // 固有尺寸换算:EMU = px * 9525(96dpi);保持宽高比缩放进 imageWidthEmu const EMU_PER_PX = 9525; const intrinsic = readImageSize(data); @@ -344,18 +363,19 @@ function imageToXml(node: { url?: unknown; alt?: unknown }, ctx: Ctx, fmt: RunFm `; } -/** 列表:numbering.xml 编号(ul=numId 1 项目符号,ol=numId 2 十进制),嵌套按 ilvl 递增 */ +/** 列表:ul 固定 numId 1;每个 ol 分配独立 numId(编号实例),嵌套按 ilvl 递增 */ function serializeList(node: { ordered?: unknown; start?: unknown; children?: unknown[] }, ctx: Ctx, ilvl: number): string { - const numId = node.ordered ? 2 : 1; - const start = Number(node.start) || 1; + let numId = 1; + if (node.ordered) { + numId = ctx.nextNumId++; + ctx.numList.push({ numId, start: Number(node.start) || 1 }); + } let out = ''; - (node.children ?? []).forEach((item, idx) => { + (node.children ?? []).forEach((item) => { const it = item as { type?: string; checked?: unknown; children?: unknown[] }; if (it.type !== 'listItem') return; const checked = typeof it.checked === 'boolean' ? (it.checked ? '☑ ' : '☐ ') : ''; - // 有序列表自定义起始号:仅首项带 startOverride - const startOverride = idx === 0 && numId === 2 && start !== 1 ? `` : ''; - const numPr = `${startOverride}`; + const numPr = ``; let first = true; for (const child of it.children ?? []) { if ((child as { type?: string }).type === 'list') { @@ -401,8 +421,40 @@ function splitParagraphAtBlockMath( return out || `${pPr ? `${pPr}` : ''}${prefix}`; } +/** callout 注入片段:左边框 + 背景色 + 左缩进(pBdr/shd/ind 顺序符合 pPr schema) */ +function calloutPPr(extra?: { callout?: { fill: string; border: string } }): string { + if (!extra?.callout) return ''; + const { fill, border } = extra.callout; + return ``; +} + +/** callout 首段:首个 \n 前为标题(加粗),其后正文保持常规格式 */ +function calloutHeadXml(children: unknown[], ctx: Ctx): string { + let out = ''; + let headDone = false; + for (const c of children) { + const n = c as { type?: string; value?: string }; + if (n.type === 'text' && typeof n.value === 'string' && !headDone) { + 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; + } + } else { + out += inlineToXml(c as never, ctx, headDone ? {} : { b: true }); + } + } + return out; +} + /** 块级节点 → OOXML 段落/表格 XML */ -function blockToXml(node: { type: string; [k: string]: unknown }, ctx: Ctx, extra?: { numPr?: string; prefix?: string; style?: string; headerBold?: boolean }): 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)); @@ -413,11 +465,11 @@ function blockToXml(node: { type: string; [k: string]: unknown }, ctx: Ctx, extr if (hasBlockMath) { return splitParagraphAtBlockMath(node as { children: unknown[] }, ctx, { style }); } - return `${inlineChildren(node.children as never[], ctx)}`; + return `${calloutPPr(extra)}${inlineChildren(node.children as never[], ctx)}`; } case 'paragraph': { const pStyle = extra?.style ?? (extra?.numPr ? 'ListParagraph' : ''); - const pPr = `${pStyle ? `` : ''}${extra?.numPr ?? ''}`; + const pPr = `${pStyle ? `` : ''}${extra?.numPr ?? ''}${calloutPPr(extra)}`; const prefix = extra?.prefix ? plainRun(extra.prefix, {}) : ''; const headerFmt = extra?.headerBold ? headerBoldFmt({}) : {}; const hasBlockMath = (node.children as unknown[])?.some( @@ -429,19 +481,10 @@ function blockToXml(node: { type: string; [k: string]: unknown }, ctx: Ctx, extr return splitParagraphAtBlockMath(node as { children: unknown[] }, ctx, { ...extra, style: pStyle }); } case 'code': { - // 块级代码:每行一段(CodeBlock 样式),保留空白;有 lang 且非 mermaid 时首行前插灰色标注 run + // 块级代码:每行一段(CodeBlock 样式,浅灰背景),保留空白;语言标注 [lang] 不作为文字输出 const lines = String(node.value ?? '').split('\n'); - const lang = typeof node.lang === 'string' ? node.lang.trim() : ''; - const annotate = lang && lang !== 'mermaid'; return lines - .map((line, idx) => { - let runs = `${esc(line)}`; - if (idx === 0 && annotate) { - // 语言标注 run:灰色 9pt 非等宽,插在代码内容 run 之前 - runs = `[${esc(lang)}] ${runs}`; - } - return `${runs}`; - }) + .map((line) => `${esc(line)}`) .join(''); } case 'list': return serializeList(node as never, ctx, 0); @@ -450,8 +493,16 @@ function blockToXml(node: { type: string; [k: string]: unknown }, ctx: Ctx, extr } case 'callout': { const tag = String((node as { tag?: unknown }).tag ?? 'NOTE'); - return `${esc(tag)}` + - (node.children as never[]).map((c) => blockToXml(c as never, ctx)).join(''); + const [fill, border] = CALLOUT_COLORS[tag] ?? CALLOUT_DEFAULT; + 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; + let out = ''; + if (first && first.type === 'paragraph' && (first.children?.length ?? 0) > 0) { + out += `${calloutPPr({ callout: { fill, border } })}${calloutHeadXml(first.children, ctx)}`; + } + out += rest.map((c) => blockToXml(c as never, ctx, { callout: { fill, border } })).join(''); + return out; } case 'thematicBreak': { // 水平线:段落底部边框 @@ -473,9 +524,10 @@ 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 = ''; + let out = ''; out += '' + ['top', 'left', 'bottom', 'right', 'insideH', 'insideV'] .map((b) => ``).join('') + ''; + out += ''; out += ''; out += `${colWidths.map((w) => ``).join('')}`; rows.forEach((row, ri) => { @@ -484,6 +536,7 @@ function tableToXml(node: { children?: unknown[] }, ctx: Ctx): string { const isHeader = ri === 0; out += ''; out += ``; + out += ''; if (isHeader) out += ''; out += ''; const blocks = (cell as { children?: unknown[] }).children ?? []; @@ -502,11 +555,11 @@ function tableToXml(node: { children?: unknown[] }, ctx: Ctx): string { return out + ''; } -/** 内容宽度启发式:CJK 计 2 / ASCII 计 1,×120 DXA,min 800,总宽超 9000 等比压缩,全空列等分兜底 */ +/** 内容宽度启发式:CJK 计 2 / ASCII 计 1,×120 DXA,min 800,总宽超表宽 9026 等比压缩,全空列等分兜底 */ function computeTableColumnWidths(rows: { children?: unknown[] }[], colCount: number): number[] { const DXA_PER_UNIT = 120; const MIN_COL_W = 800; - const MAX_TOTAL = 9000; + const MAX_TOTAL = 9026; // 页宽 11906 - 左右页边距 1440×2 const widths: number[] = new Array(colCount).fill(0); let hasContent = false; for (let ci = 0; ci < colCount; ci++) { @@ -640,7 +693,7 @@ const STYLES_XML = ` - + @@ -657,7 +710,17 @@ const STYLES_XML = ` `; // 编号定义:abstractNum 0 = 项目符号(ul),abstractNum 1 = 十进制(ol),各 8 级嵌套 -const NUMBERING_XML = ` +// numId 1 固定绑定 abstractNum 0;每个 ol 列表实例独占 numId(≥2,经 ctx.numList 声明),互不连续计数; +// 自定义起始号经 lvlOverride/startOverride 表达(段落 numPr 内无 startOverride 元素,放置无效)。 +function numberingXml(ctx: Ctx): string { + const nums = [ + '', + ...ctx.numList.map(({ numId, start }) => + start !== 1 + ? `` + : ``), + ]; + return ` @@ -675,9 +738,9 @@ ${[0, 1, 2, 3, 4, 5, 6, 7].map((lvl) => { return ``; }).join('')} - - +${nums.join('\n')} `; +} /** * 将 .mdpkg 包内容渲染为 .docx(OOXML 文档)字节。 @@ -728,6 +791,8 @@ export function toDocx(files: Map, opts: DocxOptions = {}, o warnings: [], nextRid: 3, // rId1=styles、rId2=numbering 已占用 docPrId: 1, + nextNumId: 2, // numId 1 固定绑定项目符号 abstractNum + numList: [], }; const bodyXml = (tree as { children?: unknown[] }).children?.map((c) => blockToXml(c as never, ctx)).join('') ?? ''; @@ -739,7 +804,7 @@ export function toDocx(files: Map, opts: DocxOptions = {}, o out.set('word/document.xml', enc(documentXml(bodyXml))); out.set('word/_rels/document.xml.rels', enc(documentRelsXml(ctx))); out.set('word/styles.xml', enc(STYLES_XML)); - out.set('word/numbering.xml', enc(NUMBERING_XML)); + out.set('word/numbering.xml', enc(numberingXml(ctx))); for (const m of ctx.media) out.set(m.path, m.data); const bytes = packRaw(out); diff --git a/packages/mdpkg/test/docx.test.ts b/packages/mdpkg/test/docx.test.ts index 596dbdd..54d47fc 100644 --- a/packages/mdpkg/test/docx.test.ts +++ b/packages/mdpkg/test/docx.test.ts @@ -403,15 +403,16 @@ test('Wave 1.1 未闭合 $ 不崩溃且保持原样', async () => { // ============ Wave 1.2 Callout 识别 ============ -test('Wave 1.2 已知键 callout:> [!TIP] 输出带标签的 callout 块', async () => { +test('Wave 1.2 已知键 callout:> [!TIP] 去标识输出带底纹与左边框的 callout 块', async () => { const body = '> [!TIP]\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('TIP'), '应含 TIP 标签'); + assert.ok(!text.includes('TIP'), '不应残留 TIP 标识文本'); + assert.ok(!text.includes('[!'), '不应残留 [! 标识'); assert.ok(text.includes('提示内容'), 'callout 内容应保真'); - assert.ok(doc.includes(''), 'callout 应有左边框'); - assert.ok(doc.includes(' [!FOO] 保持 blockquote', async () => { @@ -471,16 +472,14 @@ test('Wave 1.3 嵌套任务列表:子项也使用字形', async () => { // ============ Wave 2.1 代码块语言标注 ============ -test('Wave 2.1 有 lang:```ts 首行前插 [ts] 灰色标注 run', async () => { - const body = '```ts\nconst x = 1;\n```\n'; +test('Wave 2.1 有 lang:```ts 不输出 [ts] 语言标注文本', async () => { + const body = '```ts\nconst a = 1;\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('[ts]'), '应含 [ts] 标注'); - assert.ok(text.includes('const x = 1;'), '代码内容应保真'); - assert.ok(doc.includes(''), '标注应为灰色'); - assert.ok(doc.includes(''), '标注应为 9pt'); - assert.ok(doc.includes(''), '应保留 CodeBlock 样式'); + assert.ok(!text.includes('[ts]'), '不应输出 [ts] 语言标注'); + assert.ok(doc.includes(''), '应使用 CodeBlock 样式(含背景色)'); + assert.ok(text.includes('const a = 1;'), '代码内容应保真'); }); test('Wave 2.1 无 lang:纯代码块无标注', async () => { @@ -736,4 +735,97 @@ test('Review 修复 显式 imageHeightEmu 等于默认值时优先使用显式 // 若使用显式值:h = 4114800 // 只有 explicitImageHeight 标志正确时才会用 4114800 assert.ok(doc.includes('cy="4114800"'), '显式 imageHeightEmu 等于默认值时仍应优先使用显式值'); +}); + +// ============ 缺陷修复回归(issue #9):docx 导出 8 项 ============ + +test('回归#9-1 图片:rels Target 相对 word/(media/img-1.png),非 word/media/…', async () => { + const body = '![图](assets/a.png)\n'; + const out = await unpackDocx(toDocx(pkg(body, { 'assets/a.png': PNG }))); + const rels = dec.decode(out.get('word/_rels/document.xml.rels')!); + assert.ok(rels.includes('Target="media/img-1.png"'), 'image 关系 Target 应相对 word/'); + assert.ok(!rels.includes('Target="word/media/'), '不应出现 word/media/ 绝对形式'); +}); + +test('回归#9-2 列表:多个有序列表各自独立 numId 实例', async () => { + const body = '1. 甲\n2. 乙\n\n分隔段\n\n1. 丙\n2. 丁\n'; + const out = await unpackDocx(toDocx(pkg(body))); + const doc = dec.decode(out.get('word/document.xml')!); + const numbering = dec.decode(out.get('word/numbering.xml')!); + assert.ok(doc.includes(''), '第一个 ol 应使用 numId 2'); + assert.ok(doc.includes(''), '第二个 ol 应使用 numId 3'); + assert.ok(numbering.includes(''), 'numbering.xml 应声明 numId 2 实例'); + assert.ok(numbering.includes(''), 'numbering.xml 应声明 numId 3 实例'); + assert.ok(!doc.includes(' { + 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(''), '起始号应写入 numbering.xml lvlOverride'); +}); + +test('回归#9-3 行距:docDefaults 单倍(line=240)', async () => { + const out = await unpackDocx(toDocx(pkg('正文\n'))); + const styles = dec.decode(out.get('word/styles.xml')!); + assert.ok(styles.includes(''), 'docDefaults 应为 line=240'); + assert.ok(!styles.includes('w:line="360"'), '不应再出现 1.5 倍行距'); +}); + +test('回归#9-4 软换行:\\n 并入空格而非 w:br(与 HTML 语义一致)', async () => { + const body = '第一行\n第二行\n'; + const out = await unpackDocx(toDocx(pkg(body))); + const doc = dec.decode(out.get('word/document.xml')!); + const text = docxText(doc); + assert.ok(!doc.includes(''), '软换行不应输出 w:br'); + assert.ok(text.includes('第一行 第二行'), '软换行应合并为空格'); +}); + +test('回归#9-4b 硬换行(行尾两空格)仍输出 w:br', async () => { + const body = '第一行 \n第二行\n'; + const out = await unpackDocx(toDocx(pkg(body))); + const doc = dec.decode(out.get('word/document.xml')!); + assert.ok(doc.includes(''), '硬换行应保留 w:br'); +}); + +test('回归#9-5 表格:tblW 满宽 dxa + fixed 布局', async () => { + const body = '| 列A | 列B |\n| --- | --- |\n| 甲 | 乙 |\n'; + const out = await unpackDocx(toDocx(pkg(body))); + const doc = dec.decode(out.get('word/document.xml')!); + assert.ok(doc.includes(''), '表格应满页宽(9026 dxa)'); + assert.ok(doc.includes(''), '表格应固定布局'); +}); + +test('回归#9-6 表格:单元格垂直居中 + 内边距', async () => { + const body = '| 列A | 列B |\n| --- | --- |\n| 甲 | 乙 |\n'; + const out = await unpackDocx(toDocx(pkg(body))); + const doc = dec.decode(out.get('word/document.xml')!); + assert.ok(doc.includes(''), '单元格应垂直居中'); + assert.ok(doc.includes(''), '应声明单元格内边距'); +}); + +test('回归#9-7 callout 同行标题:> [!tip] 实用提示 → 去标识、标题加粗、类型背景色', async () => { + 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('[!tip]'), '不应残留 [!. ] 标识'); + assert.ok(!text.includes('TIP'), '不应输出 TIP 标签文本'); + assert.ok(text.includes('实用提示'), '标题文本应保真'); + assert.ok(text.includes('Markdown 是最通用的文档格式'), '正文应保真'); + assert.ok(doc.includes('w:fill="ECF7EC"'), 'TIP 应使用类型背景色'); + const titleRun = doc.match(/<\/w:rPr>]*>实用提示<\/w:t><\/w:r>/); + assert.ok(titleRun, '标题 run 应加粗'); + const bodyBold = doc.match(/<\/w:rPr>]*>Markdown<\/w:t>/); + assert.ok(!bodyBold, '同行正文 run 不应加粗(仅标题加粗)'); +}); + +test('回归#9-7b callout 类型色:warning 黄 / note 蓝 / quote 灰', async () => { + const body = '> [!warning] 注意\n> 内容\n\n> [!note] 说明\n> 内容\n\n> [!quote] 引文\n> 内容\n'; + const out = await unpackDocx(toDocx(pkg(body))); + const doc = dec.decode(out.get('word/document.xml')!); + assert.ok(doc.includes('w:fill="FCF8E8"'), 'warning 应使用黄色背景'); + assert.ok(doc.includes('w:fill="F0F7FA"'), 'note 应使用蓝色背景'); + assert.ok(doc.includes('w:fill="F5F5F5"'), 'quote 应使用灰色背景'); }); \ 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 1d33045..b22fe5c 100644 --- a/packages/mdpkg/web/mdpkg-web.iife.js +++ b/packages/mdpkg/web/mdpkg-web.iife.js @@ -23372,10 +23372,14 @@ ${bodyHtml} // src/image-size.ts function readImageSize(data) { - if (pngSize(data) != null) return pngSize(data); - if (jpegSize(data) != null) return jpegSize(data); - if (gifSize(data) != null) return gifSize(data); - if (webpSize(data) != null) return webpSize(data); + const png = pngSize(data); + if (png) return png; + const jpeg = jpegSize(data); + if (jpeg) return jpeg; + const gif = gifSize(data); + if (gif) return gif; + const webp = webpSize(data); + if (webp) return webp; return null; } function pngSize(data) { @@ -23397,6 +23401,10 @@ ${bodyHtml} offset++; continue; } + while (offset + 1 < data.length && data[offset + 1] === 255) { + offset++; + } + if (offset + 1 >= data.length) break; const marker = data[offset + 1]; if (marker === 192 || marker === 193 || marker === 194) { const height = readU16BE(data, offset + 5); @@ -23442,7 +23450,7 @@ ${bodyHtml} const b22 = data[23]; const b3 = data[24]; const width = 1 + ((b1 & 63) << 8 | b0); - const height = 1 + (b3 << 6 | (b22 & 240) >> 4 | (b1 & 192) >> 2); + const height = 1 + ((b1 & 192) >> 6 | b22 << 2 | (b3 & 15) << 10); return { width, height }; } return null; @@ -23496,7 +23504,7 @@ ${bodyHtml} const parts = text8.split("\n"); let out = ""; for (let i2 = 0; i2 < parts.length; i2++) { - if (i2 > 0) out += `${rPrXml(fmt)}`; + if (i2 > 0 && parts[i2]) out += plainRun(" ", fmt); if (parts[i2]) out += plainRun(parts[i2], fmt); } return out; @@ -23570,8 +23578,38 @@ ${bodyHtml} "TODO", "QUOTE", "CITATION", - "EXAMPLE" + "EXAMPLE", + "FAILURE", + "ERROR", + "BUG", + "QUESTION", + "HINT" ]); + var CALLOUT_COLORS = { + 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"] + }; + var CALLOUT_DEFAULT = ["F0F7FA", "6C9DBF"]; function extractCallouts(tree) { if (!tree.children) return; for (let i2 = 0; i2 < tree.children.length; i2++) { @@ -23581,11 +23619,11 @@ ${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*(?:\n|$)/); + const m = firstText.value.match(/^\[!([A-Za-z]+)\]\s*/); if (!m) continue; const tag = m[1].toUpperCase(); if (!CALLOUT_TYPES.has(tag)) continue; - const remainingText = firstText.value.replace(/^\[!([A-Za-z]+)\]\s*/, ""); + const remainingText = firstText.value.slice(m[0].length); if (remainingText) { firstText.value = remainingText; } else { @@ -23670,15 +23708,21 @@ ${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 }); + ctx.rels.push({ id: rId, type: "image", target: mediaPath.replace(/^word\//, "") }); const EMU_PER_PX = 9525; const intrinsic = readImageSize(data); let w; let h; if (intrinsic) { - const fullW = intrinsic.width * EMU_PER_PX; - w = Math.min(fullW, ctx.imageWidthEmu); - h = ctx.imageHeightEmu !== DEFAULT_IMAGE_HEIGHT_EMU ? ctx.imageHeightEmu : Math.round(w * (intrinsic.height / intrinsic.width)); + if (intrinsic.width === 0 || intrinsic.height === 0) { + w = ctx.imageWidthEmu; + h = ctx.imageHeightEmu; + ctx.warnings.push(`\u56FE\u7247\u56FA\u6709\u5C3A\u5BF8\u65E0\u6548(0)\uFF0C\u5DF2\u4F7F\u7528\u7F3A\u7701\u5C3A\u5BF8: ${src}`); + } 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)); + } } else { w = ctx.imageWidthEmu; h = ctx.imageHeightEmu; @@ -23712,15 +23756,17 @@ ${bodyHtml} `; } function serializeList(node2, ctx, ilvl) { - const numId = node2.ordered ? 2 : 1; - const start = Number(node2.start) || 1; + let numId = 1; + if (node2.ordered) { + numId = ctx.nextNumId++; + ctx.numList.push({ numId, start: Number(node2.start) || 1 }); + } let out = ""; - (node2.children ?? []).forEach((item, idx) => { + (node2.children ?? []).forEach((item) => { const it = item; if (it.type !== "listItem") return; const checked = typeof it.checked === "boolean" ? it.checked ? "\u2611 " : "\u2610 " : ""; - const startOverride = idx === 0 && numId === 2 && start !== 1 ? `` : ""; - const numPr = `${startOverride}`; + const numPr = ``; let first = true; for (const child of it.children ?? []) { if (child.type === "list") { @@ -23759,15 +23805,50 @@ ${bodyHtml} flushInline(); return out || `${pPr ? `${pPr}` : ""}${prefix}`; } + function calloutPPr(extra) { + if (!extra?.callout) return ""; + const { fill, border } = extra.callout; + return ``; + } + function calloutHeadXml(children2, ctx) { + let out = ""; + let headDone = false; + for (const c of children2) { + const n = c; + if (n.type === "text" && typeof n.value === "string" && !headDone) { + 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; + } + } else { + out += inlineToXml(c, ctx, headDone ? {} : { b: true }); + } + } + return out; + } function blockToXml(node2, ctx, extra) { switch (node2.type) { case "heading": { const depth = Math.min(6, Math.max(1, Number(node2.depth) || 1)); - return `${inlineChildren(node2.children, ctx)}`; + const style = `Heading${depth}`; + const hasBlockMath = node2.children?.some( + (c) => c.type === "math" && c.display + ); + if (hasBlockMath) { + return splitParagraphAtBlockMath(node2, ctx, { style }); + } + return `${calloutPPr(extra)}${inlineChildren(node2.children, ctx)}`; } case "paragraph": { const pStyle = extra?.style ?? (extra?.numPr ? "ListParagraph" : ""); - const pPr = `${pStyle ? `` : ""}${extra?.numPr ?? ""}`; + const pPr = `${pStyle ? `` : ""}${extra?.numPr ?? ""}${calloutPPr(extra)}`; const prefix = extra?.prefix ? plainRun(extra.prefix, {}) : ""; const headerFmt = extra?.headerBold ? headerBoldFmt({}) : {}; const hasBlockMath = node2.children?.some( @@ -23780,15 +23861,7 @@ ${bodyHtml} } case "code": { const lines = String(node2.value ?? "").split("\n"); - const lang = typeof node2.lang === "string" ? node2.lang.trim() : ""; - const annotate = lang && lang !== "mermaid"; - return lines.map((line, idx) => { - let runs = `${esc(line)}`; - if (idx === 0 && annotate) { - runs = `[${esc(lang)}] ${runs}`; - } - return `${runs}`; - }).join(""); + return lines.map((line) => `${esc(line)}`).join(""); } case "list": return serializeList(node2, ctx, 0); @@ -23797,7 +23870,16 @@ ${bodyHtml} } case "callout": { const tag = String(node2.tag ?? "NOTE"); - return `${esc(tag)}` + node2.children.map((c) => blockToXml(c, ctx)).join(""); + const [fill, border] = CALLOUT_COLORS[tag] ?? CALLOUT_DEFAULT; + const children2 = node2.children ?? []; + const first = children2[0]; + const rest = first && first.type === "paragraph" ? children2.slice(1) : children2; + let out = ""; + if (first && first.type === "paragraph" && (first.children?.length ?? 0) > 0) { + out += `${calloutPPr({ callout: { fill, border } })}${calloutHeadXml(first.children, ctx)}`; + } + out += rest.map((c) => blockToXml(c, ctx, { callout: { fill, border } })).join(""); + return out; } case "thematicBreak": { return ''; @@ -23819,8 +23901,9 @@ ${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 = ''; + let out = ''; out += "" + ["top", "left", "bottom", "right", "insideH", "insideV"].map((b) => ``).join("") + ""; + out += ''; out += ''; out += `${colWidths.map((w) => ``).join("")}`; rows.forEach((row, ri) => { @@ -23829,6 +23912,7 @@ ${bodyHtml} const isHeader = ri === 0; out += ""; out += ``; + out += ''; if (isHeader) out += ''; out += ""; const blocks2 = cell.children ?? []; @@ -23848,7 +23932,7 @@ ${bodyHtml} function computeTableColumnWidths(rows, colCount) { const DXA_PER_UNIT = 120; const MIN_COL_W = 800; - const MAX_TOTAL = 9e3; + const MAX_TOTAL = 9026; const widths = new Array(colCount).fill(0); let hasContent = false; for (let ci = 0; ci < colCount; ci++) { @@ -23960,7 +24044,7 @@ ${items} - + @@ -23975,27 +24059,32 @@ ${items} `; - var NUMBERING_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("")} + 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 lvlText = Array.from({ length: lvl + 1 }, (_, i2) => `%${i2 + 1}`).join(".") + "."; - const left = 720 + lvl * 720; - return ``; - }).join("")} + const lvlText = Array.from({ length: lvl + 1 }, (_, i2) => `%${i2 + 1}`).join(".") + "."; + const left = 720 + lvl * 720; + return ``; + }).join("")} - - +${nums.join("\n")} `; + } function toDocx(files, opts = {}, onWarning) { const manifestRaw = files.get("manifest.json"); let manifest; @@ -24018,18 +24107,23 @@ ${[0, 1, 2, 3, 4, 5, 6, 7].map((lvl) => { const tree = unified().use(remarkParse).use(remarkGfm).parse(guardEscapes(expanded)); extractMath(tree); extractCallouts(tree); + const explicitImageHeight = opts.imageHeightEmu !== void 0; const ctx = { files, entryDir, symbols: opts.symbols !== false && manifest.extensions?.symbols !== "off", imageWidthEmu: opts.imageWidthEmu ?? DEFAULT_IMAGE_WIDTH_EMU, imageHeightEmu: opts.imageHeightEmu ?? DEFAULT_IMAGE_HEIGHT_EMU, + explicitImageHeight, media: [], rels: [], warnings: [], nextRid: 3, // rId1=styles、rId2=numbering 已占用 - docPrId: 1 + docPrId: 1, + nextNumId: 2, + // numId 1 固定绑定项目符号 abstractNum + numList: [] }; const bodyXml = tree.children?.map((c) => blockToXml(c, ctx)).join("") ?? ""; const enc = (s) => new TextEncoder().encode(s); @@ -24039,7 +24133,7 @@ ${[0, 1, 2, 3, 4, 5, 6, 7].map((lvl) => { out.set("word/document.xml", enc(documentXml(bodyXml))); out.set("word/_rels/document.xml.rels", enc(documentRelsXml(ctx))); out.set("word/styles.xml", enc(STYLES_XML)); - out.set("word/numbering.xml", enc(NUMBERING_XML)); + out.set("word/numbering.xml", enc(numberingXml(ctx))); for (const m of ctx.media) out.set(m.path, m.data); const bytes = packRaw(out); if (onWarning) for (const w of ctx.warnings) onWarning(w); diff --git a/packages/mdpkg/web/mdpkg-web.js b/packages/mdpkg/web/mdpkg-web.js index 1eb5a9c..589d8cc 100644 --- a/packages/mdpkg/web/mdpkg-web.js +++ b/packages/mdpkg/web/mdpkg-web.js @@ -23352,10 +23352,14 @@ function toMarkdown(files, opts = {}) { // src/image-size.ts function readImageSize(data) { - if (pngSize(data) != null) return pngSize(data); - if (jpegSize(data) != null) return jpegSize(data); - if (gifSize(data) != null) return gifSize(data); - if (webpSize(data) != null) return webpSize(data); + const png = pngSize(data); + if (png) return png; + const jpeg = jpegSize(data); + if (jpeg) return jpeg; + const gif = gifSize(data); + if (gif) return gif; + const webp = webpSize(data); + if (webp) return webp; return null; } function pngSize(data) { @@ -23377,6 +23381,10 @@ function jpegSize(data) { offset++; continue; } + while (offset + 1 < data.length && data[offset + 1] === 255) { + offset++; + } + if (offset + 1 >= data.length) break; const marker = data[offset + 1]; if (marker === 192 || marker === 193 || marker === 194) { const height = readU16BE(data, offset + 5); @@ -23422,7 +23430,7 @@ function webpSize(data) { const b22 = data[23]; const b3 = data[24]; const width = 1 + ((b1 & 63) << 8 | b0); - const height = 1 + (b3 << 6 | (b22 & 240) >> 4 | (b1 & 192) >> 2); + const height = 1 + ((b1 & 192) >> 6 | b22 << 2 | (b3 & 15) << 10); return { width, height }; } return null; @@ -23476,7 +23484,7 @@ function textToRuns(text8, fmt) { const parts = text8.split("\n"); let out = ""; for (let i2 = 0; i2 < parts.length; i2++) { - if (i2 > 0) out += `${rPrXml(fmt)}`; + if (i2 > 0 && parts[i2]) out += plainRun(" ", fmt); if (parts[i2]) out += plainRun(parts[i2], fmt); } return out; @@ -23550,8 +23558,38 @@ var CALLOUT_TYPES = /* @__PURE__ */ new Set([ "TODO", "QUOTE", "CITATION", - "EXAMPLE" + "EXAMPLE", + "FAILURE", + "ERROR", + "BUG", + "QUESTION", + "HINT" ]); +var CALLOUT_COLORS = { + 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"] +}; +var CALLOUT_DEFAULT = ["F0F7FA", "6C9DBF"]; function extractCallouts(tree) { if (!tree.children) return; for (let i2 = 0; i2 < tree.children.length; i2++) { @@ -23561,11 +23599,11 @@ 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*(?:\n|$)/); + const m = firstText.value.match(/^\[!([A-Za-z]+)\]\s*/); if (!m) continue; const tag = m[1].toUpperCase(); if (!CALLOUT_TYPES.has(tag)) continue; - const remainingText = firstText.value.replace(/^\[!([A-Za-z]+)\]\s*/, ""); + const remainingText = firstText.value.slice(m[0].length); if (remainingText) { firstText.value = remainingText; } else { @@ -23650,15 +23688,21 @@ 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 }); + ctx.rels.push({ id: rId, type: "image", target: mediaPath.replace(/^word\//, "") }); const EMU_PER_PX = 9525; const intrinsic = readImageSize(data); let w; let h; if (intrinsic) { - const fullW = intrinsic.width * EMU_PER_PX; - w = Math.min(fullW, ctx.imageWidthEmu); - h = ctx.imageHeightEmu !== DEFAULT_IMAGE_HEIGHT_EMU ? ctx.imageHeightEmu : Math.round(w * (intrinsic.height / intrinsic.width)); + if (intrinsic.width === 0 || intrinsic.height === 0) { + w = ctx.imageWidthEmu; + h = ctx.imageHeightEmu; + ctx.warnings.push(`\u56FE\u7247\u56FA\u6709\u5C3A\u5BF8\u65E0\u6548(0)\uFF0C\u5DF2\u4F7F\u7528\u7F3A\u7701\u5C3A\u5BF8: ${src}`); + } 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)); + } } else { w = ctx.imageWidthEmu; h = ctx.imageHeightEmu; @@ -23692,15 +23736,17 @@ function imageToXml(node2, ctx, fmt) { `; } function serializeList(node2, ctx, ilvl) { - const numId = node2.ordered ? 2 : 1; - const start = Number(node2.start) || 1; + let numId = 1; + if (node2.ordered) { + numId = ctx.nextNumId++; + ctx.numList.push({ numId, start: Number(node2.start) || 1 }); + } let out = ""; - (node2.children ?? []).forEach((item, idx) => { + (node2.children ?? []).forEach((item) => { const it = item; if (it.type !== "listItem") return; const checked = typeof it.checked === "boolean" ? it.checked ? "\u2611 " : "\u2610 " : ""; - const startOverride = idx === 0 && numId === 2 && start !== 1 ? `` : ""; - const numPr = `${startOverride}`; + const numPr = ``; let first = true; for (const child of it.children ?? []) { if (child.type === "list") { @@ -23739,15 +23785,50 @@ function splitParagraphAtBlockMath(node2, ctx, extra) { flushInline(); return out || `${pPr ? `${pPr}` : ""}${prefix}`; } +function calloutPPr(extra) { + if (!extra?.callout) return ""; + const { fill, border } = extra.callout; + return ``; +} +function calloutHeadXml(children2, ctx) { + let out = ""; + let headDone = false; + for (const c of children2) { + const n = c; + if (n.type === "text" && typeof n.value === "string" && !headDone) { + 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; + } + } else { + out += inlineToXml(c, ctx, headDone ? {} : { b: true }); + } + } + return out; +} function blockToXml(node2, ctx, extra) { switch (node2.type) { case "heading": { const depth = Math.min(6, Math.max(1, Number(node2.depth) || 1)); - return `${inlineChildren(node2.children, ctx)}`; + const style = `Heading${depth}`; + const hasBlockMath = node2.children?.some( + (c) => c.type === "math" && c.display + ); + if (hasBlockMath) { + return splitParagraphAtBlockMath(node2, ctx, { style }); + } + return `${calloutPPr(extra)}${inlineChildren(node2.children, ctx)}`; } case "paragraph": { const pStyle = extra?.style ?? (extra?.numPr ? "ListParagraph" : ""); - const pPr = `${pStyle ? `` : ""}${extra?.numPr ?? ""}`; + const pPr = `${pStyle ? `` : ""}${extra?.numPr ?? ""}${calloutPPr(extra)}`; const prefix = extra?.prefix ? plainRun(extra.prefix, {}) : ""; const headerFmt = extra?.headerBold ? headerBoldFmt({}) : {}; const hasBlockMath = node2.children?.some( @@ -23760,15 +23841,7 @@ function blockToXml(node2, ctx, extra) { } case "code": { const lines = String(node2.value ?? "").split("\n"); - const lang = typeof node2.lang === "string" ? node2.lang.trim() : ""; - const annotate = lang && lang !== "mermaid"; - return lines.map((line, idx) => { - let runs = `${esc(line)}`; - if (idx === 0 && annotate) { - runs = `[${esc(lang)}] ${runs}`; - } - return `${runs}`; - }).join(""); + return lines.map((line) => `${esc(line)}`).join(""); } case "list": return serializeList(node2, ctx, 0); @@ -23777,7 +23850,16 @@ function blockToXml(node2, ctx, extra) { } case "callout": { const tag = String(node2.tag ?? "NOTE"); - return `${esc(tag)}` + node2.children.map((c) => blockToXml(c, ctx)).join(""); + const [fill, border] = CALLOUT_COLORS[tag] ?? CALLOUT_DEFAULT; + const children2 = node2.children ?? []; + const first = children2[0]; + const rest = first && first.type === "paragraph" ? children2.slice(1) : children2; + let out = ""; + if (first && first.type === "paragraph" && (first.children?.length ?? 0) > 0) { + out += `${calloutPPr({ callout: { fill, border } })}${calloutHeadXml(first.children, ctx)}`; + } + out += rest.map((c) => blockToXml(c, ctx, { callout: { fill, border } })).join(""); + return out; } case "thematicBreak": { return ''; @@ -23799,8 +23881,9 @@ 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 = ''; + let out = ''; out += "" + ["top", "left", "bottom", "right", "insideH", "insideV"].map((b) => ``).join("") + ""; + out += ''; out += ''; out += `${colWidths.map((w) => ``).join("")}`; rows.forEach((row, ri) => { @@ -23809,6 +23892,7 @@ function tableToXml(node2, ctx) { const isHeader = ri === 0; out += ""; out += ``; + out += ''; if (isHeader) out += ''; out += ""; const blocks2 = cell.children ?? []; @@ -23828,7 +23912,7 @@ function tableToXml(node2, ctx) { function computeTableColumnWidths(rows, colCount) { const DXA_PER_UNIT = 120; const MIN_COL_W = 800; - const MAX_TOTAL = 9e3; + const MAX_TOTAL = 9026; const widths = new Array(colCount).fill(0); let hasContent = false; for (let ci = 0; ci < colCount; ci++) { @@ -23940,7 +24024,7 @@ var STYLES_XML = ` - + @@ -23955,27 +24039,32 @@ var STYLES_XML = ` `; -var NUMBERING_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("")} + 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 lvlText = Array.from({ length: lvl + 1 }, (_, i2) => `%${i2 + 1}`).join(".") + "."; - const left = 720 + lvl * 720; - return ``; -}).join("")} + const lvlText = Array.from({ length: lvl + 1 }, (_, i2) => `%${i2 + 1}`).join(".") + "."; + const left = 720 + lvl * 720; + return ``; + }).join("")} - - +${nums.join("\n")} `; +} function toDocx(files, opts = {}, onWarning) { const manifestRaw = files.get("manifest.json"); let manifest; @@ -23998,18 +24087,23 @@ function toDocx(files, opts = {}, onWarning) { const tree = unified().use(remarkParse).use(remarkGfm).parse(guardEscapes(expanded)); extractMath(tree); extractCallouts(tree); + const explicitImageHeight = opts.imageHeightEmu !== void 0; const ctx = { files, entryDir, symbols: opts.symbols !== false && manifest.extensions?.symbols !== "off", imageWidthEmu: opts.imageWidthEmu ?? DEFAULT_IMAGE_WIDTH_EMU, imageHeightEmu: opts.imageHeightEmu ?? DEFAULT_IMAGE_HEIGHT_EMU, + explicitImageHeight, media: [], rels: [], warnings: [], nextRid: 3, // rId1=styles、rId2=numbering 已占用 - docPrId: 1 + docPrId: 1, + nextNumId: 2, + // numId 1 固定绑定项目符号 abstractNum + numList: [] }; const bodyXml = tree.children?.map((c) => blockToXml(c, ctx)).join("") ?? ""; const enc = (s) => new TextEncoder().encode(s); @@ -24019,7 +24113,7 @@ function toDocx(files, opts = {}, onWarning) { out.set("word/document.xml", enc(documentXml(bodyXml))); out.set("word/_rels/document.xml.rels", enc(documentRelsXml(ctx))); out.set("word/styles.xml", enc(STYLES_XML)); - out.set("word/numbering.xml", enc(NUMBERING_XML)); + out.set("word/numbering.xml", enc(numberingXml(ctx))); for (const m of ctx.media) out.set(m.path, m.data); const bytes = packRaw(out); if (onWarning) for (const w of ctx.warnings) onWarning(w);