'use strict';

var React = require('react');
var Channel_context = require('../../ChannelProvider-b1290e55.js');
var ui_PlaceHolder = require('../../index-cf139ee0.js');
var ui_Icon = require('../../ui/Icon.js');
var Channel_components_Message = require('./Message.js');
var index = require('../../index-78e2bb42.js');
var Channel_components_UnreadCount = require('./UnreadCount.js');
var Channel_components_FrozenNotification = require('./FrozenNotification.js');
var _const = require('../../const-77194948.js');
require('../../UserProfileContext-cde95db8.js');
require('prop-types');
require('../../useSendbirdStateContext.js');
require('../../withSendbird.js');
require('../../_rollupPluginBabelHelpers-32557b21.js');
require('../../index-81e19961.js');
require('../../index-f5502150.js');
require('../../topics-5edbb1b2.js');
require('../../index-b32fce67.js');
require('../../tslib.es6-d2ba1a6b.js');
require('../../utils/message/getOutgoingMessageState.js');
require('../../compareIds-32f97a73.js');
require('@sendbird/chat/groupChannel');
require('../../uuid-28e4a814.js');
require('@sendbird/chat/message');
require('../../ui/ContextMenu.js');
require('react-dom');
require('../../ui/SortByRow.js');
require('../../index-1b11bb85.js');
require('../../stringSet-ddd351f0.js');
require('../../ui/ReactionButton.js');
require('../../ui/ImageRenderer.js');
require('../../consts-f82aaae9.js');
require('../../LocalizationContext-1f669b3c.js');
require('../../ui/Loader.js');
require('./SuggestedMentionList.js');
require('../../ui/Avatar.js');
require('../../const-fe838b59.js');
require('../../ThreadProvider-5eafb9ef.js');
require('../../Thread/context/types.js');
require('@sendbird/chat');
require('../../ui/DateSeparator.js');
require('../../color-97cfc61b.js');
require('../../ui/MessageInput.js');
require('react-dom/server');
require('../../ui/IconButton.js');
require('../../ui/Button.js');
require('../../ui/MentionUserLabel.js');
require('dompurify');
require('../../ui/MessageContent.js');
require('../../ui/UserProfile.js');
require('../../sendbirdSelectors.js');
require('../../utils-602ab2fc.js');
require('../../index-b911f8b3.js');
require('../../index-c4869cdb.js');
require('../../ui/MessageItemMenu.js');
require('../../types-3fb94919.js');
require('../../ui/MessageItemReactionMenu.js');
require('../../ui/EmojiReactions.js');
require('../../ui/Tooltip.js');
require('../../ui/TooltipWrapper.js');
require('../../ui/ReactionBadge.js');
require('../../ui/AdminMessage.js');
require('../../ui/TextMessageItemBody.js');
require('../../ui/Word.js');
require('../../ui/LinkLabel.js');
require('../../ui/MentionLabel.js');
require('../../ui/FileMessageItemBody.js');
require('../../ui/TextButton.js');
require('../../MediaQueryContext-130143d7.js');
require('../../ui/ThumbnailMessageItemBody.js');
require('../../ui/OGMessageItemBody.js');
require('../../ui/UnknownMessageItemBody.js');
require('../../ui/QuoteMessage.js');
require('../../useLongPress-778d6f15.js');
require('../../ui/BottomSheet.js');
require('../../index-577c9a9b.js');
require('../../ui/ThreadReplies.js');
require('../../ui/VoiceMessageItemBody.js');
require('../../ui/ProgressBar.js');
require('../../VoicePlayer/useVoicePlayer.js');
require('../../index-26ff28a8.js');
require('../../VoiceRecorder/context.js');
require('../../lame.all.js');
require('../../ui/PlaybackTime.js');
require('./FileViewer.js');
require('./RemoveMessageModal.js');
require('../../ui/Modal.js');

function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }

var React__default = /*#__PURE__*/_interopDefaultLegacy(React);

var getMessagePartsInfo = function (_a) {
  var _b = _a.allMessages,
      allMessages = _b === void 0 ? [] : _b,
      _c = _a.isMessageGroupingEnabled,
      isMessageGroupingEnabled = _c === void 0 ? true : _c,
      _d = _a.currentIndex,
      currentIndex = _d === void 0 ? 0 : _d,
      _e = _a.currentMessage,
      currentMessage = _e === void 0 ? null : _e,
      _f = _a.currentChannel,
      currentChannel = _f === void 0 ? null : _f,
      _g = _a.replyType,
      replyType = _g === void 0 ? '' : _g;
  var previousMessage = allMessages[currentIndex - 1];
  var nextMessage = allMessages[currentIndex + 1];

  var _h = isMessageGroupingEnabled ? Channel_context.compareMessagesForGrouping(previousMessage, currentMessage, nextMessage, currentChannel, replyType) : [false, false],
      chainTop = _h[0],
      chainBottom = _h[1];

  var previousMessageCreatedAt = previousMessage === null || previousMessage === void 0 ? void 0 : previousMessage.createdAt;
  var currentCreatedAt = currentMessage.createdAt; // https://stackoverflow.com/a/41855608

  var hasSeparator = !(previousMessageCreatedAt && index.isSameDay(currentCreatedAt, previousMessageCreatedAt));
  return {
    chainTop: chainTop,
    chainBottom: chainBottom,
    hasSeparator: hasSeparator
  };
};

