congo/assets/js/code.js

67 lines
2.3 KiB
JavaScript
Raw Permalink Normal View History

2022-01-27 04:26:18 +00:00
var scriptBundle = document.getElementById("script-bundle");
var copyText = scriptBundle ? scriptBundle.getAttribute("data-copy") : "Copy";
var copiedText = scriptBundle ? scriptBundle.getAttribute("data-copied") : "Copied";
2022-01-25 23:49:30 +00:00
function createCopyButton(highlightDiv) {
const button = document.createElement("button");
button.className = "copy-button";
button.type = "button";
button.ariaLabel = copyText;
2022-01-25 23:49:30 +00:00
button.innerText = copyText;
button.addEventListener("click", () => copyCodeToClipboard(button, highlightDiv));
addCopyButtonToDom(button, highlightDiv);
}
async function copyCodeToClipboard(button, highlightDiv) {
const codeToCopy = highlightDiv.querySelector(":last-child > .chroma > code").innerText;
try {
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 {
codeWasCopied(button);
}
}
function copyCodeBlockExecCommand(codeToCopy, highlightDiv) {
const textArea = document.createElement("textArea");
textArea.contentEditable = "true";
textArea.readOnly = "false";
textArea.className = "copy-textarea";
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);
}
function codeWasCopied(button) {
button.blur();
button.innerText = copiedText;
setTimeout(function () {
button.innerText = copyText;
}, 2000);
}
function addCopyButtonToDom(button, highlightDiv) {
highlightDiv.insertBefore(button, highlightDiv.firstChild);
const wrapper = document.createElement("div");
wrapper.className = "highlight-wrapper";
highlightDiv.parentNode.insertBefore(wrapper, highlightDiv);
wrapper.appendChild(highlightDiv);
}
window.addEventListener("DOMContentLoaded", (event) => {
document.querySelectorAll(".highlight").forEach((highlightDiv) => createCopyButton(highlightDiv));
});