Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: copy button on snippet code #217

Merged
merged 2 commits into from
Jan 7, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
59 changes: 53 additions & 6 deletions src/layouts/PostDetails.astro
Original file line number Diff line number Diff line change
Expand Up @@ -100,10 +100,57 @@ const layoutProps = {
</style>

<script is:inline>
/* When the user clicks on the "Back to Top" button,
* scroll to the top of the document */
document.querySelector("#back-to-top")?.addEventListener("click", () => {
document.body.scrollTop = 0; // For Safari
document.documentElement.scrollTop = 0; // For Chrome, Firefox, IE and Opera
});
/** Attaches copy buttons to code blocks in the document,
* allowing users to copy code easily. */
function attachCopyButtons() {
let copyButtonLabel = "Copy";
let codeBlocks = Array.from(document.querySelectorAll("pre"));

for (let codeBlock of codeBlocks) {
let wrapper = document.createElement("div");
wrapper.style.position = "relative";

let copyButton = document.createElement("button");
copyButton.className =
"copy-code absolute right-3 -top-3 rounded bg-skin-card px-2 py-1 text-xs leading-4 text-skin-base font-medium";
copyButton.innerHTML = copyButtonLabel;
codeBlock.setAttribute("tabindex", "0");
codeBlock.appendChild(copyButton);

// wrap codebock with relative parent element
codeBlock.parentNode.insertBefore(wrapper, codeBlock);
wrapper.appendChild(codeBlock);

copyButton.addEventListener("click", async () => {
await copyCode(codeBlock, copyButton);
});
}

async function copyCode(block, button) {
let code = block.querySelector("code");
let text = code.innerText;

await navigator.clipboard.writeText(text);

// visual feedback that task is completed
button.innerText = "Copied";

setTimeout(() => {
button.innerText = copyButtonLabel;
}, 700);
}
}
attachCopyButtons();
document.addEventListener("astro:after-swap", attachCopyButtons);

/** Scrolls the document to the top when
* the "Back to Top" button is clicked. */
function backToTop() {
document.querySelector("#back-to-top")?.addEventListener("click", () => {
document.body.scrollTop = 0; // For Safari
document.documentElement.scrollTop = 0; // For Chrome, Firefox, IE and Opera
});
}
backToTop();
document.addEventListener("astro:after-swap", backToTop);
</script>