Elffuss BraidHub

kikocis/continue public

4e3281ed77e4 · 13.2 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 lines = code.split("\n");
247 const actualHeight = lines.length * options.lineHeight;
248
249 const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="${options.dimensions.width}" height="${actualHeight}" shape-rendering="crispEdges">
250 <style>
251 :root {
252 --purple: rgb(112, 114, 209);
253 --green: rgb(136, 194, 163);
254 --blue: rgb(107, 166, 205);
255 }
256 </style>
257 <g>
258 <rect x="0" y="0" rx="10" ry="10" width="${options.dimensions.width}" height="${actualHeight}" fill="${this.editorBackground}" shape-rendering="crispEdges" />
259 ${lineBackgrounds}
260 ${guts}
261 </g>
262 </svg>`;
263 // console.log(svg);
264
265 return Buffer.from(svg, "utf8");
266 }
267
268 convertShikiHtmlToSvgGut(
269 shikiHtml: string,
270 options: ConversionOptions,
271 ): { guts: string; lineBackgrounds: string } {
272 const dom = new JSDOM(shikiHtml);
273 const document = dom.window.document;
274
275 const lines = Array.from(document.querySelectorAll(".line"));
276 const svgLines = lines.map((line, index) => {
277 const spans = Array.from(line.childNodes)
278 .map((node) => {
279 if (node.nodeType === 3) {
280 return `<tspan xml:space="preserve">${escapeForSVG(node.textContent ?? "")}</tspan>`;
281 }
282
283 const el = node as HTMLElement;
284 const style = el.getAttribute("style") || "";
285 const colorMatch = style.match(/color:\s*(#[0-9a-fA-F]{6})/);
286 const classes = el.getAttribute("class") || "";
287 let fill = colorMatch ? ` fill="${colorMatch[1]}"` : "";
288 if (classes.includes("highlighted")) {
289 fill = ` fill="${this.editorLineHighlight}"`;
290 }
291
292 const content = el.textContent || "";
293 return `<tspan xml:space="preserve"${fill}>${escapeForSVG(content)}</tspan>`;
294 })
295 .join("");
296
297 // Typography notes:
298 // Each line of code is a <text> inside a <rect>.
299 // Math becomes interesting here; the y value is actually aligned to the topmost border.
300 // So y = 0 will have the rect be flush with the top border.
301 // More importantly, text will also be positioned that way.
302 // 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.
303 // 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).
304 // The first step is to add lineHeight / 2 to move the axis down.
305 // The second step is to add 'dominant-baseline="central"' to vertically center the text.
306 // Note that we choose "central" over "middle". "middle" will center the text too perfectly, which is actually undesirable!
307 const y = index * options.lineHeight + options.lineHeight / 2;
308 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>`;
309 });
310
311 const lineBackgrounds = lines
312 .map((line, index) => {
313 const classes = line?.getAttribute("class") || "";
314 const bgColor = classes.includes("highlighted")
315 ? this.editorLineHighlight
316 : classes.includes("diff add")
317 ? "rgba(255, 255, 0, 0.2)"
318 : this.editorBackground;
319
320 const y = index * options.lineHeight;
321 const isFirst = index === 0;
322 const isLast = index === lines.length - 1;
323 const isSingleLine = isFirst && isLast;
324 const radius = 10;
325
326 // Handle single line case (both first and last)
327 if (isSingleLine) {
328 return `<path d="M ${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 - radius}
332 Q ${options.dimensions.width} ${y + options.lineHeight} ${options.dimensions.width - radius} ${y + options.lineHeight}
333 L ${radius} ${y + options.lineHeight}
334 Q ${0} ${y + options.lineHeight} ${0} ${y + options.lineHeight - radius}
335 L ${0} ${y + radius}
336 Q ${0} ${y} ${radius} ${y}
337 Z"
338 fill="${bgColor}" />`;
339 }
340
341 // SVG notes:
342 // By default SVGs have anti-aliasing on.
343 // This is undesirable in our case because pixel-perfect alignment of these rectangles will introduce thin gaps.
344 // Turning it off with 'shape-rendering="crispEdges"' solves the issue.
345 return isFirst
346 ? `<path d="M ${0} ${y + options.lineHeight}
347 L ${0} ${y + radius}
348 Q ${0} ${y} ${radius} ${y}
349 L ${options.dimensions.width - radius} ${y}
350 Q ${options.dimensions.width} ${y} ${options.dimensions.width} ${y + radius}
351 L ${options.dimensions.width} ${y + options.lineHeight}
352 Z"
353 fill="${bgColor}" />`
354 : isLast
355 ? `<path d="M ${0} ${y}
356 L ${0} ${y + options.lineHeight - radius}
357 Q ${0} ${y + options.lineHeight} ${radius} ${y + options.lineHeight}
358 L ${options.dimensions.width - radius} ${y + options.lineHeight}
359 Q ${options.dimensions.width} ${y + options.lineHeight} ${options.dimensions.width} ${y + options.lineHeight - 10}
360 L ${options.dimensions.width} ${y}
361 Z"
362 fill="${bgColor}" />`
363 : `<rect x="0" y="${y}" width="100%" height="${options.lineHeight}" fill="${bgColor}" shape-rendering="crispEdges" />`;
364 })
365 .join("\n");
366
367 return {
368 guts: svgLines.join("\n"),
369 lineBackgrounds,
370 };
371 }
372
373 getBackgroundColor(shikiHtml: string): string {
374 const dom = new JSDOM(shikiHtml);
375 const document = dom.window.document;
376
377 const preElement = document.querySelector("pre");
378 let backgroundColor = "#333333"; // Default white background
379 if (preElement) {
380 const style = preElement.getAttribute("style") || "";
381 const bgColorMatch = style.match(/background-color:\s*(#[0-9a-fA-F]{6})/);
382 if (bgColorMatch) {
383 backgroundColor = bgColorMatch[1];
384 }
385 }
386
387 return backgroundColor;
388 }
389
390 async getDataUri(
391 code: string,
392 language: string = "javascript",
393 options: ConversionOptions,
394 currLineOffsetFromTop: number,
395 newDiffLines: DiffLine[],
396 ): Promise<DataUri> {
397 switch (options.imageType) {
398 // case "png":
399 // const pngBuffer = await this.convertToPNG(
400 // code,
401 // language,
402 // fontSize,
403 // dimensions,
404 // lineHeight,
405 // options,
406 // );
407 // return `data:image/png;base64,${pngBuffer.data.toString("base64")}`;
408 case "svg":
409 const svgBuffer = await this.convertToSVG(
410 code,
411 language,
412 options,
413 currLineOffsetFromTop,
414 newDiffLines,
415 );
416 return `data:image/svg+xml;base64,${svgBuffer.toString("base64")}`;
417 }
418 }
419}