mirror of
https://github.com/danog/telegram-tt.git
synced 2024-12-04 10:40:09 +01:00
1 line
687 KiB
Plaintext
1 line
687 KiB
Plaintext
{"version":3,"sources":["webpack:///webpack/bootstrap","webpack:///./src/lib/teact/teact.ts","webpack:///./src/lib/teact/teactn.tsx","webpack:///./src/config.ts","webpack:///./src/util/iteratees.ts","webpack:///./src/modules/helpers/messages.ts","webpack:///./src/modules/helpers/messageMedia.ts","webpack:///./src/modules/helpers/localSearch.ts","webpack:///./src/api/gramjs/worker/provider.ts","webpack:///./src/util/environmentWebp.ts","webpack:///./src/util/environmentSystemTheme.ts","webpack:///./src/util/environment.ts","webpack:///./src/modules/selectors/users.ts","webpack:///./src/modules/selectors/settings.ts","webpack:///./src/modules/selectors/chats.ts","webpack:///./src/modules/selectors/symbols.ts","webpack:///./src/modules/selectors/messages.ts","webpack:///./src/modules/selectors/localSearch.ts","webpack:///./src/modules/selectors/management.ts","webpack:///./src/modules/selectors/ui.ts","webpack:///./src/modules/selectors/globalSearch.ts","webpack:///./src/modules/selectors/payments.ts","webpack:///./src/api/types/index.ts","webpack:///./src/util/buildClassName.ts","webpack:///./src/util/schedulers.ts","webpack:///./src/modules/reducers/chats.ts","webpack:///./src/modules/reducers/messages.ts","webpack:///./src/modules/reducers/symbols.ts","webpack:///./src/modules/reducers/users.ts","webpack:///./src/modules/reducers/globalSearch.ts","webpack:///./src/modules/reducers/localSearch.ts","webpack:///./src/modules/reducers/management.ts","webpack:///./src/modules/reducers/settings.ts","webpack:///./src/modules/reducers/twoFaSettings.ts","webpack:///./src/modules/reducers/payments.ts","webpack:///./src/util/cacheApi.ts","webpack:///./src/types/index.ts","webpack:///./src/util/langProvider.ts","webpack:///./src/util/callbacks.ts","webpack:///./src/util/moduleLoader.ts","webpack:///./node_modules/idb-keyval/dist/esm/index.js","webpack:///./src/util/sessions.ts","webpack:///./src/util/files.ts","webpack:///./src/hooks/useLang.ts","webpack:///./src/lib/twemojiRegex.js","webpack:///./src/components/ui/Loading.tsx","webpack:///./src/util/notifications.ts","webpack:///./src/components/ui/Button.tsx","webpack:///./src/components/common/helpers/renderText.tsx","webpack:///./src/util/countries.ts","webpack:///./src/util/phoneNumber.ts","webpack:///./src/hooks/useFlag.ts","webpack:///./src/hooks/useModuleLoader.ts","webpack:///./src/components/ui/Spinner.tsx","webpack:///./src/util/handleError.ts","webpack:///./src/util/arePropsShallowEqual.ts","webpack:///./src/hooks/usePrevious.ts","webpack:///./src/util/dateFormat.ts","webpack:///./src/util/websync.ts","webpack:///./src/hooks/useForceUpdate.ts","webpack:///./src/util/oggToWav.ts","webpack:///./src/util/mediaLoader.ts","webpack:///./src/components/ui/Link.tsx","webpack:///./src/util/generateIdFor.ts","webpack:///./src/modules/helpers/users.ts","webpack:///./src/modules/helpers/chats.ts","webpack:///./src/hooks/useHeavyAnimationCheck.ts","webpack:///./src/lib/teact/dom-events.ts","webpack:///./src/hooks/useHistoryBack.ts","webpack:///./src/hooks/useShowTransition.ts","webpack:///./src/util/trimText.ts","webpack:///./src/components/ui/MenuItem.tsx","webpack:///./src/components/ui/RippleEffect.tsx","webpack:///./src/util/webpToPng.ts","webpack:///./src/util/switchTheme.ts","webpack:///./src/components/ui/InputText.tsx","webpack:///./src/components/ui/Checkbox.tsx","webpack:///./src/util/captureEscKeyListener.ts","webpack:///./src/util/textFormat.ts","webpack:///./src/util/memo.ts","webpack:///./src/hooks/useOnChange.ts","webpack:///./src/util/searchWords.ts","webpack:///./src/util/windowSize.ts","webpack:///./src/components/ui/Menu.tsx","webpack:///./src/util/captureKeyboardListeners.ts","webpack:///./src/hooks/useEffectWithPrevDeps.ts","webpack:///./src/lib/punycode.js","webpack:///./src/components/common/SafeLink.tsx","webpack:///./src/components/common/helpers/documentInfo.ts","webpack:///./src/modules/helpers/payments.ts","webpack:///./src/util/animation.ts","webpack:///./src/components/ui/DropdownMenu.tsx","webpack:///./src/hooks/useKeyboardListNavigation.ts","webpack:///./src/components/common/helpers/parseEmojiOnlyString.ts","webpack:///./src/util/emoji.ts","webpack:///./src/lib/teact/teact-dom.ts","webpack:///./src/components/common/UserLink.tsx","webpack:///./src/components/common/MessageLink.tsx","webpack:///./src/components/common/ChatLink.tsx","webpack:///./src/components/common/helpers/renderActionMessageText.tsx","webpack:///./src/api/types/messages.ts","webpack:///./src/api/types/media.ts","webpack:///./src/components/middle/message/MentionLink.tsx","webpack:///./src/util/appBadge.ts","webpack:///./src/hooks/useVirtualBackdrop.ts","webpack:///./src/api/gramjs/worker/worker.ts","webpack:///./node_modules/opus-recorder/dist/decoderWorker.min.js","webpack:///./node_modules/opus-recorder/dist/waveWorker.min.js","webpack:///./src/lib/webp/webp_wasm.worker.js","webpack:///./src/modules/actions/ui/initial.ts","webpack:///./src/modules/actions/ui/settings.ts","webpack:///./src/modules/actions/api/initial.ts","webpack:///./src/modules/actions/api/settings.ts","webpack:///./src/modules/actions/apiUpdaters/initial.ts","webpack:///./src/serviceWorker.ts","webpack:///./src/util/setupServiceWorker.ts","webpack:///./src/global/initial.ts","webpack:///./src/global/cache.ts","webpack:///./src/global/index.ts","webpack:///./src/util/activeTabMonitor.ts","webpack:///./src/util/fonts.ts","webpack:///./src/assets/telegram-logo.svg","webpack:///./src/assets/monkey.svg","webpack:///./src/components/common/UiLoader.tsx","webpack:///./src/hooks/useLangString.ts","webpack:///./src/components/auth/helpers/getSuggestedLanguage.ts","webpack:///./src/components/auth/CountryCodeInput.tsx","webpack:///./src/components/auth/AuthPhoneNumber.tsx","webpack:///./src/components/auth/AuthCode.async.tsx","webpack:///./src/components/auth/AuthPassword.async.tsx","webpack:///./src/components/auth/AuthRegister.async.tsx","webpack:///./node_modules/qr-creator/dist/qr-creator.es6.min.js","webpack:///./src/components/auth/AuthQrCode.tsx","webpack:///./src/components/auth/Auth.tsx","webpack:///./src/components/main/Main.async.tsx","webpack:///./src/assets/app-inactive.png","webpack:///./src/components/main/AppInactive.tsx","webpack:///./src/App.tsx","webpack:///./src/index.tsx"],"names":["webpackJsonpCallback","data","moduleId","chunkId","chunkIds","moreModules","i","resolves","length","Object","prototype","hasOwnProperty","call","installedChunks","push","modules","parentJsonpFunction","shift","installedModules","installedCssChunks","2","__webpack_require__","exports","module","l","e","promises","Promise","resolve","reject","href","fullhref","p","existingLinkTags","document","getElementsByTagName","dataHref","tag","getAttribute","rel","existingStyleTags","linkTag","createElement","type","onload","onerror","event","request","target","src","err","Error","code","parentNode","removeChild","appendChild","then","installedChunkData","promise","onScriptComplete","script","charset","timeout","nc","setAttribute","jsonpScriptSrc","error","clearTimeout","chunk","errorType","realSrc","message","name","undefined","setTimeout","head","all","m","c","d","getter","o","defineProperty","enumerable","get","r","Symbol","toStringTag","value","t","mode","__esModule","ns","create","key","bind","n","object","property","oe","console","jsonpArray","window","oldJsonpFunction","slice","s","VirtualElementTypesEnum","Fragment","renderingInstance","isEmptyElement","$element","Empty","isTextElement","Text","isTagElement","Tag","isComponentElement","Component","isRealElement","source","props","children","flatten","parsedChildren","componentInstance","isMounted","hooks","state","cursor","byCursor","effects","memos","buildComponentElement","createComponentInstance","dropEmptyTail","map","buildChildElement","buildTagElement","isEmptyPlaceholder","child","String","DEBUG_components","renderComponent","newRenderedValue","DEBUG_startAt","DEBUG","componentName","renderCount","renderTimes","DEBUG_MORE","log","performance","now","renderTime","warn","Math","round","handleError","renderedValue","newChild","hasElementChanged","$old","$new","unmountTree","forEach","hook","current","cleanup","effect","dependencies","nextValue","setter","forceUpdate","onUpdate","helpGc","unmountComponent","removeAllDelegatedListeners","mountComponent","forceUpdateComponent","currentElement","getTarget","setTarget","useState","initial","newValue","prepareForFrame","throttleWithPrimaryRaf","prepareComponentForFrame","throttleWithRaf","DEBUG_contentComponentName","useLayoutEffectBase","schedulerFn","debugKey","exec","some","dependency","causedBy","reduce","res","prevValue","join","useEffect","fastRaf","useLayoutEffect","onTickEnd","useMemo","resolver","getUnequalProps","useCallback","newCallback","useRef","memo","areEqual","arePropsShallowEqual","propsRef","renderedRef","addEventListener","orderBy","values","React","currentGlobal","reducers","callbacks","container","containers","mapStateToProps","mapReducersToProps","ownProps","mappedProps","newMappedProps","setGlobal","actions","Number","isNaN","DEBUG_componentName","keys","areMappedPropsChanged","DEBUG_updates","updateTime","Map","runCallbacks","cb","runCallbacksThrottled","newGlobal","noThrottle","getGlobal","getDispatch","addReducer","reducer","payload","onDispatch","addCallback","removeCallback","index","indexOf","splice","withGlobal","TeactNContainer","id","generateIdFor","useForceUpdate","delete","set","Array","from","PAGE_TITLE","INACTIVE_MARKER","APP_NAME","process","APP_VERSION","IS_TEST","DEBUG_ALERT_MSG","SESSION_USER_KEY","LEGACY_SESSION_KEY","GLOBAL_STATE_CACHE_DISABLED","GLOBAL_STATE_CACHE_KEY","GLOBAL_STATE_CACHE_CHAT_LIST_LIMIT","GLOBAL_STATE_CACHE_USER_LIST_LIMIT","MEDIA_CACHE_DISABLED","MEDIA_CACHE_NAME","MEDIA_CACHE_NAME_AVATARS","MEDIA_PROGRESSIVE_CACHE_NAME","CUSTOM_BG_CACHE_NAME","LANG_CACHE_NAME","TRANSPARENT_PIXEL","isBigScreen","innerHeight","MIN_PASSWORD_LENGTH","MESSAGE_LIST_SENSITIVE_AREA","MESSAGE_LIST_SLICE","MESSAGE_LIST_VIEWPORT_LIMIT","CHAT_HEIGHT_PX","CHAT_LIST_SLICE","CHAT_LIST_LOAD_SLICE","SHARED_MEDIA_SLICE","MESSAGE_SEARCH_SLICE","GLOBAL_SEARCH_SLICE","MEMBERS_SLICE","MEMBERS_LOAD_SLICE","PROFILE_SENSITIVE_AREA","TOP_CHAT_MESSAGES_PRELOAD_LIMIT","ALL_CHATS_PRELOAD_DISABLED","ANIMATION_LEVEL_MIN","ANIMATION_LEVEL_MAX","ANIMATION_LEVEL_DEFAULT","DEFAULT_MESSAGE_TEXT_SIZE_PX","IOS_DEFAULT_MESSAGE_TEXT_SIZE_PX","MACOS_DEFAULT_MESSAGE_TEXT_SIZE_PX","DRAFT_DEBOUNCE","EDITABLE_INPUT_ID","EDITABLE_INPUT_MODAL_ID","SAFE_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN","SAFE_SCREEN_WIDTH_FOR_CHAT_INFO","MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN","MIN_SCREEN_WIDTH_FOR_STATIC_LEFT_COLUMN","MOBILE_SCREEN_MAX_WIDTH","MOBILE_SCREEN_LANDSCAPE_MAX_WIDTH","MOBILE_SCREEN_LANDSCAPE_MAX_HEIGHT","LOCAL_MESSAGE_ID_BASE","ANIMATION_END_DELAY","FAST_SMOOTH_MAX_DISTANCE","FAST_SMOOTH_MIN_DURATION","FAST_SMOOTH_MAX_DURATION","FAST_SMOOTH_SHORT_TRANSITION_MAX_DISTANCE","STICKER_SIZE_INLINE_DESKTOP_FACTOR","Set","STICKER_SIZE_INLINE_MOBILE_FACTOR","STICKER_SIZE_AUTH","STICKER_SIZE_AUTH_MOBILE","STICKER_SIZE_PICKER","STICKER_SIZE_GENERAL_SETTINGS","STICKER_SIZE_PICKER_HEADER","STICKER_SIZE_SEARCH","STICKER_SIZE_MODAL","STICKER_SIZE_TWO_FA","STICKER_SIZE_DISCUSSION_GROUPS","STICKER_SIZE_FOLDER_SETTINGS","STICKER_SIZE_INLINE_BOT_RESULT","MEMOJI_STICKER_ID","BASE_EMOJI_KEYWORD_LANG","MENU_TRANSITION_DURATION","SLIDE_TRANSITION_DURATION","CONTENT_TYPES_FOR_QUICK_UPLOAD","RE_LINK_TEMPLATE","RE_MENTION_TEMPLATE","RE_TME_LINK","RE_TME_INVITE_LINK","SERVICE_NOTIFICATIONS_USER_ID","ALL_FOLDER_ID","ARCHIVED_FOLDER_ID","MAX_MEDIA_FILES_FOR_ALBUM","MAX_ACTIVE_PINNED_CHATS","SCHEDULED_WHEN_ONLINE","DEFAULT_LANG_CODE","DEFAULT_LANG_PACK","LANG_PACKS","TIPS_USERNAME","LOCALIZED_TIPS","FEEDBACK_URL","LIGHT_THEME_BG_COLOR","DARK_THEME_BG_COLOR","DARK_THEME_PATTERN_COLOR","DEFAULT_PATTERN_COLOR","buildCollectionByKey","collection","byKey","member","mapValues","callback","newByKey","pick","result","pickTruthy","omit","stringKeys","filter","has","orderKey","sort","a","b","isArray","mode1","mode2","orderKey1","orderKey2","aValue1","bValue1","aValue2","bValue2","aValue","bValue","array","concat","unique","compact","Boolean","areSortedArraysEqual","array1","array2","every","item","areSortedArraysIntersecting","findIntersectionWithSet","split","chunkSize","cloneDeep","acc","findLast","predicate","RE_LINK","RegExp","getMessageKey","chatId","parseMessageKey","match","messageId","getMessageOriginalId","previousLocalId","getMessageSummaryText","lang","noEmoji","text","photo","video","audio","voice","sticker","contact","poll","invoice","content","truncatedText","substr","groupedId","isGif","emoji","trim","getMessageAudioCaption","fileName","summary","question","getMessageText","webPage","getMessageCustomShape","isRound","parseEmojiOnlyString","getMessageSingleEmoji","getFirstLinkInMessage","entities","link","find","entity","ApiMessageEntityTypes","TextUrl","url","Url","offset","substring","domain","isOwnMessage","isOutgoing","isReplyMessage","replyToMessageId","isForwardedMessage","forwardInfo","isActionMessage","action","isServiceNotificationMessage","isMessageLocal","isAnonymousOwnMessage","senderId","getSenderTitle","sender","getUserFullName","getChatTitle","getSendingState","sendingState","isHistoryClearMessage","title","performer","getMessageContent","hasMessageMedia","getMessagePhoto","getMessageVideo","getMessageDocument","getMessageSticker","getMessageContact","getMessagePoll","getMessageAction","getMessageAudio","getMessageVoice","getMessageRoundVideo","isMessageDocumentPhoto","mediaType","isMessageDocumentVideo","getMessageInvoice","getMessageWebPage","getMessageWebPagePhoto","getMessageWebPageVideo","getMessageMediaThumbDataUri","thumbnail","media","getMessageMediaThumbnail","dataUri","getMessageMediaHash","webPagePhoto","webPageVideo","messageVideo","messagePhoto","base","hasMessageLocalBlobUrl","getVideoOrAudioBaseHash","getDocumentHasPreview","IS_PROGRESSIVE_SUPPORTED","IS_SAFARI","size","mimeType","getMessageMediaFormat","fullVideo","isAnimated","ApiMediaFormat","Lottie","Progressive","IS_OPUS_SUPPORTED","BlobUrl","getMessageFileName","date","getMessageFileSize","blobUrl","previewBlobUrl","getChatMediaMessageIds","messages","listedIds","isFromSharedMedia","ids","getMessageContentIds","reverse","getPhotoFullDimensions","sizes","getPhotoInlineDimensions","getVideoDimensions","width","height","getMediaTransferState","progress","isDownloadNeeded","isUploading","isTransferring","transferProgress","messageIds","contentType","validator","matchLinkInMessageText","getMediaDuration","duration","buildChatThreadKey","threadId","worker","requestStates","requestStatesByCallback","initApi","initialArgs","Worker","update","requestState","response","callbackArgs","subscribeToWorker","makeRequest","args","callApi","fnName","cancelApiProgress","progressCallback","isCanceled","postMessage","assign","pop","catch","finally","isWebpSupportedCache","isWebpSupported","webp","Image","handleLoadOrError","hasWebp","systemThemeCache","matchMedia","matches","getSystemTheme","handleSystemThemeChange","mql","addListener","PLATFORM_ENV","userAgent","platform","navigator","os","test","getPlatform","IS_MAC_OS","IS_IOS","IS_ANDROID","IS_PWA","standalone","referrer","includes","IS_TOUCH_ENV","IS_SINGLE_COLUMN_LAYOUT","innerWidth","IS_TABLET_COLUMN_LAYOUT","IS_VOICE_RECORDING_SUPPORTED","mediaDevices","AudioContext","webkitAudioContext","IS_EMOJI_SUPPORTED","documentElement","style","IS_SERVICE_WORKER_SUPPORTED","Audio","canPlayType","IS_CANVAS_FILTER_SUPPORTED","getContext","LAYERS_ANIMATION_NAME","DPR","devicePixelRatio","MASK_IMAGE_DISABLED","selectUser","global","userId","users","byId","selectIsUserBlocked","user","fullInfo","isBlocked","selectNotifySettings","settings","selectNotifyExceptions","notifyExceptions","selectChat","chats","selectChatUser","chat","getPrivateChatUserId","selectIsChatWithSelf","currentUserId","selectIsChatWithBot","isUserBot","selectSupportChat","isSupport","selectChatOnlineCount","isChatPrivate","isChatChannel","members","onlineCount","isUserOnline","selectChatBot","selectIsChatBotNotStarted","bot","lastMessage","messageInfo","byChatId","threadsById","MAIN_THREAD_ID","selectAreActiveChatsLoaded","listIds","active","selectIsChatListed","targetList","list","selectChatListType","folderId","selectChatFolder","chatFolders","selectIsChatPinned","archived","orderedPinnedIds","chatFoldersById","pinnedChatIds","selectChatByUsername","username","usernameLowered","toLowerCase","selectCountNotMutedUnread","activeChatIds","unreadCount","selectIsChatMuted","selectCurrentStickerSearch","stickers","search","selectCurrentGifSearch","gifs","selectStickerSet","setsById","selectStickerSetByShortName","shortName","selectStickersForEmoji","stickerSets","stickersForEmoji","packs","selectAnimatedEmoji","animatedEmojis","cleanedEmoji","replace","selectCurrentMessageList","messageLists","selectCurrentChat","selectChatMessages","selectScheduledMessages","scheduledMessages","selectThreadParam","thread","selectListedIds","selectOutlyingIds","selectCurrentMessageIds","messageListType","selectViewportIds","selectPinnedIds","selectScheduledIds","selectScrollOffset","selectReplyingToId","selectEditingId","selectEditingScheduledId","selectDraft","selectNoWebPage","selectThreadInfo","selectFirstMessageId","selectReplyStack","selectThreadOriginChat","threadInfo","originChannelId","selectThreadTopMessageId","topMessageId","selectThreadByMessage","replyToTopMessageId","isMessageInCurrentMessageList","currentMessageList","selectIsViewportNewest","viewportIds","lastMessageId","selectChatMessage","chatMessages","selectScheduledMessage","selectEditingMessage","selectChatMessageByPollId","pollId","messageWithPoll","selectFocusedMessageId","focusedChatId","focusedMessage","selectIsMessageFocused","focusedId","selectOutgoingStatus","isScheduledList","lastReadOutboxMessageId","selectIsMessageUnread","selectSender","selectForwardedSender","isChannelPost","fromChatId","senderUserId","selectAllowedMessageActions","serverTimeOffset","isRestricted","isPrivate","isChatWithSelf","isBasicGroup","isChatBasicGroup","isSuperGroup","isChatSuperGroup","isChannel","isServiceNotification","isOwn","isAction","isMessageEditable","getHasAdminRight","Date","viaBotId","canReply","getCanPostInChat","hasPinPermission","isCreator","isUserRightBanned","canPin","canUnpin","pinnedMessageIds","canDelete","canReport","canDeleteForAll","canEdit","canForward","hasSticker","hasFavoriteSticker","favorite","selectIsStickerFavorite","canFaveSticker","canUnfaveSticker","canCopy","canCopyLink","canSelect","noOptions","ability","selectCanDeleteSelectedMessages","selectedMessageIds","selectedMessages","messageActions","selectCanReportSelectedMessages","selectUploadProgress","fileTransfer","fileUploads","byMessageLocalId","selectRealLastReadId","lastReadInboxMessageId","min","Infinity","selectFirstUnreadId","outlyingIds","lastReadId","isNotJoined","found","isFromScheduled","selectIsForwardModalOpen","forwardMessages","isModalShown","selectCommonBoxChatId","fromLastMessage","isCommonBoxChat","selectIsInSelectMode","selectIsMessageSelected","selectForwardedMessageIdsByGroupId","fromMessageId","selectMessageIdsByGroupId","selectIsDocumentGroupSelected","selectedIds","groupIds","selectSelectedMessagesCount","selectNewestMessageWithBotKeyboardButtons","keyboardButtons","replyHideMessageId","shouldHideKeyboardButtons","selectShouldAutoLoadMedia","shouldAutoDownloadMediaFromContacts","shouldAutoDownloadMediaInPrivateChats","shouldAutoDownloadMediaInGroups","shouldAutoDownloadMediaInChannels","isChatGroup","userOrChat","contactList","userIds","selectIsUserOrChatContact","selectShouldAutoPlayMedia","shouldAutoPlayVideos","shouldAutoPlayGifs","asGif","selectShouldLoopStickers","shouldLoopStickers","selectCurrentTextSearch","chatThreadKey","currentSearch","localTextSearch","byChatThreadKey","isActive","selectCurrentMediaSearchPeerId","localMediaSearch","currentProfileUserId","selectedId","selectCurrentMediaSearch","peerId","selectManagement","management","selectCurrentManagementType","selectIsMediaViewerOpen","mediaViewer","avatarOwnerId","selectRightColumnContentKey","isChatInfoShown","newChatMembersProgress","isAddingChatMembersShown","NewChatMembersProgress","Closed","isPollResults","pollResults","selectIsPollResultsOpen","isSearch","isManagement","currentManagement","selectCurrentManagement","isStickerSearch","query","isGifSearch","currentChatId","areActiveChatsLoaded","isUserInfo","isChatInfo","RightColumnContent","PollResults","Search","Management","StickerSearch","GifSearch","AddingMembers","UserInfo","ChatInfo","selectIsRightColumnShown","selectTheme","theme","shouldUseSystemTheme","selectCurrentGlobalSearchQuery","globalSearch","selectPaymentMessageId","payment","selectPaymentRequestId","formId","selectProviderPublishableKey","nativeParams","publishableKey","selectStripeCredentials","stripeCredentials","parts","debounce","fn","ms","shouldRunFirst","shouldRunLast","waitingTimeout","self","throttle","interval","isPending","_args","setInterval","clearInterval","throttleWith","fastPrimaryRaf","waiting","onIdle","requestIdleCallback","pause","rafPromise","fastRafCallbacks","fastRafPrimaryCallbacks","beforeUnloadCallbacks","isPrimary","requestAnimationFrame","currentCallbacks","currentPrimaryCallbacks","onBeforeUnload","isLast","unshift","replaceChatListIds","newIds","updateChatListIds","idsUpdate","replaceChats","newById","getUpdatedChat","chatUpdate","shouldOmitMinInfo","isMin","updatedChat","photos","updateChat","updateChats","updatedById","updatedChats","addChats","addedById","isAdded","addedChats","updateChatListType","listType","currentListIds","listTypeKey","currentFolderList","updateChatListSecondaryInfo","info","totalCountKey","totalCount","totalChatCount","isFullyLoaded","updateCurrentMessageList","shouldReplaceHistory","newMessageLists","last","replaceChatMessages","updateMessageStore","replaceThreadParam","paramName","threadUpdate","updateThread","addMessages","addedByChatId","messagesByChatId","addChatMessagesById","newId","updateChatMessage","messageUpdate","updatedMessage","updateScheduledMessage","replaceScheduledMessages","deleteChatMessages","deletedForwardedPosts","isLinkedChannelPost","pinnedIds","newMessageCount","messagesCount","canDeleteCurrentThread","currentThreadId","originalPost","deleteChatScheduledMessages","scheduledIds","updateListedIds","orderHistoryIds","updateOutlyingIds","addViewportId","safeReplaceViewportIds","newViewportIds","updateThreadInfo","newThreadInfo","updateThreadInfos","updates","hash","updateScheduledMessages","updateFocusedMessage","noHighlight","updateFocusDirection","direction","enterMessageSelectMode","toggleMessageSelection","childMessageIds","withShift","oldSelectedMessages","newMessageIds","newSelectedMessageIds","prevIndex","currentIndex","to","max","exitMessageSelectMode","updateStickerSets","category","sets","resultIds","updatedSets","stickerSet","existing","setIds","updateStickerSet","stickerSetId","currentStickerSet","updateGifSearch","isNew","results","nextOffset","currentResults","newResults","currentIds","gif","replaceAnimatedEmojis","updateStickersForEmoji","remoteStickers","allStickers","uniqueIds","forEmoji","rebuildStickersForEmoji","replaceUsers","getUpdatedUser","userUpdate","updatedUser","updateContactList","updatedUsers","contactUserIds","newContactUserIds","isContact","updateUser","updateUsers","addUsers","addedUsers","updateSelectedUserId","deleteUser","MEMO_EMPTY_ARRAY","updateUserSearch","searchStatePartial","userSearch","updateUserSearchFetchingStatus","newState","fetchingStatus","updateUserBlockedState","getComplexKey","updateGlobalSearch","updateGlobalSearchContent","currentContent","updateGlobalSearchResults","newFoundMessages","nextRate","resultsByType","newFoundMessagesById","foundIdsForType","foundIds","updateGlobalSearchFetchingStatus","prevFoundIds","newFoundIds","foundOrPrevFoundIds","nextOffsetId","replaceLocalTextSearch","searchParams","updateLocalTextSearch","replaceLocalTextSearchResults","updateLocalTextSearchResults","orderFoundIds","replaceLocalMediaSearch","updateLocalMediaSearchType","currentType","updateLocalMediaSearchResults","replaceLocalMediaSearchResults","updateManagementProgress","updateManagement","replaceSettings","newSettings","replaceThemeSettings","themes","addNotifyExceptions","notifyException","exceptionData","addNotifyException","updateNotifySettings","peerType","isSilent","shouldShowPreviews","hasPrivateChatsNotifications","hasPrivateChatsMessagePreview","hasGroupNotifications","hasGroupMessagePreview","hasBroadcastNotifications","hasBroadcastMessagePreview","addBlockedContact","contactId","blocked","removeBlockedContact","updateTwoFaSettings","twoFaSettings","updateShippingOptions","shippingOptions","setRequestInfoId","setPaymentStep","step","setInvoiceMessageInfo","description","photoUrl","invoiceContent","setStripeCardInfo","cardInfo","setPaymentForm","form","setReceipt","receipt","messageInvoice","clearPayment","closeInvoice","isPaymentModalOpen","cacheApi","caches","Type","async","fetch","cacheName","Request","cache","open","Blob","blob","headers","Json","json","save","cacheData","JSON","stringify","Response","put","clear","LoadMoreDirection","FocusDirection","SettingsScreens","LeftColumnContent","GlobalSearchContent","MediaViewerOrigin","ChatCreationProgress","ProfileEditProgress","ManagementProgress","ProfileState","PaymentStep","UPLOADING_WALLPAPER_SLUG","ManagementScreens","SUBSTITUTION_REGEX","PLURAL_OPTIONS","PLURAL_RULES","en","ar","ca","de","es","fa","fr","it","ko","nl","pl","pt_BR","ru","tr","uk","uz","langPack","fallbackLangPack","createCallbackManager","currentLangCode","getTranslation","format","cacheValue","cached","langString","processTranslation","importFallbackLangPack","getTranslationForLangString","langCode","translateString","remoteLangPack","remote","fetchRemoteString","setLanguage","withFallback","newLangPack","sourceLangPacks","fetchRemote","languages","langInfo","isRtl","rtl","default","template","amount","optionIndex","getPluralOption","translationSlices","initialValue","str","processTemplate","formatInteger","Bundles","LOAD_PROMISES","MEMORY_CACHE","loadModule","bundleName","moduleName","Auth","Main","Extra","handleBundleLoad","bundle","getModuleFromMemory","listeners","addLoadListener","listener","promisifyRequest","oncomplete","onsuccess","onabort","defaultGetStoreFunc","defaultGetStore","dbName","storeName","indexedDB","onupgradeneeded","createObjectStore","dbp","txMode","db","transaction","objectStore","createStore","eachCursor","customStore","store","openCursor","this","continue","DC_IDS","hasStoredSession","withLegacy","localStorage","getItem","userAuthJson","userAuth","parse","dcID","storeSession","sessionData","mainDcId","hashes","setItem","dcId","clearStoredSession","removeItem","loadStoredSession","importLegacySession","sessionId","sessionJson","idb","clearLegacySessions","idbKeys","items","k","startsWith","File","constructor","fileBits","options","rest","super","dataUriToBlob","arr","mime","bstr","atob","u8arr","Uint8Array","charCodeAt","blobToDataUri","reader","FileReader","readAsDataURL","blobToFile","lastModified","preloadImage","img","preloadVideo","volume","onloadedmetadata","createPosterForVideo","race","onseeked","videoWidth","videoHeight","canvas","drawImage","toDataURL","currentTime","fetchBlob","imgToCanvas","useOnChange","langProvider","vs16RegExp","zeroWidthJoiner","fromCharCode","removeVS16s","rawEmoji","color","className","withBackground","getDeviceToken","subscription","toJSON","endpoint","checkIfPushSupported","ServiceWorkerRegistration","Notification","permission","soundPlayed","playNotificationSound","notificationSoundVolume","add","once","play","requestPermission","unsubscribeFromPush","dispatch","deviceToken","unsubscribe","deleteDeviceToken","serviceWorkerRegistration","serviceWorker","ready","pushManager","getSubscription","areSettingsLoaded","subscribe","subscribedAt","checkIfShouldResubscribe","userVisibleOnly","setDeviceToken","DOMException","ABORT_ERR","showNewMessageNotification","isActiveChat","resultSettings","resultExceptions","loadNotificationSettings","isListed","hasFocus","checkIfShouldNotify","body","messageSender","messageAction","actionTargetMessage","targetUserIds","actionTargetUserIds","targetChatId","actionTargetChatId","actionTargetUsers","privateChatUserId","privateChatUser","selectShouldShowMessagePreview","actionOrigin","renderActionMessageText","asPlain","senderName","getMessageSenderName","getNotificationContent","icon","imageHash","getChatAvatarHash","mediaData","mediaLoader","getAvatar","controller","badge","toString","vibrate","notification","onclick","close","focusMessage","focus","onshow","notifyClientReady","Button","ref","onClick","onContextMenu","onMouseDown","onMouseEnter","onMouseLeave","onFocus","pill","fluid","isText","isLoading","ariaLabel","download","disabled","ripple","faded","tabIndex","elementRef","isClicked","setIsClicked","fullClassName","buildClassName","handleClick","handleMouseDown","preventDefault","dir","aria-label","RE_LETTER_OR_DIGIT","SIMPLE_MARKDOWN_REGEX","renderText","part","filters","params","textParts","divEl","innerText","innerHTML","escapeHtml","EMOJI_REGEX","lastIndex","replaceEmojis","addLineBreaks","highlight","lowerCaseText","queryPosition","nextSymbol","newParts","links","nextLink","endsWith","addLinks","replaceSimpleMarkdown","emojis","emojiResult","nativeToUnfified","alt","line","trimmedLine","trimLeft","indentLength","repeat","entityResult","formatsCache","defaultPhoneNumberFormat","parsed","flag","phoneFormat","formatValue","phoneNumberFormat","phoneNumberGroups","count","getPhoneNumberFormat","getCountryById","countryList","getCountryFromPhoneNumber","input","phoneNumber","possibleCountries","country","formatPhoneNumber","_","p1","p2","p3","p4","p5","separator","output","formatPhoneNumberWithCode","numberWithPlus","setValue","noLoad","autoUpdate","Spinner","handleErrorEvent","ErrorEvent","reason","alert","currentProps","newProps","currentKeys","currentKeysLength","prop","usePrevious","next","shouldSkipUndefined","WEEKDAYS_FULL","MONTHS_FULL","MONTHS_FULL_LOWERCASE","month","getDayStart","datetime","setHours","getDayStartAt","getTime","toYearMonth","timestamp","getFullYear","getMonth","toIsoString","getDate","formatTime","getHours","padStart","getMinutes","formatPastTimeShort","today","weekAgo","setDate","getDay","withYear","formatDate","formatFullDate","formatMonthAndYear","isShort","formatHumanDate","noWeekdays","lowerFirst","upperFirst","yesterday","weekAhead","weekDay","day","monthIndex","formatMediaDateTime","formatMediaDuration","hours","floor","minutes","seconds","string","formatVoiceRecordDuration","durationInMs","milliseconds","formatDateToString","locale","toLocaleString","year","isValidDate","MAX_MONTH_IN_YEAR","parseDateString","matchStringDate","matchEuropeStringDate","matchNumberDate","dateParts","findIndex","timestampPlusDay","MILISECONDS_IN_DAY","toUpperCase","WEBSYNC_URLS","WEBSYNC_VERSION","getTs","lastTimeout","forceWebsync","authed","currentTs","canRedirect","ts","removeElement","URLSearchParams","version","saveSync","startWebsync","authState","setTrigger","trigger","oggToWav","opusData","arrayBuffer","typedArray","decoderWorker","DecoderWorker","wavWorker","WavWorker","onmessage","command","buffers","buffer","page","terminate","wavBitDepth","wavSampleRate","decoderSampleRate","outputBufferSampleRate","pages","asCacheApiType","DataUri","Stream","memoryCache","fetchPromises","mediaFormat","onProgress","progressiveUrl","getProgressive","mediaPng","webpToPng","prepared","prepareMedia","mediaSource","MediaSource","streamUrl","URL","createObjectURL","isOpen","sourceBuffer","addSourceBuffer","endOfStream","appendBuffer","revokeObjectURL","fetchFromCacheOrRemote","getFromMemory","cancelProgress","fullSize","Link","random","USER_COLOR_KEYS","getUserFirstOrLastName","firstName","lastName","isDeletedUser","getUserStatus","status","wasOnline","wasOnlineDate","diff","sortUserIds","usersById","priorityIds","expires","getUserColorKey","peer","abs","FOREVER_BANNED_DATE","getChatTypeString","isSelf","getChatDescription","about","getChatLink","inviteLink","owner","avatarHash","isChatSummaryOnly","isChatAdmin","adminRights","currentUserBannedRights","defaultBannedRights","migratedTo","getAllowedAttachmentOptions","isChatWithBot","canAttachMedia","canAttachPolls","canSendStickers","canSendGifs","canAttachEmbedLinks","isAdmin","getMessageSendingRestrictionReason","sendMessages","untilDate","getChatSlowModeOptions","slowMode","getChatOrder","joinDate","draftDate","isChatArchived","notifySettings","isMuted","getCanDeleteChat","prepareFolderListIds","chatsById","folder","chatIdsCache","excludedChatIds","includedChatIds","excludeArchived","excludeMuted","unreadMentionsCount","hasUnreadMark","excludeRead","bots","contacts","nonContacts","groups","channels","filterChatFolder","prepareChatList","folderType","chatFilter","listedChats","listIdsSet","pinnedChats","otherChats","getFolderUnreadDialogs","unreadDialogsCount","total","hasActiveDialogs","getFolderDescriptionText","emoticon","getFolderChatsCount","isChat","chatOrUser","sortChatIds","chatIds","shouldPrioritizeVerified","priority","isVerified","ANIMATION_START_EVENT","ANIMATION_END_EVENT","isAnimating","dispatchHeavyAnimationEvent","dispatchEvent","Event","handleAnimationStart","handleAnimationEnd","removeEventListener","NON_BUBBLEABLE_EVENTS","delegationRegistry","delegatedEventsByElement","documentEventCounters","element","propName","handler","asCapture","eventName","resolveEventName","canUseEventDelegation","handleEvent","resolveDelegationRegistryForName","newSet","resolveDelegatedEventsForElement","addDelegatedListener","removeDelegatedListener","tagName","realEventName","eventNames","realEvent","events","furtherCallsPrevented","stopPropagation","Proxy","Reflect","LOCATION_HASH","location","historyState","nextStateIndexToReplace","isHistoryAltered","isDisabled","isEdge","currentIndexes","disableHistoryBack","handleTouchStart","x","touches","pageX","handleTouchEnd","useHistoryBack","onBack","onForward","currentState","shouldReplaceNext","indexRef","isForward","prevIsActive","isClosed","indexHashRef","prevHashes","isHashChangedFromEvent","handleChange","isForceClose","prev","history","pushState","delta","realDelta","indexLast","go","replaceState","back","handlePopState","currIndex","disableHistoryAnimations","hasChanged","forceClose","pathname","onCloseTransitionEnd","noOpenTransition","noCloseTransition","setIsClosed","closeTimeoutRef","hasOpenClassName","setHasOpenClassName","shouldHaveOpenClassName","isClosing","shouldRender","transitionClassNames","trimText","MenuItem","destructive","useLang","handleKeyDown","keyCode","data-char","origin","role","onKeyDown","ripples","setRipples","cleanUpDebounced","button","currentTarget","position","getBoundingClientRect","rippleSize","offsetWidth","clientX","y","clientY","EMPTY_IMAGE_DATA_URI","initWebpWorker","wasmReady","requests","getDecodePromise","ImageData","putImageData","toBlob","createPng","webpToPngBase64","pngBlob","WebpWorker","handleLibWebpMessage","isInitialized","HEX_COLOR_REGEX","lerp","start","end","interpolationRatio","colors","themeColors","hexToRgb","hex","parseInt","g","applyColorAnimationStep","startIndex","endIndex","propertyColors","setProperty","withAnimation","isDarkTheme","shouldAnimate","startAt","themeColorTag","querySelector","classList","remove","animateSingle","transition","label","success","readOnly","placeholder","autoComplete","inputMode","maxLength","onChange","onInput","onKeyPress","onBlur","onPaste","labelText","htmlFor","subLabel","checked","blocking","onCheck","captureEscKeyListener","captureKeyboardListener","onEsc","formatFixedNumber","number","toFixed","formatIntegerCompact","views","getFirstLetters","phrase","word","prevDeps","RE_NOT_LETTER","searchWords","haystack","needle","haystackWords","needleWord","haystackWord","IS_LANDSCAPE","isLandscape","initialHeight","windowSize","updateSizes","isRefreshDisabled","handleResize","reload","vh","getIsKeyboardVisible","disableRefresh","enableRefresh","Menu","containerRef","positionX","positionY","autoClose","footer","noCloseOnBackdrop","onCloseAnimationEnd","onClose","shouldSkipTransition","menuRef","backdropContainerRef","useShowTransition","useEffectWithPrevDeps","prevIsOpen","useKeyboardListNavigation","useVirtualBackdrop","bubbleClassName","keyToHandlerName","Enter","Backspace","Delete","Esc","Escape","ArrowUp","ArrowDown","ArrowLeft","ArrowRight","Tab","handlers","onEnter","onDelete","onBackspace","onUp","onDown","onLeft","onRight","onTab","captureKeyboardListeners","hasActiveHandlers","handlerName","currentEventHandlers","releaseKeyboardListener","keyHandlers","utf16","len","RangeError","adapt","numpoints","firsttime","decode","preserveCase","case_flags","input_length","out","bias","basic","j","ic","oldi","w","digit","lastIndexOf","cp","toUnicode","domain_array","ensureProtocol","getDomain","decodedHref","decodeURI","convertPunycode","toggleSafeLinkModal","openTelegramLink","isNotSafe","ctrlKey","altKey","shiftKey","metaKey","classNames","getFileSizeString","bytes","ONE_GIGABYTE","ONE_MEGABYTE","getDocumentExtension","getFileExtension","getColorFromExtension","extension","STRIPE_ERRORS","missing_payment_information","field","fieldError","invalid_number","exp_year","exp_month","invalid_expiry_year","invalid_expiry_month","cvc","invalid_cvc","getStripeError","param","SHIPPING_ERRORS","ADDRESS_STREET_LINE1_INVALID","ADDRESS_STREET_LINE2_INVALID","ADDRESS_CITY_INVALID","ADDRESS_COUNTRY_INVALID","ADDRESS_POSTCODE_INVALID","ADDRESS_STATE_INVALID","REQ_INFO_NAME_INVALID","REQ_INFO_PHONE_INVALID","REQ_INFO_EMAIL_INVALID","getShippingErrors","dialogs","cur","hasErrorKey","currentInstance","tick","instance","isCancelled","animate","DropdownMenu","forceOpen","onOpen","dropdownRef","setIsOpen","menu","focusedElement","activeElement","elementChildren","onTrigger","onSelectWithEnter","itemSelector","noCaptureFocus","focusedIndex","setFocusedIndex","querySelectorAll","newIndex","RE_EMOJI_ONLY","twemojiRegex","DETECT_UP_TO","emojiCount","EXCLUDE_EMOJIS","unifiedToNative","unified","codePoints","fromCodePoint","pairs","uncompressEmoji","emojiData","categories","emojiRaw","names","native","image","FILTERED_ATTRIBUTES","HTML_ATTRIBUTES","MAPPED_ATTRIBUTES","autoPlay","headsByElement","renderWithVirtual","parentEl","$current","$parent","skipComponentUpdate","forceIndex","fragment","moveDirection","updateComponent","setupComponentUpdateListener","initComponent","node","createNode","childNodes","insertBefore","replaceChild","areComponents","nextSibling","newKeys","removeAttribute","addAttribute","oldValue","updateAttribute","updateAttributes","currentEl","teactFastList","$newChild","currentRemainingIndex","remainingByKey","$currentChild","newChildKey","order","teactOrderKey","fragmentQueue","fragmentIndex","newChildren","currentPreservedIndex","currentChildInfo","flushFragmentQueue","shouldMoveNode","isMovingDown","renderFastListChildren","createDocumentFragment","renderChildren","$firstChild","createTextNode","$child","$fragmentChild","cssText","render","headId","$head","openUserInfo","handleMessageClick","openChat","targetUsers","targetMessage","translationValues","textOptions","maxTextLength","unprocessed","processed","processPlaceholder","isEmbedded","renderChatContent","renderUserContent","renderOriginContent","showQuotes","messageText","renderMessageContent","renderProductContent","renderMigratedContent","replaceValue","placeholderPosition","MESSAGE_DELETED","openChatByUsername","updateAppBadge","setAppBadge","contains","currentThemeMatch","currentTheme","nextTheme","animationLevel","switchTheme","subscribeToSystemThemeChange","messageTextSize","language","uiReadyState","authPhoneNumber","authRememberMe","authError","shouldSkipHistoryAnimations","apiUpdate","authIsLoading","password","file","authIsLoadingQrCode","reset","langCachePrefix","langCacheVersion","init","connectionState","authNearestCountry","buildInputPrivacyRules","visibility","allowedIds","deniedIds","rules","collectUsers","accessHash","collectChats","allowedUsers","allowedChats","blockedUsers","blockedChats","bio","profileEdit","InProgress","currentUser","Complete","Idle","isUsernameAvailable","loadedWallpapers","wallpapers","slug","wallpaper","firstWallpaper","withLocalMedia","blockedIds","activeSessions","session","isCurrent","hasPushNotifications","hasWebNotifications","hasContactJoinedNotifications","phoneNumberSettings","lastSeenSettings","profilePhotoSettings","forwardsSettings","chatInviteSettings","privacy","lastSeen","profilePhoto","forwards","chatInvite","privacyKey","allowUserIds","allowChatIds","blockUserIds","blockChatIds","isAllowList","contactsIds","isSensitiveEnabled","onUpdateApiReady","wasAuthReady","authorizationState","isLoggingOut","authIsCodeViaApp","isCodeViaApp","authHint","hint","authQrCode","qrCode","lastSyncTime","onUpdateAuthorizationState","onUpdateAuthorizationError","sync","signOut","onUpdateConnectionState","isEmpty","saveSession","onUpdateSession","onUpdateServerTimeOffset","sessionUserAuth","updateSessionUserId","onUpdateCurrentUser","showDialog","ServiceWorkerNoSupportError","setPrototypeOf","scriptUrl","handleWorkerMessage","register","INITIAL_STATE","isLeftColumnShown","activeChatFolder","recentEmojis","added","recent","greeting","featured","emojiKeywords","saved","inlineBots","byUsername","topPeers","topInlineBots","audioPlayer","notifications","messageSendKeyCombo","shouldSuggestStickers","light","isBlurred","patternColor","dark","shouldShowContextMenuHint","updateCacheThrottled","updateCache","unsubscribeFromBeforeUnload","isCaching","isHeavyAnimating","loadCache","initialState","setupCaching","time","timeEnd","readCache","clearCaching","reducedGlobal","reduceShowChatInfo","reduceUsers","reduceChats","reduceMessages","recentlyFoundChatIds","reduceSettings","reduceChatFolders","idsToSave","cid","chatIdsToSave","mainThread","tabKey","SITE_FONTS","preloadFonts","font","fonts","load","preloadAvatars","preloadTasks","main","telegramLogoPath","authCode","monkeyPath","authPassword","background","backgroundColor","hasCustomBackground","hasCustomBackgroundColor","isRightColumnShown","setIsUiReady","isReady","markReady","useFlag","shouldRenderMask","safePreload","translation","setTranslation","getSuggestedLanguage","suggestedLanguage","MENU_HIDING_DURATION","inputRef","setFilter","filteredList","setFilteredList","updateFilter","filterValue","getFilteredList","countryId","firstElementChild","dataset","handleInput","handleInputKeyDown","handleTrigger","select","formEl","getElementById","scrollTo","top","scrollHeight","behavior","inputValue","data-country-id","isPreloadInitiated","setAuthPhoneNumber","setAuthRememberMe","loadNearestCountry","clearAuthError","goToAuthQrCode","setSettingOption","continueText","useLangString","setCountry","setPhoneNumber","isTouched","setIsTouched","lastSelection","setLastSelection","markIsLoading","unmarkIsLoading","fullNumber","canSubmit","parseFullNumber","newFullNumber","suggestedCountry","selectedCountry","handleLangChange","setSelectionRange","isJustPastedRef","handlePaste","handlePhoneNumberChange","selectionStart","selectionEnd","shouldFixSafariAutoComplete","handleKeepSessionChange","isAuthReady","onSubmit","InputText","Checkbox","Loading","AuthCode","useModuleLoader","AuthPassword","AuthRegister","G","H","B","QrCreator","h","u","J","level","O","C","f","lineTo","arcTo","moveTo","z","v","N","K","P","fillStyle","fillRect","left","beginPath","q","D","E","R","I","F","fill","colorStops","createLinearGradient","apply","createRadialGradient","addColorStop","A","minVersion","maxVersion","ecLevel","radius","quiet","HTMLCanvasElement","clearRect","write","S","multiply","L","M","Q","returnToAuthPhoneNumber","qrCodeRef","token","isMobile","AuthQrCode","AppInactive","appInactivePath","renderMain","disconnect","isInactive","markInactive","TeactDOM"],"mappings":"aACE,SAASA,EAAqBC,GAQ7B,IAPA,IAMIC,EAAUC,EANVC,EAAWH,EAAK,GAChBI,EAAcJ,EAAK,GAKAK,EAAI,EAAGC,EAAW,GACpCD,EAAI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,WACb,yBAAK/xC,IAAKi5E,GAAiB5+B,IAAI,KAC/B,wBAAItI,UAAU,SAAd,yBACA,yBAAKA,UAAU,eAAf,sDAEE,6BAFF,mEAKA,yBAAKA,UAAU,WACb,kBAAC8E,GAAA,EAAD,CAAQU,QAAM,EAACK,QAAM,EAACb,QAfT,KACnB1zC,OAAOkqD,SAAS+J,WAcV,iBCoCV,SAAS4hB,KACP,OACE,kBAAC,EAAD,CAAU91B,KAAK,OAAOvgD,IAAI,QACxB,kBAAC,GAAD,OAKSkK,mBACZqX,GAAuBnQ,YAAKmQ,EAAQ,CAAC,cACtC,CAAC/Y,EAAWC,IAA2B2I,YAAK3I,EAAS,CAAC,eAFzCyB,CA9C6B,EAAGs1C,YAAW82B,iBACxD,MAAOC,EAAYC,GAAgBlI,aAAQ,GAc3C,GAZA3nE,YAAU,KACR2tD,clBRFpjD,EkBS6B,KACzBolE,IACAl6E,SAAS6b,MAAS,GAAEtN,OAAaC,MAEjC4rE,MAED,CAACF,EAAYE,IAIZD,EACF,OAAO,kBAAC,GAAD,MAGT,GAAI/2B,EACF,OAAQA,GACN,IAAK,oCACL,IAAK,6BACL,IAAK,iCACL,IAAK,qCACL,IAAK,+BACH,OAAO,kBAAC,GAAD,MACT,IAAK,2BACL,IAAK,4BACL,IAAK,+BACL,IAAK,0BACH,OAAO62B,KAIb,OAAOzrC,aAAiB,GAAQyrC,KAAe,kBAAC,GAAD,Q,OC1C7ClzE,KAEF7C,QAAQkD,IAAI,YAGdgG,cAAcw7D,OAEV7hE,KAEF7C,QAAQkD,IAAI,4BAGdizE,IAAS5U,OACP,kBAAC,GAAD,MACAzlE,SAASyzE,eAAe,SAGtB1sE,KAEF7C,QAAQkD,IAAI,6BAGdpH,SAASsL,iBAAiB,WAAY,KAEpCpH,QAAQkD,IAAI,eAAgB+F","file":"main.e8fae56b26f205f69c4c.js","sourcesContent":[" \t// install a JSONP callback for chunk loading\n \tfunction webpackJsonpCallback(data) {\n \t\tvar chunkIds = data[0];\n \t\tvar moreModules = data[1];\n\n\n \t\t// add \"moreModules\" to the modules object,\n \t\t// then flag all \"chunkIds\" as loaded and fire callback\n \t\tvar moduleId, chunkId, i = 0, resolves = [];\n \t\tfor(;i < chunkIds.length; i++) {\n \t\t\tchunkId = chunkIds[i];\n \t\t\tif(Object.prototype.hasOwnProperty.call(installedChunks, chunkId) && installedChunks[chunkId]) {\n \t\t\t\tresolves.push(installedChunks[chunkId][0]);\n \t\t\t}\n \t\t\tinstalledChunks[chunkId] = 0;\n \t\t}\n \t\tfor(moduleId in moreModules) {\n \t\t\tif(Object.prototype.hasOwnProperty.call(moreModules, moduleId)) {\n \t\t\t\tmodules[moduleId] = moreModules[moduleId];\n \t\t\t}\n \t\t}\n \t\tif(parentJsonpFunction) parentJsonpFunction(data);\n\n \t\twhile(resolves.length) {\n \t\t\tresolves.shift()();\n \t\t}\n\n \t};\n\n\n \t// The module cache\n \tvar installedModules = {};\n\n \t// object to store loaded CSS chunks\n \tvar installedCssChunks = {\n \t\t2: 0\n \t}\n\n \t// object to store loaded and loading chunks\n \t// undefined = chunk not loaded, null = chunk preloaded/prefetched\n \t// Promise = chunk loading, 0 = chunk loaded\n \tvar installedChunks = {\n \t\t2: 0\n \t};\n\n\n\n \t// script path function\n \tfunction jsonpScriptSrc(chunkId) {\n \t\treturn __webpack_require__.p + \"\" + chunkId + \".\" + {\"0\":\"5b30c68c9d873a9c7445\",\"1\":\"7e82665c294b00b1ad01\",\"3\":\"169a4db27e15b29d4577\",\"4\":\"e7ab7e659007d8f15d4f\",\"5\":\"52a05d90e1e8c254e0d3\",\"6\":\"28ade786fe9232965702\",\"7\":\"99de4b789a3c0b7f6d7d\",\"8\":\"8120c92d9a6e9dd9df62\",\"9\":\"3ea811530bc0ccdd95f2\",\"10\":\"90d13e627c200bd7aaf1\"}[chunkId] + \".js\"\n \t}\n\n \t// The require function\n \tfunction __webpack_require__(moduleId) {\n\n \t\t// Check if module is in cache\n \t\tif(installedModules[moduleId]) {\n \t\t\treturn installedModules[moduleId].exports;\n \t\t}\n \t\t// Create a new module (and put it into the cache)\n \t\tvar module = installedModules[moduleId] = {\n \t\t\ti: moduleId,\n \t\t\tl: false,\n \t\t\texports: {}\n \t\t};\n\n \t\t// Execute the module function\n \t\tmodules[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n \t\t// Flag the module as loaded\n \t\tmodule.l = true;\n\n \t\t// Return the exports of the module\n \t\treturn module.exports;\n \t}\n\n \t// This file contains only the entry chunk.\n \t// The chunk loading function for additional chunks\n \t__webpack_require__.e = function requireEnsure(chunkId) {\n \t\tvar promises = [];\n\n\n \t\t// mini-css-extract-plugin CSS loading\n \t\tvar cssChunks = {\"0\":1,\"3\":1,\"4\":1,\"5\":1,\"6\":1};\n \t\tif(installedCssChunks[chunkId]) promises.push(installedCssChunks[chunkId]);\n \t\telse if(installedCssChunks[chunkId] !== 0 && cssChunks[chunkId]) {\n \t\t\tpromises.push(installedCssChunks[chunkId] = new Promise(function(resolve, reject) {\n \t\t\t\tvar href = \"\" + ({}[chunkId]||chunkId) + \".\" + {\"0\":\"5b30c68c9d873a9c7445\",\"1\":\"7e82665c294b00b1ad01\",\"3\":\"169a4db27e15b29d4577\",\"4\":\"e7ab7e659007d8f15d4f\",\"5\":\"52a05d90e1e8c254e0d3\",\"6\":\"28ade786fe9232965702\",\"7\":\"99de4b789a3c0b7f6d7d\",\"8\":\"8120c92d9a6e9dd9df62\",\"9\":\"3ea811530bc0ccdd95f2\",\"10\":\"90d13e627c200bd7aaf1\"}[chunkId] + \".css\";\n \t\t\t\tvar fullhref = __webpack_require__.p + href;\n \t\t\t\tvar existingLinkTags = document.getElementsByTagName(\"link\");\n \t\t\t\tfor(var i = 0; i < existingLinkTags.length; i++) {\n \t\t\t\t\tvar tag = existingLinkTags[i];\n \t\t\t\t\tvar dataHref = tag.getAttribute(\"data-href\") || tag.getAttribute(\"href\");\n \t\t\t\t\tif(tag.rel === \"stylesheet\" && (dataHref === href || dataHref === fullhref)) return resolve();\n \t\t\t\t}\n \t\t\t\tvar existingStyleTags = document.getElementsByTagName(\"style\");\n \t\t\t\tfor(var i = 0; i < existingStyleTags.length; i++) {\n \t\t\t\t\tvar tag = existingStyleTags[i];\n \t\t\t\t\tvar dataHref = tag.getAttribute(\"data-href\");\n \t\t\t\t\tif(dataHref === href || dataHref === fullhref) return resolve();\n \t\t\t\t}\n \t\t\t\tvar linkTag = document.createElement(\"link\");\n \t\t\t\tlinkTag.rel = \"stylesheet\";\n \t\t\t\tlinkTag.type = \"text/css\";\n \t\t\t\tlinkTag.onload = resolve;\n \t\t\t\tlinkTag.onerror = function(event) {\n \t\t\t\t\tvar request = event && event.target && event.target.src || fullhref;\n \t\t\t\t\tvar err = new Error(\"Loading CSS chunk \" + chunkId + \" failed.\\n(\" + request + \")\");\n \t\t\t\t\terr.code = \"CSS_CHUNK_LOAD_FAILED\";\n \t\t\t\t\terr.request = request;\n \t\t\t\t\tdelete installedCssChunks[chunkId]\n \t\t\t\t\tlinkTag.parentNode.removeChild(linkTag)\n \t\t\t\t\treject(err);\n \t\t\t\t};\n \t\t\t\tlinkTag.href = fullhref;\n\n \t\t\t\tvar head = document.getElementsByTagName(\"head\")[0];\n \t\t\t\thead.appendChild(linkTag);\n \t\t\t}).then(function() {\n \t\t\t\tinstalledCssChunks[chunkId] = 0;\n \t\t\t}));\n \t\t}\n\n \t\t// JSONP chunk loading for javascript\n\n \t\tvar installedChunkData = installedChunks[chunkId];\n \t\tif(installedChunkData !== 0) { // 0 means \"already installed\".\n\n \t\t\t// a Promise means \"currently loading\".\n \t\t\tif(installedChunkData) {\n \t\t\t\tpromises.push(installedChunkData[2]);\n \t\t\t} else {\n \t\t\t\t// setup Promise in chunk cache\n \t\t\t\tvar promise = new Promise(function(resolve, reject) {\n \t\t\t\t\tinstalledChunkData = installedChunks[chunkId] = [resolve, reject];\n \t\t\t\t});\n \t\t\t\tpromises.push(installedChunkData[2] = promise);\n\n \t\t\t\t// start chunk loading\n \t\t\t\tvar script = document.createElement('script');\n \t\t\t\tvar onScriptComplete;\n\n \t\t\t\tscript.charset = 'utf-8';\n \t\t\t\tscript.timeout = 120;\n \t\t\t\tif (__webpack_require__.nc) {\n \t\t\t\t\tscript.setAttribute(\"nonce\", __webpack_require__.nc);\n \t\t\t\t}\n \t\t\t\tscript.src = jsonpScriptSrc(chunkId);\n\n \t\t\t\t// create error before stack unwound to get useful stacktrace later\n \t\t\t\tvar error = new Error();\n \t\t\t\tonScriptComplete = function (event) {\n \t\t\t\t\t// avoid mem leaks in IE.\n \t\t\t\t\tscript.onerror = script.onload = null;\n \t\t\t\t\tclearTimeout(timeout);\n \t\t\t\t\tvar chunk = installedChunks[chunkId];\n \t\t\t\t\tif(chunk !== 0) {\n \t\t\t\t\t\tif(chunk) {\n \t\t\t\t\t\t\tvar errorType = event && (event.type === 'load' ? 'missing' : event.type);\n \t\t\t\t\t\t\tvar realSrc = event && event.target && event.target.src;\n \t\t\t\t\t\t\terror.message = 'Loading chunk ' + chunkId + ' failed.\\n(' + errorType + ': ' + realSrc + ')';\n \t\t\t\t\t\t\terror.name = 'ChunkLoadError';\n \t\t\t\t\t\t\terror.type = errorType;\n \t\t\t\t\t\t\terror.request = realSrc;\n \t\t\t\t\t\t\tchunk[1](error);\n \t\t\t\t\t\t}\n \t\t\t\t\t\tinstalledChunks[chunkId] = undefined;\n \t\t\t\t\t}\n \t\t\t\t};\n \t\t\t\tvar timeout = setTimeout(function(){\n \t\t\t\t\tonScriptComplete({ type: 'timeout', target: script });\n \t\t\t\t}, 120000);\n \t\t\t\tscript.onerror = script.onload = onScriptComplete;\n \t\t\t\tdocument.head.appendChild(script);\n \t\t\t}\n \t\t}\n \t\treturn Promise.all(promises);\n \t};\n\n \t// expose the modules object (__webpack_modules__)\n \t__webpack_require__.m = modules;\n\n \t// expose the module cache\n \t__webpack_require__.c = installedModules;\n\n \t// define getter function for harmony exports\n \t__webpack_require__.d = function(exports, name, getter) {\n \t\tif(!__webpack_require__.o(exports, name)) {\n \t\t\tObject.defineProperty(exports, name, { enumerable: true, get: getter });\n \t\t}\n \t};\n\n \t// define __esModule on exports\n \t__webpack_require__.r = function(exports) {\n \t\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n \t\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n \t\t}\n \t\tObject.defineProperty(exports, '__esModule', { value: true });\n \t};\n\n \t// create a fake namespace object\n \t// mode & 1: value is a module id, require it\n \t// mode & 2: merge all properties of value into the ns\n \t// mode & 4: return value when already ns object\n \t// mode & 8|1: behave like require\n \t__webpack_require__.t = function(value, mode) {\n \t\tif(mode & 1) value = __webpack_require__(value);\n \t\tif(mode & 8) return value;\n \t\tif((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;\n \t\tvar ns = Object.create(null);\n \t\t__webpack_require__.r(ns);\n \t\tObject.defineProperty(ns, 'default', { enumerable: true, value: value });\n \t\tif(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));\n \t\treturn ns;\n \t};\n\n \t// getDefaultExport function for compatibility with non-harmony modules\n \t__webpack_require__.n = function(module) {\n \t\tvar getter = module && module.__esModule ?\n \t\t\tfunction getDefault() { return module['default']; } :\n \t\t\tfunction getModuleExports() { return module; };\n \t\t__webpack_require__.d(getter, 'a', getter);\n \t\treturn getter;\n \t};\n\n \t// Object.prototype.hasOwnProperty.call\n \t__webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };\n\n \t// __webpack_public_path__\n \t__webpack_require__.p = \"\";\n\n \t// on error function for async loading\n \t__webpack_require__.oe = function(err) { console.error(err); throw err; };\n\n \tvar jsonpArray = window[\"webpackJsonp\"] = window[\"webpackJsonp\"] || [];\n \tvar oldJsonpFunction = jsonpArray.push.bind(jsonpArray);\n \tjsonpArray.push = webpackJsonpCallback;\n \tjsonpArray = jsonpArray.slice();\n \tfor(var i = 0; i < jsonpArray.length; i++) webpackJsonpCallback(jsonpArray[i]);\n \tvar parentJsonpFunction = oldJsonpFunction;\n\n\n \t// Load entry module and return exports\n \treturn __webpack_require__(__webpack_require__.s = 105);\n","import { DEBUG, DEBUG_MORE } from '../../config';\nimport {\n fastRaf, onTickEnd, throttleWithPrimaryRaf, throttleWithRaf,\n} from '../../util/schedulers';\nimport { flatten, orderBy } from '../../util/iteratees';\nimport arePropsShallowEqual, { getUnequalProps } from '../../util/arePropsShallowEqual';\nimport { handleError } from '../../util/handleError';\nimport { removeAllDelegatedListeners } from './dom-events';\n\nexport type Props = AnyLiteral;\nexport type FC<P extends Props = any> = (props: P) => any;\nexport type FC_withDebug =\n FC\n & {\n DEBUG_contentComponentName?: string;\n};\n\nexport enum VirtualElementTypesEnum {\n Empty,\n Text,\n Tag,\n Component,\n}\n\ninterface VirtualElementEmpty {\n type: VirtualElementTypesEnum.Empty;\n target?: Node;\n}\n\ninterface VirtualElementText {\n type: VirtualElementTypesEnum.Text;\n target?: Node;\n value: string;\n}\n\nexport interface VirtualElementTag {\n type: VirtualElementTypesEnum.Tag;\n target?: Node;\n tag: string;\n props: Props;\n children: VirtualElementChildren;\n}\n\nexport interface VirtualElementComponent {\n type: VirtualElementTypesEnum.Component;\n componentInstance: ComponentInstance;\n props: Props;\n children: VirtualElementChildren;\n}\n\nexport type StateHookSetter<T> = (newValue: ((current: T) => T) | T) => void;\n\ninterface ComponentInstance {\n $element: VirtualElementComponent;\n Component: FC;\n name: string;\n props: Props;\n renderedValue?: any;\n isMounted: boolean;\n hooks: {\n state: {\n cursor: number;\n byCursor: {\n value: any;\n nextValue: any;\n setter: StateHookSetter<any>;\n }[];\n };\n effects: {\n cursor: number;\n byCursor: {\n effect: () => void;\n dependencies?: any[];\n cleanup?: Function;\n }[];\n };\n memos: {\n cursor: number;\n byCursor: {\n current: any;\n dependencies: any[];\n }[];\n };\n };\n prepareForFrame?: () => void;\n forceUpdate?: () => void;\n onUpdate?: () => void;\n}\n\nexport type VirtualElement =\n VirtualElementEmpty\n | VirtualElementText\n | VirtualElementTag\n | VirtualElementComponent;\nexport type VirtualRealElement =\n VirtualElementTag\n | VirtualElementComponent;\nexport type VirtualElementChildren = VirtualElement[];\n\nconst Fragment = Symbol('Fragment');\n\nlet renderingInstance: ComponentInstance;\n\nexport function isEmptyElement($element: VirtualElement): $element is VirtualElementEmpty {\n return $element.type === VirtualElementTypesEnum.Empty;\n}\n\nexport function isTextElement($element: VirtualElement): $element is VirtualElementText {\n return $element.type === VirtualElementTypesEnum.Text;\n}\n\nexport function isTagElement($element: VirtualElement): $element is VirtualElementTag {\n return $element.type === VirtualElementTypesEnum.Tag;\n}\n\nexport function isComponentElement($element: VirtualElement): $element is VirtualElementComponent {\n return $element.type === VirtualElementTypesEnum.Component;\n}\n\nexport function isRealElement($element: VirtualElement): $element is VirtualRealElement {\n return isTagElement($element) || isComponentElement($element);\n}\n\nfunction createElement(\n source: string | FC | typeof Fragment,\n props: Props,\n ...children: any[]\n): VirtualRealElement | VirtualElementChildren {\n if (!props) {\n props = {};\n }\n\n children = flatten(children);\n\n if (source === Fragment) {\n return children;\n } else if (typeof source === 'function') {\n return createComponentInstance(source, props, children);\n } else {\n return buildTagElement(source, props, children);\n }\n}\n\nfunction createComponentInstance(Component: FC, props: Props, children: any[]): VirtualElementComponent {\n let parsedChildren: any | any[] | undefined;\n if (children.length === 0) {\n parsedChildren = undefined;\n } else if (children.length === 1) {\n [parsedChildren] = children;\n } else {\n parsedChildren = children;\n }\n\n const componentInstance: ComponentInstance = {\n $element: {} as VirtualElementComponent,\n Component,\n name: Component.name,\n props: {\n ...props,\n ...(parsedChildren && { children: parsedChildren }),\n },\n isMounted: false,\n hooks: {\n state: {\n cursor: 0,\n byCursor: [],\n },\n effects: {\n cursor: 0,\n byCursor: [],\n },\n memos: {\n cursor: 0,\n byCursor: [],\n },\n },\n };\n\n componentInstance.$element = buildComponentElement(componentInstance);\n\n return componentInstance.$element;\n}\n\nfunction buildComponentElement(\n componentInstance: ComponentInstance,\n children: VirtualElementChildren = [],\n): VirtualElementComponent {\n const { props } = componentInstance;\n\n return {\n componentInstance,\n type: VirtualElementTypesEnum.Component,\n props,\n children,\n };\n}\n\nfunction buildTagElement(tag: string, props: Props, children: any[]): VirtualElementTag {\n return {\n type: VirtualElementTypesEnum.Tag,\n tag,\n props,\n children: dropEmptyTail(children).map(buildChildElement),\n };\n}\n\n// We only need placeholders in the middle of collection (to ensure other elements order).\nfunction dropEmptyTail(children: any[]) {\n let i = children.length - 1;\n\n for (; i >= 0; i--) {\n if (!isEmptyPlaceholder(children[i])) {\n break;\n }\n }\n\n return i + 1 < children.length ? children.slice(0, i + 1) : children;\n}\n\nfunction isEmptyPlaceholder(child: any) {\n // eslint-disable-next-line no-null/no-null\n return child === false || child === null || child === undefined;\n}\n\nfunction buildChildElement(child: any): VirtualElement {\n if (isEmptyPlaceholder(child)) {\n return buildEmptyElement();\n } else if (isRealElement(child)) {\n return child;\n } else {\n return buildTextElement(child);\n }\n}\n\nfunction buildTextElement(value: any): VirtualElementText {\n return {\n type: VirtualElementTypesEnum.Text,\n value: String(value),\n };\n}\n\nfunction buildEmptyElement(): VirtualElementEmpty {\n return { type: VirtualElementTypesEnum.Empty };\n}\n\nconst DEBUG_components: AnyLiteral = {};\n\ndocument.addEventListener('dblclick', () => {\n // eslint-disable-next-line no-console\n console.log('COMPONENTS', orderBy(Object.values(DEBUG_components), 'renderCount', 'desc'));\n});\n\nexport function renderComponent(componentInstance: ComponentInstance) {\n renderingInstance = componentInstance;\n componentInstance.hooks.state.cursor = 0;\n componentInstance.hooks.effects.cursor = 0;\n componentInstance.hooks.memos.cursor = 0;\n\n const { Component, props } = componentInstance;\n let newRenderedValue;\n\n try {\n let DEBUG_startAt: number | undefined;\n if (DEBUG) {\n const componentName = componentInstance.name;\n if (!DEBUG_components[componentName]) {\n DEBUG_components[componentName] = {\n componentName,\n renderCount: 0,\n renderTimes: [],\n };\n }\n\n if (DEBUG_MORE) {\n if (componentName !== 'TeactMemoWrapper' && componentName !== 'TeactNContainer') {\n // eslint-disable-next-line no-console\n console.log(`[Teact] Render ${componentName}`);\n }\n }\n\n DEBUG_startAt = performance.now();\n }\n\n newRenderedValue = Component(props);\n\n if (DEBUG) {\n const renderTime = performance.now() - DEBUG_startAt!;\n const componentName = componentInstance.name;\n if (renderTime > 7) {\n // eslint-disable-next-line no-console\n console.warn(`[Teact] Slow component render: ${componentName}, ${Math.round(renderTime)} ms`);\n }\n DEBUG_components[componentName].renderTimes.push(renderTime);\n DEBUG_components[componentName].renderCount++;\n }\n } catch (err) {\n handleError(err);\n\n newRenderedValue = componentInstance.renderedValue;\n }\n\n if (componentInstance.isMounted && newRenderedValue === componentInstance.renderedValue) {\n return componentInstance.$element;\n }\n\n componentInstance.renderedValue = newRenderedValue;\n\n const newChild = buildChildElement(newRenderedValue);\n componentInstance.$element = buildComponentElement(componentInstance, [newChild]);\n\n return componentInstance.$element;\n}\n\nexport function hasElementChanged($old: VirtualElement, $new: VirtualElement) {\n if (typeof $old !== typeof $new) {\n return true;\n } else if ($old.type !== $new.type) {\n return true;\n } else if (isTextElement($old) && isTextElement($new)) {\n return $old.value !== $new.value;\n } else if (isTagElement($old) && isTagElement($new)) {\n return ($old.tag !== $new.tag) || ($old.props.key !== $new.props.key);\n } else if (isComponentElement($old) && isComponentElement($new)) {\n return (\n $old.componentInstance.Component !== $new.componentInstance.Component\n ) || (\n $old.props.key !== $new.props.key\n );\n }\n\n return false;\n}\n\nexport function unmountTree($element: VirtualElement) {\n if (!isRealElement($element)) {\n return;\n }\n\n if (isComponentElement($element)) {\n unmountComponent($element.componentInstance);\n } else if ($element.target) {\n removeAllDelegatedListeners($element.target as HTMLElement);\n // Trying to help GC\n // eslint-disable-next-line no-null/no-null\n $element.target = null as any;\n }\n\n $element.children.forEach(unmountTree);\n}\n\nexport function mountComponent(componentInstance: ComponentInstance) {\n renderComponent(componentInstance);\n componentInstance.isMounted = true;\n return componentInstance.$element;\n}\n\nfunction unmountComponent(componentInstance: ComponentInstance) {\n if (!componentInstance.isMounted) {\n return;\n }\n\n componentInstance.hooks.memos.byCursor.forEach((hook) => {\n // eslint-disable-next-line no-null/no-null\n hook.current = null;\n });\n\n componentInstance.hooks.effects.byCursor.forEach(({ cleanup }) => {\n if (typeof cleanup === 'function') {\n try {\n cleanup();\n } catch (err) {\n handleError(err);\n }\n }\n });\n\n componentInstance.isMounted = false;\n\n helpGc(componentInstance);\n}\n\n// We need to remove all references to DOM objects. We also clean all other references, just in case.\nfunction helpGc(componentInstance: ComponentInstance) {\n /* eslint-disable no-null/no-null */\n\n componentInstance.hooks.effects.byCursor.forEach((hook) => {\n hook.cleanup = null as any;\n hook.effect = null as any;\n hook.dependencies = null as any;\n });\n\n componentInstance.hooks.state.byCursor.forEach((hook) => {\n hook.value = null as any;\n hook.nextValue = null as any;\n hook.setter = null as any;\n });\n\n componentInstance.hooks.memos.byCursor.forEach((hook) => {\n hook.dependencies = null as any;\n });\n\n componentInstance.hooks = null as any;\n componentInstance.$element = null as any;\n componentInstance.renderedValue = null as any;\n componentInstance.Component = null as any;\n componentInstance.props = null as any;\n componentInstance.forceUpdate = null as any;\n componentInstance.onUpdate = null as any;\n\n /* eslint-enable no-null/no-null */\n}\n\nfunction prepareComponentForFrame(componentInstance: ComponentInstance) {\n if (!componentInstance.isMounted) {\n return;\n }\n\n componentInstance.hooks.state.byCursor.forEach((hook) => {\n hook.value = hook.nextValue;\n });\n\n componentInstance.prepareForFrame = throttleWithPrimaryRaf(() => prepareComponentForFrame(componentInstance));\n componentInstance.forceUpdate = throttleWithRaf(() => forceUpdateComponent(componentInstance));\n}\n\nfunction forceUpdateComponent(componentInstance: ComponentInstance) {\n if (!componentInstance.isMounted || !componentInstance.onUpdate) {\n return;\n }\n\n const currentElement = componentInstance.$element;\n\n renderComponent(componentInstance);\n\n if (componentInstance.$element !== currentElement) {\n componentInstance.onUpdate();\n }\n}\n\nexport function getTarget($element: VirtualElement): Node | undefined {\n if (isComponentElement($element)) {\n return getTarget($element.children[0]);\n } else {\n return $element.target;\n }\n}\n\nexport function setTarget($element: VirtualElement, target: Node) {\n if (isComponentElement($element)) {\n setTarget($element.children[0], target);\n } else {\n $element.target = target;\n }\n}\n\nexport function useState<T>(initial?: T): [T, StateHookSetter<T>] {\n const { cursor, byCursor } = renderingInstance.hooks.state;\n\n if (byCursor[cursor] === undefined) {\n byCursor[cursor] = {\n value: initial,\n nextValue: initial,\n setter: ((componentInstance) => (newValue: ((current: T) => T) | T) => {\n if (byCursor[cursor].nextValue !== newValue) {\n byCursor[cursor].nextValue = typeof newValue === 'function'\n ? (newValue as (current: T) => T)(byCursor[cursor].value)\n : newValue;\n\n if (!componentInstance.prepareForFrame || !componentInstance.forceUpdate) {\n componentInstance.prepareForFrame = throttleWithPrimaryRaf(\n () => prepareComponentForFrame(componentInstance),\n );\n componentInstance.forceUpdate = throttleWithRaf(\n () => forceUpdateComponent(componentInstance),\n );\n }\n\n componentInstance.prepareForFrame();\n componentInstance.forceUpdate();\n\n if (DEBUG_MORE) {\n if (componentInstance.name !== 'TeactNContainer') {\n // eslint-disable-next-line no-console\n console.log(\n '[Teact.useState]',\n componentInstance.name,\n // `componentInstance.Component` may be set to `null` by GC helper\n componentInstance.Component && (componentInstance.Component as FC_withDebug).DEBUG_contentComponentName\n ? `> ${(componentInstance.Component as FC_withDebug).DEBUG_contentComponentName}`\n : '',\n `Forced update at cursor #${cursor}, next value: `,\n byCursor[cursor].nextValue,\n );\n }\n }\n }\n })(renderingInstance),\n };\n }\n\n renderingInstance.hooks.state.cursor++;\n\n return [\n byCursor[cursor].value,\n byCursor[cursor].setter,\n ];\n}\n\nfunction useLayoutEffectBase(\n schedulerFn: typeof onTickEnd | typeof requestAnimationFrame,\n effect: () => Function | void,\n dependencies?: any[],\n debugKey?: string,\n) {\n const { cursor, byCursor } = renderingInstance.hooks.effects;\n const componentInstance = renderingInstance;\n\n const exec = () => {\n if (!componentInstance.isMounted) {\n return;\n }\n\n const { cleanup } = byCursor[cursor];\n if (typeof cleanup === 'function') {\n try {\n cleanup();\n } catch (err) {\n handleError(err);\n }\n }\n\n byCursor[cursor].cleanup = effect() as Function;\n };\n\n if (byCursor[cursor] !== undefined && dependencies && byCursor[cursor].dependencies) {\n if (dependencies.some((dependency, i) => dependency !== byCursor[cursor].dependencies![i])) {\n if (debugKey) {\n const causedBy = dependencies.reduce((res, newValue, i) => {\n const prevValue = byCursor[cursor].dependencies![i];\n if (newValue !== prevValue) {\n res.push(`${i}: ${prevValue} => ${newValue}`);\n }\n\n return res;\n }, []);\n\n // eslint-disable-next-line no-console\n console.log(\n '[Teact]',\n debugKey,\n 'Effect caused by dependencies.',\n causedBy.join(', '),\n );\n }\n\n schedulerFn(exec);\n }\n } else {\n schedulerFn(exec);\n }\n\n byCursor[cursor] = {\n effect,\n dependencies,\n cleanup: byCursor[cursor] ? byCursor[cursor].cleanup : undefined,\n };\n\n renderingInstance.hooks.effects.cursor++;\n}\n\nexport function useEffect(effect: () => Function | void, dependencies?: any[], debugKey?: string) {\n return useLayoutEffectBase(fastRaf, effect, dependencies, debugKey);\n}\n\nexport function useLayoutEffect(effect: () => Function | void, dependencies?: any[], debugKey?: string) {\n return useLayoutEffectBase(onTickEnd, effect, dependencies, debugKey);\n}\n\nexport function useMemo<T extends any>(resolver: () => T, dependencies: any[], debugKey?: string): T {\n const { cursor, byCursor } = renderingInstance.hooks.memos;\n let { current } = byCursor[cursor] || {};\n\n if (\n byCursor[cursor] === undefined\n || dependencies.some((dependency, i) => dependency !== byCursor[cursor].dependencies[i])\n ) {\n if (DEBUG && debugKey) {\n // eslint-disable-next-line no-console\n console.log(\n `[Teact.useMemo] ${renderingInstance.name} (${debugKey}): Update is caused by:`,\n byCursor[cursor]\n ? getUnequalProps(dependencies, byCursor[cursor].dependencies).join(', ')\n : '[first render]',\n );\n }\n\n current = resolver();\n }\n\n byCursor[cursor] = {\n current,\n dependencies,\n };\n\n renderingInstance.hooks.memos.cursor++;\n\n return current;\n}\n\nexport function useCallback<F extends AnyFunction>(newCallback: F, dependencies: any[]): F {\n // eslint-disable-next-line react-hooks/exhaustive-deps\n return useMemo(() => newCallback, dependencies);\n}\n\nexport function useRef<T>(initial: T): { current: T };\nexport function useRef<T>(): { current: T | undefined }; // TT way (empty is `undefined`)\nexport function useRef<T>(initial: null): { current: T | null }; // React way (empty is `null`)\n// eslint-disable-next-line no-null/no-null\nexport function useRef<T>(initial?: T | null) {\n return useMemo(() => ({\n current: initial,\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }), []);\n}\n\nexport function memo<T extends FC>(Component: T, areEqual = arePropsShallowEqual, debugKey?: string) {\n return function TeactMemoWrapper(props: Props) {\n // eslint-disable-next-line react-hooks/rules-of-hooks\n const propsRef = useRef(props);\n const renderedRef = useRef();\n\n if (!renderedRef.current || (propsRef.current && !areEqual(propsRef.current, props))) {\n if (DEBUG && debugKey) {\n // eslint-disable-next-line no-console\n console.log(\n `[Teact.memo] ${Component.name} (${debugKey}): Update is caused by:`,\n getUnequalProps(propsRef.current!, props).join(', '),\n );\n }\n\n propsRef.current = props;\n renderedRef.current = createElement(Component, props) as VirtualElementComponent;\n }\n\n return renderedRef.current;\n } as T;\n}\n\n// We need to keep it here for JSX.\nexport default {\n createElement,\n Fragment,\n};\n","import React, {\n FC, FC_withDebug, Props, useEffect, useState,\n} from './teact';\n\nimport { DEBUG, DEBUG_MORE } from '../../config';\nimport useForceUpdate from '../../hooks/useForceUpdate';\nimport generateIdFor from '../../util/generateIdFor';\nimport { throttleWithRaf } from '../../util/schedulers';\nimport arePropsShallowEqual, { getUnequalProps } from '../../util/arePropsShallowEqual';\nimport { orderBy } from '../../util/iteratees';\nimport { GlobalState, GlobalActions, ActionTypes } from '../../global/types';\nimport { handleError } from '../../util/handleError';\n\nexport default React;\n\ntype ActionPayload = AnyLiteral;\n\ntype Reducer = (\n global: GlobalState,\n actions: GlobalActions,\n payload: any,\n) => GlobalState | void;\n\ntype MapStateToProps<OwnProps = undefined> = ((global: GlobalState, ownProps: OwnProps) => AnyLiteral | null);\ntype MapActionsToProps = ((setGlobal: Function, actions: GlobalActions) => Partial<GlobalActions> | null);\n\nlet currentGlobal = {} as GlobalState;\n\nconst reducers: Record<string, Reducer[]> = {};\nconst callbacks: Function[] = [updateContainers];\nconst actions = {} as GlobalActions;\nconst containers = new Map<string, {\n mapStateToProps: MapStateToProps<any>;\n mapReducersToProps: MapActionsToProps;\n ownProps: Props;\n mappedProps?: Props;\n forceUpdate: Function;\n areMappedPropsChanged: boolean;\n DEBUG_updates: number;\n DEBUG_componentName: string;\n}>();\n\nfunction runCallbacks() {\n callbacks.forEach((cb) => cb(currentGlobal));\n}\n\nconst runCallbacksThrottled = throttleWithRaf(runCallbacks);\n\n// `noThrottle = true` is used as a workaround for iOS gesture history navigation\nexport function setGlobal(newGlobal?: GlobalState, noThrottle = false) {\n if (typeof newGlobal === 'object' && newGlobal !== currentGlobal) {\n currentGlobal = newGlobal;\n if (!noThrottle) {\n runCallbacksThrottled();\n } else {\n runCallbacks();\n }\n }\n}\n\nexport function getGlobal() {\n return currentGlobal;\n}\n\nexport function getDispatch() {\n return actions;\n}\n\nfunction onDispatch(name: string, payload?: ActionPayload, noThrottle?: boolean) {\n if (reducers[name]) {\n reducers[name].forEach((reducer) => {\n const newGlobal = reducer(currentGlobal, actions, payload);\n if (newGlobal) {\n setGlobal(newGlobal, noThrottle);\n }\n });\n }\n}\n\nfunction updateContainers() {\n let DEBUG_startAt: number | undefined;\n if (DEBUG) {\n DEBUG_startAt = performance.now();\n }\n\n // eslint-disable-next-line no-restricted-syntax\n for (const container of containers.values()) {\n const {\n mapStateToProps, mapReducersToProps, ownProps, mappedProps, forceUpdate,\n } = container;\n\n let newMappedProps;\n\n try {\n newMappedProps = {\n ...mapStateToProps(currentGlobal, ownProps),\n ...mapReducersToProps(setGlobal, actions),\n };\n } catch (err) {\n handleError(err);\n\n return;\n }\n\n if (DEBUG) {\n if (Object.values(newMappedProps).some(Number.isNaN)) {\n // eslint-disable-next-line no-console\n console.warn(\n // eslint-disable-next-line max-len\n `[TeactN] Some of \\`${container.DEBUG_componentName}\\` mappers contain NaN values. This may cause redundant updates because of incorrect equality check.`,\n );\n }\n }\n\n if (Object.keys(newMappedProps).length && !arePropsShallowEqual(mappedProps!, newMappedProps)) {\n if (DEBUG_MORE) {\n // eslint-disable-next-line no-console\n console.log(\n '[TeactN] Will update',\n container.DEBUG_componentName,\n 'caused by',\n getUnequalProps(mappedProps!, newMappedProps).join(', '),\n );\n }\n\n container.mappedProps = newMappedProps;\n container.areMappedPropsChanged = true;\n container.DEBUG_updates++;\n\n forceUpdate();\n }\n }\n\n if (DEBUG) {\n const updateTime = performance.now() - DEBUG_startAt!;\n if (updateTime > 7) {\n // eslint-disable-next-line no-console\n console.warn(`[TeactN] Slow containers update: ${Math.round(updateTime)} ms`);\n }\n }\n}\n\nexport function addReducer(name: ActionTypes, reducer: Reducer) {\n if (!reducers[name]) {\n reducers[name] = [];\n\n actions[name] = (payload?: ActionPayload, noThrottle = false) => {\n onDispatch(name, payload, noThrottle);\n };\n }\n\n reducers[name].push(reducer);\n}\n\nexport function addCallback(cb: Function) {\n callbacks.push(cb);\n}\n\nexport function removeCallback(cb: Function) {\n const index = callbacks.indexOf(cb);\n if (index !== -1) {\n callbacks.splice(index, 1);\n }\n}\n\nexport function withGlobal<OwnProps>(\n mapStateToProps: MapStateToProps<OwnProps> = () => ({}),\n mapReducersToProps: MapActionsToProps = () => ({}),\n) {\n return (Component: FC) => {\n return function TeactNContainer(props: OwnProps) {\n (TeactNContainer as FC_withDebug).DEBUG_contentComponentName = Component.name;\n\n const [id] = useState(generateIdFor(containers));\n const forceUpdate = useForceUpdate();\n\n useEffect(() => {\n return () => {\n containers.delete(id);\n };\n }, [id]);\n\n let container = containers.get(id);\n if (!container) {\n container = {\n mapStateToProps,\n mapReducersToProps,\n ownProps: props,\n areMappedPropsChanged: false,\n forceUpdate,\n DEBUG_updates: 0,\n DEBUG_componentName: Component.name,\n };\n\n containers.set(id, container);\n }\n\n if (container.areMappedPropsChanged) {\n container.areMappedPropsChanged = false;\n }\n\n if (!container.mappedProps || !arePropsShallowEqual(container.ownProps, props)) {\n container.ownProps = props;\n\n try {\n container.mappedProps = {\n ...mapStateToProps(currentGlobal, props),\n ...mapReducersToProps(setGlobal, actions),\n };\n } catch (err) {\n handleError(err);\n }\n }\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return <Component {...container.mappedProps} {...props} />;\n };\n };\n}\n\nif (DEBUG) {\n (window as any).getGlobal = getGlobal;\n\n document.addEventListener('dblclick', () => {\n // eslint-disable-next-line no-console\n console.log(\n 'GLOBAL CONTAINERS',\n orderBy(\n Array.from(containers.values())\n .map(({ DEBUG_componentName, DEBUG_updates }) => ({ DEBUG_componentName, DEBUG_updates })),\n 'DEBUG_updates',\n 'desc',\n ),\n );\n });\n}\n","export const PAGE_TITLE = 'Telegram';\nexport const INACTIVE_MARKER = ' [Inactive]';\n\nexport const APP_NAME = process.env.APP_NAME || 'Telegram WebZ';\nexport const APP_VERSION = process.env.APP_VERSION || 'dev';\n\nexport const DEBUG = (\n process.env.APP_ENV !== 'production' && process.env.APP_ENV !== 'perf' && process.env.APP_ENV !== 'test'\n);\nexport const DEBUG_MORE = false;\n\nexport const IS_TEST = process.env.APP_ENV === 'test';\nexport const IS_PERF = process.env.APP_ENV === 'perf';\n\nexport const DEBUG_ALERT_MSG = 'Shoot!\\nSomething went wrong, please see the error details in Dev Tools Console.';\nexport const DEBUG_GRAMJS = false;\n\nexport const SESSION_USER_KEY = 'user_auth';\nexport const LEGACY_SESSION_KEY = 'GramJs:sessionId';\n\nexport const GLOBAL_STATE_CACHE_DISABLED = false;\nexport const GLOBAL_STATE_CACHE_KEY = 'tt-global-state';\nexport const GLOBAL_STATE_CACHE_CHAT_LIST_LIMIT = 30;\nexport const GLOBAL_STATE_CACHE_USER_LIST_LIMIT = 5000;\n\nexport const MEDIA_CACHE_DISABLED = false;\nexport const MEDIA_CACHE_NAME = 'tt-media';\nexport const MEDIA_CACHE_NAME_AVATARS = 'tt-media-avatars';\nexport const MEDIA_PROGRESSIVE_CACHE_DISABLED = false;\nexport const MEDIA_PROGRESSIVE_CACHE_NAME = 'tt-media-progressive';\nexport const MEDIA_CACHE_MAX_BYTES = 512 * 1024; // 512 KB\nexport const CUSTOM_BG_CACHE_NAME = 'tt-custom-bg';\nexport const LANG_CACHE_NAME = 'tt-lang-packs-v5';\nexport const ASSET_CACHE_NAME = 'tt-assets';\nexport const TRANSPARENT_PIXEL = 'data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==';\n\nexport const DOWNLOAD_WORKERS = 16;\nexport const UPLOAD_WORKERS = 16;\n\nconst isBigScreen = typeof window !== 'undefined' && window.innerHeight >= 900;\n\nexport const MIN_PASSWORD_LENGTH = 1;\n\nexport const MESSAGE_LIST_SENSITIVE_AREA = 750;\nexport const MESSAGE_LIST_SLICE = isBigScreen ? 60 : 40;\nexport const MESSAGE_LIST_VIEWPORT_LIMIT = MESSAGE_LIST_SLICE * 2;\n\nexport const CHAT_HEIGHT_PX = 72;\nexport const CHAT_LIST_SLICE = isBigScreen ? 30 : 25;\nexport const CHAT_LIST_LOAD_SLICE = 100;\nexport const SHARED_MEDIA_SLICE = 42;\nexport const MESSAGE_SEARCH_SLICE = 42;\nexport const GLOBAL_SEARCH_SLICE = 20;\nexport const MEMBERS_SLICE = 30;\nexport const MEMBERS_LOAD_SLICE = 200;\nexport const PINNED_MESSAGES_LIMIT = 50;\nexport const BLOCKED_LIST_LIMIT = 100;\nexport const PROFILE_PHOTOS_LIMIT = 40;\nexport const PROFILE_SENSITIVE_AREA = 500;\n\nexport const TOP_CHAT_MESSAGES_PRELOAD_LIMIT = 20;\nexport const ALL_CHATS_PRELOAD_DISABLED = false;\n\nexport const ANIMATION_LEVEL_MIN = 0;\nexport const ANIMATION_LEVEL_MED = 1;\nexport const ANIMATION_LEVEL_MAX = 2;\nexport const ANIMATION_LEVEL_DEFAULT = ANIMATION_LEVEL_MAX;\n\nexport const DEFAULT_MESSAGE_TEXT_SIZE_PX = 16;\nexport const IOS_DEFAULT_MESSAGE_TEXT_SIZE_PX = 17;\nexport const MACOS_DEFAULT_MESSAGE_TEXT_SIZE_PX = 15;\n\nexport const DRAFT_DEBOUNCE = 10000; // 10s\n\nexport const EDITABLE_INPUT_ID = 'editable-message-text';\nexport const EDITABLE_INPUT_MODAL_ID = 'editable-message-text-modal';\n\n// Screen width where Pinned Message / Audio Player in the Middle Header can be safely displayed\nexport const SAFE_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN = 1440; // px\n// Screen width where Pinned Message / Audio Player in the Middle Header shouldn't collapse with ChatInfo\nexport const SAFE_SCREEN_WIDTH_FOR_CHAT_INFO = 1150; // px\n\nexport const MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN = 1275; // px\nexport const MIN_SCREEN_WIDTH_FOR_STATIC_LEFT_COLUMN = 925; // px\nexport const MOBILE_SCREEN_MAX_WIDTH = 600; // px\nexport const MOBILE_SCREEN_LANDSCAPE_MAX_WIDTH = 950; // px\nexport const MOBILE_SCREEN_LANDSCAPE_MAX_HEIGHT = 450; // px\n\nexport const LOCAL_MESSAGE_ID_BASE = 1e9;\n\nexport const ANIMATION_END_DELAY = 100;\n\nexport const FAST_SMOOTH_MAX_DISTANCE = 1500;\nexport const FAST_SMOOTH_MIN_DURATION = 250;\nexport const FAST_SMOOTH_MAX_DURATION = 600;\nexport const FAST_SMOOTH_SHORT_TRANSITION_MAX_DISTANCE = 500; // px\n\n// Average duration of message sending animation\nexport const API_UPDATE_THROTTLE = Math.round((FAST_SMOOTH_MIN_DURATION + FAST_SMOOTH_MAX_DURATION) / 2);\nexport const API_THROTTLE_RESET_UPDATES = new Set([\n 'newMessage', 'newScheduledMessage', 'deleteMessages', 'deleteScheduledMessages', 'deleteHistory',\n]);\n\nexport const STICKER_SIZE_INLINE_DESKTOP_FACTOR = 13;\nexport const STICKER_SIZE_INLINE_MOBILE_FACTOR = 11;\nexport const STICKER_SIZE_AUTH = 160;\nexport const STICKER_SIZE_AUTH_MOBILE = 120;\nexport const STICKER_SIZE_PICKER = 64;\nexport const STICKER_SIZE_GENERAL_SETTINGS = 48;\nexport const STICKER_SIZE_PICKER_HEADER = 32;\nexport const STICKER_SIZE_SEARCH = 64;\nexport const STICKER_SIZE_MODAL = 64;\nexport const STICKER_SIZE_TWO_FA = 160;\nexport const STICKER_SIZE_DISCUSSION_GROUPS = 140;\nexport const STICKER_SIZE_FOLDER_SETTINGS = 80;\nexport const STICKER_SIZE_INLINE_BOT_RESULT = 100;\nexport const RECENT_STICKERS_LIMIT = 20;\nexport const MEMOJI_STICKER_ID = 'MEMOJI_STICKER';\n\nexport const BASE_EMOJI_KEYWORD_LANG = 'en';\n\nexport const MENU_TRANSITION_DURATION = 200;\nexport const SLIDE_TRANSITION_DURATION = 450;\n\nexport const CONTENT_TYPES_FOR_QUICK_UPLOAD = new Set([\n 'image/png', 'image/gif', 'image/jpeg', 'video/mp4', 'video/avi', 'video/quicktime',\n]);\n\n// eslint-disable-next-line max-len\nexport const RE_LINK_TEMPLATE = '((ftp|https?):\\\\/\\\\/)?((www\\\\.)?[-a-zA-Z0-9@:%._+~#=]{1,256}\\\\.[a-zA-Z0-9()]{1,63})\\\\b([-a-zA-Z0-9()@:%_+.~#?&/=]*)';\nexport const RE_MENTION_TEMPLATE = '(@[\\\\w\\\\d_-]+)';\nexport const RE_TME_LINK = /^(?:https?:\\/\\/)?(?:t\\.me\\/)([\\d\\w_]+)(?:\\/([\\d]+))?(?:\\/([\\d]+))?$/gm;\nexport const RE_TME_INVITE_LINK = /^(?:https?:\\/\\/)?(?:t\\.me\\/joinchat\\/)([\\d\\w_-]+)?$/gm;\n\n// MTProto constants\nexport const SERVICE_NOTIFICATIONS_USER_ID = 777000;\nexport const ALL_FOLDER_ID = 0;\nexport const ARCHIVED_FOLDER_ID = 1;\nexport const DELETED_COMMENTS_CHANNEL_ID = 777;\nexport const MAX_MEDIA_FILES_FOR_ALBUM = 10;\nexport const MAX_ACTIVE_PINNED_CHATS = 5;\nexport const SCHEDULED_WHEN_ONLINE = 0x7FFFFFFE;\nexport const DEFAULT_LANG_CODE = 'en';\nexport const DEFAULT_LANG_PACK = 'android';\nexport const LANG_PACKS = ['android', 'ios', 'tdesktop', 'macos'] as const;\nexport const TIPS_USERNAME = 'TelegramTips';\nexport const LOCALIZED_TIPS = ['ar', 'pt-br', 'id', 'it', 'ko', 'ms', 'pl', 'es', 'tr'];\nexport const FEEDBACK_URL = 'https://bugs.telegram.org/?tag_ids=41&sort=time';\nexport const LIGHT_THEME_BG_COLOR = '#A2AF8E';\nexport const DARK_THEME_BG_COLOR = '#0F0F0F';\nexport const DARK_THEME_PATTERN_COLOR = '#0a0a0a8c';\nexport const DEFAULT_PATTERN_COLOR = 'rgba(90, 110, 70, 0.6)';\n","type CollectionByKey<Member> = Record<number | string, Member>;\n\ntype OrderDirection = 'asc' | 'desc';\n\ninterface OrderCallback<T> {\n (member: T): any;\n}\n\nexport function buildCollectionByKey<T extends AnyLiteral>(collection: T[], key: keyof T) {\n return collection.reduce((byKey: CollectionByKey<T>, member: T) => {\n byKey[member[key]] = member;\n\n return byKey;\n }, {});\n}\n\nexport function mapValues<R extends any, M extends any>(\n byKey: CollectionByKey<M>,\n callback: (member: M, key: string, index: number, originalByKey: CollectionByKey<M>) => R,\n): CollectionByKey<R> {\n return Object.keys(byKey).reduce((newByKey: CollectionByKey<R>, key, index) => {\n newByKey[key] = callback(byKey[key], key, index, byKey);\n return newByKey;\n }, {});\n}\n\nexport function pick<T, K extends keyof T>(object: T, keys: K[]) {\n return keys.reduce((result, key) => {\n result[key] = object[key];\n return result;\n }, {} as Pick<T, K>);\n}\n\nexport function pickTruthy<T, K extends keyof T>(object: T, keys: K[]) {\n return keys.reduce((result, key) => {\n if (object[key]) {\n result[key] = object[key];\n }\n\n return result;\n }, {} as Pick<T, K>);\n}\n\nexport function omit<T, K extends keyof T>(object: T, keys: K[]) {\n const stringKeys = new Set(keys.map(String));\n const savedKeys = Object.keys(object)\n .filter((key) => !stringKeys.has(key)) as Array<Exclude<keyof T, K>>;\n\n return pick(object, savedKeys);\n}\n\nexport function orderBy<T>(\n collection: T[],\n orderKey: (keyof T) | OrderCallback<T> | ((keyof T) | OrderCallback<T>)[],\n mode: OrderDirection | [OrderDirection, OrderDirection] = 'asc',\n): T[] {\n return collection.sort((a, b) => {\n if (Array.isArray(orderKey)) {\n const [mode1, mode2] = Array.isArray(mode) ? mode : [mode, mode];\n const [orderKey1, orderKey2] = orderKey;\n\n let aValue1;\n let bValue1;\n\n if (typeof orderKey1 === 'function') {\n aValue1 = orderKey1(a) || 0;\n bValue1 = orderKey1(b) || 0;\n } else if (typeof orderKey1 === 'string') {\n aValue1 = a[orderKey1] || 0;\n bValue1 = b[orderKey1] || 0;\n }\n\n if (aValue1 !== bValue1) {\n return mode1 === 'asc' ? aValue1 - bValue1 : bValue1 - aValue1;\n } else {\n let aValue2;\n let bValue2;\n\n if (typeof orderKey2 === 'function') {\n aValue2 = orderKey2(a) || 0;\n bValue2 = orderKey2(b) || 0;\n } else if (typeof orderKey2 === 'string') {\n aValue2 = a[orderKey2] || 0;\n bValue2 = b[orderKey2] || 0;\n }\n\n return mode2 === 'asc' ? aValue2 - bValue2 : bValue2 - aValue2;\n }\n }\n\n let aValue;\n let bValue;\n\n if (typeof orderKey === 'function') {\n aValue = orderKey(a) || 0;\n bValue = orderKey(b) || 0;\n } else if (typeof orderKey === 'string') {\n aValue = a[orderKey] || 0;\n bValue = b[orderKey] || 0;\n }\n\n return mode === 'asc' ? aValue - bValue : bValue - aValue;\n });\n}\n\nexport function flatten(array: any[]) {\n return array.reduce((result, member) => {\n if (Array.isArray(member)) {\n return result.concat(member);\n } else {\n result.push(member);\n return result;\n }\n }, []);\n}\n\nexport function unique<T extends any>(array: T[]): T[] {\n return Array.from(new Set(array));\n}\n\nexport function compact(array: any[]) {\n return array.filter(Boolean);\n}\n\nexport function areSortedArraysEqual(array1: any[], array2: any[]) {\n if (array1.length !== array2.length) {\n return false;\n }\n\n return array1.every((item, i) => item === array2[i]);\n}\n\nexport function areSortedArraysIntersecting(array1: any[], array2: any[]) {\n return array1[0] <= array2[array2.length - 1] && array1[array1.length - 1] >= array2[0];\n}\n\nexport function findIntersectionWithSet<T>(array: T[], set: Set<T>): T[] {\n return array.filter((a) => set.has(a));\n}\n\nexport function split(array: any[], chunkSize: number) {\n const result = [];\n for (let i = 0; i < array.length; i += chunkSize) {\n result.push(array.slice(i, i + chunkSize));\n }\n\n return result;\n}\n\nexport function cloneDeep<T>(value: T): T {\n if (typeof value !== 'object') {\n return value;\n }\n\n if (Array.isArray(value)) {\n return value.map(cloneDeep) as typeof value;\n }\n\n return Object.keys(value).reduce((acc, key) => {\n acc[key as keyof T] = cloneDeep(value[key as keyof T]);\n return acc;\n }, {} as T);\n}\n\n/**\n * Returns the index of the last element in the array where predicate is true, and -1 otherwise.\n *\n * @param array The source array to search in\n * @param predicate find calls predicate once for each element of the array, in descending\n * order, until it finds one where predicate returns true. If such an element is found,\n * findLastIndex immediately returns that element index. Otherwise, findLastIndex returns -1.\n */\nexport function findLast<T>(array: Array<T>, predicate: (value: T, index: number, obj: T[]) => boolean): T | undefined {\n let cursor = array.length;\n\n while (cursor--) {\n if (predicate(array[cursor], cursor, array)) {\n return array[cursor];\n }\n }\n\n return undefined;\n}\n","import {\n ApiChat, ApiMessage, ApiMessageEntityTypes, ApiUser,\n} from '../../api/types';\nimport { LangFn } from '../../hooks/useLang';\n\nimport { LOCAL_MESSAGE_ID_BASE, SERVICE_NOTIFICATIONS_USER_ID, RE_LINK_TEMPLATE } from '../../config';\nimport parseEmojiOnlyString from '../../components/common/helpers/parseEmojiOnlyString';\nimport { getUserFullName } from './users';\nimport { getChatTitle } from './chats';\n\nconst CONTENT_NOT_SUPPORTED = 'The message is not supported on this version of Telegram';\nconst RE_LINK = new RegExp(RE_LINK_TEMPLATE, 'i');\nconst TRUNCATED_SUMMARY_LENGTH = 80;\n\nexport function getMessageKey(message: ApiMessage) {\n const { chatId, id } = message;\n\n return `msg${chatId}-${id}`;\n}\n\nexport function parseMessageKey(key: string) {\n const match = key.match(/^msg(-?\\d+)-(\\d+)/)!;\n\n return { chatId: Number(match[1]), messageId: Number(match[2]) };\n}\n\nexport function getMessageOriginalId(message: ApiMessage) {\n return message.previousLocalId || message.id;\n}\n\nexport function getMessageSummaryText(lang: LangFn, message: ApiMessage, noEmoji = false) {\n const {\n text, photo, video, audio, voice, document, sticker, contact, poll, invoice,\n } = message.content;\n\n const truncatedText = text && text.text.substr(0, TRUNCATED_SUMMARY_LENGTH);\n\n if (message.groupedId) {\n return `${noEmoji ? '' : '🖼 '}${truncatedText || lang('lng_in_dlg_album')}`;\n }\n\n if (photo) {\n return `${noEmoji ? '' : '🖼 '}${truncatedText || lang('AttachPhoto')}`;\n }\n\n if (video) {\n return `${noEmoji ? '' : '📹 '}${truncatedText || lang(video.isGif ? 'AttachGif' : 'AttachVideo')}`;\n }\n\n if (sticker) {\n return `${sticker.emoji || ''} ${lang('AttachSticker')}`.trim();\n }\n\n if (audio) {\n return `${noEmoji ? '' : '🎧 '}${getMessageAudioCaption(message) || lang('AttachMusic')}`;\n }\n\n if (voice) {\n return `${noEmoji ? '' : '🎤 '}${truncatedText || lang('AttachAudio')}`;\n }\n\n if (document) {\n return `${noEmoji ? '' : '📎 '}${truncatedText || document.fileName}`;\n }\n\n if (contact) {\n return lang('AttachContact');\n }\n\n if (poll) {\n return `${noEmoji ? '' : '📊 '}${poll.summary.question}`;\n }\n\n if (invoice) {\n return 'Invoice';\n }\n\n if (text) {\n return truncatedText;\n }\n\n return CONTENT_NOT_SUPPORTED;\n}\n\nexport function getMessageText(message: ApiMessage) {\n const {\n text, sticker, photo, video, audio, voice, document, poll, webPage, contact, invoice,\n } = message.content;\n\n if (text) {\n return text.text;\n }\n\n if (sticker || photo || video || audio || voice || document || contact || poll || webPage || invoice) {\n return undefined;\n }\n\n return CONTENT_NOT_SUPPORTED;\n}\n\nexport function getMessageCustomShape(message: ApiMessage): boolean | number {\n const {\n text, sticker, photo, video, audio, voice, document, poll, webPage, contact,\n } = message.content;\n\n if (sticker || (video && video.isRound)) {\n return true;\n }\n\n if (!text || photo || video || audio || voice || document || poll || webPage || contact) {\n return false;\n }\n\n // This is a \"dual-intent\" method used to limit calls of `parseEmojiOnlyString`.\n return parseEmojiOnlyString(text.text) || false;\n}\n\nexport function getMessageSingleEmoji(message: ApiMessage) {\n const { text } = message.content;\n if (!(text && text.text.length <= 6)) {\n return undefined;\n }\n\n if (getMessageCustomShape(message) !== 1) {\n return undefined;\n }\n\n return text.text;\n}\n\nexport function getFirstLinkInMessage(message: ApiMessage) {\n const { text } = message.content;\n\n let match: RegExpMatchArray | null | undefined;\n if (text && text.entities) {\n let link = text.entities.find((entity) => entity.type === ApiMessageEntityTypes.TextUrl);\n if (link) {\n match = link.url!.match(RE_LINK);\n }\n\n if (!match) {\n link = text.entities.find((entity) => entity.type === ApiMessageEntityTypes.Url);\n if (link) {\n const { offset, length } = link;\n match = text.text.substring(offset, offset + length).match(RE_LINK);\n }\n }\n }\n\n if (!match && text) {\n match = text.text.match(RE_LINK);\n }\n\n if (!match) {\n return undefined;\n }\n\n return {\n url: match[0],\n domain: match[3],\n };\n}\n\nexport function matchLinkInMessageText(message: ApiMessage) {\n const { text } = message.content;\n const match = text && text.text.match(RE_LINK);\n\n if (!match) {\n return undefined;\n }\n\n return {\n url: match[0],\n domain: match[3],\n };\n}\n\nexport function isOwnMessage(message: ApiMessage) {\n return message.isOutgoing;\n}\n\nexport function isReplyMessage(message: ApiMessage) {\n return Boolean(message.replyToMessageId);\n}\n\nexport function isForwardedMessage(message: ApiMessage) {\n return Boolean(message.forwardInfo);\n}\n\nexport function isActionMessage(message: ApiMessage) {\n return !!message.content.action;\n}\n\nexport function isServiceNotificationMessage(message: ApiMessage) {\n return message.chatId === SERVICE_NOTIFICATIONS_USER_ID && isMessageLocal(message);\n}\n\nexport function isAnonymousOwnMessage(message: ApiMessage) {\n return Boolean(message.senderId) && message.senderId! < 0 && isOwnMessage(message);\n}\n\nexport function getSenderTitle(lang: LangFn, sender: ApiUser | ApiChat) {\n return sender.id > 0 ? getUserFullName(sender as ApiUser) : getChatTitle(lang, sender as ApiChat);\n}\n\nexport function getSendingState(message: ApiMessage) {\n if (!message.sendingState) {\n return 'succeeded';\n }\n\n return message.sendingState === 'messageSendingStateFailed' ? 'failed' : 'pending';\n}\n\nexport function isMessageLocal(message: ApiMessage) {\n return message.id >= LOCAL_MESSAGE_ID_BASE;\n}\n\nexport function isHistoryClearMessage(message: ApiMessage) {\n return message.content.action && message.content.action.type === 'historyClear';\n}\n\nexport function getMessageAudioCaption(message: ApiMessage) {\n const { audio, text } = message.content;\n\n return (audio && [audio.title, audio.performer].filter(Boolean).join(' — ')) || (text && text.text);\n}\n","import {\n ApiAudio, ApiMediaFormat, ApiMessage, ApiMessageSearchType, ApiPhoto, ApiVideo, ApiDimensions,\n} from '../../api/types';\n\nimport { IS_OPUS_SUPPORTED, IS_PROGRESSIVE_SUPPORTED, IS_SAFARI } from '../../util/environment';\nimport { getMessageKey, isMessageLocal, matchLinkInMessageText } from './messages';\nimport { getDocumentHasPreview } from '../../components/common/helpers/documentInfo';\n\ntype Target =\n 'micro'\n | 'pictogram'\n | 'inline'\n | 'viewerPreview'\n | 'viewerFull'\n | 'download';\n\n\nexport function getMessageContent(message: ApiMessage) {\n return message.content;\n}\n\nexport function hasMessageMedia(message: ApiMessage) {\n return Boolean((\n getMessagePhoto(message)\n || getMessageVideo(message)\n || getMessageDocument(message)\n || getMessageSticker(message)\n || getMessageContact(message)\n || getMessagePoll(message)\n || getMessageAction(message)\n || getMessageAudio(message)\n || getMessageVoice(message)\n ));\n}\n\nexport function getMessagePhoto(message: ApiMessage) {\n return message.content.photo;\n}\n\nexport function getMessageVideo(message: ApiMessage) {\n return message.content.video;\n}\n\nexport function getMessageRoundVideo(message: ApiMessage) {\n const { video } = message.content;\n\n return video && video.isRound ? video : undefined;\n}\n\nexport function getMessageAction(message: ApiMessage) {\n return message.content.action;\n}\n\nexport function getMessageAudio(message: ApiMessage) {\n return message.content.audio;\n}\n\nexport function getMessageVoice(message: ApiMessage) {\n return message.content.voice;\n}\n\nexport function getMessageSticker(message: ApiMessage) {\n return message.content.sticker;\n}\n\nexport function getMessageDocument(message: ApiMessage) {\n return message.content.document;\n}\n\nexport function isMessageDocumentPhoto(message: ApiMessage) {\n const document = getMessageDocument(message);\n return document ? document.mediaType === 'photo' : undefined;\n}\n\nexport function isMessageDocumentVideo(message: ApiMessage) {\n const document = getMessageDocument(message);\n return document ? document.mediaType === 'video' : undefined;\n}\n\nexport function getMessageContact(message: ApiMessage) {\n return message.content.contact;\n}\n\nexport function getMessagePoll(message: ApiMessage) {\n return message.content.poll;\n}\n\nexport function getMessageInvoice(message: ApiMessage) {\n return message.content.invoice;\n}\n\nexport function getMessageWebPage(message: ApiMessage) {\n return message.content.webPage;\n}\n\nexport function getMessageWebPagePhoto(message: ApiMessage) {\n const webPage = getMessageWebPage(message);\n return webPage ? webPage.photo : undefined;\n}\n\nexport function getMessageWebPageDocument(message: ApiMessage) {\n const webPage = getMessageWebPage(message);\n return webPage ? webPage.document : undefined;\n}\n\nexport function getMessageWebPageVideo(message: ApiMessage): ApiVideo | undefined {\n const webPage = getMessageWebPage(message);\n if (!webPage) return undefined;\n return webPage.video;\n}\n\nexport function getMessageMediaThumbnail(message: ApiMessage) {\n const media = getMessagePhoto(message)\n || getMessageVideo(message)\n || getMessageDocument(message)\n || getMessageSticker(message)\n || getMessageWebPagePhoto(message)\n || getMessageWebPageVideo(message);\n\n if (!media) {\n return undefined;\n }\n\n return media.thumbnail;\n}\n\nexport function getMessageMediaThumbDataUri(message: ApiMessage) {\n const thumbnail = getMessageMediaThumbnail(message);\n\n return thumbnail ? thumbnail.dataUri : undefined;\n}\n\nexport function getMessageMediaHash(\n message: ApiMessage,\n target: Target,\n) {\n const {\n photo, video, sticker, audio, voice, document,\n } = message.content;\n const webPagePhoto = getMessageWebPagePhoto(message);\n const webPageVideo = getMessageWebPageVideo(message);\n\n const messageVideo = video || webPageVideo;\n const messagePhoto = photo || webPagePhoto;\n\n if (!(messagePhoto || messageVideo || sticker || audio || voice || document)) {\n return undefined;\n }\n\n const base = getMessageKey(message);\n\n if (messageVideo) {\n switch (target) {\n case 'micro':\n case 'pictogram':\n return `${base}?size=m`;\n case 'inline':\n return !hasMessageLocalBlobUrl(message) ? getVideoOrAudioBaseHash(messageVideo, base) : undefined;\n case 'viewerPreview':\n return `${base}?size=m`;\n case 'viewerFull':\n return getVideoOrAudioBaseHash(messageVideo, base);\n case 'download':\n return `${base}?download`;\n }\n }\n\n if (messagePhoto) {\n switch (target) {\n case 'micro':\n case 'pictogram':\n return `${base}?size=m`;\n case 'inline':\n return !hasMessageLocalBlobUrl(message) ? `${base}?size=x` : undefined;\n case 'viewerPreview':\n return `${base}?size=x`;\n case 'viewerFull':\n return `${base}?size=z`;\n }\n }\n\n if (document) {\n switch (target) {\n case 'micro':\n case 'pictogram':\n case 'inline':\n case 'viewerPreview':\n if (!getDocumentHasPreview(document) || hasMessageLocalBlobUrl(message)) {\n return undefined;\n }\n\n return `${base}?size=m`;\n default:\n return base;\n }\n }\n\n if (sticker) {\n switch (target) {\n case 'micro':\n return undefined;\n case 'pictogram':\n return `${base}?size=m`;\n default:\n return base;\n }\n }\n\n if (audio) {\n switch (target) {\n case 'micro':\n case 'pictogram':\n return undefined;\n case 'download':\n return `${base}?download`;\n default:\n return getVideoOrAudioBaseHash(audio, base);\n }\n }\n\n if (voice) {\n switch (target) {\n case 'micro':\n case 'pictogram':\n return undefined;\n default:\n return base;\n }\n }\n\n return undefined;\n}\n\nfunction getVideoOrAudioBaseHash(media: ApiAudio | ApiVideo, base: string) {\n if (IS_PROGRESSIVE_SUPPORTED && IS_SAFARI) {\n return `${base}?fileSize=${media.size}&mimeType=${media.mimeType}`;\n }\n\n return base;\n}\n\nexport function getMessageMediaFormat(\n message: ApiMessage, target: Target,\n): Exclude<ApiMediaFormat, ApiMediaFormat.Lottie>;\nexport function getMessageMediaFormat(message: ApiMessage, target: Target, canBeLottie: true): ApiMediaFormat;\nexport function getMessageMediaFormat(\n message: ApiMessage, target: Target,\n): ApiMediaFormat {\n const {\n sticker, video, audio, voice,\n } = message.content;\n\n const fullVideo = video || getMessageWebPageVideo(message);\n\n if (sticker && target === 'inline' && sticker.isAnimated) {\n return ApiMediaFormat.Lottie;\n } else if (fullVideo && IS_PROGRESSIVE_SUPPORTED && (\n target === 'viewerFull' || target === 'inline'\n )) {\n return ApiMediaFormat.Progressive;\n } else if (audio || voice) {\n // Safari\n if (voice && !IS_OPUS_SUPPORTED) {\n return ApiMediaFormat.BlobUrl;\n }\n\n return ApiMediaFormat.Progressive;\n }\n\n return ApiMediaFormat.BlobUrl;\n}\n\nexport function getMessageFileName(message: ApiMessage) {\n const {\n photo, video, document,\n } = message.content;\n const webPagePhoto = getMessageWebPagePhoto(message);\n const webPageVideo = getMessageWebPageVideo(message);\n\n if (photo || webPagePhoto) {\n return `photo${message.date}.jpeg`;\n }\n\n const { fileName } = video || webPageVideo || document || {};\n\n return fileName;\n}\n\nexport function getMessageFileSize(message: ApiMessage) {\n const { video, document } = message.content;\n const webPageVideo = getMessageWebPageVideo(message);\n const { size } = video || webPageVideo || document || {};\n\n return size;\n}\n\nexport function hasMessageLocalBlobUrl(message: ApiMessage) {\n const { photo, video, document } = message.content;\n\n return (photo && photo.blobUrl) || (video && video.blobUrl) || (document && document.previewBlobUrl);\n}\n\nexport function getChatMediaMessageIds(\n messages: Record<number, ApiMessage>, listedIds: number[], isFromSharedMedia = false,\n) {\n const ids = getMessageContentIds(messages, listedIds, isFromSharedMedia ? 'media' : 'inlineMedia');\n\n return isFromSharedMedia ? ids.reverse() : ids;\n}\n\nexport function getPhotoFullDimensions(photo: ApiPhoto): ApiDimensions | undefined {\n return (\n photo.sizes.find((size) => size.type === 'z')\n || photo.sizes.find((size) => size.type === 'y')\n || getPhotoInlineDimensions(photo)\n );\n}\n\nexport function getPhotoInlineDimensions(photo: ApiPhoto): ApiDimensions | undefined {\n return (\n photo.sizes.find((size) => size.type === 'x')\n || photo.sizes.find((size) => size.type === 'm')\n || photo.sizes.find((size) => size.type === 's')\n || photo.thumbnail\n );\n}\n\nexport function getVideoDimensions(video: ApiVideo): ApiDimensions | undefined {\n if (video.width && video.height) {\n return video as ApiDimensions;\n }\n\n return undefined;\n}\n\nexport function getMediaTransferState(message: ApiMessage, progress?: number, isDownloadNeeded = false) {\n const isUploading = isMessageLocal(message);\n const isTransferring = isUploading || isDownloadNeeded;\n const transferProgress = Number(progress);\n\n return {\n isUploading, isTransferring, transferProgress,\n };\n}\n\nexport function getMessageContentIds(\n messages: Record<number, ApiMessage>, messageIds: number[], contentType: ApiMessageSearchType | 'inlineMedia',\n) {\n let validator: Function;\n\n switch (contentType) {\n case 'media':\n validator = (message: ApiMessage) => {\n const video = getMessageVideo(message);\n return getMessagePhoto(message) || (video && !video.isRound && !video.isGif);\n };\n break;\n\n case 'documents':\n validator = getMessageDocument;\n break;\n\n case 'links':\n validator = (message: ApiMessage) => getMessageWebPage(message) || matchLinkInMessageText(message);\n break;\n\n case 'audio':\n validator = getMessageAudio;\n break;\n\n case 'inlineMedia':\n validator = (message: ApiMessage) => {\n const video = getMessageVideo(message);\n return (\n getMessagePhoto(message)\n || (video && !video.isRound && !video.isGif)\n || isMessageDocumentPhoto(message)\n || isMessageDocumentVideo(message)\n );\n };\n break;\n\n default:\n return [] as Array<number>;\n }\n\n return messageIds.reduce((result, messageId) => {\n if (messages[messageId] && validator(messages[messageId])) {\n result.push(messageId);\n }\n\n return result;\n }, [] as Array<number>);\n}\n\nexport function getMediaDuration(message: ApiMessage) {\n const { audio, voice, video } = getMessageContent(message);\n const media = audio || voice || video || getMessageWebPageVideo(message);\n if (!media) {\n return undefined;\n }\n\n return media.duration;\n}\n","export function buildChatThreadKey(chatId: number, threadId: number) {\n return `${chatId}_${threadId}`;\n}\n","import Worker from 'worker-loader!./worker';\n\nimport { ApiInitialArgs, ApiOnProgress, OnApiUpdate } from '../../types';\nimport { Methods, MethodArgs, MethodResponse } from '../methods/types';\nimport { WorkerMessageEvent, ThenArg, OriginRequest } from './types';\n\nimport { DEBUG } from '../../../config';\nimport generateIdFor from '../../../util/generateIdFor';\n\ntype RequestStates = {\n messageId: string;\n resolve: Function;\n reject: Function;\n callback?: AnyToVoidFunction;\n};\n\nlet worker: Worker;\nconst requestStates = new Map<string, RequestStates>();\nconst requestStatesByCallback = new Map<AnyToVoidFunction, RequestStates>();\n\n// TODO Re-use `util/WorkerConnector.ts`\n\nexport function initApi(onUpdate: OnApiUpdate, initialArgs: ApiInitialArgs) {\n if (!worker) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('>>> START LOAD WORKER');\n }\n\n worker = new Worker();\n subscribeToWorker(onUpdate);\n }\n\n return makeRequest({\n type: 'initApi',\n args: [initialArgs],\n });\n}\n\nexport function callApi<T extends keyof Methods>(fnName: T, ...args: MethodArgs<T>) {\n if (!worker) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.warn('API is not initialized');\n }\n\n return undefined;\n }\n\n return makeRequest({\n type: 'callMethod',\n name: fnName,\n args,\n }) as MethodResponse<T>;\n}\n\nexport function cancelApiProgress(progressCallback: ApiOnProgress) {\n progressCallback.isCanceled = true;\n\n const { messageId } = requestStatesByCallback.get(progressCallback) || {};\n if (!messageId) {\n return;\n }\n\n worker.postMessage({\n type: 'cancelProgress',\n messageId,\n });\n}\n\nfunction subscribeToWorker(onUpdate: OnApiUpdate) {\n worker.addEventListener('message', ({ data }: WorkerMessageEvent) => {\n if (data.type === 'update') {\n onUpdate(data.update);\n } else if (data.type === 'methodResponse') {\n const requestState = requestStates.get(data.messageId);\n if (requestState) {\n if (data.error) {\n requestState.reject(data.error);\n } else {\n requestState.resolve(data.response);\n }\n }\n } else if (data.type === 'methodCallback') {\n const requestState = requestStates.get(data.messageId);\n if (requestState && requestState.callback) {\n requestState.callback(...data.callbackArgs);\n }\n } else if (data.type === 'unhandledError') {\n throw data.error;\n }\n });\n}\n\nfunction makeRequest(message: OriginRequest) {\n const messageId = generateIdFor(requestStates);\n const payload: OriginRequest = {\n messageId,\n ...message,\n };\n\n const requestState = { messageId } as RequestStates;\n\n // Re-wrap type because of `postMessage`\n const promise: Promise<ThenArg<MethodResponse<keyof Methods>>> = new Promise((resolve, reject) => {\n Object.assign(requestState, { resolve, reject });\n });\n\n if (typeof payload.args[1] === 'function') {\n const callback = payload.args.pop() as AnyToVoidFunction;\n requestState.callback = callback;\n requestStatesByCallback.set(callback, requestState);\n }\n\n requestStates.set(messageId, requestState);\n promise\n .catch(() => undefined)\n .finally(() => {\n requestStates.delete(messageId);\n\n if (requestState.callback) {\n requestStatesByCallback.delete(requestState.callback);\n }\n });\n\n worker.postMessage(payload);\n\n return promise;\n}\n","let isWebpSupportedCache: boolean | undefined;\n\nexport function isWebpSupported() {\n return Boolean(isWebpSupportedCache);\n}\n\nfunction testWebp(): Promise<boolean> {\n return new Promise((resolve) => {\n const webp = new Image();\n // eslint-disable-next-line max-len\n webp.src = 'data:image/webp;base64,UklGRjoAAABXRUJQVlA4IC4AAACyAgCdASoCAAIALmk0mk0iIiIiIgBoSygABc6WWgAA/veff/0PP8bA//LwYAAA';\n const handleLoadOrError = () => {\n resolve(webp.height === 2);\n };\n webp.onload = handleLoadOrError;\n webp.onerror = handleLoadOrError;\n });\n}\n\ntestWebp().then((hasWebp) => {\n isWebpSupportedCache = hasWebp;\n});\n","import { ThemeKey } from '../types';\n\nlet systemThemeCache: ThemeKey = (\n window && window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches\n) ? 'dark' : 'light';\n\nexport function getSystemTheme() {\n return systemThemeCache;\n}\n\nfunction handleSystemThemeChange(e: MediaQueryListEventMap['change']) {\n systemThemeCache = e.matches ? 'dark' : 'light';\n}\n\nconst mql = window.matchMedia('(prefers-color-scheme: dark)');\nif (typeof mql.addEventListener === 'function') {\n mql.addEventListener('change', handleSystemThemeChange);\n} else if (typeof mql.addListener === 'function') {\n mql.addListener(handleSystemThemeChange);\n}\n","import {\n MIN_SCREEN_WIDTH_FOR_STATIC_LEFT_COLUMN,\n MOBILE_SCREEN_MAX_WIDTH,\n MOBILE_SCREEN_LANDSCAPE_MAX_HEIGHT,\n MOBILE_SCREEN_LANDSCAPE_MAX_WIDTH,\n IS_TEST,\n} from '../config';\n\nexport * from './environmentWebp';\n\nexport * from './environmentSystemTheme';\n\nexport function getPlatform() {\n const { userAgent, platform } = window.navigator;\n const macosPlatforms = ['Macintosh', 'MacIntel', 'MacPPC', 'Mac68K'];\n const windowsPlatforms = ['Win32', 'Win64', 'Windows', 'WinCE'];\n const iosPlatforms = ['iPhone', 'iPad', 'iPod'];\n let os: 'macOS' | 'iOS' | 'Windows' | 'Android' | 'Linux' | undefined;\n\n if (macosPlatforms.indexOf(platform) !== -1) {\n os = 'macOS';\n } else if (iosPlatforms.indexOf(platform) !== -1) {\n os = 'iOS';\n } else if (windowsPlatforms.indexOf(platform) !== -1) {\n os = 'Windows';\n } else if (/Android/.test(userAgent)) {\n os = 'Android';\n } else if (/Linux/.test(platform)) {\n os = 'Linux';\n }\n\n return os;\n}\n\nexport const PLATFORM_ENV = getPlatform();\nexport const IS_MAC_OS = PLATFORM_ENV === 'macOS';\nexport const IS_IOS = PLATFORM_ENV === 'iOS';\nexport const IS_ANDROID = PLATFORM_ENV === 'Android';\nexport const IS_SAFARI = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);\nexport const IS_PWA = window.matchMedia('(display-mode: standalone)').matches\n|| (window.navigator as any).standalone\n|| document.referrer.includes('android-app://');\n\nexport const IS_TOUCH_ENV = window.matchMedia('(pointer: coarse)').matches;\n// Keep in mind the landscape orientation\nexport const IS_SINGLE_COLUMN_LAYOUT = window.innerWidth <= MOBILE_SCREEN_MAX_WIDTH || (\n window.innerWidth <= MOBILE_SCREEN_LANDSCAPE_MAX_WIDTH && window.innerHeight <= MOBILE_SCREEN_LANDSCAPE_MAX_HEIGHT\n);\n// Special layout, 1 column while chat opened, 2 columns while collapsed\nexport const IS_TABLET_COLUMN_LAYOUT = !IS_SINGLE_COLUMN_LAYOUT && (\n window.innerWidth <= MIN_SCREEN_WIDTH_FOR_STATIC_LEFT_COLUMN\n);\nexport const IS_VOICE_RECORDING_SUPPORTED = (navigator.mediaDevices && 'getUserMedia' in navigator.mediaDevices && (\n window.AudioContext || (window as any).webkitAudioContext\n));\nexport const IS_SMOOTH_SCROLL_SUPPORTED = 'scrollBehavior' in document.documentElement.style;\nexport const IS_EMOJI_SUPPORTED = PLATFORM_ENV && (IS_MAC_OS || IS_IOS);\nexport const IS_SERVICE_WORKER_SUPPORTED = 'serviceWorker' in navigator;\n// TODO Consider failed service worker\nexport const IS_PROGRESSIVE_SUPPORTED = IS_SERVICE_WORKER_SUPPORTED;\nexport const IS_STREAMING_SUPPORTED = 'MediaSource' in window;\nexport const IS_OPUS_SUPPORTED = Boolean((new Audio()).canPlayType('audio/ogg; codecs=opus'));\nexport const IS_CANVAS_FILTER_SUPPORTED = (\n !IS_TEST && 'filter' in (document.createElement('canvas').getContext('2d') || {})\n);\nexport const LAYERS_ANIMATION_NAME = IS_ANDROID ? 'slide-fade' : IS_IOS ? 'slide-layers' : 'push-slide';\n\nexport const DPR = window.devicePixelRatio || 1;\n\nexport const MASK_IMAGE_DISABLED = true;\n","import { GlobalState } from '../../global/types';\nimport { ApiChat, ApiUser } from '../../api/types';\n\nexport function selectUser(global: GlobalState, userId: number): ApiUser | undefined {\n return global.users.byId[userId];\n}\n\nexport function selectIsUserBlocked(global: GlobalState, userId: number) {\n const user = selectUser(global, userId);\n\n return user && user.fullInfo && user.fullInfo.isBlocked;\n}\n\n// Slow, not to be used in `withGlobal`\nexport function selectUserByUsername(global: GlobalState, username: string) {\n const usernameLowered = username.toLowerCase();\n return Object.values(global.users.byId).find(\n (user) => user.username.toLowerCase() === usernameLowered,\n );\n}\n\nexport function selectIsUserOrChatContact(global: GlobalState, userOrChat: ApiUser | ApiChat) {\n return global.contactList && global.contactList.userIds.includes(userOrChat.id);\n}\n","import { GlobalState } from '../../global/types';\n\nexport function selectNotifySettings(global: GlobalState) {\n return global.settings.byKey;\n}\n\nexport function selectNotifyExceptions(global: GlobalState) {\n return global.settings.notifyExceptions;\n}\n","import { ApiChat, MAIN_THREAD_ID } from '../../api/types';\nimport { GlobalState } from '../../global/types';\n\nimport {\n getPrivateChatUserId, isChatChannel, isChatPrivate, isHistoryClearMessage, isUserBot, isUserOnline, selectIsChatMuted,\n} from '../helpers';\nimport { selectUser } from './users';\nimport { ALL_FOLDER_ID, ARCHIVED_FOLDER_ID, MEMBERS_LOAD_SLICE } from '../../config';\nimport { selectNotifyExceptions, selectNotifySettings } from './settings';\n\nexport function selectChat(global: GlobalState, chatId: number): ApiChat | undefined {\n return global.chats.byId[chatId];\n}\n\nexport function selectChatUser(global: GlobalState, chat: ApiChat) {\n const userId = getPrivateChatUserId(chat);\n if (!userId) {\n return false;\n }\n\n return selectUser(global, userId);\n}\n\nexport function selectIsChatWithSelf(global: GlobalState, chatId: number) {\n return chatId === global.currentUserId;\n}\n\nexport function selectIsChatWithBot(global: GlobalState, chat: ApiChat) {\n const user = selectChatUser(global, chat);\n return user && isUserBot(user);\n}\n\nexport function selectSupportChat(global: GlobalState) {\n return Object.values(global.chats.byId).find(({ isSupport }: ApiChat) => isSupport);\n}\n\nexport function selectChatOnlineCount(global: GlobalState, chat: ApiChat) {\n if (isChatPrivate(chat.id) || isChatChannel(chat) || !chat.fullInfo) {\n return undefined;\n }\n\n if (!chat.fullInfo.members || chat.fullInfo.members.length === MEMBERS_LOAD_SLICE) {\n return chat.fullInfo.onlineCount;\n }\n\n return chat.fullInfo.members.reduce((onlineCount, { userId }) => {\n if (global.users.byId[userId] && isUserOnline(global.users.byId[userId]) && userId !== global.currentUserId) {\n return onlineCount + 1;\n }\n\n return onlineCount;\n }, 0);\n}\n\nexport function selectChatBot(global: GlobalState, chatId: number) {\n const chat = selectChat(global, chatId);\n const userId = chat && getPrivateChatUserId(chat);\n const user = userId && selectUser(global, userId);\n if (!user || !isUserBot(user)) {\n return undefined;\n }\n\n return user;\n}\n\nexport function selectIsChatBotNotStarted(global: GlobalState, chatId: number) {\n const chat = selectChat(global, chatId);\n const bot = selectChatBot(global, chatId);\n if (!chat || !bot) {\n return false;\n }\n\n if (chat.lastMessage && isHistoryClearMessage(chat.lastMessage)) {\n return true;\n }\n\n const messageInfo = global.messages.byChatId[chatId];\n if (!messageInfo) {\n return false;\n }\n\n const { listedIds } = messageInfo.threadsById[MAIN_THREAD_ID] || {};\n return listedIds && !listedIds.length;\n}\n\nexport function selectAreActiveChatsLoaded(global: GlobalState): boolean {\n return Boolean(global.chats.listIds.active);\n}\n\nexport function selectIsChatListed(global: GlobalState, chatId: number, type?: 'active' | 'archived'): boolean {\n const { listIds } = global.chats;\n if (type) {\n const targetList = listIds[type];\n return Boolean(targetList && targetList.includes(chatId));\n }\n\n return Object.values(listIds).some((list) => list && list.includes(chatId));\n}\n\nexport function selectChatListType(global: GlobalState, chatId: number): 'active' | 'archived' | undefined {\n const chat = selectChat(global, chatId);\n if (!chat || !selectIsChatListed(global, chatId)) {\n return undefined;\n }\n\n return chat.folderId === ARCHIVED_FOLDER_ID ? 'archived' : 'active';\n}\n\nexport function selectChatFolder(global: GlobalState, folderId: number) {\n return global.chatFolders.byId[folderId];\n}\n\nexport function selectTotalChatCount(global: GlobalState, listType: 'active' | 'archived'): number {\n const { totalCount } = global.chats;\n const allChatsCount = totalCount.all;\n const archivedChatsCount = totalCount.archived || 0;\n\n if (listType === 'archived') {\n return archivedChatsCount;\n }\n\n return allChatsCount ? allChatsCount - archivedChatsCount : 0;\n}\n\nexport function selectIsChatPinned(global: GlobalState, chatId: number, folderId = ALL_FOLDER_ID): boolean {\n const { active, archived } = global.chats.orderedPinnedIds;\n\n if (folderId === ALL_FOLDER_ID) {\n return !!active && active.includes(chatId);\n }\n\n if (folderId === ARCHIVED_FOLDER_ID) {\n return !!archived && archived.includes(chatId);\n }\n\n const { byId: chatFoldersById } = global.chatFolders;\n\n const { pinnedChatIds } = chatFoldersById[folderId] || {};\n return !!pinnedChatIds && pinnedChatIds.includes(chatId);\n}\n\n// Slow, not to be used in `withGlobal`\nexport function selectChatByUsername(global: GlobalState, username: string) {\n const usernameLowered = username.toLowerCase();\n return Object.values(global.chats.byId).find(\n (chat) => chat.username && chat.username.toLowerCase() === usernameLowered,\n );\n}\n\nexport function selectCountNotMutedUnread(global: GlobalState) {\n const activeChatIds = global.chats.listIds.active;\n if (!activeChatIds) {\n return 0;\n }\n\n const chats = global.chats.byId;\n\n return activeChatIds.reduce((acc, chatId) => {\n const chat = chats[chatId];\n\n if (\n chat\n && chat.unreadCount\n && !selectIsChatMuted(chat, selectNotifySettings(global), selectNotifyExceptions(global))\n ) {\n return acc + chat.unreadCount;\n }\n\n return acc;\n }, 0);\n}\n","import { GlobalState } from '../../global/types';\nimport { ApiSticker } from '../../api/types';\n\nexport function selectIsStickerFavorite(global: GlobalState, sticker: ApiSticker) {\n const { stickers } = global.stickers.favorite;\n return stickers && stickers.some(({ id }) => id === sticker.id);\n}\n\nexport function selectCurrentStickerSearch(global: GlobalState) {\n return global.stickers.search;\n}\n\nexport function selectCurrentGifSearch(global: GlobalState) {\n return global.gifs.search;\n}\n\nexport function selectStickerSet(global: GlobalState, id: string) {\n return global.stickers.setsById[id];\n}\n\nexport function selectStickerSetByShortName(global: GlobalState, shortName: string) {\n return Object.values(global.stickers.setsById).find((l) => l.shortName.toLowerCase() === shortName.toLowerCase());\n}\n\nexport function selectStickersForEmoji(global: GlobalState, emoji: string) {\n const stickerSets = Object.values(global.stickers.setsById);\n let stickersForEmoji: ApiSticker[] = [];\n stickerSets.forEach(({ packs }) => {\n if (!packs) {\n return;\n }\n const stickers = packs[emoji];\n if (stickers) {\n stickersForEmoji = stickersForEmoji.concat(stickers);\n }\n });\n return stickersForEmoji;\n}\n\nexport function selectAnimatedEmoji(global: GlobalState, emoji: string) {\n const { animatedEmojis } = global;\n if (!animatedEmojis || !animatedEmojis.stickers) {\n return undefined;\n }\n\n // Some emojis (❤️ for example) with a service symbol 'VARIATION SELECTOR-16' are not recognized as animated\n const cleanedEmoji = emoji.replace('\\ufe0f', '');\n\n return animatedEmojis.stickers.find((sticker) => sticker.emoji === emoji || sticker.emoji === cleanedEmoji);\n}\n","import { GlobalState, MessageListType, Thread } from '../../global/types';\nimport {\n ApiChat,\n ApiMessage,\n ApiMessageOutgoingStatus,\n ApiUser,\n MAIN_THREAD_ID,\n} from '../../api/types';\n\nimport { LOCAL_MESSAGE_ID_BASE } from '../../config';\nimport {\n selectChat, selectIsChatWithBot, selectIsChatWithSelf,\n} from './chats';\nimport { selectIsUserOrChatContact, selectUser } from './users';\nimport {\n getSendingState,\n isChatChannel,\n isMessageLocal,\n isChatPrivate,\n isForwardedMessage,\n getCanPostInChat,\n isUserRightBanned,\n getHasAdminRight,\n isChatBasicGroup,\n isCommonBoxChat,\n isServiceNotificationMessage,\n isOwnMessage,\n isActionMessage,\n isChatGroup,\n isChatSuperGroup,\n getMessageVideo,\n getMessageWebPageVideo,\n} from '../helpers';\nimport { findLast } from '../../util/iteratees';\nimport { selectIsStickerFavorite } from './symbols';\n\nconst MESSAGE_EDIT_ALLOWED_TIME_MS = 172800000; // 48 hours\n\nexport function selectCurrentMessageList(global: GlobalState) {\n const { messageLists } = global.messages;\n\n if (messageLists.length) {\n return messageLists[messageLists.length - 1];\n }\n\n return undefined;\n}\n\nexport function selectCurrentChat(global: GlobalState) {\n const { chatId } = selectCurrentMessageList(global) || {};\n\n return chatId ? selectChat(global, chatId) : undefined;\n}\n\nexport function selectChatMessages(global: GlobalState, chatId: number) {\n const messages = global.messages.byChatId[chatId];\n\n return messages ? messages.byId : undefined;\n}\n\nexport function selectScheduledMessages(global: GlobalState, chatId: number) {\n const messages = global.scheduledMessages.byChatId[chatId];\n\n return messages ? messages.byId : undefined;\n}\n\nexport function selectThreadParam<K extends keyof Thread>(\n global: GlobalState,\n chatId: number,\n threadId: number,\n key: K,\n) {\n const messageInfo = global.messages.byChatId[chatId];\n if (!messageInfo) {\n return undefined;\n }\n\n const thread = messageInfo.threadsById[threadId];\n if (!thread) {\n return undefined;\n }\n\n return thread[key];\n}\n\nexport function selectListedIds(global: GlobalState, chatId: number, threadId: number) {\n return selectThreadParam(global, chatId, threadId, 'listedIds');\n}\n\nexport function selectOutlyingIds(global: GlobalState, chatId: number, threadId: number) {\n return selectThreadParam(global, chatId, threadId, 'outlyingIds');\n}\n\nexport function selectCurrentMessageIds(\n global: GlobalState, chatId: number, threadId: number, messageListType: MessageListType,\n) {\n switch (messageListType) {\n case 'thread':\n return selectViewportIds(global, chatId, threadId);\n case 'pinned':\n return selectPinnedIds(global, chatId);\n case 'scheduled':\n return selectScheduledIds(global, chatId);\n }\n\n return undefined;\n}\n\nexport function selectViewportIds(global: GlobalState, chatId: number, threadId: number) {\n return selectThreadParam(global, chatId, threadId, 'viewportIds');\n}\n\nexport function selectPinnedIds(global: GlobalState, chatId: number) {\n return selectThreadParam(global, chatId, MAIN_THREAD_ID, 'pinnedIds');\n}\n\nexport function selectScheduledIds(global: GlobalState, chatId: number) {\n return selectThreadParam(global, chatId, MAIN_THREAD_ID, 'scheduledIds');\n}\n\nexport function selectScrollOffset(global: GlobalState, chatId: number, threadId: number) {\n return selectThreadParam(global, chatId, threadId, 'scrollOffset');\n}\n\nexport function selectReplyingToId(global: GlobalState, chatId: number, threadId: number) {\n return selectThreadParam(global, chatId, threadId, 'replyingToId');\n}\n\nexport function selectEditingId(global: GlobalState, chatId: number, threadId: number) {\n return selectThreadParam(global, chatId, threadId, 'editingId');\n}\n\nexport function selectEditingScheduledId(global: GlobalState, chatId: number) {\n return selectThreadParam(global, chatId, MAIN_THREAD_ID, 'editingScheduledId');\n}\n\nexport function selectDraft(global: GlobalState, chatId: number, threadId: number) {\n return selectThreadParam(global, chatId, threadId, 'draft');\n}\n\nexport function selectNoWebPage(global: GlobalState, chatId: number, threadId: number) {\n return selectThreadParam(global, chatId, threadId, 'noWebPage');\n}\n\nexport function selectThreadInfo(global: GlobalState, chatId: number, threadId: number) {\n return selectThreadParam(global, chatId, threadId, 'threadInfo');\n}\n\nexport function selectFirstMessageId(global: GlobalState, chatId: number, threadId: number) {\n return selectThreadParam(global, chatId, threadId, 'firstMessageId');\n}\n\nexport function selectReplyStack(global: GlobalState, chatId: number, threadId: number) {\n return selectThreadParam(global, chatId, threadId, 'replyStack');\n}\n\nexport function selectThreadOriginChat(global: GlobalState, chatId: number, threadId: number) {\n if (threadId === MAIN_THREAD_ID) {\n return selectChat(global, chatId);\n }\n\n const threadInfo = selectThreadInfo(global, chatId, threadId);\n if (!threadInfo) {\n return undefined;\n }\n\n return selectChat(global, threadInfo.originChannelId || chatId);\n}\n\nexport function selectThreadTopMessageId(global: GlobalState, chatId: number, threadId: number) {\n if (threadId === MAIN_THREAD_ID) {\n return undefined;\n }\n\n const threadInfo = selectThreadInfo(global, chatId, threadId);\n if (!threadInfo) {\n return undefined;\n }\n\n return threadInfo.topMessageId;\n}\n\nexport function selectThreadByMessage(global: GlobalState, chatId: number, message: ApiMessage) {\n const messageInfo = global.messages.byChatId[chatId];\n if (!messageInfo) {\n return undefined;\n }\n\n const { replyToMessageId, replyToTopMessageId } = message;\n if (!replyToMessageId && !replyToTopMessageId) {\n return undefined;\n }\n\n return Object.values<Thread>(messageInfo.threadsById).find((thread) => {\n return thread.threadInfo && (\n (replyToMessageId && replyToMessageId === thread.threadInfo.topMessageId)\n || (replyToTopMessageId && replyToTopMessageId === thread.threadInfo.topMessageId)\n );\n });\n}\n\nexport function isMessageInCurrentMessageList(global: GlobalState, chatId: number, message: ApiMessage) {\n const currentMessageList = selectCurrentMessageList(global);\n if (!currentMessageList) {\n return false;\n }\n\n const { threadInfo } = selectThreadByMessage(global, chatId, message) || {};\n return (\n chatId === currentMessageList.chatId\n && (\n (currentMessageList.threadId === MAIN_THREAD_ID)\n || (threadInfo && currentMessageList.threadId === threadInfo.threadId)\n )\n );\n}\n\nexport function selectIsViewportNewest(global: GlobalState, chatId: number, threadId: number) {\n const viewportIds = selectViewportIds(global, chatId, threadId);\n if (!viewportIds || !viewportIds.length) {\n return true;\n }\n\n let lastMessageId: number;\n\n if (threadId === MAIN_THREAD_ID) {\n const chat = selectChat(global, chatId);\n if (!chat || !chat.lastMessage) {\n return true;\n }\n\n lastMessageId = chat.lastMessage.id;\n } else {\n const threadInfo = selectThreadInfo(global, chatId, threadId);\n if (!threadInfo || !threadInfo.lastMessageId) {\n return undefined;\n }\n\n lastMessageId = threadInfo.lastMessageId;\n }\n\n // Edge case: outgoing `lastMessage` is updated with a delay to optimize animation\n if (lastMessageId >= LOCAL_MESSAGE_ID_BASE && !selectChatMessage(global, chatId, lastMessageId)) {\n return true;\n }\n\n return viewportIds[viewportIds.length - 1] >= lastMessageId;\n}\n\nexport function selectChatMessage(global: GlobalState, chatId: number, messageId: number) {\n const chatMessages = selectChatMessages(global, chatId);\n\n return chatMessages ? chatMessages[messageId] : undefined;\n}\n\nexport function selectScheduledMessage(global: GlobalState, chatId: number, messageId: number) {\n const chatMessages = selectScheduledMessages(global, chatId);\n\n return chatMessages ? chatMessages[messageId] : undefined;\n}\n\nexport function selectEditingMessage(\n global: GlobalState, chatId: number, threadId: number, messageListType: MessageListType,\n) {\n if (messageListType === 'scheduled') {\n const messageId = selectEditingScheduledId(global, chatId);\n return messageId ? selectScheduledMessage(global, chatId, messageId) : undefined;\n } else {\n const messageId = selectEditingId(global, chatId, threadId);\n return messageId ? selectChatMessage(global, chatId, messageId) : undefined;\n }\n}\n\nexport function selectChatMessageByPollId(global: GlobalState, pollId: string) {\n let messageWithPoll: ApiMessage | undefined;\n\n // eslint-disable-next-line no-restricted-syntax\n for (const chatMessages of Object.values(global.messages.byChatId)) {\n const { byId } = chatMessages;\n messageWithPoll = Object.values(byId).find((message) => {\n return message.content.poll && message.content.poll.id === pollId;\n });\n if (messageWithPoll) {\n break;\n }\n }\n\n return messageWithPoll;\n}\n\nexport function selectFocusedMessageId(global: GlobalState, chatId: number) {\n const { chatId: focusedChatId, messageId } = global.focusedMessage || {};\n\n return focusedChatId === chatId ? messageId : undefined;\n}\n\nexport function selectIsMessageFocused(global: GlobalState, message: ApiMessage) {\n const focusedId = selectFocusedMessageId(global, message.chatId);\n\n return focusedId ? focusedId === message.id || focusedId === message.previousLocalId : false;\n}\n\nexport function selectIsMessageUnread(global: GlobalState, message: ApiMessage) {\n const { lastReadOutboxMessageId } = selectChat(global, message.chatId) || {};\n return isMessageLocal(message) || !lastReadOutboxMessageId || lastReadOutboxMessageId < message.id;\n}\n\nexport function selectOutgoingStatus(\n global: GlobalState, message: ApiMessage, isScheduledList = false,\n): ApiMessageOutgoingStatus {\n if (!selectIsMessageUnread(global, message) && !isScheduledList) {\n return 'read';\n }\n\n return getSendingState(message);\n}\n\nexport function selectSender(global: GlobalState, message: ApiMessage): ApiUser | ApiChat | undefined {\n const { senderId } = message;\n if (!senderId) {\n return undefined;\n }\n\n return senderId > 0 ? selectUser(global, senderId) : selectChat(global, senderId);\n}\n\nexport function selectForwardedSender(global: GlobalState, message: ApiMessage): ApiUser | ApiChat | undefined {\n const { forwardInfo } = message;\n if (!forwardInfo) {\n return undefined;\n }\n\n if (forwardInfo.isChannelPost && forwardInfo.fromChatId) {\n return selectChat(global, forwardInfo.fromChatId);\n } else if (forwardInfo.senderUserId) {\n return selectUser(global, forwardInfo.senderUserId);\n }\n\n return undefined;\n}\n\nexport function selectAllowedMessageActions(global: GlobalState, message: ApiMessage, threadId: number) {\n const { serverTimeOffset } = global;\n const chat = selectChat(global, message.chatId);\n if (!chat || chat.isRestricted) {\n return {};\n }\n\n const isPrivate = isChatPrivate(chat.id);\n const isChatWithSelf = selectIsChatWithSelf(global, message.chatId);\n const isBasicGroup = isChatBasicGroup(chat);\n const isSuperGroup = isChatSuperGroup(chat);\n const isChannel = isChatChannel(chat);\n const isServiceNotification = isServiceNotificationMessage(message);\n\n const isOwn = isOwnMessage(message);\n const isAction = isActionMessage(message);\n const { content } = message;\n const canEditMessagesIndefinitely = isChatWithSelf\n || (isSuperGroup && getHasAdminRight(chat, 'pinMessages'))\n || (isChannel && getHasAdminRight(chat, 'editMessages'));\n const isMessageEditable = (\n (canEditMessagesIndefinitely\n || Date.now() + serverTimeOffset * 1000 - message.date * 1000 < MESSAGE_EDIT_ALLOWED_TIME_MS)\n && !(\n content.sticker || content.contact || content.poll || content.action || content.audio\n || (content.video && content.video.isRound)\n )\n && !isForwardedMessage(message)\n && !message.viaBotId\n );\n\n const canReply = getCanPostInChat(chat, threadId) && !isServiceNotification;\n\n const hasPinPermission = isPrivate || (\n chat.isCreator\n || (!isChannel && !isUserRightBanned(chat, 'pinMessages'))\n || getHasAdminRight(chat, 'pinMessages')\n );\n\n let canPin = !isAction && hasPinPermission;\n let canUnpin = false;\n\n const pinnedMessageIds = selectPinnedIds(global, chat.id);\n\n if (canPin) {\n canUnpin = Boolean(pinnedMessageIds && pinnedMessageIds.includes(message.id));\n canPin = !canUnpin;\n }\n\n const canDelete = isPrivate\n || isOwn\n || isBasicGroup\n || chat.isCreator\n || getHasAdminRight(chat, 'deleteMessages');\n\n const canReport = !isPrivate && !isOwn;\n\n const canDeleteForAll = canDelete && !isServiceNotification && (\n (isPrivate && !isChatWithSelf)\n || (isBasicGroup && (\n isOwn || getHasAdminRight(chat, 'deleteMessages') || chat.isCreator\n ))\n );\n\n const canEdit = !isAction && isMessageEditable && (\n isOwn\n || (isChannel && (chat.isCreator || getHasAdminRight(chat, 'editMessages')))\n );\n\n const canForward = !isAction && !isServiceNotification;\n\n const hasSticker = Boolean(message.content.sticker);\n const hasFavoriteSticker = hasSticker && selectIsStickerFavorite(global, message.content.sticker!);\n const canFaveSticker = !isAction && hasSticker && !hasFavoriteSticker;\n const canUnfaveSticker = !isAction && hasFavoriteSticker;\n const canCopy = !isAction;\n const canCopyLink = !isAction && (isChannel || isSuperGroup);\n const canSelect = !isAction;\n const noOptions = [\n canReply,\n canEdit,\n canPin,\n canUnpin,\n canDelete,\n canDeleteForAll,\n canForward,\n canFaveSticker,\n canUnfaveSticker,\n canCopy,\n canCopyLink,\n canSelect,\n ].every((ability) => !ability);\n\n return {\n noOptions,\n canReply,\n canEdit,\n canPin,\n canUnpin,\n canDelete,\n canReport,\n canDeleteForAll,\n canForward,\n canFaveSticker,\n canUnfaveSticker,\n canCopy,\n canCopyLink,\n canSelect,\n };\n}\n\n// This selector always returns a new object which can not be safely used in shallow-equal checks\nexport function selectCanDeleteSelectedMessages(global: GlobalState) {\n const { messageIds: selectedMessageIds } = global.selectedMessages || {};\n const { chatId, threadId } = selectCurrentMessageList(global) || {};\n const chatMessages = chatId && selectChatMessages(global, chatId);\n if (!chatMessages || !selectedMessageIds || !threadId) {\n return {};\n }\n\n const messageActions = selectedMessageIds\n .map((id) => chatMessages[id] && selectAllowedMessageActions(global, chatMessages[id], threadId))\n .filter(Boolean);\n\n return {\n canDelete: messageActions.every((actions) => actions.canDelete),\n canDeleteForAll: messageActions.every((actions) => actions.canDeleteForAll),\n };\n}\n\nexport function selectCanReportSelectedMessages(global: GlobalState) {\n const { messageIds: selectedMessageIds } = global.selectedMessages || {};\n const { chatId, threadId } = selectCurrentMessageList(global) || {};\n const chatMessages = chatId && selectChatMessages(global, chatId);\n if (!chatMessages || !selectedMessageIds || !threadId) {\n return false;\n }\n\n const messageActions = selectedMessageIds\n .map((id) => chatMessages[id] && selectAllowedMessageActions(global, chatMessages[id], threadId))\n .filter(Boolean);\n\n return messageActions.every((actions) => actions.canReport);\n}\n\nexport function selectUploadProgress(global: GlobalState, message: ApiMessage) {\n const fileTransfer = global.fileUploads.byMessageLocalId[message.previousLocalId || message.id];\n\n return fileTransfer ? fileTransfer.progress : undefined;\n}\n\nexport function selectRealLastReadId(global: GlobalState, chatId: number, threadId: number) {\n if (threadId === MAIN_THREAD_ID) {\n const chat = selectChat(global, chatId);\n if (!chat) {\n return undefined;\n }\n\n // `lastReadInboxMessageId` is empty for new chats\n if (!chat.lastReadInboxMessageId) {\n return undefined;\n }\n\n if (!chat.lastMessage) {\n return chat.lastReadInboxMessageId;\n }\n\n if (isMessageLocal(chat.lastMessage)) {\n return chat.lastMessage.id;\n }\n\n // Some previously read messages may be deleted\n return Math.min(chat.lastMessage.id, chat.lastReadInboxMessageId);\n } else {\n const threadInfo = selectThreadInfo(global, chatId, threadId);\n if (!threadInfo) {\n return undefined;\n }\n\n if (!threadInfo.lastReadInboxMessageId) {\n return threadInfo.topMessageId;\n }\n\n // Some previously read messages may be deleted\n return Math.min(threadInfo.lastReadInboxMessageId, threadInfo.lastMessageId || Infinity);\n }\n}\n\nexport function selectFirstUnreadId(global: GlobalState, chatId: number, threadId: number) {\n const chat = selectChat(global, chatId);\n\n if (threadId === MAIN_THREAD_ID) {\n if (!chat) {\n return undefined;\n }\n } else {\n const threadInfo = selectThreadInfo(global, chatId, threadId);\n if (!threadInfo || threadInfo.lastMessageId === threadInfo.lastReadInboxMessageId) {\n return undefined;\n }\n }\n\n const outlyingIds = selectOutlyingIds(global, chatId, threadId);\n const listedIds = selectListedIds(global, chatId, threadId);\n const byId = selectChatMessages(global, chatId);\n if (!byId || !(outlyingIds || listedIds)) {\n return undefined;\n }\n\n const lastReadId = selectRealLastReadId(global, chatId, threadId);\n if (!lastReadId && chat && chat.isNotJoined) {\n return undefined;\n }\n\n if (outlyingIds) {\n const found = !lastReadId ? outlyingIds[0] : outlyingIds.find((id) => {\n return id > lastReadId && byId[id] && (!byId[id].isOutgoing || byId[id].isFromScheduled);\n });\n if (found) {\n return found;\n }\n }\n\n if (listedIds) {\n const found = !lastReadId ? listedIds[0] : listedIds.find((id) => {\n return id > lastReadId && byId[id] && (!byId[id].isOutgoing || byId[id].isFromScheduled);\n });\n if (found) {\n return found;\n }\n }\n\n return undefined;\n}\n\nexport function selectIsPollResultsOpen(global: GlobalState) {\n const { pollResults } = global;\n return Boolean(pollResults.messageId);\n}\n\nexport function selectIsForwardModalOpen(global: GlobalState) {\n const { forwardMessages } = global;\n return Boolean(forwardMessages.isModalShown);\n}\n\nexport function selectCommonBoxChatId(global: GlobalState, messageId: number) {\n const fromLastMessage = Object.values(global.chats.byId).find((chat) => (\n isCommonBoxChat(chat) && chat.lastMessage && chat.lastMessage.id === messageId\n ));\n if (fromLastMessage) {\n return fromLastMessage.id;\n }\n\n const { byChatId } = global.messages;\n return Number(Object.keys(byChatId).find((chatId) => {\n const chat = selectChat(global, Number(chatId));\n return chat && isCommonBoxChat(chat) && byChatId[chat.id].byId[messageId];\n }));\n}\n\nexport function selectIsInSelectMode(global: GlobalState) {\n const { selectedMessages } = global;\n\n return Boolean(selectedMessages);\n}\n\nexport function selectIsMessageSelected(global: GlobalState, messageId: number) {\n const { messageIds } = global.selectedMessages || {};\n if (!messageIds) {\n return false;\n }\n\n return messageIds.includes(messageId);\n}\n\nexport function selectForwardedMessageIdsByGroupId(global: GlobalState, chatId: number, groupedId: string) {\n const chatMessages = selectChatMessages(global, chatId);\n if (!chatMessages) {\n return undefined;\n }\n\n return Object.values(chatMessages)\n .filter((message) => message.groupedId === groupedId && message.forwardInfo)\n .map(({ forwardInfo }) => forwardInfo!.fromMessageId);\n}\n\nexport function selectMessageIdsByGroupId(global: GlobalState, chatId: number, groupedId: string) {\n const chatMessages = selectChatMessages(global, chatId);\n if (!chatMessages) {\n return undefined;\n }\n\n return Object.keys(chatMessages)\n .map(Number)\n .filter((id) => chatMessages[id].groupedId === groupedId);\n}\n\nexport function selectIsDocumentGroupSelected(global: GlobalState, chatId: number, groupedId: string) {\n const { messageIds: selectedIds } = global.selectedMessages || {};\n if (!selectedIds) {\n return false;\n }\n\n const groupIds = selectMessageIdsByGroupId(global, chatId, groupedId);\n return groupIds && groupIds.every((id) => selectedIds.includes(id));\n}\n\nexport function selectSelectedMessagesCount(global: GlobalState) {\n const { messageIds } = global.selectedMessages || {};\n\n return messageIds ? messageIds.length : 0;\n}\n\nexport function selectNewestMessageWithBotKeyboardButtons(\n global: GlobalState, chatId: number,\n): ApiMessage | undefined {\n const chat = selectChat(global, chatId);\n if (!chat) {\n return undefined;\n }\n\n if (!selectIsChatWithBot(global, chat)) {\n return undefined;\n }\n\n const chatMessages = selectChatMessages(global, chatId);\n const viewportIds = selectViewportIds(global, chatId, MAIN_THREAD_ID);\n if (!chatMessages || !viewportIds) {\n return undefined;\n }\n\n const messageId = findLast(viewportIds, (id) => {\n return !chatMessages[id].isOutgoing && Boolean(chatMessages[id].keyboardButtons);\n });\n\n const replyHideMessageId = findLast(viewportIds, (id) => {\n return Boolean(chatMessages[id].shouldHideKeyboardButtons);\n });\n\n if (messageId && replyHideMessageId && replyHideMessageId > messageId) {\n return undefined;\n }\n\n return messageId ? chatMessages[messageId] : undefined;\n}\n\nexport function selectShouldAutoLoadMedia(\n global: GlobalState, message: ApiMessage, chat: ApiChat, sender?: ApiChat | ApiUser,\n) {\n const {\n shouldAutoDownloadMediaFromContacts,\n shouldAutoDownloadMediaInPrivateChats,\n shouldAutoDownloadMediaInGroups,\n shouldAutoDownloadMediaInChannels,\n } = global.settings.byKey;\n\n return Boolean(\n (shouldAutoDownloadMediaInPrivateChats && isChatPrivate(chat.id))\n || (shouldAutoDownloadMediaInGroups && isChatGroup(chat))\n || (shouldAutoDownloadMediaInChannels && isChatChannel(chat))\n || (shouldAutoDownloadMediaFromContacts && sender && (\n sender.id === global.currentUserId\n || selectIsUserOrChatContact(global, sender)\n )),\n );\n}\n\nexport function selectShouldAutoPlayMedia(global: GlobalState, message: ApiMessage) {\n const video = getMessageVideo(message) || getMessageWebPageVideo(message);\n if (!video) {\n return undefined;\n }\n\n const {\n shouldAutoPlayVideos,\n shouldAutoPlayGifs,\n } = global.settings.byKey;\n\n const asGif = video.isGif || video.isRound;\n\n return (shouldAutoPlayVideos && !asGif) || (shouldAutoPlayGifs && asGif);\n}\n\nexport function selectShouldLoopStickers(global: GlobalState) {\n return global.settings.byKey.shouldLoopStickers;\n}\n","import { GlobalState } from '../../global/types';\nimport { selectCurrentMessageList } from './messages';\nimport { buildChatThreadKey } from '../helpers';\n\nexport function selectCurrentTextSearch(global: GlobalState) {\n const { chatId, threadId } = selectCurrentMessageList(global) || {};\n if (!chatId || !threadId) {\n return undefined;\n }\n\n const chatThreadKey = buildChatThreadKey(chatId, threadId);\n const currentSearch = global.localTextSearch.byChatThreadKey[chatThreadKey];\n if (!currentSearch || !currentSearch.isActive) {\n return undefined;\n }\n\n return currentSearch;\n}\n\nexport function selectCurrentMediaSearchPeerId(global: GlobalState) {\n const { byChatId } = global.localMediaSearch;\n const { chatId } = selectCurrentMessageList(global) || {};\n const currentProfileUserId = global.users.selectedId;\n\n return currentProfileUserId && byChatId[currentProfileUserId] ? currentProfileUserId : chatId;\n}\n\nexport function selectCurrentMediaSearch(global: GlobalState) {\n const peerId = selectCurrentMediaSearchPeerId(global);\n if (!peerId) {\n return undefined;\n }\n\n return global.localMediaSearch.byChatId[peerId];\n}\n","import { GlobalState } from '../../global/types';\n\nimport { selectCurrentMessageList } from './messages';\nimport { selectChat } from './chats';\nimport { isChatGroup, isChatPrivate } from '../helpers';\n\nexport function selectManagement(global: GlobalState, chatId: number) {\n return global.management.byChatId[chatId];\n}\n\nexport function selectCurrentManagement(global: GlobalState) {\n const { chatId, threadId } = selectCurrentMessageList(global) || {};\n if (!chatId || !threadId) {\n return undefined;\n }\n\n const currentManagement = global.management.byChatId[chatId];\n if (!currentManagement || !currentManagement.isActive) {\n return undefined;\n }\n\n return currentManagement;\n}\n\nexport function selectCurrentManagementType(global: GlobalState) {\n const { chatId, threadId } = selectCurrentMessageList(global) || {};\n if (!chatId || !threadId) {\n return undefined;\n }\n\n if (isChatPrivate(chatId)) {\n return 'user';\n }\n\n const chat = selectChat(global, chatId);\n if (!chat) {\n return undefined;\n }\n\n if (isChatGroup(chat)) {\n return 'group';\n }\n\n return 'channel';\n}\n","import { GlobalState } from '../../global/types';\nimport { NewChatMembersProgress, RightColumnContent } from '../../types';\n\nimport { getSystemTheme, IS_SINGLE_COLUMN_LAYOUT } from '../../util/environment';\nimport { selectCurrentMessageList, selectIsPollResultsOpen } from './messages';\nimport { selectCurrentTextSearch } from './localSearch';\nimport { selectCurrentStickerSearch, selectCurrentGifSearch } from './symbols';\nimport { selectAreActiveChatsLoaded } from './chats';\nimport { selectCurrentManagement } from './management';\n\nexport function selectIsMediaViewerOpen(global: GlobalState) {\n const { mediaViewer } = global;\n return Boolean(mediaViewer.messageId || mediaViewer.avatarOwnerId);\n}\n\nexport function selectRightColumnContentKey(global: GlobalState) {\n const {\n users,\n isChatInfoShown,\n newChatMembersProgress,\n } = global;\n\n const isAddingChatMembersShown = newChatMembersProgress !== NewChatMembersProgress.Closed;\n const isPollResults = selectIsPollResultsOpen(global);\n const isSearch = Boolean(!IS_SINGLE_COLUMN_LAYOUT && selectCurrentTextSearch(global));\n const isManagement = selectCurrentManagement(global);\n const stickerSearch = selectCurrentStickerSearch(global);\n const isStickerSearch = stickerSearch.query !== undefined;\n const gifSearch = selectCurrentGifSearch(global);\n const isGifSearch = gifSearch.query !== undefined;\n const { chatId: currentChatId } = selectCurrentMessageList(global) || {};\n const currentProfileUserId = users.selectedId;\n const areActiveChatsLoaded = selectAreActiveChatsLoaded(global);\n const isUserInfo = Boolean(currentProfileUserId && areActiveChatsLoaded);\n const isChatShown = Boolean(currentChatId && areActiveChatsLoaded);\n const isChatInfo = isChatShown && isChatInfoShown;\n\n return isPollResults ? (\n RightColumnContent.PollResults\n ) : isSearch ? (\n RightColumnContent.Search\n ) : isManagement ? (\n RightColumnContent.Management\n ) : isStickerSearch ? (\n RightColumnContent.StickerSearch\n ) : isGifSearch ? (\n RightColumnContent.GifSearch\n ) : isAddingChatMembersShown ? (\n RightColumnContent.AddingMembers\n ) : isUserInfo ? (\n RightColumnContent.UserInfo\n ) : isChatInfo ? (\n RightColumnContent.ChatInfo\n ) : undefined;\n}\n\nexport function selectIsRightColumnShown(global: GlobalState) {\n return selectRightColumnContentKey(global) !== undefined;\n}\n\nexport function selectTheme(global: GlobalState) {\n const { theme, shouldUseSystemTheme } = global.settings.byKey;\n\n return shouldUseSystemTheme ? getSystemTheme() : theme;\n}\n","import { GlobalState } from '../../global/types';\n\nexport function selectCurrentGlobalSearchQuery(global: GlobalState) {\n return global.globalSearch.query;\n}\n","\nimport { GlobalState } from '../../global/types';\n\nexport function selectPaymentMessageId(global: GlobalState) {\n return global.payment.messageId;\n}\n\nexport function selectPaymentRequestId(global: GlobalState) {\n return global.payment.formId;\n}\n\nexport function selectProviderPublishableKey(global: GlobalState) {\n return global.payment.nativeParams ? global.payment.nativeParams.publishableKey : undefined;\n}\n\nexport function selectStripeCredentials(global: GlobalState) {\n return global.payment.stripeCredentials;\n}\n","export * from './users';\nexport * from './chats';\nexport * from './messages';\nexport * from './updates';\nexport * from './media';\nexport * from './payments';\nexport * from './settings';\nexport * from './bots';\nexport * from './misc';\n","type Parts = (string | false | undefined)[];\n\nexport default (...parts: Parts) => {\n return parts.filter(Boolean).join(' ');\n};\n","type Scheduler =\n typeof requestAnimationFrame\n | typeof onTickEnd\n | typeof runNow;\n\nexport function debounce<F extends AnyToVoidFunction>(\n fn: F,\n ms: number,\n shouldRunFirst = true,\n shouldRunLast = true,\n) {\n let waitingTimeout: number | undefined;\n\n return (...args: Parameters<F>) => {\n if (waitingTimeout) {\n clearTimeout(waitingTimeout);\n waitingTimeout = undefined;\n } else if (shouldRunFirst) {\n // @ts-ignore\n fn(...args);\n }\n\n // eslint-disable-next-line no-restricted-globals\n waitingTimeout = self.setTimeout(() => {\n if (shouldRunLast) {\n // @ts-ignore\n fn(...args);\n }\n\n waitingTimeout = undefined;\n }, ms);\n };\n}\n\nexport function throttle<F extends AnyToVoidFunction>(\n fn: F,\n ms: number,\n shouldRunFirst = true,\n) {\n let interval: number | undefined;\n let isPending: boolean;\n let args: Parameters<F>;\n\n return (..._args: Parameters<F>) => {\n isPending = true;\n args = _args;\n\n if (!interval) {\n if (shouldRunFirst) {\n isPending = false;\n // @ts-ignore\n fn(...args);\n }\n\n // eslint-disable-next-line no-restricted-globals\n interval = self.setInterval(() => {\n if (!isPending) {\n // eslint-disable-next-line no-restricted-globals\n self.clearInterval(interval!);\n interval = undefined;\n return;\n }\n\n isPending = false;\n // @ts-ignore\n fn(...args);\n }, ms);\n }\n };\n}\n\nexport function throttleWithRaf<F extends AnyToVoidFunction>(fn: F) {\n return throttleWith(fastRaf, fn);\n}\n\nexport function throttleWithPrimaryRaf<F extends AnyToVoidFunction>(fn: F) {\n return throttleWith(fastPrimaryRaf, fn);\n}\n\nexport function throttleWithTickEnd<F extends AnyToVoidFunction>(fn: F) {\n return throttleWith(onTickEnd, fn);\n}\n\nexport function throttleWithNow<F extends AnyToVoidFunction>(fn: F) {\n return throttleWith(runNow, fn);\n}\n\nexport function throttleWith<F extends AnyToVoidFunction>(schedulerFn: Scheduler, fn: F) {\n let waiting = false;\n let args: Parameters<F>;\n\n return (..._args: Parameters<F>) => {\n args = _args;\n\n if (!waiting) {\n waiting = true;\n\n schedulerFn(() => {\n waiting = false;\n // @ts-ignore\n fn(...args);\n });\n }\n };\n}\n\nexport function onTickEnd(cb: NoneToVoidFunction) {\n Promise.resolve().then(cb);\n}\n\nexport function onIdle(cb: NoneToVoidFunction) {\n // eslint-disable-next-line no-restricted-globals\n if (self.requestIdleCallback) {\n // eslint-disable-next-line no-restricted-globals\n self.requestIdleCallback(cb);\n } else {\n onTickEnd(cb);\n }\n}\n\nfunction runNow(fn: NoneToVoidFunction) {\n fn();\n}\n\nexport const pause = (ms: number) => new Promise((resolve) => {\n setTimeout(() => resolve(), ms);\n});\n\nexport function rafPromise() {\n return new Promise((resolve) => {\n fastRaf(resolve);\n });\n}\n\nlet fastRafCallbacks: NoneToVoidFunction[] | undefined;\nlet fastRafPrimaryCallbacks: NoneToVoidFunction[] | undefined;\n\n// May result in an immediate execution if called from another `requestAnimationFrame` callback\nexport function fastRaf(callback: NoneToVoidFunction, isPrimary = false) {\n if (!fastRafCallbacks) {\n fastRafCallbacks = isPrimary ? [] : [callback];\n fastRafPrimaryCallbacks = isPrimary ? [callback] : [];\n\n requestAnimationFrame(() => {\n const currentCallbacks = fastRafCallbacks!;\n const currentPrimaryCallbacks = fastRafPrimaryCallbacks!;\n fastRafCallbacks = undefined;\n fastRafPrimaryCallbacks = undefined;\n currentPrimaryCallbacks.forEach((cb) => cb());\n currentCallbacks.forEach((cb) => cb());\n });\n } else if (isPrimary) {\n fastRafPrimaryCallbacks!.push(callback);\n } else {\n fastRafCallbacks.push(callback);\n }\n}\n\nexport function fastPrimaryRaf(callback: NoneToVoidFunction) {\n fastRaf(callback, true);\n}\n\nlet beforeUnloadCallbacks: NoneToVoidFunction[] | undefined;\n\nexport function onBeforeUnload(callback: NoneToVoidFunction, isLast = false) {\n if (!beforeUnloadCallbacks) {\n beforeUnloadCallbacks = [];\n // eslint-disable-next-line no-restricted-globals\n self.addEventListener('beforeunload', () => {\n beforeUnloadCallbacks!.forEach((cb) => cb());\n });\n }\n\n if (isLast) {\n beforeUnloadCallbacks.push(callback);\n } else {\n beforeUnloadCallbacks.unshift(callback);\n }\n\n return () => {\n beforeUnloadCallbacks = beforeUnloadCallbacks!.filter((cb) => cb !== callback);\n };\n}\n","import { GlobalState } from '../../global/types';\nimport { ApiChat, ApiPhoto } from '../../api/types';\n\nimport { ARCHIVED_FOLDER_ID } from '../../config';\nimport { omit } from '../../util/iteratees';\n\nexport function replaceChatListIds(\n global: GlobalState,\n type: 'active' | 'archived',\n newIds: number[] | undefined,\n): GlobalState {\n return {\n ...global,\n chats: {\n ...global.chats,\n listIds: {\n ...global.chats.listIds,\n [type]: newIds,\n },\n },\n };\n}\n\nexport function updateChatListIds(global: GlobalState, type: 'active' | 'archived', idsUpdate: number[]): GlobalState {\n const { [type]: listIds } = global.chats.listIds;\n const newIds = listIds && listIds.length\n ? idsUpdate.filter((id) => !listIds.includes(id))\n : idsUpdate;\n\n if (listIds && !newIds.length) {\n return global;\n }\n\n return replaceChatListIds(global, type, [\n ...(listIds || []),\n ...newIds,\n ]);\n}\n\nexport function replaceChats(global: GlobalState, newById: Record<number, ApiChat>): GlobalState {\n return {\n ...global,\n chats: {\n ...global.chats,\n byId: newById,\n },\n };\n}\n\n// @optimization Don't spread/unspread global for each element, do it in a batch\nfunction getUpdatedChat(\n global: GlobalState, chatId: number, chatUpdate: Partial<ApiChat>, photo?: ApiPhoto,\n): ApiChat {\n const { byId } = global.chats;\n const chat = byId[chatId];\n const shouldOmitMinInfo = chatUpdate.isMin && chat && !chat.isMin;\n const updatedChat = {\n ...chat,\n ...(shouldOmitMinInfo ? omit(chatUpdate, ['isMin', 'accessHash']) : chatUpdate),\n ...(photo && { photos: [photo, ...(chat.photos || [])] }),\n };\n\n if (!updatedChat.id || !updatedChat.type) {\n return updatedChat;\n }\n\n return updatedChat;\n}\n\nexport function updateChat(\n global: GlobalState, chatId: number, chatUpdate: Partial<ApiChat>, photo?: ApiPhoto,\n): GlobalState {\n const { byId } = global.chats;\n\n const updatedChat = getUpdatedChat(global, chatId, chatUpdate, photo);\n\n return replaceChats(global, {\n ...byId,\n [chatId]: updatedChat,\n });\n}\n\nexport function updateChats(global: GlobalState, updatedById: Record<number, ApiChat>): GlobalState {\n const updatedChats = Object.keys(updatedById).map(Number).reduce<Record<number, ApiChat>>((acc, id) => {\n const updatedChat = getUpdatedChat(global, id, updatedById[id]);\n if (updatedChat) {\n acc[id] = updatedChat;\n }\n return acc;\n }, {});\n\n global = replaceChats(global, {\n ...global.chats.byId,\n ...updatedChats,\n });\n\n return global;\n}\n\n// @optimization Allows to avoid redundant updates which cause a lot of renders\nexport function addChats(global: GlobalState, addedById: Record<number, ApiChat>): GlobalState {\n const { byId } = global.chats;\n let isAdded = false;\n\n const addedChats = Object.keys(addedById).map(Number).reduce<Record<number, ApiChat>>((acc, id) => {\n if (!byId[id] || (byId[id].isMin && !addedById[id].isMin)) {\n const updatedChat = getUpdatedChat(global, id, addedById[id]);\n if (updatedChat) {\n acc[id] = updatedChat;\n\n if (!isAdded) {\n isAdded = true;\n }\n }\n }\n return acc;\n }, {});\n\n if (isAdded) {\n global = replaceChats(global, {\n ...global.chats.byId,\n ...addedChats,\n });\n }\n\n return global;\n}\n\nexport function updateChatListType(\n global: GlobalState,\n chatId: number,\n folderId?: number,\n): GlobalState {\n const listType = folderId === ARCHIVED_FOLDER_ID ? 'archived' : 'active';\n\n let currentListIds = global.chats.listIds;\n (Object.keys(currentListIds) as Array<keyof typeof currentListIds>).forEach((listTypeKey) => {\n const currentFolderList = currentListIds[listTypeKey] || [];\n if (listTypeKey === listType && !currentFolderList.includes(chatId)) {\n currentListIds = {\n ...currentListIds,\n [listTypeKey]: [...currentFolderList, chatId],\n };\n } else if (listTypeKey !== listType && currentFolderList.includes(chatId)) {\n currentListIds = {\n ...currentListIds,\n [listTypeKey]: currentFolderList.filter((id) => id !== chatId),\n };\n }\n });\n\n global = {\n ...global,\n chats: {\n ...global.chats,\n listIds: currentListIds,\n },\n };\n\n global = updateChat(global, chatId, { folderId: folderId || undefined });\n\n return global;\n}\n\nexport function updateChatListSecondaryInfo(\n global: GlobalState,\n type: 'active' | 'archived',\n info: {\n orderedPinnedIds?: number[];\n totalChatCount: number;\n },\n): GlobalState {\n const totalCountKey = type === 'active' ? 'all' : 'archived';\n\n return {\n ...global,\n chats: {\n ...global.chats,\n ...(info.orderedPinnedIds && {\n orderedPinnedIds: {\n ...global.chats.orderedPinnedIds,\n [type]: info.orderedPinnedIds,\n },\n }),\n totalCount: {\n ...global.chats.totalCount,\n [totalCountKey]: info.totalChatCount,\n },\n isFullyLoaded: {\n ...global.chats.isFullyLoaded,\n [type]: false,\n },\n },\n };\n}\n","import {\n GlobalState, MessageList, MessageListType, Thread,\n} from '../../global/types';\nimport { ApiMessage, ApiThreadInfo, MAIN_THREAD_ID } from '../../api/types';\nimport { FocusDirection } from '../../types';\n\nimport { IS_TEST, MESSAGE_LIST_SLICE, MESSAGE_LIST_VIEWPORT_LIMIT } from '../../config';\nimport {\n selectListedIds,\n selectChatMessages,\n selectViewportIds,\n selectOutlyingIds,\n selectPinnedIds,\n selectThreadInfo,\n selectMessageIdsByGroupId,\n selectScheduledMessages,\n selectScheduledIds,\n selectCurrentMessageIds,\n selectChatMessage,\n selectCurrentMessageList,\n} from '../selectors';\nimport {\n areSortedArraysEqual, omit, pickTruthy, unique,\n} from '../../util/iteratees';\n\nconst TMP_CHAT_ID = -1;\n\ntype MessageStoreSections = {\n byId: Record<number, ApiMessage>;\n threadsById: Record<number, Thread>;\n};\n\nexport function updateCurrentMessageList(\n global: GlobalState,\n chatId: number | undefined,\n threadId: number = MAIN_THREAD_ID,\n type: MessageListType = 'thread',\n shouldReplaceHistory?: boolean,\n): GlobalState {\n const { messageLists } = global.messages;\n let newMessageLists: MessageList[] = messageLists;\n if (shouldReplaceHistory || IS_TEST) {\n newMessageLists = chatId ? [{ chatId, threadId, type }] : [];\n } else if (chatId) {\n const last = messageLists[messageLists.length - 1];\n if (!last || last.chatId !== chatId || last.threadId !== threadId || last.type !== type) {\n if (last && last.chatId === TMP_CHAT_ID) {\n newMessageLists = [...messageLists.slice(0, -1), { chatId, threadId, type }];\n } else {\n newMessageLists = [...messageLists, { chatId, threadId, type }];\n }\n }\n } else {\n newMessageLists = messageLists.slice(0, -1);\n }\n\n return {\n ...global,\n messages: {\n ...global.messages,\n messageLists: newMessageLists,\n },\n };\n}\n\nfunction replaceChatMessages(global: GlobalState, chatId: number, newById: Record<number, ApiMessage>): GlobalState {\n return updateMessageStore(global, chatId, {\n byId: newById,\n });\n}\n\nfunction updateThread(\n global: GlobalState, chatId: number, threadId: number, threadUpdate: Partial<Thread>,\n): GlobalState {\n const current = global.messages.byChatId[chatId];\n\n return updateMessageStore(global, chatId, {\n threadsById: {\n ...(current && current.threadsById),\n [threadId]: {\n ...(current && current.threadsById[threadId]),\n ...threadUpdate,\n },\n },\n });\n}\n\nfunction updateMessageStore(\n global: GlobalState, chatId: number, update: Partial<MessageStoreSections>,\n): GlobalState {\n const current = global.messages.byChatId[chatId] || { byId: {}, threadsById: {} };\n\n return {\n ...global,\n messages: {\n ...global.messages,\n byChatId: {\n ...global.messages.byChatId,\n [chatId]: {\n ...current,\n ...update,\n },\n },\n },\n };\n}\n\nexport function replaceThreadParam<T extends keyof Thread>(\n global: GlobalState, chatId: number, threadId: number, paramName: T, newValue: Thread[T] | undefined,\n) {\n return updateThread(global, chatId, threadId, { [paramName]: newValue });\n}\n\nexport function addMessages(\n global: GlobalState, messages: ApiMessage[],\n): GlobalState {\n const addedByChatId = messages.reduce((messagesByChatId, message: ApiMessage) => {\n if (!messagesByChatId[message.chatId]) {\n messagesByChatId[message.chatId] = {};\n }\n messagesByChatId[message.chatId][message.id] = message;\n\n return messagesByChatId;\n }, {} as Record<number, Record<number, ApiMessage>>);\n\n Object.keys(addedByChatId).map(Number).forEach((chatId) => {\n global = addChatMessagesById(global, chatId, addedByChatId[chatId]);\n });\n\n return global;\n}\n\nexport function addChatMessagesById(\n global: GlobalState, chatId: number, newById: Record<number, ApiMessage>,\n): GlobalState {\n const byId = selectChatMessages(global, chatId);\n\n if (byId && Object.keys(newById).every((newId) => Boolean(byId[Number(newId)]))) {\n return global;\n }\n\n return replaceChatMessages(global, chatId, {\n ...newById,\n ...byId,\n });\n}\n\nexport function updateChatMessage(\n global: GlobalState, chatId: number, messageId: number, messageUpdate: Partial<ApiMessage>,\n): GlobalState {\n const byId = selectChatMessages(global, chatId) || {};\n const message = byId[messageId];\n const updatedMessage = {\n ...message,\n ...messageUpdate,\n };\n\n if (!updatedMessage.id) {\n return global;\n }\n\n return replaceChatMessages(global, chatId, {\n ...byId,\n [messageId]: updatedMessage,\n });\n}\n\nexport function updateScheduledMessage(\n global: GlobalState, chatId: number, messageId: number, messageUpdate: Partial<ApiMessage>,\n): GlobalState {\n const byId = selectScheduledMessages(global, chatId) || {};\n const message = byId[messageId];\n const updatedMessage = {\n ...message,\n ...messageUpdate,\n };\n\n if (!updatedMessage.id) {\n return global;\n }\n\n return replaceScheduledMessages(global, chatId, {\n ...byId,\n [messageId]: updatedMessage,\n }, undefined);\n}\n\nexport function deleteChatMessages(\n global: GlobalState,\n chatId: number,\n messageIds: number[],\n): GlobalState {\n const byId = selectChatMessages(global, chatId);\n if (!byId) {\n return global;\n }\n const newById = omit(byId, messageIds);\n const deletedForwardedPosts = Object.values(pickTruthy(byId, messageIds)).filter(\n ({ forwardInfo }) => forwardInfo && forwardInfo.isLinkedChannelPost,\n );\n\n const threadIds = Object.keys(global.messages.byChatId[chatId].threadsById).map(Number);\n threadIds.forEach((threadId) => {\n const threadInfo = selectThreadInfo(global, chatId, threadId);\n\n let listedIds = selectListedIds(global, chatId, threadId);\n let outlyingIds = selectOutlyingIds(global, chatId, threadId);\n let viewportIds = selectViewportIds(global, chatId, threadId);\n let pinnedIds = selectPinnedIds(global, chatId);\n let newMessageCount = threadInfo ? threadInfo.messagesCount : undefined;\n\n messageIds.forEach((messageId) => {\n if (listedIds && listedIds.includes(messageId)) {\n listedIds = listedIds.filter((id) => id !== messageId);\n if (newMessageCount !== undefined) newMessageCount -= 1;\n }\n\n if (outlyingIds && outlyingIds.includes(messageId)) {\n outlyingIds = outlyingIds.filter((id) => id !== messageId);\n }\n\n if (viewportIds && viewportIds.includes(messageId)) {\n viewportIds = viewportIds.filter((id) => id !== messageId);\n }\n\n if (pinnedIds && pinnedIds.includes(messageId)) {\n pinnedIds = pinnedIds.filter((id) => id !== messageId);\n }\n });\n\n\n global = replaceThreadParam(global, chatId, threadId, 'listedIds', listedIds);\n global = replaceThreadParam(global, chatId, threadId, 'outlyingIds', outlyingIds);\n global = replaceThreadParam(global, chatId, threadId, 'viewportIds', viewportIds);\n global = replaceThreadParam(global, chatId, threadId, 'pinnedIds', pinnedIds);\n\n if (threadInfo && newMessageCount !== undefined) {\n global = replaceThreadParam(global, chatId, threadId, 'threadInfo', {\n ...threadInfo,\n messagesCount: newMessageCount,\n });\n }\n });\n\n if (deletedForwardedPosts.length) {\n const currentMessageList = selectCurrentMessageList(global);\n const canDeleteCurrentThread = currentMessageList && currentMessageList.chatId === chatId\n && currentMessageList.type === 'thread';\n const currentThreadId = currentMessageList && currentMessageList.threadId;\n\n deletedForwardedPosts.forEach((message) => {\n const { fromChatId, fromMessageId } = message.forwardInfo!;\n const originalPost = selectChatMessage(global, fromChatId!, fromMessageId!);\n\n if (canDeleteCurrentThread && currentThreadId === fromMessageId) {\n global = updateCurrentMessageList(global, chatId);\n }\n if (originalPost) {\n global = updateChatMessage(global, fromChatId!, fromMessageId!, { threadInfo: undefined });\n }\n });\n }\n\n global = replaceChatMessages(global, chatId, newById);\n\n return global;\n}\n\nexport function deleteChatScheduledMessages(\n global: GlobalState,\n chatId: number,\n messageIds: number[],\n): GlobalState {\n const byId = selectScheduledMessages(global, chatId);\n if (!byId) {\n return global;\n }\n const newById = omit(byId, messageIds);\n\n let scheduledIds = selectScheduledIds(global, chatId);\n if (scheduledIds) {\n messageIds.forEach((messageId) => {\n if (scheduledIds!.includes(messageId)) {\n scheduledIds = scheduledIds!.filter((id) => id !== messageId);\n }\n });\n global = replaceThreadParam(global, chatId, MAIN_THREAD_ID, 'scheduledIds', scheduledIds);\n }\n\n global = replaceScheduledMessages(global, chatId, newById, undefined);\n\n return global;\n}\n\nexport function updateListedIds(\n global: GlobalState,\n chatId: number,\n threadId: number,\n idsUpdate: number[],\n): GlobalState {\n const listedIds = selectListedIds(global, chatId, threadId);\n const newIds = listedIds && listedIds.length\n ? idsUpdate.filter((id) => !listedIds.includes(id))\n : idsUpdate;\n\n if (listedIds && !newIds.length) {\n return global;\n }\n\n return replaceThreadParam(global, chatId, threadId, 'listedIds', orderHistoryIds([\n ...(listedIds || []),\n ...newIds,\n ]));\n}\n\nexport function updateOutlyingIds(\n global: GlobalState,\n chatId: number,\n threadId: number,\n idsUpdate: number[],\n): GlobalState {\n const outlyingIds = selectOutlyingIds(global, chatId, threadId);\n const newIds = outlyingIds && outlyingIds.length\n ? idsUpdate.filter((id) => !outlyingIds.includes(id))\n : idsUpdate;\n\n if (outlyingIds && !newIds.length) {\n return global;\n }\n\n return replaceThreadParam(global, chatId, threadId, 'outlyingIds', orderHistoryIds([\n ...(outlyingIds || []),\n ...newIds,\n ]));\n}\n\nfunction orderHistoryIds(listedIds: number[]) {\n return listedIds.sort((a, b) => a - b);\n}\n\nexport function addViewportId(\n global: GlobalState,\n chatId: number,\n threadId: number,\n newId: number,\n): GlobalState {\n const viewportIds = selectViewportIds(global, chatId, threadId) || [];\n if (viewportIds.includes(newId)) {\n return global;\n }\n\n const newIds = orderHistoryIds([\n ...(\n viewportIds.length < MESSAGE_LIST_VIEWPORT_LIMIT\n ? viewportIds\n : viewportIds.slice(-(MESSAGE_LIST_SLICE / 2))\n ),\n newId,\n ]);\n\n return replaceThreadParam(global, chatId, threadId, 'viewportIds', newIds);\n}\n\nexport function safeReplaceViewportIds(\n global: GlobalState,\n chatId: number,\n threadId: number,\n newViewportIds: number[],\n): GlobalState {\n const viewportIds = selectViewportIds(global, chatId, threadId) || [];\n\n return replaceThreadParam(\n global,\n chatId,\n threadId,\n 'viewportIds',\n areSortedArraysEqual(viewportIds, newViewportIds) ? viewportIds : newViewportIds,\n );\n}\n\nexport function updateThreadInfo(\n global: GlobalState, chatId: number, threadId: number, update: Partial<ApiThreadInfo> | undefined,\n): GlobalState {\n const newThreadInfo = {\n ...(selectThreadInfo(global, chatId, threadId) as ApiThreadInfo),\n ...update,\n };\n\n if (!newThreadInfo.threadId) {\n return global;\n }\n\n return replaceThreadParam(global, chatId, threadId, 'threadInfo', newThreadInfo);\n}\n\nexport function updateThreadInfos(\n global: GlobalState, chatId: number, updates: Partial<ApiThreadInfo>[],\n): GlobalState {\n updates.forEach((update) => {\n global = updateThreadInfo(global, update.chatId!, update.threadId!, update);\n });\n\n return global;\n}\n\nexport function replaceScheduledMessages(\n global: GlobalState, chatId: number, newById: Record<number, ApiMessage>, hash: number | undefined,\n): GlobalState {\n return updateScheduledMessages(global, chatId, {\n byId: newById,\n hash,\n });\n}\n\nfunction updateScheduledMessages(\n global: GlobalState, chatId: number, update: Partial<{ byId: Record<number, ApiMessage>; hash: number }>,\n): GlobalState {\n const current = global.scheduledMessages.byChatId[chatId] || { byId: {}, hash: 0 };\n\n return {\n ...global,\n scheduledMessages: {\n byChatId: {\n ...global.scheduledMessages.byChatId,\n [chatId]: {\n ...current,\n ...update,\n },\n },\n },\n };\n}\n\nexport function updateFocusedMessage(\n global: GlobalState, chatId?: number, messageId?: number, noHighlight = false,\n): GlobalState {\n return {\n ...global,\n focusedMessage: {\n ...global.focusedMessage,\n chatId,\n messageId,\n noHighlight,\n },\n };\n}\n\nexport function updateFocusDirection(\n global: GlobalState, direction?: FocusDirection,\n): GlobalState {\n return {\n ...global,\n focusedMessage: {\n ...global.focusedMessage,\n direction,\n },\n };\n}\n\nexport function enterMessageSelectMode(\n global: GlobalState,\n chatId: number,\n messageId?: number | number[],\n): GlobalState {\n const messageIds = messageId ? Array.prototype.concat([], messageId) : [];\n return {\n ...global,\n selectedMessages: {\n chatId,\n messageIds,\n },\n };\n}\n\nexport function toggleMessageSelection(\n global: GlobalState,\n chatId: number,\n threadId: number,\n messageListType: MessageListType,\n messageId: number,\n groupedId?: string,\n childMessageIds?: number[],\n withShift = false,\n): GlobalState {\n const { selectedMessages: oldSelectedMessages } = global;\n if (groupedId) {\n childMessageIds = selectMessageIdsByGroupId(global, chatId, groupedId);\n }\n const selectedMessageIds = childMessageIds || [messageId];\n if (!oldSelectedMessages) {\n return enterMessageSelectMode(global, chatId, selectedMessageIds);\n }\n\n const { messageIds } = oldSelectedMessages;\n\n let newMessageIds;\n const newSelectedMessageIds = selectedMessageIds.filter((id) => !messageIds.includes(id));\n if (newSelectedMessageIds && !newSelectedMessageIds.length) {\n newMessageIds = messageIds.filter((id) => !selectedMessageIds.includes(id));\n } else if (withShift && messageIds.length) {\n const viewportIds = selectCurrentMessageIds(global, chatId, threadId, messageListType)!;\n const prevIndex = viewportIds.indexOf(messageIds[messageIds.length - 1]);\n const currentIndex = viewportIds.indexOf(messageId);\n const from = Math.min(prevIndex, currentIndex);\n const to = Math.max(prevIndex, currentIndex);\n const slice = viewportIds.slice(from, to + 1);\n newMessageIds = unique([...messageIds, ...slice]);\n } else {\n newMessageIds = [...messageIds, ...newSelectedMessageIds];\n }\n\n if (!newMessageIds.length) {\n return exitMessageSelectMode(global);\n }\n\n return {\n ...global,\n selectedMessages: {\n ...oldSelectedMessages,\n messageIds: newMessageIds,\n },\n };\n}\n\nexport function exitMessageSelectMode(global: GlobalState): GlobalState {\n return {\n ...global,\n selectedMessages: undefined,\n };\n}\n","import { GlobalState } from '../../global/types';\nimport { ApiSticker, ApiStickerSet, ApiVideo } from '../../api/types';\nimport { buildCollectionByKey, unique } from '../../util/iteratees';\nimport { selectStickersForEmoji } from '../selectors';\n\nexport function updateStickerSets(\n global: GlobalState,\n category: 'added' | 'featured' | 'search',\n hash: number,\n sets: ApiStickerSet[],\n resultIds?: string[],\n): GlobalState {\n const updatedSets = sets.map((stickerSet) => {\n const existing = global.stickers.setsById[stickerSet.id];\n if (!existing) {\n return stickerSet;\n }\n\n return {\n ...existing,\n ...stickerSet,\n };\n });\n\n return {\n ...global,\n stickers: {\n ...global.stickers,\n setsById: {\n ...global.stickers.setsById,\n ...buildCollectionByKey(updatedSets, 'id'),\n },\n [category]: {\n ...global.stickers[category],\n hash,\n ...(\n category === 'search'\n ? { resultIds }\n : { setIds: sets.map(({ id }) => id) }\n ),\n },\n },\n };\n}\n\nexport function updateStickerSet(\n global: GlobalState, stickerSetId: string, update: Partial<ApiStickerSet>,\n): GlobalState {\n const currentStickerSet = global.stickers.setsById[stickerSetId] || {};\n\n return {\n ...global,\n stickers: {\n ...global.stickers,\n setsById: {\n ...global.stickers.setsById,\n [stickerSetId]: {\n ...currentStickerSet,\n ...update,\n },\n },\n },\n };\n}\n\nexport function updateGifSearch(\n global: GlobalState, isNew: boolean, results: ApiVideo[], nextOffset?: string,\n): GlobalState {\n const { results: currentResults } = global.gifs.search;\n\n let newResults!: ApiVideo[];\n if (isNew || !currentResults) {\n newResults = results;\n } else {\n const currentIds = new Set(currentResults.map((gif) => gif.id));\n newResults = [\n ...currentResults,\n ...results.filter((gif) => !currentIds.has(gif.id)),\n ];\n }\n\n return {\n ...global,\n gifs: {\n ...global.gifs,\n search: {\n ...global.gifs.search,\n offset: nextOffset,\n results: newResults,\n },\n },\n };\n}\n\nexport function replaceAnimatedEmojis(global: GlobalState, stickerSet: ApiStickerSet): GlobalState {\n return {\n ...global,\n animatedEmojis: stickerSet,\n };\n}\n\nexport function updateStickersForEmoji(\n global: GlobalState, emoji: string, remoteStickers?: ApiSticker[], hash?: number,\n): GlobalState {\n const localStickers = selectStickersForEmoji(global, emoji);\n const allStickers = [...localStickers, ...(remoteStickers || [])];\n const uniqueIds = unique(allStickers.map(({ id }) => id));\n const byId = buildCollectionByKey(allStickers, 'id');\n const stickers = uniqueIds.map((id) => byId[id]);\n\n return {\n ...global,\n stickers: {\n ...global.stickers,\n forEmoji: {\n emoji,\n stickers,\n hash,\n },\n },\n };\n}\n\nexport function rebuildStickersForEmoji(global: GlobalState): GlobalState {\n const { emoji, stickers, hash } = global.stickers.forEmoji || {};\n if (!emoji) {\n return global;\n }\n\n return updateStickersForEmoji(global, emoji, stickers, hash);\n}\n","import { GlobalState } from '../../global/types';\nimport { ApiUser } from '../../api/types';\n\nimport { omit } from '../../util/iteratees';\nimport { MEMO_EMPTY_ARRAY } from '../../util/memo';\n\nexport function replaceUsers(global: GlobalState, newById: Record<number, ApiUser>): GlobalState {\n return {\n ...global,\n users: {\n ...global.users,\n byId: newById,\n },\n };\n}\n\n// @optimization Don't spread/unspread global for each element, do it in a batch\nfunction getUpdatedUser(global: GlobalState, userId: number, userUpdate: Partial<ApiUser>): ApiUser {\n const { byId } = global.users;\n const user = byId[userId];\n const shouldOmitMinInfo = userUpdate.isMin && user && !user.isMin;\n\n const updatedUser = {\n ...user,\n ...(shouldOmitMinInfo ? omit(userUpdate, ['isMin', 'accessHash']) : userUpdate),\n };\n\n if (!updatedUser.id || !updatedUser.type) {\n return user;\n }\n\n return updatedUser;\n}\n\nfunction updateContactList(global: GlobalState, updatedUsers: ApiUser[]): GlobalState {\n const { hash, userIds: contactUserIds } = global.contactList || {};\n\n if (!contactUserIds) return global;\n\n const newContactUserIds = updatedUsers\n .filter((user) => user && user.isContact && !contactUserIds.includes(user.id))\n .map((user) => user.id);\n\n if (newContactUserIds.length === 0) return global;\n\n return {\n ...global,\n contactList: {\n hash: hash || 0,\n userIds: [\n ...newContactUserIds,\n ...contactUserIds,\n ],\n },\n };\n}\n\nexport function updateUser(global: GlobalState, userId: number, userUpdate: Partial<ApiUser>): GlobalState {\n const { byId } = global.users;\n\n const updatedUser = getUpdatedUser(global, userId, userUpdate);\n\n global = updateContactList(global, [updatedUser]);\n\n return replaceUsers(global, {\n ...byId,\n [userId]: updatedUser,\n });\n}\n\n\nexport function updateUsers(global: GlobalState, updatedById: Record<number, ApiUser>): GlobalState {\n const updatedUsers = Object.keys(updatedById).map(Number).reduce<Record<number, ApiUser>>((acc, id) => {\n const updatedUser = getUpdatedUser(global, id, updatedById[id]);\n if (updatedUser) {\n acc[id] = updatedUser;\n }\n return acc;\n }, {});\n\n global = updateContactList(global, Object.values(updatedUsers));\n\n global = replaceUsers(global, {\n ...global.users.byId,\n ...updatedUsers,\n });\n\n return global;\n}\n\n// @optimization Allows to avoid redundant updates which cause a lot of renders\nexport function addUsers(global: GlobalState, addedById: Record<number, ApiUser>): GlobalState {\n const { byId } = global.users;\n let isAdded = false;\n\n const addedUsers = Object.keys(addedById).map(Number).reduce<Record<number, ApiUser>>((acc, id) => {\n if (!byId[id] || (byId[id].isMin && !addedById[id].isMin)) {\n const updatedUser = getUpdatedUser(global, id, addedById[id]);\n if (updatedUser) {\n acc[id] = updatedUser;\n\n if (!isAdded) {\n isAdded = true;\n }\n }\n }\n return acc;\n }, {});\n\n if (isAdded) {\n global = replaceUsers(global, {\n ...global.users.byId,\n ...addedUsers,\n });\n\n global = updateContactList(global, Object.values(addedUsers));\n }\n\n return global;\n}\n\nexport function updateSelectedUserId(global: GlobalState, selectedId?: number): GlobalState {\n if (global.users.selectedId === selectedId) {\n return global;\n }\n\n return {\n ...global,\n users: {\n ...global.users,\n selectedId,\n },\n };\n}\n\nexport function deleteUser(global: GlobalState, userId: number): GlobalState {\n const { byId } = global.users;\n const { hash, userIds } = global.contactList || {};\n delete byId[userId];\n\n global = {\n ...global,\n contactList: {\n hash: hash || 0,\n userIds: userIds ? userIds.filter((id) => id !== userId) : MEMO_EMPTY_ARRAY,\n },\n };\n\n return replaceUsers(global, byId);\n}\n\nexport function updateUserSearch(\n global: GlobalState,\n searchStatePartial: Partial<GlobalState['userSearch']>,\n) {\n return {\n ...global,\n userSearch: {\n ...global.userSearch,\n ...searchStatePartial,\n },\n };\n}\n\nexport function updateUserSearchFetchingStatus(\n global: GlobalState, newState: boolean,\n) {\n return updateUserSearch(global, {\n fetchingStatus: newState,\n });\n}\n\nexport function updateUserBlockedState(global: GlobalState, userId: number, isBlocked: boolean) {\n const { byId } = global.users;\n const user = byId[userId];\n if (!user || !user.fullInfo) {\n return global;\n }\n\n return updateUser(global, userId, {\n ...user,\n fullInfo: {\n ...user.fullInfo,\n isBlocked,\n },\n });\n}\n","import { GlobalState } from '../../global/types';\nimport { GlobalSearchContent } from '../../types';\nimport { ApiGlobalMessageSearchType, ApiMessage } from '../../api/types';\nimport { areSortedArraysEqual } from '../../util/iteratees';\n\nconst getComplexKey = (message: ApiMessage) => `${message.chatId}_${message.id}`;\n\nexport function updateGlobalSearch(\n global: GlobalState,\n searchStatePartial: Partial<GlobalState['globalSearch']>,\n) {\n return {\n ...global,\n globalSearch: {\n ...global.globalSearch,\n ...searchStatePartial,\n },\n };\n}\n\nexport function updateGlobalSearchContent(\n global: GlobalState,\n currentContent: GlobalSearchContent | undefined,\n): GlobalState {\n return updateGlobalSearch(global, { currentContent });\n}\n\nexport function updateGlobalSearchResults(\n global: GlobalState,\n newFoundMessages: ApiMessage[],\n totalCount: number,\n type: ApiGlobalMessageSearchType,\n nextRate?: number,\n): GlobalState {\n const { resultsByType } = global.globalSearch || {};\n const newFoundMessagesById = newFoundMessages.reduce((result, message) => {\n result[getComplexKey(message)] = message;\n\n return result;\n }, {} as Record<string, ApiMessage>);\n const foundIdsForType = resultsByType && resultsByType[type] ? resultsByType[type]!.foundIds : undefined;\n\n if (foundIdsForType !== undefined\n && Object.keys(newFoundMessagesById).every(\n (newId) => foundIdsForType.includes(getComplexKey(newFoundMessagesById[newId])),\n )\n ) {\n return updateGlobalSearchFetchingStatus(global, { messages: false });\n }\n\n const prevFoundIds = foundIdsForType || [];\n const newFoundIds = newFoundMessages.map((message) => getComplexKey(message));\n const foundIds = Array.prototype.concat(prevFoundIds, newFoundIds);\n const foundOrPrevFoundIds = areSortedArraysEqual(prevFoundIds, foundIds) ? prevFoundIds : foundIds;\n\n global = updateGlobalSearchFetchingStatus(global, { messages: false });\n\n return updateGlobalSearch(global, {\n resultsByType: {\n ...(global.globalSearch || {}).resultsByType,\n [type]: {\n totalCount,\n nextOffsetId: nextRate,\n foundIds: foundOrPrevFoundIds,\n },\n },\n });\n}\n\nexport function updateGlobalSearchFetchingStatus(\n global: GlobalState, newState: { chats?: boolean; messages?: boolean },\n) {\n return updateGlobalSearch(global, {\n fetchingStatus: {\n ...global.globalSearch.fetchingStatus,\n ...newState,\n },\n });\n}\n","import { GlobalState } from '../../global/types';\nimport { ApiMessageSearchType } from '../../api/types';\n\nimport { areSortedArraysEqual, unique } from '../../util/iteratees';\nimport { SharedMediaType } from '../../types';\nimport { buildChatThreadKey } from '../helpers';\n\ninterface TextSearchParams {\n isActive: boolean;\n query?: string;\n results?: {\n totalCount?: number;\n nextOffsetId?: number;\n foundIds?: number[];\n };\n}\n\ninterface MediaSearchParams {\n currentType?: SharedMediaType;\n resultsByType?: Partial<Record<SharedMediaType, {\n totalCount?: number;\n nextOffsetId: number;\n foundIds: number[];\n }>>;\n}\n\nfunction replaceLocalTextSearch(\n global: GlobalState,\n chatThreadKey: string,\n searchParams: TextSearchParams,\n): GlobalState {\n return {\n ...global,\n localTextSearch: {\n byChatThreadKey: {\n ...global.localTextSearch.byChatThreadKey,\n [chatThreadKey]: searchParams,\n },\n },\n };\n}\n\nexport function updateLocalTextSearch(\n global: GlobalState,\n chatId: number,\n threadId: number,\n isActive: boolean,\n query?: string,\n): GlobalState {\n const chatThreadKey = buildChatThreadKey(chatId, threadId);\n\n return replaceLocalTextSearch(global, chatThreadKey, {\n ...global.localTextSearch.byChatThreadKey[chatThreadKey],\n isActive,\n query,\n });\n}\n\nexport function replaceLocalTextSearchResults(\n global: GlobalState,\n chatId: number,\n threadId: number,\n foundIds?: number[],\n totalCount?: number,\n nextOffsetId?: number,\n): GlobalState {\n const chatThreadKey = buildChatThreadKey(chatId, threadId);\n\n return replaceLocalTextSearch(global, chatThreadKey, {\n ...global.localTextSearch.byChatThreadKey[chatThreadKey],\n results: {\n foundIds,\n totalCount,\n nextOffsetId,\n },\n });\n}\n\nexport function updateLocalTextSearchResults(\n global: GlobalState,\n chatId: number,\n threadId: number,\n newFoundIds: number[],\n totalCount?: number,\n nextOffsetId?: number,\n): GlobalState {\n const chatThreadKey = buildChatThreadKey(chatId, threadId);\n const { results } = global.localTextSearch.byChatThreadKey[chatThreadKey] || {};\n const prevFoundIds = (results && results.foundIds) || [];\n const foundIds = orderFoundIds(unique(Array.prototype.concat(prevFoundIds, newFoundIds)));\n const foundOrPrevFoundIds = areSortedArraysEqual(prevFoundIds, foundIds) ? prevFoundIds : foundIds;\n\n return replaceLocalTextSearchResults(global, chatId, threadId, foundOrPrevFoundIds, totalCount, nextOffsetId);\n}\n\nfunction replaceLocalMediaSearch(\n global: GlobalState,\n chatId: number,\n searchParams: MediaSearchParams,\n): GlobalState {\n return {\n ...global,\n localMediaSearch: {\n byChatId: {\n ...global.localMediaSearch.byChatId,\n [chatId]: searchParams,\n },\n },\n };\n}\n\nexport function updateLocalMediaSearchType(\n global: GlobalState,\n chatId: number,\n currentType: SharedMediaType | undefined,\n): GlobalState {\n return replaceLocalMediaSearch(global, chatId, {\n ...global.localMediaSearch.byChatId[chatId],\n currentType,\n });\n}\n\nexport function replaceLocalMediaSearchResults(\n global: GlobalState,\n chatId: number,\n type: ApiMessageSearchType,\n foundIds?: number[],\n totalCount?: number,\n nextOffsetId?: number,\n): GlobalState {\n return replaceLocalMediaSearch(global, chatId, {\n ...global.localMediaSearch.byChatId[chatId],\n resultsByType: {\n ...(global.localMediaSearch.byChatId[chatId] || {}).resultsByType,\n [type]: {\n foundIds,\n totalCount,\n nextOffsetId,\n },\n },\n });\n}\n\nexport function updateLocalMediaSearchResults(\n global: GlobalState,\n chatId: number,\n type: SharedMediaType,\n newFoundIds: number[],\n totalCount?: number,\n nextOffsetId?: number,\n): GlobalState {\n const { resultsByType } = global.localMediaSearch.byChatId[chatId] || {};\n const prevFoundIds = resultsByType && resultsByType[type] ? resultsByType[type]!.foundIds : [];\n const foundIds = orderFoundIds(unique(Array.prototype.concat(prevFoundIds, newFoundIds)));\n const foundOrPrevFoundIds = areSortedArraysEqual(prevFoundIds, foundIds) ? prevFoundIds : foundIds;\n\n return replaceLocalMediaSearchResults(global, chatId, type, foundOrPrevFoundIds, totalCount, nextOffsetId);\n}\n\nfunction orderFoundIds(listedIds: number[]) {\n return listedIds.sort((a, b) => a - b);\n}\n","import { GlobalState } from '../../global/types';\nimport { ManagementProgress } from '../../types';\n\ninterface ManagementState {\n isActive: boolean;\n isUsernameAvailable?: boolean;\n error?: string;\n}\n\nexport function updateManagementProgress(global: GlobalState, progress: ManagementProgress): GlobalState {\n return {\n ...global,\n management: {\n ...global.management,\n progress,\n },\n };\n}\n\nexport function updateManagement(global: GlobalState, chatId: number, update: Partial<ManagementState>): GlobalState {\n return {\n ...global,\n management: {\n ...global.management,\n byChatId: {\n ...global.management.byChatId,\n [chatId]: {\n ...(global.management.byChatId[chatId] || {}),\n ...update,\n },\n },\n },\n };\n}\n","import { GlobalState } from '../../global/types';\nimport {\n ISettings, IThemeSettings, ThemeKey, NotifyException,\n} from '../../types';\nimport { ApiNotifyException } from '../../api/types';\nimport { updateUserBlockedState } from './users';\n\nexport function replaceSettings(global: GlobalState, newSettings?: Partial<ISettings>): GlobalState {\n return {\n ...global,\n settings: {\n ...global.settings,\n byKey: {\n ...global.settings.byKey,\n ...newSettings,\n },\n },\n };\n}\n\nexport function replaceThemeSettings(\n global: GlobalState, theme: ThemeKey, newSettings?: Partial<IThemeSettings>,\n): GlobalState {\n return {\n ...global,\n settings: {\n ...global.settings,\n themes: {\n ...global.settings.themes,\n [theme]: {\n ...(global.settings.themes[theme] || {}),\n ...newSettings,\n },\n },\n },\n };\n}\n\nexport function addNotifyExceptions(\n global: GlobalState, notifyExceptions: ApiNotifyException[],\n): GlobalState {\n notifyExceptions.forEach((notifyException) => {\n const { chatId, ...exceptionData } = notifyException;\n global = addNotifyException(global, chatId, exceptionData);\n });\n\n return global;\n}\n\nexport function addNotifyException(\n global: GlobalState, id: number, notifyException: NotifyException,\n): GlobalState {\n return {\n ...global,\n settings: {\n ...global.settings,\n notifyExceptions: {\n ...global.settings.notifyExceptions,\n [id]: notifyException,\n },\n },\n };\n}\n\nexport function updateNotifySettings(\n global: GlobalState, peerType: 'contact' | 'group' | 'broadcast', isSilent?: boolean, shouldShowPreviews?: boolean,\n) {\n switch (peerType) {\n case 'contact':\n return replaceSettings(global, {\n ...(typeof isSilent !== 'undefined' && { hasPrivateChatsNotifications: !isSilent }),\n ...(typeof shouldShowPreviews !== 'undefined' && { hasPrivateChatsMessagePreview: shouldShowPreviews }),\n });\n case 'group':\n return replaceSettings(global, {\n ...(typeof isSilent !== 'undefined' && { hasGroupNotifications: !isSilent }),\n ...(typeof shouldShowPreviews !== 'undefined' && { hasGroupMessagePreview: shouldShowPreviews }),\n });\n case 'broadcast':\n return replaceSettings(global, {\n ...(typeof isSilent !== 'undefined' && { hasBroadcastNotifications: !isSilent }),\n ...(typeof shouldShowPreviews !== 'undefined' && { hasBroadcastMessagePreview: shouldShowPreviews }),\n });\n\n default:\n return undefined;\n }\n}\n\nexport function addBlockedContact(global: GlobalState, contactId: number): GlobalState {\n global = updateUserBlockedState(global, contactId, true);\n\n return {\n ...global,\n blocked: {\n ...global.blocked,\n ids: [contactId, ...global.blocked.ids],\n totalCount: global.blocked.totalCount + 1,\n },\n };\n}\n\nexport function removeBlockedContact(global: GlobalState, contactId: number): GlobalState {\n global = updateUserBlockedState(global, contactId, false);\n\n return {\n ...global,\n blocked: {\n ...global.blocked,\n ids: global.blocked.ids.filter((id) => id !== contactId),\n totalCount: global.blocked.totalCount - 1,\n },\n };\n}\n","import { GlobalState } from '../../global/types';\n\nexport function updateTwoFaSettings(\n global: GlobalState,\n update: GlobalState['twoFaSettings'],\n): GlobalState {\n return {\n ...global,\n twoFaSettings: {\n ...global.twoFaSettings,\n ...update,\n },\n };\n}\n","import { GlobalState } from '../../global/types';\nimport { ShippingOption, PaymentStep } from '../../types';\nimport { ApiMessage, ApiPaymentForm, ApiReceipt } from '../../api/types';\n\nexport function updateShippingOptions(\n global: GlobalState,\n shippingOptions: ShippingOption[],\n): GlobalState {\n return {\n ...global,\n payment: {\n ...global.payment,\n shippingOptions,\n },\n };\n}\n\nexport function setRequestInfoId(global: GlobalState, id: string): GlobalState {\n return {\n ...global,\n payment: {\n ...global.payment,\n formId: id,\n },\n };\n}\n\nexport function setPaymentStep(global: GlobalState, step: PaymentStep): GlobalState {\n return {\n ...global,\n payment: {\n ...global.payment,\n step,\n },\n };\n}\n\nexport function setInvoiceMessageInfo(global: GlobalState, message: ApiMessage): GlobalState {\n if (!message.content || !message.content.invoice) {\n return global;\n }\n const {\n title,\n text,\n description,\n photoUrl,\n } = message.content.invoice;\n return {\n ...global,\n payment: {\n ...global.payment,\n invoiceContent: {\n title,\n text,\n description,\n photoUrl,\n },\n },\n };\n}\n\nexport function setStripeCardInfo(global: GlobalState, cardInfo: { type: string; id: string }): GlobalState {\n return {\n ...global,\n payment: {\n ...global.payment,\n stripeCredentials: {\n ...cardInfo,\n },\n },\n };\n}\n\nexport function setPaymentForm(global: GlobalState, form: ApiPaymentForm): GlobalState {\n return {\n ...global,\n payment: {\n ...global.payment,\n ...form,\n },\n };\n}\n\nexport function setReceipt(\n global: GlobalState,\n receipt?: ApiReceipt,\n message?: ApiMessage,\n): GlobalState {\n if (!receipt || !message) {\n return {\n ...global,\n payment: {\n ...global.payment,\n receipt: undefined,\n },\n };\n }\n\n const { invoice: messageInvoice } = message.content;\n const { photoUrl, text, title } = (messageInvoice || {});\n\n return {\n ...global,\n payment: {\n ...global.payment,\n receipt: {\n ...receipt,\n photoUrl,\n text,\n title,\n },\n },\n };\n}\n\nexport function clearPayment(global: GlobalState): GlobalState {\n return {\n ...global,\n payment: {},\n };\n}\n\nexport function closeInvoice(global: GlobalState): GlobalState {\n return {\n ...global,\n payment: {\n ...global.payment,\n isPaymentModalOpen: false,\n },\n };\n}\n","// eslint-disable-next-line no-restricted-globals\nconst cacheApi = self.caches;\n\nexport enum Type {\n Text,\n Blob,\n Json,\n}\n\nexport async function fetch(cacheName: string, key: string, type: Type) {\n if (!cacheApi) {\n return undefined;\n }\n\n try {\n // To avoid the error \"Request scheme 'webdocument' is unsupported\"\n const request = new Request(key.replace(/:/g, '_'));\n const cache = await cacheApi.open(cacheName);\n const response = await cache.match(request);\n if (!response) {\n return undefined;\n }\n\n switch (type) {\n case Type.Text:\n return await response.text();\n case Type.Blob: {\n const blob = await response.blob();\n\n // Safari does not return correct Content-Type header for webp images.\n if (key.substr(0, 7) === 'sticker') {\n return new Blob([blob], { type: 'image/webp' });\n }\n\n // iOS Safari fails to preserve `type` in cache\n if (!blob.type) {\n const contentType = response.headers.get('Content-Type');\n if (contentType) {\n return new Blob([blob], { type: contentType });\n }\n }\n\n return blob;\n }\n case Type.Json:\n return await response.json();\n default:\n return undefined;\n }\n } catch (err) {\n // eslint-disable-next-line no-console\n console.warn(err);\n return undefined;\n }\n}\n\nexport async function save(cacheName: string, key: string, data: AnyLiteral | Blob | string) {\n if (!cacheApi) {\n return undefined;\n }\n\n try {\n const cacheData = typeof data === 'string' || data instanceof Blob ? data : JSON.stringify(data);\n // To avoid the error \"Request scheme 'webdocument' is unsupported\"\n const request = new Request(key.replace(/:/g, '_'));\n const response = new Response(cacheData);\n const cache = await cacheApi.open(cacheName);\n return await cache.put(request, response);\n } catch (err) {\n // eslint-disable-next-line no-console\n console.warn(err);\n return undefined;\n }\n}\n\nexport async function clear(cacheName: string) {\n try {\n if (!cacheApi) {\n return undefined;\n }\n\n return await cacheApi.delete(cacheName);\n } catch (err) {\n // eslint-disable-next-line no-console\n console.warn(err);\n return undefined;\n }\n}\n","import {\n ApiBotInlineMediaResult, ApiBotInlineResult, ApiBotInlineSwitchPm,\n ApiLanguage, ApiMessage, ApiShippingAddress, ApiStickerSet,\n} from '../api/types';\n\nexport enum LoadMoreDirection {\n Backwards,\n Forwards,\n Around,\n}\n\nexport enum FocusDirection {\n Up,\n Down,\n Static,\n}\n\nexport interface IAlbum {\n albumId: string;\n messages: ApiMessage[];\n mainMessage: ApiMessage;\n}\n\nexport type ThemeKey = 'light' | 'dark';\n\nexport interface IThemeSettings {\n background?: string;\n backgroundColor?: string;\n patternColor?: string;\n isBlurred?: boolean;\n}\n\nexport type NotifySettings = {\n hasPrivateChatsNotifications?: boolean;\n hasPrivateChatsMessagePreview?: boolean;\n hasGroupNotifications?: boolean;\n hasGroupMessagePreview?: boolean;\n hasBroadcastNotifications?: boolean;\n hasBroadcastMessagePreview?: boolean;\n hasContactJoinedNotifications?: boolean;\n hasWebNotifications: boolean;\n hasPushNotifications: boolean;\n notificationSoundVolume: number;\n};\n\nexport type LangCode = (\n 'en' | 'ar' | 'be' | 'ca' | 'nl' | 'fr' | 'de' | 'id' | 'it' | 'ko' | 'ms' | 'fa' | 'pl' | 'pt-br' | 'ru' | 'es'\n | 'tr' | 'uk' | 'uz'\n);\n\nexport interface ISettings extends NotifySettings, Record<string, any> {\n theme: ThemeKey;\n shouldUseSystemTheme: boolean;\n messageTextSize: number;\n animationLevel: 0 | 1 | 2;\n messageSendKeyCombo: 'enter' | 'ctrl-enter';\n shouldAutoDownloadMediaFromContacts: boolean;\n shouldAutoDownloadMediaInPrivateChats: boolean;\n shouldAutoDownloadMediaInGroups: boolean;\n shouldAutoDownloadMediaInChannels: boolean;\n shouldAutoPlayGifs: boolean;\n shouldAutoPlayVideos: boolean;\n shouldSuggestStickers: boolean;\n shouldLoopStickers: boolean;\n hasPassword?: boolean;\n languages?: ApiLanguage[];\n language: LangCode;\n isSensitiveEnabled?: boolean;\n canChangeSensitive?: boolean;\n}\n\nexport interface ApiPrivacySettings {\n visibility: PrivacyVisibility;\n allowUserIds: number[];\n allowChatIds: number[];\n blockUserIds: number[];\n blockChatIds: number[];\n}\n\nexport interface IInputPrivacyContact {\n id: number;\n accessHash?: string;\n}\n\nexport interface IInputPrivacyRules {\n visibility: PrivacyVisibility;\n allowedUsers?: IInputPrivacyContact[];\n allowedChats?: IInputPrivacyContact[];\n blockedUsers?: IInputPrivacyContact[];\n blockedChats?: IInputPrivacyContact[];\n}\n\nexport type IAnchorPosition = {\n x: number;\n y: number;\n};\n\nexport interface ShippingOption {\n id: string;\n title: string;\n amount: number;\n prices: Price[];\n}\n\nexport interface Price {\n label: string;\n amount: number;\n}\n\nexport interface Invoice {\n currency?: string;\n emailRequested?: boolean;\n emailToProvider?: boolean;\n flexible?: boolean;\n nameRequested?: boolean;\n phoneRequested?: boolean;\n phoneToProvider?: boolean;\n prices?: Price[];\n shippingAddressRequested?: boolean;\n test?: boolean;\n}\n\nexport interface Receipt {\n currency: string;\n prices: Price[];\n info?: {\n shippingAddress?: ApiShippingAddress;\n phone?: string;\n name?: string;\n };\n totalAmount: number;\n credentialsTitle: string;\n shippingPrices?: Price[];\n shippingMethod?: string;\n photoUrl?: string;\n text?: string;\n title?: string;\n}\n\nexport enum SettingsScreens {\n Main,\n EditProfile,\n Notifications,\n Language,\n General,\n GeneralChatBackground,\n GeneralChatBackgroundColor,\n Privacy,\n PrivacyPhoneNumber,\n PrivacyLastSeen,\n PrivacyProfilePhoto,\n PrivacyForwarding,\n PrivacyGroupChats,\n PrivacyPhoneNumberAllowedContacts,\n PrivacyPhoneNumberDeniedContacts,\n PrivacyLastSeenAllowedContacts,\n PrivacyLastSeenDeniedContacts,\n PrivacyProfilePhotoAllowedContacts,\n PrivacyProfilePhotoDeniedContacts,\n PrivacyForwardingAllowedContacts,\n PrivacyForwardingDeniedContacts,\n PrivacyGroupChatsAllowedContacts,\n PrivacyGroupChatsDeniedContacts,\n PrivacyActiveSessions,\n PrivacyBlockedUsers,\n Folders,\n FoldersCreateFolder,\n FoldersEditFolder,\n FoldersEditFolderFromChatList,\n FoldersIncludedChats,\n FoldersIncludedChatsFromChatList,\n FoldersExcludedChats,\n FoldersExcludedChatsFromChatList,\n TwoFaDisabled,\n TwoFaNewPassword,\n TwoFaNewPasswordConfirm,\n TwoFaNewPasswordHint,\n TwoFaNewPasswordEmail,\n TwoFaNewPasswordEmailCode,\n TwoFaEnabled,\n TwoFaChangePasswordCurrent,\n TwoFaChangePasswordNew,\n TwoFaChangePasswordConfirm,\n TwoFaChangePasswordHint,\n TwoFaTurnOff,\n TwoFaRecoveryEmailCurrentPassword,\n TwoFaRecoveryEmail,\n TwoFaRecoveryEmailCode,\n TwoFaCongratulations,\n}\n\nexport type StickerSetOrRecent = Pick<ApiStickerSet, (\n 'id' | 'title' | 'count' | 'stickers' | 'hasThumbnail' | 'isAnimated'\n)>;\n\nexport enum LeftColumnContent {\n ChatList,\n GlobalSearch,\n Settings,\n Contacts,\n Archived,\n NewChannelStep1,\n NewChannelStep2,\n NewGroupStep1,\n NewGroupStep2,\n}\n\nexport enum GlobalSearchContent {\n ChatList,\n Media,\n Links,\n Files,\n Music,\n Voice,\n}\n\nexport enum RightColumnContent {\n ChatInfo,\n UserInfo,\n Search,\n Management,\n StickerSearch,\n GifSearch,\n PollResults,\n AddingMembers,\n}\n\nexport enum MediaViewerOrigin {\n Inline,\n ScheduledInline,\n SharedMedia,\n ProfileAvatar,\n MiddleHeaderAvatar,\n Album,\n ScheduledAlbum,\n SearchResult,\n}\n\nexport enum ChatCreationProgress {\n Idle,\n InProgress,\n Complete,\n Error,\n}\n\nexport enum ProfileEditProgress {\n Idle,\n InProgress,\n Complete,\n Error,\n}\n\nexport enum ManagementProgress {\n Idle,\n InProgress,\n Complete,\n Error,\n}\n\nexport enum NewChatMembersProgress {\n Closed,\n InProgress,\n Loading,\n}\n\nexport type ProfileTabType = 'members' | 'media' | 'documents' | 'links' | 'audio';\nexport type SharedMediaType = 'media' | 'documents' | 'links' | 'audio';\nexport type ApiPrivacyKey = 'phoneNumber' | 'lastSeen' | 'profilePhoto' | 'forwards' | 'chatInvite';\nexport type PrivacyVisibility = 'everybody' | 'contacts' | 'nonContacts' | 'nobody';\n\nexport enum ProfileState {\n Profile,\n SharedMedia,\n MemberList,\n}\n\nexport enum PaymentStep {\n ShippingInfo,\n Shipping,\n PaymentInfo,\n Checkout\n}\n\nexport const UPLOADING_WALLPAPER_SLUG = 'UPLOADING_WALLPAPER_SLUG';\n\nexport enum ManagementScreens {\n Initial,\n ChatPrivacyType,\n Discussion,\n ChannelSubscribers,\n GroupType,\n GroupPermissions,\n GroupRemovedUsers,\n GroupUserPermissionsCreate,\n GroupUserPermissions,\n ChatAdministrators,\n GroupRecentActions,\n ChatAdminRights,\n GroupMembers,\n}\n\nexport type ManagementType = 'user' | 'group' | 'channel';\n\nexport type NotifyException = {\n isMuted: boolean;\n isSilent?: boolean;\n shouldShowPreviews?: boolean;\n};\n\nexport type EmojiKeywords = {\n isLoading?: boolean;\n version: number;\n keywords: Record<string, string[]>;\n};\n\nexport type InlineBotSettings = {\n id: number;\n help?: string;\n query?: string;\n offset?: string;\n canLoadMore?: boolean;\n results?: (ApiBotInlineResult | ApiBotInlineMediaResult)[];\n isGallery?: boolean;\n switchPm?: ApiBotInlineSwitchPm;\n};\n","import { ApiLangPack, ApiLangString } from '../api/types';\n\nimport {\n DEFAULT_LANG_CODE, DEFAULT_LANG_PACK, LANG_CACHE_NAME, LANG_PACKS,\n} from '../config';\nimport * as cacheApi from './cacheApi';\nimport { callApi } from '../api/gramjs';\nimport { createCallbackManager } from './callbacks';\nimport { formatInteger } from './textFormat';\nimport { getGlobal } from '../lib/teact/teactn';\n\ninterface LangFn {\n (key: string, value?: any, format?: 'i'): any;\n\n isRtl?: boolean;\n code?: string;\n}\n\nconst SUBSTITUTION_REGEX = /%\\d?\\$?[sdf@]/g;\nconst PLURAL_OPTIONS = ['value', 'zeroValue', 'oneValue', 'twoValue', 'fewValue', 'manyValue', 'otherValue'] as const;\nconst PLURAL_RULES = {\n /* eslint-disable max-len */\n en: (n: number) => (n !== 1 ? 6 : 2),\n ar: (n: number) => (n === 0 ? 1 : n === 1 ? 2 : n === 2 ? 3 : n % 100 >= 3 && n % 100 <= 10 ? 4 : n % 100 >= 11 ? 5 : 6),\n ca: (n: number) => (n !== 1 ? 6 : 2),\n de: (n: number) => (n !== 1 ? 6 : 2),\n es: (n: number) => (n !== 1 ? 6 : 2),\n fa: (n: number) => (n > 1 ? 6 : 2),\n fr: (n: number) => (n > 1 ? 6 : 2),\n id: () => 0,\n it: (n: number) => (n !== 1 ? 6 : 2),\n ko: () => 0,\n ms: () => 0,\n nl: (n: number) => (n !== 1 ? 6 : 2),\n pl: (n: number) => (n === 1 ? 2 : n % 10 >= 2 && n % 10 <= 4 && (n % 100 < 10 || n % 100 >= 20) ? 4 : 5),\n pt_BR: (n: number) => (n > 1 ? 6 : 2),\n ru: (n: number) => (n % 10 === 1 && n % 100 !== 11 ? 2 : n % 10 >= 2 && n % 10 <= 4 && (n % 100 < 10 || n % 100 >= 20) ? 4 : 5),\n tr: (n: number) => (n > 1 ? 6 : 2),\n uk: (n: number) => (n % 10 === 1 && n % 100 !== 11 ? 2 : n % 10 >= 2 && n % 10 <= 4 && (n % 100 < 10 || n % 100 >= 20) ? 4 : 5),\n uz: (n: number) => (n > 1 ? 6 : 2),\n /* eslint-enable max-len */\n};\n\nconst cache = new Map<string, string>();\n\nlet langPack: ApiLangPack | undefined;\nlet fallbackLangPack: ApiLangPack | undefined;\n\nconst {\n addCallback,\n removeCallback,\n runCallbacks,\n} = createCallbackManager();\n\nexport { addCallback, removeCallback };\n\nlet currentLangCode: string | undefined;\n\nexport const getTranslation: LangFn = (key: string, value?: any, format?: 'i') => {\n if (value !== undefined) {\n const cacheValue = Array.isArray(value) ? JSON.stringify(value) : value;\n const cached = cache.get(`${key}_${cacheValue}_${format}`);\n if (cached) {\n return cached;\n }\n }\n\n if (!langPack && !fallbackLangPack) {\n return key;\n }\n\n const langString = (langPack && langPack[key]) || (fallbackLangPack && fallbackLangPack[key]);\n if (!langString) {\n if (!fallbackLangPack) {\n void importFallbackLangPack();\n }\n\n return key;\n }\n\n return processTranslation(langString, key, value, format);\n};\n\nexport async function getTranslationForLangString(langCode: string, key: string) {\n let translateString = await cacheApi.fetch(\n LANG_CACHE_NAME,\n `${DEFAULT_LANG_PACK}_${langCode}_${key}`,\n cacheApi.Type.Json,\n );\n\n if (!translateString) {\n translateString = await fetchRemoteString(DEFAULT_LANG_PACK, langCode, key);\n }\n\n return processTranslation(translateString, key);\n}\n\nexport async function setLanguage(langCode: string, callback?: NoneToVoidFunction, withFallback = false) {\n if (langPack && langCode === currentLangCode) {\n if (callback) {\n callback();\n }\n\n return;\n }\n\n let newLangPack = await cacheApi.fetch(LANG_CACHE_NAME, langCode, cacheApi.Type.Json);\n if (!newLangPack) {\n if (withFallback) {\n await importFallbackLangPack();\n }\n\n newLangPack = await fetchRemote(langCode);\n if (!newLangPack) {\n return;\n }\n }\n\n cache.clear();\n\n currentLangCode = langCode;\n langPack = newLangPack;\n document.documentElement.lang = langCode;\n\n const { languages } = getGlobal().settings.byKey;\n const langInfo = languages ? languages.find((l) => l.langCode === langCode) : undefined;\n getTranslation.isRtl = Boolean(langInfo && langInfo.rtl);\n getTranslation.code = langCode;\n\n if (callback) {\n callback();\n }\n\n runCallbacks();\n}\n\nasync function importFallbackLangPack() {\n if (fallbackLangPack) {\n return;\n }\n\n fallbackLangPack = (await import('./fallbackLangPack')).default;\n runCallbacks();\n}\n\nasync function fetchRemote(langCode: string): Promise<ApiLangPack | undefined> {\n const remote = await callApi('fetchLangPack', { sourceLangPacks: LANG_PACKS, langCode });\n if (remote) {\n await cacheApi.save(LANG_CACHE_NAME, langCode, remote.langPack);\n return remote.langPack;\n }\n\n return undefined;\n}\n\nasync function fetchRemoteString(\n remoteLangPack: typeof LANG_PACKS[number], langCode: string, key: string,\n): Promise<string | undefined> {\n const remote = await callApi('fetchLangStrings', {\n langPack: remoteLangPack,\n langCode,\n keys: [key],\n });\n\n if (remote && remote.length) {\n await cacheApi.save(LANG_CACHE_NAME, `${remoteLangPack}_${langCode}_${key}`, remote[0]);\n\n return remote[0];\n }\n\n return undefined;\n}\n\nfunction getPluralOption(amount: number) {\n const langCode = currentLangCode || DEFAULT_LANG_CODE;\n const optionIndex = PLURAL_RULES[langCode as keyof typeof PLURAL_RULES]\n ? PLURAL_RULES[langCode as keyof typeof PLURAL_RULES](amount)\n : 0;\n\n return PLURAL_OPTIONS[optionIndex];\n}\n\nfunction processTemplate(template: string, value: any) {\n value = Array.isArray(value) ? value : [value];\n const translationSlices = template.split(SUBSTITUTION_REGEX);\n const initialValue = translationSlices.shift();\n\n return translationSlices.reduce((result, str, index) => {\n return `${result}${String(value[index] || '')}${str}`;\n }, initialValue || '');\n}\n\nfunction processTranslation(langString: ApiLangString | undefined, key: string, value?: any, format?: 'i') {\n const template = langString ? langString[typeof value === 'number' ? getPluralOption(value) : 'value'] : undefined;\n if (!template || !template.trim()) {\n const parts = key.split('.');\n\n return parts[parts.length - 1];\n }\n\n if (value !== undefined) {\n const formattedValue = format === 'i' ? formatInteger(value) : value;\n const result = processTemplate(template, formattedValue);\n const cacheValue = Array.isArray(value) ? JSON.stringify(value) : value;\n cache.set(`${key}_${cacheValue}_${format}`, result);\n return result;\n }\n\n return template;\n}\n","export function createCallbackManager() {\n const callbacks: AnyToVoidFunction[] = [];\n\n function addCallback(cb: AnyToVoidFunction) {\n callbacks.push(cb);\n\n return () => {\n removeCallback(cb);\n };\n }\n\n function removeCallback(cb: AnyToVoidFunction) {\n const index = callbacks.indexOf(cb);\n if (index !== -1) {\n callbacks.splice(index, 1);\n }\n }\n\n function runCallbacks(...args: any[]) {\n callbacks.forEach((callback) => {\n callback(...args);\n });\n }\n\n return {\n runCallbacks,\n addCallback,\n removeCallback,\n };\n}\n","import { DEBUG } from '../config';\n\nexport enum Bundles {\n Auth,\n Main,\n Extra\n}\n\ninterface ImportedBundles {\n [Bundles.Auth]: typeof import('../bundles/auth');\n [Bundles.Main]: typeof import('../bundles/main');\n [Bundles.Extra]: typeof import('../bundles/extra');\n}\n\ntype BundlePromises = {\n [K in keyof ImportedBundles]: Promise<ImportedBundles[K]>\n};\n\nexport type BundleModules<B extends keyof ImportedBundles> = keyof ImportedBundles[B];\n\nconst LOAD_PROMISES: Partial<BundlePromises> = {};\nconst MEMORY_CACHE: Partial<ImportedBundles> = {};\n\nexport async function loadModule<B extends Bundles, M extends BundleModules<B>>(bundleName: B, moduleName: M) {\n if (!LOAD_PROMISES[bundleName]) {\n switch (bundleName) {\n case Bundles.Auth:\n LOAD_PROMISES[Bundles.Auth] = import('../bundles/auth');\n break;\n case Bundles.Main:\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('>>> START LOAD MAIN BUNDLE');\n }\n\n LOAD_PROMISES[Bundles.Main] = import('../bundles/main');\n break;\n case Bundles.Extra:\n LOAD_PROMISES[Bundles.Extra] = import('../bundles/extra');\n break;\n }\n\n (LOAD_PROMISES[bundleName] as Promise<ImportedBundles[B]>).then(handleBundleLoad);\n }\n\n const bundle = (await LOAD_PROMISES[bundleName]) as unknown as ImportedBundles[B];\n\n if (!MEMORY_CACHE[bundleName]) {\n MEMORY_CACHE[bundleName] = bundle;\n }\n\n return getModuleFromMemory(bundleName, moduleName);\n}\n\nexport function getModuleFromMemory<B extends Bundles, M extends BundleModules<B>>(bundleName: B, moduleName: M) {\n const bundle = MEMORY_CACHE[bundleName] as ImportedBundles[B];\n\n if (!bundle) {\n return undefined;\n }\n\n return bundle[moduleName];\n}\n\nconst listeners: NoneToVoidFunction[] = [];\n\nexport function addLoadListener(listener: NoneToVoidFunction) {\n if (!listeners.includes(listener)) {\n listeners.push(listener);\n }\n}\n\nfunction handleBundleLoad() {\n listeners.forEach((listener) => {\n listener();\n });\n}\n","function promisifyRequest(request) {\n return new Promise((resolve, reject) => {\n // @ts-ignore - file size hacks\n request.oncomplete = request.onsuccess = () => resolve(request.result);\n // @ts-ignore - file size hacks\n request.onabort = request.onerror = () => reject(request.error);\n });\n}\nfunction createStore(dbName, storeName) {\n const request = indexedDB.open(dbName);\n request.onupgradeneeded = () => request.result.createObjectStore(storeName);\n const dbp = promisifyRequest(request);\n return (txMode, callback) => dbp.then((db) => callback(db.transaction(storeName, txMode).objectStore(storeName)));\n}\nlet defaultGetStoreFunc;\nfunction defaultGetStore() {\n if (!defaultGetStoreFunc) {\n defaultGetStoreFunc = createStore('keyval-store', 'keyval');\n }\n return defaultGetStoreFunc;\n}\n/**\n * Get a value by its key.\n *\n * @param key\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction get(key, customStore = defaultGetStore()) {\n return customStore('readonly', (store) => promisifyRequest(store.get(key)));\n}\n/**\n * Set a value with a key.\n *\n * @param key\n * @param value\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction set(key, value, customStore = defaultGetStore()) {\n return customStore('readwrite', (store) => {\n store.put(value, key);\n return promisifyRequest(store.transaction);\n });\n}\n/**\n * Set multiple values at once. This is faster than calling set() multiple times.\n * It's also atomic – if one of the pairs can't be added, none will be added.\n *\n * @param entries Array of entries, where each entry is an array of `[key, value]`.\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction setMany(entries, customStore = defaultGetStore()) {\n return customStore('readwrite', (store) => {\n entries.forEach((entry) => store.put(entry[1], entry[0]));\n return promisifyRequest(store.transaction);\n });\n}\n/**\n * Get multiple values by their keys\n *\n * @param keys\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction getMany(keys, customStore = defaultGetStore()) {\n return customStore('readonly', (store) => Promise.all(keys.map((key) => promisifyRequest(store.get(key)))));\n}\n/**\n * Update a value. This lets you see the old value and update it as an atomic operation.\n *\n * @param key\n * @param updater A callback that takes the old value and returns a new value.\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction update(key, updater, customStore = defaultGetStore()) {\n return customStore('readwrite', (store) => \n // Need to create the promise manually.\n // If I try to chain promises, the transaction closes in browsers\n // that use a promise polyfill (IE10/11).\n new Promise((resolve, reject) => {\n store.get(key).onsuccess = function () {\n try {\n store.put(updater(this.result), key);\n resolve(promisifyRequest(store.transaction));\n }\n catch (err) {\n reject(err);\n }\n };\n }));\n}\n/**\n * Delete a particular key from the store.\n *\n * @param key\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction del(key, customStore = defaultGetStore()) {\n return customStore('readwrite', (store) => {\n store.delete(key);\n return promisifyRequest(store.transaction);\n });\n}\n/**\n * Clear all values in the store.\n *\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction clear(customStore = defaultGetStore()) {\n return customStore('readwrite', (store) => {\n store.clear();\n return promisifyRequest(store.transaction);\n });\n}\nfunction eachCursor(customStore, callback) {\n return customStore('readonly', (store) => {\n // This would be store.getAllKeys(), but it isn't supported by Edge or Safari.\n // And openKeyCursor isn't supported by Safari.\n store.openCursor().onsuccess = function () {\n if (!this.result)\n return;\n callback(this.result);\n this.result.continue();\n };\n return promisifyRequest(store.transaction);\n });\n}\n/**\n * Get all keys in the store.\n *\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction keys(customStore = defaultGetStore()) {\n const items = [];\n return eachCursor(customStore, (cursor) => items.push(cursor.key)).then(() => items);\n}\n/**\n * Get all values in the store.\n *\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction values(customStore = defaultGetStore()) {\n const items = [];\n return eachCursor(customStore, (cursor) => items.push(cursor.value)).then(() => items);\n}\n/**\n * Get all entries in the store. Each entry is an array of `[key, value]`.\n *\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction entries(customStore = defaultGetStore()) {\n const items = [];\n return eachCursor(customStore, (cursor) => items.push([cursor.key, cursor.value])).then(() => items);\n}\n\nexport { clear, createStore, del, entries, get, getMany, keys, promisifyRequest, set, setMany, update, values };\n","import * as idb from 'idb-keyval';\n\nimport { ApiSessionData } from '../api/types';\n\nimport { DEBUG, LEGACY_SESSION_KEY, SESSION_USER_KEY } from '../config';\nimport * as cacheApi from './cacheApi';\n\nconst DC_IDS = [1, 2, 3, 4, 5];\n\nexport function hasStoredSession(withLegacy = false) {\n if (withLegacy && localStorage.getItem(LEGACY_SESSION_KEY)) {\n return true;\n }\n\n const userAuthJson = localStorage.getItem(SESSION_USER_KEY);\n if (!userAuthJson) return false;\n\n try {\n const userAuth = JSON.parse(userAuthJson);\n return Boolean(userAuth && userAuth.id && userAuth.dcID);\n } catch (err) {\n // Do nothing.\n return false;\n }\n}\n\nexport function storeSession(sessionData: ApiSessionData, currentUserId?: number) {\n const { mainDcId, keys, hashes } = sessionData;\n\n localStorage.setItem(SESSION_USER_KEY, JSON.stringify({ dcID: mainDcId, id: currentUserId }));\n localStorage.setItem('dc', String(mainDcId));\n Object.keys(keys).map(Number).forEach((dcId) => {\n localStorage.setItem(`dc${dcId}_auth_key`, JSON.stringify(keys[dcId]));\n });\n Object.keys(hashes).map(Number).forEach((dcId) => {\n localStorage.setItem(`dc${dcId}_hash`, JSON.stringify(hashes[dcId]));\n });\n}\n\nexport function clearStoredSession() {\n [\n SESSION_USER_KEY,\n 'dc',\n ...DC_IDS.map((dcId) => `dc${dcId}_auth_key`),\n ...DC_IDS.map((dcId) => `dc${dcId}_hash`),\n ].forEach((key) => {\n localStorage.removeItem(key);\n });\n}\n\nexport function loadStoredSession(): ApiSessionData | undefined {\n if (!hasStoredSession()) {\n return undefined;\n }\n\n const userAuth = JSON.parse(localStorage.getItem(SESSION_USER_KEY)!);\n const mainDcId = Number(userAuth.dcID);\n const keys: Record<number, string> = {};\n const hashes: Record<number, string> = {};\n\n DC_IDS.forEach((dcId) => {\n try {\n const key = localStorage.getItem(`dc${dcId}_auth_key`);\n if (key) {\n keys[dcId] = JSON.parse(key);\n }\n\n const hash = localStorage.getItem(`dc${dcId}_hash`);\n if (hash) {\n hashes[dcId] = JSON.parse(hash);\n }\n } catch (err) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.warn('Failed to load stored session', err);\n }\n // Do nothing.\n }\n });\n\n if (!Object.keys(keys).length) return undefined;\n\n return {\n mainDcId,\n keys,\n hashes,\n };\n}\n\nexport async function importLegacySession() {\n const sessionId = localStorage.getItem(LEGACY_SESSION_KEY);\n if (!sessionId) return;\n\n const sessionJson = await idb.get(`GramJs:${sessionId}`);\n try {\n const sessionData = JSON.parse(sessionJson) as ApiSessionData;\n storeSession(sessionData);\n } catch (err) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.warn('Failed to load legacy session', err);\n }\n // Do nothing.\n }\n}\n\n// Remove previously created IndexedDB and cache API sessions\nexport async function clearLegacySessions() {\n localStorage.removeItem(LEGACY_SESSION_KEY);\n\n const idbKeys = await idb.keys();\n\n await Promise.all<Promise<any>>([\n cacheApi.clear('GramJs'),\n ...idbKeys\n .filter((k) => typeof k === 'string' && k.startsWith('GramJs:GramJs-session-'))\n .map((k) => idb.del(k)),\n ]);\n}\n\nexport function importTestSession() {\n const sessionJson = process.env.TEST_SESSION!;\n try {\n const sessionData = JSON.parse(sessionJson) as ApiSessionData & { userId: number };\n storeSession(sessionData, sessionData.userId);\n } catch (err) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.warn('Failed to load test session', err);\n }\n // Do nothing.\n }\n}\n","import { pause } from './schedulers';\n\n// Polyfill for Safari: `File` is not available in web worker\nif (typeof File === 'undefined') {\n // eslint-disable-next-line no-global-assign, no-restricted-globals, func-names\n self.File = class extends Blob {\n name: string;\n\n constructor(fileBits: BlobPart[], fileName: string, options?: FilePropertyBag) {\n if (options) {\n const { type, ...rest } = options;\n super(fileBits, { type });\n Object.assign(this, rest);\n } else {\n super(fileBits);\n }\n\n this.name = fileName;\n }\n } as typeof File;\n}\n\nexport function dataUriToBlob(dataUri: string) {\n const arr = dataUri.split(',');\n const mime = arr[0].match(/:(.*?);/)![1];\n const bstr = atob(arr[1]);\n let n = bstr.length;\n const u8arr = new Uint8Array(n);\n\n while (n--) {\n u8arr[n] = bstr.charCodeAt(n);\n }\n\n return new Blob([u8arr], { type: mime });\n}\n\nexport function blobToDataUri(blob: Blob): Promise<string> {\n return new Promise((resolve, reject) => {\n const reader = new FileReader();\n\n reader.onload = (e: ProgressEvent<FileReader>) => {\n const { result } = e.target || {};\n if (typeof result === 'string') {\n resolve(result);\n }\n\n reject(new Error('Failed to read blob'));\n };\n\n reader.onerror = reject;\n reader.readAsDataURL(blob);\n });\n}\n\nexport function blobToFile(blob: Blob, fileName: string) {\n return new File([blob], fileName, {\n lastModified: Date.now(),\n type: blob.type,\n });\n}\n\nexport function preloadImage(url: string): Promise<HTMLImageElement> {\n return new Promise((resolve, reject) => {\n const img = new Image();\n img.onload = () => resolve(img);\n img.onerror = reject;\n img.src = url;\n });\n}\n\nexport function preloadVideo(url: string): Promise<HTMLVideoElement> {\n return new Promise((resolve, reject) => {\n const video = document.createElement('video');\n video.volume = 0;\n video.onloadedmetadata = () => resolve(video);\n video.onerror = reject;\n video.src = url;\n });\n}\n\nexport async function createPosterForVideo(url: string): Promise<string | undefined> {\n const video = await preloadVideo(url);\n\n return Promise.race([\n pause(2000) as Promise<undefined>,\n new Promise<string>((resolve, reject) => {\n video.onseeked = () => {\n if (!video.videoWidth || !video.videoHeight) {\n resolve(undefined);\n }\n\n const canvas = document.createElement('canvas');\n canvas.width = video.videoWidth;\n canvas.height = video.videoHeight;\n const ctx = canvas.getContext('2d')!;\n ctx.drawImage(video, 0, 0);\n resolve(canvas.toDataURL('image/jpeg'));\n };\n video.onerror = reject;\n video.currentTime = Math.min(video.duration, 1);\n }),\n ]);\n}\n\nexport async function fetchBlob(blobUrl: string) {\n const response = await fetch(blobUrl);\n return response.blob();\n}\n\nexport async function fetchFile(blobUrl: string, fileName: string) {\n const blob = await fetchBlob(blobUrl);\n return blobToFile(blob, fileName);\n}\n\nexport function imgToCanvas(img: HTMLImageElement) {\n const canvas = document.createElement('canvas');\n canvas.width = img.width;\n canvas.height = img.height;\n\n const ctx = canvas.getContext('2d')!;\n ctx.drawImage(img, 0, 0);\n\n return canvas;\n}\n","import { ApiMediaFormat } from '../api/types';\n\nimport * as langProvider from '../util/langProvider';\nimport useForceUpdate from './useForceUpdate';\nimport useOnChange from './useOnChange';\n\nexport type LangFn = typeof langProvider.getTranslation;\n\nexport default <T extends ApiMediaFormat = ApiMediaFormat.BlobUrl>(): LangFn => {\n const forceUpdate = useForceUpdate();\n\n useOnChange(() => {\n return langProvider.addCallback(forceUpdate);\n }, [forceUpdate]);\n\n return langProvider.getTranslation;\n};\n","// Copyright Twitter Inc. Licensed under MIT\n// https://github.com/twitter/twemoji-parser/blob/master/LICENSE.md\n// Version 2c193ce 28.05.2021\n\nconst vs16RegExp = /\\uFE0F/g;\n// avoid using a string literal like '\\u200D' here because minifiers expand it inline\nconst zeroWidthJoiner = String.fromCharCode(0x200d);\n\nexport function removeVS16s(rawEmoji) {\n return rawEmoji.indexOf(zeroWidthJoiner) < 0 ? rawEmoji.replace(vs16RegExp, '') : rawEmoji;\n}\n\n// This file is generated by source/emoji/scripts/generate.sh\n// eslint-disable-next-line max-len\nexport default /(?:\\ud83d\\udc68\\ud83c\\udffb\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc8b\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc68\\ud83c\\udffc\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc8b\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc68\\ud83c\\udffd\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc8b\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc68\\ud83c\\udffe\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc8b\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc68\\ud83c\\udfff\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc8b\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc69\\ud83c\\udffb\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc8b\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc69\\ud83c\\udffb\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc8b\\u200d\\ud83d\\udc69\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc69\\ud83c\\udffc\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc8b\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc69\\ud83c\\udffc\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc8b\\u200d\\ud83d\\udc69\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc69\\ud83c\\udffd\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc8b\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc69\\ud83c\\udffd\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc8b\\u200d\\ud83d\\udc69\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc69\\ud83c\\udffe\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc8b\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc69\\ud83c\\udffe\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc8b\\u200d\\ud83d\\udc69\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc69\\ud83c\\udfff\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc8b\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc69\\ud83c\\udfff\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc8b\\u200d\\ud83d\\udc69\\ud83c[\\udffb-\\udfff]|\\ud83e\\uddd1\\ud83c\\udffb\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc8b\\u200d\\ud83e\\uddd1\\ud83c[\\udffc-\\udfff]|\\ud83e\\uddd1\\ud83c\\udffc\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc8b\\u200d\\ud83e\\uddd1\\ud83c[\\udffb\\udffd-\\udfff]|\\ud83e\\uddd1\\ud83c\\udffd\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc8b\\u200d\\ud83e\\uddd1\\ud83c[\\udffb\\udffc\\udffe\\udfff]|\\ud83e\\uddd1\\ud83c\\udffe\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc8b\\u200d\\ud83e\\uddd1\\ud83c[\\udffb-\\udffd\\udfff]|\\ud83e\\uddd1\\ud83c\\udfff\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc8b\\u200d\\ud83e\\uddd1\\ud83c[\\udffb-\\udffe]|\\ud83d\\udc68\\ud83c\\udffb\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc68\\ud83c\\udffb\\u200d\\ud83e\\udd1d\\u200d\\ud83d\\udc68\\ud83c[\\udffc-\\udfff]|\\ud83d\\udc68\\ud83c\\udffc\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc68\\ud83c\\udffc\\u200d\\ud83e\\udd1d\\u200d\\ud83d\\udc68\\ud83c[\\udffb\\udffd-\\udfff]|\\ud83d\\udc68\\ud83c\\udffd\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc68\\ud83c\\udffd\\u200d\\ud83e\\udd1d\\u200d\\ud83d\\udc68\\ud83c[\\udffb\\udffc\\udffe\\udfff]|\\ud83d\\udc68\\ud83c\\udffe\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc68\\ud83c\\udffe\\u200d\\ud83e\\udd1d\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udffd\\udfff]|\\ud83d\\udc68\\ud83c\\udfff\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc68\\ud83c\\udfff\\u200d\\ud83e\\udd1d\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udffe]|\\ud83d\\udc69\\ud83c\\udffb\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc69\\ud83c\\udffb\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc69\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc69\\ud83c\\udffb\\u200d\\ud83e\\udd1d\\u200d\\ud83d\\udc68\\ud83c[\\udffc-\\udfff]|\\ud83d\\udc69\\ud83c\\udffb\\u200d\\ud83e\\udd1d\\u200d\\ud83d\\udc69\\ud83c[\\udffc-\\udfff]|\\ud83d\\udc69\\ud83c\\udffc\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc69\\ud83c\\udffc\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc69\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc69\\ud83c\\udffc\\u200d\\ud83e\\udd1d\\u200d\\ud83d\\udc68\\ud83c[\\udffb\\udffd-\\udfff]|\\ud83d\\udc69\\ud83c\\udffc\\u200d\\ud83e\\udd1d\\u200d\\ud83d\\udc69\\ud83c[\\udffb\\udffd-\\udfff]|\\ud83d\\udc69\\ud83c\\udffd\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc69\\ud83c\\udffd\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc69\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc69\\ud83c\\udffd\\u200d\\ud83e\\udd1d\\u200d\\ud83d\\udc68\\ud83c[\\udffb\\udffc\\udffe\\udfff]|\\ud83d\\udc69\\ud83c\\udffd\\u200d\\ud83e\\udd1d\\u200d\\ud83d\\udc69\\ud83c[\\udffb\\udffc\\udffe\\udfff]|\\ud83d\\udc69\\ud83c\\udffe\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc69\\ud83c\\udffe\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc69\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc69\\ud83c\\udffe\\u200d\\ud83e\\udd1d\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udffd\\udfff]|\\ud83d\\udc69\\ud83c\\udffe\\u200d\\ud83e\\udd1d\\u200d\\ud83d\\udc69\\ud83c[\\udffb-\\udffd\\udfff]|\\ud83d\\udc69\\ud83c\\udfff\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc69\\ud83c\\udfff\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc69\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc69\\ud83c\\udfff\\u200d\\ud83e\\udd1d\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udffe]|\\ud83d\\udc69\\ud83c\\udfff\\u200d\\ud83e\\udd1d\\u200d\\ud83d\\udc69\\ud83c[\\udffb-\\udffe]|\\ud83e\\uddd1\\ud83c\\udffb\\u200d\\u2764\\ufe0f\\u200d\\ud83e\\uddd1\\ud83c[\\udffc-\\udfff]|\\ud83e\\uddd1\\ud83c\\udffb\\u200d\\ud83e\\udd1d\\u200d\\ud83e\\uddd1\\ud83c[\\udffb-\\udfff]|\\ud83e\\uddd1\\ud83c\\udffc\\u200d\\u2764\\ufe0f\\u200d\\ud83e\\uddd1\\ud83c[\\udffb\\udffd-\\udfff]|\\ud83e\\uddd1\\ud83c\\udffc\\u200d\\ud83e\\udd1d\\u200d\\ud83e\\uddd1\\ud83c[\\udffb-\\udfff]|\\ud83e\\uddd1\\ud83c\\udffd\\u200d\\u2764\\ufe0f\\u200d\\ud83e\\uddd1\\ud83c[\\udffb\\udffc\\udffe\\udfff]|\\ud83e\\uddd1\\ud83c\\udffd\\u200d\\ud83e\\udd1d\\u200d\\ud83e\\uddd1\\ud83c[\\udffb-\\udfff]|\\ud83e\\uddd1\\ud83c\\udffe\\u200d\\u2764\\ufe0f\\u200d\\ud83e\\uddd1\\ud83c[\\udffb-\\udffd\\udfff]|\\ud83e\\uddd1\\ud83c\\udffe\\u200d\\ud83e\\udd1d\\u200d\\ud83e\\uddd1\\ud83c[\\udffb-\\udfff]|\\ud83e\\uddd1\\ud83c\\udfff\\u200d\\u2764\\ufe0f\\u200d\\ud83e\\uddd1\\ud83c[\\udffb-\\udffe]|\\ud83e\\uddd1\\ud83c\\udfff\\u200d\\ud83e\\udd1d\\u200d\\ud83e\\uddd1\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc68\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc8b\\u200d\\ud83d\\udc68|\\ud83d\\udc69\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc8b\\u200d\\ud83d[\\udc68\\udc69]|\\ud83d\\udc68\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc68|\\ud83d\\udc69\\u200d\\u2764\\ufe0f\\u200d\\ud83d[\\udc68\\udc69]|\\ud83e\\uddd1\\u200d\\ud83e\\udd1d\\u200d\\ud83e\\uddd1|\\ud83d\\udc6b\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc6c\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc6d\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc8f\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc91\\ud83c[\\udffb-\\udfff]|\\ud83d[\\udc6b-\\udc6d\\udc8f\\udc91])|(?:\\ud83d[\\udc68\\udc69]|\\ud83e\\uddd1)(?:\\ud83c[\\udffb-\\udfff])?\\u200d(?:\\u2695\\ufe0f|\\u2696\\ufe0f|\\u2708\\ufe0f|\\ud83c[\\udf3e\\udf73\\udf7c\\udf84\\udf93\\udfa4\\udfa8\\udfeb\\udfed]|\\ud83d[\\udcbb\\udcbc\\udd27\\udd2c\\ude80\\ude92]|\\ud83e[\\uddaf-\\uddb3\\uddbc\\uddbd])|(?:\\ud83c[\\udfcb\\udfcc]|\\ud83d[\\udd74\\udd75]|\\u26f9)((?:\\ud83c[\\udffb-\\udfff]|\\ufe0f)\\u200d[\\u2640\\u2642]\\ufe0f)|(?:\\ud83c[\\udfc3\\udfc4\\udfca]|\\ud83d[\\udc6e\\udc70\\udc71\\udc73\\udc77\\udc81\\udc82\\udc86\\udc87\\ude45-\\ude47\\ude4b\\ude4d\\ude4e\\udea3\\udeb4-\\udeb6]|\\ud83e[\\udd26\\udd35\\udd37-\\udd39\\udd3d\\udd3e\\uddb8\\uddb9\\uddcd-\\uddcf\\uddd4\\uddd6-\\udddd])(?:\\ud83c[\\udffb-\\udfff])?\\u200d[\\u2640\\u2642]\\ufe0f|(?:\\ud83d\\udc68\\u200d\\ud83d\\udc68\\u200d\\ud83d\\udc66\\u200d\\ud83d\\udc66|\\ud83d\\udc68\\u200d\\ud83d\\udc68\\u200d\\ud83d\\udc67\\u200d\\ud83d[\\udc66\\udc67]|\\ud83d\\udc68\\u200d\\ud83d\\udc69\\u200d\\ud83d\\udc66\\u200d\\ud83d\\udc66|\\ud83d\\udc68\\u200d\\ud83d\\udc69\\u200d\\ud83d\\udc67\\u200d\\ud83d[\\udc66\\udc67]|\\ud83d\\udc69\\u200d\\ud83d\\udc69\\u200d\\ud83d\\udc66\\u200d\\ud83d\\udc66|\\ud83d\\udc69\\u200d\\ud83d\\udc69\\u200d\\ud83d\\udc67\\u200d\\ud83d[\\udc66\\udc67]|\\ud83d\\udc68\\u200d\\ud83d\\udc66\\u200d\\ud83d\\udc66|\\ud83d\\udc68\\u200d\\ud83d\\udc67\\u200d\\ud83d[\\udc66\\udc67]|\\ud83d\\udc68\\u200d\\ud83d\\udc68\\u200d\\ud83d[\\udc66\\udc67]|\\ud83d\\udc68\\u200d\\ud83d\\udc69\\u200d\\ud83d[\\udc66\\udc67]|\\ud83d\\udc69\\u200d\\ud83d\\udc66\\u200d\\ud83d\\udc66|\\ud83d\\udc69\\u200d\\ud83d\\udc67\\u200d\\ud83d[\\udc66\\udc67]|\\ud83d\\udc69\\u200d\\ud83d\\udc69\\u200d\\ud83d[\\udc66\\udc67]|\\ud83c\\udff3\\ufe0f\\u200d\\u26a7\\ufe0f|\\ud83c\\udff3\\ufe0f\\u200d\\ud83c\\udf08|\\ud83d\\ude36\\u200d\\ud83c\\udf2b\\ufe0f|\\u2764\\ufe0f\\u200d\\ud83d\\udd25|\\u2764\\ufe0f\\u200d\\ud83e\\ude79|\\ud83c\\udff4\\u200d\\u2620\\ufe0f|\\ud83d\\udc15\\u200d\\ud83e\\uddba|\\ud83d\\udc3b\\u200d\\u2744\\ufe0f|\\ud83d\\udc41\\u200d\\ud83d\\udde8|\\ud83d\\udc68\\u200d\\ud83d[\\udc66\\udc67]|\\ud83d\\udc69\\u200d\\ud83d[\\udc66\\udc67]|\\ud83d\\udc6f\\u200d\\u2640\\ufe0f|\\ud83d\\udc6f\\u200d\\u2642\\ufe0f|\\ud83d\\ude2e\\u200d\\ud83d\\udca8|\\ud83d\\ude35\\u200d\\ud83d\\udcab|\\ud83e\\udd3c\\u200d\\u2640\\ufe0f|\\ud83e\\udd3c\\u200d\\u2642\\ufe0f|\\ud83e\\uddde\\u200d\\u2640\\ufe0f|\\ud83e\\uddde\\u200d\\u2642\\ufe0f|\\ud83e\\udddf\\u200d\\u2640\\ufe0f|\\ud83e\\udddf\\u200d\\u2642\\ufe0f|\\ud83d\\udc08\\u200d\\u2b1b)|[#*0-9]\\ufe0f?\\u20e3|(?:[©®\\u2122\\u265f]\\ufe0f)|(?:\\ud83c[\\udc04\\udd70\\udd71\\udd7e\\udd7f\\ude02\\ude1a\\ude2f\\ude37\\udf21\\udf24-\\udf2c\\udf36\\udf7d\\udf96\\udf97\\udf99-\\udf9b\\udf9e\\udf9f\\udfcd\\udfce\\udfd4-\\udfdf\\udff3\\udff5\\udff7]|\\ud83d[\\udc3f\\udc41\\udcfd\\udd49\\udd4a\\udd6f\\udd70\\udd73\\udd76-\\udd79\\udd87\\udd8a-\\udd8d\\udda5\\udda8\\uddb1\\uddb2\\uddbc\\uddc2-\\uddc4\\uddd1-\\uddd3\\udddc-\\uddde\\udde1\\udde3\\udde8\\uddef\\uddf3\\uddfa\\udecb\\udecd-\\udecf\\udee0-\\udee5\\udee9\\udef0\\udef3]|[\\u203c\\u2049\\u2139\\u2194-\\u2199\\u21a9\\u21aa\\u231a\\u231b\\u2328\\u23cf\\u23ed-\\u23ef\\u23f1\\u23f2\\u23f8-\\u23fa\\u24c2\\u25aa\\u25ab\\u25b6\\u25c0\\u25fb-\\u25fe\\u2600-\\u2604\\u260e\\u2611\\u2614\\u2615\\u2618\\u2620\\u2622\\u2623\\u2626\\u262a\\u262e\\u262f\\u2638-\\u263a\\u2640\\u2642\\u2648-\\u2653\\u2660\\u2663\\u2665\\u2666\\u2668\\u267b\\u267f\\u2692-\\u2697\\u2699\\u269b\\u269c\\u26a0\\u26a1\\u26a7\\u26aa\\u26ab\\u26b0\\u26b1\\u26bd\\u26be\\u26c4\\u26c5\\u26c8\\u26cf\\u26d1\\u26d3\\u26d4\\u26e9\\u26ea\\u26f0-\\u26f5\\u26f8\\u26fa\\u26fd\\u2702\\u2708\\u2709\\u270f\\u2712\\u2714\\u2716\\u271d\\u2721\\u2733\\u2734\\u2744\\u2747\\u2757\\u2763\\u2764\\u27a1\\u2934\\u2935\\u2b05-\\u2b07\\u2b1b\\u2b1c\\u2b50\\u2b55\\u3030\\u303d\\u3297\\u3299])(?:\\ufe0f|(?!\\ufe0e))|(?:(?:\\ud83c[\\udfcb\\udfcc]|\\ud83d[\\udd74\\udd75\\udd90]|[\\u261d\\u26f7\\u26f9\\u270c\\u270d])(?:\\ufe0f|(?!\\ufe0e))|(?:\\ud83c[\\udf85\\udfc2-\\udfc4\\udfc7\\udfca]|\\ud83d[\\udc42\\udc43\\udc46-\\udc50\\udc66-\\udc69\\udc6e\\udc70-\\udc78\\udc7c\\udc81-\\udc83\\udc85-\\udc87\\udcaa\\udd7a\\udd95\\udd96\\ude45-\\ude47\\ude4b-\\ude4f\\udea3\\udeb4-\\udeb6\\udec0\\udecc]|\\ud83e[\\udd0c\\udd0f\\udd18-\\udd1c\\udd1e\\udd1f\\udd26\\udd30-\\udd39\\udd3d\\udd3e\\udd77\\uddb5\\uddb6\\uddb8\\uddb9\\uddbb\\uddcd-\\uddcf\\uddd1-\\udddd]|[\\u270a\\u270b]))(?:\\ud83c[\\udffb-\\udfff])?|(?:\\ud83c\\udff4\\udb40\\udc67\\udb40\\udc62\\udb40\\udc65\\udb40\\udc6e\\udb40\\udc67\\udb40\\udc7f|\\ud83c\\udff4\\udb40\\udc67\\udb40\\udc62\\udb40\\udc73\\udb40\\udc63\\udb40\\udc74\\udb40\\udc7f|\\ud83c\\udff4\\udb40\\udc67\\udb40\\udc62\\udb40\\udc77\\udb40\\udc6c\\udb40\\udc73\\udb40\\udc7f|\\ud83c\\udde6\\ud83c[\\udde8-\\uddec\\uddee\\uddf1\\uddf2\\uddf4\\uddf6-\\uddfa\\uddfc\\uddfd\\uddff]|\\ud83c\\udde7\\ud83c[\\udde6\\udde7\\udde9-\\uddef\\uddf1-\\uddf4\\uddf6-\\uddf9\\uddfb\\uddfc\\uddfe\\uddff]|\\ud83c\\udde8\\ud83c[\\udde6\\udde8\\udde9\\uddeb-\\uddee\\uddf0-\\uddf5\\uddf7\\uddfa-\\uddff]|\\ud83c\\udde9\\ud83c[\\uddea\\uddec\\uddef\\uddf0\\uddf2\\uddf4\\uddff]|\\ud83c\\uddea\\ud83c[\\udde6\\udde8\\uddea\\uddec\\udded\\uddf7-\\uddfa]|\\ud83c\\uddeb\\ud83c[\\uddee-\\uddf0\\uddf2\\uddf4\\uddf7]|\\ud83c\\uddec\\ud83c[\\udde6\\udde7\\udde9-\\uddee\\uddf1-\\uddf3\\uddf5-\\uddfa\\uddfc\\uddfe]|\\ud83c\\udded\\ud83c[\\uddf0\\uddf2\\uddf3\\uddf7\\uddf9\\uddfa]|\\ud83c\\uddee\\ud83c[\\udde8-\\uddea\\uddf1-\\uddf4\\uddf6-\\uddf9]|\\ud83c\\uddef\\ud83c[\\uddea\\uddf2\\uddf4\\uddf5]|\\ud83c\\uddf0\\ud83c[\\uddea\\uddec-\\uddee\\uddf2\\uddf3\\uddf5\\uddf7\\uddfc\\uddfe\\uddff]|\\ud83c\\uddf1\\ud83c[\\udde6-\\udde8\\uddee\\uddf0\\uddf7-\\uddfb\\uddfe]|\\ud83c\\uddf2\\ud83c[\\udde6\\udde8-\\udded\\uddf0-\\uddff]|\\ud83c\\uddf3\\ud83c[\\udde6\\udde8\\uddea-\\uddec\\uddee\\uddf1\\uddf4\\uddf5\\uddf7\\uddfa\\uddff]|\\ud83c\\uddf4\\ud83c\\uddf2|\\ud83c\\uddf5\\ud83c[\\udde6\\uddea-\\udded\\uddf0-\\uddf3\\uddf7-\\uddf9\\uddfc\\uddfe]|\\ud83c\\uddf6\\ud83c\\udde6|\\ud83c\\uddf7\\ud83c[\\uddea\\uddf4\\uddf8\\uddfa\\uddfc]|\\ud83c\\uddf8\\ud83c[\\udde6-\\uddea\\uddec-\\uddf4\\uddf7-\\uddf9\\uddfb\\uddfd-\\uddff]|\\ud83c\\uddf9\\ud83c[\\udde6\\udde8\\udde9\\uddeb-\\udded\\uddef-\\uddf4\\uddf7\\uddf9\\uddfb\\uddfc\\uddff]|\\ud83c\\uddfa\\ud83c[\\udde6\\uddec\\uddf2\\uddf3\\uddf8\\uddfe\\uddff]|\\ud83c\\uddfb\\ud83c[\\udde6\\udde8\\uddea\\uddec\\uddee\\uddf3\\uddfa]|\\ud83c\\uddfc\\ud83c[\\uddeb\\uddf8]|\\ud83c\\uddfd\\ud83c\\uddf0|\\ud83c\\uddfe\\ud83c[\\uddea\\uddf9]|\\ud83c\\uddff\\ud83c[\\udde6\\uddf2\\uddfc]|\\ud83c[\\udccf\\udd8e\\udd91-\\udd9a\\udde6-\\uddff\\ude01\\ude32-\\ude36\\ude38-\\ude3a\\ude50\\ude51\\udf00-\\udf20\\udf2d-\\udf35\\udf37-\\udf7c\\udf7e-\\udf84\\udf86-\\udf93\\udfa0-\\udfc1\\udfc5\\udfc6\\udfc8\\udfc9\\udfcf-\\udfd3\\udfe0-\\udff0\\udff4\\udff8-\\udfff]|\\ud83d[\\udc00-\\udc3e\\udc40\\udc44\\udc45\\udc51-\\udc65\\udc6a\\udc6f\\udc79-\\udc7b\\udc7d-\\udc80\\udc84\\udc88-\\udc8e\\udc90\\udc92-\\udca9\\udcab-\\udcfc\\udcff-\\udd3d\\udd4b-\\udd4e\\udd50-\\udd67\\udda4\\uddfb-\\ude44\\ude48-\\ude4a\\ude80-\\udea2\\udea4-\\udeb3\\udeb7-\\udebf\\udec1-\\udec5\\uded0-\\uded2\\uded5-\\uded7\\udeeb\\udeec\\udef4-\\udefc\\udfe0-\\udfeb]|\\ud83e[\\udd0d\\udd0e\\udd10-\\udd17\\udd1d\\udd20-\\udd25\\udd27-\\udd2f\\udd3a\\udd3c\\udd3f-\\udd45\\udd47-\\udd76\\udd78\\udd7a-\\uddb4\\uddb7\\uddba\\uddbc-\\uddcb\\uddd0\\uddde-\\uddff\\ude70-\\ude74\\ude78-\\ude7a\\ude80-\\ude86\\ude90-\\udea8\\udeb0-\\udeb6\\udec0-\\udec2\\uded0-\\uded6]|[\\u23e9-\\u23ec\\u23f0\\u23f3\\u267e\\u26ce\\u2705\\u2728\\u274c\\u274e\\u2753-\\u2755\\u2795-\\u2797\\u27b0\\u27bf\\ue50a])|\\ufe0f/g;\n","import React, { FC, memo } from '../../lib/teact/teact';\n\nimport Spinner from './Spinner';\n\nimport './Loading.scss';\n\ntype OwnProps = {\n color?: 'blue' | 'white' | 'black';\n};\n\nconst Loading: FC<OwnProps> = ({ color = 'blue' }) => {\n return (\n <div className=\"Loading\">\n <Spinner color={color} withBackground={color === 'white'} />\n </div>\n );\n};\n\nexport default memo(Loading);\n","import { callApi } from '../api/gramjs';\nimport {\n ApiChat, ApiMediaFormat, ApiMessage, ApiUser,\n} from '../api/types';\nimport { renderActionMessageText } from '../components/common/helpers/renderActionMessageText';\nimport { DEBUG } from '../config';\nimport { getDispatch, getGlobal, setGlobal } from '../lib/teact/teactn';\nimport {\n getChatAvatarHash,\n getChatTitle,\n getMessageAction,\n getMessageSenderName,\n getMessageSummaryText,\n getPrivateChatUserId,\n isActionMessage,\n isChatChannel,\n selectIsChatMuted, selectShouldShowMessagePreview,\n} from '../modules/helpers';\nimport { getTranslation } from './langProvider';\nimport { addNotifyExceptions, replaceSettings } from '../modules/reducers';\nimport {\n selectChatMessage, selectNotifyExceptions, selectNotifySettings, selectUser,\n} from '../modules/selectors';\nimport { IS_SERVICE_WORKER_SUPPORTED } from './environment';\nimport * as mediaLoader from './mediaLoader';\nimport { debounce } from './schedulers';\n\nfunction getDeviceToken(subscription: PushSubscription) {\n const data = subscription.toJSON();\n return JSON.stringify({\n endpoint: data.endpoint,\n keys: data.keys,\n });\n}\n\nfunction checkIfPushSupported() {\n if (!IS_SERVICE_WORKER_SUPPORTED) return false;\n if (!('showNotification' in ServiceWorkerRegistration.prototype)) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.warn('[PUSH] Push notifications aren\\'t supported.');\n }\n return false;\n }\n\n // Check the current Notification permission.\n // If its denied, it's a permanent block until the\n // user changes the permission\n if (Notification.permission === 'denied') {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.warn('[PUSH] The user has blocked push notifications.');\n }\n return false;\n }\n\n // Check if push messaging is supported\n if (!('PushManager' in window)) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.warn('[PUSH] Push messaging isn\\'t supported.');\n }\n return false;\n }\n return true;\n}\n\nfunction checkIfNotificationsSupported() {\n // Let's check if the browser supports notifications\n if (!('Notification' in window)) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.warn('[PUSH] This browser does not support desktop notification');\n }\n return false;\n }\n\n if (Notification.permission === 'denied' as NotificationPermission) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.warn('[PUSH] The user has blocked push notifications.');\n }\n return false;\n }\n return true;\n}\n\nconst expirationTime = 12 * 60 * 60 * 1000; // 12 hours\n// Notification id is removed from soundPlayed cache after 3 seconds\nconst soundPlayedDelay = 3 * 1000;\nconst soundPlayed = new Set<number>();\n\nasync function playSound(id: number) {\n if (soundPlayed.has(id)) return;\n const { notificationSoundVolume } = selectNotifySettings(getGlobal());\n const volume = notificationSoundVolume / 10;\n if (volume === 0) return;\n\n const audio = new Audio('/notification.mp3');\n audio.volume = volume;\n audio.setAttribute('mozaudiochannel', 'notification');\n audio.addEventListener('ended', () => {\n soundPlayed.add(id);\n }, { once: true });\n\n setTimeout(() => {\n soundPlayed.delete(id);\n }, soundPlayedDelay);\n\n try {\n await audio.play();\n } catch (error) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.warn('[PUSH] Unable to play notification sound');\n }\n }\n}\n\nexport const playNotificationSound = debounce(playSound, 1000, true, false);\n\nfunction checkIfShouldResubscribe(subscription: PushSubscription | null) {\n const global = getGlobal();\n if (!global.push || !subscription) return true;\n if (getDeviceToken(subscription) !== global.push.deviceToken) return true;\n return Date.now() - global.push.subscribedAt > expirationTime;\n}\n\nasync function requestPermission() {\n if (!('Notification' in window)) return;\n if (!['granted', 'denied'].includes(Notification.permission)) {\n await Notification.requestPermission();\n }\n}\n\nasync function unsubscribeFromPush(subscription: PushSubscription | null) {\n const global = getGlobal();\n const dispatch = getDispatch();\n if (subscription) {\n try {\n const deviceToken = getDeviceToken(subscription);\n await callApi('unregisterDevice', deviceToken);\n await subscription.unsubscribe();\n dispatch.deleteDeviceToken();\n return;\n } catch (error) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('[PUSH] Unable to unsubscribe from push.', error);\n }\n }\n }\n if (global.push) {\n await callApi('unregisterDevice', global.push.deviceToken);\n dispatch.deleteDeviceToken();\n }\n}\n\nexport async function unsubscribe() {\n if (!checkIfPushSupported()) return;\n const serviceWorkerRegistration = await navigator.serviceWorker.ready;\n const subscription = await serviceWorkerRegistration.pushManager.getSubscription();\n await unsubscribeFromPush(subscription);\n}\n\n// Indicates if notification settings are loaded from the api\nlet areSettingsLoaded = false;\n\n// Load notification settings from the api\nasync function loadNotificationSettings() {\n if (areSettingsLoaded) return;\n const [resultSettings, resultExceptions] = await Promise.all([\n callApi('fetchNotificationSettings', {\n serverTimeOffset: getGlobal().serverTimeOffset,\n }),\n callApi('fetchNotificationExceptions', {\n serverTimeOffset: getGlobal().serverTimeOffset,\n }),\n ]);\n if (!resultSettings) return;\n\n let global = replaceSettings(getGlobal(), resultSettings);\n if (resultExceptions) {\n global = addNotifyExceptions(global, resultExceptions);\n }\n setGlobal(global);\n areSettingsLoaded = true;\n}\n\nexport async function subscribe() {\n if (!checkIfPushSupported()) {\n // Ask for notification permissions only if service worker notifications are not supported\n // As pushManager.subscribe automatically triggers permission popup\n await requestPermission();\n return;\n }\n const serviceWorkerRegistration = await navigator.serviceWorker.ready;\n let subscription = await serviceWorkerRegistration.pushManager.getSubscription();\n if (!checkIfShouldResubscribe(subscription)) return;\n await unsubscribeFromPush(subscription);\n try {\n subscription = await serviceWorkerRegistration.pushManager.subscribe({\n userVisibleOnly: true,\n });\n const deviceToken = getDeviceToken(subscription);\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('[PUSH] Received push subscription: ', deviceToken);\n }\n await callApi('registerDevice', deviceToken);\n getDispatch()\n .setDeviceToken(deviceToken);\n } catch (error) {\n if (Notification.permission === 'denied' as NotificationPermission) {\n // The user denied the notification permission which\n // means we failed to subscribe and the user will need\n // to manually change the notification permission to\n // subscribe to push messages\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.warn('[PUSH] The user has blocked push notifications.');\n }\n } else if (DEBUG) {\n // A problem occurred with the subscription, this can\n // often be down to an issue or lack of the gcm_sender_id\n // and / or gcm_user_visible_only\n // eslint-disable-next-line no-console\n console.log('[PUSH] Unable to subscribe to push.', error);\n\n // Request permissions and fall back to local notifications\n // if pushManager.subscribe was aborted due to invalid VAPID key.\n if (error.code === DOMException.ABORT_ERR) {\n await requestPermission();\n }\n }\n }\n}\n\nfunction checkIfShouldNotify(chat: ApiChat, isActive: boolean) {\n if (!areSettingsLoaded) return false;\n const global = getGlobal();\n const isMuted = selectIsChatMuted(chat, selectNotifySettings(global), selectNotifyExceptions(global));\n if (isMuted || chat.isNotJoined || !chat.isListed) {\n return false;\n }\n // Dont show notification for active chat if client has focus\n return !(isActive && document.hasFocus());\n}\n\nfunction getNotificationContent(chat: ApiChat, message: ApiMessage) {\n const global = getGlobal();\n const {\n senderId,\n replyToMessageId,\n } = message;\n\n const messageSender = senderId ? selectUser(global, senderId) : undefined;\n const messageAction = getMessageAction(message as ApiMessage);\n const actionTargetMessage = messageAction && replyToMessageId\n ? selectChatMessage(global, chat.id, replyToMessageId)\n : undefined;\n const {\n targetUserIds: actionTargetUserIds,\n targetChatId: actionTargetChatId,\n } = messageAction || {};\n\n const actionTargetUsers = actionTargetUserIds\n ? actionTargetUserIds.map((userId) => selectUser(global, userId))\n .filter<ApiUser>(Boolean as any)\n : undefined;\n const privateChatUserId = getPrivateChatUserId(chat);\n const privateChatUser = privateChatUserId ? selectUser(global, privateChatUserId) : undefined;\n\n let body: string;\n if (selectShouldShowMessagePreview(chat, selectNotifySettings(global), selectNotifyExceptions(global))) {\n if (isActionMessage(message)) {\n const actionOrigin = chat && (isChatChannel(chat) || message.senderId === message.chatId)\n ? chat\n : messageSender;\n body = renderActionMessageText(\n getTranslation,\n message,\n actionOrigin,\n actionTargetUsers,\n actionTargetMessage,\n actionTargetChatId,\n { asPlain: true },\n ) as string;\n } else {\n const senderName = getMessageSenderName(getTranslation, chat.id, messageSender);\n const summary = getMessageSummaryText(getTranslation, message);\n\n body = senderName ? `${senderName}: ${summary}` : summary;\n }\n } else {\n body = 'New message';\n }\n\n return {\n title: getChatTitle(getTranslation, chat, privateChatUser),\n body,\n };\n}\n\nasync function getAvatar(chat: ApiChat) {\n const imageHash = getChatAvatarHash(chat);\n if (!imageHash) return undefined;\n let mediaData = mediaLoader.getFromMemory<ApiMediaFormat.BlobUrl>(imageHash);\n if (!mediaData) {\n await mediaLoader.fetch(imageHash, ApiMediaFormat.BlobUrl);\n mediaData = mediaLoader.getFromMemory<ApiMediaFormat.BlobUrl>(imageHash);\n }\n return mediaData;\n}\n\nexport async function showNewMessageNotification({\n chat,\n message,\n isActiveChat,\n}: { chat: ApiChat; message: Partial<ApiMessage>; isActiveChat: boolean }) {\n if (!checkIfNotificationsSupported()) return;\n if (!message.id) return;\n\n await loadNotificationSettings();\n if (!checkIfShouldNotify(chat, isActiveChat)) return;\n\n const {\n title,\n body,\n } = getNotificationContent(chat, message as ApiMessage);\n\n const icon = await getAvatar(chat);\n\n if (checkIfPushSupported()) {\n if (navigator.serviceWorker.controller) {\n // notify service worker about new message notification\n navigator.serviceWorker.controller.postMessage({\n type: 'newMessageNotification',\n payload: {\n title,\n body,\n icon,\n chatId: chat.id,\n messageId: message.id,\n },\n });\n }\n } else {\n const dispatch = getDispatch();\n const options: NotificationOptions = {\n body,\n icon,\n badge: icon,\n tag: message.id.toString(),\n };\n\n if ('vibrate' in navigator) {\n options.vibrate = [200, 100, 200];\n }\n\n const notification = new Notification(title, options);\n\n notification.onclick = () => {\n notification.close();\n dispatch.focusMessage({\n chatId: chat.id,\n messageId: message.id,\n });\n if (window.focus) {\n window.focus();\n }\n };\n\n // Play sound when notification is displayed\n notification.onshow = () => {\n playNotificationSound(message.id || chat.id);\n };\n }\n}\n\n// Notify service worker that client is fully loaded\nexport function notifyClientReady() {\n if (!navigator.serviceWorker.controller) return;\n navigator.serviceWorker.controller.postMessage({\n type: 'clientReady',\n });\n}\n","import { MouseEvent as ReactMouseEvent, RefObject } from 'react';\n\nimport React, {\n FC, useRef, useCallback, useState,\n} from '../../lib/teact/teact';\n\nimport buildClassName from '../../util/buildClassName';\n\nimport Spinner from './Spinner';\nimport RippleEffect from './RippleEffect';\n\nimport './Button.scss';\n\nexport type OwnProps = {\n ref?: RefObject<HTMLButtonElement | HTMLAnchorElement>;\n type?: 'button' | 'submit' | 'reset';\n children: any;\n size?: 'default' | 'smaller' | 'tiny';\n color?: 'primary' | 'secondary' | 'gray' | 'danger' | 'translucent' | 'translucent-white' | 'dark';\n className?: string;\n round?: boolean;\n pill?: boolean;\n fluid?: boolean;\n isText?: boolean;\n isLoading?: boolean;\n ariaLabel?: string;\n href?: string;\n download?: string;\n disabled?: boolean;\n ripple?: boolean;\n faded?: boolean;\n tabIndex?: number;\n isRtl?: boolean;\n onClick?: (e: ReactMouseEvent<HTMLButtonElement, MouseEvent>) => void;\n onContextMenu?: (e: ReactMouseEvent<HTMLButtonElement, MouseEvent>) => void;\n onMouseDown?: (e: ReactMouseEvent<HTMLButtonElement>) => void;\n onMouseEnter?: NoneToVoidFunction;\n onMouseLeave?: NoneToVoidFunction;\n onFocus?: NoneToVoidFunction;\n};\n\n// Longest animation duration;\nconst CLICKED_TIMEOUT = 400;\n\nconst Button: FC<OwnProps> = ({\n ref,\n type = 'button',\n onClick,\n onContextMenu,\n onMouseDown,\n onMouseEnter,\n onMouseLeave,\n onFocus,\n children,\n size = 'default',\n color = 'primary',\n className,\n round,\n pill,\n fluid,\n isText,\n isLoading,\n ariaLabel,\n href,\n download,\n disabled,\n ripple,\n faded,\n tabIndex,\n isRtl,\n}) => {\n // eslint-disable-next-line no-null/no-null\n let elementRef = useRef<HTMLButtonElement | HTMLAnchorElement>(null);\n if (ref) {\n elementRef = ref;\n }\n\n const [isClicked, setIsClicked] = useState(false);\n\n const fullClassName = buildClassName(\n 'Button',\n className,\n size,\n color,\n round && 'round',\n pill && 'pill',\n fluid && 'fluid',\n disabled && 'disabled',\n isText && 'text',\n isLoading && 'loading',\n ripple && 'has-ripple',\n faded && 'faded',\n isClicked && 'clicked',\n );\n\n const handleClick = useCallback((e: ReactMouseEvent<HTMLButtonElement, MouseEvent>) => {\n if (!disabled && onClick) {\n onClick(e);\n }\n\n setIsClicked(true);\n setTimeout(() => {\n setIsClicked(false);\n }, CLICKED_TIMEOUT);\n }, [disabled, onClick]);\n\n const handleMouseDown = useCallback((e: ReactMouseEvent<HTMLButtonElement>) => {\n e.preventDefault();\n if (!disabled && onMouseDown) {\n onMouseDown(e);\n }\n }, [onMouseDown, disabled]);\n\n if (href) {\n return (\n <a\n ref={elementRef as RefObject<HTMLAnchorElement>}\n className={fullClassName}\n href={href}\n title={ariaLabel}\n download={download}\n tabIndex={tabIndex}\n dir={isRtl ? 'rtl' : undefined}\n >\n {children}\n {!disabled && ripple && (\n <RippleEffect />\n )}\n </a>\n );\n }\n\n return (\n // eslint-disable-next-line react/button-has-type\n <button\n ref={elementRef as RefObject<HTMLButtonElement>}\n type={type}\n className={fullClassName}\n onClick={handleClick}\n onContextMenu={onContextMenu}\n onMouseDown={handleMouseDown}\n onMouseEnter={onMouseEnter && !disabled ? onMouseEnter : undefined}\n onMouseLeave={onMouseLeave && !disabled ? onMouseLeave : undefined}\n onFocus={onFocus && !disabled ? onFocus : undefined}\n aria-label={ariaLabel}\n title={ariaLabel}\n tabIndex={tabIndex}\n dir={isRtl ? 'rtl' : undefined}\n >\n {isLoading ? (\n <div>\n <span dir={isRtl ? 'auto' : undefined}>Please wait..</span>\n <Spinner color={isText ? 'blue' : 'white'} />\n </div>\n ) : children}\n {!disabled && ripple && (\n <RippleEffect />\n )}\n </button>\n );\n};\n\nexport default Button;\n","import React from '../../../lib/teact/teact';\nimport EMOJI_REGEX, { removeVS16s } from '../../../lib/twemojiRegex';\n\nimport { RE_LINK_TEMPLATE, RE_MENTION_TEMPLATE } from '../../../config';\nimport { IS_EMOJI_SUPPORTED } from '../../../util/environment';\nimport { nativeToUnfified } from '../../../util/emoji';\nimport buildClassName from '../../../util/buildClassName';\n\nimport MentionLink from '../../middle/message/MentionLink';\nimport SafeLink from '../SafeLink';\n\ntype TextPart = string | Element;\n\nconst RE_LETTER_OR_DIGIT = /^[\\d\\wа-яё]$/i;\nconst SIMPLE_MARKDOWN_REGEX = /(\\*\\*|__).+?\\1/g;\n\nexport default function renderText(\n part: TextPart,\n filters: Array<(\n 'escape_html' | 'hq_emoji' | 'emoji' | 'emoji_html' | 'br' | 'br_html' | 'highlight' | 'links' |\n 'simple_markdown' | 'simple_markdown_html'\n )> = ['emoji'],\n params?: { highlight: string | undefined },\n): TextPart[] {\n if (typeof part !== 'string') {\n return [part];\n }\n\n return filters.reduce((text, filter) => {\n switch (filter) {\n case 'escape_html':\n return escapeHtml(text);\n\n case 'hq_emoji':\n EMOJI_REGEX.lastIndex = 0;\n return replaceEmojis(text, 'big', 'jsx');\n\n case 'emoji':\n EMOJI_REGEX.lastIndex = 0;\n return replaceEmojis(text, 'small', 'jsx');\n\n case 'emoji_html':\n EMOJI_REGEX.lastIndex = 0;\n return replaceEmojis(text, 'small', 'html');\n\n case 'br':\n return addLineBreaks(text, 'jsx');\n\n case 'br_html':\n return addLineBreaks(text, 'html');\n\n case 'highlight':\n return addHighlight(text, params!.highlight);\n\n case 'links':\n return addLinks(text);\n\n case 'simple_markdown':\n return replaceSimpleMarkdown(text, 'jsx');\n\n case 'simple_markdown_html':\n return replaceSimpleMarkdown(text, 'html');\n }\n\n return text;\n }, [part] as TextPart[]);\n}\n\nfunction escapeHtml(textParts: TextPart[]): TextPart[] {\n const divEl = document.createElement('div');\n return textParts.reduce((result, part) => {\n if (typeof part !== 'string') {\n return [...result, part];\n }\n\n divEl.innerText = part;\n\n return [...result, divEl.innerHTML];\n }, [] as TextPart[]);\n}\n\nfunction replaceEmojis(textParts: TextPart[], size: 'big' | 'small', type: 'jsx' | 'html'): TextPart[] {\n if (IS_EMOJI_SUPPORTED) {\n return textParts;\n }\n\n return textParts.reduce((result, part) => {\n if (typeof part !== 'string') {\n return [...result, part];\n }\n\n const parts = part.split(EMOJI_REGEX);\n const emojis = part.match(EMOJI_REGEX) || [];\n result.push(parts[0]);\n\n return emojis.reduce((emojiResult: TextPart[], emoji, i) => {\n const code = nativeToUnfified(removeVS16s(emoji));\n const className = buildClassName(\n 'emoji',\n size === 'small' && 'emoji-small',\n );\n if (type === 'jsx') {\n emojiResult.push(\n <img\n className={className}\n src={`./img-apple-${size === 'big' ? '160' : '64'}/${code}.png`}\n alt={emoji}\n />,\n );\n }\n if (type === 'html') {\n emojiResult.push(\n // For preventing extra spaces in html\n // eslint-disable-next-line max-len\n `<img draggable=\"false\" class=\"${className}\" src=\"./img-apple-${size === 'big' ? '160' : '64'}/${code}.png\" alt=\"${emoji}\" />`,\n );\n }\n\n const index = i * 2 + 2;\n if (parts[index]) {\n emojiResult.push(parts[index]);\n }\n\n return emojiResult;\n }, result);\n }, [] as TextPart[]);\n}\n\nfunction addLineBreaks(textParts: TextPart[], type: 'jsx' | 'html'): TextPart[] {\n return textParts.reduce((result, part) => {\n if (typeof part !== 'string') {\n return [...result, part];\n }\n\n return [...result, ...part\n .split(/\\r\\n|\\r|\\n/g)\n .reduce((parts: TextPart[], line: string, i, source) => {\n // This adds non-breaking space if line was indented with spaces, to preserve the indentation\n const trimmedLine = line.trimLeft();\n const indentLength = line.length - trimmedLine.length;\n parts.push(String.fromCharCode(160).repeat(indentLength) + trimmedLine);\n\n if (i !== source.length - 1) {\n parts.push(\n type === 'jsx' ? <br /> : '<br />',\n );\n }\n\n return parts;\n }, [])];\n }, [] as TextPart[]);\n}\n\nfunction addHighlight(textParts: TextPart[], highlight: string | undefined): TextPart[] {\n return textParts.reduce((result, part) => {\n if (typeof part !== 'string' || !highlight) {\n return [...result, part];\n }\n\n const lowerCaseText = part.toLowerCase();\n const queryPosition = lowerCaseText.indexOf(highlight.toLowerCase());\n const nextSymbol = lowerCaseText[queryPosition + highlight.length];\n if (queryPosition < 0 || (nextSymbol && nextSymbol.match(RE_LETTER_OR_DIGIT))) {\n return [...result, part];\n }\n\n const newParts: TextPart[] = [];\n newParts.push(part.substring(0, queryPosition));\n newParts.push(\n <span className=\"matching-text-highlight\">\n {part.substring(queryPosition, queryPosition + highlight.length)}\n </span>,\n );\n newParts.push(part.substring(queryPosition + highlight.length));\n\n return [...result, ...newParts];\n }, [] as TextPart[]);\n}\n\nconst RE_LINK = new RegExp(`${RE_LINK_TEMPLATE}|${RE_MENTION_TEMPLATE}`, 'ig');\n\nfunction addLinks(textParts: TextPart[]): TextPart[] {\n return textParts.reduce((result, part) => {\n if (typeof part !== 'string') {\n return [...result, part];\n }\n\n const links = part.match(RE_LINK);\n if (!links || !links.length) {\n return [...result, part];\n }\n\n const content: TextPart[] = [];\n\n let nextLink = links.shift();\n let lastIndex = 0;\n while (nextLink) {\n const index = part.indexOf(nextLink, lastIndex);\n content.push(part.substring(lastIndex, index));\n if (nextLink.startsWith('@')) {\n content.push(\n <MentionLink username={nextLink}>\n {nextLink}\n </MentionLink>,\n );\n } else {\n if (nextLink.endsWith('?')) {\n nextLink = nextLink.slice(0, nextLink.length - 1);\n }\n\n content.push(\n <SafeLink text={nextLink} url={nextLink} />,\n );\n }\n lastIndex = index + nextLink.length;\n nextLink = links.shift();\n }\n content.push(part.substring(lastIndex));\n\n return [...result, ...content];\n }, [] as TextPart[]);\n}\n\nfunction replaceSimpleMarkdown(textParts: TextPart[], type: 'jsx' | 'html'): TextPart[] {\n return textParts.reduce((result, part) => {\n if (typeof part !== 'string') {\n return [...result, part];\n }\n\n const parts = part.split(SIMPLE_MARKDOWN_REGEX);\n const entities = part.match(SIMPLE_MARKDOWN_REGEX) || [];\n result.push(parts[0]);\n\n return entities.reduce((entityResult: TextPart[], entity, i) => {\n if (type === 'jsx') {\n entityResult.push(\n entity.startsWith('**')\n ? <b>{entity.replace(/\\*\\*/g, '')}</b>\n : <i>{entity.replace(/__/g, '')}</i>,\n );\n } else {\n entityResult.push(\n entity.startsWith('**')\n ? `<b>${entity.replace(/\\*\\*/g, '')}</b>`\n : `<i>${entity.replace(/__/g, '')}</i>`,\n );\n }\n\n const index = i * 2 + 2;\n if (parts[index]) {\n entityResult.push(parts[index]);\n }\n\n return entityResult;\n }, result);\n }, [] as TextPart[]);\n}\n","// This data was received from Telegram Desktop (Telegram/Resources/numbers.txt)\nconst DATA = `AF🇦🇫93Afghanistan333\nAO🇦🇴244Angola333\nAL🇦🇱355Albania234\nAD🇦🇩376Andorra222\nAE🇦🇪971United Arab Emirates234\nAI🇦🇮1264Anguilla34\nAR🇦🇷54Argentina\nAM🇦🇲374Armenia233\nAG🇦🇬1268Antigua and Barbuda34\nAU🇦🇺61Australia333\nAS🇦🇸1684American Samoa34\nAT🇦🇹43Austria\nAW🇦🇼297Aruba34\nAZ🇦🇿994Azerbaijan2322\nBI🇧🇮257Burundi224\nBE🇧🇪32Belgium3222\nBJ🇧🇯229Benin233\nBF🇧🇫226Burkina Faso2222\nBD🇧🇩880Bangladesh\nBG🇧🇬359Bulgaria\nBH🇧🇭973Bahrain44\nBS🇧🇸1242Bahamas34\nBA🇧🇦387Bosnia and Herzegovina\nBY🇧🇾375Belarus2322\nBZ🇧🇿501Belize\nBO🇧🇴591Bolivia134\nBR🇧🇷55Brazil254\nBB🇧🇧1246Barbados34\nBM🇧🇲1441Bermuda34\nBN🇧🇳673Brunei34\nBQ🇧🇶599Bonaire, Sint Eustatius and Saba\nBT🇧🇹975Bhutan\nBW🇧🇼267Botswana233\nCF🇨🇫236Central African Republic2222\nCA🇨🇦1Canada334\nCH🇨🇭41Switzerland234\nCK🇨🇰682Cook Islands\nCL🇨🇱56Chile144\nCN🇨🇳86China344\nCI🇨🇮225Côte d\\`Ivoire233\nCM🇨🇲237Cameroon44\nCD🇨🇩243DR Congo234\nCG🇨🇬242Republic of the Congo234\nCO🇨🇴57Colombia334\nKM🇰🇲269Comoros34\nCV🇨🇻238Cape Verde34\nCR🇨🇷506Costa Rica\nCU🇨🇺53Cuba44\nCY🇨🇾357Cyprus44\nCW🇨🇼599Curaçao\nCZ🇨🇿420Czech Republic\nDE🇩🇪49Germany38\nDJ🇩🇯253Djibouti2222\nDM🇩🇲1767Dominica34\nDK🇩🇰45Denmark44\nDO🇩🇴1Dominican Republic334\nDZ🇩🇿213Algeria3222\nEC🇪🇨593Ecuador\nEG🇪🇬20Egypt234\nER🇪🇷291Eritrea133\nES🇪🇸34Spain333\nEE🇪🇪372Estonia\nET🇪🇹251Ethiopia234\nFI🇫🇮358Finland\nFJ🇫🇯679Fiji\nFK🇫🇰500Falkland Islands\nFM🇫🇲691Micronesia\nFO🇫🇴298Faroe Islands33\nFR🇫🇷33France12222\nGA🇬🇦241Gabon1222\nGB🇬🇧44United Kingdom46\nGE🇬🇪995Georgia\nGF🇬🇫594French Guiana\nGH🇬🇭233Ghana\nGI🇬🇮350Gibraltar44\nGL🇬🇱299Greenland33\nGN🇬🇳224Guinea333\nGM🇬🇲220Gambia34\nGP🇬🇵590Guadeloupe\nGU🇬🇺1671Guam34\nGW🇬🇼245Guinea-Bissau34\nGQ🇬🇶240Equatorial Guinea333\nGR🇬🇷30Greece244\nGD🇬🇩1473Grenada34\nGT🇬🇹502Guatemala134\nGY🇬🇾592Guyana\nHK🇭🇰852Hong Kong\nHN🇭🇳504Honduras44\nHR🇭🇷385Croatia\nHT🇭🇹509Haiti\nHU🇭🇺36Hungary234\nID🇮🇩62Indonesia\nIN🇮🇳91India55\nIO🇩🇬246Diego Garcia34\nIE🇮🇪353Ireland234\nIR🇮🇷98Iran334\nIQ🇮🇶964Iraq334\nIS🇮🇸354Iceland34\nIL🇮🇱972Israel234\nIT🇮🇹39Italy334\nJM🇯🇲1876Jamaica34\nJO🇯🇴962Jordan144\nJP🇯🇵81Japan244\nKZ🇰🇿7Kazakhstan3322\nKE🇰🇪254Kenya333\nKG🇰🇬996Kyrgyzstan\nKH🇰🇭855Cambodia\nKI🇰🇮686Kiribati\nKN🇰🇳1869Saint Kitts and Nevis34\nKR🇰🇷82South Korea\nKW🇰🇼965Kuwait44\nKY🇰🇾1345Cayman Islands34\nLA🇱🇦856Laos\nLB🇱🇧961Lebanon\nLR🇱🇷231Liberia\nLY🇱🇾218Libya234\nLC🇱🇨1758Saint Lucia34\nLI🇱🇮423Liechtenstein\nLK🇱🇰94Sri Lanka234\nLS🇱🇸266Lesotho233\nLT🇱🇹370Lithuania35\nLU🇱🇺352Luxembourg\nLV🇱🇻371Latvia35\nMA🇲🇦212Morocco234\nMC🇲🇨377Monaco44\nMD🇲🇩373Moldova233\nMG🇲🇬261Madagascar2232\nMP🇲🇵1670Northern Mariana Islands34\nMO🇲🇴853Macau\nMS🇲🇸1664Montserrat34\nMV🇲🇻960Maldives\nMX🇲🇽52Mexico\nMH🇲🇭692Marshall Islands\nMK🇲🇰389Macedonia\nML🇲🇱223Mali44\nMT🇲🇹356Malta2222\nMM🇲🇲95Myanmar\nME🇲🇪382Montenegro\nMN🇲🇳976Mongolia\nMZ🇲🇿258Mozambique234\nMQ🇲🇶596Martinique\nMR🇲🇷222Mauritania44\nMU🇲🇺230Mauritius\nMW🇲🇼265Malawi\nMY🇲🇾60Malaysia\nNA🇳🇦264Namibia234\nNC🇳🇨687New Caledonia6\nNE🇳🇪227Niger2222\nNF🇳🇫672Norfolk Island\nNG🇳🇬234Nigeria\nNI🇳🇮505Nicaragua44\nNL🇳🇱31Netherlands12222\nNO🇳🇴47Norway44\nNP🇳🇵977Nepal\nNU🇳🇺683Niue\nNR🇳🇷674Nauru\nNZ🇳🇿64New Zealand\nOM🇴🇲968Oman44\nPK🇵🇰92Pakistan334\nPA🇵🇦507Panama44\nPE🇵🇪51Peru333\nPF🇵🇫689French Polynesia\nPH🇵🇭63Philippines334\nPM🇵🇲508Saint Pierre and Miquelon\nPR🇵🇷1Puerto Rico334\nPS🇵🇸970Palestine324\nPW🇵🇼680Palau\nPG🇵🇬675Papua New Guinea\nPL🇵🇱48Poland333\nKP🇰🇵850North Korea\nPT🇵🇹351Portugal144\nPY🇵🇾595Paraguay333\nQA🇶🇦974Qatar\nRE🇷🇪262Réunion333\nRO🇷🇴40Romania333\nRU🇷🇺7Russia3322\nRW🇷🇼250Rwanda333\nSA🇸🇦966Saudi Arabia\nSD🇸🇩249Sudan234\nSN🇸🇳221Senegal234\nSG🇸🇬65Singapore44\nSH🇸🇭290Saint Helena23\nSH🇸🇭247Saint Helena4\nSB🇸🇧677Solomon Islands\nSL🇸🇱232Sierra Leone233\nSV🇸🇻503El Salvador44\nSM🇸🇲378San Marino334\nSO🇸🇴252Somalia233\nRS🇷🇸381Serbia234\nSS🇸🇸211South Sudan234\nST🇸🇹239São Tomé and Príncipe25\nSR🇸🇷597Suriname34\nSK🇸🇰421Slovakia\nSI🇸🇮386Slovenia\nSE🇸🇪46Sweden234\nSZ🇸🇿268Swaziland44\nSC🇸🇨248Seychelles1222\nSX🇸🇽1721Sint Maarten34\nSY🇸🇾963Syria\nTC🇹🇨1649Turks and Caicos Islands34\nTD🇹🇩235Chad2222\nTG🇹🇬228Togo233\nTH🇹🇭66Thailand144\nTJ🇹🇯992Tajikistan\nTK🇹🇰690Tokelau\nTM🇹🇲993Turkmenistan26\nTL🇹🇱670Timor-Leste\nTO🇹🇴676Tonga\nTT🇹🇹1868Trinidad and Tobago34\nTN🇹🇳216Tunisia233\nTR🇹🇷90Turkey334\nTV🇹🇻688Tuvalu\nTW🇹🇼886Taiwan\nTZ🇹🇿255Tanzania234\nUG🇺🇬256Uganda234\nUA🇺🇦380Ukraine2322\nUY🇺🇾598Uruguay44\nUS🇺🇸1United States334\nUZ🇺🇿998Uzbekistan27\nVA🇻🇦3Vatican City\nVC🇻🇨1784Saint Vincent and the Grenadines34\nVE🇻🇪58Venezuela334\nVG🇻🇬1284British Virgin Islands34\nVI🇻🇮1340US Virgin Islands34\nVN🇻🇳84Vietnam\nVU🇻🇺678Vanuatu\nWF🇼🇫681Wallis and Futuna\nWS🇼🇸685Samoa\nXK🇽🇰383Kosovo44\nYE🇾🇪967Yemen333\nZA🇿🇦27South Africa234\nZM🇿🇲260Zambia234\nZW🇿🇼263Zimbabwe234`;\n\nconst formatsCache: Record<string, RegExp> = {};\nexport const defaultPhoneNumberFormat = /(\\d{1,3})(\\d{1,3})?(\\d{1,3})?(\\d{1,3})?(\\d{1,3})?/;\n\nconst parsed = DATA\n .split('\\n')\n .map((str) => {\n const id = str.substr(0, 2);\n const flag = str.substr(2, 4);\n const code = `+${str.match(/\\d+/)![0]}`;\n const name = str.split(/\\d+/)[1];\n const format = str.match(/\\d+$/);\n const phoneFormat = getPhoneNumberFormat(format);\n\n return {\n id, flag, code, name, phoneFormat,\n };\n });\n\nfunction getPhoneNumberFormat(format: RegExpMatchArray | null) {\n if (!format) {\n return defaultPhoneNumberFormat;\n }\n\n const formatValue = format[0] as string;\n let phoneNumberFormat;\n\n if (!formatsCache[formatValue]) {\n const phoneNumberGroups = formatValue.split('').map(Number);\n phoneNumberFormat = phoneNumberGroups.reduce((result, count, i) => {\n return `${result}(\\\\d{1,${count}})${i > 0 ? '?' : ''}`;\n }, '');\n formatsCache[formatValue] = new RegExp(`${phoneNumberFormat}${'()?'.repeat(5 - phoneNumberGroups.length)}`);\n }\n\n return formatsCache[formatValue];\n}\n\nexport default parsed;\n","import countryList, { defaultPhoneNumberFormat } from './countries';\n\nexport function getCountryById(id: string) {\n return countryList.find((c) => c.id === id) as Country;\n}\n\n// Empty groups are used to preserve 5 callback arguments for `replace` method\nfunction getPhoneNumberFormat(country?: Country) {\n return country ? country.phoneFormat : defaultPhoneNumberFormat;\n}\n\nexport function getCountryFromPhoneNumber(input: string) {\n let phoneNumber = input.replace(/[^\\d+]+/g, '');\n if (!phoneNumber.startsWith('+')) {\n phoneNumber = `+${phoneNumber}`;\n }\n\n const possibleCountries = countryList\n .filter((country: Country) => phoneNumber.startsWith(country.code))\n .sort((a, b) => a.code.length - b.code.length);\n\n return possibleCountries[possibleCountries.length - 1];\n}\n\nexport function formatPhoneNumber(input: string, country?: Country) {\n let phoneNumber = input.replace(/[^\\d]+/g, '');\n if (country) {\n phoneNumber = phoneNumber.substr(country.code.length - 1);\n } else if (input.startsWith('+')) {\n return input;\n }\n\n phoneNumber = phoneNumber.replace(getPhoneNumberFormat(country), (_, p1, p2, p3, p4, p5) => {\n const separator = country && country.id === 'GB' ? ' ' : '-';\n\n let output = '';\n if (p1) output = `${p1}`;\n if (p2) output += ` ${p2}`;\n if (p3) output += `${separator}${p3}`;\n if (p4) output += `${separator}${p4}`;\n if (p5) output += `${separator}${p5}`;\n return output;\n });\n\n return phoneNumber;\n}\n\nexport function formatPhoneNumberWithCode(phoneNumber: string) {\n const numberWithPlus = phoneNumber.startsWith('+') ? phoneNumber : `+${phoneNumber}`;\n const country = getCountryFromPhoneNumber(numberWithPlus);\n if (!country) {\n return numberWithPlus;\n }\n return `${country.code} ${formatPhoneNumber(numberWithPlus, country)}`;\n}\n\nexport { countryList };\n","import { useCallback, useState } from '../lib/teact/teact';\n\nexport default (initial = false): [boolean, AnyToVoidFunction, AnyToVoidFunction] => {\n const [value, setValue] = useState(initial);\n\n const setTrue = useCallback(() => {\n setValue(true);\n }, []);\n\n const setFalse = useCallback(() => {\n setValue(false);\n }, []);\n\n return [value, setTrue, setFalse];\n};\n","import { useEffect } from '../lib/teact/teact';\n\nimport {\n BundleModules, Bundles, getModuleFromMemory, loadModule, addLoadListener,\n} from '../util/moduleLoader';\n\nimport useForceUpdate from './useForceUpdate';\n\nexport default <B extends Bundles, M extends BundleModules<B>>(\n bundleName: B, moduleName: M, noLoad = false, autoUpdate = false,\n) => {\n const module = getModuleFromMemory(bundleName, moduleName);\n const forceUpdate = useForceUpdate();\n\n if (autoUpdate) {\n // Use effect and cleanup for listener removal\n addLoadListener(forceUpdate);\n }\n\n useEffect(() => {\n if (!noLoad && !module) {\n loadModule(bundleName, moduleName).then(forceUpdate);\n }\n }, [bundleName, forceUpdate, module, moduleName, noLoad]);\n\n return module;\n};\n","import React, { FC } from '../../lib/teact/teact';\n\nimport buildClassName from '../../util/buildClassName';\n\nimport './Spinner.scss';\n\nconst Spinner: FC<{\n color?: 'blue' | 'white' | 'black' | 'green' | 'gray';\n withBackground?: boolean;\n}> = ({\n color = 'blue',\n withBackground,\n}) => {\n return (\n <div className={buildClassName('Spinner', color, withBackground && 'with-background')}>\n <div />\n </div>\n );\n};\n\nexport default Spinner;\n","import { DEBUG_ALERT_MSG } from '../config';\nimport { throttle } from './schedulers';\n\nwindow.addEventListener('error', handleErrorEvent);\nwindow.addEventListener('unhandledrejection', handleErrorEvent);\n\n// eslint-disable-next-line prefer-destructuring\nconst APP_ENV = process.env.APP_ENV;\n\nfunction handleErrorEvent(e: ErrorEvent | PromiseRejectionEvent) {\n e.preventDefault();\n\n handleError(e instanceof ErrorEvent ? e.error : e.reason);\n}\n\nconst throttledAlert = throttle(window.alert, 1000);\n\nexport function handleError(err: Error) {\n // eslint-disable-next-line no-console\n console.error(err);\n\n if (APP_ENV === 'development' || APP_ENV === 'staging') {\n throttledAlert(`${DEBUG_ALERT_MSG}\\n\\n${(err && err.message) || err}\\n${err && err.stack}`);\n }\n}\n","export default function arePropsShallowEqual(currentProps: AnyLiteral, newProps: AnyLiteral) {\n if (currentProps === newProps) {\n return true;\n }\n\n const currentKeys = Object.keys(currentProps);\n const currentKeysLength = currentKeys.length;\n const newKeysLength = Object.keys(newProps).length;\n\n if (currentKeysLength !== newKeysLength) {\n return false;\n }\n\n if (currentKeysLength === 0) {\n return true;\n }\n\n for (let i = 0; i < currentKeysLength; i++) {\n const prop = currentKeys[i];\n if (currentProps[prop] !== newProps[prop]) {\n return false;\n }\n }\n\n return true;\n}\n\nexport function getUnequalProps(currentProps: AnyLiteral, newProps: AnyLiteral) {\n const currentKeys = Object.keys(currentProps);\n const currentKeysLength = currentKeys.length;\n const newKeysLength = Object.keys(newProps).length;\n\n if (currentKeysLength !== newKeysLength) {\n return ['%LENGTH%'];\n }\n\n return currentKeys.reduce((res, prop) => {\n if (currentProps[prop] !== newProps[prop]) {\n res.push(`${prop}: ${currentProps[prop]} => ${newProps[prop]}`);\n }\n\n return res;\n }, [] as string[]);\n}\n","import { useRef } from '../lib/teact/teact';\n\nfunction usePrevious<T extends any>(next: T): T | undefined;\nfunction usePrevious<T extends any>(next: T, shouldSkipUndefined: true): Exclude<T, undefined> | undefined;\nfunction usePrevious<T extends any>(next: T, shouldSkipUndefined?: boolean): Exclude<T, undefined> | undefined;\nfunction usePrevious<T extends any>(next: T, shouldSkipUndefined?: boolean) {\n const ref = useRef<T>();\n const { current } = ref;\n if (!shouldSkipUndefined || next !== undefined) {\n ref.current = next;\n }\n\n return current;\n}\n\nexport default usePrevious;\n","import { LangFn } from '../hooks/useLang';\n\nconst WEEKDAYS_FULL = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];\nconst MONTHS_FULL = [\n 'January', 'February', 'March', 'April', 'May', 'June',\n 'July', 'August', 'September', 'October', 'November', 'December',\n];\n\nconst MONTHS_FULL_LOWERCASE = MONTHS_FULL.map((month) => month.toLowerCase());\nconst MIN_SEARCH_YEAR = 2015;\nconst MAX_DAY_IN_MONTH = 31;\nconst MAX_MONTH_IN_YEAR = 12;\nexport const MILISECONDS_IN_DAY = 24 * 60 * 60 * 1000;\n\nexport function getDayStart(datetime: number | Date) {\n const date = new Date(datetime);\n date.setHours(0, 0, 0, 0);\n return date;\n}\n\nexport function getDayStartAt(datetime: number | Date) {\n return getDayStart(datetime).getTime();\n}\n\nexport function toYearMonth(timestamp: number) {\n const date = new Date(timestamp * 1000);\n return `${date.getFullYear()}-${date.getMonth()}`;\n}\n\nfunction toIsoString(date: Date) {\n return `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`;\n}\n\nexport function formatTime(datetime: number | Date) {\n const date = typeof datetime === 'number' ? new Date(datetime) : datetime;\n const hours = String(date.getHours()).padStart(2, '0');\n const minutes = String(date.getMinutes()).padStart(2, '0');\n\n return `${hours}:${minutes}`;\n}\n\nexport function formatPastTimeShort(lang: LangFn, datetime: number | Date) {\n const date = typeof datetime === 'number' ? new Date(datetime) : datetime;\n\n const today = getDayStart(new Date());\n if (date >= today) {\n return formatTime(date);\n }\n\n const weekAgo = new Date(today);\n weekAgo.setDate(today.getDate() - 7);\n if (date >= weekAgo) {\n return lang(`Weekday.Short${WEEKDAYS_FULL[date.getDay()]}`);\n }\n\n const withYear = date.getFullYear() !== today.getFullYear();\n const format = (\n lang(withYear ? 'formatDateScheduleYear' : 'formatDateSchedule')\n || (withYear ? 'd MMM yyyy' : 'd MMM')\n );\n\n return formatDate(lang, date, format);\n}\n\nexport function formatFullDate(lang: LangFn, datetime: number | Date) {\n const date = typeof datetime === 'number' ? new Date(datetime) : datetime;\n const format = lang('formatterYearMax') || 'dd.MM.yyyy';\n\n return formatDate(lang, date, format);\n}\n\nexport function formatMonthAndYear(lang: LangFn, date: Date, isShort = false) {\n const format = lang(isShort ? 'formatterMonthYear2' : 'formatterMonthYear') || 'MMM yyyy';\n\n return formatDate(lang, date, format);\n}\n\nexport function formatHumanDate(lang: LangFn, datetime: number | Date, isShort = false, noWeekdays = false) {\n const date = typeof datetime === 'number' ? new Date(datetime) : datetime;\n\n const today = getDayStart(new Date());\n\n if (!noWeekdays) {\n if (toIsoString(date) === toIsoString(today)) {\n return (isShort ? lowerFirst : upperFirst)(lang('Weekday.Today'));\n }\n\n const yesterday = new Date(today);\n yesterday.setDate(today.getDate() - 1);\n if (toIsoString(date) === toIsoString(yesterday)) {\n return (isShort ? lowerFirst : upperFirst)(lang('Weekday.Yesterday'));\n }\n\n const weekAgo = new Date(today);\n const weekAhead = new Date(today);\n weekAgo.setDate(today.getDate() - 7);\n weekAhead.setDate(today.getDate() + 7);\n if (date >= weekAgo && date <= weekAhead) {\n const weekDay = WEEKDAYS_FULL[date.getDay()];\n return isShort\n ? lowerFirst(lang(`Weekday.Short${weekDay}`))\n : upperFirst(lang(`Weekday.${weekDay}`));\n }\n }\n\n const withYear = date.getFullYear() !== today.getFullYear();\n const formatKey = isShort\n ? (withYear ? 'formatDateScheduleYear' : 'formatDateSchedule')\n : (withYear ? 'chatFullDate' : 'chatDate');\n const format = lang(formatKey) || 'd MMMM yyyy';\n\n return (isShort ? lowerFirst : upperFirst)(formatDate(lang, date, format));\n}\n\nfunction formatDate(lang: LangFn, date: Date, format: string) {\n const day = date.getDate();\n const monthIndex = date.getMonth();\n\n return format\n .replace('LLLL', lang(MONTHS_FULL[monthIndex]))\n .replace('MMMM', lang(`Month.Gen${MONTHS_FULL[monthIndex]}`))\n .replace('MMM', lang(`Month.Short${MONTHS_FULL[monthIndex]}`))\n .replace('MM', String(monthIndex + 1).padStart(2, '0'))\n .replace('dd', String(day).padStart(2, '0'))\n .replace('d', String(day))\n .replace('yyyy', String(date.getFullYear()));\n}\n\nexport function formatMediaDateTime(lang: LangFn, datetime: number | Date) {\n const date = typeof datetime === 'number' ? new Date(datetime) : datetime;\n\n return `${formatHumanDate(lang, date, true)}, ${formatTime(date)}`;\n}\n\nexport function formatMediaDuration(duration: number) {\n const hours = Math.floor(duration / 3600);\n const minutes = Math.floor((duration % 3600) / 60);\n const seconds = Math.floor(duration % 3600 % 60);\n\n let string = '';\n if (hours > 0) {\n string += `${String(hours).padStart(2, '0')}:`;\n string += `${String(minutes).padStart(2, '0')}:`;\n } else {\n string += `${String(minutes)}:`;\n }\n string += String(seconds).padStart(2, '0');\n\n return string;\n}\n\nexport function formatVoiceRecordDuration(durationInMs: number) {\n const parts = [];\n\n let milliseconds = durationInMs % 1000;\n durationInMs -= milliseconds;\n milliseconds = Math.floor(milliseconds / 10);\n\n durationInMs = Math.floor(durationInMs / 1000);\n const seconds = durationInMs % 60;\n durationInMs -= seconds;\n\n durationInMs = Math.floor(durationInMs / 60);\n const minutes = durationInMs % 60;\n durationInMs -= minutes;\n\n durationInMs = Math.floor(durationInMs / 60);\n const hours = durationInMs % 60;\n\n if (hours > 0) {\n parts.push(String(hours).padStart(2, '0'));\n }\n parts.push(String(minutes).padStart(hours > 0 ? 2 : 1, '0'));\n parts.push(String(seconds).padStart(2, '0'));\n\n return `${parts.join(':')},${String(milliseconds).padStart(2, '0')}`;\n}\n\nexport function formatDateToString(date: Date, locale = 'en-US') {\n return date.toLocaleString(\n locale,\n {\n year: 'numeric',\n month: 'short',\n day: 'numeric',\n },\n );\n}\n\nfunction isValidDate(day: number, month: number, year = 2021): boolean {\n if (month > (MAX_MONTH_IN_YEAR - 1) || day > MAX_DAY_IN_MONTH) {\n return false;\n }\n const date = new Date(year, month, day);\n return !Number.isNaN(date.getTime()) && date.getDate() === day;\n}\n\nexport function parseDateString(query = ''): string | undefined {\n const matchStringDate = query.match(/\\d{1,2}\\s[a-zA-Z]{3,}/);\n const matchEuropeStringDate = query.match(/[a-zA-Z]{3,}\\s\\d{1,2}/);\n const matchNumberDate = query.match(/\\d{1,2}[./-]\\d{1,2}([./-]\\d{2,4})?/);\n if (!matchStringDate && !matchNumberDate && !matchEuropeStringDate) {\n return undefined;\n }\n\n if (matchNumberDate) {\n const [date, month, year] = query.split(/[./-]/).map(Number);\n return !(year && year < MIN_SEARCH_YEAR) && isValidDate(date, month - 1, year || undefined)\n ? `${year ? `${year}-` : ''}${String(month).padStart(2, '0')}-${String(date).padStart(2, '0')}`\n : undefined;\n }\n\n const dateParts = query.split(' ');\n const date = matchStringDate ? dateParts[0] : dateParts[1];\n const month = (matchStringDate ? dateParts[1] : dateParts[0]).toLowerCase();\n const monthIndex = MONTHS_FULL_LOWERCASE.findIndex((item) => item.startsWith(month));\n\n return monthIndex !== -1 && isValidDate(Number(date), monthIndex)\n ? `${String(monthIndex + 1).padStart(2, '0')}-${String(date).padStart(2, '0')}`\n : undefined;\n}\n\nexport function timestampPlusDay(timestamp: number) {\n return timestamp + MILISECONDS_IN_DAY / 1000;\n}\n\nfunction lowerFirst(str: string) {\n return `${str[0].toLowerCase()}${str.slice(1)}`;\n}\n\nfunction upperFirst(str: string) {\n return `${str[0].toUpperCase()}${str.slice(1)}`;\n}\n","import { APP_VERSION } from '../config';\nimport { getGlobal } from '../lib/teact/teactn';\nimport { hasStoredSession } from './sessions';\n\nconst WEBSYNC_URLS = [\n 't.me',\n 'telegram.me',\n].map((domain) => `//${domain}/_websync_?`);\nconst WEBSYNC_VERSION = `${APP_VERSION} Z`;\nconst WEBSYNC_KEY = 'tgme_sync';\nconst WEBSYNC_TIMEOUT = 86400;\n\nconst getTs = () => {\n return Math.floor(Number(new Date()) / 1000);\n};\n\nconst saveSync = (authed: boolean) => {\n const ts = getTs();\n localStorage.setItem(WEBSYNC_KEY, JSON.stringify({\n canRedirect: authed,\n ts,\n }));\n};\n\nlet lastTimeout: NodeJS.Timeout | undefined;\n\nexport const forceWebsync = (authed: boolean) => {\n const currentTs = getTs();\n\n const { canRedirect, ts } = JSON.parse(localStorage.getItem(WEBSYNC_KEY) || '{}');\n\n if (canRedirect !== authed || ts + WEBSYNC_TIMEOUT <= currentTs) {\n return Promise.all(WEBSYNC_URLS.map((url) => {\n return new Promise((resolve, reject) => {\n const script = document.createElement('script');\n\n const removeElement = () => !!document.body.removeChild(script);\n\n script.src = url + new URLSearchParams({\n authed: Number(authed).toString(),\n version: WEBSYNC_VERSION,\n });\n\n document.body.appendChild(script);\n\n script.onload = () => {\n saveSync(authed);\n removeElement();\n if (lastTimeout) {\n clearTimeout(lastTimeout);\n lastTimeout = undefined;\n }\n startWebsync();\n resolve();\n };\n\n script.onerror = () => {\n removeElement();\n reject();\n };\n });\n }));\n } else {\n return Promise.resolve();\n }\n};\n\nexport function startWebsync() {\n if (lastTimeout !== undefined) return;\n const currentTs = getTs();\n\n const { ts } = JSON.parse(localStorage.getItem(WEBSYNC_KEY) || '{}');\n\n const timeout = WEBSYNC_TIMEOUT - (currentTs - ts);\n\n lastTimeout = setTimeout(() => {\n const { authState } = getGlobal();\n\n const authed = authState === 'authorizationStateReady' || hasStoredSession(true);\n forceWebsync(authed);\n }, Math.max(0, timeout * 1000));\n}\n","import { useCallback, useState } from '../lib/teact/teact';\n\nexport default () => {\n const [, setTrigger] = useState<boolean>(false);\n\n return useCallback(() => {\n setTrigger((trigger) => !trigger);\n }, []);\n};\n","import DecoderWorker from 'worker-loader!opus-recorder/dist/decoderWorker.min';\nimport WavWorker from 'worker-loader!opus-recorder/dist/waveWorker.min';\n\nconst SAMPLE_RATE = 48000;\nconst BIT_DEPTH = 16;\n\nexport async function oggToWav(opusData: Blob): Promise<Blob> {\n const arrayBuffer = await new Response(opusData).arrayBuffer();\n\n return new Promise((resolve) => {\n const typedArray = new Uint8Array(arrayBuffer);\n\n let decoderWorker: DecoderWorker | undefined = new DecoderWorker();\n let wavWorker: WavWorker | undefined = new WavWorker();\n\n decoderWorker.onmessage = (e) => {\n // eslint-disable-next-line no-null/no-null\n if (e.data === null) {\n // `null` means decoder is finished\n wavWorker!.postMessage({ command: 'done' });\n } else {\n // `e.data` contains decoded buffers as float32 values\n wavWorker!.postMessage(\n {\n command: 'encode',\n buffers: e.data,\n },\n e.data.map(({ buffer }: Float32Array) => buffer),\n );\n }\n };\n\n wavWorker.onmessage = (e) => {\n if (e.data.message === 'page') {\n resolve(new Blob([e.data.page], { type: 'audio/wav' }));\n\n decoderWorker!.terminate();\n decoderWorker = undefined;\n wavWorker!.terminate();\n wavWorker = undefined;\n }\n };\n\n wavWorker.postMessage({\n command: 'init',\n wavBitDepth: BIT_DEPTH,\n wavSampleRate: SAMPLE_RATE,\n });\n\n decoderWorker.postMessage({\n command: 'init',\n decoderSampleRate: SAMPLE_RATE,\n outputBufferSampleRate: SAMPLE_RATE,\n });\n\n decoderWorker.postMessage({\n command: 'decode',\n pages: typedArray,\n }, [typedArray.buffer]);\n });\n}\n","import {\n ApiMediaFormat,\n ApiMediaFormatToPrepared,\n ApiOnProgress,\n ApiParsedMedia,\n ApiPreparedMedia,\n} from '../api/types';\n\nimport {\n DEBUG, MEDIA_CACHE_DISABLED, MEDIA_CACHE_NAME, MEDIA_CACHE_NAME_AVATARS, TRANSPARENT_PIXEL,\n} from '../config';\nimport { callApi, cancelApiProgress } from '../api/gramjs';\nimport * as cacheApi from './cacheApi';\nimport { dataUriToBlob, fetchBlob } from './files';\nimport { IS_OPUS_SUPPORTED, IS_PROGRESSIVE_SUPPORTED, isWebpSupported } from './environment';\nimport { oggToWav } from './oggToWav';\nimport { webpToPng } from './webpToPng';\n\nconst asCacheApiType = {\n [ApiMediaFormat.DataUri]: cacheApi.Type.Text,\n [ApiMediaFormat.BlobUrl]: cacheApi.Type.Blob,\n [ApiMediaFormat.Lottie]: cacheApi.Type.Json,\n [ApiMediaFormat.Progressive]: undefined,\n [ApiMediaFormat.Stream]: undefined,\n};\n\nconst PROGRESSIVE_URL_PREFIX = './progressive/';\n\nconst memoryCache = new Map<string, ApiPreparedMedia>();\nconst fetchPromises = new Map<string, Promise<ApiPreparedMedia | undefined>>();\n\nexport function fetch<T extends ApiMediaFormat>(\n url: string, mediaFormat: T, onProgress?: ApiOnProgress,\n): Promise<ApiMediaFormatToPrepared<T>> {\n if (mediaFormat === ApiMediaFormat.Progressive) {\n return (\n IS_PROGRESSIVE_SUPPORTED\n ? getProgressive(url)\n : fetch(url, ApiMediaFormat.BlobUrl, onProgress)\n ) as Promise<ApiMediaFormatToPrepared<T>>;\n }\n\n if (!fetchPromises.has(url)) {\n const promise = fetchFromCacheOrRemote(url, mediaFormat, onProgress)\n .catch((err) => {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.warn(err);\n }\n\n return undefined;\n })\n .finally(() => {\n fetchPromises.delete(url);\n });\n\n fetchPromises.set(url, promise);\n }\n\n return fetchPromises.get(url) as Promise<ApiMediaFormatToPrepared<T>>;\n}\n\nexport function getFromMemory<T extends ApiMediaFormat>(url: string) {\n return memoryCache.get(url) as ApiMediaFormatToPrepared<T>;\n}\n\nexport function cancelProgress(progressCallback: ApiOnProgress) {\n cancelApiProgress(progressCallback);\n}\n\nfunction getProgressive(url: string) {\n const progressiveUrl = `${PROGRESSIVE_URL_PREFIX}${url}`;\n\n memoryCache.set(url, progressiveUrl);\n\n return Promise.resolve(progressiveUrl);\n}\n\nasync function fetchFromCacheOrRemote(url: string, mediaFormat: ApiMediaFormat, onProgress?: ApiOnProgress) {\n if (!MEDIA_CACHE_DISABLED) {\n const cacheName = url.startsWith('avatar') ? MEDIA_CACHE_NAME_AVATARS : MEDIA_CACHE_NAME;\n const cached = await cacheApi.fetch(cacheName, url, asCacheApiType[mediaFormat]!);\n if (cached) {\n let media = cached;\n\n if (cached.type === 'audio/ogg' && !IS_OPUS_SUPPORTED) {\n media = await oggToWav(media);\n }\n\n if (cached.type === 'image/webp' && !isWebpSupported() && media) {\n const mediaPng = await webpToPng(url, media);\n if (mediaPng) {\n media = mediaPng;\n }\n }\n\n const prepared = prepareMedia(media);\n\n memoryCache.set(url, prepared);\n\n return prepared;\n }\n }\n\n if (mediaFormat === ApiMediaFormat.Stream) {\n const mediaSource = new MediaSource();\n const streamUrl = URL.createObjectURL(mediaSource);\n let isOpen = false;\n\n mediaSource.addEventListener('sourceopen', () => {\n if (isOpen) {\n return;\n }\n isOpen = true;\n\n const sourceBuffer = mediaSource.addSourceBuffer('audio/mpeg');\n\n void callApi('downloadMedia', { url, mediaFormat }, (progress: number, arrayBuffer: ArrayBuffer) => {\n if (onProgress) {\n onProgress(progress);\n }\n\n if (progress === 1) {\n mediaSource.endOfStream();\n }\n\n if (!arrayBuffer) {\n return;\n }\n\n sourceBuffer.appendBuffer(arrayBuffer!);\n });\n });\n\n memoryCache.set(url, streamUrl);\n return streamUrl;\n }\n\n const remote = await callApi('downloadMedia', { url, mediaFormat }, onProgress);\n if (!remote) {\n throw new Error('Failed to fetch media');\n }\n\n let { prepared, mimeType } = remote;\n\n if (mimeType === 'audio/ogg' && !IS_OPUS_SUPPORTED) {\n const blob = await fetchBlob(prepared as string);\n URL.revokeObjectURL(prepared as string);\n const media = await oggToWav(blob);\n prepared = prepareMedia(media);\n mimeType = blob.type;\n }\n\n if (mimeType === 'image/webp' && !isWebpSupported()) {\n const blob = await fetchBlob(prepared as string);\n URL.revokeObjectURL(prepared as string);\n const media = await webpToPng(url, blob);\n if (media) {\n prepared = prepareMedia(media);\n }\n }\n\n memoryCache.set(url, prepared);\n\n return prepared;\n}\n\nfunction prepareMedia(mediaData: ApiParsedMedia): ApiPreparedMedia {\n if (mediaData instanceof Blob) {\n // Prevent HTML-in-video attacks\n if (mediaData.type.includes('text/html')) {\n return URL.createObjectURL(dataUriToBlob(TRANSPARENT_PIXEL));\n }\n\n return URL.createObjectURL(mediaData);\n }\n\n return mediaData;\n}\n\nif (IS_PROGRESSIVE_SUPPORTED) {\n navigator.serviceWorker.addEventListener('message', async (e) => {\n const { type, messageId, params } = e.data as {\n type: string;\n messageId: string;\n params: { url: string; start: number; end: number };\n };\n\n if (type !== 'requestPart') {\n return;\n }\n\n const result = await callApi('downloadMedia', { mediaFormat: ApiMediaFormat.Progressive, ...params });\n if (!result) {\n return;\n }\n\n const { arrayBuffer, mimeType, fullSize } = result;\n\n navigator.serviceWorker.controller!.postMessage({\n type: 'partResponse',\n messageId,\n result: {\n arrayBuffer,\n mimeType,\n fullSize,\n },\n }, [arrayBuffer!]);\n });\n}\n","import React, { FC, useCallback } from '../../lib/teact/teact';\n\nimport buildClassName from '../../util/buildClassName';\n\nimport './Link.scss';\n\ntype OwnProps = {\n children: any;\n className?: string;\n isRtl?: boolean;\n onClick?: (e: React.MouseEvent<HTMLAnchorElement>) => void;\n};\n\nconst Link: FC<OwnProps> = ({\n children, className, isRtl, onClick,\n}) => {\n const handleClick = useCallback((e: React.MouseEvent<HTMLAnchorElement>) => {\n e.preventDefault();\n onClick!(e);\n }, [onClick]);\n\n return (\n <a\n href=\"#\"\n className={buildClassName('Link', className)}\n dir={isRtl ? 'rtl' : 'auto'}\n onClick={onClick ? handleClick : undefined}\n >\n {children}\n </a>\n );\n};\n\nexport default Link;\n","export default (store: AnyLiteral) => {\n let id;\n\n do {\n id = String(Math.random()).replace('0.', 'id');\n } while (store.hasOwnProperty(id));\n\n return id;\n};\n","import { ApiChat, ApiUser } from '../../api/types';\n\nimport { SERVICE_NOTIFICATIONS_USER_ID } from '../../config';\nimport { formatFullDate, formatTime } from '../../util/dateFormat';\nimport { orderBy } from '../../util/iteratees';\nimport { LangFn } from '../../hooks/useLang';\n\nconst USER_COLOR_KEYS = [1, 8, 5, 2, 7, 4, 6];\n\nexport function getUserFirstOrLastName(user?: ApiUser) {\n if (!user) {\n return undefined;\n }\n\n switch (user.type) {\n case 'userTypeBot':\n case 'userTypeRegular': {\n return user.firstName || user.lastName;\n }\n\n case 'userTypeDeleted':\n case 'userTypeUnknown': {\n return 'Deleted';\n }\n\n default:\n return undefined;\n }\n}\n\nexport function getUserFullName(user?: ApiUser) {\n if (!user) {\n return undefined;\n }\n\n if (isDeletedUser(user)) {\n return 'Deleted account';\n }\n\n switch (user.type) {\n case 'userTypeBot':\n case 'userTypeRegular': {\n if (user.firstName && user.lastName) {\n return `${user.firstName} ${user.lastName}`;\n }\n\n if (user.firstName) {\n return user.firstName;\n }\n\n if (user.lastName) {\n return user.lastName;\n }\n\n break;\n }\n\n case 'userTypeDeleted':\n case 'userTypeUnknown': {\n return 'Deleted account';\n }\n }\n\n return undefined;\n}\n\nexport function getUserStatus(lang: LangFn, user: ApiUser, serverTimeOffset: number) {\n if (user.id === SERVICE_NOTIFICATIONS_USER_ID) {\n return lang('ServiceNotifications').toLowerCase();\n }\n\n if (user.type && user.type === 'userTypeBot') {\n return lang('Bot');\n }\n\n if (!user.status) {\n return '';\n }\n\n switch (user.status.type) {\n case 'userStatusEmpty': {\n return lang('ALongTimeAgo');\n }\n\n case 'userStatusLastMonth': {\n return lang('WithinAMonth');\n }\n\n case 'userStatusLastWeek': {\n return lang('WithinAWeek');\n }\n\n case 'userStatusOffline': {\n const { wasOnline } = user.status;\n\n if (!wasOnline) return lang('LastSeen.Offline');\n\n const now = new Date(new Date().getTime() + serverTimeOffset * 1000);\n const wasOnlineDate = new Date(wasOnline * 1000);\n\n if (wasOnlineDate >= now) {\n return lang('LastSeen.JustNow');\n }\n\n const diff = new Date(now.getTime() - wasOnlineDate.getTime());\n\n // within a minute\n if (diff.getTime() / 1000 < 60) {\n return lang('LastSeen.JustNow');\n }\n\n // within an hour\n if (diff.getTime() / 1000 < 60 * 60) {\n const minutes = Math.floor(diff.getTime() / 1000 / 60);\n return lang('LastSeen.MinutesAgo', minutes);\n }\n\n // today\n const today = new Date();\n today.setHours(0, 0, 0, 0);\n const serverToday = new Date(today.getTime() + serverTimeOffset * 1000);\n if (wasOnlineDate > serverToday) {\n // up to 6 hours ago\n if (diff.getTime() / 1000 < 6 * 60 * 60) {\n const hours = Math.floor(diff.getTime() / 1000 / 60 / 60);\n return lang('LastSeen.HoursAgo', hours);\n }\n\n // other\n return lang('LastSeen.TodayAt', formatTime(wasOnlineDate));\n }\n\n // yesterday\n const yesterday = new Date();\n yesterday.setDate(now.getDate() - 1);\n yesterday.setHours(0, 0, 0, 0);\n const serverYesterday = new Date(yesterday.getTime() + serverTimeOffset * 1000);\n if (wasOnlineDate > serverYesterday) {\n return lang('LastSeen.YesterdayAt', formatTime(wasOnlineDate));\n }\n\n return lang('LastSeen.AtDate', formatFullDate(lang, wasOnlineDate));\n }\n\n case 'userStatusOnline': {\n return lang('Online');\n }\n\n case 'userStatusRecently': {\n return lang('Lately');\n }\n\n default:\n return undefined;\n }\n}\n\nexport function isUserOnline(user: ApiUser) {\n const { id, status, type } = user;\n\n if (!status) {\n return false;\n }\n\n if (id === SERVICE_NOTIFICATIONS_USER_ID) {\n return false;\n }\n\n return status.type === 'userStatusOnline' && type !== 'userTypeBot';\n}\n\nexport function isDeletedUser(user: ApiUser) {\n if (!user.status || user.type === 'userTypeBot' || user.id === SERVICE_NOTIFICATIONS_USER_ID) {\n return false;\n }\n\n return user.type === 'userTypeDeleted'\n || user.type === 'userTypeUnknown';\n}\n\nexport function isUserBot(user: ApiUser) {\n return user.type === 'userTypeBot';\n}\n\nexport function sortUserIds(\n userIds: number[],\n usersById: Record<number, ApiUser>,\n priorityIds?: number[],\n serverTimeOffset = 0,\n) {\n return orderBy(userIds, (id) => {\n const now = Date.now() / 1000 + serverTimeOffset;\n\n if (priorityIds && priorityIds.includes(id)) {\n // Assuming that online status expiration date can't be as far as two days from now,\n // this should place prioritized on top of the list.\n // Then we subtract index of `id` in `priorityIds` to preserve selected order\n return now + (48 * 60 * 60) - (priorityIds.length - priorityIds.indexOf(id));\n }\n\n const user = usersById[id];\n if (!user || !user.status) {\n return 0;\n }\n\n if (user.status.type === 'userStatusOnline') {\n return user.status.expires;\n } else if (user.status.type === 'userStatusOffline' && user.status.wasOnline) {\n return user.status.wasOnline;\n }\n\n switch (user.status.type) {\n case 'userStatusRecently':\n return now - 60 * 60 * 24;\n case 'userStatusLastWeek':\n return now - 60 * 60 * 24 * 7;\n case 'userStatusLastMonth':\n return now - 60 * 60 * 24 * 7 * 30;\n default:\n return 0;\n }\n }, 'desc');\n}\n\n// eslint-disable-next-line max-len\n// https://github.com/telegramdesktop/tdesktop/blob/371510cfe23b0bd226de8c076bc49248fbe40c26/Telegram/SourceFiles/data/data_peer.cpp#L53\nexport function getUserColorKey(peer: ApiUser | ApiChat | undefined) {\n const index = peer ? Math.abs(peer.id) % 7 : 0;\n\n return USER_COLOR_KEYS[index];\n}\n","import {\n ApiChat,\n ApiUser,\n ApiChatBannedRights,\n ApiChatAdminRights,\n ApiChatFolder,\n MAIN_THREAD_ID,\n} from '../../api/types';\n\nimport { NotifyException, NotifySettings } from '../../types';\nimport { LangFn } from '../../hooks/useLang';\n\nimport { ARCHIVED_FOLDER_ID } from '../../config';\nimport { orderBy } from '../../util/iteratees';\nimport { getUserFirstOrLastName } from './users';\nimport { formatDateToString, formatTime } from '../../util/dateFormat';\n\nconst FOREVER_BANNED_DATE = Date.now() / 1000 + 31622400; // 366 days\n\nconst VERIFIED_PRIORITY_BASE = 3e9;\nconst PINNED_PRIORITY_BASE = 3e8;\n\nexport function isChatPrivate(chatId: number) {\n return chatId > 0;\n}\n\nexport function isChatGroup(chat: ApiChat) {\n return isChatBasicGroup(chat) || isChatSuperGroup(chat);\n}\n\nexport function isChatBasicGroup(chat: ApiChat) {\n return chat.type === 'chatTypeBasicGroup';\n}\n\nexport function isChatSuperGroup(chat: ApiChat) {\n return chat.type === 'chatTypeSuperGroup';\n}\n\nexport function isChatChannel(chat: ApiChat) {\n return chat.type === 'chatTypeChannel';\n}\n\nexport function isCommonBoxChat(chat: ApiChat) {\n return chat.type === 'chatTypePrivate' || chat.type === 'chatTypeBasicGroup';\n}\n\nexport function getChatTypeString(chat: ApiChat) {\n switch (chat.type) {\n case 'chatTypePrivate':\n return 'PrivateChat';\n case 'chatTypeBasicGroup':\n case 'chatTypeSuperGroup':\n return 'AccDescrGroup';\n case 'chatTypeChannel':\n return 'AccDescrChannel';\n default:\n return 'Chat';\n }\n}\n\nexport function getPrivateChatUserId(chat: ApiChat) {\n if (chat.type !== 'chatTypePrivate' && chat.type !== 'chatTypeSecret') {\n return undefined;\n }\n return chat.id;\n}\n\n// TODO Get rid of `user`\nexport function getChatTitle(lang: LangFn, chat: ApiChat, user?: ApiUser, isSelf = false) {\n if (isSelf || (user && chat.id === user.id && user.isSelf)) {\n return lang('SavedMessages');\n }\n return chat.title || lang('HiddenName');\n}\n\nexport function getChatDescription(chat: ApiChat) {\n if (!chat.fullInfo) {\n return undefined;\n }\n return chat.fullInfo.about;\n}\n\nexport function getChatLink(chat: ApiChat) {\n const { username } = chat;\n if (username) {\n return `https://t.me/${username}`;\n }\n\n const { inviteLink } = chat.fullInfo || {};\n\n return inviteLink;\n}\n\nexport function getChatAvatarHash(\n owner: ApiChat | ApiUser,\n size: 'normal' | 'big' = 'normal',\n) {\n if (!owner.avatarHash) {\n return undefined;\n }\n\n switch (size) {\n case 'big':\n return `profile${owner.id}?${owner.avatarHash}`;\n default:\n return `avatar${owner.id}?${owner.avatarHash}`;\n }\n}\n\nexport function isChatSummaryOnly(chat: ApiChat) {\n return !chat.lastMessage;\n}\n\nexport function isChatAdmin(chat: ApiChat) {\n return Boolean(chat.adminRights);\n}\n\nexport function getHasAdminRight(chat: ApiChat, key: keyof ApiChatAdminRights) {\n return chat.adminRights ? chat.adminRights[key] : false;\n}\n\nexport function isUserRightBanned(chat: ApiChat, key: keyof ApiChatBannedRights) {\n return Boolean(\n (chat.currentUserBannedRights && chat.currentUserBannedRights[key])\n || (chat.defaultBannedRights && chat.defaultBannedRights[key]),\n );\n}\n\nexport function getCanPostInChat(chat: ApiChat, threadId: number) {\n if (threadId !== MAIN_THREAD_ID) {\n return true;\n }\n\n if (chat.isRestricted || chat.migratedTo || chat.isNotJoined) {\n return false;\n }\n\n if (chat.isCreator) {\n return true;\n }\n\n if (isChatPrivate(chat.id)) {\n return true;\n }\n\n if (isChatChannel(chat)) {\n return getHasAdminRight(chat, 'postMessages');\n }\n\n return isChatAdmin(chat) || !isUserRightBanned(chat, 'sendMessages');\n}\n\nexport interface IAllowedAttachmentOptions {\n canAttachMedia: boolean;\n canAttachPolls: boolean;\n canSendStickers: boolean;\n canSendGifs: boolean;\n canAttachEmbedLinks: boolean;\n}\n\nexport function getAllowedAttachmentOptions(chat?: ApiChat, isChatWithBot = false): IAllowedAttachmentOptions {\n if (!chat) {\n return {\n canAttachMedia: false,\n canAttachPolls: false,\n canSendStickers: false,\n canSendGifs: false,\n canAttachEmbedLinks: false,\n };\n }\n\n const isAdmin = isChatAdmin(chat);\n\n return {\n canAttachMedia: isAdmin || !isUserRightBanned(chat, 'sendMedia'),\n canAttachPolls: (isAdmin || !isUserRightBanned(chat, 'sendPolls')) && (!isChatPrivate(chat.id) || isChatWithBot),\n canSendStickers: isAdmin || !isUserRightBanned(chat, 'sendStickers'),\n canSendGifs: isAdmin || !isUserRightBanned(chat, 'sendGifs'),\n canAttachEmbedLinks: isAdmin || !isUserRightBanned(chat, 'embedLinks'),\n };\n}\n\nexport function getMessageSendingRestrictionReason(\n lang: LangFn, currentUserBannedRights?: ApiChatBannedRights, defaultBannedRights?: ApiChatBannedRights,\n) {\n if (currentUserBannedRights && currentUserBannedRights.sendMessages) {\n const { untilDate } = currentUserBannedRights;\n return untilDate && untilDate < FOREVER_BANNED_DATE\n ? lang(\n 'Channel.Persmission.Denied.SendMessages.Until',\n lang(\n 'formatDateAtTime',\n [formatDateToString(new Date(untilDate * 1000), lang.code), formatTime(untilDate * 1000)],\n ),\n )\n : lang('Channel.Persmission.Denied.SendMessages.Forever');\n }\n\n if (defaultBannedRights && defaultBannedRights.sendMessages) {\n return lang('Channel.Persmission.Denied.SendMessages.DefaultRestrictedText');\n }\n\n return undefined;\n}\n\nexport function getChatSlowModeOptions(chat?: ApiChat) {\n if (!chat || !chat.fullInfo) {\n return undefined;\n }\n\n return chat.fullInfo.slowMode;\n}\n\n\nexport function getChatOrder(chat: ApiChat) {\n return Math.max(\n chat.joinDate || 0,\n chat.draftDate || 0,\n chat.lastMessage ? chat.lastMessage.date : 0,\n );\n}\n\nexport function isChatArchived(chat: ApiChat) {\n return chat.folderId === ARCHIVED_FOLDER_ID;\n}\n\nexport function selectIsChatMuted(\n chat: ApiChat, notifySettings: NotifySettings, notifyExceptions: Record<number, NotifyException> = [],\n) {\n // If this chat is in exceptions they take precedence\n if (notifyExceptions[chat.id] && notifyExceptions[chat.id].isMuted !== undefined) {\n return notifyExceptions[chat.id].isMuted;\n }\n\n return (\n chat.isMuted\n || (isChatPrivate(chat.id) && !notifySettings.hasPrivateChatsNotifications)\n || (isChatChannel(chat) && !notifySettings.hasBroadcastNotifications)\n || (isChatGroup(chat) && !notifySettings.hasGroupNotifications)\n );\n}\n\nexport function selectShouldShowMessagePreview(\n chat: ApiChat, notifySettings: NotifySettings, notifyExceptions: Record<number, NotifyException> = [],\n) {\n const {\n hasPrivateChatsMessagePreview = true,\n hasBroadcastMessagePreview = true,\n hasGroupMessagePreview = true,\n } = notifySettings;\n // If this chat is in exceptions they take precedence\n if (notifyExceptions[chat.id] && notifyExceptions[chat.id].shouldShowPreviews !== undefined) {\n return notifyExceptions[chat.id].shouldShowPreviews;\n }\n\n return (isChatPrivate(chat.id) && hasPrivateChatsMessagePreview)\n || (isChatChannel(chat) && hasBroadcastMessagePreview)\n || (isChatGroup(chat) && hasGroupMessagePreview);\n}\n\nexport function getCanDeleteChat(chat: ApiChat) {\n return isChatBasicGroup(chat) || ((isChatSuperGroup(chat) || isChatChannel(chat)) && chat.isCreator);\n}\n\nexport function prepareFolderListIds(\n chatsById: Record<number, ApiChat>,\n usersById: Record<number, ApiUser>,\n folder: ApiChatFolder,\n notifySettings: NotifySettings,\n notifyExceptions?: Record<number, NotifyException>,\n chatIdsCache?: number[],\n) {\n const excludedChatIds = folder.excludedChatIds ? new Set(folder.excludedChatIds) : undefined;\n const includedChatIds = folder.excludedChatIds ? new Set(folder.includedChatIds) : undefined;\n const pinnedChatIds = folder.excludedChatIds ? new Set(folder.pinnedChatIds) : undefined;\n const listIds = (chatIdsCache || Object.keys(chatsById).map(Number))\n .filter((id) => {\n return filterChatFolder(\n chatsById[id],\n folder,\n usersById,\n notifySettings,\n notifyExceptions,\n excludedChatIds,\n includedChatIds,\n pinnedChatIds,\n );\n });\n\n return [listIds, folder.pinnedChatIds] as const;\n}\n\nfunction filterChatFolder(\n chat: ApiChat,\n folder: ApiChatFolder,\n usersById: Record<number, ApiUser>,\n notifySettings: NotifySettings,\n notifyExceptions?: Record<number, NotifyException>,\n excludedChatIds?: Set<number>,\n includedChatIds?: Set<number>,\n pinnedChatIds?: Set<number>,\n) {\n if (!chat.isListed) {\n return false;\n }\n\n if (excludedChatIds && excludedChatIds.has(chat.id)) {\n return false;\n }\n\n if (includedChatIds && includedChatIds.has(chat.id)) {\n return true;\n }\n\n if (pinnedChatIds && pinnedChatIds.has(chat.id)) {\n return true;\n }\n\n if (isChatArchived(chat) && folder.excludeArchived) {\n return false;\n }\n\n if (folder.excludeMuted && !chat.unreadMentionsCount && selectIsChatMuted(chat, notifySettings, notifyExceptions)) {\n return false;\n }\n\n if (!chat.unreadCount && !chat.unreadMentionsCount && !chat.hasUnreadMark && folder.excludeRead) {\n return false;\n }\n\n if (isChatPrivate(chat.id)) {\n const privateChatUser = usersById[chat.id];\n\n const isChatWithBot = privateChatUser && privateChatUser.type === 'userTypeBot';\n if (isChatWithBot) {\n if (folder.bots) {\n return true;\n }\n } else {\n if (folder.contacts && privateChatUser && privateChatUser.isContact) {\n return true;\n }\n\n if (folder.nonContacts && privateChatUser && !privateChatUser.isContact) {\n return true;\n }\n }\n } else if (isChatGroup(chat)) {\n return !!folder.groups;\n } else if (isChatChannel(chat)) {\n return !!folder.channels;\n }\n\n return false;\n}\n\nexport function prepareChatList(\n chatsById: Record<number, ApiChat>,\n listIds: number[],\n orderedPinnedIds?: number[],\n folderType: 'all' | 'archived' | 'folder' = 'all',\n) {\n function chatFilter(chat?: ApiChat) {\n if (!chat || !chat.lastMessage || chat.migratedTo) {\n return false;\n }\n\n switch (folderType) {\n case 'all':\n if (isChatArchived(chat)) {\n return false;\n }\n break;\n case 'archived':\n if (!isChatArchived(chat)) {\n return false;\n }\n break;\n }\n\n return !chat.isRestricted && !chat.isNotJoined;\n }\n\n const listedChats = listIds\n .map((id) => chatsById[id])\n .filter(chatFilter);\n\n const listIdsSet = new Set(listIds);\n const pinnedChats = orderedPinnedIds\n ? (\n orderedPinnedIds\n .map((id) => chatsById[id])\n .filter(chatFilter)\n .filter((chat) => listIdsSet.has(chat.id))\n )\n : [];\n\n const otherChats = orderBy(\n orderedPinnedIds\n ? listedChats.filter((chat) => !orderedPinnedIds.includes(chat.id))\n : listedChats,\n getChatOrder,\n 'desc',\n );\n\n return {\n pinnedChats,\n otherChats,\n };\n}\n\nexport function getFolderUnreadDialogs(\n chatsById: Record<number, ApiChat>,\n usersById: Record<number, ApiUser>,\n folder: ApiChatFolder,\n chatIdsCache: number[],\n notifySettings: NotifySettings,\n notifyExceptions?: Record<number, NotifyException>,\n) {\n const [listIds] = prepareFolderListIds(chatsById, usersById, folder, notifySettings, notifyExceptions, chatIdsCache);\n\n const listedChats = listIds\n .map((id) => chatsById[id])\n .filter((chat) => (chat && chat.lastMessage && !chat.isRestricted && !chat.isNotJoined));\n\n const unreadDialogsCount = listedChats\n .reduce((total, chat) => (chat.unreadCount || chat.hasUnreadMark ? total + 1 : total), 0);\n\n const hasActiveDialogs = listedChats.some((chat) => (\n chat.unreadMentionsCount\n || (!selectIsChatMuted(chat, notifySettings, notifyExceptions) && (chat.unreadCount || chat.hasUnreadMark))\n ));\n\n return {\n unreadDialogsCount,\n hasActiveDialogs,\n };\n}\n\nexport function getFolderDescriptionText(\n lang: LangFn,\n chatsById: Record<number, ApiChat>,\n usersById: Record<number, ApiUser>,\n folder: ApiChatFolder,\n chatIdsCache: number[],\n notifySettings: NotifySettings,\n notifyExceptions?: Record<number, NotifyException>,\n) {\n const {\n id, title, emoticon, description, pinnedChatIds,\n excludedChatIds, includedChatIds,\n excludeArchived, excludeMuted, excludeRead,\n ...filters\n } = folder;\n\n // If folder has multiple additive filters or uses include/exclude lists,\n // we display folder chats count\n if (\n Object.values(filters).filter(Boolean).length > 1\n || (excludedChatIds && excludedChatIds.length)\n || (includedChatIds && includedChatIds.length)\n ) {\n const length = getFolderChatsCount(chatsById, usersById, folder, chatIdsCache, notifySettings, notifyExceptions);\n return lang('Chats', length);\n }\n\n // Otherwise, we return a short description of a single filter\n if (filters.bots) {\n return lang('FilterBots');\n } else if (filters.groups) {\n return lang('FilterGroups');\n } else if (filters.channels) {\n return lang('FilterChannels');\n } else if (filters.contacts) {\n return lang('FilterContacts');\n } else if (filters.nonContacts) {\n return lang('FilterNonContacts');\n } else {\n return undefined;\n }\n}\n\nfunction getFolderChatsCount(\n chatsById: Record<number, ApiChat>,\n usersById: Record<number, ApiUser>,\n folder: ApiChatFolder,\n chatIdsCache: number[],\n notifySettings: NotifySettings,\n notifyExceptions?: Record<number, NotifyException>,\n) {\n const [listIds, pinnedIds] = prepareFolderListIds(\n chatsById, usersById, folder, notifySettings, notifyExceptions, chatIdsCache,\n );\n const { pinnedChats, otherChats } = prepareChatList(chatsById, listIds, pinnedIds, 'folder');\n return pinnedChats.length + otherChats.length;\n}\n\nexport function isChat(chatOrUser?: ApiUser | ApiChat): chatOrUser is ApiChat {\n if (!chatOrUser) {\n return false;\n }\n\n return chatOrUser.id < 0;\n}\n\nexport function getMessageSenderName(lang: LangFn, chatId: number, sender?: ApiUser) {\n if (!sender || isChatPrivate(chatId)) {\n return undefined;\n }\n\n if (sender.isSelf) {\n return lang('FromYou');\n }\n\n return getUserFirstOrLastName(sender);\n}\n\nexport function sortChatIds(\n chatIds: number[],\n chatsById: Record<number, ApiChat>,\n shouldPrioritizeVerified = false,\n priorityIds?: number[],\n) {\n return orderBy(chatIds, (id) => {\n const chat = chatsById[id];\n if (!chat) {\n return 0;\n }\n\n let priority = 0;\n\n if (chat.lastMessage) {\n priority += chat.lastMessage.date;\n }\n\n if (shouldPrioritizeVerified && chat.isVerified) {\n priority += VERIFIED_PRIORITY_BASE; // ~100 years in seconds\n }\n\n if (priorityIds && priorityIds.includes(id)) {\n priority = Date.now() + PINNED_PRIORITY_BASE + (priorityIds.length - priorityIds.indexOf(id));\n }\n\n return priority;\n }, 'desc');\n}\n","import { useEffect } from '../lib/teact/teact';\n\nexport const ANIMATION_START_EVENT = 'tt-event-heavy-animation-start';\nexport const ANIMATION_END_EVENT = 'tt-event-heavy-animation-end';\n\nlet timeout: number | undefined;\nlet isAnimating = false;\n\nexport const dispatchHeavyAnimationEvent = (duration?: number) => {\n if (!isAnimating) {\n isAnimating = true;\n document.dispatchEvent(new Event(ANIMATION_START_EVENT));\n }\n\n if (timeout) {\n clearTimeout(timeout);\n timeout = undefined;\n }\n\n if (duration) {\n timeout = window.setTimeout(() => {\n isAnimating = false;\n document.dispatchEvent(new Event(ANIMATION_END_EVENT));\n timeout = undefined;\n }, duration);\n }\n\n return () => {\n isAnimating = false;\n document.dispatchEvent(new Event(ANIMATION_END_EVENT));\n };\n};\n\nexport default (\n handleAnimationStart: AnyToVoidFunction,\n handleAnimationEnd: AnyToVoidFunction,\n) => {\n useEffect(() => {\n if (isAnimating) {\n handleAnimationStart();\n }\n\n document.addEventListener(ANIMATION_START_EVENT, handleAnimationStart);\n document.addEventListener(ANIMATION_END_EVENT, handleAnimationEnd);\n\n return () => {\n document.removeEventListener(ANIMATION_END_EVENT, handleAnimationEnd);\n document.removeEventListener(ANIMATION_START_EVENT, handleAnimationStart);\n };\n }, [handleAnimationEnd, handleAnimationStart]);\n};\n","import { DEBUG } from '../../config';\n\ntype Handler = (e: Event) => void;\n\nconst NON_BUBBLEABLE_EVENTS = new Set(['scroll', 'mouseenter', 'mouseleave']);\n\nconst delegationRegistry: Record<string, Map<HTMLElement, Handler>> = {};\nconst delegatedEventsByElement = new Map<HTMLElement, Set<string>>();\nconst documentEventCounters: Record<string, number> = {};\n\nexport function addEventListener(element: HTMLElement, propName: string, handler: Handler, asCapture = false) {\n const eventName = resolveEventName(propName, element);\n if (canUseEventDelegation(eventName, element, asCapture)) {\n addDelegatedListener(eventName, element, handler);\n } else {\n element.addEventListener(eventName, handler, asCapture);\n }\n}\n\nexport function removeEventListener(element: HTMLElement, propName: string, handler: Handler, asCapture = false) {\n const eventName = resolveEventName(propName, element);\n if (canUseEventDelegation(eventName, element, asCapture)) {\n removeDelegatedListener(eventName, element);\n } else {\n element.removeEventListener(eventName, handler, asCapture);\n }\n}\n\nfunction resolveEventName(propName: string, element: HTMLElement) {\n const eventName = propName\n .replace(/^on/, '')\n .replace(/Capture$/, '').toLowerCase();\n\n if (eventName === 'change' && element.tagName !== 'SELECT') {\n // React behavior repeated here.\n // https://stackoverflow.com/questions/38256332/in-react-whats-the-difference-between-onchange-and-oninput\n return 'input';\n }\n\n if (eventName === 'doubleclick') {\n return 'dblclick';\n }\n\n // Replace focus/blur by their \"bubbleable\" versions\n if (eventName === 'focus') {\n return 'focusin';\n }\n\n if (eventName === 'blur') {\n return 'focusout';\n }\n\n return eventName;\n}\n\nfunction canUseEventDelegation(realEventName: string, element: HTMLElement, asCapture: boolean) {\n return (\n !asCapture\n && !NON_BUBBLEABLE_EVENTS.has(realEventName)\n && element.tagName !== 'VIDEO'\n && element.tagName !== 'IFRAME'\n );\n}\n\nfunction addDelegatedListener(eventName: string, element: HTMLElement, handler: Handler) {\n if (!documentEventCounters[eventName]) {\n documentEventCounters[eventName] = 0;\n document.addEventListener(eventName, handleEvent);\n }\n\n resolveDelegationRegistryForName(eventName).set(element, handler);\n resolveDelegatedEventsForElement(element).add(eventName);\n documentEventCounters[eventName]++;\n}\n\nfunction removeDelegatedListener(eventName: string, element: HTMLElement) {\n documentEventCounters[eventName]--;\n if (!documentEventCounters[eventName]) {\n // Synchronous deletion on 0 will cause perf degradation in the case of 1 element\n // which is not a real case, so it's ok to do it this way\n document.removeEventListener(eventName, handleEvent);\n }\n\n delegationRegistry[eventName].delete(element);\n delegatedEventsByElement.get(element)!.delete(eventName);\n}\n\nexport function removeAllDelegatedListeners(element: HTMLElement) {\n const eventNames = delegatedEventsByElement.get(element);\n if (!eventNames) {\n return;\n }\n\n eventNames.forEach((eventName) => removeDelegatedListener(eventName, element));\n delegatedEventsByElement.delete(element);\n}\n\nfunction handleEvent(realEvent: Event) {\n const events = delegationRegistry[realEvent.type];\n\n if (events) {\n let furtherCallsPrevented = false;\n let current: HTMLElement = realEvent.target as HTMLElement;\n\n const stopPropagation = () => {\n furtherCallsPrevented = true;\n };\n\n const preventDefault = () => {\n realEvent.preventDefault();\n };\n\n // Proxy is a simplest way to provide an access to the event property\n const event = new Proxy(realEvent, {\n get(target, p) {\n if (p === 'currentTarget') {\n return current;\n }\n if (p === 'stopPropagation' || p === 'stopImmediatePropagation') {\n return stopPropagation;\n }\n if (p === 'preventDefault') {\n // \"this\" is changed to proxy and one can't call methods via it\n return preventDefault;\n }\n return Reflect.get(target, p);\n },\n });\n\n // This can also be limited by teact root\n while (current && current !== document.body) {\n const handler = events.get(current);\n if (handler) {\n handler(event);\n if (furtherCallsPrevented) {\n return;\n }\n }\n\n current = current.parentNode as HTMLElement;\n }\n }\n}\n\nfunction resolveDelegationRegistryForName(eventName: string) {\n if (!delegationRegistry[eventName]) {\n delegationRegistry[eventName] = new Map();\n }\n\n return delegationRegistry[eventName];\n}\n\nfunction resolveDelegatedEventsForElement(element: HTMLElement) {\n const existing = delegatedEventsByElement.get(element);\n if (existing) {\n return existing;\n }\n\n const newSet = new Set<string>();\n delegatedEventsByElement.set(element, newSet);\n\n return newSet;\n}\n\nif (DEBUG) {\n document.addEventListener('dblclick', () => {\n // eslint-disable-next-line no-console\n console.log('DELEGATED EVENTS', { delegationRegistry, delegatedEventsByElement, documentEventCounters });\n });\n}\n","import { useCallback, useEffect, useRef } from '../lib/teact/teact';\n\nimport { IS_IOS } from '../util/environment';\nimport usePrevious from './usePrevious';\nimport { getDispatch } from '../lib/teact/teactn';\nimport { areSortedArraysEqual } from '../util/iteratees';\n\n// Carefully selected by swiping and observing visual changes\n// TODO: may be different on other devices such as iPad, maybe take dpi into account?\nconst SAFARI_EDGE_BACK_GESTURE_LIMIT = 300;\nconst SAFARI_EDGE_BACK_GESTURE_DURATION = 350;\nexport const LOCATION_HASH = window.location.hash;\n\ntype HistoryState = {\n currentIndex: number;\n nextStateIndexToReplace: number;\n isHistoryAltered: boolean;\n isDisabled: boolean;\n isEdge: boolean;\n currentIndexes: number[];\n};\n\nconst historyState: HistoryState = {\n currentIndex: 0,\n nextStateIndexToReplace: -1,\n isHistoryAltered: false,\n isDisabled: false,\n isEdge: false,\n currentIndexes: [],\n};\n\nexport const disableHistoryBack = () => {\n historyState.isDisabled = true;\n};\n\nconst handleTouchStart = (event: TouchEvent) => {\n const x = event.touches[0].pageX;\n\n if (x <= SAFARI_EDGE_BACK_GESTURE_LIMIT || x >= window.innerWidth - SAFARI_EDGE_BACK_GESTURE_LIMIT) {\n historyState.isEdge = true;\n }\n};\n\nconst handleTouchEnd = () => {\n if (historyState.isEdge) {\n setTimeout(() => {\n historyState.isEdge = false;\n }, SAFARI_EDGE_BACK_GESTURE_DURATION);\n }\n};\n\nif (IS_IOS) {\n window.addEventListener('touchstart', handleTouchStart);\n window.addEventListener('touchend', handleTouchEnd);\n window.addEventListener('popstate', handleTouchEnd);\n}\n\nwindow.history.replaceState({ index: historyState.currentIndex }, '', window.location.pathname);\n\nexport default function useHistoryBack(\n isActive: boolean | undefined,\n onBack: ((noDisableAnimation: boolean) => void) | undefined,\n onForward?: (state: any) => void,\n currentState?: any,\n shouldReplaceNext = false,\n hashes?: string[],\n) {\n const indexRef = useRef(-1);\n const isForward = useRef(false);\n const prevIsActive = usePrevious(isActive);\n const isClosed = useRef(true);\n const indexHashRef = useRef<{ index: number; hash: string }[]>([]);\n const prevHashes = usePrevious(hashes);\n const isHashChangedFromEvent = useRef<boolean>(false);\n\n const handleChange = useCallback((isForceClose = false) => {\n if (!hashes) {\n if (isActive && !isForceClose) {\n isClosed.current = false;\n\n if (isForward.current) {\n isForward.current = false;\n historyState.currentIndexes.push(indexRef.current);\n } else {\n setTimeout(() => {\n const index = ++historyState.currentIndex;\n\n historyState.currentIndexes.push(index);\n\n window.history[\n (historyState.currentIndexes.includes(historyState.nextStateIndexToReplace - 1)\n && window.history.state.index !== 0\n && historyState.nextStateIndexToReplace === index\n && !shouldReplaceNext)\n ? 'replaceState'\n : 'pushState'\n ]({\n index,\n state: currentState,\n }, '');\n\n\n indexRef.current = index;\n\n if (shouldReplaceNext) {\n historyState.nextStateIndexToReplace = historyState.currentIndex + 1;\n }\n }, 0);\n }\n }\n\n if ((isForceClose || !isActive) && !isClosed.current) {\n if ((indexRef.current === historyState.currentIndex || !shouldReplaceNext)) {\n historyState.isHistoryAltered = true;\n window.history.back();\n\n setTimeout(() => {\n historyState.nextStateIndexToReplace = -1;\n }, 400);\n }\n historyState.currentIndexes.splice(historyState.currentIndexes.indexOf(indexRef.current), 1);\n\n isClosed.current = true;\n }\n } else {\n const prev = prevHashes || [];\n if (prev.length < hashes.length) {\n const index = ++historyState.currentIndex;\n historyState.currentIndexes.push(index);\n\n window.history.pushState({\n index,\n state: currentState,\n }, '', `#${hashes[hashes.length - 1]}`);\n\n indexHashRef.current.push({\n index,\n hash: hashes[hashes.length - 1],\n });\n } else {\n const delta = prev.length - hashes.length;\n if (isHashChangedFromEvent.current) {\n isHashChangedFromEvent.current = false;\n } else {\n if (hashes.length !== indexHashRef.current.length) {\n if (delta > 0) {\n const last = indexHashRef.current[indexHashRef.current.length - delta - 1];\n let realDelta = delta;\n if (last) {\n const indexLast = historyState.currentIndexes.findIndex(\n (l) => l === last.index,\n );\n realDelta = historyState.currentIndexes.length - indexLast - 1;\n }\n historyState.isHistoryAltered = true;\n window.history.go(-realDelta);\n const removed = indexHashRef.current.splice(indexHashRef.current.length - delta - 1, delta);\n removed.forEach(({ index }) => {\n historyState.currentIndexes.splice(historyState.currentIndexes.indexOf(index), 1);\n });\n }\n }\n\n if (hashes.length > 0) {\n setTimeout(() => {\n const index = ++historyState.currentIndex;\n historyState.currentIndexes[historyState.currentIndexes.length - 1] = index;\n\n window.history.replaceState({\n index,\n state: currentState,\n }, '', `#${hashes[hashes.length - 1]}`);\n\n indexHashRef.current[indexHashRef.current.length - 1] = {\n index,\n hash: hashes[hashes.length - 1],\n };\n }, 0);\n }\n }\n }\n }\n }, [currentState, hashes, isActive, prevHashes, shouldReplaceNext]);\n\n useEffect(() => {\n const handlePopState = (event: PopStateEvent) => {\n if (historyState.isHistoryAltered) {\n setTimeout(() => {\n historyState.isHistoryAltered = false;\n }, 0);\n return;\n }\n const { index: i } = event.state;\n const index = i || 0;\n try {\n const currIndex = hashes ? indexHashRef.current[indexHashRef.current.length - 1].index : indexRef.current;\n\n const prev = historyState.currentIndexes[historyState.currentIndexes.indexOf(currIndex) - 1];\n\n if (historyState.isDisabled) return;\n\n if ((!isClosed.current && (index === 0 || index === prev)) || (hashes && (index === 0 || index === prev))) {\n if (hashes) {\n isHashChangedFromEvent.current = true;\n indexHashRef.current.pop();\n }\n\n historyState.currentIndexes.splice(historyState.currentIndexes.indexOf(currIndex), 1);\n\n if (onBack) {\n if (historyState.isEdge) {\n getDispatch()\n .disableHistoryAnimations();\n }\n onBack(!historyState.isEdge);\n isClosed.current = true;\n }\n } else if (index === currIndex && isClosed.current && onForward && !hashes) {\n isForward.current = true;\n if (historyState.isEdge) {\n getDispatch()\n .disableHistoryAnimations();\n }\n onForward(event.state.state);\n }\n } catch (e) {\n // Forward navigation for hashed is not supported\n }\n };\n\n const hasChanged = hashes\n ? (!prevHashes || !areSortedArraysEqual(prevHashes, hashes))\n : prevIsActive !== isActive;\n\n if (!historyState.isDisabled && hasChanged) {\n handleChange();\n }\n\n window.addEventListener('popstate', handlePopState);\n return () => window.removeEventListener('popstate', handlePopState);\n }, [\n currentState, handleChange, hashes, isActive, onBack, onForward, prevHashes, prevIsActive, shouldReplaceNext,\n ]);\n\n return {\n forceClose: () => handleChange(true),\n };\n}\n","import { useRef, useState } from '../lib/teact/teact';\nimport buildClassName from '../util/buildClassName';\n\nconst CLOSE_DURATION = 350;\n\nexport default (\n isOpen = false,\n onCloseTransitionEnd?: () => void,\n noOpenTransition = false,\n className: string | false = 'fast',\n noCloseTransition = false,\n) => {\n const [isClosed, setIsClosed] = useState(!isOpen);\n const closeTimeoutRef = useRef<number>();\n // СSS class should be added in a separate tick to turn on CSS transition.\n const [hasOpenClassName, setHasOpenClassName] = useState(isOpen && noOpenTransition);\n\n\n if (isOpen) {\n setIsClosed(false);\n setHasOpenClassName(true);\n\n if (closeTimeoutRef.current) {\n window.clearTimeout(closeTimeoutRef.current);\n closeTimeoutRef.current = undefined;\n }\n } else {\n setHasOpenClassName(false);\n\n if (!isClosed && !closeTimeoutRef.current) {\n closeTimeoutRef.current = window.setTimeout(() => {\n setIsClosed(true);\n\n if (onCloseTransitionEnd) {\n onCloseTransitionEnd();\n }\n\n closeTimeoutRef.current = undefined;\n }, noCloseTransition ? 0 : CLOSE_DURATION);\n }\n }\n\n // `noCloseTransition`, when set to true, should remove the open class immediately\n const shouldHaveOpenClassName = hasOpenClassName && !(noCloseTransition && !isOpen);\n const isClosing = Boolean(closeTimeoutRef.current);\n const shouldRender = isOpen || isClosing;\n const transitionClassNames = buildClassName(\n className && 'opacity-transition',\n className,\n shouldHaveOpenClassName && 'open',\n shouldRender && 'shown',\n isClosing && 'closing',\n );\n\n return {\n shouldRender,\n transitionClassNames,\n };\n};\n","const DEFAULT_MAX_TEXT_LENGTH = 30;\n\nexport default function trimText(text: string | undefined, length = DEFAULT_MAX_TEXT_LENGTH) {\n if (!text || text.length <= length) {\n return text;\n }\n\n return `${text.substr(0, length)}...`;\n}\n","import React, { FC, useCallback } from '../../lib/teact/teact';\n\nimport buildClassName from '../../util/buildClassName';\nimport useLang from '../../hooks/useLang';\n\nimport './MenuItem.scss';\n\ntype OnClickHandler = (e: React.SyntheticEvent<HTMLDivElement | HTMLAnchorElement>) => void;\n\ntype OwnProps = {\n icon?: string;\n className?: string;\n children: any;\n onClick?: OnClickHandler;\n href?: string;\n download?: string;\n disabled?: boolean;\n destructive?: boolean;\n ariaLabel?: string;\n};\n\nconst MenuItem: FC<OwnProps> = (props) => {\n const {\n icon,\n className,\n children,\n onClick,\n href,\n download,\n disabled,\n destructive,\n ariaLabel,\n } = props;\n\n const lang = useLang();\n const handleClick = useCallback((e: React.MouseEvent<HTMLDivElement>) => {\n if (disabled || !onClick) {\n e.stopPropagation();\n e.preventDefault();\n\n return;\n }\n\n onClick(e);\n }, [disabled, onClick]);\n\n const handleKeyDown = useCallback((e: React.KeyboardEvent<HTMLDivElement>) => {\n if (e.keyCode !== 13 && e.keyCode !== 32) {\n return;\n }\n\n if (disabled || !onClick) {\n e.stopPropagation();\n e.preventDefault();\n\n return;\n }\n\n onClick(e);\n }, [disabled, onClick]);\n\n const fullClassName = buildClassName(\n 'MenuItem',\n className,\n disabled && 'disabled',\n destructive && 'destructive',\n );\n\n const content = (\n <>\n {icon && (\n <i className={`icon-${icon}`} data-char={icon.startsWith('char-') ? icon.replace('char-', '') : undefined} />\n )}\n {children}\n </>\n );\n\n if (href) {\n return (\n <a\n tabIndex={0}\n className={fullClassName}\n href={href}\n download={download}\n aria-label={ariaLabel}\n title={ariaLabel}\n target={href.startsWith(window.location.origin) ? '_self' : '_blank'}\n rel=\"noopener noreferrer\"\n dir={lang.isRtl ? 'rtl' : undefined}\n onClick={onClick}\n >\n {content}\n </a>\n );\n }\n\n return (\n <div\n role=\"button\"\n tabIndex={0}\n className={fullClassName}\n onClick={handleClick}\n onKeyDown={handleKeyDown}\n aria-label={ariaLabel}\n title={ariaLabel}\n dir={lang.isRtl ? 'rtl' : undefined}\n >\n {content}\n </div>\n );\n};\n\nexport default MenuItem;\n","import React, {\n FC, useCallback, useMemo, useState, memo,\n} from '../../lib/teact/teact';\nimport { debounce } from '../../util/schedulers';\n\nimport './RippleEffect.scss';\n\ninterface Ripple {\n x: number;\n y: number;\n size: number;\n}\n\nconst ANIMATION_DURATION_MS = 700;\n\nconst RippleEffect: FC = () => {\n const [ripples, setRipples] = useState<Ripple[]>([]);\n\n const cleanUpDebounced = useMemo(() => {\n return debounce(() => {\n setRipples([]);\n }, ANIMATION_DURATION_MS, false);\n }, []);\n\n const handleMouseDown = useCallback((e: React.MouseEvent<HTMLDivElement, MouseEvent>) => {\n if (e.button !== 0) {\n return;\n }\n\n const container = e.currentTarget as HTMLDivElement;\n const position = container.getBoundingClientRect() as DOMRect;\n\n const rippleSize = container.offsetWidth / 2;\n\n setRipples([\n ...ripples,\n {\n x: e.clientX - position.x - (rippleSize / 2),\n y: e.clientY - position.y - (rippleSize / 2),\n size: rippleSize,\n },\n ]);\n\n requestAnimationFrame(() => {\n cleanUpDebounced();\n });\n }, [ripples, cleanUpDebounced]);\n\n return (\n <div className=\"ripple-container\" onMouseDown={handleMouseDown}>\n {ripples.map(({ x, y, size }: Ripple) => (\n <span\n // @ts-ignore\n style={`left: ${x}px; top: ${y}px; width: ${size}px; height: ${size}px;`}\n />\n ))}\n </div>\n );\n};\n\nexport default memo(RippleEffect);\n","import WebpWorker from 'worker-loader!../lib/webp/webp_wasm.worker';\nimport { isWebpSupported } from './environment';\nimport { dataUriToBlob, blobToDataUri } from './files';\nimport { pause } from './schedulers';\n\ntype TEncodedImage = {\n result: Uint8ClampedArray;\n width: number;\n height: number;\n};\n\nconst WORKER_INITIALIZATION_TIMEOUT = 2000;\n\nlet canvas: HTMLCanvasElement;\nlet worker: IWebpWorker;\n\nexport const EMPTY_IMAGE_DATA_URI = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk'\n + 'YAAAAAYAAjCB0C8AAAAASUVORK5CYII=';\n\nexport async function webpToPng(url: string, blob: Blob): Promise<Blob | undefined> {\n initWebpWorker();\n\n while (!worker.wasmReady) {\n await pause(WORKER_INITIALIZATION_TIMEOUT);\n }\n\n const { result, width, height } = await getDecodePromise(url, blob);\n if (!width || !height) {\n return undefined;\n }\n\n return createPng({ result, width, height });\n}\n\nexport async function webpToPngBase64(key: string, url: string): Promise<string> {\n if (isWebpSupported() || url.substr(0, 15) !== 'data:image/webp') {\n return url;\n }\n\n initWebpWorker();\n\n const pngBlob = await webpToPng(key, dataUriToBlob(url));\n\n if (!pngBlob) {\n throw new Error(`Can't convert webp to png. Url: ${url}`);\n }\n\n return blobToDataUri(pngBlob);\n}\n\nfunction initWebpWorker() {\n if (!worker) {\n worker = new WebpWorker() as IWebpWorker;\n worker.wasmReady = false;\n worker.onmessage = handleLibWebpMessage;\n }\n}\n\nfunction createPng({ result, width, height }: TEncodedImage): Promise<Blob | undefined> {\n if (!canvas) {\n canvas = document.createElement('canvas');\n }\n\n return new Promise((resolve) => {\n const img = new ImageData(result, width, height);\n\n canvas.width = width;\n canvas.height = height;\n const ctx = canvas.getContext('2d')!;\n ctx.putImageData(img, 0, 0);\n\n canvas.toBlob((blob) => {\n resolve(blob ?? undefined);\n }, 'image/png', 1);\n });\n}\n\nfunction handleLibWebpMessage(e: MessageEvent) {\n const { id } = e.data;\n switch (e.data.type) {\n case 'initialized': {\n worker.wasmReady = true;\n break;\n }\n\n case 'result': {\n if (worker.requests.has(id)) {\n const resolve = worker.requests.get(id)!;\n\n worker.requests.delete(id);\n resolve(e.data!);\n }\n break;\n }\n }\n}\n\nfunction getDecodePromise(url: string, blob: Blob): Promise<TEncodedImage> {\n return new Promise((resolve) => {\n worker.requests = worker.requests || new Map();\n worker.requests.set(url, resolve);\n worker.postMessage({ id: url, blob });\n });\n}\n","import { ISettings } from '../types';\n\nimport { animateSingle } from './animation';\n\nimport themeColors from '../styles/themes.json';\n\ntype RGBAColor = {\n r: number;\n g: number;\n b: number;\n a?: number;\n};\n\nlet isInitialized = false;\n\nconst HEX_COLOR_REGEX = /^#?([a-f\\d]{2})([a-f\\d]{2})([a-f\\d]{2})([a-f\\d]{2})?$/i;\nconst DURATION_MS = 200;\nconst ENABLE_ANIMATION_DELAY_MS = 500;\n\nconst lerp = (start: number, end: number, interpolationRatio: number) => {\n return (1 - interpolationRatio) * start + interpolationRatio * end;\n};\n\nconst colors = (Object.keys(themeColors) as Array<keyof typeof themeColors>).map((property) => ({\n property,\n colors: [hexToRgb(themeColors[property][0]), hexToRgb(themeColors[property][1])],\n}));\n\nexport default (theme: ISettings['theme'], withAnimation: boolean) => {\n const isDarkTheme = theme === 'dark';\n const shouldAnimate = isInitialized && withAnimation;\n const startIndex = isDarkTheme ? 0 : 1;\n const endIndex = isDarkTheme ? 1 : 0;\n const startAt = Date.now();\n const themeColorTag = document.querySelector('meta[name=\"theme-color\"]');\n\n document.documentElement.classList.remove(`theme-${isDarkTheme ? 'light' : 'dark'}`);\n if (isInitialized) {\n document.documentElement.classList.add('no-animations');\n }\n document.documentElement.classList.add(`theme-${theme}`);\n if (themeColorTag) {\n themeColorTag.setAttribute('content', isDarkTheme ? '#212121' : '#fff');\n }\n\n setTimeout(() => {\n document.documentElement.classList.remove('no-animations');\n }, ENABLE_ANIMATION_DELAY_MS);\n\n isInitialized = true;\n\n if (shouldAnimate) {\n animateSingle(() => {\n const t = Math.min((Date.now() - startAt) / DURATION_MS, 1);\n\n applyColorAnimationStep(startIndex, endIndex, transition(t));\n\n return t < 1;\n });\n } else {\n applyColorAnimationStep(startIndex, endIndex);\n }\n};\n\nfunction transition(t: number) {\n return 1 - ((1 - t) ** 3.5);\n}\n\nfunction hexToRgb(hex: string): RGBAColor {\n const result = HEX_COLOR_REGEX.exec(hex)!;\n\n return {\n r: parseInt(result[1], 16),\n g: parseInt(result[2], 16),\n b: parseInt(result[3], 16),\n a: result[4] !== undefined ? parseInt(result[4], 16) : undefined,\n };\n}\n\nfunction applyColorAnimationStep(startIndex: number, endIndex: number, interpolationRatio: number = 1) {\n colors.forEach(({ property, colors: propertyColors }) => {\n const r = Math.round(lerp(propertyColors[startIndex].r, propertyColors[endIndex].r, interpolationRatio));\n const g = Math.round(lerp(propertyColors[startIndex].g, propertyColors[endIndex].g, interpolationRatio));\n const b = Math.round(lerp(propertyColors[startIndex].b, propertyColors[endIndex].b, interpolationRatio));\n const a = propertyColors[startIndex].a !== undefined\n ? Math.round(lerp(propertyColors[startIndex].a!, propertyColors[endIndex].a!, interpolationRatio))\n : undefined;\n\n document.documentElement.style.setProperty(property, a !== undefined\n ? `rgba(${r},${g},${b},${a / 255})`\n : `rgb(${r},${g},${b})`);\n });\n}\n","import { ChangeEvent, FormEvent, RefObject } from 'react';\nimport React, { FC, memo } from '../../lib/teact/teact';\n\nimport buildClassName from '../../util/buildClassName';\nimport useLang from '../../hooks/useLang';\n\ntype OwnProps = {\n ref?: RefObject<HTMLInputElement>;\n id?: string;\n className?: string;\n value?: string;\n label?: string;\n error?: string;\n success?: string;\n disabled?: boolean;\n readOnly?: boolean;\n placeholder?: string;\n autoComplete?: string;\n maxLength?: number;\n inputMode?: 'text' | 'none' | 'tel' | 'url' | 'email' | 'numeric' | 'decimal' | 'search';\n onChange?: (e: ChangeEvent<HTMLInputElement>) => void;\n onInput?: (e: FormEvent<HTMLInputElement>) => void;\n onKeyPress?: (e: React.KeyboardEvent<HTMLInputElement>) => void;\n onKeyDown?: (e: React.KeyboardEvent<HTMLInputElement>) => void;\n onBlur?: (e: React.FocusEvent<HTMLInputElement>) => void;\n onPaste?: (e: React.ClipboardEvent<HTMLInputElement>) => void;\n};\n\nconst InputText: FC<OwnProps> = ({\n ref,\n id,\n className,\n value,\n label,\n error,\n success,\n disabled,\n readOnly,\n placeholder,\n autoComplete,\n inputMode,\n maxLength,\n onChange,\n onInput,\n onKeyPress,\n onKeyDown,\n onBlur,\n onPaste,\n}) => {\n const lang = useLang();\n const labelText = error || success || label;\n const fullClassName = buildClassName(\n 'input-group',\n value && 'touched',\n error ? 'error' : success && 'success',\n disabled && 'disabled',\n readOnly && 'disabled',\n labelText && 'with-label',\n className,\n );\n\n return (\n <div className={fullClassName} dir={lang.isRtl ? 'rtl' : undefined}>\n <input\n ref={ref}\n className=\"form-control\"\n type=\"text\"\n id={id}\n dir=\"auto\"\n value={value || ''}\n placeholder={placeholder}\n maxLength={maxLength}\n autoComplete={autoComplete}\n inputMode={inputMode}\n disabled={disabled}\n readOnly={readOnly}\n onChange={onChange}\n onInput={onInput}\n onKeyPress={onKeyPress}\n onKeyDown={onKeyDown}\n onBlur={onBlur}\n onPaste={onPaste}\n />\n {labelText && (\n <label htmlFor={id}>{labelText}</label>\n )}\n </div>\n );\n};\n\nexport default memo(InputText);\n","import { ChangeEvent } from 'react';\nimport React, { FC, memo, useCallback } from '../../lib/teact/teact';\n\nimport buildClassName from '../../util/buildClassName';\nimport useLang from '../../hooks/useLang';\n\nimport Spinner from './Spinner';\n\nimport './Checkbox.scss';\n\ntype OwnProps = {\n id?: string;\n name?: string;\n value?: string;\n label: string;\n subLabel?: string;\n checked: boolean;\n disabled?: boolean;\n round?: boolean;\n blocking?: boolean;\n isLoading?: boolean;\n withCheckedCallback?: boolean;\n onChange?: (e: ChangeEvent<HTMLInputElement>) => void;\n onCheck?: (isChecked: boolean) => void;\n};\n\nconst Checkbox: FC<OwnProps> = ({\n id,\n name,\n value,\n label,\n subLabel,\n checked,\n disabled,\n round,\n blocking,\n isLoading,\n onChange,\n onCheck,\n}) => {\n const lang = useLang();\n const handleChange = useCallback((event: ChangeEvent<HTMLInputElement>) => {\n if (onChange) {\n onChange(event);\n }\n\n if (onCheck) {\n onCheck(event.currentTarget.checked);\n }\n }, [onChange, onCheck]);\n\n const className = buildClassName(\n 'Checkbox',\n disabled && 'disabled',\n round && 'round',\n isLoading && 'loading',\n blocking && 'blocking',\n );\n\n return (\n <label className={className} dir={lang.isRtl ? 'rtl' : undefined}>\n <input\n type=\"checkbox\"\n id={id}\n name={name}\n value={value}\n checked={checked}\n disabled={disabled}\n onChange={handleChange}\n />\n <div className=\"Checkbox-main\">\n <span className=\"label\" dir=\"auto\">{label}</span>\n {subLabel && <span className=\"subLabel\" dir=\"auto\">{subLabel}</span>}\n </div>\n {isLoading && <Spinner />}\n </label>\n );\n};\n\nexport default memo(Checkbox);\n","import captureKeyboardListener from './captureKeyboardListeners';\n\ntype IHandlerFunction = () => void;\n\nexport default function captureEscKeyListener(handler: IHandlerFunction) {\n return captureKeyboardListener({ onEsc: handler });\n}\n","export function formatInteger(value: number) {\n return String(value).replace(/\\d(?=(\\d{3})+$)/g, '$& ');\n}\n\nfunction formatFixedNumber(number: number) {\n const fixed = String(number.toFixed(1));\n if (fixed.substr(-2) === '.0') {\n return Math.round(number);\n }\n\n return number.toFixed(1).replace('.', ',');\n}\n\nexport function formatIntegerCompact(views: number) {\n if (views < 1e3) {\n return views;\n }\n\n if (views < 1e6) {\n return `${formatFixedNumber(views / 1e3)}K`;\n }\n\n return `${formatFixedNumber(views / 1e6)}M`;\n}\n\nexport function getFirstLetters(phrase: string, count = 2) {\n return phrase\n .replace(/[.,!@#$%^&*()_+=\\-`~[\\]/\\\\{}:\"|<>?]+/gi, '')\n .trim()\n .split(/\\s+/)\n .slice(0, count)\n .map((word: string) => word.length && word.match(/./u)![0].toUpperCase())\n .join('');\n}\n","export const MEMO_EMPTY_ARRAY = [];\n","import usePrevious from './usePrevious';\n\nexport default <T extends any[], PT = T>(cb: (args: PT) => void, dependencies: T) => {\n const prevDeps = usePrevious<T>(dependencies);\n if (!prevDeps || dependencies.some((d, i) => d !== prevDeps[i])) {\n // @ts-ignore (workaround for \"could be instantiated with a different subtype\" issue)\n cb(prevDeps || []);\n }\n};\n","let RE_NOT_LETTER: RegExp;\n\ntry {\n RE_NOT_LETTER = new RegExp('[^\\\\p{L}\\\\p{M}]+', 'ui');\n} catch (e) {\n // Support for older versions of firefox\n RE_NOT_LETTER = new RegExp('[^\\\\wа-яё]+', 'i');\n}\n\nexport default function searchWords(haystack: string, needle: string) {\n if (!haystack || !needle) {\n return false;\n }\n\n const haystackWords = haystack.toLowerCase().split(RE_NOT_LETTER);\n const needleWords = needle.toLowerCase().split(RE_NOT_LETTER);\n\n return needleWords.every((needleWord) => (\n haystackWords.some((haystackWord) => haystackWord.startsWith(needleWord))\n ));\n}\n","import { throttle } from './schedulers';\nimport {\n MOBILE_SCREEN_LANDSCAPE_MAX_HEIGHT,\n MOBILE_SCREEN_LANDSCAPE_MAX_WIDTH,\n MOBILE_SCREEN_MAX_WIDTH,\n} from '../config';\nimport { IS_IOS, IS_SINGLE_COLUMN_LAYOUT } from './environment';\n\ntype IDimensions = {\n width: number;\n height: number;\n};\n\nconst IS_LANDSCAPE = IS_SINGLE_COLUMN_LAYOUT && isLandscape();\n\nconst initialHeight = window.innerHeight;\nlet windowSize = updateSizes();\nlet isRefreshDisabled = false;\n\nfunction disableRefresh() {\n isRefreshDisabled = true;\n}\n\nfunction enableRefresh() {\n isRefreshDisabled = false;\n}\n\nconst handleResize = throttle(() => {\n windowSize = updateSizes();\n\n if (!isRefreshDisabled && (\n isMobileScreen() !== IS_SINGLE_COLUMN_LAYOUT\n || (IS_SINGLE_COLUMN_LAYOUT && IS_LANDSCAPE !== isLandscape())\n )) {\n window.location.reload();\n }\n}, 250, true);\n\nwindow.addEventListener('resize', handleResize);\nwindow.addEventListener('orientationchange', handleResize);\n\nexport function updateSizes(): IDimensions {\n const vh = window.innerHeight * 0.01;\n\n document.documentElement.style.setProperty('--vh', `${vh}px`);\n\n return {\n width: window.innerWidth,\n height: window.innerHeight,\n };\n}\n\nfunction isMobileScreen() {\n return windowSize.width <= MOBILE_SCREEN_MAX_WIDTH || (\n windowSize.width <= MOBILE_SCREEN_LANDSCAPE_MAX_WIDTH && windowSize.height <= MOBILE_SCREEN_LANDSCAPE_MAX_HEIGHT\n );\n}\n\nfunction isLandscape() {\n if (IS_IOS) {\n return window.matchMedia('(orientation: landscape)').matches;\n }\n\n // eslint-disable-next-line max-len\n // Source: https://web.archive.org/web/20160509220835/http://blog.abouthalf.com/development/orientation-media-query-challenges-in-android-browsers/\n // Feature is marked as deprecated now, but it is still supported\n // https://developer.mozilla.org/en-US/docs/Web/CSS/@media/device-aspect-ratio#browser_compatibility\n return window.matchMedia('screen and (min-device-aspect-ratio: 1/1) and (orientation: landscape)').matches;\n}\n\nexport default {\n get: () => windowSize,\n getIsKeyboardVisible: () => initialHeight > windowSize.height,\n disableRefresh,\n enableRefresh,\n};\n","import { RefObject } from 'react';\nimport React, { FC, useEffect, useRef } from '../../lib/teact/teact';\n\nimport useShowTransition from '../../hooks/useShowTransition';\nimport useKeyboardListNavigation from '../../hooks/useKeyboardListNavigation';\nimport useVirtualBackdrop from '../../hooks/useVirtualBackdrop';\nimport useEffectWithPrevDeps from '../../hooks/useEffectWithPrevDeps';\nimport captureEscKeyListener from '../../util/captureEscKeyListener';\nimport buildClassName from '../../util/buildClassName';\nimport { dispatchHeavyAnimationEvent } from '../../hooks/useHeavyAnimationCheck';\nimport useHistoryBack from '../../hooks/useHistoryBack';\n\nimport './Menu.scss';\n\ntype OwnProps = {\n ref?: RefObject<HTMLDivElement>;\n containerRef?: RefObject<HTMLElement>;\n isOpen: boolean;\n className?: string;\n style?: string;\n positionX?: 'left' | 'right';\n positionY?: 'top' | 'bottom';\n autoClose?: boolean;\n shouldSkipTransition?: boolean;\n footer?: string;\n noCloseOnBackdrop?: boolean;\n onKeyDown?: (e: React.KeyboardEvent<any>) => void;\n onCloseAnimationEnd?: () => void;\n onClose?: () => void;\n onMouseEnter?: (e: React.MouseEvent<HTMLDivElement, MouseEvent>) => void;\n onMouseLeave?: (e: React.MouseEvent<HTMLDivElement, MouseEvent>) => void;\n children: any;\n};\n\nconst ANIMATION_DURATION = 200;\n\nconst Menu: FC<OwnProps> = ({\n ref,\n containerRef,\n isOpen,\n className,\n style,\n children,\n positionX = 'left',\n positionY = 'top',\n autoClose = false,\n footer,\n noCloseOnBackdrop = false,\n onCloseAnimationEnd,\n onClose,\n onMouseEnter,\n onMouseLeave,\n shouldSkipTransition,\n}) => {\n // eslint-disable-next-line no-null/no-null\n let menuRef = useRef<HTMLDivElement>(null);\n if (ref) {\n menuRef = ref;\n }\n const backdropContainerRef = containerRef || menuRef;\n\n const {\n transitionClassNames,\n } = useShowTransition(\n isOpen,\n onCloseAnimationEnd,\n shouldSkipTransition,\n undefined,\n shouldSkipTransition,\n );\n\n useEffect(\n () => (isOpen && onClose ? captureEscKeyListener(onClose) : undefined),\n [isOpen, onClose],\n );\n\n useHistoryBack(isOpen, onClose, undefined, undefined, autoClose);\n\n useEffectWithPrevDeps(([prevIsOpen]) => {\n if (prevIsOpen !== undefined) {\n dispatchHeavyAnimationEvent(ANIMATION_DURATION);\n }\n }, [isOpen]);\n\n const handleKeyDown = useKeyboardListNavigation(menuRef, isOpen, autoClose ? onClose : undefined, undefined, true);\n\n useVirtualBackdrop(\n isOpen,\n backdropContainerRef,\n noCloseOnBackdrop ? undefined : onClose,\n );\n\n const bubbleClassName = buildClassName(\n 'bubble menu-container custom-scroll',\n positionY,\n positionX,\n footer && 'with-footer',\n transitionClassNames,\n );\n\n return (\n <div\n className={buildClassName('Menu no-selection', className)}\n onKeyDown={isOpen ? handleKeyDown : undefined}\n onMouseEnter={onMouseEnter}\n onMouseLeave={isOpen ? onMouseLeave : undefined}\n // @ts-ignore teact feature\n style={style}\n >\n {isOpen && (\n // This only prevents click events triggering on underlying elements\n <div className=\"backdrop\" />\n )}\n <div\n ref={menuRef}\n className={bubbleClassName}\n // @ts-ignore teact feature\n style={`transform-origin: ${positionY} ${positionX}`}\n onClick={autoClose ? onClose : undefined}\n >\n {children}\n {footer && <div className=\"footer\">{footer}</div>}\n </div>\n </div>\n );\n};\n\nexport default Menu;\n","type HandlerName = 'onEnter' | 'onBackspace' | 'onDelete' | 'onEsc' | 'onUp' | 'onDown' | 'onLeft' | 'onRight'\n| 'onTab';\ntype Handler = (e: KeyboardEvent) => void;\ntype CaptureOptions = Partial<Record<HandlerName, Handler>>;\n\nconst keyToHandlerName: Record<string, HandlerName> = {\n Enter: 'onEnter',\n Backspace: 'onBackspace',\n Delete: 'onDelete',\n Esc: 'onEsc',\n Escape: 'onEsc',\n ArrowUp: 'onUp',\n ArrowDown: 'onDown',\n ArrowLeft: 'onLeft',\n ArrowRight: 'onRight',\n Tab: 'onTab',\n};\n\nconst handlers: Record<HandlerName, Handler[]> = {\n onEnter: [],\n onDelete: [],\n onBackspace: [],\n onEsc: [],\n onUp: [],\n onDown: [],\n onLeft: [],\n onRight: [],\n onTab: [],\n};\n\nexport default function captureKeyboardListeners(options: CaptureOptions) {\n if (!hasActiveHandlers()) {\n document.addEventListener('keydown', handleKeyDown, true);\n }\n\n (Object.keys(options) as Array<HandlerName>).forEach((handlerName) => {\n const handler = options[handlerName];\n if (!handler) {\n return;\n }\n\n const currentEventHandlers = handlers[handlerName];\n if (currentEventHandlers) {\n currentEventHandlers.push(handler);\n }\n });\n\n return () => {\n releaseKeyboardListener(options);\n };\n}\n\nfunction hasActiveHandlers() {\n return Object.values(handlers).some((keyHandlers) => Boolean(keyHandlers.length));\n}\n\nfunction handleKeyDown(e: KeyboardEvent) {\n const handlerName = keyToHandlerName[e.key];\n if (!handlerName) {\n return;\n }\n\n const { length } = handlers[handlerName];\n if (!length) {\n return;\n }\n e.stopPropagation();\n\n const handler = handlers[handlerName][length - 1];\n handler!(e);\n}\n\nfunction releaseKeyboardListener(options: CaptureOptions) {\n (Object.keys(options) as Array<HandlerName>).forEach((handlerName) => {\n const handler = options[handlerName];\n const currentEventHandlers = handlers[handlerName];\n if (currentEventHandlers) {\n const index = currentEventHandlers.findIndex((cb) => cb === handler);\n if (index !== -1) {\n currentEventHandlers.splice(index, 1);\n }\n }\n });\n\n if (!hasActiveHandlers()) {\n document.removeEventListener('keydown', handleKeyDown, false);\n }\n}\n","import { useEffect } from '../lib/teact/teact';\nimport usePrevious from './usePrevious';\n\nexport default <T extends any[], PT = T>(cb: (args: PT) => void, dependencies: T, debugKey?: string) => {\n const prevDeps = usePrevious<T>(dependencies);\n return useEffect(() => {\n // @ts-ignore (workaround for \"could be instantiated with a different subtype\" issue)\n return cb(prevDeps || []);\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, dependencies, debugKey);\n};\n","/* eslint-disable no-nested-ternary */\n/* eslint-disable no-bitwise */\n\nconst utf16 = {\n // The utf16-class is necessary to convert from javascripts internal character representation to unicode and back.\n decode: (input) => {\n const output = [];\n let i = 0;\n const len = input.length;\n let value;\n let extra;\n\n while (i < len) {\n value = input.charCodeAt(i++);\n if ((value & 0xf800) === 0xd800) {\n extra = input.charCodeAt(i++);\n if ((value & 0xfc00) !== 0xd800 || (extra & 0xfc00) !== 0xdc00) {\n throw new RangeError('UTF-16(decode): Illegal UTF-16 sequence');\n }\n value = ((value & 0x3ff) << 10) + (extra & 0x3ff) + 0x10000;\n }\n output.push(value);\n }\n return output;\n },\n encode: (input) => {\n const output = [];\n let i = 0;\n const len = input.length;\n let value;\n\n while (i < len) {\n value = input[i++];\n if ((value & 0xf800) === 0xd800) {\n throw new RangeError('UTF-16(encode): Illegal UTF-16 value');\n }\n if (value > 0xffff) {\n value -= 0x10000;\n output.push(String.fromCharCode(((value >>> 10) & 0x3ff) | 0xd800));\n value = 0xdc00 | (value & 0x3ff);\n }\n output.push(String.fromCharCode(value));\n }\n return output.join('');\n },\n};\n\n// Default parameters\nconst initial_n = 0x80;\nconst initial_bias = 72;\nconst delimiter = '\\x2D';\nconst base = 36;\nconst damp = 700;\nconst tmin = 1;\nconst tmax = 26;\nconst skew = 38;\nconst maxint = 0x7fffffff;\n\n// decode_digit(cp) returns the numeric value of a basic code\n// point (for use in representing integers) in the range 0 to\n// base-1, or base if cp is does not represent a value.\n\nfunction decode_digit(cp) {\n return cp - 48 < 10 ? cp - 22 : cp - 65 < 26 ? cp - 65 : cp - 97 < 26 ? cp - 97 : base;\n}\n\n// ** Bias adaptation function **\nfunction adapt(delta, numpoints, firsttime) {\n let k;\n delta = firsttime ? Math.floor(delta / damp) : delta >> 1;\n delta += Math.floor(delta / numpoints);\n\n for (k = 0; delta > ((base - tmin) * tmax) >> 1; k += base) {\n delta = Math.floor(delta / (base - tmin));\n }\n return Math.floor(k + ((base - tmin + 1) * delta) / (delta + skew));\n}\n\n// Main decode\nfunction decode(input, preserveCase) {\n // Dont use utf16\n const output = [];\n const case_flags = [];\n const input_length = input.length;\n\n let n; let out; let i; let bias; let basic; let j; let ic; let oldi; let w; let k; let digit; let t; let len;\n\n // Initialize the state:\n\n n = initial_n;\n i = 0;\n bias = initial_bias;\n\n // Handle the basic code points: Let basic be the number of input code\n // points before the last delimiter, or 0 if there is none, then\n // copy the first basic code points to the output.\n\n basic = input.lastIndexOf(delimiter);\n if (basic < 0) basic = 0;\n\n for (j = 0; j < basic; ++j) {\n if (preserveCase) case_flags[output.length] = input.charCodeAt(j) - 65 < 26;\n if (input.charCodeAt(j) >= 0x80) {\n throw new RangeError('Illegal input >= 0x80');\n }\n output.push(input.charCodeAt(j));\n }\n\n // Main decoding loop: Start just after the last delimiter if any\n // basic code points were copied; start at the beginning otherwise.\n\n for (ic = basic > 0 ? basic + 1 : 0; ic < input_length;) {\n // ic is the index of the next character to be consumed,\n\n // Decode a generalized variable-length integer into delta,\n // which gets added to i. The overflow checking is easier\n // if we increase i as we go, then subtract off its starting\n // value at the end to obtain delta.\n for (oldi = i, w = 1, k = base; ; k += base) {\n if (ic >= input_length) {\n throw RangeError('punycode_bad_input(1)');\n }\n digit = decode_digit(input.charCodeAt(ic++));\n\n if (digit >= base) {\n throw RangeError('punycode_bad_input(2)');\n }\n if (digit > Math.floor((maxint - i) / w)) {\n throw RangeError('punycode_overflow(1)');\n }\n i += digit * w;\n t = k <= bias ? tmin : k >= bias + tmax ? tmax : k - bias;\n if (digit < t) {\n break;\n }\n if (w > Math.floor(maxint / (base - t))) {\n throw RangeError('punycode_overflow(2)');\n }\n w *= base - t;\n }\n\n out = output.length + 1;\n bias = adapt(i - oldi, out, oldi === 0);\n\n // i was supposed to wrap around from out to 0,\n // incrementing n each time, so we'll fix that now:\n if (Math.floor(i / out) > maxint - n) {\n throw RangeError('punycode_overflow(3)');\n }\n n += Math.floor(i / out);\n i %= out;\n\n // Insert n at position i of the output:\n // Case of last character determines uppercase flag:\n if (preserveCase) {\n case_flags.splice(i, 0, input.charCodeAt(ic - 1) - 65 < 26);\n }\n\n output.splice(i, 0, n);\n i++;\n }\n if (preserveCase) {\n for (i = 0, len = output.length; i < len; i++) {\n if (case_flags[i]) {\n output[i] = String.fromCharCode(output[i])\n .toUpperCase()\n .charCodeAt(0);\n }\n }\n }\n return utf16.encode(output);\n}\n\nfunction toUnicode(domain) {\n const domain_array = domain.split('.');\n const out = [];\n for (let i = 0; i < domain_array.length; ++i) {\n const s = domain_array[i];\n out.push(s.match(/^xn--/) ? decode(s.slice(4)) : s);\n }\n return out.join('.');\n}\n\nexport default toUnicode;\n","import React, { FC, memo, useCallback } from '../../lib/teact/teact';\nimport { getDispatch } from '../../lib/teact/teactn';\nimport convertPunycode from '../../lib/punycode';\n\nimport { DEBUG, RE_TME_INVITE_LINK, RE_TME_LINK } from '../../config';\nimport buildClassName from '../../util/buildClassName';\n\ntype OwnProps = {\n url?: string;\n text: string;\n className?: string;\n children?: any;\n isRtl?: boolean;\n};\n\nconst SafeLink: FC<OwnProps> = ({\n url,\n text,\n className,\n children,\n isRtl,\n}) => {\n const { toggleSafeLinkModal, openTelegramLink } = getDispatch();\n\n const content = children || text;\n const isNotSafe = url !== content;\n\n const handleClick = useCallback((e: React.MouseEvent<HTMLAnchorElement, MouseEvent>) => {\n if (\n e.ctrlKey || e.altKey || e.shiftKey || e.metaKey\n || !url || (!url.match(RE_TME_LINK) && !url.match(RE_TME_INVITE_LINK))\n ) {\n if (isNotSafe) {\n toggleSafeLinkModal({ url });\n\n e.preventDefault();\n return false;\n }\n\n return true;\n }\n\n e.preventDefault();\n openTelegramLink({ url });\n\n return false;\n }, [isNotSafe, openTelegramLink, toggleSafeLinkModal, url]);\n\n if (!url) {\n return undefined;\n }\n\n const classNames = buildClassName(\n className || 'text-entity-link',\n text.length > 50 && 'long-word-break-all',\n );\n\n return (\n <a\n href={ensureProtocol(url)}\n title={getDomain(url)}\n target=\"_blank\"\n rel=\"noopener noreferrer\"\n className={classNames}\n onClick={handleClick}\n dir={isRtl ? 'rtl' : 'auto'}\n >\n {content}\n </a>\n );\n};\n\nfunction ensureProtocol(url?: string) {\n if (!url) {\n return undefined;\n }\n\n return url.includes('://') ? url : `https://${url}`;\n}\n\nfunction getDomain(url?: string) {\n if (!url) {\n return undefined;\n }\n\n const href = ensureProtocol(url);\n if (!href) {\n return undefined;\n }\n\n try {\n let decodedHref = decodeURI(href);\n\n const match = decodedHref.match(/^https?:\\/\\/([^/:?#]+)(?:[/:?#]|$)/i);\n if (!match) {\n return undefined;\n }\n const domain = match[1];\n decodedHref = decodedHref.replace(domain, convertPunycode(domain));\n\n return decodedHref;\n } catch (error) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error('SafeLink.getDecodedUrl error ', url, error);\n }\n }\n\n return undefined;\n}\n\nexport default memo(SafeLink);\n","import { ApiDocument } from '../../../api/types';\n\nconst ONE_GIGABYTE = 1024 * 1024 * 1024;\nconst ONE_MEGABYTE = 1024 * 1024;\n\nexport function getFileSizeString(bytes: number) {\n if (bytes > (ONE_GIGABYTE / 2)) {\n return `${(bytes / ONE_GIGABYTE).toFixed(1)} GB`;\n }\n if (bytes > (ONE_MEGABYTE / 2)) {\n return `${(bytes / ONE_MEGABYTE).toFixed(1)} MB`;\n }\n return `${(bytes / (1024)).toFixed(1)} KB`;\n}\n\nexport function getDocumentExtension(document: ApiDocument) {\n const { fileName, mimeType } = document;\n\n return getFileExtension(fileName, mimeType);\n}\n\nexport function getFileExtension(fileName: string, mimeType: string) {\n if (fileName && fileName.indexOf('.') !== -1) {\n return fileName.split('.').pop();\n } else {\n return mimeType.split('/').pop();\n }\n}\n\nexport function getColorFromExtension(extension: string) {\n switch (extension) {\n case 'apk':\n case 'xls':\n case 'xlsx':\n return 'green';\n case 'zip':\n case 'rar':\n case '7z':\n case 'tar':\n case 'gz':\n case 'ppt':\n case 'pptx':\n return 'orange';\n case 'pdf':\n case 'xps':\n return 'red';\n default:\n return 'default';\n }\n}\n\nexport function getDocumentHasPreview(document: ApiDocument) {\n return Boolean(document.previewBlobUrl || document.thumbnail);\n}\n","import { ApiError, ApiInviteInfo } from '../../api/types';\n\nconst STRIPE_ERRORS: Record<string, Record<string, string>> = {\n missing_payment_information: {\n field: 'cardNumber',\n fieldError: 'Incorrect card number',\n },\n invalid_number: {\n field: 'cardNumber',\n fieldError: 'Incorrect card number',\n },\n number: {\n field: 'cardNumber',\n fieldError: 'Incorrect card number',\n },\n exp_year: {\n field: 'expiry',\n fieldError: 'Incorrect year',\n },\n exp_month: {\n field: 'expiry',\n fieldError: 'Incorrect month',\n },\n invalid_expiry_year: {\n field: 'expiry',\n fieldError: 'Incorrect year',\n },\n invalid_expiry_month: {\n field: 'expiry',\n fieldError: 'Incorrect month',\n },\n cvc: {\n field: 'cvv',\n fieldError: 'Incorrect CVV',\n },\n invalid_cvc: {\n field: 'cvv',\n fieldError: 'Incorrect CVV',\n },\n};\n\nexport function getStripeError(error: {\n code: string;\n message: string;\n param?: string;\n}) {\n const { message, code, param } = error;\n const { field, fieldError, description } = param ? STRIPE_ERRORS[param] : STRIPE_ERRORS[code];\n return {\n field,\n fieldError,\n description: description || message,\n };\n}\n\nconst SHIPPING_ERRORS: Record<string, Record<string, string>> = {\n ADDRESS_STREET_LINE1_INVALID: {\n field: 'streetLine1',\n fieldError: 'Incorrect street address',\n },\n ADDRESS_STREET_LINE2_INVALID: {\n field: 'streetLine2',\n fieldError: 'Incorrect street address',\n },\n ADDRESS_CITY_INVALID: {\n field: 'city',\n fieldError: 'Incorrect city',\n },\n ADDRESS_COUNTRY_INVALID: {\n field: 'countryIso2',\n fieldError: 'Incorrect country',\n },\n ADDRESS_POSTCODE_INVALID: {\n field: 'postCode',\n fieldError: 'Incorrect post code',\n },\n ADDRESS_STATE_INVALID: {\n field: 'state',\n fieldError: 'Incorrect state',\n },\n REQ_INFO_NAME_INVALID: {\n field: 'fullName',\n fieldError: 'Incorrect name',\n },\n REQ_INFO_PHONE_INVALID: {\n field: 'phone',\n fieldError: 'Incorrect phone',\n },\n REQ_INFO_EMAIL_INVALID: {\n field: 'email',\n fieldError: 'Incorrect email',\n },\n};\n\n\nexport function getShippingErrors(dialogs: (ApiError | ApiInviteInfo)[]) {\n return Object.values(dialogs).reduce((acc, cur) => {\n if (!('hasErrorKey' in cur) || !cur.hasErrorKey) return acc;\n const error = SHIPPING_ERRORS[cur.message];\n if (error) {\n acc = {\n ...acc,\n [error.field]: error.fieldError,\n };\n }\n return acc;\n }, {});\n}\n","import { fastRaf } from './schedulers';\n\ninterface AnimationInstance {\n isCancelled: boolean;\n}\n\nlet currentInstance: AnimationInstance | undefined;\n\nexport function animateSingle(tick: Function, instance?: AnimationInstance) {\n if (!instance) {\n if (currentInstance && !currentInstance.isCancelled) {\n currentInstance.isCancelled = true;\n }\n\n instance = { isCancelled: false };\n currentInstance = instance;\n }\n\n fastRaf(() => {\n if (!instance!.isCancelled && tick()) {\n animateSingle(tick, instance);\n }\n });\n}\n\nexport function animate(tick: Function) {\n fastRaf(() => {\n if (tick()) {\n animate(tick);\n }\n });\n}\n","import React, { FC, useState, useRef } from '../../lib/teact/teact';\n\nimport Menu from './Menu';\n\nimport './DropdownMenu.scss';\n\ntype OwnProps = {\n className?: string;\n trigger: FC<{ onTrigger: () => void; isOpen?: boolean }>;\n positionX?: 'left' | 'right';\n positionY?: 'top' | 'bottom';\n footer?: string;\n forceOpen?: boolean;\n onOpen?: NoneToVoidFunction;\n onClose?: NoneToVoidFunction;\n children: any;\n};\n\nconst DropdownMenu: FC<OwnProps> = ({\n trigger,\n className,\n children,\n positionX = 'left',\n positionY = 'top',\n footer,\n forceOpen,\n onOpen,\n onClose,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const menuRef = useRef<HTMLDivElement>(null);\n // eslint-disable-next-line no-null/no-null\n const dropdownRef = useRef<HTMLDivElement>(null);\n const [isOpen, setIsOpen] = useState(false);\n\n const toggleIsOpen = () => {\n setIsOpen(!isOpen);\n if (isOpen) {\n if (onClose) onClose();\n } else if (onOpen) onOpen();\n };\n\n const handleKeyDown = (e: React.KeyboardEvent<any>) => {\n const menu = menuRef.current;\n\n if (!isOpen || e.keyCode !== 40 || !menu) {\n return;\n }\n\n const focusedElement = document.activeElement;\n const elementChildren = Array.from(menu.children);\n\n if (!focusedElement || elementChildren.indexOf(focusedElement) === -1) {\n (elementChildren[0] as HTMLElement).focus();\n }\n };\n\n const handleClose = () => {\n setIsOpen(false);\n if (onClose) onClose();\n };\n\n return (\n <div\n ref={dropdownRef}\n className={`DropdownMenu ${className || ''}`}\n onKeyDown={handleKeyDown}\n >\n {trigger({ onTrigger: toggleIsOpen, isOpen })}\n\n <Menu\n ref={menuRef}\n containerRef={dropdownRef}\n isOpen={isOpen || !!forceOpen}\n className={className || ''}\n positionX={positionX}\n positionY={positionY}\n footer={footer}\n autoClose\n onClose={handleClose}\n shouldSkipTransition={forceOpen}\n >\n {children}\n </Menu>\n </div>\n );\n};\n\nexport default DropdownMenu;\n","import { RefObject } from 'react';\nimport { useState, useCallback, useEffect } from '../lib/teact/teact';\n\nexport default (\n elementRef: RefObject<HTMLElement>,\n isOpen: boolean,\n onSelectWithEnter?: (index: number) => void,\n itemSelector?: string,\n noCaptureFocus?: boolean,\n) => {\n const [focusedIndex, setFocusedIndex] = useState(-1);\n\n useEffect(() => {\n setFocusedIndex(-1);\n\n const element = elementRef.current;\n if (isOpen && element && !noCaptureFocus) {\n element.tabIndex = -1;\n element.focus();\n }\n }, [elementRef, isOpen, noCaptureFocus]);\n\n const handleKeyDown = useCallback((e: React.KeyboardEvent<any>) => {\n const element = elementRef.current;\n\n if (!element) {\n return;\n }\n\n if (e.keyCode === 13 && onSelectWithEnter) {\n onSelectWithEnter(focusedIndex);\n return;\n }\n\n if (e.keyCode !== 38 && e.keyCode !== 40) {\n return;\n }\n\n const focusedElement = document.activeElement;\n const elementChildren = Array.from(itemSelector ? element.querySelectorAll(itemSelector) : element.children);\n\n let newIndex = (focusedElement && elementChildren.indexOf(focusedElement)) || focusedIndex;\n\n if (e.keyCode === 38 && newIndex > 0) {\n newIndex--;\n } else if (e.keyCode === 40 && newIndex < elementChildren.length - 1) {\n newIndex++;\n } else if (elementChildren.length === 1) {\n newIndex = 0;\n } else {\n return;\n }\n\n const item = elementChildren[newIndex] as HTMLElement;\n if (item) {\n setFocusedIndex(newIndex);\n item.focus();\n }\n }, [elementRef, onSelectWithEnter, itemSelector, focusedIndex]);\n\n return handleKeyDown;\n};\n","// @ts-ignore\nimport twemojiRegex from '../../../lib/twemojiRegex';\n\nconst DETECT_UP_TO = 3;\nconst MAX_LENGTH = DETECT_UP_TO * 8; // Maximum 8 per one emoji.\nconst RE_EMOJI_ONLY = new RegExp(`^(?:${twemojiRegex.source})+$`, '');\n\nexport default (text: string): number | false => {\n if (text.length > MAX_LENGTH) {\n return false;\n }\n\n const isEmojiOnly = Boolean(text.match(RE_EMOJI_ONLY));\n if (!isEmojiOnly) {\n return false;\n }\n\n let emojiCount = 0;\n while (twemojiRegex.exec(text)) {\n emojiCount++;\n\n if (emojiCount > DETECT_UP_TO) {\n twemojiRegex.lastIndex = 0;\n return false;\n }\n }\n\n return emojiCount;\n};\n","// Due to the fact that emoji from Apple do not contain some characters, it is necessary to remove them from emoji-data\n// https://github.com/iamcal/emoji-data/issues/136\nconst EXCLUDE_EMOJIS = ['female_sign', 'male_sign', 'medical_symbol'];\n\nexport type EmojiRawData = typeof import('emoji-data-ios/emoji-data.json');\nexport type EmojiModule = { default: EmojiRawData };\n\nexport type EmojiData = {\n categories: Array<EmojiCategory>;\n emojis: Record<string, Emoji>;\n};\n\nfunction unifiedToNative(unified: string) {\n const unicodes = unified.split('-');\n const codePoints = unicodes.map((i) => parseInt(i, 16));\n\n return String.fromCodePoint(...codePoints);\n}\n\nexport function nativeToUnfified(emoji: string) {\n let code;\n\n if (emoji.length === 1) {\n code = emoji.charCodeAt(0).toString(16).padStart(4, '0');\n } else {\n const pairs = [];\n for (let i = 0; i < emoji.length; i++) {\n if (emoji.charCodeAt(i) >= 0xd800 && emoji.charCodeAt(i) <= 0xdbff) {\n if (emoji.charCodeAt(i + 1) >= 0xdc00 && emoji.charCodeAt(i + 1) <= 0xdfff) {\n pairs.push(\n (emoji.charCodeAt(i) - 0xd800) * 0x400\n + (emoji.charCodeAt(i + 1) - 0xdc00) + 0x10000,\n );\n }\n } else if (emoji.charCodeAt(i) < 0xd800 || emoji.charCodeAt(i) > 0xdfff) {\n pairs.push(emoji.charCodeAt(i));\n }\n }\n\n code = pairs.map((x) => x.toString(16).padStart(4, '0')).join('-');\n }\n\n return code;\n}\n\nexport function uncompressEmoji(data: EmojiRawData): EmojiData {\n const emojiData: EmojiData = { categories: [], emojis: {} };\n\n for (let i = 0; i < data.length; i += 2) {\n const category = {\n id: data[i][0],\n name: data[i][1],\n emojis: [],\n } as EmojiCategory;\n\n for (let j = 0; j < data[i + 1].length; j++) {\n const emojiRaw = data[i + 1][j];\n if (!EXCLUDE_EMOJIS.includes(emojiRaw[1][0])) {\n category.emojis.push(emojiRaw[1][0]);\n emojiData.emojis[emojiRaw[1][0]] = {\n id: emojiRaw[1][0],\n names: emojiRaw[1] as string[],\n native: unifiedToNative(emojiRaw[0] as string),\n image: (emojiRaw[0] as string).toLowerCase(),\n };\n }\n }\n\n emojiData.categories.push(category);\n }\n\n return emojiData;\n}\n","import {\n hasElementChanged,\n isComponentElement,\n isEmptyElement,\n isRealElement,\n isTextElement,\n mountComponent,\n renderComponent,\n unmountTree,\n getTarget,\n setTarget,\n VirtualElement,\n VirtualElementComponent,\n VirtualRealElement,\n} from './teact';\nimport generateIdFor from '../../util/generateIdFor';\nimport { DEBUG } from '../../config';\nimport { addEventListener, removeEventListener } from './dom-events';\n\ntype VirtualDomHead = {\n children: [VirtualElement] | [];\n};\n\nconst FILTERED_ATTRIBUTES = new Set(['key', 'ref', 'teactFastList', 'teactOrderKey']);\nconst HTML_ATTRIBUTES = new Set(['dir']);\nconst MAPPED_ATTRIBUTES: { [k: string]: string } = {\n autoPlay: 'autoplay',\n autoComplete: 'autocomplete',\n};\nconst INDEX_KEY_PREFIX = '__indexKey#';\n\nconst headsByElement: Record<string, VirtualDomHead> = {};\nlet DEBUG_virtualTreeSize = 1;\n\nfunction render($element?: VirtualElement, parentEl?: HTMLElement | null) {\n if (!parentEl) {\n return undefined;\n }\n\n let headId = parentEl.getAttribute('data-teact-head-id');\n if (!headId) {\n headId = generateIdFor(headsByElement);\n headsByElement[headId] = { children: [] };\n parentEl.setAttribute('data-teact-head-id', headId);\n }\n\n const $head = headsByElement[headId];\n $head.children = [renderWithVirtual(parentEl, $head.children[0], $element, $head, 0) as VirtualElement];\n\n if (process.env.APP_ENV === 'perf') {\n DEBUG_virtualTreeSize = 0;\n DEBUG_addToVirtualTreeSize($head);\n\n return DEBUG_virtualTreeSize;\n }\n\n return undefined;\n}\n\nfunction renderWithVirtual(\n parentEl: HTMLElement,\n $current: VirtualElement | undefined,\n $new: VirtualElement | undefined,\n $parent: VirtualRealElement | VirtualDomHead,\n index: number,\n {\n skipComponentUpdate = false,\n forceIndex = false,\n fragment,\n moveDirection,\n }: {\n skipComponentUpdate?: boolean;\n forceIndex?: boolean;\n fragment?: DocumentFragment;\n moveDirection?: 'up' | 'down';\n } = {},\n) {\n if (\n !skipComponentUpdate\n && $current && $new\n && isComponentElement($current) && isComponentElement($new)\n && !hasElementChanged($current, $new)\n ) {\n $new = updateComponent($current, $new);\n }\n\n // Parent element may have changed, so we need to update the listener closure.\n if (!skipComponentUpdate && $new && isComponentElement($new) && $new.componentInstance.isMounted) {\n setupComponentUpdateListener($new, $parent, index, parentEl);\n }\n\n if ($current === $new) {\n return $new;\n }\n\n if (!$current && $new) {\n if (isComponentElement($new)) {\n $new = initComponent($new, $parent, index, parentEl);\n }\n\n const node = createNode($new);\n setTarget($new, node);\n\n if (forceIndex && parentEl.childNodes[index]) {\n parentEl.insertBefore(node, parentEl.childNodes[index]);\n } else {\n (fragment || parentEl).appendChild(node);\n }\n } else if ($current && !$new) {\n parentEl.removeChild(getTarget($current)!);\n unmountTree($current);\n } else if ($current && $new) {\n if (hasElementChanged($current, $new)) {\n if (isComponentElement($new)) {\n $new = initComponent($new, $parent, index, parentEl);\n }\n\n const node = createNode($new);\n setTarget($new, node);\n parentEl.replaceChild(node, getTarget($current)!);\n unmountTree($current);\n } else {\n const areComponents = isComponentElement($current) && isComponentElement($new);\n\n if (!areComponents) {\n setTarget($new, getTarget($current)!);\n }\n\n if (isRealElement($current) && isRealElement($new)) {\n if (moveDirection) {\n const node = getTarget($current)!;\n const nextSibling = parentEl.childNodes[moveDirection === 'up' ? index : index + 1];\n\n if (nextSibling) {\n parentEl.insertBefore(node, nextSibling);\n } else {\n (fragment || parentEl).appendChild(node);\n }\n }\n\n if (!areComponents) {\n updateAttributes($current, $new, getTarget($current) as HTMLElement);\n }\n\n $new.children = renderChildren(\n $current,\n $new,\n areComponents ? parentEl : getTarget($current) as HTMLElement,\n );\n }\n }\n }\n\n return $new;\n}\n\nfunction initComponent(\n $element: VirtualElementComponent, $parent: VirtualRealElement | VirtualDomHead, index: number, parentEl: HTMLElement,\n) {\n if (!isComponentElement($element)) {\n return $element;\n }\n\n const { componentInstance } = $element;\n\n if (!componentInstance.isMounted) {\n $element = mountComponent(componentInstance);\n setupComponentUpdateListener($element, $parent, index, parentEl);\n\n const $firstChild = $element.children[0];\n if (isComponentElement($firstChild)) {\n $element.children = [initComponent($firstChild, $element, 0, parentEl)];\n }\n\n componentInstance.isMounted = true;\n }\n\n return $element;\n}\n\nfunction updateComponent($current: VirtualElementComponent, $new: VirtualElementComponent) {\n $current.componentInstance.props = $new.componentInstance.props;\n\n return renderComponent($current.componentInstance);\n}\n\nfunction setupComponentUpdateListener(\n $element: VirtualElementComponent, $parent: VirtualRealElement | VirtualDomHead, index: number, parentEl: HTMLElement,\n) {\n const { componentInstance } = $element;\n\n componentInstance.onUpdate = () => {\n $parent.children[index] = renderWithVirtual(\n parentEl,\n $parent.children[index],\n componentInstance.$element,\n $parent,\n index,\n { skipComponentUpdate: true },\n ) as VirtualElementComponent;\n };\n}\n\nfunction createNode($element: VirtualElement): Node {\n if (isEmptyElement($element)) {\n return document.createTextNode('');\n }\n\n if (isTextElement($element)) {\n return document.createTextNode($element.value);\n }\n\n if (isComponentElement($element)) {\n return createNode($element.children[0] as VirtualElement);\n }\n\n const { tag, props, children = [] } = $element;\n const element = document.createElement(tag);\n\n if (typeof props.ref === 'object') {\n props.ref.current = element;\n }\n\n Object.keys(props).forEach((key) => {\n addAttribute(element, key, props[key]);\n });\n\n $element.children = children.map(($child, i) => (\n renderWithVirtual(element, undefined, $child, $element, i) as VirtualElement\n ));\n\n return element;\n}\n\nfunction renderChildren(\n $current: VirtualRealElement, $new: VirtualRealElement, currentEl: HTMLElement,\n) {\n if ($new.props.teactFastList) {\n return renderFastListChildren($current, $new, currentEl);\n }\n\n const maxLength = Math.max($current.children.length, $new.children.length);\n const newChildren = [];\n const fragment = $new.children.length > $current.children.length + 1 ? document.createDocumentFragment() : undefined;\n\n for (let i = 0; i < maxLength; i++) {\n const $newChild = renderWithVirtual(\n currentEl,\n $current.children[i],\n $new.children[i],\n $new,\n i,\n i >= $current.children.length ? { fragment } : undefined,\n );\n\n if ($newChild) {\n newChildren.push($newChild);\n }\n }\n\n if (fragment) {\n currentEl.appendChild(fragment);\n }\n\n return newChildren;\n}\n\nfunction renderFastListChildren($current: VirtualRealElement, $new: VirtualRealElement, currentEl: HTMLElement) {\n const newKeys = new Set(\n $new.children.map(($newChild) => {\n const key = 'props' in $newChild && $newChild.props.key;\n\n if (DEBUG && isRealElement($newChild) && !key) {\n // eslint-disable-next-line no-console\n console.warn('Missing `key` in `teactFastList`');\n }\n\n return key;\n }),\n );\n\n let currentRemainingIndex = 0;\n const remainingByKey = $current.children\n .reduce((acc, $currentChild, i) => {\n let key = 'props' in $currentChild ? $currentChild.props.key : undefined;\n\n // First we handle removed children\n if (key && !newKeys.has(key)) {\n renderWithVirtual(currentEl, $currentChild, undefined, $new, -1);\n\n return acc;\n } else if (!key) {\n const $newChild = $new.children[i];\n const newChildKey = ($newChild && 'props' in $newChild) ? $newChild.props.key : undefined;\n // If a non-key element remains at the same index we preserve it with a virtual `key`\n if ($newChild && !newChildKey) {\n key = `${INDEX_KEY_PREFIX}${i}`;\n } else {\n renderWithVirtual(currentEl, $currentChild, undefined, $new, -1);\n\n return acc;\n }\n }\n\n // Then we build up info about remaining children\n acc[key] = {\n $element: $currentChild,\n index: currentRemainingIndex++,\n order: 'props' in $currentChild ? $currentChild.props.teactOrderKey : undefined,\n };\n return acc;\n }, {} as Record<string, { $element: VirtualElement; index: number; order?: number }>);\n\n let newChildren: VirtualElement[] = [];\n\n let fragmentQueue: VirtualElement[] | undefined;\n let fragmentIndex: number | undefined;\n\n let currentPreservedIndex = 0;\n\n $new.children.forEach(($newChild, i) => {\n const key = 'props' in $newChild ? $newChild.props.key : `${INDEX_KEY_PREFIX}${i}`;\n const currentChildInfo = remainingByKey[key];\n\n if (!currentChildInfo) {\n // All new nodes are queued to be inserted with fragments if possible.\n if (!fragmentQueue) {\n fragmentQueue = [];\n fragmentIndex = i;\n }\n\n fragmentQueue.push($newChild);\n return;\n }\n\n if (fragmentQueue) {\n newChildren = newChildren.concat(flushFragmentQueue(fragmentQueue, fragmentIndex!, currentEl, $new));\n fragmentIndex = undefined;\n fragmentQueue = undefined;\n }\n\n // This is a \"magic\" `teactOrderKey` property that tells us the element is updated\n const order = 'props' in $newChild ? $newChild.props.teactOrderKey : undefined;\n const shouldMoveNode = currentChildInfo.index !== currentPreservedIndex && currentChildInfo.order !== order;\n const isMovingDown = shouldMoveNode && currentPreservedIndex > currentChildInfo.index;\n\n // When the node goes down, preserved indexing actually breaks, so the \"magic\" should help.\n if (!shouldMoveNode || isMovingDown) {\n currentPreservedIndex++;\n }\n\n newChildren.push(\n renderWithVirtual(currentEl, currentChildInfo.$element, $newChild, $new, i, {\n forceIndex: true,\n ...(shouldMoveNode && {\n moveDirection: isMovingDown ? 'down' : 'up',\n }),\n })!,\n );\n });\n\n if (fragmentQueue) {\n newChildren = newChildren.concat(flushFragmentQueue(fragmentQueue, fragmentIndex!, currentEl, $new));\n }\n\n return newChildren;\n}\n\nfunction flushFragmentQueue(\n fragmentQueue: VirtualElement[], fragmentIndex: number, parentEl: HTMLElement, $parent: VirtualRealElement,\n) {\n if (fragmentQueue.length === 1) {\n return [renderWithVirtual(parentEl, undefined, fragmentQueue[0], $parent, fragmentIndex, { forceIndex: true })!];\n } else if (fragmentQueue.length > 1) {\n const fragment = document.createDocumentFragment();\n const newChildren = fragmentQueue.map(($fragmentChild) => (\n renderWithVirtual(parentEl, undefined, $fragmentChild, $parent, fragmentIndex!, { fragment })!\n ));\n\n if (parentEl.childNodes[fragmentIndex]) {\n parentEl.insertBefore(fragment, parentEl.childNodes[fragmentIndex]);\n } else {\n parentEl.appendChild(fragment);\n }\n\n return newChildren;\n }\n\n throw new Error('Unexpected input');\n}\n\nfunction updateAttributes($current: VirtualRealElement, $new: VirtualRealElement, element: HTMLElement) {\n const currentKeys = Object.keys($current.props);\n const newKeys = Object.keys($new.props);\n\n currentKeys.forEach((key) => {\n if ($current.props[key] !== undefined && $new.props[key] === undefined) {\n removeAttribute(element, key, $current.props[key]);\n }\n });\n\n newKeys.forEach((key) => {\n if ($new.props[key] === undefined) {\n return;\n }\n\n if ($current.props[key] !== $new.props[key]) {\n if ($current.props[key] === undefined) {\n addAttribute(element, key, $new.props[key]);\n } else {\n updateAttribute(element, key, $current.props[key], $new.props[key]);\n }\n }\n });\n}\n\nfunction addAttribute(element: HTMLElement, key: string, value: any) {\n if (value === undefined) {\n return;\n }\n\n // An optimization attempt\n if (key === 'className') {\n element.className = value;\n // An optimization attempt\n } else if (key === 'value') {\n (element as HTMLInputElement).value = value;\n } else if (key === 'style') {\n element.style.cssText = value;\n } else if (key.startsWith('on')) {\n addEventListener(element, key, value, key.endsWith('Capture'));\n } else if (key.startsWith('data-') || HTML_ATTRIBUTES.has(key)) {\n element.setAttribute(key, value);\n } else if (!FILTERED_ATTRIBUTES.has(key)) {\n (element as any)[MAPPED_ATTRIBUTES[key] || key] = value;\n }\n}\n\nfunction removeAttribute(element: HTMLElement, key: string, value: any) {\n if (key === 'className') {\n element.className = '';\n } else if (key === 'value') {\n (element as HTMLInputElement).value = '';\n } else if (key === 'style') {\n element.style.cssText = '';\n } else if (key.startsWith('on')) {\n removeEventListener(element, key, value, key.endsWith('Capture'));\n } else if (key.startsWith('data-') || HTML_ATTRIBUTES.has(key)) {\n element.removeAttribute(key);\n } else if (!FILTERED_ATTRIBUTES.has(key)) {\n delete (element as any)[MAPPED_ATTRIBUTES[key] || key];\n }\n}\n\nfunction updateAttribute(element: HTMLElement, key: string, oldValue: any, newValue: any) {\n if (key === 'value') {\n // Removing and adding value causes a cursor jump\n (element as HTMLInputElement).value = newValue !== undefined ? newValue : '';\n } else {\n removeAttribute(element, key, oldValue);\n addAttribute(element, key, newValue);\n }\n}\n\nfunction DEBUG_addToVirtualTreeSize($current: VirtualRealElement | VirtualDomHead) {\n DEBUG_virtualTreeSize += $current.children.length;\n\n $current.children.forEach(($child) => {\n if (isRealElement($child)) {\n DEBUG_addToVirtualTreeSize($child);\n }\n });\n}\n\nexport default { render };\n","import React, { FC, useCallback } from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../global/types';\nimport { ApiChat, ApiUser } from '../../api/types';\n\nimport { pick } from '../../util/iteratees';\nimport buildClassName from '../../util/buildClassName';\n\nimport Link from '../ui/Link';\n\ntype OwnProps = {\n className?: string;\n sender?: ApiUser | ApiChat;\n children: any;\n};\n\ntype DispatchProps = Pick<GlobalActions, 'openUserInfo'>;\n\nconst UserLink: FC<OwnProps & DispatchProps> = ({\n className, sender, openUserInfo, children,\n}) => {\n const handleClick = useCallback(() => {\n if (sender) {\n openUserInfo({ id: sender.id });\n }\n }, [sender, openUserInfo]);\n\n if (!sender) {\n return children;\n }\n\n return (\n <Link className={buildClassName('UserLink', className)} onClick={handleClick}>{children}</Link>\n );\n};\n\nexport default withGlobal<OwnProps>(\n undefined,\n (setGlobal, actions): DispatchProps => pick(actions, ['openUserInfo']),\n)(UserLink);\n","import React, { FC, useCallback } from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../global/types';\nimport { ApiMessage } from '../../api/types';\n\nimport { pick } from '../../util/iteratees';\nimport buildClassName from '../../util/buildClassName';\n\nimport Link from '../ui/Link';\n\ntype OwnProps = {\n className?: string;\n message?: ApiMessage;\n children: any;\n};\n\ntype DispatchProps = Pick<GlobalActions, 'focusMessage'>;\n\nconst MessageLink: FC<OwnProps & DispatchProps> = ({\n className, message, children, focusMessage,\n}) => {\n const handleMessageClick = useCallback((): void => {\n if (message) {\n focusMessage({ chatId: message.chatId, messageId: message.id });\n }\n }, [focusMessage, message]);\n\n if (!message) {\n return children;\n }\n\n return (\n <Link className={buildClassName('MessageLink', className)} onClick={handleMessageClick}>{children}</Link>\n );\n};\n\nexport default withGlobal<OwnProps>(\n undefined,\n (setGlobal, actions): DispatchProps => pick(actions, ['focusMessage']),\n)(MessageLink);\n","import React, { FC, useCallback } from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../global/types';\n\nimport { pick } from '../../util/iteratees';\nimport buildClassName from '../../util/buildClassName';\n\nimport Link from '../ui/Link';\n\ntype OwnProps = {\n className?: string;\n chatId?: number;\n children: any;\n};\n\ntype DispatchProps = Pick<GlobalActions, 'openChat'>;\n\nconst ChatLink: FC<OwnProps & DispatchProps> = ({\n className, chatId, openChat, children,\n}) => {\n const handleClick = useCallback(() => {\n if (chatId) {\n openChat({ id: chatId });\n }\n }, [chatId, openChat]);\n\n if (!chatId) {\n return children;\n }\n\n return (\n <Link className={buildClassName('ChatLink', className)} onClick={handleClick}>{children}</Link>\n );\n};\n\nexport default withGlobal<OwnProps>(\n undefined,\n (setGlobal, actions): DispatchProps => pick(actions, ['openChat']),\n)(ChatLink);\n","import React from '../../../lib/teact/teact';\n\nimport { ApiChat, ApiMessage, ApiUser } from '../../../api/types';\nimport { LangFn } from '../../../hooks/useLang';\nimport {\n getChatTitle,\n getMessageContent,\n getMessageSummaryText,\n getUserFullName,\n isChat,\n} from '../../../modules/helpers';\nimport trimText from '../../../util/trimText';\nimport { TextPart } from './renderMessageText';\nimport renderText from './renderText';\n\nimport UserLink from '../UserLink';\nimport MessageLink from '../MessageLink';\nimport ChatLink from '../ChatLink';\n\ninterface ActionMessageTextOptions {\n maxTextLength?: number;\n asPlain?: boolean;\n isEmbedded?: boolean;\n}\n\nconst NBSP = '\\u00A0';\n\nexport function renderActionMessageText(\n lang: LangFn,\n message: ApiMessage,\n actionOrigin?: ApiUser | ApiChat,\n targetUsers?: ApiUser[],\n targetMessage?: ApiMessage,\n targetChatId?: number,\n options: ActionMessageTextOptions = {},\n) {\n if (!message.content.action) {\n return [];\n }\n const { text, translationValues } = message.content.action;\n const content: TextPart[] = [];\n const textOptions: ActionMessageTextOptions = { ...options, maxTextLength: 32 };\n const translationKey = text === 'Chat.Service.Group.UpdatedPinnedMessage1' && !targetMessage\n ? 'Message.PinnedGenericMessage'\n : text;\n\n let unprocessed: string;\n let processed = processPlaceholder(\n lang(translationKey, translationValues && translationValues.length ? translationValues : undefined),\n '%action_origin%',\n actionOrigin\n ? (!options.isEmbedded && renderOriginContent(lang, actionOrigin, options.asPlain)) || NBSP\n : 'User',\n );\n\n unprocessed = processed.pop() as string;\n content.push(...processed);\n\n processed = processPlaceholder(\n unprocessed,\n '%target_user%',\n targetUsers\n ? targetUsers.map((user) => renderUserContent(user, options.asPlain)).filter<TextPart>(Boolean as any)\n : 'User',\n );\n\n unprocessed = processed.pop() as string;\n content.push(...processed);\n\n processed = processPlaceholder(\n unprocessed,\n '%message%',\n targetMessage\n ? renderMessageContent(lang, targetMessage, textOptions)\n : 'a message',\n );\n unprocessed = processed.pop() as string;\n content.push(...processed);\n\n processed = processPlaceholder(\n unprocessed,\n '%product%',\n targetMessage\n ? renderProductContent(targetMessage)\n : 'a product',\n );\n unprocessed = processed.pop() as string;\n content.push(...processed);\n\n processed = processPlaceholder(\n unprocessed,\n '%target_chat%',\n targetChatId\n ? renderMigratedContent(targetChatId, options.asPlain)\n : 'another chat',\n );\n content.push(...processed);\n\n if (options.asPlain) {\n return content.join('').trim();\n }\n\n return content;\n}\n\nfunction renderProductContent(message: ApiMessage) {\n return message.content && message.content.invoice\n ? message.content.invoice.title\n : 'a product';\n}\n\nfunction renderMessageContent(lang: LangFn, message: ApiMessage, options: ActionMessageTextOptions = {}) {\n const text = getMessageSummaryText(lang, message);\n const {\n photo, video, document, sticker,\n } = getMessageContent(message);\n\n const { maxTextLength, isEmbedded, asPlain } = options;\n\n const showQuotes = isEmbedded && text && !photo && !video && !document && !sticker;\n let messageText = trimText(text as string, maxTextLength)!;\n\n if (isEmbedded) {\n if (photo) {\n messageText = 'a photo';\n } else if (video) {\n messageText = video.isGif ? 'a GIF' : 'a video';\n } else if (document) {\n messageText = 'a document';\n } else if (sticker) {\n messageText = text;\n }\n }\n\n if (asPlain) {\n return showQuotes ? `«${messageText}»` : messageText;\n }\n\n if (showQuotes) {\n return (\n <span>\n «\n <MessageLink className=\"action-link\" message={message}>{renderText(messageText)}</MessageLink>\n »\n </span>\n );\n }\n\n return (\n <MessageLink className=\"action-link\" message={message}>{renderText(messageText)}</MessageLink>\n );\n}\n\nfunction renderOriginContent(lang: LangFn, origin: ApiUser | ApiChat, asPlain?: boolean) {\n return isChat(origin)\n ? renderChatContent(lang, origin, asPlain)\n : renderUserContent(origin, asPlain);\n}\n\nfunction renderUserContent(sender: ApiUser, asPlain?: boolean): string | TextPart | undefined {\n const text = trimText(getUserFullName(sender));\n\n if (asPlain) {\n return text;\n }\n\n return <UserLink className=\"action-link\" sender={sender}>{sender && renderText(text!)}</UserLink>;\n}\n\nfunction renderChatContent(lang: LangFn, chat: ApiChat, asPlain?: boolean): string | TextPart | undefined {\n const text = trimText(getChatTitle(lang, chat));\n\n if (asPlain) {\n return text;\n }\n\n return <ChatLink className=\"action-link\" chatId={chat.id}>{chat && renderText(text!)}</ChatLink>;\n}\n\nfunction renderMigratedContent(chatId: number, asPlain?: boolean): string | TextPart | undefined {\n const text = 'another chat';\n\n if (asPlain) {\n return text;\n }\n\n return <ChatLink className=\"action-link\" chatId={chatId}>{text}</ChatLink>;\n}\n\nfunction processPlaceholder(text: string, placeholder: string, replaceValue?: TextPart | TextPart[]): TextPart[] {\n const placeholderPosition = text.indexOf(placeholder);\n if (placeholderPosition < 0 || !replaceValue) {\n return [text];\n }\n\n const content: TextPart[] = [];\n content.push(text.substring(0, placeholderPosition));\n if (Array.isArray(replaceValue)) {\n replaceValue.forEach((value, index) => {\n content.push(value);\n if (index + 1 < replaceValue.length) {\n content.push(', ');\n }\n });\n } else {\n content.push(replaceValue);\n }\n content.push(text.substring(placeholderPosition + placeholder.length));\n\n return content;\n}\n","export interface ApiDimensions {\n width: number;\n height: number;\n}\n\nexport interface ApiPhotoSize extends ApiDimensions {\n type: 's' | 'm' | 'x' | 'y' | 'z';\n}\n\nexport interface ApiThumbnail extends ApiDimensions {\n dataUri: string;\n}\n\nexport interface ApiPhoto {\n id: string;\n thumbnail?: ApiThumbnail;\n sizes: ApiPhotoSize[];\n blobUrl?: string;\n}\n\nexport interface ApiSticker {\n id: string;\n stickerSetId: string;\n stickerSetAccessHash?: string;\n emoji?: string;\n isAnimated: boolean;\n width?: number;\n height?: number;\n thumbnail?: ApiThumbnail;\n isPreloadedGlobally?: boolean;\n}\n\nexport interface ApiStickerSet {\n archived?: true;\n isAnimated?: true;\n installedDate?: number;\n id: string;\n accessHash: string;\n title: string;\n hasThumbnail?: boolean;\n count: number;\n hash: number;\n stickers?: ApiSticker[];\n packs?: Record<string, ApiSticker[]>;\n covers?: ApiSticker[];\n shortName: string;\n}\n\nexport interface ApiVideo {\n id: string;\n mimeType: string;\n duration: number;\n fileName: string;\n width?: number;\n height?: number;\n supportsStreaming?: boolean;\n isRound?: boolean;\n isGif?: boolean;\n thumbnail?: ApiThumbnail;\n blobUrl?: string;\n size: number;\n}\n\nexport interface ApiAudio {\n size: number;\n mimeType: string;\n fileName: string;\n duration: number;\n performer?: string;\n title?: string;\n}\n\nexport interface ApiVoice {\n duration: number;\n waveform?: number[];\n}\n\nexport interface ApiDocument {\n id?: string;\n fileName: string;\n size: number;\n timestamp?: number;\n mimeType: string;\n thumbnail?: ApiThumbnail;\n previewBlobUrl?: string;\n mediaType?: 'photo' | 'video';\n mediaSize?: ApiDimensions;\n}\n\nexport interface ApiContact {\n firstName: string;\n lastName: string;\n phoneNumber: string;\n userId: number;\n}\n\nexport interface ApiPollAnswer {\n text: string;\n option: string;\n}\n\nexport interface ApiPollResult {\n isChosen?: true;\n isCorrect?: true;\n option: string;\n votersCount: number;\n}\n\nexport interface ApiPoll {\n id: string;\n summary: {\n closed?: true;\n isPublic?: true;\n multipleChoice?: true;\n quiz?: true;\n question: string;\n answers: ApiPollAnswer[];\n closePeriod?: number;\n closeDate?: number;\n };\n results: {\n results?: ApiPollResult[];\n totalVoters?: number;\n recentVoterIds?: number[];\n solution?: string;\n solutionEntities?: ApiMessageEntity[];\n };\n}\n\nexport interface ApiInvoice {\n text: string;\n title: string;\n photoUrl?: string;\n description?: string;\n receiptMsgId?: number;\n}\n\nexport type ApiNewPoll = {\n summary: ApiPoll['summary'];\n quiz?: {\n correctAnswers: string[];\n solution?: string;\n solutionEntities?: ApiMessageEntity[];\n };\n};\n\nexport interface ApiAction {\n text: string;\n targetUserIds?: number[];\n targetChatId?: number;\n type: 'historyClear' | 'contactSignUp' | 'chatCreate' | 'other';\n photo?: ApiPhoto;\n translationValues: string[];\n}\n\nexport interface ApiWebPage {\n id: number;\n url: string;\n displayUrl: string;\n type?: string;\n siteName?: string;\n title?: string;\n description?: string;\n photo?: ApiPhoto;\n duration?: number;\n document?: ApiDocument;\n video?: ApiVideo;\n}\n\nexport interface ApiMessageForwardInfo {\n isChannelPost: boolean;\n isLinkedChannelPost?: boolean;\n fromChatId?: number;\n senderUserId?: number;\n fromMessageId?: number;\n hiddenUserName?: string;\n adminTitle?: string;\n}\n\nexport interface ApiMessageEntity {\n type: string;\n offset: number;\n length: number;\n userId?: number;\n url?: string;\n}\n\nexport enum ApiMessageEntityTypes {\n Bold = 'MessageEntityBold',\n Blockquote = 'MessageEntityBlockquote',\n BotCommand = 'MessageEntityBotCommand',\n Cashtag = 'MessageEntityCashtag',\n Code = 'MessageEntityCode',\n Email = 'MessageEntityEmail',\n Hashtag = 'MessageEntityHashtag',\n Italic = 'MessageEntityItalic',\n MentionName = 'MessageEntityMentionName',\n Mention = 'MessageEntityMention',\n Phone = 'MessageEntityPhone',\n Pre = 'MessageEntityPre',\n Strike = 'MessageEntityStrike',\n TextUrl = 'MessageEntityTextUrl',\n Url = 'MessageEntityUrl',\n Underline = 'MessageEntityUnderline',\n Unknown = 'MessageEntityUnknown',\n}\n\nexport interface ApiFormattedText {\n text: string;\n entities?: ApiMessageEntity[];\n}\n\nexport interface ApiMessage {\n id: number;\n chatId: number;\n content: {\n text?: ApiFormattedText;\n photo?: ApiPhoto;\n video?: ApiVideo;\n document?: ApiDocument;\n sticker?: ApiSticker;\n contact?: ApiContact;\n poll?: ApiPoll;\n action?: ApiAction;\n webPage?: ApiWebPage;\n audio?: ApiAudio;\n voice?: ApiVoice;\n invoice?: ApiInvoice;\n };\n date: number;\n isOutgoing: boolean;\n senderId?: number;\n replyToMessageId?: number;\n replyToTopMessageId?: number;\n sendingState?: 'messageSendingStatePending' | 'messageSendingStateFailed';\n forwardInfo?: ApiMessageForwardInfo;\n isDeleting?: boolean;\n previousLocalId?: number;\n views?: number;\n isEdited?: boolean;\n isMediaUnread?: boolean;\n groupedId?: string;\n isInAlbum?: boolean;\n hasUnreadMention?: boolean;\n inlineButtons?: ApiKeyboardButtons;\n keyboardButtons?: ApiKeyboardButtons;\n keyboardPlaceholder?: string;\n isKeyboardSingleUse?: boolean;\n viaBotId?: number;\n threadInfo?: ApiThreadInfo;\n adminTitle?: string;\n isScheduled?: boolean;\n shouldHideKeyboardButtons?: boolean;\n isFromScheduled?: boolean;\n}\n\nexport interface ApiThreadInfo {\n threadId: number;\n chatId: number;\n topMessageId?: number;\n originChannelId?: number;\n messagesCount: number;\n lastMessageId?: number;\n lastReadInboxMessageId?: number;\n recentReplierIds?: number[];\n}\n\nexport type ApiMessageOutgoingStatus = 'read' | 'succeeded' | 'pending' | 'failed';\n\nexport interface ApiKeyboardButton {\n type: 'command' | 'url' | 'callback' | 'requestPoll' | 'buy' | 'NOT_SUPPORTED';\n text: string;\n messageId: number;\n value?: string;\n}\n\nexport type ApiKeyboardButtons = ApiKeyboardButton[][];\nexport type ApiReplyKeyboard = {\n keyboardPlaceholder?: string;\n isKeyboardSingleUse?: boolean;\n} & {\n [K in 'inlineButtons' | 'keyboardButtons']?: ApiKeyboardButtons;\n};\n\nexport type ApiMessageSearchType = 'text' | 'media' | 'documents' | 'links' | 'audio' | 'profilePhoto';\nexport type ApiGlobalMessageSearchType = 'text' | 'media' | 'documents' | 'links' | 'audio' | 'voice';\n\nexport type ApiReportReason = 'spam' | 'violence' | 'pornography' | 'childAbuse'\n| 'copyright' | 'geoIrrelevant' | 'fake' | 'other';\n\nexport const MAIN_THREAD_ID = -1;\n\n// `Symbol` can not be transferred from worker\nexport const MESSAGE_DELETED = 'MESSAGE_DELETED';\n","// We cache avatars as Data URI for faster initial load\n// and messages media as Blob for smaller size.\n\nexport enum ApiMediaFormat {\n DataUri,\n BlobUrl,\n Lottie,\n Progressive,\n Stream,\n}\n\nexport type ApiParsedMedia = string | Blob | AnyLiteral | ArrayBuffer;\nexport type ApiPreparedMedia = string | AnyLiteral;\nexport type ApiMediaFormatToPrepared<T> = T extends ApiMediaFormat.Lottie ? AnyLiteral : string;\n","import React, { FC } from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../../global/types';\nimport { ApiChat, ApiUser } from '../../../api/types';\n\nimport { pick } from '../../../util/iteratees';\nimport { selectUser } from '../../../modules/selectors';\n\ntype OwnProps = {\n userId?: number;\n username?: string;\n children: any;\n};\n\ntype StateProps = {\n userOrChat?: ApiUser | ApiChat;\n};\n\ntype DispatchProps = Pick<GlobalActions, 'openChat' | 'openChatByUsername'>;\n\nconst MentionLink: FC<OwnProps & StateProps & DispatchProps> = ({\n username,\n userOrChat,\n children,\n openChat,\n openChatByUsername,\n}) => {\n const handleClick = () => {\n if (userOrChat) {\n openChat({ id: userOrChat.id });\n } else if (username) {\n openChatByUsername({ username: username.substring(1) });\n }\n };\n\n return (\n <a onClick={handleClick} className=\"text-entity-link\" dir=\"auto\">\n {children}\n </a>\n );\n};\n\nexport default withGlobal<OwnProps>(\n (global, { userId }): StateProps => {\n return {\n userOrChat: userId ? selectUser(global, userId) : undefined,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, ['openChat', 'openChatByUsername']),\n)(MentionLink);\n","import { DEBUG } from '../config';\n\nexport function updateAppBadge(unreadCount: number) {\n if (typeof window.navigator.setAppBadge !== 'function') {\n return;\n }\n\n window.navigator.setAppBadge(unreadCount).catch((err) => {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error(err);\n }\n });\n}\n","import { RefObject } from 'react';\nimport { useEffect } from '../lib/teact/teact';\n\nconst BACKDROP_CLASSNAME = 'backdrop';\n\n// This effect implements closing menus by clicking outside of them\n// without adding extra elements to the DOM\nexport default function useVirtualBackdrop(\n isOpen: boolean,\n menuRef: RefObject<HTMLElement>,\n onClose?: () => void | undefined,\n) {\n useEffect(() => {\n const handleEvent = (e: Event) => {\n const menu = menuRef.current;\n const target = e.target as HTMLElement | null;\n if (!menu || !target) {\n return;\n }\n\n if (\n !menu.contains(e.target as Node | null)\n || target.classList.contains(BACKDROP_CLASSNAME)\n ) {\n e.preventDefault();\n e.stopPropagation();\n if (onClose) {\n onClose();\n }\n }\n };\n\n if (isOpen && onClose) {\n document.addEventListener('mousedown', handleEvent);\n }\n\n return () => {\n document.removeEventListener('mousedown', handleEvent);\n };\n }, [isOpen, menuRef, onClose]);\n}\n","module.exports = function() {\n return new Worker(__webpack_public_path__ + \"4429a4020960ac5c6282.worker.js\");\n};","module.exports = function() {\n return new Worker(__webpack_public_path__ + \"5054ce745024de60a724.worker.js\");\n};","module.exports = function() {\n return new Worker(__webpack_public_path__ + \"695e66b225ec96107343.worker.js\");\n};","module.exports = function() {\n return new Worker(__webpack_public_path__ + \"4c9029ba18603b924ede.worker.js\");\n};","import { addReducer, getGlobal, setGlobal } from '../../../lib/teact/teactn';\n\nimport { ANIMATION_LEVEL_MAX } from '../../../config';\nimport {\n IS_ANDROID, IS_IOS, IS_MAC_OS, IS_SAFARI, IS_TOUCH_ENV,\n} from '../../../util/environment';\nimport { setLanguage } from '../../../util/langProvider';\nimport switchTheme from '../../../util/switchTheme';\nimport { selectTheme } from '../../selectors';\nimport { startWebsync } from '../../../util/websync';\n\nconst HISTORY_ANIMATION_DURATION = 450;\n\nsubscribeToSystemThemeChange();\n\naddReducer('init', (global) => {\n const { animationLevel, messageTextSize, language } = global.settings.byKey;\n const theme = selectTheme(global);\n\n setLanguage(language, undefined, true);\n\n document.documentElement.style.setProperty(\n '--composer-text-size', `${Math.max(messageTextSize, IS_IOS ? 16 : 15)}px`,\n );\n document.documentElement.style.setProperty('--message-meta-height', `${Math.floor(messageTextSize * 1.3125)}px`);\n document.documentElement.style.setProperty('--message-text-size', `${messageTextSize}px`);\n document.documentElement.setAttribute('data-message-text-size', messageTextSize.toString());\n document.body.classList.add('initial');\n document.body.classList.add(`animation-level-${animationLevel}`);\n document.body.classList.add(IS_TOUCH_ENV ? 'is-touch-env' : 'is-pointer-env');\n switchTheme(theme, animationLevel === ANIMATION_LEVEL_MAX);\n startWebsync();\n\n if (IS_SAFARI) {\n document.body.classList.add('is-safari');\n }\n if (IS_IOS) {\n document.body.classList.add('is-ios');\n } else if (IS_ANDROID) {\n document.body.classList.add('is-android');\n } else if (IS_MAC_OS) {\n document.body.classList.add('is-macos');\n }\n});\n\naddReducer('setIsUiReady', (global, actions, payload) => {\n const { uiReadyState } = payload!;\n\n if (uiReadyState === 2) {\n document.body.classList.remove('initial');\n }\n\n return {\n ...global,\n uiReadyState,\n };\n});\n\naddReducer('setAuthPhoneNumber', (global, actions, payload) => {\n const { phoneNumber } = payload!;\n\n return {\n ...global,\n authPhoneNumber: phoneNumber,\n };\n});\n\naddReducer('setAuthRememberMe', (global, actions, payload) => {\n return {\n ...global,\n authRememberMe: Boolean(payload),\n };\n});\n\naddReducer('clearAuthError', (global) => {\n return {\n ...global,\n authError: undefined,\n };\n});\n\naddReducer('disableHistoryAnimations', () => {\n setTimeout(() => {\n setGlobal({\n ...getGlobal(),\n shouldSkipHistoryAnimations: false,\n });\n document.body.classList.remove('no-animate');\n }, HISTORY_ANIMATION_DURATION);\n\n setGlobal({\n ...getGlobal(),\n shouldSkipHistoryAnimations: true,\n }, true);\n});\n\nfunction subscribeToSystemThemeChange() {\n function handleSystemThemeChange() {\n const currentThemeMatch = document.documentElement.className.match(/theme-(\\w+)/);\n const currentTheme = currentThemeMatch ? currentThemeMatch[1] : 'light';\n const global = getGlobal();\n const nextTheme = selectTheme(global);\n const { animationLevel } = global.settings.byKey;\n\n if (nextTheme !== currentTheme) {\n switchTheme(nextTheme, animationLevel === ANIMATION_LEVEL_MAX);\n // Force-update component containers\n setGlobal({ ...global });\n }\n }\n\n const mql = window.matchMedia('(prefers-color-scheme: dark)');\n if (typeof mql.addEventListener === 'function') {\n mql.addEventListener('change', handleSystemThemeChange);\n } else if (typeof mql.addListener === 'function') {\n mql.addListener(handleSystemThemeChange);\n }\n}\n","import { addReducer } from '../../../lib/teact/teactn';\nimport { ISettings, IThemeSettings, ThemeKey } from '../../../types';\nimport { replaceSettings, replaceThemeSettings } from '../../reducers';\n\naddReducer('setSettingOption', (global, actions, payload?: Partial<ISettings>) => {\n return replaceSettings(global, payload);\n});\n\naddReducer('setThemeSettings', (global, actions, payload: { theme: ThemeKey } & Partial<IThemeSettings>) => {\n const { theme, ...settings } = payload;\n\n return replaceThemeSettings(global, theme, settings);\n});\n","import {\n addReducer, getDispatch, getGlobal, setGlobal,\n} from '../../../lib/teact/teactn';\n\nimport { initApi, callApi } from '../../../api/gramjs';\nimport { GlobalState } from '../../../global/types';\n\nimport {\n LANG_CACHE_NAME,\n CUSTOM_BG_CACHE_NAME,\n MEDIA_CACHE_NAME,\n MEDIA_CACHE_NAME_AVATARS,\n MEDIA_PROGRESSIVE_CACHE_NAME,\n IS_TEST,\n} from '../../../config';\nimport { PLATFORM_ENV } from '../../../util/environment';\nimport { unsubscribe } from '../../../util/notifications';\nimport * as cacheApi from '../../../util/cacheApi';\nimport { updateAppBadge } from '../../../util/appBadge';\nimport {\n storeSession,\n loadStoredSession,\n clearStoredSession,\n importLegacySession,\n clearLegacySessions,\n} from '../../../util/sessions';\nimport { forceWebsync } from '../../../util/websync';\n\naddReducer('initApi', (global: GlobalState, actions) => {\n (async () => {\n if (!IS_TEST) {\n await importLegacySession();\n void clearLegacySessions();\n }\n\n void initApi(actions.apiUpdate, {\n userAgent: navigator.userAgent,\n platform: PLATFORM_ENV,\n sessionData: loadStoredSession(),\n });\n })();\n});\n\naddReducer('setAuthPhoneNumber', (global, actions, payload) => {\n const { phoneNumber } = payload!;\n\n void callApi('provideAuthPhoneNumber', phoneNumber.replace(/[^\\d]/g, ''));\n\n return {\n ...global,\n authIsLoading: true,\n authError: undefined,\n };\n});\n\naddReducer('setAuthCode', (global, actions, payload) => {\n const { code } = payload!;\n\n void callApi('provideAuthCode', code);\n\n return {\n ...global,\n authIsLoading: true,\n authError: undefined,\n };\n});\n\naddReducer('setAuthPassword', (global, actions, payload) => {\n const { password } = payload!;\n\n void callApi('provideAuthPassword', password);\n\n return {\n ...global,\n authIsLoading: true,\n authError: undefined,\n };\n});\n\naddReducer('uploadProfilePhoto', (global, actions, payload) => {\n const { file } = payload!;\n\n void callApi('uploadProfilePhoto', file);\n});\n\naddReducer('signUp', (global, actions, payload) => {\n const { firstName, lastName } = payload!;\n\n void callApi('provideAuthRegistration', { firstName, lastName });\n\n return {\n ...global,\n authIsLoading: true,\n authError: undefined,\n };\n});\n\naddReducer('returnToAuthPhoneNumber', (global) => {\n void callApi('restartAuth');\n\n return {\n ...global,\n authError: undefined,\n };\n});\n\naddReducer('goToAuthQrCode', (global) => {\n void callApi('restartAuthWithQr');\n\n return {\n ...global,\n authIsLoadingQrCode: true,\n authError: undefined,\n };\n});\n\naddReducer('saveSession', (global, actions, payload) => {\n const { sessionData } = payload;\n\n if (sessionData) {\n storeSession(payload.sessionData, global.currentUserId);\n } else {\n clearStoredSession();\n }\n});\n\naddReducer('signOut', () => {\n (async () => {\n try {\n await unsubscribe();\n await callApi('destroy');\n await forceWebsync(false);\n } catch (err) {\n // Do nothing\n }\n\n getDispatch().reset();\n })();\n});\n\naddReducer('reset', () => {\n clearStoredSession();\n\n void cacheApi.clear(MEDIA_CACHE_NAME);\n void cacheApi.clear(MEDIA_CACHE_NAME_AVATARS);\n void cacheApi.clear(MEDIA_PROGRESSIVE_CACHE_NAME);\n void cacheApi.clear(CUSTOM_BG_CACHE_NAME);\n\n const langCachePrefix = LANG_CACHE_NAME.replace(/\\d+$/, '');\n const langCacheVersion = (LANG_CACHE_NAME.match(/\\d+$/) || [0])[0];\n for (let i = 0; i < langCacheVersion; i++) {\n void cacheApi.clear(`${langCachePrefix}${i === 0 ? '' : i}`);\n }\n\n void clearLegacySessions();\n\n updateAppBadge(0);\n\n getDispatch().init();\n});\n\naddReducer('disconnect', () => {\n (async () => {\n await callApi('disconnect');\n })();\n});\n\naddReducer('loadNearestCountry', (global) => {\n if (global.connectionState !== 'connectionStateReady') {\n return;\n }\n\n (async () => {\n const authNearestCountry = await callApi('fetchNearestCountry');\n\n setGlobal({\n ...getGlobal(),\n authNearestCountry,\n });\n })();\n});\n\naddReducer('setDeviceToken', (global, actions, deviceToken) => {\n setGlobal({\n ...global,\n push: {\n deviceToken,\n subscribedAt: Date.now(),\n },\n });\n});\n\naddReducer('deleteDeviceToken', (global) => {\n const newGlobal = { ...global };\n delete newGlobal.push;\n setGlobal(newGlobal);\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 { subscribe, unsubscribe } from '../../../util/notifications';\nimport { selectUser } from '../../selectors';\nimport {\n addUsers, addBlockedContact, updateChats, updateUser, removeBlockedContact, replaceSettings, updateNotifySettings,\n addNotifyExceptions,\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, accessHash } = payload!;\n\n (async () => {\n const result = await callApi('blockContact', contactId, accessHash);\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', (global) => {\n const { serverTimeOffset } = global;\n\n (async () => {\n const result = await callApi('fetchNotificationExceptions', { serverTimeOffset });\n if (!result) {\n return;\n }\n\n setGlobal(addNotifyExceptions(getGlobal(), result));\n })();\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('updateWebNotificationSettings', (global, actions, payload) => {\n (async () => {\n setGlobal(replaceSettings(getGlobal(), payload));\n const newGlobal = getGlobal();\n const { hasPushNotifications, hasWebNotifications } = newGlobal.settings.byKey;\n if (hasWebNotifications && hasPushNotifications) {\n await subscribe();\n } else {\n await unsubscribe();\n }\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 {\n addReducer, getDispatch, getGlobal, setGlobal,\n} from '../../../lib/teact/teactn';\n\nimport { GlobalState } from '../../../global/types';\n\nimport {\n ApiUpdate,\n ApiUpdateAuthorizationState,\n ApiUpdateAuthorizationError,\n ApiUpdateConnectionState,\n ApiUpdateSession,\n ApiUpdateCurrentUser, ApiUpdateServerTimeOffset,\n} from '../../../api/types';\nimport { DEBUG, SESSION_USER_KEY } from '../../../config';\nimport { subscribe } from '../../../util/notifications';\nimport { updateUser } from '../../reducers';\nimport { setLanguage } from '../../../util/langProvider';\nimport { selectNotifySettings } from '../../selectors';\nimport { forceWebsync } from '../../../util/websync';\n\naddReducer('apiUpdate', (global, actions, update: ApiUpdate) => {\n if (DEBUG) {\n if (update['@type'] !== 'updateUserStatus' && update['@type'] !== 'updateServerTimeOffset') {\n // eslint-disable-next-line no-console\n console.log('[GramJs] UPDATE', update['@type'], { update });\n }\n }\n\n switch (update['@type']) {\n case 'updateApiReady':\n onUpdateApiReady(global);\n break;\n\n case 'updateAuthorizationState':\n onUpdateAuthorizationState(update);\n break;\n\n case 'updateAuthorizationError':\n onUpdateAuthorizationError(update);\n break;\n\n case 'updateConnectionState':\n onUpdateConnectionState(update);\n break;\n\n case 'updateSession':\n onUpdateSession(update);\n break;\n\n case 'updateServerTimeOffset':\n onUpdateServerTimeOffset(update);\n break;\n\n case 'updateCurrentUser':\n onUpdateCurrentUser(update);\n break;\n\n case 'error':\n if (update.error.message === 'SESSION_REVOKED') {\n actions.signOut();\n }\n\n if (actions.showDialog) {\n actions.showDialog({ data: { ...update.error, hasErrorKey: true } });\n }\n\n break;\n }\n});\n\nfunction onUpdateApiReady(global: GlobalState) {\n const { hasWebNotifications, hasPushNotifications } = selectNotifySettings(global);\n if (hasWebNotifications && hasPushNotifications) subscribe();\n setLanguage(global.settings.byKey.language);\n}\n\nfunction onUpdateAuthorizationState(update: ApiUpdateAuthorizationState) {\n let global = getGlobal();\n\n const wasAuthReady = global.authState === 'authorizationStateReady';\n const authState = update.authorizationState;\n\n setGlobal({\n ...global,\n authState,\n authIsLoading: false,\n });\n\n global = getGlobal();\n\n switch (authState) {\n case 'authorizationStateLoggingOut':\n void forceWebsync(false);\n\n setGlobal({\n ...global,\n isLoggingOut: true,\n });\n break;\n case 'authorizationStateWaitCode':\n setGlobal({\n ...global,\n authIsCodeViaApp: update.isCodeViaApp,\n });\n break;\n case 'authorizationStateWaitPassword':\n setGlobal({\n ...global,\n authHint: update.hint,\n });\n break;\n case 'authorizationStateWaitQrCode':\n setGlobal({\n ...global,\n authIsLoadingQrCode: false,\n authQrCode: update.qrCode,\n });\n break;\n case 'authorizationStateReady': {\n if (wasAuthReady) {\n break;\n }\n\n void forceWebsync(true);\n\n setGlobal({\n ...global,\n isLoggingOut: false,\n lastSyncTime: Date.now(),\n });\n\n break;\n }\n }\n}\n\nfunction onUpdateAuthorizationError(update: ApiUpdateAuthorizationError) {\n setGlobal({\n ...getGlobal(),\n authError: update.message,\n });\n}\n\nfunction onUpdateConnectionState(update: ApiUpdateConnectionState) {\n const { connectionState } = update;\n const global = getGlobal();\n\n setGlobal({\n ...global,\n connectionState,\n });\n\n if (connectionState === 'connectionStateReady' && global.authState === 'authorizationStateReady') {\n getDispatch().sync();\n } else if (connectionState === 'connectionStateBroken') {\n getDispatch().signOut();\n }\n}\n\nfunction onUpdateSession(update: ApiUpdateSession) {\n const { sessionData } = update;\n const { authRememberMe, authState } = getGlobal();\n const isEmpty = !sessionData || !sessionData.mainDcId;\n\n if (!authRememberMe || authState !== 'authorizationStateReady' || isEmpty) {\n return;\n }\n\n getDispatch().saveSession({ sessionData });\n}\n\nfunction onUpdateServerTimeOffset(update: ApiUpdateServerTimeOffset) {\n const global = getGlobal();\n\n if (global.serverTimeOffset === update.serverTimeOffset) {\n return;\n }\n\n setGlobal({\n ...global,\n serverTimeOffset: update.serverTimeOffset,\n });\n}\n\nfunction onUpdateCurrentUser(update: ApiUpdateCurrentUser) {\n const { currentUser } = update;\n\n setGlobal({\n ...updateUser(getGlobal(), currentUser.id, currentUser),\n currentUserId: currentUser.id,\n });\n\n updateSessionUserId(currentUser.id);\n}\n\nfunction updateSessionUserId(currentUserId: number) {\n const sessionUserAuth = localStorage.getItem(SESSION_USER_KEY);\n if (!sessionUserAuth) return;\n\n const userAuth = JSON.parse(sessionUserAuth);\n userAuth.id = currentUserId;\n\n localStorage.setItem(SESSION_USER_KEY, JSON.stringify(userAuth));\n}\n","export var ServiceWorkerNoSupportError = (function() {\n\n\tfunction ServiceWorkerNoSupportError() {\n\t\tvar err = Error.call(this, 'ServiceWorker is not supported.');\n\t\tObject.setPrototypeOf(err, ServiceWorkerNoSupportError.prototype);\n\t\treturn err;\n\t}\n\n\tServiceWorkerNoSupportError.prototype = Object.create(Error.prototype);\n\n\treturn ServiceWorkerNoSupportError;\n})();\n\nexport var scriptUrl = __webpack_public_path__ + \"serviceWorker.js\";\n\nexport default function registerServiceWorkerIfSupported(mapScriptUrlOrOptions, maybeOptions) {\n\n\tvar targetScriptUrl = scriptUrl;\n\tvar options = maybeOptions;\n\n\tif (typeof mapScriptUrlOrOptions === 'function') {\n\t\ttargetScriptUrl = mapScriptUrlOrOptions(targetScriptUrl);\n\t} else {\n\t\toptions = mapScriptUrlOrOptions;\n\t}\n\n\tif ('serviceWorker' in navigator) {\n\t\treturn navigator.serviceWorker.register(targetScriptUrl, options);\n\t}\n\n\treturn Promise.reject(new ServiceWorkerNoSupportError());\n}\n","import { scriptUrl } from 'service-worker-loader!../serviceWorker';\n\nimport { DEBUG } from '../config';\nimport { getDispatch } from '../lib/teact/teactn';\nimport { IS_ANDROID, IS_IOS, IS_SERVICE_WORKER_SUPPORTED } from './environment';\nimport { notifyClientReady, playNotificationSound } from './notifications';\n\ntype WorkerAction = {\n type: string;\n payload: Record<string, any>;\n};\n\nfunction handleWorkerMessage(e: MessageEvent) {\n const action: WorkerAction = e.data;\n if (!action.type) return;\n const dispatch = getDispatch();\n switch (action.type) {\n case 'focusMessage':\n if (dispatch.focusMessage) {\n dispatch.focusMessage(action.payload);\n }\n break;\n case 'playNotificationSound':\n playNotificationSound(action.payload.id);\n break;\n }\n}\n\nfunction subscribeToWorker() {\n navigator.serviceWorker.removeEventListener('message', handleWorkerMessage);\n navigator.serviceWorker.addEventListener('message', handleWorkerMessage);\n // Notify web worker that client is ready to receive messages\n notifyClientReady();\n}\n\nif (IS_SERVICE_WORKER_SUPPORTED) {\n window.addEventListener('load', async () => {\n try {\n await navigator.serviceWorker.register(scriptUrl);\n\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('[SW] ServiceWorker registered');\n }\n\n await navigator.serviceWorker.ready;\n\n if (navigator.serviceWorker.controller) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('[SW] ServiceWorker ready');\n }\n subscribeToWorker();\n } else {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error('[SW] ServiceWorker not available');\n }\n\n if (!IS_IOS && !IS_ANDROID) {\n getDispatch().showDialog({ data: { message: 'SERVICE_WORKER_DISABLED', hasErrorKey: true } });\n }\n }\n } catch (err) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error('[SW] ServiceWorker registration failed: ', err);\n }\n }\n });\n window.addEventListener('focus', async () => {\n await navigator.serviceWorker.ready;\n subscribeToWorker();\n });\n}\n","import { GlobalState } from './types';\nimport { NewChatMembersProgress } from '../types';\n\nimport {\n ANIMATION_LEVEL_DEFAULT, DARK_THEME_PATTERN_COLOR, DEFAULT_MESSAGE_TEXT_SIZE_PX, DEFAULT_PATTERN_COLOR,\n IOS_DEFAULT_MESSAGE_TEXT_SIZE_PX, MACOS_DEFAULT_MESSAGE_TEXT_SIZE_PX,\n} from '../config';\nimport { IS_IOS, IS_MAC_OS } from '../util/environment';\n\nexport const INITIAL_STATE: GlobalState = {\n isLeftColumnShown: true,\n isChatInfoShown: false,\n newChatMembersProgress: NewChatMembersProgress.Closed,\n uiReadyState: 0,\n serverTimeOffset: 0,\n\n authRememberMe: true,\n\n blocked: {\n ids: [],\n totalCount: 0,\n },\n\n users: {\n byId: {},\n },\n\n chats: {\n listIds: {},\n isFullyLoaded: {},\n orderedPinnedIds: {},\n totalCount: {},\n byId: {},\n },\n\n messages: {\n byChatId: {},\n messageLists: [],\n },\n\n scheduledMessages: {\n byChatId: {},\n },\n\n chatFolders: {\n byId: {},\n activeChatFolder: 0,\n },\n\n fileUploads: {\n byMessageLocalId: {},\n },\n\n recentEmojis: ['grinning', 'kissing_heart', 'christmas_tree', 'brain', 'trophy'],\n\n stickers: {\n setsById: {},\n added: {},\n recent: {\n stickers: [],\n },\n favorite: {\n stickers: [],\n },\n greeting: {\n stickers: [],\n },\n featured: {\n setIds: [],\n },\n search: {},\n forEmoji: {},\n },\n\n emojiKeywords: {},\n\n gifs: {\n saved: {},\n search: {},\n },\n\n inlineBots: {\n isLoading: false,\n byUsername: {},\n },\n\n globalSearch: {},\n\n userSearch: {},\n\n localTextSearch: {\n byChatThreadKey: {},\n },\n\n localMediaSearch: {\n byChatId: {},\n },\n\n management: {\n byChatId: {},\n },\n\n topPeers: {},\n\n topInlineBots: {},\n\n mediaViewer: {},\n\n audioPlayer: {},\n\n forwardMessages: {},\n\n pollResults: {},\n\n payment: {},\n\n notifications: [],\n\n dialogs: [],\n\n activeSessions: [],\n\n settings: {\n byKey: {\n theme: 'light',\n shouldUseSystemTheme: true,\n messageTextSize: IS_IOS\n ? IOS_DEFAULT_MESSAGE_TEXT_SIZE_PX\n : (IS_MAC_OS ? MACOS_DEFAULT_MESSAGE_TEXT_SIZE_PX : DEFAULT_MESSAGE_TEXT_SIZE_PX),\n animationLevel: ANIMATION_LEVEL_DEFAULT,\n messageSendKeyCombo: 'enter',\n shouldAutoDownloadMediaFromContacts: true,\n shouldAutoDownloadMediaInPrivateChats: true,\n shouldAutoDownloadMediaInGroups: true,\n shouldAutoDownloadMediaInChannels: true,\n hasWebNotifications: true,\n hasPushNotifications: true,\n notificationSoundVolume: 5,\n shouldAutoPlayGifs: true,\n shouldAutoPlayVideos: true,\n shouldSuggestStickers: true,\n shouldLoopStickers: true,\n language: 'en',\n },\n themes: {\n light: {\n isBlurred: true,\n patternColor: DEFAULT_PATTERN_COLOR,\n },\n dark: {\n isBlurred: true,\n patternColor: DARK_THEME_PATTERN_COLOR,\n },\n },\n privacy: {},\n notifyExceptions: {},\n },\n\n twoFaSettings: {},\n\n shouldShowContextMenuHint: true,\n};\n","import {\n addCallback, addReducer, getGlobal, removeCallback,\n} from '../lib/teact/teactn';\n\nimport { GlobalState } from './types';\nimport { MAIN_THREAD_ID } from '../api/types';\n\nimport { onBeforeUnload, onIdle, throttle } from '../util/schedulers';\nimport {\n DEBUG,\n GLOBAL_STATE_CACHE_DISABLED,\n GLOBAL_STATE_CACHE_KEY,\n GLOBAL_STATE_CACHE_CHAT_LIST_LIMIT,\n MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN,\n GLOBAL_STATE_CACHE_USER_LIST_LIMIT,\n} from '../config';\nimport { IS_SINGLE_COLUMN_LAYOUT } from '../util/environment';\nimport { ANIMATION_END_EVENT, ANIMATION_START_EVENT } from '../hooks/useHeavyAnimationCheck';\nimport { pick } from '../util/iteratees';\nimport { selectCurrentMessageList } from '../modules/selectors';\nimport { hasStoredSession } from '../util/sessions';\nimport { INITIAL_STATE } from './initial';\n\nconst UPDATE_THROTTLE = 5000;\n\nconst updateCacheThrottled = throttle(() => onIdle(updateCache), UPDATE_THROTTLE, false);\n\nlet isCaching = false;\nlet isHeavyAnimating = false;\nlet unsubscribeFromBeforeUnload: NoneToVoidFunction | undefined;\n\nsetupHeavyAnimationListeners();\n\nexport function initCache() {\n if (GLOBAL_STATE_CACHE_DISABLED) {\n return;\n }\n\n addReducer('saveSession', () => {\n if (isCaching) {\n return;\n }\n\n setupCaching();\n });\n\n addReducer('reset', () => {\n localStorage.removeItem(GLOBAL_STATE_CACHE_KEY);\n\n if (!isCaching) {\n return;\n }\n\n clearCaching();\n });\n}\n\nexport function loadCache(initialState: GlobalState) {\n if (GLOBAL_STATE_CACHE_DISABLED) {\n return undefined;\n }\n\n if (hasStoredSession(true)) {\n setupCaching();\n\n return readCache(initialState);\n } else {\n clearCaching();\n\n return undefined;\n }\n}\n\nfunction setupCaching() {\n isCaching = true;\n unsubscribeFromBeforeUnload = onBeforeUnload(updateCache, true);\n window.addEventListener('blur', updateCache);\n addCallback(updateCacheThrottled);\n}\n\nfunction clearCaching() {\n isCaching = false;\n removeCallback(updateCacheThrottled);\n window.removeEventListener('blur', updateCache);\n if (unsubscribeFromBeforeUnload) {\n unsubscribeFromBeforeUnload();\n }\n}\n\nfunction readCache(initialState: GlobalState) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.time('global-state-cache-read');\n }\n\n const json = localStorage.getItem(GLOBAL_STATE_CACHE_KEY);\n const cached = json ? JSON.parse(json) as GlobalState : undefined;\n\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.timeEnd('global-state-cache-read');\n }\n\n if (cached) {\n // Pre-fill defaults in nested objects which may be missing in older cache\n cached.settings.byKey = {\n ...initialState.settings.byKey,\n ...cached.settings.byKey,\n };\n cached.settings.themes = {\n ...initialState.settings.themes,\n ...cached.settings.themes,\n };\n cached.chatFolders = {\n ...initialState.chatFolders,\n ...cached.chatFolders,\n };\n\n if (!cached.messages.messageLists) {\n cached.messages.messageLists = initialState.messages.messageLists;\n }\n\n if (!cached.stickers.greeting) {\n cached.stickers.greeting = initialState.stickers.greeting;\n }\n }\n\n return {\n ...initialState,\n ...cached,\n };\n}\n\nfunction updateCache() {\n if (!isCaching || isHeavyAnimating) {\n return;\n }\n\n const global = getGlobal();\n\n if (global.isLoggingOut) {\n return;\n }\n\n const reducedGlobal: GlobalState = {\n ...INITIAL_STATE,\n ...pick(global, [\n 'authState',\n 'authPhoneNumber',\n 'authRememberMe',\n 'authNearestCountry',\n 'currentUserId',\n 'contactList',\n 'topPeers',\n 'topInlineBots',\n 'recentEmojis',\n 'push',\n 'shouldShowContextMenuHint',\n ]),\n isChatInfoShown: reduceShowChatInfo(global),\n users: reduceUsers(global),\n chats: reduceChats(global),\n messages: reduceMessages(global),\n globalSearch: {\n recentlyFoundChatIds: global.globalSearch.recentlyFoundChatIds,\n },\n settings: reduceSettings(global),\n chatFolders: reduceChatFolders(global),\n };\n\n const json = JSON.stringify(reducedGlobal);\n localStorage.setItem(GLOBAL_STATE_CACHE_KEY, json);\n}\n\nfunction reduceShowChatInfo(global: GlobalState): boolean {\n return window.innerWidth > MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN\n ? global.isChatInfoShown\n : false;\n}\n\nfunction reduceUsers(global: GlobalState): GlobalState['users'] {\n const { users: { byId, selectedId } } = global;\n const idsToSave = [\n ...(global.chats.listIds.active || []).slice(0, GLOBAL_STATE_CACHE_CHAT_LIST_LIMIT).filter((cid) => cid > 0),\n ...Object.keys(byId),\n ].slice(0, GLOBAL_STATE_CACHE_USER_LIST_LIMIT);\n\n return {\n byId: pick(byId, idsToSave as number[]),\n selectedId: window.innerWidth > MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN ? selectedId : undefined,\n };\n}\n\nfunction reduceChats(global: GlobalState): GlobalState['chats'] {\n const chatIdsToSave = [\n ...(global.chats.listIds.active || []).slice(0, GLOBAL_STATE_CACHE_CHAT_LIST_LIMIT),\n ];\n const { chatId: currentChatId } = selectCurrentMessageList(global) || {};\n\n return {\n ...global.chats,\n byId: pick(global.chats.byId, currentChatId ? [...chatIdsToSave, currentChatId] : chatIdsToSave),\n listIds: {\n active: chatIdsToSave,\n },\n isFullyLoaded: {},\n orderedPinnedIds: {\n active: global.chats.orderedPinnedIds.active,\n },\n };\n}\n\nfunction reduceMessages(global: GlobalState): GlobalState['messages'] {\n const byChatId: GlobalState['messages']['byChatId'] = {};\n const { chatId: currentChatId } = selectCurrentMessageList(global) || {};\n\n const chatIdsToSave = [\n ...(global.chats.listIds.active || []).slice(0, GLOBAL_STATE_CACHE_CHAT_LIST_LIMIT),\n ...(currentChatId ? [currentChatId] : []),\n ];\n chatIdsToSave.forEach((chatId) => {\n const current = global.messages.byChatId[chatId];\n if (!current) {\n return;\n }\n\n const mainThread = current.threadsById[MAIN_THREAD_ID];\n if (!mainThread || !mainThread.viewportIds) {\n return;\n }\n\n byChatId[chatId] = {\n byId: pick(current.byId, mainThread.viewportIds),\n threadsById: {\n [MAIN_THREAD_ID]: mainThread,\n },\n };\n });\n\n const currentMessageList = selectCurrentMessageList(global);\n\n return {\n byChatId,\n messageLists: !currentMessageList || IS_SINGLE_COLUMN_LAYOUT ? [] : [{\n ...currentMessageList,\n threadId: MAIN_THREAD_ID,\n type: 'thread',\n }],\n };\n}\n\nfunction reduceSettings(global: GlobalState): GlobalState['settings'] {\n const { byKey, themes } = global.settings;\n\n return {\n byKey,\n themes,\n privacy: {},\n notifyExceptions: {},\n };\n}\n\nfunction reduceChatFolders(global: GlobalState): GlobalState['chatFolders'] {\n return {\n ...global.chatFolders,\n activeChatFolder: 0,\n };\n}\n\nfunction setupHeavyAnimationListeners() {\n document.addEventListener(ANIMATION_START_EVENT, () => {\n isHeavyAnimating = true;\n });\n document.addEventListener(ANIMATION_END_EVENT, () => {\n isHeavyAnimating = false;\n });\n}\n","import { addReducer } from '../lib/teact/teactn';\n\nimport { INITIAL_STATE } from './initial';\nimport { initCache, loadCache } from './cache';\nimport { cloneDeep } from '../util/iteratees';\n\ninitCache();\n\naddReducer('init', () => {\n const initial = cloneDeep(INITIAL_STATE);\n return loadCache(initial) || initial;\n});\n","const STORAGE_KEY = 'tt-active-tab';\nconst INTERVAL = 2000;\n\nconst tabKey = String(Date.now() + Math.random());\n\nlocalStorage.setItem(STORAGE_KEY, tabKey);\n\nlet callback: NoneToVoidFunction;\n\nconst interval = window.setInterval(() => {\n if (callback && localStorage.getItem(STORAGE_KEY) !== tabKey) {\n callback();\n clearInterval(interval);\n }\n}, INTERVAL);\n\nexport function addActiveTabChangeListener(_callback: NoneToVoidFunction) {\n callback = _callback;\n}\n","const SITE_FONTS = ['400 1em Roboto', '500 1em Roboto'];\n\nexport default function preloadFonts() {\n if ('fonts' in document) {\n return Promise.all(SITE_FONTS.map((font) => document.fonts.load(font)));\n }\n\n return undefined;\n}\n","export default __webpack_public_path__ + \"telegram-logo.df3a91becaa9678c529b4c4cadd45204.svg\";","export default __webpack_public_path__ + \"monkey.a3d5fcdc50b18dc55695f7dd4101a8c9.svg\";","import React, { FC, useEffect } from '../../lib/teact/teact';\nimport { getGlobal, withGlobal } from '../../lib/teact/teactn';\n\nimport { ApiMediaFormat } from '../../api/types';\nimport { GlobalActions, GlobalState } from '../../global/types';\n\nimport { getChatAvatarHash } from '../../modules/helpers/chats'; // Direct import for better module splitting\nimport useFlag from '../../hooks/useFlag';\nimport useShowTransition from '../../hooks/useShowTransition';\nimport { pause } from '../../util/schedulers';\nimport { preloadImage } from '../../util/files';\nimport preloadFonts from '../../util/fonts';\nimport * as mediaLoader from '../../util/mediaLoader';\nimport { Bundles, loadModule } from '../../util/moduleLoader';\nimport { pick } from '../../util/iteratees';\nimport buildClassName from '../../util/buildClassName';\n\nimport './UiLoader.scss';\n\n// @ts-ignore\nimport telegramLogoPath from '../../assets/telegram-logo.svg';\n// @ts-ignore\nimport monkeyPath from '../../assets/monkey.svg';\nimport { selectIsRightColumnShown, selectTheme } from '../../modules/selectors';\n\ntype OwnProps = {\n page: 'main' | 'authCode' | 'authPassword' | 'authPhoneNumber' | 'authQrCode';\n children: any;\n};\n\ntype StateProps = Pick<GlobalState, 'uiReadyState' | 'shouldSkipHistoryAnimations'> & {\n hasCustomBackground?: boolean;\n hasCustomBackgroundColor: boolean;\n isRightColumnShown?: boolean;\n};\n\ntype DispatchProps = Pick<GlobalActions, 'setIsUiReady'>;\n\nconst MAX_PRELOAD_DELAY = 700;\nconst SECOND_STATE_DELAY = 1000;\nconst AVATARS_TO_PRELOAD = 10;\n\nfunction preloadAvatars() {\n const { listIds, byId } = getGlobal().chats;\n if (!listIds.active) {\n return undefined;\n }\n\n return Promise.all(listIds.active.slice(0, AVATARS_TO_PRELOAD).map((chatId) => {\n const chat = byId[chatId];\n if (!chat) {\n return undefined;\n }\n\n const avatarHash = getChatAvatarHash(chat);\n if (!avatarHash) {\n return undefined;\n }\n\n return mediaLoader.fetch(avatarHash, ApiMediaFormat.DataUri);\n }));\n}\n\nconst preloadTasks = {\n main: () => Promise.all([\n loadModule(Bundles.Main, 'Main')\n .then(preloadFonts),\n preloadAvatars(),\n ]),\n authPhoneNumber: () => Promise.all([\n preloadFonts(),\n preloadImage(telegramLogoPath),\n ]),\n authCode: () => preloadImage(monkeyPath),\n authPassword: () => preloadImage(monkeyPath),\n authQrCode: preloadFonts,\n};\n\nconst UiLoader: FC<OwnProps & StateProps & DispatchProps> = ({\n page,\n children,\n hasCustomBackground,\n hasCustomBackgroundColor,\n isRightColumnShown,\n shouldSkipHistoryAnimations,\n setIsUiReady,\n}) => {\n const [isReady, markReady] = useFlag();\n const {\n shouldRender: shouldRenderMask, transitionClassNames,\n } = useShowTransition(!isReady, undefined, true);\n\n useEffect(() => {\n let timeout: number | undefined;\n\n const safePreload = async () => {\n try {\n await preloadTasks[page]();\n } catch (err) {\n // Do nothing\n }\n };\n\n Promise.race([\n pause(MAX_PRELOAD_DELAY),\n safePreload(),\n ]).then(() => {\n markReady();\n setIsUiReady({ uiReadyState: 1 });\n\n timeout = window.setTimeout(() => {\n setIsUiReady({ uiReadyState: 2 });\n }, SECOND_STATE_DELAY);\n });\n\n return () => {\n if (timeout) {\n clearTimeout(timeout);\n timeout = undefined;\n }\n\n setIsUiReady({ uiReadyState: 0 });\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n\n return (\n <div id=\"UiLoader\">\n {children}\n {shouldRenderMask && !shouldSkipHistoryAnimations && (\n <div className={buildClassName('mask', transitionClassNames)}>\n {page === 'main' ? (\n <>\n <div className=\"left\" />\n <div\n className={buildClassName(\n 'middle',\n hasCustomBackground && 'custom-bg-image',\n hasCustomBackgroundColor && 'custom-bg-color',\n isRightColumnShown && 'with-right-column',\n )}\n />\n {isRightColumnShown && <div className=\"right\" />}\n </>\n ) : (\n <div className=\"blank\" />\n )}\n </div>\n )}\n </div>\n );\n};\n\nexport default withGlobal<OwnProps>(\n (global): StateProps => {\n const theme = selectTheme(global);\n const { background, backgroundColor } = global.settings.themes[theme] || {};\n\n return {\n shouldSkipHistoryAnimations: global.shouldSkipHistoryAnimations,\n uiReadyState: global.uiReadyState,\n hasCustomBackground: Boolean(background),\n hasCustomBackgroundColor: Boolean(backgroundColor),\n isRightColumnShown: selectIsRightColumnShown(global),\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, ['setIsUiReady']),\n)(UiLoader);\n","import * as langProvider from '../util/langProvider';\nimport { useState } from '../lib/teact/teact';\n\nexport default (langCode: string | undefined, key: string): string | undefined => {\n const [translation, setTranslation] = useState<string>();\n\n if (langCode) {\n langProvider\n .getTranslationForLangString(langCode, key)\n .then(setTranslation);\n }\n\n return translation;\n};\n","export function getSuggestedLanguage() {\n let suggestedLanguage = navigator.language;\n\n if (suggestedLanguage && suggestedLanguage !== 'pt-br') {\n suggestedLanguage = suggestedLanguage.substr(0, 2);\n }\n\n return suggestedLanguage;\n}\n","import React, {\n FC, useState, memo, useCallback, useRef,\n} from '../../lib/teact/teact';\n\nimport { ANIMATION_END_DELAY } from '../../config';\nimport { countryList } from '../../util/phoneNumber';\nimport searchWords from '../../util/searchWords';\nimport buildClassName from '../../util/buildClassName';\nimport renderText from '../common/helpers/renderText';\nimport useLang from '../../hooks/useLang';\n\nimport DropdownMenu from '../ui/DropdownMenu';\nimport MenuItem from '../ui/MenuItem';\nimport Spinner from '../ui/Spinner';\n\nimport './CountryCodeInput.scss';\n\ntype OwnProps = {\n id: string;\n value?: Country;\n isLoading?: boolean;\n onChange: (value: Country) => void;\n};\n\nconst MENU_HIDING_DURATION = 200 + ANIMATION_END_DELAY;\nconst SELECT_TIMEOUT = 50;\n\nconst CountryCodeInput: FC<OwnProps> = ({\n id,\n value,\n isLoading,\n onChange,\n}) => {\n const lang = useLang();\n // eslint-disable-next-line no-null/no-null\n const inputRef = useRef<HTMLInputElement>(null);\n\n const [filter, setFilter] = useState<string | undefined>();\n const [filteredList, setFilteredList] = useState(countryList);\n\n function updateFilter(filterValue?: string) {\n setFilter(filterValue);\n setFilteredList(getFilteredList(filterValue));\n }\n\n const handleChange = useCallback((e: React.SyntheticEvent<HTMLElement>) => {\n const { countryId } = (e.currentTarget.firstElementChild as HTMLDivElement).dataset;\n const country = countryList.find((c) => c.id === countryId);\n\n if (country) {\n onChange(country);\n }\n\n setTimeout(() => updateFilter(undefined), MENU_HIDING_DURATION);\n }, [onChange]);\n\n const handleInput = useCallback((e: React.FormEvent<HTMLInputElement>) => {\n updateFilter(e.currentTarget.value);\n }, []);\n\n const handleInputKeyDown = useCallback((e: React.KeyboardEvent<HTMLInputElement>) => {\n if (e.keyCode !== 8) {\n return;\n }\n\n const target = e.currentTarget;\n if (value && filter === undefined) {\n target.value = '';\n }\n\n updateFilter(target.value);\n }, [filter, value]);\n\n const CodeInput: FC<{ onTrigger: () => void; isOpen?: boolean }> = ({ onTrigger, isOpen }) => {\n const handleTrigger = () => {\n if (isOpen) {\n return;\n }\n\n setTimeout(() => {\n inputRef.current!.select();\n }, SELECT_TIMEOUT);\n\n onTrigger();\n\n const formEl = document.getElementById('auth-phone-number-form')!;\n formEl.scrollTo({ top: formEl.scrollHeight, behavior: 'smooth' });\n };\n\n const inputValue = filter !== undefined\n ? filter\n : (value && value.name) || '';\n\n return (\n <div className={buildClassName('input-group', value && 'touched')}>\n <input\n ref={inputRef}\n className={buildClassName('form-control', isOpen && 'focus')}\n type=\"text\"\n id={id}\n value={inputValue}\n autoComplete=\"off\"\n onClick={handleTrigger}\n onFocus={handleTrigger}\n onInput={handleInput}\n onKeyDown={handleInputKeyDown}\n />\n <label>{lang('Login.SelectCountry.Title')}</label>\n {isLoading ? (\n <Spinner color=\"black\" />\n ) : (\n <i onClick={handleTrigger} className={buildClassName('css-icon-down', isOpen && 'open')} />\n )}\n </div>\n );\n };\n\n return (\n <DropdownMenu\n className=\"CountryCodeInput\"\n trigger={CodeInput}\n >\n {filteredList.map((country: Country) => (\n <MenuItem\n key={country.id}\n className={value && country.id === value.id ? 'selected' : ''}\n onClick={handleChange}\n >\n <span data-country-id={country.id} />\n <span className=\"country-flag\">{renderText(country.flag, ['hq_emoji'])}</span>\n <span className=\"country-name\">{country.name}</span>\n <span className=\"country-code\">{country.code}</span>\n </MenuItem>\n ))}\n {!filteredList.length && (\n <MenuItem\n key=\"no-results\"\n className=\"no-results\"\n disabled\n >\n <span>{lang('lng_country_none')}</span>\n </MenuItem>\n )}\n </DropdownMenu>\n );\n};\n\nfunction getFilteredList(filter = ''): Country[] {\n return filter.length\n ? countryList.filter((country) => searchWords(country.name, filter))\n : countryList;\n}\n\nexport default memo(CountryCodeInput);\n","import { ChangeEvent } from 'react';\n\n// @ts-ignore\nimport monkeyPath from '../../assets/monkey.svg';\n\nimport React, {\n FC, memo, useCallback, useEffect, useLayoutEffect, useRef, useState,\n} from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { GlobalActions, GlobalState } from '../../global/types';\nimport { LangCode } from '../../types';\n\nimport { IS_SAFARI, IS_TOUCH_ENV } from '../../util/environment';\nimport { preloadImage } from '../../util/files';\nimport preloadFonts from '../../util/fonts';\nimport { pick } from '../../util/iteratees';\nimport { formatPhoneNumber, getCountryById, getCountryFromPhoneNumber } from '../../util/phoneNumber';\nimport { setLanguage } from '../../util/langProvider';\nimport useLang from '../../hooks/useLang';\nimport useFlag from '../../hooks/useFlag';\nimport useLangString from '../../hooks/useLangString';\nimport { getSuggestedLanguage } from './helpers/getSuggestedLanguage';\n\nimport Button from '../ui/Button';\nimport Checkbox from '../ui/Checkbox';\nimport InputText from '../ui/InputText';\nimport Loading from '../ui/Loading';\nimport CountryCodeInput from './CountryCodeInput';\n\ntype StateProps = Pick<GlobalState, (\n 'connectionState' | 'authState' |\n 'authPhoneNumber' | 'authIsLoading' | 'authIsLoadingQrCode' | 'authError' | 'authRememberMe' | 'authNearestCountry'\n)> & {\n language?: LangCode;\n};\ntype DispatchProps = Pick<GlobalActions, (\n 'setAuthPhoneNumber' | 'setAuthRememberMe' | 'loadNearestCountry' | 'clearAuthError' | 'goToAuthQrCode' |\n 'setSettingOption'\n)>;\n\nconst MIN_NUMBER_LENGTH = 7;\n\nlet isPreloadInitiated = false;\n\nconst AuthPhoneNumber: FC<StateProps & DispatchProps> = ({\n connectionState,\n authState,\n authPhoneNumber,\n authIsLoading,\n authIsLoadingQrCode,\n authError,\n authRememberMe,\n authNearestCountry,\n language,\n setAuthPhoneNumber,\n setAuthRememberMe,\n loadNearestCountry,\n clearAuthError,\n goToAuthQrCode,\n setSettingOption,\n}) => {\n const lang = useLang();\n // eslint-disable-next-line no-null/no-null\n const inputRef = useRef<HTMLInputElement>(null);\n const suggestedLanguage = getSuggestedLanguage();\n\n const continueText = useLangString(suggestedLanguage, 'ContinueOnThisLanguage');\n const [country, setCountry] = useState<Country | undefined>();\n const [phoneNumber, setPhoneNumber] = useState<string | undefined>();\n const [isTouched, setIsTouched] = useState(false);\n const [lastSelection, setLastSelection] = useState<[number, number] | undefined>();\n const [isLoading, markIsLoading, unmarkIsLoading] = useFlag();\n\n const fullNumber = country ? `${country.code} ${phoneNumber || ''}` : phoneNumber;\n const canSubmit = fullNumber && fullNumber.replace(/[^\\d]+/g, '').length >= MIN_NUMBER_LENGTH;\n\n useEffect(() => {\n if (!IS_TOUCH_ENV) {\n inputRef.current!.focus();\n }\n }, [country]);\n\n useEffect(() => {\n if (connectionState === 'connectionStateReady' && !authNearestCountry) {\n loadNearestCountry();\n }\n }, [connectionState, authNearestCountry, loadNearestCountry]);\n\n useEffect(() => {\n if (authNearestCountry && !country && !isTouched) {\n setCountry(getCountryById(authNearestCountry));\n }\n }, [country, authNearestCountry, isTouched]);\n\n const parseFullNumber = useCallback((newFullNumber: string) => {\n if (!newFullNumber.length) {\n setPhoneNumber('');\n }\n\n const suggestedCountry = getCountryFromPhoneNumber(newFullNumber);\n\n // Any phone numbers should be allowed, in some cases ignoring formatting\n const selectedCountry = !country\n || (suggestedCountry && suggestedCountry.id !== country.id)\n || (!suggestedCountry && newFullNumber.length)\n ? suggestedCountry\n : country;\n\n if (!country || !selectedCountry || (selectedCountry && selectedCountry.code !== country.code)) {\n setCountry(selectedCountry);\n }\n\n setPhoneNumber(formatPhoneNumber(newFullNumber, selectedCountry));\n }, [country]);\n\n const handleLangChange = useCallback(() => {\n markIsLoading();\n\n setLanguage(suggestedLanguage!, () => {\n unmarkIsLoading();\n\n setSettingOption({ language: suggestedLanguage });\n });\n }, [markIsLoading, setSettingOption, suggestedLanguage, unmarkIsLoading]);\n\n useEffect(() => {\n if (phoneNumber === undefined && authPhoneNumber) {\n parseFullNumber(authPhoneNumber);\n }\n }, [authPhoneNumber, phoneNumber, parseFullNumber]);\n\n useLayoutEffect(() => {\n if (inputRef.current && lastSelection) {\n inputRef.current.setSelectionRange(...lastSelection);\n }\n }, [lastSelection]);\n\n const isJustPastedRef = useRef(false);\n const handlePaste = useCallback(() => {\n isJustPastedRef.current = true;\n requestAnimationFrame(() => {\n isJustPastedRef.current = false;\n });\n }, []);\n\n const handlePhoneNumberChange = useCallback((e: ChangeEvent<HTMLInputElement>) => {\n if (authError) {\n clearAuthError();\n }\n\n // This is for further screens. We delay it until user input to speed up the initial loading.\n if (!isPreloadInitiated) {\n isPreloadInitiated = true;\n preloadFonts();\n preloadImage(monkeyPath);\n }\n\n const { value, selectionStart, selectionEnd } = e.target;\n setLastSelection(\n selectionStart && selectionEnd && selectionEnd < value.length\n ? [selectionStart, selectionEnd]\n : undefined,\n );\n\n setIsTouched(true);\n\n const shouldFixSafariAutoComplete = (\n IS_SAFARI && country && fullNumber !== undefined\n && value.length - fullNumber.length > 1 && !isJustPastedRef.current\n );\n parseFullNumber(shouldFixSafariAutoComplete ? `${country!.code} ${value}` : value);\n }, [authError, clearAuthError, country, fullNumber, parseFullNumber]);\n\n const handleKeepSessionChange = useCallback((e: ChangeEvent<HTMLInputElement>) => {\n setAuthRememberMe(e.target.checked);\n }, [setAuthRememberMe]);\n\n function handleSubmit(event: React.FormEvent<HTMLFormElement>) {\n event.preventDefault();\n\n if (authIsLoading) {\n return;\n }\n\n if (canSubmit) {\n setAuthPhoneNumber({ phoneNumber: fullNumber });\n }\n }\n\n const isAuthReady = authState === 'authorizationStateWaitPhoneNumber';\n\n return (\n <div id=\"auth-phone-number-form\" className=\"custom-scroll\">\n <div className=\"auth-form\">\n <div id=\"logo\" />\n <h2>Telegram</h2>\n <p className=\"note\">{lang('StartText')}</p>\n <form action=\"\" onSubmit={handleSubmit}>\n <CountryCodeInput\n id=\"sign-in-phone-code\"\n value={country}\n isLoading={!authNearestCountry && !country}\n onChange={setCountry}\n />\n <InputText\n ref={inputRef}\n id=\"sign-in-phone-number\"\n label={lang('Login.PhonePlaceholder')}\n value={fullNumber}\n error={authError && lang(authError)}\n inputMode=\"tel\"\n onChange={handlePhoneNumberChange}\n onPaste={IS_SAFARI ? handlePaste : undefined}\n />\n <Checkbox\n id=\"sign-in-keep-session\"\n label=\"Keep me signed in\"\n checked={Boolean(authRememberMe)}\n onChange={handleKeepSessionChange}\n />\n {canSubmit && (\n isAuthReady ? (\n <Button type=\"submit\" ripple isLoading={authIsLoading}>{lang('Login.Next')}</Button>\n ) : (\n <Loading />\n )\n )}\n {isAuthReady && (\n <Button isText ripple isLoading={authIsLoadingQrCode} onClick={goToAuthQrCode}>\n {lang('Login.QR.Login')}\n </Button>\n )}\n {suggestedLanguage && suggestedLanguage !== language && continueText && (\n <Button isText isLoading={isLoading} onClick={handleLangChange}>{continueText}</Button>\n )}\n </form>\n </div>\n </div>\n );\n};\n\nexport default memo(withGlobal(\n (global): StateProps => {\n const {\n settings: { byKey: { language } },\n } = global;\n\n return {\n ...pick(global, [\n 'connectionState',\n 'authState',\n 'authPhoneNumber',\n 'authIsLoading',\n 'authIsLoadingQrCode',\n 'authError',\n 'authRememberMe',\n 'authNearestCountry',\n ]),\n language,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'setAuthPhoneNumber',\n 'setAuthRememberMe',\n 'clearAuthError',\n 'loadNearestCountry',\n 'goToAuthQrCode',\n 'setSettingOption',\n ]),\n)(AuthPhoneNumber));\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 AuthCodeAsync: FC = () => {\n const AuthCode = useModuleLoader(Bundles.Auth, 'AuthCode');\n\n return AuthCode ? <AuthCode /> : <Loading />;\n};\n\nexport default memo(AuthCodeAsync);\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 AuthPasswordAsync: FC = () => {\n const AuthPassword = useModuleLoader(Bundles.Auth, 'AuthPassword');\n\n return AuthPassword ? <AuthPassword /> : <Loading />;\n};\n\nexport default memo(AuthPasswordAsync);\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 AuthRegisterAsync: FC = () => {\n const AuthRegister = useModuleLoader(Bundles.Auth, 'AuthRegister');\n\n return AuthRegister ? <AuthRegister /> : <Loading />;\n};\n\nexport default memo(AuthRegisterAsync);\n","/*\n jquery-qrcode v0.14.0 - https://larsjung.de/jquery-qrcode/ */\n'use strict';let G=null;class H{}H.render=function(w,B){G(w,B)};self.QrCreator=H;\n(function(w){function B(t,c,a,e){var b={},h=w(a,c);h.u(t);h.J();e=e||0;var r=h.h(),d=h.h()+2*e;b.text=t;b.level=c;b.version=a;b.O=d;b.a=function(b,a){b-=e;a-=e;return 0>b||b>=r||0>a||a>=r?!1:h.a(b,a)};return b}function C(t,c,a,e,b,h,r,d,g,x){function u(b,a,f,c,d,r,g){b?(t.lineTo(a+r,f+g),t.arcTo(a,f,c,d,h)):t.lineTo(a,f)}r?t.moveTo(c+h,a):t.moveTo(c,a);u(d,e,a,e,b,-h,0);u(g,e,b,c,b,0,-h);u(x,c,b,c,a,h,0);u(r,c,a,e,a,0,h)}function z(t,c,a,e,b,h,r,d,g,x){function u(b,a,c,d){t.moveTo(b+c,a);t.lineTo(b,\na);t.lineTo(b,a+d);t.arcTo(b,a,b+c,a,h)}r&&u(c,a,h,h);d&&u(e,a,-h,h);g&&u(e,b,-h,-h);x&&u(c,b,h,-h)}function A(t,c){var a=c.fill;if(\"string\"===typeof a)t.fillStyle=a;else{var e=a.type,b=a.colorStops;a=a.position.map((b)=>Math.round(b*c.size));if(\"linear-gradient\"===e)var h=t.createLinearGradient.apply(t,a);else if(\"radial-gradient\"===e)h=t.createRadialGradient.apply(t,a);else throw Error(\"Unsupported fill\");b.forEach(([b,a])=>{h.addColorStop(b,a)});t.fillStyle=h}}function y(t,c){a:{var a=c.text,e=\nc.v,b=c.N,h=c.K,r=c.P;b=Math.max(1,b||1);for(h=Math.min(40,h||40);b<=h;b+=1)try{var d=B(a,e,b,r);break a}catch(J){}d=void 0}if(!d)return null;a=t.getContext(\"2d\");c.background&&(a.fillStyle=c.background,a.fillRect(c.left,c.top,c.size,c.size));e=d.O;h=c.size/e;a.beginPath();for(r=0;r<e;r+=1)for(b=0;b<e;b+=1){var g=a,x=c.left+b*h,u=c.top+r*h,p=r,q=b,f=d.a,k=x+h,m=u+h,D=p-1,E=p+1,n=q-1,l=q+1,y=Math.floor(Math.min(.5,Math.max(0,c.R))*h),v=f(p,q),I=f(D,n),w=f(D,q);D=f(D,l);var F=f(p,l);l=f(E,l);q=f(E,\nq);E=f(E,n);p=f(p,n);x=Math.round(x);u=Math.round(u);k=Math.round(k);m=Math.round(m);v?C(g,x,u,k,m,y,!w&&!p,!w&&!F,!q&&!F,!q&&!p):z(g,x,u,k,m,y,w&&p&&I,w&&F&&D,q&&F&&l,q&&p&&E)}A(a,c);a.fill();return t}var v={minVersion:1,maxVersion:40,ecLevel:\"L\",left:0,top:0,size:200,fill:\"#000\",background:null,text:\"no text\",radius:.5,quiet:0};G=function(t,c){var a={};Object.assign(a,v,t);a.N=a.minVersion;a.K=a.maxVersion;a.v=a.ecLevel;a.left=a.left;a.top=a.top;a.size=a.size;a.fill=a.fill;a.background=a.background;\na.text=a.text;a.R=a.radius;a.P=a.quiet;if(c instanceof HTMLCanvasElement){if(c.width!==a.size||c.height!==a.size)c.width=a.size,c.height=a.size;c.getContext(\"2d\").clearRect(0,0,c.width,c.height);y(c,a)}else t=document.createElement(\"canvas\"),t.width=a.size,t.height=a.size,a=y(t,a),c.appendChild(a)}})(function(){function w(c){var a=C.s(c);return{S:function(){return 4},b:function(){return a.length},write:function(c){for(var b=0;b<a.length;b+=1)c.put(a[b],8)}}}function B(){var c=[],a=0,e={B:function(){return c},\nc:function(b){return 1==(c[Math.floor(b/8)]>>>7-b%8&1)},put:function(b,h){for(var a=0;a<h;a+=1)e.m(1==(b>>>h-a-1&1))},f:function(){return a},m:function(b){var h=Math.floor(a/8);c.length<=h&&c.push(0);b&&(c[h]|=128>>>a%8);a+=1}};return e}function C(c,a){function e(b,h){for(var a=-1;7>=a;a+=1)if(!(-1>=b+a||d<=b+a))for(var c=-1;7>=c;c+=1)-1>=h+c||d<=h+c||(r[b+a][h+c]=0<=a&&6>=a&&(0==c||6==c)||0<=c&&6>=c&&(0==a||6==a)||2<=a&&4>=a&&2<=c&&4>=c?!0:!1)}function b(b,a){for(var f=d=4*c+17,k=Array(f),m=0;m<\nf;m+=1){k[m]=Array(f);for(var p=0;p<f;p+=1)k[m][p]=null}r=k;e(0,0);e(d-7,0);e(0,d-7);f=y.G(c);for(k=0;k<f.length;k+=1)for(m=0;m<f.length;m+=1){p=f[k];var q=f[m];if(null==r[p][q])for(var n=-2;2>=n;n+=1)for(var l=-2;2>=l;l+=1)r[p+n][q+l]=-2==n||2==n||-2==l||2==l||0==n&&0==l}for(f=8;f<d-8;f+=1)null==r[f][6]&&(r[f][6]=0==f%2);for(f=8;f<d-8;f+=1)null==r[6][f]&&(r[6][f]=0==f%2);f=y.w(h<<3|a);for(k=0;15>k;k+=1)m=!b&&1==(f>>k&1),r[6>k?k:8>k?k+1:d-15+k][8]=m,r[8][8>k?d-k-1:9>k?15-k:14-k]=m;r[d-8][8]=!b;if(7<=\nc){f=y.A(c);for(k=0;18>k;k+=1)m=!b&&1==(f>>k&1),r[Math.floor(k/3)][k%3+d-8-3]=m;for(k=0;18>k;k+=1)m=!b&&1==(f>>k&1),r[k%3+d-8-3][Math.floor(k/3)]=m}if(null==g){b=t.I(c,h);f=B();for(k=0;k<x.length;k+=1)m=x[k],f.put(4,4),f.put(m.b(),y.f(4,c)),m.write(f);for(k=m=0;k<b.length;k+=1)m+=b[k].j;if(f.f()>8*m)throw Error(\"code length overflow. (\"+f.f()+\">\"+8*m+\")\");for(f.f()+4<=8*m&&f.put(0,4);0!=f.f()%8;)f.m(!1);for(;!(f.f()>=8*m);){f.put(236,8);if(f.f()>=8*m)break;f.put(17,8)}var u=0;m=k=0;p=Array(b.length);\nq=Array(b.length);for(n=0;n<b.length;n+=1){var v=b[n].j,w=b[n].o-v;k=Math.max(k,v);m=Math.max(m,w);p[n]=Array(v);for(l=0;l<p[n].length;l+=1)p[n][l]=255&f.B()[l+u];u+=v;l=y.C(w);v=z(p[n],l.b()-1).l(l);q[n]=Array(l.b()-1);for(l=0;l<q[n].length;l+=1)w=l+v.b()-q[n].length,q[n][l]=0<=w?v.c(w):0}for(l=f=0;l<b.length;l+=1)f+=b[l].o;f=Array(f);for(l=u=0;l<k;l+=1)for(n=0;n<b.length;n+=1)l<p[n].length&&(f[u]=p[n][l],u+=1);for(l=0;l<m;l+=1)for(n=0;n<b.length;n+=1)l<q[n].length&&(f[u]=q[n][l],u+=1);g=f}b=g;f=\n-1;k=d-1;m=7;p=0;a=y.F(a);for(q=d-1;0<q;q-=2)for(6==q&&--q;;){for(n=0;2>n;n+=1)null==r[k][q-n]&&(l=!1,p<b.length&&(l=1==(b[p]>>>m&1)),a(k,q-n)&&(l=!l),r[k][q-n]=l,--m,-1==m&&(p+=1,m=7));k+=f;if(0>k||d<=k){k-=f;f=-f;break}}}var h=A[a],r=null,d=0,g=null,x=[],u={u:function(b){b=w(b);x.push(b);g=null},a:function(b,a){if(0>b||d<=b||0>a||d<=a)throw Error(b+\",\"+a);return r[b][a]},h:function(){return d},J:function(){for(var a=0,h=0,c=0;8>c;c+=1){b(!0,c);var d=y.D(u);if(0==c||a>d)a=d,h=c}b(!1,h)}};return u}\nfunction z(c,a){if(\"undefined\"==typeof c.length)throw Error(c.length+\"/\"+a);var e=function(){for(var b=0;b<c.length&&0==c[b];)b+=1;for(var r=Array(c.length-b+a),d=0;d<c.length-b;d+=1)r[d]=c[d+b];return r}(),b={c:function(b){return e[b]},b:function(){return e.length},multiply:function(a){for(var h=Array(b.b()+a.b()-1),c=0;c<b.b();c+=1)for(var g=0;g<a.b();g+=1)h[c+g]^=v.i(v.g(b.c(c))+v.g(a.c(g)));return z(h,0)},l:function(a){if(0>b.b()-a.b())return b;for(var c=v.g(b.c(0))-v.g(a.c(0)),h=Array(b.b()),\ng=0;g<b.b();g+=1)h[g]=b.c(g);for(g=0;g<a.b();g+=1)h[g]^=v.i(v.g(a.c(g))+c);return z(h,0).l(a)}};return b}C.s=function(c){for(var a=[],e=0;e<c.length;e++){var b=c.charCodeAt(e);128>b?a.push(b):2048>b?a.push(192|b>>6,128|b&63):55296>b||57344<=b?a.push(224|b>>12,128|b>>6&63,128|b&63):(e++,b=65536+((b&1023)<<10|c.charCodeAt(e)&1023),a.push(240|b>>18,128|b>>12&63,128|b>>6&63,128|b&63))}return a};var A={L:1,M:0,Q:3,H:2},y=function(){function c(b){for(var a=0;0!=b;)a+=1,b>>>=1;return a}var a=[[],[6,18],\n[6,22],[6,26],[6,30],[6,34],[6,22,38],[6,24,42],[6,26,46],[6,28,50],[6,30,54],[6,32,58],[6,34,62],[6,26,46,66],[6,26,48,70],[6,26,50,74],[6,30,54,78],[6,30,56,82],[6,30,58,86],[6,34,62,90],[6,28,50,72,94],[6,26,50,74,98],[6,30,54,78,102],[6,28,54,80,106],[6,32,58,84,110],[6,30,58,86,114],[6,34,62,90,118],[6,26,50,74,98,122],[6,30,54,78,102,126],[6,26,52,78,104,130],[6,30,56,82,108,134],[6,34,60,86,112,138],[6,30,58,86,114,142],[6,34,62,90,118,146],[6,30,54,78,102,126,150],[6,24,50,76,102,128,154],\n[6,28,54,80,106,132,158],[6,32,58,84,110,136,162],[6,26,54,82,110,138,166],[6,30,58,86,114,142,170]],e={w:function(b){for(var a=b<<10;0<=c(a)-c(1335);)a^=1335<<c(a)-c(1335);return(b<<10|a)^21522},A:function(b){for(var a=b<<12;0<=c(a)-c(7973);)a^=7973<<c(a)-c(7973);return b<<12|a},G:function(b){return a[b-1]},F:function(b){switch(b){case 0:return function(b,a){return 0==(b+a)%2};case 1:return function(b){return 0==b%2};case 2:return function(b,a){return 0==a%3};case 3:return function(b,a){return 0==\n(b+a)%3};case 4:return function(b,a){return 0==(Math.floor(b/2)+Math.floor(a/3))%2};case 5:return function(b,a){return 0==b*a%2+b*a%3};case 6:return function(b,a){return 0==(b*a%2+b*a%3)%2};case 7:return function(b,a){return 0==(b*a%3+(b+a)%2)%2};default:throw Error(\"bad maskPattern:\"+b);}},C:function(b){for(var a=z([1],0),c=0;c<b;c+=1)a=a.multiply(z([1,v.i(c)],0));return a},f:function(b,a){if(4!=b||1>a||40<a)throw Error(\"mode: \"+b+\"; type: \"+a);return 10>a?8:16},D:function(b){for(var a=b.h(),c=0,\nd=0;d<a;d+=1)for(var g=0;g<a;g+=1){for(var e=0,t=b.a(d,g),p=-1;1>=p;p+=1)if(!(0>d+p||a<=d+p))for(var q=-1;1>=q;q+=1)0>g+q||a<=g+q||(0!=p||0!=q)&&t==b.a(d+p,g+q)&&(e+=1);5<e&&(c+=3+e-5)}for(d=0;d<a-1;d+=1)for(g=0;g<a-1;g+=1)if(e=0,b.a(d,g)&&(e+=1),b.a(d+1,g)&&(e+=1),b.a(d,g+1)&&(e+=1),b.a(d+1,g+1)&&(e+=1),0==e||4==e)c+=3;for(d=0;d<a;d+=1)for(g=0;g<a-6;g+=1)b.a(d,g)&&!b.a(d,g+1)&&b.a(d,g+2)&&b.a(d,g+3)&&b.a(d,g+4)&&!b.a(d,g+5)&&b.a(d,g+6)&&(c+=40);for(g=0;g<a;g+=1)for(d=0;d<a-6;d+=1)b.a(d,g)&&!b.a(d+\n1,g)&&b.a(d+2,g)&&b.a(d+3,g)&&b.a(d+4,g)&&!b.a(d+5,g)&&b.a(d+6,g)&&(c+=40);for(g=e=0;g<a;g+=1)for(d=0;d<a;d+=1)b.a(d,g)&&(e+=1);return c+=Math.abs(100*e/a/a-50)/5*10}};return e}(),v=function(){for(var c=Array(256),a=Array(256),e=0;8>e;e+=1)c[e]=1<<e;for(e=8;256>e;e+=1)c[e]=c[e-4]^c[e-5]^c[e-6]^c[e-8];for(e=0;255>e;e+=1)a[c[e]]=e;return{g:function(b){if(1>b)throw Error(\"glog(\"+b+\")\");return a[b]},i:function(b){for(;0>b;)b+=255;for(;256<=b;)b-=255;return c[b]}}}(),t=function(){function c(b,c){switch(c){case A.L:return a[4*\n(b-1)];case A.M:return a[4*(b-1)+1];case A.Q:return a[4*(b-1)+2];case A.H:return a[4*(b-1)+3]}}var a=[[1,26,19],[1,26,16],[1,26,13],[1,26,9],[1,44,34],[1,44,28],[1,44,22],[1,44,16],[1,70,55],[1,70,44],[2,35,17],[2,35,13],[1,100,80],[2,50,32],[2,50,24],[4,25,9],[1,134,108],[2,67,43],[2,33,15,2,34,16],[2,33,11,2,34,12],[2,86,68],[4,43,27],[4,43,19],[4,43,15],[2,98,78],[4,49,31],[2,32,14,4,33,15],[4,39,13,1,40,14],[2,121,97],[2,60,38,2,61,39],[4,40,18,2,41,19],[4,40,14,2,41,15],[2,146,116],[3,58,36,\n2,59,37],[4,36,16,4,37,17],[4,36,12,4,37,13],[2,86,68,2,87,69],[4,69,43,1,70,44],[6,43,19,2,44,20],[6,43,15,2,44,16],[4,101,81],[1,80,50,4,81,51],[4,50,22,4,51,23],[3,36,12,8,37,13],[2,116,92,2,117,93],[6,58,36,2,59,37],[4,46,20,6,47,21],[7,42,14,4,43,15],[4,133,107],[8,59,37,1,60,38],[8,44,20,4,45,21],[12,33,11,4,34,12],[3,145,115,1,146,116],[4,64,40,5,65,41],[11,36,16,5,37,17],[11,36,12,5,37,13],[5,109,87,1,110,88],[5,65,41,5,66,42],[5,54,24,7,55,25],[11,36,12,7,37,13],[5,122,98,1,123,99],[7,73,\n45,3,74,46],[15,43,19,2,44,20],[3,45,15,13,46,16],[1,135,107,5,136,108],[10,74,46,1,75,47],[1,50,22,15,51,23],[2,42,14,17,43,15],[5,150,120,1,151,121],[9,69,43,4,70,44],[17,50,22,1,51,23],[2,42,14,19,43,15],[3,141,113,4,142,114],[3,70,44,11,71,45],[17,47,21,4,48,22],[9,39,13,16,40,14],[3,135,107,5,136,108],[3,67,41,13,68,42],[15,54,24,5,55,25],[15,43,15,10,44,16],[4,144,116,4,145,117],[17,68,42],[17,50,22,6,51,23],[19,46,16,6,47,17],[2,139,111,7,140,112],[17,74,46],[7,54,24,16,55,25],[34,37,13],[4,\n151,121,5,152,122],[4,75,47,14,76,48],[11,54,24,14,55,25],[16,45,15,14,46,16],[6,147,117,4,148,118],[6,73,45,14,74,46],[11,54,24,16,55,25],[30,46,16,2,47,17],[8,132,106,4,133,107],[8,75,47,13,76,48],[7,54,24,22,55,25],[22,45,15,13,46,16],[10,142,114,2,143,115],[19,74,46,4,75,47],[28,50,22,6,51,23],[33,46,16,4,47,17],[8,152,122,4,153,123],[22,73,45,3,74,46],[8,53,23,26,54,24],[12,45,15,28,46,16],[3,147,117,10,148,118],[3,73,45,23,74,46],[4,54,24,31,55,25],[11,45,15,31,46,16],[7,146,116,7,147,117],\n[21,73,45,7,74,46],[1,53,23,37,54,24],[19,45,15,26,46,16],[5,145,115,10,146,116],[19,75,47,10,76,48],[15,54,24,25,55,25],[23,45,15,25,46,16],[13,145,115,3,146,116],[2,74,46,29,75,47],[42,54,24,1,55,25],[23,45,15,28,46,16],[17,145,115],[10,74,46,23,75,47],[10,54,24,35,55,25],[19,45,15,35,46,16],[17,145,115,1,146,116],[14,74,46,21,75,47],[29,54,24,19,55,25],[11,45,15,46,46,16],[13,145,115,6,146,116],[14,74,46,23,75,47],[44,54,24,7,55,25],[59,46,16,1,47,17],[12,151,121,7,152,122],[12,75,47,26,76,48],\n[39,54,24,14,55,25],[22,45,15,41,46,16],[6,151,121,14,152,122],[6,75,47,34,76,48],[46,54,24,10,55,25],[2,45,15,64,46,16],[17,152,122,4,153,123],[29,74,46,14,75,47],[49,54,24,10,55,25],[24,45,15,46,46,16],[4,152,122,18,153,123],[13,74,46,32,75,47],[48,54,24,14,55,25],[42,45,15,32,46,16],[20,147,117,4,148,118],[40,75,47,7,76,48],[43,54,24,22,55,25],[10,45,15,67,46,16],[19,148,118,6,149,119],[18,75,47,31,76,48],[34,54,24,34,55,25],[20,45,15,61,46,16]],e={I:function(b,a){var e=c(b,a);if(\"undefined\"==\ntypeof e)throw Error(\"bad rs block @ typeNumber:\"+b+\"/errorCorrectLevel:\"+a);b=e.length/3;a=[];for(var d=0;d<b;d+=1)for(var g=e[3*d],h=e[3*d+1],t=e[3*d+2],p=0;p<g;p+=1){var q=t,f={};f.o=h;f.j=q;a.push(f)}return a}};return e}();return C}());\nexport default QrCreator;\n//# sourceMappingURL=qr-creator.min.js.map\n","import QrCreator from 'qr-creator';\nimport React, {\n FC, useEffect, useRef, memo, useCallback,\n} from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { GlobalState, GlobalActions } from '../../global/types';\nimport { LangCode } from '../../types';\n\nimport { pick } from '../../util/iteratees';\nimport { setLanguage } from '../../util/langProvider';\nimport renderText from '../common/helpers/renderText';\nimport useLangString from '../../hooks/useLangString';\nimport useFlag from '../../hooks/useFlag';\nimport useLang from '../../hooks/useLang';\nimport { getSuggestedLanguage } from './helpers/getSuggestedLanguage';\n\nimport Loading from '../ui/Loading';\nimport Button from '../ui/Button';\n\ntype StateProps = Pick<GlobalState, 'connectionState' | 'authState' | 'authQrCode'> & {\n language?: LangCode;\n};\ntype DispatchProps = Pick<GlobalActions, (\n 'returnToAuthPhoneNumber' | 'setSettingOption'\n)>;\n\nconst DATA_PREFIX = 'tg://login?token=';\n\nconst AuthCode: FC<StateProps & DispatchProps> = ({\n connectionState,\n authState,\n authQrCode,\n language,\n returnToAuthPhoneNumber,\n setSettingOption,\n}) => {\n const suggestedLanguage = getSuggestedLanguage();\n const lang = useLang();\n // eslint-disable-next-line no-null/no-null\n const qrCodeRef = useRef<HTMLDivElement>(null);\n const continueText = useLangString(suggestedLanguage, 'ContinueOnThisLanguage');\n const [isLoading, markIsLoading, unmarkIsLoading] = useFlag();\n\n useEffect(() => {\n if (!authQrCode || connectionState !== 'connectionStateReady') {\n return;\n }\n\n const container = qrCodeRef.current!;\n\n container.innerHTML = '';\n container.classList.remove('pre-animate');\n\n QrCreator.render({\n text: `${DATA_PREFIX}${authQrCode.token}`,\n radius: 0.5,\n ecLevel: 'M',\n fill: '#4E96D4',\n size: 280,\n }, container);\n }, [connectionState, authQrCode]);\n\n const handleLangChange = useCallback(() => {\n markIsLoading();\n\n setLanguage(suggestedLanguage!, () => {\n unmarkIsLoading();\n\n setSettingOption({ language: suggestedLanguage });\n });\n }, [markIsLoading, setSettingOption, suggestedLanguage, unmarkIsLoading]);\n\n const isAuthReady = authState === 'authorizationStateWaitQrCode';\n\n return (\n <div id=\"auth-qr-form\" className=\"custom-scroll\">\n <div className=\"auth-form qr\">\n {authQrCode ? (\n <div key=\"qr-container\" className=\"qr-container pre-animate\" ref={qrCodeRef} />\n ) : (\n <div key=\"qr-loading\" className=\"qr-loading\"><Loading /></div>\n )}\n <h3>{lang('Login.QR.Title')}</h3>\n <ol>\n <li><span>{lang('Login.QR.Help1')}</span></li>\n <li><span>{renderText(lang('Login.QR.Help2'), ['simple_markdown'])}</span></li>\n <li><span>{lang('Login.QR.Help3')}</span></li>\n </ol>\n {isAuthReady && (\n <Button isText onClick={returnToAuthPhoneNumber}>{lang('Login.QR.Cancel')}</Button>\n )}\n {suggestedLanguage && suggestedLanguage !== language && continueText && (\n <Button isText isLoading={isLoading} onClick={handleLangChange}>{continueText}</Button>\n )}\n </div>\n </div>\n );\n};\n\nexport default memo(withGlobal(\n (global): StateProps => {\n const {\n connectionState, authState, authQrCode, settings: { byKey: { language } },\n } = global;\n\n return {\n connectionState,\n authState,\n authQrCode,\n language,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'returnToAuthPhoneNumber', 'setSettingOption',\n ]),\n)(AuthCode));\n","import React, { FC, useEffect, memo } from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { GlobalActions, GlobalState } from '../../global/types';\n\nimport '../../modules/actions/initial';\nimport { pick } from '../../util/iteratees';\nimport { PLATFORM_ENV } from '../../util/environment';\nimport useHistoryBack from '../../hooks/useHistoryBack';\n\nimport UiLoader from '../common/UiLoader';\nimport AuthPhoneNumber from './AuthPhoneNumber';\nimport AuthCode from './AuthCode.async';\nimport AuthPassword from './AuthPassword.async';\nimport AuthRegister from './AuthRegister.async';\nimport AuthQrCode from './AuthQrCode';\n\nimport './Auth.scss';\n\ntype StateProps = Pick<GlobalState, 'authState'>;\ntype DispatchProps = Pick<GlobalActions, 'reset' | 'initApi' | 'returnToAuthPhoneNumber' | 'goToAuthQrCode'>;\n\nconst Auth: FC<StateProps & DispatchProps> = ({\n authState, reset, initApi, returnToAuthPhoneNumber, goToAuthQrCode,\n}) => {\n useEffect(() => {\n reset();\n initApi();\n }, [reset, initApi]);\n\n const isMobile = PLATFORM_ENV === 'iOS' || PLATFORM_ENV === 'Android';\n\n const handleChangeAuthorizationMethod = () => {\n if (!isMobile) {\n goToAuthQrCode();\n } else {\n returnToAuthPhoneNumber();\n }\n };\n\n useHistoryBack(\n (!isMobile && authState === 'authorizationStateWaitPhoneNumber')\n || (isMobile && authState === 'authorizationStateWaitQrCode'), handleChangeAuthorizationMethod,\n );\n\n switch (authState) {\n case 'authorizationStateWaitCode':\n return <UiLoader page=\"authCode\" key=\"authCode\"><AuthCode /></UiLoader>;\n case 'authorizationStateWaitPassword':\n return <UiLoader page=\"authPassword\" key=\"authPassword\"><AuthPassword /></UiLoader>;\n case 'authorizationStateWaitRegistration':\n return <AuthRegister />;\n case 'authorizationStateWaitPhoneNumber':\n return <UiLoader page=\"authPhoneNumber\" key=\"authPhoneNumber\"><AuthPhoneNumber /></UiLoader>;\n case 'authorizationStateWaitQrCode':\n return <UiLoader page=\"authQrCode\" key=\"authQrCode\"><AuthQrCode /></UiLoader>;\n default:\n return isMobile\n ? <UiLoader page=\"authPhoneNumber\" key=\"authPhoneNumber\"><AuthPhoneNumber /></UiLoader>\n : <UiLoader page=\"authQrCode\" key=\"authQrCode\"><AuthQrCode /></UiLoader>;\n }\n};\n\nexport default memo(withGlobal(\n (global): StateProps => pick(global, ['authState']),\n (global, actions): DispatchProps => pick(actions, ['reset', 'initApi', 'returnToAuthPhoneNumber', 'goToAuthQrCode']),\n)(Auth));\n","import React, { FC, memo } from '../../lib/teact/teact';\nimport { Bundles } from '../../util/moduleLoader';\n\nimport useModuleLoader from '../../hooks/useModuleLoader';\n\nconst MainAsync: FC = () => {\n const Main = useModuleLoader(Bundles.Main, 'Main');\n\n return Main ? <Main /> : undefined;\n};\n\nexport default memo(MainAsync);\n","export default __webpack_public_path__ + \"app-inactive.bc7953c2dfebcabce2c43ca7dc778a89.png\";","import React, { FC } from '../../lib/teact/teact';\n\nimport Button from '../ui/Button';\n\nimport appInactivePath from '../../assets/app-inactive.png';\nimport './AppInactive.scss';\n\nconst AppInactive: FC = () => {\n const handleReload = () => {\n window.location.reload();\n };\n\n return (\n <div id=\"AppInactive\">\n <div className=\"content\">\n <img src={appInactivePath} alt=\"\" />\n <h3 className=\"title\">Such error, many tabs</h3>\n <div className=\"description\">\n Telegram supports only one active tab with the app.\n <br />\n Please reload this page to continue using this tab or close it.\n </div>\n <div className=\"actions\">\n <Button isText ripple onClick={handleReload}>Reload app</Button>\n </div>\n </div>\n </div>\n );\n};\n\nexport default AppInactive;\n","import { FC, useEffect } from './lib/teact/teact';\nimport React, { withGlobal } from './lib/teact/teactn';\n\nimport { GlobalActions, GlobalState } from './global/types';\n\nimport { INACTIVE_MARKER, PAGE_TITLE } from './config';\nimport { pick } from './util/iteratees';\nimport { updateSizes } from './util/windowSize';\nimport { addActiveTabChangeListener } from './util/activeTabMonitor';\nimport useFlag from './hooks/useFlag';\n\nimport Auth from './components/auth/Auth';\nimport UiLoader from './components/common/UiLoader';\nimport Main from './components/main/Main.async';\nimport AppInactive from './components/main/AppInactive';\nimport { hasStoredSession } from './util/sessions';\n// import Test from './components/test/TestNoRedundancy';\n\ntype StateProps = Pick<GlobalState, 'authState'>;\ntype DispatchProps = Pick<GlobalActions, 'disconnect'>;\n\nconst App: FC<StateProps & DispatchProps> = ({ authState, disconnect }) => {\n const [isInactive, markInactive] = useFlag(false);\n\n useEffect(() => {\n updateSizes();\n addActiveTabChangeListener(() => {\n disconnect();\n document.title = `${PAGE_TITLE}${INACTIVE_MARKER}`;\n\n markInactive();\n });\n }, [disconnect, markInactive]);\n\n // return <Test />;\n\n if (isInactive) {\n return <AppInactive />;\n }\n\n if (authState) {\n switch (authState) {\n case 'authorizationStateWaitPhoneNumber':\n case 'authorizationStateWaitCode':\n case 'authorizationStateWaitPassword':\n case 'authorizationStateWaitRegistration':\n case 'authorizationStateWaitQrCode':\n return <Auth />;\n case 'authorizationStateClosed':\n case 'authorizationStateClosing':\n case 'authorizationStateLoggingOut':\n case 'authorizationStateReady':\n return renderMain();\n }\n }\n\n return hasStoredSession(true) ? renderMain() : <Auth />;\n};\n\nfunction renderMain() {\n return (\n <UiLoader page=\"main\" key=\"main\">\n <Main />\n </UiLoader>\n );\n}\n\nexport default withGlobal(\n (global): StateProps => pick(global, ['authState']),\n (setGlobal, actions): DispatchProps => pick(actions, ['disconnect']),\n)(App);\n","import './util/handleError';\nimport './util/setupServiceWorker';\n\nimport React, { getDispatch, getGlobal } from './lib/teact/teactn';\nimport TeactDOM from './lib/teact/teact-dom';\n\nimport './global';\n\nimport { DEBUG } from './config';\n\nimport App from './App';\n\nimport './styles/index.scss';\n\nif (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('>>> INIT');\n}\n\ngetDispatch().init();\n\nif (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('>>> START INITIAL RENDER');\n}\n\nTeactDOM.render(\n <App />,\n document.getElementById('root'),\n);\n\nif (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('>>> FINISH INITIAL RENDER');\n}\n\ndocument.addEventListener('dblclick', () => {\n // eslint-disable-next-line no-console\n console.log('GLOBAL STATE', getGlobal());\n});\n"],"sourceRoot":""} |