Skip to content

Commit

Permalink
refactor: update post detail script codes
Browse files Browse the repository at this point in the history
Updates:
- add optional chaining in possible null variables
- remove unnecessary after-swap event listeners
  • Loading branch information
satnaing committed Jan 24, 2024
1 parent 7c88c6a commit b05ab62
Showing 1 changed file with 4 additions and 6 deletions.
10 changes: 4 additions & 6 deletions src/layouts/PostDetails.astro
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
}
Expand All @@ -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 () => {
Expand All @@ -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";
Expand All @@ -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. */
Expand All @@ -174,5 +173,4 @@ const layoutProps = {
});
}
backToTop();
document.addEventListener("astro:after-swap", backToTop);
</script>

0 comments on commit b05ab62

Please sign in to comment.