diff --git a/client/components/chat/index.tsx b/client/components/chat/index.tsx index 15844f3..22d1953 100644 --- a/client/components/chat/index.tsx +++ b/client/components/chat/index.tsx @@ -1,5 +1,5 @@ -import { FC, useEffect, useState } from "react" -import { CHAT_URL } from "../../config" +import { FC, KeyboardEventHandler, useEffect, useRef, useState } from "react" +import { CHAT_URL, MAX_CHAT_MESSAGES } from "../../config" import useSession from "../../hooks/useSession" import { ChatMessage as Message } from "../../types" import Input from "../common/Input" @@ -8,15 +8,43 @@ import ChatMessage from "../message/ChatMessage" const Chat: FC = () => { const { session } = useSession() const [messages, setMessages] = useState([]) + const wsRef = useRef(null) + const messagesEndRef = useRef(null) useEffect(() => { - const ws = new WebSocket(CHAT_URL) - ws.onmessage = (ev) => { + wsRef.current = new WebSocket(CHAT_URL) + wsRef.current.onmessage = (ev) => { const newMsg = JSON.parse(ev.data) as Message - setMessages((old) => [...old, newMsg]) + if (typeof newMsg === "string") return + setMessages((old) => { + if (old.length >= MAX_CHAT_MESSAGES) old.shift() + return [...old, newMsg] + }) + } + + return () => { + if (wsRef.current) wsRef.current.close() } }, []) + useEffect(() => { + messagesEndRef.current?.scrollIntoView({ behavior: "smooth" }) + }, [messages]) + + const handleChatInput: KeyboardEventHandler = (event) => { + if (event.key === "Enter" && wsRef.current) { + const msg = JSON.stringify({ + fromUser: "niku", + fromUserID: 10, + toUser: "niku", + toUserID: 10, + content: event.currentTarget.value, + }) + wsRef.current.send(msg) + event.currentTarget.value = "" + } + } + return (
@@ -26,12 +54,14 @@ const Chat: FC = () => { {messages.map((message) => ( ))} +
diff --git a/client/config/index.ts b/client/config/index.ts index dcf2f6b..8dc7f7e 100644 --- a/client/config/index.ts +++ b/client/config/index.ts @@ -1,2 +1,3 @@ export const KRATOS_URL = "http://127.0.0.1:4433" export const CHAT_URL = "ws://localhost:1323" +export const MAX_CHAT_MESSAGES = 50