-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.tsx
205 lines (175 loc) · 6.34 KB
/
index.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
import React, { useEffect, useState, useRef } from 'react';
import { useAppDispatch, useAppSelector } from 'hooks/useRedux';
import FullModal from '../common/FullModal';
import AdminProfile from './AdminProfile';
import ChatInput from './ChatInput';
import ChatMessage from './ChatMessage';
import Loading from '../common/Loading';
import useOnlineStatus from 'hooks/useOnlineStatus';
import {
addChat,
setChatRoomDetailChatList,
setOnlineEmailList,
} from 'reducers/chat';
import { IChatMessage, emailList } from 'types/chat';
import {
getCustomDateString,
getPrevDateString,
stringToTime,
} from 'utils/convertDate';
import styles from './chatModal.module.scss';
import { io } from 'socket.io-client';
function ChatModal() {
const [modalTitle, setModalTitle] = useState<string>('');
const [isLoading, setIsLoading] = useState(true);
const dispatch = useAppDispatch();
const { chatList } = useAppSelector(state => state.chat.chatRoomDetail);
const chatRoomDetail = useAppSelector(state => state.chat.chatRoomDetail);
const socket = io(`${process.env.REACT_APP_SOCKET_ENDPOINT}`, {
reconnection: false,
path: '/socket.io/',
transports: ['websocket'],
});
/****************** 소켓 위해 지정한 관리자 이메일 *****************/
const adminEmail = 'elliseusobanggwan@gmail.com';
const userEmail = useAppSelector(state => state.user.email);
const isOnline = useOnlineStatus(userEmail);
/***********************************************************************/
/****************************** 자동 스트롤 *******************************/
const scrollContainerRef = useRef<HTMLDivElement>(null);
useEffect(() => {
scrollContainerRef.current?.scrollIntoView({ behavior: 'smooth' });
}, [chatList, enterChatRoom]);
/***********************************************************************/
/********* 채팅방 첫 입성시 어드민 상태, 날짜, 소켓 연결, 해당방의 채팅 리스트 *********/
useEffect(() => {
if (userEmail === adminEmail)
setModalTitle(`[${chatRoomDetail.generation}] ${chatRoomDetail.name}`);
else setModalTitle('1:1 문의 채팅방');
enterChatRoom();
return () => {
socket.off('enterChatRoom');
socket.off('AllMessages');
};
}, [chatRoomDetail.email, userEmail, adminEmail, dispatch]);
/***********************************************************************/
useEffect(() => {
onMessage();
getOnline();
return () => {
socket.off('message');
socket.off('latestMessage');
socket.off('onlineStatus');
};
}, [addChat, setOnlineEmailList]);
/************************** 채팅 보내기 관련 함수 *****************************/
const inputRef = useRef<HTMLTextAreaElement>(null);
function handleSend(value: string) {
if (value.trim().length === 0) {
return;
}
sendMessage(value);
sendOnline();
}
/***************************************************************************/
/***************************** 소켓 관련 함수 코드임 ***************************/
function enterChatRoom() {
if (userEmail === adminEmail) {
socket.emit('enterChatRoom', chatRoomDetail.email);
} else {
socket.emit('enterChatRoom', userEmail);
}
socket.on('AllMessages', data => {
dispatch(setChatRoomDetailChatList(data));
setIsLoading(false);
if (!data) {
setIsLoading(false);
socket.emit('createChatRoom', userEmail);
}
});
}
function sendMessage(message: string) {
if (userEmail === adminEmail) {
socket.emit('message', chatRoomDetail.email, adminEmail, message);
} else {
socket.emit('message', userEmail, userEmail, message);
}
}
function onMessage() {
socket.on('latestMessage', (data: IChatMessage[]) => {
console.log('latestMessage: ', data);
const newChatMessage = {
sender_email: data[0].sender_email,
name: data[0].name,
generation: data[0].generation,
message: data[0].message,
sentAt: data[0].sentAt,
};
dispatch(addChat({ chatMessage: newChatMessage }));
});
}
function sendOnline() {
if (userEmail === adminEmail) {
socket.emit('isOnlineStatus', chatRoomDetail.email, adminEmail);
} else {
socket.emit('isOnlineStatus', userEmail, adminEmail);
}
}
function getOnline() {
socket.on('onlineStatus', (data: emailList[]) => {
dispatch(setOnlineEmailList(data));
});
}
/***********************************************************************/
return (
<FullModal title={modalTitle} modalType='chat'>
<div className={styles.chatModalContainer}>
<div className={styles.scrollContainer}>
{userEmail !== adminEmail && <AdminProfile isOnline={isOnline} />}
<div className={styles.chatListContainer}>
{isLoading ? (
<div className={styles.loadingContainer}>
<Loading />
</div>
) : (
<>
{chatList ? (
chatList.map((msg, i) => {
const currentDate = getPrevDateString(msg.sentAt);
const formattedDate =
i === 0 ||
currentDate !== getPrevDateString(chatList[i - 1]?.sentAt)
? getCustomDateString(msg.sentAt)
: '';
return (
<div key={i}>
{formattedDate && (
<div className={styles.nowDate}>{formattedDate}</div>
)}
<ChatMessage
key={i}
sender_email={msg.sender_email}
name={msg.name}
generation={msg.generation}
message={msg.message}
sentAt={stringToTime(msg.sentAt)}
/>
</div>
);
})
) : (
<div></div>
)}
</>
)}
<div ref={scrollContainerRef} />
</div>
</div>
<div className={styles.chatInputContainer}>
<ChatInput inputRef={inputRef} handleClick={handleSend} />
</div>
</div>
</FullModal>
);
}
export default ChatModal;