stream-chat-react-native-core 8.5.2 → 8.6.0-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. package/lib/commonjs/components/MessageList/MessageFlashList.js +877 -0
  2. package/lib/commonjs/components/MessageList/MessageFlashList.js.map +1 -0
  3. package/lib/commonjs/components/MessageList/MessageList.js +6 -8
  4. package/lib/commonjs/components/MessageList/MessageList.js.map +1 -1
  5. package/lib/commonjs/components/MessageList/hooks/useMessageList.js +8 -3
  6. package/lib/commonjs/components/MessageList/hooks/useMessageList.js.map +1 -1
  7. package/lib/commonjs/components/MessageList/hooks/useShouldScrollToRecentOnNewOwnMessage.js +1 -1
  8. package/lib/commonjs/components/MessageList/hooks/useShouldScrollToRecentOnNewOwnMessage.js.map +1 -1
  9. package/lib/commonjs/components/MessageList/utils/getLastReceivedMessageFlashList.js +15 -0
  10. package/lib/commonjs/components/MessageList/utils/getLastReceivedMessageFlashList.js.map +1 -0
  11. package/lib/commonjs/components/MessageMenu/MessageUserReactions.js +4 -4
  12. package/lib/commonjs/components/MessageMenu/MessageUserReactions.js.map +1 -1
  13. package/lib/commonjs/components/MessageMenu/hooks/useFetchReactions.js +28 -24
  14. package/lib/commonjs/components/MessageMenu/hooks/useFetchReactions.js.map +1 -1
  15. package/lib/commonjs/components/Thread/Thread.js +12 -1
  16. package/lib/commonjs/components/Thread/Thread.js.map +1 -1
  17. package/lib/commonjs/components/index.js +11 -0
  18. package/lib/commonjs/components/index.js.map +1 -1
  19. package/lib/commonjs/version.json +1 -1
  20. package/lib/module/components/MessageList/MessageFlashList.js +877 -0
  21. package/lib/module/components/MessageList/MessageFlashList.js.map +1 -0
  22. package/lib/module/components/MessageList/MessageList.js +6 -8
  23. package/lib/module/components/MessageList/MessageList.js.map +1 -1
  24. package/lib/module/components/MessageList/hooks/useMessageList.js +8 -3
  25. package/lib/module/components/MessageList/hooks/useMessageList.js.map +1 -1
  26. package/lib/module/components/MessageList/hooks/useShouldScrollToRecentOnNewOwnMessage.js +1 -1
  27. package/lib/module/components/MessageList/hooks/useShouldScrollToRecentOnNewOwnMessage.js.map +1 -1
  28. package/lib/module/components/MessageList/utils/getLastReceivedMessageFlashList.js +15 -0
  29. package/lib/module/components/MessageList/utils/getLastReceivedMessageFlashList.js.map +1 -0
  30. package/lib/module/components/MessageMenu/MessageUserReactions.js +4 -4
  31. package/lib/module/components/MessageMenu/MessageUserReactions.js.map +1 -1
  32. package/lib/module/components/MessageMenu/hooks/useFetchReactions.js +28 -24
  33. package/lib/module/components/MessageMenu/hooks/useFetchReactions.js.map +1 -1
  34. package/lib/module/components/Thread/Thread.js +12 -1
  35. package/lib/module/components/Thread/Thread.js.map +1 -1
  36. package/lib/module/components/index.js +11 -0
  37. package/lib/module/components/index.js.map +1 -1
  38. package/lib/module/version.json +1 -1
  39. package/lib/typescript/components/MessageList/MessageFlashList.d.ts +81 -0
  40. package/lib/typescript/components/MessageList/MessageFlashList.d.ts.map +1 -0
  41. package/lib/typescript/components/MessageList/MessageList.d.ts +2 -1
  42. package/lib/typescript/components/MessageList/MessageList.d.ts.map +1 -1
  43. package/lib/typescript/components/MessageList/hooks/useMessageList.d.ts +1 -0
  44. package/lib/typescript/components/MessageList/hooks/useMessageList.d.ts.map +1 -1
  45. package/lib/typescript/components/MessageList/utils/getLastReceivedMessageFlashList.d.ts +3 -0
  46. package/lib/typescript/components/MessageList/utils/getLastReceivedMessageFlashList.d.ts.map +1 -0
  47. package/lib/typescript/components/MessageMenu/MessageUserReactions.d.ts.map +1 -1
  48. package/lib/typescript/components/MessageMenu/hooks/useFetchReactions.d.ts.map +1 -1
  49. package/lib/typescript/components/Thread/Thread.d.ts +9 -1
  50. package/lib/typescript/components/Thread/Thread.d.ts.map +1 -1
  51. package/lib/typescript/components/index.d.ts +1 -0
  52. package/lib/typescript/components/index.d.ts.map +1 -1
  53. package/package.json +7 -1
  54. package/src/components/MessageList/MessageFlashList.tsx +1319 -0
  55. package/src/components/MessageList/MessageList.tsx +9 -6
  56. package/src/components/MessageList/hooks/useMessageList.ts +8 -3
  57. package/src/components/MessageList/hooks/useShouldScrollToRecentOnNewOwnMessage.ts +1 -1
  58. package/src/components/MessageList/utils/getLastReceivedMessageFlashList.ts +20 -0
  59. package/src/components/MessageMenu/MessageUserReactions.tsx +13 -9
  60. package/src/components/MessageMenu/hooks/useFetchReactions.ts +27 -24
  61. package/src/components/Thread/Thread.tsx +31 -6
  62. package/src/components/index.ts +1 -0
  63. package/src/version.json +1 -1
