vscode-colaview 0.4.1 → 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.
@@ -0,0 +1,187 @@
1
+ // 本地相对图片解析 — 文档预览 / 幻灯片 / 全屏放映 / 导出共用。
2
+ //
3
+ // Markdown 里的图片通常写成相对路径(`![](./images/example.png)`),但预览
4
+ // WebView 与导出的独立 HTML 都没有「文档所在目录」这一上下文:相对路径会按
5
+ // 页面地址解析,图片加载失败后引擎会把源码 `![alt](path)` 原样显示出来。
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(/&amp;/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
+ /** 行内代码用占位符保护,避免把 `` `![x](y)` `` 里的示例路径也替换掉。 */
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
+ }
@@ -90,9 +90,23 @@ export async function exportSlidesPDF(document: vscode.TextDocument, fullHTML: s
90
90
  await page.emulateMediaType('print');
91
91
  await page.evaluate('document.fonts && document.fonts.ready ? document.fonts.ready.then(() => true) : true');
92
92
  // 幻灯片文档的水合脚本(mermaid/KaTeX 从 CDN 加载)完成后才打印;
93
- // 没有该脚本的文档立即返回。水合后再按 print 纸面逐页 fit。
93
+ // 没有该脚本的文档立即返回。
94
94
  await page.evaluate('window.__colaviewSlidesHydrated ? window.__colaviewSlidesHydrated.then(() => true) : true');
95
- await page.evaluate('window.__colaviewFitSlides ? window.__colaviewFitSlides() : 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
+ })()`);
96
110
  await new Promise(r => setTimeout(r, 300));
97
111
 
98
112
  const pdfBuffer = await page.pdf({
@@ -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, rewriteImageSources } from '../slides/render';
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?.getText() || '';
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 = rewriteImageSources(stage.html, path.dirname(document.fileName));
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 = rewriteImageSources(html, path.dirname(document.fileName));
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 markdown = document.getText();
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);
@@ -154,6 +154,27 @@ async function hydrateSlides(): Promise<void> {
154
154
  console.error('[ColaView] slide math render failed:', e);
155
155
  }
156
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
+ }
157
178
  }
158
179
 
159
180
  /** 幻灯片样式表只注入一次(几十 KB,逐键更新时不重复下发)。 */
@@ -183,6 +204,9 @@ function renderSlides(html: string): void {
183
204
  if (!host) return;
184
205
  host.innerHTML = html;
185
206
  fitSlidesStage();
207
+ fitSlidePages();
208
+ // Web 字体到位后行高会变,再适配一次。
209
+ if (document.fonts?.ready) void document.fonts.ready.then(() => fitSlidePages());
186
210
  }
187
211
 
188
212
  function setMode(next: 'document' | 'slides'): void {