/** * คัดลอกข้อความลง clipboard ให้ได้มากที่สุด: * 1. navigator.clipboard (ต้อง secure context + permission — บาง embedded browser/webview บล็อก) * 2. fallback: textarea ชั่วคราว + document.execCommand("copy") (deprecated แต่ยังใช้ได้ทุก browser) * คืน true เมื่อสำเร็จ — ผู้เรียกควรมีทางหนี (เลือกข้อความให้ผู้ใช้กด Ctrl+C เอง) เมื่อได้ false */ export async function copyText(text: string): Promise { if (typeof navigator !== "undefined" && navigator.clipboard?.writeText) { try { await navigator.clipboard.writeText(text); return true; } catch { // ลอง fallback ต่อ } } if (typeof document === "undefined") return false; const ta = document.createElement("textarea"); ta.value = text; ta.setAttribute("readonly", ""); ta.style.position = "fixed"; ta.style.top = "0"; ta.style.left = "0"; ta.style.opacity = "0"; document.body.appendChild(ta); const active = document.activeElement as HTMLElement | null; try { ta.focus(); ta.select(); ta.setSelectionRange(0, text.length); return document.execCommand("copy"); } catch { return false; } finally { ta.remove(); active?.focus?.(); } } /** เลือกข้อความทั้งก้อนใน element (ให้ผู้ใช้กด Ctrl+C ได้ทันทีเมื่อ copy อัตโนมัติไม่ได้) */ export function selectContents(el: Element | null): void { if (!el || typeof window === "undefined") return; const sel = window.getSelection(); if (!sel) return; const range = document.createRange(); range.selectNodeContents(el); sel.removeAllRanges(); sel.addRange(range); }