forked from remote/pelican
feat: copy code block button
This commit is contained in:
parent
731155fa47
commit
80f257003f
1 changed files with 27 additions and 0 deletions
27
static/js/copy-code.js
Normal file
27
static/js/copy-code.js
Normal file
|
|
@ -0,0 +1,27 @@
|
|||
// NOTE: Pelican's fenced_code puts language-* on <code>, not <pre>,
|
||||
// so we select the <code> elements and walk up to the <pre>.
|
||||
const codeBlocks = document.querySelectorAll('code[class*="language-"]');
|
||||
|
||||
console.log("copy-code.js loaded, found:", codeBlocks.length);
|
||||
|
||||
codeBlocks.forEach((code) => {
|
||||
const pre = code.closest("pre");
|
||||
if (!pre) return;
|
||||
|
||||
const button = document.createElement("button");
|
||||
button.className = "copy-to-clipboard-button";
|
||||
button.type = "button";
|
||||
button.textContent = "Copy";
|
||||
|
||||
button.addEventListener("click", async () => {
|
||||
try {
|
||||
await navigator.clipboard.writeText(code.innerText);
|
||||
button.textContent = "Copied";
|
||||
} catch {
|
||||
button.textContent = "Failed";
|
||||
}
|
||||
setTimeout(() => (button.textContent = "Copy"), 1500);
|
||||
});
|
||||
|
||||
pre.appendChild(button);
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue