-
Notifications
You must be signed in to change notification settings - Fork 0
/
ChatListWithVirtualScroll.jsx
273 lines (244 loc) · 9.11 KB
/
ChatListWithVirtualScroll.jsx
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
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
import ChatHeaderComponent from '../Header/ChatHeaderComponent.jsx';
import EmojiIcon from '../../../icons/Emoji.icon.jsx';
import AddFileIcon from '../../../icons/AddFile.icon.jsx';
import VectorUpIcon from '../../../icons/Vector_up.icon.jsx';
import Requests from '../../../services/requests.js';
import MessageField from '../MessageFieldComponent/MessageFieldComponent.jsx'
import { loadInitialMessages, loadMoreNextMessages, loadMorePreviousMessages, setTopHasMore, setBottomHasMore } from '../../../../Redux/actions/messageActions.js';
import css from './ChatListComponent.module.css';
import io from 'socket.io-client';
import { useState, useRef, useEffect} from 'react';
import { useRouter } from 'next/router';
import { getCookie } from 'cookies-next';
import { useSelector, useDispatch } from 'react-redux';
import { FixedSizeList } from 'react-window';
import AutoSizer from 'react-virtualized-auto-sizer';
const ChatListComponent = () => {
const router = useRouter();
const dispatch = useDispatch();
const messages = useSelector((state) => state.messages);
const TopHasMore = useSelector((state) => state.topHasMore);
const BottomHasMore = useSelector((state) => state.bottomHasMore);
const cookie = getCookie("access_token");
const userId = getCookie('inchatId')
const [idSocket, setIdSocket] = useState(null)
const [messagesForRender, setMessagesForRender] = useState([]);
const socketRef = useRef();
const containerRef = useRef(null);
const listRef = useRef(null);
const [discriber, setDiscriber] = useState();
const [prevHeight, setPrevHeight] = useState()
const { id } = router?.query;
const container = containerRef?.current;
const getDataChats = async () => {
if (id) {
const res = await Requests.authenticate('/chats/get_data_for_chat', { cookie, id });
setDiscriber(res?.data)
}
}
// Обработчик отправки сообщения
const handleSendMessage = () => {
dispatch(setBottomHasMore(true));
// Отправка сообщения
let msg = document?.getElementById("message");
if (msg?.value) {
socketRef?.current.emit('send message', { chat_id: id, content: msg?.value, sender: cookie, })
msg.value = '';
};
// Прокрутка вниз после отправки сообщения
};
const getLoadInitialMessages = () => {
//начальные сообщения с сервера
socketRef?.current?.emit('load_messages_for_pages', { id }, 20, userId, idSocket);
};
const getLoadMoreNextMessages = () => {
if (BottomHasMore) {
const lastMessage = messages[messages?.length - 1];
const lastId = lastMessage?.id
const count = 20;
// Загружаем следующие сообщения с сервера
socketRef?.current?.emit('loadMoreNextMessages', { id }, lastId, count, idSocket)
}
};
const getLoadMorePreviousMessages = () => {
if (TopHasMore) {
const firstMessage = messages[0]?.id;
const count = 20;
// Загружаем предыдущие сообщения с сервера
socketRef?.current.emit('loadMorePreviousMessages', { id }, firstMessage, count, idSocket)
}
};
const handleScroll = () => {
const container = containerRef?.current;
// Дополнительная логика обработки прокрутки, если необходимо
if (container?.scrollTop == 0) {
// Доскроллили до самого верха
getLoadMorePreviousMessages();
} else if (container?.scrollTop + container?.clientHeight >= container?.scrollHeight) {
// Доскроллили до самого низа
getLoadMoreNextMessages();
}
};
useEffect(() => {
getLoadInitialMessages();
}, [idSocket]);
useEffect(() => {
socketRef.current = io.connect("ws://localhost:8081");
socketRef.current.on('connect', function () {
setIdSocket(() => socketRef.current.id)
});
getDataChats()
socketRef.current.emit('online', +userId);
socketRef?.current?.on('add messages', (msg) => {
dispatch(loadInitialMessages(msg.msg))
dispatch(setTopHasMore(msg.TopHasMore))
dispatch(setBottomHasMore(msg.BottomHasMore))
})
//обработчик прокрутки
socketRef.current.on('loadMoreNextMessages', (newMessages, bottomHasMore) => {
dispatch(loadMoreNextMessages(newMessages))
dispatch(setBottomHasMore(bottomHasMore))
});
socketRef.current.on('loadMorePreviousMessages', (newMessages, TopHasMore) => {
if (newMessages) {
dispatch(loadMorePreviousMessages(newMessages));
dispatch(setTopHasMore(TopHasMore));
setPagination([...pagination, 1])
} else {
dispatch(setTopHasMore(TopHasMore));
};
});
const container = containerRef?.current;
container.addEventListener('scroll', handleScroll);
//unmounting =>
return () => {
socketRef?.current.emit('offline', +userId)
container?.removeEventListener('scroll', handleScroll);
socketRef?.current.disconnect();
dispatch(setBottomHasMore(true));
dispatch(setTopHasMore(true));
dispatch(loadInitialMessages([]))
};
}, [id, router?.isReady]);
useEffect(() => {
socketRef?.current.on('newMessage', (msg) => {
dispatch(loadMoreNextMessages([msg?.msg]));
setSendMess([...sendMess, 1])
});
checkMessages()
}, [messages]);
useEffect(() => {
if (container?.scrollHeight) {
setPrevHeight(container?.scrollHeight)
}
}, [container?.scrollHeight]);
const [pagination, setPagination] = useState([])
const [sendMess, setSendMess] = useState([])
useEffect(() => {
const container = containerRef?.current;
container.scrollTop = container?.scrollHeight - prevHeight
}, [pagination]);
useEffect(() => {
if (listRef.current) {
listRef.current.scrollIntoView({ behavior: 'smooth', block: 'end' });
}
}, [sendMess]);
const checkMessages = () => {
for (let i = messages.length - 1; i >= 0; i--) {
const currentId = messages[i]?.id;
for (let j = i - 1; j >= 0; j--) {
if (messages[j]?.id === currentId) {
messages.splice(j, 1);
}
}
}
return setMessagesForRender(messages)
}
const handleKeyPress = (e) => {
e.key === 'Enter' ? handleSendMessage() : null
}
const MessageRenderer = ({ data, index, style }) => {
const msg = data[index];
const currentDate = new Date(msg.date);
const options = { day: 'numeric', month: 'long' };
const formattedDate = new Intl.DateTimeFormat('ru-RU', options).format(currentDate);
const prevMessage = data[index - 1];
const prevDate = prevMessage && new Date(prevMessage.date);
return (
<div style={{ ...style, minHeight: 40 }} >
{currentDate.getMonth() !== prevDate?.getMonth() && (
<div className={css.date}>
<div className={css.line} />
<div className={css.value}>{formattedDate}</div>
<div className={css.line} />
</div>
)}
<MessageField
message={msg}
key={msg.id}
CN={msg.sender === +userId ? css.left : css.right}
/>
</div>
);
};
return (
<div className={css.container}>
<div className={css.header}>
<ChatHeaderComponent avatar={discriber?.avatar || null} fullName={discriber?.fullName} state={discriber?.online} phone={discriber?.phone} />
</div>
<div
className={css.list}
onScroll={handleScroll}
ref={containerRef}
>
<AutoSizer className={css.scrollList}>
{({ height, width }) => (
<FixedSizeList
height={height}
width={width}
itemCount={messagesForRender.length}
itemSize={40} // Минимальная высота каждого элемента сообщения (40px)
itemData={messagesForRender}
>
{MessageRenderer}
</FixedSizeList>
)}
</AutoSizer>
</div>
<div className={css.sendField}>
<div className={css.inputWrapper}>
<EmojiIcon
width={20}
height={20}
color='#817CFF'
/>
<input
className={css.input}
id='message'
type='text'
placeholder='Введите сообщение'
onKeyDown={handleKeyPress}
/>
<AddFileIcon
width={20}
height={20}
color='#817CFF'
/>
</div>
<button
className={css.btn}
onClick={handleSendMessage}
>
<div className={css.send}>
<VectorUpIcon
width={33}
height={30}
color='#817CFF'
/>
</div>
</button>
</div>
</div>
);
};
export default ChatListComponent;