-
Notifications
You must be signed in to change notification settings - Fork 280
/
Copy pathChannel.tsx
1241 lines (1105 loc) Β· 53.7 KB
/
Channel.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
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
import React, {
PropsWithChildren,
useCallback,
useEffect,
useLayoutEffect,
useMemo,
useReducer,
useRef,
useState,
} from 'react';
import debounce from 'lodash.debounce';
import throttle from 'lodash.throttle';
import {
ChannelAPIResponse,
ChannelMemberResponse,
ChannelQueryOptions,
ChannelState,
Event,
EventAPIResponse,
Message,
MessageResponse,
SendMessageAPIResponse,
Channel as StreamChannel,
StreamChat,
UpdatedMessage,
UserResponse,
} from 'stream-chat';
import { nanoid } from 'nanoid';
import clsx from 'clsx';
import { channelReducer, ChannelStateReducer, initialState } from './channelState';
import { useCreateChannelStateContext } from './hooks/useCreateChannelStateContext';
import { useCreateTypingContext } from './hooks/useCreateTypingContext';
import { useEditMessageHandler } from './hooks/useEditMessageHandler';
import { useIsMounted } from './hooks/useIsMounted';
import { OnMentionAction, useMentionsHandlers } from './hooks/useMentionsHandlers';
import { Attachment as DefaultAttachment } from '../Attachment/Attachment';
import {
LoadingErrorIndicator as DefaultLoadingErrorIndicator,
LoadingErrorIndicatorProps,
} from '../Loading';
import { LoadingChannel as DefaultLoadingIndicator } from './LoadingChannel';
import { MessageSimple } from '../Message/MessageSimple';
import { DropzoneProvider } from '../MessageInput/DropzoneProvider';
import {
ChannelActionContextValue,
ChannelActionProvider,
MarkReadWrapperOptions,
MessageToSend,
} from '../../context/ChannelActionContext';
import {
ChannelNotifications,
ChannelStateProvider,
StreamMessage,
} from '../../context/ChannelStateContext';
import { ComponentContextValue, ComponentProvider } from '../../context/ComponentContext';
import { useChatContext } from '../../context/ChatContext';
import { useTranslationContext } from '../../context/TranslationContext';
import { TypingProvider } from '../../context/TypingContext';
import {
DEFAULT_INITIAL_CHANNEL_PAGE_SIZE,
DEFAULT_NEXT_CHANNEL_PAGE_SIZE,
DEFAULT_THREAD_PAGE_SIZE,
} from '../../constants/limits';
import type { UnreadMessagesNotificationProps } from '../MessageList';
import { hasMoreMessagesProbably, UnreadMessagesSeparator } from '../MessageList';
import { useChannelContainerClasses } from './hooks/useChannelContainerClasses';
import { makeAddNotifications } from './utils';
import { getChannel } from '../../utils';
import type { MessageProps } from '../Message/types';
import type { MessageInputProps } from '../MessageInput/MessageInput';
import type {
ChannelUnreadUiState,
CustomTrigger,
DefaultStreamChatGenerics,
GiphyVersions,
ImageAttachmentSizeHandler,
SendMessageOptions,
UpdateMessageOptions,
VideoAttachmentSizeHandler,
} from '../../types/types';
import {
getImageAttachmentConfiguration,
getVideoAttachmentConfiguration,
} from '../Attachment/attachment-sizing';
import type { URLEnrichmentConfig } from '../MessageInput/hooks/useLinkPreviews';
import { defaultReactionOptions, ReactionOptions } from '../Reactions';
import { EventComponent } from '../EventComponent';
import { DateSeparator } from '../DateSeparator';
type ChannelPropsForwardedToComponentContext<
StreamChatGenerics extends DefaultStreamChatGenerics = DefaultStreamChatGenerics
> = {
/** Custom UI component to display a message attachment, defaults to and accepts same props as: [Attachment](https://github.com/GetStream/stream-chat-react/blob/master/src/components/Attachment/Attachment.tsx) */
Attachment?: ComponentContextValue<StreamChatGenerics>['Attachment'];
/** Custom UI component to display a attachment previews in MessageInput, defaults to and accepts same props as: [Attachment](https://github.com/GetStream/stream-chat-react/blob/master/src/components/MessageInput/AttachmentPreviewList.tsx) */
AttachmentPreviewList?: ComponentContextValue<StreamChatGenerics>['AttachmentPreviewList'];
/** Optional UI component to override the default suggestion Header component, defaults to and accepts same props as: [Header](https://github.com/GetStream/stream-chat-react/blob/master/src/components/AutoCompleteTextarea/Header.tsx) */
AutocompleteSuggestionHeader?: ComponentContextValue<StreamChatGenerics>['AutocompleteSuggestionHeader'];
/** Optional UI component to override the default suggestion Item component, defaults to and accepts same props as: [Item](https://github.com/GetStream/stream-chat-react/blob/master/src/components/AutoCompleteTextarea/Item.js) */
AutocompleteSuggestionItem?: ComponentContextValue<StreamChatGenerics>['AutocompleteSuggestionItem'];
/** Optional UI component to override the default List component that displays suggestions, defaults to and accepts same props as: [List](https://github.com/GetStream/stream-chat-react/blob/master/src/components/AutoCompleteTextarea/List.js) */
AutocompleteSuggestionList?: ComponentContextValue<StreamChatGenerics>['AutocompleteSuggestionList'];
/** UI component to display a user's avatar, defaults to and accepts same props as: [Avatar](https://github.com/GetStream/stream-chat-react/blob/master/src/components/Avatar/Avatar.tsx) */
Avatar?: ComponentContextValue<StreamChatGenerics>['Avatar'];
/** Custom UI component to display <img/> elements resp. a fallback in case of load error, defaults to and accepts same props as: [BaseImage](https://github.com/GetStream/stream-chat-react/blob/master/src/components/Gallery/BaseImage.tsx) */
BaseImage?: ComponentContextValue<StreamChatGenerics>['BaseImage'];
/** Custom UI component to display the slow mode cooldown timer, defaults to and accepts same props as: [CooldownTimer](https://github.com/GetStream/stream-chat-react/blob/master/src/components/MessageInput/CooldownTimer.tsx) */
CooldownTimer?: ComponentContextValue<StreamChatGenerics>['CooldownTimer'];
/** Custom UI component to render set of buttons to be displayed in the MessageActionsBox, defaults to and accepts same props as: [CustomMessageActionsList](https://github.com/GetStream/stream-chat-react/blob/master/src/components/MessageActions/CustomMessageActionsList.tsx) */
CustomMessageActionsList?: ComponentContextValue<StreamChatGenerics>['CustomMessageActionsList'];
/** Custom UI component for date separators, defaults to and accepts same props as: [DateSeparator](https://github.com/GetStream/stream-chat-react/blob/master/src/components/DateSeparator.tsx) */
DateSeparator?: ComponentContextValue<StreamChatGenerics>['DateSeparator'];
/** Custom UI component to override default edit message input, defaults to and accepts same props as: [EditMessageForm](https://github.com/GetStream/stream-chat-react/blob/master/src/components/MessageInput/EditMessageForm.tsx) */
EditMessageInput?: ComponentContextValue<StreamChatGenerics>['EditMessageInput'];
/** Custom UI component for rendering button with emoji picker in MessageInput */
EmojiPicker?: ComponentContextValue<StreamChatGenerics>['EmojiPicker'];
/** Mechanism to be used with autocomplete and text replace features of the `MessageInput` component, see [emoji-mart `SearchIndex`](https://github.com/missive/emoji-mart#%EF%B8%8F%EF%B8%8F-headless-search) */
emojiSearchIndex?: ComponentContextValue<StreamChatGenerics>['emojiSearchIndex'];
/** Custom UI component to be displayed when the `MessageList` is empty, defaults to and accepts same props as: [EmptyStateIndicator](https://github.com/GetStream/stream-chat-react/blob/master/src/components/EmptyStateIndicator/EmptyStateIndicator.tsx) */
EmptyStateIndicator?: ComponentContextValue<StreamChatGenerics>['EmptyStateIndicator'];
/** Custom UI component for file upload icon, defaults to and accepts same props as: [FileUploadIcon](https://github.com/GetStream/stream-chat-react/blob/master/src/components/MessageInput/icons.tsx) */
FileUploadIcon?: ComponentContextValue<StreamChatGenerics>['FileUploadIcon'];
/** Custom UI component to render a Giphy preview in the `VirtualizedMessageList` */
GiphyPreviewMessage?: ComponentContextValue<StreamChatGenerics>['GiphyPreviewMessage'];
/** Custom UI component to render at the top of the `MessageList` */
HeaderComponent?: ComponentContextValue<StreamChatGenerics>['HeaderComponent'];
/** Custom UI component handling how the message input is rendered, defaults to and accepts the same props as [MessageInputFlat](https://github.com/GetStream/stream-chat-react/blob/master/src/components/MessageInput/MessageInputFlat.tsx) */
Input?: ComponentContextValue<StreamChatGenerics>['Input'];
/** Custom component to render link previews in message input **/
LinkPreviewList?: ComponentContextValue<StreamChatGenerics>['LinkPreviewList'];
/** Custom UI component to be shown if the channel query fails, defaults to and accepts same props as: [LoadingErrorIndicator](https://github.com/GetStream/stream-chat-react/blob/master/src/components/Loading/LoadingErrorIndicator.tsx) */
LoadingErrorIndicator?: React.ComponentType<LoadingErrorIndicatorProps>;
/** Custom UI component to render while the `MessageList` is loading new messages, defaults to and accepts same props as: [LoadingIndicator](https://github.com/GetStream/stream-chat-react/blob/master/src/components/Loading/LoadingIndicator.tsx) */
LoadingIndicator?: ComponentContextValue<StreamChatGenerics>['LoadingIndicator'];
/** Custom UI component to display a message in the standard `MessageList`, defaults to and accepts the same props as: [MessageSimple](https://github.com/GetStream/stream-chat-react/blob/master/src/components/Message/MessageSimple.tsx) */
Message?: ComponentContextValue<StreamChatGenerics>['Message'];
/** Custom UI component to display the contents of a bounced message modal. Usually it allows to retry, edit, or delete the message. Defaults to and accepts the same props as: [MessageBouncePrompt](https://github.com/GetStream/stream-chat-react/blob/master/src/components/MessageBounce/MessageBouncePrompt.tsx) */
MessageBouncePrompt?: ComponentContextValue<StreamChatGenerics>['MessageBouncePrompt'];
/** Custom UI component for a deleted message, defaults to and accepts same props as: [MessageDeleted](https://github.com/GetStream/stream-chat-react/blob/master/src/components/Message/MessageDeleted.tsx) */
MessageDeleted?: ComponentContextValue<StreamChatGenerics>['MessageDeleted'];
/** Custom UI component that displays message and connection status notifications in the `MessageList`, defaults to and accepts same props as [DefaultMessageListNotifications](https://github.com/GetStream/stream-chat-react/blob/master/src/components/MessageList/MessageListNotifications.tsx) */
MessageListNotifications?: ComponentContextValue<StreamChatGenerics>['MessageListNotifications'];
/** Custom UI component to display a notification when scrolled up the list and new messages arrive, defaults to and accepts same props as [MessageNotification](https://github.com/GetStream/stream-chat-react/blob/master/src/components/MessageList/MessageNotification.tsx) */
MessageNotification?: ComponentContextValue<StreamChatGenerics>['MessageNotification'];
/** Custom UI component for message options popup, defaults to and accepts same props as: [MessageOptions](https://github.com/GetStream/stream-chat-react/blob/master/src/components/Message/MessageOptions.tsx) */
MessageOptions?: ComponentContextValue<StreamChatGenerics>['MessageOptions'];
/** Custom UI component to display message replies, defaults to and accepts same props as: [MessageRepliesCountButton](https://github.com/GetStream/stream-chat-react/blob/master/src/components/Message/MessageRepliesCountButton.tsx) */
MessageRepliesCountButton?: ComponentContextValue<StreamChatGenerics>['MessageRepliesCountButton'];
/** Custom UI component to display message delivery status, defaults to and accepts same props as: [MessageStatus](https://github.com/GetStream/stream-chat-react/blob/master/src/components/Message/MessageStatus.tsx) */
MessageStatus?: ComponentContextValue<StreamChatGenerics>['MessageStatus'];
/** Custom UI component to display system messages, defaults to and accepts same props as: [EventComponent](https://github.com/GetStream/stream-chat-react/blob/master/src/components/EventComponent/EventComponent.tsx) */
MessageSystem?: ComponentContextValue<StreamChatGenerics>['MessageSystem'];
/** Custom UI component to display a timestamp on a message, defaults to and accepts same props as: [MessageTimestamp](https://github.com/GetStream/stream-chat-react/blob/master/src/components/Message/MessageTimestamp.tsx) */
MessageTimestamp?: ComponentContextValue<StreamChatGenerics>['MessageTimestamp'];
/** Custom UI component for viewing message's image attachments, defaults to and accepts the same props as [ModalGallery](https://github.com/GetStream/stream-chat-react/blob/master/src/components/Gallery/ModalGallery.tsx) */
ModalGallery?: ComponentContextValue<StreamChatGenerics>['ModalGallery'];
/** Custom UI component to override default pinned message indicator, defaults to and accepts same props as: [PinIndicator](https://github.com/GetStream/stream-chat-react/blob/master/src/components/Message/icons.tsx) */
PinIndicator?: ComponentContextValue<StreamChatGenerics>['PinIndicator'];
/** Custom UI component to override quoted message UI on a sent message, defaults to and accepts same props as: [QuotedMessage](https://github.com/GetStream/stream-chat-react/blob/master/src/components/Message/QuotedMessage.tsx) */
QuotedMessage?: ComponentContextValue<StreamChatGenerics>['QuotedMessage'];
/** Custom UI component to override the message input's quoted message preview, defaults to and accepts same props as: [QuotedMessagePreview](https://github.com/GetStream/stream-chat-react/blob/master/src/components/MessageInput/QuotedMessagePreview.tsx) */
QuotedMessagePreview?: ComponentContextValue<StreamChatGenerics>['QuotedMessagePreview'];
/** Custom reaction options to be applied to ReactionSelector, ReactionList and SimpleReactionList components */
reactionOptions?: ReactionOptions;
/** Custom UI component to display the reaction selector, defaults to and accepts same props as: [ReactionSelector](https://github.com/GetStream/stream-chat-react/blob/master/src/components/Reactions/ReactionSelector.tsx) */
ReactionSelector?: ComponentContextValue<StreamChatGenerics>['ReactionSelector'];
/** Custom UI component to display the list of reactions on a message, defaults to and accepts same props as: [ReactionsList](https://github.com/GetStream/stream-chat-react/blob/master/src/components/Reactions/ReactionsList.tsx) */
ReactionsList?: ComponentContextValue<StreamChatGenerics>['ReactionsList'];
/** Custom UI component for send button, defaults to and accepts same props as: [SendButton](https://github.com/GetStream/stream-chat-react/blob/master/src/components/MessageInput/icons.tsx) */
SendButton?: ComponentContextValue<StreamChatGenerics>['SendButton'];
/** Custom UI component that displays thread's parent or other message at the top of the `MessageList`, defaults to and accepts same props as [MessageSimple](https://github.com/GetStream/stream-chat-react/blob/master/src/components/Message/MessageSimple.tsx) */
ThreadHead?: React.ComponentType<MessageProps<StreamChatGenerics>>;
/** Custom UI component to display the header of a `Thread`, defaults to and accepts same props as: [DefaultThreadHeader](https://github.com/GetStream/stream-chat-react/blob/master/src/components/Thread/Thread.tsx) */
ThreadHeader?: ComponentContextValue<StreamChatGenerics>['ThreadHeader'];
/** Custom UI component to display the start of a threaded `MessageList`, defaults to and accepts same props as: [DefaultThreadStart](https://github.com/GetStream/stream-chat-react/blob/master/src/components/Thread/Thread.tsx) */
ThreadStart?: ComponentContextValue<StreamChatGenerics>['ThreadStart'];
/** Optional context provider that lets you override the default autocomplete triggers, defaults to: [DefaultTriggerProvider](https://github.com/GetStream/stream-chat-react/blob/master/src/components/MessageInput/DefaultTriggerProvider.tsx) */
TriggerProvider?: ComponentContextValue<StreamChatGenerics>['TriggerProvider'];
/** Custom UI component for the typing indicator, defaults to and accepts same props as: [TypingIndicator](https://github.com/GetStream/stream-chat-react/blob/master/src/components/TypingIndicator/TypingIndicator.tsx) */
TypingIndicator?: ComponentContextValue<StreamChatGenerics>['TypingIndicator'];
/** Custom UI component that indicates a user is viewing unread messages. It disappears once the user scrolls to UnreadMessagesSeparator. Defaults to and accepts same props as: [UnreadMessagesNotification](https://github.com/GetStream/stream-chat-react/blob/master/src/components/MessageList/UnreadMessagesNotification.tsx) */
UnreadMessagesNotification?: React.ComponentType<UnreadMessagesNotificationProps>;
/** Custom UI component that separates read messages from unread, defaults to and accepts same props as: [UnreadMessagesSeparator](https://github.com/GetStream/stream-chat-react/blob/master/src/components/MessageList/UnreadMessagesSeparator.tsx) */
UnreadMessagesSeparator?: ComponentContextValue<StreamChatGenerics>['UnreadMessagesSeparator'];
/** Custom UI component to display a message in the `VirtualizedMessageList`, does not have a default implementation */
VirtualMessage?: ComponentContextValue<StreamChatGenerics>['VirtualMessage'];
};
const isUserResponseArray = <
StreamChatGenerics extends DefaultStreamChatGenerics = DefaultStreamChatGenerics
>(
output: string[] | UserResponse<StreamChatGenerics>[],
): output is UserResponse<StreamChatGenerics>[] =>
(output as UserResponse<StreamChatGenerics>[])[0]?.id != null;
export type ChannelProps<
StreamChatGenerics extends DefaultStreamChatGenerics = DefaultStreamChatGenerics,
V extends CustomTrigger = CustomTrigger
> = ChannelPropsForwardedToComponentContext<StreamChatGenerics> & {
/** List of accepted file types */
acceptedFiles?: string[];
/** Custom handler function that runs when the active channel has unread messages (i.e., when chat is running in a separate browser tab) */
activeUnreadHandler?: (unread: number, documentTitle: string) => void;
/** The connected and active channel */
channel?: StreamChannel<StreamChatGenerics>;
/**
* Optional configuration parameters used for the initial channel query.
* Applied only if the value of channel.initialized is false.
* If the channel instance has already been initialized (channel has been queried),
* then the channel query will be skipped and channelQueryOptions will not be applied.
*/
channelQueryOptions?: ChannelQueryOptions<StreamChatGenerics>;
/** Custom action handler to override the default `client.deleteMessage(message.id)` function */
doDeleteMessageRequest?: (
message: StreamMessage<StreamChatGenerics>,
) => Promise<MessageResponse<StreamChatGenerics>>;
/** Custom action handler to override the default `channel.markRead` request function (advanced usage only) */
doMarkReadRequest?: (
channel: StreamChannel<StreamChatGenerics>,
setChannelUnreadUiState?: (state: ChannelUnreadUiState) => void,
) => Promise<EventAPIResponse<StreamChatGenerics>> | void;
/** Custom action handler to override the default `channel.sendMessage` request function (advanced usage only) */
doSendMessageRequest?: (
channel: StreamChannel<StreamChatGenerics>,
message: Message<StreamChatGenerics>,
options?: SendMessageOptions,
) => ReturnType<StreamChannel<StreamChatGenerics>['sendMessage']> | void;
/** Custom action handler to override the default `client.updateMessage` request function (advanced usage only) */
doUpdateMessageRequest?: (
cid: string,
updatedMessage: UpdatedMessage<StreamChatGenerics>,
options?: UpdateMessageOptions,
) => ReturnType<StreamChat<StreamChatGenerics>['updateMessage']>;
/** If true, chat users will be able to drag and drop file uploads to the entire channel window */
dragAndDropWindow?: boolean;
/** Custom UI component to be shown if no active channel is set, defaults to null and skips rendering the Channel component */
EmptyPlaceholder?: React.ReactElement;
/**
* A global flag to toggle the URL enrichment and link previews in `MessageInput` components.
* By default, the feature is disabled. Can be overridden on Thread, MessageList level through additionalMessageInputProps
* or directly on MessageInput level through urlEnrichmentConfig.
*/
enrichURLForPreview?: URLEnrichmentConfig['enrichURLForPreview'];
/** Global configuration for link preview generation in all the MessageInput components */
enrichURLForPreviewConfig?: Omit<URLEnrichmentConfig, 'enrichURLForPreview'>;
/** The giphy version to render - check the keys of the [Image Object](https://developers.giphy.com/docs/api/schema#image-object) for possible values. Uses 'fixed_height' by default */
giphyVersion?: GiphyVersions;
/** A custom function to provide size configuration for image attachments */
imageAttachmentSizeHandler?: ImageAttachmentSizeHandler;
/**
* Allows to prevent triggering the channel.watch() call when mounting the component.
* That means that no channel data from the back-end will be received neither channel WS events will be delivered to the client.
* Preventing to initialize the channel on mount allows us to postpone the channel creation to a later point in time.
*/
initializeOnMount?: boolean;
/** Configuration parameter to mark the active channel as read when mounted (opened). By default, the channel is marked read on mount. */
markReadOnMount?: boolean;
/** Maximum number of attachments allowed per message */
maxNumberOfFiles?: number;
/** Whether to allow multiple attachment uploads */
multipleUploads?: boolean;
/** Custom action handler function to run on click of an @mention in a message */
onMentionsClick?: OnMentionAction<StreamChatGenerics>;
/** Custom action handler function to run on hover of an @mention in a message */
onMentionsHover?: OnMentionAction<StreamChatGenerics>;
/** If `dragAndDropWindow` prop is true, the props to pass to the MessageInput component (overrides props placed directly on MessageInput) */
optionalMessageInputProps?: MessageInputProps<StreamChatGenerics, V>;
/** You can turn on/off thumbnail generation for video attachments */
shouldGenerateVideoThumbnail?: boolean;
/** If true, skips the message data string comparison used to memoize the current channel messages (helpful for channels with 1000s of messages) */
skipMessageDataMemoization?: boolean;
/** A custom function to provide size configuration for video attachments */
videoAttachmentSizeHandler?: VideoAttachmentSizeHandler;
};
const UnMemoizedChannel = <
StreamChatGenerics extends DefaultStreamChatGenerics = DefaultStreamChatGenerics,
V extends CustomTrigger = CustomTrigger
>(
props: PropsWithChildren<ChannelProps<StreamChatGenerics, V>>,
) => {
const {
channel: propsChannel,
EmptyPlaceholder = null,
LoadingErrorIndicator,
LoadingIndicator = DefaultLoadingIndicator,
} = props;
const {
channel: contextChannel,
channelsQueryState,
customClasses,
theme,
} = useChatContext<StreamChatGenerics>('Channel');
const { channelClass, chatClass } = useChannelContainerClasses({
customClasses,
});
const channel = propsChannel || contextChannel;
const className = clsx(chatClass, theme, channelClass);
if (channelsQueryState.queryInProgress === 'reload' && LoadingIndicator) {
return (
<div className={className}>
<LoadingIndicator />
</div>
);
}
if (channelsQueryState.error && LoadingErrorIndicator) {
return (
<div className={className}>
<LoadingErrorIndicator error={channelsQueryState.error} />
</div>
);
}
if (!channel?.cid) {
return <div className={className}>{EmptyPlaceholder}</div>;
}
return <ChannelInner {...props} channel={channel} key={channel.cid} />;
};
const ChannelInner = <
StreamChatGenerics extends DefaultStreamChatGenerics = DefaultStreamChatGenerics,
V extends CustomTrigger = CustomTrigger
>(
props: PropsWithChildren<
ChannelProps<StreamChatGenerics, V> & {
channel: StreamChannel<StreamChatGenerics>;
key: string;
}
>,
) => {
const {
acceptedFiles,
activeUnreadHandler,
channel,
channelQueryOptions,
children,
doDeleteMessageRequest,
doMarkReadRequest,
doSendMessageRequest,
doUpdateMessageRequest,
dragAndDropWindow = false,
enrichURLForPreviewConfig,
initializeOnMount = true,
LoadingErrorIndicator = DefaultLoadingErrorIndicator,
LoadingIndicator = DefaultLoadingIndicator,
markReadOnMount = true,
maxNumberOfFiles,
multipleUploads = true,
onMentionsClick,
onMentionsHover,
optionalMessageInputProps = {},
skipMessageDataMemoization,
} = props;
const {
client,
customClasses,
latestMessageDatesByChannels,
mutes,
theme,
} = useChatContext<StreamChatGenerics>('Channel');
const { t } = useTranslationContext('Channel');
const {
channelClass,
chatClass,
chatContainerClass,
windowsEmojiClass,
} = useChannelContainerClasses({ customClasses });
const [channelConfig, setChannelConfig] = useState(channel.getConfig());
const [notifications, setNotifications] = useState<ChannelNotifications>([]);
const [quotedMessage, setQuotedMessage] = useState<StreamMessage<StreamChatGenerics>>();
const [channelUnreadUiState, setChannelUnreadUiState] = useState<ChannelUnreadUiState>();
const notificationTimeouts: Array<NodeJS.Timeout> = [];
const [state, dispatch] = useReducer<ChannelStateReducer<StreamChatGenerics>>(
channelReducer,
// channel.initialized === false if client.channel().query() was not called, e.g. ChannelList is not used
// => Channel will call channel.watch() in useLayoutEffect => state.loading is used to signal the watch() call state
{ ...initialState, loading: !channel.initialized },
);
const isMounted = useIsMounted();
const originalTitle = useRef('');
const lastRead = useRef(new Date());
const online = useRef(true);
const channelCapabilitiesArray = channel.data?.own_capabilities as string[];
const throttledCopyStateFromChannel = throttle(
() => dispatch({ channel, type: 'copyStateFromChannelOnEvent' }),
500,
{
leading: true,
trailing: true,
},
);
// eslint-disable-next-line react-hooks/exhaustive-deps
const markRead = useCallback(
throttle(
async (options?: MarkReadWrapperOptions) => {
const { updateChannelUiUnreadState = true } = options ?? {};
if (channel.disconnected || !channelConfig?.read_events) {
return;
}
lastRead.current = new Date();
try {
if (doMarkReadRequest) {
doMarkReadRequest(
channel,
updateChannelUiUnreadState ? setChannelUnreadUiState : undefined,
);
} else {
const markReadResponse = await channel.markRead();
if (updateChannelUiUnreadState && markReadResponse) {
setChannelUnreadUiState({
last_read: lastRead.current,
last_read_message_id: markReadResponse.event.last_read_message_id,
unread_messages: 0,
});
}
}
if (activeUnreadHandler) {
activeUnreadHandler(0, originalTitle.current);
} else if (originalTitle.current) {
document.title = originalTitle.current;
}
} catch (e) {
console.error(t<string>('Failed to mark channel as read'));
}
},
500,
{ leading: true, trailing: false },
),
[activeUnreadHandler, channel, channelConfig, doMarkReadRequest, t],
);
const handleEvent = async (event: Event<StreamChatGenerics>) => {
if (event.message) {
dispatch({
channel,
message: event.message,
type: 'updateThreadOnEvent',
});
}
if (event.type === 'user.watching.start' || event.type === 'user.watching.stop') return;
if (event.type === 'typing.start' || event.type === 'typing.stop') {
return dispatch({ channel, type: 'setTyping' });
}
if (event.type === 'connection.changed' && typeof event.online === 'boolean') {
online.current = event.online;
}
if (event.type === 'message.new') {
let mainChannelUpdated = true;
if (event.message?.parent_id && !event.message?.show_in_channel) {
mainChannelUpdated = false;
}
if (mainChannelUpdated) {
if (document.hidden && channelConfig?.read_events && !channel.muteStatus().muted) {
const unread = channel.countUnread(lastRead.current);
if (activeUnreadHandler) {
activeUnreadHandler(unread, originalTitle.current);
} else {
document.title = `(${unread}) ${originalTitle.current}`;
}
}
}
if (
event.message?.user?.id === client.userID &&
event?.message?.created_at &&
event?.message?.cid
) {
const messageDate = new Date(event.message.created_at);
const cid = event.message.cid;
if (
!latestMessageDatesByChannels[cid] ||
latestMessageDatesByChannels[cid].getTime() < messageDate.getTime()
) {
latestMessageDatesByChannels[cid] = messageDate;
}
}
}
if (event.type === 'user.deleted') {
const oldestID = channel.state?.messages?.[0]?.id;
/**
* As the channel state is not normalized we re-fetch the channel data. Thus, we avoid having to search for user references in the channel state.
*/
// FIXME: we should use channelQueryOptions if they are available
await channel.query({
messages: { id_lt: oldestID, limit: DEFAULT_NEXT_CHANNEL_PAGE_SIZE },
watchers: { limit: DEFAULT_NEXT_CHANNEL_PAGE_SIZE },
});
}
if (event.type === 'notification.mark_unread')
setChannelUnreadUiState((prev) => {
if (!(event.last_read_at && event.user)) return prev;
return {
first_unread_message_id: event.first_unread_message_id,
last_read: new Date(event.last_read_at),
last_read_message_id: event.last_read_message_id,
unread_messages: event.unread_messages ?? 0,
};
});
throttledCopyStateFromChannel();
};
// useLayoutEffect here to prevent spinner. Use Suspense when it is available in stable release
useLayoutEffect(() => {
let errored = false;
let done = false;
(async () => {
if (!channel.initialized && initializeOnMount) {
try {
// if active channel has been set without id, we will create a temporary channel id from its member IDs
// to keep track of the /query request in progress. This is the same approach of generating temporary id
// that the JS client uses to keep track of channel in client.activeChannels
const members: string[] = [];
if (!channel.id && channel.data?.members) {
for (const member of channel.data.members) {
let userId: string | undefined;
if (typeof member === 'string') {
userId = member;
} else if (typeof member === 'object') {
const { user, user_id } = member as ChannelMemberResponse<StreamChatGenerics>;
userId = user_id || user?.id;
}
if (userId) {
members.push(userId);
}
}
}
await getChannel({ channel, client, members, options: channelQueryOptions });
const config = channel.getConfig();
setChannelConfig(config);
} catch (e) {
dispatch({ error: e as Error, type: 'setError' });
errored = true;
}
}
done = true;
originalTitle.current = document.title;
if (!errored) {
dispatch({
channel,
hasMore: hasMoreMessagesProbably(
channel.state.messages.length,
channelQueryOptions?.messages?.limit ?? DEFAULT_INITIAL_CHANNEL_PAGE_SIZE,
),
type: 'initStateFromChannel',
});
if (client.user?.id && channel.state.read[client.user.id]) {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const { user, ...ownReadState } = channel.state.read[client.user.id];
setChannelUnreadUiState(ownReadState);
}
/**
* TODO: maybe pass last_read to the countUnread method to get proper value
* combined with channel.countUnread adjustment (_countMessageAsUnread)
* to allow counting own messages too
*
* const lastRead = channel.state.read[client.userID as string].last_read;
*/
if (channel.countUnread() > 0 && markReadOnMount)
markRead({ updateChannelUiUnreadState: false });
// The more complex sync logic is done in Chat
client.on('connection.changed', handleEvent);
client.on('connection.recovered', handleEvent);
client.on('user.updated', handleEvent);
client.on('user.deleted', handleEvent);
channel.on(handleEvent);
}
})();
return () => {
if (errored || !done) return;
channel?.off(handleEvent);
client.off('connection.changed', handleEvent);
client.off('connection.recovered', handleEvent);
client.off('user.updated', handleEvent);
client.off('user.deleted', handleEvent);
notificationTimeouts.forEach(clearTimeout);
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [
channel.cid,
channelQueryOptions,
doMarkReadRequest,
channelConfig?.read_events,
initializeOnMount,
]);
useEffect(() => {
if (!state.thread) return;
const message = state.messages?.find((m) => m.id === state.thread?.id);
if (message) dispatch({ message, type: 'setThread' });
}, [state.messages, state.thread]);
/** MESSAGE */
// Adds a temporary notification to message list, will be removed after 5 seconds
const addNotification = makeAddNotifications(setNotifications, notificationTimeouts);
// eslint-disable-next-line react-hooks/exhaustive-deps
const loadMoreFinished = useCallback(
debounce(
(hasMore: boolean, messages: ChannelState<StreamChatGenerics>['messages']) => {
if (!isMounted.current) return;
dispatch({ hasMore, messages, type: 'loadMoreFinished' });
},
2000,
{ leading: true, trailing: true },
),
[],
);
const loadMore = async (limit = DEFAULT_NEXT_CHANNEL_PAGE_SIZE) => {
if (!online.current || !window.navigator.onLine || !state.hasMore) return 0;
// prevent duplicate loading events...
const oldestMessage = state?.messages?.[0];
if (state.loadingMore || state.loadingMoreNewer || oldestMessage?.status !== 'received') {
return 0;
}
dispatch({ loadingMore: true, type: 'setLoadingMore' });
const oldestID = oldestMessage?.id;
const perPage = limit;
let queryResponse: ChannelAPIResponse<StreamChatGenerics>;
try {
queryResponse = await channel.query({
messages: { id_lt: oldestID, limit: perPage },
watchers: { limit: perPage },
});
} catch (e) {
console.warn('message pagination request failed with error', e);
dispatch({ loadingMore: false, type: 'setLoadingMore' });
return 0;
}
const hasMoreMessages = queryResponse.messages.length === perPage;
loadMoreFinished(hasMoreMessages, channel.state.messages);
return queryResponse.messages.length;
};
const loadMoreNewer = async (limit = 100) => {
if (!online.current || !window.navigator.onLine || !state.hasMoreNewer) return 0;
const newestMessage = state?.messages?.[state?.messages?.length - 1];
if (state.loadingMore || state.loadingMoreNewer) return 0;
dispatch({ loadingMoreNewer: true, type: 'setLoadingMoreNewer' });
const newestId = newestMessage?.id;
const perPage = limit;
let queryResponse: ChannelAPIResponse<StreamChatGenerics>;
try {
queryResponse = await channel.query({
messages: { id_gt: newestId, limit: perPage },
watchers: { limit: perPage },
});
} catch (e) {
console.warn('message pagination request failed with error', e);
dispatch({ loadingMoreNewer: false, type: 'setLoadingMoreNewer' });
return 0;
}
const hasMoreNewerMessages = channel.state.messages !== channel.state.latestMessages;
dispatch({
hasMoreNewer: hasMoreNewerMessages,
messages: channel.state.messages,
type: 'loadMoreNewerFinished',
});
return queryResponse.messages.length;
};
const clearHighlightedMessageTimeoutId = useRef<ReturnType<typeof setTimeout> | null>(null);
const jumpToMessage = async (messageId: string, messageLimit = 100) => {
dispatch({ loadingMore: true, type: 'setLoadingMore' });
await channel.state.loadMessageIntoState(messageId, undefined, messageLimit);
/**
* if the message we are jumping to has less than half of the page size older messages,
* we have jumped to the beginning of the channel.
*/
const indexOfMessage = channel.state.messages.findIndex((message) => message.id === messageId);
const hasMoreMessages = indexOfMessage >= Math.floor(messageLimit / 2);
loadMoreFinished(hasMoreMessages, channel.state.messages);
dispatch({
hasMoreNewer: channel.state.messages !== channel.state.latestMessages,
highlightedMessageId: messageId,
type: 'jumpToMessageFinished',
});
if (clearHighlightedMessageTimeoutId.current) {
clearTimeout(clearHighlightedMessageTimeoutId.current);
}
clearHighlightedMessageTimeoutId.current = setTimeout(() => {
clearHighlightedMessageTimeoutId.current = null;
dispatch({ type: 'clearHighlightedMessage' });
}, 500);
};
const jumpToLatestMessage = async () => {
await channel.state.loadMessageIntoState('latest');
// FIXME: we cannot rely on constant value 25 as the page size can be customized by integrators
const hasMoreOlder = channel.state.messages.length >= 25;
loadMoreFinished(hasMoreOlder, channel.state.messages);
dispatch({
type: 'jumpToLatestMessage',
});
};
const jumpToFirstUnreadMessage = useCallback(
async (queryMessageLimit = 100) => {
if (!client.user) return;
if (!channelUnreadUiState?.last_read_message_id) {
addNotification(t('Failed to jump to the first unread message'), 'error');
return;
}
let indexOfLastReadMessage;
const currentMessageSet = channel.state.messages;
for (let i = currentMessageSet.length - 1; i >= 0; i--) {
const { id } = currentMessageSet[i];
if (id === channelUnreadUiState.last_read_message_id) {
indexOfLastReadMessage = i;
break;
}
}
if (typeof indexOfLastReadMessage === 'undefined') {
dispatch({ loadingMore: true, type: 'setLoadingMore' });
let hasMoreMessages = true;
try {
await channel.state.loadMessageIntoState(
channelUnreadUiState.last_read_message_id,
undefined,
queryMessageLimit,
);
/**
* if the index of the last read message on the page is beyond the half of the page,
* we have arrived to the oldest page of the channel
*/
indexOfLastReadMessage = channel.state.messages.findIndex(
(message) => message.id === channelUnreadUiState.last_read_message_id,
) as number;
hasMoreMessages = indexOfLastReadMessage >= Math.floor(queryMessageLimit / 2);
} catch (e) {
addNotification(t('Failed to jump to the first unread message'), 'error');
loadMoreFinished(hasMoreMessages, channel.state.messages);
return;
}
loadMoreFinished(hasMoreMessages, channel.state.messages);
}
const firstUnreadMessage = channel.state.messages[indexOfLastReadMessage + 1];
const jumpToMessageId = firstUnreadMessage?.id ?? channelUnreadUiState.last_read_message_id;
dispatch({
hasMoreNewer: channel.state.messages !== channel.state.latestMessages,
highlightedMessageId: jumpToMessageId,
type: 'jumpToMessageFinished',
});
if (clearHighlightedMessageTimeoutId.current) {
clearTimeout(clearHighlightedMessageTimeoutId.current);
}
clearHighlightedMessageTimeoutId.current = setTimeout(() => {
clearHighlightedMessageTimeoutId.current = null;
dispatch({ type: 'clearHighlightedMessage' });
}, 500);
},
[addNotification, channel, client, loadMoreFinished, t, channelUnreadUiState],
);
const deleteMessage = useCallback(
async (
message: StreamMessage<StreamChatGenerics>,
): Promise<MessageResponse<StreamChatGenerics>> => {
if (!message?.id) {
throw new Error('Cannot delete a message - missing message ID.');
}
let deletedMessage;
if (doDeleteMessageRequest) {
deletedMessage = await doDeleteMessageRequest(message);
} else {
const result = await client.deleteMessage(message.id);
deletedMessage = result.message;
}
return deletedMessage;
},
[client, doDeleteMessageRequest],
);
const updateMessage = (
updatedMessage: MessageToSend<StreamChatGenerics> | StreamMessage<StreamChatGenerics>,
) => {
// add the message to the local channel state
channel.state.addMessageSorted(updatedMessage as MessageResponse<StreamChatGenerics>, true);
dispatch({
channel,
parentId: state.thread && updatedMessage.parent_id,
type: 'copyMessagesFromChannel',
});
};
const doSendMessage = async (
message: MessageToSend<StreamChatGenerics> | StreamMessage<StreamChatGenerics>,
customMessageData?: Partial<Message<StreamChatGenerics>>,
options?: SendMessageOptions,
) => {
const { attachments, id, mentioned_users = [], parent_id, text } = message;
// channel.sendMessage expects an array of user id strings
const mentions = isUserResponseArray<StreamChatGenerics>(mentioned_users)
? mentioned_users.map(({ id }) => id)
: mentioned_users;
const messageData = {
attachments,
id,
mentioned_users: mentions,
parent_id,
quoted_message_id: parent_id === quotedMessage?.parent_id ? quotedMessage?.id : undefined,
text,
...customMessageData,
} as Message<StreamChatGenerics>;
try {
let messageResponse: void | SendMessageAPIResponse<StreamChatGenerics>;
if (doSendMessageRequest) {
messageResponse = await doSendMessageRequest(channel, messageData, options);
} else {
messageResponse = await channel.sendMessage(messageData, options);
}
let existingMessage;
for (let i = channel.state.messages.length - 1; i >= 0; i--) {
const msg = channel.state.messages[i];
if (msg.id && msg.id === messageData.id) {
existingMessage = msg;
break;
}
}
const responseTimestamp = new Date(messageResponse?.message?.updated_at || 0).getTime();
const existingMessageTimestamp = existingMessage?.updated_at?.getTime() || 0;
const responseIsTheNewest = responseTimestamp > existingMessageTimestamp;
// Replace the message payload after send is completed
// We need to check for the newest message payload, because on slow network, the response can arrive later than WS events message.new, message.updated.
// Always override existing message in status "sending"
if (
messageResponse?.message &&
(responseIsTheNewest || existingMessage?.status === 'sending')
) {
updateMessage({
...messageResponse.message,
status: 'received',
});
}
if (quotedMessage && parent_id === quotedMessage?.parent_id) setQuotedMessage(undefined);
} catch (error) {
// error response isn't usable so needs to be stringified then parsed
const stringError = JSON.stringify(error);
const parsedError = stringError ? JSON.parse(stringError) : {};
updateMessage({
...message,
error: parsedError,
errorStatusCode: (parsedError.status as number) || undefined,
status: 'failed',
});
}
};
const sendMessage = async (
{
attachments = [],
mentioned_users = [],
parent,
text = '',
}: MessageToSend<StreamChatGenerics>,
customMessageData?: Partial<Message<StreamChatGenerics>>,
options?: SendMessageOptions,
) => {
channel.state.filterErrorMessages();
const messagePreview = {
__html: text,
attachments,
created_at: new Date(),
html: text,
id: customMessageData?.id ?? `${client.userID}-${nanoid()}`,
mentioned_users,
reactions: [],
status: 'sending',
text,
type: 'regular',
user: client.user,
...(parent?.id ? { parent_id: parent.id } : null),
};
updateMessage(messagePreview);
await doSendMessage(messagePreview, customMessageData, options);
};
const retrySendMessage = async (message: StreamMessage<StreamChatGenerics>) => {
updateMessage({
...message,
errorStatusCode: undefined,
status: 'sending',
});
if (message.attachments) {
// remove scraped attachments added during the message composition in MessageInput to prevent sync issues
message.attachments = message.attachments.filter((attachment) => !attachment.og_scrape_url);
}
await doSendMessage(message);
};
const removeMessage = (message: StreamMessage<StreamChatGenerics>) => {
channel.state.removeMessage(message);
dispatch({
channel,
parentId: state.thread && message.parent_id,
type: 'copyMessagesFromChannel',
});
};
/** THREAD */
const openThread = (
message: StreamMessage<StreamChatGenerics>,
event?: React.BaseSyntheticEvent,
) => {
event?.preventDefault();
setQuotedMessage((current) => {
if (current?.parent_id !== message?.parent_id) {
return undefined;
} else {
return current;