52 lines
1.8 KiB
TypeScript
52 lines
1.8 KiB
TypeScript
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<boolean> {
|
|
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(() => <SaveToast variant="success" title={translate(options.successKey ?? "shared.copyToast.successTitle")} />, {
|
|
duration: COPY_TOAST_DURATION_MS,
|
|
});
|
|
return true;
|
|
} catch {
|
|
toast.custom(
|
|
() => (
|
|
<SaveToast
|
|
variant="error"
|
|
title={translate("shared.copyToast.errorTitle")}
|
|
description={translate(options.errorKey ?? "shared.copyToast.errorDescription")}
|
|
/>
|
|
),
|
|
{ duration: COPY_TOAST_DURATION_MS }
|
|
);
|
|
return false;
|
|
}
|
|
}, []);
|
|
}
|