'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'; 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 [replies, setReplies] = useState([]); 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 startReply = (username) => { setReplyTo(username); 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 { // 答案由服务端 HMAC 校验 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'); } }; return ( <>
{replies.length} 条回复
{replies.length === 0 ? (
还没有回复,快来发表第一条回复吧
) : ( replies.map((r) => { const rTime = r.created_at ? new Date(r.created_at).toLocaleString('zh-CN') : ''; return (
openUser(r.username)} > {r.username || '匿名用户'} {rTime} {currentUser && (currentUser.id === r.user_id || currentUser.role === 'admin') && ( )}
{r.reply_to_username && (
{ const target = document.querySelector(`.reply-item[data-username="${r.reply_to_username}"]`); if (target) target.scrollIntoView({ behavior: 'smooth', block: 'center' }); }} > 正在回复 @{r.reply_to_username}
)}
); }) )}

发表回复

{replyTo && (
回复 @{replyTo}
)}