|
1 | 1 | function CopyCode(clipboard) {
|
2 |
| - document.querySelectorAll('pre > code').forEach(function(codeBlock) { |
3 |
| - var button = document.createElement('button'); |
4 |
| - button.className = 'code-copy'; |
5 |
| - button.type = 'button'; |
6 |
| - button.innerHTML = '<i class="fas fa-copy"></i> Copy'; |
| 2 | + document.querySelectorAll(".highlight").forEach((codeBlock) => { |
| 3 | + const button = document.createElement("button"); |
| 4 | + button.className = "code-copy"; |
| 5 | + button.type = "button"; |
| 6 | + button.innerHTML = '<i class="fas fa-copy"></i> Copy'; |
7 | 7 |
|
8 |
| - button.addEventListener('click', function() { |
9 |
| - // removes return carriage from copied text |
10 |
| - clipboard.writeText(codeBlock.textContent.replace(/\n$/g, "")).then( |
11 |
| - function() { |
12 |
| - button.blur(); /* Chrome fix */ |
13 |
| - button.innerHTML = '<i class="fas fa-check"></i> Copied!'; |
14 |
| - setTimeout(function() { |
15 |
| - button.innerHTML = '<i class="fas fa-copy"></i> Copy'; |
16 |
| - }, 2000); |
17 |
| - }, |
18 |
| - function(error) { |
19 |
| - button.innerHTML = '<i class="fas fa-exclamation"></i> Error'; |
20 |
| - console.error(error); |
21 |
| - } |
22 |
| - ); |
23 |
| - }); |
| 8 | + button.addEventListener("click", async () => { |
| 9 | + try { |
| 10 | + await clipboard.writeText( |
| 11 | + codeBlock.textContent |
| 12 | + .replace(/^\s*\d+\s/gm, "") // remove line numbers |
| 13 | + .replace(/^\s*|\s*$/g, "") // remove carriage returns at top and bottom of block |
| 14 | + ); |
24 | 15 |
|
25 |
| - var pre = codeBlock.parentNode; |
26 |
| - if (pre.parentNode.classList.contains('highlight')) { |
27 |
| - var highlight = pre.parentNode; |
28 |
| - highlight.parentNode.insertBefore(button, highlight); |
29 |
| - } |
| 16 | + button.blur(); /* Chrome fix */ |
| 17 | + button.innerHTML = '<i class="fas fa-check"></i> Copied!'; |
| 18 | + setTimeout(() => { |
| 19 | + button.innerHTML = '<i class="fas fa-copy"></i> Copy'; |
| 20 | + }, 2000); |
| 21 | + } catch (error) { |
| 22 | + button.innerHTML = '<i class="fas fa-exclamation"></i> Error'; |
| 23 | + console.error(error); |
| 24 | + } |
30 | 25 | });
|
| 26 | + |
| 27 | + codeBlock.parentNode.insertBefore(button, codeBlock); |
| 28 | + }); |
31 | 29 | }
|
32 | 30 |
|
33 | 31 | CopyCode(navigator.clipboard);
|
0 commit comments