vscode-colaview 0.3.3 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/.vscode/settings.json +1 -1
  2. package/CHANGELOG.md +20 -4
  3. package/README.md +310 -286
  4. package/README_CN.md +310 -286
  5. package/RELEASE_NOTES.md +36 -4
  6. package/esbuild.js +2 -0
  7. package/package.json +58 -19
  8. package/package.nls.json +14 -0
  9. package/package.nls.zh-cn.json +14 -0
  10. package/src/commands/commands.ts +48 -0
  11. package/src/docx/docx-builder.ts +241 -0
  12. package/src/export/docx-exporter.ts +961 -961
  13. package/src/export/html-exporter.ts +8 -2
  14. package/src/export/pdf-exporter.ts +65 -0
  15. package/src/export/pptx-exporter.ts +63 -0
  16. package/src/export/render-export-images.ts +386 -386
  17. package/src/export/theme-style.ts +195 -195
  18. package/src/pptx/pptx-builder.ts +249 -0
  19. package/src/pptx/zip.ts +158 -0
  20. package/src/present/presenter.ts +64 -0
  21. package/src/preview/preview-manager.ts +783 -541
  22. package/src/preview/webview/app.ts +588 -370
  23. package/src/preview/webview/index.html +167 -146
  24. package/src/slides/deck.ts +397 -0
  25. package/src/slides/markdown.ts +393 -0
  26. package/src/slides/render.ts +484 -0
  27. package/src/slides/slides.css +1082 -0
  28. package/src/themes/built-in/bear.css +89 -38
  29. package/src/themes/built-in/dark.css +87 -28
  30. package/src/themes/built-in/dracula.css +93 -34
  31. package/src/themes/built-in/elegant.css +109 -45
  32. package/src/themes/built-in/gruvbox.css +97 -38
  33. package/src/themes/built-in/light.css +80 -20
  34. package/src/themes/built-in/midnight.css +93 -35
  35. package/src/themes/built-in/nord.css +93 -34
  36. package/src/themes/built-in/notion.css +98 -46
  37. package/src/themes/built-in/sepia.css +99 -44
  38. package/src/themes/built-in/solarized-dark.css +94 -35
  39. package/src/themes/built-in/writer.css +99 -52
  40. package/src/themes/theme-manager.ts +207 -180
  41. package/src/types/colamd-renderer.d.ts +47 -47
