|
1 | 1 | (function () { |
2 | | - function select(element) { |
3 | | - const selection = window.getSelection(); |
| 2 | + var copyIcon = '<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="9" y="9" width="13" height="13" rx="2" ry="2"></rect><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"></path></svg>'; |
| 3 | + var checkIcon = '<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"></polyline></svg>'; |
4 | 4 |
|
5 | | - const range = document.createRange(); |
6 | | - range.selectNodeContents(element); |
| 5 | + document.querySelectorAll("pre code").forEach(function (code) { |
| 6 | + var pre = code.parentElement; |
7 | 7 |
|
8 | | - selection.removeAllRanges(); |
9 | | - selection.addRange(range); |
10 | | - } |
| 8 | + var langClass = Array.from(code.classList).find(function (c) { |
| 9 | + return c.startsWith("language-"); |
| 10 | + }); |
| 11 | + var lang = langClass ? langClass.replace("language-", "") : null; |
| 12 | + |
| 13 | + var controls = document.createElement("div"); |
| 14 | + controls.className = "code-controls"; |
11 | 15 |
|
12 | | - document.querySelectorAll("pre code").forEach(code => { |
13 | | - code.addEventListener("click", function (event) { |
14 | | - if (window.getSelection().toString()) { |
15 | | - return; |
16 | | - } |
17 | | - select(code.parentElement); |
| 16 | + if (lang && lang !== "fallback") { |
| 17 | + var label = document.createElement("span"); |
| 18 | + label.className = "code-lang"; |
| 19 | + label.textContent = lang; |
| 20 | + controls.appendChild(label); |
| 21 | + } |
18 | 22 |
|
19 | | - if (navigator.clipboard) { |
20 | | - navigator.clipboard.writeText(code.parentElement.textContent); |
21 | | - } |
| 23 | + var btn = document.createElement("button"); |
| 24 | + btn.className = "code-copy-btn"; |
| 25 | + btn.setAttribute("aria-label", "Copy code"); |
| 26 | + btn.innerHTML = copyIcon; |
| 27 | + |
| 28 | + btn.addEventListener("click", function () { |
| 29 | + var text = code.textContent; |
| 30 | + navigator.clipboard.writeText(text).then(function () { |
| 31 | + btn.innerHTML = checkIcon; |
| 32 | + setTimeout(function () { |
| 33 | + btn.innerHTML = copyIcon; |
| 34 | + }, 2000); |
| 35 | + }); |
22 | 36 | }); |
| 37 | + |
| 38 | + controls.appendChild(btn); |
| 39 | + pre.appendChild(controls); |
23 | 40 | }); |
24 | 41 | })(); |
0 commit comments