|
| 1 | +(function () { |
| 2 | + function copyText(text) { |
| 3 | + if (navigator.clipboard && window.isSecureContext) { |
| 4 | + return navigator.clipboard.writeText(text); |
| 5 | + } |
| 6 | + |
| 7 | + return new Promise(function (resolve, reject) { |
| 8 | + var textArea = document.createElement("textarea"); |
| 9 | + textArea.value = text; |
| 10 | + textArea.setAttribute("readonly", ""); |
| 11 | + textArea.style.position = "fixed"; |
| 12 | + textArea.style.top = "-9999px"; |
| 13 | + document.body.appendChild(textArea); |
| 14 | + textArea.select(); |
| 15 | + |
| 16 | + try { |
| 17 | + document.execCommand("copy"); |
| 18 | + resolve(); |
| 19 | + } catch (error) { |
| 20 | + reject(error); |
| 21 | + } finally { |
| 22 | + document.body.removeChild(textArea); |
| 23 | + } |
| 24 | + }); |
| 25 | + } |
| 26 | + |
| 27 | + function addCopyButtons() { |
| 28 | + document.querySelectorAll("div.highlight").forEach(function (block) { |
| 29 | + if (block.querySelector(".eventlab-copy-button")) { |
| 30 | + return; |
| 31 | + } |
| 32 | + |
| 33 | + var pre = block.querySelector("pre"); |
| 34 | + if (!pre) { |
| 35 | + return; |
| 36 | + } |
| 37 | + |
| 38 | + var button = document.createElement("button"); |
| 39 | + button.type = "button"; |
| 40 | + button.className = "eventlab-copy-button"; |
| 41 | + button.textContent = "Copy"; |
| 42 | + button.setAttribute("aria-label", "Copy code block"); |
| 43 | + |
| 44 | + button.addEventListener("click", function () { |
| 45 | + var text = pre.innerText.replace(/\s+$/, ""); |
| 46 | + copyText(text).then(function () { |
| 47 | + button.textContent = "Copied"; |
| 48 | + button.classList.add("is-copied"); |
| 49 | + window.setTimeout(function () { |
| 50 | + button.textContent = "Copy"; |
| 51 | + button.classList.remove("is-copied"); |
| 52 | + }, 1400); |
| 53 | + }).catch(function () { |
| 54 | + button.textContent = "Failed"; |
| 55 | + window.setTimeout(function () { |
| 56 | + button.textContent = "Copy"; |
| 57 | + }, 1400); |
| 58 | + }); |
| 59 | + }); |
| 60 | + |
| 61 | + block.appendChild(button); |
| 62 | + }); |
| 63 | + } |
| 64 | + |
| 65 | + if (document.readyState === "loading") { |
| 66 | + document.addEventListener("DOMContentLoaded", addCopyButtons); |
| 67 | + } else { |
| 68 | + addCopyButtons(); |
| 69 | + } |
| 70 | +}()); |
0 commit comments