41 lines
1.1 KiB
JavaScript
41 lines
1.1 KiB
JavaScript
/** Bind one .copy-input; never caches the input value. */
|
|
export function mountCopyField(root, { notify, t = (ru) => ru } = {}) {
|
|
const input = root.querySelector("input"),
|
|
button = root.querySelector("[data-copy-input]");
|
|
if (!input || !button)
|
|
throw new TypeError("Copy field needs an input and copy button");
|
|
const abort = new AbortController();
|
|
let disposed = false,
|
|
pending = false;
|
|
button.addEventListener(
|
|
"click",
|
|
async () => {
|
|
if (pending) return;
|
|
pending = true;
|
|
try {
|
|
await navigator.clipboard.writeText(input.value);
|
|
if (!disposed)
|
|
notify?.(t("Значение поля скопировано.", "Field value copied."), {
|
|
type: "success",
|
|
});
|
|
} catch {
|
|
if (!disposed)
|
|
notify?.(
|
|
t(
|
|
"Не удалось скопировать значение.",
|
|
"Could not copy the field value.",
|
|
),
|
|
{ type: "error" },
|
|
);
|
|
} finally {
|
|
pending = false;
|
|
}
|
|
},
|
|
{ signal: abort.signal },
|
|
);
|
|
return () => {
|
|
disposed = true;
|
|
abort.abort();
|
|
};
|
|
}
|