| 6 | import { copyToClipboard } from "../lib/clipboard"; |
| 7 | |
| 8 | function CopyButton({ |
| 9 | value, |
| 10 | label, |
| 11 | className, |
| 12 | onCopy, |
| 13 | }: { |
| 14 | value: string; |
| 15 | label?: string; |
| 16 | className?: string; |
| 17 | /** Fires after a successful copy. Receives nothing — the copied value may be sensitive. */ |
| 18 | onCopy?: () => void; |
| 19 | }) { |
| 20 | const [copied, setCopied] = useState(false); |
| 21 | |
| 22 | const handleCopy = () => { |
| 23 | void copyToClipboard(value).then((ok) => { |
| 24 | if (!ok) { |
| 25 | toast.error("Failed to copy to clipboard"); |
| 26 | return; |
| 27 | } |
| 28 | setCopied(true); |
| 29 | onCopy?.(); |
| 30 | setTimeout(() => setCopied(false), 1500); |
| 31 | }); |
| 32 | }; |
| 33 | |
| 34 | if (label) { |
| 35 | return ( |
| 36 | <Button |
| 37 | variant="ghost" |
| 38 | size="xs" |
| 39 | onClick={handleCopy} |
| 40 | className={cn("text-muted-foreground", className)} |
| 41 | title={label} |
| 42 | > |
| 43 | {copied ? <Check /> : <Copy />} |
| 44 | {copied ? "Copied" : label} |
| 45 | </Button> |
| 46 | ); |
| 47 | } |
| 48 | |
| 49 | return ( |
| 50 | <Button |
| 51 | variant="ghost" |
| 52 | size="icon-xs" |
| 53 | onClick={handleCopy} |
| 54 | className={cn("shrink-0 text-muted-foreground", className)} |
| 55 | title="Copy" |
| 56 | > |
| 57 | {copied ? <Check /> : <Copy />} |
| 58 | </Button> |
| 59 | ); |
| 60 | } |
| 61 | |
| 62 | export { CopyButton }; |