import { useCallback, useRef } from "react"; import { useTranslation } from "react-i18next"; import { toast } from "sonner"; import { SaveToast } from "~/components/notifications/SaveToast"; export const COPY_TOAST_DURATION_MS = 4000; export type CopyToastOptions = { /** Headline that names the copied value, for example "Form link copied". */ readonly successKey?: string; /** Plain-language recovery hint for a failed clipboard write. */ readonly errorKey?: string; }; /** * Copies text and reports the browser-confirmed outcome consistently. * * Clipboard writes are one of the few client-only mutations in the product: * there is no route action whose result could drive `useSaveToast`. Keeping * the toast behind the resolved clipboard promise prevents false success. */ export function useCopyToast(): (text: string, options?: CopyToastOptions) => Promise { const { t } = useTranslation(); const latestTranslation = useRef(t); latestTranslation.current = t; return useCallback(async (text: string, options: CopyToastOptions = {}) => { const translate = latestTranslation.current; try { if (!navigator.clipboard?.writeText) throw new Error("Clipboard API unavailable"); await navigator.clipboard.writeText(text); toast.custom(() => , { duration: COPY_TOAST_DURATION_MS, }); return true; } catch { toast.custom( () => ( ), { duration: COPY_TOAST_DURATION_MS } ); return false; } }, []); }