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