feat(comments): 支持编辑与管理可见历史,采纳展示改用楼层号

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
2026-09-16 08:05:41 +08:00
parent d032668c66
commit 1b2b87c976
14 changed files with 716 additions and 42 deletions

View File

@@ -0,0 +1,173 @@
"use client";
import { useCallback, useEffect, useState } from "react";
import Link from "next/link";
import { Loader2 } from "lucide-react";
import Modal from "@/components/Modal";
import Avatar from "@/components/Avatar";
import MarkdownBodyClient from "@/components/MarkdownBodyClient";
import {
apiAdminCommentHistory,
type CommentEditHistoryItem,
} from "@/lib/api";
const PAGE_SIZE = 10;
/**
* 版主可见:评论历次编辑前的旧正文快照(倒序分页)。
* 宽度对齐详情页评论主栏(约 800px+),长文可滚动;底部「加载更多」。
*/
export default function CommentEditHistoryModal({
open,
commentId,
onClose,
}: {
open: boolean;
commentId: number | null;
onClose: () => void;
}) {
const [loading, setLoading] = useState(false);
const [loadingMore, setLoadingMore] = useState(false);
const [error, setError] = useState("");
const [items, setItems] = useState<CommentEditHistoryItem[]>([]);
const [page, setPage] = useState(1);
const [total, setTotal] = useState(0);
const hasMore = items.length < total;
const loadPage = useCallback(
async (nextPage: number, append: boolean) => {
if (commentId == null) return;
if (append) setLoadingMore(true);
else {
setLoading(true);
setError("");
}
try {
const res = await apiAdminCommentHistory(commentId, nextPage, PAGE_SIZE);
const batch = res.items || [];
setError("");
setTotal(res.total ?? 0);
setPage(res.page ?? nextPage);
setItems((prev) => (append ? [...prev, ...batch] : batch));
} catch (e) {
const msg = e instanceof Error ? e.message : "加载失败";
if (append) {
// 追加失败不清空已有列表
setError(msg);
} else {
setError(msg);
setItems([]);
setTotal(0);
}
} finally {
setLoading(false);
setLoadingMore(false);
}
},
[commentId]
);
useEffect(() => {
if (!open || commentId == null) return;
setItems([]);
setPage(1);
setTotal(0);
setError("");
void loadPage(1, false);
}, [open, commentId, loadPage]);
return (
<Modal
open={open}
title="评论编辑历史"
description={total > 0 ? `共 ${total} 条修订记录` : undefined}
onClose={onClose}
// 对齐详情页中间评论栏可用宽度(1440 三栏布局下约 800px)
maxWidthClass="max-w-[min(840px,calc(100vw-2rem))]"
panelClassName="p-5 sm:p-6 max-h-[85vh] flex flex-col min-h-0 overflow-hidden"
bodyClassName="overflow-y-auto min-h-0 flex-1 -mx-1 px-1"
footer={
<button type="button" className="btn btn-line btn-sm" onClick={onClose}>
关闭
</button>
}
>
{loading ? (
<div className="flex items-center justify-center gap-2 py-10 meta text-[13px]">
<Loader2 size={16} className="animate-spin" />
加载中…
</div>
) : error && items.length === 0 ? (
<p className="text-[13.5px] py-6 text-center" style={{ color: "var(--danger)" }}>
{error}
</p>
) : items.length === 0 ? (
<p className="meta text-[13.5px] py-8 text-center">暂无编辑记录</p>
) : (
<div className="flex flex-col gap-4">
<ul className="flex flex-col gap-4">
{items.map((it) => {
const name = it.editor.nickname || it.editor.username || "用户";
return (
<li
key={it.id}
className="rounded-md p-3 sm:p-4"
style={{ background: "var(--panel-2)", border: "1px solid var(--line)" }}
>
<div className="flex items-center gap-2 mb-2.5">
<Link href={`/u/${it.editor.id}`} className="shrink-0">
<Avatar name={name} src={it.editor.avatar || undefined} size={28} />
</Link>
<div className="min-w-0 flex-1">
<Link
href={`/u/${it.editor.id}`}
className="text-[13px] hover:text-[var(--accent)]"
style={{ color: "var(--ink)" }}
>
{name}
</Link>
<p className="meta text-[11.5px] tabular-nums">
{new Date(it.created_at).toLocaleString("zh-CN")} · 编辑前正文
</p>
</div>
</div>
<MarkdownBodyClient
content={it.old_content}
className="prose-content prose-comment"
/>
</li>
);
})}
</ul>
{error && items.length > 0 && (
<p className="text-[12.5px] text-center" style={{ color: "var(--danger)" }}>
{error}
</p>
)}
{hasMore && (
<div className="flex justify-center pt-1 pb-1">
<button
type="button"
className="btn btn-line btn-sm"
disabled={loadingMore}
onClick={() => void loadPage(page + 1, true)}
>
{loadingMore ? (
<span className="inline-flex items-center gap-1.5">
<Loader2 size={14} className="animate-spin" />
加载中…
</span>
) : (
`加载更多(已显示 ${items.length}/${total})`
)}
</button>
</div>
)}
</div>
)}
</Modal>
);
}

