medkit/src/lib/clipboard.ts

40 lines
1.8 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { toast } from "sonner"
/**
* Скопировать текст в буфер. navigator.clipboard есть только в защищённом контексте (https, localhost);
* открыто по http в локальной сети или нет разрешения — запасной путь через скрытое поле и execCommand.
*/
export async function copyText(text: string): Promise<void> {
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<HTMLElement>("[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 })
}
}