diff options
| author | Jieiku | 2022-06-14 13:09:17 -0700 |
|---|---|---|
| committer | Jieiku | 2022-06-14 13:09:17 -0700 |
| commit | 4827695147bea438cf5c42c0ebc325b89f6e731e (patch) | |
| tree | 4c788bd96785473eab59a7b5d1bc87445c45966a /static/codecopy.js | |
| parent | 9ac96c9c0e205584004faed5ca03040450606fb2 (diff) | |
| download | abridge-4827695147bea438cf5c42c0ebc325b89f6e731e.tar.gz abridge-4827695147bea438cf5c42c0ebc325b89f6e731e.tar.bz2 abridge-4827695147bea438cf5c42c0ebc325b89f6e731e.zip | |
Code Blocks: Language and Copy Clipboard, Integrity Option
Diffstat (limited to 'static/codecopy.js')
| -rw-r--r-- | static/codecopy.js | 64 |
1 files changed, 64 insertions, 0 deletions
diff --git a/static/codecopy.js b/static/codecopy.js new file mode 100644 index 0000000..7163cdb --- /dev/null +++ b/static/codecopy.js @@ -0,0 +1,64 @@ +// https://aaronluna.dev/blog/add-copy-button-to-code-blocks-hugo-chroma/ + +// create copy button +function ccb(highlightDiv) { + const button = document.createElement("button"); + button.className = "cc "; + button.type = "button"; + button.innerHTML = "Copy"; + button.addEventListener("click", () => + ccc(button, highlightDiv) + ); + + // addCopyButtonToDom + const wrapper = document.createElement("div"); + wrapper.className = "ccw"; + wrapper.appendChild(button); + highlightDiv.parentNode.insertBefore(wrapper, highlightDiv); + wrapper.appendChild(highlightDiv); +} + +// copy code clipboard +async function ccc(button, highlightDiv) { + const codeToCopy = highlightDiv.querySelector(":last-child > code") + .innerText; + try { + result = await navigator.permissions.query({ name: "clipboard-write" }); + if (result.state == "granted" || result.state == "prompt") { + await navigator.clipboard.writeText(codeToCopy); + } else { + cce(codeToCopy, highlightDiv);//copyCodeBlockExecCommand + } + } catch (_) { + cce(codeToCopy, highlightDiv);//copyCodeBlockExecCommand + } finally { + //codeWasCopied + button.blur(); + button.innerHTML = "Copied"; + setTimeout(function () { + button.innerHTML = "Copy"; + }, 2000); + } +} + +//copyCodeBlockExecCommand +function cce(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); +} + +document + .querySelectorAll("pre") + .forEach((highlightDiv) => ccb(highlightDiv)); |
