'use client';
// 回复列表 + 发表回复表单
// 支持树形子回复链折叠:每条回复的子回复 >3 条时折叠,点击"继续此消息串"进入独立链视图
import { useEffect, useState, useCallback, useRef } from 'react';
import { API } from '@/lib/api';
import { useApp } from './AppProvider';
import { Icon } from './Icons';
import { renderMarkdown } from '@/lib/markdown';
import CaptchaImage from './CaptchaImage';
import { useToast } from './Toast';
function avatar(username) {
return 'https://ui-avatars.com/api/?name=' + encodeURIComponent(username || '匿名用户') +
'&background=6366f1&color=fff&size=64';
}
// 渲染单条回复(树形,带子回复折叠)
function ReplyItem({ r, children, onStartReply, onDelete, currentUser, openUser, onShowChain, chainParentId }) {
const rTime = r.created_at ? new Date(r.created_at).toLocaleString('zh-CN') : '';
const childList = children[r.id] || [];
// 子回复折叠:最多显示 3 条,超出的折叠显示"继续此消息串"
const [showAll, setShowAll] = useState(false);
const visibleChildren = chainParentId || showAll ? childList : childList.slice(0, 3);
const hiddenCount = childList.length - visibleChildren.length;
return (
openUser(r.username)}>
{r.username || '匿名用户'}
{rTime}
{currentUser && (currentUser.id === r.user_id || currentUser.role === 'admin') && (
)}
{/* 子回复列表 */}
{visibleChildren.map((child) => (
))}
{/* 子回复折叠按钮 */}
{hiddenCount > 0 && !chainParentId && (
)}
);
}
export default function ReplyList({ postId, onRefresh, chainParentId, onBack }) {
const { currentUser, openUser } = useApp();
const { toast, confirmAction } = useToast();
const [replies, setReplies] = useState([]);
const [content, setContent] = useState('');
const [captcha, setCaptcha] = useState(null);
const [captchaInput, setCaptchaInput] = useState('');
const [replyTo, setReplyTo] = useState(null);
const replyAreaRef = useRef(null);
const replyInputRef = useRef(null);
const startReply = (replyId) => {
setReplyTo(replyId);
setTimeout(() => {
replyAreaRef.current?.scrollIntoView({ behavior: 'smooth', block: 'center' });
replyInputRef.current?.focus();
}, 120);
};
const load = useCallback(async () => {
try {
const data = await API.getReplies(postId);
setReplies(data || []);
} catch { setReplies([]); }
}, [postId]);
useEffect(() => { load(); }, [load]);
useEffect(() => { API.getCaptcha().then((c) => setCaptcha(c)).catch(() => {}); }, [postId]);
const handleSubmit = async () => {
if (!currentUser) { toast('请先登录', 'warning'); return; }
if (!content.trim()) { toast('请填写回复内容', 'warning'); return; }
if (!captcha || !captchaInput.trim()) { toast('请填写验证码', 'warning'); return; }
try {
await API.createReply(postId, content.trim(), { id: captcha.id, answer: captchaInput.trim(), sig: captcha.sig }, replyTo);
API.logEvent('create_reply').catch(() => {});
setContent('');
setCaptchaInput('');
setReplyTo(null);
API.getCaptcha().then((c) => setCaptcha(c)).catch(() => {});
load();
onRefresh();
} catch (err) {
toast('回复失败:' + err.message, 'error');
API.getCaptcha().then((c) => setCaptcha(c)).catch(() => {});
setCaptchaInput('');
}
};
const handleDelete = async (replyId) => {
if (!await confirmAction('确定要删除这条回复吗?')) return;
try {
await API.deleteReply(replyId);
load();
} catch (err) {
toast('删除失败:' + err.message, 'error');
}
};
// 构建回复树(reply_id → children)
const children = {};
replies.forEach((r) => {
const pid = r.reply_to_id || '__root__';
if (!children[pid]) children[pid] = [];
children[pid].push(r);
});
// 根回复(无 reply_to 或回复目标不在当前回复列表)
const rootReplies = (children['__root__'] || []).concat(
replies.filter((r) => r.reply_to_id && !replies.find((x) => x.id === r.reply_to_id))
);
const replyToObj = replyTo ? replies.find((x) => x.id === replyTo) : null;
return (
<>
{chainParentId && onBack && (
回复链
)}
{replies.length} 条回复
{replies.length === 0 ? (
还没有回复,快来发表第一条回复吧
) : chainParentId ? (
// 链视图:显示指定回复 + 所有子回复(递归展开)
(() => {
const chainRoot = replies.find((r) => r.id === chainParentId);
if (!chainRoot) return null;
return (
);
})()
) : (
// 普通视图:显示根回复,每条回复的子回复最多 3 条
rootReplies.map((r) => (
))
)}
发表回复
{replyTo && replyToObj && (
回复
@{replyToObj.username}
)}
>
);
}