mirror of
https://github.com/saicaca/fuwari.git
synced 2026-01-11 23:02:53 +01:00
feat: copy button for code blocks (#67)
* Add code copy * fix: safari copyButton style * fix: addPreCopyButton up time * modify: CopyButton style * fix: Duplicate rendering issue with copy button
This commit is contained in:
@@ -13,6 +13,58 @@ const className = Astro.props.class;
|
||||
<slot/>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
import { i18n } from "@i18n/translation";
|
||||
import I18nKey from "@i18n/i18nKey";
|
||||
|
||||
const observer = new MutationObserver(addPreCopyButton);
|
||||
observer.observe(document.body, { childList: true, subtree: true });
|
||||
|
||||
document.addEventListener("DOMContentLoaded", addPreCopyButton);
|
||||
|
||||
function addPreCopyButton() {
|
||||
observer.disconnect();
|
||||
|
||||
let codeBlocks = Array.from(document.querySelectorAll("pre"));
|
||||
|
||||
for (let codeBlock of codeBlocks) {
|
||||
if (codeBlock.parentElement?.nodeName === "DIV" && codeBlock.parentElement?.classList.contains("code-block")) continue
|
||||
|
||||
let wrapper = document.createElement("div");
|
||||
wrapper.className = "relative code-block";
|
||||
|
||||
let copyButton = document.createElement("button");
|
||||
copyButton.className = "copy-code btn-regular absolute top-0 right-0 text-sm px-3 py-2 rounded-bl-lg rounded-tr-lg opacity-75 hover:opacity-100 transition-all duration-200 ease-in-out";
|
||||
copyButton.textContent = i18n(I18nKey.codeCopy);
|
||||
|
||||
codeBlock.setAttribute("tabindex", "0");
|
||||
if (codeBlock.parentNode) {
|
||||
codeBlock.parentNode.insertBefore(wrapper, codeBlock);
|
||||
}
|
||||
|
||||
wrapper.appendChild(codeBlock);
|
||||
wrapper.appendChild(copyButton);
|
||||
|
||||
copyButton.addEventListener("click", async () => {
|
||||
let text = codeBlock?.querySelector("code")?.innerText;
|
||||
|
||||
await navigator.clipboard.writeText(text);
|
||||
|
||||
copyButton.textContent = i18n(I18nKey.codeCopied);
|
||||
copyButton.classList.toggle("opacity-100");
|
||||
|
||||
setTimeout(() => {
|
||||
copyButton.textContent = i18n(I18nKey.codeCopy);
|
||||
copyButton.classList.toggle("opacity-100");
|
||||
}, 700);
|
||||
});
|
||||
}
|
||||
|
||||
observer.observe(document.body, { childList: true, subtree: true });
|
||||
}
|
||||
</script>
|
||||
|
||||
|
||||
<style lang="stylus" is:global>
|
||||
.custom-md
|
||||
h1, h2, h3, h4, h5, h6
|
||||
|
||||
Reference in New Issue
Block a user