Files
jiang13-bbs/frontend/components/LikeButton.tsx
freefire 1eaf3903d4 feat: 新增大量社区功能与基础组件,优化站点整体体验
- 新增事件总线式toast通知系统
- 新增头像、阅读进度、404/500错误页等基础组件
- 重构页脚、布局、分页、点赞按钮等现有组件
- 新增用户个人页、通知中心、帖子编辑/发布/置顶/推荐管理功能
- 优化登录注册页面样式与交互
- 修复路径类型文件引用,更新站点元信息与字体配置
2026-09-12 04:30:02 +08:00

81 lines
2.4 KiB
TypeScript

"use client";
import { useState } from "react";
import { useRouter, usePathname } from "next/navigation";
import { IconHeart } from "./Icons";
import { apiToggleLike } from "@/lib/api";
import { toast } from "@/lib/toast";
interface LikeButtonProps {
postId: string;
liked: boolean;
likeCount: number;
variant?: "default" | "compact";
}
export default function LikeButton({
postId,
liked: initialLiked,
likeCount: initialCount,
variant = "default",
}: LikeButtonProps) {
const router = useRouter();
const pathname = usePathname();
const [liked, setLiked] = useState(initialLiked);
const [count, setCount] = useState(initialCount);
const [loading, setLoading] = useState(false);
const handleClick = async () => {
if (loading) return;
setLoading(true);
// 乐观更新:先给反馈,失败再回滚
const wasLiked = liked;
setLiked(!wasLiked);
setCount((c) => c + (wasLiked ? -1 : 1));
try {
const res = await apiToggleLike(postId);
if (res.error === "未登录") {
router.push(`/login?redirect=${encodeURIComponent(pathname)}`);
return;
}
if (typeof res.liked === "boolean") {
setLiked(res.liked);
setCount(res.like_count ?? count);
} else {
throw new Error(res.error || "FAIL");
}
} catch {
setLiked(wasLiked);
setCount((c) => c + (wasLiked ? 1 : -1));
toast("操作失败,请稍后重试");
} finally {
setLoading(false);
}
};
const compact =
variant === "compact"
? "px-2.5 py-1.5 gap-1 text-[12.5px]"
: "px-4 py-2 gap-1.5 text-sm";
return (
<button
onClick={handleClick}
disabled={loading}
title={liked ? "取消点赞" : "点赞"}
aria-pressed={liked}
className={`inline-flex items-center font-semibold tabular-nums rounded-full border transition-colors duration-150 hover:border-[var(--accent)] disabled:opacity-50 ${compact}`}
style={{
borderColor: liked ? "var(--accent)" : "var(--line-2)",
color: liked ? "var(--accent)" : "var(--ink-2)",
background: liked ? "var(--accent-soft)" : "var(--panel)",
}}
>
<span key={String(liked)} className={liked ? "j13-heart-pop inline-flex" : "inline-flex"}>
<IconHeart size={variant === "compact" ? 13 : 15} filled={liked} />
</span>
<span>{count}</span>
</button>
);
}