var SCROLL_REF_CLASS_NAME = '.sendbird-msg--scroll-ref';

var MessageList = function (_a) {
  var _b = _a.className,
      className = _b === void 0 ? '' : _b,
      renderMessage = _a.renderMessage,
      renderPlaceholderEmpty = _a.renderPlaceholderEmpty,
      renderCustomSeparator = _a.renderCustomSeparator,
      renderPlaceholderLoader = _a.renderPlaceholderLoader;

  var _c = Channel_context.useChannelContext(),
      allMessages = _c.allMessages,
      hasMorePrev = _c.hasMorePrev,
      setInitialTimeStamp = _c.setInitialTimeStamp,
      setAnimatedMessageId = _c.setAnimatedMessageId,
      setHighLightedMessageId = _c.setHighLightedMessageId,
      isMessageGroupingEnabled = _c.isMessageGroupingEnabled,
      scrollRef = _c.scrollRef,
      onScrollCallback = _c.onScrollCallback,
      onScrollDownCallback = _c.onScrollDownCallback,
      messagesDispatcher = _c.messagesDispatcher,
      messageActionTypes = _c.messageActionTypes,
      currentGroupChannel = _c.currentGroupChannel,
      disableMarkAsRead = _c.disableMarkAsRead,
      replyType = _c.replyType,
      loading = _c.loading,
      unreadSince = _c.unreadSince;

  var _d = React.useState(0),
      scrollBottom = _d[0],
      setScrollBottom = _d[1];

  var onScroll = function (e) {
    var element = e.target;
    var scrollTop = element.scrollTop,
        clientHeight = element.clientHeight,
        scrollHeight = element.scrollHeight;

    if (scrollTop === 0) {
      if (!hasMorePrev) {
        return;
      }

      var nodes = scrollRef.current.querySelectorAll(SCROLL_REF_CLASS_NAME);
      var first_1 = nodes && nodes[0];
      onScrollCallback(function (_a) {
        var messages = _a[0];

        if (messages) {
          // https://github.com/scabbiaza/react-scroll-position-on-updating-dom
          // Set block to nearest to prevent unexpected scrolling from outer components
          try {
            first_1.scrollIntoView({
              block: "start",
              inline: "nearest"
            });
          } catch (error) {//
          }
        }
      });
    }

    if (Channel_context.isAboutSame(clientHeight + scrollTop, scrollHeight, _const.MESSAGE_SCROLL_BUFFER)) {
      onScrollDownCallback(function (_a) {
        _a[0];
      });
    } // Save the lastest scroll bottom value


    if (scrollRef === null || scrollRef === void 0 ? void 0 : scrollRef.current) {
      var current = scrollRef === null || scrollRef === void 0 ? void 0 : scrollRef.current;
      setScrollBottom(current.scrollHeight - current.scrollTop - current.offsetHeight);
    }

    if (!disableMarkAsRead && Channel_context.isAboutSame(clientHeight + scrollTop, scrollHeight, _const.MESSAGE_SCROLL_BUFFER)) {
      // Mark as read if scroll is at end
      setTimeout(function () {
        var _a;

        messagesDispatcher({
          type: messageActionTypes.MARK_AS_READ,
          payload: {
            channel: currentGroupChannel
          }
        });

        try {
          (_a = currentGroupChannel === null || currentGroupChannel === void 0 ? void 0 : currentGroupChannel.markAsRead) === null || _a === void 0 ? void 0 : _a.call(currentGroupChannel);
        } catch (_b) {//
        }
      }, 500);
    }
  };

  var onClickScrollBot = function () {
    var _a, _b, _c;

    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 = ((_b = scrollRef === null || scrollRef === void 0 ? void 0 : scrollRef.current) === null || _b === void 0 ? void 0 : _b.scrollHeight) - ((_c = scrollRef === null || scrollRef === void 0 ? void 0 : scrollRef.current) === null || _c === void 0 ? void 0 : _c.offsetHeight);
    }
  };

  var handleScroll = function () {
    var current = scrollRef === null || scrollRef === void 0 ? void 0 : scrollRef.current;

    if (current) {
      var bottom = current.scrollHeight - current.scrollTop - current.offsetHeight;

      if (scrollBottom < bottom && scrollBottom <= _const.MESSAGE_SCROLL_BUFFER) {
        current.scrollTop += bottom - scrollBottom;
      }
    }
  };

  if (loading) {
    return typeof renderPlaceholderLoader === 'function' ? renderPlaceholderLoader() : /*#__PURE__*/React__default["default"].createElement(ui_PlaceHolder.PlaceHolder, {
      type: ui_PlaceHolder.PlaceHolderTypes.LOADING
    });
  }

  if (allMessages.length < 1) {
    if (renderPlaceholderEmpty && typeof renderPlaceholderEmpty === 'function') {
      return renderPlaceholderEmpty();
    }

    return /*#__PURE__*/React__default["default"].createElement(ui_PlaceHolder.PlaceHolder, {
      className: "sendbird-conversation__no-messages",
      type: ui_PlaceHolder.PlaceHolderTypes.NO_MESSAGES
    });
  }

  return /*#__PURE__*/React__default["default"].createElement("div", {
    className: "sendbird-conversation__messages ".concat(className)
  }, /*#__PURE__*/React__default["default"].createElement("div", {
    className: "sendbird-conversation__scroll-container"
  }, /*#__PURE__*/React__default["default"].createElement("div", {
    className: "sendbird-conversation__padding"
  }), /*#__PURE__*/React__default["default"].createElement("div", {
    className: "sendbird-conversation__messages-padding",
    ref: scrollRef,
    onScroll: onScroll
  }, allMessages.map(function (m, idx) {
    var _a = getMessagePartsInfo({
      allMessages: allMessages,
      replyType: replyType,
      isMessageGroupingEnabled: isMessageGroupingEnabled,
      currentIndex: idx,
      currentMessage: m,
      currentChannel: currentGroupChannel
    }),
        chainTop = _a.chainTop,
        chainBottom = _a.chainBottom,
        hasSeparator = _a.hasSeparator;

    return /*#__PURE__*/React__default["default"].createElement(Channel_components_Message, {
      key: m === null || m === void 0 ? void 0 : m.messageId,
      handleScroll: handleScroll,
      renderMessage: renderMessage,
      message: m,
      hasSeparator: hasSeparator,
      chainTop: chainTop,
      chainBottom: chainBottom,
      renderCustomSeparator: renderCustomSeparator
    });
  }))), (currentGroupChannel === null || currentGroupChannel === void 0 ? void 0 : currentGroupChannel.isFrozen) && /*#__PURE__*/React__default["default"].createElement(Channel_components_FrozenNotification, {
    className: "sendbird-conversation__messages__notification"
  }), /*#__PURE__*/React__default["default"].createElement(Channel_components_UnreadCount, {
    className: "sendbird-conversation__messages__notification",
    count: currentGroupChannel === null || currentGroupChannel === void 0 ? void 0 : currentGroupChannel.unreadMessageCount,
    time: unreadSince,
    onClick: function () {
      var _a, _b, _c;

      if ((_a = scrollRef === null || scrollRef === void 0 ? void 0 : scrollRef.current) === null || _a === void 0 ? void 0 : _a.scrollTop) {
        scrollRef.current.scrollTop = ((_b = scrollRef === null || scrollRef === void 0 ? void 0 : scrollRef.current) === null || _b === void 0 ? void 0 : _b.scrollHeight) - ((_c = scrollRef === null || scrollRef === void 0 ? void 0 : scrollRef.current) === null || _c === void 0 ? void 0 : _c.offsetHeight);
      }

      if (!disableMarkAsRead) {
        try {
          currentGroupChannel === null || currentGroupChannel === void 0 ? void 0 : currentGroupChannel.markAsRead();
        } catch (_d) {//
        }

        messagesDispatcher({
          type: messageActionTypes.MARK_AS_READ,
          payload: {
            channel: currentGroupChannel
          }
        });
      }

      setInitialTimeStamp(null);
      setAnimatedMessageId(null);
      setHighLightedMessageId(null);
    }
  }), // This flag is an unmatched variable
  scrollBottom > 1 && /*#__PURE__*/React__default["default"].createElement("div", {
    className: "sendbird-conversation__scroll-bottom-button",
    onClick: onClickScrollBot,
    onKeyDown: onClickScrollBot,
    tabIndex: 0,
    role: "button"
  }, /*#__PURE__*/React__default["default"].createElement(ui_Icon["default"], {
    width: "24px",
    height: "24px",
    type: ui_Icon.IconTypes.CHEVRON_DOWN,
    fillColor: ui_Icon.IconColors.PRIMARY
  })));
};

module.exports = MessageList;
//# sourceMappingURL=MessageList.js.map
