'use strict';

var React = require('react');
var Channel_context = require('../Channel/context.js');
var ui_PlaceHolder = require('../ui/PlaceHolder.js');
var ui_Icon = require('../ui/Icon.js');
var Channel_components_Message = require('./bundle-Eqd9bAds.js');
var utils = require('./bundle-CrbMqpah.js');
var Channel_utils_getMessagePartsInfo = require('../Channel/utils/getMessagePartsInfo.js');
var index$3 = require('./bundle-DfMlIvtm.js');
var index$2 = require('./bundle-u7wWilEW.js');
var consts = require('./bundle-UAspU0bH.js');
var useSendbirdStateContext = require('../useSendbirdStateContext.js');
var Message_context = require('../Message/context.js');
var index = require('./bundle-OdZXNc-g.js');
var useThrottleCallback = require('./bundle-Njt4gDEW.js');
var ui_TypingIndicatorBubble = require('../ui/TypingIndicatorBubble.js');
var index$1 = require('./bundle-zHDXCFIb.js');

exports.TypingIndicatorType = void 0;
(function (TypingIndicatorType) {
    TypingIndicatorType["Text"] = "text";
    TypingIndicatorType["Bubble"] = "bubble";
})(exports.TypingIndicatorType || (exports.TypingIndicatorType = {}));

var DELAY = 100;
function useSetScrollToBottom(_a) {
    var loading = _a.loading;
    var _b = React.useState(0), scrollBottom = _b[0], setScrollBottom = _b[1];
    React.useEffect(function () {
        if (loading) {
            setScrollBottom(0);
        }
    }, [loading]);
    var scrollCb = function (e) {
        var element = e.target;
        try {
            setScrollBottom(element.scrollHeight - element.scrollTop - element.offsetHeight);
        }
        catch (_a) {
            //
        }
    };
    return {
        scrollBottom: scrollBottom,
        scrollToBottomHandler: useThrottleCallback.useThrottleCallback(scrollCb, DELAY, { trailing: true }),
    };
}

function useScrollBehavior() {
    var _a = Channel_context.useChannelContext(), scrollRef = _a.scrollRef, _b = _a.scrollBehavior, scrollBehavior = _b === void 0 ? 'auto' : _b;
    React.useEffect(function () {
        if (scrollRef.current) {
            scrollRef.current.style.scrollBehavior = scrollBehavior;
        }
    }, [scrollRef.current]);
    return null;
}