View File

@@ -12,12 +12,15 @@ import {
BadgeCheck,
XCircle,
RotateCcw,
Pencil,
History,
} from "lucide-react";
import {
apiCreateComment,
apiDeleteComment,
apiRestoreComment,
apiPurgeComment,
apiUpdateComment,
apiAcceptBounty,
apiAcceptQuestion,
apiAdminApproveComment,
@@ -34,6 +37,7 @@ import Pagination from "./Pagination";
import MarkdownBodyClient from "@/components/MarkdownBodyClient";
import ConfirmDialog from "@/components/ConfirmDialog";
import DeleteCommentModal, { type DeleteCommentPayload } from "@/components/DeleteCommentModal";
import CommentEditHistoryModal from "@/components/CommentEditHistoryModal";
interface CommentSectionProps {
postId: string;
@@ -51,6 +55,8 @@ interface CommentSectionProps {
/** 悬赏或问答:可采纳时在评论旁显示采纳按钮(二者按帖子类型二选一) */
acceptMode?: "bounty" | "question" | null;
acceptedCommentId?: number;
/** 抽奖已开奖:中奖用户 ID,用于楼层旁显示「中奖」徽标 */
winnerUserIds?: number[];
/** 全站是否开放评论;缺省 true。关闭时隐藏发评/回复入口 */
allowComments?: boolean;
}
@@ -109,8 +115,10 @@ export default function CommentSection({
user,
acceptMode = null,
acceptedCommentId = 0,
winnerUserIds = [],
allowComments: allowCommentsProp = true,
}: CommentSectionProps) {
const winnerIdSet = new Set(winnerUserIds.filter((id) => id > 0));
const router = useRouter();
const [content, setContent] = useState("");
// 内联回复目标:在该评论下方就地发子评论(同一时间只有一个回复框)
@@ -127,6 +135,10 @@ export default function CommentSection({
const [purging, setPurging] = useState(false);
const [restoreTargetId, setRestoreTargetId] = useState<number | null>(null);
const [restoring, setRestoring] = useState(false);
const [editingId, setEditingId] = useState<number | null>(null);
const [editContent, setEditContent] = useState("");
const [savingEdit, setSavingEdit] = useState(false);
const [historyCommentId, setHistoryCommentId] = useState<number | null>(null);
// 折叠状态:哪些楼层展开了子回复(默认全部折叠,SSR 初始为收起)
const [expandedFloors, setExpandedFloors] = useState<Set<number>>(new Set());
const [commentsOpen, setCommentsOpen] = useState(allowCommentsProp !== false);
@@ -323,6 +335,10 @@ export default function CommentSection({
!!user &&
(user.id === comment.user?.id || canModerateBoard(user, boardId));
const canEdit = (comment: CommentNode) => canSoftDelete(comment);
const canViewHistory = !!user && canModerateBoard(user, boardId);
const canPurge = (comment: CommentNode) =>
!!user && canModerateBoard(user, boardId);
@@ -347,10 +363,84 @@ export default function CommentSection({
comment.user?.id !== authorId;
const openReply = (c: CommentNode) => {
setEditingId(null);
setReplyTarget({ id: c.id, nickname: c.user.nickname || c.user.username });
setReplyContent("");
};
const startEdit = (c: CommentNode) => {
setReplyTarget(null);
setEditingId(c.id);
setEditContent(c.content);
};
const cancelEdit = () => {
setEditingId(null);
setEditContent("");
};
const handleSaveEdit = async () => {
if (editingId == null || !editContent.trim()) return;
setSavingEdit(true);
try {
const res = await apiUpdateComment(postId, editingId, editContent);
if (res.error) {
toast(res.error);
return;
}
toast("评论已更新", "ok");
cancelEdit();
router.refresh();
} catch (e) {
toast(e instanceof Error ? e.message : "更新失败");
} finally {
setSavingEdit(false);
}
};
const renderContentOrEditor = (c: CommentNode) => {
if (editingId === c.id) {
return (
<div className="mt-1">
<textarea
value={editContent}
onChange={(e) => setEditContent(e.target.value)}
rows={4}
className="input w-full text-sm"
disabled={savingEdit}
autoFocus
/>
<div className="flex gap-2 mt-2">
<button
type="button"
className="btn btn-primary btn-sm"
disabled={savingEdit || !editContent.trim()}
onClick={() => void handleSaveEdit()}
>
{savingEdit ? "保存中…" : "保存"}
</button>
<button
type="button"
className="btn btn-line btn-sm"
disabled={savingEdit}
onClick={cancelEdit}
>
取消
</button>
</div>
</div>
);
}
return <MarkdownBodyClient content={c.content} className="prose-content prose-comment" />;
};
const timeMeta = (c: CommentNode) => (
<span className="meta text-[11.5px] inline-flex items-center gap-1.5 flex-wrap">
<span>{new Date(c.created_at).toLocaleString("zh-CN")}</span>
{c.edited && <span title="此评论曾被编辑">已编辑</span>}
</span>
);
// 切换某楼层子回复的展开/折叠
const toggleFloor = (floorId: number) => {
setExpandedFloors((prev) => {
@@ -525,9 +615,21 @@ export default function CommentSection({
恢复
</button>
);
const historyBtn = canViewHistory && (
<button
type="button"
className="cmt-mod-btn"
onClick={() => setHistoryCommentId(c.id)}
aria-label="编辑历史"
>
<History size={12} />
历史
</button>
);
const tombstoneActions =
restoreBtn || purgeBtn ? (
restoreBtn || purgeBtn || historyBtn ? (
<div className="cmt-mod-actions">
{historyBtn}
{restoreBtn}
{purgeBtn}
</div>
@@ -542,7 +644,7 @@ export default function CommentSection({
<div className="mb-1">{nameRow}</div>
{tombstoneBody}
<div className="flex items-center justify-between gap-3 mt-1.5 flex-wrap">
<span className="meta text-[11.5px]">{new Date(c.created_at).toLocaleString("zh-CN")}</span>
{timeMeta(c)}
{tombstoneActions}
</div>
</div>
@@ -576,7 +678,7 @@ export default function CommentSection({
</div>
{tombstoneBody}
<div className="flex items-center justify-between gap-3 mt-2 flex-wrap">
<span className="meta text-[11.5px]">{new Date(c.created_at).toLocaleString("zh-CN")}</span>
{timeMeta(c)}
{tombstoneActions}
</div>
{node.replies && node.replies.length > 0 && (
@@ -620,6 +722,9 @@ export default function CommentSection({
</span>
</Link>
{c.status === "pending" && <span className="badge-pending shrink-0 !text-[10px] !py-0.5 !px-1.5">待审</span>}
{acceptedCommentId === c.id && (
<span className="badge-accepted shrink-0 !text-[10px] !py-0.5 !px-1.5">已采纳</span>
)}
{isReplyToReply && parent && (
<>
<ChevronRight size={12} className="cmt-reply-arrow" aria-hidden="true" />
@@ -630,16 +735,13 @@ export default function CommentSection({
)}
</div>
<div className="mt-0.5">
<MarkdownBodyClient
content={c.content}
className="prose-content prose-comment"
/>
{renderContentOrEditor(c)}
</div>
{/* 底部行:时间 · 回复(左),删除(右) */}
<div className="flex items-center justify-between mt-1.5">
<div className="flex items-center gap-3">
<span className="meta text-[11.5px]">{new Date(c.created_at).toLocaleString("zh-CN")}</span>
{commentsOpen && user && (
{timeMeta(c)}
{commentsOpen && user && editingId !== c.id && (
<button
onClick={() => openReply(c)}
className={`cmt-reply-btn transition-colors ${
@@ -651,9 +753,6 @@ export default function CommentSection({
回复
</button>
)}
{acceptedCommentId === c.id && (
<span className="badge-type !text-[10px] !py-0.5 !px-1.5">已采纳</span>
)}
{canAccept(c) && (
<button
type="button"
@@ -690,8 +789,31 @@ export default function CommentSection({
</>
)}
</div>
{(canSoftDelete(c) || (canPurge(c) && !c.deleted)) && (
{(canEdit(c) || canSoftDelete(c) || (canPurge(c) && !c.deleted) || canViewHistory) && (
<div className="cmt-mod-actions" role="group" aria-label="评论管理">
{canEdit(c) && editingId !== c.id && (
<button
type="button"
className="cmt-mod-btn"
onClick={() => startEdit(c)}
disabled={savingEdit}
aria-label="编辑评论"
>
<Pencil size={12} />
编辑
</button>
)}
{canViewHistory && (
<button
type="button"
className="cmt-mod-btn"
onClick={() => setHistoryCommentId(c.id)}
aria-label="编辑历史"
>
<History size={12} />
历史
</button>
)}
{canSoftDelete(c) && (
<button
type="button"
@@ -742,29 +864,32 @@ export default function CommentSection({
<Link href={`/u/${c.user.id}`} className="shrink-0 mt-0.5" aria-label={c.user.nickname || c.user.username}>
<Avatar name={c.user.nickname || c.user.username} src={c.user.avatar || undefined} size={38} />
</Link>
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2.5 mb-1.5">
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2.5 mb-1.5 flex-wrap">
<Link href={`/u/${c.user.id}`} className="group">
<span className="truncate group-hover:text-[var(--accent)] transition-colors text-sm" style={{ color: "var(--ink)" }}>
{c.user.nickname || c.user.username}
</span>
</Link>
{c.status === "pending" && <span className="badge-pending shrink-0">待审</span>}
{acceptedCommentId === c.id && (
<span className="badge-accepted shrink-0">已采纳</span>
)}
{winnerIdSet.has(c.user.id) && (
<span className="badge-winner shrink-0">中奖楼层</span>
)}
{floor && (
<a href={`#comment-${c.id}`} className="cmt-floor-label" aria-label={`楼层 ${floor}`}>
#{floor}
</a>
)}
</div>
<MarkdownBodyClient
content={c.content}
className="prose-content prose-comment"
/>
{renderContentOrEditor(c)}
{/* 底部行:时间 · 回复(左),删除(右) */}
<div className="flex items-center justify-between mt-2">
<div className="flex items-center gap-3">
<span className="meta text-[11.5px]">{new Date(c.created_at).toLocaleString("zh-CN")}</span>
{commentsOpen && user && (
{timeMeta(c)}
{commentsOpen && user && editingId !== c.id && (
<button
onClick={() => openReply(c)}
className={`cmt-reply-btn transition-colors ${
@@ -776,9 +901,6 @@ export default function CommentSection({
回复
</button>
)}
{acceptedCommentId === c.id && (
<span className="badge-type !text-[10px] !py-0.5 !px-1.5">已采纳</span>
)}
{canAccept(c) && (
<button
type="button"
@@ -815,8 +937,31 @@ export default function CommentSection({
</>
)}
</div>
{(canSoftDelete(c) || canPurge(c)) && (
{(canEdit(c) || canSoftDelete(c) || canPurge(c) || canViewHistory) && (
<div className="cmt-mod-actions" role="group" aria-label="评论管理">
{canEdit(c) && editingId !== c.id && (
<button
type="button"
className="cmt-mod-btn"
onClick={() => startEdit(c)}
disabled={savingEdit}
aria-label="编辑评论"
>
<Pencil size={12} />
编辑
</button>
)}
{canViewHistory && (
<button
type="button"
className="cmt-mod-btn"
onClick={() => setHistoryCommentId(c.id)}
aria-label="编辑历史"
>
<History size={12} />
历史
</button>
)}
{canSoftDelete(c) && (
<button
type="button"
@@ -1021,6 +1166,12 @@ export default function CommentSection({
if (!purging) setPurgeTargetId(null);
}}
/>
<CommentEditHistoryModal
open={historyCommentId != null}
commentId={historyCommentId}
onClose={() => setHistoryCommentId(null)}
/>
</section>
);
}

View File

@@ -81,7 +81,18 @@ function QuestionPanel({ postId, state }: { postId: number; state: QuestionState
<p className="meta text-[12.5px] mt-1">
{state.solved
? state.accepted_comment_id
? `已采纳评论 #${state.accepted_comment_id}`
? (
<>
已采纳{" "}
<a
href={`#comment-${state.accepted_comment_id}`}
className="hover:underline"
style={{ color: "var(--accent)" }}
>
#{state.accepted_floor || "?"}
</a>
</>
)
: "作者已标记为已解决"
: "可在评论旁采纳答案,或手动标记已解决"}
</p>
@@ -295,7 +306,7 @@ function BountyPanel({ postId, state }: { postId: number; state: BountyState })
: state.refunded
? "已退回给发帖人"
: state.accepted_comment_id
? `已采纳评论 #${state.accepted_comment_id}`
? null
: state.escrowed
? "积分已托管,采纳优质回答后发放"
: "悬赏未托管";
@@ -308,7 +319,20 @@ function BountyPanel({ postId, state }: { postId: number; state: BountyState })
悬赏 {state.points} 积分
</h2>
<p className="meta text-[12.5px] mt-1">
{statusText}
{state.accepted_comment_id ? (
<>
已采纳{" "}
<a
href={`#comment-${state.accepted_comment_id}`}
className="hover:underline"
style={{ color: "var(--accent)" }}
>
#{state.accepted_floor || "?"}
</a>
</>
) : (
statusText
)}
{state.ends_at && !state.settled ? ` · 截止 ${formatEndsAt(state.ends_at)}` : ""}
</p>
</div>
@@ -404,11 +428,10 @@ function LotteryPanel({
<li key={w.id}>
<Link
href={`/u/${w.id}`}
className="inline-flex items-center gap-2 px-2.5 py-1.5 rounded-full"
style={{ background: "var(--accent-soft)", color: "var(--accent)" }}
className="badge-winner inline-flex items-center gap-2 !py-1.5 !px-2.5 !text-[13px] !font-medium"
>
<Avatar name={w.nickname || w.username} src={w.avatar || undefined} size={22} />
<span className="text-[13px]">{w.nickname || w.username}</span>
<span>{w.nickname || w.username}</span>
</Link>
</li>
))}