Skip to content

Commit

Permalink
Merge pull request #549 from canopas/copy-btn-blogs-snippet
Browse files Browse the repository at this point in the history
Feat : Copy button for code snippet for blogs
  • Loading branch information
cp-ashish-k authored Feb 8, 2024
2 parents 0e8b2e0 + 8f87aa0 commit bb7dcdb
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 0 deletions.
36 changes: 36 additions & 0 deletions nuxt-frontend/pages/[slug].vue
Original file line number Diff line number Diff line change
Expand Up @@ -139,4 +139,40 @@ function getJsonLdSchema() {
},
};
}
//for copy to clipboard of code blocks
function copyCode(bash) {
const code = bash.querySelector("code");
const text = code.innerText;
navigator.clipboard.writeText(text);
}
onMounted(() => {
const bashes = document.querySelectorAll("pre");
bashes.forEach((bash) => {
if (navigator.clipboard) {
const wrapperDiv = document.createElement("div");
bash.parentNode.insertBefore(wrapperDiv, bash);
wrapperDiv.appendChild(bash);
wrapperDiv.classList.add("relative");
const isSingleLine = bash.textContent.trim().split("\n").length === 1;
if (isSingleLine) {
bash.classList.add("!pr-20");
}
const button = document.createElement("button");
button.classList.add("copy-btn");
button.innerText = "copy";
bash.appendChild(button);
button.addEventListener("click", async () => {
await copyCode(bash, button);
button.innerText = "copied!";
button.classList.add("text-green-500");
});
}
});
});
</script>
<style lang="postcss">
.copy-btn {
@apply absolute top-3 right-3 border-1 px-2 bg-gray-700 rounded-lg;
}
</style>
2 changes: 2 additions & 0 deletions nuxt-frontend/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -156,7 +156,9 @@ function getReadingTime(content) {
function formateDate(date) {
if (!date) return [null, null];
const newDate = new Date(date);
const userTimezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
const formattedDate = newDate.toLocaleDateString("en-US", {
timeZone: userTimezone,
month: "short",
day: "numeric",
year: "numeric",
Expand Down

0 comments on commit bb7dcdb

Please sign in to comment.