refactor: update post detail script codes

Updates:
- add optional chaining in possible null variables
- remove unnecessary after-swap event listeners
This commit is contained in:
satnaing
2024-01-24 13:44:32 +06:30
parent 7c88c6af50
commit b05ab6213e
+4 -6
View File
@@ -116,7 +116,7 @@ const layoutProps = {
link.innerText = "#";
link.className = "heading-link hidden group-hover:inline-block ml-2";
link.href = "#" + heading.id;
link.ariaHidden = true;
link.ariaHidden = "true";
heading.appendChild(link);
}
}
@@ -140,7 +140,7 @@ const layoutProps = {
codeBlock.appendChild(copyButton);
// wrap codebock with relative parent element
codeBlock.parentNode.insertBefore(wrapper, codeBlock);
codeBlock?.parentNode?.insertBefore(wrapper, codeBlock);
wrapper.appendChild(codeBlock);
copyButton.addEventListener("click", async () => {
@@ -150,9 +150,9 @@ const layoutProps = {
async function copyCode(block, button) {
let code = block.querySelector("code");
let text = code.innerText;
let text = code?.innerText;
await navigator.clipboard.writeText(text);
await navigator.clipboard.writeText(text ?? "");
// visual feedback that task is completed
button.innerText = "Copied";
@@ -163,7 +163,6 @@ const layoutProps = {
}
}
attachCopyButtons();
document.addEventListener("astro:after-swap", attachCopyButtons);
/** Scrolls the document to the top when
* the "Back to Top" button is clicked. */
@@ -174,5 +173,4 @@ const layoutProps = {
});
}
backToTop();
document.addEventListener("astro:after-swap", backToTop);
</script>