copy-button.tsx
863 bytes
| 1 | 'use client'; |
|---|---|
| 2 | |
| 3 | import { Check, Copy } from 'lucide-react'; |
| 4 | import { useState } from 'react'; |
| 5 | import { Button } from '@/components/ui/button'; |
| 6 | import { cn } from '@/lib/utils'; |
| 7 | |
| 8 | export function CopyButton({ |
| 9 | text, |
| 10 | label = 'Copy', |
| 11 | className, |
| 12 | }: { |
| 13 | text: string; |
| 14 | label?: string; |
| 15 | className?: string; |
| 16 | }) { |
| 17 | const [copied, setCopied] = useState(false); |
| 18 | |
| 19 | const onCopy = async () => { |
| 20 | try { |
| 21 | await navigator.clipboard.writeText(text); |
| 22 | setCopied(true); |
| 23 | setTimeout(() => setCopied(false), 1500); |
| 24 | } catch { |
| 25 | /* clipboard unavailable (insecure context) */ |
| 26 | } |
| 27 | }; |
| 28 | |
| 29 | return ( |
| 30 | <Button variant="ghost" size="sm" className={cn('gap-1.5', className)} onClick={onCopy} aria-label={label}> |
| 31 | {copied ? <Check className="h-3.5 w-3.5" /> : <Copy className="h-3.5 w-3.5" />} |
| 32 | {copied ? 'Copied' : label} |
| 33 | </Button> |
| 34 | ); |
| 35 | } |
| 36 | |