github.com/SamarSidharth/kpt@v0.0.0-20231122062228-c7d747ae3ace/site/static/js/plugins/copy_buttons.js (about)

     1  function addCodeCopyButtons() {
     2    const preBlocks = Array.from(document.getElementsByTagName("pre")).filter(
     3      (el) =>
     4        el.classList.contains("language-shell") &&
     5        el.firstElementChild.textContent
     6          .split("\n")
     7          .find((line) => line.trimLeft().startsWith("$"))
     8    );
     9  
    10    const makeButton = () => {
    11      const copyButton = document.createElement("button");
    12      const buttonClassName = "copy-button";
    13      copyButton.classList.add(buttonClassName);
    14      copyButton.title = "Copy to clipboard";
    15  
    16      const copyIcon = document.createElement("span");
    17      copyIcon.innerText = "copy";
    18      copyIcon.classList.add("material-icons-outlined");
    19      copyButton.appendChild(copyIcon);
    20  
    21      copyButton.addEventListener("click", (el) =>
    22        navigator.clipboard.writeText([
    23          el
    24            .composedPath()
    25            .find((el) => el.classList.contains(buttonClassName))
    26            .previousElementSibling.textContent.split("\n")
    27            .map((s) => s.trim())
    28            .filter(
    29              (s, ix, arr) =>
    30                s.startsWith("$") || (ix > 0 && arr[ix - 1].endsWith("\\"))
    31            )
    32            .map((s) => s.replace(/^\$\s+/, ""))
    33            .join("\n"),
    34        ])
    35      );
    36      return copyButton;
    37    };
    38    preBlocks.forEach((pre) => pre.appendChild(makeButton()));
    39  }
    40  
    41  // Load plugins into Docsify.
    42  window.$docsify = window.$docsify || {};
    43  window.$docsify.plugins = [].concat(function (hook, _vm) {
    44    hook.doneEach(addCodeCopyButtons);
    45  }, window.$docsify.plugins);
    46  
    47  // Export functions for testing.
    48  if (typeof module !== "undefined") {
    49    module.exports = { addCodeCopyButtons };
    50  }