-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathchat-view.component.tsx
More file actions
490 lines (431 loc) · 17 KB
/
Copy pathchat-view.component.tsx
File metadata and controls
490 lines (431 loc) · 17 KB
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
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
import { FC, useEffect, useMemo, useRef, useState } from 'react';
import { Alert, Button, Empty, Spin } from 'antd';
import { useTranslation } from 'react-i18next';
import Message from './message/message.component';
import LeftGroupAlert from 'components/alerts/left-group-alert.component';
import {
CHAT_HISTORY_COUNT_STEP,
FULL_CHAT_HISTORY_COUNT,
MAX_CHAT_HISTORY_COUNT,
MINI_CHAT_HISTORY_COUNT,
} from 'configs';
import { useActions, useAppSelector } from 'hooks';
import { useIsMaxInstance } from 'hooks/use-is-max-instance';
import { useIsWabaInstance } from 'hooks/use-is-waba-instance';
import { useGetChatHistoryQuery, useGetTemplatesQuery } from 'services/green-api/endpoints';
import { selectActiveChat, selectMiniVersion } from 'store/slices/chat.slice';
import { selectInstance } from 'store/slices/instances.slice';
import {
ActiveChat,
LanguageLiteral,
ParsedWabaTemplateInterface,
TemplateButtonTypesEnum,
} from 'types';
import {
formatMessages,
getErrorMessage,
getJSONMessage,
getPhoneNumberFromChatId,
getTextMessage,
isMessagesDate,
isOutgoingTemplateMessage,
} from 'utils';
const ChatView: FC = () => {
const instanceCredentials = useAppSelector(selectInstance);
const activeChat = useAppSelector(selectActiveChat) as ActiveChat;
const isMiniVersion = useAppSelector(selectMiniVersion);
const [count, setCount] = useState(FULL_CHAT_HISTORY_COUNT);
const { setMessageCount } = useActions();
const isMax = useIsMaxInstance();
const isWaba = useIsWabaInstance();
let previousMessageAreOutgoing = false;
let previousSenderName = '';
const {
t,
i18n: { resolvedLanguage },
} = useTranslation();
const chatViewRef = useRef<HTMLDivElement | null>(null);
const scrollPositionRef = useRef<{ top: number; height: number } | null>(null);
const { data: templates, isLoading: templatesLoading } = useGetTemplatesQuery(
instanceCredentials,
{
skip: !isWaba,
}
);
const {
data: messages,
isLoading,
isFetching,
error,
} = useGetChatHistoryQuery(
{
...instanceCredentials,
chatId: activeChat.chatId,
count: isMiniVersion ? MINI_CHAT_HISTORY_COUNT : count,
},
{
skipPollingIfUnfocused: true,
pollingInterval: 15000,
}
);
useEffect(() => {
setMessageCount(FULL_CHAT_HISTORY_COUNT);
}, [activeChat]);
const handleLoadMore = () => {
if (count >= MAX_CHAT_HISTORY_COUNT) return;
const element = chatViewRef.current;
if (!element) return;
scrollPositionRef.current = {
top: element.scrollTop,
height: element.scrollHeight,
};
setCount((prev) => {
const next = Math.min(prev + CHAT_HISTORY_COUNT_STEP, MAX_CHAT_HISTORY_COUNT);
setMessageCount(next);
return next;
});
};
useEffect(() => {
const element = chatViewRef.current;
if (!element || !scrollPositionRef.current) return;
const heightDiff = element.scrollHeight - scrollPositionRef.current.height;
element.scrollTop = scrollPositionRef.current.top + heightDiff;
scrollPositionRef.current = null;
}, [messages]);
useEffect(() => {
const element = chatViewRef.current;
if (element && count === FULL_CHAT_HISTORY_COUNT && !scrollPositionRef.current) {
setTimeout(() => {
element.scrollTo({ top: element.scrollHeight, behavior: 'smooth' });
}, 10);
}
}, [count, templates]);
const loaderVisible = !isMiniVersion && isFetching;
const getReactionTargetId = (msg: Record<string, unknown>): string | undefined => {
const quoted = msg.quotedMessage as { stanzaId?: string } | undefined;
const templateReply = msg.templateButtonReplyMessage as { stanzaId?: string } | undefined;
const ext = msg.extendedTextMessage as
| { contextInfo?: { stanzaId?: string; quotedMessage?: { stanzaId?: string } } }
| undefined;
return (
quoted?.stanzaId ||
templateReply?.stanzaId ||
ext?.contextInfo?.stanzaId ||
ext?.contextInfo?.quotedMessage?.stanzaId
);
};
const getReactionEmoji = (msg: Record<string, unknown>): string | undefined => {
const extData = msg.extendedTextMessageData as { text?: string } | undefined;
const ext = msg.extendedTextMessage as { text?: string } | undefined;
const text = msg.textMessage;
if (typeof extData?.text === 'string' && extData.text.trim()) return extData.text.trim();
if (typeof ext?.text === 'string' && ext.text.trim()) return ext.text.trim();
if (typeof text === 'string' && text.trim()) return text.trim();
return undefined;
};
const getReactionKeysForMessage = (msg: Record<string, unknown>): string[] => {
const keys = new Set<string>();
const addKey = (value: unknown) => {
if (typeof value === 'string') {
const normalized = value.trim();
if (normalized) keys.add(normalized);
}
};
const idMessage = msg.idMessage;
addKey(idMessage);
const ext = msg.extendedTextMessage as { stanzaId?: string } | undefined;
addKey(ext?.stanzaId);
const quoted = msg.quotedMessage as { stanzaId?: string } | undefined;
addKey(quoted?.stanzaId);
const templateReply = msg.templateButtonReplyMessage as { stanzaId?: string } | undefined;
addKey(templateReply?.stanzaId);
return Array.from(keys);
};
const formattedMessages = useMemo(() => {
if (!messages) return [];
const allFormatted = formatMessages(messages, resolvedLanguage as LanguageLiteral);
const reactionMap = new Map<string, Map<string, string>>();
const pollUpdateMap = new Map<
string,
Map<string, { timestamp: number; selectedOptions: string[] }>
>();
for (const msg of allFormatted) {
if ('typeMessage' in msg && msg.typeMessage === 'reactionMessage') {
const targetId = getReactionTargetId(msg as unknown as Record<string, unknown>);
const reaction = getReactionEmoji(msg as unknown as Record<string, unknown>);
const senderId =
typeof msg.senderId === 'string' && msg.senderId.trim()
? msg.senderId.trim()
: msg.type === 'outgoing'
? 'outgoing:self'
: undefined;
const normalizedTarget = targetId?.trim();
if (normalizedTarget && reaction && senderId) {
const existingReactions = reactionMap.get(normalizedTarget) ?? new Map<string, string>();
existingReactions.set(senderId, reaction);
reactionMap.set(normalizedTarget, existingReactions);
}
continue;
}
if ('typeMessage' in msg && msg.typeMessage === 'pollUpdateMessage') {
const stanzaId = msg.pollMessageData?.stanzaId;
if (!stanzaId) continue;
const senderId =
typeof msg.senderId === 'string' && msg.senderId.trim()
? msg.senderId.trim()
: msg.type === 'outgoing'
? 'outgoing:self'
: undefined;
if (!senderId) continue;
const senderPhone = getPhoneNumberFromChatId(senderId);
const selectedOptions =
msg.pollMessageData?.votes
?.filter((vote) =>
vote.optionVoters.some((voter) => getPhoneNumberFromChatId(voter) === senderPhone)
)
.map((vote) => vote.optionName) ?? [];
const updatesBySender = pollUpdateMap.get(stanzaId) ?? new Map();
const existing = updatesBySender.get(senderPhone);
if (!existing || msg.timestamp >= existing.timestamp) {
updatesBySender.set(senderPhone, { timestamp: msg.timestamp, selectedOptions });
pollUpdateMap.set(stanzaId, updatesBySender);
}
}
}
const processedMessages = allFormatted
.filter((msg) => {
return (
!('typeMessage' in msg) ||
(msg.typeMessage !== 'pollUpdateMessage' && msg.typeMessage !== 'reactionMessage')
);
})
.map((msg) => {
if ('typeMessage' in msg && msg.typeMessage === 'pollMessage') {
const updatesBySender = pollUpdateMap.get(msg.idMessage);
if (updatesBySender) {
const votesByOption = new Map<string, Set<string>>();
for (const option of msg.pollMessageData?.options ?? []) {
votesByOption.set(option.optionName, new Set());
}
for (const [senderPhone, update] of updatesBySender.entries()) {
for (const selectedOption of update.selectedOptions) {
const optionVoters = votesByOption.get(selectedOption) ?? new Set<string>();
optionVoters.add(senderPhone);
votesByOption.set(selectedOption, optionVoters);
}
}
return {
...msg,
pollMessageData: {
name: msg.pollMessageData?.name ?? '',
options: msg.pollMessageData?.options ?? [],
multipleAnswers: msg.pollMessageData?.multipleAnswers ?? false,
votes: Array.from(votesByOption.entries()).map(([optionName, optionVoters]) => ({
optionName,
optionVoters: Array.from(optionVoters),
})),
},
};
}
}
return {
...msg,
reactions:
'idMessage' in msg
? (() => {
const aggregated = new Map<string, number>();
for (const key of getReactionKeysForMessage(
msg as unknown as Record<string, unknown>
)) {
const keyReactions = reactionMap.get(key);
if (!keyReactions) continue;
for (const emoji of keyReactions.values()) {
aggregated.set(emoji, (aggregated.get(emoji) ?? 0) + 1);
}
}
return Array.from(aggregated.entries()).map(([emoji, count]) => ({
emoji,
count,
}));
})()
: undefined,
};
});
return processedMessages;
}, [messages, resolvedLanguage]);
if (isLoading || templatesLoading) {
return (
<div className={`chat-view flex-center ${isMiniVersion ? '' : 'full'}`}>
<Spin size="large" />
</div>
);
}
if (error) {
if ('status' in error && error.status === 429) {
return (
<div className={`chat-view flex-center ${isMiniVersion ? '' : 'full'}`}>
<Spin size="large" />
</div>
);
}
return (
<div className={`chat-view flex-center ${isMiniVersion ? '' : 'full'}`}>
<Empty description={getErrorMessage(error, t)} />
</div>
);
}
return (
<div className={`chat-view ${isMiniVersion ? '' : 'full'}`} ref={chatViewRef}>
{count < MAX_CHAT_HISTORY_COUNT ? (
<div style={{ textAlign: 'center', padding: '12px 0' }}>
<Button onClick={handleLoadMore}>{t('LOAD_MORE_MESSAGES')}</Button>
</div>
) : (
<Alert
style={{ textAlign: 'center' }}
message={t('CHAT_MESSAGE_LIMIT_REACHED_TITLE')}
type="warning"
/>
)}
<Spin size="large" style={{ visibility: loaderVisible ? 'initial' : 'hidden' }} />
{formattedMessages.map((message, idx) => {
if (isMessagesDate(message)) {
return (
<div
className="message date p-10"
key={message.date}
style={{ alignSelf: 'center' }}
data-message-id={`date-${message.date}`}
>
{message.date.toUpperCase()}
</div>
);
}
const typeMessage = message.typeMessage;
const showSenderName =
(previousSenderName !== message.senderName &&
previousSenderName !== message.senderId &&
message.type !== 'outgoing') ||
(message.type === 'outgoing' && !previousMessageAreOutgoing);
previousMessageAreOutgoing = message.type === 'outgoing';
previousSenderName = message.senderName || message.senderId || '';
let templateMessage: ParsedWabaTemplateInterface | undefined;
let interactiveButtonsMessage: ParsedWabaTemplateInterface | undefined;
if (message.templateMessage && !isMiniVersion) {
if (isOutgoingTemplateMessage(message.templateMessage, message.type)) {
const id = message.templateMessage.templateId;
const templateData = templates?.templates.find(
(template) => template.templateId === id
);
if (templateData && templateData.containerMeta) {
templateMessage = JSON.parse(
templateData.containerMeta
) as ParsedWabaTemplateInterface;
templateMessage.params = message.templateMessage.params;
}
} else {
if (message.templateMessage.contentText) {
templateMessage = {
header: message.templateMessage.titleText,
data: message.templateMessage.contentText,
footer: message.templateMessage.footerText,
mediaUrl: message.templateMessage.mediaUrl,
buttons: message.templateMessage.buttons?.map((button) => {
if (button.callButton) {
return {
text: button.callButton.displayText,
value: button.callButton.displayText,
type: TemplateButtonTypesEnum.PhoneNumber,
};
} else if (button.urlButton) {
return {
text: button.urlButton.displayText,
value: button.urlButton.displayText,
type: TemplateButtonTypesEnum.Url,
};
} else if (button.quickReplyButton) {
return {
text: button.quickReplyButton.displayText,
value: button.quickReplyButton.displayText,
type: TemplateButtonTypesEnum.Url,
};
}
return { text: '', value: '', type: TemplateButtonTypesEnum.Url };
}),
};
}
}
}
if (message.interactiveButtons && !isMiniVersion) {
interactiveButtonsMessage = {
header: message.interactiveButtons.titleText,
data: message.interactiveButtons.contentText,
footer: message.interactiveButtons.footerText,
buttons: message.interactiveButtons.buttons?.map((button) => {
if (button.type === 'call') {
return {
text: button.buttonText,
value: button.phoneNumber ?? '',
type: TemplateButtonTypesEnum.PhoneNumber,
};
} else if (button.type === 'url') {
return {
text: button.buttonText,
value: button.url ?? '',
type: TemplateButtonTypesEnum.Url,
};
} else if (button.type === 'reply') {
return {
text: button.buttonText,
value: button.buttonId ?? '',
type: TemplateButtonTypesEnum.QuickReply,
};
} else if (button.type === 'copy') {
return {
text: button.buttonText,
value: button.copyCode ?? '',
type: TemplateButtonTypesEnum.CopyCode,
};
}
return { text: '', value: '', type: TemplateButtonTypesEnum.Url };
}),
};
}
return (
<Message
key={message.idMessage}
messageDataForRender={{
idMessage: message.idMessage,
showSenderName,
type: message.type,
typeMessage,
textMessage: getTextMessage(message),
senderName: message.type === 'outgoing' ? t('YOU_SENDER_NAME') : message.senderName!,
senderType: message.senderType,
phone: message.senderId && getPhoneNumberFromChatId(message.senderId),
isLastMessage: idx === formattedMessages.length - 1,
timestamp: message.timestamp,
jsonMessage: getJSONMessage(message),
downloadUrl: message.downloadUrl,
statusMessage: message.statusMessage,
quotedMessage: message.quotedMessage,
templateMessage: templateMessage,
extendedTextMessage: message.extendedTextMessage,
interactiveButtonsMessage: interactiveButtonsMessage,
caption: message.caption,
fileName: message.fileName,
isDeleted: message.isDeleted,
isEdited: message.isEdited,
pollMessageData: message.pollMessageData,
reactions: 'reactions' in message ? message.reactions : undefined,
}}
/>
);
})}
{activeChat.contactInfo === (isMax ? 'groupId not found' : 'Error:forbiden') && (
<LeftGroupAlert />
)}
</div>
);
};
export default ChatView;