Branchwell

AI Resource Pro / website · airesourcepro.com / src / components / mdx / code-block.tsx

Raw 1.6 KB on b7854f3692d64213a2fce644d0b5101d3e345b03
1"use client";
2
3import { useRef, useState, type ComponentProps, type ReactElement } from "react";
4import { Check, Copy } from "lucide-react";
5
6// <pre> with a copy button, used for every fenced code block in tutorials
7export function CodeBlock(props: ComponentProps<"pre">) {
8 const ref = useRef<HTMLPreElement>(null);
9 const [copied, setCopied] = useState(false);
10
11 // ```prompt fences hold a sentence to paste into an agent, so they wrap
12 const child = props.children as ReactElement<{ className?: string }> | undefined;
13 const isPrompt = child?.props?.className === "language-prompt";
14
15 const copy = async () => {
16 await navigator.clipboard.writeText(ref.current?.innerText ?? "");
17 setCopied(true);
18 setTimeout(() => setCopied(false), 1500);
19 };
20
21 return (
22 <div className="group relative my-6">
23 <pre
24 ref={ref}
25 {...props}
26 className={`overflow-x-auto rounded-xl border border-border bg-[var(--code-bg)] p-5 font-mono text-[13.5px] leading-relaxed text-[var(--code-fg)] ${isPrompt ? "whitespace-pre-wrap pr-20 [&>code]:whitespace-pre-wrap" : ""}`}
27 />
28 <button
29 onClick={copy}
30 className={`absolute right-2 top-2 inline-flex items-center gap-1 rounded-md border border-white/10 bg-white/5 px-2 py-1 text-xs text-white/70 transition-opacity hover:text-white focus:opacity-100 group-hover:opacity-100 ${isPrompt ? "" : "opacity-0"}`}
31 aria-label="Copy code"
32 >
33 {copied ? <Check className="h-3.5 w-3.5" /> : <Copy className="h-3.5 w-3.5" />}
34 {copied ? "Copied" : "Copy"}
35 </button>
36 </div>
37 );
38}