'use client' import React from 'react' export type UseClipboardCopyOptions = { /** * Duration in milliseconds before the copied state resets. * @default 1000 */ resetDelay?: number /** * Callback function called after successful copy. */ onCopy?: (text: string) => void /** * Callback function called when copy fails. */ onError?: (error: Error) => void } export type UseClipboardCopyReturn = { /** * Whether the text was recently copied to the clipboard. * Resets to `false` after the `resetDelay` duration. */ isCopied: boolean /** * Copies the provided text to the clipboard. * @param text - The text to copy to the clipboard. */ copy: (text: string) => Promise } /** * A hook to copy text to the clipboard with a temporary "copied" state. * * @param options - Configuration options for the clipboard copy behavior. * @returns An object containing `isCopied` state and `copy` function. * * @example * ```tsx * import { useClipboardCopy } from '@chainlink/blocks' * * export const CopyCode = ({ code }: { code: string }) => { * const { isCopied, copy } = useClipboardCopy() * * return ( * * ) * } * ``` * * @example * ```tsx * // With custom options * const { isCopied, copy } = useClipboardCopy({ * resetDelay: 2000, * onCopy: (text) => console.log('Copied:', text), * onError: (error) => console.error('Failed to copy:', error), * }) * ``` */ export const useClipboardCopy = ( options: UseClipboardCopyOptions = {}, ): UseClipboardCopyReturn => { const { resetDelay = 1000, onCopy, onError } = options const [isCopied, setIsCopied] = React.useState(false) const timeoutRef = React.useRef | null>(null) React.useEffect(() => { return () => { if (timeoutRef.current) { clearTimeout(timeoutRef.current) } } }, []) const copy = React.useCallback( async (text: string) => { try { await navigator.clipboard.writeText(text) setIsCopied(true) onCopy?.(text) if (timeoutRef.current) { clearTimeout(timeoutRef.current) } timeoutRef.current = setTimeout(() => { setIsCopied(false) }, resetDelay) } catch (error) { const err = error instanceof Error ? error : new Error(String(error)) onError?.(err) console.error('Failed to copy to clipboard:', err) } }, [resetDelay, onCopy, onError], ) return { isCopied, copy } }