vscode-colaview 0.0.0-stage → 0.3.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.vscode/launch.json +30 -0
- package/.vscode/settings.json +4 -0
- package/.vscode/tasks.json +18 -0
- package/.vscodeignore +23 -0
- package/CHANGELOG.md +141 -0
- package/LICENSE +21 -0
- package/README.md +278 -2
- package/README_CN.md +279 -0
- package/RELEASE_NOTES.md +292 -0
- package/esbuild.js +112 -0
- package/icon.png +0 -0
- package/package.json +162 -4
- package/patches/@bytechain.cn+colamd+2.7.11.patch +22 -0
- package/src/commands/commands.ts +105 -0
- package/src/export/css-collector.ts +50 -0
- package/src/export/docx-exporter.ts +962 -0
- package/src/export/html-exporter.ts +18 -0
- package/src/export/pdf-exporter.ts +121 -0
- package/src/export/render-export-images.ts +373 -0
- package/src/export/theme-style.ts +156 -0
- package/src/extension.ts +48 -0
- package/src/preview/preview-manager.ts +542 -0
- package/src/preview/webview/app.ts +366 -0
- package/src/preview/webview/index.html +134 -0
- package/src/themes/built-in/bear.css +38 -0
- package/src/themes/built-in/dark.css +20 -0
- package/src/themes/built-in/dracula.css +38 -0
- package/src/themes/built-in/elegant.css +52 -0
- package/src/themes/built-in/gruvbox.css +42 -0
- package/src/themes/built-in/light.css +20 -0
- package/src/themes/built-in/midnight.css +31 -0
- package/src/themes/built-in/nord.css +38 -0
- package/src/themes/built-in/notion.css +48 -0
- package/src/themes/built-in/sepia.css +47 -0
- package/src/themes/built-in/solarized-dark.css +35 -0
- package/src/themes/built-in/writer.css +44 -0
- package/src/themes/theme-manager.ts +180 -0
- package/src/types/colamd-renderer.d.ts +47 -0
- package/src/types.ts +20 -0
- package/test/fixtures/basic.md +34 -0
- package/test/fixtures/math.md +20 -0
- package/test/fixtures/mermaid.md +19 -0
- package/test/runTest.ts +30 -0
- package/test/suite/html-exporter.test.ts +20 -0
- package/test/suite/markdown-parser.test.ts +8 -0
- package/test/suite/theme-manager.test.ts +31 -0
- package/tsconfig.json +19 -0
package/src/extension.ts
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
// 扩展激活入口
|
|
2
|
+
import * as vscode from 'vscode';
|
|
3
|
+
import { PreviewManager } from './preview/preview-manager';
|
|
4
|
+
import { registerCommands } from './commands/commands';
|
|
5
|
+
import { ThemeManager } from './themes/theme-manager';
|
|
6
|
+
|
|
7
|
+
export function activate(context: vscode.ExtensionContext) {
|
|
8
|
+
console.log('ColaView: Activating extension...');
|
|
9
|
+
|
|
10
|
+
let themeManagerReady = false;
|
|
11
|
+
try {
|
|
12
|
+
ThemeManager.init(context);
|
|
13
|
+
themeManagerReady = true;
|
|
14
|
+
console.log('ColaView: ThemeManager initialized');
|
|
15
|
+
} catch (e) {
|
|
16
|
+
console.error('ColaView: ThemeManager.init failed:', e);
|
|
17
|
+
vscode.window.showWarningMessage(`ColaView: ThemeManager init failed, some features may not work: ${e instanceof Error ? e.message : String(e)}`);
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
let previewManager: PreviewManager | null = null;
|
|
21
|
+
try {
|
|
22
|
+
previewManager = new PreviewManager(context);
|
|
23
|
+
console.log('ColaView: PreviewManager initialized');
|
|
24
|
+
} catch (e) {
|
|
25
|
+
console.error('ColaView: PreviewManager init failed:', e);
|
|
26
|
+
vscode.window.showErrorMessage(`ColaView: Failed to initialize preview manager: ${e instanceof Error ? e.message : String(e)}. Please check the developer console for more details.`);
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
try {
|
|
30
|
+
registerCommands(context, previewManager);
|
|
31
|
+
console.log('ColaView: Commands registered');
|
|
32
|
+
} catch (e) {
|
|
33
|
+
console.error('ColaView: registerCommands failed:', e);
|
|
34
|
+
vscode.window.showErrorMessage(`ColaView: registerCommands failed: ${e instanceof Error ? e.message : String(e)}`);
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
if (previewManager && vscode.workspace.getConfiguration('colaview').get('autoPreview')) {
|
|
38
|
+
try {
|
|
39
|
+
previewManager.showPreview();
|
|
40
|
+
} catch (e) {
|
|
41
|
+
console.warn('ColaView: autoPreview failed:', e);
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
console.log('ColaView: activated');
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export function deactivate() {}
|
|
@@ -0,0 +1,542 @@
|
|
|
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
|
+
const themeOverrideCss = translateThemeCssForExport(ThemeManager.loadThemeCSS(theme));
|
|
393
|
+
const THEME_FIX = themeOverrideCss ? `<style>${themeOverrideCss}</style>` : '';
|
|
394
|
+
// colamd.css 里还有一批 body.theme-X .cm-content .cm-md-* 的正文差异化规则
|
|
395
|
+
// (sepia/dark/notion/midnight/writer 等主题的加粗、行内代码、标题配色只存在于
|
|
396
|
+
// 这一层),导出文档的语义化结构无法命中原选择器 —— 抽取并翻译后一并注入,
|
|
397
|
+
// 导出的正文颜色才能跟预览一致。
|
|
398
|
+
const ENGINE_THEME_FIX = `<style>${translateEngineThemeCssForExport(this.loadEngineColamdCss())}</style>`;
|
|
399
|
+
const PRINT_FIX = `<style>@media print { body > article.colamd-document:not(#_) { display: block !important; } }</style>`;
|
|
400
|
+
// 导出文档里 mermaid 块被引擎序列化成不带类名的 `<p><svg class="pele pele-…">…</svg></p>`
|
|
401
|
+
// (实测 block widget 以非 .cm-line 子节点进入序列化,走段落分支,不是
|
|
402
|
+
// `hte('mermaid')` 的 `<div>` 分支)—— .cm-md-mermaid 上的居中、--pele-* 令牌、
|
|
403
|
+
// 代码块底色都随之丢掉。所以这里按导出文档的实际结构再补一份:<p> 容器给代码块底色
|
|
404
|
+
// (图和代码块共用一块底,和 ColaMD 导出一致),SVG 用 block + 左右 auto 外边距居中。
|
|
405
|
+
// 图上的缩放控件(.pele-zoom)是编辑器的东西,不是文档内容 —— 导出纸面上藏掉
|
|
406
|
+
// (镜像 colamd-extend print-layout.ts 的修复;Chromium 打印不执行脚本,
|
|
407
|
+
// pele 没机会收回它们,控件会叠在图上进 PDF)。
|
|
408
|
+
const MERMAID_FIX = `<style>
|
|
409
|
+
/* 图表配色不要在这里重新推导:buildExportHTML 已经把预览里 \`.cm-md-mermaid\` 上
|
|
410
|
+
实际生效的 --pele-* 变量(含自定义主题显式覆盖的值)收进导出文档的 :root,
|
|
411
|
+
那才是“预览中的配色”。导出端只需要补两件引擎序列化时丢掉的东西:
|
|
412
|
+
代码块底色背景(图和代码块共用一块底)与居中。 */
|
|
413
|
+
.colamd-document .cm-md-mermaid,
|
|
414
|
+
.colamd-document p:has(> svg.pele) {
|
|
415
|
+
background: var(--code-block-bg);
|
|
416
|
+
border-radius: 6px;
|
|
417
|
+
padding: 0.8em 1em;
|
|
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(--code-block-bg);
|
|
433
|
+
--pele-fg: var(--code-block-text, var(--text-color));
|
|
434
|
+
--pele-muted: color-mix(in srgb, var(--code-block-text, var(--text-color)) 70%, var(--code-block-bg));
|
|
435
|
+
--pele-line: var(--code-block-text, var(--text-color));
|
|
436
|
+
--pele-surface: color-mix(in srgb, var(--code-block-text, var(--text-color)) 18%, var(--code-block-bg));
|
|
437
|
+
--pele-surface-alt: color-mix(in srgb, var(--code-block-text, var(--text-color)) 28%, var(--code-block-bg));
|
|
438
|
+
--pele-border: color-mix(in srgb, var(--code-block-text, var(--text-color)) 45%, var(--code-block-bg));
|
|
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
|
+
}
|
|
542
|
+
}
|