'use client'; // 回复列表 + 发表回复表单 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'; import { useTranslation } from 'react-i18next'; function avatar(username) { return 'https://ui-avatars.com/api/?name=' + encodeURIComponent(username || '匿名用户') + '&background=6366f1&color=fff&size=64'; } export default function ReplyList({ postId, onRefresh }) { const { currentUser, openUser } = useApp(); const { toast, confirmAction } = useToast(); const { t } = useTranslation(); const [replies, setReplies] = useState(null); const [loading, setLoading] = useState(true); const [showLoading, setShowLoading] = useState(false); const [content, setContent] = useState(''); const [captcha, setCaptcha] = useState(null); const [captchaInput, setCaptchaInput] = useState(''); // 正在回复的用户(hover 回复按钮 → 回填到回复框) const [replyTo, setReplyTo] = useState(null); const replyAreaRef = useRef(null); const replyInputRef = useRef(null); const loadRequestRef = useRef(0); // 点击"回复":记录目标回复 ID,滚动到回复框并聚焦 const startReply = (replyId) => { setReplyTo(replyId); setTimeout(() => { replyAreaRef.current?.scrollIntoView({ behavior: 'smooth', block: 'center' }); replyInputRef.current?.focus(); }, 120); }; const load = useCallback(async ({ reset = false } = {}) => { const requestId = ++loadRequestRef.current; if (reset) setReplies(null); setLoading(true); try { const data = await API.getReplies(postId); if (requestId !== loadRequestRef.current) return; setReplies(data || []); } catch { if (requestId !== loadRequestRef.current) return; setReplies([]); } finally { if (requestId === loadRequestRef.current) setLoading(false); } }, [postId]); useEffect(() => { load({ reset: true }); return () => { loadRequestRef.current += 1; }; }, [load]); // 快请求不闪加载态;慢请求的加载动画由 CSS 等帖子 View Transition 结束后再淡入。 useEffect(() => { if (!loading) { setShowLoading(false); return; } const timer = setTimeout(() => setShowLoading(true), 180); return () => clearTimeout(timer); }, [loading]); 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 { // 答案由服务端 HMAC 校验 await API.createReply( postId, content.trim(), { id: captcha.id, answer: captchaInput.trim(), sig: captcha.sig }, replyTo, replyToObj?.username ); 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_to_id 精确追踪回复链) const loadedReplies = replies || []; const replyDepths = (() => { const map = {}; const getDepth = (r) => { if (map[r.id] !== undefined) return map[r.id]; if (!r.reply_to_id) { map[r.id] = 0; return 0; } const parent = loadedReplies.find((x) => x.id === r.reply_to_id); const d = parent ? getDepth(parent) + 1 : 0; map[r.id] = d; return d; }; loadedReplies.forEach((r) => getDepth(r)); return map; })(); // 正在回复的目标回复对象(用于显示 @用户名) const replyToObj = replyTo ? loadedReplies.find((x) => x.id === replyTo) : null; return ( <> {loading && replies === null ? ( showLoading && (
) ) : ( <>
{loadedReplies.length} 条回复
{loadedReplies.length === 0 ? (
还没有回复,快来发表第一条回复吧
) : ( loadedReplies.map((r) => { const rTime = r.created_at ? new Date(r.created_at).toLocaleString('zh-CN') : ''; const nestDepth = Math.min(replyDepths[r.id] || 0, 5); return (
openUser(r.username)} > {r.username || '匿名用户'} {rTime} {currentUser && (currentUser.id === r.user_id || currentUser.role === 'admin') && ( )}
); }) )}
)}

发表回复

{replyTo && replyToObj && (
回复 @{replyToObj.username}
)}