var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
var _typeof = require("@babel/runtime/helpers/typeof");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.reactionData = exports.Channel = void 0;
var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator"));
var _toConsumableArray2 = _interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray"));
var _objectWithoutProperties2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutProperties"));
var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator"));
var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray"));
var _react = _interopRequireWildcard(require("react"));
var _reactNative = require("react-native");
var _debounce = _interopRequireDefault(require("lodash/debounce"));
var _omit = _interopRequireDefault(require("lodash/omit"));
var _throttle = _interopRequireDefault(require("lodash/throttle"));
var _mimeTypes = require("mime-types");
var _useChannelDataState2 = require("./hooks/useChannelDataState");
var _useCreateChannelContext = require("./hooks/useCreateChannelContext");
var _useCreateInputMessageInputContext = require("./hooks/useCreateInputMessageInputContext");
var _useCreateMessagesContext = require("./hooks/useCreateMessagesContext");
var _useCreateOwnCapabilitiesContext = require("./hooks/useCreateOwnCapabilitiesContext");
var _useCreatePaginatedMessageListContext = require("./hooks/useCreatePaginatedMessageListContext");
var _useCreateThreadContext = require("./hooks/useCreateThreadContext");
var _useCreateTypingContext = require("./hooks/useCreateTypingContext");
var _useMessageListPagination = require("./hooks/useMessageListPagination");
var _useTargetedMessage2 = require("./hooks/useTargetedMessage");
var _ChannelContext = require("../../contexts/channelContext/ChannelContext");
var _useChannelState2 = require("../../contexts/channelsStateContext/useChannelState");
var _ChatContext = require("../../contexts/chatContext/ChatContext");
var _MessageInputContext = require("../../contexts/messageInputContext/MessageInputContext");
var _MessagesContext = require("../../contexts/messagesContext/MessagesContext");
var _OwnCapabilitiesContext = require("../../contexts/ownCapabilitiesContext/OwnCapabilitiesContext");
var _PaginatedMessageListContext = require("../../contexts/paginatedMessageListContext/PaginatedMessageListContext");
var _SuggestionsContext = require("../../contexts/suggestionsContext/SuggestionsContext");
var _ThemeContext = require("../../contexts/themeContext/ThemeContext");
var _ThreadContext = require("../../contexts/threadContext/ThreadContext");
var _TranslationContext = require("../../contexts/translationContext/TranslationContext");
var _TypingContext = require("../../contexts/typingContext/TypingContext");
var _hooks = require("../../hooks");
var _useAppStateListener = require("../../hooks/useAppStateListener");
var _icons = require("../../icons");
var _native = require("../../native");
var dbApi = _interopRequireWildcard(require("../../store/apis"));
var _types = require("../../types/types");
var _addReactionToLocalState = require("../../utils/addReactionToLocalState");
var _compressImage = require("../../utils/compressImage");
var _patchMessageTextCommand = require("../../utils/patchMessageTextCommand");
var _removeReservedFields = require("../../utils/removeReservedFields");
var _utils = require("../../utils/utils");
var _Attachment = require("../Attachment/Attachment");
var _AttachmentActions = require("../Attachment/AttachmentActions");
var _AudioAttachment = require("../Attachment/AudioAttachment");
var _Card = require("../Attachment/Card");
var _FileAttachment = require("../Attachment/FileAttachment");
var _FileAttachmentGroup = require("../Attachment/FileAttachmentGroup");
var _FileIcon = require("../Attachment/FileIcon");
var _Gallery = require("../Attachment/Gallery");
var _Giphy = require("../Attachment/Giphy");
var _ImageLoadingFailedIndicator = require("../Attachment/ImageLoadingFailedIndicator");
var _ImageLoadingIndicator = require("../Attachment/ImageLoadingIndicator");
var _ImageReloadIndicator = require("../Attachment/ImageReloadIndicator");
var _VideoThumbnail = require("../Attachment/VideoThumbnail");
var _AutoCompleteSuggestionHeader = require("../AutoCompleteInput/AutoCompleteSuggestionHeader");
var _AutoCompleteSuggestionItem = require("../AutoCompleteInput/AutoCompleteSuggestionItem");
var _AutoCompleteSuggestionList = require("../AutoCompleteInput/AutoCompleteSuggestionList");
var _EmptyStateIndicator = require("../Indicators/EmptyStateIndicator");
var _LoadingErrorIndicator = require("../Indicators/LoadingErrorIndicator");
var _LoadingIndicator = require("../Indicators/LoadingIndicator");
var _KeyboardCompatibleView = require("../KeyboardCompatibleView/KeyboardCompatibleView");
var _Message = require("../Message/Message");
var _MessageAvatar = require("../Message/MessageSimple/MessageAvatar");
var _MessageBounce = require("../Message/MessageSimple/MessageBounce");
var _MessageContent = require("../Message/MessageSimple/MessageContent");
var _MessageDeleted = require("../Message/MessageSimple/MessageDeleted");
var _MessageEditedTimestamp = require("../Message/MessageSimple/MessageEditedTimestamp");
var _MessageError = require("../Message/MessageSimple/MessageError");
var _MessageFooter = require("../Message/MessageSimple/MessageFooter");
var _MessagePinnedHeader = require("../Message/MessageSimple/MessagePinnedHeader");
var _MessageReplies = require("../Message/MessageSimple/MessageReplies");
var _MessageRepliesAvatars = require("../Message/MessageSimple/MessageRepliesAvatars");
var _MessageSimple = require("../Message/MessageSimple/MessageSimple");
var _MessageStatus = require("../Message/MessageSimple/MessageStatus");
var _MessageSwipeContent = require("../Message/MessageSimple/MessageSwipeContent");
var _MessageTimestamp = require("../Message/MessageSimple/MessageTimestamp");
var _ReactionListBottom = require("../Message/MessageSimple/ReactionList/ReactionListBottom");
var _ReactionListTop = require("../Message/MessageSimple/ReactionList/ReactionListTop");
var _StreamingMessageView = require("../Message/MessageSimple/StreamingMessageView");
var _AttachButton = require("../MessageInput/AttachButton");
var _CommandsButton = require("../MessageInput/CommandsButton");
var _AudioRecorder = require("../MessageInput/components/AudioRecorder/AudioRecorder");
var _AudioRecordingButton = require("../MessageInput/components/AudioRecorder/AudioRecordingButton");
var _AudioRecordingInProgress = require("../MessageInput/components/AudioRecorder/AudioRecordingInProgress");
var _AudioRecordingLockIndicator = require("../MessageInput/components/AudioRecorder/AudioRecordingLockIndicator");
var _AudioRecordingPreview = require("../MessageInput/components/AudioRecorder/AudioRecordingPreview");
var _AudioRecordingWaveform = require("../MessageInput/components/AudioRecorder/AudioRecordingWaveform");
var _InputEditingStateHeader = require("../MessageInput/components/InputEditingStateHeader");
var _InputGiphySearch = require("../MessageInput/components/InputGiphySearch");
var _InputReplyStateHeader = require("../MessageInput/components/InputReplyStateHeader");
var _CooldownTimer = require("../MessageInput/CooldownTimer");
var _FileUploadPreview = require("../MessageInput/FileUploadPreview");
var _ImageUploadPreview = require("../MessageInput/ImageUploadPreview");
var _InputButtons = require("../MessageInput/InputButtons");
var _MoreOptionsButton = require("../MessageInput/MoreOptionsButton");
var _SendButton = require("../MessageInput/SendButton");
var _SendMessageDisallowedIndicator = require("../MessageInput/SendMessageDisallowedIndicator");
var _ShowThreadMessageInChannelButton = require("../MessageInput/ShowThreadMessageInChannelButton");
var _StopMessageStreamingButton = require("../MessageInput/StopMessageStreamingButton");
var _UploadProgressIndicator = require("../MessageInput/UploadProgressIndicator");
var _DateHeader = require("../MessageList/DateHeader");
var _InlineDateSeparator = require("../MessageList/InlineDateSeparator");
var _InlineUnreadIndicator = require("../MessageList/InlineUnreadIndicator");
var _MessageList = require("../MessageList/MessageList");
var _MessageSystem = require("../MessageList/MessageSystem");
var _NetworkDownIndicator = require("../MessageList/NetworkDownIndicator");
var _ScrollToBottomButton = require("../MessageList/ScrollToBottomButton");
var _StickyHeader = require("../MessageList/StickyHeader");
var _TypingIndicator = require("../MessageList/TypingIndicator");
var _TypingIndicatorContainer = require("../MessageList/TypingIndicatorContainer");
var _UnreadMessagesNotification = require("../MessageList/UnreadMessagesNotification");
var _MessageActionList = require("../MessageMenu/MessageActionList");
var _MessageActionListItem = require("../MessageMenu/MessageActionListItem");
var _MessageMenu = require("../MessageMenu/MessageMenu");
var _MessageReactionPicker = require("../MessageMenu/MessageReactionPicker");
var _MessageUserReactions = require("../MessageMenu/MessageUserReactions");
var _MessageUserReactionsAvatar = require("../MessageMenu/MessageUserReactionsAvatar");
var _MessageUserReactionsItem = require("../MessageMenu/MessageUserReactionsItem");
var _Reply = require("../Reply/Reply");
var _jsxRuntime = require("react/jsx-runtime");
var _excluded = ["user"],
  _excluded2 = ["user"],
  _excluded3 = ["attachments", "mentioned_users", "parent_id", "poll_id", "text"],
  _excluded4 = ["channel_mutes", "devices", "mutes"];
var _this = this,
  _jsxFileName = "/home/runner/work/stream-chat-react-native/stream-chat-react-native/package/src/components/Channel/Channel.tsx";
