import { toast } from "sonner" /** * Скопировать текст в буфер. navigator.clipboard есть только в защищённом контексте (https, localhost); * открыто по http в локальной сети или нет разрешения — запасной путь через скрытое поле и execCommand. */ export async function copyText(text: string): Promise { if (navigator.clipboard && window.isSecureContext) { try { return await navigator.clipboard.writeText(text) } catch { // нет разрешения на буфер — пробуем по-старому } } const active = document.activeElement as HTMLElement | null const area = Object.assign(document.createElement("textarea"), { value: text, readOnly: true }) Object.assign(area.style, { position: "fixed", top: "0", left: "0", opacity: "0", pointerEvents: "none" }) // Внутри модального окна поле кладём в него: фокус-ловушка Radix не отдаёт фокус наружу. const host = active?.closest("[role=dialog], [role=alertdialog]") ?? document.body host.appendChild(area) area.focus({ preventScroll: true }) area.select() try { if (!document.execCommand("copy")) throw new Error("Браузер не дал скопировать") } finally { area.remove() active?.focus({ preventScroll: true }) } } /** Скопировать значение и показать подтверждение (или ошибку). */ export async function copyToClipboard(value: string, title = "Скопировано") { try { await copyText(value) toast.success(title, { description: value }) } catch { toast.error("Не удалось скопировать", { description: value }) } }