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/).
This commit is contained in:
parent
d1267ac587
commit
75f56d8fad
13 changed files with 138 additions and 7 deletions
|
@ -1,3 +1,21 @@
|
|||
document.addEventListener("DOMContentLoaded", function (event) {
|
||||
var clipboard = new ClipboardJS(".clip");
|
||||
|
||||
clipboard.on("success", function (e) {
|
||||
const trigger = e.trigger;
|
||||
|
||||
if (trigger.hasAttribute("data-copy-feedback")) {
|
||||
trigger.classList.add("gdoc-post__codecopy--success");
|
||||
trigger.querySelector(".icon.copy").classList.add("hidden");
|
||||
trigger.querySelector(".icon.check").classList.remove("hidden");
|
||||
|
||||
setTimeout(function () {
|
||||
trigger.classList.remove("gdoc-post__codecopy--success");
|
||||
trigger.querySelector(".icon.copy").classList.remove("hidden");
|
||||
trigger.querySelector(".icon.check").classList.add("hidden");
|
||||
}, 3000);
|
||||
}
|
||||
|
||||
e.clearSelection();
|
||||
});
|
||||
});
|
||||
|
|
34
src/js/copycode.js
Normal file
34
src/js/copycode.js
Normal file
|
@ -0,0 +1,34 @@
|
|||
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));
|
Loading…
Add table
Add a link
Reference in a new issue