aboutsummaryrefslogtreecommitdiff
path: root/static/js/codecopy.js
blob: c1f3a755cabfc5a6658e6a6f7c3799c0c713e973 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
// https://aaronluna.dev/blog/add-copy-button-to-code-blocks-hugo-chroma/
// Further modified for Zola by Jieiku: https://github.com/Jieiku
(function() {
  // 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) {
    //look for table, if so do it different
    const { length } = highlightDiv.querySelectorAll("table");
    let codeToCopy = "";
    if (length > 0) {
      const items = highlightDiv.querySelectorAll(":last-child > tr > td:last-child");
      items.forEach(item => {
        codeToCopy = codeToCopy + item.innerText;
        //console.log(codeToCopy);
      });
    } else {
      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));
})();