vscode-colaview 0.0.0-stage → 0.3.2

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 (47) hide show
  1. package/.vscode/launch.json +30 -0
  2. package/.vscode/settings.json +4 -0
  3. package/.vscode/tasks.json +18 -0
  4. package/.vscodeignore +23 -0
  5. package/CHANGELOG.md +141 -0
  6. package/LICENSE +21 -0
  7. package/README.md +278 -2
  8. package/README_CN.md +279 -0
  9. package/RELEASE_NOTES.md +292 -0
  10. package/esbuild.js +112 -0
  11. package/icon.png +0 -0
  12. package/package.json +162 -4
  13. package/patches/@bytechain.cn+colamd+2.7.11.patch +22 -0
  14. package/src/commands/commands.ts +105 -0
  15. package/src/export/css-collector.ts +50 -0
  16. package/src/export/docx-exporter.ts +962 -0
  17. package/src/export/html-exporter.ts +18 -0
  18. package/src/export/pdf-exporter.ts +121 -0
  19. package/src/export/render-export-images.ts +373 -0
  20. package/src/export/theme-style.ts +156 -0
  21. package/src/extension.ts +48 -0
  22. package/src/preview/preview-manager.ts +542 -0
  23. package/src/preview/webview/app.ts +366 -0
  24. package/src/preview/webview/index.html +134 -0
  25. package/src/themes/built-in/bear.css +38 -0
  26. package/src/themes/built-in/dark.css +20 -0
  27. package/src/themes/built-in/dracula.css +38 -0
  28. package/src/themes/built-in/elegant.css +52 -0
  29. package/src/themes/built-in/gruvbox.css +42 -0
  30. package/src/themes/built-in/light.css +20 -0
  31. package/src/themes/built-in/midnight.css +31 -0
  32. package/src/themes/built-in/nord.css +38 -0
  33. package/src/themes/built-in/notion.css +48 -0
  34. package/src/themes/built-in/sepia.css +47 -0
  35. package/src/themes/built-in/solarized-dark.css +35 -0
  36. package/src/themes/built-in/writer.css +44 -0
  37. package/src/themes/theme-manager.ts +180 -0
  38. package/src/types/colamd-renderer.d.ts +47 -0
  39. package/src/types.ts +20 -0
  40. package/test/fixtures/basic.md +34 -0
  41. package/test/fixtures/math.md +20 -0
  42. package/test/fixtures/mermaid.md +19 -0
  43. package/test/runTest.ts +30 -0
  44. package/test/suite/html-exporter.test.ts +20 -0
  45. package/test/suite/markdown-parser.test.ts +8 -0
  46. package/test/suite/theme-manager.test.ts +31 -0
  47. package/tsconfig.json +19 -0
