-
Notifications
You must be signed in to change notification settings - Fork 283
/
Copy pathMessageList.tsx
394 lines (363 loc) Β· 15.6 KB
/
MessageList.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
import React from 'react';
import {
useEnrichedMessages,
useMessageListElements,
useScrollLocationLogic,
useUnreadMessagesNotification,
} from './hooks/MessageList';
import { useMarkRead } from './hooks/useMarkRead';
import { MessageNotification as DefaultMessageNotification } from './MessageNotification';
import { MessageListNotifications as DefaultMessageListNotifications } from './MessageListNotifications';
import { UnreadMessagesNotification as DefaultUnreadMessagesNotification } from './UnreadMessagesNotification';
import {
ChannelActionContextValue,
useChannelActionContext,
} from '../../context/ChannelActionContext';
import {
ChannelStateContextValue,
useChannelStateContext,
} from '../../context/ChannelStateContext';
import { useChatContext } from '../../context/ChatContext';
import { useComponentContext } from '../../context/ComponentContext';
import { MessageListContextProvider } from '../../context/MessageListContext';
import { EmptyStateIndicator as DefaultEmptyStateIndicator } from '../EmptyStateIndicator';
import { InfiniteScroll, InfiniteScrollProps } from '../InfiniteScrollPaginator/InfiniteScroll';
import { LoadingIndicator as DefaultLoadingIndicator } from '../Loading';
import { defaultPinPermissions, MESSAGE_ACTIONS } from '../Message/utils';
import { TypingIndicator as DefaultTypingIndicator } from '../TypingIndicator';
import { MessageListMainPanel } from './MessageListMainPanel';
import type { GroupStyle } from './utils';
import { defaultRenderMessages, MessageRenderer } from './renderMessages';
import type { MessageProps } from '../Message/types';
import type { StreamMessage } from '../../context/ChannelStateContext';
import type { DefaultStreamChatGenerics } from '../../types/types';
import { DEFAULT_NEXT_CHANNEL_PAGE_SIZE } from '../../constants/limits';
type MessageListWithContextProps<
StreamChatGenerics extends DefaultStreamChatGenerics = DefaultStreamChatGenerics
> = Omit<ChannelStateContextValue<StreamChatGenerics>, 'members' | 'mutes' | 'watchers'> &
MessageListProps<StreamChatGenerics>;
const MessageListWithContext = <
StreamChatGenerics extends DefaultStreamChatGenerics = DefaultStreamChatGenerics
>(
props: MessageListWithContextProps<StreamChatGenerics>,
) => {
const {
channel,
channelUnreadUiState,
disableDateSeparator = false,
groupStyles,
hideDeletedMessages = false,
hideNewMessageSeparator = false,
internalInfiniteScrollProps,
messageActions = Object.keys(MESSAGE_ACTIONS),
messages = [],
notifications,
noGroupByUser = false,
pinPermissions = defaultPinPermissions, // @deprecated in favor of `channelCapabilities` - TODO: remove in next major release
returnAllReadData = false,
threadList = false,
unsafeHTML = false,
headerPosition,
read,
renderMessages = defaultRenderMessages,
messageLimit = DEFAULT_NEXT_CHANNEL_PAGE_SIZE,
loadMore: loadMoreCallback,
loadMoreNewer: loadMoreNewerCallback,
hasMoreNewer = false,
showUnreadNotificationAlways,
suppressAutoscroll,
highlightedMessageId,
jumpToLatestMessage = () => Promise.resolve(),
} = props;
const [listElement, setListElement] = React.useState<HTMLDivElement | null>(null);
const [ulElement, setUlElement] = React.useState<HTMLUListElement | null>(null);
const { customClasses } = useChatContext<StreamChatGenerics>('MessageList');
const {
EmptyStateIndicator = DefaultEmptyStateIndicator,
LoadingIndicator = DefaultLoadingIndicator,
MessageListNotifications = DefaultMessageListNotifications,
MessageNotification = DefaultMessageNotification,
TypingIndicator = DefaultTypingIndicator,
UnreadMessagesNotification = DefaultUnreadMessagesNotification,
} = useComponentContext<StreamChatGenerics>('MessageList');
const loadMoreScrollThreshold = internalInfiniteScrollProps?.threshold || 250;
const {
hasNewMessages,
isMessageListScrolledToBottom,
onScroll,
scrollToBottom,
wrapperRect,
} = useScrollLocationLogic({
hasMoreNewer,
listElement,
loadMoreScrollThreshold,
messages,
scrolledUpThreshold: props.scrolledUpThreshold,
suppressAutoscroll,
});
const { show: showUnreadMessagesNotification } = useUnreadMessagesNotification({
isMessageListScrolledToBottom,
showAlways: !!showUnreadNotificationAlways,
unreadCount: channelUnreadUiState?.unread_messages,
});
useMarkRead({
isMessageListScrolledToBottom,
messageListIsThread: threadList,
unreadCount: channelUnreadUiState?.unread_messages ?? 0,
wasMarkedUnread: !!channelUnreadUiState?.first_unread_message_id,
});
const { messageGroupStyles, messages: enrichedMessages } = useEnrichedMessages({
channel,
disableDateSeparator,
groupStyles,
headerPosition,
hideDeletedMessages,
hideNewMessageSeparator,
messages,
noGroupByUser,
});
const elements = useMessageListElements({
channelUnreadUiState,
enrichedMessages,
internalMessageProps: {
additionalMessageInputProps: props.additionalMessageInputProps,
closeReactionSelectorOnClick: props.closeReactionSelectorOnClick,
customMessageActions: props.customMessageActions,
disableQuotedMessages: props.disableQuotedMessages,
formatDate: props.formatDate,
getDeleteMessageErrorNotification: props.getDeleteMessageErrorNotification,
getFlagMessageErrorNotification: props.getFlagMessageErrorNotification,
getFlagMessageSuccessNotification: props.getFlagMessageSuccessNotification,
getMarkMessageUnreadErrorNotification: props.getMarkMessageUnreadErrorNotification,
getMarkMessageUnreadSuccessNotification: props.getMarkMessageUnreadSuccessNotification,
getMuteUserErrorNotification: props.getMuteUserErrorNotification,
getMuteUserSuccessNotification: props.getMuteUserSuccessNotification,
getPinMessageErrorNotification: props.getPinMessageErrorNotification,
Message: props.Message,
messageActions,
messageListRect: wrapperRect,
onlySenderCanEdit: props.onlySenderCanEdit,
onMentionsClick: props.onMentionsClick,
onMentionsHover: props.onMentionsHover,
onUserClick: props.onUserClick,
onUserHover: props.onUserHover,
openThread: props.openThread,
pinPermissions,
renderText: props.renderText,
retrySendMessage: props.retrySendMessage,
unsafeHTML,
},
messageGroupStyles,
read,
renderMessages,
returnAllReadData,
threadList,
});
const messageListClass = customClasses?.messageList || 'str-chat__list';
const threadListClass = threadList
? customClasses?.threadList || 'str-chat__list--thread str-chat__thread-list'
: '';
const loadMore = React.useCallback(() => {
if (loadMoreCallback) {
loadMoreCallback(messageLimit);
}
}, [loadMoreCallback, messageLimit]);
const loadMoreNewer = React.useCallback(() => {
if (loadMoreNewerCallback) {
loadMoreNewerCallback(messageLimit);
}
}, [loadMoreNewerCallback, messageLimit]);
const scrollToBottomFromNotification = React.useCallback(async () => {
if (hasMoreNewer) {
await jumpToLatestMessage();
} else {
scrollToBottom();
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [scrollToBottom, hasMoreNewer]);
React.useLayoutEffect(() => {
if (highlightedMessageId) {
const element = ulElement?.querySelector(`[data-message-id='${highlightedMessageId}']`);
element?.scrollIntoView({ block: 'center' });
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [highlightedMessageId]);
const showEmptyStateIndicator = elements.length === 0 && !threadList;
return (
<MessageListContextProvider value={{ listElement, scrollToBottom }}>
<MessageListMainPanel>
{!threadList && showUnreadMessagesNotification && (
<UnreadMessagesNotification unreadCount={channelUnreadUiState?.unread_messages} />
)}
<div
className={`${messageListClass} ${threadListClass}`}
onScroll={onScroll}
ref={setListElement}
tabIndex={0}
>
{showEmptyStateIndicator ? (
<EmptyStateIndicator
key={'empty-state-indicator'}
listType={threadList ? 'thread' : 'message'}
/>
) : (
<InfiniteScroll
className='str-chat__reverse-infinite-scroll str-chat__message-list-scroll'
data-testid='reverse-infinite-scroll'
hasNextPage={props.hasMoreNewer}
hasPreviousPage={props.hasMore}
head={props.head}
isLoading={props.loadingMore}
loader={
<div className='str-chat__list__loading' key='loading-indicator'>
{props.loadingMore && <LoadingIndicator size={20} />}
</div>
}
loadNextPage={loadMoreNewer}
loadPreviousPage={loadMore}
{...props.internalInfiniteScrollProps}
threshold={loadMoreScrollThreshold}
>
<ul className='str-chat__ul' ref={setUlElement}>
{elements}
</ul>
<TypingIndicator threadList={threadList} />
<div key='bottom' />
</InfiniteScroll>
)}
</div>
</MessageListMainPanel>
<MessageListNotifications
hasNewMessages={hasNewMessages}
isMessageListScrolledToBottom={isMessageListScrolledToBottom}
isNotAtLatestMessageSet={hasMoreNewer}
MessageNotification={MessageNotification}
notifications={notifications}
scrollToBottom={scrollToBottomFromNotification}
threadList={threadList}
unreadCount={threadList ? undefined : channelUnreadUiState?.unread_messages}
/>
</MessageListContextProvider>
);
};
type PropsDrilledToMessage =
| 'additionalMessageInputProps'
| 'closeReactionSelectorOnClick'
| 'customMessageActions'
| 'disableQuotedMessages'
| 'formatDate'
| 'getDeleteMessageErrorNotification'
| 'getFlagMessageErrorNotification'
| 'getFlagMessageSuccessNotification'
| 'getMarkMessageUnreadErrorNotification'
| 'getMarkMessageUnreadSuccessNotification'
| 'getMuteUserErrorNotification'
| 'getMuteUserSuccessNotification'
| 'getPinMessageErrorNotification'
| 'Message'
| 'messageActions'
| 'onlySenderCanEdit'
| 'onMentionsClick'
| 'onMentionsHover'
| 'onUserClick'
| 'onUserHover'
| 'openThread'
| 'pinPermissions' // @deprecated in favor of `channelCapabilities` - TODO: remove in next major release
| 'renderText'
| 'retrySendMessage'
| 'sortReactions'
| 'sortReactionDetails'
| 'unsafeHTML';
export type MessageListProps<
StreamChatGenerics extends DefaultStreamChatGenerics = DefaultStreamChatGenerics
> = Partial<Pick<MessageProps<StreamChatGenerics>, PropsDrilledToMessage>> & {
/** Disables the injection of date separator components in MessageList, defaults to `false` */
disableDateSeparator?: boolean;
/** Callback function to set group styles for each message */
groupStyles?: (
message: StreamMessage<StreamChatGenerics>,
previousMessage: StreamMessage<StreamChatGenerics>,
nextMessage: StreamMessage<StreamChatGenerics>,
noGroupByUser: boolean,
) => GroupStyle;
/** Whether the list has more items to load */
hasMore?: boolean;
/** Element to be rendered at the top of the thread message list. By default, these are the Message and ThreadStart components */
head?: React.ReactElement;
/** Position to render HeaderComponent */
headerPosition?: number;
/** 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;
/** Overrides the default props passed to [InfiniteScroll](https://github.com/GetStream/stream-chat-react/blob/master/src/components/InfiniteScrollPaginator/InfiniteScroll.tsx) */
internalInfiniteScrollProps?: InfiniteScrollProps;
/** Function called when latest messages should be loaded, after the list has jumped at an earlier message set */
jumpToLatestMessage?: () => Promise<void>;
/** 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, defaults to function stored in [ChannelActionContext](https://getstream.io/chat/docs/sdk/react/contexts/channel_action_context/) */
loadMore?: ChannelActionContextValue['loadMore'] | (() => Promise<void>);
/** Function called when newer messages are to be loaded, defaults to function stored in [ChannelActionContext](https://getstream.io/chat/docs/sdk/react/contexts/channel_action_context/) */
loadMoreNewer?: ChannelActionContextValue['loadMoreNewer'] | (() => Promise<void>);
/** The limit to use when paginating messages */
messageLimit?: number;
/** The messages to render in the list, defaults to messages stored in [ChannelStateContext](https://getstream.io/chat/docs/sdk/react/contexts/channel_state_context/) */
messages?: StreamMessage<StreamChatGenerics>[];
/** If true, turns off message UI grouping by user */
noGroupByUser?: boolean;
/** Overrides the way MessageList renders messages */
renderMessages?: MessageRenderer<StreamChatGenerics>;
/** If true, `readBy` data supplied to the `Message` components will include all user read states per sent message */
returnAllReadData?: boolean;
/**
* The pixel threshold under which the message list is considered to be so near to the bottom,
* so that if a new message is delivered, the list will be scrolled to the absolute bottom.
* Defaults to 200px
*/
scrolledUpThreshold?: number;
/**
* 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;
/** If true, indicates the message list is a thread */
threadList?: boolean; // todo: refactor needed - message list should have a state in which among others it would be optionally flagged as thread
};
/**
* The MessageList component renders a list of Messages.
* It is a consumer of the following contexts:
* - [ChannelStateContext](https://getstream.io/chat/docs/sdk/react/contexts/channel_state_context/)
* - [ChannelActionContext](https://getstream.io/chat/docs/sdk/react/contexts/channel_action_context/)
* - [ComponentContext](https://getstream.io/chat/docs/sdk/react/contexts/component_context/)
* - [TypingContext](https://getstream.io/chat/docs/sdk/react/contexts/typing_context/)
*/
export const MessageList = <
StreamChatGenerics extends DefaultStreamChatGenerics = DefaultStreamChatGenerics
>(
props: MessageListProps<StreamChatGenerics>,
) => {
const {
jumpToLatestMessage,
loadMore,
loadMoreNewer,
} = useChannelActionContext<StreamChatGenerics>('MessageList');
const {
members: membersPropToNotPass, // eslint-disable-line @typescript-eslint/no-unused-vars
mutes: mutesPropToNotPass, // eslint-disable-line @typescript-eslint/no-unused-vars
watchers: watchersPropToNotPass, // eslint-disable-line @typescript-eslint/no-unused-vars
...restChannelStateContext
} = useChannelStateContext<StreamChatGenerics>('MessageList');
return (
<MessageListWithContext<StreamChatGenerics>
jumpToLatestMessage={jumpToLatestMessage}
loadMore={loadMore}
loadMoreNewer={loadMoreNewer}
{...restChannelStateContext}
{...props}
/>
);
};