telegram-tt/dist/main.74d30ee49eca27f798d3.js.map
Alexander Zinchuk f8852fdf45 [Build]
2021-05-09 03:57:53 +03:00

1 line
535 KiB
Plaintext
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

{"version":3,"sources":["webpack:///webpack/bootstrap","webpack:///./src/lib/teact/teact.ts","webpack:///./src/config.ts","webpack:///./src/lib/teact/teactn.tsx","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/types/index.ts","webpack:///./src/modules/selectors/users.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/util/buildClassName.ts","webpack:///./src/util/environment.ts","webpack:///./src/util/schedulers.ts","webpack:///./src/api/gramjs/worker/provider.ts","webpack:///./src/assets/lang/en-extra.json","webpack:///./src/assets/lang/es-extra.json","webpack:///./src/assets/lang/it-extra.json","webpack:///./src/assets/lang/pl-extra.json","webpack:///./src/assets/lang/ru-extra.json","webpack:///./src/util/langProvider.ts","webpack:///./src/util/callbacks.ts","webpack:///./src/util/moduleLoader.ts","webpack:///./src/util/cacheApi.ts","webpack:///./src/util/files.ts","webpack:///./src/lib/twemojiRegex.js","webpack:///./src/components/ui/Loading.tsx","webpack:///./src/hooks/useModuleLoader.ts","webpack:///./src/util/countries.ts","webpack:///./src/util/phoneNumber.ts","webpack:///./src/types/index.ts","webpack:///./src/components/ui/Spinner.tsx","webpack:///./src/util/handleError.ts","webpack:///./src/components/common/helpers/renderText.tsx","webpack:///./src/util/arePropsShallowEqual.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/components/ui/Button.tsx","webpack:///./src/lib/teact/dom-events.ts","webpack:///./src/hooks/useFlag.ts","webpack:///./src/hooks/useShowTransition.ts","webpack:///./src/util/dateFormat.ts","webpack:///./src/hooks/useForceUpdate.ts","webpack:///./src/util/notifications.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/hooks/usePrevious.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/components/ui/InputText.tsx","webpack:///./src/components/ui/Checkbox.tsx","webpack:///./src/util/captureEscKeyListener.ts","webpack:///./src/hooks/useHeavyAnimationCheck.ts","webpack:///./src/util/textFormat.ts","webpack:///./src/util/memo.ts","webpack:///./src/util/searchWords.ts","webpack:///./src/components/ui/Menu.tsx","webpack:///./src/hooks/useKeyboardListNavigation.ts","webpack:///./src/util/oggToWav.ts","webpack:///./src/util/mediaLoader.ts","webpack:///./src/util/windowSize.ts","webpack:///./src/util/captureKeyboardListeners.ts","webpack:///./src/lib/punycode.js","webpack:///./src/components/common/SafeLink.tsx","webpack:///./src/hooks/useEffectWithPrevDeps.ts","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/lib/teact/teact-dom.ts","webpack:///./src/components/common/helpers/parseEmojiOnlyString.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/util/switchTheme.ts","webpack:///./src/util/emoji.ts","webpack:///./src/components/middle/message/MentionLink.tsx","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/api/initial.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/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:///./src/components/auth/AuthQrCode.async.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","1","__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","getTarget","setTarget","useState","initial","newValue","scheduleNextState","throttleWithPrimaryRaf","applyNextState","throttleWithRaf","currentElement","forceUpdateComponent","DEBUG_contentComponentName","useLayoutEffectBase","schedulerFn","exec","some","dependency","useEffect","fastRaf","useLayoutEffect","onTickEnd","useMemo","resolver","useCallback","newCallback","useRef","memo","areEqual","arePropsShallowEqual","withDebug","propsRef","renderedRef","getUnequalProps","join","addEventListener","orderBy","values","PAGE_TITLE","INACTIVE_MARKER","APP_INFO","process","IS_TEST","DEBUG_ALERT_MSG","GRAMJS_SESSION_ID_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","isBigScreen","Set","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_MAX","ANIMATION_LEVEL_DEFAULT","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","STICKER_SIZE_INLINE_DESKTOP_FACTOR","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","MEMOJI_STICKER_ID","MENU_TRANSITION_DURATION","SLIDE_TRANSITION_DURATION","LAYERS_TRANSITION_DURATION","CONTENT_TYPES_FOR_QUICK_UPLOAD","RE_LINK_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","LANG_PACKS","TIPS_USERNAME","FEEDBACK_URL","DARK_THEME_BG_COLOR","DARK_THEME_PATTERN_COLOR","DEFAULT_PATTERN_COLOR","React","currentGlobal","reducers","callbacks","container","containers","mapStateToProps","mapReducersToProps","ownProps","mappedProps","newMappedProps","setGlobal","actions","Number","isNaN","DEBUG_componentName","keys","areMappedPropsChanged","DEBUG_updates","updateTime","Map","runCallbacksThrottled","cb","newGlobal","getGlobal","getDispatch","addReducer","reducer","payload","onDispatch","addCallback","removeCallback","index","indexOf","splice","withGlobal","TeactNContainer","id","generateIdFor","useForceUpdate","delete","set","buildCollectionByKey","collection","reduce","byKey","member","mapValues","callback","newByKey","pick","result","pickTruthy","omit","stringKeys","filter","has","orderKey","sort","a","b","Array","isArray","mode1","mode2","orderKey1","orderKey2","aValue1","bValue1","aValue2","bValue2","aValue","bValue","array","concat","unique","from","compact","Boolean","areSortedArraysEqual","array1","array2","every","item","areSortedArraysIntersecting","findIntersectionWithSet","split","chunkSize","cloneDeep","acc","findLast","predicate","CONTENT_NOT_SUPPORTED","RE_LINK","RegExp","getMessageKey","chatId","parseMessageKey","match","messageId","getMessageOriginalId","previousLocalId","getMessageSummaryText","noEmoji","text","photo","video","audio","voice","sticker","contact","poll","invoice","content","groupedId","isGif","emoji","caption","title","performer","fileName","summary","question","getNotificationText","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","getMessageContent","hasMessageMedia","getMessagePhoto","getMessageVideo","getMessageDocument","getMessageSticker","getMessageContact","getMessagePoll","getMessageAction","getMessageAudio","getMessageVoice","getMessageInvoice","getMessageWebPage","getMessageWebPagePhoto","getMessageMediaThumbDataUri","thumbnail","media","getMessageMediaThumbnail","dataUri","getMessageMediaHash","webPagePhoto","base","hasMessageLocalBlobUrl","canMessagePlayVideoInline","getVideoOrAudioBaseHash","getDocumentHasPreview","IS_PROGRESSIVE_SUPPORTED","IS_SAFARI","size","mimeType","getMessageMediaFormat","isAnimated","ApiMediaFormat","Lottie","Progressive","IS_OPUS_SUPPORTED","BlobUrl","getMessageMediaFilename","date","blobUrl","previewBlobUrl","getChatMediaMessageIds","messages","listedIds","reverseOrder","ids","getMessageContentIds","reverse","getPhotoFullDimensions","sizes","getPhotoInlineDimensions","getVideoDimensions","width","height","getMediaTransferState","progress","isDownloadNeeded","isUploading","isTransferring","transferProgress","messageIds","contentType","validator","matchLinkInMessageText","getMediaDuration","duration","buildChatThreadKey","threadId","selectUser","global","userId","users","byId","selectChat","chats","selectChatUser","chat","getPrivateChatUserId","selectIsChatWithSelf","currentUserId","selectIsChatWithBot","user","isUserBot","selectSupportChat","isSupport","selectChatOnlineCount","isChatPrivate","isChatChannel","fullInfo","members","onlineCount","isUserOnline","selectChatBot","selectIsChatBotNotStarted","bot","lastMessage","messageInfo","byChatId","threadsById","MAIN_THREAD_ID","selectAreActiveChatsLoaded","listIds","active","selectIsChatListed","targetList","includes","list","selectChatListType","folderId","selectChatFolder","chatFolders","selectIsChatPinned","archived","orderedPinnedIds","chatFoldersById","pinnedChatIds","selectChatByUsername","username","usernameLowered","toLowerCase","selectCountNotMutedUnread","activeChatIds","unreadCount","isMuted","selectCurrentStickerSearch","stickers","search","selectCurrentGifSearch","gifs","selectStickerSet","setsById","selectStickersForEmoji","stickerSets","stickersForEmoji","packs","selectAnimatedEmoji","animatedEmojis","replace","selectCurrentMessageList","messageLists","selectCurrentChat","selectChatMessages","selectScheduledMessages","scheduledMessages","selectThreadParam","thread","selectListedIds","selectOutlyingIds","selectCurrentMessageIds","messageListType","selectViewportIds","selectPinnedIds","selectScheduledIds","selectScrollOffset","selectReplyingToId","selectEditingId","selectEditingScheduledId","selectDraft","selectNoWebPage","selectThreadInfo","selectFirstMessageId","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","isRestricted","isPrivate","isChatWithSelf","isBasicGroup","isChatBasicGroup","isSuperGroup","isChatSuperGroup","isChannel","isServiceNotification","isOwn","isAction","isMessageEditable","Date","viaBotId","canReply","getCanPostInChat","hasPinPermission","isCreator","isUserRightBanned","getHasAdminRight","canPin","canUnpin","pinnedMessageIds","canDelete","canDeleteForAll","canEdit","canForward","hasSticker","hasFavoriteSticker","favorite","selectIsStickerFavorite","canFaveSticker","canUnfaveSticker","canCopy","canCopyLink","canSelect","noOptions","ability","selectCanDeleteSelectedMessages","selectedMessageIds","selectedMessages","messageActions","selectUploadProgress","fileTransfer","fileUploads","byMessageLocalId","selectRealLastReadId","lastReadInboxMessageId","min","selectFirstUnreadId","outlyingIds","lastReadId","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","settings","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","isPollResults","pollResults","selectIsPollResultsOpen","isSearch","IS_MOBILE_SCREEN","isManagement","currentManagement","selectCurrentManagement","isStickerSearch","query","isGifSearch","currentChatId","areActiveChatsLoaded","isUserInfo","isChatInfo","RightColumnContent","PollResults","Search","Management","StickerSearch","GifSearch","UserInfo","ChatInfo","selectIsRightColumnShown","selectCurrentGlobalSearchQuery","globalSearch","selectPaymentMessageId","payment","selectPaymentRequestId","formId","selectProviderPublishableKey","nativeParams","publishableKey","selectStripeCredentials","stripeCredentials","parts","PLATFORM_ENV","userAgent","platform","navigator","os","test","getPlatform","IS_MAC_OS","IS_IOS","IS_ANDROID","IS_TOUCH_ENV","matchMedia","matches","innerWidth","IS_VOICE_RECORDING_SUPPORTED","mediaDevices","AudioContext","webkitAudioContext","IS_EMOJI_SUPPORTED","documentElement","style","IS_SERVICE_WORKER_SUPPORTED","Audio","canPlayType","DPR","devicePixelRatio","MASK_IMAGE_DISABLED","isWebpSupportedCache","isWebpSupported","webp","Image","handleLoadOrError","hasWebp","debounce","fn","ms","shouldRunFirst","shouldRunLast","waitingTimeout","args","self","throttle","interval","isPending","_args","setInterval","clearInterval","throttleWith","fastPrimaryRaf","throttleWithTickEnd","waiting","onIdle","requestIdleCallback","pause","rafPromise","requestAnimationFrame","fastRafCallbacks","isPrimary","unshift","currentCallbacks","worker","requestStates","requestStatesByCallback","initApi","sessionId","Worker","update","requestState","response","callbackArgs","subscribeToWorker","makeRequest","callApi","fnName","cancelApiProgress","progressCallback","isCanceled","postMessage","assign","pop","catch","finally","EXTRA_PACK_PATHS","en","enExtraJson","es","esExtraJson","it","itExtraJson","pl","plExtraJson","ru","ruExtraJson","PLURAL_OPTIONS","PLURAL_RULES","ar","ca","de","fa","fr","ko","nl","pt_BR","tr","uk","uz","cache","langPack","runCallbacks","createCallbackManager","currentLangCode","async","setLanguage","langCode","lang","newLangPack","cached","cacheApi","Json","remote","sourceLangPacks","fetchFromCacheOrRemote","fetch","pairs","json","extraLangPack","clear","getTranslation","format","langString","template","amount","optionIndex","getPluralOption","trim","processTemplate","formatInteger","Bundles","LOAD_PROMISES","MEMORY_CACHE","loadModule","bundleName","moduleName","Auth","Main","Extra","handleBundleLoad","bundle","getModuleFromMemory","listeners","addLoadListener","listener","caches","Type","cacheName","Request","open","Blob","blob","substr","headers","save","cacheData","JSON","stringify","Response","put","File","constructor","fileBits","options","rest","super","this","dataUriToBlob","arr","mime","bstr","atob","u8arr","Uint8Array","charCodeAt","blobToDataUri","reader","FileReader","readAsDataURL","blobToFile","lastModified","preloadImage","img","preloadVideo","volume","onloadedmetadata","createPosterForVideo","race","onseeked","canvas","videoWidth","videoHeight","getContext","drawImage","toDataURL","currentTime","fetchBlob","imgToCanvas","vs16RegExp","zeroWidthJoiner","fromCharCode","removeVS16s","rawEmoji","color","className","withBackground","noLoad","autoUpdate","formatsCache","defaultPhoneNumberFormat","parsed","str","flag","phoneFormat","formatValue","phoneNumberFormat","phoneNumberGroups","count","repeat","getPhoneNumberFormat","getCountryById","countryList","getCountryFromPhoneNumber","input","phoneNumber","startsWith","possibleCountries","country","formatPhoneNumber","_","p1","p2","p3","p4","p5","separator","output","formatPhoneNumberWithCode","numberWithPlus","LoadMoreDirection","FocusDirection","SettingsScreens","LeftColumnContent","GlobalSearchContent","MediaViewerOrigin","ChatCreationProgress","ProfileEditProgress","ManagementProgress","ProfileState","PaymentStep","UPLOADING_WALLPAPER_SLUG","ManagementScreens","Spinner","buildClassName","handleErrorEvent","startedAt","isReloading","preventDefault","ErrorEvent","reason","alert","localStorage","getItem","removeItem","location","reload","APP_ENV","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","RE_MENTION","nextLink","addLinks","replaceSimpleMarkdown","emojis","emojiResult","nativeToUnfified","alt","line","trimmedLine","trimLeft","indentLength","entityResult","currentProps","newProps","currentKeys","currentKeysLength","prop","Link","onClick","handleClick","store","random","USER_COLOR_KEYS","getUserFirstOrLastName","firstName","lastName","isDeletedUser","getUserStatus","status","wasOnline","wasOnlineDate","diff","getTime","floor","today","setHours","formatTime","yesterday","setDate","getDate","formatFullDate","sortUserIds","usersById","priorityIds","expires","getUserColorKey","peer","abs","getChatTypeString","isSelf","getChatDescription","about","getChatLink","inviteLink","getChatAvatarHash","owner","avatarHash","isChatSummaryOnly","isChatAdmin","adminRights","currentUserBannedRights","defaultBannedRights","migratedTo","isNotJoined","getAllowedAttachmentOptions","isChatWithBot","canAttachMedia","canAttachPolls","canSendStickers","canSendGifs","canAttachEmbedLinks","isAdmin","getMessageSendingRestrictionReason","sendMessages","getChatSlowModeOptions","slowMode","getChatOrder","max","joinDate","isChatArchived","getCanDeleteChat","prepareFolderListIds","chatsById","folder","chatIdsCache","excludedChatIds","includedChatIds","excludeArchived","excludeMuted","unreadMentionsCount","hasUnreadMark","excludeRead","privateChatUser","bots","contacts","isContact","nonContacts","groups","channels","filterChatFolder","prepareChatList","folderType","chatFilter","listedChats","listIdsSet","pinnedChats","otherChats","getFolderUnreadDialogs","unreadDialogsCount","total","hasActiveDialogs","getFolderDescriptionText","emoticon","description","pinnedIds","getFolderChatsCount","isChat","chatOrUser","getMessageSenderName","sortChatIds","chatIds","shouldPrioritizeVerified","priority","isVerified","Button","ref","onContextMenu","onMouseDown","onMouseEnter","onMouseLeave","onFocus","pill","fluid","isText","isLoading","ariaLabel","download","disabled","ripple","faded","tabIndex","elementRef","isClicked","setIsClicked","fullClassName","handleMouseDown","aria-label","NON_BUBBLEABLE_EVENTS","delegationRegistry","delegatedEventsByElement","documentEventCounters","element","propName","handler","eventName","resolveEventName","canUseEventDelegation","handleEvent","resolveDelegationRegistryForName","existing","newSet","resolveDelegatedEventsForElement","add","addDelegatedListener","removeEventListener","removeDelegatedListener","tagName","realEventName","eventNames","realEvent","events","furtherCallsPrevented","stopPropagation","Proxy","Reflect","body","setValue","isOpen","onCloseTransitionEnd","noOpenTransition","noCloseTransition","isClosed","setIsClosed","closeTimeoutRef","hasOpenClassName","setHasOpenClassName","isClosing","shouldRender","transitionClassNames","WEEKDAYS_FULL","MONTHS_FULL","MONTHS_FULL_LOWERCASE","month","getDayStart","datetime","getDayStartAt","toYearMonth","timestamp","getFullYear","getMonth","toIsoString","getHours","padStart","getMinutes","formatPastTimeShort","weekAgo","getDay","withYear","formatDate","formatMonthAndYear","isShort","formatHumanDate","noWeekdays","lowerFirst","upperFirst","weekAhead","weekDay","formatKey","day","monthIndex","formatMediaDateTime","formatMediaDuration","hours","minutes","seconds","string","formatVoiceRecordDuration","durationInMs","milliseconds","formatDateToString","toLocaleString","year","isValidDate","MAX_MONTH_IN_YEAR","parseDateString","matchStringDate","matchEuropeStringDate","matchNumberDate","dateParts","findIndex","timestampPlusDay","MILISECONDS_IN_DAY","toUpperCase","setTrigger","trigger","getDeviceToken","subscription","toJSON","endpoint","checkIfPushSupported","ServiceWorkerRegistration","Notification","permission","unsubscribeFromPush","dispatch","deviceToken","unsubscribe","deleteDeviceToken","serviceWorkerRegistration","serviceWorker","ready","pushManager","getSubscription","subscribe","requestPermission","subscribedAt","checkIfShouldResubscribe","userVisibleOnly","setDeviceToken","showNewMessageNotification","loadNotificationsSettings","hasPrivateChatsNotifications","hasGroupNotifications","hasBroadcastNotifications","checkIfShouldNotify","messageSender","messageAction","actionTargetMessage","targetUserId","actionTargetUserId","targetChatId","actionTargetChatId","actionTargetUser","privateChatUserId","actionOrigin","renderActionMessageText","asPlain","senderName","getNotificationContent","notification","icon","badge","toString","vibrate","controller","onclick","close","focusMessage","notifyClientReady","trimText","MenuItem","destructive","handleKeyDown","keyCode","role","onKeyDown","ripples","setRipples","cleanUpDebounced","button","currentTarget","position","getBoundingClientRect","rippleSize","offsetWidth","x","clientX","y","clientY","EMPTY_IMAGE_DATA_URI","webpToPng","initWebpWorker","wasmReady","requests","getDecodePromise","ImageData","putImageData","toBlob","createPng","webpToPngBase64","pngBlob","WebpWorker","onmessage","handleLibWebpMessage","usePrevious","next","shouldSkipUndefined","replaceChatListIds","newIds","updateChatListIds","idsUpdate","replaceChats","newById","updateChat","chatUpdate","shouldOmitMinInfo","isMin","updatedChat","photos","updateChats","updatedById","addChats","addedById","updateChatListType","listType","currentListIds","listTypeKey","currentFolderList","updateChatListSecondaryInfo","info","totalCountKey","totalCount","totalChatCount","isFullyLoaded","updateCurrentMessageList","replaceChatMessages","updateMessageStore","replaceThreadParam","paramName","threadUpdate","updateThread","addMessages","addedByChatId","messagesByChatId","addChatMessagesById","newId","updateChatMessage","messageUpdate","updatedMessage","updateScheduledMessage","replaceScheduledMessages","deleteChatMessages","deletedForwardedPosts","isLinkedChannelPost","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","exitMessageSelectMode","updateStickerSets","category","sets","resultIds","updatedSets","stickerSet","setIds","updateStickerSet","stickerSetId","currentStickerSet","updateGifSearch","isNew","results","nextOffset","currentResults","newResults","currentIds","gif","replaceAnimatedEmojis","updateStickersForEmoji","remoteStickers","allStickers","uniqueIds","forEmoji","rebuildStickersForEmoji","replaceUsers","updateUser","userUpdate","contactUserIds","updatedUser","updateUsers","addUsers","updateSelectedUserId","deleteUser","MEMO_EMPTY_ARRAY","getComplexKey","updateGlobalSearch","searchStatePartial","updateGlobalSearchContent","currentContent","updateGlobalSearchResults","newFoundMessages","nextRate","resultsByType","newFoundMessagesById","foundIdsForType","foundIds","updateGlobalSearchFetchingStatus","prevFoundIds","newFoundIds","foundOrPrevFoundIds","nextOffsetId","newState","fetchingStatus","replaceLocalTextSearch","searchParams","updateLocalTextSearch","replaceLocalTextSearchResults","updateLocalTextSearchResults","orderFoundIds","replaceLocalMediaSearch","updateLocalMediaSearchType","currentType","updateLocalMediaSearchResults","replaceLocalMediaSearchResults","updateManagementProgress","updateManagement","replaceSettings","newSettings","updateNotifySettings","peerType","isSilent","isShowPreviews","hasPrivateChatsMessagePreview","hasGroupMessagePreview","hasBroadcastMessagePreview","addBlockedContact","contactId","blocked","removeBlockedContact","updateTwoFaSettings","twoFaSettings","updateShippingOptions","shippingOptions","setRequestInfoId","setPaymentStep","step","setInvoiceMessageInfo","photoUrl","invoiceContent","setStripeCardInfo","cardInfo","setPaymentForm","form","setReceipt","receipt","messageInvoice","clearPayment","closeInvoice","isPaymentModalOpen","label","success","readOnly","placeholder","autoComplete","inputMode","maxLength","onChange","onInput","onKeyPress","onBlur","labelText","htmlFor","subLabel","checked","blocking","onCheck","handleChange","captureEscKeyListener","captureKeyboardListener","onEsc","isAnimating","dispatchHeavyAnimationEvent","dispatchEvent","Event","handleAnimationStart","handleAnimationEnd","formatFixedNumber","number","toFixed","formatIntegerCompact","views","getFirstLetters","phrase","word","RE_NOT_LETTER","searchWords","haystack","needle","haystackWords","needleWord","haystackWord","Menu","containerRef","positionX","positionY","autoClose","footer","noCloseOnBackdrop","onCloseAnimationEnd","onClose","menuRef","backdropContainerRef","useShowTransition","useEffectWithPrevDeps","prevIsOpen","onSelectWithEnter","focusedIndex","setFocusedIndex","focusedElement","activeElement","elementChildren","newIndex","focus","useKeyboardListNavigation","useVirtualBackdrop","bubbleClassName","oggToWav","opusData","arrayBuffer","typedArray","decoderWorker","DecoderWorker","wavWorker","WavWorker","command","buffers","buffer","page","terminate","wavBitDepth","wavSampleRate","decoderSampleRate","outputBufferSampleRate","pages","asCacheApiType","DataUri","Stream","memoryCache","fetchPromises","mediaFormat","onProgress","progressiveUrl","getProgressive","mediaPng","prepared","prepareMedia","mediaSource","MediaSource","streamUrl","URL","createObjectURL","sourceBuffer","addSourceBuffer","endOfStream","appendBuffer","revokeObjectURL","getFromMemory","cancelProgress","mediaData","fullSize","windowSize","updateSizes","vh","setProperty","handleResize","keyToHandlerName","Enter","Backspace","Delete","Esc","Escape","ArrowUp","ArrowDown","Tab","handlers","onEnter","onDelete","onBackspace","onUp","onDown","onTab","captureKeyboardListeners","hasActiveHandlers","handlerName","currentEventHandlers","releaseKeyboardListener","keyHandlers","utf16","len","RangeError","adapt","delta","numpoints","firsttime","k","decode","preserveCase","case_flags","input_length","out","bias","basic","j","ic","oldi","w","digit","lastIndexOf","cp","toUnicode","domain_array","getHref","getDecodedUrl","decodedHref","decodeURI","convertPunycode","openTelegramLink","ctrlKey","altKey","shiftKey","metaKey","classNames","prevDeps","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","getShippingError","errors","cur","currentInstance","animateSingle","tick","instance","isCancelled","animate","DropdownMenu","dropdownRef","setIsOpen","menu","onTrigger","FILTERED_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","RE_EMOJI_ONLY","twemojiRegex","DETECT_UP_TO","emojiCount","openUserInfo","handleMessageClick","openChat","targetUser","targetMessage","textOptions","maxTextLength","unprocessed","processed","processPlaceholder","isEmbedded","origin","renderChatContent","renderUserContent","showQuotes","messageText","renderMessageContent","renderProductContent","renderMigratedContent","replaceValue","placeholderPosition","MESSAGE_DELETED","isInitialized","HEX_COLOR_REGEX","lerp","start","end","interpolationRatio","colors","themeColors","hexToRgb","hex","parseInt","g","applyColorAnimationStep","startIndex","endIndex","propertyColors","theme","withAnimation","isDarkTheme","shouldAnimate","startAt","themeColorTag","querySelector","classList","remove","transition","EXCLUDE_EMOJIS","unifiedToNative","unified","codePoints","fromCodePoint","uncompressEmoji","emojiData","categories","emojiRaw","colons","native","image","openChatByUsername","contains","animationLevel","messageTextSize","language","switchTheme","uiReadyState","authPhoneNumber","authRememberMe","authError","apiUpdate","authIsSessionRemembered","authIsLoading","password","file","authIsLoadingQrCode","setItem","reset","init","connectionState","authNearestCountry","onUpdateApiReady","wasAuthReady","authState","authorizationState","isLoggingOut","authIsCodeViaApp","isCodeViaApp","authHint","hint","authQrCode","qrCode","lastSyncTime","saveSession","onUpdateAuthorizationState","onUpdateAuthorizationError","sync","signOut","onUpdateConnectionState","currentUser","onUpdateCurrentUser","showError","ServiceWorkerNoSupportError","setPrototypeOf","scriptUrl","handleWorkerMessage","register","INITIAL_STATE","isLeftColumnShown","recentEmojis","added","recent","featured","saved","topPeers","audioPlayer","notifications","activeSessions","isBackgroundBlurred","patternColor","messageSendKeyCombo","shouldSuggestStickers","privacy","updateCacheThrottled","isAllowed","reducedGlobal","reduceShowChatInfo","reduceUsers","reduceChats","reduceMessages","recentlyFoundChatIds","reduceSettings","loadCache","initialState","time","parse","timeEnd","readCache","idsToSave","cid","chatIdsToSave","mainThread","history","replaceState","tabKey","SITE_FONTS","preloadFonts","font","fonts","load","preloadAvatars","mediaLoader","preloadTasks","main","telegramLogoPath","authCode","monkeyPath","authPassword","hasCustomBackground","customBackground","isCustomBackgroundColor","isRightColumnShown","setIsUiReady","isReady","markReady","useFlag","shouldRenderMask","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","gotToAuthQrCode","setCountry","setPhoneNumber","isTouched","setIsTouched","lastSelection","setLastSelection","fullNumber","canSubmit","parseFullNumber","newFullNumber","suggestedCountry","selectedCountry","setSelectionRange","handlePhoneNumberChange","selectionStart","selectionEnd","handleKeepSessionChange","isAuthReady","onSubmit","InputText","Checkbox","Loading","AuthCode","useModuleLoader","AuthPassword","AuthRegister","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,EAAIF,EAASI,OAAQF,IACzBH,EAAUC,EAASE,GAChBG,OAAOC,UAAUC,eAAeC,KAAKC,EAAiBV,IAAYU,EAAgBV,IACpFI,EAASO,KAAKD,EAAgBV,GAAS,IAExCU,EAAgBV,GAAW,EAE5B,IAAID,KAAYG,EACZI,OAAOC,UAAUC,eAAeC,KAAKP,EAAaH,KACpDa,EAAQb,GAAYG,EAAYH,IAKlC,IAFGc,GAAqBA,EAAoBf,GAEtCM,EAASC,QACdD,EAASU,OAATV,GAOF,IAAIW,EAAmB,GAGnBC,EAAqB,CACxBC,EAAG,GAMAP,EAAkB,CACrBO,EAAG,GAWJ,SAASC,EAAoBnB,GAG5B,GAAGgB,EAAiBhB,GACnB,OAAOgB,EAAiBhB,GAAUoB,QAGnC,IAAIC,EAASL,EAAiBhB,GAAY,CACzCI,EAAGJ,EACHsB,GAAG,EACHF,QAAS,IAUV,OANAP,EAAQb,GAAUU,KAAKW,EAAOD,QAASC,EAAQA,EAAOD,QAASD,GAG/DE,EAAOC,GAAI,EAGJD,EAAOD,QAKfD,EAAoBI,EAAI,SAAuBtB,GAC9C,IAAIuB,EAAW,GAKZP,EAAmBhB,GAAUuB,EAASZ,KAAKK,EAAmBhB,IACzB,IAAhCgB,EAAmBhB,IAFX,CAAC,EAAI,EAAE,EAAI,EAAE,EAAI,EAAE,EAAI,EAAE,EAAI,GAEUA,IACtDuB,EAASZ,KAAKK,EAAmBhB,GAAW,IAAIwB,SAAQ,SAASC,EAASC,GAIzE,IAHA,IAAIC,GAAa,GAAG3B,IAAUA,GAAW,IAAM,CAAC,EAAI,uBAAuB,EAAI,u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AKnvD,GAAG,eACN,yBAAKoqB,UAAU,WACb,yBAAKj8B,IAAKihE,GAAiBr/B,IAAI,KAC/B,wBAAI3F,UAAU,SAAd,yBACA,yBAAKA,UAAU,eAAf,sDAEE,6BAFF,mEAKA,yBAAKA,UAAU,WACb,kBAACiN,EAAA,EAAD,CAAQS,QAAM,EAACK,QAAM,EAACxH,QAfT,KACnBn/B,OAAOw8B,SAASC,WAcV,iBCmCV,SAASohC,KACP,OACE,kBAAC,EAAD,CAAU1a,KAAK,OAAO3jD,IAAI,QACxB,kBAAC,GAAD,OAKS8O,mBACZmM,GAAuBpL,YAAKoL,EAAQ,CAAC,YAAa,4BACnD,CAAC3N,EAAWC,IAA2BsC,YAAKtC,EAAS,CAAC,eAFzCuB,CA9C6B,EAAGymD,YAAWZ,0BAAyB2J,iBACjF,MAAOC,EAAYC,GAAgB/D,aAAQ,GAc3C,GAZAp0D,YAAU,KACRw/C,cfPFl2C,EeQ6B,KACzB2uD,IACAliE,SAAS6X,MAAS,GAAExM,OAAaC,MAEjC82D,MAED,CAACF,EAAYE,IAIZD,EACF,OAAO,kBAAC,GAAD,MAGT,GAAIhJ,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,OAAO8I,KAIb,OAAO1J,EAA0B0J,KAAe,kBAAC,GAAD,Q,MCzC9Cl7D,KAEF7C,QAAQkD,IAAI,YAGd4K,cAAc8mD,OAEV/xD,KAEF7C,QAAQkD,IAAI,4BAGdi7D,IAAS5O,OACP,kBAAC,GAAD,MACAzzD,SAASu/D,eAAe,SAGtBx4D,KAEF7C,QAAQkD,IAAI,6BAGdpH,SAASkL,iBAAiB,WAAY,KAEpChH,QAAQkD,IAAI,eAAgB2K","file":"main.74d30ee49eca27f798d3.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\t1: 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\t1: 0\n \t};\n\n\n\n \t// script path function\n \tfunction jsonpScriptSrc(chunkId) {\n \t\treturn __webpack_require__.p + \"\" + chunkId + \".\" + {\"0\":\"7ddaef0d4603eee1ad1f\",\"2\":\"13a0dc5a3839d1711416\",\"3\":\"d45dcd7f0b362a5148c7\",\"4\":\"7c56ec130aa2a7b4d81b\",\"5\":\"9890406ccb0a04aa1293\",\"6\":\"9095aa91fc3684692eaf\",\"7\":\"b3047ce293a0e552bf8b\",\"8\":\"3a39c82251f73bbe0fea\",\"9\":\"a144f84357fa2a4cccc2\"}[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,\"2\":1,\"3\":1,\"4\":1,\"5\":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\":\"7ddaef0d4603eee1ad1f\",\"2\":\"13a0dc5a3839d1711416\",\"3\":\"d45dcd7f0b362a5148c7\",\"4\":\"7c56ec130aa2a7b4d81b\",\"5\":\"9890406ccb0a04aa1293\",\"6\":\"9095aa91fc3684692eaf\",\"7\":\"b3047ce293a0e552bf8b\",\"8\":\"3a39c82251f73bbe0fea\",\"9\":\"a144f84357fa2a4cccc2\"}[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 = 94);\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 = FC & {\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 scheduleNextState?: () => void;\n forceUpdate?: () => void;\n onUpdate?: () => void;\n}\n\nexport type VirtualElement = VirtualElementEmpty | VirtualElementText | VirtualElementTag | VirtualElementComponent;\nexport type VirtualRealElement = VirtualElementTag | 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 force cleaning as many objects as possible. Not sure this is needed at all.\n/* eslint-disable no-null/no-null */\nfunction helpGc(componentInstance: ComponentInstance) {\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.Component = null as any;\n componentInstance.props = null as any;\n componentInstance.forceUpdate = null as any;\n componentInstance.onUpdate = null as any;\n}\n\n/* eslint-enable no-null/no-null */\n\nfunction applyNextState(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\nfunction forceUpdateComponent(componentInstance: ComponentInstance) {\n if (!componentInstance.isMounted || !componentInstance.onUpdate) {\n return;\n }\n\n const currentElement = componentInstance.$element;\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.scheduleNextState || !componentInstance.forceUpdate) {\n componentInstance.scheduleNextState = throttleWithPrimaryRaf(() => applyNextState(componentInstance));\n componentInstance.forceUpdate = throttleWithRaf(() => forceUpdateComponent(componentInstance));\n }\n\n if (DEBUG_MORE) {\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 componentInstance.scheduleNextState();\n componentInstance.forceUpdate();\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) {\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 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[]) {\n return useLayoutEffectBase(fastRaf, effect, dependencies);\n}\n\nexport function useLayoutEffect(effect: () => Function | void, dependencies?: any[]) {\n return useLayoutEffectBase(onTickEnd, effect, dependencies);\n}\n\nexport function useMemo<T extends any>(resolver: () => T, dependencies: any[]): 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 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, withDebug = false) {\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 && withDebug) {\n // eslint-disable-next-line no-console\n console.log(\n `[Teact.memo] ${Component.name}: 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","export const PAGE_TITLE = 'Telegram';\nexport const INACTIVE_MARKER = ' [Inactive]';\n\nexport const APP_INFO = process.env.APP_INFO || 'Telegram T';\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 GRAMJS_SESSION_ID_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';\nexport const ASSET_CACHE_NAME = 'tt-assets';\n\nexport const API_UPDATE_THROTTLE = 300;\nexport const API_THROTTLE_RESET_UPDATES = new Set([\n 'newMessage', 'newScheduledMessage', 'deleteMessages', 'deleteScheduledMessages', 'deleteHistory',\n]);\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 = 25;\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;\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 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 MEMOJI_STICKER_ID = 'MEMOJI_STICKER';\n\nexport const MENU_TRANSITION_DURATION = 200;\nexport const SLIDE_TRANSITION_DURATION = 450;\nexport const LAYERS_TRANSITION_DURATION = 450;\n\nexport const CONTENT_TYPES_FOR_QUICK_UPLOAD = 'image/png,image/gif,image/jpeg,video/mp4,video/avi,video/quicktime';\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,6})\\\\b([-a-zA-Z0-9()@:%_+.~#?&/=]*)';\nexport const RE_TME_LINK = /^(?:https?:\\/\\/)?(?:t\\.me\\/)([\\d\\w_]+)(?:\\/([\\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_PACK = 'android';\nexport const LANG_PACKS = ['android', 'ios'];\nexport const TIPS_USERNAME = 'TelegramTips';\nexport const FEEDBACK_URL = 'https://bugs.telegram.org/?tag_ids=41&sort=time';\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","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\nexport function setGlobal(newGlobal?: GlobalState) {\n if (typeof newGlobal === 'object' && newGlobal !== currentGlobal) {\n currentGlobal = newGlobal;\n runCallbacksThrottled();\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) {\n if (reducers[name]) {\n reducers[name].forEach((reducer) => {\n const newGlobal = reducer(currentGlobal, actions, payload);\n if (newGlobal) {\n setGlobal(newGlobal);\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) => {\n onDispatch(name, payload);\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('GLOBAL CONTAINERS', orderBy(Object.values(containers), 'DEBUG_updates', 'desc'));\n });\n}\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';\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');\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(message: ApiMessage, noEmoji = false) {\n const {\n text, photo, video, audio, voice, document, sticker, contact, poll, invoice,\n } = message.content;\n\n if (message.groupedId) {\n if (text) {\n return `${noEmoji ? '' : '🖼 '}${text.text}`;\n }\n\n return 'Album';\n }\n\n if (photo) {\n if (text) {\n return `${noEmoji ? '' : '🖼 '}${text.text}`;\n }\n\n return 'Photo';\n }\n\n if (video) {\n if (video.isGif) {\n if (text) {\n return `${noEmoji ? '' : 'GIF '}${text.text}`;\n }\n\n return 'GIF';\n } else {\n if (text) {\n return `${noEmoji ? '' : '📹 '}${text.text}`;\n }\n\n return 'Video';\n }\n }\n\n if (sticker) {\n return `${sticker.emoji} Sticker`;\n }\n\n if (audio) {\n const caption = [audio.title, audio.performer].filter(Boolean).join(' — ') || (text && text.text);\n if (caption) {\n return `🎧 ${caption}`;\n }\n\n return 'Audio';\n }\n\n if (voice) {\n if (text) {\n return `${noEmoji ? '' : '🎤 '}${text.text}`;\n }\n\n return 'Voice Message';\n }\n\n if (document) {\n return `${noEmoji ? '' : '📎 '}${text ? text.text : document.fileName}`;\n }\n\n if (contact) {\n return 'Contact';\n }\n\n if (poll) {\n return `📊 ${poll.summary.question}`;\n }\n\n if (invoice) {\n return 'Invoice';\n }\n\n if (text) {\n return text.text;\n }\n\n return CONTENT_NOT_SUPPORTED;\n}\n\nexport function getNotificationText(message: ApiMessage) {\n const {\n text, photo, video, audio, voice, document, sticker, contact, poll, invoice,\n } = message.content;\n\n if (message.groupedId) {\n return `🖼 ${text ? text.text : 'Album'}`;\n }\n\n if (photo) {\n return `🖼 ${text ? text.text : 'Photo'}`;\n }\n\n if (video) {\n return `📹 ${text ? text.text : video.isGif ? 'GIF' : 'Video'}`;\n }\n\n if (sticker) {\n return `${sticker.emoji} Sticker `;\n }\n\n if (audio) {\n const caption = [audio.title, audio.performer].filter(Boolean).join(' — ') || (text && text.text);\n return `🎧 ${caption || 'Audio'}`;\n }\n\n if (voice) {\n return `🎤 ${text ? text.text : 'Voice Message'}`;\n }\n\n if (document) {\n return `📎 ${text ? text.text : document.fileName}`;\n }\n\n if (contact) {\n return 'Contact';\n }\n\n if (poll) {\n return `📊 ${poll.summary.question}`;\n }\n\n if (invoice) {\n return 'Invoice';\n }\n\n if (text) {\n return text.text;\n }\n\n return CONTENT_NOT_SUPPORTED;\n}\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(sender: ApiUser | ApiChat) {\n return sender.id > 0 ? getUserFullName(sender as ApiUser) : getChatTitle(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","import {\n ApiAudio, ApiMediaFormat, ApiMessage, ApiMessageSearchType, ApiPhoto, ApiVideo,\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\nexport type IDimensions = {\n width: number;\n height: number;\n};\n\ntype Target = 'micro' | 'pictogram' | 'inline' | 'viewerPreview' | 'viewerFull' | 'download';\n\nconst MAX_INLINE_VIDEO_SIZE = 10 * 1024 ** 2; // 10 MB\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 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 getMessageMediaThumbnail(message: ApiMessage) {\n const media = getMessagePhoto(message)\n || getMessageVideo(message)\n || getMessageDocument(message)\n || getMessageSticker(message)\n || getMessageWebPagePhoto(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\n if (!(photo || video || sticker || webPagePhoto || audio || voice || document)) {\n return undefined;\n }\n\n const base = getMessageKey(message);\n\n if (photo || webPagePhoto) {\n switch (target) {\n case 'micro':\n case 'pictogram':\n return `${base}?size=m`;\n case 'inline':\n if (hasMessageLocalBlobUrl(message)) {\n return undefined;\n }\n\n return `${base}?size=x`;\n case 'viewerPreview':\n return `${base}?size=x`;\n case 'viewerFull':\n return `${base}?size=z`;\n }\n }\n\n if (video) {\n switch (target) {\n case 'micro':\n case 'pictogram':\n return `${base}?size=m`;\n case 'inline':\n if (hasMessageLocalBlobUrl(message)) {\n return undefined;\n }\n\n if (canMessagePlayVideoInline(video)) {\n return getVideoOrAudioBaseHash(video, base);\n }\n\n return `${base}?size=z`;\n case 'viewerPreview':\n return `${base}?size=m`;\n case 'viewerFull':\n return getVideoOrAudioBaseHash(video, base);\n case 'download':\n return `${base}?download`;\n }\n }\n\n if (document) {\n switch (target) {\n case 'micro':\n case 'pictogram':\n case 'inline':\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 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 if (sticker && target === 'inline' && sticker.isAnimated) {\n return ApiMediaFormat.Lottie;\n } else if (video && IS_PROGRESSIVE_SUPPORTED && (\n (target === 'viewerFull') || (target === 'inline' && canMessagePlayVideoInline(video))\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 getMessageMediaFilename(message: ApiMessage) {\n const { photo, video, webPage } = message.content;\n\n if (photo || (webPage && webPage.photo)) {\n return `photo${message.date}.jpeg`;\n }\n\n if (video) {\n return video.fileName;\n }\n\n return undefined;\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 canMessagePlayVideoInline(video: ApiVideo): boolean {\n return video.isGif || video.isRound || video.size <= MAX_INLINE_VIDEO_SIZE;\n}\n\nexport function getChatMediaMessageIds(\n messages: Record<number, ApiMessage>, listedIds: number[], reverseOrder = false,\n) {\n const ids = getMessageContentIds(messages, listedIds, 'media');\n\n return reverseOrder ? ids.reverse() : ids;\n}\n\nexport function getPhotoFullDimensions(photo: ApiPhoto): IDimensions | 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): IDimensions | 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): IDimensions | undefined {\n if (video.width && video.height) {\n return video as IDimensions;\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,\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 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;\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 { ApiDocument } from './messages';\n\nexport * from './users';\nexport * from './chats';\nexport * from './messages';\nexport * from './updates';\nexport * from './media';\nexport * from './payments';\nexport * from './settings';\n\nexport interface ApiOnProgress {\n (\n progress: number, // Float between 0 and 1.\n ...args: any[]\n ): void;\n\n isCanceled?: boolean;\n acceptsBuffer?: boolean;\n}\n\nexport interface ApiAttachment {\n blobUrl: string;\n filename: string;\n mimeType: string;\n size: number;\n quick?: {\n width: number;\n height: number;\n duration?: number;\n };\n voice?: {\n duration: number;\n waveform: number[];\n };\n previewBlobUrl?: string;\n}\n\nexport interface ApiWallpaper {\n slug: string;\n document: ApiDocument;\n}\n\nexport interface ApiSession {\n hash: string;\n isCurrent: boolean;\n isOfficialApp: boolean;\n isPasswordPending: boolean;\n deviceModel: string;\n platform: string;\n systemVersion: string;\n appName: string;\n appVersion: string;\n dateCreated: number;\n dateActive: number;\n ip: string;\n country: string;\n region: string;\n}\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\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 { ApiChat, MAIN_THREAD_ID } from '../../api/types';\nimport { GlobalState } from '../../global/types';\n\nimport {\n getPrivateChatUserId, isChatChannel, isChatPrivate, isHistoryClearMessage, isUserBot, isUserOnline,\n} from '../helpers';\nimport { selectUser } from './users';\nimport { ALL_FOLDER_ID, ARCHIVED_FOLDER_ID, MEMBERS_LOAD_SLICE } from '../../config';\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 (chat && chat.unreadCount && !chat.isMuted) {\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 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 emoji = emoji.replace('\\ufe0f', '');\n\n return animatedEmojis.stickers.find((sticker) => sticker.emoji === emoji);\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} 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 && 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 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 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 isMessageEditable = (\n (isChatWithSelf || Date.now() - 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 canDeleteForAll = canDelete && !isServiceNotification && (\n (isPrivate && !isChatWithSelf)\n || (isBasicGroup && (\n isOwn || getHasAdminRight(chat, 'deleteMessages')\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 canDeleteForAll,\n canForward,\n canFaveSticker,\n canUnfaveSticker,\n canCopy,\n canCopyLink,\n canSelect,\n };\n}\n\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 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 threadInfo.lastMessageId\n ? Math.min(threadInfo.lastReadInboxMessageId, threadInfo.lastMessageId)\n : threadInfo.lastReadInboxMessageId;\n }\n}\n\nexport function selectFirstUnreadId(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 } 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\n if (outlyingIds) {\n const found = outlyingIds.find((id) => {\n return !lastReadId || (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 = listedIds.find((id) => {\n return !lastReadId || (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);\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 { RightColumnContent } from '../../types';\n\nimport { IS_MOBILE_SCREEN } 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 } = global;\n\n const isPollResults = selectIsPollResultsOpen(global);\n const isSearch = Boolean(!IS_MOBILE_SCREEN && 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 ) : 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","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","type Parts = (string | false | undefined)[];\n\nexport default (...parts: Parts) => {\n return parts.filter(Boolean).join(' ');\n};\n","import {\n MOBILE_SCREEN_MAX_WIDTH,\n MOBILE_SCREEN_LANDSCAPE_MAX_HEIGHT,\n MOBILE_SCREEN_LANDSCAPE_MAX_WIDTH,\n} from '../config';\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: 'Mac OS' | 'iOS' | 'Windows' | 'Android' | 'Linux' | undefined;\n\n if (macosPlatforms.indexOf(platform) !== -1) {\n os = 'Mac OS';\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 === 'Mac OS';\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);\n\nexport const IS_TOUCH_ENV = window.matchMedia('(pointer: coarse)').matches;\n// Keep in mind the landscape orientation\nexport const IS_MOBILE_SCREEN = window.innerWidth <= MOBILE_SCREEN_MAX_WIDTH || (\n window.innerWidth <= MOBILE_SCREEN_LANDSCAPE_MAX_WIDTH && window.innerHeight <= MOBILE_SCREEN_LANDSCAPE_MAX_HEIGHT\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'));\n\nexport const DPR = window.devicePixelRatio || 1;\n\nexport const MASK_IMAGE_DISABLED = true;\n\nlet 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","type Scheduler = typeof requestAnimationFrame | typeof onTickEnd | 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 requestAnimationFrame(resolve);\n });\n}\n\nlet fastRafCallbacks: NoneToVoidFunction[] | undefined;\n\nexport function fastRaf(callback: NoneToVoidFunction, isPrimary = false) {\n if (!fastRafCallbacks) {\n fastRafCallbacks = [callback];\n\n requestAnimationFrame(() => {\n const currentCallbacks = fastRafCallbacks!;\n fastRafCallbacks = undefined;\n currentCallbacks.forEach((cb) => cb());\n });\n } else if (isPrimary) {\n fastRafCallbacks.unshift(callback);\n } else {\n fastRafCallbacks.push(callback);\n }\n}\n\nexport function fastPrimaryRaf(callback: NoneToVoidFunction) {\n return fastRaf(callback, true);\n}\n","import Worker from 'worker-loader!./worker';\n\nimport { 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, sessionId = '') {\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: [sessionId],\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","export default __webpack_public_path__ + \"en-extra.e73049da90714ecdae3233e8ffa74d39.json\";","export default __webpack_public_path__ + \"es-extra.b80575cdf988e1a7e3a915abe97f63b4.json\";","export default __webpack_public_path__ + \"it-extra.78e5568451a888818c7e2209e05a9602.json\";","export default __webpack_public_path__ + \"pl-extra.38fd67a6c26e58f5c912568332c7c074.json\";","export default __webpack_public_path__ + \"ru-extra.5761b75bfbe92bb46eb8bba9acbdbb4c.json\";","import { ApiLangPack } from '../api/types';\n\nimport { DEBUG, LANG_CACHE_NAME, LANG_PACKS } from '../config';\nimport * as cacheApi from './cacheApi';\nimport { callApi } from '../api/gramjs';\nimport { createCallbackManager } from './callbacks';\nimport { mapValues } from './iteratees';\n\nimport enExtraJson from '../assets/lang/en-extra.json';\nimport esExtraJson from '../assets/lang/es-extra.json';\nimport itExtraJson from '../assets/lang/it-extra.json';\nimport plExtraJson from '../assets/lang/pl-extra.json';\nimport ruExtraJson from '../assets/lang/ru-extra.json';\nimport { formatInteger } from './textFormat';\n\nconst EXTRA_PACK_PATHS: Record<string, string> = {\n en: enExtraJson as unknown as string,\n es: esExtraJson as unknown as string,\n it: itExtraJson as unknown as string,\n pl: plExtraJson as unknown as string,\n ru: ruExtraJson as unknown as string,\n};\n\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;\n\nconst {\n addCallback,\n removeCallback,\n runCallbacks,\n} = createCallbackManager();\n\nexport { addCallback, removeCallback };\n\nlet currentLangCode: string | undefined;\n\nexport async function setLanguage(langCode: string, callback?: NoneToVoidFunction) {\n if (langPack && langCode === currentLangCode) {\n document.documentElement.lang = langCode;\n if (callback) {\n callback();\n }\n\n return;\n }\n\n const newLangPack = await fetchFromCacheOrRemote(langCode);\n if (!newLangPack) {\n return;\n }\n\n if (EXTRA_PACK_PATHS[langCode]) {\n try {\n const response = await fetch(EXTRA_PACK_PATHS[langCode]);\n const pairs = await response.json();\n const extraLangPack = mapValues(pairs, (value, key) => ({ key, value }));\n\n Object.assign(newLangPack, extraLangPack);\n } catch (err) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error(err);\n }\n }\n }\n\n cache.clear();\n\n currentLangCode = langCode;\n langPack = newLangPack;\n document.documentElement.lang = langCode;\n\n if (callback) {\n callback();\n }\n\n runCallbacks(langPack);\n}\n\nexport function getTranslation(key: string, value?: any, format?: 'i') {\n if (value !== undefined) {\n const cached = cache.get(`${key}_${value}_${format}`);\n if (cached) {\n return cached;\n }\n }\n\n if (!langPack) {\n return key;\n }\n\n const langString = langPack[key];\n if (!langString) {\n return key;\n }\n\n const template = langString[typeof value === 'number' ? getPluralOption(value) : 'value'];\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 cache.set(`${key}_${value}_${format}`, result);\n return result;\n }\n\n return template;\n}\n\nasync function fetchFromCacheOrRemote(langCode: string): Promise<ApiLangPack | undefined> {\n const cached = await cacheApi.fetch(LANG_CACHE_NAME, langCode, cacheApi.Type.Json);\n if (cached) {\n return cached;\n }\n\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\nfunction getPluralOption(amount: number) {\n const optionIndex = currentLangCode && PLURAL_RULES[currentLangCode as keyof typeof PLURAL_RULES]\n ? PLURAL_RULES[currentLangCode as keyof typeof PLURAL_RULES](amount)\n : 0;\n\n return PLURAL_OPTIONS[optionIndex];\n}\n\nfunction processTemplate(template: string, value: any) {\n return template.replace(/%\\d?\\$?[sdf@]/, String(value));\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","// 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 const request = new Request(key);\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 const request = new Request(key);\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 { 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 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","// Copyright Twitter Inc. Licensed under MIT\n// https://github.com/twitter/twemoji-parser/blob/master/LICENSE.md\n// Version 09.05.2020\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 /(?:\\u2624|\\ud83d\\udc68\\ud83c\\udffb\\u200d\\ud83e\\udd1d\\u200d\\ud83d\\udc68\\ud83c[\\udffc-\\udfff]|\\ud83d\\udc68\\ud83c\\udffc\\u200d\\ud83e\\udd1d\\u200d\\ud83d\\udc68\\ud83c[\\udffb\\udffd-\\udfff]|\\ud83d\\udc68\\ud83c\\udffd\\u200d\\ud83e\\udd1d\\u200d\\ud83d\\udc68\\ud83c[\\udffb\\udffc\\udffe\\udfff]|\\ud83d\\udc68\\ud83c\\udffe\\u200d\\ud83e\\udd1d\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udffd\\udfff]|\\ud83d\\udc68\\ud83c\\udfff\\u200d\\ud83e\\udd1d\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udffe]|\\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\\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\\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\\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\\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\\ud83e\\udd1d\\u200d\\ud83e\\uddd1\\ud83c[\\udffb-\\udfff]|\\ud83e\\uddd1\\ud83c\\udffc\\u200d\\ud83e\\udd1d\\u200d\\ud83e\\uddd1\\ud83c[\\udffb-\\udfff]|\\ud83e\\uddd1\\ud83c\\udffd\\u200d\\ud83e\\udd1d\\u200d\\ud83e\\uddd1\\ud83c[\\udffb-\\udfff]|\\ud83e\\uddd1\\ud83c\\udffe\\u200d\\ud83e\\udd1d\\u200d\\ud83e\\uddd1\\ud83c[\\udffb-\\udfff]|\\ud83e\\uddd1\\ud83c\\udfff\\u200d\\ud83e\\udd1d\\u200d\\ud83e\\uddd1\\ud83c[\\udffb-\\udfff]|\\ud83e\\uddd1\\u200d\\ud83e\\udd1d\\u200d\\ud83e\\uddd1|\\ud83d\\udc6b\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc6c\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc6d\\ud83c[\\udffb-\\udfff]|\\ud83d[\\udc6b-\\udc6d])|(?:\\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\\uddd6-\\udddd])(?:\\ud83c[\\udffb-\\udfff])?\\u200d[\\u2640\\u2642]\\ufe0f|(?:\\ud83d\\udc68\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc8b\\u200d\\ud83d\\udc68|\\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\\u2764\\ufe0f\\u200d\\ud83d\\udc8b\\u200d\\ud83d[\\udc68\\udc69]|\\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\\u2764\\ufe0f\\u200d\\ud83d\\udc68|\\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\\u2764\\ufe0f\\u200d\\ud83d[\\udc68\\udc69]|\\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|\\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|\\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-\\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 { 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","// 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 Caledonia\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 {\n ApiLanguage, ApiMessage, ApiStickerSet, ApiShippingAddress,\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 interface ISettings extends Record<string, any> {\n messageTextSize: number;\n customBackground?: string;\n patternColor?: string;\n isBackgroundBlurred?: boolean;\n animationLevel: 0 | 1 | 2;\n messageSendKeyCombo: 'enter' | 'ctrl-enter';\n theme: 'light' | 'dark';\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 hasPrivateChatsNotifications?: boolean;\n hasPrivateChatsMessagePreview?: boolean;\n hasGroupNotifications?: boolean;\n hasGroupMessagePreview?: boolean;\n hasBroadcastNotifications?: boolean;\n hasBroadcastMessagePreview?: boolean;\n hasContactJoinedNotifications?: boolean;\n languages?: ApiLanguage[];\n language: 'en' | 'fr' | 'de' | 'it' | 'pt' | 'ru' | 'es' | 'uk';\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 FoldersIncludedChats,\n FoldersExcludedChats,\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}\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 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","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 {\n DEBUG_ALERT_MSG, GLOBAL_STATE_CACHE_KEY, GRAMJS_SESSION_ID_KEY,\n} 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;\nconst STARTUP_TIMEOUT = 5000;\n\nconst startedAt = Date.now();\nlet isReloading = false;\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 (isReloading) {\n return;\n }\n\n // For startup errors, we just clean the cache or the session and refresh the page.\n if (Date.now() - startedAt <= STARTUP_TIMEOUT) {\n if (localStorage.getItem(GLOBAL_STATE_CACHE_KEY)) {\n localStorage.removeItem(GLOBAL_STATE_CACHE_KEY);\n } else if (localStorage.getItem(GRAMJS_SESSION_ID_KEY)) {\n localStorage.removeItem(GRAMJS_SESSION_ID_KEY);\n } else {\n return;\n }\n\n isReloading = true;\n window.location.reload();\n\n return;\n }\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","import React from '../../../lib/teact/teact';\nimport EMOJI_REGEX, { removeVS16s } from '../../../lib/twemojiRegex';\n\nimport { RE_LINK_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, 'ig');\nconst RE_MENTION = /@[\\w\\d_-]+/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) || []), ...(part.match(RE_MENTION) || [])];\n if (!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 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","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.filter((prop) => currentProps[prop] !== newProps[prop]);\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 onClick?: (e: React.MouseEvent<HTMLAnchorElement>) => void;\n};\n\nconst Link: FC<OwnProps> = ({ children, className, onClick }) => {\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 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(user: ApiUser, lang: LangFn) {\n if (user.id === SERVICE_NOTIFICATIONS_USER_ID) {\n return lang('ServiceNotifications').toLowerCase();\n }\n\n if (user.type && user.type === 'userTypeBot') {\n return '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();\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 if (wasOnlineDate > today) {\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 today.setHours(0, 0, 0, 0);\n if (wasOnlineDate > yesterday) {\n return lang('LastSeen.YesterdayAt', formatTime(wasOnlineDate));\n }\n\n return lang('LastSeen.AtDate', formatFullDate(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) {\n return orderBy(userIds, (id) => {\n const now = Date.now() / 1000;\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 { ARCHIVED_FOLDER_ID } from '../../config';\nimport { orderBy } from '../../util/iteratees';\nimport { getUserFirstOrLastName } from './users';\nimport { getTranslation } from '../../util/langProvider';\nimport { LangFn } from '../../hooks/useLang';\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(chat: ApiChat, user?: ApiUser, isSelf = false) {\n if (isSelf || (user && chat.id === user.id && user.isSelf)) {\n return getTranslation('SavedMessages');\n }\n return chat.title || getTranslation('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 const { inviteLink } = chat.fullInfo || {};\n\n if (inviteLink && inviteLink.length) {\n return inviteLink;\n }\n\n return username ? `t.me/${username}` : '';\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(chat: ApiChat) {\n if (chat.currentUserBannedRights && chat.currentUserBannedRights.sendMessages) {\n return 'You are not allowed to send messages in this chat.';\n }\n if (chat.defaultBannedRights && chat.defaultBannedRights.sendMessages) {\n return 'Sending messages is not allowed in this chat.';\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\nexport function getChatOrder(chat: ApiChat) {\n return Math.max(chat.joinDate || 0, chat.lastMessage ? chat.lastMessage.date : 0);\n}\n\nexport function isChatArchived(chat: ApiChat) {\n return chat.folderId === ARCHIVED_FOLDER_ID;\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 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], folder, usersById, excludedChatIds, includedChatIds, 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 excludedChatIds?: Set<number>,\n includedChatIds?: Set<number>,\n pinnedChatIds?: Set<number>,\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 (chat.isMuted && folder.excludeMuted) {\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) {\n const [listIds] = prepareFolderListIds(chatsById, usersById, folder, 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 || (!chat.isMuted && (chat.unreadCount || chat.hasUnreadMark))\n ));\n\n return {\n unreadDialogsCount,\n hasActiveDialogs,\n };\n}\n\nexport function getFolderDescriptionText(\n chatsById: Record<number, ApiChat>,\n usersById: Record<number, ApiUser>,\n folder: ApiChatFolder,\n chatIdsCache: number[],\n lang: LangFn,\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);\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) {\n const [listIds, pinnedIds] = prepareFolderListIds(chatsById, usersById, folder, chatIdsCache);\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(chatId: number, sender?: ApiUser) {\n if (!sender || isChatPrivate(chatId)) {\n return undefined;\n }\n\n if (sender.isSelf) {\n return 'You';\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 += 3e9; // ~100 years in seconds\n }\n\n if (priorityIds && priorityIds.includes(id)) {\n // Assuming that last message date can't be less than 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 priority += Date.now() + (priorityIds.length - priorityIds.indexOf(id));\n }\n\n return priority;\n }, 'desc');\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 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}) => {\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 >\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 >\n {isLoading ? (\n <div>\n <span>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 { 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) {\n const eventName = resolveEventName(propName, element);\n if (canUseEventDelegation(eventName, element)) {\n addDelegatedListener(eventName, element, handler);\n } else {\n element.addEventListener(eventName, handler);\n }\n}\n\nexport function removeEventListener(element: HTMLElement, propName: string, handler: Handler) {\n const eventName = resolveEventName(propName, element);\n if (canUseEventDelegation(eventName, element)) {\n removeDelegatedListener(eventName, element);\n } else {\n element.removeEventListener(eventName, handler);\n }\n}\n\nfunction resolveEventName(propName: string, element: HTMLElement) {\n const eventName = propName.replace(/^on/, '').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) {\n return (\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, 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 { 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 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 const isClosing = Boolean(closeTimeoutRef.current);\n const shouldRender = isOpen || isClosing;\n const transitionClassNames = buildClassName(\n className && 'opacity-transition',\n className,\n hasOpenClassName && 'open',\n shouldRender && 'shown',\n isClosing && 'closing',\n );\n\n return {\n shouldRender,\n transitionClassNames,\n };\n};\n","import { getTranslation } from './langProvider';\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(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 getTranslation(`Weekday.Short${WEEKDAYS_FULL[date.getDay()]}`);\n }\n\n const withYear = date.getFullYear() !== today.getFullYear();\n const format = (\n getTranslation(withYear ? 'formatDateScheduleYear' : 'formatDateSchedule')\n || (withYear ? 'd MMM yyyy' : 'd MMM')\n );\n\n return formatDate(date, format);\n}\n\nexport function formatFullDate(datetime: number | Date) {\n const date = typeof datetime === 'number' ? new Date(datetime) : datetime;\n const format = getTranslation('formatterYearMax') || 'dd.MM.yyyy';\n\n return formatDate(date, format);\n}\n\nexport function formatMonthAndYear(date: Date, isShort = false) {\n const format = getTranslation(isShort ? 'formatterMonthYear2' : 'formatterMonthYear') || 'MMM yyyy';\n\n return formatDate(date, format);\n}\n\nexport function formatHumanDate(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)(getTranslation('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)(getTranslation('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(getTranslation(`Weekday.Short${weekDay}`))\n : upperFirst(getTranslation(`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 = getTranslation(formatKey) || 'd MMMM yyyy';\n\n return (isShort ? lowerFirst : upperFirst)(formatDate(date, format));\n}\n\nfunction formatDate(date: Date, format: string) {\n const day = date.getDate();\n const monthIndex = date.getMonth();\n\n return format\n .replace('LLLL', getTranslation(MONTHS_FULL[monthIndex]))\n .replace('MMMM', getTranslation(`Month.Gen${MONTHS_FULL[monthIndex]}`))\n .replace('MMM', getTranslation(`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(datetime: number | Date) {\n const date = typeof datetime === 'number' ? new Date(datetime) : datetime;\n\n return `${formatHumanDate(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) {\n return date.toLocaleString(\n 'en-US',\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 { 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 { callApi } from '../api/gramjs';\nimport { ApiChat, ApiMessage } from '../api/types';\nimport { renderActionMessageText } from '../components/common/helpers/renderActionMessageText';\nimport { DEBUG } from '../config';\nimport { getDispatch, getGlobal } from '../lib/teact/teactn';\nimport {\n getChatTitle,\n getMessageAction,\n getMessageSenderName,\n getNotificationText,\n getPrivateChatUserId,\n isActionMessage,\n isChatChannel,\n} from '../modules/helpers';\nimport { selectChatMessage, selectUser } from '../modules/selectors';\nimport { IS_SERVICE_WORKER_SUPPORTED } from './environment';\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\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\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\nexport async function subscribe() {\n await requestPermission();\n if (!checkIfPushSupported()) return;\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 }\n}\n\nasync function checkIfShouldNotify(chat: ApiChat) {\n if (chat.isMuted) return false;\n await getDispatch().loadNotificationsSettings();\n const global = getGlobal();\n switch (chat.type) {\n case 'chatTypePrivate':\n case 'chatTypeSecret':\n return Boolean(global.settings.byKey.hasPrivateChatsNotifications);\n case 'chatTypeBasicGroup':\n case 'chatTypeSuperGroup':\n return Boolean(global.settings.byKey.hasGroupNotifications);\n case 'chatTypeChannel':\n return Boolean(global.settings.byKey.hasBroadcastNotifications);\n }\n return false;\n}\n\nfunction getNotificationContent(chat: ApiChat, message: ApiMessage) {\n const global = getGlobal();\n const {\n senderId,\n replyToMessageId,\n } = message;\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 targetUserId: actionTargetUserId,\n targetChatId: actionTargetChatId,\n } = messageAction || {};\n const actionTargetUser = actionTargetUserId ? selectUser(global, actionTargetUserId) : undefined;\n const privateChatUserId = getPrivateChatUserId(chat);\n const privateChatUser = privateChatUserId ? selectUser(global, privateChatUserId) : undefined;\n let body: string;\n if (isActionMessage(message)) {\n const actionOrigin = chat && (isChatChannel(chat) || message.senderId === message.chatId)\n ? chat\n : messageSender;\n body = renderActionMessageText(\n message,\n actionOrigin,\n actionTargetUser,\n actionTargetMessage,\n actionTargetChatId,\n { asPlain: true },\n ) as string;\n } else {\n const senderName = getMessageSenderName(chat.id, messageSender);\n const summary = getNotificationText(message);\n\n body = senderName ? `${senderName}: ${summary}` : summary;\n }\n\n return {\n title: getChatTitle(chat, privateChatUser),\n body,\n };\n}\n\nexport async function showNewMessageNotification({\n chat,\n message,\n}: { chat: ApiChat; message: Partial<ApiMessage> }) {\n if (!checkIfNotificationsSupported()) return;\n if (!message.id) return;\n\n const shouldNotify = await checkIfShouldNotify(chat);\n if (!shouldNotify) return;\n\n const {\n title,\n body,\n } = getNotificationContent(chat, message as ApiMessage);\n\n const notification = new Notification(title, {\n body,\n icon: 'icon-192x192.png',\n badge: 'icon-192x192.png',\n tag: message.id.toString(),\n vibrate: [200, 100, 200],\n });\n\n if (navigator.serviceWorker.controller) {\n // notify service worker about new message notification\n navigator.serviceWorker.controller.postMessage({\n type: 'newMessageNotification',\n payload: { messageId: message.id },\n });\n }\n const dispatch = getDispatch();\n\n notification.onclick = () => {\n notification.close();\n dispatch.focusMessage({\n chatId: chat.id,\n messageId: message.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","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';\n\nimport './MenuItem.scss';\n\ntype OnClickHandler = (e: React.SyntheticEvent<HTMLDivElement>) => 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 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}`} />\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=\"_blank\"\n rel=\"noopener noreferrer\"\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 >\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 { 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 { 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\nexport function updateChat(\n global: GlobalState, chatId: number, chatUpdate: Partial<ApiChat>, photo?: ApiPhoto,\n): GlobalState {\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 global;\n }\n\n return replaceChats(global, {\n ...byId,\n [chatId]: updatedChat,\n });\n}\n\nexport function updateChats(global: GlobalState, updatedById: Record<number, ApiChat>): GlobalState {\n Object.keys(updatedById).forEach((id) => {\n global = updateChat(global, Number(id), updatedById[Number(id)]);\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 Object.keys(addedById).map(Number).forEach((id) => {\n if (!byId[id] || (byId[id].isMin && !addedById[id].isMin)) {\n global = updateChat(global, id, addedById[id]);\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 { GlobalState, MessageListType, Thread } from '../../global/types';\nimport { ApiMessage, ApiThreadInfo, MAIN_THREAD_ID } from '../../api/types';\nimport { FocusDirection } from '../../types';\n\nimport { 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\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): GlobalState {\n return {\n ...global,\n messages: {\n ...global.messages,\n // TODO Support stack navigation\n messageLists: chatId ? [{ chatId, threadId, type }] : undefined,\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 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\n messageIds.forEach((messageId) => {\n if (listedIds && listedIds.includes(messageId)) {\n listedIds = listedIds.filter((id) => id !== messageId);\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 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\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}\nexport function updateUser(global: GlobalState, userId: number, userUpdate: Partial<ApiUser>): GlobalState {\n const { byId } = global.users;\n const { hash, userIds: contactUserIds } = global.contactList || {};\n const user = byId[userId];\n const shouldOmitMinInfo = userUpdate.isMin && user && !user.isMin;\n const updatedUser = {\n ...user,\n ...(shouldOmitMinInfo ? omit(userUpdate, ['isMin', 'accessHash']) : userUpdate),\n };\n\n if (!updatedUser.id || !updatedUser.type) {\n return global;\n }\n\n if (updatedUser.isContact && (contactUserIds && !contactUserIds.includes(userId))) {\n global = {\n ...global,\n contactList: {\n hash: hash || 0,\n userIds: [userId, ...contactUserIds],\n },\n };\n }\n\n return replaceUsers(global, {\n ...byId,\n [userId]: updatedUser,\n });\n}\n\nexport function updateUsers(global: GlobalState, updatedById: Record<number, ApiUser>): GlobalState {\n Object.keys(updatedById).map(Number).forEach((id) => {\n global = updateUser(global, id, updatedById[id]);\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 Object.keys(addedById).map(Number).forEach((id) => {\n if (!byId[id] || (byId[id].isMin && !addedById[id].isMin)) {\n global = updateUser(global, id, addedById[id]);\n }\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","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 { ISettings } from '../../types';\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 updateNotifySettings(\n global: GlobalState, peerType: 'contact' | 'group' | 'broadcast', isSilent?: boolean, isShowPreviews?: boolean,\n) {\n switch (peerType) {\n case 'contact':\n return replaceSettings(global, {\n ...(typeof isSilent !== 'undefined' && { hasPrivateChatsNotifications: !isSilent }),\n ...(typeof isShowPreviews !== 'undefined' && { hasPrivateChatsMessagePreview: isShowPreviews }),\n });\n case 'group':\n return replaceSettings(global, {\n ...(typeof isSilent !== 'undefined' && { hasGroupNotifications: !isSilent }),\n ...(typeof isShowPreviews !== 'undefined' && { hasGroupMessagePreview: isShowPreviews }),\n });\n case 'broadcast':\n return replaceSettings(global, {\n ...(typeof isSilent !== 'undefined' && { hasBroadcastNotifications: !isSilent }),\n ...(typeof isShowPreviews !== 'undefined' && { hasBroadcastMessagePreview: isShowPreviews }),\n });\n\n default:\n return undefined;\n }\n}\n\nexport function addBlockedContact(global: GlobalState, contactId: number): GlobalState {\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 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","import { ChangeEvent, FormEvent, RefObject } from 'react';\nimport React, { FC, memo } from '../../lib/teact/teact';\n\nimport buildClassName from '../../util/buildClassName';\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};\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}) => {\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}>\n <input\n ref={ref}\n className=\"form-control\"\n type=\"text\"\n id={id}\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 />\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';\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 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}>\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\">{label}</span>\n {subLabel && <span className=\"subLabel\">{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","import { useEffect } from '../lib/teact/teact';\n\nconst ANIMATION_START_EVENT = 'tt-event-heavy-animation-start';\nconst ANIMATION_END_EVENT = 'tt-event-heavy-animation-end';\n\nlet timeout: number | undefined;\nlet isAnimating = false;\n\nexport const dispatchHeavyAnimationEvent = (duration: number) => {\n document.dispatchEvent(new Event(ANIMATION_START_EVENT));\n isAnimating = true;\n\n if (timeout) {\n clearTimeout(timeout);\n timeout = undefined;\n }\n\n timeout = window.setTimeout(() => {\n isAnimating = false;\n document.dispatchEvent(new Event(ANIMATION_END_EVENT));\n timeout = undefined;\n }, duration);\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","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","const RE_NOT_LETTER = /[^\\wа-яё]+/;\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 { 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';\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 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}) => {\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 { transitionClassNames } = useShowTransition(isOpen, onCloseAnimationEnd);\n\n useEffect(() => (isOpen && onClose ? captureEscKeyListener(onClose) : undefined), [isOpen, onClose]);\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);\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","import { RefObject } from 'react';\nimport { useState, useCallback, useEffect } from '../lib/teact/teact';\n\nexport default (\n elementRef: RefObject<HTMLElement>,\n isOpen: boolean,\n onSelectWithEnter?: () => void,\n) => {\n const [focusedIndex, setFocusedIndex] = useState(-1);\n\n useEffect(() => {\n setFocusedIndex(-1);\n }, [isOpen]);\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();\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(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 }, [focusedIndex, elementRef, onSelectWithEnter]);\n\n return handleKeyDown;\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,\n} from '../config';\nimport { callApi, cancelApiProgress } from '../api/gramjs';\nimport * as cacheApi from './cacheApi';\nimport { 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 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 { throttle } from './schedulers';\n\ntype IDimensions = {\n width: number;\n height: number;\n};\n\nlet windowSize = updateSizes();\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\nconst handleResize = throttle(() => {\n windowSize = updateSizes();\n}, 250, true);\n\nwindow.addEventListener('resize', handleResize);\nwindow.addEventListener('orientationchange', handleResize);\n\nexport default {\n get: () => windowSize,\n};\n","type HandlerName = 'onEnter' | 'onBackspace' | 'onDelete' | 'onEsc' | 'onUp' | 'onDown' | '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 Tab: 'onTab',\n};\n\nconst handlers: Record<HandlerName, Handler[]> = {\n onEnter: [],\n onDelete: [],\n onBackspace: [],\n onEsc: [],\n onUp: [],\n onDown: [],\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","/* 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 { withGlobal } from '../../lib/teact/teactn';\nimport convertPunycode from '../../lib/punycode';\nimport { GlobalActions } from '../../global/types';\n\nimport { DEBUG, RE_TME_INVITE_LINK, RE_TME_LINK } from '../../config';\nimport { pick } from '../../util/iteratees';\nimport buildClassName from '../../util/buildClassName';\n\ntype OwnProps = {\n url?: string;\n text: string;\n className?: string;\n children?: any;\n};\n\ntype DispatchProps = Pick<GlobalActions, 'openTelegramLink'>;\n\nconst SafeLink: FC<OwnProps & DispatchProps> = ({\n url,\n text,\n className,\n children,\n openTelegramLink,\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 return true;\n }\n\n e.preventDefault();\n openTelegramLink({ url });\n\n return false;\n }, [openTelegramLink, 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={getHref(url)}\n title={getDecodedUrl(url)}\n target=\"_blank\"\n rel=\"noopener noreferrer\"\n className={classNames}\n onClick={handleClick}\n >\n {children || text}\n </a>\n );\n};\n\nfunction getHref(url?: string) {\n if (!url) {\n return undefined;\n }\n\n return url.includes('://') ? url : `http://${url}`;\n}\n\nfunction getDecodedUrl(url?: string) {\n if (!url) {\n return undefined;\n }\n\n const href = getHref(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(withGlobal<OwnProps>(\n undefined,\n (setGlobal, actions): DispatchProps => pick(actions, ['openTelegramLink']),\n)(SafeLink));\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) => {\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);\n};\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","const 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 getShippingError(errors: Record<number, { message: string }>) {\n return Object.values(errors).reduce((acc, cur) => {\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 children: any;\n};\n\nconst DropdownMenu: FC<OwnProps> = ({\n trigger,\n className,\n children,\n positionX = 'left',\n positionY = 'top',\n footer,\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 };\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 };\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}\n className={className || ''}\n positionX={positionX}\n positionY={positionY}\n footer={footer}\n autoClose\n onClose={handleClose}\n >\n {children}\n </Menu>\n </div>\n );\n};\n\nexport default DropdownMenu;\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 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);\n } else if (key.startsWith('data-')) {\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);\n } else if (key.startsWith('data-')) {\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","// @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","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 {\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 message: ApiMessage,\n actionOrigin?: ApiUser | ApiChat,\n targetUser?: ApiUser,\n targetMessage?: ApiMessage,\n targetChatId?: number,\n options: ActionMessageTextOptions = {},\n) {\n if (!message.content.action) {\n return [];\n }\n const { text } = message.content.action;\n const content: TextPart[] = [];\n const textOptions: ActionMessageTextOptions = { ...options, maxTextLength: 16 };\n\n let unprocessed: string;\n let processed = processPlaceholder(\n text,\n '%action_origin%',\n actionOrigin\n ? (!options.isEmbedded && renderOriginContent(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 targetUser\n ? renderUserContent(targetUser, options.asPlain)\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(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(message: ApiMessage, options: ActionMessageTextOptions = {}) {\n const text = getMessageSummaryText(message);\n const {\n photo, video, document, sticker,\n } = getMessageContent(message);\n\n const showQuotes = text && !photo && !video && !document && !sticker;\n let messageText = trimText(text as string, options.maxTextLength)!;\n\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 if (options.asPlain) {\n return showQuotes ? `«${messageText}»` : messageText;\n }\n\n if (showQuotes) {\n return (\n <span>\n &laquo;\n <MessageLink className=\"action-link\" message={message}>{renderText(messageText)}</MessageLink>\n &raquo;\n </span>\n );\n }\n\n return (\n <MessageLink className=\"action-link\" message={message}>{renderText(messageText)}</MessageLink>\n );\n}\n\nfunction renderOriginContent(origin: ApiUser | ApiChat, asPlain?: boolean) {\n return isChat(origin)\n ? renderChatContent(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(chat: ApiChat, asPlain?: boolean): string | TextPart | undefined {\n const text = trimText(getChatTitle(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[] {\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 content.push(replaceValue);\n content.push(text.substring(placeholderPosition + placeholder.length));\n\n return content;\n}\n","export interface ApiPhotoSize {\n type: 's' | 'm' | 'x' | 'y' | 'z';\n width: number;\n height: number;\n}\n\nexport interface ApiThumbnail {\n dataUri: string;\n height: number;\n width: number;\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}\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}\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 targetUserId?: number;\n targetChatId?: number;\n type: 'historyClear' | 'other';\n photo?: ApiPhoto;\n}\n\nexport interface ApiWebPage {\n id: number;\n url: string;\n displayUrl: string;\n siteName?: string;\n title?: string;\n description?: string;\n photo?: ApiPhoto;\n hasDocument?: true;\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 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[][];\n\nexport type ApiMessageSearchType = 'text' | 'media' | 'documents' | 'links' | 'audio' | 'profilePhoto';\nexport type ApiGlobalMessageSearchType = 'text' | 'media' | 'documents' | 'links' | 'audio' | 'voice';\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.\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 { 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('disable-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('disable-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","// 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])) {\n category.emojis.push(emojiRaw[1]);\n emojiData.emojis[emojiRaw[1]] = {\n id: emojiRaw[1],\n colons: `:${emojiRaw[1]}:`,\n native: unifiedToNative(emojiRaw[0]),\n image: emojiRaw[0].toLowerCase(),\n };\n }\n }\n\n emojiData.categories.push(category);\n }\n\n return emojiData;\n}\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\">\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 { 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__ + \"f52f8cb8dd6763aaca42.worker.js\");\n};","module.exports = function() {\n return new Worker(__webpack_public_path__ + \"01705582fc3eca0e007b.worker.js\");\n};","module.exports = function() {\n return new Worker(__webpack_public_path__ + \"0dbbe0a906f6c2adf071.worker.js\");\n};","module.exports = function() {\n return new Worker(__webpack_public_path__ + \"a66075669d8d0ac2d740.worker.js\");\n};","import { addReducer } from '../../../lib/teact/teactn';\n\nimport {\n IS_ANDROID, IS_IOS, IS_SAFARI, IS_TOUCH_ENV,\n} from '../../../util/environment';\nimport { setLanguage } from '../../../util/langProvider';\nimport switchTheme from '../../../util/switchTheme';\n\naddReducer('init', (global) => {\n const {\n theme, animationLevel, messageTextSize, language,\n } = global.settings.byKey;\n\n setLanguage(language);\n\n document.documentElement.style.setProperty('--message-text-size', `${messageTextSize}px`);\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 > 0);\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 }\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","import {\n addReducer, getDispatch, getGlobal, setGlobal,\n} from '../../../lib/teact/teactn';\n\nimport { GlobalState } from '../../../global/types';\n\nimport {\n LANG_CACHE_NAME,\n CUSTOM_BG_CACHE_NAME,\n GRAMJS_SESSION_ID_KEY,\n MEDIA_CACHE_NAME,\n MEDIA_CACHE_NAME_AVATARS,\n MEDIA_PROGRESSIVE_CACHE_NAME,\n} from '../../../config';\nimport { initApi, callApi } from '../../../api/gramjs';\nimport { unsubscribe } from '../../../util/notifications';\nimport * as cacheApi from '../../../util/cacheApi';\n\naddReducer('initApi', (global: GlobalState, actions) => {\n const sessionId = localStorage.getItem(GRAMJS_SESSION_ID_KEY) || undefined;\n\n void initApi(actions.apiUpdate, sessionId);\n\n return {\n ...global,\n authIsSessionRemembered: Boolean(sessionId),\n };\n});\n\naddReducer('setAuthPhoneNumber', (global, actions, payload) => {\n const { phoneNumber } = payload!;\n\n void callApi('provideAuthPhoneNumber', phoneNumber);\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('gotToAuthQrCode', (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 { sessionId } = payload!;\n localStorage.setItem(GRAMJS_SESSION_ID_KEY, sessionId);\n});\n\naddReducer('signOut', () => {\n (async () => {\n await unsubscribe();\n await callApi('destroy');\n\n getDispatch().reset();\n })();\n});\n\naddReducer('reset', () => {\n localStorage.removeItem(GRAMJS_SESSION_ID_KEY);\n\n cacheApi.clear(MEDIA_CACHE_NAME);\n cacheApi.clear(MEDIA_CACHE_NAME_AVATARS);\n cacheApi.clear(MEDIA_PROGRESSIVE_CACHE_NAME);\n cacheApi.clear(CUSTOM_BG_CACHE_NAME);\n cacheApi.clear(LANG_CACHE_NAME);\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\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 {\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 ApiUpdateCurrentUser,\n} from '../../../api/types';\nimport { DEBUG } from '../../../config';\nimport { subscribe } from '../../../util/notifications';\nimport { updateUser } from '../../reducers';\nimport { setLanguage } from '../../../util/langProvider';\n\naddReducer('apiUpdate', (global, actions, update: ApiUpdate) => {\n if (DEBUG) {\n if (update['@type'] !== 'updateUserStatus') {\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 'updateCurrentUser':\n onUpdateCurrentUser(update);\n break;\n\n case 'error':\n if (update.error.message === 'SESSION_REVOKED') {\n actions.signOut();\n }\n\n actions.showError({ error: update.error });\n\n break;\n }\n});\n\nfunction onUpdateApiReady(global: GlobalState) {\n 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 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 setGlobal({\n ...global,\n isLoggingOut: false,\n lastSyncTime: Date.now(),\n });\n\n const { sessionId } = update;\n if (sessionId && global.authRememberMe) {\n getDispatch().saveSession({ sessionId });\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 onUpdateCurrentUser(update: ApiUpdateCurrentUser) {\n const { currentUser } = update;\n\n setGlobal({\n ...updateUser(getGlobal(), currentUser.id, currentUser),\n currentUserId: currentUser.id,\n });\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_SERVICE_WORKER_SUPPORTED } from './environment';\n\ntype WorkerAction = {\n type: string;\n payload: Record<string, any>;\n};\n\n\nfunction handleWorkerMessage(e: MessageEvent) {\n const action:WorkerAction = e.data;\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('[SW] New action from service worker', action);\n }\n if (!action.type) return;\n const dispatch = getDispatch();\n switch (action.type) {\n case 'focusMessage':\n dispatch.focusMessage(action.payload);\n break;\n }\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\n navigator.serviceWorker.addEventListener('message', handleWorkerMessage);\n } else {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error('[SW] ServiceWorker not available');\n }\n getDispatch().showError({ error: { message: 'SERVICE_WORKER_DISABLED' } });\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}\n","import { GlobalState } from './types';\n\nimport { ANIMATION_LEVEL_DEFAULT, DEFAULT_MESSAGE_TEXT_SIZE_PX, DEFAULT_PATTERN_COLOR } from '../config';\n\nexport const INITIAL_STATE: GlobalState = {\n isLeftColumnShown: true,\n isChatInfoShown: false,\n uiReadyState: 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 },\n\n scheduledMessages: {\n byChatId: {},\n },\n\n chatFolders: {\n byId: {},\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 featured: {\n setIds: [],\n },\n search: {},\n forEmoji: {},\n },\n\n gifs: {\n saved: {},\n search: {},\n },\n\n globalSearch: {},\n\n localTextSearch: {\n byChatThreadKey: {},\n },\n\n localMediaSearch: {\n byChatId: {},\n },\n\n management: {\n byChatId: {},\n },\n\n topPeers: {},\n\n mediaViewer: {},\n\n audioPlayer: {},\n\n forwardMessages: {},\n\n pollResults: {},\n\n payment: {},\n\n notifications: [],\n\n errors: [],\n\n activeSessions: [],\n\n settings: {\n byKey: {\n messageTextSize: DEFAULT_MESSAGE_TEXT_SIZE_PX,\n isBackgroundBlurred: true,\n patternColor: DEFAULT_PATTERN_COLOR,\n animationLevel: ANIMATION_LEVEL_DEFAULT,\n messageSendKeyCombo: 'enter',\n theme: 'light',\n shouldAutoDownloadMediaFromContacts: true,\n shouldAutoDownloadMediaInPrivateChats: true,\n shouldAutoDownloadMediaInGroups: true,\n shouldAutoDownloadMediaInChannels: true,\n shouldAutoPlayGifs: true,\n shouldAutoPlayVideos: true,\n shouldSuggestStickers: true,\n shouldLoopStickers: true,\n language: 'en',\n },\n privacy: {},\n },\n\n twoFaSettings: {},\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 { 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 GRAMJS_SESSION_ID_KEY,\n MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN, GLOBAL_STATE_CACHE_USER_LIST_LIMIT,\n} from '../config';\nimport { IS_MOBILE_SCREEN } from '../util/environment';\nimport { pick } from '../util/iteratees';\nimport { INITIAL_STATE } from './initial';\nimport { selectCurrentMessageList } from '../modules/selectors';\n\nconst UPDATE_THROTTLE = 1000;\n\nconst updateCacheThrottled = throttle(updateCache, UPDATE_THROTTLE, false);\n\nlet isAllowed = false;\n\nexport function initCache() {\n if (GLOBAL_STATE_CACHE_DISABLED) {\n return;\n }\n\n addReducer('saveSession', () => {\n isAllowed = true;\n addCallback(updateCacheThrottled);\n });\n\n addReducer('reset', () => {\n isAllowed = false;\n removeCallback(updateCacheThrottled);\n localStorage.removeItem(GLOBAL_STATE_CACHE_KEY);\n });\n}\n\nexport function loadCache(initialState: GlobalState) {\n if (!GLOBAL_STATE_CACHE_DISABLED) {\n const hasActiveSession = localStorage.getItem(GRAMJS_SESSION_ID_KEY);\n if (hasActiveSession) {\n isAllowed = true;\n addCallback(updateCacheThrottled);\n return readCache(initialState);\n } else {\n isAllowed = false;\n }\n }\n\n return undefined;\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 for new settings which may be missing in older cache\n cached.settings.byKey = {\n ...initialState.settings.byKey,\n ...cached.settings.byKey,\n };\n }\n\n return {\n ...initialState,\n ...cached,\n };\n}\n\nfunction updateCache() {\n onIdle(() => {\n if (!isAllowed) {\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 'authIsSessionRemembered',\n 'authNearestCountry',\n 'currentUserId',\n 'contactList',\n 'chatFolders',\n 'topPeers',\n 'recentEmojis',\n 'push',\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 };\n\n const json = JSON.stringify(reducedGlobal);\n localStorage.setItem(GLOBAL_STATE_CACHE_KEY, json);\n });\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_MOBILE_SCREEN ? undefined : [{\n ...currentMessageList,\n threadId: MAIN_THREAD_ID,\n type: 'thread',\n }],\n };\n}\n\nfunction reduceSettings(global: GlobalState): GlobalState['settings'] {\n const { byKey } = global.settings;\n\n return {\n byKey,\n privacy: {},\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';\nimport { selectCurrentMessageList } from '../modules/selectors';\n\ninitCache();\n\naddReducer('init', () => {\n const initial = cloneDeep(INITIAL_STATE);\n const newGlobal = loadCache(initial) || initial;\n\n const currentMessageList = selectCurrentMessageList(newGlobal) || {};\n window.history.replaceState(currentMessageList, '');\n\n return newGlobal;\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 } from '../../modules/selectors';\n\ntype OwnProps = {\n page: 'main' | 'authCode' | 'authPassword' | 'authPhoneNumber' | 'authQrCode';\n children: any;\n};\n\ntype StateProps = Pick<GlobalState, 'uiReadyState'> & {\n hasCustomBackground?: boolean;\n isCustomBackgroundColor: 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 isCustomBackgroundColor,\n isRightColumnShown,\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 Promise.race([\n pause(MAX_PRELOAD_DELAY),\n preloadTasks[page](),\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 && (\n <div className={buildClassName('mask', transitionClassNames)}>\n {page === 'main' ? (\n <>\n <div className=\"left\" />\n <div\n className={buildClassName(\n 'middle',\n hasCustomBackground && !isCustomBackgroundColor && 'custom-bg-image',\n hasCustomBackground && isCustomBackgroundColor && '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 return {\n uiReadyState: global.uiReadyState,\n hasCustomBackground: Boolean(global.settings.byKey.customBackground),\n isCustomBackgroundColor: Boolean((global.settings.byKey.customBackground || '').match(/^#[a-f\\d]{6,8}$/i)),\n isRightColumnShown: selectIsRightColumnShown(global),\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, ['setIsUiReady']),\n)(UiLoader);\n","import React, {\n FC, useState, memo, useCallback, useRef,\n} from '../../lib/teact/teact';\n\nimport { countryList } from '../../util/phoneNumber';\nimport searchWords from '../../util/searchWords';\nimport buildClassName from '../../util/buildClassName';\nimport renderText from '../common/helpers/renderText';\n\nimport DropdownMenu from '../ui/DropdownMenu';\nimport MenuItem from '../ui/MenuItem';\nimport Spinner from '../ui/Spinner';\n\nimport './CountryCodeInput.scss';\nimport { ANIMATION_END_DELAY } from '../../config';\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 // 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>Country</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>No countries matched your filter.</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 { GlobalActions, GlobalState } from '../../global/types';\nimport React, {\n FC, memo, useCallback, useEffect, useLayoutEffect, useRef, useState,\n} from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\nimport { 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';\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)>;\ntype DispatchProps = Pick<GlobalActions, (\n 'setAuthPhoneNumber' | 'setAuthRememberMe' | 'loadNearestCountry' | 'clearAuthError' | 'gotToAuthQrCode'\n)>;\n\nconst MIN_NUMBER_LENGTH = 10;\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 setAuthPhoneNumber,\n setAuthRememberMe,\n loadNearestCountry,\n clearAuthError,\n gotToAuthQrCode,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const inputRef = useRef<HTMLInputElement>(null);\n\n const [country, setCountry] = useState<Country | undefined>();\n const [phoneNumber, setPhoneNumber] = useState<string>();\n const [isTouched, setIsTouched] = useState(false);\n const [lastSelection, setLastSelection] = useState<[number, number] | undefined>();\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 const suggestedCountry = getCountryFromPhoneNumber(newFullNumber);\n const selectedCountry = !country || (suggestedCountry && suggestedCountry.id !== country.id)\n ? suggestedCountry\n : country;\n\n if (!newFullNumber.length) {\n setCountry(undefined);\n } else if (!country || (selectedCountry && selectedCountry.code !== country.code)) {\n setCountry(selectedCountry);\n }\n\n setPhoneNumber(formatPhoneNumber(newFullNumber, selectedCountry));\n }, [country]);\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 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 parseFullNumber(value);\n }, [authError, clearAuthError, 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>Sign in to Telegram</h2>\n <p className=\"note\">\n Please confirm your country and\n <br />enter your phone number.\n </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=\"Phone Number\"\n value={fullNumber}\n error={authError}\n inputMode=\"tel\"\n onChange={handlePhoneNumberChange}\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}>Next</Button>\n ) : (\n <Loading />\n )\n )}\n {isAuthReady && (\n <Button isText ripple isLoading={authIsLoadingQrCode} onClick={gotToAuthQrCode}>\n Log in by QR code\n </Button>\n )}\n </form>\n </div>\n </div>\n );\n};\n\nexport default memo(withGlobal(\n (global): StateProps => pick(global, [\n 'connectionState',\n 'authState',\n 'authPhoneNumber',\n 'authIsLoading',\n 'authIsLoadingQrCode',\n 'authError',\n 'authRememberMe',\n 'authNearestCountry',\n ]),\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'setAuthPhoneNumber',\n 'setAuthRememberMe',\n 'clearAuthError',\n 'loadNearestCountry',\n 'gotToAuthQrCode',\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","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 AuthQrCodeAsync: FC = () => {\n const AuthQrCode = useModuleLoader(Bundles.Auth, 'AuthQrCode');\n\n return AuthQrCode ? <AuthQrCode /> : <Loading />;\n};\n\nexport default memo(AuthQrCodeAsync);\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';\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.async';\n\nimport './Auth.scss';\n\ntype StateProps = Pick<GlobalState, 'authState'>;\ntype DispatchProps = Pick<GlobalActions, 'reset' | 'initApi'>;\n\nconst Auth: FC<StateProps & DispatchProps> = ({ authState, reset, initApi }) => {\n useEffect(() => {\n reset();\n initApi();\n }, [reset, initApi]);\n\n useEffect(() => {\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 'authorizationStateWaitQrCode':\n return <UiLoader page=\"authQrCode\" key=\"authQrCode\"><AuthQrCode /></UiLoader>;\n case 'authorizationStateWaitPhoneNumber':\n default:\n return <UiLoader page=\"authPhoneNumber\" key=\"authPhoneNumber\"><AuthPhoneNumber /></UiLoader>;\n }\n};\n\nexport default memo(withGlobal(\n (global): StateProps => pick(global, ['authState']),\n (global, actions): DispatchProps => pick(actions, ['reset', 'initApi']),\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';\n// import Test from './components/test/TestNoRedundancy';\n\ntype StateProps = Pick<GlobalState, 'authState' | 'authIsSessionRemembered'>;\ntype DispatchProps = Pick<GlobalActions, 'disconnect'>;\n\nconst App: FC<StateProps & DispatchProps> = ({ authState, authIsSessionRemembered, 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 authIsSessionRemembered ? 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', 'authIsSessionRemembered']),\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":""}