vscode-colaview 0.4.0 → 0.4.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.vscode/settings.json +1 -1
- package/CHANGELOG.md +67 -32
- package/README.md +62 -95
- package/README_CN.md +61 -94
- package/RELEASE_NOTES.md +87 -20
- package/assets/gallery/academic-paper.png +0 -0
- package/assets/gallery/builtin-bear.png +0 -0
- package/assets/gallery/builtin-dark.png +0 -0
- package/assets/gallery/builtin-dracula.png +0 -0
- package/assets/gallery/builtin-elegant.png +0 -0
- package/assets/gallery/builtin-gruvbox.png +0 -0
- package/assets/gallery/builtin-light.png +0 -0
- package/assets/gallery/builtin-midnight.png +0 -0
- package/assets/gallery/builtin-nord.png +0 -0
- package/assets/gallery/builtin-notion.png +0 -0
- package/assets/gallery/builtin-sepia.png +0 -0
- package/assets/gallery/builtin-solarized-dark.png +0 -0
- package/assets/gallery/builtin-writer.png +0 -0
- package/assets/gallery/forest-ink.png +0 -0
- package/assets/gallery/pink-script-dark.png +0 -0
- package/assets/gallery/swiss-design.png +0 -0
- package/assets/gallery/trae-blue.png +0 -0
- package/package.json +204 -203
- package/src/assets/local-images.ts +187 -0
- package/src/export/pdf-exporter.ts +18 -0
- package/src/present/presenter.ts +25 -0
- package/src/preview/preview-manager.ts +24 -14
- package/src/preview/webview/app.ts +131 -0
- package/src/slides/deck.ts +11 -0
- package/src/slides/markdown.ts +27 -0
- package/src/slides/render.ts +175 -87
- package/src/themes/built-in/bear.css +89 -89
- package/src/themes/built-in/dark.css +87 -87
- package/src/themes/built-in/dracula.css +93 -93
- package/src/themes/built-in/elegant.css +109 -109
- package/src/themes/built-in/gruvbox.css +97 -97
- package/src/themes/built-in/light.css +80 -80
- package/src/themes/built-in/midnight.css +93 -93
- package/src/themes/built-in/nord.css +93 -93
- package/src/themes/built-in/notion.css +98 -98
- package/src/themes/built-in/sepia.css +99 -99
- package/src/themes/built-in/solarized-dark.css +94 -94
- package/src/themes/built-in/writer.css +99 -99
- package/src/types/pele-lazy.d.ts +21 -0
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
// 本地相对图片解析 — 文档预览 / 幻灯片 / 全屏放映 / 导出共用。
|
|
2
|
+
//
|
|
3
|
+
// Markdown 里的图片通常写成相对路径(``),但预览
|
|
4
|
+
// WebView 与导出的独立 HTML 都没有「文档所在目录」这一上下文:相对路径会按
|
|
5
|
+
// 页面地址解析,图片加载失败后引擎会把源码 `` 原样显示出来。
|
|
6
|
+
// 这里把本地图片内联成 data URL,一次解析、四处通用(与 ColaMD-themes 的
|
|
7
|
+
// `dsh-assets.ts` 同一条思路)。
|
|
8
|
+
import * as fs from 'fs/promises';
|
|
9
|
+
import * as path from 'path';
|
|
10
|
+
import { fileURLToPath } from 'url';
|
|
11
|
+
|
|
12
|
+
/** 单张图片上限;超过时保留原 src,交给浏览器按原路径处理。 */
|
|
13
|
+
const MAX_ASSET_BYTES = 24 * 1024 * 1024;
|
|
14
|
+
/** 进程内缓存:同一文件在 mtime/size 不变时复用 data URL。 */
|
|
15
|
+
const assetCache = new Map<string, { stamp: string; dataUrl: string }>();
|
|
16
|
+
const ASSET_CACHE_LIMIT = 64;
|
|
17
|
+
|
|
18
|
+
const MIME_BY_EXT: Record<string, string> = {
|
|
19
|
+
'.png': 'image/png',
|
|
20
|
+
'.jpg': 'image/jpeg',
|
|
21
|
+
'.jpeg': 'image/jpeg',
|
|
22
|
+
'.gif': 'image/gif',
|
|
23
|
+
'.webp': 'image/webp',
|
|
24
|
+
'.svg': 'image/svg+xml',
|
|
25
|
+
'.bmp': 'image/bmp',
|
|
26
|
+
'.avif': 'image/avif',
|
|
27
|
+
'.ico': 'image/x-icon',
|
|
28
|
+
};
|
|
29
|
+
|
|
30
|
+
/** `D:\…` 这类 Windows 盘符不是 URL 协议。 */
|
|
31
|
+
function hasScheme(raw: string): boolean {
|
|
32
|
+
return /^[a-z][a-z0-9+.-]*:/i.test(raw) && !/^[a-z]:[\\/]/i.test(raw);
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** 逐段解码,坏转义保留原样。 */
|
|
36
|
+
function decodeSegments(raw: string): string {
|
|
37
|
+
return raw
|
|
38
|
+
.split('/')
|
|
39
|
+
.map((segment) => {
|
|
40
|
+
try {
|
|
41
|
+
return decodeURIComponent(segment);
|
|
42
|
+
} catch {
|
|
43
|
+
return segment;
|
|
44
|
+
}
|
|
45
|
+
})
|
|
46
|
+
.join('/');
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function mimeFor(file: string): string | undefined {
|
|
50
|
+
return MIME_BY_EXT[path.extname(file).toLowerCase()];
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
async function dataUrlFor(file: string): Promise<string | undefined> {
|
|
54
|
+
try {
|
|
55
|
+
const info = await fs.stat(file);
|
|
56
|
+
if (!info.isFile() || info.size === 0 || info.size > MAX_ASSET_BYTES) return undefined;
|
|
57
|
+
const stamp = `${info.size}:${info.mtimeMs}`;
|
|
58
|
+
const hit = assetCache.get(file);
|
|
59
|
+
if (hit !== undefined && hit.stamp === stamp) return hit.dataUrl;
|
|
60
|
+
const bytes = await fs.readFile(file);
|
|
61
|
+
const mime = mimeFor(file);
|
|
62
|
+
if (mime === undefined) return undefined;
|
|
63
|
+
const dataUrl = `data:${mime};base64,${bytes.toString('base64')}`;
|
|
64
|
+
if (assetCache.size >= ASSET_CACHE_LIMIT) {
|
|
65
|
+
const oldest = assetCache.keys().next();
|
|
66
|
+
if (oldest.done !== true) assetCache.delete(oldest.value);
|
|
67
|
+
}
|
|
68
|
+
assetCache.set(file, { stamp, dataUrl });
|
|
69
|
+
return dataUrl;
|
|
70
|
+
} catch {
|
|
71
|
+
return undefined;
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* 解析单个图片地址:远程地址保持原样,本地文件转 data URL。
|
|
77
|
+
* 解析失败或超限时返回原值,不影响页面其它内容。
|
|
78
|
+
*/
|
|
79
|
+
export async function resolveLocalImage(src: string, baseDir: string): Promise<string> {
|
|
80
|
+
const value = src.trim();
|
|
81
|
+
if (value === '' || value.startsWith('#')) return src;
|
|
82
|
+
if (/^(?:data:|blob:|https?:\/\/|\/\/)/i.test(value)) return src;
|
|
83
|
+
if (/^file:/i.test(value)) {
|
|
84
|
+
let filePath: string;
|
|
85
|
+
try {
|
|
86
|
+
filePath = fileURLToPath(value);
|
|
87
|
+
} catch {
|
|
88
|
+
return src;
|
|
89
|
+
}
|
|
90
|
+
return (await dataUrlFor(filePath)) ?? src;
|
|
91
|
+
}
|
|
92
|
+
// 其它协议(vscode-webview、mailto…)不动;Windows 盘符除外。
|
|
93
|
+
if (hasScheme(value)) return src;
|
|
94
|
+
|
|
95
|
+
const decoded = decodeSegments(value).replace(/&/g, '&');
|
|
96
|
+
const target = path.isAbsolute(decoded) ? decoded : path.resolve(baseDir, decoded);
|
|
97
|
+
return (await dataUrlFor(target)) ?? src;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** 把 HTML 里的 `<img src="…">` 按文档目录解析为 data URL。 */
|
|
101
|
+
export async function inlineHtmlImages(html: string, baseDir: string): Promise<string> {
|
|
102
|
+
if (baseDir === '') return html;
|
|
103
|
+
const pattern = /(<img\b[^>]*?\bsrc\s*=\s*)("([^"]*)"|'([^']*)'|([^\s>]+))/gi;
|
|
104
|
+
let cursor = 0;
|
|
105
|
+
let result = '';
|
|
106
|
+
for (const match of html.matchAll(pattern)) {
|
|
107
|
+
const quoted = match[3] ?? match[4];
|
|
108
|
+
const raw = quoted ?? match[5] ?? '';
|
|
109
|
+
const resolved = await resolveLocalImage(raw, baseDir);
|
|
110
|
+
if (resolved === raw) continue;
|
|
111
|
+
const quote = match[3] !== undefined ? '"' : match[4] !== undefined ? "'" : '';
|
|
112
|
+
result += html.slice(cursor, (match.index ?? 0) + match[1].length);
|
|
113
|
+
result += quote + resolved + quote;
|
|
114
|
+
cursor = (match.index ?? 0) + match[0].length;
|
|
115
|
+
}
|
|
116
|
+
return cursor === 0 ? html : result + html.slice(cursor);
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/** 行内代码用占位符保护,避免把 `` `` `` 里的示例路径也替换掉。 */
|
|
120
|
+
async function rewriteLineImages(line: string, baseDir: string): Promise<string> {
|
|
121
|
+
const parts = line.split(/(`+[^`]*`+)/g);
|
|
122
|
+
for (let i = 0; i < parts.length; i += 2) {
|
|
123
|
+
const part = parts[i] ?? '';
|
|
124
|
+
parts[i] = await rewriteImageSyntax(part, baseDir);
|
|
125
|
+
}
|
|
126
|
+
return parts.join('');
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
const MARKDOWN_IMAGE = /(!\[[^\]]*\]\()\s*(<[^>]*>|[^)\s]+)(\s+"[^"]*")?(\))/g;
|
|
130
|
+
const HTML_IMAGE = /(<img\b[^>]*?\bsrc\s*=\s*)(["'])([^"']+)\2/gi;
|
|
131
|
+
|
|
132
|
+
async function rewriteImageSyntax(text: string, baseDir: string): Promise<string> {
|
|
133
|
+
let out = text;
|
|
134
|
+
const mdMatches = [...out.matchAll(MARKDOWN_IMAGE)];
|
|
135
|
+
if (mdMatches.length > 0) {
|
|
136
|
+
let cursor = 0;
|
|
137
|
+
let result = '';
|
|
138
|
+
for (const match of mdMatches) {
|
|
139
|
+
const raw = (match[2] ?? '').replace(/^<|>$/g, '');
|
|
140
|
+
const resolved = await resolveLocalImage(raw, baseDir);
|
|
141
|
+
result += out.slice(cursor, match.index);
|
|
142
|
+
result += `${match[1] ?? ''}${resolved}${match[3] ?? ''}${match[4] ?? ''}`;
|
|
143
|
+
cursor = (match.index ?? 0) + match[0].length;
|
|
144
|
+
}
|
|
145
|
+
out = result + out.slice(cursor);
|
|
146
|
+
}
|
|
147
|
+
const htmlMatches = [...out.matchAll(HTML_IMAGE)];
|
|
148
|
+
if (htmlMatches.length > 0) {
|
|
149
|
+
let cursor = 0;
|
|
150
|
+
let result = '';
|
|
151
|
+
for (const match of htmlMatches) {
|
|
152
|
+
const resolved = await resolveLocalImage(match[3] ?? '', baseDir);
|
|
153
|
+
result += out.slice(cursor, match.index);
|
|
154
|
+
result += `${match[1] ?? ''}${match[2] ?? ''}${resolved}${match[2] ?? ''}`;
|
|
155
|
+
cursor = (match.index ?? 0) + match[0].length;
|
|
156
|
+
}
|
|
157
|
+
out = result + out.slice(cursor);
|
|
158
|
+
}
|
|
159
|
+
return out;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/**
|
|
163
|
+
* 把 Markdown 里的本地图片路径内联成 data URL。
|
|
164
|
+
* 围栏代码块与行内代码原样保留;远程地址、data/blob、其它协议不动。
|
|
165
|
+
*/
|
|
166
|
+
export async function inlineMarkdownImages(markdown: string, baseDir: string): Promise<string> {
|
|
167
|
+
if (baseDir === '') return markdown;
|
|
168
|
+
const lines = markdown.replace(/\r\n?/g, '\n').split('\n');
|
|
169
|
+
let fence: string | null = null;
|
|
170
|
+
const out: string[] = [];
|
|
171
|
+
for (const line of lines) {
|
|
172
|
+
const fenceMatch = /^\s*(`{3,}|~{3,})/.exec(line);
|
|
173
|
+
if (fenceMatch !== null) {
|
|
174
|
+
const marker = fenceMatch[1] ?? '```';
|
|
175
|
+
if (fence === null) fence = marker;
|
|
176
|
+
else if (line.trimStart().startsWith(fence)) fence = null;
|
|
177
|
+
out.push(line);
|
|
178
|
+
continue;
|
|
179
|
+
}
|
|
180
|
+
if (fence !== null) {
|
|
181
|
+
out.push(line);
|
|
182
|
+
continue;
|
|
183
|
+
}
|
|
184
|
+
out.push(await rewriteLineImages(line, baseDir));
|
|
185
|
+
}
|
|
186
|
+
return out.join('\n');
|
|
187
|
+
}
|
|
@@ -89,6 +89,24 @@ export async function exportSlidesPDF(document: vscode.TextDocument, fullHTML: s
|
|
|
89
89
|
// 打印媒体下的盒模型与屏幕略有差异(容器查询单位、分页),切过去再打。
|
|
90
90
|
await page.emulateMediaType('print');
|
|
91
91
|
await page.evaluate('document.fonts && document.fonts.ready ? document.fonts.ready.then(() => true) : true');
|
|
92
|
+
// 幻灯片文档的水合脚本(mermaid/KaTeX 从 CDN 加载)完成后才打印;
|
|
93
|
+
// 没有该脚本的文档立即返回。
|
|
94
|
+
await page.evaluate('window.__colaviewSlidesHydrated ? window.__colaviewSlidesHydrated.then(() => true) : true');
|
|
95
|
+
// 与 DSH/extend 导出同一条路线:装不下时对每页内容整体 zoom(字体与 px
|
|
96
|
+
// 元素一起缩)。打印文档没有放映脚本,不能依赖 window.__colaviewFitSlides。
|
|
97
|
+
await page.evaluate(`(() => {
|
|
98
|
+
const papers = Array.from(document.querySelectorAll('.cm-page'));
|
|
99
|
+
for (const paper of papers) {
|
|
100
|
+
const content = paper.querySelector('.cm-content');
|
|
101
|
+
if (!content) continue;
|
|
102
|
+
content.style.zoom = '';
|
|
103
|
+
const room = paper.clientHeight;
|
|
104
|
+
const need = content.scrollHeight;
|
|
105
|
+
if (!room || !need || need <= room + 1) continue;
|
|
106
|
+
content.style.zoom = Math.max(0.2, (room / need) * 0.995).toFixed(4);
|
|
107
|
+
}
|
|
108
|
+
return true;
|
|
109
|
+
})()`);
|
|
92
110
|
await new Promise(r => setTimeout(r, 300));
|
|
93
111
|
|
|
94
112
|
const pdfBuffer = await page.pdf({
|
package/src/present/presenter.ts
CHANGED
|
@@ -5,6 +5,7 @@ import * as vscode from 'vscode';
|
|
|
5
5
|
import * as path from 'path';
|
|
6
6
|
import * as os from 'os';
|
|
7
7
|
import * as fs from 'fs';
|
|
8
|
+
import { exec } from 'child_process';
|
|
8
9
|
|
|
9
10
|
const PRESENT_DIR = path.join(os.tmpdir(), 'colaview-present');
|
|
10
11
|
const MAX_KEPT_FILES = 8;
|
|
@@ -37,6 +38,24 @@ function prunePresentDir(keep: string): void {
|
|
|
37
38
|
}
|
|
38
39
|
}
|
|
39
40
|
|
|
41
|
+
/**
|
|
42
|
+
* 用系统 shell 交给默认浏览器打开文件。
|
|
43
|
+
* `vscode.env.openExternal` 对 `file:` URI 在 Windows 上常报
|
|
44
|
+
* “系统找不到指定的文件”(ShellExecute 走 file:// 关联失败),所以直接走
|
|
45
|
+
* 平台 shell:Windows `start`、macOS `open`、Linux `xdg-open`。
|
|
46
|
+
*/
|
|
47
|
+
function openWithShell(filePath: string): Promise<void> {
|
|
48
|
+
return new Promise((resolve, reject) => {
|
|
49
|
+
const command =
|
|
50
|
+
process.platform === 'win32'
|
|
51
|
+
? `start "" "${filePath}"`
|
|
52
|
+
: process.platform === 'darwin'
|
|
53
|
+
? `open "${filePath}"`
|
|
54
|
+
: `xdg-open "${filePath}"`;
|
|
55
|
+
exec(command, { timeout: 15000 }, (err) => (err ? reject(err) : resolve()));
|
|
56
|
+
});
|
|
57
|
+
}
|
|
58
|
+
|
|
40
59
|
/**
|
|
41
60
|
* 用默认浏览器打开一份全屏演示文档。
|
|
42
61
|
* @param title 文档标题(用于文件名与提示)
|
|
@@ -50,6 +69,12 @@ export async function openPresentWindow(title: string, html: string): Promise<vo
|
|
|
50
69
|
prunePresentDir(name);
|
|
51
70
|
|
|
52
71
|
try {
|
|
72
|
+
try {
|
|
73
|
+
await openWithShell(filePath);
|
|
74
|
+
return;
|
|
75
|
+
} catch {
|
|
76
|
+
/* shell 打开失败时退回 VS Code 通道 */
|
|
77
|
+
}
|
|
53
78
|
const opened = await vscode.env.openExternal(vscode.Uri.file(filePath));
|
|
54
79
|
if (!opened) {
|
|
55
80
|
vscode.window.showWarningMessage(
|
|
@@ -8,7 +8,8 @@ import { exportPDF, exportSlidesPDF } from '../export/pdf-exporter';
|
|
|
8
8
|
import { exportWord } from '../export/docx-exporter';
|
|
9
9
|
import { exportPPTX } from '../export/pptx-exporter';
|
|
10
10
|
import { translateThemeCssForExport, translateEngineThemeCssForExport } from '../export/theme-style';
|
|
11
|
-
import { composeDeckCss, decoratePresentDocument, renderDeckStage, renderSlidesDocument
|
|
11
|
+
import { composeDeckCss, decoratePresentDocument, renderDeckStage, renderSlidesDocument } from '../slides/render';
|
|
12
|
+
import { inlineHtmlImages, inlineMarkdownImages } from '../assets/local-images';
|
|
12
13
|
import { openPresentWindow } from '../present/presenter';
|
|
13
14
|
|
|
14
15
|
/** 预览模式:整篇文档 / 幻灯片(自有渲染层)。 */
|
|
@@ -48,6 +49,8 @@ export class PreviewManager {
|
|
|
48
49
|
private editorScrollDelay = Date.now();
|
|
49
50
|
/** 当前面板处于文档模式还是幻灯片模式。 */
|
|
50
51
|
private mode: PreviewMode = 'document';
|
|
52
|
+
/** Markdown 图片内联是异步的:只接受最后一次请求的结果,避免慢请求覆盖新内容。 */
|
|
53
|
+
private previewSeq = 0;
|
|
51
54
|
|
|
52
55
|
constructor(private context: vscode.ExtensionContext) {
|
|
53
56
|
this.registerActiveEditorListener();
|
|
@@ -61,7 +64,7 @@ export class PreviewManager {
|
|
|
61
64
|
if (editor && editor.document.languageId === 'markdown' && this.panel) {
|
|
62
65
|
if (this.currentUri?.toString() !== editor.document.uri.toString()) {
|
|
63
66
|
this.currentUri = editor.document.uri;
|
|
64
|
-
this.updatePreview(editor.document);
|
|
67
|
+
void this.updatePreview(editor.document);
|
|
65
68
|
}
|
|
66
69
|
}
|
|
67
70
|
} catch (e) {
|
|
@@ -164,7 +167,7 @@ export class PreviewManager {
|
|
|
164
167
|
this.panel.title = `Preview: ${path.basename(editor.document.fileName)}`;
|
|
165
168
|
this.panel.reveal(vscode.ViewColumn.Two);
|
|
166
169
|
this.pushMode();
|
|
167
|
-
this.updatePreview(editor.document);
|
|
170
|
+
void this.updatePreview(editor.document);
|
|
168
171
|
} else {
|
|
169
172
|
this.panel = vscode.window.createWebviewPanel(
|
|
170
173
|
'colaview',
|
|
@@ -184,11 +187,11 @@ export class PreviewManager {
|
|
|
184
187
|
this.panel.webview.html = this.buildWebViewHTML();
|
|
185
188
|
this.panel.onDidDispose(() => { this.panel = null; }, null, this.disposables);
|
|
186
189
|
|
|
187
|
-
this.panel.webview.onDidReceiveMessage((msg: { type: string; html?: string; message?: string; name?: string; scrollPercent?: number; mode?: string }) => {
|
|
190
|
+
this.panel.webview.onDidReceiveMessage(async (msg: { type: string; html?: string; message?: string; name?: string; scrollPercent?: number; mode?: string }) => {
|
|
188
191
|
switch (msg.type) {
|
|
189
192
|
case 'ready': {
|
|
190
193
|
const theme = ThemeManager.getCurrentTheme();
|
|
191
|
-
const markdown = this.pendingDocument
|
|
194
|
+
const markdown = this.pendingDocument ? await this.previewMarkdown(this.pendingDocument) : '';
|
|
192
195
|
const builtins = ThemeManager.getBuiltinThemes();
|
|
193
196
|
const isCustom = !builtins.includes(theme);
|
|
194
197
|
const customCSS = isCustom ? ThemeManager.loadThemeCSS(theme) : undefined;
|
|
@@ -279,7 +282,7 @@ export class PreviewManager {
|
|
|
279
282
|
if (e.document.uri.toString() === this.currentUri?.toString()) {
|
|
280
283
|
if (this.debounceTimer) clearTimeout(this.debounceTimer);
|
|
281
284
|
this.debounceTimer = setTimeout(() => {
|
|
282
|
-
this.updatePreview(e.document);
|
|
285
|
+
void this.updatePreview(e.document);
|
|
283
286
|
}, 150);
|
|
284
287
|
}
|
|
285
288
|
}, null, this.disposables);
|
|
@@ -427,7 +430,7 @@ export class PreviewManager {
|
|
|
427
430
|
try {
|
|
428
431
|
const document = await vscode.workspace.openTextDocument(this.currentUri);
|
|
429
432
|
const stage = renderDeckStage(document.getText(), this.documentTitle(document), 'flow');
|
|
430
|
-
const html =
|
|
433
|
+
const html = await inlineHtmlImages(stage.html, path.dirname(document.fileName));
|
|
431
434
|
const payload: Record<string, unknown> = {
|
|
432
435
|
type: 'slides',
|
|
433
436
|
html,
|
|
@@ -458,7 +461,7 @@ export class PreviewManager {
|
|
|
458
461
|
}
|
|
459
462
|
|
|
460
463
|
/** 生成自包含的幻灯片文档(打印=每页一张纸;放映=一次一页 + 全屏交互)。 */
|
|
461
|
-
private buildSlidesDocument(document: vscode.TextDocument, mode: 'print' | 'present'): string {
|
|
464
|
+
private async buildSlidesDocument(document: vscode.TextDocument, mode: 'print' | 'present'): Promise<string> {
|
|
462
465
|
const html = renderSlidesDocument({
|
|
463
466
|
title: this.documentTitle(document),
|
|
464
467
|
themeCss: ThemeManager.loadThemeCSS(ThemeManager.getCurrentTheme()),
|
|
@@ -467,10 +470,15 @@ export class PreviewManager {
|
|
|
467
470
|
bodyClass: this.themeBodyClass(),
|
|
468
471
|
mode,
|
|
469
472
|
});
|
|
470
|
-
const localised =
|
|
473
|
+
const localised = await inlineHtmlImages(html, path.dirname(document.fileName));
|
|
471
474
|
return mode === 'present' ? decoratePresentDocument(localised) : localised;
|
|
472
475
|
}
|
|
473
476
|
|
|
477
|
+
/** 预览用的 Markdown:把本地相对图片路径内联成 data URL(WebView 没有文档目录上下文)。 */
|
|
478
|
+
private previewMarkdown(document: vscode.TextDocument): Promise<string> {
|
|
479
|
+
return inlineMarkdownImages(document.getText(), path.dirname(document.fileName));
|
|
480
|
+
}
|
|
481
|
+
|
|
474
482
|
/** 导出幻灯片 PDF(每页一张 1920×1080 纸)。 */
|
|
475
483
|
async exportSlidesPDFToFile(): Promise<void> {
|
|
476
484
|
const document = await this.currentMarkdownDocument();
|
|
@@ -479,7 +487,7 @@ export class PreviewManager {
|
|
|
479
487
|
return;
|
|
480
488
|
}
|
|
481
489
|
try {
|
|
482
|
-
await exportSlidesPDF(document, this.buildSlidesDocument(document, 'print'));
|
|
490
|
+
await exportSlidesPDF(document, await this.buildSlidesDocument(document, 'print'));
|
|
483
491
|
} catch (e) {
|
|
484
492
|
vscode.window.showErrorMessage(`Slides PDF export failed: ${e instanceof Error ? e.message : String(e)}`);
|
|
485
493
|
}
|
|
@@ -495,7 +503,7 @@ export class PreviewManager {
|
|
|
495
503
|
try {
|
|
496
504
|
await exportStandaloneHTML(
|
|
497
505
|
document.fileName.replace(/\.md$/i, '.slides.html'),
|
|
498
|
-
this.buildSlidesDocument(document, 'present')
|
|
506
|
+
await this.buildSlidesDocument(document, 'present')
|
|
499
507
|
);
|
|
500
508
|
} catch (e) {
|
|
501
509
|
vscode.window.showErrorMessage(`Slides HTML export failed: ${e instanceof Error ? e.message : String(e)}`);
|
|
@@ -534,7 +542,7 @@ export class PreviewManager {
|
|
|
534
542
|
try {
|
|
535
543
|
let html: string;
|
|
536
544
|
if (mode === 'slides') {
|
|
537
|
-
html = this.buildSlidesDocument(document, 'present');
|
|
545
|
+
html = await this.buildSlidesDocument(document, 'present');
|
|
538
546
|
} else {
|
|
539
547
|
if (!this.panel) this.showPreview();
|
|
540
548
|
this.mode = 'document';
|
|
@@ -554,9 +562,11 @@ export class PreviewManager {
|
|
|
554
562
|
}
|
|
555
563
|
}
|
|
556
564
|
|
|
557
|
-
private updatePreview(document: vscode.TextDocument): void {
|
|
565
|
+
private async updatePreview(document: vscode.TextDocument): Promise<void> {
|
|
558
566
|
if (!this.panel) return;
|
|
559
|
-
const
|
|
567
|
+
const seq = ++this.previewSeq;
|
|
568
|
+
const markdown = await this.previewMarkdown(document);
|
|
569
|
+
if (!this.panel || seq !== this.previewSeq) return;
|
|
560
570
|
const theme = ThemeManager.getCurrentTheme();
|
|
561
571
|
const builtins = ThemeManager.getBuiltinThemes();
|
|
562
572
|
const isCustom = !builtins.includes(theme);
|
|
@@ -5,6 +5,13 @@
|
|
|
5
5
|
* @bytechain.cn/colamd@2.7.9 适配
|
|
6
6
|
*/
|
|
7
7
|
import { createColaMDEditor, type ColaMDRendererHandle } from '@bytechain.cn/colamd/renderer';
|
|
8
|
+
/** KaTeX:幻灯片渲染层只输出占位容器,由这里水合成公式。 */
|
|
9
|
+
import katex from 'katex';
|
|
10
|
+
// mermaid 图走 pele 渲染(与 ColaMD-extend 同一实现):懒加载,按需 import。
|
|
11
|
+
|
|
12
|
+
/** 图内文字字体:测量与绘制必须同一套,否则 CJK 标签会被量窄、裁掉(上游 #94)。 */
|
|
13
|
+
const DIAGRAM_FONT = '"PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", "Noto Sans CJK SC", sans-serif';
|
|
14
|
+
const DIAGRAM_MONO_FONT = "'SF Mono', 'Fira Code', Menlo, Consolas, monospace";
|
|
8
15
|
|
|
9
16
|
// @ts-ignore — VSCode WebView API
|
|
10
17
|
const vscode = acquireVsCodeApi();
|
|
@@ -50,6 +57,126 @@ let labels: MenuLabels = {
|
|
|
50
57
|
/** 暗色内置主题集合,用于主题子菜单分组(亮色 = 内置全集 - 暗色)。 */
|
|
51
58
|
const DARK_BUILTIN_THEMES = new Set(['dark', 'solarized-dark', 'nord', 'gruvbox', 'dracula', 'midnight']);
|
|
52
59
|
|
|
60
|
+
/** 图内文字字体:测量与绘制必须同一套,否则 CJK 标签会被量窄、裁掉(上游 #94)。 */
|
|
61
|
+
|
|
62
|
+
let peleLoaded: Promise<typeof import('pele/lazy')> | null = null;
|
|
63
|
+
|
|
64
|
+
function loadPele(): Promise<typeof import('pele/lazy')> {
|
|
65
|
+
peleLoaded ??= import('pele/lazy');
|
|
66
|
+
return peleLoaded;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
let mermaidReady = false;
|
|
71
|
+
let mermaidSeq = 0;
|
|
72
|
+
|
|
73
|
+
/** 颜色混合:a 占比 t,与引擎 pele 令牌同一公式(18%/28%/45% 混合)。 */
|
|
74
|
+
function mixColor(a: string, b: string, t: number): string {
|
|
75
|
+
const parse = (c: string): [number, number, number] | null => {
|
|
76
|
+
const v = c.trim();
|
|
77
|
+
if (v.startsWith('#')) {
|
|
78
|
+
const hex = v.length === 4 ? '#' + v.slice(1).split('').map((x) => x + x).join('') : v;
|
|
79
|
+
return [parseInt(hex.slice(1, 3), 16), parseInt(hex.slice(3, 5), 16), parseInt(hex.slice(5, 7), 16)];
|
|
80
|
+
}
|
|
81
|
+
const m = /rgba?\(([^)]+)\)/.exec(v);
|
|
82
|
+
if (m) {
|
|
83
|
+
const parts = (m[1] ?? '').split(',').map((s) => parseFloat(s));
|
|
84
|
+
return [parts[0] ?? 128, parts[1] ?? 128, parts[2] ?? 128];
|
|
85
|
+
}
|
|
86
|
+
return null;
|
|
87
|
+
};
|
|
88
|
+
const pa = parse(a) ?? [128, 128, 128];
|
|
89
|
+
const pb = parse(b) ?? [255, 255, 255];
|
|
90
|
+
const r = Math.round(pa[0] * t + pb[0] * (1 - t));
|
|
91
|
+
const g = Math.round(pa[1] * t + pb[1] * (1 - t));
|
|
92
|
+
const bl = Math.round(pa[2] * t + pb[2] * (1 - t));
|
|
93
|
+
return `rgb(${r},${g},${bl})`;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** 按当前主题推导 mermaid 配色(与文档模式的 pele 令牌一致:画在页面底色上)。 */
|
|
97
|
+
function mermaidThemeVariables(): Record<string, string> {
|
|
98
|
+
const style = getComputedStyle(document.body);
|
|
99
|
+
const bg = style.backgroundColor || '#ffffff';
|
|
100
|
+
const fg = style.color || '#1f1f1f';
|
|
101
|
+
const accentRaw = (style.getPropertyValue('--seed-accent') || style.getPropertyValue('--link-color') || '').trim();
|
|
102
|
+
const accent = /^#|^rgb/.test(accentRaw) ? accentRaw : mixColor(fg, bg, 0.45);
|
|
103
|
+
const borderRaw = (style.getPropertyValue('--border-color') || '').trim();
|
|
104
|
+
const border = /^#|^rgb/.test(borderRaw) ? borderRaw : mixColor(fg, bg, 0.45);
|
|
105
|
+
return {
|
|
106
|
+
background: bg,
|
|
107
|
+
primaryColor: mixColor(fg, bg, 0.18),
|
|
108
|
+
primaryTextColor: fg,
|
|
109
|
+
primaryBorderColor: accent,
|
|
110
|
+
lineColor: mixColor(fg, bg, 0.28),
|
|
111
|
+
secondaryColor: mixColor(fg, bg, 0.28),
|
|
112
|
+
tertiaryColor: mixColor(fg, bg, 0.18),
|
|
113
|
+
clusterBkg: mixColor(fg, bg, 0.08),
|
|
114
|
+
clusterBorder: border,
|
|
115
|
+
edgeLabelBackground: bg,
|
|
116
|
+
fontFamily: style.fontFamily,
|
|
117
|
+
fontSize: '28px',
|
|
118
|
+
};
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/**
|
|
122
|
+
* 水合幻灯片里的 mermaid 图与块级公式。
|
|
123
|
+
* 渲染层(src/slides/render.ts)把 ```mermaid 围栏输出为
|
|
124
|
+
* `<pre class="mermaid-src" hidden>`、`$$` 块输出为 `<span class="math-src" hidden>`,
|
|
125
|
+
* 由这里替换成 SVG / KaTeX HTML;失败时保留源码兜底。
|
|
126
|
+
*/
|
|
127
|
+
async function hydrateSlides(): Promise<void> {
|
|
128
|
+
const host = document.getElementById('slides-host');
|
|
129
|
+
if (!host) return;
|
|
130
|
+
|
|
131
|
+
for (const node of Array.from(host.querySelectorAll<HTMLElement>('pre.mermaid-src'))) {
|
|
132
|
+
const holder = node.parentElement;
|
|
133
|
+
if (!holder) continue;
|
|
134
|
+
try {
|
|
135
|
+
const { renderAsync } = await loadPele();
|
|
136
|
+
const { svg } = await renderAsync(node.textContent ?? '', {
|
|
137
|
+
fontFamily: DIAGRAM_FONT,
|
|
138
|
+
fontFamilyMono: DIAGRAM_MONO_FONT,
|
|
139
|
+
});
|
|
140
|
+
holder.innerHTML = svg;
|
|
141
|
+
node.remove();
|
|
142
|
+
} catch (e) {
|
|
143
|
+
console.error('[ColaView] slide mermaid render failed:', e);
|
|
144
|
+
/* 渲染失败保留源码 */
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
for (const node of Array.from(host.querySelectorAll<HTMLElement>('span.math-src'))) {
|
|
149
|
+
const holder = node.parentElement;
|
|
150
|
+
if (!holder) continue;
|
|
151
|
+
try {
|
|
152
|
+
katex.render(node.textContent ?? '', holder, { displayMode: true, throwOnError: false });
|
|
153
|
+
} catch (e) {
|
|
154
|
+
console.error('[ColaView] slide math render failed:', e);
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
// 图与公式改变了页内容高度:水合完成后再逐页适配一次。
|
|
159
|
+
fitSlidePages();
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/**
|
|
163
|
+
* 幻灯片逐页适配:装不下时对内容整体 zoom(字体、px 元素、间距一起缩),
|
|
164
|
+
* 与全屏放映、幻灯片 PDF 导出同一条路线。
|
|
165
|
+
*/
|
|
166
|
+
function fitSlidePages(): void {
|
|
167
|
+
const host = document.getElementById('slides-host');
|
|
168
|
+
if (!host) return;
|
|
169
|
+
for (const page of Array.from(host.querySelectorAll<HTMLElement>('.cm-page'))) {
|
|
170
|
+
const content = page.querySelector<HTMLElement>('.cm-content');
|
|
171
|
+
if (!content) continue;
|
|
172
|
+
content.style.zoom = '';
|
|
173
|
+
const room = page.clientHeight;
|
|
174
|
+
const need = content.scrollHeight;
|
|
175
|
+
if (!room || !need || need <= room + 1) continue;
|
|
176
|
+
content.style.zoom = Math.max(0.2, (room / need) * 0.995).toFixed(4);
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
|
|
53
180
|
/** 幻灯片样式表只注入一次(几十 KB,逐键更新时不重复下发)。 */
|
|
54
181
|
function injectSlidesCss(css: string | undefined): void {
|
|
55
182
|
if (!css) return;
|
|
@@ -77,6 +204,9 @@ function renderSlides(html: string): void {
|
|
|
77
204
|
if (!host) return;
|
|
78
205
|
host.innerHTML = html;
|
|
79
206
|
fitSlidesStage();
|
|
207
|
+
fitSlidePages();
|
|
208
|
+
// Web 字体到位后行高会变,再适配一次。
|
|
209
|
+
if (document.fonts?.ready) void document.fonts.ready.then(() => fitSlidePages());
|
|
80
210
|
}
|
|
81
211
|
|
|
82
212
|
function setMode(next: 'document' | 'slides'): void {
|
|
@@ -344,6 +474,7 @@ window.addEventListener('message', async (event: MessageEvent) => {
|
|
|
344
474
|
}
|
|
345
475
|
setMode('slides');
|
|
346
476
|
renderSlides(data.html || '');
|
|
477
|
+
void hydrateSlides();
|
|
347
478
|
break;
|
|
348
479
|
}
|
|
349
480
|
case 'update': {
|
package/src/slides/deck.ts
CHANGED
|
@@ -287,6 +287,11 @@ export function deckChrome(slides: readonly Slide[]): DeckChrome {
|
|
|
287
287
|
export function paginateDeck(slides: readonly Slide[], budget = 820): Slide[] {
|
|
288
288
|
const pages: Slide[] = [];
|
|
289
289
|
for (const slide of slides) {
|
|
290
|
+
// 过滤纯指令/空白页(与上游 deckPages 一致):无标题、lead、kicker 与
|
|
291
|
+
// 正文的页会在放映与打印里产出空白纸面。
|
|
292
|
+
if (slide.blocks.length === 0 && slide.title === '' && slide.lead === '' && slide.kicker === '') {
|
|
293
|
+
continue;
|
|
294
|
+
}
|
|
290
295
|
const weight = blockWeights(slide.blocks);
|
|
291
296
|
if (weight <= budget) {
|
|
292
297
|
pages.push({ ...slide, pageStart: true });
|
|
@@ -332,6 +337,7 @@ function blockWeight(block: MdBlock): number {
|
|
|
332
337
|
if (block.kind === 'paragraph') return block.text.length + 24;
|
|
333
338
|
if (block.kind === 'quote') return block.text.length + 30;
|
|
334
339
|
if (block.kind === 'code') return block.text.split('\n').length * 34 + 40;
|
|
340
|
+
if (block.kind === 'math') return block.text.split('\n').length * 40 + 120;
|
|
335
341
|
if (block.kind === 'table') return (block.rows.length + 1) * 34 + 40;
|
|
336
342
|
if (block.kind === 'html') return 320;
|
|
337
343
|
if (block.kind === 'divider') return 30;
|
|
@@ -343,6 +349,11 @@ function blockWeights(blocks: readonly MdBlock[]): number {
|
|
|
343
349
|
}
|
|
344
350
|
|
|
345
351
|
function splitBlock(block: MdBlock, budget: number): MdBlock[] {
|
|
352
|
+
// mermaid 围栏不可按行切分:切开的每一段都是非法源码,水合时会报
|
|
353
|
+
// "Syntax error in text"。整块保留,超预算时独占一页。
|
|
354
|
+
if (block.kind === 'code' && block.lang.toLowerCase() === 'mermaid') {
|
|
355
|
+
return [block];
|
|
356
|
+
}
|
|
346
357
|
if (block.kind === 'code') {
|
|
347
358
|
const lines = block.text.split('\n');
|
|
348
359
|
const chunks: MdBlock[] = [];
|
package/src/slides/markdown.ts
CHANGED
|
@@ -109,6 +109,8 @@ export type MdBlock =
|
|
|
109
109
|
| { kind: 'heading'; level: 1 | 2 | 3 | 4 | 5 | 6; text: string }
|
|
110
110
|
| { kind: 'paragraph'; text: string }
|
|
111
111
|
| { kind: 'code'; text: string; lang: string }
|
|
112
|
+
/** 块级公式:`$$ ... $$`,交给 WebView 的 KaTeX 渲染。 */
|
|
113
|
+
| { kind: 'math'; text: string }
|
|
112
114
|
| { kind: 'quote'; text: string }
|
|
113
115
|
| { kind: 'list'; ordered: boolean; items: MdListItem[] }
|
|
114
116
|
| { kind: 'table'; header: string[]; aligns: string[]; rows: string[][] }
|
|
@@ -148,6 +150,25 @@ export function parseBlocksLines(lines: string[]): MdBlock[] {
|
|
|
148
150
|
continue;
|
|
149
151
|
}
|
|
150
152
|
|
|
153
|
+
// 块级公式:`$$` 独占一行开合,或 `$$…$$` 单行成块。
|
|
154
|
+
const mathInline = /^\s*\$\$(.+)\$\$\s*$/.exec(line);
|
|
155
|
+
if (mathInline !== null) {
|
|
156
|
+
out.push({ kind: 'math', text: mathInline[1] ?? '' });
|
|
157
|
+
index += 1;
|
|
158
|
+
continue;
|
|
159
|
+
}
|
|
160
|
+
if (/^\s*\$\$\s*$/.test(line)) {
|
|
161
|
+
const buffer: string[] = [];
|
|
162
|
+
index += 1;
|
|
163
|
+
while (index < lines.length && !/^\s*\$\$\s*$/.test(lines[index] ?? '')) {
|
|
164
|
+
buffer.push(lines[index] ?? '');
|
|
165
|
+
index += 1;
|
|
166
|
+
}
|
|
167
|
+
index += 1;
|
|
168
|
+
out.push({ kind: 'math', text: buffer.join('\n') });
|
|
169
|
+
continue;
|
|
170
|
+
}
|
|
171
|
+
|
|
151
172
|
const heading = /^\s*(#{1,6})\s+(.*?)\s*#*\s*$/.exec(line);
|
|
152
173
|
if (heading !== null) {
|
|
153
174
|
const level = (heading[1] ?? '#').length as 1 | 2 | 3 | 4 | 5 | 6;
|
|
@@ -315,6 +336,7 @@ export function parseBlocks(markdown: string): MdBlock[] {
|
|
|
315
336
|
export function blockPlainText(block: MdBlock): string {
|
|
316
337
|
if (block.kind === 'heading' || block.kind === 'paragraph') return plainInline(block.text);
|
|
317
338
|
if (block.kind === 'code') return block.text;
|
|
339
|
+
if (block.kind === 'math') return block.text;
|
|
318
340
|
if (block.kind === 'quote') return block.text;
|
|
319
341
|
if (block.kind === 'list') return block.items.map((item) => plainInline(item.text)).join('\n');
|
|
320
342
|
if (block.kind === 'table') return [block.header, ...block.rows].map((row) => row.join(' | ')).join('\n');
|
|
@@ -371,6 +393,11 @@ export function renderBlocksHtml(blocks: readonly MdBlock[]): string {
|
|
|
371
393
|
out.push(renderListBlock(block));
|
|
372
394
|
continue;
|
|
373
395
|
}
|
|
396
|
+
if (block.kind === 'math') {
|
|
397
|
+
// 语义 HTML 场景没有 KaTeX 运行时,保留 $$ 源码(webview / 放映端可再水合)。
|
|
398
|
+
out.push(`<div class="math-block">\n$$${escapeHtml(block.text)}$$\n</div>`);
|
|
399
|
+
continue;
|
|
400
|
+
}
|
|
374
401
|
const th = block.header
|
|
375
402
|
.map((cell, i) => `<th${block.aligns[i] ? ` style="text-align:${block.aligns[i]}"` : ''}>${renderInline(cell)}</th>`)
|
|
376
403
|
.join('');
|