"use client"; import ReactMarkdown from "react-markdown"; import remarkGfm from "remark-gfm"; import rehypeHighlight from "rehype-highlight"; import { useEffect, useState } from "react"; import { codeToHtml } from "shiki"; export function CodeViewer({ content, language, showLineNumbers = false }: { content: string; language: string; showLineNumbers?: boolean }) { const [highlightedCode, setHighlightedCode] = useState(null); useEffect(() => { if (language === "markdown" || language === "md") return; async function highlight() { try { const html = await codeToHtml(content, { lang: language === "text" ? "plaintext" : language, theme: "github-dark-default", }); setHighlightedCode(html); } catch { setHighlightedCode(null); } } highlight(); }, [content, language]); if (language === "markdown" || language === "md") { return (
{content}
); } if (highlightedCode) { const lines = content.split("\n"); return (
{showLineNumbers && (
{lines.map((_, i) => (
{i + 1}
))}
)}
); } const lines = content.split("\n"); return (
{lines.map((line, i) => ( {showLineNumbers && ( )} ))}
{i + 1}{line || " "}
); }