telegram-tt/dist/3.4bcadbdcb5986d5c9ba9.js.map
Alexander Zinchuk bedd3d2119 [Build]
2021-04-29 13:10:42 +03:00

1 line
796 KiB
Plaintext

{"version":3,"sources":["webpack:///./src/lib/lovely-chart/utils.js","webpack:///./src/modules/actions/ui/chats.ts","webpack:///./src/modules/actions/ui/messages.ts","webpack:///./src/modules/actions/ui/globalSearch.ts","webpack:///./src/modules/actions/ui/localSearch.ts","webpack:///./src/modules/actions/ui/stickerSearch.ts","webpack:///./src/modules/actions/ui/users.ts","webpack:///./src/modules/actions/ui/settings.ts","webpack:///./src/modules/actions/ui/misc.ts","webpack:///./src/modules/actions/ui/payments.ts","webpack:///./src/modules/actions/api/chats.ts","webpack:///./src/modules/actions/api/messages.ts","webpack:///./src/modules/actions/api/symbols.ts","webpack:///./src/modules/actions/api/globalSearch.ts","webpack:///./src/modules/actions/api/sync.ts","webpack:///./src/modules/actions/api/localSearch.ts","webpack:///./src/modules/actions/api/management.ts","webpack:///./src/modules/actions/api/users.ts","webpack:///./src/modules/actions/api/settings.ts","webpack:///./src/modules/actions/api/bots.ts","webpack:///./src/modules/actions/api/twoFaSettings.ts","webpack:///./src/modules/actions/api/payments.ts","webpack:///./src/util/requestQuery.ts","webpack:///./src/modules/actions/apiUpdaters/chats.ts","webpack:///./src/modules/actions/apiUpdaters/messages.ts","webpack:///./src/modules/actions/apiUpdaters/users.ts","webpack:///./src/modules/actions/apiUpdaters/symbols.ts","webpack:///./src/modules/actions/apiUpdaters/misc.ts","webpack:///./src/modules/actions/apiUpdaters/settings.ts","webpack:///./src/modules/actions/apiUpdaters/twoFaSettings.ts","webpack:///./src/components/ui/Switcher.tsx","webpack:///./src/components/left/main/LeftMainHeader.tsx","webpack:///./src/components/left/ConnectionState.tsx","webpack:///./src/hooks/useThrottledMemo.ts","webpack:///./src/hooks/useThrottle.ts","webpack:///./src/components/left/main/ChatFolders.tsx","webpack:///./src/components/left/search/LeftSearch.async.tsx","webpack:///./src/components/left/main/ContactList.async.tsx","webpack:///./src/components/left/NewChatButton.tsx","webpack:///./src/components/left/main/LeftMain.tsx","webpack:///./src/components/left/settings/Settings.async.tsx","webpack:///./src/components/left/newChat/NewChat.async.tsx","webpack:///./src/components/left/ArchivedChats.async.tsx","webpack:///./src/components/left/LeftColumn.tsx","webpack:///./src/hooks/useWindowSize.ts","webpack:///./src/hooks/usePrevForAnimation.ts","webpack:///./src/components/middle/helpers/calculateMiddleFooterTransforms.ts","webpack:///./src/hooks/useCurrentOrPrev.ts","webpack:///./src/components/middle/HeaderMenuContainer.async.tsx","webpack:///./src/components/middle/HeaderActions.tsx","webpack:///./src/hooks/useWebpThumbnail.ts","webpack:///./src/components/middle/PinnedMessageNavigation.tsx","webpack:///./src/components/middle/HeaderPinnedMessage.tsx","webpack:///./src/components/middle/AudioPlayer.tsx","webpack:///./src/components/middle/MiddleHeader.tsx","webpack:///./src/components/middle/helpers/groupMessages.ts","webpack:///./src/components/middle/hooks/useStickyDates.ts","webpack:///./src/hooks/useDebounce.ts","webpack:///./src/components/middle/MessageScroll.tsx","webpack:///./src/components/middle/message/helpers/buildContentClassName.ts","webpack:///./src/components/middle/message/helpers/mediaDimensions.ts","webpack:///./src/components/middle/message/helpers/calculateAlbumLayout.ts","webpack:///./src/components/middle/message/helpers/calculateAuthorWidth.ts","webpack:///./src/components/middle/message/hooks/useFocusMessage.ts","webpack:///./src/components/middle/message/ContextMenuContainer.async.tsx","webpack:///./src/components/middle/ActionMessage.tsx","webpack:///./src/components/common/EmbeddedMessage.tsx","webpack:///./src/components/middle/message/MessageMeta.tsx","webpack:///./src/components/middle/message/Sticker.tsx","webpack:///./src/components/middle/message/hooks/useBlurredMediaThumb.ts","webpack:///./src/components/middle/message/helpers/getCustomAppendixBg.ts","webpack:///./src/components/middle/message/Photo.tsx","webpack:///./src/hooks/useHeavyAnimationCheckForVideo.ts","webpack:///./src/components/middle/message/Video.tsx","webpack:///./src/components/middle/message/Contact.tsx","webpack:///./src/components/ui/CheckboxGroup.tsx","webpack:///./src/components/middle/message/PollOption.tsx","webpack:///./src/components/middle/message/Poll.tsx","webpack:///./src/components/middle/message/WebPage.tsx","webpack:///./src/components/middle/message/Invoice.tsx","webpack:///./src/components/middle/message/hocs/withSelectControl.tsx","webpack:///./src/components/middle/message/Album.tsx","webpack:///./src/components/middle/message/RoundVideo.tsx","webpack:///./src/components/middle/message/InlineButtons.tsx","webpack:///./src/components/middle/message/CommentButton.tsx","webpack:///./src/components/middle/message/Message.tsx","webpack:///./src/components/middle/MessageList.tsx","webpack:///./src/components/middle/ScrollDownButton.tsx","webpack:///./src/components/middle/composer/helpers/buildAttachment.ts","webpack:///./node_modules/opus-recorder/dist/encoderWorker.min.js","webpack:///./src/util/voiceRecording.ts","webpack:///./src/components/middle/composer/hooks/useClipboardPaste.ts","webpack:///./src/components/middle/composer/helpers/getMessageTextAsHtml.ts","webpack:///./src/components/middle/composer/hooks/useDraft.ts","webpack:///./src/components/common/DeleteMessageModal.async.tsx","webpack:///./src/components/ui/ResponsiveHoverButton.tsx","webpack:///./src/components/middle/composer/AttachMenu.async.tsx","webpack:///./src/components/middle/composer/SymbolMenu.async.tsx","webpack:///./src/components/middle/composer/MentionMenu.async.tsx","webpack:///./src/components/middle/composer/CustomSendMenu.async.tsx","webpack:///./src/components/middle/composer/EmojiTooltip.async.tsx","webpack:///./src/components/middle/composer/BotKeyboardMenu.async.tsx","webpack:///./src/components/middle/composer/ComposerEmbeddedMessage.tsx","webpack:///./src/components/middle/composer/AttachmentModal.async.tsx","webpack:///./src/components/middle/composer/PollModal.async.tsx","webpack:///./src/components/middle/composer/DropArea.async.tsx","webpack:///./src/components/middle/composer/WebPagePreview.tsx","webpack:///./src/components/common/CalendarModal.async.tsx","webpack:///./src/components/payment/PaymentModal.async.tsx","webpack:///./src/components/payment/ReceiptModal.async.tsx","webpack:///./src/components/middle/composer/Composer.tsx","webpack:///./src/components/middle/composer/hooks/useVoiceRecording.ts","webpack:///./src/components/middle/composer/hooks/useEmojiTooltip.ts","webpack:///./src/util/insertHtmlInSelection.ts","webpack:///./src/util/deleteLastCharacterOutsideSelection.ts","webpack:///./src/components/middle/composer/hooks/useEditing.ts","webpack:///./src/components/middle/MobileSearch.async.tsx","webpack:///./src/components/middle/MessageSelectToolbar.async.tsx","webpack:///./src/components/common/UnpinAllMessagesModal.async.tsx","webpack:///./src/components/middle/MiddleColumn.tsx","webpack:///./src/hooks/useCustomBackground.ts","webpack:///./src/components/right/RightHeader.tsx","webpack:///./src/components/right/hooks/useProfileViewportIds.ts","webpack:///./src/components/right/hooks/useProfileState.ts","webpack:///./src/components/right/UserExtra.tsx","webpack:///./src/components/right/ChatExtra.tsx","webpack:///./src/components/right/Profile.tsx","webpack:///./src/components/right/hooks/useTransitionFixes.ts","webpack:///./src/hooks/useCacheBuster.ts","webpack:///./src/components/right/RightSearch.async.tsx","webpack:///./src/components/right/management/Management.async.tsx","webpack:///./src/components/right/Statistics.async.tsx","webpack:///./src/components/right/StickerSearch.async.tsx","webpack:///./src/components/right/GifSearch.async.tsx","webpack:///./src/components/right/PollResults.async.tsx","webpack:///./src/components/right/RightColumn.tsx","webpack:///./src/components/mediaViewer/MediaViewer.async.tsx","webpack:///./src/components/main/Notifications.async.tsx","webpack:///./src/components/main/Errors.async.tsx","webpack:///./src/components/main/ForwardPicker.async.tsx","webpack:///./src/components/main/Main.tsx","webpack:///./src/bundles/main.ts"],"names":["getMaxMin","array","length","max","min","i","value","mergeArrays","arrays","concat","apply","sumArrays","sums","n","l","j","proxyMerge","obj1","obj2","Proxy","get","obj","prop","undefined","throttle","fn","ms","shouldRunFirst","isPending","args","interval","_args","window","setInterval","clearInterval","throttleWithRaf","waiting","requestAnimationFrame","debounce","shouldRunLast","waitingTimeout","clearTimeout","setTimeout","addEventListener","e","state","chatId","id","threadId","messageListType","type","getDispatch","openChat","noPushState","addReducer","global","actions","payload","currentMessageList","selectCurrentMessageList","exitMessageSelectMode","messages","contentToBeScheduled","forwardMessages","toChatId","setGlobal","history","pushState","updateCurrentMessageList","isChatInfoShown","chatCreation","blurTimeout","scrollOffset","replaceThreadParam","messageId","paramName","chatMessages","selectChatMessages","viewportIds","selectViewportIds","lastOwnEditableMessageId","findLast","Boolean","selectAllowedMessageActions","canEdit","avatarOwnerId","origin","mediaViewer","audioPlayer","selectIsRightColumnShown","pollResults","voters","newGlobal","getGlobal","lastMessageId","MAIN_THREAD_ID","chat","selectChat","lastMessage","threadInfo","selectThreadInfo","focusMessage","noHighlight","groupedId","groupedChatId","ids","selectForwardedMessageIdsByGroupId","shouldSwitchChat","updateFocusedMessage","updateFocusDirection","FocusDirection","Static","includes","direction","Down","Up","loadViewportMessages","fromChatId","messageIds","groupedMessageIds","selectMessageIdsByGroupId","isModalShown","closeMediaViewer","selectedMessages","openForwardMenu","selectCurrentChat","enterMessageSelectMode","childMessageIds","withShift","toggleMessageSelection","isPollModalOpen","query","globalSearch","updateGlobalSearch","globalResults","localResults","resultsByType","fetchingStatus","chats","recentlyFoundChatIds","newRecentIds","filter","unshift","pop","content","updateGlobalSearchContent","updateLocalTextSearch","replaceLocalTextSearchResults","chatThreadKey","buildChatThreadKey","currentQuery","localTextSearch","byChatThreadKey","MEMO_EMPTY_ARRAY","mediaType","updateLocalMediaSearchType","stickers","search","resultIds","gifs","offsetId","results","updateSelectedUserId","replaceSettings","management","byChatId","isActive","isStatisticsShown","IS_MOBILE_SCREEN","isLeftColumnShown","action","emoji","recentEmojis","newEmojis","sticker","recent","hash","newStickers","s","notification","newNotifications","notifications","existingNotificationIndex","findIndex","message","splice","push","error","getReadableErrorText","newErrors","errors","existingErrorIndex","err","payment","isPaymentModalOpen","clearPayment","closeInvoice","runThrottledForLoadChats","cb","runThrottledForLoadTopChats","runDebouncedForFetchFullChat","runDebouncedForFetchOnlines","async","loadChats","listType","offsetDate","result","callApi","limit","CHAT_LIST_LOAD_SLICE","archived","withPinned","orderedPinnedIds","chatIds","shift","addUsers","buildCollectionByKey","users","updateChats","updateChatListIds","updateChatListSecondaryInfo","Object","keys","draftsById","map","Number","forEach","replyingToById","isFullyLoaded","loadFullChat","fullInfo","updateChat","openChatByUsername","username","channelPostId","localChat","selectChatByUsername","isMin","previousChat","showNotification","preloadedChatIds","TOP_CHAT_MESSAGES_PRELOAD_LIMIT","pause","byId","listIds","active","currentChatId","pinnedChats","otherChats","prepareChatList","chatToPreload","find","IS_TOUCH_ENV","loadPinnedMessages","currentUserId","hasUnreadMark","toggleChatUnread","isChatSummaryOnly","requestChatUpdate","user","selectUser","selectThreadTopMessageId","requestThreadInfoUpdate","selectSupportChat","TIPS_USERNAME","oldestChat","selectIsChatPinned","sort","chat1","chat2","date","force","isMuted","title","about","photo","memberIds","progress","ChatCreationProgress","InProgress","createdChannel","channelId","accessHash","Complete","Error","createChannel","createdChat","createGroupChat","folderId","folder","selectChatFolder","shouldBePinned","pinnedChatIds","includedChatIds","newPinnedIds","pinnedId","newIncludedChatIds","folderUpdate","selectChatListType","isPinned","ARCHIVED_FOLDER_ID","isChatArchived","chatFolders","loadChatFolders","recommendedChatFolders","recommended","loadRecommendedChatFolders","emoticon","orderedIds","maxId","recommendedId","description","newFolder","createChatFolder","Math","deleteChatFolder","unreadCount","url","match","RE_TME_INVITE_LINK","exec","RE_TME_LINK","isEnabled","isChatBasicGroup","bannedRights","userId","chatAfterUpdate","members","kickedMembers","isBanned","viewMessages","isUnblocked","m","adminRights","customTitle","adminMembers","isDismissed","updateManagementProgress","ManagementProgress","Promise","all","groups","addedById","reduce","group","addChats","forDiscussionIds","channel","fullChat","isPreHistoryHidden","linkedChatId","uploadProgressCallbacks","Map","isOutlying","isBudgetPreload","addOffset","LoadMoreDirection","Backwards","Around","round","MESSAGE_LIST_SLICE","Forwards","selectThreadOriginChat","threadInfos","firstMessageId","addChatMessagesById","updateOutlyingIds","updateListedIds","updateThreadInfos","listedIds","selectListedIds","outlyingIds","selectOutlyingIds","areSortedArraysIntersecting","historyIds","newViewportIds","getViewportSlice","safeReplaceViewportIds","sourceIds","index","findClosestIndex","indexForDirection","from","to","slice","areSomeLocal","areAllLocal","sendMessage","params","localId","progressCallback","attachment","messageLocalId","has","set","fileUploads","byMessageLocalId","replyingTo","rafPromise","delete","isRestricted","resolve","loadWithBudget","selectFocusedMessageId","selectRealLastReadId","replyOriginForId","MESSAGE_DELETED","replyMessage","selectChatMessage","updateChatMessage","replyToMessageId","loadMessage","scheduledAt","setReplyingToId","clearWebPagePreview","selectReplyingToId","noWebPage","selectNoWebPage","isSingle","attachments","isGrouped","restParams","text","entities","commonParams","groupedAttachments","split","MAX_MEDIA_FILES_FOR_ALBUM","firstAttachment","restAttachments","Date","now","selectEditingMessage","setEditingId","previousLocalId","cancelApiProgress","apiUpdate","draft","replyToMsgId","localOnly","selectDraft","isUnpin","isOneSide","isSilent","unpinAllMessages","shouldDeleteForAll","editingId","selectEditingId","selectEditingScheduledId","webPagePreview","loadWebPagePreview","options","option","offset","shouldResetVoters","v","a","indexOf","offsets","nextOffset","loadPollOptionResults","fromChat","toChat","b","scheduledMessages","historyHash","replaceScheduledMessages","loadScheduledHistory","selectScheduledMessage","copyTextToClipboard","link","searchThrottled","searchGifs","updateGifSearch","added","addedStickers","updateStickerSets","sets","loadStickerSets","setIds","addedSetIds","loadStickers","stickerSetId","recentStickers","loadRecentStickers","favorite","favoriteStickers","loadFavoriteStickers","featured","featuredStickers","loadFeaturedStickers","stickerSetAccessHash","stickerSet","selectStickerSet","packs","updateStickerSet","currentEmoji","forEmoji","rebuildStickersForEmoji","replaceAnimatedEmojis","loadAnimatedEmojis","saved","savedGifs","loadSavedGifs","unfave","unfaveSticker","installedDate","setsById","searchWords","searchStickers","updateStickersForEmoji","loadStickersForEmoji","searchMessagesGlobal","offsetRate","maxDate","minDate","localResult","chatOrUser","GLOBAL_SEARCH_SLICE","totalCount","nextOffsetId","nextRate","currentSearchQuery","selectCurrentGlobalSearchQuery","updateGlobalSearchFetchingStatus","addMessages","updateGlobalSearchResults","loadAndReplaceArchivedChats","updateUsers","replaceChatListIds","loadAndUpdateUsers","userIds","contactIds","contactList","updatedUsers","localChats","localUsers","globalChats","globalUsers","searchChats","timestampPlusDay","foundIds","currentSearch","selectCurrentTextSearch","topMessageId","MESSAGE_SEARCH_SLICE","newFoundIds","updateLocalTextSearchResults","searchTextMessages","peerId","selectCurrentMediaSearchPeerId","selectCurrentMediaSearch","currentType","currentResults","SHARED_MEDIA_SLICE","updateLocalMediaSearchResults","searchSharedMedia","timestamp","searchMessagesByDate","updateManagement","isUsernameAvailable","afterSyncCallback","DEBUG","console","log","savedUsers","savedPrivateChatIds","savedChats","selectedChat","isChatPrivate","selectedChatUser","replaceChats","loadAndReplaceChats","areMessagesLoaded","draftsByChatId","acc","lastReadInboxMessageId","newCurrentChatId","currentMessageListInfo","threadsById","Array","prototype","replaceUsers","loadAndReplaceMessages","lastSyncTime","sync","afterSync","runDebouncedForFetchFullUser","buildInputPrivacyRules","visibility","allowedIds","deniedIds","usersById","chatsById","rules","collectUsers","collectChats","allowedUsers","allowedChats","blockedUsers","blockedChats","lastRequestedAt","topPeers","usersHash","loadTopUsers","getCompareString","lastName","firstName","collator","Intl","Collator","sortedUsers","compare","isSelf","loadContactList","updateChatMutedState","phone","phoneNumber","updateUser","updateContact","deleteUser","button","sendBotCommand","command","openTelegramLink","open","data","alert","isError","showError","answerCallbackButton","openPollModal","getReceipt","receiptMessageId","getPaymentForm","setInvoiceMessageInfo","openPaymentModal","bio","profileEdit","ProfileEditProgress","currentUser","Idle","settings","loadedWallpapers","wallpapers","file","previewBlobUrl","URL","createObjectURL","slug","UPLOADING_WALLPAPER_SLUG","document","fileName","size","mimeType","wallpaper","firstWallpaper","withLocalMedia","blocked","blockedIds","contactId","addBlockedContact","removeBlockedContact","activeSessions","session","isCurrent","peerType","isShowPreviews","updateNotifySettings","hasContactJoinedNotifications","languages","phoneNumberSettings","lastSeenSettings","profilePhotoSettings","forwardsSettings","chatInviteSettings","privacy","lastSeen","profilePhoto","forwards","chatInvite","privacyKey","allowUserIds","allowChatIds","blockUserIds","blockChatIds","isAllowList","contactsIds","hasPassword","updateTwoFaSettings","hint","currentPassword","onSuccess","isLoading","isSuccess","password","email","waitingEmailCodeLength","code","requestInfo","saveInfo","selectPaymentMessageId","shouldSave","shippingOptions","setRequestInfoId","updateShippingOptions","setPaymentStep","PaymentStep","Shipping","PaymentInfo","validateRequestedInfo","setPaymentForm","step","invoice","shippingAddressRequested","nameRequested","phoneRequested","emailRequested","ShippingInfo","setReceipt","receipt","publishableKey","selectProviderPublishableKey","credentials","k","join","buildQueryString","cardNumber","expiryMonth","expiryYear","cvv","zip","country","response","fetch","method","headers","Authorization","json","getStripeError","setStripeCardInfo","Checkout","sendStipeCredentials","shippingOptionId","saveCredentials","requestInfoId","selectPaymentRequestId","stripeCredentials","selectStripeCredentials","requestedInfoId","sendPaymentForm","save","update","selectIsChatListed","loadTopChats","isNotJoined","listId","typingStatus","senderId","isFromScheduled","hasUnreadMention","unreadMentionsCount","messageUpdate","selectCommonBoxChatId","targetChat","newOrderedPinnedIds","MAX_ACTIVE_PINNED_CHATS","updateChatListType","chatFoldersById","newChatFoldersById","pick","newOrderedIds","orderedId","folders","replacedMembers","addedMember","deletedMemberId","shouldUpdate","some","deleteIndex","isOwner","isAdmin","membersCount","updateWithLocalMedia","isScheduled","currentMessage","video","getMessageContent","blobUrl","thumbnail","isPreloadedGlobally","updateScheduledMessage","updateListedAndViewportIds","selectIsViewportNewest","addViewportId","selectThreadByMessage","isMessageLocal","updateChatLastMessage","currentLastMessage","findLastMessage","isDeleting","deleteMessages","newLastMessage","threadIdsToUpdate","unique","deleteChatMessages","chatsIdsToUpdate","commonBoxChatId","updateThreadInfo","newMessage","isMessageInCurrentMessageList","isOutgoing","scheduledIds","selectScheduledIds","selectScheduledMessages","deleteChatScheduledMessages","currentPinnedIds","selectPinnedIds","newTheadInfo","messagesById","deleteScheduledMessages","pollId","pollUpdate","selectChatMessageByPollId","poll","updatedPoll","updatedResults","isChosen","chosenAnswers","chosenAnswer","chosenAnswerIndex","recentVoterIds","totalVoters","newRecentVoterIds","newTotalVoters","newResults","targetOption","targetOptionIndex","updatedOption","votersCount","flushStatusUpdatesThrottled","pendingStatusUpdates","statusUpdate","status","targetUser","isBlocked","key","twoFaSettings","memo","name","label","checked","disabled","onChange","onCheck","handleChange","useCallback","event","currentTarget","className","buildClassName","ANIMATION_LEVEL_OPTIONS","withGlobal","searchQuery","theme","animationLevel","byKey","globalSearchChatId","searchDate","contactsFilter","onSearchQuery","onSelectSettings","onSelectContacts","onSelectArchived","setGlobalSearchChatId","onReset","openTipsChat","setGlobalSearchDate","setSettingOption","hasMenu","LeftColumnContent","ChatList","clearedDateSearchParam","clearedChatSearchParam","selectedSearchDate","useMemo","formatDateToString","archivedUnreadChatsCount","values","total","MainButton","onTrigger","isOpen","Button","ripple","color","onClick","ariaLabel","handleSearchFocus","handleSelectSaved","handleDarkModeToggle","stopPropagation","newTheme","isNewThemeDark","customBackground","DARK_THEME_BG_COLOR","patternColor","DARK_THEME_PATTERN_COLOR","DEFAULT_PATTERN_COLOR","switchTheme","handleAnimationLevelChange","newLevel","_","body","classList","toggle","lang","useLang","isSearchFocused","GlobalSearch","Contacts","searchInputPlaceholder","DropdownMenu","trigger","footer","APP_INFO","MenuItem","icon","toLowerCase","href","FEEDBACK_URL","SearchInput","inputId","focused","placeholder","canClose","onFocus","PickerSelectedItem","isMinimized","clickArg","chatOrUserId","connectionState","Spinner","resolverFn","dependencies","valueRef","useRef","runThrottled","useThrottle","forceUpdate","useForceUpdate","useOnChange","isSync","current","orderedFolderIds","transitionRef","activeTab","setActiveTab","useState","useEffect","displayedFolders","folderCountersById","useThrottledMemo","counters","unreadDialogsCount","hasActiveDialogs","getFolderUnreadDialogs","badgeCount","isBadgeActive","folderTabs","handleSwitchTab","captureEvents","onSwipe","SwipeDirection","Left","Right","shouldRender","shouldRenderPlaceholder","transitionClassNames","useShowTransition","renderCurrentTab","activeFolder","folderType","noChatsText","TabList","tabs","onSwitchTab","Transition","ref","activeKey","renderCount","LeftSearchAsync","props","LeftSearch","useModuleLoader","Bundles","Extra","Loading","ContactListAsync","ContactList","closeTimeout","isShown","onNewPrivateChat","onNewChannel","onNewGroup","isMenuOpen","setIsMenuOpen","fabClassName","handleMouseEnter","handleMouseLeave","onMouseEnter","onMouseLeave","tabIndex","Menu","positionX","positionY","autoClose","onClose","TRANSITION_RENDER_COUNT","onContentChange","isNewChatButtonShown","setIsNewChatButtonShown","isMouseInside","handleSelectSettings","Settings","handleSelectContacts","handleSelectNewChannel","NewChannelStep1","handleSelectNewGroup","NewGroupStep1","handleSelectArchived","Archived","autoCloseTimeout","SettingsAsync","NewChatAsync","NewChat","ArchivedChatsAsync","ContentType","ArchivedChats","RENDER_COUNT","setGlobalSearchQuery","resetChatCreation","loadPasswordInfo","clearTwoFaError","setContent","settingsScreen","setSettingsScreen","SettingsScreens","Main","setContactsFilter","lastResetTime","setLastResetTime","contentType","NewChannelStep2","NewChannel","NewGroupStep2","NewGroup","handleReset","forceReturnToChatList","pickerSearchInput","getElementById","blur","EditProfile","Folders","General","Notifications","Privacy","Language","GeneralChatBackground","GeneralChatBackgroundColor","PrivacyPhoneNumber","PrivacyLastSeen","PrivacyProfilePhoto","PrivacyForwarding","PrivacyGroupChats","PrivacyActiveSessions","PrivacyBlockedUsers","TwoFaDisabled","TwoFaEnabled","TwoFaCongratulations","PrivacyPhoneNumberAllowedContacts","PrivacyPhoneNumberDeniedContacts","PrivacyLastSeenAllowedContacts","PrivacyLastSeenDeniedContacts","PrivacyProfilePhotoAllowedContacts","PrivacyProfilePhotoDeniedContacts","PrivacyForwardingAllowedContacts","PrivacyForwardingDeniedContacts","PrivacyGroupChatsAllowedContacts","PrivacyGroupChatsDeniedContacts","TwoFaNewPassword","TwoFaNewPasswordConfirm","TwoFaNewPasswordHint","TwoFaNewPasswordEmail","TwoFaNewPasswordEmailCode","TwoFaChangePasswordCurrent","TwoFaTurnOff","TwoFaRecoveryEmailCurrentPassword","TwoFaChangePasswordNew","TwoFaChangePasswordConfirm","TwoFaChangePasswordHint","TwoFaRecoveryEmail","TwoFaRecoveryEmailCode","FoldersCreateFolder","FoldersEditFolder","handleSearchQuery","captureEscKeyListener","currentScreen","onScreenSelect","isChannel","setSize","windowSize","handleResize","removeEventListener","usePrevForAnimation","duration","prev","usePrevious","timeoutRef","isCurrentPresent","calculateMiddleFooterTransforms","windowWidth","canPost","sidePadding","MOBILE_SCREEN_MAX_WIDTH","messageListWidth","MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN","leftColumnWidth","rightColumnWidth","MIN_SCREEN_WIDTH_FOR_STATIC_LEFT_COLUMN","getMessageListWidth","sendButtonWidth","composerWidth","toolbarWidth","composerHiddenScale","toolbarHiddenScale","composerTranslateX","toolbarTranslateX","unpinHiddenScale","toolbarForUnpinHiddenScale","useCurrentOrPrev","shouldSkipUndefined","shouldForceCurrent","HeaderMenuContainerAsync","HeaderMenuContainer","isChatChannel","noMenu","isChatWithSelf","selectIsChatWithSelf","isMainThread","isDiscussionThread","isRightColumnShown","canStartBot","selectIsChatBotNotStarted","canSubscribe","isChatSuperGroup","canSearch","canMute","canSelect","selectIsInSelectMode","canLeave","joinChannel","openLocalTextSearch","menuButtonRef","menuPosition","setMenuPosition","handleHeaderMenuOpen","rect","getBoundingClientRect","x","right","y","bottom","handleHeaderMenuClose","handleHeaderMenuHide","handleSubscribeClick","handleStartBot","handleSearchClick","querySelector","focus","searchInput","fluid","anchor","onSubscribeChannel","onSearchClick","onCloseAnimationEnd","useWebpThumbnail","getMessageMediaThumbDataUri","shouldDecodeThumbnail","isWebpSupported","thumbnailDecoded","setThumbnailDecoded","EMPTY_IMAGE_DATA_URI","useLayoutEffect","webpToPngBase64","then","catch","drawRect","width","height","radius","count","containerRef","markupParams","reverseIndex","barHeight","getBarHeight","markHeight","getMarkHeight","trackHeight","getTrackHeight","clipPathId","clipPath","d","getClipPath","markTranslateY","getMarkTranslateY","trackTranslateY","getTrackTranslateY","calculateMarkup","firstChild","firstElementChild","currentElement","style","transform","svg","div","defs","innerHTML","onUnpinMessage","onAllPinnedClick","mediaThumbnail","mediaBlobUrl","useMedia","getMessageMediaHash","getMessageSummaryText","isUnpinDialogOpen","openUnpinDialog","closeUnpinDialog","useFlag","handleUnpinMessage","ConfirmDialog","confirmLabel","confirmHandler","thumbDataUri","getPictogramDimensions","src","alt","renderPictogram","renderText","RippleEffect","sender","selectSender","senderName","getSenderTitle","noUi","closeAudioPlayer","mediaData","mediaLoader","playPause","isPlaying","useAudioPlayer","getMessageKey","getMediaDuration","handleClick","handleClose","audio","getMessageAudio","performer","renderAudio","subtitle","renderVoice","audioChatId","audioMessageId","audioMessage","originChat","messagesCount","pinnedIds","isSelectModeActive","chatTitleLength","getChatTitle","originChatId","isChatWithBot","selectIsChatWithBot","pinnedMessageIds","firstPinnedMessage","canUnpin","pinnedMessageId","selectForwardedSender","topMessageTitle","openChatWithInfo","pinMessage","toggleLeftColumn","pinnedMessageIndex","setPinnedMessageIndex","isArray","pinnedMessage","pinnedMessagesCount","cycleRestrict","useEnsureMessage","useWindowSize","isLeftColumnHideable","shouldShowCloseButton","componentRef","shouldAnimateTools","handleHeaderClick","handlePinnedMessageClick","newIndex","handleAllPinnedClick","handleBackClick","messageInput","EDITABLE_INPUT_ID","canToolsCollideWithChatInfo","SAFE_SCREEN_WIDTH_FOR_CHAT_INFO","shouldUseStackedToolsClass","SAFE_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN","shouldRenderAudioPlayer","audioPlayerClassNames","renderingAudioMessage","shouldRenderPinnedMessage","pinnedMessageClassNames","renderingPinnedMessage","renderingPinnedMessageTitle","canRevealTools","componentEl","add","remove","renderInfo","renderBackButton","PrivateChatInfo","withFullInfo","withMediaViewer","withUpdatingStatus","GroupChatInfo","asClose","unreadCountInfo","formatIntegerCompact","isAlbum","messageOrAlbum","groupMessages","firstUnreadId","currentAlbum","currentSenderGroup","currentDateGroup","originalDate","datetime","getDayStart","senderGroups","dateGroups","isInAlbum","mainMessage","albumId","nextMessage","nextMessageDatetime","isActionMessage","forwardInfo","senderUserId","hiddenUserName","inlineButtons","useStickyDates","isScrolled","markIsScrolled","runDebounced","updateStickyDates","container","hasTools","contains","fastRaf","currentStuck","stuckDateEl","allElements","querySelectorAll","containerTop","scrollTop","el","offsetTop","offsetHeight","top","findStuckDate","isFabFrozen","MessageScroll","containerHeight","listItemElementsRef","focusingId","anchorIdRef","anchorTopRef","loadMoreForwards","loadMoreBackwards","isViewportNewest","onFabToggle","children","backwardsTriggerRef","forwardsTriggerRef","fabTriggerRef","updateFabVisibility","scrollHeight","scrollBottom","observe","observeIntersection","freeze","freezeForLoadMore","unfreeze","unfreezeForLoadMore","useIntersectionObserver","rootRef","margin","MESSAGE_LIST_SENSITIVE_AREA","entries","triggerEntry","isIntersecting","target","resetScroll","dataset","useOnIntersect","observeIntersectionForFab","freezeForFab","unfreezeForFab","preservedItemElements","element","teactFastList","data-is-active","isEmojiOnlyMessage","customShape","getMinMediaWidth","hasText","calculateMediaDimensions","isOwn","isOwnMessage","isForwarded","isForwardedMessage","getMessagePhoto","getMessageWebPagePhoto","getMessageVideo","isWebPagePhoto","calculateInlineImageDimensions","calculateVideoDimensions","minMediaWidth","getMessageText","stretchFactor","finalWidth","finalHeight","isSmall","AlbumRectPart","accumulate","list","initValue","accumulator","item","clamp","num","low","high","calculateContainerSize","layout","styles","dimensions","sides","calculateAlbumLayout","album","ratios","proportions","ratio","getProportions","averageRatio","getAverageRatio","albumCount","forceCalc","maxWidth","REM","getMaxWidth","minWidth","maxHeight","spacing","originalRatios","cropRatios","attempts","pushAttempt","lineCounts","heights","currentCount","attemptCount","sum","multiHeight","first","second","third","fourth","optimalAttempt","optimalDiff","lineCount","totalHeight","bad1","bad2","line","diff","abs","optimalCounts","optimalHeights","rowCount","row","colCount","lineHeight","col","layoutWithComplexLayouter","layoutTwoTopBottom","layoutTwoLeftRightEqual","minimalWidth","secondWidth","firstWidth","layoutTwoLeftRight","layoutTwo","firstHeight","thirdHeight","secondHeight","rightWidth","leftWidth","layoutThreeLeftAndOther","layoutThreeTopAndOther","layoutThree","w","h0","h","w0","w2","w1","h1","layoutFourTopAndOther","h2","layoutFourLeftAndOther","layoutFour","containerStyle","calculateAuthorWidth","createElement","font","whiteSpace","position","left","opacity","appendChild","offsetWidth","useFocusMessage","elementRef","isFocused","focusDirection","noFocusHighlight","messagesContainer","closest","fastSmoothScroll","ContextMenuContainerAsync","ContextMenuContainer","targetUserId","targetChatId","targetMessageId","targetMessage","selectIsMessageFocused","focusedMessage","isEmbedded","appearanceOrder","noAppearanceAnimation","markShown","renderActionMessageText","asPlain","isContextMenuOpen","contextMenuPosition","handleBeforeContextMenu","handleContextMenu","handleContextMenuClose","handleContextMenuHide","useContextMenuHandlers","isContextMenuShown","data-message-id","onMouseDown","onContextMenu","EmbeddedMessage","customText","useIsIntersecting","pictogramId","senderTitle","MessageMeta","outgoingStatus","signature","views","isEdited","formatTime","MessageOutgoingStatus","Sticker","observeIntersectionForPlaying","shouldLoop","isModalOpen","openModal","closeModal","isAnimated","isMemojiSticker","MEMOJI_STICKER_ID","shouldLoad","shouldPlay","mediaHash","getMessageMediaFormat","isMediaLoaded","isAnimationLoaded","markAnimationLoaded","isMediaReady","shouldRenderFullMedia","useTransitionForMedia","getStickerDimensions","thumbClassName","stickerClassName","AnimatedSticker","animationData","play","noLoop","onLoad","fromSticker","useBlurredMediaThumb","fullMediaData","useBlur","LAYERS_TRANSITION_DURATION","inSelectMode","isSelected","img","Image","onload","canvas","ctx","getContext","drawImage","getImageData","getAppendixColorFromImage","Photo","shouldAutoLoad","isInSelectMode","uploadProgress","shouldAffectAppendix","onCancelUpload","localBlobUrl","isDownloadAllowed","setIsDownloadAllowed","shouldDownload","downloadProgress","useMediaWithDownloadProgress","isUploading","isTransferring","transferProgress","getMediaTransferState","wasDownloadDisabled","shouldRenderSpinner","spinnerClassNames","shouldRenderThumb","isAllowed","contentEl","getCustomAppendixBg","appendixBg","setProperty","setAttribute","ProgressSpinner","useHeavyAnimationCheckForVideo","playerRef","shouldPlayRef","safePlay","useHeavyAnimationCheck","Video","shouldAutoPlay","videoRef","canPlayInline","canMessagePlayVideoInline","isPlayAllowed","setIsPlayAllowed","previewMediaData","isInline","isBuffered","bufferingHandlers","useBuffering","playProgress","setPlayProgress","handleTimeUpdate","currentTime","useVideoCleanup","videoClassName","videoStyle","shouldRenderInlineVideo","shouldRenderHqPreview","shouldRenderPlayButton","shouldRenderDownloadButton","autoPlay","muted","loop","playsInline","onTimeUpdate","isGif","formatMediaDuration","contact","openUserInfo","Avatar","formatPhoneNumberWithCode","selected","loadingOptions","setValues","newValues","Checkbox","subLabel","getPercentage","toFixed","PollOption","answer","voteResults","maxVotersCount","correctResults","shouldAnimate","r","correctAnswer","showIcon","answerPercent","finalPercent","setFinalPercent","lineRef","lineWidth","isAnimationDoesNotStart","lineEl","svgEl","lineStyle","onSendVote","openPollResults","summary","isSubmitting","setIsSubmitting","chosenOptions","setChosenOptions","isSolutionShown","setIsSolutionShown","wasSubmitted","setWasSubmitted","closePeriod","setClosePeriod","closed","closeDate","floor","countdownRef","hasVoted","canVote","canViewResult","isPublic","isMultiple","multipleChoice","answers","isCorrect","hidden","quiz","countdownEl","circumference","PI","lastElementChild","timerEl","strokeDashOffset","textContent","timer","recentVoters","handleRadioChange","handleCheckboxChange","handleVoteClick","handleViewResultsClick","handleSolutionShow","handleSolutionHide","solution","Notification","renderTextWithEntities","solutionEntities","onDismiss","question","getPollTypeString","RadioGroup","loadingOption","isQuiz","getReadableVotersCount","isText","inPreview","onMediaClick","onCancelMediaTransfer","webPage","getMessageWebPage","isSquarePhoto","handleMediaClick","hasDocument","siteName","displayUrl","truncatedDescription","trimText","data-initial","SafeLink","getMessageInvoice","photoUrl","withSelectControl","WrapedComponent","ownProps","selectIsMessageSelected","handleMessageSelect","shiftKey","newProps","PhotoWithSelect","VideoWithSelect","uploadsById","hasCustomAppendix","albumLayout","cancelSendingMessage","mediaCount","handleCancelUpload","containerWidth","fileUpload","currentOnRelease","RoundVideo","playingProgressRef","shouldSpinnerRender","isActivated","setIsActivated","setProgress","playerEl","playingProgressEl","toString","stopPlaying","capturePlaying","onRelease","paused","ROUND_VIDEO_DIMENSIONS","poster","onEnded","InlineButtons","recentReplierIds","recentRepliers","hasUnread","data-cnt","formatInteger","renderLabel","handleDocumentGroupMouseEnter","lastGroupElement","getLastElementInDocumentGroup","handleDocumentGroupMouseLeave","removeAttribute","nextElementSibling","withSenderName","withAvatar","viaBotId","forceSenderName","isAnonymousOwnMessage","originSender","botSender","threadTopMessageId","isThreadTop","shouldHideReply","replyMessageSender","selectUploadProgress","isForwarding","highlight","singleEmoji","getMessageSingleEmoji","every","selectOutgoingStatus","isSingleEmoji","animatedEmoji","selectAnimatedEmoji","isGroupSelected","selectIsDocumentGroupSelected","isPinnedList","shouldAutoLoadMedia","selectShouldAutoLoadMedia","shouldAutoPlayMedia","selectShouldAutoPlayMedia","shouldLoopStickers","selectShouldLoopStickers","observeIntersectionForBottom","observeIntersectionForMedia","observeIntersectionForAnimatedStickers","noComments","isFirstInGroup","isLastInGroup","isFirstInDocumentGroup","isLastInDocumentGroup","isLastInList","openMediaViewer","openAudioPlayer","markMessagesRead","sendPollVote","clickInlineButton","bottomMarkerRef","appendixRef","hasReply","isReplyMessage","hasThread","asForwarded","isLinkedChannelPost","isInDocumentGroup","voice","getMessageCustomShape","textParts","renderMessageText","containerClassName","contentClassName","hasComments","classNames","isMediaWithNoText","isViaBot","isRound","buildContentClassName","avatarPeer","senderPeer","adminTitle","handleGroupDocumentMessagesSelect","handleContainerDoubleClick","handleContentDoubleClick","handleAvatarClick","handleSenderClick","handleViaBotClick","handleReplyClick","MediaViewerOrigin","ScheduledInline","Inline","handleAudioPlay","handleAlbumMediaClick","albumMessageId","ScheduledAlbum","Album","handleReadMedia","handleVoteSend","handleGroupForward","handleForward","handleFocus","handleFocusForwarded","fromMessageId","calculatedWidth","extraPadding","metaSafeAuthorWidth","canShowActionButton","canForward","canFocus","isChannelPost","showCommentsButton","onDoubleClick","data-last-message-id","data-has-unread-mention","isAvatarPeerUser","avatarUser","avatarChat","hiddenName","renderAvatar","senderColor","getUserColorKey","renderSenderName","AnimatedEmoji","Audio","isSelectable","onPlay","onReadMedia","Document","renderContent","INTERSECTION_THROTTLE_FOR_MEDIA","IS_ANDROID","INTERSECTION_MARGIN_FOR_MEDIA","runDebouncedForScroll","runThrottledOnTickEnd","throttleWithTickEnd","selectCurrentMessageIds","restrictionReason","withLastMessageWhenPreloading","botDescription","chatBot","selectChatBot","isChatLoaded","isChannelChat","getCanPostInChat","selectFirstUnreadId","threadFirstMessageId","selectFirstMessageId","hasLinkedChat","bottomOffset","markMessageListRead","setScrollOffset","scrollOffsetRef","selectScrollOffset","memoUnreadDividerBeforeIdRef","memoFirstUnreadIdRef","memoFocusingIdRef","isScrollTopJustUpdatedRef","shouldAnimateAppearanceRef","setContainerHeight","hasFocusing","setHasFocusing","onTickEnd","freezeForMedia","unfreezeForMedia","throttleMs","observeIntersectionForReading","freezeForReading","unfreezeForReading","mentionIds","entry","messageGroups","listedMessages","orderBy","loadMoreAround","handleScroll","parentElement","observer","ResizeObserver","offsetParent","contentRect","disconnect","IS_IOS","webkitOverflowScrolling","clientHeight","useLayoutEffectWithPrevDeps","prevMessageIds","prevIsViewportNewest","prevContainerHeight","shouldForceScroll","lastItemElement","lastItemHeight","isAtBottom","newScrollTop","hasFirstMessageChanged","hasLastMessageChanged","isResized","unreadDivider","dispatchHeavyAnimationEvent","ANIMATION_END_DELAY","isPrivate","withUsers","onScroll","currentAnchorIdRef","isSchedule","messageCountToAnimate","messageGroup","flatten","appearanceIndex","dateGroup","dateGroupIndex","dateGroupsArray","senderGroup","senderGroupIndex","senderGroupsArray","compact","currentDocumentGroupId","messageIndex","isMessageAlbum","documentGroupId","nextDocumentGroupId","shouldRenderUnreadDivider","originalId","getMessageOriginalId","SCHEDULED_WHEN_ONLINE","formatHumanDate","renderMessages","focusLastMessage","messsageElements","lastMessageElement","buildAttachment","filename","blob","isQuick","quick","startsWith","preloadImage","newBlob","toBlob","squeezeImage","revokeObjectURL","videoWidth","videoHeight","preloadVideo","createPosterForVideo","POLYFILL_OPTIONS","encoderPath","reuseWorker","BLOB_PARAMS","opusRecorderPromise","OpusRecorder","mediaRecorder","init","default","start","analyzerCallback","startMediaRecorder","startedAt","pausedAt","chunks","waveform","ondataavailable","typedArray","releaseAnalyzer","recorder","source","sourceNode","analyser","context","createAnalyser","fftSize","connect","dataLength","frequencyBinCount","dataArray","Uint8Array","isDestroyed","tick","getByteFrequencyData","volume","subscribeToAnalyzer","stop","reject","onstop","Blob","onerror","delayStop","CLIPBOARD_ACCEPTED_TYPES","getMessageTextAsHtml","formattedText","currentThreadId","DeleteMessageModalAsync","DeleteMessageModal","openTimeout","isFirstTimeActivation","onActivate","buttonProps","AttachMenuAsync","AttachMenu","SymbolMenuAsync","SymbolMenu","MentionMenuAsync","MentionMenu","CustomSendMenuAsync","CustomSend","EmojiTooltipAsync","EmojiTooltip","BotKeyboardMenuAsync","BotKeyboardMenu","forwardMessageIds","replyingToId","forwardedMessagesCount","exitForwardMode","canAnimate","useAsyncRendering","clearEmbedded","handleMessageClick","AttachmentModalAsync","AttachmentModal","PollModalAsync","PollModal","DropAreaAsync","DropArea","RE_LINK","messageText","toggleMessageWebPage","parseMessageInput","linkEntity","ApiMessageEntityTypes","TextUrl","textMatch","webPageWithoutPhoto","messageStub","CalendarModalAsync","CalendarModal","PaymentModalAsync","PaymentModal","ReceiptModalAsync","MainButtonState","ReceiptModal","chatUser","selectChatUser","messageWithActualBotKeyboard","selectNewestMessageWithBotKeyboardButtons","editingMessage","canScheduleUntilOnline","wasOnline","withScheduledButton","shouldSchedule","botKeyboardMessageId","canSuggestMembers","isChatGroup","stickersForEmoji","groupChatMembers","isReceiptModalOpen","shouldSuggestStickers","dropAreaState","onDropHide","editMessage","saveDraft","clearDraft","setStickerSearchQuery","setGifSearchQuery","closePollModal","closePaymentModal","clearReceipt","html","setHtml","lastMessageSendTimeSeconds","prevDropAreaState","isCalendarOpen","openCalendar","closeCalendar","scheduledMessageArgs","setScheduledMessageArgs","htmlRef","setAttachments","isBotKeyboardOpen","openBotKeyboard","closeBotKeyboard","isAttachMenuOpen","openAttachMenu","closeAttachMenu","isSymbolMenuOpen","openSymbolMenu","closeSymbolMenu","isDeleteModalOpen","openDeleteModal","closeDeleteModal","isSymbolMenuLoaded","onSymbolMenuLoadingComplete","isHoverDisabled","disableHover","enableHover","startRecordingVoice","stopRecordingVoice","pauseRecordingVoice","activeVoiceRecording","currentRecordTime","recordButtonRef","mainButtonRef","startRecordTimeRef","setActiveVoiceRecording","setCurrentRecordTime","voiceRecording","tickVolume","boxShadow","useVoiceRecording","mainButtonState","Edit","IS_VOICE_RECORDING_SUPPORTED","Send","Record","canShowCustomSendMenu","isMentionMenuOpen","mentionFilter","closeMentionMenu","insertMention","mentionFilteredMembers","useMentionMenu","isCustomSendMenuOpen","allowedAttachmentOptions","getAllowedAttachmentOptions","isChatAdmin","slowMode","getChatSlowModeOptions","isEmojiTooltipOpen","closeEmojiTooltip","clearStickersForEmoji","IS_EMOJI_SUPPORTED","parseEmojiOnlyString","hasStickers","useEmojiTooltip","canSendStickers","insertTextAndUpdateCursor","selection","getSelection","newHtml","replace","rangeCount","selectionRange","getRangeAt","isSelectionInsideInput","execCommand","range","deleteContents","fragment","createContextualFragment","lastInsertedNode","lastChild","insertNode","setStartAfter","setEndAfter","removeAllRanges","addRange","insertHtmlInSelection","dispatchEvent","Event","bubbles","focusEditableElement","removeSymbol","tempInput","contentEditable","textLength","createRange","setStart","setEnd","removeChild","deleteLastCharacterOutsideSelection","resetComposer","prevChatId","handleEditComplete","editedMessage","hasMessageMedia","useEditing","updateDraft","draftChatId","draftThreadId","runDebouncedForSaveDraft","DRAFT_DEBOUNCE","prevThreadId","prevHtml","handleBlur","useDraft","handlePaste","clipboardData","input","activeElement","tagName","EDITABLE_INPUT_MODAL_ID","items","media","getAsFile","pastedText","getData","substring","preventDefault","useClipboardPaste","handleFileSelect","files","handleClearAttachment","handleSend","currentAttachments","record","extraLength","textParams","nowSeconds","secondsSinceLastMessage","nextSendDateNotReached","nextSendDate","seconds","secondsRemaining","isSlowMode","handleStickerSelect","handleGifSelect","gif","handlePollSend","handleSilentSend","handleMessageSchedule","restArgs","getTime","handleMessageScheduleUntilOnline","handleCloseCalendar","handleSearchOpen","handleSymbolMenuOpen","handleAllScheduledClick","mainButtonHandler","areVoiceMessagesNotAllowed","canAttachMedia","prevEditedMessage","renderedEditedMessage","scheduledDefaultDate","setSeconds","setMilliseconds","scheduledMaxDate","setFullYear","getFullYear","sendButtonAriaLabel","symbolMenuButtonClassName","Portal","containerId","DropAreaState","None","withQuick","QuickFile","onHide","onFileSelect","caption","onCaptionUpdate","onSend","onClear","onInsertUserName","filteredChatMembers","canAttachEmbedLinks","faded","MessageInput","innerWidth","shouldSetFocus","shouldSupressFocus","onUpdate","onSupressedFocus","formatVoiceRecordDuration","onStickerSelect","onPollCreate","onEmojiSelect","onGifSelect","onRemoveSymbol","onSearchOpen","onSilentSend","onScheduleSend","withTimePicker","selectedAt","maxAt","getDayStartAt","isFutureMode","secondButtonLabel","onSubmit","onSecondButtonClick","MobileSearchAsync","MobileSearch","MessageSelectToolbarAsync","MessageSelectToolbar","UnpinAllMessagesModalAsync","UnpinAllMessagesModal","CLOSE_ANIMATION_DURATION","canBeQuicklyUploaded","kind","CONTENT_TYPES_FOR_QUICK_UPLOAD","isBackgroundBlurred","isCustomBackgroundColor","isBotNotStarted","isPinnedMessageList","messageSendingRestrictionReason","getMessageSendingRestrictionReason","hasPinnedOrAudioMessage","isMobileSearchActive","loadUser","setDropAreaState","isFabShown","setIsFabShown","isUnpinModalOpen","setIsUnpinModalOpen","renderingChatId","renderingThreadId","renderingMessageListType","renderingCanPost","handleDragEnter","dataTransfer","shouldDrawQuick","handleHideDropArea","handleOpenUnpinModal","closeUnpinModal","handleUnpinAllMessages","customBackgroundValue","settingValue","setValue","cacheApi","CUSTOM_BG_CACHE_NAME","useCustomBackground","MASK_IMAGE_ENABLED","messagingDisabledClassName","onDragEnter","ANIMATION_LEVEL_MAX","shouldCleanup","onUnpin","runDebouncedForSearch","HeaderContent","isProfile","isManagement","messageSearchQuery","stickerSearchQuery","selectCurrentStickerSearch","gifSearchQuery","selectCurrentGifSearch","canManage","isCreator","isColumnOpen","isSearch","isStatistics","isStickerSearch","isGifSearch","isPollResults","profileState","managementScreen","setLocalTextSearchQuery","searchTextMessagesLocal","toggleManagement","backButtonRef","handleMessageSearchQueryChange","handleJumpToDate","valueOf","handleStickerSearchQueryChange","handleGifSearchQueryChange","shouldSkipTransition","setShouldSkipTransition","contentKey","ProfileState","Profile","SharedMedia","MemberList","Search","PollResults","StickerSearch","GifSearch","ManagementScreens","Initial","ManageInitial","ChatPrivacyType","ManageChatPrivacyType","Discussion","ManageDiscussion","ChannelSubscribers","ManageChannelSubscribers","GroupPermissions","ManageGroupPermissions","ChatAdministrators","ManageChatAdministrators","GroupRemovedUsers","ManageGroupRemovedUsers","GroupUserPermissionsCreate","ManageGroupUserPermissionsCreate","GroupUserPermissions","ManageGroupUserPermissions","GroupRecentActions","ManageGroupRecentActions","ChatAdminRights","ManageGroupAdminRights","GroupMembers","ManageGroupMembers","Statistics","renderingContentKey","renderHeaderContent","isBackButton","buttonClassName","isPastMode","submitButtonLabel","useInfiniteScrollForSharedMedia","forSharedMediaType","currentResultType","handleLoadMore","messageIdsRef","getMessageContentIds","reverse","getMore","useInfiniteScroll","runThrottledForScroll","isScrollingProgrammatically","forceShowSelf","loadFullUser","formattedNumber","canInviteUsers","isUserRightBanned","getHasAdminRight","getChatDescription","getChatLink","TABS","buildInfiniteScrollItemSelector","resultType","mediaSearchType","isGroup","hasMembersTab","areMembersHidden","canViewMembers","resolvedUserId","onProfileStateChange","setLocalMediaSearchType","searchMediaMessagesLocal","tabType","noProfileInfo","searchMessages","getSortedUserIds","mediaViewportIds","getMoreMedia","noProfileInfoForMedia","documentViewportIds","getMoreDocuments","noProfileInfoForDocuments","linkViewportIds","getMoreLinks","noProfileInfoForLinks","audioViewportIds","getMoreAudio","noProfileInfoForAudio","useProfileViewportIds","useEffectWithPrevDeps","prevTabType","tabsEl","prevProfileState","tabListEl","determineProfileState","useProfileState","applyTransitionFix","releaseTransitionFix","setMinHeight","transitionEl","minHeight","overflowY","scrollBarWidth","clientWidth","marginRight","useTransitionFixes","cacheBuster","resetCacheBuster","setCacheBuster","useCacheBuster","handleTransitionStop","profileId","handleSelectMedia","handlePlayAudio","handleMemberClick","handleMessageFocus","renderingDelay","isFirstTab","SLIDE_TRANSITION_DURATION","canRenderContents","renderSharedMedia","noSpinner","NothingFound","Media","withDate","smaller","onDateClick","WebLink","onMessageClick","renderingFor","ListItem","teactOrderKey","InfiniteScroll","itemSelector","preloadBackwards","isDisabled","noFastList","onLoadMore","avatarSize","renderProfileInfo","shouldRestoreHeight","onStart","onStop","RightSearchAsync","RightSearch","ManagementAsync","Management","StatisticsAsync","StickerSearchAsync","GifSearchAsync","PollResultsAsync","MAIN_SCREENS_COUNT","RightColumnContent","MANAGEMENT_SCREENS_COUNT","blurSearchInput","areActiveChatsLoaded","selectAreActiveChatsLoaded","selectRightColumnContentKey","currentProfileUserId","selectedId","isChatSelected","toggleChatInfo","toggleStatistics","closeLocalTextSearch","closePollResults","setProfileState","setManagementScreen","selectedChatMemberId","setSelectedChatMemberId","isPromotedByCurrentUser","setIsPromotedByCurrentUser","isScrolledDown","ChatInfo","UserInfo","isOverlaying","close","GroupType","handleSelectChatMember","memberId","isPromoted","onChatMemberSelect","prevContentKey","MediaViewer","NotificationsAsync","ErrorsAsync","Errors","ForwardPickerAsync","ForwardPicker","rightColumnAnimationTimeout","notificationInterval","DEBUG_isLogged","updateIcon","asUnread","isMediaViewerOpen","selectIsMediaViewerOpen","isForwardModalOpen","selectIsForwardModalOpen","hasNotifications","hasErrors","middleColumnTransitionClassNames","rightColumnTransitionClassNames","stopEvent","useBackgroundMode","initialUnread","selectCountNotMutedUnread","newUnread","onDrop","onDragOver","init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AW,GAGbjvE,KAvFwB,MAyFzB,KACDzV,cAAcwkF,IACdA,QAAuBnlF,EACvBonB,SAAS1X,MA9FI,WA+Fb21E,IAAW,KASX,yBAAK7jF,GAAG,OAAO4yB,UAAWA,EAAWgyD,OAAQL,EAAWM,WAAYN,GAClE,kBAAC,GAAD,MACA,kBAAC,GAAD,MACA,kBAAC,GAAD,MACA,kBAAC,GAAD,CAAa1vD,OAAQkvD,IACrB,kBAAC,GAAD,CAAelvD,OAAQovD,IACvB,kBAAC,GAAD,CAAepvD,OAAQsvD,IACvB,kBAAC,GAAD,CAAQtvD,OAAQuvD,IACfz3C,GAAgB,kBAAC,GAAD,CAAa5a,IAAK4a,EAAa3sC,GAAIyI,QAASkkC,EAAcnB,MAAI,QCxJjFrrB,KAEFC,QAAQC,IAAI,+BAGTvd,cAAYg1B,iBACf13B,cAAc0kF","file":"3.4bcadbdcb5986d5c9ba9.js","sourcesContent":["// https://jsperf.com/finding-maximum-element-in-an-array\nexport function getMaxMin(array) {\n const length = array.length;\n let max = array[0];\n let min = array[0];\n\n for (let i = 0; i < length; i++) {\n const value = array[i];\n\n if (value > max) {\n max = value;\n } else if (value < min) {\n min = value;\n }\n }\n\n return { max, min };\n}\n\n// https://jsperf.com/multi-array-concat/24\nexport function mergeArrays(arrays) {\n return [].concat.apply([], arrays);\n}\n\nexport function sumArrays(arrays) {\n const sums = [];\n const n = arrays.length;\n\n for (let i = 0, l = arrays[0].length; i < l; i++) {\n sums[i] = 0;\n\n for (let j = 0; j < n; j++) {\n sums[i] += arrays[j][i];\n }\n }\n\n return sums;\n}\n\nexport function proxyMerge(obj1, obj2) {\n return new Proxy({}, {\n get: (obj, prop) => {\n if (obj[prop] !== undefined) {\n return obj[prop];\n } else if (obj2[prop] !== undefined) {\n return obj2[prop];\n } else {\n return obj1[prop];\n }\n },\n });\n}\n\nexport function throttle(\n fn,\n ms,\n shouldRunFirst = true,\n) {\n let interval = null;\n let isPending;\n let args;\n\n return (..._args) => {\n isPending = true;\n args = _args;\n\n if (!interval) {\n if (shouldRunFirst) {\n isPending = false;\n // @ts-ignore\n fn(...args);\n }\n\n interval = window.setInterval(() => {\n if (!isPending) {\n window.clearInterval(interval);\n interval = null;\n return;\n }\n\n isPending = false;\n // @ts-ignore\n fn(...args);\n }, ms);\n }\n };\n}\n\nexport function throttleWithRaf(fn) {\n let waiting = false;\n let args;\n\n return function (..._args) {\n args = _args;\n\n if (!waiting) {\n waiting = true;\n\n requestAnimationFrame(() => {\n waiting = false;\n fn(...args);\n });\n }\n };\n}\n\nexport function debounce(fn, ms, shouldRunFirst = true, shouldRunLast = true) {\n let waitingTimeout = null;\n\n return function () {\n if (waitingTimeout) {\n clearTimeout(waitingTimeout);\n waitingTimeout = null;\n } else if (shouldRunFirst) {\n fn();\n }\n\n waitingTimeout = setTimeout(() => {\n if (shouldRunLast) {\n fn();\n }\n\n waitingTimeout = null;\n }, ms);\n };\n}\n","import { addReducer, getDispatch, setGlobal } from '../../../lib/teact/teactn';\nimport {\n exitMessageSelectMode,\n updateCurrentMessageList,\n} from '../../reducers';\nimport { selectCurrentMessageList } from '../../selectors';\n\nwindow.addEventListener('popstate', (e) => {\n if (!e.state) {\n return;\n }\n\n const { chatId: id, threadId, messageListType: type } = e.state;\n\n getDispatch().openChat({\n id, threadId, type, noPushState: true,\n });\n});\n\naddReducer('openChat', (global, actions, payload) => {\n const {\n id, threadId = -1, type = 'thread', noPushState,\n } = payload!;\n\n const currentMessageList = selectCurrentMessageList(global);\n\n if (!currentMessageList\n || (\n currentMessageList.chatId !== id\n || currentMessageList.threadId !== threadId\n || currentMessageList.type !== type\n )) {\n global = exitMessageSelectMode(global);\n\n global = {\n ...global,\n messages: {\n ...global.messages,\n contentToBeScheduled: undefined,\n },\n ...(id !== global.forwardMessages.toChatId && {\n forwardMessages: {},\n }),\n };\n\n setGlobal(global);\n\n if (!noPushState) {\n window.history.pushState({ chatId: id, threadId, messageListType: type }, '');\n }\n }\n\n return updateCurrentMessageList(global, id, threadId, type);\n});\n\naddReducer('openChatWithInfo', (global, actions, payload) => {\n setGlobal({\n ...global,\n isChatInfoShown: true,\n });\n\n actions.openChat(payload);\n});\n\naddReducer('resetChatCreation', (global) => {\n return {\n ...global,\n chatCreation: undefined,\n };\n});\n","import { addReducer, getGlobal, setGlobal } from '../../../lib/teact/teactn';\n\nimport { MAIN_THREAD_ID } from '../../../api/types';\nimport { FocusDirection } from '../../../types';\n\nimport {\n enterMessageSelectMode,\n toggleMessageSelection,\n exitMessageSelectMode,\n replaceThreadParam,\n updateFocusDirection,\n updateFocusedMessage,\n} from '../../reducers';\nimport {\n selectCurrentChat,\n selectViewportIds,\n selectIsRightColumnShown,\n selectCurrentMessageList,\n selectChat,\n selectThreadInfo,\n selectChatMessages,\n selectAllowedMessageActions,\n selectMessageIdsByGroupId,\n selectForwardedMessageIdsByGroupId,\n} from '../../selectors';\nimport { findLast } from '../../../util/iteratees';\n\nconst FOCUS_DURATION = 2000;\nconst POLL_RESULT_OPEN_DELAY_MS = 450;\n\nlet blurTimeout: number | undefined;\n\naddReducer('setScrollOffset', (global, actions, payload) => {\n const { chatId, threadId, scrollOffset } = payload!;\n\n return replaceThreadParam(global, chatId, threadId, 'scrollOffset', scrollOffset);\n});\n\naddReducer('setReplyingToId', (global, actions, payload) => {\n const { messageId } = payload!;\n const currentMessageList = selectCurrentMessageList(global);\n if (!currentMessageList) {\n return undefined;\n }\n const { chatId, threadId } = currentMessageList;\n\n return replaceThreadParam(global, chatId, threadId, 'replyingToId', messageId);\n});\n\naddReducer('setEditingId', (global, actions, payload) => {\n const { messageId } = payload!;\n const currentMessageList = selectCurrentMessageList(global);\n if (!currentMessageList) {\n return undefined;\n }\n\n const { chatId, threadId, type } = currentMessageList;\n const paramName = type === 'scheduled' ? 'editingScheduledId' : 'editingId';\n\n return replaceThreadParam(global, chatId, threadId, paramName, messageId);\n});\n\naddReducer('editLastMessage', (global) => {\n const { chatId, threadId } = selectCurrentMessageList(global) || {};\n if (!chatId || !threadId) {\n return undefined;\n }\n\n const chatMessages = selectChatMessages(global, chatId);\n const viewportIds = selectViewportIds(global, chatId, threadId);\n if (!chatMessages || !viewportIds) {\n return undefined;\n }\n\n const lastOwnEditableMessageId = findLast(viewportIds, (id) => {\n return Boolean(chatMessages[id] && selectAllowedMessageActions(global, chatMessages[id], threadId).canEdit);\n });\n\n if (!lastOwnEditableMessageId) {\n return undefined;\n }\n\n return replaceThreadParam(global, chatId, threadId, 'editingId', lastOwnEditableMessageId);\n});\n\naddReducer('openMediaViewer', (global, actions, payload) => {\n const {\n chatId, threadId, messageId, avatarOwnerId, origin,\n } = payload!;\n\n return {\n ...global,\n mediaViewer: {\n chatId,\n threadId,\n messageId,\n avatarOwnerId,\n origin,\n },\n forwardMessages: {},\n };\n});\n\naddReducer('closeMediaViewer', (global) => {\n return {\n ...global,\n mediaViewer: {},\n };\n});\n\naddReducer('openAudioPlayer', (global, actions, payload) => {\n const {\n chatId, threadId, messageId,\n } = payload!;\n\n return {\n ...global,\n audioPlayer: {\n chatId,\n threadId,\n messageId,\n },\n };\n});\n\naddReducer('closeAudioPlayer', (global) => {\n return {\n ...global,\n audioPlayer: {},\n };\n});\n\naddReducer('openPollResults', (global, actions, payload) => {\n const { chatId, messageId } = payload!;\n\n const shouldOpenInstantly = selectIsRightColumnShown(global);\n\n if (!shouldOpenInstantly) {\n window.setTimeout(() => {\n const newGlobal = getGlobal();\n\n setGlobal({\n ...newGlobal,\n pollResults: {\n chatId,\n messageId,\n voters: {},\n },\n });\n }, POLL_RESULT_OPEN_DELAY_MS);\n } else if (chatId !== global.pollResults.chatId || messageId !== global.pollResults.messageId) {\n setGlobal({\n ...global,\n pollResults: {\n chatId,\n messageId,\n voters: {},\n },\n });\n }\n});\n\naddReducer('closePollResults', (global) => {\n setGlobal({\n ...global,\n pollResults: {},\n });\n});\n\naddReducer('focusLastMessage', (global, actions) => {\n const currentMessageList = selectCurrentMessageList(global);\n if (!currentMessageList) {\n return;\n }\n\n const { chatId, threadId } = currentMessageList;\n\n let lastMessageId: number | undefined;\n if (threadId === MAIN_THREAD_ID) {\n const chat = selectChat(global, chatId);\n\n lastMessageId = chat && chat.lastMessage ? chat.lastMessage.id : undefined;\n } else {\n const threadInfo = selectThreadInfo(global, chatId, threadId);\n\n lastMessageId = threadInfo ? threadInfo.lastMessageId : undefined;\n }\n\n if (!lastMessageId) {\n return;\n }\n\n actions.focusMessage({\n chatId, threadId, messageId: lastMessageId, noHighlight: true,\n });\n});\n\naddReducer('focusMessage', (global, actions, payload) => {\n const {\n chatId, threadId = MAIN_THREAD_ID, messageListType = 'thread', noHighlight, groupedId, groupedChatId,\n } = payload!;\n\n let { messageId } = payload!;\n\n if (groupedId !== undefined) {\n const ids = selectForwardedMessageIdsByGroupId(global, groupedChatId, groupedId);\n if (ids && ids.length) {\n ([messageId] = ids);\n }\n }\n\n const currentMessageList = selectCurrentMessageList(global);\n const shouldSwitchChat = !currentMessageList || (\n chatId !== currentMessageList.chatId\n || threadId !== currentMessageList.threadId\n || messageListType !== currentMessageList.type\n );\n\n if (blurTimeout) {\n clearTimeout(blurTimeout);\n blurTimeout = undefined;\n }\n blurTimeout = window.setTimeout(() => {\n let newGlobal = getGlobal();\n newGlobal = updateFocusedMessage(newGlobal);\n newGlobal = updateFocusDirection(newGlobal);\n setGlobal(newGlobal);\n }, FOCUS_DURATION);\n\n global = updateFocusedMessage(global, chatId, messageId, noHighlight);\n global = updateFocusDirection(global, undefined);\n\n if (shouldSwitchChat) {\n global = updateFocusDirection(global, FocusDirection.Static);\n }\n\n const viewportIds = selectViewportIds(global, chatId, threadId);\n if (viewportIds && viewportIds.includes(messageId)) {\n setGlobal(global);\n actions.openChat({ id: chatId, threadId });\n return undefined;\n }\n\n if (shouldSwitchChat) {\n global = replaceThreadParam(global, chatId, threadId, 'viewportIds', undefined);\n }\n\n global = replaceThreadParam(global, chatId, threadId, 'outlyingIds', undefined);\n\n if (viewportIds && !shouldSwitchChat) {\n const direction = messageId > viewportIds[0] ? FocusDirection.Down : FocusDirection.Up;\n global = updateFocusDirection(global, direction);\n }\n\n setGlobal(global);\n\n actions.openChat({ id: chatId, threadId });\n actions.loadViewportMessages();\n return undefined;\n});\n\naddReducer('openForwardMenu', (global, actions, payload) => {\n const { fromChatId, messageIds, groupedId } = payload!;\n let groupedMessageIds;\n if (groupedId) {\n groupedMessageIds = selectMessageIdsByGroupId(global, fromChatId, groupedId);\n }\n return {\n ...global,\n forwardMessages: {\n fromChatId,\n messageIds: groupedMessageIds || messageIds,\n isModalShown: true,\n },\n };\n});\n\naddReducer('exitForwardMode', (global) => {\n setGlobal({\n ...global,\n forwardMessages: {},\n });\n});\n\naddReducer('setForwardChatId', (global, actions, payload) => {\n const { id } = payload!;\n\n setGlobal({\n ...global,\n forwardMessages: {\n ...global.forwardMessages,\n toChatId: id,\n isModalShown: false,\n },\n });\n\n actions.openChat({ id });\n actions.closeMediaViewer();\n});\n\naddReducer('openForwardMenuForSelectedMessages', (global, actions) => {\n if (!global.selectedMessages) {\n return;\n }\n\n const { chatId: fromChatId, messageIds } = global.selectedMessages;\n\n actions.openForwardMenu({ fromChatId, messageIds });\n});\n\naddReducer('enterMessageSelectMode', (global, actions, payload) => {\n const { messageId } = payload || {};\n const openChat = selectCurrentChat(global);\n if (!openChat) {\n return global;\n }\n\n return enterMessageSelectMode(global, openChat.id, messageId);\n});\n\naddReducer('toggleMessageSelection', (global, actions, payload) => {\n const {\n messageId,\n groupedId,\n childMessageIds,\n withShift,\n } = payload!;\n const currentMessageList = selectCurrentMessageList(global);\n if (!currentMessageList) {\n return undefined;\n }\n\n const { chatId, threadId, type: messageListType } = currentMessageList;\n\n return toggleMessageSelection(\n global, chatId, threadId, messageListType, messageId, groupedId, childMessageIds, withShift,\n );\n});\n\n\naddReducer('exitMessageSelectMode', exitMessageSelectMode);\n\naddReducer('openPollModal', (global) => {\n return {\n ...global,\n isPollModalOpen: true,\n };\n});\n\naddReducer('closePollModal', (global) => {\n return {\n ...global,\n isPollModalOpen: false,\n };\n});\n","import { addReducer } from '../../../lib/teact/teactn';\n\nimport { updateGlobalSearch, updateGlobalSearchContent } from '../../reducers';\n\nconst MAX_RECENTLY_FOUND_IDS = 10;\n\naddReducer('setGlobalSearchQuery', (global, actions, payload) => {\n const { query } = payload!;\n const { chatId } = global.globalSearch;\n\n return updateGlobalSearch(global, {\n globalResults: {},\n localResults: {},\n resultsByType: undefined,\n ...(query ? { fetchingStatus: { chats: !chatId, messages: true } } : { fetchingStatus: undefined }),\n query,\n });\n});\n\naddReducer('addRecentlyFoundChatId', (global, actions, payload) => {\n const { id } = payload!;\n const { recentlyFoundChatIds } = global.globalSearch;\n\n if (!recentlyFoundChatIds) {\n return updateGlobalSearch(global, { recentlyFoundChatIds: [id] });\n }\n\n const newRecentIds = recentlyFoundChatIds.filter((chatId) => chatId !== id);\n newRecentIds.unshift(id);\n if (newRecentIds.length > MAX_RECENTLY_FOUND_IDS) {\n newRecentIds.pop();\n }\n\n return updateGlobalSearch(global, { recentlyFoundChatIds: newRecentIds });\n});\n\naddReducer('clearRecentlyFoundChats', (global) => {\n return updateGlobalSearch(global, { recentlyFoundChatIds: undefined });\n});\n\naddReducer('setGlobalSearchContent', (global, actions, payload) => {\n const { content } = payload!;\n\n return updateGlobalSearchContent(global, content);\n});\n\naddReducer('setGlobalSearchChatId', (global, actions, payload) => {\n const { id } = payload!;\n\n return updateGlobalSearch(global, { chatId: id, query: undefined, resultsByType: undefined });\n});\n","import { addReducer } from '../../../lib/teact/teactn';\n\nimport {\n updateLocalTextSearch,\n replaceLocalTextSearchResults,\n updateLocalMediaSearchType,\n} from '../../reducers';\nimport { MEMO_EMPTY_ARRAY } from '../../../util/memo';\nimport { selectCurrentMessageList } from '../../selectors';\nimport { buildChatThreadKey } from '../../helpers';\n\naddReducer('openLocalTextSearch', (global) => {\n const { chatId, threadId } = selectCurrentMessageList(global) || {};\n if (!chatId || !threadId) {\n return undefined;\n }\n\n return updateLocalTextSearch(global, chatId, threadId, true);\n});\n\naddReducer('closeLocalTextSearch', (global) => {\n const { chatId, threadId } = selectCurrentMessageList(global) || {};\n if (!chatId || !threadId) {\n return undefined;\n }\n\n global = updateLocalTextSearch(global, chatId, threadId, false);\n global = replaceLocalTextSearchResults(global, chatId, threadId, undefined);\n return global;\n});\n\naddReducer('setLocalTextSearchQuery', (global, actions, payload) => {\n const { chatId, threadId } = selectCurrentMessageList(global) || {};\n if (!chatId || !threadId) {\n return undefined;\n }\n\n const { query } = payload!;\n const chatThreadKey = buildChatThreadKey(chatId, threadId);\n const { query: currentQuery } = global.localTextSearch.byChatThreadKey[chatThreadKey] || {};\n\n if (query !== currentQuery) {\n global = replaceLocalTextSearchResults(global, chatId, threadId, MEMO_EMPTY_ARRAY);\n }\n\n global = updateLocalTextSearch(global, chatId, threadId, true, query);\n\n return global;\n});\n\naddReducer('setLocalMediaSearchType', (global, actions, payload) => {\n const { chatId } = selectCurrentMessageList(global) || {};\n if (!chatId) {\n return undefined;\n }\n\n const { mediaType } = payload!;\n return updateLocalMediaSearchType(global, chatId, mediaType);\n});\n","import { addReducer } from '../../../lib/teact/teactn';\n\naddReducer('setStickerSearchQuery', (global, actions, payload) => {\n const { query } = payload!;\n\n return {\n ...global,\n stickers: {\n ...global.stickers,\n search: {\n query,\n resultIds: undefined,\n },\n },\n };\n});\n\naddReducer('setGifSearchQuery', (global, actions, payload) => {\n const { query } = payload!;\n\n return {\n ...global,\n gifs: {\n ...global.gifs,\n search: {\n query,\n offsetId: undefined,\n results: undefined,\n },\n },\n };\n});\n","import { addReducer } from '../../../lib/teact/teactn';\n\nimport { GlobalState } from '../../../global/types';\n\nimport { updateSelectedUserId } from '../../reducers';\n\naddReducer('openUserInfo', (global, actions, payload) => {\n const { id } = payload!;\n\n actions.openChat({ id });\n});\n\nconst clearSelectedUserId = (global: GlobalState) => updateSelectedUserId(global, undefined);\n\naddReducer('openChat', clearSelectedUserId);\n","import { addReducer } from '../../../lib/teact/teactn';\nimport { ISettings } from '../../../types';\nimport { replaceSettings } from '../../reducers';\n\naddReducer('setSettingOption', (global, actions, payload?: Partial<ISettings>) => {\n return replaceSettings(global, payload);\n});\n","import { addReducer } from '../../../lib/teact/teactn';\n\nimport { GlobalState } from '../../../global/types';\n\nimport { IS_MOBILE_SCREEN } from '../../../util/environment';\nimport getReadableErrorText from '../../../util/getReadableErrorText';\nimport { selectCurrentMessageList } from '../../selectors';\n\nconst MAX_STORED_EMOJIS = 18; // Represents two rows of recent emojis\n\naddReducer('toggleChatInfo', (global) => {\n return {\n ...global,\n isChatInfoShown: !global.isChatInfoShown,\n };\n});\n\naddReducer('toggleManagement', (global): GlobalState | undefined => {\n const { chatId } = selectCurrentMessageList(global) || {};\n\n if (!chatId) {\n return undefined;\n }\n\n return {\n ...global,\n management: {\n byChatId: {\n ...global.management.byChatId,\n [chatId]: {\n ...global.management.byChatId[chatId],\n isActive: !(global.management.byChatId[chatId] || {}).isActive,\n },\n },\n },\n };\n});\n\naddReducer('closeManagement', (global): GlobalState | undefined => {\n const { chatId } = selectCurrentMessageList(global) || {};\n\n if (!chatId) {\n return undefined;\n }\n\n return {\n ...global,\n management: {\n byChatId: {\n ...global.management.byChatId,\n [chatId]: {\n ...global.management.byChatId[chatId],\n isActive: false,\n },\n },\n },\n };\n});\n\naddReducer('toggleStatistics', (global) => {\n return {\n ...global,\n isStatisticsShown: !global.isStatisticsShown,\n };\n});\n\naddReducer('openChat', (global, actions, payload) => {\n if (!IS_MOBILE_SCREEN) {\n return undefined;\n }\n\n const { id } = payload!;\n\n return {\n ...global,\n isLeftColumnShown: id === undefined,\n };\n});\n\naddReducer('toggleLeftColumn', (global) => {\n return {\n ...global,\n isLeftColumnShown: !global.isLeftColumnShown,\n };\n});\n\naddReducer('addRecentEmoji', (global, action, payload) => {\n const { emoji } = payload!;\n const { recentEmojis } = global;\n if (!recentEmojis) {\n return {\n ...global,\n recentEmojis: [emoji],\n };\n }\n\n const newEmojis = recentEmojis.filter((e) => e !== emoji);\n newEmojis.unshift(emoji);\n if (newEmojis.length > MAX_STORED_EMOJIS) {\n newEmojis.pop();\n }\n\n return {\n ...global,\n recentEmojis: newEmojis,\n };\n});\n\naddReducer('addRecentSticker', (global, action, payload) => {\n const { sticker } = payload!;\n const { recent } = global.stickers;\n if (!recent) {\n return {\n ...global,\n stickers: {\n ...global.stickers,\n recent: {\n hash: 0,\n stickers: [sticker],\n },\n },\n };\n }\n\n const newStickers = recent.stickers.filter((s) => s.id !== sticker.id);\n newStickers.unshift(sticker);\n\n return {\n ...global,\n stickers: {\n ...global.stickers,\n recent: {\n ...recent,\n stickers: newStickers,\n },\n },\n };\n});\n\naddReducer('showNotification', (global, actions, payload) => {\n const notification = payload!;\n\n const newNotifications = [...global.notifications];\n const existingNotificationIndex = newNotifications.findIndex((n) => n.message === notification.message);\n if (existingNotificationIndex !== -1) {\n newNotifications.splice(existingNotificationIndex, 1);\n }\n\n newNotifications.push(notification);\n\n return {\n ...global,\n notifications: newNotifications,\n };\n});\n\naddReducer('dismissNotification', (global) => {\n const newNotifications = [...global.notifications];\n\n newNotifications.pop();\n\n return {\n ...global,\n notifications: newNotifications,\n };\n});\n\naddReducer('showError', (global, actions, payload) => {\n const { error } = payload!;\n\n // Filter out errors that we don't want to show to the user\n if (!getReadableErrorText(error)) {\n return global;\n }\n\n const newErrors = [...global.errors];\n const existingErrorIndex = newErrors.findIndex((err) => err.message === error.message);\n if (existingErrorIndex !== -1) {\n newErrors.splice(existingErrorIndex, 1);\n }\n\n newErrors.push(error);\n\n return {\n ...global,\n errors: newErrors,\n };\n});\n\naddReducer('dismissError', (global) => {\n const newErrors = [...global.errors];\n\n newErrors.pop();\n\n return {\n ...global,\n errors: newErrors,\n };\n});\n","import { addReducer } from '../../../lib/teact/teactn';\nimport {\n clearPayment, closeInvoice,\n} from '../../reducers';\n\naddReducer('openPaymentModal', (global, actions, payload) => {\n const { messageId } = payload;\n return {\n ...global,\n payment: {\n ...global.payment,\n messageId,\n isPaymentModalOpen: true,\n },\n };\n});\n\naddReducer('closePaymentModal', (global) => {\n const newGlobal = clearPayment(global);\n return closeInvoice(newGlobal);\n});\n","import {\n addReducer, getDispatch, getGlobal, setGlobal,\n} from '../../../lib/teact/teactn';\n\nimport {\n ApiChat, ApiUser, ApiChatFolder, MAIN_THREAD_ID,\n} from '../../../api/types';\nimport { ChatCreationProgress, ManagementProgress } from '../../../types';\nimport { GlobalActions } from '../../../global/types';\n\nimport {\n ARCHIVED_FOLDER_ID,\n TOP_CHAT_MESSAGES_PRELOAD_LIMIT,\n CHAT_LIST_LOAD_SLICE,\n RE_TME_INVITE_LINK,\n RE_TME_LINK,\n TIPS_USERNAME,\n} from '../../../config';\nimport { IS_TOUCH_ENV } from '../../../util/environment';\nimport { callApi } from '../../../api/gramjs';\nimport {\n addChats,\n addUsers,\n replaceThreadParam,\n updateChatListIds,\n updateChats,\n updateChat,\n updateChatListSecondaryInfo,\n updateManagementProgress,\n} from '../../reducers';\nimport {\n selectChat,\n selectCurrentChat,\n selectUser,\n selectChatListType,\n selectIsChatPinned,\n selectChatFolder,\n selectSupportChat,\n selectChatByUsername,\n selectThreadTopMessageId,\n selectCurrentMessageList,\n} from '../../selectors';\nimport { buildCollectionByKey } from '../../../util/iteratees';\nimport { debounce, pause, throttle } from '../../../util/schedulers';\nimport {\n isChatSummaryOnly, isChatArchived, prepareChatList, isChatBasicGroup,\n} from '../../helpers';\n\nconst TOP_CHATS_PRELOAD_PAUSE = 200;\n// We expect this ID does not exist\nconst TMP_CHAT_ID = -1;\n\nconst runThrottledForLoadChats = throttle((cb) => cb(), 1000, true);\nconst runThrottledForLoadTopChats = throttle((cb) => cb(), 3000, true);\nconst runDebouncedForFetchFullChat = debounce((cb) => cb(), 500, false, true);\nconst runDebouncedForFetchOnlines = debounce((cb) => cb(), 500, false, true);\n\naddReducer('preloadTopChatMessages', (global, actions) => {\n (async () => {\n const preloadedChatIds: number[] = [];\n\n for (let i = 0; i < TOP_CHAT_MESSAGES_PRELOAD_LIMIT; i++) {\n await pause(TOP_CHATS_PRELOAD_PAUSE);\n\n const {\n byId,\n listIds: { active: listIds },\n orderedPinnedIds: { active: orderedPinnedIds },\n } = getGlobal().chats;\n if (!listIds) {\n return;\n }\n\n const { chatId: currentChatId } = selectCurrentMessageList(global) || {};\n const { pinnedChats, otherChats } = prepareChatList(byId, listIds, orderedPinnedIds);\n const topChats = [...pinnedChats, ...otherChats];\n const chatToPreload = topChats.find(({ id }) => id !== currentChatId && !preloadedChatIds.includes(id));\n if (!chatToPreload) {\n return;\n }\n\n preloadedChatIds.push(chatToPreload.id);\n\n actions.loadViewportMessages({ chatId: chatToPreload.id, threadId: MAIN_THREAD_ID });\n\n if (IS_TOUCH_ENV) {\n actions.loadPinnedMessages({ chatId: chatToPreload.id });\n }\n }\n })();\n});\n\naddReducer('openChat', (global, actions, payload) => {\n const { id, threadId } = payload!;\n const { currentUserId } = global;\n const chat = selectChat(global, id);\n\n if (chat && chat.hasUnreadMark) {\n actions.toggleChatUnread({ id });\n }\n\n if (!chat) {\n if (id === currentUserId) {\n void callApi('fetchChat', { type: 'self' });\n } else {\n const user = selectUser(global, id);\n if (user) {\n void callApi('fetchChat', { type: 'user', user });\n }\n }\n } else if (isChatSummaryOnly(chat) && !chat.isMin) {\n actions.requestChatUpdate({ chatId: id });\n }\n\n if (threadId !== MAIN_THREAD_ID) {\n const topMessageId = selectThreadTopMessageId(global, id, threadId);\n if (!topMessageId) {\n actions.requestThreadInfoUpdate({ chatId: id, threadId });\n }\n }\n});\n\naddReducer('openSupportChat', (global, actions) => {\n const chat = selectSupportChat(global);\n\n actions.openChat({ id: chat ? chat.id : TMP_CHAT_ID });\n\n if (chat) {\n return;\n }\n\n (async () => {\n const result = await callApi('fetchChat', { type: 'support' });\n if (result) {\n actions.openChat({ id: result.chatId });\n }\n })();\n});\n\naddReducer('openTipsChat', (global, actions) => {\n actions.openChatByUsername({ username: TIPS_USERNAME });\n});\n\naddReducer('loadMoreChats', (global, actions, payload) => {\n const { listType = 'active' } = payload!;\n const listIds = global.chats.listIds[listType as ('active' | 'archived')];\n const isFullyLoaded = global.chats.isFullyLoaded[listType as ('active' | 'archived')];\n\n if (isFullyLoaded) {\n return;\n }\n\n const oldestChat = listIds\n ? listIds\n .map((id) => global.chats.byId[id])\n .filter((chat) => Boolean(chat && chat.lastMessage) && !selectIsChatPinned(global, chat.id))\n .sort((chat1, chat2) => (chat1.lastMessage!.date - chat2.lastMessage!.date))[0]\n : undefined;\n\n if (oldestChat) {\n runThrottledForLoadChats(() => loadChats(listType, oldestChat.id, oldestChat.lastMessage!.date));\n } else {\n runThrottledForLoadChats(() => loadChats(listType));\n }\n});\n\naddReducer('loadFullChat', (global, actions, payload) => {\n const { chatId, force } = payload!;\n const chat = selectChat(global, chatId);\n if (!chat) {\n return;\n }\n\n if (force) {\n loadFullChat(chat);\n } else {\n runDebouncedForFetchFullChat(() => loadFullChat(chat));\n }\n});\n\naddReducer('loadSuperGroupOnlines', (global, actions, payload) => {\n const { chatId } = payload!;\n const chat = selectChat(global, chatId);\n if (!chat) {\n return;\n }\n\n runDebouncedForFetchOnlines(() => callApi('fetchSuperGroupOnlines', chat));\n});\n\naddReducer('loadTopChats', () => {\n runThrottledForLoadTopChats(() => loadChats('active'));\n});\n\naddReducer('requestChatUpdate', (global, actions, payload) => {\n const { chatId } = payload!;\n const chat = selectChat(global, chatId);\n if (!chat) {\n return;\n }\n\n void callApi('requestChatUpdate', chat);\n});\n\naddReducer('updateChatMutedState', (global, actions, payload) => {\n const { chatId, isMuted } = payload!;\n const chat = selectChat(global, chatId);\n if (!chat) {\n return;\n }\n\n void callApi('updateChatMutedState', { chat, isMuted });\n});\n\naddReducer('createChannel', (global, actions, payload) => {\n const {\n title, about, photo, memberIds,\n } = payload!;\n\n const members = (memberIds as number[])\n .map((id: number) => selectUser(global, id))\n .filter<ApiUser>(Boolean as any);\n\n void createChannel(title, members, about, photo);\n});\n\naddReducer('joinChannel', (global, actions, payload) => {\n const { chatId } = payload!;\n const chat = selectChat(global, chatId);\n if (!chat) {\n return;\n }\n\n const { id: channelId, accessHash } = chat;\n\n if (channelId && accessHash) {\n void callApi('joinChannel', { channelId, accessHash });\n }\n});\n\naddReducer('leaveChannel', (global, actions, payload) => {\n const { chatId } = payload!;\n const chat = selectChat(global, chatId);\n if (!chat) {\n return;\n }\n\n const { id: channelId, accessHash } = chat;\n\n if (channelId && accessHash) {\n void callApi('leaveChannel', { channelId, accessHash });\n }\n});\n\naddReducer('deleteChannel', (global, actions, payload) => {\n const { chatId } = payload!;\n const chat = selectChat(global, chatId);\n if (!chat) {\n return;\n }\n\n const { id: channelId, accessHash } = chat;\n\n if (channelId && accessHash) {\n void callApi('deleteChannel', { channelId, accessHash });\n }\n});\n\naddReducer('createGroupChat', (global, actions, payload) => {\n const { title, memberIds, photo } = payload!;\n const members = (memberIds as number[])\n .map((id: number) => selectUser(global, id))\n .filter<ApiUser>(Boolean as any);\n\n void createGroupChat(title, members, photo);\n});\n\naddReducer('toggleChatPinned', (global, actions, payload) => {\n const { id, folderId } = payload!;\n const chat = selectChat(global, id);\n if (!chat) {\n return;\n }\n\n if (folderId) {\n const folder = selectChatFolder(global, folderId);\n if (folder) {\n const shouldBePinned = !selectIsChatPinned(global, id, folderId);\n\n const { pinnedChatIds, includedChatIds } = folder;\n const newPinnedIds = shouldBePinned\n ? [id, ...(pinnedChatIds || [])]\n : (pinnedChatIds || []).filter((pinnedId) => pinnedId !== id);\n\n // With both Pin and Unpin we need to re-add a user to the included group\n const newIncludedChatIds = [id, ...includedChatIds];\n\n void callApi('editChatFolder', {\n id: folderId,\n folderUpdate: {\n ...folder,\n pinnedChatIds: newPinnedIds,\n includedChatIds: newIncludedChatIds,\n },\n });\n }\n } else {\n const listType = selectChatListType(global, id);\n const isPinned = selectIsChatPinned(global, id, listType === 'archived' ? ARCHIVED_FOLDER_ID : undefined);\n void callApi('toggleChatPinned', { chat, shouldBePinned: !isPinned });\n }\n});\n\naddReducer('toggleChatArchived', (global, actions, payload) => {\n const { id } = payload!;\n const chat = selectChat(global, id);\n if (chat) {\n void callApi('toggleChatArchived', {\n chat,\n folderId: isChatArchived(chat) ? 0 : ARCHIVED_FOLDER_ID,\n });\n }\n});\n\naddReducer('loadChatFolders', () => {\n void loadChatFolders();\n});\n\naddReducer('loadRecommendedChatFolders', () => {\n void loadRecommendedChatFolders();\n});\n\naddReducer('editChatFolder', (global, actions, payload) => {\n const { id, folderUpdate } = payload!;\n const folder = selectChatFolder(global, id);\n\n if (folder) {\n void callApi('editChatFolder', {\n id,\n folderUpdate: {\n id,\n emoticon: folder.emoticon,\n pinnedChatIds: folder.pinnedChatIds,\n ...folderUpdate,\n },\n });\n }\n});\n\naddReducer('addChatFolder', (global, actions, payload) => {\n const { folder } = payload!;\n const { orderedIds } = global.chatFolders;\n const maxId = orderedIds && orderedIds.length ? Math.max.apply(Math.max, orderedIds) : ARCHIVED_FOLDER_ID;\n\n void createChatFolder(folder, maxId);\n});\n\naddReducer('deleteChatFolder', (global, actions, payload) => {\n const { id } = payload!;\n const folder = selectChatFolder(global, id);\n\n if (folder) {\n void deleteChatFolder(id);\n }\n});\n\naddReducer('toggleChatUnread', (global, actions, payload) => {\n const { id } = payload!;\n const chat = selectChat(global, id);\n if (chat) {\n if (chat.unreadCount) {\n void callApi('markMessageListRead', { chat, threadId: MAIN_THREAD_ID });\n } else {\n void callApi('toggleDialogUnread', {\n chat,\n hasUnreadMark: !chat.hasUnreadMark,\n });\n }\n }\n});\n\naddReducer('openTelegramLink', (global, actions, payload) => {\n const { url } = payload!;\n let match = RE_TME_INVITE_LINK.exec(url);\n\n if (match) {\n const hash = match[1];\n\n (async () => {\n const chat = await callApi('openChatByInvite', hash);\n\n if (!chat) {\n return;\n }\n\n actions.openChat({ id: chat.id });\n })();\n } else {\n match = RE_TME_LINK.exec(url)!;\n\n const username = match[1];\n const channelPostId = match[2] ? Number(match[2]) : undefined;\n\n void openChatByUsername(actions, username, channelPostId);\n }\n});\n\naddReducer('openChatByUsername', (global, actions, payload) => {\n const { username } = payload!;\n\n void openChatByUsername(actions, username);\n});\n\naddReducer('togglePreHistoryHidden', (global, actions, payload) => {\n const { chatId, isEnabled } = payload!;\n let chat = selectChat(global, chatId);\n\n if (!chat) {\n return;\n }\n\n (async () => {\n if (isChatBasicGroup(chat)) {\n chat = await callApi('migrateChat', chat);\n\n if (!chat) {\n return;\n }\n\n actions.openChat({ id: chat.id });\n }\n\n void callApi('togglePreHistoryHidden', { chat, isEnabled });\n })();\n});\n\naddReducer('updateChatDefaultBannedRights', (global, actions, payload) => {\n const { chatId, bannedRights } = payload!;\n const chat = selectChat(global, chatId);\n\n if (!chat) {\n return;\n }\n\n void callApi('updateChatDefaultBannedRights', { chat, bannedRights });\n});\n\naddReducer('updateChatMemberBannedRights', (global, actions, payload) => {\n const { chatId, userId, bannedRights } = payload!;\n let chat = selectChat(global, chatId);\n const user = selectUser(global, userId);\n\n if (!chat || !user) {\n return;\n }\n\n (async () => {\n if (isChatBasicGroup(chat)) {\n chat = await callApi('migrateChat', chat);\n\n if (!chat) {\n return;\n }\n\n actions.openChat({ id: chat.id });\n }\n\n await callApi('updateChatMemberBannedRights', { chat, user, bannedRights });\n\n const newGlobal = getGlobal();\n const chatAfterUpdate = selectChat(newGlobal, chatId);\n\n if (!chatAfterUpdate || !chatAfterUpdate.fullInfo) {\n return;\n }\n\n const { members, kickedMembers } = chatAfterUpdate.fullInfo;\n\n const isBanned = !!bannedRights.viewMessages;\n const isUnblocked = !Object.keys(bannedRights).length;\n\n setGlobal(updateChat(newGlobal, chatId, {\n fullInfo: {\n ...chatAfterUpdate.fullInfo,\n ...(members && isBanned && {\n members: members.filter((m) => m.userId !== userId),\n }),\n ...(members && !isBanned && {\n members: members.map((m) => (\n m.userId === userId\n ? { ...m, bannedRights }\n : m\n )),\n }),\n ...(isUnblocked && kickedMembers && {\n kickedMembers: kickedMembers.filter((m) => m.userId !== userId),\n }),\n },\n }));\n })();\n});\n\naddReducer('updateChatAdmin', (global, actions, payload) => {\n const {\n chatId, userId, adminRights, customTitle,\n } = payload!;\n let chat = selectChat(global, chatId);\n const user = selectUser(global, userId);\n\n if (!chat || !user) {\n return;\n }\n\n (async () => {\n if (isChatBasicGroup(chat)) {\n chat = await callApi('migrateChat', chat);\n\n if (!chat) {\n return;\n }\n\n actions.openChat({ id: chat.id });\n }\n\n await callApi('updateChatAdmin', {\n chat, user, adminRights, customTitle,\n });\n\n const newGlobal = getGlobal();\n const chatAfterUpdate = selectChat(newGlobal, chatId);\n\n if (!chatAfterUpdate || !chatAfterUpdate.fullInfo) {\n return;\n }\n\n const { adminMembers } = chatAfterUpdate.fullInfo;\n\n const isDismissed = !Object.keys(adminRights).length;\n\n setGlobal(updateChat(newGlobal, chatId, {\n fullInfo: {\n ...chatAfterUpdate.fullInfo,\n ...(adminMembers && isDismissed && {\n adminMembers: adminMembers.filter((m) => m.userId !== userId),\n }),\n ...(adminMembers && !isDismissed && {\n adminMembers: adminMembers.map((m) => (\n m.userId === userId\n ? { ...m, adminRights, customTitle }\n : m\n )),\n }),\n },\n }));\n })();\n});\n\naddReducer('updateChat', (global, actions, payload) => {\n const {\n chatId, title, about, photo,\n } = payload!;\n\n const chat = selectChat(global, chatId);\n if (!chat) {\n return;\n }\n\n (async () => {\n setGlobal(updateManagementProgress(getGlobal(), ManagementProgress.InProgress));\n\n await Promise.all([\n chat.title !== title\n ? callApi('updateChatTitle', chat, title)\n : undefined,\n chat.fullInfo && chat.fullInfo.about !== about\n ? callApi('updateChatAbout', chat, about)\n : undefined,\n photo\n ? callApi('editChatPhoto', { chatId, accessHash: chat.accessHash, photo })\n : undefined,\n ]);\n\n setGlobal(updateManagementProgress(getGlobal(), ManagementProgress.Complete));\n })();\n});\n\naddReducer('toggleSignatures', (global, actions, payload) => {\n const { chatId, isEnabled } = payload!;\n const chat = selectChat(global, chatId);\n\n if (!chat) {\n return;\n }\n\n void callApi('toggleSignatures', { chat, isEnabled });\n});\n\naddReducer('loadGroupsForDiscussion', () => {\n (async () => {\n const groups = await callApi('fetchGroupsForDiscussion');\n if (!groups) {\n return;\n }\n\n const addedById = groups.reduce((result, group) => {\n if (group) {\n result[group.id] = group;\n }\n\n return result;\n }, {} as Record<number, ApiChat>);\n\n const global = addChats(getGlobal(), addedById);\n setGlobal({\n ...global,\n chats: {\n ...global.chats,\n forDiscussionIds: Object.keys(addedById).map(Number),\n },\n });\n })();\n});\n\naddReducer('linkDiscussionGroup', (global, actions, payload) => {\n const { channelId, chatId } = payload!;\n\n const channel = selectChat(global, channelId);\n let chat = selectChat(global, chatId);\n if (!channel || !chat) {\n return;\n }\n\n (async () => {\n if (isChatBasicGroup(chat)) {\n chat = await callApi('migrateChat', chat);\n\n if (!chat) {\n return;\n }\n\n actions.openChat({ id: chat.id });\n }\n\n let { fullInfo } = chat;\n if (!fullInfo) {\n const fullChat = await callApi('fetchFullChat', chat);\n if (!fullChat) {\n return;\n }\n\n fullInfo = fullChat.fullInfo;\n }\n\n if (fullInfo.isPreHistoryHidden) {\n await callApi('togglePreHistoryHidden', { chat, isEnabled: false });\n }\n\n void callApi('setDiscussionGroup', { channel, chat });\n })();\n});\n\naddReducer('unlinkDiscussionGroup', (global, actions, payload) => {\n const { channelId } = payload!;\n\n const channel = selectChat(global, channelId);\n if (!channel) {\n return;\n }\n\n let chat: ApiChat | undefined;\n if (channel.fullInfo && channel.fullInfo.linkedChatId) {\n chat = selectChat(global, channel.fullInfo.linkedChatId);\n }\n\n (async () => {\n await callApi('setDiscussionGroup', { channel });\n if (chat) {\n loadFullChat(chat);\n }\n })();\n});\n\nasync function loadChats(listType: 'active' | 'archived', offsetId?: number, offsetDate?: number) {\n const result = await callApi('fetchChats', {\n limit: CHAT_LIST_LOAD_SLICE,\n offsetDate,\n archived: listType === 'archived',\n withPinned: getGlobal().chats.orderedPinnedIds[listType] === undefined,\n });\n\n if (!result) {\n return;\n }\n\n const { chatIds } = result;\n\n if (chatIds.length > 0 && chatIds[0] === offsetId) {\n chatIds.shift();\n }\n\n let global = getGlobal();\n\n global = addUsers(global, buildCollectionByKey(result.users, 'id'));\n global = updateChats(global, buildCollectionByKey(result.chats, 'id'));\n global = updateChatListIds(global, listType, chatIds);\n global = updateChatListSecondaryInfo(global, listType, result);\n\n Object.keys(result.draftsById).map(Number).forEach((chatId) => {\n global = replaceThreadParam(\n global, chatId, MAIN_THREAD_ID, 'draft', result.draftsById[chatId],\n );\n });\n\n Object.keys(result.replyingToById).map(Number).forEach((chatId) => {\n global = replaceThreadParam(\n global, chatId, MAIN_THREAD_ID, 'replyingToId', result.replyingToById[chatId],\n );\n });\n\n\n if (chatIds.length === 0 && !global.chats.isFullyLoaded[listType]) {\n global = {\n ...global,\n chats: {\n ...global.chats,\n isFullyLoaded: {\n ...global.chats.isFullyLoaded,\n [listType]: true,\n },\n },\n };\n }\n\n setGlobal(global);\n}\n\nasync function loadFullChat(chat: ApiChat) {\n const result = await callApi('fetchFullChat', chat);\n if (!result) {\n return;\n }\n\n const { users, fullInfo } = result;\n\n let global = getGlobal();\n if (users) {\n global = addUsers(global, buildCollectionByKey(users, 'id'));\n }\n global = updateChat(global, chat.id, { fullInfo });\n\n setGlobal(global);\n}\n\nasync function createChannel(title: string, users: ApiUser[], about?: string, photo?: File) {\n setGlobal({\n ...getGlobal(),\n chatCreation: {\n progress: ChatCreationProgress.InProgress,\n },\n });\n\n const createdChannel = await callApi('createChannel', { title, about, users });\n if (!createdChannel) {\n return;\n }\n\n const { id: channelId, accessHash } = createdChannel;\n\n let global = getGlobal();\n global = updateChat(global, channelId, createdChannel);\n global = {\n ...global,\n chatCreation: {\n ...global.chatCreation,\n progress: createdChannel ? ChatCreationProgress.Complete : ChatCreationProgress.Error,\n },\n };\n setGlobal(global);\n getDispatch().openChat({ id: channelId });\n\n if (channelId && accessHash && photo) {\n await callApi('editChatPhoto', { chatId: channelId, accessHash, photo });\n }\n}\n\nasync function createGroupChat(title: string, users: ApiUser[], photo?: File) {\n setGlobal({\n ...getGlobal(),\n chatCreation: {\n progress: ChatCreationProgress.InProgress,\n },\n });\n\n const createdChat = await callApi('createGroupChat', { title, users });\n if (!createdChat) {\n return;\n }\n\n const { id: chatId } = createdChat;\n\n let global = getGlobal();\n global = updateChat(global, chatId, createdChat);\n global = {\n ...global,\n chatCreation: {\n ...global.chatCreation,\n progress: createdChat ? ChatCreationProgress.Complete : ChatCreationProgress.Error,\n },\n };\n setGlobal(global);\n getDispatch().openChat({ id: chatId });\n\n if (chatId && photo) {\n await callApi('editChatPhoto', { chatId, photo });\n }\n}\n\nasync function loadChatFolders() {\n const chatFolders = await callApi('fetchChatFolders');\n\n if (chatFolders) {\n const global = getGlobal();\n\n setGlobal({\n ...global,\n chatFolders: {\n ...global.chatFolders,\n ...chatFolders,\n },\n });\n }\n}\n\nasync function loadRecommendedChatFolders() {\n const recommendedChatFolders = await callApi('fetchRecommendedChatFolders');\n\n if (recommendedChatFolders) {\n const global = getGlobal();\n\n setGlobal({\n ...global,\n chatFolders: {\n ...global.chatFolders,\n recommended: recommendedChatFolders,\n },\n });\n }\n}\n\nasync function createChatFolder(folder: ApiChatFolder, maxId: number) {\n // Clear fields from recommended folders\n const { id: recommendedId, description, ...newFolder } = folder;\n\n await callApi('editChatFolder', {\n id: maxId + 1,\n folderUpdate: {\n id: maxId + 1,\n ...newFolder,\n },\n });\n\n if (!description) {\n return;\n }\n\n const global = getGlobal();\n const { recommended } = global.chatFolders;\n\n if (recommended) {\n setGlobal({\n ...global,\n chatFolders: {\n ...global.chatFolders,\n recommended: recommended.filter(({ id }) => id !== recommendedId),\n },\n });\n }\n}\n\nasync function deleteChatFolder(id: number) {\n await callApi('deleteChatFolder', id);\n}\n\nasync function openChatByUsername(\n actions: GlobalActions,\n username: string,\n channelPostId?: number,\n) {\n const global = getGlobal();\n const localChat = selectChatByUsername(global, username);\n if (localChat && !localChat.isMin) {\n if (channelPostId) {\n actions.focusMessage({ chatId: localChat.id, messageId: channelPostId });\n } else {\n actions.openChat({ id: localChat.id });\n }\n return;\n }\n\n const previousChat = selectCurrentChat(global);\n // Open temporary empty chat to make the click response feel faster\n actions.openChat({ id: TMP_CHAT_ID });\n\n const chat = await callApi('getChatByUsername', username);\n if (!chat) {\n if (previousChat) {\n actions.openChat({ id: previousChat.id });\n }\n\n actions.showNotification({ message: 'User does not exist' });\n\n return;\n }\n\n setGlobal(updateChat(getGlobal(), chat.id, chat));\n\n if (channelPostId) {\n actions.focusMessage({ chatId: chat.id, messageId: channelPostId });\n } else {\n actions.openChat({ id: chat.id });\n }\n}\n","import { addReducer, getGlobal, setGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../../global/types';\nimport {\n ApiAttachment,\n ApiChat,\n ApiMessage,\n ApiMessageEntity,\n ApiNewPoll,\n ApiOnProgress,\n ApiSticker,\n ApiVideo,\n MAIN_THREAD_ID,\n MESSAGE_DELETED,\n} from '../../../api/types';\nimport { LoadMoreDirection } from '../../../types';\n\nimport { MAX_MEDIA_FILES_FOR_ALBUM, MESSAGE_LIST_SLICE } from '../../../config';\nimport { callApi, cancelApiProgress } from '../../../api/gramjs';\nimport { areSortedArraysIntersecting, buildCollectionByKey, split } from '../../../util/iteratees';\nimport {\n addUsers,\n addChatMessagesById,\n replaceThreadParam,\n safeReplaceViewportIds,\n updateChatMessage,\n addChats,\n updateListedIds,\n updateOutlyingIds,\n replaceScheduledMessages,\n updateThreadInfos,\n} from '../../reducers';\nimport {\n selectChat,\n selectChatMessage,\n selectCurrentMessageList,\n selectFocusedMessageId,\n selectCurrentChat,\n selectListedIds,\n selectOutlyingIds,\n selectViewportIds,\n selectRealLastReadId,\n selectReplyingToId,\n selectEditingId,\n selectDraft,\n selectThreadOriginChat,\n selectThreadTopMessageId,\n selectEditingScheduledId,\n selectEditingMessage,\n selectScheduledMessage,\n selectNoWebPage,\n} from '../../selectors';\nimport { rafPromise } from '../../../util/schedulers';\nimport { copyTextToClipboard } from '../../../util/clipboard';\n\nconst uploadProgressCallbacks = new Map<number, ApiOnProgress>();\n\naddReducer('loadViewportMessages', (global, actions, payload) => {\n const {\n direction = LoadMoreDirection.Around,\n isBudgetPreload = false,\n } = payload || {};\n\n let { chatId, threadId } = payload || {};\n\n if (!chatId) {\n const currentMessageList = selectCurrentMessageList(global);\n if (!currentMessageList) {\n return undefined;\n }\n\n chatId = currentMessageList.chatId;\n threadId = currentMessageList.threadId;\n }\n\n const chat = selectChat(global, chatId);\n // TODO Revise if `chat.isRestricted` check is needed\n if (!chat || chat.isRestricted) {\n return undefined;\n }\n\n const viewportIds = selectViewportIds(global, chatId, threadId);\n const listedIds = selectListedIds(global, chatId, threadId);\n const outlyingIds = selectOutlyingIds(global, chatId, threadId);\n\n if (!viewportIds || !viewportIds.length || direction === LoadMoreDirection.Around) {\n const offsetId = selectFocusedMessageId(global, chatId) || selectRealLastReadId(global, chatId, threadId);\n const isOutlying = Boolean(offsetId && listedIds && !listedIds.includes(offsetId));\n const historyIds = (isOutlying ? outlyingIds : listedIds) || [];\n const {\n newViewportIds, areSomeLocal, areAllLocal,\n } = getViewportSlice(historyIds, offsetId, LoadMoreDirection.Around);\n\n if (areSomeLocal && newViewportIds.length >= MESSAGE_LIST_SLICE) {\n global = safeReplaceViewportIds(global, chatId, threadId, newViewportIds);\n }\n\n if (!areAllLocal) {\n void loadViewportMessages(chat, threadId, offsetId, LoadMoreDirection.Around, isOutlying, isBudgetPreload);\n }\n } else {\n const offsetId = direction === LoadMoreDirection.Backwards ? viewportIds[0] : viewportIds[viewportIds.length - 1];\n const isOutlying = Boolean(outlyingIds);\n const historyIds = (isOutlying ? outlyingIds : listedIds)!;\n const {\n newViewportIds, areSomeLocal, areAllLocal,\n } = getViewportSlice(historyIds, offsetId, direction);\n\n if (areSomeLocal) {\n global = safeReplaceViewportIds(global, chatId, threadId, newViewportIds);\n }\n\n void loadWithBudget(actions, areAllLocal, isOutlying, isBudgetPreload, chat, threadId, direction, offsetId);\n\n if (isBudgetPreload) {\n return undefined;\n }\n }\n\n return global;\n});\n\nasync function loadWithBudget(\n actions: GlobalActions,\n areAllLocal: boolean, isOutlying: boolean, isBudgetPreload: boolean,\n chat: ApiChat, threadId: number, direction: LoadMoreDirection, offsetId?: number,\n) {\n if (!areAllLocal) {\n await loadViewportMessages(\n chat, threadId, offsetId, direction, isOutlying, isBudgetPreload,\n );\n }\n\n if (!isBudgetPreload) {\n // Let reducer return and update global\n await Promise.resolve();\n actions.loadViewportMessages({\n chatId: chat.id, threadId, direction, isBudgetPreload: true,\n });\n }\n}\n\naddReducer('loadMessage', (global, actions, payload) => {\n const { chatId, messageId, replyOriginForId } = payload!;\n const chat = selectChat(global, chatId);\n\n if (!chat) {\n return;\n }\n\n void loadMessage(chat, messageId, replyOriginForId);\n});\n\naddReducer('sendMessage', (global, actions, payload) => {\n const currentMessageList = selectCurrentMessageList(global);\n if (!currentMessageList) {\n return undefined;\n }\n\n const { chatId, threadId, type } = currentMessageList;\n\n if (type === 'scheduled' && !payload.scheduledAt) {\n return {\n ...global,\n messages: {\n ...global.messages,\n contentToBeScheduled: payload,\n },\n };\n }\n\n const chat = selectChat(global, chatId)!;\n\n actions.setReplyingToId({ messageId: undefined });\n actions.clearWebPagePreview({ chatId, threadId, value: false });\n\n const params = {\n ...payload,\n chat,\n replyingTo: selectReplyingToId(global, chatId, threadId),\n noWebPage: selectNoWebPage(global, chatId, threadId),\n };\n\n const isSingle = !payload.attachments || payload.attachments.length <= 1;\n const isGrouped = !isSingle && payload.attachments && payload.attachments.length > 1;\n\n if (isSingle) {\n const { attachments, ...restParams } = params;\n sendMessage({\n ...restParams,\n attachment: attachments ? attachments[0] : undefined,\n });\n } else if (isGrouped) {\n const {\n text, entities, attachments, ...commonParams\n } = params;\n const groupedAttachments = split(attachments, MAX_MEDIA_FILES_FOR_ALBUM);\n for (let i = 0; i < groupedAttachments.length; i++) {\n const [firstAttachment, ...restAttachments] = groupedAttachments[i];\n const groupedId = `${Date.now()}${i}`;\n\n sendMessage({\n ...commonParams,\n text: i === 0 ? text : undefined,\n entities: i === 0 ? entities : undefined,\n attachment: firstAttachment,\n groupedId: restAttachments.length > 0 ? groupedId : undefined,\n });\n\n restAttachments.forEach((attachment: ApiAttachment) => {\n sendMessage({\n ...commonParams,\n attachment,\n groupedId,\n });\n });\n }\n } else {\n const {\n text, entities, attachments, replyingTo, ...commonParams\n } = params;\n\n if (text) {\n sendMessage({\n ...commonParams,\n text,\n entities,\n replyingTo,\n });\n }\n\n attachments.forEach((attachment: ApiAttachment) => {\n sendMessage({\n ...commonParams,\n attachment,\n });\n });\n }\n\n return undefined;\n});\n\naddReducer('editMessage', (global, actions, payload) => {\n const { text, entities } = payload!;\n\n const currentMessageList = selectCurrentMessageList(global);\n if (!currentMessageList) {\n return;\n }\n\n const { chatId, threadId, type: messageListType } = currentMessageList;\n const chat = selectChat(global, chatId);\n const message = selectEditingMessage(global, chatId, threadId, messageListType);\n if (!chat || !message) {\n return;\n }\n\n void callApi('editMessage', {\n chat, message, text, entities,\n });\n\n actions.setEditingId({ messageId: undefined });\n});\n\naddReducer('cancelSendingMessage', (global, actions, payload) => {\n const { chatId, messageId } = payload!;\n const message = selectChatMessage(global, chatId, messageId);\n const progressCallback = message && uploadProgressCallbacks.get(message.previousLocalId || message.id);\n if (progressCallback) {\n cancelApiProgress(progressCallback);\n }\n\n actions.apiUpdate({\n '@type': 'deleteMessages',\n ids: [messageId],\n chatId,\n });\n});\n\naddReducer('saveDraft', (global, actions, payload) => {\n const { chatId, threadId, draft } = payload!;\n if (!draft) {\n return undefined;\n }\n\n const { text, entities } = draft;\n const chat = selectChat(global, chatId)!;\n\n if (threadId === MAIN_THREAD_ID) {\n void callApi('saveDraft', {\n chat,\n text,\n entities,\n replyToMsgId: selectReplyingToId(global, chatId, threadId),\n });\n }\n\n return replaceThreadParam(global, chatId, threadId, 'draft', draft);\n});\n\naddReducer('clearDraft', (global, actions, payload) => {\n const { chatId, threadId, localOnly } = payload!;\n if (!selectDraft(global, chatId, threadId)) {\n return undefined;\n }\n\n const chat = selectChat(global, chatId)!;\n\n if (!localOnly && threadId === MAIN_THREAD_ID) {\n void callApi('clearDraft', chat);\n }\n\n return replaceThreadParam(global, chatId, threadId, 'draft', undefined);\n});\n\naddReducer('toggleMessageWebPage', (global, actions, payload) => {\n const { chatId, threadId, noWebPage } = payload!;\n\n return replaceThreadParam(global, chatId, threadId, 'noWebPage', noWebPage);\n});\n\naddReducer('pinMessage', (global, actions, payload) => {\n const chat = selectCurrentChat(global);\n if (!chat) {\n return;\n }\n\n const {\n messageId, isUnpin, isOneSide, isSilent,\n } = payload!;\n\n void callApi('pinMessage', {\n chat, messageId, isUnpin, isOneSide, isSilent,\n });\n});\n\naddReducer('unpinAllMessages', (global, actions, payload) => {\n const chat = selectChat(global, payload.chatId);\n if (!chat) {\n return;\n }\n\n void unpinAllMessages(chat);\n});\n\nasync function unpinAllMessages(chat: ApiChat) {\n await callApi('unpinAllMessages', { chat });\n let global = getGlobal();\n global = replaceThreadParam(global, chat.id, MAIN_THREAD_ID, 'pinnedIds', []);\n setGlobal(global);\n}\n\naddReducer('deleteMessages', (global, actions, payload) => {\n const { messageIds, shouldDeleteForAll } = payload!;\n const currentMessageList = selectCurrentMessageList(global);\n if (!currentMessageList) {\n return;\n }\n const { chatId, threadId } = currentMessageList;\n const chat = selectChat(global, chatId)!;\n\n void callApi('deleteMessages', { chat, messageIds, shouldDeleteForAll });\n\n const editingId = selectEditingId(global, chatId, threadId);\n if (messageIds.includes(editingId)) {\n actions.setEditingId({ messageId: undefined });\n }\n});\n\naddReducer('deleteScheduledMessages', (global, actions, payload) => {\n const { messageIds } = payload!;\n const currentMessageList = selectCurrentMessageList(global);\n if (!currentMessageList) {\n return;\n }\n\n const { chatId } = currentMessageList;\n const chat = selectChat(global, chatId)!;\n\n void callApi('deleteScheduledMessages', { chat, messageIds });\n\n const editingId = selectEditingScheduledId(global, chatId);\n if (messageIds.includes(editingId)) {\n actions.setEditingId({ messageId: undefined });\n }\n});\n\naddReducer('deleteHistory', (global, actions, payload) => {\n const { chatId, maxId, shouldDeleteForAll } = payload!;\n const chat = selectChat(global, chatId);\n if (!chat) {\n return;\n }\n\n void callApi('deleteHistory', { chat, shouldDeleteForAll, maxId });\n});\n\naddReducer('markMessageListRead', (global, actions, payload) => {\n const currentMessageList = selectCurrentMessageList(global);\n if (!currentMessageList) {\n return;\n }\n\n const { chatId, threadId } = currentMessageList;\n const chat = selectThreadOriginChat(global, chatId, threadId);\n if (!chat) {\n return;\n }\n\n const { maxId } = payload!;\n\n void callApi('markMessageListRead', { chat, threadId, maxId });\n});\n\naddReducer('markMessagesRead', (global, actions, payload) => {\n const chat = selectCurrentChat(global);\n if (!chat) {\n return;\n }\n\n const { messageIds } = payload!;\n\n void callApi('markMessagesRead', { chat, messageIds });\n});\n\naddReducer('loadWebPagePreview', (global, actions, payload) => {\n const { text } = payload!;\n void loadWebPagePreview(text);\n});\n\naddReducer('clearWebPagePreview', (global) => {\n if (!global.webPagePreview) {\n return undefined;\n }\n\n return {\n ...global,\n webPagePreview: undefined,\n };\n});\n\naddReducer('sendPollVote', (global, actions, payload) => {\n const { chatId, messageId, options } = payload!;\n const chat = selectChat(global, chatId);\n\n if (chat) {\n void callApi('sendPollVote', { chat, messageId, options });\n }\n});\n\naddReducer('loadPollOptionResults', (global, actions, payload) => {\n const {\n chat, messageId, option, offset, limit, shouldResetVoters,\n } = payload!;\n\n void loadPollOptionResults(chat, messageId, option, offset, limit, shouldResetVoters);\n});\n\naddReducer('forwardMessages', (global) => {\n const { fromChatId, messageIds, toChatId } = global.forwardMessages;\n const fromChat = fromChatId ? selectChat(global, fromChatId) : undefined;\n const toChat = toChatId ? selectChat(global, toChatId) : undefined;\n const messages = fromChatId && messageIds\n ? messageIds\n .sort((a, b) => a - b)\n .map((id) => selectChatMessage(global, fromChatId, id)).filter<ApiMessage>(Boolean as any)\n : undefined;\n\n if (fromChat && toChat && messages && messages.length) {\n void forwardMessages(fromChat, toChat, messages);\n }\n});\n\naddReducer('loadScheduledHistory', (global) => {\n const chat = selectCurrentChat(global);\n if (!chat) {\n return;\n }\n\n const { hash } = global.scheduledMessages.byChatId[chat.id] || {};\n\n void loadScheduledHistory(chat, hash);\n});\n\naddReducer('sendScheduledMessages', (global, actions, payload) => {\n const {\n chatId, id,\n } = payload!;\n\n const chat = selectChat(global, chatId);\n\n if (!chat) {\n return;\n }\n\n void callApi('sendScheduledMessages', {\n chat,\n ids: [id],\n });\n});\n\naddReducer('rescheduleMessage', (global, actions, payload) => {\n const {\n chatId, messageId, scheduledAt,\n } = payload!;\n\n const chat = selectChat(global, chatId);\n const message = chat && selectScheduledMessage(global, chat.id, messageId);\n if (!chat || !message) {\n return;\n }\n\n void callApi('rescheduleMessage', {\n chat,\n message,\n scheduledAt,\n });\n});\n\naddReducer('requestThreadInfoUpdate', (global, actions, payload) => {\n const { chatId, threadId } = payload;\n const chat = selectThreadOriginChat(global, chatId, threadId);\n if (!chat) {\n return;\n }\n\n void callApi('requestThreadInfoUpdate', { chat, threadId });\n});\n\nasync function loadWebPagePreview(message: string) {\n const webPagePreview = await callApi('fetchWebPagePreview', { message });\n\n setGlobal({\n ...getGlobal(),\n webPagePreview,\n });\n}\n\nasync function loadViewportMessages(\n chat: ApiChat,\n threadId: number,\n offsetId: number | undefined,\n direction: LoadMoreDirection,\n isOutlying = false,\n isBudgetPreload = false,\n) {\n const chatId = chat.id;\n\n let addOffset: number | undefined;\n switch (direction) {\n case LoadMoreDirection.Backwards:\n addOffset = undefined;\n break;\n case LoadMoreDirection.Around:\n addOffset = -(Math.round(MESSAGE_LIST_SLICE / 2) + 1);\n break;\n case LoadMoreDirection.Forwards:\n addOffset = -(MESSAGE_LIST_SLICE + 1);\n break;\n }\n\n const result = await callApi('fetchMessages', {\n chat: selectThreadOriginChat(getGlobal(), chatId, threadId)!,\n offsetId,\n addOffset,\n limit: MESSAGE_LIST_SLICE,\n threadId,\n });\n\n if (!result) {\n return;\n }\n\n const {\n messages, users, chats, threadInfos, firstMessageId,\n } = result;\n\n const byId = buildCollectionByKey(messages, 'id');\n const ids = Object.keys(byId).map(Number);\n\n let global = getGlobal();\n\n global = addChatMessagesById(global, chatId, byId);\n global = isOutlying\n ? updateOutlyingIds(global, chatId, threadId, ids)\n : updateListedIds(global, chatId, threadId, ids);\n global = addUsers(global, buildCollectionByKey(users, 'id'));\n global = addChats(global, buildCollectionByKey(chats, 'id'));\n global = updateThreadInfos(global, chatId, threadInfos);\n\n if (firstMessageId) {\n global = replaceThreadParam(global, chatId, threadId, 'firstMessageId', firstMessageId);\n }\n\n let listedIds = selectListedIds(global, chatId, threadId);\n const outlyingIds = selectOutlyingIds(global, chatId, threadId);\n\n if (isOutlying && listedIds && outlyingIds) {\n if (areSortedArraysIntersecting(listedIds, outlyingIds)) {\n global = updateListedIds(global, chatId, threadId, outlyingIds);\n listedIds = selectListedIds(global, chatId, threadId);\n global = replaceThreadParam(global, chatId, threadId, 'outlyingIds', undefined);\n isOutlying = false;\n }\n }\n\n if (!isBudgetPreload) {\n const historyIds = isOutlying ? outlyingIds! : listedIds!;\n const { newViewportIds } = getViewportSlice(historyIds, offsetId, direction);\n global = safeReplaceViewportIds(global, chatId, threadId, newViewportIds!);\n }\n\n setGlobal(global);\n}\n\nasync function loadMessage(chat: ApiChat, messageId: number, replyOriginForId: number) {\n const result = await callApi('fetchMessage', { chat, messageId });\n if (!result) {\n return;\n }\n\n if (result === MESSAGE_DELETED) {\n if (replyOriginForId) {\n let global = getGlobal();\n const replyMessage = selectChatMessage(global, chat.id, replyOriginForId);\n global = updateChatMessage(global, chat.id, replyOriginForId, {\n ...replyMessage,\n replyToMessageId: undefined,\n });\n setGlobal(global);\n }\n\n return;\n }\n\n let global = getGlobal();\n global = updateChatMessage(global, chat.id, messageId, result.message);\n global = addUsers(global, buildCollectionByKey(result.users, 'id'));\n setGlobal(global);\n}\n\nfunction findClosestIndex(sourceIds: number[], offsetId: number) {\n if (offsetId < sourceIds[0]) {\n return 0;\n }\n\n if (offsetId > sourceIds[sourceIds.length - 1]) {\n return sourceIds.length - 1;\n }\n\n return sourceIds.findIndex((id, i) => (\n id === offsetId\n || (id < offsetId && sourceIds[i + 1] > offsetId)\n ));\n}\n\nfunction getViewportSlice(\n sourceIds: number[],\n offsetId: number | undefined,\n direction: LoadMoreDirection,\n) {\n const { length } = sourceIds;\n const index = offsetId ? findClosestIndex(sourceIds, offsetId) : -1;\n const isBackwards = direction === LoadMoreDirection.Backwards;\n const indexForDirection = isBackwards ? index : (index + 1) || length;\n const from = indexForDirection - MESSAGE_LIST_SLICE;\n const to = indexForDirection + MESSAGE_LIST_SLICE - 1;\n const newViewportIds = sourceIds.slice(Math.max(0, from), to + 1);\n\n let areSomeLocal;\n let areAllLocal;\n switch (direction) {\n case LoadMoreDirection.Backwards:\n areSomeLocal = indexForDirection > 0;\n areAllLocal = from >= 0;\n break;\n case LoadMoreDirection.Forwards:\n areSomeLocal = indexForDirection < length;\n areAllLocal = to <= length - 1;\n break;\n case LoadMoreDirection.Around:\n default:\n areSomeLocal = newViewportIds.length > 0;\n areAllLocal = newViewportIds.length === MESSAGE_LIST_SLICE;\n break;\n }\n\n return { newViewportIds, areSomeLocal, areAllLocal };\n}\n\nasync function sendMessage(params: {\n chat: ApiChat;\n text: string;\n entities: ApiMessageEntity[];\n replyingTo: number;\n attachment: ApiAttachment;\n sticker: ApiSticker;\n gif: ApiVideo;\n poll: ApiNewPoll;\n}) {\n let localId: number | undefined;\n const progressCallback = params.attachment ? (progress: number, messageLocalId: number) => {\n if (!uploadProgressCallbacks.has(messageLocalId)) {\n localId = messageLocalId;\n uploadProgressCallbacks.set(messageLocalId, progressCallback!);\n }\n\n const global = getGlobal();\n\n setGlobal({\n ...global,\n fileUploads: {\n byMessageLocalId: {\n ...global.fileUploads.byMessageLocalId,\n [messageLocalId]: { progress },\n },\n },\n });\n } : undefined;\n\n // @optimization\n if (params.replyingTo) {\n await rafPromise();\n }\n\n const global = getGlobal();\n const currentMessageList = selectCurrentMessageList(global);\n if (!currentMessageList) {\n return;\n }\n const { threadId } = currentMessageList;\n\n if (!params.replyingTo && threadId !== MAIN_THREAD_ID) {\n params.replyingTo = selectThreadTopMessageId(global, params.chat.id, threadId)!;\n }\n\n await callApi('sendMessage', params, progressCallback);\n\n if (progressCallback && localId) {\n uploadProgressCallbacks.delete(localId);\n }\n}\n\nfunction forwardMessages(\n fromChat: ApiChat,\n toChat: ApiChat,\n messages: ApiMessage[],\n) {\n callApi('forwardMessages', {\n fromChat,\n toChat,\n messages,\n });\n\n setGlobal({\n ...getGlobal(),\n forwardMessages: {},\n });\n}\n\nasync function loadPollOptionResults(\n chat: ApiChat,\n messageId: number,\n option: string,\n offset?: string,\n limit?: number,\n shouldResetVoters?: boolean,\n) {\n const result = await callApi('loadPollOptionResults', {\n chat, messageId, option, offset, limit,\n });\n\n if (!result) {\n return;\n }\n\n const isUnique = (v: number, i: number, a: number[]) => a.indexOf(v) === i;\n let global = getGlobal();\n\n global = addUsers(global, buildCollectionByKey(result.users, 'id'));\n const { voters } = global.pollResults;\n\n setGlobal({\n ...global,\n pollResults: {\n ...global.pollResults,\n voters: {\n ...voters,\n [option]: [\n ...(!shouldResetVoters && voters && voters[option] ? voters[option] : []),\n ...(result && result.users.map((user) => user.id)),\n ].filter(isUnique),\n },\n offsets: {\n ...(global.pollResults.offsets ? global.pollResults.offsets : {}),\n [option]: result.nextOffset || '',\n },\n },\n });\n}\n\naddReducer('loadPinnedMessages', (global, actions, payload) => {\n const { chatId } = payload;\n const chat = selectChat(global, chatId);\n if (!chat) {\n return;\n }\n\n void loadPinnedMessages(chat);\n});\n\naddReducer('loadMessageLink', (global, actions, payload) => {\n const { messageId, chatId } = payload;\n const chat = selectChat(global, chatId);\n const message = selectChatMessage(global, chatId, messageId);\n\n if (!chat || !message) {\n return;\n }\n\n (async () => {\n const result = await callApi('fetchMessageLink', { chat, message });\n\n if (result) {\n copyTextToClipboard(result.link);\n }\n })();\n});\n\nasync function loadPinnedMessages(chat: ApiChat) {\n const result = await callApi('fetchPinnedMessages', { chat });\n if (!result) {\n return;\n }\n\n const { messages, chats, users } = result;\n\n const byId = buildCollectionByKey(messages, 'id');\n const ids = Object.keys(byId).map(Number).sort((a, b) => b - a);\n\n let global = getGlobal();\n global = addChatMessagesById(global, chat.id, byId);\n global = replaceThreadParam(global, chat.id, MAIN_THREAD_ID, 'pinnedIds', ids);\n global = addUsers(global, buildCollectionByKey(users, 'id'));\n global = addChats(global, buildCollectionByKey(chats, 'id'));\n setGlobal(global);\n}\n\nasync function loadScheduledHistory(chat: ApiChat, historyHash?: number) {\n const result = await callApi('fetchScheduledHistory', { chat, hash: historyHash });\n if (!result) {\n return;\n }\n\n const { hash, messages } = result;\n\n const byId = buildCollectionByKey(messages, 'id');\n const ids = Object.keys(byId).map(Number).sort((a, b) => b - a);\n\n let global = getGlobal();\n global = replaceScheduledMessages(global, chat.id, byId, hash);\n global = replaceThreadParam(global, chat.id, MAIN_THREAD_ID, 'scheduledIds', ids);\n setGlobal(global);\n}\n","import { addReducer, getGlobal, setGlobal } from '../../../lib/teact/teactn';\n\nimport { ApiSticker } from '../../../api/types';\nimport { callApi } from '../../../api/gramjs';\nimport { pause, throttle } from '../../../util/schedulers';\nimport {\n updateStickerSets,\n updateStickerSet,\n replaceAnimatedEmojis,\n updateGifSearch,\n updateStickersForEmoji,\n rebuildStickersForEmoji,\n} from '../../reducers';\nimport searchWords from '../../../util/searchWords';\nimport { selectStickerSet } from '../../selectors';\n\nconst ADDED_SETS_THROTTLE = 500;\nconst ADDED_SETS_THROTTLE_CHUNK = 50;\n\nconst searchThrottled = throttle((cb) => cb(), 500, false);\n\naddReducer('loadStickerSets', (global) => {\n const { hash } = global.stickers.added || {};\n void loadStickerSets(hash);\n});\n\naddReducer('loadAddedStickers', (global, actions) => {\n const { setIds: addedSetIds } = global.stickers.added;\n if (!addedSetIds || !addedSetIds.length) {\n return;\n }\n\n (async () => {\n for (let i = 0; i < addedSetIds.length; i++) {\n actions.loadStickers({ stickerSetId: addedSetIds[i] });\n\n if (i % ADDED_SETS_THROTTLE_CHUNK === 0 && i > 0) {\n await pause(ADDED_SETS_THROTTLE);\n }\n }\n })();\n});\n\naddReducer('loadRecentStickers', (global) => {\n const { hash } = global.stickers.recent || {};\n void loadRecentStickers(hash);\n});\n\naddReducer('loadFavoriteStickers', (global) => {\n const { hash } = global.stickers.favorite || {};\n void loadFavoriteStickers(hash);\n});\n\naddReducer('loadFeaturedStickers', (global) => {\n const { hash } = global.stickers.featured || {};\n void loadFeaturedStickers(hash);\n});\n\naddReducer('loadStickers', (global, actions, payload) => {\n const { stickerSetId } = payload!;\n let { stickerSetAccessHash } = payload!;\n\n if (!stickerSetAccessHash) {\n const stickerSet = selectStickerSet(global, stickerSetId);\n if (!stickerSet) {\n return;\n }\n\n stickerSetAccessHash = stickerSet.accessHash;\n }\n\n void loadStickers(stickerSetId, stickerSetAccessHash);\n});\n\naddReducer('loadAnimatedEmojis', () => {\n void loadAnimatedEmojis();\n});\n\naddReducer('loadSavedGifs', (global) => {\n const { hash } = global.gifs.saved;\n void loadSavedGifs(hash);\n});\n\naddReducer('faveSticker', (global, actions, payload) => {\n const { sticker } = payload!;\n\n if (sticker) {\n void callApi('faveSticker', { sticker });\n }\n});\n\naddReducer('unfaveSticker', (global, actions, payload) => {\n const { sticker } = payload!;\n\n if (sticker) {\n void unfaveSticker(sticker);\n }\n});\n\naddReducer('toggleStickerSet', (global, actions, payload) => {\n const { stickerSetId } = payload!;\n const stickerSet = selectStickerSet(global, stickerSetId);\n if (!stickerSet) {\n return;\n }\n\n const { accessHash, installedDate } = stickerSet;\n\n void callApi(!installedDate ? 'installStickerSet' : 'uninstallStickerSet', { stickerSetId, accessHash });\n});\n\nasync function loadStickerSets(hash = 0) {\n const addedStickers = await callApi('fetchStickerSets', { hash });\n if (!addedStickers) {\n return;\n }\n\n setGlobal(updateStickerSets(\n getGlobal(),\n 'added',\n addedStickers.hash,\n addedStickers.sets,\n ));\n}\n\nasync function loadRecentStickers(hash = 0) {\n const recentStickers = await callApi('fetchRecentStickers', { hash });\n if (!recentStickers) {\n return;\n }\n\n const global = getGlobal();\n\n setGlobal({\n ...global,\n stickers: {\n ...global.stickers,\n recent: recentStickers,\n },\n });\n}\n\nasync function loadFavoriteStickers(hash = 0) {\n const favoriteStickers = await callApi('fetchFavoriteStickers', { hash });\n if (!favoriteStickers) {\n return;\n }\n\n const global = getGlobal();\n\n setGlobal({\n ...global,\n stickers: {\n ...global.stickers,\n favorite: favoriteStickers,\n },\n });\n}\n\nasync function loadFeaturedStickers(hash = 0) {\n const featuredStickers = await callApi('fetchFeaturedStickers', { hash });\n if (!featuredStickers) {\n return;\n }\n\n setGlobal(updateStickerSets(\n getGlobal(),\n 'featured',\n featuredStickers.hash,\n featuredStickers.sets,\n ));\n}\n\nasync function loadStickers(stickerSetId: string, accessHash: string) {\n const stickerSet = await callApi('fetchStickers', { stickerSetId, accessHash });\n if (!stickerSet) {\n return;\n }\n\n const { set, stickers, packs } = stickerSet;\n\n let global = getGlobal();\n\n global = updateStickerSet(global, set.id, { ...set, stickers, packs });\n\n const currentEmoji = global.stickers.forEmoji.emoji;\n if (currentEmoji && packs[currentEmoji]) {\n global = rebuildStickersForEmoji(global);\n }\n\n setGlobal(global);\n}\n\nasync function loadAnimatedEmojis() {\n const stickerSet = await callApi('fetchAnimatedEmojis');\n if (!stickerSet) {\n return;\n }\n\n const { set, stickers } = stickerSet;\n\n setGlobal(replaceAnimatedEmojis(getGlobal(), { ...set, stickers }));\n}\n\nfunction unfaveSticker(sticker: ApiSticker) {\n const global = getGlobal();\n\n // Remove sticker preemptively to get instant feedback when user removes sticker\n // from favorites while in Sticker Picker\n setGlobal({\n ...global,\n stickers: {\n ...global.stickers,\n favorite: {\n ...global.stickers.favorite,\n stickers: global.stickers.favorite.stickers.filter(({ id }) => id !== sticker.id),\n },\n },\n });\n\n void callApi('faveSticker', { sticker, unfave: true });\n}\n\naddReducer('setStickerSearchQuery', (global, actions, payload) => {\n const { query } = payload!;\n\n if (query) {\n void searchThrottled(() => {\n searchStickers(query);\n });\n }\n});\n\naddReducer('setGifSearchQuery', (global, actions, payload) => {\n const { query } = payload!;\n\n if (typeof query === 'string') {\n void searchThrottled(() => {\n searchGifs(query);\n });\n }\n});\n\naddReducer('searchMoreGifs', (global) => {\n const { query, offset } = global.gifs.search;\n\n if (typeof query === 'string') {\n void searchThrottled(() => {\n searchGifs(query, offset);\n });\n }\n});\n\naddReducer('loadStickersForEmoji', (global, actions, payload) => {\n const { emoji } = payload!;\n const { hash } = global.stickers.forEmoji;\n\n void searchThrottled(() => {\n loadStickersForEmoji(emoji, hash);\n });\n});\n\naddReducer('clearStickersForEmoji', (global) => {\n return {\n ...global,\n stickers: {\n ...global.stickers,\n forEmoji: {},\n },\n };\n});\n\nasync function searchStickers(query: string, hash = 0) {\n const result = await callApi('searchStickers', { query, hash });\n\n if (!result) {\n return;\n }\n\n const global = getGlobal();\n const { setsById, added } = global.stickers;\n\n const resultIds = result.sets.map(({ id }) => id);\n\n if (added.setIds) {\n added.setIds.forEach((id) => {\n if (!resultIds.includes(id)) {\n const { title } = setsById[id] || {};\n if (title && searchWords(title, query)) {\n resultIds.unshift(id);\n }\n }\n });\n }\n\n setGlobal(updateStickerSets(\n global,\n 'search',\n result.hash,\n result.sets,\n resultIds,\n ));\n}\n\nasync function searchGifs(query: string, offset?: string) {\n const result = await callApi('searchGifs', { query, offset });\n if (!result) {\n return;\n }\n\n setGlobal(updateGifSearch(getGlobal(), !offset, result.gifs, result.nextOffset));\n}\n\nasync function loadSavedGifs(hash = 0) {\n const savedGifs = await callApi('fetchSavedGifs', { hash });\n if (!savedGifs) {\n return;\n }\n\n const global = getGlobal();\n\n setGlobal({\n ...global,\n gifs: {\n ...global.gifs,\n saved: savedGifs,\n },\n });\n}\n\nasync function loadStickersForEmoji(emoji: string, hash = 0) {\n let global = getGlobal();\n setGlobal({\n ...global,\n stickers: {\n ...global.stickers,\n forEmoji: {\n ...global.stickers.forEmoji,\n emoji,\n },\n },\n });\n\n const result = await callApi('fetchStickersForEmoji', { emoji, hash });\n\n global = getGlobal();\n\n if (!result || global.stickers.forEmoji.emoji !== emoji) {\n return;\n }\n\n global = updateStickersForEmoji(global, emoji, result.stickers, result.hash);\n\n setGlobal(global);\n}\n","import { addReducer, getGlobal, setGlobal } from '../../../lib/teact/teactn';\n\nimport { callApi } from '../../../api/gramjs';\nimport { ApiChat, ApiGlobalMessageSearchType } from '../../../api/types';\n\nimport {\n addChats,\n addMessages,\n addUsers,\n updateGlobalSearch,\n updateGlobalSearchFetchingStatus,\n updateGlobalSearchResults,\n} from '../../reducers';\nimport { throttle } from '../../../util/schedulers';\nimport { selectChat, selectCurrentGlobalSearchQuery } from '../../selectors';\nimport { buildCollectionByKey } from '../../../util/iteratees';\nimport { GLOBAL_SEARCH_SLICE } from '../../../config';\nimport { timestampPlusDay } from '../../../util/dateFormat';\n\nconst searchThrottled = throttle((cb) => cb(), 500, false);\n\naddReducer('setGlobalSearchQuery', (global, actions, payload) => {\n const { chatId } = global.globalSearch;\n const { query } = payload!;\n\n if (query && !chatId) {\n void searchThrottled(() => {\n searchChats(query);\n });\n }\n});\n\naddReducer('setGlobalSearchDate', (global, actions, payload) => {\n const { date } = payload!;\n const maxDate = date ? timestampPlusDay(date) : date;\n const newGlobal = updateGlobalSearch(global, {\n date,\n query: '',\n resultsByType: {\n ...global.globalSearch.resultsByType,\n text: {\n totalCount: undefined,\n foundIds: [],\n nextOffsetId: 0,\n },\n },\n });\n setGlobal(newGlobal);\n const { chatId } = global.globalSearch;\n const chat = chatId ? selectChat(global, chatId) : undefined;\n searchMessagesGlobal('', 'text', undefined, chat, maxDate, date);\n});\n\naddReducer('searchMessagesGlobal', (global, actions, payload) => {\n const {\n query, resultsByType, chatId, date,\n } = global.globalSearch;\n const maxDate = date ? timestampPlusDay(date) : date;\n const { type } = payload;\n const { nextOffsetId } = (resultsByType && resultsByType[type as ApiGlobalMessageSearchType]) || {};\n\n const chat = chatId ? selectChat(global, chatId) : undefined;\n\n searchMessagesGlobal(query, type, nextOffsetId, chat, maxDate, date);\n});\n\nasync function searchChats(query: string) {\n const result = await callApi('searchChats', { query, limit: GLOBAL_SEARCH_SLICE });\n\n let global = getGlobal();\n const currentSearchQuery = selectCurrentGlobalSearchQuery(global);\n if (!result || !currentSearchQuery || (query !== currentSearchQuery)) {\n setGlobal(updateGlobalSearchFetchingStatus(global, { chats: false }));\n return;\n }\n\n const {\n localChats, localUsers, globalChats, globalUsers,\n } = result;\n\n if (localChats.length || globalChats.length) {\n global = addChats(global, buildCollectionByKey([...localChats, ...globalChats], 'id'));\n }\n\n if (localUsers.length || globalUsers.length) {\n global = addUsers(global, buildCollectionByKey([...localUsers, ...globalUsers], 'id'));\n }\n\n global = updateGlobalSearchFetchingStatus(global, { chats: false });\n global = updateGlobalSearch(global, {\n localResults: {\n chats: localChats,\n users: localUsers,\n },\n globalResults: {\n ...global.globalSearch.globalResults,\n chats: globalChats,\n users: globalUsers,\n },\n });\n\n setGlobal(global);\n}\n\nasync function searchMessagesGlobal(\n query = '', type: ApiGlobalMessageSearchType, offsetRate?: number, chat?: ApiChat, maxDate?: number, minDate?: number,\n) {\n let result;\n\n if (chat) {\n const localResult = await callApi('searchMessagesLocal', {\n chatOrUser: chat,\n query,\n type,\n limit: GLOBAL_SEARCH_SLICE,\n offsetId: offsetRate,\n minDate,\n maxDate,\n });\n\n if (localResult) {\n const {\n messages, users, totalCount, nextOffsetId,\n } = localResult;\n\n result = {\n messages,\n users,\n chats: [],\n totalCount,\n nextRate: nextOffsetId,\n };\n }\n } else {\n result = await callApi('searchMessagesGlobal', {\n query,\n offsetRate,\n limit: GLOBAL_SEARCH_SLICE,\n type,\n maxDate,\n minDate,\n });\n }\n\n let global = getGlobal();\n const currentSearchQuery = selectCurrentGlobalSearchQuery(global);\n if (!result || (query !== '' && query !== currentSearchQuery)) {\n setGlobal(updateGlobalSearchFetchingStatus(global, { messages: false }));\n return;\n }\n\n const {\n messages, users, chats, totalCount, nextRate,\n } = result;\n\n if (chats.length) {\n global = addChats(global, buildCollectionByKey(chats, 'id'));\n }\n\n if (users.length) {\n global = addUsers(global, buildCollectionByKey(users, 'id'));\n }\n\n if (messages.length) {\n global = addMessages(global, messages);\n }\n\n global = updateGlobalSearchResults(\n global,\n messages,\n totalCount,\n type,\n nextRate,\n );\n\n setGlobal(global);\n}\n","import {\n addReducer, getGlobal, setGlobal, getDispatch,\n} from '../../../lib/teact/teactn';\n\nimport {\n ApiChat, ApiFormattedText, ApiUser, MAIN_THREAD_ID,\n} from '../../../api/types';\nimport { GlobalActions } from '../../../global/types';\n\nimport {\n CHAT_LIST_LOAD_SLICE, DEBUG, MESSAGE_LIST_SLICE,\n} from '../../../config';\nimport { callApi } from '../../../api/gramjs';\nimport { buildCollectionByKey } from '../../../util/iteratees';\nimport {\n replaceChatListIds,\n replaceChats,\n replaceUsers,\n updateUsers,\n updateChats,\n updateChatListSecondaryInfo,\n updateThreadInfos,\n replaceThreadParam,\n} from '../../reducers';\nimport {\n selectUser, selectChat, selectCurrentMessageList, selectDraft,\n} from '../../selectors';\nimport { isChatPrivate } from '../../helpers';\n\naddReducer('sync', (global, actions) => {\n void sync(actions.afterSync);\n});\n\naddReducer('afterSync', (global, actions) => {\n void afterSync(actions);\n});\n\nasync function sync(afterSyncCallback: () => void) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('>>> START SYNC');\n }\n\n await callApi('fetchCurrentUser');\n\n // This fetches only active chats and clears archived chats, which will be fetched in `afterSync`\n const savedUsers = await loadAndReplaceChats();\n await loadAndReplaceMessages(savedUsers);\n\n setGlobal({\n ...getGlobal(),\n lastSyncTime: Date.now(),\n });\n\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('>>> FINISH SYNC');\n }\n\n afterSyncCallback();\n}\n\nasync function afterSync(actions: GlobalActions) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('>>> START AFTER-SYNC');\n }\n\n actions.loadFavoriteStickers();\n\n await Promise.all([\n loadAndUpdateUsers(),\n loadAndReplaceArchivedChats(),\n ]);\n\n await callApi('fetchCurrentUser');\n\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('>>> FINISH AFTER-SYNC');\n }\n}\n\nasync function loadAndReplaceChats() {\n const result = await callApi('fetchChats', {\n limit: CHAT_LIST_LOAD_SLICE,\n withPinned: true,\n });\n if (!result) {\n return undefined;\n }\n\n let global = getGlobal();\n\n const { recentlyFoundChatIds } = global.globalSearch;\n const { userIds: contactIds } = global.contactList || {};\n const { currentUserId } = global;\n\n const savedPrivateChatIds = [\n ...(recentlyFoundChatIds || []),\n ...(contactIds || []),\n ...(currentUserId ? [currentUserId] : []),\n ];\n\n const savedUsers = savedPrivateChatIds\n .map((id) => selectUser(global, id))\n .filter<ApiUser>(Boolean as any);\n\n const savedChats = savedPrivateChatIds\n .map((id) => selectChat(global, id))\n .filter<ApiChat>(Boolean as any);\n\n const { chatId: currentChatId } = selectCurrentMessageList(global) || {};\n if (currentChatId) {\n const selectedChat = selectChat(global, currentChatId);\n if (selectedChat && !savedPrivateChatIds.includes(currentChatId)) {\n savedChats.push(selectedChat);\n }\n\n if (isChatPrivate(currentChatId)) {\n const selectedChatUser = selectUser(global, currentChatId);\n if (selectedChatUser && !savedPrivateChatIds.includes(currentChatId)) {\n savedUsers.push(selectedChatUser);\n }\n }\n }\n\n savedUsers.push(...result.users);\n savedChats.push(...result.chats);\n\n global = replaceChats(global, buildCollectionByKey(savedChats, 'id'));\n global = replaceChatListIds(global, 'active', result.chatIds);\n\n global = {\n ...global,\n chats: {\n ...global.chats,\n },\n };\n\n global = updateChatListSecondaryInfo(global, 'active', result);\n\n Object.keys(result.draftsById).map(Number).forEach((chatId) => {\n global = replaceThreadParam(\n global, chatId, MAIN_THREAD_ID, 'draft', result.draftsById[chatId],\n );\n });\n\n Object.keys(result.replyingToById).map(Number).forEach((chatId) => {\n global = replaceThreadParam(\n global, chatId, MAIN_THREAD_ID, 'replyingToId', result.replyingToById[chatId],\n );\n });\n\n setGlobal(global);\n\n if (currentChatId && !global.chats.byId[currentChatId]) {\n getDispatch().openChat({ id: undefined });\n }\n\n return savedUsers;\n}\n\nasync function loadAndReplaceArchivedChats() {\n const result = await callApi('fetchChats', {\n limit: CHAT_LIST_LOAD_SLICE,\n archived: true,\n withPinned: true,\n });\n if (!result) {\n return;\n }\n\n let global = getGlobal();\n global = updateUsers(global, buildCollectionByKey(result.users, 'id'));\n global = updateChats(global, buildCollectionByKey(result.chats, 'id'));\n global = replaceChatListIds(global, 'archived', result.chatIds);\n global = updateChatListSecondaryInfo(global, 'archived', result);\n setGlobal(global);\n}\n\nasync function loadAndReplaceMessages(savedUsers?: ApiUser[]) {\n let areMessagesLoaded = false;\n let users = savedUsers || [];\n\n let global = getGlobal();\n const { chatId: currentChatId } = selectCurrentMessageList(global) || {};\n\n // Memoize drafts\n const draftChatIds = Object.keys(global.messages.byChatId).map(Number);\n const draftsByChatId = draftChatIds.reduce<Record<number, ApiFormattedText>>((acc, chatId) => {\n const draft = selectDraft(global, chatId, MAIN_THREAD_ID);\n return draft ? { ...acc, [chatId]: draft } : acc;\n }, {});\n\n if (currentChatId) {\n const result = await loadTopMessages(global.chats.byId[currentChatId]);\n global = getGlobal();\n const { chatId: newCurrentChatId } = selectCurrentMessageList(global) || {};\n\n if (result && newCurrentChatId === currentChatId) {\n const currentMessageListInfo = global.messages.byChatId[currentChatId];\n const byId = buildCollectionByKey(result.messages, 'id');\n const listedIds = Object.keys(byId).map(Number);\n\n global = {\n ...global,\n messages: {\n ...global.messages,\n byChatId: {\n [currentChatId]: {\n byId,\n threadsById: {\n [MAIN_THREAD_ID]: {\n ...(currentMessageListInfo && currentMessageListInfo.threadsById[MAIN_THREAD_ID]),\n listedIds,\n viewportIds: listedIds,\n outlyingIds: undefined,\n },\n },\n },\n },\n },\n };\n\n global = updateChats(global, buildCollectionByKey(result.chats, 'id'));\n global = updateThreadInfos(global, currentChatId, result.threadInfos);\n\n areMessagesLoaded = true;\n users = Array.prototype.concat(users, result.users);\n }\n }\n\n if (!areMessagesLoaded) {\n global = {\n ...global,\n messages: {\n ...global.messages,\n byChatId: {},\n },\n };\n }\n\n // Restore drafts\n Object.keys(draftsByChatId).map(Number).forEach((chatId) => {\n global = replaceThreadParam(global, chatId, MAIN_THREAD_ID, 'draft', draftsByChatId[chatId]);\n });\n\n if (savedUsers) {\n global = replaceUsers(global, buildCollectionByKey(users, 'id'));\n } else if (users) {\n // If `fetchChats` has failed for some reason, we don't have saved chats, thus we can not replace\n global = updateUsers(global, buildCollectionByKey(users, 'id'));\n }\n\n setGlobal(global);\n}\n\nasync function loadAndUpdateUsers() {\n let global = getGlobal();\n const { recentlyFoundChatIds } = global.globalSearch;\n const { userIds: contactIds } = global.contactList || {};\n if (\n (!contactIds || !contactIds.length)\n && (!recentlyFoundChatIds || !recentlyFoundChatIds.length)\n ) {\n return;\n }\n\n const users = [\n ...(recentlyFoundChatIds || []),\n ...(contactIds || []),\n ].map((id) => selectUser(global, id)).filter<ApiUser>(Boolean as any);\n\n const updatedUsers = await callApi('fetchUsers', { users });\n if (!updatedUsers) {\n return;\n }\n\n global = getGlobal();\n global = updateUsers(global, buildCollectionByKey(updatedUsers, 'id'));\n setGlobal(global);\n}\n\nfunction loadTopMessages(chat: ApiChat) {\n return callApi('fetchMessages', {\n chat,\n threadId: MAIN_THREAD_ID,\n offsetId: chat.lastReadInboxMessageId,\n addOffset: -(Math.round(MESSAGE_LIST_SLICE / 2) + 1),\n limit: MESSAGE_LIST_SLICE,\n });\n}\n","import {\n addReducer, getDispatch, getGlobal, setGlobal,\n} from '../../../lib/teact/teactn';\n\nimport { ApiChat, ApiUser, MAIN_THREAD_ID } from '../../../api/types';\n\nimport { MESSAGE_SEARCH_SLICE, SHARED_MEDIA_SLICE } from '../../../config';\nimport { callApi } from '../../../api/gramjs';\nimport {\n selectCurrentTextSearch,\n selectCurrentMediaSearchPeerId,\n selectCurrentMediaSearch, selectCurrentMessageList, selectChat, selectThreadInfo,\n} from '../../selectors';\nimport { buildCollectionByKey } from '../../../util/iteratees';\nimport {\n addChatMessagesById,\n addUsers,\n updateLocalMediaSearchResults,\n updateLocalTextSearchResults,\n} from '../../reducers';\nimport { SharedMediaType } from '../../../types';\n\naddReducer('searchTextMessagesLocal', (global) => {\n const { chatId, threadId } = selectCurrentMessageList(global) || {};\n const chat = chatId ? selectChat(global, chatId) : undefined;\n const currentSearch = selectCurrentTextSearch(global);\n if (!chat || !currentSearch || !threadId) {\n return;\n }\n\n const { query, results } = currentSearch;\n const offsetId = results ? results.nextOffsetId : undefined;\n\n let topMessageId: number | undefined;\n if (threadId !== MAIN_THREAD_ID) {\n const threadInfo = selectThreadInfo(global, chatId!, threadId);\n topMessageId = threadInfo ? threadInfo.topMessageId : undefined;\n }\n\n void searchTextMessages(chat, threadId, topMessageId, query, offsetId);\n});\n\naddReducer('searchMediaMessagesLocal', (global) => {\n const peerId = selectCurrentMediaSearchPeerId(global);\n const chatOrUser = peerId\n ? global.users.byId[peerId] || global.chats.byId[peerId]\n : undefined;\n const currentSearch = selectCurrentMediaSearch(global);\n\n if (!chatOrUser || !currentSearch) {\n return;\n }\n\n const { currentType: type, resultsByType } = currentSearch;\n const currentResults = type && resultsByType && resultsByType[type];\n const offsetId = currentResults ? currentResults.nextOffsetId : undefined;\n\n if (!type) {\n return;\n }\n\n void searchSharedMedia(chatOrUser, type, offsetId);\n});\n\naddReducer('searchMessagesByDate', (global, actions, payload) => {\n const { timestamp } = payload!;\n\n const { chatId } = selectCurrentMessageList(global) || {};\n if (!chatId) {\n return;\n }\n\n const chat = selectChat(global, chatId);\n if (!chat) {\n return;\n }\n\n void searchMessagesByDate(chat, timestamp);\n});\n\nasync function searchTextMessages(\n chatOrUser: ApiChat,\n threadId: number,\n topMessageId?: number,\n query?: string,\n offsetId?: number,\n) {\n const result = await callApi('searchMessagesLocal', {\n chatOrUser,\n type: 'text',\n query,\n topMessageId,\n limit: MESSAGE_SEARCH_SLICE,\n offsetId,\n });\n\n if (!result) {\n return;\n }\n\n const {\n messages, users, totalCount, nextOffsetId,\n } = result;\n\n const byId = buildCollectionByKey(messages, 'id');\n const newFoundIds = Object.keys(byId).map(Number);\n\n let global = getGlobal();\n\n const currentSearch = selectCurrentTextSearch(global);\n if (!currentSearch || (query && query !== currentSearch.query)) {\n return;\n }\n\n global = addChatMessagesById(global, chatOrUser.id, byId);\n global = addUsers(global, buildCollectionByKey(users, 'id'));\n global = updateLocalTextSearchResults(global, chatOrUser.id, threadId, newFoundIds, totalCount, nextOffsetId);\n setGlobal(global);\n}\n\nasync function searchSharedMedia(\n chatOrUser: ApiChat | ApiUser,\n type: SharedMediaType,\n offsetId?: number,\n) {\n const result = await callApi('searchMessagesLocal', {\n chatOrUser,\n type,\n limit: SHARED_MEDIA_SLICE,\n offsetId,\n });\n\n if (!result) {\n return;\n }\n\n const {\n messages, users, totalCount, nextOffsetId,\n } = result;\n\n const byId = buildCollectionByKey(messages, 'id');\n const newFoundIds = Object.keys(byId).map(Number);\n\n let global = getGlobal();\n\n const currentSearch = selectCurrentMediaSearch(global);\n if (!currentSearch) {\n return;\n }\n\n global = addChatMessagesById(global, chatOrUser.id, byId);\n global = addUsers(global, buildCollectionByKey(users, 'id'));\n global = updateLocalMediaSearchResults(global, chatOrUser.id, type, newFoundIds, totalCount, nextOffsetId);\n setGlobal(global);\n}\n\n/**\n * @param timestamp start of target date in seconds\n */\nasync function searchMessagesByDate(chat: ApiChat, timestamp: number) {\n const messageId = await callApi('findFirstMessageIdAfterDate', {\n chat,\n timestamp,\n });\n\n if (!messageId) {\n return;\n }\n\n getDispatch().focusMessage({\n chatId: chat.id,\n messageId,\n });\n}\n","import { addReducer, getGlobal, setGlobal } from '../../../lib/teact/teactn';\n\nimport { ManagementProgress } from '../../../types';\nimport { callApi } from '../../../api/gramjs';\nimport { updateManagement, updateManagementProgress } from '../../reducers';\nimport { selectChat, selectCurrentMessageList } from '../../selectors';\nimport { isChatBasicGroup } from '../../helpers';\n\naddReducer('checkPublicLink', (global, actions, payload) => {\n const { chatId } = selectCurrentMessageList(global) || {};\n if (!chatId) {\n return;\n }\n\n // No need to check the username if already in progress\n if (global.management.progress === ManagementProgress.InProgress) {\n return;\n }\n\n const { username } = payload!;\n\n (async () => {\n global = updateManagementProgress(global, ManagementProgress.InProgress);\n global = updateManagement(global, chatId, { isUsernameAvailable: undefined });\n setGlobal(global);\n\n const isUsernameAvailable = await callApi('checkChatUsername', { username })!;\n\n global = getGlobal();\n global = updateManagementProgress(\n global, isUsernameAvailable ? ManagementProgress.Complete : ManagementProgress.Error,\n );\n global = updateManagement(global, chatId, { isUsernameAvailable });\n setGlobal(global);\n })();\n});\n\naddReducer('updatePublicLink', (global, actions, payload) => {\n const { chatId } = selectCurrentMessageList(global) || {};\n let chat = chatId && selectChat(global, chatId);\n if (!chatId || !chat) {\n return;\n }\n\n const { username } = payload!;\n\n (async () => {\n global = updateManagementProgress(global, ManagementProgress.InProgress);\n setGlobal(global);\n\n if (isChatBasicGroup(chat)) {\n chat = await callApi('migrateChat', chat);\n\n if (!chat) {\n return;\n }\n\n actions.openChat({ id: chat.id });\n }\n\n const result = await callApi('setChatUsername', { chat, username });\n\n global = getGlobal();\n global = updateManagementProgress(global, result ? ManagementProgress.Complete : ManagementProgress.Error);\n global = updateManagement(global, chatId, { isUsernameAvailable: undefined });\n setGlobal(global);\n })();\n});\n\naddReducer('updatePrivateLink', (global) => {\n const { chatId } = selectCurrentMessageList(global) || {};\n const chat = chatId && selectChat(global, chatId);\n if (!chatId || !chat) {\n return;\n }\n\n callApi('updatePrivateLink', { chat });\n});\n","import {\n addReducer, getDispatch, getGlobal, setGlobal,\n} from '../../../lib/teact/teactn';\n\nimport { ApiUser } from '../../../api/types';\nimport { ManagementProgress } from '../../../types';\n\nimport { debounce } from '../../../util/schedulers';\nimport { buildCollectionByKey } from '../../../util/iteratees';\nimport { callApi } from '../../../api/gramjs';\nimport { selectUser } from '../../selectors';\nimport {\n addChats, addUsers, updateManagementProgress, updateUser, updateUsers,\n} from '../../reducers';\n\nconst runDebouncedForFetchFullUser = debounce((cb) => cb(), 500, false, true);\nconst TOP_PEERS_REQUEST_COOLDOWN = 60000; // 1 min\n\naddReducer('loadFullUser', (global, actions, payload) => {\n const { userId } = payload!;\n const user = selectUser(global, userId);\n if (!user) {\n return;\n }\n\n const { id, accessHash } = user;\n\n runDebouncedForFetchFullUser(() => callApi('fetchFullUser', { id, accessHash }));\n});\n\naddReducer('loadUser', (global, actions, payload) => {\n const { userId } = payload!;\n const user = selectUser(global, userId);\n if (!user) {\n return;\n }\n\n (async () => {\n const updatedUsers = await callApi('fetchUsers', { users: [user] });\n if (!updatedUsers) {\n return;\n }\n\n global = getGlobal();\n global = updateUsers(global, buildCollectionByKey(updatedUsers, 'id'));\n setGlobal(global);\n })();\n});\n\naddReducer('loadTopUsers', (global) => {\n const { hash, lastRequestedAt } = global.topPeers;\n\n if (!lastRequestedAt || Date.now() - lastRequestedAt > TOP_PEERS_REQUEST_COOLDOWN) {\n void loadTopUsers(hash);\n }\n});\n\naddReducer('loadContactList', (global) => {\n const { hash } = global.contactList || {};\n void loadContactList(hash);\n});\n\naddReducer('loadCurrentUser', () => {\n void callApi('fetchCurrentUser');\n});\n\naddReducer('updateContact', (global, actions, payload) => {\n const {\n userId, isMuted, firstName, lastName,\n } = payload!;\n\n void updateContact(userId, isMuted, firstName, lastName);\n});\n\naddReducer('deleteUser', (global, actions, payload) => {\n const { userId } = payload!;\n\n void deleteUser(userId);\n});\n\nasync function loadTopUsers(usersHash?: number) {\n const result = await callApi('fetchTopUsers', { hash: usersHash });\n if (!result) {\n return;\n }\n\n const { hash, ids, users } = result;\n\n let global = getGlobal();\n global = addUsers(global, buildCollectionByKey(users, 'id'));\n global = {\n ...global,\n topPeers: {\n ...global.topPeers,\n hash,\n userIds: ids,\n lastRequestedAt: Date.now(),\n },\n };\n setGlobal(global);\n}\n\nasync function loadContactList(hash?: number) {\n const contactList = await callApi('fetchContactList', { hash });\n if (!contactList) {\n return;\n }\n\n let global = addUsers(getGlobal(), buildCollectionByKey(contactList.users, 'id'));\n global = addChats(global, buildCollectionByKey(contactList.chats, 'id'));\n\n // Sort contact list by Last Name (or First Name), with latin names being placed first\n const getCompareString = (user: ApiUser) => (user.lastName || user.firstName || '');\n const collator = new Intl.Collator('en-US');\n\n const sortedUsers = contactList.users.sort((a, b) => (\n collator.compare(getCompareString(a), getCompareString(b))\n )).filter((user) => !user.isSelf);\n\n setGlobal({\n ...global,\n contactList: {\n hash: contactList.hash,\n userIds: sortedUsers.map((user) => user.id),\n },\n });\n}\n\nasync function updateContact(\n userId: number,\n isMuted: boolean,\n firstName: string,\n lastName?: string,\n) {\n const global = getGlobal();\n const user = selectUser(global, userId);\n if (!user) {\n return;\n }\n\n getDispatch().updateChatMutedState({ chatId: userId, isMuted });\n\n setGlobal(updateManagementProgress(getGlobal(), ManagementProgress.InProgress));\n\n const result = await callApi('updateContact', { phone: user.phoneNumber, firstName, lastName });\n\n if (result) {\n setGlobal(updateUser(\n getGlobal(),\n user.id,\n {\n firstName,\n lastName,\n },\n ));\n }\n\n setGlobal(updateManagementProgress(getGlobal(), ManagementProgress.Complete));\n}\n\nasync function deleteUser(userId: number) {\n const global = getGlobal();\n const user = selectUser(global, userId);\n\n if (!user) {\n return;\n }\n\n const { id, accessHash } = user;\n\n await callApi('deleteUser', { id, accessHash });\n}\n","import { addReducer, getGlobal, setGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalState } from '../../../global/types';\nimport {\n ApiPrivacyKey, PrivacyVisibility, ProfileEditProgress, IInputPrivacyRules, IInputPrivacyContact,\n UPLOADING_WALLPAPER_SLUG,\n} from '../../../types';\n\nimport { callApi } from '../../../api/gramjs';\nimport { buildCollectionByKey } from '../../../util/iteratees';\nimport { selectUser } from '../../selectors';\nimport {\n addUsers, addBlockedContact, updateChats, updateUser, removeBlockedContact, replaceSettings, updateNotifySettings,\n} from '../../reducers';\nimport { isChatPrivate } from '../../helpers';\n\naddReducer('updateProfile', (global, actions, payload) => {\n const {\n photo, firstName, lastName, bio: about, username,\n } = payload!;\n\n (async () => {\n const { currentUserId } = global;\n if (!currentUserId) {\n return;\n }\n\n setGlobal({\n ...getGlobal(),\n profileEdit: {\n progress: ProfileEditProgress.InProgress,\n },\n });\n\n if (photo) {\n await callApi('updateProfilePhoto', photo);\n }\n\n if (firstName || lastName || about) {\n const result = await callApi('updateProfile', { firstName, lastName, about });\n if (result) {\n global = getGlobal();\n const currentUser = currentUserId && selectUser(global, currentUserId);\n\n if (currentUser) {\n setGlobal(updateUser(\n global,\n currentUser.id,\n {\n firstName,\n lastName,\n fullInfo: {\n ...currentUser.fullInfo,\n bio: about,\n },\n },\n ));\n }\n }\n }\n\n if (username) {\n const result = await callApi('updateUsername', username);\n if (result && currentUserId) {\n setGlobal(updateUser(getGlobal(), currentUserId, { username }));\n }\n }\n\n setGlobal({\n ...getGlobal(),\n profileEdit: {\n progress: ProfileEditProgress.Complete,\n },\n });\n })();\n});\n\naddReducer('checkUsername', (global, actions, payload) => {\n const { username } = payload!;\n\n (async () => {\n // No need to check the username if profile update is already in progress\n if (global.profileEdit && global.profileEdit.progress === ProfileEditProgress.InProgress) {\n return;\n }\n\n setGlobal({\n ...global,\n profileEdit: {\n progress: global.profileEdit ? global.profileEdit.progress : ProfileEditProgress.Idle,\n isUsernameAvailable: undefined,\n },\n });\n\n const isUsernameAvailable = await callApi('checkUsername', username);\n\n global = getGlobal();\n setGlobal({\n ...global,\n profileEdit: {\n ...global.profileEdit!,\n isUsernameAvailable,\n },\n });\n })();\n});\n\naddReducer('loadWallpapers', () => {\n (async () => {\n const result = await callApi('fetchWallpapers', 0);\n if (!result) {\n return;\n }\n\n const global = getGlobal();\n setGlobal({\n ...global,\n settings: {\n ...global.settings,\n loadedWallpapers: result.wallpapers,\n },\n });\n })();\n});\n\naddReducer('uploadWallpaper', (global, actions, payload) => {\n const file = payload;\n const previewBlobUrl = URL.createObjectURL(file);\n\n setGlobal({\n ...global,\n settings: {\n ...global.settings,\n loadedWallpapers: [\n {\n slug: UPLOADING_WALLPAPER_SLUG,\n document: {\n fileName: '',\n size: file.size,\n mimeType: file.type,\n previewBlobUrl,\n },\n },\n ...(global.settings.loadedWallpapers || []),\n ],\n },\n });\n\n (async () => {\n const result = await callApi('uploadWallpaper', file);\n if (!result) {\n return;\n }\n\n const { wallpaper } = result;\n\n global = getGlobal();\n if (!global.settings.loadedWallpapers) {\n return;\n }\n\n const firstWallpaper = global.settings.loadedWallpapers[0];\n if (!firstWallpaper || firstWallpaper.slug !== UPLOADING_WALLPAPER_SLUG) {\n return;\n }\n\n const withLocalMedia = {\n ...wallpaper,\n document: {\n ...wallpaper.document,\n previewBlobUrl,\n },\n };\n\n setGlobal({\n ...global,\n settings: {\n ...global.settings,\n loadedWallpapers: [\n withLocalMedia,\n ...global.settings.loadedWallpapers.slice(1),\n ],\n },\n });\n })();\n});\n\naddReducer('loadBlockedContacts', () => {\n (async () => {\n const result = await callApi('fetchBlockedContacts');\n\n if (!result) {\n return;\n }\n\n let newGlobal = getGlobal();\n\n if (result.users && result.users.length) {\n newGlobal = addUsers(newGlobal, buildCollectionByKey(result.users, 'id'));\n }\n if (result.chats && result.chats.length) {\n newGlobal = updateChats(newGlobal, buildCollectionByKey(result.chats, 'id'));\n }\n\n newGlobal = {\n ...newGlobal,\n blocked: {\n ...newGlobal.blocked,\n ids: [...(newGlobal.blocked.ids || []), ...result.blockedIds],\n totalCount: result.totalCount,\n },\n };\n\n setGlobal(newGlobal);\n })();\n});\n\naddReducer('blockContact', (global, actions, payload) => {\n const { contactId } = payload!;\n\n (async () => {\n const result = await callApi('blockContact', contactId);\n if (!result) {\n return;\n }\n\n const newGlobal = getGlobal();\n\n setGlobal(addBlockedContact(newGlobal, contactId));\n })();\n});\n\naddReducer('unblockContact', (global, actions, payload) => {\n const { contactId } = payload!;\n let accessHash: string | undefined;\n const isPrivate = isChatPrivate(contactId);\n\n if (isPrivate) {\n const user = selectUser(global, contactId);\n if (!user) {\n return;\n }\n\n accessHash = user.accessHash;\n }\n\n (async () => {\n const result = await callApi('unblockContact', contactId, accessHash);\n if (!result) {\n return;\n }\n\n const newGlobal = getGlobal();\n\n setGlobal(removeBlockedContact(newGlobal, contactId));\n })();\n});\n\naddReducer('loadAuthorizations', () => {\n (async () => {\n const result = await callApi('fetchAuthorizations');\n if (!result) {\n return;\n }\n\n setGlobal({\n ...getGlobal(),\n activeSessions: result,\n });\n })();\n});\n\naddReducer('terminateAuthorization', (global, actions, payload) => {\n const { hash } = payload!;\n\n (async () => {\n const result = await callApi('terminateAuthorization', hash);\n if (!result) {\n return;\n }\n\n const newGlobal = getGlobal();\n\n setGlobal({\n ...newGlobal,\n activeSessions: newGlobal.activeSessions.filter((session) => session.hash !== hash),\n });\n })();\n});\n\naddReducer('terminateAllAuthorizations', () => {\n (async () => {\n const result = await callApi('terminateAllAuthorizations');\n if (!result) {\n return;\n }\n\n const global = getGlobal();\n\n setGlobal({\n ...global,\n activeSessions: global.activeSessions.filter((session) => session.isCurrent),\n });\n })();\n});\n\naddReducer('loadNotificationsSettings', () => {\n (async () => {\n const result = await callApi('loadNotificationsSettings');\n if (!result) {\n return;\n }\n\n setGlobal(replaceSettings(getGlobal(), result));\n })();\n});\n\naddReducer('updateNotificationSettings', (global, actions, payload) => {\n const { peerType, isSilent, isShowPreviews } = payload!;\n\n (async () => {\n const result = await callApi('updateNotificationSettings', peerType, { isSilent, isShowPreviews });\n\n if (!result) {\n return;\n }\n\n setGlobal(updateNotifySettings(getGlobal(), peerType, isSilent, isShowPreviews));\n })();\n});\n\naddReducer('updateContactSignUpNotification', (global, actions, payload) => {\n const { isSilent } = payload!;\n\n (async () => {\n const result = await callApi('updateContactSignUpNotification', isSilent);\n if (!result) {\n return;\n }\n\n setGlobal(replaceSettings(getGlobal(), { hasContactJoinedNotifications: !isSilent }));\n })();\n});\n\naddReducer('loadLanguages', () => {\n (async () => {\n const result = await callApi('fetchLanguages');\n if (!result) {\n return;\n }\n\n setGlobal(replaceSettings(getGlobal(), { languages: result }));\n })();\n});\n\naddReducer('loadPrivacySettings', () => {\n (async () => {\n const [\n phoneNumberSettings, lastSeenSettings, profilePhotoSettings, forwardsSettings, chatInviteSettings,\n ] = await Promise.all([\n callApi('fetchPrivacySettings', 'phoneNumber'),\n callApi('fetchPrivacySettings', 'lastSeen'),\n callApi('fetchPrivacySettings', 'profilePhoto'),\n callApi('fetchPrivacySettings', 'forwards'),\n callApi('fetchPrivacySettings', 'chatInvite'),\n ]);\n\n if (\n !phoneNumberSettings || !lastSeenSettings || !profilePhotoSettings || !forwardsSettings || !chatInviteSettings\n ) {\n return;\n }\n\n const global = getGlobal();\n\n global.settings.privacy.phoneNumber = phoneNumberSettings;\n global.settings.privacy.lastSeen = lastSeenSettings;\n global.settings.privacy.profilePhoto = profilePhotoSettings;\n global.settings.privacy.forwards = forwardsSettings;\n global.settings.privacy.chatInvite = chatInviteSettings;\n\n setGlobal(global);\n })();\n});\n\naddReducer('setPrivacyVisibility', (global, actions, payload) => {\n const { privacyKey, visibility } = payload!;\n\n const {\n privacy: { [privacyKey as ApiPrivacyKey]: settings },\n } = global.settings;\n\n if (!settings) {\n return;\n }\n\n const rules = buildInputPrivacyRules(global, {\n visibility,\n allowedIds: [...settings.allowUserIds, ...settings.allowChatIds],\n deniedIds: [...settings.blockUserIds, ...settings.blockChatIds],\n });\n\n (async () => {\n const result = await callApi('setPrivacySettings', privacyKey, rules);\n\n if (result) {\n const newGlobal = getGlobal();\n\n newGlobal.settings.privacy[privacyKey as ApiPrivacyKey] = result;\n\n setGlobal(newGlobal);\n }\n })();\n});\n\naddReducer('setPrivacySettings', (global, actions, payload) => {\n const { privacyKey, isAllowList, contactsIds } = payload!;\n const {\n privacy: { [privacyKey as ApiPrivacyKey]: settings },\n } = global.settings;\n\n if (!settings) {\n return;\n }\n\n const rules = buildInputPrivacyRules(global, {\n visibility: settings.visibility,\n allowedIds: isAllowList ? contactsIds : [...settings.allowUserIds, ...settings.allowChatIds],\n deniedIds: !isAllowList ? contactsIds : [...settings.blockUserIds, ...settings.blockChatIds],\n });\n\n (async () => {\n const result = await callApi('setPrivacySettings', privacyKey, rules);\n\n if (result) {\n const newGlobal = getGlobal();\n\n newGlobal.settings.privacy[privacyKey as ApiPrivacyKey] = result;\n\n setGlobal(newGlobal);\n }\n })();\n});\n\nfunction buildInputPrivacyRules(global: GlobalState, {\n visibility,\n allowedIds,\n deniedIds,\n}: {\n visibility: PrivacyVisibility;\n allowedIds: number[];\n deniedIds: number[];\n}): IInputPrivacyRules {\n const {\n users: { byId: usersById },\n chats: { byId: chatsById },\n } = global;\n\n const rules: IInputPrivacyRules = {\n visibility,\n };\n let users: IInputPrivacyContact[];\n let chats: IInputPrivacyContact[];\n\n const collectUsers = (userId: number) => {\n if (!isChatPrivate(userId)) {\n return undefined;\n }\n const { id, accessHash } = usersById[userId] || {};\n if (!id) {\n return undefined;\n }\n\n return { id, accessHash };\n };\n\n const collectChats = (userId: number) => {\n if (isChatPrivate(userId)) {\n return undefined;\n }\n const chat = chatsById[userId];\n\n return chat ? { id: chat.id } : undefined;\n };\n\n if (visibility === 'contacts' || visibility === 'nobody') {\n users = allowedIds.map(collectUsers).filter(Boolean) as IInputPrivacyContact[];\n chats = allowedIds.map(collectChats).filter(Boolean) as IInputPrivacyContact[];\n\n if (users.length > 0) {\n rules.allowedUsers = users;\n }\n if (chats.length > 0) {\n rules.allowedChats = chats;\n }\n }\n\n if (visibility === 'everybody' || visibility === 'contacts') {\n users = deniedIds.map(collectUsers).filter(Boolean) as IInputPrivacyContact[];\n chats = deniedIds.map(collectChats).filter(Boolean) as IInputPrivacyContact[];\n\n if (users.length > 0) {\n rules.blockedUsers = users;\n }\n if (chats.length > 0) {\n rules.blockedChats = chats;\n }\n }\n\n return rules;\n}\n","import { addReducer, getDispatch } from '../../../lib/teact/teactn';\n\nimport { ApiChat } from '../../../api/types';\n\nimport { RE_TME_INVITE_LINK, RE_TME_LINK } from '../../../config';\nimport { callApi } from '../../../api/gramjs';\nimport { selectChatMessage, selectCurrentChat } from '../../selectors';\n\naddReducer('clickInlineButton', (global, actions, payload) => {\n const { button } = payload;\n\n switch (button.type) {\n case 'command':\n actions.sendBotCommand({ command: button.value });\n break;\n case 'url':\n if (button.value.match(RE_TME_INVITE_LINK) || button.value.match(RE_TME_LINK)) {\n actions.openTelegramLink({ url: button.value });\n } else {\n window.open(button.value);\n }\n break;\n case 'callback': {\n const chat = selectCurrentChat(global);\n if (!chat) {\n return;\n }\n\n void answerCallbackButton(chat, button.messageId, button.value);\n break;\n }\n case 'requestPoll':\n actions.openPollModal();\n break;\n case 'buy': {\n const chat = selectCurrentChat(global);\n const { messageId, value } = button;\n if (!chat) {\n return;\n }\n\n if (value) {\n actions.getReceipt({ receiptMessageId: value, chatId: chat.id, messageId });\n } else {\n actions.getPaymentForm({ messageId });\n actions.setInvoiceMessageInfo(selectChatMessage(global, chat.id, messageId));\n actions.openPaymentModal({ messageId });\n }\n break;\n }\n }\n});\n\naddReducer('sendBotCommand', (global, actions, payload) => {\n const { command } = payload;\n const { currentUserId } = global;\n const chat = selectCurrentChat(global);\n if (!currentUserId || !chat) {\n return;\n }\n\n void sendBotCommand(chat, currentUserId, command);\n});\n\nasync function sendBotCommand(chat: ApiChat, currentUserId: number, command: string) {\n await callApi('sendMessage', {\n chat,\n text: command,\n });\n}\n\nasync function answerCallbackButton(chat: ApiChat, messageId: number, data: string) {\n const result = await callApi('answerCallbackButton', {\n chatId: chat.id,\n accessHash: chat.accessHash,\n messageId,\n data,\n });\n\n if (!result || !result.message) {\n return;\n }\n\n const { message, alert: isError } = result;\n\n if (isError) {\n getDispatch().showError({ error: { message } });\n } else {\n getDispatch().showNotification({ message });\n }\n}\n","import { addReducer, getGlobal, setGlobal } from '../../../lib/teact/teactn';\n\nimport { callApi } from '../../../api/gramjs';\nimport { replaceSettings, updateTwoFaSettings } from '../../reducers';\n\naddReducer('loadPasswordInfo', () => {\n (async () => {\n const result = await callApi('getPasswordInfo');\n if (!result) {\n return;\n }\n\n let global = getGlobal();\n global = replaceSettings(global, { hasPassword: result.hasPassword });\n global = updateTwoFaSettings(global, { hint: result.hint });\n setGlobal(global);\n })();\n});\n\naddReducer('checkPassword', (global, actions, payload) => {\n const { currentPassword, onSuccess } = payload;\n\n setGlobal(updateTwoFaSettings(global, { isLoading: true, error: undefined }));\n\n (async () => {\n const isSuccess = await callApi('checkPassword', currentPassword);\n\n setGlobal(updateTwoFaSettings(getGlobal(), { isLoading: false }));\n\n if (isSuccess) {\n onSuccess();\n }\n })();\n});\n\naddReducer('clearPassword', (global, actions, payload) => {\n const { currentPassword, onSuccess } = payload;\n\n setGlobal(updateTwoFaSettings(global, { isLoading: true, error: undefined }));\n\n (async () => {\n const isSuccess = await callApi('clearPassword', currentPassword);\n\n setGlobal(updateTwoFaSettings(getGlobal(), { isLoading: false }));\n\n if (isSuccess) {\n onSuccess();\n }\n })();\n});\n\naddReducer('updatePassword', (global, actions, payload) => {\n const {\n currentPassword, password, hint, email, onSuccess,\n } = payload;\n\n setGlobal(updateTwoFaSettings(global, { isLoading: true, error: undefined }));\n\n (async () => {\n const isSuccess = await callApi('updatePassword', currentPassword, password, hint, email);\n\n setGlobal(updateTwoFaSettings(getGlobal(), { isLoading: false }));\n\n if (isSuccess) {\n onSuccess();\n }\n })();\n});\n\naddReducer('updateRecoveryEmail', (global, actions, payload) => {\n const {\n currentPassword, email, onSuccess,\n } = payload;\n\n setGlobal(updateTwoFaSettings(global, { isLoading: true, error: undefined }));\n\n (async () => {\n const isSuccess = await callApi('updateRecoveryEmail', currentPassword, email);\n\n setGlobal(updateTwoFaSettings(getGlobal(), { isLoading: false, waitingEmailCodeLength: undefined }));\n\n if (isSuccess) {\n onSuccess();\n }\n })();\n});\n\naddReducer('provideTwoFaEmailCode', (global, actions, payload) => {\n const { code } = payload;\n\n void callApi('provideRecoveryEmailCode', code);\n});\n\naddReducer('clearTwoFaError', (global) => {\n return updateTwoFaSettings(global, { error: undefined });\n});\n","import { addReducer, getGlobal, setGlobal } from '../../../lib/teact/teactn';\n\nimport { PaymentStep } from '../../../types/index';\nimport { callApi } from '../../../api/gramjs';\nimport {\n selectPaymentMessageId,\n selectPaymentRequestId,\n selectProviderPublishableKey,\n selectStripeCredentials,\n selectChatMessage,\n} from '../../selectors';\n\nimport { getStripeError } from '../../helpers/payments';\nimport { buildQueryString } from '../../../util/requestQuery';\n\nimport {\n updateShippingOptions,\n setPaymentStep,\n setRequestInfoId,\n setPaymentForm,\n setStripeCardInfo,\n setInvoiceMessageInfo,\n setReceipt,\n clearPayment,\n closeInvoice,\n} from '../../reducers';\n\naddReducer('validateRequestedInfo', (global, actions, payload) => {\n const { requestInfo, saveInfo } = payload;\n const messageId = selectPaymentMessageId(global);\n if (!messageId) {\n return;\n }\n validateRequestedInfo(messageId, requestInfo, saveInfo);\n});\n\nasync function validateRequestedInfo(messageId: number, requestInfo: any, shouldSave?: true) {\n const result = await callApi('validateRequestedInfo', { messageId, requestInfo, shouldSave });\n if (!result) {\n return;\n }\n const { id, shippingOptions } = result;\n if (!id) {\n return;\n }\n let global = setRequestInfoId(getGlobal(), id);\n if (shippingOptions) {\n global = updateShippingOptions(global, shippingOptions);\n global = setPaymentStep(global, PaymentStep.Shipping);\n } else {\n global = setPaymentStep(global, PaymentStep.PaymentInfo);\n }\n setGlobal(global);\n}\n\naddReducer('getPaymentForm', (global, actions, payload) => {\n const { messageId } = payload;\n if (!messageId) {\n return;\n }\n getPaymentForm(messageId);\n});\n\n\nasync function getPaymentForm(messageId: number) {\n const result = await callApi('getPaymentForm', { messageId });\n if (!result) {\n return;\n }\n let global = setPaymentForm(getGlobal(), result);\n let step = PaymentStep.PaymentInfo;\n if (global.payment.invoice\n && (global.payment.invoice.shippingAddressRequested\n || global.payment.invoice.nameRequested\n || global.payment.invoice.phoneRequested\n || global.payment.invoice.emailRequested)) {\n step = PaymentStep.ShippingInfo;\n }\n global = setPaymentStep(global, step);\n setGlobal(global);\n}\n\naddReducer('getReceipt', (global, actions, payload) => {\n const { receiptMessageId, chatId, messageId } = payload;\n if (!messageId || !receiptMessageId || !chatId) {\n return;\n }\n getReceipt(messageId, receiptMessageId, chatId);\n});\n\nasync function getReceipt(messageId: number, receiptMessageId: number, chatId: number) {\n const result = await callApi('getReceipt', receiptMessageId);\n if (!result) {\n return;\n }\n let global = getGlobal();\n const message = selectChatMessage(global, chatId, messageId);\n global = setReceipt(global, result, message);\n setGlobal(global);\n}\n\naddReducer('clearPaymentError', (global) => {\n setGlobal({\n ...global,\n payment: {\n ...global.payment,\n error: undefined,\n },\n });\n});\n\naddReducer('clearReceipt', (global) => {\n setGlobal({\n ...global,\n payment: {\n ...global.payment,\n receipt: undefined,\n },\n });\n});\n\naddReducer('sendCredentialsInfo', (global, actions, payload) => {\n const publishableKey = selectProviderPublishableKey(global);\n if (!publishableKey) {\n return;\n }\n const { credentials } = payload;\n const { data } = credentials;\n sendStipeCredentials(data, publishableKey);\n});\n\naddReducer('sendPaymentForm', (global, actions, payload) => {\n const { shippingOptionId, saveCredentials } = payload;\n const messageId = selectPaymentMessageId(global);\n const requestInfoId = selectPaymentRequestId(global);\n const publishableKey = selectProviderPublishableKey(global);\n const stripeCredentials = selectStripeCredentials(global);\n if (!messageId || !publishableKey) {\n return;\n }\n sendPaymentForm(messageId, {\n save: saveCredentials,\n data: stripeCredentials,\n }, requestInfoId, shippingOptionId);\n});\n\nasync function sendStipeCredentials(data: {\n cardNumber: string;\n cardholder?: string;\n expiryMonth: string;\n expiryYear: string;\n cvv: string;\n country: string;\n zip: string;\n},\npublishableKey: string) {\n const query = buildQueryString({\n 'card[number]': data.cardNumber,\n 'card[exp_month]': data.expiryMonth,\n 'card[exp_year]': data.expiryYear,\n 'card[cvc]': data.cvv,\n 'card[address_zip]': data.zip,\n 'card[address_country]': data.country,\n });\n\n const response = await fetch(`https://api.stripe.com/v1/tokens${query}`, {\n method: 'POST',\n credentials: 'same-origin',\n headers: {\n 'Content-Type': 'application/x-www-form-urlencoded',\n Authorization: `Bearer ${publishableKey}`,\n },\n });\n const result = await response.json();\n if (result.error) {\n const error = getStripeError(result.error);\n const global = getGlobal();\n setGlobal({\n ...global,\n payment: {\n ...global.payment,\n error: {\n ...error,\n },\n },\n });\n return;\n }\n let global = setStripeCardInfo(getGlobal(), {\n type: result.type,\n id: result.id,\n });\n global = setPaymentStep(global, PaymentStep.Checkout);\n setGlobal(global);\n}\n\nasync function sendPaymentForm(\n messageId: number,\n credentials: any,\n requestedInfoId?: string,\n shippingOptionId?: string,\n) {\n const result = await callApi('sendPaymentForm', {\n messageId, credentials, requestedInfoId, shippingOptionId,\n });\n if (result) {\n const global = clearPayment(getGlobal());\n setGlobal(closeInvoice(global));\n }\n}\n\naddReducer('setPaymentStep', (global, actions, payload = {}) => {\n return setPaymentStep(global, payload.step || PaymentStep.ShippingInfo);\n});\n\naddReducer('setInvoiceMessageInfo', (global, actions, payload) => {\n return setInvoiceMessageInfo(global, payload);\n});\n","export function buildQueryString(data: Record<string, string>) {\n const query = Object.keys(data).map((k) => `${k}=${data[k]}`).join('&');\n return query.length > 0 ? `?${query}` : '';\n}\n","import { addReducer, getGlobal, setGlobal } from '../../../lib/teact/teactn';\n\nimport { ApiUpdate } from '../../../api/types';\n\nimport { ARCHIVED_FOLDER_ID, MAX_ACTIVE_PINNED_CHATS } from '../../../config';\nimport { pick } from '../../../util/iteratees';\nimport {\n updateChat,\n replaceChatListIds,\n updateChatListIds,\n updateChatListType,\n} from '../../reducers';\nimport {\n selectChat,\n selectCommonBoxChatId,\n selectIsChatListed,\n selectChatListType,\n selectCurrentMessageList,\n} from '../../selectors';\n\nconst TYPING_STATUS_CLEAR_DELAY = 6000; // 6 seconds\n\n// Enough to animate and mark as read in Message List\nconst CURRENT_CHAT_UNREAD_DELAY = 1000;\n\naddReducer('apiUpdate', (global, actions, update: ApiUpdate) => {\n switch (update['@type']) {\n case 'updateChat': {\n if (!selectIsChatListed(global, update.id)) {\n // Chat can appear in dialogs list.\n actions.loadTopChats();\n }\n\n setGlobal(updateChat(global, update.id, update.chat));\n\n break;\n }\n\n case 'updateChatJoin': {\n const listType = selectChatListType(global, update.id);\n if (!listType) {\n break;\n }\n\n global = updateChatListIds(global, listType, [update.id]);\n global = updateChat(global, update.id, { isNotJoined: false });\n setGlobal(global);\n\n const chat = selectChat(global, update.id);\n if (chat) {\n actions.requestChatUpdate({ chatId: chat.id });\n }\n break;\n }\n\n case 'updateChatLeave': {\n const listType = selectChatListType(global, update.id);\n if (!listType) {\n break;\n }\n\n const { [listType]: listIds } = global.chats.listIds;\n\n if (listIds) {\n global = replaceChatListIds(global, listType, listIds.filter((listId) => listId !== update.id));\n }\n\n global = updateChat(global, update.id, { isNotJoined: true });\n setGlobal(global);\n\n break;\n }\n\n case 'updateChatInbox': {\n setGlobal(updateChat(global, update.id, update.chat));\n\n break;\n }\n\n case 'updateChatTypingStatus': {\n const { id, typingStatus } = update;\n setGlobal(updateChat(global, id, { typingStatus }));\n\n setTimeout(() => {\n const newGlobal = getGlobal();\n const chat = selectChat(newGlobal, id);\n if (chat && typingStatus && chat.typingStatus && chat.typingStatus.timestamp === typingStatus.timestamp) {\n setGlobal(updateChat(newGlobal, id, { typingStatus: undefined }));\n }\n }, TYPING_STATUS_CLEAR_DELAY);\n\n break;\n }\n\n case 'newMessage': {\n const { message } = update;\n const { chatId: currentChatId } = selectCurrentMessageList(global) || {};\n\n if (message.senderId === global.currentUserId && !message.isFromScheduled) {\n return;\n }\n\n const chat = selectChat(global, update.chatId);\n if (!chat) {\n return;\n }\n\n if (update.chatId === currentChatId) {\n setTimeout(() => {\n actions.requestChatUpdate({ chatId: update.chatId });\n }, CURRENT_CHAT_UNREAD_DELAY);\n } else {\n setGlobal(updateChat(global, update.chatId, {\n unreadCount: chat.unreadCount ? chat.unreadCount + 1 : 1,\n ...(update.message.hasUnreadMention && {\n unreadMentionsCount: chat.unreadMentionsCount ? chat.unreadMentionsCount + 1 : 1,\n }),\n }));\n }\n\n break;\n }\n\n case 'updateCommonBoxMessages':\n case 'updateChannelMessages': {\n const { ids, messageUpdate } = update;\n if (messageUpdate.hasUnreadMention !== false) {\n return;\n }\n\n ids.forEach((id) => {\n const chatId = 'channelId' in update ? update.channelId : selectCommonBoxChatId(global, id);\n const chat = selectChat(global, chatId);\n if (chat && chat.unreadMentionsCount) {\n global = updateChat(global, chatId, {\n unreadMentionsCount: chat.unreadMentionsCount - 1,\n });\n }\n });\n\n setGlobal(global);\n\n break;\n }\n\n case 'updateChatFullInfo': {\n const { fullInfo } = update;\n const targetChat = global.chats.byId[update.id];\n if (!targetChat) {\n return;\n }\n\n setGlobal(updateChat(global, update.id, {\n fullInfo: {\n ...targetChat.fullInfo,\n ...fullInfo,\n },\n }));\n\n break;\n }\n\n case 'updatePinnedChatIds': {\n const { ids, folderId } = update;\n\n const listType = folderId === ARCHIVED_FOLDER_ID ? 'archived' : 'active';\n\n global = {\n ...global,\n chats: {\n ...global.chats,\n orderedPinnedIds: {\n ...global.chats.orderedPinnedIds,\n [listType]: ids.length ? ids : undefined,\n },\n },\n };\n\n setGlobal(global);\n\n break;\n }\n\n case 'updateChatPinned': {\n const { id, isPinned } = update;\n const listType = selectChatListType(global, id);\n if (listType) {\n const { [listType]: orderedPinnedIds } = global.chats.orderedPinnedIds;\n\n let newOrderedPinnedIds = orderedPinnedIds || [];\n if (!isPinned) {\n newOrderedPinnedIds = newOrderedPinnedIds.filter((pinnedId) => pinnedId !== id);\n } else if (!newOrderedPinnedIds.includes(id)) {\n // When moving pinned chats to archive, active ordered pinned ids don't get updated\n // (to preserve chat pinned state when it returns from archive)\n // If user already has max pinned chats, we should check for orderedIds\n // that don't point to listed chats\n if (listType === 'active' && newOrderedPinnedIds.length >= MAX_ACTIVE_PINNED_CHATS) {\n const listIds = global.chats.listIds.active;\n newOrderedPinnedIds = newOrderedPinnedIds.filter((pinnedId) => listIds && listIds.includes(pinnedId));\n }\n\n newOrderedPinnedIds = [id, ...newOrderedPinnedIds];\n }\n\n global = {\n ...global,\n chats: {\n ...global.chats,\n orderedPinnedIds: {\n ...global.chats.orderedPinnedIds,\n [listType]: newOrderedPinnedIds.length ? newOrderedPinnedIds : undefined,\n },\n },\n };\n }\n\n setGlobal(global);\n\n break;\n }\n\n case 'updateChatListType': {\n const { id, folderId } = update;\n\n setGlobal(updateChatListType(global, id, folderId));\n\n break;\n }\n\n case 'updateChatFolder': {\n const { id, folder } = update;\n const { byId: chatFoldersById, orderedIds } = global.chatFolders;\n\n const newChatFoldersById = folder\n ? { ...chatFoldersById, [id]: folder }\n : pick(\n chatFoldersById,\n Object.keys(chatFoldersById).map(Number).filter((folderId) => folderId !== id),\n );\n\n const newOrderedIds = folder\n ? orderedIds && orderedIds.includes(id) ? orderedIds : [...(orderedIds || []), id]\n : orderedIds ? orderedIds.filter((orderedId) => orderedId !== id) : undefined;\n\n setGlobal({\n ...global,\n chatFolders: {\n ...global.chatFolders,\n byId: newChatFoldersById,\n orderedIds: newOrderedIds,\n },\n });\n\n break;\n }\n\n case 'updateChatFoldersOrder': {\n const { orderedIds } = update;\n\n setGlobal({\n ...global,\n chatFolders: {\n ...global.chatFolders,\n orderedIds,\n },\n });\n\n break;\n }\n\n case 'updateRecommendedChatFolders': {\n const { folders } = update;\n\n setGlobal({\n ...global,\n chatFolders: {\n ...global.chatFolders,\n recommended: folders,\n },\n });\n\n break;\n }\n\n case 'updateChatMembers': {\n const targetChat = global.chats.byId[update.id];\n const { replacedMembers, addedMember, deletedMemberId } = update;\n if (!targetChat) {\n return;\n }\n\n let shouldUpdate = false;\n let members = targetChat.fullInfo && targetChat.fullInfo.members\n ? [...targetChat.fullInfo.members]\n : [];\n\n if (replacedMembers) {\n members = replacedMembers;\n shouldUpdate = true;\n } else if (addedMember) {\n if (\n !members.length\n || !members.some((m) => m.userId === addedMember.userId)\n ) {\n members.push(addedMember);\n shouldUpdate = true;\n }\n } else if (members.length && deletedMemberId) {\n const deleteIndex = members.findIndex((m) => m.userId === deletedMemberId);\n if (deleteIndex > -1) {\n members.slice(deleteIndex, 1);\n shouldUpdate = true;\n }\n }\n\n if (shouldUpdate) {\n const adminMembers = members.filter(({ isOwner, isAdmin }) => isOwner || isAdmin);\n // TODO Kicked members?\n\n setGlobal(updateChat(global, update.id, {\n membersCount: members.length,\n fullInfo: {\n ...targetChat.fullInfo,\n members,\n adminMembers,\n },\n }));\n }\n\n break;\n }\n }\n});\n","import { addReducer, getGlobal, setGlobal } from '../../../lib/teact/teactn';\n\nimport {\n ApiUpdate, ApiMessage, ApiPollResult, ApiThreadInfo, MAIN_THREAD_ID,\n} from '../../../api/types';\n\nimport { unique } from '../../../util/iteratees';\nimport {\n updateChat,\n deleteChatMessages,\n updateChatMessage,\n updateListedIds,\n addViewportId,\n updateThreadInfo,\n replaceThreadParam,\n updateScheduledMessage,\n deleteChatScheduledMessages,\n} from '../../reducers';\nimport { GlobalActions, GlobalState } from '../../../global/types';\nimport {\n selectChatMessage,\n selectChatMessages,\n selectIsViewportNewest,\n selectListedIds,\n selectChatMessageByPollId,\n selectCommonBoxChatId,\n selectIsChatListed,\n selectThreadInfo,\n selectThreadByMessage,\n selectPinnedIds,\n selectScheduledMessage,\n selectScheduledMessages,\n isMessageInCurrentMessageList,\n selectScheduledIds,\n selectCurrentMessageList,\n} from '../../selectors';\nimport { getMessageContent, isChatPrivate, isMessageLocal } from '../../helpers';\n\nconst ANIMATION_DELAY = 350;\n\naddReducer('apiUpdate', (global, actions, update: ApiUpdate) => {\n switch (update['@type']) {\n case 'newMessage': {\n const { chatId, id, message } = update;\n global = updateWithLocalMedia(global, chatId, id, message);\n global = updateListedAndViewportIds(global, message as ApiMessage);\n\n if (message.threadInfo) {\n global = updateThreadInfo(\n global,\n message.threadInfo.chatId,\n message.threadInfo.threadId,\n message.threadInfo,\n );\n }\n\n setGlobal(global);\n\n const newMessage = selectChatMessage(global, chatId, id)!;\n\n if (isMessageInCurrentMessageList(global, chatId, message as ApiMessage)) {\n if (message.isOutgoing && !(message.content && message.content.action)) {\n const currentMessageList = selectCurrentMessageList(global);\n if (currentMessageList) {\n // We do not use `actions.focusLastMessage` as it may be set with a delay (see below)\n actions.focusMessage({\n chatId,\n threadId: currentMessageList.threadId,\n messageId: message.id,\n noHighlight: true,\n });\n }\n }\n\n const { threadInfo } = selectThreadByMessage(global, chatId, message as ApiMessage) || {};\n if (threadInfo) {\n actions.requestThreadInfoUpdate({ chatId, threadId: threadInfo.threadId });\n }\n\n // @perf Wait until scroll animation finishes or simply rely on delivery status update (which is itself delayed)\n if (!message.isOutgoing) {\n setTimeout(() => {\n setGlobal(updateChatLastMessage(getGlobal(), chatId, newMessage));\n }, ANIMATION_DELAY);\n }\n } else {\n setGlobal(updateChatLastMessage(getGlobal(), chatId, newMessage));\n }\n\n // Edge case: New message in an old (not loaded) chat.\n if (!selectIsChatListed(global, chatId)) {\n actions.loadTopChats();\n }\n\n break;\n }\n\n case 'newScheduledMessage': {\n const { chatId, id, message } = update;\n\n global = updateWithLocalMedia(global, chatId, id, message, true);\n\n const scheduledIds = selectScheduledIds(global, chatId) || [];\n global = replaceThreadParam(global, chatId, MAIN_THREAD_ID, 'scheduledIds', unique([...scheduledIds, id]));\n\n setGlobal(global);\n\n break;\n }\n\n case 'updateMessage': {\n const { chatId, id, message } = update;\n\n const currentMessage = selectChatMessage(global, chatId, id);\n if (!currentMessage) {\n return;\n }\n\n global = updateWithLocalMedia(global, chatId, id, message);\n\n const newMessage = selectChatMessage(global, chatId, id)!;\n if (message.threadInfo) {\n global = updateThreadInfo(\n global,\n message.threadInfo.chatId,\n message.threadInfo.threadId,\n message.threadInfo,\n );\n }\n global = updateChatLastMessage(global, chatId, newMessage);\n\n setGlobal(global);\n\n break;\n }\n\n case 'updateScheduledMessage': {\n const { chatId, id, message } = update;\n\n const currentMessage = selectScheduledMessage(global, chatId, id);\n if (!currentMessage) {\n return;\n }\n\n global = updateWithLocalMedia(global, chatId, id, message, true);\n const ids = Object.keys(selectScheduledMessages(global, chatId) || {}).map(Number).sort((a, b) => b - a);\n global = replaceThreadParam(global, chatId, MAIN_THREAD_ID, 'scheduledIds', ids);\n setGlobal(global);\n\n break;\n }\n\n case 'updateMessageSendSucceeded': {\n const { chatId, localId, message } = update;\n\n global = updateListedAndViewportIds(global, message as ApiMessage);\n\n const currentMessage = selectChatMessage(global, chatId, localId);\n\n global = deleteChatMessages(global, chatId, [localId]);\n\n // Edge case for \"Send When Online\"\n if (message.isScheduled) {\n global = deleteChatScheduledMessages(global, chatId, [localId]);\n }\n\n global = updateChatMessage(global, chatId, message.id, {\n ...currentMessage,\n ...message,\n previousLocalId: localId,\n });\n\n const newMessage = selectChatMessage(global, chatId, message.id)!;\n global = updateChatLastMessage(global, chatId, newMessage);\n\n setGlobal(global);\n\n break;\n }\n\n case 'updateScheduledMessageSendSucceeded': {\n const { chatId, localId, message } = update;\n const scheduledIds = selectScheduledIds(global, chatId) || [];\n global = replaceThreadParam(global, chatId, MAIN_THREAD_ID, 'scheduledIds', [...scheduledIds, message.id]);\n\n const currentMessage = selectScheduledMessage(global, chatId, localId);\n\n global = deleteChatScheduledMessages(global, chatId, [localId]);\n global = updateScheduledMessage(global, chatId, message.id, {\n ...currentMessage,\n ...message,\n previousLocalId: localId,\n });\n\n setGlobal(global);\n break;\n }\n\n case 'updatePinnedIds': {\n const { chatId, isPinned, messageIds } = update;\n\n const currentPinnedIds = selectPinnedIds(global, chatId) || [];\n const newPinnedIds = isPinned\n ? [...currentPinnedIds, ...messageIds]\n : currentPinnedIds.filter((id) => !messageIds.includes(id));\n\n setGlobal(replaceThreadParam(global, chatId, MAIN_THREAD_ID, 'pinnedIds', newPinnedIds));\n\n break;\n }\n\n case 'updateThreadInfo': {\n const { chatId, threadId, threadInfo } = update;\n\n const currentThreadInfo = selectThreadInfo(global, chatId, threadId);\n const newTheadInfo = {\n ...currentThreadInfo,\n ...threadInfo,\n };\n\n if (!newTheadInfo.threadId) {\n return;\n }\n\n global = updateThreadInfo(global, chatId, threadId, newTheadInfo as ApiThreadInfo);\n setGlobal(global);\n\n break;\n }\n\n case 'resetMessages': {\n const { id: chatId } = update;\n const messagesById = selectChatMessages(global, chatId);\n\n if (messagesById && !isChatPrivate(chatId)) {\n global = deleteChatMessages(global, chatId, Object.keys(messagesById).map(Number));\n setGlobal(global);\n actions.loadFullChat({ chatId, force: true });\n }\n\n break;\n }\n\n case 'deleteMessages': {\n const { ids, chatId } = update;\n\n deleteMessages(chatId, ids, actions, global);\n break;\n }\n\n case 'deleteScheduledMessages': {\n const { ids, chatId } = update;\n\n deleteScheduledMessages(chatId, ids, actions, global);\n break;\n }\n\n case 'deleteHistory': {\n const { chatId } = update;\n const ids = Object.keys(global.messages.byChatId[chatId].byId).map(Number);\n\n deleteMessages(chatId, ids, actions, global);\n break;\n }\n\n case 'updateCommonBoxMessages': {\n const { ids, messageUpdate } = update;\n\n ids.forEach((id) => {\n const chatId = selectCommonBoxChatId(global, id);\n if (chatId) {\n global = updateChatMessage(global, chatId, id, messageUpdate);\n }\n });\n\n setGlobal(global);\n\n break;\n }\n\n case 'updateChannelMessages': {\n const { channelId, ids, messageUpdate } = update;\n\n ids.forEach((id) => {\n global = updateChatMessage(global, channelId, id, messageUpdate);\n });\n\n setGlobal(global);\n\n break;\n }\n\n case 'updateMessagePoll': {\n const { pollId, pollUpdate } = update;\n\n const message = selectChatMessageByPollId(global, pollId);\n\n if (message && message.content.poll) {\n const updatedPoll = { ...message.content.poll, ...pollUpdate };\n\n // Workaround for poll update bug: `chosen` option gets reset when someone votes after current user\n const { results: updatedResults } = updatedPoll.results || {};\n if (updatedResults && !updatedResults.some(((result) => result.isChosen))) {\n const { results } = message.content.poll.results;\n const chosenAnswers = results && results.filter((result) => result.isChosen);\n if (chosenAnswers) {\n chosenAnswers.forEach((chosenAnswer) => {\n const chosenAnswerIndex = updatedResults.findIndex((result) => result.option === chosenAnswer.option);\n if (chosenAnswerIndex >= 0) {\n updatedPoll.results.results![chosenAnswerIndex].isChosen = true;\n }\n });\n }\n }\n\n setGlobal(updateChatMessage(\n global,\n message.chatId,\n message.id,\n {\n content: {\n ...message.content,\n poll: updatedPoll,\n },\n },\n ));\n }\n break;\n }\n\n case 'updateMessagePollVote': {\n const { pollId, userId, options } = update;\n const message = selectChatMessageByPollId(global, pollId);\n if (!message || !message.content.poll || !message.content.poll.results) {\n break;\n }\n\n const { poll } = message.content;\n\n const { recentVoterIds, totalVoters, results } = poll.results;\n const newRecentVoterIds = recentVoterIds ? [...recentVoterIds] : [];\n const newTotalVoters = totalVoters ? totalVoters + 1 : 1;\n const newResults = results ? [...results] : [];\n\n newRecentVoterIds.push(userId);\n\n options.forEach((option) => {\n const targetOption = newResults.find((result) => result.option === option);\n const targetOptionIndex = newResults.findIndex((result) => result.option === option);\n const updatedOption: ApiPollResult = targetOption ? { ...targetOption } : { option, votersCount: 0 };\n\n updatedOption.votersCount += 1;\n if (userId === global.currentUserId) {\n updatedOption.isChosen = true;\n }\n\n if (targetOptionIndex) {\n newResults[targetOptionIndex] = updatedOption;\n } else {\n newResults.push(updatedOption);\n }\n });\n\n setGlobal(updateChatMessage(\n global,\n message.chatId,\n message.id,\n {\n content: {\n ...message.content,\n poll: {\n ...poll,\n results: {\n ...poll.results,\n recentVoterIds: newRecentVoterIds,\n totalVoters: newTotalVoters,\n results: newResults,\n },\n },\n },\n },\n ));\n\n break;\n }\n }\n});\n\nfunction updateWithLocalMedia(\n global: GlobalState, chatId: number, id: number, message: Partial<ApiMessage>, isScheduled = false,\n) {\n // Preserve locally uploaded media.\n const currentMessage = isScheduled\n ? selectScheduledMessage(global, chatId, id)\n : selectChatMessage(global, chatId, id);\n if (currentMessage && message.content) {\n const {\n photo, video, sticker, document,\n } = getMessageContent(currentMessage);\n if (photo && message.content.photo) {\n message.content.photo.blobUrl = photo.blobUrl;\n message.content.photo.thumbnail = photo.thumbnail;\n } else if (video && message.content.video) {\n message.content.video.blobUrl = video.blobUrl;\n } else if (sticker && message.content.sticker) {\n message.content.sticker.isPreloadedGlobally = sticker.isPreloadedGlobally;\n } else if (document && message.content.document) {\n message.content.document.previewBlobUrl = document.previewBlobUrl;\n }\n }\n\n return isScheduled\n ? updateScheduledMessage(global, chatId, id, message)\n : updateChatMessage(global, chatId, id, message);\n}\n\nfunction updateListedAndViewportIds(global: GlobalState, message: ApiMessage) {\n const { id, chatId } = message;\n\n global = updateListedIds(global, chatId, MAIN_THREAD_ID, [id]);\n\n if (selectIsViewportNewest(global, chatId, MAIN_THREAD_ID)) {\n global = addViewportId(global, chatId, MAIN_THREAD_ID, id);\n }\n\n const { threadInfo, firstMessageId } = selectThreadByMessage(global, chatId, message) || {};\n\n if (!firstMessageId && isMessageLocal(message)) {\n return global;\n }\n\n if (threadInfo) {\n global = updateListedIds(global, chatId, threadInfo.threadId, [id]);\n\n if (selectIsViewportNewest(global, chatId, threadInfo.threadId)) {\n global = addViewportId(global, chatId, threadInfo.threadId, id);\n\n if (!firstMessageId) {\n global = replaceThreadParam(global, chatId, threadInfo.threadId, 'firstMessageId', message.id);\n }\n\n if (!threadInfo.lastMessageId) {\n global = replaceThreadParam(global, chatId, threadInfo.threadId, 'threadInfo', {\n ...threadInfo,\n lastMessageId: message.id,\n });\n }\n }\n }\n\n return global;\n}\n\nfunction updateChatLastMessage(\n global: GlobalState,\n chatId: number,\n message: ApiMessage,\n force = false,\n) {\n const { chats } = global;\n const currentLastMessage = chats.byId[chatId] && chats.byId[chatId].lastMessage;\n\n if (currentLastMessage && !force) {\n const isSameOrNewer = (\n currentLastMessage.id === message.id || currentLastMessage.id === message.previousLocalId\n ) || message.id > currentLastMessage.id;\n\n if (!isSameOrNewer) {\n return global;\n }\n }\n\n return updateChat(global, chatId, { lastMessage: message });\n}\n\nfunction findLastMessage(global: GlobalState, chatId: number) {\n const byId = selectChatMessages(global, chatId);\n const listedIds = selectListedIds(global, chatId, MAIN_THREAD_ID);\n\n if (!byId || !listedIds) {\n return undefined;\n }\n\n let i = listedIds.length;\n while (i--) {\n const message = byId[listedIds[i]];\n if (!message.isDeleting) {\n return message;\n }\n }\n\n return undefined;\n}\n\nfunction deleteMessages(chatId: number | undefined, ids: number[], actions: GlobalActions, global: GlobalState) {\n // Channel update\n\n if (chatId) {\n ids.forEach((id) => {\n global = updateChatMessage(global, chatId, id, {\n isDeleting: true,\n });\n\n const newLastMessage = findLastMessage(global, chatId);\n if (newLastMessage) {\n global = updateChatLastMessage(global, chatId, newLastMessage, true);\n }\n });\n\n setGlobal(global);\n\n actions.requestChatUpdate({ chatId });\n\n const threadIdsToUpdate: number[] = [];\n\n ids.forEach((id) => {\n const message = selectChatMessage(global, chatId, id);\n if (!message) {\n return;\n }\n\n const { threadInfo } = selectThreadByMessage(global, chatId, message) || {};\n if (threadInfo) {\n threadIdsToUpdate.push(threadInfo.threadId);\n }\n });\n\n unique(threadIdsToUpdate).forEach((threadId) => {\n actions.requestThreadInfoUpdate({ chatId, threadId });\n });\n\n setTimeout(() => {\n setGlobal(deleteChatMessages(getGlobal(), chatId, ids));\n }, ANIMATION_DELAY);\n\n return;\n }\n\n // Common box update\n\n const chatsIdsToUpdate: number[] = [];\n\n ids.forEach((id) => {\n const commonBoxChatId = selectCommonBoxChatId(global, id);\n if (commonBoxChatId) {\n chatsIdsToUpdate.push(commonBoxChatId);\n\n global = updateChatMessage(global, commonBoxChatId, id, {\n isDeleting: true,\n });\n\n const newLastMessage = findLastMessage(global, commonBoxChatId);\n if (newLastMessage) {\n global = updateChatLastMessage(global, commonBoxChatId, newLastMessage, true);\n }\n\n setTimeout(() => {\n setGlobal(deleteChatMessages(getGlobal(), commonBoxChatId, [id]));\n }, ANIMATION_DELAY);\n }\n });\n\n setGlobal(global);\n\n unique(chatsIdsToUpdate).forEach((id) => {\n actions.requestChatUpdate({ chatId: id });\n });\n}\n\nfunction deleteScheduledMessages(\n chatId: number | undefined, ids: number[], actions: GlobalActions, global: GlobalState,\n) {\n if (!chatId) {\n return;\n }\n\n ids.forEach((id) => {\n global = updateScheduledMessage(global, chatId, id, {\n isDeleting: true,\n });\n });\n\n setGlobal(global);\n\n setTimeout(() => {\n global = deleteChatScheduledMessages(getGlobal(), chatId, ids);\n const scheduledMessages = selectScheduledMessages(global, chatId);\n global = replaceThreadParam(\n global, chatId, MAIN_THREAD_ID, 'scheduledIds', Object.keys(scheduledMessages || {}).map(Number),\n );\n setGlobal(global);\n }, ANIMATION_DELAY);\n}\n","import { addReducer, getGlobal, setGlobal } from '../../../lib/teact/teactn';\n\nimport { ApiUpdate, ApiUserStatus } from '../../../api/types';\n\nimport { deleteUser, updateUser } from '../../reducers';\nimport { throttle } from '../../../lib/lovely-chart/utils';\n\nconst STATUS_UPDATE_THROTTLE = 3000;\n\nconst flushStatusUpdatesThrottled = throttle(flushStatusUpdates, STATUS_UPDATE_THROTTLE, true);\n\nlet pendingStatusUpdates: [number, ApiUserStatus][] = [];\n\nfunction scheduleStatusUpdate(userId: number, statusUpdate: ApiUserStatus) {\n pendingStatusUpdates.push([userId, statusUpdate]);\n flushStatusUpdatesThrottled();\n}\n\nfunction flushStatusUpdates() {\n let global = getGlobal();\n pendingStatusUpdates.forEach(([userId, statusUpdate]) => {\n global = updateUser(global, userId, {\n status: statusUpdate,\n });\n });\n setGlobal(global);\n\n pendingStatusUpdates = [];\n}\n\naddReducer('apiUpdate', (global, actions, update: ApiUpdate) => {\n switch (update['@type']) {\n case 'deleteUser': {\n return deleteUser(global, update.id);\n }\n\n case 'updateUser': {\n return updateUser(global, update.id, update.user);\n }\n\n case 'updateUserStatus': {\n // Status updates come very often so we throttle them\n scheduleStatusUpdate(update.userId, update.status);\n return undefined;\n }\n\n case 'updateUserFullInfo': {\n const { id, fullInfo } = update;\n const targetUser = global.users.byId[id];\n if (!targetUser) {\n return undefined;\n }\n\n return updateUser(global, id, {\n fullInfo: {\n ...targetUser.fullInfo,\n ...fullInfo,\n },\n });\n }\n }\n\n return undefined;\n});\n","import { addReducer } from '../../../lib/teact/teactn';\n\nimport { ApiUpdate } from '../../../api/types';\n\nimport { updateStickerSet } from '../../reducers';\n\naddReducer('apiUpdate', (global, actions, update: ApiUpdate) => {\n switch (update['@type']) {\n case 'updateStickerSet': {\n return updateStickerSet(global, update.id, update.stickerSet);\n }\n }\n\n return undefined;\n});\n","import {\n addReducer, getGlobal, setGlobal,\n} from '../../../lib/teact/teactn';\n\nimport { ApiUpdate } from '../../../api/types';\nimport { ApiPrivacyKey } from '../../../types';\n\nimport { addBlockedContact, removeBlockedContact } from '../../reducers';\n\naddReducer('apiUpdate', (global, actions, update: ApiUpdate) => {\n switch (update['@type']) {\n case 'updatePeerBlocked':\n if (update.isBlocked) {\n return addBlockedContact(getGlobal(), update.id);\n } else {\n return removeBlockedContact(getGlobal(), update.id);\n }\n\n case 'updateResetContactList':\n setGlobal({\n ...getGlobal(),\n contactList: {\n hash: 0,\n userIds: [],\n },\n });\n break;\n\n case 'updateFavoriteStickers':\n actions.loadFavoriteStickers();\n break;\n\n case 'updatePrivacy':\n global.settings.privacy[update.key as ApiPrivacyKey] = update.rules;\n break;\n }\n\n return undefined;\n});\n","import { addReducer } from '../../../lib/teact/teactn';\n\nimport { ApiUpdate } from '../../../api/types';\nimport { GlobalState } from '../../../global/types';\nimport { updateNotifySettings } from '../../reducers';\n\naddReducer('apiUpdate', (global, actions, update: ApiUpdate): GlobalState | undefined => {\n switch (update['@type']) {\n case 'updateNotifySettings': {\n return updateNotifySettings(global, update.peerType, update.isSilent, update.isShowPreviews);\n }\n }\n\n return undefined;\n});\n","import { addReducer } from '../../../lib/teact/teactn';\n\nimport { ApiUpdate } from '../../../api/types';\nimport { GlobalState } from '../../../global/types';\n\naddReducer('apiUpdate', (global, actions, update: ApiUpdate): GlobalState | undefined => {\n switch (update['@type']) {\n case 'updateTwoFaStateWaitCode': {\n return {\n ...global,\n twoFaSettings: {\n ...global.twoFaSettings,\n isLoading: false,\n waitingEmailCodeLength: update.length,\n },\n };\n }\n\n case 'updateTwoFaError': {\n return {\n ...global,\n twoFaSettings: {\n ...global.twoFaSettings,\n error: update.message,\n },\n };\n }\n }\n\n return undefined;\n});\n","import { ChangeEvent } from 'react';\nimport React, { FC, memo, useCallback } from '../../lib/teact/teact';\n\nimport buildClassName from '../../util/buildClassName';\n\nimport './Switcher.scss';\n\ntype OwnProps = {\n id?: string;\n name?: string;\n value?: string;\n label: string;\n checked?: boolean;\n disabled?: boolean;\n onChange?: (e: ChangeEvent<HTMLInputElement>) => void;\n onCheck?: (isChecked: boolean) => void;\n};\n\nconst Switcher: FC<OwnProps> = ({\n id,\n name,\n value,\n label,\n checked = false,\n disabled,\n onChange,\n onCheck,\n}) => {\n const handleChange = useCallback((event: ChangeEvent<HTMLInputElement>) => {\n if (onChange) {\n onChange(event);\n }\n\n if (onCheck) {\n onCheck(event.currentTarget.checked);\n }\n }, [onChange, onCheck]);\n\n const className = buildClassName(\n 'Switcher',\n disabled && 'disabled',\n );\n\n return (\n <label className={className} title={label}>\n <input\n type=\"checkbox\"\n id={id}\n name={name}\n value={value}\n checked={checked}\n disabled={disabled}\n onChange={handleChange}\n />\n <span className=\"widget\" />\n </label>\n );\n};\n\nexport default memo(Switcher);\n","import React, {\n FC, useCallback, useMemo, memo,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../../global/types';\nimport { LeftColumnContent, ISettings } from '../../../types';\nimport { ApiChat } from '../../../api/types';\n\nimport {\n APP_INFO, DEFAULT_PATTERN_COLOR, FEEDBACK_URL, DARK_THEME_BG_COLOR, DARK_THEME_PATTERN_COLOR,\n} from '../../../config';\nimport { IS_MOBILE_SCREEN } from '../../../util/environment';\nimport buildClassName from '../../../util/buildClassName';\nimport { pick } from '../../../util/iteratees';\nimport { isChatArchived } from '../../../modules/helpers';\nimport { formatDateToString } from '../../../util/dateFormat';\nimport switchTheme from '../../../util/switchTheme';\nimport useLang from '../../../hooks/useLang';\n\nimport DropdownMenu from '../../ui/DropdownMenu';\nimport MenuItem from '../../ui/MenuItem';\nimport Button from '../../ui/Button';\nimport SearchInput from '../../ui/SearchInput';\nimport PickerSelectedItem from '../../common/PickerSelectedItem';\nimport Switcher from '../../ui/Switcher';\n\nimport './LeftMainHeader.scss';\n\ntype OwnProps = {\n content: LeftColumnContent;\n contactsFilter: string;\n onSearchQuery: (query: string) => void;\n onSelectSettings: () => void;\n onSelectContacts: () => void;\n onSelectArchived: () => void;\n onReset: () => void;\n};\n\ntype StateProps = {\n searchQuery?: string;\n isLoading: boolean;\n currentUserId?: number;\n globalSearchChatId?: number;\n searchDate?: number;\n theme: ISettings['theme'];\n animationLevel: 0 | 1 | 2;\n chatsById?: Record<number, ApiChat>;\n};\n\ntype DispatchProps = Pick<GlobalActions, (\n 'openChat' | 'openTipsChat' | 'setGlobalSearchDate' | 'setGlobalSearchChatId' | 'setSettingOption'\n)>;\n\nconst ANIMATION_LEVEL_OPTIONS = [0, 1, 2];\n\nconst LeftMainHeader: FC<OwnProps & StateProps & DispatchProps> = ({\n content,\n contactsFilter,\n onSearchQuery,\n onSelectSettings,\n onSelectContacts,\n onSelectArchived,\n setGlobalSearchChatId,\n onReset,\n searchQuery,\n isLoading,\n currentUserId,\n globalSearchChatId,\n searchDate,\n theme,\n animationLevel,\n chatsById,\n openChat,\n openTipsChat,\n setGlobalSearchDate,\n setSettingOption,\n}) => {\n const hasMenu = content === LeftColumnContent.ChatList;\n const clearedDateSearchParam = { date: undefined };\n const clearedChatSearchParam = { id: undefined };\n const selectedSearchDate = useMemo(() => {\n return searchDate\n ? formatDateToString(new Date(searchDate * 1000))\n : undefined;\n }, [searchDate]);\n const archivedUnreadChatsCount = useMemo(() => {\n if (!hasMenu || !chatsById) {\n return 0;\n }\n\n return Object.values(chatsById).reduce((total, chat) => {\n if (!isChatArchived(chat)) {\n return total;\n }\n\n return chat.unreadCount ? total + 1 : total;\n }, 0);\n }, [hasMenu, chatsById]);\n\n const MainButton: FC<{ onTrigger: () => void; isOpen?: boolean }> = useMemo(() => {\n return ({ onTrigger, isOpen }) => (\n <Button\n round\n ripple={hasMenu && !IS_MOBILE_SCREEN}\n size=\"smaller\"\n color=\"translucent\"\n className={isOpen ? 'active' : ''}\n onClick={hasMenu ? onTrigger : () => onReset()}\n ariaLabel={hasMenu ? 'Open menu' : 'Return to chat list'}\n >\n <div className={buildClassName('animated-menu-icon', !hasMenu && 'state-back')} />\n </Button>\n );\n }, [hasMenu, onReset]);\n\n const handleSearchFocus = useCallback(() => {\n if (!searchQuery) {\n onSearchQuery('');\n }\n }, [searchQuery, onSearchQuery]);\n\n const handleSelectSaved = useCallback(() => {\n openChat({ id: currentUserId });\n }, [currentUserId, openChat]);\n\n const handleDarkModeToggle = useCallback((e: React.SyntheticEvent<HTMLDivElement>) => {\n e.stopPropagation();\n const newTheme = theme === 'light' ? 'dark' : 'light';\n const isNewThemeDark = newTheme === 'dark';\n\n setSettingOption({\n theme: newTheme,\n customBackground: isNewThemeDark ? DARK_THEME_BG_COLOR : undefined,\n patternColor: isNewThemeDark ? DARK_THEME_PATTERN_COLOR : DEFAULT_PATTERN_COLOR,\n });\n switchTheme(newTheme, animationLevel > 0);\n }, [animationLevel, setSettingOption, theme]);\n\n const handleAnimationLevelChange = useCallback((e: React.SyntheticEvent<HTMLDivElement>) => {\n e.stopPropagation();\n\n const newLevel = animationLevel === 0 ? 2 : 0;\n ANIMATION_LEVEL_OPTIONS.forEach((_, i) => {\n document.body.classList.toggle(`animation-level-${i}`, newLevel === i);\n });\n\n setSettingOption({ animationLevel: newLevel });\n }, [animationLevel, setSettingOption]);\n\n const lang = useLang();\n\n const isSearchFocused = (\n Boolean(globalSearchChatId)\n || content === LeftColumnContent.GlobalSearch\n || content === LeftColumnContent.Contacts\n );\n\n const searchInputPlaceholder = content === LeftColumnContent.Contacts\n ? lang('SearchFriends')\n : lang('Search');\n\n return (\n <div className=\"LeftMainHeader\">\n <div id=\"LeftMainHeader\" className=\"left-header\">\n <DropdownMenu\n trigger={MainButton}\n footer={APP_INFO}\n >\n <MenuItem\n icon=\"saved-messages\"\n onClick={handleSelectSaved}\n >\n {lang('SavedMessages')}\n </MenuItem>\n <MenuItem\n icon=\"archive\"\n onClick={onSelectArchived}\n >\n <span className=\"menu-item-name\">{lang('ArchivedChats')}</span>\n {archivedUnreadChatsCount > 0 && (\n <div className=\"archived-badge\">{archivedUnreadChatsCount}</div>\n )}\n </MenuItem>\n <MenuItem\n icon=\"user\"\n onClick={onSelectContacts}\n >\n {lang('Contacts')}\n </MenuItem>\n <MenuItem\n icon=\"settings\"\n onClick={onSelectSettings}\n >\n {lang('Settings')}\n </MenuItem>\n <MenuItem\n icon=\"darkmode\"\n onClick={handleDarkModeToggle}\n >\n <span className=\"menu-item-name\">Dark Mode</span>\n <Switcher\n id=\"darkmode\"\n label=\"Toggle Dark Mode\"\n checked={theme === 'dark'}\n />\n </MenuItem>\n <MenuItem\n icon=\"animations\"\n onClick={handleAnimationLevelChange}\n >\n <span className=\"menu-item-name capitalize\">{lang('Appearance.Animations').toLowerCase()}</span>\n <Switcher\n id=\"animations\"\n label=\"Toggle Animations\"\n checked={animationLevel > 0}\n />\n </MenuItem>\n <MenuItem\n icon=\"help\"\n onClick={openTipsChat}\n >\n Telegram Features\n </MenuItem>\n <MenuItem\n icon=\"bug\"\n href={FEEDBACK_URL}\n >\n Report Bug\n </MenuItem>\n </DropdownMenu>\n <SearchInput\n inputId=\"telegram-search-input\"\n className={globalSearchChatId || searchDate ? 'with-picker-item' : ''}\n value={contactsFilter || searchQuery}\n focused={isSearchFocused}\n isLoading={isLoading}\n placeholder={searchInputPlaceholder}\n canClose={Boolean(globalSearchChatId || searchDate)}\n onChange={onSearchQuery}\n onReset={onReset}\n onFocus={handleSearchFocus}\n >\n {selectedSearchDate && (\n <PickerSelectedItem\n icon=\"calendar\"\n title={selectedSearchDate}\n canClose\n isMinimized={Boolean(globalSearchChatId)}\n className=\"search-date\"\n onClick={setGlobalSearchDate}\n clickArg={clearedDateSearchParam}\n />\n )}\n {globalSearchChatId && (\n <PickerSelectedItem\n chatOrUserId={globalSearchChatId}\n onClick={setGlobalSearchChatId}\n canClose\n clickArg={clearedChatSearchParam}\n />\n )}\n </SearchInput>\n </div>\n </div>\n );\n};\n\nexport default memo(withGlobal<OwnProps>(\n (global): StateProps => {\n const {\n query: searchQuery, fetchingStatus, chatId, date,\n } = global.globalSearch;\n const { currentUserId } = global;\n const { byId: chatsById } = global.chats;\n const { theme, animationLevel } = global.settings.byKey;\n\n return {\n searchQuery,\n isLoading: fetchingStatus ? Boolean(fetchingStatus.chats || fetchingStatus.messages) : false,\n currentUserId,\n chatsById,\n globalSearchChatId: chatId,\n searchDate: date,\n theme,\n animationLevel,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'openChat',\n 'openTipsChat',\n 'setGlobalSearchDate',\n 'setGlobalSearchChatId',\n 'setSettingOption',\n ]),\n)(LeftMainHeader));\n","import React, { FC } from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { GlobalState } from '../../global/types';\n\nimport { pick } from '../../util/iteratees';\nimport useLang from '../../hooks/useLang';\n\nimport Spinner from '../ui/Spinner';\n\nimport './ConnectionState.scss';\n\ntype StateProps = Pick<GlobalState, 'connectionState'>;\n\nconst ConnectionState: FC<StateProps> = ({ connectionState }) => {\n const lang = useLang();\n\n const isConnecting = connectionState === 'connectionStateConnecting';\n\n return isConnecting && (\n <div id=\"ConnectionState\">\n <Spinner color=\"black\" />\n <div className=\"state-text\">{lang('WaitingForNetwork')}</div>\n </div>\n );\n};\n\nexport default withGlobal(\n (global): StateProps => pick(global, ['connectionState']),\n)(ConnectionState);\n","import { useRef } from '../lib/teact/teact';\n\nimport useThrottle from './useThrottle';\nimport useOnChange from './useOnChange';\nimport useForceUpdate from './useForceUpdate';\n\nexport default <R extends any, D extends any[]>(resolverFn: () => R, ms: number, dependencies: D) => {\n const valueRef = useRef<R>();\n const runThrottled = useThrottle(ms);\n const forceUpdate = useForceUpdate();\n\n useOnChange(() => {\n let isSync = true;\n runThrottled(() => {\n valueRef.current = resolverFn();\n\n if (!isSync) {\n forceUpdate();\n }\n });\n isSync = false;\n }, dependencies);\n\n return valueRef.current;\n};\n","import { useMemo } from '../lib/teact/teact';\n\nimport { throttle } from '../util/schedulers';\n\nexport default (ms: number) => {\n return useMemo(() => {\n return throttle((cb) => cb(), ms);\n }, [ms]);\n};\n","import React, {\n FC, memo, useCallback, useEffect, useMemo, useRef, useState,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { ApiChat, ApiChatFolder, ApiUser } from '../../../api/types';\nimport { GlobalActions } from '../../../global/types';\n\nimport { IS_TOUCH_ENV } from '../../../util/environment';\nimport { buildCollectionByKey, pick } from '../../../util/iteratees';\nimport { captureEvents, SwipeDirection } from '../../../util/captureEvents';\nimport { getFolderUnreadDialogs } from '../../../modules/helpers';\nimport useShowTransition from '../../../hooks/useShowTransition';\nimport buildClassName from '../../../util/buildClassName';\nimport useThrottledMemo from '../../../hooks/useThrottledMemo';\nimport useLang from '../../../hooks/useLang';\n\nimport Transition from '../../ui/Transition';\nimport TabList from '../../ui/TabList';\nimport ChatList from './ChatList';\n\ntype StateProps = {\n chatsById: Record<number, ApiChat>;\n usersById: Record<number, ApiUser>;\n chatFoldersById: Record<number, ApiChatFolder>;\n orderedFolderIds?: number[];\n lastSyncTime?: number;\n};\n\ntype DispatchProps = Pick<GlobalActions, 'loadChatFolders'>;\n\nconst INFO_THROTTLE = 3000;\n\nconst ChatFolders: FC<StateProps & DispatchProps> = ({\n chatsById,\n usersById,\n chatFoldersById,\n orderedFolderIds,\n lastSyncTime,\n loadChatFolders,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const transitionRef = useRef<HTMLDivElement>(null);\n\n const [activeTab, setActiveTab] = useState(0);\n\n useEffect(() => {\n if (lastSyncTime) {\n loadChatFolders();\n }\n }, [lastSyncTime, loadChatFolders]);\n\n const displayedFolders = useMemo(() => {\n return orderedFolderIds\n ? orderedFolderIds.map((id) => chatFoldersById[id] || {}).filter(Boolean)\n : undefined;\n }, [chatFoldersById, orderedFolderIds]);\n\n const folderCountersById = useThrottledMemo(() => {\n if (!displayedFolders || !displayedFolders.length) {\n return undefined;\n }\n\n const chatIds = Object.keys(chatsById).map(Number);\n const counters = displayedFolders.map((folder) => {\n const {\n unreadDialogsCount, hasActiveDialogs,\n } = getFolderUnreadDialogs(chatsById, usersById, folder, chatIds) || {};\n\n return {\n id: folder.id,\n badgeCount: unreadDialogsCount,\n isBadgeActive: hasActiveDialogs,\n };\n });\n\n return buildCollectionByKey(counters, 'id');\n }, INFO_THROTTLE, [displayedFolders, chatsById, usersById]);\n\n const folderTabs = useMemo(() => {\n if (!displayedFolders || !displayedFolders.length) {\n return undefined;\n }\n\n return [\n { title: 'All' },\n ...displayedFolders.map((folder) => ({\n title: folder.title,\n ...(folderCountersById && folderCountersById[folder.id]),\n })),\n ];\n }, [displayedFolders, folderCountersById]);\n\n const handleSwitchTab = useCallback((index: number) => {\n setActiveTab(index);\n }, []);\n\n // Prevent `activeTab` pointing at non-existing folder after update\n useEffect(() => {\n if (!folderTabs || !folderTabs.length) {\n return;\n }\n\n if (activeTab >= folderTabs.length) {\n setActiveTab(0);\n }\n }, [activeTab, folderTabs]);\n\n useEffect(() => {\n if (!transitionRef.current || !IS_TOUCH_ENV || !folderTabs || !folderTabs.length) {\n return undefined;\n }\n\n return captureEvents(transitionRef.current, {\n onSwipe: ((e, direction) => {\n if (direction === SwipeDirection.Left) {\n setActiveTab(Math.min(activeTab + 1, folderTabs.length - 1));\n } else if (direction === SwipeDirection.Right) {\n setActiveTab(Math.max(0, activeTab - 1));\n }\n }),\n });\n }, [activeTab, folderTabs]);\n\n const {\n shouldRender: shouldRenderPlaceholder, transitionClassNames,\n } = useShowTransition(!orderedFolderIds, undefined, true);\n\n const lang = useLang();\n\n function renderCurrentTab() {\n const activeFolder = Object.values(chatFoldersById)\n .find(({ title }) => title === folderTabs![activeTab].title);\n\n if (!activeFolder || activeTab === 0) {\n return <ChatList folderType=\"all\" />;\n }\n\n return <ChatList folderType=\"folder\" folderId={activeFolder.id} noChatsText={lang('FilterNoChatsToDisplay')} />;\n }\n\n return (\n <div className=\"ChatFolders\">\n {folderTabs && folderTabs.length ? (\n <TabList tabs={folderTabs} activeTab={activeTab} onSwitchTab={handleSwitchTab} />\n ) : shouldRenderPlaceholder ? (\n <div className={buildClassName('tabs-placeholder', transitionClassNames)} />\n ) : undefined}\n <Transition\n ref={transitionRef}\n name=\"slide\"\n activeKey={activeTab}\n renderCount={folderTabs ? folderTabs.length : undefined}\n >\n {renderCurrentTab}\n </Transition>\n </div>\n );\n};\n\nexport default memo(withGlobal(\n (global): StateProps => {\n const {\n chats: { byId: chatsById },\n users: { byId: usersById },\n chatFolders: {\n byId: chatFoldersById,\n orderedIds: orderedFolderIds,\n },\n lastSyncTime,\n } = global;\n\n return {\n chatsById,\n usersById,\n chatFoldersById,\n orderedFolderIds,\n lastSyncTime,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, ['loadChatFolders']),\n)(ChatFolders));\n","import React, { FC } from '../../../lib/teact/teact';\nimport { Bundles } from '../../../util/moduleLoader';\nimport { OwnProps } from './LeftSearch';\n\nimport useModuleLoader from '../../../hooks/useModuleLoader';\nimport Loading from '../../ui/Loading';\n\nconst LeftSearchAsync: FC<OwnProps> = (props) => {\n const LeftSearch = useModuleLoader(Bundles.Extra, 'LeftSearch');\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return LeftSearch ? <LeftSearch {...props} /> : <Loading />;\n};\n\nexport default LeftSearchAsync;\n","import React, { FC } from '../../../lib/teact/teact';\nimport { Bundles } from '../../../util/moduleLoader';\nimport { OwnProps } from './ContactList';\n\nimport useModuleLoader from '../../../hooks/useModuleLoader';\nimport Loading from '../../ui/Loading';\n\nconst ContactListAsync: FC<OwnProps> = (props) => {\n const ContactList = useModuleLoader(Bundles.Extra, 'ContactList');\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return ContactList ? <ContactList {...props} /> : <Loading />;\n};\n\nexport default ContactListAsync;\n","import React, {\n FC, useCallback, useState, useEffect, memo,\n} from '../../lib/teact/teact';\n\nimport buildClassName from '../../util/buildClassName';\nimport useLang from '../../hooks/useLang';\n\nimport Button from '../ui/Button';\nimport Menu from '../ui/Menu';\nimport MenuItem from '../ui/MenuItem';\n\nimport './NewChatButton.scss';\n\nconst MENU_CLOSE_DELAY_MS = 750;\nlet closeTimeout: number | undefined;\n\ntype OwnProps = {\n isShown: boolean;\n onNewPrivateChat: () => void;\n onNewChannel: () => void;\n onNewGroup: () => void;\n};\n\nconst NewChatButton: FC<OwnProps> = ({\n isShown,\n onNewPrivateChat,\n onNewChannel,\n onNewGroup,\n}) => {\n const [isMenuOpen, setIsMenuOpen] = useState(false);\n\n useEffect(() => {\n if (!isShown) {\n setIsMenuOpen(false);\n }\n }, [isShown]);\n\n const lang = useLang();\n\n const fabClassName = buildClassName(\n 'NewChatButton',\n isShown && 'revealed',\n isMenuOpen && 'menu-is-open',\n );\n\n const toggleIsMenuOpen = () => {\n setIsMenuOpen(!isMenuOpen);\n };\n\n const handleClose = () => {\n setIsMenuOpen(false);\n };\n\n const handleMouseEnter = useCallback(() => {\n if (closeTimeout) {\n clearTimeout(closeTimeout);\n closeTimeout = undefined;\n }\n }, []);\n\n const handleMouseLeave = useCallback(() => {\n if (closeTimeout) {\n clearTimeout(closeTimeout);\n closeTimeout = undefined;\n }\n\n closeTimeout = window.setTimeout(() => {\n setIsMenuOpen(false);\n }, MENU_CLOSE_DELAY_MS);\n }, []);\n\n return (\n <div\n className={fabClassName}\n onMouseEnter={handleMouseEnter}\n onMouseLeave={handleMouseLeave}\n >\n <Button\n round\n color=\"primary\"\n className={isMenuOpen ? 'active' : ''}\n onClick={toggleIsMenuOpen}\n ariaLabel={isMenuOpen ? 'Close' : 'Create new chat'}\n tabIndex={-1}\n >\n <i className=\"icon-new-chat-filled\" />\n <i className=\"icon-close\" />\n </Button>\n <Menu\n isOpen={isMenuOpen}\n positionX=\"right\"\n positionY=\"bottom\"\n autoClose\n onClose={handleClose}\n >\n <MenuItem icon=\"channel\" onClick={onNewChannel}>{lang('NewChannel')}</MenuItem>\n <MenuItem icon=\"group\" onClick={onNewGroup}>{lang('NewGroup')}</MenuItem>\n <MenuItem icon=\"user\" onClick={onNewPrivateChat}>New Private Chat</MenuItem>\n </Menu>\n </div>\n );\n};\n\nexport default memo(NewChatButton);\n","import React, {\n FC, memo, useState, useRef, useCallback, useEffect,\n} from '../../../lib/teact/teact';\n\nimport { LeftColumnContent } from '../../../types';\n\nimport { IS_TOUCH_ENV } from '../../../util/environment';\n\nimport Transition from '../../ui/Transition';\nimport LeftMainHeader from './LeftMainHeader';\nimport ConnectionState from '../ConnectionState';\nimport ChatFolders from './ChatFolders';\nimport LeftSearch from '../search/LeftSearch.async';\nimport ContactList from './ContactList.async';\nimport NewChatButton from '../NewChatButton';\n\nimport './LeftMain.scss';\n\ntype OwnProps = {\n content: LeftColumnContent;\n searchQuery?: string;\n searchDate?: number;\n contactsFilter: string;\n onSearchQuery: (query: string) => void;\n onContentChange: (content: LeftColumnContent) => void;\n onReset: () => void;\n};\n\ntype StateProps = {};\n\nconst TRANSITION_RENDER_COUNT = Object.keys(LeftColumnContent).length / 2;\nconst BUTTON_CLOSE_DELAY_MS = 250;\nlet closeTimeout: number | undefined;\n\nconst LeftMain: FC<OwnProps & StateProps> = ({\n content,\n searchQuery,\n searchDate,\n contactsFilter,\n onSearchQuery,\n onContentChange,\n onReset,\n}) => {\n const [isNewChatButtonShown, setIsNewChatButtonShown] = useState(IS_TOUCH_ENV);\n\n const isMouseInside = useRef(false);\n\n const handleSelectSettings = useCallback(() => {\n onContentChange(LeftColumnContent.Settings);\n }, [onContentChange]);\n\n const handleSelectContacts = useCallback(() => {\n onContentChange(LeftColumnContent.Contacts);\n }, [onContentChange]);\n\n const handleSelectNewChannel = useCallback(() => {\n onContentChange(LeftColumnContent.NewChannelStep1);\n }, [onContentChange]);\n\n const handleSelectNewGroup = useCallback(() => {\n onContentChange(LeftColumnContent.NewGroupStep1);\n }, [onContentChange]);\n\n const handleSelectArchived = useCallback(() => {\n onContentChange(LeftColumnContent.Archived);\n }, [onContentChange]);\n\n const handleMouseEnter = useCallback(() => {\n if (content !== LeftColumnContent.ChatList) {\n return;\n }\n isMouseInside.current = true;\n setIsNewChatButtonShown(true);\n }, [content]);\n\n const handleMouseLeave = useCallback(() => {\n isMouseInside.current = false;\n\n if (closeTimeout) {\n clearTimeout(closeTimeout);\n closeTimeout = undefined;\n }\n\n closeTimeout = window.setTimeout(() => {\n if (!isMouseInside.current) {\n setIsNewChatButtonShown(false);\n }\n }, BUTTON_CLOSE_DELAY_MS);\n }, []);\n\n useEffect(() => {\n let autoCloseTimeout: number | undefined;\n if (content !== LeftColumnContent.ChatList) {\n autoCloseTimeout = window.setTimeout(() => {\n setIsNewChatButtonShown(false);\n }, BUTTON_CLOSE_DELAY_MS);\n } else if (isMouseInside.current || IS_TOUCH_ENV) {\n setIsNewChatButtonShown(true);\n }\n\n return () => {\n if (autoCloseTimeout) {\n clearTimeout(autoCloseTimeout);\n autoCloseTimeout = undefined;\n }\n };\n }, [content]);\n\n return (\n <div\n id=\"LeftColumn-main\"\n onMouseEnter={!IS_TOUCH_ENV ? handleMouseEnter : undefined}\n onMouseLeave={!IS_TOUCH_ENV ? handleMouseLeave : undefined}\n >\n <LeftMainHeader\n content={content}\n contactsFilter={contactsFilter}\n onSearchQuery={onSearchQuery}\n onSelectSettings={handleSelectSettings}\n onSelectContacts={handleSelectContacts}\n onSelectArchived={handleSelectArchived}\n onReset={onReset}\n />\n <ConnectionState />\n <Transition name=\"zoom-fade\" renderCount={TRANSITION_RENDER_COUNT} activeKey={content}>\n {() => {\n switch (content) {\n case LeftColumnContent.ChatList:\n return <ChatFolders />;\n case LeftColumnContent.GlobalSearch:\n return (\n <LeftSearch\n searchQuery={searchQuery}\n searchDate={searchDate}\n onReset={onReset}\n />\n );\n case LeftColumnContent.Contacts:\n return <ContactList filter={contactsFilter} />;\n default:\n return undefined;\n }\n }}\n </Transition>\n <NewChatButton\n isShown={isNewChatButtonShown}\n onNewPrivateChat={handleSelectContacts}\n onNewChannel={handleSelectNewChannel}\n onNewGroup={handleSelectNewGroup}\n />\n </div>\n );\n};\n\nexport default memo(LeftMain);\n","import React, { FC } from '../../../lib/teact/teact';\nimport { Bundles } from '../../../util/moduleLoader';\n\nimport { OwnProps } from './Settings';\n\nimport useModuleLoader from '../../../hooks/useModuleLoader';\nimport Loading from '../../ui/Loading';\n\nconst SettingsAsync: FC<OwnProps> = (props) => {\n const Settings = useModuleLoader(Bundles.Extra, 'Settings');\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return Settings ? <Settings {...props} /> : <Loading />;\n};\n\nexport default SettingsAsync;\n","import React, { FC } from '../../../lib/teact/teact';\nimport { Bundles } from '../../../util/moduleLoader';\n\nimport { OwnProps } from './NewChat';\n\nimport useModuleLoader from '../../../hooks/useModuleLoader';\nimport Loading from '../../ui/Loading';\n\nconst NewChatAsync: FC<OwnProps> = (props) => {\n const NewChat = useModuleLoader(Bundles.Extra, 'NewChat');\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return NewChat ? <NewChat {...props} /> : <Loading />;\n};\n\nexport default NewChatAsync;\n","import React, { FC } from '../../lib/teact/teact';\nimport { OwnProps } from './ArchivedChats';\nimport { Bundles } from '../../util/moduleLoader';\n\nimport useModuleLoader from '../../hooks/useModuleLoader';\nimport Loading from '../ui/Loading';\n\nconst ArchivedChatsAsync: FC<OwnProps> = (props) => {\n const ArchivedChats = useModuleLoader(Bundles.Extra, 'ArchivedChats');\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return ArchivedChats ? <ArchivedChats {...props} /> : <Loading />;\n};\n\nexport default ArchivedChatsAsync;\n","import React, {\n FC, memo, useCallback, useEffect, useState,\n} from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../global/types';\nimport { LeftColumnContent, SettingsScreens } from '../../types';\n\nimport { IS_MOBILE_SCREEN } from '../../util/environment';\nimport captureEscKeyListener from '../../util/captureEscKeyListener';\nimport { pick } from '../../util/iteratees';\n\nimport Transition from '../ui/Transition';\nimport LeftMain from './main/LeftMain';\nimport Settings from './settings/Settings.async';\nimport NewChat from './newChat/NewChat.async';\nimport ArchivedChats from './ArchivedChats.async';\n\nimport './LeftColumn.scss';\n\ntype StateProps = {\n searchQuery?: string;\n searchDate?: number;\n};\n\ntype DispatchProps = Pick<GlobalActions, (\n 'setGlobalSearchQuery' | 'setGlobalSearchChatId' | 'resetChatCreation' | 'setGlobalSearchDate' |\n 'loadPasswordInfo' | 'clearTwoFaError'\n)>;\n\nenum ContentType {\n Main,\n // eslint-disable-next-line no-shadow\n Settings,\n Archived,\n // eslint-disable-next-line no-shadow\n NewGroup,\n // eslint-disable-next-line no-shadow\n NewChannel\n}\n\nconst RENDER_COUNT = Object.keys(ContentType).length / 2;\nconst RESET_TRANSITION_DELAY_MS = 250;\n\nconst LeftColumn: FC<StateProps & DispatchProps> = ({\n searchQuery,\n searchDate,\n setGlobalSearchQuery,\n setGlobalSearchChatId,\n resetChatCreation,\n setGlobalSearchDate,\n loadPasswordInfo,\n clearTwoFaError,\n}) => {\n const [content, setContent] = useState<LeftColumnContent>(LeftColumnContent.ChatList);\n const [settingsScreen, setSettingsScreen] = useState(SettingsScreens.Main);\n const [contactsFilter, setContactsFilter] = useState<string>('');\n\n // Used to reset child components in background.\n const [lastResetTime, setLastResetTime] = useState<number>(0);\n\n let contentType: ContentType = ContentType.Main;\n switch (content) {\n case LeftColumnContent.Archived:\n contentType = ContentType.Archived;\n break;\n case LeftColumnContent.Settings:\n contentType = ContentType.Settings;\n break;\n case LeftColumnContent.NewChannelStep1:\n case LeftColumnContent.NewChannelStep2:\n contentType = ContentType.NewChannel;\n break;\n case LeftColumnContent.NewGroupStep1:\n case LeftColumnContent.NewGroupStep2:\n contentType = ContentType.NewGroup;\n break;\n }\n\n const handleReset = useCallback((forceReturnToChatList?: boolean) => {\n if (\n content === LeftColumnContent.NewGroupStep2\n && !forceReturnToChatList\n ) {\n setContent(LeftColumnContent.NewGroupStep1);\n return;\n }\n\n if (content === LeftColumnContent.NewGroupStep1) {\n const pickerSearchInput = document.getElementById('new-group-picker-search');\n if (pickerSearchInput) {\n pickerSearchInput.blur();\n }\n }\n\n if (content === LeftColumnContent.Settings) {\n switch (settingsScreen) {\n case SettingsScreens.EditProfile:\n case SettingsScreens.Folders:\n case SettingsScreens.General:\n case SettingsScreens.Notifications:\n case SettingsScreens.Privacy:\n case SettingsScreens.Language:\n setSettingsScreen(SettingsScreens.Main);\n return;\n\n case SettingsScreens.GeneralChatBackground:\n setSettingsScreen(SettingsScreens.General);\n return;\n case SettingsScreens.GeneralChatBackgroundColor:\n setSettingsScreen(SettingsScreens.GeneralChatBackground);\n return;\n\n case SettingsScreens.PrivacyPhoneNumber:\n case SettingsScreens.PrivacyLastSeen:\n case SettingsScreens.PrivacyProfilePhoto:\n case SettingsScreens.PrivacyForwarding:\n case SettingsScreens.PrivacyGroupChats:\n case SettingsScreens.PrivacyActiveSessions:\n case SettingsScreens.PrivacyBlockedUsers:\n case SettingsScreens.TwoFaDisabled:\n case SettingsScreens.TwoFaEnabled:\n case SettingsScreens.TwoFaCongratulations:\n setSettingsScreen(SettingsScreens.Privacy);\n return;\n case SettingsScreens.PrivacyPhoneNumberAllowedContacts:\n case SettingsScreens.PrivacyPhoneNumberDeniedContacts:\n setSettingsScreen(SettingsScreens.PrivacyPhoneNumber);\n return;\n case SettingsScreens.PrivacyLastSeenAllowedContacts:\n case SettingsScreens.PrivacyLastSeenDeniedContacts:\n setSettingsScreen(SettingsScreens.PrivacyLastSeen);\n return;\n case SettingsScreens.PrivacyProfilePhotoAllowedContacts:\n case SettingsScreens.PrivacyProfilePhotoDeniedContacts:\n setSettingsScreen(SettingsScreens.PrivacyProfilePhoto);\n return;\n case SettingsScreens.PrivacyForwardingAllowedContacts:\n case SettingsScreens.PrivacyForwardingDeniedContacts:\n setSettingsScreen(SettingsScreens.PrivacyForwarding);\n return;\n case SettingsScreens.PrivacyGroupChatsAllowedContacts:\n case SettingsScreens.PrivacyGroupChatsDeniedContacts:\n setSettingsScreen(SettingsScreens.PrivacyGroupChats);\n return;\n case SettingsScreens.TwoFaNewPassword:\n setSettingsScreen(SettingsScreens.TwoFaDisabled);\n return;\n case SettingsScreens.TwoFaNewPasswordConfirm:\n setSettingsScreen(SettingsScreens.TwoFaNewPassword);\n return;\n case SettingsScreens.TwoFaNewPasswordHint:\n setSettingsScreen(SettingsScreens.TwoFaNewPasswordConfirm);\n return;\n case SettingsScreens.TwoFaNewPasswordEmail:\n setSettingsScreen(SettingsScreens.TwoFaNewPasswordHint);\n return;\n case SettingsScreens.TwoFaNewPasswordEmailCode:\n setSettingsScreen(SettingsScreens.TwoFaNewPasswordEmail);\n return;\n case SettingsScreens.TwoFaChangePasswordCurrent:\n case SettingsScreens.TwoFaTurnOff:\n case SettingsScreens.TwoFaRecoveryEmailCurrentPassword:\n setSettingsScreen(SettingsScreens.TwoFaEnabled);\n return;\n case SettingsScreens.TwoFaChangePasswordNew:\n setSettingsScreen(SettingsScreens.TwoFaChangePasswordCurrent);\n return;\n case SettingsScreens.TwoFaChangePasswordConfirm:\n setSettingsScreen(SettingsScreens.TwoFaChangePasswordNew);\n return;\n case SettingsScreens.TwoFaChangePasswordHint:\n setSettingsScreen(SettingsScreens.TwoFaChangePasswordConfirm);\n return;\n case SettingsScreens.TwoFaRecoveryEmail:\n setSettingsScreen(SettingsScreens.TwoFaRecoveryEmailCurrentPassword);\n return;\n case SettingsScreens.TwoFaRecoveryEmailCode:\n setSettingsScreen(SettingsScreens.TwoFaRecoveryEmail);\n return;\n\n case SettingsScreens.FoldersCreateFolder:\n case SettingsScreens.FoldersEditFolder:\n setSettingsScreen(SettingsScreens.Folders);\n return;\n default:\n break;\n }\n }\n\n setContent(LeftColumnContent.ChatList);\n setContactsFilter('');\n setGlobalSearchQuery({ query: '' });\n setGlobalSearchDate({ date: undefined });\n setGlobalSearchChatId({ id: undefined });\n resetChatCreation();\n setTimeout(() => {\n setLastResetTime(Date.now());\n }, RESET_TRANSITION_DELAY_MS);\n }, [content, setGlobalSearchQuery, setGlobalSearchChatId, setGlobalSearchDate, resetChatCreation, settingsScreen]);\n\n const handleSearchQuery = useCallback((query: string) => {\n if (content === LeftColumnContent.Contacts) {\n setContactsFilter(query);\n return;\n }\n\n setContent(LeftColumnContent.GlobalSearch);\n\n if (query !== searchQuery) {\n setGlobalSearchQuery({ query });\n }\n }, [content, setGlobalSearchQuery, searchQuery]);\n\n useEffect(\n () => (content !== LeftColumnContent.ChatList ? captureEscKeyListener(() => handleReset()) : undefined),\n [content, handleReset],\n );\n\n useEffect(() => {\n clearTwoFaError();\n\n if (settingsScreen === SettingsScreens.Privacy) {\n loadPasswordInfo();\n }\n }, [clearTwoFaError, loadPasswordInfo, settingsScreen]);\n\n return (\n <Transition\n id=\"LeftColumn\"\n name={IS_MOBILE_SCREEN ? 'slide-layers' : 'push-slide'}\n renderCount={RENDER_COUNT}\n activeKey={contentType}\n >\n {() => {\n switch (contentType) {\n case ContentType.Archived:\n return (\n <ArchivedChats\n onReset={handleReset}\n />\n );\n case ContentType.Settings:\n return (\n <Settings\n currentScreen={settingsScreen}\n onScreenSelect={setSettingsScreen}\n onReset={handleReset}\n />\n );\n case ContentType.NewChannel:\n return (\n <NewChat\n key={lastResetTime}\n isChannel\n content={content}\n onContentChange={setContent}\n onReset={handleReset}\n />\n );\n case ContentType.NewGroup:\n return (\n <NewChat\n key={lastResetTime}\n content={content}\n onContentChange={setContent}\n onReset={handleReset}\n />\n );\n default:\n return (\n <LeftMain\n content={content}\n searchQuery={searchQuery}\n searchDate={searchDate}\n contactsFilter={contactsFilter}\n onContentChange={setContent}\n onSearchQuery={handleSearchQuery}\n onReset={handleReset}\n />\n );\n }\n }}\n </Transition>\n );\n};\n\nexport default memo(withGlobal(\n (global): StateProps => {\n const { query, date } = global.globalSearch;\n return { searchQuery: query, searchDate: date };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'setGlobalSearchQuery', 'setGlobalSearchChatId', 'resetChatCreation', 'setGlobalSearchDate',\n 'loadPasswordInfo', 'clearTwoFaError',\n ]),\n)(LeftColumn));\n","import { useEffect, useState } from '../lib/teact/teact';\n\nimport { IDimensions } from '../modules/helpers';\n\nimport { throttle } from '../util/schedulers';\nimport windowSize from '../util/windowSize';\n\nconst RESIZE_TIMEOUT_MS = 250;\n\nexport default () => {\n const [size, setSize] = useState<IDimensions>(windowSize.get());\n\n useEffect(() => {\n const handleResize = throttle(() => {\n setSize(windowSize.get());\n }, RESIZE_TIMEOUT_MS, false);\n\n window.addEventListener('resize', handleResize);\n\n return () => {\n window.removeEventListener('resize', handleResize);\n };\n });\n\n return size;\n};\n","import { useRef } from '../lib/teact/teact';\n\nimport usePrevious from './usePrevious';\nimport useForceUpdate from './useForceUpdate';\nimport useOnChange from './useOnChange';\n\nexport default function usePrevForAnimation(current: any, duration?: number) {\n const prev = usePrevious(current, true);\n const timeoutRef = useRef<number>();\n const forceUpdate = useForceUpdate();\n // eslint-disable-next-line no-null/no-null\n const isCurrentPresent = current !== undefined && current !== null;\n\n if (isCurrentPresent && timeoutRef.current) {\n clearTimeout(timeoutRef.current);\n timeoutRef.current = undefined;\n }\n\n useOnChange(() => {\n // When `current` becomes empty\n if (duration && !isCurrentPresent && prev && !timeoutRef.current) {\n timeoutRef.current = window.setTimeout(() => {\n timeoutRef.current = undefined;\n forceUpdate();\n }, duration);\n }\n }, [current]);\n\n return !timeoutRef.current || !duration || isCurrentPresent ? current : prev;\n}\n","import {\n MIN_SCREEN_WIDTH_FOR_STATIC_LEFT_COLUMN,\n MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN,\n MOBILE_SCREEN_MAX_WIDTH,\n} from '../../../config';\n\nconst REM = 16; // px\nconst MAX_TOOLBAR_WIDTH = 32 * REM;\nconst MAX_MESSAGES_LIST_WIDTH = 45.5 * REM;\nconst SIDE_COLUMN_MAX_WIDTH = 26.5 * REM;\nconst MIN_LEFT_COLUMN_WIDTH = 18 * REM;\nconst UNPIN_BUTTON_WIDTH = 16.125 * REM;\n\nexport default function calculateMiddleFooterTransforms(windowWidth: number, canPost?: boolean) {\n const sidePadding = windowWidth <= MOBILE_SCREEN_MAX_WIDTH\n ? REM\n : 2 * REM;\n const messageListWidth = getMessageListWidth(windowWidth);\n const sendButtonWidth = windowWidth <= MOBILE_SCREEN_MAX_WIDTH\n ? 3.375 * REM\n : 4 * REM;\n\n const composerWidth = canPost\n ? messageListWidth - sidePadding - sendButtonWidth\n : messageListWidth - sidePadding;\n const toolbarWidth = windowWidth > MOBILE_SCREEN_MAX_WIDTH\n ? Math.min(messageListWidth - sidePadding, MAX_TOOLBAR_WIDTH)\n : messageListWidth - sidePadding;\n\n const composerHiddenScale = toolbarWidth / composerWidth;\n const toolbarHiddenScale = composerWidth / toolbarWidth;\n const unpinHiddenScale = toolbarWidth / UNPIN_BUTTON_WIDTH;\n const toolbarForUnpinHiddenScale = UNPIN_BUTTON_WIDTH / toolbarWidth;\n\n const composerTranslateX = canPost\n ? (sendButtonWidth / 2) * toolbarHiddenScale\n : 0;\n\n const toolbarTranslateX = canPost\n ? (sendButtonWidth / 2) * -1 * composerHiddenScale\n : 0;\n\n return {\n composerHiddenScale,\n toolbarHiddenScale,\n composerTranslateX,\n toolbarTranslateX,\n unpinHiddenScale,\n toolbarForUnpinHiddenScale,\n };\n}\n\nfunction getMessageListWidth(windowWidth: number) {\n if (windowWidth > MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN) {\n const leftColumnWidth = Math.min(\n Math.max(windowWidth * 0.25, MIN_LEFT_COLUMN_WIDTH),\n SIDE_COLUMN_MAX_WIDTH,\n );\n\n const rightColumnWidth = Math.min(\n windowWidth * 0.25,\n SIDE_COLUMN_MAX_WIDTH,\n );\n\n return Math.min(\n windowWidth - leftColumnWidth - rightColumnWidth,\n MAX_MESSAGES_LIST_WIDTH,\n );\n }\n\n if (windowWidth > MIN_SCREEN_WIDTH_FOR_STATIC_LEFT_COLUMN) {\n const leftColumnWidth = Math.min(\n Math.max(windowWidth * 0.4, MIN_LEFT_COLUMN_WIDTH),\n SIDE_COLUMN_MAX_WIDTH,\n );\n\n return Math.min(\n windowWidth - leftColumnWidth,\n MAX_MESSAGES_LIST_WIDTH,\n );\n }\n\n if (windowWidth > MAX_MESSAGES_LIST_WIDTH) {\n return MAX_MESSAGES_LIST_WIDTH;\n }\n\n return windowWidth;\n}\n","import usePrevious from './usePrevious';\n\nexport default function useCurrentOrPrev<T extends any>(\n current: T, shouldSkipUndefined = false, shouldForceCurrent = false,\n): T | undefined {\n const prev = usePrevious(current, shouldSkipUndefined);\n\n // eslint-disable-next-line no-null/no-null\n return shouldForceCurrent || (current !== null && current !== undefined) ? current : prev;\n}\n","import React, { FC } from '../../lib/teact/teact';\nimport { OwnProps } from './HeaderMenuContainer';\nimport { Bundles } from '../../util/moduleLoader';\n\nimport useModuleLoader from '../../hooks/useModuleLoader';\n\nconst HeaderMenuContainerAsync: FC<OwnProps> = (props) => {\n const { isOpen } = props;\n const HeaderMenuContainer = useModuleLoader(Bundles.Extra, 'HeaderMenuContainer', !isOpen);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return HeaderMenuContainer ? <HeaderMenuContainer {...props} /> : undefined;\n};\n\nexport default HeaderMenuContainerAsync;\n","import React, {\n FC,\n memo,\n useRef,\n useCallback,\n useState,\n} from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { GlobalActions, MessageListType } from '../../global/types';\nimport { MAIN_THREAD_ID } from '../../api/types';\nimport { IAnchorPosition } from '../../types';\n\nimport { IS_MOBILE_SCREEN } from '../../util/environment';\nimport { pick } from '../../util/iteratees';\nimport { isChatChannel, isChatSuperGroup } from '../../modules/helpers';\nimport {\n selectChat,\n selectIsChatBotNotStarted, selectIsChatWithSelf,\n selectIsInSelectMode,\n selectIsRightColumnShown,\n} from '../../modules/selectors';\nimport useLang from '../../hooks/useLang';\n\nimport Button from '../ui/Button';\nimport HeaderMenuContainer from './HeaderMenuContainer.async';\n\ninterface OwnProps {\n chatId: number;\n threadId: number;\n messageListType: MessageListType;\n}\n\ninterface StateProps {\n noMenu?: boolean;\n isChannel?: boolean;\n isRightColumnShown?: boolean;\n canStartBot?: boolean;\n canSubscribe?: boolean;\n canSearch?: boolean;\n canMute?: boolean;\n canSelect?: boolean;\n canLeave?: boolean;\n}\n\ntype DispatchProps = Pick<GlobalActions, 'joinChannel' | 'sendBotCommand' | 'openLocalTextSearch'>;\n\n// Chrome breaks layout when focusing input during transition\nconst SEARCH_FOCUS_DELAY_MS = 400;\n\nconst HeaderActions: FC<OwnProps & StateProps & DispatchProps> = ({\n chatId,\n threadId,\n noMenu,\n isChannel,\n canStartBot,\n canSubscribe,\n canSearch,\n canMute,\n canSelect,\n canLeave,\n isRightColumnShown,\n joinChannel,\n sendBotCommand,\n openLocalTextSearch,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const menuButtonRef = useRef<HTMLButtonElement>(null);\n const [isMenuOpen, setIsMenuOpen] = useState(false);\n const [menuPosition, setMenuPosition] = useState<IAnchorPosition | undefined>(undefined);\n\n const handleHeaderMenuOpen = useCallback(() => {\n setIsMenuOpen(true);\n const rect = menuButtonRef.current!.getBoundingClientRect();\n setMenuPosition({ x: rect.right, y: rect.bottom });\n }, []);\n\n const handleHeaderMenuClose = useCallback(() => {\n setIsMenuOpen(false);\n }, []);\n\n const handleHeaderMenuHide = useCallback(() => {\n setMenuPosition(undefined);\n }, []);\n\n const handleSubscribeClick = useCallback(() => {\n joinChannel({ chatId });\n }, [joinChannel, chatId]);\n\n const handleStartBot = useCallback(() => {\n sendBotCommand({ command: '/start' });\n }, [sendBotCommand]);\n\n const handleSearchClick = useCallback(() => {\n openLocalTextSearch();\n\n if (IS_MOBILE_SCREEN) {\n // iOS requires synchronous focus on user event.\n const searchInput = document.querySelector<HTMLInputElement>('#MobileSearch input')!;\n searchInput.focus();\n } else {\n setTimeout(() => {\n const searchInput = document.querySelector<HTMLInputElement>('.RightHeader .SearchInput input');\n if (searchInput) {\n searchInput.focus();\n }\n }, SEARCH_FOCUS_DELAY_MS);\n }\n }, [openLocalTextSearch]);\n\n const lang = useLang();\n\n return (\n <div className=\"HeaderActions\">\n {!IS_MOBILE_SCREEN && canSubscribe && (\n <Button\n size=\"tiny\"\n ripple\n fluid\n onClick={handleSubscribeClick}\n >\n {lang(isChannel ? 'Subscribe' : 'Join Group')}\n </Button>\n )}\n {!IS_MOBILE_SCREEN && canStartBot && (\n <Button\n size=\"tiny\"\n ripple\n fluid\n onClick={handleStartBot}\n >\n {lang('Start')}\n </Button>\n )}\n {!IS_MOBILE_SCREEN && canSearch && (\n <Button\n round\n ripple={isRightColumnShown}\n color=\"translucent\"\n size=\"smaller\"\n onClick={handleSearchClick}\n ariaLabel=\"Search in this chat\"\n >\n <i className=\"icon-search\" />\n </Button>\n )}\n {(IS_MOBILE_SCREEN || !canSubscribe) && (\n <Button\n ref={menuButtonRef}\n className={isMenuOpen ? 'active' : ''}\n round\n ripple={!IS_MOBILE_SCREEN}\n size=\"smaller\"\n color=\"translucent\"\n disabled={noMenu}\n ariaLabel=\"More actions\"\n onClick={handleHeaderMenuOpen}\n >\n <i className=\"icon-more\" />\n </Button>\n )}\n {menuPosition && (\n <HeaderMenuContainer\n chatId={chatId}\n threadId={threadId}\n isOpen={isMenuOpen}\n anchor={menuPosition}\n isChannel={isChannel}\n canSubscribe={canSubscribe}\n canSearch={canSearch}\n canMute={canMute}\n canSelect={canSelect}\n canLeave={canLeave}\n onSubscribeChannel={handleSubscribeClick}\n onSearchClick={handleSearchClick}\n onClose={handleHeaderMenuClose}\n onCloseAnimationEnd={handleHeaderMenuHide}\n />\n )}\n </div>\n );\n};\n\nexport default memo(withGlobal<OwnProps>(\n (global, { chatId, threadId, messageListType }): StateProps => {\n const chat = selectChat(global, chatId);\n const isChannel = Boolean(chat && isChatChannel(chat));\n\n if (chat && chat.isRestricted) {\n return {\n noMenu: true,\n };\n }\n\n const isChatWithSelf = selectIsChatWithSelf(global, chatId);\n const isMainThread = messageListType === 'thread' && threadId === MAIN_THREAD_ID;\n const isDiscussionThread = messageListType === 'thread' && threadId !== MAIN_THREAD_ID;\n const isRightColumnShown = selectIsRightColumnShown(global);\n\n const canStartBot = Boolean(selectIsChatBotNotStarted(global, chatId));\n const canSubscribe = Boolean(\n isMainThread && chat && (isChannel || isChatSuperGroup(chat)) && chat.isNotJoined,\n );\n const canSearch = isMainThread || isDiscussionThread;\n const canMute = isMainThread && !isChatWithSelf && !canSubscribe;\n const canSelect = !selectIsInSelectMode(global);\n const canLeave = isMainThread && !canSubscribe;\n\n const noMenu = !(\n (IS_MOBILE_SCREEN && canSubscribe)\n || (IS_MOBILE_SCREEN && canSearch)\n || canMute\n || canSelect\n || canLeave\n );\n\n return {\n noMenu,\n isChannel,\n isRightColumnShown,\n canStartBot,\n canSubscribe,\n canSearch,\n canMute,\n canSelect,\n canLeave,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'joinChannel', 'sendBotCommand', 'openLocalTextSearch',\n ]),\n)(HeaderActions));\n","import { useLayoutEffect, useState } from '../lib/teact/teact';\n\nimport { ApiMessage } from '../api/types';\n\nimport { DEBUG } from '../config';\nimport { isWebpSupported } from '../util/environment';\nimport { EMPTY_IMAGE_DATA_URI, webpToPngBase64 } from '../util/webpToPng';\nimport { getMessageMediaThumbDataUri } from '../modules/helpers';\n\nexport default function useWebpThumbnail(message?: ApiMessage) {\n const thumbnail = message && getMessageMediaThumbDataUri(message);\n const { sticker } = (message && message.content) || {};\n const shouldDecodeThumbnail = thumbnail && sticker && !isWebpSupported() && thumbnail.includes('image/webp');\n const [thumbnailDecoded, setThumbnailDecoded] = useState(EMPTY_IMAGE_DATA_URI);\n const messageId = message && message.id;\n\n useLayoutEffect(() => {\n if (!shouldDecodeThumbnail) {\n return;\n }\n\n webpToPngBase64(`b64-${messageId}`, thumbnail!)\n .then(setThumbnailDecoded)\n .catch((err) => {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error(err);\n }\n });\n }, [messageId, shouldDecodeThumbnail, thumbnail]);\n\n return shouldDecodeThumbnail ? thumbnailDecoded : thumbnail;\n}\n","import React, {\n FC,\n useRef,\n useEffect,\n useMemo,\n memo,\n} from '../../lib/teact/teact';\n\nimport buildClassName from '../../util/buildClassName';\n\ntype OwnProps = {\n count: number;\n index: number;\n};\n\nconst BORDER_MASK_LEVEL = 4;\n\nconst PinnedMessageNavigation: FC<OwnProps> = ({\n count, index,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const containerRef = useRef<HTMLDivElement>(null);\n\n const markupParams = useMemo(() => {\n return calculateMarkup(count, index);\n }, [count, index]);\n\n useEffect(() => {\n if (!containerRef.current) {\n return;\n }\n\n const {\n trackHeight,\n trackTranslateY,\n markHeight,\n markTranslateY,\n clipPathId,\n clipPath,\n } = markupParams;\n\n const firstChild = containerRef.current.firstElementChild;\n if (containerRef && containerRef.current) {\n const currentElement = containerRef.current;\n const { style } = currentElement;\n style.height = `${trackHeight}px`;\n style.transform = `translateY(-${trackTranslateY}px)`;\n style.clipPath = `url(\"#${clipPathId}\")`;\n const svg = currentElement.querySelector('svg');\n const div = currentElement.querySelector('div');\n const defs = currentElement.querySelector('defs');\n if (!svg) {\n if (firstChild) {\n firstChild.innerHTML = `<svg height=\"0\" width=\"0\"><defs> ${clipPath} </defs></svg>`;\n }\n }\n if (defs) {\n defs.innerHTML = clipPath;\n }\n if (div) {\n div.style.height = `${markHeight}px`;\n div.style.transform = `translateY(${markTranslateY}px)`;\n }\n }\n }, [markupParams]);\n\n if (count === 1) {\n return (\n <div className=\"pinned-message-border\">\n <div\n className=\"pinned-message-border-wrapper-1\"\n ref={containerRef}\n />\n </div>\n );\n }\n\n const {\n trackHeight, trackTranslateY, markHeight, markTranslateY, clipPathId,\n } = markupParams;\n\n return (\n <div className={buildClassName('pinned-message-border', count > BORDER_MASK_LEVEL && 'pinned-message-border-mask')}>\n <div\n className=\"pinned-message-border-wrapper\"\n ref={containerRef}\n // @ts-ignore\n style={\n `clip-path: url(\"#${clipPathId}\"); width: 2px;\n height: ${trackHeight}px; transform: translateY(-${trackTranslateY}px);`\n }\n >\n <span />\n <div\n className=\"pinned-message-border-mark\"\n // @ts-ignore\n style={`height: ${markHeight}px; transform: translateY(${markTranslateY}px);`}\n />\n </div>\n </div>\n );\n};\n\nfunction calculateMarkup(count: number, index: number) {\n const reverseIndex = count - index - 1;\n const barHeight = getBarHeight(count);\n const markHeight = getMarkHeight(count, reverseIndex);\n const trackHeight = getTrackHeight(count, barHeight);\n\n const clipPathId = `clipPath${count}`;\n const clipPath = getClipPath(clipPathId, barHeight, count);\n\n const markTranslateY = getMarkTranslateY(reverseIndex, barHeight, count);\n const trackTranslateY = getTrackTranslateY(reverseIndex, count, barHeight, trackHeight);\n return {\n markHeight,\n clipPath,\n markTranslateY,\n trackTranslateY,\n trackHeight,\n clipPathId,\n };\n}\n\nfunction getBarHeight(count: number): number {\n let barHeight = 8;\n if (count === 1) {\n barHeight = 36;\n } else if (count === 2) {\n barHeight = 17;\n } else if (count === 3) {\n barHeight = 11;\n } else if (count === 4) {\n barHeight = 7.5;\n } else if (count > 3) {\n barHeight = 7.5;\n }\n\n return barHeight;\n}\n\nfunction getMarkHeight(count: number, index: number) {\n let barHeight = 36;\n if (count === 1) {\n barHeight = 36;\n } else if (count === 2) {\n barHeight = 17;\n } else if (count === 3) {\n barHeight = index === 1 ? 12 : 11;\n } else if (count === 4) {\n barHeight = 7.5;\n } else if (count > 3) {\n barHeight = 7.5;\n }\n\n return barHeight;\n}\n\nfunction getTrackHeight(count: number, barHeight: number) {\n return count <= 3 ? 36 : barHeight * count + 2 * (count - 1);\n}\n\nfunction getClipPath(id: string, barHeight: number, count: number) {\n const radius = 1;\n\n let d = '';\n if (count === 3) {\n d = drawRect(0, 0, 2, barHeight, radius)\n + drawRect(0, 12, 2, barHeight + 1, radius)\n + drawRect(0, 25, 2, barHeight, radius);\n } else {\n for (let i = 0; i < count; i++) {\n d += drawRect(0, (barHeight + 2) * i, 2, barHeight, radius);\n }\n }\n\n return (\n `<clipPath id=\"${id}\">\n <path d=\"${d}\" />\n </clipPath>`\n );\n}\n\nfunction drawRect(x: number, y: number, width: number, height: number, radius: number) {\n return `M${x},${y + radius}a${radius},${radius},0,0,1,\n ${width},0v${height - 2 * radius}a${radius},${radius},0,0,1,${-width},0Z`;\n}\n\nfunction getMarkTranslateY(index: number, barHeight: number, count: number) {\n if (count === 1) {\n return 0;\n } else if (count === 2) {\n return index === 0 ? 0 : barHeight + 2;\n }\n\n if (count === 3) {\n if (index === 0) {\n return 0;\n } else if (index === 1) {\n return 12;\n }\n\n return 25;\n } else {\n return (barHeight + 2) * index;\n }\n}\n\nfunction getTrackTranslateY(index: number, count: number, barHeight: number, trackHeight: number) {\n if (count <= 4) {\n return 0;\n }\n\n if (index <= 1) {\n return 0;\n } else if (index >= count - 2) {\n return trackHeight - 36;\n }\n\n return (barHeight + 4) / 2 + (index - 2) * (barHeight + 2);\n}\n\nexport default memo(PinnedMessageNavigation);\n","import React, { FC, memo, useCallback } from '../../lib/teact/teact';\n\nimport { ApiMessage } from '../../api/types';\n\nimport { getPictogramDimensions } from '../common/helpers/mediaDimensions';\nimport { getMessageMediaHash, getMessageSummaryText } from '../../modules/helpers';\nimport renderText from '../common/helpers/renderText';\nimport useMedia from '../../hooks/useMedia';\nimport useWebpThumbnail from '../../hooks/useWebpThumbnail';\n\nimport ConfirmDialog from '../ui/ConfirmDialog';\nimport Button from '../ui/Button';\nimport RippleEffect from '../ui/RippleEffect';\nimport buildClassName from '../../util/buildClassName';\nimport useFlag from '../../hooks/useFlag';\nimport useLang from '../../hooks/useLang';\n\nimport PinnedMessageNavigation from './PinnedMessageNavigation';\n\ntype OwnProps = {\n message: ApiMessage;\n index: number;\n count: number;\n customTitle?: string;\n className?: string;\n onUnpinMessage?: (id: number) => void;\n onClick?: () => void;\n onAllPinnedClick?: () => void;\n};\n\nconst HeaderPinnedMessage: FC<OwnProps> = ({\n message, count, index, customTitle, className, onUnpinMessage, onClick, onAllPinnedClick,\n}) => {\n const mediaThumbnail = useWebpThumbnail(message);\n const mediaBlobUrl = useMedia(getMessageMediaHash(message, 'pictogram'));\n\n const text = getMessageSummaryText(message, Boolean(mediaThumbnail));\n const [isUnpinDialogOpen, openUnpinDialog, closeUnpinDialog] = useFlag();\n\n const handleUnpinMessage = useCallback(() => {\n closeUnpinDialog();\n\n if (onUnpinMessage) {\n onUnpinMessage(message.id);\n }\n }, [closeUnpinDialog, onUnpinMessage, message.id]);\n\n const lang = useLang();\n\n return (\n <div className={buildClassName('HeaderPinnedMessage-wrapper', className)}>\n {count > 1 && (\n <Button\n round\n size=\"smaller\"\n color=\"translucent\"\n className=\"pin-list-button\"\n ariaLabel={lang('EventLogFilterPinnedMessages')}\n onClick={onAllPinnedClick}\n >\n <i className=\"icon-pin-list\" />\n </Button>\n )}\n {onUnpinMessage && (\n <Button\n round\n size=\"smaller\"\n color=\"translucent\"\n ariaLabel={lang('UnpinMessageAlertTitle')}\n className=\"unpin-button\"\n onClick={openUnpinDialog}\n >\n <i className=\"icon-close\" />\n </Button>\n )}\n <ConfirmDialog\n isOpen={isUnpinDialogOpen}\n onClose={closeUnpinDialog}\n text=\"Would you like to unpin this message?\"\n confirmLabel=\"Unpin\"\n confirmHandler={handleUnpinMessage}\n />\n <div className=\"HeaderPinnedMessage\" onClick={onClick}>\n <PinnedMessageNavigation\n count={count}\n index={index}\n />\n {mediaThumbnail && renderPictogram(mediaThumbnail, mediaBlobUrl)}\n <div className=\"message-text\">\n <div className=\"title\">\n {customTitle || `${lang('PinnedMessage')} ${index > 0 ? `#${count - index}` : ''}`}\n </div>\n <p>{renderText(text)}</p>\n </div>\n\n <RippleEffect />\n </div>\n </div>\n );\n};\n\nfunction renderPictogram(thumbDataUri: string, blobUrl?: string) {\n const { width, height } = getPictogramDimensions();\n\n return (\n <img src={blobUrl || thumbDataUri} width={width} height={height} alt=\"\" />\n );\n}\n\nexport default memo(HeaderPinnedMessage);\n","import React, { FC, useCallback } from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../global/types';\nimport { ApiAudio, ApiMessage } from '../../api/types';\n\nimport { IS_MOBILE_SCREEN } from '../../util/environment';\nimport * as mediaLoader from '../../util/mediaLoader';\nimport {\n getMediaDuration, getMessageAudio, getMessageKey, getMessageMediaHash, getSenderTitle,\n} from '../../modules/helpers';\nimport { selectSender } from '../../modules/selectors';\nimport { pick } from '../../util/iteratees';\nimport renderText from '../common/helpers/renderText';\nimport useAudioPlayer from '../../hooks/useAudioPlayer';\nimport buildClassName from '../../util/buildClassName';\nimport useLang from '../../hooks/useLang';\n\nimport RippleEffect from '../ui/RippleEffect';\nimport Button from '../ui/Button';\n\nimport './AudioPlayer.scss';\n\ntype OwnProps = {\n message: ApiMessage;\n className?: string;\n noUi?: boolean;\n};\n\ntype StateProps = {\n senderName?: string;\n};\n\ntype DispatchProps = Pick<GlobalActions, 'focusMessage' | 'closeAudioPlayer'>;\n\nconst AudioPlayer: FC<OwnProps & StateProps & DispatchProps> = ({\n message, className, noUi, senderName, focusMessage, closeAudioPlayer,\n}) => {\n const mediaData = mediaLoader.getFromMemory(getMessageMediaHash(message, 'inline')!) as (string | undefined);\n const { playPause, isPlaying } = useAudioPlayer(\n getMessageKey(message), getMediaDuration(message)!, mediaData, undefined, undefined, true,\n );\n\n const handleClick = useCallback(() => {\n focusMessage({ chatId: message.chatId, messageId: message.id });\n }, [focusMessage, message.chatId, message.id]);\n\n const handleClose = useCallback(() => {\n if (isPlaying) {\n playPause();\n }\n closeAudioPlayer();\n }, [closeAudioPlayer, isPlaying, playPause]);\n\n const lang = useLang();\n\n if (noUi) {\n return undefined;\n }\n\n const audio = getMessageAudio(message);\n\n return (\n <div className={buildClassName('AudioPlayer', className)}>\n <Button\n round\n ripple={!IS_MOBILE_SCREEN}\n color=\"translucent\"\n size=\"smaller\"\n className={buildClassName('toggle-play', isPlaying ? 'pause' : 'play')}\n onClick={playPause}\n ariaLabel={isPlaying ? 'Pause audio' : 'Play audio'}\n >\n <i className=\"icon-play\" />\n <i className=\"icon-pause\" />\n </Button>\n\n <div className=\"AudioPlayer-content\" onClick={handleClick}>\n {audio ? renderAudio(audio) : renderVoice(lang('AttachAudio'), senderName)}\n <RippleEffect />\n </div>\n\n <Button\n round\n className=\"player-close\"\n color=\"translucent\"\n size=\"smaller\"\n onClick={handleClose}\n ariaLabel=\"Close player\"\n >\n <i className=\"icon-close\" />\n </Button>\n </div>\n );\n};\n\nfunction renderAudio(audio: ApiAudio) {\n const { title, performer, fileName } = audio;\n\n return (\n <>\n <div className=\"title\">{renderText(title || fileName)}</div>\n {performer && (\n <div className=\"subtitle\">{renderText(performer)}</div>\n )}\n </>\n );\n}\n\nfunction renderVoice(subtitle: string, senderName?: string) {\n return (\n <>\n <div className=\"title\">{senderName && renderText(senderName)}</div>\n <div className=\"subtitle\">{subtitle}</div>\n </>\n );\n}\n\nexport default withGlobal<OwnProps>(\n (global, { message }) => {\n const sender = selectSender(global, message);\n const senderName = sender ? getSenderTitle(sender) : undefined;\n\n return { senderName };\n },\n (setGlobal, actions): DispatchProps => pick(actions, ['focusMessage', 'closeAudioPlayer']),\n)(AudioPlayer);\n","import React, {\n FC, useCallback, useMemo, memo, useEffect, useRef, useState,\n} from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\nimport cycleRestrict from '../../util/cycleRestrict';\n\nimport { GlobalActions, MessageListType } from '../../global/types';\nimport {\n ApiMessage,\n ApiChat,\n ApiTypingStatus,\n MAIN_THREAD_ID,\n} from '../../api/types';\n\nimport {\n MIN_SCREEN_WIDTH_FOR_STATIC_LEFT_COLUMN,\n MOBILE_SCREEN_MAX_WIDTH,\n EDITABLE_INPUT_ID,\n MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN,\n SAFE_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN,\n SAFE_SCREEN_WIDTH_FOR_CHAT_INFO,\n} from '../../config';\nimport { IS_MOBILE_SCREEN } from '../../util/environment';\nimport {\n isChatPrivate,\n isChatArchived,\n getMessageKey,\n getChatTitle,\n getSenderTitle,\n} from '../../modules/helpers';\nimport {\n selectChat,\n selectChatMessage,\n selectAllowedMessageActions,\n selectIsRightColumnShown,\n selectThreadTopMessageId,\n selectThreadOriginChat,\n selectThreadInfo,\n selectChatMessages,\n selectPinnedIds,\n selectIsChatWithSelf,\n selectForwardedSender,\n selectScheduledIds,\n selectIsInSelectMode,\n selectIsChatWithBot,\n} from '../../modules/selectors';\nimport useEnsureMessage from '../../hooks/useEnsureMessage';\nimport useWindowSize from '../../hooks/useWindowSize';\nimport useShowTransition from '../../hooks/useShowTransition';\nimport useCurrentOrPrev from '../../hooks/useCurrentOrPrev';\nimport { pick } from '../../util/iteratees';\nimport { formatIntegerCompact } from '../../util/textFormat';\nimport buildClassName from '../../util/buildClassName';\nimport useLang from '../../hooks/useLang';\n\nimport PrivateChatInfo from '../common/PrivateChatInfo';\nimport GroupChatInfo from '../common/GroupChatInfo';\nimport Transition from '../ui/Transition';\nimport Button from '../ui/Button';\nimport HeaderActions from './HeaderActions';\nimport HeaderPinnedMessage from './HeaderPinnedMessage';\nimport AudioPlayer from './AudioPlayer';\n\nimport './MiddleHeader.scss';\n\nconst ANIMATION_DURATION = 350;\n\ntype OwnProps = {\n chatId: number;\n threadId: number;\n messageListType: MessageListType;\n};\n\ntype StateProps = {\n pinnedMessageIds?: number[] | number;\n messagesById?: Record<number, ApiMessage>;\n canUnpin?: boolean;\n topMessageTitle?: string;\n typingStatus?: ApiTypingStatus;\n isSelectModeActive?: boolean;\n isLeftColumnShown?: boolean;\n isRightColumnShown?: boolean;\n audioMessage?: ApiMessage;\n chatTitleLength?: number;\n chatsById?: Record<number, ApiChat>;\n originChatId: number;\n messagesCount?: number;\n isChatWithSelf?: boolean;\n isChatWithBot?: boolean;\n lastSyncTime?: number;\n};\n\ntype DispatchProps = Pick<GlobalActions, (\n 'openChatWithInfo' | 'pinMessage' | 'focusMessage' | 'openChat' | 'loadPinnedMessages' | 'toggleLeftColumn' |\n 'exitMessageSelectMode'\n)>;\n\nconst MiddleHeader: FC<OwnProps & StateProps & DispatchProps> = ({\n chatId,\n threadId,\n messageListType,\n pinnedMessageIds,\n messagesById,\n canUnpin,\n topMessageTitle,\n typingStatus,\n isSelectModeActive,\n isLeftColumnShown,\n isRightColumnShown,\n audioMessage,\n chatTitleLength,\n chatsById,\n originChatId,\n messagesCount,\n isChatWithSelf,\n isChatWithBot,\n lastSyncTime,\n openChatWithInfo,\n pinMessage,\n focusMessage,\n openChat,\n loadPinnedMessages,\n toggleLeftColumn,\n exitMessageSelectMode,\n}) => {\n const [pinnedMessageIndex, setPinnedMessageIndex] = useState(0);\n const pinnedMessageId = Array.isArray(pinnedMessageIds) ? pinnedMessageIds[pinnedMessageIndex] : pinnedMessageIds;\n const pinnedMessage = messagesById && pinnedMessageId ? messagesById[pinnedMessageId] : undefined;\n const pinnedMessagesCount = Array.isArray(pinnedMessageIds) ? pinnedMessageIds.length : (pinnedMessageIds ? 1 : 0);\n\n useEffect(() => {\n if (threadId === MAIN_THREAD_ID && lastSyncTime) {\n loadPinnedMessages({ chatId });\n }\n }, [chatId, loadPinnedMessages, lastSyncTime, threadId]);\n\n useEffect(() => {\n setPinnedMessageIndex(0);\n }, [chatId]);\n\n // Modify index after unpinning\n useEffect(() => {\n setPinnedMessageIndex(pinnedMessagesCount ? cycleRestrict(pinnedMessagesCount, pinnedMessageIndex) : -1);\n }, [pinnedMessagesCount, pinnedMessageIndex]);\n\n useEnsureMessage(chatId, pinnedMessageId, pinnedMessage);\n\n const { width: windowWidth } = useWindowSize();\n\n const isLeftColumnHideable = windowWidth <= MIN_SCREEN_WIDTH_FOR_STATIC_LEFT_COLUMN;\n const shouldShowCloseButton = windowWidth >= MOBILE_SCREEN_MAX_WIDTH && isLeftColumnShown;\n\n // eslint-disable-next-line no-null/no-null\n const componentRef = useRef<HTMLDivElement>(null);\n const shouldAnimateTools = useRef<boolean>(true);\n\n const handleHeaderClick = useCallback(() => {\n openChatWithInfo({ id: chatId });\n }, [openChatWithInfo, chatId]);\n\n const handleUnpinMessage = useCallback((messageId: number) => {\n pinMessage({ chatId, messageId, isUnpin: true });\n }, [pinMessage, chatId]);\n\n const handlePinnedMessageClick = useCallback((): void => {\n if (pinnedMessage) {\n focusMessage({ chatId: pinnedMessage.chatId, threadId, messageId: pinnedMessage.id });\n\n const newIndex = cycleRestrict(pinnedMessagesCount, pinnedMessageIndex + 1);\n setPinnedMessageIndex(newIndex);\n }\n }, [pinnedMessage, focusMessage, threadId, pinnedMessagesCount, pinnedMessageIndex]);\n\n const handleAllPinnedClick = useCallback(() => {\n openChat({ id: chatId, threadId: MAIN_THREAD_ID, type: 'pinned' });\n }, [openChat, chatId]);\n\n const handleBackClick = useCallback(() => {\n if (IS_MOBILE_SCREEN) {\n const messageInput = document.getElementById(EDITABLE_INPUT_ID);\n if (messageInput) {\n messageInput.blur();\n }\n }\n if (threadId === MAIN_THREAD_ID && messageListType === 'thread') {\n if (IS_MOBILE_SCREEN) {\n openChat({ id: undefined });\n } else {\n toggleLeftColumn();\n }\n\n return;\n }\n\n if (messageListType === 'scheduled' && isSelectModeActive) {\n exitMessageSelectMode();\n }\n openChat({ id: originChatId, threadId: MAIN_THREAD_ID });\n }, [openChat, originChatId, threadId, messageListType, toggleLeftColumn, isSelectModeActive, exitMessageSelectMode]);\n\n const unreadCount = useMemo(() => {\n if (!isLeftColumnHideable || !chatsById) {\n return undefined;\n }\n\n let isActive = false;\n\n const totalCount = Object.values(chatsById).reduce((total, chat) => {\n if (isChatArchived(chat)) {\n return total;\n }\n\n const count = chat.unreadCount || 0;\n if (count && (!chat.isMuted || chat.unreadMentionsCount)) {\n isActive = true;\n }\n\n return total + count;\n }, 0);\n\n if (!totalCount) {\n return undefined;\n }\n\n return {\n isActive,\n totalCount,\n };\n }, [isLeftColumnHideable, chatsById]);\n\n const canToolsCollideWithChatInfo = (\n windowWidth >= MIN_SCREEN_WIDTH_FOR_STATIC_LEFT_COLUMN\n && windowWidth < SAFE_SCREEN_WIDTH_FOR_CHAT_INFO\n ) || (\n windowWidth > MOBILE_SCREEN_MAX_WIDTH\n && windowWidth < MIN_SCREEN_WIDTH_FOR_STATIC_LEFT_COLUMN\n && (!chatTitleLength || chatTitleLength > 30)\n );\n const shouldUseStackedToolsClass = canToolsCollideWithChatInfo || (\n windowWidth > MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN\n && windowWidth < SAFE_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN\n );\n\n const {\n shouldRender: shouldRenderAudioPlayer,\n transitionClassNames: audioPlayerClassNames,\n } = useShowTransition(Boolean(audioMessage));\n\n const renderingAudioMessage = useCurrentOrPrev(audioMessage);\n\n const {\n shouldRender: shouldRenderPinnedMessage,\n transitionClassNames: pinnedMessageClassNames,\n } = useShowTransition(pinnedMessage && !shouldRenderAudioPlayer);\n\n const renderingPinnedMessage = useCurrentOrPrev(pinnedMessage);\n const renderingPinnedMessageTitle = useCurrentOrPrev(topMessageTitle);\n\n const canRevealTools = (shouldRenderPinnedMessage && renderingPinnedMessage)\n || (shouldRenderAudioPlayer && renderingAudioMessage);\n\n // Logic for transition to and from custom display of AudioPlayer/PinnedMessage on smaller screens\n useEffect(() => {\n const componentEl = componentRef.current;\n if (!componentEl) {\n return;\n }\n\n if (!shouldUseStackedToolsClass || !canRevealTools) {\n componentEl.classList.remove('tools-stacked', 'animated');\n shouldAnimateTools.current = true;\n return;\n }\n\n if (isRightColumnShown || canToolsCollideWithChatInfo) {\n if (shouldAnimateTools.current) {\n componentEl.classList.add('tools-stacked', 'animated');\n shouldAnimateTools.current = false;\n }\n\n // Remove animation class to prevent it messing up the show transitions\n setTimeout(() => {\n componentEl.classList.remove('animated');\n }, ANIMATION_DURATION);\n } else {\n componentEl.classList.remove('tools-stacked');\n shouldAnimateTools.current = true;\n }\n }, [shouldUseStackedToolsClass, canRevealTools, canToolsCollideWithChatInfo, isRightColumnShown]);\n\n const lang = useLang();\n\n function renderInfo() {\n return (\n messageListType === 'thread' && threadId === MAIN_THREAD_ID ? (\n renderMainThreadInfo()\n ) : messageListType === 'thread' ? (\n <>\n {renderBackButton()}\n <h3>\n {lang('CommentsCount', messagesCount)}\n </h3>\n </>\n ) : messageListType === 'pinned' ? (\n <>\n {renderBackButton()}\n <h3>\n {lang('PinnedMessagesCount', messagesCount)}\n </h3>\n </>\n ) : messageListType === 'scheduled' ? (\n <>\n {renderBackButton()}\n <h3>\n {isChatWithSelf ? lang('Reminders') : lang('messages', messagesCount)}\n </h3>\n </>\n ) : undefined\n );\n }\n\n function renderMainThreadInfo() {\n return (\n <>\n {isLeftColumnHideable && renderBackButton(shouldShowCloseButton, unreadCount)}\n <div className=\"chat-info-wrapper\" onClick={handleHeaderClick}>\n {isChatPrivate(chatId) ? (\n <PrivateChatInfo\n userId={chatId}\n typingStatus={typingStatus}\n withFullInfo={isChatWithBot}\n withMediaViewer\n withUpdatingStatus\n />\n ) : (\n <GroupChatInfo\n chatId={chatId}\n typingStatus={typingStatus}\n withMediaViewer\n withFullInfo\n withUpdatingStatus\n />\n )}\n </div>\n </>\n );\n }\n\n function renderBackButton(asClose = false, unreadCountInfo?: typeof unreadCount) {\n return (\n <div className=\"back-button\">\n <Button\n round\n size=\"smaller\"\n color=\"translucent\"\n onClick={handleBackClick}\n ariaLabel={asClose ? 'Close' : 'Back'}\n >\n <div className={buildClassName('animated-close-icon', !asClose && 'state-back')} />\n </Button>\n {unreadCountInfo && (\n <div className={`unread-count ${unreadCountInfo.isActive ? 'active' : ''}`}>\n {formatIntegerCompact(unreadCountInfo.totalCount)}\n </div>\n )}\n </div>\n );\n }\n\n return (\n <div className=\"MiddleHeader\" ref={componentRef}>\n <Transition name=\"slide-fade\" activeKey={messageListType === 'thread' ? threadId : 1}>\n {renderInfo}\n </Transition>\n\n <div className=\"header-tools\">\n {shouldRenderPinnedMessage && renderingPinnedMessage && !shouldRenderAudioPlayer && (\n <HeaderPinnedMessage\n key={chatId}\n message={renderingPinnedMessage}\n count={pinnedMessagesCount}\n index={pinnedMessageIndex}\n customTitle={renderingPinnedMessageTitle}\n className={pinnedMessageClassNames}\n onUnpinMessage={canUnpin ? handleUnpinMessage : undefined}\n onClick={handlePinnedMessageClick}\n onAllPinnedClick={handleAllPinnedClick}\n />\n )}\n {shouldRenderAudioPlayer && renderingAudioMessage && (\n <AudioPlayer\n key={getMessageKey(renderingAudioMessage)}\n message={renderingAudioMessage!}\n className={audioPlayerClassNames}\n />\n )}\n <HeaderActions\n chatId={chatId}\n threadId={threadId}\n messageListType={messageListType}\n />\n </div>\n </div>\n );\n};\n\nexport default memo(withGlobal<OwnProps>(\n (global, { chatId, threadId, messageListType }): StateProps => {\n const { isLeftColumnShown, lastSyncTime } = global;\n const { byId: chatsById } = global.chats;\n const chat = selectChat(global, chatId);\n\n const { typingStatus } = chat || {};\n\n const { chatId: audioChatId, messageId: audioMessageId } = global.audioPlayer;\n const audioMessage = audioChatId && audioMessageId\n ? selectChatMessage(global, audioChatId, audioMessageId)\n : undefined;\n\n const originChat = selectThreadOriginChat(global, chatId, threadId);\n\n let messagesCount: number | undefined;\n if (messageListType === 'pinned') {\n const pinnedIds = selectPinnedIds(global, chatId);\n messagesCount = pinnedIds && pinnedIds.length;\n } else if (messageListType === 'scheduled') {\n const scheduledIds = selectScheduledIds(global, chatId);\n messagesCount = scheduledIds && scheduledIds.length;\n } else if (messageListType === 'thread' && threadId !== MAIN_THREAD_ID) {\n const threadInfo = selectThreadInfo(global, chatId, threadId);\n if (threadInfo) {\n messagesCount = threadInfo.messagesCount;\n }\n }\n\n let state: StateProps = {\n typingStatus,\n isLeftColumnShown,\n isRightColumnShown: selectIsRightColumnShown(global),\n isSelectModeActive: selectIsInSelectMode(global),\n audioMessage,\n chatTitleLength: chat && getChatTitle(chat).length,\n chatsById,\n originChatId: originChat ? originChat.id : chatId,\n messagesCount,\n isChatWithSelf: selectIsChatWithSelf(global, chatId),\n isChatWithBot: chat && selectIsChatWithBot(global, chat),\n lastSyncTime,\n };\n\n const messagesById = selectChatMessages(global, chatId);\n if (messageListType === 'thread' && messagesById) {\n if (threadId === MAIN_THREAD_ID) {\n const pinnedMessageIds = selectPinnedIds(global, chatId);\n\n if (pinnedMessageIds && pinnedMessageIds.length) {\n const firstPinnedMessage = messagesById[pinnedMessageIds[0]];\n const {\n canUnpin,\n } = (firstPinnedMessage && selectAllowedMessageActions(global, firstPinnedMessage, threadId)) || {};\n state = {\n ...state,\n pinnedMessageIds,\n messagesById,\n canUnpin,\n };\n }\n } else {\n const pinnedMessageId = selectThreadTopMessageId(global, chatId, threadId);\n const message = pinnedMessageId ? selectChatMessage(global, chatId, pinnedMessageId) : undefined;\n const sender = message ? selectForwardedSender(global, message) : undefined;\n const topMessageTitle = sender ? getSenderTitle(sender) : undefined;\n\n state = {\n ...state,\n pinnedMessageIds: pinnedMessageId,\n messagesById,\n canUnpin: false,\n topMessageTitle,\n };\n }\n }\n\n return state;\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'openChatWithInfo',\n 'pinMessage',\n 'focusMessage',\n 'openChat',\n 'loadPinnedMessages',\n 'toggleLeftColumn',\n 'exitMessageSelectMode',\n ]),\n)(MiddleHeader));\n","import { ApiMessage } from '../../../api/types';\nimport { IAlbum } from '../../../types';\n\nimport { getDayStart } from '../../../util/dateFormat';\nimport { isActionMessage } from '../../../modules/helpers';\n\ntype SenderGroup = (ApiMessage | IAlbum)[];\n\nexport type MessageDateGroup = {\n originalDate: number;\n datetime: number;\n senderGroups: SenderGroup[];\n};\n\nexport function isAlbum(messageOrAlbum: ApiMessage | IAlbum): messageOrAlbum is IAlbum {\n return 'albumId' in messageOrAlbum;\n}\n\nexport function groupMessages(messages: ApiMessage[], firstUnreadId?: number) {\n let currentSenderGroup: SenderGroup = [];\n let currentDateGroup = {\n originalDate: messages[0].date,\n datetime: Number(getDayStart(messages[0].date * 1000)),\n senderGroups: [currentSenderGroup],\n };\n let currentAlbum: IAlbum | undefined;\n\n const dateGroups: MessageDateGroup[] = [currentDateGroup];\n\n messages.forEach((message, index) => {\n if (message.isInAlbum) {\n if (!currentAlbum) {\n currentAlbum = {\n albumId: message.groupedId!,\n messages: [message],\n mainMessage: message,\n };\n } else {\n currentAlbum.messages.push(message);\n if (message.content.text) {\n currentAlbum.mainMessage = message;\n }\n }\n } else {\n currentSenderGroup.push(message);\n }\n\n const nextMessage = messages[index + 1];\n\n if (\n currentAlbum\n && (!nextMessage || !nextMessage.groupedId || nextMessage.groupedId !== currentAlbum.albumId)\n ) {\n currentSenderGroup.push(currentAlbum);\n currentAlbum = undefined;\n }\n if (nextMessage) {\n const nextMessageDatetime = Number(getDayStart(nextMessage.date * 1000));\n if (currentDateGroup.datetime !== nextMessageDatetime) {\n currentDateGroup = {\n originalDate: nextMessage.date,\n datetime: nextMessageDatetime,\n senderGroups: [],\n };\n dateGroups.push(currentDateGroup);\n\n currentSenderGroup = [];\n currentDateGroup.senderGroups.push(currentSenderGroup);\n } else if (\n nextMessage.id === firstUnreadId\n || message.senderId !== nextMessage.senderId\n || message.isOutgoing !== nextMessage.isOutgoing\n || isActionMessage(message)\n || isActionMessage(nextMessage)\n || (\n message.forwardInfo && nextMessage.forwardInfo\n && (\n message.forwardInfo.senderUserId !== nextMessage.forwardInfo.senderUserId\n || message.forwardInfo.fromChatId !== nextMessage.forwardInfo.fromChatId\n || message.forwardInfo.hiddenUserName !== nextMessage.forwardInfo.hiddenUserName\n )\n )\n || message.inlineButtons\n || nextMessage.inlineButtons\n ) {\n currentSenderGroup = [];\n currentDateGroup.senderGroups.push(currentSenderGroup);\n }\n }\n });\n\n return dateGroups;\n}\n","import { useCallback } from '../../../lib/teact/teact';\n\nimport { fastRaf } from '../../../util/schedulers';\nimport useDebounce from '../../../hooks/useDebounce';\nimport useFlag from '../../../hooks/useFlag';\n\nconst DEBOUNCE = 1000;\nconst STICKY_TOP = 10;\nconst STICKY_TOP_WITH_TOOLS = 60;\n\nexport default function useStickyDates() {\n // For some reason we can not synchronously hide a sticky element (from `useLayoutEffect`) when chat opens\n // so we will add `position: sticky` only after first scroll. There would be no animation on the first show though.\n const [isScrolled, markIsScrolled] = useFlag(false);\n\n const runDebounced = useDebounce(DEBOUNCE, false);\n\n const updateStickyDates = useCallback((container: HTMLDivElement, hasTools?: boolean) => {\n markIsScrolled();\n\n if (!document.body.classList.contains('is-scrolling-messages')) {\n fastRaf(() => {\n document.body.classList.add('is-scrolling-messages');\n });\n }\n\n runDebounced(() => {\n fastRaf(() => {\n const currentStuck = document.querySelector('.stuck');\n if (currentStuck) {\n currentStuck.classList.remove('stuck');\n }\n\n const stuckDateEl = findStuckDate(container, hasTools);\n if (stuckDateEl) {\n stuckDateEl.classList.add('stuck');\n }\n\n document.body.classList.remove('is-scrolling-messages');\n });\n });\n }, [markIsScrolled, runDebounced]);\n\n return {\n isScrolled,\n updateStickyDates,\n };\n}\n\nfunction findStuckDate(container: HTMLElement, hasTools?: boolean) {\n const allElements = container.querySelectorAll<HTMLDivElement>('.sticky-date');\n const containerTop = container.scrollTop;\n\n return Array.from(allElements).find((el) => {\n const { offsetTop, offsetHeight } = el;\n const top = offsetTop - containerTop;\n return -offsetHeight <= top && top <= (hasTools ? STICKY_TOP_WITH_TOOLS : STICKY_TOP);\n });\n}\n","import { useMemo } from '../lib/teact/teact';\n\nimport { debounce } from '../util/schedulers';\n\nexport default function useDebounce(ms: number, shouldRunFirst?: boolean, shouldRunLast?: boolean) {\n return useMemo(() => {\n return debounce((cb) => cb(), ms, shouldRunFirst, shouldRunLast);\n }, [ms, shouldRunFirst, shouldRunLast]);\n}\n","import { MutableRefObject } from 'react';\nimport React, {\n FC, useCallback, useEffect, useRef,\n} from '../../lib/teact/teact';\n\nimport { MESSAGE_LIST_SENSITIVE_AREA } from '../../config';\nimport resetScroll from '../../util/resetScroll';\nimport { useIntersectionObserver, useOnIntersect } from '../../hooks/useIntersectionObserver';\nimport useOnChange from '../../hooks/useOnChange';\n\ntype OwnProps = {\n containerRef: MutableRefObject<HTMLDivElement | null>;\n className: string;\n messageIds: number[];\n containerHeight?: number;\n listItemElementsRef: MutableRefObject<HTMLDivElement[] | undefined>;\n anchorIdRef: MutableRefObject<string | undefined>;\n anchorTopRef: MutableRefObject<number | undefined>;\n loadMoreForwards?: NoneToVoidFunction;\n loadMoreBackwards?: NoneToVoidFunction;\n isViewportNewest?: boolean;\n firstUnreadId?: number;\n focusingId?: number;\n onFabToggle: AnyToVoidFunction;\n children: any;\n};\n\nconst FAB_THRESHOLD = 50;\nconst FAB_FREEZE_TIMEOUT = 100;\n\n// Local flag is used because `freeze/unfreeze` methods are controlled by heavy animation\nlet isFabFrozen = false;\n\nconst MessageScroll: FC<OwnProps> = ({\n containerRef,\n className,\n messageIds,\n containerHeight,\n listItemElementsRef,\n focusingId,\n anchorIdRef,\n anchorTopRef,\n loadMoreForwards,\n loadMoreBackwards,\n isViewportNewest,\n firstUnreadId,\n onFabToggle,\n children,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const backwardsTriggerRef = useRef<HTMLDivElement>(null);\n // eslint-disable-next-line no-null/no-null\n const forwardsTriggerRef = useRef<HTMLDivElement>(null);\n // eslint-disable-next-line no-null/no-null\n const fabTriggerRef = useRef<HTMLDivElement>(null);\n\n const updateFabVisibility = useCallback(() => {\n if (isFabFrozen) {\n return;\n }\n\n if (!messageIds || !messageIds.length) {\n onFabToggle(false);\n return;\n }\n\n if (!isViewportNewest) {\n onFabToggle(true);\n return;\n }\n\n const { offsetHeight, scrollHeight, scrollTop } = containerRef.current!;\n const scrollBottom = scrollHeight - scrollTop - offsetHeight;\n const isNearBottom = scrollBottom <= FAB_THRESHOLD;\n const isAtBottom = scrollBottom === 0;\n\n onFabToggle(firstUnreadId ? !isAtBottom : !isNearBottom);\n }, [messageIds, isViewportNewest, containerRef, onFabToggle, firstUnreadId]);\n\n const {\n observe: observeIntersection,\n freeze: freezeForLoadMore,\n unfreeze: unfreezeForLoadMore,\n } = useIntersectionObserver({\n rootRef: containerRef,\n margin: MESSAGE_LIST_SENSITIVE_AREA,\n }, (entries) => {\n if (!loadMoreForwards || !loadMoreBackwards) {\n return;\n }\n\n const triggerEntry = entries.find(({ isIntersecting }) => isIntersecting);\n if (!triggerEntry) {\n return;\n }\n\n const { target } = triggerEntry;\n\n if (target.className === 'backwards-trigger') {\n resetScroll(containerRef.current!);\n loadMoreBackwards();\n } else if (target.className === 'forwards-trigger' && (target as HTMLDivElement).dataset.isActive) {\n resetScroll(containerRef.current!);\n loadMoreForwards();\n }\n });\n\n useOnIntersect(backwardsTriggerRef, observeIntersection);\n useOnIntersect(forwardsTriggerRef, observeIntersection);\n\n const {\n observe: observeIntersectionForFab,\n freeze: freezeForFab,\n unfreeze: unfreezeForFab,\n } = useIntersectionObserver({\n rootRef: containerRef,\n margin: FAB_THRESHOLD,\n }, ([{ target }]) => {\n if ((target as HTMLDivElement).dataset.isActive) {\n updateFabVisibility();\n }\n });\n\n useOnIntersect(fabTriggerRef, observeIntersectionForFab);\n\n // Do not load more and show FAB when focusing\n useOnChange(() => {\n if (focusingId) {\n freezeForLoadMore();\n freezeForFab();\n } else {\n unfreezeForFab();\n unfreezeForLoadMore();\n }\n }, [focusingId]);\n\n // Remember scroll position before updating height\n useOnChange(() => {\n if (!listItemElementsRef.current) {\n return;\n }\n\n const preservedItemElements = listItemElementsRef.current\n .filter((element) => messageIds.includes(Number(element.dataset.messageId)));\n\n // We avoid the very first item as it may be a partly-loaded album\n // and also because it may be removed when messages limit is reached\n const anchor = preservedItemElements[1] || preservedItemElements[0];\n if (!anchor) {\n return;\n }\n\n anchorIdRef.current = anchor.id;\n anchorTopRef.current = anchor.getBoundingClientRect().top;\n }, [messageIds, containerHeight]);\n\n // Workaround for FAB flickering with tall incoming message\n useOnChange(() => {\n isFabFrozen = true;\n\n setTimeout(() => {\n isFabFrozen = false;\n }, FAB_FREEZE_TIMEOUT);\n }, [messageIds]);\n\n // Workaround for stuck FAB when many unread messages\n useEffect(updateFabVisibility, [firstUnreadId]);\n\n return (\n <div className={className} teactFastList>\n <div ref={backwardsTriggerRef} key=\"backwards-trigger\" className=\"backwards-trigger\" />\n {children}\n <div\n ref={forwardsTriggerRef}\n key=\"forwards-trigger\"\n className=\"forwards-trigger\"\n data-is-active={!isViewportNewest}\n />\n <div\n ref={fabTriggerRef}\n key=\"fab-trigger\"\n className=\"fab-trigger\"\n data-is-active={isViewportNewest}\n />\n </div>\n );\n};\n\nexport default MessageScroll;\n","import { ApiMessage } from '../../../../api/types';\n\nimport { getMessageContent } from '../../../../modules/helpers';\n\nexport function isEmojiOnlyMessage(customShape?: boolean | number) {\n return typeof customShape === 'number';\n}\n\nexport function buildContentClassName(\n message: ApiMessage,\n {\n hasReply,\n customShape,\n isLastInGroup,\n asForwarded,\n hasThread,\n forceSenderName,\n hasComments,\n }: {\n hasReply?: boolean;\n customShape?: boolean | number;\n isLastInGroup?: boolean;\n asForwarded?: boolean;\n hasThread?: boolean;\n forceSenderName?: boolean;\n hasComments?: boolean;\n } = {},\n) {\n const {\n text, photo, video, audio, voice, document, poll, webPage, contact,\n } = getMessageContent(message);\n\n const classNames = ['message-content'];\n const isMediaWithNoText = (photo || video) && !text;\n const isViaBot = Boolean(message.viaBotId);\n\n if (isEmojiOnlyMessage(customShape)) {\n classNames.push(`emoji-only emoji-only-${customShape}`);\n } else if (text) {\n classNames.push('text');\n }\n\n if (customShape) {\n classNames.push('custom-shape');\n if (video && video.isRound) {\n classNames.push('round');\n }\n\n if (hasComments) {\n classNames.push('has-comments');\n }\n }\n if (photo || video) {\n classNames.push('media');\n } else if (audio) {\n classNames.push('audio');\n } else if (voice) {\n classNames.push('voice');\n } else if (document) {\n classNames.push('document');\n } else if (contact) {\n classNames.push('contact');\n } else if (poll) {\n classNames.push('poll');\n } else if (webPage) {\n classNames.push('web-page');\n\n if (webPage.photo) {\n classNames.push('media');\n }\n }\n\n if (asForwarded && !customShape) {\n classNames.push('is-forwarded');\n }\n\n if (hasReply) {\n classNames.push('is-reply');\n }\n\n if (hasThread) {\n classNames.push('has-replies');\n }\n\n if (isViaBot) {\n classNames.push('is-via-bot');\n }\n\n if (forceSenderName) {\n classNames.push('force-sender-name');\n }\n\n if (!customShape) {\n classNames.push('has-shadow');\n\n if (hasReply || asForwarded || !isMediaWithNoText || isViaBot || forceSenderName) {\n classNames.push('has-solid-background');\n }\n\n if (isLastInGroup && (photo || !isMediaWithNoText)) {\n classNames.push('has-appendix');\n }\n }\n\n return classNames.join(' ');\n}\n","import { ApiMessage } from '../../../../api/types';\nimport { calculateInlineImageDimensions, calculateVideoDimensions } from '../../../common/helpers/mediaDimensions';\nimport {\n getMessageText,\n getMessagePhoto,\n getMessageWebPagePhoto,\n isForwardedMessage,\n isOwnMessage,\n getMessageVideo,\n} from '../../../../modules/helpers';\n\nconst MIN_MEDIA_WIDTH = 100;\nconst MIN_MEDIA_WIDTH_WITH_TEXT = 175;\nconst MIN_MEDIA_HEIGHT = 90;\nconst SMALL_IMAGE_THRESHOLD = 12;\n\nexport function getMinMediaWidth(hasText?: boolean) {\n return hasText ? MIN_MEDIA_WIDTH_WITH_TEXT : MIN_MEDIA_WIDTH;\n}\n\nexport function calculateMediaDimensions(message: ApiMessage) {\n const isOwn = isOwnMessage(message);\n const isForwarded = isForwardedMessage(message);\n const photo = getMessagePhoto(message) || getMessageWebPagePhoto(message);\n const video = getMessageVideo(message);\n\n const isWebPagePhoto = Boolean(getMessageWebPagePhoto(message));\n const { width, height } = photo\n ? calculateInlineImageDimensions(photo, isOwn, isForwarded, isWebPagePhoto)\n : calculateVideoDimensions(video!, isOwn, isForwarded);\n\n const hasText = Boolean(getMessageText(message));\n const minMediaWidth = getMinMediaWidth(hasText);\n\n let stretchFactor = 1;\n if (width < minMediaWidth && minMediaWidth - width < SMALL_IMAGE_THRESHOLD) {\n stretchFactor = minMediaWidth / width;\n }\n if (height * stretchFactor < MIN_MEDIA_HEIGHT && MIN_MEDIA_HEIGHT - height * stretchFactor < SMALL_IMAGE_THRESHOLD) {\n stretchFactor = MIN_MEDIA_HEIGHT / height;\n }\n\n const finalWidth = Math.round(width * stretchFactor);\n const finalHeight = Math.round(height * stretchFactor);\n\n return {\n width: finalWidth,\n height: finalHeight,\n isSmall: finalWidth < minMediaWidth || finalHeight < MIN_MEDIA_HEIGHT,\n };\n}\n","/* eslint-disable no-bitwise */\n// Based on\n// https://github.com/telegramdesktop/tdesktop/blob/dev/Telegram/SourceFiles/ui/grouped_layout.cpp\n// https://github.com/overtake/TelegramSwift/blob/master/Telegram-Mac/GroupedLayout.swift#L83\n\nimport { IAlbum } from '../../../../types';\nimport { ApiMessage } from '../../../../api/types';\nimport { IDimensions } from '../../../../modules/helpers';\n\nimport { MOBILE_SCREEN_MAX_WIDTH } from '../../../../config';\nimport { REM } from '../../../common/helpers/mediaDimensions';\nimport { calculateMediaDimensions } from './mediaDimensions';\n\nconst MAX_WIDTH_MOBILE_VW = 69;\nconst MAX_WIDTH_DESK_OWN_REM = 30;\nconst MAX_WIDTH_DESK_REM = 29;\nexport const AlbumRectPart = {\n None: 0,\n Top: 1,\n Right: 2,\n Bottom: 4,\n Left: 8,\n};\n\ntype IAttempt = {\n lineCounts: number[];\n heights: number[];\n};\nexport type IMediaDimensions = {\n width: number;\n height: number;\n x: number;\n y: number;\n};\ntype IMediaLayout = {\n dimensions: IMediaDimensions;\n sides: number;\n};\ntype ILayoutParams = {\n ratios: number[];\n proportions: string;\n averageRatio: number;\n maxWidth: number;\n minWidth: number;\n maxHeight: number;\n spacing: number;\n};\nexport type IAlbumLayout = {\n layout: IMediaLayout[];\n containerStyle: IDimensions;\n};\n\nfunction getMaxWidth(isOwn: boolean, isForwarded: boolean, windowWidth: number) {\n if (windowWidth <= MOBILE_SCREEN_MAX_WIDTH) {\n return (windowWidth / 100) * MAX_WIDTH_MOBILE_VW - (isForwarded ? 1.625 : 0) * REM;\n }\n\n const maxWidth = isOwn ? MAX_WIDTH_DESK_OWN_REM : MAX_WIDTH_DESK_REM;\n\n return (maxWidth - (isForwarded ? 1.625 : 0)) * REM;\n}\n\nfunction getRatios(messages: ApiMessage[]) {\n return messages.map(\n (message) => {\n const dimensions = calculateMediaDimensions(message) as IDimensions;\n\n return dimensions.width / dimensions.height;\n },\n );\n}\n\nfunction getProportions(ratios: number[]) {\n return ratios.map((ratio) => (ratio > 1.2 ? 'w' : (ratio < 0.8 ? 'n' : 'q'))).join('');\n}\n\nfunction getAverageRatio(ratios: number[]) {\n return ratios.reduce((result, ratio) => ratio + result, 1) / ratios.length;\n}\n\nfunction accumulate(list: number[], initValue: number) {\n return list.reduce((accumulator, item) => accumulator + item, initValue);\n}\n\nfunction clamp(num: number, low: number, high: number) {\n return num < low ? low : (num > high ? high : num);\n}\n\nfunction cropRatios(ratios: number[], averageRatio: number) {\n return ratios.map((ratio) => (averageRatio > 1.1 ? clamp(ratio, 1, 2.75) : clamp(ratio, 0.6667, 1)));\n}\n\nfunction calculateContainerSize(layout: IMediaLayout[]) {\n const styles: IDimensions = { width: 0, height: 0 };\n layout.forEach(({\n dimensions,\n sides,\n }) => {\n if (sides & AlbumRectPart.Right) {\n styles.width = dimensions.width + dimensions.x;\n }\n if (sides & AlbumRectPart.Bottom) {\n styles.height = dimensions.height + dimensions.y;\n }\n });\n\n return styles;\n}\n\nexport function calculateAlbumLayout(\n isOwn: boolean,\n isForwarded: boolean,\n album: IAlbum,\n windowWidth: number,\n): IAlbumLayout {\n const spacing = 2;\n const ratios = getRatios(album.messages);\n const proportions = getProportions(ratios);\n const averageRatio = getAverageRatio(ratios);\n const albumCount = ratios.length;\n const forceCalc = ratios.some((ratio) => ratio > 2);\n const maxWidth = getMaxWidth(isOwn, isForwarded, windowWidth);\n const maxHeight = maxWidth;\n\n let layout;\n\n const params = {\n ratios,\n proportions,\n averageRatio,\n maxWidth,\n minWidth: 100,\n maxHeight,\n spacing,\n };\n\n if (albumCount >= 5 || forceCalc) {\n layout = layoutWithComplexLayouter(params);\n } else if (albumCount === 2) {\n layout = layoutTwo(params);\n } else if (albumCount === 3) {\n layout = layoutThree(params);\n } else {\n layout = layoutFour(params);\n }\n\n return {\n layout,\n containerStyle: calculateContainerSize(layout),\n };\n}\n\nfunction layoutWithComplexLayouter({\n ratios: originalRatios,\n averageRatio,\n maxWidth,\n minWidth,\n spacing,\n maxHeight = (4 * maxWidth) / 3,\n}: ILayoutParams) {\n const ratios = cropRatios(originalRatios, averageRatio);\n const count = originalRatios.length;\n const result = new Array(count);\n const attempts: IAttempt[] = [];\n\n const multiHeight = (offset: number, attemptCount: number) => {\n const attemptRatios = ratios.slice(offset, offset + attemptCount);\n const sum = accumulate(attemptRatios, 0);\n\n return (maxWidth - (attemptCount - 1) * spacing) / sum;\n };\n\n const pushAttempt = (lineCounts: number[]) => {\n const heights: number[] = [];\n let offset = 0;\n lineCounts.forEach((currentCount) => {\n heights.push(multiHeight(offset, currentCount));\n offset += currentCount;\n });\n\n attempts.push({\n lineCounts,\n heights,\n });\n };\n\n for (let first = 1; first !== count; ++first) {\n const second = count - first;\n if (first <= 3 && second <= 3) {\n pushAttempt([first, second]);\n }\n }\n\n for (let first = 1; first !== count - 1; ++first) {\n for (let second = 1; second !== count - first; ++second) {\n const third = count - first - second;\n if (first <= 3 && second <= (averageRatio < 0.85 ? 4 : 3) && third <= 3) {\n pushAttempt([first, second, third]);\n }\n }\n }\n\n for (let first = 1; first !== count - 1; ++first) {\n for (let second = 1; second !== count - first; ++second) {\n for (let third = 1; third !== count - first - second; ++third) {\n const fourth = count - first - second - third;\n if (first <= 3 && second <= 3 && third <= 3 && fourth <= 4) {\n pushAttempt([first, second, third, fourth]);\n }\n }\n }\n }\n\n let optimalAttempt: IAttempt | undefined;\n let optimalDiff = 0;\n for (let i = 0; i < attempts.length; i++) {\n const {\n heights,\n lineCounts,\n } = attempts[i];\n const lineCount = lineCounts.length;\n const totalHeight = accumulate(heights, 0) + spacing * (lineCount - 1);\n const minLineHeight = Math.min(...heights);\n const bad1 = minLineHeight < minWidth ? 1.5 : 1;\n const bad2 = (() => {\n for (let line = 1; line !== lineCount; ++line) {\n if (lineCounts[line - 1] > lineCounts[line]) {\n return 1.5;\n }\n }\n\n return 1;\n })();\n const diff = Math.abs(totalHeight - maxHeight) * bad1 * bad2;\n\n if (!optimalAttempt || diff < optimalDiff) {\n optimalAttempt = attempts[i];\n optimalDiff = diff;\n }\n }\n\n const optimalCounts = optimalAttempt!.lineCounts;\n const optimalHeights = optimalAttempt!.heights;\n const rowCount = optimalCounts.length;\n let index = 0;\n let y = 0;\n for (let row = 0; row !== rowCount; ++row) {\n const colCount = optimalCounts[row];\n const lineHeight = optimalHeights[row];\n const height = Math.round(lineHeight);\n let x = 0;\n\n for (let col = 0; col !== colCount; ++col) {\n const sides = AlbumRectPart.None\n | (row === 0 ? AlbumRectPart.Top : AlbumRectPart.None)\n | (row === rowCount - 1 ? AlbumRectPart.Bottom : AlbumRectPart.None)\n | (col === 0 ? AlbumRectPart.Left : AlbumRectPart.None)\n | (col === colCount - 1 ? AlbumRectPart.Right : AlbumRectPart.None);\n const ratio = ratios[index];\n const width = col === colCount - 1 ? maxWidth - x : Math.round(ratio * lineHeight);\n result[index] = {\n dimensions: {\n x,\n y,\n width,\n height,\n },\n sides,\n };\n x += width + spacing;\n ++index;\n }\n y += height + spacing;\n }\n\n return result;\n}\n\n\nfunction layoutTwo(params: ILayoutParams) {\n const {\n ratios,\n proportions,\n averageRatio,\n } = params;\n return proportions === 'ww' && averageRatio > 1.4 && ratios[1] - ratios[0] < 0.2\n ? layoutTwoTopBottom(params)\n : proportions === 'ww' || proportions === 'qq'\n ? layoutTwoLeftRightEqual(params)\n : layoutTwoLeftRight(params);\n}\n\nfunction layoutTwoTopBottom(params: ILayoutParams) {\n const {\n ratios,\n maxWidth,\n spacing,\n maxHeight,\n } = params;\n const height = Math.round(Math.min(maxWidth / ratios[0], Math.min(maxWidth / ratios[1], (maxHeight - spacing) / 2)));\n\n return [{\n dimensions: {\n x: 0,\n y: 0,\n width: maxWidth,\n height,\n },\n sides: AlbumRectPart.Left | AlbumRectPart.Top | AlbumRectPart.Right,\n }, {\n dimensions: {\n x: 0,\n y: height + spacing,\n width: maxWidth,\n height,\n },\n sides: AlbumRectPart.Left | AlbumRectPart.Bottom | AlbumRectPart.Right,\n }];\n}\n\nfunction layoutTwoLeftRightEqual(params: ILayoutParams) {\n const {\n ratios,\n maxWidth,\n spacing,\n maxHeight,\n } = params;\n const width = (maxWidth - spacing) / 2;\n const height = Math.round(Math.min(width / ratios[0], Math.min(width / ratios[1], maxHeight)));\n return [{\n dimensions: {\n x: 0,\n y: 0,\n width,\n height,\n },\n sides: AlbumRectPart.Top | AlbumRectPart.Left | AlbumRectPart.Bottom,\n }, {\n dimensions: {\n x: width + spacing,\n y: 0,\n width,\n height,\n },\n sides: AlbumRectPart.Top | AlbumRectPart.Right | AlbumRectPart.Bottom,\n }];\n}\n\nfunction layoutTwoLeftRight(params: ILayoutParams) {\n const {\n ratios,\n minWidth,\n maxWidth,\n spacing,\n maxHeight,\n } = params;\n const minimalWidth = Math.round(1.5 * minWidth);\n const secondWidth = Math.min(\n Math.round(\n Math.max(\n 0.4 * (maxWidth - spacing),\n (maxWidth - spacing) / ratios[0] / (1 / ratios[0] + 1 / ratios[1]),\n ),\n ),\n maxWidth - spacing - minimalWidth,\n );\n const firstWidth = maxWidth - secondWidth - spacing;\n const height = Math.min(maxHeight, Math.round(Math.min(firstWidth / ratios[0], secondWidth / ratios[1])));\n\n return [{\n dimensions: {\n x: 0,\n y: 0,\n width: firstWidth,\n height,\n },\n sides: AlbumRectPart.Top | AlbumRectPart.Left | AlbumRectPart.Bottom,\n }, {\n dimensions: {\n x: firstWidth + spacing,\n y: 0,\n width: secondWidth,\n height,\n },\n sides: AlbumRectPart.Top | AlbumRectPart.Right | AlbumRectPart.Bottom,\n }];\n}\n\nfunction layoutThree(params: ILayoutParams) {\n const { proportions } = params;\n\n return proportions[0] === 'n'\n ? layoutThreeLeftAndOther(params)\n : layoutThreeTopAndOther(params);\n}\n\nfunction layoutThreeLeftAndOther(params: ILayoutParams) {\n const {\n maxHeight,\n spacing,\n ratios,\n maxWidth,\n minWidth,\n } = params;\n const firstHeight = maxHeight;\n const thirdHeight = Math.round(\n Math.min(\n (maxHeight - spacing) / 2,\n (ratios[1] * (maxWidth - spacing)) / (ratios[2] + ratios[1]),\n ),\n );\n const secondHeight = firstHeight - thirdHeight - spacing;\n const rightWidth = Math.max(\n minWidth,\n Math.round(\n Math.min(\n (maxWidth - spacing) / 2,\n Math.min(\n thirdHeight * ratios[2],\n secondHeight * ratios[1],\n ),\n ),\n ),\n );\n const leftWidth = Math.min(Math.round(firstHeight * ratios[0]), maxWidth - spacing - rightWidth);\n\n return [{\n dimensions: {\n x: 0,\n y: 0,\n width: leftWidth,\n height: firstHeight,\n },\n sides: AlbumRectPart.Top | AlbumRectPart.Left | AlbumRectPart.Bottom,\n }, {\n dimensions: {\n x: leftWidth + spacing,\n y: 0,\n width: rightWidth,\n height: secondHeight,\n },\n sides: AlbumRectPart.Top | AlbumRectPart.Right,\n }, {\n dimensions: {\n x: leftWidth + spacing,\n y: secondHeight + spacing,\n width: rightWidth,\n height: thirdHeight,\n },\n sides: AlbumRectPart.Bottom | AlbumRectPart.Right,\n }];\n}\n\nfunction layoutThreeTopAndOther(params: ILayoutParams) {\n const {\n maxWidth,\n ratios,\n maxHeight,\n spacing,\n } = params;\n const firstWidth = maxWidth;\n const firstHeight = Math.round(Math.min(firstWidth / ratios[0], 0.66 * (maxHeight - spacing)));\n const secondWidth = (maxWidth - spacing) / 2;\n const secondHeight = Math.min(\n maxHeight - firstHeight - spacing,\n Math.round(Math.min(\n secondWidth / ratios[1],\n secondWidth / ratios[2],\n )),\n );\n const thirdWidth = firstWidth - secondWidth - spacing;\n\n return [{\n dimensions: {\n x: 0,\n y: 0,\n width: firstWidth,\n height: firstHeight,\n },\n sides: AlbumRectPart.Left | AlbumRectPart.Top | AlbumRectPart.Right,\n }, {\n dimensions: {\n x: 0,\n y: firstHeight + spacing,\n width: secondWidth,\n height: secondHeight,\n },\n sides: AlbumRectPart.Bottom | AlbumRectPart.Left,\n }, {\n dimensions: {\n x: secondWidth + spacing,\n y: firstHeight + spacing,\n width: thirdWidth,\n height: secondHeight,\n },\n sides: AlbumRectPart.Bottom | AlbumRectPart.Right,\n }];\n}\n\nfunction layoutFour(params: ILayoutParams) {\n const { proportions } = params;\n\n return proportions[0] === 'w'\n ? layoutFourTopAndOther(params)\n : layoutFourLeftAndOther(params);\n}\n\nfunction layoutFourTopAndOther({\n maxWidth,\n ratios,\n spacing,\n maxHeight,\n minWidth,\n}: ILayoutParams) {\n const w = maxWidth;\n const h0 = Math.round(Math.min(w / ratios[0], 0.66 * (maxHeight - spacing)));\n const h = Math.round((maxWidth - 2 * spacing) / (ratios[1] + ratios[2] + ratios[3]));\n const w0 = Math.max(minWidth, Math.round(Math.min(0.4 * (maxWidth - 2 * spacing), h * ratios[1])));\n const w2 = Math.round(Math.max(Math.max(minWidth, 0.33 * (maxWidth - 2 * spacing)), h * ratios[3]));\n const w1 = w - w0 - w2 - 2 * spacing;\n const h1 = Math.min(maxHeight - h0 - spacing, h);\n\n return [{\n dimensions: {\n x: 0,\n y: 0,\n width: w,\n height: h0,\n },\n sides: AlbumRectPart.Left | AlbumRectPart.Top | AlbumRectPart.Right,\n }, {\n dimensions: {\n x: 0,\n y: h0 + spacing,\n width: w0,\n height: h1,\n },\n sides: AlbumRectPart.Bottom | AlbumRectPart.Left,\n }, {\n dimensions: {\n x: w0 + spacing,\n y: h0 + spacing,\n width: w1,\n height: h1,\n },\n sides: AlbumRectPart.Bottom,\n }, {\n dimensions: {\n x: w0 + spacing + w1 + spacing,\n y: h0 + spacing,\n width: w2,\n height: h1,\n },\n sides: AlbumRectPart.Right | AlbumRectPart.Bottom,\n }];\n}\n\nfunction layoutFourLeftAndOther({\n maxHeight,\n ratios,\n maxWidth,\n spacing,\n minWidth,\n}: ILayoutParams) {\n const h = maxHeight;\n const w0 = Math.round(Math.min(h * ratios[0], 0.6 * (maxWidth - spacing)));\n const w = Math.round((maxHeight - 2 * spacing) / (1 / ratios[1] + 1 / ratios[2] + 1 / ratios[3]));\n const h0 = Math.round(w / ratios[1]);\n const h1 = Math.round(w / ratios[2]);\n const h2 = h - h0 - h1 - 2 * spacing;\n const w1 = Math.max(minWidth, Math.min(maxWidth - w0 - spacing, w));\n\n return [{\n dimensions: {\n x: 0,\n y: 0,\n width: w0,\n height: h,\n },\n sides: AlbumRectPart.Top | AlbumRectPart.Left | AlbumRectPart.Bottom,\n }, {\n dimensions: {\n x: w0 + spacing,\n y: 0,\n width: w1,\n height: h0,\n },\n sides: AlbumRectPart.Top | AlbumRectPart.Right,\n }, {\n dimensions: {\n x: w0 + spacing,\n y: h0 + spacing,\n width: w1,\n height: h1,\n },\n sides: AlbumRectPart.Right,\n }, {\n dimensions: {\n x: w0 + spacing,\n y: h0 + h1 + 2 * spacing,\n width: w1,\n height: h2,\n },\n sides: AlbumRectPart.Bottom | AlbumRectPart.Right,\n }];\n}\n","let element: HTMLSpanElement | undefined;\n\nexport default function calculateAuthorWidth(text: string) {\n if (!element) {\n element = document.createElement('span');\n element.style.font = '400 12px Roboto, \"Helvetica Neue\", \"Apple Color Emoji\", sans-serif';\n element.style.whiteSpace = 'nowrap';\n element.style.position = 'absolute';\n element.style.left = '-999px';\n element.style.opacity = '.01';\n document.body.appendChild(element);\n }\n\n element.innerHTML = text;\n\n return element.offsetWidth;\n}\n","import { useLayoutEffect } from '../../../../lib/teact/teact';\nimport fastSmoothScroll from '../../../../util/fastSmoothScroll';\nimport { FocusDirection } from '../../../../types';\n\n// This is the max scroll offset within existing viewport.\nconst FOCUS_MAX_OFFSET = 1500;\n// This is used when the viewport was replaced.\nconst RELOCATED_FOCUS_OFFSET = 1000;\nconst FOCUS_MARGIN = 20;\n\nexport default function useFocusMessage(\n elementRef: { current: HTMLDivElement | null },\n chatId: number,\n isFocused?: boolean,\n focusDirection?: FocusDirection,\n noFocusHighlight?: boolean,\n) {\n useLayoutEffect(() => {\n if (isFocused && elementRef.current) {\n const messagesContainer = elementRef.current.closest<HTMLDivElement>('.MessageList')!;\n\n fastSmoothScroll(\n messagesContainer,\n elementRef.current,\n // `noFocusHighlight` always called from “scroll-to-bottom” buttons\n noFocusHighlight ? 'end' : 'center',\n FOCUS_MARGIN,\n focusDirection === undefined ? FOCUS_MAX_OFFSET : RELOCATED_FOCUS_OFFSET,\n focusDirection,\n );\n }\n }, [elementRef, chatId, isFocused, focusDirection, noFocusHighlight]);\n}\n","import React, { FC } from '../../../lib/teact/teact';\nimport { OwnProps } from './ContextMenuContainer';\nimport { Bundles } from '../../../util/moduleLoader';\n\nimport useModuleLoader from '../../../hooks/useModuleLoader';\n\nconst ContextMenuContainerAsync: FC<OwnProps> = (props) => {\n const { isOpen } = props;\n const ContextMenuContainer = useModuleLoader(Bundles.Extra, 'ContextMenuContainer', !isOpen);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return ContextMenuContainer ? <ContextMenuContainer {...props} /> : undefined;\n};\n\nexport default ContextMenuContainerAsync;\n","import React, {\n FC, memo, useEffect, useRef,\n} from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { ApiUser, ApiMessage, ApiChat } from '../../api/types';\nimport { FocusDirection } from '../../types';\n\nimport {\n selectUser,\n selectChatMessage,\n selectIsMessageFocused,\n selectChat,\n} from '../../modules/selectors';\nimport { isChatChannel } from '../../modules/helpers';\nimport buildClassName from '../../util/buildClassName';\nimport renderText from '../common/helpers/renderText';\nimport { renderActionMessageText } from '../common/helpers/renderActionMessageText';\nimport useEnsureMessage from '../../hooks/useEnsureMessage';\nimport useContextMenuHandlers from '../../hooks/useContextMenuHandlers';\nimport { ObserveFn, useOnIntersect } from '../../hooks/useIntersectionObserver';\nimport useFocusMessage from './message/hooks/useFocusMessage';\nimport useLang from '../../hooks/useLang';\n\nimport ContextMenuContainer from './message/ContextMenuContainer.async';\nimport useFlag from '../../hooks/useFlag';\nimport useShowTransition from '../../hooks/useShowTransition';\n\ntype OwnProps = {\n message: ApiMessage;\n observeIntersection?: ObserveFn;\n isEmbedded?: boolean;\n appearanceOrder?: number;\n};\n\ntype StateProps = {\n sender?: ApiUser | ApiChat;\n targetUser?: ApiUser;\n targetMessage?: ApiMessage;\n targetChatId?: number;\n isFocused: boolean;\n focusDirection?: FocusDirection;\n noFocusHighlight?: boolean;\n};\n\nconst APPEARANCE_DELAY = 10;\n\nconst ActionMessage: FC<OwnProps & StateProps> = ({\n message,\n observeIntersection,\n isEmbedded,\n appearanceOrder = 0,\n sender,\n targetUser,\n targetMessage,\n targetChatId,\n isFocused,\n focusDirection,\n noFocusHighlight,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const ref = useRef<HTMLDivElement>(null);\n\n useOnIntersect(ref, observeIntersection);\n useEnsureMessage(message.chatId, message.replyToMessageId, targetMessage);\n useFocusMessage(ref, message.chatId, isFocused, focusDirection, noFocusHighlight);\n\n useLang();\n\n const noAppearanceAnimation = appearanceOrder <= 0;\n const [isShown, markShown] = useFlag(noAppearanceAnimation);\n useEffect(() => {\n if (noAppearanceAnimation) {\n return;\n }\n\n setTimeout(markShown, appearanceOrder * APPEARANCE_DELAY);\n }, [appearanceOrder, markShown, noAppearanceAnimation]);\n const { transitionClassNames } = useShowTransition(isShown, undefined, noAppearanceAnimation, false);\n\n const content = renderActionMessageText(\n message,\n sender,\n targetUser,\n targetMessage,\n targetChatId,\n isEmbedded ? { isEmbedded: true, asPlain: true } : undefined,\n );\n const {\n isContextMenuOpen, contextMenuPosition,\n handleBeforeContextMenu, handleContextMenu,\n handleContextMenuClose, handleContextMenuHide,\n } = useContextMenuHandlers(ref);\n const isContextMenuShown = contextMenuPosition !== undefined;\n\n if (isEmbedded) {\n return <span className=\"embedded-action-message\">{renderText(content as string)}</span>;\n }\n\n return (\n <div\n ref={ref}\n id={`message${message.id}`}\n className={buildClassName(\n 'ActionMessage message-list-item',\n isFocused && !noFocusHighlight && 'focused',\n isContextMenuShown && 'has-menu-open',\n transitionClassNames,\n )}\n data-message-id={message.id}\n onMouseDown={handleBeforeContextMenu}\n onContextMenu={handleContextMenu}\n >\n <span>{content}</span>\n {contextMenuPosition && (\n <ContextMenuContainer\n isOpen={isContextMenuOpen}\n anchor={contextMenuPosition}\n message={message}\n messageListType=\"thread\"\n onClose={handleContextMenuClose}\n onCloseAnimationEnd={handleContextMenuHide}\n />\n )}\n </div>\n );\n};\n\nexport default memo(withGlobal<OwnProps>(\n (global, { message }): StateProps => {\n const userId = message.senderId;\n const { targetUserId, targetChatId } = message.content.action || {};\n const targetMessageId = message.replyToMessageId;\n const targetMessage = targetMessageId\n ? selectChatMessage(global, message.chatId, targetMessageId)\n : undefined;\n\n const isFocused = selectIsMessageFocused(global, message);\n const { direction: focusDirection, noHighlight: noFocusHighlight } = (isFocused && global.focusedMessage) || {};\n\n const chat = selectChat(global, message.chatId);\n const sender = chat && (isChatChannel(chat) || userId === message.chatId)\n ? chat\n : userId ? selectUser(global, userId) : undefined;\n\n return {\n sender,\n ...(targetUserId && { targetUser: selectUser(global, targetUserId) }),\n targetChatId,\n targetMessage,\n isFocused,\n ...(isFocused && { focusDirection, noFocusHighlight }),\n };\n },\n)(ActionMessage));\n","import React, { FC, useRef } from '../../lib/teact/teact';\n\nimport { ApiUser, ApiMessage, ApiChat } from '../../api/types';\n\nimport {\n getMessageMediaHash,\n isActionMessage,\n getMessageSummaryText,\n getSenderTitle,\n} from '../../modules/helpers';\nimport renderText from './helpers/renderText';\nimport { getPictogramDimensions } from './helpers/mediaDimensions';\nimport buildClassName from '../../util/buildClassName';\nimport { ObserveFn, useIsIntersecting } from '../../hooks/useIntersectionObserver';\nimport useMedia from '../../hooks/useMedia';\nimport useWebpThumbnail from '../../hooks/useWebpThumbnail';\nimport useLang from '../../hooks/useLang';\n\nimport ActionMessage from '../middle/ActionMessage';\n\nimport './EmbeddedMessage.scss';\n\ntype OwnProps = {\n observeIntersection?: ObserveFn;\n className?: string;\n message?: ApiMessage;\n sender?: ApiUser | ApiChat;\n title?: string;\n customText?: string;\n onClick: NoneToVoidFunction;\n};\n\nconst NBSP = '\\u00A0';\n\nconst EmbeddedMessage: FC<OwnProps> = ({\n className,\n message,\n sender,\n title,\n customText,\n observeIntersection,\n onClick,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const ref = useRef<HTMLDivElement>(null);\n const isIntersecting = useIsIntersecting(ref, observeIntersection);\n\n const mediaBlobUrl = useMedia(message && getMessageMediaHash(message, 'pictogram'), !isIntersecting);\n const pictogramId = message && `sticker-reply-thumb${message.id}`;\n const mediaThumbnail = useWebpThumbnail(message);\n\n useLang();\n\n const senderTitle = sender && getSenderTitle(sender);\n\n return (\n <div\n ref={ref}\n className={buildClassName('EmbeddedMessage', className)}\n onClick={message ? onClick : undefined}\n >\n {mediaThumbnail && renderPictogram(pictogramId, mediaThumbnail, mediaBlobUrl)}\n <div className=\"message-text\">\n <div className=\"message-title\">{renderText(senderTitle || title || NBSP)}</div>\n <p>\n {!message ? (\n customText || NBSP\n ) : isActionMessage(message) ? (\n <ActionMessage message={message} isEmbedded />\n ) : (\n renderText(getMessageSummaryText(message, Boolean(mediaThumbnail)))\n )}\n </p>\n </div>\n </div>\n );\n};\n\nfunction renderPictogram(\n id: string | undefined,\n thumbDataUri: string,\n blobUrl?: string,\n) {\n const { width, height } = getPictogramDimensions();\n\n return (\n <img id={id} src={blobUrl || thumbDataUri} width={width} height={height} alt=\"\" />\n );\n}\n\nexport default EmbeddedMessage;\n","import React, { FC } from '../../../lib/teact/teact';\n\nimport { ApiMessage, ApiMessageOutgoingStatus } from '../../../api/types';\n\nimport { formatTime } from '../../../util/dateFormat';\nimport { formatIntegerCompact } from '../../../util/textFormat';\n\nimport MessageOutgoingStatus from '../../common/MessageOutgoingStatus';\nimport renderText from '../../common/helpers/renderText';\nimport useLang from '../../../hooks/useLang';\n\nimport './MessageMeta.scss';\n\ntype OwnProps = {\n message: ApiMessage;\n outgoingStatus?: ApiMessageOutgoingStatus;\n signature?: string;\n onClick: () => void;\n};\n\nconst MessageMeta: FC<OwnProps> = ({\n message, outgoingStatus, signature, onClick,\n}) => {\n const lang = useLang();\n\n return (\n <span className=\"MessageMeta\" onClick={onClick}>\n {Boolean(message.views) && (\n <>\n <span className=\"message-views\">\n {formatIntegerCompact(message.views!)}\n </span>\n <i className=\"icon-channelviews\" />\n </>\n )}\n {signature && (\n <span className=\"message-signature\">{renderText(signature)}</span>\n )}\n <span className=\"message-time\">\n {message.isEdited && `${lang('EditedMessage')} `}\n {formatTime(message.date * 1000)}\n </span>\n {outgoingStatus && (\n <MessageOutgoingStatus status={outgoingStatus} />\n )}\n </span>\n );\n};\n\nexport default MessageMeta;\n","import React, { FC, useRef } from '../../../lib/teact/teact';\n\nimport { ApiMessage } from '../../../api/types';\n\nimport { MEMOJI_STICKER_ID } from '../../../config';\nimport { getStickerDimensions } from '../../common/helpers/mediaDimensions';\nimport { getMessageMediaFormat, getMessageMediaHash } from '../../../modules/helpers';\nimport useMedia from '../../../hooks/useMedia';\nimport useTransitionForMedia from '../../../hooks/useTransitionForMedia';\nimport buildClassName from '../../../util/buildClassName';\nimport { ObserveFn, useIsIntersecting } from '../../../hooks/useIntersectionObserver';\nimport useFlag from '../../../hooks/useFlag';\nimport useWebpThumbnail from '../../../hooks/useWebpThumbnail';\n\nimport AnimatedSticker from '../../common/AnimatedSticker';\nimport StickerSetModal from '../../common/StickerSetModal.async';\n\nimport './Sticker.scss';\n\ntype OwnProps = {\n message: ApiMessage;\n observeIntersection: ObserveFn;\n observeIntersectionForPlaying: ObserveFn;\n shouldLoop?: boolean;\n lastSyncTime?: number;\n};\n\nconst Sticker: FC<OwnProps> = ({\n message, observeIntersection, observeIntersectionForPlaying, shouldLoop, lastSyncTime,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const ref = useRef<HTMLDivElement>(null);\n\n const [isModalOpen, openModal, closeModal] = useFlag();\n\n const sticker = message.content.sticker!;\n const { isAnimated, stickerSetId } = sticker;\n const isMemojiSticker = stickerSetId === MEMOJI_STICKER_ID;\n\n const shouldLoad = useIsIntersecting(ref, observeIntersection);\n const shouldPlay = useIsIntersecting(ref, observeIntersectionForPlaying);\n\n const mediaHash = sticker.isPreloadedGlobally ? `sticker${sticker.id}` : getMessageMediaHash(message, 'inline')!;\n const thumbDataUri = useWebpThumbnail(message);\n const mediaData = useMedia(\n mediaHash,\n !shouldLoad,\n getMessageMediaFormat(message, 'inline', true),\n lastSyncTime,\n );\n\n const isMediaLoaded = Boolean(mediaData);\n const [isAnimationLoaded, markAnimationLoaded] = useFlag(isMediaLoaded);\n const isMediaReady = isAnimated ? isAnimationLoaded : isMediaLoaded;\n const { shouldRenderFullMedia, transitionClassNames } = useTransitionForMedia(isMediaReady, 'slow');\n\n const { width, height } = getStickerDimensions(sticker);\n const thumbClassName = buildClassName('thumbnail', !thumbDataUri && 'empty');\n\n const stickerClassName = buildClassName(\n 'Sticker media-inner',\n isMemojiSticker && 'inactive',\n );\n\n return (\n <div ref={ref} className={stickerClassName} onClick={!isMemojiSticker ? openModal : undefined}>\n {!isMediaReady && (\n <img\n id={`sticker-thumb-${message.id}`}\n src={thumbDataUri}\n width={width}\n height={height}\n alt=\"\"\n className={thumbClassName}\n />\n )}\n {!isAnimated && shouldRenderFullMedia && (\n <img\n id={`sticker-${message.id}`}\n src={mediaData as string}\n width={width}\n height={height}\n alt=\"\"\n className={buildClassName('full-media', transitionClassNames)}\n />\n )}\n {isAnimated && isMediaLoaded && (\n <AnimatedSticker\n key={mediaHash}\n className={buildClassName('full-media', transitionClassNames)}\n id={mediaHash}\n animationData={mediaData as AnyLiteral}\n size={width}\n play={shouldPlay}\n noLoop={!shouldLoop}\n onLoad={markAnimationLoaded}\n />\n )}\n <StickerSetModal\n isOpen={isModalOpen}\n fromSticker={sticker}\n onClose={closeModal}\n />\n </div>\n );\n};\n\nexport default Sticker;\n","import { ApiMessage } from '../../../../api/types';\n\nimport { LAYERS_TRANSITION_DURATION } from '../../../../config';\nimport { IS_MOBILE_SCREEN } from '../../../../util/environment';\nimport { getMessageMediaThumbDataUri } from '../../../../modules/helpers';\nimport useBlur from '../../../../hooks/useBlur';\n\nexport default function useBlurredMediaThumb(message: ApiMessage, fullMediaData?: string) {\n return useBlur(\n getMessageMediaThumbDataUri(message),\n Boolean(fullMediaData),\n IS_MOBILE_SCREEN ? LAYERS_TRANSITION_DURATION : undefined,\n );\n}\n","const SELECTED_APPENDIX_BACKGROUND = 'rgba(255,255,255,1)';\n\nexport default async (src: string, isOwn: boolean, inSelectMode?: boolean, isSelected?: boolean) => {\n return isSelected ? SELECTED_APPENDIX_BACKGROUND : getAppendixColorFromImage(src, isOwn);\n};\n\nasync function getAppendixColorFromImage(src: string, isOwn: boolean) {\n const img = new Image();\n img.src = src;\n\n if (!img.width) {\n await new Promise((resolve) => {\n img.onload = resolve;\n });\n }\n\n const canvas = document.createElement('canvas');\n const ctx = canvas.getContext('2d')!;\n\n canvas.width = img.width;\n canvas.height = img.height;\n\n ctx.drawImage(img, 0, 0, img.width, img.height);\n\n const x = isOwn ? img.width - 1 : 0;\n const y = img.height - 1;\n\n const pixel = Array.from(ctx.getImageData(x, y, 1, 1).data);\n return `rgba(${pixel.join(',')})`;\n}\n","import React, {\n FC, useCallback, useLayoutEffect, useRef, useState,\n} from '../../../lib/teact/teact';\n\nimport { ApiMessage } from '../../../api/types';\nimport { IMediaDimensions } from './helpers/calculateAlbumLayout';\n\nimport {\n getMessagePhoto,\n getMessageWebPagePhoto,\n getMessageMediaHash,\n getMediaTransferState,\n isOwnMessage,\n} from '../../../modules/helpers';\nimport { ObserveFn, useIsIntersecting } from '../../../hooks/useIntersectionObserver';\nimport useMediaWithDownloadProgress from '../../../hooks/useMediaWithDownloadProgress';\nimport useTransitionForMedia from '../../../hooks/useTransitionForMedia';\nimport useShowTransition from '../../../hooks/useShowTransition';\nimport usePrevious from '../../../hooks/usePrevious';\nimport useBlurredMediaThumb from './hooks/useBlurredMediaThumb';\nimport buildClassName from '../../../util/buildClassName';\nimport getCustomAppendixBg from './helpers/getCustomAppendixBg';\nimport { calculateMediaDimensions } from './helpers/mediaDimensions';\n\nimport ProgressSpinner from '../../ui/ProgressSpinner';\n\nexport type OwnProps = {\n id?: string;\n message: ApiMessage;\n observeIntersection?: ObserveFn;\n shouldAutoLoad?: boolean;\n isInSelectMode?: boolean;\n isSelected?: boolean;\n uploadProgress?: number;\n size?: 'inline' | 'pictogram';\n shouldAffectAppendix?: boolean;\n dimensions?: IMediaDimensions & { isSmall?: boolean };\n onClick?: (id: number) => void;\n onCancelUpload?: (message: ApiMessage) => void;\n};\n\nconst CUSTOM_APPENDIX_ATTRIBUTE = 'data-has-custom-appendix';\n\nconst Photo: FC<OwnProps> = ({\n id,\n message,\n observeIntersection,\n shouldAutoLoad,\n isInSelectMode,\n isSelected,\n uploadProgress,\n size = 'inline',\n dimensions,\n shouldAffectAppendix,\n onClick,\n onCancelUpload,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const ref = useRef<HTMLDivElement>(null);\n\n const photo = (getMessagePhoto(message) || getMessageWebPagePhoto(message))!;\n const localBlobUrl = photo.blobUrl;\n\n const isIntersecting = useIsIntersecting(ref, observeIntersection);\n\n const [isDownloadAllowed, setIsDownloadAllowed] = useState(shouldAutoLoad);\n const shouldDownload = isDownloadAllowed && isIntersecting;\n const {\n mediaData, downloadProgress,\n } = useMediaWithDownloadProgress(getMessageMediaHash(message, size), !shouldDownload);\n const fullMediaData = localBlobUrl || mediaData;\n const thumbDataUri = useBlurredMediaThumb(message, fullMediaData);\n\n const {\n isUploading, isTransferring, transferProgress,\n } = getMediaTransferState(message, uploadProgress || downloadProgress, shouldDownload && !fullMediaData);\n const wasDownloadDisabled = usePrevious(isDownloadAllowed) === false;\n const {\n shouldRender: shouldRenderSpinner,\n transitionClassNames: spinnerClassNames,\n } = useShowTransition(isTransferring, undefined, wasDownloadDisabled, 'slow');\n const {\n shouldRenderThumb, shouldRenderFullMedia, transitionClassNames,\n } = useTransitionForMedia(fullMediaData, 'slow');\n\n const handleClick = useCallback(() => {\n if (isUploading) {\n if (onCancelUpload) {\n onCancelUpload(message);\n }\n } else if (!fullMediaData) {\n setIsDownloadAllowed((isAllowed) => !isAllowed);\n } else if (onClick) {\n onClick(message.id);\n }\n }, [fullMediaData, isUploading, message, onCancelUpload, onClick]);\n\n const isOwn = isOwnMessage(message);\n useLayoutEffect(() => {\n if (!shouldAffectAppendix) {\n return;\n }\n\n const contentEl = ref.current!.closest<HTMLDivElement>('.message-content')!;\n\n if (fullMediaData) {\n getCustomAppendixBg(fullMediaData, isOwn, isInSelectMode, isSelected).then((appendixBg) => {\n contentEl.style.setProperty('--appendix-bg', appendixBg);\n contentEl.setAttribute(CUSTOM_APPENDIX_ATTRIBUTE, '');\n });\n } else {\n contentEl.classList.add('has-appendix-thumb');\n }\n }, [fullMediaData, isOwn, shouldAffectAppendix, isInSelectMode, isSelected]);\n\n const { width, height, isSmall } = dimensions || calculateMediaDimensions(message);\n\n const className = buildClassName(\n 'media-inner',\n !isUploading && 'interactive',\n isSmall && 'small-image',\n width === height && 'square-image',\n );\n\n const thumbClassName = buildClassName(\n 'thumbnail',\n !thumbDataUri && 'empty',\n );\n\n const style = dimensions\n ? `width: ${width}px; height: ${height}px; left: ${dimensions.x}px; top: ${dimensions.y}px;`\n : '';\n\n return (\n <div\n id={id}\n ref={ref}\n className={className}\n // @ts-ignore teact feature\n style={style}\n onClick={isUploading ? undefined : handleClick}\n >\n {shouldRenderThumb && (\n <img\n src={thumbDataUri}\n className={thumbClassName}\n width={width}\n height={height}\n alt=\"\"\n />\n )}\n {shouldRenderFullMedia && (\n <img\n src={fullMediaData}\n className={`full-media ${transitionClassNames}`}\n width={width}\n height={height}\n alt=\"\"\n />\n )}\n {shouldRenderSpinner && (\n <div className={`media-loading ${spinnerClassNames}`}>\n <ProgressSpinner progress={transferProgress} onClick={isUploading ? handleClick : undefined} />\n </div>\n )}\n {!fullMediaData && !isDownloadAllowed && (\n <i className=\"icon-download\" />\n )}\n {isTransferring && (\n <span className=\"message-upload-progress\">{Math.round(transferProgress * 100)}%</span>\n )}\n </div>\n );\n};\n\nexport default Photo;\n","import { RefObject } from 'react';\nimport { useCallback, useRef } from '../lib/teact/teact';\n\nimport useHeavyAnimationCheck from './useHeavyAnimationCheck';\nimport safePlay from '../util/safePlay';\n\nexport default function useHeavyAnimationCheckForVideo(playerRef: RefObject<HTMLVideoElement>, shouldPlay: boolean) {\n const shouldPlayRef = useRef();\n shouldPlayRef.current = shouldPlay;\n\n const pause = useCallback(() => {\n if (playerRef.current) {\n playerRef.current.pause();\n }\n }, [playerRef]);\n\n const play = useCallback(() => {\n if (playerRef.current && shouldPlayRef.current) {\n safePlay(playerRef.current);\n }\n }, [playerRef]);\n\n useHeavyAnimationCheck(pause, play);\n}\n","import React, {\n FC, useCallback, useRef, useState,\n} from '../../../lib/teact/teact';\n\nimport { ApiMessage } from '../../../api/types';\nimport { IMediaDimensions } from './helpers/calculateAlbumLayout';\n\nimport { formatMediaDuration } from '../../../util/dateFormat';\nimport buildClassName from '../../../util/buildClassName';\nimport { calculateVideoDimensions } from '../../common/helpers/mediaDimensions';\nimport {\n canMessagePlayVideoInline,\n getMediaTransferState,\n getMessageMediaFormat,\n getMessageMediaHash,\n isForwardedMessage,\n isOwnMessage,\n} from '../../../modules/helpers';\nimport { ObserveFn, useIsIntersecting } from '../../../hooks/useIntersectionObserver';\nimport useMediaWithDownloadProgress from '../../../hooks/useMediaWithDownloadProgress';\nimport useMedia from '../../../hooks/useMedia';\nimport useShowTransition from '../../../hooks/useShowTransition';\nimport useTransitionForMedia from '../../../hooks/useTransitionForMedia';\nimport usePrevious from '../../../hooks/usePrevious';\nimport useBuffering from '../../../hooks/useBuffering';\nimport useHeavyAnimationCheckForVideo from '../../../hooks/useHeavyAnimationCheckForVideo';\nimport useBlurredMediaThumb from './hooks/useBlurredMediaThumb';\nimport useVideoCleanup from '../../../hooks/useVideoCleanup';\n\nimport ProgressSpinner from '../../ui/ProgressSpinner';\n\nexport type OwnProps = {\n id?: string;\n message: ApiMessage;\n observeIntersection: ObserveFn;\n shouldAutoLoad?: boolean;\n shouldAutoPlay?: boolean;\n uploadProgress?: number;\n dimensions?: IMediaDimensions;\n lastSyncTime?: number;\n onClick?: (id: number) => void;\n onCancelUpload?: (message: ApiMessage) => void;\n};\n\nconst Video: FC<OwnProps> = ({\n id,\n message,\n observeIntersection,\n shouldAutoLoad,\n shouldAutoPlay,\n uploadProgress,\n lastSyncTime,\n dimensions,\n onClick,\n onCancelUpload,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const ref = useRef<HTMLDivElement>(null);\n // eslint-disable-next-line no-null/no-null\n const videoRef = useRef<HTMLVideoElement>(null);\n\n const video = message.content.video!;\n const localBlobUrl = video.blobUrl;\n const canPlayInline = Boolean(localBlobUrl) || canMessagePlayVideoInline(video);\n\n const isIntersecting = useIsIntersecting(ref, observeIntersection);\n\n const [isDownloadAllowed, setIsDownloadAllowed] = useState(shouldAutoLoad);\n const shouldDownload = Boolean(isDownloadAllowed && isIntersecting && lastSyncTime);\n const [isPlayAllowed, setIsPlayAllowed] = useState(shouldAutoPlay);\n\n const previewBlobUrl = useMedia(\n getMessageMediaHash(message, 'pictogram'),\n !(isIntersecting && lastSyncTime),\n getMessageMediaFormat(message, 'pictogram'),\n lastSyncTime,\n );\n const thumbDataUri = useBlurredMediaThumb(message, previewBlobUrl);\n const { mediaData, downloadProgress } = useMediaWithDownloadProgress(\n getMessageMediaHash(message, 'inline'),\n !shouldDownload,\n getMessageMediaFormat(message, 'inline'),\n lastSyncTime,\n );\n\n const previewMediaData = previewBlobUrl || thumbDataUri;\n const fullMediaData = localBlobUrl || mediaData;\n const isInline = Boolean(canPlayInline && isIntersecting && fullMediaData);\n\n const { isBuffered, bufferingHandlers } = useBuffering(!shouldAutoLoad);\n const { isUploading, isTransferring, transferProgress } = getMediaTransferState(\n message,\n uploadProgress || downloadProgress,\n shouldDownload && (canPlayInline && !isBuffered),\n );\n const wasDownloadDisabled = usePrevious(isDownloadAllowed) === false;\n const {\n shouldRender: shouldRenderSpinner,\n transitionClassNames: spinnerClassNames,\n } = useShowTransition(isTransferring, undefined, wasDownloadDisabled);\n const { shouldRenderThumb, transitionClassNames } = useTransitionForMedia(fullMediaData, 'slow');\n\n const [playProgress, setPlayProgress] = useState<number>(0);\n const handleTimeUpdate = useCallback((e: React.SyntheticEvent<HTMLVideoElement>) => {\n setPlayProgress(Math.max(0, e.currentTarget.currentTime - 1));\n }, []);\n\n const isOwn = isOwnMessage(message);\n const isForwarded = isForwardedMessage(message);\n const { width, height } = dimensions || calculateVideoDimensions(video, isOwn, isForwarded);\n\n useHeavyAnimationCheckForVideo(videoRef, isInline);\n\n useVideoCleanup(videoRef, [isInline]);\n\n const handleClick = useCallback(() => {\n if (isUploading) {\n if (onCancelUpload) {\n onCancelUpload(message);\n }\n } else if (canPlayInline && !fullMediaData) {\n setIsDownloadAllowed((isAllowed) => !isAllowed);\n } else if (canPlayInline && fullMediaData && !isPlayAllowed) {\n setIsPlayAllowed(true);\n videoRef.current!.play();\n } else if (onClick) {\n onClick(message.id);\n }\n }, [isUploading, canPlayInline, fullMediaData, isPlayAllowed, onClick, onCancelUpload, message]);\n\n const className = buildClassName('media-inner dark', !isUploading && 'interactive');\n const thumbClassName = buildClassName('thumbnail', !previewMediaData && 'empty');\n const videoClassName = buildClassName('full-media', transitionClassNames);\n const videoStyle = previewMediaData ? `background-image: url(${previewMediaData}); background-size: cover` : '';\n\n const style = dimensions\n ? `width: ${width}px; height: ${height}px; left: ${dimensions.x}px; top: ${dimensions.y}px;`\n : '';\n\n const shouldRenderInlineVideo = isInline;\n const shouldRenderHqPreview = !canPlayInline && mediaData;\n const shouldRenderPlayButton = !canPlayInline || (isDownloadAllowed && !isPlayAllowed && !shouldRenderSpinner);\n const shouldRenderDownloadButton = canPlayInline && !isDownloadAllowed;\n\n return (\n <div\n ref={ref}\n id={id}\n className={className}\n // @ts-ignore teact feature\n style={style}\n onClick={isUploading ? undefined : handleClick}\n >\n {(shouldRenderThumb || !isInline) && (\n <img\n src={previewMediaData}\n className={thumbClassName}\n width={width}\n height={height}\n alt=\"\"\n />\n )}\n {shouldRenderInlineVideo && (\n <video\n ref={videoRef}\n className={videoClassName}\n width={width}\n height={height}\n autoPlay={isPlayAllowed}\n muted\n loop\n playsInline\n // @ts-ignore teact feature\n style={videoStyle}\n // eslint-disable-next-line react/jsx-props-no-spreading\n {...bufferingHandlers}\n onTimeUpdate={handleTimeUpdate}\n >\n <source src={fullMediaData} />\n </video>\n )}\n {shouldRenderHqPreview && (\n <img\n src={mediaData}\n className={`full-media ${transitionClassNames}`}\n width={width}\n height={height}\n alt=\"\"\n />\n )}\n {shouldRenderPlayButton && (\n <i className=\"icon-large-play\" />\n )}\n {shouldRenderSpinner && (\n <div className={`media-loading ${spinnerClassNames}`}>\n <ProgressSpinner progress={transferProgress} onClick={isUploading ? handleClick : undefined} />\n </div>\n )}\n {shouldRenderDownloadButton && (\n <i className=\"icon-download\" />\n )}\n {isTransferring && !canPlayInline ? (\n <span className=\"message-upload-progress\">{Math.round(transferProgress * 100)}%</span>\n ) : isTransferring && canPlayInline ? (\n <span className=\"message-upload-progress\">...</span>\n ) : (\n <div className=\"message-media-duration\">\n {video.isGif ? 'GIF' : formatMediaDuration(video.duration - playProgress)}\n </div>\n )}\n </div>\n );\n};\n\nexport default Video;\n","import React, { FC, useCallback } from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../../global/types';\nimport { ApiUser, ApiContact } from '../../../api/types';\n\nimport { selectUser } from '../../../modules/selectors';\nimport { formatPhoneNumberWithCode } from '../../../util/phoneNumber';\n\nimport Avatar from '../../common/Avatar';\n\nimport './Contact.scss';\nimport { pick } from '../../../util/iteratees';\nimport buildClassName from '../../../util/buildClassName';\n\ntype OwnProps = {\n contact: ApiContact;\n};\n\ntype StateProps = {\n user?: ApiUser;\n};\n\ntype DispatchProps = Pick<GlobalActions, 'openUserInfo'>;\n\nconst Contact: FC<OwnProps & StateProps & DispatchProps> = ({\n contact, user, openUserInfo,\n}) => {\n const {\n firstName,\n lastName,\n phoneNumber,\n userId,\n } = contact;\n\n const handleClick = useCallback(() => {\n openUserInfo({ id: userId });\n }, [openUserInfo, userId]);\n\n return (\n <div\n className={buildClassName('Contact', Boolean(userId) && 'interactive')}\n onClick={userId ? handleClick : undefined}\n >\n <Avatar size=\"large\" user={user} text={firstName || lastName} />\n <div className=\"contact-info\">\n <div className=\"contact-name\">{firstName} {lastName}</div>\n <div className=\"contact-phone\">{formatPhoneNumberWithCode(phoneNumber)}</div>\n </div>\n </div>\n );\n};\n\nexport default withGlobal<OwnProps>(\n (global, { contact }): StateProps => {\n return {\n user: selectUser(global, contact.userId),\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'openUserInfo',\n ]),\n)(Contact);\n","import { ChangeEvent } from 'react';\nimport React, {\n FC, useCallback, memo, useState,\n} from '../../lib/teact/teact';\n\nimport Checkbox from './Checkbox';\n\ntype IRadioOption = {\n label: string;\n subLabel?: string;\n value: string;\n};\n\ntype OwnProps = {\n id?: string;\n options: IRadioOption[];\n selected?: string[];\n disabled?: boolean;\n round?: boolean;\n loadingOptions?: string[];\n onChange: (value: string[]) => void;\n};\n\nconst CheckboxGroup: FC<OwnProps> = ({\n id,\n options,\n selected = [],\n disabled,\n round,\n loadingOptions,\n onChange,\n}) => {\n const [values, setValues] = useState<string[]>([]);\n\n const handleChange = useCallback((event: ChangeEvent<HTMLInputElement>) => {\n const { value, checked } = event.currentTarget;\n let newValues: string[];\n if (checked) {\n newValues = [...values, value];\n } else {\n newValues = values.filter((v) => v !== value);\n }\n\n setValues(newValues);\n onChange(newValues);\n }, [onChange, values]);\n\n return (\n <div id={id} className=\"radio-group\">\n {options.map((option) => (\n <Checkbox\n label={option.label}\n subLabel={option.subLabel}\n value={option.value}\n checked={selected.indexOf(option.value) !== -1}\n disabled={disabled}\n round={round}\n isLoading={loadingOptions ? loadingOptions.indexOf(option.value) !== -1 : undefined}\n onChange={handleChange}\n />\n ))}\n </div>\n );\n};\n\nexport default memo(CheckboxGroup);\n","import React, {\n FC, useState, useEffect, useRef,\n} from '../../../lib/teact/teact';\n\nimport { ApiPollAnswer, ApiPollResult } from '../../../api/types';\n\nimport buildClassName from '../../../util/buildClassName';\nimport renderText from '../../common/helpers/renderText';\n\nimport './PollOption.scss';\n\ntype OwnProps = {\n answer: ApiPollAnswer;\n voteResults?: ApiPollResult[];\n totalVoters?: number;\n maxVotersCount?: number;\n correctResults: string[];\n shouldAnimate: boolean;\n};\n\nconst PollOption: FC<OwnProps> = ({\n answer,\n voteResults,\n totalVoters,\n maxVotersCount,\n correctResults,\n shouldAnimate,\n}) => {\n const result = voteResults && voteResults.find((r) => r.option === answer.option);\n const correctAnswer = correctResults.length === 0 || correctResults.indexOf(answer.option) !== -1;\n const showIcon = (correctResults.length > 0 && correctAnswer) || (result && result.isChosen);\n const answerPercent = result ? getPercentage(result.votersCount, totalVoters || 0) : 0;\n const [finalPercent, setFinalPercent] = useState(shouldAnimate ? 0 : answerPercent);\n // eslint-disable-next-line no-null/no-null\n const lineRef = useRef<HTMLDivElement>(null);\n const lineWidth = result ? getPercentage(result.votersCount, maxVotersCount || 0) : 0;\n const isAnimationDoesNotStart = finalPercent < answerPercent;\n\n useEffect(() => {\n if (shouldAnimate) {\n setFinalPercent(answerPercent);\n }\n }, [shouldAnimate, answerPercent]);\n\n useEffect(() => {\n const lineEl = lineRef.current;\n\n if (lineEl && shouldAnimate) {\n const svgEl = lineEl.firstElementChild;\n\n const style = isAnimationDoesNotStart ? '' : 'stroke-dasharray: 100% 200%; stroke-dashoffset: -44';\n if (!svgEl) {\n lineEl.innerHTML = `\n <svg class=\"poll-line\" xmlns=\"http://www.w3.org/2000/svg\" style=\"${style}\">\n <path d=\"M4.47 5.33v13.6a9 9 0 009 9h13\"/>\n </svg>`;\n } else {\n svgEl.setAttribute('style', style);\n }\n }\n }, [isAnimationDoesNotStart, shouldAnimate]);\n\n if (!voteResults || !result) {\n return undefined;\n }\n\n const lineStyle = `width: ${lineWidth}%; transform:scaleX(${isAnimationDoesNotStart ? 0 : 1})`;\n\n return (\n <div className=\"PollOption\">\n <div className={`poll-option-share ${answerPercent === '100' ? 'limit-width' : ''}`}>\n {answerPercent}%\n {showIcon && (\n <span className={buildClassName(\n 'poll-option-chosen',\n !correctAnswer && 'wrong',\n shouldAnimate && 'animate',\n )}\n >\n <i className={correctAnswer ? 'icon-check' : 'icon-close'} />\n </span>\n )}\n </div>\n <div className=\"poll-option-right\">\n <div className=\"poll-option-text\">\n {renderText(answer.text)}\n </div>\n <div className={buildClassName('poll-option-answer', showIcon && !correctAnswer && 'wrong')}>\n <div className=\"poll-option-corner\" ref={lineRef} />\n <div\n className=\"poll-option-line\"\n // @ts-ignore\n style={lineStyle}\n />\n </div>\n </div>\n </div>\n );\n};\n\nfunction getPercentage(value: number, total: number) {\n return total > 0 ? ((value / total) * 100).toFixed() : 0;\n}\n\nexport default PollOption;\n","import React, {\n FC,\n useCallback,\n useEffect,\n useState,\n memo,\n useMemo,\n useRef,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../../global/types';\nimport {\n ApiMessage, ApiPoll, ApiUser, ApiPollAnswer,\n} from '../../../api/types';\n\nimport { pick } from '../../../util/iteratees';\nimport renderText from '../../common/helpers/renderText';\nimport { renderTextWithEntities } from '../../common/helpers/renderMessageText';\nimport { formatMediaDuration } from '../../../util/dateFormat';\nimport useLang from '../../../hooks/useLang';\n\nimport CheckboxGroup from '../../ui/CheckboxGroup';\nimport RadioGroup from '../../ui/RadioGroup';\nimport Avatar from '../../common/Avatar';\nimport Button from '../../ui/Button';\nimport Notification from '../../ui/Notification';\nimport PollOption from './PollOption';\n\nimport './Poll.scss';\n\ntype OwnProps = {\n message: ApiMessage;\n poll: ApiPoll;\n onSendVote: (options: string[]) => void;\n};\n\ntype StateProps = {\n recentVoterIds?: number[];\n usersById: Record<number, ApiUser>;\n};\n\ntype DispatchProps = Pick<GlobalActions, ('loadMessage' | 'openPollResults')>;\n\nconst SOLUTION_DURATION = 5000;\nconst NBSP = '\\u00A0';\n\nconst Poll: FC<OwnProps & StateProps & DispatchProps> = ({\n message,\n poll,\n recentVoterIds,\n usersById,\n loadMessage,\n onSendVote,\n openPollResults,\n}) => {\n const { id: messageId, chatId } = message;\n const { summary, results } = poll;\n const [isSubmitting, setIsSubmitting] = useState<boolean>(false);\n const [chosenOptions, setChosenOptions] = useState<string[]>([]);\n const [isSolutionShown, setIsSolutionShown] = useState<boolean>(false);\n const [wasSubmitted, setWasSubmitted] = useState<boolean>(false);\n const [closePeriod, setClosePeriod] = useState<number>(\n !summary.closed && summary.closeDate && summary.closeDate > 0\n ? Math.min(summary.closeDate - Math.floor(Date.now() / 1000), summary.closePeriod!)\n : 0,\n );\n // eslint-disable-next-line no-null/no-null\n const countdownRef = useRef<HTMLDivElement>(null);\n const { results: voteResults, totalVoters } = results;\n const hasVoted = voteResults && voteResults.some((r) => r.isChosen);\n const canVote = !summary.closed && !hasVoted;\n const canViewResult = !canVote && summary.isPublic && Number(results.totalVoters) > 0;\n const isMultiple = canVote && summary.multipleChoice;\n const maxVotersCount = voteResults ? Math.max(...voteResults.map((r) => r.votersCount)) : totalVoters;\n const correctResults = voteResults ? voteResults.reduce((answers: string[], r) => {\n if (r.isCorrect) {\n answers.push(r.option);\n }\n\n return answers;\n }, []) : [];\n const answers = summary.answers.map((a) => ({\n label: a.text,\n value: a.option,\n hidden: Boolean(summary.quiz && summary.closePeriod && closePeriod <= 0),\n }));\n\n useEffect(() => {\n if (\n isSubmitting\n && poll.results.results\n && poll.results.results.some((result) => result.isChosen)\n ) {\n setIsSubmitting(false);\n }\n }, [isSubmitting, poll.results.results]);\n\n useEffect(() => {\n if (closePeriod > 0) {\n setTimeout(() => setClosePeriod(closePeriod - 1), 1000);\n }\n\n const countdownEl = countdownRef.current;\n\n if (countdownEl) {\n const circumference = 6 * 2 * Math.PI;\n const svgEl = countdownEl.lastElementChild;\n const timerEl = countdownEl.firstElementChild;\n if (closePeriod <= 5) {\n countdownEl.classList.add('hurry-up');\n }\n\n if (!svgEl || !timerEl) {\n countdownEl.innerHTML = `\n <span>${formatMediaDuration(closePeriod)}</span>\n <svg width=\"16px\" height=\"16px\">\n <circle cx=\"8\" cy=\"8\" r=\"6\" class=\"poll-countdown-progress\" transform=\"rotate(-90, 8, 8)\"\n stroke-dasharray=\"${circumference} ${circumference}\"\n stroke-dashoffset=\"0\"\n />\n </svg>`;\n } else {\n const strokeDashOffset = ((summary.closePeriod! - closePeriod) / summary.closePeriod!) * circumference;\n timerEl.textContent = formatMediaDuration(closePeriod);\n (svgEl.firstElementChild as SVGElement).setAttribute('stroke-dashoffset', `-${strokeDashOffset}`);\n }\n }\n }, [closePeriod, summary.closePeriod]);\n\n useEffect(() => {\n if (summary.quiz && (closePeriod <= 0 || (hasVoted && !summary.closed))) {\n loadMessage({ chatId, messageId });\n }\n }, [chatId, closePeriod, hasVoted, loadMessage, messageId, summary.closed, summary.quiz]);\n\n // If the client time is not synchronized, the poll must be updated after the closePeriod time has expired.\n useEffect(() => {\n let timer: number | undefined;\n\n if (summary.quiz && !summary.closed && summary.closePeriod && summary.closePeriod > 0) {\n timer = window.setTimeout(() => {\n loadMessage({ chatId, messageId });\n }, summary.closePeriod * 1000);\n }\n\n return () => {\n if (timer) {\n window.clearTimeout(timer);\n }\n };\n }, [canVote, chatId, loadMessage, messageId, summary.closePeriod, summary.closed, summary.quiz]);\n\n const recentVoters = useMemo(() => {\n return recentVoterIds ? recentVoterIds.reduce((result: ApiUser[], id) => {\n const user = usersById[id];\n if (user) {\n result.push(user);\n }\n\n return result;\n }, []) : [];\n }, [usersById, recentVoterIds]);\n\n const handleRadioChange = useCallback(\n (option: string) => {\n setChosenOptions([option]);\n setIsSubmitting(true);\n setWasSubmitted(true);\n onSendVote([option]);\n }, [onSendVote],\n );\n\n const handleCheckboxChange = useCallback(\n (options: string[]) => {\n setChosenOptions(options);\n }, [],\n );\n\n const handleVoteClick = useCallback(\n () => {\n setIsSubmitting(true);\n setWasSubmitted(true);\n onSendVote(chosenOptions);\n }, [onSendVote, chosenOptions],\n );\n\n const handleViewResultsClick = useCallback(\n () => {\n openPollResults({ chatId, messageId });\n }, [chatId, messageId, openPollResults],\n );\n\n const handleSolutionShow = useCallback(() => {\n setIsSolutionShown(true);\n }, []);\n\n const handleSolutionHide = useCallback(() => {\n setIsSolutionShown(false);\n setWasSubmitted(false);\n }, []);\n\n // Show the solution to quiz if the answer was incorrect\n useEffect(() => {\n if (wasSubmitted && hasVoted && summary.quiz && results.results && poll.results.solution) {\n const correctResult = results.results.find((r) => r.isChosen && r.isCorrect);\n if (!correctResult) {\n setIsSolutionShown(true);\n }\n }\n }, [hasVoted, wasSubmitted, results.results, summary.quiz, poll.results.solution]);\n\n const lang = useLang();\n\n function renderResultOption(answer: ApiPollAnswer) {\n return (\n <PollOption\n key={answer.option}\n shouldAnimate={wasSubmitted}\n answer={answer}\n voteResults={voteResults}\n totalVoters={totalVoters}\n maxVotersCount={maxVotersCount}\n correctResults={correctResults}\n />\n );\n }\n\n function renderRecentVoters() {\n return (\n recentVoters.length > 0 && (\n <div className=\"poll-recent-voters\">\n {recentVoters.map((user) => (\n <Avatar\n size=\"micro\"\n user={user}\n />\n ))}\n </div>\n )\n );\n }\n\n function renderSolution() {\n return (\n isSolutionShown && poll.results.solution && (\n <Notification\n message={renderTextWithEntities(poll.results.solution, poll.results.solutionEntities)}\n duration={SOLUTION_DURATION}\n onDismiss={handleSolutionHide}\n />\n )\n );\n }\n\n return (\n <div className=\"Poll\">\n {renderSolution()}\n <div className=\"poll-question\">{renderText(summary.question)}</div>\n <div className=\"poll-type\">\n {getPollTypeString(summary)}\n {renderRecentVoters()}\n {closePeriod > 0 && canVote && <div ref={countdownRef} className=\"poll-countdown\" />}\n {summary.quiz && poll.results.solution && !canVote && (\n <Button\n round\n size=\"tiny\"\n color=\"translucent\"\n className=\"poll-quiz-help\"\n disabled={isSolutionShown}\n onClick={handleSolutionShow}\n ariaLabel=\"Show Solution\"\n >\n <i className=\"icon-lamp\" />\n </Button>\n )}\n </div>\n {canVote && (\n <div className=\"poll-answers\">\n {isMultiple\n ? (\n <CheckboxGroup\n options={answers}\n onChange={handleCheckboxChange}\n disabled={message.isScheduled || isSubmitting}\n loadingOptions={isSubmitting ? chosenOptions : undefined}\n round\n />\n )\n : (\n <RadioGroup\n name={`poll-${messageId}`}\n options={answers}\n onChange={handleRadioChange}\n disabled={message.isScheduled || isSubmitting}\n loadingOption={isSubmitting ? chosenOptions[0] : undefined}\n />\n )}\n </div>\n )}\n {!canVote && (\n <div className=\"poll-results\">\n {summary.answers.map(renderResultOption)}\n </div>\n )}\n {!canViewResult && !isMultiple && (\n <div className=\"poll-voters-count\">{getReadableVotersCount(summary.quiz, results.totalVoters)}</div>\n )}\n {isMultiple && (\n <Button\n isText\n disabled={chosenOptions.length === 0}\n size=\"tiny\"\n onClick={handleVoteClick}\n >\n {lang('PollSubmitVotes')}\n </Button>\n )}\n {canViewResult && (\n <Button\n isText\n size=\"tiny\"\n onClick={handleViewResultsClick}\n >\n {lang('PollViewResults')}\n </Button>\n )}\n </div>\n );\n};\n\nfunction getPollTypeString(summary: ApiPoll['summary']) {\n // When we just created the poll, some properties don't exist.\n if (typeof summary.isPublic === 'undefined') {\n return NBSP;\n }\n\n if (summary.quiz) {\n return summary.isPublic ? 'Quiz' : 'Anonymous Quiz';\n }\n\n if (summary.closed) {\n return 'Final results';\n }\n\n return summary.isPublic ? 'Poll' : 'Anonymous Poll';\n}\n\nfunction getReadableVotersCount(isQuiz: true | undefined, count?: number) {\n if (!count) {\n return isQuiz ? 'No answers yet' : 'No voters yet';\n }\n\n return isQuiz ? `${count} answered` : `${count} voted`;\n}\n\nexport default memo(withGlobal<OwnProps>(\n (global, { poll }) => {\n const { recentVoterIds } = poll.results;\n const { byId: usersById } = global.users;\n if (!recentVoterIds || recentVoterIds.length === 0) {\n return {};\n }\n\n return {\n recentVoterIds,\n usersById,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, ['loadMessage', 'openPollResults']),\n)(Poll));\n","import React, { FC, memo, useCallback } from '../../../lib/teact/teact';\n\nimport { ApiMessage } from '../../../api/types';\n\nimport { getMessageWebPage } from '../../../modules/helpers';\nimport { calculateMediaDimensions } from './helpers/mediaDimensions';\nimport renderText from '../../common/helpers/renderText';\nimport trimText from '../../../util/trimText';\nimport { ObserveFn } from '../../../hooks/useIntersectionObserver';\n\nimport SafeLink from '../../common/SafeLink';\nimport Photo from './Photo';\n\nimport './WebPage.scss';\n\nconst MAX_TEXT_LENGTH = 170; // symbols\n\ntype OwnProps = {\n message: ApiMessage;\n observeIntersection?: ObserveFn;\n shouldAutoLoad?: boolean;\n inPreview?: boolean;\n onMediaClick?: () => void;\n onCancelMediaTransfer?: () => void;\n};\n\nconst WebPage: FC<OwnProps> = ({\n message,\n observeIntersection,\n shouldAutoLoad,\n inPreview,\n onMediaClick,\n onCancelMediaTransfer,\n}) => {\n const webPage = getMessageWebPage(message);\n\n let isSquarePhoto = false;\n if (webPage && webPage.photo) {\n const { width, height } = calculateMediaDimensions(message);\n isSquarePhoto = width === height;\n }\n\n const handleMediaClick = useCallback(() => {\n if (webPage && (isSquarePhoto || webPage.hasDocument)) {\n window.open(webPage.url);\n } else if (onMediaClick) {\n onMediaClick();\n }\n }, [webPage, isSquarePhoto, onMediaClick]);\n\n if (!webPage) {\n return undefined;\n }\n\n const {\n siteName,\n url,\n displayUrl,\n title,\n description,\n photo,\n } = webPage;\n\n const truncatedDescription = trimText(description, MAX_TEXT_LENGTH);\n\n const className = [\n 'WebPage',\n photo\n ? (isSquarePhoto && 'with-square-photo')\n : (!inPreview && 'without-photo'),\n ].filter(Boolean).join(' ');\n\n return (\n <div\n className={className}\n data-initial={(siteName || displayUrl)[0]}\n >\n {photo && (\n <Photo\n message={message}\n observeIntersection={observeIntersection}\n shouldAutoLoad={shouldAutoLoad}\n size={isSquarePhoto ? 'pictogram' : 'inline'}\n onClick={handleMediaClick}\n onCancelUpload={onCancelMediaTransfer}\n />\n )}\n <div className=\"WebPage-text\">\n <SafeLink className=\"site-name\" url={url} text={siteName || displayUrl} />\n {title && (\n <p className=\"site-title\">{renderText(title)}</p>\n )}\n {truncatedDescription && (\n <p className=\"site-description\">{renderText(truncatedDescription, ['emoji', 'br'])}</p>\n )}\n </div>\n </div>\n );\n};\n\nexport default memo(WebPage);\n","import React, { FC, memo } from '../../../lib/teact/teact';\n\nimport { ApiMessage } from '../../../api/types';\n\nimport { getMessageInvoice } from '../../../modules/helpers';\nimport renderText from '../../common/helpers/renderText';\n\nimport './Invoice.scss';\n\ntype OwnProps = {\n message: ApiMessage;\n};\n\nconst Invoice: FC<OwnProps> = ({\n message,\n}) => {\n const invoice = getMessageInvoice(message);\n\n const {\n title,\n text,\n description,\n photoUrl,\n } = invoice!;\n\n return (\n <div\n className=\"Invoice\"\n >\n {title && (\n <p className=\"title\">{renderText(title)}</p>\n )}\n {text && (\n <p>{renderText(text, ['emoji', 'br'])}</p>\n )}\n <div className={`description ${photoUrl ? 'has-image' : ''}`}>\n {photoUrl && (\n <img\n className=\"invoice-image\"\n src={photoUrl}\n alt=\"\"\n />\n )}\n {description && (\n <p className=\"description-text\">{renderText(description, ['emoji', 'br'])}</p>\n )}\n </div>\n </div>\n );\n};\n\nexport default memo(Invoice);\n","import { MouseEvent as ReactMouseEvent } from 'react';\nimport React, {\n FC,\n useCallback,\n useMemo,\n memo,\n} from '../../../../lib/teact/teact';\nimport { withGlobal } from '../../../../lib/teact/teactn';\n\nimport { OwnProps as PhotoProps } from '../Photo';\nimport { OwnProps as VideoProps } from '../Video';\n\nimport buildClassName from '../../../../util/buildClassName';\nimport { GlobalActions } from '../../../../global/types';\nimport {\n selectIsInSelectMode,\n selectIsMessageSelected,\n} from '../../../../modules/selectors';\n\nimport { pick } from '../../../../util/iteratees';\n\ntype OwnProps = PhotoProps & VideoProps;\n\ntype StateProps = {\n isInSelectMode?: boolean;\n isSelected?: boolean;\n};\n\ntype DispatchProps = Pick<GlobalActions, ('toggleMessageSelection')>;\n\nexport default function withSelectControl(WrapedComponent: FC) {\n const Component: FC<OwnProps & StateProps & DispatchProps> = (props) => {\n const {\n isInSelectMode,\n isSelected,\n message,\n toggleMessageSelection,\n dimensions,\n } = props;\n\n const handleMessageSelect = useCallback((e: ReactMouseEvent<HTMLDivElement, MouseEvent>) => {\n e.stopPropagation();\n toggleMessageSelection({ messageId: message.id, withShift: e && e.shiftKey });\n }, [toggleMessageSelection, message]);\n\n const newProps = useMemo(() => {\n return {\n ...props,\n isInSelectMode,\n isSelected,\n dimensions: {\n ...props.dimensions,\n x: 0,\n y: 0,\n },\n onClick: isInSelectMode ? undefined : props.onClick,\n };\n }, [props, isInSelectMode, isSelected]);\n\n return (\n <div\n className={\n buildClassName(\n 'album-item-select-wrapper',\n isSelected && 'is-selected',\n )\n }\n // @ts-ignore\n style={dimensions ? `left: ${dimensions.x}px; top: ${dimensions.y}px;` : ''}\n onClick={isInSelectMode ? handleMessageSelect : undefined}\n >\n {isInSelectMode && (\n <div className=\"message-select-control\">\n {isSelected && (\n <i className=\"icon-select\" />\n )}\n </div>\n )}\n {/* eslint-disable-next-line react/jsx-props-no-spreading */}\n <WrapedComponent {...newProps} />\n </div>\n );\n };\n\n return memo(withGlobal<OwnProps>(\n (global, ownProps) => {\n const { message } = ownProps;\n return {\n isInSelectMode: selectIsInSelectMode(global),\n isSelected: selectIsMessageSelected(global, message.id),\n };\n },\n (setGlobal, actions) => pick(actions, [\n 'toggleMessageSelection',\n ]),\n )(Component));\n}\n","import React, { FC, useCallback } from '../../../lib/teact/teact';\n\nimport { GlobalActions, GlobalState } from '../../../global/types';\nimport { ApiMessage } from '../../../api/types';\nimport { IAlbum } from '../../../types';\nimport { AlbumRectPart, IAlbumLayout } from './helpers/calculateAlbumLayout';\n\nimport { getMessageContent } from '../../../modules/helpers';\nimport { withGlobal } from '../../../lib/teact/teactn';\nimport { pick } from '../../../util/iteratees';\nimport withSelectControl from './hocs/withSelectControl';\nimport { ObserveFn } from '../../../hooks/useIntersectionObserver';\n\nimport Photo from './Photo';\nimport Video from './Video';\n\nimport './Album.scss';\n\nconst PhotoWithSelect = withSelectControl(Photo);\nconst VideoWithSelect = withSelectControl(Video);\n\ntype OwnProps = {\n album: IAlbum;\n observeIntersection: ObserveFn;\n shouldAutoLoad?: boolean;\n shouldAutoPlay?: boolean;\n hasCustomAppendix?: boolean;\n lastSyncTime?: number;\n isOwn: boolean;\n albumLayout: IAlbumLayout;\n onMediaClick: (messageId: number) => void;\n};\n\ntype StateProps = {\n uploadsById: GlobalState['fileUploads']['byMessageLocalId'];\n};\n\ntype DispatchProps = Pick<GlobalActions, 'cancelSendingMessage'>;\n\nconst Album: FC<OwnProps & StateProps & DispatchProps> = ({\n album,\n observeIntersection,\n shouldAutoLoad,\n shouldAutoPlay,\n hasCustomAppendix,\n lastSyncTime,\n isOwn,\n albumLayout,\n onMediaClick,\n uploadsById,\n cancelSendingMessage,\n}) => {\n const mediaCount = album.messages.length;\n\n const handleCancelUpload = useCallback((message: ApiMessage) => {\n cancelSendingMessage({ chatId: message.chatId, messageId: message.id });\n }, [cancelSendingMessage]);\n\n function renderAlbumMessage(message: ApiMessage, index: number) {\n const { photo, video } = getMessageContent(message);\n const fileUpload = uploadsById[message.previousLocalId || message.id];\n const uploadProgress = fileUpload ? fileUpload.progress : undefined;\n const { dimensions, sides } = albumLayout.layout[index];\n\n if (photo) {\n const shouldAffectAppendix = hasCustomAppendix && (\n // eslint-disable-next-line no-bitwise\n isOwn ? index === mediaCount - 1 : Boolean(sides & AlbumRectPart.Left && sides & AlbumRectPart.Bottom)\n );\n\n return (\n <PhotoWithSelect\n id={`album-media-${message.id}`}\n message={message}\n observeIntersection={observeIntersection}\n shouldAutoLoad={shouldAutoLoad}\n shouldAffectAppendix={shouldAffectAppendix}\n uploadProgress={uploadProgress}\n dimensions={dimensions}\n onClick={onMediaClick}\n onCancelUpload={handleCancelUpload}\n />\n );\n } else if (video) {\n return (\n <VideoWithSelect\n id={`album-media-${message.id}`}\n message={message}\n observeIntersection={observeIntersection}\n shouldAutoLoad={shouldAutoLoad}\n shouldAutoPlay={shouldAutoPlay}\n uploadProgress={uploadProgress}\n lastSyncTime={lastSyncTime}\n dimensions={dimensions}\n onClick={onMediaClick}\n onCancelUpload={handleCancelUpload}\n />\n );\n }\n\n return undefined;\n }\n\n const { width: containerWidth, height: containerHeight } = albumLayout.containerStyle;\n\n return (\n <div\n className=\"Album\"\n // @ts-ignore\n style={`width: ${containerWidth}px; height: ${containerHeight}px;`}\n >\n {album.messages.map(renderAlbumMessage)}\n </div>\n );\n};\n\nexport default withGlobal<OwnProps>(\n (global): StateProps => {\n return {\n uploadsById: global.fileUploads.byMessageLocalId,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'cancelSendingMessage',\n ]),\n)(Album);\n","import React, {\n FC,\n useCallback,\n useEffect,\n useRef,\n useState,\n} from '../../../lib/teact/teact';\n\nimport { ApiMessage } from '../../../api/types';\n\nimport { ROUND_VIDEO_DIMENSIONS } from '../../common/helpers/mediaDimensions';\nimport { formatMediaDuration } from '../../../util/dateFormat';\nimport { getMessageMediaFormat, getMessageMediaHash } from '../../../modules/helpers';\nimport { ObserveFn, useIsIntersecting } from '../../../hooks/useIntersectionObserver';\nimport useMediaWithDownloadProgress from '../../../hooks/useMediaWithDownloadProgress';\nimport useShowTransition from '../../../hooks/useShowTransition';\nimport useTransitionForMedia from '../../../hooks/useTransitionForMedia';\nimport usePrevious from '../../../hooks/usePrevious';\nimport useBuffering from '../../../hooks/useBuffering';\nimport buildClassName from '../../../util/buildClassName';\nimport useHeavyAnimationCheckForVideo from '../../../hooks/useHeavyAnimationCheckForVideo';\nimport useVideoCleanup from '../../../hooks/useVideoCleanup';\nimport useBlurredMediaThumb from './hooks/useBlurredMediaThumb';\nimport safePlay from '../../../util/safePlay';\n\nimport ProgressSpinner from '../../ui/ProgressSpinner';\n\nimport './RoundVideo.scss';\n\ntype OwnProps = {\n message: ApiMessage;\n observeIntersection: ObserveFn;\n shouldAutoLoad?: boolean;\n shouldAutoPlay?: boolean;\n lastSyncTime?: number;\n};\n\nlet currentOnRelease: NoneToVoidFunction;\n\nfunction createCapture(onRelease: NoneToVoidFunction) {\n return () => {\n if (currentOnRelease) {\n currentOnRelease();\n }\n\n currentOnRelease = onRelease;\n };\n}\n\nconst RoundVideo: FC<OwnProps> = ({\n message,\n observeIntersection,\n shouldAutoLoad,\n shouldAutoPlay,\n lastSyncTime,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const ref = useRef<HTMLDivElement>(null);\n // eslint-disable-next-line no-null/no-null\n const playingProgressRef = useRef<HTMLDivElement>(null);\n // eslint-disable-next-line no-null/no-null\n const playerRef = useRef<HTMLVideoElement>(null);\n\n const video = message.content.video!;\n\n const isIntersecting = useIsIntersecting(ref, observeIntersection);\n\n const [isDownloadAllowed, setIsDownloadAllowed] = useState(shouldAutoLoad && shouldAutoPlay);\n const shouldDownload = Boolean(isDownloadAllowed && isIntersecting && lastSyncTime);\n const { mediaData, downloadProgress } = useMediaWithDownloadProgress(\n getMessageMediaHash(message, 'inline'),\n !shouldDownload,\n getMessageMediaFormat(message, 'inline'),\n lastSyncTime,\n );\n const thumbDataUri = useBlurredMediaThumb(message, mediaData);\n\n const { isBuffered, bufferingHandlers } = useBuffering();\n const isTransferring = isDownloadAllowed && !isBuffered;\n const wasDownloadDisabled = usePrevious(isDownloadAllowed) === false;\n const {\n shouldRender: shouldSpinnerRender,\n transitionClassNames: spinnerClassNames,\n } = useShowTransition(isTransferring || !isBuffered, undefined, wasDownloadDisabled);\n const { shouldRenderThumb, transitionClassNames } = useTransitionForMedia(mediaData, 'slow');\n\n const [isActivated, setIsActivated] = useState<boolean>(false);\n const [progress, setProgress] = useState<number>(0);\n\n useEffect(() => {\n if (!isActivated) {\n return;\n }\n\n const circumference = 94 * 2 * Math.PI;\n const strokeDashOffset = circumference - progress * circumference;\n\n const playerEl = playerRef.current!;\n const playingProgressEl = playingProgressRef.current!;\n const svgEl = playingProgressEl.firstElementChild;\n\n if (!svgEl) {\n playingProgressEl.innerHTML = `<svg width=\"200px\" height=\"200px\">\n <circle cx=\"100\" cy=\"100\" r=\"94\" class=\"progress-circle\" transform=\"rotate(-90, 100, 100)\"\n stroke-dasharray=\"${circumference} ${circumference}\"\n stroke-dashoffset=\"${circumference}\"\n />\n </svg>`;\n } else {\n (svgEl.firstElementChild as SVGElement).setAttribute('stroke-dashoffset', strokeDashOffset.toString());\n }\n\n setProgress(playerEl.currentTime / playerEl.duration);\n }, [isActivated, progress]);\n\n const shouldPlay = Boolean(mediaData && isIntersecting);\n\n const stopPlaying = () => {\n setIsActivated(false);\n setProgress(0);\n safePlay(playerRef.current!);\n\n requestAnimationFrame(() => {\n playingProgressRef.current!.innerHTML = '';\n });\n };\n\n const capturePlaying = createCapture(stopPlaying);\n\n useEffect(() => {\n if (!playerRef.current) {\n return;\n }\n\n if (shouldPlay) {\n safePlay(playerRef.current);\n } else {\n playerRef.current.pause();\n }\n }, [shouldPlay]);\n\n useHeavyAnimationCheckForVideo(playerRef, shouldPlay);\n\n useVideoCleanup(playerRef, [mediaData]);\n\n const handleClick = useCallback(() => {\n if (!mediaData) {\n setIsDownloadAllowed((isAllowed) => !isAllowed);\n\n return;\n }\n\n const playerEl = playerRef.current!;\n if (isActivated) {\n if (playerEl.paused) {\n safePlay(playerEl);\n } else {\n playerEl.pause();\n }\n } else {\n playerEl.currentTime = 0;\n setIsActivated(true);\n capturePlaying();\n }\n }, [capturePlaying, isActivated, mediaData]);\n\n const handleTimeUpdate = useCallback((e: React.UIEvent<HTMLVideoElement>) => {\n const playerEl = e.currentTarget;\n\n setProgress(playerEl.currentTime / playerEl.duration);\n }, []);\n\n const videoClassName = buildClassName('full-media', transitionClassNames);\n\n return (\n <div\n ref={ref}\n className=\"RoundVideo media-inner\"\n onClick={handleClick}\n >\n {shouldRenderThumb && (\n <div className=\"thumbnail-wrapper\">\n <img\n src={thumbDataUri}\n className=\"thumbnail\"\n width={ROUND_VIDEO_DIMENSIONS}\n height={ROUND_VIDEO_DIMENSIONS}\n alt=\"\"\n />\n </div>\n )}\n {mediaData && (\n <div className=\"video-wrapper\">\n {/* eslint-disable-next-line jsx-a11y/media-has-caption */}\n <video\n ref={playerRef}\n className={videoClassName}\n width={ROUND_VIDEO_DIMENSIONS}\n height={ROUND_VIDEO_DIMENSIONS}\n autoPlay\n muted={!isActivated}\n loop={!isActivated}\n playsInline\n poster={thumbDataUri}\n onEnded={isActivated ? stopPlaying : undefined}\n // eslint-disable-next-line react/jsx-props-no-spreading\n {...bufferingHandlers}\n onTimeUpdate={isActivated ? handleTimeUpdate : undefined}\n >\n <source src={mediaData} />\n </video>\n </div>\n )}\n <div className=\"progress\" ref={playingProgressRef} />\n {shouldSpinnerRender && (\n <div className={`media-loading ${spinnerClassNames}`}>\n <ProgressSpinner progress={downloadProgress} />\n </div>\n )}\n {!mediaData && !isDownloadAllowed && (\n <i className=\"icon-large-play\" />\n )}\n <div className=\"message-media-duration\">\n {isActivated ? formatMediaDuration(playerRef.current!.currentTime) : formatMediaDuration(video.duration)}\n {(!isActivated || playerRef.current!.paused) && <i className=\"icon-muted-chat\" />}\n </div>\n </div>\n );\n};\n\nexport default RoundVideo;\n","import React, { FC } from '../../../lib/teact/teact';\n\nimport { ApiKeyboardButton, ApiMessage } from '../../../api/types';\n\nimport Button from '../../ui/Button';\n\nimport './InlineButtons.scss';\n\ntype OwnProps = {\n message: ApiMessage;\n onClick: ({ button }: { button: ApiKeyboardButton }) => void;\n};\n\nconst InlineButtons: FC<OwnProps> = ({ message, onClick }) => {\n return (\n <div className=\"InlineButtons\">\n {message.inlineButtons!.map((row) => (\n <div className=\"row\">\n {row.map((button) => (\n <Button\n size=\"tiny\"\n ripple\n disabled={button.type === 'NOT_SUPPORTED'}\n onClick={() => onClick({ button })}\n >\n {button.text}\n </Button>\n ))}\n </div>\n ))}\n </div>\n );\n};\n\nexport default InlineButtons;\n","import React, { FC, memo, useCallback } from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport {\n ApiChat, ApiMessage, ApiThreadInfo, ApiUser,\n} from '../../../api/types';\nimport { GlobalActions } from '../../../global/types';\n\nimport { pick } from '../../../util/iteratees';\nimport { isChatPrivate } from '../../../modules/helpers';\nimport { formatInteger, formatIntegerCompact } from '../../../util/textFormat';\nimport buildClassName from '../../../util/buildClassName';\nimport { selectThreadInfo } from '../../../modules/selectors';\n\nimport Avatar from '../../common/Avatar';\n\nimport './CommentButton.scss';\n\ntype OwnProps = {\n message: ApiMessage;\n disabled?: boolean;\n};\n\ntype StateProps = {\n threadInfo: ApiThreadInfo;\n usersById?: Record<number, ApiUser>;\n chatsById?: Record<number, ApiChat>;\n};\n\ntype DispatchProps = Pick<GlobalActions, 'openChat'>;\n\nconst CommentButton: FC<OwnProps & StateProps & DispatchProps> = ({\n disabled, threadInfo, usersById, chatsById, openChat,\n}) => {\n const {\n threadId, chatId, messagesCount, lastMessageId, lastReadInboxMessageId, recentReplierIds,\n } = threadInfo;\n\n const handleClick = useCallback(() => {\n openChat({ id: chatId, threadId });\n }, [openChat, chatId, threadId]);\n\n if (messagesCount === undefined) {\n return undefined;\n }\n\n const recentRepliers = recentReplierIds && recentReplierIds.map((peerId) => {\n return isChatPrivate(peerId) ? usersById![peerId] : chatsById![peerId];\n }).filter(Boolean);\n\n function renderRecentRepliers() {\n return (\n recentRepliers && recentRepliers.length > 0 && (\n <div className=\"recent-repliers\">\n {recentRepliers.map((user) => (\n <Avatar\n key={user.id}\n size=\"small\"\n user={isChatPrivate(user.id) ? user as ApiUser : undefined}\n chat={!isChatPrivate(user.id) ? user as ApiChat : undefined}\n />\n ))}\n </div>\n )\n );\n }\n\n const hasUnread = Boolean(lastReadInboxMessageId && lastMessageId && lastReadInboxMessageId < lastMessageId);\n\n return (\n <div\n data-cnt={formatIntegerCompact(messagesCount)}\n className={buildClassName('CommentButton', hasUnread && 'has-unread', disabled && 'disabled')}\n onClick={handleClick}\n >\n <i className=\"icon-comments-sticker\" />\n {(!recentRepliers || recentRepliers.length === 0) && <i className=\"icon-comments\" />}\n {renderRecentRepliers()}\n <div className=\"label\">{renderLabel(messagesCount)}</div>\n <i className=\"icon-next\" />\n </div>\n );\n};\n\nfunction renderLabel(messagesCount: number) {\n if (messagesCount === 0) {\n return 'Leave a Comment';\n }\n\n if (messagesCount === 1) {\n return '1 Comment';\n }\n\n return `${formatInteger(messagesCount)} Comments`;\n}\n\nexport default memo(withGlobal<OwnProps>(\n (global, { message }) => {\n const { threadId, chatId } = message.threadInfo!;\n\n const threadInfo = selectThreadInfo(global, chatId, threadId) || message.threadInfo!;\n const { byId: usersById } = global.users;\n const { byId: chatsById } = global.chats;\n\n return {\n threadInfo,\n usersById,\n chatsById,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'openChat',\n ]),\n)(CommentButton));\n","import { MouseEvent as ReactMouseEvent } from 'react';\nimport React, {\n FC,\n memo,\n useCallback,\n useEffect,\n useLayoutEffect,\n useMemo,\n useRef,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalActions, MessageListType } from '../../../global/types';\nimport {\n ApiMessage,\n ApiMessageOutgoingStatus,\n ApiUser,\n ApiChat,\n ApiSticker,\n MAIN_THREAD_ID,\n} from '../../../api/types';\nimport { FocusDirection, IAlbum, MediaViewerOrigin } from '../../../types';\n\nimport { pick } from '../../../util/iteratees';\nimport {\n selectChat,\n selectChatMessage,\n selectUploadProgress,\n selectIsChatWithSelf,\n selectOutgoingStatus,\n selectUser,\n selectIsMessageFocused,\n selectCurrentTextSearch,\n selectAnimatedEmoji,\n selectIsInSelectMode,\n selectIsMessageSelected,\n selectIsDocumentGroupSelected,\n selectSender,\n selectForwardedSender,\n selectThreadTopMessageId,\n selectShouldAutoLoadMedia,\n selectShouldAutoPlayMedia, selectShouldLoopStickers,\n} from '../../../modules/selectors';\nimport {\n getMessageContent,\n isOwnMessage,\n isReplyMessage,\n isAnonymousOwnMessage,\n isChatPrivate,\n getMessageCustomShape,\n isChatChannel,\n getMessageSingleEmoji, getSenderTitle, getUserColorKey,\n} from '../../../modules/helpers';\nimport buildClassName from '../../../util/buildClassName';\nimport useEnsureMessage from '../../../hooks/useEnsureMessage';\nimport useContextMenuHandlers from '../../../hooks/useContextMenuHandlers';\nimport { renderMessageText } from '../../common/helpers/renderMessageText';\nimport { ROUND_VIDEO_DIMENSIONS } from '../../common/helpers/mediaDimensions';\nimport { buildContentClassName, isEmojiOnlyMessage } from './helpers/buildContentClassName';\nimport { getMinMediaWidth, calculateMediaDimensions } from './helpers/mediaDimensions';\nimport { calculateAlbumLayout } from './helpers/calculateAlbumLayout';\nimport renderText from '../../common/helpers/renderText';\nimport calculateAuthorWidth from './helpers/calculateAuthorWidth';\nimport { ObserveFn, useOnIntersect } from '../../../hooks/useIntersectionObserver';\nimport useFocusMessage from './hooks/useFocusMessage';\nimport useWindowSize from '../../../hooks/useWindowSize';\nimport useLang from '../../../hooks/useLang';\nimport useShowTransition from '../../../hooks/useShowTransition';\nimport useFlag from '../../../hooks/useFlag';\n\nimport Button from '../../ui/Button';\nimport Avatar from '../../common/Avatar';\nimport EmbeddedMessage from '../../common/EmbeddedMessage';\nimport Document from '../../common/Document';\nimport Audio from '../../common/Audio';\nimport MessageMeta from './MessageMeta';\nimport ContextMenuContainer from './ContextMenuContainer.async';\nimport Sticker from './Sticker';\nimport AnimatedEmoji from '../../common/AnimatedEmoji';\nimport Photo from './Photo';\nimport Video from './Video';\nimport Contact from './Contact';\nimport Poll from './Poll';\nimport WebPage from './WebPage';\nimport Invoice from './Invoice';\nimport Album from './Album';\nimport RoundVideo from './RoundVideo';\nimport InlineButtons from './InlineButtons';\nimport CommentsButton from './CommentButton';\n\nimport './Message.scss';\n\ntype MessagePositionProperties = {\n isFirstInGroup: boolean;\n isLastInGroup: boolean;\n isFirstInDocumentGroup: boolean;\n isLastInDocumentGroup: boolean;\n isLastInList: boolean;\n};\n\ntype OwnProps = {\n message: ApiMessage;\n observeIntersectionForBottom: ObserveFn;\n observeIntersectionForMedia: ObserveFn;\n observeIntersectionForAnimatedStickers: ObserveFn;\n album?: IAlbum;\n withAvatar?: boolean;\n withSenderName?: boolean;\n threadId: number;\n messageListType: MessageListType;\n noComments: boolean;\n appearanceOrder: number;\n} & MessagePositionProperties;\n\ntype StateProps = {\n forceSenderName?: boolean;\n sender?: ApiUser | ApiChat;\n originSender?: ApiUser | ApiChat;\n botSender?: ApiUser;\n isThreadTop?: boolean;\n shouldHideReply?: boolean;\n replyMessage?: ApiMessage;\n replyMessageSender?: ApiUser | ApiChat;\n outgoingStatus?: ApiMessageOutgoingStatus;\n uploadProgress?: number;\n isFocused?: boolean;\n focusDirection?: FocusDirection;\n noFocusHighlight?: boolean;\n isForwarding?: boolean;\n isChatWithSelf?: boolean;\n isChannel?: boolean;\n lastSyncTime?: number;\n highlight?: string;\n isSingleEmoji?: boolean;\n animatedEmoji?: ApiSticker;\n isInSelectMode?: boolean;\n isSelected?: boolean;\n isGroupSelected?: boolean;\n threadId?: number;\n isPinnedList?: boolean;\n shouldAutoLoadMedia?: boolean;\n shouldAutoPlayMedia?: boolean;\n shouldLoopStickers?: boolean;\n};\n\ntype DispatchProps = Pick<GlobalActions, (\n 'focusMessage' | 'openMediaViewer' | 'openAudioPlayer' |\n 'openUserInfo' | 'openChat' |\n 'cancelSendingMessage' | 'markMessagesRead' |\n 'sendPollVote' | 'toggleMessageSelection' | 'setReplyingToId' | 'openForwardMenu' |\n 'clickInlineButton'\n)>;\n\nconst NBSP = '\\u00A0';\nconst GROUP_MESSAGE_HOVER_ATTRIBUTE = 'data-is-document-group-hover';\n// eslint-disable-next-line max-len\nconst APPENDIX_OWN = '<svg width=\"9\" height=\"20\" xmlns=\"http://www.w3.org/2000/svg\"><defs><filter x=\"-50%\" y=\"-14.7%\" width=\"200%\" height=\"141.2%\" filterUnits=\"objectBoundingBox\" id=\"a\"><feOffset dy=\"1\" in=\"SourceAlpha\" result=\"shadowOffsetOuter1\"/><feGaussianBlur stdDeviation=\"1\" in=\"shadowOffsetOuter1\" result=\"shadowBlurOuter1\"/><feColorMatrix values=\"0 0 0 0 0.0621962482 0 0 0 0 0.138574144 0 0 0 0 0.185037364 0 0 0 0.15 0\" in=\"shadowBlurOuter1\"/></filter></defs><g fill=\"none\" fill-rule=\"evenodd\"><path d=\"M6 17H0V0c.193 2.84.876 5.767 2.05 8.782.904 2.325 2.446 4.485 4.625 6.48A1 1 0 016 17z\" fill=\"#000\" filter=\"url(#a)\"/><path d=\"M6 17H0V0c.193 2.84.876 5.767 2.05 8.782.904 2.325 2.446 4.485 4.625 6.48A1 1 0 016 17z\" fill=\"#EEFFDE\" class=\"corner\"/></g></svg>';\n// eslint-disable-next-line max-len\nconst APPENDIX_NOT_OWN = '<svg width=\"9\" height=\"20\" xmlns=\"http://www.w3.org/2000/svg\"><defs><filter x=\"-50%\" y=\"-14.7%\" width=\"200%\" height=\"141.2%\" filterUnits=\"objectBoundingBox\" id=\"a\"><feOffset dy=\"1\" in=\"SourceAlpha\" result=\"shadowOffsetOuter1\"/><feGaussianBlur stdDeviation=\"1\" in=\"shadowOffsetOuter1\" result=\"shadowBlurOuter1\"/><feColorMatrix values=\"0 0 0 0 0.0621962482 0 0 0 0 0.138574144 0 0 0 0 0.185037364 0 0 0 0.15 0\" in=\"shadowBlurOuter1\"/></filter></defs><g fill=\"none\" fill-rule=\"evenodd\"><path d=\"M3 17h6V0c-.193 2.84-.876 5.767-2.05 8.782-.904 2.325-2.446 4.485-4.625 6.48A1 1 0 003 17z\" fill=\"#000\" filter=\"url(#a)\"/><path d=\"M3 17h6V0c-.193 2.84-.876 5.767-2.05 8.782-.904 2.325-2.446 4.485-4.625 6.48A1 1 0 003 17z\" fill=\"#FFF\" class=\"corner\"/></g></svg>';\nconst APPEARANCE_DELAY = 10;\n\nconst Message: FC<OwnProps & StateProps & DispatchProps> = ({\n message,\n observeIntersectionForBottom,\n observeIntersectionForMedia,\n observeIntersectionForAnimatedStickers,\n album,\n withAvatar,\n withSenderName,\n noComments,\n appearanceOrder,\n isFirstInGroup,\n isLastInGroup,\n isFirstInDocumentGroup,\n isLastInDocumentGroup,\n isLastInList,\n forceSenderName,\n sender,\n originSender,\n botSender,\n isThreadTop,\n shouldHideReply,\n replyMessage,\n replyMessageSender,\n outgoingStatus,\n uploadProgress,\n isFocused,\n focusDirection,\n noFocusHighlight,\n isForwarding,\n isChatWithSelf,\n isChannel,\n lastSyncTime,\n highlight,\n animatedEmoji,\n isInSelectMode,\n isSelected,\n isGroupSelected,\n threadId,\n messageListType,\n isPinnedList,\n shouldAutoLoadMedia,\n shouldAutoPlayMedia,\n shouldLoopStickers,\n focusMessage,\n openMediaViewer,\n openAudioPlayer,\n openUserInfo,\n openChat,\n cancelSendingMessage,\n markMessagesRead,\n sendPollVote,\n toggleMessageSelection,\n setReplyingToId,\n openForwardMenu,\n clickInlineButton,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const ref = useRef<HTMLDivElement>(null);\n // eslint-disable-next-line no-null/no-null\n const bottomMarkerRef = useRef<HTMLDivElement>(null);\n // eslint-disable-next-line no-null/no-null\n const appendixRef = useRef<HTMLDivElement>(null);\n\n useOnIntersect(bottomMarkerRef, observeIntersectionForBottom);\n\n const { width: windowWidth } = useWindowSize();\n\n const {\n isContextMenuOpen, contextMenuPosition,\n handleBeforeContextMenu, handleContextMenu,\n handleContextMenuClose, handleContextMenuHide,\n } = useContextMenuHandlers(ref);\n\n const noAppearanceAnimation = appearanceOrder <= 0;\n const [isShown, markShown] = useFlag(noAppearanceAnimation);\n useEffect(() => {\n if (noAppearanceAnimation) {\n return;\n }\n\n setTimeout(markShown, appearanceOrder * APPEARANCE_DELAY);\n }, [appearanceOrder, markShown, noAppearanceAnimation]);\n const { transitionClassNames } = useShowTransition(isShown, undefined, noAppearanceAnimation, false);\n\n const { chatId, id: messageId, threadInfo } = message;\n\n const isOwn = isOwnMessage(message);\n const isScheduled = messageListType === 'scheduled' || message.isScheduled;\n const hasReply = isReplyMessage(message) && !shouldHideReply;\n const hasThread = Boolean(threadInfo) && messageListType === 'thread';\n const { forwardInfo, viaBotId } = message;\n const asForwarded = forwardInfo && !isChatWithSelf && !forwardInfo.isLinkedChannelPost;\n const isInDocumentGroup = !!message.groupedId && !message.isInAlbum;\n const isAlbum = Boolean(album) && album!.messages.length > 1;\n const {\n text, photo, video, audio, voice, document, sticker, contact, poll, webPage, invoice,\n } = getMessageContent(message);\n const customShape = getMessageCustomShape(message);\n const textParts = renderMessageText(message, highlight, isEmojiOnlyMessage(customShape));\n const isContextMenuShown = contextMenuPosition !== undefined;\n const containerClassName = buildClassName(\n 'Message message-list-item',\n isFirstInGroup && 'first-in-group',\n isLastInGroup && 'last-in-group',\n isFirstInDocumentGroup && 'first-in-document-group',\n isLastInDocumentGroup && 'last-in-document-group',\n isLastInList && 'last-in-list',\n isOwn && 'own',\n Boolean(message.views) && 'has-views',\n message.isEdited && 'was-edited',\n hasReply && 'has-reply',\n isContextMenuShown && 'has-menu-open',\n isFocused && !noFocusHighlight && 'focused',\n isForwarding && 'is-forwarding',\n message.isDeleting && 'is-deleting',\n isInDocumentGroup && 'is-in-document-group',\n isAlbum && 'is-album',\n message.hasUnreadMention && 'has-unread-mention',\n isSelected && 'is-selected',\n isInSelectMode && 'is-in-selection-mode',\n isThreadTop && 'is-thread-top',\n Boolean(message.inlineButtons) && 'has-inline-buttons',\n transitionClassNames,\n );\n const contentClassName = buildContentClassName(message, {\n hasReply,\n customShape,\n isLastInGroup,\n asForwarded,\n hasThread,\n forceSenderName,\n hasComments: message.threadInfo && message.threadInfo.messagesCount > 0,\n });\n const avatarPeer = forwardInfo && (isChatWithSelf || !sender) ? originSender : sender;\n const senderPeer = forwardInfo ? originSender : sender;\n const signature = (\n (isChannel && message.adminTitle) || (forwardInfo && !asForwarded && forwardInfo.adminTitle) || undefined\n );\n\n useEnsureMessage(chatId, hasReply ? message.replyToMessageId : undefined, replyMessage, message.id);\n useFocusMessage(ref, chatId, isFocused, focusDirection, noFocusHighlight);\n useLayoutEffect(() => {\n if (!appendixRef.current) {\n return;\n }\n\n appendixRef.current.innerHTML = isOwn ? APPENDIX_OWN : APPENDIX_NOT_OWN;\n }, [isOwn]);\n\n const handleGroupDocumentMessagesSelect = useCallback((e: ReactMouseEvent<HTMLDivElement, MouseEvent>) => {\n e.stopPropagation();\n\n toggleMessageSelection({\n messageId,\n groupedId: message.groupedId,\n });\n }, [messageId, message.groupedId, toggleMessageSelection]);\n\n const handleMessageSelect = useCallback((e?: ReactMouseEvent<HTMLDivElement, MouseEvent>) => {\n const params = isAlbum && album && album.messages\n ? {\n messageId,\n childMessageIds: album.messages.map(({ id }) => id),\n withShift: e && e.shiftKey,\n }\n : { messageId, withShift: e && e.shiftKey };\n toggleMessageSelection(params);\n }, [toggleMessageSelection, messageId, isAlbum, album]);\n\n const handleContainerDoubleClick = useCallback(() => {\n setReplyingToId({ messageId });\n }, [setReplyingToId, messageId]);\n\n const handleContentDoubleClick = useCallback((e: ReactMouseEvent<HTMLDivElement, MouseEvent>) => {\n e.stopPropagation();\n }, []);\n\n const handleAvatarClick = useCallback(() => {\n if (!avatarPeer) {\n return;\n }\n\n if (isChatPrivate(avatarPeer.id)) {\n openUserInfo({ id: avatarPeer.id });\n } else {\n openChat({ id: avatarPeer.id });\n }\n }, [avatarPeer, openUserInfo, openChat]);\n\n const handleSenderClick = useCallback(() => {\n if (!senderPeer) {\n return;\n }\n\n if (isChatPrivate(senderPeer.id)) {\n openUserInfo({ id: senderPeer.id });\n } else {\n openChat({ id: senderPeer.id });\n }\n }, [senderPeer, openUserInfo, openChat]);\n\n const handleViaBotClick = useCallback(() => {\n if (!botSender) {\n return;\n }\n\n openUserInfo({ id: botSender.id });\n }, [botSender, openUserInfo]);\n\n const handleReplyClick = useCallback((): void => {\n focusMessage({ chatId, threadId, messageId: message.replyToMessageId });\n }, [focusMessage, chatId, threadId, message.replyToMessageId]);\n\n const handleMediaClick = useCallback((): void => {\n openMediaViewer({\n chatId, threadId, messageId, origin: isScheduled ? MediaViewerOrigin.ScheduledInline : MediaViewerOrigin.Inline,\n });\n }, [chatId, threadId, messageId, openMediaViewer, isScheduled]);\n\n const handleAudioPlay = useCallback((): void => {\n openAudioPlayer({ chatId, messageId });\n }, [chatId, messageId, openAudioPlayer]);\n\n const handleAlbumMediaClick = useCallback((albumMessageId: number): void => {\n openMediaViewer({\n chatId,\n threadId,\n messageId: albumMessageId,\n origin: isScheduled ? MediaViewerOrigin.ScheduledAlbum : MediaViewerOrigin.Album,\n });\n }, [chatId, threadId, openMediaViewer, isScheduled]);\n\n const handleReadMedia = useCallback((): void => {\n markMessagesRead({ messageIds: [messageId] });\n }, [messageId, markMessagesRead]);\n\n const handleCancelUpload = useCallback(() => {\n cancelSendingMessage({ chatId, messageId });\n }, [cancelSendingMessage, chatId, messageId]);\n\n const handleVoteSend = useCallback((options: string[]) => {\n sendPollVote({ chatId, messageId, options });\n }, [chatId, messageId, sendPollVote]);\n\n const handleGroupForward = useCallback(() => {\n openForwardMenu({ fromChatId: chatId, groupedId: message.groupedId });\n }, [openForwardMenu, chatId, message.groupedId]);\n\n const handleForward = useCallback(() => {\n if (album && album.messages) {\n const messageIds = album.messages.map(({ id }) => id);\n openForwardMenu({ fromChatId: chatId, messageIds });\n } else {\n openForwardMenu({ fromChatId: chatId, messageIds: [messageId] });\n }\n }, [album, openForwardMenu, chatId, messageId]);\n\n const handleFocus = useCallback(() => {\n focusMessage({\n chatId, threadId: MAIN_THREAD_ID, messageId,\n });\n }, [focusMessage, chatId, messageId]);\n\n const handleFocusForwarded = useCallback(() => {\n if (isInDocumentGroup) {\n focusMessage({\n chatId: forwardInfo!.fromChatId, groupedId: message.groupedId, groupedChatId: chatId,\n });\n return;\n }\n focusMessage({\n chatId: forwardInfo!.fromChatId, messageId: forwardInfo!.fromMessageId,\n });\n }, [focusMessage, forwardInfo, message, chatId, isInDocumentGroup]);\n\n const lang = useLang();\n\n let style = '';\n let calculatedWidth;\n const albumLayout = useMemo(() => {\n return isAlbum ? calculateAlbumLayout(isOwn, Boolean(asForwarded), album!, windowWidth) : undefined;\n }, [isAlbum, windowWidth, isOwn, asForwarded, album]);\n\n const extraPadding = asForwarded ? 28 : 0;\n if (!isAlbum && (photo || video)) {\n let width: number | undefined;\n if (photo) {\n width = calculateMediaDimensions(message).width;\n } else if (video) {\n if (video.isRound) {\n width = ROUND_VIDEO_DIMENSIONS;\n } else {\n width = calculateMediaDimensions(message).width;\n }\n }\n\n if (width) {\n calculatedWidth = Math.max(getMinMediaWidth(Boolean(text)), width);\n }\n } else if (albumLayout) {\n calculatedWidth = Math.max(getMinMediaWidth(Boolean(text)), albumLayout.containerStyle.width);\n }\n\n if (calculatedWidth) {\n style = `width: ${calculatedWidth + extraPadding}px`;\n }\n\n function renderAvatar() {\n const isAvatarPeerUser = avatarPeer && isChatPrivate(avatarPeer.id);\n const avatarUser = avatarPeer && isAvatarPeerUser ? avatarPeer as ApiUser : undefined;\n const avatarChat = avatarPeer && !isAvatarPeerUser ? avatarPeer as ApiChat : undefined;\n const hiddenName = !avatarPeer && forwardInfo ? forwardInfo.hiddenUserName : undefined;\n\n return (\n <Avatar\n size=\"small\"\n user={avatarUser}\n chat={avatarChat}\n text={hiddenName}\n lastSyncTime={lastSyncTime}\n onClick={(avatarUser || avatarChat) ? handleAvatarClick : undefined}\n />\n );\n }\n\n function renderContent() {\n const className = buildClassName(\n 'content-inner',\n asForwarded && !customShape && 'forwarded-message',\n hasReply && 'reply-message',\n );\n const hasCustomAppendix = isLastInGroup && !textParts && !asForwarded && !hasThread;\n\n return (\n <div className={className} onDoubleClick={handleContentDoubleClick}>\n {renderSenderName()}\n {hasReply && (\n <EmbeddedMessage\n message={replyMessage}\n sender={replyMessageSender}\n observeIntersection={observeIntersectionForMedia}\n onClick={handleReplyClick}\n />\n )}\n {sticker && (\n <Sticker\n message={message}\n observeIntersection={observeIntersectionForMedia}\n observeIntersectionForPlaying={observeIntersectionForAnimatedStickers}\n shouldLoop={shouldLoopStickers}\n lastSyncTime={lastSyncTime}\n />\n )}\n {animatedEmoji && (\n <AnimatedEmoji\n isInline\n sticker={animatedEmoji}\n observeIntersection={observeIntersectionForMedia}\n lastSyncTime={lastSyncTime}\n />\n )}\n {isAlbum && (\n <Album\n album={album!}\n albumLayout={albumLayout!}\n observeIntersection={observeIntersectionForMedia}\n shouldAutoLoad={shouldAutoLoadMedia}\n shouldAutoPlay={shouldAutoPlayMedia}\n isOwn={isOwn}\n hasCustomAppendix={hasCustomAppendix}\n lastSyncTime={lastSyncTime}\n onMediaClick={handleAlbumMediaClick}\n />\n )}\n {!isAlbum && photo && (\n <Photo\n message={message}\n observeIntersection={observeIntersectionForMedia}\n shouldAutoLoad={shouldAutoLoadMedia}\n uploadProgress={uploadProgress}\n shouldAffectAppendix={hasCustomAppendix}\n onClick={handleMediaClick}\n onCancelUpload={handleCancelUpload}\n />\n )}\n {!isAlbum && video && video.isRound && (\n <RoundVideo\n message={message}\n observeIntersection={observeIntersectionForMedia}\n shouldAutoLoad={shouldAutoLoadMedia}\n shouldAutoPlay={shouldAutoPlayMedia}\n lastSyncTime={lastSyncTime}\n />\n )}\n {!isAlbum && video && !video.isRound && (\n <Video\n message={message}\n observeIntersection={observeIntersectionForMedia}\n shouldAutoLoad={shouldAutoLoadMedia}\n shouldAutoPlay={shouldAutoPlayMedia}\n uploadProgress={uploadProgress}\n lastSyncTime={lastSyncTime}\n onClick={handleMediaClick}\n onCancelUpload={handleCancelUpload}\n />\n )}\n {(audio || voice) && (\n <Audio\n message={message}\n uploadProgress={uploadProgress}\n lastSyncTime={lastSyncTime}\n isSelectable={isInDocumentGroup}\n isSelected={isSelected}\n onPlay={handleAudioPlay}\n onReadMedia={voice && (!isOwn || isChatWithSelf) ? handleReadMedia : undefined}\n onCancelUpload={handleCancelUpload}\n />\n )}\n {document && (\n <Document\n message={message}\n observeIntersection={observeIntersectionForMedia}\n uploadProgress={uploadProgress}\n isSelectable={isInDocumentGroup}\n isSelected={isSelected}\n onCancelUpload={handleCancelUpload}\n />\n )}\n {contact && (\n <Contact contact={contact} />\n )}\n {poll && (\n <Poll message={message} poll={poll} onSendVote={handleVoteSend} />\n )}\n {!animatedEmoji && textParts && <p className=\"text-content\">{textParts}</p>}\n {webPage && (\n <WebPage\n message={message}\n observeIntersection={observeIntersectionForMedia}\n shouldAutoLoad={shouldAutoLoadMedia}\n onMediaClick={handleMediaClick}\n onCancelMediaTransfer={handleCancelUpload}\n />\n )}\n {invoice && (\n <Invoice\n message={message}\n />\n )}\n </div>\n );\n }\n\n function renderSenderName() {\n const shouldRender = !customShape && (\n (withSenderName && !photo && !video) || asForwarded || viaBotId || forceSenderName\n ) && (!isInDocumentGroup || isFirstInDocumentGroup);\n\n if (!shouldRender) {\n return undefined;\n }\n\n let senderTitle;\n let senderColor;\n if (senderPeer) {\n senderTitle = getSenderTitle(senderPeer);\n\n if (!asForwarded) {\n senderColor = `color-${getUserColorKey(senderPeer)}`;\n }\n } else if (forwardInfo && forwardInfo.hiddenUserName) {\n senderTitle = forwardInfo.hiddenUserName;\n }\n\n return (\n <div className=\"message-title\">\n {senderTitle ? (\n <span\n className={buildClassName(senderPeer && 'interactive', senderColor)}\n onClick={senderPeer ? handleSenderClick : undefined}\n >\n {renderText(senderTitle)}\n </span>\n ) : !botSender ? (\n NBSP\n ) : undefined}\n {botSender && (\n <>\n <span className=\"via\">{lang('ViaBot')}</span>\n <span\n className=\"interactive\"\n onClick={handleViaBotClick}\n >\n {renderText(`@${botSender.username}`)}\n </span>\n </>\n )}\n {forwardInfo && forwardInfo.isLinkedChannelPost ? (\n <span className=\"admin-title\">{lang('DiscussChannel')}</span>\n ) : message.adminTitle && !isChannel ? (\n <span className=\"admin-title\">{message.adminTitle}</span>\n ) : undefined}\n </div>\n );\n }\n\n const metaSafeAuthorWidth = useMemo(() => {\n return signature ? calculateAuthorWidth(signature) : undefined;\n }, [signature]);\n\n const canShowActionButton = (\n !(isContextMenuShown || isInSelectMode || isForwarding)\n && (!isInDocumentGroup || isLastInDocumentGroup)\n );\n const canForward = canShowActionButton && isChannel && !isScheduled;\n const canFocus = canShowActionButton && (\n (forwardInfo && (forwardInfo.isChannelPost || (isChatWithSelf && !isOwn)) && forwardInfo.fromMessageId)\n || isPinnedList\n );\n const showCommentsButton = message.threadInfo && (!isInDocumentGroup || isLastInDocumentGroup)\n && messageListType === 'thread' && !noComments;\n\n return (\n <div\n ref={ref}\n id={`message${messageId}`}\n className={containerClassName}\n // @ts-ignore teact feature\n style={metaSafeAuthorWidth ? `--meta-safe-author-width: ${metaSafeAuthorWidth}px` : undefined}\n data-message-id={messageId}\n onClick={isInSelectMode ? handleMessageSelect : undefined}\n onDoubleClick={!isInSelectMode ? handleContainerDoubleClick : undefined}\n onMouseDown={!isInSelectMode ? handleBeforeContextMenu : undefined}\n onContextMenu={!isInSelectMode ? handleContextMenu : undefined}\n onMouseEnter={isInDocumentGroup && !isLastInDocumentGroup ? handleDocumentGroupMouseEnter : undefined}\n onMouseLeave={isInDocumentGroup && !isLastInDocumentGroup ? handleDocumentGroupMouseLeave : undefined}\n >\n <div\n ref={bottomMarkerRef}\n className=\"bottom-marker\"\n data-message-id={messageId}\n data-last-message-id={album ? album.messages[album.messages.length - 1].id : undefined}\n data-has-unread-mention={message.hasUnreadMention}\n />\n {!isInDocumentGroup && (\n <div className=\"message-select-control\">\n {isSelected && <i className=\"icon-select\" />}\n </div>\n )}\n {isLastInDocumentGroup && (\n <div\n className={buildClassName('message-select-control group-select', isGroupSelected && 'is-selected')}\n onClick={handleGroupDocumentMessagesSelect}\n >\n {isGroupSelected && (\n <i className=\"icon-select\" />\n )}\n </div>\n )}\n {withAvatar && renderAvatar()}\n <div\n className=\"message-content-wrapper\"\n onClick={isInSelectMode && isInDocumentGroup ? handleMessageSelect : undefined}\n >\n <div\n className={contentClassName}\n // @ts-ignore\n style={style}\n >\n {contentClassName.includes('has-appendix') && (<div className=\"svg-appendix\" ref={appendixRef} />)}\n {asForwarded && !customShape && (!isInDocumentGroup || isFirstInDocumentGroup) && (\n <div className=\"message-title\">{lang('ForwardedMessage')}</div>\n )}\n {renderContent()}\n {(!isInDocumentGroup || isLastInDocumentGroup) && (\n <MessageMeta\n message={message}\n outgoingStatus={outgoingStatus}\n signature={signature}\n onClick={handleMessageSelect}\n />\n )}\n {canForward ? (\n <Button\n className=\"message-action-button\"\n color=\"translucent-white\"\n round\n size=\"tiny\"\n ariaLabel=\"Forward message\"\n onClick={isLastInDocumentGroup ? handleGroupForward : handleForward}\n >\n <i className=\"icon-share-filled\" />\n </Button>\n ) : canFocus ? (\n <Button\n className=\"message-action-button\"\n color=\"translucent-white\"\n round\n size=\"tiny\"\n ariaLabel=\"Focus message\"\n onClick={isPinnedList ? handleFocus : handleFocusForwarded}\n >\n <i className=\"icon-arrow-right\" />\n </Button>\n ) : undefined}\n {showCommentsButton && <CommentsButton message={message} disabled={noComments} />}\n </div>\n {message.inlineButtons && (\n <InlineButtons message={message} onClick={clickInlineButton} />\n )}\n </div>\n {contextMenuPosition && (\n <ContextMenuContainer\n isOpen={isContextMenuOpen}\n anchor={contextMenuPosition}\n message={message}\n album={album}\n messageListType={messageListType}\n onClose={handleContextMenuClose}\n onCloseAnimationEnd={handleContextMenuHide}\n />\n )}\n </div>\n );\n};\n\nfunction handleDocumentGroupMouseEnter(e: React.MouseEvent<HTMLDivElement>) {\n const lastGroupElement = getLastElementInDocumentGroup(e.currentTarget);\n if (lastGroupElement) {\n lastGroupElement.setAttribute(GROUP_MESSAGE_HOVER_ATTRIBUTE, '');\n }\n}\n\nfunction handleDocumentGroupMouseLeave(e: React.MouseEvent<HTMLDivElement>) {\n const lastGroupElement = getLastElementInDocumentGroup(e.currentTarget);\n if (lastGroupElement) {\n lastGroupElement.removeAttribute(GROUP_MESSAGE_HOVER_ATTRIBUTE);\n }\n}\n\nfunction getLastElementInDocumentGroup(element: Element) {\n let current: Element | null = element;\n\n do {\n current = current.nextElementSibling;\n } while (current && !current.classList.contains('last-in-document-group'));\n\n return current;\n}\n\nexport default memo(withGlobal<OwnProps>(\n (global, ownProps): StateProps => {\n const { focusedMessage, forwardMessages, lastSyncTime } = global;\n const {\n message, album, withSenderName, withAvatar, threadId, messageListType,\n } = ownProps;\n const {\n id, chatId, viaBotId, replyToMessageId, isOutgoing,\n } = message;\n\n const chat = selectChat(global, chatId);\n const isChatWithSelf = selectIsChatWithSelf(global, chatId);\n const isChannel = chat && isChatChannel(chat);\n\n const forceSenderName = !isChatWithSelf && isAnonymousOwnMessage(message);\n const canShowSender = withSenderName || withAvatar || forceSenderName;\n const sender = canShowSender ? selectSender(global, message) : undefined;\n const originSender = selectForwardedSender(global, message);\n const botSender = viaBotId ? selectUser(global, viaBotId) : undefined;\n\n const threadTopMessageId = threadId ? selectThreadTopMessageId(global, chatId, threadId) : undefined;\n const isThreadTop = message.id === threadTopMessageId;\n\n const shouldHideReply = replyToMessageId === threadTopMessageId;\n const replyMessage = replyToMessageId && !shouldHideReply\n ? selectChatMessage(global, chatId, replyToMessageId)\n : undefined;\n const replyMessageSender = replyMessage && selectSender(global, replyMessage);\n\n const uploadProgress = selectUploadProgress(global, message);\n const isFocused = messageListType === 'thread' && (\n album\n ? album.messages.some((m) => selectIsMessageFocused(global, m))\n : selectIsMessageFocused(global, message)\n );\n\n const { direction: focusDirection, noHighlight: noFocusHighlight } = (isFocused && focusedMessage) || {};\n\n const isForwarding = forwardMessages.messageIds && forwardMessages.messageIds.includes(id);\n\n const { query: highlight } = selectCurrentTextSearch(global) || {};\n\n const singleEmoji = getMessageSingleEmoji(message);\n let isSelected: boolean;\n\n if (album && album.messages) {\n isSelected = album.messages.every(({ id: messageId }) => selectIsMessageSelected(global, messageId));\n } else {\n isSelected = selectIsMessageSelected(global, id);\n }\n\n return {\n forceSenderName,\n sender,\n originSender,\n botSender,\n shouldHideReply,\n isThreadTop,\n replyMessage,\n replyMessageSender,\n ...(isOutgoing && { outgoingStatus: selectOutgoingStatus(global, message, messageListType === 'scheduled') }),\n ...(typeof uploadProgress === 'number' && { uploadProgress }),\n isFocused,\n ...(isFocused && { focusDirection, noFocusHighlight }),\n isForwarding,\n isChatWithSelf,\n isChannel,\n lastSyncTime,\n highlight,\n isSingleEmoji: Boolean(singleEmoji),\n animatedEmoji: singleEmoji ? selectAnimatedEmoji(global, singleEmoji) : undefined,\n isInSelectMode: selectIsInSelectMode(global),\n isSelected,\n isGroupSelected: (\n !!message.groupedId && !message.isInAlbum && selectIsDocumentGroupSelected(global, chatId, message.groupedId)\n ),\n threadId,\n isPinnedList: messageListType === 'pinned',\n shouldAutoLoadMedia: chat ? selectShouldAutoLoadMedia(global, message, chat, sender) : undefined,\n shouldAutoPlayMedia: selectShouldAutoPlayMedia(global, message),\n shouldLoopStickers: selectShouldLoopStickers(global),\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'focusMessage',\n 'openMediaViewer',\n 'openAudioPlayer',\n 'cancelSendingMessage',\n 'openUserInfo',\n 'openChat',\n 'markMessagesRead',\n 'sendPollVote',\n 'toggleMessageSelection',\n 'setReplyingToId',\n 'openForwardMenu',\n 'clickInlineButton',\n ]),\n)(Message));\n","import React, {\n FC, memo, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState,\n} from '../../lib/teact/teact';\nimport { getGlobal, withGlobal } from '../../lib/teact/teactn';\n\nimport { ApiMessage, ApiRestrictionReason, MAIN_THREAD_ID } from '../../api/types';\nimport { GlobalActions, MessageListType } from '../../global/types';\nimport { LoadMoreDirection } from '../../types';\n\nimport { ANIMATION_END_DELAY, MESSAGE_LIST_SLICE, SCHEDULED_WHEN_ONLINE } from '../../config';\nimport { IS_ANDROID, IS_IOS, IS_MOBILE_SCREEN } from '../../util/environment';\nimport {\n selectChatMessages,\n selectIsViewportNewest,\n selectFirstUnreadId,\n selectFocusedMessageId,\n selectChat,\n selectIsInSelectMode,\n selectIsChatWithSelf,\n selectChatBot,\n selectIsChatBotNotStarted,\n selectScrollOffset,\n selectThreadTopMessageId,\n selectFirstMessageId,\n selectScheduledMessages, selectCurrentMessageIds,\n} from '../../modules/selectors';\nimport {\n getMessageOriginalId,\n isActionMessage,\n isChatChannel,\n isChatPrivate,\n isOwnMessage,\n getCanPostInChat,\n} from '../../modules/helpers';\nimport {\n compact,\n flatten,\n orderBy,\n pick,\n} from '../../util/iteratees';\nimport {\n fastRaf, debounce, throttleWithTickEnd, onTickEnd,\n} from '../../util/schedulers';\nimport { formatHumanDate } from '../../util/dateFormat';\nimport useLayoutEffectWithPrevDeps from '../../hooks/useLayoutEffectWithPrevDeps';\nimport buildClassName from '../../util/buildClassName';\nimport { groupMessages, MessageDateGroup, isAlbum } from './helpers/groupMessages';\nimport { ObserveFn, useIntersectionObserver } from '../../hooks/useIntersectionObserver';\nimport useOnChange from '../../hooks/useOnChange';\nimport useStickyDates from './hooks/useStickyDates';\nimport { dispatchHeavyAnimationEvent } from '../../hooks/useHeavyAnimationCheck';\nimport resetScroll from '../../util/resetScroll';\nimport fastSmoothScroll from '../../util/fastSmoothScroll';\nimport renderText from '../common/helpers/renderText';\nimport useLang, { LangFn } from '../../hooks/useLang';\n\nimport Loading from '../ui/Loading';\nimport MessageScroll from './MessageScroll';\nimport Message from './message/Message';\nimport ActionMessage from './ActionMessage';\n\nimport './MessageList.scss';\n\ntype OwnProps = {\n chatId: number;\n threadId: number;\n type: MessageListType;\n onFabToggle: (show: boolean) => void;\n hasTools?: boolean;\n bottomOffset: 'none' | 'small' | 'big';\n};\n\ntype StateProps = {\n isChatLoaded?: boolean;\n isChannelChat?: boolean;\n canPost?: boolean;\n isChatWithSelf?: boolean;\n messageIds?: number[];\n messagesById?: Record<number, ApiMessage>;\n firstUnreadId?: number;\n isViewportNewest?: boolean;\n isRestricted?: boolean;\n restrictionReason?: ApiRestrictionReason;\n focusingId?: number;\n isSelectModeActive?: boolean;\n animationLevel?: number;\n lastMessage?: ApiMessage;\n botDescription?: string;\n threadTopMessageId?: number;\n threadFirstMessageId?: number;\n hasLinkedChat?: boolean;\n};\n\ntype DispatchProps = Pick<GlobalActions, (\n 'loadViewportMessages' | 'markMessageListRead' | 'markMessagesRead' | 'setScrollOffset'\n)>;\n\nconst BOTTOM_THRESHOLD = 100;\nconst UNREAD_DIVIDER_TOP = 10;\nconst UNREAD_DIVIDER_TOP_WITH_TOOLS = 60;\nconst SCROLL_DEBOUNCE = 200;\nconst INTERSECTION_THROTTLE_FOR_MEDIA = IS_ANDROID ? 1000 : 350;\nconst INTERSECTION_MARGIN_FOR_MEDIA = IS_MOBILE_SCREEN ? 300 : 500;\nconst FOCUSING_DURATION = 1000;\nconst BOTTOM_FOCUS_MARGIN = 20;\nconst SELECT_MODE_ANIMATION_DURATION = 200;\nconst FOCUSING_FADE_ANIMATION_DURATION = 200;\nconst UNREAD_DIVIDER_CLASS = 'unread-divider';\n\nconst runDebouncedForScroll = debounce((cb) => cb(), SCROLL_DEBOUNCE, false);\nconst runThrottledOnTickEnd = throttleWithTickEnd((cb) => cb());\n\nconst MessageList: FC<OwnProps & StateProps & DispatchProps> = ({\n chatId,\n threadId,\n type,\n hasTools,\n onFabToggle,\n isChatLoaded,\n isChannelChat,\n canPost,\n bottomOffset,\n isChatWithSelf,\n messageIds,\n messagesById,\n firstUnreadId,\n isViewportNewest,\n threadFirstMessageId,\n isRestricted,\n restrictionReason,\n focusingId,\n isSelectModeActive,\n animationLevel,\n loadViewportMessages,\n markMessageListRead,\n markMessagesRead,\n setScrollOffset,\n lastMessage,\n botDescription,\n threadTopMessageId,\n hasLinkedChat,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const containerRef = useRef<HTMLDivElement>(null);\n\n // We update local cached `scrollOffsetRef` when opening chat.\n // Then we update global version every second on scrolling.\n const scrollOffsetRef = useRef<number>((type === 'thread' && selectScrollOffset(getGlobal(), chatId, threadId)) || 0);\n const anchorIdRef = useRef<string>();\n const anchorTopRef = useRef<number>();\n const listItemElementsRef = useRef<HTMLDivElement[]>();\n // Updated when opening chat (to preserve divider even after messages are read)\n const memoUnreadDividerBeforeIdRef = useRef<number | undefined>(firstUnreadId);\n // Updated every time (to be used from intersection callback closure)\n const memoFirstUnreadIdRef = useRef<number>();\n const memoFocusingIdRef = useRef<number>();\n const isScrollTopJustUpdatedRef = useRef(false);\n const shouldAnimateAppearanceRef = useRef(!messageIds);\n\n const [containerHeight, setContainerHeight] = useState<number | undefined>();\n const [hasFocusing, setHasFocusing] = useState<boolean>(Boolean(focusingId));\n\n const areMessagesLoaded = Boolean(messageIds);\n useOnChange(() => {\n // We only need it first time when message list appears\n if (areMessagesLoaded) {\n onTickEnd(() => {\n shouldAnimateAppearanceRef.current = false;\n });\n }\n }, [areMessagesLoaded]);\n\n useOnChange(() => {\n memoFirstUnreadIdRef.current = firstUnreadId;\n }, [firstUnreadId]);\n\n const {\n observe: observeIntersectionForMedia, freeze: freezeForMedia, unfreeze: unfreezeForMedia,\n } = useIntersectionObserver({\n rootRef: containerRef,\n throttleMs: INTERSECTION_THROTTLE_FOR_MEDIA,\n margin: INTERSECTION_MARGIN_FOR_MEDIA,\n });\n\n const {\n observe: observeIntersectionForReading, freeze: freezeForReading, unfreeze: unfreezeForReading,\n } = useIntersectionObserver({\n rootRef: containerRef,\n }, (entries) => {\n if (type !== 'thread') {\n return;\n }\n\n let maxId = 0;\n const mentionIds: number[] = [];\n\n entries.forEach((entry) => {\n const { isIntersecting, target } = entry;\n\n if (!isIntersecting) {\n return;\n }\n\n const { dataset } = target as HTMLDivElement;\n\n const messageId = Number(dataset.lastMessageId || dataset.messageId);\n if (messageId > maxId) {\n maxId = messageId;\n }\n\n if (dataset.hasUnreadMention) {\n mentionIds.push(messageId);\n }\n });\n\n if (memoFirstUnreadIdRef.current && maxId >= memoFirstUnreadIdRef.current) {\n markMessageListRead({ maxId });\n }\n\n if (mentionIds.length) {\n markMessagesRead({ messageIds: mentionIds });\n }\n });\n\n useOnChange(() => {\n memoFocusingIdRef.current = focusingId;\n\n if (focusingId) {\n freezeForMedia();\n freezeForReading();\n } else {\n unfreezeForReading();\n unfreezeForMedia();\n }\n }, [focusingId]);\n\n const { observe: observeIntersectionForAnimatedStickers } = useIntersectionObserver({\n rootRef: containerRef,\n throttleMs: INTERSECTION_THROTTLE_FOR_MEDIA,\n });\n\n useEffect(() => {\n if (focusingId) {\n setHasFocusing(true);\n } else {\n setTimeout(() => {\n setHasFocusing(false);\n }, FOCUSING_FADE_ANIMATION_DURATION);\n }\n }, [focusingId]);\n\n const messageGroups = useMemo(() => {\n if (!messageIds || !messagesById) {\n return undefined;\n }\n\n const viewportIds = threadTopMessageId && (!messageIds[0] || threadFirstMessageId === messageIds[0])\n ? [threadTopMessageId, ...messageIds]\n : messageIds;\n\n if (!viewportIds.length) {\n return undefined;\n }\n\n const listedMessages = viewportIds.map((id) => messagesById[id]);\n return groupMessages(orderBy(listedMessages, ['date', 'id']), memoUnreadDividerBeforeIdRef.current);\n }, [messageIds, messagesById, threadFirstMessageId, threadTopMessageId]);\n\n const [loadMoreBackwards, loadMoreForwards, loadMoreAround] = useMemo(\n () => (type === 'thread' ? [\n debounce(() => loadViewportMessages({ direction: LoadMoreDirection.Backwards }), 1000, true, false),\n debounce(() => loadViewportMessages({ direction: LoadMoreDirection.Forwards }), 1000, true, false),\n debounce(() => loadViewportMessages({ direction: LoadMoreDirection.Around }), 1000, true, false),\n ] : []),\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [loadViewportMessages, messageIds],\n );\n\n const { isScrolled, updateStickyDates } = useStickyDates();\n\n const handleScroll = useCallback(() => {\n if (isScrollTopJustUpdatedRef.current) {\n isScrollTopJustUpdatedRef.current = false;\n return;\n }\n\n const container = containerRef.current!;\n\n if (!memoFocusingIdRef.current) {\n updateStickyDates(container, hasTools);\n }\n\n runDebouncedForScroll(() => {\n fastRaf(() => {\n if (!container.parentElement) {\n return;\n }\n\n scrollOffsetRef.current = container.scrollHeight - container.scrollTop;\n\n if (type === 'thread') {\n setScrollOffset({ chatId, threadId, scrollOffset: scrollOffsetRef.current });\n }\n });\n });\n }, [updateStickyDates, hasTools, type, setScrollOffset, chatId, threadId]);\n\n // Container resize observer (caused by Composer reply/webpage panels)\n useEffect(() => {\n if (!('ResizeObserver' in window) || process.env.APP_ENV === 'perf') {\n return undefined;\n }\n\n const observer = new ResizeObserver(([entry]) => {\n // During animation\n if (!(entry.target as HTMLDivElement).offsetParent) {\n return;\n }\n\n setContainerHeight(entry.contentRect.height);\n });\n\n observer.observe(containerRef.current!);\n\n return () => {\n observer.disconnect();\n };\n }, []);\n\n // Workaround for an iOS bug when animated stickers sometimes disappear\n useLayoutEffect(() => {\n if (!IS_IOS) {\n return;\n }\n\n runThrottledOnTickEnd(() => {\n if (!(containerRef.current as HTMLDivElement).querySelector('.AnimatedSticker.is-playing')) {\n return;\n }\n\n const style = (containerRef.current as HTMLDivElement).style as any;\n style.webkitOverflowScrolling = style.webkitOverflowScrolling === 'auto' ? '' : 'auto';\n });\n });\n\n // Initial message loading\n useEffect(() => {\n if (!loadMoreAround || !isChatLoaded || isRestricted || focusingId) {\n return;\n }\n\n const container = containerRef.current!;\n\n if (!messageIds || (\n messageIds.length < MESSAGE_LIST_SLICE / 2\n && (container.firstElementChild as HTMLDivElement).clientHeight <= container.offsetHeight\n )) {\n loadMoreAround();\n }\n }, [isChatLoaded, messageIds, loadMoreAround, focusingId, isRestricted]);\n\n // Handles updated message list, takes care of scroll repositioning\n useLayoutEffectWithPrevDeps(([\n prevMessageIds, prevIsViewportNewest, prevContainerHeight,\n ]: [\n typeof messageIds, typeof isViewportNewest, typeof containerHeight\n ]) => {\n const container = containerRef.current!;\n listItemElementsRef.current = Array.from(container.querySelectorAll<HTMLDivElement>('.message-list-item'));\n\n // During animation\n if (!container.offsetParent) {\n return;\n }\n\n // Add extra height when few messages to allow smooth scroll animation. Uses assumption that `parentElement`\n // is a Transition slide and its CSS class can not be reset in a declarative way.\n const shouldForceScroll = (\n isViewportNewest\n && (messageIds && messageIds.length < MESSAGE_LIST_SLICE / 2)\n && !container.parentElement!.classList.contains('force-messages-scroll')\n && (container.firstElementChild as HTMLDivElement)!.clientHeight <= container.offsetHeight * 2\n );\n\n if (shouldForceScroll) {\n container.parentElement!.classList.add('force-messages-scroll');\n\n setTimeout(() => {\n if (container.parentElement) {\n container.parentElement.classList.remove('force-messages-scroll');\n }\n }, FOCUSING_DURATION);\n }\n\n const { scrollTop, scrollHeight, offsetHeight } = container;\n const scrollOffset = scrollOffsetRef.current!;\n const lastItemElement = listItemElementsRef.current[listItemElementsRef.current.length - 1];\n\n // If two messages come at once (e.g. via Quiz Bot) then the first message will update `scrollOffset`\n // right away (before animation) which creates inconsistency until the animation completes.\n // To workaround that, we calculate `isAtBottom` with a \"buffer\" of the latest message height (this is approximate).\n const lastItemHeight = lastItemElement ? lastItemElement.offsetHeight : 0;\n const isAtBottom = isViewportNewest && prevIsViewportNewest && (\n scrollOffset - (prevContainerHeight || offsetHeight) - lastItemHeight <= BOTTOM_THRESHOLD\n );\n\n let newScrollTop!: number;\n\n const hasFirstMessageChanged = messageIds && prevMessageIds && messageIds[0] !== prevMessageIds[0];\n const hasLastMessageChanged = (\n messageIds && prevMessageIds && messageIds[messageIds.length - 1] !== prevMessageIds[prevMessageIds.length - 1]\n );\n if (isAtBottom && hasLastMessageChanged && !hasFirstMessageChanged) {\n if (lastItemElement) {\n fastRaf(() => {\n fastSmoothScroll(container, lastItemElement, 'end', BOTTOM_FOCUS_MARGIN);\n });\n }\n\n newScrollTop = scrollHeight - offsetHeight;\n scrollOffsetRef.current = Math.max(scrollHeight - newScrollTop, offsetHeight);\n\n // Scroll still needs to be restored after container resize\n if (!shouldForceScroll) {\n return;\n }\n }\n\n if (process.env.APP_ENV === 'perf') {\n // eslint-disable-next-line no-console\n console.time('scrollTop');\n }\n\n const isResized = prevContainerHeight !== undefined && prevContainerHeight !== containerHeight;\n const anchor = anchorIdRef.current && container.querySelector(`#${anchorIdRef.current}`);\n const unreadDivider = (\n !anchor\n && memoUnreadDividerBeforeIdRef.current\n && container.querySelector<HTMLDivElement>(`.${UNREAD_DIVIDER_CLASS}`)\n );\n\n if (isAtBottom && isResized) {\n newScrollTop = scrollHeight - offsetHeight;\n } else if (anchor) {\n const newAnchorTop = anchor.getBoundingClientRect().top;\n newScrollTop = scrollTop + (newAnchorTop - (anchorTopRef.current || 0));\n } else if (unreadDivider) {\n newScrollTop = unreadDivider.offsetTop - (hasTools ? UNREAD_DIVIDER_TOP_WITH_TOOLS : UNREAD_DIVIDER_TOP);\n } else {\n newScrollTop = scrollHeight - scrollOffset;\n }\n\n resetScroll(container, newScrollTop);\n\n if (!memoFocusingIdRef.current) {\n isScrollTopJustUpdatedRef.current = true;\n fastRaf(() => {\n isScrollTopJustUpdatedRef.current = false;\n });\n }\n\n scrollOffsetRef.current = Math.max(scrollHeight - newScrollTop, offsetHeight);\n\n if (process.env.APP_ENV === 'perf') {\n // eslint-disable-next-line no-console\n console.timeEnd('scrollTop');\n }\n }, [messageIds, isViewportNewest, containerHeight, hasTools]);\n\n useEffect(() => {\n if (!animationLevel || animationLevel > 0) {\n dispatchHeavyAnimationEvent(SELECT_MODE_ANIMATION_DURATION + ANIMATION_END_DELAY);\n }\n }, [animationLevel, isSelectModeActive]);\n\n const lang = useLang();\n\n const isPrivate = Boolean(chatId && isChatPrivate(chatId));\n const withUsers = Boolean((!isPrivate && !isChannelChat) || isChatWithSelf);\n\n const className = buildClassName(\n 'MessageList custom-scroll',\n !withUsers && 'no-avatars',\n isChannelChat && 'no-avatars',\n (!canPost || bottomOffset !== 'none') && 'bottom-padding',\n (bottomOffset !== 'none') && `bottom-padding-${bottomOffset}`,\n isSelectModeActive && 'select-mode-active',\n hasFocusing && 'has-focusing',\n isScrolled && 'scrolled',\n );\n\n return (\n <div ref={containerRef} className={className} onScroll={handleScroll}>\n {isRestricted ? (\n <div className=\"empty\">\n <span>\n {restrictionReason ? restrictionReason.text : `This is a private ${isChannelChat ? 'channel' : 'chat'}`}\n </span>\n </div>\n ) : botDescription ? (\n <div className=\"empty rich\"><span>{renderText(lang(botDescription), ['br', 'emoji', 'links'])}</span></div>\n ) : messageIds && !messageGroups ? (\n <div className=\"empty\"><span>{lang('NoMessages')}</span></div>\n ) : ((messageIds && messageGroups) || lastMessage) ? (\n <MessageScroll\n containerRef={containerRef}\n className=\"messages-container\"\n messageIds={messageIds || [lastMessage!.id]}\n containerHeight={containerHeight}\n listItemElementsRef={listItemElementsRef}\n focusingId={focusingId}\n anchorIdRef={anchorIdRef}\n anchorTopRef={anchorTopRef}\n loadMoreForwards={loadMoreForwards}\n loadMoreBackwards={loadMoreBackwards}\n isViewportNewest={isViewportNewest}\n firstUnreadId={firstUnreadId}\n onFabToggle={onFabToggle}\n >\n {renderMessages(\n lang,\n messageGroups || groupMessages([lastMessage!]),\n observeIntersectionForReading,\n observeIntersectionForMedia,\n observeIntersectionForAnimatedStickers,\n withUsers,\n anchorIdRef,\n memoUnreadDividerBeforeIdRef,\n threadId,\n type,\n threadTopMessageId,\n threadFirstMessageId,\n hasLinkedChat,\n messageGroups ? type === 'scheduled' : false,\n !messageGroups || !shouldAnimateAppearanceRef.current,\n )}\n </MessageScroll>\n ) : (\n <Loading color=\"white\" />\n )}\n </div>\n );\n};\n\nfunction renderMessages(\n lang: LangFn,\n messageGroups: MessageDateGroup[],\n observeIntersectionForReading: ObserveFn,\n observeIntersectionForMedia: ObserveFn,\n observeIntersectionForAnimatedStickers: ObserveFn,\n withUsers: boolean,\n currentAnchorIdRef: { current: string | undefined },\n memoFirstUnreadIdRef: { current: number | undefined },\n threadId: number,\n type: MessageListType,\n threadTopMessageId?: number,\n threadFirstMessageId?: number,\n hasLinkedChat?: boolean,\n isSchedule = false,\n noAppearanceAnimation = false,\n) {\n const unreadDivider = (\n <div className={buildClassName(UNREAD_DIVIDER_CLASS, 'local-action-message')} key=\"unread-messages\">\n <span>{lang('UnreadMessages')}</span>\n </div>\n );\n\n const messageCountToAnimate = noAppearanceAnimation ? 0 : messageGroups.reduce((acc, messageGroup) => {\n return acc + flatten(messageGroup.senderGroups).length;\n }, 0);\n let appearanceIndex = 0;\n\n const dateGroups = messageGroups.map((\n dateGroup: MessageDateGroup,\n dateGroupIndex: number,\n dateGroupsArray: MessageDateGroup[],\n ) => {\n const senderGroups = dateGroup.senderGroups.map((\n senderGroup,\n senderGroupIndex,\n senderGroupsArray,\n ) => {\n if (senderGroup.length === 1 && !isAlbum(senderGroup[0]) && isActionMessage(senderGroup[0])) {\n const message = senderGroup[0];\n\n return compact([\n message.id === memoFirstUnreadIdRef.current && unreadDivider,\n <ActionMessage\n key={message.id}\n message={message}\n observeIntersection={observeIntersectionForReading}\n appearanceOrder={messageCountToAnimate - ++appearanceIndex}\n />,\n ]);\n }\n\n let currentDocumentGroupId: string | undefined;\n\n return flatten(senderGroup.map((\n messageOrAlbum,\n messageIndex,\n ) => {\n const message = isAlbum(messageOrAlbum) ? messageOrAlbum.mainMessage : messageOrAlbum;\n const album = isAlbum(messageOrAlbum) ? messageOrAlbum : undefined;\n const isOwn = isOwnMessage(message);\n const isMessageAlbum = isAlbum(messageOrAlbum);\n const nextMessage = senderGroup[messageIndex + 1];\n\n if (message.previousLocalId && currentAnchorIdRef.current === `message${message.previousLocalId}`) {\n currentAnchorIdRef.current = `message${message.id}`;\n }\n\n const documentGroupId = !isMessageAlbum && message.groupedId ? message.groupedId : undefined;\n const nextDocumentGroupId = nextMessage && !isAlbum(nextMessage) ? nextMessage.groupedId : undefined;\n\n const position = {\n isFirstInGroup: messageIndex === 0,\n isLastInGroup: messageIndex === senderGroup.length - 1,\n isFirstInDocumentGroup: Boolean(documentGroupId && documentGroupId !== currentDocumentGroupId),\n isLastInDocumentGroup: Boolean(documentGroupId && documentGroupId !== nextDocumentGroupId),\n isLastInList: (\n messageIndex === senderGroup.length - 1\n && senderGroupIndex === senderGroupsArray.length - 1\n && dateGroupIndex === dateGroupsArray.length - 1\n ),\n };\n\n currentDocumentGroupId = documentGroupId;\n\n const shouldRenderUnreadDivider = (\n (message.id === memoFirstUnreadIdRef.current && memoFirstUnreadIdRef.current !== threadFirstMessageId)\n || (message.id === threadTopMessageId && memoFirstUnreadIdRef.current === threadFirstMessageId)\n );\n const originalId = getMessageOriginalId(message);\n // Scheduled messages can have local IDs in the middle of the list,\n // and keys should be ordered, so we prefix it with a date.\n // However, this may lead to issues if server date is not synchronized with the local one.\n const key = type !== 'scheduled' ? originalId : `${message.date}_${originalId}`;\n\n return compact([\n shouldRenderUnreadDivider && unreadDivider,\n <Message\n key={key}\n message={message}\n observeIntersectionForBottom={observeIntersectionForReading}\n observeIntersectionForMedia={observeIntersectionForMedia}\n observeIntersectionForAnimatedStickers={observeIntersectionForAnimatedStickers}\n album={album}\n withAvatar={position.isLastInGroup && withUsers && !isOwn && !(message.id === threadTopMessageId)}\n withSenderName={position.isFirstInGroup && withUsers && !isOwn}\n threadId={threadId}\n messageListType={type}\n noComments={hasLinkedChat === false}\n appearanceOrder={messageCountToAnimate - ++appearanceIndex}\n isFirstInGroup={position.isFirstInGroup}\n isLastInGroup={position.isLastInGroup}\n isFirstInDocumentGroup={position.isFirstInDocumentGroup}\n isLastInDocumentGroup={position.isLastInDocumentGroup}\n isLastInList={position.isLastInList}\n />,\n message.id === threadTopMessageId && (\n <div className=\"local-action-message\" key=\"discussion-started\">\n <span>{lang('DiscussionStarted')}</span>\n </div>\n ),\n ]);\n }));\n });\n\n return (\n <div\n className=\"message-date-group\"\n key={dateGroup.datetime}\n teactFastList\n >\n <div className=\"sticky-date\" key=\"date-header\">\n <span>\n {isSchedule && dateGroup.originalDate === SCHEDULED_WHEN_ONLINE && (\n lang('MessageScheduledUntilOnline')\n )}\n {isSchedule && dateGroup.originalDate !== SCHEDULED_WHEN_ONLINE && (\n lang('MessageScheduledOn', formatHumanDate(dateGroup.datetime, undefined, true))\n )}\n {!isSchedule && formatHumanDate(dateGroup.datetime)}\n </span>\n </div>\n {flatten(senderGroups)}\n </div>\n );\n });\n\n return flatten(dateGroups);\n}\n\nexport default memo(withGlobal<OwnProps>(\n (global, { chatId, threadId, type }): StateProps => {\n const chat = selectChat(global, chatId);\n if (!chat) {\n return {};\n }\n\n const messageIds = selectCurrentMessageIds(global, chatId, threadId, type);\n const messagesById = type === 'scheduled'\n ? selectScheduledMessages(global, chatId)\n : selectChatMessages(global, chatId);\n const threadTopMessageId = selectThreadTopMessageId(global, chatId, threadId);\n\n if (\n threadId !== MAIN_THREAD_ID\n && !(messagesById && threadTopMessageId && messagesById[threadTopMessageId])\n ) {\n return {};\n }\n\n const { isRestricted, restrictionReason, lastMessage } = chat;\n const focusingId = selectFocusedMessageId(global, chatId);\n\n const withLastMessageWhenPreloading = (\n threadId === MAIN_THREAD_ID\n && !messageIds && !chat.unreadCount && !focusingId && lastMessage && !lastMessage.groupedId\n );\n\n let botDescription: string | undefined;\n if (selectIsChatBotNotStarted(global, chatId)) {\n const chatBot = selectChatBot(global, chatId)!;\n if (chatBot.fullInfo) {\n botDescription = chatBot.fullInfo.botDescription || 'NoMessages';\n } else {\n botDescription = 'Updating bot info...';\n }\n }\n\n return {\n isChatLoaded: true,\n isRestricted,\n restrictionReason,\n isChannelChat: isChatChannel(chat),\n canPost: getCanPostInChat(chat, threadId),\n isChatWithSelf: selectIsChatWithSelf(global, chatId),\n messageIds,\n messagesById,\n firstUnreadId: selectFirstUnreadId(global, chatId, threadId),\n isViewportNewest: type !== 'thread' || selectIsViewportNewest(global, chatId, threadId),\n threadFirstMessageId: selectFirstMessageId(global, chatId, threadId),\n focusingId,\n isSelectModeActive: selectIsInSelectMode(global),\n animationLevel: global.settings.byKey.animationLevel,\n ...(withLastMessageWhenPreloading && { lastMessage }),\n botDescription,\n threadTopMessageId,\n hasLinkedChat: chat.fullInfo && ('linkedChatId' in chat.fullInfo)\n ? Boolean(chat.fullInfo.linkedChatId)\n : undefined,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'loadViewportMessages',\n 'markMessageListRead',\n 'markMessagesRead',\n 'setScrollOffset',\n ]),\n)(MessageList));\n","import React, {\n FC, useCallback, memo, useRef,\n} from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { GlobalActions, MessageListType } from '../../global/types';\nimport { MAIN_THREAD_ID } from '../../api/types';\n\nimport { selectChat, selectCurrentMessageList } from '../../modules/selectors';\nimport { getCanPostInChat } from '../../modules/helpers';\nimport { formatIntegerCompact } from '../../util/textFormat';\nimport buildClassName from '../../util/buildClassName';\nimport { pick } from '../../util/iteratees';\nimport fastSmoothScroll from '../../util/fastSmoothScroll';\n\nimport Button from '../ui/Button';\n\nimport './ScrollDownButton.scss';\n\ntype OwnProps = {\n isShown: boolean;\n};\n\ntype StateProps = {\n messageListType?: MessageListType;\n canPost?: boolean;\n unreadCount?: number;\n};\n\ntype DispatchProps = Pick<GlobalActions, 'focusLastMessage'>;\n\nconst FOCUS_MARGIN = 20;\n\nconst ScrollDownButton: FC<OwnProps & StateProps & DispatchProps> = ({\n isShown,\n messageListType,\n canPost,\n unreadCount,\n focusLastMessage,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const elementRef = useRef<HTMLDivElement>(null);\n\n const handleClick = useCallback(() => {\n if (!isShown) {\n return;\n }\n\n if (messageListType === 'thread') {\n focusLastMessage();\n } else {\n const messagesContainer = elementRef.current!.parentElement!.querySelector<HTMLDivElement>('.MessageList')!;\n const messsageElements = messagesContainer.querySelectorAll<HTMLDivElement>('.message-list-item');\n const lastMessageElement = messsageElements[messsageElements.length - 1];\n if (!lastMessageElement) {\n return;\n }\n\n fastSmoothScroll(messagesContainer, lastMessageElement, 'end', FOCUS_MARGIN);\n }\n }, [isShown, messageListType, focusLastMessage]);\n\n const fabClassName = buildClassName(\n 'ScrollDownButton',\n isShown && 'revealed',\n !canPost && 'no-composer',\n );\n\n return (\n <div ref={elementRef} className={fabClassName}>\n <div className=\"ScrollDownButton-inner\">\n <Button\n color=\"secondary\"\n round\n onClick={handleClick}\n ariaLabel=\"Scroll to bottom\"\n >\n <i className=\"icon-arrow-down\" />\n </Button>\n {Boolean(unreadCount) && (\n <div className=\"unread-count\">{formatIntegerCompact(unreadCount!)}</div>\n )}\n </div>\n </div>\n );\n};\n\nexport default memo(withGlobal<OwnProps>(\n (global): StateProps => {\n const currentMessageList = selectCurrentMessageList(global);\n if (!currentMessageList) {\n return {};\n }\n\n const { chatId, threadId, type: messageListType } = currentMessageList;\n const chat = selectChat(global, chatId);\n const canPost = chat && getCanPostInChat(chat, threadId);\n\n return {\n messageListType,\n canPost,\n unreadCount: chat && threadId === MAIN_THREAD_ID && messageListType === 'thread' ? chat.unreadCount : undefined,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, ['focusLastMessage']),\n)(ScrollDownButton));\n","import { ApiAttachment } from '../../../../api/types';\nimport { preloadImage, preloadVideo, createPosterForVideo } from '../../../../util/files';\n\nconst MAX_QUICK_VIDEO_SIZE = 10 * 1024 ** 2; // 10 MB\nconst MAX_QUICK_IMG_SIZE = 1280; // px\n\nexport default async function buildAttachment(\n filename: string, blob: Blob, isQuick: boolean, options?: Partial<ApiAttachment>,\n): Promise<ApiAttachment> {\n const blobUrl = URL.createObjectURL(blob);\n const { type: mimeType, size } = blob;\n let quick;\n let previewBlobUrl;\n\n if (mimeType.startsWith('image/')) {\n if (isQuick) {\n const img = await preloadImage(blobUrl);\n const { width, height } = img;\n\n if (width > MAX_QUICK_IMG_SIZE || height > MAX_QUICK_IMG_SIZE || mimeType !== 'image/jpeg') {\n const newBlob = await squeezeImage(img);\n if (newBlob) {\n URL.revokeObjectURL(blobUrl);\n return buildAttachment(filename, newBlob, true, options);\n } else {\n return buildAttachment(filename, blob, false, options);\n }\n }\n\n quick = { width, height };\n } else {\n previewBlobUrl = blobUrl;\n }\n } else if (mimeType.startsWith('video/')) {\n // Videos < 10 MB are always sent in quick mode (in other clients).\n // Quick mode for videos > 10 MB is not supported until client-side video squeezing is implemented.\n if (size < MAX_QUICK_VIDEO_SIZE) {\n const { videoWidth: width, videoHeight: height, duration } = await preloadVideo(blobUrl);\n quick = { width, height, duration };\n }\n\n previewBlobUrl = await createPosterForVideo(blobUrl);\n }\n\n return {\n blobUrl,\n filename,\n mimeType,\n size,\n quick,\n previewBlobUrl,\n ...options,\n };\n}\n\nfunction squeezeImage(img: HTMLImageElement): Promise<Blob | null> {\n return new Promise((resolve) => {\n const canvas = document.createElement('canvas');\n const ctx = canvas.getContext('2d')!;\n\n let { width, height } = img;\n\n if (width > MAX_QUICK_IMG_SIZE || height > MAX_QUICK_IMG_SIZE) {\n if (width >= height) {\n height *= MAX_QUICK_IMG_SIZE / width;\n width = MAX_QUICK_IMG_SIZE;\n } else {\n width *= MAX_QUICK_IMG_SIZE / height;\n height = MAX_QUICK_IMG_SIZE;\n }\n }\n\n canvas.width = width;\n canvas.height = height;\n\n ctx.drawImage(img, 0, 0, img.width, img.height, 0, 0, width, height);\n canvas.toBlob(resolve, 'image/jpeg', 100);\n });\n}\n","export default __webpack_public_path__ + \"8ccc0b555efcec3616377aea078dda16.js\";","// @ts-ignore\nimport encoderPath from 'file-loader!opus-recorder/dist/encoderWorker.min';\n\nexport type Result = { blob: Blob; duration: number; waveform: number[] };\n\ninterface OpusRecorder extends Omit<MediaRecorder, 'start' | 'ondataavailable'> {\n new(options: AnyLiteral): OpusRecorder;\n\n start(stream?: MediaStreamAudioSourceNode): void;\n\n sourceNode: MediaStreamAudioSourceNode;\n\n ondataavailable: (typedArray: Uint8Array) => void;\n}\n\nconst MIN_RECORDING_TIME = 1000;\nconst POLYFILL_OPTIONS = { encoderPath, reuseWorker: true };\nconst BLOB_PARAMS = { type: 'audio/ogg' };\nconst FFT_SIZE = 64;\nconst MIN_VOLUME = 0.1;\n\nlet opusRecorderPromise: Promise<{ default: OpusRecorder }>;\nlet OpusRecorder: OpusRecorder;\nlet mediaRecorder: OpusRecorder;\n\nexport async function init() {\n if (!opusRecorderPromise) {\n // @ts-ignore\n opusRecorderPromise = import('opus-recorder');\n OpusRecorder = (await opusRecorderPromise).default;\n mediaRecorder = new OpusRecorder(POLYFILL_OPTIONS);\n }\n\n return opusRecorderPromise;\n}\n\nexport async function start(analyzerCallback: Function) {\n await startMediaRecorder();\n\n const startedAt = Date.now();\n let pausedAt: number;\n const chunks: Uint8Array[] = [];\n const waveform: number[] = [];\n\n mediaRecorder.ondataavailable = (typedArray) => {\n chunks.push(typedArray);\n };\n\n const releaseAnalyzer = subscribeToAnalyzer(mediaRecorder, (volume: number) => {\n waveform.push(volume * 255);\n analyzerCallback(volume);\n });\n\n return {\n stop: () => new Promise<Result>((resolve, reject) => {\n mediaRecorder.onstop = () => {\n resolve({\n blob: new Blob(chunks, BLOB_PARAMS),\n duration: Math.round(((pausedAt || Date.now()) - startedAt) / 1000),\n waveform,\n });\n };\n mediaRecorder.onerror = reject;\n\n const delayStop = Math.max(0, startedAt + MIN_RECORDING_TIME - Date.now());\n setTimeout(() => {\n mediaRecorder.stop();\n releaseAnalyzer();\n }, delayStop);\n }),\n pause: () => {\n const delayStop = Math.max(0, startedAt + MIN_RECORDING_TIME - Date.now());\n setTimeout(() => {\n mediaRecorder.pause();\n pausedAt = Date.now();\n releaseAnalyzer();\n }, delayStop);\n },\n };\n}\n\nasync function startMediaRecorder() {\n await init();\n await mediaRecorder.start();\n}\n\nfunction subscribeToAnalyzer(recorder: OpusRecorder, cb: Function) {\n const source = recorder.sourceNode;\n const analyser = source.context.createAnalyser();\n analyser.fftSize = FFT_SIZE;\n source.connect(analyser);\n\n const dataLength = analyser.frequencyBinCount;\n const dataArray = new Uint8Array(dataLength);\n let isDestroyed = false;\n\n function tick() {\n if (isDestroyed) {\n return;\n }\n\n analyser.getByteFrequencyData(dataArray);\n\n const sum = dataArray.reduce((acc, current) => acc + current, 0);\n const mean = (sum / dataLength);\n const volume = mean / 255;\n\n cb(volume < MIN_VOLUME ? 0 : volume);\n\n requestAnimationFrame(tick);\n }\n\n tick();\n\n return () => {\n isDestroyed = true;\n };\n}\n","import { StateHookSetter, useEffect } from '../../../../lib/teact/teact';\nimport { ApiAttachment, ApiMessage } from '../../../../api/types';\n\nimport buildAttachment from '../helpers/buildAttachment';\nimport { EDITABLE_INPUT_ID, EDITABLE_INPUT_MODAL_ID } from '../../../../config';\n\nconst CLIPBOARD_ACCEPTED_TYPES = ['image/png', 'image/jpeg', 'image/gif'];\nconst MAX_MESSAGE_LENGTH = 4096;\n\nexport default (\n insertTextAndUpdateCursor: (text: string) => void,\n setAttachments: StateHookSetter<ApiAttachment[]>,\n editedMessage: ApiMessage | undefined,\n) => {\n useEffect(() => {\n async function handlePaste(e: ClipboardEvent) {\n if (!e.clipboardData) {\n return;\n }\n\n const input = document.activeElement;\n if (input && input.tagName === 'INPUT' && ![EDITABLE_INPUT_ID, EDITABLE_INPUT_MODAL_ID].includes(input.id)) {\n return;\n }\n\n const { items } = e.clipboardData;\n const media = Array.from(items).find((item) => CLIPBOARD_ACCEPTED_TYPES.includes(item.type));\n const file = media && media.getAsFile();\n const pastedText = e.clipboardData.getData('text').substring(0, MAX_MESSAGE_LENGTH);\n\n if (!file && !pastedText) {\n return;\n }\n\n e.preventDefault();\n\n if (file && !editedMessage) {\n const attachment = await buildAttachment(file.name, file, true);\n setAttachments((attachments) => [\n ...attachments,\n attachment,\n ]);\n }\n\n if (pastedText) {\n insertTextAndUpdateCursor(pastedText);\n }\n }\n\n document.addEventListener('paste', handlePaste, false);\n\n return () => {\n document.removeEventListener('paste', handlePaste, false);\n };\n }, [insertTextAndUpdateCursor, editedMessage, setAttachments]);\n};\n","import { ApiFormattedText } from '../../../../api/types';\nimport { renderTextWithEntities } from '../../../common/helpers/renderMessageText';\n\nexport default function getMessageTextAsHtml(formattedText?: ApiFormattedText) {\n const { text, entities } = formattedText || {};\n if (!text) {\n return '';\n }\n\n const result = renderTextWithEntities(\n text,\n entities,\n undefined,\n undefined,\n true,\n );\n\n if (Array.isArray(result)) {\n return result.join('');\n }\n\n return result;\n}\n","import { useCallback, useEffect, useMemo } from '../../../../lib/teact/teact';\n\nimport { ApiFormattedText, ApiMessage } from '../../../../api/types';\nimport { GlobalActions } from '../../../../global/types';\n\nimport { DRAFT_DEBOUNCE, EDITABLE_INPUT_ID } from '../../../../config';\nimport usePrevious from '../../../../hooks/usePrevious';\nimport { debounce } from '../../../../util/schedulers';\nimport focusEditableElement from '../../../../util/focusEditableElement';\nimport parseMessageInput from '../helpers/parseMessageInput';\nimport getMessageTextAsHtml from '../helpers/getMessageTextAsHtml';\n\n// Used to avoid running debounced callbacks when chat changes.\nlet currentChatId: number | undefined;\nlet currentThreadId: number | undefined;\n\nexport default (\n draft: ApiFormattedText | undefined,\n chatId: number,\n threadId: number,\n html: string,\n htmlRef: { current: string },\n setHtml: (html: string) => void,\n editedMessage: ApiMessage | undefined,\n saveDraft: GlobalActions['saveDraft'],\n clearDraft: GlobalActions['clearDraft'],\n) => {\n const updateDraft = useCallback((draftChatId: number, draftThreadId: number) => {\n if (htmlRef.current.length && !editedMessage) {\n saveDraft({ chatId: draftChatId, threadId: draftThreadId, draft: parseMessageInput(htmlRef.current!) });\n } else {\n clearDraft({ chatId: draftChatId, threadId: draftThreadId });\n }\n }, [clearDraft, editedMessage, htmlRef, saveDraft]);\n\n // eslint-disable-next-line react-hooks/exhaustive-deps\n const runDebouncedForSaveDraft = useMemo(() => debounce((cb) => cb(), DRAFT_DEBOUNCE, false), [chatId]);\n\n const prevChatId = usePrevious(chatId);\n const prevThreadId = usePrevious(threadId);\n\n // Save draft on chat change\n useEffect(() => {\n currentChatId = chatId;\n currentThreadId = threadId;\n\n return () => {\n currentChatId = undefined;\n currentThreadId = undefined;\n\n updateDraft(chatId, threadId);\n };\n }, [chatId, threadId, updateDraft]);\n\n // Restore draft on chat change\n useEffect(() => {\n if (chatId === prevChatId && threadId === prevThreadId) {\n return;\n }\n\n if (!draft) {\n return;\n }\n\n setHtml(getMessageTextAsHtml(draft));\n\n requestAnimationFrame(() => {\n const messageInput = document.getElementById(EDITABLE_INPUT_ID)!;\n focusEditableElement(messageInput, true);\n });\n }, [chatId, threadId, draft, setHtml, updateDraft, prevChatId, prevThreadId]);\n\n // Update draft when input changes\n const prevHtml = usePrevious(html);\n useEffect(() => {\n if (!chatId || !threadId || prevChatId !== chatId || prevThreadId !== threadId || prevHtml === html) {\n return;\n }\n\n if (html.length) {\n runDebouncedForSaveDraft(() => {\n if (currentChatId !== chatId || currentThreadId !== threadId) {\n return;\n }\n\n updateDraft(chatId, threadId);\n });\n } else {\n updateDraft(chatId, threadId);\n }\n }, [chatId, html, prevChatId, prevHtml, prevThreadId, runDebouncedForSaveDraft, threadId, updateDraft]);\n\n // Subscribe and handle `window.blur`\n useEffect(() => {\n function handleBlur() {\n if (chatId && threadId) {\n updateDraft(chatId, threadId);\n }\n }\n\n window.addEventListener('blur', handleBlur);\n\n return () => {\n window.removeEventListener('blur', handleBlur);\n };\n }, [chatId, threadId, updateDraft]);\n};\n","import React, { FC } from '../../lib/teact/teact';\nimport { OwnProps } from './DeleteMessageModal';\nimport { Bundles } from '../../util/moduleLoader';\n\nimport useModuleLoader from '../../hooks/useModuleLoader';\n\nconst DeleteMessageModalAsync: FC<OwnProps> = (props) => {\n const { isOpen } = props;\n const DeleteMessageModal = useModuleLoader(Bundles.Extra, 'DeleteMessageModal', !isOpen);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return DeleteMessageModal ? <DeleteMessageModal {...props} /> : undefined;\n};\n\nexport default DeleteMessageModalAsync;\n","import React, {\n FC, useRef, useCallback, memo,\n} from '../../lib/teact/teact';\n\nimport { IS_TOUCH_ENV } from '../../util/environment';\n\nimport Button, { OwnProps as ButtonProps } from './Button';\n\ntype OwnProps = {\n onActivate: NoneToVoidFunction;\n} & Omit<ButtonProps, (\n 'onClick' | 'onMouseDown' |\n 'onMouseEnter' | 'onMouseLeave' |\n 'onFocus'\n)>;\n\nconst BUTTON_ACTIVATE_DELAY = 200;\nlet openTimeout: number | undefined;\nlet isFirstTimeActivation = true;\n\nconst ResponsiveHoverButton: FC<OwnProps> = ({ onActivate, ...buttonProps }) => {\n const isMouseInside = useRef(false);\n\n const handleMouseEnter = useCallback(() => {\n isMouseInside.current = true;\n\n // This is used to counter additional delay caused by asynchronous module loading\n if (isFirstTimeActivation) {\n isFirstTimeActivation = false;\n onActivate();\n return;\n }\n\n if (openTimeout) {\n clearTimeout(openTimeout);\n openTimeout = undefined;\n }\n openTimeout = window.setTimeout(() => {\n if (isMouseInside.current) {\n onActivate();\n }\n }, BUTTON_ACTIVATE_DELAY);\n }, [onActivate]);\n\n const handleMouseLeave = useCallback(() => {\n isMouseInside.current = false;\n }, []);\n\n return (\n <Button\n // eslint-disable-next-line react/jsx-props-no-spreading\n {...buttonProps}\n onMouseEnter={!IS_TOUCH_ENV ? handleMouseEnter : undefined}\n onMouseLeave={!IS_TOUCH_ENV ? handleMouseLeave : undefined}\n onClick={IS_TOUCH_ENV ? onActivate : undefined}\n />\n );\n};\n\nexport default memo(ResponsiveHoverButton);\n","import React, { FC } from '../../../lib/teact/teact';\nimport { OwnProps } from './AttachMenu';\nimport { Bundles } from '../../../util/moduleLoader';\n\nimport useModuleLoader from '../../../hooks/useModuleLoader';\n\nconst AttachMenuAsync: FC<OwnProps> = (props) => {\n const { isOpen } = props;\n const AttachMenu = useModuleLoader(Bundles.Extra, 'AttachMenu', !isOpen);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return AttachMenu ? <AttachMenu {...props} /> : undefined;\n};\n\nexport default AttachMenuAsync;\n","import React, { FC } from '../../../lib/teact/teact';\nimport { OwnProps } from './SymbolMenu';\nimport { Bundles } from '../../../util/moduleLoader';\n\nimport useModuleLoader from '../../../hooks/useModuleLoader';\n\nconst SymbolMenuAsync: FC<OwnProps> = (props) => {\n const { isOpen } = props;\n const SymbolMenu = useModuleLoader(Bundles.Extra, 'SymbolMenu', !isOpen);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return SymbolMenu ? <SymbolMenu {...props} /> : undefined;\n};\n\nexport default SymbolMenuAsync;\n","import React, { FC } from '../../../lib/teact/teact';\nimport { OwnProps } from './MentionMenu';\nimport { Bundles } from '../../../util/moduleLoader';\n\nimport useModuleLoader from '../../../hooks/useModuleLoader';\n\nconst MentionMenuAsync: FC<OwnProps> = (props) => {\n const { isOpen } = props;\n const MentionMenu = useModuleLoader(Bundles.Extra, 'MentionMenu', !isOpen);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return MentionMenu ? <MentionMenu {...props} /> : undefined;\n};\n\nexport default MentionMenuAsync;\n","import React, { FC } from '../../../lib/teact/teact';\nimport { OwnProps } from './CustomSendMenu';\nimport { Bundles } from '../../../util/moduleLoader';\n\nimport useModuleLoader from '../../../hooks/useModuleLoader';\n\nconst CustomSendMenuAsync: FC<OwnProps> = (props) => {\n const { isOpen } = props;\n const CustomSend = useModuleLoader(Bundles.Extra, 'CustomSendMenu', !isOpen);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return CustomSend ? <CustomSend {...props} /> : undefined;\n};\n\nexport default CustomSendMenuAsync;\n","import React, { FC } from '../../../lib/teact/teact';\nimport { OwnProps } from './EmojiTooltip';\nimport { Bundles } from '../../../util/moduleLoader';\n\nimport useModuleLoader from '../../../hooks/useModuleLoader';\n\nconst EmojiTooltipAsync: FC<OwnProps> = (props) => {\n const { isOpen } = props;\n const EmojiTooltip = useModuleLoader(Bundles.Extra, 'EmojiTooltip', !isOpen);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return EmojiTooltip ? <EmojiTooltip {...props} /> : undefined;\n};\n\nexport default EmojiTooltipAsync;\n","import React, { FC } from '../../../lib/teact/teact';\nimport { OwnProps } from './BotKeyboardMenu';\nimport { Bundles } from '../../../util/moduleLoader';\n\nimport useModuleLoader from '../../../hooks/useModuleLoader';\n\nconst BotKeyboardMenuAsync: FC<OwnProps> = (props) => {\n const { isOpen } = props;\n const BotKeyboardMenu = useModuleLoader(Bundles.Extra, 'BotKeyboardMenu', !isOpen);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return BotKeyboardMenu ? <BotKeyboardMenu {...props} /> : undefined;\n};\n\nexport default BotKeyboardMenuAsync;\n","import React, {\n FC, memo, useCallback, useEffect,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../../global/types';\nimport { ApiChat, ApiMessage, ApiUser } from '../../../api/types';\n\nimport {\n selectChat,\n selectChatMessage,\n selectSender,\n selectForwardedSender,\n selectUser,\n selectCurrentMessageList,\n selectReplyingToId,\n selectEditingId,\n selectEditingScheduledId,\n selectEditingMessage,\n} from '../../../modules/selectors';\nimport captureEscKeyListener from '../../../util/captureEscKeyListener';\nimport { pick } from '../../../util/iteratees';\nimport useAsyncRendering from '../../right/hooks/useAsyncRendering';\nimport useShowTransition from '../../../hooks/useShowTransition';\nimport buildClassName from '../../../util/buildClassName';\nimport { isChatPrivate } from '../../../modules/helpers';\n\nimport Button from '../../ui/Button';\nimport EmbeddedMessage from '../../common/EmbeddedMessage';\n\nimport './ComposerEmbeddedMessage.scss';\n\ntype StateProps = {\n replyingToId?: number;\n editingId?: number;\n message?: ApiMessage;\n sender?: ApiUser | ApiChat;\n shouldAnimate?: boolean;\n forwardedMessagesCount?: number;\n};\n\ntype DispatchProps = Pick<GlobalActions, 'setReplyingToId' | 'setEditingId' | 'focusMessage' | 'exitForwardMode'>;\n\nconst FORWARD_RENDERING_DELAY = 300;\n\nconst ComposerEmbeddedMessage: FC<StateProps & DispatchProps> = ({\n replyingToId,\n editingId,\n message,\n sender,\n shouldAnimate,\n forwardedMessagesCount,\n setReplyingToId,\n setEditingId,\n focusMessage,\n exitForwardMode,\n}) => {\n const isShown = Boolean(\n ((replyingToId || editingId) && message)\n || (sender && forwardedMessagesCount),\n );\n const canAnimate = useAsyncRendering(\n [forwardedMessagesCount],\n forwardedMessagesCount ? FORWARD_RENDERING_DELAY : undefined,\n );\n\n const {\n shouldRender, transitionClassNames,\n } = useShowTransition(canAnimate && isShown, undefined, !shouldAnimate, undefined, !shouldAnimate);\n\n const clearEmbedded = useCallback(() => {\n if (replyingToId) {\n setReplyingToId({ messageId: undefined });\n } else if (editingId) {\n setEditingId({ messageId: undefined });\n } else if (forwardedMessagesCount) {\n exitForwardMode();\n }\n }, [replyingToId, editingId, forwardedMessagesCount, setReplyingToId, setEditingId, exitForwardMode]);\n\n useEffect(() => (isShown ? captureEscKeyListener(clearEmbedded) : undefined), [isShown, clearEmbedded]);\n\n const handleMessageClick = useCallback((): void => {\n focusMessage({ chatId: message!.chatId, messageId: message!.id });\n }, [focusMessage, message]);\n\n const className = buildClassName('ComposerEmbeddedMessage', transitionClassNames);\n\n const customText = forwardedMessagesCount && forwardedMessagesCount > 1\n ? `${forwardedMessagesCount} forwarded messages`\n : undefined;\n\n if (!shouldRender) {\n return undefined;\n }\n\n return (\n <div className={className}>\n <div>\n <Button round color=\"translucent\" ariaLabel=\"Cancel replying\" onClick={clearEmbedded}>\n <i className=\"icon-close\" />\n </Button>\n <EmbeddedMessage\n className=\"inside-input\"\n message={message}\n sender={sender}\n customText={customText}\n title={editingId ? 'Edit Message' : undefined}\n onClick={handleMessageClick}\n />\n </div>\n </div>\n );\n};\n\nexport default memo(withGlobal(\n (global): StateProps => {\n const { chatId, threadId, type: messageListType } = selectCurrentMessageList(global) || {};\n if (!chatId || !threadId || !messageListType) {\n return {};\n }\n\n const {\n currentUserId,\n forwardMessages: { fromChatId, toChatId, messageIds: forwardMessageIds },\n } = global;\n\n const replyingToId = selectReplyingToId(global, chatId, threadId);\n const editingId = messageListType === 'scheduled'\n ? selectEditingScheduledId(global, chatId)\n : selectEditingId(global, chatId, threadId);\n const shouldAnimate = global.settings.byKey.animationLevel >= 1;\n const isForwarding = toChatId === chatId;\n\n let message;\n if (replyingToId) {\n message = selectChatMessage(global, chatId, replyingToId);\n } else if (editingId) {\n message = selectEditingMessage(global, chatId, threadId, messageListType);\n } else if (isForwarding && forwardMessageIds!.length === 1) {\n message = selectChatMessage(global, fromChatId!, forwardMessageIds![0]);\n }\n\n let sender: ApiChat | ApiUser | undefined;\n if (replyingToId && message) {\n const { forwardInfo } = message;\n const isChatWithSelf = chatId === currentUserId;\n\n if (forwardInfo && (forwardInfo.isChannelPost || isChatWithSelf)) {\n sender = selectForwardedSender(global, message);\n }\n\n if (!sender) {\n sender = selectSender(global, message);\n }\n } else if (isForwarding) {\n sender = isChatPrivate(fromChatId!) ? selectUser(global, fromChatId!) : selectChat(global, fromChatId!);\n }\n\n return {\n replyingToId,\n editingId,\n message,\n sender,\n shouldAnimate,\n forwardedMessagesCount: isForwarding ? forwardMessageIds!.length : undefined,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'setReplyingToId',\n 'setEditingId',\n 'focusMessage',\n 'exitForwardMode',\n ]),\n)(ComposerEmbeddedMessage));\n","import React, { FC } from '../../../lib/teact/teact';\nimport { OwnProps } from './AttachmentModal';\nimport { Bundles } from '../../../util/moduleLoader';\n\nimport useModuleLoader from '../../../hooks/useModuleLoader';\n\nconst AttachmentModalAsync: FC<OwnProps> = (props) => {\n const { attachments } = props;\n const AttachmentModal = useModuleLoader(Bundles.Extra, 'AttachmentModal', !attachments.length);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return AttachmentModal ? <AttachmentModal {...props} /> : undefined;\n};\n\nexport default AttachmentModalAsync;\n","import React, { FC } from '../../../lib/teact/teact';\nimport { OwnProps } from './PollModal';\nimport { Bundles } from '../../../util/moduleLoader';\n\nimport useModuleLoader from '../../../hooks/useModuleLoader';\n\nconst PollModalAsync: FC<OwnProps> = (props) => {\n const { isOpen } = props;\n const PollModal = useModuleLoader(Bundles.Extra, 'PollModal', !isOpen);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return PollModal ? <PollModal {...props} /> : undefined;\n};\n\nexport default PollModalAsync;\n","import React, { FC } from '../../../lib/teact/teact';\nimport { OwnProps } from './DropArea';\nimport { Bundles } from '../../../util/moduleLoader';\n\nimport useModuleLoader from '../../../hooks/useModuleLoader';\n\nconst DropAreaAsync: FC<OwnProps> = (props) => {\n const { isOpen } = props;\n const DropArea = useModuleLoader(Bundles.Extra, 'DropArea', !isOpen);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return DropArea ? <DropArea {...props} /> : undefined;\n};\n\nexport default DropAreaAsync;\nexport { DropAreaState } from './DropArea';\n","import React, {\n FC, memo, useEffect, useMemo,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../../global/types';\nimport { ApiMessage, ApiMessageEntityTypes, ApiWebPage } from '../../../api/types';\n\nimport { selectNoWebPage } from '../../../modules/selectors';\nimport { pick } from '../../../util/iteratees';\nimport parseMessageInput from './helpers/parseMessageInput';\nimport useOnChange from '../../../hooks/useOnChange';\n\nimport WebPage from '../message/WebPage';\nimport Button from '../../ui/Button';\n\nimport './WebPagePreview.scss';\n\ntype OwnProps = {\n chatId: number;\n threadId: number;\n messageText: string;\n};\n\ntype StateProps = {\n webPagePreview?: ApiWebPage;\n noWebPage?: boolean;\n};\ntype DispatchProps = Pick<GlobalActions, 'loadWebPagePreview' | 'clearWebPagePreview' | 'toggleMessageWebPage'>;\n\nconst RE_LINK = /https?:\\/\\/(www.)?([a-zA-Z0-9.-]{2,256})([a-zA-Z/.-]{1,256})([?|#][=&#a-zA-Z0-9]{2,128})?/;\n\nconst WebPagePreview: FC<OwnProps & StateProps & DispatchProps> = ({\n chatId,\n threadId,\n messageText,\n webPagePreview,\n noWebPage,\n loadWebPagePreview,\n clearWebPagePreview,\n toggleMessageWebPage,\n}) => {\n const link = useMemo(() => {\n const { text, entities } = parseMessageInput(messageText);\n\n const linkEntity = entities && entities.find(({ type }) => type === ApiMessageEntityTypes.TextUrl);\n if (linkEntity) {\n return linkEntity.url;\n }\n\n const textMatch = text.match(RE_LINK);\n if (textMatch) {\n return textMatch[0];\n }\n\n return undefined;\n }, [messageText]);\n\n useEffect(() => {\n if (link) {\n loadWebPagePreview({ text: link });\n } else {\n clearWebPagePreview();\n toggleMessageWebPage({ chatId, threadId });\n }\n }, [chatId, toggleMessageWebPage, clearWebPagePreview, link, loadWebPagePreview, threadId]);\n\n useOnChange(() => {\n clearWebPagePreview();\n toggleMessageWebPage({ chatId, threadId });\n }, [chatId]);\n\n const handleClearWebpagePreview = () => {\n toggleMessageWebPage({ chatId, threadId, noWebPage: true });\n };\n\n if (!webPagePreview || !messageText.length || noWebPage) {\n return undefined;\n }\n\n // TODO Refactor so `WebPage` can be used without message\n const { photo, ...webPageWithoutPhoto } = webPagePreview;\n const messageStub = {\n content: {\n webPage: webPageWithoutPhoto,\n },\n } as ApiMessage;\n\n return (\n <div className=\"WebPagePreview\">\n <Button round color=\"translucent\" ariaLabel=\"Clear Webpage Preview\" onClick={handleClearWebpagePreview}>\n <i className=\"icon-close\" />\n </Button>\n <WebPage message={messageStub} inPreview />\n </div>\n );\n};\n\nexport default memo(withGlobal<OwnProps>(\n (global, { chatId, threadId }): StateProps => {\n const noWebPage = selectNoWebPage(global, chatId, threadId);\n return {\n webPagePreview: global.webPagePreview,\n noWebPage,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'loadWebPagePreview', 'clearWebPagePreview', 'toggleMessageWebPage',\n ]),\n)(WebPagePreview));\n","import React, { FC } from '../../lib/teact/teact';\nimport { OwnProps } from './CalendarModal';\nimport { Bundles } from '../../util/moduleLoader';\n\nimport useModuleLoader from '../../hooks/useModuleLoader';\n\nconst CalendarModalAsync: FC<OwnProps> = (props) => {\n const { isOpen } = props;\n const CalendarModal = useModuleLoader(Bundles.Extra, 'CalendarModal', !isOpen);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return CalendarModal ? <CalendarModal {...props} /> : undefined;\n};\n\nexport default CalendarModalAsync;\n","import React, { FC } from '../../lib/teact/teact';\nimport { OwnProps } from './PaymentModal';\nimport { Bundles } from '../../util/moduleLoader';\n\nimport useModuleLoader from '../../hooks/useModuleLoader';\n\nconst PaymentModalAsync: FC<OwnProps> = (props) => {\n const { isOpen } = props;\n const PaymentModal = useModuleLoader(Bundles.Extra, 'PaymentModal', !isOpen);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return PaymentModal ? <PaymentModal {...props} /> : undefined;\n};\n\nexport default PaymentModalAsync;\n","import React, { FC } from '../../lib/teact/teact';\nimport { OwnProps } from './ReceiptModal';\nimport { Bundles } from '../../util/moduleLoader';\n\nimport useModuleLoader from '../../hooks/useModuleLoader';\n\nconst ReceiptModalAsync: FC<OwnProps> = (props) => {\n const { isOpen } = props;\n const ReceiptModal = useModuleLoader(Bundles.Extra, 'ReceiptModal', !isOpen);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return ReceiptModal ? <ReceiptModal {...props} /> : undefined;\n};\n\nexport default ReceiptModalAsync;\n","import React, {\n FC, memo, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalActions, GlobalState, MessageListType } from '../../../global/types';\nimport {\n ApiAttachment,\n ApiSticker,\n ApiVideo,\n ApiNewPoll,\n ApiMessage,\n ApiFormattedText,\n ApiChat,\n ApiChatMember,\n ApiUser,\n MAIN_THREAD_ID,\n} from '../../../api/types';\n\nimport { EDITABLE_INPUT_ID, SCHEDULED_WHEN_ONLINE } from '../../../config';\nimport { IS_EMOJI_SUPPORTED, IS_VOICE_RECORDING_SUPPORTED, IS_MOBILE_SCREEN } from '../../../util/environment';\nimport {\n selectChat,\n selectIsChatWithBot,\n selectIsRightColumnShown,\n selectIsInSelectMode,\n selectNewestMessageWithBotKeyboardButtons,\n selectDraft,\n selectScheduledIds,\n selectEditingMessage,\n selectIsChatWithSelf,\n selectChatUser,\n} from '../../../modules/selectors';\nimport {\n getAllowedAttachmentOptions,\n getChatSlowModeOptions,\n isChatGroup,\n isChatPrivate,\n isChatAdmin,\n} from '../../../modules/helpers';\nimport { formatVoiceRecordDuration, getDayStartAt } from '../../../util/dateFormat';\nimport focusEditableElement from '../../../util/focusEditableElement';\nimport parseMessageInput from './helpers/parseMessageInput';\nimport buildAttachment from './helpers/buildAttachment';\nimport renderText from '../../common/helpers/renderText';\nimport insertHtmlInSelection from '../../../util/insertHtmlInSelection';\nimport deleteLastCharacterOutsideSelection from '../../../util/deleteLastCharacterOutsideSelection';\nimport { pick } from '../../../util/iteratees';\nimport buildClassName from '../../../util/buildClassName';\nimport { isSelectionInsideInput } from './helpers/selection';\n\nimport useFlag from '../../../hooks/useFlag';\nimport useVoiceRecording from './hooks/useVoiceRecording';\nimport useClipboardPaste from './hooks/useClipboardPaste';\nimport useDraft from './hooks/useDraft';\nimport useEditing from './hooks/useEditing';\nimport usePrevious from '../../../hooks/usePrevious';\nimport useEmojiTooltip from './hooks/useEmojiTooltip';\nimport useMentionMenu from './hooks/useMentionMenu';\nimport useContextMenuHandlers from '../../../hooks/useContextMenuHandlers';\nimport useLang from '../../../hooks/useLang';\n\nimport DeleteMessageModal from '../../common/DeleteMessageModal.async';\nimport Button from '../../ui/Button';\nimport ResponsiveHoverButton from '../../ui/ResponsiveHoverButton';\nimport Spinner from '../../ui/Spinner';\nimport AttachMenu from './AttachMenu.async';\nimport SymbolMenu from './SymbolMenu.async';\nimport MentionMenu from './MentionMenu.async';\nimport CustomSendMenu from './CustomSendMenu.async';\nimport EmojiTooltip from './EmojiTooltip.async';\nimport BotKeyboardMenu from './BotKeyboardMenu.async';\nimport MessageInput from './MessageInput';\nimport ComposerEmbeddedMessage from './ComposerEmbeddedMessage';\nimport AttachmentModal from './AttachmentModal.async';\nimport PollModal from './PollModal.async';\nimport DropArea, { DropAreaState } from './DropArea.async';\nimport WebPagePreview from './WebPagePreview';\nimport Portal from '../../ui/Portal';\nimport CalendarModal from '../../common/CalendarModal.async';\nimport PaymentModal from '../../payment/PaymentModal.async';\nimport ReceiptModal from '../../payment/ReceiptModal.async';\n\nimport './Composer.scss';\n\ntype OwnProps = {\n chatId: number;\n threadId: number;\n messageListType: MessageListType;\n dropAreaState: string;\n onDropHide: NoneToVoidFunction;\n};\n\ntype StateProps = {\n editingMessage?: ApiMessage;\n chat?: ApiChat;\n draft?: ApiFormattedText;\n isChatWithBot?: boolean;\n isChatWithSelf?: boolean;\n isRightColumnShown?: boolean;\n isSelectModeActive?: boolean;\n isForwarding?: boolean;\n canSuggestMembers?: boolean;\n isPollModalOpen?: boolean;\n isPaymentModalOpen?: boolean;\n isReceiptModalOpen?: boolean;\n botKeyboardMessageId?: number;\n withScheduledButton?: boolean;\n shouldSchedule?: boolean;\n canScheduleUntilOnline?: boolean;\n stickersForEmoji?: ApiSticker[];\n groupChatMembers?: ApiChatMember[];\n currentUserId?: number;\n usersById?: Record<number, ApiUser>;\n lastSyncTime?: number;\n contentToBeScheduled?: GlobalState['messages']['contentToBeScheduled'];\n shouldSuggestStickers?: boolean;\n} & Pick<GlobalState, 'connectionState'>;\n\ntype DispatchProps = Pick<GlobalActions, (\n 'sendMessage' | 'editMessage' | 'saveDraft' | 'forwardMessages' |\n 'clearDraft' | 'showError' | 'setStickerSearchQuery' | 'setGifSearchQuery' |\n 'openPollModal' | 'closePollModal' | 'loadScheduledHistory' | 'openChat' | 'closePaymentModal' |\n 'clearReceipt'\n)>;\n\nenum MainButtonState {\n Send = 'send',\n Record = 'record',\n Edit = 'edit',\n}\n\nconst VOICE_RECORDING_FILENAME = 'wonderful-voice-message.ogg';\n// When voice recording is active, composer placeholder will hide to prevent overlapping\nconst SCREEN_WIDTH_TO_HIDE_PLACEHOLDER = 600; // px\n\nconst MOBILE_KEYBOARD_HIDE_DELAY_MS = 100;\nconst SELECT_MODE_TRANSITION_MS = 200;\nconst CAPTION_MAX_LENGTH = 1024;\nconst SENDING_ANIMATION_DURATION = 350;\n// eslint-disable-next-line max-len\nconst APPENDIX = '<svg width=\"9\" height=\"20\" xmlns=\"http://www.w3.org/2000/svg\"><defs><filter x=\"-50%\" y=\"-14.7%\" width=\"200%\" height=\"141.2%\" filterUnits=\"objectBoundingBox\" id=\"a\"><feOffset dy=\"1\" in=\"SourceAlpha\" result=\"shadowOffsetOuter1\"/><feGaussianBlur stdDeviation=\"1\" in=\"shadowOffsetOuter1\" result=\"shadowBlurOuter1\"/><feColorMatrix values=\"0 0 0 0 0.0621962482 0 0 0 0 0.138574144 0 0 0 0 0.185037364 0 0 0 0.15 0\" in=\"shadowBlurOuter1\"/></filter></defs><g fill=\"none\" fill-rule=\"evenodd\"><path d=\"M6 17H0V0c.193 2.84.876 5.767 2.05 8.782.904 2.325 2.446 4.485 4.625 6.48A1 1 0 016 17z\" fill=\"#000\" filter=\"url(#a)\"/><path d=\"M6 17H0V0c.193 2.84.876 5.767 2.05 8.782.904 2.325 2.446 4.485 4.625 6.48A1 1 0 016 17z\" fill=\"#FFF\" class=\"corner\"/></g></svg>';\n\nconst Composer: FC<OwnProps & StateProps & DispatchProps> = ({\n dropAreaState,\n shouldSchedule,\n canScheduleUntilOnline,\n onDropHide,\n editingMessage,\n chatId,\n threadId,\n messageListType,\n draft,\n chat,\n connectionState,\n isChatWithBot,\n isChatWithSelf,\n isRightColumnShown,\n isSelectModeActive,\n isForwarding,\n canSuggestMembers,\n isPollModalOpen,\n isPaymentModalOpen,\n isReceiptModalOpen,\n botKeyboardMessageId,\n withScheduledButton,\n stickersForEmoji,\n groupChatMembers,\n currentUserId,\n usersById,\n lastSyncTime,\n contentToBeScheduled,\n shouldSuggestStickers,\n sendMessage,\n editMessage,\n saveDraft,\n clearDraft,\n showError,\n setStickerSearchQuery,\n setGifSearchQuery,\n forwardMessages,\n openPollModal,\n closePollModal,\n loadScheduledHistory,\n closePaymentModal,\n openChat,\n clearReceipt,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const appendixRef = useRef<HTMLDivElement>(null);\n const [html, setHtml] = useState<string>('');\n const lastMessageSendTimeSeconds = useRef<number>();\n const prevDropAreaState = usePrevious(dropAreaState);\n const [isCalendarOpen, openCalendar, closeCalendar] = useFlag();\n const [\n scheduledMessageArgs, setScheduledMessageArgs,\n ] = useState<GlobalState['messages']['contentToBeScheduled'] | undefined>();\n\n // Cache for frequently updated state\n const htmlRef = useRef<string>(html);\n useEffect(() => {\n htmlRef.current = html;\n }, [html]);\n\n useEffect(() => {\n lastMessageSendTimeSeconds.current = undefined;\n }, [chatId]);\n\n useEffect(() => {\n if (chatId && lastSyncTime && threadId === MAIN_THREAD_ID) {\n loadScheduledHistory();\n }\n }, [chatId, loadScheduledHistory, lastSyncTime, threadId]);\n\n useLayoutEffect(() => {\n if (!appendixRef.current) {\n return;\n }\n\n appendixRef.current.innerHTML = APPENDIX;\n }, []);\n\n useEffect(() => {\n if (contentToBeScheduled) {\n setScheduledMessageArgs(contentToBeScheduled);\n openCalendar();\n }\n }, [contentToBeScheduled, openCalendar]);\n\n const [attachments, setAttachments] = useState<ApiAttachment[]>([]);\n\n const [isBotKeyboardOpen, openBotKeyboard, closeBotKeyboard] = useFlag();\n const [isAttachMenuOpen, openAttachMenu, closeAttachMenu] = useFlag();\n const [isSymbolMenuOpen, openSymbolMenu, closeSymbolMenu] = useFlag();\n const [isDeleteModalOpen, openDeleteModal, closeDeleteModal] = useFlag();\n const [isSymbolMenuLoaded, onSymbolMenuLoadingComplete] = useFlag();\n const [isHoverDisabled, disableHover, enableHover] = useFlag();\n\n const {\n startRecordingVoice,\n stopRecordingVoice,\n pauseRecordingVoice,\n activeVoiceRecording,\n currentRecordTime,\n recordButtonRef: mainButtonRef,\n startRecordTimeRef,\n } = useVoiceRecording();\n\n const mainButtonState = editingMessage\n ? MainButtonState.Edit\n : !IS_VOICE_RECORDING_SUPPORTED || activeVoiceRecording || (html && !attachments.length) || isForwarding\n ? MainButtonState.Send\n : MainButtonState.Record;\n const canShowCustomSendMenu = !shouldSchedule;\n\n const {\n isMentionMenuOpen, mentionFilter,\n closeMentionMenu, insertMention,\n mentionFilteredMembers,\n } = useMentionMenu(\n canSuggestMembers && !attachments.length,\n html,\n setHtml,\n undefined,\n groupChatMembers,\n currentUserId,\n usersById,\n );\n\n const {\n isContextMenuOpen: isCustomSendMenuOpen,\n handleContextMenu,\n handleContextMenuClose,\n handleContextMenuHide,\n } = useContextMenuHandlers(mainButtonRef, !(mainButtonState === MainButtonState.Send && canShowCustomSendMenu));\n\n const allowedAttachmentOptions = useMemo(() => {\n return getAllowedAttachmentOptions(chat, isChatWithBot);\n }, [chat, isChatWithBot]);\n\n const isAdmin = chat && isChatAdmin(chat);\n const slowMode = getChatSlowModeOptions(chat);\n\n const { isEmojiTooltipOpen, closeEmojiTooltip } = useEmojiTooltip(\n Boolean(shouldSuggestStickers && allowedAttachmentOptions.canSendStickers && !attachments.length),\n html,\n stickersForEmoji,\n );\n\n const insertTextAndUpdateCursor = useCallback((text: string) => {\n const selection = window.getSelection()!;\n const messageInput = document.getElementById(EDITABLE_INPUT_ID)!;\n const newHtml = renderText(text, ['escape_html', 'emoji_html', 'br_html'])\n .join('')\n .replace(/\\u200b+/g, '\\u200b');\n if (selection.rangeCount) {\n const selectionRange = selection.getRangeAt(0);\n if (isSelectionInsideInput(selectionRange)) {\n if (IS_EMOJI_SUPPORTED) {\n // Insertion will trigger `onChange` in MessageInput, so no need to setHtml in state\n document.execCommand('insertText', false, text);\n } else {\n insertHtmlInSelection(newHtml);\n messageInput.dispatchEvent(new Event('input', { bubbles: true }));\n }\n\n return;\n }\n\n setHtml(`${htmlRef.current!}${newHtml}`);\n\n if (!IS_MOBILE_SCREEN) {\n // If selection is outside of input, set cursor at the end of input\n requestAnimationFrame(() => {\n focusEditableElement(messageInput);\n });\n }\n } else {\n setHtml(`${htmlRef.current!}${newHtml}`);\n }\n }, []);\n\n const removeSymbol = useCallback(() => {\n const selection = window.getSelection()!;\n\n if (selection.rangeCount) {\n const selectionRange = selection.getRangeAt(0);\n if (isSelectionInsideInput(selectionRange)) {\n document.execCommand('delete', false);\n return;\n }\n }\n\n setHtml(deleteLastCharacterOutsideSelection(htmlRef.current!));\n }, []);\n\n const resetComposer = useCallback(() => {\n setHtml('');\n setAttachments([]);\n closeEmojiTooltip();\n closeCalendar();\n setScheduledMessageArgs(undefined);\n closeMentionMenu();\n\n if (IS_MOBILE_SCREEN) {\n // @perf\n setTimeout(() => closeSymbolMenu(), SENDING_ANIMATION_DURATION);\n } else {\n closeSymbolMenu();\n }\n }, [closeEmojiTooltip, closeCalendar, closeMentionMenu, closeSymbolMenu]);\n\n // Handle chat change\n const prevChatId = usePrevious(chatId);\n useEffect(() => {\n if (!prevChatId || chatId === prevChatId) {\n return;\n }\n\n stopRecordingVoice();\n resetComposer();\n }, [chatId, prevChatId, resetComposer, stopRecordingVoice]);\n\n const handleEditComplete = useEditing(htmlRef, setHtml, editingMessage, resetComposer, openDeleteModal, editMessage);\n useDraft(draft, chatId, threadId, html, htmlRef, setHtml, editingMessage, saveDraft, clearDraft);\n useClipboardPaste(insertTextAndUpdateCursor, setAttachments, editingMessage);\n\n const handleFileSelect = useCallback(async (files: File[], isQuick: boolean) => {\n setAttachments(await Promise.all(files.map((file) => buildAttachment(file.name, file, isQuick))));\n }, []);\n\n const handleClearAttachment = useCallback(() => {\n setAttachments([]);\n }, []);\n\n const handleSend = useCallback(async (isSilent = false, scheduledAt?: number) => {\n if (connectionState !== 'connectionStateReady') {\n return;\n }\n\n let currentAttachments = attachments;\n\n if (activeVoiceRecording) {\n const record = await stopRecordingVoice();\n if (record) {\n const { blob, duration, waveform } = record;\n currentAttachments = [await buildAttachment(\n VOICE_RECORDING_FILENAME,\n blob,\n false,\n { voice: { duration, waveform } },\n )];\n }\n }\n\n const { text, entities } = parseMessageInput(htmlRef.current!);\n if (!currentAttachments.length && !text && !isForwarding) {\n return;\n }\n\n if (currentAttachments.length && text && text.length > CAPTION_MAX_LENGTH) {\n const extraLength = text.length - CAPTION_MAX_LENGTH;\n showError({\n error: {\n message: 'CAPTION_TOO_LONG_PLEASE_REMOVE_CHARACTERS',\n textParams: {\n '{EXTRA_CHARS_COUNT}': extraLength,\n '{PLURAL_S}': extraLength > 1 ? 's' : '',\n },\n },\n });\n return;\n }\n\n if (currentAttachments.length || text) {\n if (slowMode && !isAdmin) {\n const nowSeconds = Math.floor(Date.now() / 1000);\n const secondsSinceLastMessage = lastMessageSendTimeSeconds.current\n && Math.floor(nowSeconds - lastMessageSendTimeSeconds.current);\n const nextSendDateNotReached = slowMode.nextSendDate && slowMode.nextSendDate > nowSeconds;\n\n if (\n (secondsSinceLastMessage && secondsSinceLastMessage < slowMode.seconds)\n || nextSendDateNotReached\n ) {\n const secondsRemaining = nextSendDateNotReached\n ? slowMode.nextSendDate! - nowSeconds\n : slowMode.seconds - secondsSinceLastMessage!;\n showError({\n error: {\n message: `A wait of ${secondsRemaining} seconds is required before sending another message in this chat`,\n isSlowMode: true,\n },\n });\n\n const messageInput = document.getElementById(EDITABLE_INPUT_ID)!;\n messageInput.blur();\n\n return;\n }\n }\n\n sendMessage({\n text,\n entities,\n attachments: currentAttachments,\n scheduledAt,\n isSilent,\n });\n }\n if (isForwarding) {\n forwardMessages();\n }\n\n lastMessageSendTimeSeconds.current = Math.floor(Date.now() / 1000);\n\n clearDraft({ chatId, localOnly: true });\n\n // Wait until message animation starts\n requestAnimationFrame(resetComposer);\n }, [\n activeVoiceRecording, attachments, connectionState, chatId, slowMode, isForwarding, isAdmin,\n sendMessage, stopRecordingVoice, resetComposer, clearDraft, showError, forwardMessages,\n ]);\n\n const handleStickerSelect = useCallback((sticker: ApiSticker) => {\n sticker = {\n ...sticker,\n isPreloadedGlobally: true,\n };\n\n if (shouldSchedule) {\n setScheduledMessageArgs({ sticker });\n openCalendar();\n } else {\n sendMessage({ sticker });\n requestAnimationFrame(resetComposer);\n }\n }, [shouldSchedule, openCalendar, sendMessage, resetComposer]);\n\n const handleGifSelect = useCallback((gif: ApiVideo) => {\n if (shouldSchedule) {\n setScheduledMessageArgs({ gif });\n openCalendar();\n } else {\n sendMessage({ gif });\n requestAnimationFrame(resetComposer);\n }\n }, [shouldSchedule, openCalendar, sendMessage, resetComposer]);\n\n const handlePollSend = useCallback((poll: ApiNewPoll) => {\n if (shouldSchedule) {\n setScheduledMessageArgs({ poll });\n closePollModal();\n openCalendar();\n } else {\n sendMessage({ poll });\n closePollModal();\n }\n }, [closePollModal, openCalendar, sendMessage, shouldSchedule]);\n\n const handleSilentSend = useCallback(() => {\n if (shouldSchedule) {\n setScheduledMessageArgs({ isSilent: true });\n openCalendar();\n } else {\n handleSend(true);\n }\n }, [handleSend, openCalendar, shouldSchedule]);\n\n const handleMessageSchedule = useCallback((date: Date) => {\n const { isSilent, ...restArgs } = scheduledMessageArgs || {};\n\n // Scheduled time can not be less than 10 seconds in future\n const scheduledAt = Math.round(Math.max(date.getTime(), Date.now() + 60 * 1000) / 1000);\n\n if (!scheduledMessageArgs || Object.keys(restArgs).length === 0) {\n handleSend(!!isSilent, scheduledAt);\n } else {\n sendMessage({\n ...scheduledMessageArgs,\n scheduledAt,\n });\n requestAnimationFrame(resetComposer);\n }\n closeCalendar();\n }, [closeCalendar, handleSend, resetComposer, scheduledMessageArgs, sendMessage]);\n\n const handleMessageScheduleUntilOnline = useCallback(() => {\n handleMessageSchedule(new Date(SCHEDULED_WHEN_ONLINE * 1000));\n }, [handleMessageSchedule]);\n\n const handleCloseCalendar = useCallback(() => {\n closeCalendar();\n setScheduledMessageArgs(undefined);\n }, [closeCalendar]);\n\n const handleSearchOpen = useCallback((type: 'stickers' | 'gifs') => {\n if (type === 'stickers') {\n setStickerSearchQuery({ query: '' });\n setGifSearchQuery({ query: undefined });\n } else {\n setGifSearchQuery({ query: '' });\n setStickerSearchQuery({ query: undefined });\n }\n }, [setStickerSearchQuery, setGifSearchQuery]);\n\n const handleSymbolMenuOpen = useCallback(() => {\n const messageInput = document.getElementById(EDITABLE_INPUT_ID)!;\n\n if (!IS_MOBILE_SCREEN || messageInput !== document.activeElement) {\n openSymbolMenu();\n return;\n }\n\n messageInput.blur();\n setTimeout(() => {\n openSymbolMenu();\n }, MOBILE_KEYBOARD_HIDE_DELAY_MS);\n }, [openSymbolMenu]);\n\n const handleAllScheduledClick = useCallback(() => {\n openChat({ id: chatId, threadId, type: 'scheduled' });\n }, [openChat, chatId, threadId]);\n\n useEffect(() => {\n if (isRightColumnShown && IS_MOBILE_SCREEN) {\n closeSymbolMenu();\n }\n }, [isRightColumnShown, closeSymbolMenu]);\n\n useEffect(() => {\n if (isSelectModeActive) {\n disableHover();\n } else {\n setTimeout(() => {\n enableHover();\n }, SELECT_MODE_TRANSITION_MS);\n }\n }, [isSelectModeActive, enableHover, disableHover]);\n\n const mainButtonHandler = useCallback(() => {\n switch (mainButtonState) {\n case MainButtonState.Send:\n if (shouldSchedule) {\n if (activeVoiceRecording) {\n pauseRecordingVoice();\n }\n openCalendar();\n } else {\n handleSend();\n requestAnimationFrame(resetComposer);\n }\n break;\n case MainButtonState.Record:\n startRecordingVoice();\n break;\n case MainButtonState.Edit:\n handleEditComplete();\n break;\n default:\n break;\n }\n }, [\n mainButtonState, resetComposer, shouldSchedule, startRecordingVoice, handleEditComplete,\n activeVoiceRecording, openCalendar, pauseRecordingVoice, handleSend,\n ]);\n\n const lang = useLang();\n\n const areVoiceMessagesNotAllowed = mainButtonState === MainButtonState.Record\n && !allowedAttachmentOptions.canAttachMedia;\n\n const prevEditedMessage = usePrevious(editingMessage, true);\n const renderedEditedMessage = editingMessage || prevEditedMessage;\n\n const scheduledDefaultDate = new Date();\n scheduledDefaultDate.setSeconds(0);\n scheduledDefaultDate.setMilliseconds(0);\n\n const scheduledMaxDate = new Date();\n scheduledMaxDate.setFullYear(scheduledMaxDate.getFullYear() + 1);\n\n let sendButtonAriaLabel = 'Send message';\n switch (mainButtonState) {\n case MainButtonState.Edit:\n sendButtonAriaLabel = 'Save edited message';\n break;\n case MainButtonState.Record:\n sendButtonAriaLabel = areVoiceMessagesNotAllowed\n ? 'Posting media content is not allowed in this group.'\n : 'Record a voice message';\n }\n\n const className = buildClassName(\n 'Composer',\n !isSelectModeActive && 'shown',\n isHoverDisabled && 'hover-disabled',\n );\n\n const symbolMenuButtonClassName = buildClassName(\n 'mobile-symbol-menu-button',\n isSymbolMenuLoaded\n ? (isSymbolMenuOpen && 'menu-opened')\n : (isSymbolMenuOpen && 'is-loading'),\n );\n\n return (\n <div className={className}>\n {allowedAttachmentOptions.canAttachMedia && (\n <Portal containerId=\"#middle-column-portals\">\n <DropArea\n isOpen={dropAreaState !== DropAreaState.None}\n withQuick={[dropAreaState, prevDropAreaState].includes(DropAreaState.QuickFile)}\n onHide={onDropHide}\n onFileSelect={handleFileSelect}\n />\n </Portal>\n )}\n <AttachmentModal\n attachments={attachments}\n caption={attachments.length ? html : ''}\n canSuggestMembers={canSuggestMembers}\n groupChatMembers={groupChatMembers}\n currentUserId={currentUserId}\n usersById={usersById}\n onCaptionUpdate={setHtml}\n onSend={shouldSchedule ? openCalendar : handleSend}\n onClear={handleClearAttachment}\n />\n <PollModal\n isOpen={Boolean(isPollModalOpen)}\n onClear={closePollModal}\n onSend={handlePollSend}\n />\n <PaymentModal\n isOpen={Boolean(isPaymentModalOpen)}\n onClose={closePaymentModal}\n />\n <ReceiptModal\n isOpen={Boolean(isReceiptModalOpen)}\n onClose={clearReceipt}\n />\n {renderedEditedMessage && (\n <DeleteMessageModal\n isOpen={isDeleteModalOpen}\n isSchedule={messageListType === 'scheduled'}\n onClose={closeDeleteModal}\n message={renderedEditedMessage}\n />\n )}\n <MentionMenu\n isOpen={isMentionMenuOpen}\n filter={mentionFilter}\n onClose={closeMentionMenu}\n onInsertUserName={insertMention}\n filteredChatMembers={mentionFilteredMembers}\n usersById={usersById}\n />\n <div id=\"message-compose\">\n <div className=\"svg-appendix\" ref={appendixRef} />\n <ComposerEmbeddedMessage />\n {allowedAttachmentOptions.canAttachEmbedLinks && (\n <WebPagePreview chatId={chatId} threadId={threadId} messageText={!attachments.length ? html : ''} />\n )}\n <div className=\"message-input-wrapper\">\n {IS_MOBILE_SCREEN ? (\n <Button\n className={symbolMenuButtonClassName}\n round\n color=\"translucent\"\n onClick={isSymbolMenuOpen ? closeSymbolMenu : handleSymbolMenuOpen}\n ariaLabel=\"Choose emoji, sticker or GIF\"\n >\n <i className=\"icon-smile\" />\n <i className=\"icon-keyboard\" />\n <Spinner color=\"gray\" />\n </Button>\n ) : (\n <ResponsiveHoverButton\n className={`${isSymbolMenuOpen ? 'activated' : ''}`}\n round\n faded\n color=\"translucent\"\n onActivate={openSymbolMenu}\n ariaLabel=\"Choose emoji, sticker or GIF\"\n >\n <i className=\"icon-smile\" />\n </ResponsiveHoverButton>\n )}\n <MessageInput\n id=\"message-input-text\"\n html={!attachments.length ? html : ''}\n placeholder={\n activeVoiceRecording && window.innerWidth <= SCREEN_WIDTH_TO_HIDE_PLACEHOLDER ? '' : lang('Message')\n }\n shouldSetFocus={isSymbolMenuOpen}\n shouldSupressFocus={IS_MOBILE_SCREEN && isSymbolMenuOpen}\n onUpdate={setHtml}\n onSend={mainButtonState === MainButtonState.Edit\n ? handleEditComplete\n : (shouldSchedule ? openCalendar : handleSend)}\n onSupressedFocus={closeSymbolMenu}\n />\n {withScheduledButton && (\n <Button\n round\n faded\n className=\"scheduled-button\"\n color=\"translucent\"\n onClick={handleAllScheduledClick}\n ariaLabel=\"Open scheduled messages\"\n >\n <i className=\"icon-schedule\" />\n </Button>\n )}\n {botKeyboardMessageId && !activeVoiceRecording && !editingMessage && (\n <ResponsiveHoverButton\n className={`${isBotKeyboardOpen ? 'activated' : ''}`}\n round\n faded\n color=\"translucent\"\n onActivate={openBotKeyboard}\n ariaLabel=\"Open bot command keyboard\"\n >\n <i className=\"icon-bot-command\" />\n </ResponsiveHoverButton>\n )}\n {!activeVoiceRecording && !editingMessage && (\n <ResponsiveHoverButton\n className={`${isAttachMenuOpen ? 'activated' : ''}`}\n round\n faded\n color=\"translucent\"\n onActivate={openAttachMenu}\n ariaLabel=\"Add an attachment\"\n >\n <i className=\"icon-attach\" />\n </ResponsiveHoverButton>\n )}\n {activeVoiceRecording && currentRecordTime && (\n <span className=\"recording-state\">\n {formatVoiceRecordDuration(currentRecordTime - startRecordTimeRef.current!)}\n </span>\n )}\n <EmojiTooltip\n isOpen={isEmojiTooltipOpen}\n onStickerSelect={handleStickerSelect}\n />\n <AttachMenu\n isOpen={isAttachMenuOpen}\n allowedAttachmentOptions={allowedAttachmentOptions}\n onFileSelect={handleFileSelect}\n onPollCreate={openPollModal}\n onClose={closeAttachMenu}\n />\n {botKeyboardMessageId && (\n <BotKeyboardMenu\n messageId={botKeyboardMessageId}\n isOpen={isBotKeyboardOpen}\n onClose={closeBotKeyboard}\n />\n )}\n <SymbolMenu\n isOpen={isSymbolMenuOpen}\n allowedAttachmentOptions={allowedAttachmentOptions}\n onLoad={onSymbolMenuLoadingComplete}\n onClose={closeSymbolMenu}\n onEmojiSelect={insertTextAndUpdateCursor}\n onStickerSelect={handleStickerSelect}\n onGifSelect={handleGifSelect}\n onRemoveSymbol={removeSymbol}\n onSearchOpen={handleSearchOpen}\n />\n </div>\n </div>\n {activeVoiceRecording && (\n <Button\n round\n color=\"danger\"\n className=\"cancel\"\n onClick={stopRecordingVoice}\n ariaLabel=\"Cancel voice recording\"\n >\n <i className=\"icon-delete\" />\n </Button>\n )}\n <Button\n ref={mainButtonRef}\n round\n color=\"secondary\"\n className={`${mainButtonState} ${activeVoiceRecording ? 'recording' : ''}`}\n disabled={areVoiceMessagesNotAllowed}\n ariaLabel={sendButtonAriaLabel}\n onClick={mainButtonHandler}\n onContextMenu={\n mainButtonState === MainButtonState.Send && canShowCustomSendMenu ? handleContextMenu : undefined\n }\n >\n <i className=\"icon-send\" />\n <i className=\"icon-microphone-alt\" />\n <i className=\"icon-check\" />\n </Button>\n {canShowCustomSendMenu && (\n <CustomSendMenu\n isOpen={isCustomSendMenuOpen}\n onSilentSend={!isChatWithSelf ? handleSilentSend : undefined}\n onScheduleSend={!shouldSchedule ? openCalendar : undefined}\n onClose={handleContextMenuClose}\n onCloseAnimationEnd={handleContextMenuHide}\n />\n )}\n <CalendarModal\n isOpen={isCalendarOpen}\n withTimePicker\n selectedAt={scheduledDefaultDate.getTime()}\n maxAt={getDayStartAt(scheduledMaxDate)}\n isFutureMode\n secondButtonLabel={canScheduleUntilOnline ? 'Send When Online' : undefined}\n onClose={handleCloseCalendar}\n onSubmit={handleMessageSchedule}\n onSecondButtonClick={canScheduleUntilOnline ? handleMessageScheduleUntilOnline : undefined}\n />\n </div>\n );\n};\n\nexport default memo(withGlobal<OwnProps>(\n (global, { chatId, threadId, messageListType }): StateProps => {\n const chat = selectChat(global, chatId);\n const chatUser = chat && selectChatUser(global, chat);\n const isChatWithBot = chat ? selectIsChatWithBot(global, chat) : undefined;\n const isChatWithSelf = selectIsChatWithSelf(global, chatId);\n const messageWithActualBotKeyboard = isChatWithBot && selectNewestMessageWithBotKeyboardButtons(global, chatId);\n const scheduledIds = selectScheduledIds(global, chatId);\n\n return {\n editingMessage: selectEditingMessage(global, chatId, threadId, messageListType),\n connectionState: global.connectionState,\n draft: selectDraft(global, chatId, threadId),\n chat,\n isChatWithBot,\n isChatWithSelf,\n canScheduleUntilOnline: (\n !isChatWithSelf && !isChatWithBot\n && (chat && chatUser && isChatPrivate(chatId) && chatUser.status && Boolean(chatUser.status.wasOnline))\n ),\n isRightColumnShown: selectIsRightColumnShown(global),\n isSelectModeActive: selectIsInSelectMode(global),\n withScheduledButton: (\n threadId === MAIN_THREAD_ID\n && messageListType === 'thread'\n && Boolean(scheduledIds && scheduledIds.length)\n ),\n shouldSchedule: messageListType === 'scheduled',\n botKeyboardMessageId: messageWithActualBotKeyboard ? messageWithActualBotKeyboard.id : undefined,\n isForwarding: chatId === global.forwardMessages.toChatId,\n canSuggestMembers: chat && isChatGroup(chat),\n isPollModalOpen: global.isPollModalOpen,\n stickersForEmoji: global.stickers.forEmoji.stickers,\n groupChatMembers: chat && chat.fullInfo && chat.fullInfo.members,\n currentUserId: global.currentUserId,\n usersById: global.users.byId,\n lastSyncTime: global.lastSyncTime,\n contentToBeScheduled: global.messages.contentToBeScheduled,\n isPaymentModalOpen: global.payment.isPaymentModalOpen,\n isReceiptModalOpen: Boolean(global.payment.receipt),\n shouldSuggestStickers: global.settings.byKey.shouldSuggestStickers,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'sendMessage',\n 'editMessage',\n 'saveDraft',\n 'clearDraft',\n 'showError',\n 'setStickerSearchQuery',\n 'setGifSearchQuery',\n 'forwardMessages',\n 'openPollModal',\n 'closePollModal',\n 'closePaymentModal',\n 'clearReceipt',\n 'loadScheduledHistory',\n 'openChat',\n ]),\n)(Composer));\n","import {\n useCallback, useEffect, useRef, useState,\n} from '../../../../lib/teact/teact';\n\nimport { IS_IOS } from '../../../../util/environment';\nimport * as voiceRecording from '../../../../util/voiceRecording';\nimport captureEscKeyListener from '../../../../util/captureEscKeyListener';\n\ntype ActiveVoiceRecording = { stop: () => Promise<voiceRecording.Result>; pause: NoneToVoidFunction } | undefined;\n\nexport default () => {\n // eslint-disable-next-line no-null/no-null\n const recordButtonRef = useRef<HTMLButtonElement>(null);\n const [activeVoiceRecording, setActiveVoiceRecording] = useState<ActiveVoiceRecording>();\n const startRecordTimeRef = useRef<number>();\n const [currentRecordTime, setCurrentRecordTime] = useState<number | undefined>();\n\n useEffect(() => {\n // Preloading worker fixes silent first record on iOS\n if (IS_IOS) {\n void voiceRecording.init();\n }\n }, []);\n\n const startRecordingVoice = useCallback(async () => {\n try {\n const { stop, pause } = await voiceRecording.start((tickVolume: number) => {\n if (recordButtonRef.current) {\n if (startRecordTimeRef.current && Date.now() % 4 === 0) {\n recordButtonRef.current.style.boxShadow = `0 0 0 ${(tickVolume || 0) * 50}px rgba(0,0,0,.15)`;\n }\n setCurrentRecordTime(Date.now());\n }\n });\n startRecordTimeRef.current = Date.now();\n setCurrentRecordTime(Date.now());\n\n setActiveVoiceRecording({ stop, pause });\n } catch (err) {\n // eslint-disable-next-line no-console\n console.error(err);\n }\n }, []);\n\n const pauseRecordingVoice = useCallback(() => {\n if (!activeVoiceRecording) {\n return undefined;\n }\n\n if (recordButtonRef.current) {\n recordButtonRef.current.style.boxShadow = 'none';\n }\n\n try {\n return activeVoiceRecording!.pause();\n } catch (err) {\n // eslint-disable-next-line no-console\n console.error(err);\n return undefined;\n }\n }, [activeVoiceRecording]);\n\n const stopRecordingVoice = useCallback(() => {\n if (!activeVoiceRecording) {\n return undefined;\n }\n\n setActiveVoiceRecording(undefined);\n startRecordTimeRef.current = undefined;\n setCurrentRecordTime(undefined);\n if (recordButtonRef.current) {\n recordButtonRef.current.style.boxShadow = 'none';\n }\n try {\n return activeVoiceRecording!.stop();\n } catch (err) {\n // eslint-disable-next-line no-console\n console.error(err);\n return undefined;\n }\n }, [activeVoiceRecording]);\n\n useEffect(() => {\n return activeVoiceRecording ? captureEscKeyListener(stopRecordingVoice) : undefined;\n }, [activeVoiceRecording, stopRecordingVoice]);\n\n return {\n startRecordingVoice,\n pauseRecordingVoice,\n stopRecordingVoice,\n activeVoiceRecording,\n currentRecordTime,\n recordButtonRef,\n startRecordTimeRef,\n };\n};\n","import { useEffect } from '../../../../lib/teact/teact';\nimport { getDispatch } from '../../../../lib/teact/teactn';\n\nimport { ApiSticker } from '../../../../api/types';\n\nimport { IS_EMOJI_SUPPORTED } from '../../../../util/environment';\n\nimport parseEmojiOnlyString from '../../../common/helpers/parseEmojiOnlyString';\n\nexport default function useEmojiTooltip(\n isAllowed: boolean,\n html: string,\n stickers?: ApiSticker[],\n) {\n const { loadStickersForEmoji, clearStickersForEmoji } = getDispatch();\n const isSingleEmoji = (\n (IS_EMOJI_SUPPORTED && parseEmojiOnlyString(html) === 1)\n || (!IS_EMOJI_SUPPORTED && Boolean(html.match(/^<img.[^>]*?>$/g)))\n );\n const hasStickers = Boolean(stickers) && isSingleEmoji;\n\n useEffect(() => {\n if (isAllowed && isSingleEmoji) {\n loadStickersForEmoji({ emoji: html });\n } else if (hasStickers || !isSingleEmoji) {\n clearStickersForEmoji();\n }\n // We omit `hasStickers` here to prevent re-fetching after manually closing tooltip (via <Esc>).\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [html, isSingleEmoji, clearStickersForEmoji, loadStickersForEmoji, isAllowed]);\n\n return {\n isEmojiTooltipOpen: hasStickers,\n closeEmojiTooltip: clearStickersForEmoji,\n };\n}\n","export default function insertHtmlInSelection(html: string) {\n const selection = window.getSelection();\n\n if (selection && selection.getRangeAt && selection.rangeCount) {\n const range = selection.getRangeAt(0);\n range.deleteContents();\n\n const fragment = range.createContextualFragment(html);\n const lastInsertedNode = fragment.lastChild;\n range.insertNode(fragment);\n if (lastInsertedNode) {\n range.setStartAfter(lastInsertedNode);\n range.setEndAfter(lastInsertedNode);\n selection.removeAllRanges();\n selection.addRange(range);\n }\n }\n}\n","export default function deleteLastCharacterOutsideSelection(html: string) {\n const tempInput = document.createElement('div');\n tempInput.contentEditable = 'true';\n tempInput.style.position = 'absolute';\n tempInput.style.left = '-10000px';\n tempInput.style.top = '-10000px';\n tempInput.innerHTML = html;\n document.body.appendChild(tempInput);\n let element = tempInput.lastChild!;\n\n if (element.lastChild) {\n // Selects the last and the deepest child of the element.\n while (element.lastChild) {\n element = element.lastChild;\n }\n }\n\n // Gets length of the element's content.\n const textLength = element.textContent!.length;\n const range = document.createRange();\n const selection = window.getSelection()!;\n\n // Sets selection position to the end of the element.\n range.setStart(element, textLength);\n range.setEnd(element, textLength);\n selection.removeAllRanges();\n selection.addRange(range);\n document.execCommand('delete', false);\n\n const result = tempInput.innerHTML;\n document.body.removeChild(tempInput);\n\n return result;\n}\n","import { useCallback, useEffect } from '../../../../lib/teact/teact';\n\nimport { ApiMessage } from '../../../../api/types';\nimport { GlobalActions } from '../../../../global/types';\n\nimport { EDITABLE_INPUT_ID } from '../../../../config';\nimport parseMessageInput from '../helpers/parseMessageInput';\nimport getMessageTextAsHtml from '../helpers/getMessageTextAsHtml';\nimport focusEditableElement from '../../../../util/focusEditableElement';\nimport { hasMessageMedia } from '../../../../modules/helpers';\n\nexport default (\n htmlRef: { current: string },\n setHtml: (html: string) => void,\n editedMessage: ApiMessage | undefined,\n resetComposer: () => void,\n openDeleteModal: () => void,\n editMessage: GlobalActions['editMessage'],\n) => {\n // TODO useOnChange\n // Handle editing message\n useEffect(() => {\n if (!editedMessage) {\n setHtml('');\n return;\n }\n\n setHtml(getMessageTextAsHtml(editedMessage.content.text));\n\n requestAnimationFrame(() => {\n const messageInput = document.getElementById(EDITABLE_INPUT_ID)!;\n focusEditableElement(messageInput, true);\n });\n }, [editedMessage, setHtml]);\n\n const handleEditComplete = useCallback(() => {\n const { text, entities } = parseMessageInput(htmlRef.current!);\n\n if (!editedMessage) {\n return;\n }\n\n if (!text && !hasMessageMedia(editedMessage)) {\n openDeleteModal();\n return;\n }\n\n editMessage({\n messageId: editedMessage.id,\n text,\n entities,\n });\n\n resetComposer();\n }, [editMessage, editedMessage, htmlRef, openDeleteModal, resetComposer]);\n\n return handleEditComplete;\n};\n","import React, { FC } from '../../lib/teact/teact';\nimport { OwnProps } from './MobileSearch';\nimport { Bundles } from '../../util/moduleLoader';\n\nimport useModuleLoader from '../../hooks/useModuleLoader';\n\nconst MobileSearchAsync: FC<OwnProps> = (props) => {\n const { isActive } = props;\n const MobileSearch = useModuleLoader(Bundles.Extra, 'MobileSearch', !isActive, true);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return MobileSearch ? <MobileSearch {...props} /> : undefined;\n};\n\nexport default MobileSearchAsync;\n","import React, { FC } from '../../lib/teact/teact';\nimport { Bundles } from '../../util/moduleLoader';\nimport { OwnProps } from './MessageSelectToolbar';\n\nimport useModuleLoader from '../../hooks/useModuleLoader';\n\nconst MessageSelectToolbarAsync: FC<OwnProps> = (props) => {\n const { isActive } = props;\n const MessageSelectToolbar = useModuleLoader(Bundles.Extra, 'MessageSelectToolbar', !isActive);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return MessageSelectToolbar ? <MessageSelectToolbar {...props} /> : undefined;\n};\n\nexport default MessageSelectToolbarAsync;\n","import React, { FC } from '../../lib/teact/teact';\nimport { OwnProps } from './UnpinAllMessagesModal';\nimport { Bundles } from '../../util/moduleLoader';\n\nimport useModuleLoader from '../../hooks/useModuleLoader';\n\nconst UnpinAllMessagesModalAsync: FC<OwnProps> = (props) => {\n const { isOpen } = props;\n const UnpinAllMessagesModal = useModuleLoader(Bundles.Extra, 'UnpinAllMessagesModal', !isOpen);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return UnpinAllMessagesModal ? <UnpinAllMessagesModal {...props} /> : undefined;\n};\n\nexport default UnpinAllMessagesModalAsync;\n","import React, {\n FC, useEffect, useState, memo, useMemo, useCallback,\n} from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { MAIN_THREAD_ID } from '../../api/types';\nimport { GlobalActions, MessageListType } from '../../global/types';\n\nimport {\n MIN_SCREEN_WIDTH_FOR_STATIC_LEFT_COLUMN,\n MOBILE_SCREEN_MAX_WIDTH,\n MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN,\n SAFE_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN,\n SAFE_SCREEN_WIDTH_FOR_CHAT_INFO,\n CONTENT_TYPES_FOR_QUICK_UPLOAD,\n ANIMATION_LEVEL_MAX,\n ANIMATION_END_DELAY,\n} from '../../config';\nimport { IS_MOBILE_SCREEN, IS_TOUCH_ENV, MASK_IMAGE_ENABLED } from '../../util/environment';\nimport { DropAreaState } from './composer/DropArea';\nimport {\n selectChat,\n selectCurrentMessageList,\n selectCurrentTextSearch,\n selectIsChatBotNotStarted,\n selectIsInSelectMode,\n selectIsRightColumnShown,\n selectPinnedIds,\n} from '../../modules/selectors';\nimport { getCanPostInChat, getMessageSendingRestrictionReason, isChatPrivate } from '../../modules/helpers';\nimport captureEscKeyListener from '../../util/captureEscKeyListener';\nimport { pick } from '../../util/iteratees';\nimport buildClassName from '../../util/buildClassName';\nimport useCustomBackground from '../../hooks/useCustomBackground';\nimport useWindowSize from '../../hooks/useWindowSize';\nimport usePrevForAnimation from '../../hooks/usePrevForAnimation';\nimport calculateMiddleFooterTransforms from './helpers/calculateMiddleFooterTransforms';\nimport useLang from '../../hooks/useLang';\n\nimport Transition from '../ui/Transition';\nimport MiddleHeader from './MiddleHeader';\nimport MessageList from './MessageList';\nimport ScrollDownButton from './ScrollDownButton';\nimport Composer from './composer/Composer';\nimport Button from '../ui/Button';\nimport MobileSearch from './MobileSearch.async';\nimport MessageSelectToolbar from './MessageSelectToolbar.async';\nimport UnpinAllMessagesModal from '../common/UnpinAllMessagesModal.async';\n\nimport './MiddleColumn.scss';\n\ntype StateProps = {\n chatId?: number;\n threadId?: number;\n messageListType?: MessageListType;\n isPrivate?: boolean;\n isPinnedMessageList?: boolean;\n canPost?: boolean;\n messageSendingRestrictionReason?: string;\n hasPinnedOrAudioMessage?: boolean;\n customBackground?: string;\n patternColor?: string;\n isCustomBackgroundColor?: boolean;\n isRightColumnShown?: boolean;\n isBackgroundBlurred?: boolean;\n isMobileSearchActive?: boolean;\n isSelectModeActive?: boolean;\n animationLevel?: number;\n};\n\ntype DispatchProps = Pick<GlobalActions, 'openChat' | 'unpinAllMessages' | 'loadUser'>;\n\nconst CLOSE_ANIMATION_DURATION = IS_MOBILE_SCREEN ? 450 + ANIMATION_END_DELAY : undefined;\n\nfunction canBeQuicklyUploaded(item: DataTransferItem) {\n return item.kind === 'file' && item.type && CONTENT_TYPES_FOR_QUICK_UPLOAD.includes(item.type);\n}\n\nconst MiddleColumn: FC<StateProps & DispatchProps> = ({\n chatId,\n threadId,\n messageListType,\n isPrivate,\n isPinnedMessageList,\n canPost,\n messageSendingRestrictionReason,\n hasPinnedOrAudioMessage,\n customBackground,\n patternColor,\n isCustomBackgroundColor,\n isRightColumnShown,\n isBackgroundBlurred,\n isMobileSearchActive,\n isSelectModeActive,\n animationLevel,\n openChat,\n unpinAllMessages,\n loadUser,\n}) => {\n const { width: windowWidth } = useWindowSize();\n\n const [dropAreaState, setDropAreaState] = useState(DropAreaState.None);\n const [isFabShown, setIsFabShown] = useState(false);\n const [isUnpinModalOpen, setIsUnpinModalOpen] = useState(false);\n\n const renderingChatId = usePrevForAnimation(chatId, CLOSE_ANIMATION_DURATION);\n const renderingThreadId = usePrevForAnimation(threadId, CLOSE_ANIMATION_DURATION);\n const renderingMessageListType = usePrevForAnimation(messageListType, CLOSE_ANIMATION_DURATION);\n const renderingCanPost = usePrevForAnimation(canPost, CLOSE_ANIMATION_DURATION);\n\n useEffect(() => {\n return chatId\n ? captureEscKeyListener(() => {\n openChat({ id: undefined });\n })\n : undefined;\n }, [chatId, openChat]);\n\n useEffect(() => {\n setDropAreaState(DropAreaState.None);\n }, [chatId]);\n\n useEffect(() => {\n if (isPrivate) {\n loadUser({ userId: chatId });\n }\n }, [chatId, isPrivate, loadUser]);\n\n const handleDragEnter = useCallback((e: React.DragEvent<HTMLDivElement>) => {\n if (IS_TOUCH_ENV) {\n return;\n }\n\n const { items } = e.dataTransfer || {};\n const shouldDrawQuick = items && Array.from(items).every(canBeQuicklyUploaded);\n\n setDropAreaState(shouldDrawQuick ? DropAreaState.QuickFile : DropAreaState.Document);\n }, []);\n\n const handleHideDropArea = useCallback(() => {\n setDropAreaState(DropAreaState.None);\n }, []);\n\n const handleOpenUnpinModal = useCallback(() => {\n setIsUnpinModalOpen(true);\n }, []);\n\n const closeUnpinModal = useCallback(() => {\n setIsUnpinModalOpen(false);\n }, []);\n\n const handleUnpinAllMessages = useCallback(() => {\n unpinAllMessages({ chatId });\n closeUnpinModal();\n openChat({ id: chatId });\n }, [unpinAllMessages, openChat, closeUnpinModal, chatId]);\n\n const customBackgroundValue = useCustomBackground(customBackground);\n\n const hasTools = hasPinnedOrAudioMessage && (\n windowWidth < MOBILE_SCREEN_MAX_WIDTH\n || (\n isRightColumnShown && windowWidth > MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN\n && windowWidth < SAFE_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN\n ) || (\n windowWidth >= MIN_SCREEN_WIDTH_FOR_STATIC_LEFT_COLUMN\n && windowWidth < SAFE_SCREEN_WIDTH_FOR_CHAT_INFO\n )\n );\n\n const className = buildClassName(\n hasTools && 'has-header-tools',\n customBackground && !isCustomBackgroundColor && 'custom-bg-image',\n customBackground && isCustomBackgroundColor && 'custom-bg-color',\n customBackground && isBackgroundBlurred && 'blurred',\n MASK_IMAGE_ENABLED ? 'mask-image-enabled' : 'mask-image-disabled',\n );\n\n const messagingDisabledClassName = buildClassName(\n 'messaging-disabled',\n !isSelectModeActive && 'shown',\n );\n\n // CSS Variables calculation doesn't work properly with transforms, so we calculate transform values in JS\n const {\n composerHiddenScale, toolbarHiddenScale,\n composerTranslateX, toolbarTranslateX,\n unpinHiddenScale, toolbarForUnpinHiddenScale,\n } = useMemo(\n () => calculateMiddleFooterTransforms(windowWidth, renderingCanPost),\n [renderingCanPost, windowWidth],\n );\n\n const lang = useLang();\n\n return (\n <div\n id=\"MiddleColumn\"\n className={className}\n // @ts-ignore teact-feature\n style={`\n --composer-hidden-scale: ${composerHiddenScale};\n --toolbar-hidden-scale: ${toolbarHiddenScale};\n --unpin-hidden-scale: ${unpinHiddenScale};\n --toolbar-unpin-hidden-scale: ${toolbarForUnpinHiddenScale};\n --composer-translate-x: ${composerTranslateX}px;\n --toolbar-translate-x: ${toolbarTranslateX}px;\n --pattern-color: ${patternColor};\n `}\n >\n <div\n id=\"middle-column-bg\"\n // @ts-ignore\n style={customBackgroundValue ? `--custom-background: ${customBackgroundValue}` : undefined}\n />\n <div id=\"middle-column-portals\" />\n {renderingChatId && renderingThreadId && (\n <>\n <div className=\"messages-layout\" onDragEnter={renderingCanPost ? handleDragEnter : undefined}>\n <MiddleHeader\n chatId={renderingChatId}\n threadId={renderingThreadId}\n messageListType={renderingMessageListType}\n />\n <Transition\n name={animationLevel === ANIMATION_LEVEL_MAX ? 'slide' : 'fade'}\n activeKey={renderingMessageListType === 'thread' && renderingThreadId === MAIN_THREAD_ID ? 1 : 2}\n shouldCleanup\n >\n {() => (\n <>\n <MessageList\n key={`${renderingChatId}-${renderingThreadId}-${renderingMessageListType}`}\n chatId={renderingChatId}\n threadId={renderingThreadId}\n type={renderingMessageListType}\n hasTools={hasTools}\n onFabToggle={setIsFabShown}\n bottomOffset={renderingCanPost ? 'none' : (isPinnedMessageList ? 'big' : 'small')}\n />\n <div className={buildClassName('middle-column-footer', !renderingCanPost && 'no-composer')}>\n {renderingCanPost && (\n <Composer\n chatId={renderingChatId}\n threadId={renderingThreadId}\n messageListType={renderingMessageListType}\n dropAreaState={dropAreaState}\n onDropHide={handleHideDropArea}\n />\n )}\n {isPinnedMessageList && (\n <div className=\"unpin-button-container\">\n <Button\n size=\"tiny\"\n fluid\n color=\"secondary\"\n className=\"unpin-all-button\"\n onClick={handleOpenUnpinModal}\n >\n <i className=\"icon-unpin\" />\n <span>{lang('Chat.PanelHidePinnedMessages')}</span>\n </Button>\n </div>\n )}\n {!isPinnedMessageList && !renderingCanPost && messageSendingRestrictionReason && (\n <div className={messagingDisabledClassName}>\n <div className=\"messaging-disabled-inner\">\n <span>\n {messageSendingRestrictionReason}\n </span>\n </div>\n </div>\n )}\n <MessageSelectToolbar\n messageListType={renderingMessageListType}\n isActive={isSelectModeActive}\n canPost={renderingCanPost}\n />\n </div>\n </>\n )}\n </Transition>\n\n <ScrollDownButton isShown={isFabShown} />\n </div>\n {IS_MOBILE_SCREEN && <MobileSearch isActive={Boolean(isMobileSearchActive)} />}\n </>\n )}\n {chatId && (\n <UnpinAllMessagesModal\n isOpen={isUnpinModalOpen}\n chatId={chatId}\n onClose={closeUnpinModal}\n onUnpin={handleUnpinAllMessages}\n />\n )}\n </div>\n );\n};\n\nexport default memo(withGlobal(\n (global): StateProps => {\n const { isBackgroundBlurred, customBackground, patternColor } = global.settings.byKey;\n\n const isCustomBackgroundColor = Boolean((customBackground || '').match(/^#[a-f\\d]{6,8}$/i));\n const currentMessageList = selectCurrentMessageList(global);\n const { chats: { listIds } } = global;\n if (!currentMessageList || !listIds.active) {\n return {\n customBackground,\n isBackgroundBlurred,\n isCustomBackgroundColor,\n };\n }\n\n const { chatId, threadId, type: messageListType } = currentMessageList;\n const chat = selectChat(global, chatId);\n const pinnedIds = selectPinnedIds(global, chatId);\n const { chatId: audioChatId, messageId: audioMessageId } = global.audioPlayer;\n\n const canPost = chat && getCanPostInChat(chat, threadId);\n const isBotNotStarted = selectIsChatBotNotStarted(global, chatId);\n const isPinnedMessageList = messageListType === 'pinned';\n\n return {\n chatId,\n threadId,\n messageListType,\n isPrivate: isChatPrivate(chatId),\n canPost: !isPinnedMessageList && (!chat || canPost) && (!isBotNotStarted || IS_MOBILE_SCREEN),\n isPinnedMessageList,\n messageSendingRestrictionReason: chat && getMessageSendingRestrictionReason(chat),\n hasPinnedOrAudioMessage: Boolean(pinnedIds && pinnedIds.length) || Boolean(audioChatId && audioMessageId),\n customBackground,\n patternColor,\n isCustomBackgroundColor,\n isRightColumnShown: selectIsRightColumnShown(global),\n isBackgroundBlurred,\n isMobileSearchActive: Boolean(IS_MOBILE_SCREEN && selectCurrentTextSearch(global)),\n isSelectModeActive: selectIsInSelectMode(global),\n animationLevel: global.settings.byKey.animationLevel,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'openChat', 'unpinAllMessages', 'loadUser',\n ]),\n)(MiddleColumn));\n","import { CUSTOM_BG_CACHE_NAME } from '../config';\nimport * as cacheApi from '../util/cacheApi';\nimport { useEffect, useState } from '../lib/teact/teact';\n\nexport default (settingValue?: string) => {\n const [value, setValue] = useState(settingValue);\n\n useEffect(() => {\n if (!settingValue) {\n return;\n }\n\n if (settingValue.startsWith('#')) {\n setValue(settingValue);\n } else {\n cacheApi.fetch(CUSTOM_BG_CACHE_NAME, CUSTOM_BG_CACHE_NAME, cacheApi.Type.Blob)\n .then((blob) => {\n setValue(`url(${URL.createObjectURL(blob)}`);\n });\n }\n }, [settingValue]);\n\n return value;\n};\n","import React, {\n FC, memo, useCallback, useEffect, useRef, useState,\n} from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../global/types';\nimport { ManagementScreens, ProfileState } from '../../types';\n\nimport { IS_MOBILE_SCREEN } from '../../util/environment';\nimport { debounce } from '../../util/schedulers';\nimport { pick } from '../../util/iteratees';\nimport buildClassName from '../../util/buildClassName';\nimport {\n selectChat,\n selectCurrentGifSearch,\n selectCurrentStickerSearch,\n selectCurrentTextSearch,\n selectIsChatWithSelf,\n} from '../../modules/selectors';\nimport { isChatAdmin, isChatChannel, isChatPrivate } from '../../modules/helpers';\nimport useCurrentOrPrev from '../../hooks/useCurrentOrPrev';\nimport useFlag from '../../hooks/useFlag';\nimport useLang from '../../hooks/useLang';\n\nimport CalendarModal from '../common/CalendarModal.async';\nimport SearchInput from '../ui/SearchInput';\nimport Button from '../ui/Button';\nimport Transition from '../ui/Transition';\nimport './RightHeader.scss';\n\ntype OwnProps = {\n chatId?: number;\n isColumnOpen?: boolean;\n isProfile?: boolean;\n isSearch?: boolean;\n isManagement?: boolean;\n isStatistics?: boolean;\n isStickerSearch?: boolean;\n isGifSearch?: boolean;\n isPollResults?: boolean;\n profileState?: ProfileState;\n managementScreen?: ManagementScreens;\n onClose: () => void;\n};\n\ntype StateProps = {\n canManage?: boolean;\n isChannel?: boolean;\n messageSearchQuery?: string;\n stickerSearchQuery?: string;\n gifSearchQuery?: string;\n};\n\ntype DispatchProps = Pick<GlobalActions, (\n 'setLocalTextSearchQuery' | 'setStickerSearchQuery' | 'setGifSearchQuery' |\n 'searchTextMessagesLocal' | 'toggleManagement' | 'searchMessagesByDate'\n)>;\n\nconst COLUMN_CLOSE_DELAY_MS = 300;\nconst runDebouncedForSearch = debounce((cb) => cb(), 200, false);\n\nenum HeaderContent {\n Profile,\n MemberList,\n SharedMedia,\n Search,\n Statistics,\n Management,\n ManageInitial,\n ManageChannelSubscribers,\n ManageChatAdministrators,\n ManageChatPrivacyType,\n ManageDiscussion,\n ManageGroupPermissions,\n ManageGroupRemovedUsers,\n ManageGroupUserPermissionsCreate,\n ManageGroupUserPermissions,\n ManageGroupRecentActions,\n ManageGroupAdminRights,\n ManageGroupMembers,\n StickerSearch,\n GifSearch,\n PollResults,\n}\n\nconst RightHeader: FC<OwnProps & StateProps & DispatchProps> = ({\n isColumnOpen,\n isProfile,\n isSearch,\n isManagement,\n isStatistics,\n isStickerSearch,\n isGifSearch,\n isPollResults,\n profileState,\n managementScreen,\n canManage,\n isChannel,\n onClose,\n messageSearchQuery,\n stickerSearchQuery,\n gifSearchQuery,\n setLocalTextSearchQuery,\n setStickerSearchQuery,\n setGifSearchQuery,\n searchTextMessagesLocal,\n toggleManagement,\n searchMessagesByDate,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const backButtonRef = useRef<HTMLDivElement>(null);\n\n const [isCalendarOpen, openCalendar, closeCalendar] = useFlag();\n\n const handleMessageSearchQueryChange = useCallback((query: string) => {\n setLocalTextSearchQuery({ query });\n\n if (query.length) {\n runDebouncedForSearch(searchTextMessagesLocal);\n }\n }, [searchTextMessagesLocal, setLocalTextSearchQuery]);\n\n const handleJumpToDate = useCallback((date: Date) => {\n searchMessagesByDate({ timestamp: date.valueOf() / 1000 });\n closeCalendar();\n }, [closeCalendar, searchMessagesByDate]);\n\n const handleStickerSearchQueryChange = useCallback((query: string) => {\n setStickerSearchQuery({ query });\n }, [setStickerSearchQuery]);\n\n const handleGifSearchQueryChange = useCallback((query: string) => {\n setGifSearchQuery({ query });\n }, [setGifSearchQuery]);\n\n const [shouldSkipTransition, setShouldSkipTransition] = useState(!isColumnOpen);\n\n useEffect(() => {\n setTimeout(() => {\n setShouldSkipTransition(!isColumnOpen);\n }, COLUMN_CLOSE_DELAY_MS);\n }, [isColumnOpen]);\n\n const lang = useLang();\n const contentKey = isProfile ? (\n profileState === ProfileState.Profile ? (\n HeaderContent.Profile\n ) : profileState === ProfileState.SharedMedia ? (\n HeaderContent.SharedMedia\n ) : profileState === ProfileState.MemberList ? (\n HeaderContent.MemberList\n ) : -1 // Never reached\n ) : isSearch ? (\n HeaderContent.Search\n ) : isPollResults ? (\n HeaderContent.PollResults\n ) : isStickerSearch ? (\n HeaderContent.StickerSearch\n ) : isGifSearch ? (\n HeaderContent.GifSearch\n ) : isManagement ? (\n managementScreen === ManagementScreens.Initial ? (\n HeaderContent.ManageInitial\n ) : managementScreen === ManagementScreens.ChatPrivacyType ? (\n HeaderContent.ManageChatPrivacyType\n ) : managementScreen === ManagementScreens.Discussion ? (\n HeaderContent.ManageDiscussion\n ) : managementScreen === ManagementScreens.ChannelSubscribers ? (\n HeaderContent.ManageChannelSubscribers\n ) : managementScreen === ManagementScreens.GroupPermissions ? (\n HeaderContent.ManageGroupPermissions\n ) : managementScreen === ManagementScreens.ChatAdministrators ? (\n HeaderContent.ManageChatAdministrators\n ) : managementScreen === ManagementScreens.GroupRemovedUsers ? (\n HeaderContent.ManageGroupRemovedUsers\n ) : managementScreen === ManagementScreens.GroupUserPermissionsCreate ? (\n HeaderContent.ManageGroupUserPermissionsCreate\n ) : managementScreen === ManagementScreens.GroupUserPermissions ? (\n HeaderContent.ManageGroupUserPermissions\n ) : managementScreen === ManagementScreens.GroupRecentActions ? (\n HeaderContent.ManageGroupRecentActions\n ) : managementScreen === ManagementScreens.ChatAdminRights ? (\n HeaderContent.ManageGroupAdminRights\n ) : managementScreen === ManagementScreens.GroupMembers ? (\n HeaderContent.ManageGroupMembers\n ) : undefined // Never reached\n ) : isStatistics ? (\n HeaderContent.Statistics\n ) : undefined; // When column is closed\n\n const renderingContentKey = useCurrentOrPrev(contentKey, true) ?? -1;\n\n function renderHeaderContent() {\n if (renderingContentKey === -1) {\n return undefined;\n }\n\n switch (renderingContentKey) {\n case HeaderContent.PollResults:\n return <h3>{lang('PollResults')}</h3>;\n case HeaderContent.Search:\n return (\n <>\n <SearchInput\n value={messageSearchQuery}\n onChange={handleMessageSearchQueryChange}\n />\n <Button\n round\n size=\"smaller\"\n color=\"translucent\"\n onClick={openCalendar}\n ariaLabel=\"Search messages by date\"\n >\n <i className=\"icon-calendar\" />\n </Button>\n </>\n );\n case HeaderContent.ManageInitial:\n return <h3>{lang('Edit')}</h3>;\n case HeaderContent.ManageChatPrivacyType:\n return <h3>{lang(isChannel ? 'ChannelTypeHeader' : 'GroupTypeHeader')}</h3>;\n case HeaderContent.ManageDiscussion:\n return <h3>{lang('Discussion')}</h3>;\n case HeaderContent.ManageChatAdministrators:\n return <h3>{lang('ChannelAdministrators')}</h3>;\n case HeaderContent.ManageGroupRecentActions:\n return <h3>{lang('Group.Info.AdminLog')}</h3>;\n case HeaderContent.ManageGroupAdminRights:\n return <h3>{lang('EditAdminRights')}</h3>;\n case HeaderContent.ManageGroupPermissions:\n return <h3>{lang('ChannelPermissions')}</h3>;\n case HeaderContent.ManageGroupRemovedUsers:\n return <h3>{lang('ChannelBlockedUsers')}</h3>;\n case HeaderContent.ManageGroupUserPermissionsCreate:\n return <h3>{lang('ChannelAddException')}</h3>;\n case HeaderContent.ManageGroupUserPermissions:\n return <h3>{lang('UserRestrictions')}</h3>;\n case HeaderContent.StickerSearch:\n return (\n <SearchInput\n value={stickerSearchQuery}\n placeholder=\"Search Stickers\"\n onChange={handleStickerSearchQueryChange}\n />\n );\n case HeaderContent.GifSearch:\n return (\n <SearchInput\n value={gifSearchQuery}\n placeholder={lang('SearchGifsTitle')}\n onChange={handleGifSearchQueryChange}\n />\n );\n case HeaderContent.Statistics:\n return <h3>{lang('Statistics')}</h3>;\n case HeaderContent.SharedMedia:\n return <h3>{lang('SharedMedia')}</h3>;\n case HeaderContent.ManageChannelSubscribers:\n return <h3>{lang('ChannelSubscribers')}</h3>;\n case HeaderContent.MemberList:\n case HeaderContent.ManageGroupMembers:\n return <h3>{lang('GroupMembers')}</h3>;\n default:\n return (\n <>\n <h3>{lang('Info')}</h3>\n <section className=\"tools\">\n {canManage && (\n <Button\n round\n color=\"translucent\"\n size=\"smaller\"\n ariaLabel={lang('Edit')}\n onClick={toggleManagement}\n >\n <i className=\"icon-edit\" />\n </Button>\n )}\n </section>\n </>\n );\n }\n }\n\n const isBackButton = (\n IS_MOBILE_SCREEN\n || contentKey === HeaderContent.SharedMedia\n || contentKey === HeaderContent.MemberList\n || isManagement\n );\n\n const buttonClassName = buildClassName(\n 'animated-close-icon',\n shouldSkipTransition && 'no-transition',\n );\n\n // Add class in the next AF to synchronize with animation with Transition components\n useEffect(() => {\n backButtonRef.current!.classList.toggle('state-back', isBackButton);\n }, [isBackButton]);\n\n return (\n <div className=\"RightHeader\">\n <Button\n className=\"close-button\"\n round\n color=\"translucent\"\n size=\"smaller\"\n onClick={onClose}\n ariaLabel={isBackButton ? lang('Common.Back') : lang('Common.Close')}\n >\n <div ref={backButtonRef} className={buttonClassName} />\n </Button>\n <Transition\n name={shouldSkipTransition ? 'none' : 'slide-fade'}\n activeKey={renderingContentKey}\n >\n {renderHeaderContent}\n </Transition>\n {!IS_MOBILE_SCREEN && (\n <CalendarModal\n isOpen={isCalendarOpen}\n isPastMode\n submitButtonLabel={lang('JumpToDate')}\n onClose={closeCalendar}\n onSubmit={handleJumpToDate}\n />\n )}\n </div>\n );\n};\n\nexport default memo(withGlobal<OwnProps>(\n (global, { chatId, isProfile, isManagement }): StateProps => {\n const { query: messageSearchQuery } = selectCurrentTextSearch(global) || {};\n const { query: stickerSearchQuery } = selectCurrentStickerSearch(global) || {};\n const { query: gifSearchQuery } = selectCurrentGifSearch(global) || {};\n const chat = chatId ? selectChat(global, chatId) : undefined;\n const isChannel = chat && isChatChannel(chat);\n\n const canManage = Boolean(\n !isManagement\n && isProfile\n && chat\n && !selectIsChatWithSelf(global, chat.id)\n // chat.isCreator is for Basic Groups\n && (isChatPrivate(chat.id) || ((isChatAdmin(chat) || chat.isCreator) && !chat.isNotJoined)),\n );\n\n return {\n canManage,\n isChannel,\n messageSearchQuery,\n stickerSearchQuery,\n gifSearchQuery,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'setLocalTextSearchQuery',\n 'setStickerSearchQuery',\n 'setGifSearchQuery',\n 'searchTextMessagesLocal',\n 'toggleManagement',\n 'searchMessagesByDate',\n ]),\n)(RightHeader));\n","import { useMemo, useRef } from '../../../lib/teact/teact';\n\nimport { ApiChatMember, ApiMessage, ApiUser } from '../../../api/types';\nimport { ProfileTabType, SharedMediaType } from '../../../types';\n\nimport { MESSAGE_SEARCH_SLICE, SHARED_MEDIA_SLICE } from '../../../config';\nimport { getMessageContentIds, getSortedUserIds } from '../../../modules/helpers';\nimport useOnChange from '../../../hooks/useOnChange';\nimport useInfiniteScroll from '../../../hooks/useInfiniteScroll';\n\nexport default function useProfileViewportIds(\n isRightColumnShown: boolean,\n searchMessages: AnyToVoidFunction,\n tabType: ProfileTabType,\n mediaSearchType?: SharedMediaType,\n groupChatMembers?: ApiChatMember[],\n usersById?: Record<number, ApiUser>,\n chatMessages?: Record<number, ApiMessage>,\n foundIds?: number[],\n chatId?: number,\n lastSyncTime?: number,\n) {\n const resultType = tabType === 'members' || !mediaSearchType ? tabType : mediaSearchType;\n\n const memberIds = useMemo(() => {\n if (!groupChatMembers || !usersById) {\n return undefined;\n }\n\n return getSortedUserIds(groupChatMembers.map(({ userId }) => userId), usersById);\n }, [groupChatMembers, usersById]);\n\n const [mediaViewportIds, getMoreMedia, noProfileInfoForMedia] = useInfiniteScrollForSharedMedia(\n 'media', resultType, searchMessages, lastSyncTime, chatMessages, foundIds,\n );\n\n const [documentViewportIds, getMoreDocuments, noProfileInfoForDocuments] = useInfiniteScrollForSharedMedia(\n 'documents', resultType, searchMessages, lastSyncTime, chatMessages, foundIds,\n );\n\n const [linkViewportIds, getMoreLinks, noProfileInfoForLinks] = useInfiniteScrollForSharedMedia(\n 'links', resultType, searchMessages, lastSyncTime, chatMessages, foundIds,\n );\n\n const [audioViewportIds, getMoreAudio, noProfileInfoForAudio] = useInfiniteScrollForSharedMedia(\n 'audio', resultType, searchMessages, lastSyncTime, chatMessages, foundIds,\n );\n\n let viewportIds: number[] | undefined;\n let getMore: AnyToVoidFunction | undefined;\n let noProfileInfo = false;\n\n switch (resultType) {\n case 'members':\n viewportIds = memberIds;\n getMore = undefined;\n break;\n case 'media':\n viewportIds = mediaViewportIds;\n getMore = getMoreMedia;\n noProfileInfo = noProfileInfoForMedia;\n break;\n case 'documents':\n viewportIds = documentViewportIds;\n getMore = getMoreDocuments;\n noProfileInfo = noProfileInfoForDocuments;\n break;\n case 'links':\n viewportIds = linkViewportIds;\n getMore = getMoreLinks;\n noProfileInfo = noProfileInfoForLinks;\n break;\n case 'audio':\n viewportIds = audioViewportIds;\n getMore = getMoreAudio;\n noProfileInfo = noProfileInfoForAudio;\n break;\n }\n\n return [resultType, viewportIds, getMore, noProfileInfo] as const;\n}\n\nfunction useInfiniteScrollForSharedMedia(\n forSharedMediaType: SharedMediaType,\n currentResultType?: ProfileTabType,\n handleLoadMore?: AnyToVoidFunction,\n lastSyncTime?: number,\n chatMessages?: Record<number, ApiMessage>,\n foundIds?: number[],\n) {\n const messageIdsRef = useRef<number[]>();\n\n useOnChange(() => {\n if (currentResultType === forSharedMediaType && chatMessages && foundIds) {\n messageIdsRef.current = getMessageContentIds(\n chatMessages,\n foundIds,\n forSharedMediaType,\n ).reverse();\n }\n }, [chatMessages, foundIds, currentResultType, forSharedMediaType]);\n\n const [viewportIds, getMore] = useInfiniteScroll(\n lastSyncTime ? handleLoadMore : undefined,\n messageIdsRef.current,\n undefined,\n forSharedMediaType === 'media' ? SHARED_MEDIA_SLICE : MESSAGE_SEARCH_SLICE,\n );\n\n const isOnTop = !viewportIds || !messageIdsRef.current || viewportIds[0] === messageIdsRef.current[0];\n\n return [viewportIds, getMore, !isOnTop] as const;\n}\n","import { useCallback, useEffect } from '../../../lib/teact/teact';\n\nimport { ProfileState } from '../../../types';\n\nimport fastSmoothScroll from '../../../util/fastSmoothScroll';\nimport { throttle } from '../../../util/schedulers';\nimport useEffectWithPrevDeps from '../../../hooks/useEffectWithPrevDeps';\n\nconst TRANSITION_DURATION = 300;\nconst PROGRAMMATIC_SCROLL_TIMEOUT_MS = 350;\n\nconst runThrottledForScroll = throttle((cb) => cb(), 250, false);\n\nlet isScrollingProgrammatically = false;\n\nexport default function useProfileState(\n containerRef: { current: HTMLDivElement | null },\n tabType: string,\n profileState: ProfileState,\n onProfileStateChange: (state: ProfileState) => void,\n) {\n // Scroll to tabs if needed\n useEffectWithPrevDeps(([prevTabType]) => {\n if (prevTabType && prevTabType !== tabType) {\n const container = containerRef.current!;\n const tabsEl = container.querySelector<HTMLDivElement>('.TabList')!;\n if (container.scrollTop < tabsEl.offsetTop) {\n onProfileStateChange(tabType === 'members' ? ProfileState.MemberList : ProfileState.SharedMedia);\n isScrollingProgrammatically = true;\n fastSmoothScroll(container, tabsEl, 'start', undefined, undefined, undefined, TRANSITION_DURATION);\n setTimeout(() => {\n isScrollingProgrammatically = false;\n }, PROGRAMMATIC_SCROLL_TIMEOUT_MS);\n }\n }\n }, [tabType, onProfileStateChange]);\n\n // Scroll to top\n useEffectWithPrevDeps(([prevProfileState]) => {\n if (profileState !== ProfileState.Profile || profileState === prevProfileState) {\n return;\n }\n\n const container = containerRef.current;\n if (!container) {\n return;\n }\n\n const tabListEl = container.querySelector<HTMLDivElement>('.TabList');\n if (!tabListEl || tabListEl.offsetTop > container.scrollTop) {\n return;\n }\n\n isScrollingProgrammatically = true;\n fastSmoothScroll(\n container,\n container.firstElementChild as HTMLElement,\n 'start',\n undefined,\n container.offsetHeight * 2,\n );\n\n setTimeout(() => {\n isScrollingProgrammatically = false;\n }, PROGRAMMATIC_SCROLL_TIMEOUT_MS);\n\n onProfileStateChange(profileState);\n }, [profileState]);\n\n const determineProfileState = useCallback(() => {\n const container = containerRef.current;\n if (!container) {\n return;\n }\n\n const tabListEl = container.querySelector<HTMLDivElement>('.TabList');\n if (!tabListEl) {\n return;\n }\n\n let state: ProfileState = ProfileState.Profile;\n if (container.scrollTop >= tabListEl.offsetTop) {\n state = tabType === 'members'\n ? ProfileState.MemberList\n : ProfileState.SharedMedia;\n }\n\n onProfileStateChange(state);\n }, [containerRef, onProfileStateChange, tabType]);\n\n // Determine profile state when switching tabs\n useEffect(() => {\n if (isScrollingProgrammatically) {\n return;\n }\n\n determineProfileState();\n }, [determineProfileState, tabType]);\n\n // Determine profile state when scrolling\n const handleScroll = useCallback(() => {\n if (isScrollingProgrammatically) {\n return;\n }\n\n runThrottledForScroll(determineProfileState);\n }, [determineProfileState]);\n\n return { handleScroll };\n}\n","import React, { FC, useEffect, memo } from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { ApiUser } from '../../api/types';\nimport { GlobalActions, GlobalState } from '../../global/types';\n\nimport { selectUser } from '../../modules/selectors';\nimport { formatPhoneNumberWithCode } from '../../util/phoneNumber';\nimport renderText from '../common/helpers/renderText';\nimport { pick } from '../../util/iteratees';\nimport useLang from '../../hooks/useLang';\n\ntype OwnProps = {\n userId: number;\n forceShowSelf?: boolean;\n};\n\ntype StateProps = {\n user?: ApiUser;\n} & Pick<GlobalState, 'lastSyncTime'>;\n\ntype DispatchProps = Pick<GlobalActions, 'loadFullUser'>;\n\nconst UserExtra: FC<OwnProps & StateProps & DispatchProps> = ({\n lastSyncTime, user, forceShowSelf, loadFullUser,\n}) => {\n const {\n id: userId,\n fullInfo,\n username,\n phoneNumber,\n isSelf,\n } = user || {};\n\n useEffect(() => {\n if (lastSyncTime) {\n loadFullUser({ userId });\n }\n }, [loadFullUser, userId, lastSyncTime]);\n\n const lang = useLang();\n\n if (!user || (isSelf && !forceShowSelf)) {\n return undefined;\n }\n\n const bio = fullInfo && fullInfo.bio;\n const formattedNumber = phoneNumber && formatPhoneNumberWithCode(phoneNumber);\n\n return (\n <div className=\"ChatExtra\">\n {bio && !!bio.length && (\n <div className=\"item\">\n <i className=\"icon-info\" />\n <div>\n <p className=\"title\">{renderText(bio, ['br', 'links', 'emoji'])}</p>\n <p className=\"subtitle\">{lang('UserBio')}</p>\n </div>\n </div>\n )}\n {username && !!username.length && (\n <div className=\"item\">\n <i className=\"icon-mention\" />\n <div>\n <p className=\"title\">{renderText(username)}</p>\n <p className=\"subtitle\">{lang('Username')}</p>\n </div>\n </div>\n )}\n {formattedNumber && !!formattedNumber.length && (\n <div className=\"item\">\n <i className=\"icon-phone\" />\n <div>\n <p className=\"title\">{formattedNumber}</p>\n <p className=\"subtitle\">{lang('Phone')}</p>\n </div>\n </div>\n )}\n </div>\n );\n};\n\nexport default memo(withGlobal<OwnProps>(\n (global, { userId }): StateProps => {\n const { lastSyncTime } = global;\n const user = selectUser(global, userId);\n\n return { lastSyncTime, user };\n },\n (setGlobal, actions): DispatchProps => pick(actions, ['loadFullUser']),\n)(UserExtra));\n","import React, { FC, memo } from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { ApiChat } from '../../api/types';\n\nimport { selectChat } from '../../modules/selectors';\nimport {\n getChatDescription, getChatLink, getHasAdminRight, isChatChannel, isUserRightBanned,\n} from '../../modules/helpers';\nimport renderText from '../common/helpers/renderText';\nimport useLang from '../../hooks/useLang';\n\nimport SafeLink from '../common/SafeLink';\n\ntype OwnProps = {\n chatId: number;\n};\n\ntype StateProps = {\n chat?: ApiChat;\n canInviteUsers?: boolean;\n};\n\nconst ChatExtra: FC<OwnProps & StateProps> = ({ chat, canInviteUsers }) => {\n const lang = useLang();\n\n if (!chat || chat.isRestricted) {\n return undefined;\n }\n\n const description = getChatDescription(chat);\n const link = getChatLink(chat);\n const url = link.indexOf('http') === 0 ? link : `http://${link}`;\n\n return (\n <div className=\"ChatExtra\">\n {description && !!description.length && (\n <div className=\"item\">\n <i className=\"icon-info\" />\n <div>\n <p className=\"title\">{renderText(description, ['br', 'links', 'emoji'])}</p>\n <p className=\"subtitle\">{lang('Info')}</p>\n </div>\n </div>\n )}\n {canInviteUsers && !!link.length && (\n <div className=\"item\">\n <i className=\"icon-mention\" />\n <div>\n <SafeLink url={url} className=\"title\" text={link} />\n <p className=\"subtitle\">{lang('SetUrlPlaceholder')}</p>\n </div>\n </div>\n )}\n </div>\n );\n};\n\nexport default memo(withGlobal<OwnProps>(\n (global, { chatId }): StateProps => {\n const chat = selectChat(global, chatId);\n\n\n const canInviteUsers = chat && (\n (!isChatChannel(chat) && !isUserRightBanned(chat, 'inviteUsers'))\n || getHasAdminRight(chat, 'inviteUsers')\n );\n\n return { chat, canInviteUsers };\n },\n)(ChatExtra));\n","import React, {\n FC, useCallback, useEffect, useMemo, useRef, useState, memo,\n} from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport {\n ApiMessage,\n ApiChatMember,\n ApiUser,\n MAIN_THREAD_ID,\n} from '../../api/types';\nimport { GlobalActions } from '../../global/types';\nimport {\n MediaViewerOrigin, ProfileState, ProfileTabType, SharedMediaType,\n} from '../../types';\n\nimport { SHARED_MEDIA_SLICE, SLIDE_TRANSITION_DURATION } from '../../config';\nimport { IS_TOUCH_ENV } from '../../util/environment';\nimport {\n isChatAdmin, isChatChannel, isChatGroup, isChatPrivate,\n} from '../../modules/helpers';\nimport {\n selectChatMessages,\n selectChat,\n selectCurrentMediaSearch,\n selectIsRightColumnShown,\n} from '../../modules/selectors';\nimport { pick } from '../../util/iteratees';\nimport { captureEvents, SwipeDirection } from '../../util/captureEvents';\nimport useCacheBuster from '../../hooks/useCacheBuster';\nimport useProfileViewportIds from './hooks/useProfileViewportIds';\nimport useProfileState from './hooks/useProfileState';\nimport useTransitionFixes from './hooks/useTransitionFixes';\nimport useAsyncRendering from './hooks/useAsyncRendering';\n\nimport Transition from '../ui/Transition';\nimport InfiniteScroll from '../ui/InfiniteScroll';\nimport TabList from '../ui/TabList';\nimport Spinner from '../ui/Spinner';\nimport ListItem from '../ui/ListItem';\nimport PrivateChatInfo from '../common/PrivateChatInfo';\nimport GroupChatInfo from '../common/GroupChatInfo';\nimport Document from '../common/Document';\nimport Audio from '../common/Audio';\nimport UserExtra from './UserExtra';\nimport GroupExtra from './ChatExtra';\nimport Media from '../common/Media';\nimport WebLink from '../common/WebLink';\nimport NothingFound from '../common/NothingFound';\n\nimport './Profile.scss';\n\ntype OwnProps = {\n chatId: number;\n userId?: number;\n profileState: ProfileState;\n onProfileStateChange: (state: ProfileState) => void;\n};\n\ntype StateProps = {\n isChannel?: boolean;\n resolvedUserId?: number;\n chatMessages?: Record<number, ApiMessage>;\n foundIds?: number[];\n mediaSearchType?: SharedMediaType;\n hasMembersTab?: boolean;\n areMembersHidden?: boolean;\n members?: ApiChatMember[];\n usersById?: Record<number, ApiUser>;\n isRightColumnShown: boolean;\n isRestricted?: boolean;\n lastSyncTime?: number;\n};\n\ntype DispatchProps = Pick<GlobalActions, (\n 'setLocalMediaSearchType' | 'searchMediaMessagesLocal' | 'openMediaViewer' |\n 'openAudioPlayer' | 'openUserInfo' | 'focusMessage'\n)>;\n\nconst TABS = [\n { type: 'media', title: 'SharedMediaTab2' },\n { type: 'documents', title: 'SharedFilesTab2' },\n { type: 'links', title: 'SharedLinksTab2' },\n { type: 'audio', title: 'SharedMusicTab2' },\n];\n\nconst HIDDEN_RENDER_DELAY = 1000;\n\nconst Profile: FC<OwnProps & StateProps & DispatchProps> = ({\n chatId,\n profileState,\n onProfileStateChange,\n isChannel,\n resolvedUserId,\n chatMessages,\n foundIds,\n mediaSearchType,\n hasMembersTab,\n areMembersHidden,\n members,\n usersById,\n isRightColumnShown,\n isRestricted,\n lastSyncTime,\n setLocalMediaSearchType,\n searchMediaMessagesLocal,\n openMediaViewer,\n openAudioPlayer,\n openUserInfo,\n focusMessage,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const containerRef = useRef<HTMLDivElement>(null);\n // eslint-disable-next-line no-null/no-null\n const transitionRef = useRef<HTMLDivElement>(null);\n\n const [activeTab, setActiveTab] = useState(0);\n\n const tabs = useMemo(() => ([\n ...(hasMembersTab ? [{\n type: 'members', title: isChannel ? 'ChannelSubscribers' : 'GroupMembers',\n }] : []),\n ...TABS,\n ]), [hasMembersTab, isChannel]);\n const tabType = tabs[activeTab].type as ProfileTabType;\n\n const [resultType, viewportIds, getMore, noProfileInfo] = useProfileViewportIds(\n isRightColumnShown, searchMediaMessagesLocal, tabType, mediaSearchType, members,\n usersById, chatMessages, foundIds, chatId, lastSyncTime,\n );\n const activeKey = tabs.findIndex(({ type }) => type === resultType);\n\n const { handleScroll } = useProfileState(containerRef, tabType, profileState, onProfileStateChange);\n\n const { applyTransitionFix, releaseTransitionFix } = useTransitionFixes(containerRef);\n\n const [cacheBuster, resetCacheBuster] = useCacheBuster();\n\n const handleTransitionStop = useCallback(() => {\n releaseTransitionFix();\n resetCacheBuster();\n }, [releaseTransitionFix, resetCacheBuster]);\n\n // Update search type when switching tabs\n useEffect(() => {\n setLocalMediaSearchType({ mediaType: tabType });\n }, [setLocalMediaSearchType, tabType]);\n\n const profileId = resolvedUserId || chatId;\n\n const handleSelectMedia = useCallback((messageId: number) => {\n openMediaViewer({\n chatId: profileId,\n threadId: MAIN_THREAD_ID,\n messageId,\n origin: MediaViewerOrigin.SharedMedia,\n });\n }, [profileId, openMediaViewer]);\n\n const handlePlayAudio = useCallback((messageId: number) => {\n openAudioPlayer({ chatId: profileId, messageId });\n }, [profileId, openAudioPlayer]);\n\n const handleMemberClick = useCallback((id: number) => {\n openUserInfo({ id });\n }, [openUserInfo]);\n\n const handleMessageFocus = useCallback((messageId: number) => {\n focusMessage({ chatId: profileId, messageId });\n }, [profileId, focusMessage]);\n\n useEffect(() => {\n if (!transitionRef.current || !IS_TOUCH_ENV) {\n return undefined;\n }\n\n return captureEvents(transitionRef.current, {\n onSwipe: ((e, direction) => {\n if (direction === SwipeDirection.Left) {\n setActiveTab(Math.min(activeTab + 1, tabs.length - 1));\n } else if (direction === SwipeDirection.Right) {\n setActiveTab(Math.max(0, activeTab - 1));\n }\n }),\n });\n }, [activeTab, tabs.length]);\n\n let renderingDelay;\n const isFirstTab = resultType === 'members' || (!hasMembersTab && resultType === 'media');\n // @optimization Used to unparallelize rendering of message list and profile media\n if (isFirstTab) {\n renderingDelay = !isRightColumnShown ? HIDDEN_RENDER_DELAY : 0;\n // @optimization Used to delay first render of secondary tabs while animating\n } else if (!viewportIds) {\n renderingDelay = SLIDE_TRANSITION_DURATION;\n }\n const canRenderContents = useAsyncRendering([chatId, resultType], renderingDelay);\n\n function renderSharedMedia() {\n if (!viewportIds || !canRenderContents || !chatMessages) {\n // This is just a single-frame delay so we do not show spinner\n const noSpinner = isFirstTab && viewportIds && !canRenderContents;\n\n return (\n <div className=\"content empty-list\">\n {!noSpinner && <Spinner />}\n </div>\n );\n }\n\n if (!viewportIds.length) {\n let text: string;\n\n switch (resultType) {\n case 'members':\n text = areMembersHidden ? 'You have no access to group members list.' : 'No members found';\n break;\n case 'documents':\n text = 'No documents found.';\n break;\n case 'links':\n text = 'No links found.';\n break;\n case 'audio':\n text = 'No audio found.';\n break;\n default:\n text = 'No media found.';\n }\n\n return (\n <div className=\"content empty-list\">\n <NothingFound text={text} />\n </div>\n );\n }\n\n return (\n <div className={`content ${resultType}-list`} teactFastList>\n {resultType === 'media' ? (\n viewportIds!.map((id) => chatMessages[id] && (\n <Media\n key={id}\n message={chatMessages[id]}\n onClick={handleSelectMedia}\n />\n ))\n ) : resultType === 'documents' ? (\n viewportIds!.map((id) => chatMessages[id] && (\n <Document\n key={id}\n message={chatMessages[id]}\n withDate\n smaller\n className=\"scroll-item\"\n onDateClick={handleMessageFocus}\n />\n ))\n ) : resultType === 'links' ? (\n viewportIds!.map((id) => chatMessages[id] && (\n <WebLink\n key={id}\n message={chatMessages[id]}\n onMessageClick={handleMessageFocus}\n />\n ))\n ) : resultType === 'audio' ? (\n viewportIds!.map((id) => chatMessages[id] && (\n <Audio\n key={id}\n renderingFor=\"sharedMedia\"\n message={chatMessages[id]}\n date={chatMessages[id].date}\n lastSyncTime={lastSyncTime}\n className=\"scroll-item\"\n onPlay={handlePlayAudio}\n onDateClick={handleMessageFocus}\n />\n ))\n ) : resultType === 'members' ? (\n viewportIds!.map((id, i) => (\n <ListItem\n key={id}\n teactOrderKey={i}\n className=\"chat-item-clickable scroll-item\"\n onClick={() => handleMemberClick(id)}\n >\n <PrivateChatInfo userId={id} forceShowSelf />\n </ListItem>\n ))\n ) : undefined}\n </div>\n );\n }\n\n return (\n <InfiniteScroll\n ref={containerRef}\n className=\"Profile custom-scroll\"\n itemSelector={buildInfiniteScrollItemSelector(resultType)}\n items={viewportIds}\n cacheBuster={cacheBuster}\n preloadBackwards={SHARED_MEDIA_SLICE}\n isDisabled={tabType === 'members'}\n noFastList\n onLoadMore={getMore}\n onScroll={handleScroll}\n >\n {!noProfileInfo && renderProfileInfo(chatId, resolvedUserId)}\n {!isRestricted && (\n <div className=\"shared-media\">\n <Transition\n ref={transitionRef}\n name=\"slide\"\n activeKey={activeKey}\n renderCount={tabs.length}\n shouldRestoreHeight\n className=\"shared-media-transition\"\n onStart={applyTransitionFix}\n onStop={handleTransitionStop}\n >\n {renderSharedMedia}\n </Transition>\n <TabList activeTab={activeTab} tabs={tabs} onSwitchTab={setActiveTab} />\n </div>\n )}\n </InfiniteScroll>\n );\n};\n\nfunction renderProfileInfo(chatId: number, resolvedUserId?: number) {\n return (\n <div className=\"profile-info\">\n {resolvedUserId ? (\n <>\n <PrivateChatInfo\n userId={resolvedUserId}\n avatarSize=\"jumbo\"\n forceShowSelf={resolvedUserId !== chatId}\n withMediaViewer\n withFullInfo\n />\n <UserExtra userId={resolvedUserId} forceShowSelf={resolvedUserId !== chatId} />\n </>\n ) : (\n <>\n <GroupChatInfo chatId={chatId} avatarSize=\"jumbo\" withMediaViewer withFullInfo />\n <GroupExtra chatId={chatId} />\n </>\n )}\n </div>\n );\n}\n\nfunction buildInfiniteScrollItemSelector(resultType: string) {\n return [\n // Used on first render\n `.shared-media-transition > div:only-child > .${resultType}-list > .scroll-item`,\n // Used after transition\n `.shared-media-transition > div.active > .${resultType}-list > .scroll-item`,\n ].join(', ');\n}\n\nexport default memo(withGlobal<OwnProps>(\n (global, { chatId, userId }): StateProps => {\n const chat = selectChat(global, chatId);\n\n const chatMessages = selectChatMessages(global, userId || chatId);\n const { currentType: mediaSearchType, resultsByType } = selectCurrentMediaSearch(global) || {};\n const { foundIds } = (resultsByType && mediaSearchType && resultsByType[mediaSearchType]) || {};\n\n const { byId: usersById } = global.users;\n\n const isGroup = chat && isChatGroup(chat);\n const isChannel = chat && isChatChannel(chat);\n const hasMembersTab = isGroup || (isChannel && isChatAdmin(chat!));\n const members = chat && chat.fullInfo && chat.fullInfo.members;\n const areMembersHidden = hasMembersTab && chat && chat.fullInfo && !chat.fullInfo.canViewMembers;\n\n let resolvedUserId;\n if (userId) {\n resolvedUserId = userId;\n } else if (isChatPrivate(chatId)) {\n resolvedUserId = chatId;\n }\n\n return {\n isChannel,\n resolvedUserId,\n chatMessages,\n foundIds,\n mediaSearchType,\n hasMembersTab,\n areMembersHidden,\n ...(hasMembersTab && members && {\n members,\n usersById,\n }),\n isRightColumnShown: selectIsRightColumnShown(global),\n isRestricted: chat && chat.isRestricted,\n lastSyncTime: global.lastSyncTime,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'setLocalMediaSearchType',\n 'searchMediaMessagesLocal',\n 'openMediaViewer',\n 'openAudioPlayer',\n 'openUserInfo',\n 'focusMessage',\n ]),\n)(Profile));\n","import { useCallback, useEffect } from '../../../lib/teact/teact';\n\nexport default function useTransitionFixes(\n containerRef: { current: HTMLDivElement | null },\n) {\n // Set `min-height` for shared media container to prevent jumping when switching tabs\n useEffect(() => {\n function setMinHeight() {\n const container = containerRef.current!;\n const transitionEl = container.querySelector<HTMLDivElement>('.Transition');\n const tabsEl = container.querySelector<HTMLDivElement>('.TabList');\n if (transitionEl && tabsEl) {\n transitionEl.style.minHeight = `${container.offsetHeight - tabsEl.offsetHeight}px`;\n }\n }\n\n setMinHeight();\n\n window.addEventListener('resize', setMinHeight, false);\n\n return () => {\n window.removeEventListener('resize', setMinHeight, false);\n };\n }, [containerRef]);\n\n // Workaround for scrollable content flickering during animation.\n const applyTransitionFix = useCallback(() => {\n const container = containerRef.current!;\n if (container.style.overflowY !== 'hidden') {\n const scrollBarWidth = container.offsetWidth - container.clientWidth;\n container.style.overflowY = 'hidden';\n container.style.marginRight = `${scrollBarWidth}px`;\n }\n }, [containerRef]);\n\n const releaseTransitionFix = useCallback(() => {\n const container = containerRef.current!;\n container.style.overflowY = 'scroll';\n container.style.marginRight = '0';\n }, [containerRef]);\n\n return { applyTransitionFix, releaseTransitionFix };\n}\n","import { useCallback, useState } from '../lib/teact/teact';\n\nexport default () => {\n const [cacheBuster, setCacheBuster] = useState<boolean>(false);\n\n const updateCacheBuster = useCallback(() => {\n setCacheBuster((current) => !current);\n }, []);\n\n return [cacheBuster, updateCacheBuster] as const;\n};\n","import React, { FC } from '../../lib/teact/teact';\nimport { OwnProps } from './RightSearch';\nimport { Bundles } from '../../util/moduleLoader';\n\nimport useModuleLoader from '../../hooks/useModuleLoader';\nimport Loading from '../ui/Loading';\n\nconst RightSearchAsync: FC<OwnProps> = (props) => {\n const RightSearch = useModuleLoader(Bundles.Extra, 'RightSearch');\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return RightSearch ? <RightSearch {...props} /> : <Loading />;\n};\n\nexport default RightSearchAsync;\n","import React, { FC } from '../../../lib/teact/teact';\nimport { Bundles } from '../../../util/moduleLoader';\n\nimport { OwnProps } from './Management';\n\nimport useModuleLoader from '../../../hooks/useModuleLoader';\n\nimport Loading from '../../ui/Loading';\n\nconst ManagementAsync: FC<OwnProps> = (props) => {\n const Management = useModuleLoader(Bundles.Extra, 'Management');\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return Management ? <Management {...props} /> : <Loading />;\n};\n\nexport default ManagementAsync;\n","import React, { FC } from '../../lib/teact/teact';\nimport { Bundles } from '../../util/moduleLoader';\n\nimport useModuleLoader from '../../hooks/useModuleLoader';\nimport Loading from '../ui/Loading';\n\nconst StatisticsAsync: FC = () => {\n const Statistics = useModuleLoader(Bundles.Extra, 'Statistics');\n\n return Statistics ? <Statistics /> : <Loading />;\n};\n\nexport default StatisticsAsync;\n","import React, { FC } from '../../lib/teact/teact';\nimport { Bundles } from '../../util/moduleLoader';\n\nimport useModuleLoader from '../../hooks/useModuleLoader';\nimport Loading from '../ui/Loading';\n\nconst StickerSearchAsync: FC = () => {\n const StickerSearch = useModuleLoader(Bundles.Extra, 'StickerSearch');\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return StickerSearch ? <StickerSearch /> : <Loading />;\n};\n\nexport default StickerSearchAsync;\n","import React, { FC } from '../../lib/teact/teact';\nimport { Bundles } from '../../util/moduleLoader';\n\nimport useModuleLoader from '../../hooks/useModuleLoader';\nimport Loading from '../ui/Loading';\n\nconst GifSearchAsync: FC = () => {\n const GifSearch = useModuleLoader(Bundles.Extra, 'GifSearch');\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return GifSearch ? <GifSearch /> : <Loading />;\n};\n\nexport default GifSearchAsync;\n","import React, { FC } from '../../lib/teact/teact';\nimport { Bundles } from '../../util/moduleLoader';\n\nimport useModuleLoader from '../../hooks/useModuleLoader';\nimport Loading from '../ui/Loading';\n\nconst PollResultsAsync: FC = () => {\n const PollResults = useModuleLoader(Bundles.Extra, 'PollResults');\n\n return PollResults ? <PollResults /> : <Loading />;\n};\n\nexport default PollResultsAsync;\n","import React, {\n FC, memo, useCallback, useEffect, useState,\n} from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../global/types';\nimport { ManagementScreens, ProfileState, RightColumnContent } from '../../types';\n\nimport { MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN } from '../../config';\nimport captureEscKeyListener from '../../util/captureEscKeyListener';\nimport { pick } from '../../util/iteratees';\nimport {\n selectAreActiveChatsLoaded,\n selectCurrentMessageList,\n selectRightColumnContentKey,\n} from '../../modules/selectors';\nimport useLayoutEffectWithPrevDeps from '../../hooks/useLayoutEffectWithPrevDeps';\nimport useWindowSize from '../../hooks/useWindowSize';\nimport useCurrentOrPrev from '../../hooks/useCurrentOrPrev';\n\nimport RightHeader from './RightHeader';\nimport Profile from './Profile';\nimport Transition from '../ui/Transition';\nimport RightSearch from './RightSearch.async';\nimport Management from './management/Management.async';\nimport Statistics from './Statistics.async';\nimport StickerSearch from './StickerSearch.async';\nimport GifSearch from './GifSearch.async';\nimport PollResults from './PollResults.async';\n\nimport './RightColumn.scss';\n\ntype StateProps = {\n contentKey?: RightColumnContent;\n chatId?: number;\n threadId?: number;\n currentProfileUserId?: number;\n isChatSelected: boolean;\n};\n\ntype DispatchProps = Pick<GlobalActions, (\n 'toggleChatInfo' | 'toggleManagement' | 'toggleStatistics' | 'openUserInfo' |\n 'closeLocalTextSearch' | 'closePollResults' |\n 'setStickerSearchQuery' | 'setGifSearchQuery'\n)>;\n\nconst COLUMN_CLOSE_DELAY_MS = 300;\nconst MAIN_SCREENS_COUNT = Object.keys(RightColumnContent).length / 2;\nconst MANAGEMENT_SCREENS_COUNT = Object.keys(ManagementScreens).length / 2;\n\nfunction blurSearchInput() {\n const searchInput = document.querySelector('.RightHeader .SearchInput input') as HTMLInputElement;\n if (searchInput) {\n searchInput.blur();\n }\n}\n\nconst RightColumn: FC<StateProps & DispatchProps> = ({\n contentKey,\n chatId,\n threadId,\n currentProfileUserId,\n isChatSelected,\n toggleChatInfo,\n toggleManagement,\n toggleStatistics,\n openUserInfo,\n closeLocalTextSearch,\n setStickerSearchQuery,\n setGifSearchQuery,\n closePollResults,\n}) => {\n const { width: windowWidth } = useWindowSize();\n const [profileState, setProfileState] = useState<ProfileState>(ProfileState.Profile);\n const [managementScreen, setManagementScreen] = useState<ManagementScreens>(ManagementScreens.Initial);\n const [selectedChatMemberId, setSelectedChatMemberId] = useState<number | undefined>();\n const [isPromotedByCurrentUser, setIsPromotedByCurrentUser] = useState<boolean | undefined>();\n const isScrolledDown = profileState !== ProfileState.Profile;\n\n const isOpen = contentKey !== undefined;\n const isProfile = contentKey === RightColumnContent.ChatInfo || contentKey === RightColumnContent.UserInfo;\n const isSearch = contentKey === RightColumnContent.Search;\n const isManagement = contentKey === RightColumnContent.Management;\n const isStatistics = contentKey === RightColumnContent.Statistics;\n const isStickerSearch = contentKey === RightColumnContent.StickerSearch;\n const isGifSearch = contentKey === RightColumnContent.GifSearch;\n const isPollResults = contentKey === RightColumnContent.PollResults;\n const isOverlaying = windowWidth <= MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN;\n\n const [shouldSkipTransition, setShouldSkipTransition] = useState(!isOpen);\n\n const renderingContentKey = useCurrentOrPrev(contentKey, true, !isChatSelected) ?? -1;\n\n const close = useCallback(() => {\n switch (contentKey) {\n case RightColumnContent.ChatInfo:\n if (isScrolledDown) {\n setProfileState(ProfileState.Profile);\n break;\n }\n toggleChatInfo();\n break;\n case RightColumnContent.UserInfo:\n if (isScrolledDown) {\n setProfileState(ProfileState.Profile);\n break;\n }\n openUserInfo({ id: undefined });\n break;\n case RightColumnContent.Management: {\n switch (managementScreen) {\n case ManagementScreens.Initial:\n toggleManagement();\n break;\n case ManagementScreens.ChatPrivacyType:\n case ManagementScreens.Discussion:\n case ManagementScreens.GroupPermissions:\n case ManagementScreens.GroupType:\n case ManagementScreens.ChatAdministrators:\n case ManagementScreens.ChannelSubscribers:\n case ManagementScreens.GroupMembers:\n setManagementScreen(ManagementScreens.Initial);\n break;\n case ManagementScreens.GroupUserPermissionsCreate:\n case ManagementScreens.GroupRemovedUsers:\n case ManagementScreens.GroupUserPermissions:\n setManagementScreen(ManagementScreens.GroupPermissions);\n setSelectedChatMemberId(undefined);\n setIsPromotedByCurrentUser(undefined);\n break;\n case ManagementScreens.ChatAdminRights:\n case ManagementScreens.GroupRecentActions:\n setManagementScreen(ManagementScreens.ChatAdministrators);\n break;\n }\n\n break;\n }\n case RightColumnContent.Statistics:\n toggleStatistics();\n break;\n case RightColumnContent.Search: {\n blurSearchInput();\n closeLocalTextSearch();\n break;\n }\n case RightColumnContent.StickerSearch:\n case RightColumnContent.GifSearch: {\n blurSearchInput();\n setStickerSearchQuery({ query: undefined });\n setGifSearchQuery({ query: undefined });\n break;\n }\n case RightColumnContent.PollResults:\n closePollResults();\n break;\n }\n }, [\n contentKey, isScrolledDown, toggleChatInfo, openUserInfo, toggleStatistics, closePollResults,\n managementScreen, toggleManagement, closeLocalTextSearch, setStickerSearchQuery, setGifSearchQuery,\n ]);\n\n const handleSelectChatMember = useCallback((memberId, isPromoted) => {\n setSelectedChatMemberId(memberId);\n setIsPromotedByCurrentUser(isPromoted);\n }, []);\n\n useEffect(() => (isOpen ? captureEscKeyListener(close) : undefined), [isOpen, close]);\n\n useEffect(() => {\n setTimeout(() => {\n setShouldSkipTransition(!isOpen);\n }, COLUMN_CLOSE_DELAY_MS);\n }, [isOpen]);\n\n // Close Right Column when it transforms into overlayed state on screen resize\n useEffect(() => {\n if (isOpen && isOverlaying) {\n close();\n }\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [isOverlaying]);\n\n // We need to clear profile state and management screen state, when changing chats\n useLayoutEffectWithPrevDeps(([prevContentKey, prevChatId]) => {\n if (\n (prevContentKey === RightColumnContent.ChatInfo && contentKey === RightColumnContent.UserInfo)\n || (prevContentKey === RightColumnContent.UserInfo && contentKey === RightColumnContent.ChatInfo)\n || (prevChatId !== chatId)\n ) {\n setProfileState(ProfileState.Profile);\n setManagementScreen(ManagementScreens.Initial);\n }\n }, [contentKey, chatId]);\n\n // eslint-disable-next-line consistent-return\n function renderContent() {\n if (renderingContentKey === -1) {\n return undefined;\n }\n\n switch (renderingContentKey) {\n case RightColumnContent.ChatInfo:\n case RightColumnContent.UserInfo:\n return (\n <Profile\n key={currentProfileUserId || chatId!}\n chatId={chatId!}\n userId={currentProfileUserId}\n profileState={profileState}\n onProfileStateChange={setProfileState}\n />\n );\n case RightColumnContent.Search:\n return <RightSearch chatId={chatId!} threadId={threadId!} />;\n case RightColumnContent.Management:\n return (\n <Management\n chatId={chatId!}\n currentScreen={managementScreen}\n isPromotedByCurrentUser={isPromotedByCurrentUser}\n selectedChatMemberId={selectedChatMemberId}\n onScreenSelect={setManagementScreen}\n onChatMemberSelect={handleSelectChatMember}\n />\n );\n case RightColumnContent.Statistics:\n return <Statistics />;\n case RightColumnContent.StickerSearch:\n return <StickerSearch />;\n case RightColumnContent.GifSearch:\n return <GifSearch />;\n case RightColumnContent.PollResults:\n return <PollResults />;\n }\n }\n\n return (\n <div\n id=\"RightColumn-wrapper\"\n className={!isChatSelected ? 'is-hidden' : undefined}\n >\n {isOverlaying && (\n <div className=\"overlay-backdrop\" onClick={close} />\n )}\n <div id=\"RightColumn\">\n <RightHeader\n chatId={chatId}\n isColumnOpen={isOpen}\n isProfile={isProfile}\n isSearch={isSearch}\n isManagement={isManagement}\n isStatistics={isStatistics}\n isStickerSearch={isStickerSearch}\n isGifSearch={isGifSearch}\n isPollResults={isPollResults}\n profileState={profileState}\n managementScreen={managementScreen}\n onClose={close}\n />\n <Transition\n name={shouldSkipTransition ? 'none' : 'zoom-fade'}\n renderCount={MAIN_SCREENS_COUNT + MANAGEMENT_SCREENS_COUNT}\n activeKey={isManagement ? MAIN_SCREENS_COUNT + managementScreen : renderingContentKey}\n >\n {renderContent}\n </Transition>\n </div>\n </div>\n );\n};\n\nexport default memo(withGlobal(\n (global): StateProps => {\n const { chatId, threadId } = selectCurrentMessageList(global) || {};\n const areActiveChatsLoaded = selectAreActiveChatsLoaded(global);\n\n return {\n contentKey: selectRightColumnContentKey(global),\n chatId,\n threadId,\n currentProfileUserId: global.users.selectedId,\n isChatSelected: Boolean(chatId && areActiveChatsLoaded),\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'openUserInfo',\n 'toggleChatInfo',\n 'toggleManagement',\n 'toggleStatistics',\n 'closeLocalTextSearch',\n 'setStickerSearchQuery',\n 'setGifSearchQuery',\n 'closePollResults',\n ]),\n)(RightColumn));\n","import React, { FC, memo } from '../../lib/teact/teact';\n\nimport { Bundles } from '../../util/moduleLoader';\nimport useModuleLoader from '../../hooks/useModuleLoader';\n\ninterface OwnProps {\n isOpen: boolean;\n}\n\nconst MediaViewerAsync: FC<OwnProps> = ({ isOpen }) => {\n const MediaViewer = useModuleLoader(Bundles.Extra, 'MediaViewer', !isOpen);\n\n return MediaViewer ? <MediaViewer /> : undefined;\n};\n\nexport default memo(MediaViewerAsync);\n","import React, { FC } from '../../lib/teact/teact';\nimport { Bundles } from '../../util/moduleLoader';\n\nimport useModuleLoader from '../../hooks/useModuleLoader';\n\nconst NotificationsAsync: FC = ({ isOpen }) => {\n const Notifications = useModuleLoader(Bundles.Extra, 'Notifications', !isOpen);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return Notifications ? <Notifications /> : undefined;\n};\n\nexport default NotificationsAsync;\n","import React, { FC } from '../../lib/teact/teact';\nimport { Bundles } from '../../util/moduleLoader';\n\nimport useModuleLoader from '../../hooks/useModuleLoader';\n\nconst ErrorsAsync: FC = ({ isOpen }) => {\n const Errors = useModuleLoader(Bundles.Extra, 'Errors', !isOpen);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return Errors ? <Errors /> : undefined;\n};\n\nexport default ErrorsAsync;\n","import React, { FC } from '../../lib/teact/teact';\nimport { Bundles } from '../../util/moduleLoader';\nimport { OwnProps } from './ForwardPicker';\n\nimport useModuleLoader from '../../hooks/useModuleLoader';\n\nconst ForwardPickerAsync: FC<OwnProps> = (props) => {\n const { isOpen } = props;\n const ForwardPicker = useModuleLoader(Bundles.Extra, 'ForwardPicker', !isOpen);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return ForwardPicker ? <ForwardPicker {...props} /> : undefined;\n};\n\nexport default ForwardPickerAsync;\n","import React, { FC, useEffect, memo } from '../../lib/teact/teact';\nimport { getGlobal, withGlobal } from '../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../global/types';\nimport { ApiMessage } from '../../api/types';\n\nimport '../../modules/actions/all';\nimport { ANIMATION_END_DELAY, DEBUG } from '../../config';\nimport { pick } from '../../util/iteratees';\nimport {\n selectChatMessage,\n selectCountNotMutedUnread,\n selectIsForwardModalOpen,\n selectIsMediaViewerOpen,\n selectIsRightColumnShown,\n} from '../../modules/selectors';\nimport { dispatchHeavyAnimationEvent } from '../../hooks/useHeavyAnimationCheck';\nimport buildClassName from '../../util/buildClassName';\nimport useShowTransition from '../../hooks/useShowTransition';\nimport useBackgroundMode from '../../hooks/useBackgroundMode';\n\nimport LeftColumn from '../left/LeftColumn';\nimport MiddleColumn from '../middle/MiddleColumn';\nimport RightColumn from '../right/RightColumn';\nimport MediaViewer from '../mediaViewer/MediaViewer.async';\nimport AudioPlayer from '../middle/AudioPlayer';\nimport Notifications from './Notifications.async';\nimport Errors from './Errors.async';\nimport ForwardPicker from './ForwardPicker.async';\n\nimport './Main.scss';\n\ntype StateProps = {\n animationLevel: number;\n lastSyncTime?: number;\n isLeftColumnShown: boolean;\n isRightColumnShown: boolean;\n isMediaViewerOpen: boolean;\n isForwardModalOpen: boolean;\n hasNotifications: boolean;\n hasErrors: boolean;\n audioMessage?: ApiMessage;\n};\n\ntype DispatchProps = Pick<GlobalActions, 'loadAnimatedEmojis'>;\n\nconst APP_NAME = 'Telegram';\nconst ANIMATION_DURATION = 350;\nconst NOTIFICATION_INTERVAL = 1000;\n\nlet rightColumnAnimationTimeout: number | undefined;\nlet notificationInterval: number | undefined;\n\nlet DEBUG_isLogged = false;\n\nconst Main: FC<StateProps & DispatchProps> = ({\n lastSyncTime,\n loadAnimatedEmojis,\n isLeftColumnShown,\n isRightColumnShown,\n isMediaViewerOpen,\n isForwardModalOpen,\n animationLevel,\n hasNotifications,\n hasErrors,\n audioMessage,\n}) => {\n if (DEBUG && !DEBUG_isLogged) {\n DEBUG_isLogged = true;\n // eslint-disable-next-line no-console\n console.log('>>> RENDER MAIN');\n }\n\n // Initial API calls\n useEffect(() => {\n if (lastSyncTime) {\n loadAnimatedEmojis();\n }\n }, [lastSyncTime, loadAnimatedEmojis]);\n\n const {\n transitionClassNames: middleColumnTransitionClassNames,\n } = useShowTransition(!isLeftColumnShown, undefined, true);\n\n const {\n transitionClassNames: rightColumnTransitionClassNames,\n } = useShowTransition(isRightColumnShown, undefined, true);\n\n const className = buildClassName(\n middleColumnTransitionClassNames.replace(/([\\w-]+)/g, 'middle-column-$1'),\n rightColumnTransitionClassNames.replace(/([\\w-]+)/g, 'right-column-$1'),\n );\n\n useEffect(() => {\n // For animating Symbol Menu on mobile\n document.body.classList.toggle('is-middle-column-open', className.includes('middle-column-open'));\n // For animating components in portals (i.e. Notification)\n document.body.classList.toggle('is-right-column-shown', className.includes('right-column-open'));\n }, [className]);\n\n // Add `body` classes when toggling right column\n useEffect(() => {\n if (animationLevel > 0) {\n document.body.classList.add('animating-right-column');\n dispatchHeavyAnimationEvent(ANIMATION_DURATION + ANIMATION_END_DELAY);\n\n if (rightColumnAnimationTimeout) {\n clearTimeout(rightColumnAnimationTimeout);\n rightColumnAnimationTimeout = undefined;\n }\n\n rightColumnAnimationTimeout = window.setTimeout(() => {\n document.body.classList.remove('animating-right-column');\n rightColumnAnimationTimeout = undefined;\n }, ANIMATION_DURATION + ANIMATION_END_DELAY);\n }\n }, [animationLevel, isRightColumnShown]);\n\n useBackgroundMode(() => {\n const initialUnread = selectCountNotMutedUnread(getGlobal());\n let index = 0;\n\n clearInterval(notificationInterval);\n notificationInterval = window.setInterval(() => {\n if (index % 2 === 0) {\n const newUnread = selectCountNotMutedUnread(getGlobal()) - initialUnread;\n if (newUnread > 0) {\n document.title = `${newUnread} notification${newUnread > 1 ? 's' : ''}`;\n updateIcon(true);\n }\n } else {\n document.title = APP_NAME;\n updateIcon(false);\n }\n\n index++;\n }, NOTIFICATION_INTERVAL);\n }, () => {\n clearInterval(notificationInterval);\n notificationInterval = undefined;\n document.title = APP_NAME;\n updateIcon(false);\n });\n\n function stopEvent(e: React.MouseEvent<HTMLDivElement, MouseEvent>) {\n e.preventDefault();\n e.stopPropagation();\n }\n\n return (\n <div id=\"Main\" className={className} onDrop={stopEvent} onDragOver={stopEvent}>\n <LeftColumn />\n <MiddleColumn />\n <RightColumn />\n <MediaViewer isOpen={isMediaViewerOpen} />\n <ForwardPicker isOpen={isForwardModalOpen} />\n <Notifications isOpen={hasNotifications} />\n <Errors isOpen={hasErrors} />\n {audioMessage && <AudioPlayer key={audioMessage.id} message={audioMessage} noUi />}\n </div>\n );\n};\n\nfunction updateIcon(asUnread: boolean) {\n document.querySelectorAll<HTMLLinkElement>('link[rel=\"icon\"]')\n .forEach((link) => {\n if (asUnread) {\n if (!link.href.includes('favicon-unread')) {\n link.href = link.href.replace('favicon', 'favicon-unread');\n }\n } else {\n link.href = link.href.replace('favicon-unread', 'favicon');\n }\n });\n}\n\nexport default memo(withGlobal(\n (global): StateProps => {\n const { chatId: audioChatId, messageId: audioMessageId } = global.audioPlayer;\n const audioMessage = audioChatId && audioMessageId\n ? selectChatMessage(global, audioChatId, audioMessageId)\n : undefined;\n\n return {\n animationLevel: global.settings.byKey.animationLevel,\n lastSyncTime: global.lastSyncTime,\n isLeftColumnShown: global.isLeftColumnShown,\n isRightColumnShown: selectIsRightColumnShown(global),\n isMediaViewerOpen: selectIsMediaViewerOpen(global),\n isForwardModalOpen: selectIsForwardModalOpen(global),\n hasNotifications: Boolean(global.notifications.length),\n hasErrors: Boolean(global.errors.length),\n audioMessage,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, ['loadAnimatedEmojis']),\n)(Main));\n","import { getDispatch, getGlobal } from '../lib/teact/teactn';\n\nimport { DEBUG } from '../config';\n\nexport { default as Main } from '../components/main/Main';\n\nif (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('>>> FINISH LOAD MAIN BUNDLE');\n}\n\nif (!getGlobal().connectionState) {\n getDispatch().initApi();\n}\n"],"sourceRoot":""}