{"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/hooks/useBeforeUnload.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/hooks/useBrowserOnline.ts","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/helpers/preventMessageInputBlur.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:///./src/components/middle/composer/helpers/applyIosAutoCapitalizationFix.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/Dialogs.async.tsx","webpack:///./src/components/main/ForwardPicker.async.tsx","webpack:///./src/components/main/SafeLinkModal.async.tsx","webpack:///./src/components/main/HistoryCalendar.async.tsx","webpack:///./src/components/main/Main.tsx","webpack:///./src/bundles/main.ts"],"names":["window","addEventListener","e","state","chatId","id","threadId","messageListType","type","getDispatch","openChat","noPushState","addReducer","global","actions","payload","currentMessageList","selectCurrentMessageList","exitMessageSelectMode","messages","contentToBeScheduled","undefined","forwardMessages","toChatId","setGlobal","history","pushState","updateCurrentMessageList","isChatInfoShown","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","selectIsRightColumnShown","pollResults","voters","setTimeout","newGlobal","getGlobal","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","shouldShowContextMenuHint","disableContextMenuHint","showNotification","message","IS_TOUCH_ENV","isPollModalOpen","query","globalSearch","updateGlobalSearch","globalResults","localResults","resultsByType","fetchingStatus","chats","recentlyFoundChatIds","newRecentIds","filter","unshift","pop","content","updateGlobalSearchContent","updateLocalTextSearch","replaceLocalTextSearchResults","chatThreadKey","buildChatThreadKey","currentQuery","localTextSearch","byChatThreadKey","MEMO_EMPTY_ARRAY","mediaType","updateLocalMediaSearchType","stickers","search","resultIds","gifs","offsetId","results","updateSelectedUserId","replaceSettings","theme","settings","replaceThemeSettings","management","byChatId","isActive","IS_SINGLE_COLUMN_LAYOUT","IS_TABLET_COLUMN_LAYOUT","isLeftColumnShown","action","emoji","recentEmojis","newEmojis","sticker","recent","hash","newStickers","s","notification","newNotifications","notifications","existingNotificationIndex","findIndex","n","splice","push","data","hasErrorKey","getReadableErrorText","newDialogs","dialogs","existingErrorIndex","err","url","safeLinkModalUrl","selectedAt","historyCalendarSelectedAt","payment","isPaymentModalOpen","clearPayment","closeInvoice","runThrottledForLoadChats","throttle","cb","runThrottledForLoadTopChats","runDebouncedForLoadFullChat","debounce","async","loadChats","listType","offsetDate","result","callApi","limit","CHAT_LIST_LOAD_SLICE","archived","withPinned","orderedPinnedIds","serverTimeOffset","chatIds","shift","addUsers","buildCollectionByKey","users","updateChats","updateChatListIds","updateChatListSecondaryInfo","draftsById","map","forEach","replyingToById","isFullyLoaded","loadFullChat","fullInfo","updateChat","openChatByUsername","username","channelPostId","localChat","selectChatByUsername","isMin","previousChat","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","createChannel","userId","activeChat","activeChannel","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","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","IS_IOS","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","draftDate","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","language","currentEmojiKeywords","selectEmojiKeywords","isLoading","emojiKeywords","fromVersion","version","keywords","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","loadTopMessages","lastReadInboxMessageId","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","currentThreadId","draftsByChatId","acc","newCurrentChatId","currentMessageListInfo","threadsById","originChannelId","currentMessageListInfoOrigin","resultOrigin","byIdOrigin","listedIdsOrigin","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","topPeers","lastRequestedAt","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","alert","isError","showDialog","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","isSensitiveEnabled","hasPassword","updateTwoFaSettings","hint","currentPassword","onSuccess","error","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","formattedText","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","useBeforeUnload","callback","useEffect","onBeforeUnload","memo","name","label","checked","disabled","inactive","noAnimation","onChange","onCheck","handleChange","useCallback","currentTarget","className","buildClassName","ANIMATION_LEVEL_OPTIONS","withGlobal","searchQuery","animationLevel","byKey","globalSearchChatId","searchDate","selectTheme","contactsFilter","onSearchQuery","onSelectSettings","onSelectContacts","onSelectArchived","setGlobalSearchChatId","onReset","openTipsChat","setGlobalSearchDate","setSettingOption","lang","useLang","hasMenu","LeftColumnContent","ChatList","clearedDateSearchParam","clearedChatSearchParam","selectedSearchDate","useMemo","formatDateToString","archivedUnreadChatsCount","values","total","withOtherVersions","location","hostname","MainButton","onTrigger","isOpen","Button","ripple","color","onClick","ariaLabel","handleSearchFocus","handleSelectSaved","handleDarkModeToggle","stopPropagation","newTheme","shouldUseSystemTheme","switchTheme","ANIMATION_LEVEL_MAX","handleAnimationLevelChange","newLevel","_","body","classList","toggle","isSearchFocused","GlobalSearch","Contacts","searchInputPlaceholder","DropdownMenu","trigger","footer","APP_NAME","APP_VERSION","MenuItem","icon","toLowerCase","href","FEEDBACK_URL","localStorage","setItem","JSON","stringify","SearchInput","inputId","parentContainerClassName","focused","placeholder","autoComplete","canClose","onFocus","PickerSelectedItem","isMinimized","clickArg","chatOrUserId","dir","isRtl","Spinner","resolverFn","ms","dependencies","valueRef","useRef","runThrottled","useThrottle","forceUpdate","useForceUpdate","useOnChange","isSync","current","orderedFolderIds","notifySettings","selectNotifySettings","notifyExceptions","selectNotifyExceptions","setActiveChatFolder","transitionRef","displayedFolders","folderCountersById","useThrottledMemo","counters","unreadDialogsCount","hasActiveDialogs","getFolderUnreadDialogs","badgeCount","isBadgeActive","folderTabs","handleSwitchTab","captureEvents","onSwipe","SwipeDirection","Left","min","Right","isNotInAllTabRef","captureEscKeyListener","handleKeyDown","metaKey","startsWith","digit","preventDefault","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","isMenuOpen","setIsMenuOpen","useState","fabClassName","handleMouseEnter","handleMouseLeave","onMouseEnter","onMouseLeave","tabIndex","Menu","positionX","positionY","autoClose","onClose","TRANSITION_RENDER_COUNT","onContentChange","connectionState","isNewChatButtonShown","setIsNewChatButtonShown","isConnecting","isOnline","setIsOnline","navigator","onLine","useBrowserOnline","isMouseInside","handleSelectSettings","Settings","handleSelectContacts","handleSelectNewChannel","NewChannelStep1","handleSelectNewGroup","NewGroupStep1","handleSelectArchived","Archived","autoCloseTimeout","shouldRenderUpdateButton","updateButtonClassNames","handleUpdateClick","isAppOutdated","markIsAppOutdated","useFlag","timeout","reload","useAppOutdatedCheck","ShowTransition","isCustom","shouldCleanup","cleanupExceptionKey","fluid","pill","NewChat","ContentType","ArchivedChats","RENDER_COUNT","setGlobalSearchQuery","resetChatCreation","loadPasswordInfo","clearTwoFaError","setContent","settingsScreen","setSettingsScreen","SettingsScreens","Main","setContactsFilter","lastResetTime","setLastResetTime","contentType","NewChannelStep2","NewChannel","NewGroupStep2","NewGroup","handleReset","forceReturnToChatList","pickerSearchInput","getElementById","blur","EditProfile","Folders","General","Notifications","Privacy","Language","GeneralChatBackground","GeneralChatBackgroundColor","PrivacyPhoneNumber","PrivacyLastSeen","PrivacyProfilePhoto","PrivacyForwarding","PrivacyGroupChats","PrivacyActiveSessions","PrivacyBlockedUsers","TwoFaDisabled","TwoFaEnabled","TwoFaCongratulations","PrivacyPhoneNumberAllowedContacts","PrivacyPhoneNumberDeniedContacts","PrivacyLastSeenAllowedContacts","PrivacyLastSeenDeniedContacts","PrivacyProfilePhotoAllowedContacts","PrivacyProfilePhotoDeniedContacts","PrivacyForwardingAllowedContacts","PrivacyForwardingDeniedContacts","PrivacyGroupChatsAllowedContacts","PrivacyGroupChatsDeniedContacts","TwoFaNewPassword","TwoFaNewPasswordConfirm","TwoFaNewPasswordHint","TwoFaNewPasswordEmail","TwoFaNewPasswordEmailCode","TwoFaChangePasswordCurrent","TwoFaTurnOff","TwoFaRecoveryEmailCurrentPassword","TwoFaChangePasswordNew","TwoFaChangePasswordConfirm","TwoFaChangePasswordHint","TwoFaRecoveryEmail","TwoFaRecoveryEmailCode","FoldersCreateFolder","FoldersEditFolder","handleSearchQuery","LAYERS_ANIMATION_NAME","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","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","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","nextMessageDayStartsAt","isActionMessage","forwardInfo","senderUserId","hiddenUserName","inlineButtons","preventMessageInputBlur","activeElement","target","useStickyDates","isScrolled","markIsScrolled","runDebounced","shouldRunFirst","shouldRunLast","updateStickyDates","container","hasTools","contains","fastRaf","currentStuck","stuckDateEl","allElements","querySelectorAll","containerTop","scrollTop","el","offsetTop","offsetHeight","top","findStuckDate","MessageScroll","loadMoreForwards","loadMoreBackwards","isViewportNewest","onFabToggle","onNotchToggle","children","backwardsTriggerRef","forwardsTriggerRef","fabTriggerRef","toggleScrollTools","scrollHeight","scrollBottom","isAtBottom","observe","observeIntersection","useIntersectionObserver","rootRef","margin","MESSAGE_LIST_SENSITIVE_AREA","entries","triggerEntry","isIntersecting","resetScroll","useOnIntersect","observeIntersectionForFab","freeze","freezeForFab","unfreeze","unfreezeForFab","observeIntersectionForNotch","freezeForNotch","unfreezeForNotch","teactFastList","isEmojiOnlyMessage","customShape","getMinMediaWidth","hasText","hasCommentButton","calculateMediaDimensions","noAvatars","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","getAvailableWidth","REM","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","SELECTED_APPENDIX_BACKGROUND","getCustomAppendixBg","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","appendixBg","setProperty","setAttribute","ProgressSpinner","useHeavyAnimationCheckForVideo","playerRef","shouldPlayRef","safePlay","useHeavyAnimationCheck","isPlayAllowed","wasPlaying","isFrozen","freezePlaying","paused","unfreezePlaying","unfreezePlayingOnRaf","hasFocus","useBackgroundMode","Video","shouldAutoPlay","videoRef","getMessageWebPageVideo","setIsPlayAllowed","isInline","isBuffered","bufferingHandlers","useBuffering","playProgress","setPlayProgress","handleTimeUpdate","currentTime","duration","usePauseOnInactive","useVideoCleanup","videoClassName","shouldRenderInlineVideo","shouldRenderPlayButton","shouldRenderDownloadButton","autoPlay","muted","loop","playsInline","onTimeUpdate","isGif","formatMediaDuration","contact","openUserInfo","Avatar","formatPhoneNumberWithCode","selected","loadingOptions","setValues","event","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","truncatedDescription","trimText","data-initial","SafeLink","getMessageInvoice","photoUrl","withSelectControl","WrappedComponent","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","isLocal","hasReply","isReplyMessage","hasThread","asForwarded","isLinkedChannelPost","isInDocumentGroup","voice","getMessageCustomShape","textParts","renderMessageText","adminTitle","metaSafeAuthorWidth","canShowActionButton","canForward","canFocus","isChannelPost","fromMessageId","avatarPeer","senderPeer","containerClassName","contentClassName","hasComments","classNames","isMediaWithNoText","isViaBot","isRound","buildContentClassName","withCommentButton","withAppendix","handleGroupDocumentMessagesSelect","handleContainerDoubleClick","handleContentDoubleClick","handleAvatarClick","handleSenderClick","handleViaBotClick","handleReplyClick","MediaViewerOrigin","ScheduledInline","Inline","handleAudioPlay","handleAlbumMediaClick","albumMessageId","ScheduledAlbum","Album","IS_ANDROID","handleReadMedia","handleVoteSend","handleGroupForward","handleForward","handleFocus","handleFocusForwarded","calculatedWidth","noMediaCorners","extraPadding","onDoubleClick","data-last-message-id","data-has-unread-mention","isAvatarPeerUser","avatarUser","avatarChat","hiddenName","renderAvatar","shouldInlineMeta","senderColor","getUserColorKey","renderSenderName","AnimatedEmoji","forceLoadPreview","Audio","isSelectable","onPlay","onReadMedia","Document","renderContent","INTERSECTION_THROTTLE_FOR_MEDIA","INTERSECTION_MARGIN_FOR_MEDIA","runDebouncedForScroll","selectCurrentMessageIds","restrictionReason","focusingId","withLastMessageWhenPreloading","botDescription","chatBot","selectChatBot","isChatLoaded","isChannelChat","threadFirstMessageId","selectFirstMessageId","hasLinkedChat","markMessageListRead","setScrollOffset","openHistoryCalendar","scrollOffsetRef","selectScrollOffset","anchorIdRef","anchorTopRef","listItemElementsRef","memoUnreadDividerBeforeIdRef","memoFirstUnreadIdRef","memoFocusingIdRef","isScrollTopJustUpdatedRef","shouldAnimateAppearanceRef","setContainerHeight","hasFocusing","setHasFocusing","onTickEnd","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","resetInput","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","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","baseEmojiKeywords","editingMessage","canScheduleUntilOnline","wasOnline","withScheduledButton","shouldSchedule","botKeyboardMessageId","canSuggestMembers","isChatGroup","stickersForEmoji","groupChatMembers","isReceiptModalOpen","shouldSuggestStickers","dropAreaState","onDropHide","editMessage","saveDraft","clearDraft","setStickerSearchQuery","setGifSearchQuery","closePollModal","closePaymentModal","clearReceipt","addRecentEmoji","loadEmojiKeywords","html","setHtml","lastMessageSendTimeSeconds","prevDropAreaState","isCalendarOpen","openCalendar","closeCalendar","scheduledMessageArgs","setScheduledMessageArgs","htmlRef","setAttachments","isBotKeyboardOpen","openBotKeyboard","closeBotKeyboard","isAttachMenuOpen","openAttachMenu","closeAttachMenu","isSymbolMenuOpen","openSymbolMenu","closeSymbolMenu","isDeleteModalOpen","openDeleteModal","closeDeleteModal","isSymbolMenuLoaded","onSymbolMenuLoadingComplete","isHoverDisabled","disableHover","enableHover","startRecordingVoice","stopRecordingVoice","pauseRecordingVoice","activeVoiceRecording","currentRecordTime","recordButtonRef","mainButtonRef","startRecordTimeRef","setActiveVoiceRecording","setCurrentRecordTime","voiceRecording","tickVolume","boxShadow","useVoiceRecording","mainButtonState","Edit","IS_VOICE_RECORDING_SUPPORTED","Send","Record","canShowCustomSendMenu","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","range","deleteContents","fragment","createContextualFragment","lastInsertedNode","lastChild","insertNode","setStartAfter","setEndAfter","removeAllRanges","addRange","insertHtmlInSelection","dispatchEvent","Event","bubbles","focusEditableElement","removeSymbol","execCommand","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","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","inputEl","handleStickerSelect","handleGifSelect","gif","handlePollSend","handleSilentSend","handleMessageSchedule","isWhenOnline","restArgs","getTime","handleMessageScheduleUntilOnline","handleCloseCalendar","handleSearchOpen","handleSymbolMenuOpen","handleAllScheduledClick","mainButtonHandler","areVoiceMessagesNotAllowed","canAttachMedia","prevEditedMessage","renderedEditedMessage","scheduledDefaultDate","setSeconds","setMilliseconds","scheduledMaxDate","setFullYear","getFullYear","sendButtonAriaLabel","symbolMenuButtonClassName","onSend","Portal","DropAreaState","None","withQuick","QuickFile","onHide","onFileSelect","caption","onCaptionUpdate","onFileAppend","onClear","onInsertUserName","filteredChatMembers","canAttachEmbedLinks","faded","MessageInput","innerWidth","shouldSetFocus","shouldSuppressFocus","shouldSuppressTextFormatter","onUpdate","onSuppressedFocus","formatVoiceRecordDuration","onStickerSelect","emojis","onEmojiSelect","onPollCreate","onGifSelect","onRemoveSymbol","onSearchOpen","onSilentSend","onScheduleSend","withTimePicker","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","handleTabletFocus","customBackgroundValue","settingValue","setValue","cacheApi","CUSTOM_BG_CACHE_NAME","useCustomBackground","MASK_IMAGE_DISABLED","messagingDisabledClassName","footerClassName","DARK_THEME_BG_COLOR","LIGHT_THEME_BG_COLOR","onDragEnter","onUnpin","runDebouncedForSearch","HeaderContent","isProfile","isManagement","messageSearchQuery","stickerSearchQuery","selectCurrentStickerSearch","gifSearchQuery","selectCurrentGifSearch","canManage","isCreator","isColumnOpen","isSearch","isStickerSearch","isGifSearch","isPollResults","profileState","managementScreen","setLocalTextSearchQuery","searchTextMessagesLocal","toggleManagement","backButtonRef","handleMessageSearchQueryChange","handleStickerSearchQueryChange","handleGifSearchQueryChange","shouldSkipTransition","setShouldSkipTransition","contentKey","ProfileState","Profile","SharedMedia","MemberList","Search","PollResults","StickerSearch","GifSearch","ManagementScreens","Initial","ManageInitial","ChatPrivacyType","ManageChatPrivacyType","Discussion","ManageDiscussion","ChannelSubscribers","ManageChannelSubscribers","GroupPermissions","ManageGroupPermissions","ChatAdministrators","ManageChatAdministrators","GroupRemovedUsers","ManageGroupRemovedUsers","GroupUserPermissionsCreate","ManageGroupUserPermissionsCreate","GroupUserPermissions","ManageGroupUserPermissions","GroupRecentActions","ManageGroupRecentActions","ChatAdminRights","ManageGroupAdminRights","GroupMembers","ManageGroupMembers","renderingContentKey","renderHeaderContent","isBackButton","buttonClassName","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","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","teactOrderKey","InfiniteScroll","itemSelector","sensitiveArea","PROFILE_SENSITIVE_AREA","preloadBackwards","noScrollRestoreOnTop","noFastList","onLoadMore","renderProfileInfo","shouldRestoreHeight","onStart","onStop","big","RightSearch","Management","MAIN_SCREENS_COUNT","RightColumnContent","MANAGEMENT_SCREENS_COUNT","blurSearchInput","areActiveChatsLoaded","selectAreActiveChatsLoaded","selectRightColumnContentKey","currentProfileUserId","selectedId","isChatSelected","toggleChatInfo","closeLocalTextSearch","closePollResults","setProfileState","setManagementScreen","selectedChatMemberId","setSelectedChatMemberId","isPromotedByCurrentUser","setIsPromotedByCurrentUser","isScrolledDown","ChatInfo","UserInfo","isOverlaying","close","GroupType","handleSelectChatMember","memberId","isPromoted","onChatMemberSelect","prevContentKey","MediaViewer","Dialogs","ForwardPicker","SafeLinkModal","HistoryCalendar","rightColumnAnimationTimeout","notificationInterval","DEBUG_isLogged","updateIcon","asUnread","isMediaViewerOpen","selectIsMediaViewerOpen","isForwardModalOpen","selectIsForwardModalOpen","hasNotifications","hasDialogs","isHistoryCalendarOpen","loadNotificationSettings","loadNotificationExceptions","updateIsOnline","middleColumnTransitionClassNames","rightColumnTransitionClassNames","initialUnread","clearInterval","setInterval","INACTIVE_MARKER","newUnread","PAGE_TITLE","stopEvent","onDrop","onDragOver","initApi"],"mappings":"uLAOAA,OAAOC,iBAAiB,WAAaC,IACnC,IAAKA,EAAEC,MACL,OAGF,MAAQC,OAAQC,EAAV,SAAcC,EAAUC,gBAAiBC,GAASN,EAAEC,MAE1DM,cAAcC,SAAS,CACrBL,KAAIC,WAAUE,OAAMG,aAAa,MAIrCC,YAAW,WAAY,CAACC,EAAQC,EAASC,KACvC,MAAM,GACJV,EADI,SACAC,GAAW,EADX,KACeE,EAAO,SADtB,YACgCG,GAClCI,EAEEC,EAAqBC,YAAyBJ,GA4BpD,OA1BKG,GAEDA,EAAmBZ,SAAWC,GAC3BW,EAAmBV,WAAaA,GAChCU,EAAmBR,OAASA,IAEjCK,EAASK,YAAsBL,GAE/BA,EAAS,IACJA,EACHM,SAAU,IACLN,EAAOM,SACVC,0BAAsBC,MAEpBhB,IAAOQ,EAAOS,gBAAgBC,UAAY,CAC5CD,gBAAiB,KAIrBE,YAAUX,GAELF,GACHX,OAAOyB,QAAQC,UAAU,CAAEtB,OAAQC,EAAIC,WAAUC,gBAAiBC,GAAQ,KAIvEmB,YAAyBd,EAAQR,EAAIC,EAAUE,KAGxDI,YAAW,mBAAoB,CAACC,EAAQC,EAASC,KAC/CS,YAAU,IACLX,EACHe,iBAAiB,IAGnBd,EAAQJ,SAASK,KAGnBH,YAAW,oBAAsBC,IACxB,IACFA,EACHgB,kBAAcR,K,iCCpClB,IAAIS,EAEJlB,YAAW,kBAAmB,CAACC,EAAQC,EAASC,KAC9C,MAAM,OAAEX,EAAF,SAAUE,EAAV,aAAoByB,GAAiBhB,EAE3C,OAAOiB,YAAmBnB,EAAQT,EAAQE,EAAU,eAAgByB,KAGtEnB,YAAW,kBAAmB,CAACC,EAAQC,EAASC,KAC9C,MAAM,UAAEkB,GAAclB,EAChBC,EAAqBC,YAAyBJ,GACpD,IAAKG,EACH,OAEF,MA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,GAAe,GAEfI,cAAcjB,IACdA,QAAuB7sF,EAElBioB,SAASpZ,MAAM3K,SAAS8pF,OAC3B/lE,SAASpZ,MAAQq/E,MAGnBnB,IAAW,IACV,CAACW,IAMJ,SAASS,EAAUtvF,GACjBA,EAAE0/B,iBACF1/B,EAAEo6B,kBAGJ,OARAwxB,aAAkBioB,EAAYpX,GAC9BpmC,GAAgBw9C,GAQd,yBAAK1zE,GAAG,OAAOk3B,UAAWA,EAAWk4D,OAAQD,EAAWE,WAAYF,GAClE,kBAAC,GAAD,MACA,kBAAC,GAAD,MACA,kBAAC,GAAD,MACA,kBAAC,GAAD,CAAa31D,OAAQy0D,IACrB,kBAAC,GAAD,CAAez0D,OAAQ20D,IACvB,kBAAC,GAAD,CAAe30D,OAAQ60D,IACvB,kBAAC,GAAD,CAAS70D,OAAQ80D,IAChBh8C,GAAgB,kBAAC,GAAD,CAAavc,IAAKuc,EAAatyC,GAAIuG,QAAS+rC,EAAclB,MAAI,IAC/E,kBAAC,GAAD,CAAexmC,IAAKC,IACpB,kBAAC,GAAD,CAAiB2uB,OAAQ+0D,QC7L3BzrE,KAEFC,QAAQC,IAAI,+BAGT1e,cAAY+9B,iBACfjiC,cAAckvF,W","file":"4.ba74ef98314995630f28.js","sourcesContent":["import { addReducer, getDispatch, setGlobal } from '../../../lib/teact/teactn';\nimport {\n exitMessageSelectMode,\n updateCurrentMessageList,\n} from '../../reducers';\nimport { selectCurrentMessageList } from '../../selectors';\n\nwindow.addEventListener('popstate', (e) => {\n if (!e.state) {\n return;\n }\n\n const { chatId: id, threadId, messageListType: type } = e.state;\n\n getDispatch().openChat({\n id, threadId, type, noPushState: true,\n });\n});\n\naddReducer('openChat', (global, actions, payload) => {\n const {\n id, threadId = -1, type = 'thread', noPushState,\n } = payload!;\n\n const currentMessageList = selectCurrentMessageList(global);\n\n if (!currentMessageList\n || (\n currentMessageList.chatId !== id\n || currentMessageList.threadId !== threadId\n || currentMessageList.type !== type\n )) {\n global = exitMessageSelectMode(global);\n\n global = {\n ...global,\n messages: {\n ...global.messages,\n contentToBeScheduled: undefined,\n },\n ...(id !== global.forwardMessages.toChatId && {\n forwardMessages: {},\n }),\n };\n\n setGlobal(global);\n\n if (!noPushState) {\n window.history.pushState({ chatId: id, threadId, messageListType: type }, '');\n }\n }\n\n return updateCurrentMessageList(global, id, threadId, type);\n});\n\naddReducer('openChatWithInfo', (global, actions, payload) => {\n setGlobal({\n ...global,\n isChatInfoShown: true,\n });\n\n actions.openChat(payload);\n});\n\naddReducer('resetChatCreation', (global) => {\n return {\n ...global,\n chatCreation: undefined,\n };\n});\n","import { addReducer, getGlobal, setGlobal } from '../../../lib/teact/teactn';\n\nimport { MAIN_THREAD_ID } from '../../../api/types';\nimport { FocusDirection } from '../../../types';\n\nimport {\n enterMessageSelectMode,\n toggleMessageSelection,\n exitMessageSelectMode,\n replaceThreadParam,\n updateFocusDirection,\n updateFocusedMessage,\n} from '../../reducers';\nimport {\n selectCurrentChat,\n selectViewportIds,\n selectIsRightColumnShown,\n selectCurrentMessageList,\n selectChat,\n selectThreadInfo,\n selectChatMessages,\n selectAllowedMessageActions,\n selectMessageIdsByGroupId,\n selectForwardedMessageIdsByGroupId, selectIsViewportNewest, selectReplyingToId,\n} from '../../selectors';\nimport { findLast } from '../../../util/iteratees';\nimport { IS_TOUCH_ENV } from '../../../util/environment';\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 } = payload!;\n\n const shouldOpenInstantly = selectIsRightColumnShown(global);\n\n if (!shouldOpenInstantly) {\n window.setTimeout(() => {\n const newGlobal = getGlobal();\n\n setGlobal({\n ...newGlobal,\n pollResults: {\n chatId,\n messageId,\n voters: {},\n },\n });\n }, POLL_RESULT_OPEN_DELAY_MS);\n } else if (chatId !== global.pollResults.chatId || messageId !== global.pollResults.messageId) {\n setGlobal({\n ...global,\n pollResults: {\n chatId,\n messageId,\n voters: {},\n },\n });\n }\n});\n\naddReducer('closePollResults', (global) => {\n setGlobal({\n ...global,\n pollResults: {},\n });\n});\n\naddReducer('focusLastMessage', (global, actions) => {\n const currentMessageList = selectCurrentMessageList(global);\n if (!currentMessageList) {\n return;\n }\n\n const { chatId, threadId } = currentMessageList;\n\n let lastMessageId: number | undefined;\n if (threadId === MAIN_THREAD_ID) {\n const chat = selectChat(global, chatId);\n\n lastMessageId = chat && chat.lastMessage ? chat.lastMessage.id : undefined;\n } else {\n const threadInfo = selectThreadInfo(global, chatId, threadId);\n\n lastMessageId = threadInfo ? threadInfo.lastMessageId : undefined;\n }\n\n if (!lastMessageId) {\n return;\n }\n\n actions.focusMessage({\n chatId, threadId, messageId: lastMessageId, noHighlight: true,\n });\n});\n\naddReducer('focusMessage', (global, actions, payload) => {\n const {\n chatId, threadId = MAIN_THREAD_ID, messageListType = 'thread', noHighlight, groupedId, groupedChatId,\n } = payload!;\n\n let { messageId } = payload!;\n\n if (groupedId !== undefined) {\n const ids = selectForwardedMessageIdsByGroupId(global, groupedChatId, groupedId);\n if (ids && ids.length) {\n ([messageId] = ids);\n }\n }\n\n const currentMessageList = selectCurrentMessageList(global);\n const shouldSwitchChat = !currentMessageList || (\n chatId !== currentMessageList.chatId\n || threadId !== currentMessageList.threadId\n || messageListType !== currentMessageList.type\n );\n\n if (blurTimeout) {\n clearTimeout(blurTimeout);\n blurTimeout = undefined;\n }\n blurTimeout = window.setTimeout(() => {\n let newGlobal = getGlobal();\n newGlobal = updateFocusedMessage(newGlobal);\n newGlobal = updateFocusDirection(newGlobal);\n setGlobal(newGlobal);\n }, FOCUS_DURATION);\n\n global = updateFocusedMessage(global, chatId, messageId, noHighlight);\n global = updateFocusDirection(global, undefined);\n\n if (shouldSwitchChat) {\n global = updateFocusDirection(global, FocusDirection.Static);\n }\n\n const viewportIds = selectViewportIds(global, chatId, threadId);\n if (viewportIds && viewportIds.includes(messageId)) {\n setGlobal(global);\n actions.openChat({ id: chatId, threadId });\n return undefined;\n }\n\n if (shouldSwitchChat) {\n global = replaceThreadParam(global, chatId, threadId, 'viewportIds', undefined);\n }\n\n global = replaceThreadParam(global, chatId, threadId, 'outlyingIds', undefined);\n\n if (viewportIds && !shouldSwitchChat) {\n const direction = messageId > viewportIds[0] ? FocusDirection.Down : FocusDirection.Up;\n global = updateFocusDirection(global, direction);\n }\n\n setGlobal(global);\n\n actions.openChat({ id: chatId, threadId });\n actions.loadViewportMessages();\n return undefined;\n});\n\naddReducer('openForwardMenu', (global, actions, payload) => {\n const { fromChatId, messageIds, groupedId } = payload!;\n let groupedMessageIds;\n if (groupedId) {\n groupedMessageIds = selectMessageIdsByGroupId(global, fromChatId, groupedId);\n }\n return {\n ...global,\n forwardMessages: {\n fromChatId,\n messageIds: groupedMessageIds || messageIds,\n isModalShown: true,\n },\n };\n});\n\naddReducer('exitForwardMode', (global) => {\n setGlobal({\n ...global,\n forwardMessages: {},\n });\n});\n\naddReducer('setForwardChatId', (global, actions, payload) => {\n const { id } = payload!;\n\n setGlobal({\n ...global,\n forwardMessages: {\n ...global.forwardMessages,\n toChatId: id,\n isModalShown: false,\n },\n });\n\n actions.openChat({ id });\n actions.closeMediaViewer();\n 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;\n }\n\n const { chatId, threadId, type: messageListType } = currentMessageList;\n\n global = toggleMessageSelection(\n global, chatId, threadId, messageListType, messageId, groupedId, childMessageIds, withShift,\n );\n\n setGlobal(global);\n\n if (global.shouldShowContextMenuHint) {\n actions.disableContextMenuHint();\n actions.showNotification({\n // eslint-disable-next-line max-len\n message: `To **edit** or **reply**, close this menu. Then ${IS_TOUCH_ENV ? 'long tap' : 'right click'} on a message.`,\n });\n }\n});\n\naddReducer('disableContextMenuHint', (global) => {\n if (!global.shouldShowContextMenuHint) {\n return undefined;\n }\n\n return {\n ...global,\n shouldShowContextMenuHint: false,\n };\n});\n\naddReducer('exitMessageSelectMode', exitMessageSelectMode);\n\naddReducer('openPollModal', (global) => {\n return {\n ...global,\n isPollModalOpen: true,\n };\n});\n\naddReducer('closePollModal', (global) => {\n return {\n ...global,\n isPollModalOpen: false,\n };\n});\n","import { addReducer } from '../../../lib/teact/teactn';\n\nimport { updateGlobalSearch, updateGlobalSearchContent } from '../../reducers';\n\nconst MAX_RECENTLY_FOUND_IDS = 10;\n\naddReducer('setGlobalSearchQuery', (global, actions, payload) => {\n const { query } = payload!;\n const { chatId } = global.globalSearch;\n\n return updateGlobalSearch(global, {\n globalResults: {},\n localResults: {},\n resultsByType: undefined,\n ...(query ? { fetchingStatus: { chats: !chatId, messages: true } } : { fetchingStatus: undefined }),\n query,\n });\n});\n\naddReducer('addRecentlyFoundChatId', (global, actions, payload) => {\n const { id } = payload!;\n const { recentlyFoundChatIds } = global.globalSearch;\n\n if (!recentlyFoundChatIds) {\n return updateGlobalSearch(global, { recentlyFoundChatIds: [id] });\n }\n\n const newRecentIds = recentlyFoundChatIds.filter((chatId) => chatId !== id);\n newRecentIds.unshift(id);\n if (newRecentIds.length > MAX_RECENTLY_FOUND_IDS) {\n newRecentIds.pop();\n }\n\n return updateGlobalSearch(global, { recentlyFoundChatIds: newRecentIds });\n});\n\naddReducer('clearRecentlyFoundChats', (global) => {\n return updateGlobalSearch(global, { recentlyFoundChatIds: undefined });\n});\n\naddReducer('setGlobalSearchContent', (global, actions, payload) => {\n const { content } = payload!;\n\n return updateGlobalSearchContent(global, content);\n});\n\naddReducer('setGlobalSearchChatId', (global, actions, payload) => {\n const { id } = payload!;\n\n return updateGlobalSearch(global, { chatId: id, query: undefined, resultsByType: undefined });\n});\n","import { addReducer } from '../../../lib/teact/teactn';\n\nimport {\n updateLocalTextSearch,\n replaceLocalTextSearchResults,\n updateLocalMediaSearchType,\n} from '../../reducers';\nimport { MEMO_EMPTY_ARRAY } from '../../../util/memo';\nimport { selectCurrentMessageList } from '../../selectors';\nimport { buildChatThreadKey } from '../../helpers';\n\naddReducer('openLocalTextSearch', (global) => {\n const { chatId, threadId } = selectCurrentMessageList(global) || {};\n if (!chatId || !threadId) {\n return undefined;\n }\n\n return updateLocalTextSearch(global, chatId, threadId, true);\n});\n\naddReducer('closeLocalTextSearch', (global) => {\n const { chatId, threadId } = selectCurrentMessageList(global) || {};\n if (!chatId || !threadId) {\n return undefined;\n }\n\n global = updateLocalTextSearch(global, chatId, threadId, false);\n global = replaceLocalTextSearchResults(global, chatId, threadId, undefined);\n return global;\n});\n\naddReducer('setLocalTextSearchQuery', (global, actions, payload) => {\n const { chatId, threadId } = selectCurrentMessageList(global) || {};\n if (!chatId || !threadId) {\n return undefined;\n }\n\n const { query } = payload!;\n const chatThreadKey = buildChatThreadKey(chatId, threadId);\n const { query: currentQuery } = global.localTextSearch.byChatThreadKey[chatThreadKey] || {};\n\n if (query !== currentQuery) {\n global = replaceLocalTextSearchResults(global, chatId, threadId, MEMO_EMPTY_ARRAY);\n }\n\n global = updateLocalTextSearch(global, chatId, threadId, true, query);\n\n return global;\n});\n\naddReducer('setLocalMediaSearchType', (global, actions, payload) => {\n const { chatId } = selectCurrentMessageList(global) || {};\n if (!chatId) {\n return undefined;\n }\n\n const { mediaType } = payload!;\n return updateLocalMediaSearchType(global, chatId, mediaType);\n});\n","import { addReducer } from '../../../lib/teact/teactn';\n\naddReducer('setStickerSearchQuery', (global, actions, payload) => {\n const { query } = payload!;\n\n return {\n ...global,\n stickers: {\n ...global.stickers,\n search: {\n query,\n resultIds: undefined,\n },\n },\n };\n});\n\naddReducer('setGifSearchQuery', (global, actions, payload) => {\n const { query } = payload!;\n\n return {\n ...global,\n gifs: {\n ...global.gifs,\n search: {\n query,\n offsetId: undefined,\n results: undefined,\n },\n },\n };\n});\n","import { addReducer } from '../../../lib/teact/teactn';\n\nimport { GlobalState } from '../../../global/types';\n\nimport { updateSelectedUserId } from '../../reducers';\n\naddReducer('openUserInfo', (global, actions, payload) => {\n const { id } = payload!;\n\n actions.openChat({ id });\n});\n\nconst clearSelectedUserId = (global: GlobalState) => updateSelectedUserId(global, undefined);\n\naddReducer('openChat', clearSelectedUserId);\n","import { addReducer } from '../../../lib/teact/teactn';\nimport { ISettings, IThemeSettings, ThemeKey } from '../../../types';\nimport { replaceSettings, replaceThemeSettings } from '../../reducers';\n\naddReducer('setSettingOption', (global, actions, payload?: Partial) => {\n return replaceSettings(global, payload);\n});\n\naddReducer('setThemeSettings', (global, actions, payload: { theme: ThemeKey } & Partial) => {\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_SINGLE_COLUMN_LAYOUT, IS_TABLET_COLUMN_LAYOUT } from '../../../util/environment';\nimport getReadableErrorText from '../../../util/getReadableErrorText';\nimport { selectCurrentMessageList } from '../../selectors';\nimport { ApiError } from '../../../api/types';\n\nconst MAX_STORED_EMOJIS = 18; // Represents two rows of recent emojis\n\naddReducer('toggleChatInfo', (global) => {\n return {\n ...global,\n isChatInfoShown: !global.isChatInfoShown,\n };\n});\n\naddReducer('toggleManagement', (global): GlobalState | undefined => {\n const { chatId } = selectCurrentMessageList(global) || {};\n\n if (!chatId) {\n return undefined;\n }\n\n return {\n ...global,\n management: {\n byChatId: {\n ...global.management.byChatId,\n [chatId]: {\n ...global.management.byChatId[chatId],\n isActive: !(global.management.byChatId[chatId] || {}).isActive,\n },\n },\n },\n };\n});\n\naddReducer('closeManagement', (global): GlobalState | undefined => {\n const { chatId } = selectCurrentMessageList(global) || {};\n\n if (!chatId) {\n return undefined;\n }\n\n return {\n ...global,\n management: {\n byChatId: {\n ...global.management.byChatId,\n [chatId]: {\n ...global.management.byChatId[chatId],\n isActive: false,\n },\n },\n },\n };\n});\n\naddReducer('openChat', (global, actions, payload) => {\n if (!IS_SINGLE_COLUMN_LAYOUT && !IS_TABLET_COLUMN_LAYOUT) {\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('showDialog', (global, actions, payload) => {\n const { data } = payload!;\n\n // Filter out errors that we don't want to show to the user\n if ('message' in data && data.hasErrorKey && !getReadableErrorText(data)) {\n return global;\n }\n\n const newDialogs = [...global.dialogs];\n if ('message' in data) {\n const existingErrorIndex = newDialogs.findIndex((err) => (err as ApiError).message === data.message);\n if (existingErrorIndex !== -1) {\n newDialogs.splice(existingErrorIndex, 1);\n }\n }\n\n newDialogs.push(data);\n\n return {\n ...global,\n dialogs: newDialogs,\n };\n});\n\naddReducer('dismissDialog', (global) => {\n const newDialogs = [...global.dialogs];\n\n newDialogs.pop();\n\n return {\n ...global,\n dialogs: newDialogs,\n };\n});\n\naddReducer('toggleSafeLinkModal', (global, actions, payload) => {\n const { url: safeLinkModalUrl } = payload;\n\n return {\n ...global,\n safeLinkModalUrl,\n };\n});\n\naddReducer('openHistoryCalendar', (global, actions, payload) => {\n const { selectedAt } = payload;\n\n return {\n ...global,\n historyCalendarSelectedAt: selectedAt,\n };\n});\n\naddReducer('closeHistoryCalendar', (global) => {\n return {\n ...global,\n historyCalendarSelectedAt: undefined,\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 { serverTimeOffset } = global;\n const { chatId } = payload!;\n const chat = selectChat(global, chatId);\n if (!chat) {\n return;\n }\n\n void callApi('requestChatUpdate', {\n chat,\n serverTimeOffset,\n });\n});\n\naddReducer('updateChatMutedState', (global, actions, payload) => {\n const { serverTimeOffset } = global;\n const { chatId, isMuted } = payload!;\n const chat = selectChat(global, chatId);\n if (!chat) {\n return;\n }\n\n setGlobal(updateChat(global, chatId, { isMuted }));\n void callApi('updateChatMutedState', { chat, isMuted, serverTimeOffset });\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(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('deleteChatUser', (global, actions, payload) => {\n (async () => {\n const { chatId, userId } : {chatId: number; userId: number} = payload!;\n const chat = selectChat(global, chatId);\n const user = selectUser(global, userId);\n if (!chat || !user) {\n return;\n }\n await callApi('deleteChatUser', { chat, user });\n\n const activeChat = selectCurrentMessageList(global);\n if (activeChat && activeChat.chatId === chatId && global.currentUserId === userId) {\n actions.openChat({ id: undefined });\n }\n })();\n});\n\naddReducer('deleteChat', (global, actions, payload) => {\n (async () => {\n const { chatId } : {chatId: number } = payload!;\n const chat = selectChat(global, chatId);\n if (!chat) {\n return;\n }\n await callApi('deleteChat', { chatId: chat.id });\n\n const activeChat = selectCurrentMessageList(global);\n if (activeChat && activeChat.chatId === chatId) {\n actions.openChat({ id: undefined });\n }\n })();\n});\n\naddReducer('leaveChannel', (global, actions, payload) => {\n (async () => {\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 await callApi('leaveChannel', { channelId, accessHash });\n }\n\n const activeChannel = selectCurrentMessageList(global);\n if (activeChannel && activeChannel.chatId === chatId) {\n actions.openChat({ id: undefined });\n }\n })();\n});\n\naddReducer('deleteChannel', (global, actions, payload) => {\n (async () => {\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 await callApi('deleteChannel', { channelId, accessHash });\n }\n\n const activeChannel = selectCurrentMessageList(global);\n if (activeChannel && activeChannel.chatId === chatId) {\n actions.openChat({ id: undefined });\n }\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(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 { serverTimeOffset } = global;\n const chat = selectChat(global, id);\n if (chat) {\n if (chat.unreadCount) {\n void callApi('markMessageListRead', { serverTimeOffset, 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 result = await callApi('openChatByInvite', hash);\n if (!result) {\n return;\n }\n\n actions.openChat({ id: result.chatId });\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('acceptInviteConfirmation', (global, actions, payload) => {\n const { hash } = payload!;\n (async () => {\n const result = await callApi('importChatInvite', { hash });\n if (!result) {\n return;\n }\n\n actions.openChat({ id: result.id });\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);\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 serverTimeOffset: getGlobal().serverTimeOffset,\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 updateChat,\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';\nimport { IS_IOS } from '../../../util/environment';\n\nconst uploadProgressCallbacks = new Map();\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 { serverTimeOffset } = global;\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), serverTimeOffset,\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 global = replaceThreadParam(global, chatId, threadId, 'draft', draft);\n global = updateChat(global, chatId, { draftDate: Math.round(Date.now() / 1000) });\n\n return global;\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 global = replaceThreadParam(global, chatId, threadId, 'draft', undefined);\n global = updateChat(global, chatId, { draftDate: undefined });\n\n return global;\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 (async () => {\n const { chatId, shouldDeleteForAll } = payload!;\n const chat = selectChat(global, chatId);\n if (!chat) {\n return;\n }\n\n const maxId = chat.lastMessage && chat.lastMessage.id;\n\n await callApi('deleteHistory', { chat, shouldDeleteForAll, maxId });\n\n const activeChat = selectCurrentMessageList(global);\n if (activeChat && activeChat.chatId === chatId) {\n actions.openChat({ id: undefined });\n }\n })();\n});\n\naddReducer('markMessageListRead', (global, actions, payload) => {\n const { serverTimeOffset } = global;\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', {\n serverTimeOffset, chat, threadId, maxId,\n });\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(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 serverTimeOffset?: number;\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 || IS_IOS) {\n await rafPromise();\n }\n\n const global = getGlobal();\n params.serverTimeOffset = global.serverTimeOffset;\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 serverTimeOffset: getGlobal().serverTimeOffset,\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 { LangCode } from '../../../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 { selectEmojiKeywords, 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\naddReducer('loadEmojiKeywords', (global, actions, payload: { language: LangCode }) => {\n const { language } = payload;\n let currentEmojiKeywords = selectEmojiKeywords(global, language);\n\n if (currentEmojiKeywords && currentEmojiKeywords.isLoading) {\n return;\n }\n\n setGlobal({\n ...global,\n emojiKeywords: {\n ...global.emojiKeywords,\n [language]: {\n ...currentEmojiKeywords,\n isLoading: true,\n },\n },\n });\n\n (async () => {\n const emojiKeywords = await callApi('fetchEmojiKeywords', {\n language,\n fromVersion: currentEmojiKeywords ? currentEmojiKeywords.version : 0,\n });\n\n global = getGlobal();\n currentEmojiKeywords = selectEmojiKeywords(global, language);\n\n if (!emojiKeywords) {\n setGlobal({\n ...global,\n emojiKeywords: {\n ...global.emojiKeywords,\n [language]: {\n ...currentEmojiKeywords,\n isLoading: false,\n },\n },\n });\n\n return;\n }\n\n setGlobal({\n ...global,\n emojiKeywords: {\n ...global.emojiKeywords,\n [language]: {\n isLoading: false,\n version: emojiKeywords.version,\n keywords: {\n ...(currentEmojiKeywords && currentEmojiKeywords.keywords),\n ...emojiKeywords.keywords,\n },\n },\n },\n });\n })();\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, selectThreadInfo,\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 serverTimeOffset: getGlobal().serverTimeOffset,\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(Boolean as any);\n\n const savedChats = savedPrivateChatIds\n .map((id) => selectChat(global, id))\n .filter(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(global, chatId, MAIN_THREAD_ID, 'draft', result.draftsById[chatId]);\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 serverTimeOffset: getGlobal().serverTimeOffset,\n });\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, threadId: currentThreadId } = selectCurrentMessageList(global) || {};\n\n // Memoize drafts\n const draftChatIds = Object.keys(global.messages.byChatId).map(Number);\n const draftsByChatId = draftChatIds.reduce>((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 const threadInfo = currentThreadId && selectThreadInfo(global, currentChatId, currentThreadId);\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 if (currentThreadId && threadInfo && threadInfo.originChannelId) {\n const { originChannelId } = threadInfo;\n const currentMessageListInfoOrigin = global.messages.byChatId[originChannelId];\n const resultOrigin = await loadTopMessages(global.chats.byId[originChannelId]);\n if (resultOrigin) {\n const byIdOrigin = buildCollectionByKey(resultOrigin.messages, 'id');\n const listedIdsOrigin = Object.keys(byIdOrigin)\n .map(Number);\n\n global = {\n ...global,\n messages: {\n ...global.messages,\n byChatId: {\n ...global.messages.byChatId,\n [threadInfo.originChannelId]: {\n byId: byIdOrigin,\n threadsById: {\n [MAIN_THREAD_ID]: {\n ...(currentMessageListInfoOrigin && currentMessageListInfoOrigin.threadsById[MAIN_THREAD_ID]),\n listedIds: listedIdsOrigin,\n viewportIds: listedIdsOrigin,\n outlyingIds: undefined,\n },\n },\n },\n [currentChatId]: {\n ...global.messages.byChatId[currentChatId],\n threadsById: {\n ...global.messages.byChatId[currentChatId].threadsById,\n [currentThreadId]: {\n ...(currentMessageListInfo && currentMessageListInfo.threadsById[currentThreadId]),\n outlyingIds: undefined,\n },\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(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 = 60; // 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 {\n serverTimeOffset,\n topPeers: {\n hash, lastRequestedAt,\n },\n } = global;\n\n if (!lastRequestedAt || Date.now() / 1000 + serverTimeOffset - 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() / 1000 + global.serverTimeOffset,\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', (global) => {\n const { serverTimeOffset } = global;\n (async () => {\n const result = await callApi('fetchNotificationSettings', {\n serverTimeOffset,\n });\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\naddReducer('updateIsOnline', (global, actions, payload) => {\n callApi('updateIsOnline', payload);\n});\n\naddReducer('loadContentSettings', () => {\n (async () => {\n const result = await callApi('fetchContentSettings');\n if (!result) return;\n\n setGlobal(replaceSettings(getGlobal(), result));\n })();\n});\n\naddReducer('updateContentSettings', (global, actions, payload) => {\n (async () => {\n setGlobal(replaceSettings(getGlobal(), { isSensitiveEnabled: payload }));\n\n const result = await callApi('updateContentSettings', payload);\n if (!result) {\n setGlobal(replaceSettings(getGlobal(), { isSensitiveEnabled: !payload }));\n }\n })();\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().showDialog({ data: { 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) {\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 replaceThreadParam,\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 case 'draftMessage': {\n const {\n chatId, formattedText, date, replyingToId,\n } = update;\n const chat = global.chats.byId[chatId];\n\n if (chat) {\n global = replaceThreadParam(global, chatId, MAIN_THREAD_ID, 'draft', formattedText);\n global = replaceThreadParam(global, chatId, MAIN_THREAD_ID, 'replyingToId', replyingToId);\n global = updateChat(global, chatId, { draftDate: date });\n\n setGlobal(global);\n }\n break;\n }\n\n case 'showInvite': {\n const { data } = update;\n\n actions.showDialog({ data });\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 selectChat,\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 (!isMessageLocal(message as ApiMessage)) {\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 chatMessages = global.messages.byChatId[chatId];\n if (chatMessages) {\n const ids = Object.keys(chatMessages.byId).map(Number);\n deleteMessages(chatId, ids, actions, global);\n } else {\n actions.requestChatUpdate({ chatId });\n }\n\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, 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 const chat = selectChat(global, chatId);\n const isUnreadChatNotLoaded = chat && chat.unreadCount && !selectListedIds(global, chatId, MAIN_THREAD_ID);\n if (isUnreadChatNotLoaded) {\n return global;\n }\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 { useEffect } from '../lib/teact/teact';\n\nimport { onBeforeUnload } from '../util/schedulers';\n\nexport default function useBeforeUnload(callback: AnyToVoidFunction) {\n useEffect(() => {\n return onBeforeUnload(callback);\n }, [callback]);\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) => void;\n onCheck?: (isChecked: boolean) => void;\n};\n\nconst Switcher: FC = ({\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) => {\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 \n );\n};\n\nexport default memo(Switcher);\n","import React, {\n FC, useCallback, useMemo, memo,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../../global/types';\nimport { LeftColumnContent, ISettings } from '../../../types';\nimport { ApiChat } from '../../../api/types';\n\nimport {\n ANIMATION_LEVEL_MAX, APP_NAME, APP_VERSION, FEEDBACK_URL,\n} from '../../../config';\nimport { IS_SINGLE_COLUMN_LAYOUT } from '../../../util/environment';\nimport buildClassName from '../../../util/buildClassName';\nimport { pick } from '../../../util/iteratees';\nimport { isChatArchived } from '../../../modules/helpers';\nimport { formatDateToString } from '../../../util/dateFormat';\nimport { selectTheme } from '../../../modules/selectors';\nimport switchTheme from '../../../util/switchTheme';\nimport useLang from '../../../hooks/useLang';\n\nimport DropdownMenu from '../../ui/DropdownMenu';\nimport MenuItem from '../../ui/MenuItem';\nimport Button from '../../ui/Button';\nimport SearchInput from '../../ui/SearchInput';\nimport PickerSelectedItem from '../../common/PickerSelectedItem';\nimport Switcher from '../../ui/Switcher';\n\nimport './LeftMainHeader.scss';\n\ntype OwnProps = {\n content: LeftColumnContent;\n contactsFilter: string;\n onSearchQuery: (query: string) => void;\n onSelectSettings: () => void;\n onSelectContacts: () => void;\n onSelectArchived: () => void;\n onReset: () => void;\n};\n\ntype StateProps = {\n searchQuery?: string;\n isLoading: boolean;\n currentUserId?: number;\n globalSearchChatId?: number;\n searchDate?: number;\n theme: ISettings['theme'];\n animationLevel: 0 | 1 | 2;\n chatsById?: Record;\n};\n\ntype DispatchProps = Pick;\n\nconst ANIMATION_LEVEL_OPTIONS = [0, 1, 2];\n\nconst PRODUCTION_HOSTNAME = 'web.telegram.org';\nconst LEGACY_VERSION_URL = 'https://web.telegram.org/?legacy=1';\nconst WEBK_VERSION_URL = 'https://web.telegram.org/k/';\nconst PERMANENT_VERSION_KEY = 'kz_version';\n\nconst LeftMainHeader: FC = ({\n content,\n contactsFilter,\n onSearchQuery,\n onSelectSettings,\n onSelectContacts,\n onSelectArchived,\n setGlobalSearchChatId,\n onReset,\n searchQuery,\n isLoading,\n currentUserId,\n globalSearchChatId,\n searchDate,\n theme,\n animationLevel,\n chatsById,\n openChat,\n openTipsChat,\n setGlobalSearchDate,\n setSettingOption,\n}) => {\n const 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 withOtherVersions = window.location.hostname === PRODUCTION_HOSTNAME;\n\n const MainButton: FC<{ onTrigger: () => void; isOpen?: boolean }> = useMemo(() => {\n return ({ onTrigger, isOpen }) => (\n onReset()}\n ariaLabel={hasMenu ? lang('AccDescrOpenMenu2') : 'Return to chat list'}\n >\n
\n \n );\n }, [hasMenu, lang, onReset]);\n\n const handleSearchFocus = useCallback(() => {\n if (!searchQuery) {\n onSearchQuery('');\n }\n }, [searchQuery, onSearchQuery]);\n\n const handleSelectSaved = useCallback(() => {\n openChat({ id: currentUserId });\n }, [currentUserId, openChat]);\n\n const handleDarkModeToggle = useCallback((e: React.SyntheticEvent) => {\n e.stopPropagation();\n const newTheme = theme === 'light' ? 'dark' : 'light';\n\n setSettingOption({ theme: newTheme });\n setSettingOption({ shouldUseSystemTheme: false });\n switchTheme(newTheme, animationLevel === ANIMATION_LEVEL_MAX);\n }, [animationLevel, setSettingOption, theme]);\n\n const handleAnimationLevelChange = useCallback((e: React.SyntheticEvent) => {\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 handleSwitchToWebK = () => {\n localStorage.setItem(PERMANENT_VERSION_KEY, JSON.stringify('K'));\n };\n\n const isSearchFocused = (\n Boolean(globalSearchChatId)\n || content === LeftColumnContent.GlobalSearch\n || content === LeftColumnContent.Contacts\n );\n\n const searchInputPlaceholder = content === LeftColumnContent.Contacts\n ? lang('SearchFriends')\n : lang('Search');\n\n return (\n
\n
\n \n \n {lang('SavedMessages')}\n \n \n {lang('ArchivedChats')}\n {archivedUnreadChatsCount > 0 && (\n
{archivedUnreadChatsCount}
\n )}\n \n \n {lang('Contacts')}\n \n \n {lang('Settings')}\n \n \n {lang('lng_menu_night_mode')}\n \n \n \n {lang('Appearance.Animations').toLowerCase()}\n 0}\n />\n \n \n {lang('TelegramFeatures')}\n \n \n Report Bug\n \n {withOtherVersions && (\n <>\n \n Switch to K Version\n \n \n Switch to Old Version\n \n \n )}\n \n \n {selectedSearchDate && (\n \n )}\n {globalSearchChatId && (\n \n )}\n \n
\n
\n );\n};\n\nexport default memo(withGlobal(\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 { 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: selectTheme(global),\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, { memo, FC } from '../../lib/teact/teact';\n\nimport { GlobalState } from '../../global/types';\n\nimport useLang from '../../hooks/useLang';\n\nimport Spinner from '../ui/Spinner';\n\nimport './ConnectionState.scss';\n\ntype StateProps = Pick;\n\nconst ConnectionState: FC = () => {\n const lang = useLang();\n\n return (\n
\n \n
{lang('WaitingForNetwork')}
\n
\n );\n};\n\nexport default memo(ConnectionState);\n","import { useRef } from '../lib/teact/teact';\n\nimport useThrottle from './useThrottle';\nimport useOnChange from './useOnChange';\nimport useForceUpdate from './useForceUpdate';\n\nexport default (resolverFn: () => R, ms: number, dependencies: D) => {\n const valueRef = useRef();\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;\n usersById: Record;\n chatFoldersById: Record;\n notifySettings: NotifySettings;\n notifyExceptions?: Record;\n orderedFolderIds?: number[];\n activeChatFolder: number;\n currentUserId?: number;\n lastSyncTime?: number;\n};\n\ntype DispatchProps = Pick;\n\nconst INFO_THROTTLE = 3000;\nconst SAVED_MESSAGES_HOTKEY = '0';\n\nconst ChatFolders: FC = ({\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(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 ;\n }\n\n return (\n \n );\n }\n\n return (\n
\n {folderTabs && folderTabs.length ? (\n \n ) : shouldRenderPlaceholder ? (\n
\n ) : undefined}\n \n {renderCurrentTab}\n \n
\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 = (props) => {\n const LeftSearch = useModuleLoader(Bundles.Extra, 'LeftSearch');\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return LeftSearch ? : ;\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 = (props) => {\n const ContactList = useModuleLoader(Bundles.Extra, 'ContactList');\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return ContactList ? : ;\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 = ({\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 \n \n \n \n \n \n {lang('NewChannel')}\n {lang('NewGroup')}\n {lang('NewMessageTitle')}\n \n
\n );\n};\n\nexport default memo(NewChatButton);\n","import React, {\n FC, useState, useRef, useCallback, useEffect,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalState } from '../../../global/types';\nimport { LeftColumnContent } from '../../../types';\n\nimport { IS_TOUCH_ENV } from '../../../util/environment';\nimport { pick } from '../../../util/iteratees';\nimport buildClassName from '../../../util/buildClassName';\nimport useBrowserOnline from '../../../hooks/useBrowserOnline';\nimport useFlag from '../../../hooks/useFlag';\nimport useShowTransition from '../../../hooks/useShowTransition';\nimport useLang from '../../../hooks/useLang';\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';\nimport ShowTransition from '../../ui/ShowTransition';\nimport Button from '../../ui/Button';\n\nimport './LeftMain.scss';\n\ntype OwnProps = {\n content: LeftColumnContent;\n searchQuery?: string;\n searchDate?: number;\n contactsFilter: string;\n onSearchQuery: (query: string) => void;\n onContentChange: (content: LeftColumnContent) => void;\n onReset: () => void;\n};\n\ntype StateProps = Pick;\n\nconst TRANSITION_RENDER_COUNT = Object.keys(LeftColumnContent).length / 2;\nconst BUTTON_CLOSE_DELAY_MS = 250;\nconst APP_OUTDATED_TIMEOUT = 3 * 24 * 60 * 60 * 1000; // 3 days\n\nlet closeTimeout: number | undefined;\n\nconst LeftMain: FC = ({\n content,\n searchQuery,\n searchDate,\n contactsFilter,\n onSearchQuery,\n onContentChange,\n onReset,\n connectionState,\n}) => {\n const [isNewChatButtonShown, setIsNewChatButtonShown] = useState(IS_TOUCH_ENV);\n\n const isBrowserOnline = useBrowserOnline();\n const isConnecting = !isBrowserOnline || connectionState === 'connectionStateConnecting';\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 const [shouldRenderUpdateButton, updateButtonClassNames, handleUpdateClick] = useAppOutdatedCheck();\n\n const lang = useLang();\n\n return (\n \n \n \n {() => }\n \n \n {(isActive) => {\n switch (content) {\n case LeftColumnContent.ChatList:\n return ;\n case LeftColumnContent.GlobalSearch:\n return (\n \n );\n case LeftColumnContent.Contacts:\n return ;\n default:\n return undefined;\n }\n }}\n \n {shouldRenderUpdateButton && (\n \n {lang('lng_update_telegram')}\n \n )}\n \n
\n );\n};\n\nfunction useAppOutdatedCheck() {\n const [isAppOutdated, markIsAppOutdated] = useFlag(false);\n\n useEffect(() => {\n const timeout = window.setTimeout(markIsAppOutdated, APP_OUTDATED_TIMEOUT);\n\n return () => {\n clearTimeout(timeout);\n };\n }, [markIsAppOutdated]);\n\n const { shouldRender, transitionClassNames } = useShowTransition(isAppOutdated);\n\n const handleUpdateClick = () => {\n window.location.reload();\n };\n\n return [shouldRender, transitionClassNames, handleUpdateClick] as const;\n}\n\nexport default withGlobal(\n (global): StateProps => pick(global, ['connectionState']),\n)(LeftMain);\n","import { useEffect, useState } from '../lib/teact/teact';\n\nexport default function useBrowserOnline() {\n const [isOnline, setIsOnline] = useState(window.navigator.onLine);\n\n useEffect(() => {\n function handleChange() {\n setIsOnline(window.navigator.onLine);\n }\n\n window.addEventListener('online', handleChange);\n window.addEventListener('offline', handleChange);\n\n return () => {\n window.removeEventListener('offline', handleChange);\n window.removeEventListener('online', handleChange);\n };\n }, []);\n\n return isOnline;\n}\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 = (props) => {\n const Settings = useModuleLoader(Bundles.Extra, 'Settings');\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return Settings ? : ;\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 = (props) => {\n const NewChat = useModuleLoader(Bundles.Extra, 'NewChat');\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return NewChat ? : ;\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 = (props) => {\n const ArchivedChats = useModuleLoader(Bundles.Extra, 'ArchivedChats');\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return ArchivedChats ? : ;\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 { LAYERS_ANIMATION_NAME } from '../../util/environment';\nimport captureEscKeyListener from '../../util/captureEscKeyListener';\nimport { pick } from '../../util/iteratees';\n\nimport Transition from '../ui/Transition';\nimport LeftMain from './main/LeftMain';\nimport Settings from './settings/Settings.async';\nimport NewChat from './newChat/NewChat.async';\nimport ArchivedChats from './ArchivedChats.async';\n\nimport './LeftColumn.scss';\n\ntype StateProps = {\n searchQuery?: string;\n searchDate?: number;\n activeChatFolder: number;\n};\n\ntype DispatchProps = Pick;\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 = ({\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.ChatList);\n const [settingsScreen, setSettingsScreen] = useState(SettingsScreens.Main);\n const [contactsFilter, setContactsFilter] = useState('');\n\n // Used to reset child components in background.\n const [lastResetTime, setLastResetTime] = useState(0);\n\n let contentType: ContentType = ContentType.Main;\n switch (content) {\n case LeftColumnContent.Archived:\n contentType = ContentType.Archived;\n break;\n case LeftColumnContent.Settings:\n contentType = ContentType.Settings;\n break;\n case LeftColumnContent.NewChannelStep1:\n case LeftColumnContent.NewChannelStep2:\n contentType = ContentType.NewChannel;\n break;\n case LeftColumnContent.NewGroupStep1:\n case LeftColumnContent.NewGroupStep2:\n contentType = ContentType.NewGroup;\n break;\n }\n\n const handleReset = useCallback((forceReturnToChatList?: boolean) => {\n if (\n content === LeftColumnContent.NewGroupStep2\n && !forceReturnToChatList\n ) {\n setContent(LeftColumnContent.NewGroupStep1);\n return;\n }\n\n if (content === LeftColumnContent.NewGroupStep1) {\n const pickerSearchInput = document.getElementById('new-group-picker-search');\n if (pickerSearchInput) {\n pickerSearchInput.blur();\n }\n }\n\n if (content === LeftColumnContent.Settings) {\n switch (settingsScreen) {\n case SettingsScreens.EditProfile:\n case SettingsScreens.Folders:\n case SettingsScreens.General:\n case SettingsScreens.Notifications:\n case SettingsScreens.Privacy:\n case SettingsScreens.Language:\n setSettingsScreen(SettingsScreens.Main);\n return;\n\n case SettingsScreens.GeneralChatBackground:\n setSettingsScreen(SettingsScreens.General);\n return;\n case SettingsScreens.GeneralChatBackgroundColor:\n setSettingsScreen(SettingsScreens.GeneralChatBackground);\n return;\n\n case SettingsScreens.PrivacyPhoneNumber:\n case SettingsScreens.PrivacyLastSeen:\n case SettingsScreens.PrivacyProfilePhoto:\n case SettingsScreens.PrivacyForwarding:\n case SettingsScreens.PrivacyGroupChats:\n case SettingsScreens.PrivacyActiveSessions:\n case SettingsScreens.PrivacyBlockedUsers:\n case SettingsScreens.TwoFaDisabled:\n case SettingsScreens.TwoFaEnabled:\n case SettingsScreens.TwoFaCongratulations:\n setSettingsScreen(SettingsScreens.Privacy);\n return;\n case SettingsScreens.PrivacyPhoneNumberAllowedContacts:\n case SettingsScreens.PrivacyPhoneNumberDeniedContacts:\n setSettingsScreen(SettingsScreens.PrivacyPhoneNumber);\n return;\n case SettingsScreens.PrivacyLastSeenAllowedContacts:\n case SettingsScreens.PrivacyLastSeenDeniedContacts:\n setSettingsScreen(SettingsScreens.PrivacyLastSeen);\n return;\n case SettingsScreens.PrivacyProfilePhotoAllowedContacts:\n case SettingsScreens.PrivacyProfilePhotoDeniedContacts:\n setSettingsScreen(SettingsScreens.PrivacyProfilePhoto);\n return;\n case SettingsScreens.PrivacyForwardingAllowedContacts:\n case SettingsScreens.PrivacyForwardingDeniedContacts:\n setSettingsScreen(SettingsScreens.PrivacyForwarding);\n return;\n case SettingsScreens.PrivacyGroupChatsAllowedContacts:\n case SettingsScreens.PrivacyGroupChatsDeniedContacts:\n setSettingsScreen(SettingsScreens.PrivacyGroupChats);\n return;\n case SettingsScreens.TwoFaNewPassword:\n setSettingsScreen(SettingsScreens.TwoFaDisabled);\n return;\n case SettingsScreens.TwoFaNewPasswordConfirm:\n setSettingsScreen(SettingsScreens.TwoFaNewPassword);\n return;\n case SettingsScreens.TwoFaNewPasswordHint:\n setSettingsScreen(SettingsScreens.TwoFaNewPasswordConfirm);\n return;\n case SettingsScreens.TwoFaNewPasswordEmail:\n setSettingsScreen(SettingsScreens.TwoFaNewPasswordHint);\n return;\n case SettingsScreens.TwoFaNewPasswordEmailCode:\n setSettingsScreen(SettingsScreens.TwoFaNewPasswordEmail);\n return;\n case SettingsScreens.TwoFaChangePasswordCurrent:\n case SettingsScreens.TwoFaTurnOff:\n case SettingsScreens.TwoFaRecoveryEmailCurrentPassword:\n setSettingsScreen(SettingsScreens.TwoFaEnabled);\n return;\n case SettingsScreens.TwoFaChangePasswordNew:\n setSettingsScreen(SettingsScreens.TwoFaChangePasswordCurrent);\n return;\n case SettingsScreens.TwoFaChangePasswordConfirm:\n setSettingsScreen(SettingsScreens.TwoFaChangePasswordNew);\n return;\n case SettingsScreens.TwoFaChangePasswordHint:\n setSettingsScreen(SettingsScreens.TwoFaChangePasswordConfirm);\n return;\n case SettingsScreens.TwoFaRecoveryEmail:\n setSettingsScreen(SettingsScreens.TwoFaRecoveryEmailCurrentPassword);\n return;\n case SettingsScreens.TwoFaRecoveryEmailCode:\n setSettingsScreen(SettingsScreens.TwoFaRecoveryEmail);\n return;\n\n case SettingsScreens.FoldersCreateFolder:\n case SettingsScreens.FoldersEditFolder:\n setSettingsScreen(SettingsScreens.Folders);\n return;\n default:\n break;\n }\n }\n\n if (content === LeftColumnContent.ChatList && activeChatFolder === 0) {\n setContent(LeftColumnContent.GlobalSearch);\n return;\n }\n\n setContent(LeftColumnContent.ChatList);\n setContactsFilter('');\n setGlobalSearchQuery({ query: '' });\n setGlobalSearchDate({ date: undefined });\n setGlobalSearchChatId({ id: undefined });\n resetChatCreation();\n setTimeout(() => {\n setLastResetTime(Date.now());\n }, RESET_TRANSITION_DELAY_MS);\n }, [\n content, activeChatFolder, setGlobalSearchQuery, setGlobalSearchDate, setGlobalSearchChatId, resetChatCreation,\n settingsScreen,\n ]);\n\n const handleSearchQuery = useCallback((query: string) => {\n if (content === LeftColumnContent.Contacts) {\n setContactsFilter(query);\n return;\n }\n\n setContent(LeftColumnContent.GlobalSearch);\n\n if (query !== searchQuery) {\n setGlobalSearchQuery({ query });\n }\n }, [content, setGlobalSearchQuery, searchQuery]);\n\n useEffect(\n () => (content !== LeftColumnContent.ChatList || 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 \n {(isActive) => {\n switch (contentType) {\n case ContentType.Archived:\n return (\n \n );\n case ContentType.Settings:\n return (\n \n );\n case ContentType.NewChannel:\n return (\n \n );\n case ContentType.NewGroup:\n return (\n \n );\n default:\n return (\n \n );\n }\n }}\n \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 { throttle } from '../util/schedulers';\nimport windowSize from '../util/windowSize';\nimport { ApiDimensions } from '../api/types';\n\nconst THROTTLE = 250;\n\nexport default () => {\n const [size, setSize] = useState(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 = (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 ? : 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_SINGLE_COLUMN_LAYOUT } 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;\n\n// Chrome breaks layout when focusing input during transition\nconst SEARCH_FOCUS_DELAY_MS = 400;\n\nconst HeaderActions: FC = ({\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(null);\n const [isMenuOpen, setIsMenuOpen] = useState(false);\n const [menuPosition, setMenuPosition] = useState(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_SINGLE_COLUMN_LAYOUT) {\n // iOS requires synchronous focus on user event.\n const searchInput = document.querySelector('#MobileSearch input')!;\n searchInput.focus();\n } else {\n setTimeout(() => {\n const searchInput = document.querySelector('.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
\n {!IS_SINGLE_COLUMN_LAYOUT && canSubscribe && (\n \n {lang(isChannel ? 'Subscribe' : 'Join Group')}\n \n )}\n {!IS_SINGLE_COLUMN_LAYOUT && canStartBot && (\n \n {lang('BotStart')}\n \n )}\n {!IS_SINGLE_COLUMN_LAYOUT && canSearch && (\n \n \n \n )}\n {(IS_SINGLE_COLUMN_LAYOUT || !canSubscribe) && (\n \n \n \n )}\n {menuPosition && (\n \n )}\n
\n );\n};\n\nexport default memo(withGlobal(\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_SINGLE_COLUMN_LAYOUT && canSubscribe)\n || (IS_SINGLE_COLUMN_LAYOUT && 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 = ({\n count, index,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const containerRef = useRef(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 = ` ${clipPath} `;\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
\n \n
\n );\n }\n\n const {\n trackHeight, trackTranslateY, markHeight, markTranslateY, clipPathId,\n } = markupParams;\n\n return (\n
BORDER_MASK_LEVEL && 'pinned-message-border-mask')}>\n \n \n \n
\n \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 `\n \n `\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 = ({\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
\n {count > 1 && (\n \n \n \n )}\n {onUnpinMessage && (\n \n \n \n )}\n \n
\n \n {mediaThumbnail && renderPictogram(mediaThumbnail, mediaBlobUrl)}\n
\n
\n {customTitle || `${lang('PinnedMessage')} ${index > 0 ? `#${count - index}` : ''}`}\n
\n

{renderText(text)}

\n
\n\n \n
\n
\n );\n};\n\nfunction renderPictogram(thumbDataUri: string, blobUrl?: string) {\n const { width, height } = getPictogramDimensions();\n\n return (\n \"\"\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_SINGLE_COLUMN_LAYOUT } 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;\n\nconst AudioPlayer: FC = ({\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
\n \n \n \n \n\n
\n {audio ? renderAudio(audio) : renderVoice(lang('AttachAudio'), senderName)}\n \n
\n\n \n \n \n
\n );\n};\n\nfunction renderAudio(audio: ApiAudio) {\n const { title, performer, fileName } = audio;\n\n return (\n <>\n
{renderText(title || fileName)}
\n {performer && (\n
{renderText(performer)}
\n )}\n \n );\n}\n\nfunction renderVoice(subtitle: string, senderName?: string) {\n return (\n <>\n
{senderName && renderText(senderName)}
\n
{subtitle}
\n \n );\n}\n\nexport default withGlobal(\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_SINGLE_COLUMN_LAYOUT, IS_TABLET_COLUMN_LAYOUT } 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;\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;\n originChatId: number;\n messagesCount?: number;\n isChatWithSelf?: boolean;\n isChatWithBot?: boolean;\n lastSyncTime?: number;\n notifySettings: NotifySettings;\n notifyExceptions?: Record;\n};\n\ntype DispatchProps = Pick;\n\nconst MiddleHeader: FC = ({\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 = IS_TABLET_COLUMN_LAYOUT && isLeftColumnShown;\n\n // eslint-disable-next-line no-null/no-null\n const componentRef = useRef(null);\n const shouldAnimateTools = useRef(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((e: React.MouseEvent) => {\n if (IS_SINGLE_COLUMN_LAYOUT) {\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_SINGLE_COLUMN_LAYOUT || shouldShowCloseButton) {\n e.stopPropagation(); // Stop propagation to prevent chat re-opening on tablets\n openChat({ id: undefined });\n } else {\n toggleLeftColumn();\n }\n\n return;\n }\n\n if (messageListType === 'scheduled' && isSelectModeActive) {\n exitMessageSelectMode();\n }\n\n openChat({ id: originChatId, threadId: MAIN_THREAD_ID });\n }, [\n openChat, originChatId, threadId, messageListType, toggleLeftColumn, isSelectModeActive, exitMessageSelectMode,\n shouldShowCloseButton,\n ]);\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

\n {lang('CommentsCount', messagesCount)}\n

\n \n ) : messageListType === 'pinned' ? (\n <>\n {renderBackButton()}\n

\n {lang('PinnedMessagesCount', messagesCount)}\n

\n \n ) : messageListType === 'scheduled' ? (\n <>\n {renderBackButton()}\n

\n {isChatWithSelf ? lang('Reminders') : lang('messages', messagesCount)}\n

\n \n ) : undefined\n );\n }\n\n function renderMainThreadInfo() {\n return (\n <>\n {isLeftColumnHideable && renderBackButton(shouldShowCloseButton, unreadCount)}\n
\n {isChatPrivate(chatId) ? (\n \n ) : (\n \n )}\n
\n \n );\n }\n\n function renderBackButton(asClose = false, unreadCountInfo?: typeof unreadCount) {\n return (\n
\n \n
\n \n {unreadCountInfo && (\n
\n {formatIntegerCompact(unreadCountInfo.totalCount)}\n
\n )}\n
\n );\n }\n\n return (\n
\n \n {renderInfo}\n \n\n
\n {shouldRenderPinnedMessage && renderingPinnedMessage && !shouldRenderAudioPlayer && (\n \n )}\n {shouldRenderAudioPlayer && renderingAudioMessage && (\n \n )}\n \n
\n
\n );\n};\n\nexport default memo(withGlobal(\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\nconst GROUP_INTERVAL_SECONDS = 600; // 10 minutes\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 nextMessageDayStartsAt = Number(getDayStart(nextMessage.date * 1000));\n if (currentDateGroup.datetime !== nextMessageDayStartsAt) {\n currentDateGroup = {\n originalDate: nextMessage.date,\n datetime: nextMessageDayStartsAt,\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 || (nextMessage.date - message.date) > GROUP_INTERVAL_SECONDS\n ) {\n currentSenderGroup = [];\n currentDateGroup.senderGroups.push(currentSenderGroup);\n }\n }\n });\n\n return dateGroups;\n}\n","import React from '../../../lib/teact/teact';\n\nimport { EDITABLE_INPUT_ID } from '../../../config';\nimport { IS_SINGLE_COLUMN_LAYOUT } from '../../../util/environment';\n\nexport function preventMessageInputBlur(e: React.MouseEvent) {\n if (\n IS_SINGLE_COLUMN_LAYOUT\n || !document.activeElement\n || document.activeElement.id !== EDITABLE_INPUT_ID\n || e.target !== e.currentTarget\n ) {\n return;\n }\n\n e.preventDefault();\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('.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, { FC, useCallback, useRef } 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;\n className: string;\n messageIds: 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 TOOLS_FREEZE_TIMEOUT = 100;\n\nconst MessageScroll: FC = ({\n containerRef,\n className,\n messageIds,\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(null);\n // eslint-disable-next-line no-null/no-null\n const forwardsTriggerRef = useRef(null);\n // eslint-disable-next-line no-null/no-null\n const fabTriggerRef = useRef(null);\n\n const toggleScrollTools = useCallback(() => {\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 } = 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 freeze: freezeForNotch,\n unfreeze: unfreezeForNotch,\n } = useIntersectionObserver({\n rootRef: containerRef,\n }, toggleScrollTools);\n\n useOnIntersect(fabTriggerRef, observeIntersectionForNotch);\n\n // Workaround for FAB and notch flickering with tall incoming message\n useOnChange(() => {\n freezeForFab();\n freezeForNotch();\n\n setTimeout(() => {\n unfreezeForNotch();\n unfreezeForFab();\n }, TOOLS_FREEZE_TIMEOUT);\n }, [messageIds]);\n\n return (\n
\n
\n {children}\n \n \n
\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 || webPage.video) {\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, noAvatars?: boolean) {\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, noAvatars)\n : calculateVideoDimensions(video!, isOwn, isForwarded, noAvatars);\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, ApiDimensions } from '../../../../api/types';\n\nimport { getAvailableWidth, REM } from '../../../common/helpers/mediaDimensions';\nimport { calculateMediaDimensions } from './mediaDimensions';\n\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: ApiDimensions;\n};\n\nfunction getRatios(messages: ApiMessage[]) {\n return messages.map(\n (message) => {\n const dimensions = calculateMediaDimensions(message) as ApiDimensions;\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: ApiDimensions = { 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 noAvatars: boolean,\n album: IAlbum,\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 = getAvailableWidth(isOwn, isForwarded, false, noAvatars) - (isForwarded ? 2.5 : 0) * REM;\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 // eslint-disable-next-line max-len\n element.style.font = '400 12px \"Roboto\", -apple-system, \"Apple Color Emoji\", BlinkMacSystemFont, \"Helvetica Neue\", 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('.MessageList')!;\n\n fastSmoothScroll(\n messagesContainer,\n elementRef.current,\n // `noFocusHighlight` always called from “scroll-to-bottom” buttons\n noFocusHighlight ? 'end' : 'centerOrTop',\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 = (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 ? : 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';\nimport { preventMessageInputBlur } from './helpers/preventMessageInputBlur';\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 = ({\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(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 const handleMouseDown = (e: React.MouseEvent) => {\n preventMessageInputBlur(e);\n handleBeforeContextMenu(e);\n };\n\n if (isEmbedded) {\n return {renderText(content as string)};\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 \n {content}\n {contextMenuPosition && (\n \n )}\n
\n );\n};\n\nexport default memo(withGlobal(\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 = ({\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(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 \n {mediaThumbnail && renderPictogram(pictogramId, mediaThumbnail, mediaBlobUrl, isRoundVideo)}\n
\n

\n {!message ? (\n customText || NBSP\n ) : isActionMessage(message) ? (\n \n ) : (\n renderText(getMessageSummaryText(lang, message, Boolean(mediaThumbnail)))\n )}\n

\n
{renderText(senderTitle || title || NBSP)}
\n
\n
\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 \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 = ({\n message, outgoingStatus, signature, onClick,\n}) => {\n const lang = useLang();\n\n return (\n \n {Boolean(message.views) && (\n <>\n \n {formatIntegerCompact(message.views!)}\n \n \n \n )}\n {signature && (\n {renderText(signature)}\n )}\n \n {message.isEdited && `${lang('EditedMessage')} `}\n {formatTime(message.date * 1000)}\n \n {outgoingStatus && (\n \n )}\n \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 = ({\n message, observeIntersection, observeIntersectionForPlaying, shouldLoop, lastSyncTime,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const ref = useRef(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
\n {!isMediaReady && (\n \n )}\n {!isAnimated && shouldRenderFullMedia && (\n \n )}\n {isAnimated && isMediaLoaded && (\n \n )}\n \n
\n );\n};\n\nexport default Sticker;\n","import { ApiMessage } from '../../../../api/types';\n\nimport { IS_CANVAS_FILTER_SUPPORTED, IS_SINGLE_COLUMN_LAYOUT } 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_SINGLE_COLUMN_LAYOUT && !IS_CANVAS_FILTER_SUPPORTED,\n );\n}\n","const SELECTED_APPENDIX_BACKGROUND = Promise.resolve('rgba(255,255,255,1)');\n\nexport default function getCustomAppendixBg(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 noAvatars?: boolean;\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 = ({\n id,\n message,\n observeIntersection,\n noAvatars,\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(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('.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, noAvatars);\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 \n {shouldRenderThumb && (\n \n )}\n {shouldRenderFullMedia && (\n \n )}\n {shouldRenderSpinner && (\n
\n \n
\n )}\n {!fullMediaData && !isDownloadAllowed && (\n \n )}\n {isTransferring && (\n {Math.round(transferProgress * 100)}%\n )}\n \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, 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 getMediaTransferState,\n getMessageMediaFormat,\n getMessageMediaHash,\n getMessageVideo,\n getMessageWebPageVideo,\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 noAvatars?: boolean;\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 = ({\n id,\n message,\n observeIntersection,\n noAvatars,\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(null);\n // eslint-disable-next-line no-null/no-null\n const videoRef = useRef(null);\n\n const video = (getMessageVideo(message) || getMessageWebPageVideo(message))!;\n const localBlobUrl = video.blobUrl;\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(isIntersecting && fullMediaData);\n\n const { isBuffered, bufferingHandlers } = useBuffering(!shouldAutoLoad);\n const { isUploading, isTransferring, transferProgress } = getMediaTransferState(\n message,\n uploadProgress || downloadProgress,\n shouldDownload && !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(0);\n const handleTimeUpdate = useCallback((e: React.SyntheticEvent) => {\n setPlayProgress(Math.max(0, e.currentTarget.currentTime - 1));\n }, []);\n\n const duration = video.duration || (videoRef.current && videoRef.current.duration) || 0;\n\n const isOwn = isOwnMessage(message);\n const isForwarded = isForwardedMessage(message);\n const { width, height } = dimensions || calculateVideoDimensions(video, isOwn, isForwarded, noAvatars);\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 (!fullMediaData) {\n setIsDownloadAllowed((isAllowed) => !isAllowed);\n } else if (fullMediaData && !isPlayAllowed) {\n setIsPlayAllowed(true);\n videoRef.current!.play();\n } else if (onClick) {\n onClick(message.id);\n }\n }, [isUploading, 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 shouldRenderPlayButton = (isDownloadAllowed && !isPlayAllowed && !shouldRenderSpinner);\n const shouldRenderDownloadButton = !isDownloadAllowed;\n\n return (\n \n {(!isInline || shouldRenderThumb || shouldRenderInlineVideo)\n && (\n \n )}\n {previewBlobUrl && (\n \n )}\n\n {shouldRenderInlineVideo && (\n \n \n \n )}\n {shouldRenderPlayButton && (\n \n )}\n {shouldRenderSpinner && (\n
\n \n
\n )}\n {shouldRenderDownloadButton && (\n \n )}\n {isTransferring ? (\n ...\n ) : (\n
\n {video.isGif ? 'GIF' : formatMediaDuration(Math.max(duration - playProgress, 0))}\n
\n )}\n \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;\n\nconst Contact: FC = ({\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 \n \n
\n
{firstName} {lastName}
\n
{formatPhoneNumberWithCode(phoneNumber)}
\n
\n \n );\n};\n\nexport default withGlobal(\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 = ({\n id,\n options,\n selected = [],\n disabled,\n round,\n loadingOptions,\n onChange,\n}) => {\n const [values, setValues] = useState([]);\n\n const handleChange = useCallback((event: ChangeEvent) => {\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
\n {options.map((option) => (\n \n ))}\n
\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 = ({\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(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 \n \n `;\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
\n
\n {answerPercent}%\n {showIcon && (\n \n \n \n )}\n
\n
\n
\n {renderText(answer.text)}\n
\n
\n
\n \n
\n
\n
\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;\n serverTimeOffset: number;\n};\n\ntype DispatchProps = Pick;\n\nconst SOLUTION_CONTAINER_ID = '#middle-column-portals';\nconst SOLUTION_DURATION = 5000;\nconst NBSP = '\\u00A0';\n\nconst Poll: FC = ({\n message,\n poll,\n recentVoterIds,\n usersById,\n loadMessage,\n onSendVote,\n openPollResults,\n serverTimeOffset,\n}) => {\n const { id: messageId, chatId } = message;\n const { summary, results } = poll;\n const [isSubmitting, setIsSubmitting] = useState(false);\n const [chosenOptions, setChosenOptions] = useState([]);\n const [isSolutionShown, setIsSolutionShown] = useState(false);\n const [wasSubmitted, setWasSubmitted] = useState(false);\n const [closePeriod, setClosePeriod] = useState(\n !summary.closed && summary.closeDate && summary.closeDate > 0\n ? Math.min(summary.closeDate - Math.floor(Date.now() / 1000) + serverTimeOffset, summary.closePeriod!)\n : 0,\n );\n // eslint-disable-next-line no-null/no-null\n const countdownRef = useRef(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 ${formatMediaDuration(closePeriod)}\n \n \n `;\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 \n );\n }\n\n function renderRecentVoters() {\n return (\n recentVoters.length > 0 && (\n
\n {recentVoters.map((user) => (\n \n ))}\n
\n )\n );\n }\n\n function renderSolution() {\n return (\n isSolutionShown && poll.results.solution && (\n \n )\n );\n }\n\n return (\n
\n {renderSolution()}\n
{renderText(summary.question)}
\n
\n {lang(getPollTypeString(summary))}\n {renderRecentVoters()}\n {closePeriod > 0 && canVote &&
}\n {summary.quiz && poll.results.solution && !canVote && (\n \n \n \n )}\n
\n {canVote && (\n
\n {isMultiple\n ? (\n \n )\n : (\n \n )}\n
\n )}\n {!canVote && (\n
\n {summary.answers.map(renderResultOption)}\n
\n )}\n {!canViewResult && !isMultiple && (\n
{getReadableVotersCount(lang, summary.quiz, results.totalVoters)}
\n )}\n {isMultiple && (\n \n {lang('PollSubmitVotes')}\n \n )}\n {canViewResult && (\n \n {lang('PollViewResults')}\n \n )}\n
\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(\n (global, { poll }) => {\n const { recentVoterIds } = poll.results;\n const { serverTimeOffset, users: { byId: usersById } } = global;\n if (!recentVoterIds || recentVoterIds.length === 0) {\n return {};\n }\n\n return {\n recentVoterIds,\n usersById,\n serverTimeOffset,\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';\nimport Video from './Video';\n\nimport './WebPage.scss';\n\nconst MAX_TEXT_LENGTH = 170; // symbols\n\ntype OwnProps = {\n message: ApiMessage;\n observeIntersection?: ObserveFn;\n noAvatars?: boolean;\n shouldAutoLoad?: boolean;\n shouldAutoPlay?: boolean;\n inPreview?: boolean;\n lastSyncTime?: number;\n onMediaClick?: () => void;\n onCancelMediaTransfer?: () => void;\n};\n\nconst WebPage: FC = ({\n message,\n observeIntersection,\n noAvatars,\n shouldAutoLoad,\n shouldAutoPlay,\n inPreview,\n lastSyncTime,\n onMediaClick,\n onCancelMediaTransfer,\n}) => {\n const webPage = getMessageWebPage(message);\n\n let isSquarePhoto = false;\n if (webPage && webPage.photo && !webPage.video) {\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 video,\n } = webPage;\n const isMediaInteractive = (photo || video) && onMediaClick && !isSquarePhoto;\n const truncatedDescription = trimText(description, MAX_TEXT_LENGTH);\n\n const className = buildClassName(\n 'WebPage',\n isSquarePhoto && 'with-square-photo',\n !photo && !video && !inPreview && 'without-media',\n video && 'with-video',\n );\n\n return (\n \n {photo && !video && (\n \n )}\n
\n \n {!inPreview && title && (\n

{renderText(title)}

\n )}\n {truncatedDescription && (\n

{renderText(truncatedDescription, ['emoji', 'br'])}

\n )}\n
\n {!inPreview && video && (\n \n )}\n
\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 = ({\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 \n {title && (\n

{renderText(title)}

\n )}\n {text && (\n

{renderText(text, ['emoji', 'br'])}

\n )}\n
\n {photoUrl && (\n \n )}\n {description && (\n

{renderText(description, ['emoji', 'br'])}

\n )}\n
\n
\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;\n\nexport default function withSelectControl(WrappedComponent: FC) {\n const ComponentWithSelectControl: FC = (props) => {\n const {\n isInSelectMode,\n isSelected,\n message,\n toggleMessageSelection,\n dimensions,\n } = props;\n\n const handleMessageSelect = useCallback((e: ReactMouseEvent) => {\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 \n {isInSelectMode && (\n
\n {isSelected && (\n \n )}\n
\n )}\n {/* eslint-disable-next-line react/jsx-props-no-spreading */}\n \n \n );\n };\n\n return memo(withGlobal(\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 )(ComponentWithSelectControl));\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;\n\nconst Album: FC = ({\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 \n );\n } else if (video) {\n return (\n \n );\n }\n\n return undefined;\n }\n\n const { width: containerWidth, height: containerHeight } = albumLayout.containerStyle;\n\n return (\n \n {album.messages.map(renderAlbumMessage)}\n \n );\n};\n\nexport default withGlobal(\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 = ({\n message,\n observeIntersection,\n shouldAutoLoad,\n shouldAutoPlay,\n lastSyncTime,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const ref = useRef(null);\n // eslint-disable-next-line no-null/no-null\n const playingProgressRef = useRef(null);\n // eslint-disable-next-line no-null/no-null\n const playerRef = useRef(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(false);\n const [progress, setProgress] = useState(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 = `\n \n `;\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) => {\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 \n {(shouldRenderThumb || mediaData) && (\n
\n \n
\n )}\n {mediaData && (\n
\n {/* eslint-disable-next-line jsx-a11y/media-has-caption */}\n \n \n \n
\n )}\n
\n {shouldSpinnerRender && (\n
\n \n
\n )}\n {!mediaData && !isDownloadAllowed && (\n \n )}\n
\n {isActivated ? formatMediaDuration(playerRef.current!.currentTime) : formatMediaDuration(video.duration)}\n {(!isActivated || playerRef.current!.paused) && }\n
\n
\n );\n};\n\nexport default RoundVideo;\n","import React, { FC } from '../../../lib/teact/teact';\n\nimport { ApiKeyboardButton, ApiMessage } from '../../../api/types';\n\nimport { RE_TME_LINK } from '../../../config';\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 = ({ message, onClick }) => {\n return (\n
\n {message.inlineButtons!.map((row) => (\n
\n {row.map((button) => (\n onClick({ button })}\n >\n {button.text}\n {button.type === 'url' && !button.value!.match(RE_TME_LINK) && }\n \n ))}\n
\n ))}\n
\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;\n chatsById?: Record;\n};\n\ntype DispatchProps = Pick;\n\nconst CommentButton: FC = ({\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
\n {recentRepliers.map((user) => (\n \n ))}\n
\n )\n );\n }\n\n const hasUnread = Boolean(lastReadInboxMessageId && lastMessageId && lastReadInboxMessageId < lastMessageId);\n\n return (\n \n \n {(!recentRepliers || recentRepliers.length === 0) && }\n {renderRecentRepliers()}\n
\n {messagesCount ? lang('Comments', messagesCount, 'i') : lang('LeaveAComment')}\n
\n \n \n );\n};\n\nexport default memo(withGlobal(\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 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 {\n FocusDirection, IAlbum, ISettings, MediaViewerOrigin,\n} from '../../../types';\n\nimport { IS_ANDROID } from '../../../util/environment';\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,\n selectShouldLoopStickers,\n selectTheme,\n} from '../../../modules/selectors';\nimport {\n getMessageContent,\n isOwnMessage,\n isReplyMessage,\n isAnonymousOwnMessage,\n isMessageLocal,\n isChatPrivate,\n getMessageCustomShape,\n isChatChannel,\n getMessageSingleEmoji,\n getSenderTitle,\n 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 { preventMessageInputBlur } from '../helpers/preventMessageInputBlur';\nimport renderText from '../../common/helpers/renderText';\nimport calculateAuthorWidth from './helpers/calculateAuthorWidth';\nimport { ObserveFn, useOnIntersect } from '../../../hooks/useIntersectionObserver';\nimport useFocusMessage from './hooks/useFocusMessage';\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 noAvatars?: boolean;\n withAvatar?: boolean;\n withSenderName?: boolean;\n threadId: number;\n messageListType: MessageListType;\n noComments: boolean;\n appearanceOrder: number;\n} & MessagePositionProperties;\n\ntype StateProps = {\n theme: ISettings['theme'];\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;\n\nconst NBSP = '\\u00A0';\nconst GROUP_MESSAGE_HOVER_ATTRIBUTE = 'data-is-document-group-hover';\n// eslint-disable-next-line max-len\nconst APPENDIX_OWN = '';\n// eslint-disable-next-line max-len\nconst APPENDIX_NOT_OWN = '';\nconst APPEARANCE_DELAY = 10;\nconst NO_MEDIA_CORNERS_THRESHOLD = 18;\nconst ANDROID_KEYBOARD_HIDE_DELAY_MS = 150;\n\nconst Message: FC = ({\n message,\n observeIntersectionForBottom,\n observeIntersectionForMedia,\n observeIntersectionForAnimatedStickers,\n album,\n noAvatars,\n withAvatar,\n withSenderName,\n noComments,\n appearanceOrder,\n isFirstInGroup,\n isLastInGroup,\n isFirstInDocumentGroup,\n isLastInDocumentGroup,\n isLastInList,\n theme,\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 disableContextMenuHint,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const ref = useRef(null);\n // eslint-disable-next-line no-null/no-null\n const bottomMarkerRef = useRef(null);\n // eslint-disable-next-line no-null/no-null\n const appendixRef = useRef(null);\n\n useOnIntersect(bottomMarkerRef, observeIntersectionForBottom);\n\n const {\n isContextMenuOpen, contextMenuPosition,\n handleBeforeContextMenu, handleContextMenu,\n handleContextMenuClose, handleContextMenuHide,\n } = useContextMenuHandlers(ref, false, true);\n\n useEffect(() => {\n if (isContextMenuOpen) {\n disableContextMenuHint();\n }\n }, [isContextMenuOpen, disableContextMenuHint]);\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 isLocal = isMessageLocal(message);\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 signature = (\n (isChannel && message.adminTitle) || (forwardInfo && !asForwarded && forwardInfo.adminTitle) || undefined\n );\n const metaSafeAuthorWidth = useMemo(() => {\n return signature ? calculateAuthorWidth(signature) : undefined;\n }, [signature]);\n const canShowActionButton = (\n !(isContextMenuShown || isInSelectMode || isForwarding)\n && (!isInDocumentGroup || isLastInDocumentGroup)\n );\n const canForward = canShowActionButton && isChannel && !isScheduled;\n const canFocus = Boolean(canShowActionButton && (\n (forwardInfo && (forwardInfo.isChannelPost || (isChatWithSelf && !isOwn)) && forwardInfo.fromMessageId)\n || isPinnedList\n ));\n const avatarPeer = forwardInfo && (isChatWithSelf || !sender) ? originSender : sender;\n const senderPeer = forwardInfo ? originSender : sender;\n\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 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: React.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?: React.MouseEvent) => {\n if (isLocal) {\n return;\n }\n\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 }, [isLocal, isAlbum, album, messageId, toggleMessageSelection]);\n\n const handleContainerDoubleClick = useCallback(() => {\n setReplyingToId({ messageId });\n }, [setReplyingToId, messageId]);\n\n const handleContentDoubleClick = useCallback((e: React.MouseEvent) => {\n e.stopPropagation();\n }, []);\n\n const handleMouseDown = (e: React.MouseEvent) => {\n preventMessageInputBlur(e);\n\n if (!isLocal) {\n handleBeforeContextMenu(e);\n }\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 handleClick = useCallback((e: React.MouseEvent) => {\n const target = e.target as HTMLDivElement;\n if (!target.classList.contains('text-content') && !target.classList.contains('Message')) {\n return;\n }\n\n if (IS_ANDROID) {\n setTimeout(() => {\n handleContextMenu(e);\n }, ANDROID_KEYBOARD_HIDE_DELAY_MS);\n } else {\n handleContextMenu(e);\n }\n }, [handleContextMenu]);\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), Boolean(noAvatars), album!) : undefined;\n }, [isAlbum, isOwn, asForwarded, noAvatars, 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, noAvatars).width;\n } else if (video) {\n if (video.isRound) {\n width = ROUND_VIDEO_DIMENSIONS;\n } else {\n width = calculateMediaDimensions(message, noAvatars).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 \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
\n {renderSenderName()}\n {hasReply && (\n \n )}\n {sticker && (\n \n )}\n {animatedEmoji && (\n \n )}\n {isAlbum && (\n \n )}\n {!isAlbum && photo && (\n \n )}\n {!isAlbum && video && video.isRound && (\n \n )}\n {!isAlbum && video && !video.isRound && (\n \n )}\n {(audio || voice) && (\n \n )}\n {document && (\n \n )}\n {contact && (\n \n )}\n {poll && (\n \n )}\n {!animatedEmoji && textParts && (\n

\n {textParts}\n {shouldInlineMeta && (\n \n )}\n

\n )}\n {webPage && (\n \n )}\n {invoice && (\n \n )}\n
\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
\n {senderTitle ? (\n \n {renderText(senderTitle)}\n \n ) : !botSender ? (\n NBSP\n ) : undefined}\n {botSender && (\n <>\n {lang('ViaBot')}\n \n {renderText(`@${botSender.username}`)}\n \n \n )}\n {forwardInfo && forwardInfo.isLinkedChannelPost ? (\n {lang('DiscussChannel')}\n ) : message.adminTitle && !isChannel ? (\n {message.adminTitle}\n ) : undefined}\n
\n );\n }\n\n return (\n \n \n {!isLocal && !isInDocumentGroup && (\n
\n {isSelected && }\n
\n )}\n {!isLocal && isLastInDocumentGroup && (\n \n {isGroupSelected && (\n \n )}\n \n )}\n {withAvatar && renderAvatar()}\n \n \n {asForwarded && !customShape && (!isInDocumentGroup || isFirstInDocumentGroup) && (\n
{lang('ForwardedMessage')}
\n )}\n {renderContent()}\n {(!isInDocumentGroup || isLastInDocumentGroup) && !(!webPage && !animatedEmoji && textParts) && (\n \n )}\n {canForward ? (\n \n \n \n ) : canFocus ? (\n \n \n \n ) : undefined}\n {withCommentButton && }\n {withAppendix &&
}\n
\n {message.inlineButtons && (\n \n )}\n \n {contextMenuPosition && (\n \n )}\n \n );\n};\n\nfunction handleDocumentGroupMouseEnter(e: React.MouseEvent) {\n const lastGroupElement = getLastElementInDocumentGroup(e.currentTarget);\n if (lastGroupElement) {\n lastGroupElement.setAttribute(GROUP_MESSAGE_HOVER_ATTRIBUTE, '');\n }\n}\n\nfunction handleDocumentGroupMouseLeave(e: React.MouseEvent) {\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(\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 theme: selectTheme(global),\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 'disableContextMenuHint',\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_SINGLE_COLUMN_LAYOUT } 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,\n 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 { preventMessageInputBlur } from './helpers/preventMessageInputBlur';\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';\nimport useBackgroundMode from '../../hooks/useBackgroundMode';\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;\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;\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_SINGLE_COLUMN_LAYOUT ? 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 = ({\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 openHistoryCalendar,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const containerRef = useRef(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((type === 'thread' && selectScrollOffset(getGlobal(), chatId, threadId)) || 0);\n const anchorIdRef = useRef();\n const anchorTopRef = useRef();\n const listItemElementsRef = useRef();\n const memoUnreadDividerBeforeIdRef = useRef();\n // Updated every time (to be used from intersection callback closure)\n const memoFirstUnreadIdRef = useRef();\n const memoFocusingIdRef = useRef();\n const isScrollTopJustUpdatedRef = useRef(false);\n const shouldAnimateAppearanceRef = useRef(Boolean(lastMessage));\n\n const [containerHeight, setContainerHeight] = useState();\n const [hasFocusing, setHasFocusing] = useState(Boolean(focusingId));\n\n const areMessagesLoaded = Boolean(messageIds);\n\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,\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 useBackgroundMode(freezeForReading, unfreezeForReading);\n\n useOnChange(() => {\n memoFocusingIdRef.current = focusingId;\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]).filter(Boolean);\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('.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(`.${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 = Math.min(\n unreadDivider.offsetTop - (hasTools ? UNREAD_DIVIDER_TOP_WITH_TOOLS : UNREAD_DIVIDER_TOP),\n scrollHeight - scrollOffset,\n );\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 const noAvatars = Boolean(!withUsers || isChannelChat);\n\n const className = buildClassName(\n 'MessageList custom-scroll',\n noAvatars && '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 \n {isRestricted ? (\n
\n \n {restrictionReason ? restrictionReason.text : `This is a private ${isChannelChat ? 'channel' : 'chat'}`}\n \n
\n ) : botDescription ? (\n
{renderText(lang(botDescription), ['br', 'emoji', 'links'])}
\n ) : messageIds && !messageGroups ? (\n
{lang('NoMessages')}
\n ) : ((messageIds && messageGroups) || lastMessage) ? (\n \n {renderMessages(\n lang,\n messageGroups || groupMessages([lastMessage!]),\n observeIntersectionForReading,\n observeIntersectionForMedia,\n observeIntersectionForAnimatedStickers,\n withUsers,\n noAvatars,\n anchorIdRef,\n memoUnreadDividerBeforeIdRef,\n threadId,\n type,\n threadTopMessageId,\n threadFirstMessageId,\n hasLinkedChat,\n messageGroups ? type === 'scheduled' : false,\n !messageGroups || !shouldAnimateAppearanceRef.current,\n openHistoryCalendar,\n )}\n \n ) : (\n \n )}\n \n );\n};\n\nfunction renderMessages(\n lang: LangFn,\n messageGroups: MessageDateGroup[],\n observeIntersectionForReading: ObserveFn,\n observeIntersectionForMedia: ObserveFn,\n observeIntersectionForAnimatedStickers: ObserveFn,\n withUsers: boolean,\n noAvatars: boolean,\n currentAnchorIdRef: { current: string | undefined },\n memoFirstUnreadIdRef: { current: number | undefined },\n threadId: number,\n type: MessageListType,\n threadTopMessageId: number | undefined,\n threadFirstMessageId: number | undefined,\n hasLinkedChat: boolean | undefined,\n isSchedule: boolean,\n noAppearanceAnimation: boolean,\n openHistoryCalendar: Function,\n) {\n const unreadDivider = (\n
\n {lang('UnreadMessages')}\n
\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 ,\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 ,\n message.id === threadTopMessageId && (\n
\n {lang('DiscussionStarted')}\n
\n ),\n ]);\n }));\n });\n\n return (\n \n openHistoryCalendar({ selectedAt: dateGroup.datetime }) : undefined}\n >\n \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 \n \n {flatten(senderGroups)}\n \n );\n });\n\n return flatten(dateGroups);\n}\n\nexport default memo(withGlobal(\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 'openHistoryCalendar',\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;\n\nconst FOCUS_MARGIN = 20;\n\nconst ScrollDownButton: FC = ({\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(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('.MessageList')!;\n const messageElements = messagesContainer.querySelectorAll('.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
\n
\n \n \n \n {Boolean(unreadCount) && (\n
{formatIntegerCompact(unreadCount!)}
\n )}\n
\n
\n );\n};\n\nexport default memo(withGlobal(\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,\n): Promise {\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 {\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","import { IS_IOS } from '../../../../util/environment';\n\nlet resetInput: HTMLInputElement;\n\nif (IS_IOS) {\n resetInput = document.createElement('input');\n resetInput.classList.add('for-ios-autocapitalization-fix');\n document.body.appendChild(resetInput);\n}\n\n// https://stackoverflow.com/a/55652503\nexport default function applyIosAutoCapitalizationFix(inputEl: HTMLElement) {\n resetInput.focus();\n inputEl.focus();\n}\n","export default __webpack_public_path__ + \"c0155344d336103c2b6a0b28cc510750.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 {\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((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,\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 && ![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';\nimport useBackgroundMode from '../../../../hooks/useBackgroundMode';\nimport useBeforeUnload from '../../../../hooks/useBeforeUnload';\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 const handleBlur = useCallback(() => {\n if (chatId && threadId) {\n updateDraft(chatId, threadId);\n }\n }, [chatId, threadId, updateDraft]);\n\n useBackgroundMode(handleBlur);\n useBeforeUnload(handleBlur);\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 = (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 ? : 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;\n\nconst BUTTON_ACTIVATE_DELAY = 200;\nlet openTimeout: number | undefined;\nlet isFirstTimeActivation = true;\n\nconst ResponsiveHoverButton: FC = ({ 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 \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 = (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 ? : 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 = (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 ? : 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 = (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 ? : 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 = (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 ? : 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 = (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 ? : 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 = (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 ? : 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;\n\nconst FORWARD_RENDERING_DELAY = 300;\n\nconst ComposerEmbeddedMessage: FC = ({\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
\n
\n \n \n
\n
\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 = (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 ? : 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 = (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 ? : 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 = (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 ? : 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;\n\nconst RE_LINK = new RegExp(RE_LINK_TEMPLATE, 'i');\n\nconst WebPagePreview: FC = ({\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
\n
\n \n \n
\n
\n );\n};\n\nexport default memo(withGlobal(\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 = (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 ? : 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 = (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 ? : 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 = (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 ? : 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';\nimport { LangCode } from '../../../types';\n\nimport { EDITABLE_INPUT_ID, SCHEDULED_WHEN_ONLINE } from '../../../config';\nimport { IS_VOICE_RECORDING_SUPPORTED, IS_SINGLE_COLUMN_LAYOUT, IS_IOS } 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 selectEmojiKeywords,\n} from '../../../modules/selectors';\nimport {\n getAllowedAttachmentOptions,\n getChatSlowModeOptions,\n isChatGroup,\n isChatPrivate,\n isChatAdmin,\n} from '../../../modules/helpers';\nimport { formatMediaDuration, 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';\nimport applyIosAutoCapitalizationFix from './helpers/applyIosAutoCapitalizationFix';\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;\n recentEmojis: string[];\n lastSyncTime?: number;\n contentToBeScheduled?: GlobalState['messages']['contentToBeScheduled'];\n shouldSuggestStickers?: boolean;\n language: LangCode;\n baseEmojiKeywords?: Record;\n emojiKeywords?: Record;\n serverTimeOffset: number;\n} & Pick;\n\ntype DispatchProps = Pick;\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 = '';\n\nconst Composer: FC = ({\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 language,\n baseEmojiKeywords,\n emojiKeywords,\n serverTimeOffset,\n recentEmojis,\n sendMessage,\n editMessage,\n saveDraft,\n clearDraft,\n showDialog,\n setStickerSearchQuery,\n setGifSearchQuery,\n forwardMessages,\n openPollModal,\n closePollModal,\n loadScheduledHistory,\n closePaymentModal,\n openChat,\n clearReceipt,\n addRecentEmoji,\n loadEmojiKeywords,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const appendixRef = useRef(null);\n const [html, setHtml] = useState('');\n const lastMessageSendTimeSeconds = useRef();\n const prevDropAreaState = usePrevious(dropAreaState);\n const [isCalendarOpen, openCalendar, closeCalendar] = useFlag();\n const [\n scheduledMessageArgs, setScheduledMessageArgs,\n ] = useState();\n const lang = useLang();\n\n // Cache for frequently updated state\n const htmlRef = useRef(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([]);\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 baseEmojiKeywords,\n emojiKeywords,\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\n if (selection.rangeCount) {\n const selectionRange = selection.getRangeAt(0);\n if (isSelectionInsideInput(selectionRange, inputId)) {\n insertHtmlInSelection(newHtml);\n messageInput.dispatchEvent(new Event('input', { bubbles: true }));\n return;\n }\n }\n\n setHtml(`${htmlRef.current!}${newHtml}`);\n\n if (!IS_SINGLE_COLUMN_LAYOUT) {\n // If selection is outside of input, set cursor at the end of input\n requestAnimationFrame(() => {\n focusEditableElement(messageInput);\n });\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, EDITABLE_INPUT_ID)) {\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_SINGLE_COLUMN_LAYOUT) {\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 showDialog({\n data: {\n message: 'CAPTION_TOO_LONG_PLEASE_REMOVE_CHARACTERS',\n textParams: {\n '{EXTRA_CHARS_COUNT}': extraLength,\n '{PLURAL_S}': extraLength > 1 ? 's' : '',\n },\n hasErrorKey: true,\n },\n });\n return;\n }\n\n const messageInput = document.getElementById(EDITABLE_INPUT_ID)!;\n\n if (currentAttachments.length || text) {\n if (slowMode && !isAdmin) {\n const nowSeconds = Math.floor(Date.now() / 1000) + serverTimeOffset;\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 showDialog({\n data: {\n message: lang('SlowModeHint', formatMediaDuration(secondsRemaining)),\n isSlowMode: true,\n hasErrorKey: false,\n },\n });\n\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) + serverTimeOffset;\n\n clearDraft({ chatId, localOnly: true });\n\n if (IS_IOS && messageInput === document.activeElement) {\n applyIosAutoCapitalizationFix(messageInput);\n }\n\n // Wait until message animation starts\n requestAnimationFrame(resetComposer);\n }, [\n connectionState, attachments, activeVoiceRecording, isForwarding, serverTimeOffset, clearDraft, chatId,\n resetComposer, stopRecordingVoice, showDialog, slowMode, isAdmin, sendMessage, forwardMessages, lang,\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, isWhenOnline = false) => {\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 + (isWhenOnline ? 0 : serverTimeOffset);\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, serverTimeOffset]);\n\n const handleMessageScheduleUntilOnline = useCallback(() => {\n handleMessageSchedule(new Date(SCHEDULED_WHEN_ONLINE * 1000), true);\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_SINGLE_COLUMN_LAYOUT || 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_SINGLE_COLUMN_LAYOUT) {\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 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 const onSend = mainButtonState === MainButtonState.Edit\n ? handleEditComplete\n : (shouldSchedule ? openCalendar : handleSend);\n\n return (\n
\n {allowedAttachmentOptions.canAttachMedia && (\n \n \n \n )}\n \n \n \n \n {renderedEditedMessage && (\n \n )}\n \n
\n
\n \n \n
\n {IS_SINGLE_COLUMN_LAYOUT ? (\n \n \n \n \n \n ) : (\n \n \n \n )}\n \n {withScheduledButton && (\n \n \n \n )}\n {botKeyboardMessageId && !activeVoiceRecording && !editingMessage && (\n \n \n \n )}\n {!activeVoiceRecording && !editingMessage && (\n \n \n \n )}\n {activeVoiceRecording && currentRecordTime && (\n \n {formatVoiceRecordDuration(currentRecordTime - startRecordTimeRef.current!)}\n \n )}\n \n \n \n {botKeyboardMessageId && (\n \n )}\n \n
\n
\n {activeVoiceRecording && (\n \n \n \n )}\n \n \n \n \n \n {canShowCustomSendMenu && (\n \n )}\n \n
\n );\n};\n\nexport default memo(withGlobal(\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 const { language } = global.settings.byKey;\n const baseEmojiKeywords = selectEmojiKeywords(global, 'en');\n const emojiKeywords = language !== 'en' ? selectEmojiKeywords(global, language) : undefined;\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 language,\n baseEmojiKeywords: baseEmojiKeywords ? baseEmojiKeywords.keywords : undefined,\n emojiKeywords: emojiKeywords ? emojiKeywords.keywords : undefined,\n serverTimeOffset: global.serverTimeOffset,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'sendMessage',\n 'editMessage',\n 'saveDraft',\n 'clearDraft',\n 'showDialog',\n 'setStickerSearchQuery',\n 'setGifSearchQuery',\n 'forwardMessages',\n 'openPollModal',\n 'closePollModal',\n 'closePaymentModal',\n 'clearReceipt',\n 'loadScheduledHistory',\n 'openChat',\n 'addRecentEmoji',\n 'loadEmojiKeywords',\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; pause: NoneToVoidFunction } | undefined;\n\nexport default () => {\n // eslint-disable-next-line no-null/no-null\n const recordButtonRef = useRef(null);\n const [activeVoiceRecording, setActiveVoiceRecording] = useState();\n const startRecordTimeRef = useRef();\n const [currentRecordTime, setCurrentRecordTime] = useState();\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(/^]*?>$/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 ).\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 = (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 ? : 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 = (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 ? : 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 = (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 ? : 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 {\n IS_SINGLE_COLUMN_LAYOUT,\n IS_TABLET_COLUMN_LAYOUT,\n IS_TOUCH_ENV,\n MASK_IMAGE_DISABLED,\n} from '../../util/environment';\nimport { DropAreaState } from './composer/DropArea';\nimport {\n selectChat,\n selectCurrentMessageList,\n selectCurrentTextSearch,\n selectIsChatBotNotStarted,\n selectIsInSelectMode,\n selectIsRightColumnShown,\n selectPinnedIds,\n selectTheme,\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 isLeftColumnShown?: boolean;\n isRightColumnShown?: boolean;\n isBackgroundBlurred?: boolean;\n isMobileSearchActive?: boolean;\n isSelectModeActive?: boolean;\n animationLevel?: number;\n};\n\ntype DispatchProps = Pick;\n\nconst CLOSE_ANIMATION_DURATION = IS_SINGLE_COLUMN_LAYOUT ? 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 = ({\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 isLeftColumnShown,\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();\n const [isNotchShown, setIsNotchShown] = useState();\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) => {\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 handleTabletFocus = useCallback(() => {\n openChat({ id: chatId });\n }, [openChat, 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 \n \n
\n {renderingChatId && renderingThreadId && (\n <>\n
\n \n \n {() => (\n <>\n \n
\n {renderingCanPost && (\n \n )}\n {isPinnedMessageList && (\n
\n \n \n {lang('Chat.Pinned.UnpinAll', pinnedMessagesCount, 'i')}\n \n
\n )}\n {!isPinnedMessageList && !renderingCanPost && messageSendingRestrictionReason && (\n
\n
\n \n {messageSendingRestrictionReason}\n \n
\n
\n )}\n \n
\n \n )}\n \n\n \n
\n {IS_SINGLE_COLUMN_LAYOUT && }\n \n )}\n {chatId && (\n \n )}\n
\n );\n};\n\nexport default memo(withGlobal(\n (global): StateProps => {\n const theme = selectTheme(global);\n const {\n isBlurred: isBackgroundBlurred, background: customBackground, backgroundColor, patternColor,\n } = global.settings.themes[theme] || {};\n\n const currentMessageList = selectCurrentMessageList(global);\n const { isLeftColumnShown, chats: { listIds } } = global;\n\n const state: StateProps = {\n theme,\n customBackground,\n backgroundColor,\n patternColor,\n isLeftColumnShown,\n isRightColumnShown: selectIsRightColumnShown(global),\n isBackgroundBlurred,\n isMobileSearchActive: Boolean(IS_SINGLE_COLUMN_LAYOUT && 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_SINGLE_COLUMN_LAYOUT),\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_SINGLE_COLUMN_LAYOUT } 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 useLang from '../../hooks/useLang';\n\nimport SearchInput from '../ui/SearchInput';\nimport Button from '../ui/Button';\nimport Transition from '../ui/Transition';\nimport './RightHeader.scss';\nimport { getDayStartAt } from '../../util/dateFormat';\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 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;\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 = ({\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 openHistoryCalendar,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const backButtonRef = useRef(null);\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 handleStickerSearchQueryChange = useCallback((query: string) => {\n setStickerSearchQuery({ query });\n }, [setStickerSearchQuery]);\n\n const handleGifSearchQueryChange = useCallback((query: string) => {\n setGifSearchQuery({ query });\n }, [setGifSearchQuery]);\n\n const [shouldSkipTransition, setShouldSkipTransition] = useState(!isColumnOpen);\n\n useEffect(() => {\n setTimeout(() => {\n setShouldSkipTransition(!isColumnOpen);\n }, COLUMN_CLOSE_DELAY_MS);\n }, [isColumnOpen]);\n\n const lang = useLang();\n const contentKey = isProfile ? (\n profileState === ProfileState.Profile ? (\n HeaderContent.Profile\n ) : profileState === ProfileState.SharedMedia ? (\n HeaderContent.SharedMedia\n ) : profileState === ProfileState.MemberList ? (\n HeaderContent.MemberList\n ) : -1 // Never reached\n ) : isSearch ? (\n HeaderContent.Search\n ) : isPollResults ? (\n HeaderContent.PollResults\n ) : isStickerSearch ? (\n HeaderContent.StickerSearch\n ) : isGifSearch ? (\n HeaderContent.GifSearch\n ) : isManagement ? (\n managementScreen === ManagementScreens.Initial ? (\n HeaderContent.ManageInitial\n ) : managementScreen === ManagementScreens.ChatPrivacyType ? (\n HeaderContent.ManageChatPrivacyType\n ) : managementScreen === ManagementScreens.Discussion ? (\n HeaderContent.ManageDiscussion\n ) : managementScreen === ManagementScreens.ChannelSubscribers ? (\n HeaderContent.ManageChannelSubscribers\n ) : managementScreen === ManagementScreens.GroupPermissions ? (\n HeaderContent.ManageGroupPermissions\n ) : managementScreen === ManagementScreens.ChatAdministrators ? (\n HeaderContent.ManageChatAdministrators\n ) : managementScreen === ManagementScreens.GroupRemovedUsers ? (\n HeaderContent.ManageGroupRemovedUsers\n ) : managementScreen === ManagementScreens.GroupUserPermissionsCreate ? (\n HeaderContent.ManageGroupUserPermissionsCreate\n ) : managementScreen === ManagementScreens.GroupUserPermissions ? (\n HeaderContent.ManageGroupUserPermissions\n ) : managementScreen === ManagementScreens.GroupRecentActions ? (\n HeaderContent.ManageGroupRecentActions\n ) : managementScreen === ManagementScreens.ChatAdminRights ? (\n HeaderContent.ManageGroupAdminRights\n ) : managementScreen === ManagementScreens.GroupMembers ? (\n HeaderContent.ManageGroupMembers\n ) : undefined // Never reached\n ) : 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

{lang('PollResults')}

;\n case HeaderContent.Search:\n return (\n <>\n \n openHistoryCalendar({ selectedAt: getDayStartAt(Date.now()) })}\n ariaLabel=\"Search messages by date\"\n >\n \n \n \n );\n case HeaderContent.ManageInitial:\n return

{lang('Edit')}

;\n case HeaderContent.ManageChatPrivacyType:\n return

{lang(isChannel ? 'ChannelTypeHeader' : 'GroupTypeHeader')}

;\n case HeaderContent.ManageDiscussion:\n return

{lang('Discussion')}

;\n case HeaderContent.ManageChatAdministrators:\n return

{lang('ChannelAdministrators')}

;\n case HeaderContent.ManageGroupRecentActions:\n return

{lang('Group.Info.AdminLog')}

;\n case HeaderContent.ManageGroupAdminRights:\n return

{lang('EditAdminRights')}

;\n case HeaderContent.ManageGroupPermissions:\n return

{lang('ChannelPermissions')}

;\n case HeaderContent.ManageGroupRemovedUsers:\n return

{lang('ChannelBlockedUsers')}

;\n case HeaderContent.ManageGroupUserPermissionsCreate:\n return

{lang('ChannelAddException')}

;\n case HeaderContent.ManageGroupUserPermissions:\n return

{lang('UserRestrictions')}

;\n case HeaderContent.StickerSearch:\n return (\n \n );\n case HeaderContent.GifSearch:\n return (\n \n );\n case HeaderContent.SharedMedia:\n return

{lang('SharedMedia')}

;\n case HeaderContent.ManageChannelSubscribers:\n return

{lang('ChannelSubscribers')}

;\n case HeaderContent.MemberList:\n case HeaderContent.ManageGroupMembers:\n return

{lang('GroupMembers')}

;\n default:\n return (\n <>\n

Profile

\n
\n {canManage && (\n \n \n \n )}\n
\n \n );\n }\n }\n\n const isBackButton = (\n IS_SINGLE_COLUMN_LAYOUT\n || contentKey === HeaderContent.SharedMedia\n || contentKey === HeaderContent.MemberList\n || isManagement\n );\n\n const buttonClassName = buildClassName(\n 'animated-close-icon',\n shouldSkipTransition && 'no-transition',\n );\n\n // Add class in the next AF to synchronize with animation with Transition components\n useEffect(() => {\n backButtonRef.current!.classList.toggle('state-back', isBackButton);\n }, [isBackButton]);\n\n return (\n
\n \n
\n \n \n {renderHeaderContent}\n \n
\n );\n};\n\nexport default memo(withGlobal(\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 'openHistoryCalendar',\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,\n chatMessages?: Record,\n foundIds?: number[],\n chatId?: number,\n lastSyncTime?: number,\n serverTimeOffset = 0,\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, undefined, serverTimeOffset);\n }, [groupChatMembers, serverTimeOffset, 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,\n foundIds?: number[],\n) {\n const messageIdsRef = useRef();\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('.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('.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('.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 = ({\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 = ;\n } else if (isDeleted) {\n content = ;\n } else if (imageSrc) {\n content = \"\";\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
\n \n
\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
\n {prevImageSrc && imageSrc && prevImageSrc !== imageSrc && (\n \"\"\n )}\n {typeof content === 'string' ? renderText(content, ['hq_emoji']) : content}\n
\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 serverTimeOffset: number;\n} & Pick;\n\ntype DispatchProps = Pick;\n\nconst PrivateChatInfo: FC = ({\n user,\n chat,\n isSavedMessages,\n lastSyncTime,\n animationLevel,\n loadFullUser,\n openMediaViewer,\n serverTimeOffset,\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(\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
\n {photos.map((_, i) => (\n \n ))}\n
\n );\n }\n\n function renderPhoto() {\n const photo = !isSavedMessages && photos && photos.length > 0 ? photos[currentPhotoIndex] : undefined;\n\n return (\n \n );\n }\n\n function renderStatus() {\n if (user) {\n return (\n
\n {getUserStatus(lang, user, serverTimeOffset)}\n
\n );\n }\n\n return (\n {\n isChatChannel(chat!)\n ? lang('Subscribers', chat!.membersCount, 'i')\n : lang('Members', chat!.membersCount, 'i')\n }\n \n );\n }\n\n const isVerifiedIconShown = (user && user.isVerified) || (chat && chat.isVerified);\n\n return (\n
\n
\n {renderPhotoTabs()}\n \n {renderPhoto}\n \n\n {!isFirst && (\n \n )}\n {!isLast && (\n \n )}\n
\n\n
\n {isSavedMessages ? (\n
\n

{lang('SavedMessages')}

\n
\n ) : (\n
\n

{fullName && renderText(fullName)}

\n {isVerifiedIconShown && }\n
\n )}\n {!isSavedMessages && renderStatus()}\n
\n
\n );\n};\n\nexport default memo(withGlobal(\n (global, { userId, forceShowSelf }): StateProps => {\n const { lastSyncTime, serverTimeOffset } = 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, serverTimeOffset,\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 {\n selectChat, selectNotifyExceptions, selectNotifySettings, selectUser,\n} from '../../modules/selectors';\nimport {\n getChatDescription, getChatLink, getHasAdminRight, isChatChannel, isChatPrivate, isUserRightBanned, selectIsChatMuted,\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 isMuted?: boolean;\n} & Pick;\n\ntype DispatchProps = Pick;\n\nconst ChatExtra: FC = ({\n lastSyncTime,\n user,\n chat,\n forceShowSelf,\n canInviteUsers,\n isMuted,\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 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: !isMuted });\n }, [chatId, isMuted, 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
\n {formattedNumber && !!formattedNumber.length && (\n copy(formattedNumber, lang('Phone'))}>\n {formattedNumber}\n {lang('Phone')}\n \n )}\n {printedUsername && (\n copy(`@${printedUsername}`, lang('Username'))}\n >\n {renderText(printedUsername)}\n {lang('Username')}\n \n )}\n {description && !!description.length && (\n \n \n {renderText(description, ['br', 'links', 'emoji'])}\n \n {lang(userId ? 'UserBio' : 'Info')}\n \n )}\n {canInviteUsers && !printedUsername && !!link.length && (\n copy(link, lang('SetUrlPlaceholder'))}>\n
\n \n
\n {lang('SetUrlPlaceholder')}\n
\n )}\n \n {lang('Notifications')}\n \n \n
\n );\n};\n\nexport default memo(withGlobal(\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 const isMuted = chat && selectIsChatMuted(chat, selectNotifySettings(global), selectNotifyExceptions(global));\n\n const canInviteUsers = chat && (\n (!isChatChannel(chat) && !isUserRightBanned(chat, 'inviteUsers'))\n || getHasAdminRight(chat, 'inviteUsers')\n );\n\n return {\n lastSyncTime, chat, user, canInviteUsers, isMuted,\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 ISettings,\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 selectTheme,\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 theme: ISettings['theme'];\n isChannel?: boolean;\n resolvedUserId?: number;\n chatMessages?: Record;\n foundIds?: number[];\n mediaSearchType?: SharedMediaType;\n hasMembersTab?: boolean;\n areMembersHidden?: boolean;\n members?: ApiChatMember[];\n usersById?: Record;\n isRightColumnShown: boolean;\n isRestricted?: boolean;\n lastSyncTime?: number;\n serverTimeOffset: number;\n};\n\ntype DispatchProps = Pick;\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 = ({\n chatId,\n profileState,\n onProfileStateChange,\n theme,\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 serverTimeOffset,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const containerRef = useRef(null);\n // eslint-disable-next-line no-null/no-null\n const transitionRef = useRef(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, serverTimeOffset,\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
\n {!noSpinner && }\n
\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
\n \n
\n );\n }\n\n return (\n \n {resultType === 'media' ? (\n viewportIds!.map((id) => chatMessages[id] && (\n \n ))\n ) : resultType === 'documents' ? (\n viewportIds!.map((id) => chatMessages[id] && (\n \n ))\n ) : resultType === 'links' ? (\n viewportIds!.map((id) => chatMessages[id] && (\n \n ))\n ) : resultType === 'audio' ? (\n viewportIds!.map((id) => chatMessages[id] && (\n \n ))\n ) : resultType === 'members' ? (\n viewportIds!.map((id, i) => (\n handleMemberClick(id)}\n >\n \n \n ))\n ) : undefined}\n
\n );\n }\n\n return (\n \n {!noProfileInfo && renderProfileInfo(chatId, resolvedUserId)}\n {!isRestricted && (\n
\n \n {renderSharedMedia}\n \n \n
\n )}\n \n );\n};\n\nfunction renderProfileInfo(chatId: number, resolvedUserId?: number) {\n return (\n
\n \n \n
\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(\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 theme: selectTheme(global),\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 serverTimeOffset: global.serverTimeOffset,\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(transitionElSelector);\n const tabsEl = container.querySelector('.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(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 = (props) => {\n const RightSearch = useModuleLoader(Bundles.Extra, 'RightSearch');\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return RightSearch ? : ;\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 = (props) => {\n const Management = useModuleLoader(Bundles.Extra, 'Management');\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return Management ? : ;\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 ? : ;\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 ? : ;\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 ? : ;\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';\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';\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;\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 = ({\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.Profile);\n const [managementScreen, setManagementScreen] = useState(ManagementScreens.Initial);\n const [selectedChatMemberId, setSelectedChatMemberId] = useState();\n const [isPromotedByCurrentUser, setIsPromotedByCurrentUser] = useState();\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(() => {\n switch (contentKey) {\n case RightColumnContent.ChatInfo:\n if (isScrolledDown) {\n setProfileState(ProfileState.Profile);\n break;\n }\n toggleChatInfo();\n break;\n case RightColumnContent.UserInfo:\n if (isScrolledDown) {\n setProfileState(ProfileState.Profile);\n break;\n }\n openUserInfo({ id: undefined });\n break;\n case RightColumnContent.Management: {\n switch (managementScreen) {\n case ManagementScreens.Initial:\n toggleManagement();\n break;\n case ManagementScreens.ChatPrivacyType:\n case ManagementScreens.Discussion:\n case ManagementScreens.GroupPermissions:\n case ManagementScreens.GroupType:\n case ManagementScreens.ChatAdministrators:\n case ManagementScreens.ChannelSubscribers:\n case ManagementScreens.GroupMembers:\n setManagementScreen(ManagementScreens.Initial);\n break;\n case ManagementScreens.GroupUserPermissionsCreate:\n case ManagementScreens.GroupRemovedUsers:\n case ManagementScreens.GroupUserPermissions:\n setManagementScreen(ManagementScreens.GroupPermissions);\n setSelectedChatMemberId(undefined);\n setIsPromotedByCurrentUser(undefined);\n break;\n case ManagementScreens.ChatAdminRights:\n case ManagementScreens.GroupRecentActions:\n setManagementScreen(ManagementScreens.ChatAdministrators);\n break;\n }\n\n break;\n }\n case RightColumnContent.Search: {\n blurSearchInput();\n closeLocalTextSearch();\n break;\n }\n case RightColumnContent.StickerSearch:\n case RightColumnContent.GifSearch: {\n blurSearchInput();\n setStickerSearchQuery({ query: undefined });\n setGifSearchQuery({ query: undefined });\n break;\n }\n case RightColumnContent.PollResults:\n closePollResults();\n break;\n }\n }, [\n contentKey, isScrolledDown, toggleChatInfo, openUserInfo, closePollResults,\n managementScreen, toggleManagement, closeLocalTextSearch, setStickerSearchQuery, setGifSearchQuery,\n ]);\n\n const handleSelectChatMember = useCallback((memberId, isPromoted) => {\n setSelectedChatMemberId(memberId);\n setIsPromotedByCurrentUser(isPromoted);\n }, []);\n\n useEffect(() => (isOpen ? captureEscKeyListener(close) : undefined), [isOpen, close]);\n\n useEffect(() => {\n setTimeout(() => {\n setShouldSkipTransition(!isOpen);\n }, COLUMN_CLOSE_DELAY_MS);\n }, [isOpen]);\n\n // Close Right Column when it transforms into overlayed state on screen resize\n useEffect(() => {\n if (isOpen && isOverlaying) {\n close();\n }\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [isOverlaying]);\n\n // We need to clear profile state and management screen state, when changing chats\n useLayoutEffectWithPrevDeps(([prevContentKey, prevChatId]) => {\n if (\n (prevContentKey === RightColumnContent.ChatInfo && contentKey === RightColumnContent.UserInfo)\n || (prevContentKey === RightColumnContent.UserInfo && contentKey === RightColumnContent.ChatInfo)\n || (prevChatId !== chatId)\n ) {\n setProfileState(ProfileState.Profile);\n setManagementScreen(ManagementScreens.Initial);\n }\n }, [contentKey, chatId]);\n\n // eslint-disable-next-line consistent-return\n function renderContent() {\n if (renderingContentKey === -1) {\n return undefined;\n }\n\n switch (renderingContentKey) {\n case RightColumnContent.ChatInfo:\n case RightColumnContent.UserInfo:\n return (\n \n );\n case RightColumnContent.Search:\n return ;\n case RightColumnContent.Management:\n return (\n \n );\n case RightColumnContent.StickerSearch:\n return ;\n case RightColumnContent.GifSearch:\n return ;\n case RightColumnContent.PollResults:\n return ;\n }\n }\n\n return (\n \n {isOverlaying && (\n
\n )}\n
\n \n \n {renderContent}\n \n
\n
\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 = ({ isOpen }) => {\n const MediaViewer = useModuleLoader(Bundles.Extra, 'MediaViewer', !isOpen);\n\n return 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 ? : 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 DialogsAsync: FC = ({ isOpen }) => {\n const Dialogs = useModuleLoader(Bundles.Extra, 'Dialogs', !isOpen);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return Dialogs ? : undefined;\n};\n\nexport default memo(DialogsAsync);\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 = (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 ? : 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 = (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 ? : undefined;\n};\n\nexport default memo(SafeLinkModalAsync);\n","import React, { FC, memo } from '../../lib/teact/teact';\nimport { Bundles } from '../../util/moduleLoader';\n\nimport { OwnProps } from './HistoryCalendar';\n\nimport useModuleLoader from '../../hooks/useModuleLoader';\n\nconst HistoryCalendarAsync: FC = (props) => {\n const { isOpen } = props;\n const HistoryCalendar = useModuleLoader(Bundles.Extra, 'HistoryCalendar', !isOpen);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return HistoryCalendar ? : undefined;\n};\n\nexport default memo(HistoryCalendarAsync);\n","import React, {\n FC, useEffect, memo, useCallback,\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,\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 useBeforeUnload from '../../hooks/useBeforeUnload';\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 Dialogs from './Dialogs.async';\nimport ForwardPicker from './ForwardPicker.async';\nimport SafeLinkModal from './SafeLinkModal.async';\nimport HistoryCalendar from './HistoryCalendar.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 hasDialogs: boolean;\n audioMessage?: ApiMessage;\n safeLinkModalUrl?: string;\n isHistoryCalendarOpen: boolean;\n};\n\ntype DispatchProps = Pick;\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 = ({\n lastSyncTime,\n isLeftColumnShown,\n isRightColumnShown,\n isMediaViewerOpen,\n isForwardModalOpen,\n animationLevel,\n hasNotifications,\n hasDialogs,\n audioMessage,\n safeLinkModalUrl,\n isHistoryCalendarOpen,\n loadAnimatedEmojis,\n loadNotificationSettings,\n loadNotificationExceptions,\n updateIsOnline,\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 updateIsOnline(true);\n loadAnimatedEmojis();\n loadNotificationSettings();\n loadNotificationExceptions();\n }\n }, [lastSyncTime, loadAnimatedEmojis, loadNotificationExceptions, loadNotificationSettings, updateIsOnline]);\n\n const {\n transitionClassNames: middleColumnTransitionClassNames,\n } = useShowTransition(!isLeftColumnShown, undefined, true);\n\n const {\n transitionClassNames: rightColumnTransitionClassNames,\n } = useShowTransition(isRightColumnShown, undefined, true);\n\n const className = buildClassName(\n middleColumnTransitionClassNames.replace(/([\\w-]+)/g, 'middle-column-$1'),\n rightColumnTransitionClassNames.replace(/([\\w-]+)/g, 'right-column-$1'),\n );\n\n useEffect(() => {\n // For animating Symbol Menu on mobile\n document.body.classList.toggle('is-middle-column-open', className.includes('middle-column-open'));\n }, [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 const handleBlur = useCallback(() => {\n updateIsOnline(false);\n\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 }, [updateIsOnline]);\n\n const handleFocus = useCallback(() => {\n updateIsOnline(true);\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 }, [updateIsOnline]);\n\n // Online status and browser tab indicators\n useBackgroundMode(handleBlur, handleFocus);\n useBeforeUnload(handleBlur);\n\n function stopEvent(e: React.MouseEvent) {\n e.preventDefault();\n e.stopPropagation();\n }\n\n return (\n
\n \n \n \n \n \n \n \n {audioMessage && }\n \n \n
\n );\n};\n\nfunction updateIcon(asUnread: boolean) {\n document.querySelectorAll('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 hasDialogs: Boolean(global.dialogs.length),\n audioMessage,\n safeLinkModalUrl: global.safeLinkModalUrl,\n isHistoryCalendarOpen: Boolean(global.historyCalendarSelectedAt),\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'loadAnimatedEmojis', 'loadNotificationSettings', 'loadNotificationExceptions', 'updateIsOnline',\n ]),\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":""}