@@ -0,0 +1,18 @@
1
+ // HTML 导出器 — WebView 的 buildExportHTML() 已生成完整独立 HTML,直接保存
2
+ import * as vscode from 'vscode';
3
+
4
+ /**
5
+ * 导出 WebView 渲染的完整 HTML 为独立文件。
6
+ * fullHTML 由 WebView 的 buildExportHTML() 生成,已包含所有 CSS 和主题。
7
+ */
8
+ export async function exportHTML(document: vscode.TextDocument, fullHTML: string): Promise<void> {
9
+ const defaultName = document.fileName.replace(/\.md$/, '.html');
10
+ const uri = await vscode.window.showSaveDialog({
11
+ defaultUri: vscode.Uri.file(defaultName),
12
+ filters: { 'HTML Files': ['html'] },
13
+ });
14
+ if (uri) {
15
+ await vscode.workspace.fs.writeFile(uri, Buffer.from(fullHTML, 'utf-8'));
16
+ vscode.window.showInformationMessage(`Exported to ${uri.fsPath}`);
17
+ }
18
+ }
@@ -0,0 +1,121 @@
1
+ // PDF 导出器 — 使用 puppeteer-core + 系统 Chrome/Edge 渲染
2
+ // fullHTML 由 WebView 的 buildExportHTML() 生成,已包含所有 CSS 和主题
3
+ import * as vscode from 'vscode';
4
+ import * as path from 'path';
5
+ import * as os from 'os';
6
+ import * as fs from 'fs';
7
+
8
+ /**
9
+ * 查找系统中已安装的 Chrome 或 Edge 可执行文件路径
10
+ */
11
+ export function findChromePath(): string | null {
12
+ const platform = process.platform;
13
+ const candidates: string[] = [];
14
+
15
+ if (platform === 'darwin') {
16
+ candidates.push(
17
+ '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
18
+ '/Applications/Chromium.app/Contents/MacOS/Chromium',
19
+ '/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge',
20
+ `${os.homedir()}/Applications/Google Chrome.app/Contents/MacOS/Google Chrome`,
21
+ );
22
+ } else if (platform === 'win32') {
23
+ const progFiles = process.env['PROGRAMFILES'] || 'C:\\Program Files';
24
+ const progFilesX86 = process.env['PROGRAMFILES(X86)'] || 'C:\\Program Files (x86)';
25
+ const localAppData = process.env['LOCALAPPDATA'] || '';
26
+ candidates.push(
27
+ `${progFiles}\\Google\\Chrome\\Application\\chrome.exe`,
28
+ `${progFilesX86}\\Google\\Chrome\\Application\\chrome.exe`,
29
+ `${localAppData}\\Google\\Chrome\\Application\\chrome.exe`,
30
+ `${progFiles}\\Microsoft\\Edge\\Application\\msedge.exe`,
31
+ `${progFilesX86}\\Microsoft\\Edge\\Application\\msedge.exe`,
32
+ );
33
+ } else {
34
+ candidates.push(
35
+ '/usr/bin/google-chrome',
36
+ '/usr/bin/google-chrome-stable',
37
+ '/usr/bin/chromium',
38
+ '/usr/bin/chromium-browser',
39
+ '/snap/bin/chromium',
40
+ );
41
+ }
42
+
43
+ for (const p of candidates) {
44
+ if (fs.existsSync(p)) return p;
45
+ }
46
+ return null;
47
+ }
48
+
49
+ /**
50
+ * 导出完整 HTML 为 A4 PDF。
51
+ * fullHTML 由 WebView 的 buildExportHTML() 生成,已是完整独立文档。
52
+ */
53
+ export async function exportPDF(document: vscode.TextDocument, fullHTML: string): Promise<void> {
54
+ // 在 </head> 前注入打印专用 CSS
55
+ const printCSS = `<style>
56
+ html, body { height: auto !important; overflow: visible !important; -webkit-print-color-adjust: exact !important; print-color-adjust: exact !important; }
57
+ body { max-width: none !important; margin: 0 !important; padding: 20px !important; }
58
+ .mermaid-error, .mermaid-loading { display: none !important; }
59
+ .mermaid-block { page-break-inside: avoid; }
60
+ @page { margin: 15mm; size: A4; }
61
+ </style>`;
62
+ const htmlWithPrint = fullHTML.replace('</head>', printCSS + '\n</head>');
63
+
64
+ const tmpDir = os.tmpdir();
65
+ const tmpHtmlPath = path.join(tmpDir, `colaview-pdf-${Date.now()}.html`);
66
+ fs.writeFileSync(tmpHtmlPath, htmlWithPrint, 'utf-8');
67
+
68
+ const defaultName = document.fileName.replace(/\.md$/, '.pdf');
69
+ const uri = await vscode.window.showSaveDialog({
70
+ defaultUri: vscode.Uri.file(defaultName),
71
+ filters: { 'PDF Files': ['pdf'] },
72
+ });
73
+ if (!uri) {
74
+ try { fs.unlinkSync(tmpHtmlPath); } catch { /* ignore */ }
75
+ return;
76
+ }
77
+
78
+ await vscode.window.withProgress(
79
+ {
80
+ location: vscode.ProgressLocation.Notification,
81
+ title: 'Exporting PDF...',
82
+ cancellable: false,
83
+ },
84
+ async () => {
85
+ try {
86
+ const chromePath = findChromePath();
87
+ if (!chromePath) {
88
+ throw new Error(
89
+ 'Chrome or Edge not found. Please install Google Chrome or Microsoft Edge.'
90
+ );
91
+ }
92
+
93
+ const puppeteer = require('puppeteer-core');
94
+ const browser = await puppeteer.launch({
95
+ headless: true,
96
+ executablePath: chromePath,
97
+ });
98
+ const page = await browser.newPage();
99
+ await page.goto(`file://${tmpHtmlPath}`, { waitUntil: 'networkidle0' });
100
+
101
+ await new Promise(r => setTimeout(r, 500));
102
+
103
+ const pdfBuffer = await page.pdf({
104
+ format: 'A4',
105
+ printBackground: true,
106
+ margin: { top: '15mm', right: '15mm', bottom: '15mm', left: '15mm' },
107
+ });
108
+
109
+ await browser.close();
110
+ await vscode.workspace.fs.writeFile(uri, pdfBuffer);
111
+ vscode.window.showInformationMessage(`Exported to ${uri.fsPath}`);
112
+ } catch (e) {
113
+ vscode.window.showErrorMessage(
114
+ `PDF export failed: ${e instanceof Error ? e.message : String(e)}`
115
+ );
116
+ } finally {
117
+ try { fs.unlinkSync(tmpHtmlPath); } catch { /* ignore */ }
118
+ }
119
+ }
120
+ );
121
+ }
@@ -0,0 +1,373 @@
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
+ export interface DiagramPalette {
124
+ background: string;
125
+ foreground: string;
126
+ accent: string;
127
+ }
128
+
129
+ /** 没有主题令牌时按浅色默认画(与 docx-exporter 的 DEFAULT_STYLE 同源)。 */
130
+ const DEFAULT_DIAGRAM_PALETTE: DiagramPalette = {
131
+ background: 'F6F8FA',
132
+ foreground: '24292F',
133
+ accent: '0969DA',
134
+ };
135
+
136
+ function normalizeHex(value: unknown, fallback: string): string {
137
+ if (typeof value !== 'string') return fallback;
138
+ const raw = value.trim().replace(/^#/, '');
139
+ if (/^[0-9a-f]{6}$/i.test(raw)) return raw.toUpperCase();
140
+ if (/^[0-9a-f]{3}$/i.test(raw)) return raw.split('').map((digit) => digit + digit).join('').toUpperCase();
141
+ if (/^[0-9a-f]{8}$/i.test(raw)) return raw.slice(0, 6).toUpperCase();
142
+ return fallback;
143
+ }
144
+
145
+ /** 从主题令牌推导 Mermaid 的 themeVariables(theme: 'base')。 */
146
+ function mermaidThemeVariables(palette: DiagramPalette): Record<string, string> {
147
+ const { background: bg, foreground: fg } = palette;
148
+ const surface = mixSrgb(fg, bg, 0.18);
149
+ const surfaceAlt = mixSrgb(fg, bg, 0.28);
150
+ const border = mixSrgb(fg, bg, 0.45);
151
+ return {
152
+ background: `#${bg}`,
153
+ textColor: `#${fg}`,
154
+ primaryTextColor: `#${fg}`,
155
+ secondaryTextColor: `#${fg}`,
156
+ tertiaryTextColor: `#${fg}`,
157
+ primaryColor: `#${surface}`,
158
+ secondaryColor: `#${surfaceAlt}`,
159
+ tertiaryColor: `#${bg}`,
160
+ mainBkg: `#${surface}`,
161
+ clusterBkg: `#${surface}`,
162
+ clusterBorder: `#${border}`,
163
+ primaryBorderColor: `#${border}`,
164
+ secondaryBorderColor: `#${border}`,
165
+ tertiaryBorderColor: `#${border}`,
166
+ lineColor: `#${fg}`,
167
+ edgeLabelBackground: `#${bg}`,
168
+ noteBkgColor: `#${surfaceAlt}`,
169
+ noteTextColor: `#${fg}`,
170
+ noteBorderColor: `#${border}`,
171
+ actorBkg: `#${surface}`,
172
+ actorBorder: `#${border}`,
173
+ actorTextColor: `#${fg}`,
174
+ actorLineColor: `#${border}`,
175
+ signalColor: `#${fg}`,
176
+ signalTextColor: `#${fg}`,
177
+ labelBoxBkgColor: `#${surface}`,
178
+ labelBoxBorderColor: `#${border}`,
179
+ labelTextColor: `#${fg}`,
180
+ loopTextColor: `#${fg}`,
181
+ activationBkgColor: `#${surfaceAlt}`,
182
+ sequenceNumberColor: `#${bg}`,
183
+ sectionBkgColor: `#${surface}`,
184
+ altSectionBkgColor: `#${bg}`,
185
+ sectionBkgColor2: `#${surfaceAlt}`,
186
+ taskBkgColor: `#${surfaceAlt}`,
187
+ taskBorderColor: `#${border}`,
188
+ taskTextColor: `#${fg}`,
189
+ taskTextOutsideColor: `#${fg}`,
190
+ activeTaskBkgColor: `#${mixSrgb(palette.accent, bg, 0.28)}`,
191
+ activeTaskBorderColor: `#${palette.accent}`,
192
+ doneTaskBkgColor: `#${bg}`,
193
+ doneTaskBorderColor: `#${border}`,
194
+ critBkgColor: `#${mixSrgb(fg, bg, 0.45)}`,
195
+ critBorderColor: `#${fg}`,
196
+ todayLineColor: `#${palette.accent}`,
197
+ pie1: `#${surface}`,
198
+ pie2: `#${surfaceAlt}`,
199
+ pie3: `#${mixSrgb(palette.accent, bg, 0.18)}`,
200
+ pieTitleTextColor: `#${fg}`,
201
+ pieSectionTextColor: `#${fg}`,
202
+ pieStrokeColor: `#${border}`,
203
+ };
204
+ }
205
+
206
+ /** 扫描 Markdown,用占位图重写公式/Mermaid 并收集各自内容。 */
207
+ function scan(markdown: string): { content: string; items: RenderItem[] } {
208
+ const items: RenderItem[] = [];
209
+ let rewritten = markdown;
210
+ let formulaIndex = 0;
211
+ let diagramIndex = 0;
212
+
213
+ // 1) Mermaid 代码块
214
+ rewritten = rewritten.replace(/```mermaid[ \t]*\n([\s\S]*?)\n```/g, (_match, code: string) => {
215
+ diagramIndex += 1;
216
+ const name = `colamd-diagram-${diagramIndex}.png`;
217
+ items.push({ kind: 'mermaid', tex: String(code), name });
218
+ return `![示意图 ${diagramIndex}](${name})`;
219
+ });
220
+
221
+ // 2) 块级公式 $$...$$
222
+ rewritten = rewritten.replace(/\$\$([\s\S]+?)\$\$/g, (_match, tex: string) => {
223
+ formulaIndex += 1;
224
+ const name = `colamd-formula-${formulaIndex}.png`;
225
+ items.push({ kind: 'math-block', tex: String(tex), name });
226
+ return `![公式 ${formulaIndex}](${name})`;
227
+ });
228
+
229
+ // 3) 行内公式 $...$(块级已替换完,仅剩单行非空、非货币)
230
+ rewritten = rewritten.replace(/\$([^$\n]+?)\$/g, (_match, tex: string) => {
231
+ const value = String(tex).trim();
232
+ if (value === '' || isPlainNumber(value)) return _match;
233
+ formulaIndex += 1;
234
+ const name = `colamd-formula-${formulaIndex}.png`;
235
+ items.push({ kind: 'math-inline', tex: value, name });
236
+ return `![公式 ${formulaIndex}](${name})`;
237
+ });
238
+
239
+ return { content: rewritten, items };
240
+ }
241
+
242
+ /**
243
+ * 公式/Mermaid 光栅化。`paletteTokens` 来自主题令牌(DocxStyle 的子集),
244
+ * Mermaid 图配色跟随当前预览主题;不传或令牌不全时按浅色默认画。
245
+ */
246
+ export async function renderMathAndMermaidToImages(
247
+ markdown: string,
248
+ paletteTokens?: { codeBlockBackground?: unknown; codeBlockText?: unknown; link?: unknown },
249
+ ): Promise<RichImageResult> {
250
+ const palette: DiagramPalette = paletteTokens
251
+ ? {
252
+ background: normalizeHex(paletteTokens.codeBlockBackground, DEFAULT_DIAGRAM_PALETTE.background),
253
+ foreground: normalizeHex(paletteTokens.codeBlockText, DEFAULT_DIAGRAM_PALETTE.foreground),
254
+ accent: normalizeHex(paletteTokens.link, DEFAULT_DIAGRAM_PALETTE.accent),
255
+ }
256
+ : DEFAULT_DIAGRAM_PALETTE;
257
+ const { content, items } = scan(markdown);
258
+ if (items.length === 0) {
259
+ return { content, images: {}, imageSizes: {} };
260
+ }
261
+
262
+ const katexCssPath = assetPath('katex', path.join('dist', 'katex.min.css'));
263
+ const katexCssRaw = readIfExists(katexCssPath);
264
+ // 字体转 base64 内联:page.setContent 的页面解析不到相对字体路径
265
+ const katexCss = katexCssRaw && katexCssPath ? inlineKatexFonts(katexCssRaw, katexCssPath) : null;
266
+ const mermaidJs = readIfExists(assetPath('mermaid', path.join('dist', 'mermaid.min.js')));
267
+ const useMathml = !katexCss;
268
+
269
+ const cards = items.map((item, index) => {
270
+ if (item.kind === 'mermaid') {
271
+ if (!mermaidJs) {
272
+ return `<div class="card" id="card-${index}"><pre>${escapeHtml(item.tex)}</pre></div>`;
273
+ }
274
+ return `<div class="card" id="card-${index}"><pre class="mermaid">${escapeHtml(item.tex)}</pre></div>`;
275
+ }
276
+ const displayMode = item.kind === 'math-block';
277
+ const katexOut = katex.renderToString(item.tex, {
278
+ displayMode,
279
+ throwOnError: false,
280
+ output: useMathml ? 'mathml' : 'html',
281
+ });
282
+ return `<div class="card" id="card-${index}">${katexOut}</div>`;
283
+ }).join('\n');
284
+
285
+ const html = `<!DOCTYPE html>
286
+ <html lang="zh"><head><meta charset="utf-8">
287
+ ${katexCss ? `<style>${katexCss}</style>` : ''}
288
+ <style>
289
+ body { margin: 16px; background: #ffffff; }
290
+ .card { display: inline-block; margin: 8px; vertical-align: middle; }
291
+ .card pre { margin: 0; font-family: monospace; }
292
+ </style>
293
+ </head><body>
294
+ ${cards}
295
+ ${mermaidJs ? `<script>${mermaidJs}</script>` : ''}
296
+ <script>
297
+ (function () {
298
+ if (!window.mermaid) { document.documentElement.dataset.ready = '1'; return; }
299
+ mermaid.initialize({ startOnLoad: false, theme: 'base', themeVariables: ${JSON.stringify(mermaidThemeVariables(palette))}, securityLevel: 'loose' });
300
+ var els = Array.prototype.slice.call(document.querySelectorAll('pre.mermaid'));
301
+ var remaining = els.length;
302
+ if (remaining === 0) { document.documentElement.dataset.ready = '1'; return; }
303
+ els.forEach(function (el, i) {
304
+ mermaid.render('mmd-' + i, el.textContent || '').then(function (result) {
305
+ var tmp = document.createElement('template');
306
+ tmp.innerHTML = result.svg;
307
+ el.parentNode.replaceChild(tmp.content, el);
308
+ }).catch(function () {
309
+ el.outerHTML = '<span style="color:#999">mermaid render error</span>';
310
+ }).finally(function () {
311
+ remaining -= 1;
312
+ if (remaining <= 0) document.documentElement.dataset.ready = '1';
313
+ });
314
+ });
315
+ })();
316
+ </script>
317
+ </body></html>`;
318
+
319
+ const chromePath = findChromePath();
320
+ if (!chromePath) {
321
+ // 无 Chrome/Edge:跳过图片渲染,公式/图回退为文本(占位图仅剩 alt 文本)。
322
+ return { content, images: {}, imageSizes: {} };
323
+ }
324
+
325
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
326
+ const puppeteer = require('puppeteer-core');
327
+ const browser = await puppeteer.launch({ headless: true, executablePath: chromePath });
328
+ try {
329
+ const page = await browser.newPage();
330
+ // 测量用的窗口宽度。太窄的话稍宽的行内公式会在 KaTeX 内部折行,截出来的 PNG
331
+ // 本身就是两行(导出 Word 后看到「公式换行」,镜像 colamd-extend MEASURE_WIDTH)。
332
+ const MEASURE_WIDTH = 2000;
333
+ await page.setViewport({ width: MEASURE_WIDTH, height: 900, deviceScaleFactor: 1 });
334
+ await page.setContent(html, { waitUntil: 'load' });
335
+ // 等待 mermaid 渲染完成(无 mermaid 时页面立即置 ready)
336
+ await page.waitForFunction("document.documentElement.dataset.ready === '1'", { timeout: 15000 })
337
+ .catch(() => { /* 超时也继续:至少能截到已渲染部分 */ });
338
+
339
+ const images: Record<string, string> = {};
340
+ const imageSizes: Record<string, { width: number; height: number }> = {};
341
+
342
+ for (let index = 0; index < items.length; index += 1) {
343
+ const item = items[index];
344
+ const handle = await page.$(`#card-${index}`);
345
+ if (!handle) continue;
346
+ const box = await handle.boundingBox();
347
+ if (!box || box.width < 1 || box.height < 1) continue;
348
+ // puppeteer v25 起截图返回 Uint8Array(TypedArray 的 toString 会输出
349
+ // 「137,80,78,…」逗号十进制串而不是 base64),必须先转 Buffer,
350
+ // 否则 Word 里的图片数据全是坏的 —— 表现为图表/公式没有被正确渲染。
351
+ const raw = (await handle.screenshot({ type: 'png' })) as Buffer | Uint8Array;
352
+ const shot = Buffer.isBuffer(raw) ? raw : Buffer.from(raw as Uint8Array);
353
+ if (!shot || shot.length === 0) continue;
354
+
355
+ images[item.name] = `data:image/png;base64,${shot.toString('base64')}`;
356
+ if (item.kind === 'math-inline') {
357
+ // 行内公式缩放到正文字高(约 22px)
358
+ const targetHeight = 22;
359
+ const scale = Math.min(1, targetHeight / box.height);
360
+ imageSizes[item.name] = {
361
+ width: Math.max(1, Math.round(box.width * scale)),
362
+ height: Math.max(1, Math.round(box.height * scale)),
363
+ };
364
+ } else {
365
+ imageSizes[item.name] = { width: Math.round(box.width), height: Math.round(box.height) };
366
+ }
367
+ await handle.dispose();
368
+ }
369
+ return { content, images, imageSizes };
370
+ } finally {
371
+ await browser.close();
372
+ }
373
+ }
@@ -0,0 +1,156 @@
1
+ // 从「预览所用主题 CSS」中抽取令牌,并把它翻译成导出文档可用的语义样式。
2
+ //
3
+ // 背景:预览里主题的排版/强调色通过 `#editor .cm-content .cm-md-*` 选择器生效;
4
+ // 而 buildExportHTML 会把内容序列化成 `<article class="colamd-document">` 语义 HTML
5
+ // (<h1>/<strong>/<em>/<code>/<table>/<blockquote>…),并只把 `:root` 变量带过去。
6
+ // 结果:颜色令牌能跟过去,但主题的字体、加粗/行内代码强调色、表格表头下划线等丢光。
7
+ // 这里把主题 CSS 的编辑器选择器改写成语义选择器,再注入导出 HTML / Word 样式。
8
+
9
+ /** .cm-md-* 装饰类 → 导出文档里的语义标签映射(顺序敏感,长的先)。 */
10
+ const CLASS_TO_TAG: Array<[RegExp, string]> = [
11
+ [/\.cm-md-atxheading([1-6])\b/g, 'h$1'],
12
+ [/\.cm-md-strong\b/g, 'strong'],
13
+ [/\.cm-md-em\b/g, 'em'],
14
+ [/\.cm-md-strike\b/g, 's'],
15
+ [/\.cm-md-inlinecode\b/g, 'code'],
16
+ [/\.cm-md-highlight\b/g, 'mark'],
17
+ [/\.cm-md-link\b/g, 'a'],
18
+ [/\.cm-md-url\b/g, 'a'],
19
+ [/\.cm-md-blockquote\b/g, 'blockquote'],
20
+ [/\.cm-md-codeblock(?:-first|-last)?\b/g, 'pre'],
21
+ [/\.cm-md-codeinfo\b/g, 'pre'],
22
+ [/\.cm-md-table-widget\b/g, 'table'],
23
+ [/\.cm-md-table\b/g, 'table'],
24
+ [/\.cm-md-hr\b/g, 'hr'],
25
+ [/\.cm-md-task-checked\b/g, 'li'],
26
+ [/\.cm-md-task\b/g, 'li'],
27
+ [/\.cm-md-li-[0-6]\b/g, 'li'],
28
+ [/\.cm-md-footnote-ref\b/g, 'sup'],
29
+ [/\.cm-md-footnote-def\b/g, 'section'],
30
+ [/\.cm-md-image\b/g, 'img'],
31
+ ];
32
+
33
+ interface ThemeTokens {
34
+ vars: Record<string, string>;
35
+ fontFamily: string;
36
+ lineHeight: number | null;
37
+ }
38
+
39
+ /** 解析主题 CSS 里的 `:root {}` 变量与 `.cm-content` 上的字体/行高。 */
40
+ function parseThemeTokens(themeCss: string): ThemeTokens {
41
+ const vars: Record<string, string> = {};
42
+ const rootMatch = /:root\s*\{([^}]*)\}/s.exec(themeCss);
43
+ if (rootMatch) {
44
+ const declRe = /(--[a-zA-Z0-9-]+)\s*:\s*([^;]+)/g;
45
+ let m: RegExpExecArray | null;
46
+ while ((m = declRe.exec(rootMatch[1]))) {
47
+ vars[m[1]] = m[2].trim();
48
+ }
49
+ }
50
+
51
+ // 遍历所有 `.cm-content { … }` 块:字体/行高可能不在第一个块里,
52
+ // 优先取含 font-family 的那个(如 writer 主题的整站等宽字体)。
53
+ let fontFamily = '';
54
+ let lineHeight: number | null = null;
55
+ const blockRe = /([^{}]*\.cm-content\b[^{}]*)\{([^}]*)\}/gs;
56
+ let firstBlock: string | null = null;
57
+ let m: RegExpExecArray | null;
58
+ while ((m = blockRe.exec(themeCss))) {
59
+ const body = m[2];
60
+ if (firstBlock === null) firstBlock = body;
61
+ const fontMatch = /font-family\s*:\s*([^;]+)/i.exec(body);
62
+ if (fontMatch) {
63
+ fontFamily = fontMatch[1].trim();
64
+ const lineMatch = /line-height\s*:\s*([0-9.]+)/i.exec(body);
65
+ if (lineMatch) lineHeight = parseFloat(lineMatch[1]);
66
+ break;
67
+ }
68
+ }
69
+ if (fontFamily === '' && firstBlock !== null) {
70
+ const lineMatch = /line-height\s*:\s*([0-9.]+)/i.exec(firstBlock);
71
+ if (lineMatch) lineHeight = parseFloat(lineMatch[1]);
72
+ }
73
+
74
+ return { vars, fontFamily, lineHeight };
75
+ }
76
+
77
+ /**
78
+ * 把主题 CSS 中针对编辑器 DOM 的规则翻译成导出文档(`.colamd-document` 语义结构)能命中的规则。
79
+ * 返回纯 CSS 文本(不含 <style> 包裹),供注入导出 HTML。
80
+ */
81
+ export function translateThemeCssForExport(themeCss: string): string {
82
+ if (!themeCss) return '';
83
+
84
+ // 保留 :root 变量块:导出 HTML 里的 :root 是渲染端收集的「运行时变量」,
85
+ // 当 webview body 缺主题类时会退回 colamd 的浅色默认值。注入的样式排在
86
+ // 最后,同特异性下后者胜,能让主题变量稳定覆盖默认值(自定义主题的唯一变量来源)。
87
+ let css = themeCss;
88
+
89
+ // 导出的 <body> 即原编辑器 #editor 容器。
90
+ css = css.replace(/#editor\b/g, 'body');
91
+
92
+ // 编辑器内容容器 → 导出文档容器。
93
+ css = css.replace(/\.cm-content\b/g, '.colamd-document');
94
+
95
+ // 编辑器装饰类 → 语义标签。
96
+ for (const [re, tag] of CLASS_TO_TAG) {
97
+ css = css.replace(re, tag);
98
+ }
99
+
100
+ return css.trim();
101
+ }
102
+
103
+ /**
104
+ * 从 colamd.css(引擎内置样式)里提取主题作用域的正文规则并翻译成导出可用的语义选择器。
105
+ *
106
+ * 背景:各主题的正文差异化规则(加粗/行内代码/标题配色、表格表头、引用块等)以
107
+ * `body.theme-x .cm-content .cm-md-*` 形式写在引擎的 colamd.css 里,导出 HTML 虽然原样
108
+ * 内联了 colamd.css,但导出文档是语义化结构(.colamd-document strong 等),这些规则
109
+ * 全部无法命中 —— 表现为导出的加粗、行内代码等颜色与预览/ColaMD-extend 不一致。
110
+ * 这里按主题抽出这些规则,套用与 translateThemeCssForExport 相同的映射翻译后返回。
111
+ */
112
+ export function translateEngineThemeCssForExport(colamdCss: string): string {
113
+ if (!colamdCss) return '';
114
+
115
+ // 抽出所有 body.theme-* 作用域、且作用于编辑器内容层的规则块
116
+ const ruleRe = /body\.theme-[a-z0-9-]+[^{}]*\.cm-content[^{}]*\{[^}]*\}/g;
117
+ const rules = colamdCss.match(ruleRe);
118
+ if (!rules || rules.length === 0) return '';
119
+
120
+ const out = rules.join('\n');
121
+ return translateThemeCssForExport(out);
122
+ }
123
+
124
+ /**
125
+ * 从主题 CSS 构造 Word 导出用的样式令牌(docx 的 DocxStyle)。只覆盖能可靠取到的字段,
126
+ * 其余由 markdownToDocx 的 normalizeStyle 回退到默认浅色样式。颜色返回原始值(hex),
127
+ * 由 docx-exporter 的 hexColor 归一化。
128
+ */
129
+ export function buildDocxStyleFromThemeCss(themeCss: string): Record<string, string | number | null> {
130
+ const { vars, fontFamily, lineHeight } = parseThemeTokens(themeCss);
131
+
132
+ const style: Record<string, string | number | null> = {};
133
+ const put = (key: string, varName: string) => {
134
+ if (vars[varName]) style[key] = vars[varName];
135
+ };
136
+
137
+ put('text', '--text-color');
138
+ put('secondaryText', '--text-secondary');
139
+ put('link', '--link-color');
140
+ put('inlineCodeBackground', '--code-bg');
141
+ put('codeBlockBackground', '--code-block-bg');
142
+ put('codeBlockText', '--code-block-text');
143
+ put('highlightBackground', '--highlight-bg');
144
+ put('blockquoteBorder', '--blockquote-border');
145
+ put('blockquoteBackground', '--blockquote-bg');
146
+ put('border', '--border-color');
147
+ put('tableHeaderBackground', '--table-header-bg');
148
+
149
+ // 主题若显式定义了等宽字体栈(如自定义 .themes 主题),一并带上
150
+ if (vars['--font-mono']) style.monoFontStack = vars['--font-mono'];
151
+
152
+ if (fontFamily) style.bodyFontStack = fontFamily;
153
+ if (lineHeight !== null && Number.isFinite(lineHeight)) style.lineHeight = lineHeight;
154
+
155
+ return style;
156
+ }