Skip to content
Source
Sign inSign up
fuko/trytanstackdb-v2
Open History to see the last commit

code-block.tsx

56 lines2.0 KB

1import { Check, Copy } from "lucide-react";
2import { useMemo, useState } from "react";
3import { highlight } from "sugar-high";
4​
5import { cn } from "@/lib/utils";
6​
7import { withLineIndents } from "./code-lines";
8​
9interface CodeBlockProps {
10 code: string;
11 /** Shown in the header, e.g. `src/collections/notes.ts`. */
12 filename?: string;
13 className?: string;
15​
16export function CodeBlock({ code, filename, className }: CodeBlockProps) {
17 const html = useMemo(() => {
18 const source = code.trim();
19 return withLineIndents(highlight(source), source);
20 }, [code]);
21 const [copied, setCopied] = useState(false);
22​
23 async function copy() {
24 await navigator.clipboard.writeText(code.trim());
25 setCopied(true);
26 setTimeout(() => setCopied(false), 1500);
27 }
28​
29 return (
30 <figure
31 className={cn(
32 "group/code my-5 overflow-hidden rounded-xl border bg-muted/40 dark:bg-white/[0.03]",
33 className,
34 )}
35 >
36 <figcaption className="flex h-9 items-center justify-between gap-2 border-b px-4 font-mono text-xs text-muted-foreground">
37 <span className="min-w-0 truncate" title={filename}>
38 {filename ?? "example.ts"}
39 </span>
40 <button
41 type="button"
42 onClick={copy}
43 className="code-block-copy flex shrink-0 items-center gap-1 rounded-md px-1.5 py-1 opacity-0 transition-opacity group-hover/code:opacity-100 hover:bg-muted focus-visible:opacity-100"
44 aria-label="Copy code"
45 >
46 {copied ? <Check className="size-3.5" /> : <Copy className="size-3.5" />}
47 </button>
48 </figcaption>
49 <pre className="code-block-pre notes-scroll overflow-x-auto px-4 py-3.5 font-mono text-[12.5px] leading-relaxed">
50 {/* sugar-high only emits <span>s with colour variables, from our own static snippets.
51 Copy uses `code`, so wrapped lines (small screens) are copied unwrapped. */}
52 <code dangerouslySetInnerHTML={{ __html: html }} />
53 </pre>
54 </figure>
55 );