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

code-block.tsx

48 lines1.7 KB

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