vscode-colaview 0.3.3 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/.vscode/settings.json +1 -1
  2. package/CHANGELOG.md +20 -4
  3. package/README.md +310 -286
  4. package/README_CN.md +310 -286
  5. package/RELEASE_NOTES.md +36 -4
  6. package/esbuild.js +2 -0
  7. package/package.json +58 -19
  8. package/package.nls.json +14 -0
  9. package/package.nls.zh-cn.json +14 -0
  10. package/src/commands/commands.ts +48 -0
  11. package/src/docx/docx-builder.ts +241 -0
  12. package/src/export/docx-exporter.ts +961 -961
  13. package/src/export/html-exporter.ts +8 -2
  14. package/src/export/pdf-exporter.ts +65 -0
  15. package/src/export/pptx-exporter.ts +63 -0
  16. package/src/export/render-export-images.ts +386 -386
  17. package/src/export/theme-style.ts +195 -195
  18. package/src/pptx/pptx-builder.ts +249 -0
  19. package/src/pptx/zip.ts +158 -0
  20. package/src/present/presenter.ts +64 -0
  21. package/src/preview/preview-manager.ts +783 -541
  22. package/src/preview/webview/app.ts +588 -370
  23. package/src/preview/webview/index.html +167 -146
  24. package/src/slides/deck.ts +397 -0
  25. package/src/slides/markdown.ts +393 -0
  26. package/src/slides/render.ts +484 -0
  27. package/src/slides/slides.css +1082 -0
  28. package/src/themes/built-in/bear.css +89 -38
  29. package/src/themes/built-in/dark.css +87 -28
  30. package/src/themes/built-in/dracula.css +93 -34
  31. package/src/themes/built-in/elegant.css +109 -45
  32. package/src/themes/built-in/gruvbox.css +97 -38
  33. package/src/themes/built-in/light.css +80 -20
  34. package/src/themes/built-in/midnight.css +93 -35
  35. package/src/themes/built-in/nord.css +93 -34
  36. package/src/themes/built-in/notion.css +98 -46
  37. package/src/themes/built-in/sepia.css +99 -44
  38. package/src/themes/built-in/solarized-dark.css +94 -35
  39. package/src/themes/built-in/writer.css +99 -52
  40. package/src/themes/theme-manager.ts +207 -180
  41. package/src/types/colamd-renderer.d.ts +47 -47
