From 923efbc936ad2aea6d78556aa07e0907d9794028 Mon Sep 17 00:00:00 2001 From: Aroy-Art <39088602+Aroy-Art@users.noreply.github.com> Date: Fri, 8 Oct 2021 10:24:07 +0200 Subject: [PATCH] Added code copy function --- assets/js/script.js | 64 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 64 insertions(+) diff --git a/assets/js/script.js b/assets/js/script.js index 78817dc..b513287 100644 --- a/assets/js/script.js +++ b/assets/js/script.js @@ -14,6 +14,70 @@ function imgIsLoaded(imgElement) { $(imgElement).removeClass("unloaded"); } + +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)); + 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 = "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); + } + + function codeWasCopied(button) { + button.blur(); + button.innerText = "Copied!"; + setTimeout(function() { + button.innerText = "Copy"; + }, 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); + } + + document.querySelectorAll(".highlight") + .forEach(highlightDiv => createCopyButton(highlightDiv)); + + jQuery(function ($) { "use strict";