'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); // 点击"回复":记录目标回复 ID,滚动到回复框并聚焦 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 { // 答案由服务端 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 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 = replies.find((x) => x.id === r.reply_to_id); const d = parent ? getDepth(parent) + 1 : 0; map[r.id] = d; return d; }; replies.forEach((r) => getDepth(r)); return map; })(); // 正在回复的目标回复对象(用于显示 @用户名) const replyToObj = replyTo ? replies.find((x) => x.id === replyTo) : null; return ( <>