feat: implement clipboard utility for copying text and update components to use it

This commit is contained in:
Anders Böttcher
2026-05-13 17:19:43 +02:00
parent f7c52d0b1c
commit ffbbf1b6eb
3 changed files with 41 additions and 16 deletions
+33
View File
@@ -0,0 +1,33 @@
/**
* Copies text to the clipboard.
*
* Tries the modern Clipboard API first (requires secure context / HTTPS).
* Falls back to the legacy textarea + execCommand technique, which works on
* plain HTTP and private-IP origins where navigator.clipboard is unavailable.
*/
export async function copyText(text: string): Promise<void> {
// Modern path — secure context (HTTPS or localhost)
if (typeof navigator !== 'undefined' && navigator.clipboard?.writeText) {
try {
await navigator.clipboard.writeText(text)
return
} catch {
// Fall through to legacy method
}
}
// Legacy fallback — works on HTTP / private IPs
const el = document.createElement('textarea')
el.value = text
// Keep it out of the viewport so it doesn't flash
el.style.cssText = 'position:fixed;top:0;left:0;width:1px;height:1px;opacity:0;pointer-events:none;'
document.body.appendChild(el)
el.focus()
el.select()
try {
// eslint-disable-next-line @typescript-eslint/no-deprecated
document.execCommand('copy')
} finally {
document.body.removeChild(el)
}
}