import { useState } from "react"; import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query"; import { Button } from "@/components/ui/button"; import { Textarea } from "@/components/ui/textarea"; import { Input } from "@/components/ui/input"; import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"; import { Separator } from "@/components/ui/separator"; import { ThumbsUp, ThumbsDown, ChevronDown, ChevronUp, ArrowUpDown } from "lucide-react"; import { formatTimeAgo } from "@/lib/utils"; import { apiRequest } from "@/lib/queryClient"; import AvatarPreviewDialog from "@/components/AvatarPreviewDialog"; interface Comment { id: string; content: string; nickname: string; avatar?: string; createdAt: string; likesCount: number; dislikesCount: number; repliesCount: number; parentId?: string; } interface CommentSectionProps { articleId: string; } function getUserIdentifier() { let userId = localStorage.getItem('commentUserId'); if (!userId) { userId = 'user_' + Math.random().toString(36).substring(2, 15); localStorage.setItem('commentUserId', userId); } return userId; } function CommentForm({ articleId, parentId, onSuccess, placeholder = "Add comment...", buttonText = "Comment" }: { articleId: string; parentId?: string; onSuccess?: () => void; placeholder?: string; buttonText?: string; }) { const [content, setContent] = useState(""); const [nickname, setNickname] = useState(() => localStorage.getItem('commentNickname') || "" ); const [showForm, setShowForm] = useState(false); const [isFocused, setIsFocused] = useState(false); const queryClient = useQueryClient(); const createComment = useMutation({ mutationFn: async (data: { content: string; nickname: string; parentId?: string }) => { const response = await apiRequest('POST', `/api/articles/${articleId}/comments`, data); return response.json(); }, onSuccess: () => { setContent(""); setShowForm(false); setIsFocused(false); localStorage.setItem('commentNickname', nickname); queryClient.invalidateQueries({ queryKey: ['/api/articles', articleId, 'comments'] }); if (parentId) { queryClient.invalidateQueries({ queryKey: ['/api/comments', parentId, 'replies'] }); } onSuccess?.(); }, }); const handleSubmit = (e: React.FormEvent) => { e.preventDefault(); if (!content.trim() || !nickname.trim()) return; createComment.mutate({ content: content.trim(), nickname: nickname.trim(), parentId }); }; if (!showForm && parentId) { return ( ); } if (!showForm && !parentId) { return (
setShowForm(true)} data-testid="button-add-comment" > 👤
{placeholder}
); } return (
👤
{!localStorage.getItem('commentNickname') && ( setNickname(e.target.value)} className="border-0 border-b-2 border-muted rounded-none bg-transparent px-0 focus-visible:ring-0 focus-visible:border-foreground" data-testid="input-nickname" required /> )}