'use client'; import { useState, useEffect, useRef } from 'react'; import { getAnonymousUserId, getDisplayName, setDisplayName } from '@/lib/client/anonymousUser'; interface CommentFormProps { postId: string; onSuccess?: (comment: any) => void; } export default function CommentForm({ postId, onSuccess }: CommentFormProps) { const [content, setContent] = useState(''); const [displayName, setDisplayNameState] = useState(''); const [isLoading, setIsLoading] = useState(false); const [error, setError] = useState(''); const textareaRef = useRef(null); // Load display name from localStorage on mount useEffect(() => { const savedName = getDisplayName(); if (savedName) { setDisplayNameState(savedName); } }, []); // Auto-resize textarea useEffect(() => { if (textareaRef.current) { textareaRef.current.style.height = 'auto'; textareaRef.current.style.height = textareaRef.current.scrollHeight + 'px'; } }, [content]); const handleSubmit = async (e: React.FormEvent) => { e.preventDefault(); setError(''); // Validation if (content.trim().length < 1 || content.trim().length > 2000) { setError('Comment must be 1-2000 characters'); return; } if (displayName.trim().length < 3 || displayName.trim().length > 50) { setError('Display name must be 3-50 characters'); return; } setIsLoading(true); try { const anonymousId = getAnonymousUserId(); const response = await fetch(`/api/posts/${postId}/comments-web`, { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ content: content.trim(), displayName: displayName.trim(), anonymousId, }), }); if (!response.ok) { const data = await response.json(); throw new Error(data.error || 'Failed to post comment'); } const data = await response.json(); // Save display name to localStorage setDisplayName(displayName.trim()); // Clear form setContent(''); setError(''); // Call success callback and trigger refresh if (onSuccess) { onSuccess(data.comment); } // Also trigger refresh event window.dispatchEvent(new Event(`refresh-comments-${postId}`)); } catch (err) { setError(err instanceof Error ? err.message : 'Failed to post comment'); } finally { setIsLoading(false); } }; const isValid = content.trim().length >= 1 && content.trim().length <= 2000 && displayName.trim().length >= 3 && displayName.trim().length <= 50; return (

Leave a comment