"use client"; import * as React from "react"; import { CheckIcon, CircleAlertIcon, CopyIcon } from "lucide-react"; import { Button } from "./button"; import { useComponentLabels } from "./component-labels"; import { cn } from "../lib/cn"; export interface CodeBlockProps { /** What the code is: "Selettore". Shown above it, and part of the copy * button's name. */ label: string; code: string; /** "Copia" and "Copiato" in the page's language by default. */ copyLabel?: string; copiedLabel?: string; /** What it says, under the block, when the browser refuses the copy. */ copyFailedLabel?: string; className?: string; } /** How long the button says it has copied. */ const COPIED_FOR_MS = 2000; // The design system's CodeBlock: code to copy exactly as it is (the snippet // of a problem, a selector, the code that embeds the statement), on navy in // monospace, under its label and beside a button that copies it. // // The button's name carries the label ("Copia: Selettore"), so several blocks // on one page stay distinct. Once it has copied it says so for two seconds: // with a check and "Copiato" for the eye, and through a status line for // assistive technology, which is not told when a button changes its name. // The block takes the keyboard's focus, so a long snippet can be read through. // A copy the browser refuses is said too, under the block (ACC-536): the // button that only failed to answer left the person thinking the code was // on the clipboard. function CodeBlock({ label, code, copyLabel, copiedLabel, copyFailedLabel, className, }: CodeBlockProps) { const id = React.useId(); const labels = useComponentLabels(); const [copied, setCopied] = React.useState(false); const [failed, setFailed] = React.useState(false); const timer = React.useRef | null>(null); React.useEffect( () => () => { if (timer.current) clearTimeout(timer.current); }, [], ); const copy = async () => { try { await navigator.clipboard.writeText(code); } catch { // The clipboard can be refused, or missing on a page not served over // HTTPS; the code stays there to select by hand, and the block says so. setCopied(false); setFailed(true); return; } setFailed(false); setCopied(true); if (timer.current) clearTimeout(timer.current); timer.current = setTimeout(() => { timer.current = null; setCopied(false); }, COPIED_FOR_MS); }; const word = copied ? (copiedLabel ?? labels.copied) : (copyLabel ?? labels.copy); return (
{label}
        {code}
      
{failed && (

)} {copied ? `${word}: ${label}` : failed ? (copyFailedLabel ?? labels.copyFailed) : ""}
); } export { CodeBlock };