File size: 1,199 Bytes
1f21206 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 | import { useEffect, useState } from 'react'
import { copyTextToClipboard } from '../chat/clipboard'
type Props = {
text: string
label?: string
copiedLabel?: string
displayLabel?: string
displayCopiedLabel?: string
className?: string
}
export function CopyButton({
text,
label = 'Copy',
copiedLabel = 'Copied',
displayLabel,
displayCopiedLabel,
className = '',
}: Props) {
const [copied, setCopied] = useState(false)
useEffect(() => {
if (!copied) return
const timer = window.setTimeout(() => setCopied(false), 1500)
return () => window.clearTimeout(timer)
}, [copied])
const handleCopy = async () => {
try {
const ok = await copyTextToClipboard(text)
if (!ok) {
setCopied(false)
return
}
setCopied(true)
} catch {
setCopied(false)
}
}
const currentLabel = copied ? copiedLabel : label
const buttonText = copied
? (displayCopiedLabel ?? copiedLabel)
: (displayLabel ?? label)
return (
<button
type="button"
onClick={handleCopy}
className={className}
aria-label={currentLabel}
title={currentLabel}
>
{buttonText}
</button>
)
}
|