-
Notifications
You must be signed in to change notification settings - Fork 373
Expand file tree
/
Copy pathMessageFlashList.tsx
More file actions
1355 lines (1208 loc) · 44 KB
/
MessageFlashList.tsx
File metadata and controls
1355 lines (1208 loc) · 44 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 React, { PropsWithChildren, useCallback, useEffect, useMemo, useRef, useState } from 'react';
import {
LayoutChangeEvent,
ScrollViewProps,
StyleSheet,
View,
ViewabilityConfig,
ViewToken,
} from 'react-native';
import Animated from 'react-native-reanimated';
import type { FlashListProps, FlashListRef } from '@shopify/flash-list';
import type { Channel, Event, LocalMessage, MessageResponse } from 'stream-chat';
import { useMessageList } from './hooks/useMessageList';
import { useShouldScrollToRecentOnNewOwnMessage } from './hooks/useShouldScrollToRecentOnNewOwnMessage';
import { useTypingUsers } from './hooks/useTypingUsers';
import { InlineLoadingMoreIndicator } from './InlineLoadingMoreIndicator';
import { InlineLoadingMoreRecentIndicator } from './InlineLoadingMoreRecentIndicator';
import { InlineLoadingMoreRecentThreadIndicator } from './InlineLoadingMoreRecentThreadIndicator';
import {
AttachmentPickerContextValue,
useAttachmentPickerContext,
} from '../../contexts/attachmentPickerContext/AttachmentPickerContext';
import {
ChannelContextValue,
useChannelContext,
} from '../../contexts/channelContext/ChannelContext';
import { ChatContextValue, useChatContext } from '../../contexts/chatContext/ChatContext';
import {
MessageInputContextValue,
useMessageInputContext,
} from '../../contexts/messageInputContext/MessageInputContext';
import {
MessageListItemContextValue,
MessageListItemProvider,
} from '../../contexts/messageListItemContext/MessageListItemContext';
import {
MessagesContextValue,
useMessagesContext,
} from '../../contexts/messagesContext/MessagesContext';
import {
OwnCapabilitiesContextValue,
useOwnCapabilitiesContext,
} from '../../contexts/ownCapabilitiesContext/OwnCapabilitiesContext';
import {
PaginatedMessageListContextValue,
usePaginatedMessageListContext,
} from '../../contexts/paginatedMessageListContext/PaginatedMessageListContext';
import { mergeThemes, useTheme } from '../../contexts/themeContext/ThemeContext';
import { ThreadContextValue, useThreadContext } from '../../contexts/threadContext/ThreadContext';
import { useStableCallback, useStateStore } from '../../hooks';
import { bumpOverlayLayoutRevision } from '../../state-store';
import { MessageInputHeightState } from '../../state-store/message-input-height-store';
import { primitives } from '../../theme';
import { transitions } from '../../utils/transitions';
import { MessageWrapper } from '../Message/MessageItemView/MessageWrapper';
type FlashListContextApi = { getRef?: () => FlashListRef<LocalMessage> | null } | undefined;
let FlashList;
let useFlashListContext: () => FlashListContextApi = () => undefined;
try {
const flashListModule = require('@shopify/flash-list');
FlashList = flashListModule.FlashList;
useFlashListContext = flashListModule.useFlashListContext;
} catch {
FlashList = undefined;
}
const keyExtractor = (item: LocalMessage) => {
if (item.id) {
return item.id;
}
if (item.created_at) {
return typeof item.created_at === 'string' ? item.created_at : item.created_at.toISOString();
}
return Date.now().toString();
};
const flatListViewabilityConfig: ViewabilityConfig = {
viewAreaCoveragePercentThreshold: 1,
};
const hasReadLastMessage = (channel: Channel, userId: string) => {
const latestMessageIdInChannel =
channel.state.latestMessages[channel.state.latestMessages.length - 1]?.id;
const lastReadMessageIdServer = channel.state.read[userId]?.last_read_message_id;
return latestMessageIdInChannel === lastReadMessageIdServer;
};
const getPreviousLastMessage = (messages: LocalMessage[], newMessage?: MessageResponse) => {
if (!newMessage) return;
let previousLastMessage;
for (let i = messages.length - 1; i >= 0; i--) {
const msg = messages[i];
if (!msg?.id) break;
if (msg.id !== newMessage.id) {
previousLastMessage = msg;
break;
}
}
return previousLastMessage;
};
const messageInputHeightStoreSelector = (state: MessageInputHeightState) => ({
height: state.height,
});
type MessageFlashListPropsWithContext = Pick<
AttachmentPickerContextValue,
'closePicker' | 'attachmentPickerStore'
> &
Pick<OwnCapabilitiesContextValue, 'readEvents'> &
Pick<
ChannelContextValue,
| 'channel'
| 'channelUnreadStateStore'
| 'disabled'
| 'EmptyStateIndicator'
| 'hideStickyDateHeader'
| 'highlightedMessageId'
| 'loadChannelAroundMessage'
| 'loading'
| 'LoadingIndicator'
| 'markRead'
| 'NetworkDownIndicator'
| 'reloadChannel'
| 'scrollToFirstUnreadThreshold'
| 'setChannelUnreadState'
| 'setTargetedMessage'
| 'StickyHeader'
| 'targetedMessage'
| 'threadList'
| 'maximumMessageLimit'
> &
Pick<ChatContextValue, 'client'> &
Pick<MessageInputContextValue, 'messageInputFloating' | 'messageInputHeightStore'> &
Pick<PaginatedMessageListContextValue, 'loadMore' | 'loadMoreRecent'> &
Pick<
MessagesContextValue,
| 'DateHeader'
| 'disableTypingIndicator'
| 'FlatList'
| 'InlineDateSeparator'
| 'InlineUnreadIndicator'
| 'Message'
| 'ScrollToBottomButton'
| 'MessageSystem'
| 'myMessageTheme'
| 'shouldShowUnreadUnderlay'
| 'TypingIndicator'
| 'TypingIndicatorContainer'
| 'UnreadMessagesNotification'
> &
Pick<
ThreadContextValue,
'loadMoreRecentThread' | 'loadMoreThread' | 'thread' | 'threadInstance'
> & {
/**
* Besides existing (default) UX behavior of underlying FlatList of MessageList component, if you want
* to attach some additional props to underlying FlatList, you can add it to following prop.
*
* You can find list of all the available FlatList props here - https://facebook.github.io/react-native/docs/flatlist#props
*
* **NOTE** Don't use `additionalFlatListProps` to get access to ref of flatlist. Use `setFlatListRef` instead.
*
* e.g.
* ```js
* <MessageList
* additionalFlatListProps={{ bounces: true, keyboardDismissMode: true }} />
* ```
*/
additionalFlashListProps?: Partial<FlashListProps<LocalMessage>>;
/**
* UI component for footer of message list. By default message list will use `InlineLoadingMoreIndicator`
* as FooterComponent. If you want to implement your own inline loading indicator, you can access `loadingMore`
* from context.
*
* This is a [ListHeaderComponent](https://facebook.github.io/react-native/docs/flatlist#listheadercomponent) of FlatList
* used in MessageList. Should be used for header by default if inverted is true or defaulted
*/
FooterComponent?: React.ComponentType;
/**
* UI component for header of message list. By default message list will use `InlineLoadingMoreRecentIndicator`
* as HeaderComponent. If you want to implement your own inline loading indicator, you can access `loadingMoreRecent`
* from context.
*
* This is a [ListFooterComponent](https://facebook.github.io/react-native/docs/flatlist#listheadercomponent) of FlatList
* used in MessageList. Should be used for header if inverted is false
*/
HeaderComponent?: React.ComponentType;
/** Whether or not the FlatList is inverted. Defaults to true */
inverted?: boolean;
/** Turn off grouping of messages by user */
noGroupByUser?: boolean;
onListScroll?: ScrollViewProps['onScroll'];
/**
* Handler to open the thread on message. This is callback for touch event for replies button.
*
* @param message A message object to open the thread upon.
*/
onThreadSelect?: (message: ThreadContextValue['thread']) => void;
/**
* Use `setFlatListRef` to get access to ref to inner FlatList.
*
* e.g.
* ```js
* <MessageList
* setFlatListRef={(ref) => {
* // Use ref for your own good
* }}
* ```
*/
setFlatListRef?: (ref: FlashListRef<LocalMessage> | null) => void;
/**
* If true, the message list will be used in a live-streaming scenario.
* This flag is used to make sure that the auto scroll behaves well, if multiple messages are received.
*
* This flag is experimental and is subject to change. Please test thoroughly before using it.
*
* @experimental
*/
isLiveStreaming?: boolean;
};
const WAIT_FOR_SCROLL_TIMEOUT = 0;
const getItemTypeInternal = (message: LocalMessage) => {
if (message.type === 'regular') {
if ((message.attachments?.length ?? 0) > 0) {
return 'message-with-attachments';
}
if (message.poll_id) {
return 'message-with-poll';
}
if (message.quoted_message_id) {
return 'message-with-quote';
}
if (message.shared_location) {
return 'message-with-shared-location';
}
if (message.text) {
return 'message-with-text';
}
return 'message-with-nothing';
}
if (message.type === 'deleted') {
return 'deleted-message';
}
if (message.type === 'system') {
return 'system-message';
}
return 'generic-message';
};
const MessageFlashListWithContext = (props: MessageFlashListPropsWithContext) => {
const LoadingMoreRecentIndicator = props.threadList
? InlineLoadingMoreRecentThreadIndicator
: InlineLoadingMoreRecentIndicator;
const {
attachmentPickerStore,
additionalFlashListProps,
channel,
channelUnreadStateStore,
client,
closePicker,
DateHeader,
disabled,
disableTypingIndicator,
EmptyStateIndicator,
// FlatList,
FooterComponent,
HeaderComponent = InlineLoadingMoreIndicator,
hideStickyDateHeader,
isLiveStreaming = false,
loadChannelAroundMessage,
loading,
LoadingIndicator,
loadMore,
loadMoreRecent,
loadMoreRecentThread,
loadMoreThread,
markRead,
maximumMessageLimit,
messageInputFloating,
messageInputHeightStore,
myMessageTheme,
readEvents,
NetworkDownIndicator,
noGroupByUser,
onListScroll,
onThreadSelect,
reloadChannel,
ScrollToBottomButton,
setChannelUnreadState,
setFlatListRef,
setTargetedMessage,
StickyHeader,
targetedMessage,
thread,
threadInstance,
threadList = false,
TypingIndicator,
TypingIndicatorContainer,
UnreadMessagesNotification,
} = props;
const flashListRef = useRef<FlashListRef<LocalMessage> | null>(null);
const { height: messageInputHeight } = useStateStore(
messageInputHeightStore.store,
messageInputHeightStoreSelector,
);
const [hasMoved, setHasMoved] = useState(false);
const [scrollToBottomButtonVisible, setScrollToBottomButtonVisible] = useState(false);
const [isUnreadNotificationOpen, setIsUnreadNotificationOpen] = useState<boolean>(false);
const [stickyHeaderDate, setStickyHeaderDate] = useState<Date | undefined>();
const [scrollEnabled, setScrollEnabled] = useState<boolean>(true);
const stickyHeaderDateRef = useRef<Date | undefined>(undefined);
/**
* We want to call onEndReached and onStartReached only once, per content length.
* We keep track of calls to these functions per content length, with following trackers.
*/
const onStartReachedTracker = useRef<Record<number, boolean>>({});
const onEndReachedTracker = useRef<Record<number, boolean>>({});
const onStartReachedInPromise = useRef<Promise<void> | null>(null);
const onEndReachedInPromise = useRef<Promise<void> | null>(null);
/**
* The timeout id used to debounce our scrollToIndex calls on messageList updates
*/
const scrollToDebounceTimeoutRef = useRef<ReturnType<typeof setTimeout>>(undefined);
const channelResyncScrollSet = useRef<boolean>(true);
const { theme } = useTheme();
const styles = useStyles();
const myMessageThemeString = useMemo(() => JSON.stringify(myMessageTheme), [myMessageTheme]);
const modifiedTheme = useMemo(
() => mergeThemes({ style: myMessageTheme, theme }),
// eslint-disable-next-line react-hooks/exhaustive-deps
[myMessageThemeString, theme],
);
const { processedMessageList, rawMessageList, viewabilityChangedCallback } = useMessageList({
isFlashList: true,
isLiveStreaming,
threadList,
});
const renderItem = useCallback(
({ item: message, index }: { item: LocalMessage; index: number }) => {
const previousMessage = processedMessageList[index - 1];
const nextMessage = processedMessageList[index + 1];
return (
<MessageWrapper
message={message}
previousMessage={previousMessage}
nextMessage={nextMessage}
/>
);
},
[processedMessageList],
);
/**
* We need topMessage and channelLastRead values to set the initial scroll position.
* So these values only get used if `initialScrollToFirstUnreadMessage` prop is true.
*/
const topMessageBeforeUpdate = useRef<LocalMessage>(undefined);
const topMessageAfterUpdate: LocalMessage | undefined = rawMessageList[0];
const latestNonCurrentMessageBeforeUpdateRef = useRef<LocalMessage>(undefined);
const messageListLengthBeforeUpdate = useRef(0);
const messageListLengthAfterUpdate = processedMessageList.length;
const shouldScrollToRecentOnNewOwnMessageRef = useShouldScrollToRecentOnNewOwnMessage(
rawMessageList,
client.userID,
);
const [autoscrollToRecent, setAutoscrollToRecent] = useState(true);
useEffect(() => {
if (autoscrollToRecent && flashListRef.current) {
flashListRef.current.scrollToEnd({
animated: true,
});
}
}, [autoscrollToRecent]);
const maintainVisibleContentPosition = useMemo(() => {
return {
animateAutoscrollToBottom: true,
autoscrollToBottomThreshold: autoscrollToRecent ? 1 : undefined,
startRenderingFromBottom: true,
};
}, [autoscrollToRecent]);
useEffect(() => {
if (disabled) {
setScrollToBottomButtonVisible(false);
}
}, [disabled]);
const indexToScrollToRef = useRef<number | undefined>(undefined);
const initialIndexToScrollTo = useMemo(() => {
return targetedMessage
? processedMessageList.findIndex((message) => message?.id === targetedMessage)
: -1;
}, [processedMessageList, targetedMessage]);
useEffect(() => {
indexToScrollToRef.current = initialIndexToScrollTo;
}, [initialIndexToScrollTo]);
/**
* Check if a messageId needs to be scrolled to after list loads, and scroll to it
* Note: This effect fires on every list change with a small debounce so that scrolling isnt abrupted by an immediate rerender
*/
useEffect(() => {
if (!targetedMessage) {
return;
}
const indexOfParentInMessageList = processedMessageList.findIndex(
(message) => message?.id === targetedMessage,
);
// the message we want to scroll to has not been loaded in the state yet
if (indexOfParentInMessageList === -1) {
loadChannelAroundMessage({ messageId: targetedMessage, setTargetedMessage });
} else {
scrollToDebounceTimeoutRef.current = setTimeout(() => {
clearTimeout(scrollToDebounceTimeoutRef.current);
// now scroll to it
flashListRef.current?.scrollToIndex({
animated: true,
index: indexOfParentInMessageList,
viewPosition: 0.5,
});
setTargetedMessage(undefined);
}, WAIT_FOR_SCROLL_TIMEOUT);
}
}, [loadChannelAroundMessage, processedMessageList, setTargetedMessage, targetedMessage]);
const goToMessage = useStableCallback(async (messageId: string) => {
const indexOfParentInMessageList = processedMessageList.findIndex(
(message) => message?.id === messageId,
);
indexToScrollToRef.current = indexOfParentInMessageList;
try {
if (indexOfParentInMessageList === -1) {
clearTimeout(scrollToDebounceTimeoutRef.current);
await loadChannelAroundMessage({ messageId, setTargetedMessage });
} else {
setTargetedMessage(messageId);
}
} catch (e) {
console.warn('Error while scrolling to message', e);
}
});
useEffect(() => {
/**
* Condition to check if a message is removed from MessageList.
* Eg: This would happen when giphy search is cancelled, message is deleted with visibility "never" etc.
* If such a case arises, we scroll to bottom.
*/
const isMessageRemovedFromMessageList =
messageListLengthBeforeUpdate.current - messageListLengthAfterUpdate === 1;
/**
* Scroll down when
* created_at timestamp of top message before update is lesser than created_at timestamp of top message after update - channel has resynced
*/
const scrollToBottomIfNeeded = () => {
if (!client || !channel || processedMessageList.length === 0) {
return;
}
if (
isMessageRemovedFromMessageList ||
(topMessageBeforeUpdate.current?.created_at &&
topMessageAfterUpdate?.created_at &&
topMessageBeforeUpdate.current.created_at < topMessageAfterUpdate.created_at)
) {
channelResyncScrollSet.current = false;
setScrollToBottomButtonVisible(false);
resetPaginationTrackersRef.current();
setTimeout(() => {
channelResyncScrollSet.current = true;
if (channel.countUnread() > 0) {
markRead();
}
}, WAIT_FOR_SCROLL_TIMEOUT);
}
};
if (isMessageRemovedFromMessageList && !maximumMessageLimit) {
scrollToBottomIfNeeded();
}
messageListLengthBeforeUpdate.current = messageListLengthAfterUpdate;
topMessageBeforeUpdate.current = topMessageAfterUpdate;
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [messageListLengthAfterUpdate, topMessageAfterUpdate?.id, maximumMessageLimit]);
useEffect(() => {
if (!processedMessageList.length) {
return;
}
const notLatestSet = channel.state.messages !== channel.state.latestMessages;
if (notLatestSet) {
latestNonCurrentMessageBeforeUpdateRef.current =
channel.state.latestMessages[channel.state.latestMessages.length - 1];
setAutoscrollToRecent(false);
setScrollToBottomButtonVisible(true);
return;
} else {
indexToScrollToRef.current = undefined;
setAutoscrollToRecent(true);
}
const latestNonCurrentMessageBeforeUpdate = latestNonCurrentMessageBeforeUpdateRef.current;
latestNonCurrentMessageBeforeUpdateRef.current = undefined;
const latestCurrentMessageAfterUpdate = processedMessageList[processedMessageList.length - 1];
if (!latestCurrentMessageAfterUpdate) {
return;
}
const didMergeMessageSetsWithNoUpdates =
latestNonCurrentMessageBeforeUpdate?.id === latestCurrentMessageAfterUpdate.id;
if (!didMergeMessageSetsWithNoUpdates) {
const shouldScrollToRecentOnNewOwnMessage = shouldScrollToRecentOnNewOwnMessageRef.current();
// we should scroll to bottom where ever we are now
// as we have sent a new own message
if (shouldScrollToRecentOnNewOwnMessage) {
flashListRef.current?.scrollToEnd({
animated: true,
});
}
}
}, [channel, processedMessageList, shouldScrollToRecentOnNewOwnMessageRef, threadList]);
/**
* Effect to mark the channel as read when the user scrolls to the bottom of the message list.
*/
useEffect(() => {
const shouldMarkRead = () => {
const channelUnreadState = channelUnreadStateStore.channelUnreadState;
return (
!channelUnreadState?.first_unread_message_id &&
!scrollToBottomButtonVisible &&
client.user?.id &&
!hasReadLastMessage(channel, client.user?.id)
);
};
const handleEvent = async (event: Event) => {
const mainChannelUpdated = !event.message?.parent_id || event.message?.show_in_channel;
const isMyOwnMessage = event.message?.user?.id === client.user?.id;
const channelUnreadState = channelUnreadStateStore.channelUnreadState;
// When the scrollToBottomButtonVisible is true, we need to manually update the channelUnreadState when its a received message.
if (
(scrollToBottomButtonVisible || channelUnreadState?.first_unread_message_id) &&
!isMyOwnMessage
) {
const previousUnreadCount = channelUnreadState?.unread_messages ?? 0;
const previousLastMessage = getPreviousLastMessage(channel.state.messages, event.message);
setChannelUnreadState({
...channelUnreadState,
last_read:
channelUnreadState?.last_read ??
(previousUnreadCount === 0 && previousLastMessage?.created_at
? new Date(previousLastMessage.created_at)
: new Date(0)), // not having information about the last read message means the whole channel is unread,
unread_messages: previousUnreadCount + 1,
});
} else if (mainChannelUpdated && shouldMarkRead()) {
await markRead();
}
};
const listener: ReturnType<typeof channel.on> = channel.on('message.new', handleEvent);
return () => {
listener?.unsubscribe();
};
}, [
channel,
channelUnreadStateStore,
client.user?.id,
markRead,
scrollToBottomButtonVisible,
setChannelUnreadState,
threadList,
]);
const updateStickyHeaderDateIfNeeded = useStableCallback((viewableItems: ViewToken[]) => {
if (!viewableItems.length) {
return;
}
const lastItem = viewableItems[0];
if (!lastItem) return;
if (
!channel.state.messagePagination.hasPrev &&
processedMessageList[0].id === lastItem.item.id
) {
setStickyHeaderDate(undefined);
return;
}
const isMessageTypeDeleted = lastItem.item.type === 'deleted';
if (
lastItem?.item?.created_at &&
!isMessageTypeDeleted &&
typeof lastItem.item.created_at !== 'string' &&
lastItem.item.created_at.toDateString() !== stickyHeaderDateRef.current?.toDateString()
) {
stickyHeaderDateRef.current = lastItem.item.created_at;
setStickyHeaderDate(lastItem.item.created_at);
}
});
/**
* This function should show or hide the unread indicator depending on the
*/
const updateStickyUnreadIndicator = useStableCallback((viewableItems: ViewToken[]) => {
const channelUnreadState = channelUnreadStateStore.channelUnreadState;
// we need this check to make sure that regular list change do not trigger
// the unread notification to appear (for example if the old last read messages
// go out of the viewport).
const lastReadMessageId = channelUnreadState?.last_read_message_id;
const lastReadMessageVisible = viewableItems.some((item) => item.item.id === lastReadMessageId);
if (
!viewableItems.length ||
!readEvents ||
lastReadMessageVisible ||
attachmentPickerStore.state.getLatestValue().selectedPicker === 'images'
) {
setIsUnreadNotificationOpen(false);
return;
}
const lastItem = viewableItems[0];
if (!lastItem) return;
const lastItemMessage = lastItem.item;
const lastItemCreatedAt = lastItemMessage.created_at;
const unreadIndicatorDate = channelUnreadState?.last_read?.getTime();
const lastItemDate = lastItemCreatedAt.getTime();
if (
!channel.state.messagePagination.hasPrev &&
processedMessageList[0].id === lastItemMessage.id
) {
setIsUnreadNotificationOpen(false);
return;
}
/**
* This is a special case where there is a single long message by the sender.
* When a message is sent, we mark it as read before it actually has a `created_at` timestamp.
* This is a workaround to prevent the unread indicator from showing when the message is sent.
*/
if (
viewableItems.length === 1 &&
channel.countUnread() === 0 &&
lastItemMessage.user.id === client.userID
) {
setIsUnreadNotificationOpen(false);
return;
}
if (unreadIndicatorDate && lastItemDate > unreadIndicatorDate) {
setIsUnreadNotificationOpen(true);
} else {
setIsUnreadNotificationOpen(false);
}
});
/**
* FlatList doesn't accept changeable function for onViewableItemsChanged prop.
* Thus useRef.
*/
const unstableOnViewableItemsChanged = ({
viewableItems,
}: {
viewableItems: ViewToken[] | undefined;
}) => {
if (!viewableItems) {
return;
}
viewabilityChangedCallback({ inverted: false, viewableItems });
if (!hideStickyDateHeader) {
updateStickyHeaderDateIfNeeded(viewableItems);
}
updateStickyUnreadIndicator(viewableItems);
};
const onViewableItemsChanged = useRef(unstableOnViewableItemsChanged);
onViewableItemsChanged.current = unstableOnViewableItemsChanged;
const stableOnViewableItemsChanged = useCallback(
({ viewableItems }: { viewableItems: ViewToken[] | undefined }) => {
onViewableItemsChanged.current({ viewableItems });
},
[],
);
const setNativeScrollability = useStableCallback((value: boolean) => {
// FlashList does not have setNativeProps exposed, hence we cannot use that.
// Instead, we resort to state.
setScrollEnabled(value);
});
const messageListItemContextValue: MessageListItemContextValue = useMemo(
() => ({
goToMessage,
modifiedTheme,
noGroupByUser,
onThreadSelect,
setNativeScrollability,
}),
[goToMessage, modifiedTheme, noGroupByUser, onThreadSelect, setNativeScrollability],
);
/**
* We are keeping full control on message pagination, and not relying on react-native for it.
* The reasons being,
* 1. FlatList doesn't support onStartReached prop
* 2. `onEndReached` function prop available on react-native, gets executed
* once per content length (and thats actually a nice optimization strategy).
* But it also means, we always need to prioritize onEndReached above our
* logic for `onStartReached`.
* 3. `onEndReachedThreshold` prop decides - at which scroll position to call `onEndReached`.
* Its a factor of content length (which is necessary for "real" infinite scroll). But on
* the other hand, it also makes calls to `onEndReached` (and this `channel.query`) way
* too early during scroll, which we don't really need. So we are going to instead
* keep some fixed offset distance, to decide when to call `loadMore` or `loadMoreRecent`.
*
* We are still gonna keep the optimization, which react-native does - only call onEndReached
* once per content length.
*/
/**
* 1. Makes a call to `loadMore` function, which queries more older messages.
* 2. Ensures that we call `loadMore`, once per content length
* 3. If the call to `loadMoreRecent` is in progress, we wait for it to finish to make sure scroll doesn't jump.
*/
const maybeCallOnStartReached = useStableCallback(async () => {
// If onEndReached has already been called for given messageList length, then ignore.
if (
processedMessageList?.length &&
onStartReachedTracker.current[processedMessageList.length]
) {
return;
}
if (processedMessageList?.length) {
onStartReachedTracker.current[processedMessageList.length] = true;
}
const callback = () => {
onStartReachedInPromise.current = null;
return Promise.resolve();
};
const onError = () => {
/** Release the onEndReachedTracker trigger after 2 seconds, to try again */
setTimeout(() => {
onStartReachedTracker.current = {};
}, 2000);
};
// If onStartReached is in progress, better to wait for it to finish for smooth UX
if (onEndReachedInPromise.current) {
await onEndReachedInPromise.current;
}
onStartReachedInPromise.current = (
threadList && !!threadInstance && loadMoreRecentThread
? loadMoreRecentThread({})
: loadMoreRecent()
)
.then(callback)
.catch(onError);
});
/**
* 1. Makes a call to `loadMoreRecent` function, which queries more recent messages.
* 2. Ensures that we call `loadMoreRecent`, once per content length
* 3. If the call to `loadMore` is in progress, we wait for it to finish to make sure scroll doesn't jump.
*/
const maybeCallOnEndReached = useStableCallback(async () => {
// If onStartReached has already been called for given data length, then ignore.
if (processedMessageList?.length && onEndReachedTracker.current[processedMessageList.length]) {
return;
}
if (processedMessageList?.length) {
onEndReachedTracker.current[processedMessageList.length] = true;
}
const callback = () => {
onEndReachedInPromise.current = null;
return Promise.resolve();
};
const onError = () => {
/** Release the onStartReached trigger after 2 seconds, to try again */
setTimeout(() => {
onEndReachedTracker.current = {};
}, 2000);
};
// If onEndReached is in progress, better to wait for it to finish for smooth UX
if (onStartReachedInPromise.current) {
await onStartReachedInPromise.current;
}
onEndReachedInPromise.current = (threadList ? loadMoreThread() : loadMore())
.then(callback)
.catch(onError);
});
const onUserScrollEvent: NonNullable<ScrollViewProps['onScroll']> = useStableCallback((event) => {
const nativeEvent = event.nativeEvent;
const offset = nativeEvent.contentOffset.y;
const visibleLength = nativeEvent.layoutMeasurement.height;
const contentLength = nativeEvent.contentSize.height;
if (!channel || !channelResyncScrollSet.current) {
return;
}
// Check if scroll has reached either start of end of list.
const isScrollAtEnd = offset < 100;
const isScrollAtStart = contentLength - visibleLength - offset < 100;
if (isScrollAtEnd) {
maybeCallOnEndReached();
}
if (isScrollAtStart) {
maybeCallOnStartReached();
}
});
/**
* Resets the pagination trackers, doing so cancels currently scheduled loading more calls
*/
const resetPaginationTrackersRef = useRef(() => {
onStartReachedTracker.current = {};
onEndReachedTracker.current = {};
});
const currentScrollOffsetRef = useRef(0);
const handleScroll: ScrollViewProps['onScroll'] = useStableCallback((event) => {
const messageListHasMessages = processedMessageList.length > 0;
const nativeEvent = event.nativeEvent;
const offset = nativeEvent.contentOffset.y;
currentScrollOffsetRef.current = offset;
const visibleLength = nativeEvent.layoutMeasurement.height;
const contentLength = nativeEvent.contentSize.height;
const isScrollAtStart = contentLength - visibleLength - offset < messageInputHeight;
const notLatestSet = channel.state.messages !== channel.state.latestMessages;
const showScrollToBottomButton =
messageListHasMessages && ((!threadList && notLatestSet) || !isScrollAtStart);
/**
* 1. If I scroll up -> show scrollToBottom button.
* 2. If I scroll to bottom of screen
* |-> hide scrollToBottom button.
* |-> if channel is unread, call markRead().
*/
setScrollToBottomButtonVisible(showScrollToBottomButton);
if (onListScroll) {
onListScroll(event);
}
});
const goToNewMessages = useStableCallback(async () => {
const isNotLatestSet = channel.state.messages !== channel.state.latestMessages;
if (isNotLatestSet) {
resetPaginationTrackersRef.current();
await reloadChannel();
} else if (flashListRef.current) {
flashListRef.current.scrollToEnd({
animated: true,
});
}
setScrollToBottomButtonVisible(false);
/**
* When we are not in the bottom of the list, and we receive new messages, we need to mark the channel as read.
We would still need to show the unread label, where the first unread message appeared so we don't update the channelUnreadState.
*/
await markRead({
updateChannelUnreadState: false,
});
});
const dismissImagePicker = useStableCallback(() => {
if (attachmentPickerStore.state.getLatestValue().selectedPicker) {
attachmentPickerStore.setSelectedPicker(undefined);
closePicker();
}
});
const onScrollBeginDrag: ScrollViewProps['onScrollBeginDrag'] = useStableCallback((event) => {
!hasMoved && attachmentPickerStore.state.getLatestValue().selectedPicker && setHasMoved(true);
onUserScrollEvent(event);
});
const onScrollEndDrag: ScrollViewProps['onScrollEndDrag'] = useStableCallback((event) => {
hasMoved && attachmentPickerStore.state.getLatestValue().selectedPicker && setHasMoved(false);
onUserScrollEvent(event);
});
const refCallback = useStableCallback((ref: FlashListRef<LocalMessage>) => {
flashListRef.current = ref;
if (setFlatListRef) {
setFlatListRef(ref);
}
});
const onUnreadNotificationClose = useStableCallback(async () => {
await markRead();
setIsUnreadNotificationOpen(false);
});
// We need to omit the style related props from the additionalFlatListProps and add them directly instead of spreading
let additionalFlashListPropsExcludingStyle:
| Omit<NonNullable<typeof additionalFlashListProps>, 'style' | 'contentContainerStyle'>
| undefined;
if (additionalFlashListProps) {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const { contentContainerStyle, style, ...rest } = additionalFlashListProps;
additionalFlashListPropsExcludingStyle = rest;
}
const flatListStyle = useMemo(
() => [styles.listContainer, additionalFlashListProps?.style],
[additionalFlashListProps?.style, styles.listContainer],
);
const flatListContentContainerStyle = useMemo(
() => [
styles.contentContainer,
{ paddingBottom: messageInputFloating ? messageInputHeight : 0 },
additionalFlashListProps?.contentContainerStyle,
],
[
additionalFlashListProps?.contentContainerStyle,
styles.contentContainer,
messageInputFloating,
messageInputHeight,
],
);
const currentListHeightRef = useRef<number | undefined>(undefined);
const onLayout = useStableCallback((e: LayoutChangeEvent) => {
const { height } = e.nativeEvent.layout;