mirror of
https://github.com/zoriya/blog.git
synced 2026-08-15 18:44:35 +00:00
Add copy code button
This commit is contained in:
@@ -80,6 +80,11 @@ const currentPath = Astro.url.pathname;
|
||||
<Comments />
|
||||
<ScrollToTop />
|
||||
</article>
|
||||
|
||||
<div id="copy-code-icons" class="hidden">
|
||||
<span id="copy-icon"><Icon name="fa6-solid:clone" class="w-4 h-4" /></span>
|
||||
<span id="check-icon"><Icon name="fa6-solid:check" class="w-4 h-4" /></span>
|
||||
</div>
|
||||
</BaseLayout>
|
||||
|
||||
<script>
|
||||
@@ -103,4 +108,48 @@ const currentPath = Astro.url.pathname;
|
||||
document.body.style.overflow = "";
|
||||
}
|
||||
});
|
||||
|
||||
function initCopyCodeButtons() {
|
||||
const copyIcon = document.getElementById("copy-icon")?.innerHTML;
|
||||
const checkIcon = document.getElementById("check-icon")?.innerHTML;
|
||||
|
||||
if (!copyIcon || !checkIcon) return;
|
||||
|
||||
const codeBlocks = document.querySelectorAll("pre");
|
||||
|
||||
codeBlocks.forEach((pre) => {
|
||||
if (!pre.querySelector("code")) return;
|
||||
if (pre.querySelector(".copy-code-btn")) return;
|
||||
|
||||
pre.classList.add("relative", "group");
|
||||
|
||||
const button = document.createElement("button");
|
||||
button.className = "copy-code-btn absolute top-2 right-2 p-1.5 bg-surface-alt border border-border rounded-md text-fg-secondary cursor-pointer opacity-0 transition-opacity group-hover:opacity-100 hover:bg-accent hover:text-white hover:border-accent z-10 flex items-center justify-center";
|
||||
button.setAttribute("aria-label", "Copy code");
|
||||
button.innerHTML = copyIcon;
|
||||
|
||||
button.addEventListener("click", async () => {
|
||||
const code = pre.querySelector("code")?.innerText || pre.innerText;
|
||||
try {
|
||||
await navigator.clipboard.writeText(code);
|
||||
button.classList.add("copied");
|
||||
button.classList.remove("text-fg-secondary");
|
||||
button.classList.add("text-green-500");
|
||||
button.innerHTML = checkIcon;
|
||||
setTimeout(() => {
|
||||
button.classList.remove("copied");
|
||||
button.classList.remove("text-green-500");
|
||||
button.classList.add("text-fg-secondary");
|
||||
button.innerHTML = copyIcon;
|
||||
}, 2000);
|
||||
} catch (err) {
|
||||
console.error("Failed to copy code:", err);
|
||||
}
|
||||
});
|
||||
|
||||
pre.appendChild(button);
|
||||
});
|
||||
}
|
||||
|
||||
initCopyCodeButtons();
|
||||
</script>
|
||||
|
||||
Reference in New Issue
Block a user