Elffuss BraidHub

kikocis/continue public

7f8b1ea26802 · 7.1 KiBRawPermalink
1/**
2 * CodeRenderer is a class that, when given a code string,
3 * highlights the code string using shiki and
4 * returns a svg representation of it.
5 * We could technically just call shiki's methods to do a
6 * one-liner syntax highlighting code, but
7 * a separate class for this is useful because
8 * we rarely ever need syntax highlighting outside of
9 * creating a render of it.
10 */
11import { JSDOM } from "jsdom";
12import { BundledTheme, codeToHtml, getSingletonHighlighter } from "shiki";
13import { escapeForSVG, kebabOfStr } from "../util/text";
14
15interface CodeRendererOptions {
16 themesDir?: string;
17 theme?: string;
18}
19
20interface HTMLOptions {
21 theme?: string;
22 customCSS?: string;
23 containerClass?: string;
24}
25
26interface ConversionOptions extends HTMLOptions {
27 transparent?: boolean;
28 imageType: "svg";
29}
30
31interface Dimensions {
32 width: number;
33 height: number;
34}
35
36type DataUri = PngUri | SvgUri;
37type PngUri = string;
38type SvgUri = string;
39
40export class CodeRenderer {
41 private static instance: CodeRenderer;
42 private currentTheme: string = "dark-plus";
43 private editorBackground: string = "#000000";
44 private editorForeground: string = "#FFFFFF";
45
46 private constructor() {}
47
48 static getInstance(): CodeRenderer {
49 if (!CodeRenderer.instance) {
50 CodeRenderer.instance = new CodeRenderer();
51 }
52 return CodeRenderer.instance;
53 }
54
55 public async setTheme(themeName: string): Promise<void> {
56 if (
57 this.themeExists(kebabOfStr(themeName)) ||
58 themeName === "Default Dark Modern"
59 ) {
60 this.currentTheme =
61 themeName === "Default Dark Modern"
62 ? "dark-plus"
63 : kebabOfStr(themeName);
64
65 const highlighter = await getSingletonHighlighter({
66 themes: [this.currentTheme],
67 });
68
69 const th = highlighter.getTheme(this.currentTheme);
70 this.editorBackground = th.bg;
71 this.editorForeground = th.fg;
72 } else {
73 this.currentTheme = "dark-plus";
74 }
75 }
76
77 async init(): Promise<void> {}
78
79 async close(): Promise<void> {}
80
81 themeExists(themeNameKebab: string): themeNameKebab is BundledTheme {
82 const themeArray: BundledTheme[] = [
83 "andromeeda",
84 "aurora-x",
85 "ayu-dark",
86 "catppuccin-frappe",
87 "catppuccin-latte",
88 "catppuccin-macchiato",
89 "catppuccin-mocha",
90 "dark-plus",
91 "dracula",
92 "dracula-soft",
93 "everforest-dark",
94 "everforest-light",
95 "github-dark",
96 "github-dark-default",
97 "github-dark-dimmed",
98 "github-dark-high-contrast",
99 "github-light",
100 "github-light-default",
101 "github-light-high-contrast",
102 "gruvbox-dark-hard",
103 "gruvbox-dark-medium",
104 "gruvbox-dark-soft",
105 "gruvbox-light-hard",
106 "gruvbox-light-medium",
107 "gruvbox-light-soft",
108 "houston",
109 "kanagawa-dragon",
110 "kanagawa-lotus",
111 "kanagawa-wave",
112 "laserwave",
113 "light-plus",
114 "material-theme",
115 "material-theme-darker",
116 "material-theme-lighter",
117 "material-theme-ocean",
118 "material-theme-palenight",
119 "min-dark",
120 "min-light",
121 "monokai",
122 "night-owl",
123 "nord",
124 "one-dark-pro",
125 "one-light",
126 "plastic",
127 "poimandres",
128 "red",
129 "rose-pine",
130 "rose-pine-dawn",
131 "rose-pine-moon",
132 "slack-dark",
133 "slack-ochin",
134 "snazzy-light",
135 "solarized-dark",
136 "solarized-light",
137 "synthwave-84",
138 "tokyo-night",
139 "vesper",
140 "vitesse-black",
141 "vitesse-dark",
142 "vitesse-light",
143 ];
144
145 return themeArray.includes(themeNameKebab as BundledTheme);
146 }
147
148 async highlightCode(
149 code: string,
150 language: string = "javascript",
151 ): Promise<string> {
152 return await codeToHtml(code, {
153 lang: language,
154 theme: this.currentTheme,
155 });
156 }
157
158 async convertToSVG(
159 code: string,
160 language: string = "javascript",
161 fontSize: number,
162 fontFamily: string,
163 dimensions: Dimensions,
164 lineHeight: number,
165 options: ConversionOptions,
166 ): Promise<Buffer> {
167 const highlightedCodeHtml = await this.highlightCode(code, language);
168
169 const guts = this.convertShikiHtmlToSvgGut(
170 highlightedCodeHtml,
171 fontSize,
172 fontFamily,
173 lineHeight,
174 );
175 const backgroundColor = this.getBackgroundColor(highlightedCodeHtml);
176
177 const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="${dimensions.width}" height="${dimensions.height}">
178 <g>
179 <rect width="${dimensions.width}" height="${dimensions.height}" fill="${backgroundColor}" stroke="${this.editorForeground}" stroke-width="1" />
180 ${guts}
181 </g>
182</svg>`;
183
184 return Buffer.from(svg, "utf8");
185 }
186
187 convertShikiHtmlToSvgGut(
188 shikiHtml: string,
189 fontSize: number,
190 fontFamily: string,
191 lineHeight: number,
192 ): string {
193 const dom = new JSDOM(shikiHtml);
194 const document = dom.window.document;
195
196 const lines = Array.from(document.querySelectorAll(".line"));
197 const svgLines = lines.map((line, index) => {
198 const spans = Array.from(line.childNodes)
199 .map((node) => {
200 if (node.nodeType === 3) {
201 return `<tspan xml:space="preserve">${escapeForSVG(node.textContent ?? "")}</tspan>`;
202 }
203
204 const el = node as HTMLElement;
205 const style = el.getAttribute("style") || "";
206 const colorMatch = style.match(/color:\s*(#[0-9a-fA-F]{6})/);
207 const fill = colorMatch ? ` fill="${colorMatch[1]}"` : "";
208 const content = el.textContent || "";
209 return `<tspan xml:space="preserve"${fill}>${escapeForSVG(content)}</tspan>`;
210 })
211 .join("");
212
213 const y = (index + 1) * lineHeight;
214 return `<text x="0" y="${y}" font-family="${fontFamily}" font-size="${fontSize.toString()}" xml:space="preserve">${spans}</text>`;
215 });
216
217 return `
218 ${svgLines.join("\n")}
219 `.trim();
220 }
221
222 getBackgroundColor(shikiHtml: string): string {
223 const dom = new JSDOM(shikiHtml);
224 const document = dom.window.document;
225
226 const preElement = document.querySelector("pre");
227 let backgroundColor = "#333333"; // Default white background
228 if (preElement) {
229 const style = preElement.getAttribute("style") || "";
230 const bgColorMatch = style.match(/background-color:\s*(#[0-9a-fA-F]{6})/);
231 if (bgColorMatch) {
232 backgroundColor = bgColorMatch[1];
233 }
234 }
235
236 return backgroundColor;
237 }
238
239 async getDataUri(
240 code: string,
241 language: string = "javascript",
242 fontSize: number,
243 fontFamily: string,
244 dimensions: Dimensions,
245 lineHeight: number,
246 options: ConversionOptions,
247 ): Promise<DataUri> {
248 switch (options.imageType) {
249 // case "png":
250 // const pngBuffer = await this.convertToPNG(
251 // code,
252 // language,
253 // fontSize,
254 // dimensions,
255 // lineHeight,
256 // options,
257 // );
258 // return `data:image/png;base64,${pngBuffer.data.toString("base64")}`;
259 case "svg":
260 const svgBuffer = await this.convertToSVG(
261 code,
262 language,
263 fontSize,
264 fontFamily,
265 dimensions,
266 lineHeight,
267 options,
268 );
269 return `data:image/svg+xml;base64,${svgBuffer.toString("base64")}`;
270 }
271 }
272}