-
Notifications
You must be signed in to change notification settings - Fork 78
Expand file tree
/
Copy pathMessageThread.tsx
More file actions
1148 lines (1075 loc) · 41 KB
/
MessageThread.tsx
File metadata and controls
1148 lines (1075 loc) · 41 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
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { Icon, IStyle, mergeStyles, PrimaryButton } from '@fluentui/react';
import { Chat } from '@fluentui-contrib/react-chat';
import { mergeClasses } from '@fluentui/react-components';
import {
DownIconStyle,
newMessageButtonContainerStyle,
messageThreadContainerStyle,
messageThreadWrapperContainerStyle,
useChatStyles,
buttonWithIconStyles,
newMessageButtonStyle
} from './styles/MessageThread.styles';
import { delay } from './utils/delay';
import {
BaseCustomStyles,
ChatMessage,
CustomMessage,
SystemMessage,
OnRenderAvatarCallback,
Message,
ReadReceiptsBySenderId,
ComponentSlotStyle
} from '../types';
/* @conditional-compile-remove(data-loss-prevention) */
import { BlockedMessage } from '../types';
import { MessageStatusIndicator, MessageStatusIndicatorProps } from './MessageStatusIndicator';
import { memoizeFnAll, MessageStatus } from '@internal/acs-ui-common';
import { useLocale } from '../localization/LocalizationProvider';
import { isNarrowWidth, _useContainerWidth } from './utils/responsive';
import getParticipantsWhoHaveReadMessage from './utils/getParticipantsWhoHaveReadMessage';
/* @conditional-compile-remove(file-sharing) */
import { FileDownloadHandler } from './FileDownloadCards';
/* @conditional-compile-remove(file-sharing) */ /* @conditional-compile-remove(teams-inline-images-and-file-sharing) */
import { AttachmentMetadata } from './FileDownloadCards';
/* @conditional-compile-remove(teams-inline-images-and-file-sharing) */
import { AttachmentDownloadResult } from './FileDownloadCards';
import { useTheme } from '../theming';
import { FluentV9ThemeProvider } from './../theming/FluentV9ThemeProvider';
import LiveAnnouncer from './Announcer/LiveAnnouncer';
/* @conditional-compile-remove(mention) */
import { MentionOptions } from './MentionPopover';
/* @conditional-compile-remove(file-sharing) */ /* @conditional-compile-remove(teams-inline-images-and-file-sharing) */
import { initializeFileTypeIcons } from '@fluentui/react-file-type-icons';
import { createStyleFromV8Style } from './styles/v8StyleShim';
import {
ChatMessageComponentWrapper,
ChatMessageComponentWrapperProps
} from './ChatMessage/ChatMessageComponentWrapper';
import { Announcer } from './Announcer';
const isMessageSame = (first: ChatMessage, second: ChatMessage): boolean => {
return (
first.messageId === second.messageId &&
first.content === second.content &&
first.contentType === second.contentType &&
JSON.stringify(first.createdOn) === JSON.stringify(second.createdOn) &&
first.senderId === second.senderId &&
first.senderDisplayName === second.senderDisplayName &&
JSON.stringify(first.editedOn) === JSON.stringify(second.editedOn)
);
};
/**
* Get the latest message from the message array.
*
* @param messages
*/
const getLatestChatMessage = (messages: Message[]): ChatMessage | undefined => {
for (let i = messages.length - 1; i >= 0; i--) {
const message = messages[i];
if (message.messageType === 'chat' && !!message.createdOn) {
return message;
}
}
return undefined;
};
/**
* Compare latestMessageFromPreviousMessages & latestMessageFromNewMessages to see if the new message is not from
* current user.
*/
const isThereNewMessageNotFromCurrentUser = (
userId: string,
latestMessageFromPreviousMessages?: ChatMessage,
latestMessageFromNewMessages?: ChatMessage
): boolean => {
if (latestMessageFromNewMessages === undefined) {
return false;
}
if (latestMessageFromPreviousMessages === undefined) {
return latestMessageFromNewMessages.senderId !== userId;
}
return (
!isMessageSame(latestMessageFromNewMessages, latestMessageFromPreviousMessages) &&
latestMessageFromNewMessages.senderId !== userId
);
};
/**
* Returns true if the current user sent the latest message and false otherwise. It will ignore messages that have no
* sender, messages that have failed to send, and messages from the current user that is marked as SEEN. This is meant
* as an indirect way to detect if user is at bottom of the chat when the component updates with new messages. If we
* updated this component due to current user sending a message we want to then call scrollToBottom.
*/
const didUserSendTheLatestMessage = (
userId: string,
latestMessageFromPreviousMessages?: ChatMessage,
latestMessageFromNewMessages?: ChatMessage
): boolean => {
if (latestMessageFromNewMessages === undefined) {
return false;
}
if (latestMessageFromPreviousMessages === undefined) {
return latestMessageFromNewMessages.senderId === userId;
}
return (
!isMessageSame(latestMessageFromNewMessages, latestMessageFromPreviousMessages) &&
latestMessageFromNewMessages.senderId === userId
);
};
/**
* Fluent styles for {@link MessageThread}.
*
* @public
*/
export interface MessageThreadStyles extends BaseCustomStyles {
/** Styles for load previous messages container. */
loadPreviousMessagesButtonContainer?: IStyle;
/** Styles for new message container. */
newMessageButtonContainer?: IStyle;
/** Styles for chat container. */
chatContainer?: ComponentSlotStyle;
/** styles for my chat items. */
myChatItemMessageContainer?: ComponentSlotStyle;
/** styles for chat items. */
chatItemMessageContainer?: ComponentSlotStyle;
/** Styles for my chat message container. */
myChatMessageContainer?: ComponentSlotStyle;
/** Styles for my chat message container in case of failure. */
failedMyChatMessageContainer?: ComponentSlotStyle;
/** Styles for chat message container. */
chatMessageContainer?: ComponentSlotStyle;
/** Styles for system message container. */
systemMessageContainer?: ComponentSlotStyle;
/** Styles for blocked message container. */
/* @conditional-compile-remove(data-loss-prevention) */
blockedMessageContainer?: ComponentSlotStyle;
/** Styles for message status indicator container. */
messageStatusContainer?: (mine: boolean) => IStyle;
}
/**
* Strings of {@link MessageThread} that can be overridden.
*
* @public
*/
export interface MessageThreadStrings {
/** String for Sunday */
sunday: string;
/** String for Monday */
monday: string;
/** String for Tuesday */
tuesday: string;
/** String for Wednesday */
wednesday: string;
/** String for Thursday */
thursday: string;
/** String for Friday */
friday: string;
/** String for Saturday */
saturday: string;
/** String for Yesterday */
yesterday: string;
/** String for participants joined */
participantJoined: string;
/** String for participants left */
participantLeft: string;
/** Tag shown on a message that has been edited */
editedTag: string;
/** String for editing message in floating menu */
editMessage: string;
/** String for removing message in floating menu */
removeMessage: string;
/** String for resending failed message in floating menu */
resendMessage?: string;
/** String for indicating failed to send messages */
failToSendTag?: string;
/** String for LiveMessage introduction for the Chat Message */
liveAuthorIntro: string;
/** String for aria text of remote user's message content */
messageContentAriaText: string;
/** String for aria text of local user's message content */
messageContentMineAriaText: string;
/** String for warning on text limit exceeded in EditBox*/
editBoxTextLimit: string;
/** String for placeholder text in EditBox when there is no user input*/
editBoxPlaceholderText: string;
/** String for new messages indicator*/
newMessagesIndicator: string;
/** String for showing message read status in floating menu */
messageReadCount?: string;
/** String for replacing display name when there is none*/
noDisplayNameSub: string;
/** String for Cancel button in EditBox*/
editBoxCancelButton: string;
/** String for Submit in EditBox when there is no user input*/
editBoxSubmitButton: string;
/** String for action menu indicating there are more options */
actionMenuMoreOptions?: string;
/** Aria label to announce when a message is deleted */
messageDeletedAnnouncementAriaLabel: string;
/* @conditional-compile-remove(file-sharing) */
/** String for download file button in file card */
downloadFile: string;
/* @conditional-compile-remove(data-loss-prevention) */
/** String for policy violation message removal */
blockedWarningText: string;
/* @conditional-compile-remove(data-loss-prevention) */
/** String for policy violation message removal details link */
blockedWarningLinkText: string;
/* @conditional-compile-remove(file-sharing) @conditional-compile-remove(teams-inline-images-and-file-sharing) */
/** String for aria text in file attachment group*/
fileCardGroupMessage: string;
}
/**
* Arguments for {@link MessageThreadProps.onRenderJumpToNewMessageButton}.
*
* @public
*/
export interface JumpToNewMessageButtonProps {
/** String for button text */
text: string;
/** Callback for when button is clicked */
onClick: () => void;
}
const DefaultJumpToNewMessageButton = (props: JumpToNewMessageButtonProps): JSX.Element => {
const { text, onClick } = props;
return (
<PrimaryButton
className={newMessageButtonStyle}
styles={buttonWithIconStyles}
text={text}
onClick={onClick}
onRenderIcon={() => <Icon iconName="Down" className={DownIconStyle} />}
/>
);
};
/**
* A component to render a single message.
*
* @public
*/
export type MessageRenderer = (props: MessageProps) => JSX.Element;
const memoizeAllMessages = memoizeFnAll(
(
message: Message,
showMessageDate: boolean,
showMessageStatus: boolean,
strings: MessageThreadStrings,
index: number,
onUpdateMessage?: UpdateMessageCallback,
onCancelEditMessage?: CancelEditCallback,
onDeleteMessage?: (messageId: string) => Promise<void>,
onSendMessage?: (content: string) => Promise<void>,
disableEditing?: boolean,
lastSeenChatMessage?: string,
lastSendingChatMessage?: string,
lastDeliveredChatMessage?: string
): _ChatMessageProps => {
let key: string | undefined = message.messageId;
let statusToRender: MessageStatus | undefined = undefined;
if (
message.messageType === 'chat' ||
/* @conditional-compile-remove(data-loss-prevention) */ message.messageType === 'blocked'
) {
if ((!message.messageId || message.messageId === '') && 'clientMessageId' in message) {
key = message.clientMessageId;
}
if (showMessageStatus && message.mine) {
switch (message.messageId) {
case lastSeenChatMessage: {
statusToRender = 'seen';
break;
}
case lastSendingChatMessage: {
statusToRender = 'sending';
break;
}
case lastDeliveredChatMessage: {
statusToRender = 'delivered';
break;
}
}
}
if (message.mine && message.status === 'failed') {
statusToRender = 'failed';
}
}
return {
key: key ?? 'id_' + index,
statusToRender,
message,
strings,
showDate: showMessageDate,
onUpdateMessage,
onCancelEditMessage,
onDeleteMessage,
onSendMessage,
disableEditing,
showMessageStatus
};
}
);
const getLastChatMessageIdWithStatus = (messages: Message[], status: MessageStatus): string | undefined => {
for (let i = messages.length - 1; i >= 0; i--) {
const message = messages[i];
if (message.messageType === 'chat' && message.status === status && message.mine) {
return message.messageId;
}
}
return undefined;
};
/**
* @public
* Callback function run when a message is updated.
*/
export type UpdateMessageCallback = (
messageId: string,
content: string,
/* @conditional-compile-remove(file-sharing) */
options?: {
/* @conditional-compile-remove(file-sharing) */
metadata?: Record<string, string>;
attachmentMetadata?: AttachmentMetadata[];
}
) => Promise<void>;
/**
* @public
* Callback function run when a message edit is cancelled.
*/
export type CancelEditCallback = (messageId: string) => void;
/**
* Props for {@link MessageThread}.
*
* @public
*/
export type MessageThreadProps = {
/**
* UserId of the current user.
*/
userId: string;
/**
* Messages to render in message thread. A message can be of type `ChatMessage`, `SystemMessage`, `BlockedMessage` or `CustomMessage`.
*/
messages: (
| ChatMessage
| SystemMessage
| CustomMessage
| /* @conditional-compile-remove(data-loss-prevention) */ BlockedMessage
)[];
/**
* number of participants in the thread
*/
participantCount?: number;
/**
* read receipts for each sender in the chat
*/
readReceiptsBySenderId?: ReadReceiptsBySenderId;
/**
* Allows users to pass an object containing custom CSS styles.
* @Example
* ```
* <MessageThread styles={{ root: { background: 'blue' } }} />
* ```
*/
styles?: MessageThreadStyles;
/**
* Whether the new message button is disabled or not.
*
* @defaultValue `false`
*/
disableJumpToNewMessageButton?: boolean;
/**
* Whether the date of each message is displayed or not.
* It is ignored when onDisplayDateTimeString is supplied.
*
* @defaultValue `false`
*/
showMessageDate?: boolean;
/**
* Whether the status indicator for each message is displayed or not.
*
* @defaultValue `false`
*/
showMessageStatus?: boolean;
/**
* Number of chat messages to reload each time onLoadPreviousChatMessages is called.
*
* @defaultValue 0
*/
numberOfChatMessagesToReload?: number;
/**
* Optional callback to override actions on message being seen.
*
* @param messageId - message Id
*/
onMessageSeen?: (messageId: string) => Promise<void>;
/**
* Optional callback to override render of the message status indicator.
*
* @param messageStatusIndicatorProps - props of type MessageStatusIndicatorProps
*/
onRenderMessageStatus?: (messageStatusIndicatorProps: MessageStatusIndicatorProps) => JSX.Element | null;
/**
* Optional callback to override render of the avatar.
*
* @param userId - user Id
*/
onRenderAvatar?: OnRenderAvatarCallback;
/**
* Optional callback to override render of the button for jumping to the new message.
*
* @param newMessageButtonProps - button props of type JumpToNewMessageButtonProps 0 */
onRenderJumpToNewMessageButton?: (newMessageButtonProps: JumpToNewMessageButtonProps) => JSX.Element;
/**
* Optional callback to override loading of previous messages.
* It accepts the number of history chat messages that we want to load and return a boolean Promise indicating if we have got all the history messages.
* If the promise resolves to `true`, we have load all chat messages into the message thread and `loadPreviousMessagesButton` will not be rendered anymore.
*/
onLoadPreviousChatMessages?: (messagesToLoad: number) => Promise<boolean>;
/**
* Optional callback to override render of a message.
*
* @param messageProps - props of type {@link communication-react#MessageProps}
* @param defaultOnRender - default render of type {@link communication-react#MessageRenderer}
*
* @remarks
* `messageRenderer` is not provided for `CustomMessage` and thus only available for `ChatMessage` and `SystemMessage`.
*/
onRenderMessage?: (messageProps: MessageProps, messageRenderer?: MessageRenderer) => JSX.Element;
/* @conditional-compile-remove(file-sharing) */
/**
* Optional callback to render attached files in the message component.
* @beta
*/
onRenderFileDownloads?: (userId: string, message: ChatMessage) => JSX.Element;
/* @conditional-compile-remove(teams-inline-images-and-file-sharing) */
/**
* Optional callback to retrieve the inline image in a message.
* @param attachment - AttachmentMetadata object we want to render
* @beta
*/
onFetchAttachments?: (attachments: AttachmentMetadata[]) => Promise<AttachmentDownloadResult[]>;
/**
* Optional callback to edit a message.
*
* @param messageId - message id from chatClient
* @param content - new content of the message
*
*/
onUpdateMessage?: UpdateMessageCallback;
/**
* Optional callback for when a message edit is cancelled.
*
* @param messageId - message id from chatClient
*/
onCancelEditMessage?: CancelEditCallback;
/**
* Optional callback to delete a message.
*
* @param messageId - message id from chatClient
*
*/
onDeleteMessage?: (messageId: string) => Promise<void>;
/**
* Optional callback to send a message.
*
* @param content - message body to send
*
*/
onSendMessage?: (content: string) => Promise<void>;
/**
/**
* Disable editing messages.
*
* @remarks This removes the action menu on messages.
*
* @defaultValue `false`
*/
disableEditing?: boolean;
/**
* Optional strings to override in component
*/
strings?: Partial<MessageThreadStrings>;
/* @conditional-compile-remove(file-sharing) */
/**
* @beta
* Optional function called when someone clicks on the file download icon.
* If file attachments are defined in the `message.metadata` property using the `fileSharingMetadata` key,
* this function will be called with the data inside `fileSharingMetadata` key.
*/
fileDownloadHandler?: FileDownloadHandler;
/* @conditional-compile-remove(date-time-customization) */
/**
* Optional function to provide customized date format.
* @beta
*/
onDisplayDateTimeString?: (messageDate: Date) => string;
/* @conditional-compile-remove(mention) */
/**
* Optional props needed to lookup a mention query and display mentions
* @beta
*/
mentionOptions?: MentionOptions;
/* @conditional-compile-remove(image-gallery) */
/**
* Optional callback called when an inline image is clicked.
* @beta
*/
onInlineImageClicked?: (attachmentId: string, messageId: string) => Promise<void>;
};
/**
* Props to render a single message.
*
* See {@link MessageRenderer}.
*
* @public
*/
export type MessageProps = {
/**
* Message to render. It can type `ChatMessage` or `SystemMessage`, `BlockedMessage` or `CustomMessage`.
*/
message: Message;
/**
* Strings from parent MessageThread component
*/
strings: MessageThreadStrings;
/**
* Custom CSS styles for chat message container.
*/
messageContainerStyle?: ComponentSlotStyle;
/**
* Whether the date of a message is displayed or not.
*
* @defaultValue `false`
*/
showDate?: boolean;
/**
* Disable editing messages.
*
* @remarks This removes the action menu on messages.
*
* @defaultValue `false`
*/
disableEditing?: boolean;
/**
* Optional callback to edit a message.
*
* @param messageId - message id from chatClient
* @param content - new content of the message
*/
onUpdateMessage?: UpdateMessageCallback;
/**
* Optional callback for when a message edit is cancelled.
*
* @param messageId - message id from chatClient
*/
onCancelEditMessage?: CancelEditCallback;
/**
* Optional callback to delete a message.
*
* @param messageId - message id from chatClient
*
*/
onDeleteMessage?: (messageId: string) => Promise<void>;
/**
* Optional callback to send a message.
*
* @param messageId - message id from chatClient
*
*/
onSendMessage?: (messageId: string) => Promise<void>;
};
/**
* @internal
*/
export type _ChatMessageProps = MessageProps & {
key: string;
statusToRender: MessageStatus | undefined;
showMessageStatus?: boolean;
};
/**
* `MessageThread` allows you to easily create a component for rendering chat messages, handling scrolling behavior of new/old messages and customizing icons & controls inside the chat thread.
* @param props - of type MessageThreadProps
*
* Users will need to provide at least chat messages and userId to render the `MessageThread` component.
* Users can also customize `MessageThread` by passing in their own Avatar, `MessageStatusIndicator` icon, `JumpToNewMessageButton`, `LoadPreviousMessagesButton` and the behavior of these controls.
*
* `MessageThread` internally uses the `Chat` component from `@fluentui-contrib/chat`. You can checkout the details about these components [here](https://microsoft.github.io/fluentui-contrib/react-chat/).
*
* @public
*/
export const MessageThread = (props: MessageThreadProps): JSX.Element => {
const theme = useTheme();
const chatBody = useMemo(() => {
return (
<FluentV9ThemeProvider v8Theme={theme}>
{/* Wrapper is required to call "useClasses" hook with proper context values */}
<MessageThreadWrapper {...props} />
</FluentV9ThemeProvider>
);
}, [theme, props]);
return <div className={mergeStyles(messageThreadContainerStyle, props.styles?.root)}>{chatBody}</div>;
};
/**
* @private
*/
export const MessageThreadWrapper = (props: MessageThreadProps): JSX.Element => {
const {
messages: newMessages,
userId,
participantCount,
readReceiptsBySenderId,
styles,
disableJumpToNewMessageButton = false,
showMessageDate = false,
showMessageStatus = false,
numberOfChatMessagesToReload = 5,
onMessageSeen,
onRenderMessageStatus,
onRenderAvatar,
onLoadPreviousChatMessages,
onRenderJumpToNewMessageButton,
onRenderMessage,
onUpdateMessage,
onCancelEditMessage,
onDeleteMessage,
onSendMessage,
/* @conditional-compile-remove(date-time-customization) */
onDisplayDateTimeString,
/* @conditional-compile-remove(teams-inline-images-and-file-sharing) */
onFetchAttachments,
/* @conditional-compile-remove(mention) */
mentionOptions,
/* @conditional-compile-remove(image-gallery) */
onInlineImageClicked,
/* @conditional-compile-remove(file-sharing) */
onRenderFileDownloads
} = props;
// We need this state to wait for one tick and scroll to bottom after messages have been initialized.
// Otherwise chatScrollDivRef.current.clientHeight is wrong if we scroll to bottom before messages are initialized.
const [chatMessagesInitialized, setChatMessagesInitialized] = useState<boolean>(false);
const [isAtBottomOfScroll, setIsAtBottomOfScroll] = useState<boolean>(true);
const [forceUpdate, setForceUpdate] = useState<number>(0);
// Used to decide if should auto scroll to bottom or show "new message" button
const [latestPreviousChatMessage, setLatestPreviousChatMessage] = useState<ChatMessage | undefined>(undefined);
const [latestCurrentChatMessage, setLatestCurrentChatMessage] = useState<ChatMessage | undefined>(undefined);
const [existsNewChatMessage, setExistsNewChatMessage] = useState<boolean>(false);
const [lastSeenChatMessage, setLastSeenChatMessage] = useState<string | undefined>(undefined);
const [lastDeliveredChatMessage, setLastDeliveredChatMessage] = useState<string | undefined>(undefined);
const [lastSendingChatMessage, setLastSendingChatMessage] = useState<string | undefined>(undefined);
// readCount and participantCount will only need to be updated on-fly when user hover on an indicator
const [readCountForHoveredIndicator, setReadCountForHoveredIndicator] = useState<number | undefined>(undefined);
/* @conditional-compile-remove(teams-inline-images-and-file-sharing) */
const [inlineAttachments, setInlineAttachments] = useState<Record<string, Record<string, string>>>({});
/* @conditional-compile-remove(teams-inline-images-and-file-sharing) */
const onFetchInlineAttachment = useCallback(
async (attachments: AttachmentMetadata[], messageId: string): Promise<void> => {
if (!onFetchAttachments || attachments.length === 0) {
return;
}
const attachmentDownloadResult = await onFetchAttachments(attachments);
if (attachmentDownloadResult.length > 0) {
setInlineAttachments((prev) => {
// The new state should always be based on the previous one
// otherwise there can be issues with renders
const listOfAttachments = prev[messageId] ?? {};
for (const result of attachmentDownloadResult) {
const { attachmentId, blobUrl } = result;
listOfAttachments[attachmentId] = blobUrl;
}
return { ...prev, [messageId]: listOfAttachments };
});
}
},
[onFetchAttachments]
);
const localeStrings = useLocale().strings.messageThread;
const strings = useMemo(() => ({ ...localeStrings, ...props.strings }), [localeStrings, props.strings]);
// id for the latest deleted message
const [latestDeletedMessageId, setLatestDeletedMessageId] = useState<string | undefined>(undefined);
// this value is used to check if a message is deleted for the previous value of messages array
const previousMessagesRef = useRef<Message[]>([]);
// an aria label for Narrator to notify when a message is deleted
const [deletedMessageAriaLabel, setDeletedMessageAriaLabel] = useState<string | undefined>(undefined);
const onDeleteMessageCallback = useCallback(
async (messageId: string): Promise<void> => {
if (!onDeleteMessage) {
return;
}
try {
await onDeleteMessage(messageId);
// reset deleted message label in case if there was a value already (messages are deleted 1 after another)
setDeletedMessageAriaLabel(undefined);
setLatestDeletedMessageId(messageId);
} catch (e) {
console.log('onDeleteMessage failed: messageId', messageId, 'error', e);
}
},
[onDeleteMessage]
);
const isAllChatMessagesLoadedRef = useRef(false);
// isAllChatMessagesLoadedRef needs to be updated every time when a new adapter is set in order to display correct data
// onLoadPreviousChatMessages is updated when a new adapter is set
useEffect(() => {
if (onLoadPreviousChatMessages) {
isAllChatMessagesLoadedRef.current = false;
}
}, [onLoadPreviousChatMessages]);
/* @conditional-compile-remove(file-sharing) */ /* @conditional-compile-remove(teams-inline-images-and-file-sharing) */
useEffect(() => {
initializeFileTypeIcons();
}, []);
const previousTopRef = useRef<number>(-1);
const previousHeightRef = useRef<number>(-1);
const messageIdSeenByMeRef = useRef<string>('');
const chatScrollDivRef = useRef<HTMLDivElement>(null);
const isLoadingChatMessagesRef = useRef(false);
const messages = useMemo(() => {
return newMessages;
}, [newMessages]);
useEffect(() => {
if (latestDeletedMessageId === undefined) {
setDeletedMessageAriaLabel(undefined);
} else {
if (!previousMessagesRef.current.find((message) => message.messageId === latestDeletedMessageId)) {
// the message is deleted in previousMessagesRef
// no need to update deletedMessageAriaLabel
setDeletedMessageAriaLabel(undefined);
} else if (!messages.find((message) => message.messageId === latestDeletedMessageId)) {
// the message is deleted in messages array but still exists in previousMessagesRef
// update deletedMessageAriaLabel
setDeletedMessageAriaLabel(strings.messageDeletedAnnouncementAriaLabel);
} else {
// the message exists in both arrays
// no need to update deletedMessageAriaLabel
setDeletedMessageAriaLabel(undefined);
}
}
previousMessagesRef.current = messages;
}, [latestDeletedMessageId, messages, strings.messageDeletedAnnouncementAriaLabel]);
const messagesRef = useRef(messages);
const setMessagesRef = (messagesWithAttachedValue: Message[]): void => {
messagesRef.current = messagesWithAttachedValue;
};
const isAtBottomOfScrollRef = useRef(isAtBottomOfScroll);
const setIsAtBottomOfScrollRef = (isAtBottomOfScrollValue: boolean): void => {
isAtBottomOfScrollRef.current = isAtBottomOfScrollValue;
setIsAtBottomOfScroll(isAtBottomOfScrollValue);
};
const chatMessagesInitializedRef = useRef(chatMessagesInitialized);
const setChatMessagesInitializedRef = (chatMessagesInitialized: boolean): void => {
chatMessagesInitializedRef.current = chatMessagesInitialized;
setChatMessagesInitialized(chatMessagesInitialized);
};
const chatThreadRef = useRef<HTMLDivElement>(null);
// When the chat thread is narrow, we perform space optimizations such as overlapping
// the avatar on top of the chat message and moving the chat accept/reject edit buttons
// to a new line
const chatThreadWidth = _useContainerWidth(chatThreadRef);
const isNarrow = chatThreadWidth ? isNarrowWidth(chatThreadWidth) : false;
/**
* ClientHeight controls the number of messages to render. However ClientHeight will not be initialized after the
* first render (not sure but I guess Fluent is updating it in hook which is after render maybe?) so we need to
* trigger a re-render until ClientHeight is initialized. This force re-render should only happen once.
*/
const clientHeight = chatThreadRef.current?.clientHeight;
// we try to only send those message status if user is scrolled to the bottom.
const sendMessageStatusIfAtBottom = useCallback(async (): Promise<void> => {
if (
!isAtBottomOfScrollRef.current ||
!document.hasFocus() ||
!messagesRef.current ||
messagesRef.current.length === 0 ||
!showMessageStatus
) {
return;
}
const messagesWithId = messagesRef.current.filter((message) => {
return message.messageType === 'chat' && !message.mine && !!message.messageId;
});
if (messagesWithId.length === 0) {
return;
}
const lastMessage: ChatMessage = messagesWithId[messagesWithId.length - 1] as ChatMessage;
try {
if (
onMessageSeen &&
lastMessage &&
lastMessage.messageId &&
lastMessage.messageId !== messageIdSeenByMeRef.current
) {
await onMessageSeen(lastMessage.messageId);
messageIdSeenByMeRef.current = lastMessage.messageId;
}
} catch (e) {
console.log('onMessageSeen Error', lastMessage, e);
}
}, [showMessageStatus, onMessageSeen]);
const scrollToBottom = useCallback((): void => {
if (chatScrollDivRef.current) {
chatScrollDivRef.current.scrollTop = chatScrollDivRef.current.scrollHeight;
}
setExistsNewChatMessage(false);
setIsAtBottomOfScrollRef(true);
sendMessageStatusIfAtBottom();
}, [sendMessageStatusIfAtBottom]);
const handleScrollToTheBottom = useCallback((): void => {
if (!chatScrollDivRef.current) {
return;
}
const atBottom =
Math.ceil(chatScrollDivRef.current.scrollTop) >=
chatScrollDivRef.current.scrollHeight - chatScrollDivRef.current.clientHeight;
if (atBottom) {
sendMessageStatusIfAtBottom();
if (!isAtBottomOfScrollRef.current) {
scrollToBottom();
}
}
setIsAtBottomOfScrollRef(atBottom);
}, [scrollToBottom, sendMessageStatusIfAtBottom]);
// Infinite scrolling + threadInitialize function
const fetchNewMessageWhenAtTop = useCallback(async () => {
if (!isLoadingChatMessagesRef.current) {
if (onLoadPreviousChatMessages) {
isLoadingChatMessagesRef.current = true;
try {
// Fetch message until scrollTop reach the threshold for fetching new message
while (
!isAllChatMessagesLoadedRef.current &&
chatScrollDivRef.current &&
chatScrollDivRef.current.scrollTop <= 500
) {
isAllChatMessagesLoadedRef.current = await onLoadPreviousChatMessages(numberOfChatMessagesToReload);
await delay(200);
}
} finally {
// Set isLoadingChatMessagesRef to false after messages are fetched
isLoadingChatMessagesRef.current = false;
}
}
}
}, [numberOfChatMessagesToReload, onLoadPreviousChatMessages]);
// The below 2 of useEffects are design for fixing infinite scrolling problem
// Scrolling element will behave differently when scrollTop = 0(it sticks at the top)
// we need to get previousTop before it prepend contents
// Execute order [newMessage useEffect] => get previousTop => dom update => [messages useEffect]
useEffect(() => {
if (!chatScrollDivRef.current) {
return;
}
previousTopRef.current = chatScrollDivRef.current.scrollTop;
previousHeightRef.current = chatScrollDivRef.current.scrollHeight;
}, [newMessages]);
useEffect(() => {
if (!chatScrollDivRef.current) {
return;
}
chatScrollDivRef.current.scrollTop =
chatScrollDivRef.current.scrollHeight - (previousHeightRef.current - previousTopRef.current);
}, [messages]);
// Fetch more messages to make the scroll bar appear, infinity scroll is then handled in the handleScroll function.
useEffect(() => {
fetchNewMessageWhenAtTop();
}, [fetchNewMessageWhenAtTop]);
/**
* One time run useEffects. Sets up listeners when component is mounted and tears down listeners when component
* unmounts unless these function changed
*/
useEffect(() => {
window && window.addEventListener('click', sendMessageStatusIfAtBottom);
window && window.addEventListener('focus', sendMessageStatusIfAtBottom);
return () => {
window && window.removeEventListener('click', sendMessageStatusIfAtBottom);
window && window.removeEventListener('focus', sendMessageStatusIfAtBottom);
};
}, [sendMessageStatusIfAtBottom]);
useEffect(() => {
const chatScrollDiv = chatScrollDivRef.current;
chatScrollDiv?.addEventListener('scroll', handleScrollToTheBottom);
chatScrollDiv?.addEventListener('scroll', fetchNewMessageWhenAtTop);
return () => {
chatScrollDiv?.removeEventListener('scroll', handleScrollToTheBottom);
chatScrollDiv?.removeEventListener('scroll', fetchNewMessageWhenAtTop);
};
}, [fetchNewMessageWhenAtTop, handleScrollToTheBottom]);
useEffect(() => {
if (clientHeight === undefined) {
setForceUpdate(forceUpdate + 1);
return;
}
// Only scroll to bottom if isAtBottomOfScrollRef is true
isAtBottomOfScrollRef.current && scrollToBottom();
}, [clientHeight, forceUpdate, scrollToBottom, chatMessagesInitialized]);
/**
* This needs to run to update latestPreviousChatMessage & latestCurrentChatMessage.
* These two states are used to manipulate scrollbar
*/
useEffect(() => {
setLatestPreviousChatMessage(getLatestChatMessage(messagesRef.current));
setLatestCurrentChatMessage(getLatestChatMessage(newMessages));
setMessagesRef(newMessages);
!chatMessagesInitializedRef.current && setChatMessagesInitializedRef(true);
setLastDeliveredChatMessage(getLastChatMessageIdWithStatus(newMessages, 'delivered'));
setLastSeenChatMessage(getLastChatMessageIdWithStatus(newMessages, 'seen'));
setLastSendingChatMessage(getLastChatMessageIdWithStatus(newMessages, 'sending'));
}, [newMessages]);
/**
* This needs to run after messages are rendered so we can manipulate the scroll bar.
*/
useEffect(() => {
// If user just sent the latest message then we assume we can move user to bottom of scroll.
if (
isThereNewMessageNotFromCurrentUser(userId, latestPreviousChatMessage, latestCurrentChatMessage) &&
!isAtBottomOfScrollRef.current
) {
setExistsNewChatMessage(true);
} else if (
didUserSendTheLatestMessage(userId, latestPreviousChatMessage, latestCurrentChatMessage) ||
isAtBottomOfScrollRef.current
) {
scrollToBottom();
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [messages]);
const participantCountRef = useRef(participantCount);