import { useCallback } from "react"; import clsx from "clsx"; import { useAdminContext } from "../context"; type CopyButtonProps = { value: string | number; className?: string; "aria-label"?: string; successMessage?: string; }; const copyFallback = (text: string) => { if (typeof document === "undefined") { throw new Error("Clipboard API недоступен"); } const textarea = document.createElement("textarea"); textarea.value = text; textarea.style.position = "fixed"; textarea.style.top = "-1000px"; textarea.style.left = "-1000px"; document.body.appendChild(textarea); textarea.focus(); textarea.select(); try { document.execCommand("copy"); } finally { document.body.removeChild(textarea); } }; export const CopyButton = ({ value, className, "aria-label": ariaLabel, successMessage }: CopyButtonProps) => { const { pushFlash } = useAdminContext(); const handleCopy = useCallback(async () => { const text = String(value ?? ""); if (!text) { return; } try { if (typeof navigator !== "undefined" && navigator.clipboard?.writeText) { await navigator.clipboard.writeText(text); } else { copyFallback(text); } pushFlash({ type: "success", message: successMessage ?? "Значение скопировано в буфер обмена", }); } catch (error) { pushFlash({ type: "error", message: error instanceof Error ? `Не удалось скопировать: ${error.message}` : "Не удалось скопировать значение", }); } }, [pushFlash, successMessage, value]); return ( ); };