RotNot / src /components /coding /code-block.tsx
deploy
Deploy RotNot
9580dce
Raw History Blame Contribute Delete
2.13 kB
"use client";
import { tokenize, type TokenKind } from "@/lib/coding/highlight";
import type { CodingLanguage } from "@/lib/coding/types";
const KIND_COLOR: Record<TokenKind, string> = {
keyword: "#c792ea",
string: "#c3e88d",
comment: "#677a8e",
number: "#f78c6c",
plain: "var(--text-primary)",
};
interface LineFragment {
text: string;
kind: TokenKind;
}
/** Split the token stream into per-line fragment arrays (keeps line numbers). */
function toLines(code: string, language: CodingLanguage): LineFragment[][] {
const tokens = tokenize(code, language);
const lines: LineFragment[][] = [[]];
for (const tok of tokens) {
const parts = tok.text.split("\n");
parts.forEach((part, i) => {
if (i > 0) lines.push([]);
if (part.length > 0) {
lines[lines.length - 1].push({ text: part, kind: tok.kind });
}
});
}
return lines;
}
export function CodeBlock({
code,
language,
testId = "code-block",
}: {
code: string;
language: CodingLanguage;
testId?: string;
}) {
const lines = toLines(code.replace(/\n$/, ""), language);
return (
<div
data-testid={testId}
className="rounded-lg overflow-x-auto text-sm font-mono leading-relaxed"
style={{ background: "rgba(10,14,20,0.7)", border: "1px solid rgba(255,255,255,0.08)" }}
>
<pre className="p-0 m-0">
<code>
{lines.map((frags, i) => (
<div key={i} className="flex">
<span
className="select-none text-right pr-3 pl-3 shrink-0"
style={{ color: "rgba(255,255,255,0.25)", minWidth: "3rem" }}
>
{i + 1}
</span>
<span className="pr-4 whitespace-pre">
{frags.length === 0 ? (
" "
) : (
frags.map((f, j) => (
<span key={j} style={{ color: KIND_COLOR[f.kind] }}>
{f.text}
</span>
))
)}
</span>
</div>
))}
</code>
</pre>
</div>
);
}