Skip to content

Commit

Permalink
Merge pull request #46 from KTB-Hackathon-GoLang/dev
Browse files Browse the repository at this point in the history
test
  • Loading branch information
sayyyho authored Sep 6, 2024
2 parents 484f9a7 + 4800c77 commit a59a9ff
Showing 1 changed file with 55 additions and 49 deletions.
104 changes: 55 additions & 49 deletions src/pages/ChatPage/ChatPage.jsx
Original file line number Diff line number Diff line change
@@ -1,21 +1,23 @@
import React, { useRef, useEffect, useState } from 'react';
import SockJS from 'sockjs-client';
import Stomp from 'stompjs';
import { Header } from "@/components/Header/Header";
import { EndButton } from "@/components/Button/Button";
import * as S from "./style";
import BOT_IMG from "@/assets/bot.png";
import CHATTING_LAYOUT from "@/assets/chatLayout.svg";
import { useRef, useEffect, useState } from "react";
import useSpeechToText from "@/hooks/useSpeechToText";
import { useNavigate, useParams } from "react-router-dom";
import SockJS from "sockjs-client";
import useSpeechToText from "@/hooks/useSpeechToText";

export const ChatPage = () => {
const customInput = useRef();
const recommendZone = useRef();
const { transcript, toggleListening } = useSpeechToText();
const [messages, setMessages] = useState([]); // 메시지 배열
const socketRef = useRef();
const [messages, setMessages] = useState([]);
const stompClient = useRef(null);
const params = useParams();
const navigate = useNavigate();
const [currentRoomId, setCurrentRoomId] = useState(null);

const handleResizeHeight = () => {
if (customInput.current && recommendZone.current) {
Expand All @@ -40,44 +42,61 @@ export const ChatPage = () => {
localStorage.setItem("nextpage", "/chatting/info/another");
navigate("/");
} else {
// SockJS 연결 설정
const sock = new SockJS(`${import.meta.env.VITE_BASE_API}/chat/sockjs`);

sock.onopen = () => {
console.log("SockJS connected");
sock.send(JSON.stringify({ type: "join", room: params.room }));
};

sock.onmessage = (event) => {
const message = JSON.parse(event.data);
setMessages((prevMessages) => [...prevMessages, message]);
};

sock.onclose = () => {
console.log("SockJS disconnected");
};
// SockJS와 Stomp 클라이언트 설정
const socket = new SockJS(`${import.meta.env.VITE_BASE_API}/chat/ws`);
stompClient.current = Stomp.over(socket);

socketRef.current = sock;
stompClient.current.connect({}, (frame) => {
console.log('Connected: ' + frame);
subscribeToRoom(params.room);
});

return () => {
sock.close();
if (stompClient.current) {
stompClient.current.disconnect();
}
};
}
}, [navigate, params.room]);

const subscribeToRoom = (roomId) => {
if (roomId === currentRoomId) {
alert('You are already subscribed to this room.');
return;
}

if (currentRoomId !== null) {
stompClient.current.unsubscribe(`/sub/chatrooms/${currentRoomId}`);
console.log(`Unsubscribed from room: ${currentRoomId}`);
}

setCurrentRoomId(roomId);

stompClient.current.subscribe(`/sub/chatrooms/${roomId}`, (message) => {
const chatMessage = JSON.parse(message.body);
setMessages((prevMessages) => [...prevMessages, `${chatMessage.username}: ${chatMessage.message}`]);
});

console.log(`Subscribed to room: ${roomId}`);
};

const handleSendMessage = () => {
const message = customInput.current.value;
if (message.trim()) {
const newMessage = { text: message, isMine: true };
setMessages((prevMessages) => [...prevMessages, newMessage]);
if (message.trim() === '' || currentRoomId === null) {
alert('Please subscribe to a chat room and enter a message.');
return;
}

if (socketRef.current.readyState === SockJS.OPEN) {
socketRef.current.send(JSON.stringify(newMessage));
}
const chatMessage = {
chatroomUUID: currentRoomId,
username: 'UserA',
message: message
};

customInput.current.value = "";
handleResizeHeight();
}
stompClient.current.send('/pub/messages', {}, JSON.stringify(chatMessage));
setMessages((prevMessages) => [...prevMessages, `UserA: ${message}`]);
customInput.current.value = "";
handleResizeHeight();
};

return (
Expand All @@ -93,22 +112,9 @@ export const ChatPage = () => {
<EndButton>끝내기</EndButton>
</Header>
<S.ChattingZone>
{messages.map((message, index) =>
message.isMine ? (
<S.SendZone key={index}>{message.text}</S.SendZone>
) : (
<S.ResBox key={index}>
<S.ResZone>{message.text}</S.ResZone>
<S.ResImage
style={{
backgroundImage: `url(${BOT_IMG})`,
backgroundSize: "cover",
backgroundPosition: "center",
}}
></S.ResImage>
</S.ResBox>
)
)}
{messages.map((msg, index) => (
<S.SendZone key={index}>{msg}</S.SendZone>
))}
</S.ChattingZone>
<S.RecommendTextContainer ref={recommendZone}>
{/* <S.RecommendText>추천1</S.RecommendText>
Expand All @@ -127,4 +133,4 @@ export const ChatPage = () => {
</S.InputContainer>
</S.ChatLayout>
);
};
};

0 comments on commit a59a9ff

Please sign in to comment.