Skip to content

Commit

Permalink
feat: add new clipboard button to all code blocks
Browse files Browse the repository at this point in the history
  • Loading branch information
branchvincent committed Sep 8, 2022
1 parent 10a2aff commit 4901c01
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 10 deletions.
20 changes: 13 additions & 7 deletions src/js/controllers/clipboard_controller.js
Original file line number Diff line number Diff line change
@@ -1,28 +1,34 @@
import checkmark from "../../../static/images/checkmark.svg"
import copyIcon from "../../../static/images/content_copy.svg"
import { Controller } from "@hotwired/stimulus"
import checkmarkIcon from "../../../static/images/checkmark.svg"
import copyIcon from "../../../static/images/content_copy.svg"

export default class extends Controller {
initialize() {
document
.querySelectorAll("div.clipboard > div.highlight > pre")
.querySelectorAll("div.highlight > pre > code")
.forEach((codeBlock) => {
const button = document.createElement("button")
button.className = "clipboard-button"
button.type = "button"
button.title = "Copy to clipboard"
button.appendChild(copyIcon)
const _copyIcon = copyIcon.cloneNode()
const _checkmarkIcon = checkmarkIcon.cloneNode()
button.appendChild(_copyIcon)
button.addEventListener("click", () => {
navigator.clipboard.writeText(codeBlock.innerText).then(
() => {
button.blur()
button.replaceChild(checkmark, copyIcon)
setTimeout(() => button.replaceChild(copyIcon, checkmark), 2000)
button.replaceChild(_checkmarkIcon, _copyIcon)
setTimeout(
() => button.replaceChild(_copyIcon, _checkmarkIcon),
2000
)
},
() => (button.innerHTML = "Error")
)
})
codeBlock.parentNode.insertBefore(button, codeBlock)
const pre = codeBlock.parentNode
pre.parentNode.insertBefore(button, pre)
})
}
}
3 changes: 0 additions & 3 deletions themes/poetry/layouts/shortcodes/clipboard.html

This file was deleted.

0 comments on commit 4901c01

Please sign in to comment.