Skip to content

Commit 5e41929

Browse files
committed
feat: build Shiki syntax-highlighted code display server component
1 parent 2876186 commit 5e41929

3 files changed

Lines changed: 391 additions & 0 deletions

File tree

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
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+
}

apps/web/package.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,7 @@
3636
"react": "^19.2.4",
3737
"react-dom": "^19.2.4",
3838
"shadcn": "^4.5.0",
39+
"shiki": "^4.0.2",
3940
"svix": "^1.92.2",
4041
"tailwind-merge": "^3.5.0",
4142
"tw-animate-css": "^1.4.0",

0 commit comments

Comments
 (0)