UNPKG

@sendbird/uikit-react-native

Version:

Sendbird UIKit for React Native: A feature-rich and customizable chat UI kit with messaging, channel management, and user authentication.

339 lines 15 kB
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); } import React, { useCallback, useContext, useEffect, useRef, useState } from 'react'; import { useToast } from '@sendbird/uikit-react-native-foundation'; import { useGroupChannelHandler } from '@sendbird/uikit-tools'; import { confirmAndMarkAsRead, isDifferentChannel, useFreshCallback, useIsFirstMount } from '@sendbird/uikit-utils'; import ChannelMessageList from '../../../components/ChannelMessageList'; import { MESSAGE_FOCUS_ANIMATION_DELAY, MESSAGE_SEARCH_SAFE_SCROLL_DELAY } from '../../../constants'; import { useLocalization, useSendbirdChat } from '../../../hooks/useContext'; import { GroupChannelContexts } from '../module/moduleContext'; const GroupChannelMessageList = props => { const toast = useToast(); const { STRINGS } = useLocalization(); const { sdk, sbOptions, groupChannelFragmentOptions } = useSendbirdChat(); const { setMessageToEdit, setMessageToReply } = useContext(GroupChannelContexts.Fragment); const groupChannelPubSub = useContext(GroupChannelContexts.PubSub); const { flatListRef, lazyScrollToBottom, lazyScrollToMessageId, onPressReplyMessageInThread } = useContext(GroupChannelContexts.MessageList); const isFirstMount = useIsFirstMount(); const hasSeenNewLineRef = useRef(false); const isNewLineInViewportRef = useRef(false); const isNewLineExistInChannelRef = useRef(false); const scrolledAwayFromBottomRef = useRef(false); const [isVisibleUnreadMessageFloating, setIsVisibleUnreadMessageFloating] = useState(false); const viewableMessages = useRef(); const hasUserMarkedAsUnreadRef = useRef(false); const [unreadFirstMessage, setUnreadFirstMessage] = useState(undefined); const pendingBottomReachedRef = useRef(null); const updateHasSeenNewLine = useCallback(hasSeenNewLine => { if (hasSeenNewLineRef.current !== hasSeenNewLine) { var _props$onNewLineSeenC; hasSeenNewLineRef.current = hasSeenNewLine; (_props$onNewLineSeenC = props.onNewLineSeenChange) === null || _props$onNewLineSeenC === void 0 || _props$onNewLineSeenC.call(props, hasSeenNewLine); } }, [props.onNewLineSeenChange]); const updateHasUserMarkedAsUnread = useCallback(hasUserMarkedAsUnread => { if (hasUserMarkedAsUnreadRef.current !== hasUserMarkedAsUnread) { var _props$onUserMarkedAs; hasUserMarkedAsUnreadRef.current = hasUserMarkedAsUnread; (_props$onUserMarkedAs = props.onUserMarkedAsUnreadChange) === null || _props$onUserMarkedAs === void 0 || _props$onUserMarkedAs.call(props, hasUserMarkedAsUnread); } }, [props.onUserMarkedAsUnreadChange]); const scrollToMessageWithCreatedAt = useFreshCallback((createdAt, focusAnimated, timeout) => { const foundMessage = props.messages.find(it => it.createdAt === createdAt); const isIncludedInList = !!foundMessage; pendingBottomReachedRef.current = null; if (isIncludedInList) { if (focusAnimated) { setTimeout(() => props.onUpdateSearchItem({ startingPoint: createdAt }), MESSAGE_FOCUS_ANIMATION_DELAY); } pendingBottomReachedRef.current = { timeout, timestamp: Date.now() }; lazyScrollToMessageId({ messageId: foundMessage.messageId, animated: true, timeout }); } else { if (props.channel.messageOffsetTimestamp <= createdAt) { if (focusAnimated) { props.onUpdateSearchItem({ startingPoint: createdAt }); } props.onResetMessageListWithStartingPoint(createdAt).catch(_ => {}); } else { return false; } } return true; }); const onScrolledAwayFromBottom = useFreshCallback(value => { scrolledAwayFromBottomRef.current = value; props.onScrolledAwayFromBottom(value); }); const scrollToBottom = useFreshCallback(async (animated = false) => { if (props.hasNext()) { props.onUpdateSearchItem(undefined); onScrolledAwayFromBottom(false); await props.onResetMessageList().catch(_ => {}); onScrolledAwayFromBottom(false); lazyScrollToBottom({ animated }); } else { lazyScrollToBottom({ animated }); } }); const onPressUnreadMessagesFloatingCloseButton = useCallback(() => { var _props$resetNewMessag; updateHasSeenNewLine(true); updateHasUserMarkedAsUnread(false); (_props$resetNewMessag = props.resetNewMessages) === null || _props$resetNewMessag === void 0 || _props$resetNewMessag.call(props); confirmAndMarkAsRead([props.channel]); }, [updateHasSeenNewLine, updateHasUserMarkedAsUnread, props.channel.url, props.resetNewMessages]); const getPrevNonSilentMessage = useCallback((messages, prevMessageIndex) => { if (messages.length <= prevMessageIndex) { return null; } const prevMessage = messages[prevMessageIndex]; if (prevMessage) { if (prevMessage.silent) { return getPrevNonSilentMessage(messages, prevMessageIndex + 1); } else { return prevMessage; } } return null; }, []); const findFirstUnreadMessage = useFreshCallback(isNewLineExistInChannel => { if (!sbOptions.uikit.groupChannel.channel.enableMarkAsUnread || !isNewLineExistInChannel) { return; } return props.messages.find((msg, index) => { var _props$hasPrevious; if (msg.silent) { return false; } const isMarkedAsUnreadMessage = props.channel.myLastRead === msg.createdAt - 1; if (isMarkedAsUnreadMessage) { return true; } const prevNonSilentMessage = getPrevNonSilentMessage(props.messages, index + 1); const hasNoPreviousAndNoPrevMessage = !((_props$hasPrevious = props.hasPrevious) !== null && _props$hasPrevious !== void 0 && _props$hasPrevious.call(props)) && prevNonSilentMessage == null; const prevMessageIsRead = prevNonSilentMessage != null && prevNonSilentMessage.createdAt <= props.channel.myLastRead; const isMessageUnread = props.channel.myLastRead < msg.createdAt; return (hasNoPreviousAndNoPrevMessage || prevMessageIsRead) && isMessageUnread; }); }); useEffect(() => { if (!unreadFirstMessage) { const foundUnreadFirstMessage = findFirstUnreadMessage(props.isNewLineExistInChannel ?? false); if (foundUnreadFirstMessage) { processNewLineVisibility(foundUnreadFirstMessage); setUnreadFirstMessage(foundUnreadFirstMessage); } } }, [props.messages, props.channel.myLastRead, sbOptions.uikit.groupChannel.channel.enableMarkAsUnread]); const processNewLineVisibility = useFreshCallback(unreadFirstMsg => { var _viewableMessages$cur; const isNewLineInViewport = !!((_viewableMessages$cur = viewableMessages.current) !== null && _viewableMessages$cur !== void 0 && _viewableMessages$cur.some(message => message.messageId === (unreadFirstMsg === null || unreadFirstMsg === void 0 ? void 0 : unreadFirstMsg.messageId))); if (isNewLineInViewportRef.current !== isNewLineInViewport) { isNewLineInViewportRef.current = isNewLineInViewport; updateUnreadMessagesFloatingProps(); if (!isNewLineInViewport || hasSeenNewLineRef.current) { return; } updateHasSeenNewLine(true); if (hasUserMarkedAsUnreadRef.current) { return; } if (0 < props.newMessages.length) { props.channel.markAsUnread(props.newMessages[0]); } else { props.channel.markAsRead(); } } }); const onViewableItemsChanged = useFreshCallback(async info => { if (!sbOptions.uikit.groupChannel.channel.enableMarkAsUnread) { return; } viewableMessages.current = info.viewableItems.filter(token => token.item).map(token => token.item); processNewLineVisibility(unreadFirstMessage); }); const onPressMarkAsUnreadMessage = useCallback(async message => { if (sbOptions.uikit.groupChannel.channel.enableMarkAsUnread && message) { await props.channel.markAsUnread(message); updateHasUserMarkedAsUnread(true); } }, [sbOptions.uikit.groupChannel.channel.enableMarkAsUnread, updateHasUserMarkedAsUnread]); useEffect(() => { isNewLineExistInChannelRef.current = !!props.isNewLineExistInChannel && !!viewableMessages.current; }, [props.isNewLineExistInChannel, viewableMessages.current]); const unreadMessagesFloatingPropsRef = useRef(); const updateUnreadMessagesFloatingProps = useFreshCallback(() => { const canAutoMarkAsRead = !scrolledAwayFromBottomRef.current && !hasUserMarkedAsUnreadRef.current && (hasSeenNewLineRef.current || !isNewLineExistInChannelRef.current); unreadMessagesFloatingPropsRef.current = { visible: sbOptions.uikit.groupChannel.channel.enableMarkAsUnread && !canAutoMarkAsRead && isNewLineExistInChannelRef.current && 0 < props.channel.unreadMessageCount && !isNewLineInViewportRef.current, onPressClose: onPressUnreadMessagesFloatingCloseButton, unreadMessageCount: props.channel.unreadMessageCount }; if (isVisibleUnreadMessageFloating !== unreadMessagesFloatingPropsRef.current.visible) { setIsVisibleUnreadMessageFloating(unreadMessagesFloatingPropsRef.current.visible); } }); useEffect(() => { updateUnreadMessagesFloatingProps(); }, [isNewLineExistInChannelRef.current, props.channel.unreadMessageCount, sbOptions.uikit.groupChannel.channel.enableMarkAsUnread]); useGroupChannelHandler(sdk, { onReactionUpdated(channel, event) { if (isDifferentChannel(channel, props.channel)) return; const recentMessage = props.messages[0]; const isRecentMessage = recentMessage && recentMessage.messageId === event.messageId; const scrollReachedBottomAndCanScroll = !props.scrolledAwayFromBottom && !props.hasNext(); if (isRecentMessage && scrollReachedBottomAndCanScroll) { lazyScrollToBottom({ animated: true, timeout: 250 }); } } }); useEffect(() => { return groupChannelPubSub.subscribe(({ type, data }) => { switch (type) { case 'TYPING_BUBBLE_RENDERED': case 'MESSAGES_RECEIVED': { if (!props.scrolledAwayFromBottom) { scrollToBottom(true); } break; } case 'MESSAGES_UPDATED': { const lastMessage = props.channel.lastMessage; const [updatedMessage] = data.messages; const lastMessageUpdated = updatedMessage && lastMessage && lastMessage.messageId === updatedMessage.messageId; const isMaybeStreaming = props.channel.hasAiBot && lastMessageUpdated; if (isMaybeStreaming) { scrollToBottom(false); } else if (!props.scrolledAwayFromBottom && lastMessageUpdated) { scrollToBottom(true); } break; } case 'MESSAGE_SENT_SUCCESS': case 'MESSAGE_SENT_PENDING': { scrollToBottom(false); break; } case 'ON_MARKED_AS_READ_BY_CURRENT_USER': { updateUnreadMessagesFloatingProps(); break; } case 'ON_MARKED_AS_UNREAD_BY_CURRENT_USER': { isNewLineExistInChannelRef.current = true; const foundFirstUnreadMessage = findFirstUnreadMessage(true); processNewLineVisibility(foundFirstUnreadMessage); setUnreadFirstMessage(foundFirstUnreadMessage); if (!props.scrolledAwayFromBottom) { scrollToBottom(true); } break; } } }); }, [props.scrolledAwayFromBottom]); useEffect(() => { return groupChannelFragmentOptions.pubsub.subscribe(payload => { switch (payload.type) { case 'OVERRIDE_SEARCH_ITEM_STARTING_POINT': { scrollToMessageWithCreatedAt(payload.data.startingPoint, false, MESSAGE_SEARCH_SAFE_SCROLL_DELAY); break; } } }); }, []); useEffect(() => { // Only trigger once when message list mount with initial props.searchItem // - Search screen + searchItem > mount message list // - Reset message list + searchItem > re-mount message list if (isFirstMount && props.searchItem) { scrollToMessageWithCreatedAt(props.searchItem.startingPoint, false, MESSAGE_SEARCH_SAFE_SCROLL_DELAY); } }, [isFirstMount]); const onPressParentMessage = useFreshCallback((parentMessage, childMessage) => { if (onPressReplyMessageInThread && sbOptions.uikit.groupChannel.channel.replyType === 'thread' && sbOptions.uikit.groupChannel.channel.threadReplySelectType === 'thread') { if (parentMessage.createdAt >= props.channel.messageOffsetTimestamp) { onPressReplyMessageInThread(parentMessage, childMessage.createdAt); } else { toast.show(STRINGS.TOAST.FIND_PARENT_MSG_ERROR, 'error'); } } else { const canScrollToParent = scrollToMessageWithCreatedAt(parentMessage.createdAt, true, 0); if (!canScrollToParent) toast.show(STRINGS.TOAST.FIND_PARENT_MSG_ERROR, 'error'); } }); const onBottomReached = useFreshCallback(() => { if (props.hasNext()) { if (pendingBottomReachedRef.current) { const currentTime = Date.now(); const elapsedTime = currentTime - pendingBottomReachedRef.current.timestamp; const timeoutThreshold = 500; if (elapsedTime >= pendingBottomReachedRef.current.timeout + timeoutThreshold) { var _props$onBottomReache; (_props$onBottomReache = props.onBottomReached) === null || _props$onBottomReache === void 0 || _props$onBottomReache.call(props); pendingBottomReachedRef.current = null; } } else { var _props$onBottomReache2; (_props$onBottomReache2 = props.onBottomReached) === null || _props$onBottomReache2 === void 0 || _props$onBottomReache2.call(props); } } }); return /*#__PURE__*/React.createElement(ChannelMessageList, _extends({}, props, { ref: flatListRef, onScrolledAwayFromBottom: onScrolledAwayFromBottom, onReplyMessage: setMessageToReply, onReplyInThreadMessage: setMessageToReply, onEditMessage: setMessageToEdit, onViewableItemsChanged: onViewableItemsChanged, onPressParentMessage: onPressParentMessage, onPressNewMessagesButton: scrollToBottom, onPressScrollToBottomButton: scrollToBottom, onPressMarkAsUnreadMessage: onPressMarkAsUnreadMessage, onBottomReached: onBottomReached, unreadFirstMessage: unreadFirstMessage, unreadMessagesFloatingProps: unreadMessagesFloatingPropsRef.current })); }; export default /*#__PURE__*/React.memo(GroupChannelMessageList); //# sourceMappingURL=GroupChannelMessageList.js.map