import { useToggle } from "@react-hookz/web"; import { useEffect, useRef, useState } from "react"; import { FaChevronDown, FaChevronUp } from "react-icons/fa"; import Button from "src/Components/Button/Button"; import { useAppSelector } from "src/utils/hooks"; import AddComment from "../AddComment/AddComment"; import CommentCard from "../CommentCard/CommentCard"; import { CommentWithReplies } from "../types"; interface Props { comment: CommentWithReplies isRoot?: boolean; canReply: boolean; onClickedReply?: () => void; onReply?: (text: string) => void } export default function Comment({ comment, canReply, isRoot, onClickedReply, onReply }: Props) { const [replyOpen, setReplyOpen] = useState(false); const [repliesCollapsed, toggleRepliesCollapsed] = useToggle(true) const [scrollToLatestReply, setScrollToLatestReply] = useState(true); const repliesContainer = useRef(null!) const user = useAppSelector(s => s.user.me); useEffect(() => { if (repliesCollapsed) setReplyOpen(false); }, [repliesCollapsed]) useEffect(() => { if (scrollToLatestReply) { repliesContainer.current?.querySelector(`:scope > div:nth-child(${comment.replies.length})`)?.scrollIntoView({ behavior: 'smooth', block: "center" }) setScrollToLatestReply(false); } }, [comment.replies.length, scrollToLatestReply]) const clickReply = () => { if (isRoot) setReplyOpen(true); else onClickedReply?.() } const handleReply = async (text: string) => { try { await onReply?.(text); toggleRepliesCollapsed(false); setReplyOpen(false); setScrollToLatestReply(true) return true; } catch (error) { return false; } } return (
{(comment.replies.length > 0 || replyOpen) &&
{comment.replies.length > 0 && }
{!repliesCollapsed && comment.replies.map(reply => )} {replyOpen && }
}
) }