|
| 1 | +import tippy from 'tippy.js' |
| 2 | + |
| 3 | +export default function () { |
| 4 | + |
| 5 | + // get the list of all highlight code blocks |
| 6 | + const highlights = document.querySelectorAll("div.highlighter-rouge") |
| 7 | + |
| 8 | + |
| 9 | + |
| 10 | + |
| 11 | + highlights.forEach(div => { |
| 12 | + // create the copy button |
| 13 | + const copy = document.createElement("button") |
| 14 | + copy.innerHTML = "<img src='/docs/images/duplicate.svg' />" |
| 15 | + // add the event listener to each click |
| 16 | + copy.addEventListener("click", handleCopyClick) |
| 17 | + // append the copy button to each code block |
| 18 | + div.append(copy) |
| 19 | + |
| 20 | + }) |
| 21 | + |
| 22 | + |
| 23 | + |
| 24 | + |
| 25 | + |
| 26 | + const copyToClipboard = str => { |
| 27 | + const el = document.createElement("textarea") // Create a <textarea> element |
| 28 | + el.value = str // Set its value to the string that you want copied |
| 29 | + el.setAttribute("readonly", "") // Make it readonly to be tamper-proof |
| 30 | + el.style.position = "absolute" |
| 31 | + el.style.left = "-9999px" // Move outside the screen to make it invisible |
| 32 | + document.body.appendChild(el) // Append the <textarea> element to the HTML document |
| 33 | + const selected = |
| 34 | + document.getSelection().rangeCount > 0 // Check if there is any content selected previously |
| 35 | + ? |
| 36 | + document.getSelection().getRangeAt(0) // Store selection if found |
| 37 | + : |
| 38 | + false // Mark as false to know no selection existed before |
| 39 | + el.select() // Select the <textarea> content |
| 40 | + document.execCommand("copy") // Copy - only works as a result of a user action (e.g. click events) |
| 41 | + document.body.removeChild(el) // Remove the <textarea> element |
| 42 | + if (selected) { |
| 43 | + // If a selection existed before copying |
| 44 | + document.getSelection().removeAllRanges() // Unselect everything on the HTML document |
| 45 | + document.getSelection().addRange(selected) // Restore the original selection |
| 46 | + } |
| 47 | + } |
| 48 | + |
| 49 | + |
| 50 | + |
| 51 | + function handleCopyClick(evt) { |
| 52 | + // get the children of the parent element |
| 53 | + const { |
| 54 | + children |
| 55 | + } = evt.target.parentElement.parentElement |
| 56 | + // grab the first element (we append the copy button on afterwards, so the first will be the code element) |
| 57 | + // destructure the innerText from the code block |
| 58 | + const { |
| 59 | + innerText |
| 60 | + } = Array.from(children)[0] |
| 61 | + // copy all of the code to the clipboard |
| 62 | + copyToClipboard(innerText) |
| 63 | + // alert to show it worked, but you can put any kind of tooltip/popup to notify it worked |
| 64 | + const alert = children[1] |
| 65 | + alert.classList.add("green") |
| 66 | + setTimeout(() => { |
| 67 | + alert.classList.remove("green") |
| 68 | + }, 700) |
| 69 | + } |
| 70 | +} |
0 commit comments