46 lines
1.0 KiB
TypeScript
46 lines
1.0 KiB
TypeScript
export const useClipboard = () => {
|
|
const fallbackCopy = (value: string) => {
|
|
const textarea = document.createElement("textarea");
|
|
textarea.value = value;
|
|
textarea.setAttribute("readonly", "true");
|
|
textarea.style.position = "fixed";
|
|
textarea.style.top = "-9999px";
|
|
textarea.style.left = "-9999px";
|
|
textarea.style.opacity = "0";
|
|
|
|
document.body.appendChild(textarea);
|
|
textarea.focus();
|
|
textarea.select();
|
|
|
|
try {
|
|
return document.execCommand("copy");
|
|
} finally {
|
|
document.body.removeChild(textarea);
|
|
}
|
|
};
|
|
|
|
const copyText = async (value: string) => {
|
|
if (!process.client) {
|
|
return false;
|
|
}
|
|
|
|
const normalized = value.trim();
|
|
if (!normalized) {
|
|
return false;
|
|
}
|
|
|
|
try {
|
|
if (navigator.clipboard?.writeText) {
|
|
await navigator.clipboard.writeText(normalized);
|
|
return true;
|
|
}
|
|
} catch {
|
|
// Fall through to legacy copy API for embedded webviews.
|
|
}
|
|
|
|
return fallbackCopy(normalized);
|
|
};
|
|
|
|
return { copyText };
|
|
};
|