/* eslint-disable react-hooks/exhaustive-deps */ /* eslint-disable @typescript-eslint/no-explicit-any */ import { FormEvent, useEffect, useRef, useState } from "react"; import useSocketStore from "../stores/useSocketStore"; import { UIEvent } from "react"; import "./Chat.css"; import ChevronDownIcon from "./icons/ChevronDownIcon"; import CloseIcon from "./icons/CloseIcon"; import useChatStore from "../stores/useChatStore"; interface ChatProps { className?: string; handleClose: () => void; } function Chat({ className, handleClose }: ChatProps) { const socket = useSocketStore((state) => state.socket); const [message, setMessage] = useState(""); const [messages, setMessages] = useChatStore((state) => [ state.messages, state.setMessages, ]); const [isBottom, setIsBottom] = useState(true); const [isNewMessage, setIsNewMessage] = useState(false); const inputRef = useRef(null); const messagesEndRef = useRef(null); function sendMessage(e: FormEvent) { e.preventDefault(); if (!socket || !message) return; socket.emit("message", socket.id, message); setMessage(""); inputRef.current?.focus(); messagesEndRef.current?.scrollIntoView(); } const handleScroll = (e: UIEvent) => { if ( e.currentTarget.scrollHeight - Math.round(e.currentTarget.scrollTop) === e.currentTarget.clientHeight ) { setIsBottom(true); setIsNewMessage(false); } else { setIsBottom(false); } }; useEffect(() => { function handleKeyUp(e: KeyboardEvent) { if (e.key === "Escape") { handleClose(); } } document.addEventListener("keyup", handleKeyUp); return () => { document.removeEventListener("keyup", handleKeyUp); }; }, []); useEffect(() => { if (!socket) return; console.log(messages); console.log("CHAT Socket Init: ", socket.id); socket.on("message", (socketId, message) => { setMessages([ ...useChatStore.getState().messages, { id: socketId, message }, ]); }); return () => { socket.off("message"); }; }, [socket]); useEffect(() => { if (isBottom) { messagesEndRef.current?.scrollIntoView({ behavior: "smooth" }); } else { setIsNewMessage(true); } }, [messages]); return (

Чат

{messages.map((data, index) => (

{data.city && data.city + ":"} {data.message}

))}
messagesEndRef.current?.scrollIntoView({ behavior: "smooth" }) } className={[ "absolute mr-8 right-0 bottom-[136px] bg-neutral-950 p-2 rounded-full shadow transition-opacity", isBottom ? "opacity-0 pointer-events-none cursor-auto" : "opacity-100 pointer-events-auto cursor-pointer", ].join(" ")} >
setMessage(e.target.value)} className="px-3 py-2 outline-none rounded" />
); } export default Chat;