Elffuss BraidHub

kikocis/continue public

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