mirror of
https://github.com/danog/telegram-tt.git
synced 2024-12-15 10:47:04 +01:00
1 line
846 KiB
Plaintext
1 line
846 KiB
Plaintext
{"version":3,"sources":["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/components/middle/helpers/calculateMiddleFooterTransforms.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/useBlurredMediaThumbRef.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/hooks/usePauseOnInactive.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/MentionTooltip.async.tsx","webpack:///./src/components/middle/composer/CustomSendMenu.async.tsx","webpack:///./src/components/middle/composer/StickerTooltip.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/useStickerTooltip.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/ProfilePhoto.tsx","webpack:///./src/components/right/ProfileInfo.tsx","webpack:///./src/components/right/hooks/usePhotosPreload.ts","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/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/SafeLinkModal.async.tsx","webpack:///./src/components/main/Main.tsx","webpack:///./src/bundles/main.ts"],"names":["addReducer","global","actions","payload","id","threadId","type","noPushState","currentMessageList","selectCurrentMessageList","chatId","exitMessageSelectMode","messages","contentToBeScheduled","undefined","forwardMessages","toChatId","setGlobal","HistoryWrapper","pushState","messageListType","back","updateCurrentMessageList","isChatInfoShown","contentKey","selectRightColumnContentKey","openChat","chatCreation","blurTimeout","scrollOffset","replaceThreadParam","messageId","paramName","chatMessages","selectChatMessages","viewportIds","selectViewportIds","lastOwnEditableMessageId","findLast","Boolean","selectAllowedMessageActions","canEdit","targetIndexDelta","replyingToId","selectReplyingToId","selectIsViewportNewest","chatMessageKeys","Object","keys","newIndex","indexOf","toString","length","Number","MAIN_THREAD_ID","chat","selectChat","lastMessage","threadInfo","selectThreadInfo","lastMessageId","setReplyingToId","focusMessage","avatarOwnerId","profilePhotoIndex","origin","mediaViewer","audioPlayer","shouldOpenInstantly","selectIsRightColumnShown","RightColumnContent","PollResults","window","setTimeout","newGlobal","getGlobal","pollResults","voters","noHighlight","groupedId","groupedChatId","ids","selectForwardedMessageIdsByGroupId","shouldSwitchChat","clearTimeout","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","Search","updateLocalTextSearch","replaceLocalTextSearchResults","chatThreadKey","buildChatThreadKey","currentQuery","localTextSearch","byChatThreadKey","MEMO_EMPTY_ARRAY","mediaType","updateLocalMediaSearchType","previousQuery","stickers","search","StickerSearch","resultIds","gifs","GifSearch","offsetId","results","updateSelectedUserId","replaceSettings","theme","settings","replaceThemeSettings","isActive","prevIsActive","management","byChatId","IS_MOBILE_SCREEN","isLeftColumnShown","action","emoji","recentEmojis","newEmojis","e","sticker","recent","hash","newStickers","s","notification","newNotifications","notifications","existingNotificationIndex","findIndex","n","message","splice","push","error","getReadableErrorText","newErrors","errors","existingErrorIndex","err","url","safeLinkModalUrl","payment","isPaymentModalOpen","clearPayment","closeInvoice","runThrottledForLoadChats","throttle","cb","runThrottledForLoadTopChats","runDebouncedForLoadFullChat","debounce","async","loadChats","listType","offsetDate","result","callApi","limit","CHAT_LIST_LOAD_SLICE","archived","withPinned","orderedPinnedIds","chatIds","shift","addUsers","buildCollectionByKey","users","updateChats","updateChatListIds","updateChatListSecondaryInfo","draftsById","map","forEach","replyingToById","isFullyLoaded","loadFullChat","fullInfo","updateChat","openChatByUsername","username","channelPostId","localChat","selectChatByUsername","isMin","previousChat","showNotification","preloadedChatIds","i","TOP_CHAT_MESSAGES_PRELOAD_LIMIT","pause","byId","listIds","active","currentChatId","pinnedChats","otherChats","prepareChatList","chatToPreload","find","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","getDispatch","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","max","apply","deleteChatFolder","unreadCount","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","activeChatFolder","offset","uploadProgressCallbacks","Map","runThrottledForMarkRead","isOutlying","isBudgetPreload","addOffset","LoadMoreDirection","Backwards","Around","round","MESSAGE_LIST_SLICE","Forwards","selectThreadOriginChat","threadInfos","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","clearWebPagePreview","value","noWebPage","selectNoWebPage","isSingle","attachments","isGrouped","restParams","text","entities","commonParams","groupedAttachments","split","MAX_MEDIA_FILES_FOR_ALBUM","firstAttachment","restAttachments","Date","now","selectEditingMessage","setEditingId","get","previousLocalId","cancelApiProgress","apiUpdate","draft","replyToMsgId","localOnly","selectDraft","isUnpin","isOneSide","isSilent","unpinAllMessages","shouldDeleteForAll","editingId","selectEditingId","selectEditingScheduledId","webPagePreview","loadWebPagePreview","options","option","shouldResetVoters","v","a","offsets","nextOffset","loadPollOptionResults","fromChat","toChat","b","scheduledMessages","historyHash","replaceScheduledMessages","loadScheduledHistory","selectScheduledMessage","loadPinnedMessages","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","concat","replaceUsers","audioChatId","audioMessageId","closeAudioPlayer","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","profileId","isPrivate","photos","button","sendBotCommand","command","openTelegramLink","toggleSafeLinkModal","data","alert","isError","showError","answerCallbackButton","openPollModal","getReceipt","receiptMessageId","getPaymentForm","setInvoiceMessageInfo","openPaymentModal","bio","profileEdit","ProfileEditProgress","currentUser","Idle","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","shouldShowPreviews","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","runThrottledForUpdateAppBadge","update","noTopChatsRequest","selectIsChatListed","loadTopChats","newProfilePhoto","selectCountNotMutedUnread","updateAppBadge","isNotJoined","listId","typingStatus","senderId","isFromScheduled","isActiveChat","hasUnreadMention","unreadMentionsCount","showNewMessageNotification","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","firstUnreadId","selectFirstUnreadId","addViewportId","firstMessageId","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","addNotifyException","twoFaSettings","memo","name","label","checked","disabled","inactive","noAnimation","onChange","onCheck","handleChange","useCallback","currentTarget","className","buildClassName","ANIMATION_LEVEL_OPTIONS","withGlobal","searchQuery","animationLevel","byKey","globalSearchChatId","searchDate","contactsFilter","onSearchQuery","onSelectSettings","onSelectContacts","onSelectArchived","onOpenMenu","onCloseMenu","setGlobalSearchChatId","onReset","shouldSkipTransition","openTipsChat","setGlobalSearchDate","setSettingOption","lang","useLang","hasMenu","LeftColumnContent","ChatList","clearedDateSearchParam","clearedChatSearchParam","selectedSearchDate","useMemo","formatDateToString","archivedUnreadChatsCount","values","total","MainButton","onTrigger","isOpen","Button","ripple","color","onClick","ariaLabel","handleSearchFocus","handleSelectSaved","handleDarkModeToggle","stopPropagation","newTheme","switchTheme","handleAnimationLevelChange","newLevel","_","body","classList","toggle","isSearchFocused","GlobalSearch","Contacts","searchInputPlaceholder","forceOpenDropdown","setForceOpenDropdown","useState","useHistoryBack","event","previousHistoryState","isMenuOpen","DropdownMenu","trigger","footer","APP_NAME","APP_VERSION","forceOpen","onOpen","onClose","MenuItem","icon","toLowerCase","href","FEEDBACK_URL","SearchInput","inputId","parentContainerClassName","focused","placeholder","canClose","onFocus","PickerSelectedItem","isMinimized","clickArg","chatOrUserId","connectionState","dir","isRtl","Spinner","resolverFn","ms","dependencies","valueRef","useRef","runThrottled","useThrottle","forceUpdate","useForceUpdate","useOnChange","isSync","current","orderedFolderIds","notifySettings","selectNotifySettings","notifyExceptions","selectNotifyExceptions","setActiveChatFolder","transitionRef","useEffect","displayedFolders","folderCountersById","useThrottledMemo","counters","unreadDialogsCount","hasActiveDialogs","getFolderUnreadDialogs","badgeCount","isBadgeActive","folderTabs","handleSwitchTab","IS_TOUCH_ENV","captureEvents","onSwipe","SwipeDirection","Left","min","Right","isNotInAllTabRef","captureEscKeyListener","handleKeyDown","metaKey","startsWith","digit","preventDefault","addEventListener","removeEventListener","shouldRender","shouldRenderPlaceholder","transitionClassNames","useShowTransition","renderCurrentTab","activeFolder","folderType","noChatsText","TabList","tabs","activeTab","onSwitchTab","Transition","ref","activeKey","renderCount","props","LeftSearch","useModuleLoader","Bundles","Extra","Loading","ContactList","closeTimeout","isShown","onNewPrivateChat","onNewChannel","onNewGroup","setIsMenuOpen","fabClassName","handleMouseEnter","handleMouseLeave","onMouseEnter","onMouseLeave","tabIndex","Menu","positionX","positionY","autoClose","TRANSITION_RENDER_COUNT","onContentChange","isNewChatButtonShown","setIsNewChatButtonShown","isMouseInside","handleSelectSettings","Settings","handleSelectContacts","handleSelectNewChannel","NewChannelStep1","handleSelectNewGroup","NewGroupStep1","handleSelectArchived","Archived","autoCloseTimeout","NewChat","ContentType","ArchivedChats","RENDER_COUNT","setGlobalSearchQuery","resetChatCreation","loadPasswordInfo","clearTwoFaError","setContent","settingsScreen","setSettingsScreen","SettingsScreens","Main","setContactsFilter","openMenu","closeMenu","useFlag","setContentWithHistory","NewChannelStep2","NewGroupStep2","setSettingsScreenWithHistory","screen","lastResetTime","setLastResetTime","contentType","NewChannel","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","setShouldSkipTransition","ANIMATION_DURATION","handleSearchQuery","currentScreen","onScreenSelect","isChannel","setSize","windowSize","handleResize","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","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","handleUnpinMessage","ConfirmDialog","confirmLabel","confirmHandler","thumbDataUri","getPictogramDimensions","src","alt","renderPictogram","renderText","RippleEffect","sender","selectSender","noUi","senderName","getSenderTitle","mediaData","mediaLoader","playPause","isPlaying","useAudioPlayer","getMessageKey","getMediaDuration","handleClick","handleClose","audio","getMessageAudio","performer","renderAudio","subtitle","renderVoice","audioMessage","originChat","messagesCount","pinnedIds","state","isSelectModeActive","originChatId","isChatWithBot","selectIsChatWithBot","assign","pinnedMessageId","topMessageSender","selectForwardedSender","pinnedMessageIds","canUnpin","firstPinnedMessage","openChatWithInfo","pinMessage","toggleLeftColumn","pinnedMessageIndex","setPinnedMessageIndex","isArray","pinnedMessage","pinnedMessagesCount","chatTitleLength","getChatTitle","topMessageTitle","useEnsureMessage","useWindowSize","isLeftColumnHideable","shouldShowCloseButton","componentRef","shouldAnimateTools","handleHeaderClick","handlePinnedMessageClick","cycleRestrict","handleAllPinnedClick","handleBackClick","messageInput","EDITABLE_INPUT_ID","currentChat","selectIsChatMuted","canToolsCollideWithChatInfo","SAFE_SCREEN_WIDTH_FOR_CHAT_INFO","shouldUseStackedToolsClass","SAFE_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN","shouldRenderAudioPlayer","audioPlayerClassNames","renderingAudioMessage","useCurrentOrPrev","shouldRenderPinnedMessage","pinnedMessageClassNames","renderingPinnedMessage","renderingPinnedMessageTitle","canRevealTools","renderInfo","renderBackButton","PrivateChatInfo","withFullInfo","withMediaViewer","withUpdatingStatus","noRtl","GroupChatInfo","asClose","unreadCountInfo","formatIntegerCompact","componentEl","add","remove","isAlbum","messageOrAlbum","groupMessages","currentAlbum","currentSenderGroup","currentDateGroup","originalDate","datetime","getDayStart","senderGroups","dateGroups","isInAlbum","mainMessage","albumId","nextMessage","nextMessageDatetime","isActionMessage","forwardInfo","senderUserId","hiddenUserName","inlineButtons","useStickyDates","isScrolled","markIsScrolled","runDebounced","shouldRunFirst","shouldRunLast","updateStickyDates","container","hasTools","contains","fastRaf","currentStuck","stuckDateEl","allElements","querySelectorAll","containerTop","scrollTop","el","offsetTop","offsetHeight","top","findStuckDate","isFabFrozen","MessageScroll","focusingId","loadMoreForwards","loadMoreBackwards","isViewportNewest","onFabToggle","onNotchToggle","children","backwardsTriggerRef","forwardsTriggerRef","fabTriggerRef","toggleScrollTools","scrollHeight","scrollBottom","isAtBottom","observe","observeIntersection","freeze","freezeForLoadMore","unfreeze","unfreezeForLoadMore","useIntersectionObserver","rootRef","margin","MESSAGE_LIST_SENSITIVE_AREA","entries","triggerEntry","isIntersecting","target","resetScroll","useOnIntersect","observeIntersectionForFab","freezeForFab","unfreezeForFab","observeIntersectionForNotch","teactFastList","isEmojiOnlyMessage","customShape","getMinMediaWidth","hasText","hasCommentButton","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","element","calculateAuthorWidth","createElement","font","whiteSpace","position","left","opacity","appendChild","offsetWidth","useFocusMessage","elementRef","isFocused","focusDirection","noFocusHighlight","messagesContainer","closest","fastSmoothScroll","ContextMenuContainer","targetUserId","targetChatId","targetMessageId","targetMessage","selectIsMessageFocused","focusedMessage","isEmbedded","appearanceOrder","isLastInList","noAppearanceAnimation","markShown","renderActionMessageText","asPlain","isContextMenuOpen","contextMenuPosition","handleBeforeContextMenu","handleContextMenu","handleContextMenuClose","handleContextMenuHide","useContextMenuHandlers","isContextMenuShown","data-message-id","onMouseDown","onContextMenu","EmbeddedMessage","customText","useIsIntersecting","pictogramId","isRoundVideo","getMessageRoundVideo","senderTitle","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","useBlurredMediaThumbRef","fullMediaData","useCanvasBlur","IS_CANVAS_FILTER_SUPPORTED","inSelectMode","isSelected","img","Image","onload","canvas","ctx","getContext","drawImage","getImageData","getAppendixColorFromImage","Photo","shouldAutoLoad","isInSelectMode","uploadProgress","nonInteractive","shouldAffectAppendix","onCancelUpload","localBlobUrl","isDownloadAllowed","setIsDownloadAllowed","shouldDownload","downloadProgress","useMediaWithDownloadProgress","thumbRef","isUploading","isTransferring","transferProgress","getMediaTransferState","wasDownloadDisabled","usePrevious","shouldRenderSpinner","spinnerClassNames","shouldRenderThumb","isAllowed","contentEl","getCustomAppendixBg","appendixBg","setProperty","setAttribute","ProgressSpinner","useHeavyAnimationCheckForVideo","playerRef","shouldPlayRef","safePlay","useHeavyAnimationCheck","isPlayAllowed","wasPlaying","isFrozen","freezePlaying","paused","unfreezePlaying","unfreezePlayingOnRaf","hasFocus","useBackgroundMode","Video","shouldAutoPlay","videoRef","canPlayInline","canMessagePlayVideoInline","setIsPlayAllowed","isInline","isBuffered","bufferingHandlers","useBuffering","playProgress","setPlayProgress","handleTimeUpdate","currentTime","usePauseOnInactive","useVideoCleanup","videoClassName","shouldRenderInlineVideo","shouldRenderHqPreview","shouldRenderPlayButton","shouldRenderDownloadButton","autoPlay","muted","loop","playsInline","onTimeUpdate","isGif","formatMediaDuration","duration","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","containerId","question","getPollTypeString","RadioGroup","loadingOption","isQuiz","getReadableVotersCount","isText","inPreview","onMediaClick","onCancelMediaTransfer","webPage","getMessageWebPage","isSquarePhoto","handleMediaClick","siteName","displayUrl","isMediaInteractive","hasDocument","truncatedDescription","trimText","data-initial","SafeLink","getMessageInvoice","photoUrl","withSelectControl","WrapedComponent","ownProps","selectIsMessageSelected","handleMessageSelect","shiftKey","newProps","PhotoWithSelect","VideoWithSelect","uploadsById","hasCustomAppendix","albumLayout","cancelSendingMessage","mediaCount","handleCancelUpload","containerWidth","containerHeight","fileUpload","currentOnRelease","RoundVideo","playingProgressRef","shouldSpinnerRender","isActivated","setIsActivated","setProgress","playerEl","playingProgressEl","stopPlaying","requestAnimationFrame","capturePlaying","onRelease","ROUND_VIDEO_DIMENSIONS","onEnded","InlineButtons","recentReplierIds","recentRepliers","hasUnread","data-cnt","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","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","withCommentButton","withAppendix","handleGroupDocumentMessagesSelect","handleContainerDoubleClick","handleContentDoubleClick","handleAvatarClick","handleSenderClick","handleViaBotClick","handleReplyClick","MediaViewerOrigin","ScheduledInline","Inline","handleAudioPlay","handleAlbumMediaClick","albumMessageId","ScheduledAlbum","Album","handleReadMedia","handleVoteSend","handleGroupForward","handleForward","handleFocus","handleFocusForwarded","fromMessageId","calculatedWidth","noMediaCorners","extraPadding","metaSafeAuthorWidth","canShowActionButton","canForward","canFocus","isChannelPost","onDoubleClick","data-last-message-id","data-has-unread-mention","isAvatarPeerUser","avatarUser","avatarChat","hiddenName","renderAvatar","shouldInlineMeta","senderColor","getUserColorKey","renderSenderName","AnimatedEmoji","Audio","isSelectable","onPlay","onReadMedia","Document","renderContent","INTERSECTION_THROTTLE_FOR_MEDIA","IS_ANDROID","INTERSECTION_MARGIN_FOR_MEDIA","runDebouncedForScroll","selectCurrentMessageIds","restrictionReason","withLastMessageWhenPreloading","botDescription","chatBot","selectChatBot","isChatLoaded","isChannelChat","threadFirstMessageId","selectFirstMessageId","hasLinkedChat","markMessageListRead","setScrollOffset","scrollOffsetRef","selectScrollOffset","anchorIdRef","anchorTopRef","listItemElementsRef","memoUnreadDividerBeforeIdRef","memoFirstUnreadIdRef","memoFocusingIdRef","isScrollTopJustUpdatedRef","shouldAnimateAppearanceRef","setContainerHeight","hasFocusing","setHasFocusing","onTickEnd","freezeForMedia","unfreezeForMedia","throttleMs","observeIntersectionForReading","freezeForReading","unfreezeForReading","mentionIds","entry","dataset","messageGroups","listedMessages","orderBy","loadMoreAround","handleScroll","parentElement","observer","ResizeObserver","offsetParent","contentRect","disconnect","windowHeight","normalHeight","String","clientHeight","preservedItemElements","useLayoutEffectWithPrevDeps","prevMessageIds","prevIsViewportNewest","prevContainerHeight","shouldForceScroll","lastItemElement","lastItemHeight","newScrollTop","hasFirstMessageChanged","hasLastMessageChanged","isAlreadyFocusing","isResized","unreadDivider","isAnimatingScroll","dispatchHeavyAnimationEvent","ANIMATION_END_DELAY","withUsers","onScroll","currentAnchorIdRef","isSchedule","messageCountToAnimate","messageGroup","flatten","appearanceIndex","dateGroup","dateGroupIndex","dateGroupsArray","senderGroup","senderGroupIndex","senderGroupsArray","compact","currentDocumentGroupId","messageIndex","isMessageAlbum","documentGroupId","nextDocumentGroupId","originalId","getMessageOriginalId","SCHEDULED_WHEN_ONLINE","formatHumanDate","renderMessages","focusLastMessage","messageElements","lastMessageElement","buildAttachment","filename","blob","isQuick","quick","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","DeleteMessageModal","openTimeout","isFirstTimeActivation","onActivate","buttonProps","AttachMenu","SymbolMenu","MentionTooltip","CustomSend","StickerTooltipAsync","StickerTooltip","BotKeyboardMenu","forwardMessageIds","forwardedMessagesCount","exitForwardMode","canAnimate","useAsyncRendering","clearEmbedded","handleMessageClick","AttachmentModal","PollModal","DropArea","RE_LINK","RegExp","RE_LINK_TEMPLATE","messageText","toggleMessageWebPage","parseMessageInput","linkEntity","ApiMessageEntityTypes","TextUrl","textMatch","renderingWebPage","webPageWithoutPhoto","messageStub","CalendarModal","PaymentModal","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","addRecentEmoji","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","IS_IOS","voiceRecording","tickVolume","boxShadow","useVoiceRecording","mainButtonState","Edit","IS_VOICE_RECORDING_SUPPORTED","Send","Record","canShowCustomSendMenu","isMentionTooltipOpen","mentionFilter","closeMentionTooltip","insertMention","mentionFilteredMembers","useMentionTooltip","isCustomSendMenuOpen","allowedAttachmentOptions","getAllowedAttachmentOptions","isChatAdmin","slowMode","getChatSlowModeOptions","isStickerTooltipOpen","closeStickerTooltip","clearStickersForEmoji","IS_EMOJI_SUPPORTED","parseEmojiOnlyString","hasStickers","useStickerTooltip","canSendStickers","isEmojiTooltipOpen","closeEmojiTooltip","filteredEmojis","insertEmoji","useEmojiTooltip","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","useClipboardPaste","handleFileSelect","files","handleAppendFiles","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","DropAreaState","None","withQuick","QuickFile","onHide","onFileSelect","caption","onCaptionUpdate","onSend","onFileAppend","onClear","onInsertUserName","filteredChatMembers","canAttachEmbedLinks","faded","MessageInput","innerWidth","shouldSetFocus","shouldSupressFocus","shouldSupressTextFormatter","onUpdate","onSupressedFocus","formatVoiceRecordDuration","onStickerSelect","emojis","onEmojiSelect","onPollCreate","onGifSelect","onRemoveSymbol","onSearchOpen","onSilentSend","onScheduleSend","withTimePicker","selectedAt","maxAt","getDayStartAt","isFutureMode","secondButtonLabel","onSubmit","onSecondButtonClick","MobileSearch","MessageSelectToolbar","UnpinAllMessagesModal","CLOSE_ANIMATION_DURATION","canBeQuicklyUploaded","kind","CONTENT_TYPES_FOR_QUICK_UPLOAD","isBlurred","isBackgroundBlurred","background","customBackground","backgroundColor","patternColor","themes","isMobileSearchActive","getCanPostInChat","isBotNotStarted","isPinnedMessageList","messageSendingRestrictionReason","getMessageSendingRestrictionReason","hasPinnedOrAudioMessage","loadUser","setDropAreaState","isFabShown","setIsFabShown","isNotchShown","setIsNotchShown","isUnpinModalOpen","setIsUnpinModalOpen","renderingChatId","usePrevDuringAnimation","renderingThreadId","renderingMessageListType","renderingCanPost","renderingHasTools","renderingIsFabShown","handleDragEnter","dataTransfer","shouldDrawQuick","handleHideDropArea","handleOpenUnpinModal","closeUnpinModal","handleUnpinAllMessages","customBackgroundValue","settingValue","setValue","cacheApi","CUSTOM_BG_CACHE_NAME","useCustomBackground","MASK_IMAGE_DISABLED","messagingDisabledClassName","footerClassName","DARK_THEME_BG_COLOR","LIGHT_THEME_BG_COLOR","onDragEnter","ANIMATION_LEVEL_MAX","shouldCleanup","onUnpin","runDebouncedForSearch","HeaderContent","isProfile","isManagement","messageSearchQuery","stickerSearchQuery","selectCurrentStickerSearch","gifSearchQuery","selectCurrentGifSearch","canManage","isCreator","isColumnOpen","isSearch","isStickerSearch","isGifSearch","isPollResults","profileState","managementScreen","setLocalTextSearchQuery","searchTextMessagesLocal","toggleManagement","shouldSkipAnimation","backButtonRef","handleMessageSearchQueryChange","handleJumpToDate","valueOf","handleStickerSearchQueryChange","handleGifSearchQueryChange","ProfileState","Profile","SharedMedia","MemberList","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","renderingContentKey","renderHeaderContent","isBackButton","buttonClassName","isPastMode","submitButtonLabel","useProfileViewportIds","loadMoreMembers","searchMessages","tabType","mediaSearchType","resultType","sortUserIds","memberViewportIds","getMoreMembers","noProfileInfoForMembers","currentResultType","handleLoadMore","getMore","useInfiniteScroll","MEMBERS_SLICE","isOnTop","useInfiniteScrollForMembers","mediaViewportIds","getMoreMedia","noProfileInfoForMedia","useInfiniteScrollForSharedMedia","documentViewportIds","getMoreDocuments","noProfileInfoForDocuments","linkViewportIds","getMoreLinks","noProfileInfoForLinks","audioViewportIds","getMoreAudio","noProfileInfoForAudio","noProfileInfo","forSharedMediaType","messageIdsRef","getMessageContentIds","reverse","runThrottledForScroll","isScrollingProgrammatically","isFirstPhoto","isSavedMessages","isDeleted","isDeletedUser","getMediaHash","forceAvatar","getChatAvatarHash","imageHash","ApiMediaFormat","BlobUrl","avatarThumbnailData","useBlurSync","dataUri","imageSrc","prevImageSrc","decoding","userFullName","getUserFullName","getFirstLetters","fullClassName","forceShowSelf","loadFullUser","fullName","slideAnimation","currentPhotoIndex","setCurrentPhotoIndex","isFirst","isLast","profile","currentIndex","usePhotosPreload","handleProfilePhotoClick","ProfileAvatar","selectPreviousMedia","selectNextMedia","excludedClosestSelector","renderPhoto","isVerifiedIconShown","isVerified","renderPhotoTabs","aria-label","VerifiedIcon","isUserOnline","getUserStatus","canInviteUsers","isUserRightBanned","getHasAdminRight","currentIsMuted","chatUsername","handleNotificationChange","copy","entity","formattedNumber","getChatLink","printedUsername","getChatDescription","ListItem","multiline","narrow","isStatic","TABS","buildInfiniteScrollItemSelector","isGroup","hasMembersTab","areMembersHidden","canViewMembers","resolvedUserId","onProfileStateChange","setLocalMediaSearchType","searchMediaMessagesLocal","loadProfilePhotos","setActiveTab","useEffectWithPrevDeps","prevTabType","tabsEl","prevProfileState","tabListEl","determineProfileState","useProfileState","applyTransitionFix","releaseTransitionFix","transitionElSelector","setMinHeight","transitionEl","minHeight","overflowY","scrollBarWidth","clientWidth","marginRight","useTransitionFixes","cacheBuster","resetCacheBuster","setCacheBuster","useCacheBuster","handleTransitionStop","handleSelectMedia","handlePlayAudio","handleMemberClick","handleMessageFocus","renderingDelay","isFirstTab","SLIDE_TRANSITION_DURATION","canRenderContents","renderSharedMedia","noSpinner","NothingFound","Media","withDate","smaller","onDateClick","WebLink","onMessageClick","renderingFor","teactOrderKey","InfiniteScroll","itemSelector","sensitiveArea","PROFILE_SENSITIVE_AREA","preloadBackwards","noScrollRestoreOnTop","noFastList","onLoadMore","renderProfileInfo","shouldRestoreHeight","onStart","onStop","big","RightSearch","Management","MAIN_SCREENS_COUNT","MANAGEMENT_SCREENS_COUNT","blurSearchInput","areActiveChatsLoaded","selectAreActiveChatsLoaded","currentProfileUserId","selectedId","isChatSelected","toggleChatInfo","closeLocalTextSearch","closePollResults","setProfileState","setManagementScreen","selectedChatMemberId","setSelectedChatMemberId","isPromotedByCurrentUser","setIsPromotedByCurrentUser","isScrolledDown","ChatInfo","UserInfo","isOverlaying","close","GroupType","handleSelectChatMember","memberId","isPromoted","handleManagementScreenSelect","onChatMemberSelect","prevContentKey","MediaViewer","Errors","ForwardPicker","SafeLinkModal","rightColumnAnimationTimeout","notificationInterval","DEBUG_isLogged","updateIcon","asUnread","isMediaViewerOpen","selectIsMediaViewerOpen","isForwardModalOpen","selectIsForwardModalOpen","hasNotifications","hasErrors","isHistoryAnimationDisabled","setIsHistoryAnimationDisabled","middleColumnTransitionClassNames","rightColumnTransitionClassNames","stopEvent","initialUnread","clearInterval","setInterval","INACTIVE_MARKER","newUnread","PAGE_TITLE","onDrop","onDragOver","initApi"],"mappings":"+LAQAA,YAAW,WAAY,CAACC,EAAQC,EAASC,KACvC,MAAM,GACJC,EADI,SACAC,GAAW,EADX,KACeC,EAAO,SADtB,YACgCC,GAClCJ,EAEEK,EAAqBC,YAAyBR,GAqCpD,OAnCKO,GAEDA,EAAmBE,SAAWN,GAC3BI,EAAmBH,WAAaA,GAChCG,EAAmBF,OAASA,IAEjCL,EAASU,YAAsBV,GAE/BA,EAAS,IACJA,EACHW,SAAU,IACLX,EAAOW,SACVC,0BAAsBC,MAEpBV,IAAOH,EAAOc,gBAAgBC,UAAY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D,IACvB,kBAAC,GAAD,CAAeh0D,OAAQk0D,IACvB,kBAAC,GAAD,CAAQl0D,OAAQm0D,IACf/7C,GAAgB,kBAAC,GAAD,CAAaxb,IAAKwb,EAAarwC,GAAIsK,QAAS+lC,EAAclB,MAAI,IAC/E,kBAAC,GAAD,CAAepkC,IAAKC,QC1MtBkX,KAEFC,QAAQC,IAAI,+BAGT7d,cAAY+2B,iBACf5qB,cAAcw8E,W","file":"4.8cdfd787b07dfff9733c.js","sourcesContent":["import { addReducer, setGlobal } from '../../../lib/teact/teactn';\nimport {\n exitMessageSelectMode,\n updateCurrentMessageList,\n} from '../../reducers';\nimport { selectCurrentMessageList, selectRightColumnContentKey } from '../../selectors';\nimport { HistoryWrapper } from '../../../util/history';\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 if (id !== undefined) {\n HistoryWrapper.pushState({\n type: 'chat',\n chatId: id,\n threadId,\n messageListType: type,\n });\n } else {\n HistoryWrapper.back();\n }\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 HistoryWrapper.pushState({\n type: 'right',\n contentKey: selectRightColumnContentKey(global),\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, RightColumnContent } 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, selectIsViewportNewest, selectReplyingToId,\n} from '../../selectors';\nimport { findLast } from '../../../util/iteratees';\nimport { HistoryWrapper } from '../../../util/history';\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('replyToNextMessage', (global, actions, payload) => {\n const { targetIndexDelta } = payload;\n const { chatId, threadId } = selectCurrentMessageList(global) || {};\n if (!chatId || !threadId) {\n return;\n }\n\n const chatMessages = selectChatMessages(global, chatId);\n const viewportIds = selectViewportIds(global, chatId, threadId);\n if (!chatMessages || !viewportIds) {\n return;\n }\n\n const replyingToId = selectReplyingToId(global, chatId, threadId);\n const isLatest = selectIsViewportNewest(global, chatId, threadId);\n\n let messageId: number | undefined;\n\n if (!isLatest || !replyingToId) {\n if (threadId === MAIN_THREAD_ID) {\n const chat = selectChat(global, chatId);\n\n messageId = chat && chat.lastMessage ? chat.lastMessage.id : undefined;\n } else {\n const threadInfo = selectThreadInfo(global, chatId, threadId);\n\n messageId = threadInfo ? threadInfo.lastMessageId : undefined;\n }\n } else {\n const chatMessageKeys = Object.keys(chatMessages);\n const indexOfCurrent = chatMessageKeys.indexOf(replyingToId.toString());\n const newIndex = indexOfCurrent + targetIndexDelta;\n messageId = newIndex <= chatMessageKeys.length + 1 && newIndex >= 0\n ? Number(chatMessageKeys[newIndex])\n : undefined;\n }\n actions.setReplyingToId({ messageId });\n actions.focusMessage({\n chatId, threadId, messageId,\n });\n});\n\naddReducer('openMediaViewer', (global, actions, payload) => {\n const {\n chatId, threadId, messageId, avatarOwnerId, profilePhotoIndex, origin,\n } = payload!;\n\n return {\n ...global,\n mediaViewer: {\n chatId,\n threadId,\n messageId,\n avatarOwnerId,\n profilePhotoIndex,\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, noPushState } = payload!;\n\n const shouldOpenInstantly = selectIsRightColumnShown(global);\n\n if (!noPushState) {\n HistoryWrapper.pushState({\n type: 'right',\n contentKey: RightColumnContent.PollResults,\n });\n }\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, actions, payload) => {\n const { noPushState } = payload;\n\n if (!noPushState) {\n HistoryWrapper.back();\n }\n\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 actions.exitMessageSelectMode();\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';\nimport { HistoryWrapper } from '../../../util/history';\nimport { RightColumnContent } from '../../../types';\n\naddReducer('openLocalTextSearch', (global) => {\n const { chatId, threadId } = selectCurrentMessageList(global) || {};\n if (!chatId || !threadId) {\n return undefined;\n }\n\n HistoryWrapper.pushState({\n type: 'right',\n contentKey: RightColumnContent.Search,\n });\n\n return updateLocalTextSearch(global, chatId, threadId, true);\n});\n\naddReducer('closeLocalTextSearch', (global, actions, payload) => {\n const { noPushState } = payload;\n const { chatId, threadId } = selectCurrentMessageList(global) || {};\n if (!chatId || !threadId) {\n return undefined;\n }\n\n if (!noPushState) {\n HistoryWrapper.back();\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';\nimport { HistoryWrapper } from '../../../util/history';\nimport { RightColumnContent } from '../../../types';\n\naddReducer('setStickerSearchQuery', (global, actions, payload) => {\n const { query, noPushState } = payload!;\n const previousQuery = global.stickers.search.query;\n\n if (!noPushState && previousQuery !== query) {\n if (query !== undefined && previousQuery === undefined) {\n HistoryWrapper.pushState({\n type: 'right',\n contentKey: RightColumnContent.StickerSearch,\n });\n } else {\n HistoryWrapper.back();\n }\n }\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, noPushState } = payload!;\n const previousQuery = global.gifs.search.query;\n\n if (!noPushState && previousQuery !== query) {\n if (query !== undefined) {\n HistoryWrapper.pushState({\n type: 'right',\n contentKey: RightColumnContent.GifSearch,\n });\n } else {\n HistoryWrapper.back();\n }\n }\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, IThemeSettings, ThemeKey } from '../../../types';\nimport { replaceSettings, replaceThemeSettings } from '../../reducers';\n\naddReducer('setSettingOption', (global, actions, payload?: Partial<ISettings>) => {\n return replaceSettings(global, payload);\n});\n\naddReducer('setThemeSettings', (global, actions, payload: { theme: ThemeKey } & Partial<IThemeSettings>) => {\n const { theme, ...settings } = payload;\n\n return replaceThemeSettings(global, theme, settings);\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, selectRightColumnContentKey } from '../../selectors';\nimport { HistoryWrapper } from '../../../util/history';\n\nconst MAX_STORED_EMOJIS = 18; // Represents two rows of recent emojis\n\naddReducer('toggleChatInfo', (global, actions, payload) => {\n const { noPushState } = payload;\n\n if (!noPushState) {\n if (global.isChatInfoShown) {\n HistoryWrapper.back();\n } else {\n HistoryWrapper.pushState({\n type: 'right',\n contentKey: selectRightColumnContentKey(global),\n });\n }\n }\n\n return {\n ...global,\n isChatInfoShown: !global.isChatInfoShown,\n };\n});\n\naddReducer('toggleManagement', (global, actions, payload): GlobalState | undefined => {\n const { chatId } = selectCurrentMessageList(global) || {};\n const { noPushState } = payload;\n\n if (!chatId) {\n return undefined;\n }\n\n const { isActive: prevIsActive } = global.management.byChatId[chatId] || {};\n\n if (!noPushState) {\n if (prevIsActive) {\n HistoryWrapper.back();\n } else {\n HistoryWrapper.pushState({\n type: 'right',\n contentKey: selectRightColumnContentKey(global),\n });\n }\n }\n\n return {\n ...global,\n management: {\n byChatId: {\n ...global.management.byChatId,\n [chatId]: {\n ...global.management.byChatId[chatId],\n isActive: !prevIsActive,\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('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\naddReducer('toggleSafeLinkModal', (global, actions, payload) => {\n const { url: safeLinkModalUrl } = payload;\n\n return {\n ...global,\n safeLinkModalUrl,\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 { 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 = 100;\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 runDebouncedForLoadFullChat = 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 })();\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 runDebouncedForLoadFullChat(() => loadFullChat(chat));\n }\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\n\naddReducer('setActiveChatFolder', (global, actions, payload) => {\n return {\n ...global,\n chatFolders: {\n ...global.chatFolders,\n activeChatFolder: payload,\n },\n };\n});\n\naddReducer('loadMoreMembers', (global) => {\n (async () => {\n const { chatId } = selectCurrentMessageList(global) || {};\n const chat = chatId ? selectChat(global, chatId) : undefined;\n if (!chat || isChatBasicGroup(chat)) {\n return;\n }\n\n const offset = (chat.fullInfo && chat.fullInfo.members && chat.fullInfo.members.length) || undefined;\n const result = await callApi('fetchMembers', chat.id, chat.accessHash!, 'recent', offset);\n if (!result) {\n return;\n }\n\n const { members, users } = result;\n if (!members || !members.length) {\n return;\n }\n\n global = getGlobal();\n global = addUsers(global, buildCollectionByKey(users, 'id'));\n global = updateChat(global, chat.id, {\n fullInfo: {\n ...chat.fullInfo,\n members: [\n ...((chat.fullInfo || {}).members || []),\n ...(members || []),\n ],\n },\n });\n setGlobal(global);\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, throttle } from '../../../util/schedulers';\nimport { copyTextToClipboard } from '../../../util/clipboard';\n\nconst uploadProgressCallbacks = new Map<number, ApiOnProgress>();\n\nconst runThrottledForMarkRead = throttle((cb) => cb(), 1000, true);\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, noWebPage: selectNoWebPage(global, chatId, threadId),\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 runThrottledForMarkRead(() => {\n void callApi('markMessageListRead', { chat, threadId, maxId });\n });\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,\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 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 });\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 chatIds: localChats.map(({ id }) => id),\n userIds: localUsers.map(({ id }) => id),\n },\n globalResults: {\n ...global.globalSearch.globalResults,\n chatIds: globalUsers.map(({ id }) => id),\n userIds: globalChats.map(({ id }) => id),\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, selectChatMessage,\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 const { chatId: audioChatId, messageId: audioMessageId } = global.audioPlayer;\n if (audioChatId && audioMessageId && !selectChatMessage(global, audioChatId, audioMessageId)) {\n getDispatch().closeAudioPlayer();\n }\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 { isChatPrivate } from '../../helpers';\nimport { callApi } from '../../../api/gramjs';\nimport { selectChat, selectUser } from '../../selectors';\nimport {\n addChats, addUsers, updateChat, 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\naddReducer('loadProfilePhotos', (global, actions, payload) => {\n const { profileId } = payload!;\n const isPrivate = isChatPrivate(profileId);\n const user = isPrivate ? selectUser(global, profileId) : undefined;\n const chat = !isPrivate ? selectChat(global, profileId) : undefined;\n\n (async () => {\n const result = await callApi('fetchProfilePhotos', user, chat);\n if (!result || !result.photos) {\n return;\n }\n\n let newGlobal = getGlobal();\n if (isPrivate) {\n newGlobal = updateUser(newGlobal, profileId, { photos: result.photos });\n } else {\n newGlobal = addUsers(newGlobal, buildCollectionByKey(result.users!, 'id'));\n newGlobal = updateChat(newGlobal, profileId, { photos: result.photos });\n }\n\n setGlobal(newGlobal);\n })();\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('loadNotificationExceptions', () => {\n callApi('fetchNotificationExceptions');\n});\n\naddReducer('loadNotificationSettings', () => {\n (async () => {\n const result = await callApi('fetchNotificationSettings');\n if (!result) {\n return;\n }\n\n setGlobal(replaceSettings(getGlobal(), result));\n })();\n});\n\naddReducer('updateNotificationSettings', (global, actions, payload) => {\n const { peerType, isSilent, shouldShowPreviews } = payload!;\n\n (async () => {\n const result = await callApi('updateNotificationSettings', peerType, { isSilent, shouldShowPreviews });\n\n if (!result) {\n return;\n }\n\n setGlobal(updateNotifySettings(getGlobal(), peerType, isSilent, shouldShowPreviews));\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 actions.toggleSafeLinkModal({ url: 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, MAIN_THREAD_ID } from '../../../api/types';\n\nimport { ARCHIVED_FOLDER_ID, MAX_ACTIVE_PINNED_CHATS } from '../../../config';\nimport { pick } from '../../../util/iteratees';\nimport { showNewMessageNotification } from '../../../util/notifications';\nimport { updateAppBadge } from '../../../util/appBadge';\nimport {\n updateChat,\n replaceChatListIds,\n updateChatListIds,\n updateChatListType,\n} from '../../reducers';\nimport {\n selectChat,\n selectCommonBoxChatId,\n selectIsChatListed,\n selectChatListType,\n selectCurrentMessageList,\n selectCountNotMutedUnread,\n} from '../../selectors';\nimport { throttle } from '../../../util/schedulers';\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;\nconst runThrottledForUpdateAppBadge = throttle((cb) => cb(), CURRENT_CHAT_UNREAD_DELAY, true);\n\naddReducer('apiUpdate', (global, actions, update: ApiUpdate) => {\n switch (update['@type']) {\n case 'updateChat': {\n if (!update.noTopChatsRequest && !selectIsChatListed(global, update.id)) {\n // Chat can appear in dialogs list.\n actions.loadTopChats();\n }\n\n const newGlobal = updateChat(global, update.id, update.chat, update.newProfilePhoto);\n setGlobal(newGlobal);\n\n const unreadCount = selectCountNotMutedUnread(newGlobal);\n runThrottledForUpdateAppBadge(() => updateAppBadge(unreadCount));\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, threadId, type: messageListType } = 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 const isActiveChat = (\n messageListType === 'thread'\n && threadId === MAIN_THREAD_ID\n && update.chatId === currentChatId\n );\n\n if (isActiveChat) {\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 const unreadCount = selectCountNotMutedUnread(getGlobal());\n updateAppBadge(unreadCount);\n showNewMessageNotification({ chat, message, isActiveChat });\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 case 'deleteProfilePhotos': {\n const { chatId, ids } = update;\n const chat = global.chats.byId[chatId];\n\n if (chat && chat.photos) {\n setGlobal(updateChat(global, chatId, {\n photos: chat.photos.filter((photo) => !ids.includes(photo.id)),\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 selectViewportIds,\n selectFirstUnreadId,\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].sort((a, b) => b - a)\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 {\n chatId, threadId, threadInfo, firstMessageId,\n } = 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\n if (firstMessageId) {\n global = replaceThreadParam(global, chatId, threadId, 'firstMessageId', firstMessageId);\n }\n\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 // Always keep the first uread message in the viewport list\n const firstUnreadId = selectFirstUnreadId(global, chatId, MAIN_THREAD_ID);\n const newGlobal = addViewportId(global, chatId, MAIN_THREAD_ID, id);\n const newViewportIds = selectViewportIds(newGlobal, chatId, MAIN_THREAD_ID);\n\n if (!firstUnreadId || newViewportIds!.includes(firstUnreadId)) {\n global = newGlobal;\n }\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 '../../../util/schedulers';\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, setGlobal } from '../../../lib/teact/teactn';\n\nimport { ApiUpdate } from '../../../api/types';\nimport { GlobalState } from '../../../global/types';\nimport { addNotifyException, updateChat, 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.shouldShowPreviews);\n }\n\n case 'updateNotifyExceptions': {\n const {\n id, isMuted, isSilent, shouldShowPreviews,\n } = update;\n const chat = global.chats.byId[id];\n\n if (chat) {\n global = updateChat(global, id, { isMuted });\n }\n\n setGlobal(addNotifyException(global, id, { isMuted, isSilent, shouldShowPreviews }));\n break;\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 inactive?: boolean;\n noAnimation?: 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 inactive,\n noAnimation,\n onChange,\n onCheck,\n}) => {\n const handleChange = useCallback((e: ChangeEvent<HTMLInputElement>) => {\n if (onChange) {\n onChange(e);\n }\n\n if (onCheck) {\n onCheck(e.currentTarget.checked);\n }\n }, [onChange, onCheck]);\n\n const className = buildClassName(\n 'Switcher',\n disabled && 'disabled',\n inactive && 'inactive',\n noAnimation && 'no-animation',\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, useState,\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 { APP_NAME, APP_VERSION, FEEDBACK_URL } 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';\nimport useHistoryBack from '../../../hooks/useHistoryBack';\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 shouldSkipTransition?: boolean;\n onSearchQuery: (query: string) => void;\n onSelectSettings: () => void;\n onSelectContacts: () => void;\n onSelectArchived: () => void;\n onReset: () => void;\n onOpenMenu: NoneToVoidFunction;\n onCloseMenu: NoneToVoidFunction;\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];\nconst MENU_ANIMATION_DURATION = 300;\n\nconst LEGACY_VERSION = 'https://web.telegram.org/';\nconst WEBK_VERSION = 'https://web.telegram.org/k/';\n\nconst LeftMainHeader: FC<OwnProps & StateProps & DispatchProps> = ({\n content,\n contactsFilter,\n onSearchQuery,\n onSelectSettings,\n onSelectContacts,\n onSelectArchived,\n onOpenMenu,\n onCloseMenu,\n setGlobalSearchChatId,\n onReset,\n searchQuery,\n isLoading,\n shouldSkipTransition,\n currentUserId,\n globalSearchChatId,\n searchDate,\n theme,\n animationLevel,\n chatsById,\n openChat,\n openTipsChat,\n setGlobalSearchDate,\n setSettingOption,\n}) => {\n const lang = useLang();\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 ? lang('AccDescrOpenMenu2') : 'Return to chat list'}\n >\n <div className={buildClassName(\n 'animated-menu-icon',\n !hasMenu && 'state-back',\n shouldSkipTransition && 'no-animation',\n )}\n />\n </Button>\n );\n }, [hasMenu, lang, onReset, shouldSkipTransition]);\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\n setSettingOption({ theme: newTheme });\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 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 const [forceOpenDropdown, setForceOpenDropdown] = useState(false);\n\n useHistoryBack((event, noAnimation, previousHistoryState) => {\n if (previousHistoryState && previousHistoryState.type === 'left' && previousHistoryState.isMenuOpen\n && noAnimation) {\n setForceOpenDropdown(true);\n setTimeout(() => setForceOpenDropdown(false), MENU_ANIMATION_DURATION);\n }\n });\n\n return (\n <div className=\"LeftMainHeader\">\n <div id=\"LeftMainHeader\" className=\"left-header\">\n <DropdownMenu\n trigger={MainButton}\n footer={`${APP_NAME} ${APP_VERSION}`}\n forceOpen={forceOpenDropdown}\n onOpen={onOpenMenu}\n onClose={onCloseMenu}\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\">{lang('lng_menu_night_mode')}</span>\n <Switcher\n id=\"darkmode\"\n label={lang(theme === 'dark' ? 'lng_settings_disable_night_theme' : 'lng_settings_enable_night_theme')}\n checked={theme === 'dark'}\n noAnimation\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 {lang('TelegramFeatures')}\n </MenuItem>\n <MenuItem\n icon=\"bug\"\n href={FEEDBACK_URL}\n >\n Report Bug\n </MenuItem>\n <MenuItem\n icon=\"char-K\"\n href={WEBK_VERSION}\n >\n Switch to WebK\n </MenuItem>\n <MenuItem\n icon=\"char-W\"\n href={LEGACY_VERSION}\n >\n Switch to Webogram\n </MenuItem>\n </DropdownMenu>\n <SearchInput\n inputId=\"telegram-search-input\"\n parentContainerClassName=\"LeftSearch\"\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\" dir={lang.isRtl ? 'rtl' : undefined}>\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,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { ApiChat, ApiChatFolder, ApiUser } from '../../../api/types';\nimport { GlobalActions } from '../../../global/types';\nimport { NotifyException, NotifySettings } from '../../../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 { selectNotifyExceptions, selectNotifySettings } from '../../../modules/selectors';\nimport useShowTransition from '../../../hooks/useShowTransition';\nimport buildClassName from '../../../util/buildClassName';\nimport useThrottledMemo from '../../../hooks/useThrottledMemo';\nimport useLang from '../../../hooks/useLang';\nimport captureEscKeyListener from '../../../util/captureEscKeyListener';\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 notifySettings: NotifySettings;\n notifyExceptions?: Record<number, NotifyException>;\n orderedFolderIds?: number[];\n activeChatFolder: number;\n currentUserId?: number;\n lastSyncTime?: number;\n};\n\ntype DispatchProps = Pick<GlobalActions, 'loadChatFolders' | 'setActiveChatFolder' | 'openChat'>;\n\nconst INFO_THROTTLE = 3000;\nconst SAVED_MESSAGES_HOTKEY = '0';\n\nconst ChatFolders: FC<StateProps & DispatchProps> = ({\n chatsById,\n usersById,\n chatFoldersById,\n notifySettings,\n notifyExceptions,\n orderedFolderIds,\n activeChatFolder,\n currentUserId,\n lastSyncTime,\n loadChatFolders,\n setActiveChatFolder,\n openChat,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const transitionRef = useRef<HTMLDivElement>(null);\n\n const lang = useLang();\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, notifySettings, notifyExceptions) || {};\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, notifySettings, notifyExceptions]);\n\n const folderTabs = useMemo(() => {\n if (!displayedFolders || !displayedFolders.length) {\n return undefined;\n }\n\n return [\n { title: lang('FilterAllChats') },\n ...displayedFolders.map((folder) => ({\n title: folder.title,\n ...(folderCountersById && folderCountersById[folder.id]),\n })),\n ];\n }, [displayedFolders, folderCountersById, lang]);\n\n const handleSwitchTab = useCallback((index: number) => {\n setActiveChatFolder(index);\n }, [setActiveChatFolder]);\n\n // Prevent `activeTab` pointing at non-existing folder after update\n useEffect(() => {\n if (!folderTabs || !folderTabs.length) {\n return;\n }\n\n if (activeChatFolder >= folderTabs.length) {\n setActiveChatFolder(0);\n }\n }, [activeChatFolder, folderTabs, setActiveChatFolder]);\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 setActiveChatFolder(Math.min(activeChatFolder + 1, folderTabs.length - 1));\n } else if (direction === SwipeDirection.Right) {\n setActiveChatFolder(Math.max(0, activeChatFolder - 1));\n }\n }),\n });\n }, [activeChatFolder, folderTabs, setActiveChatFolder]);\n\n const isNotInAllTabRef = useRef();\n isNotInAllTabRef.current = activeChatFolder !== 0;\n useEffect(() => (isNotInAllTabRef.current ? captureEscKeyListener(() => {\n if (isNotInAllTabRef.current) {\n setActiveChatFolder(0);\n }\n }) : undefined), [activeChatFolder, setActiveChatFolder]);\n\n useEffect(() => {\n const handleKeyDown = (e: KeyboardEvent) => {\n if (e.metaKey && e.code.startsWith('Digit') && folderTabs) {\n const [, digit] = e.code.match(/Digit(\\d)/) || [];\n if (!digit) return;\n\n if (digit === SAVED_MESSAGES_HOTKEY) {\n openChat({ id: currentUserId });\n return;\n }\n\n const folder = Number(digit) - 1;\n if (folder > folderTabs.length - 1) return;\n\n setActiveChatFolder(folder);\n e.preventDefault();\n }\n };\n\n document.addEventListener('keydown', handleKeyDown, true);\n\n return () => {\n document.removeEventListener('keydown', handleKeyDown, true);\n };\n });\n\n const {\n shouldRender: shouldRenderPlaceholder, transitionClassNames,\n } = useShowTransition(!orderedFolderIds, undefined, true);\n\n function renderCurrentTab(isActive: boolean) {\n const activeFolder = Object.values(chatFoldersById)\n .find(({ title }) => title === folderTabs![activeChatFolder].title);\n\n if (!activeFolder || activeChatFolder === 0) {\n return <ChatList folderType=\"all\" isActive={isActive} />;\n }\n\n return (\n <ChatList\n folderType=\"folder\"\n folderId={activeFolder.id}\n noChatsText={lang('FilterNoChatsToDisplay')}\n isActive={isActive}\n />\n );\n }\n\n return (\n <div className=\"ChatFolders\">\n {folderTabs && folderTabs.length ? (\n <TabList tabs={folderTabs} activeTab={activeChatFolder} onSwitchTab={handleSwitchTab} />\n ) : shouldRenderPlaceholder ? (\n <div className={buildClassName('tabs-placeholder', transitionClassNames)} />\n ) : undefined}\n <Transition\n ref={transitionRef}\n name={lang.isRtl ? 'slide-reversed' : 'slide'}\n activeKey={activeChatFolder}\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 activeChatFolder,\n },\n currentUserId,\n lastSyncTime,\n } = global;\n\n return {\n chatsById,\n usersById,\n chatFoldersById,\n orderedFolderIds,\n lastSyncTime,\n notifySettings: selectNotifySettings(global),\n notifyExceptions: selectNotifyExceptions(global),\n activeChatFolder,\n currentUserId,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'loadChatFolders',\n 'setActiveChatFolder',\n 'openChat',\n ]),\n)(ChatFolders));\n","import React, { FC, memo } 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 memo(LeftSearchAsync);\n","import React, { FC, memo } 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 memo(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={lang(isMenuOpen ? 'Close' : 'NewMessageTitle')}\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}>{lang('NewMessageTitle')}</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 shouldSkipTransition?: boolean;\n onSearchQuery: (query: string) => void;\n onContentChange: (content: LeftColumnContent) => void;\n onReset: () => void;\n onOpenMenu: NoneToVoidFunction;\n onCloseMenu: NoneToVoidFunction;\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 shouldSkipTransition,\n onSearchQuery,\n onContentChange,\n onReset,\n onOpenMenu,\n onCloseMenu,\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 onOpenMenu={onOpenMenu}\n onCloseMenu={onCloseMenu}\n onReset={onReset}\n shouldSkipTransition={shouldSkipTransition}\n />\n <ConnectionState />\n <Transition\n name={shouldSkipTransition ? 'none' : 'zoom-fade'}\n renderCount={TRANSITION_RENDER_COUNT}\n activeKey={content}\n >\n {(isActive) => {\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 isActive={isActive}\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, memo } 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 memo(SettingsAsync);\n","import React, { FC, memo } 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 memo(NewChatAsync);\n","import React, { FC, memo } 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 memo(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 useHistoryBack from '../../hooks/useHistoryBack';\nimport useFlag from '../../hooks/useFlag';\n\nimport { IS_MOBILE_SCREEN } from '../../util/environment';\nimport captureEscKeyListener from '../../util/captureEscKeyListener';\nimport { pick } from '../../util/iteratees';\n\nimport Transition, { ANIMATION_DURATION } 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';\nimport { HistoryWrapper } from '../../util/history';\n\nimport './LeftColumn.scss';\n\ntype StateProps = {\n searchQuery?: string;\n searchDate?: number;\n activeChatFolder: 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 activeChatFolder,\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 const [isMenuOpen, openMenu, closeMenu] = useFlag();\n\n const setContentWithHistory = useCallback((contentKey: LeftColumnContent) => {\n if (contentKey !== LeftColumnContent.ChatList\n && contentKey !== LeftColumnContent.NewChannelStep2\n && contentKey !== LeftColumnContent.NewGroupStep2) {\n HistoryWrapper.pushState({\n type: 'left',\n contentKey,\n isMenuOpen,\n });\n }\n setContent(contentKey);\n }, [isMenuOpen]);\n\n const setSettingsScreenWithHistory = useCallback((screen: SettingsScreens, noPushState = false) => {\n setSettingsScreen(screen);\n if (!noPushState) {\n HistoryWrapper.pushState({\n type: 'left',\n contentKey: LeftColumnContent.Settings,\n screen,\n isMenuOpen,\n });\n }\n }, [isMenuOpen]);\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, noPushState = false) => {\n if (\n content === LeftColumnContent.NewGroupStep2\n && !forceReturnToChatList\n ) {\n if (!noPushState) HistoryWrapper.back();\n setContentWithHistory(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 if (!noPushState) {\n HistoryWrapper.back();\n }\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 setSettingsScreenWithHistory(SettingsScreens.Main, noPushState);\n return;\n\n case SettingsScreens.GeneralChatBackground:\n setSettingsScreenWithHistory(SettingsScreens.General, noPushState);\n return;\n case SettingsScreens.GeneralChatBackgroundColor:\n setSettingsScreenWithHistory(SettingsScreens.GeneralChatBackground, noPushState);\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 setSettingsScreenWithHistory(SettingsScreens.Privacy, noPushState);\n return;\n case SettingsScreens.PrivacyPhoneNumberAllowedContacts:\n case SettingsScreens.PrivacyPhoneNumberDeniedContacts:\n setSettingsScreenWithHistory(SettingsScreens.PrivacyPhoneNumber, noPushState);\n return;\n case SettingsScreens.PrivacyLastSeenAllowedContacts:\n case SettingsScreens.PrivacyLastSeenDeniedContacts:\n setSettingsScreenWithHistory(SettingsScreens.PrivacyLastSeen, noPushState);\n return;\n case SettingsScreens.PrivacyProfilePhotoAllowedContacts:\n case SettingsScreens.PrivacyProfilePhotoDeniedContacts:\n setSettingsScreenWithHistory(SettingsScreens.PrivacyProfilePhoto, noPushState);\n return;\n case SettingsScreens.PrivacyForwardingAllowedContacts:\n case SettingsScreens.PrivacyForwardingDeniedContacts:\n setSettingsScreenWithHistory(SettingsScreens.PrivacyForwarding, noPushState);\n return;\n case SettingsScreens.PrivacyGroupChatsAllowedContacts:\n case SettingsScreens.PrivacyGroupChatsDeniedContacts:\n setSettingsScreenWithHistory(SettingsScreens.PrivacyGroupChats, noPushState);\n return;\n case SettingsScreens.TwoFaNewPassword:\n setSettingsScreenWithHistory(SettingsScreens.TwoFaDisabled, noPushState);\n return;\n case SettingsScreens.TwoFaNewPasswordConfirm:\n setSettingsScreenWithHistory(SettingsScreens.TwoFaNewPassword, noPushState);\n return;\n case SettingsScreens.TwoFaNewPasswordHint:\n setSettingsScreenWithHistory(SettingsScreens.TwoFaNewPasswordConfirm, noPushState);\n return;\n case SettingsScreens.TwoFaNewPasswordEmail:\n setSettingsScreenWithHistory(SettingsScreens.TwoFaNewPasswordHint, noPushState);\n return;\n case SettingsScreens.TwoFaNewPasswordEmailCode:\n setSettingsScreenWithHistory(SettingsScreens.TwoFaNewPasswordEmail, noPushState);\n return;\n case SettingsScreens.TwoFaChangePasswordCurrent:\n case SettingsScreens.TwoFaTurnOff:\n case SettingsScreens.TwoFaRecoveryEmailCurrentPassword:\n setSettingsScreenWithHistory(SettingsScreens.TwoFaEnabled, noPushState);\n return;\n case SettingsScreens.TwoFaChangePasswordNew:\n setSettingsScreenWithHistory(SettingsScreens.TwoFaChangePasswordCurrent, noPushState);\n return;\n case SettingsScreens.TwoFaChangePasswordConfirm:\n setSettingsScreenWithHistory(SettingsScreens.TwoFaChangePasswordNew, noPushState);\n return;\n case SettingsScreens.TwoFaChangePasswordHint:\n setSettingsScreenWithHistory(SettingsScreens.TwoFaChangePasswordConfirm, noPushState);\n return;\n case SettingsScreens.TwoFaRecoveryEmail:\n setSettingsScreenWithHistory(SettingsScreens.TwoFaRecoveryEmailCurrentPassword, noPushState);\n return;\n case SettingsScreens.TwoFaRecoveryEmailCode:\n setSettingsScreenWithHistory(SettingsScreens.TwoFaRecoveryEmail, noPushState);\n return;\n\n case SettingsScreens.FoldersCreateFolder:\n case SettingsScreens.FoldersEditFolder:\n setSettingsScreenWithHistory(SettingsScreens.Folders, noPushState);\n return;\n default:\n break;\n }\n }\n\n if (!noPushState) {\n HistoryWrapper.back();\n }\n\n if (content === LeftColumnContent.ChatList && activeChatFolder === 0) {\n setContentWithHistory(LeftColumnContent.GlobalSearch);\n return;\n }\n\n setContentWithHistory(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 }, [\n content, activeChatFolder, setContentWithHistory, settingsScreen, setSettingsScreenWithHistory,\n setGlobalSearchQuery, setGlobalSearchDate, setGlobalSearchChatId, resetChatCreation,\n ]);\n\n const [shouldSkipTransition, setShouldSkipTransition] = useState(false);\n useHistoryBack((event, noAnimation, previousHistoryState) => {\n if (previousHistoryState && previousHistoryState.type === 'left') {\n if (noAnimation) {\n setShouldSkipTransition(true);\n setTimeout(() => {\n setShouldSkipTransition(false);\n }, ANIMATION_DURATION[IS_MOBILE_SCREEN ? 'slide-layers' : 'push-slide']);\n }\n handleReset(false, true);\n }\n });\n\n const handleSearchQuery = useCallback((query: string) => {\n if (content === LeftColumnContent.Contacts) {\n setContactsFilter(query);\n return;\n }\n\n setContentWithHistory(LeftColumnContent.GlobalSearch);\n\n if (query !== searchQuery) {\n setGlobalSearchQuery({ query });\n }\n }, [content, setContentWithHistory, searchQuery, setGlobalSearchQuery]);\n\n useEffect(\n () => (content !== LeftColumnContent.ChatList || activeChatFolder === 0\n ? captureEscKeyListener(() => handleReset())\n : undefined),\n [activeChatFolder, 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={shouldSkipTransition ? 'none' : IS_MOBILE_SCREEN ? 'slide-layers' : 'push-slide'}\n renderCount={RENDER_COUNT}\n activeKey={contentType}\n >\n {(isActive) => {\n switch (contentType) {\n case ContentType.Archived:\n return (\n <ArchivedChats\n isActive={isActive}\n onReset={handleReset}\n />\n );\n case ContentType.Settings:\n return (\n <Settings\n currentScreen={settingsScreen}\n onScreenSelect={setSettingsScreenWithHistory}\n onReset={handleReset}\n shouldSkipTransition={shouldSkipTransition}\n />\n );\n case ContentType.NewChannel:\n return (\n <NewChat\n key={lastResetTime}\n isChannel\n content={content}\n onContentChange={setContentWithHistory}\n onReset={handleReset}\n />\n );\n case ContentType.NewGroup:\n return (\n <NewChat\n key={lastResetTime}\n content={content}\n onContentChange={setContentWithHistory}\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={setContentWithHistory}\n onSearchQuery={handleSearchQuery}\n onReset={handleReset}\n shouldSkipTransition={shouldSkipTransition}\n onOpenMenu={openMenu}\n onCloseMenu={closeMenu}\n />\n );\n }\n }}\n </Transition>\n );\n};\n\nexport default memo(withGlobal(\n (global): StateProps => {\n const {\n globalSearch: {\n query,\n date,\n },\n chatFolders: {\n activeChatFolder,\n },\n } = global;\n return { searchQuery: query, searchDate: date, activeChatFolder };\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 THROTTLE = 250;\n\nexport default () => {\n const [size, setSize] = useState<IDimensions>(windowSize.get());\n\n useEffect(() => {\n const handleResize = throttle(() => {\n setSize(windowSize.get());\n }, THROTTLE, false);\n\n window.addEventListener('resize', handleResize);\n\n return () => {\n window.removeEventListener('resize', handleResize);\n };\n }, []);\n\n return size;\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 React, { FC, memo } 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 memo(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 lang = useLang();\n const mediaThumbnail = useWebpThumbnail(message);\n const mediaBlobUrl = useMedia(getMessageMediaHash(message, 'pictogram'));\n\n const text = getMessageSummaryText(lang, 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 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} dir={lang.isRtl ? 'rtl' : undefined}>\n <PinnedMessageNavigation\n count={count}\n index={index}\n />\n {mediaThumbnail && renderPictogram(mediaThumbnail, mediaBlobUrl)}\n <div className=\"message-text\">\n <div className=\"title\" dir=\"auto\">\n {customTitle || `${lang('PinnedMessage')} ${index > 0 ? `#${count - index}` : ''}`}\n </div>\n <p dir=\"auto\">{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 {\n ApiAudio, ApiChat, ApiMessage, ApiUser,\n} 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 sender?: ApiChat | ApiUser;\n};\n\ntype DispatchProps = Pick<GlobalActions, 'focusMessage' | 'closeAudioPlayer'>;\n\nconst AudioPlayer: FC<OwnProps & StateProps & DispatchProps> = ({\n message, className, noUi, sender, focusMessage, closeAudioPlayer,\n}) => {\n const lang = useLang();\n\n const senderName = sender ? getSenderTitle(lang, sender) : undefined;\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 if (noUi) {\n return undefined;\n }\n\n const audio = getMessageAudio(message);\n\n return (\n <div className={buildClassName('AudioPlayer', className)} dir={lang.isRtl ? 'rtl' : undefined}>\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\" dir=\"auto\">{renderText(title || fileName)}</div>\n {performer && (\n <div className=\"subtitle\" dir=\"auto\">{renderText(performer)}</div>\n )}\n </>\n );\n}\n\nfunction renderVoice(subtitle: string, senderName?: string) {\n return (\n <>\n <div className=\"title\" dir=\"auto\">{senderName && renderText(senderName)}</div>\n <div className=\"subtitle\" dir=\"auto\">{subtitle}</div>\n </>\n );\n}\n\nexport default withGlobal<OwnProps>(\n (global, { message }): StateProps => {\n const sender = selectSender(global, message);\n\n return { sender };\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, ApiUser,\n} from '../../api/types';\nimport { NotifyException, NotifySettings } from '../../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 selectIsChatMuted,\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 selectNotifySettings,\n selectNotifyExceptions,\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 chat?: ApiChat;\n pinnedMessageIds?: number[] | number;\n messagesById?: Record<number, ApiMessage>;\n canUnpin?: boolean;\n topMessageSender?: ApiChat | ApiUser;\n typingStatus?: ApiTypingStatus;\n isSelectModeActive?: boolean;\n isLeftColumnShown?: boolean;\n isRightColumnShown?: boolean;\n audioMessage?: ApiMessage;\n chatsById?: Record<number, ApiChat>;\n originChatId: number;\n messagesCount?: number;\n isChatWithSelf?: boolean;\n isChatWithBot?: boolean;\n lastSyncTime?: number;\n notifySettings: NotifySettings;\n notifyExceptions?: Record<number, NotifyException>;\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 topMessageSender,\n typingStatus,\n isSelectModeActive,\n isLeftColumnShown,\n isRightColumnShown,\n audioMessage,\n chat,\n chatsById,\n originChatId,\n messagesCount,\n isChatWithSelf,\n isChatWithBot,\n lastSyncTime,\n notifySettings,\n notifyExceptions,\n openChatWithInfo,\n pinMessage,\n focusMessage,\n openChat,\n loadPinnedMessages,\n toggleLeftColumn,\n exitMessageSelectMode,\n}) => {\n const lang = useLang();\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 const chatTitleLength = chat && getChatTitle(lang, chat).length;\n const topMessageTitle = topMessageSender ? getSenderTitle(lang, topMessageSender) : undefined;\n\n useEffect(() => {\n if (threadId === MAIN_THREAD_ID && lastSyncTime) {\n loadPinnedMessages({ chatId });\n }\n }, [chatId, loadPinnedMessages, lastSyncTime, threadId]);\n\n // Reset pinned index when switching chats and pinning/unpinning\n useEffect(() => {\n setPinnedMessageIndex(0);\n }, [pinnedMessageIds]);\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, currentChat) => {\n if (isChatArchived(currentChat)) {\n return total;\n }\n\n const count = currentChat.unreadCount || 0;\n if (\n count && (!selectIsChatMuted(currentChat, notifySettings, notifyExceptions) || currentChat.unreadMentionsCount)\n ) {\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, notifySettings, notifyExceptions]);\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 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 noRtl\n />\n ) : (\n <GroupChatInfo\n chatId={chatId}\n typingStatus={typingStatus}\n noRtl\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 const state: StateProps = {\n typingStatus,\n isLeftColumnShown,\n isRightColumnShown: selectIsRightColumnShown(global),\n isSelectModeActive: selectIsInSelectMode(global),\n audioMessage,\n chat,\n chatsById,\n originChatId: originChat ? originChat.id : chatId,\n messagesCount,\n isChatWithSelf: selectIsChatWithSelf(global, chatId),\n isChatWithBot: chat && selectIsChatWithBot(global, chat),\n lastSyncTime,\n notifySettings: selectNotifySettings(global),\n notifyExceptions: selectNotifyExceptions(global),\n };\n\n const messagesById = selectChatMessages(global, chatId);\n if (messageListType !== 'thread' || !messagesById) {\n return state;\n }\n\n Object.assign(state, { messagesById });\n\n if (threadId !== MAIN_THREAD_ID) {\n const pinnedMessageId = selectThreadTopMessageId(global, chatId, threadId);\n const message = pinnedMessageId ? selectChatMessage(global, chatId, pinnedMessageId) : undefined;\n const topMessageSender = message ? selectForwardedSender(global, message) : undefined;\n\n return {\n ...state,\n pinnedMessageIds: pinnedMessageId,\n canUnpin: false,\n topMessageSender,\n };\n }\n\n const pinnedMessageIds = selectPinnedIds(global, chatId);\n if (pinnedMessageIds && pinnedMessageIds.length) {\n const firstPinnedMessage = messagesById[pinnedMessageIds[0]];\n const {\n canUnpin,\n } = (firstPinnedMessage && selectAllowedMessageActions(global, firstPinnedMessage, threadId)) || {};\n\n return {\n ...state,\n pinnedMessageIds,\n canUnpin,\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 focusingId?: number;\n loadMoreForwards?: NoneToVoidFunction;\n loadMoreBackwards?: NoneToVoidFunction;\n isViewportNewest?: boolean;\n firstUnreadId?: number;\n onFabToggle: AnyToVoidFunction;\n onNotchToggle: 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 focusingId,\n loadMoreForwards,\n loadMoreBackwards,\n isViewportNewest,\n firstUnreadId,\n onFabToggle,\n onNotchToggle,\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 toggleScrollTools = useCallback(() => {\n if (isFabFrozen) {\n return;\n }\n\n if (!messageIds || !messageIds.length) {\n onFabToggle(false);\n onNotchToggle(false);\n return;\n }\n\n if (!isViewportNewest) {\n onFabToggle(true);\n onNotchToggle(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 onNotchToggle(!isAtBottom);\n }, [messageIds, isViewportNewest, containerRef, onFabToggle, firstUnreadId, onNotchToggle]);\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') {\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 }, toggleScrollTools);\n\n useOnIntersect(fabTriggerRef, observeIntersectionForFab);\n\n const {\n observe: observeIntersectionForNotch,\n } = useIntersectionObserver({\n rootRef: containerRef,\n }, toggleScrollTools);\n\n useOnIntersect(fabTriggerRef, observeIntersectionForNotch);\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 // 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(toggleScrollTools, [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 />\n <div\n ref={fabTriggerRef}\n key=\"fab-trigger\"\n className=\"fab-trigger\"\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_WIDTH_WITH_TEXT_AND_COMMENTS = 238;\nconst MIN_MEDIA_HEIGHT = 90;\nconst SMALL_IMAGE_THRESHOLD = 12;\n\nexport function getMinMediaWidth(hasText?: boolean, hasCommentButton?: boolean) {\n return hasText\n ? (hasCommentButton ? MIN_MEDIA_WIDTH_WITH_TEXT_AND_COMMENTS : MIN_MEDIA_WIDTH_WITH_TEXT)\n : 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, memo } 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 memo(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 isLastInList?: boolean;\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 isLastInList,\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 const lang = 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 lang,\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 const className = buildClassName(\n 'ActionMessage message-list-item',\n isFocused && !noFocusHighlight && 'focused',\n isContextMenuShown && 'has-menu-open',\n isLastInList && 'last-in-list',\n transitionClassNames,\n );\n\n return (\n <div\n ref={ref}\n id={`message${message.id}`}\n className={className}\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 getMessageRoundVideo,\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 const isRoundVideo = Boolean(message && getMessageRoundVideo(message));\n\n const lang = useLang();\n\n const senderTitle = sender && getSenderTitle(lang, 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, isRoundVideo)}\n <div className=\"message-text\">\n <p dir=\"auto\">\n {!message ? (\n customText || NBSP\n ) : isActionMessage(message) ? (\n <ActionMessage message={message} isEmbedded />\n ) : (\n renderText(getMessageSummaryText(lang, message, Boolean(mediaThumbnail)))\n )}\n </p>\n <div className=\"message-title\" dir=\"auto\">{renderText(senderTitle || title || NBSP)}</div>\n </div>\n </div>\n );\n};\n\nfunction renderPictogram(\n id: string | undefined,\n thumbDataUri: string,\n blobUrl?: string,\n isRoundVideo?: boolean,\n) {\n const { width, height } = getPictogramDimensions();\n\n return (\n <img\n id={id}\n src={blobUrl || thumbDataUri}\n width={width}\n height={height}\n alt=\"\"\n className={isRoundVideo ? 'round' : ''}\n />\n );\n}\n\nexport default EmbeddedMessage;\n","import React, { FC, memo } 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\" dir={lang.isRtl ? 'rtl' : 'ltr'} 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 memo(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 { IS_CANVAS_FILTER_SUPPORTED, IS_MOBILE_SCREEN } from '../../../../util/environment';\nimport { getMessageMediaThumbDataUri } from '../../../../modules/helpers';\nimport useCanvasBlur from '../../../../hooks/useCanvasBlur';\n\nexport default function useBlurredMediaThumbRef(message: ApiMessage, fullMediaData?: string) {\n return useCanvasBlur(\n getMessageMediaThumbDataUri(message),\n Boolean(fullMediaData),\n IS_MOBILE_SCREEN && !IS_CANVAS_FILTER_SUPPORTED,\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 useBlurredMediaThumbRef from './hooks/useBlurredMediaThumbRef';\nimport usePrevious from '../../../hooks/usePrevious';\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 nonInteractive?: 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 nonInteractive,\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 thumbRef = useBlurredMediaThumbRef(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 && !nonInteractive && 'interactive',\n isSmall && 'small-image',\n width === height && 'square-image',\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 <canvas\n ref={thumbRef}\n className=\"thumbnail\"\n // @ts-ignore teact feature\n style={`width: ${width}px; height: ${height}px`}\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 { useCallback, useRef } from '../../../../lib/teact/teact';\nimport { fastRaf } from '../../../../util/schedulers';\nimport useBackgroundMode from '../../../../hooks/useBackgroundMode';\nimport safePlay from '../../../../util/safePlay';\n\nexport default (playerRef: { current: HTMLVideoElement | null }, isPlayAllowed = false) => {\n const wasPlaying = useRef(false);\n const isFrozen = useRef(false);\n\n const freezePlaying = useCallback(() => {\n isFrozen.current = true;\n\n if (!isPlayAllowed || !playerRef.current) {\n return;\n }\n\n if (!wasPlaying.current) {\n wasPlaying.current = !playerRef.current.paused;\n }\n\n playerRef.current.pause();\n }, [isPlayAllowed, playerRef]);\n\n const unfreezePlaying = useCallback(() => {\n // At this point HTMLVideoElement can be unmounted from the DOM\n if (isPlayAllowed && playerRef.current && wasPlaying.current && document.body.contains(playerRef.current)) {\n safePlay(playerRef.current);\n }\n\n wasPlaying.current = false;\n isFrozen.current = false;\n }, [isPlayAllowed, playerRef]);\n\n const unfreezePlayingOnRaf = useCallback(() => {\n fastRaf(unfreezePlaying);\n }, [unfreezePlaying]);\n\n if (!document.hasFocus()) {\n freezePlaying();\n }\n\n useBackgroundMode(freezePlaying, unfreezePlayingOnRaf);\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 useVideoCleanup from '../../../hooks/useVideoCleanup';\nimport usePauseOnInactive from './hooks/usePauseOnInactive';\nimport useBlurredMediaThumbRef from './hooks/useBlurredMediaThumbRef';\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 thumbRef = useBlurredMediaThumbRef(message);\n const { mediaData, downloadProgress } = useMediaWithDownloadProgress(\n getMessageMediaHash(message, 'inline'),\n !shouldDownload,\n getMessageMediaFormat(message, 'inline'),\n lastSyncTime,\n );\n\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, Boolean(isInline && shouldAutoPlay));\n\n usePauseOnInactive(videoRef, isPlayAllowed);\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 videoClassName = buildClassName('full-media', transitionClassNames);\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 {(!isInline || shouldRenderThumb)\n && (\n <canvas\n ref={thumbRef}\n className=\"thumbnail\"\n // @ts-ignore teact feature\n style={`width: ${width}px; height: ${height}px;`}\n />\n )}\n {previewBlobUrl && (\n <img\n src={previewBlobUrl}\n className=\"thumbnail\"\n // @ts-ignore teact feature\n style={`width: ${width}px; height: ${height}px;`}\n alt=\"\"\n />\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 // 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\" dir=\"ltr\">\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\" dir=\"auto\">\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, { LangFn } 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_CONTAINER_ID = '#middle-column-portals';\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 containerId={SOLUTION_CONTAINER_ID}\n />\n )\n );\n }\n\n return (\n <div className=\"Poll\" dir={lang.isRtl ? 'auto' : 'ltr'}>\n {renderSolution()}\n <div className=\"poll-question\">{renderText(summary.question)}</div>\n <div className=\"poll-type\">\n {lang(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(lang, 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 ? 'QuizPoll' : 'AnonymousQuizPoll';\n }\n\n if (summary.closed) {\n return 'FinalResults';\n }\n\n return summary.isPublic ? 'PublicPoll' : 'AnonymousPoll';\n}\n\nfunction getReadableVotersCount(lang: LangFn, isQuiz: true | undefined, count?: number) {\n if (!count) {\n return lang(isQuiz ? 'Chat.Quiz.TotalVotesEmpty' : 'Chat.Poll.TotalVotesResultEmpty');\n }\n\n return lang(isQuiz ? 'Answer' : 'Vote', count, 'i');\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';\nimport { ObserveFn } from '../../../hooks/useIntersectionObserver';\n\nimport { getMessageWebPage } from '../../../modules/helpers';\nimport { calculateMediaDimensions } from './helpers/mediaDimensions';\nimport renderText from '../../common/helpers/renderText';\nimport trimText from '../../../util/trimText';\nimport buildClassName from '../../../util/buildClassName';\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 onMediaClick!();\n }, [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 isMediaInteractive = photo && onMediaClick && !isSquarePhoto && !webPage.hasDocument;\n const truncatedDescription = trimText(description, MAX_TEXT_LENGTH);\n\n const className = buildClassName(\n 'WebPage',\n photo\n ? (isSquarePhoto && 'with-square-photo')\n : (!inPreview && 'without-photo'),\n );\n\n return (\n <div\n className={className}\n data-initial={(siteName || displayUrl)[0]}\n dir=\"auto\"\n >\n {photo && (\n <Photo\n message={message}\n observeIntersection={observeIntersection}\n shouldAutoLoad={shouldAutoLoad}\n size={isSquarePhoto ? 'pictogram' : 'inline'}\n nonInteractive={!isMediaInteractive}\n onClick={isMediaInteractive ? handleMediaClick : undefined}\n onCancelUpload={onCancelMediaTransfer}\n />\n )}\n <div className=\"WebPage-text\">\n <SafeLink className=\"site-name\" url={url} text={siteName || displayUrl} />\n {!inPreview && 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 usePauseOnInactive from './hooks/usePauseOnInactive';\nimport useBlurredMediaThumbRef from './hooks/useBlurredMediaThumbRef';\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 thumbRef = useBlurredMediaThumbRef(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 usePauseOnInactive(playerRef, Boolean(mediaData));\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 capturePlaying();\n playerEl.currentTime = 0;\n setIsActivated(true);\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 <canvas\n ref={thumbRef}\n className=\"thumbnail\"\n // @ts-ignore teact feature\n style={`width: ${ROUND_VIDEO_DIMENSIONS}px; height: ${ROUND_VIDEO_DIMENSIONS}px`}\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 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.type === 'url' && <i className=\"icon-arrow-right\" />}\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 { formatIntegerCompact } from '../../../util/textFormat';\nimport buildClassName from '../../../util/buildClassName';\nimport { selectThreadInfo } from '../../../modules/selectors';\nimport useLang from '../../../hooks/useLang';\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 lang = useLang();\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\" dir={lang.isRtl ? 'rtl' : 'ltr'}>\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 dir={lang.isRtl ? 'rtl' : 'ltr'}\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\" dir=\"auto\">\n {messagesCount ? lang('Comments', messagesCount, 'i') : lang('LeaveAComment')}\n </div>\n <i className=\"icon-next\" />\n </div>\n );\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 CommentButton 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;\nconst NO_MEDIA_CORNERS_THRESHOLD = 18;\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, false, true);\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 const withCommentButton = message.threadInfo && (!isInDocumentGroup || isLastInDocumentGroup)\n && messageListType === 'thread' && !noComments;\n const withAppendix = contentClassName.includes('has-appendix');\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, withAppendix]);\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 let noMediaCorners = false;\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), withCommentButton), width);\n if (calculatedWidth - width > NO_MEDIA_CORNERS_THRESHOLD) {\n noMediaCorners = true;\n }\n }\n } else if (albumLayout) {\n calculatedWidth = Math.max(getMinMediaWidth(Boolean(text), withCommentButton), albumLayout.containerStyle.width);\n if (calculatedWidth - albumLayout.containerStyle.width > NO_MEDIA_CORNERS_THRESHOLD) {\n noMediaCorners = true;\n }\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 noMediaCorners && 'no-media-corners',\n );\n const hasCustomAppendix = isLastInGroup && !textParts && !asForwarded && !hasThread;\n const shouldInlineMeta = !webPage && !animatedEmoji && textParts;\n\n return (\n <div className={className} onDoubleClick={handleContentDoubleClick} dir=\"auto\">\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 && (\n <p className={`text-content ${shouldInlineMeta ? 'with-meta' : ''}`} dir=\"auto\">\n {textParts}\n {shouldInlineMeta && (\n <MessageMeta\n message={message}\n outgoingStatus={outgoingStatus}\n signature={signature}\n onClick={handleMessageSelect}\n />\n )}\n </p>\n )}\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(lang, 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\" dir=\"ltr\">\n {senderTitle ? (\n <span\n className={buildClassName(senderPeer && 'interactive', senderColor)}\n onClick={senderPeer ? handleSenderClick : undefined}\n dir=\"auto\"\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\" dir=\"auto\">{lang('DiscussChannel')}</span>\n ) : message.adminTitle && !isChannel ? (\n <span className=\"admin-title\" dir=\"auto\">{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\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 dir=\"auto\"\n >\n {withAppendix && (<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) && !(!webPage && !animatedEmoji && textParts) && (\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={lang('lng_context_forward_msg')}\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 {withCommentButton && <CommentButton message={message} disabled={noComments} />}\n {contentClassName.includes('has-appendix') && <div className=\"svg-appendix\" ref={appendixRef} />}\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, 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_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} from '../../modules/helpers';\nimport {\n compact,\n flatten,\n orderBy,\n pick,\n} from '../../util/iteratees';\nimport {\n fastRaf, debounce, 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, { isAnimatingScroll } from '../../util/fastSmoothScroll';\nimport renderText from '../common/helpers/renderText';\nimport useLang, { LangFn } from '../../hooks/useLang';\nimport useWindowSize from '../../hooks/useWindowSize';\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 canPost: boolean;\n onFabToggle: (shouldShow: boolean) => void;\n onNotchToggle: (shouldShow: boolean) => void;\n hasTools?: boolean;\n};\n\ntype StateProps = {\n isChatLoaded?: boolean;\n isChannelChat?: 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);\n\nconst MessageList: FC<OwnProps & StateProps & DispatchProps> = ({\n chatId,\n threadId,\n type,\n hasTools,\n onFabToggle,\n onNotchToggle,\n isChatLoaded,\n isChannelChat,\n canPost,\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 const memoUnreadDividerBeforeIdRef = useRef<number | undefined>();\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\n // Updated only once (to preserve divider even after messages are read)\n if (!memoUnreadDividerBeforeIdRef.current) {\n memoUnreadDividerBeforeIdRef.current = firstUnreadId;\n }\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 // Memorize height for scroll animation\n const { height: windowHeight } = useWindowSize();\n useEffect(() => {\n containerRef.current!.dataset.normalHeight = String(containerRef.current!.offsetHeight);\n }, [windowHeight]);\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 // Remember scroll position before repositioning it\n useOnChange(() => {\n if (!messageIds || !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 // This should match deps for `useLayoutEffectWithPrevDeps` below\n }, [messageIds, isViewportNewest, containerHeight, hasTools]);\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 const isAlreadyFocusing = messageIds && memoFocusingIdRef.current === messageIds[messageIds.length - 1];\n\n if (isAtBottom && hasLastMessageChanged && !hasFirstMessageChanged && !isAlreadyFocusing) {\n if (lastItemElement) {\n fastRaf(() => {\n fastSmoothScroll(\n container,\n lastItemElement,\n 'end',\n BOTTOM_FOCUS_MARGIN,\n undefined,\n undefined,\n undefined,\n true,\n );\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 if (isAnimatingScroll()) {\n return;\n }\n\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 // This should match deps for `useOnChange` above\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 && 'no-composer',\n type === 'pinned' && 'type-pinned',\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 focusingId={focusingId}\n loadMoreForwards={loadMoreForwards}\n loadMoreBackwards={loadMoreBackwards}\n isViewportNewest={isViewportNewest}\n firstUnreadId={firstUnreadId}\n onFabToggle={onFabToggle}\n onNotchToggle={onNotchToggle}\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 const isLastInList = (\n senderGroupIndex === senderGroupsArray.length - 1\n && dateGroupIndex === dateGroupsArray.length - 1\n );\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 isLastInList={isLastInList}\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 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 message.id === memoFirstUnreadIdRef.current ? unreadDivider : undefined,\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 dir=\"auto\">\n {isSchedule && dateGroup.originalDate === SCHEDULED_WHEN_ONLINE && (\n lang('MessageScheduledUntilOnline')\n )}\n {isSchedule && dateGroup.originalDate !== SCHEDULED_WHEN_ONLINE && (\n lang('MessageScheduledOn', formatHumanDate(lang, dateGroup.datetime, undefined, true))\n )}\n {!isSchedule && formatHumanDate(lang, 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 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 { formatIntegerCompact } from '../../util/textFormat';\nimport buildClassName from '../../util/buildClassName';\nimport { pick } from '../../util/iteratees';\nimport fastSmoothScroll from '../../util/fastSmoothScroll';\nimport useLang from '../../hooks/useLang';\n\nimport Button from '../ui/Button';\n\nimport './ScrollDownButton.scss';\n\ntype OwnProps = {\n isShown: boolean;\n canPost?: boolean;\n};\n\ntype StateProps = {\n messageListType?: MessageListType;\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 canPost,\n messageListType,\n unreadCount,\n focusLastMessage,\n}) => {\n const lang = useLang();\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 messageElements = messagesContainer.querySelectorAll<HTMLDivElement>('.message-list-item');\n const lastMessageElement = messageElements[messageElements.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={lang('AccDescrPageDown')}\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\n return {\n messageListType,\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, inputId?: 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, input ? input.id : undefined);\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, memo } 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 memo(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, memo } 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 memo(AttachMenuAsync);\n","import React, { FC, memo } 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 memo(SymbolMenuAsync);\n","import React, { FC, memo } from '../../../lib/teact/teact';\nimport { OwnProps } from './MentionTooltip';\nimport { Bundles } from '../../../util/moduleLoader';\n\nimport useModuleLoader from '../../../hooks/useModuleLoader';\n\nconst MentionTooltipAsync: FC<OwnProps> = (props) => {\n const { isOpen } = props;\n const MentionTooltip = useModuleLoader(Bundles.Extra, 'MentionTooltip', !isOpen);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return MentionTooltip ? <MentionTooltip {...props} /> : undefined;\n};\n\nexport default memo(MentionTooltipAsync);\n","import React, { FC, memo } 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 memo(CustomSendMenuAsync);\n","import React, { FC } from '../../../lib/teact/teact';\nimport { OwnProps } from './StickerTooltip';\nimport { Bundles } from '../../../util/moduleLoader';\n\nimport useModuleLoader from '../../../hooks/useModuleLoader';\n\nconst StickerTooltipAsync: FC<OwnProps> = (props) => {\n const { isOpen } = props;\n const StickerTooltip = useModuleLoader(Bundles.Extra, 'StickerTooltip', !isOpen);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return StickerTooltip ? <StickerTooltip {...props} /> : undefined;\n};\n\nexport default StickerTooltipAsync;\n","import React, { FC, memo } 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 memo(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, memo } 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 memo(AttachmentModalAsync);\n","import React, { FC, memo } 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 memo(PollModalAsync);\n","import React, { FC, memo } 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 memo(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 { RE_LINK_TEMPLATE } from '../../../config';\nimport { selectNoWebPage } from '../../../modules/selectors';\nimport { pick } from '../../../util/iteratees';\nimport parseMessageInput from './helpers/parseMessageInput';\nimport useOnChange from '../../../hooks/useOnChange';\nimport useShowTransition from '../../../hooks/useShowTransition';\nimport useCurrentOrPrev from '../../../hooks/useCurrentOrPrev';\nimport buildClassName from '../../../util/buildClassName';\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 disabled?: boolean;\n};\n\ntype StateProps = {\n webPagePreview?: ApiWebPage;\n noWebPage?: boolean;\n};\ntype DispatchProps = Pick<GlobalActions, 'loadWebPagePreview' | 'clearWebPagePreview' | 'toggleMessageWebPage'>;\n\nconst RE_LINK = new RegExp(RE_LINK_TEMPLATE, 'i');\n\nconst WebPagePreview: FC<OwnProps & StateProps & DispatchProps> = ({\n chatId,\n threadId,\n messageText,\n disabled,\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 isShown = Boolean(webPagePreview && messageText.length && !noWebPage && !disabled);\n const { shouldRender, transitionClassNames } = useShowTransition(isShown);\n\n const renderingWebPage = useCurrentOrPrev(webPagePreview);\n\n if (!shouldRender || !renderingWebPage) {\n return undefined;\n }\n\n const handleClearWebpagePreview = () => {\n toggleMessageWebPage({ chatId, threadId, noWebPage: true });\n };\n\n // TODO Refactor so `WebPage` can be used without message\n const { photo, ...webPageWithoutPhoto } = renderingWebPage;\n const messageStub = {\n content: {\n webPage: webPageWithoutPhoto,\n },\n } as ApiMessage;\n\n return (\n <div className={buildClassName('WebPagePreview', transitionClassNames)}>\n <div>\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 </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, memo } 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 memo(CalendarModalAsync);\n","import React, { FC, memo } 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 memo(PaymentModalAsync);\n","import React, { FC, memo } 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 memo(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_VOICE_RECORDING_SUPPORTED, IS_MOBILE_SCREEN, IS_EMOJI_SUPPORTED } 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 useStickerTooltip from './hooks/useStickerTooltip';\nimport useEmojiTooltip from './hooks/useEmojiTooltip';\nimport useMentionTooltip from './hooks/useMentionTooltip';\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 MentionTooltip from './MentionTooltip.async';\nimport CustomSendMenu from './CustomSendMenu.async';\nimport StickerTooltip from './StickerTooltip.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 recentEmojis: string[];\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' | 'addRecentEmoji'\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 recentEmojis,\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 addRecentEmoji,\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 isMentionTooltipOpen, mentionFilter,\n closeMentionTooltip, insertMention,\n mentionFilteredMembers,\n } = useMentionTooltip(\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 { isStickerTooltipOpen, closeStickerTooltip } = useStickerTooltip(\n Boolean(shouldSuggestStickers && allowedAttachmentOptions.canSendStickers && !attachments.length),\n html,\n stickersForEmoji,\n );\n const {\n isEmojiTooltipOpen, closeEmojiTooltip, filteredEmojis, insertEmoji,\n } = useEmojiTooltip(\n Boolean(shouldSuggestStickers && allowedAttachmentOptions.canSendStickers && !attachments.length),\n html,\n recentEmojis,\n undefined,\n setHtml,\n );\n\n const insertTextAndUpdateCursor = useCallback((text: string, inputId: string = EDITABLE_INPUT_ID) => {\n const selection = window.getSelection()!;\n const messageInput = document.getElementById(inputId)!;\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 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 closeStickerTooltip();\n closeCalendar();\n setScheduledMessageArgs(undefined);\n closeMentionTooltip();\n closeEmojiTooltip();\n\n if (IS_MOBILE_SCREEN) {\n // @perf\n setTimeout(() => closeSymbolMenu(), SENDING_ANIMATION_DURATION);\n } else {\n closeSymbolMenu();\n }\n }, [closeStickerTooltip, closeCalendar, closeMentionTooltip, closeEmojiTooltip, 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 handleAppendFiles = useCallback(async (files: File[], isQuick: boolean) => {\n setAttachments([\n ...attachments,\n ...await Promise.all(files.map((file) => buildAttachment(file.name, file, isQuick))),\n ]);\n }, [attachments]);\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 = 'SendMessage';\n switch (mainButtonState) {\n case MainButtonState.Edit:\n sendButtonAriaLabel = 'Save edited message';\n break;\n case MainButtonState.Record:\n sendButtonAriaLabel = areVoiceMessagesNotAllowed\n ? 'Conversation.DefaultRestrictedMedia'\n : 'AccDescrVoiceMessage';\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 recentEmojis={recentEmojis}\n onCaptionUpdate={setHtml}\n addRecentEmoji={addRecentEmoji}\n onSend={shouldSchedule ? openCalendar : handleSend}\n onFileAppend={handleAppendFiles}\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 <MentionTooltip\n isOpen={isMentionTooltipOpen}\n filter={mentionFilter}\n onClose={closeMentionTooltip}\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 <WebPagePreview\n chatId={chatId}\n threadId={threadId}\n messageText={!attachments.length ? html : ''}\n disabled={!allowedAttachmentOptions.canAttachEmbedLinks}\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 shouldSupressTextFormatter={isEmojiTooltipOpen || isMentionTooltipOpen}\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 <StickerTooltip\n isOpen={isStickerTooltipOpen}\n onStickerSelect={handleStickerSelect}\n />\n <EmojiTooltip\n isOpen={isEmojiTooltipOpen}\n emojis={filteredEmojis}\n onClose={closeEmojiTooltip}\n onEmojiSelect={insertEmoji}\n addRecentEmoji={addRecentEmoji}\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 addRecentEmoji={addRecentEmoji}\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={lang(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 recentEmojis: global.recentEmojis,\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 'addRecentEmoji',\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 useStickerTooltip(\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 isStickerTooltipOpen: hasStickers,\n closeStickerTooltip: 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, memo } 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 memo(MobileSearchAsync);\n","import React, { FC, memo } 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 memo(MessageSelectToolbarAsync);\n","import React, { FC, memo } 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 memo(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';\nimport { ThemeKey } from '../../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 DARK_THEME_BG_COLOR,\n LIGHT_THEME_BG_COLOR,\n} from '../../config';\nimport { IS_MOBILE_SCREEN, IS_TOUCH_ENV, MASK_IMAGE_DISABLED } 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 usePrevDuringAnimation from '../../hooks/usePrevDuringAnimation';\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 pinnedMessagesCount?: number;\n theme: ThemeKey;\n customBackground?: string;\n backgroundColor?: string;\n patternColor?: string;\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 pinnedMessagesCount,\n customBackground,\n theme,\n backgroundColor,\n patternColor,\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<boolean | undefined>();\n const [isNotchShown, setIsNotchShown] = useState<boolean | undefined>();\n const [isUnpinModalOpen, setIsUnpinModalOpen] = useState(false);\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 renderingChatId = usePrevDuringAnimation(chatId, CLOSE_ANIMATION_DURATION);\n const renderingThreadId = usePrevDuringAnimation(threadId, CLOSE_ANIMATION_DURATION);\n const renderingMessageListType = usePrevDuringAnimation(messageListType, CLOSE_ANIMATION_DURATION);\n const renderingCanPost = usePrevDuringAnimation(canPost, CLOSE_ANIMATION_DURATION);\n const renderingHasTools = usePrevDuringAnimation(hasTools, CLOSE_ANIMATION_DURATION);\n const renderingIsFabShown = usePrevDuringAnimation(isFabShown, 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 setIsFabShown(undefined);\n setIsNotchShown(undefined);\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(theme, customBackground);\n\n const className = buildClassName(\n renderingHasTools && 'has-header-tools',\n customBackground && 'custom-bg-image',\n backgroundColor && 'custom-bg-color',\n customBackground && isBackgroundBlurred && 'blurred',\n MASK_IMAGE_DISABLED ? 'mask-image-disabled' : 'mask-image-enabled',\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 const footerClassName = buildClassName(\n 'middle-column-footer',\n !renderingCanPost && 'no-composer',\n renderingCanPost && isNotchShown && !isSelectModeActive && 'with-notch',\n );\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 --theme-background-color:\n ${backgroundColor || (theme === 'dark' ? DARK_THEME_BG_COLOR : LIGHT_THEME_BG_COLOR)};\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 canPost={renderingCanPost}\n hasTools={renderingHasTools}\n onFabToggle={setIsFabShown}\n onNotchToggle={setIsNotchShown}\n />\n <div className={footerClassName}>\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\" dir={lang.isRtl ? 'rtl' : undefined}>\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.Pinned.UnpinAll', pinnedMessagesCount, 'i')}</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\n isShown={renderingIsFabShown}\n canPost={renderingCanPost}\n />\n </div>\n {IS_MOBILE_SCREEN && <MobileSearch isActive={Boolean(isMobileSearchActive)} />}\n </>\n )}\n {chatId && (\n <UnpinAllMessagesModal\n isOpen={isUnpinModalOpen}\n chatId={chatId}\n pinnedMessagesCount={pinnedMessagesCount}\n onClose={closeUnpinModal}\n onUnpin={handleUnpinAllMessages}\n />\n )}\n </div>\n );\n};\n\nexport default memo(withGlobal(\n (global): StateProps => {\n const { theme } = global.settings.byKey;\n const {\n isBlurred: isBackgroundBlurred, background: customBackground, backgroundColor, patternColor,\n } = global.settings.themes[theme] || {};\n\n const currentMessageList = selectCurrentMessageList(global);\n const { chats: { listIds } } = global;\n\n const state: StateProps = {\n theme,\n customBackground,\n backgroundColor,\n patternColor,\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 if (!currentMessageList || !listIds.active) {\n return state;\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 ...state,\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: (\n threadId !== MAIN_THREAD_ID\n || Boolean(pinnedIds && pinnedIds.length)\n || Boolean(audioChatId && audioMessageId)\n ),\n pinnedMessagesCount: pinnedIds ? pinnedIds.length : 0,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'openChat', 'unpinAllMessages', 'loadUser',\n ]),\n)(MiddleColumn));\n","import { useEffect, useState } from '../lib/teact/teact';\n\nimport { ThemeKey } from '../types';\n\nimport { CUSTOM_BG_CACHE_NAME } from '../config';\nimport * as cacheApi from '../util/cacheApi';\nimport { preloadImage } from '../util/files';\n\nexport default (theme: ThemeKey, 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, theme, cacheApi.Type.Blob)\n .then((blob) => {\n const url = URL.createObjectURL(blob);\n preloadImage(url)\n .then(() => {\n setValue(`url(${url})`);\n });\n });\n }\n }, [settingValue, theme]);\n\n return settingValue ? value : undefined;\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 isStickerSearch?: boolean;\n isGifSearch?: boolean;\n isPollResults?: boolean;\n shouldSkipAnimation?: 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 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 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 shouldSkipAnimation,\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, noPushState: true });\n }, [setStickerSearchQuery]);\n\n const handleGifSearchQueryChange = useCallback((query: string) => {\n setGifSearchQuery({ query, noPushState: true });\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 ) : 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 parentContainerClassName=\"RightSearch\"\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={lang('SearchStickersHint')}\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.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>Profile</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 || shouldSkipAnimation) && '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 || shouldSkipAnimation) ? '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 { MEMBERS_SLICE, MESSAGE_SEARCH_SLICE, SHARED_MEDIA_SLICE } from '../../../config';\nimport { getMessageContentIds, sortUserIds } from '../../../modules/helpers';\nimport useOnChange from '../../../hooks/useOnChange';\nimport useInfiniteScroll from '../../../hooks/useInfiniteScroll';\n\nexport default function useProfileViewportIds(\n isRightColumnShown: boolean,\n loadMoreMembers: AnyToVoidFunction,\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 sortUserIds(groupChatMembers.map(({ userId }) => userId), usersById);\n }, [groupChatMembers, usersById]);\n\n const [memberViewportIds, getMoreMembers, noProfileInfoForMembers] = useInfiniteScrollForMembers(\n resultType, loadMoreMembers, lastSyncTime, memberIds,\n );\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 = memberViewportIds;\n getMore = getMoreMembers;\n noProfileInfo = noProfileInfoForMembers;\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 useInfiniteScrollForMembers(\n currentResultType?: ProfileTabType,\n handleLoadMore?: AnyToVoidFunction,\n lastSyncTime?: number,\n memberIds?: number[],\n) {\n const [viewportIds, getMore] = useInfiniteScroll(\n lastSyncTime ? handleLoadMore : undefined,\n memberIds,\n undefined,\n MEMBERS_SLICE,\n );\n\n const isOnTop = !viewportIds || !memberIds || viewportIds[0] === memberIds[0];\n\n return [viewportIds, getMore, !isOnTop] 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, memo } from '../../lib/teact/teact';\n\nimport {\n ApiUser, ApiChat, ApiMediaFormat, ApiPhoto,\n} from '../../api/types';\n\nimport {\n getChatAvatarHash, isDeletedUser, getUserColorKey, getChatTitle, isChatPrivate, getUserFullName,\n} from '../../modules/helpers';\nimport renderText from '../common/helpers/renderText';\nimport buildClassName from '../../util/buildClassName';\nimport { getFirstLetters } from '../../util/textFormat';\nimport useMedia from '../../hooks/useMedia';\nimport useBlurSync from '../../hooks/useBlurSync';\nimport usePrevious from '../../hooks/usePrevious';\nimport useLang from '../../hooks/useLang';\n\nimport Spinner from '../ui/Spinner';\n\nimport './ProfilePhoto.scss';\n\ntype OwnProps = {\n chat?: ApiChat;\n user?: ApiUser;\n isFirstPhoto?: boolean;\n isSavedMessages?: boolean;\n photo?: ApiPhoto;\n lastSyncTime?: number;\n onClick: NoneToVoidFunction;\n};\n\nconst ProfilePhoto: FC<OwnProps> = ({\n chat,\n user,\n photo,\n isFirstPhoto,\n isSavedMessages,\n lastSyncTime,\n onClick,\n}) => {\n const lang = useLang();\n const isDeleted = user && isDeletedUser(user);\n\n function getMediaHash(size: 'normal' | 'big' = 'big', forceAvatar?: boolean) {\n if (photo && !forceAvatar) {\n return `photo${photo.id}?size=c`;\n }\n\n let hash: string | undefined;\n if (!isSavedMessages && !isDeleted) {\n if (user) {\n hash = getChatAvatarHash(user, size);\n } else if (chat) {\n hash = getChatAvatarHash(chat, size);\n }\n }\n\n return hash;\n }\n\n const imageHash = getMediaHash();\n const fullMediaData = useMedia(imageHash, false, ApiMediaFormat.BlobUrl, lastSyncTime);\n const avatarThumbnailData = useMedia(\n !fullMediaData && isFirstPhoto ? getMediaHash('normal', true) : undefined,\n false,\n ApiMediaFormat.BlobUrl,\n lastSyncTime,\n );\n const thumbDataUri = useBlurSync(!fullMediaData && photo && photo.thumbnail && photo.thumbnail.dataUri);\n const imageSrc = fullMediaData || avatarThumbnailData || thumbDataUri;\n const prevImageSrc = usePrevious(imageSrc);\n\n let content: string | undefined = '';\n\n if (isSavedMessages) {\n content = <i className=\"icon-avatar-saved-messages\" />;\n } else if (isDeleted) {\n content = <i className=\"icon-avatar-deleted-account\" />;\n } else if (imageSrc) {\n content = <img src={imageSrc} className=\"avatar-media\" alt=\"\" decoding=\"async\" />;\n } else if (!imageSrc && user) {\n const userFullName = getUserFullName(user);\n content = userFullName ? getFirstLetters(userFullName, 2) : undefined;\n } else if (!imageSrc && chat) {\n const title = getChatTitle(lang, chat);\n content = title && getFirstLetters(title, isChatPrivate(chat.id) ? 2 : 1);\n } else {\n content = (\n <div className=\"spinner-wrapper\">\n <Spinner color=\"white\" />\n </div>\n );\n }\n\n const fullClassName = buildClassName(\n 'ProfilePhoto',\n `color-bg-${getUserColorKey(user || chat)}`,\n isSavedMessages && 'saved-messages',\n isDeleted && 'deleted-account',\n (!isSavedMessages && !(imageSrc)) && 'no-photo',\n );\n\n return (\n <div className={fullClassName} onClick={imageSrc ? onClick : undefined}>\n {prevImageSrc && imageSrc && prevImageSrc !== imageSrc && (\n <img src={prevImageSrc} className=\"prev-avatar-media\" alt=\"\" decoding=\"async\" />\n )}\n {typeof content === 'string' ? renderText(content, ['hq_emoji']) : content}\n </div>\n );\n};\n\nexport default memo(ProfilePhoto);\n","import React, {\n FC, useEffect, useCallback, memo, useState,\n} from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { ApiUser, ApiChat } from '../../api/types';\nimport { GlobalActions, GlobalState } from '../../global/types';\nimport { MediaViewerOrigin } from '../../types';\n\nimport { IS_TOUCH_ENV } from '../../util/environment';\nimport { selectChat, selectUser } from '../../modules/selectors';\nimport {\n getUserFullName, getUserStatus, isChatChannel, isUserOnline,\n} from '../../modules/helpers';\nimport renderText from '../common/helpers/renderText';\nimport { pick } from '../../util/iteratees';\nimport { captureEvents, SwipeDirection } from '../../util/captureEvents';\nimport usePhotosPreload from './hooks/usePhotosPreload';\nimport useLang from '../../hooks/useLang';\n\nimport VerifiedIcon from '../common/VerifiedIcon';\nimport ProfilePhoto from './ProfilePhoto';\nimport Transition from '../ui/Transition';\n\nimport './ProfileInfo.scss';\n\ntype OwnProps = {\n userId: number;\n forceShowSelf?: boolean;\n};\n\ntype StateProps = {\n user?: ApiUser;\n chat?: ApiChat;\n isSavedMessages?: boolean;\n animationLevel: 0 | 1 | 2;\n} & Pick<GlobalState, 'lastSyncTime'>;\n\ntype DispatchProps = Pick<GlobalActions, 'loadFullUser' | 'openMediaViewer'>;\n\nconst PrivateChatInfo: FC<OwnProps & StateProps & DispatchProps> = ({\n user,\n chat,\n isSavedMessages,\n lastSyncTime,\n animationLevel,\n loadFullUser,\n openMediaViewer,\n}) => {\n const { id: userId } = user || {};\n const { id: chatId } = chat || {};\n const fullName = user ? getUserFullName(user) : (chat ? chat.title : '');\n const photos = (user ? user.photos : (chat ? chat.photos : undefined)) || [];\n const slideAnimation = animationLevel >= 1 ? 'slide' : 'none';\n\n const [currentPhotoIndex, setCurrentPhotoIndex] = useState(0);\n const isFirst = isSavedMessages || photos.length <= 1 || currentPhotoIndex === 0;\n const isLast = isSavedMessages || photos.length <= 1 || currentPhotoIndex === photos.length - 1;\n\n // Deleting the last profile photo may result in an error\n useEffect(() => {\n if (currentPhotoIndex > photos.length) {\n setCurrentPhotoIndex(Math.max(0, photos.length - 1));\n }\n }, [currentPhotoIndex, photos.length]);\n\n const lang = useLang();\n\n useEffect(() => {\n if (lastSyncTime && userId) {\n loadFullUser({ userId });\n }\n }, [userId, loadFullUser, lastSyncTime]);\n\n usePhotosPreload(user || chat, photos, currentPhotoIndex);\n\n const handleProfilePhotoClick = useCallback(() => {\n openMediaViewer({\n avatarOwnerId: userId || chatId,\n profilePhotoIndex: currentPhotoIndex,\n origin: MediaViewerOrigin.ProfileAvatar,\n });\n }, [openMediaViewer, userId, chatId, currentPhotoIndex]);\n\n const selectPreviousMedia = useCallback(() => {\n if (isFirst) {\n return;\n }\n\n setCurrentPhotoIndex(currentPhotoIndex - 1);\n }, [currentPhotoIndex, isFirst]);\n\n const selectNextMedia = useCallback(() => {\n if (isLast) {\n return;\n }\n\n setCurrentPhotoIndex(currentPhotoIndex + 1);\n }, [currentPhotoIndex, isLast]);\n\n // Support for swipe gestures and closing on click\n useEffect(() => {\n const element = document.querySelector<HTMLDivElement>(\n '.profile-slide-container > .active, .profile-slide-container > .to',\n );\n if (!element) {\n return undefined;\n }\n\n return captureEvents(element, {\n excludedClosestSelector: '.navigation',\n onSwipe: IS_TOUCH_ENV ? (e, direction) => {\n if (direction === SwipeDirection.Right) {\n selectPreviousMedia();\n } else if (direction === SwipeDirection.Left) {\n selectNextMedia();\n }\n } : undefined,\n });\n }, [selectNextMedia, selectPreviousMedia]);\n\n if (!user && !chat) {\n return undefined;\n }\n\n function renderPhotoTabs() {\n if (isSavedMessages || !photos || photos.length <= 1) {\n return undefined;\n }\n\n return (\n <div className=\"photo-dashes\">\n {photos.map((_, i) => (\n <span className={`photo-dash ${i === currentPhotoIndex ? 'current' : ''}`} />\n ))}\n </div>\n );\n }\n\n function renderPhoto() {\n const photo = !isSavedMessages && photos && photos.length > 0 ? photos[currentPhotoIndex] : undefined;\n\n return (\n <ProfilePhoto\n key={currentPhotoIndex}\n user={user}\n chat={chat}\n photo={photo}\n isSavedMessages={isSavedMessages}\n isFirstPhoto={isFirst}\n onClick={handleProfilePhotoClick}\n />\n );\n }\n\n function renderStatus() {\n if (user) {\n return (\n <div className={`status ${isUserOnline(user) ? 'online' : ''}`}>\n <span className=\"user-status\" dir=\"auto\">{getUserStatus(lang, user)}</span>\n </div>\n );\n }\n\n return (\n <span className=\"status\" dir=\"auto\">{\n isChatChannel(chat!)\n ? lang('Subscribers', chat!.membersCount, 'i')\n : lang('Members', chat!.membersCount, 'i')\n }\n </span>\n );\n }\n\n const isVerifiedIconShown = (user && user.isVerified) || (chat && chat.isVerified);\n\n return (\n <div className=\"ProfileInfo\" dir={lang.isRtl ? 'rtl' : undefined}>\n <div className=\"photo-wrapper\">\n {renderPhotoTabs()}\n <Transition activeKey={currentPhotoIndex} name={slideAnimation} className=\"profile-slide-container\">\n {renderPhoto}\n </Transition>\n\n {!isFirst && (\n <button\n type=\"button\"\n className=\"navigation prev\"\n aria-label={lang('AccDescrPrevious')}\n onClick={selectPreviousMedia}\n />\n )}\n {!isLast && (\n <button\n type=\"button\"\n className=\"navigation next\"\n aria-label={lang('Next')}\n onClick={selectNextMedia}\n />\n )}\n </div>\n\n <div className=\"info\" dir={lang.isRtl ? 'rtl' : 'auto'}>\n {isSavedMessages ? (\n <div className=\"title\">\n <h3 dir=\"auto\">{lang('SavedMessages')}</h3>\n </div>\n ) : (\n <div className=\"title\">\n <h3 dir=\"auto\">{fullName && renderText(fullName)}</h3>\n {isVerifiedIconShown && <VerifiedIcon />}\n </div>\n )}\n {!isSavedMessages && renderStatus()}\n </div>\n </div>\n );\n};\n\nexport default memo(withGlobal<OwnProps>(\n (global, { userId, forceShowSelf }): StateProps => {\n const { lastSyncTime } = global;\n const user = selectUser(global, userId);\n const chat = selectChat(global, userId);\n const isSavedMessages = !forceShowSelf && user && user.isSelf;\n const { animationLevel } = global.settings.byKey;\n\n return {\n lastSyncTime, user, chat, isSavedMessages, animationLevel,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, ['loadFullUser', 'openMediaViewer']),\n)(PrivateChatInfo));\n","import {\n ApiChat, ApiMediaFormat, ApiPhoto, ApiUser,\n} from '../../../api/types';\nimport { useEffect } from '../../../lib/teact/teact';\nimport * as mediaLoader from '../../../util/mediaLoader';\n\nconst PHOTOS_TO_PRELOAD = 4;\n\nexport default function usePhotosPreload(\n profile: ApiUser | ApiChat | undefined,\n photos: ApiPhoto[],\n currentIndex: number,\n) {\n useEffect(() => {\n photos.slice(currentIndex, currentIndex + PHOTOS_TO_PRELOAD).forEach((photo) => {\n const mediaData = mediaLoader.getFromMemory(`photo${photo.id}?size=c`);\n if (!mediaData) {\n mediaLoader.fetch(`photo${photo.id}?size=c`, ApiMediaFormat.BlobUrl);\n }\n });\n }, [currentIndex, photos]);\n}\n","import React, {\n FC, memo, useCallback, useEffect,\n} from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { GlobalActions, GlobalState } from '../../global/types';\nimport { ApiChat, ApiUser } from '../../api/types';\n\nimport { selectChat, selectUser } from '../../modules/selectors';\nimport {\n getChatDescription, getChatLink, getHasAdminRight, isChatChannel, isChatPrivate, isUserRightBanned,\n} from '../../modules/helpers';\nimport renderText from '../common/helpers/renderText';\nimport { pick } from '../../util/iteratees';\nimport { copyTextToClipboard } from '../../util/clipboard';\nimport { formatPhoneNumberWithCode } from '../../util/phoneNumber';\nimport useLang from '../../hooks/useLang';\n\nimport SafeLink from '../common/SafeLink';\nimport ListItem from '../ui/ListItem';\nimport Switcher from '../ui/Switcher';\n\ntype OwnProps = {\n chatOrUserId: number;\n forceShowSelf?: boolean;\n};\n\ntype StateProps = {\n user?: ApiUser;\n chat?: ApiChat;\n canInviteUsers?: boolean;\n} & Pick<GlobalState, 'lastSyncTime'>;\n\ntype DispatchProps = Pick<GlobalActions, 'loadFullUser' | 'updateChatMutedState' | 'showNotification'>;\n\nconst ChatExtra: FC<OwnProps & StateProps & DispatchProps> = ({\n lastSyncTime,\n user,\n chat,\n forceShowSelf,\n canInviteUsers,\n loadFullUser,\n showNotification,\n updateChatMutedState,\n}) => {\n const {\n id: userId,\n fullInfo,\n username,\n phoneNumber,\n isSelf,\n } = user || {};\n const {\n id: chatId,\n isMuted: currentIsMuted,\n username: chatUsername,\n } = chat || {};\n const lang = useLang();\n\n useEffect(() => {\n if (lastSyncTime && userId) {\n loadFullUser({ userId });\n }\n }, [loadFullUser, userId, lastSyncTime]);\n\n const handleNotificationChange = useCallback(() => {\n updateChatMutedState({ chatId, isMuted: !currentIsMuted });\n }, [chatId, currentIsMuted, updateChatMutedState]);\n\n if (!chat || chat.isRestricted || (isSelf && !forceShowSelf)) {\n return undefined;\n }\n\n function copy(text: string, entity: string) {\n copyTextToClipboard(text);\n showNotification({ message: `${entity} was copied` });\n }\n\n const formattedNumber = phoneNumber && formatPhoneNumberWithCode(phoneNumber);\n const link = getChatLink(chat);\n const url = link.indexOf('http') === 0 ? link : `http://${link}`;\n const printedUsername = username || chatUsername;\n const description = (fullInfo && fullInfo.bio) || getChatDescription(chat);\n\n return (\n <div className=\"ChatExtra\">\n {formattedNumber && !!formattedNumber.length && (\n <ListItem icon=\"phone\" multiline narrow ripple onClick={() => copy(formattedNumber, lang('Phone'))}>\n <span className=\"title\" dir=\"auto\">{formattedNumber}</span>\n <span className=\"subtitle\">{lang('Phone')}</span>\n </ListItem>\n )}\n {printedUsername && (\n <ListItem\n icon=\"mention\"\n multiline\n narrow\n ripple\n onClick={() => copy(`@${printedUsername}`, lang('Username'))}\n >\n <span className=\"title\" dir=\"auto\">{renderText(printedUsername)}</span>\n <span className=\"subtitle\">{lang('Username')}</span>\n </ListItem>\n )}\n {description && !!description.length && (\n <ListItem\n icon=\"info\"\n multiline\n narrow\n isStatic\n >\n <span className=\"title\" dir=\"auto\">\n {renderText(description, ['br', 'links', 'emoji'])}\n </span>\n <span className=\"subtitle\">{lang(userId ? 'UserBio' : 'Info')}</span>\n </ListItem>\n )}\n {canInviteUsers && !printedUsername && !!link.length && (\n <ListItem icon=\"mention\" multiline narrow ripple onClick={() => copy(link, lang('SetUrlPlaceholder'))}>\n <div className=\"title\">\n <SafeLink url={url} className=\"title\" text={link} />\n </div>\n <span className=\"subtitle\">{lang('SetUrlPlaceholder')}</span>\n </ListItem>\n )}\n <ListItem icon=\"unmute\" ripple onClick={handleNotificationChange}>\n <span>{lang('Notifications')}</span>\n <Switcher\n id=\"group-notifications\"\n label={userId ? 'Toggle User Notifications' : 'Toggle Chat Notifications'}\n checked={!currentIsMuted}\n inactive\n />\n </ListItem>\n </div>\n );\n};\n\nexport default memo(withGlobal<OwnProps>(\n (global, { chatOrUserId }): StateProps => {\n const { lastSyncTime } = global;\n\n const chat = chatOrUserId ? selectChat(global, chatOrUserId) : undefined;\n const user = isChatPrivate(chatOrUserId) ? selectUser(global, chatOrUserId) : undefined;\n\n const canInviteUsers = chat && (\n (!isChatChannel(chat) && !isUserRightBanned(chat, 'inviteUsers'))\n || getHasAdminRight(chat, 'inviteUsers')\n );\n\n return {\n lastSyncTime, chat, user, canInviteUsers,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'loadFullUser', 'updateChatMutedState', 'showNotification',\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 {\n MEMBERS_SLICE,\n PROFILE_SENSITIVE_AREA,\n SHARED_MEDIA_SLICE,\n SLIDE_TRANSITION_DURATION,\n} 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';\nimport useLang from '../../hooks/useLang';\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 ProfileInfo from './ProfileInfo';\nimport Document from '../common/Document';\nimport Audio from '../common/Audio';\nimport ChatExtra 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' | 'loadMoreMembers' | 'searchMediaMessagesLocal' | 'openMediaViewer' |\n 'openAudioPlayer' | 'openUserInfo' | 'focusMessage' | 'loadProfilePhotos'\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 loadMoreMembers,\n searchMediaMessagesLocal,\n openMediaViewer,\n openAudioPlayer,\n openUserInfo,\n focusMessage,\n loadProfilePhotos,\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 const lang = useLang();\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, loadMoreMembers, 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 useEffect(() => {\n if (lastSyncTime) {\n loadProfilePhotos({ profileId });\n }\n }, [loadProfilePhotos, profileId, lastSyncTime]);\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 = lang('lng_media_file_empty_search');\n break;\n case 'links':\n text = lang('lng_media_link_empty_search');\n break;\n case 'audio':\n text = lang('lng_media_song_empty_search');\n break;\n default:\n text = lang('SharedMedia.EmptyTitle');\n }\n\n return (\n <div className=\"content empty-list\">\n <NothingFound text={text} />\n </div>\n );\n }\n\n return (\n <div\n className={`content ${resultType}-list`}\n dir={lang.isRtl && resultType === 'media' ? 'rtl' : undefined}\n teactFastList\n >\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={canRenderContents ? viewportIds : undefined}\n cacheBuster={cacheBuster}\n sensitiveArea={PROFILE_SENSITIVE_AREA}\n preloadBackwards={canRenderContents ? (resultType === 'members' ? MEMBERS_SLICE : SHARED_MEDIA_SLICE) : 0}\n // To prevent scroll jumps caused by reordering member list\n noScrollRestoreOnTop\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={lang.isRtl ? 'slide-reversed' : '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 big 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 <ProfileInfo\n userId={resolvedUserId || chatId}\n forceShowSelf={resolvedUserId !== chatId}\n />\n <ChatExtra chatOrUserId={resolvedUserId || chatId} forceShowSelf={resolvedUserId !== chatId} />\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 'loadMoreMembers',\n 'searchMediaMessagesLocal',\n 'openMediaViewer',\n 'openAudioPlayer',\n 'openUserInfo',\n 'focusMessage',\n 'loadProfilePhotos',\n ]),\n)(Profile));\n","import { useCallback, useEffect } from '../../../lib/teact/teact';\n\nexport default function useTransitionFixes(\n containerRef: { current: HTMLDivElement | null },\n transitionElSelector = '.Transition.shared-media-transition',\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>(transitionElSelector);\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, transitionElSelector]);\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, memo } 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 memo(RightSearchAsync);\n","import React, { FC, memo } 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 memo(ManagementAsync);\n","import React, { FC, memo } 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 memo(StickerSearchAsync);\n","import React, { FC, memo } 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 memo(GifSearchAsync);\n","import React, { FC, memo } 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 memo(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';\nimport useHistoryBack from '../../hooks/useHistoryBack';\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 StickerSearch from './StickerSearch.async';\nimport GifSearch from './GifSearch.async';\nimport PollResults from './PollResults.async';\nimport { HistoryWrapper } from '../../util/history';\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' | '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 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 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((noPushState = false) => {\n switch (contentKey) {\n case RightColumnContent.ChatInfo:\n if (isScrolledDown) {\n setProfileState(ProfileState.Profile);\n if (!noPushState) break;\n }\n toggleChatInfo({ noPushState }, true);\n break;\n case RightColumnContent.UserInfo:\n if (isScrolledDown) {\n setProfileState(ProfileState.Profile);\n if (!noPushState) break;\n }\n openUserInfo({ id: undefined });\n break;\n case RightColumnContent.Management: {\n switch (managementScreen) {\n case ManagementScreens.Initial:\n toggleManagement({ noPushState }, true);\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 if (!noPushState) {\n HistoryWrapper.back();\n }\n setManagementScreen(ManagementScreens.Initial);\n break;\n case ManagementScreens.GroupUserPermissionsCreate:\n case ManagementScreens.GroupRemovedUsers:\n case ManagementScreens.GroupUserPermissions:\n if (!noPushState) {\n HistoryWrapper.back();\n }\n\n setManagementScreen(ManagementScreens.GroupPermissions);\n setSelectedChatMemberId(undefined);\n setIsPromotedByCurrentUser(undefined);\n break;\n case ManagementScreens.ChatAdminRights:\n case ManagementScreens.GroupRecentActions:\n if (!noPushState) {\n HistoryWrapper.back();\n }\n\n setManagementScreen(ManagementScreens.ChatAdministrators);\n break;\n }\n\n break;\n }\n case RightColumnContent.Search: {\n blurSearchInput();\n closeLocalTextSearch({ noPushState });\n break;\n }\n case RightColumnContent.StickerSearch:\n blurSearchInput();\n setStickerSearchQuery({ query: undefined, noPushState });\n break;\n case RightColumnContent.GifSearch: {\n blurSearchInput();\n setGifSearchQuery({ query: undefined, noPushState });\n break;\n }\n case RightColumnContent.PollResults:\n closePollResults({ noPushState });\n break;\n }\n }, [\n contentKey, isScrolledDown, toggleChatInfo, openUserInfo, closePollResults,\n managementScreen, toggleManagement, closeLocalTextSearch, setStickerSearchQuery, setGifSearchQuery,\n ]);\n\n const handleClose = useCallback(() => {\n close(false);\n }, [close]);\n\n useHistoryBack((event, noAnimation, previousHistoryState) => {\n if (previousHistoryState && previousHistoryState.type === 'right') {\n if (noAnimation) {\n setShouldSkipTransition(true);\n setTimeout(() => setShouldSkipTransition(false), COLUMN_CLOSE_DELAY_MS);\n }\n close(true);\n }\n });\n\n const handleSelectChatMember = useCallback((memberId, isPromoted) => {\n setSelectedChatMemberId(memberId);\n setIsPromotedByCurrentUser(isPromoted);\n }, []);\n\n const handleManagementScreenSelect = useCallback((screen: ManagementScreens) => {\n if (screen !== managementScreen) {\n HistoryWrapper.pushState({ type: 'right', contentKey });\n setManagementScreen(screen);\n }\n }, [contentKey, managementScreen]);\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={handleManagementScreenSelect}\n onChatMemberSelect={handleSelectChatMember}\n />\n );\n\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 isStickerSearch={isStickerSearch}\n isGifSearch={isGifSearch}\n isPollResults={isPollResults}\n profileState={profileState}\n managementScreen={managementScreen}\n onClose={handleClose}\n shouldSkipAnimation={shouldSkipTransition}\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 '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, memo } 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 memo(NotificationsAsync);\n","import React, { FC, memo } 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 memo(ErrorsAsync);\n","import React, { FC, memo } 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 memo(ForwardPickerAsync);\n","import React, { FC, memo } from '../../lib/teact/teact';\nimport { Bundles } from '../../util/moduleLoader';\n\nimport { OwnProps } from './SafeLinkModal';\n\nimport useModuleLoader from '../../hooks/useModuleLoader';\n\nconst SafeLinkModalAsync: FC<OwnProps> = (props) => {\n const { url } = props;\n const SafeLinkModal = useModuleLoader(Bundles.Extra, 'SafeLinkModal', !url);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return SafeLinkModal ? <SafeLinkModal {...props} /> : undefined;\n};\n\nexport default memo(SafeLinkModalAsync);\n","import React, {\n FC, useEffect, memo, useState,\n} 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 {\n ANIMATION_END_DELAY, DEBUG, INACTIVE_MARKER, PAGE_TITLE, SLIDE_TRANSITION_DURATION,\n} 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';\nimport useHistoryBack from '../../hooks/useHistoryBack';\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';\nimport SafeLinkModal from './SafeLinkModal.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 safeLinkModalUrl?: string;\n};\n\ntype DispatchProps = Pick<GlobalActions, 'loadAnimatedEmojis' | 'openChat'>;\n\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 openChat,\n isLeftColumnShown,\n isRightColumnShown,\n isMediaViewerOpen,\n isForwardModalOpen,\n animationLevel,\n hasNotifications,\n hasErrors,\n audioMessage,\n safeLinkModalUrl,\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 [isHistoryAnimationDisabled, setIsHistoryAnimationDisabled] = useState(false);\n\n const {\n transitionClassNames: middleColumnTransitionClassNames,\n } = useShowTransition(!isLeftColumnShown, undefined, true, undefined, isHistoryAnimationDisabled);\n\n const {\n transitionClassNames: rightColumnTransitionClassNames,\n } = useShowTransition(isRightColumnShown, undefined, true, undefined, isHistoryAnimationDisabled);\n\n\n const className = buildClassName(\n middleColumnTransitionClassNames.replace(/([\\w-]+)/g, 'middle-column-$1'),\n rightColumnTransitionClassNames.replace(/([\\w-]+)/g, 'right-column-$1'),\n isHistoryAnimationDisabled && 'history-animation-disabled',\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 (document.title.includes(INACTIVE_MARKER)) {\n updateIcon(false);\n return;\n }\n\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 = PAGE_TITLE;\n updateIcon(false);\n }\n\n index++;\n }, NOTIFICATION_INTERVAL);\n }, () => {\n clearInterval(notificationInterval);\n notificationInterval = undefined;\n\n if (!document.title.includes(INACTIVE_MARKER)) {\n document.title = PAGE_TITLE;\n }\n\n updateIcon(false);\n });\n\n function stopEvent(e: React.MouseEvent<HTMLDivElement, MouseEvent>) {\n e.preventDefault();\n e.stopPropagation();\n }\n\n useHistoryBack((event, noAnimation) => {\n const { state } = event;\n\n if (state.type !== 'right') {\n if (state.type === 'chat') {\n const { chatId: id, threadId, messageListType: type } = state;\n\n openChat({\n id, threadId, type, noPushState: true,\n }, true);\n } else {\n openChat({\n id: undefined,\n noPushState: true,\n }, true);\n }\n }\n\n // Must disable pane closing animation for back/forward gestures on iOS\n if (noAnimation) {\n setIsHistoryAnimationDisabled(true);\n\n setTimeout(() => {\n setIsHistoryAnimationDisabled(false);\n }, SLIDE_TRANSITION_DURATION);\n }\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 <SafeLinkModal url={safeLinkModalUrl} />\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 safeLinkModalUrl: global.safeLinkModalUrl,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, ['loadAnimatedEmojis', 'openChat']),\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":""} |