runtimeterror/assets/js/code-copy-button.js

53 lines
2 KiB
JavaScript
Raw Normal View History

2023-11-10 03:57:47 +00:00
// adapted from https://digitaldrummerj.me/hugo-add-copy-code-snippet-button/
2023-10-21 21:13:44 +00:00
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) {
2023-11-09 04:02:57 +00:00
// capture all code lines in the selected block which aren't classed `nocopy` or `line-remove`
let codeToCopy = highlightDiv.querySelectorAll(":last-child > .torchlight > code > .line:not(.nocopy, .line-remove)");
2024-06-21 03:17:18 +00:00
// remove child elements with class `line-number` and `diff-indicator diff-indicator-add`
2023-11-05 01:49:39 +00:00
codeToCopy = Array.from(codeToCopy).reduce((accumulator, line) => {
return accumulator + Array.from(line.children).filter(
2024-06-21 03:17:18 +00:00
(child) => child.className != "line-number" && child.className != "diff-indicator diff-indicator-add"
).reduce((accumulator, child) => accumulator + child.innerText, "") + "\n";
2023-11-05 01:49:39 +00:00
}, "");
2023-10-21 21:13:44 +00:00
try {
var result = await navigator.permissions.query({ name: "clipboard-write" });
if (result.state == "granted" || result.state == "prompt") {
await navigator.clipboard.writeText(codeToCopy);
} else {
2023-11-09 02:28:42 +00:00
button.blur();
button.innerText = "Error!";
setTimeout(function () {
button.innerText = "Copy";
}, 2000);
2023-10-21 21:13:44 +00:00
}
} catch (_) {
2023-11-09 02:28:42 +00:00
button.blur();
button.innerText = "Error!";
setTimeout(function () {
button.innerText = "Copy";
}, 2000);
2023-10-21 21:13:44 +00:00
} finally {
2023-11-09 02:28:42 +00:00
button.blur();
button.innerText = "Copied!";
setTimeout(function () {
button.innerText = "Copy";
}, 2000);
}
2023-10-21 21:13:44 +00:00
}