"use client"; import Link from "next/link"; import { useMemo, useState } from "react"; import { Post } from "@/types/post"; type AdminPost = Post & { createdAtText?: string }; export function AdminPostList({ initialPosts, title = "最近内容", description, emptyText = "暂无内容。", canDelete = false, canPin = false, showEdit = true }: { initialPosts: AdminPost[]; title?: string; description?: string; emptyText?: string; canDelete?: boolean; canPin?: boolean; showEdit?: boolean; }) { const [posts, setPosts] = useState(initialPosts); const [tagQuery, setTagQuery] = useState(""); const [busySlug, setBusySlug] = useState(null); const visiblePosts = useMemo(() => { const query = tagQuery.trim().toLowerCase(); if (!query) return posts; return posts.filter((post) => post.tags?.some((tag) => tag.toLowerCase().includes(query))); }, [posts, tagQuery]); async function handleDelete(slug: string) { if (!window.confirm("确定要删除这条内容吗?此操作不可恢复。")) return; setBusySlug(slug); try { const res = await fetch(`/api/posts/${slug}`, { method: "DELETE" }); if (!res.ok) { const data = await res.json().catch(() => ({})); alert(data.error || "删除失败"); return; } setPosts((prev) => prev.filter((post) => post.slug !== slug)); } finally { setBusySlug(null); } } async function handleTogglePin(post: AdminPost) { setBusySlug(post.slug); try { const res = await fetch(`/api/posts/${post.slug}/pin`, { method: post.isPinned ? "DELETE" : "POST" }); const data = await res.json().catch(() => ({})); if (!res.ok) { alert(data.error || "置顶操作失败"); return; } setPosts((prev) => [...prev] .map((item) => item.slug === post.slug ? { ...item, isPinned: Boolean(data.isPinned), pinnedAt: data.pinnedAt } : item ) .sort((a, b) => { const pinnedDiff = Number(Boolean(b.isPinned)) - Number(Boolean(a.isPinned)); if (pinnedDiff !== 0) return pinnedDiff; const pinTimeDiff = (b.pinnedAt || "").localeCompare(a.pinnedAt || ""); if (pinTimeDiff !== 0) return pinTimeDiff; return b.createdAt.localeCompare(a.createdAt); }) ); } finally { setBusySlug(null); } } if (posts.length === 0) { return (
{emptyText}
); } const summary = tagQuery ? `匹配 ${visiblePosts.length} / 共 ${posts.length} 条` : `共 ${posts.length} 条`; return (

{title}

{description ?

{description}

: null}

{summary}

setTagQuery(e.target.value)} placeholder="按标签搜索" className="w-40 rounded-full border border-slate-200 bg-white px-3 py-1 text-xs shadow-inner focus:border-brand-500 focus:outline-none" /> {tagQuery ? ( ) : null}
{visiblePosts.map((post) => (
{post.isPinned ? ( 置顶 ) : null} {post.title}

{(post.author || "匿名") + " | " + (post.createdAtText || new Date(post.createdAt).toLocaleString("zh-CN", { hour12: false, timeZone: "Asia/Shanghai" }))}

{post.tags && post.tags.length > 0 ? (
{post.tags.map((tag) => ( #{tag} ))}
) : null}
{showEdit ? ( 编辑 ) : null} {canPin ? ( ) : null} {canDelete ? ( ) : null}
))}
); }