"use client"; import { useState, useEffect } from "react"; import { useRouter } from "next/navigation"; import Link from "next/link"; import { Pencil, Trash2, Pin, Star } from "lucide-react"; import { apiMe, apiDeletePost, apiTogglePin, apiToggleRecommend, type User } from "@/lib/api"; import { toast } from "@/lib/toast"; interface PostActionsProps { postId: string; authorId: number; pinned: number; recommended: boolean; } export default function PostActions({ postId, authorId, pinned, recommended }: PostActionsProps) { const router = useRouter(); const [user, setUser] = useState(null); const [deleting, setDeleting] = useState(false); const [isPinned, setIsPinned] = useState(pinned > 0); const [isRecommended, setIsRecommended] = useState(recommended); const [acting, setActing] = useState(false); useEffect(() => { apiMe() .then((res) => setUser(res.user || null)) .catch(() => setUser(null)); }, []); const canManage = user && (user.id === authorId || user.role === "admin"); const isAdmin = user?.role === "admin"; if (!canManage) return null; const handleDelete = async () => { if (!confirm("确定要删除这篇帖子吗?此操作不可恢复。")) return; setDeleting(true); try { const res = await apiDeletePost(postId); if (res.message) { router.push("/"); toast("帖子已删除", "ok"); } else { toast(res.error || "删除失败"); } } catch { toast("网络错误,删除失败"); } finally { setDeleting(false); } }; const handlePin = async () => { setActing(true); try { const res = await apiTogglePin(postId); setIsPinned(res.pinned > 0); toast(res.pinned > 0 ? "已置顶" : "已取消置顶", "ok"); router.refresh(); } catch { toast("操作失败,请稍后重试"); } finally { setActing(false); } }; const handleRecommend = async () => { setActing(true); try { const res = await apiToggleRecommend(postId); setIsRecommended(res.recommended); toast(res.recommended ? "已设为推荐" : "已取消推荐", "ok"); router.refresh(); } catch { toast("操作失败,请稍后重试"); } finally { setActing(false); } }; return (
{isAdmin && ( <> )} 编辑
); }