feat: add share buttons

This commit is contained in:
KazooTTT
2025-02-06 14:43:03 +08:00
parent 19ebdc0c9a
commit 6e1f206bd8
2 changed files with 85 additions and 0 deletions

View File

@ -1,5 +1,6 @@
---
import { Icon } from "astro-icon/components";
import ShareButtons from "./ShareButtons.astro";
export interface Props {
className?: string;
@ -11,6 +12,10 @@ const { className = "", dataPagefindBody = true } = Astro.props;
<article class={`${className}`} data-pagefind-body={dataPagefindBody}>
<slot />
<div class="mt-8 border-t pt-4">
<ShareButtons />
</div>
<div id="myModal" class="modal">
<span class="close">
<Icon aria-hidden="true" class="h-6 w-6" focusable="false" name="mdi:close" />

View File

@ -0,0 +1,80 @@
---
import { Icon } from "astro-icon/components";
const shareButtons = [
{
name: "twitter",
icon: "mdi:twitter",
shareUrl: "https://twitter.com/intent/tweet?url={url}&text={title}",
},
{
name: "weibo",
icon: "mdi:sina-weibo",
shareUrl: "http://service.weibo.com/share/share.php?url={url}&title={title}",
},
];
---
<div class="share-buttons flex gap-2">
{
shareButtons.map((button) => (
<button
class="share-button rounded-full p-2 transition-colors hover:bg-gray-100"
data-share-url={button.shareUrl}
aria-label={`Share on ${button.name}`}
>
<Icon name={button.icon} class="h-5 w-5" />
</button>
))
}
<button
class="share-link rounded-full p-2 transition-colors hover:bg-gray-100"
aria-label="Copy link"
>
<Icon name="mdi:link-variant" class="h-5 w-5" />
</button>
<button
class="share-title-link rounded-full p-2 transition-colors hover:bg-gray-100"
aria-label="Copy title and link"
>
<Icon name="mdi:content-copy" class="h-5 w-5" />
</button>
</div>
<script>
const buttons = document.querySelectorAll(".share-button");
const linkButton = document.querySelector(".share-link");
const titleLinkButton = document.querySelector(".share-title-link");
buttons.forEach((button) => {
button.addEventListener("click", () => {
const url = encodeURIComponent(window.location.href);
const title = encodeURIComponent(document.title);
const shareUrlTemplate = button.getAttribute("data-share-url");
if (shareUrlTemplate) {
const finalUrl = shareUrlTemplate.replace("{url}", url).replace("{title}", title);
window.open(finalUrl, "_blank", "width=600,height=400");
}
});
});
linkButton?.addEventListener("click", async () => {
try {
await navigator.clipboard.writeText(window.location.href);
alert("链接已复制到剪贴板!");
} catch (err) {
console.error("复制失败:", err);
}
});
titleLinkButton?.addEventListener("click", async () => {
try {
const title = document.title;
const url = window.location.href;
await navigator.clipboard.writeText(`${title}\n${url}`);
alert("标题和链接已复制到剪贴板!");
} catch (err) {
console.error("复制失败:", err);
}
});
</script>