import { useState, useCallback, useRef, useEffect, memo } from 'react'; import { sleep } from 'timing-functions'; import ButtonComponent, { type ButtonProps } from './button'; type Props = { /** * The text to place into the copy buffer */ textToCopy: string; /** * The text placed in the button before copy event */ beforeCopy?: string; /** * The text placed in the button after copy event */ afterCopy?: string; onCopy?: (copied: string) => void; }; const CopyToClipboard = memo( ({ textToCopy, beforeCopy = 'Copy', afterCopy = 'Copied', onCopy, ...props }: Props & Omit) => { const [copied, setCopied] = useState(false); const copyPromiseRef = useRef | null>(null); useEffect(() => { setCopied(false); return () => { // Clear any potential ongoing promise on changing value or unmounting copyPromiseRef.current = null; }; }, [textToCopy]); const handleClick = useCallback(() => { const p = navigator.clipboard .writeText(textToCopy) .then(() => { if (copyPromiseRef.current === p) { // Display copied for 10 seconds setCopied(true); onCopy?.(textToCopy); return sleep(10000); } return null; }) .then(() => { if (copyPromiseRef.current === p) { setCopied(false); } }); copyPromiseRef.current = p; }, [onCopy, textToCopy]); if (!('clipboard' in navigator) || !('writeText' in navigator.clipboard)) { return null; } return ( {copied ? afterCopy : beforeCopy} ); } ); export default CopyToClipboard;