Elffuss BraidHub

kikocis/continue public

3ff29c567dd0 · 13.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 transformerNotationDiff,
13 transformerNotationHighlight,
14} from "@shikijs/transformers";
15import { JSDOM } from "jsdom";
16import {
17 BundledLanguage,
18 BundledTheme,
19 getSingletonHighlighter,
20 Highlighter,
21} from "shiki";
22import { DiffChar, DiffLine } from "..";
23import { escapeForSVG, kebabOfThemeStr } 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(kebabOfThemeStr(themeName)) ||
74 themeName === "Default Dark Modern"
75 ) {
76 this.currentTheme =
77 themeName === "Default Dark Modern"
78 ? "dark-plus"
79 : kebabOfThemeStr(themeName);
80 } else {
81 // Fallback to default theme for unsupported themes.
82 this.currentTheme = "dark-plus";
83 }
84
85 // Always initialize the highlighter with the current theme.
86 this.highlighter = await getSingletonHighlighter({
87 langs: ["typescript"],
88 themes: [this.currentTheme],
89 });
90
91 const th = this.highlighter.getTheme(this.currentTheme);
92 this.editorBackground = th.bg;
93 this.editorForeground = th.fg;
94 this.editorLineHighlight =
95 th.colors!["editor.lineHighlightBackground"] ?? "#000000";
96 }
97
98 async init(): Promise<void> {}
99
100 async close(): Promise<void> {}
101
102 themeExists(themeNameKebab: string): themeNameKebab is BundledTheme {
103 const themeArray: BundledTheme[] = [
104 "andromeeda",
105 "aurora-x",
106 "ayu-dark",
107 "catppuccin-frappe",
108 "catppuccin-latte",
109 "catppuccin-macchiato",
110 "catppuccin-mocha",
111 "dark-plus",
112 "dracula",
113 "dracula-soft",
114 "everforest-dark",
115 "everforest-light",
116 "github-dark",
117 "github-dark-default",
118 "github-dark-dimmed",
119 "github-dark-high-contrast",
120 "github-light",
121 "github-light-default",
122 "github-light-high-contrast",
123 "gruvbox-dark-hard",
124 "gruvbox-dark-medium",
125 "gruvbox-dark-soft",
126 "gruvbox-light-hard",
127 "gruvbox-light-medium",
128 "gruvbox-light-soft",
129 "houston",
130 "kanagawa-dragon",
131 "kanagawa-lotus",
132 "kanagawa-wave",
133 "laserwave",
134 "light-plus",
135 "material-theme",
136 "material-theme-darker",
137 "material-theme-lighter",
138 "material-theme-ocean",
139 "material-theme-palenight",
140 "min-dark",
141 "min-light",
142 "monokai",
143 "night-owl",
144 "nord",
145 "one-dark-pro",
146 "one-light",
147 "plastic",
148 "poimandres",
149 "red",
150 "rose-pine",
151 "rose-pine-dawn",
152 "rose-pine-moon",
153 "slack-dark",
154 "slack-ochin",
155 "snazzy-light",
156 "solarized-dark",
157 "solarized-light",
158 "synthwave-84",
159 "tokyo-night",
160 "vesper",
161 "vitesse-black",
162 "vitesse-dark",
163 "vitesse-light",
164 ];
165
166 return themeArray.includes(themeNameKebab as BundledTheme);
167 }
168
169 async highlightCode(
170 code: string,
171 language: string = "javascript",
172 currLineOffsetFromTop: number,
173 newDiffLines: DiffLine[],
174 ): Promise<string> {
175 const lines = code.split("\n");
176 const newDiffLineMap = new Set();
177
178 if (newDiffLines) {
179 newDiffLines.forEach((diffLine) => {
180 if (diffLine.type === "new") {
181 newDiffLineMap.add(diffLine.line);
182 }
183 });
184 }
185
186 const annotatedLines = [];
187
188 // NOTE: Shiki's preprocessor deletes transformer annotations when applied to an empty line.
189 // If you are transforming an empty line, make sure that
190 // the transformation is applied to a non-empty line first.
191 for (let i = 0; i < lines.length; i++) {
192 const line = lines[i];
193
194 // Add highlight comment before target line.
195 if (i + 1 === currLineOffsetFromTop && currLineOffsetFromTop >= 0) {
196 annotatedLines.push("// [!code highlight:1]");
197 }
198
199 // Handle diff lines
200 if (newDiffLineMap.has(line)) {
201 if (line.trim() === "") {
202 // For empty lines, add the magic comment on a separate line before.
203 annotatedLines.push("// [!code ++]");
204 annotatedLines.push(line); // The empty line itself.
205 } else {
206 // For non-empty lines, append the magic comment.
207 annotatedLines.push(line + "// [!code ++]");
208 }
209 newDiffLineMap.delete(line);
210 } else {
211 annotatedLines.push(line);
212 }
213 }
214
215 const annotatedCode = annotatedLines.join("\n");
216
217 await this.highlighter!.loadLanguage(language as BundledLanguage);
218 return this.highlighter!.codeToHtml(annotatedCode, {
219 lang: language,
220 theme: this.currentTheme,
221 transformers: [transformerNotationHighlight(), transformerNotationDiff()],
222 });
223 }
224
225 async convertToSVG(
226 code: string,
227 language: string = "javascript",
228 options: ConversionOptions,
229 currLineOffsetFromTop: number,
230 newDiffLines: DiffLine[],
231 newDiffChars: DiffChar[],
232 ): Promise<Buffer> {
233 const strokeWidth = 1;
234 const highlightedCodeHtml = await this.highlightCode(
235 code,
236 language,
237 currLineOffsetFromTop,
238 newDiffLines,
239 );
240
241 const { guts, lineBackgrounds } = this.convertShikiHtmlToSvgGut(
242 highlightedCodeHtml,
243 options,
244 newDiffChars,
245 );
246 const backgroundColor = this.getBackgroundColor(highlightedCodeHtml);
247 const borderColor = "#6b6b6b";
248
249 const lines = code.split("\n");
250 const actualHeight = lines.length * options.lineHeight;
251
252 const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="${options.dimensions.width}" height="${actualHeight}" shape-rendering="crispEdges">
253 <style>
254 :root {
255 --purple: rgb(112, 114, 209);
256 --green: rgb(136, 194, 163);
257 --blue: rgb(107, 166, 205);
258 }
259 </style>
260 <g>
261 <rect x="0" y="0" rx="2" ry="2" width="${options.dimensions.width}" height="${actualHeight}" fill="${backgroundColor}" stroke="${borderColor}" stroke-width="${strokeWidth}" shape-rendering="crispEdges" />
262 ${lineBackgrounds}
263 ${guts}
264 </g>
265 </svg>`;
266
267 return Buffer.from(svg, "utf8");
268 }
269
270 convertShikiHtmlToSvgGut(
271 shikiHtml: string,
272 options: ConversionOptions,
273 diffChars: DiffChar[],
274 ): { guts: string; lineBackgrounds: string } {
275 const dom = new JSDOM(shikiHtml);
276 const document = dom.window.document;
277
278 const lines = Array.from(document.querySelectorAll(".line"));
279
280 const additionSegmentsByLine = new Map<
281 number,
282 Array<{ start: number; end: number }>
283 >();
284
285 diffChars.forEach((diff) => {
286 if (
287 diff.type !== "new" ||
288 diff.newLineIndex === undefined ||
289 diff.newCharIndexInLine === undefined
290 ) {
291 return;
292 }
293
294 if (diff.char.includes("\n")) {
295 return;
296 }
297
298 const start = diff.newCharIndexInLine;
299 const end = start + diff.char.length;
300 const existing = additionSegmentsByLine.get(diff.newLineIndex) ?? [];
301 existing.push({ start, end });
302 additionSegmentsByLine.set(diff.newLineIndex, existing);
303 });
304
305 additionSegmentsByLine.forEach((segments, lineIndex) => {
306 segments.sort((a, b) => a.start - b.start);
307 const merged: Array<{ start: number; end: number }> = [];
308 segments.forEach((segment) => {
309 if (merged.length === 0) {
310 merged.push({ ...segment });
311 return;
312 }
313
314 const last = merged[merged.length - 1];
315 if (segment.start <= last.end) {
316 last.end = Math.max(last.end, segment.end);
317 } else {
318 merged.push({ ...segment });
319 }
320 });
321 additionSegmentsByLine.set(lineIndex, merged);
322 });
323 const svgLines = lines.map((line, index) => {
324 const spans = Array.from(line.childNodes)
325 .map((node) => {
326 if (node.nodeType === 3) {
327 return `<tspan xml:space="preserve">${escapeForSVG(node.textContent ?? "")}</tspan>`;
328 }
329
330 const el = node as HTMLElement;
331 const style = el.getAttribute("style") || "";
332 const colorMatch = style.match(/color:\s*(#[0-9a-fA-F]{6})/);
333 const classes = el.getAttribute("class") || "";
334 let fill = colorMatch ? ` fill="${colorMatch[1]}"` : "";
335 if (classes.includes("highlighted")) {
336 fill = ` fill="${this.editorLineHighlight}"`;
337 }
338
339 const content = el.textContent || "";
340 return `<tspan xml:space="preserve"${fill}>${escapeForSVG(content)}</tspan>`;
341 })
342 .join("");
343
344 // Typography notes:
345 // Each line of code is a <text> inside a <rect>.
346 // Math becomes interesting here; the y value is actually aligned to the topmost border.
347 // So y = 0 will have the rect be flush with the top border.
348 // More importantly, text will also be positioned that way.
349 // 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.
350 // 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).
351 // The first step is to add lineHeight / 2 to move the axis down.
352 // The second step is to add 'dominant-baseline="central"' to vertically center the text.
353 // Note that we choose "central" over "middle". "middle" will center the text too perfectly, which is actually undesirable!
354 const y = index * options.lineHeight + options.lineHeight / 2;
355 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>`;
356 });
357
358 const estimatedCharWidth = options.fontSize * 0.6;
359 const additionFill = "rgba(40, 167, 69, 0.25)";
360
361 const lineBackgrounds = lines
362 .map((line, index) => {
363 const classes = line?.getAttribute("class") || "";
364 const y = index * options.lineHeight;
365 const segments = additionSegmentsByLine.get(index) ?? [];
366 const backgrounds: string[] = [];
367
368 if (classes.includes("highlighted")) {
369 backgrounds.push(
370 `<rect x="0" y="${y}" width="100%" height="${options.lineHeight}" fill="${this.editorLineHighlight}" shape-rendering="crispEdges" />`,
371 );
372 }
373
374 segments.forEach(({ start, end }) => {
375 const widthInChars = Math.max(end - start, 0);
376 if (widthInChars <= 0) {
377 return;
378 }
379 const x = start * estimatedCharWidth;
380 const segmentWidth = widthInChars * estimatedCharWidth;
381 backgrounds.push(
382 `<rect x="${x}" y="${y}" width="${segmentWidth}" height="${options.lineHeight}" fill="${additionFill}" shape-rendering="crispEdges" />`,
383 );
384 });
385
386 return backgrounds.join("\n");
387 })
388 .filter((bg) => bg.length > 0)
389 .join("\n");
390
391 return {
392 guts: svgLines.join("\n"),
393 lineBackgrounds,
394 };
395 }
396
397 getBackgroundColor(shikiHtml: string): string {
398 const dom = new JSDOM(shikiHtml);
399 const document = dom.window.document;
400
401 const preElement = document.querySelector("pre");
402 let backgroundColor = "#333333"; // Default white background
403 if (preElement) {
404 const style = preElement.getAttribute("style") || "";
405 const bgColorMatch = style.match(/background-color:\s*(#[0-9a-fA-F]{6})/);
406 if (bgColorMatch) {
407 backgroundColor = bgColorMatch[1];
408 }
409 }
410
411 return backgroundColor;
412 }
413
414 async getDataUri(
415 code: string,
416 language: string = "javascript",
417 options: ConversionOptions,
418 currLineOffsetFromTop: number,
419 newDiffLines: DiffLine[],
420 newDiffChars: DiffChar[],
421 ): Promise<DataUri> {
422 switch (options.imageType) {
423 // case "png":
424 // const pngBuffer = await this.convertToPNG(
425 // code,
426 // language,
427 // fontSize,
428 // dimensions,
429 // lineHeight,
430 // options,
431 // );
432 // return `data:image/png;base64,${pngBuffer.data.toString("base64")}`;
433 case "svg":
434 const svgBuffer = await this.convertToSVG(
435 code,
436 language,
437 options,
438 currLineOffsetFromTop,
439 newDiffLines,
440 newDiffChars,
441 );
442 return `data:image/svg+xml;base64,${svgBuffer.toString("base64")}`;
443 }
444 }
445}