"use client"; import { useEffect, useMemo, useState } from "react"; import { buildCommunityAvatarText, formatCommunityTime, maskCommunityUserId, type CommunityComment, } from "./CommunityMemoCard"; import { renderCommunityMarkdown } from "./renderMarkdown"; import { emitCommunityChanged } from "./communityEvents"; import styles from "./community.module.css"; type CommunityCommentThreadProps = { memoId: string; userId: string; memoOwnerId: string; comments?: CommunityComment[]; onCommentsChanged?: (comments: CommunityComment[]) => void; }; export function CommunityCommentThread({ memoId, userId, memoOwnerId, comments = [], onCommentsChanged, }: CommunityCommentThreadProps) { const [items, setItems] = useState(comments); const [content, setContent] = useState(""); const [submitting, setSubmitting] = useState(false); const [deletingId, setDeletingId] = useState(null); const [error, setError] = useState(null); useEffect(() => { setItems(comments); }, [comments]); const syncComments = (nextItems: CommunityComment[]) => { setItems(nextItems); onCommentsChanged?.(nextItems); }; const canSubmit = useMemo(() => Boolean(content.trim()) && !submitting, [content, submitting]); const handleSubmit = async () => { const trimmed = content.trim(); if (!trimmed || submitting) { return; } setSubmitting(true); setError(null); try { const response = await fetch(`/api/community/memos/${memoId}/comments`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ user_id: userId, content: trimmed }), }); const data = await response.json().catch(() => null); if (!response.ok || !data?.comment) { setError(data?.error || "回复发布失败,请稍后重试。"); return; } const nextItems = [...items, data.comment as CommunityComment]; syncComments(nextItems); setContent(""); emitCommunityChanged(); } catch { setError("网络异常,请稍后重试。"); } finally { setSubmitting(false); } }; const handleDelete = async (commentId: string) => { if (!window.confirm("确定删除这条评论吗?")) { return; } setDeletingId(commentId); setError(null); try { const response = await fetch( `/api/community/comments/${commentId}?user_id=${encodeURIComponent(userId)}`, { method: "DELETE" } ); const data = await response.json().catch(() => null); if (!response.ok) { setError(data?.error || "评论删除失败,请稍后重试。"); return; } const nextItems = items.filter((item) => item.id !== commentId); syncComments(nextItems); emitCommunityChanged(); } catch { setError("网络异常,请稍后重试。"); } finally { setDeletingId(null); } }; return (
Discussion

评论区

把补充说明、追问和实践反馈继续沉淀在这里。