Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
microsoft
GitHub Repository: microsoft/vscode
Path: blob/main/extensions/ipynb/notebook-src/cellAttachmentRenderer.ts
3292 views
1
/*---------------------------------------------------------------------------------------------
2
* Copyright (c) Microsoft Corporation. All rights reserved.
3
* Licensed under the MIT License. See License.txt in the project root for license information.
4
*--------------------------------------------------------------------------------------------*/
5
6
import type * as MarkdownIt from 'markdown-it';
7
import type * as MarkdownItToken from 'markdown-it/lib/token';
8
import type { RendererContext } from 'vscode-notebook-renderer';
9
10
interface MarkdownItRenderer {
11
extendMarkdownIt(fn: (md: MarkdownIt) => void): void;
12
}
13
14
export async function activate(ctx: RendererContext<void>) {
15
const markdownItRenderer = (await ctx.getRenderer('vscode.markdown-it-renderer')) as MarkdownItRenderer | any;
16
if (!markdownItRenderer) {
17
throw new Error(`Could not load 'vscode.markdown-it-renderer'`);
18
}
19
20
markdownItRenderer.extendMarkdownIt((md: MarkdownIt) => {
21
const original = md.renderer.rules.image;
22
md.renderer.rules.image = (tokens: MarkdownItToken[], idx: number, options, env, self) => {
23
const token = tokens[idx];
24
const src = token.attrGet('src');
25
const attachments: Record<string, Record<string, string>> | undefined = env.outputItem.metadata?.attachments;
26
if (attachments && src && src.startsWith('attachment:')) {
27
const imageAttachment = attachments[tryDecodeURIComponent(src.replace('attachment:', ''))];
28
if (imageAttachment) {
29
// objEntries will always be length 1, with objEntries[0] holding [0]=mime,[1]=b64
30
// if length = 0, something is wrong with the attachment, mime/b64 weren't copied over
31
const objEntries = Object.entries(imageAttachment);
32
if (objEntries.length) {
33
const [attachmentKey, attachmentVal] = objEntries[0];
34
const b64Markdown = 'data:' + attachmentKey + ';base64,' + attachmentVal;
35
token.attrSet('src', b64Markdown);
36
}
37
}
38
}
39
40
if (original) {
41
return original(tokens, idx, options, env, self);
42
} else {
43
return self.renderToken(tokens, idx, options);
44
}
45
};
46
});
47
}
48
49
function tryDecodeURIComponent(uri: string) {
50
try {
51
return decodeURIComponent(uri);
52
} catch {
53
return uri;
54
}
55
}
56
57