-
Notifications
You must be signed in to change notification settings - Fork 15
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: add new clipboard button to all code blocks
- Loading branch information
1 parent
10a2aff
commit 4901c01
Showing
2 changed files
with
13 additions
and
10 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | ||
}) | ||
} | ||
} |
This file was deleted.
Oops, something went wrong.