function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(e) { return e ? t : r; })(e); }
function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != _typeof(e) && "function" != typeof e) return { "default": e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && {}.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n["default"] = e, t && t.set(e, n), n; }
var styles = _reactNative.StyleSheet.create({
  selectChannel: {
    fontWeight: 'bold',
    padding: 16
  }
});
var reactionData = exports.reactionData = [{
  Icon: _icons.LoveReaction,
  type: 'love'
}, {
  Icon: _icons.ThumbsUpReaction,
  type: 'like'
}, {
  Icon: _icons.ThumbsDownReaction,
  type: 'sad'
}, {
  Icon: _icons.LOLReaction,
  type: 'haha'
}, {
  Icon: _icons.WutReaction,
  type: 'wow'
}];
var scrollToFirstUnreadThreshold = 0;
var defaultThrottleInterval = 500;
var defaultDebounceInterval = 500;
var throttleOptions = {
  leading: true,
  trailing: true
};
var debounceOptions = {
  leading: true,
  trailing: true
};
var ChannelWithContext = function ChannelWithContext(props) {
  var _channel$getConfig, _channel$data, _ref20, _channelState$members, _channelState$read, _getChannelConfigSafe, _getChannelConfigSafe2, _ref21, _channelMessagesState3, _channelState$typing, _channelMessagesState4;
  var additionalKeyboardAvoidingViewProps = props.additionalKeyboardAvoidingViewProps,
    additionalPressableProps = props.additionalPressableProps,
    additionalTextInputProps = props.additionalTextInputProps,
    _props$allowThreadMes = props.allowThreadMessagesInChannel,
    allowThreadMessagesInChannel = _props$allowThreadMes === void 0 ? true : _props$allowThreadMes,
    _props$asyncMessagesL = props.asyncMessagesLockDistance,
    asyncMessagesLockDistance = _props$asyncMessagesL === void 0 ? 50 : _props$asyncMessagesL,
    _props$asyncMessagesM = props.asyncMessagesMinimumPressDuration,
    asyncMessagesMinimumPressDuration = _props$asyncMessagesM === void 0 ? 500 : _props$asyncMessagesM,
    _props$asyncMessagesM2 = props.asyncMessagesMultiSendEnabled,
    asyncMessagesMultiSendEnabled = _props$asyncMessagesM2 === void 0 ? true : _props$asyncMessagesM2,
    _props$asyncMessagesS = props.asyncMessagesSlideToCancelDistance,
    asyncMessagesSlideToCancelDistance = _props$asyncMessagesS === void 0 ? 100 : _props$asyncMessagesS,
    _props$AttachButton = props.AttachButton,
    AttachButton = _props$AttachButton === void 0 ? _AttachButton.AttachButton : _props$AttachButton,
    _props$Attachment = props.Attachment,
    Attachment = _props$Attachment === void 0 ? _Attachment.Attachment : _props$Attachment,
    _props$AttachmentActi = props.AttachmentActions,
    AttachmentActions = _props$AttachmentActi === void 0 ? _AttachmentActions.AttachmentActions : _props$AttachmentActi,
    _props$AudioAttachmen = props.AudioAttachment,
    AudioAttachment = _props$AudioAttachmen === void 0 ? _AudioAttachment.AudioAttachment : _props$AudioAttachmen,
    _props$AudioAttachmen2 = props.AudioAttachmentUploadPreview,
    AudioAttachmentUploadPreview = _props$AudioAttachmen2 === void 0 ? _AudioAttachment.AudioAttachment : _props$AudioAttachmen2,
    _props$AudioRecorder = props.AudioRecorder,
    AudioRecorder = _props$AudioRecorder === void 0 ? _AudioRecorder.AudioRecorder : _props$AudioRecorder,
    _props$audioRecording = props.audioRecordingEnabled,
    audioRecordingEnabled = _props$audioRecording === void 0 ? false : _props$audioRecording,
    _props$AudioRecording = props.AudioRecordingInProgress,
    AudioRecordingInProgress = _props$AudioRecording === void 0 ? _AudioRecordingInProgress.AudioRecordingInProgress : _props$AudioRecording,
    _props$AudioRecording2 = props.AudioRecordingLockIndicator,
    AudioRecordingLockIndicator = _props$AudioRecording2 === void 0 ? _AudioRecordingLockIndicator.AudioRecordingLockIndicator : _props$AudioRecording2,
    _props$AudioRecording3 = props.AudioRecordingPreview,
    AudioRecordingPreview = _props$AudioRecording3 === void 0 ? _AudioRecordingPreview.AudioRecordingPreview : _props$AudioRecording3,
    _props$AudioRecording4 = props.AudioRecordingWaveform,
    AudioRecordingWaveform = _props$AudioRecording4 === void 0 ? _AudioRecordingWaveform.AudioRecordingWaveform : _props$AudioRecording4,
    _props$AutoCompleteSu = props.AutoCompleteSuggestionHeader,
    AutoCompleteSuggestionHeader = _props$AutoCompleteSu === void 0 ? _AutoCompleteSuggestionHeader.AutoCompleteSuggestionHeader : _props$AutoCompleteSu,
    _props$AutoCompleteSu2 = props.AutoCompleteSuggestionItem,
    AutoCompleteSuggestionItem = _props$AutoCompleteSu2 === void 0 ? _AutoCompleteSuggestionItem.AutoCompleteSuggestionItem : _props$AutoCompleteSu2,
    _props$AutoCompleteSu3 = props.AutoCompleteSuggestionList,
    AutoCompleteSuggestionList = _props$AutoCompleteSu3 === void 0 ? _AutoCompleteSuggestionList.AutoCompleteSuggestionList : _props$AutoCompleteSu3,
    autoCompleteSuggestionsLimit = props.autoCompleteSuggestionsLimit,
    autoCompleteTriggerSettings = props.autoCompleteTriggerSettings,
    _props$Card = props.Card,
    Card = _props$Card === void 0 ? _Card.Card : _props$Card,
    CardCover = props.CardCover,
    CardFooter = props.CardFooter,
    CardHeader = props.CardHeader,
    channel = props.channel,
    children = props.children,
    client = props.client,
    _props$CommandsButton = props.CommandsButton,
    CommandsButton = _props$CommandsButton === void 0 ? _CommandsButton.CommandsButton : _props$CommandsButton,
    compressImageQuality = props.compressImageQuality,
    _props$CooldownTimer = props.CooldownTimer,
    CooldownTimer = _props$CooldownTimer === void 0 ? _CooldownTimer.CooldownTimer : _props$CooldownTimer,
    CreatePollContent = props.CreatePollContent,
    _props$DateHeader = props.DateHeader,
    DateHeader = _props$DateHeader === void 0 ? _DateHeader.DateHeader : _props$DateHeader,
    _props$deletedMessage = props.deletedMessagesVisibilityType,
    deletedMessagesVisibilityType = _props$deletedMessage === void 0 ? 'always' : _props$deletedMessage,
    _props$disableKeyboar = props.disableKeyboardCompatibleView,
    disableKeyboardCompatibleView = _props$disableKeyboar === void 0 ? false : _props$disableKeyboar,
    disableTypingIndicator = props.disableTypingIndicator,
    _props$dismissKeyboar = props.dismissKeyboardOnMessageTouch,
    dismissKeyboardOnMessageTouch = _props$dismissKeyboar === void 0 ? true : _props$dismissKeyboar,
    doDocUploadRequest = props.doDocUploadRequest,
    doImageUploadRequest = props.doImageUploadRequest,
    doMarkReadRequest = props.doMarkReadRequest,
    doSendMessageRequest = props.doSendMessageRequest,
    doUpdateMessageRequest = props.doUpdateMessageRequest,
    _props$emojiSearchInd = props.emojiSearchIndex,
    emojiSearchIndex = _props$emojiSearchInd === void 0 ? _utils.defaultEmojiSearchIndex : _props$emojiSearchInd,
    _props$EmptyStateIndi = props.EmptyStateIndicator,
    EmptyStateIndicator = _props$EmptyStateIndi === void 0 ? _EmptyStateIndicator.EmptyStateIndicator : _props$EmptyStateIndi,
    _props$enableMessageG = props.enableMessageGroupingByUser,
    enableMessageGroupingByUser = _props$enableMessageG === void 0 ? true : _props$enableMessageG,
    enableOfflineSupport = props.enableOfflineSupport,
    _props$enableSwipeToR = props.enableSwipeToReply,
    enableSwipeToReply = _props$enableSwipeToR === void 0 ? true : _props$enableSwipeToR,
    _props$enforceUniqueR = props.enforceUniqueReaction,
    enforceUniqueReaction = _props$enforceUniqueR === void 0 ? false : _props$enforceUniqueR,
    _props$FileAttachment = props.FileAttachment,
    FileAttachment = _props$FileAttachment === void 0 ? _FileAttachment.FileAttachment : _props$FileAttachment,
    _props$FileAttachment2 = props.FileAttachmentGroup,
    FileAttachmentGroup = _props$FileAttachment2 === void 0 ? _FileAttachmentGroup.FileAttachmentGroup : _props$FileAttachment2,
    _props$FileAttachment3 = props.FileAttachmentIcon,
    FileAttachmentIcon = _props$FileAttachment3 === void 0 ? _FileIcon.FileIcon : _props$FileAttachment3,
    _props$FileUploadPrev = props.FileUploadPreview,
    FileUploadPreview = _props$FileUploadPrev === void 0 ? _FileUploadPreview.FileUploadPreview : _props$FileUploadPrev,
    _props$FlatList = props.FlatList,
    FlatList = _props$FlatList === void 0 ? _native.NativeHandlers.FlatList : _props$FlatList,
    forceAlignMessages = props.forceAlignMessages,
    _props$Gallery = props.Gallery,
    Gallery = _props$Gallery === void 0 ? _Gallery.Gallery : _props$Gallery,
    getMessagesGroupStyles = props.getMessagesGroupStyles,
    _props$Giphy = props.Giphy,
    Giphy = _props$Giphy === void 0 ? _Giphy.Giphy : _props$Giphy,
    giphyEnabled = props.giphyEnabled,
    _props$giphyVersion = props.giphyVersion,
    giphyVersion = _props$giphyVersion === void 0 ? 'fixed_height' : _props$giphyVersion,
    handleAttachButtonPress = props.handleAttachButtonPress,
    handleBan = props.handleBan,
    handleCopy = props.handleCopy,
    handleDelete = props.handleDelete,
    handleEdit = props.handleEdit,
    handleFlag = props.handleFlag,
    handleMarkUnread = props.handleMarkUnread,
    handleMute = props.handleMute,
    handlePinMessage = props.handlePinMessage,
    handleQuotedReply = props.handleQuotedReply,
    handleReaction = props.handleReaction,
    handleRetry = props.handleRetry,
    handleThreadReply = props.handleThreadReply,
    _props$hasCameraPicke = props.hasCameraPicker,
    hasCameraPicker = _props$hasCameraPicke === void 0 ? (0, _native.isImagePickerAvailable)() : _props$hasCameraPicke,
    hasCommands = props.hasCommands,
    hasCreatePoll = props.hasCreatePoll,
    _props$hasFilePicker = props.hasFilePicker,
    hasFilePicker = _props$hasFilePicker === void 0 ? (0, _native.isDocumentPickerAvailable)() : _props$hasFilePicker,
    _props$hasImagePicker = props.hasImagePicker,
    hasImagePicker = _props$hasImagePicker === void 0 ? (0, _native.isImagePickerAvailable)() || (0, _native.isImageMediaLibraryAvailable)() : _props$hasImagePicker,
    _props$hideDateSepara = props.hideDateSeparators,
    hideDateSeparators = _props$hideDateSepara === void 0 ? false : _props$hideDateSepara,
    _props$hideStickyDate = props.hideStickyDateHeader,
    hideStickyDateHeader = _props$hideStickyDate === void 0 ? false : _props$hideStickyDate,
    _props$ImageLoadingFa = props.ImageLoadingFailedIndicator,
    ImageLoadingFailedIndicator = _props$ImageLoadingFa === void 0 ? _ImageLoadingFailedIndicator.ImageLoadingFailedIndicator : _props$ImageLoadingFa,
    _props$ImageLoadingIn = props.ImageLoadingIndicator,
    ImageLoadingIndicator = _props$ImageLoadingIn === void 0 ? _ImageLoadingIndicator.ImageLoadingIndicator : _props$ImageLoadingIn,
    _props$ImageReloadInd = props.ImageReloadIndicator,
    ImageReloadIndicator = _props$ImageReloadInd === void 0 ? _ImageReloadIndicator.ImageReloadIndicator : _props$ImageReloadInd,
    _props$ImageUploadPre = props.ImageUploadPreview,
    ImageUploadPreview = _props$ImageUploadPre === void 0 ? _ImageUploadPreview.ImageUploadPreview : _props$ImageUploadPre,
    _props$initialScrollT = props.initialScrollToFirstUnreadMessage,
    initialScrollToFirstUnreadMessage = _props$initialScrollT === void 0 ? false : _props$initialScrollT,
    initialValue = props.initialValue,
    _props$InlineDateSepa = props.InlineDateSeparator,
    InlineDateSeparator = _props$InlineDateSepa === void 0 ? _InlineDateSeparator.InlineDateSeparator : _props$InlineDateSepa,
    _props$InlineUnreadIn = props.InlineUnreadIndicator,
    InlineUnreadIndicator = _props$InlineUnreadIn === void 0 ? _InlineUnreadIndicator.InlineUnreadIndicator : _props$InlineUnreadIn,
    Input = props.Input,
    _props$InputButtons = props.InputButtons,
    InputButtons = _props$InputButtons === void 0 ? _InputButtons.InputButtons : _props$InputButtons,
    _props$InputEditingSt = props.InputEditingStateHeader,
    InputEditingStateHeader = _props$InputEditingSt === void 0 ? _InputEditingStateHeader.InputEditingStateHeader : _props$InputEditingSt,
    _props$InputGiphySear = props.InputGiphySearch,
    InputGiphySearch = _props$InputGiphySear === void 0 ? _InputGiphySearch.InputGiphySearch : _props$InputGiphySear,
    _props$InputReplyStat = props.InputReplyStateHeader,
    InputReplyStateHeader = _props$InputReplyStat === void 0 ? _InputReplyStateHeader.InputReplyStateHeader : _props$InputReplyStat,
    isAttachmentEqual = props.isAttachmentEqual,
    _props$isMessageAIGen = props.isMessageAIGenerated,
    isMessageAIGenerated = _props$isMessageAIGen === void 0 ? function () {
      return false;
    } : _props$isMessageAIGen,
    keyboardBehavior = props.keyboardBehavior,
    _props$KeyboardCompat = props.KeyboardCompatibleView,
    KeyboardCompatibleView = _props$KeyboardCompat === void 0 ? _KeyboardCompatibleView.KeyboardCompatibleView : _props$KeyboardCompat,
    keyboardVerticalOffset = props.keyboardVerticalOffset,
    _props$legacyImageVie = props.legacyImageViewerSwipeBehaviour,
    legacyImageViewerSwipeBehaviour = _props$legacyImageVie === void 0 ? false : _props$legacyImageVie,
    _props$LoadingErrorIn = props.LoadingErrorIndicator,
    LoadingErrorIndicator = _props$LoadingErrorIn === void 0 ? _LoadingErrorIndicator.LoadingErrorIndicator : _props$LoadingErrorIn,
    _props$LoadingIndicat = props.LoadingIndicator,
    LoadingIndicator = _props$LoadingIndicat === void 0 ? _LoadingIndicator.LoadingIndicator : _props$LoadingIndicat,
    loadingMoreProp = props.loadingMore,
    loadingMoreRecentProp = props.loadingMoreRecent,
    markdownRules = props.markdownRules,
    _props$markReadOnMoun = props.markReadOnMount,
    markReadOnMount = _props$markReadOnMoun === void 0 ? true : _props$markReadOnMoun,
    maxMessageLengthProp = props.maxMessageLength,
    _props$maxNumberOfFil = props.maxNumberOfFiles,
    maxNumberOfFiles = _props$maxNumberOfFil === void 0 ? 10 : _props$maxNumberOfFil,
    maxTimeBetweenGroupedMessages = props.maxTimeBetweenGroupedMessages,
    _props$mentionAllAppU = props.mentionAllAppUsersEnabled,
    mentionAllAppUsersEnabled = _props$mentionAllAppU === void 0 ? false : _props$mentionAllAppU,
    mentionAllAppUsersQuery = props.mentionAllAppUsersQuery,
    _props$Message = props.Message,
    Message = _props$Message === void 0 ? _Message.Message : _props$Message,
    _props$MessageActionL = props.MessageActionList,
    MessageActionList = _props$MessageActionL === void 0 ? _MessageActionList.MessageActionList : _props$MessageActionL,
    _props$MessageActionL2 = props.MessageActionListItem,
    MessageActionListItem = _props$MessageActionL2 === void 0 ? _MessageActionListItem.MessageActionListItem : _props$MessageActionL2,
    messageActions = props.messageActions,
    _props$MessageAvatar = props.MessageAvatar,
    MessageAvatar = _props$MessageAvatar === void 0 ? _MessageAvatar.MessageAvatar : _props$MessageAvatar,
    _props$MessageBounce = props.MessageBounce,
    MessageBounce = _props$MessageBounce === void 0 ? _MessageBounce.MessageBounce : _props$MessageBounce,
    _props$MessageContent = props.MessageContent,
    MessageContent = _props$MessageContent === void 0 ? _MessageContent.MessageContent : _props$MessageContent,
    _props$messageContent = props.messageContentOrder,
    messageContentOrder = _props$messageContent === void 0 ? ['quoted_reply', 'gallery', 'files', 'poll', 'ai_text', 'text', 'attachments'] : _props$messageContent,
    _props$MessageDeleted = props.MessageDeleted,
    MessageDeleted = _props$MessageDeleted === void 0 ? _MessageDeleted.MessageDeleted : _props$MessageDeleted,
    _props$MessageEditedT = props.MessageEditedTimestamp,
    MessageEditedTimestamp = _props$MessageEditedT === void 0 ? _MessageEditedTimestamp.MessageEditedTimestamp : _props$MessageEditedT,
    _props$MessageError = props.MessageError,
    MessageError = _props$MessageError === void 0 ? _MessageError.MessageError : _props$MessageError,
    _props$MessageFooter = props.MessageFooter,
    MessageFooter = _props$MessageFooter === void 0 ? _MessageFooter.MessageFooter : _props$MessageFooter,
    MessageHeader = props.MessageHeader,
    messageId = props.messageId,
    _props$MessageList = props.MessageList,
    MessageList = _props$MessageList === void 0 ? _MessageList.MessageList : _props$MessageList,
    _props$MessageMenu = props.MessageMenu,
    MessageMenu = _props$MessageMenu === void 0 ? _MessageMenu.MessageMenu : _props$MessageMenu,
    _props$MessagePinnedH = props.MessagePinnedHeader,
    MessagePinnedHeader = _props$MessagePinnedH === void 0 ? _MessagePinnedHeader.MessagePinnedHeader : _props$MessagePinnedH,
    _props$MessageReactio = props.MessageReactionPicker,
    MessageReactionPicker = _props$MessageReactio === void 0 ? _MessageReactionPicker.MessageReactionPicker : _props$MessageReactio,
    _props$MessageReplies = props.MessageReplies,
    MessageReplies = _props$MessageReplies === void 0 ? _MessageReplies.MessageReplies : _props$MessageReplies,
    _props$MessageReplies2 = props.MessageRepliesAvatars,
    MessageRepliesAvatars = _props$MessageReplies2 === void 0 ? _MessageRepliesAvatars.MessageRepliesAvatars : _props$MessageReplies2,
    _props$MessageSimple = props.MessageSimple,
    MessageSimple = _props$MessageSimple === void 0 ? _MessageSimple.MessageSimple : _props$MessageSimple,
    _props$MessageStatus = props.MessageStatus,
    MessageStatus = _props$MessageStatus === void 0 ? _MessageStatus.MessageStatus : _props$MessageStatus,
    _props$MessageSwipeCo = props.MessageSwipeContent,
    MessageSwipeContent = _props$MessageSwipeCo === void 0 ? _MessageSwipeContent.MessageSwipeContent : _props$MessageSwipeCo,
    messageSwipeToReplyHitSlop = props.messageSwipeToReplyHitSlop,
    _props$MessageSystem = props.MessageSystem,
    MessageSystem = _props$MessageSystem === void 0 ? _MessageSystem.MessageSystem : _props$MessageSystem,
    MessageText = props.MessageText,
    messageTextNumberOfLines = props.messageTextNumberOfLines,
    _props$MessageTimesta = props.MessageTimestamp,
    MessageTimestamp = _props$MessageTimesta === void 0 ? _MessageTimestamp.MessageTimestamp : _props$MessageTimesta,
    _props$MessageUserRea = props.MessageUserReactions,
    MessageUserReactions = _props$MessageUserRea === void 0 ? _MessageUserReactions.MessageUserReactions : _props$MessageUserRea,
    _props$MessageUserRea2 = props.MessageUserReactionsAvatar,
    MessageUserReactionsAvatar = _props$MessageUserRea2 === void 0 ? _MessageUserReactionsAvatar.MessageUserReactionsAvatar : _props$MessageUserRea2,
    _props$MessageUserRea3 = props.MessageUserReactionsItem,
    MessageUserReactionsItem = _props$MessageUserRea3 === void 0 ? _MessageUserReactionsItem.MessageUserReactionsItem : _props$MessageUserRea3,
    _props$MoreOptionsBut = props.MoreOptionsButton,
    MoreOptionsButton = _props$MoreOptionsBut === void 0 ? _MoreOptionsButton.MoreOptionsButton : _props$MoreOptionsBut,
    myMessageTheme = props.myMessageTheme,
    _props$NetworkDownInd = props.NetworkDownIndicator,
    NetworkDownIndicator = _props$NetworkDownInd === void 0 ? _NetworkDownIndicator.NetworkDownIndicator : _props$NetworkDownInd,
    _props$newMessageStat = props.newMessageStateUpdateThrottleInterval,
    newMessageStateUpdateThrottleInterval = _props$newMessageStat === void 0 ? defaultThrottleInterval : _props$newMessageStat,
    _props$numberOfLines = props.numberOfLines,
    numberOfLines = _props$numberOfLines === void 0 ? 5 : _props$numberOfLines,
    onChangeText = props.onChangeText,
    onLongPressMessage = props.onLongPressMessage,
    onPressInMessage = props.onPressInMessage,
    onPressMessage = props.onPressMessage,
    openPollCreationDialog = props.openPollCreationDialog,
    overrideOwnCapabilities = props.overrideOwnCapabilities,
    PollContent = props.PollContent,
    _props$ReactionListBo = props.ReactionListBottom,
    ReactionListBottom = _props$ReactionListBo === void 0 ? _ReactionListBottom.ReactionListBottom : _props$ReactionListBo,
    _props$reactionListPo = props.reactionListPosition,
    reactionListPosition = _props$reactionListPo === void 0 ? 'top' : _props$reactionListPo,
    _props$ReactionListTo = props.ReactionListTop,
    ReactionListTop = _props$ReactionListTo === void 0 ? _ReactionListTop.ReactionListTop : _props$ReactionListTo,
    _props$Reply = props.Reply,
    Reply = _props$Reply === void 0 ? _Reply.Reply : _props$Reply,
    _props$ScrollToBottom = props.ScrollToBottomButton,
    ScrollToBottomButton = _props$ScrollToBottom === void 0 ? _ScrollToBottomButton.ScrollToBottomButton : _props$ScrollToBottom,
    selectReaction = props.selectReaction,
    _props$SendButton = props.SendButton,
    SendButton = _props$SendButton === void 0 ? _SendButton.SendButton : _props$SendButton,
    _props$sendImageAsync = props.sendImageAsync,
    sendImageAsync = _props$sendImageAsync === void 0 ? false : _props$sendImageAsync,
    _props$SendMessageDis = props.SendMessageDisallowedIndicator,
    SendMessageDisallowedIndicator = _props$SendMessageDis === void 0 ? _SendMessageDisallowedIndicator.SendMessageDisallowedIndicator : _props$SendMessageDis,
    setInputRef = props.setInputRef,
    setThreadMessages = props.setThreadMessages,
    _props$shouldShowUnre = props.shouldShowUnreadUnderlay,
    shouldShowUnreadUnderlay = _props$shouldShowUnre === void 0 ? true : _props$shouldShowUnre,
    shouldSyncChannel = props.shouldSyncChannel,
    _props$ShowThreadMess = props.ShowThreadMessageInChannelButton,
    ShowThreadMessageInChannelButton = _props$ShowThreadMess === void 0 ? _ShowThreadMessageInChannelButton.ShowThreadMessageInChannelButton : _props$ShowThreadMess,
    _props$StartAudioReco = props.StartAudioRecordingButton,
    StartAudioRecordingButton = _props$StartAudioReco === void 0 ? _AudioRecordingButton.AudioRecordingButton : _props$StartAudioReco,
    _props$stateUpdateThr = props.stateUpdateThrottleInterval,
    stateUpdateThrottleInterval = _props$stateUpdateThr === void 0 ? defaultThrottleInterval : _props$stateUpdateThr,
    _props$StickyHeader = props.StickyHeader,
    StickyHeader = _props$StickyHeader === void 0 ? _StickyHeader.StickyHeader : _props$StickyHeader,
    StopMessageStreamingButtonOverride = props.StopMessageStreamingButton,
    _props$StreamingMessa = props.StreamingMessageView,
    StreamingMessageView = _props$StreamingMessa === void 0 ? _StreamingMessageView.StreamingMessageView : _props$StreamingMessa,
    _props$supportedReact = props.supportedReactions,
    supportedReactions = _props$supportedReact === void 0 ? reactionData : _props$supportedReact,
    t = props.t,
    threadFromProps = props.thread,
    threadList = props.threadList,
    threadMessages = props.threadMessages,
    _props$TypingIndicato = props.TypingIndicator,
    TypingIndicator = _props$TypingIndicato === void 0 ? _TypingIndicator.TypingIndicator : _props$TypingIndicato,
    _props$TypingIndicato2 = props.TypingIndicatorContainer,
    TypingIndicatorContainer = _props$TypingIndicato2 === void 0 ? _TypingIndicatorContainer.TypingIndicatorContainer : _props$TypingIndicato2,
    _props$UnreadMessages = props.UnreadMessagesNotification,
    UnreadMessagesNotification = _props$UnreadMessages === void 0 ? _UnreadMessagesNotification.UnreadMessagesNotification : _props$UnreadMessages,
    _props$UploadProgress = props.UploadProgressIndicator,
    UploadProgressIndicator = _props$UploadProgress === void 0 ? _UploadProgressIndicator.UploadProgressIndicator : _props$UploadProgress,
    _props$UrlPreview = props.UrlPreview,
    UrlPreview = _props$UrlPreview === void 0 ? _Card.Card : _props$UrlPreview,
    _props$VideoThumbnail = props.VideoThumbnail,
    VideoThumbnail = _props$VideoThumbnail === void 0 ? _VideoThumbnail.VideoThumbnail : _props$VideoThumbnail,
    isOnline = props.isOnline;
  var threadProps = threadFromProps.thread,
    threadInstance = threadFromProps.threadInstance;
  var StopMessageStreamingButton = StopMessageStreamingButtonOverride === undefined ? _StopMessageStreamingButton.StopMessageStreamingButton : StopMessageStreamingButtonOverride;
  var _useTheme = (0, _ThemeContext.useTheme)(),
    _useTheme$theme = _useTheme.theme,
    selectChannel = _useTheme$theme.channel.selectChannel,
    black = _useTheme$theme.colors.black;
  var _useState = (0, _react.useState)(false),
    _useState2 = (0, _slicedToArray2["default"])(_useState, 2),
    deleted = _useState2[0],
    setDeleted = _useState2[1];
  var _useState3 = (0, _react.useState)(undefined),
    _useState4 = (0, _slicedToArray2["default"])(_useState3, 2),
    editing = _useState4[0],
    setEditing = _useState4[1];
  var _useState5 = (0, _react.useState)(false),
    _useState6 = (0, _slicedToArray2["default"])(_useState5, 2),
    error = _useState6[0],
    setError = _useState6[1];
  var _useState7 = (0, _react.useState)(),
    _useState8 = (0, _slicedToArray2["default"])(_useState7, 2),
    lastRead = _useState8[0],
    setLastRead = _useState8[1];
  var _useState9 = (0, _react.useState)(undefined),
    _useState10 = (0, _slicedToArray2["default"])(_useState9, 2),
    quotedMessage = _useState10[0],
    setQuotedMessage = _useState10[1];
  var _useState11 = (0, _react.useState)(threadProps || null),
    _useState12 = (0, _slicedToArray2["default"])(_useState11, 2),
    thread = _useState12[0],
    setThread = _useState12[1];
  var _useState13 = (0, _react.useState)(true),
    _useState14 = (0, _slicedToArray2["default"])(_useState13, 2),
    threadHasMore = _useState14[0],
    setThreadHasMore = _useState14[1];
  var _useState15 = (0, _react.useState)(false),
    _useState16 = (0, _slicedToArray2["default"])(_useState15, 2),
    threadLoadingMore = _useState16[0],
    setThreadLoadingMore = _useState16[1];
  var _useState17 = (0, _react.useState)(undefined),
    _useState18 = (0, _slicedToArray2["default"])(_useState17, 2),
    channelUnreadState = _useState18[0],
    setChannelUnreadState = _useState18[1];
  var syncingChannelRef = (0, _react.useRef)(false);
  var _useTargetedMessage = (0, _useTargetedMessage2.useTargetedMessage)(),
    highlightedMessageId = _useTargetedMessage.highlightedMessageId,
    setTargetedMessage = _useTargetedMessage.setTargetedMessage,
    targetedMessage = _useTargetedMessage.targetedMessage;
  var uploadAbortControllerRef = (0, _react.useRef)(new Map());
  var optimisticallyUpdatedNewMessages = (0, _react.useMemo)(function () {
    return new Set();
  }, []);
  var channelId = (channel == null ? void 0 : channel.id) || '';
  var pollCreationEnabled = !channel.disconnected && !!(channel != null && channel.id) && (channel == null || (_channel$getConfig = channel.getConfig()) == null ? void 0 : _channel$getConfig.polls);
  var _useChannelDataState = (0, _useChannelDataState2.useChannelDataState)(channel),
    copyStateFromChannel = _useChannelDataState.copyStateFromChannel,
    initStateFromChannel = _useChannelDataState.initStateFromChannel,
    setRead = _useChannelDataState.setRead,
    setTyping = _useChannelDataState.setTyping,
    channelState = _useChannelDataState.state;
  var _useMessageListPagina = (0, _useMessageListPagination.useMessageListPagination)({
      channel: channel
    }),
    copyMessagesStateFromChannel = _useMessageListPagina.copyMessagesStateFromChannel,
    loadChannelAroundMessageFn = _useMessageListPagina.loadChannelAroundMessage,
    loadChannelAtFirstUnreadMessage = _useMessageListPagina.loadChannelAtFirstUnreadMessage,
    loadInitialMessagesStateFromChannel = _useMessageListPagina.loadInitialMessagesStateFromChannel,
    loadLatestMessages = _useMessageListPagina.loadLatestMessages,
    loadMore = _useMessageListPagina.loadMore,
    loadMoreRecent = _useMessageListPagina.loadMoreRecent,
    channelMessagesState = _useMessageListPagina.state;
  var setReadThrottled = (0, _react.useMemo)(function () {
    return (0, _throttle["default"])(function () {
      if (channel) {
        setRead(channel);
      }
    }, stateUpdateThrottleInterval, throttleOptions);
  }, [channel, stateUpdateThrottleInterval, setRead]);
  var copyMessagesStateFromChannelThrottled = (0, _react.useMemo)(function () {
    return (0, _throttle["default"])(function () {
      if (channel) {
        copyMessagesStateFromChannel(channel);
      }
    }, newMessageStateUpdateThrottleInterval, throttleOptions);
  }, [channel, newMessageStateUpdateThrottleInterval, copyMessagesStateFromChannel]);
  var copyChannelState = (0, _react.useMemo)(function () {
    return (0, _throttle["default"])(function () {
      if (channel) {
        copyStateFromChannel(channel);
        copyMessagesStateFromChannel(channel);
      }
    }, stateUpdateThrottleInterval, throttleOptions);
  }, [stateUpdateThrottleInterval, channel, copyStateFromChannel, copyMessagesStateFromChannel]);
  var handleEvent = (0, _hooks.useStableCallback)(function (event) {
    if (shouldSyncChannel) {
      if (event.type.startsWith('poll.') || event.type === 'user.watching.start' || event.type === 'user.watching.stop') {
        return;
      }
      if (event.type === 'typing.start' || event.type === 'typing.stop') {
        var _event$user;
        if (((_event$user = event.user) == null ? void 0 : _event$user.id) !== client.userID) {
          setTyping(channel);
        }
        return;
      } else {
        if (thread != null && thread.id) {
          var _event$message;
          var updatedThreadMessages = thread.id && channel && channel.state.threads[thread.id] || threadMessages;
          setThreadMessages(updatedThreadMessages);
          if (channel && ((_event$message = event.message) == null ? void 0 : _event$message.id) === thread.id && !threadInstance) {
            var updatedThread = channel.state.formatMessage(event.message);
            setThread(updatedThread);
          }
        }
      }
      if (event.type === 'notification.mark_unread') {
        setChannelUnreadState(function (prev) {
          var _event$unread_message;
          if (!(event.last_read_at && event.user)) {
            return prev;
          }
          return {
            first_unread_message_id: event.first_unread_message_id,
            last_read: new Date(event.last_read_at),
            last_read_message_id: event.last_read_message_id,
            unread_messages: (_event$unread_message = event.unread_messages) != null ? _event$unread_message : 0
          };
        });
      }
      if (event.type === 'channel.truncated' && event.cid === channel.cid) {
        setChannelUnreadState(undefined);
      }
      if (channel && channel.initialized) {
        if (event.type === 'message.new' || event.type === 'notification.message_new') {
          var _event$message$id, _event$message2, _event$user2;
          var _messageId = (_event$message$id = (_event$message2 = event.message) == null ? void 0 : _event$message2.id) != null ? _event$message$id : '';
          if (((_event$user2 = event.user) == null ? void 0 : _event$user2.id) !== client.userID || !optimisticallyUpdatedNewMessages.has(_messageId)) {
            copyMessagesStateFromChannelThrottled();
          }
          optimisticallyUpdatedNewMessages["delete"](_messageId);
          return;
        }
        if (event.type === 'message.read' || event.type === 'notification.mark_read') {
          setReadThrottled();
          return;
        }
        copyChannelState();
      }
    }
  });
  (0, _react.useEffect)(function () {
    var listener;
    var initChannel = function () {
      var _ref = (0, _asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee() {
        var _client$user;
        var unreadCount, errored, _channel$state$read$c, user, ownReadState, _channel$state$read$c2, _user, _ownReadState;
        return _regenerator["default"].wrap(function _callee$(_context) {
          while (1) switch (_context.prev = _context.next) {
            case 0:
              setLastRead(new Date());
              unreadCount = channel.countUnread();
              if (!(!channel || !shouldSyncChannel)) {
                _context.next = 4;
                break;
              }
              return _context.abrupt("return");
            case 4:
              errored = false;
              if (!(!channel.initialized || !channel.state.isUpToDate)) {
                _context.next = 16;
                break;
              }
              _context.prev = 6;
              _context.next = 9;
              return channel == null ? void 0 : channel.watch();
            case 9:
              _context.next = 16;
              break;
            case 11:
              _context.prev = 11;
              _context.t0 = _context["catch"](6);
              console.warn('Channel watch request failed with error:', _context.t0);
              setError(true);
              errored = true;
            case 16:
              if (!errored) {
                initStateFromChannel(channel);
                loadInitialMessagesStateFromChannel(channel, channel.state.messagePagination.hasPrev);
              }
              if ((_client$user = client.user) != null && _client$user.id && channel.state.read[client.user.id]) {
                _channel$state$read$c = channel.state.read[client.user.id], user = _channel$state$read$c.user, ownReadState = (0, _objectWithoutProperties2["default"])(_channel$state$read$c, _excluded);
                setChannelUnreadState(ownReadState);
              }
              if (!messageId) {
                _context.next = 23;
                break;
              }
              _context.next = 21;
              return loadChannelAroundMessage({
                messageId: messageId,
                setTargetedMessage: setTargetedMessage
              });
            case 21:
              _context.next = 27;
              break;
            case 23:
              if (!(initialScrollToFirstUnreadMessage && client.user && unreadCount > scrollToFirstUnreadThreshold)) {
                _context.next = 27;
                break;
              }
              _channel$state$read$c2 = channel.state.read[client.user.id], _user = _channel$state$read$c2.user, _ownReadState = (0, _objectWithoutProperties2["default"])(_channel$state$read$c2, _excluded2);
              _context.next = 27;
              return loadChannelAtFirstUnreadMessage({
                channelUnreadState: _ownReadState,
                setChannelUnreadState: setChannelUnreadState,
                setTargetedMessage: setTargetedMessage
              });
            case 27:
              if (!(unreadCount > 0 && markReadOnMount)) {
                _context.next = 30;
                break;
              }
              _context.next = 30;
              return markRead({
                updateChannelUnreadState: false
              });
            case 30:
              listener = channel.on(handleEvent);
            case 31:
            case "end":
              return _context.stop();
          }
        }, _callee, null, [[6, 11]]);
      }));
      return function initChannel() {
        return _ref.apply(this, arguments);
      };
    }();
    initChannel();
    return function () {
      var _listener;
      copyChannelState.cancel();
      loadMoreThreadFinished.cancel();
      (_listener = listener) == null || _listener.unsubscribe();
    };
  }, [channel.cid, messageId, shouldSyncChannel]);
  (0, _react.useEffect)(function () {
    var _client$on = client.on('channel.deleted', function (event) {
        if (event.cid === (channel == null ? void 0 : channel.cid)) {
          setDeleted(true);
        }
      }),
      unsubscribe = _client$on.unsubscribe;
    return unsubscribe;
  }, [channel == null ? void 0 : channel.cid, client]);
  var threadPropsExists = !!threadProps;
  (0, _react.useEffect)(function () {
    if (threadProps && shouldSyncChannel) {
      setThread(threadProps);
      if (channel && threadProps != null && threadProps.id) {
        var _channel$state$thread;
        setThreadMessages(((_channel$state$thread = channel.state.threads) == null ? void 0 : _channel$state$thread[threadProps.id]) || []);
      }
    } else {
      setThread(null);
    }
  }, [threadPropsExists, shouldSyncChannel]);
  var handleAppBackground = (0, _react.useCallback)(function () {
    var _channelData$own_capa;
    var channelData = channel.data;
    if (channelData != null && (_channelData$own_capa = channelData.own_capabilities) != null && _channelData$own_capa.includes('send-typing-events')) {
      channel.sendEvent({
        parent_id: thread == null ? void 0 : thread.id,
        type: 'typing.stop'
      });
    }
  }, [thread == null ? void 0 : thread.id, channelId]);
  (0, _useAppStateListener.useAppStateListener)(undefined, handleAppBackground);
  var markReadInternal = (0, _throttle["default"])(function () {
    var _ref2 = (0, _asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee2(options) {
      var _ref3, _ref3$updateChannelUn, updateChannelUnreadState, response;
      return _regenerator["default"].wrap(function _callee2$(_context2) {
        while (1) switch (_context2.prev = _context2.next) {
          case 0:
            _ref3 = options != null ? options : {}, _ref3$updateChannelUn = _ref3.updateChannelUnreadState, updateChannelUnreadState = _ref3$updateChannelUn === void 0 ? true : _ref3$updateChannelUn;
            if (!(!channel || channel != null && channel.disconnected || !(clientChannelConfig != null && clientChannelConfig.read_events))) {
              _context2.next = 3;
              break;
            }
            return _context2.abrupt("return");
          case 3:
            if (!doMarkReadRequest) {
              _context2.next = 7;
              break;
            }
            doMarkReadRequest(channel, updateChannelUnreadState ? setChannelUnreadState : undefined);
            _context2.next = 17;
            break;
          case 7:
            _context2.prev = 7;
            _context2.next = 10;
            return channel.markRead();
          case 10:
            response = _context2.sent;
            if (updateChannelUnreadState && response && lastRead) {
              setChannelUnreadState({
                last_read: lastRead,
                last_read_message_id: response == null ? void 0 : response.event.last_read_message_id,
                unread_messages: 0
              });
              setLastRead(new Date());
            }
            _context2.next = 17;
            break;
          case 14:
            _context2.prev = 14;
            _context2.t0 = _context2["catch"](7);
            console.log('Error marking channel as read:', _context2.t0);
          case 17:
          case "end":
            return _context2.stop();
        }
      }, _callee2, null, [[7, 14]]);
    }));
    return function (_x) {
      return _ref2.apply(this, arguments);
    };
  }(), defaultThrottleInterval, throttleOptions);
  var markRead = (0, _hooks.useStableCallback)(markReadInternal);
  var reloadThread = (0, _hooks.useStableCallback)((0, _asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee3() {
    var parentID, limit, queryResponse, updatedHasMore, updatedThreadMessages, _yield$channel$getMes, messages, _messages, threadMessage, formattedMessage;
    return _regenerator["default"].wrap(function _callee3$(_context3) {
      while (1) switch (_context3.prev = _context3.next) {
        case 0:
          if (!(!channel || !(thread != null && thread.id))) {
            _context3.next = 2;
            break;
          }
          return _context3.abrupt("return");
        case 2:
          setThreadLoadingMore(true);
          _context3.prev = 3;
          parentID = thread.id;
          limit = 50;
          channel.state.threads[parentID] = [];
          _context3.next = 9;
          return channel.getReplies(parentID, {
            limit: limit
          });
        case 9:
          queryResponse = _context3.sent;
          updatedHasMore = queryResponse.messages.length === limit;
          updatedThreadMessages = channel.state.threads[parentID] || [];
          loadMoreThreadFinished(updatedHasMore, updatedThreadMessages);
          _context3.next = 15;
          return channel.getMessagesById([parentID]);
        case 15:
          _yield$channel$getMes = _context3.sent;
          messages = _yield$channel$getMes.messages;
          _messages = (0, _slicedToArray2["default"])(messages, 1), threadMessage = _messages[0];
          if (threadMessage && !threadInstance) {
            formattedMessage = channel.state.formatMessage(threadMessage);
            setThread(formattedMessage);
          }
          _context3.next = 27;
          break;
        case 21:
          _context3.prev = 21;
          _context3.t0 = _context3["catch"](3);
          console.warn('Thread loading request failed with error', _context3.t0);
          if (_context3.t0 instanceof Error) {
            setError(_context3.t0);
          } else {
            setError(true);
          }
          setThreadLoadingMore(false);
          throw _context3.t0;
        case 27:
        case "end":
          return _context3.stop();
      }
    }, _callee3, null, [[3, 21]]);
  })));
  var resyncChannel = (0, _hooks.useStableCallback)((0, _asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee4() {
    var parseMessage, _channelMessagesState, failedMessages, failedThreadMessages;
    return _regenerator["default"].wrap(function _callee4$(_context4) {
      while (1) switch (_context4.prev = _context4.next) {
        case 0:
          if (!(!channel || syncingChannelRef.current)) {
            _context4.next = 2;
            break;
          }
          return _context4.abrupt("return");
        case 2:
          syncingChannelRef.current = true;
          setError(false);
          parseMessage = function parseMessage(message) {
            var _message$pinned_at, _message$updated_at;
            return Object.assign({}, message, {
              created_at: message.created_at.toString(),
              pinned_at: (_message$pinned_at = message.pinned_at) == null ? void 0 : _message$pinned_at.toString(),
              updated_at: (_message$updated_at = message.updated_at) == null ? void 0 : _message$updated_at.toString()
            });
          };
          _context4.prev = 5;
          if (!(channelMessagesState != null && channelMessagesState.messages)) {
            _context4.next = 9;
            break;
          }
          _context4.next = 9;
          return channel == null ? void 0 : channel.watch({
            messages: {
              limit: channelMessagesState.messages.length + 30
            }
          });
        case 9:
          if (thread) {
            _context4.next = 16;
            break;
          }
          copyChannelState();
          failedMessages = (_channelMessagesState = channelMessagesState.messages) == null ? void 0 : _channelMessagesState.filter(function (message) {
            return message.status === _utils.MessageStatusTypes.FAILED;
          }).map(parseMessage);
          if (failedMessages != null && failedMessages.length) {
            channel.state.addMessagesSorted(failedMessages);
          }
          channel.state.setIsUpToDate(true);
          _context4.next = 20;
          break;
        case 16:
          _context4.next = 18;
          return reloadThread();
        case 18:
          failedThreadMessages = thread ? threadMessages.filter(function (message) {
            return message.status === _utils.MessageStatusTypes.FAILED;
          }).map(parseMessage) : [];
          if (failedThreadMessages.length) {
            channel.state.addMessagesSorted(failedThreadMessages);
            setThreadMessages((0, _toConsumableArray2["default"])(channel.state.threads[thread.id]));
          }
        case 20:
          _context4.next = 25;
          break;
        case 22:
          _context4.prev = 22;
          _context4.t0 = _context4["catch"](5);
          if (_context4.t0 instanceof Error) {
            setError(_context4.t0);
          } else {
            setError(true);
          }
        case 25:
          syncingChannelRef.current = false;
        case 26:
        case "end":
          return _context4.stop();
      }
    }, _callee4, null, [[5, 22]]);
  })));
  var resyncChannelRef = (0, _react.useRef)(resyncChannel);
  resyncChannelRef.current = resyncChannel;
  (0, _react.useEffect)(function () {
    var connectionChangedHandler = function connectionChangedHandler() {
      if (shouldSyncChannel) {
        resyncChannelRef.current();
      }
    };
    var connectionChangedSubscription;
    if (enableOfflineSupport && client.offlineDb) {
      connectionChangedSubscription = client.offlineDb.syncManager.onSyncStatusChange(function (statusChanged) {
        if (statusChanged) {
          connectionChangedHandler();
        }
      });
    } else {
      connectionChangedSubscription = client.on('connection.changed', function (event) {
        if (event.online) {
          connectionChangedHandler();
        }
      });
    }
    return function () {
      connectionChangedSubscription.unsubscribe();
    };
  }, [enableOfflineSupport, client, shouldSyncChannel]);
  var getChannelConfigSafely = function getChannelConfigSafely() {
    try {
      return channel == null ? void 0 : channel.getConfig();
    } catch (_) {
      return null;
    }
  };
  var clientChannelConfig = getChannelConfigSafely();
  var reloadChannel = (0, _hooks.useStableCallback)((0, _asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee5() {
    return _regenerator["default"].wrap(function _callee5$(_context5) {
      while (1) switch (_context5.prev = _context5.next) {
        case 0:
          _context5.prev = 0;
          _context5.next = 3;
          return loadLatestMessages();
        case 3:
          _context5.next = 8;
          break;
        case 5:
          _context5.prev = 5;
          _context5.t0 = _context5["catch"](0);
          console.warn('Reloading channel failed with error:', _context5.t0);
        case 8:
        case "end":
          return _context5.stop();
      }
    }, _callee5, null, [[0, 5]]);
  })));
  var loadChannelAroundMessage = (0, _hooks.useStableCallback)(function () {
    var _ref8 = (0, _asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee6(_ref7) {
      var messageIdToLoadAround;
      return _regenerator["default"].wrap(function _callee6$(_context6) {
        while (1) switch (_context6.prev = _context6.next) {
          case 0:
            messageIdToLoadAround = _ref7.messageId;
            if (messageIdToLoadAround) {
              _context6.next = 3;
              break;
            }
            return _context6.abrupt("return");
          case 3:
            _context6.prev = 3;
            if (!thread) {
              _context6.next = 20;
              break;
            }
            setThreadLoadingMore(true);
            _context6.prev = 6;
            _context6.next = 9;
            return channel.state.loadMessageIntoState(messageIdToLoadAround, thread.id);
          case 9:
            setThreadLoadingMore(false);
            setThreadMessages(channel.state.threads[thread.id]);
            if (setTargetedMessage) {
              setTargetedMessage(messageIdToLoadAround);
            }
            _context6.next = 18;
            break;
          case 14:
            _context6.prev = 14;
            _context6.t0 = _context6["catch"](6);
            if (_context6.t0 instanceof Error) {
              setError(_context6.t0);
            } else {
              setError(true);
            }
            setThreadLoadingMore(false);
          case 18:
            _context6.next = 22;
            break;
          case 20:
            _context6.next = 22;
            return loadChannelAroundMessageFn({
              messageId: messageIdToLoadAround,
              setTargetedMessage: setTargetedMessage
            });
          case 22:
            _context6.next = 27;
            break;
          case 24:
            _context6.prev = 24;
            _context6.t1 = _context6["catch"](3);
            console.warn('Loading channel around message failed with error:', _context6.t1);
          case 27:
          case "end":
            return _context6.stop();
        }
      }, _callee6, null, [[3, 24], [6, 14]]);
    }));
    return function (_x2) {
      return _ref8.apply(this, arguments);
    };
  }());
  var updateMessage = (0, _hooks.useStableCallback)(function (updatedMessage) {
    var extraState = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
    var throttled = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
    if (!channel) {
      return;
    }
    channel.state.addMessageSorted(updatedMessage, true);
    if (throttled) {
      copyMessagesStateFromChannelThrottled();
    } else {
      copyMessagesStateFromChannel(channel);
    }
    if (thread && updatedMessage.parent_id) {
      extraState.threadMessages = channel.state.threads[updatedMessage.parent_id] || [];
      setThreadMessages(extraState.threadMessages);
    }
  });
  var replaceMessage = (0, _hooks.useStableCallback)(function (oldMessage, newMessage) {
    if (channel) {
      channel.state.removeMessage(oldMessage);
      channel.state.addMessageSorted(newMessage, true);
      copyMessagesStateFromChannel(channel);
      if (thread && newMessage.parent_id) {
        var _threadMessages = channel.state.threads[newMessage.parent_id] || [];
        setThreadMessages(_threadMessages);
      }
    }
  });
  var createMessagePreview = (0, _hooks.useStableCallback)(function (_ref9) {
    var attachments = _ref9.attachments,
      mentioned_users = _ref9.mentioned_users,
      parent_id = _ref9.parent_id,
      poll_id = _ref9.poll_id,
      text = _ref9.text,
      extraFields = (0, _objectWithoutProperties2["default"])(_ref9, _excluded3);
    var _client$user2 = client.user,
      channel_mutes = _client$user2.channel_mutes,
      devices = _client$user2.devices,
      mutes = _client$user2.mutes,
      messageUser = (0, _objectWithoutProperties2["default"])(_client$user2, _excluded4);
    var preview = Object.assign({
      __html: text,
      attachments: attachments,
      created_at: new Date(),
      html: text,
      id: "".concat(client.userID, "-").concat((0, _utils.generateRandomId)()),
      mentioned_users: (mentioned_users == null ? void 0 : mentioned_users.map(function (userId) {
        return {
          id: userId
        };
      })) || [],
      parent_id: parent_id,
      poll_id: poll_id,
      reactions: [],
      status: _utils.MessageStatusTypes.SENDING,
      text: text,
      type: 'regular',
      user: Object.assign({}, messageUser, {
        id: client.userID
      })
    }, extraFields);
    if (preview.quoted_message_id) {
      var _channelMessagesState2;
      var _quotedMessage = (_channelMessagesState2 = channelMessagesState.messages) == null ? void 0 : _channelMessagesState2.find(function (message) {
        return message.id === preview.quoted_message_id;
      });
      preview.quoted_message = _quotedMessage;
    }
    return preview;
  });
  var uploadPendingAttachments = (0, _hooks.useStableCallback)(function () {
    var _ref10 = (0, _asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee7(message) {
      var _updatedMessage$attac;
      var updatedMessage, i, _updatedMessage$attac2, attachment, image, file, _image$name, filename, controller, compressedUri, contentType, uploadResponse, _controller, response;
      return _regenerator["default"].wrap(function _callee7$(_context7) {
        while (1) switch (_context7.prev = _context7.next) {
          case 0:
            updatedMessage = Object.assign({}, message);
            if (!((_updatedMessage$attac = updatedMessage.attachments) != null && _updatedMessage$attac.length)) {
              _context7.next = 50;
              break;
            }
            i = 0;
          case 3:
            if (!(i < ((_updatedMessage$attac2 = updatedMessage.attachments) == null ? void 0 : _updatedMessage$attac2.length))) {
              _context7.next = 50;
              break;
            }
            attachment = updatedMessage.attachments[i];
            image = attachment.originalImage;
            file = attachment.originalFile;
            if (!(attachment.type === _types.FileTypes.Image && image != null && image.uri && attachment.image_url && (0, _utils.isLocalUrl)(attachment.image_url))) {
              _context7.next = 29;
              break;
            }
            filename = (_image$name = image.name) != null ? _image$name : (0, _utils.getFileNameFromPath)(image.uri);
            controller = uploadAbortControllerRef.current.get(filename);
            if (controller) {
              controller.abort();
              uploadAbortControllerRef.current["delete"](filename);
            }
            _context7.next = 13;
            return (0, _compressImage.compressedImageURI)(image, compressImageQuality);
          case 13:
            compressedUri = _context7.sent;
            contentType = (0, _mimeTypes.lookup)(filename) || 'multipart/form-data';
            if (!doImageUploadRequest) {
              _context7.next = 21;
              break;
            }
            _context7.next = 18;
            return doImageUploadRequest(image, channel);
          case 18:
            _context7.t0 = _context7.sent;
            _context7.next = 24;
            break;
          case 21:
            _context7.next = 23;
            return channel.sendImage(compressedUri, filename, contentType);
          case 23:
            _context7.t0 = _context7.sent;
          case 24:
            uploadResponse = _context7.t0;
            attachment.image_url = uploadResponse.file;
            delete attachment.originalFile;
            _context7.next = 29;
            return dbApi.updateMessage({
              message: Object.assign({}, updatedMessage, {
                cid: channel.cid
              })
            });
          case 29:
            if (!((attachment.type === _types.FileTypes.File || attachment.type === _types.FileTypes.Audio || attachment.type === _types.FileTypes.VoiceRecording || attachment.type === _types.FileTypes.Video) && attachment.asset_url && (0, _utils.isLocalUrl)(attachment.asset_url) && file != null && file.uri)) {
              _context7.next = 47;
              break;
            }
            _controller = uploadAbortControllerRef.current.get(file.name);
            if (_controller) {
              _controller.abort();
              uploadAbortControllerRef.current["delete"](file.name);
            }
            if (!doDocUploadRequest) {
              _context7.next = 38;
              break;
            }
            _context7.next = 35;
            return doDocUploadRequest(file, channel);
          case 35:
            _context7.t1 = _context7.sent;
            _context7.next = 41;
            break;
          case 38:
            _context7.next = 40;
            return channel.sendFile(file.uri, file.name, file.type);
          case 40:
            _context7.t1 = _context7.sent;
          case 41:
            response = _context7.t1;
            attachment.asset_url = response.file;
            if (response.thumb_url) {
              attachment.thumb_url = response.thumb_url;
            }
            delete attachment.originalFile;
            _context7.next = 47;
            return dbApi.updateMessage({
              message: Object.assign({}, updatedMessage, {
                cid: channel.cid
              })
            });
          case 47:
            i++;
            _context7.next = 3;
            break;
          case 50:
            return _context7.abrupt("return", updatedMessage);
          case 51:
          case "end":
            return _context7.stop();
        }
      }, _callee7);
    }));
    return function (_x3) {
      return _ref10.apply(this, arguments);
    };
  }());
  var sendMessageRequest = (0, _hooks.useStableCallback)(function () {
    var _ref11 = (0, _asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee9(message, retrying) {
      var failedMessageUpdated, handleFailedMessage, _messageResponse, updatedMessage, extraFields, attachments, id, mentioned_users, parent_id, text, mentionedUserIds, messageData, messageResponse, newMessageResponse;
      return _regenerator["default"].wrap(function _callee9$(_context9) {
        while (1) switch (_context9.prev = _context9.next) {
          case 0:
            failedMessageUpdated = false;
            handleFailedMessage = function () {
              var _ref12 = (0, _asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee8() {
                var updatedMessage;
                return _regenerator["default"].wrap(function _callee8$(_context8) {
                  while (1) switch (_context8.prev = _context8.next) {
                    case 0:
                      if (failedMessageUpdated) {
                        _context8.next = 9;
                        break;
                      }
                      updatedMessage = Object.assign({}, message, {
                        cid: channel.cid,
                        status: _utils.MessageStatusTypes.FAILED
                      });
                      updateMessage(updatedMessage);
                      threadInstance == null || threadInstance.upsertReplyLocally == null || threadInstance.upsertReplyLocally({
                        message: updatedMessage
                      });
                      optimisticallyUpdatedNewMessages["delete"](message.id);
                      if (!enableOfflineSupport) {
                        _context8.next = 8;
                        break;
                      }
                      _context8.next = 8;
                      return dbApi.updateMessage({
                        message: updatedMessage
                      });
                    case 8:
                      failedMessageUpdated = true;
                    case 9:
                    case "end":
                      return _context8.stop();
                  }
                }, _callee8);
              }));
              return function handleFailedMessage() {
                return _ref12.apply(this, arguments);
              };
            }();
            _context9.prev = 2;
            if (isOnline) {
              _context9.next = 6;
              break;
            }
            _context9.next = 6;
            return handleFailedMessage();
          case 6:
            _context9.next = 8;
            return uploadPendingAttachments(message);
          case 8:
            updatedMessage = _context9.sent;
            extraFields = (0, _omit["default"])(updatedMessage, ['__html', 'attachments', 'created_at', 'deleted_at', 'html', 'id', 'latest_reactions', 'mentioned_users', 'own_reactions', 'parent_id', 'quoted_message', 'reaction_counts', 'reaction_groups', 'reactions', 'status', 'text', 'type', 'updated_at', 'user']);
            attachments = updatedMessage.attachments, id = updatedMessage.id, mentioned_users = updatedMessage.mentioned_users, parent_id = updatedMessage.parent_id, text = updatedMessage.text;
            if (channel.id) {
              _context9.next = 13;
              break;
            }
            return _context9.abrupt("return");
          case 13:
            mentionedUserIds = (mentioned_users == null ? void 0 : mentioned_users.map(function (user) {
              return user.id;
            })) || [];
            messageData = Object.assign({
              attachments: attachments,
              id: id,
              mentioned_users: mentionedUserIds,
              parent_id: parent_id,
              text: (0, _patchMessageTextCommand.patchMessageTextCommand)(text != null ? text : '', mentionedUserIds)
            }, extraFields);
            messageResponse = {};
            if (!doSendMessageRequest) {
              _context9.next = 22;
              break;
            }
            _context9.next = 19;
            return doSendMessageRequest((channel == null ? void 0 : channel.cid) || '', messageData);
          case 19:
            messageResponse = _context9.sent;
            _context9.next = 26;
            break;
          case 22:
            if (!channel) {
              _context9.next = 26;
              break;
            }
            _context9.next = 25;
            return channel.sendMessage(messageData);
          case 25:
            messageResponse = _context9.sent;
          case 26:
            if (!((_messageResponse = messageResponse) != null && _messageResponse.message)) {
              _context9.next = 32;
              break;
            }
            newMessageResponse = Object.assign({}, messageResponse.message, {
              status: _utils.MessageStatusTypes.RECEIVED
            });
            if (!enableOfflineSupport) {
              _context9.next = 31;
              break;
            }
            _context9.next = 31;
            return dbApi.updateMessage({
              message: Object.assign({}, newMessageResponse, {
                cid: channel.cid
              })
            });
          case 31:
            if (retrying) {
              replaceMessage(message, newMessageResponse);
            } else {
              updateMessage(newMessageResponse, {}, true);
            }
          case 32:
            _context9.next = 39;
            break;
          case 34:
            _context9.prev = 34;
            _context9.t0 = _context9["catch"](2);
            console.log(_context9.t0);
            _context9.next = 39;
            return handleFailedMessage();
          case 39:
          case "end":
            return _context9.stop();
        }
      }, _callee9, null, [[2, 34]]);
    }));
    return function (_x4, _x5) {
      return _ref11.apply(this, arguments);
    };
  }());
  var sendMessage = (0, _hooks.useStableCallback)(function () {
    var _ref13 = (0, _asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee10(message) {
      var _channel$state;
      var messagePreview;
      return _regenerator["default"].wrap(function _callee10$(_context10) {
        while (1) switch (_context10.prev = _context10.next) {
          case 0:
            if (channel != null && (_channel$state = channel.state) != null && _channel$state.filterErrorMessages) {
              channel.state.filterErrorMessages();
            }
            messagePreview = createMessagePreview(Object.assign({}, message, {
              attachments: message.attachments || []
            }));
            updateMessage(messagePreview, {
              commands: [],
              messageInput: ''
            });
            threadInstance == null || threadInstance.upsertReplyLocally == null || threadInstance.upsertReplyLocally({
              message: messagePreview
            });
            optimisticallyUpdatedNewMessages.add(messagePreview.id);
            if (!enableOfflineSupport) {
              _context10.next = 8;
              break;
            }
            _context10.next = 8;
            return dbApi.upsertMessages({
              messages: [Object.assign({}, messagePreview, {
                cid: channel.cid,
                status: _utils.MessageStatusTypes.FAILED
              })]
            });
          case 8:
            _context10.next = 10;
            return sendMessageRequest(messagePreview);
          case 10:
          case "end":
            return _context10.stop();
        }
      }, _callee10);
    }));
    return function (_x6) {
      return _ref13.apply(this, arguments);
    };
  }());
  var retrySendMessage = (0, _hooks.useStableCallback)(function () {
    var _ref14 = (0, _asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee11(message) {
      var statusPendingMessage, messageWithoutReservedFields;
      return _regenerator["default"].wrap(function _callee11$(_context11) {
        while (1) switch (_context11.prev = _context11.next) {
          case 0:
            statusPendingMessage = Object.assign({}, message, {
              status: _utils.MessageStatusTypes.SENDING
            });
            messageWithoutReservedFields = (0, _removeReservedFields.removeReservedFields)(statusPendingMessage);
            if (!(0, _utils.isBouncedMessage)(message)) {
              updateMessage(messageWithoutReservedFields);
            }
            _context11.next = 5;
            return sendMessageRequest(messageWithoutReservedFields, true);
          case 5:
          case "end":
            return _context11.stop();
        }
      }, _callee11);
    }));
    return function (_x7) {
      return _ref14.apply(this, arguments);
    };
  }());
  var editMessage = (0, _hooks.useStableCallback)(function (updatedMessage) {
    return doUpdateMessageRequest ? doUpdateMessageRequest((channel == null ? void 0 : channel.cid) || '', updatedMessage) : client.updateMessage(updatedMessage);
  });
  var setEditingState = (0, _hooks.useStableCallback)(function (message) {
    clearQuotedMessageState();
    setEditing(message);
  });
  var setQuotedMessageState = (0, _hooks.useStableCallback)(function (messageOrBoolean) {
    setQuotedMessage(messageOrBoolean);
  });
  var clearEditingState = (0, _hooks.useStableCallback)(function () {
    return setEditing(undefined);
  });
  var clearQuotedMessageState = (0, _hooks.useStableCallback)(function () {
    return setQuotedMessage(undefined);
  });
  var removeMessage = (0, _hooks.useStableCallback)(function () {
    var _ref15 = (0, _asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee12(message) {
      return _regenerator["default"].wrap(function _callee12$(_context12) {
        while (1) switch (_context12.prev = _context12.next) {
          case 0:
            if (channel) {
              channel.state.removeMessage(message);
              copyMessagesStateFromChannel(channel);
              if (thread) {
                setThreadMessages(channel.state.threads[thread.id] || []);
              }
            }
            if (!client.offlineDb) {
              _context12.next = 4;
              break;
            }
            _context12.next = 4;
            return client.offlineDb.handleRemoveMessage({
              messageId: message.id
            });
          case 4:
          case "end":
            return _context12.stop();
        }
      }, _callee12);
    }));
    return function (_x8) {
      return _ref15.apply(this, arguments);
    };
  }());
  var sendReaction = (0, _hooks.useStableCallback)(function () {
    var _ref16 = (0, _asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee13(type, messageId) {
      var payload, sendReactionResponse;
      return _regenerator["default"].wrap(function _callee13$(_context13) {
        while (1) switch (_context13.prev = _context13.next) {
          case 0:
            if (!(!(channel != null && channel.id) || !client.user)) {
              _context13.next = 2;
              break;
            }
            throw new Error('Channel has not been initialized');
          case 2:
            payload = [messageId, {
              type: type
            }, {
              enforce_unique: enforceUniqueReaction
            }];
            if (!enableOfflineSupport) {
              _context13.next = 7;
              break;
            }
            _context13.next = 6;
            return (0, _addReactionToLocalState.addReactionToLocalState)({
              channel: channel,
              enforceUniqueReaction: enforceUniqueReaction,
              messageId: messageId,
              reactionType: type,
              user: client.user
            });
          case 6:
            copyMessagesStateFromChannel(channel);
          case 7:
            _context13.next = 9;
            return channel.sendReaction.apply(channel, payload);
          case 9:
            sendReactionResponse = _context13.sent;
            if (sendReactionResponse != null && sendReactionResponse.message) {
              threadInstance == null || threadInstance.upsertReplyLocally == null || threadInstance.upsertReplyLocally({
                message: sendReactionResponse.message
              });
            }
          case 11:
          case "end":
            return _context13.stop();
        }
      }, _callee13);
    }));
    return function (_x9, _x10) {
      return _ref16.apply(this, arguments);
    };
  }());
  var deleteMessage = (0, _hooks.useStableCallback)(function () {
    var _ref17 = (0, _asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee14(message) {
      var hardDelete,
        updatedMessage,
        data,
        _args14 = arguments;
      return _regenerator["default"].wrap(function _callee14$(_context14) {
        while (1) switch (_context14.prev = _context14.next) {
          case 0:
            hardDelete = _args14.length > 1 && _args14[1] !== undefined ? _args14[1] : false;
            if (channel.id) {
              _context14.next = 3;
              break;
            }
            throw new Error('Channel has not been initialized yet');
          case 3:
            if (!(message.status === _utils.MessageStatusTypes.FAILED)) {
              _context14.next = 7;
              break;
            }
            _context14.next = 6;
            return removeMessage(message);
          case 6:
            return _context14.abrupt("return");
          case 7:
            updatedMessage = Object.assign({}, message, {
              cid: channel.cid,
              deleted_at: new Date(),
              type: 'deleted'
            });
            updateMessage(updatedMessage);
            threadInstance == null || threadInstance.upsertReplyLocally({
              message: updatedMessage
            });
            _context14.next = 12;
            return client.deleteMessage(message.id, hardDelete);
          case 12:
            data = _context14.sent;
            if (data != null && data.message) {
              updateMessage(Object.assign({}, data.message));
            }
          case 14:
          case "end":
            return _context14.stop();
        }
      }, _callee14);
    }));
    return function (_x11) {
      return _ref17.apply(this, arguments);
    };
  }());
  var deleteReaction = (0, _hooks.useStableCallback)(function () {
    var _ref18 = (0, _asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee15(type, messageId) {
      var payload;
      return _regenerator["default"].wrap(function _callee15$(_context15) {
        while (1) switch (_context15.prev = _context15.next) {
          case 0:
            if (!(!(channel != null && channel.id) || !client.user)) {
              _context15.next = 2;
              break;
            }
            throw new Error('Channel has not been initialized');
          case 2:
            payload = [messageId, type];
            if (enableOfflineSupport) {
              channel.state.removeReaction({
                created_at: '',
                message_id: messageId,
                type: type,
                updated_at: ''
              });
              copyMessagesStateFromChannel(channel);
            }
            _context15.next = 6;
            return channel.deleteReaction.apply(channel, payload);
          case 6:
          case "end":
            return _context15.stop();
        }
      }, _callee15);
    }));
    return function (_x12, _x13) {
      return _ref18.apply(this, arguments);
    };
  }());
  var openThread = (0, _react.useCallback)(function (message) {
    setThread(message);
    if (channel.initialized) {
      channel.markRead({
        thread_id: message.id
      });
    }
  }, [channel, setThread]);
  var closeThread = (0, _react.useCallback)(function () {
    setThread(null);
    setThreadMessages([]);
  }, [setThread, setThreadMessages]);
  var loadMoreThreadFinished = (0, _react.useRef)((0, _debounce["default"])(function (newThreadHasMore, updatedThreadMessages) {
    setThreadHasMore(newThreadHasMore);
    setThreadLoadingMore(false);
    setThreadMessages(updatedThreadMessages);
  }, defaultDebounceInterval, debounceOptions)).current;
  var loadMoreThread = (0, _hooks.useStableCallback)((0, _asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee16() {
    var _threadMessages$, parentID, oldestMessageID, limit, queryResponse, updatedHasMore, updatedThreadMessages;
    return _regenerator["default"].wrap(function _callee16$(_context16) {
      while (1) switch (_context16.prev = _context16.next) {
        case 0:
          if (!(threadLoadingMore || !(thread != null && thread.id))) {
            _context16.next = 2;
            break;
          }
          return _context16.abrupt("return");
        case 2:
          setThreadLoadingMore(true);
          _context16.prev = 3;
          if (!channel) {
            _context16.next = 15;
            break;
          }
          parentID = thread.id;
          channel.state.threads[parentID] = threadMessages;
          oldestMessageID = threadMessages == null || (_threadMessages$ = threadMessages[0]) == null ? void 0 : _threadMessages$.id;
          limit = 50;
          _context16.next = 11;
          return channel.getReplies(parentID, {
            id_lt: oldestMessageID,
            limit: limit
          });
        case 11:
          queryResponse = _context16.sent;
          updatedHasMore = queryResponse.messages.length === limit;
          updatedThreadMessages = channel.state.threads[parentID] || [];
          loadMoreThreadFinished(updatedHasMore, updatedThreadMessages);
        case 15:
          _context16.next = 23;
          break;
        case 17:
          _context16.prev = 17;
          _context16.t0 = _context16["catch"](3);
          console.warn('Message pagination request failed with error', _context16.t0);
          if (_context16.t0 instanceof Error) {
            setError(_context16.t0);
          } else {
            setError(true);
          }
          setThreadLoadingMore(false);
          throw _context16.t0;
        case 23:
        case "end":
          return _context16.stop();
      }
    }, _callee16, null, [[3, 17]]);
  })));
  var ownCapabilitiesContext = (0, _useCreateOwnCapabilitiesContext.useCreateOwnCapabilitiesContext)({
    channel: channel,
    overrideCapabilities: overrideOwnCapabilities
  });
  var channelContext = (0, _useCreateChannelContext.useCreateChannelContext)({
    channel: channel,
    channelUnreadState: channelUnreadState,
    disabled: !!(channel != null && (_channel$data = channel.data) != null && _channel$data.frozen),
    EmptyStateIndicator: EmptyStateIndicator,
    enableMessageGroupingByUser: enableMessageGroupingByUser,
    enforceUniqueReaction: enforceUniqueReaction,
    error: error,
    giphyEnabled: giphyEnabled != null ? giphyEnabled : !!((_ref20 = (clientChannelConfig == null ? void 0 : clientChannelConfig.commands) || []) != null && _ref20.some(function (command) {
      return command.name === 'giphy';
    })),
    hideDateSeparators: hideDateSeparators,
    hideStickyDateHeader: hideStickyDateHeader,
    highlightedMessageId: highlightedMessageId,
    isChannelActive: shouldSyncChannel,
    lastRead: lastRead,
    loadChannelAroundMessage: loadChannelAroundMessage,
    loadChannelAtFirstUnreadMessage: loadChannelAtFirstUnreadMessage,
    loading: channelMessagesState.loading,
    LoadingIndicator: LoadingIndicator,
    markRead: markRead,
    maxTimeBetweenGroupedMessages: maxTimeBetweenGroupedMessages,
    members: (_channelState$members = channelState.members) != null ? _channelState$members : {},
    NetworkDownIndicator: NetworkDownIndicator,
    read: (_channelState$read = channelState.read) != null ? _channelState$read : {},
    reloadChannel: reloadChannel,
    scrollToFirstUnreadThreshold: scrollToFirstUnreadThreshold,
    setChannelUnreadState: setChannelUnreadState,
    setLastRead: setLastRead,
    setTargetedMessage: setTargetedMessage,
    StickyHeader: StickyHeader,
    targetedMessage: targetedMessage,
    threadList: threadList,
    uploadAbortControllerRef: uploadAbortControllerRef,
    watcherCount: channelState.watcherCount,
    watchers: channelState.watchers
  });
  var inputMessageInputContext = (0, _useCreateInputMessageInputContext.useCreateInputMessageInputContext)({
    additionalTextInputProps: additionalTextInputProps,
    asyncMessagesLockDistance: asyncMessagesLockDistance,
    asyncMessagesMinimumPressDuration: asyncMessagesMinimumPressDuration,
    asyncMessagesMultiSendEnabled: asyncMessagesMultiSendEnabled,
    asyncMessagesSlideToCancelDistance: asyncMessagesSlideToCancelDistance,
    AttachButton: AttachButton,
    AudioAttachmentUploadPreview: AudioAttachmentUploadPreview,
    AudioRecorder: AudioRecorder,
    audioRecordingEnabled: audioRecordingEnabled,
    AudioRecordingInProgress: AudioRecordingInProgress,
    AudioRecordingLockIndicator: AudioRecordingLockIndicator,
    AudioRecordingPreview: AudioRecordingPreview,
    AudioRecordingWaveform: AudioRecordingWaveform,
    autoCompleteSuggestionsLimit: autoCompleteSuggestionsLimit,
    autoCompleteTriggerSettings: autoCompleteTriggerSettings,
    channelId: channelId,
    clearEditingState: clearEditingState,
    clearQuotedMessageState: clearQuotedMessageState,
    CommandsButton: CommandsButton,
    compressImageQuality: compressImageQuality,
    CooldownTimer: CooldownTimer,
    CreatePollContent: CreatePollContent,
    doDocUploadRequest: doDocUploadRequest,
    doImageUploadRequest: doImageUploadRequest,
    editing: editing,
    editMessage: editMessage,
    emojiSearchIndex: emojiSearchIndex,
    FileUploadPreview: FileUploadPreview,
    handleAttachButtonPress: handleAttachButtonPress,
    hasCameraPicker: hasCameraPicker,
    hasCommands: hasCommands != null ? hasCommands : ((_getChannelConfigSafe = (_getChannelConfigSafe2 = getChannelConfigSafely()) == null ? void 0 : _getChannelConfigSafe2.commands) != null ? _getChannelConfigSafe : []).length > 0,
    hasFilePicker: hasFilePicker,
    hasImagePicker: hasImagePicker,
    ImageUploadPreview: ImageUploadPreview,
    initialValue: initialValue,
    Input: Input,
    InputButtons: InputButtons,
    InputEditingStateHeader: InputEditingStateHeader,
    InputGiphySearch: InputGiphySearch,
    InputReplyStateHeader: InputReplyStateHeader,
    maxMessageLength: (_ref21 = maxMessageLengthProp != null ? maxMessageLengthProp : clientChannelConfig == null ? void 0 : clientChannelConfig.max_message_length) != null ? _ref21 : undefined,
    maxNumberOfFiles: maxNumberOfFiles,
    mentionAllAppUsersEnabled: mentionAllAppUsersEnabled,
    mentionAllAppUsersQuery: mentionAllAppUsersQuery,
    MoreOptionsButton: MoreOptionsButton,
    numberOfLines: numberOfLines,
    onChangeText: onChangeText,
    openPollCreationDialog: openPollCreationDialog,
    quotedMessage: quotedMessage,
    SendButton: SendButton,
    sendImageAsync: sendImageAsync,
    sendMessage: sendMessage,
    SendMessageDisallowedIndicator: SendMessageDisallowedIndicator,
    setInputRef: setInputRef,
    setQuotedMessageState: setQuotedMessageState,
    ShowThreadMessageInChannelButton: ShowThreadMessageInChannelButton,
    StartAudioRecordingButton: StartAudioRecordingButton,
    StopMessageStreamingButton: StopMessageStreamingButton,
    UploadProgressIndicator: UploadProgressIndicator
  });
  var messageListContext = (0, _useCreatePaginatedMessageListContext.useCreatePaginatedMessageListContext)({
    channelId: channelId,
    hasMore: channelMessagesState.hasMore,
    loadingMore: loadingMoreProp !== undefined ? loadingMoreProp : channelMessagesState.loadingMore,
    loadingMoreRecent: loadingMoreRecentProp !== undefined ? loadingMoreRecentProp : channelMessagesState.loadingMoreRecent,
    loadLatestMessages: loadLatestMessages,
    loadMore: loadMore,
    loadMoreRecent: loadMoreRecent,
    messages: (_channelMessagesState3 = channelMessagesState.messages) != null ? _channelMessagesState3 : []
  });
  var messagesContext = (0, _useCreateMessagesContext.useCreateMessagesContext)({
    additionalPressableProps: additionalPressableProps,
    Attachment: Attachment,
    AttachmentActions: AttachmentActions,
    AudioAttachment: AudioAttachment,
    Card: Card,
    CardCover: CardCover,
    CardFooter: CardFooter,
    CardHeader: CardHeader,
    channelId: channelId,
    clearQuotedMessageState: clearQuotedMessageState,
    DateHeader: DateHeader,
    deletedMessagesVisibilityType: deletedMessagesVisibilityType,
    deleteMessage: deleteMessage,
    deleteReaction: deleteReaction,
    disableTypingIndicator: disableTypingIndicator,
    dismissKeyboardOnMessageTouch: dismissKeyboardOnMessageTouch,
    enableMessageGroupingByUser: enableMessageGroupingByUser,
    enableSwipeToReply: enableSwipeToReply,
    FileAttachment: FileAttachment,
    FileAttachmentGroup: FileAttachmentGroup,
    FileAttachmentIcon: FileAttachmentIcon,
    FlatList: FlatList,
    forceAlignMessages: forceAlignMessages,
    Gallery: Gallery,
    getMessagesGroupStyles: getMessagesGroupStyles,
    Giphy: Giphy,
    giphyVersion: giphyVersion,
    handleBan: handleBan,
    handleCopy: handleCopy,
    handleDelete: handleDelete,
    handleEdit: handleEdit,
    handleFlag: handleFlag,
    handleMarkUnread: handleMarkUnread,
    handleMute: handleMute,
    handlePinMessage: handlePinMessage,
    handleQuotedReply: handleQuotedReply,
    handleReaction: handleReaction,
    handleRetry: handleRetry,
    handleThreadReply: handleThreadReply,
    hasCreatePoll: hasCreatePoll === undefined ? pollCreationEnabled : hasCreatePoll && pollCreationEnabled,
    ImageLoadingFailedIndicator: ImageLoadingFailedIndicator,
    ImageLoadingIndicator: ImageLoadingIndicator,
    ImageReloadIndicator: ImageReloadIndicator,
    initialScrollToFirstUnreadMessage: !messageId && initialScrollToFirstUnreadMessage,
    InlineDateSeparator: InlineDateSeparator,
    InlineUnreadIndicator: InlineUnreadIndicator,
    isAttachmentEqual: isAttachmentEqual,
    isMessageAIGenerated: isMessageAIGenerated,
    legacyImageViewerSwipeBehaviour: legacyImageViewerSwipeBehaviour,
    markdownRules: markdownRules,
    Message: Message,
    MessageActionList: MessageActionList,
    MessageActionListItem: MessageActionListItem,
    messageActions: messageActions,
    MessageAvatar: MessageAvatar,
    MessageBounce: MessageBounce,
    MessageContent: MessageContent,
    messageContentOrder: messageContentOrder,
    MessageDeleted: MessageDeleted,
    MessageEditedTimestamp: MessageEditedTimestamp,
    MessageError: MessageError,
    MessageFooter: MessageFooter,
    MessageHeader: MessageHeader,
    MessageList: MessageList,
    MessageMenu: MessageMenu,
    MessagePinnedHeader: MessagePinnedHeader,
    MessageReactionPicker: MessageReactionPicker,
    MessageReplies: MessageReplies,
    MessageRepliesAvatars: MessageRepliesAvatars,
    MessageSimple: MessageSimple,
    MessageStatus: MessageStatus,
    MessageSwipeContent: MessageSwipeContent,
    messageSwipeToReplyHitSlop: messageSwipeToReplyHitSlop,
    MessageSystem: MessageSystem,
    MessageText: MessageText,
    messageTextNumberOfLines: messageTextNumberOfLines,
    MessageTimestamp: MessageTimestamp,
    MessageUserReactions: MessageUserReactions,
    MessageUserReactionsAvatar: MessageUserReactionsAvatar,
    MessageUserReactionsItem: MessageUserReactionsItem,
    myMessageTheme: myMessageTheme,
    onLongPressMessage: onLongPressMessage,
    onPressInMessage: onPressInMessage,
    onPressMessage: onPressMessage,
    PollContent: PollContent,
    ReactionListBottom: ReactionListBottom,
    reactionListPosition: reactionListPosition,
    ReactionListTop: ReactionListTop,
    removeMessage: removeMessage,
    Reply: Reply,
    retrySendMessage: retrySendMessage,
    ScrollToBottomButton: ScrollToBottomButton,
    selectReaction: selectReaction,
    sendReaction: sendReaction,
    setEditingState: setEditingState,
    setQuotedMessageState: setQuotedMessageState,
    shouldShowUnreadUnderlay: shouldShowUnreadUnderlay,
    StreamingMessageView: StreamingMessageView,
    supportedReactions: supportedReactions,
    targetedMessage: targetedMessage,
    TypingIndicator: TypingIndicator,
    TypingIndicatorContainer: TypingIndicatorContainer,
    UnreadMessagesNotification: UnreadMessagesNotification,
    updateMessage: updateMessage,
    UrlPreview: UrlPreview,
    VideoThumbnail: VideoThumbnail
  });
  var suggestionsContext = (0, _react.useMemo)(function () {
    return {
      AutoCompleteSuggestionHeader: AutoCompleteSuggestionHeader,
      AutoCompleteSuggestionItem: AutoCompleteSuggestionItem,
      AutoCompleteSuggestionList: AutoCompleteSuggestionList
    };
  }, [AutoCompleteSuggestionHeader, AutoCompleteSuggestionItem, AutoCompleteSuggestionList]);
  var threadContext = (0, _useCreateThreadContext.useCreateThreadContext)({
    allowThreadMessagesInChannel: allowThreadMessagesInChannel,
    closeThread: closeThread,
    loadMoreThread: loadMoreThread,
    openThread: openThread,
    reloadThread: reloadThread,
    setThreadLoadingMore: setThreadLoadingMore,
    thread: thread,
    threadHasMore: threadHasMore,
    threadInstance: threadInstance,
    threadLoadingMore: threadLoadingMore,
    threadMessages: threadMessages
  });
  var typingContext = (0, _useCreateTypingContext.useCreateTypingContext)({
    typing: (_channelState$typing = channelState.typing) != null ? _channelState$typing : {}
  });
  if (deleted) {
    return null;
  }
  if (!channel || error && ((_channelMessagesState4 = channelMessagesState.messages) == null ? void 0 : _channelMessagesState4.length) === 0) {
    return (0, _jsxRuntime.jsx)(LoadingErrorIndicator, {
      error: error,
      listType: "message",
      retry: reloadChannel
    });
  }
  if (!(channel != null && channel.cid) || !channel.watch) {
    return (0, _jsxRuntime.jsx)(_reactNative.Text, {
      style: [styles.selectChannel, {
        color: black
      }, selectChannel],
      testID: "no-channel",
      children: t('Please select a channel first')
    });
  }
  return (0, _jsxRuntime.jsx)(KeyboardCompatibleView, Object.assign({
    behavior: keyboardBehavior,
    enabled: !disableKeyboardCompatibleView,
    keyboardVerticalOffset: keyboardVerticalOffset
  }, additionalKeyboardAvoidingViewProps, {
    children: (0, _jsxRuntime.jsx)(_ChannelContext.ChannelProvider, {
      value: channelContext,
      children: (0, _jsxRuntime.jsx)(_OwnCapabilitiesContext.OwnCapabilitiesProvider, {
        value: ownCapabilitiesContext,
        children: (0, _jsxRuntime.jsx)(_TypingContext.TypingProvider, {
          value: typingContext,
          children: (0, _jsxRuntime.jsx)(_PaginatedMessageListContext.PaginatedMessageListProvider, {
            value: messageListContext,
            children: (0, _jsxRuntime.jsx)(_MessagesContext.MessagesProvider, {
              value: messagesContext,
              children: (0, _jsxRuntime.jsx)(_ThreadContext.ThreadProvider, {
                value: threadContext,
                children: (0, _jsxRuntime.jsx)(_SuggestionsContext.SuggestionsProvider, {
                  value: suggestionsContext,
                  children: (0, _jsxRuntime.jsx)(_MessageInputContext.MessageInputProvider, {
                    value: inputMessageInputContext,
                    children: (0, _jsxRuntime.jsx)(_reactNative.View, {
                      style: {
                        height: '100%'
                      },
                      children: children
                    })
                  })
                })
              })
            })
          })
        })
      })
    })
  }));
};
var Channel = exports.Channel = function Channel(props) {
  var _useChatContext = (0, _ChatContext.useChatContext)(),
    client = _useChatContext.client,
    enableOfflineSupport = _useChatContext.enableOfflineSupport,
    isOnline = _useChatContext.isOnline,
    isMessageAIGenerated = _useChatContext.isMessageAIGenerated;
  var _useTranslationContex = (0, _TranslationContext.useTranslationContext)(),
    t = _useTranslationContex.t;
  var threadFromProps = props == null ? void 0 : props.thread;
  var threadInstance = threadFromProps == null ? void 0 : threadFromProps.threadInstance;
  var threadMessage = threadInstance ? threadFromProps.thread : threadFromProps;
  var thread = {
    thread: threadMessage,
    threadInstance: threadInstance
  };
  var shouldSyncChannel = threadMessage != null && threadMessage.id ? !!props.threadList : true;
  var _useChannelState = (0, _useChannelState2.useChannelState)(props.channel, props.threadList ? threadMessage == null ? void 0 : threadMessage.id : undefined),
    setThreadMessages = _useChannelState.setThreadMessages,
    threadMessages = _useChannelState.threadMessages;
  return (0, _jsxRuntime.jsx)(ChannelWithContext, Object.assign({
    client: client,
    enableOfflineSupport: enableOfflineSupport,
    t: t
  }, props, {
    shouldSyncChannel: shouldSyncChannel,
    isMessageAIGenerated: isMessageAIGenerated,
    isOnline: isOnline,
    setThreadMessages: setThreadMessages,
    thread: thread,
    threadMessages: threadMessages
  }));
};
//# sourceMappingURL=Channel.js.map