vscode-colaview 0.3.3 → 0.4.1

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 (43) hide show
  1. package/.release-notes-v0.4.1.md +29 -0
  2. package/.vscode/settings.json +1 -1
  3. package/CHANGELOG.md +45 -16
  4. package/README.md +318 -287
  5. package/README_CN.md +318 -287
  6. package/RELEASE_NOTES.md +80 -21
  7. package/esbuild.js +2 -0
  8. package/package.json +204 -164
  9. package/package.nls.json +14 -0
  10. package/package.nls.zh-cn.json +14 -0
  11. package/src/commands/commands.ts +48 -0
  12. package/src/docx/docx-builder.ts +241 -0
  13. package/src/export/docx-exporter.ts +961 -961
  14. package/src/export/html-exporter.ts +8 -2
  15. package/src/export/pdf-exporter.ts +69 -0
  16. package/src/export/pptx-exporter.ts +63 -0
  17. package/src/export/render-export-images.ts +386 -386
  18. package/src/export/theme-style.ts +195 -195
  19. package/src/pptx/pptx-builder.ts +249 -0
  20. package/src/pptx/zip.ts +158 -0
  21. package/src/present/presenter.ts +89 -0
  22. package/src/preview/preview-manager.ts +783 -541
  23. package/src/preview/webview/app.ts +695 -370
  24. package/src/preview/webview/index.html +167 -146
  25. package/src/slides/deck.ts +408 -0
  26. package/src/slides/markdown.ts +420 -0
  27. package/src/slides/render.ts +580 -0
  28. package/src/slides/slides.css +1082 -0
  29. package/src/themes/built-in/bear.css +64 -13
  30. package/src/themes/built-in/dark.css +64 -5
  31. package/src/themes/built-in/dracula.css +64 -5
  32. package/src/themes/built-in/elegant.css +75 -11
  33. package/src/themes/built-in/gruvbox.css +65 -6
  34. package/src/themes/built-in/light.css +62 -2
  35. package/src/themes/built-in/midnight.css +64 -6
  36. package/src/themes/built-in/nord.css +64 -5
  37. package/src/themes/built-in/notion.css +63 -11
  38. package/src/themes/built-in/sepia.css +65 -10
  39. package/src/themes/built-in/solarized-dark.css +64 -5
  40. package/src/themes/built-in/writer.css +66 -19
  41. package/src/themes/theme-manager.ts +207 -180
  42. package/src/types/colamd-renderer.d.ts +47 -47
  43. package/src/types/pele-lazy.d.ts +21 -0
