|
| 1 | +// Adds a "Copy" button to every code block so readers can easily copy snippets. |
| 2 | +function createCopyButton() { |
| 3 | + const button = document.createElement('button') |
| 4 | + button.className = 'copy-code-button' |
| 5 | + button.setAttribute('aria-label', 'Copy code to clipboard') |
| 6 | + button.textContent = 'Copy' |
| 7 | + return button |
| 8 | +} |
| 9 | + |
| 10 | +function attachCopyHandler(button, getText) { |
| 11 | + button.addEventListener('click', function () { |
| 12 | + const text = getText() |
| 13 | + if (navigator.clipboard && navigator.clipboard.writeText) { |
| 14 | + navigator.clipboard.writeText(text).then( |
| 15 | + function () { |
| 16 | + button.textContent = 'Copied!' |
| 17 | + setTimeout(function () { |
| 18 | + button.textContent = 'Copy' |
| 19 | + }, 2000) |
| 20 | + }, |
| 21 | + function () { |
| 22 | + button.textContent = 'Failed' |
| 23 | + setTimeout(function () { |
| 24 | + button.textContent = 'Copy' |
| 25 | + }, 2000) |
| 26 | + } |
| 27 | + ) |
| 28 | + } else { |
| 29 | + // Fallback for non-HTTPS environments |
| 30 | + const el = document.createElement('textarea') |
| 31 | + el.value = text |
| 32 | + document.body.appendChild(el) |
| 33 | + el.select() |
| 34 | + document.execCommand('copy') |
| 35 | + document.body.removeChild(el) |
| 36 | + button.textContent = 'Copied!' |
| 37 | + setTimeout(function () { |
| 38 | + button.textContent = 'Copy' |
| 39 | + }, 2000) |
| 40 | + } |
| 41 | + }) |
| 42 | +} |
| 43 | + |
| 44 | +document.addEventListener('DOMContentLoaded', function () { |
| 45 | + // table.pre blocks (F# highlighted code, sometimes with line numbers) |
| 46 | + document.querySelectorAll('table.pre').forEach(function (table) { |
| 47 | + const wrapper = document.createElement('div') |
| 48 | + wrapper.className = 'code-block-wrapper' |
| 49 | + table.parentNode.insertBefore(wrapper, table) |
| 50 | + wrapper.appendChild(table) |
| 51 | + |
| 52 | + const button = createCopyButton() |
| 53 | + wrapper.appendChild(button) |
| 54 | + |
| 55 | + const snippet = table.querySelector('.snippet pre') |
| 56 | + attachCopyHandler(button, function () { |
| 57 | + return (snippet || table).innerText |
| 58 | + }) |
| 59 | + }) |
| 60 | + |
| 61 | + // Standard pre > code blocks (Markdown fenced code, standalone fssnip, etc.) |
| 62 | + // Skip those already handled inside table.pre above. |
| 63 | + document.querySelectorAll('pre > code').forEach(function (code) { |
| 64 | + if (code.closest('table.pre')) return |
| 65 | + const pre = code.parentElement |
| 66 | + pre.classList.add('has-copy-button') |
| 67 | + |
| 68 | + const button = createCopyButton() |
| 69 | + pre.appendChild(button) |
| 70 | + |
| 71 | + attachCopyHandler(button, function () { |
| 72 | + return code.innerText |
| 73 | + }) |
| 74 | + }) |
| 75 | +}) |
0 commit comments