Add admin pinning and user favorites with role management

This commit is contained in:
爱喝水的木子
2026-03-20 13:55:27 +08:00
parent e6788d0e8f
commit 8e6bd210a8
19 changed files with 629 additions and 101 deletions

View File

@@ -8,13 +8,24 @@ type AdminPost = Post & { createdAtText?: string };
export function AdminPostList({
initialPosts,
canDelete = false
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<AdminPost[]>(initialPosts);
const [tagQuery, setTagQuery] = useState("");
const [busySlug, setBusySlug] = useState<string | null>(null);
const visiblePosts = useMemo(() => {
const query = tagQuery.trim().toLowerCase();
@@ -25,33 +36,74 @@ export function AdminPostList({
async function handleDelete(slug: string) {
if (!window.confirm("确定要删除这条内容吗?此操作不可恢复。")) return;
const res = await fetch(`/api/posts/${slug}`, { method: "DELETE" });
if (!res.ok) {
const data = await res.json().catch(() => ({}));
alert(data.error || "删除失败");
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));
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 (
<div className="rounded-2xl bg-white/80 p-4 text-sm text-slate-500 shadow-sm ring-1 ring-slate-100">
{emptyText}
</div>
);
}
const summary = tagQuery
? `匹配 ${visiblePosts.length} / 共 ${posts.length}`
: `${posts.length}`;
const summary = tagQuery ? `匹配 ${visiblePosts.length} / 共 ${posts.length}` : `${posts.length}`;
return (
<div className="space-y-3 rounded-2xl bg-white/80 p-4 shadow-sm ring-1 ring-slate-100">
<div className="flex flex-wrap items-center justify-between gap-3">
<div>
<h3 className="text-lg font-semibold"></h3>
<h3 className="text-lg font-semibold">{title}</h3>
{description ? <p className="mt-1 text-sm text-slate-500">{description}</p> : null}
<p className="text-xs text-slate-400">{summary}</p>
</div>
<div className="flex items-center gap-2">
@@ -80,7 +132,12 @@ export function AdminPostList({
className="flex flex-wrap items-center justify-between gap-3 rounded-xl border border-slate-100 bg-white/70 p-3"
>
<div>
<Link href={`/p/${post.slug}`} className="font-medium text-slate-900 hover:text-brand-600">
{post.isPinned ? (
<span className="mb-1 inline-flex rounded-full bg-amber-50 px-2 py-1 text-xs font-medium text-amber-700 ring-1 ring-amber-100">
</span>
) : null}
<Link href={`/p/${post.slug}`} className="block font-medium text-slate-900 hover:text-brand-600">
{post.title}
</Link>
<p className="text-xs text-slate-500">
@@ -103,17 +160,30 @@ export function AdminPostList({
) : null}
</div>
<div className="flex items-center gap-2">
<Link
href={`/admin/edit/${post.slug}`}
className="rounded-full bg-brand-50 px-3 py-1 text-xs font-medium text-brand-700 ring-1 ring-brand-100 hover:bg-brand-100"
>
</Link>
{showEdit ? (
<Link
href={`/admin/edit/${post.slug}`}
className="rounded-full bg-brand-50 px-3 py-1 text-xs font-medium text-brand-700 ring-1 ring-brand-100 hover:bg-brand-100"
>
</Link>
) : null}
{canPin ? (
<button
type="button"
disabled={busySlug === post.slug}
onClick={() => handleTogglePin(post)}
className="rounded-full bg-amber-50 px-3 py-1 text-xs font-medium text-amber-700 ring-1 ring-amber-100 hover:bg-amber-100 disabled:opacity-60"
>
{post.isPinned ? "取消置顶" : "置顶"}
</button>
) : null}
{canDelete ? (
<button
type="button"
disabled={busySlug === post.slug}
onClick={() => handleDelete(post.slug)}
className="rounded-full bg-red-50 px-3 py-1 text-xs font-medium text-red-600 ring-1 ring-red-100 hover:bg-red-100"
className="rounded-full bg-red-50 px-3 py-1 text-xs font-medium text-red-600 ring-1 ring-red-100 hover:bg-red-100 disabled:opacity-60"
>
</button>

View File

@@ -6,19 +6,26 @@ type ManagedPost = {
slug: string;
title: string;
createdAt: string;
isPinned?: boolean;
};
type ManagedUser = {
id: string;
username: string;
displayName: string;
role: "admin" | "user";
role: "user" | "sponsor" | "admin";
dailyPostLimit: number;
postCount: number;
todayPostCount: number;
posts: ManagedPost[];
};
const ROLE_OPTIONS: Array<{ value: ManagedUser["role"]; label: string }> = [
{ value: "user", label: "普通" },
{ value: "sponsor", label: "赞助" },
{ value: "admin", label: "管理员" }
];
export function AdminUserManager({
initialUsers,
currentUserId
@@ -67,13 +74,46 @@ export function AdminUserManager({
);
}
async function handleSaveLimit(userId: string, dailyPostLimit: number) {
async function handleTogglePin(userId: string, slug: string, isPinned: boolean) {
const res = await fetch(`/api/posts/${slug}/pin`, {
method: isPinned ? "DELETE" : "POST"
});
const data = await res.json().catch(() => ({}));
if (!res.ok) {
alert(data.error || "置顶操作失败");
return;
}
setUsers((prev) =>
prev.map((user) =>
user.id !== userId
? user
: {
...user,
posts: [...user.posts]
.map((post) =>
post.slug === slug ? { ...post, isPinned: Boolean(data.isPinned) } : post
)
.sort((a, b) => {
const pinnedDiff = Number(Boolean(b.isPinned)) - Number(Boolean(a.isPinned));
if (pinnedDiff !== 0) return pinnedDiff;
return b.createdAt.localeCompare(a.createdAt);
})
}
)
);
}
async function handleSaveUser(
userId: string,
payload: { dailyPostLimit: number; role: ManagedUser["role"] }
) {
setSavingId(userId);
try {
const res = await fetch(`/api/admin/users/${userId}`, {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ dailyPostLimit })
body: JSON.stringify(payload)
});
const data = await res.json().catch(() => ({}));
if (!res.ok) {
@@ -83,7 +123,13 @@ export function AdminUserManager({
setUsers((prev) =>
prev.map((user) =>
user.id === userId ? { ...user, dailyPostLimit: data.dailyPostLimit ?? dailyPostLimit } : user
user.id === userId
? {
...user,
dailyPostLimit: data.dailyPostLimit ?? payload.dailyPostLimit,
role: data.role ?? payload.role
}
: user
)
);
} finally {
@@ -109,7 +155,9 @@ export function AdminUserManager({
<div className="flex flex-wrap items-center justify-between gap-3">
<div>
<h3 className="text-lg font-semibold text-slate-900"></h3>
<p className="text-sm text-slate-500"></p>
<p className="text-sm text-slate-500">
</p>
</div>
<input
value={query}
@@ -130,8 +178,9 @@ export function AdminUserManager({
currentUserId={currentUserId}
saving={savingId === user.id}
onDeletePost={handleDeletePost}
onTogglePin={handleTogglePin}
onDeleteUser={handleDeleteUser}
onSaveLimit={handleSaveLimit}
onSaveUser={handleSaveUser}
/>
))
)}
@@ -151,17 +200,23 @@ function AdminUserCard({
currentUserId,
saving,
onDeletePost,
onTogglePin,
onDeleteUser,
onSaveLimit
onSaveUser
}: {
user: ManagedUser;
currentUserId: string;
saving: boolean;
onDeletePost: (slug: string) => Promise<void>;
onTogglePin: (userId: string, slug: string, isPinned: boolean) => Promise<void>;
onDeleteUser: (userId: string) => Promise<void>;
onSaveLimit: (userId: string, dailyPostLimit: number) => Promise<void>;
onSaveUser: (
userId: string,
payload: { dailyPostLimit: number; role: ManagedUser["role"] }
) => Promise<void>;
}) {
const [limit, setLimit] = useState(user.dailyPostLimit);
const [role, setRole] = useState<ManagedUser["role"]>(user.role);
return (
<div className="rounded-2xl border border-slate-100 bg-white/70 p-4">
@@ -171,11 +226,23 @@ function AdminUserCard({
{user.displayName} <span className="text-sm font-normal text-slate-500">(@{user.username})</span>
</h4>
<p className="mt-1 text-sm text-slate-500">
{user.role === "admin" ? "管理员" : "用户"} | {user.postCount} | {user.todayPostCount}
{ROLE_OPTIONS.find((item) => item.value === user.role)?.label || "普通"} |
{user.postCount} | {user.todayPostCount}
</p>
</div>
<div className="flex flex-wrap items-center gap-2">
<select
value={role}
onChange={(e) => setRole(e.target.value as ManagedUser["role"])}
className="rounded-full border border-slate-200 bg-white px-3 py-2 text-sm shadow-inner focus:border-brand-500 focus:outline-none"
>
{ROLE_OPTIONS.map((option) => (
<option key={option.value} value={option.value}>
{option.label}
</option>
))}
</select>
<input
type="number"
min={0}
@@ -186,10 +253,10 @@ function AdminUserCard({
<button
type="button"
disabled={saving}
onClick={() => onSaveLimit(user.id, limit)}
onClick={() => onSaveUser(user.id, { dailyPostLimit: limit, role })}
className="rounded-full bg-brand-50 px-3 py-2 text-xs font-medium text-brand-700 ring-1 ring-brand-100 hover:bg-brand-100 disabled:opacity-60"
>
</button>
{user.id !== currentUserId ? (
<button
@@ -213,7 +280,12 @@ function AdminUserCard({
className="flex flex-wrap items-center justify-between gap-3 rounded-xl border border-slate-100 bg-white px-3 py-2"
>
<div>
<a href={`/p/${post.slug}`} className="text-sm font-medium text-slate-900 hover:text-brand-600">
{post.isPinned ? (
<span className="mb-1 inline-flex rounded-full bg-amber-50 px-2 py-1 text-xs font-medium text-amber-700 ring-1 ring-amber-100">
</span>
) : null}
<a href={`/p/${post.slug}`} className="block text-sm font-medium text-slate-900 hover:text-brand-600">
{post.title}
</a>
<p className="text-xs text-slate-500">
@@ -223,13 +295,22 @@ function AdminUserCard({
})}
</p>
</div>
<button
type="button"
onClick={() => onDeletePost(post.slug)}
className="rounded-full bg-red-50 px-3 py-1 text-xs font-medium text-red-600 ring-1 ring-red-100 hover:bg-red-100"
>
</button>
<div className="flex items-center gap-2">
<button
type="button"
onClick={() => onTogglePin(user.id, post.slug, Boolean(post.isPinned))}
className="rounded-full bg-amber-50 px-3 py-1 text-xs font-medium text-amber-700 ring-1 ring-amber-100 hover:bg-amber-100"
>
{post.isPinned ? "取消置顶" : "置顶"}
</button>
<button
type="button"
onClick={() => onDeletePost(post.slug)}
className="rounded-full bg-red-50 px-3 py-1 text-xs font-medium text-red-600 ring-1 ring-red-100 hover:bg-red-100"
>
</button>
</div>
</div>
))
)}

View File

@@ -0,0 +1,70 @@
"use client";
import Link from "next/link";
import { useState } from "react";
type FavoriteButtonProps = {
slug: string;
initialFavorited: boolean;
initialCount: number;
canFavorite: boolean;
};
export function FavoriteButton({
slug,
initialFavorited,
initialCount,
canFavorite
}: FavoriteButtonProps) {
const [favorited, setFavorited] = useState(initialFavorited);
const [count, setCount] = useState(initialCount);
const [loading, setLoading] = useState(false);
async function handleToggle() {
if (loading) return;
setLoading(true);
try {
const res = await fetch(`/api/posts/${slug}/favorite`, {
method: favorited ? "DELETE" : "POST"
});
const data = await res.json().catch(() => ({}));
if (!res.ok) {
alert(data.error || "收藏操作失败");
return;
}
setFavorited(Boolean(data.isFavorited));
setCount(typeof data.favoriteCount === "number" ? data.favoriteCount : count);
} finally {
setLoading(false);
}
}
if (!canFavorite) {
return (
<Link
href={`/login?next=/p/${encodeURIComponent(slug)}`}
className="rounded-full bg-amber-50 px-3 py-2 text-sm font-medium text-amber-700 ring-1 ring-amber-100 hover:bg-amber-100"
>
</Link>
);
}
return (
<button
type="button"
onClick={handleToggle}
disabled={loading}
className={`rounded-full px-3 py-2 text-sm font-medium ring-1 transition disabled:cursor-not-allowed disabled:opacity-60 ${
favorited
? "bg-rose-50 text-rose-700 ring-rose-100 hover:bg-rose-100"
: "bg-slate-100 text-slate-700 ring-slate-200 hover:bg-slate-200"
}`}
>
{loading ? "处理中..." : `${favorited ? "已收藏" : "收藏"} · ${count}`}
</button>
);
}

View File

@@ -14,6 +14,11 @@ export function PostCard({ post }: Props) {
<article className="group rounded-2xl bg-white/80 p-4 shadow-sm ring-1 ring-slate-100 transition-[transform,box-shadow] duration-300 will-change-transform transform-gpu hover:shadow-lg hover:[transform:perspective(900px)_translateY(-4px)_rotateX(2deg)_rotateY(-2deg)]">
<div className="flex items-start justify-between gap-3">
<div className="space-y-1">
{post.isPinned ? (
<span className="inline-flex rounded-full bg-amber-50 px-2 py-1 text-xs font-medium text-amber-700 ring-1 ring-amber-100">
</span>
) : null}
<Link
href={`/p/${post.slug}`}
className="block text-lg font-semibold text-slate-900 transition group-hover:text-brand-600"