|
| 1 | +import { useAtom } from 'jotai'; |
| 2 | +import { useCallback, useEffect, useRef, useState } from 'react'; |
| 3 | +import { useNavigate, useParams } from 'react-router-dom'; |
| 4 | +import type { Message } from '../../api/room'; |
| 5 | +import { getMessages } from '../../api/room'; |
| 6 | +import { createStompClient } from '../../api/websocket'; |
| 7 | +import { isLoggedInAtom, userIdAtom } from '../../common/user'; |
| 8 | +import './ChatRoom.css'; |
| 9 | +import type { Client } from '@stomp/stompjs'; |
| 10 | + |
| 11 | +const ChatRoom = () => { |
| 12 | + const { roomId } = useParams<{ roomId: string }>(); |
| 13 | + const navigate = useNavigate(); |
| 14 | + const [messages, setMessages] = useState<Message[]>([]); |
| 15 | + const [_loading, setLoading] = useState(true); |
| 16 | + const [hasNext, setHasNext] = useState(true); |
| 17 | + const [cursor, setCursor] = useState(Date.now()); |
| 18 | + const [isLoggedIn] = useAtom(isLoggedInAtom); |
| 19 | + const [userId] = useAtom(userIdAtom); |
| 20 | + const [newMessage, setNewMessage] = useState(''); |
| 21 | + const clientRef = useRef<Client | null>(null); |
| 22 | + |
| 23 | + useEffect(() => { |
| 24 | + if (!isLoggedIn) { |
| 25 | + alert('로그인이 필요합니다.'); |
| 26 | + navigate('/'); |
| 27 | + } |
| 28 | + }, [isLoggedIn, navigate]); |
| 29 | + |
| 30 | + const fetchMessages = useCallback(async () => { |
| 31 | + if (!roomId || !hasNext) return; |
| 32 | + |
| 33 | + setLoading(true); |
| 34 | + try { |
| 35 | + const { |
| 36 | + items, |
| 37 | + nextCursor, |
| 38 | + hasNext: newHasNext, |
| 39 | + } = await getMessages(parseInt(roomId, 10), cursor); |
| 40 | + setMessages((prev) => [...items, ...prev]); // Prepend old messages |
| 41 | + setCursor(nextCursor); |
| 42 | + setHasNext(newHasNext); |
| 43 | + } catch (error) { |
| 44 | + console.error('Error fetching messages:', error); |
| 45 | + } finally { |
| 46 | + setLoading(false); |
| 47 | + } |
| 48 | + }, [roomId, cursor, hasNext]); |
| 49 | + |
| 50 | + useEffect(() => { |
| 51 | + if (isLoggedIn) { |
| 52 | + fetchMessages(); |
| 53 | + } |
| 54 | + }, [isLoggedIn, fetchMessages]); |
| 55 | + |
| 56 | + useEffect(() => { |
| 57 | + if (!roomId || !userId) return; |
| 58 | + |
| 59 | + const client = createStompClient(); |
| 60 | + clientRef.current = client; |
| 61 | + |
| 62 | + client.onConnect = () => { |
| 63 | + client.subscribe(`/sub/rooms/${roomId}`, (message) => { |
| 64 | + const receivedMessage = JSON.parse(message.body); |
| 65 | + setMessages((prevMessages) => [receivedMessage, ...prevMessages]); |
| 66 | + }); |
| 67 | + }; |
| 68 | + |
| 69 | + client.activate(); |
| 70 | + |
| 71 | + return () => { |
| 72 | + client.deactivate(); |
| 73 | + }; |
| 74 | + }, [roomId, userId]); |
| 75 | + |
| 76 | + const sendMessage = () => { |
| 77 | + if (clientRef.current && newMessage.trim() !== '' && roomId && userId) { |
| 78 | + const messageToSend = { |
| 79 | + text: newMessage, |
| 80 | + }; |
| 81 | + clientRef.current.publish({ |
| 82 | + destination: `/pub/rooms/${roomId}`, |
| 83 | + body: JSON.stringify(messageToSend), |
| 84 | + }); |
| 85 | + setNewMessage(''); |
| 86 | + } |
| 87 | + }; |
| 88 | + |
| 89 | + return ( |
| 90 | + <div className="chat-room-container"> |
| 91 | + <div className="messages-container"> |
| 92 | + {messages.map((msg, index) => { |
| 93 | + const isMyMessage = msg.senderId === userId; |
| 94 | + return ( |
| 95 | + <div |
| 96 | + key={msg.id || `msg-${index}`} |
| 97 | + className={`message-bubble ${ |
| 98 | + isMyMessage ? 'my-message' : 'other-message' |
| 99 | + }`} |
| 100 | + > |
| 101 | + <p className="message-text">{msg.text}</p> |
| 102 | + <span className="message-time"> |
| 103 | + {new Date(msg.datetimeSendAt).toLocaleTimeString()} |
| 104 | + </span> |
| 105 | + </div> |
| 106 | + ); |
| 107 | + })} |
| 108 | + </div> |
| 109 | + <div className="message-input-container"> |
| 110 | + <input |
| 111 | + type="text" |
| 112 | + placeholder="Type a message..." |
| 113 | + value={newMessage} |
| 114 | + onChange={(e) => setNewMessage(e.target.value)} |
| 115 | + onKeyPress={(e) => e.key === 'Enter' && sendMessage()} |
| 116 | + /> |
| 117 | + <button onClick={sendMessage}>Send</button> |
| 118 | + </div> |
| 119 | + </div> |
| 120 | + ); |
| 121 | +}; |
| 122 | + |
| 123 | +export default ChatRoom; |
0 commit comments