hugo-theme-hilfe/src/js/copycode.js
Robert Kaussow 75f56d8fad
feat: add button to copy code blocks (#228)
BREAKING CHANGE: The `--code-max-height` formatting is applied only to code blocks that use syntax highlighting, see [documentation](https://geekdocs.de/features/code-blocks/).
2021-11-07 22:12:14 +01:00

35 lines
1 KiB
JavaScript

function createCopyButton(highlightDiv) {
const button = document.createElement("span");
if (highlightDiv.querySelector(".lntable")) {
selector = ".lntable .lntd:last-child pre > code";
} else {
selector = "pre > code";
}
const codeToCopy = highlightDiv.querySelector(selector).innerText.trim();
button.classList.add(
"flex",
"align-center",
"justify-center",
"clip",
"gdoc-post__codecopy"
);
button.type = "button";
button.innerHTML =
'<svg class="icon copy"><use xlink:href="#gdoc_copy"></use></svg>' +
'<svg class="icon check hidden"><use xlink:href="#gdoc_check"></use></svg>';
button.setAttribute("data-clipboard-text", codeToCopy);
button.setAttribute("data-copy-feedback", "Copied!");
button.setAttribute("role", "button");
button.setAttribute("aria-label", "Copy");
highlightDiv.classList.add("gdoc-post__codecontainer");
highlightDiv.insertBefore(button, highlightDiv.firstChild);
}
document
.querySelectorAll(".highlight")
.forEach((highlightDiv) => createCopyButton(highlightDiv));