-
Notifications
You must be signed in to change notification settings - Fork 298
Expand file tree
/
Copy pathVirtualizedMessageList.tsx
More file actions
780 lines (716 loc) Β· 28.8 KB
/
Copy pathVirtualizedMessageList.tsx
File metadata and controls
780 lines (716 loc) Β· 28.8 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
import type { RefObject } from 'react';
import React, { useCallback, useEffect, useMemo, useRef } from 'react';
import { FloatingDateSeparator } from './FloatingDateSeparator';
import type {
ComputeItemKey,
ScrollSeekConfiguration,
ScrollSeekPlaceholderProps,
VirtuosoHandle,
VirtuosoProps,
} from 'react-virtuoso';
import { Virtuoso } from 'react-virtuoso';
import { GiphyPreviewMessage as DefaultGiphyPreviewMessage } from './GiphyPreviewMessage';
import { useLastReadData } from './hooks';
import {
useGiphyPreview,
useMessageSetKey,
useNewMessageNotification,
usePrependedMessagesCount,
useScrollToBottomOnNewMessage,
useShouldForceScrollToBottom,
useUnreadMessagesNotificationVirtualized,
} from './hooks/VirtualizedMessageList';
import { useMarkRead } from './hooks/useMarkRead';
import {
NotificationList as DefaultNotificationList,
useNotificationTarget,
} from '../Notifications';
import { AriaLiveRegion, useIncomingMessageAnnouncements } from '../Accessibility';
import { NewMessageNotification as DefaultNewMessageNotification } from './NewMessageNotification';
import { MessageListMainPanel as DefaultMessageListMainPanel } from './MessageListMainPanel';
import type { GroupStyle, ProcessMessagesParams, RenderedMessage } from './utils';
import { getGroupStyles, getLastReceived, processMessages } from './utils';
import type { MessageProps, MessageUIComponentProps } from '../Message';
import { MessageUI } from '../Message';
import { UnreadMessagesNotification as DefaultUnreadMessagesNotification } from './UnreadMessagesNotification';
import {
calculateFirstItemIndex,
calculateItemIndex,
EmptyPlaceholder,
Header,
Item,
makeItemsRenderedHandler,
messageRenderer,
} from './VirtualizedMessageListComponents';
import {
UnreadMessagesSeparator as DefaultUnreadMessagesSeparator,
ScrollToLatestMessageButton,
} from '../MessageList';
import { DateSeparator as DefaultDateSeparator } from '../DateSeparator';
import { EventComponent as DefaultMessageSystem } from '../EventComponent';
import { DialogManagerProvider, useChannel } from '../../context';
import type { ChatContextValue } from '../../context/ChatContext';
import { useChatContext } from '../../context/ChatContext';
import type { ComponentContextValue } from '../../context/ComponentContext';
import { useComponentContext } from '../../context/ComponentContext';
import { MessageTranslationViewProvider } from '../../context/MessageTranslationViewContext';
import { VirtualizedMessageListContextProvider } from '../../context/VirtualizedMessageListContext';
import { useStateStore } from '../../store';
import { useThreadContext } from '../Threads';
import { useMessagePaginator } from '../../hooks';
import type {
Channel,
LocalMessage,
MessageFocusSignalState,
MessagePaginatorState,
ChannelState as StreamChannelState,
UnreadSnapshotState,
UserResponse,
} from 'stream-chat';
import type { UnknownType } from '../../types/types';
import { useStableId } from '../UtilityComponents/useStableId';
import { useLastDeliveredData } from './hooks/useLastDeliveredData';
import { useLastOwnMessage } from './hooks/useLastOwnMessage';
type PropsDrilledToMessage =
| 'additionalMessageComposerProps'
| 'formatDate'
| 'messageActions'
| 'reactionDetailsSort'
| 'renderText'
| 'showAvatar'
| 'sortReactions';
type VirtualizedMessageListPropsForContext =
| PropsDrilledToMessage
| 'closeReactionSelectorOnClick'
| 'customMessageRenderer'
| 'head'
// | 'loadingMore'
| 'Message'
| 'returnAllReadData'
| 'shouldGroupByUser';
/**
* Context object provided to some Virtuoso props that are functions (components rendered by Virtuoso and other functions)
*/
export type VirtuosoContext = Required<
Pick<
ComponentContextValue,
'DateSeparator' | 'MessageSystem' | 'UnreadMessagesSeparator'
>
> &
Pick<VirtualizedMessageListProps, VirtualizedMessageListPropsForContext> &
Pick<ChatContextValue, 'customClasses'> & {
channel: Channel;
/** Latest received message id in the current channel */
lastReceivedMessageId: string | null | undefined;
loadingMore: boolean;
/** Object mapping between the message ID and a string representing the position in the group of a sequence of messages posted by the same user. */
messageGroupStyles: Record<string, GroupStyle>;
/** Number of messages prepended before the first page of messages. This is needed to calculate the virtual position in the virtual list. */
numItemsPrepended: number;
/** Mapping of message ID of own messages to the array of users, who were delivered the given message */
ownMessagesDeliveredToOthers: Record<string, UserResponse[]>;
/** Mapping of message ID of own messages to the array of users, who read the given message */
ownMessagesReadByOthers: Record<string, UserResponse[]>;
/** The original message list enriched with date separators, omitted deleted messages or giphy previews. */
processedMessages: RenderedMessage[];
/** Instance of VirtuosoHandle object providing the API to navigate in the virtualized list by various scroll actions. */
virtuosoRef: RefObject<VirtuosoHandle | null>;
/** Latest own message in currently displayed message set. */
lastOwnMessage?: LocalMessage;
/** Message id which was marked as unread. ALl the messages following this message are considered unrea. */
firstUnreadMessageId: string | null;
lastReadDate: Date | null;
/**
* The ID of the last message considered read by the current user in the current channel.
* All the messages following this message are considered unread.
*/
lastReadMessageId: string | null;
/** The number of unread messages in the current channel. */
unreadMessageCount: number;
/** Message id currently targeted by paginator focus signal. */
focusedMessageId?: string | null;
};
type VirtualizedMessageListWithContextProps = VirtualizedMessageListProps & {
channel: Channel;
// hasMore: boolean;
// hasMoreNewer: boolean;
// jumpToLatestMessage: () => Promise<void>;
// loadingMore: boolean;
// loadingMoreNewer: boolean;
read?: StreamChannelState['read'];
};
const channelReadSelector = (nextValue: { read: StreamChannelState['read'] }) => ({
read: nextValue.read,
});
function captureResizeObserverExceededError(e: ErrorEvent) {
if (
e.message === 'ResizeObserver loop completed with undelivered notifications.' ||
e.message === 'ResizeObserver loop limit exceeded'
) {
e.stopImmediatePropagation();
}
}
function useCaptureResizeObserverExceededError() {
useEffect(() => {
window.addEventListener('error', captureResizeObserverExceededError);
return () => {
window.removeEventListener('error', captureResizeObserverExceededError);
};
}, []);
}
function fractionalItemSize(element: HTMLElement) {
return element.getBoundingClientRect().height;
}
function findMessageIndex(messages: RenderedMessage[], id: string) {
return messages.findIndex((message) => message.id === id);
}
function calculateInitialTopMostItemIndex(
messages: RenderedMessage[],
focusedMessageId: string | undefined,
) {
if (focusedMessageId) {
const index = findMessageIndex(messages, focusedMessageId);
if (index !== -1) {
return { align: 'center', index } as const;
}
}
return messages.length - 1;
}
const unreadStateSnapshotSelector = (state: UnreadSnapshotState) => state;
const messageFocusSignalSelector = (state: MessageFocusSignalState) => ({
messageFocusSignal: state.signal,
});
const messagePaginatorStateSelector = (state: MessagePaginatorState) => ({
hasMoreNewer: state.hasMoreHead,
isLoading: state.isLoading,
messages: state.items ?? [],
});
const VirtualizedMessageListWithContext = (
props: VirtualizedMessageListWithContextProps,
) => {
const {
additionalMessageComposerProps,
additionalVirtuosoProps = {},
channel,
// channelUnreadUiState,
closeReactionSelectorOnClick,
customMessageRenderer,
defaultItemHeight,
disableDateSeparator = true,
formatDate,
groupStyles,
// hasMoreNewer,
head,
hideDeletedMessages = false,
hideNewMessageSeparator = false,
// jumpToLatestMessage,
// loadingMore,
// loadMore,
// loadMoreNewer,
maxTimeBetweenGroupedMessages,
Message: MessageUIComponentFromProps,
messageActions,
// messageLimit = DEFAULT_NEXT_CHANNEL_PAGE_SIZE,
// messages,
// TODO: refactor to scrollSeekPlaceHolderConfiguration and components.ScrollSeekPlaceholder, like the Virtuoso Component
overscan = 0,
reactionDetailsSort,
renderText,
returnAllReadData = false,
reviewProcessedMessage,
scrollSeekPlaceHolder,
scrollToLatestMessageOnFocus = false,
separateGiphyPreview = false,
shouldGroupByUser = false,
showAvatar,
showUnreadNotificationAlways,
sortReactions,
stickToBottomScrollBehavior = 'smooth',
suppressAutoscroll: suppressAutoscrollFromProps = false,
} = props;
const thread = useThreadContext();
const isThreadList = !!thread;
const [suppressAutoscrollWhileLoadingOlder, setSuppressAutoscrollWhileLoadingOlder] =
React.useState(false);
const suppressAutoscroll =
suppressAutoscrollFromProps || suppressAutoscrollWhileLoadingOlder;
const loadingOlderRef = useRef(false);
const { components: virtuosoComponentsFromProps, ...overridingVirtuosoProps } =
additionalVirtuosoProps;
// Stops errors generated from react-virtuoso to bubble up
// to Sentry or other tracking tools.
useCaptureResizeObserverExceededError();
const {
DateSeparator = DefaultDateSeparator,
GiphyPreviewMessage = DefaultGiphyPreviewMessage,
MessageListMainPanel = DefaultMessageListMainPanel,
MessageSystem = DefaultMessageSystem,
NewMessageNotification = DefaultNewMessageNotification,
NotificationList = DefaultNotificationList,
TypingIndicator,
UnreadMessagesNotification = DefaultUnreadMessagesNotification,
UnreadMessagesSeparator = DefaultUnreadMessagesSeparator,
VirtualMessage: MessageUIComponentFromContext = MessageUI,
} = useComponentContext('VirtualizedMessageList');
const MessageUIComponent = MessageUIComponentFromProps || MessageUIComponentFromContext;
const { client, customClasses } = useChatContext('VirtualizedMessageList');
const messagePaginator = useMessagePaginator();
const { hasMoreNewer, isLoading, messages } = useStateStore(
messagePaginator.state,
messagePaginatorStateSelector,
);
const { messageFocusSignal } = useStateStore(
messagePaginator.messageFocusSignal,
messageFocusSignalSelector,
);
const channelUnreadUiState = useStateStore(
messagePaginator.unreadStateSnapshot,
unreadStateSnapshotSelector,
);
const focusedMessageId = messageFocusSignal?.messageId;
const focusToken = messageFocusSignal?.token;
const virtuoso = useRef<VirtuosoHandle>(null);
const lastRead = useMemo(() => channel.lastRead?.(), [channel]);
const { show: showUnreadMessagesNotification, toggleShowUnreadMessagesNotification } =
useUnreadMessagesNotificationVirtualized({
showAlways: !!showUnreadNotificationAlways,
});
const { giphyPreviewMessage, setGiphyPreviewMessage } =
useGiphyPreview(separateGiphyPreview);
const processedMessages = useMemo(() => {
if (typeof messages === 'undefined') {
return [];
}
if (
disableDateSeparator &&
!hideDeletedMessages &&
hideNewMessageSeparator &&
!separateGiphyPreview
) {
return messages;
}
return processMessages({
enableDateSeparator: !disableDateSeparator,
hideDeletedMessages,
hideNewMessageSeparator,
lastRead,
messages,
reviewProcessedMessage,
setGiphyPreviewMessage,
userId: client.userID || '',
});
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [
disableDateSeparator,
hideDeletedMessages,
hideNewMessageSeparator,
lastRead,
messages,
messages?.length,
client.userID,
]);
/**
* This indirection via a ref is needed because Virtuosoβs itemsRendered is set at render time,
* while FloatingDateSeparator lives in a child component that may run its hooks in a different order.
* Using a ref lets the parent provide the callback to Virtuoso while the child keeps ownership
* of the actual handler implementation.
*/
const floatingDateItemsRenderedRef = useRef<
((rendered: RenderedMessage[]) => void) | null
>(null);
const lastOwnMessage = useLastOwnMessage({ messages, ownUserId: client.user?.id });
// get the mapping of own messages to array of users who read them
const ownMessagesReadByOthers = useLastReadData({
channel,
lastOwnMessage,
messages: messages || [],
returnAllReadData,
});
const ownMessagesDeliveredToOthers = useLastDeliveredData({
channel,
lastOwnMessage,
messages: messages || [],
returnAllReadData,
});
const lastReceivedMessageId = useMemo(
() => getLastReceived(processedMessages),
[processedMessages],
);
const groupStylesFn = groupStyles || getGroupStyles;
const messageGroupStyles = useMemo(
() =>
processedMessages.reduce<Record<string, GroupStyle>>((acc, message, i) => {
const style = groupStylesFn(
message,
processedMessages[i - 1],
processedMessages[i + 1],
!shouldGroupByUser,
maxTimeBetweenGroupedMessages,
);
if (style && message.id) acc[message.id] = style;
return acc;
}, {}),
// processedMessages were incorrectly rebuilt with a new object identity at some point, hence the .length usage
// eslint-disable-next-line react-hooks/exhaustive-deps
[
maxTimeBetweenGroupedMessages,
processedMessages.length,
shouldGroupByUser,
groupStylesFn,
],
);
const {
atBottom,
isMessageListScrolledToBottom,
newMessagesNotification,
setIsMessageListScrolledToBottom,
setNewMessagesNotification,
} = useNewMessageNotification(processedMessages, client.userID);
useMarkRead({
hasMoreNewer,
isMessageListScrolledToBottom,
messageListIsThread: isThreadList,
});
const notificationTarget = useNotificationTarget();
useIncomingMessageAnnouncements({
activeThreadId: thread?.id,
channel,
ownUserId: channel.getClient().user?.id,
threadList: isThreadList,
});
const scrollToBottom = useCallback(async () => {
if (messagePaginator.hasMoreHead) {
await messagePaginator.jumpToTheLatestMessage();
} else if (virtuoso.current) {
virtuoso.current.scrollToIndex(processedMessages.length - 1);
}
setNewMessagesNotification(false);
}, [
messagePaginator,
virtuoso,
processedMessages,
setNewMessagesNotification,
// processedMessages were incorrectly rebuilt with a new object identity at some point, hence the .length usage
// processedMessages.length,
// hasMoreNewer,
// jumpToLatestMessage,
]);
useScrollToBottomOnNewMessage({
messages,
scrollToBottom,
scrollToLatestMessageOnFocus,
});
const numItemsPrepended = usePrependedMessagesCount(
processedMessages,
!disableDateSeparator,
);
const { messageSetKey } = useMessageSetKey({ messages });
const shouldForceScrollToBottom = useShouldForceScrollToBottom(
processedMessages,
client.userID,
);
const handleItemsRendered = useMemo(
() =>
makeItemsRenderedHandler(
[
toggleShowUnreadMessagesNotification,
(rendered) => floatingDateItemsRenderedRef.current?.(rendered),
],
processedMessages,
),
[processedMessages, toggleShowUnreadMessagesNotification],
);
const followOutput = (isAtBottom: boolean) => {
if (messagePaginator.hasMoreHead || suppressAutoscroll) {
return false;
}
if (shouldForceScrollToBottom()) {
return isAtBottom ? stickToBottomScrollBehavior : 'auto';
}
// a message from another user has been received - don't scroll to bottom unless already there
return isAtBottom ? stickToBottomScrollBehavior : false;
};
const computeItemKey = useCallback<ComputeItemKey<UnknownType, VirtuosoContext>>(
(index, _, { numItemsPrepended, processedMessages }) =>
processedMessages[calculateItemIndex(index, numItemsPrepended)].id,
[],
);
const atBottomStateChange = (isAtBottom: boolean) => {
atBottom.current = isAtBottom;
setIsMessageListScrolledToBottom(isAtBottom);
if (isAtBottom) {
messagePaginator.toHead();
// loadMoreNewer?.(messageLimit);
setNewMessagesNotification?.(false);
}
};
const atTopStateChange = (isAtTop: boolean) => {
if (isAtTop) {
if (loadingOlderRef.current) return;
loadingOlderRef.current = true;
setSuppressAutoscrollWhileLoadingOlder(true);
void messagePaginator.toTail().finally(() => {
loadingOlderRef.current = false;
setSuppressAutoscrollWhileLoadingOlder(false);
});
}
};
useEffect(() => {
let scrollTimeout: ReturnType<typeof setTimeout>;
if (focusedMessageId) {
const index = findMessageIndex(processedMessages, focusedMessageId);
if (index !== -1) {
scrollTimeout = setTimeout(() => {
virtuoso.current?.scrollToIndex({ align: 'center', index });
messagePaginator.scheduleMessageFocusSignalClear({ token: focusToken });
}, 0);
}
}
return () => {
clearTimeout(scrollTimeout);
};
}, [focusedMessageId, focusToken, processedMessages, messagePaginator]);
useEffect(() => {
const paginator = messagePaginator;
return () => paginator.clearMessageFocusSignal();
}, [messagePaginator]);
const id = useStableId();
if (!processedMessages) return null;
const dialogManagerId = isThreadList
? `virtualized-message-list-dialog-manager-thread-${id}`
: `virtualized-message-list-dialog-manager-${id}`;
return (
<VirtualizedMessageListContextProvider value={{ scrollToBottom }}>
<MessageTranslationViewProvider>
<MessageListMainPanel>
<DialogManagerProvider id={dialogManagerId}>
{!isThreadList && showUnreadMessagesNotification && (
<UnreadMessagesNotification
unreadCount={channelUnreadUiState?.unreadCount}
/>
)}
<div
className={
customClasses?.virtualizedMessageList || 'str-chat__virtual-list'
}
>
<FloatingDateSeparator
disableDateSeparator={disableDateSeparator}
itemsRenderedRef={floatingDateItemsRenderedRef}
processedMessages={processedMessages}
/>
<Virtuoso<UnknownType, VirtuosoContext>
atBottomStateChange={atBottomStateChange}
atBottomThreshold={100}
atTopStateChange={atTopStateChange}
atTopThreshold={100}
className='str-chat__message-list-scroll'
components={{
EmptyPlaceholder,
Header,
Item,
...virtuosoComponentsFromProps,
}}
computeItemKey={computeItemKey}
context={{
additionalMessageComposerProps,
channel,
closeReactionSelectorOnClick,
customClasses,
customMessageRenderer,
DateSeparator,
firstUnreadMessageId: channelUnreadUiState?.firstUnreadMessageId,
focusedMessageId,
formatDate,
head,
lastOwnMessage,
lastReadDate: channelUnreadUiState?.lastReadAt,
lastReadMessageId: channelUnreadUiState?.lastReadMessageId,
lastReceivedMessageId,
loadingMore: isLoading,
Message: MessageUIComponent,
messageActions,
messageGroupStyles,
MessageSystem,
numItemsPrepended,
ownMessagesDeliveredToOthers,
ownMessagesReadByOthers,
processedMessages,
reactionDetailsSort,
renderText,
returnAllReadData,
shouldGroupByUser,
showAvatar,
sortReactions,
unreadMessageCount: channelUnreadUiState?.unreadCount,
UnreadMessagesSeparator,
virtuosoRef: virtuoso,
}}
firstItemIndex={calculateFirstItemIndex(numItemsPrepended)}
followOutput={followOutput}
increaseViewportBy={{ bottom: 200, top: 0 }}
initialTopMostItemIndex={calculateInitialTopMostItemIndex(
processedMessages,
focusedMessageId,
)}
itemContent={messageRenderer}
itemSize={fractionalItemSize}
itemsRendered={handleItemsRendered}
key={messageSetKey}
overscan={overscan}
ref={virtuoso}
style={{ overflowX: 'hidden' }}
totalCount={processedMessages.length}
{...overridingVirtuosoProps}
{...(scrollSeekPlaceHolder ? { scrollSeek: scrollSeekPlaceHolder } : {})}
{...(defaultItemHeight ? { defaultItemHeight } : {})}
/>
<NewMessageNotification
newMessageCount={channelUnreadUiState?.unreadCount}
showNotification={
(newMessagesNotification || hasMoreNewer) &&
!isMessageListScrolledToBottom
}
/>
<ScrollToLatestMessageButton
isMessageListScrolledToBottom={isMessageListScrolledToBottom}
isNotAtLatestMessageSet={hasMoreNewer && messages.length > 0}
onClick={scrollToBottom}
/>
</div>
</DialogManagerProvider>
{TypingIndicator && <TypingIndicator />}
<NotificationList panel={notificationTarget} />
</MessageListMainPanel>
{giphyPreviewMessage && <GiphyPreviewMessage message={giphyPreviewMessage} />}
</MessageTranslationViewProvider>
</VirtualizedMessageListContextProvider>
);
};
export type VirtualizedMessageListProps = Partial<
Pick<MessageProps, PropsDrilledToMessage>
> & {
/** Additional props to be passed the underlying [`react-virtuoso` virtualized list dependency](https://virtuoso.dev/virtuoso-api-reference/) */
additionalVirtuosoProps?: VirtuosoProps<UnknownType, VirtuosoContext>;
/** If true, picking a reaction from the `ReactionSelector` component will close the selector */
closeReactionSelectorOnClick?: boolean;
/** Custom render function, if passed, certain UI props are ignored */
customMessageRenderer?: (
messageList: RenderedMessage[],
index: number,
) => React.ReactElement;
/** @deprecated Use additionalVirtuosoProps.defaultItemHeight instead. Will be removed with next major release - `v11.0.0`.
* If set, the default item height is used for the calculation of the total list height. Use if you expect messages with a lot of height variance
* */
defaultItemHeight?: number;
/** Disables the injection of date separator components in MessageList, defaults to `true` */
disableDateSeparator?: boolean;
/** Callback function to set group styles for each message */
groupStyles?: (
message: RenderedMessage,
previousMessage: RenderedMessage,
nextMessage: RenderedMessage,
noGroupByUser: boolean,
maxTimeBetweenGroupedMessages?: number,
) => GroupStyle;
// /** Whether or not the list has more items to load */
// hasMore?: boolean;
// /** Whether or not the list has newer items to load */
// hasMoreNewer?: boolean;
/**
* @deprecated Use additionalVirtuosoProps.components.Header to override default component rendered above the list ove messages.
* Element to be rendered at the top of the thread message list. By default, these are the Message and ThreadStart components
*/
head?: React.ReactElement;
/** Hides the `MessageDeleted` components from the list, defaults to `false` */
hideDeletedMessages?: boolean;
/** Hides the `DateSeparator` component when new messages are received in a channel that's watched but not active, defaults to false */
hideNewMessageSeparator?: boolean;
// /** Whether or not the list is currently loading more items */
// loadingMore?: boolean;
// /** Whether or not the list is currently loading newer items */
// loadingMoreNewer?: boolean;
/** Function called when more messages are to be loaded. */
// loadMore?: () => Promise<void>;
/** Function called when new messages are to be loaded. */
// loadMoreNewer?: () => Promise<void>;
/** Maximum time in milliseconds that should occur between messages to still consider them grouped together */
maxTimeBetweenGroupedMessages?: number;
/** Custom UI component to display a message, defaults to and accepts same props as [MessageSimple](https://github.com/GetStream/stream-chat-react/blob/master/src/components/Message/MessageSimple.tsx) */
Message?: React.ComponentType<MessageUIComponentProps>;
// /** The limit to use when paginating messages */
// messageLimit?: number;
/** Optional prop to override the messages available from the active message paginator. */
messages?: LocalMessage[];
/**
* @deprecated Use additionalVirtuosoProps.overscan instead. Will be removed with next major release - `v11.0.0`.
* The amount of extra content the list should render in addition to what's necessary to fill in the viewport
*/
overscan?: number;
/** Keep track of read receipts for each message sent by the user. When disabled, only the last own message delivery / read status is rendered. */
returnAllReadData?: boolean;
/**
* Allows to review changes introduced to messages array on per message basis (e.g. date separator injected before a message).
* The array returned from the function is appended to the array of messages that are later rendered into React elements in the `VirtualizedMessageList`.
*/
reviewProcessedMessage?: ProcessMessagesParams['reviewProcessedMessage'];
/**
* @deprecated Pass additionalVirtuosoProps.scrollSeekConfiguration and specify the placeholder in additionalVirtuosoProps.components.ScrollSeekPlaceholder instead. Will be removed with next major release - `v11.0.0`.
* Performance improvement by showing placeholders if user scrolls fast through list.
* it can be used like this:
* ```
* {
* enter: (velocity) => Math.abs(velocity) > 120,
* exit: (velocity) => Math.abs(velocity) < 40,
* change: () => null,
* placeholder: ({index, height})=> <div style={{height: height + "px"}}>{index}</div>,
* }
* ```
*/
scrollSeekPlaceHolder?: ScrollSeekConfiguration & {
placeholder: React.ComponentType<ScrollSeekPlaceholderProps>;
};
/** When `true`, the list will scroll to the latest message when the window regains focus */
scrollToLatestMessageOnFocus?: boolean;
/** If true, the Giphy preview will render as a separate component above the `MessageInput`, rather than inline with the other messages in the list */
separateGiphyPreview?: boolean;
/** If true, group messages belonging to the same user, otherwise show each message individually */
shouldGroupByUser?: boolean;
/**
* The floating notification informing about unread messages will be shown when the
* UnreadMessagesSeparator is not visible. The default is false, that means the notification
* is shown only when viewing unread messages.
*/
showUnreadNotificationAlways?: boolean;
/** The scrollTo behavior when new messages appear. Use `"smooth"` for regular chat channels, and `"auto"` (which results in instant scroll to bottom) if you expect high throughput. */
stickToBottomScrollBehavior?: 'smooth' | 'auto';
/** If true, prevents autoscroll-to-bottom behavior on new messages. */
suppressAutoscroll?: boolean;
};
/**
* The VirtualizedMessageList component renders a list of messages in a virtualized list.
* It is a consumer of the React contexts set in [Channel](https://github.com/GetStream/stream-chat-react/blob/master/src/components/Channel/Channel.tsx).
*/
export function VirtualizedMessageList(props: VirtualizedMessageListProps) {
const channel = useChannel();
const { read } = useStateStore(channel?.state.readStore, channelReadSelector) ?? {};
const messages = props.messages; // || contextMessages;
return (
<AriaLiveRegion>
<VirtualizedMessageListWithContext
channel={channel}
// channelUnreadUiState={props.channelUnreadUiState ?? channelUnreadUiState}
// hasMore={!!hasMore}
// hasMoreNewer={!!hasMoreNewer}
// jumpToLatestMessage={jumpToLatestMessage}
// loadingMore={!!loadingMore}
// loadingMoreNewer={!!loadingMoreNewer}
// loadMore={loadMore}
// loadMoreNewer={loadMoreNewer}
messages={messages}
read={read}
{...props}
/>
</AriaLiveRegion>
);
}