(getText: () => string | null)
| 39 | * rather than copying an empty string over the user's clipboard. |
| 40 | */ |
| 41 | export function buildCopyButton(getText: () => string | null): HTMLButtonElement { |
| 42 | const btn = document.createElement('button'); |
| 43 | btn.type = 'button'; |
| 44 | btn.className = 'code-copy-btn'; |
| 45 | btn.setAttribute('contenteditable', 'false'); |
| 46 | btn.setAttribute('aria-label', 'Copy code'); |
| 47 | btn.title = 'Copy'; |
| 48 | btn.textContent = 'Copy'; |
| 49 | // mousedown + preventDefault avoids stealing focus / clobbering the selection |
| 50 | btn.addEventListener('mousedown', (e) => e.preventDefault()); |
| 51 | btn.addEventListener('click', async (e) => { |
| 52 | e.preventDefault(); |
| 53 | e.stopPropagation(); |
| 54 | const text = getText(); |
| 55 | const ok = text !== null && (await copyToClipboard(text)); |
| 56 | const prev = btn.textContent; |
| 57 | btn.textContent = ok ? 'Copied' : 'Failed'; |
| 58 | btn.classList.toggle('copied', ok); |
| 59 | setTimeout(() => { |
| 60 | btn.textContent = prev; |
| 61 | btn.classList.remove('copied'); |
| 62 | }, 1200); |
| 63 | }); |
| 64 | return btn; |
| 65 | } |
| 66 | |
| 67 | /** |
| 68 | * The NodeView for a non-mermaid code block: `<pre class="code-block">` with |
no test coverage detected