File size: 2,133 Bytes
9580dce
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
"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>
  );
}