@@ -1,387 +1,387 @@
1
- // 公式(KaTeX) / 图(Mermaid) 转 PNG —— 复用 puppeteer-core + 系统 Chrome/Edge。
2
- // 扩展宿主是纯 Node(无 DOM),故用无头浏览器把 `$$`/`$` 公式与 ```mermaid 代码块
3
- // 光栅化为 PNG,并把源 Markdown 重写为 `![...](colamd-xxx-N.png)` 占位图,
4
- // 与 colamd-extend 渲染进程的做法一致(最终由 docx 的 ImageRun 内嵌)。
5
- import * as fs from 'fs';
6
- import * as path from 'path';
7
- import katex from 'katex';
8
- import { findChromePath } from './pdf-exporter';
9
-
10
- export interface RichImageResult {
11
- /** 重写后的 Markdown(公式/图已替换为图片占位)。 */
12
- content: string;
13
- /** 占位图名字 → PNG dataURL。 */
14
- images: Record<string, string>;
15
- /** 占位图名字 → 目标尺寸(CSS 像素)。 */
16
- imageSizes: Record<string, { width: number; height: number }>;
17
- }
18
-
19
- interface RenderItem {
20
- kind: 'math-block' | 'math-inline' | 'mermaid';
21
- tex: string;
22
- name: string;
23
- }
24
-
25
- function escapeHtml(text: string): string {
26
- return text
27
- .replace(/&/g, '&amp;')
28
- .replace(/</g, '&lt;')
29
- .replace(/>/g, '&gt;');
30
- }
31
-
32
- /** 定位依赖内的静态资源(打包后优先取 out/assets 下的副本,其次回退 node_modules)。 */
33
- function assetPath(pkg: string, file: string): string | null {
34
- const candidates: string[] = [];
35
- // 打包进 vsix 时 node_modules 被 .vscodeignore 排除,故把散件复制到 out/assets/。
36
- candidates.push(path.resolve(__dirname, 'assets', path.basename(file)));
37
- try {
38
- candidates.push(path.resolve(path.dirname(require.resolve(`${pkg}/package.json`)), file));
39
- } catch {
40
- /* ignore */
41
- }
42
- candidates.push(path.resolve(__dirname, '..', 'node_modules', pkg, file));
43
- for (const candidate of candidates) {
44
- if (fs.existsSync(candidate)) return candidate;
45
- }
46
- return null;
47
- }
48
-
49
- function readIfExists(p: string | null): string | null {
50
- if (!p) return null;
51
- try {
52
- return fs.readFileSync(p, 'utf-8');
53
- } catch {
54
- return null;
55
- }
56
- }
57
-
58
- /**
59
- * 把 katex.min.css 里相对路径的字体 URL 换成 base64 data URI。
60
- *
61
- * 公式截图页通过 page.setContent 加载(about:blank 基准),CSS 内联后
62
- * `url(fonts/KaTeX_*.woff2)` 解析不到任何文件 —— KaTeX 全部退回回退字体,
63
- * 公式字形错乱(问题表现就是「导出到 Word 时公式没有正确渲染」)。
64
- * 字体优先取 CSS 同级的 fonts/ 目录,其次 out/assets/katex-fonts/,
65
- * 最后回退 node_modules 的 katex 发行目录。
66
- */
67
- function inlineKatexFonts(css: string, cssPath: string): string {
68
- const candidates = [
69
- path.resolve(path.dirname(cssPath), 'fonts'),
70
- path.resolve(__dirname, 'assets', 'katex-fonts'),
71
- ];
72
- try {
73
- const katexDist = path.dirname(require.resolve('katex/package.json'));
74
- candidates.push(path.join(katexDist, 'dist', 'fonts'), path.join(katexDist, 'fonts'));
75
- } catch {
76
- /* ignore */
77
- }
78
- const fontDir = candidates.find((dir) => fs.existsSync(dir));
79
- if (!fontDir) return css;
80
-
81
- const cache = new Map<string, string>();
82
- const load = (file: string): string | null => {
83
- if (cache.has(file)) return cache.get(file)!;
84
- let dataUri: string | null = null;
85
- try {
86
- const buf = fs.readFileSync(path.join(fontDir, file));
87
- dataUri = `data:font/woff2;base64,${buf.toString('base64')}`;
88
- } catch {
89
- /* ignore */
90
- }
91
- cache.set(file, dataUri ?? '');
92
- return dataUri;
93
- };
94
-
95
- return css.replace(/url\(\s*['"]?(fonts\/[^)'"]+)['"]?\s*\)/g, (match, file: string) => {
96
- const dataUri = load(file);
97
- return dataUri ? `url(${dataUri})` : match;
98
- });
99
- }
100
-
101
- /** 是否为纯数字/货币式内容(避免把 "$5.99" 之类误判为行内公式)。 */
102
- function isPlainNumber(s: string): boolean {
103
- return /^[\d\s.,%\-+()]*$/.test(s);
104
- }
105
-
106
- /** sRGB 按权重混合,等价于 `color-mix(in srgb, a w%, b)`。入参出参都不带 `#`。 */
107
- function mixSrgb(a: string, b: string, weightA: number): string {
108
- const parse = (hex: string) => [0, 2, 4].map((index) => Number.parseInt(hex.slice(index, index + 2), 16) || 0);
109
- const [ra, ga, ba] = parse(a);
110
- const [rb, gb, bb] = parse(b);
111
- const mix = (x: number, y: number) => Math.max(0, Math.min(255, Math.round(x * weightA + y * (1 - weightA))));
112
- return [mix(ra, rb), mix(ga, gb), mix(ba, bb)]
113
- .map((value) => value.toString(16).padStart(2, '0'))
114
- .join('')
115
- .toUpperCase();
116
- }
117
-
118
- /**
119
- * Mermaid 画图用的调色板令牌(镜像 colamd-extend diagramPrintPalette 的推导规则)。
120
- * 令牌与 DocxStyle 同源:「浅色跟随主题、深色整体回落浅色」,混合比例照抄
121
- * colamd.css 的 `.cm-md-mermaid`(18% / 28% / 45% 三档),两边要一起改。
122
- *
123
- * 但代码块的底不一定是纸的颜色:elegant、bear 是浅色主题配深色代码块,它们的
124
- * codeBlockText 是浅色。Word 是白纸、PNG 也先铺白底,照搬就成了浅色线条落在
125
- * 白纸上,所以这类主题改按正文色画(2026-11-14,与 colamd-extend 一致)。
126
- */
127
- export interface DiagramPalette {
128
- background: string;
129
- foreground: string;
130
- accent: string;
131
- }
132
-
133
- /** 没有主题令牌时按浅色默认画(与 docx-exporter 的 DEFAULT_STYLE 同源)。 */
134
- const DEFAULT_DIAGRAM_PALETTE: DiagramPalette = {
135
- background: 'F6F8FA',
136
- foreground: '24292F',
137
- accent: '0969DA',
138
- };
139
-
140
- function normalizeHex(value: unknown, fallback: string): string {
141
- if (typeof value !== 'string') return fallback;
142
- const raw = value.trim().replace(/^#/, '');
143
- if (/^[0-9a-f]{6}$/i.test(raw)) return raw.toUpperCase();
144
- if (/^[0-9a-f]{3}$/i.test(raw)) return raw.split('').map((digit) => digit + digit).join('').toUpperCase();
145
- if (/^[0-9a-f]{8}$/i.test(raw)) return raw.slice(0, 6).toUpperCase();
146
- return fallback;
147
- }
148
-
149
- /** 感知亮度,判断代码块底色是深是浅。入参不带 `#`。 */
150
- function isDarkHex(hex: string): boolean {
151
- const channel = (index: number): number => (Number.parseInt(hex.slice(index, index + 2), 16) || 0) / 255;
152
- return 0.2126 * channel(0) + 0.7152 * channel(2) + 0.0722 * channel(4) < 0.5;
153
- }
154
-
155
- /** 从主题令牌推导 Mermaid 的 themeVariables(theme: 'base')。 */
156
- function mermaidThemeVariables(palette: DiagramPalette): Record<string, string> {
157
- const { background: bg, foreground: fg } = palette;
158
- const surface = mixSrgb(fg, bg, 0.18);
159
- const surfaceAlt = mixSrgb(fg, bg, 0.28);
160
- const border = mixSrgb(fg, bg, 0.45);
161
- return {
162
- background: `#${bg}`,
163
- textColor: `#${fg}`,
164
- primaryTextColor: `#${fg}`,
165
- secondaryTextColor: `#${fg}`,
166
- tertiaryTextColor: `#${fg}`,
167
- primaryColor: `#${surface}`,
168
- secondaryColor: `#${surfaceAlt}`,
169
- tertiaryColor: `#${bg}`,
170
- mainBkg: `#${surface}`,
171
- clusterBkg: `#${surface}`,
172
- clusterBorder: `#${border}`,
173
- primaryBorderColor: `#${border}`,
174
- secondaryBorderColor: `#${border}`,
175
- tertiaryBorderColor: `#${border}`,
176
- lineColor: `#${fg}`,
177
- edgeLabelBackground: `#${bg}`,
178
- noteBkgColor: `#${surfaceAlt}`,
179
- noteTextColor: `#${fg}`,
180
- noteBorderColor: `#${border}`,
181
- actorBkg: `#${surface}`,
182
- actorBorder: `#${border}`,
183
- actorTextColor: `#${fg}`,
184
- actorLineColor: `#${border}`,
185
- signalColor: `#${fg}`,
186
- signalTextColor: `#${fg}`,
187
- labelBoxBkgColor: `#${surface}`,
188
- labelBoxBorderColor: `#${border}`,
189
- labelTextColor: `#${fg}`,
190
- loopTextColor: `#${fg}`,
191
- activationBkgColor: `#${surfaceAlt}`,
192
- sequenceNumberColor: `#${bg}`,
193
- sectionBkgColor: `#${surface}`,
194
- altSectionBkgColor: `#${bg}`,
195
- sectionBkgColor2: `#${surfaceAlt}`,
196
- taskBkgColor: `#${surfaceAlt}`,
197
- taskBorderColor: `#${border}`,
198
- taskTextColor: `#${fg}`,
199
- taskTextOutsideColor: `#${fg}`,
200
- activeTaskBkgColor: `#${mixSrgb(palette.accent, bg, 0.28)}`,
201
- activeTaskBorderColor: `#${palette.accent}`,
202
- doneTaskBkgColor: `#${bg}`,
203
- doneTaskBorderColor: `#${border}`,
204
- critBkgColor: `#${mixSrgb(fg, bg, 0.45)}`,
205
- critBorderColor: `#${fg}`,
206
- todayLineColor: `#${palette.accent}`,
207
- pie1: `#${surface}`,
208
- pie2: `#${surfaceAlt}`,
209
- pie3: `#${mixSrgb(palette.accent, bg, 0.18)}`,
210
- pieTitleTextColor: `#${fg}`,
211
- pieSectionTextColor: `#${fg}`,
212
- pieStrokeColor: `#${border}`,
213
- };
214
- }
215
-
216
- /** 扫描 Markdown,用占位图重写公式/Mermaid 并收集各自内容。 */
217
- function scan(markdown: string): { content: string; items: RenderItem[] } {
218
- const items: RenderItem[] = [];
219
- let rewritten = markdown;
220
- let formulaIndex = 0;
221
- let diagramIndex = 0;
222
-
223
- // 1) Mermaid 代码块
224
- rewritten = rewritten.replace(/```mermaid[ \t]*\n([\s\S]*?)\n```/g, (_match, code: string) => {
225
- diagramIndex += 1;
226
- const name = `colamd-diagram-${diagramIndex}.png`;
227
- items.push({ kind: 'mermaid', tex: String(code), name });
228
- return `![示意图 ${diagramIndex}](${name})`;
229
- });
230
-
231
- // 2) 块级公式 $$...$$
232
- rewritten = rewritten.replace(/\$\$([\s\S]+?)\$\$/g, (_match, tex: string) => {
233
- formulaIndex += 1;
234
- const name = `colamd-formula-${formulaIndex}.png`;
235
- items.push({ kind: 'math-block', tex: String(tex), name });
236
- return `![公式 ${formulaIndex}](${name})`;
237
- });
238
-
239
- // 3) 行内公式 $...$(块级已替换完,仅剩单行非空、非货币)
240
- rewritten = rewritten.replace(/\$([^$\n]+?)\$/g, (_match, tex: string) => {
241
- const value = String(tex).trim();
242
- if (value === '' || isPlainNumber(value)) return _match;
243
- formulaIndex += 1;
244
- const name = `colamd-formula-${formulaIndex}.png`;
245
- items.push({ kind: 'math-inline', tex: value, name });
246
- return `![公式 ${formulaIndex}](${name})`;
247
- });
248
-
249
- return { content: rewritten, items };
250
- }
251
-
252
- /**
253
- * 公式/Mermaid 光栅化。`paletteTokens` 来自主题令牌(DocxStyle 的子集),
254
- * Mermaid 图配色跟随当前预览主题;不传或令牌不全时按浅色默认画。
255
- */
256
- export async function renderMathAndMermaidToImages(
257
- markdown: string,
258
- paletteTokens?: { text?: unknown; codeBlockBackground?: unknown; codeBlockText?: unknown; link?: unknown },
259
- ): Promise<RichImageResult> {
260
- const bodyText = normalizeHex(paletteTokens?.text, DEFAULT_DIAGRAM_PALETTE.foreground);
261
- const codeBackground = normalizeHex(paletteTokens?.codeBlockBackground, DEFAULT_DIAGRAM_PALETTE.background);
262
- const codeText = normalizeHex(paletteTokens?.codeBlockText, bodyText);
263
- // 浅色主题配深色代码块(elegant / bear)时,codeBlockText 是浅色;Word 的白纸上
264
- // 会糊成一片。这类主题改按页面正文色画,底色换成白纸。
265
- const darkCodeBlock = isDarkHex(codeBackground);
266
- const palette: DiagramPalette = {
267
- background: darkCodeBlock ? 'FFFFFF' : codeBackground,
268
- foreground: darkCodeBlock ? bodyText : codeText,
269
- accent: normalizeHex(paletteTokens?.link, DEFAULT_DIAGRAM_PALETTE.accent),
270
- };
271
- const { content, items } = scan(markdown);
272
- if (items.length === 0) {
273
- return { content, images: {}, imageSizes: {} };
274
- }
275
-
276
- const katexCssPath = assetPath('katex', path.join('dist', 'katex.min.css'));
277
- const katexCssRaw = readIfExists(katexCssPath);
278
- // 字体转 base64 内联:page.setContent 的页面解析不到相对字体路径
279
- const katexCss = katexCssRaw && katexCssPath ? inlineKatexFonts(katexCssRaw, katexCssPath) : null;
280
- const mermaidJs = readIfExists(assetPath('mermaid', path.join('dist', 'mermaid.min.js')));
281
- const useMathml = !katexCss;
282
-
283
- const cards = items.map((item, index) => {
284
- if (item.kind === 'mermaid') {
285
- if (!mermaidJs) {
286
- return `<div class="card" id="card-${index}"><pre>${escapeHtml(item.tex)}</pre></div>`;
287
- }
288
- return `<div class="card" id="card-${index}"><pre class="mermaid">${escapeHtml(item.tex)}</pre></div>`;
289
- }
290
- const displayMode = item.kind === 'math-block';
291
- const katexOut = katex.renderToString(item.tex, {
292
- displayMode,
293
- throwOnError: false,
294
- output: useMathml ? 'mathml' : 'html',
295
- });
296
- return `<div class="card" id="card-${index}">${katexOut}</div>`;
297
- }).join('\n');
298
-
299
- const html = `<!DOCTYPE html>
300
- <html lang="zh"><head><meta charset="utf-8">
301
- ${katexCss ? `<style>${katexCss}</style>` : ''}
302
- <style>
303
- body { margin: 16px; background: #ffffff; }
304
- .card { display: inline-block; margin: 8px; vertical-align: middle; }
305
- .card pre { margin: 0; font-family: monospace; }
306
- </style>
307
- </head><body>
308
- ${cards}
309
- ${mermaidJs ? `<script>${mermaidJs}</script>` : ''}
310
- <script>
311
- (function () {
312
- if (!window.mermaid) { document.documentElement.dataset.ready = '1'; return; }
313
- mermaid.initialize({ startOnLoad: false, theme: 'base', themeVariables: ${JSON.stringify(mermaidThemeVariables(palette))}, securityLevel: 'loose' });
314
- var els = Array.prototype.slice.call(document.querySelectorAll('pre.mermaid'));
315
- var remaining = els.length;
316
- if (remaining === 0) { document.documentElement.dataset.ready = '1'; return; }
317
- els.forEach(function (el, i) {
318
- mermaid.render('mmd-' + i, el.textContent || '').then(function (result) {
319
- var tmp = document.createElement('template');
320
- tmp.innerHTML = result.svg;
321
- el.parentNode.replaceChild(tmp.content, el);
322
- }).catch(function () {
323
- el.outerHTML = '<span style="color:#999">mermaid render error</span>';
324
- }).finally(function () {
325
- remaining -= 1;
326
- if (remaining <= 0) document.documentElement.dataset.ready = '1';
327
- });
328
- });
329
- })();
330
- </script>
331
- </body></html>`;
332
-
333
- const chromePath = findChromePath();
334
- if (!chromePath) {
335
- // 无 Chrome/Edge:跳过图片渲染,公式/图回退为文本(占位图仅剩 alt 文本)。
336
- return { content, images: {}, imageSizes: {} };
337
- }
338
-
339
- // eslint-disable-next-line @typescript-eslint/no-var-requires
340
- const puppeteer = require('puppeteer-core');
341
- const browser = await puppeteer.launch({ headless: true, executablePath: chromePath });
342
- try {
343
- const page = await browser.newPage();
344
- // 测量用的窗口宽度。太窄的话稍宽的行内公式会在 KaTeX 内部折行,截出来的 PNG
345
- // 本身就是两行(导出 Word 后看到「公式换行」,镜像 colamd-extend MEASURE_WIDTH)。
346
- const MEASURE_WIDTH = 2000;
347
- await page.setViewport({ width: MEASURE_WIDTH, height: 900, deviceScaleFactor: 1 });
348
- await page.setContent(html, { waitUntil: 'load' });
349
- // 等待 mermaid 渲染完成(无 mermaid 时页面立即置 ready)
350
- await page.waitForFunction("document.documentElement.dataset.ready === '1'", { timeout: 15000 })
351
- .catch(() => { /* 超时也继续:至少能截到已渲染部分 */ });
352
-
353
- const images: Record<string, string> = {};
354
- const imageSizes: Record<string, { width: number; height: number }> = {};
355
-
356
- for (let index = 0; index < items.length; index += 1) {
357
- const item = items[index];
358
- const handle = await page.$(`#card-${index}`);
359
- if (!handle) continue;
360
- const box = await handle.boundingBox();
361
- if (!box || box.width < 1 || box.height < 1) continue;
362
- // puppeteer v25 起截图返回 Uint8Array(TypedArray 的 toString 会输出
363
- // 「137,80,78,…」逗号十进制串而不是 base64),必须先转 Buffer,
364
- // 否则 Word 里的图片数据全是坏的 —— 表现为图表/公式没有被正确渲染。
365
- const raw = (await handle.screenshot({ type: 'png' })) as Buffer | Uint8Array;
366
- const shot = Buffer.isBuffer(raw) ? raw : Buffer.from(raw as Uint8Array);
367
- if (!shot || shot.length === 0) continue;
368
-
369
- images[item.name] = `data:image/png;base64,${shot.toString('base64')}`;
370
- if (item.kind === 'math-inline') {
371
- // 行内公式缩放到正文字高(约 22px)
372
- const targetHeight = 22;
373
- const scale = Math.min(1, targetHeight / box.height);
374
- imageSizes[item.name] = {
375
- width: Math.max(1, Math.round(box.width * scale)),
376
- height: Math.max(1, Math.round(box.height * scale)),
377
- };
378
- } else {
379
- imageSizes[item.name] = { width: Math.round(box.width), height: Math.round(box.height) };
380
- }
381
- await handle.dispose();
382
- }
383
- return { content, images, imageSizes };
384
- } finally {
385
- await browser.close();
386
- }
1
+ // 公式(KaTeX) / 图(Mermaid) 转 PNG —— 复用 puppeteer-core + 系统 Chrome/Edge。
2
+ // 扩展宿主是纯 Node(无 DOM),故用无头浏览器把 `$$`/`$` 公式与 ```mermaid 代码块
3
+ // 光栅化为 PNG,并把源 Markdown 重写为 `![...](colamd-xxx-N.png)` 占位图,
4
+ // 与 colamd-extend 渲染进程的做法一致(最终由 docx 的 ImageRun 内嵌)。
5
+ import * as fs from 'fs';
6
+ import * as path from 'path';
7
+ import katex from 'katex';
8
+ import { findChromePath } from './pdf-exporter';
9
+
10
+ export interface RichImageResult {
11
+ /** 重写后的 Markdown(公式/图已替换为图片占位)。 */
12
+ content: string;
13
+ /** 占位图名字 → PNG dataURL。 */
14
+ images: Record<string, string>;
15
+ /** 占位图名字 → 目标尺寸(CSS 像素)。 */
16
+ imageSizes: Record<string, { width: number; height: number }>;
17
+ }
18
+
19
+ interface RenderItem {
20
+ kind: 'math-block' | 'math-inline' | 'mermaid';
21
+ tex: string;
22
+ name: string;
23
+ }
24
+
25
+ function escapeHtml(text: string): string {
26
+ return text
27
+ .replace(/&/g, '&amp;')
28
+ .replace(/</g, '&lt;')
29
+ .replace(/>/g, '&gt;');
30
+ }
31
+
32
+ /** 定位依赖内的静态资源(打包后优先取 out/assets 下的副本,其次回退 node_modules)。 */
33
+ function assetPath(pkg: string, file: string): string | null {
34
+ const candidates: string[] = [];
35
+ // 打包进 vsix 时 node_modules 被 .vscodeignore 排除,故把散件复制到 out/assets/。
36
+ candidates.push(path.resolve(__dirname, 'assets', path.basename(file)));
37
+ try {
38
+ candidates.push(path.resolve(path.dirname(require.resolve(`${pkg}/package.json`)), file));
39
+ } catch {
40
+ /* ignore */
41
+ }
42
+ candidates.push(path.resolve(__dirname, '..', 'node_modules', pkg, file));
43
+ for (const candidate of candidates) {
44
+ if (fs.existsSync(candidate)) return candidate;
45
+ }
46
+ return null;
47
+ }
48
+
49
+ function readIfExists(p: string | null): string | null {
50
+ if (!p) return null;
51
+ try {
52
+ return fs.readFileSync(p, 'utf-8');
53
+ } catch {
54
+ return null;
55
+ }
56
+ }
57
+
58
+ /**
59
+ * 把 katex.min.css 里相对路径的字体 URL 换成 base64 data URI。
60
+ *
61
+ * 公式截图页通过 page.setContent 加载(about:blank 基准),CSS 内联后
62
+ * `url(fonts/KaTeX_*.woff2)` 解析不到任何文件 —— KaTeX 全部退回回退字体,
63
+ * 公式字形错乱(问题表现就是「导出到 Word 时公式没有正确渲染」)。
64
+ * 字体优先取 CSS 同级的 fonts/ 目录,其次 out/assets/katex-fonts/,
65
+ * 最后回退 node_modules 的 katex 发行目录。
66
+ */
67
+ function inlineKatexFonts(css: string, cssPath: string): string {
68
+ const candidates = [
69
+ path.resolve(path.dirname(cssPath), 'fonts'),
70
+ path.resolve(__dirname, 'assets', 'katex-fonts'),
71
+ ];
72
+ try {
73
+ const katexDist = path.dirname(require.resolve('katex/package.json'));
74
+ candidates.push(path.join(katexDist, 'dist', 'fonts'), path.join(katexDist, 'fonts'));
75
+ } catch {
76
+ /* ignore */
77
+ }
78
+ const fontDir = candidates.find((dir) => fs.existsSync(dir));
79
+ if (!fontDir) return css;
80
+
81
+ const cache = new Map<string, string>();
82
+ const load = (file: string): string | null => {
83
+ if (cache.has(file)) return cache.get(file)!;
84
+ let dataUri: string | null = null;
85
+ try {
86
+ const buf = fs.readFileSync(path.join(fontDir, file));
87
+ dataUri = `data:font/woff2;base64,${buf.toString('base64')}`;
88
+ } catch {
89
+ /* ignore */
90
+ }
91
+ cache.set(file, dataUri ?? '');
92
+ return dataUri;
93
+ };
94
+
95
+ return css.replace(/url\(\s*['"]?(fonts\/[^)'"]+)['"]?\s*\)/g, (match, file: string) => {
96
+ const dataUri = load(file);
97
+ return dataUri ? `url(${dataUri})` : match;
98
+ });
99
+ }
100
+
101
+ /** 是否为纯数字/货币式内容(避免把 "$5.99" 之类误判为行内公式)。 */
102
+ function isPlainNumber(s: string): boolean {
103
+ return /^[\d\s.,%\-+()]*$/.test(s);
104
+ }
105
+
106
+ /** sRGB 按权重混合,等价于 `color-mix(in srgb, a w%, b)`。入参出参都不带 `#`。 */
107
+ function mixSrgb(a: string, b: string, weightA: number): string {
108
+ const parse = (hex: string) => [0, 2, 4].map((index) => Number.parseInt(hex.slice(index, index + 2), 16) || 0);
109
+ const [ra, ga, ba] = parse(a);
110
+ const [rb, gb, bb] = parse(b);
111
+ const mix = (x: number, y: number) => Math.max(0, Math.min(255, Math.round(x * weightA + y * (1 - weightA))));
112
+ return [mix(ra, rb), mix(ga, gb), mix(ba, bb)]
113
+ .map((value) => value.toString(16).padStart(2, '0'))
114
+ .join('')
115
+ .toUpperCase();
116
+ }
117
+
118
+ /**
119
+ * Mermaid 画图用的调色板令牌(镜像 colamd-extend diagramPrintPalette 的推导规则)。
120
+ * 令牌与 DocxStyle 同源:「浅色跟随主题、深色整体回落浅色」,混合比例照抄
121
+ * colamd.css 的 `.cm-md-mermaid`(18% / 28% / 45% 三档),两边要一起改。
122
+ *
123
+ * 但代码块的底不一定是纸的颜色:elegant、bear 是浅色主题配深色代码块,它们的
124
+ * codeBlockText 是浅色。Word 是白纸、PNG 也先铺白底,照搬就成了浅色线条落在
125
+ * 白纸上,所以这类主题改按正文色画(2026-11-14,与 colamd-extend 一致)。
126
+ */
127
+ export interface DiagramPalette {
128
+ background: string;
129
+ foreground: string;
130
+ accent: string;
131
+ }
132
+
133
+ /** 没有主题令牌时按浅色默认画(与 docx-exporter 的 DEFAULT_STYLE 同源)。 */
134
+ const DEFAULT_DIAGRAM_PALETTE: DiagramPalette = {
135
+ background: 'F6F8FA',
136
+ foreground: '24292F',
137
+ accent: '0969DA',
138
+ };
139
+
140
+ function normalizeHex(value: unknown, fallback: string): string {
141
+ if (typeof value !== 'string') return fallback;
142
+ const raw = value.trim().replace(/^#/, '');
143
+ if (/^[0-9a-f]{6}$/i.test(raw)) return raw.toUpperCase();
144
+ if (/^[0-9a-f]{3}$/i.test(raw)) return raw.split('').map((digit) => digit + digit).join('').toUpperCase();
145
+ if (/^[0-9a-f]{8}$/i.test(raw)) return raw.slice(0, 6).toUpperCase();
146
+ return fallback;
147
+ }
148
+
149
+ /** 感知亮度,判断代码块底色是深是浅。入参不带 `#`。 */
150
+ function isDarkHex(hex: string): boolean {
151
+ const channel = (index: number): number => (Number.parseInt(hex.slice(index, index + 2), 16) || 0) / 255;
152
+ return 0.2126 * channel(0) + 0.7152 * channel(2) + 0.0722 * channel(4) < 0.5;
153
+ }
154
+
155
+ /** 从主题令牌推导 Mermaid 的 themeVariables(theme: 'base')。 */
156
+ function mermaidThemeVariables(palette: DiagramPalette): Record<string, string> {
157
+ const { background: bg, foreground: fg } = palette;
158
+ const surface = mixSrgb(fg, bg, 0.18);
159
+ const surfaceAlt = mixSrgb(fg, bg, 0.28);
160
+ const border = mixSrgb(fg, bg, 0.45);
161
+ return {
162
+ background: `#${bg}`,
163
+ textColor: `#${fg}`,
164
+ primaryTextColor: `#${fg}`,
165
+ secondaryTextColor: `#${fg}`,
166
+ tertiaryTextColor: `#${fg}`,
167
+ primaryColor: `#${surface}`,
168
+ secondaryColor: `#${surfaceAlt}`,
169
+ tertiaryColor: `#${bg}`,
170
+ mainBkg: `#${surface}`,
171
+ clusterBkg: `#${surface}`,
172
+ clusterBorder: `#${border}`,
173
+ primaryBorderColor: `#${border}`,
174
+ secondaryBorderColor: `#${border}`,
175
+ tertiaryBorderColor: `#${border}`,
176
+ lineColor: `#${fg}`,
177
+ edgeLabelBackground: `#${bg}`,
178
+ noteBkgColor: `#${surfaceAlt}`,
179
+ noteTextColor: `#${fg}`,
180
+ noteBorderColor: `#${border}`,
181
+ actorBkg: `#${surface}`,
182
+ actorBorder: `#${border}`,
183
+ actorTextColor: `#${fg}`,
184
+ actorLineColor: `#${border}`,
185
+ signalColor: `#${fg}`,
186
+ signalTextColor: `#${fg}`,
187
+ labelBoxBkgColor: `#${surface}`,
188
+ labelBoxBorderColor: `#${border}`,
189
+ labelTextColor: `#${fg}`,
190
+ loopTextColor: `#${fg}`,
191
+ activationBkgColor: `#${surfaceAlt}`,
192
+ sequenceNumberColor: `#${bg}`,
193
+ sectionBkgColor: `#${surface}`,
194
+ altSectionBkgColor: `#${bg}`,
195
+ sectionBkgColor2: `#${surfaceAlt}`,
196
+ taskBkgColor: `#${surfaceAlt}`,
197
+ taskBorderColor: `#${border}`,
198
+ taskTextColor: `#${fg}`,
199
+ taskTextOutsideColor: `#${fg}`,
200
+ activeTaskBkgColor: `#${mixSrgb(palette.accent, bg, 0.28)}`,
201
+ activeTaskBorderColor: `#${palette.accent}`,
202
+ doneTaskBkgColor: `#${bg}`,
203
+ doneTaskBorderColor: `#${border}`,
204
+ critBkgColor: `#${mixSrgb(fg, bg, 0.45)}`,
205
+ critBorderColor: `#${fg}`,
206
+ todayLineColor: `#${palette.accent}`,
207
+ pie1: `#${surface}`,
208
+ pie2: `#${surfaceAlt}`,
209
+ pie3: `#${mixSrgb(palette.accent, bg, 0.18)}`,
210
+ pieTitleTextColor: `#${fg}`,
211
+ pieSectionTextColor: `#${fg}`,
212
+ pieStrokeColor: `#${border}`,
213
+ };
214
+ }
215
+
216
+ /** 扫描 Markdown,用占位图重写公式/Mermaid 并收集各自内容。 */
217
+ function scan(markdown: string): { content: string; items: RenderItem[] } {
218
+ const items: RenderItem[] = [];
219
+ let rewritten = markdown;
220
+ let formulaIndex = 0;
221
+ let diagramIndex = 0;
222
+
223
+ // 1) Mermaid 代码块
224
+ rewritten = rewritten.replace(/```mermaid[ \t]*\n([\s\S]*?)\n```/g, (_match, code: string) => {
225
+ diagramIndex += 1;
226
+ const name = `colamd-diagram-${diagramIndex}.png`;
227
+ items.push({ kind: 'mermaid', tex: String(code), name });
228
+ return `![示意图 ${diagramIndex}](${name})`;
229
+ });
230
+
231
+ // 2) 块级公式 $$...$$
232
+ rewritten = rewritten.replace(/\$\$([\s\S]+?)\$\$/g, (_match, tex: string) => {
233
+ formulaIndex += 1;
234
+ const name = `colamd-formula-${formulaIndex}.png`;
235
+ items.push({ kind: 'math-block', tex: String(tex), name });
236
+ return `![公式 ${formulaIndex}](${name})`;
237
+ });
238
+
239
+ // 3) 行内公式 $...$(块级已替换完,仅剩单行非空、非货币)
240
+ rewritten = rewritten.replace(/\$([^$\n]+?)\$/g, (_match, tex: string) => {
241
+ const value = String(tex).trim();
242
+ if (value === '' || isPlainNumber(value)) return _match;
243
+ formulaIndex += 1;
244
+ const name = `colamd-formula-${formulaIndex}.png`;
245
+ items.push({ kind: 'math-inline', tex: value, name });
246
+ return `![公式 ${formulaIndex}](${name})`;
247
+ });
248
+
249
+ return { content: rewritten, items };
250
+ }
251
+
252
+ /**
253
+ * 公式/Mermaid 光栅化。`paletteTokens` 来自主题令牌(DocxStyle 的子集),
254
+ * Mermaid 图配色跟随当前预览主题;不传或令牌不全时按浅色默认画。
255
+ */
256
+ export async function renderMathAndMermaidToImages(
257
+ markdown: string,
258
+ paletteTokens?: { text?: unknown; codeBlockBackground?: unknown; codeBlockText?: unknown; link?: unknown },
259
+ ): Promise<RichImageResult> {
260
+ const bodyText = normalizeHex(paletteTokens?.text, DEFAULT_DIAGRAM_PALETTE.foreground);
261
+ const codeBackground = normalizeHex(paletteTokens?.codeBlockBackground, DEFAULT_DIAGRAM_PALETTE.background);
262
+ const codeText = normalizeHex(paletteTokens?.codeBlockText, bodyText);
263
+ // 浅色主题配深色代码块(elegant / bear)时,codeBlockText 是浅色;Word 的白纸上
264
+ // 会糊成一片。这类主题改按页面正文色画,底色换成白纸。
265
+ const darkCodeBlock = isDarkHex(codeBackground);
266
+ const palette: DiagramPalette = {
267
+ background: darkCodeBlock ? 'FFFFFF' : codeBackground,
268
+ foreground: darkCodeBlock ? bodyText : codeText,
269
+ accent: normalizeHex(paletteTokens?.link, DEFAULT_DIAGRAM_PALETTE.accent),
270
+ };
271
+ const { content, items } = scan(markdown);
272
+ if (items.length === 0) {
273
+ return { content, images: {}, imageSizes: {} };
274
+ }
275
+
276
+ const katexCssPath = assetPath('katex', path.join('dist', 'katex.min.css'));
277
+ const katexCssRaw = readIfExists(katexCssPath);
278
+ // 字体转 base64 内联:page.setContent 的页面解析不到相对字体路径
279
+ const katexCss = katexCssRaw && katexCssPath ? inlineKatexFonts(katexCssRaw, katexCssPath) : null;
280
+ const mermaidJs = readIfExists(assetPath('mermaid', path.join('dist', 'mermaid.min.js')));
281
+ const useMathml = !katexCss;
282
+
283
+ const cards = items.map((item, index) => {
284
+ if (item.kind === 'mermaid') {
285
+ if (!mermaidJs) {
286
+ return `<div class="card" id="card-${index}"><pre>${escapeHtml(item.tex)}</pre></div>`;
287
+ }
288
+ return `<div class="card" id="card-${index}"><pre class="mermaid">${escapeHtml(item.tex)}</pre></div>`;
289
+ }
290
+ const displayMode = item.kind === 'math-block';
291
+ const katexOut = katex.renderToString(item.tex, {
292
+ displayMode,
293
+ throwOnError: false,
294
+ output: useMathml ? 'mathml' : 'html',
295
+ });
296
+ return `<div class="card" id="card-${index}">${katexOut}</div>`;
297
+ }).join('\n');
298
+
299
+ const html = `<!DOCTYPE html>
300
+ <html lang="zh"><head><meta charset="utf-8">
301
+ ${katexCss ? `<style>${katexCss}</style>` : ''}
302
+ <style>
303
+ body { margin: 16px; background: #ffffff; }
304
+ .card { display: inline-block; margin: 8px; vertical-align: middle; }
305
+ .card pre { margin: 0; font-family: monospace; }
306
+ </style>
307
+ </head><body>
308
+ ${cards}
309
+ ${mermaidJs ? `<script>${mermaidJs}</script>` : ''}
310
+ <script>
311
+ (function () {
312
+ if (!window.mermaid) { document.documentElement.dataset.ready = '1'; return; }
313
+ mermaid.initialize({ startOnLoad: false, theme: 'base', themeVariables: ${JSON.stringify(mermaidThemeVariables(palette))}, securityLevel: 'loose' });
314
+ var els = Array.prototype.slice.call(document.querySelectorAll('pre.mermaid'));
315
+ var remaining = els.length;
316
+ if (remaining === 0) { document.documentElement.dataset.ready = '1'; return; }
317
+ els.forEach(function (el, i) {
318
+ mermaid.render('mmd-' + i, el.textContent || '').then(function (result) {
319
+ var tmp = document.createElement('template');
320
+ tmp.innerHTML = result.svg;
321
+ el.parentNode.replaceChild(tmp.content, el);
322
+ }).catch(function () {
323
+ el.outerHTML = '<span style="color:#999">mermaid render error</span>';
324
+ }).finally(function () {
325
+ remaining -= 1;
326
+ if (remaining <= 0) document.documentElement.dataset.ready = '1';
327
+ });
328
+ });
329
+ })();
330
+ </script>
331
+ </body></html>`;
332
+
333
+ const chromePath = findChromePath();
334
+ if (!chromePath) {
335
+ // 无 Chrome/Edge:跳过图片渲染,公式/图回退为文本(占位图仅剩 alt 文本)。
336
+ return { content, images: {}, imageSizes: {} };
337
+ }
338
+
339
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
340
+ const puppeteer = require('puppeteer-core');
341
+ const browser = await puppeteer.launch({ headless: true, executablePath: chromePath });
342
+ try {
343
+ const page = await browser.newPage();
344
+ // 测量用的窗口宽度。太窄的话稍宽的行内公式会在 KaTeX 内部折行,截出来的 PNG
345
+ // 本身就是两行(导出 Word 后看到「公式换行」,镜像 colamd-extend MEASURE_WIDTH)。
346
+ const MEASURE_WIDTH = 2000;
347
+ await page.setViewport({ width: MEASURE_WIDTH, height: 900, deviceScaleFactor: 1 });
348
+ await page.setContent(html, { waitUntil: 'load' });
349
+ // 等待 mermaid 渲染完成(无 mermaid 时页面立即置 ready)
350
+ await page.waitForFunction("document.documentElement.dataset.ready === '1'", { timeout: 15000 })
351
+ .catch(() => { /* 超时也继续:至少能截到已渲染部分 */ });
352
+
353
+ const images: Record<string, string> = {};
354
+ const imageSizes: Record<string, { width: number; height: number }> = {};
355
+
356
+ for (let index = 0; index < items.length; index += 1) {
357
+ const item = items[index];
358
+ const handle = await page.$(`#card-${index}`);
359
+ if (!handle) continue;
360
+ const box = await handle.boundingBox();
361
+ if (!box || box.width < 1 || box.height < 1) continue;
362
+ // puppeteer v25 起截图返回 Uint8Array(TypedArray 的 toString 会输出
363
+ // 「137,80,78,…」逗号十进制串而不是 base64),必须先转 Buffer,
364
+ // 否则 Word 里的图片数据全是坏的 —— 表现为图表/公式没有被正确渲染。
365
+ const raw = (await handle.screenshot({ type: 'png' })) as Buffer | Uint8Array;
366
+ const shot = Buffer.isBuffer(raw) ? raw : Buffer.from(raw as Uint8Array);
367
+ if (!shot || shot.length === 0) continue;
368
+
369
+ images[item.name] = `data:image/png;base64,${shot.toString('base64')}`;
370
+ if (item.kind === 'math-inline') {
371
+ // 行内公式缩放到正文字高(约 22px)
372
+ const targetHeight = 22;
373
+ const scale = Math.min(1, targetHeight / box.height);
374
+ imageSizes[item.name] = {
375
+ width: Math.max(1, Math.round(box.width * scale)),
376
+ height: Math.max(1, Math.round(box.height * scale)),
377
+ };
378
+ } else {
379
+ imageSizes[item.name] = { width: Math.round(box.width), height: Math.round(box.height) };
380
+ }
381
+ await handle.dispose();
382
+ }
383
+ return { content, images, imageSizes };
384
+ } finally {
385
+ await browser.close();
386
+ }
387
387
  }