| 34 | // when the copy fires. A document selection survives the focus trap, so the |
| 35 | // copy works wherever the button lives. |
| 36 | function legacyCopy(text: string): boolean { |
| 37 | if (typeof document === "undefined" || !document.body) return false; |
| 38 | const selection = document.getSelection(); |
| 39 | if (!selection) return false; |
| 40 | |
| 41 | const node = document.createElement("span"); |
| 42 | node.textContent = text; |
| 43 | node.style.whiteSpace = "pre"; // preserve spaces/newlines exactly |
| 44 | node.style.userSelect = "text"; |
| 45 | node.style.position = "fixed"; |
| 46 | node.style.top = "0"; |
| 47 | node.style.left = "0"; |
| 48 | node.style.opacity = "0"; |
| 49 | node.style.pointerEvents = "none"; |
| 50 | document.body.appendChild(node); |
| 51 | |
| 52 | const previousRange = selection.rangeCount > 0 ? selection.getRangeAt(0) : null; |
| 53 | const range = document.createRange(); |
| 54 | range.selectNodeContents(node); |
| 55 | selection.removeAllRanges(); |
| 56 | selection.addRange(range); |
| 57 | |
| 58 | // oxlint-disable-next-line executor/no-try-catch-or-throw -- boundary: execCommand can throw in restricted DOM contexts; selection + node must be restored regardless |
| 59 | try { |
| 60 | return document.execCommand("copy"); |
| 61 | } catch { |
| 62 | return false; |
| 63 | } finally { |
| 64 | selection.removeAllRanges(); |
| 65 | if (previousRange) selection.addRange(previousRange); |
| 66 | document.body.removeChild(node); |
| 67 | } |
| 68 | } |