vscode-colaview 0.3.0 → 0.3.3

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.
@@ -55,11 +55,164 @@ function readIfExists(p: string | null): string | null {
55
55
  }
56
56
  }
57
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
+
58
101
  /** 是否为纯数字/货币式内容(避免把 "$5.99" 之类误判为行内公式)。 */
59
102
  function isPlainNumber(s: string): boolean {
60
103
  return /^[\d\s.,%\-+()]*$/.test(s);
61
104
  }
62
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
+
63
216
  /** 扫描 Markdown,用占位图重写公式/Mermaid 并收集各自内容。 */
64
217
  function scan(markdown: string): { content: string; items: RenderItem[] } {
65
218
  const items: RenderItem[] = [];
@@ -96,13 +249,34 @@ function scan(markdown: string): { content: string; items: RenderItem[] } {
96
249
  return { content: rewritten, items };
97
250
  }
98
251
 
99
- export async function renderMathAndMermaidToImages(markdown: string): Promise<RichImageResult> {
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
+ };
100
271
  const { content, items } = scan(markdown);
101
272
  if (items.length === 0) {
102
273
  return { content, images: {}, imageSizes: {} };
103
274
  }
104
275
 
105
- const katexCss = readIfExists(assetPath('katex', path.join('dist', 'katex.min.css')));
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;
106
280
  const mermaidJs = readIfExists(assetPath('mermaid', path.join('dist', 'mermaid.min.js')));
107
281
  const useMathml = !katexCss;
108
282
 
@@ -136,7 +310,7 @@ ${mermaidJs ? `<script>${mermaidJs}</script>` : ''}
136
310
  <script>
137
311
  (function () {
138
312
  if (!window.mermaid) { document.documentElement.dataset.ready = '1'; return; }
139
- mermaid.initialize({ startOnLoad: false, theme: 'neutral', securityLevel: 'loose' });
313
+ mermaid.initialize({ startOnLoad: false, theme: 'base', themeVariables: ${JSON.stringify(mermaidThemeVariables(palette))}, securityLevel: 'loose' });
140
314
  var els = Array.prototype.slice.call(document.querySelectorAll('pre.mermaid'));
141
315
  var remaining = els.length;
142
316
  if (remaining === 0) { document.documentElement.dataset.ready = '1'; return; }
@@ -167,7 +341,10 @@ ${mermaidJs ? `<script>${mermaidJs}</script>` : ''}
167
341
  const browser = await puppeteer.launch({ headless: true, executablePath: chromePath });
168
342
  try {
169
343
  const page = await browser.newPage();
170
- await page.setViewport({ width: 1200, height: 900, deviceScaleFactor: 1 });
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 });
171
348
  await page.setContent(html, { waitUntil: 'load' });
172
349
  // 等待 mermaid 渲染完成(无 mermaid 时页面立即置 ready)
173
350
  await page.waitForFunction("document.documentElement.dataset.ready === '1'", { timeout: 15000 })
@@ -182,7 +359,11 @@ ${mermaidJs ? `<script>${mermaidJs}</script>` : ''}
182
359
  if (!handle) continue;
183
360
  const box = await handle.boundingBox();
184
361
  if (!box || box.width < 1 || box.height < 1) continue;
185
- const shot = (await handle.screenshot({ type: 'png' })) as Buffer;
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);
186
367
  if (!shot || shot.length === 0) continue;
187
368
 
188
369
  images[item.name] = `data:image/png;base64,${shot.toString('base64')}`;
@@ -100,30 +100,91 @@ export function translateThemeCssForExport(themeCss: string): string {
100
100
  return css.trim();
101
101
  }
102
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
+ * 深色主题导出 Word 时回落的浅色板,字段与 docx-exporter 的 DEFAULT_STYLE 一致。
126
+ * Word 是白纸,深色主题的浅色正文直接搬过去会看不见(镜像 colamd-extend
127
+ * docx-style.ts 的 LIGHT 常量:浅色跟随主题、深色整体回落浅色)。
128
+ */
129
+ const LIGHT_TOKENS: Record<string, string> = {
130
+ text: '24292F',
131
+ secondaryText: '656D76',
132
+ link: '0969DA',
133
+ inlineCodeBackground: 'EFF1F3',
134
+ codeBlockBackground: 'F6F8FA',
135
+ codeBlockText: '24292F',
136
+ highlightBackground: 'FFF3BF',
137
+ blockquoteBorder: 'D0D7DE',
138
+ border: 'D0D7DE',
139
+ tableHeaderBackground: 'F6F8FA',
140
+ };
141
+
142
+ /** 取 #rgb / #rrggbb / #rrggbbaa 的主色,取不到返回 null。入参可带 `#`。 */
143
+ function themeHex(value: string | undefined): string | null {
144
+ if (!value) return null;
145
+ const raw = value.trim().replace(/^#/, '');
146
+ if (/^[0-9a-f]{6}$/i.test(raw)) return raw.toUpperCase();
147
+ if (/^[0-9a-f]{3}$/i.test(raw)) return raw.split('').map((digit) => digit + digit).join('').toUpperCase();
148
+ if (/^[0-9a-f]{8}$/i.test(raw)) return raw.slice(0, 6).toUpperCase();
149
+ return null;
150
+ }
151
+
152
+ /** 感知亮度,用来判断主题底色是深是浅。入参不带 `#`。 */
153
+ function hexLuminance(hex: string): number {
154
+ const channel = (index: number): number => (Number.parseInt(hex.slice(index, index + 2), 16) || 0) / 255;
155
+ return 0.2126 * channel(0) + 0.7152 * channel(2) + 0.0722 * channel(4);
156
+ }
157
+
103
158
  /**
104
159
  * 从主题 CSS 构造 Word 导出用的样式令牌(docx 的 DocxStyle)。只覆盖能可靠取到的字段,
105
160
  * 其余由 markdownToDocx 的 normalizeStyle 回退到默认浅色样式。颜色返回原始值(hex),
106
161
  * 由 docx-exporter 的 hexColor 归一化。
162
+ *
163
+ * 深色主题(--bg-color 亮度 < 0.5)整体回落浅色板,与 Mermaid 导出挑浅色配色是同一条规则。
107
164
  */
108
165
  export function buildDocxStyleFromThemeCss(themeCss: string): Record<string, string | number | null> {
109
166
  const { vars, fontFamily, lineHeight } = parseThemeTokens(themeCss);
110
167
 
111
- const style: Record<string, string | number | null> = {};
112
- const put = (key: string, varName: string) => {
113
- if (vars[varName]) style[key] = vars[varName];
114
- };
115
-
116
- put('text', '--text-color');
117
- put('secondaryText', '--text-secondary');
118
- put('link', '--link-color');
119
- put('inlineCodeBackground', '--code-bg');
120
- put('codeBlockBackground', '--code-block-bg');
121
- put('codeBlockText', '--code-block-text');
122
- put('highlightBackground', '--highlight-bg');
123
- put('blockquoteBorder', '--blockquote-border');
124
- put('blockquoteBackground', '--blockquote-bg');
125
- put('border', '--border-color');
126
- put('tableHeaderBackground', '--table-header-bg');
168
+ const bg = themeHex(vars['--bg-color']);
169
+ const isDarkTheme = bg !== null && hexLuminance(bg) < 0.5;
170
+ const style: Record<string, string | number | null> = isDarkTheme ? { ...LIGHT_TOKENS } : {};
171
+ if (!isDarkTheme) {
172
+ const put = (key: string, varName: string) => {
173
+ if (vars[varName]) style[key] = vars[varName];
174
+ };
175
+
176
+ put('text', '--text-color');
177
+ put('secondaryText', '--text-secondary');
178
+ put('link', '--link-color');
179
+ put('inlineCodeBackground', '--code-bg');
180
+ put('codeBlockBackground', '--code-block-bg');
181
+ put('codeBlockText', '--code-block-text');
182
+ put('highlightBackground', '--highlight-bg');
183
+ put('blockquoteBorder', '--blockquote-border');
184
+ put('blockquoteBackground', '--blockquote-bg');
185
+ put('border', '--border-color');
186
+ put('tableHeaderBackground', '--table-header-bg');
187
+ }
127
188
 
128
189
  // 主题若显式定义了等宽字体栈(如自定义 .themes 主题),一并带上
129
190
  if (vars['--font-mono']) style.monoFontStack = vars['--font-mono'];
package/src/extension.ts CHANGED
@@ -42,17 +42,6 @@ export function activate(context: vscode.ExtensionContext) {
42
42
  }
43
43
  }
44
44
 
45
- vscode.workspace.onDidChangeConfiguration(e => {
46
- if (!previewManager) return;
47
- const cfg = vscode.workspace.getConfiguration('colaview');
48
- if (e.affectsConfiguration('colaview.plugins.math')) {
49
- previewManager.togglePlugin('math', cfg.get('plugins.math', true));
50
- }
51
- if (e.affectsConfiguration('colaview.plugins.mermaid')) {
52
- previewManager.togglePlugin('mermaid', cfg.get('plugins.mermaid', true));
53
- }
54
- });
55
-
56
45
  console.log('ColaView: activated');
57
46
  }
58
47
 
@@ -6,7 +6,7 @@ import { ThemeManager } from '../themes/theme-manager';
6
6
  import { exportHTML } from '../export/html-exporter';
7
7
  import { exportPDF } from '../export/pdf-exporter';
8
8
  import { exportWord } from '../export/docx-exporter';
9
- import { translateThemeCssForExport } from '../export/theme-style';
9
+ import { translateThemeCssForExport, translateEngineThemeCssForExport } from '../export/theme-style';
10
10
 
11
11
  function getNonce(): string {
12
12
  const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
@@ -44,7 +44,6 @@ export class PreviewManager {
44
44
  constructor(private context: vscode.ExtensionContext) {
45
45
  this.registerActiveEditorListener();
46
46
  this.registerScrollSyncListeners();
47
- this.registerConfigurationListener();
48
47
  }
49
48
 
50
49
  private registerActiveEditorListener(): void {
@@ -135,18 +134,6 @@ export class PreviewManager {
135
134
  }
136
135
  }
137
136
 
138
- private registerConfigurationListener(): void {
139
- try {
140
- vscode.workspace.onDidChangeConfiguration((event) => {
141
- if (event.affectsConfiguration('colaview.scrollSync')) {
142
- // config changed, no action needed — will be checked on next scroll event
143
- }
144
- }, null, this.disposables);
145
- } catch (e) {
146
- console.error('[ColaView] registerConfigurationListener failed:', e);
147
- }
148
- }
149
-
150
137
  private isScrollSyncEnabled(): boolean {
151
138
  try {
152
139
  return vscode.workspace.getConfiguration('colaview').get<boolean>('scrollSync', false);
@@ -402,10 +389,71 @@ export class PreviewManager {
402
389
 
403
390
  // 自定义主题的规则不在 colamd.css 里(内置主题的翻译规则是冗余兜底),
404
391
  // 翻译成语义选择器后注入到 </head> 前,保证优先级最高。
405
- const themeOverrideCss = translateThemeCssForExport(ThemeManager.loadThemeCSS(theme));
392
+ // 变量同样要提到 body.theme-X:引擎把内置主题变量写在 body.theme-X(0,1,1)
393
+ // 上,裸 :root(0,1,0)压不住它,导出会退回引擎旧值、和预览对不上。
394
+ const rawThemeCss = translateThemeCssForExport(ThemeManager.loadThemeCSS(theme));
395
+ const themeOverrideCss = rawThemeCss.replace(/:root\b/g, `:root, body.${themeClass}`);
406
396
  const THEME_FIX = themeOverrideCss ? `<style>${themeOverrideCss}</style>` : '';
397
+ // colamd.css 里还有一批 body.theme-X .cm-content .cm-md-* 的正文差异化规则
398
+ // (sepia/dark/notion/midnight/writer 等主题的加粗、行内代码、标题配色只存在于
399
+ // 这一层),导出文档的语义化结构无法命中原选择器 —— 抽取并翻译后一并注入,
400
+ // 导出的正文颜色才能跟预览一致。
401
+ const ENGINE_THEME_FIX = `<style>${translateEngineThemeCssForExport(this.loadEngineColamdCss())}</style>`;
407
402
  const PRINT_FIX = `<style>@media print { body > article.colamd-document:not(#_) { display: block !important; } }</style>`;
408
- return patched.replace('</head>', PRINT_FIX + '\n' + THEME_FIX + '\n</head>');
403
+ // 导出文档里 mermaid 块被引擎序列化成不带类名的 `<p><svg class="pele pele-…">…</svg></p>`
404
+ // (实测 block widget 以非 .cm-line 子节点进入序列化,走段落分支,不是
405
+ // `hte('mermaid')` 的 `<div>` 分支)—— .cm-md-mermaid 上的居中、--pele-* 令牌
406
+ // 随之丢掉。所以这里按导出文档的实际结构补一份:<p> 容器补居中与上下留白。
407
+ // 图不铺底色(与 ColaMD-extend 一致:图画在页面底色上,配色按页面色推导)。
408
+ // 图上的缩放控件(.pele-zoom)是编辑器的东西,不是文档内容 —— 导出纸面上藏掉
409
+ // (镜像 colamd-extend print-layout.ts 的修复;Chromium 打印不执行脚本,
410
+ // pele 没机会收回它们,控件会叠在图上进 PDF)。
411
+ const MERMAID_FIX = `<style>
412
+ /* 图表配色不要在这里重新推导:buildExportHTML 已经把预览里 \`.cm-md-mermaid\` 上
413
+ 实际生效的 --pele-* 变量(含自定义主题显式覆盖的值)收进导出文档的 :root,
414
+ 那才是“预览中的配色”。导出端只需要补引擎序列化时丢掉的居中与留白。 */
415
+ .colamd-document .cm-md-mermaid,
416
+ .colamd-document p:has(> svg.pele) {
417
+ padding: 0.8em 0;
418
+ text-align: center;
419
+ }
420
+ .colamd-document svg.pele {
421
+ display: block; margin: 0 auto; max-width: 100%; height: auto;
422
+ }
423
+ .colamd-document .pele-zoom { display: none !important; }
424
+ </style>`;
425
+ // 兜底:导出那一刻文档里没有已渲染的 mermaid 节点(虚拟滚动把它们卸载了)时,
426
+ // 引擎收集不到 --pele-*,SVG 只能落回 pele 的浅色兜底色 —— 深色主题下整张图
427
+ // 会明显偏离预览。仅在 :root 确实缺这组令牌时按引擎同一份公式补一次;
428
+ // 已有运行时值的场景一律不动,避免覆盖预览里的真实配色。
429
+ const PELE_TOKEN_FALLBACK = /:root\s*\{[^}]*--pele-bg\s*:/i.test(patched)
430
+ ? ''
431
+ : `<style>:root {
432
+ --pele-bg: var(--bg-color);
433
+ --pele-fg: var(--text-color);
434
+ --pele-muted: color-mix(in srgb, var(--text-color) 70%, var(--bg-color));
435
+ --pele-line: var(--text-color);
436
+ --pele-surface: color-mix(in srgb, var(--text-color) 18%, var(--bg-color));
437
+ --pele-surface-alt: color-mix(in srgb, var(--text-color) 28%, var(--bg-color));
438
+ --pele-border: color-mix(in srgb, var(--text-color) 45%, var(--bg-color));
439
+ --pele-accent: var(--link-color);
440
+ --pele-radius: 6px;
441
+ }</style>`;
442
+ return patched.replace('</head>', PRINT_FIX + '\n' + MERMAID_FIX + '\n' + PELE_TOKEN_FALLBACK + '\n' + ENGINE_THEME_FIX + '\n' + THEME_FIX + '\n</head>');
443
+ }
444
+
445
+ /**
446
+ * 读取引擎自带的 colamd.css(与 WebView 加载的是同一份),供导出侧抽取主题规则。
447
+ */
448
+ private loadEngineColamdCss(): string {
449
+ const outDir = path.join(this.context.extensionPath, 'out', 'preview', 'webview');
450
+ const srcDir = path.join(this.context.extensionPath, 'src', 'preview', 'webview');
451
+ const webviewDir = fs.existsSync(outDir) ? outDir : srcDir;
452
+ try {
453
+ return fs.readFileSync(path.join(webviewDir, 'colamd.css'), 'utf-8');
454
+ } catch {
455
+ return '';
456
+ }
409
457
  }
410
458
 
411
459
  sendTheme(theme: string): void {
@@ -430,11 +478,6 @@ export class PreviewManager {
430
478
  this.panel.webview.postMessage({ type: 'themeList', ...list });
431
479
  }
432
480
 
433
- togglePlugin(id: string, enabled: boolean): void {
434
- if (!this.panel) return;
435
- this.panel.webview.postMessage({ type: 'togglePlugin', id, enabled });
436
- }
437
-
438
481
  private handleScrollSync(msg: { scrollPercent: number }): void {
439
482
  if (!this.isScrollSyncEnabled()) { return; }
440
483
 
@@ -83,7 +83,7 @@ function scrollToLine(line: number, totalLines: number, topRatio: number = 0.3):
83
83
  });
84
84
  }
85
85
 
86
- function injectThemeCSS(css: string | undefined): void {
86
+ function injectThemeCSS(css: string | undefined, themeName: string, isCustom: boolean): void {
87
87
  if (!css) return;
88
88
  let el = document.getElementById('colaview-theme-css');
89
89
  if (!el) {
@@ -91,7 +91,11 @@ function injectThemeCSS(css: string | undefined): void {
91
91
  el.id = 'colaview-theme-css';
92
92
  document.head.appendChild(el);
93
93
  }
94
- el.textContent = css;
94
+ // 主题文件的变量写在 :root 上,而引擎把同一批变量写在 body.theme-X 上
95
+ // (特异性 0,1,1 > 0,1,0),直接注入 :root 会被引擎盖掉。这里把选择器
96
+ // 提升到 body.theme-X:与引擎同特异性且后注入,主题文件里的新值才生效。
97
+ const scope = isCustom ? 'body.theme-custom' : `body.theme-${themeName}`;
98
+ el.textContent = css.replace(/:root\b/g, `:root, ${scope}`);
95
99
  }
96
100
 
97
101
  /**
@@ -116,7 +120,7 @@ window.addEventListener('message', async (event: MessageEvent) => {
116
120
  case 'init': {
117
121
  try {
118
122
  currentTheme = data.theme || 'elegant';
119
- injectThemeCSS(data.themeCSS);
123
+ injectThemeCSS(data.themeCSS, currentTheme, !!(data.customCSS && data.theme));
120
124
 
121
125
  // 2.7.9 API: 先创建编辑器(options 中不含 theme)
122
126
  handle = await createColaMDEditor({
@@ -152,13 +156,13 @@ window.addEventListener('message', async (event: MessageEvent) => {
152
156
  currentMarkdown = data.markdown;
153
157
  }
154
158
  if (data.theme) {
155
- injectThemeCSS(data.themeCSS);
159
+ currentTheme = data.theme;
160
+ injectThemeCSS(data.themeCSS, data.theme, !!data.customCSS);
156
161
  if (data.customCSS) {
157
162
  handle.applyTheme('custom:' + data.theme, data.customCSS);
158
163
  } else {
159
164
  handle.applyTheme(data.theme);
160
165
  }
161
- currentTheme = data.theme;
162
166
  ensureBodyThemeClass();
163
167
  }
164
168
  break;
@@ -182,13 +186,13 @@ window.addEventListener('message', async (event: MessageEvent) => {
182
186
  }
183
187
  case 'updateTheme': {
184
188
  if (!handle || !data.theme) return;
185
- injectThemeCSS(data.themeCSS);
189
+ currentTheme = data.theme;
190
+ injectThemeCSS(data.themeCSS, data.theme, !!data.customCSS);
186
191
  if (data.customCSS) {
187
192
  handle.applyTheme('custom:' + data.theme, data.customCSS);
188
193
  } else {
189
194
  handle.applyTheme(data.theme);
190
195
  }
191
- currentTheme = data.theme;
192
196
  ensureBodyThemeClass();
193
197
  break;
194
198
  }
@@ -198,11 +202,6 @@ window.addEventListener('message', async (event: MessageEvent) => {
198
202
  handle.applyTheme('custom:' + themeName, data.css);
199
203
  break;
200
204
  }
201
- case 'togglePlugin': {
202
- // 2.7.9 不再支持 togglePlugin — math 和 mermaid 是内置的
203
- // 此消息保留但不再执行操作,避免旧配置项报错
204
- break;
205
- }
206
205
  case 'themeList': {
207
206
  themeListData = {
208
207
  builtins: data.builtins || [],
@@ -50,6 +50,25 @@
50
50
  #editor .cm-scroller {
51
51
  overflow: auto;
52
52
  }
53
+ /* mermaid 图画在页面底色上(与 ColaMD-extend 一致):围栏是整块替换,
54
+ 没有代码块底,图表配色按页面底色/正文色推导。引擎的
55
+ `.cm-content .cm-md-mermaid` 以代码块配色推导 --pele-*,这里用
56
+ #editor 提高特异性覆盖。background 铺页面色是为了盖住 2.7.x 引擎
57
+ 可能残留的代码块行底色。 */
58
+ #editor .cm-md-mermaid {
59
+ background: var(--bg-color);
60
+ border-radius: 0;
61
+ padding: 0.8em 0;
62
+ --pele-bg: var(--bg-color);
63
+ --pele-fg: var(--text-color);
64
+ --pele-muted: color-mix(in srgb, var(--text-color) 70%, var(--bg-color));
65
+ --pele-line: var(--text-color);
66
+ --pele-surface: color-mix(in srgb, var(--text-color) 18%, var(--bg-color));
67
+ --pele-surface-alt: color-mix(in srgb, var(--text-color) 28%, var(--bg-color));
68
+ --pele-border: color-mix(in srgb, var(--text-color) 45%, var(--bg-color));
69
+ --pele-accent: var(--link-color);
70
+ --pele-radius: 6px;
71
+ }
53
72
 
54
73
  /* ── Context Menu ── */
55
74
  .ctx-menu {
@@ -9,7 +9,7 @@
9
9
  --text-color: #262626;
10
10
  --text-secondary: #767676;
11
11
  --text-muted: #8a8a8a;
12
- --border-color: #e8e6e3;
12
+ --border-color: #eeecea;
13
13
  --link-color: #d43d2a;
14
14
  --code-bg: rgba(212, 61, 42, 0.07);
15
15
  --code-block-bg: #2e2a28;
@@ -9,7 +9,7 @@
9
9
  --text-color: #e6edf3;
10
10
  --text-secondary: #aab3bd;
11
11
  --text-muted: #8b949e;
12
- --border-color: #30363d;
12
+ --border-color: #272d34;
13
13
  --link-color: #58a6ff;
14
14
  --code-bg: rgba(110, 118, 129, 0.3);
15
15
  --code-block-bg: #161b22;
@@ -18,3 +18,11 @@
18
18
  --selection-bg: rgba(88, 166, 255, 0.2);
19
19
  --highlight-bg: rgba(210, 153, 34, 0.35);
20
20
  }
21
+
22
+ #editor .cm-content .cm-md-strong {
23
+ color: #e6edf3;
24
+ }
25
+
26
+ #editor .cm-content .cm-md-inlinecode {
27
+ color: #ff7b72;
28
+ }
@@ -9,7 +9,7 @@
9
9
  --text-color: #f8f8f2;
10
10
  --text-secondary: #afb7db;
11
11
  --text-muted: #7f86a8;
12
- --border-color: #44475a;
12
+ --border-color: #3d4051;
13
13
  --link-color: #bd93f9;
14
14
  --code-bg: rgba(98, 114, 164, 0.2);
15
15
  --code-block-bg: #21222c;
@@ -32,7 +32,3 @@
32
32
  #editor .cm-content .cm-md-inlinecode {
33
33
  color: #8be9fd;
34
34
  }
35
-
36
- #editor .cm-content .cm-md-blockquote {
37
- color: #c3c8e0;
38
- }