@@ -1,542 +1,784 @@
1
- // 预览面板管理器 — WebView 面板生命周期管理 + Milkdown 编辑器同步
2
- import * as vscode from 'vscode';
3
- import * as path from 'path';
4
- import * as fs from 'fs';
5
- import { ThemeManager } from '../themes/theme-manager';
6
- import { exportHTML } from '../export/html-exporter';
7
- import { exportPDF } from '../export/pdf-exporter';
8
- import { exportWord } from '../export/docx-exporter';
9
- import { translateThemeCssForExport, translateEngineThemeCssForExport } from '../export/theme-style';
10
-
11
- function getNonce(): string {
12
- const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
13
- let result = '';
14
- for (let i = 0; i < 32; i++) {
15
- result += chars.charAt(Math.floor(Math.random() * chars.length));
16
- }
17
- return result;
18
- }
19
-
20
- function getTopVisibleLine(editor: vscode.TextEditor): number | undefined {
21
- if (!editor.visibleRanges.length) {
22
- return undefined;
23
- }
24
- return editor.visibleRanges[0].start.line;
25
- }
26
-
27
- function getBottomVisibleLine(editor: vscode.TextEditor): number | undefined {
28
- if (!editor.visibleRanges.length) {
29
- return undefined;
30
- }
31
- const lastRange = editor.visibleRanges[editor.visibleRanges.length - 1];
32
- return lastRange.end.line;
33
- }
34
-
35
- export class PreviewManager {
36
- private panel: vscode.WebviewPanel | null = null;
37
- private currentUri: vscode.Uri | null = null;
38
- private debounceTimer: NodeJS.Timeout | null = null;
39
- private disposables: vscode.Disposable[] = [];
40
- private pendingDocument: vscode.TextDocument | null = null;
41
- private exportResolve: ((html: string) => void) | null = null;
42
- private editorScrollDelay = Date.now();
43
-
44
- constructor(private context: vscode.ExtensionContext) {
45
- this.registerActiveEditorListener();
46
- this.registerScrollSyncListeners();
47
- }
48
-
49
- private registerActiveEditorListener(): void {
50
- try {
51
- vscode.window.onDidChangeActiveTextEditor(editor => {
52
- try {
53
- if (editor && editor.document.languageId === 'markdown' && this.panel) {
54
- if (this.currentUri?.toString() !== editor.document.uri.toString()) {
55
- this.currentUri = editor.document.uri;
56
- this.updatePreview(editor.document);
57
- }
58
- }
59
- } catch (e) {
60
- console.error('[ColaView] onDidChangeActiveTextEditor error:', e);
61
- }
62
- }, null, this.disposables);
63
- } catch (e) {
64
- console.error('[ColaView] registerActiveEditorListener failed:', e);
65
- }
66
- }
67
-
68
- private registerScrollSyncListeners(): void {
69
- try {
70
- vscode.window.onDidChangeTextEditorSelection((event) => {
71
- try {
72
- if (!this.isScrollSyncEnabled()) { return; }
73
- const editor = event.textEditor;
74
- if (Date.now() < this.editorScrollDelay) { return; }
75
- if (editor.document.languageId !== 'markdown') { return; }
76
- if (editor.document.uri.toString() !== this.currentUri?.toString()) { return; }
77
-
78
- const topLine = getTopVisibleLine(editor);
79
- const bottomLine = getBottomVisibleLine(editor);
80
- if (typeof topLine === 'undefined' || typeof bottomLine === 'undefined') { return; }
81
-
82
- const cursorLine = event.selections[0].active.line;
83
- const topRatio = (bottomLine > topLine)
84
- ? (cursorLine - topLine) / (bottomLine - topLine)
85
- : 0.3;
86
-
87
- this.panel?.webview.postMessage({
88
- type: 'editorScroll',
89
- line: cursorLine,
90
- totalLines: editor.document.lineCount,
91
- topRatio: Math.max(0, Math.min(1, topRatio)),
92
- });
93
- } catch (e) {
94
- // silently ignore errors in scroll sync handler
95
- }
96
- }, null, this.disposables);
97
-
98
- vscode.window.onDidChangeTextEditorVisibleRanges((event) => {
99
- try {
100
- if (!this.isScrollSyncEnabled()) { return; }
101
- const editor = event.textEditor;
102
- if (Date.now() < this.editorScrollDelay) { return; }
103
- if (editor.document.languageId !== 'markdown') { return; }
104
- if (editor.document.uri.toString() !== this.currentUri?.toString()) { return; }
105
-
106
- const totalLines = editor.document.lineCount;
107
- if (totalLines <= 1) { return; }
108
-
109
- const topLine = getTopVisibleLine(editor);
110
- const bottomLine = getBottomVisibleLine(editor);
111
- if (typeof topLine === 'undefined' || typeof bottomLine === 'undefined') { return; }
112
-
113
- let midLine: number;
114
- if (topLine === 0) {
115
- midLine = 0;
116
- } else if (Math.floor(bottomLine) === totalLines - 1) {
117
- midLine = bottomLine;
118
- } else {
119
- midLine = Math.floor((topLine + bottomLine) / 2);
120
- }
121
-
122
- const scrollPercent = midLine / (totalLines - 1);
123
-
124
- this.panel?.webview.postMessage({
125
- type: 'editorScroll',
126
- scrollPercent: Math.max(0, Math.min(1, scrollPercent)),
127
- });
128
- } catch (e) {
129
- // silently ignore errors in scroll sync handler
130
- }
131
- }, null, this.disposables);
132
- } catch (e) {
133
- console.error('[ColaView] registerScrollSyncListeners failed:', e);
134
- }
135
- }
136
-
137
- private isScrollSyncEnabled(): boolean {
138
- try {
139
- return vscode.workspace.getConfiguration('colaview').get<boolean>('scrollSync', false);
140
- } catch {
141
- return false;
142
- }
143
- }
144
-
145
- showPreview(): void {
146
- const editor = vscode.window.activeTextEditor;
147
- if (!editor || editor.document.languageId !== 'markdown') {
148
- vscode.window.showWarningMessage('No Markdown file is open');
149
- return;
150
- }
151
-
152
- this.currentUri = editor.document.uri;
153
-
154
- if (this.panel) {
155
- this.panel.reveal(vscode.ViewColumn.Two);
156
- this.updatePreview(editor.document);
157
- } else {
158
- this.panel = vscode.window.createWebviewPanel(
159
- 'colaview',
160
- `Preview: ${path.basename(editor.document.fileName)}`,
161
- vscode.ViewColumn.Two,
162
- {
163
- enableScripts: true,
164
- localResourceRoots: [
165
- vscode.Uri.joinPath(this.context.extensionUri, 'out', 'preview', 'webview'),
166
- vscode.Uri.joinPath(this.context.extensionUri, 'src', 'preview', 'webview'),
167
- vscode.Uri.file(path.dirname(editor.document.fileName)),
168
- ],
169
- retainContextWhenHidden: true,
170
- }
171
- );
172
-
173
- this.panel.webview.html = this.buildWebViewHTML();
174
- this.panel.onDidDispose(() => { this.panel = null; }, null, this.disposables);
175
-
176
- this.panel.webview.onDidReceiveMessage((msg: { type: string; html?: string; message?: string; name?: string; scrollPercent?: number }) => {
177
- switch (msg.type) {
178
- case 'ready': {
179
- const theme = ThemeManager.getCurrentTheme();
180
- const markdown = this.pendingDocument?.getText() || '';
181
- const builtins = ThemeManager.getBuiltinThemes();
182
- const isCustom = !builtins.includes(theme);
183
- const customCSS = isCustom ? ThemeManager.loadThemeCSS(theme) : undefined;
184
- const themeCSS = ThemeManager.loadThemeCSS(theme);
185
- this.panel?.webview.postMessage({
186
- type: 'init',
187
- markdown,
188
- theme,
189
- customCSS,
190
- themeCSS,
191
- });
192
- this.pendingDocument = null;
193
- const list = ThemeManager.getThemeList();
194
- this.panel?.webview.postMessage({ type: 'themeList', ...list });
195
- break;
196
- }
197
- case 'exportHTMLResult': {
198
- if (this.exportResolve) {
199
- this.exportResolve(msg.html || '');
200
- this.exportResolve = null;
201
- }
202
- break;
203
- }
204
- case 'error': {
205
- console.error('[ColaView] WebView error:', msg.message);
206
- break;
207
- }
208
- case 'requestExportHTML': {
209
- this.handleExportHTML();
210
- break;
211
- }
212
- case 'requestExportPDF': {
213
- this.handleExportPDF();
214
- break;
215
- }
216
- case 'requestExportWord': {
217
- this.handleExportWord();
218
- break;
219
- }
220
- case 'requestImportTheme': {
221
- vscode.commands.executeCommand('colaview.importTheme');
222
- break;
223
- }
224
- case 'requestThemeList': {
225
- const list = ThemeManager.getThemeList();
226
- this.panel?.webview.postMessage({ type: 'themeList', ...list });
227
- break;
228
- }
229
- case 'switchTheme': {
230
- if (msg.name) {
231
- this.handleSwitchTheme(msg.name);
232
- }
233
- break;
234
- }
235
- case 'scrollSync': {
236
- if (msg.scrollPercent !== undefined) {
237
- this.handleScrollSync({ scrollPercent: msg.scrollPercent });
238
- }
239
- break;
240
- }
241
- }
242
- }, null, this.disposables);
243
-
244
- this.pendingDocument = editor.document;
245
-
246
- vscode.workspace.onDidChangeTextDocument(e => {
247
- if (e.document.uri.toString() === this.currentUri?.toString()) {
248
- if (this.debounceTimer) clearTimeout(this.debounceTimer);
249
- this.debounceTimer = setTimeout(() => {
250
- this.updatePreview(e.document);
251
- }, 150);
252
- }
253
- }, null, this.disposables);
254
- }
255
- }
256
-
257
- private async handleExportHTML(): Promise<void> {
258
- if (!this.currentUri) {
259
- vscode.window.showWarningMessage('No Markdown file is open');
260
- return;
261
- }
262
- try {
263
- const document = await vscode.workspace.openTextDocument(this.currentUri);
264
- const fullHTML = await this.getExportHTML();
265
- if (!fullHTML) {
266
- vscode.window.showWarningMessage('Could not get rendered HTML from preview');
267
- return;
268
- }
269
- await exportHTML(document, fullHTML);
270
- } catch (e) {
271
- vscode.window.showErrorMessage(`HTML export failed: ${e instanceof Error ? e.message : String(e)}`);
272
- }
273
- }
274
-
275
- private async handleExportPDF(): Promise<void> {
276
- if (!this.currentUri) {
277
- vscode.window.showWarningMessage('No Markdown file is open');
278
- return;
279
- }
280
- try {
281
- const document = await vscode.workspace.openTextDocument(this.currentUri);
282
- const fullHTML = await this.getExportHTML();
283
- if (!fullHTML) {
284
- vscode.window.showWarningMessage('Could not get rendered HTML from preview');
285
- return;
286
- }
287
- await exportPDF(document, fullHTML);
288
- } catch (e) {
289
- vscode.window.showErrorMessage(`PDF export failed: ${e instanceof Error ? e.message : String(e)}`);
290
- }
291
- }
292
-
293
- private async handleExportWord(): Promise<void> {
294
- if (!this.currentUri) {
295
- vscode.window.showWarningMessage('No Markdown file is open');
296
- return;
297
- }
298
- try {
299
- const document = await vscode.workspace.openTextDocument(this.currentUri);
300
- await exportWord(document);
301
- } catch (e) {
302
- vscode.window.showErrorMessage(`Word export failed: ${e instanceof Error ? e.message : String(e)}`);
303
- }
304
- }
305
-
306
- private async handleSwitchTheme(name: string): Promise<void> {
307
- await ThemeManager.switchTheme(name);
308
- const builtins = ThemeManager.getBuiltinThemes();
309
- const isCustom = !builtins.includes(name);
310
- const customCSS = isCustom ? ThemeManager.loadThemeCSS(name) : undefined;
311
- const themeCSS = ThemeManager.loadThemeCSS(name);
312
- this.panel?.webview.postMessage({ type: 'updateTheme', theme: name, customCSS, themeCSS });
313
- const list = ThemeManager.getThemeList();
314
- this.panel?.webview.postMessage({ type: 'themeList', ...list });
315
- }
316
-
317
- private updatePreview(document: vscode.TextDocument): void {
318
- if (!this.panel) return;
319
- const markdown = document.getText();
320
- const theme = ThemeManager.getCurrentTheme();
321
- const builtins = ThemeManager.getBuiltinThemes();
322
- const isCustom = !builtins.includes(theme);
323
- const customCSS = isCustom ? ThemeManager.loadThemeCSS(theme) : undefined;
324
- const themeCSS = ThemeManager.loadThemeCSS(theme);
325
- this.panel.webview.postMessage({
326
- type: 'update',
327
- markdown,
328
- theme,
329
- customCSS,
330
- themeCSS,
331
- });
332
- }
333
-
334
- async getExportHTML(): Promise<string> {
335
- if (!this.panel) {
336
- throw new Error('No preview panel is open. Please open a preview first.');
337
- }
338
- const html = await new Promise<string>((resolve) => {
339
- this.exportResolve = resolve;
340
- const title = this.currentUri
341
- ? path.basename(this.currentUri.fsPath, '.md')
342
- : undefined;
343
- this.panel!.webview.postMessage({ type: 'exportHTML', title });
344
- setTimeout(() => {
345
- if (this.exportResolve) {
346
- this.exportResolve('');
347
- this.exportResolve = null;
348
- }
349
- }, 30000);
350
- });
351
- return this.patchExportHTML(html);
352
- }
353
-
354
- /**
355
- * 导出 HTML 后处理:
356
- * colamd.css 末尾带一条 Electron 桌面版专用的打印规则
357
- * `@media print { body > :not(#editor-region), ... { display: none !important } }`
358
- * 它假定打印时 body 下只保留 #editor-region(ColaMD 桌面版结构),而我们的导出
359
- * HTML 是 <body><article class="colamd-document">,没有 #editor-region ——
360
- * article 会被整体隐藏,PDF/浏览器打印全部空白(仅剩一页空纸)。
361
- *
362
- * 覆盖规则用 :not(#_) 抬高特异性:原规则含 ID(:not(#editor-region) = 1,0,1),
363
- * 普通 class 选择器(0,1,2)同带 !important 时也输给它;:not(#_) 恒真但贡献
364
- * ID 特异性,得到 (1,1,2),稳定压制原规则。
365
- * HTML 导出在浏览器中 Ctrl+P 同样受益。
366
- */
367
- private patchExportHTML(html: string): string {
368
- if (!html) return html;
369
-
370
- // colamd 导出器把 document.body 的 class 原样复制到导出 HTML 的 <body> 上,
371
- // 而它收集的主题规则(colamd.css 内置的 body.theme-X 字体/强调色/变量)全部
372
- // 以 body.theme-X 为作用域 —— body 缺主题类时这些规则整体失配,导出就只剩
373
- // 浅色默认样式。这里兜底把主题类补到导出 body 上。
374
- const theme = ThemeManager.getCurrentTheme();
375
- const isBuiltin = ThemeManager.getBuiltinThemes().includes(theme);
376
- const themeClass = isBuiltin ? ThemeManager.getThemeClass(theme) : 'theme-custom';
377
- let patched = html;
378
- const bodyTagMatch = /<body[^>]*>/i.exec(patched);
379
- if (bodyTagMatch) {
380
- const bodyTag = bodyTagMatch[0];
381
- if (/\sclass="/.test(bodyTag)) {
382
- if (!new RegExp(`\\s${themeClass}[\\s"]`).test(bodyTag)) {
383
- patched = patched.replace(bodyTag, bodyTag.replace(/\sclass="/, ` class="${themeClass} `));
384
- }
385
- } else {
386
- patched = patched.replace(bodyTag, bodyTag.replace(/<body/i, `<body class="${themeClass}"`));
387
- }
388
- }
389
-
390
- // 自定义主题的规则不在 colamd.css 里(内置主题的翻译规则是冗余兜底),
391
- // 翻译成语义选择器后注入到 </head> 前,保证优先级最高。
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}`);
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>`;
402
- const PRINT_FIX = `<style>@media print { body > article.colamd-document:not(#_) { display: block !important; } }</style>`;
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
- }
457
- }
458
-
459
- sendTheme(theme: string): void {
460
- if (!this.panel) return;
461
- this.panel.webview.postMessage({ type: 'updateTheme', theme });
462
- }
463
-
464
- switchThemeFromCommand(name: string): void {
465
- if (!this.panel) return;
466
- const builtins = ThemeManager.getBuiltinThemes();
467
- const isCustom = !builtins.includes(name);
468
- const customCSS = isCustom ? ThemeManager.loadThemeCSS(name) : undefined;
469
- const themeCSS = ThemeManager.loadThemeCSS(name);
470
- this.panel.webview.postMessage({ type: 'updateTheme', theme: name, customCSS, themeCSS });
471
- const list = ThemeManager.getThemeList();
472
- this.panel.webview.postMessage({ type: 'themeList', ...list });
473
- }
474
-
475
- refreshThemeList(): void {
476
- if (!this.panel) return;
477
- const list = ThemeManager.getThemeList();
478
- this.panel.webview.postMessage({ type: 'themeList', ...list });
479
- }
480
-
481
- private handleScrollSync(msg: { scrollPercent: number }): void {
482
- if (!this.isScrollSyncEnabled()) { return; }
483
-
484
- const scrollPercent = msg.scrollPercent;
485
- const editor = vscode.window.activeTextEditor;
486
- if (!editor || editor.document.uri.toString() !== this.currentUri?.toString()) {
487
- return;
488
- }
489
-
490
- const totalLines = editor.document.lineCount;
491
- const targetLine = Math.floor(scrollPercent * (totalLines - 1));
492
-
493
- this.editorScrollDelay = Date.now() + 500;
494
-
495
- const range = new vscode.Range(targetLine, 0, targetLine + 1, 0);
496
- editor.revealRange(range, vscode.TextEditorRevealType.AtTop);
497
- }
498
-
499
- private buildWebViewHTML(): string {
500
- const outDir = path.join(this.context.extensionPath, 'out', 'preview', 'webview');
501
- const srcDir = path.join(this.context.extensionPath, 'src', 'preview', 'webview');
502
- const webviewDir = fs.existsSync(outDir) ? outDir : srcDir;
503
-
504
- const appJsPath = vscode.Uri.file(path.join(webviewDir, 'app.js'));
505
- const appJsUri = this.panel!.webview.asWebviewUri(appJsPath);
506
-
507
- const nonce = getNonce();
508
-
509
- const indexPath = path.join(webviewDir, 'index.html');
510
- let html = fs.readFileSync(indexPath, 'utf-8');
511
-
512
- html = html.replace(
513
- /<meta http-equiv="Content-Security-Policy"[^>]*>/,
514
- `<meta http-equiv="Content-Security-Policy" content="default-src 'none'; style-src 'unsafe-inline' vscode-webview-resource:; script-src 'nonce-${nonce}' vscode-webview-resource:; font-src vscode-webview-resource: data:; img-src file: data: https: vscode-webview-resource:; connect-src https: vscode-webview-resource:;">`
515
- );
516
-
517
- // colamd.css 必须内联为 <style>,不能用 <link>:
518
- // 跨源 <link> 的 cssRules 对 CSSOM 不可访问(SecurityError),buildExportHTML 的
519
- // collectExportStyles() 会静默丢掉全部渲染样式(1.43MB → 15KB),导出的 HTML/PDF
520
- // 就没有排版和 KaTeX 字体了。内联样式对 CSSOM 完全可读,导出管线才能完整带走样式。
521
- const colamdCss = fs.readFileSync(path.join(webviewDir, 'colamd.css'), 'utf-8')
522
- .replace(/<\/style/gi, '<\\/style') // 防 css 内容意外闭合 style 标签
523
- // 剥离 ColaMD 桌面版打印隐藏规则,从源头避免导出 HTML/PDF 里 article 被 display:none
524
- .replace(/@media\s*print\s*\{[^}]*\}/gi, (m) => m.includes('#editor-region') ? '' : m);
525
- html = html.replace(
526
- /<link rel="stylesheet" href="colamd\.css" id="colamd-css">/,
527
- `<style id="colamd-css">${colamdCss}</style>`
528
- );
529
-
530
- html = html.replace(
531
- '<script src="app.js"></script>',
532
- `<script nonce="${nonce}" src="${appJsUri}"></script>`
533
- );
534
-
535
- return html;
536
- }
537
-
538
- dispose(): void {
539
- this.panel?.dispose();
540
- this.disposables.forEach(d => d.dispose());
541
- }
1
+ // 预览面板管理器 — WebView 面板生命周期管理 + Milkdown 编辑器同步
2
+ import * as vscode from 'vscode';
3
+ import * as path from 'path';
4
+ import * as fs from 'fs';
5
+ import { ThemeManager } from '../themes/theme-manager';
6
+ import { exportHTML, exportStandaloneHTML } from '../export/html-exporter';
7
+ import { exportPDF, exportSlidesPDF } from '../export/pdf-exporter';
8
+ import { exportWord } from '../export/docx-exporter';
9
+ import { exportPPTX } from '../export/pptx-exporter';
10
+ import { translateThemeCssForExport, translateEngineThemeCssForExport } from '../export/theme-style';
11
+ import { composeDeckCss, decoratePresentDocument, renderDeckStage, renderSlidesDocument, rewriteImageSources } from '../slides/render';
12
+ import { openPresentWindow } from '../present/presenter';
13
+
14
+ /** 预览模式:整篇文档 / 幻灯片(自有渲染层)。 */
15
+ type PreviewMode = 'document' | 'slides';
16
+
17
+ function getNonce(): string {
18
+ const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
19
+ let result = '';
20
+ for (let i = 0; i < 32; i++) {
21
+ result += chars.charAt(Math.floor(Math.random() * chars.length));
22
+ }
23
+ return result;
24
+ }
25
+
26
+ function getTopVisibleLine(editor: vscode.TextEditor): number | undefined {
27
+ if (!editor.visibleRanges.length) {
28
+ return undefined;
29
+ }
30
+ return editor.visibleRanges[0].start.line;
31
+ }
32
+
33
+ function getBottomVisibleLine(editor: vscode.TextEditor): number | undefined {
34
+ if (!editor.visibleRanges.length) {
35
+ return undefined;
36
+ }
37
+ const lastRange = editor.visibleRanges[editor.visibleRanges.length - 1];
38
+ return lastRange.end.line;
39
+ }
40
+
41
+ export class PreviewManager {
42
+ private panel: vscode.WebviewPanel | null = null;
43
+ private currentUri: vscode.Uri | null = null;
44
+ private debounceTimer: NodeJS.Timeout | null = null;
45
+ private disposables: vscode.Disposable[] = [];
46
+ private pendingDocument: vscode.TextDocument | null = null;
47
+ private exportResolve: ((html: string) => void) | null = null;
48
+ private editorScrollDelay = Date.now();
49
+ /** 当前面板处于文档模式还是幻灯片模式。 */
50
+ private mode: PreviewMode = 'document';
51
+
52
+ constructor(private context: vscode.ExtensionContext) {
53
+ this.registerActiveEditorListener();
54
+ this.registerScrollSyncListeners();
55
+ }
56
+
57
+ private registerActiveEditorListener(): void {
58
+ try {
59
+ vscode.window.onDidChangeActiveTextEditor(editor => {
60
+ try {
61
+ if (editor && editor.document.languageId === 'markdown' && this.panel) {
62
+ if (this.currentUri?.toString() !== editor.document.uri.toString()) {
63
+ this.currentUri = editor.document.uri;
64
+ this.updatePreview(editor.document);
65
+ }
66
+ }
67
+ } catch (e) {
68
+ console.error('[ColaView] onDidChangeActiveTextEditor error:', e);
69
+ }
70
+ }, null, this.disposables);
71
+ } catch (e) {
72
+ console.error('[ColaView] registerActiveEditorListener failed:', e);
73
+ }
74
+ }
75
+
76
+ private registerScrollSyncListeners(): void {
77
+ try {
78
+ vscode.window.onDidChangeTextEditorSelection((event) => {
79
+ try {
80
+ if (!this.isScrollSyncEnabled()) { return; }
81
+ const editor = event.textEditor;
82
+ if (Date.now() < this.editorScrollDelay) { return; }
83
+ if (editor.document.languageId !== 'markdown') { return; }
84
+ if (editor.document.uri.toString() !== this.currentUri?.toString()) { return; }
85
+
86
+ const topLine = getTopVisibleLine(editor);
87
+ const bottomLine = getBottomVisibleLine(editor);
88
+ if (typeof topLine === 'undefined' || typeof bottomLine === 'undefined') { return; }
89
+
90
+ const cursorLine = event.selections[0].active.line;
91
+ const topRatio = (bottomLine > topLine)
92
+ ? (cursorLine - topLine) / (bottomLine - topLine)
93
+ : 0.3;
94
+
95
+ this.panel?.webview.postMessage({
96
+ type: 'editorScroll',
97
+ line: cursorLine,
98
+ totalLines: editor.document.lineCount,
99
+ topRatio: Math.max(0, Math.min(1, topRatio)),
100
+ });
101
+ } catch (e) {
102
+ // silently ignore errors in scroll sync handler
103
+ }
104
+ }, null, this.disposables);
105
+
106
+ vscode.window.onDidChangeTextEditorVisibleRanges((event) => {
107
+ try {
108
+ if (!this.isScrollSyncEnabled()) { return; }
109
+ const editor = event.textEditor;
110
+ if (Date.now() < this.editorScrollDelay) { return; }
111
+ if (editor.document.languageId !== 'markdown') { return; }
112
+ if (editor.document.uri.toString() !== this.currentUri?.toString()) { return; }
113
+
114
+ const totalLines = editor.document.lineCount;
115
+ if (totalLines <= 1) { return; }
116
+
117
+ const topLine = getTopVisibleLine(editor);
118
+ const bottomLine = getBottomVisibleLine(editor);
119
+ if (typeof topLine === 'undefined' || typeof bottomLine === 'undefined') { return; }
120
+
121
+ let midLine: number;
122
+ if (topLine === 0) {
123
+ midLine = 0;
124
+ } else if (Math.floor(bottomLine) === totalLines - 1) {
125
+ midLine = bottomLine;
126
+ } else {
127
+ midLine = Math.floor((topLine + bottomLine) / 2);
128
+ }
129
+
130
+ const scrollPercent = midLine / (totalLines - 1);
131
+
132
+ this.panel?.webview.postMessage({
133
+ type: 'editorScroll',
134
+ scrollPercent: Math.max(0, Math.min(1, scrollPercent)),
135
+ });
136
+ } catch (e) {
137
+ // silently ignore errors in scroll sync handler
138
+ }
139
+ }, null, this.disposables);
140
+ } catch (e) {
141
+ console.error('[ColaView] registerScrollSyncListeners failed:', e);
142
+ }
143
+ }
144
+
145
+ private isScrollSyncEnabled(): boolean {
146
+ try {
147
+ return vscode.workspace.getConfiguration('colaview').get<boolean>('scrollSync', false);
148
+ } catch {
149
+ return false;
150
+ }
151
+ }
152
+
153
+ showPreview(): void {
154
+ const editor = vscode.window.activeTextEditor;
155
+ if (!editor || editor.document.languageId !== 'markdown') {
156
+ vscode.window.showWarningMessage('No Markdown file is open');
157
+ return;
158
+ }
159
+
160
+ this.currentUri = editor.document.uri;
161
+ this.mode = 'document';
162
+
163
+ if (this.panel) {
164
+ this.panel.title = `Preview: ${path.basename(editor.document.fileName)}`;
165
+ this.panel.reveal(vscode.ViewColumn.Two);
166
+ this.pushMode();
167
+ this.updatePreview(editor.document);
168
+ } else {
169
+ this.panel = vscode.window.createWebviewPanel(
170
+ 'colaview',
171
+ `Preview: ${path.basename(editor.document.fileName)}`,
172
+ vscode.ViewColumn.Two,
173
+ {
174
+ enableScripts: true,
175
+ localResourceRoots: [
176
+ vscode.Uri.joinPath(this.context.extensionUri, 'out', 'preview', 'webview'),
177
+ vscode.Uri.joinPath(this.context.extensionUri, 'src', 'preview', 'webview'),
178
+ vscode.Uri.file(path.dirname(editor.document.fileName)),
179
+ ],
180
+ retainContextWhenHidden: true,
181
+ }
182
+ );
183
+
184
+ this.panel.webview.html = this.buildWebViewHTML();
185
+ this.panel.onDidDispose(() => { this.panel = null; }, null, this.disposables);
186
+
187
+ this.panel.webview.onDidReceiveMessage((msg: { type: string; html?: string; message?: string; name?: string; scrollPercent?: number; mode?: string }) => {
188
+ switch (msg.type) {
189
+ case 'ready': {
190
+ const theme = ThemeManager.getCurrentTheme();
191
+ const markdown = this.pendingDocument?.getText() || '';
192
+ const builtins = ThemeManager.getBuiltinThemes();
193
+ const isCustom = !builtins.includes(theme);
194
+ const customCSS = isCustom ? ThemeManager.loadThemeCSS(theme) : undefined;
195
+ const themeCSS = ThemeManager.loadThemeCSS(theme);
196
+ this.panel?.webview.postMessage({
197
+ type: 'init',
198
+ markdown,
199
+ theme,
200
+ customCSS,
201
+ themeCSS,
202
+ mode: this.mode,
203
+ labels: this.menuLabels(),
204
+ });
205
+ this.pendingDocument = null;
206
+ const list = ThemeManager.getThemeList();
207
+ this.panel?.webview.postMessage({ type: 'themeList', ...list });
208
+ break;
209
+ }
210
+ case 'exportHTMLResult': {
211
+ if (this.exportResolve) {
212
+ this.exportResolve(msg.html || '');
213
+ this.exportResolve = null;
214
+ }
215
+ break;
216
+ }
217
+ case 'error': {
218
+ console.error('[ColaView] WebView error:', msg.message);
219
+ break;
220
+ }
221
+ case 'requestExportHTML': {
222
+ // 文档模式导出 Milkdown 渲染的独立 HTML;幻灯片模式导出放映文档。
223
+ if (this.mode === 'slides') void this.exportSlidesHTMLToFile();
224
+ else this.handleExportHTML();
225
+ break;
226
+ }
227
+ case 'requestExportPDF': {
228
+ if (this.mode === 'slides') void this.exportSlidesPDFToFile();
229
+ else this.handleExportPDF();
230
+ break;
231
+ }
232
+ case 'requestExportWord': {
233
+ this.handleExportWord();
234
+ break;
235
+ }
236
+ case 'requestExportPPTX': {
237
+ void this.exportPPTXFile();
238
+ break;
239
+ }
240
+ case 'requestPresent': {
241
+ void this.handlePresent(msg.mode === 'slides' ? 'slides' : 'document');
242
+ break;
243
+ }
244
+ case 'requestSlides': {
245
+ this.showSlides();
246
+ break;
247
+ }
248
+ case 'requestDocument': {
249
+ this.showPreview();
250
+ break;
251
+ }
252
+ case 'requestImportTheme': {
253
+ vscode.commands.executeCommand('colaview.importTheme');
254
+ break;
255
+ }
256
+ case 'requestThemeList': {
257
+ const list = ThemeManager.getThemeList();
258
+ this.panel?.webview.postMessage({ type: 'themeList', ...list });
259
+ break;
260
+ }
261
+ case 'switchTheme': {
262
+ if (msg.name) {
263
+ this.handleSwitchTheme(msg.name);
264
+ }
265
+ break;
266
+ }
267
+ case 'scrollSync': {
268
+ if (msg.scrollPercent !== undefined) {
269
+ this.handleScrollSync({ scrollPercent: msg.scrollPercent });
270
+ }
271
+ break;
272
+ }
273
+ }
274
+ }, null, this.disposables);
275
+
276
+ this.pendingDocument = editor.document;
277
+
278
+ vscode.workspace.onDidChangeTextDocument(e => {
279
+ if (e.document.uri.toString() === this.currentUri?.toString()) {
280
+ if (this.debounceTimer) clearTimeout(this.debounceTimer);
281
+ this.debounceTimer = setTimeout(() => {
282
+ this.updatePreview(e.document);
283
+ }, 150);
284
+ }
285
+ }, null, this.disposables);
286
+ }
287
+ }
288
+
289
+ private async handleExportHTML(): Promise<void> {
290
+ if (!this.currentUri) {
291
+ vscode.window.showWarningMessage('No Markdown file is open');
292
+ return;
293
+ }
294
+ try {
295
+ const document = await vscode.workspace.openTextDocument(this.currentUri);
296
+ const fullHTML = await this.getExportHTML();
297
+ if (!fullHTML) {
298
+ vscode.window.showWarningMessage('Could not get rendered HTML from preview');
299
+ return;
300
+ }
301
+ await exportHTML(document, fullHTML);
302
+ } catch (e) {
303
+ vscode.window.showErrorMessage(`HTML export failed: ${e instanceof Error ? e.message : String(e)}`);
304
+ }
305
+ }
306
+
307
+ private async handleExportPDF(): Promise<void> {
308
+ if (!this.currentUri) {
309
+ vscode.window.showWarningMessage('No Markdown file is open');
310
+ return;
311
+ }
312
+ try {
313
+ const document = await vscode.workspace.openTextDocument(this.currentUri);
314
+ const fullHTML = await this.getExportHTML();
315
+ if (!fullHTML) {
316
+ vscode.window.showWarningMessage('Could not get rendered HTML from preview');
317
+ return;
318
+ }
319
+ await exportPDF(document, fullHTML);
320
+ } catch (e) {
321
+ vscode.window.showErrorMessage(`PDF export failed: ${e instanceof Error ? e.message : String(e)}`);
322
+ }
323
+ }
324
+
325
+ private async handleExportWord(): Promise<void> {
326
+ if (!this.currentUri) {
327
+ vscode.window.showWarningMessage('No Markdown file is open');
328
+ return;
329
+ }
330
+ try {
331
+ const document = await vscode.workspace.openTextDocument(this.currentUri);
332
+ await exportWord(document);
333
+ } catch (e) {
334
+ vscode.window.showErrorMessage(`Word export failed: ${e instanceof Error ? e.message : String(e)}`);
335
+ }
336
+ }
337
+
338
+ private async handleSwitchTheme(name: string): Promise<void> {
339
+ await ThemeManager.switchTheme(name);
340
+ const builtins = ThemeManager.getBuiltinThemes();
341
+ const isCustom = !builtins.includes(name);
342
+ const customCSS = isCustom ? ThemeManager.loadThemeCSS(name) : undefined;
343
+ const themeCSS = ThemeManager.loadThemeCSS(name);
344
+ this.panel?.webview.postMessage({ type: 'updateTheme', theme: name, customCSS, themeCSS });
345
+ const list = ThemeManager.getThemeList();
346
+ this.panel?.webview.postMessage({ type: 'themeList', ...list });
347
+ if (this.mode === 'slides') void this.pushSlides(true, name);
348
+ }
349
+
350
+ /** 切到幻灯片模式(同一面板内切换,保留当前文档与主题)。 */
351
+ showSlides(): void {
352
+ const editor = vscode.window.activeTextEditor;
353
+ if (!editor || editor.document.languageId !== 'markdown') {
354
+ vscode.window.showWarningMessage('No Markdown file is open');
355
+ return;
356
+ }
357
+ if (!this.panel) {
358
+ this.showPreview();
359
+ }
360
+ if (!this.panel) return;
361
+
362
+ this.mode = 'slides';
363
+ this.currentUri = editor.document.uri;
364
+ this.panel.title = `Slides: ${path.basename(editor.document.fileName)}`;
365
+ this.panel.reveal(vscode.ViewColumn.Two);
366
+ this.pushMode();
367
+ void this.pushSlides(true);
368
+ }
369
+
370
+ private pushMode(): void {
371
+ this.panel?.webview.postMessage({ type: 'mode', mode: this.mode });
372
+ }
373
+
374
+ /**
375
+ * WebView 右键菜单文案:面板内菜单由扩展宿主按 `vscode.env.language` 下发。
376
+ */
377
+ private menuLabels(): Record<string, string> {
378
+ const zh = vscode.env.language.toLowerCase().startsWith('zh');
379
+ return zh
380
+ ? {
381
+ present: '全屏显示',
382
+ exportPdf: '导出到 PDF',
383
+ exportHtml: '导出到 HTML',
384
+ exportWord: '导出到 Word',
385
+ exportPptx: '导出到 PPTX',
386
+ theme: '主题',
387
+ importTheme: '导入主题…',
388
+ loading: '加载中…',
389
+ groupLight: '内置 · 亮色',
390
+ groupDark: '内置 · 暗色',
391
+ groupCustom: '自定义',
392
+ }
393
+ : {
394
+ present: 'Present (Fullscreen)',
395
+ exportPdf: 'Export to PDF',
396
+ exportHtml: 'Export to HTML',
397
+ exportWord: 'Export to Word',
398
+ exportPptx: 'Export to PPTX',
399
+ theme: 'Theme',
400
+ importTheme: 'Import Theme…',
401
+ loading: 'Loading…',
402
+ groupLight: 'Built-in · Light',
403
+ groupDark: 'Built-in · Dark',
404
+ groupCustom: 'Custom',
405
+ };
406
+ }
407
+
408
+ /** 主题 body 类名:内置主题 `theme-<name>`,自定义主题统一 `theme-custom`。 */
409
+ private themeBodyClass(theme?: string): string {
410
+ const current = theme ?? ThemeManager.getCurrentTheme();
411
+ const builtins = ThemeManager.getBuiltinThemes();
412
+ return builtins.includes(current) ? ThemeManager.getThemeClass(current) : 'theme-custom';
413
+ }
414
+
415
+ private documentTitle(document: vscode.TextDocument): string {
416
+ return path.basename(document.fileName).replace(/\.md$/i, '');
417
+ }
418
+
419
+ /**
420
+ * 把当前文档渲染成幻灯片舞台推给 WebView。
421
+ * `withCss` 只在切模式/换主题时为真,逐键更新的消息里不再重复下发样式表。
422
+ * `themeName` 显式传入主题(换主题场景):配置可能被工作区设置遮蔽,
423
+ * 重读 getCurrentTheme() 会拿到旧值,deck 就会合回原主题。
424
+ */
425
+ private async pushSlides(withCss: boolean, themeName?: string): Promise<void> {
426
+ if (!this.panel || !this.currentUri) return;
427
+ try {
428
+ const document = await vscode.workspace.openTextDocument(this.currentUri);
429
+ const stage = renderDeckStage(document.getText(), this.documentTitle(document), 'flow');
430
+ const html = rewriteImageSources(stage.html, path.dirname(document.fileName));
431
+ const payload: Record<string, unknown> = {
432
+ type: 'slides',
433
+ html,
434
+ pageCount: stage.pageCount,
435
+ };
436
+ if (withCss) {
437
+ const theme = themeName ?? ThemeManager.getCurrentTheme();
438
+ payload.css = composeDeckCss(ThemeManager.loadThemeCSS(theme), ThemeManager.loadSlidesCSS());
439
+ payload.bodyClass = this.themeBodyClass(theme);
440
+ }
441
+ this.panel.webview.postMessage(payload);
442
+ } catch (e) {
443
+ console.error('[ColaView] pushSlides failed:', e);
444
+ }
445
+ }
446
+
447
+ /** 当前预览/活动编辑器对应的 Markdown 文档。 */
448
+ private async currentMarkdownDocument(): Promise<vscode.TextDocument | null> {
449
+ if (this.currentUri) {
450
+ try {
451
+ return await vscode.workspace.openTextDocument(this.currentUri);
452
+ } catch {
453
+ /* 落回活动编辑器 */
454
+ }
455
+ }
456
+ const editor = vscode.window.activeTextEditor;
457
+ return editor && editor.document.languageId === 'markdown' ? editor.document : null;
458
+ }
459
+
460
+ /** 生成自包含的幻灯片文档(打印=每页一张纸;放映=一次一页 + 全屏交互)。 */
461
+ private buildSlidesDocument(document: vscode.TextDocument, mode: 'print' | 'present'): string {
462
+ const html = renderSlidesDocument({
463
+ title: this.documentTitle(document),
464
+ themeCss: ThemeManager.loadThemeCSS(ThemeManager.getCurrentTheme()),
465
+ slidesCss: ThemeManager.loadSlidesCSS(),
466
+ markdown: document.getText(),
467
+ bodyClass: this.themeBodyClass(),
468
+ mode,
469
+ });
470
+ const localised = rewriteImageSources(html, path.dirname(document.fileName));
471
+ return mode === 'present' ? decoratePresentDocument(localised) : localised;
472
+ }
473
+
474
+ /** 导出幻灯片 PDF(每页一张 1920×1080 纸)。 */
475
+ async exportSlidesPDFToFile(): Promise<void> {
476
+ const document = await this.currentMarkdownDocument();
477
+ if (!document) {
478
+ vscode.window.showWarningMessage('No Markdown file is open');
479
+ return;
480
+ }
481
+ try {
482
+ await exportSlidesPDF(document, this.buildSlidesDocument(document, 'print'));
483
+ } catch (e) {
484
+ vscode.window.showErrorMessage(`Slides PDF export failed: ${e instanceof Error ? e.message : String(e)}`);
485
+ }
486
+ }
487
+
488
+ /** 导出幻灯片 HTML(放映文档:一次一页 + 全屏交互,CSS 全内联)。 */
489
+ async exportSlidesHTMLToFile(): Promise<void> {
490
+ const document = await this.currentMarkdownDocument();
491
+ if (!document) {
492
+ vscode.window.showWarningMessage('No Markdown file is open');
493
+ return;
494
+ }
495
+ try {
496
+ await exportStandaloneHTML(
497
+ document.fileName.replace(/\.md$/i, '.slides.html'),
498
+ this.buildSlidesDocument(document, 'present')
499
+ );
500
+ } catch (e) {
501
+ vscode.window.showErrorMessage(`Slides HTML export failed: ${e instanceof Error ? e.message : String(e)}`);
502
+ }
503
+ }
504
+
505
+ /** 导出原生 PowerPoint(16:9,逐页幻灯片)。 */
506
+ async exportPPTXFile(): Promise<void> {
507
+ const document = await this.currentMarkdownDocument();
508
+ if (!document) {
509
+ vscode.window.showWarningMessage('No Markdown file is open');
510
+ return;
511
+ }
512
+ try {
513
+ const themeCSS = ThemeManager.loadThemeCSS(ThemeManager.getCurrentTheme());
514
+ await exportPPTX(document, document.getText(), {
515
+ accent: ThemeManager.getAccentColor(themeCSS),
516
+ fontBody: ThemeManager.getBodyFontFamily(themeCSS),
517
+ title: this.documentTitle(document),
518
+ });
519
+ } catch (e) {
520
+ vscode.window.showErrorMessage(`PPTX export failed: ${e instanceof Error ? e.message : String(e)}`);
521
+ }
522
+ }
523
+
524
+ /**
525
+ * 全屏演示:幻灯片用自有渲染层的放映文档,文档用 Milkdown 导出的完整 HTML,
526
+ * 两者都交给系统浏览器(WebView 面板拿不到真正的全屏)。
527
+ */
528
+ async handlePresent(mode: PreviewMode): Promise<void> {
529
+ const document = await this.currentMarkdownDocument();
530
+ if (!document) {
531
+ vscode.window.showWarningMessage('No Markdown file is open');
532
+ return;
533
+ }
534
+ try {
535
+ let html: string;
536
+ if (mode === 'slides') {
537
+ html = this.buildSlidesDocument(document, 'present');
538
+ } else {
539
+ if (!this.panel) this.showPreview();
540
+ this.mode = 'document';
541
+ this.pushMode();
542
+ // 让 WebView 先把文档编辑器显示出来,Mermaid / KaTeX 才能量到真实尺寸。
543
+ await new Promise((resolve) => setTimeout(resolve, 150));
544
+ const exported = await this.getExportHTML();
545
+ if (!exported) {
546
+ vscode.window.showWarningMessage('Could not get rendered HTML from preview');
547
+ return;
548
+ }
549
+ html = decoratePresentDocument(exported);
550
+ }
551
+ await openPresentWindow(this.documentTitle(document), html);
552
+ } catch (e) {
553
+ vscode.window.showErrorMessage(`Present failed: ${e instanceof Error ? e.message : String(e)}`);
554
+ }
555
+ }
556
+
557
+ private updatePreview(document: vscode.TextDocument): void {
558
+ if (!this.panel) return;
559
+ const markdown = document.getText();
560
+ const theme = ThemeManager.getCurrentTheme();
561
+ const builtins = ThemeManager.getBuiltinThemes();
562
+ const isCustom = !builtins.includes(theme);
563
+ const customCSS = isCustom ? ThemeManager.loadThemeCSS(theme) : undefined;
564
+ const themeCSS = ThemeManager.loadThemeCSS(theme);
565
+ this.panel.webview.postMessage({
566
+ type: 'update',
567
+ markdown,
568
+ theme,
569
+ customCSS,
570
+ themeCSS,
571
+ });
572
+ if (this.mode === 'slides') void this.pushSlides(false);
573
+ }
574
+
575
+ async getExportHTML(): Promise<string> {
576
+ if (!this.panel) {
577
+ throw new Error('No preview panel is open. Please open a preview first.');
578
+ }
579
+ const html = await new Promise<string>((resolve) => {
580
+ this.exportResolve = resolve;
581
+ const title = this.currentUri
582
+ ? path.basename(this.currentUri.fsPath, '.md')
583
+ : undefined;
584
+ this.panel!.webview.postMessage({ type: 'exportHTML', title });
585
+ setTimeout(() => {
586
+ if (this.exportResolve) {
587
+ this.exportResolve('');
588
+ this.exportResolve = null;
589
+ }
590
+ }, 30000);
591
+ });
592
+ return this.patchExportHTML(html);
593
+ }
594
+
595
+ /**
596
+ * 导出 HTML 后处理:
597
+ * colamd.css 末尾带一条 Electron 桌面版专用的打印规则
598
+ * `@media print { body > :not(#editor-region), ... { display: none !important } }`
599
+ * 它假定打印时 body 下只保留 #editor-region(ColaMD 桌面版结构),而我们的导出
600
+ * HTML 是 <body><article class="colamd-document">,没有 #editor-region ——
601
+ * article 会被整体隐藏,PDF/浏览器打印全部空白(仅剩一页空纸)。
602
+ *
603
+ * 覆盖规则用 :not(#_) 抬高特异性:原规则含 ID(:not(#editor-region) = 1,0,1),
604
+ * 普通 class 选择器(0,1,2)同带 !important 时也输给它;:not(#_) 恒真但贡献
605
+ * ID 特异性,得到 (1,1,2),稳定压制原规则。
606
+ * HTML 导出在浏览器中 Ctrl+P 同样受益。
607
+ */
608
+ private patchExportHTML(html: string): string {
609
+ if (!html) return html;
610
+
611
+ // colamd 导出器把 document.body 的 class 原样复制到导出 HTML 的 <body> 上,
612
+ // 而它收集的主题规则(colamd.css 内置的 body.theme-X 字体/强调色/变量)全部
613
+ // 以 body.theme-X 为作用域 —— body 缺主题类时这些规则整体失配,导出就只剩
614
+ // 浅色默认样式。这里兜底把主题类补到导出 body 上。
615
+ const theme = ThemeManager.getCurrentTheme();
616
+ const isBuiltin = ThemeManager.getBuiltinThemes().includes(theme);
617
+ const themeClass = isBuiltin ? ThemeManager.getThemeClass(theme) : 'theme-custom';
618
+ let patched = html;
619
+ const bodyTagMatch = /<body[^>]*>/i.exec(patched);
620
+ if (bodyTagMatch) {
621
+ const bodyTag = bodyTagMatch[0];
622
+ if (/\sclass="/.test(bodyTag)) {
623
+ if (!new RegExp(`\\s${themeClass}[\\s"]`).test(bodyTag)) {
624
+ patched = patched.replace(bodyTag, bodyTag.replace(/\sclass="/, ` class="${themeClass} `));
625
+ }
626
+ } else {
627
+ patched = patched.replace(bodyTag, bodyTag.replace(/<body/i, `<body class="${themeClass}"`));
628
+ }
629
+ }
630
+
631
+ // 自定义主题的规则不在 colamd.css 里(内置主题的翻译规则是冗余兜底),
632
+ // 翻译成语义选择器后注入到 </head> 前,保证优先级最高。
633
+ // 变量同样要提到 body.theme-X:引擎把内置主题变量写在 body.theme-X(0,1,1)
634
+ // 上,裸 :root(0,1,0)压不住它,导出会退回引擎旧值、和预览对不上。
635
+ const rawThemeCss = translateThemeCssForExport(ThemeManager.loadThemeCSS(theme));
636
+ const themeOverrideCss = rawThemeCss.replace(/:root\b/g, `:root, body.${themeClass}`);
637
+ const THEME_FIX = themeOverrideCss ? `<style>${themeOverrideCss}</style>` : '';
638
+ // colamd.css 里还有一批 body.theme-X .cm-content .cm-md-* 的正文差异化规则
639
+ // (sepia/dark/notion/midnight/writer 等主题的加粗、行内代码、标题配色只存在于
640
+ // 这一层),导出文档的语义化结构无法命中原选择器 —— 抽取并翻译后一并注入,
641
+ // 导出的正文颜色才能跟预览一致。
642
+ const ENGINE_THEME_FIX = `<style>${translateEngineThemeCssForExport(this.loadEngineColamdCss())}</style>`;
643
+ const PRINT_FIX = `<style>@media print { body > article.colamd-document:not(#_) { display: block !important; } }</style>`;
644
+ // 导出文档里 mermaid 块被引擎序列化成不带类名的 `<p><svg class="pele pele-…">…</svg></p>`
645
+ // (实测 block widget 以非 .cm-line 子节点进入序列化,走段落分支,不是
646
+ // `hte('mermaid')` 的 `<div>` 分支)—— .cm-md-mermaid 上的居中、--pele-* 令牌
647
+ // 随之丢掉。所以这里按导出文档的实际结构补一份:<p> 容器补居中与上下留白。
648
+ // 图不铺底色(与 ColaMD-extend 一致:图画在页面底色上,配色按页面色推导)。
649
+ // 图上的缩放控件(.pele-zoom)是编辑器的东西,不是文档内容 —— 导出纸面上藏掉
650
+ // (镜像 colamd-extend print-layout.ts 的修复;Chromium 打印不执行脚本,
651
+ // pele 没机会收回它们,控件会叠在图上进 PDF)。
652
+ const MERMAID_FIX = `<style>
653
+ /* 图表配色不要在这里重新推导:buildExportHTML 已经把预览里 \`.cm-md-mermaid\` 上
654
+ 实际生效的 --pele-* 变量(含自定义主题显式覆盖的值)收进导出文档的 :root,
655
+ 那才是“预览中的配色”。导出端只需要补引擎序列化时丢掉的居中与留白。 */
656
+ .colamd-document .cm-md-mermaid,
657
+ .colamd-document p:has(> svg.pele) {
658
+ padding: 0.8em 0;
659
+ text-align: center;
660
+ }
661
+ .colamd-document svg.pele {
662
+ display: block; margin: 0 auto; max-width: 100%; height: auto;
663
+ }
664
+ .colamd-document .pele-zoom { display: none !important; }
665
+ </style>`;
666
+ // 兜底:导出那一刻文档里没有已渲染的 mermaid 节点(虚拟滚动把它们卸载了)时,
667
+ // 引擎收集不到 --pele-*,SVG 只能落回 pele 的浅色兜底色 —— 深色主题下整张图
668
+ // 会明显偏离预览。仅在 :root 确实缺这组令牌时按引擎同一份公式补一次;
669
+ // 已有运行时值的场景一律不动,避免覆盖预览里的真实配色。
670
+ const PELE_TOKEN_FALLBACK = /:root\s*\{[^}]*--pele-bg\s*:/i.test(patched)
671
+ ? ''
672
+ : `<style>:root {
673
+ --pele-bg: var(--bg-color);
674
+ --pele-fg: var(--text-color);
675
+ --pele-muted: color-mix(in srgb, var(--text-color) 70%, var(--bg-color));
676
+ --pele-line: var(--text-color);
677
+ --pele-surface: color-mix(in srgb, var(--text-color) 18%, var(--bg-color));
678
+ --pele-surface-alt: color-mix(in srgb, var(--text-color) 28%, var(--bg-color));
679
+ --pele-border: color-mix(in srgb, var(--text-color) 45%, var(--bg-color));
680
+ --pele-accent: var(--link-color);
681
+ --pele-radius: 6px;
682
+ }</style>`;
683
+ return patched.replace('</head>', PRINT_FIX + '\n' + MERMAID_FIX + '\n' + PELE_TOKEN_FALLBACK + '\n' + ENGINE_THEME_FIX + '\n' + THEME_FIX + '\n</head>');
684
+ }
685
+
686
+ /**
687
+ * 读取引擎自带的 colamd.css(与 WebView 加载的是同一份),供导出侧抽取主题规则。
688
+ */
689
+ private loadEngineColamdCss(): string {
690
+ const outDir = path.join(this.context.extensionPath, 'out', 'preview', 'webview');
691
+ const srcDir = path.join(this.context.extensionPath, 'src', 'preview', 'webview');
692
+ const webviewDir = fs.existsSync(outDir) ? outDir : srcDir;
693
+ try {
694
+ return fs.readFileSync(path.join(webviewDir, 'colamd.css'), 'utf-8');
695
+ } catch {
696
+ return '';
697
+ }
698
+ }
699
+
700
+ sendTheme(theme: string): void {
701
+ if (!this.panel) return;
702
+ this.panel.webview.postMessage({ type: 'updateTheme', theme });
703
+ }
704
+
705
+ switchThemeFromCommand(name: string): void {
706
+ if (!this.panel) return;
707
+ const builtins = ThemeManager.getBuiltinThemes();
708
+ const isCustom = !builtins.includes(name);
709
+ const customCSS = isCustom ? ThemeManager.loadThemeCSS(name) : undefined;
710
+ const themeCSS = ThemeManager.loadThemeCSS(name);
711
+ this.panel.webview.postMessage({ type: 'updateTheme', theme: name, customCSS, themeCSS });
712
+ const list = ThemeManager.getThemeList();
713
+ this.panel.webview.postMessage({ type: 'themeList', ...list });
714
+ if (this.mode === 'slides') void this.pushSlides(true, name);
715
+ }
716
+
717
+ refreshThemeList(): void {
718
+ if (!this.panel) return;
719
+ const list = ThemeManager.getThemeList();
720
+ this.panel.webview.postMessage({ type: 'themeList', ...list });
721
+ }
722
+
723
+ private handleScrollSync(msg: { scrollPercent: number }): void {
724
+ if (!this.isScrollSyncEnabled()) { return; }
725
+
726
+ const scrollPercent = msg.scrollPercent;
727
+ const editor = vscode.window.activeTextEditor;
728
+ if (!editor || editor.document.uri.toString() !== this.currentUri?.toString()) {
729
+ return;
730
+ }
731
+
732
+ const totalLines = editor.document.lineCount;
733
+ const targetLine = Math.floor(scrollPercent * (totalLines - 1));
734
+
735
+ this.editorScrollDelay = Date.now() + 500;
736
+
737
+ const range = new vscode.Range(targetLine, 0, targetLine + 1, 0);
738
+ editor.revealRange(range, vscode.TextEditorRevealType.AtTop);
739
+ }
740
+
741
+ private buildWebViewHTML(): string {
742
+ const outDir = path.join(this.context.extensionPath, 'out', 'preview', 'webview');
743
+ const srcDir = path.join(this.context.extensionPath, 'src', 'preview', 'webview');
744
+ const webviewDir = fs.existsSync(outDir) ? outDir : srcDir;
745
+
746
+ const appJsPath = vscode.Uri.file(path.join(webviewDir, 'app.js'));
747
+ const appJsUri = this.panel!.webview.asWebviewUri(appJsPath);
748
+
749
+ const nonce = getNonce();
750
+
751
+ const indexPath = path.join(webviewDir, 'index.html');
752
+ let html = fs.readFileSync(indexPath, 'utf-8');
753
+
754
+ html = html.replace(
755
+ /<meta http-equiv="Content-Security-Policy"[^>]*>/,
756
+ `<meta http-equiv="Content-Security-Policy" content="default-src 'none'; style-src 'unsafe-inline' https://fonts.googleapis.com vscode-webview-resource:; script-src 'nonce-${nonce}' vscode-webview-resource:; font-src https://fonts.gstatic.com vscode-webview-resource: data:; img-src file: data: https: vscode-webview-resource:; connect-src https: vscode-webview-resource:;">`
757
+ );
758
+
759
+ // colamd.css 必须内联为 <style>,不能用 <link>:
760
+ // 跨源 <link> 的 cssRules 对 CSSOM 不可访问(SecurityError),buildExportHTML 的
761
+ // collectExportStyles() 会静默丢掉全部渲染样式(1.43MB → 15KB),导出的 HTML/PDF
762
+ // 就没有排版和 KaTeX 字体了。内联样式对 CSSOM 完全可读,导出管线才能完整带走样式。
763
+ const colamdCss = fs.readFileSync(path.join(webviewDir, 'colamd.css'), 'utf-8')
764
+ .replace(/<\/style/gi, '<\\/style') // 防 css 内容意外闭合 style 标签
765
+ // 剥离 ColaMD 桌面版打印隐藏规则,从源头避免导出 HTML/PDF 里 article 被 display:none
766
+ .replace(/@media\s*print\s*\{[^}]*\}/gi, (m) => m.includes('#editor-region') ? '' : m);
767
+ html = html.replace(
768
+ /<link rel="stylesheet" href="colamd\.css" id="colamd-css">/,
769
+ `<style id="colamd-css">${colamdCss}</style>`
770
+ );
771
+
772
+ html = html.replace(
773
+ '<script src="app.js"></script>',
774
+ `<script nonce="${nonce}" src="${appJsUri}"></script>`
775
+ );
776
+
777
+ return html;
778
+ }
779
+
780
+ dispose(): void {
781
+ this.panel?.dispose();
782
+ this.disposables.forEach(d => d.dispose());
783
+ }
542
784
  }