mirror of
https://github.com/jakejarvis/jarv.is.git
synced 2025-07-03 17:46:39 -04:00
add copy-to-clipboard button to code fences
This commit is contained in:
@ -1,6 +1,7 @@
|
||||
import "./src/dark-mode.js";
|
||||
import "./src/emoji.js";
|
||||
import "./src/counter.js";
|
||||
import "./src/clipboard.js";
|
||||
import "./src/projects.js";
|
||||
|
||||
export default () => {};
|
||||
|
33
assets/js/src/clipboard.js
Normal file
33
assets/js/src/clipboard.js
Normal file
@ -0,0 +1,33 @@
|
||||
import ClipboardJS from "clipboard";
|
||||
|
||||
// the default text of the copy button:
|
||||
const copyTerm = "Copy";
|
||||
|
||||
// immediately give up if not supported
|
||||
if (ClipboardJS.isSupported()) {
|
||||
// loop through each code fence on page (if any)
|
||||
document.querySelectorAll("div.highlight").forEach((highlightDiv) => {
|
||||
const button = document.createElement("button");
|
||||
button.className = "copy-button";
|
||||
button.innerText = copyTerm;
|
||||
|
||||
// insert button as a sibling to Hugo's code fence
|
||||
highlightDiv.insertBefore(button, highlightDiv.firstChild);
|
||||
|
||||
new ClipboardJS(button, {
|
||||
// actual code element will have class "language-*", even if plaintext
|
||||
text: (trigger) => trigger.parentElement.querySelector('code[class^="language-"]').innerText, // eslint-disable-line quotes
|
||||
}).on("success", (e) => {
|
||||
// show a subtle indication of success
|
||||
e.trigger.innerText = "✓";
|
||||
|
||||
// reset button to original text after 2 seconds
|
||||
setTimeout(() => {
|
||||
e.trigger.innerText = copyTerm;
|
||||
}, 2000);
|
||||
|
||||
// text needed to be auto-selected to copy, unselect immediately
|
||||
e.clearSelection();
|
||||
});
|
||||
});
|
||||
}
|
Reference in New Issue
Block a user