@@ -0,0 +1,1319 @@
1
+ import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
2
+ import {
3
+ LayoutChangeEvent,
4
+ ScrollViewProps,
5
+ StyleSheet,
6
+ View,
7
+ ViewabilityConfig,
8
+ ViewToken,
9
+ } from 'react-native';
10
+
11
+ import type { FlashListProps, FlashListRef } from '@shopify/flash-list';
12
+ import type { Channel, Event, LocalMessage, MessageResponse } from 'stream-chat';
13
+
14
+ import { useMessageList } from './hooks/useMessageList';
15
+ import { useShouldScrollToRecentOnNewOwnMessage } from './hooks/useShouldScrollToRecentOnNewOwnMessage';
16
+ import { InlineLoadingMoreIndicator } from './InlineLoadingMoreIndicator';
17
+ import { InlineLoadingMoreRecentIndicator } from './InlineLoadingMoreRecentIndicator';
18
+ import { InlineLoadingMoreRecentThreadIndicator } from './InlineLoadingMoreRecentThreadIndicator';
19
+
20
+ import { getLastReceivedMessageFlashList } from './utils/getLastReceivedMessageFlashList';
21
+
22
+ import {
23
+ AttachmentPickerContextValue,
24
+ useAttachmentPickerContext,
25
+ } from '../../contexts/attachmentPickerContext/AttachmentPickerContext';
26
+ import {
27
+ ChannelContextValue,
28
+ useChannelContext,
29
+ } from '../../contexts/channelContext/ChannelContext';
30
+ import { ChatContextValue, useChatContext } from '../../contexts/chatContext/ChatContext';
31
+ import {
32
+ ImageGalleryContextValue,
33
+ useImageGalleryContext,
34
+ } from '../../contexts/imageGalleryContext/ImageGalleryContext';
35
+ import {
36
+ MessagesContextValue,
37
+ useMessagesContext,
38
+ } from '../../contexts/messagesContext/MessagesContext';
39
+ import {
40
+ OwnCapabilitiesContextValue,
41
+ useOwnCapabilitiesContext,
42
+ } from '../../contexts/ownCapabilitiesContext/OwnCapabilitiesContext';
43
+ import {
44
+ PaginatedMessageListContextValue,
45
+ usePaginatedMessageListContext,
46
+ } from '../../contexts/paginatedMessageListContext/PaginatedMessageListContext';
47
+ import { mergeThemes, ThemeProvider, useTheme } from '../../contexts/themeContext/ThemeContext';
48
+ import { ThreadContextValue, useThreadContext } from '../../contexts/threadContext/ThreadContext';
49
+
50
+ import { useStableCallback } from '../../hooks';
51
+ import { FileTypes } from '../../types/types';
52
+
53
+ let FlashList;
54
+
55
+ try {
56
+ FlashList = require('@shopify/flash-list').FlashList;
57
+ } catch {
58
+ FlashList = undefined;
59
+ }
60
+
61
+ const keyExtractor = (item: LocalMessage) => {
62
+ if (item.id) {
63
+ return item.id;
64
+ }
65
+ if (item.created_at) {
66
+ return typeof item.created_at === 'string' ? item.created_at : item.created_at.toISOString();
67
+ }
68
+ return Date.now().toString();
69
+ };
70
+
71
+ const flatListViewabilityConfig: ViewabilityConfig = {
72
+ viewAreaCoveragePercentThreshold: 1,
73
+ };
74
+
75
+ const hasReadLastMessage = (channel: Channel, userId: string) => {
76
+ const latestMessageIdInChannel =
77
+ channel.state.latestMessages[channel.state.latestMessages.length - 1]?.id;
78
+ const lastReadMessageIdServer = channel.state.read[userId]?.last_read_message_id;
79
+ return latestMessageIdInChannel === lastReadMessageIdServer;
80
+ };
81
+
82
+ const getPreviousLastMessage = (messages: LocalMessage[], newMessage?: MessageResponse) => {
83
+ if (!newMessage) return;
84
+ let previousLastMessage;
85
+ for (let i = messages.length - 1; i >= 0; i--) {
86
+ const msg = messages[i];
87
+ if (!msg?.id) break;
88
+ if (msg.id !== newMessage.id) {
89
+ previousLastMessage = msg;
90
+ break;
91
+ }
92
+ }
93
+ return previousLastMessage;
94
+ };
95
+
96
+ type MessageFlashListPropsWithContext = Pick<
97
+ AttachmentPickerContextValue,
98
+ 'closePicker' | 'selectedPicker' | 'setSelectedPicker'
99
+ > &
100
+ Pick<OwnCapabilitiesContextValue, 'readEvents'> &
101
+ Pick<
102
+ ChannelContextValue,
103
+ | 'channel'
104
+ | 'channelUnreadState'
105
+ | 'disabled'
106
+ | 'EmptyStateIndicator'
107
+ | 'hideStickyDateHeader'
108
+ | 'highlightedMessageId'
109
+ | 'loadChannelAroundMessage'
110
+ | 'loading'
111
+ | 'LoadingIndicator'
112
+ | 'markRead'
113
+ | 'NetworkDownIndicator'
114
+ | 'reloadChannel'
115
+ | 'scrollToFirstUnreadThreshold'
116
+ | 'setChannelUnreadState'
117
+ | 'setTargetedMessage'
118
+ | 'StickyHeader'
119
+ | 'targetedMessage'
120
+ | 'threadList'
121
+ > &
122
+ Pick<ChatContextValue, 'client'> &
123
+ Pick<ImageGalleryContextValue, 'setMessages'> &
124
+ Pick<PaginatedMessageListContextValue, 'loadMore' | 'loadMoreRecent'> &
125
+ Pick<
126
+ MessagesContextValue,
127
+ | 'DateHeader'
128
+ | 'disableTypingIndicator'
129
+ | 'FlatList'
130
+ | 'InlineDateSeparator'
131
+ | 'InlineUnreadIndicator'
132
+ | 'legacyImageViewerSwipeBehaviour'
133
+ | 'Message'
134
+ | 'ScrollToBottomButton'
135
+ | 'MessageSystem'
136
+ | 'myMessageTheme'
137
+ | 'shouldShowUnreadUnderlay'
138
+ | 'TypingIndicator'
139
+ | 'TypingIndicatorContainer'
140
+ | 'UnreadMessagesNotification'
141
+ > &
142
+ Pick<
143
+ ThreadContextValue,
144
+ 'loadMoreRecentThread' | 'loadMoreThread' | 'thread' | 'threadInstance'
145
+ > & {
146
+ /**
147
+ * Besides existing (default) UX behavior of underlying FlatList of MessageList component, if you want
148
+ * to attach some additional props to underlying FlatList, you can add it to following prop.
149
+ *
150
+ * You can find list of all the available FlatList props here - https://facebook.github.io/react-native/docs/flatlist#props
151
+ *
152
+ * **NOTE** Don't use `additionalFlatListProps` to get access to ref of flatlist. Use `setFlatListRef` instead.
153
+ *
154
+ * e.g.
155
+ * ```js
156
+ * <MessageList
157
+ * additionalFlatListProps={{ bounces: true, keyboardDismissMode: true }} />
158
+ * ```
159
+ */
160
+ additionalFlashListProps?: Partial<FlashListProps<LocalMessage>>;
161
+ /**
162
+ * UI component for footer of message list. By default message list will use `InlineLoadingMoreIndicator`
163
+ * as FooterComponent. If you want to implement your own inline loading indicator, you can access `loadingMore`
164
+ * from context.
165
+ *
166
+ * This is a [ListHeaderComponent](https://facebook.github.io/react-native/docs/flatlist#listheadercomponent) of FlatList
167
+ * used in MessageList. Should be used for header by default if inverted is true or defaulted
168
+ */
169
+ FooterComponent?: React.ComponentType;
170
+ /**
171
+ * UI component for header of message list. By default message list will use `InlineLoadingMoreRecentIndicator`
172
+ * as HeaderComponent. If you want to implement your own inline loading indicator, you can access `loadingMoreRecent`
173
+ * from context.
174
+ *
175
+ * This is a [ListFooterComponent](https://facebook.github.io/react-native/docs/flatlist#listheadercomponent) of FlatList
176
+ * used in MessageList. Should be used for header if inverted is false
177
+ */
178
+ HeaderComponent?: React.ComponentType;
179
+ /** Whether or not the FlatList is inverted. Defaults to true */
180
+ inverted?: boolean;
181
+ isListActive?: boolean;
182
+ /** Turn off grouping of messages by user */
183
+ noGroupByUser?: boolean;
184
+ onListScroll?: ScrollViewProps['onScroll'];
185
+ /**
186
+ * Handler to open the thread on message. This is callback for touch event for replies button.
187
+ *
188
+ * @param message A message object to open the thread upon.
189
+ */
190
+ onThreadSelect?: (message: ThreadContextValue['thread']) => void;
191
+ /**
192
+ * Use `setFlatListRef` to get access to ref to inner FlatList.
193
+ *
194
+ * e.g.
195
+ * ```js
196
+ * <MessageList
197
+ * setFlatListRef={(ref) => {
198
+ * // Use ref for your own good
199
+ * }}
200
+ * ```
201
+ */
202
+ setFlatListRef?: (ref: FlashListRef<LocalMessage> | null) => void;
203
+ };
204
+
205
+ const WAIT_FOR_SCROLL_TIMEOUT = 0;
206
+
207
+ const getItemTypeInternal = (message: LocalMessage) => {
208
+ if (message.type === 'regular') {
209
+ if ((message.attachments?.length ?? 0) > 0) {
210
+ return 'message-with-attachments';
211
+ }
212
+
213
+ if (message.poll_id) {
214
+ return 'message-with-poll';
215
+ }
216
+
217
+ if (message.quoted_message_id) {
218
+ return 'message-with-quote';
219
+ }
220
+
221
+ if (message.shared_location) {
222
+ return 'message-with-shared-location';
223
+ }
224
+
225
+ if (message.text) {
226
+ return 'message-with-text';
227
+ }
228
+
229
+ return 'message-with-nothing';
230
+ }
231
+
232
+ if (message.type === 'deleted') {
233
+ return 'deleted-message';
234
+ }
235
+
236
+ if (message.type === 'system') {
237
+ return 'system-message';
238
+ }
239
+
240
+ return 'generic-message';
241
+ };
242
+
243
+ const MessageFlashListWithContext = (props: MessageFlashListPropsWithContext) => {
244
+ const LoadingMoreRecentIndicator = props.threadList
245
+ ? InlineLoadingMoreRecentThreadIndicator
246
+ : InlineLoadingMoreRecentIndicator;
247
+ const {
248
+ additionalFlashListProps,
249
+ channel,
250
+ channelUnreadState,
251
+ client,
252
+ closePicker,
253
+ DateHeader,
254
+ disabled,
255
+ disableTypingIndicator,
256
+ EmptyStateIndicator,
257
+ // FlatList,
258
+ FooterComponent = LoadingMoreRecentIndicator,
259
+ HeaderComponent = InlineLoadingMoreIndicator,
260
+ hideStickyDateHeader,
261
+ highlightedMessageId,
262
+ InlineDateSeparator,
263
+ InlineUnreadIndicator,
264
+ isListActive = false,
265
+ legacyImageViewerSwipeBehaviour,
266
+ loadChannelAroundMessage,
267
+ loading,
268
+ LoadingIndicator,
269
+ loadMore,
270
+ loadMoreRecent,
271
+ loadMoreRecentThread,
272
+ loadMoreThread,
273
+ markRead,
274
+ Message,
275
+ MessageSystem,
276
+ myMessageTheme,
277
+ readEvents,
278
+ NetworkDownIndicator,
279
+ noGroupByUser,
280
+ onListScroll,
281
+ onThreadSelect,
282
+ reloadChannel,
283
+ ScrollToBottomButton,
284
+ selectedPicker,
285
+ setChannelUnreadState,
286
+ setFlatListRef,
287
+ setMessages,
288
+ setSelectedPicker,
289
+ setTargetedMessage,
290
+ shouldShowUnreadUnderlay,
291
+ StickyHeader,
292
+ targetedMessage,
293
+ thread,
294
+ threadInstance,
295
+ threadList = false,
296
+ TypingIndicator,
297
+ TypingIndicatorContainer,
298
+ UnreadMessagesNotification,
299
+ } = props;
300
+ const flashListRef = useRef<FlashListRef<LocalMessage> | null>(null);
301
+
302
+ const [hasMoved, setHasMoved] = useState(false);
303
+ const [scrollToBottomButtonVisible, setScrollToBottomButtonVisible] = useState(false);
304
+ const [isUnreadNotificationOpen, setIsUnreadNotificationOpen] = useState<boolean>(false);
305
+ const [stickyHeaderDate, setStickyHeaderDate] = useState<Date | undefined>();
306
+ const [autoScrollToRecent, setAutoScrollToRecent] = useState(false);
307
+
308
+ const stickyHeaderDateRef = useRef<Date | undefined>(undefined);
309
+ /**
310
+ * We want to call onEndReached and onStartReached only once, per content length.
311
+ * We keep track of calls to these functions per content length, with following trackers.
312
+ */
313
+ const onStartReachedTracker = useRef<Record<number, boolean>>({});
314
+ const onEndReachedTracker = useRef<Record<number, boolean>>({});
315
+
316
+ const onStartReachedInPromise = useRef<Promise<void> | null>(null);
317
+ const onEndReachedInPromise = useRef<Promise<void> | null>(null);
318
+
319
+ /**
320
+ * The timeout id used to debounce our scrollToIndex calls on messageList updates
321
+ */
322
+ const scrollToDebounceTimeoutRef = useRef<ReturnType<typeof setTimeout>>(undefined);
323
+
324
+ const channelResyncScrollSet = useRef<boolean>(true);
325
+ const { theme } = useTheme();
326
+
327
+ const {
328
+ colors: { white_snow },
329
+ messageList: { container, contentContainer, listContainer },
330
+ } = theme;
331
+
332
+ const myMessageThemeString = useMemo(() => JSON.stringify(myMessageTheme), [myMessageTheme]);
333
+
334
+ const modifiedTheme = useMemo(
335
+ () => mergeThemes({ style: myMessageTheme, theme }),
336
+ // eslint-disable-next-line react-hooks/exhaustive-deps
337
+ [myMessageThemeString, theme],
338
+ );
339
+
340
+ const { dateSeparatorsRef, messageGroupStylesRef, processedMessageList, rawMessageList } =
341
+ useMessageList({
342
+ isFlashList: true,
343
+ noGroupByUser,
344
+ threadList,
345
+ });
346
+
347
+ /**
348
+ * We need topMessage and channelLastRead values to set the initial scroll position.
349
+ * So these values only get used if `initialScrollToFirstUnreadMessage` prop is true.
350
+ */
351
+ const topMessageBeforeUpdate = useRef<LocalMessage>(undefined);
352
+ const topMessageAfterUpdate: LocalMessage | undefined = rawMessageList[0];
353
+
354
+ const latestNonCurrentMessageBeforeUpdateRef = useRef<LocalMessage>(undefined);
355
+
356
+ const messageListLengthBeforeUpdate = useRef(0);
357
+ const messageListLengthAfterUpdate = processedMessageList.length;
358
+
359
+ const shouldScrollToRecentOnNewOwnMessageRef = useShouldScrollToRecentOnNewOwnMessage(
360
+ rawMessageList,
361
+ client.userID,
362
+ );
363
+
364
+ const lastReceivedId = useMemo(
365
+ () => getLastReceivedMessageFlashList(processedMessageList)?.id,
366
+ [processedMessageList],
367
+ );
368
+
369
+ const maintainVisibleContentPosition = useMemo(() => {
370
+ return {
371
+ animateAutoscrollToBottom: true,
372
+ autoscrollToBottomThreshold: autoScrollToRecent || threadList ? 10 : undefined,
373
+ startRenderingFromBottom: true,
374
+ };
375
+ }, [autoScrollToRecent, threadList]);
376
+
377
+ useEffect(() => {
378
+ if (disabled) {
379
+ setScrollToBottomButtonVisible(false);
380
+ }
381
+ }, [disabled]);
382
+
383
+ /**
384
+ * Check if a messageId needs to be scrolled to after list loads, and scroll to it
385
+ * Note: This effect fires on every list change with a small debounce so that scrolling isnt abrupted by an immediate rerender
386
+ */
387
+ useEffect(() => {
388
+ if (!targetedMessage) {
389
+ return;
390
+ }
391
+
392
+ const indexOfParentInMessageList = processedMessageList.findIndex(
393
+ (message) => message?.id === targetedMessage,
394
+ );
395
+
396
+ // the message we want to scroll to has not been loaded in the state yet
397
+ if (indexOfParentInMessageList === -1) {
398
+ loadChannelAroundMessage({ messageId: targetedMessage, setTargetedMessage });
399
+ } else {
400
+ scrollToDebounceTimeoutRef.current = setTimeout(() => {
401
+ clearTimeout(scrollToDebounceTimeoutRef.current);
402
+
403
+ // now scroll to it
404
+ flashListRef.current?.scrollToIndex({
405
+ animated: true,
406
+ index: indexOfParentInMessageList,
407
+ viewPosition: 0.5,
408
+ });
409
+ setTargetedMessage(undefined);
410
+ }, WAIT_FOR_SCROLL_TIMEOUT);
411
+ }
412
+ }, [loadChannelAroundMessage, processedMessageList, setTargetedMessage, targetedMessage]);
413
+
414
+ const goToMessage = useStableCallback(async (messageId: string) => {
415
+ const indexOfParentInMessageList = processedMessageList.findIndex(
416
+ (message) => message?.id === messageId,
417
+ );
418
+ if (indexOfParentInMessageList !== -1) {
419
+ flashListRef.current?.scrollToIndex({
420
+ animated: true,
421
+ index: indexOfParentInMessageList,
422
+ viewPosition: 0.5,
423
+ });
424
+ setTargetedMessage(messageId);
425
+ return;
426
+ }
427
+ try {
428
+ if (indexOfParentInMessageList === -1) {
429
+ clearTimeout(scrollToDebounceTimeoutRef.current);
430
+ await loadChannelAroundMessage({ messageId });
431
+ setTargetedMessage(messageId);
432
+
433
+ // now scroll to it with animated=true
434
+ flashListRef.current?.scrollToIndex({
435
+ animated: true,
436
+ index: indexOfParentInMessageList,
437
+ viewPosition: 0.5, // try to place message in the center of the screen
438
+ });
439
+ return;
440
+ }
441
+ } catch (e) {
442
+ console.warn('Error while scrolling to message', e);
443
+ }
444
+ });
445
+
446
+ useEffect(() => {
447
+ /**
448
+ * Condition to check if a message is removed from MessageList.
449
+ * Eg: This would happen when giphy search is cancelled, message is deleted with visibility "never" etc.
450
+ * If such a case arises, we scroll to bottom.
451
+ */
452
+ const isMessageRemovedFromMessageList =
453
+ messageListLengthBeforeUpdate.current - messageListLengthAfterUpdate === 1;
454
+
455
+ /**
456
+ * Scroll down when
457
+ * created_at timestamp of top message before update is lesser than created_at timestamp of top message after update - channel has resynced
458
+ */
459
+ const scrollToBottomIfNeeded = () => {
460
+ if (!client || !channel || processedMessageList.length === 0) {
461
+ return;
462
+ }
463
+
464
+ if (
465
+ isMessageRemovedFromMessageList ||
466
+ (topMessageBeforeUpdate.current?.created_at &&
467
+ topMessageAfterUpdate?.created_at &&
468
+ topMessageBeforeUpdate.current.created_at < topMessageAfterUpdate.created_at)
469
+ ) {
470
+ channelResyncScrollSet.current = false;
471
+ setScrollToBottomButtonVisible(false);
472
+ resetPaginationTrackersRef.current();
473
+
474
+ setAutoScrollToRecent(true);
475
+ setTimeout(() => {
476
+ channelResyncScrollSet.current = true;
477
+ if (channel.countUnread() > 0) {
478
+ markRead();
479
+ }
480
+ setAutoScrollToRecent(false);
481
+ }, WAIT_FOR_SCROLL_TIMEOUT);
482
+ }
483
+ };
484
+
485
+ if (isMessageRemovedFromMessageList) {
486
+ scrollToBottomIfNeeded();
487
+ }
488
+
489
+ messageListLengthBeforeUpdate.current = messageListLengthAfterUpdate;
490
+ topMessageBeforeUpdate.current = topMessageAfterUpdate;
491
+ // eslint-disable-next-line react-hooks/exhaustive-deps
492
+ }, [messageListLengthAfterUpdate, topMessageAfterUpdate?.id]);
493
+
494
+ useEffect(() => {
495
+ if (!processedMessageList.length) {
496
+ return;
497
+ }
498
+
499
+ const notLatestSet = channel.state.messages !== channel.state.latestMessages;
500
+ if (notLatestSet) {
501
+ latestNonCurrentMessageBeforeUpdateRef.current =
502
+ channel.state.latestMessages[channel.state.latestMessages.length - 1];
503
+ setAutoScrollToRecent(false);
504
+ setScrollToBottomButtonVisible(true);
505
+ return;
506
+ }
507
+ const latestNonCurrentMessageBeforeUpdate = latestNonCurrentMessageBeforeUpdateRef.current;
508
+ latestNonCurrentMessageBeforeUpdateRef.current = undefined;
509
+
510
+ const latestCurrentMessageAfterUpdate = processedMessageList[processedMessageList.length - 1];
511
+ if (!latestCurrentMessageAfterUpdate) {
512
+ setAutoScrollToRecent(true);
513
+ return;
514
+ }
515
+ const didMergeMessageSetsWithNoUpdates =
516
+ latestNonCurrentMessageBeforeUpdate?.id === latestCurrentMessageAfterUpdate.id;
517
+
518
+ if (!didMergeMessageSetsWithNoUpdates) {
519
+ const shouldScrollToRecentOnNewOwnMessage = shouldScrollToRecentOnNewOwnMessageRef.current();
520
+ // we should scroll to bottom where ever we are now
521
+ // as we have sent a new own message
522
+ if (shouldScrollToRecentOnNewOwnMessage) {
523
+ flashListRef.current?.scrollToEnd({
524
+ animated: true,
525
+ });
526
+ }
527
+ }
528
+ }, [channel, processedMessageList, shouldScrollToRecentOnNewOwnMessageRef, threadList]);
529
+
530
+ /**
531
+ * Effect to scroll to the bottom of the message list when a new message is received if the scroll to bottom button is not visible.
532
+ */
533
+ useEffect(() => {
534
+ const handleEvent = (event: Event) => {
535
+ if (event.message?.user?.id !== client.userID) {
536
+ if (!scrollToBottomButtonVisible) {
537
+ flashListRef.current?.scrollToEnd({
538
+ animated: true,
539
+ });
540
+ } else {
541
+ setAutoScrollToRecent(false);
542
+ }
543
+ }
544
+ };
545
+ const listener: ReturnType<typeof channel.on> = channel.on('message.new', handleEvent);
546
+
547
+ return () => {
548
+ listener?.unsubscribe();
549
+ };
550
+ }, [channel, client.userID, scrollToBottomButtonVisible]);
551
+
552
+ /**
553
+ * Effect to mark the channel as read when the user scrolls to the bottom of the message list.
554
+ */
555
+ useEffect(() => {
556
+ const shouldMarkRead = () => {
557
+ return (
558
+ !channelUnreadState?.first_unread_message_id &&
559
+ !scrollToBottomButtonVisible &&
560
+ client.user?.id &&
561
+ !hasReadLastMessage(channel, client.user?.id)
562
+ );
563
+ };
564
+
565
+ const handleEvent = async (event: Event) => {
566
+ const mainChannelUpdated = !event.message?.parent_id || event.message?.show_in_channel;
567
+ const isMyOwnMessage = event.message?.user?.id === client.user?.id;
568
+ // When the scrollToBottomButtonVisible is true, we need to manually update the channelUnreadState when its a received message.
569
+ if (
570
+ (scrollToBottomButtonVisible || channelUnreadState?.first_unread_message_id) &&
571
+ !isMyOwnMessage
572
+ ) {
573
+ setChannelUnreadState((prev) => {
574
+ const previousUnreadCount = prev?.unread_messages ?? 0;
575
+ const previousLastMessage = getPreviousLastMessage(channel.state.messages, event.message);
576
+ return {
577
+ ...(prev || {}),
578
+ last_read:
579
+ prev?.last_read ??
580
+ (previousUnreadCount === 0 && previousLastMessage?.created_at
581
+ ? new Date(previousLastMessage.created_at)
582
+ : new Date(0)), // not having information about the last read message means the whole channel is unread,
583
+ unread_messages: previousUnreadCount + 1,
584
+ };
585
+ });
586
+ } else if (mainChannelUpdated && shouldMarkRead()) {
587
+ await markRead();
588
+ }
589
+ };
590
+
591
+ const listener: ReturnType<typeof channel.on> = channel.on('message.new', handleEvent);
592
+
593
+ return () => {
594
+ listener?.unsubscribe();
595
+ };
596
+ }, [
597
+ channel,
598
+ channelUnreadState?.first_unread_message_id,
599
+ client.user?.id,
600
+ markRead,
601
+ scrollToBottomButtonVisible,
602
+ setChannelUnreadState,
603
+ threadList,
604
+ ]);
605
+
606
+ const updateStickyHeaderDateIfNeeded = useStableCallback((viewableItems: ViewToken[]) => {
607
+ if (!viewableItems.length) {
608
+ return;
609
+ }
610
+
611
+ const lastItem = viewableItems[0];
612
+
613
+ if (!lastItem) return;
614
+
615
+ if (
616
+ !channel.state.messagePagination.hasPrev &&
617
+ processedMessageList[0].id === lastItem.item.id
618
+ ) {
619
+ setStickyHeaderDate(undefined);
620
+ return;
621
+ }
622
+ const isMessageTypeDeleted = lastItem.item.type === 'deleted';
623
+
624
+ if (
625
+ lastItem?.item?.created_at &&
626
+ !isMessageTypeDeleted &&
627
+ typeof lastItem.item.created_at !== 'string' &&
628
+ lastItem.item.created_at.toDateString() !== stickyHeaderDateRef.current?.toDateString()
629
+ ) {
630
+ stickyHeaderDateRef.current = lastItem.item.created_at;
631
+ setStickyHeaderDate(lastItem.item.created_at);
632
+ }
633
+ });
634
+
635
+ /**
636
+ * This function should show or hide the unread indicator depending on the
637
+ */
638
+ const updateStickyUnreadIndicator = useStableCallback((viewableItems: ViewToken[]) => {
639
+ if (!viewableItems.length || !readEvents) {
640
+ setIsUnreadNotificationOpen(false);
641
+ return;
642
+ }
643
+
644
+ if (selectedPicker === 'images') {
645
+ setIsUnreadNotificationOpen(false);
646
+ return;
647
+ }
648
+
649
+ const lastItem = viewableItems[0];
650
+
651
+ if (!lastItem) return;
652
+
653
+ const lastItemMessage = lastItem.item;
654
+ const lastItemCreatedAt = lastItemMessage.created_at;
655
+
656
+ const unreadIndicatorDate = channelUnreadState?.last_read.getTime();
657
+ const lastItemDate = lastItemCreatedAt.getTime();
658
+
659
+ if (
660
+ !channel.state.messagePagination.hasPrev &&
661
+ processedMessageList[0].id === lastItemMessage.id
662
+ ) {
663
+ setIsUnreadNotificationOpen(false);
664
+ return;
665
+ }
666
+ /**
667
+ * This is a special case where there is a single long message by the sender.
668
+ * When a message is sent, we mark it as read before it actually has a `created_at` timestamp.
669
+ * This is a workaround to prevent the unread indicator from showing when the message is sent.
670
+ */
671
+ if (
672
+ viewableItems.length === 1 &&
673
+ channel.countUnread() === 0 &&
674
+ lastItemMessage.user.id === client.userID
675
+ ) {
676
+ setIsUnreadNotificationOpen(false);
677
+ return;
678
+ }
679
+ if (unreadIndicatorDate && lastItemDate > unreadIndicatorDate) {
680
+ setIsUnreadNotificationOpen(true);
681
+ } else {
682
+ setIsUnreadNotificationOpen(false);
683
+ }
684
+ });
685
+
686
+ /**
687
+ * FlatList doesn't accept changeable function for onViewableItemsChanged prop.
688
+ * Thus useRef.
689
+ */
690
+ const unstableOnViewableItemsChanged = ({
691
+ viewableItems,
692
+ }: {
693
+ viewableItems: ViewToken[] | undefined;
694
+ }) => {
695
+ if (!viewableItems) {
696
+ return;
697
+ }
698
+ if (!hideStickyDateHeader) {
699
+ updateStickyHeaderDateIfNeeded(viewableItems);
700
+ }
701
+ updateStickyUnreadIndicator(viewableItems);
702
+ };
703
+
704
+ const onViewableItemsChanged = useRef(unstableOnViewableItemsChanged);
705
+ onViewableItemsChanged.current = unstableOnViewableItemsChanged;
706
+
707
+ const stableOnViewableItemsChanged = useCallback(
708
+ ({ viewableItems }: { viewableItems: ViewToken[] | undefined }) => {
709
+ onViewableItemsChanged.current({ viewableItems });
710
+ },
711
+ [],
712
+ );
713
+
714
+ const renderItem = useCallback(
715
+ ({ index, item: message }: { index: number; item: LocalMessage }) => {
716
+ if (!channel || channel.disconnected || (!channel.initialized && !channel.offlineMode)) {
717
+ return null;
718
+ }
719
+
720
+ const createdAtTimestamp = message.created_at && new Date(message.created_at).getTime();
721
+ const lastReadTimestamp = channelUnreadState?.last_read.getTime();
722
+ const isNewestMessage = index === 0;
723
+ const isLastReadMessage =
724
+ channelUnreadState?.last_read_message_id === message.id ||
725
+ (!channelUnreadState?.unread_messages && createdAtTimestamp === lastReadTimestamp);
726
+
727
+ const showUnreadSeparator =
728
+ isLastReadMessage &&
729
+ !isNewestMessage &&
730
+ // The `channelUnreadState?.first_unread_message_id` is here for sent messages unread label
731
+ (!!channelUnreadState?.first_unread_message_id || !!channelUnreadState?.unread_messages);
732
+
733
+ const showUnreadUnderlay = !!shouldShowUnreadUnderlay && showUnreadSeparator;
734
+
735
+ const wrapMessageInTheme = client.userID === message.user?.id && !!myMessageTheme;
736
+ const renderDateSeperator = dateSeparatorsRef.current[message.id] && (
737
+ <InlineDateSeparator date={dateSeparatorsRef.current[message.id]} />
738
+ );
739
+
740
+ const renderMessage = (
741
+ <Message
742
+ goToMessage={goToMessage}
743
+ groupStyles={messageGroupStylesRef.current[message.id] ?? []}
744
+ isTargetedMessage={highlightedMessageId === message.id}
745
+ lastReceivedId={
746
+ lastReceivedId === message.id || message.quoted_message_id ? lastReceivedId : undefined
747
+ }
748
+ message={message}
749
+ onThreadSelect={onThreadSelect}
750
+ showUnreadUnderlay={showUnreadUnderlay}
751
+ threadList={threadList}
752
+ />
753
+ );
754
+
755
+ return (
756
+ <View testID={`message-list-item-${index}`}>
757
+ {message.type === 'system' ? (
758
+ <MessageSystem message={message} />
759
+ ) : wrapMessageInTheme ? (
760
+ <ThemeProvider mergedStyle={modifiedTheme}>
761
+ <View testID={`message-list-item-${index}`}>
762
+ {renderDateSeperator}
763
+ {renderMessage}
764
+ </View>
765
+ </ThemeProvider>
766
+ ) : (
767
+ <View testID={`message-list-item-${index}`}>
768
+ {renderDateSeperator}
769
+ {renderMessage}
770
+ </View>
771
+ )}
772
+ {showUnreadUnderlay && <InlineUnreadIndicator />}
773
+ </View>
774
+ );
775
+ },
776
+ [
777
+ InlineDateSeparator,
778
+ InlineUnreadIndicator,
779
+ Message,
780
+ MessageSystem,
781
+ channel,
782
+ channelUnreadState?.first_unread_message_id,
783
+ channelUnreadState?.last_read,
784
+ channelUnreadState?.last_read_message_id,
785
+ channelUnreadState?.unread_messages,
786
+ client.userID,
787
+ dateSeparatorsRef,
788
+ goToMessage,
789
+ highlightedMessageId,
790
+ lastReceivedId,
791
+ messageGroupStylesRef,
792
+ modifiedTheme,
793
+ myMessageTheme,
794
+ onThreadSelect,
795
+ shouldShowUnreadUnderlay,
796
+ threadList,
797
+ ],
798
+ );
799
+
800
+ const messagesWithImages =
801
+ legacyImageViewerSwipeBehaviour &&
802
+ processedMessageList.filter((message) => {
803
+ const isMessageTypeDeleted = message.type === 'deleted';
804
+ if (!isMessageTypeDeleted && message.attachments) {
805
+ return message.attachments.some(
806
+ (attachment) =>
807
+ attachment.type === FileTypes.Image &&
808
+ !attachment.title_link &&
809
+ !attachment.og_scrape_url &&
810
+ (attachment.image_url || attachment.thumb_url),
811
+ );
812
+ }
813
+ return false;
814
+ });
815
+
816
+ /**
817
+ * This is for the useEffect to run again in the case that a message
818
+ * gets edited with more or the same number of images
819
+ */
820
+ const imageString =
821
+ legacyImageViewerSwipeBehaviour &&
822
+ messagesWithImages &&
823
+ messagesWithImages
824
+ .map((message) =>
825
+ message.attachments
826
+ ?.map((attachment) => attachment.image_url || attachment.thumb_url || '')
827
+ .join(),
828
+ )
829
+ .join();
830
+
831
+ const numberOfMessagesWithImages =
832
+ legacyImageViewerSwipeBehaviour && messagesWithImages && messagesWithImages.length;
833
+ const threadExists = !!thread;
834
+
835
+ useEffect(() => {
836
+ if (
837
+ legacyImageViewerSwipeBehaviour &&
838
+ isListActive &&
839
+ ((threadList && thread) || (!threadList && !thread))
840
+ ) {
841
+ setMessages(messagesWithImages as LocalMessage[]);
842
+ }
843
+ // eslint-disable-next-line react-hooks/exhaustive-deps
844
+ }, [
845
+ imageString,
846
+ isListActive,
847
+ legacyImageViewerSwipeBehaviour,
848
+ numberOfMessagesWithImages,
849
+ threadExists,
850
+ threadList,
851
+ ]);
852
+
853
+ /**
854
+ * We are keeping full control on message pagination, and not relying on react-native for it.
855
+ * The reasons being,
856
+ * 1. FlatList doesn't support onStartReached prop
857
+ * 2. `onEndReached` function prop available on react-native, gets executed
858
+ * once per content length (and thats actually a nice optimization strategy).
859
+ * But it also means, we always need to prioritize onEndReached above our
860
+ * logic for `onStartReached`.
861
+ * 3. `onEndReachedThreshold` prop decides - at which scroll position to call `onEndReached`.
862
+ * Its a factor of content length (which is necessary for "real" infinite scroll). But on
863
+ * the other hand, it also makes calls to `onEndReached` (and this `channel.query`) way
864
+ * too early during scroll, which we don't really need. So we are going to instead
865
+ * keep some fixed offset distance, to decide when to call `loadMore` or `loadMoreRecent`.
866
+ *
867
+ * We are still gonna keep the optimization, which react-native does - only call onEndReached
868
+ * once per content length.
869
+ */
870
+
871
+ /**
872
+ * 1. Makes a call to `loadMore` function, which queries more older messages.
873
+ * 2. Ensures that we call `loadMore`, once per content length
874
+ * 3. If the call to `loadMoreRecent` is in progress, we wait for it to finish to make sure scroll doesn't jump.
875
+ */
876
+ const maybeCallOnStartReached = useStableCallback(async () => {
877
+ // If onEndReached has already been called for given messageList length, then ignore.
878
+ if (
879
+ processedMessageList?.length &&
880
+ onStartReachedTracker.current[processedMessageList.length]
881
+ ) {
882
+ return;
883
+ }
884
+
885
+ if (processedMessageList?.length) {
886
+ onStartReachedTracker.current[processedMessageList.length] = true;
887
+ }
888
+
889
+ const callback = () => {
890
+ onStartReachedInPromise.current = null;
891
+ return Promise.resolve();
892
+ };
893
+
894
+ const onError = () => {
895
+ /** Release the onEndReachedTracker trigger after 2 seconds, to try again */
896
+ setTimeout(() => {
897
+ onStartReachedTracker.current = {};
898
+ }, 2000);
899
+ };
900
+
901
+ // If onStartReached is in progress, better to wait for it to finish for smooth UX
902
+ if (onEndReachedInPromise.current) {
903
+ await onEndReachedInPromise.current;
904
+ }
905
+ onStartReachedInPromise.current = (
906
+ threadList && !!threadInstance && loadMoreRecentThread
907
+ ? loadMoreRecentThread({})
908
+ : loadMoreRecent()
909
+ )
910
+ .then(callback)
911
+ .catch(onError);
912
+ });
913
+
914
+ /**
915
+ * 1. Makes a call to `loadMoreRecent` function, which queries more recent messages.
916
+ * 2. Ensures that we call `loadMoreRecent`, once per content length
917
+ * 3. If the call to `loadMore` is in progress, we wait for it to finish to make sure scroll doesn't jump.
918
+ */
919
+ const maybeCallOnEndReached = useStableCallback(async () => {
920
+ // If onStartReached has already been called for given data length, then ignore.
921
+ if (processedMessageList?.length && onEndReachedTracker.current[processedMessageList.length]) {
922
+ return;
923
+ }
924
+
925
+ if (processedMessageList?.length) {
926
+ onEndReachedTracker.current[processedMessageList.length] = true;
927
+ }
928
+
929
+ const callback = () => {
930
+ onEndReachedInPromise.current = null;
931
+
932
+ return Promise.resolve();
933
+ };
934
+
935
+ const onError = () => {
936
+ /** Release the onStartReached trigger after 2 seconds, to try again */
937
+ setTimeout(() => {
938
+ onEndReachedTracker.current = {};
939
+ }, 2000);
940
+ };
941
+
942
+ // If onEndReached is in progress, better to wait for it to finish for smooth UX
943
+ if (onStartReachedInPromise.current) {
944
+ await onStartReachedInPromise.current;
945
+ }
946
+
947
+ onEndReachedInPromise.current = (threadList ? loadMoreThread() : loadMore())
948
+ .then(callback)
949
+ .catch(onError);
950
+ });
951
+
952
+ const onUserScrollEvent: NonNullable<ScrollViewProps['onScroll']> = useStableCallback((event) => {
953
+ const nativeEvent = event.nativeEvent;
954
+ const offset = nativeEvent.contentOffset.y;
955
+ const visibleLength = nativeEvent.layoutMeasurement.height;
956
+ const contentLength = nativeEvent.contentSize.height;
957
+ if (!channel || !channelResyncScrollSet.current) {
958
+ return;
959
+ }
960
+
961
+ // Check if scroll has reached either start of end of list.
962
+ const isScrollAtEnd = offset < 100;
963
+ const isScrollAtStart = contentLength - visibleLength - offset < 100;
964
+
965
+ if (isScrollAtEnd) {
966
+ maybeCallOnEndReached();
967
+ }
968
+
969
+ if (isScrollAtStart) {
970
+ maybeCallOnStartReached();
971
+ }
972
+ });
973
+
974
+ /**
975
+ * Resets the pagination trackers, doing so cancels currently scheduled loading more calls
976
+ */
977
+ const resetPaginationTrackersRef = useRef(() => {
978
+ onStartReachedTracker.current = {};
979
+ onEndReachedTracker.current = {};
980
+ });
981
+
982
+ const currentScrollOffsetRef = useRef(0);
983
+
984
+ const handleScroll: ScrollViewProps['onScroll'] = useStableCallback((event) => {
985
+ const messageListHasMessages = processedMessageList.length > 0;
986
+ const nativeEvent = event.nativeEvent;
987
+ const offset = nativeEvent.contentOffset.y;
988
+ currentScrollOffsetRef.current = offset;
989
+ const visibleLength = nativeEvent.layoutMeasurement.height;
990
+ const contentLength = nativeEvent.contentSize.height;
991
+
992
+ // Show scrollToBottom button once scroll position goes beyond 150.
993
+ const isScrollAtStart = contentLength - visibleLength - offset < 150;
994
+
995
+ const notLatestSet = channel.state.messages !== channel.state.latestMessages;
996
+
997
+ const showScrollToBottomButton =
998
+ messageListHasMessages && ((!threadList && notLatestSet) || !isScrollAtStart);
999
+
1000
+ /**
1001
+ * 1. If I scroll up -> show scrollToBottom button.
1002
+ * 2. If I scroll to bottom of screen
1003
+ * |-> hide scrollToBottom button.
1004
+ * |-> if channel is unread, call markRead().
1005
+ */
1006
+ setScrollToBottomButtonVisible(showScrollToBottomButton);
1007
+
1008
+ if (onListScroll) {
1009
+ onListScroll(event);
1010
+ }
1011
+ });
1012
+
1013
+ const goToNewMessages = useStableCallback(async () => {
1014
+ const isNotLatestSet = channel.state.messages !== channel.state.latestMessages;
1015
+
1016
+ if (isNotLatestSet) {
1017
+ resetPaginationTrackersRef.current();
1018
+ await reloadChannel();
1019
+ } else if (flashListRef.current) {
1020
+ flashListRef.current.scrollToEnd({
1021
+ animated: true,
1022
+ });
1023
+ }
1024
+
1025
+ setScrollToBottomButtonVisible(false);
1026
+ /**
1027
+ * When we are not in the bottom of the list, and we receive new messages, we need to mark the channel as read.
1028
+ We would still need to show the unread label, where the first unread message appeared so we don't update the channelUnreadState.
1029
+ */
1030
+ await markRead({
1031
+ updateChannelUnreadState: false,
1032
+ });
1033
+ });
1034
+
1035
+ const dismissImagePicker = useStableCallback(() => {
1036
+ if (selectedPicker) {
1037
+ setSelectedPicker(undefined);
1038
+ closePicker();
1039
+ }
1040
+ });
1041
+
1042
+ const onScrollBeginDrag: ScrollViewProps['onScrollBeginDrag'] = useStableCallback((event) => {
1043
+ !hasMoved && selectedPicker && setHasMoved(true);
1044
+ onUserScrollEvent(event);
1045
+ });
1046
+
1047
+ const onScrollEndDrag: ScrollViewProps['onScrollEndDrag'] = useStableCallback((event) => {
1048
+ hasMoved && selectedPicker && setHasMoved(false);
1049
+ onUserScrollEvent(event);
1050
+ });
1051
+
1052
+ const refCallback = useStableCallback((ref: FlashListRef<LocalMessage>) => {
1053
+ flashListRef.current = ref;
1054
+
1055
+ if (setFlatListRef) {
1056
+ setFlatListRef(ref);
1057
+ }
1058
+ });
1059
+
1060
+ const onUnreadNotificationClose = useStableCallback(async () => {
1061
+ await markRead();
1062
+ setIsUnreadNotificationOpen(false);
1063
+ });
1064
+
1065
+ // We need to omit the style related props from the additionalFlatListProps and add them directly instead of spreading
1066
+ let additionalFlashListPropsExcludingStyle:
1067
+ | Omit<NonNullable<typeof additionalFlashListProps>, 'style' | 'contentContainerStyle'>
1068
+ | undefined;
1069
+
1070
+ if (additionalFlashListProps) {
1071
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
1072
+ const { contentContainerStyle, style, ...rest } = additionalFlashListProps;
1073
+ additionalFlashListPropsExcludingStyle = rest;
1074
+ }
1075
+
1076
+ const flatListStyle = useMemo(
1077
+ () => ({ ...styles.listContainer, ...listContainer, ...additionalFlashListProps?.style }),
1078
+ [additionalFlashListProps?.style, listContainer],
1079
+ );
1080
+
1081
+ const flatListContentContainerStyle = useMemo(
1082
+ () => ({
1083
+ ...styles.contentContainer,
1084
+ ...contentContainer,
1085
+ }),
1086
+ [contentContainer],
1087
+ );
1088
+
1089
+ const getItemType = useStableCallback((item: LocalMessage) => {
1090
+ const type = getItemTypeInternal(item);
1091
+ return client.userID === item.user?.id ? `own-${type}` : type;
1092
+ });
1093
+
1094
+ const currentListHeightRef = useRef<number | undefined>(undefined);
1095
+
1096
+ const onLayout = useStableCallback((e: LayoutChangeEvent) => {
1097
+ const { height } = e.nativeEvent.layout;
1098
+ if (!currentListHeightRef.current) {
1099
+ currentListHeightRef.current = height;
1100
+ return;
1101
+ }
1102
+
1103
+ const changedBy = currentListHeightRef.current - height;
1104
+ flashListRef.current?.scrollToOffset({
1105
+ offset: currentScrollOffsetRef.current + changedBy,
1106
+ });
1107
+ currentListHeightRef.current = height;
1108
+ });
1109
+
1110
+ if (loading) {
1111
+ return (
1112
+ <View style={[styles.container, { backgroundColor: white_snow }, container]}>
1113
+ <LoadingIndicator listType='message' />
1114
+ </View>
1115
+ );
1116
+ }
1117
+
1118
+ if (!FlashList) {
1119
+ throw new Error(
1120
+ 'The package @shopify/flash-list is not installed. Installing this package will enable the use of the FlashList component.',
1121
+ );
1122
+ }
1123
+
1124
+ return (
1125
+ <View
1126
+ onLayout={onLayout}
1127
+ style={[styles.container, { backgroundColor: white_snow }, container]}
1128
+ testID='message-flat-list-wrapper'
1129
+ >
1130
+ {processedMessageList.length === 0 && !thread ? (
1131
+ <View style={[styles.flex, { backgroundColor: white_snow }]} testID='empty-state'>
1132
+ {EmptyStateIndicator ? <EmptyStateIndicator listType='message' /> : null}
1133
+ </View>
1134
+ ) : (
1135
+ <FlashList
1136
+ contentContainerStyle={flatListContentContainerStyle}
1137
+ data={processedMessageList}
1138
+ drawDistance={800}
1139
+ getItemType={getItemType}
1140
+ keyboardShouldPersistTaps='handled'
1141
+ keyExtractor={keyExtractor}
1142
+ ListFooterComponent={FooterComponent}
1143
+ ListHeaderComponent={HeaderComponent}
1144
+ maintainVisibleContentPosition={maintainVisibleContentPosition}
1145
+ onMomentumScrollEnd={onUserScrollEvent}
1146
+ onScroll={handleScroll}
1147
+ onScrollBeginDrag={onScrollBeginDrag}
1148
+ onScrollEndDrag={onScrollEndDrag}
1149
+ onTouchEnd={dismissImagePicker}
1150
+ onViewableItemsChanged={stableOnViewableItemsChanged}
1151
+ ref={refCallback}
1152
+ renderItem={renderItem}
1153
+ showsVerticalScrollIndicator={false}
1154
+ style={flatListStyle}
1155
+ testID='message-flash-list'
1156
+ viewabilityConfig={flatListViewabilityConfig}
1157
+ {...additionalFlashListPropsExcludingStyle}
1158
+ />
1159
+ )}
1160
+ <View style={styles.stickyHeader}>
1161
+ {messageListLengthAfterUpdate && StickyHeader ? (
1162
+ <StickyHeader date={stickyHeaderDate} DateHeader={DateHeader} />
1163
+ ) : null}
1164
+ </View>
1165
+ {!disableTypingIndicator && TypingIndicator && (
1166
+ <TypingIndicatorContainer>
1167
+ <TypingIndicator />
1168
+ </TypingIndicatorContainer>
1169
+ )}
1170
+ <ScrollToBottomButton
1171
+ onPress={goToNewMessages}
1172
+ showNotification={scrollToBottomButtonVisible}
1173
+ unreadCount={threadList ? 0 : channel?.countUnread()}
1174
+ />
1175
+ <NetworkDownIndicator />
1176
+ {isUnreadNotificationOpen && !threadList ? (
1177
+ <UnreadMessagesNotification onCloseHandler={onUnreadNotificationClose} />
1178
+ ) : null}
1179
+ </View>
1180
+ );
1181
+ };
1182
+
1183
+ export type MessageFlashListProps = Partial<MessageFlashListPropsWithContext>;
1184
+
1185
+ /**
1186
+ * This is a @experimental component.
1187
+ * It is implemented using @shopify/flash-list package to optimize the performance of the MessageList component.
1188
+ * The implementation is experimental and is subject to change.
1189
+ * Please feel free to report any issues or suggestions.
1190
+ */
1191
+ export const MessageFlashList = (props: MessageFlashListProps) => {
1192
+ const { closePicker, selectedPicker, setSelectedPicker } = useAttachmentPickerContext();
1193
+ const {
1194
+ channel,
1195
+ channelUnreadState,
1196
+ disabled,
1197
+ EmptyStateIndicator,
1198
+ enableMessageGroupingByUser,
1199
+ error,
1200
+ hideStickyDateHeader,
1201
+ highlightedMessageId,
1202
+ isChannelActive,
1203
+ loadChannelAroundMessage,
1204
+ loading,
1205
+ LoadingIndicator,
1206
+ markRead,
1207
+ NetworkDownIndicator,
1208
+ reloadChannel,
1209
+ scrollToFirstUnreadThreshold,
1210
+ setChannelUnreadState,
1211
+ setTargetedMessage,
1212
+ StickyHeader,
1213
+ targetedMessage,
1214
+ threadList,
1215
+ } = useChannelContext();
1216
+ const { client } = useChatContext();
1217
+ const { setMessages } = useImageGalleryContext();
1218
+ const {
1219
+ DateHeader,
1220
+ disableTypingIndicator,
1221
+ FlatList,
1222
+ InlineDateSeparator,
1223
+ InlineUnreadIndicator,
1224
+ legacyImageViewerSwipeBehaviour,
1225
+ Message,
1226
+ MessageSystem,
1227
+ myMessageTheme,
1228
+ ScrollToBottomButton,
1229
+ shouldShowUnreadUnderlay,
1230
+ TypingIndicator,
1231
+ TypingIndicatorContainer,
1232
+ UnreadMessagesNotification,
1233
+ } = useMessagesContext();
1234
+ const { loadMore, loadMoreRecent } = usePaginatedMessageListContext();
1235
+ const { loadMoreRecentThread, loadMoreThread, thread, threadInstance } = useThreadContext();
1236
+ const { readEvents } = useOwnCapabilitiesContext();
1237
+
1238
+ return (
1239
+ <MessageFlashListWithContext
1240
+ {...{
1241
+ channel,
1242
+ channelUnreadState,
1243
+ client,
1244
+ closePicker,
1245
+ DateHeader,
1246
+ disabled,
1247
+ disableTypingIndicator,
1248
+ EmptyStateIndicator,
1249
+ enableMessageGroupingByUser,
1250
+ error,
1251
+ FlatList,
1252
+ hideStickyDateHeader,
1253
+ highlightedMessageId,
1254
+ InlineDateSeparator,
1255
+ InlineUnreadIndicator,
1256
+ isListActive: isChannelActive,
1257
+ legacyImageViewerSwipeBehaviour,
1258
+ loadChannelAroundMessage,
1259
+ loading,
1260
+ LoadingIndicator,
1261
+ loadMore,
1262
+ loadMoreRecent,
1263
+ loadMoreRecentThread,
1264
+ loadMoreThread,
1265
+ markRead,
1266
+ Message,
1267
+ MessageSystem,
1268
+ myMessageTheme,
1269
+ NetworkDownIndicator,
1270
+ readEvents,
1271
+ reloadChannel,
1272
+ ScrollToBottomButton,
1273
+ scrollToFirstUnreadThreshold,
1274
+ selectedPicker,
1275
+ setChannelUnreadState,
1276
+ setMessages,
1277
+ setSelectedPicker,
1278
+ setTargetedMessage,
1279
+ shouldShowUnreadUnderlay,
1280
+ StickyHeader,
1281
+ targetedMessage,
1282
+ thread,
1283
+ threadInstance,
1284
+ threadList,
1285
+ TypingIndicator,
1286
+ TypingIndicatorContainer,
1287
+ UnreadMessagesNotification,
1288
+ }}
1289
+ {...props}
1290
+ noGroupByUser={!enableMessageGroupingByUser || props.noGroupByUser}
1291
+ />
1292
+ );
1293
+ };
1294
+
1295
+ const styles = StyleSheet.create({
1296
+ container: {
1297
+ alignItems: 'center',
1298
+ flex: 1,
1299
+ width: '100%',
1300
+ },
1301
+ contentContainer: {
1302
+ /**
1303
+ * paddingBottom is set to 4 to account for the default date
1304
+ * header and inline indicator alignment. The top margin is 8
1305
+ * on the header but 4 on the inline date, this adjusts the spacing
1306
+ * to allow the "first" inline date to align with the date header.
1307
+ */
1308
+ paddingBottom: 4,
1309
+ },
1310
+ flex: { flex: 1 },
1311
+ listContainer: {
1312
+ flex: 1,
1313
+ width: '100%',
1314
+ },
1315
+ stickyHeader: {
1316
+ position: 'absolute',
1317
+ top: 0,
1318
+ },
1319
+ });