本次提交实现了完整的社区首页功能: 1. 新增首页聚合接口与服务,包含社区统计、热门帖、活跃用户与板块数据 2. 实现帖子推荐排序、SSR缓存与点赞态同步逻辑 3. 重构导航与布局系统,新增工作台侧边栏与移动端适配 4. 优化主题色与UI样式,统一设计系统风格 5. 修复登录注册页自动跳转与组件状态同步问题
88 lines
2.6 KiB
TypeScript
88 lines
2.6 KiB
TypeScript
"use client";
|
|
|
|
import { useState, useEffect } 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);
|
|
|
|
// router.refresh()(登录/登出后)服务端会重新下发 liked 态,同步到本地,
|
|
// 避免客户端状态停留在刷新前的用户视角
|
|
useEffect(() => {
|
|
setLiked(initialLiked);
|
|
setCount(initialCount);
|
|
}, [initialLiked, initialCount]);
|
|
|
|
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>
|
|
);
|
|
}
|