/* We operate the CSS files for Channel&GroupChannel modules in the GroupChannel */
var SCROLL_BOTTOM_PADDING = 50;
var MessageList = function (_a) {
    var _b, _c, _d, _e, _f;
    var _g = _a.className, className = _g === void 0 ? '' : _g, renderMessage = _a.renderMessage, renderMessageContent = _a.renderMessageContent, renderPlaceholderEmpty = _a.renderPlaceholderEmpty, renderCustomSeparator = _a.renderCustomSeparator, renderPlaceholderLoader = _a.renderPlaceholderLoader, renderFrozenNotification = _a.renderFrozenNotification;
    var _h = Channel_context.useChannelContext(), allMessages = _h.allMessages, localMessages = _h.localMessages, hasMorePrev = _h.hasMorePrev, hasMoreNext = _h.hasMoreNext, setInitialTimeStamp = _h.setInitialTimeStamp, setAnimatedMessageId = _h.setAnimatedMessageId, setHighLightedMessageId = _h.setHighLightedMessageId, isMessageGroupingEnabled = _h.isMessageGroupingEnabled, scrollRef = _h.scrollRef, onScrollCallback = _h.onScrollCallback, onScrollDownCallback = _h.onScrollDownCallback, messagesDispatcher = _h.messagesDispatcher, messageActionTypes = _h.messageActionTypes, currentGroupChannel = _h.currentGroupChannel, disableMarkAsRead = _h.disableMarkAsRead, filterMessageList = _h.filterMessageList, replyType = _h.replyType, loading = _h.loading, isScrolled = _h.isScrolled, unreadSince = _h.unreadSince, unreadSinceDate = _h.unreadSinceDate, typingMembers = _h.typingMembers;
    var store = useSendbirdStateContext.useSendbirdStateContext();
    var allMessagesFiltered = (typeof filterMessageList === 'function')
        ? allMessages.filter(filterMessageList)
        : allMessages;
    var markAsReadScheduler = store.config.markAsReadScheduler;
    var _j = React.useState(false), isScrollBottom = _j[0], setIsScrollBottom = _j[1];
    useScrollBehavior();
    /**
     * @param {function} callback callback from useHandleOnScrollCallback, it adjusts scroll position
     * */
    var onScroll = function (callback) {
        var element = scrollRef === null || scrollRef === void 0 ? void 0 : scrollRef.current;
        if (element == null) {
            return;
        }
        var scrollTop = element.scrollTop, clientHeight = element.clientHeight, scrollHeight = element.scrollHeight;
        if (hasMorePrev && utils.isAboutSame(scrollTop, 0, consts.SCROLL_BUFFER)) {
            onScrollCallback(callback);
        }
        if (hasMoreNext && utils.isAboutSame(clientHeight + scrollTop, scrollHeight, consts.SCROLL_BUFFER)) {
            onScrollDownCallback(callback);
        }
        if (!disableMarkAsRead
            && utils.isAboutSame(clientHeight + scrollTop, scrollHeight, consts.SCROLL_BUFFER)
            && !!currentGroupChannel) {
            messagesDispatcher({
                type: messageActionTypes.MARK_AS_READ,
                payload: { channel: currentGroupChannel },
            });
            markAsReadScheduler.push(currentGroupChannel);
        }
    };
    var onClickScrollBot = function () {
        var _a, _b, _c, _d, _e;
        setInitialTimeStamp === null || setInitialTimeStamp === void 0 ? void 0 : setInitialTimeStamp(null);
        setAnimatedMessageId === null || setAnimatedMessageId === void 0 ? void 0 : setAnimatedMessageId(null);
        setHighLightedMessageId === null || setHighLightedMessageId === void 0 ? void 0 : setHighLightedMessageId(null);
        if (((_a = scrollRef === null || scrollRef === void 0 ? void 0 : scrollRef.current) === null || _a === void 0 ? void 0 : _a.scrollTop) > -1) {
            scrollRef.current.scrollTop = ((_c = (_b = scrollRef === null || scrollRef === void 0 ? void 0 : scrollRef.current) === null || _b === void 0 ? void 0 : _b.scrollHeight) !== null && _c !== void 0 ? _c : 0) - ((_e = (_d = scrollRef === null || scrollRef === void 0 ? void 0 : scrollRef.current) === null || _d === void 0 ? void 0 : _d.offsetHeight) !== null && _e !== void 0 ? _e : 0);
        }
    };
    /**
     * 1. Move the messsage list scroll
     *    when each message's height is changed by `reactions` OR `showEdit`
     * 2. Keep the scrollBottom value after fetching new message list
     */
    var moveScroll = function (isBottomMessageAffected) {
        if (isBottomMessageAffected === void 0) { isBottomMessageAffected = false; }
        var current = scrollRef === null || scrollRef === void 0 ? void 0 : scrollRef.current;
        if (current) {
            var bottom = current.scrollHeight - current.scrollTop - current.offsetHeight;
            if (scrollBottom < bottom
                && (!isBottomMessageAffected || scrollBottom < consts.SCROLL_BUFFER)) {
                // Move the scroll as much as the height of the message has changed
                current.scrollTop += bottom - scrollBottom;
            }
        }
    };
    var handleOnScroll = index.useHandleOnScrollCallback({
        hasMore: hasMorePrev,
        hasNext: hasMoreNext,
        onScroll: onScroll,
        scrollRef: scrollRef,
    });
    var onScrollReachedEndDetector = index$1.useOnScrollPositionChangeDetector({
        onReachedBottom: function () {
            /**
             * Note that this event is already being called in onScroll() above. However, it is only being called when
             * hasMoreNext is true but it needs to be called when hasNext is false when reached bottom as well.
             */
            if (!hasMoreNext && !disableMarkAsRead && !!currentGroupChannel) {
                messagesDispatcher({
                    type: messageActionTypes.MARK_AS_READ,
                    payload: { channel: currentGroupChannel },
                });
                markAsReadScheduler.push(currentGroupChannel);
            }
            setIsScrollBottom(true);
        },
        onReachedTop: function () {
            setIsScrollBottom(false);
        },
        onInBetween: function () {
            setIsScrollBottom(false);
        },
    });
    var _k = useSetScrollToBottom({ loading: loading }), scrollToBottomHandler = _k.scrollToBottomHandler, scrollBottom = _k.scrollBottom;
    if (loading) {
        return (typeof renderPlaceholderLoader === 'function')
            ? renderPlaceholderLoader()
            : React.createElement(ui_PlaceHolder.default, { type: ui_PlaceHolder.PlaceHolderTypes.LOADING });
    }
    if (allMessagesFiltered.length < 1) {
        if (renderPlaceholderEmpty && typeof renderPlaceholderEmpty === 'function') {
            return renderPlaceholderEmpty();
        }
        return React.createElement(ui_PlaceHolder.default, { className: "sendbird-conversation__no-messages", type: ui_PlaceHolder.PlaceHolderTypes.NO_MESSAGES });
    }
    return (React.createElement(React.Fragment, null,
        !isScrolled && React.createElement(ui_PlaceHolder.default, { type: ui_PlaceHolder.PlaceHolderTypes.LOADING }),
        React.createElement("div", { className: "sendbird-conversation__messages ".concat(className) },
            React.createElement("div", { className: "sendbird-conversation__scroll-container" },
                React.createElement("div", { className: "sendbird-conversation__padding" }),
                React.createElement("div", { className: "sendbird-conversation__messages-padding", ref: scrollRef, onScroll: function (e) {
                        handleOnScroll();
                        scrollToBottomHandler(e);
                        onScrollReachedEndDetector(e);
                    } },
                    allMessagesFiltered.map(function (m, idx) {
                        var _a, _b;
                        var _c = Channel_utils_getMessagePartsInfo.getMessagePartsInfo({
                            allMessages: allMessagesFiltered,
                            replyType: replyType,
                            isMessageGroupingEnabled: isMessageGroupingEnabled,
                            currentIndex: idx,
                            currentMessage: m,
                            currentChannel: currentGroupChannel,
                        }), chainTop = _c.chainTop, chainBottom = _c.chainBottom, hasSeparator = _c.hasSeparator;
                        var isByMe = ((_a = m === null || m === void 0 ? void 0 : m.sender) === null || _a === void 0 ? void 0 : _a.userId) === ((_b = store === null || store === void 0 ? void 0 : store.config) === null || _b === void 0 ? void 0 : _b.userId);
                        return (React.createElement(Message_context.MessageProvider, { message: m, key: m === null || m === void 0 ? void 0 : m.messageId, isByMe: isByMe },
                            React.createElement(Channel_components_Message.Message, { handleScroll: moveScroll, renderMessage: renderMessage, renderMessageContent: renderMessageContent, message: m, hasSeparator: hasSeparator, chainTop: chainTop, chainBottom: chainBottom, renderCustomSeparator: renderCustomSeparator })));
                    }),
                    localMessages.map(function (m, idx) {
                        var _a, _b;
                        var _c = Channel_utils_getMessagePartsInfo.getMessagePartsInfo({
                            allMessages: allMessagesFiltered,
                            replyType: replyType,
                            isMessageGroupingEnabled: isMessageGroupingEnabled,
                            currentIndex: idx,
                            currentMessage: m,
                            currentChannel: currentGroupChannel,
                        }), chainTop = _c.chainTop, chainBottom = _c.chainBottom;
                        var isByMe = ((_a = m === null || m === void 0 ? void 0 : m.sender) === null || _a === void 0 ? void 0 : _a.userId) === ((_b = store === null || store === void 0 ? void 0 : store.config) === null || _b === void 0 ? void 0 : _b.userId);
                        return (React.createElement(Message_context.MessageProvider, { message: m, key: m === null || m === void 0 ? void 0 : m.messageId, isByMe: isByMe },
                            React.createElement(Channel_components_Message.Message, { handleScroll: moveScroll, renderMessage: renderMessage, renderMessageContent: renderMessageContent, message: m, chainTop: chainTop, chainBottom: chainBottom, renderCustomSeparator: renderCustomSeparator })));
                    }),
                    !hasMoreNext
                        && ((_c = (_b = store === null || store === void 0 ? void 0 : store.config) === null || _b === void 0 ? void 0 : _b.groupChannel) === null || _c === void 0 ? void 0 : _c.enableTypingIndicator)
                        && ((_f = (_e = (_d = store === null || store === void 0 ? void 0 : store.config) === null || _d === void 0 ? void 0 : _d.groupChannel) === null || _e === void 0 ? void 0 : _e.typingIndicatorTypes) === null || _f === void 0 ? void 0 : _f.has(exports.TypingIndicatorType.Bubble))
                        && React.createElement(ui_TypingIndicatorBubble, { typingMembers: typingMembers, handleScroll: moveScroll }))),
            (currentGroupChannel === null || currentGroupChannel === void 0 ? void 0 : currentGroupChannel.isFrozen) && (renderFrozenNotification
                ? renderFrozenNotification()
                : React.createElement(index$2.FrozenNotification, { className: "sendbird-conversation__messages__notification" })),
            /**
             * Show unread count IFF scroll is not bottom or is bottom but hasNext is true.
             */
            (!isScrollBottom || hasMoreNext) && (unreadSince || unreadSinceDate) && (React.createElement(index$3.UnreadCount, { className: "sendbird-conversation__messages__notification", count: currentGroupChannel === null || currentGroupChannel === void 0 ? void 0 : currentGroupChannel.unreadMessageCount, time: unreadSince, lastReadAt: unreadSinceDate, onClick: function () {
                    if (scrollRef === null || scrollRef === void 0 ? void 0 : scrollRef.current)
                        scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
                    if (!disableMarkAsRead && !!currentGroupChannel) {
                        markAsReadScheduler.push(currentGroupChannel);
                        messagesDispatcher({
                            type: messageActionTypes.MARK_AS_READ,
                            payload: { channel: currentGroupChannel },
                        });
                    }
                    setInitialTimeStamp(null);
                    setAnimatedMessageId(null);
                    setHighLightedMessageId(null);
                } })),
            // This flag is an unmatched variable
            scrollBottom > SCROLL_BOTTOM_PADDING && (React.createElement("div", { className: "sendbird-conversation__scroll-bottom-button", onClick: onClickScrollBot, onKeyDown: onClickScrollBot, tabIndex: 0, role: "button" },
                React.createElement(ui_Icon.default, { width: "24px", height: "24px", type: ui_Icon.IconTypes.CHEVRON_DOWN, fillColor: ui_Icon.IconColors.PRIMARY }))))));
};

exports.MessageList = MessageList;
//# sourceMappingURL=bundle-fTMJH5JE.js.map
