mirror of
https://github.com/davegallant/davegallant.github.io.git
synced 2025-08-07 00:58:13 +00:00
Re-enable pygments and add copy-code button
This commit is contained in:
58
themes/archie/static/js/copy-code-button.js
Normal file
58
themes/archie/static/js/copy-code-button.js
Normal file
@@ -0,0 +1,58 @@
|
||||
function createCopyButton(highlightDiv) {
|
||||
const button = document.createElement("button");
|
||||
button.className = "copy-code-button";
|
||||
button.type = "button";
|
||||
button.innerText = "Copy";
|
||||
button.addEventListener("click", () =>
|
||||
copyCodeToClipboard(button, highlightDiv)
|
||||
);
|
||||
highlightDiv.insertBefore(button, highlightDiv.firstChild);
|
||||
|
||||
const wrapper = document.createElement("div");
|
||||
wrapper.className = "highlight-wrapper";
|
||||
highlightDiv.parentNode.insertBefore(wrapper, highlightDiv);
|
||||
wrapper.appendChild(highlightDiv);
|
||||
}
|
||||
|
||||
document
|
||||
.querySelectorAll(".highlight")
|
||||
.forEach((highlightDiv) => createCopyButton(highlightDiv));
|
||||
|
||||
async function copyCodeToClipboard(button, highlightDiv) {
|
||||
const codeToCopy = highlightDiv.querySelector(
|
||||
"pre > code"
|
||||
).innerText;
|
||||
try {
|
||||
var result = await navigator.permissions.query({ name: "clipboard-write" });
|
||||
if (result.state == "granted" || result.state == "prompt") {
|
||||
await navigator.clipboard.writeText(codeToCopy);
|
||||
} else {
|
||||
copyCodeBlockExecCommand(codeToCopy, highlightDiv);
|
||||
}
|
||||
} catch (_) {
|
||||
copyCodeBlockExecCommand(codeToCopy, highlightDiv);
|
||||
} finally {
|
||||
button.blur();
|
||||
button.innerText = "Copied!";
|
||||
setTimeout(function () {
|
||||
button.innerText = "Copy";
|
||||
}, 2000);
|
||||
}
|
||||
}
|
||||
|
||||
function copyCodeBlockExecCommand(codeToCopy, highlightDiv) {
|
||||
const textArea = document.createElement("textArea");
|
||||
textArea.contentEditable = "true";
|
||||
textArea.readOnly = "false";
|
||||
textArea.className = "copyable-text-area";
|
||||
textArea.value = codeToCopy;
|
||||
highlightDiv.insertBefore(textArea, highlightDiv.firstChild);
|
||||
const range = document.createRange();
|
||||
range.selectNodeContents(textArea);
|
||||
const sel = window.getSelection();
|
||||
sel.removeAllRanges();
|
||||
sel.addRange(range);
|
||||
textArea.setSelectionRange(0, 999999);
|
||||
document.execCommand("copy");
|
||||
highlightDiv.removeChild(textArea);
|
||||
}
|
Reference in New Issue
Block a user