@@ -1,370 +1,588 @@
1
- /// <reference lib="dom" />
2
- /**
3
- * ColaView MD — WebView runtime
4
- * CodeMirror 6 based ColaMD editor in read-only mode + right-click context menu.
5
- * @bytechain.cn/colamd@2.7.9 适配
6
- */
7
- import { createColaMDEditor, type ColaMDRendererHandle } from '@bytechain.cn/colamd/renderer';
8
-
9
- // @ts-ignore — VSCode WebView API
10
- const vscode = acquireVsCodeApi();
11
-
12
- let handle: ColaMDRendererHandle | null = null;
13
- let currentMarkdown = '';
14
- let currentTheme = 'elegant';
15
- let themeListData: { builtins: string[]; customs: string[]; current: string } | null = null;
16
- let scrollDebounceTimer: number | null = null;
17
- let receivedScrollFromEditor = false;
18
-
19
- function getScrollContainer(): HTMLElement | null {
20
- // CodeMirror 6 把滚动放在 .cm-scroller 上,#editor 本身不动
21
- return document.querySelector<HTMLElement>('.cm-scroller');
22
- }
23
-
24
- function setupScrollSync(): void {
25
- const scroller = getScrollContainer();
26
- if (!scroller) return;
27
-
28
- scroller.addEventListener('scroll', (e) => {
29
- const target = e.target as HTMLElement;
30
- if (scrollDebounceTimer) clearTimeout(scrollDebounceTimer);
31
-
32
- scrollDebounceTimer = window.setTimeout(() => {
33
- if (receivedScrollFromEditor) {
34
- receivedScrollFromEditor = false;
35
- return;
36
- }
37
-
38
- const scrollPercent = target.scrollTop / (target.scrollHeight - target.clientHeight);
39
- vscode.postMessage({
40
- type: 'scrollSync',
41
- scrollPercent: Math.max(0, Math.min(1, scrollPercent)),
42
- });
43
- }, 50);
44
- });
45
- }
46
-
47
- function scrollToPercent(percent: number): void {
48
- const scroller = getScrollContainer();
49
- if (!scroller || !handle) return;
50
-
51
- receivedScrollFromEditor = true;
52
-
53
- const maxScroll = scroller.scrollHeight - scroller.clientHeight;
54
- const targetScrollTop = Math.max(0, Math.min(percent * maxScroll, maxScroll));
55
-
56
- scroller.scrollTo({
57
- top: targetScrollTop,
58
- behavior: 'smooth'
59
- });
60
- }
61
-
62
- function scrollToLine(line: number, totalLines: number, topRatio: number = 0.3): void {
63
- const scroller = getScrollContainer();
64
- if (!scroller || !handle) return;
65
-
66
- receivedScrollFromEditor = true;
67
-
68
- const contentEl = document.querySelector<HTMLElement>('#editor .cm-content');
69
- if (!contentEl) {
70
- const scrollPercent = totalLines > 1 ? line / (totalLines - 1) : 0;
71
- scrollToPercent(scrollPercent);
72
- return;
73
- }
74
-
75
- // CM6 只渲染视口内的内容,所以只能用比例估算
76
- const scrollPercent = totalLines > 1 ? line / (totalLines - 1) : 0;
77
- const maxScroll = scroller.scrollHeight - scroller.clientHeight;
78
- const targetScrollTop = Math.max(0, Math.min(scrollPercent * maxScroll, maxScroll));
79
-
80
- scroller.scrollTo({
81
- top: targetScrollTop,
82
- behavior: 'smooth'
83
- });
84
- }
85
-
86
- function injectThemeCSS(css: string | undefined, themeName: string, isCustom: boolean): void {
87
- if (!css) return;
88
- let el = document.getElementById('colaview-theme-css');
89
- if (!el) {
90
- el = document.createElement('style');
91
- el.id = 'colaview-theme-css';
92
- document.head.appendChild(el);
93
- }
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}`);
99
- }
100
-
101
- /**
102
- * 确保 body 挂上主题类。colamd 的 buildExportHTML 会把 document.body 的 class
103
- * 原样复制到导出 HTML 的 <body>,而它收集的主题规则全部以 body.theme-X 为作用域
104
- * (字体、强调色、主题变量)。预览本身靠注入的 :root 变量 + #editor 规则就能生效,
105
- * 不依赖 body 类 —— 但导出不补上这个类就会整体丢格式。
106
- */
107
- function ensureBodyThemeClass(): void {
108
- const builtins = themeListData?.builtins ?? [];
109
- if (builtins.length > 0 && !builtins.includes(currentTheme)) {
110
- document.body.classList.add('theme-custom');
111
- return;
112
- }
113
- // 内置主题:与 colamd 内部映射一致(theme-<name>)
114
- document.body.classList.add(`theme-${currentTheme}`);
115
- }
116
-
117
- window.addEventListener('message', async (event: MessageEvent) => {
118
- const data = event.data;
119
- switch (data.type) {
120
- case 'init': {
121
- try {
122
- currentTheme = data.theme || 'elegant';
123
- injectThemeCSS(data.themeCSS, currentTheme, !!(data.customCSS && data.theme));
124
-
125
- // 2.7.9 API: 先创建编辑器(options 中不含 theme)
126
- handle = await createColaMDEditor({
127
- rootId: 'editor',
128
- editable: false,
129
- });
130
-
131
- // 然后应用主题
132
- if (data.customCSS && data.theme) {
133
- handle.applyTheme('custom:' + data.theme, data.customCSS);
134
- } else {
135
- handle.applyTheme(currentTheme);
136
- }
137
- ensureBodyThemeClass();
138
-
139
- // 最后设置 markdown
140
- if (data.markdown) {
141
- handle.setMarkdown(data.markdown);
142
- currentMarkdown = data.markdown;
143
- }
144
-
145
- setupScrollSync();
146
- } catch (e) {
147
- console.error('[ColaView] init failed:', e);
148
- vscode.postMessage({ type: 'error', message: String(e) });
149
- }
150
- break;
151
- }
152
- case 'update': {
153
- if (!handle) return;
154
- if (data.markdown !== undefined && data.markdown !== currentMarkdown) {
155
- handle.setMarkdown(data.markdown);
156
- currentMarkdown = data.markdown;
157
- }
158
- if (data.theme) {
159
- currentTheme = data.theme;
160
- injectThemeCSS(data.themeCSS, data.theme, !!data.customCSS);
161
- if (data.customCSS) {
162
- handle.applyTheme('custom:' + data.theme, data.customCSS);
163
- } else {
164
- handle.applyTheme(data.theme);
165
- }
166
- ensureBodyThemeClass();
167
- }
168
- break;
169
- }
170
- case 'exportHTML': {
171
- if (!handle) {
172
- vscode.postMessage({ type: 'exportHTMLResult', html: '' });
173
- return;
174
- }
175
- try {
176
- ensureBodyThemeClass();
177
- const html = await handle.buildExportHTML({
178
- title: data.title || document.title || 'Document',
179
- });
180
- vscode.postMessage({ type: 'exportHTMLResult', html });
181
- } catch (e) {
182
- console.error('[ColaView] exportHTML failed:', e);
183
- vscode.postMessage({ type: 'exportHTMLResult', html: '', error: String(e) });
184
- }
185
- break;
186
- }
187
- case 'updateTheme': {
188
- if (!handle || !data.theme) return;
189
- currentTheme = data.theme;
190
- injectThemeCSS(data.themeCSS, data.theme, !!data.customCSS);
191
- if (data.customCSS) {
192
- handle.applyTheme('custom:' + data.theme, data.customCSS);
193
- } else {
194
- handle.applyTheme(data.theme);
195
- }
196
- ensureBodyThemeClass();
197
- break;
198
- }
199
- case 'applyCustomTheme': {
200
- if (!data.css || !handle) return;
201
- const themeName = data.name || currentTheme;
202
- handle.applyTheme('custom:' + themeName, data.css);
203
- break;
204
- }
205
- case 'themeList': {
206
- themeListData = {
207
- builtins: data.builtins || [],
208
- customs: data.customs || [],
209
- current: data.current || currentTheme,
210
- };
211
- refreshThemeSubmenu();
212
- break;
213
- }
214
- case 'editorScroll': {
215
- if (data.scrollPercent !== undefined) {
216
- scrollToPercent(data.scrollPercent);
217
- } else if (data.line !== undefined) {
218
- scrollToLine(data.line, data.totalLines || 100, data.topRatio || 0.3);
219
- }
220
- break;
221
- }
222
- }
223
- });
224
-
225
- // ── Context Menu ──────────────────────────────────────────────
226
- let menuEl: HTMLElement | null = null;
227
- let themeSubmenuEl: HTMLElement | null = null;
228
-
229
- function closeMenu(): void {
230
- if (menuEl) {
231
- menuEl.remove();
232
- menuEl = null;
233
- themeSubmenuEl = null;
234
- }
235
- document.removeEventListener('click', closeMenu);
236
- document.removeEventListener('contextmenu', closeMenu);
237
- }
238
-
239
- function createMenuItem(label: string, onClick: () => void): HTMLElement {
240
- const item = document.createElement('div');
241
- item.className = 'ctx-menu-item';
242
- item.textContent = label;
243
- item.addEventListener('click', (e) => {
244
- e.stopPropagation();
245
- closeMenu();
246
- onClick();
247
- });
248
- return item;
249
- }
250
-
251
- function createMenuSeparator(): HTMLElement {
252
- const sep = document.createElement('div');
253
- sep.className = 'ctx-menu-separator';
254
- return sep;
255
- }
256
-
257
- function buildThemeSubmenu(): HTMLElement {
258
- const submenu = document.createElement('div');
259
- submenu.className = 'ctx-menu-submenu';
260
- themeSubmenuEl = submenu;
261
-
262
- if (!themeListData) {
263
- vscode.postMessage({ type: 'requestThemeList' });
264
- const loading = document.createElement('div');
265
- loading.className = 'ctx-menu-item ctx-menu-disabled';
266
- loading.textContent = 'Loading...';
267
- submenu.appendChild(loading);
268
- return submenu;
269
- }
270
-
271
- for (const name of themeListData.builtins) {
272
- const item = document.createElement('div');
273
- item.className = 'ctx-menu-item' + (name === themeListData.current ? ' ctx-menu-active' : '');
274
- item.textContent = name.charAt(0).toUpperCase() + name.slice(1).replace(/-/g, ' ');
275
- item.addEventListener('click', (e) => {
276
- e.stopPropagation();
277
- if (themeListData) themeListData.current = name;
278
- closeMenu();
279
- vscode.postMessage({ type: 'switchTheme', name });
280
- });
281
- submenu.appendChild(item);
282
- }
283
-
284
- if (themeListData.customs.length > 0) {
285
- const sep = document.createElement('div');
286
- sep.className = 'ctx-menu-separator';
287
- submenu.appendChild(sep);
288
-
289
- for (const name of themeListData.customs) {
290
- const item = document.createElement('div');
291
- item.className = 'ctx-menu-item' + (name === themeListData.current ? ' ctx-menu-active' : '');
292
- item.textContent = name;
293
- item.addEventListener('click', (e) => {
294
- e.stopPropagation();
295
- if (themeListData) themeListData.current = name;
296
- closeMenu();
297
- vscode.postMessage({ type: 'switchTheme', name });
298
- });
299
- submenu.appendChild(item);
300
- }
301
- }
302
-
303
- return submenu;
304
- }
305
-
306
- function refreshThemeSubmenu(): void {
307
- if (!menuEl || !themeSubmenuEl) return;
308
- const parent = themeSubmenuEl.parentElement;
309
- if (!parent) return;
310
- const newSubmenu = buildThemeSubmenu();
311
- parent.replaceChild(newSubmenu, themeSubmenuEl);
312
- }
313
-
314
- function showMenu(x: number, y: number): void {
315
- closeMenu();
316
-
317
- const menu = document.createElement('div');
318
- menu.className = 'ctx-menu';
319
- menu.style.left = x + 'px';
320
- menu.style.top = y + 'px';
321
- menuEl = menu;
322
-
323
- menu.appendChild(createMenuItem('Export HTML', () => {
324
- vscode.postMessage({ type: 'requestExportHTML' });
325
- }));
326
-
327
- menu.appendChild(createMenuItem('Export PDF', () => {
328
- vscode.postMessage({ type: 'requestExportPDF' });
329
- }));
330
-
331
- menu.appendChild(createMenuItem('Export Word', () => {
332
- vscode.postMessage({ type: 'requestExportWord' });
333
- }));
334
-
335
- menu.appendChild(createMenuSeparator());
336
-
337
- const themeItem = document.createElement('div');
338
- themeItem.className = 'ctx-menu-item ctx-menu-has-submenu';
339
- themeItem.textContent = 'Theme';
340
- themeItem.appendChild(buildThemeSubmenu());
341
- menu.appendChild(themeItem);
342
-
343
- menu.appendChild(createMenuSeparator());
344
-
345
- menu.appendChild(createMenuItem('Import Theme...', () => {
346
- vscode.postMessage({ type: 'requestImportTheme' });
347
- }));
348
-
349
- document.body.appendChild(menu);
350
-
351
- const rect = menu.getBoundingClientRect();
352
- if (rect.right > window.innerWidth) {
353
- menu.style.left = (x - rect.width) + 'px';
354
- }
355
- if (rect.bottom > window.innerHeight) {
356
- menu.style.top = (y - rect.height) + 'px';
357
- }
358
-
359
- setTimeout(() => {
360
- document.addEventListener('click', closeMenu);
361
- document.addEventListener('contextmenu', closeMenu);
362
- }, 0);
363
- }
364
-
365
- document.addEventListener('contextmenu', (e) => {
366
- e.preventDefault();
367
- showMenu(e.clientX, e.clientY);
368
- });
369
-
370
- vscode.postMessage({ type: 'ready' });
1
+ /// <reference lib="dom" />
2
+ /**
3
+ * ColaView MD — WebView runtime
4
+ * CodeMirror 6 based ColaMD editor in read-only mode + right-click context menu.
5
+ * @bytechain.cn/colamd@2.7.9 适配
6
+ */
7
+ import { createColaMDEditor, type ColaMDRendererHandle } from '@bytechain.cn/colamd/renderer';
8
+
9
+ // @ts-ignore — VSCode WebView API
10
+ const vscode = acquireVsCodeApi();
11
+
12
+ let handle: ColaMDRendererHandle | null = null;
13
+ let currentMarkdown = '';
14
+ let currentTheme = 'elegant';
15
+ let themeListData: { builtins: string[]; customs: string[]; current: string } | null = null;
16
+ let scrollDebounceTimer: number | null = null;
17
+ let receivedScrollFromEditor = false;
18
+ /** 当前预览模式:整篇文档(CodeMirror)/ 幻灯片(扩展侧渲染好的舞台 HTML)。 */
19
+ let mode: 'document' | 'slides' = 'document';
20
+
21
+ /** 右键菜单文案(扩展宿主按 VS Code 显示语言下发,缺省英文)。 */
22
+ interface MenuLabels {
23
+ present: string;
24
+ exportPdf: string;
25
+ exportHtml: string;
26
+ exportWord: string;
27
+ exportPptx: string;
28
+ theme: string;
29
+ importTheme: string;
30
+ loading: string;
31
+ groupLight: string;
32
+ groupDark: string;
33
+ groupCustom: string;
34
+ }
35
+
36
+ let labels: MenuLabels = {
37
+ present: 'Present (Fullscreen)',
38
+ exportPdf: 'Export to PDF',
39
+ exportHtml: 'Export to HTML',
40
+ exportWord: 'Export to Word',
41
+ exportPptx: 'Export to PPTX',
42
+ theme: 'Theme',
43
+ importTheme: 'Import Theme…',
44
+ loading: 'Loading…',
45
+ groupLight: 'Built-in · Light',
46
+ groupDark: 'Built-in · Dark',
47
+ groupCustom: 'Custom',
48
+ };
49
+
50
+ /** 暗色内置主题集合,用于主题子菜单分组(亮色 = 内置全集 - 暗色)。 */
51
+ const DARK_BUILTIN_THEMES = new Set(['dark', 'solarized-dark', 'nord', 'gruvbox', 'dracula', 'midnight']);
52
+
53
+ /** 幻灯片样式表只注入一次(几十 KB,逐键更新时不重复下发)。 */
54
+ function injectSlidesCss(css: string | undefined): void {
55
+ if (!css) return;
56
+ let el = document.getElementById('colaview-slides-css');
57
+ if (!el) {
58
+ el = document.createElement('style');
59
+ el.id = 'colaview-slides-css';
60
+ document.head.appendChild(el);
61
+ }
62
+ el.textContent = css;
63
+ }
64
+
65
+ /** 整副牌按面板宽度整体缩放(纸面固定 1920×1080,缩放只改视觉尺寸)。 */
66
+ function fitSlidesStage(): void {
67
+ const host = document.getElementById('slides-host');
68
+ const stage = host?.querySelector<HTMLElement>('.ct-stage');
69
+ if (!host || !stage) return;
70
+ const available = host.clientWidth || window.innerWidth;
71
+ const scale = Math.min(1, Math.max(0.1, (available - 32) / 1920));
72
+ stage.style.setProperty('--deck-scale', scale.toFixed(4));
73
+ }
74
+
75
+ function renderSlides(html: string): void {
76
+ const host = document.getElementById('slides-host');
77
+ if (!host) return;
78
+ host.innerHTML = html;
79
+ fitSlidesStage();
80
+ }
81
+
82
+ function setMode(next: 'document' | 'slides'): void {
83
+ mode = next;
84
+ document.body.classList.toggle('slides-mode', mode === 'slides');
85
+ if (mode === 'slides') {
86
+ fitSlidesStage();
87
+ window.scrollTo(0, 0);
88
+ }
89
+ }
90
+
91
+ window.addEventListener('resize', () => {
92
+ if (mode === 'slides') fitSlidesStage();
93
+ });
94
+
95
+ function getScrollContainer(): HTMLElement | null {
96
+ // CodeMirror 6 把滚动放在 .cm-scroller 上,#editor 本身不动
97
+ return document.querySelector<HTMLElement>('.cm-scroller');
98
+ }
99
+
100
+ function setupScrollSync(): void {
101
+ const scroller = getScrollContainer();
102
+ if (!scroller) return;
103
+
104
+ scroller.addEventListener('scroll', (e) => {
105
+ const target = e.target as HTMLElement;
106
+ if (scrollDebounceTimer) clearTimeout(scrollDebounceTimer);
107
+
108
+ scrollDebounceTimer = window.setTimeout(() => {
109
+ if (receivedScrollFromEditor) {
110
+ receivedScrollFromEditor = false;
111
+ return;
112
+ }
113
+
114
+ const scrollPercent = target.scrollTop / (target.scrollHeight - target.clientHeight);
115
+ vscode.postMessage({
116
+ type: 'scrollSync',
117
+ scrollPercent: Math.max(0, Math.min(1, scrollPercent)),
118
+ });
119
+ }, 50);
120
+ });
121
+ }
122
+
123
+ function scrollToPercent(percent: number): void {
124
+ const scroller = getScrollContainer();
125
+ if (!scroller || !handle) return;
126
+
127
+ receivedScrollFromEditor = true;
128
+
129
+ const maxScroll = scroller.scrollHeight - scroller.clientHeight;
130
+ const targetScrollTop = Math.max(0, Math.min(percent * maxScroll, maxScroll));
131
+
132
+ scroller.scrollTo({
133
+ top: targetScrollTop,
134
+ behavior: 'smooth'
135
+ });
136
+ }
137
+
138
+ function scrollToLine(line: number, totalLines: number, topRatio: number = 0.3): void {
139
+ const scroller = getScrollContainer();
140
+ if (!scroller || !handle) return;
141
+
142
+ receivedScrollFromEditor = true;
143
+
144
+ const contentEl = document.querySelector<HTMLElement>('#editor .cm-content');
145
+ if (!contentEl) {
146
+ const scrollPercent = totalLines > 1 ? line / (totalLines - 1) : 0;
147
+ scrollToPercent(scrollPercent);
148
+ return;
149
+ }
150
+
151
+ // CM6 只渲染视口内的内容,所以只能用比例估算
152
+ const scrollPercent = totalLines > 1 ? line / (totalLines - 1) : 0;
153
+ const maxScroll = scroller.scrollHeight - scroller.clientHeight;
154
+ const targetScrollTop = Math.max(0, Math.min(scrollPercent * maxScroll, maxScroll));
155
+
156
+ scroller.scrollTo({
157
+ top: targetScrollTop,
158
+ behavior: 'smooth'
159
+ });
160
+ }
161
+
162
+ function injectThemeCSS(css: string | undefined, themeName: string, isCustom: boolean): void {
163
+ if (!css) return;
164
+ let el = document.getElementById('colaview-theme-css');
165
+ if (!el) {
166
+ el = document.createElement('style');
167
+ el.id = 'colaview-theme-css';
168
+ document.head.appendChild(el);
169
+ }
170
+ // 主题文件的变量写在 :root 上,而引擎把同一批变量写在 body.theme-X 上
171
+ // (特异性 0,1,1 > 0,1,0),直接注入 :root 会被引擎盖掉。这里把选择器
172
+ // 提升到 body.theme-X:与引擎同特异性且后注入,主题文件里的新值才生效。
173
+ const scope = isCustom ? 'body.theme-custom' : `body.theme-${themeName}`;
174
+ el.textContent = css.replace(/:root\b/g, `:root, ${scope}`);
175
+ ensureDshBaseCss();
176
+ }
177
+
178
+ /**
179
+ * DSH(DeepSeek Harness)插件渲染对齐层。
180
+ *
181
+ * DSH 的文档渲染 = 主题令牌(:root)+ BASE_CSS 基础版式,且 BASE_CSS 后注入、
182
+ * 同特异性下覆盖主题元素规则。这里把 BASE_CSS 翻译到编辑器 DOM(.cm-content
183
+ * + .cm-md-*),并用 `:where()` 降权,形成三级级联:
184
+ *
185
+ * 引擎默认 < 本层(:where,令牌兜底) < 主题文件个性规则
186
+ *
187
+ * 令牌与 DSH BASE_CSS 完全同名同兜底值:--font-body / --editor-font-size /
188
+ * --leading-body(1.78) / --editor-column-width(46rem) / 字距 0.01em /
189
+ * --type-* 标题度量 / --seed-emphasis / --layout-radius 等。
190
+ */
191
+ const DSH_BASE_CSS = `
192
+ #editor :where(.cm-content) {
193
+ font-size: var(--editor-font-size, 16px);
194
+ line-height: var(--leading-body, 1.78);
195
+ letter-spacing: 0.01em;
196
+ width: min(100%, calc(var(--editor-column-width, 46rem) + 4.4rem));
197
+ padding: 3.4rem 2.2rem 6rem;
198
+ }
199
+ #editor :where(.cm-content) :where(.cm-md-atxheading1, .cm-md-atxheading2, .cm-md-atxheading3, .cm-md-atxheading4, .cm-md-atxheading5, .cm-md-atxheading6) {
200
+ font-weight: var(--weight-display, 700);
201
+ line-height: var(--leading-display, 1.3);
202
+ letter-spacing: var(--tracking-display, -0.01em);
203
+ border-bottom: none;
204
+ }
205
+ #editor :where(.cm-content) :where(.cm-md-atxheading1) { font-size: var(--type-display, 2rem); }
206
+ #editor :where(.cm-content) :where(.cm-md-atxheading2) { font-size: var(--type-section, 1.5rem); letter-spacing: var(--tracking-section, 0); }
207
+ #editor :where(.cm-content) :where(.cm-md-atxheading3) { font-size: var(--type-subhead, 1.2rem); font-weight: var(--weight-subhead, 650); letter-spacing: var(--tracking-subhead, 0); }
208
+ #editor :where(.cm-content) :where(.cm-md-atxheading4) { font-size: var(--type-body, 1.05rem); }
209
+ #editor :where(.cm-content) :where(.cm-md-strong) {
210
+ font-weight: var(--weight-body, 700);
211
+ color: var(--seed-emphasis, inherit);
212
+ }
213
+ #editor :where(.cm-content) :where(.cm-md-strike) { color: var(--text-muted, #8a8a8a); }
214
+ #editor :where(.cm-content) :where(.cm-md-highlight) {
215
+ background: var(--highlight-bg, rgba(255, 214, 102, 0.42));
216
+ color: inherit;
217
+ padding: 0 0.15em;
218
+ border-radius: 2px;
219
+ }
220
+ #editor :where(.cm-content) :where(.cm-md-link) {
221
+ color: var(--link-color, #0969da);
222
+ text-decoration: underline;
223
+ text-underline-offset: 0.18em;
224
+ text-decoration-thickness: 1px;
225
+ }
226
+ #editor :where(.cm-content) :where(.cm-md-inlinecode) {
227
+ font-family: var(--font-mono, ui-monospace, SFMono-Regular, Menlo, Consolas, monospace);
228
+ font-size: 0.9em;
229
+ background: var(--code-bg, rgba(0, 0, 0, 0.05));
230
+ padding: 0.15em 0.38em;
231
+ border-radius: var(--layout-radius, 4px);
232
+ }
233
+ #editor :where(.cm-content) :where(.cm-md-codeblock) {
234
+ font-family: var(--font-mono, ui-monospace, SFMono-Regular, Menlo, Consolas, monospace);
235
+ font-size: 0.86em;
236
+ line-height: 1.62;
237
+ background: var(--code-block-bg, #23252b);
238
+ color: var(--code-block-text, #e7e7ea);
239
+ }
240
+ #editor :where(.cm-content) :where(.cm-md-codeblock-first) {
241
+ border-top-left-radius: var(--layout-radius, 8px);
242
+ border-top-right-radius: var(--layout-radius, 8px);
243
+ }
244
+ #editor :where(.cm-content) :where(.cm-md-codeblock-last) {
245
+ border-bottom-left-radius: var(--layout-radius, 8px);
246
+ border-bottom-right-radius: var(--layout-radius, 8px);
247
+ }
248
+ #editor :where(.cm-content) :where(.cm-md-blockquote) {
249
+ color: var(--text-secondary, #555555);
250
+ border-left: 3px solid var(--blockquote-border, var(--seed-accent, #b0401f));
251
+ background: var(--blockquote-bg, transparent);
252
+ }
253
+ #editor :where(.cm-content) :where(.cm-md-listmark) {
254
+ color: var(--layout-list-marker, var(--seed-accent, currentColor));
255
+ }
256
+ #editor :where(.cm-content) :where(.cm-md-hr) {
257
+ border-top: 1px solid var(--border-color, var(--seed-border, #d8d6d2));
258
+ margin: 2.6em 0;
259
+ }
260
+ #editor :where(.cm-content) :where(.cm-md-table-widget) { font-size: 0.94em; }
261
+ #editor :where(.cm-content) :where(.cm-md-table-widget th) {
262
+ background: var(--table-header-bg, var(--seed-panel, #eaeae9));
263
+ font-weight: 650;
264
+ padding: 0.6em 0.8em;
265
+ }
266
+ #editor :where(.cm-content) :where(.cm-md-table-widget td) { padding: 0.58em 0.8em; }
267
+ ::selection { background: var(--selection-bg, rgba(176, 64, 31, 0.18)); }
268
+ `;
269
+
270
+ /** 保证对齐层存在且位于主题样式之后(DSH 语义:后注入者在同特异性下胜出)。 */
271
+ function ensureDshBaseCss(): void {
272
+ let el = document.getElementById('colaview-dsh-base');
273
+ if (!el) {
274
+ el = document.createElement('style');
275
+ el.id = 'colaview-dsh-base';
276
+ el.textContent = DSH_BASE_CSS;
277
+ }
278
+ document.head.appendChild(el);
279
+ }
280
+
281
+ /**
282
+ * 确保 body 挂上主题类。colamd 的 buildExportHTML 会把 document.body 的 class
283
+ * 原样复制到导出 HTML 的 <body>,而它收集的主题规则全部以 body.theme-X 为作用域
284
+ * (字体、强调色、主题变量)。预览本身靠注入的 :root 变量 + #editor 规则就能生效,
285
+ * 不依赖 body 类 —— 但导出不补上这个类就会整体丢格式。
286
+ */
287
+ function ensureBodyThemeClass(): void {
288
+ const builtins = themeListData?.builtins ?? [];
289
+ if (builtins.length > 0 && !builtins.includes(currentTheme)) {
290
+ document.body.classList.add('theme-custom');
291
+ return;
292
+ }
293
+ // 内置主题:与 colamd 内部映射一致(theme-<name>)
294
+ document.body.classList.add(`theme-${currentTheme}`);
295
+ }
296
+
297
+ window.addEventListener('message', async (event: MessageEvent) => {
298
+ const data = event.data;
299
+ switch (data.type) {
300
+ case 'init': {
301
+ try {
302
+ currentTheme = data.theme || 'elegant';
303
+ if (data.labels) labels = { ...labels, ...data.labels };
304
+ injectThemeCSS(data.themeCSS, currentTheme, !!(data.customCSS && data.theme));
305
+
306
+ // 2.7.9 API: 先创建编辑器(options 中不含 theme)
307
+ handle = await createColaMDEditor({
308
+ rootId: 'editor',
309
+ editable: false,
310
+ });
311
+
312
+ // 然后应用主题
313
+ if (data.customCSS && data.theme) {
314
+ handle.applyTheme('custom:' + data.theme, data.customCSS);
315
+ } else {
316
+ handle.applyTheme(currentTheme);
317
+ }
318
+ ensureBodyThemeClass();
319
+
320
+ // 最后设置 markdown
321
+ if (data.markdown) {
322
+ handle.setMarkdown(data.markdown);
323
+ currentMarkdown = data.markdown;
324
+ }
325
+
326
+ setupScrollSync();
327
+ if (data.mode === 'slides') setMode('slides');
328
+ } catch (e) {
329
+ console.error('[ColaView] init failed:', e);
330
+ vscode.postMessage({ type: 'error', message: String(e) });
331
+ }
332
+ break;
333
+ }
334
+ case 'mode': {
335
+ setMode(data.mode === 'slides' ? 'slides' : 'document');
336
+ break;
337
+ }
338
+ case 'slides': {
339
+ injectSlidesCss(data.css);
340
+ if (data.bodyClass) {
341
+ document.body.classList
342
+ .forEach((cls) => { if (cls.startsWith('theme-')) document.body.classList.remove(cls); });
343
+ document.body.classList.add(data.bodyClass);
344
+ }
345
+ setMode('slides');
346
+ renderSlides(data.html || '');
347
+ break;
348
+ }
349
+ case 'update': {
350
+ if (!handle) return;
351
+ if (data.markdown !== undefined && data.markdown !== currentMarkdown) {
352
+ handle.setMarkdown(data.markdown);
353
+ currentMarkdown = data.markdown;
354
+ }
355
+ if (data.theme) {
356
+ currentTheme = data.theme;
357
+ injectThemeCSS(data.themeCSS, data.theme, !!data.customCSS);
358
+ if (data.customCSS) {
359
+ handle.applyTheme('custom:' + data.theme, data.customCSS);
360
+ } else {
361
+ handle.applyTheme(data.theme);
362
+ }
363
+ ensureBodyThemeClass();
364
+ }
365
+ break;
366
+ }
367
+ case 'exportHTML': {
368
+ if (!handle) {
369
+ vscode.postMessage({ type: 'exportHTMLResult', html: '' });
370
+ return;
371
+ }
372
+ try {
373
+ ensureBodyThemeClass();
374
+ const html = await handle.buildExportHTML({
375
+ title: data.title || document.title || 'Document',
376
+ });
377
+ vscode.postMessage({ type: 'exportHTMLResult', html });
378
+ } catch (e) {
379
+ console.error('[ColaView] exportHTML failed:', e);
380
+ vscode.postMessage({ type: 'exportHTMLResult', html: '', error: String(e) });
381
+ }
382
+ break;
383
+ }
384
+ case 'updateTheme': {
385
+ if (!handle || !data.theme) return;
386
+ currentTheme = data.theme;
387
+ injectThemeCSS(data.themeCSS, data.theme, !!data.customCSS);
388
+ if (data.customCSS) {
389
+ handle.applyTheme('custom:' + data.theme, data.customCSS);
390
+ } else {
391
+ handle.applyTheme(data.theme);
392
+ }
393
+ ensureBodyThemeClass();
394
+ break;
395
+ }
396
+ case 'applyCustomTheme': {
397
+ if (!data.css || !handle) return;
398
+ const themeName = data.name || currentTheme;
399
+ handle.applyTheme('custom:' + themeName, data.css);
400
+ break;
401
+ }
402
+ case 'themeList': {
403
+ themeListData = {
404
+ builtins: data.builtins || [],
405
+ customs: data.customs || [],
406
+ current: data.current || currentTheme,
407
+ };
408
+ refreshThemeSubmenu();
409
+ break;
410
+ }
411
+ case 'editorScroll': {
412
+ if (data.scrollPercent !== undefined) {
413
+ scrollToPercent(data.scrollPercent);
414
+ } else if (data.line !== undefined) {
415
+ scrollToLine(data.line, data.totalLines || 100, data.topRatio || 0.3);
416
+ }
417
+ break;
418
+ }
419
+ }
420
+ });
421
+
422
+ // ── Context Menu ──────────────────────────────────────────────
423
+ let menuEl: HTMLElement | null = null;
424
+ let themeSubmenuEl: HTMLElement | null = null;
425
+
426
+ function closeMenu(): void {
427
+ if (menuEl) {
428
+ menuEl.remove();
429
+ menuEl = null;
430
+ themeSubmenuEl = null;
431
+ }
432
+ document.removeEventListener('click', closeMenu);
433
+ document.removeEventListener('contextmenu', closeMenu);
434
+ }
435
+
436
+ function createMenuItem(label: string, onClick: () => void): HTMLElement {
437
+ const item = document.createElement('div');
438
+ item.className = 'ctx-menu-item';
439
+ item.textContent = label;
440
+ item.addEventListener('click', (e) => {
441
+ e.stopPropagation();
442
+ closeMenu();
443
+ onClick();
444
+ });
445
+ return item;
446
+ }
447
+
448
+ function createMenuSeparator(): HTMLElement {
449
+ const sep = document.createElement('div');
450
+ sep.className = 'ctx-menu-separator';
451
+ return sep;
452
+ }
453
+
454
+ function createGroupHeader(label: string): HTMLElement {
455
+ const header = document.createElement('div');
456
+ header.className = 'ctx-menu-group';
457
+ header.textContent = label;
458
+ return header;
459
+ }
460
+
461
+ function createThemeItem(name: string, label: string): HTMLElement {
462
+ const item = document.createElement('div');
463
+ item.className = 'ctx-menu-item' + (themeListData && name === themeListData.current ? ' ctx-menu-active' : '');
464
+ item.textContent = label;
465
+ item.addEventListener('click', (e) => {
466
+ e.stopPropagation();
467
+ if (themeListData) themeListData.current = name;
468
+ closeMenu();
469
+ vscode.postMessage({ type: 'switchTheme', name });
470
+ });
471
+ return item;
472
+ }
473
+
474
+ function buildThemeSubmenu(): HTMLElement {
475
+ const submenu = document.createElement('div');
476
+ submenu.className = 'ctx-menu-submenu';
477
+ themeSubmenuEl = submenu;
478
+
479
+ if (!themeListData) {
480
+ vscode.postMessage({ type: 'requestThemeList' });
481
+ const loading = document.createElement('div');
482
+ loading.className = 'ctx-menu-item ctx-menu-disabled';
483
+ loading.textContent = labels.loading;
484
+ submenu.appendChild(loading);
485
+ return submenu;
486
+ }
487
+
488
+ // 内置主题按亮色/暗色分组,自定义主题单独一组;子菜单限高可滚动,项多时不会超出页面。
489
+ const pretty = (name: string): string => name.charAt(0).toUpperCase() + name.slice(1).replace(/-/g, ' ');
490
+ const lights = themeListData.builtins.filter((n) => !DARK_BUILTIN_THEMES.has(n));
491
+ const darks = themeListData.builtins.filter((n) => DARK_BUILTIN_THEMES.has(n));
492
+
493
+ submenu.appendChild(createGroupHeader(labels.groupLight));
494
+ for (const name of lights) {
495
+ submenu.appendChild(createThemeItem(name, pretty(name)));
496
+ }
497
+
498
+ submenu.appendChild(createGroupHeader(labels.groupDark));
499
+ for (const name of darks) {
500
+ submenu.appendChild(createThemeItem(name, pretty(name)));
501
+ }
502
+
503
+ if (themeListData.customs.length > 0) {
504
+ submenu.appendChild(createGroupHeader(labels.groupCustom));
505
+ for (const name of themeListData.customs) {
506
+ submenu.appendChild(createThemeItem(name, name));
507
+ }
508
+ }
509
+
510
+ return submenu;
511
+ }
512
+
513
+ function refreshThemeSubmenu(): void {
514
+ if (!menuEl || !themeSubmenuEl) return;
515
+ const parent = themeSubmenuEl.parentElement;
516
+ if (!parent) return;
517
+ const newSubmenu = buildThemeSubmenu();
518
+ parent.replaceChild(newSubmenu, themeSubmenuEl);
519
+ }
520
+
521
+ function showMenu(x: number, y: number): void {
522
+ closeMenu();
523
+
524
+ const menu = document.createElement('div');
525
+ menu.className = 'ctx-menu';
526
+ menu.style.left = x + 'px';
527
+ menu.style.top = y + 'px';
528
+ menuEl = menu;
529
+
530
+ // 全屏显示固定排在最前面,文档/幻灯片模式均可放映;导出项按当前模式区分:文档给 PDF/HTML/Word,幻灯片只给 PDF/PPTX。
531
+ menu.appendChild(createMenuItem(labels.present, () => {
532
+ vscode.postMessage({ type: 'requestPresent', mode });
533
+ }));
534
+ menu.appendChild(createMenuSeparator());
535
+
536
+ menu.appendChild(createMenuItem(labels.exportPdf, () => {
537
+ vscode.postMessage({ type: 'requestExportPDF' });
538
+ }));
539
+
540
+ if (mode === 'slides') {
541
+ menu.appendChild(createMenuItem(labels.exportPptx, () => {
542
+ vscode.postMessage({ type: 'requestExportPPTX' });
543
+ }));
544
+ } else {
545
+ menu.appendChild(createMenuItem(labels.exportHtml, () => {
546
+ vscode.postMessage({ type: 'requestExportHTML' });
547
+ }));
548
+ menu.appendChild(createMenuItem(labels.exportWord, () => {
549
+ vscode.postMessage({ type: 'requestExportWord' });
550
+ }));
551
+ }
552
+
553
+ menu.appendChild(createMenuSeparator());
554
+
555
+ const themeItem = document.createElement('div');
556
+ themeItem.className = 'ctx-menu-item ctx-menu-has-submenu';
557
+ themeItem.textContent = labels.theme;
558
+ themeItem.appendChild(buildThemeSubmenu());
559
+ menu.appendChild(themeItem);
560
+
561
+ menu.appendChild(createMenuSeparator());
562
+
563
+ menu.appendChild(createMenuItem(labels.importTheme, () => {
564
+ vscode.postMessage({ type: 'requestImportTheme' });
565
+ }));
566
+
567
+ document.body.appendChild(menu);
568
+
569
+ const rect = menu.getBoundingClientRect();
570
+ if (rect.right > window.innerWidth) {
571
+ menu.style.left = (x - rect.width) + 'px';
572
+ }
573
+ if (rect.bottom > window.innerHeight) {
574
+ menu.style.top = (y - rect.height) + 'px';
575
+ }
576
+
577
+ setTimeout(() => {
578
+ document.addEventListener('click', closeMenu);
579
+ document.addEventListener('contextmenu', closeMenu);
580
+ }, 0);
581
+ }
582
+
583
+ document.addEventListener('contextmenu', (e) => {
584
+ e.preventDefault();
585
+ showMenu(e.clientX, e.clientY);
586
+ });
587
+
588
+ vscode.postMessage({ type: 'ready' });