import { useCallback, useEffect, useRef, useState } from 'react'; import { copyToClipboard } from '../clipboard'; /** How long the "Copied" state stays visible after a successful copy. */ export const COPY_FEEDBACK_MS = 2000; /** The key a copy is marked under when the caller names none. */ const DEFAULT_COPY_KEY = 'default'; /** * Copy-to-clipboard with a timed "copied" indicator. Several copy targets on * one screen are told apart by their keys: ``copiedKey`` holds the key of * the most recent successful copy until the feedback window elapses. * * @return {{ copiedKey: string | null, copy: (text: string, key?: string) => Promise }} * The key copied last (null when idle) and the copy trigger. */ export function useCopyFeedback(): { copiedKey: string | null; copy: (text: string, key?: string) => Promise; } { const [copiedKey, setCopiedKey] = useState(null); const timerRef = useRef | null>(null); useEffect(() => { return () => { if (timerRef.current) clearTimeout(timerRef.current); }; }, []); const copy = useCallback(async (text: string, key = DEFAULT_COPY_KEY) => { const isCopied = await copyToClipboard(text); if (!isCopied) return false; setCopiedKey(key); if (timerRef.current) clearTimeout(timerRef.current); timerRef.current = setTimeout(() => setCopiedKey(null), COPY_FEEDBACK_MS); return true; }, []); return { copiedKey, copy }; }