Become a Pro / website · becomeapro.ai / src / components / mdx / code-block.tsx
| 1 | "use client"; |
| 2 | |
| 3 | import { useRef, useState, type ComponentProps, type ReactElement } from "react"; |
| 4 | import { Check, Copy } from "lucide-react"; |
| 5 | |
| 6 | // <pre> with a copy button, used for every fenced code block in lessons |
| 7 | export 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-md border border-border bg-[var(--soft)] p-4 font-mono text-[14px] leading-relaxed text-foreground ${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 border border-border bg-background px-2 py-1 text-xs" |
| 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 | } |