-
Notifications
You must be signed in to change notification settings - Fork 297
Expand file tree
/
Copy pathChannel.tsx
More file actions
1401 lines (1313 loc) Β· 47.5 KB
/
Channel.tsx
File metadata and controls
1401 lines (1313 loc) Β· 47.5 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
import type { ComponentProps, PropsWithChildren } from 'react';
import React, {
useCallback,
useEffect,
useLayoutEffect,
useMemo,
useReducer,
useRef,
useState,
} from 'react';
import clsx from 'clsx';
import debounce from 'lodash.debounce';
import defaultsDeep from 'lodash.defaultsdeep';
import throttle from 'lodash.throttle';
import type {
APIErrorResponse,
ChannelAPIResponse,
ChannelMemberResponse,
ChannelQueryOptions,
ChannelState,
DeleteMessageOptions,
ErrorFromResponse,
Event,
EventAPIResponse,
LocalMessage,
Message,
MessageResponse,
SendMessageAPIResponse,
SendMessageOptions,
Channel as StreamChannel,
StreamChat,
UpdateMessageOptions,
} from 'stream-chat';
import { localMessageToNewMessagePayload } from 'stream-chat';
import { initialState, makeChannelReducer } from './channelState';
import { useCreateChannelStateContext } from './hooks/useCreateChannelStateContext';
import { useCreateTypingContext } from './hooks/useCreateTypingContext';
import { useEditMessageHandler } from './hooks/useEditMessageHandler';
import { useIsMounted } from './hooks/useIsMounted';
import type { OnMentionAction } from './hooks/useMentionsHandlers';
import { useMentionsHandlers } from './hooks/useMentionsHandlers';
import type { LoadingErrorIndicatorProps } from '../Loading';
import {
LoadingErrorIndicator as DefaultLoadingErrorIndicator,
LoadingChannel as DefaultLoadingIndicator,
} from '../Loading';
import type {
ChannelActionContextValue,
ChannelNotifications,
ComponentContextValue,
MarkReadWrapperOptions,
} from '../../context';
import {
ChannelActionProvider,
ChannelStateProvider,
TypingProvider,
useChatContext,
useTranslationContext,
WithComponents,
} from '../../context';
import { CHANNEL_CONTAINER_ID } from './constants';
import {
DEFAULT_HIGHLIGHT_DURATION,
DEFAULT_INITIAL_CHANNEL_PAGE_SIZE,
DEFAULT_JUMP_TO_PAGE_SIZE,
DEFAULT_NEXT_CHANNEL_PAGE_SIZE,
DEFAULT_THREAD_PAGE_SIZE,
} from '../../constants/limits';
import { hasMoreMessagesProbably } from '../MessageList';
import {
getChatContainerClass,
useChannelContainerClasses,
useImageFlagEmojisOnWindowsClass,
} from './hooks/useChannelContainerClasses';
import { findInMsgSetByDate, findInMsgSetById, makeAddNotifications } from './utils';
import { useThreadContext } from '../Threads';
import { getChannel } from '../../utils';
import type {
// ChannelUnreadUiState,
GiphyVersions,
ImageAttachmentSizeHandler,
VideoAttachmentSizeHandler,
} from '../../types/types';
import {
getImageAttachmentConfiguration,
getVideoAttachmentConfiguration,
} from '../Attachment/attachment-sizing';
import { useSearchFocusedMessage } from '../../experimental/Search/hooks';
import { WithAudioPlayback } from '../AudioPlayback';
type ChannelPropsForwardedToComponentContext = Pick<
ComponentContextValue,
| 'Attachment'
| 'AttachmentPreviewList'
| 'AttachmentSelector'
| 'AttachmentSelectorInitiationButtonContents'
| 'AudioRecorder'
| 'AutocompleteSuggestionItem'
| 'AutocompleteSuggestionList'
| 'Avatar'
| 'BaseImage'
| 'CooldownTimer'
| 'CustomMessageActionsList'
| 'DateSeparator'
| 'EditMessageInput'
| 'EditMessageModal'
| 'EmojiPicker'
| 'emojiSearchIndex'
| 'EmptyStateIndicator'
| 'FileUploadIcon'
| 'GiphyPreviewMessage'
| 'HeaderComponent'
| 'Input'
| 'LinkPreviewList'
| 'LoadingIndicator'
| 'ShareLocationDialog'
| 'Message'
| 'MessageActions'
| 'MessageBouncePrompt'
| 'MessageBlocked'
| 'MessageDeleted'
| 'MessageIsThreadReplyInChannelButtonIndicator'
| 'MessageListNotifications'
| 'MessageListMainPanel'
| 'MessageNotification'
| 'MessageOptions'
| 'MessageRepliesCountButton'
| 'MessageStatus'
| 'MessageSystem'
| 'MessageTimestamp'
| 'Modal'
| 'ModalGallery'
| 'PinIndicator'
| 'PollActions'
| 'PollContent'
| 'PollCreationDialog'
| 'PollHeader'
| 'PollOptionSelector'
| 'QuotedMessage'
| 'QuotedMessagePreview'
| 'QuotedPoll'
| 'reactionOptions'
| 'ReactionSelector'
| 'ReactionsList'
| 'ReactionsListModal'
| 'ReminderNotification'
| 'SendButton'
| 'SendToChannelCheckbox'
| 'StartRecordingAudioButton'
| 'TextareaComposer'
| 'ThreadHead'
| 'ThreadHeader'
| 'ThreadStart'
| 'Timestamp'
| 'TypingIndicator'
| 'UnreadMessagesNotification'
| 'UnreadMessagesSeparator'
| 'VirtualMessage'
| 'StopAIGenerationButton'
| 'StreamedMessageText'
>;
export type ChannelProps = ChannelPropsForwardedToComponentContext & {
/** Custom handler function that runs when the active channel has unread messages and the app is running on a separate browser tab */
activeUnreadHandler?: (unread: number, documentTitle: string) => void;
/** Allows multiple audio players to play the audio at the same time. Disabled by default. */
allowConcurrentAudioPlayback?: boolean;
/** The connected and active channel */
channel?: StreamChannel;
/**
* 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;
/** Custom action handler to override the default `client.deleteMessage(message.id)` function */
doDeleteMessageRequest?: (
message: LocalMessage,
options?: DeleteMessageOptions,
) => Promise<MessageResponse>;
/** Custom action handler to override the default `channel.markRead` request function (advanced usage only) */
doMarkReadRequest?: (
channel: StreamChannel,
// setChannelUnreadUiState?: (state: ChannelUnreadUiState) => void,
) => Promise<EventAPIResponse> | void;
/** Custom action handler to override the default `channel.sendMessage` request function (advanced usage only) */
doSendMessageRequest?: (
channel: StreamChannel,
message: Message,
options?: SendMessageOptions,
) => ReturnType<StreamChannel['sendMessage']> | void;
/** Custom action handler to override the default `client.updateMessage` request function (advanced usage only) */
doUpdateMessageRequest?: (
cid: string,
updatedMessage: LocalMessage | MessageResponse,
options?: UpdateMessageOptions,
) => ReturnType<StreamChat['updateMessage']>;
/** Custom UI component to be shown if no active channel is set, defaults to null and skips rendering the Channel component */
EmptyPlaceholder?: React.ReactElement;
/** 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;
/** 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>;
/** Configuration parameter to mark the active channel as read when mounted (opened). By default, the channel is marked read on mount. */
markReadOnMount?: boolean;
/** Custom action handler function to run on click of an @mention in a message */
onMentionsClick?: OnMentionAction;
/** Custom action handler function to run on hover of an @mention in a message */
onMentionsHover?: OnMentionAction;
/** 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 ChannelContainer = ({
children,
className: additionalClassName,
...props
}: PropsWithChildren<ComponentProps<'div'>>) => {
const { customClasses, theme } = useChatContext('Channel');
const { channelClass, chatClass } = useChannelContainerClasses({
customClasses,
});
const className = clsx(chatClass, theme, channelClass, additionalClassName);
return (
<div id={CHANNEL_CONTAINER_ID} {...props} className={className}>
{children}
</div>
);
};
const UnMemoizedChannel = (props: PropsWithChildren<ChannelProps>) => {
const {
channel: propsChannel,
EmptyPlaceholder = null,
LoadingErrorIndicator,
LoadingIndicator = DefaultLoadingIndicator,
} = props;
const { channel: contextChannel, channelsQueryState } = useChatContext('Channel');
const channel = propsChannel || contextChannel;
if (channelsQueryState.queryInProgress === 'reload' && LoadingIndicator) {
return (
<ChannelContainer>
<LoadingIndicator />
</ChannelContainer>
);
}
if (channelsQueryState.error && LoadingErrorIndicator) {
return (
<ChannelContainer>
<LoadingErrorIndicator error={channelsQueryState.error} />
</ChannelContainer>
);
}
if (!channel?.cid) {
return <ChannelContainer>{EmptyPlaceholder}</ChannelContainer>;
}
return <ChannelInner {...props} channel={channel} key={channel.cid} />;
};
const ChannelInner = (
props: PropsWithChildren<
ChannelProps & {
channel: StreamChannel;
key: string;
}
>,
) => {
const {
activeUnreadHandler,
allowConcurrentAudioPlayback,
channel,
channelQueryOptions: propChannelQueryOptions,
children,
doDeleteMessageRequest,
doMarkReadRequest,
doSendMessageRequest,
doUpdateMessageRequest,
initializeOnMount = true,
LoadingErrorIndicator = DefaultLoadingErrorIndicator,
LoadingIndicator = DefaultLoadingIndicator,
markReadOnMount = true,
onMentionsClick,
onMentionsHover,
skipMessageDataMemoization,
} = props;
const channelQueryOptions: ChannelQueryOptions & {
messages: { limit: number };
} = useMemo(
() =>
defaultsDeep(propChannelQueryOptions, {
messages: { limit: DEFAULT_INITIAL_CHANNEL_PAGE_SIZE },
}),
[propChannelQueryOptions],
);
const { client, customClasses, latestMessageDatesByChannels, mutes, searchController } =
useChatContext('Channel');
const { t } = useTranslationContext('Channel');
const chatContainerClass = getChatContainerClass(customClasses?.chatContainer);
const windowsEmojiClass = useImageFlagEmojisOnWindowsClass();
const thread = useThreadContext();
const [channelConfig, setChannelConfig] = useState(channel.getConfig());
const [notifications, setNotifications] = useState<ChannelNotifications>([]);
const notificationTimeouts = useRef<Array<NodeJS.Timeout>>([]);
// const [channelUnreadUiState, _setChannelUnreadUiState] =
// useState<ChannelUnreadUiState>();
// const channelReducer = useMemo(() => makeChannelReducer(), []);
// const [state, dispatch] = useReducer(
// 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,
// hasMore: channel.state.messagePagination.hasPrev,
// loading: !channel.initialized,
// messages: channel.state.messages,
// },
// );
const jumpToMessageFromSearch = useSearchFocusedMessage();
const isMounted = useIsMounted();
const originalTitle = useRef('');
const lastRead = useRef<Date | undefined>(undefined);
const online = useRef(true);
const clearHighlightedMessageTimeoutId = useRef<ReturnType<typeof setTimeout> | null>(
null,
);
const channelCapabilitiesArray = channel.data?.own_capabilities as string[];
// const throttledCopyStateFromChannel = throttle(
// () => dispatch({ channel, type: 'copyStateFromChannelOnEvent' }),
// 500,
// {
// leading: true,
// trailing: true,
// },
// );
// const setChannelUnreadUiState = useMemo(
// () =>
// throttle(_setChannelUnreadUiState, 200, {
// leading: true,
// trailing: false,
// }),
// [],
// );
const markRead = useMemo(
() =>
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();
// markReadResponse.event can be null in case of a user that is not a member of a channel being marked read
// in that case event is null and we should not set unread UI
if (updateChannelUiUnreadState && markReadResponse?.event) {
channel.messagePaginator.unreadStateSnapshot.next({
firstUnreadMessageId: null,
lastReadAt: lastRead.current,
lastReadMessageId: markReadResponse.event.last_read_message_id ?? null,
unreadCount: 0,
});
}
}
if (activeUnreadHandler) {
activeUnreadHandler(0, originalTitle.current);
} else if (originalTitle.current) {
document.title = originalTitle.current;
}
} catch (e) {
console.error(t('Failed to mark channel as read'));
}
},
500,
{ leading: true, trailing: false },
),
[
activeUnreadHandler,
channel,
channelConfig,
doMarkReadRequest,
// setChannelUnreadUiState,
t,
],
);
const handleEvent = async (event: Event) => {
if (event.message) {
// dispatch({
// channel,
// message: event.message,
// type: 'updateThreadOnEvent',
// });
}
// ignore the event if it is not targeted at the current channel.
// Event targeted at this channel or globally targeted event should lead to state refresh
if (event.type === 'user.messages.deleted' && event.cid && event.cid !== channel.cid)
return;
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') {
const mainChannelUpdated =
!event.message?.parent_id || event.message?.show_in_channel;
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,
// };
// });
// if (event.type === 'channel.truncated' && event.cid === channel.cid) {
// _setChannelUnreadUiState(undefined);
// }
// 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;
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: channel.state.messagePagination.hasPrev,
// 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);
client.on('user.messages.deleted', handleEvent);
channel.on(handleEvent);
}
})();
const notificationTimeoutsRef = notificationTimeouts.current;
return () => {
if (errored || !done) return;
channel?.off(handleEvent);
client.off('connection.changed', handleEvent);
client.off('connection.recovered', handleEvent);
client.off('user.deleted', handleEvent);
notificationTimeoutsRef.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]);
const handleHighlightedMessageChange = useCallback(
({
highlightDuration,
highlightedMessageId,
}: {
highlightedMessageId: string;
highlightDuration?: number;
}) => {
// dispatch({
// channel,
// highlightedMessageId,
// type: 'jumpToMessageFinished',
// });
if (clearHighlightedMessageTimeoutId.current) {
clearTimeout(clearHighlightedMessageTimeoutId.current);
}
clearHighlightedMessageTimeoutId.current = setTimeout(() => {
if (searchController._internalState.getLatestValue().focusedMessage) {
searchController._internalState.partialNext({ focusedMessage: undefined });
}
clearHighlightedMessageTimeoutId.current = null;
// dispatch({ type: 'clearHighlightedMessage' });
}, highlightDuration ?? DEFAULT_HIGHLIGHT_DURATION);
},
[searchController._internalState],
);
useEffect(() => {
if (!jumpToMessageFromSearch?.id) return;
handleHighlightedMessageChange({ highlightedMessageId: jumpToMessageFromSearch.id });
}, [jumpToMessageFromSearch, handleHighlightedMessageChange]);
/** MESSAGE */
// Adds a temporary notification to message list, will be removed after 5 seconds
const addNotification = useMemo(
() => makeAddNotifications(setNotifications, notificationTimeouts.current),
[],
);
// const loadMoreFinished = useCallback(
// debounce(
// (hasMore: boolean, messages: ChannelState['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 ||
// !channel.state.messagePagination.hasPrev
// )
// 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;
//
// 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;
// }
//
// loadMoreFinished(channel.state.messagePagination.hasPrev, channel.state.messages);
//
// return queryResponse.messages.length;
// };
// const loadMoreNewer = async (limit = DEFAULT_NEXT_CHANNEL_PAGE_SIZE) => {
// if (
// !online.current ||
// !window.navigator.onLine ||
// !channel.state.messagePagination.hasNext
// )
// 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;
//
// 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;
// }
//
// dispatch({
// hasMoreNewer: channel.state.messagePagination.hasNext,
// messages: channel.state.messages,
// type: 'loadMoreNewerFinished',
// });
// return queryResponse.messages.length;
// };
// const jumpToMessage: ChannelActionContextValue['jumpToMessage'] = useCallback(
// async (
// messageId,
// messageLimit = DEFAULT_JUMP_TO_PAGE_SIZE,
// highlightDuration = DEFAULT_HIGHLIGHT_DURATION,
// ) => {
// dispatch({ loadingMore: true, type: 'setLoadingMore' });
// await channel.state.loadMessageIntoState(messageId, undefined, messageLimit);
//
// loadMoreFinished(channel.state.messagePagination.hasPrev, channel.state.messages);
// handleHighlightedMessageChange({
// highlightDuration,
// highlightedMessageId: messageId,
// });
// },
// [channel, handleHighlightedMessageChange, loadMoreFinished],
// );
// const jumpToLatestMessage: ChannelActionContextValue['jumpToLatestMessage'] =
// useCallback(async () => {
// await channel.state.loadMessageIntoState('latest');
// loadMoreFinished(channel.state.messagePagination.hasPrev, channel.state.messages);
// dispatch({
// type: 'jumpToLatestMessage',
// });
// }, [channel, loadMoreFinished]);
//
// const jumpToFirstUnreadMessage: ChannelActionContextValue['jumpToFirstUnreadMessage'] =
// useCallback(
// async (
// queryMessageLimit = DEFAULT_JUMP_TO_PAGE_SIZE,
// highlightDuration = DEFAULT_HIGHLIGHT_DURATION,
// ) => {
// if (!channelUnreadUiState?.unread_messages) return;
// let lastReadMessageId = channelUnreadUiState?.last_read_message_id;
// let firstUnreadMessageId = channelUnreadUiState?.first_unread_message_id;
// let isInCurrentMessageSet = false;
//
// if (firstUnreadMessageId) {
// const result = findInMsgSetById(firstUnreadMessageId, channel.state.messages);
// isInCurrentMessageSet = result.index !== -1;
// } else if (lastReadMessageId) {
// const result = findInMsgSetById(lastReadMessageId, channel.state.messages);
// isInCurrentMessageSet = !!result.target;
// firstUnreadMessageId =
// result.index > -1 ? channel.state.messages[result.index + 1]?.id : undefined;
// } else {
// const lastReadTimestamp = channelUnreadUiState.last_read.getTime();
// const { index: lastReadMessageIndex, target: lastReadMessage } =
// findInMsgSetByDate(
// channelUnreadUiState.last_read,
// channel.state.messages,
// true,
// );
//
// if (lastReadMessage) {
// firstUnreadMessageId = channel.state.messages[lastReadMessageIndex + 1]?.id;
// isInCurrentMessageSet = !!firstUnreadMessageId;
// lastReadMessageId = lastReadMessage.id;
// } else {
// dispatch({ loadingMore: true, type: 'setLoadingMore' });
// let messages;
// try {
// messages = (
// await channel.query(
// {
// messages: {
// created_at_around: channelUnreadUiState.last_read.toISOString(),
// limit: queryMessageLimit,
// },
// },
// 'new',
// )
// ).messages;
// } catch (e) {
// addNotification(t('Failed to jump to the first unread message'), 'error');
// loadMoreFinished(
// channel.state.messagePagination.hasPrev,
// channel.state.messages,
// );
// return;
// }
//
// const firstMessageWithCreationDate = messages.find((msg) => msg.created_at);
// if (!firstMessageWithCreationDate) {
// addNotification(t('Failed to jump to the first unread message'), 'error');
// loadMoreFinished(
// channel.state.messagePagination.hasPrev,
// channel.state.messages,
// );
// return;
// }
// const firstMessageTimestamp = new Date(
// firstMessageWithCreationDate.created_at as string,
// ).getTime();
// if (lastReadTimestamp < firstMessageTimestamp) {
// // whole channel is unread
// firstUnreadMessageId = firstMessageWithCreationDate.id;
// } else {
// const result = findInMsgSetByDate(channelUnreadUiState.last_read, messages);
// lastReadMessageId = result.target?.id;
// }
// loadMoreFinished(
// channel.state.messagePagination.hasPrev,
// channel.state.messages,
// );
// }
// }
//
// if (!firstUnreadMessageId && !lastReadMessageId) {
// addNotification(t('Failed to jump to the first unread message'), 'error');
// return;
// }
//
// if (!isInCurrentMessageSet) {
// dispatch({ loadingMore: true, type: 'setLoadingMore' });
// try {
// const targetId = (firstUnreadMessageId ?? lastReadMessageId) as string;
// await channel.state.loadMessageIntoState(
// targetId,
// 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
// */
// const indexOfTarget = channel.state.messages.findIndex(
// (message) => message.id === targetId,
// ) as number;
// loadMoreFinished(
// channel.state.messagePagination.hasPrev,
// channel.state.messages,
// );
// firstUnreadMessageId =
// firstUnreadMessageId ?? channel.state.messages[indexOfTarget + 1]?.id;
// } catch (e) {
// addNotification(t('Failed to jump to the first unread message'), 'error');
// loadMoreFinished(
// channel.state.messagePagination.hasPrev,
// channel.state.messages,
// );
// return;
// }
// }
//
// if (!firstUnreadMessageId) {
// addNotification(t('Failed to jump to the first unread message'), 'error');
// return;
// }
// if (!channelUnreadUiState.first_unread_message_id)
// _setChannelUnreadUiState({
// ...channelUnreadUiState,
// first_unread_message_id: firstUnreadMessageId,
// last_read_message_id: lastReadMessageId,
// });
// handleHighlightedMessageChange({
// highlightDuration,
// highlightedMessageId: firstUnreadMessageId,
// });
// },
// [
// addNotification,
// channel,
// handleHighlightedMessageChange,
// loadMoreFinished,
// t,
// channelUnreadUiState,
// ],
// );
const deleteMessage = useCallback(
async (
message: LocalMessage,
options?: DeleteMessageOptions,
): Promise<MessageResponse> => {
if (!message?.id) {
throw new Error('Cannot delete a message - missing message ID.');
}
let deletedMessage;
if (doDeleteMessageRequest) {
deletedMessage = await doDeleteMessageRequest(message, options);
} else {
const result = await client.deleteMessage(message.id, options);
deletedMessage = result.message;
}
return deletedMessage;
},
[client, doDeleteMessageRequest],
);
const updateMessage = (updatedMessage: MessageResponse | LocalMessage) => {
// add the message to the local channel state
channel.state.addMessageSorted(updatedMessage, true);
// dispatch({
// channel,
// parentId: state.thread && updatedMessage.parent_id,
// type: 'copyMessagesFromChannel',
// });
};
// const doSendMessage = async ({
// localMessage,
// message,
// options,
// }: {
// localMessage: LocalMessage;
// message: Message;
// options?: SendMessageOptions;
// }) => {
// try {
// let messageResponse: void | SendMessageAPIResponse;
//
// if (doSendMessageRequest) {
// messageResponse = await doSendMessageRequest(channel, message, options);
// } else {
// messageResponse = await channel.sendMessage(message, options);
// }
//
// let existingMessage: LocalMessage | undefined = undefined;
// for (let i = channel.state.messages.length - 1; i >= 0; i--) {
// const msg = channel.state.messages[i];
// if (msg.id && msg.id === message.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',
// });
// }
// } catch (error) {
// // error response isn't usable so needs to be stringified then parsed
// const stringError = JSON.stringify(error);
// const parsedError = (