'use client' import { ButtonHTMLAttributes, useEffect, useState } from 'react' import { Check, Copy } from 'lucide-react' import { cn } from '@/utils/cn' type CopyButtonProps = ButtonHTMLAttributes & { textToCopy: string } type CopyState = 'idle' | 'copied' | 'failed' const labels: Record = { idle: 'Copy code', copied: 'Copied!', failed: 'Copy failed', } export function CopyButton({ textToCopy, className, ...props }: CopyButtonProps) { const [state, setState] = useState('idle') useEffect(() => { if (state === 'idle') return const timeout = setTimeout(() => setState('idle'), 2000) return () => clearTimeout(timeout) }, [state]) const handleCopy = async () => { try { await navigator.clipboard.writeText(textToCopy) setState('copied') } catch { setState('failed') } } return ( <> {/* Outside the button: a button's children are presentational, so they aren't announced */} {state === 'idle' ? '' : labels[state]} ) }