add copy-to-clipboard button to code fences

This commit is contained in:
jake committed 2021-08-16 08:08:56 -04:00
1 parent 86ded40854
commit fdb9532cc5
5 files changed
+119 -31

No files matched your search

+1
View File
@@ -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
View 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();
});
});
}
+22
View File
@@ -32,6 +32,7 @@ div.highlight {
overflow-x: scroll;
margin: 1em 0;
border: 1px solid;
position: relative;
pre {
padding-left: 1.5em;
@@ -42,6 +43,25 @@ div.highlight {
> pre > code {
padding-right: 1.5em;
}
button.copy-button {
position: absolute;
top: 0;
right: 0;
z-index: 2;
cursor: pointer;
width: 5em;
padding: 0.75em 0.25em;
font-size: 0.9em;
font-weight: 500;
background: transparent;
border-top: 0;
border-right: 0;
border-left: 1px solid;
border-bottom: 1px solid;
}
}
// global table styles for line numbers and font styles
@@ -95,6 +115,7 @@ div.highlight {
/*! Syntax Highlighting (light) - modified from Monokai Light: https://github.com/mlgill/pygments-style-monokailight */
body.light {
div.highlight,
button.copy-button,
:not(pre) > code {
color: #313131;
background-color: #fbfbfb;
@@ -170,6 +191,7 @@ body.light {
/*! Syntax Highlighting (dark) - modified from Dracula: https://github.com/dracula/pygments */
body.dark {
div.highlight,
button.copy-button,
:not(pre) > code {
color: #e4e4e4;
background-color: #252525;