|
| 1 | +'use strict'; |
| 2 | + |
| 3 | +// Attach copy-button logic only after the full DOM is loaded |
| 4 | +document.addEventListener('DOMContentLoaded', () => { |
| 5 | + // Inline SVG icons so no external asset load is required |
| 6 | + const copyIcon = ` |
| 7 | + <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"> |
| 8 | + <rect x="9" y="9" width="13" height="13" rx="2" ry="2"></rect> |
| 9 | + <path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"></path> |
| 10 | + </svg> |
| 11 | + `; |
| 12 | + |
| 13 | + const checkIcon = ` |
| 14 | + <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"> |
| 15 | + <path d="M20 6L9 17l-5-5"></path> |
| 16 | + </svg> |
| 17 | + `; |
| 18 | + |
| 19 | + // Inject a copy button into each <pre><code> block used in docs |
| 20 | + document.querySelectorAll('pre code').forEach(block => { |
| 21 | + const wrapper = block.parentElement; |
| 22 | + wrapper.style.position = 'relative'; // ensures button can be positioned correctly |
| 23 | + |
| 24 | + const btn = document.createElement('button'); |
| 25 | + btn.className = 'copy-btn'; |
| 26 | + btn.setAttribute('aria-label', 'Copy code to clipboard'); // accessibility support |
| 27 | + btn.innerHTML = copyIcon; // initial icon state |
| 28 | + |
| 29 | + // Handle the copy-to-clipboard action |
| 30 | + btn.onclick = async() => { |
| 31 | + if (btn.dataset.locked) return; // prevents multiple fast clicks |
| 32 | + btn.dataset.locked = '1'; |
| 33 | + |
| 34 | + // Uses Clipboard API to copy code block text |
| 35 | + await navigator.clipboard.writeText(block.textContent); |
| 36 | + |
| 37 | + // Show success tick briefly |
| 38 | + btn.innerHTML = checkIcon; |
| 39 | + btn.classList.add('copied'); |
| 40 | + |
| 41 | + // Restore original icon after delay |
| 42 | + setTimeout(() => { |
| 43 | + btn.innerHTML = copyIcon; |
| 44 | + btn.classList.remove('copied'); |
| 45 | + btn.dataset.locked = ''; |
| 46 | + }, 1200); |
| 47 | + }; |
| 48 | + |
| 49 | + wrapper.appendChild(btn); // attach button to code block |
| 50 | + }); |
| 51 | +}); |
0 commit comments