|
| 1 | +// Server Component — no "use client" |
| 2 | +import { codeToHtml } from "shiki" |
| 3 | +import { cn } from "@/lib/utils" |
| 4 | + |
| 5 | +interface CodeDisplayProps { |
| 6 | + code: string |
| 7 | + language: string |
| 8 | + className?: string |
| 9 | +} |
| 10 | + |
| 11 | +// Maps our internal language names to Shiki bundle language IDs |
| 12 | +function toShikiLang(lang: string): string { |
| 13 | + const map: Record<string, string> = { |
| 14 | + typescript: "typescript", |
| 15 | + javascript: "javascript", |
| 16 | + python: "python", |
| 17 | + css: "css", |
| 18 | + html: "html", |
| 19 | + json: "json", |
| 20 | + bash: "bash", |
| 21 | + sh: "bash", |
| 22 | + shell: "bash", |
| 23 | + sql: "sql", |
| 24 | + markdown: "markdown", |
| 25 | + md: "markdown", |
| 26 | + other: "text", |
| 27 | + } |
| 28 | + return map[lang.toLowerCase()] ?? "text" |
| 29 | +} |
| 30 | + |
| 31 | +export async function CodeDisplay({ code, language, className }: CodeDisplayProps) { |
| 32 | + let html: string |
| 33 | + |
| 34 | + try { |
| 35 | + html = await codeToHtml(code, { |
| 36 | + lang: toShikiLang(language), |
| 37 | + theme: "github-dark", |
| 38 | + }) |
| 39 | + } catch { |
| 40 | + // Fallback: render as plain text if language is unsupported |
| 41 | + html = await codeToHtml(code, { lang: "text", theme: "github-dark" }) |
| 42 | + } |
| 43 | + |
| 44 | + return ( |
| 45 | + <div |
| 46 | + className={cn( |
| 47 | + // Shiki wraps output in <pre><code> — style them here |
| 48 | + "[&_pre]:m-0 [&_pre]:overflow-x-auto", |
| 49 | + "[&_pre]:p-5 [&_pre]:text-sm [&_pre]:leading-[1.65]", |
| 50 | + "[&_pre]:font-[family-name:var(--font-mono,ui-monospace,monospace)]", |
| 51 | + "[&_pre]:[font-variant-numeric:tabular-nums]", |
| 52 | + // Let shiki control the background color via its theme |
| 53 | + className, |
| 54 | + )} |
| 55 | + // biome-ignore lint: shiki output is trusted server-side HTML |
| 56 | + dangerouslySetInnerHTML={{ __html: html }} |
| 57 | + /> |
| 58 | + ) |
| 59 | +} |
0 commit comments