Skip to content

Commit

Permalink
Merge pull request #14 from shimdokite/chat
Browse files Browse the repository at this point in the history
[FE] ♻️ 핵심 채팅 관련 리팩토링
  • Loading branch information
shimdokite authored Apr 12, 2024
2 parents 78a9c36 + e31b2b1 commit 40d97e7
Show file tree
Hide file tree
Showing 10 changed files with 121 additions and 137 deletions.
2 changes: 1 addition & 1 deletion client/src/components/admin/ChatModal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ interface ChatModalProps {
export default function ChatModal({ close, handleAnswered }: ChatModalProps) {
return (
<Modal>
<div className="px-2 py-2 mx-2 flex flex-col justify-center items-center border-2 rounded-lg border-brown-50 bg-brown-20">
<div className="w-[416px] max-[500px]:w-[270px] px-2 py-2 mx-2 flex flex-col justify-center items-center border-2 rounded-lg border-brown-50 bg-brown-20">
<Chat role="admin" />

<div className="flex justify-center items-center">
Expand Down
65 changes: 9 additions & 56 deletions client/src/components/inquiry/Chat.tsx
Original file line number Diff line number Diff line change
@@ -1,39 +1,31 @@
'use client';

import { useRouter } from 'next/navigation';
import { useEffect, useRef, useState } from 'react';
import { useEffect } from 'react';
import InfiniteScroll from 'react-infinite-scroller';

import { CompatClient, Stomp, StompSubscription } from '@stomp/stompjs';
import SockJS from 'sockjs-client';

import useUserStore from '@/stores/userStore';
import useChatStore from '@/stores/chatStore';

import useChatMessageQuery from '@/hooks/query/useChatMessageQuery';
import useChat from '@/hooks/useChat';

import { ChatInput, ChatBox } from '.';

import { ChatData } from '@/types/data';

import checkForToken from '@/utils/checkForToken';

interface ChatProps {
role: 'user' | 'admin';
}

export default function Chat({ role }: ChatProps) {
const client = useRef<CompatClient>();
const scrollRef = useRef<HTMLDivElement | null>(null);

const [connected, setConnected] = useState(false);
const [chat, setChat] = useState<ChatData[]>([]);

const router = useRouter();

const { roomId, message, setMessage } = useChatStore();
const { accessToken, refreshToken, userId, displayName, setClear } =
useUserStore();
const { roomId, message, isNewChatConnect, setMessage } = useChatStore();
const { userId, displayName, setClear } = useUserStore();

const { setConnected, setChat, client, scrollRef, chat, connected } =
useChat(isNewChatConnect);

const {
data: messageList,
Expand All @@ -43,10 +35,6 @@ export default function Chat({ role }: ChatProps) {

const { authVerify } = checkForToken();

const url = process.env.NEXT_PUBLIC_API_URL;

let subscription: StompSubscription | undefined;

const newMessge = {
senderId: +userId,
chatRoomId: roomId,
Expand All @@ -72,6 +60,7 @@ export default function Chat({ role }: ChatProps) {
}

client?.current?.send(`/pub/chatRoom/send`, {}, JSON.stringify(newMessge));

setMessage('');
};

Expand All @@ -81,42 +70,6 @@ export default function Chat({ role }: ChatProps) {
}
}, [messageList]);

useEffect(() => {
client.current = Stomp.over(() => new SockJS(`${url}/wss`));
client.current.debug = () => {};
client.current.connect(
{
Authorization: accessToken,
refresh: refreshToken,
},
() => {
subscription = client?.current?.subscribe(
`/sub/chatRoom/${roomId}`,
(payload) => {
const receivedMessage: ChatData = JSON.parse(payload.body);

setChat((previousChat) => [...previousChat, receivedMessage]);
},
);

setConnected(true);
},
);

return () => {
client.current?.disconnect(() => {
subscription?.unsubscribe();
setConnected(false);
});
};
}, []);

useEffect(() => {
if (!scrollRef.current) return;

scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
}, [chat]);

return (
<section className="w-full">
<div
Expand Down Expand Up @@ -145,5 +98,5 @@ export default function Chat({ role }: ChatProps) {

const CHAT_STYLE = {
user: 'w-[220px] h-[232px] mb-[7px]',
admin: 'lg:w-[392px] sm:w-[312px] h-[327px]',
admin: 'w-full h-[327px]',
};
11 changes: 6 additions & 5 deletions client/src/components/inquiry/ChatBox.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,10 @@ export default function ChatBox({ chat, user, role }: ChatBoxProps) {
useEffect(() => {
if (chat && role === 'admin') {
const getQuestionerId = (chat: ChatData[]) => {
return chat.map((data) => {
if (data.senderId !== 101) setQuestionerId(`${data.senderId}`);
});
return chat.map(
(data) =>
data.senderId !== 101 && setQuestionerId(`${data.senderId}`),
);
};

getQuestionerId(chat);
Expand Down Expand Up @@ -74,8 +75,8 @@ const CHAT_BOX_STYLE = {
},

admin: {
container: 'lg:w-[392px] md:w-auto md:w-full',
width: 'lg:w-[365px] md:w-auto md:w-full',
container: 'w-auto',
width: 'w-auto',
name: 'text-[14px]',
box: 'text-[12px]',
},
Expand Down
9 changes: 5 additions & 4 deletions client/src/components/inquiry/ChatInput.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +3,18 @@ import { KeyboardEvent } from 'react';
interface ChatInputProps {
connected: boolean;
message: string;
role: 'user' | 'admin';

setMessage: (message: string) => void;
sendMessage: () => void;
role: 'user' | 'admin';
}

export default function ChatInput({
connected,
message,
role,
setMessage,
sendMessage,
role,
}: ChatInputProps) {
const handleKeyDown = (event: KeyboardEvent<HTMLInputElement>) => {
if (event.key === 'Enter' && message !== '') {
Expand All @@ -26,7 +27,7 @@ export default function ChatInput({
<input
type="text"
value={message}
placeholder={connected ? '메세지를 입력하세요.' : '연결중입니다...'}
placeholder={connected ? '메시지를 입력하세요.' : '연결 중입니다...'}
disabled={!connected}
onChange={(event) => setMessage(event.target.value)}
onKeyDown={(event) => handleKeyDown(event)}
Expand All @@ -37,7 +38,7 @@ export default function ChatInput({
type="submit"
onClick={sendMessage}
disabled={!connected}
className={`${CHAT_INPUT_STYLE[role].submit} text-[12px] flex justify-center items-center text-brown-40 font-bold border-brown-50 rounded-xl border-2 bg-contain bg-center bg-repeat bg-[url('/assets/img/bg_wood_light.png')] shadow-outer/down`}>
className={`${CHAT_INPUT_STYLE[role].submit} flex justify-center items-center text-xs text-brown-40 font-bold border-brown-50 rounded-xl border-2 bg-contain bg-center bg-repeat bg-[url('/assets/img/bg_wood_light.png')] shadow-outer/down`}>
전송
</button>
</div>
Expand Down
76 changes: 8 additions & 68 deletions client/src/components/inquiry/NewChat.tsx
Original file line number Diff line number Diff line change
@@ -1,17 +1,13 @@
'use client';

import { useRouter } from 'next/navigation';
import { useEffect, useRef, useState } from 'react';

import { CompatClient, Stomp, StompSubscription } from '@stomp/stompjs';
import SockJS from 'sockjs-client';

import useUserStore from '@/stores/userStore';
import useChatStore from '@/stores/chatStore';

import { ChatInput, ChatBox } from '.';
import useChat from '@/hooks/useChat';

import { ChatData } from '@/types/data';
import { ChatInput, ChatBox } from '.';

import checkForToken from '@/utils/checkForToken';

Expand All @@ -20,33 +16,15 @@ interface NewChatProps {
}

export default function NewChat({ role }: NewChatProps) {
const client = useRef<CompatClient>();
const scrollRef = useRef<HTMLDivElement | null>(null);

const [connected, setConnected] = useState(false);
const [chat, setChat] = useState<ChatData[]>([]);

const router = useRouter();

const { message, setMessage, roomId } = useChatStore();
const { accessToken, refreshToken, displayName, userId, setClear } =
useUserStore();

const { authVerify } = checkForToken();

const url = process.env.NEXT_PUBLIC_API_URL;

let subscription: StompSubscription | undefined;
const { message, roomId, isNewChatConnect, setMessage } = useChatStore();
const { displayName, userId, setClear } = useUserStore();

const entryMessage = () => {
const adminId = 101;
const { setConnected, client, scrollRef, chat, connected } =
useChat(isNewChatConnect);

client?.current?.send(
`/pub/chatRoom/enter`,
{},
JSON.stringify({ senderId: +userId, chatRoomId: +roomId, adminId }),
);
};
const { authVerify } = checkForToken();

const newMessge = {
senderId: +userId,
Expand All @@ -73,48 +51,10 @@ export default function NewChat({ role }: NewChatProps) {
}

client?.current?.send(`/pub/chatRoom/send`, {}, JSON.stringify(newMessge));

setMessage('');
};

useEffect(() => {
if (roomId) {
client.current = Stomp.over(() => new SockJS(`${url}/wss`));
client.current.debug = () => {};
client.current.connect(
{
Authorization: accessToken,
refresh: refreshToken,
},
() => {
subscription = client?.current?.subscribe(
`/sub/chatRoom/${roomId}`,
(payload) => {
const receivedMessage: ChatData = JSON.parse(payload.body);

setChat((previousChat) => [...previousChat, receivedMessage]);
},
);

entryMessage();
setConnected(true);
},
);
}

return () => {
client.current?.disconnect(() => {
subscription?.unsubscribe();
setConnected(false);
});
};
}, [roomId]);

useEffect(() => {
if (!scrollRef.current) return;

scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
}, [chat]);

return (
<section className="w-full">
<div
Expand Down
3 changes: 2 additions & 1 deletion client/src/hooks/mutation/useCreateChatRoomMutation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import useChatStore from '@/stores/chatStore';

const useCreateChatRoomMutation = (qnaTitle: string) => {
const { userId } = useUserStore();
const { setRoomId } = useChatStore();
const { setRoomId, setIsNewChatConnect } = useChatStore();

const { mutate } = useMutation({
mutationFn: () => postCreateChatRoom(+userId, qnaTitle),
Expand All @@ -16,6 +16,7 @@ const useCreateChatRoomMutation = (qnaTitle: string) => {
const roomId = `${data.data.chatRoomId}`;

setRoomId(roomId);
setIsNewChatConnect(true);
},
});

Expand Down
1 change: 0 additions & 1 deletion client/src/hooks/mutation/useSigninMutation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,6 @@ const useSigninMutation = () => {
profileImageUrl,
});

//TODO: userId가 cookie에 잘 들어오는지 확인하기.
setCookiesByUserId(userId);

getSigninForm(false);
Expand Down
Loading

0 comments on commit 40d97e7

Please sign in to comment.