Elffuss BraidHub

kikocis/continue public

8cf316c34504 · 12.5 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 {
12 transformerNotationDiff,
13 transformerNotationHighlight,
14} from "@shikijs/transformers";
15import { JSDOM } from "jsdom";
16import {
17 BundledLanguage,
18 BundledTheme,
19 getSingletonHighlighter,
20 Highlighter,
21} from "shiki";
22import { DiffLine } from "..";
23import { escapeForSVG, kebabOfStr } from "../util/text";
24
25interface CodeRendererOptions {
26 themesDir?: string;
27 theme?: string;
28}
29
30interface HTMLOptions {
31 theme?: string;
32 customCSS?: string;
33 containerClass?: string;
34}
35
36interface ConversionOptions extends HTMLOptions {
37 transparent?: boolean;
38 imageType: "svg";
39 fontSize: number;
40 fontFamily: string;
41 dimensions: Dimensions;
42 lineHeight: number;
43}
44
45interface Dimensions {
46 width: number;
47 height: number;
48}
49
50type DataUri = PngUri | SvgUri;
51type PngUri = string;
52type SvgUri = string;
53
54export class CodeRenderer {
55 private static instance: CodeRenderer;
56 private currentTheme: string = "dark-plus";
57 private editorBackground: string = "#000000";
58 private editorForeground: string = "#FFFFFF";
59 private editorLineHighlight: string = "#000000";
60 private highlighter: Highlighter | null = null;
61
62 private constructor() {}
63
64 static getInstance(): CodeRenderer {
65 if (!CodeRenderer.instance) {
66 CodeRenderer.instance = new CodeRenderer();
67 }
68 return CodeRenderer.instance;
69 }
70
71 public async setTheme(themeName: string): Promise<void> {
72 if (
73 this.themeExists(kebabOfStr(themeName)) ||
74 themeName === "Default Dark Modern"
75 ) {
76 this.currentTheme =
77 themeName === "Default Dark Modern"
78 ? "dark-plus"
79 : kebabOfStr(themeName);
80
81 this.highlighter = await getSingletonHighlighter({
82 langs: ["typescript"],
83 themes: [this.currentTheme],
84 });
85
86 const th = this.highlighter.getTheme(this.currentTheme);
87
88 this.editorBackground = th.bg;
89 this.editorForeground = th.fg;
90 this.editorLineHighlight =
91 th.colors!["editor.lineHighlightBackground"] ?? "#000000";
92 } else {
93 this.currentTheme = "dark-plus";
94 }
95 }
96
97 async init(): Promise<void> {}
98
99 async close(): Promise<void> {}
100
101 themeExists(themeNameKebab: string): themeNameKebab is BundledTheme {
102 const themeArray: BundledTheme[] = [
103 "andromeeda",
104 "aurora-x",
105 "ayu-dark",
106 "catppuccin-frappe",
107 "catppuccin-latte",
108 "catppuccin-macchiato",
109 "catppuccin-mocha",
110 "dark-plus",
111 "dracula",
112 "dracula-soft",
113 "everforest-dark",
114 "everforest-light",
115 "github-dark",
116 "github-dark-default",
117 "github-dark-dimmed",
118 "github-dark-high-contrast",
119 "github-light",
120 "github-light-default",
121 "github-light-high-contrast",
122 "gruvbox-dark-hard",
123 "gruvbox-dark-medium",
124 "gruvbox-dark-soft",
125 "gruvbox-light-hard",
126 "gruvbox-light-medium",
127 "gruvbox-light-soft",
128 "houston",
129 "kanagawa-dragon",
130 "kanagawa-lotus",
131 "kanagawa-wave",
132 "laserwave",
133 "light-plus",
134 "material-theme",
135 "material-theme-darker",
136 "material-theme-lighter",
137 "material-theme-ocean",
138 "material-theme-palenight",
139 "min-dark",
140 "min-light",
141 "monokai",
142 "night-owl",
143 "nord",
144 "one-dark-pro",
145 "one-light",
146 "plastic",
147 "poimandres",
148 "red",
149 "rose-pine",
150 "rose-pine-dawn",
151 "rose-pine-moon",
152 "slack-dark",
153 "slack-ochin",
154 "snazzy-light",
155 "solarized-dark",
156 "solarized-light",
157 "synthwave-84",
158 "tokyo-night",
159 "vesper",
160 "vitesse-black",
161 "vitesse-dark",
162 "vitesse-light",
163 ];
164
165 return themeArray.includes(themeNameKebab as BundledTheme);
166 }
167
168 async highlightCode(
169 code: string,
170 language: string = "javascript",
171 currLineOffsetFromTop: number,
172 newDiffLines: DiffLine[],
173 ): Promise<string> {
174 const lines = code.split("\n");
175 const newDiffLineMap = new Set();
176
177 if (newDiffLines) {
178 newDiffLines.forEach((diffLine) => {
179 if (diffLine.type === "new") {
180 newDiffLineMap.add(diffLine.line);
181 }
182 });
183 }
184
185 const annotatedLines = [];
186
187 // NOTE: Shiki's preprocessor deletes transformer annotations when applied to an empty line.
188 // If you are transforming an empty line, make sure that
189 // the transformation is applied to a non-empty line first.
190 for (let i = 0; i < lines.length; i++) {
191 const line = lines[i];
192
193 // Add highlight comment before target line.
194 if (i + 1 === currLineOffsetFromTop && currLineOffsetFromTop >= 0) {
195 annotatedLines.push("// [!code highlight:1]");
196 }
197
198 // Handle diff lines
199 if (newDiffLineMap.has(line)) {
200 if (line.trim() === "") {
201 // For empty lines, add the magic comment on a separate line before.
202 annotatedLines.push("// [!code ++]");
203 annotatedLines.push(line); // The empty line itself.
204 } else {
205 // For non-empty lines, append the magic comment.
206 annotatedLines.push(line + "// [!code ++]");
207 }
208 newDiffLineMap.delete(line);
209 } else {
210 annotatedLines.push(line);
211 }
212 }
213
214 const annotatedCode = annotatedLines.join("\n");
215
216 await this.highlighter!.loadLanguage(language as BundledLanguage);
217 return this.highlighter!.codeToHtml(annotatedCode, {
218 lang: language,
219 theme: this.currentTheme,
220 transformers: [transformerNotationHighlight(), transformerNotationDiff()],
221 });
222 }
223
224 async convertToSVG(
225 code: string,
226 language: string = "javascript",
227 options: ConversionOptions,
228 currLineOffsetFromTop: number,
229 newDiffLines: DiffLine[],
230 ): Promise<Buffer> {
231 const strokeWidth = 1;
232 const highlightedCodeHtml = await this.highlightCode(
233 code,
234 language,
235 currLineOffsetFromTop,
236 newDiffLines,
237 );
238 // console.log(highlightedCodeHtml);
239
240 const { guts, lineBackgrounds } = this.convertShikiHtmlToSvgGut(
241 highlightedCodeHtml,
242 options,
243 );
244 const backgroundColor = this.getBackgroundColor(highlightedCodeHtml);
245
246 const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="${options.dimensions.width}" height="${options.dimensions.height}" shape-rendering="crispEdges">
247 <style>
248 :root {
249 --purple: rgb(112, 114, 209);
250 --green: rgb(136, 194, 163);
251 --blue: rgb(107, 166, 205);
252 }
253 </style>
254 <g>
255 <rect x="0" y="0" rx="10" ry="10" width="${options.dimensions.width}" height="${options.dimensions.height}" fill="${this.editorBackground}" shape-rendering="crispEdges" />
256 ${lineBackgrounds}
257 ${guts}
258 </g>
259 </svg>`;
260 // console.log(svg);
261
262 return Buffer.from(svg, "utf8");
263 }
264
265 convertShikiHtmlToSvgGut(
266 shikiHtml: string,
267 options: ConversionOptions,
268 ): { guts: string; lineBackgrounds: string } {
269 const dom = new JSDOM(shikiHtml);
270 const document = dom.window.document;
271
272 const lines = Array.from(document.querySelectorAll(".line"));
273 const svgLines = lines.map((line, index) => {
274 const spans = Array.from(line.childNodes)
275 .map((node) => {
276 if (node.nodeType === 3) {
277 return `<tspan xml:space="preserve">${escapeForSVG(node.textContent ?? "")}</tspan>`;
278 }
279
280 const el = node as HTMLElement;
281 const style = el.getAttribute("style") || "";
282 const colorMatch = style.match(/color:\s*(#[0-9a-fA-F]{6})/);
283 const classes = el.getAttribute("class") || "";
284 let fill = colorMatch ? ` fill="${colorMatch[1]}"` : "";
285 if (classes.includes("highlighted")) {
286 fill = ` fill="${this.editorLineHighlight}"`;
287 }
288
289 const content = el.textContent || "";
290 return `<tspan xml:space="preserve"${fill}>${escapeForSVG(content)}</tspan>`;
291 })
292 .join("");
293
294 // Typography notes:
295 // Each line of code is a <text> inside a <rect>.
296 // Math becomes interesting here; the y value is actually aligned to the topmost border.
297 // So y = 0 will have the rect be flush with the top border.
298 // More importantly, text will also be positioned that way.
299 // Since y = 0 is the axis the text will align itself to, the default settings will actually have the text sitting "on top of" the y = 0 axis, which effectively shifts them up.
300 // To prevent this, we want the alignment axis to be at the middle of each rect, and have the text align itself vertically to the center (skwered by the axis).
301 // The first step is to add lineHeight / 2 to move the axis down.
302 // The second step is to add 'dominant-baseline="central"' to vertically center the text.
303 // Note that we choose "central" over "middle". "middle" will center the text too perfectly, which is actually undesirable!
304 const y = index * options.lineHeight + options.lineHeight / 2;
305 return `<text x="0" y="${y}" font-family="${options.fontFamily}" font-size="${options.fontSize.toString()}" xml:space="preserve" dominant-baseline="central" shape-rendering="crispEdges">${spans}</text>`;
306 });
307
308 const lineBackgrounds = lines
309 .map((line, index) => {
310 const classes = line?.getAttribute("class") || "";
311 const bgColor = classes.includes("highlighted")
312 ? this.editorLineHighlight
313 : classes.includes("diff add")
314 ? "rgba(255, 255, 0, 0.2)"
315 : this.editorBackground;
316
317 const y = index * options.lineHeight;
318 const isFirst = index === 0;
319 const isLast = index === lines.length - 1;
320 const radius = 10;
321 // SVG notes:
322 // By default SVGs have anti-aliasing on.
323 // This is undesirable in our case because pixel-perfect alignment of these rectangles will introduce thin gaps.
324 // Turning it off with 'shape-rendering="crispEdges"' solves the issue.
325 return isFirst
326 ? `<path d="M ${0} ${y + options.lineHeight}
327 L ${0} ${y + radius}
328 Q ${0} ${y} ${radius} ${y}
329 L ${options.dimensions.width - radius} ${y}
330 Q ${options.dimensions.width} ${y} ${options.dimensions.width} ${y + radius}
331 L ${options.dimensions.width} ${y + options.lineHeight}
332 Z"
333 fill="${bgColor}" />`
334 : isLast
335 ? `<path d="M ${0} ${y}
336 L ${0} ${y + options.lineHeight - radius}
337 Q ${0} ${y + options.lineHeight} ${radius} ${y + options.lineHeight}
338 L ${options.dimensions.width - radius} ${y + options.lineHeight}
339 Q ${options.dimensions.width} ${y + options.lineHeight} ${options.dimensions.width} ${y + options.lineHeight - 10}
340 L ${options.dimensions.width} ${y}
341 Z"
342 fill="${bgColor}" />`
343 : `<rect x="0" y="${y}" width="100%" height="${options.lineHeight}" fill="${bgColor}" shape-rendering="crispEdges" />`;
344 })
345 .join("\n");
346
347 return {
348 guts: svgLines.join("\n"),
349 lineBackgrounds,
350 };
351 }
352
353 getBackgroundColor(shikiHtml: string): string {
354 const dom = new JSDOM(shikiHtml);
355 const document = dom.window.document;
356
357 const preElement = document.querySelector("pre");
358 let backgroundColor = "#333333"; // Default white background
359 if (preElement) {
360 const style = preElement.getAttribute("style") || "";
361 const bgColorMatch = style.match(/background-color:\s*(#[0-9a-fA-F]{6})/);
362 if (bgColorMatch) {
363 backgroundColor = bgColorMatch[1];
364 }
365 }
366
367 return backgroundColor;
368 }
369
370 async getDataUri(
371 code: string,
372 language: string = "javascript",
373 options: ConversionOptions,
374 currLineOffsetFromTop: number,
375 newDiffLines: DiffLine[],
376 ): Promise<DataUri> {
377 switch (options.imageType) {
378 // case "png":
379 // const pngBuffer = await this.convertToPNG(
380 // code,
381 // language,
382 // fontSize,
383 // dimensions,
384 // lineHeight,
385 // options,
386 // );
387 // return `data:image/png;base64,${pngBuffer.data.toString("base64")}`;
388 case "svg":
389 const svgBuffer = await this.convertToSVG(
390 code,
391 language,
392 options,
393 currLineOffsetFromTop,
394 newDiffLines,
395 );
396 return `data:image/svg+xml;base64,${svgBuffer.toString("base64")}`;
397 }
398 }
399}