mirror of
https://github.com/danog/telegram-tt.git
synced 2024-12-11 16:49:44 +01:00
1 line
722 KiB
Plaintext
1 line
722 KiB
Plaintext
{"version":3,"file":"main.796ebda225409aa7e740.js","mappings":"uBACIA,EADAC,ECAAC,EACAC,ECwCAC,EASAC,E,8ECpCJ,IAAIC,EACJ,MAAMC,EAAgB,IAAIC,IACpBC,EAA0B,IAAID,IAI7B,SAASE,EAAQC,EAAuBC,GAW7C,OAVKN,IACCO,EAAAA,IAEFC,QAAQC,IAAI,yBAGdT,EAAS,IAAIU,OAAO,IAAIC,IAAI,mBAyChC,SAA2BN,GACzBL,EAAOY,iBAAiB,WAAW,EAAGC,KAAAA,MACpC,GAAkB,WAAdA,EAAKC,KACPT,EAASQ,EAAKE,aACT,GAAkB,mBAAdF,EAAKC,KAA2B,CACzC,MAAME,EAAef,EAAcgB,IAAIJ,EAAKK,WACxCF,IACEH,EAAKM,MACPH,EAAaI,OAAOP,EAAKM,OAEzBH,EAAaK,QAAQR,EAAKS,gBAGzB,GAAkB,mBAAdT,EAAKC,KAA2B,CACzC,MAAME,EAAef,EAAcgB,IAAIJ,EAAKK,WACxCF,GAAgBA,EAAaO,UAC/BP,EAAaO,YAAYV,EAAKW,mBAE3B,GAAkB,mBAAdX,EAAKC,KACd,MAAMD,EAAKM,SA3DbM,CAAkBpB,IAGbqB,EAAY,CACjBZ,KAAM,UACNa,KAAM,CAACrB,KAIJ,SAASsB,EAAiCC,KAAcF,GAC7D,GAAK3B,EASL,OAAO0B,EAAY,CACjBZ,KAAM,aACNgB,KAAMD,EACNF,KAAAA,IAXIpB,EAAAA,IAEFC,QAAQuB,KAAK,0BAaZ,SAASC,EAAkBC,GAChCA,EAAiBC,YAAa,EAE9B,MAAM,UAAEhB,GAAcf,EAAwBc,IAAIgB,IAAqB,GAClEf,GAILlB,EAAOmC,YAAY,CACjBrB,KAAM,iBACNI,UAAAA,IA4BJ,SAASQ,EAAYU,GACnB,MAAMlB,GAAYmB,EAAAA,EAAAA,GAA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ACF,OAAQA,GACN,IAAK,oCACL,IAAK,6BACL,IAAK,iCACL,IAAK,qCACL,IAAK,+BACH,OAAO,mBAAC,GAAD,MACT,IAAK,2BACL,IAAK,4BACL,IAAK,+BACL,IAAK,0BACH,OAAO+lD,KAIb,OAAOvV,EAAAA,EAAAA,KAAiB,GAAQuV,KAAe,mBAAC,GAAD,SC1C7Cr/E,EAAAA,IAEFC,QAAQC,IAAI,aAGdyG,EAAAA,EAAAA,MAAc+sB,OAEV1zB,EAAAA,IAEFC,QAAQC,IAAI,4BAGdu/E,EAAAA,EAAAA,OACE,mBAAC,GAAD,MACAp3E,SAASywE,eAAe,SAGtB94E,EAAAA,IAEFC,QAAQC,IAAI,6BAGdmI,SAAShI,iBAAiB,YAAY,KAEpCJ,QAAQC,IAAI,gBAAgBmxB,EAAAA,EAAAA,W","sources":["webpack://telegram-t/webpack/runtime/create fake namespace object","webpack://telegram-t/webpack/runtime/load script","webpack://telegram-t/webpack/runtime/css loading","webpack://telegram-t/./src/api/gramjs/worker/provider.ts","webpack://telegram-t/./src/api/types/media.ts","webpack://telegram-t/./src/api/types/messages.ts","webpack://telegram-t/./src/lib/punycode.js","webpack://telegram-t/./src/components/common/SafeLink.tsx","webpack://telegram-t/./src/components/common/helpers/documentInfo.ts","webpack://telegram-t/./src/components/common/helpers/parseEmojiOnlyString.ts","webpack://telegram-t/./src/components/common/UserLink.tsx","webpack://telegram-t/./src/components/common/MessageLink.tsx","webpack://telegram-t/./src/components/common/ChatLink.tsx","webpack://telegram-t/./src/components/common/helpers/renderActionMessageText.tsx","webpack://telegram-t/./src/components/common/helpers/renderText.tsx","webpack://telegram-t/./src/components/middle/message/MentionLink.tsx","webpack://telegram-t/./src/components/ui/Button.tsx","webpack://telegram-t/./src/components/ui/Checkbox.tsx","webpack://telegram-t/./src/components/ui/DropdownMenu.tsx","webpack://telegram-t/./src/components/ui/InputText.tsx","webpack://telegram-t/./src/components/ui/Link.tsx","webpack://telegram-t/./src/components/ui/Loading.tsx","webpack://telegram-t/./src/components/ui/Menu.tsx","webpack://telegram-t/./src/components/ui/MenuItem.tsx","webpack://telegram-t/./src/components/ui/RippleEffect.tsx","webpack://telegram-t/./src/components/ui/Spinner.tsx","webpack://telegram-t/./src/config.ts","webpack://telegram-t/./src/hooks/useEffectWithPrevDeps.ts","webpack://telegram-t/./src/hooks/useFlag.ts","webpack://telegram-t/./src/hooks/useForceUpdate.ts","webpack://telegram-t/./src/hooks/useHeavyAnimationCheck.ts","webpack://telegram-t/./src/hooks/useHistoryBack.ts","webpack://telegram-t/./src/hooks/useKeyboardListNavigation.ts","webpack://telegram-t/./src/hooks/useLang.ts","webpack://telegram-t/./src/hooks/useModuleLoader.ts","webpack://telegram-t/./src/hooks/useOnChange.ts","webpack://telegram-t/./src/hooks/usePrevious.ts","webpack://telegram-t/./src/hooks/useShowTransition.ts","webpack://telegram-t/./src/hooks/useVirtualBackdrop.ts","webpack://telegram-t/./src/lib/teact/dom-events.ts","webpack://telegram-t/./src/lib/teact/teact-dom.ts","webpack://telegram-t/./src/lib/teact/teact.ts","webpack://telegram-t/./src/lib/teact/teactn.tsx","webpack://telegram-t/./src/lib/twemojiRegex.js","webpack://telegram-t/./src/modules/actions/api/initial.ts","webpack://telegram-t/./src/modules/actions/api/settings.ts","webpack://telegram-t/./src/modules/actions/apiUpdaters/initial.ts","webpack://telegram-t/./src/modules/actions/ui/initial.ts","webpack://telegram-t/./src/modules/actions/ui/settings.ts","webpack://telegram-t/./src/modules/helpers/chats.ts","webpack://telegram-t/./src/modules/helpers/messages.ts","webpack://telegram-t/./src/modules/helpers/messageMedia.ts","webpack://telegram-t/./src/modules/helpers/localSearch.ts","webpack://telegram-t/./src/modules/helpers/payments.ts","webpack://telegram-t/./src/modules/helpers/users.ts","webpack://telegram-t/./src/modules/reducers/chats.ts","webpack://telegram-t/./src/modules/reducers/messages.ts","webpack://telegram-t/./src/modules/reducers/symbols.ts","webpack://telegram-t/./src/modules/reducers/users.ts","webpack://telegram-t/./src/modules/reducers/globalSearch.ts","webpack://telegram-t/./src/modules/reducers/localSearch.ts","webpack://telegram-t/./src/modules/reducers/management.ts","webpack://telegram-t/./src/modules/reducers/settings.ts","webpack://telegram-t/./src/modules/reducers/twoFaSettings.ts","webpack://telegram-t/./src/modules/reducers/payments.ts","webpack://telegram-t/./src/modules/selectors/users.ts","webpack://telegram-t/./src/modules/selectors/settings.ts","webpack://telegram-t/./src/modules/selectors/chats.ts","webpack://telegram-t/./src/modules/selectors/symbols.ts","webpack://telegram-t/./src/modules/selectors/messages.ts","webpack://telegram-t/./src/modules/selectors/localSearch.ts","webpack://telegram-t/./src/modules/selectors/management.ts","webpack://telegram-t/./src/modules/selectors/ui.ts","webpack://telegram-t/./src/modules/selectors/globalSearch.ts","webpack://telegram-t/./src/modules/selectors/payments.ts","webpack://telegram-t/./src/types/index.ts","webpack://telegram-t/./src/util/animation.ts","webpack://telegram-t/./src/util/appBadge.ts","webpack://telegram-t/./src/util/arePropsShallowEqual.ts","webpack://telegram-t/./src/util/buildClassName.ts","webpack://telegram-t/./src/util/cacheApi.ts","webpack://telegram-t/./src/util/captureEscKeyListener.ts","webpack://telegram-t/./src/util/captureKeyboardListeners.ts","webpack://telegram-t/./src/util/dateFormat.ts","webpack://telegram-t/./src/util/emoji.ts","webpack://telegram-t/./src/util/environmentWebp.ts","webpack://telegram-t/./src/util/environmentSystemTheme.ts","webpack://telegram-t/./src/util/environment.ts","webpack://telegram-t/./src/util/files.ts","webpack://telegram-t/./src/util/formatCurrency.ts","webpack://telegram-t/./src/util/generateIdFor.ts","webpack://telegram-t/./src/util/getReadableErrorText.ts","webpack://telegram-t/./src/util/handleError.ts","webpack://telegram-t/./src/util/iteratees.ts","webpack://telegram-t/./src/util/langProvider.ts","webpack://telegram-t/./src/util/callbacks.ts","webpack://telegram-t/./src/util/oggToWav.ts","webpack://telegram-t/./src/util/mediaLoader.ts","webpack://telegram-t/./src/util/memo.ts","webpack://telegram-t/./src/util/moduleLoader.ts","webpack://telegram-t/./src/util/notifications.ts","webpack://telegram-t/./src/util/countries.ts","webpack://telegram-t/./src/util/phoneNumber.ts","webpack://telegram-t/./src/util/schedulers.ts","webpack://telegram-t/./src/util/searchWords.ts","webpack://telegram-t/./node_modules/idb-keyval/dist/esm/index.js","webpack://telegram-t/./node_modules/safari-14-idb-fix/dist/esm/index.js","webpack://telegram-t/./src/util/sessions.ts","webpack://telegram-t/./src/util/switchTheme.ts","webpack://telegram-t/./src/util/textFormat.ts","webpack://telegram-t/./src/util/trimText.ts","webpack://telegram-t/./src/util/webpToPng.ts","webpack://telegram-t/./src/util/websync.ts","webpack://telegram-t/./src/util/windowSize.ts","webpack://telegram-t/webpack/bootstrap","webpack://telegram-t/webpack/runtime/compat get default export","webpack://telegram-t/webpack/runtime/define property getters","webpack://telegram-t/webpack/runtime/ensure chunk","webpack://telegram-t/webpack/runtime/get javascript chunk filename","webpack://telegram-t/webpack/runtime/get mini-css chunk filename","webpack://telegram-t/webpack/runtime/global","webpack://telegram-t/webpack/runtime/hasOwnProperty shorthand","webpack://telegram-t/webpack/runtime/make namespace object","webpack://telegram-t/webpack/runtime/publicPath","webpack://telegram-t/webpack/runtime/jsonp chunk loading","webpack://telegram-t/./src/util/setupServiceWorker.ts","webpack://telegram-t/./src/global/initial.ts","webpack://telegram-t/./src/global/cache.ts","webpack://telegram-t/./src/global/index.ts","webpack://telegram-t/./src/util/activeTabMonitor.ts","webpack://telegram-t/./src/util/fonts.ts","webpack://telegram-t/./src/components/common/UiLoader.tsx","webpack://telegram-t/./src/hooks/useLangString.ts","webpack://telegram-t/./src/components/auth/helpers/getSuggestedLanguage.ts","webpack://telegram-t/./src/components/auth/CountryCodeInput.tsx","webpack://telegram-t/./src/components/auth/AuthPhoneNumber.tsx","webpack://telegram-t/./src/components/auth/AuthCode.async.tsx","webpack://telegram-t/./src/components/auth/AuthPassword.async.tsx","webpack://telegram-t/./src/components/auth/AuthRegister.async.tsx","webpack://telegram-t/./node_modules/qr-creator/dist/qr-creator.es6.min.js","webpack://telegram-t/./src/components/auth/AuthQrCode.tsx","webpack://telegram-t/./src/components/auth/Auth.tsx","webpack://telegram-t/./src/components/main/Main.async.tsx","webpack://telegram-t/./src/components/main/AppInactive.tsx","webpack://telegram-t/./src/App.tsx","webpack://telegram-t/./src/index.tsx"],"sourcesContent":["var getProto = Object.getPrototypeOf ? (obj) => (Object.getPrototypeOf(obj)) : (obj) => (obj.__proto__);\nvar leafPrototypes;\n// create a fake namespace object\n// mode & 1: value is a module id, require it\n// mode & 2: merge all properties of value into the ns\n// mode & 4: return value when already ns object\n// mode & 16: return value when it's Promise-like\n// mode & 8|1: behave like require\n__webpack_require__.t = function(value, mode) {\n\tif(mode & 1) value = this(value);\n\tif(mode & 8) return value;\n\tif(typeof value === 'object' && value) {\n\t\tif((mode & 4) && value.__esModule) return value;\n\t\tif((mode & 16) && typeof value.then === 'function') return value;\n\t}\n\tvar ns = Object.create(null);\n\t__webpack_require__.r(ns);\n\tvar def = {};\n\tleafPrototypes = leafPrototypes || [null, getProto({}), getProto([]), getProto(getProto)];\n\tfor(var current = mode & 2 && value; typeof current == 'object' && !~leafPrototypes.indexOf(current); current = getProto(current)) {\n\t\tObject.getOwnPropertyNames(current).forEach((key) => (def[key] = () => (value[key])));\n\t}\n\tdef['default'] = () => (value);\n\t__webpack_require__.d(ns, def);\n\treturn ns;\n};","var inProgress = {};\nvar dataWebpackPrefix = \"telegram-t:\";\n// loadScript function to load a script via script tag\n__webpack_require__.l = (url, done, key, chunkId) => {\n\tif(inProgress[url]) { inProgress[url].push(done); return; }\n\tvar script, needAttach;\n\tif(key !== undefined) {\n\t\tvar scripts = document.getElementsByTagName(\"script\");\n\t\tfor(var i = 0; i < scripts.length; i++) {\n\t\t\tvar s = scripts[i];\n\t\t\tif(s.getAttribute(\"src\") == url || s.getAttribute(\"data-webpack\") == dataWebpackPrefix + key) { script = s; break; }\n\t\t}\n\t}\n\tif(!script) {\n\t\tneedAttach = true;\n\t\tscript = document.createElement('script');\n\n\t\tscript.charset = 'utf-8';\n\t\tscript.timeout = 120;\n\t\tif (__webpack_require__.nc) {\n\t\t\tscript.setAttribute(\"nonce\", __webpack_require__.nc);\n\t\t}\n\t\tscript.setAttribute(\"data-webpack\", dataWebpackPrefix + key);\n\t\tscript.src = url;\n\t}\n\tinProgress[url] = [done];\n\tvar onScriptComplete = (prev, event) => {\n\t\t// avoid mem leaks in IE.\n\t\tscript.onerror = script.onload = null;\n\t\tclearTimeout(timeout);\n\t\tvar doneFns = inProgress[url];\n\t\tdelete inProgress[url];\n\t\tscript.parentNode && script.parentNode.removeChild(script);\n\t\tdoneFns && doneFns.forEach((fn) => (fn(event)));\n\t\tif(prev) return prev(event);\n\t}\n\t;\n\tvar timeout = setTimeout(onScriptComplete.bind(null, undefined, { type: 'timeout', target: script }), 120000);\n\tscript.onerror = onScriptComplete.bind(null, script.onerror);\n\tscript.onload = onScriptComplete.bind(null, script.onload);\n\tneedAttach && document.head.appendChild(script);\n};","var createStylesheet = (chunkId, fullhref, resolve, reject) => {\n\tvar linkTag = document.createElement(\"link\");\n\n\tlinkTag.rel = \"stylesheet\";\n\tlinkTag.type = \"text/css\";\n\tvar onLinkComplete = (event) => {\n\t\t// avoid mem leaks.\n\t\tlinkTag.onerror = linkTag.onload = null;\n\t\tif (event.type === 'load') {\n\t\t\tresolve();\n\t\t} else {\n\t\t\tvar errorType = event && (event.type === 'load' ? 'missing' : event.type);\n\t\t\tvar realHref = event && event.target && event.target.href || fullhref;\n\t\t\tvar err = new Error(\"Loading CSS chunk \" + chunkId + \" failed.\\n(\" + realHref + \")\");\n\t\t\terr.code = \"CSS_CHUNK_LOAD_FAILED\";\n\t\t\terr.type = errorType;\n\t\t\terr.request = realHref;\n\t\t\tlinkTag.parentNode.removeChild(linkTag)\n\t\t\treject(err);\n\t\t}\n\t}\n\tlinkTag.onerror = linkTag.onload = onLinkComplete;\n\tlinkTag.href = fullhref;\n\n\tdocument.head.appendChild(linkTag);\n\treturn linkTag;\n};\nvar findStylesheet = (href, fullhref) => {\n\tvar existingLinkTags = document.getElementsByTagName(\"link\");\n\tfor(var i = 0; i < existingLinkTags.length; i++) {\n\t\tvar tag = existingLinkTags[i];\n\t\tvar dataHref = tag.getAttribute(\"data-href\") || tag.getAttribute(\"href\");\n\t\tif(tag.rel === \"stylesheet\" && (dataHref === href || dataHref === fullhref)) return tag;\n\t}\n\tvar existingStyleTags = document.getElementsByTagName(\"style\");\n\tfor(var i = 0; i < existingStyleTags.length; i++) {\n\t\tvar tag = existingStyleTags[i];\n\t\tvar dataHref = tag.getAttribute(\"data-href\");\n\t\tif(dataHref === href || dataHref === fullhref) return tag;\n\t}\n};\nvar loadStylesheet = (chunkId) => {\n\treturn new Promise((resolve, reject) => {\n\t\tvar href = __webpack_require__.miniCssF(chunkId);\n\t\tvar fullhref = __webpack_require__.p + href;\n\t\tif(findStylesheet(href, fullhref)) return resolve();\n\t\tcreateStylesheet(chunkId, fullhref, resolve, reject);\n\t});\n}\n// object to store loaded CSS chunks\nvar installedCssChunks = {\n\t179: 0\n};\n\n__webpack_require__.f.miniCss = (chunkId, promises) => {\n\tvar cssChunks = {\"133\":1,\"146\":1,\"280\":1,\"472\":1,\"923\":1};\n\tif(installedCssChunks[chunkId]) promises.push(installedCssChunks[chunkId]);\n\telse if(installedCssChunks[chunkId] !== 0 && cssChunks[chunkId]) {\n\t\tpromises.push(installedCssChunks[chunkId] = loadStylesheet(chunkId).then(() => {\n\t\t\tinstalledCssChunks[chunkId] = 0;\n\t\t}, (e) => {\n\t\t\tdelete installedCssChunks[chunkId];\n\t\t\tthrow e;\n\t\t}));\n\t}\n};\n\n// no hmr","import { ApiInitialArgs, ApiOnProgress, OnApiUpdate } from '../../types';\nimport { Methods, MethodArgs, MethodResponse } from '../methods/types';\nimport { WorkerMessageEvent, ThenArg, OriginRequest } from './types';\n\nimport { DEBUG } from '../../../config';\nimport generateIdFor from '../../../util/generateIdFor';\n\ntype RequestStates = {\n messageId: string;\n resolve: Function;\n reject: Function;\n callback?: AnyToVoidFunction;\n};\n\nlet worker: Worker;\nconst requestStates = new Map<string, RequestStates>();\nconst requestStatesByCallback = new Map<AnyToVoidFunction, RequestStates>();\n\n// TODO Re-use `util/WorkerConnector.ts`\n\nexport function initApi(onUpdate: OnApiUpdate, initialArgs: ApiInitialArgs) {\n if (!worker) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('>>> START LOAD WORKER');\n }\n\n worker = new Worker(new URL('./worker.ts', import.meta.url));\n subscribeToWorker(onUpdate);\n }\n\n return makeRequest({\n type: 'initApi',\n args: [initialArgs],\n });\n}\n\nexport function callApi<T extends keyof Methods>(fnName: T, ...args: MethodArgs<T>) {\n if (!worker) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.warn('API is not initialized');\n }\n\n return undefined;\n }\n\n return makeRequest({\n type: 'callMethod',\n name: fnName,\n args,\n }) as MethodResponse<T>;\n}\n\nexport function cancelApiProgress(progressCallback: ApiOnProgress) {\n progressCallback.isCanceled = true;\n\n const { messageId } = requestStatesByCallback.get(progressCallback) || {};\n if (!messageId) {\n return;\n }\n\n worker.postMessage({\n type: 'cancelProgress',\n messageId,\n });\n}\n\nfunction subscribeToWorker(onUpdate: OnApiUpdate) {\n worker.addEventListener('message', ({ data }: WorkerMessageEvent) => {\n if (data.type === 'update') {\n onUpdate(data.update);\n } else if (data.type === 'methodResponse') {\n const requestState = requestStates.get(data.messageId);\n if (requestState) {\n if (data.error) {\n requestState.reject(data.error);\n } else {\n requestState.resolve(data.response);\n }\n }\n } else if (data.type === 'methodCallback') {\n const requestState = requestStates.get(data.messageId);\n if (requestState && requestState.callback) {\n requestState.callback(...data.callbackArgs);\n }\n } else if (data.type === 'unhandledError') {\n throw data.error;\n }\n });\n}\n\nfunction makeRequest(message: OriginRequest) {\n const messageId = generateIdFor(requestStates);\n const payload: OriginRequest = {\n messageId,\n ...message,\n };\n\n const requestState = { messageId } as RequestStates;\n\n // Re-wrap type because of `postMessage`\n const promise: Promise<ThenArg<MethodResponse<keyof Methods>>> = new Promise((resolve, reject) => {\n Object.assign(requestState, { resolve, reject });\n });\n\n if (typeof payload.args[1] === 'function') {\n const callback = payload.args.pop() as AnyToVoidFunction;\n requestState.callback = callback;\n requestStatesByCallback.set(callback, requestState);\n }\n\n requestStates.set(messageId, requestState);\n promise\n .catch(() => undefined)\n .finally(() => {\n requestStates.delete(messageId);\n\n if (requestState.callback) {\n requestStatesByCallback.delete(requestState.callback);\n }\n });\n\n worker.postMessage(payload);\n\n return promise;\n}\n","// We cache avatars as Data URI for faster initial load\n// and messages media as Blob for smaller size.\n\nexport enum ApiMediaFormat {\n DataUri,\n BlobUrl,\n Lottie,\n Progressive,\n Stream,\n}\n\nexport type ApiParsedMedia = string | Blob | AnyLiteral | ArrayBuffer;\nexport type ApiPreparedMedia = string | AnyLiteral;\nexport type ApiMediaFormatToPrepared<T> = T extends ApiMediaFormat.Lottie ? AnyLiteral : string;\n","export interface ApiDimensions {\n width: number;\n height: number;\n}\n\nexport interface ApiPhotoSize extends ApiDimensions {\n type: 's' | 'm' | 'x' | 'y' | 'z';\n}\n\nexport interface ApiThumbnail extends ApiDimensions {\n dataUri: string;\n}\n\nexport interface ApiPhoto {\n id: string;\n thumbnail?: ApiThumbnail;\n sizes: ApiPhotoSize[];\n blobUrl?: string;\n}\n\nexport interface ApiSticker {\n id: string;\n stickerSetId: string;\n stickerSetAccessHash?: string;\n emoji?: string;\n isAnimated: boolean;\n width?: number;\n height?: number;\n thumbnail?: ApiThumbnail;\n isPreloadedGlobally?: boolean;\n}\n\nexport interface ApiStickerSet {\n archived?: true;\n isAnimated?: true;\n installedDate?: number;\n id: string;\n accessHash: string;\n title: string;\n hasThumbnail?: boolean;\n count: number;\n hash: number;\n stickers?: ApiSticker[];\n packs?: Record<string, ApiSticker[]>;\n covers?: ApiSticker[];\n shortName: string;\n}\n\nexport interface ApiVideo {\n id: string;\n mimeType: string;\n duration: number;\n fileName: string;\n width?: number;\n height?: number;\n supportsStreaming?: boolean;\n isRound?: boolean;\n isGif?: boolean;\n thumbnail?: ApiThumbnail;\n blobUrl?: string;\n size: number;\n}\n\nexport interface ApiAudio {\n size: number;\n mimeType: string;\n fileName: string;\n duration: number;\n performer?: string;\n title?: string;\n}\n\nexport interface ApiVoice {\n duration: number;\n waveform?: number[];\n}\n\nexport interface ApiDocument {\n id?: string;\n fileName: string;\n size: number;\n timestamp?: number;\n mimeType: string;\n thumbnail?: ApiThumbnail;\n previewBlobUrl?: string;\n mediaType?: 'photo' | 'video';\n mediaSize?: ApiDimensions;\n}\n\nexport interface ApiContact {\n firstName: string;\n lastName: string;\n phoneNumber: string;\n userId: number;\n}\n\nexport interface ApiPollAnswer {\n text: string;\n option: string;\n}\n\nexport interface ApiPollResult {\n isChosen?: true;\n isCorrect?: true;\n option: string;\n votersCount: number;\n}\n\nexport interface ApiPoll {\n id: string;\n summary: {\n closed?: true;\n isPublic?: true;\n multipleChoice?: true;\n quiz?: true;\n question: string;\n answers: ApiPollAnswer[];\n closePeriod?: number;\n closeDate?: number;\n };\n results: {\n results?: ApiPollResult[];\n totalVoters?: number;\n recentVoterIds?: number[];\n solution?: string;\n solutionEntities?: ApiMessageEntity[];\n };\n}\n\nexport interface ApiInvoice {\n text: string;\n title: string;\n photoUrl?: string;\n amount: number;\n currency: string;\n receiptMsgId?: number;\n isTest?: boolean;\n}\n\nexport type ApiNewPoll = {\n summary: ApiPoll['summary'];\n quiz?: {\n correctAnswers: string[];\n solution?: string;\n solutionEntities?: ApiMessageEntity[];\n };\n};\n\nexport interface ApiAction {\n text: string;\n targetUserIds?: number[];\n targetChatId?: number;\n type: 'historyClear' | 'contactSignUp' | 'chatCreate' | 'other';\n photo?: ApiPhoto;\n amount?: number;\n currency?: string;\n translationValues: string[];\n}\n\nexport interface ApiWebPage {\n id: number;\n url: string;\n displayUrl: string;\n type?: string;\n siteName?: string;\n title?: string;\n description?: string;\n photo?: ApiPhoto;\n duration?: number;\n document?: ApiDocument;\n video?: ApiVideo;\n}\n\nexport interface ApiMessageForwardInfo {\n isChannelPost: boolean;\n isLinkedChannelPost?: boolean;\n fromChatId?: number;\n senderUserId?: number;\n fromMessageId?: number;\n hiddenUserName?: string;\n adminTitle?: string;\n}\n\nexport interface ApiMessageEntity {\n type: string;\n offset: number;\n length: number;\n userId?: number;\n url?: string;\n}\n\nexport enum ApiMessageEntityTypes {\n Bold = 'MessageEntityBold',\n Blockquote = 'MessageEntityBlockquote',\n BotCommand = 'MessageEntityBotCommand',\n Cashtag = 'MessageEntityCashtag',\n Code = 'MessageEntityCode',\n Email = 'MessageEntityEmail',\n Hashtag = 'MessageEntityHashtag',\n Italic = 'MessageEntityItalic',\n MentionName = 'MessageEntityMentionName',\n Mention = 'MessageEntityMention',\n Phone = 'MessageEntityPhone',\n Pre = 'MessageEntityPre',\n Strike = 'MessageEntityStrike',\n TextUrl = 'MessageEntityTextUrl',\n Url = 'MessageEntityUrl',\n Underline = 'MessageEntityUnderline',\n Unknown = 'MessageEntityUnknown',\n}\n\nexport interface ApiFormattedText {\n text: string;\n entities?: ApiMessageEntity[];\n}\n\nexport interface ApiMessage {\n id: number;\n chatId: number;\n content: {\n text?: ApiFormattedText;\n photo?: ApiPhoto;\n video?: ApiVideo;\n document?: ApiDocument;\n sticker?: ApiSticker;\n contact?: ApiContact;\n poll?: ApiPoll;\n action?: ApiAction;\n webPage?: ApiWebPage;\n audio?: ApiAudio;\n voice?: ApiVoice;\n invoice?: ApiInvoice;\n };\n date: number;\n isOutgoing: boolean;\n senderId?: number;\n replyToMessageId?: number;\n replyToTopMessageId?: number;\n sendingState?: 'messageSendingStatePending' | 'messageSendingStateFailed';\n forwardInfo?: ApiMessageForwardInfo;\n isDeleting?: boolean;\n previousLocalId?: number;\n views?: number;\n isEdited?: boolean;\n isMediaUnread?: boolean;\n groupedId?: string;\n isInAlbum?: boolean;\n hasUnreadMention?: boolean;\n inlineButtons?: ApiKeyboardButtons;\n keyboardButtons?: ApiKeyboardButtons;\n keyboardPlaceholder?: string;\n isKeyboardSingleUse?: boolean;\n viaBotId?: number;\n threadInfo?: ApiThreadInfo;\n adminTitle?: string;\n isScheduled?: boolean;\n shouldHideKeyboardButtons?: boolean;\n isFromScheduled?: boolean;\n}\n\nexport interface ApiThreadInfo {\n threadId: number;\n chatId: number;\n topMessageId?: number;\n originChannelId?: number;\n messagesCount: number;\n lastMessageId?: number;\n lastReadInboxMessageId?: number;\n recentReplierIds?: number[];\n}\n\nexport type ApiMessageOutgoingStatus = 'read' | 'succeeded' | 'pending' | 'failed';\n\nexport interface ApiKeyboardButton {\n type: 'command' | 'url' | 'callback' | 'requestPoll' | 'buy' | 'NOT_SUPPORTED';\n text: string;\n messageId: number;\n value?: string;\n}\n\nexport type ApiKeyboardButtons = ApiKeyboardButton[][];\nexport type ApiReplyKeyboard = {\n keyboardPlaceholder?: string;\n isKeyboardSingleUse?: boolean;\n} & {\n [K in 'inlineButtons' | 'keyboardButtons']?: ApiKeyboardButtons;\n};\n\nexport type ApiMessageSearchType = 'text' | 'media' | 'documents' | 'links' | 'audio' | 'profilePhoto';\nexport type ApiGlobalMessageSearchType = 'text' | 'media' | 'documents' | 'links' | 'audio' | 'voice';\n\nexport type ApiReportReason = 'spam' | 'violence' | 'pornography' | 'childAbuse'\n| 'copyright' | 'geoIrrelevant' | 'fake' | 'other';\n\nexport const MAIN_THREAD_ID = -1;\n\n// `Symbol` can not be transferred from worker\nexport const MESSAGE_DELETED = 'MESSAGE_DELETED';\n","/* eslint-disable no-nested-ternary */\n/* eslint-disable no-bitwise */\n\nconst utf16 = {\n // The utf16-class is necessary to convert from javascripts internal character representation to unicode and back.\n decode: (input) => {\n const output = [];\n let i = 0;\n const len = input.length;\n let value;\n let extra;\n\n while (i < len) {\n value = input.charCodeAt(i++);\n if ((value & 0xf800) === 0xd800) {\n extra = input.charCodeAt(i++);\n if ((value & 0xfc00) !== 0xd800 || (extra & 0xfc00) !== 0xdc00) {\n throw new RangeError('UTF-16(decode): Illegal UTF-16 sequence');\n }\n value = ((value & 0x3ff) << 10) + (extra & 0x3ff) + 0x10000;\n }\n output.push(value);\n }\n return output;\n },\n encode: (input) => {\n const output = [];\n let i = 0;\n const len = input.length;\n let value;\n\n while (i < len) {\n value = input[i++];\n if ((value & 0xf800) === 0xd800) {\n throw new RangeError('UTF-16(encode): Illegal UTF-16 value');\n }\n if (value > 0xffff) {\n value -= 0x10000;\n output.push(String.fromCharCode(((value >>> 10) & 0x3ff) | 0xd800));\n value = 0xdc00 | (value & 0x3ff);\n }\n output.push(String.fromCharCode(value));\n }\n return output.join('');\n },\n};\n\n// Default parameters\nconst initial_n = 0x80;\nconst initial_bias = 72;\nconst delimiter = '\\x2D';\nconst base = 36;\nconst damp = 700;\nconst tmin = 1;\nconst tmax = 26;\nconst skew = 38;\nconst maxint = 0x7fffffff;\n\n// decode_digit(cp) returns the numeric value of a basic code\n// point (for use in representing integers) in the range 0 to\n// base-1, or base if cp is does not represent a value.\n\nfunction decode_digit(cp) {\n return cp - 48 < 10 ? cp - 22 : cp - 65 < 26 ? cp - 65 : cp - 97 < 26 ? cp - 97 : base;\n}\n\n// ** Bias adaptation function **\nfunction adapt(delta, numpoints, firsttime) {\n let k;\n delta = firsttime ? Math.floor(delta / damp) : delta >> 1;\n delta += Math.floor(delta / numpoints);\n\n for (k = 0; delta > ((base - tmin) * tmax) >> 1; k += base) {\n delta = Math.floor(delta / (base - tmin));\n }\n return Math.floor(k + ((base - tmin + 1) * delta) / (delta + skew));\n}\n\n// Main decode\nfunction decode(input, preserveCase) {\n // Dont use utf16\n const output = [];\n const case_flags = [];\n const input_length = input.length;\n\n let n; let out; let i; let bias; let basic; let j; let ic; let oldi; let w; let k; let digit; let t; let len;\n\n // Initialize the state:\n\n n = initial_n;\n i = 0;\n bias = initial_bias;\n\n // Handle the basic code points: Let basic be the number of input code\n // points before the last delimiter, or 0 if there is none, then\n // copy the first basic code points to the output.\n\n basic = input.lastIndexOf(delimiter);\n if (basic < 0) basic = 0;\n\n for (j = 0; j < basic; ++j) {\n if (preserveCase) case_flags[output.length] = input.charCodeAt(j) - 65 < 26;\n if (input.charCodeAt(j) >= 0x80) {\n throw new RangeError('Illegal input >= 0x80');\n }\n output.push(input.charCodeAt(j));\n }\n\n // Main decoding loop: Start just after the last delimiter if any\n // basic code points were copied; start at the beginning otherwise.\n\n for (ic = basic > 0 ? basic + 1 : 0; ic < input_length;) {\n // ic is the index of the next character to be consumed,\n\n // Decode a generalized variable-length integer into delta,\n // which gets added to i. The overflow checking is easier\n // if we increase i as we go, then subtract off its starting\n // value at the end to obtain delta.\n for (oldi = i, w = 1, k = base; ; k += base) {\n if (ic >= input_length) {\n throw RangeError('punycode_bad_input(1)');\n }\n digit = decode_digit(input.charCodeAt(ic++));\n\n if (digit >= base) {\n throw RangeError('punycode_bad_input(2)');\n }\n if (digit > Math.floor((maxint - i) / w)) {\n throw RangeError('punycode_overflow(1)');\n }\n i += digit * w;\n t = k <= bias ? tmin : k >= bias + tmax ? tmax : k - bias;\n if (digit < t) {\n break;\n }\n if (w > Math.floor(maxint / (base - t))) {\n throw RangeError('punycode_overflow(2)');\n }\n w *= base - t;\n }\n\n out = output.length + 1;\n bias = adapt(i - oldi, out, oldi === 0);\n\n // i was supposed to wrap around from out to 0,\n // incrementing n each time, so we'll fix that now:\n if (Math.floor(i / out) > maxint - n) {\n throw RangeError('punycode_overflow(3)');\n }\n n += Math.floor(i / out);\n i %= out;\n\n // Insert n at position i of the output:\n // Case of last character determines uppercase flag:\n if (preserveCase) {\n case_flags.splice(i, 0, input.charCodeAt(ic - 1) - 65 < 26);\n }\n\n output.splice(i, 0, n);\n i++;\n }\n if (preserveCase) {\n for (i = 0, len = output.length; i < len; i++) {\n if (case_flags[i]) {\n output[i] = String.fromCharCode(output[i])\n .toUpperCase()\n .charCodeAt(0);\n }\n }\n }\n return utf16.encode(output);\n}\n\nfunction toUnicode(domain) {\n const domain_array = domain.split('.');\n const out = [];\n for (let i = 0; i < domain_array.length; ++i) {\n const s = domain_array[i];\n out.push(s.match(/^xn--/) ? decode(s.slice(4)) : s);\n }\n return out.join('.');\n}\n\nexport default toUnicode;\n","import React, { FC, memo, useCallback } from '../../lib/teact/teact';\nimport { getDispatch } from '../../lib/teact/teactn';\nimport convertPunycode from '../../lib/punycode';\n\nimport { DEBUG, RE_TME_INVITE_LINK, RE_TME_LINK } from '../../config';\nimport buildClassName from '../../util/buildClassName';\n\ntype OwnProps = {\n url?: string;\n text: string;\n className?: string;\n children?: any;\n isRtl?: boolean;\n};\n\nconst SafeLink: FC<OwnProps> = ({\n url,\n text,\n className,\n children,\n isRtl,\n}) => {\n const { toggleSafeLinkModal, openTelegramLink } = getDispatch();\n\n const content = children || text;\n const isNotSafe = url !== content;\n\n const handleClick = useCallback((e: React.MouseEvent<HTMLAnchorElement, MouseEvent>) => {\n if (\n e.ctrlKey || e.altKey || e.shiftKey || e.metaKey\n || !url || (!url.match(RE_TME_LINK) && !url.match(RE_TME_INVITE_LINK))\n ) {\n if (isNotSafe) {\n toggleSafeLinkModal({ url });\n\n e.preventDefault();\n return false;\n }\n\n return true;\n }\n\n e.preventDefault();\n openTelegramLink({ url });\n\n return false;\n }, [isNotSafe, openTelegramLink, toggleSafeLinkModal, url]);\n\n if (!url) {\n return undefined;\n }\n\n const classNames = buildClassName(\n className || 'text-entity-link',\n text.length > 50 && 'long-word-break-all',\n );\n\n return (\n <a\n href={ensureProtocol(url)}\n title={getDomain(url)}\n target=\"_blank\"\n rel=\"noopener noreferrer\"\n className={classNames}\n onClick={handleClick}\n dir={isRtl ? 'rtl' : 'auto'}\n >\n {content}\n </a>\n );\n};\n\nfunction ensureProtocol(url?: string) {\n if (!url) {\n return undefined;\n }\n\n return url.includes('://') ? url : `https://${url}`;\n}\n\nfunction getDomain(url?: string) {\n if (!url) {\n return undefined;\n }\n\n const href = ensureProtocol(url);\n if (!href) {\n return undefined;\n }\n\n try {\n let decodedHref = decodeURI(href);\n\n const match = decodedHref.match(/^https?:\\/\\/([^/:?#]+)(?:[/:?#]|$)/i);\n if (!match) {\n return undefined;\n }\n const domain = match[1];\n decodedHref = decodedHref.replace(domain, convertPunycode(domain));\n\n return decodedHref;\n } catch (error) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error('SafeLink.getDecodedUrl error ', url, error);\n }\n }\n\n return undefined;\n}\n\nexport default memo(SafeLink);\n","import { ApiDocument } from '../../../api/types';\n\nconst ONE_GIGABYTE = 1024 * 1024 * 1024;\nconst ONE_MEGABYTE = 1024 * 1024;\n\nexport function getFileSizeString(bytes: number) {\n if (bytes > (ONE_GIGABYTE / 2)) {\n return `${(bytes / ONE_GIGABYTE).toFixed(1)} GB`;\n }\n if (bytes > (ONE_MEGABYTE / 2)) {\n return `${(bytes / ONE_MEGABYTE).toFixed(1)} MB`;\n }\n return `${(bytes / (1024)).toFixed(1)} KB`;\n}\n\nexport function getDocumentExtension(document: ApiDocument) {\n const { fileName, mimeType } = document;\n\n return getFileExtension(fileName, mimeType);\n}\n\nexport function getFileExtension(fileName: string, mimeType: string) {\n if (fileName && fileName.indexOf('.') !== -1) {\n return fileName.split('.').pop();\n } else {\n return mimeType.split('/').pop();\n }\n}\n\nexport function getColorFromExtension(extension: string) {\n switch (extension) {\n case 'apk':\n case 'xls':\n case 'xlsx':\n return 'green';\n case 'zip':\n case 'rar':\n case '7z':\n case 'tar':\n case 'gz':\n case 'ppt':\n case 'pptx':\n return 'orange';\n case 'pdf':\n case 'xps':\n return 'red';\n default:\n return 'default';\n }\n}\n\nexport function getDocumentHasPreview(document: ApiDocument) {\n return Boolean(document.previewBlobUrl || document.thumbnail);\n}\n","// @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 { LangFn } from '../../../hooks/useLang';\nimport {\n getChatTitle,\n getMessageContent,\n getMessageSummaryText,\n getUserFullName,\n isChat,\n} from '../../../modules/helpers';\nimport trimText from '../../../util/trimText';\nimport { formatCurrency } from '../../../util/formatCurrency';\nimport { TextPart } from './renderMessageText';\nimport renderText from './renderText';\n\nimport UserLink from '../UserLink';\nimport MessageLink from '../MessageLink';\nimport ChatLink from '../ChatLink';\n\ninterface ActionMessageTextOptions {\n maxTextLength?: number;\n asPlain?: boolean;\n isEmbedded?: boolean;\n}\n\nconst NBSP = '\\u00A0';\n\nexport function renderActionMessageText(\n lang: LangFn,\n message: ApiMessage,\n actionOrigin?: ApiUser | ApiChat,\n targetUsers?: ApiUser[],\n targetMessage?: ApiMessage,\n targetChatId?: number,\n options: ActionMessageTextOptions = {},\n) {\n if (!message.content.action) {\n return [];\n }\n const {\n text, translationValues, amount, currency,\n } = message.content.action;\n const content: TextPart[] = [];\n const textOptions: ActionMessageTextOptions = { ...options, maxTextLength: 32 };\n const translationKey = text === 'Chat.Service.Group.UpdatedPinnedMessage1' && !targetMessage\n ? 'Message.PinnedGenericMessage'\n : text;\n\n let unprocessed = lang(translationKey, translationValues && translationValues.length ? translationValues : undefined);\n let processed: TextPart[];\n\n if (unprocessed.includes('%payment_amount%')) {\n processed = processPlaceholder(\n unprocessed,\n '%payment_amount%',\n formatCurrency(amount!, currency, lang.code),\n );\n unprocessed = processed.pop() as string;\n content.push(...processed);\n }\n\n processed = processPlaceholder(\n unprocessed,\n '%action_origin%',\n actionOrigin\n ? (!options.isEmbedded && renderOriginContent(lang, actionOrigin, options.asPlain)) || NBSP\n : 'User',\n );\n\n unprocessed = processed.pop() as string;\n content.push(...processed);\n\n processed = processPlaceholder(\n unprocessed,\n '%target_user%',\n targetUsers\n ? targetUsers.map((user) => renderUserContent(user, options.asPlain)).filter<TextPart>(Boolean as any)\n : 'User',\n );\n\n unprocessed = processed.pop() as string;\n content.push(...processed);\n\n processed = processPlaceholder(\n unprocessed,\n '%message%',\n targetMessage\n ? renderMessageContent(lang, targetMessage, textOptions)\n : 'a message',\n );\n unprocessed = processed.pop() as string;\n content.push(...processed);\n\n processed = processPlaceholder(\n unprocessed,\n '%product%',\n targetMessage\n ? renderProductContent(targetMessage)\n : 'a product',\n );\n unprocessed = processed.pop() as string;\n content.push(...processed);\n\n processed = processPlaceholder(\n unprocessed,\n '%target_chat%',\n targetChatId\n ? renderMigratedContent(targetChatId, options.asPlain)\n : 'another chat',\n );\n content.push(...processed);\n\n if (options.asPlain) {\n return content.join('').trim();\n }\n\n return content;\n}\n\nfunction renderProductContent(message: ApiMessage) {\n return message.content && message.content.invoice\n ? message.content.invoice.title\n : 'a product';\n}\n\nfunction renderMessageContent(lang: LangFn, message: ApiMessage, options: ActionMessageTextOptions = {}) {\n const text = getMessageSummaryText(lang, message);\n const {\n photo, video, document, sticker,\n } = getMessageContent(message);\n\n const { maxTextLength, isEmbedded, asPlain } = options;\n\n const showQuotes = isEmbedded && text && !photo && !video && !document && !sticker;\n let messageText = trimText(text as string, maxTextLength)!;\n\n if (isEmbedded) {\n if (photo) {\n messageText = 'a photo';\n } else if (video) {\n messageText = video.isGif ? 'a GIF' : 'a video';\n } else if (document) {\n messageText = 'a document';\n } else if (sticker) {\n messageText = text;\n }\n }\n\n if (asPlain) {\n return showQuotes ? `«${messageText}»` : messageText;\n }\n\n if (showQuotes) {\n return (\n <span>\n «\n <MessageLink className=\"action-link\" message={message}>{renderText(messageText)}</MessageLink>\n »\n </span>\n );\n }\n\n return (\n <MessageLink className=\"action-link\" message={message}>{renderText(messageText)}</MessageLink>\n );\n}\n\nfunction renderOriginContent(lang: LangFn, origin: ApiUser | ApiChat, asPlain?: boolean) {\n return isChat(origin)\n ? renderChatContent(lang, origin, asPlain)\n : renderUserContent(origin, asPlain);\n}\n\nfunction renderUserContent(sender: ApiUser, asPlain?: boolean): string | TextPart | undefined {\n const text = trimText(getUserFullName(sender));\n\n if (asPlain) {\n return text;\n }\n\n return <UserLink className=\"action-link\" sender={sender}>{sender && renderText(text!)}</UserLink>;\n}\n\nfunction renderChatContent(lang: LangFn, chat: ApiChat, asPlain?: boolean): string | TextPart | undefined {\n const text = trimText(getChatTitle(lang, chat));\n\n if (asPlain) {\n return text;\n }\n\n return <ChatLink className=\"action-link\" chatId={chat.id}>{chat && renderText(text!)}</ChatLink>;\n}\n\nfunction renderMigratedContent(chatId: number, asPlain?: boolean): string | TextPart | undefined {\n const text = 'another chat';\n\n if (asPlain) {\n return text;\n }\n\n return <ChatLink className=\"action-link\" chatId={chatId}>{text}</ChatLink>;\n}\n\nfunction processPlaceholder(text: string, placeholder: string, replaceValue?: TextPart | TextPart[]): TextPart[] {\n const placeholderPosition = text.indexOf(placeholder);\n if (placeholderPosition < 0 || !replaceValue) {\n return [text];\n }\n\n const content: TextPart[] = [];\n content.push(text.substring(0, placeholderPosition));\n if (Array.isArray(replaceValue)) {\n replaceValue.forEach((value, index) => {\n content.push(value);\n if (index + 1 < replaceValue.length) {\n content.push(', ');\n }\n });\n } else {\n content.push(replaceValue);\n }\n content.push(text.substring(placeholderPosition + placeholder.length));\n\n return content;\n}\n","import React from '../../../lib/teact/teact';\nimport EMOJI_REGEX, { removeVS16s } from '../../../lib/twemojiRegex';\n\nimport { RE_LINK_TEMPLATE, RE_MENTION_TEMPLATE } from '../../../config';\nimport { IS_EMOJI_SUPPORTED } from '../../../util/environment';\nimport { nativeToUnfified } from '../../../util/emoji';\nimport buildClassName from '../../../util/buildClassName';\n\nimport MentionLink from '../../middle/message/MentionLink';\nimport SafeLink from '../SafeLink';\n\ntype TextPart = string | Element;\n\nconst RE_LETTER_OR_DIGIT = /^[\\d\\wа-яё]$/i;\nconst SIMPLE_MARKDOWN_REGEX = /(\\*\\*|__).+?\\1/g;\n\nexport default function renderText(\n part: TextPart,\n filters: Array<(\n 'escape_html' | 'hq_emoji' | 'emoji' | 'emoji_html' | 'br' | 'br_html' | 'highlight' | 'links' |\n 'simple_markdown' | 'simple_markdown_html'\n )> = ['emoji'],\n params?: { highlight: string | undefined },\n): TextPart[] {\n if (typeof part !== 'string') {\n return [part];\n }\n\n return filters.reduce((text, filter) => {\n switch (filter) {\n case 'escape_html':\n return escapeHtml(text);\n\n case 'hq_emoji':\n EMOJI_REGEX.lastIndex = 0;\n return replaceEmojis(text, 'big', 'jsx');\n\n case 'emoji':\n EMOJI_REGEX.lastIndex = 0;\n return replaceEmojis(text, 'small', 'jsx');\n\n case 'emoji_html':\n EMOJI_REGEX.lastIndex = 0;\n return replaceEmojis(text, 'small', 'html');\n\n case 'br':\n return addLineBreaks(text, 'jsx');\n\n case 'br_html':\n return addLineBreaks(text, 'html');\n\n case 'highlight':\n return addHighlight(text, params!.highlight);\n\n case 'links':\n return addLinks(text);\n\n case 'simple_markdown':\n return replaceSimpleMarkdown(text, 'jsx');\n\n case 'simple_markdown_html':\n return replaceSimpleMarkdown(text, 'html');\n }\n\n return text;\n }, [part] as TextPart[]);\n}\n\nfunction escapeHtml(textParts: TextPart[]): TextPart[] {\n const divEl = document.createElement('div');\n return textParts.reduce((result, part) => {\n if (typeof part !== 'string') {\n return [...result, part];\n }\n\n divEl.innerText = part;\n\n return [...result, divEl.innerHTML];\n }, [] as TextPart[]);\n}\n\nfunction replaceEmojis(textParts: TextPart[], size: 'big' | 'small', type: 'jsx' | 'html'): TextPart[] {\n if (IS_EMOJI_SUPPORTED) {\n return textParts;\n }\n\n return textParts.reduce((result, part) => {\n if (typeof part !== 'string') {\n return [...result, part];\n }\n\n const parts = part.split(EMOJI_REGEX);\n const emojis = part.match(EMOJI_REGEX) || [];\n result.push(parts[0]);\n\n return emojis.reduce((emojiResult: TextPart[], emoji, i) => {\n const code = nativeToUnfified(removeVS16s(emoji));\n const className = buildClassName(\n 'emoji',\n size === 'small' && 'emoji-small',\n );\n if (type === 'jsx') {\n emojiResult.push(\n <img\n className={className}\n src={`./img-apple-${size === 'big' ? '160' : '64'}/${code}.png`}\n alt={emoji}\n />,\n );\n }\n if (type === 'html') {\n emojiResult.push(\n // For preventing extra spaces in html\n // eslint-disable-next-line max-len\n `<img draggable=\"false\" class=\"${className}\" src=\"./img-apple-${size === 'big' ? '160' : '64'}/${code}.png\" alt=\"${emoji}\" />`,\n );\n }\n\n const index = i * 2 + 2;\n if (parts[index]) {\n emojiResult.push(parts[index]);\n }\n\n return emojiResult;\n }, result);\n }, [] as TextPart[]);\n}\n\nfunction addLineBreaks(textParts: TextPart[], type: 'jsx' | 'html'): TextPart[] {\n return textParts.reduce((result, part) => {\n if (typeof part !== 'string') {\n return [...result, part];\n }\n\n return [...result, ...part\n .split(/\\r\\n|\\r|\\n/g)\n .reduce((parts: TextPart[], line: string, i, source) => {\n // This adds non-breaking space if line was indented with spaces, to preserve the indentation\n const trimmedLine = line.trimLeft();\n const indentLength = line.length - trimmedLine.length;\n parts.push(String.fromCharCode(160).repeat(indentLength) + trimmedLine);\n\n if (i !== source.length - 1) {\n parts.push(\n type === 'jsx' ? <br /> : '<br />',\n );\n }\n\n return parts;\n }, [])];\n }, [] as TextPart[]);\n}\n\nfunction addHighlight(textParts: TextPart[], highlight: string | undefined): TextPart[] {\n return textParts.reduce((result, part) => {\n if (typeof part !== 'string' || !highlight) {\n return [...result, part];\n }\n\n const lowerCaseText = part.toLowerCase();\n const queryPosition = lowerCaseText.indexOf(highlight.toLowerCase());\n const nextSymbol = lowerCaseText[queryPosition + highlight.length];\n if (queryPosition < 0 || (nextSymbol && nextSymbol.match(RE_LETTER_OR_DIGIT))) {\n return [...result, part];\n }\n\n const newParts: TextPart[] = [];\n newParts.push(part.substring(0, queryPosition));\n newParts.push(\n <span className=\"matching-text-highlight\">\n {part.substring(queryPosition, queryPosition + highlight.length)}\n </span>,\n );\n newParts.push(part.substring(queryPosition + highlight.length));\n\n return [...result, ...newParts];\n }, [] as TextPart[]);\n}\n\nconst RE_LINK = new RegExp(`${RE_LINK_TEMPLATE}|${RE_MENTION_TEMPLATE}`, 'ig');\n\nfunction addLinks(textParts: TextPart[]): TextPart[] {\n return textParts.reduce((result, part) => {\n if (typeof part !== 'string') {\n return [...result, part];\n }\n\n const links = part.match(RE_LINK);\n if (!links || !links.length) {\n return [...result, part];\n }\n\n const content: TextPart[] = [];\n\n let nextLink = links.shift();\n let lastIndex = 0;\n while (nextLink) {\n const index = part.indexOf(nextLink, lastIndex);\n content.push(part.substring(lastIndex, index));\n if (nextLink.startsWith('@')) {\n content.push(\n <MentionLink username={nextLink}>\n {nextLink}\n </MentionLink>,\n );\n } else {\n if (nextLink.endsWith('?')) {\n nextLink = nextLink.slice(0, nextLink.length - 1);\n }\n\n content.push(\n <SafeLink text={nextLink} url={nextLink} />,\n );\n }\n lastIndex = index + nextLink.length;\n nextLink = links.shift();\n }\n content.push(part.substring(lastIndex));\n\n return [...result, ...content];\n }, [] as TextPart[]);\n}\n\nfunction replaceSimpleMarkdown(textParts: TextPart[], type: 'jsx' | 'html'): TextPart[] {\n return textParts.reduce((result, part) => {\n if (typeof part !== 'string') {\n return [...result, part];\n }\n\n const parts = part.split(SIMPLE_MARKDOWN_REGEX);\n const entities = part.match(SIMPLE_MARKDOWN_REGEX) || [];\n result.push(parts[0]);\n\n return entities.reduce((entityResult: TextPart[], entity, i) => {\n if (type === 'jsx') {\n entityResult.push(\n entity.startsWith('**')\n ? <b>{entity.replace(/\\*\\*/g, '')}</b>\n : <i>{entity.replace(/__/g, '')}</i>,\n );\n } else {\n entityResult.push(\n entity.startsWith('**')\n ? `<b>${entity.replace(/\\*\\*/g, '')}</b>`\n : `<i>${entity.replace(/__/g, '')}</i>`,\n );\n }\n\n const index = i * 2 + 2;\n if (parts[index]) {\n entityResult.push(parts[index]);\n }\n\n return entityResult;\n }, result);\n }, [] as TextPart[]);\n}\n","import React, { FC } from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../../global/types';\nimport { ApiChat, ApiUser } from '../../../api/types';\n\nimport { pick } from '../../../util/iteratees';\nimport { selectUser } from '../../../modules/selectors';\n\ntype OwnProps = {\n userId?: number;\n username?: string;\n children: any;\n};\n\ntype StateProps = {\n userOrChat?: ApiUser | ApiChat;\n};\n\ntype DispatchProps = Pick<GlobalActions, 'openChat' | 'openChatByUsername'>;\n\nconst MentionLink: FC<OwnProps & StateProps & DispatchProps> = ({\n username,\n userOrChat,\n children,\n openChat,\n openChatByUsername,\n}) => {\n const handleClick = () => {\n if (userOrChat) {\n openChat({ id: userOrChat.id });\n } else if (username) {\n openChatByUsername({ username: username.substring(1) });\n }\n };\n\n return (\n <a onClick={handleClick} className=\"text-entity-link\" dir=\"auto\">\n {children}\n </a>\n );\n};\n\nexport default withGlobal<OwnProps>(\n (global, { userId }): StateProps => {\n return {\n userOrChat: userId ? selectUser(global, userId) : undefined,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, ['openChat', 'openChatByUsername']),\n)(MentionLink);\n","import { MouseEvent as ReactMouseEvent, RefObject } from 'react';\n\nimport React, {\n FC, useRef, useCallback, useState,\n} from '../../lib/teact/teact';\n\nimport buildClassName from '../../util/buildClassName';\n\nimport Spinner from './Spinner';\nimport RippleEffect from './RippleEffect';\n\nimport './Button.scss';\n\nexport type OwnProps = {\n ref?: RefObject<HTMLButtonElement | HTMLAnchorElement>;\n type?: 'button' | 'submit' | 'reset';\n children: any;\n size?: 'default' | 'smaller' | 'tiny';\n color?: 'primary' | 'secondary' | 'gray' | 'danger' | 'translucent' | 'translucent-white' | 'dark';\n className?: string;\n round?: boolean;\n pill?: boolean;\n fluid?: boolean;\n isText?: boolean;\n isLoading?: boolean;\n ariaLabel?: string;\n href?: string;\n download?: string;\n disabled?: boolean;\n ripple?: boolean;\n faded?: boolean;\n tabIndex?: number;\n isRtl?: boolean;\n onClick?: (e: ReactMouseEvent<HTMLButtonElement, MouseEvent>) => void;\n onContextMenu?: (e: ReactMouseEvent<HTMLButtonElement, MouseEvent>) => void;\n onMouseDown?: (e: ReactMouseEvent<HTMLButtonElement>) => void;\n onMouseEnter?: NoneToVoidFunction;\n onMouseLeave?: NoneToVoidFunction;\n onFocus?: NoneToVoidFunction;\n};\n\n// Longest animation duration;\nconst CLICKED_TIMEOUT = 400;\n\nconst Button: FC<OwnProps> = ({\n ref,\n type = 'button',\n onClick,\n onContextMenu,\n onMouseDown,\n onMouseEnter,\n onMouseLeave,\n onFocus,\n children,\n size = 'default',\n color = 'primary',\n className,\n round,\n pill,\n fluid,\n isText,\n isLoading,\n ariaLabel,\n href,\n download,\n disabled,\n ripple,\n faded,\n tabIndex,\n isRtl,\n}) => {\n // eslint-disable-next-line no-null/no-null\n let elementRef = useRef<HTMLButtonElement | HTMLAnchorElement>(null);\n if (ref) {\n elementRef = ref;\n }\n\n const [isClicked, setIsClicked] = useState(false);\n\n const fullClassName = buildClassName(\n 'Button',\n className,\n size,\n color,\n round && 'round',\n pill && 'pill',\n fluid && 'fluid',\n disabled && 'disabled',\n isText && 'text',\n isLoading && 'loading',\n ripple && 'has-ripple',\n faded && 'faded',\n isClicked && 'clicked',\n );\n\n const handleClick = useCallback((e: ReactMouseEvent<HTMLButtonElement, MouseEvent>) => {\n if (!disabled && onClick) {\n onClick(e);\n }\n\n setIsClicked(true);\n setTimeout(() => {\n setIsClicked(false);\n }, CLICKED_TIMEOUT);\n }, [disabled, onClick]);\n\n const handleMouseDown = useCallback((e: ReactMouseEvent<HTMLButtonElement>) => {\n e.preventDefault();\n if (!disabled && onMouseDown) {\n onMouseDown(e);\n }\n }, [onMouseDown, disabled]);\n\n if (href) {\n return (\n <a\n ref={elementRef as RefObject<HTMLAnchorElement>}\n className={fullClassName}\n href={href}\n title={ariaLabel}\n download={download}\n tabIndex={tabIndex}\n dir={isRtl ? 'rtl' : undefined}\n >\n {children}\n {!disabled && ripple && (\n <RippleEffect />\n )}\n </a>\n );\n }\n\n return (\n // eslint-disable-next-line react/button-has-type\n <button\n ref={elementRef as RefObject<HTMLButtonElement>}\n type={type}\n className={fullClassName}\n onClick={handleClick}\n onContextMenu={onContextMenu}\n onMouseDown={handleMouseDown}\n onMouseEnter={onMouseEnter && !disabled ? onMouseEnter : undefined}\n onMouseLeave={onMouseLeave && !disabled ? onMouseLeave : undefined}\n onFocus={onFocus && !disabled ? onFocus : undefined}\n aria-label={ariaLabel}\n title={ariaLabel}\n tabIndex={tabIndex}\n dir={isRtl ? 'rtl' : undefined}\n >\n {isLoading ? (\n <div>\n <span dir={isRtl ? 'auto' : undefined}>Please wait..</span>\n <Spinner color={isText ? 'blue' : 'white'} />\n </div>\n ) : children}\n {!disabled && ripple && (\n <RippleEffect />\n )}\n </button>\n );\n};\n\nexport default Button;\n","import { ChangeEvent } from 'react';\nimport React, { FC, memo, useCallback } from '../../lib/teact/teact';\n\nimport buildClassName from '../../util/buildClassName';\nimport useLang from '../../hooks/useLang';\n\nimport Spinner from './Spinner';\n\nimport './Checkbox.scss';\n\ntype OwnProps = {\n id?: string;\n name?: string;\n value?: string;\n label: string;\n subLabel?: string;\n checked: boolean;\n disabled?: boolean;\n round?: boolean;\n blocking?: boolean;\n isLoading?: boolean;\n withCheckedCallback?: boolean;\n onChange?: (e: ChangeEvent<HTMLInputElement>) => void;\n onCheck?: (isChecked: boolean) => void;\n};\n\nconst Checkbox: FC<OwnProps> = ({\n id,\n name,\n value,\n label,\n subLabel,\n checked,\n disabled,\n round,\n blocking,\n isLoading,\n onChange,\n onCheck,\n}) => {\n const lang = useLang();\n const handleChange = useCallback((event: ChangeEvent<HTMLInputElement>) => {\n if (onChange) {\n onChange(event);\n }\n\n if (onCheck) {\n onCheck(event.currentTarget.checked);\n }\n }, [onChange, onCheck]);\n\n const className = buildClassName(\n 'Checkbox',\n disabled && 'disabled',\n round && 'round',\n isLoading && 'loading',\n blocking && 'blocking',\n );\n\n return (\n <label className={className} dir={lang.isRtl ? 'rtl' : undefined}>\n <input\n type=\"checkbox\"\n id={id}\n name={name}\n value={value}\n checked={checked}\n disabled={disabled}\n onChange={handleChange}\n />\n <div className=\"Checkbox-main\">\n <span className=\"label\" dir=\"auto\">{label}</span>\n {subLabel && <span className=\"subLabel\" dir=\"auto\">{subLabel}</span>}\n </div>\n {isLoading && <Spinner />}\n </label>\n );\n};\n\nexport default memo(Checkbox);\n","import React, { FC, useState, useRef } from '../../lib/teact/teact';\n\nimport Menu from './Menu';\n\nimport './DropdownMenu.scss';\n\ntype OwnProps = {\n className?: string;\n trigger: FC<{ onTrigger: () => void; isOpen?: boolean }>;\n positionX?: 'left' | 'right';\n positionY?: 'top' | 'bottom';\n footer?: string;\n forceOpen?: boolean;\n onOpen?: NoneToVoidFunction;\n onClose?: NoneToVoidFunction;\n children: any;\n};\n\nconst DropdownMenu: FC<OwnProps> = ({\n trigger,\n className,\n children,\n positionX = 'left',\n positionY = 'top',\n footer,\n forceOpen,\n onOpen,\n onClose,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const menuRef = useRef<HTMLDivElement>(null);\n // eslint-disable-next-line no-null/no-null\n const dropdownRef = useRef<HTMLDivElement>(null);\n const [isOpen, setIsOpen] = useState(false);\n\n const toggleIsOpen = () => {\n setIsOpen(!isOpen);\n if (isOpen) {\n if (onClose) onClose();\n } else if (onOpen) onOpen();\n };\n\n const handleKeyDown = (e: React.KeyboardEvent<any>) => {\n const menu = menuRef.current;\n\n if (!isOpen || e.keyCode !== 40 || !menu) {\n return;\n }\n\n const focusedElement = document.activeElement;\n const elementChildren = Array.from(menu.children);\n\n if (!focusedElement || elementChildren.indexOf(focusedElement) === -1) {\n (elementChildren[0] as HTMLElement).focus();\n }\n };\n\n const handleClose = () => {\n setIsOpen(false);\n if (onClose) onClose();\n };\n\n return (\n <div\n ref={dropdownRef}\n className={`DropdownMenu ${className || ''}`}\n onKeyDown={handleKeyDown}\n >\n {trigger({ onTrigger: toggleIsOpen, isOpen })}\n\n <Menu\n ref={menuRef}\n containerRef={dropdownRef}\n isOpen={isOpen || !!forceOpen}\n className={className || ''}\n positionX={positionX}\n positionY={positionY}\n footer={footer}\n autoClose\n onClose={handleClose}\n shouldSkipTransition={forceOpen}\n >\n {children}\n </Menu>\n </div>\n );\n};\n\nexport default DropdownMenu;\n","import { ChangeEvent, FormEvent, RefObject } from 'react';\nimport React, { FC, memo } from '../../lib/teact/teact';\n\nimport buildClassName from '../../util/buildClassName';\nimport useLang from '../../hooks/useLang';\n\ntype OwnProps = {\n ref?: RefObject<HTMLInputElement>;\n id?: string;\n className?: string;\n value?: string;\n label?: string;\n error?: string;\n success?: string;\n disabled?: boolean;\n readOnly?: boolean;\n placeholder?: string;\n autoComplete?: string;\n maxLength?: number;\n inputMode?: 'text' | 'none' | 'tel' | 'url' | 'email' | 'numeric' | 'decimal' | 'search';\n onChange?: (e: ChangeEvent<HTMLInputElement>) => void;\n onInput?: (e: FormEvent<HTMLInputElement>) => void;\n onKeyPress?: (e: React.KeyboardEvent<HTMLInputElement>) => void;\n onKeyDown?: (e: React.KeyboardEvent<HTMLInputElement>) => void;\n onBlur?: (e: React.FocusEvent<HTMLInputElement>) => void;\n onPaste?: (e: React.ClipboardEvent<HTMLInputElement>) => void;\n};\n\nconst InputText: FC<OwnProps> = ({\n ref,\n id,\n className,\n value,\n label,\n error,\n success,\n disabled,\n readOnly,\n placeholder,\n autoComplete,\n inputMode,\n maxLength,\n onChange,\n onInput,\n onKeyPress,\n onKeyDown,\n onBlur,\n onPaste,\n}) => {\n const lang = useLang();\n const labelText = error || success || label;\n const fullClassName = buildClassName(\n 'input-group',\n value && 'touched',\n error ? 'error' : success && 'success',\n disabled && 'disabled',\n readOnly && 'disabled',\n labelText && 'with-label',\n className,\n );\n\n return (\n <div className={fullClassName} dir={lang.isRtl ? 'rtl' : undefined}>\n <input\n ref={ref}\n className=\"form-control\"\n type=\"text\"\n id={id}\n dir=\"auto\"\n value={value || ''}\n placeholder={placeholder}\n maxLength={maxLength}\n autoComplete={autoComplete}\n inputMode={inputMode}\n disabled={disabled}\n readOnly={readOnly}\n onChange={onChange}\n onInput={onInput}\n onKeyPress={onKeyPress}\n onKeyDown={onKeyDown}\n onBlur={onBlur}\n onPaste={onPaste}\n />\n {labelText && (\n <label htmlFor={id}>{labelText}</label>\n )}\n </div>\n );\n};\n\nexport default memo(InputText);\n","import React, { FC, useCallback } from '../../lib/teact/teact';\n\nimport buildClassName from '../../util/buildClassName';\n\nimport './Link.scss';\n\ntype OwnProps = {\n children: any;\n className?: string;\n isRtl?: boolean;\n onClick?: (e: React.MouseEvent<HTMLAnchorElement>) => void;\n};\n\nconst Link: FC<OwnProps> = ({\n children, className, isRtl, onClick,\n}) => {\n const handleClick = useCallback((e: React.MouseEvent<HTMLAnchorElement>) => {\n e.preventDefault();\n onClick!(e);\n }, [onClick]);\n\n return (\n <a\n href=\"#\"\n className={buildClassName('Link', className)}\n dir={isRtl ? 'rtl' : 'auto'}\n onClick={onClick ? handleClick : undefined}\n >\n {children}\n </a>\n );\n};\n\nexport default Link;\n","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 { RefObject } from 'react';\nimport React, { FC, useEffect, useRef } from '../../lib/teact/teact';\n\nimport useShowTransition from '../../hooks/useShowTransition';\nimport useKeyboardListNavigation from '../../hooks/useKeyboardListNavigation';\nimport useVirtualBackdrop from '../../hooks/useVirtualBackdrop';\nimport useEffectWithPrevDeps from '../../hooks/useEffectWithPrevDeps';\nimport captureEscKeyListener from '../../util/captureEscKeyListener';\nimport buildClassName from '../../util/buildClassName';\nimport { dispatchHeavyAnimationEvent } from '../../hooks/useHeavyAnimationCheck';\nimport useHistoryBack from '../../hooks/useHistoryBack';\n\nimport './Menu.scss';\n\ntype OwnProps = {\n ref?: RefObject<HTMLDivElement>;\n containerRef?: RefObject<HTMLElement>;\n isOpen: boolean;\n className?: string;\n style?: string;\n positionX?: 'left' | 'right';\n positionY?: 'top' | 'bottom';\n autoClose?: boolean;\n shouldSkipTransition?: boolean;\n footer?: string;\n noCloseOnBackdrop?: boolean;\n onKeyDown?: (e: React.KeyboardEvent<any>) => void;\n onCloseAnimationEnd?: () => void;\n onClose?: () => void;\n onMouseEnter?: (e: React.MouseEvent<HTMLDivElement, MouseEvent>) => void;\n onMouseLeave?: (e: React.MouseEvent<HTMLDivElement, MouseEvent>) => void;\n children: any;\n};\n\nconst ANIMATION_DURATION = 200;\n\nconst Menu: FC<OwnProps> = ({\n ref,\n containerRef,\n isOpen,\n className,\n style,\n children,\n positionX = 'left',\n positionY = 'top',\n autoClose = false,\n footer,\n noCloseOnBackdrop = false,\n onCloseAnimationEnd,\n onClose,\n onMouseEnter,\n onMouseLeave,\n shouldSkipTransition,\n}) => {\n // eslint-disable-next-line no-null/no-null\n let menuRef = useRef<HTMLDivElement>(null);\n if (ref) {\n menuRef = ref;\n }\n const backdropContainerRef = containerRef || menuRef;\n\n const {\n transitionClassNames,\n } = useShowTransition(\n isOpen,\n onCloseAnimationEnd,\n shouldSkipTransition,\n undefined,\n shouldSkipTransition,\n );\n\n useEffect(\n () => (isOpen && onClose ? captureEscKeyListener(onClose) : undefined),\n [isOpen, onClose],\n );\n\n useHistoryBack(isOpen, onClose, undefined, undefined, autoClose);\n\n useEffectWithPrevDeps(([prevIsOpen]) => {\n if (prevIsOpen !== undefined) {\n dispatchHeavyAnimationEvent(ANIMATION_DURATION);\n }\n }, [isOpen]);\n\n const handleKeyDown = useKeyboardListNavigation(menuRef, isOpen, autoClose ? onClose : undefined, undefined, true);\n\n useVirtualBackdrop(\n isOpen,\n backdropContainerRef,\n noCloseOnBackdrop ? undefined : onClose,\n );\n\n const bubbleClassName = buildClassName(\n 'bubble menu-container custom-scroll',\n positionY,\n positionX,\n footer && 'with-footer',\n transitionClassNames,\n );\n\n return (\n <div\n className={buildClassName('Menu no-selection', className)}\n onKeyDown={isOpen ? handleKeyDown : undefined}\n onMouseEnter={onMouseEnter}\n onMouseLeave={isOpen ? onMouseLeave : undefined}\n // @ts-ignore teact feature\n style={style}\n >\n {isOpen && (\n // This only prevents click events triggering on underlying elements\n <div className=\"backdrop\" />\n )}\n <div\n ref={menuRef}\n className={bubbleClassName}\n // @ts-ignore teact feature\n style={`transform-origin: ${positionY} ${positionX}`}\n onClick={autoClose ? onClose : undefined}\n >\n {children}\n {footer && <div className=\"footer\">{footer}</div>}\n </div>\n </div>\n );\n};\n\nexport default Menu;\n","import React, { FC, useCallback } from '../../lib/teact/teact';\n\nimport buildClassName from '../../util/buildClassName';\nimport useLang from '../../hooks/useLang';\n\nimport './MenuItem.scss';\n\ntype OnClickHandler = (e: React.SyntheticEvent<HTMLDivElement | HTMLAnchorElement>) => void;\n\ntype OwnProps = {\n icon?: string;\n className?: string;\n children: any;\n onClick?: OnClickHandler;\n href?: string;\n download?: string;\n disabled?: boolean;\n destructive?: boolean;\n ariaLabel?: string;\n};\n\nconst MenuItem: FC<OwnProps> = (props) => {\n const {\n icon,\n className,\n children,\n onClick,\n href,\n download,\n disabled,\n destructive,\n ariaLabel,\n } = props;\n\n const lang = useLang();\n const handleClick = useCallback((e: React.MouseEvent<HTMLDivElement>) => {\n if (disabled || !onClick) {\n e.stopPropagation();\n e.preventDefault();\n\n return;\n }\n\n onClick(e);\n }, [disabled, onClick]);\n\n const handleKeyDown = useCallback((e: React.KeyboardEvent<HTMLDivElement>) => {\n if (e.keyCode !== 13 && e.keyCode !== 32) {\n return;\n }\n\n if (disabled || !onClick) {\n e.stopPropagation();\n e.preventDefault();\n\n return;\n }\n\n onClick(e);\n }, [disabled, onClick]);\n\n const fullClassName = buildClassName(\n 'MenuItem',\n className,\n disabled && 'disabled',\n destructive && 'destructive',\n );\n\n const content = (\n <>\n {icon && (\n <i className={`icon-${icon}`} data-char={icon.startsWith('char-') ? icon.replace('char-', '') : undefined} />\n )}\n {children}\n </>\n );\n\n if (href) {\n return (\n <a\n tabIndex={0}\n className={fullClassName}\n href={href}\n download={download}\n aria-label={ariaLabel}\n title={ariaLabel}\n target={href.startsWith(window.location.origin) ? '_self' : '_blank'}\n rel=\"noopener noreferrer\"\n dir={lang.isRtl ? 'rtl' : undefined}\n onClick={onClick}\n >\n {content}\n </a>\n );\n }\n\n return (\n <div\n role=\"button\"\n tabIndex={0}\n className={fullClassName}\n onClick={handleClick}\n onKeyDown={handleKeyDown}\n aria-label={ariaLabel}\n title={ariaLabel}\n dir={lang.isRtl ? 'rtl' : undefined}\n >\n {content}\n </div>\n );\n};\n\nexport default MenuItem;\n","import React, {\n FC, useCallback, useMemo, useState, memo,\n} from '../../lib/teact/teact';\nimport { debounce } from '../../util/schedulers';\n\nimport './RippleEffect.scss';\n\ninterface Ripple {\n x: number;\n y: number;\n size: number;\n}\n\nconst ANIMATION_DURATION_MS = 700;\n\nconst RippleEffect: FC = () => {\n const [ripples, setRipples] = useState<Ripple[]>([]);\n\n const cleanUpDebounced = useMemo(() => {\n return debounce(() => {\n setRipples([]);\n }, ANIMATION_DURATION_MS, false);\n }, []);\n\n const handleMouseDown = useCallback((e: React.MouseEvent<HTMLDivElement, MouseEvent>) => {\n if (e.button !== 0) {\n return;\n }\n\n const container = e.currentTarget as HTMLDivElement;\n const position = container.getBoundingClientRect() as DOMRect;\n\n const rippleSize = container.offsetWidth / 2;\n\n setRipples([\n ...ripples,\n {\n x: e.clientX - position.x - (rippleSize / 2),\n y: e.clientY - position.y - (rippleSize / 2),\n size: rippleSize,\n },\n ]);\n\n requestAnimationFrame(() => {\n cleanUpDebounced();\n });\n }, [ripples, cleanUpDebounced]);\n\n return (\n <div className=\"ripple-container\" onMouseDown={handleMouseDown}>\n {ripples.map(({ x, y, size }) => (\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 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","export const PAGE_TITLE = 'Telegram';\nexport const INACTIVE_MARKER = ' [Inactive]';\n\nexport const APP_NAME = process.env.APP_NAME || 'Telegram WebZ';\nexport const APP_VERSION = process.env.APP_VERSION || 'dev';\n\nexport const DEBUG = (\n process.env.APP_ENV !== 'production' && process.env.APP_ENV !== 'perf' && process.env.APP_ENV !== 'test'\n);\nexport const DEBUG_MORE = false;\n\nexport const IS_TEST = process.env.APP_ENV === 'test';\nexport const IS_PERF = process.env.APP_ENV === 'perf';\n\nexport const DEBUG_ALERT_MSG = 'Shoot!\\nSomething went wrong, please see the error details in Dev Tools Console.';\nexport const DEBUG_GRAMJS = false;\n\nexport const SESSION_USER_KEY = 'user_auth';\nexport const LEGACY_SESSION_KEY = 'GramJs:sessionId';\n\nexport const GLOBAL_STATE_CACHE_DISABLED = false;\nexport const GLOBAL_STATE_CACHE_KEY = 'tt-global-state';\nexport const GLOBAL_STATE_CACHE_CHAT_LIST_LIMIT = 30;\nexport const GLOBAL_STATE_CACHE_USER_LIST_LIMIT = 5000;\n\nexport const MEDIA_CACHE_DISABLED = false;\nexport const MEDIA_CACHE_NAME = 'tt-media';\nexport const MEDIA_CACHE_NAME_AVATARS = 'tt-media-avatars';\nexport const MEDIA_PROGRESSIVE_CACHE_DISABLED = false;\nexport const MEDIA_PROGRESSIVE_CACHE_NAME = 'tt-media-progressive';\nexport const MEDIA_CACHE_MAX_BYTES = 512 * 1024; // 512 KB\nexport const CUSTOM_BG_CACHE_NAME = 'tt-custom-bg';\nexport const LANG_CACHE_NAME = 'tt-lang-packs-v5';\nexport const ASSET_CACHE_NAME = 'tt-assets';\nexport const TRANSPARENT_PIXEL = 'data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==';\n\nexport const DOWNLOAD_WORKERS = 16;\nexport const UPLOAD_WORKERS = 16;\n\nconst isBigScreen = typeof window !== 'undefined' && window.innerHeight >= 900;\n\nexport const MIN_PASSWORD_LENGTH = 1;\n\nexport const MESSAGE_LIST_SENSITIVE_AREA = 750;\nexport const MESSAGE_LIST_SLICE = isBigScreen ? 60 : 40;\nexport const MESSAGE_LIST_VIEWPORT_LIMIT = MESSAGE_LIST_SLICE * 2;\n\nexport const CHAT_HEIGHT_PX = 72;\nexport const CHAT_LIST_SLICE = isBigScreen ? 30 : 25;\nexport const CHAT_LIST_LOAD_SLICE = 100;\nexport const SHARED_MEDIA_SLICE = 42;\nexport const MESSAGE_SEARCH_SLICE = 42;\nexport const GLOBAL_SEARCH_SLICE = 20;\nexport const MEMBERS_SLICE = 30;\nexport const MEMBERS_LOAD_SLICE = 200;\nexport const PINNED_MESSAGES_LIMIT = 50;\nexport const BLOCKED_LIST_LIMIT = 100;\nexport const PROFILE_PHOTOS_LIMIT = 40;\nexport const PROFILE_SENSITIVE_AREA = 500;\n\nexport const TOP_CHAT_MESSAGES_PRELOAD_LIMIT = 20;\nexport const ALL_CHATS_PRELOAD_DISABLED = false;\n\nexport const ANIMATION_LEVEL_MIN = 0;\nexport const ANIMATION_LEVEL_MED = 1;\nexport const ANIMATION_LEVEL_MAX = 2;\nexport const ANIMATION_LEVEL_DEFAULT = ANIMATION_LEVEL_MAX;\n\nexport const DEFAULT_MESSAGE_TEXT_SIZE_PX = 16;\nexport const IOS_DEFAULT_MESSAGE_TEXT_SIZE_PX = 17;\nexport const MACOS_DEFAULT_MESSAGE_TEXT_SIZE_PX = 15;\n\nexport const DRAFT_DEBOUNCE = 10000; // 10s\n\nexport const EDITABLE_INPUT_ID = 'editable-message-text';\nexport const EDITABLE_INPUT_MODAL_ID = 'editable-message-text-modal';\n\n// Screen width where Pinned Message / Audio Player in the Middle Header can be safely displayed\nexport const SAFE_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN = 1440; // px\n// Screen width where Pinned Message / Audio Player in the Middle Header shouldn't collapse with ChatInfo\nexport const SAFE_SCREEN_WIDTH_FOR_CHAT_INFO = 1150; // px\n\nexport const MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN = 1275; // px\nexport const MIN_SCREEN_WIDTH_FOR_STATIC_LEFT_COLUMN = 925; // px\nexport const MOBILE_SCREEN_MAX_WIDTH = 600; // px\nexport const MOBILE_SCREEN_LANDSCAPE_MAX_WIDTH = 950; // px\nexport const MOBILE_SCREEN_LANDSCAPE_MAX_HEIGHT = 450; // px\n\nexport const LOCAL_MESSAGE_ID_BASE = 1e9;\n\nexport const ANIMATION_END_DELAY = 100;\n\nexport const FAST_SMOOTH_MAX_DISTANCE = 1500;\nexport const FAST_SMOOTH_MIN_DURATION = 250;\nexport const FAST_SMOOTH_MAX_DURATION = 600;\nexport const FAST_SMOOTH_SHORT_TRANSITION_MAX_DISTANCE = 500; // px\n\n// Average duration of message sending animation\nexport const API_UPDATE_THROTTLE = Math.round((FAST_SMOOTH_MIN_DURATION + FAST_SMOOTH_MAX_DURATION) / 2);\nexport const API_THROTTLE_RESET_UPDATES = new Set([\n 'newMessage', 'newScheduledMessage', 'deleteMessages', 'deleteScheduledMessages', 'deleteHistory',\n]);\n\nexport const STICKER_SIZE_INLINE_DESKTOP_FACTOR = 13;\nexport const STICKER_SIZE_INLINE_MOBILE_FACTOR = 11;\nexport const STICKER_SIZE_AUTH = 160;\nexport const STICKER_SIZE_AUTH_MOBILE = 120;\nexport const STICKER_SIZE_PICKER = 64;\nexport const STICKER_SIZE_GENERAL_SETTINGS = 48;\nexport const STICKER_SIZE_PICKER_HEADER = 32;\nexport const STICKER_SIZE_SEARCH = 64;\nexport const STICKER_SIZE_MODAL = 64;\nexport const STICKER_SIZE_TWO_FA = 160;\nexport const STICKER_SIZE_DISCUSSION_GROUPS = 140;\nexport const STICKER_SIZE_FOLDER_SETTINGS = 80;\nexport const STICKER_SIZE_INLINE_BOT_RESULT = 100;\nexport const RECENT_STICKERS_LIMIT = 20;\nexport const MEMOJI_STICKER_ID = 'MEMOJI_STICKER';\n\nexport const BASE_EMOJI_KEYWORD_LANG = 'en';\n\nexport const MENU_TRANSITION_DURATION = 200;\nexport const SLIDE_TRANSITION_DURATION = 450;\n\nexport const CONTENT_TYPES_FOR_QUICK_UPLOAD = new Set([\n 'image/png', 'image/gif', 'image/jpeg', 'video/mp4', 'video/avi', 'video/quicktime',\n]);\n\n// eslint-disable-next-line max-len\nexport const RE_LINK_TEMPLATE = '((ftp|https?):\\\\/\\\\/)?((www\\\\.)?[-a-zA-Z0-9@:%._+~#=]{1,256}\\\\.[a-zA-Z0-9()]{1,63})\\\\b([-a-zA-Z0-9()@:%_+.~#?&/=]*)';\nexport const RE_MENTION_TEMPLATE = '(@[\\\\w\\\\d_-]+)';\nexport const RE_TME_LINK = /^(?:https?:\\/\\/)?(?:t\\.me\\/)([\\d\\w_]+)(?:\\/([\\d]+))?(?:\\/([\\d]+))?$/gm;\nexport const RE_TME_INVITE_LINK = /^(?:https?:\\/\\/)?(?:t\\.me\\/joinchat\\/)([\\d\\w_-]+)?$/gm;\n\n// MTProto constants\nexport const SERVICE_NOTIFICATIONS_USER_ID = 777000;\nexport const ALL_FOLDER_ID = 0;\nexport const ARCHIVED_FOLDER_ID = 1;\nexport const DELETED_COMMENTS_CHANNEL_ID = 777;\nexport const MAX_MEDIA_FILES_FOR_ALBUM = 10;\nexport const MAX_ACTIVE_PINNED_CHATS = 5;\nexport const SCHEDULED_WHEN_ONLINE = 0x7FFFFFFE;\nexport const DEFAULT_LANG_CODE = 'en';\nexport const DEFAULT_LANG_PACK = 'android';\nexport const LANG_PACKS = ['android', 'ios', 'tdesktop', 'macos'] as const;\nexport const TIPS_USERNAME = 'TelegramTips';\nexport const LOCALIZED_TIPS = ['ar', 'pt-br', 'id', 'it', 'ko', 'ms', 'pl', 'es', 'tr'];\nexport const FEEDBACK_URL = 'https://bugs.telegram.org/?tag_ids=41&sort=time';\nexport const LIGHT_THEME_BG_COLOR = '#A2AF8E';\nexport const DARK_THEME_BG_COLOR = '#0F0F0F';\nexport const DARK_THEME_PATTERN_COLOR = '#0a0a0a8c';\nexport const DEFAULT_PATTERN_COLOR = 'rgba(90, 110, 70, 0.6)';\n","import { useEffect } from '../lib/teact/teact';\nimport usePrevious from './usePrevious';\n\nexport default <T extends any[], PT = T>(cb: (args: PT) => void, dependencies: T, debugKey?: string) => {\n const prevDeps = usePrevious<T>(dependencies);\n return useEffect(() => {\n // @ts-ignore (workaround for \"could be instantiated with a different subtype\" issue)\n return cb(prevDeps || []);\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, dependencies, debugKey);\n};\n","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 { 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 { useEffect } from '../lib/teact/teact';\n\nexport const ANIMATION_START_EVENT = 'tt-event-heavy-animation-start';\nexport const ANIMATION_END_EVENT = 'tt-event-heavy-animation-end';\n\nlet timeout: number | undefined;\nlet isAnimating = false;\n\nexport const dispatchHeavyAnimationEvent = (duration?: number) => {\n if (!isAnimating) {\n isAnimating = true;\n document.dispatchEvent(new Event(ANIMATION_START_EVENT));\n }\n\n if (timeout) {\n clearTimeout(timeout);\n timeout = undefined;\n }\n\n if (duration) {\n timeout = window.setTimeout(() => {\n isAnimating = false;\n document.dispatchEvent(new Event(ANIMATION_END_EVENT));\n timeout = undefined;\n }, duration);\n }\n\n return () => {\n isAnimating = false;\n document.dispatchEvent(new Event(ANIMATION_END_EVENT));\n };\n};\n\nexport default (\n handleAnimationStart: AnyToVoidFunction,\n handleAnimationEnd: AnyToVoidFunction,\n) => {\n useEffect(() => {\n if (isAnimating) {\n handleAnimationStart();\n }\n\n document.addEventListener(ANIMATION_START_EVENT, handleAnimationStart);\n document.addEventListener(ANIMATION_END_EVENT, handleAnimationEnd);\n\n return () => {\n document.removeEventListener(ANIMATION_END_EVENT, handleAnimationEnd);\n document.removeEventListener(ANIMATION_START_EVENT, handleAnimationStart);\n };\n }, [handleAnimationEnd, handleAnimationStart]);\n};\n","import { useCallback, useEffect, useRef } from '../lib/teact/teact';\n\nimport { IS_IOS } from '../util/environment';\nimport usePrevious from './usePrevious';\nimport { getDispatch } from '../lib/teact/teactn';\nimport { areSortedArraysEqual } from '../util/iteratees';\n\n// Carefully selected by swiping and observing visual changes\n// TODO: may be different on other devices such as iPad, maybe take dpi into account?\nconst SAFARI_EDGE_BACK_GESTURE_LIMIT = 300;\nconst SAFARI_EDGE_BACK_GESTURE_DURATION = 350;\nexport const LOCATION_HASH = window.location.hash;\n\ntype HistoryState = {\n currentIndex: number;\n nextStateIndexToReplace: number;\n isHistoryAltered: boolean;\n isDisabled: boolean;\n isEdge: boolean;\n currentIndexes: number[];\n};\n\nconst historyState: HistoryState = {\n currentIndex: 0,\n nextStateIndexToReplace: -1,\n isHistoryAltered: false,\n isDisabled: false,\n isEdge: false,\n currentIndexes: [],\n};\n\nexport const disableHistoryBack = () => {\n historyState.isDisabled = true;\n};\n\nconst handleTouchStart = (event: TouchEvent) => {\n const x = event.touches[0].pageX;\n\n if (x <= SAFARI_EDGE_BACK_GESTURE_LIMIT || x >= window.innerWidth - SAFARI_EDGE_BACK_GESTURE_LIMIT) {\n historyState.isEdge = true;\n }\n};\n\nconst handleTouchEnd = () => {\n if (historyState.isEdge) {\n setTimeout(() => {\n historyState.isEdge = false;\n }, SAFARI_EDGE_BACK_GESTURE_DURATION);\n }\n};\n\nif (IS_IOS) {\n window.addEventListener('touchstart', handleTouchStart);\n window.addEventListener('touchend', handleTouchEnd);\n window.addEventListener('popstate', handleTouchEnd);\n}\n\nwindow.history.replaceState({ index: historyState.currentIndex }, '', window.location.pathname);\n\nexport default function useHistoryBack(\n isActive: boolean | undefined,\n onBack: ((noDisableAnimation: boolean) => void) | undefined,\n onForward?: (state: any) => void,\n currentState?: any,\n shouldReplaceNext = false,\n hashes?: string[],\n) {\n const indexRef = useRef(-1);\n const isForward = useRef(false);\n const prevIsActive = usePrevious(isActive);\n const isClosed = useRef(true);\n const indexHashRef = useRef<{ index: number; hash: string }[]>([]);\n const prevHashes = usePrevious(hashes);\n const isHashChangedFromEvent = useRef<boolean>(false);\n\n const handleChange = useCallback((isForceClose = false) => {\n if (!hashes) {\n if (isActive && !isForceClose) {\n isClosed.current = false;\n\n if (isForward.current) {\n isForward.current = false;\n historyState.currentIndexes.push(indexRef.current);\n } else {\n setTimeout(() => {\n const index = ++historyState.currentIndex;\n\n historyState.currentIndexes.push(index);\n\n window.history[\n (historyState.currentIndexes.includes(historyState.nextStateIndexToReplace - 1)\n && window.history.state.index !== 0\n && historyState.nextStateIndexToReplace === index\n && !shouldReplaceNext)\n ? 'replaceState'\n : 'pushState'\n ]({\n index,\n state: currentState,\n }, '');\n\n indexRef.current = index;\n\n if (shouldReplaceNext) {\n historyState.nextStateIndexToReplace = historyState.currentIndex + 1;\n }\n }, 0);\n }\n }\n\n if ((isForceClose || !isActive) && !isClosed.current) {\n if ((indexRef.current === historyState.currentIndex || !shouldReplaceNext)) {\n historyState.isHistoryAltered = true;\n window.history.back();\n\n setTimeout(() => {\n historyState.nextStateIndexToReplace = -1;\n }, 400);\n }\n historyState.currentIndexes.splice(historyState.currentIndexes.indexOf(indexRef.current), 1);\n\n isClosed.current = true;\n }\n } else {\n const prev = prevHashes || [];\n if (prev.length < hashes.length) {\n const index = ++historyState.currentIndex;\n historyState.currentIndexes.push(index);\n\n window.history.pushState({\n index,\n state: currentState,\n }, '', `#${hashes[hashes.length - 1]}`);\n\n indexHashRef.current.push({\n index,\n hash: hashes[hashes.length - 1],\n });\n } else {\n const delta = prev.length - hashes.length;\n if (isHashChangedFromEvent.current) {\n isHashChangedFromEvent.current = false;\n } else {\n if (hashes.length !== indexHashRef.current.length) {\n if (delta > 0) {\n const last = indexHashRef.current[indexHashRef.current.length - delta - 1];\n let realDelta = delta;\n if (last) {\n const indexLast = historyState.currentIndexes.findIndex(\n (l) => l === last.index,\n );\n realDelta = historyState.currentIndexes.length - indexLast - 1;\n }\n historyState.isHistoryAltered = true;\n window.history.go(-realDelta);\n const removed = indexHashRef.current.splice(indexHashRef.current.length - delta - 1, delta);\n removed.forEach(({ index }) => {\n historyState.currentIndexes.splice(historyState.currentIndexes.indexOf(index), 1);\n });\n }\n }\n\n if (hashes.length > 0) {\n setTimeout(() => {\n const index = ++historyState.currentIndex;\n historyState.currentIndexes[historyState.currentIndexes.length - 1] = index;\n\n window.history.replaceState({\n index,\n state: currentState,\n }, '', `#${hashes[hashes.length - 1]}`);\n\n indexHashRef.current[indexHashRef.current.length - 1] = {\n index,\n hash: hashes[hashes.length - 1],\n };\n }, 0);\n }\n }\n }\n }\n }, [currentState, hashes, isActive, prevHashes, shouldReplaceNext]);\n\n useEffect(() => {\n const handlePopState = (event: PopStateEvent) => {\n if (historyState.isHistoryAltered) {\n setTimeout(() => {\n historyState.isHistoryAltered = false;\n }, 0);\n return;\n }\n const { index: i } = event.state;\n const index = i || 0;\n try {\n const currIndex = hashes ? indexHashRef.current[indexHashRef.current.length - 1].index : indexRef.current;\n\n const prev = historyState.currentIndexes[historyState.currentIndexes.indexOf(currIndex) - 1];\n\n if (historyState.isDisabled) return;\n\n if ((!isClosed.current && (index === 0 || index === prev)) || (hashes && (index === 0 || index === prev))) {\n if (hashes) {\n isHashChangedFromEvent.current = true;\n indexHashRef.current.pop();\n }\n\n historyState.currentIndexes.splice(historyState.currentIndexes.indexOf(currIndex), 1);\n\n if (onBack) {\n if (historyState.isEdge) {\n getDispatch()\n .disableHistoryAnimations();\n }\n onBack(!historyState.isEdge);\n isClosed.current = true;\n }\n } else if (index === currIndex && isClosed.current && onForward && !hashes) {\n isForward.current = true;\n if (historyState.isEdge) {\n getDispatch()\n .disableHistoryAnimations();\n }\n onForward(event.state.state);\n }\n } catch (e) {\n // Forward navigation for hashed is not supported\n }\n };\n\n const hasChanged = hashes\n ? (!prevHashes || !areSortedArraysEqual(prevHashes, hashes))\n : prevIsActive !== isActive;\n\n if (!historyState.isDisabled && hasChanged) {\n handleChange();\n }\n\n window.addEventListener('popstate', handlePopState);\n return () => window.removeEventListener('popstate', handlePopState);\n }, [\n currentState, handleChange, hashes, isActive, onBack, onForward, prevHashes, prevIsActive, shouldReplaceNext,\n ]);\n\n return {\n forceClose: () => handleChange(true),\n };\n}\n","import { RefObject } from 'react';\nimport { useState, useCallback, useEffect } from '../lib/teact/teact';\n\nexport default (\n elementRef: RefObject<HTMLElement>,\n isOpen: boolean,\n onSelectWithEnter?: (index: number) => void,\n itemSelector?: string,\n noCaptureFocus?: boolean,\n) => {\n const [focusedIndex, setFocusedIndex] = useState(-1);\n\n useEffect(() => {\n setFocusedIndex(-1);\n\n const element = elementRef.current;\n if (isOpen && element && !noCaptureFocus) {\n element.tabIndex = -1;\n element.focus();\n }\n }, [elementRef, isOpen, noCaptureFocus]);\n\n const handleKeyDown = useCallback((e: React.KeyboardEvent<any>) => {\n const element = elementRef.current;\n\n if (!element) {\n return;\n }\n\n if (e.keyCode === 13 && onSelectWithEnter) {\n onSelectWithEnter(focusedIndex);\n return;\n }\n\n if (e.keyCode !== 38 && e.keyCode !== 40) {\n return;\n }\n\n const focusedElement = document.activeElement;\n const elementChildren = Array.from(itemSelector ? element.querySelectorAll(itemSelector) : element.children);\n\n let newIndex = (focusedElement && elementChildren.indexOf(focusedElement)) || focusedIndex;\n\n if (e.keyCode === 38 && newIndex > 0) {\n newIndex--;\n } else if (e.keyCode === 40 && newIndex < elementChildren.length - 1) {\n newIndex++;\n } else if (elementChildren.length === 1) {\n newIndex = 0;\n } else {\n return;\n }\n\n const item = elementChildren[newIndex] as HTMLElement;\n if (item) {\n setFocusedIndex(newIndex);\n item.focus();\n }\n }, [elementRef, onSelectWithEnter, itemSelector, focusedIndex]);\n\n return handleKeyDown;\n};\n","import * as langProvider from '../util/langProvider';\nimport useForceUpdate from './useForceUpdate';\nimport useOnChange from './useOnChange';\n\nexport type LangFn = typeof langProvider.getTranslation;\n\nexport default (): LangFn => {\n const forceUpdate = useForceUpdate();\n\n useOnChange(() => {\n return langProvider.addCallback(forceUpdate);\n }, [forceUpdate]);\n\n return langProvider.getTranslation;\n};\n","import { useEffect } from '../lib/teact/teact';\n\nimport {\n BundleModules, Bundles, getModuleFromMemory, loadModule, addLoadListener,\n} from '../util/moduleLoader';\n\nimport useForceUpdate from './useForceUpdate';\n\nexport default <B extends Bundles, M extends BundleModules<B>>(\n bundleName: B, moduleName: M, noLoad = false, autoUpdate = false,\n) => {\n const module = getModuleFromMemory(bundleName, moduleName);\n const forceUpdate = useForceUpdate();\n\n if (autoUpdate) {\n // Use effect and cleanup for listener removal\n addLoadListener(forceUpdate);\n }\n\n useEffect(() => {\n if (!noLoad && !module) {\n loadModule(bundleName, moduleName).then(forceUpdate);\n }\n }, [bundleName, forceUpdate, module, moduleName, noLoad]);\n\n return module;\n};\n","import usePrevious from './usePrevious';\n\nexport default <T extends any[], PT = T>(cb: (args: PT) => void, dependencies: T) => {\n const prevDeps = usePrevious<T>(dependencies);\n if (!prevDeps || dependencies.some((d, i) => d !== prevDeps[i])) {\n // @ts-ignore (workaround for \"could be instantiated with a different subtype\" issue)\n cb(prevDeps || []);\n }\n};\n","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 { 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 // `noCloseTransition`, when set to true, should remove the open class immediately\n const shouldHaveOpenClassName = hasOpenClassName && !(noCloseTransition && !isOpen);\n const isClosing = Boolean(closeTimeoutRef.current);\n const shouldRender = isOpen || isClosing;\n const transitionClassNames = buildClassName(\n className && 'opacity-transition',\n className,\n shouldHaveOpenClassName && 'open',\n shouldRender && 'shown',\n isClosing && 'closing',\n );\n\n return {\n shouldRender,\n transitionClassNames,\n };\n};\n","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","import { DEBUG } from '../../config';\n\ntype Handler = (e: Event) => void;\n\nconst NON_BUBBLEABLE_EVENTS = new Set(['scroll', 'mouseenter', 'mouseleave']);\n\nconst delegationRegistry: Record<string, Map<HTMLElement, Handler>> = {};\nconst delegatedEventsByElement = new Map<HTMLElement, Set<string>>();\nconst documentEventCounters: Record<string, number> = {};\n\nexport function addEventListener(element: HTMLElement, propName: string, handler: Handler, asCapture = false) {\n const eventName = resolveEventName(propName, element);\n if (canUseEventDelegation(eventName, element, asCapture)) {\n addDelegatedListener(eventName, element, handler);\n } else {\n element.addEventListener(eventName, handler, asCapture);\n }\n}\n\nexport function removeEventListener(element: HTMLElement, propName: string, handler: Handler, asCapture = false) {\n const eventName = resolveEventName(propName, element);\n if (canUseEventDelegation(eventName, element, asCapture)) {\n removeDelegatedListener(eventName, element);\n } else {\n element.removeEventListener(eventName, handler, asCapture);\n }\n}\n\nfunction resolveEventName(propName: string, element: HTMLElement) {\n const eventName = propName\n .replace(/^on/, '')\n .replace(/Capture$/, '').toLowerCase();\n\n if (eventName === 'change' && element.tagName !== 'SELECT') {\n // React behavior repeated here.\n // https://stackoverflow.com/questions/38256332/in-react-whats-the-difference-between-onchange-and-oninput\n return 'input';\n }\n\n if (eventName === 'doubleclick') {\n return 'dblclick';\n }\n\n // Replace focus/blur by their \"bubbleable\" versions\n if (eventName === 'focus') {\n return 'focusin';\n }\n\n if (eventName === 'blur') {\n return 'focusout';\n }\n\n return eventName;\n}\n\nfunction canUseEventDelegation(realEventName: string, element: HTMLElement, asCapture: boolean) {\n return (\n !asCapture\n && !NON_BUBBLEABLE_EVENTS.has(realEventName)\n && element.tagName !== 'VIDEO'\n && element.tagName !== 'IFRAME'\n );\n}\n\nfunction addDelegatedListener(eventName: string, element: HTMLElement, handler: Handler) {\n if (!documentEventCounters[eventName]) {\n documentEventCounters[eventName] = 0;\n document.addEventListener(eventName, handleEvent);\n }\n\n resolveDelegationRegistryForName(eventName).set(element, handler);\n resolveDelegatedEventsForElement(element).add(eventName);\n documentEventCounters[eventName]++;\n}\n\nfunction removeDelegatedListener(eventName: string, element: HTMLElement) {\n documentEventCounters[eventName]--;\n if (!documentEventCounters[eventName]) {\n // Synchronous deletion on 0 will cause perf degradation in the case of 1 element\n // which is not a real case, so it's ok to do it this way\n document.removeEventListener(eventName, handleEvent);\n }\n\n delegationRegistry[eventName].delete(element);\n delegatedEventsByElement.get(element)!.delete(eventName);\n}\n\nexport function removeAllDelegatedListeners(element: HTMLElement) {\n const eventNames = delegatedEventsByElement.get(element);\n if (!eventNames) {\n return;\n }\n\n eventNames.forEach((eventName) => removeDelegatedListener(eventName, element));\n delegatedEventsByElement.delete(element);\n}\n\nfunction handleEvent(realEvent: Event) {\n const events = delegationRegistry[realEvent.type];\n\n if (events) {\n let furtherCallsPrevented = false;\n let current: HTMLElement = realEvent.target as HTMLElement;\n\n const stopPropagation = () => {\n furtherCallsPrevented = true;\n };\n\n const preventDefault = () => {\n realEvent.preventDefault();\n };\n\n // Proxy is a simplest way to provide an access to the event property\n const event = new Proxy(realEvent, {\n get(target, p) {\n if (p === 'currentTarget') {\n return current;\n }\n if (p === 'stopPropagation' || p === 'stopImmediatePropagation') {\n return stopPropagation;\n }\n if (p === 'preventDefault') {\n // \"this\" is changed to proxy and one can't call methods via it\n return preventDefault;\n }\n return Reflect.get(target, p);\n },\n });\n\n // This can also be limited by teact root\n while (current && current !== document.body) {\n const handler = events.get(current);\n if (handler) {\n handler(event);\n if (furtherCallsPrevented) {\n return;\n }\n }\n\n current = current.parentNode as HTMLElement;\n }\n }\n}\n\nfunction resolveDelegationRegistryForName(eventName: string) {\n if (!delegationRegistry[eventName]) {\n delegationRegistry[eventName] = new Map();\n }\n\n return delegationRegistry[eventName];\n}\n\nfunction resolveDelegatedEventsForElement(element: HTMLElement) {\n const existing = delegatedEventsByElement.get(element);\n if (existing) {\n return existing;\n }\n\n const newSet = new Set<string>();\n delegatedEventsByElement.set(element, newSet);\n\n return newSet;\n}\n\nif (DEBUG) {\n document.addEventListener('dblclick', () => {\n // eslint-disable-next-line no-console\n console.log('DELEGATED EVENTS', { delegationRegistry, delegatedEventsByElement, documentEventCounters });\n });\n}\n","import {\n hasElementChanged,\n isComponentElement,\n isEmptyElement,\n isRealElement,\n isTextElement,\n mountComponent,\n renderComponent,\n unmountTree,\n getTarget,\n setTarget,\n VirtualElement,\n VirtualElementComponent,\n VirtualRealElement,\n} from './teact';\nimport generateIdFor from '../../util/generateIdFor';\nimport { DEBUG } from '../../config';\nimport { addEventListener, removeEventListener } from './dom-events';\n\ntype VirtualDomHead = {\n children: [VirtualElement] | [];\n};\n\nconst FILTERED_ATTRIBUTES = new Set(['key', 'ref', 'teactFastList', 'teactOrderKey']);\nconst HTML_ATTRIBUTES = new Set(['dir']);\nconst MAPPED_ATTRIBUTES: { [k: string]: string } = {\n autoPlay: 'autoplay',\n autoComplete: 'autocomplete',\n};\nconst INDEX_KEY_PREFIX = '__indexKey#';\n\nconst headsByElement: Record<string, VirtualDomHead> = {};\n// eslint-disable-next-line @typescript-eslint/naming-convention\nlet DEBUG_virtualTreeSize = 1;\n\nfunction render($element?: VirtualElement, parentEl?: HTMLElement | null) {\n if (!parentEl) {\n return undefined;\n }\n\n let headId = parentEl.getAttribute('data-teact-head-id');\n if (!headId) {\n headId = generateIdFor(headsByElement);\n headsByElement[headId] = { children: [] };\n parentEl.setAttribute('data-teact-head-id', headId);\n }\n\n const $head = headsByElement[headId];\n $head.children = [renderWithVirtual(parentEl, $head.children[0], $element, $head, 0) as VirtualElement];\n\n if (process.env.APP_ENV === 'perf') {\n DEBUG_virtualTreeSize = 0;\n DEBUG_addToVirtualTreeSize($head);\n\n return DEBUG_virtualTreeSize;\n }\n\n return undefined;\n}\n\nfunction renderWithVirtual(\n parentEl: HTMLElement,\n $current: VirtualElement | undefined,\n $new: VirtualElement | undefined,\n $parent: VirtualRealElement | VirtualDomHead,\n index: number,\n {\n skipComponentUpdate = false,\n forceIndex = false,\n fragment,\n moveDirection,\n }: {\n skipComponentUpdate?: boolean;\n forceIndex?: boolean;\n fragment?: DocumentFragment;\n moveDirection?: 'up' | 'down';\n } = {},\n) {\n if (\n !skipComponentUpdate\n && $current && $new\n && isComponentElement($current) && isComponentElement($new)\n && !hasElementChanged($current, $new)\n ) {\n $new = updateComponent($current, $new);\n }\n\n // Parent element may have changed, so we need to update the listener closure.\n if (!skipComponentUpdate && $new && isComponentElement($new) && $new.componentInstance.isMounted) {\n setupComponentUpdateListener($new, $parent, index, parentEl);\n }\n\n if ($current === $new) {\n return $new;\n }\n\n if (!$current && $new) {\n if (isComponentElement($new)) {\n $new = initComponent($new, $parent, index, parentEl);\n }\n\n const node = createNode($new);\n setTarget($new, node);\n\n if (forceIndex && parentEl.childNodes[index]) {\n parentEl.insertBefore(node, parentEl.childNodes[index]);\n } else {\n (fragment || parentEl).appendChild(node);\n }\n } else if ($current && !$new) {\n parentEl.removeChild(getTarget($current)!);\n unmountTree($current);\n } else if ($current && $new) {\n if (hasElementChanged($current, $new)) {\n if (isComponentElement($new)) {\n $new = initComponent($new, $parent, index, parentEl);\n }\n\n const node = createNode($new);\n setTarget($new, node);\n parentEl.replaceChild(node, getTarget($current)!);\n unmountTree($current);\n } else {\n const areComponents = isComponentElement($current) && isComponentElement($new);\n\n if (!areComponents) {\n setTarget($new, getTarget($current)!);\n }\n\n if (isRealElement($current) && isRealElement($new)) {\n if (moveDirection) {\n const node = getTarget($current)!;\n const nextSibling = parentEl.childNodes[moveDirection === 'up' ? index : index + 1];\n\n if (nextSibling) {\n parentEl.insertBefore(node, nextSibling);\n } else {\n (fragment || parentEl).appendChild(node);\n }\n }\n\n if (!areComponents) {\n updateAttributes($current, $new, getTarget($current) as HTMLElement);\n }\n\n $new.children = renderChildren(\n $current,\n $new,\n areComponents ? parentEl : getTarget($current) as HTMLElement,\n );\n }\n }\n }\n\n return $new;\n}\n\nfunction initComponent(\n $element: VirtualElementComponent, $parent: VirtualRealElement | VirtualDomHead, index: number, parentEl: HTMLElement,\n) {\n if (!isComponentElement($element)) {\n return $element;\n }\n\n const { componentInstance } = $element;\n\n if (!componentInstance.isMounted) {\n $element = mountComponent(componentInstance);\n setupComponentUpdateListener($element, $parent, index, parentEl);\n\n const $firstChild = $element.children[0];\n if (isComponentElement($firstChild)) {\n $element.children = [initComponent($firstChild, $element, 0, parentEl)];\n }\n\n componentInstance.isMounted = true;\n }\n\n return $element;\n}\n\nfunction updateComponent($current: VirtualElementComponent, $new: VirtualElementComponent) {\n $current.componentInstance.props = $new.componentInstance.props;\n\n return renderComponent($current.componentInstance);\n}\n\nfunction setupComponentUpdateListener(\n $element: VirtualElementComponent, $parent: VirtualRealElement | VirtualDomHead, index: number, parentEl: HTMLElement,\n) {\n const { componentInstance } = $element;\n\n componentInstance.onUpdate = () => {\n $parent.children[index] = renderWithVirtual(\n parentEl,\n $parent.children[index],\n componentInstance.$element,\n $parent,\n index,\n { skipComponentUpdate: true },\n ) as VirtualElementComponent;\n };\n}\n\nfunction createNode($element: VirtualElement): Node {\n if (isEmptyElement($element)) {\n return document.createTextNode('');\n }\n\n if (isTextElement($element)) {\n return document.createTextNode($element.value);\n }\n\n if (isComponentElement($element)) {\n return createNode($element.children[0] as VirtualElement);\n }\n\n const { tag, props, children = [] } = $element;\n const element = document.createElement(tag);\n\n if (typeof props.ref === 'object') {\n props.ref.current = element;\n }\n\n Object.keys(props).forEach((key) => {\n addAttribute(element, key, props[key]);\n });\n\n $element.children = children.map(($child, i) => (\n renderWithVirtual(element, undefined, $child, $element, i) as VirtualElement\n ));\n\n return element;\n}\n\nfunction renderChildren(\n $current: VirtualRealElement, $new: VirtualRealElement, currentEl: HTMLElement,\n) {\n if ($new.props.teactFastList) {\n return renderFastListChildren($current, $new, currentEl);\n }\n\n const maxLength = Math.max($current.children.length, $new.children.length);\n const newChildren = [];\n const fragment = $new.children.length > $current.children.length + 1 ? document.createDocumentFragment() : undefined;\n\n for (let i = 0; i < maxLength; i++) {\n const $newChild = renderWithVirtual(\n currentEl,\n $current.children[i],\n $new.children[i],\n $new,\n i,\n i >= $current.children.length ? { fragment } : undefined,\n );\n\n if ($newChild) {\n newChildren.push($newChild);\n }\n }\n\n if (fragment) {\n currentEl.appendChild(fragment);\n }\n\n return newChildren;\n}\n\nfunction renderFastListChildren($current: VirtualRealElement, $new: VirtualRealElement, currentEl: HTMLElement) {\n const newKeys = new Set(\n $new.children.map(($newChild) => {\n const key = 'props' in $newChild && $newChild.props.key;\n\n if (DEBUG && isRealElement($newChild) && !key) {\n // eslint-disable-next-line no-console\n console.warn('Missing `key` in `teactFastList`');\n }\n\n return key;\n }),\n );\n\n let currentRemainingIndex = 0;\n const remainingByKey = $current.children\n .reduce((acc, $currentChild, i) => {\n let key = 'props' in $currentChild ? $currentChild.props.key : undefined;\n\n // First we handle removed children\n if (key && !newKeys.has(key)) {\n renderWithVirtual(currentEl, $currentChild, undefined, $new, -1);\n\n return acc;\n } else if (!key) {\n const $newChild = $new.children[i];\n const newChildKey = ($newChild && 'props' in $newChild) ? $newChild.props.key : undefined;\n // If a non-key element remains at the same index we preserve it with a virtual `key`\n if ($newChild && !newChildKey) {\n key = `${INDEX_KEY_PREFIX}${i}`;\n } else {\n renderWithVirtual(currentEl, $currentChild, undefined, $new, -1);\n\n return acc;\n }\n }\n\n // Then we build up info about remaining children\n acc[key] = {\n $element: $currentChild,\n index: currentRemainingIndex++,\n order: 'props' in $currentChild ? $currentChild.props.teactOrderKey : undefined,\n };\n return acc;\n }, {} as Record<string, { $element: VirtualElement; index: number; order?: number }>);\n\n let newChildren: VirtualElement[] = [];\n\n let fragmentQueue: VirtualElement[] | undefined;\n let fragmentIndex: number | undefined;\n\n let currentPreservedIndex = 0;\n\n $new.children.forEach(($newChild, i) => {\n const key = 'props' in $newChild ? $newChild.props.key : `${INDEX_KEY_PREFIX}${i}`;\n const currentChildInfo = remainingByKey[key];\n\n if (!currentChildInfo) {\n // All new nodes are queued to be inserted with fragments if possible.\n if (!fragmentQueue) {\n fragmentQueue = [];\n fragmentIndex = i;\n }\n\n fragmentQueue.push($newChild);\n return;\n }\n\n if (fragmentQueue) {\n newChildren = newChildren.concat(flushFragmentQueue(fragmentQueue, fragmentIndex!, currentEl, $new));\n fragmentIndex = undefined;\n fragmentQueue = undefined;\n }\n\n // This is a \"magic\" `teactOrderKey` property that tells us the element is updated\n const order = 'props' in $newChild ? $newChild.props.teactOrderKey : undefined;\n const shouldMoveNode = currentChildInfo.index !== currentPreservedIndex && currentChildInfo.order !== order;\n const isMovingDown = shouldMoveNode && currentPreservedIndex > currentChildInfo.index;\n\n // When the node goes down, preserved indexing actually breaks, so the \"magic\" should help.\n if (!shouldMoveNode || isMovingDown) {\n currentPreservedIndex++;\n }\n\n newChildren.push(\n renderWithVirtual(currentEl, currentChildInfo.$element, $newChild, $new, i, {\n forceIndex: true,\n ...(shouldMoveNode && {\n moveDirection: isMovingDown ? 'down' : 'up',\n }),\n })!,\n );\n });\n\n if (fragmentQueue) {\n newChildren = newChildren.concat(flushFragmentQueue(fragmentQueue, fragmentIndex!, currentEl, $new));\n }\n\n return newChildren;\n}\n\nfunction flushFragmentQueue(\n fragmentQueue: VirtualElement[], fragmentIndex: number, parentEl: HTMLElement, $parent: VirtualRealElement,\n) {\n if (fragmentQueue.length === 1) {\n return [renderWithVirtual(parentEl, undefined, fragmentQueue[0], $parent, fragmentIndex, { forceIndex: true })!];\n } else if (fragmentQueue.length > 1) {\n const fragment = document.createDocumentFragment();\n const newChildren = fragmentQueue.map(($fragmentChild) => (\n renderWithVirtual(parentEl, undefined, $fragmentChild, $parent, fragmentIndex!, { fragment })!\n ));\n\n if (parentEl.childNodes[fragmentIndex]) {\n parentEl.insertBefore(fragment, parentEl.childNodes[fragmentIndex]);\n } else {\n parentEl.appendChild(fragment);\n }\n\n return newChildren;\n }\n\n throw new Error('Unexpected input');\n}\n\nfunction updateAttributes($current: VirtualRealElement, $new: VirtualRealElement, element: HTMLElement) {\n const currentKeys = Object.keys($current.props);\n const newKeys = Object.keys($new.props);\n\n currentKeys.forEach((key) => {\n if ($current.props[key] !== undefined && $new.props[key] === undefined) {\n removeAttribute(element, key, $current.props[key]);\n }\n });\n\n newKeys.forEach((key) => {\n if ($new.props[key] === undefined) {\n return;\n }\n\n if ($current.props[key] !== $new.props[key]) {\n if ($current.props[key] === undefined) {\n addAttribute(element, key, $new.props[key]);\n } else {\n updateAttribute(element, key, $current.props[key], $new.props[key]);\n }\n }\n });\n}\n\nfunction addAttribute(element: HTMLElement, key: string, value: any) {\n if (value === undefined) {\n return;\n }\n\n // An optimization attempt\n if (key === 'className') {\n element.className = value;\n // An optimization attempt\n } else if (key === 'value') {\n (element as HTMLInputElement).value = value;\n } else if (key === 'style') {\n element.style.cssText = value;\n } else if (key.startsWith('on')) {\n addEventListener(element, key, value, key.endsWith('Capture'));\n } else if (key.startsWith('data-') || HTML_ATTRIBUTES.has(key)) {\n element.setAttribute(key, value);\n } else if (!FILTERED_ATTRIBUTES.has(key)) {\n (element as any)[MAPPED_ATTRIBUTES[key] || key] = value;\n }\n}\n\nfunction removeAttribute(element: HTMLElement, key: string, value: any) {\n if (key === 'className') {\n element.className = '';\n } else if (key === 'value') {\n (element as HTMLInputElement).value = '';\n } else if (key === 'style') {\n element.style.cssText = '';\n } else if (key.startsWith('on')) {\n removeEventListener(element, key, value, key.endsWith('Capture'));\n } else if (key.startsWith('data-') || HTML_ATTRIBUTES.has(key)) {\n element.removeAttribute(key);\n } else if (!FILTERED_ATTRIBUTES.has(key)) {\n delete (element as any)[MAPPED_ATTRIBUTES[key] || key];\n }\n}\n\nfunction updateAttribute(element: HTMLElement, key: string, oldValue: any, newValue: any) {\n if (key === 'value') {\n // Removing and adding value causes a cursor jump\n (element as HTMLInputElement).value = newValue !== undefined ? newValue : '';\n } else {\n removeAttribute(element, key, oldValue);\n addAttribute(element, key, newValue);\n }\n}\n\n// eslint-disable-next-line @typescript-eslint/naming-convention\nfunction DEBUG_addToVirtualTreeSize($current: VirtualRealElement | VirtualDomHead) {\n DEBUG_virtualTreeSize += $current.children.length;\n\n $current.children.forEach(($child) => {\n if (isRealElement($child)) {\n DEBUG_addToVirtualTreeSize($child);\n }\n });\n}\n\nexport default { render };\n","import { 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;\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport type FC_withDebug =\n FC\n & {\n DEBUG_contentComponentName?: string;\n };\n\nexport enum VirtualElementTypesEnum {\n Empty,\n Text,\n Tag,\n Component,\n}\n\ninterface VirtualElementEmpty {\n type: VirtualElementTypesEnum.Empty;\n target?: Node;\n}\n\ninterface VirtualElementText {\n type: VirtualElementTypesEnum.Text;\n target?: Node;\n value: string;\n}\n\nexport interface VirtualElementTag {\n type: VirtualElementTypesEnum.Tag;\n target?: Node;\n tag: string;\n props: Props;\n children: VirtualElementChildren;\n}\n\nexport interface VirtualElementComponent {\n type: VirtualElementTypesEnum.Component;\n componentInstance: ComponentInstance;\n props: Props;\n children: VirtualElementChildren;\n}\n\nexport type StateHookSetter<T> = (newValue: ((current: T) => T) | T) => void;\n\ninterface ComponentInstance {\n $element: VirtualElementComponent;\n Component: FC;\n name: string;\n props: Props;\n renderedValue?: any;\n isMounted: boolean;\n hooks: {\n state: {\n cursor: number;\n byCursor: {\n value: any;\n nextValue: any;\n setter: StateHookSetter<any>;\n }[];\n };\n effects: {\n cursor: number;\n byCursor: {\n effect: () => void;\n dependencies?: any[];\n cleanup?: Function;\n }[];\n };\n memos: {\n cursor: number;\n byCursor: {\n current: any;\n dependencies: any[];\n }[];\n };\n };\n prepareForFrame?: () => void;\n forceUpdate?: () => void;\n onUpdate?: () => void;\n}\n\nexport type VirtualElement =\n VirtualElementEmpty\n | VirtualElementText\n | VirtualElementTag\n | VirtualElementComponent;\nexport type VirtualRealElement =\n VirtualElementTag\n | VirtualElementComponent;\nexport type VirtualElementChildren = VirtualElement[];\n\nconst Fragment = Symbol('Fragment');\n\nlet renderingInstance: ComponentInstance;\n\nexport function isEmptyElement($element: VirtualElement): $element is VirtualElementEmpty {\n return $element.type === VirtualElementTypesEnum.Empty;\n}\n\nexport function isTextElement($element: VirtualElement): $element is VirtualElementText {\n return $element.type === VirtualElementTypesEnum.Text;\n}\n\nexport function isTagElement($element: VirtualElement): $element is VirtualElementTag {\n return $element.type === VirtualElementTypesEnum.Tag;\n}\n\nexport function isComponentElement($element: VirtualElement): $element is VirtualElementComponent {\n return $element.type === VirtualElementTypesEnum.Component;\n}\n\nexport function isRealElement($element: VirtualElement): $element is VirtualRealElement {\n return isTagElement($element) || isComponentElement($element);\n}\n\nfunction createElement(\n source: string | FC | typeof Fragment,\n props: Props,\n ...children: any[]\n): VirtualRealElement | VirtualElementChildren {\n if (!props) {\n props = {};\n }\n\n children = flatten(children);\n\n if (source === Fragment) {\n return children;\n } else if (typeof source === 'function') {\n return createComponentInstance(source, props, children);\n } else {\n return buildTagElement(source, props, children);\n }\n}\n\nfunction createComponentInstance(Component: FC, props: Props, children: any[]): VirtualElementComponent {\n let parsedChildren: any | any[] | undefined;\n if (children.length === 0) {\n parsedChildren = undefined;\n } else if (children.length === 1) {\n [parsedChildren] = children;\n } else {\n parsedChildren = children;\n }\n\n const componentInstance: ComponentInstance = {\n $element: {} as VirtualElementComponent,\n Component,\n name: Component.name,\n props: {\n ...props,\n ...(parsedChildren && { children: parsedChildren }),\n },\n isMounted: false,\n hooks: {\n state: {\n cursor: 0,\n byCursor: [],\n },\n effects: {\n cursor: 0,\n byCursor: [],\n },\n memos: {\n cursor: 0,\n byCursor: [],\n },\n },\n };\n\n componentInstance.$element = buildComponentElement(componentInstance);\n\n return componentInstance.$element;\n}\n\nfunction buildComponentElement(\n componentInstance: ComponentInstance,\n children: VirtualElementChildren = [],\n): VirtualElementComponent {\n const { props } = componentInstance;\n\n return {\n componentInstance,\n type: VirtualElementTypesEnum.Component,\n props,\n children,\n };\n}\n\nfunction buildTagElement(tag: string, props: Props, children: any[]): VirtualElementTag {\n return {\n type: VirtualElementTypesEnum.Tag,\n tag,\n props,\n children: dropEmptyTail(children).map(buildChildElement),\n };\n}\n\n// We only need placeholders in the middle of collection (to ensure other elements order).\nfunction dropEmptyTail(children: any[]) {\n let i = children.length - 1;\n\n for (; i >= 0; i--) {\n if (!isEmptyPlaceholder(children[i])) {\n break;\n }\n }\n\n return i + 1 < children.length ? children.slice(0, i + 1) : children;\n}\n\nfunction isEmptyPlaceholder(child: any) {\n // eslint-disable-next-line no-null/no-null\n return child === false || child === null || child === undefined;\n}\n\nfunction buildChildElement(child: any): VirtualElement {\n if (isEmptyPlaceholder(child)) {\n return buildEmptyElement();\n } else if (isRealElement(child)) {\n return child;\n } else {\n return buildTextElement(child);\n }\n}\n\nfunction buildTextElement(value: any): VirtualElementText {\n return {\n type: VirtualElementTypesEnum.Text,\n value: String(value),\n };\n}\n\nfunction buildEmptyElement(): VirtualElementEmpty {\n return { type: VirtualElementTypesEnum.Empty };\n}\n\n// eslint-disable-next-line @typescript-eslint/naming-convention\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 // eslint-disable-next-line @typescript-eslint/naming-convention\n let DEBUG_startAt: number | undefined;\n if (DEBUG) {\n const componentName = componentInstance.name;\n if (!DEBUG_components[componentName]) {\n DEBUG_components[componentName] = {\n componentName,\n renderCount: 0,\n renderTimes: [],\n };\n }\n\n if (DEBUG_MORE) {\n if (componentName !== 'TeactMemoWrapper' && componentName !== 'TeactNContainer') {\n // eslint-disable-next-line no-console\n console.log(`[Teact] Render ${componentName}`);\n }\n }\n\n DEBUG_startAt = performance.now();\n }\n\n newRenderedValue = Component(props);\n\n if (DEBUG) {\n const renderTime = performance.now() - DEBUG_startAt!;\n const componentName = componentInstance.name;\n if (renderTime > 7) {\n // eslint-disable-next-line no-console\n console.warn(`[Teact] Slow component render: ${componentName}, ${Math.round(renderTime)} ms`);\n }\n DEBUG_components[componentName].renderTimes.push(renderTime);\n DEBUG_components[componentName].renderCount++;\n }\n } catch (err) {\n handleError(err);\n\n newRenderedValue = componentInstance.renderedValue;\n }\n\n if (componentInstance.isMounted && newRenderedValue === componentInstance.renderedValue) {\n return componentInstance.$element;\n }\n\n componentInstance.renderedValue = newRenderedValue;\n\n const newChild = buildChildElement(newRenderedValue);\n componentInstance.$element = buildComponentElement(componentInstance, [newChild]);\n\n return componentInstance.$element;\n}\n\nexport function hasElementChanged($old: VirtualElement, $new: VirtualElement) {\n if (typeof $old !== typeof $new) {\n return true;\n } else if ($old.type !== $new.type) {\n return true;\n } else if (isTextElement($old) && isTextElement($new)) {\n return $old.value !== $new.value;\n } else if (isTagElement($old) && isTagElement($new)) {\n return ($old.tag !== $new.tag) || ($old.props.key !== $new.props.key);\n } else if (isComponentElement($old) && isComponentElement($new)) {\n return (\n $old.componentInstance.Component !== $new.componentInstance.Component\n ) || (\n $old.props.key !== $new.props.key\n );\n }\n\n return false;\n}\n\nexport function unmountTree($element: VirtualElement) {\n if (!isRealElement($element)) {\n return;\n }\n\n if (isComponentElement($element)) {\n unmountComponent($element.componentInstance);\n } else if ($element.target) {\n removeAllDelegatedListeners($element.target as HTMLElement);\n // Trying to help GC\n // eslint-disable-next-line no-null/no-null\n $element.target = null as any;\n }\n\n $element.children.forEach(unmountTree);\n}\n\nexport function mountComponent(componentInstance: ComponentInstance) {\n renderComponent(componentInstance);\n componentInstance.isMounted = true;\n return componentInstance.$element;\n}\n\nfunction unmountComponent(componentInstance: ComponentInstance) {\n if (!componentInstance.isMounted) {\n return;\n }\n\n componentInstance.hooks.memos.byCursor.forEach((hook) => {\n // eslint-disable-next-line no-null/no-null\n hook.current = null;\n });\n\n componentInstance.hooks.effects.byCursor.forEach(({ cleanup }) => {\n if (typeof cleanup === 'function') {\n try {\n cleanup();\n } catch (err) {\n handleError(err);\n }\n }\n });\n\n componentInstance.isMounted = false;\n\n helpGc(componentInstance);\n}\n\n// We need to remove all references to DOM objects. We also clean all other references, just in case.\nfunction helpGc(componentInstance: ComponentInstance) {\n /* eslint-disable no-null/no-null */\n\n componentInstance.hooks.effects.byCursor.forEach((hook) => {\n hook.cleanup = null as any;\n hook.effect = null as any;\n hook.dependencies = null as any;\n });\n\n componentInstance.hooks.state.byCursor.forEach((hook) => {\n hook.value = null as any;\n hook.nextValue = null as any;\n hook.setter = null as any;\n });\n\n componentInstance.hooks.memos.byCursor.forEach((hook) => {\n hook.dependencies = null as any;\n });\n\n componentInstance.hooks = null as any;\n componentInstance.$element = null as any;\n componentInstance.renderedValue = null as any;\n componentInstance.Component = null as any;\n componentInstance.props = null as any;\n componentInstance.forceUpdate = null as any;\n componentInstance.onUpdate = null as any;\n\n /* eslint-enable no-null/no-null */\n}\n\nfunction prepareComponentForFrame(componentInstance: ComponentInstance) {\n if (!componentInstance.isMounted) {\n return;\n }\n\n componentInstance.hooks.state.byCursor.forEach((hook) => {\n hook.value = hook.nextValue;\n });\n\n componentInstance.prepareForFrame = throttleWithPrimaryRaf(() => prepareComponentForFrame(componentInstance));\n componentInstance.forceUpdate = throttleWithRaf(() => forceUpdateComponent(componentInstance));\n}\n\nfunction forceUpdateComponent(componentInstance: ComponentInstance) {\n if (!componentInstance.isMounted || !componentInstance.onUpdate) {\n return;\n }\n\n const currentElement = componentInstance.$element;\n\n renderComponent(componentInstance);\n\n if (componentInstance.$element !== currentElement) {\n componentInstance.onUpdate();\n }\n}\n\nexport function getTarget($element: VirtualElement): Node | undefined {\n if (isComponentElement($element)) {\n return getTarget($element.children[0]);\n } else {\n return $element.target;\n }\n}\n\nexport function setTarget($element: VirtualElement, target: Node) {\n if (isComponentElement($element)) {\n setTarget($element.children[0], target);\n } else {\n $element.target = target;\n }\n}\n\nexport function useState<T>(initial?: T): [T, StateHookSetter<T>] {\n const { cursor, byCursor } = renderingInstance.hooks.state;\n\n if (byCursor[cursor] === undefined) {\n byCursor[cursor] = {\n value: initial,\n nextValue: initial,\n setter: ((componentInstance) => (newValue: ((current: T) => T) | T) => {\n if (byCursor[cursor].nextValue !== newValue) {\n byCursor[cursor].nextValue = typeof newValue === 'function'\n ? (newValue as (current: T) => T)(byCursor[cursor].value)\n : newValue;\n\n if (!componentInstance.prepareForFrame || !componentInstance.forceUpdate) {\n componentInstance.prepareForFrame = throttleWithPrimaryRaf(\n () => prepareComponentForFrame(componentInstance),\n );\n componentInstance.forceUpdate = throttleWithRaf(\n () => forceUpdateComponent(componentInstance),\n );\n }\n\n componentInstance.prepareForFrame();\n componentInstance.forceUpdate();\n\n if (DEBUG_MORE) {\n if (componentInstance.name !== 'TeactNContainer') {\n // eslint-disable-next-line no-console\n console.log(\n '[Teact.useState]',\n componentInstance.name,\n // `componentInstance.Component` may be set to `null` by GC helper\n componentInstance.Component && (componentInstance.Component as FC_withDebug).DEBUG_contentComponentName\n ? `> ${(componentInstance.Component as FC_withDebug).DEBUG_contentComponentName}`\n : '',\n `Forced update at cursor #${cursor}, next value: `,\n byCursor[cursor].nextValue,\n );\n }\n }\n }\n })(renderingInstance),\n };\n }\n\n renderingInstance.hooks.state.cursor++;\n\n return [\n byCursor[cursor].value,\n byCursor[cursor].setter,\n ];\n}\n\nfunction useLayoutEffectBase(\n schedulerFn: typeof onTickEnd | typeof requestAnimationFrame,\n effect: () => Function | void,\n dependencies?: any[],\n debugKey?: string,\n) {\n const { cursor, byCursor } = renderingInstance.hooks.effects;\n const componentInstance = renderingInstance;\n\n const exec = () => {\n if (!componentInstance.isMounted) {\n return;\n }\n\n const { cleanup } = byCursor[cursor];\n if (typeof cleanup === 'function') {\n try {\n cleanup();\n } catch (err) {\n handleError(err);\n }\n }\n\n byCursor[cursor].cleanup = effect() as Function;\n };\n\n if (byCursor[cursor] !== undefined && dependencies && byCursor[cursor].dependencies) {\n if (dependencies.some((dependency, i) => dependency !== byCursor[cursor].dependencies![i])) {\n if (debugKey) {\n const causedBy = dependencies.reduce((res, newValue, i) => {\n const prevValue = byCursor[cursor].dependencies![i];\n if (newValue !== prevValue) {\n res.push(`${i}: ${prevValue} => ${newValue}`);\n }\n\n return res;\n }, []);\n\n // eslint-disable-next-line no-console\n console.log(\n '[Teact]',\n debugKey,\n 'Effect caused by dependencies.',\n causedBy.join(', '),\n );\n }\n\n schedulerFn(exec);\n }\n } else {\n schedulerFn(exec);\n }\n\n byCursor[cursor] = {\n effect,\n dependencies,\n cleanup: byCursor[cursor] ? byCursor[cursor].cleanup : undefined,\n };\n\n renderingInstance.hooks.effects.cursor++;\n}\n\nexport function useEffect(effect: () => Function | void, dependencies?: any[], debugKey?: string) {\n return useLayoutEffectBase(fastRaf, effect, dependencies, debugKey);\n}\n\nexport function useLayoutEffect(effect: () => Function | void, dependencies?: any[], debugKey?: string) {\n return useLayoutEffectBase(onTickEnd, effect, dependencies, debugKey);\n}\n\nexport function useMemo<T extends any>(resolver: () => T, dependencies: any[], debugKey?: string): T {\n const { cursor, byCursor } = renderingInstance.hooks.memos;\n let { current } = byCursor[cursor] || {};\n\n if (\n byCursor[cursor] === undefined\n || dependencies.some((dependency, i) => dependency !== byCursor[cursor].dependencies[i])\n ) {\n if (DEBUG && debugKey) {\n // eslint-disable-next-line no-console\n console.log(\n `[Teact.useMemo] ${renderingInstance.name} (${debugKey}): Update is caused by:`,\n byCursor[cursor]\n ? getUnequalProps(dependencies, byCursor[cursor].dependencies).join(', ')\n : '[first render]',\n );\n }\n\n current = resolver();\n }\n\n byCursor[cursor] = {\n current,\n dependencies,\n };\n\n renderingInstance.hooks.memos.cursor++;\n\n return current;\n}\n\nexport function useCallback<F extends AnyFunction>(newCallback: F, dependencies: any[]): F {\n // eslint-disable-next-line react-hooks/exhaustive-deps\n return useMemo(() => newCallback, dependencies);\n}\n\nexport function useRef<T>(initial: T): { current: T };\nexport function useRef<T>(): { current: T | undefined }; // TT way (empty is `undefined`)\nexport function useRef<T>(initial: null): { current: T | null }; // React way (empty is `null`)\n// eslint-disable-next-line no-null/no-null\nexport function useRef<T>(initial?: T | null) {\n return useMemo(() => ({\n current: initial,\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }), []);\n}\n\nexport function memo<T extends FC>(Component: T, areEqual = arePropsShallowEqual, debugKey?: string) {\n return function TeactMemoWrapper(props: Props) {\n // eslint-disable-next-line react-hooks/rules-of-hooks\n const propsRef = useRef(props);\n const renderedRef = useRef();\n\n if (!renderedRef.current || (propsRef.current && !areEqual(propsRef.current, props))) {\n if (DEBUG && debugKey) {\n // eslint-disable-next-line no-console\n console.log(\n `[Teact.memo] ${Component.name} (${debugKey}): Update is caused by:`,\n getUnequalProps(propsRef.current!, props).join(', '),\n );\n }\n\n propsRef.current = props;\n renderedRef.current = createElement(Component, props) as VirtualElementComponent;\n }\n\n return renderedRef.current;\n } as T;\n}\n\n// We need to keep it here for JSX.\nexport default {\n createElement,\n Fragment,\n};\n","import React, {\n FC, FC_withDebug, Props, useEffect, useState,\n} from './teact';\n\nimport { DEBUG, DEBUG_MORE } from '../../config';\nimport useForceUpdate from '../../hooks/useForceUpdate';\nimport generateIdFor from '../../util/generateIdFor';\nimport { throttleWithRaf } from '../../util/schedulers';\nimport arePropsShallowEqual, { getUnequalProps } from '../../util/arePropsShallowEqual';\nimport { orderBy } from '../../util/iteratees';\nimport { GlobalState, GlobalActions, ActionTypes } from '../../global/types';\nimport { handleError } from '../../util/handleError';\n\nexport default React;\n\ntype ActionPayload = AnyLiteral;\n\ntype Reducer = (\n global: GlobalState,\n actions: GlobalActions,\n payload: any,\n) => GlobalState | void;\n\ntype MapStateToProps<OwnProps = undefined> = ((global: GlobalState, ownProps: OwnProps) => AnyLiteral | null);\ntype MapActionsToProps = ((setGlobal: Function, actions: GlobalActions) => Partial<GlobalActions> | null);\n\nlet currentGlobal = {} as GlobalState;\n\nconst reducers: Record<string, Reducer[]> = {};\nconst callbacks: Function[] = [updateContainers];\nconst actions = {} as GlobalActions;\nconst containers = new Map<string, {\n mapStateToProps: MapStateToProps<any>;\n mapReducersToProps: MapActionsToProps;\n ownProps: Props;\n mappedProps?: Props;\n forceUpdate: Function;\n areMappedPropsChanged: boolean;\n DEBUG_updates: number;\n DEBUG_componentName: string;\n}>();\n\nfunction runCallbacks() {\n callbacks.forEach((cb) => cb(currentGlobal));\n}\n\nconst runCallbacksThrottled = throttleWithRaf(runCallbacks);\n\n// `noThrottle = true` is used as a workaround for iOS gesture history navigation\nexport function setGlobal(newGlobal?: GlobalState, noThrottle = false) {\n if (typeof newGlobal === 'object' && newGlobal !== currentGlobal) {\n currentGlobal = newGlobal;\n if (!noThrottle) {\n runCallbacksThrottled();\n } else {\n runCallbacks();\n }\n }\n}\n\nexport function getGlobal() {\n return currentGlobal;\n}\n\nexport function getDispatch() {\n return actions;\n}\n\nfunction onDispatch(name: string, payload?: ActionPayload, noThrottle?: boolean) {\n if (reducers[name]) {\n reducers[name].forEach((reducer) => {\n const newGlobal = reducer(currentGlobal, actions, payload);\n if (newGlobal) {\n setGlobal(newGlobal, noThrottle);\n }\n });\n }\n}\n\nfunction updateContainers() {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n let DEBUG_startAt: number | undefined;\n if (DEBUG) {\n DEBUG_startAt = performance.now();\n }\n\n // eslint-disable-next-line no-restricted-syntax\n for (const container of containers.values()) {\n const {\n mapStateToProps, mapReducersToProps, ownProps, mappedProps, forceUpdate,\n } = container;\n\n let newMappedProps;\n\n try {\n newMappedProps = {\n ...mapStateToProps(currentGlobal, ownProps),\n ...mapReducersToProps(setGlobal, actions),\n };\n } catch (err) {\n handleError(err);\n\n return;\n }\n\n if (DEBUG) {\n if (Object.values(newMappedProps).some(Number.isNaN)) {\n // eslint-disable-next-line no-console\n console.warn(\n // eslint-disable-next-line max-len\n `[TeactN] Some of \\`${container.DEBUG_componentName}\\` mappers contain NaN values. This may cause redundant updates because of incorrect equality check.`,\n );\n }\n }\n\n if (Object.keys(newMappedProps).length && !arePropsShallowEqual(mappedProps!, newMappedProps)) {\n if (DEBUG_MORE) {\n // eslint-disable-next-line no-console\n console.log(\n '[TeactN] Will update',\n container.DEBUG_componentName,\n 'caused by',\n getUnequalProps(mappedProps!, newMappedProps).join(', '),\n );\n }\n\n container.mappedProps = newMappedProps;\n container.areMappedPropsChanged = true;\n container.DEBUG_updates++;\n\n forceUpdate();\n }\n }\n\n if (DEBUG) {\n const updateTime = performance.now() - DEBUG_startAt!;\n if (updateTime > 7) {\n // eslint-disable-next-line no-console\n console.warn(`[TeactN] Slow containers update: ${Math.round(updateTime)} ms`);\n }\n }\n}\n\nexport function addReducer(name: ActionTypes, reducer: Reducer) {\n if (!reducers[name]) {\n reducers[name] = [];\n\n actions[name] = (payload?: ActionPayload, noThrottle = false) => {\n onDispatch(name, payload, noThrottle);\n };\n }\n\n reducers[name].push(reducer);\n}\n\nexport function addCallback(cb: Function) {\n callbacks.push(cb);\n}\n\nexport function removeCallback(cb: Function) {\n const index = callbacks.indexOf(cb);\n if (index !== -1) {\n callbacks.splice(index, 1);\n }\n}\n\nexport function withGlobal<OwnProps>(\n mapStateToProps: MapStateToProps<OwnProps> = () => ({}),\n mapReducersToProps: MapActionsToProps = () => ({}),\n) {\n return (Component: FC) => {\n return function TeactNContainer(props: OwnProps) {\n (TeactNContainer as FC_withDebug).DEBUG_contentComponentName = Component.name;\n\n const [id] = useState(generateIdFor(containers));\n const forceUpdate = useForceUpdate();\n\n useEffect(() => {\n return () => {\n containers.delete(id);\n };\n }, [id]);\n\n let container = containers.get(id);\n if (!container) {\n container = {\n mapStateToProps,\n mapReducersToProps,\n ownProps: props,\n areMappedPropsChanged: false,\n forceUpdate,\n DEBUG_updates: 0,\n DEBUG_componentName: Component.name,\n };\n\n containers.set(id, container);\n }\n\n if (container.areMappedPropsChanged) {\n container.areMappedPropsChanged = false;\n }\n\n if (!container.mappedProps || !arePropsShallowEqual(container.ownProps, props)) {\n container.ownProps = props;\n\n try {\n container.mappedProps = {\n ...mapStateToProps(currentGlobal, props),\n ...mapReducersToProps(setGlobal, actions),\n };\n } catch (err) {\n handleError(err);\n }\n }\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return <Component {...container.mappedProps} {...props} />;\n };\n };\n}\n\nif (DEBUG) {\n (window as any).getGlobal = getGlobal;\n\n document.addEventListener('dblclick', () => {\n // eslint-disable-next-line no-console\n console.log(\n 'GLOBAL CONTAINERS',\n orderBy(\n Array.from(containers.values())\n .map(({ DEBUG_componentName, DEBUG_updates }) => ({ DEBUG_componentName, DEBUG_updates })),\n 'DEBUG_updates',\n 'desc',\n ),\n );\n });\n}\n","// Copyright Twitter Inc. Licensed under MIT\n// https://github.com/twitter/twemoji-parser/blob/master/LICENSE.md\n// Version 2c193ce 28.05.2021\n\nconst vs16RegExp = /\\uFE0F/g;\n// avoid using a string literal like '\\u200D' here because minifiers expand it inline\nconst zeroWidthJoiner = String.fromCharCode(0x200d);\n\nexport function removeVS16s(rawEmoji) {\n return rawEmoji.indexOf(zeroWidthJoiner) < 0 ? rawEmoji.replace(vs16RegExp, '') : rawEmoji;\n}\n\n// This file is generated by source/emoji/scripts/generate.sh\n// eslint-disable-next-line max-len\nexport default /(?:\\ud83d\\udc68\\ud83c\\udffb\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc8b\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc68\\ud83c\\udffc\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc8b\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc68\\ud83c\\udffd\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc8b\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc68\\ud83c\\udffe\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc8b\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc68\\ud83c\\udfff\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc8b\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc69\\ud83c\\udffb\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc8b\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc69\\ud83c\\udffb\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc8b\\u200d\\ud83d\\udc69\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc69\\ud83c\\udffc\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc8b\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc69\\ud83c\\udffc\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc8b\\u200d\\ud83d\\udc69\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc69\\ud83c\\udffd\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc8b\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc69\\ud83c\\udffd\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc8b\\u200d\\ud83d\\udc69\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc69\\ud83c\\udffe\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc8b\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc69\\ud83c\\udffe\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc8b\\u200d\\ud83d\\udc69\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc69\\ud83c\\udfff\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc8b\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc69\\ud83c\\udfff\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc8b\\u200d\\ud83d\\udc69\\ud83c[\\udffb-\\udfff]|\\ud83e\\uddd1\\ud83c\\udffb\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc8b\\u200d\\ud83e\\uddd1\\ud83c[\\udffc-\\udfff]|\\ud83e\\uddd1\\ud83c\\udffc\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc8b\\u200d\\ud83e\\uddd1\\ud83c[\\udffb\\udffd-\\udfff]|\\ud83e\\uddd1\\ud83c\\udffd\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc8b\\u200d\\ud83e\\uddd1\\ud83c[\\udffb\\udffc\\udffe\\udfff]|\\ud83e\\uddd1\\ud83c\\udffe\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc8b\\u200d\\ud83e\\uddd1\\ud83c[\\udffb-\\udffd\\udfff]|\\ud83e\\uddd1\\ud83c\\udfff\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc8b\\u200d\\ud83e\\uddd1\\ud83c[\\udffb-\\udffe]|\\ud83d\\udc68\\ud83c\\udffb\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc68\\ud83c\\udffb\\u200d\\ud83e\\udd1d\\u200d\\ud83d\\udc68\\ud83c[\\udffc-\\udfff]|\\ud83d\\udc68\\ud83c\\udffc\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc68\\ud83c\\udffc\\u200d\\ud83e\\udd1d\\u200d\\ud83d\\udc68\\ud83c[\\udffb\\udffd-\\udfff]|\\ud83d\\udc68\\ud83c\\udffd\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc68\\ud83c\\udffd\\u200d\\ud83e\\udd1d\\u200d\\ud83d\\udc68\\ud83c[\\udffb\\udffc\\udffe\\udfff]|\\ud83d\\udc68\\ud83c\\udffe\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc68\\ud83c\\udffe\\u200d\\ud83e\\udd1d\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udffd\\udfff]|\\ud83d\\udc68\\ud83c\\udfff\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc68\\ud83c\\udfff\\u200d\\ud83e\\udd1d\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udffe]|\\ud83d\\udc69\\ud83c\\udffb\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc69\\ud83c\\udffb\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc69\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc69\\ud83c\\udffb\\u200d\\ud83e\\udd1d\\u200d\\ud83d\\udc68\\ud83c[\\udffc-\\udfff]|\\ud83d\\udc69\\ud83c\\udffb\\u200d\\ud83e\\udd1d\\u200d\\ud83d\\udc69\\ud83c[\\udffc-\\udfff]|\\ud83d\\udc69\\ud83c\\udffc\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc69\\ud83c\\udffc\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc69\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc69\\ud83c\\udffc\\u200d\\ud83e\\udd1d\\u200d\\ud83d\\udc68\\ud83c[\\udffb\\udffd-\\udfff]|\\ud83d\\udc69\\ud83c\\udffc\\u200d\\ud83e\\udd1d\\u200d\\ud83d\\udc69\\ud83c[\\udffb\\udffd-\\udfff]|\\ud83d\\udc69\\ud83c\\udffd\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc69\\ud83c\\udffd\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc69\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc69\\ud83c\\udffd\\u200d\\ud83e\\udd1d\\u200d\\ud83d\\udc68\\ud83c[\\udffb\\udffc\\udffe\\udfff]|\\ud83d\\udc69\\ud83c\\udffd\\u200d\\ud83e\\udd1d\\u200d\\ud83d\\udc69\\ud83c[\\udffb\\udffc\\udffe\\udfff]|\\ud83d\\udc69\\ud83c\\udffe\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc69\\ud83c\\udffe\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc69\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc69\\ud83c\\udffe\\u200d\\ud83e\\udd1d\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udffd\\udfff]|\\ud83d\\udc69\\ud83c\\udffe\\u200d\\ud83e\\udd1d\\u200d\\ud83d\\udc69\\ud83c[\\udffb-\\udffd\\udfff]|\\ud83d\\udc69\\ud83c\\udfff\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc69\\ud83c\\udfff\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc69\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc69\\ud83c\\udfff\\u200d\\ud83e\\udd1d\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udffe]|\\ud83d\\udc69\\ud83c\\udfff\\u200d\\ud83e\\udd1d\\u200d\\ud83d\\udc69\\ud83c[\\udffb-\\udffe]|\\ud83e\\uddd1\\ud83c\\udffb\\u200d\\u2764\\ufe0f\\u200d\\ud83e\\uddd1\\ud83c[\\udffc-\\udfff]|\\ud83e\\uddd1\\ud83c\\udffb\\u200d\\ud83e\\udd1d\\u200d\\ud83e\\uddd1\\ud83c[\\udffb-\\udfff]|\\ud83e\\uddd1\\ud83c\\udffc\\u200d\\u2764\\ufe0f\\u200d\\ud83e\\uddd1\\ud83c[\\udffb\\udffd-\\udfff]|\\ud83e\\uddd1\\ud83c\\udffc\\u200d\\ud83e\\udd1d\\u200d\\ud83e\\uddd1\\ud83c[\\udffb-\\udfff]|\\ud83e\\uddd1\\ud83c\\udffd\\u200d\\u2764\\ufe0f\\u200d\\ud83e\\uddd1\\ud83c[\\udffb\\udffc\\udffe\\udfff]|\\ud83e\\uddd1\\ud83c\\udffd\\u200d\\ud83e\\udd1d\\u200d\\ud83e\\uddd1\\ud83c[\\udffb-\\udfff]|\\ud83e\\uddd1\\ud83c\\udffe\\u200d\\u2764\\ufe0f\\u200d\\ud83e\\uddd1\\ud83c[\\udffb-\\udffd\\udfff]|\\ud83e\\uddd1\\ud83c\\udffe\\u200d\\ud83e\\udd1d\\u200d\\ud83e\\uddd1\\ud83c[\\udffb-\\udfff]|\\ud83e\\uddd1\\ud83c\\udfff\\u200d\\u2764\\ufe0f\\u200d\\ud83e\\uddd1\\ud83c[\\udffb-\\udffe]|\\ud83e\\uddd1\\ud83c\\udfff\\u200d\\ud83e\\udd1d\\u200d\\ud83e\\uddd1\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc68\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc8b\\u200d\\ud83d\\udc68|\\ud83d\\udc69\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc8b\\u200d\\ud83d[\\udc68\\udc69]|\\ud83d\\udc68\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc68|\\ud83d\\udc69\\u200d\\u2764\\ufe0f\\u200d\\ud83d[\\udc68\\udc69]|\\ud83e\\uddd1\\u200d\\ud83e\\udd1d\\u200d\\ud83e\\uddd1|\\ud83d\\udc6b\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc6c\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc6d\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc8f\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc91\\ud83c[\\udffb-\\udfff]|\\ud83d[\\udc6b-\\udc6d\\udc8f\\udc91])|(?:\\ud83d[\\udc68\\udc69]|\\ud83e\\uddd1)(?:\\ud83c[\\udffb-\\udfff])?\\u200d(?:\\u2695\\ufe0f|\\u2696\\ufe0f|\\u2708\\ufe0f|\\ud83c[\\udf3e\\udf73\\udf7c\\udf84\\udf93\\udfa4\\udfa8\\udfeb\\udfed]|\\ud83d[\\udcbb\\udcbc\\udd27\\udd2c\\ude80\\ude92]|\\ud83e[\\uddaf-\\uddb3\\uddbc\\uddbd])|(?:\\ud83c[\\udfcb\\udfcc]|\\ud83d[\\udd74\\udd75]|\\u26f9)((?:\\ud83c[\\udffb-\\udfff]|\\ufe0f)\\u200d[\\u2640\\u2642]\\ufe0f)|(?:\\ud83c[\\udfc3\\udfc4\\udfca]|\\ud83d[\\udc6e\\udc70\\udc71\\udc73\\udc77\\udc81\\udc82\\udc86\\udc87\\ude45-\\ude47\\ude4b\\ude4d\\ude4e\\udea3\\udeb4-\\udeb6]|\\ud83e[\\udd26\\udd35\\udd37-\\udd39\\udd3d\\udd3e\\uddb8\\uddb9\\uddcd-\\uddcf\\uddd4\\uddd6-\\udddd])(?:\\ud83c[\\udffb-\\udfff])?\\u200d[\\u2640\\u2642]\\ufe0f|(?:\\ud83d\\udc68\\u200d\\ud83d\\udc68\\u200d\\ud83d\\udc66\\u200d\\ud83d\\udc66|\\ud83d\\udc68\\u200d\\ud83d\\udc68\\u200d\\ud83d\\udc67\\u200d\\ud83d[\\udc66\\udc67]|\\ud83d\\udc68\\u200d\\ud83d\\udc69\\u200d\\ud83d\\udc66\\u200d\\ud83d\\udc66|\\ud83d\\udc68\\u200d\\ud83d\\udc69\\u200d\\ud83d\\udc67\\u200d\\ud83d[\\udc66\\udc67]|\\ud83d\\udc69\\u200d\\ud83d\\udc69\\u200d\\ud83d\\udc66\\u200d\\ud83d\\udc66|\\ud83d\\udc69\\u200d\\ud83d\\udc69\\u200d\\ud83d\\udc67\\u200d\\ud83d[\\udc66\\udc67]|\\ud83d\\udc68\\u200d\\ud83d\\udc66\\u200d\\ud83d\\udc66|\\ud83d\\udc68\\u200d\\ud83d\\udc67\\u200d\\ud83d[\\udc66\\udc67]|\\ud83d\\udc68\\u200d\\ud83d\\udc68\\u200d\\ud83d[\\udc66\\udc67]|\\ud83d\\udc68\\u200d\\ud83d\\udc69\\u200d\\ud83d[\\udc66\\udc67]|\\ud83d\\udc69\\u200d\\ud83d\\udc66\\u200d\\ud83d\\udc66|\\ud83d\\udc69\\u200d\\ud83d\\udc67\\u200d\\ud83d[\\udc66\\udc67]|\\ud83d\\udc69\\u200d\\ud83d\\udc69\\u200d\\ud83d[\\udc66\\udc67]|\\ud83c\\udff3\\ufe0f\\u200d\\u26a7\\ufe0f|\\ud83c\\udff3\\ufe0f\\u200d\\ud83c\\udf08|\\ud83d\\ude36\\u200d\\ud83c\\udf2b\\ufe0f|\\u2764\\ufe0f\\u200d\\ud83d\\udd25|\\u2764\\ufe0f\\u200d\\ud83e\\ude79|\\ud83c\\udff4\\u200d\\u2620\\ufe0f|\\ud83d\\udc15\\u200d\\ud83e\\uddba|\\ud83d\\udc3b\\u200d\\u2744\\ufe0f|\\ud83d\\udc41\\u200d\\ud83d\\udde8|\\ud83d\\udc68\\u200d\\ud83d[\\udc66\\udc67]|\\ud83d\\udc69\\u200d\\ud83d[\\udc66\\udc67]|\\ud83d\\udc6f\\u200d\\u2640\\ufe0f|\\ud83d\\udc6f\\u200d\\u2642\\ufe0f|\\ud83d\\ude2e\\u200d\\ud83d\\udca8|\\ud83d\\ude35\\u200d\\ud83d\\udcab|\\ud83e\\udd3c\\u200d\\u2640\\ufe0f|\\ud83e\\udd3c\\u200d\\u2642\\ufe0f|\\ud83e\\uddde\\u200d\\u2640\\ufe0f|\\ud83e\\uddde\\u200d\\u2642\\ufe0f|\\ud83e\\udddf\\u200d\\u2640\\ufe0f|\\ud83e\\udddf\\u200d\\u2642\\ufe0f|\\ud83d\\udc08\\u200d\\u2b1b)|[#*0-9]\\ufe0f?\\u20e3|(?:[©®\\u2122\\u265f]\\ufe0f)|(?:\\ud83c[\\udc04\\udd70\\udd71\\udd7e\\udd7f\\ude02\\ude1a\\ude2f\\ude37\\udf21\\udf24-\\udf2c\\udf36\\udf7d\\udf96\\udf97\\udf99-\\udf9b\\udf9e\\udf9f\\udfcd\\udfce\\udfd4-\\udfdf\\udff3\\udff5\\udff7]|\\ud83d[\\udc3f\\udc41\\udcfd\\udd49\\udd4a\\udd6f\\udd70\\udd73\\udd76-\\udd79\\udd87\\udd8a-\\udd8d\\udda5\\udda8\\uddb1\\uddb2\\uddbc\\uddc2-\\uddc4\\uddd1-\\uddd3\\udddc-\\uddde\\udde1\\udde3\\udde8\\uddef\\uddf3\\uddfa\\udecb\\udecd-\\udecf\\udee0-\\udee5\\udee9\\udef0\\udef3]|[\\u203c\\u2049\\u2139\\u2194-\\u2199\\u21a9\\u21aa\\u231a\\u231b\\u2328\\u23cf\\u23ed-\\u23ef\\u23f1\\u23f2\\u23f8-\\u23fa\\u24c2\\u25aa\\u25ab\\u25b6\\u25c0\\u25fb-\\u25fe\\u2600-\\u2604\\u260e\\u2611\\u2614\\u2615\\u2618\\u2620\\u2622\\u2623\\u2626\\u262a\\u262e\\u262f\\u2638-\\u263a\\u2640\\u2642\\u2648-\\u2653\\u2660\\u2663\\u2665\\u2666\\u2668\\u267b\\u267f\\u2692-\\u2697\\u2699\\u269b\\u269c\\u26a0\\u26a1\\u26a7\\u26aa\\u26ab\\u26b0\\u26b1\\u26bd\\u26be\\u26c4\\u26c5\\u26c8\\u26cf\\u26d1\\u26d3\\u26d4\\u26e9\\u26ea\\u26f0-\\u26f5\\u26f8\\u26fa\\u26fd\\u2702\\u2708\\u2709\\u270f\\u2712\\u2714\\u2716\\u271d\\u2721\\u2733\\u2734\\u2744\\u2747\\u2757\\u2763\\u2764\\u27a1\\u2934\\u2935\\u2b05-\\u2b07\\u2b1b\\u2b1c\\u2b50\\u2b55\\u3030\\u303d\\u3297\\u3299])(?:\\ufe0f|(?!\\ufe0e))|(?:(?:\\ud83c[\\udfcb\\udfcc]|\\ud83d[\\udd74\\udd75\\udd90]|[\\u261d\\u26f7\\u26f9\\u270c\\u270d])(?:\\ufe0f|(?!\\ufe0e))|(?:\\ud83c[\\udf85\\udfc2-\\udfc4\\udfc7\\udfca]|\\ud83d[\\udc42\\udc43\\udc46-\\udc50\\udc66-\\udc69\\udc6e\\udc70-\\udc78\\udc7c\\udc81-\\udc83\\udc85-\\udc87\\udcaa\\udd7a\\udd95\\udd96\\ude45-\\ude47\\ude4b-\\ude4f\\udea3\\udeb4-\\udeb6\\udec0\\udecc]|\\ud83e[\\udd0c\\udd0f\\udd18-\\udd1c\\udd1e\\udd1f\\udd26\\udd30-\\udd39\\udd3d\\udd3e\\udd77\\uddb5\\uddb6\\uddb8\\uddb9\\uddbb\\uddcd-\\uddcf\\uddd1-\\udddd]|[\\u270a\\u270b]))(?:\\ud83c[\\udffb-\\udfff])?|(?:\\ud83c\\udff4\\udb40\\udc67\\udb40\\udc62\\udb40\\udc65\\udb40\\udc6e\\udb40\\udc67\\udb40\\udc7f|\\ud83c\\udff4\\udb40\\udc67\\udb40\\udc62\\udb40\\udc73\\udb40\\udc63\\udb40\\udc74\\udb40\\udc7f|\\ud83c\\udff4\\udb40\\udc67\\udb40\\udc62\\udb40\\udc77\\udb40\\udc6c\\udb40\\udc73\\udb40\\udc7f|\\ud83c\\udde6\\ud83c[\\udde8-\\uddec\\uddee\\uddf1\\uddf2\\uddf4\\uddf6-\\uddfa\\uddfc\\uddfd\\uddff]|\\ud83c\\udde7\\ud83c[\\udde6\\udde7\\udde9-\\uddef\\uddf1-\\uddf4\\uddf6-\\uddf9\\uddfb\\uddfc\\uddfe\\uddff]|\\ud83c\\udde8\\ud83c[\\udde6\\udde8\\udde9\\uddeb-\\uddee\\uddf0-\\uddf5\\uddf7\\uddfa-\\uddff]|\\ud83c\\udde9\\ud83c[\\uddea\\uddec\\uddef\\uddf0\\uddf2\\uddf4\\uddff]|\\ud83c\\uddea\\ud83c[\\udde6\\udde8\\uddea\\uddec\\udded\\uddf7-\\uddfa]|\\ud83c\\uddeb\\ud83c[\\uddee-\\uddf0\\uddf2\\uddf4\\uddf7]|\\ud83c\\uddec\\ud83c[\\udde6\\udde7\\udde9-\\uddee\\uddf1-\\uddf3\\uddf5-\\uddfa\\uddfc\\uddfe]|\\ud83c\\udded\\ud83c[\\uddf0\\uddf2\\uddf3\\uddf7\\uddf9\\uddfa]|\\ud83c\\uddee\\ud83c[\\udde8-\\uddea\\uddf1-\\uddf4\\uddf6-\\uddf9]|\\ud83c\\uddef\\ud83c[\\uddea\\uddf2\\uddf4\\uddf5]|\\ud83c\\uddf0\\ud83c[\\uddea\\uddec-\\uddee\\uddf2\\uddf3\\uddf5\\uddf7\\uddfc\\uddfe\\uddff]|\\ud83c\\uddf1\\ud83c[\\udde6-\\udde8\\uddee\\uddf0\\uddf7-\\uddfb\\uddfe]|\\ud83c\\uddf2\\ud83c[\\udde6\\udde8-\\udded\\uddf0-\\uddff]|\\ud83c\\uddf3\\ud83c[\\udde6\\udde8\\uddea-\\uddec\\uddee\\uddf1\\uddf4\\uddf5\\uddf7\\uddfa\\uddff]|\\ud83c\\uddf4\\ud83c\\uddf2|\\ud83c\\uddf5\\ud83c[\\udde6\\uddea-\\udded\\uddf0-\\uddf3\\uddf7-\\uddf9\\uddfc\\uddfe]|\\ud83c\\uddf6\\ud83c\\udde6|\\ud83c\\uddf7\\ud83c[\\uddea\\uddf4\\uddf8\\uddfa\\uddfc]|\\ud83c\\uddf8\\ud83c[\\udde6-\\uddea\\uddec-\\uddf4\\uddf7-\\uddf9\\uddfb\\uddfd-\\uddff]|\\ud83c\\uddf9\\ud83c[\\udde6\\udde8\\udde9\\uddeb-\\udded\\uddef-\\uddf4\\uddf7\\uddf9\\uddfb\\uddfc\\uddff]|\\ud83c\\uddfa\\ud83c[\\udde6\\uddec\\uddf2\\uddf3\\uddf8\\uddfe\\uddff]|\\ud83c\\uddfb\\ud83c[\\udde6\\udde8\\uddea\\uddec\\uddee\\uddf3\\uddfa]|\\ud83c\\uddfc\\ud83c[\\uddeb\\uddf8]|\\ud83c\\uddfd\\ud83c\\uddf0|\\ud83c\\uddfe\\ud83c[\\uddea\\uddf9]|\\ud83c\\uddff\\ud83c[\\udde6\\uddf2\\uddfc]|\\ud83c[\\udccf\\udd8e\\udd91-\\udd9a\\udde6-\\uddff\\ude01\\ude32-\\ude36\\ude38-\\ude3a\\ude50\\ude51\\udf00-\\udf20\\udf2d-\\udf35\\udf37-\\udf7c\\udf7e-\\udf84\\udf86-\\udf93\\udfa0-\\udfc1\\udfc5\\udfc6\\udfc8\\udfc9\\udfcf-\\udfd3\\udfe0-\\udff0\\udff4\\udff8-\\udfff]|\\ud83d[\\udc00-\\udc3e\\udc40\\udc44\\udc45\\udc51-\\udc65\\udc6a\\udc6f\\udc79-\\udc7b\\udc7d-\\udc80\\udc84\\udc88-\\udc8e\\udc90\\udc92-\\udca9\\udcab-\\udcfc\\udcff-\\udd3d\\udd4b-\\udd4e\\udd50-\\udd67\\udda4\\uddfb-\\ude44\\ude48-\\ude4a\\ude80-\\udea2\\udea4-\\udeb3\\udeb7-\\udebf\\udec1-\\udec5\\uded0-\\uded2\\uded5-\\uded7\\udeeb\\udeec\\udef4-\\udefc\\udfe0-\\udfeb]|\\ud83e[\\udd0d\\udd0e\\udd10-\\udd17\\udd1d\\udd20-\\udd25\\udd27-\\udd2f\\udd3a\\udd3c\\udd3f-\\udd45\\udd47-\\udd76\\udd78\\udd7a-\\uddb4\\uddb7\\uddba\\uddbc-\\uddcb\\uddd0\\uddde-\\uddff\\ude70-\\ude74\\ude78-\\ude7a\\ude80-\\ude86\\ude90-\\udea8\\udeb0-\\udeb6\\udec0-\\udec2\\uded0-\\uded6]|[\\u23e9-\\u23ec\\u23f0\\u23f3\\u267e\\u26ce\\u2705\\u2728\\u274c\\u274e\\u2753-\\u2755\\u2795-\\u2797\\u27b0\\u27bf\\ue50a])|\\ufe0f/g;\n","import {\n addReducer, getDispatch, getGlobal, setGlobal,\n} from '../../../lib/teact/teactn';\n\nimport { initApi, callApi } from '../../../api/gramjs';\nimport { GlobalState } from '../../../global/types';\n\nimport {\n LANG_CACHE_NAME,\n CUSTOM_BG_CACHE_NAME,\n MEDIA_CACHE_NAME,\n MEDIA_CACHE_NAME_AVATARS,\n MEDIA_PROGRESSIVE_CACHE_NAME,\n IS_TEST,\n} from '../../../config';\nimport { PLATFORM_ENV } from '../../../util/environment';\nimport { unsubscribe } from '../../../util/notifications';\nimport * as cacheApi from '../../../util/cacheApi';\nimport { updateAppBadge } from '../../../util/appBadge';\nimport {\n storeSession,\n loadStoredSession,\n clearStoredSession,\n importLegacySession,\n clearLegacySessions,\n} from '../../../util/sessions';\nimport { forceWebsync } from '../../../util/websync';\n\naddReducer('initApi', (global: GlobalState, actions) => {\n (async () => {\n if (!IS_TEST) {\n await importLegacySession();\n void clearLegacySessions();\n }\n\n void initApi(actions.apiUpdate, {\n userAgent: navigator.userAgent,\n platform: PLATFORM_ENV,\n sessionData: loadStoredSession(),\n });\n })();\n});\n\naddReducer('setAuthPhoneNumber', (global, actions, payload) => {\n const { phoneNumber } = payload!;\n\n void callApi('provideAuthPhoneNumber', phoneNumber.replace(/[^\\d]/g, ''));\n\n return {\n ...global,\n authIsLoading: true,\n authError: undefined,\n };\n});\n\naddReducer('setAuthCode', (global, actions, payload) => {\n const { code } = payload!;\n\n void callApi('provideAuthCode', code);\n\n return {\n ...global,\n authIsLoading: true,\n authError: undefined,\n };\n});\n\naddReducer('setAuthPassword', (global, actions, payload) => {\n const { password } = payload!;\n\n void callApi('provideAuthPassword', password);\n\n return {\n ...global,\n authIsLoading: true,\n authError: undefined,\n };\n});\n\naddReducer('uploadProfilePhoto', (global, actions, payload) => {\n const { file } = payload!;\n\n void callApi('uploadProfilePhoto', file);\n});\n\naddReducer('signUp', (global, actions, payload) => {\n const { firstName, lastName } = payload!;\n\n void callApi('provideAuthRegistration', { firstName, lastName });\n\n return {\n ...global,\n authIsLoading: true,\n authError: undefined,\n };\n});\n\naddReducer('returnToAuthPhoneNumber', (global) => {\n void callApi('restartAuth');\n\n return {\n ...global,\n authError: undefined,\n };\n});\n\naddReducer('goToAuthQrCode', (global) => {\n void callApi('restartAuthWithQr');\n\n return {\n ...global,\n authIsLoadingQrCode: true,\n authError: undefined,\n };\n});\n\naddReducer('saveSession', (global, actions, payload) => {\n const { sessionData } = payload;\n\n if (sessionData) {\n storeSession(payload.sessionData, global.currentUserId);\n } else {\n clearStoredSession();\n }\n});\n\naddReducer('signOut', () => {\n (async () => {\n try {\n await unsubscribe();\n await callApi('destroy');\n await forceWebsync(false);\n } catch (err) {\n // Do nothing\n }\n\n getDispatch().reset();\n })();\n});\n\naddReducer('reset', () => {\n clearStoredSession();\n\n void cacheApi.clear(MEDIA_CACHE_NAME);\n void cacheApi.clear(MEDIA_CACHE_NAME_AVATARS);\n void cacheApi.clear(MEDIA_PROGRESSIVE_CACHE_NAME);\n void cacheApi.clear(CUSTOM_BG_CACHE_NAME);\n\n const langCachePrefix = LANG_CACHE_NAME.replace(/\\d+$/, '');\n const langCacheVersion = (LANG_CACHE_NAME.match(/\\d+$/) || [0])[0];\n for (let i = 0; i < langCacheVersion; i++) {\n void cacheApi.clear(`${langCachePrefix}${i === 0 ? '' : i}`);\n }\n\n void clearLegacySessions();\n\n updateAppBadge(0);\n\n getDispatch().init();\n});\n\naddReducer('disconnect', () => {\n (async () => {\n await callApi('disconnect');\n })();\n});\n\naddReducer('loadNearestCountry', (global) => {\n if (global.connectionState !== 'connectionStateReady') {\n return;\n }\n\n (async () => {\n const authNearestCountry = await callApi('fetchNearestCountry');\n\n setGlobal({\n ...getGlobal(),\n authNearestCountry,\n });\n })();\n});\n\naddReducer('setDeviceToken', (global, actions, deviceToken) => {\n setGlobal({\n ...global,\n push: {\n deviceToken,\n subscribedAt: Date.now(),\n },\n });\n});\n\naddReducer('deleteDeviceToken', (global) => {\n const newGlobal = { ...global };\n delete newGlobal.push;\n setGlobal(newGlobal);\n});\n","import { addReducer, getGlobal, setGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalState } from '../../../global/types';\nimport {\n ApiPrivacyKey, PrivacyVisibility, ProfileEditProgress, IInputPrivacyRules, IInputPrivacyContact,\n UPLOADING_WALLPAPER_SLUG,\n} from '../../../types';\n\nimport { callApi } from '../../../api/gramjs';\nimport { buildCollectionByKey } from '../../../util/iteratees';\nimport { subscribe, unsubscribe } from '../../../util/notifications';\nimport { selectUser } from '../../selectors';\nimport {\n addUsers, addBlockedContact, updateChats, updateUser, removeBlockedContact, replaceSettings, updateNotifySettings,\n addNotifyExceptions,\n} from '../../reducers';\nimport { isChatPrivate } from '../../helpers';\n\naddReducer('updateProfile', (global, actions, payload) => {\n const {\n photo, firstName, lastName, bio: about, username,\n } = payload!;\n\n (async () => {\n const { currentUserId } = global;\n if (!currentUserId) {\n return;\n }\n\n setGlobal({\n ...getGlobal(),\n profileEdit: {\n progress: ProfileEditProgress.InProgress,\n },\n });\n\n if (photo) {\n await callApi('updateProfilePhoto', photo);\n }\n\n if (firstName || lastName || about) {\n const result = await callApi('updateProfile', { firstName, lastName, about });\n if (result) {\n global = getGlobal();\n const currentUser = currentUserId && selectUser(global, currentUserId);\n\n if (currentUser) {\n setGlobal(updateUser(\n global,\n currentUser.id,\n {\n firstName,\n lastName,\n fullInfo: {\n ...currentUser.fullInfo,\n bio: about,\n },\n },\n ));\n }\n }\n }\n\n if (username) {\n const result = await callApi('updateUsername', username);\n if (result && currentUserId) {\n setGlobal(updateUser(getGlobal(), currentUserId, { username }));\n }\n }\n\n setGlobal({\n ...getGlobal(),\n profileEdit: {\n progress: ProfileEditProgress.Complete,\n },\n });\n })();\n});\n\naddReducer('checkUsername', (global, actions, payload) => {\n const { username } = payload!;\n\n (async () => {\n // No need to check the username if profile update is already in progress\n if (global.profileEdit && global.profileEdit.progress === ProfileEditProgress.InProgress) {\n return;\n }\n\n setGlobal({\n ...global,\n profileEdit: {\n progress: global.profileEdit ? global.profileEdit.progress : ProfileEditProgress.Idle,\n isUsernameAvailable: undefined,\n },\n });\n\n const isUsernameAvailable = await callApi('checkUsername', username);\n\n global = getGlobal();\n setGlobal({\n ...global,\n profileEdit: {\n ...global.profileEdit!,\n isUsernameAvailable,\n },\n });\n })();\n});\n\naddReducer('loadWallpapers', () => {\n (async () => {\n const result = await callApi('fetchWallpapers', 0);\n if (!result) {\n return;\n }\n\n const global = getGlobal();\n setGlobal({\n ...global,\n settings: {\n ...global.settings,\n loadedWallpapers: result.wallpapers,\n },\n });\n })();\n});\n\naddReducer('uploadWallpaper', (global, actions, payload) => {\n const file = payload;\n const previewBlobUrl = URL.createObjectURL(file);\n\n setGlobal({\n ...global,\n settings: {\n ...global.settings,\n loadedWallpapers: [\n {\n slug: UPLOADING_WALLPAPER_SLUG,\n document: {\n fileName: '',\n size: file.size,\n mimeType: file.type,\n previewBlobUrl,\n },\n },\n ...(global.settings.loadedWallpapers || []),\n ],\n },\n });\n\n (async () => {\n const result = await callApi('uploadWallpaper', file);\n if (!result) {\n return;\n }\n\n const { wallpaper } = result;\n\n global = getGlobal();\n if (!global.settings.loadedWallpapers) {\n return;\n }\n\n const firstWallpaper = global.settings.loadedWallpapers[0];\n if (!firstWallpaper || firstWallpaper.slug !== UPLOADING_WALLPAPER_SLUG) {\n return;\n }\n\n const withLocalMedia = {\n ...wallpaper,\n document: {\n ...wallpaper.document,\n previewBlobUrl,\n },\n };\n\n setGlobal({\n ...global,\n settings: {\n ...global.settings,\n loadedWallpapers: [\n withLocalMedia,\n ...global.settings.loadedWallpapers.slice(1),\n ],\n },\n });\n })();\n});\n\naddReducer('loadBlockedContacts', () => {\n (async () => {\n const result = await callApi('fetchBlockedContacts');\n\n if (!result) {\n return;\n }\n\n let newGlobal = getGlobal();\n\n if (result.users && result.users.length) {\n newGlobal = addUsers(newGlobal, buildCollectionByKey(result.users, 'id'));\n }\n if (result.chats && result.chats.length) {\n newGlobal = updateChats(newGlobal, buildCollectionByKey(result.chats, 'id'));\n }\n\n newGlobal = {\n ...newGlobal,\n blocked: {\n ...newGlobal.blocked,\n ids: [...(newGlobal.blocked.ids || []), ...result.blockedIds],\n totalCount: result.totalCount,\n },\n };\n\n setGlobal(newGlobal);\n })();\n});\n\naddReducer('blockContact', (global, actions, payload) => {\n const { contactId, accessHash } = payload!;\n\n (async () => {\n const result = await callApi('blockContact', contactId, accessHash);\n if (!result) {\n return;\n }\n\n const newGlobal = getGlobal();\n\n setGlobal(addBlockedContact(newGlobal, contactId));\n })();\n});\n\naddReducer('unblockContact', (global, actions, payload) => {\n const { contactId } = payload!;\n let accessHash: string | undefined;\n const isPrivate = isChatPrivate(contactId);\n\n if (isPrivate) {\n const user = selectUser(global, contactId);\n if (!user) {\n return;\n }\n\n accessHash = user.accessHash;\n }\n\n (async () => {\n const result = await callApi('unblockContact', contactId, accessHash);\n if (!result) {\n return;\n }\n\n const newGlobal = getGlobal();\n\n setGlobal(removeBlockedContact(newGlobal, contactId));\n })();\n});\n\naddReducer('loadAuthorizations', () => {\n (async () => {\n const result = await callApi('fetchAuthorizations');\n if (!result) {\n return;\n }\n\n setGlobal({\n ...getGlobal(),\n activeSessions: result,\n });\n })();\n});\n\naddReducer('terminateAuthorization', (global, actions, payload) => {\n const { hash } = payload!;\n\n (async () => {\n const result = await callApi('terminateAuthorization', hash);\n if (!result) {\n return;\n }\n\n const newGlobal = getGlobal();\n\n setGlobal({\n ...newGlobal,\n activeSessions: newGlobal.activeSessions.filter((session) => session.hash !== hash),\n });\n })();\n});\n\naddReducer('terminateAllAuthorizations', () => {\n (async () => {\n const result = await callApi('terminateAllAuthorizations');\n if (!result) {\n return;\n }\n\n const global = getGlobal();\n\n setGlobal({\n ...global,\n activeSessions: global.activeSessions.filter((session) => session.isCurrent),\n });\n })();\n});\n\naddReducer('loadNotificationExceptions', (global) => {\n const { serverTimeOffset } = global;\n\n (async () => {\n const result = await callApi('fetchNotificationExceptions', { serverTimeOffset });\n if (!result) {\n return;\n }\n\n setGlobal(addNotifyExceptions(getGlobal(), result));\n })();\n});\n\naddReducer('loadNotificationSettings', (global) => {\n const { serverTimeOffset } = global;\n (async () => {\n const result = await callApi('fetchNotificationSettings', {\n serverTimeOffset,\n });\n if (!result) {\n return;\n }\n\n setGlobal(replaceSettings(getGlobal(), result));\n })();\n});\n\naddReducer('updateNotificationSettings', (global, actions, payload) => {\n const { peerType, isSilent, shouldShowPreviews } = payload!;\n\n (async () => {\n const result = await callApi('updateNotificationSettings', peerType, { isSilent, shouldShowPreviews });\n\n if (!result) {\n return;\n }\n\n setGlobal(updateNotifySettings(getGlobal(), peerType, isSilent, shouldShowPreviews));\n })();\n});\n\naddReducer('updateWebNotificationSettings', (global, actions, payload) => {\n (async () => {\n setGlobal(replaceSettings(getGlobal(), payload));\n const newGlobal = getGlobal();\n const { hasPushNotifications, hasWebNotifications } = newGlobal.settings.byKey;\n if (hasWebNotifications && hasPushNotifications) {\n await subscribe();\n } else {\n await unsubscribe();\n }\n })();\n});\n\naddReducer('updateContactSignUpNotification', (global, actions, payload) => {\n const { isSilent } = payload!;\n\n (async () => {\n const result = await callApi('updateContactSignUpNotification', isSilent);\n if (!result) {\n return;\n }\n\n setGlobal(replaceSettings(getGlobal(), { hasContactJoinedNotifications: !isSilent }));\n })();\n});\n\naddReducer('loadLanguages', () => {\n (async () => {\n const result = await callApi('fetchLanguages');\n if (!result) {\n return;\n }\n\n setGlobal(replaceSettings(getGlobal(), { languages: result }));\n })();\n});\n\naddReducer('loadPrivacySettings', () => {\n (async () => {\n const [\n phoneNumberSettings, lastSeenSettings, profilePhotoSettings, forwardsSettings, chatInviteSettings,\n ] = await Promise.all([\n callApi('fetchPrivacySettings', 'phoneNumber'),\n callApi('fetchPrivacySettings', 'lastSeen'),\n callApi('fetchPrivacySettings', 'profilePhoto'),\n callApi('fetchPrivacySettings', 'forwards'),\n callApi('fetchPrivacySettings', 'chatInvite'),\n ]);\n\n if (\n !phoneNumberSettings || !lastSeenSettings || !profilePhotoSettings || !forwardsSettings || !chatInviteSettings\n ) {\n return;\n }\n\n const global = getGlobal();\n\n global.settings.privacy.phoneNumber = phoneNumberSettings;\n global.settings.privacy.lastSeen = lastSeenSettings;\n global.settings.privacy.profilePhoto = profilePhotoSettings;\n global.settings.privacy.forwards = forwardsSettings;\n global.settings.privacy.chatInvite = chatInviteSettings;\n\n setGlobal(global);\n })();\n});\n\naddReducer('setPrivacyVisibility', (global, actions, payload) => {\n const { privacyKey, visibility } = payload!;\n\n const {\n privacy: { [privacyKey as ApiPrivacyKey]: settings },\n } = global.settings;\n\n if (!settings) {\n return;\n }\n\n const rules = buildInputPrivacyRules(global, {\n visibility,\n allowedIds: [...settings.allowUserIds, ...settings.allowChatIds],\n deniedIds: [...settings.blockUserIds, ...settings.blockChatIds],\n });\n\n (async () => {\n const result = await callApi('setPrivacySettings', privacyKey, rules);\n\n if (result) {\n const newGlobal = getGlobal();\n\n newGlobal.settings.privacy[privacyKey as ApiPrivacyKey] = result;\n\n setGlobal(newGlobal);\n }\n })();\n});\n\naddReducer('setPrivacySettings', (global, actions, payload) => {\n const { privacyKey, isAllowList, contactsIds } = payload!;\n const {\n privacy: { [privacyKey as ApiPrivacyKey]: settings },\n } = global.settings;\n\n if (!settings) {\n return;\n }\n\n const rules = buildInputPrivacyRules(global, {\n visibility: settings.visibility,\n allowedIds: isAllowList ? contactsIds : [...settings.allowUserIds, ...settings.allowChatIds],\n deniedIds: !isAllowList ? contactsIds : [...settings.blockUserIds, ...settings.blockChatIds],\n });\n\n (async () => {\n const result = await callApi('setPrivacySettings', privacyKey, rules);\n\n if (result) {\n const newGlobal = getGlobal();\n\n newGlobal.settings.privacy[privacyKey as ApiPrivacyKey] = result;\n\n setGlobal(newGlobal);\n }\n })();\n});\n\nfunction buildInputPrivacyRules(global: GlobalState, {\n visibility,\n allowedIds,\n deniedIds,\n}: {\n visibility: PrivacyVisibility;\n allowedIds: number[];\n deniedIds: number[];\n}): IInputPrivacyRules {\n const {\n users: { byId: usersById },\n chats: { byId: chatsById },\n } = global;\n\n const rules: IInputPrivacyRules = {\n visibility,\n };\n let users: IInputPrivacyContact[];\n let chats: IInputPrivacyContact[];\n\n const collectUsers = (userId: number) => {\n if (!isChatPrivate(userId)) {\n return undefined;\n }\n const { id, accessHash } = usersById[userId] || {};\n if (!id) {\n return undefined;\n }\n\n return { id, accessHash };\n };\n\n const collectChats = (userId: number) => {\n if (isChatPrivate(userId)) {\n return undefined;\n }\n const chat = chatsById[userId];\n\n return chat ? { id: chat.id } : undefined;\n };\n\n if (visibility === 'contacts' || visibility === 'nobody') {\n users = allowedIds.map(collectUsers).filter(Boolean) as IInputPrivacyContact[];\n chats = allowedIds.map(collectChats).filter(Boolean) as IInputPrivacyContact[];\n\n if (users.length > 0) {\n rules.allowedUsers = users;\n }\n if (chats.length > 0) {\n rules.allowedChats = chats;\n }\n }\n\n if (visibility === 'everybody' || visibility === 'contacts') {\n users = deniedIds.map(collectUsers).filter(Boolean) as IInputPrivacyContact[];\n chats = deniedIds.map(collectChats).filter(Boolean) as IInputPrivacyContact[];\n\n if (users.length > 0) {\n rules.blockedUsers = users;\n }\n if (chats.length > 0) {\n rules.blockedChats = chats;\n }\n }\n\n return rules;\n}\n\naddReducer('updateIsOnline', (global, actions, payload) => {\n callApi('updateIsOnline', payload);\n});\n\naddReducer('loadContentSettings', () => {\n (async () => {\n const result = await callApi('fetchContentSettings');\n if (!result) return;\n\n setGlobal(replaceSettings(getGlobal(), result));\n })();\n});\n\naddReducer('updateContentSettings', (global, actions, payload) => {\n (async () => {\n setGlobal(replaceSettings(getGlobal(), { isSensitiveEnabled: payload }));\n\n const result = await callApi('updateContentSettings', payload);\n if (!result) {\n setGlobal(replaceSettings(getGlobal(), { isSensitiveEnabled: !payload }));\n }\n })();\n});\n","import {\n addReducer, getDispatch, getGlobal, setGlobal,\n} from '../../../lib/teact/teactn';\n\nimport { GlobalState } from '../../../global/types';\n\nimport {\n ApiUpdate,\n ApiUpdateAuthorizationState,\n ApiUpdateAuthorizationError,\n ApiUpdateConnectionState,\n ApiUpdateSession,\n ApiUpdateCurrentUser, ApiUpdateServerTimeOffset,\n} from '../../../api/types';\nimport { DEBUG, SESSION_USER_KEY } from '../../../config';\nimport { subscribe } from '../../../util/notifications';\nimport { updateUser } from '../../reducers';\nimport { setLanguage } from '../../../util/langProvider';\nimport { selectNotifySettings } from '../../selectors';\nimport { forceWebsync } from '../../../util/websync';\nimport { getShippingError } from '../../../util/getReadableErrorText';\n\naddReducer('apiUpdate', (global, actions, update: ApiUpdate) => {\n if (DEBUG) {\n if (update['@type'] !== 'updateUserStatus' && update['@type'] !== 'updateServerTimeOffset') {\n // eslint-disable-next-line no-console\n console.log('[GramJs] UPDATE', update['@type'], { update });\n }\n }\n\n switch (update['@type']) {\n case 'updateApiReady':\n onUpdateApiReady(global);\n break;\n\n case 'updateAuthorizationState':\n onUpdateAuthorizationState(update);\n break;\n\n case 'updateAuthorizationError':\n onUpdateAuthorizationError(update);\n break;\n\n case 'updateConnectionState':\n onUpdateConnectionState(update);\n break;\n\n case 'updateSession':\n onUpdateSession(update);\n break;\n\n case 'updateServerTimeOffset':\n onUpdateServerTimeOffset(update);\n break;\n\n case 'updateCurrentUser':\n onUpdateCurrentUser(update);\n break;\n\n case 'error':\n if (update.error.message === 'SESSION_REVOKED') {\n actions.signOut();\n }\n\n const paymentShippingError = getShippingError(update.error);\n if (paymentShippingError) {\n actions.addPaymentError({ error: paymentShippingError });\n } else if (actions.showDialog) {\n actions.showDialog({ data: { ...update.error, hasErrorKey: true } });\n }\n\n break;\n }\n});\n\nfunction onUpdateApiReady(global: GlobalState) {\n const { hasWebNotifications, hasPushNotifications } = selectNotifySettings(global);\n if (hasWebNotifications && hasPushNotifications) {\n void subscribe();\n }\n void setLanguage(global.settings.byKey.language);\n}\n\nfunction onUpdateAuthorizationState(update: ApiUpdateAuthorizationState) {\n let global = getGlobal();\n\n const wasAuthReady = global.authState === 'authorizationStateReady';\n const authState = update.authorizationState;\n\n setGlobal({\n ...global,\n authState,\n authIsLoading: false,\n });\n\n global = getGlobal();\n\n switch (authState) {\n case 'authorizationStateLoggingOut':\n void forceWebsync(false);\n\n setGlobal({\n ...global,\n isLoggingOut: true,\n });\n break;\n case 'authorizationStateWaitCode':\n setGlobal({\n ...global,\n authIsCodeViaApp: update.isCodeViaApp,\n });\n break;\n case 'authorizationStateWaitPassword':\n setGlobal({\n ...global,\n authHint: update.hint,\n });\n break;\n case 'authorizationStateWaitQrCode':\n setGlobal({\n ...global,\n authIsLoadingQrCode: false,\n authQrCode: update.qrCode,\n });\n break;\n case 'authorizationStateReady': {\n if (wasAuthReady) {\n break;\n }\n\n void forceWebsync(true);\n\n setGlobal({\n ...global,\n isLoggingOut: false,\n lastSyncTime: Date.now(),\n });\n\n break;\n }\n }\n}\n\nfunction onUpdateAuthorizationError(update: ApiUpdateAuthorizationError) {\n setGlobal({\n ...getGlobal(),\n authError: update.message,\n });\n}\n\nfunction onUpdateConnectionState(update: ApiUpdateConnectionState) {\n const { connectionState } = update;\n const global = getGlobal();\n\n setGlobal({\n ...global,\n connectionState,\n });\n\n if (connectionState === 'connectionStateReady' && global.authState === 'authorizationStateReady') {\n getDispatch().sync();\n } else if (connectionState === 'connectionStateBroken') {\n getDispatch().signOut();\n }\n}\n\nfunction onUpdateSession(update: ApiUpdateSession) {\n const { sessionData } = update;\n const { authRememberMe, authState } = getGlobal();\n const isEmpty = !sessionData || !sessionData.mainDcId;\n\n if (!authRememberMe || authState !== 'authorizationStateReady' || isEmpty) {\n return;\n }\n\n getDispatch().saveSession({ sessionData });\n}\n\nfunction onUpdateServerTimeOffset(update: ApiUpdateServerTimeOffset) {\n const global = getGlobal();\n\n if (global.serverTimeOffset === update.serverTimeOffset) {\n return;\n }\n\n setGlobal({\n ...global,\n serverTimeOffset: update.serverTimeOffset,\n });\n}\n\nfunction onUpdateCurrentUser(update: ApiUpdateCurrentUser) {\n const { currentUser } = update;\n\n setGlobal({\n ...updateUser(getGlobal(), currentUser.id, currentUser),\n currentUserId: currentUser.id,\n });\n\n updateSessionUserId(currentUser.id);\n}\n\nfunction updateSessionUserId(currentUserId: number) {\n const sessionUserAuth = localStorage.getItem(SESSION_USER_KEY);\n if (!sessionUserAuth) return;\n\n const userAuth = JSON.parse(sessionUserAuth);\n userAuth.id = currentUserId;\n\n localStorage.setItem(SESSION_USER_KEY, JSON.stringify(userAuth));\n}\n","import { addReducer, getGlobal, setGlobal } from '../../../lib/teact/teactn';\n\nimport { ANIMATION_LEVEL_MAX } from '../../../config';\nimport {\n IS_ANDROID, IS_IOS, IS_MAC_OS, IS_SAFARI, IS_TOUCH_ENV,\n} from '../../../util/environment';\nimport { setLanguage } from '../../../util/langProvider';\nimport switchTheme from '../../../util/switchTheme';\nimport { selectTheme } from '../../selectors';\nimport { startWebsync } from '../../../util/websync';\n\nconst HISTORY_ANIMATION_DURATION = 450;\n\nsubscribeToSystemThemeChange();\n\naddReducer('init', (global) => {\n const { animationLevel, messageTextSize, language } = global.settings.byKey;\n const theme = selectTheme(global);\n\n void setLanguage(language, undefined, true);\n\n document.documentElement.style.setProperty(\n '--composer-text-size', `${Math.max(messageTextSize, IS_IOS ? 16 : 15)}px`,\n );\n document.documentElement.style.setProperty('--message-meta-height', `${Math.floor(messageTextSize * 1.3125)}px`);\n document.documentElement.style.setProperty('--message-text-size', `${messageTextSize}px`);\n document.documentElement.setAttribute('data-message-text-size', messageTextSize.toString());\n document.body.classList.add('initial');\n document.body.classList.add(`animation-level-${animationLevel}`);\n document.body.classList.add(IS_TOUCH_ENV ? 'is-touch-env' : 'is-pointer-env');\n switchTheme(theme, animationLevel === ANIMATION_LEVEL_MAX);\n startWebsync();\n\n if (IS_SAFARI) {\n document.body.classList.add('is-safari');\n }\n if (IS_IOS) {\n document.body.classList.add('is-ios');\n } else if (IS_ANDROID) {\n document.body.classList.add('is-android');\n } else if (IS_MAC_OS) {\n document.body.classList.add('is-macos');\n }\n});\n\naddReducer('setIsUiReady', (global, actions, payload) => {\n const { uiReadyState } = payload!;\n\n if (uiReadyState === 2) {\n document.body.classList.remove('initial');\n }\n\n return {\n ...global,\n uiReadyState,\n };\n});\n\naddReducer('setAuthPhoneNumber', (global, actions, payload) => {\n const { phoneNumber } = payload!;\n\n return {\n ...global,\n authPhoneNumber: phoneNumber,\n };\n});\n\naddReducer('setAuthRememberMe', (global, actions, payload) => {\n return {\n ...global,\n authRememberMe: Boolean(payload),\n };\n});\n\naddReducer('clearAuthError', (global) => {\n return {\n ...global,\n authError: undefined,\n };\n});\n\naddReducer('disableHistoryAnimations', () => {\n setTimeout(() => {\n setGlobal({\n ...getGlobal(),\n shouldSkipHistoryAnimations: false,\n });\n document.body.classList.remove('no-animate');\n }, HISTORY_ANIMATION_DURATION);\n\n setGlobal({\n ...getGlobal(),\n shouldSkipHistoryAnimations: true,\n }, true);\n});\n\nfunction subscribeToSystemThemeChange() {\n function handleSystemThemeChange() {\n const currentThemeMatch = document.documentElement.className.match(/theme-(\\w+)/);\n const currentTheme = currentThemeMatch ? currentThemeMatch[1] : 'light';\n const global = getGlobal();\n const nextTheme = selectTheme(global);\n const { animationLevel } = global.settings.byKey;\n\n if (nextTheme !== currentTheme) {\n switchTheme(nextTheme, animationLevel === ANIMATION_LEVEL_MAX);\n // Force-update component containers\n setGlobal({ ...global });\n }\n }\n\n const mql = window.matchMedia('(prefers-color-scheme: dark)');\n if (typeof mql.addEventListener === 'function') {\n mql.addEventListener('change', handleSystemThemeChange);\n } else if (typeof mql.addListener === 'function') {\n mql.addListener(handleSystemThemeChange);\n }\n}\n","import { addReducer } from '../../../lib/teact/teactn';\nimport { ISettings, IThemeSettings, ThemeKey } from '../../../types';\nimport { replaceSettings, replaceThemeSettings } from '../../reducers';\n\naddReducer('setSettingOption', (global, actions, payload?: Partial<ISettings>) => {\n return replaceSettings(global, payload);\n});\n\naddReducer('setThemeSettings', (global, actions, payload: { theme: ThemeKey } & Partial<IThemeSettings>) => {\n const { theme, ...settings } = payload;\n\n return replaceThemeSettings(global, theme, settings);\n});\n","import {\n ApiChat,\n ApiUser,\n ApiChatBannedRights,\n ApiChatAdminRights,\n ApiChatFolder,\n MAIN_THREAD_ID,\n} from '../../api/types';\n\nimport { NotifyException, NotifySettings } from '../../types';\nimport { LangFn } from '../../hooks/useLang';\n\nimport { ARCHIVED_FOLDER_ID } from '../../config';\nimport { orderBy } from '../../util/iteratees';\nimport { getUserFirstOrLastName } from './users';\nimport { formatDateToString, formatTime } from '../../util/dateFormat';\n\nconst FOREVER_BANNED_DATE = Date.now() / 1000 + 31622400; // 366 days\n\nconst VERIFIED_PRIORITY_BASE = 3e9;\nconst PINNED_PRIORITY_BASE = 3e8;\n\nexport function isChatPrivate(chatId: number) {\n return chatId > 0;\n}\n\nexport function isChatGroup(chat: ApiChat) {\n return isChatBasicGroup(chat) || isChatSuperGroup(chat);\n}\n\nexport function isChatBasicGroup(chat: ApiChat) {\n return chat.type === 'chatTypeBasicGroup';\n}\n\nexport function isChatSuperGroup(chat: ApiChat) {\n return chat.type === 'chatTypeSuperGroup';\n}\n\nexport function isChatChannel(chat: ApiChat) {\n return chat.type === 'chatTypeChannel';\n}\n\nexport function isCommonBoxChat(chat: ApiChat) {\n return chat.type === 'chatTypePrivate' || chat.type === 'chatTypeBasicGroup';\n}\n\nexport function getChatTypeString(chat: ApiChat) {\n switch (chat.type) {\n case 'chatTypePrivate':\n return 'PrivateChat';\n case 'chatTypeBasicGroup':\n case 'chatTypeSuperGroup':\n return 'AccDescrGroup';\n case 'chatTypeChannel':\n return 'AccDescrChannel';\n default:\n return 'Chat';\n }\n}\n\nexport function getPrivateChatUserId(chat: ApiChat) {\n if (chat.type !== 'chatTypePrivate' && chat.type !== 'chatTypeSecret') {\n return undefined;\n }\n return chat.id;\n}\n\n// TODO Get rid of `user`\nexport function getChatTitle(lang: LangFn, chat: ApiChat, user?: ApiUser, isSelf = false) {\n if (isSelf || (user && chat.id === user.id && user.isSelf)) {\n return lang('SavedMessages');\n }\n return chat.title || lang('HiddenName');\n}\n\nexport function getChatDescription(chat: ApiChat) {\n if (!chat.fullInfo) {\n return undefined;\n }\n return chat.fullInfo.about;\n}\n\nexport function getChatLink(chat: ApiChat) {\n const { username } = chat;\n if (username) {\n return `https://t.me/${username}`;\n }\n\n const { inviteLink } = chat.fullInfo || {};\n\n return inviteLink;\n}\n\nexport function getChatAvatarHash(\n owner: ApiChat | ApiUser,\n size: 'normal' | 'big' = 'normal',\n) {\n if (!owner.avatarHash) {\n return undefined;\n }\n\n switch (size) {\n case 'big':\n return `profile${owner.id}?${owner.avatarHash}`;\n default:\n return `avatar${owner.id}?${owner.avatarHash}`;\n }\n}\n\nexport function isChatSummaryOnly(chat: ApiChat) {\n return !chat.lastMessage;\n}\n\nexport function isChatAdmin(chat: ApiChat) {\n return Boolean(chat.adminRights);\n}\n\nexport function getHasAdminRight(chat: ApiChat, key: keyof ApiChatAdminRights) {\n return chat.adminRights ? chat.adminRights[key] : false;\n}\n\nexport function isUserRightBanned(chat: ApiChat, key: keyof ApiChatBannedRights) {\n return Boolean(\n (chat.currentUserBannedRights && chat.currentUserBannedRights[key])\n || (chat.defaultBannedRights && chat.defaultBannedRights[key]),\n );\n}\n\nexport function getCanPostInChat(chat: ApiChat, threadId: number) {\n if (threadId !== MAIN_THREAD_ID) {\n return true;\n }\n\n if (chat.isRestricted || chat.migratedTo || chat.isNotJoined) {\n return false;\n }\n\n if (chat.isCreator) {\n return true;\n }\n\n if (isChatPrivate(chat.id)) {\n return true;\n }\n\n if (isChatChannel(chat)) {\n return getHasAdminRight(chat, 'postMessages');\n }\n\n return isChatAdmin(chat) || !isUserRightBanned(chat, 'sendMessages');\n}\n\nexport interface IAllowedAttachmentOptions {\n canAttachMedia: boolean;\n canAttachPolls: boolean;\n canSendStickers: boolean;\n canSendGifs: boolean;\n canAttachEmbedLinks: boolean;\n}\n\nexport function getAllowedAttachmentOptions(chat?: ApiChat, isChatWithBot = false): IAllowedAttachmentOptions {\n if (!chat) {\n return {\n canAttachMedia: false,\n canAttachPolls: false,\n canSendStickers: false,\n canSendGifs: false,\n canAttachEmbedLinks: false,\n };\n }\n\n const isAdmin = isChatAdmin(chat);\n\n return {\n canAttachMedia: isAdmin || !isUserRightBanned(chat, 'sendMedia'),\n canAttachPolls: (isAdmin || !isUserRightBanned(chat, 'sendPolls')) && (!isChatPrivate(chat.id) || isChatWithBot),\n canSendStickers: isAdmin || !isUserRightBanned(chat, 'sendStickers'),\n canSendGifs: isAdmin || !isUserRightBanned(chat, 'sendGifs'),\n canAttachEmbedLinks: isAdmin || !isUserRightBanned(chat, 'embedLinks'),\n };\n}\n\nexport function getMessageSendingRestrictionReason(\n lang: LangFn, currentUserBannedRights?: ApiChatBannedRights, defaultBannedRights?: ApiChatBannedRights,\n) {\n if (currentUserBannedRights && currentUserBannedRights.sendMessages) {\n const { untilDate } = currentUserBannedRights;\n return untilDate && untilDate < FOREVER_BANNED_DATE\n ? lang(\n 'Channel.Persmission.Denied.SendMessages.Until',\n lang(\n 'formatDateAtTime',\n [formatDateToString(new Date(untilDate * 1000), lang.code), formatTime(untilDate * 1000)],\n ),\n )\n : lang('Channel.Persmission.Denied.SendMessages.Forever');\n }\n\n if (defaultBannedRights && defaultBannedRights.sendMessages) {\n return lang('Channel.Persmission.Denied.SendMessages.DefaultRestrictedText');\n }\n\n return undefined;\n}\n\nexport function getChatSlowModeOptions(chat?: ApiChat) {\n if (!chat || !chat.fullInfo) {\n return undefined;\n }\n\n return chat.fullInfo.slowMode;\n}\n\nexport function getChatOrder(chat: ApiChat) {\n return Math.max(\n chat.joinDate || 0,\n chat.draftDate || 0,\n chat.lastMessage ? chat.lastMessage.date : 0,\n );\n}\n\nexport function isChatArchived(chat: ApiChat) {\n return chat.folderId === ARCHIVED_FOLDER_ID;\n}\n\nexport function selectIsChatMuted(\n chat: ApiChat, notifySettings: NotifySettings, notifyExceptions: Record<number, NotifyException> = [],\n) {\n // If this chat is in exceptions they take precedence\n if (notifyExceptions[chat.id] && notifyExceptions[chat.id].isMuted !== undefined) {\n return notifyExceptions[chat.id].isMuted;\n }\n\n return (\n chat.isMuted\n || (isChatPrivate(chat.id) && !notifySettings.hasPrivateChatsNotifications)\n || (isChatChannel(chat) && !notifySettings.hasBroadcastNotifications)\n || (isChatGroup(chat) && !notifySettings.hasGroupNotifications)\n );\n}\n\nexport function selectShouldShowMessagePreview(\n chat: ApiChat, notifySettings: NotifySettings, notifyExceptions: Record<number, NotifyException> = [],\n) {\n const {\n hasPrivateChatsMessagePreview = true,\n hasBroadcastMessagePreview = true,\n hasGroupMessagePreview = true,\n } = notifySettings;\n // If this chat is in exceptions they take precedence\n if (notifyExceptions[chat.id] && notifyExceptions[chat.id].shouldShowPreviews !== undefined) {\n return notifyExceptions[chat.id].shouldShowPreviews;\n }\n\n return (isChatPrivate(chat.id) && hasPrivateChatsMessagePreview)\n || (isChatChannel(chat) && hasBroadcastMessagePreview)\n || (isChatGroup(chat) && hasGroupMessagePreview);\n}\n\nexport function getCanDeleteChat(chat: ApiChat) {\n return isChatBasicGroup(chat) || ((isChatSuperGroup(chat) || isChatChannel(chat)) && chat.isCreator);\n}\n\nexport function prepareFolderListIds(\n chatsById: Record<number, ApiChat>,\n usersById: Record<number, ApiUser>,\n folder: ApiChatFolder,\n notifySettings: NotifySettings,\n notifyExceptions?: Record<number, NotifyException>,\n chatIdsCache?: number[],\n) {\n const excludedChatIds = folder.excludedChatIds ? new Set(folder.excludedChatIds) : undefined;\n const includedChatIds = folder.excludedChatIds ? new Set(folder.includedChatIds) : undefined;\n const pinnedChatIds = folder.excludedChatIds ? new Set(folder.pinnedChatIds) : undefined;\n const listIds = (chatIdsCache || Object.keys(chatsById).map(Number))\n .filter((id) => {\n return filterChatFolder(\n chatsById[id],\n folder,\n usersById,\n notifySettings,\n notifyExceptions,\n excludedChatIds,\n includedChatIds,\n pinnedChatIds,\n );\n });\n\n return [listIds, folder.pinnedChatIds] as const;\n}\n\nfunction filterChatFolder(\n chat: ApiChat,\n folder: ApiChatFolder,\n usersById: Record<number, ApiUser>,\n notifySettings: NotifySettings,\n notifyExceptions?: Record<number, NotifyException>,\n excludedChatIds?: Set<number>,\n includedChatIds?: Set<number>,\n pinnedChatIds?: Set<number>,\n) {\n if (!chat.isListed) {\n return false;\n }\n\n if (excludedChatIds && excludedChatIds.has(chat.id)) {\n return false;\n }\n\n if (includedChatIds && includedChatIds.has(chat.id)) {\n return true;\n }\n\n if (pinnedChatIds && pinnedChatIds.has(chat.id)) {\n return true;\n }\n\n if (isChatArchived(chat) && folder.excludeArchived) {\n return false;\n }\n\n if (folder.excludeMuted && !chat.unreadMentionsCount && selectIsChatMuted(chat, notifySettings, notifyExceptions)) {\n return false;\n }\n\n if (!chat.unreadCount && !chat.unreadMentionsCount && !chat.hasUnreadMark && folder.excludeRead) {\n return false;\n }\n\n if (isChatPrivate(chat.id)) {\n const privateChatUser = usersById[chat.id];\n\n const isChatWithBot = privateChatUser && privateChatUser.type === 'userTypeBot';\n if (isChatWithBot) {\n if (folder.bots) {\n return true;\n }\n } else {\n if (folder.contacts && privateChatUser && privateChatUser.isContact) {\n return true;\n }\n\n if (folder.nonContacts && privateChatUser && !privateChatUser.isContact) {\n return true;\n }\n }\n } else if (isChatGroup(chat)) {\n return !!folder.groups;\n } else if (isChatChannel(chat)) {\n return !!folder.channels;\n }\n\n return false;\n}\n\nexport function prepareChatList(\n chatsById: Record<number, ApiChat>,\n listIds: number[],\n orderedPinnedIds?: number[],\n folderType: 'all' | 'archived' | 'folder' = 'all',\n) {\n function chatFilter(chat?: ApiChat) {\n if (!chat || !chat.lastMessage || chat.migratedTo) {\n return false;\n }\n\n switch (folderType) {\n case 'all':\n if (isChatArchived(chat)) {\n return false;\n }\n break;\n case 'archived':\n if (!isChatArchived(chat)) {\n return false;\n }\n break;\n }\n\n return !chat.isRestricted && !chat.isNotJoined;\n }\n\n const listedChats = listIds\n .map((id) => chatsById[id])\n .filter(chatFilter);\n\n const listIdsSet = new Set(listIds);\n const pinnedChats = orderedPinnedIds\n ? (\n orderedPinnedIds\n .map((id) => chatsById[id])\n .filter(chatFilter)\n .filter((chat) => listIdsSet.has(chat.id))\n )\n : [];\n\n const otherChats = orderBy(\n orderedPinnedIds\n ? listedChats.filter((chat) => !orderedPinnedIds.includes(chat.id))\n : listedChats,\n getChatOrder,\n 'desc',\n );\n\n return {\n pinnedChats,\n otherChats,\n };\n}\n\nexport function getFolderUnreadDialogs(\n chatsById: Record<number, ApiChat>,\n usersById: Record<number, ApiUser>,\n folder: ApiChatFolder,\n chatIdsCache: number[],\n notifySettings: NotifySettings,\n notifyExceptions?: Record<number, NotifyException>,\n) {\n const [listIds] = prepareFolderListIds(chatsById, usersById, folder, notifySettings, notifyExceptions, chatIdsCache);\n\n const listedChats = listIds\n .map((id) => chatsById[id])\n .filter((chat) => (chat && chat.lastMessage && !chat.isRestricted && !chat.isNotJoined));\n\n const unreadDialogsCount = listedChats\n .reduce((total, chat) => (chat.unreadCount || chat.hasUnreadMark ? total + 1 : total), 0);\n\n const hasActiveDialogs = listedChats.some((chat) => (\n chat.unreadMentionsCount\n || (!selectIsChatMuted(chat, notifySettings, notifyExceptions) && (chat.unreadCount || chat.hasUnreadMark))\n ));\n\n return {\n unreadDialogsCount,\n hasActiveDialogs,\n };\n}\n\nexport function getFolderDescriptionText(\n lang: LangFn,\n chatsById: Record<number, ApiChat>,\n usersById: Record<number, ApiUser>,\n folder: ApiChatFolder,\n chatIdsCache: number[],\n notifySettings: NotifySettings,\n notifyExceptions?: Record<number, NotifyException>,\n) {\n const {\n id, title, emoticon, description, pinnedChatIds,\n excludedChatIds, includedChatIds,\n excludeArchived, excludeMuted, excludeRead,\n ...filters\n } = folder;\n\n // If folder has multiple additive filters or uses include/exclude lists,\n // we display folder chats count\n if (\n Object.values(filters).filter(Boolean).length > 1\n || (excludedChatIds && excludedChatIds.length)\n || (includedChatIds && includedChatIds.length)\n ) {\n const length = getFolderChatsCount(chatsById, usersById, folder, chatIdsCache, notifySettings, notifyExceptions);\n return lang('Chats', length);\n }\n\n // Otherwise, we return a short description of a single filter\n if (filters.bots) {\n return lang('FilterBots');\n } else if (filters.groups) {\n return lang('FilterGroups');\n } else if (filters.channels) {\n return lang('FilterChannels');\n } else if (filters.contacts) {\n return lang('FilterContacts');\n } else if (filters.nonContacts) {\n return lang('FilterNonContacts');\n } else {\n return undefined;\n }\n}\n\nfunction getFolderChatsCount(\n chatsById: Record<number, ApiChat>,\n usersById: Record<number, ApiUser>,\n folder: ApiChatFolder,\n chatIdsCache: number[],\n notifySettings: NotifySettings,\n notifyExceptions?: Record<number, NotifyException>,\n) {\n const [listIds, pinnedIds] = prepareFolderListIds(\n chatsById, usersById, folder, notifySettings, notifyExceptions, chatIdsCache,\n );\n const { pinnedChats, otherChats } = prepareChatList(chatsById, listIds, pinnedIds, 'folder');\n return pinnedChats.length + otherChats.length;\n}\n\nexport function isChat(chatOrUser?: ApiUser | ApiChat): chatOrUser is ApiChat {\n if (!chatOrUser) {\n return false;\n }\n\n return chatOrUser.id < 0;\n}\n\nexport function getMessageSenderName(lang: LangFn, chatId: number, sender?: ApiUser) {\n if (!sender || isChatPrivate(chatId)) {\n return undefined;\n }\n\n if (sender.isSelf) {\n return lang('FromYou');\n }\n\n return getUserFirstOrLastName(sender);\n}\n\nexport function sortChatIds(\n chatIds: number[],\n chatsById: Record<number, ApiChat>,\n shouldPrioritizeVerified = false,\n priorityIds?: number[],\n) {\n return orderBy(chatIds, (id) => {\n const chat = chatsById[id];\n if (!chat) {\n return 0;\n }\n\n let priority = 0;\n\n if (chat.lastMessage) {\n priority += chat.lastMessage.date;\n }\n\n if (shouldPrioritizeVerified && chat.isVerified) {\n priority += VERIFIED_PRIORITY_BASE; // ~100 years in seconds\n }\n\n if (priorityIds && priorityIds.includes(id)) {\n priority = Date.now() + PINNED_PRIORITY_BASE + (priorityIds.length - priorityIds.indexOf(id));\n }\n\n return priority;\n }, 'desc');\n}\n","import {\n ApiChat, ApiMessage, ApiMessageEntityTypes, ApiUser,\n} from '../../api/types';\nimport { LangFn } from '../../hooks/useLang';\n\nimport { LOCAL_MESSAGE_ID_BASE, SERVICE_NOTIFICATIONS_USER_ID, RE_LINK_TEMPLATE } from '../../config';\nimport parseEmojiOnlyString from '../../components/common/helpers/parseEmojiOnlyString';\nimport { getUserFullName } from './users';\nimport { getChatTitle } from './chats';\n\nconst CONTENT_NOT_SUPPORTED = 'The message is not supported on this version of Telegram';\nconst RE_LINK = new RegExp(RE_LINK_TEMPLATE, 'i');\nconst TRUNCATED_SUMMARY_LENGTH = 80;\n\nexport function getMessageKey(message: ApiMessage) {\n const { chatId, id } = message;\n\n return `msg${chatId}-${id}`;\n}\n\nexport function parseMessageKey(key: string) {\n const match = key.match(/^msg(-?\\d+)-(\\d+)/)!;\n\n return { chatId: Number(match[1]), messageId: Number(match[2]) };\n}\n\nexport function getMessageOriginalId(message: ApiMessage) {\n return message.previousLocalId || message.id;\n}\n\nexport function getMessageSummaryText(lang: LangFn, message: ApiMessage, noEmoji = false) {\n const {\n text, photo, video, audio, voice, document, sticker, contact, poll, invoice,\n } = message.content;\n\n const truncatedText = text && text.text.substr(0, TRUNCATED_SUMMARY_LENGTH);\n\n if (message.groupedId) {\n return `${noEmoji ? '' : '🖼 '}${truncatedText || lang('lng_in_dlg_album')}`;\n }\n\n if (photo) {\n return `${noEmoji ? '' : '🖼 '}${truncatedText || lang('AttachPhoto')}`;\n }\n\n if (video) {\n return `${noEmoji ? '' : '📹 '}${truncatedText || lang(video.isGif ? 'AttachGif' : 'AttachVideo')}`;\n }\n\n if (sticker) {\n return `${sticker.emoji || ''} ${lang('AttachSticker')}`.trim();\n }\n\n if (audio) {\n return `${noEmoji ? '' : '🎧 '}${getMessageAudioCaption(message) || lang('AttachMusic')}`;\n }\n\n if (voice) {\n return `${noEmoji ? '' : '🎤 '}${truncatedText || lang('AttachAudio')}`;\n }\n\n if (document) {\n return `${noEmoji ? '' : '📎 '}${truncatedText || document.fileName}`;\n }\n\n if (contact) {\n return lang('AttachContact');\n }\n\n if (poll) {\n return `${noEmoji ? '' : '📊 '}${poll.summary.question}`;\n }\n\n if (invoice) {\n return 'Invoice';\n }\n\n if (text) {\n return truncatedText;\n }\n\n return CONTENT_NOT_SUPPORTED;\n}\n\nexport function getMessageText(message: ApiMessage) {\n const {\n text, sticker, photo, video, audio, voice, document, poll, webPage, contact, invoice,\n } = message.content;\n\n if (text) {\n return text.text;\n }\n\n if (sticker || photo || video || audio || voice || document || contact || poll || webPage || invoice) {\n return undefined;\n }\n\n return CONTENT_NOT_SUPPORTED;\n}\n\nexport function getMessageCustomShape(message: ApiMessage): boolean | number {\n const {\n text, sticker, photo, video, audio, voice, document, poll, webPage, contact,\n } = message.content;\n\n if (sticker || (video && video.isRound)) {\n return true;\n }\n\n if (!text || photo || video || audio || voice || document || poll || webPage || contact) {\n return false;\n }\n\n // This is a \"dual-intent\" method used to limit calls of `parseEmojiOnlyString`.\n return parseEmojiOnlyString(text.text) || false;\n}\n\nexport function getMessageSingleEmoji(message: ApiMessage) {\n const { text } = message.content;\n if (!(text && text.text.length <= 6)) {\n return undefined;\n }\n\n if (getMessageCustomShape(message) !== 1) {\n return undefined;\n }\n\n return text.text;\n}\n\nexport function getFirstLinkInMessage(message: ApiMessage) {\n const { text } = message.content;\n\n let match: RegExpMatchArray | null | undefined;\n if (text && text.entities) {\n let link = text.entities.find((entity) => entity.type === ApiMessageEntityTypes.TextUrl);\n if (link) {\n match = link.url!.match(RE_LINK);\n }\n\n if (!match) {\n link = text.entities.find((entity) => entity.type === ApiMessageEntityTypes.Url);\n if (link) {\n const { offset, length } = link;\n match = text.text.substring(offset, offset + length).match(RE_LINK);\n }\n }\n }\n\n if (!match && text) {\n match = text.text.match(RE_LINK);\n }\n\n if (!match) {\n return undefined;\n }\n\n return {\n url: match[0],\n domain: match[3],\n };\n}\n\nexport function matchLinkInMessageText(message: ApiMessage) {\n const { text } = message.content;\n const match = text && text.text.match(RE_LINK);\n\n if (!match) {\n return undefined;\n }\n\n return {\n url: match[0],\n domain: match[3],\n };\n}\n\nexport function isOwnMessage(message: ApiMessage) {\n return message.isOutgoing;\n}\n\nexport function isReplyMessage(message: ApiMessage) {\n return Boolean(message.replyToMessageId);\n}\n\nexport function isForwardedMessage(message: ApiMessage) {\n return Boolean(message.forwardInfo);\n}\n\nexport function isActionMessage(message: ApiMessage) {\n return !!message.content.action;\n}\n\nexport function isServiceNotificationMessage(message: ApiMessage) {\n return message.chatId === SERVICE_NOTIFICATIONS_USER_ID && isMessageLocal(message);\n}\n\nexport function isAnonymousOwnMessage(message: ApiMessage) {\n return Boolean(message.senderId) && message.senderId! < 0 && isOwnMessage(message);\n}\n\nexport function getSenderTitle(lang: LangFn, sender: ApiUser | ApiChat) {\n return sender.id > 0 ? getUserFullName(sender as ApiUser) : getChatTitle(lang, sender as ApiChat);\n}\n\nexport function getSendingState(message: ApiMessage) {\n if (!message.sendingState) {\n return 'succeeded';\n }\n\n return message.sendingState === 'messageSendingStateFailed' ? 'failed' : 'pending';\n}\n\nexport function isMessageLocal(message: ApiMessage) {\n return message.id >= LOCAL_MESSAGE_ID_BASE;\n}\n\nexport function isHistoryClearMessage(message: ApiMessage) {\n return message.content.action && message.content.action.type === 'historyClear';\n}\n\nexport function getMessageAudioCaption(message: ApiMessage) {\n const { audio, text } = message.content;\n\n return (audio && [audio.title, audio.performer].filter(Boolean).join(' — ')) || (text && text.text);\n}\n","import {\n ApiAudio, ApiMediaFormat, ApiMessage, ApiMessageSearchType, ApiPhoto, ApiVideo, ApiDimensions,\n} from '../../api/types';\n\nimport { IS_OPUS_SUPPORTED, IS_PROGRESSIVE_SUPPORTED, IS_SAFARI } from '../../util/environment';\nimport { getMessageKey, isMessageLocal, matchLinkInMessageText } from './messages';\nimport { getDocumentHasPreview } from '../../components/common/helpers/documentInfo';\n\ntype Target =\n 'micro'\n | 'pictogram'\n | 'inline'\n | 'viewerPreview'\n | 'viewerFull'\n | 'download';\n\nexport function getMessageContent(message: ApiMessage) {\n return message.content;\n}\n\nexport function hasMessageMedia(message: ApiMessage) {\n return Boolean((\n getMessagePhoto(message)\n || getMessageVideo(message)\n || getMessageDocument(message)\n || getMessageSticker(message)\n || getMessageContact(message)\n || getMessagePoll(message)\n || getMessageAction(message)\n || getMessageAudio(message)\n || getMessageVoice(message)\n ));\n}\n\nexport function getMessagePhoto(message: ApiMessage) {\n return message.content.photo;\n}\n\nexport function getMessageVideo(message: ApiMessage) {\n return message.content.video;\n}\n\nexport function getMessageRoundVideo(message: ApiMessage) {\n const { video } = message.content;\n\n return video && video.isRound ? video : undefined;\n}\n\nexport function getMessageAction(message: ApiMessage) {\n return message.content.action;\n}\n\nexport function getMessageAudio(message: ApiMessage) {\n return message.content.audio;\n}\n\nexport function getMessageVoice(message: ApiMessage) {\n return message.content.voice;\n}\n\nexport function getMessageSticker(message: ApiMessage) {\n return message.content.sticker;\n}\n\nexport function getMessageDocument(message: ApiMessage) {\n return message.content.document;\n}\n\nexport function isMessageDocumentPhoto(message: ApiMessage) {\n const document = getMessageDocument(message);\n return document ? document.mediaType === 'photo' : undefined;\n}\n\nexport function isMessageDocumentVideo(message: ApiMessage) {\n const document = getMessageDocument(message);\n return document ? document.mediaType === 'video' : undefined;\n}\n\nexport function getMessageContact(message: ApiMessage) {\n return message.content.contact;\n}\n\nexport function getMessagePoll(message: ApiMessage) {\n return message.content.poll;\n}\n\nexport function getMessageInvoice(message: ApiMessage) {\n return message.content.invoice;\n}\n\nexport function getMessageWebPage(message: ApiMessage) {\n return message.content.webPage;\n}\n\nexport function getMessageWebPagePhoto(message: ApiMessage) {\n const webPage = getMessageWebPage(message);\n return webPage ? webPage.photo : undefined;\n}\n\nexport function getMessageWebPageDocument(message: ApiMessage) {\n const webPage = getMessageWebPage(message);\n return webPage ? webPage.document : undefined;\n}\n\nexport function getMessageWebPageVideo(message: ApiMessage): ApiVideo | undefined {\n const webPage = getMessageWebPage(message);\n if (!webPage) return undefined;\n return webPage.video;\n}\n\nexport function getMessageMediaThumbnail(message: ApiMessage) {\n const media = getMessagePhoto(message)\n || getMessageVideo(message)\n || getMessageDocument(message)\n || getMessageSticker(message)\n || getMessageWebPagePhoto(message)\n || getMessageWebPageVideo(message);\n\n if (!media) {\n return undefined;\n }\n\n return media.thumbnail;\n}\n\nexport function getMessageMediaThumbDataUri(message: ApiMessage) {\n const thumbnail = getMessageMediaThumbnail(message);\n\n return thumbnail ? thumbnail.dataUri : undefined;\n}\n\nexport function getMessageMediaHash(\n message: ApiMessage,\n target: Target,\n) {\n const {\n photo, video, sticker, audio, voice, document,\n } = message.content;\n const webPagePhoto = getMessageWebPagePhoto(message);\n const webPageVideo = getMessageWebPageVideo(message);\n\n const messageVideo = video || webPageVideo;\n const messagePhoto = photo || webPagePhoto;\n\n if (!(messagePhoto || messageVideo || sticker || audio || voice || document)) {\n return undefined;\n }\n\n const base = getMessageKey(message);\n\n if (messageVideo) {\n switch (target) {\n case 'micro':\n case 'pictogram':\n return `${base}?size=m`;\n case 'inline':\n return !hasMessageLocalBlobUrl(message) ? getVideoOrAudioBaseHash(messageVideo, base) : undefined;\n case 'viewerPreview':\n return `${base}?size=m`;\n case 'viewerFull':\n return getVideoOrAudioBaseHash(messageVideo, base);\n case 'download':\n return `${base}?download`;\n }\n }\n\n if (messagePhoto) {\n switch (target) {\n case 'micro':\n case 'pictogram':\n return `${base}?size=m`;\n case 'inline':\n return !hasMessageLocalBlobUrl(message) ? `${base}?size=x` : undefined;\n case 'viewerPreview':\n return `${base}?size=x`;\n case 'viewerFull':\n return `${base}?size=z`;\n }\n }\n\n if (document) {\n switch (target) {\n case 'micro':\n case 'pictogram':\n case 'inline':\n case 'viewerPreview':\n if (!getDocumentHasPreview(document) || hasMessageLocalBlobUrl(message)) {\n return undefined;\n }\n\n return `${base}?size=m`;\n default:\n return base;\n }\n }\n\n if (sticker) {\n switch (target) {\n case 'micro':\n return undefined;\n case 'pictogram':\n return `${base}?size=m`;\n default:\n return base;\n }\n }\n\n if (audio) {\n switch (target) {\n case 'micro':\n case 'pictogram':\n return undefined;\n case 'download':\n return `${base}?download`;\n default:\n return getVideoOrAudioBaseHash(audio, base);\n }\n }\n\n if (voice) {\n switch (target) {\n case 'micro':\n case 'pictogram':\n return undefined;\n default:\n return base;\n }\n }\n\n return undefined;\n}\n\nfunction getVideoOrAudioBaseHash(media: ApiAudio | ApiVideo, base: string) {\n if (IS_PROGRESSIVE_SUPPORTED && IS_SAFARI) {\n return `${base}?fileSize=${media.size}&mimeType=${media.mimeType}`;\n }\n\n return base;\n}\n\nexport function getMessageMediaFormat(\n message: ApiMessage, target: Target,\n): Exclude<ApiMediaFormat, ApiMediaFormat.Lottie>;\nexport function getMessageMediaFormat(message: ApiMessage, target: Target, canBeLottie: true): ApiMediaFormat;\nexport function getMessageMediaFormat(\n message: ApiMessage, target: Target,\n): ApiMediaFormat {\n const {\n sticker, video, audio, voice,\n } = message.content;\n\n const fullVideo = video || getMessageWebPageVideo(message);\n\n if (sticker && target === 'inline' && sticker.isAnimated) {\n return ApiMediaFormat.Lottie;\n } else if (fullVideo && IS_PROGRESSIVE_SUPPORTED && (\n target === 'viewerFull' || target === 'inline'\n )) {\n return ApiMediaFormat.Progressive;\n } else if (audio || voice) {\n // Safari\n if (voice && !IS_OPUS_SUPPORTED) {\n return ApiMediaFormat.BlobUrl;\n }\n\n return ApiMediaFormat.Progressive;\n }\n\n return ApiMediaFormat.BlobUrl;\n}\n\nexport function getMessageFileName(message: ApiMessage) {\n const {\n photo, video, document,\n } = message.content;\n const webPagePhoto = getMessageWebPagePhoto(message);\n const webPageVideo = getMessageWebPageVideo(message);\n\n if (photo || webPagePhoto) {\n return `photo${message.date}.jpeg`;\n }\n\n const { fileName } = video || webPageVideo || document || {};\n\n return fileName;\n}\n\nexport function getMessageFileSize(message: ApiMessage) {\n const { video, document } = message.content;\n const webPageVideo = getMessageWebPageVideo(message);\n const { size } = video || webPageVideo || document || {};\n\n return size;\n}\n\nexport function hasMessageLocalBlobUrl(message: ApiMessage) {\n const { photo, video, document } = message.content;\n\n return (photo && photo.blobUrl) || (video && video.blobUrl) || (document && document.previewBlobUrl);\n}\n\nexport function getChatMediaMessageIds(\n messages: Record<number, ApiMessage>, listedIds: number[], isFromSharedMedia = false,\n) {\n const ids = getMessageContentIds(messages, listedIds, isFromSharedMedia ? 'media' : 'inlineMedia');\n\n return isFromSharedMedia ? ids.reverse() : ids;\n}\n\nexport function getPhotoFullDimensions(photo: ApiPhoto): ApiDimensions | undefined {\n return (\n photo.sizes.find((size) => size.type === 'z')\n || photo.sizes.find((size) => size.type === 'y')\n || getPhotoInlineDimensions(photo)\n );\n}\n\nexport function getPhotoInlineDimensions(photo: ApiPhoto): ApiDimensions | undefined {\n return (\n photo.sizes.find((size) => size.type === 'x')\n || photo.sizes.find((size) => size.type === 'm')\n || photo.sizes.find((size) => size.type === 's')\n || photo.thumbnail\n );\n}\n\nexport function getVideoDimensions(video: ApiVideo): ApiDimensions | undefined {\n if (video.width && video.height) {\n return video as ApiDimensions;\n }\n\n return undefined;\n}\n\nexport function getMediaTransferState(message: ApiMessage, progress?: number, isDownloadNeeded = false) {\n const isUploading = isMessageLocal(message);\n const isTransferring = isUploading || isDownloadNeeded;\n const transferProgress = Number(progress);\n\n return {\n isUploading, isTransferring, transferProgress,\n };\n}\n\nexport function getMessageContentIds(\n messages: Record<number, ApiMessage>, messageIds: number[], contentType: ApiMessageSearchType | 'inlineMedia',\n) {\n let validator: Function;\n\n switch (contentType) {\n case 'media':\n validator = (message: ApiMessage) => {\n const video = getMessageVideo(message);\n return getMessagePhoto(message) || (video && !video.isRound && !video.isGif);\n };\n break;\n\n case 'documents':\n validator = getMessageDocument;\n break;\n\n case 'links':\n validator = (message: ApiMessage) => getMessageWebPage(message) || matchLinkInMessageText(message);\n break;\n\n case 'audio':\n validator = getMessageAudio;\n break;\n\n case 'inlineMedia':\n validator = (message: ApiMessage) => {\n const video = getMessageVideo(message);\n return (\n getMessagePhoto(message)\n || (video && !video.isRound && !video.isGif)\n || isMessageDocumentPhoto(message)\n || isMessageDocumentVideo(message)\n );\n };\n break;\n\n default:\n return [] as Array<number>;\n }\n\n return messageIds.reduce((result, messageId) => {\n if (messages[messageId] && validator(messages[messageId])) {\n result.push(messageId);\n }\n\n return result;\n }, [] as Array<number>);\n}\n\nexport function getMediaDuration(message: ApiMessage) {\n const { audio, voice, video } = getMessageContent(message);\n const media = audio || voice || video || getMessageWebPageVideo(message);\n if (!media) {\n return undefined;\n }\n\n return media.duration;\n}\n","export function buildChatThreadKey(chatId: number, threadId: number) {\n return `${chatId}_${threadId}`;\n}\n","import { ApiFieldError } from '../../api/types';\n\nconst STRIPE_ERRORS: Record<string, ApiFieldError> = {\n missing_payment_information: {\n field: 'cardNumber',\n message: 'Incorrect card number',\n },\n invalid_number: {\n field: 'cardNumber',\n message: 'Incorrect card number',\n },\n number: {\n field: 'cardNumber',\n message: 'Incorrect card number',\n },\n exp_year: {\n field: 'expiry',\n message: 'Incorrect year',\n },\n exp_month: {\n field: 'expiry',\n message: 'Incorrect month',\n },\n invalid_expiry_year: {\n field: 'expiry',\n message: 'Incorrect year',\n },\n invalid_expiry_month: {\n field: 'expiry',\n message: 'Incorrect month',\n },\n cvc: {\n field: 'cvv',\n message: 'Incorrect CVV',\n },\n invalid_cvc: {\n field: 'cvv',\n message: 'Incorrect CVV',\n },\n};\n\nexport function getStripeError(error: {\n code: string;\n message: string;\n param?: string;\n}) {\n const { message: description, code, param } = error;\n const { field, message } = param ? STRIPE_ERRORS[param] : STRIPE_ERRORS[code];\n\n return { field, message, description };\n}\n","import { ApiChat, ApiUser } from '../../api/types';\n\nimport { SERVICE_NOTIFICATIONS_USER_ID } from '../../config';\nimport { formatFullDate, formatTime } from '../../util/dateFormat';\nimport { orderBy } from '../../util/iteratees';\nimport { LangFn } from '../../hooks/useLang';\n\nconst USER_COLOR_KEYS = [1, 8, 5, 2, 7, 4, 6];\n\nexport function getUserFirstOrLastName(user?: ApiUser) {\n if (!user) {\n return undefined;\n }\n\n switch (user.type) {\n case 'userTypeBot':\n case 'userTypeRegular': {\n return user.firstName || user.lastName;\n }\n\n case 'userTypeDeleted':\n case 'userTypeUnknown': {\n return 'Deleted';\n }\n\n default:\n return undefined;\n }\n}\n\nexport function getUserFullName(user?: ApiUser) {\n if (!user) {\n return undefined;\n }\n\n if (isDeletedUser(user)) {\n return 'Deleted account';\n }\n\n switch (user.type) {\n case 'userTypeBot':\n case 'userTypeRegular': {\n if (user.firstName && user.lastName) {\n return `${user.firstName} ${user.lastName}`;\n }\n\n if (user.firstName) {\n return user.firstName;\n }\n\n if (user.lastName) {\n return user.lastName;\n }\n\n break;\n }\n\n case 'userTypeDeleted':\n case 'userTypeUnknown': {\n return 'Deleted account';\n }\n }\n\n return undefined;\n}\n\nexport function getUserStatus(lang: LangFn, user: ApiUser, serverTimeOffset: number) {\n if (user.id === SERVICE_NOTIFICATIONS_USER_ID) {\n return lang('ServiceNotifications').toLowerCase();\n }\n\n if (user.type && user.type === 'userTypeBot') {\n return lang('Bot');\n }\n\n if (!user.status) {\n return '';\n }\n\n switch (user.status.type) {\n case 'userStatusEmpty': {\n return lang('ALongTimeAgo');\n }\n\n case 'userStatusLastMonth': {\n return lang('WithinAMonth');\n }\n\n case 'userStatusLastWeek': {\n return lang('WithinAWeek');\n }\n\n case 'userStatusOffline': {\n const { wasOnline } = user.status;\n\n if (!wasOnline) return lang('LastSeen.Offline');\n\n const now = new Date(new Date().getTime() + serverTimeOffset * 1000);\n const wasOnlineDate = new Date(wasOnline * 1000);\n\n if (wasOnlineDate >= now) {\n return lang('LastSeen.JustNow');\n }\n\n const diff = new Date(now.getTime() - wasOnlineDate.getTime());\n\n // within a minute\n if (diff.getTime() / 1000 < 60) {\n return lang('LastSeen.JustNow');\n }\n\n // within an hour\n if (diff.getTime() / 1000 < 60 * 60) {\n const minutes = Math.floor(diff.getTime() / 1000 / 60);\n return lang('LastSeen.MinutesAgo', minutes);\n }\n\n // today\n const today = new Date();\n today.setHours(0, 0, 0, 0);\n const serverToday = new Date(today.getTime() + serverTimeOffset * 1000);\n if (wasOnlineDate > serverToday) {\n // up to 6 hours ago\n if (diff.getTime() / 1000 < 6 * 60 * 60) {\n const hours = Math.floor(diff.getTime() / 1000 / 60 / 60);\n return lang('LastSeen.HoursAgo', hours);\n }\n\n // other\n return lang('LastSeen.TodayAt', formatTime(wasOnlineDate));\n }\n\n // yesterday\n const yesterday = new Date();\n yesterday.setDate(now.getDate() - 1);\n yesterday.setHours(0, 0, 0, 0);\n const serverYesterday = new Date(yesterday.getTime() + serverTimeOffset * 1000);\n if (wasOnlineDate > serverYesterday) {\n return lang('LastSeen.YesterdayAt', formatTime(wasOnlineDate));\n }\n\n return lang('LastSeen.AtDate', formatFullDate(lang, wasOnlineDate));\n }\n\n case 'userStatusOnline': {\n return lang('Online');\n }\n\n case 'userStatusRecently': {\n return lang('Lately');\n }\n\n default:\n return undefined;\n }\n}\n\nexport function isUserOnline(user: ApiUser) {\n const { id, status, type } = user;\n\n if (!status) {\n return false;\n }\n\n if (id === SERVICE_NOTIFICATIONS_USER_ID) {\n return false;\n }\n\n return status.type === 'userStatusOnline' && type !== 'userTypeBot';\n}\n\nexport function isDeletedUser(user: ApiUser) {\n if (!user.status || user.type === 'userTypeBot' || user.id === SERVICE_NOTIFICATIONS_USER_ID) {\n return false;\n }\n\n return user.type === 'userTypeDeleted'\n || user.type === 'userTypeUnknown';\n}\n\nexport function isUserBot(user: ApiUser) {\n return user.type === 'userTypeBot';\n}\n\nexport function sortUserIds(\n userIds: number[],\n usersById: Record<number, ApiUser>,\n priorityIds?: number[],\n serverTimeOffset = 0,\n) {\n return orderBy(userIds, (id) => {\n const now = Date.now() / 1000 + serverTimeOffset;\n\n if (priorityIds && priorityIds.includes(id)) {\n // Assuming that online status expiration date can't be as far as two days from now,\n // this should place prioritized on top of the list.\n // Then we subtract index of `id` in `priorityIds` to preserve selected order\n return now + (48 * 60 * 60) - (priorityIds.length - priorityIds.indexOf(id));\n }\n\n const user = usersById[id];\n if (!user || !user.status) {\n return 0;\n }\n\n if (user.status.type === 'userStatusOnline') {\n return user.status.expires;\n } else if (user.status.type === 'userStatusOffline' && user.status.wasOnline) {\n return user.status.wasOnline;\n }\n\n switch (user.status.type) {\n case 'userStatusRecently':\n return now - 60 * 60 * 24;\n case 'userStatusLastWeek':\n return now - 60 * 60 * 24 * 7;\n case 'userStatusLastMonth':\n return now - 60 * 60 * 24 * 7 * 30;\n default:\n return 0;\n }\n }, 'desc');\n}\n\n// eslint-disable-next-line max-len\n// https://github.com/telegramdesktop/tdesktop/blob/371510cfe23b0bd226de8c076bc49248fbe40c26/Telegram/SourceFiles/data/data_peer.cpp#L53\nexport function getUserColorKey(peer: ApiUser | ApiChat | undefined) {\n const index = peer ? Math.abs(peer.id) % 7 : 0;\n\n return USER_COLOR_KEYS[index];\n}\n","import { GlobalState } from '../../global/types';\nimport { ApiChat, ApiPhoto } from '../../api/types';\n\nimport { ARCHIVED_FOLDER_ID } from '../../config';\nimport { omit } from '../../util/iteratees';\n\nexport function replaceChatListIds(\n global: GlobalState,\n type: 'active' | 'archived',\n newIds: number[] | undefined,\n): GlobalState {\n return {\n ...global,\n chats: {\n ...global.chats,\n listIds: {\n ...global.chats.listIds,\n [type]: newIds,\n },\n },\n };\n}\n\nexport function updateChatListIds(global: GlobalState, type: 'active' | 'archived', idsUpdate: number[]): GlobalState {\n const { [type]: listIds } = global.chats.listIds;\n const newIds = listIds && listIds.length\n ? idsUpdate.filter((id) => !listIds.includes(id))\n : idsUpdate;\n\n if (listIds && !newIds.length) {\n return global;\n }\n\n return replaceChatListIds(global, type, [\n ...(listIds || []),\n ...newIds,\n ]);\n}\n\nexport function replaceChats(global: GlobalState, newById: Record<number, ApiChat>): GlobalState {\n return {\n ...global,\n chats: {\n ...global.chats,\n byId: newById,\n },\n };\n}\n\n// @optimization Don't spread/unspread global for each element, do it in a batch\nfunction getUpdatedChat(\n global: GlobalState, chatId: number, chatUpdate: Partial<ApiChat>, photo?: ApiPhoto,\n): ApiChat {\n const { byId } = global.chats;\n const chat = byId[chatId];\n const shouldOmitMinInfo = chatUpdate.isMin && chat && !chat.isMin;\n const updatedChat = {\n ...chat,\n ...(shouldOmitMinInfo ? omit(chatUpdate, ['isMin', 'accessHash']) : chatUpdate),\n ...(photo && { photos: [photo, ...(chat.photos || [])] }),\n };\n\n if (!updatedChat.id || !updatedChat.type) {\n return updatedChat;\n }\n\n return updatedChat;\n}\n\nexport function updateChat(\n global: GlobalState, chatId: number, chatUpdate: Partial<ApiChat>, photo?: ApiPhoto,\n): GlobalState {\n const { byId } = global.chats;\n\n const updatedChat = getUpdatedChat(global, chatId, chatUpdate, photo);\n\n return replaceChats(global, {\n ...byId,\n [chatId]: updatedChat,\n });\n}\n\nexport function updateChats(global: GlobalState, updatedById: Record<number, ApiChat>): GlobalState {\n const updatedChats = Object.keys(updatedById).map(Number).reduce<Record<number, ApiChat>>((acc, id) => {\n const updatedChat = getUpdatedChat(global, id, updatedById[id]);\n if (updatedChat) {\n acc[id] = updatedChat;\n }\n return acc;\n }, {});\n\n global = replaceChats(global, {\n ...global.chats.byId,\n ...updatedChats,\n });\n\n return global;\n}\n\n// @optimization Allows to avoid redundant updates which cause a lot of renders\nexport function addChats(global: GlobalState, addedById: Record<number, ApiChat>): GlobalState {\n const { byId } = global.chats;\n let isAdded = false;\n\n const addedChats = Object.keys(addedById).map(Number).reduce<Record<number, ApiChat>>((acc, id) => {\n if (!byId[id] || (byId[id].isMin && !addedById[id].isMin)) {\n const updatedChat = getUpdatedChat(global, id, addedById[id]);\n if (updatedChat) {\n acc[id] = updatedChat;\n\n if (!isAdded) {\n isAdded = true;\n }\n }\n }\n return acc;\n }, {});\n\n if (isAdded) {\n global = replaceChats(global, {\n ...global.chats.byId,\n ...addedChats,\n });\n }\n\n return global;\n}\n\nexport function updateChatListType(\n global: GlobalState,\n chatId: number,\n folderId?: number,\n): GlobalState {\n const listType = folderId === ARCHIVED_FOLDER_ID ? 'archived' : 'active';\n\n let currentListIds = global.chats.listIds;\n (Object.keys(currentListIds) as Array<keyof typeof currentListIds>).forEach((listTypeKey) => {\n const currentFolderList = currentListIds[listTypeKey] || [];\n if (listTypeKey === listType && !currentFolderList.includes(chatId)) {\n currentListIds = {\n ...currentListIds,\n [listTypeKey]: [...currentFolderList, chatId],\n };\n } else if (listTypeKey !== listType && currentFolderList.includes(chatId)) {\n currentListIds = {\n ...currentListIds,\n [listTypeKey]: currentFolderList.filter((id) => id !== chatId),\n };\n }\n });\n\n global = {\n ...global,\n chats: {\n ...global.chats,\n listIds: currentListIds,\n },\n };\n\n global = updateChat(global, chatId, { folderId: folderId || undefined });\n\n return global;\n}\n\nexport function updateChatListSecondaryInfo(\n global: GlobalState,\n type: 'active' | 'archived',\n info: {\n orderedPinnedIds?: number[];\n totalChatCount: number;\n },\n): GlobalState {\n const totalCountKey = type === 'active' ? 'all' : 'archived';\n\n return {\n ...global,\n chats: {\n ...global.chats,\n ...(info.orderedPinnedIds && {\n orderedPinnedIds: {\n ...global.chats.orderedPinnedIds,\n [type]: info.orderedPinnedIds,\n },\n }),\n totalCount: {\n ...global.chats.totalCount,\n [totalCountKey]: info.totalChatCount,\n },\n isFullyLoaded: {\n ...global.chats.isFullyLoaded,\n [type]: false,\n },\n },\n };\n}\n","import {\n GlobalState, MessageList, MessageListType, Thread,\n} from '../../global/types';\nimport { ApiMessage, ApiThreadInfo, MAIN_THREAD_ID } from '../../api/types';\nimport { FocusDirection } from '../../types';\n\nimport { IS_TEST, MESSAGE_LIST_SLICE, MESSAGE_LIST_VIEWPORT_LIMIT } from '../../config';\nimport {\n selectListedIds,\n selectChatMessages,\n selectViewportIds,\n selectOutlyingIds,\n selectPinnedIds,\n selectThreadInfo,\n selectMessageIdsByGroupId,\n selectScheduledMessages,\n selectScheduledIds,\n selectCurrentMessageIds,\n selectChatMessage,\n selectCurrentMessageList,\n} from '../selectors';\nimport {\n areSortedArraysEqual, omit, pickTruthy, unique,\n} from '../../util/iteratees';\n\nconst TMP_CHAT_ID = -1;\n\ntype MessageStoreSections = {\n byId: Record<number, ApiMessage>;\n threadsById: Record<number, Thread>;\n};\n\nexport function updateCurrentMessageList(\n global: GlobalState,\n chatId: number | undefined,\n threadId: number = MAIN_THREAD_ID,\n type: MessageListType = 'thread',\n shouldReplaceHistory?: boolean,\n): GlobalState {\n const { messageLists } = global.messages;\n let newMessageLists: MessageList[] = messageLists;\n if (shouldReplaceHistory || IS_TEST) {\n newMessageLists = chatId ? [{ chatId, threadId, type }] : [];\n } else if (chatId) {\n const last = messageLists[messageLists.length - 1];\n if (!last || last.chatId !== chatId || last.threadId !== threadId || last.type !== type) {\n if (last && last.chatId === TMP_CHAT_ID) {\n newMessageLists = [...messageLists.slice(0, -1), { chatId, threadId, type }];\n } else {\n newMessageLists = [...messageLists, { chatId, threadId, type }];\n }\n }\n } else {\n newMessageLists = messageLists.slice(0, -1);\n }\n\n return {\n ...global,\n messages: {\n ...global.messages,\n messageLists: newMessageLists,\n },\n };\n}\n\nfunction replaceChatMessages(global: GlobalState, chatId: number, newById: Record<number, ApiMessage>): GlobalState {\n return updateMessageStore(global, chatId, {\n byId: newById,\n });\n}\n\nfunction updateThread(\n global: GlobalState, chatId: number, threadId: number, threadUpdate: Partial<Thread>,\n): GlobalState {\n const current = global.messages.byChatId[chatId];\n\n return updateMessageStore(global, chatId, {\n threadsById: {\n ...(current && current.threadsById),\n [threadId]: {\n ...(current && current.threadsById[threadId]),\n ...threadUpdate,\n },\n },\n });\n}\n\nfunction updateMessageStore(\n global: GlobalState, chatId: number, update: Partial<MessageStoreSections>,\n): GlobalState {\n const current = global.messages.byChatId[chatId] || { byId: {}, threadsById: {} };\n\n return {\n ...global,\n messages: {\n ...global.messages,\n byChatId: {\n ...global.messages.byChatId,\n [chatId]: {\n ...current,\n ...update,\n },\n },\n },\n };\n}\n\nexport function replaceThreadParam<T extends keyof Thread>(\n global: GlobalState, chatId: number, threadId: number, paramName: T, newValue: Thread[T] | undefined,\n) {\n return updateThread(global, chatId, threadId, { [paramName]: newValue });\n}\n\nexport function addMessages(\n global: GlobalState, messages: ApiMessage[],\n): GlobalState {\n const addedByChatId = messages.reduce((messagesByChatId, message: ApiMessage) => {\n if (!messagesByChatId[message.chatId]) {\n messagesByChatId[message.chatId] = {};\n }\n messagesByChatId[message.chatId][message.id] = message;\n\n return messagesByChatId;\n }, {} as Record<number, Record<number, ApiMessage>>);\n\n Object.keys(addedByChatId).map(Number).forEach((chatId) => {\n global = addChatMessagesById(global, chatId, addedByChatId[chatId]);\n });\n\n return global;\n}\n\nexport function addChatMessagesById(\n global: GlobalState, chatId: number, newById: Record<number, ApiMessage>,\n): GlobalState {\n const byId = selectChatMessages(global, chatId);\n\n if (byId && Object.keys(newById).every((newId) => Boolean(byId[Number(newId)]))) {\n return global;\n }\n\n return replaceChatMessages(global, chatId, {\n ...newById,\n ...byId,\n });\n}\n\nexport function updateChatMessage(\n global: GlobalState, chatId: number, messageId: number, messageUpdate: Partial<ApiMessage>,\n): GlobalState {\n const byId = selectChatMessages(global, chatId) || {};\n const message = byId[messageId];\n const updatedMessage = {\n ...message,\n ...messageUpdate,\n };\n\n if (!updatedMessage.id) {\n return global;\n }\n\n return replaceChatMessages(global, chatId, {\n ...byId,\n [messageId]: updatedMessage,\n });\n}\n\nexport function updateScheduledMessage(\n global: GlobalState, chatId: number, messageId: number, messageUpdate: Partial<ApiMessage>,\n): GlobalState {\n const byId = selectScheduledMessages(global, chatId) || {};\n const message = byId[messageId];\n const updatedMessage = {\n ...message,\n ...messageUpdate,\n };\n\n if (!updatedMessage.id) {\n return global;\n }\n\n return replaceScheduledMessages(global, chatId, {\n ...byId,\n [messageId]: updatedMessage,\n }, undefined);\n}\n\nexport function deleteChatMessages(\n global: GlobalState,\n chatId: number,\n messageIds: number[],\n): GlobalState {\n const byId = selectChatMessages(global, chatId);\n if (!byId) {\n return global;\n }\n const newById = omit(byId, messageIds);\n const deletedForwardedPosts = Object.values(pickTruthy(byId, messageIds)).filter(\n ({ forwardInfo }) => forwardInfo && forwardInfo.isLinkedChannelPost,\n );\n\n const threadIds = Object.keys(global.messages.byChatId[chatId].threadsById).map(Number);\n threadIds.forEach((threadId) => {\n const threadInfo = selectThreadInfo(global, chatId, threadId);\n\n let listedIds = selectListedIds(global, chatId, threadId);\n let outlyingIds = selectOutlyingIds(global, chatId, threadId);\n let viewportIds = selectViewportIds(global, chatId, threadId);\n let pinnedIds = selectPinnedIds(global, chatId);\n let newMessageCount = threadInfo ? threadInfo.messagesCount : undefined;\n\n messageIds.forEach((messageId) => {\n if (listedIds && listedIds.includes(messageId)) {\n listedIds = listedIds.filter((id) => id !== messageId);\n if (newMessageCount !== undefined) newMessageCount -= 1;\n }\n\n if (outlyingIds && outlyingIds.includes(messageId)) {\n outlyingIds = outlyingIds.filter((id) => id !== messageId);\n }\n\n if (viewportIds && viewportIds.includes(messageId)) {\n viewportIds = viewportIds.filter((id) => id !== messageId);\n }\n\n if (pinnedIds && pinnedIds.includes(messageId)) {\n pinnedIds = pinnedIds.filter((id) => id !== messageId);\n }\n });\n\n global = replaceThreadParam(global, chatId, threadId, 'listedIds', listedIds);\n global = replaceThreadParam(global, chatId, threadId, 'outlyingIds', outlyingIds);\n global = replaceThreadParam(global, chatId, threadId, 'viewportIds', viewportIds);\n global = replaceThreadParam(global, chatId, threadId, 'pinnedIds', pinnedIds);\n\n if (threadInfo && newMessageCount !== undefined) {\n global = replaceThreadParam(global, chatId, threadId, 'threadInfo', {\n ...threadInfo,\n messagesCount: newMessageCount,\n });\n }\n });\n\n if (deletedForwardedPosts.length) {\n const currentMessageList = selectCurrentMessageList(global);\n const canDeleteCurrentThread = currentMessageList && currentMessageList.chatId === chatId\n && currentMessageList.type === 'thread';\n const currentThreadId = currentMessageList && currentMessageList.threadId;\n\n deletedForwardedPosts.forEach((message) => {\n const { fromChatId, fromMessageId } = message.forwardInfo!;\n const originalPost = selectChatMessage(global, fromChatId!, fromMessageId!);\n\n if (canDeleteCurrentThread && currentThreadId === fromMessageId) {\n global = updateCurrentMessageList(global, chatId);\n }\n if (originalPost) {\n global = updateChatMessage(global, fromChatId!, fromMessageId!, { threadInfo: undefined });\n }\n });\n }\n\n global = replaceChatMessages(global, chatId, newById);\n\n return global;\n}\n\nexport function deleteChatScheduledMessages(\n global: GlobalState,\n chatId: number,\n messageIds: number[],\n): GlobalState {\n const byId = selectScheduledMessages(global, chatId);\n if (!byId) {\n return global;\n }\n const newById = omit(byId, messageIds);\n\n let scheduledIds = selectScheduledIds(global, chatId);\n if (scheduledIds) {\n messageIds.forEach((messageId) => {\n if (scheduledIds!.includes(messageId)) {\n scheduledIds = scheduledIds!.filter((id) => id !== messageId);\n }\n });\n global = replaceThreadParam(global, chatId, MAIN_THREAD_ID, 'scheduledIds', scheduledIds);\n }\n\n global = replaceScheduledMessages(global, chatId, newById, undefined);\n\n return global;\n}\n\nexport function updateListedIds(\n global: GlobalState,\n chatId: number,\n threadId: number,\n idsUpdate: number[],\n): GlobalState {\n const listedIds = selectListedIds(global, chatId, threadId);\n const newIds = listedIds && listedIds.length\n ? idsUpdate.filter((id) => !listedIds.includes(id))\n : idsUpdate;\n\n if (listedIds && !newIds.length) {\n return global;\n }\n\n return replaceThreadParam(global, chatId, threadId, 'listedIds', orderHistoryIds([\n ...(listedIds || []),\n ...newIds,\n ]));\n}\n\nexport function updateOutlyingIds(\n global: GlobalState,\n chatId: number,\n threadId: number,\n idsUpdate: number[],\n): GlobalState {\n const outlyingIds = selectOutlyingIds(global, chatId, threadId);\n const newIds = outlyingIds && outlyingIds.length\n ? idsUpdate.filter((id) => !outlyingIds.includes(id))\n : idsUpdate;\n\n if (outlyingIds && !newIds.length) {\n return global;\n }\n\n return replaceThreadParam(global, chatId, threadId, 'outlyingIds', orderHistoryIds([\n ...(outlyingIds || []),\n ...newIds,\n ]));\n}\n\nfunction orderHistoryIds(listedIds: number[]) {\n return listedIds.sort((a, b) => a - b);\n}\n\nexport function addViewportId(\n global: GlobalState,\n chatId: number,\n threadId: number,\n newId: number,\n): GlobalState {\n const viewportIds = selectViewportIds(global, chatId, threadId) || [];\n if (viewportIds.includes(newId)) {\n return global;\n }\n\n const newIds = orderHistoryIds([\n ...(\n viewportIds.length < MESSAGE_LIST_VIEWPORT_LIMIT\n ? viewportIds\n : viewportIds.slice(-(MESSAGE_LIST_SLICE / 2))\n ),\n newId,\n ]);\n\n return replaceThreadParam(global, chatId, threadId, 'viewportIds', newIds);\n}\n\nexport function safeReplaceViewportIds(\n global: GlobalState,\n chatId: number,\n threadId: number,\n newViewportIds: number[],\n): GlobalState {\n const viewportIds = selectViewportIds(global, chatId, threadId) || [];\n\n return replaceThreadParam(\n global,\n chatId,\n threadId,\n 'viewportIds',\n areSortedArraysEqual(viewportIds, newViewportIds) ? viewportIds : newViewportIds,\n );\n}\n\nexport function updateThreadInfo(\n global: GlobalState, chatId: number, threadId: number, update: Partial<ApiThreadInfo> | undefined,\n): GlobalState {\n const newThreadInfo = {\n ...(selectThreadInfo(global, chatId, threadId) as ApiThreadInfo),\n ...update,\n };\n\n if (!newThreadInfo.threadId) {\n return global;\n }\n\n return replaceThreadParam(global, chatId, threadId, 'threadInfo', newThreadInfo);\n}\n\nexport function updateThreadInfos(\n global: GlobalState, chatId: number, updates: Partial<ApiThreadInfo>[],\n): GlobalState {\n updates.forEach((update) => {\n global = updateThreadInfo(global, update.chatId!, update.threadId!, update);\n });\n\n return global;\n}\n\nexport function replaceScheduledMessages(\n global: GlobalState, chatId: number, newById: Record<number, ApiMessage>, hash: number | undefined,\n): GlobalState {\n return updateScheduledMessages(global, chatId, {\n byId: newById,\n hash,\n });\n}\n\nfunction updateScheduledMessages(\n global: GlobalState, chatId: number, update: Partial<{ byId: Record<number, ApiMessage>; hash: number }>,\n): GlobalState {\n const current = global.scheduledMessages.byChatId[chatId] || { byId: {}, hash: 0 };\n\n return {\n ...global,\n scheduledMessages: {\n byChatId: {\n ...global.scheduledMessages.byChatId,\n [chatId]: {\n ...current,\n ...update,\n },\n },\n },\n };\n}\n\nexport function updateFocusedMessage(\n global: GlobalState, chatId?: number, messageId?: number, noHighlight = false, isResizingContainer = false,\n): GlobalState {\n return {\n ...global,\n focusedMessage: {\n ...global.focusedMessage,\n chatId,\n messageId,\n noHighlight,\n isResizingContainer,\n },\n };\n}\n\nexport function updateFocusDirection(\n global: GlobalState, direction?: FocusDirection,\n): GlobalState {\n return {\n ...global,\n focusedMessage: {\n ...global.focusedMessage,\n direction,\n },\n };\n}\n\nexport function enterMessageSelectMode(\n global: GlobalState,\n chatId: number,\n messageId?: number | number[],\n): GlobalState {\n const messageIds = messageId ? Array.prototype.concat([], messageId) : [];\n return {\n ...global,\n selectedMessages: {\n chatId,\n messageIds,\n },\n };\n}\n\nexport function toggleMessageSelection(\n global: GlobalState,\n chatId: number,\n threadId: number,\n messageListType: MessageListType,\n messageId: number,\n groupedId?: string,\n childMessageIds?: number[],\n withShift = false,\n): GlobalState {\n const { selectedMessages: oldSelectedMessages } = global;\n if (groupedId) {\n childMessageIds = selectMessageIdsByGroupId(global, chatId, groupedId);\n }\n const selectedMessageIds = childMessageIds || [messageId];\n if (!oldSelectedMessages) {\n return enterMessageSelectMode(global, chatId, selectedMessageIds);\n }\n\n const { messageIds } = oldSelectedMessages;\n\n let newMessageIds;\n const newSelectedMessageIds = selectedMessageIds.filter((id) => !messageIds.includes(id));\n if (newSelectedMessageIds && !newSelectedMessageIds.length) {\n newMessageIds = messageIds.filter((id) => !selectedMessageIds.includes(id));\n } else if (withShift && messageIds.length) {\n const viewportIds = selectCurrentMessageIds(global, chatId, threadId, messageListType)!;\n const prevIndex = viewportIds.indexOf(messageIds[messageIds.length - 1]);\n const currentIndex = viewportIds.indexOf(messageId);\n const from = Math.min(prevIndex, currentIndex);\n const to = Math.max(prevIndex, currentIndex);\n const slice = viewportIds.slice(from, to + 1);\n newMessageIds = unique([...messageIds, ...slice]);\n } else {\n newMessageIds = [...messageIds, ...newSelectedMessageIds];\n }\n\n if (!newMessageIds.length) {\n return exitMessageSelectMode(global);\n }\n\n return {\n ...global,\n selectedMessages: {\n ...oldSelectedMessages,\n messageIds: newMessageIds,\n },\n };\n}\n\nexport function exitMessageSelectMode(global: GlobalState): GlobalState {\n return {\n ...global,\n selectedMessages: undefined,\n };\n}\n","import { GlobalState } from '../../global/types';\nimport { ApiSticker, ApiStickerSet, ApiVideo } from '../../api/types';\nimport { buildCollectionByKey, unique } from '../../util/iteratees';\nimport { selectStickersForEmoji } from '../selectors';\n\nexport function updateStickerSets(\n global: GlobalState,\n category: 'added' | 'featured' | 'search',\n hash: number,\n sets: ApiStickerSet[],\n resultIds?: string[],\n): GlobalState {\n const updatedSets = sets.map((stickerSet) => {\n const existing = global.stickers.setsById[stickerSet.id];\n if (!existing) {\n return stickerSet;\n }\n\n return {\n ...existing,\n ...stickerSet,\n };\n });\n\n return {\n ...global,\n stickers: {\n ...global.stickers,\n setsById: {\n ...global.stickers.setsById,\n ...buildCollectionByKey(updatedSets, 'id'),\n },\n [category]: {\n ...global.stickers[category],\n hash,\n ...(\n category === 'search'\n ? { resultIds }\n : { setIds: sets.map(({ id }) => id) }\n ),\n },\n },\n };\n}\n\nexport function updateStickerSet(\n global: GlobalState, stickerSetId: string, update: Partial<ApiStickerSet>,\n): GlobalState {\n const currentStickerSet = global.stickers.setsById[stickerSetId] || {};\n\n return {\n ...global,\n stickers: {\n ...global.stickers,\n setsById: {\n ...global.stickers.setsById,\n [stickerSetId]: {\n ...currentStickerSet,\n ...update,\n },\n },\n },\n };\n}\n\nexport function updateGifSearch(\n global: GlobalState, isNew: boolean, results: ApiVideo[], nextOffset?: string,\n): GlobalState {\n const { results: currentResults } = global.gifs.search;\n\n let newResults!: ApiVideo[];\n if (isNew || !currentResults) {\n newResults = results;\n } else {\n const currentIds = new Set(currentResults.map((gif) => gif.id));\n newResults = [\n ...currentResults,\n ...results.filter((gif) => !currentIds.has(gif.id)),\n ];\n }\n\n return {\n ...global,\n gifs: {\n ...global.gifs,\n search: {\n ...global.gifs.search,\n offset: nextOffset,\n results: newResults,\n },\n },\n };\n}\n\nexport function replaceAnimatedEmojis(global: GlobalState, stickerSet: ApiStickerSet): GlobalState {\n return {\n ...global,\n animatedEmojis: stickerSet,\n };\n}\n\nexport function updateStickersForEmoji(\n global: GlobalState, emoji: string, remoteStickers?: ApiSticker[], hash?: number,\n): GlobalState {\n const localStickers = selectStickersForEmoji(global, emoji);\n const allStickers = [...localStickers, ...(remoteStickers || [])];\n const uniqueIds = unique(allStickers.map(({ id }) => id));\n const byId = buildCollectionByKey(allStickers, 'id');\n const stickers = uniqueIds.map((id) => byId[id]);\n\n return {\n ...global,\n stickers: {\n ...global.stickers,\n forEmoji: {\n emoji,\n stickers,\n hash,\n },\n },\n };\n}\n\nexport function rebuildStickersForEmoji(global: GlobalState): GlobalState {\n const { emoji, stickers, hash } = global.stickers.forEmoji || {};\n if (!emoji) {\n return global;\n }\n\n return updateStickersForEmoji(global, emoji, stickers, hash);\n}\n","import { GlobalState } from '../../global/types';\nimport { ApiUser } from '../../api/types';\n\nimport { omit } from '../../util/iteratees';\nimport { MEMO_EMPTY_ARRAY } from '../../util/memo';\n\nexport function replaceUsers(global: GlobalState, newById: Record<number, ApiUser>): GlobalState {\n return {\n ...global,\n users: {\n ...global.users,\n byId: newById,\n },\n };\n}\n\n// @optimization Don't spread/unspread global for each element, do it in a batch\nfunction getUpdatedUser(global: GlobalState, userId: number, userUpdate: Partial<ApiUser>): ApiUser {\n const { byId } = global.users;\n const user = byId[userId];\n const shouldOmitMinInfo = userUpdate.isMin && user && !user.isMin;\n\n const updatedUser = {\n ...user,\n ...(shouldOmitMinInfo ? omit(userUpdate, ['isMin', 'accessHash']) : userUpdate),\n };\n\n if (!updatedUser.id || !updatedUser.type) {\n return user;\n }\n\n return updatedUser;\n}\n\nfunction updateContactList(global: GlobalState, updatedUsers: ApiUser[]): GlobalState {\n const { hash, userIds: contactUserIds } = global.contactList || {};\n\n if (!contactUserIds) return global;\n\n const newContactUserIds = updatedUsers\n .filter((user) => user && user.isContact && !contactUserIds.includes(user.id))\n .map((user) => user.id);\n\n if (newContactUserIds.length === 0) return global;\n\n return {\n ...global,\n contactList: {\n hash: hash || 0,\n userIds: [\n ...newContactUserIds,\n ...contactUserIds,\n ],\n },\n };\n}\n\nexport function updateUser(global: GlobalState, userId: number, userUpdate: Partial<ApiUser>): GlobalState {\n const { byId } = global.users;\n\n const updatedUser = getUpdatedUser(global, userId, userUpdate);\n\n global = updateContactList(global, [updatedUser]);\n\n return replaceUsers(global, {\n ...byId,\n [userId]: updatedUser,\n });\n}\n\nexport function updateUsers(global: GlobalState, updatedById: Record<number, ApiUser>): GlobalState {\n const updatedUsers = Object.keys(updatedById).map(Number).reduce<Record<number, ApiUser>>((acc, id) => {\n const updatedUser = getUpdatedUser(global, id, updatedById[id]);\n if (updatedUser) {\n acc[id] = updatedUser;\n }\n return acc;\n }, {});\n\n global = updateContactList(global, Object.values(updatedUsers));\n\n global = replaceUsers(global, {\n ...global.users.byId,\n ...updatedUsers,\n });\n\n return global;\n}\n\n// @optimization Allows to avoid redundant updates which cause a lot of renders\nexport function addUsers(global: GlobalState, addedById: Record<number, ApiUser>): GlobalState {\n const { byId } = global.users;\n let isAdded = false;\n\n const addedUsers = Object.keys(addedById).map(Number).reduce<Record<number, ApiUser>>((acc, id) => {\n if (!byId[id] || (byId[id].isMin && !addedById[id].isMin)) {\n const updatedUser = getUpdatedUser(global, id, addedById[id]);\n if (updatedUser) {\n acc[id] = updatedUser;\n\n if (!isAdded) {\n isAdded = true;\n }\n }\n }\n return acc;\n }, {});\n\n if (isAdded) {\n global = replaceUsers(global, {\n ...global.users.byId,\n ...addedUsers,\n });\n\n global = updateContactList(global, Object.values(addedUsers));\n }\n\n return global;\n}\n\nexport function updateSelectedUserId(global: GlobalState, selectedId?: number): GlobalState {\n if (global.users.selectedId === selectedId) {\n return global;\n }\n\n return {\n ...global,\n users: {\n ...global.users,\n selectedId,\n },\n };\n}\n\nexport function deleteUser(global: GlobalState, userId: number): GlobalState {\n const { byId } = global.users;\n const { hash, userIds } = global.contactList || {};\n delete byId[userId];\n\n global = {\n ...global,\n contactList: {\n hash: hash || 0,\n userIds: userIds ? userIds.filter((id) => id !== userId) : MEMO_EMPTY_ARRAY,\n },\n };\n\n return replaceUsers(global, byId);\n}\n\nexport function updateUserSearch(\n global: GlobalState,\n searchStatePartial: Partial<GlobalState['userSearch']>,\n) {\n return {\n ...global,\n userSearch: {\n ...global.userSearch,\n ...searchStatePartial,\n },\n };\n}\n\nexport function updateUserSearchFetchingStatus(\n global: GlobalState, newState: boolean,\n) {\n return updateUserSearch(global, {\n fetchingStatus: newState,\n });\n}\n\nexport function updateUserBlockedState(global: GlobalState, userId: number, isBlocked: boolean) {\n const { byId } = global.users;\n const user = byId[userId];\n if (!user || !user.fullInfo) {\n return global;\n }\n\n return updateUser(global, userId, {\n ...user,\n fullInfo: {\n ...user.fullInfo,\n isBlocked,\n },\n });\n}\n","import { GlobalState } from '../../global/types';\nimport { GlobalSearchContent } from '../../types';\nimport { ApiGlobalMessageSearchType, ApiMessage } from '../../api/types';\nimport { areSortedArraysEqual } from '../../util/iteratees';\n\nconst getComplexKey = (message: ApiMessage) => `${message.chatId}_${message.id}`;\n\nexport function updateGlobalSearch(\n global: GlobalState,\n searchStatePartial: Partial<GlobalState['globalSearch']>,\n) {\n return {\n ...global,\n globalSearch: {\n ...global.globalSearch,\n ...searchStatePartial,\n },\n };\n}\n\nexport function updateGlobalSearchContent(\n global: GlobalState,\n currentContent: GlobalSearchContent | undefined,\n): GlobalState {\n return updateGlobalSearch(global, { currentContent });\n}\n\nexport function updateGlobalSearchResults(\n global: GlobalState,\n newFoundMessages: ApiMessage[],\n totalCount: number,\n type: ApiGlobalMessageSearchType,\n nextRate?: number,\n): GlobalState {\n const { resultsByType } = global.globalSearch || {};\n const newFoundMessagesById = newFoundMessages.reduce((result, message) => {\n result[getComplexKey(message)] = message;\n\n return result;\n }, {} as Record<string, ApiMessage>);\n const foundIdsForType = resultsByType && resultsByType[type] ? resultsByType[type]!.foundIds : undefined;\n\n if (foundIdsForType !== undefined\n && Object.keys(newFoundMessagesById).every(\n (newId) => foundIdsForType.includes(getComplexKey(newFoundMessagesById[newId])),\n )\n ) {\n return updateGlobalSearchFetchingStatus(global, { messages: false });\n }\n\n const prevFoundIds = foundIdsForType || [];\n const newFoundIds = newFoundMessages.map((message) => getComplexKey(message));\n const foundIds = Array.prototype.concat(prevFoundIds, newFoundIds);\n const foundOrPrevFoundIds = areSortedArraysEqual(prevFoundIds, foundIds) ? prevFoundIds : foundIds;\n\n global = updateGlobalSearchFetchingStatus(global, { messages: false });\n\n return updateGlobalSearch(global, {\n resultsByType: {\n ...(global.globalSearch || {}).resultsByType,\n [type]: {\n totalCount,\n nextOffsetId: nextRate,\n foundIds: foundOrPrevFoundIds,\n },\n },\n });\n}\n\nexport function updateGlobalSearchFetchingStatus(\n global: GlobalState, newState: { chats?: boolean; messages?: boolean },\n) {\n return updateGlobalSearch(global, {\n fetchingStatus: {\n ...global.globalSearch.fetchingStatus,\n ...newState,\n },\n });\n}\n","import { GlobalState } from '../../global/types';\nimport { ApiMessageSearchType } from '../../api/types';\n\nimport { areSortedArraysEqual, unique } from '../../util/iteratees';\nimport { SharedMediaType } from '../../types';\nimport { buildChatThreadKey } from '../helpers';\n\ninterface TextSearchParams {\n isActive: boolean;\n query?: string;\n results?: {\n totalCount?: number;\n nextOffsetId?: number;\n foundIds?: number[];\n };\n}\n\ninterface MediaSearchParams {\n currentType?: SharedMediaType;\n resultsByType?: Partial<Record<SharedMediaType, {\n totalCount?: number;\n nextOffsetId: number;\n foundIds: number[];\n }>>;\n}\n\nfunction replaceLocalTextSearch(\n global: GlobalState,\n chatThreadKey: string,\n searchParams: TextSearchParams,\n): GlobalState {\n return {\n ...global,\n localTextSearch: {\n byChatThreadKey: {\n ...global.localTextSearch.byChatThreadKey,\n [chatThreadKey]: searchParams,\n },\n },\n };\n}\n\nexport function updateLocalTextSearch(\n global: GlobalState,\n chatId: number,\n threadId: number,\n isActive: boolean,\n query?: string,\n): GlobalState {\n const chatThreadKey = buildChatThreadKey(chatId, threadId);\n\n return replaceLocalTextSearch(global, chatThreadKey, {\n ...global.localTextSearch.byChatThreadKey[chatThreadKey],\n isActive,\n query,\n });\n}\n\nexport function replaceLocalTextSearchResults(\n global: GlobalState,\n chatId: number,\n threadId: number,\n foundIds?: number[],\n totalCount?: number,\n nextOffsetId?: number,\n): GlobalState {\n const chatThreadKey = buildChatThreadKey(chatId, threadId);\n\n return replaceLocalTextSearch(global, chatThreadKey, {\n ...global.localTextSearch.byChatThreadKey[chatThreadKey],\n results: {\n foundIds,\n totalCount,\n nextOffsetId,\n },\n });\n}\n\nexport function updateLocalTextSearchResults(\n global: GlobalState,\n chatId: number,\n threadId: number,\n newFoundIds: number[],\n totalCount?: number,\n nextOffsetId?: number,\n): GlobalState {\n const chatThreadKey = buildChatThreadKey(chatId, threadId);\n const { results } = global.localTextSearch.byChatThreadKey[chatThreadKey] || {};\n const prevFoundIds = (results && results.foundIds) || [];\n const foundIds = orderFoundIds(unique(Array.prototype.concat(prevFoundIds, newFoundIds)));\n const foundOrPrevFoundIds = areSortedArraysEqual(prevFoundIds, foundIds) ? prevFoundIds : foundIds;\n\n return replaceLocalTextSearchResults(global, chatId, threadId, foundOrPrevFoundIds, totalCount, nextOffsetId);\n}\n\nfunction replaceLocalMediaSearch(\n global: GlobalState,\n chatId: number,\n searchParams: MediaSearchParams,\n): GlobalState {\n return {\n ...global,\n localMediaSearch: {\n byChatId: {\n ...global.localMediaSearch.byChatId,\n [chatId]: searchParams,\n },\n },\n };\n}\n\nexport function updateLocalMediaSearchType(\n global: GlobalState,\n chatId: number,\n currentType: SharedMediaType | undefined,\n): GlobalState {\n return replaceLocalMediaSearch(global, chatId, {\n ...global.localMediaSearch.byChatId[chatId],\n currentType,\n });\n}\n\nexport function replaceLocalMediaSearchResults(\n global: GlobalState,\n chatId: number,\n type: ApiMessageSearchType,\n foundIds?: number[],\n totalCount?: number,\n nextOffsetId?: number,\n): GlobalState {\n return replaceLocalMediaSearch(global, chatId, {\n ...global.localMediaSearch.byChatId[chatId],\n resultsByType: {\n ...(global.localMediaSearch.byChatId[chatId] || {}).resultsByType,\n [type]: {\n foundIds,\n totalCount,\n nextOffsetId,\n },\n },\n });\n}\n\nexport function updateLocalMediaSearchResults(\n global: GlobalState,\n chatId: number,\n type: SharedMediaType,\n newFoundIds: number[],\n totalCount?: number,\n nextOffsetId?: number,\n): GlobalState {\n const { resultsByType } = global.localMediaSearch.byChatId[chatId] || {};\n const prevFoundIds = resultsByType && resultsByType[type] ? resultsByType[type]!.foundIds : [];\n const foundIds = orderFoundIds(unique(Array.prototype.concat(prevFoundIds, newFoundIds)));\n const foundOrPrevFoundIds = areSortedArraysEqual(prevFoundIds, foundIds) ? prevFoundIds : foundIds;\n\n return replaceLocalMediaSearchResults(global, chatId, type, foundOrPrevFoundIds, totalCount, nextOffsetId);\n}\n\nfunction orderFoundIds(listedIds: number[]) {\n return listedIds.sort((a, b) => a - b);\n}\n","import { GlobalState } from '../../global/types';\nimport { ManagementProgress } from '../../types';\n\ninterface ManagementState {\n isActive: boolean;\n isUsernameAvailable?: boolean;\n error?: string;\n}\n\nexport function updateManagementProgress(global: GlobalState, progress: ManagementProgress): GlobalState {\n return {\n ...global,\n management: {\n ...global.management,\n progress,\n },\n };\n}\n\nexport function updateManagement(global: GlobalState, chatId: number, update: Partial<ManagementState>): GlobalState {\n return {\n ...global,\n management: {\n ...global.management,\n byChatId: {\n ...global.management.byChatId,\n [chatId]: {\n ...(global.management.byChatId[chatId] || {}),\n ...update,\n },\n },\n },\n };\n}\n","import { GlobalState } from '../../global/types';\nimport {\n ISettings, IThemeSettings, ThemeKey, NotifyException,\n} from '../../types';\nimport { ApiNotifyException } from '../../api/types';\nimport { updateUserBlockedState } from './users';\n\nexport function replaceSettings(global: GlobalState, newSettings?: Partial<ISettings>): GlobalState {\n return {\n ...global,\n settings: {\n ...global.settings,\n byKey: {\n ...global.settings.byKey,\n ...newSettings,\n },\n },\n };\n}\n\nexport function replaceThemeSettings(\n global: GlobalState, theme: ThemeKey, newSettings?: Partial<IThemeSettings>,\n): GlobalState {\n return {\n ...global,\n settings: {\n ...global.settings,\n themes: {\n ...global.settings.themes,\n [theme]: {\n ...(global.settings.themes[theme] || {}),\n ...newSettings,\n },\n },\n },\n };\n}\n\nexport function addNotifyExceptions(\n global: GlobalState, notifyExceptions: ApiNotifyException[],\n): GlobalState {\n notifyExceptions.forEach((notifyException) => {\n const { chatId, ...exceptionData } = notifyException;\n global = addNotifyException(global, chatId, exceptionData);\n });\n\n return global;\n}\n\nexport function addNotifyException(\n global: GlobalState, id: number, notifyException: NotifyException,\n): GlobalState {\n return {\n ...global,\n settings: {\n ...global.settings,\n notifyExceptions: {\n ...global.settings.notifyExceptions,\n [id]: notifyException,\n },\n },\n };\n}\n\nexport function updateNotifySettings(\n global: GlobalState, peerType: 'contact' | 'group' | 'broadcast', isSilent?: boolean, shouldShowPreviews?: boolean,\n) {\n switch (peerType) {\n case 'contact':\n return replaceSettings(global, {\n ...(typeof isSilent !== 'undefined' && { hasPrivateChatsNotifications: !isSilent }),\n ...(typeof shouldShowPreviews !== 'undefined' && { hasPrivateChatsMessagePreview: shouldShowPreviews }),\n });\n case 'group':\n return replaceSettings(global, {\n ...(typeof isSilent !== 'undefined' && { hasGroupNotifications: !isSilent }),\n ...(typeof shouldShowPreviews !== 'undefined' && { hasGroupMessagePreview: shouldShowPreviews }),\n });\n case 'broadcast':\n return replaceSettings(global, {\n ...(typeof isSilent !== 'undefined' && { hasBroadcastNotifications: !isSilent }),\n ...(typeof shouldShowPreviews !== 'undefined' && { hasBroadcastMessagePreview: shouldShowPreviews }),\n });\n\n default:\n return undefined;\n }\n}\n\nexport function addBlockedContact(global: GlobalState, contactId: number): GlobalState {\n global = updateUserBlockedState(global, contactId, true);\n\n return {\n ...global,\n blocked: {\n ...global.blocked,\n ids: [contactId, ...global.blocked.ids],\n totalCount: global.blocked.totalCount + 1,\n },\n };\n}\n\nexport function removeBlockedContact(global: GlobalState, contactId: number): GlobalState {\n global = updateUserBlockedState(global, contactId, false);\n\n return {\n ...global,\n blocked: {\n ...global.blocked,\n ids: global.blocked.ids.filter((id) => id !== contactId),\n totalCount: global.blocked.totalCount - 1,\n },\n };\n}\n","import { GlobalState } from '../../global/types';\n\nexport function updateTwoFaSettings(\n global: GlobalState,\n update: GlobalState['twoFaSettings'],\n): GlobalState {\n return {\n ...global,\n twoFaSettings: {\n ...global.twoFaSettings,\n ...update,\n },\n };\n}\n","import { GlobalState } from '../../global/types';\nimport { ShippingOption, PaymentStep } from '../../types';\nimport { ApiMessage, ApiPaymentForm, ApiReceipt } from '../../api/types';\n\nexport function updateShippingOptions(\n global: GlobalState,\n shippingOptions: ShippingOption[],\n): GlobalState {\n return {\n ...global,\n payment: {\n ...global.payment,\n shippingOptions,\n },\n };\n}\n\nexport function setRequestInfoId(global: GlobalState, id: string): GlobalState {\n return {\n ...global,\n payment: {\n ...global.payment,\n requestId: 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 amount,\n currency,\n isTest,\n photoUrl,\n } = message.content.invoice;\n return {\n ...global,\n payment: {\n ...global.payment,\n invoiceContent: {\n title,\n text,\n photoUrl,\n amount,\n currency,\n isTest,\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 { GlobalState } from '../../global/types';\nimport { ApiChat, ApiUser } from '../../api/types';\n\nexport function selectUser(global: GlobalState, userId: number): ApiUser | undefined {\n return global.users.byId[userId];\n}\n\nexport function selectIsUserBlocked(global: GlobalState, userId: number) {\n const user = selectUser(global, userId);\n\n return user && user.fullInfo && user.fullInfo.isBlocked;\n}\n\n// Slow, not to be used in `withGlobal`\nexport function selectUserByUsername(global: GlobalState, username: string) {\n const usernameLowered = username.toLowerCase();\n return Object.values(global.users.byId).find(\n (user) => user.username.toLowerCase() === usernameLowered,\n );\n}\n\nexport function selectIsUserOrChatContact(global: GlobalState, userOrChat: ApiUser | ApiChat) {\n return global.contactList && global.contactList.userIds.includes(userOrChat.id);\n}\n","import { GlobalState } from '../../global/types';\n\nexport function selectNotifySettings(global: GlobalState) {\n return global.settings.byKey;\n}\n\nexport function selectNotifyExceptions(global: GlobalState) {\n return global.settings.notifyExceptions;\n}\n","import { ApiChat, MAIN_THREAD_ID } from '../../api/types';\nimport { GlobalState } from '../../global/types';\n\nimport {\n getPrivateChatUserId, isChatChannel, isChatPrivate, isHistoryClearMessage, isUserBot, isUserOnline, selectIsChatMuted,\n} from '../helpers';\nimport { selectUser } from './users';\nimport { ALL_FOLDER_ID, ARCHIVED_FOLDER_ID, MEMBERS_LOAD_SLICE } from '../../config';\nimport { selectNotifyExceptions, selectNotifySettings } from './settings';\n\nexport function selectChat(global: GlobalState, chatId: number): ApiChat | undefined {\n return global.chats.byId[chatId];\n}\n\nexport function selectChatUser(global: GlobalState, chat: ApiChat) {\n const userId = getPrivateChatUserId(chat);\n if (!userId) {\n return false;\n }\n\n return selectUser(global, userId);\n}\n\nexport function selectIsChatWithSelf(global: GlobalState, chatId: number) {\n return chatId === global.currentUserId;\n}\n\nexport function selectIsChatWithBot(global: GlobalState, chat: ApiChat) {\n const user = selectChatUser(global, chat);\n return user && isUserBot(user);\n}\n\nexport function selectSupportChat(global: GlobalState) {\n return Object.values(global.chats.byId).find(({ isSupport }: ApiChat) => isSupport);\n}\n\nexport function selectChatOnlineCount(global: GlobalState, chat: ApiChat) {\n if (isChatPrivate(chat.id) || isChatChannel(chat) || !chat.fullInfo) {\n return undefined;\n }\n\n if (!chat.fullInfo.members || chat.fullInfo.members.length === MEMBERS_LOAD_SLICE) {\n return chat.fullInfo.onlineCount;\n }\n\n return chat.fullInfo.members.reduce((onlineCount, { userId }) => {\n if (global.users.byId[userId] && isUserOnline(global.users.byId[userId]) && userId !== global.currentUserId) {\n return onlineCount + 1;\n }\n\n return onlineCount;\n }, 0);\n}\n\nexport function selectChatBot(global: GlobalState, chatId: number) {\n const chat = selectChat(global, chatId);\n const userId = chat && getPrivateChatUserId(chat);\n const user = userId && selectUser(global, userId);\n if (!user || !isUserBot(user)) {\n return undefined;\n }\n\n return user;\n}\n\nexport function selectIsChatBotNotStarted(global: GlobalState, chatId: number) {\n const chat = selectChat(global, chatId);\n const bot = selectChatBot(global, chatId);\n if (!chat || !bot) {\n return false;\n }\n\n if (chat.lastMessage && isHistoryClearMessage(chat.lastMessage)) {\n return true;\n }\n\n const messageInfo = global.messages.byChatId[chatId];\n if (!messageInfo) {\n return false;\n }\n\n const { listedIds } = messageInfo.threadsById[MAIN_THREAD_ID] || {};\n return listedIds && !listedIds.length;\n}\n\nexport function selectAreActiveChatsLoaded(global: GlobalState): boolean {\n return Boolean(global.chats.listIds.active);\n}\n\nexport function selectIsChatListed(global: GlobalState, chatId: number, type?: 'active' | 'archived'): boolean {\n const { listIds } = global.chats;\n if (type) {\n const targetList = listIds[type];\n return Boolean(targetList && targetList.includes(chatId));\n }\n\n return Object.values(listIds).some((list) => list && list.includes(chatId));\n}\n\nexport function selectChatListType(global: GlobalState, chatId: number): 'active' | 'archived' | undefined {\n const chat = selectChat(global, chatId);\n if (!chat || !selectIsChatListed(global, chatId)) {\n return undefined;\n }\n\n return chat.folderId === ARCHIVED_FOLDER_ID ? 'archived' : 'active';\n}\n\nexport function selectChatFolder(global: GlobalState, folderId: number) {\n return global.chatFolders.byId[folderId];\n}\n\nexport function selectTotalChatCount(global: GlobalState, listType: 'active' | 'archived'): number {\n const { totalCount } = global.chats;\n const allChatsCount = totalCount.all;\n const archivedChatsCount = totalCount.archived || 0;\n\n if (listType === 'archived') {\n return archivedChatsCount;\n }\n\n return allChatsCount ? allChatsCount - archivedChatsCount : 0;\n}\n\nexport function selectIsChatPinned(global: GlobalState, chatId: number, folderId = ALL_FOLDER_ID): boolean {\n const { active, archived } = global.chats.orderedPinnedIds;\n\n if (folderId === ALL_FOLDER_ID) {\n return !!active && active.includes(chatId);\n }\n\n if (folderId === ARCHIVED_FOLDER_ID) {\n return !!archived && archived.includes(chatId);\n }\n\n const { byId: chatFoldersById } = global.chatFolders;\n\n const { pinnedChatIds } = chatFoldersById[folderId] || {};\n return !!pinnedChatIds && pinnedChatIds.includes(chatId);\n}\n\n// Slow, not to be used in `withGlobal`\nexport function selectChatByUsername(global: GlobalState, username: string) {\n const usernameLowered = username.toLowerCase();\n return Object.values(global.chats.byId).find(\n (chat) => chat.username && chat.username.toLowerCase() === usernameLowered,\n );\n}\n\nexport function selectCountNotMutedUnread(global: GlobalState) {\n const activeChatIds = global.chats.listIds.active;\n if (!activeChatIds) {\n return 0;\n }\n\n const chats = global.chats.byId;\n\n return activeChatIds.reduce((acc, chatId) => {\n const chat = chats[chatId];\n\n if (\n chat\n && chat.unreadCount\n && !selectIsChatMuted(chat, selectNotifySettings(global), selectNotifyExceptions(global))\n ) {\n return acc + chat.unreadCount;\n }\n\n return acc;\n }, 0);\n}\n","import { GlobalState } from '../../global/types';\nimport { ApiSticker } from '../../api/types';\n\nexport function selectIsStickerFavorite(global: GlobalState, sticker: ApiSticker) {\n const { stickers } = global.stickers.favorite;\n return stickers && stickers.some(({ id }) => id === sticker.id);\n}\n\nexport function selectCurrentStickerSearch(global: GlobalState) {\n return global.stickers.search;\n}\n\nexport function selectCurrentGifSearch(global: GlobalState) {\n return global.gifs.search;\n}\n\nexport function selectStickerSet(global: GlobalState, id: string) {\n return global.stickers.setsById[id];\n}\n\nexport function selectStickerSetByShortName(global: GlobalState, shortName: string) {\n return Object.values(global.stickers.setsById).find((l) => l.shortName.toLowerCase() === shortName.toLowerCase());\n}\n\nexport function selectStickersForEmoji(global: GlobalState, emoji: string) {\n const stickerSets = Object.values(global.stickers.setsById);\n let stickersForEmoji: ApiSticker[] = [];\n stickerSets.forEach(({ packs }) => {\n if (!packs) {\n return;\n }\n const stickers = packs[emoji];\n if (stickers) {\n stickersForEmoji = stickersForEmoji.concat(stickers);\n }\n });\n return stickersForEmoji;\n}\n\nexport function selectAnimatedEmoji(global: GlobalState, emoji: string) {\n const { animatedEmojis } = global;\n if (!animatedEmojis || !animatedEmojis.stickers) {\n return undefined;\n }\n\n // Some emojis (❤️ for example) with a service symbol 'VARIATION SELECTOR-16' are not recognized as animated\n const cleanedEmoji = emoji.replace('\\ufe0f', '');\n\n return animatedEmojis.stickers.find((sticker) => sticker.emoji === emoji || sticker.emoji === cleanedEmoji);\n}\n","import { GlobalState, MessageListType, Thread } from '../../global/types';\nimport {\n ApiChat,\n ApiMessage,\n ApiMessageOutgoingStatus,\n ApiUser,\n MAIN_THREAD_ID,\n} from '../../api/types';\n\nimport { LOCAL_MESSAGE_ID_BASE } from '../../config';\nimport {\n selectChat, selectIsChatWithBot, selectIsChatWithSelf,\n} from './chats';\nimport { selectIsUserOrChatContact, selectUser } from './users';\nimport {\n getSendingState,\n isChatChannel,\n isMessageLocal,\n isChatPrivate,\n isForwardedMessage,\n getCanPostInChat,\n isUserRightBanned,\n getHasAdminRight,\n isChatBasicGroup,\n isCommonBoxChat,\n isServiceNotificationMessage,\n isOwnMessage,\n isActionMessage,\n isChatGroup,\n isChatSuperGroup,\n getMessageVideo,\n getMessageWebPageVideo,\n} from '../helpers';\nimport { findLast } from '../../util/iteratees';\nimport { selectIsStickerFavorite } from './symbols';\n\nconst MESSAGE_EDIT_ALLOWED_TIME_MS = 172800000; // 48 hours\n\nexport function selectCurrentMessageList(global: GlobalState) {\n const { messageLists } = global.messages;\n\n if (messageLists.length) {\n return messageLists[messageLists.length - 1];\n }\n\n return undefined;\n}\n\nexport function selectCurrentChat(global: GlobalState) {\n const { chatId } = selectCurrentMessageList(global) || {};\n\n return chatId ? selectChat(global, chatId) : undefined;\n}\n\nexport function selectChatMessages(global: GlobalState, chatId: number) {\n const messages = global.messages.byChatId[chatId];\n\n return messages ? messages.byId : undefined;\n}\n\nexport function selectScheduledMessages(global: GlobalState, chatId: number) {\n const messages = global.scheduledMessages.byChatId[chatId];\n\n return messages ? messages.byId : undefined;\n}\n\nexport function selectThreadParam<K extends keyof Thread>(\n global: GlobalState,\n chatId: number,\n threadId: number,\n key: K,\n) {\n const messageInfo = global.messages.byChatId[chatId];\n if (!messageInfo) {\n return undefined;\n }\n\n const thread = messageInfo.threadsById[threadId];\n if (!thread) {\n return undefined;\n }\n\n return thread[key];\n}\n\nexport function selectListedIds(global: GlobalState, chatId: number, threadId: number) {\n return selectThreadParam(global, chatId, threadId, 'listedIds');\n}\n\nexport function selectOutlyingIds(global: GlobalState, chatId: number, threadId: number) {\n return selectThreadParam(global, chatId, threadId, 'outlyingIds');\n}\n\nexport function selectCurrentMessageIds(\n global: GlobalState, chatId: number, threadId: number, messageListType: MessageListType,\n) {\n switch (messageListType) {\n case 'thread':\n return selectViewportIds(global, chatId, threadId);\n case 'pinned':\n return selectPinnedIds(global, chatId);\n case 'scheduled':\n return selectScheduledIds(global, chatId);\n }\n\n return undefined;\n}\n\nexport function selectViewportIds(global: GlobalState, chatId: number, threadId: number) {\n return selectThreadParam(global, chatId, threadId, 'viewportIds');\n}\n\nexport function selectPinnedIds(global: GlobalState, chatId: number) {\n return selectThreadParam(global, chatId, MAIN_THREAD_ID, 'pinnedIds');\n}\n\nexport function selectScheduledIds(global: GlobalState, chatId: number) {\n return selectThreadParam(global, chatId, MAIN_THREAD_ID, 'scheduledIds');\n}\n\nexport function selectScrollOffset(global: GlobalState, chatId: number, threadId: number) {\n return selectThreadParam(global, chatId, threadId, 'scrollOffset');\n}\n\nexport function selectReplyingToId(global: GlobalState, chatId: number, threadId: number) {\n return selectThreadParam(global, chatId, threadId, 'replyingToId');\n}\n\nexport function selectEditingId(global: GlobalState, chatId: number, threadId: number) {\n return selectThreadParam(global, chatId, threadId, 'editingId');\n}\n\nexport function selectEditingScheduledId(global: GlobalState, chatId: number) {\n return selectThreadParam(global, chatId, MAIN_THREAD_ID, 'editingScheduledId');\n}\n\nexport function selectDraft(global: GlobalState, chatId: number, threadId: number) {\n return selectThreadParam(global, chatId, threadId, 'draft');\n}\n\nexport function selectNoWebPage(global: GlobalState, chatId: number, threadId: number) {\n return selectThreadParam(global, chatId, threadId, 'noWebPage');\n}\n\nexport function selectThreadInfo(global: GlobalState, chatId: number, threadId: number) {\n return selectThreadParam(global, chatId, threadId, 'threadInfo');\n}\n\nexport function selectFirstMessageId(global: GlobalState, chatId: number, threadId: number) {\n return selectThreadParam(global, chatId, threadId, 'firstMessageId');\n}\n\nexport function selectReplyStack(global: GlobalState, chatId: number, threadId: number) {\n return selectThreadParam(global, chatId, threadId, 'replyStack');\n}\n\nexport function selectThreadOriginChat(global: GlobalState, chatId: number, threadId: number) {\n if (threadId === MAIN_THREAD_ID) {\n return selectChat(global, chatId);\n }\n\n const threadInfo = selectThreadInfo(global, chatId, threadId);\n if (!threadInfo) {\n return undefined;\n }\n\n return selectChat(global, threadInfo.originChannelId || chatId);\n}\n\nexport function selectThreadTopMessageId(global: GlobalState, chatId: number, threadId: number) {\n if (threadId === MAIN_THREAD_ID) {\n return undefined;\n }\n\n const threadInfo = selectThreadInfo(global, chatId, threadId);\n if (!threadInfo) {\n return undefined;\n }\n\n return threadInfo.topMessageId;\n}\n\nexport function selectThreadByMessage(global: GlobalState, chatId: number, message: ApiMessage) {\n const messageInfo = global.messages.byChatId[chatId];\n if (!messageInfo) {\n return undefined;\n }\n\n const { replyToMessageId, replyToTopMessageId } = message;\n if (!replyToMessageId && !replyToTopMessageId) {\n return undefined;\n }\n\n return Object.values<Thread>(messageInfo.threadsById).find((thread) => {\n return thread.threadInfo && (\n (replyToMessageId && replyToMessageId === thread.threadInfo.topMessageId)\n || (replyToTopMessageId && replyToTopMessageId === thread.threadInfo.topMessageId)\n );\n });\n}\n\nexport function isMessageInCurrentMessageList(global: GlobalState, chatId: number, message: ApiMessage) {\n const currentMessageList = selectCurrentMessageList(global);\n if (!currentMessageList) {\n return false;\n }\n\n const { threadInfo } = selectThreadByMessage(global, chatId, message) || {};\n return (\n chatId === currentMessageList.chatId\n && (\n (currentMessageList.threadId === MAIN_THREAD_ID)\n || (threadInfo && currentMessageList.threadId === threadInfo.threadId)\n )\n );\n}\n\nexport function selectIsViewportNewest(global: GlobalState, chatId: number, threadId: number) {\n const viewportIds = selectViewportIds(global, chatId, threadId);\n if (!viewportIds || !viewportIds.length) {\n return true;\n }\n\n let lastMessageId: number;\n\n if (threadId === MAIN_THREAD_ID) {\n const chat = selectChat(global, chatId);\n if (!chat || !chat.lastMessage) {\n return true;\n }\n\n lastMessageId = chat.lastMessage.id;\n } else {\n const threadInfo = selectThreadInfo(global, chatId, threadId);\n if (!threadInfo || !threadInfo.lastMessageId) {\n return undefined;\n }\n\n lastMessageId = threadInfo.lastMessageId;\n }\n\n // Edge case: outgoing `lastMessage` is updated with a delay to optimize animation\n if (lastMessageId >= LOCAL_MESSAGE_ID_BASE && !selectChatMessage(global, chatId, lastMessageId)) {\n return true;\n }\n\n return viewportIds[viewportIds.length - 1] >= lastMessageId;\n}\n\nexport function selectChatMessage(global: GlobalState, chatId: number, messageId: number) {\n const chatMessages = selectChatMessages(global, chatId);\n\n return chatMessages ? chatMessages[messageId] : undefined;\n}\n\nexport function selectScheduledMessage(global: GlobalState, chatId: number, messageId: number) {\n const chatMessages = selectScheduledMessages(global, chatId);\n\n return chatMessages ? chatMessages[messageId] : undefined;\n}\n\nexport function selectEditingMessage(\n global: GlobalState, chatId: number, threadId: number, messageListType: MessageListType,\n) {\n if (messageListType === 'scheduled') {\n const messageId = selectEditingScheduledId(global, chatId);\n return messageId ? selectScheduledMessage(global, chatId, messageId) : undefined;\n } else {\n const messageId = selectEditingId(global, chatId, threadId);\n return messageId ? selectChatMessage(global, chatId, messageId) : undefined;\n }\n}\n\nexport function selectChatMessageByPollId(global: GlobalState, pollId: string) {\n let messageWithPoll: ApiMessage | undefined;\n\n // eslint-disable-next-line no-restricted-syntax\n for (const chatMessages of Object.values(global.messages.byChatId)) {\n const { byId } = chatMessages;\n messageWithPoll = Object.values(byId).find((message) => {\n return message.content.poll && message.content.poll.id === pollId;\n });\n if (messageWithPoll) {\n break;\n }\n }\n\n return messageWithPoll;\n}\n\nexport function selectFocusedMessageId(global: GlobalState, chatId: number) {\n const { chatId: focusedChatId, messageId } = global.focusedMessage || {};\n\n return focusedChatId === chatId ? messageId : undefined;\n}\n\nexport function selectIsMessageFocused(global: GlobalState, message: ApiMessage) {\n const focusedId = selectFocusedMessageId(global, message.chatId);\n\n return focusedId ? focusedId === message.id || focusedId === message.previousLocalId : false;\n}\n\nexport function selectIsMessageUnread(global: GlobalState, message: ApiMessage) {\n const { lastReadOutboxMessageId } = selectChat(global, message.chatId) || {};\n return isMessageLocal(message) || !lastReadOutboxMessageId || lastReadOutboxMessageId < message.id;\n}\n\nexport function selectOutgoingStatus(\n global: GlobalState, message: ApiMessage, isScheduledList = false,\n): ApiMessageOutgoingStatus {\n if (!selectIsMessageUnread(global, message) && !isScheduledList) {\n return 'read';\n }\n\n return getSendingState(message);\n}\n\nexport function selectSender(global: GlobalState, message: ApiMessage): ApiUser | ApiChat | undefined {\n const { senderId } = message;\n if (!senderId) {\n return undefined;\n }\n\n return senderId > 0 ? selectUser(global, senderId) : selectChat(global, senderId);\n}\n\nexport function selectForwardedSender(global: GlobalState, message: ApiMessage): ApiUser | ApiChat | undefined {\n const { forwardInfo } = message;\n if (!forwardInfo) {\n return undefined;\n }\n\n if (forwardInfo.isChannelPost && forwardInfo.fromChatId) {\n return selectChat(global, forwardInfo.fromChatId);\n } else if (forwardInfo.senderUserId) {\n return selectUser(global, forwardInfo.senderUserId);\n }\n\n return undefined;\n}\n\nexport function selectAllowedMessageActions(global: GlobalState, message: ApiMessage, threadId: number) {\n const { serverTimeOffset } = global;\n const chat = selectChat(global, message.chatId);\n if (!chat || chat.isRestricted) {\n return {};\n }\n\n const isPrivate = isChatPrivate(chat.id);\n const isChatWithSelf = selectIsChatWithSelf(global, message.chatId);\n const isBasicGroup = isChatBasicGroup(chat);\n const isSuperGroup = isChatSuperGroup(chat);\n const isChannel = isChatChannel(chat);\n const isServiceNotification = isServiceNotificationMessage(message);\n\n const isOwn = isOwnMessage(message);\n const isAction = isActionMessage(message);\n const { content } = message;\n const canEditMessagesIndefinitely = isChatWithSelf\n || (isSuperGroup && getHasAdminRight(chat, 'pinMessages'))\n || (isChannel && getHasAdminRight(chat, 'editMessages'));\n const isMessageEditable = (\n (canEditMessagesIndefinitely\n || Date.now() + serverTimeOffset * 1000 - message.date * 1000 < MESSAGE_EDIT_ALLOWED_TIME_MS)\n && !(\n content.sticker || content.contact || content.poll || content.action || content.audio\n || (content.video && content.video.isRound)\n )\n && !isForwardedMessage(message)\n && !message.viaBotId\n );\n\n const canReply = getCanPostInChat(chat, threadId) && !isServiceNotification;\n\n const hasPinPermission = isPrivate || (\n chat.isCreator\n || (!isChannel && !isUserRightBanned(chat, 'pinMessages'))\n || getHasAdminRight(chat, 'pinMessages')\n );\n\n let canPin = !isAction && hasPinPermission;\n let canUnpin = false;\n\n const pinnedMessageIds = selectPinnedIds(global, chat.id);\n\n if (canPin) {\n canUnpin = Boolean(pinnedMessageIds && pinnedMessageIds.includes(message.id));\n canPin = !canUnpin;\n }\n\n const canDelete = isPrivate\n || isOwn\n || isBasicGroup\n || chat.isCreator\n || getHasAdminRight(chat, 'deleteMessages');\n\n const canReport = !isPrivate && !isOwn;\n\n const canDeleteForAll = canDelete && !isServiceNotification && (\n (isPrivate && !isChatWithSelf)\n || (isBasicGroup && (\n isOwn || getHasAdminRight(chat, 'deleteMessages') || chat.isCreator\n ))\n );\n\n const canEdit = !isAction && isMessageEditable && (\n isOwn\n || (isChannel && (chat.isCreator || getHasAdminRight(chat, 'editMessages')))\n );\n\n const canForward = !isAction && !isServiceNotification;\n\n const hasSticker = Boolean(message.content.sticker);\n const hasFavoriteSticker = hasSticker && selectIsStickerFavorite(global, message.content.sticker!);\n const canFaveSticker = !isAction && hasSticker && !hasFavoriteSticker;\n const canUnfaveSticker = !isAction && hasFavoriteSticker;\n const canCopy = !isAction;\n const canCopyLink = !isAction && (isChannel || isSuperGroup);\n const canSelect = !isAction;\n const noOptions = [\n canReply,\n canEdit,\n canPin,\n canUnpin,\n canDelete,\n canDeleteForAll,\n canForward,\n canFaveSticker,\n canUnfaveSticker,\n canCopy,\n canCopyLink,\n canSelect,\n ].every((ability) => !ability);\n\n return {\n noOptions,\n canReply,\n canEdit,\n canPin,\n canUnpin,\n canDelete,\n canReport,\n canDeleteForAll,\n canForward,\n canFaveSticker,\n canUnfaveSticker,\n canCopy,\n canCopyLink,\n canSelect,\n };\n}\n\n// This selector always returns a new object which can not be safely used in shallow-equal checks\nexport function selectCanDeleteSelectedMessages(global: GlobalState) {\n const { messageIds: selectedMessageIds } = global.selectedMessages || {};\n const { chatId, threadId } = selectCurrentMessageList(global) || {};\n const chatMessages = chatId && selectChatMessages(global, chatId);\n if (!chatMessages || !selectedMessageIds || !threadId) {\n return {};\n }\n\n const messageActions = selectedMessageIds\n .map((id) => chatMessages[id] && selectAllowedMessageActions(global, chatMessages[id], threadId))\n .filter(Boolean);\n\n return {\n canDelete: messageActions.every((actions) => actions.canDelete),\n canDeleteForAll: messageActions.every((actions) => actions.canDeleteForAll),\n };\n}\n\nexport function selectCanReportSelectedMessages(global: GlobalState) {\n const { messageIds: selectedMessageIds } = global.selectedMessages || {};\n const { chatId, threadId } = selectCurrentMessageList(global) || {};\n const chatMessages = chatId && selectChatMessages(global, chatId);\n if (!chatMessages || !selectedMessageIds || !threadId) {\n return false;\n }\n\n const messageActions = selectedMessageIds\n .map((id) => chatMessages[id] && selectAllowedMessageActions(global, chatMessages[id], threadId))\n .filter(Boolean);\n\n return messageActions.every((actions) => actions.canReport);\n}\n\nexport function selectUploadProgress(global: GlobalState, message: ApiMessage) {\n const fileTransfer = global.fileUploads.byMessageLocalId[message.previousLocalId || message.id];\n\n return fileTransfer ? fileTransfer.progress : undefined;\n}\n\nexport function selectRealLastReadId(global: GlobalState, chatId: number, threadId: number) {\n if (threadId === MAIN_THREAD_ID) {\n const chat = selectChat(global, chatId);\n if (!chat) {\n return undefined;\n }\n\n // `lastReadInboxMessageId` is empty for new chats\n if (!chat.lastReadInboxMessageId) {\n return undefined;\n }\n\n if (!chat.lastMessage) {\n return chat.lastReadInboxMessageId;\n }\n\n if (isMessageLocal(chat.lastMessage)) {\n return chat.lastMessage.id;\n }\n\n // Some previously read messages may be deleted\n return Math.min(chat.lastMessage.id, chat.lastReadInboxMessageId);\n } else {\n const threadInfo = selectThreadInfo(global, chatId, threadId);\n if (!threadInfo) {\n return undefined;\n }\n\n if (!threadInfo.lastReadInboxMessageId) {\n return threadInfo.topMessageId;\n }\n\n // Some previously read messages may be deleted\n return Math.min(threadInfo.lastReadInboxMessageId, threadInfo.lastMessageId || Infinity);\n }\n}\n\nexport function selectFirstUnreadId(global: GlobalState, chatId: number, threadId: number) {\n const chat = selectChat(global, chatId);\n\n if (threadId === MAIN_THREAD_ID) {\n if (!chat) {\n return undefined;\n }\n } else {\n const threadInfo = selectThreadInfo(global, chatId, threadId);\n if (!threadInfo || threadInfo.lastMessageId === threadInfo.lastReadInboxMessageId) {\n return undefined;\n }\n }\n\n const outlyingIds = selectOutlyingIds(global, chatId, threadId);\n const listedIds = selectListedIds(global, chatId, threadId);\n const byId = selectChatMessages(global, chatId);\n if (!byId || !(outlyingIds || listedIds)) {\n return undefined;\n }\n\n const lastReadId = selectRealLastReadId(global, chatId, threadId);\n if (!lastReadId && chat && chat.isNotJoined) {\n return undefined;\n }\n\n if (outlyingIds) {\n const found = !lastReadId ? outlyingIds[0] : outlyingIds.find((id) => {\n return id > lastReadId && byId[id] && (!byId[id].isOutgoing || byId[id].isFromScheduled);\n });\n if (found) {\n return found;\n }\n }\n\n if (listedIds) {\n const found = !lastReadId ? listedIds[0] : listedIds.find((id) => {\n return id > lastReadId && byId[id] && (!byId[id].isOutgoing || byId[id].isFromScheduled);\n });\n if (found) {\n return found;\n }\n }\n\n return undefined;\n}\n\nexport function selectIsPollResultsOpen(global: GlobalState) {\n const { pollResults } = global;\n return Boolean(pollResults.messageId);\n}\n\nexport function selectIsForwardModalOpen(global: GlobalState) {\n const { forwardMessages } = global;\n return Boolean(forwardMessages.isModalShown);\n}\n\nexport function selectCommonBoxChatId(global: GlobalState, messageId: number) {\n const fromLastMessage = Object.values(global.chats.byId).find((chat) => (\n isCommonBoxChat(chat) && chat.lastMessage && chat.lastMessage.id === messageId\n ));\n if (fromLastMessage) {\n return fromLastMessage.id;\n }\n\n const { byChatId } = global.messages;\n return Number(Object.keys(byChatId).find((chatId) => {\n const chat = selectChat(global, Number(chatId));\n return chat && isCommonBoxChat(chat) && byChatId[chat.id].byId[messageId];\n }));\n}\n\nexport function selectIsInSelectMode(global: GlobalState) {\n const { selectedMessages } = global;\n\n return Boolean(selectedMessages);\n}\n\nexport function selectIsMessageSelected(global: GlobalState, messageId: number) {\n const { messageIds } = global.selectedMessages || {};\n if (!messageIds) {\n return false;\n }\n\n return messageIds.includes(messageId);\n}\n\nexport function selectForwardedMessageIdsByGroupId(global: GlobalState, chatId: number, groupedId: string) {\n const chatMessages = selectChatMessages(global, chatId);\n if (!chatMessages) {\n return undefined;\n }\n\n return Object.values(chatMessages)\n .filter((message) => message.groupedId === groupedId && message.forwardInfo)\n .map(({ forwardInfo }) => forwardInfo!.fromMessageId);\n}\n\nexport function selectMessageIdsByGroupId(global: GlobalState, chatId: number, groupedId: string) {\n const chatMessages = selectChatMessages(global, chatId);\n if (!chatMessages) {\n return undefined;\n }\n\n return Object.keys(chatMessages)\n .map(Number)\n .filter((id) => chatMessages[id].groupedId === groupedId);\n}\n\nexport function selectIsDocumentGroupSelected(global: GlobalState, chatId: number, groupedId: string) {\n const { messageIds: selectedIds } = global.selectedMessages || {};\n if (!selectedIds) {\n return false;\n }\n\n const groupIds = selectMessageIdsByGroupId(global, chatId, groupedId);\n return groupIds && groupIds.every((id) => selectedIds.includes(id));\n}\n\nexport function selectSelectedMessagesCount(global: GlobalState) {\n const { messageIds } = global.selectedMessages || {};\n\n return messageIds ? messageIds.length : 0;\n}\n\nexport function selectNewestMessageWithBotKeyboardButtons(\n global: GlobalState, chatId: number,\n): ApiMessage | undefined {\n const chat = selectChat(global, chatId);\n if (!chat) {\n return undefined;\n }\n\n if (!selectIsChatWithBot(global, chat)) {\n return undefined;\n }\n\n const chatMessages = selectChatMessages(global, chatId);\n const viewportIds = selectViewportIds(global, chatId, MAIN_THREAD_ID);\n if (!chatMessages || !viewportIds) {\n return undefined;\n }\n\n const messageId = findLast(viewportIds, (id) => {\n return !chatMessages[id].isOutgoing && Boolean(chatMessages[id].keyboardButtons);\n });\n\n const replyHideMessageId = findLast(viewportIds, (id) => {\n return Boolean(chatMessages[id].shouldHideKeyboardButtons);\n });\n\n if (messageId && replyHideMessageId && replyHideMessageId > messageId) {\n return undefined;\n }\n\n return messageId ? chatMessages[messageId] : undefined;\n}\n\nexport function selectShouldAutoLoadMedia(\n global: GlobalState, message: ApiMessage, chat: ApiChat, sender?: ApiChat | ApiUser,\n) {\n const {\n shouldAutoDownloadMediaFromContacts,\n shouldAutoDownloadMediaInPrivateChats,\n shouldAutoDownloadMediaInGroups,\n shouldAutoDownloadMediaInChannels,\n } = global.settings.byKey;\n\n return Boolean(\n (shouldAutoDownloadMediaInPrivateChats && isChatPrivate(chat.id))\n || (shouldAutoDownloadMediaInGroups && isChatGroup(chat))\n || (shouldAutoDownloadMediaInChannels && isChatChannel(chat))\n || (shouldAutoDownloadMediaFromContacts && sender && (\n sender.id === global.currentUserId\n || selectIsUserOrChatContact(global, sender)\n )),\n );\n}\n\nexport function selectShouldAutoPlayMedia(global: GlobalState, message: ApiMessage) {\n const video = getMessageVideo(message) || getMessageWebPageVideo(message);\n if (!video) {\n return undefined;\n }\n\n const {\n shouldAutoPlayVideos,\n shouldAutoPlayGifs,\n } = global.settings.byKey;\n\n const asGif = video.isGif || video.isRound;\n\n return (shouldAutoPlayVideos && !asGif) || (shouldAutoPlayGifs && asGif);\n}\n\nexport function selectShouldLoopStickers(global: GlobalState) {\n return global.settings.byKey.shouldLoopStickers;\n}\n","import { GlobalState } from '../../global/types';\nimport { selectCurrentMessageList } from './messages';\nimport { buildChatThreadKey } from '../helpers';\n\nexport function selectCurrentTextSearch(global: GlobalState) {\n const { chatId, threadId } = selectCurrentMessageList(global) || {};\n if (!chatId || !threadId) {\n return undefined;\n }\n\n const chatThreadKey = buildChatThreadKey(chatId, threadId);\n const currentSearch = global.localTextSearch.byChatThreadKey[chatThreadKey];\n if (!currentSearch || !currentSearch.isActive) {\n return undefined;\n }\n\n return currentSearch;\n}\n\nexport function selectCurrentMediaSearchPeerId(global: GlobalState) {\n const { byChatId } = global.localMediaSearch;\n const { chatId } = selectCurrentMessageList(global) || {};\n const currentProfileUserId = global.users.selectedId;\n\n return currentProfileUserId && byChatId[currentProfileUserId] ? currentProfileUserId : chatId;\n}\n\nexport function selectCurrentMediaSearch(global: GlobalState) {\n const peerId = selectCurrentMediaSearchPeerId(global);\n if (!peerId) {\n return undefined;\n }\n\n return global.localMediaSearch.byChatId[peerId];\n}\n","import { GlobalState } from '../../global/types';\n\nimport { selectCurrentMessageList } from './messages';\nimport { selectChat } from './chats';\nimport { isChatGroup, isChatPrivate } from '../helpers';\n\nexport function selectManagement(global: GlobalState, chatId: number) {\n return global.management.byChatId[chatId];\n}\n\nexport function selectCurrentManagement(global: GlobalState) {\n const { chatId, threadId } = selectCurrentMessageList(global) || {};\n if (!chatId || !threadId) {\n return undefined;\n }\n\n const currentManagement = global.management.byChatId[chatId];\n if (!currentManagement || !currentManagement.isActive) {\n return undefined;\n }\n\n return currentManagement;\n}\n\nexport function selectCurrentManagementType(global: GlobalState) {\n const { chatId, threadId } = selectCurrentMessageList(global) || {};\n if (!chatId || !threadId) {\n return undefined;\n }\n\n if (isChatPrivate(chatId)) {\n return 'user';\n }\n\n const chat = selectChat(global, chatId);\n if (!chat) {\n return undefined;\n }\n\n if (isChatGroup(chat)) {\n return 'group';\n }\n\n return 'channel';\n}\n","import { GlobalState } from '../../global/types';\nimport { NewChatMembersProgress, RightColumnContent } from '../../types';\n\nimport { getSystemTheme, IS_SINGLE_COLUMN_LAYOUT } from '../../util/environment';\nimport { selectCurrentMessageList, selectIsPollResultsOpen } from './messages';\nimport { selectCurrentTextSearch } from './localSearch';\nimport { selectCurrentStickerSearch, selectCurrentGifSearch } from './symbols';\nimport { selectAreActiveChatsLoaded } from './chats';\nimport { selectCurrentManagement } from './management';\n\nexport function selectIsMediaViewerOpen(global: GlobalState) {\n const { mediaViewer } = global;\n return Boolean(mediaViewer.messageId || mediaViewer.avatarOwnerId);\n}\n\nexport function selectRightColumnContentKey(global: GlobalState) {\n const {\n users,\n isChatInfoShown,\n newChatMembersProgress,\n } = global;\n\n const isAddingChatMembersShown = newChatMembersProgress !== NewChatMembersProgress.Closed;\n const isPollResults = selectIsPollResultsOpen(global);\n const isSearch = Boolean(!IS_SINGLE_COLUMN_LAYOUT && selectCurrentTextSearch(global));\n const isManagement = selectCurrentManagement(global);\n const stickerSearch = selectCurrentStickerSearch(global);\n const isStickerSearch = stickerSearch.query !== undefined;\n const gifSearch = selectCurrentGifSearch(global);\n const isGifSearch = gifSearch.query !== undefined;\n const { chatId: currentChatId } = selectCurrentMessageList(global) || {};\n const currentProfileUserId = users.selectedId;\n const areActiveChatsLoaded = selectAreActiveChatsLoaded(global);\n const isUserInfo = Boolean(currentProfileUserId && areActiveChatsLoaded);\n const isChatShown = Boolean(currentChatId && areActiveChatsLoaded);\n const isChatInfo = isChatShown && isChatInfoShown;\n\n return isPollResults ? (\n RightColumnContent.PollResults\n ) : isSearch ? (\n RightColumnContent.Search\n ) : isManagement ? (\n RightColumnContent.Management\n ) : isStickerSearch ? (\n RightColumnContent.StickerSearch\n ) : isGifSearch ? (\n RightColumnContent.GifSearch\n ) : isAddingChatMembersShown ? (\n RightColumnContent.AddingMembers\n ) : isUserInfo ? (\n RightColumnContent.UserInfo\n ) : isChatInfo ? (\n RightColumnContent.ChatInfo\n ) : undefined;\n}\n\nexport function selectIsRightColumnShown(global: GlobalState) {\n return selectRightColumnContentKey(global) !== undefined;\n}\n\nexport function selectTheme(global: GlobalState) {\n const { theme, shouldUseSystemTheme } = global.settings.byKey;\n\n return shouldUseSystemTheme ? getSystemTheme() : theme;\n}\n","import { GlobalState } from '../../global/types';\n\nexport function selectCurrentGlobalSearchQuery(global: GlobalState) {\n return global.globalSearch.query;\n}\n","import { GlobalState } from '../../global/types';\n\nexport function selectPaymentChatId(global: GlobalState) {\n return global.payment.chatId;\n}\n\nexport function selectPaymentMessageId(global: GlobalState) {\n return global.payment.messageId;\n}\n\nexport function selectPaymentFormId(global: GlobalState) {\n return global.payment.formId;\n}\n\nexport function selectPaymentRequestId(global: GlobalState) {\n return global.payment.requestId;\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","import {\n ApiBotInlineMediaResult, ApiBotInlineResult, ApiBotInlineSwitchPm,\n ApiLanguage, ApiMessage, ApiShippingAddress, ApiStickerSet,\n} from '../api/types';\n\nexport enum LoadMoreDirection {\n Backwards,\n Forwards,\n Around,\n}\n\nexport enum FocusDirection {\n Up,\n Down,\n Static,\n}\n\nexport interface IAlbum {\n albumId: string;\n messages: ApiMessage[];\n mainMessage: ApiMessage;\n}\n\nexport type ThemeKey = 'light' | 'dark';\n\nexport interface IThemeSettings {\n background?: string;\n backgroundColor?: string;\n patternColor?: string;\n isBlurred?: boolean;\n}\n\nexport type NotifySettings = {\n hasPrivateChatsNotifications?: boolean;\n hasPrivateChatsMessagePreview?: boolean;\n hasGroupNotifications?: boolean;\n hasGroupMessagePreview?: boolean;\n hasBroadcastNotifications?: boolean;\n hasBroadcastMessagePreview?: boolean;\n hasContactJoinedNotifications?: boolean;\n hasWebNotifications: boolean;\n hasPushNotifications: boolean;\n notificationSoundVolume: number;\n};\n\nexport type LangCode = (\n 'en' | 'ar' | 'be' | 'ca' | 'nl' | 'fr' | 'de' | 'id' | 'it' | 'ko' | 'ms' | 'fa' | 'pl' | 'pt-br' | 'ru' | 'es'\n | 'tr' | 'uk' | 'uz'\n);\n\nexport interface ISettings extends NotifySettings, Record<string, any> {\n theme: ThemeKey;\n shouldUseSystemTheme: boolean;\n messageTextSize: number;\n animationLevel: 0 | 1 | 2;\n messageSendKeyCombo: 'enter' | 'ctrl-enter';\n shouldAutoDownloadMediaFromContacts: boolean;\n shouldAutoDownloadMediaInPrivateChats: boolean;\n shouldAutoDownloadMediaInGroups: boolean;\n shouldAutoDownloadMediaInChannels: boolean;\n shouldAutoPlayGifs: boolean;\n shouldAutoPlayVideos: boolean;\n shouldSuggestStickers: boolean;\n shouldLoopStickers: boolean;\n hasPassword?: boolean;\n languages?: ApiLanguage[];\n language: LangCode;\n isSensitiveEnabled?: boolean;\n canChangeSensitive?: boolean;\n}\n\nexport interface ApiPrivacySettings {\n visibility: PrivacyVisibility;\n allowUserIds: number[];\n allowChatIds: number[];\n blockUserIds: number[];\n blockChatIds: number[];\n}\n\nexport interface IInputPrivacyContact {\n id: number;\n accessHash?: string;\n}\n\nexport interface IInputPrivacyRules {\n visibility: PrivacyVisibility;\n allowedUsers?: IInputPrivacyContact[];\n allowedChats?: IInputPrivacyContact[];\n blockedUsers?: IInputPrivacyContact[];\n blockedChats?: IInputPrivacyContact[];\n}\n\nexport type IAnchorPosition = {\n x: number;\n y: number;\n};\n\nexport interface ShippingOption {\n id: string;\n title: string;\n amount: number;\n prices: Price[];\n}\n\nexport interface Price {\n label: string;\n amount: number;\n}\n\nexport interface Invoice {\n currency?: string;\n emailRequested?: boolean;\n emailToProvider?: boolean;\n flexible?: boolean;\n nameRequested?: boolean;\n phoneRequested?: boolean;\n phoneToProvider?: boolean;\n prices?: Price[];\n shippingAddressRequested?: boolean;\n test?: boolean;\n}\n\nexport interface Receipt {\n currency: string;\n prices: Price[];\n info?: {\n shippingAddress?: ApiShippingAddress;\n phone?: string;\n name?: string;\n };\n totalAmount: number;\n credentialsTitle: string;\n shippingPrices?: Price[];\n shippingMethod?: string;\n photoUrl?: string;\n text?: string;\n title?: string;\n}\n\nexport enum SettingsScreens {\n Main,\n EditProfile,\n Notifications,\n Language,\n General,\n GeneralChatBackground,\n GeneralChatBackgroundColor,\n Privacy,\n PrivacyPhoneNumber,\n PrivacyLastSeen,\n PrivacyProfilePhoto,\n PrivacyForwarding,\n PrivacyGroupChats,\n PrivacyPhoneNumberAllowedContacts,\n PrivacyPhoneNumberDeniedContacts,\n PrivacyLastSeenAllowedContacts,\n PrivacyLastSeenDeniedContacts,\n PrivacyProfilePhotoAllowedContacts,\n PrivacyProfilePhotoDeniedContacts,\n PrivacyForwardingAllowedContacts,\n PrivacyForwardingDeniedContacts,\n PrivacyGroupChatsAllowedContacts,\n PrivacyGroupChatsDeniedContacts,\n PrivacyActiveSessions,\n PrivacyBlockedUsers,\n Folders,\n FoldersCreateFolder,\n FoldersEditFolder,\n FoldersEditFolderFromChatList,\n FoldersIncludedChats,\n FoldersIncludedChatsFromChatList,\n FoldersExcludedChats,\n FoldersExcludedChatsFromChatList,\n TwoFaDisabled,\n TwoFaNewPassword,\n TwoFaNewPasswordConfirm,\n TwoFaNewPasswordHint,\n TwoFaNewPasswordEmail,\n TwoFaNewPasswordEmailCode,\n TwoFaEnabled,\n TwoFaChangePasswordCurrent,\n TwoFaChangePasswordNew,\n TwoFaChangePasswordConfirm,\n TwoFaChangePasswordHint,\n TwoFaTurnOff,\n TwoFaRecoveryEmailCurrentPassword,\n TwoFaRecoveryEmail,\n TwoFaRecoveryEmailCode,\n TwoFaCongratulations,\n}\n\nexport type StickerSetOrRecent = Pick<ApiStickerSet, (\n 'id' | 'title' | 'count' | 'stickers' | 'hasThumbnail' | 'isAnimated'\n)>;\n\nexport enum LeftColumnContent {\n ChatList,\n GlobalSearch,\n Settings,\n Contacts,\n Archived,\n NewChannelStep1,\n NewChannelStep2,\n NewGroupStep1,\n NewGroupStep2,\n}\n\nexport enum GlobalSearchContent {\n ChatList,\n Media,\n Links,\n Files,\n Music,\n Voice,\n}\n\nexport enum RightColumnContent {\n ChatInfo,\n UserInfo,\n Search,\n Management,\n StickerSearch,\n GifSearch,\n PollResults,\n AddingMembers,\n}\n\nexport enum MediaViewerOrigin {\n Inline,\n ScheduledInline,\n SharedMedia,\n ProfileAvatar,\n MiddleHeaderAvatar,\n Album,\n ScheduledAlbum,\n SearchResult,\n}\n\nexport enum ChatCreationProgress {\n Idle,\n InProgress,\n Complete,\n Error,\n}\n\nexport enum ProfileEditProgress {\n Idle,\n InProgress,\n Complete,\n Error,\n}\n\nexport enum ManagementProgress {\n Idle,\n InProgress,\n Complete,\n Error,\n}\n\nexport enum NewChatMembersProgress {\n Closed,\n InProgress,\n Loading,\n}\n\nexport type ProfileTabType = 'members' | 'media' | 'documents' | 'links' | 'audio';\nexport type SharedMediaType = 'media' | 'documents' | 'links' | 'audio';\nexport type ApiPrivacyKey = 'phoneNumber' | 'lastSeen' | 'profilePhoto' | 'forwards' | 'chatInvite';\nexport type PrivacyVisibility = 'everybody' | 'contacts' | 'nonContacts' | 'nobody';\n\nexport enum ProfileState {\n Profile,\n SharedMedia,\n MemberList,\n}\n\nexport enum PaymentStep {\n ShippingInfo,\n Shipping,\n PaymentInfo,\n Checkout,\n}\n\nexport const UPLOADING_WALLPAPER_SLUG = 'UPLOADING_WALLPAPER_SLUG';\n\nexport enum ManagementScreens {\n Initial,\n ChatPrivacyType,\n Discussion,\n ChannelSubscribers,\n GroupType,\n GroupPermissions,\n GroupRemovedUsers,\n GroupUserPermissionsCreate,\n GroupUserPermissions,\n ChatAdministrators,\n GroupRecentActions,\n ChatAdminRights,\n GroupMembers,\n}\n\nexport type ManagementType = 'user' | 'group' | 'channel';\n\nexport type NotifyException = {\n isMuted: boolean;\n isSilent?: boolean;\n shouldShowPreviews?: boolean;\n};\n\nexport type EmojiKeywords = {\n isLoading?: boolean;\n version: number;\n keywords: Record<string, string[]>;\n};\n\nexport type InlineBotSettings = {\n id: number;\n help?: string;\n query?: string;\n offset?: string;\n canLoadMore?: boolean;\n results?: (ApiBotInlineResult | ApiBotInlineMediaResult)[];\n isGallery?: boolean;\n switchPm?: ApiBotInlineSwitchPm;\n};\n","import { 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 { DEBUG } from '../config';\n\nexport function updateAppBadge(unreadCount: number) {\n if (typeof window.navigator.setAppBadge !== 'function') {\n return;\n }\n\n window.navigator.setAppBadge(unreadCount).catch((err) => {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error(err);\n }\n });\n}\n","export default function arePropsShallowEqual(currentProps: AnyLiteral, newProps: AnyLiteral) {\n if (currentProps === newProps) {\n return true;\n }\n\n const currentKeys = Object.keys(currentProps);\n const currentKeysLength = currentKeys.length;\n const newKeysLength = Object.keys(newProps).length;\n\n if (currentKeysLength !== newKeysLength) {\n return false;\n }\n\n if (currentKeysLength === 0) {\n return true;\n }\n\n for (let i = 0; i < currentKeysLength; i++) {\n const prop = currentKeys[i];\n if (currentProps[prop] !== newProps[prop]) {\n return false;\n }\n }\n\n return true;\n}\n\nexport function getUnequalProps(currentProps: AnyLiteral, newProps: AnyLiteral) {\n const currentKeys = Object.keys(currentProps);\n const currentKeysLength = currentKeys.length;\n const newKeysLength = Object.keys(newProps).length;\n\n if (currentKeysLength !== newKeysLength) {\n return ['%LENGTH%'];\n }\n\n return currentKeys.reduce((res, prop) => {\n if (currentProps[prop] !== newProps[prop]) {\n res.push(`${prop}: ${currentProps[prop]} => ${newProps[prop]}`);\n }\n\n return res;\n }, [] as string[]);\n}\n","type Parts = (string | false | undefined)[];\n\nexport default (...parts: Parts) => {\n return parts.filter(Boolean).join(' ');\n};\n","// eslint-disable-next-line no-restricted-globals\nconst cacheApi = self.caches;\n\nexport enum Type {\n Text,\n Blob,\n Json,\n}\n\nexport async function fetch(cacheName: string, key: string, type: Type) {\n if (!cacheApi) {\n return undefined;\n }\n\n try {\n // To avoid the error \"Request scheme 'webdocument' is unsupported\"\n const request = new Request(key.replace(/:/g, '_'));\n const cache = await cacheApi.open(cacheName);\n const response = await cache.match(request);\n if (!response) {\n return undefined;\n }\n\n switch (type) {\n case Type.Text:\n return await response.text();\n case Type.Blob: {\n const blob = await response.blob();\n\n // Safari does not return correct Content-Type header for webp images.\n if (key.substr(0, 7) === 'sticker') {\n return new Blob([blob], { type: 'image/webp' });\n }\n\n // iOS Safari fails to preserve `type` in cache\n if (!blob.type) {\n const contentType = response.headers.get('Content-Type');\n if (contentType) {\n return new Blob([blob], { type: contentType });\n }\n }\n\n return blob;\n }\n case Type.Json:\n return await response.json();\n default:\n return undefined;\n }\n } catch (err) {\n // eslint-disable-next-line no-console\n console.warn(err);\n return undefined;\n }\n}\n\nexport async function save(cacheName: string, key: string, data: AnyLiteral | Blob | string) {\n if (!cacheApi) {\n return undefined;\n }\n\n try {\n const cacheData = typeof data === 'string' || data instanceof Blob ? data : JSON.stringify(data);\n // To avoid the error \"Request scheme 'webdocument' is unsupported\"\n const request = new Request(key.replace(/:/g, '_'));\n const response = new Response(cacheData);\n const cache = await cacheApi.open(cacheName);\n return await cache.put(request, response);\n } catch (err) {\n // eslint-disable-next-line no-console\n console.warn(err);\n return undefined;\n }\n}\n\nexport async function clear(cacheName: string) {\n try {\n if (!cacheApi) {\n return undefined;\n }\n\n return await cacheApi.delete(cacheName);\n } catch (err) {\n // eslint-disable-next-line no-console\n console.warn(err);\n return undefined;\n }\n}\n","import captureKeyboardListener from './captureKeyboardListeners';\n\ntype IHandlerFunction = () => void;\n\nexport default function captureEscKeyListener(handler: IHandlerFunction) {\n return captureKeyboardListener({ onEsc: handler });\n}\n","type HandlerName = 'onEnter' | 'onBackspace' | 'onDelete' | 'onEsc' | 'onUp' | 'onDown' | 'onLeft' | 'onRight'\n| 'onTab';\ntype Handler = (e: KeyboardEvent) => void;\ntype CaptureOptions = Partial<Record<HandlerName, Handler>>;\n\nconst keyToHandlerName: Record<string, HandlerName> = {\n Enter: 'onEnter',\n Backspace: 'onBackspace',\n Delete: 'onDelete',\n Esc: 'onEsc',\n Escape: 'onEsc',\n ArrowUp: 'onUp',\n ArrowDown: 'onDown',\n ArrowLeft: 'onLeft',\n ArrowRight: 'onRight',\n Tab: 'onTab',\n};\n\nconst handlers: Record<HandlerName, Handler[]> = {\n onEnter: [],\n onDelete: [],\n onBackspace: [],\n onEsc: [],\n onUp: [],\n onDown: [],\n onLeft: [],\n onRight: [],\n onTab: [],\n};\n\nexport default function captureKeyboardListeners(options: CaptureOptions) {\n if (!hasActiveHandlers()) {\n document.addEventListener('keydown', handleKeyDown, true);\n }\n\n (Object.keys(options) as Array<HandlerName>).forEach((handlerName) => {\n const handler = options[handlerName];\n if (!handler) {\n return;\n }\n\n const currentEventHandlers = handlers[handlerName];\n if (currentEventHandlers) {\n currentEventHandlers.push(handler);\n }\n });\n\n return () => {\n releaseKeyboardListener(options);\n };\n}\n\nfunction hasActiveHandlers() {\n return Object.values(handlers).some((keyHandlers) => Boolean(keyHandlers.length));\n}\n\nfunction handleKeyDown(e: KeyboardEvent) {\n const handlerName = keyToHandlerName[e.key];\n if (!handlerName) {\n return;\n }\n\n const { length } = handlers[handlerName];\n if (!length) {\n return;\n }\n e.stopPropagation();\n\n const handler = handlers[handlerName][length - 1];\n handler!(e);\n}\n\nfunction releaseKeyboardListener(options: CaptureOptions) {\n (Object.keys(options) as Array<HandlerName>).forEach((handlerName) => {\n const handler = options[handlerName];\n const currentEventHandlers = handlers[handlerName];\n if (currentEventHandlers) {\n const index = currentEventHandlers.findIndex((cb) => cb === handler);\n if (index !== -1) {\n currentEventHandlers.splice(index, 1);\n }\n }\n });\n\n if (!hasActiveHandlers()) {\n document.removeEventListener('keydown', handleKeyDown, false);\n }\n}\n","import { LangFn } from '../hooks/useLang';\n\nconst WEEKDAYS_FULL = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];\nconst MONTHS_FULL = [\n 'January', 'February', 'March', 'April', 'May', 'June',\n 'July', 'August', 'September', 'October', 'November', 'December',\n];\n\nconst MONTHS_FULL_LOWERCASE = MONTHS_FULL.map((month) => month.toLowerCase());\nconst MIN_SEARCH_YEAR = 2015;\nconst MAX_DAY_IN_MONTH = 31;\nconst MAX_MONTH_IN_YEAR = 12;\nexport const MILISECONDS_IN_DAY = 24 * 60 * 60 * 1000;\n\nexport function getDayStart(datetime: number | Date) {\n const date = new Date(datetime);\n date.setHours(0, 0, 0, 0);\n return date;\n}\n\nexport function getDayStartAt(datetime: number | Date) {\n return getDayStart(datetime).getTime();\n}\n\nexport function toYearMonth(timestamp: number) {\n const date = new Date(timestamp * 1000);\n return `${date.getFullYear()}-${date.getMonth()}`;\n}\n\nfunction toIsoString(date: Date) {\n return `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`;\n}\n\nexport function formatTime(datetime: number | Date) {\n const date = typeof datetime === 'number' ? new Date(datetime) : datetime;\n const hours = String(date.getHours()).padStart(2, '0');\n const minutes = String(date.getMinutes()).padStart(2, '0');\n\n return `${hours}:${minutes}`;\n}\n\nexport function formatPastTimeShort(lang: LangFn, datetime: number | Date) {\n const date = typeof datetime === 'number' ? new Date(datetime) : datetime;\n\n const today = getDayStart(new Date());\n if (date >= today) {\n return formatTime(date);\n }\n\n const weekAgo = new Date(today);\n weekAgo.setDate(today.getDate() - 7);\n if (date >= weekAgo) {\n return lang(`Weekday.Short${WEEKDAYS_FULL[date.getDay()]}`);\n }\n\n const withYear = date.getFullYear() !== today.getFullYear();\n const format = (\n lang(withYear ? 'formatDateScheduleYear' : 'formatDateSchedule')\n || (withYear ? 'd MMM yyyy' : 'd MMM')\n );\n\n return formatDate(lang, date, format);\n}\n\nexport function formatFullDate(lang: LangFn, datetime: number | Date) {\n const date = typeof datetime === 'number' ? new Date(datetime) : datetime;\n const format = lang('formatterYearMax') || 'dd.MM.yyyy';\n\n return formatDate(lang, date, format);\n}\n\nexport function formatMonthAndYear(lang: LangFn, date: Date, isShort = false) {\n const format = lang(isShort ? 'formatterMonthYear2' : 'formatterMonthYear') || 'MMM yyyy';\n\n return formatDate(lang, date, format);\n}\n\nexport function formatHumanDate(lang: LangFn, datetime: number | Date, isShort = false, noWeekdays = false) {\n const date = typeof datetime === 'number' ? new Date(datetime) : datetime;\n\n const today = getDayStart(new Date());\n\n if (!noWeekdays) {\n if (toIsoString(date) === toIsoString(today)) {\n return (isShort ? lowerFirst : upperFirst)(lang('Weekday.Today'));\n }\n\n const yesterday = new Date(today);\n yesterday.setDate(today.getDate() - 1);\n if (toIsoString(date) === toIsoString(yesterday)) {\n return (isShort ? lowerFirst : upperFirst)(lang('Weekday.Yesterday'));\n }\n\n const weekAgo = new Date(today);\n const weekAhead = new Date(today);\n weekAgo.setDate(today.getDate() - 7);\n weekAhead.setDate(today.getDate() + 7);\n if (date >= weekAgo && date <= weekAhead) {\n const weekDay = WEEKDAYS_FULL[date.getDay()];\n return isShort\n ? lowerFirst(lang(`Weekday.Short${weekDay}`))\n : upperFirst(lang(`Weekday.${weekDay}`));\n }\n }\n\n const withYear = date.getFullYear() !== today.getFullYear();\n const formatKey = isShort\n ? (withYear ? 'formatDateScheduleYear' : 'formatDateSchedule')\n : (withYear ? 'chatFullDate' : 'chatDate');\n const format = lang(formatKey) || 'd MMMM yyyy';\n\n return (isShort ? lowerFirst : upperFirst)(formatDate(lang, date, format));\n}\n\nfunction formatDate(lang: LangFn, date: Date, format: string) {\n const day = date.getDate();\n const monthIndex = date.getMonth();\n\n return format\n .replace('LLLL', lang(MONTHS_FULL[monthIndex]))\n .replace('MMMM', lang(`Month.Gen${MONTHS_FULL[monthIndex]}`))\n .replace('MMM', lang(`Month.Short${MONTHS_FULL[monthIndex]}`))\n .replace('MM', String(monthIndex + 1).padStart(2, '0'))\n .replace('dd', String(day).padStart(2, '0'))\n .replace('d', String(day))\n .replace('yyyy', String(date.getFullYear()));\n}\n\nexport function formatMediaDateTime(lang: LangFn, datetime: number | Date) {\n const date = typeof datetime === 'number' ? new Date(datetime) : datetime;\n\n return `${formatHumanDate(lang, date, true)}, ${formatTime(date)}`;\n}\n\nexport function formatMediaDuration(duration: number) {\n const hours = Math.floor(duration / 3600);\n const minutes = Math.floor((duration % 3600) / 60);\n const seconds = Math.floor(duration % 3600 % 60);\n\n let string = '';\n if (hours > 0) {\n string += `${String(hours).padStart(2, '0')}:`;\n string += `${String(minutes).padStart(2, '0')}:`;\n } else {\n string += `${String(minutes)}:`;\n }\n string += String(seconds).padStart(2, '0');\n\n return string;\n}\n\nexport function formatVoiceRecordDuration(durationInMs: number) {\n const parts = [];\n\n let milliseconds = durationInMs % 1000;\n durationInMs -= milliseconds;\n milliseconds = Math.floor(milliseconds / 10);\n\n durationInMs = Math.floor(durationInMs / 1000);\n const seconds = durationInMs % 60;\n durationInMs -= seconds;\n\n durationInMs = Math.floor(durationInMs / 60);\n const minutes = durationInMs % 60;\n durationInMs -= minutes;\n\n durationInMs = Math.floor(durationInMs / 60);\n const hours = durationInMs % 60;\n\n if (hours > 0) {\n parts.push(String(hours).padStart(2, '0'));\n }\n parts.push(String(minutes).padStart(hours > 0 ? 2 : 1, '0'));\n parts.push(String(seconds).padStart(2, '0'));\n\n return `${parts.join(':')},${String(milliseconds).padStart(2, '0')}`;\n}\n\nexport function formatDateToString(date: Date, locale = 'en-US') {\n return date.toLocaleString(\n locale,\n {\n year: 'numeric',\n month: 'short',\n day: 'numeric',\n },\n );\n}\n\nfunction isValidDate(day: number, month: number, year = 2021): boolean {\n if (month > (MAX_MONTH_IN_YEAR - 1) || day > MAX_DAY_IN_MONTH) {\n return false;\n }\n const date = new Date(year, month, day);\n return !Number.isNaN(date.getTime()) && date.getDate() === day;\n}\n\nexport function parseDateString(query = ''): string | undefined {\n const matchStringDate = query.match(/\\d{1,2}\\s[a-zA-Z]{3,}/);\n const matchEuropeStringDate = query.match(/[a-zA-Z]{3,}\\s\\d{1,2}/);\n const matchNumberDate = query.match(/\\d{1,2}[./-]\\d{1,2}([./-]\\d{2,4})?/);\n if (!matchStringDate && !matchNumberDate && !matchEuropeStringDate) {\n return undefined;\n }\n\n if (matchNumberDate) {\n const [date, month, year] = query.split(/[./-]/).map(Number);\n return !(year && year < MIN_SEARCH_YEAR) && isValidDate(date, month - 1, year || undefined)\n ? `${year ? `${year}-` : ''}${String(month).padStart(2, '0')}-${String(date).padStart(2, '0')}`\n : undefined;\n }\n\n const dateParts = query.split(' ');\n const date = matchStringDate ? dateParts[0] : dateParts[1];\n const month = (matchStringDate ? dateParts[1] : dateParts[0]).toLowerCase();\n const monthIndex = MONTHS_FULL_LOWERCASE.findIndex((item) => item.startsWith(month));\n\n return monthIndex !== -1 && isValidDate(Number(date), monthIndex)\n ? `${String(monthIndex + 1).padStart(2, '0')}-${String(date).padStart(2, '0')}`\n : undefined;\n}\n\nexport function timestampPlusDay(timestamp: number) {\n return timestamp + MILISECONDS_IN_DAY / 1000;\n}\n\nfunction lowerFirst(str: string) {\n return `${str[0].toLowerCase()}${str.slice(1)}`;\n}\n\nfunction upperFirst(str: string) {\n return `${str[0].toUpperCase()}${str.slice(1)}`;\n}\n","// Due to the fact that emoji from Apple do not contain some characters, it is necessary to remove them from emoji-data\n// https://github.com/iamcal/emoji-data/issues/136\nconst EXCLUDE_EMOJIS = ['female_sign', 'male_sign', 'medical_symbol'];\n\nexport type EmojiRawData = typeof import('emoji-data-ios/emoji-data.json');\nexport type EmojiModule = { default: EmojiRawData };\n\nexport type EmojiData = {\n categories: Array<EmojiCategory>;\n emojis: Record<string, Emoji>;\n};\n\nfunction unifiedToNative(unified: string) {\n const unicodes = unified.split('-');\n const codePoints = unicodes.map((i) => parseInt(i, 16));\n\n return String.fromCodePoint(...codePoints);\n}\n\nexport function nativeToUnfified(emoji: string) {\n let code;\n\n if (emoji.length === 1) {\n code = emoji.charCodeAt(0).toString(16).padStart(4, '0');\n } else {\n const pairs = [];\n for (let i = 0; i < emoji.length; i++) {\n if (emoji.charCodeAt(i) >= 0xd800 && emoji.charCodeAt(i) <= 0xdbff) {\n if (emoji.charCodeAt(i + 1) >= 0xdc00 && emoji.charCodeAt(i + 1) <= 0xdfff) {\n pairs.push(\n (emoji.charCodeAt(i) - 0xd800) * 0x400\n + (emoji.charCodeAt(i + 1) - 0xdc00) + 0x10000,\n );\n }\n } else if (emoji.charCodeAt(i) < 0xd800 || emoji.charCodeAt(i) > 0xdfff) {\n pairs.push(emoji.charCodeAt(i));\n }\n }\n\n code = pairs.map((x) => x.toString(16).padStart(4, '0')).join('-');\n }\n\n return code;\n}\n\nexport function uncompressEmoji(data: EmojiRawData): EmojiData {\n const emojiData: EmojiData = { categories: [], emojis: {} };\n\n for (let i = 0; i < data.length; i += 2) {\n const category = {\n id: data[i][0],\n name: data[i][1],\n emojis: [],\n } as EmojiCategory;\n\n for (let j = 0; j < data[i + 1].length; j++) {\n const emojiRaw = data[i + 1][j];\n if (!EXCLUDE_EMOJIS.includes(emojiRaw[1][0])) {\n category.emojis.push(emojiRaw[1][0]);\n emojiData.emojis[emojiRaw[1][0]] = {\n id: emojiRaw[1][0],\n names: emojiRaw[1] as string[],\n native: unifiedToNative(emojiRaw[0] as string),\n image: (emojiRaw[0] as string).toLowerCase(),\n };\n }\n }\n\n emojiData.categories.push(category);\n }\n\n return emojiData;\n}\n","let isWebpSupportedCache: boolean | undefined;\n\nexport function isWebpSupported() {\n return Boolean(isWebpSupportedCache);\n}\n\nfunction testWebp(): Promise<boolean> {\n return new Promise((resolve) => {\n const webp = new Image();\n // eslint-disable-next-line max-len\n webp.src = 'data:image/webp;base64,UklGRjoAAABXRUJQVlA4IC4AAACyAgCdASoCAAIALmk0mk0iIiIiIgBoSygABc6WWgAA/veff/0PP8bA//LwYAAA';\n const handleLoadOrError = () => {\n resolve(webp.height === 2);\n };\n webp.onload = handleLoadOrError;\n webp.onerror = handleLoadOrError;\n });\n}\n\ntestWebp().then((hasWebp) => {\n isWebpSupportedCache = hasWebp;\n});\n","import { ThemeKey } from '../types';\n\nlet systemThemeCache: ThemeKey = (\n window && window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches\n) ? 'dark' : 'light';\n\nexport function getSystemTheme() {\n return systemThemeCache;\n}\n\nfunction handleSystemThemeChange(e: MediaQueryListEventMap['change']) {\n systemThemeCache = e.matches ? 'dark' : 'light';\n}\n\nconst mql = window.matchMedia('(prefers-color-scheme: dark)');\nif (typeof mql.addEventListener === 'function') {\n mql.addEventListener('change', handleSystemThemeChange);\n} else if (typeof mql.addListener === 'function') {\n mql.addListener(handleSystemThemeChange);\n}\n","import {\n MIN_SCREEN_WIDTH_FOR_STATIC_LEFT_COLUMN,\n MOBILE_SCREEN_MAX_WIDTH,\n MOBILE_SCREEN_LANDSCAPE_MAX_HEIGHT,\n MOBILE_SCREEN_LANDSCAPE_MAX_WIDTH,\n IS_TEST,\n} from '../config';\n\nexport * from './environmentWebp';\n\nexport * from './environmentSystemTheme';\n\nexport function getPlatform() {\n const { userAgent, platform } = window.navigator;\n const macosPlatforms = ['Macintosh', 'MacIntel', 'MacPPC', 'Mac68K'];\n const windowsPlatforms = ['Win32', 'Win64', 'Windows', 'WinCE'];\n const iosPlatforms = ['iPhone', 'iPad', 'iPod'];\n let os: 'macOS' | 'iOS' | 'Windows' | 'Android' | 'Linux' | undefined;\n\n if (macosPlatforms.indexOf(platform) !== -1) {\n os = 'macOS';\n } else if (iosPlatforms.indexOf(platform) !== -1) {\n os = 'iOS';\n } else if (windowsPlatforms.indexOf(platform) !== -1) {\n os = 'Windows';\n } else if (/Android/.test(userAgent)) {\n os = 'Android';\n } else if (/Linux/.test(platform)) {\n os = 'Linux';\n }\n\n return os;\n}\n\nexport const PLATFORM_ENV = getPlatform();\nexport const IS_MAC_OS = PLATFORM_ENV === 'macOS';\nexport const IS_IOS = PLATFORM_ENV === 'iOS';\nexport const IS_ANDROID = PLATFORM_ENV === 'Android';\nexport const IS_SAFARI = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);\nexport const IS_PWA = window.matchMedia('(display-mode: standalone)').matches\n|| (window.navigator as any).standalone\n|| document.referrer.includes('android-app://');\n\nexport const IS_TOUCH_ENV = window.matchMedia('(pointer: coarse)').matches;\n// Keep in mind the landscape orientation\nexport const IS_SINGLE_COLUMN_LAYOUT = window.innerWidth <= MOBILE_SCREEN_MAX_WIDTH || (\n window.innerWidth <= MOBILE_SCREEN_LANDSCAPE_MAX_WIDTH && window.innerHeight <= MOBILE_SCREEN_LANDSCAPE_MAX_HEIGHT\n);\n// Special layout, 1 column while chat opened, 2 columns while collapsed\nexport const IS_TABLET_COLUMN_LAYOUT = !IS_SINGLE_COLUMN_LAYOUT && (\n window.innerWidth <= MIN_SCREEN_WIDTH_FOR_STATIC_LEFT_COLUMN\n);\nexport const IS_VOICE_RECORDING_SUPPORTED = (navigator.mediaDevices && 'getUserMedia' in navigator.mediaDevices && (\n window.AudioContext || (window as any).webkitAudioContext\n));\nexport const IS_SMOOTH_SCROLL_SUPPORTED = 'scrollBehavior' in document.documentElement.style;\nexport const IS_EMOJI_SUPPORTED = PLATFORM_ENV && (IS_MAC_OS || IS_IOS);\nexport const IS_SERVICE_WORKER_SUPPORTED = 'serviceWorker' in navigator;\n// TODO Consider failed service worker\nexport const IS_PROGRESSIVE_SUPPORTED = IS_SERVICE_WORKER_SUPPORTED;\nexport const IS_STREAMING_SUPPORTED = 'MediaSource' in window;\nexport const IS_OPUS_SUPPORTED = Boolean((new Audio()).canPlayType('audio/ogg; codecs=opus'));\nexport const IS_CANVAS_FILTER_SUPPORTED = (\n !IS_TEST && 'filter' in (document.createElement('canvas').getContext('2d') || {})\n);\nexport const LAYERS_ANIMATION_NAME = IS_ANDROID ? 'slide-fade' : IS_IOS ? 'slide-layers' : 'push-slide';\n\nexport const DPR = window.devicePixelRatio || 1;\n\nexport const MASK_IMAGE_DISABLED = true;\n","import { 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 | undefined>((resolve, reject) => {\n video.onseeked = () => {\n if (!video.videoWidth || !video.videoHeight) {\n resolve(undefined);\n }\n\n const canvas = document.createElement('canvas');\n canvas.width = video.videoWidth;\n canvas.height = video.videoHeight;\n const ctx = canvas.getContext('2d')!;\n ctx.drawImage(video, 0, 0);\n resolve(canvas.toDataURL('image/jpeg'));\n };\n video.onerror = reject;\n video.currentTime = Math.min(video.duration, 1);\n }),\n ]);\n}\n\nexport async function fetchBlob(blobUrl: string) {\n const response = await fetch(blobUrl);\n return response.blob();\n}\n\nexport async function fetchFile(blobUrl: string, fileName: string) {\n const blob = await fetchBlob(blobUrl);\n return blobToFile(blob, fileName);\n}\n\nexport function imgToCanvas(img: HTMLImageElement) {\n const canvas = document.createElement('canvas');\n canvas.width = img.width;\n canvas.height = img.height;\n\n const ctx = canvas.getContext('2d')!;\n ctx.drawImage(img, 0, 0);\n\n return canvas;\n}\n","import { LangCode } from '../types';\n\nexport function formatCurrency(totalPrice: number, currency?: string, locale: LangCode = 'en') {\n return new Intl.NumberFormat(locale, {\n style: 'currency',\n currency,\n }).format(currency === 'JPY' ? totalPrice : totalPrice / 100);\n}\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 { ApiError, ApiFieldError } from '../api/types';\n\nconst READABLE_ERROR_MESSAGES: Record<string, string> = {\n CHAT_RESTRICTED: 'You can\\'t send messages in this chat, you were restricted',\n CHAT_WRITE_FORBIDDEN: 'You can\\'t write in this chat',\n CHAT_SEND_POLL_FORBIDDEN: 'You can\\'t create polls in this chat',\n CHAT_SEND_STICKERS_FORBIDDEN: 'You can\\'t send stickers in this chat',\n CHAT_SEND_GIFS_FORBIDDEN: 'You can\\'t send gifs in this chat',\n CHAT_SEND_MEDIA_FORBIDDEN: 'You can\\'t send media in this chat',\n CHAT_LINK_EXISTS: 'The chat is public, you can\\'t hide the history to new users',\n // eslint-disable-next-line max-len\n SLOWMODE_WAIT_X: 'Slowmode is enabled in this chat: you must wait for the specified number of seconds before sending another message to the chat.',\n USER_BANNED_IN_CHANNEL: 'You\\'re banned from sending messages in supergroups / channels',\n USER_IS_BLOCKED: 'You were blocked by this user',\n YOU_BLOCKED_USER: 'You blocked this user',\n IMAGE_PROCESS_FAILED: 'Failure while processing image',\n MEDIA_EMPTY: 'The provided media object is invalid',\n MEDIA_INVALID: 'Media invalid',\n PHOTO_EXT_INVALID: 'The extension of the photo is invalid',\n PHOTO_INVALID_DIMENSIONS: 'The photo dimensions are invalid',\n PHOTO_SAVE_FILE_INVALID: 'Internal issues, try again later',\n // eslint-disable-next-line max-len\n MESSAGE_DELETE_FORBIDDEN: 'You can\\'t delete one of the messages you tried to delete, most likely because it is a service message.',\n MESSAGE_POLL_CLOSED: 'Poll closed',\n MESSAGE_EDIT_TIME_EXPIRED: 'You can\\'t edit this message anymore.',\n CHAT_ADMIN_REQUIRED: 'You must be an admin in this chat to do this',\n PINNED_DIALOGS_TOO_MUCH: 'Sorry, you can only pin 5 chats to the top',\n DIALOG_FILTERS_TOO_MUCH: 'Sorry, you can\\'t have more than 10 folders',\n CHANNEL_PRIVATE: 'This channel is private',\n MEDIA_CAPTION_TOO_LONG: 'The provided caption is too long',\n ADDRESS_STREET_LINE1_INVALID: 'The address you provided is not valid',\n ADDRESS_STREET_LINE2_INVALID: 'The address you provided is not valid',\n ADDRESS_CITY_INVALID: 'The city you provided is not valid',\n ADDRESS_COUNTRY_INVALID: 'The country you provided is not valid',\n ADDRESS_POSTCODE_INVALID: 'The postcode you provided is not valid',\n ADDRESS_STATE_INVALID: 'The state you provided is not valid',\n REQ_INFO_NAME_INVALID: 'The name you provided is not valid',\n REQ_INFO_PHONE_INVALID: 'The phone you provided is not valid',\n REQ_INFO_EMAIL_INVALID: 'The email you provided is not valid',\n // TODO Bring back after fixing the weird bug\n // CHANNEL_INVALID: 'An error occurred. Please try again later',\n LINK_NOT_MODIFIED: 'This discussion is already linked to the channel',\n\n // Non-API errors\n SERVICE_WORKER_DISABLED: 'Service Worker is disabled. Please reload the page without holding <Shift> key.',\n // eslint-disable-next-line max-len\n CAPTION_TOO_LONG_PLEASE_REMOVE_CHARACTERS: 'The provided caption is too long. Please remove {EXTRA_CHARS_COUNT} character{PLURAL_S}.',\n // eslint-disable-next-line max-len\n FRESH_RESET_AUTHORISATION_FORBIDDEN: 'You can’t logout other sessions if less than 24 hours have passed since you logged on the current session',\n\n BOTS_TOO_MUCH: 'There are too many bots in this chat/channel',\n BOT_GROUPS_BLOCKED: 'This bot can\\'t be added to groups',\n USERS_TOO_MUCH: 'The maximum number of users has been exceeded',\n USER_CHANNELS_TOO_MUCH: 'One of the users you tried to add is already in too many channels/supergroups',\n USER_KICKED: 'This user was kicked from this supergroup/channel',\n USER_NOT_MUTUAL_CONTACT: 'The provided user is not a mutual contact',\n USER_PRIVACY_RESTRICTED: 'The user\\'s privacy settings do not allow you to do this',\n INVITE_HASH_EMPTY: 'The invite hash is empty',\n INVITE_HASH_EXPIRED: 'The invite link has expired',\n INVITE_HASH_INVALID: 'The invite hash is invalid',\n CHANNELS_TOO_MUCH: 'You have joined too many channels/supergroups',\n USER_ALREADY_PARTICIPANT: 'You already in the group',\n SCHEDULE_DATE_INVALID: 'Invalid schedule date provided',\n WALLPAPER_DIMENSIONS_INVALID: 'The wallpaper dimensions are invalid, please select another file',\n};\n\nexport const SHIPPING_ERRORS: Record<string, ApiFieldError> = {\n ADDRESS_STREET_LINE1_INVALID: {\n field: 'streetLine1',\n message: 'Incorrect street address',\n },\n ADDRESS_STREET_LINE2_INVALID: {\n field: 'streetLine2',\n message: 'Incorrect street address',\n },\n ADDRESS_CITY_INVALID: {\n field: 'city',\n message: 'Incorrect city',\n },\n ADDRESS_COUNTRY_INVALID: {\n field: 'countryIso2',\n message: 'Incorrect country',\n },\n ADDRESS_POSTCODE_INVALID: {\n field: 'postCode',\n message: 'Incorrect post code',\n },\n ADDRESS_STATE_INVALID: {\n field: 'state',\n message: 'Incorrect state',\n },\n REQ_INFO_NAME_INVALID: {\n field: 'fullName',\n message: 'Incorrect name',\n },\n REQ_INFO_PHONE_INVALID: {\n field: 'phone',\n message: 'Incorrect phone',\n },\n REQ_INFO_EMAIL_INVALID: {\n field: 'email',\n message: 'Incorrect email',\n },\n};\n\nexport default function getReadableErrorText(error: ApiError) {\n const { message, isSlowMode, textParams } = error;\n // Currently, Telegram API doesn't return `SLOWMODE_WAIT_X` error as described in the docs\n if (isSlowMode) {\n const extraPartIndex = message.indexOf(' (caused by');\n return extraPartIndex > 0 ? message.substring(0, extraPartIndex) : message;\n }\n let errorMessage = READABLE_ERROR_MESSAGES[message];\n if (errorMessage && textParams) {\n errorMessage = Object.keys(textParams).reduce((acc, current) => {\n return acc.replace(current, textParams[current]);\n }, errorMessage as string);\n }\n return errorMessage;\n}\n\nexport function getShippingError(error: ApiError): ApiFieldError | undefined {\n return SHIPPING_ERRORS[error.message];\n}\n","import { DEBUG_ALERT_MSG } from '../config';\nimport { throttle } from './schedulers';\n\nwindow.addEventListener('error', handleErrorEvent);\nwindow.addEventListener('unhandledrejection', handleErrorEvent);\n\n// eslint-disable-next-line prefer-destructuring\nconst APP_ENV = process.env.APP_ENV;\n\nfunction handleErrorEvent(e: ErrorEvent | PromiseRejectionEvent) {\n e.preventDefault();\n\n handleError(e instanceof ErrorEvent ? e.error : e.reason);\n}\n\nconst throttledAlert = throttle(window.alert, 1000);\n\nexport function handleError(err: Error) {\n // eslint-disable-next-line no-console\n console.error(err);\n\n if (APP_ENV === 'development' || APP_ENV === 'staging') {\n throttledAlert(`${DEBUG_ALERT_MSG}\\n\\n${(err && err.message) || err}\\n${err && err.stack}`);\n }\n}\n","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 { getGlobal } from '../lib/teact/teactn';\n\nimport { ApiLangPack, ApiLangString } from '../api/types';\nimport { LangCode } from '../types';\n\nimport {\n DEFAULT_LANG_CODE, DEFAULT_LANG_PACK, LANG_CACHE_NAME, LANG_PACKS,\n} from '../config';\nimport * as cacheApi from './cacheApi';\nimport { callApi } from '../api/gramjs';\nimport { createCallbackManager } from './callbacks';\nimport { formatInteger } from './textFormat';\n\ninterface LangFn {\n (key: string, value?: any, format?: 'i'): any;\n\n isRtl?: boolean;\n code?: LangCode;\n}\n\nconst SUBSTITUTION_REGEX = /%\\d?\\$?[sdf@]/g;\nconst PLURAL_OPTIONS = ['value', 'zeroValue', 'oneValue', 'twoValue', 'fewValue', 'manyValue', 'otherValue'] as const;\nconst PLURAL_RULES = {\n /* eslint-disable max-len */\n en: (n: number) => (n !== 1 ? 6 : 2),\n ar: (n: number) => (n === 0 ? 1 : n === 1 ? 2 : n === 2 ? 3 : n % 100 >= 3 && n % 100 <= 10 ? 4 : n % 100 >= 11 ? 5 : 6),\n ca: (n: number) => (n !== 1 ? 6 : 2),\n de: (n: number) => (n !== 1 ? 6 : 2),\n es: (n: number) => (n !== 1 ? 6 : 2),\n fa: (n: number) => (n > 1 ? 6 : 2),\n fr: (n: number) => (n > 1 ? 6 : 2),\n id: () => 0,\n it: (n: number) => (n !== 1 ? 6 : 2),\n ko: () => 0,\n ms: () => 0,\n nl: (n: number) => (n !== 1 ? 6 : 2),\n pl: (n: number) => (n === 1 ? 2 : n % 10 >= 2 && n % 10 <= 4 && (n % 100 < 10 || n % 100 >= 20) ? 4 : 5),\n pt_BR: (n: number) => (n > 1 ? 6 : 2),\n ru: (n: number) => (n % 10 === 1 && n % 100 !== 11 ? 2 : n % 10 >= 2 && n % 10 <= 4 && (n % 100 < 10 || n % 100 >= 20) ? 4 : 5),\n tr: (n: number) => (n > 1 ? 6 : 2),\n uk: (n: number) => (n % 10 === 1 && n % 100 !== 11 ? 2 : n % 10 >= 2 && n % 10 <= 4 && (n % 100 < 10 || n % 100 >= 20) ? 4 : 5),\n uz: (n: number) => (n > 1 ? 6 : 2),\n /* eslint-enable max-len */\n};\n\nconst cache = new Map<string, string>();\n\nlet langPack: ApiLangPack | undefined;\nlet fallbackLangPack: ApiLangPack | undefined;\n\nconst {\n addCallback,\n removeCallback,\n runCallbacks,\n} = createCallbackManager();\n\nexport { addCallback, removeCallback };\n\nlet currentLangCode: string | undefined;\n\nexport const getTranslation: LangFn = (key: string, value?: any, format?: 'i') => {\n if (value !== undefined) {\n const cacheValue = Array.isArray(value) ? JSON.stringify(value) : value;\n const cached = cache.get(`${key}_${cacheValue}_${format}`);\n if (cached) {\n return cached;\n }\n }\n\n if (!langPack && !fallbackLangPack) {\n return key;\n }\n\n const langString = (langPack && langPack[key]) || (fallbackLangPack && fallbackLangPack[key]);\n if (!langString) {\n if (!fallbackLangPack) {\n void importFallbackLangPack();\n }\n\n return key;\n }\n\n return processTranslation(langString, key, value, format);\n};\n\nexport async function getTranslationForLangString(langCode: string, key: string) {\n let translateString = await cacheApi.fetch(\n LANG_CACHE_NAME,\n `${DEFAULT_LANG_PACK}_${langCode}_${key}`,\n cacheApi.Type.Json,\n );\n\n if (!translateString) {\n translateString = await fetchRemoteString(DEFAULT_LANG_PACK, langCode, key);\n }\n\n return processTranslation(translateString, key);\n}\n\nexport async function setLanguage(langCode: LangCode, callback?: NoneToVoidFunction, withFallback = false) {\n if (langPack && langCode === currentLangCode) {\n if (callback) {\n callback();\n }\n\n return;\n }\n\n let newLangPack = await cacheApi.fetch(LANG_CACHE_NAME, langCode, cacheApi.Type.Json);\n if (!newLangPack) {\n if (withFallback) {\n await importFallbackLangPack();\n }\n\n newLangPack = await fetchRemote(langCode);\n if (!newLangPack) {\n return;\n }\n }\n\n cache.clear();\n\n currentLangCode = langCode;\n langPack = newLangPack;\n document.documentElement.lang = langCode;\n\n const { languages } = getGlobal().settings.byKey;\n const langInfo = languages ? languages.find((l) => l.langCode === langCode) : undefined;\n getTranslation.isRtl = Boolean(langInfo && langInfo.rtl);\n getTranslation.code = langCode;\n\n if (callback) {\n callback();\n }\n\n runCallbacks();\n}\n\nasync function importFallbackLangPack() {\n if (fallbackLangPack) {\n return;\n }\n\n fallbackLangPack = (await import('./fallbackLangPack')).default;\n runCallbacks();\n}\n\nasync function fetchRemote(langCode: string): Promise<ApiLangPack | undefined> {\n const remote = await callApi('fetchLangPack', { sourceLangPacks: LANG_PACKS, langCode });\n if (remote) {\n await cacheApi.save(LANG_CACHE_NAME, langCode, remote.langPack);\n return remote.langPack;\n }\n\n return undefined;\n}\n\nasync function fetchRemoteString(\n remoteLangPack: typeof LANG_PACKS[number], langCode: string, key: string,\n): Promise<string | undefined> {\n const remote = await callApi('fetchLangStrings', {\n langPack: remoteLangPack,\n langCode,\n keys: [key],\n });\n\n if (remote && remote.length) {\n await cacheApi.save(LANG_CACHE_NAME, `${remoteLangPack}_${langCode}_${key}`, remote[0]);\n\n return remote[0];\n }\n\n return undefined;\n}\n\nfunction getPluralOption(amount: number) {\n const langCode = currentLangCode || DEFAULT_LANG_CODE;\n const optionIndex = PLURAL_RULES[langCode as keyof typeof PLURAL_RULES]\n ? PLURAL_RULES[langCode as keyof typeof PLURAL_RULES](amount)\n : 0;\n\n return PLURAL_OPTIONS[optionIndex];\n}\n\nfunction processTemplate(template: string, value: any) {\n value = Array.isArray(value) ? value : [value];\n const translationSlices = template.split(SUBSTITUTION_REGEX);\n const initialValue = translationSlices.shift();\n\n return translationSlices.reduce((result, str, index) => {\n return `${result}${String(value[index] || '')}${str}`;\n }, initialValue || '');\n}\n\nfunction processTranslation(langString: ApiLangString | undefined, key: string, value?: any, format?: 'i') {\n const template = langString ? langString[typeof value === 'number' ? getPluralOption(value) : 'value'] : undefined;\n if (!template || !template.trim()) {\n const parts = key.split('.');\n\n return parts[parts.length - 1];\n }\n\n if (value !== undefined) {\n const formattedValue = format === 'i' ? formatInteger(value) : value;\n const result = processTemplate(template, formattedValue);\n const cacheValue = Array.isArray(value) ? JSON.stringify(value) : value;\n cache.set(`${key}_${cacheValue}_${format}`, result);\n return result;\n }\n\n return template;\n}\n","export function createCallbackManager() {\n const callbacks: AnyToVoidFunction[] = [];\n\n function addCallback(cb: AnyToVoidFunction) {\n callbacks.push(cb);\n\n return () => {\n removeCallback(cb);\n };\n }\n\n function removeCallback(cb: AnyToVoidFunction) {\n const index = callbacks.indexOf(cb);\n if (index !== -1) {\n callbacks.splice(index, 1);\n }\n }\n\n function runCallbacks(...args: any[]) {\n callbacks.forEach((callback) => {\n callback(...args);\n });\n }\n\n return {\n runCallbacks,\n addCallback,\n removeCallback,\n };\n}\n","const 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: Worker | undefined = new Worker(\n new URL('opus-recorder/dist/decoderWorker.min.js', import.meta.url),\n );\n let wavWorker: Worker | undefined = new Worker(new URL('opus-recorder/dist/waveWorker.min.js', import.meta.url));\n\n decoderWorker.onmessage = (e) => {\n // eslint-disable-next-line no-null/no-null\n if (e.data === null) {\n // `null` means decoder is finished\n wavWorker!.postMessage({ command: 'done' });\n } else {\n // `e.data` contains decoded buffers as float32 values\n wavWorker!.postMessage(\n {\n command: 'encode',\n buffers: e.data,\n },\n e.data.map(({ buffer }: Float32Array) => buffer),\n );\n }\n };\n\n wavWorker.onmessage = (e) => {\n if (e.data.message === 'page') {\n resolve(new Blob([e.data.page], { type: 'audio/wav' }));\n\n decoderWorker!.terminate();\n decoderWorker = undefined;\n wavWorker!.terminate();\n wavWorker = undefined;\n }\n };\n\n wavWorker.postMessage({\n command: 'init',\n wavBitDepth: BIT_DEPTH,\n wavSampleRate: SAMPLE_RATE,\n });\n\n decoderWorker.postMessage({\n command: 'init',\n decoderSampleRate: SAMPLE_RATE,\n outputBufferSampleRate: SAMPLE_RATE,\n });\n\n decoderWorker.postMessage({\n command: 'decode',\n pages: typedArray,\n }, [typedArray.buffer]);\n });\n}\n","import {\n ApiMediaFormat,\n ApiMediaFormatToPrepared,\n ApiOnProgress,\n ApiParsedMedia,\n ApiPreparedMedia,\n} from '../api/types';\n\nimport {\n DEBUG, MEDIA_CACHE_DISABLED, MEDIA_CACHE_NAME, MEDIA_CACHE_NAME_AVATARS, TRANSPARENT_PIXEL,\n} from '../config';\nimport { callApi, cancelApiProgress } from '../api/gramjs';\nimport * as cacheApi from './cacheApi';\nimport { dataUriToBlob, fetchBlob } from './files';\nimport { IS_OPUS_SUPPORTED, IS_PROGRESSIVE_SUPPORTED, isWebpSupported } from './environment';\nimport { oggToWav } from './oggToWav';\nimport { webpToPng } from './webpToPng';\n\nconst asCacheApiType = {\n [ApiMediaFormat.DataUri]: cacheApi.Type.Text,\n [ApiMediaFormat.BlobUrl]: cacheApi.Type.Blob,\n [ApiMediaFormat.Lottie]: cacheApi.Type.Json,\n [ApiMediaFormat.Progressive]: undefined,\n [ApiMediaFormat.Stream]: undefined,\n};\n\nconst PROGRESSIVE_URL_PREFIX = './progressive/';\n\nconst memoryCache = new Map<string, ApiPreparedMedia>();\nconst fetchPromises = new Map<string, Promise<ApiPreparedMedia | undefined>>();\n\nexport function fetch<T extends ApiMediaFormat>(\n url: string, mediaFormat: T, onProgress?: ApiOnProgress,\n): Promise<ApiMediaFormatToPrepared<T>> {\n if (mediaFormat === ApiMediaFormat.Progressive) {\n return (\n IS_PROGRESSIVE_SUPPORTED\n ? getProgressive(url)\n : fetch(url, ApiMediaFormat.BlobUrl, onProgress)\n ) as Promise<ApiMediaFormatToPrepared<T>>;\n }\n\n if (!fetchPromises.has(url)) {\n const promise = fetchFromCacheOrRemote(url, mediaFormat, onProgress)\n .catch((err) => {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.warn(err);\n }\n\n return undefined;\n })\n .finally(() => {\n fetchPromises.delete(url);\n });\n\n fetchPromises.set(url, promise);\n }\n\n return fetchPromises.get(url) as Promise<ApiMediaFormatToPrepared<T>>;\n}\n\nexport function getFromMemory<T extends ApiMediaFormat>(url: string) {\n return memoryCache.get(url) as ApiMediaFormatToPrepared<T>;\n}\n\nexport function cancelProgress(progressCallback: ApiOnProgress) {\n cancelApiProgress(progressCallback);\n}\n\nfunction getProgressive(url: string) {\n const progressiveUrl = `${PROGRESSIVE_URL_PREFIX}${url}`;\n\n memoryCache.set(url, progressiveUrl);\n\n return Promise.resolve(progressiveUrl);\n}\n\nasync function fetchFromCacheOrRemote(url: string, mediaFormat: ApiMediaFormat, onProgress?: ApiOnProgress) {\n if (!MEDIA_CACHE_DISABLED) {\n const cacheName = url.startsWith('avatar') ? MEDIA_CACHE_NAME_AVATARS : MEDIA_CACHE_NAME;\n const cached = await cacheApi.fetch(cacheName, url, asCacheApiType[mediaFormat]!);\n if (cached) {\n let media = cached;\n\n if (cached.type === 'audio/ogg' && !IS_OPUS_SUPPORTED) {\n media = await oggToWav(media);\n }\n\n if (cached.type === 'image/webp' && !isWebpSupported() && media) {\n const mediaPng = await webpToPng(url, media);\n if (mediaPng) {\n media = mediaPng;\n }\n }\n\n const prepared = prepareMedia(media);\n\n memoryCache.set(url, prepared);\n\n return prepared;\n }\n }\n\n if (mediaFormat === ApiMediaFormat.Stream) {\n const mediaSource = new MediaSource();\n const streamUrl = URL.createObjectURL(mediaSource);\n let isOpen = false;\n\n mediaSource.addEventListener('sourceopen', () => {\n if (isOpen) {\n return;\n }\n isOpen = true;\n\n const sourceBuffer = mediaSource.addSourceBuffer('audio/mpeg');\n\n void callApi('downloadMedia', { url, mediaFormat }, (progress: number, arrayBuffer: ArrayBuffer) => {\n if (onProgress) {\n onProgress(progress);\n }\n\n if (progress === 1) {\n mediaSource.endOfStream();\n }\n\n if (!arrayBuffer) {\n return;\n }\n\n sourceBuffer.appendBuffer(arrayBuffer!);\n });\n });\n\n memoryCache.set(url, streamUrl);\n return streamUrl;\n }\n\n const remote = await callApi('downloadMedia', { url, mediaFormat }, onProgress);\n if (!remote) {\n throw new Error('Failed to fetch media');\n }\n\n let { prepared, mimeType } = remote;\n\n if (mimeType === 'audio/ogg' && !IS_OPUS_SUPPORTED) {\n const blob = await fetchBlob(prepared as string);\n URL.revokeObjectURL(prepared as string);\n const media = await oggToWav(blob);\n prepared = prepareMedia(media);\n mimeType = blob.type;\n }\n\n if (mimeType === 'image/webp' && !isWebpSupported()) {\n const blob = await fetchBlob(prepared as string);\n URL.revokeObjectURL(prepared as string);\n const media = await webpToPng(url, blob);\n if (media) {\n prepared = prepareMedia(media);\n }\n }\n\n memoryCache.set(url, prepared);\n\n return prepared;\n}\n\nfunction prepareMedia(mediaData: ApiParsedMedia): ApiPreparedMedia {\n if (mediaData instanceof Blob) {\n // Prevent HTML-in-video attacks\n if (mediaData.type.includes('text/html')) {\n return URL.createObjectURL(dataUriToBlob(TRANSPARENT_PIXEL));\n }\n\n return URL.createObjectURL(mediaData);\n }\n\n return mediaData;\n}\n\nif (IS_PROGRESSIVE_SUPPORTED) {\n navigator.serviceWorker.addEventListener('message', async (e) => {\n const { type, messageId, params } = e.data as {\n type: string;\n messageId: string;\n params: { url: string; start: number; end: number };\n };\n\n if (type !== 'requestPart') {\n return;\n }\n\n const result = await callApi('downloadMedia', { mediaFormat: ApiMediaFormat.Progressive, ...params });\n if (!result) {\n return;\n }\n\n const { arrayBuffer, mimeType, fullSize } = result;\n\n navigator.serviceWorker.controller!.postMessage({\n type: 'partResponse',\n messageId,\n result: {\n arrayBuffer,\n mimeType,\n fullSize,\n },\n }, [arrayBuffer!]);\n });\n}\n","export const MEMO_EMPTY_ARRAY = [];\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","import { callApi } from '../api/gramjs';\nimport {\n ApiChat, ApiMediaFormat, ApiMessage, ApiUser,\n} from '../api/types';\nimport { renderActionMessageText } from '../components/common/helpers/renderActionMessageText';\nimport { APP_NAME, DEBUG } from '../config';\nimport { getDispatch, getGlobal, setGlobal } from '../lib/teact/teactn';\nimport {\n getChatAvatarHash,\n getChatTitle,\n getMessageAction,\n getMessageSenderName,\n getMessageSummaryText,\n getPrivateChatUserId,\n isActionMessage,\n isChatChannel,\n selectIsChatMuted, selectShouldShowMessagePreview,\n} from '../modules/helpers';\nimport { getTranslation } from './langProvider';\nimport { addNotifyExceptions, replaceSettings } from '../modules/reducers';\nimport {\n selectChatMessage, selectNotifyExceptions, selectNotifySettings, selectUser,\n} from '../modules/selectors';\nimport { IS_SERVICE_WORKER_SUPPORTED } from './environment';\nimport * as mediaLoader from './mediaLoader';\nimport { debounce } from './schedulers';\n\nfunction getDeviceToken(subscription: PushSubscription) {\n const data = subscription.toJSON();\n return JSON.stringify({\n endpoint: data.endpoint,\n keys: data.keys,\n });\n}\n\nfunction checkIfPushSupported() {\n if (!IS_SERVICE_WORKER_SUPPORTED) return false;\n if (!('showNotification' in ServiceWorkerRegistration.prototype)) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.warn('[PUSH] Push notifications aren\\'t supported.');\n }\n return false;\n }\n\n // Check the current Notification permission.\n // If its denied, it's a permanent block until the\n // user changes the permission\n if (Notification.permission === 'denied') {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.warn('[PUSH] The user has blocked push notifications.');\n }\n return false;\n }\n\n // Check if push messaging is supported\n if (!('PushManager' in window)) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.warn('[PUSH] Push messaging isn\\'t supported.');\n }\n return false;\n }\n return true;\n}\n\nfunction checkIfNotificationsSupported() {\n // Let's check if the browser supports notifications\n if (!('Notification' in window)) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.warn('[PUSH] This browser does not support desktop notification');\n }\n return false;\n }\n\n if (Notification.permission === 'denied' as NotificationPermission) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.warn('[PUSH] The user has blocked push notifications.');\n }\n return false;\n }\n return true;\n}\n\nconst expirationTime = 12 * 60 * 60 * 1000; // 12 hours\n// Notification id is removed from soundPlayed cache after 3 seconds\nconst soundPlayedDelay = 3 * 1000;\nconst soundPlayed = new Set<number>();\n\nasync function playSound(id: number) {\n if (soundPlayed.has(id)) return;\n const { notificationSoundVolume } = selectNotifySettings(getGlobal());\n const volume = notificationSoundVolume / 10;\n if (volume === 0) return;\n\n const audio = new Audio('/notification.mp3');\n audio.volume = volume;\n audio.setAttribute('mozaudiochannel', 'notification');\n audio.addEventListener('ended', () => {\n soundPlayed.add(id);\n }, { once: true });\n\n setTimeout(() => {\n soundPlayed.delete(id);\n }, soundPlayedDelay);\n\n try {\n await audio.play();\n } catch (error) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.warn('[PUSH] Unable to play notification sound');\n }\n }\n}\n\nexport const playNotificationSound = debounce(playSound, 1000, true, false);\n\nfunction checkIfShouldResubscribe(subscription: PushSubscription | null) {\n const global = getGlobal();\n if (!global.push || !subscription) return true;\n if (getDeviceToken(subscription) !== global.push.deviceToken) return true;\n return Date.now() - global.push.subscribedAt > expirationTime;\n}\n\nasync function requestPermission() {\n if (!('Notification' in window)) return;\n if (!['granted', 'denied'].includes(Notification.permission)) {\n await Notification.requestPermission();\n }\n}\n\nasync function unsubscribeFromPush(subscription: PushSubscription | null) {\n const global = getGlobal();\n const dispatch = getDispatch();\n if (subscription) {\n try {\n const deviceToken = getDeviceToken(subscription);\n await callApi('unregisterDevice', deviceToken);\n await subscription.unsubscribe();\n dispatch.deleteDeviceToken();\n return;\n } catch (error) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('[PUSH] Unable to unsubscribe from push.', error);\n }\n }\n }\n if (global.push) {\n await callApi('unregisterDevice', global.push.deviceToken);\n dispatch.deleteDeviceToken();\n }\n}\n\nexport async function unsubscribe() {\n if (!checkIfPushSupported()) return;\n const serviceWorkerRegistration = await navigator.serviceWorker.ready;\n const subscription = await serviceWorkerRegistration.pushManager.getSubscription();\n await unsubscribeFromPush(subscription);\n}\n\n// Indicates if notification settings are loaded from the api\nlet areSettingsLoaded = false;\n\n// Load notification settings from the api\nasync function loadNotificationSettings() {\n if (areSettingsLoaded) return;\n const [resultSettings, resultExceptions] = await Promise.all([\n callApi('fetchNotificationSettings', {\n serverTimeOffset: getGlobal().serverTimeOffset,\n }),\n callApi('fetchNotificationExceptions', {\n serverTimeOffset: getGlobal().serverTimeOffset,\n }),\n ]);\n if (!resultSettings) return;\n\n let global = replaceSettings(getGlobal(), resultSettings);\n if (resultExceptions) {\n global = addNotifyExceptions(global, resultExceptions);\n }\n setGlobal(global);\n areSettingsLoaded = true;\n}\n\nexport async function subscribe() {\n if (!checkIfPushSupported()) {\n // Ask for notification permissions only if service worker notifications are not supported\n // As pushManager.subscribe automatically triggers permission popup\n await requestPermission();\n return;\n }\n const serviceWorkerRegistration = await navigator.serviceWorker.ready;\n let subscription = await serviceWorkerRegistration.pushManager.getSubscription();\n if (!checkIfShouldResubscribe(subscription)) return;\n await unsubscribeFromPush(subscription);\n try {\n subscription = await serviceWorkerRegistration.pushManager.subscribe({\n userVisibleOnly: true,\n });\n const deviceToken = getDeviceToken(subscription);\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('[PUSH] Received push subscription: ', deviceToken);\n }\n await callApi('registerDevice', deviceToken);\n getDispatch()\n .setDeviceToken(deviceToken);\n } catch (error) {\n if (Notification.permission === 'denied' as NotificationPermission) {\n // The user denied the notification permission which\n // means we failed to subscribe and the user will need\n // to manually change the notification permission to\n // subscribe to push messages\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.warn('[PUSH] The user has blocked push notifications.');\n }\n } else if (DEBUG) {\n // A problem occurred with the subscription, this can\n // often be down to an issue or lack of the gcm_sender_id\n // and / or gcm_user_visible_only\n // eslint-disable-next-line no-console\n console.log('[PUSH] Unable to subscribe to push.', error);\n\n // Request permissions and fall back to local notifications\n // if pushManager.subscribe was aborted due to invalid VAPID key.\n if (error.code === DOMException.ABORT_ERR) {\n await requestPermission();\n }\n }\n }\n}\n\nfunction checkIfShouldNotify(chat: ApiChat, isActive: boolean) {\n if (!areSettingsLoaded) return false;\n const global = getGlobal();\n const isMuted = selectIsChatMuted(chat, selectNotifySettings(global), selectNotifyExceptions(global));\n if (isMuted || chat.isNotJoined || !chat.isListed) {\n return false;\n }\n // Dont show notification for active chat if client has focus\n return !(isActive && document.hasFocus());\n}\n\nfunction getNotificationContent(chat: ApiChat, message: ApiMessage) {\n const global = getGlobal();\n const {\n senderId,\n replyToMessageId,\n } = message;\n\n const messageSender = senderId ? selectUser(global, senderId) : undefined;\n const messageAction = getMessageAction(message as ApiMessage);\n const actionTargetMessage = messageAction && replyToMessageId\n ? selectChatMessage(global, chat.id, replyToMessageId)\n : undefined;\n const {\n targetUserIds: actionTargetUserIds,\n targetChatId: actionTargetChatId,\n } = messageAction || {};\n\n const actionTargetUsers = actionTargetUserIds\n ? actionTargetUserIds.map((userId) => selectUser(global, userId))\n .filter<ApiUser>(Boolean as any)\n : undefined;\n const privateChatUserId = getPrivateChatUserId(chat);\n const privateChatUser = privateChatUserId ? selectUser(global, privateChatUserId) : undefined;\n\n let body: string;\n if (selectShouldShowMessagePreview(chat, selectNotifySettings(global), selectNotifyExceptions(global))) {\n if (isActionMessage(message)) {\n const actionOrigin = chat && (isChatChannel(chat) || message.senderId === message.chatId)\n ? chat\n : messageSender;\n body = renderActionMessageText(\n getTranslation,\n message,\n actionOrigin,\n actionTargetUsers,\n actionTargetMessage,\n actionTargetChatId,\n { asPlain: true },\n ) as string;\n } else {\n const senderName = getMessageSenderName(getTranslation, chat.id, messageSender);\n const summary = getMessageSummaryText(getTranslation, message);\n\n body = senderName ? `${senderName}: ${summary}` : summary;\n }\n } else {\n body = 'New message';\n }\n\n return {\n title: getChatTitle(getTranslation, chat, privateChatUser),\n body,\n };\n}\n\nasync function getAvatar(chat: ApiChat) {\n const imageHash = getChatAvatarHash(chat);\n if (!imageHash) return undefined;\n let mediaData = mediaLoader.getFromMemory<ApiMediaFormat.BlobUrl>(imageHash);\n if (!mediaData) {\n await mediaLoader.fetch(imageHash, ApiMediaFormat.BlobUrl);\n mediaData = mediaLoader.getFromMemory<ApiMediaFormat.BlobUrl>(imageHash);\n }\n return mediaData;\n}\n\ntype NotificationData = {\n messageId?: number;\n chatId?: number;\n title: string;\n body: string;\n icon?: string;\n};\n\nconst handledNotifications = new Set();\nlet pendingNotifications: Record<number, NotificationData[]> = {};\n\nasync function showNotifications(groupLimit: number = 2) {\n const count = Object.keys(pendingNotifications).reduce<number>((result, groupId) => {\n result += pendingNotifications[Number(groupId)].length;\n return result;\n }, 0);\n // if we have more than groupLimit notification groups we send only one notification\n if (Object.keys(pendingNotifications).length > groupLimit) {\n await showNotification({\n title: APP_NAME,\n body: `You have ${count} new Telegram notifications`,\n });\n } else {\n // Else we send a notification per group\n await Promise.all(Object.keys(pendingNotifications)\n // eslint-disable-next-line no-async-without-await/no-async-without-await\n .map(async (groupId) => {\n const group = pendingNotifications[Number(groupId)];\n if (group.length > groupLimit) {\n const lastMessage = group[group.length - 1];\n return showNotification({\n title: APP_NAME,\n body: `You have ${count} notifications from ${lastMessage.title}`,\n messageId: lastMessage.messageId,\n chatId: Number(groupId),\n });\n }\n return Promise.all(group.map(showNotification));\n }));\n }\n\n // Clear all pending notifications\n pendingNotifications = {};\n}\n\nconst flushNotifications = debounce(showNotifications, 1000, false);\n\nasync function handleNotification(data: NotificationData, groupLimit?: number) {\n // Dont show already triggered notification\n if (handledNotifications.has(data.messageId)) {\n handledNotifications.delete(data.messageId);\n return;\n }\n\n const groupId = data.chatId || 0;\n if (!pendingNotifications[groupId]) {\n pendingNotifications[groupId] = [];\n }\n pendingNotifications[groupId].push(data);\n await flushNotifications(groupLimit);\n\n if (checkIfPushSupported()) {\n if (navigator.serviceWorker.controller) {\n // notify service worker that notification was handled locally\n navigator.serviceWorker.controller.postMessage({\n type: 'notificationHandled',\n payload: data,\n });\n }\n }\n\n handledNotifications.add(data.messageId);\n}\n\nfunction showNotification(data: NotificationData) {\n if (checkIfPushSupported()) {\n if (navigator.serviceWorker.controller) {\n // notify service worker about new message notification\n navigator.serviceWorker.controller.postMessage({\n type: 'newMessageNotification',\n payload: data,\n });\n }\n } else {\n const dispatch = getDispatch();\n const options: NotificationOptions = {\n body: data.body,\n icon: data.icon,\n badge: data.icon,\n tag: data.messageId ? data.messageId.toString() : undefined,\n };\n\n if ('vibrate' in navigator) {\n options.vibrate = [200, 100, 200];\n }\n\n const notification = new Notification(data.title, options);\n\n notification.onclick = () => {\n notification.close();\n dispatch.focusMessage({\n chatId: data.chatId,\n messageId: data.messageId,\n });\n if (window.focus) {\n window.focus();\n }\n };\n\n // Play sound when notification is displayed\n notification.onshow = () => {\n const id = data.messageId || data.chatId;\n if (id) playNotificationSound(id);\n };\n }\n}\n\nexport async function showNewMessageNotification({\n chat,\n message,\n isActiveChat,\n}: { chat: ApiChat; message: Partial<ApiMessage>; isActiveChat: boolean }) {\n if (!checkIfNotificationsSupported()) return;\n if (!message.id) return;\n\n await loadNotificationSettings();\n if (!checkIfShouldNotify(chat, isActiveChat)) return;\n\n const {\n title,\n body,\n } = getNotificationContent(chat, message as ApiMessage);\n\n const icon = await getAvatar(chat);\n\n await handleNotification({\n title,\n body,\n icon,\n messageId: message.id,\n chatId: chat.id,\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","// This data was received from Telegram Desktop (Telegram/Resources/numbers.txt)\nconst DATA = `AF🇦🇫93Afghanistan333\nAO🇦🇴244Angola333\nAL🇦🇱355Albania234\nAD🇦🇩376Andorra222\nAE🇦🇪971United Arab Emirates234\nAI🇦🇮1264Anguilla34\nAR🇦🇷54Argentina\nAM🇦🇲374Armenia233\nAG🇦🇬1268Antigua and Barbuda34\nAU🇦🇺61Australia333\nAS🇦🇸1684American Samoa34\nAT🇦🇹43Austria\nAW🇦🇼297Aruba34\nAZ🇦🇿994Azerbaijan2322\nBI🇧🇮257Burundi224\nBE🇧🇪32Belgium3222\nBJ🇧🇯229Benin233\nBF🇧🇫226Burkina Faso2222\nBD🇧🇩880Bangladesh\nBG🇧🇬359Bulgaria\nBH🇧🇭973Bahrain44\nBS🇧🇸1242Bahamas34\nBA🇧🇦387Bosnia and Herzegovina\nBY🇧🇾375Belarus2322\nBZ🇧🇿501Belize\nBO🇧🇴591Bolivia134\nBR🇧🇷55Brazil254\nBB🇧🇧1246Barbados34\nBM🇧🇲1441Bermuda34\nBN🇧🇳673Brunei34\nBQ🇧🇶599Bonaire, Sint Eustatius and Saba\nBT🇧🇹975Bhutan\nBW🇧🇼267Botswana233\nCF🇨🇫236Central African Republic2222\nCA🇨🇦1Canada334\nCH🇨🇭41Switzerland234\nCK🇨🇰682Cook Islands\nCL🇨🇱56Chile144\nCN🇨🇳86China344\nCI🇨🇮225Côte d\\`Ivoire233\nCM🇨🇲237Cameroon44\nCD🇨🇩243DR Congo234\nCG🇨🇬242Republic of the Congo234\nCO🇨🇴57Colombia334\nKM🇰🇲269Comoros34\nCV🇨🇻238Cape Verde34\nCR🇨🇷506Costa Rica\nCU🇨🇺53Cuba44\nCY🇨🇾357Cyprus44\nCW🇨🇼599Curaçao\nCZ🇨🇿420Czech Republic\nDE🇩🇪49Germany38\nDJ🇩🇯253Djibouti2222\nDM🇩🇲1767Dominica34\nDK🇩🇰45Denmark44\nDO🇩🇴1Dominican Republic334\nDZ🇩🇿213Algeria3222\nEC🇪🇨593Ecuador\nEG🇪🇬20Egypt234\nER🇪🇷291Eritrea133\nES🇪🇸34Spain333\nEE🇪🇪372Estonia\nET🇪🇹251Ethiopia234\nFI🇫🇮358Finland\nFJ🇫🇯679Fiji\nFK🇫🇰500Falkland Islands\nFM🇫🇲691Micronesia\nFO🇫🇴298Faroe Islands33\nFR🇫🇷33France12222\nGA🇬🇦241Gabon1222\nGB🇬🇧44United Kingdom46\nGE🇬🇪995Georgia\nGF🇬🇫594French Guiana\nGH🇬🇭233Ghana\nGI🇬🇮350Gibraltar44\nGL🇬🇱299Greenland33\nGN🇬🇳224Guinea333\nGM🇬🇲220Gambia34\nGP🇬🇵590Guadeloupe\nGU🇬🇺1671Guam34\nGW🇬🇼245Guinea-Bissau34\nGQ🇬🇶240Equatorial Guinea333\nGR🇬🇷30Greece244\nGD🇬🇩1473Grenada34\nGT🇬🇹502Guatemala134\nGY🇬🇾592Guyana\nHK🇭🇰852Hong Kong\nHN🇭🇳504Honduras44\nHR🇭🇷385Croatia\nHT🇭🇹509Haiti\nHU🇭🇺36Hungary234\nID🇮🇩62Indonesia\nIN🇮🇳91India55\nIO🇩🇬246Diego Garcia34\nIE🇮🇪353Ireland234\nIR🇮🇷98Iran334\nIQ🇮🇶964Iraq334\nIS🇮🇸354Iceland34\nIL🇮🇱972Israel234\nIT🇮🇹39Italy334\nJM🇯🇲1876Jamaica34\nJO🇯🇴962Jordan144\nJP🇯🇵81Japan244\nKZ🇰🇿7Kazakhstan3322\nKE🇰🇪254Kenya333\nKG🇰🇬996Kyrgyzstan\nKH🇰🇭855Cambodia\nKI🇰🇮686Kiribati\nKN🇰🇳1869Saint Kitts and Nevis34\nKR🇰🇷82South Korea\nKW🇰🇼965Kuwait44\nKY🇰🇾1345Cayman Islands34\nLA🇱🇦856Laos\nLB🇱🇧961Lebanon\nLR🇱🇷231Liberia\nLY🇱🇾218Libya234\nLC🇱🇨1758Saint Lucia34\nLI🇱🇮423Liechtenstein\nLK🇱🇰94Sri Lanka234\nLS🇱🇸266Lesotho233\nLT🇱🇹370Lithuania35\nLU🇱🇺352Luxembourg\nLV🇱🇻371Latvia35\nMA🇲🇦212Morocco234\nMC🇲🇨377Monaco44\nMD🇲🇩373Moldova233\nMG🇲🇬261Madagascar2232\nMP🇲🇵1670Northern Mariana Islands34\nMO🇲🇴853Macau\nMS🇲🇸1664Montserrat34\nMV🇲🇻960Maldives\nMX🇲🇽52Mexico\nMH🇲🇭692Marshall Islands\nMK🇲🇰389Macedonia\nML🇲🇱223Mali44\nMT🇲🇹356Malta2222\nMM🇲🇲95Myanmar\nME🇲🇪382Montenegro\nMN🇲🇳976Mongolia\nMZ🇲🇿258Mozambique234\nMQ🇲🇶596Martinique\nMR🇲🇷222Mauritania44\nMU🇲🇺230Mauritius\nMW🇲🇼265Malawi\nMY🇲🇾60Malaysia\nNA🇳🇦264Namibia234\nNC🇳🇨687New Caledonia6\nNE🇳🇪227Niger2222\nNF🇳🇫672Norfolk Island\nNG🇳🇬234Nigeria\nNI🇳🇮505Nicaragua44\nNL🇳🇱31Netherlands12222\nNO🇳🇴47Norway44\nNP🇳🇵977Nepal\nNU🇳🇺683Niue\nNR🇳🇷674Nauru\nNZ🇳🇿64New Zealand\nOM🇴🇲968Oman44\nPK🇵🇰92Pakistan334\nPA🇵🇦507Panama44\nPE🇵🇪51Peru333\nPF🇵🇫689French Polynesia\nPH🇵🇭63Philippines334\nPM🇵🇲508Saint Pierre and Miquelon\nPR🇵🇷1Puerto Rico334\nPS🇵🇸970Palestine324\nPW🇵🇼680Palau\nPG🇵🇬675Papua New Guinea\nPL🇵🇱48Poland333\nKP🇰🇵850North Korea\nPT🇵🇹351Portugal144\nPY🇵🇾595Paraguay333\nQA🇶🇦974Qatar\nRE🇷🇪262Réunion333\nRO🇷🇴40Romania333\nRU🇷🇺7Russia3322\nRW🇷🇼250Rwanda333\nSA🇸🇦966Saudi Arabia\nSD🇸🇩249Sudan234\nSN🇸🇳221Senegal234\nSG🇸🇬65Singapore44\nSH🇸🇭290Saint Helena23\nSH🇸🇭247Saint Helena4\nSB🇸🇧677Solomon Islands\nSL🇸🇱232Sierra Leone233\nSV🇸🇻503El Salvador44\nSM🇸🇲378San Marino334\nSO🇸🇴252Somalia233\nRS🇷🇸381Serbia234\nSS🇸🇸211South Sudan234\nST🇸🇹239São Tomé and Príncipe25\nSR🇸🇷597Suriname34\nSK🇸🇰421Slovakia\nSI🇸🇮386Slovenia\nSE🇸🇪46Sweden234\nSZ🇸🇿268Swaziland44\nSC🇸🇨248Seychelles1222\nSX🇸🇽1721Sint Maarten34\nSY🇸🇾963Syria\nTC🇹🇨1649Turks and Caicos Islands34\nTD🇹🇩235Chad2222\nTG🇹🇬228Togo233\nTH🇹🇭66Thailand144\nTJ🇹🇯992Tajikistan\nTK🇹🇰690Tokelau\nTM🇹🇲993Turkmenistan26\nTL🇹🇱670Timor-Leste\nTO🇹🇴676Tonga\nTT🇹🇹1868Trinidad and Tobago34\nTN🇹🇳216Tunisia233\nTR🇹🇷90Turkey334\nTV🇹🇻688Tuvalu\nTW🇹🇼886Taiwan\nTZ🇹🇿255Tanzania234\nUG🇺🇬256Uganda234\nUA🇺🇦380Ukraine2322\nUY🇺🇾598Uruguay44\nUS🇺🇸1United States334\nUZ🇺🇿998Uzbekistan27\nVA🇻🇦3Vatican City\nVC🇻🇨1784Saint Vincent and the Grenadines34\nVE🇻🇪58Venezuela334\nVG🇻🇬1284British Virgin Islands34\nVI🇻🇮1340US Virgin Islands34\nVN🇻🇳84Vietnam\nVU🇻🇺678Vanuatu\nWF🇼🇫681Wallis and Futuna\nWS🇼🇸685Samoa\nXK🇽🇰383Kosovo44\nYE🇾🇪967Yemen333\nZA🇿🇦27South Africa234\nZM🇿🇲260Zambia234\nZW🇿🇼263Zimbabwe234`;\n\nconst formatsCache: Record<string, RegExp> = {};\nexport const defaultPhoneNumberFormat = /(\\d{1,3})(\\d{1,3})?(\\d{1,3})?(\\d{1,3})?(\\d{1,3})?/;\n\nconst parsed = DATA\n .split('\\n')\n .map((str) => {\n const id = str.substr(0, 2);\n const flag = str.substr(2, 4);\n const code = `+${str.match(/\\d+/)![0]}`;\n const name = str.split(/\\d+/)[1];\n const format = str.match(/\\d+$/);\n const phoneFormat = getPhoneNumberFormat(format);\n\n return {\n id, flag, code, name, phoneFormat,\n };\n });\n\nfunction getPhoneNumberFormat(format: RegExpMatchArray | null) {\n if (!format) {\n return defaultPhoneNumberFormat;\n }\n\n const formatValue = format[0] as string;\n let phoneNumberFormat;\n\n if (!formatsCache[formatValue]) {\n const phoneNumberGroups = formatValue.split('').map(Number);\n phoneNumberFormat = phoneNumberGroups.reduce((result, count, i) => {\n return `${result}(\\\\d{1,${count}})${i > 0 ? '?' : ''}`;\n }, '');\n formatsCache[formatValue] = new RegExp(`${phoneNumberFormat}${'()?'.repeat(5 - phoneNumberGroups.length)}`);\n }\n\n return formatsCache[formatValue];\n}\n\nexport default parsed;\n","import countryList, { defaultPhoneNumberFormat } from './countries';\n\nexport function getCountryById(id: string) {\n return countryList.find((c) => c.id === id) as Country;\n}\n\n// Empty groups are used to preserve 5 callback arguments for `replace` method\nfunction getPhoneNumberFormat(country?: Country) {\n return country ? country.phoneFormat : defaultPhoneNumberFormat;\n}\n\nexport function getCountryFromPhoneNumber(input: string) {\n let phoneNumber = input.replace(/[^\\d+]+/g, '');\n if (!phoneNumber.startsWith('+')) {\n phoneNumber = `+${phoneNumber}`;\n }\n\n const possibleCountries = countryList\n .filter((country: Country) => phoneNumber.startsWith(country.code))\n .sort((a, b) => a.code.length - b.code.length);\n\n return possibleCountries[possibleCountries.length - 1];\n}\n\nexport function formatPhoneNumber(input: string, country?: Country) {\n let phoneNumber = input.replace(/[^\\d]+/g, '');\n if (country) {\n phoneNumber = phoneNumber.substr(country.code.length - 1);\n } else if (input.startsWith('+')) {\n return input;\n }\n\n phoneNumber = phoneNumber.replace(getPhoneNumberFormat(country), (_, p1, p2, p3, p4, p5) => {\n const separator = country && country.id === 'GB' ? ' ' : '-';\n\n let output = '';\n if (p1) output = `${p1}`;\n if (p2) output += ` ${p2}`;\n if (p3) output += `${separator}${p3}`;\n if (p4) output += `${separator}${p4}`;\n if (p5) output += `${separator}${p5}`;\n return output;\n });\n\n return phoneNumber;\n}\n\nexport function formatPhoneNumberWithCode(phoneNumber: string) {\n const numberWithPlus = phoneNumber.startsWith('+') ? phoneNumber : `+${phoneNumber}`;\n const country = getCountryFromPhoneNumber(numberWithPlus);\n if (!country) {\n return numberWithPlus;\n }\n return `${country.code} ${formatPhoneNumber(numberWithPlus, country)}`;\n}\n\nexport { countryList };\n","type Scheduler =\n typeof requestAnimationFrame\n | typeof onTickEnd\n | typeof runNow;\n\nexport function debounce<F extends AnyToVoidFunction>(\n fn: F,\n ms: number,\n shouldRunFirst = true,\n shouldRunLast = true,\n) {\n let waitingTimeout: number | undefined;\n\n return (...args: Parameters<F>) => {\n if (waitingTimeout) {\n clearTimeout(waitingTimeout);\n waitingTimeout = undefined;\n } else if (shouldRunFirst) {\n // @ts-ignore\n fn(...args);\n }\n\n // eslint-disable-next-line no-restricted-globals\n waitingTimeout = self.setTimeout(() => {\n if (shouldRunLast) {\n // @ts-ignore\n fn(...args);\n }\n\n waitingTimeout = undefined;\n }, ms);\n };\n}\n\nexport function throttle<F extends AnyToVoidFunction>(\n fn: F,\n ms: number,\n shouldRunFirst = true,\n) {\n let interval: number | undefined;\n let isPending: boolean;\n let args: Parameters<F>;\n\n return (..._args: Parameters<F>) => {\n isPending = true;\n args = _args;\n\n if (!interval) {\n if (shouldRunFirst) {\n isPending = false;\n // @ts-ignore\n fn(...args);\n }\n\n // eslint-disable-next-line no-restricted-globals\n interval = self.setInterval(() => {\n if (!isPending) {\n // eslint-disable-next-line no-restricted-globals\n self.clearInterval(interval!);\n interval = undefined;\n return;\n }\n\n isPending = false;\n // @ts-ignore\n fn(...args);\n }, ms);\n }\n };\n}\n\nexport function throttleWithRaf<F extends AnyToVoidFunction>(fn: F) {\n return throttleWith(fastRaf, fn);\n}\n\nexport function throttleWithPrimaryRaf<F extends AnyToVoidFunction>(fn: F) {\n return throttleWith(fastPrimaryRaf, fn);\n}\n\nexport function throttleWithTickEnd<F extends AnyToVoidFunction>(fn: F) {\n return throttleWith(onTickEnd, fn);\n}\n\nexport function throttleWithNow<F extends AnyToVoidFunction>(fn: F) {\n return throttleWith(runNow, fn);\n}\n\nexport function throttleWith<F extends AnyToVoidFunction>(schedulerFn: Scheduler, fn: F) {\n let waiting = false;\n let args: Parameters<F>;\n\n return (..._args: Parameters<F>) => {\n args = _args;\n\n if (!waiting) {\n waiting = true;\n\n schedulerFn(() => {\n waiting = false;\n // @ts-ignore\n fn(...args);\n });\n }\n };\n}\n\nexport function onTickEnd(cb: NoneToVoidFunction) {\n Promise.resolve().then(cb);\n}\n\nexport function onIdle(cb: NoneToVoidFunction) {\n // eslint-disable-next-line no-restricted-globals\n if (self.requestIdleCallback) {\n // eslint-disable-next-line no-restricted-globals\n self.requestIdleCallback(cb);\n } else {\n onTickEnd(cb);\n }\n}\n\nfunction runNow(fn: NoneToVoidFunction) {\n fn();\n}\n\nexport const pause = (ms: number) => new Promise<void>((resolve) => {\n setTimeout(() => resolve(), ms);\n});\n\nexport function rafPromise() {\n return new Promise<void>((resolve) => {\n fastRaf(resolve);\n });\n}\n\nlet fastRafCallbacks: NoneToVoidFunction[] | undefined;\nlet fastRafPrimaryCallbacks: NoneToVoidFunction[] | undefined;\n\n// May result in an immediate execution if called from another `requestAnimationFrame` callback\nexport function fastRaf(callback: NoneToVoidFunction, isPrimary = false) {\n if (!fastRafCallbacks) {\n fastRafCallbacks = isPrimary ? [] : [callback];\n fastRafPrimaryCallbacks = isPrimary ? [callback] : [];\n\n requestAnimationFrame(() => {\n const currentCallbacks = fastRafCallbacks!;\n const currentPrimaryCallbacks = fastRafPrimaryCallbacks!;\n fastRafCallbacks = undefined;\n fastRafPrimaryCallbacks = undefined;\n currentPrimaryCallbacks.forEach((cb) => cb());\n currentCallbacks.forEach((cb) => cb());\n });\n } else if (isPrimary) {\n fastRafPrimaryCallbacks!.push(callback);\n } else {\n fastRafCallbacks.push(callback);\n }\n}\n\nexport function fastPrimaryRaf(callback: NoneToVoidFunction) {\n fastRaf(callback, true);\n}\n\nlet beforeUnloadCallbacks: NoneToVoidFunction[] | undefined;\n\nexport function onBeforeUnload(callback: NoneToVoidFunction, isLast = false) {\n if (!beforeUnloadCallbacks) {\n beforeUnloadCallbacks = [];\n // eslint-disable-next-line no-restricted-globals\n self.addEventListener('beforeunload', () => {\n beforeUnloadCallbacks!.forEach((cb) => cb());\n });\n }\n\n if (isLast) {\n beforeUnloadCallbacks.push(callback);\n } else {\n beforeUnloadCallbacks.unshift(callback);\n }\n\n return () => {\n beforeUnloadCallbacks = beforeUnloadCallbacks!.filter((cb) => cb !== callback);\n };\n}\n","let RE_NOT_LETTER: RegExp;\n\ntry {\n RE_NOT_LETTER = new RegExp('[^\\\\p{L}\\\\p{M}]+', 'ui');\n} catch (e) {\n // Support for older versions of firefox\n RE_NOT_LETTER = new RegExp('[^\\\\wа-яё]+', 'i');\n}\n\nexport default function searchWords(haystack: string, needle: string) {\n if (!haystack || !needle) {\n return false;\n }\n\n const haystackWords = haystack.toLowerCase().split(RE_NOT_LETTER);\n const needleWords = needle.toLowerCase().split(RE_NOT_LETTER);\n\n return needleWords.every((needleWord) => (\n haystackWords.some((haystackWord) => haystackWord.startsWith(needleWord))\n ));\n}\n","import safariFix from 'safari-14-idb-fix';\n\nfunction promisifyRequest(request) {\n return new Promise((resolve, reject) => {\n // @ts-ignore - file size hacks\n request.oncomplete = request.onsuccess = () => resolve(request.result);\n // @ts-ignore - file size hacks\n request.onabort = request.onerror = () => reject(request.error);\n });\n}\nfunction createStore(dbName, storeName) {\n const dbp = safariFix().then(() => {\n const request = indexedDB.open(dbName);\n request.onupgradeneeded = () => request.result.createObjectStore(storeName);\n return promisifyRequest(request);\n });\n return (txMode, callback) => dbp.then((db) => callback(db.transaction(storeName, txMode).objectStore(storeName)));\n}\nlet defaultGetStoreFunc;\nfunction defaultGetStore() {\n if (!defaultGetStoreFunc) {\n defaultGetStoreFunc = createStore('keyval-store', 'keyval');\n }\n return defaultGetStoreFunc;\n}\n/**\n * Get a value by its key.\n *\n * @param key\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction get(key, customStore = defaultGetStore()) {\n return customStore('readonly', (store) => promisifyRequest(store.get(key)));\n}\n/**\n * Set a value with a key.\n *\n * @param key\n * @param value\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction set(key, value, customStore = defaultGetStore()) {\n return customStore('readwrite', (store) => {\n store.put(value, key);\n return promisifyRequest(store.transaction);\n });\n}\n/**\n * Set multiple values at once. This is faster than calling set() multiple times.\n * It's also atomic – if one of the pairs can't be added, none will be added.\n *\n * @param entries Array of entries, where each entry is an array of `[key, value]`.\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction setMany(entries, customStore = defaultGetStore()) {\n return customStore('readwrite', (store) => {\n entries.forEach((entry) => store.put(entry[1], entry[0]));\n return promisifyRequest(store.transaction);\n });\n}\n/**\n * Get multiple values by their keys\n *\n * @param keys\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction getMany(keys, customStore = defaultGetStore()) {\n return customStore('readonly', (store) => Promise.all(keys.map((key) => promisifyRequest(store.get(key)))));\n}\n/**\n * Update a value. This lets you see the old value and update it as an atomic operation.\n *\n * @param key\n * @param updater A callback that takes the old value and returns a new value.\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction update(key, updater, customStore = defaultGetStore()) {\n return customStore('readwrite', (store) => \n // Need to create the promise manually.\n // If I try to chain promises, the transaction closes in browsers\n // that use a promise polyfill (IE10/11).\n new Promise((resolve, reject) => {\n store.get(key).onsuccess = function () {\n try {\n store.put(updater(this.result), key);\n resolve(promisifyRequest(store.transaction));\n }\n catch (err) {\n reject(err);\n }\n };\n }));\n}\n/**\n * Delete a particular key from the store.\n *\n * @param key\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction del(key, customStore = defaultGetStore()) {\n return customStore('readwrite', (store) => {\n store.delete(key);\n return promisifyRequest(store.transaction);\n });\n}\n/**\n * Clear all values in the store.\n *\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction clear(customStore = defaultGetStore()) {\n return customStore('readwrite', (store) => {\n store.clear();\n return promisifyRequest(store.transaction);\n });\n}\nfunction eachCursor(customStore, callback) {\n return customStore('readonly', (store) => {\n // This would be store.getAllKeys(), but it isn't supported by Edge or Safari.\n // And openKeyCursor isn't supported by Safari.\n store.openCursor().onsuccess = function () {\n if (!this.result)\n return;\n callback(this.result);\n this.result.continue();\n };\n return promisifyRequest(store.transaction);\n });\n}\n/**\n * Get all keys in the store.\n *\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction keys(customStore = defaultGetStore()) {\n const items = [];\n return eachCursor(customStore, (cursor) => items.push(cursor.key)).then(() => items);\n}\n/**\n * Get all values in the store.\n *\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction values(customStore = defaultGetStore()) {\n const items = [];\n return eachCursor(customStore, (cursor) => items.push(cursor.value)).then(() => items);\n}\n/**\n * Get all entries in the store. Each entry is an array of `[key, value]`.\n *\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction entries(customStore = defaultGetStore()) {\n const items = [];\n return eachCursor(customStore, (cursor) => items.push([cursor.key, cursor.value])).then(() => items);\n}\n\nexport { clear, createStore, del, entries, get, getMany, keys, promisifyRequest, set, setMany, update, values };\n","/**\n * https://bugs.webkit.org/show_bug.cgi?id=226547\n * Safari has a horrible bug where IDB requests can hang while the browser is starting up.\n * The only solution is to keep nudging it until it's awake.\n * This probably creates garbage, but garbage is better than totally failing.\n */\nfunction idbReady() {\n const isSafari = !navigator.userAgentData &&\n /Safari\\//.test(navigator.userAgent) &&\n !/Chrom(e|ium)\\//.test(navigator.userAgent);\n // No point putting other browsers or older versions of Safari through this mess.\n if (!isSafari || !indexedDB.databases)\n return Promise.resolve();\n let intervalId;\n return new Promise((resolve) => {\n const tryIdb = () => indexedDB.databases().finally(resolve);\n intervalId = setInterval(tryIdb, 100);\n tryIdb();\n }).finally(() => clearInterval(intervalId));\n}\n\nexport default idbReady;\n","import * as idb from 'idb-keyval';\n\nimport { ApiSessionData } from '../api/types';\n\nimport { DEBUG, LEGACY_SESSION_KEY, SESSION_USER_KEY } from '../config';\nimport * as cacheApi from './cacheApi';\n\nconst DC_IDS = [1, 2, 3, 4, 5];\n\nexport function hasStoredSession(withLegacy = false) {\n if (withLegacy && localStorage.getItem(LEGACY_SESSION_KEY)) {\n return true;\n }\n\n const userAuthJson = localStorage.getItem(SESSION_USER_KEY);\n if (!userAuthJson) return false;\n\n try {\n const userAuth = JSON.parse(userAuthJson);\n return Boolean(userAuth && userAuth.id && userAuth.dcID);\n } catch (err) {\n // Do nothing.\n return false;\n }\n}\n\nexport function storeSession(sessionData: ApiSessionData, currentUserId?: number) {\n const { mainDcId, keys, hashes } = sessionData;\n\n localStorage.setItem(SESSION_USER_KEY, JSON.stringify({ dcID: mainDcId, id: currentUserId }));\n localStorage.setItem('dc', String(mainDcId));\n Object.keys(keys).map(Number).forEach((dcId) => {\n localStorage.setItem(`dc${dcId}_auth_key`, JSON.stringify(keys[dcId]));\n });\n Object.keys(hashes).map(Number).forEach((dcId) => {\n localStorage.setItem(`dc${dcId}_hash`, JSON.stringify(hashes[dcId]));\n });\n}\n\nexport function clearStoredSession() {\n [\n SESSION_USER_KEY,\n 'dc',\n ...DC_IDS.map((dcId) => `dc${dcId}_auth_key`),\n ...DC_IDS.map((dcId) => `dc${dcId}_hash`),\n ].forEach((key) => {\n localStorage.removeItem(key);\n });\n}\n\nexport function loadStoredSession(): ApiSessionData | undefined {\n if (!hasStoredSession()) {\n return undefined;\n }\n\n const userAuth = JSON.parse(localStorage.getItem(SESSION_USER_KEY)!);\n const mainDcId = Number(userAuth.dcID);\n const keys: Record<number, string> = {};\n const hashes: Record<number, string> = {};\n\n DC_IDS.forEach((dcId) => {\n try {\n const key = localStorage.getItem(`dc${dcId}_auth_key`);\n if (key) {\n keys[dcId] = JSON.parse(key);\n }\n\n const hash = localStorage.getItem(`dc${dcId}_hash`);\n if (hash) {\n hashes[dcId] = JSON.parse(hash);\n }\n } catch (err) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.warn('Failed to load stored session', err);\n }\n // Do nothing.\n }\n });\n\n if (!Object.keys(keys).length) return undefined;\n\n return {\n mainDcId,\n keys,\n hashes,\n };\n}\n\nexport async function importLegacySession() {\n const sessionId = localStorage.getItem(LEGACY_SESSION_KEY);\n if (!sessionId) return;\n\n const sessionJson = await idb.get(`GramJs:${sessionId}`);\n try {\n const sessionData = JSON.parse(sessionJson) as ApiSessionData;\n storeSession(sessionData);\n } catch (err) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.warn('Failed to load legacy session', err);\n }\n // Do nothing.\n }\n}\n\n// Remove previously created IndexedDB and cache API sessions\nexport async function clearLegacySessions() {\n localStorage.removeItem(LEGACY_SESSION_KEY);\n\n const idbKeys = await idb.keys();\n\n await Promise.all<Promise<any>>([\n cacheApi.clear('GramJs'),\n ...idbKeys\n .filter((k) => typeof k === 'string' && k.startsWith('GramJs:GramJs-session-'))\n .map((k) => idb.del(k)),\n ]);\n}\n\nexport function importTestSession() {\n const sessionJson = process.env.TEST_SESSION!;\n try {\n const sessionData = JSON.parse(sessionJson) as ApiSessionData & { userId: number };\n storeSession(sessionData, sessionData.userId);\n } catch (err) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.warn('Failed to load test session', err);\n }\n // Do nothing.\n }\n}\n","import { ISettings } from '../types';\n\nimport { animateSingle } from './animation';\n\nimport themeColors from '../styles/themes.json';\n\ntype RGBAColor = {\n r: number;\n g: number;\n b: number;\n a?: number;\n};\n\nlet isInitialized = false;\n\nconst HEX_COLOR_REGEX = /^#?([a-f\\d]{2})([a-f\\d]{2})([a-f\\d]{2})([a-f\\d]{2})?$/i;\nconst DURATION_MS = 200;\nconst ENABLE_ANIMATION_DELAY_MS = 500;\n\nconst lerp = (start: number, end: number, interpolationRatio: number) => {\n return (1 - interpolationRatio) * start + interpolationRatio * end;\n};\n\nconst colors = (Object.keys(themeColors) as Array<keyof typeof themeColors>).map((property) => ({\n property,\n colors: [hexToRgb(themeColors[property][0]), hexToRgb(themeColors[property][1])],\n}));\n\nexport default (theme: ISettings['theme'], withAnimation: boolean) => {\n const isDarkTheme = theme === 'dark';\n const shouldAnimate = isInitialized && withAnimation;\n const startIndex = isDarkTheme ? 0 : 1;\n const endIndex = isDarkTheme ? 1 : 0;\n const startAt = Date.now();\n const themeColorTag = document.querySelector('meta[name=\"theme-color\"]');\n\n document.documentElement.classList.remove(`theme-${isDarkTheme ? 'light' : 'dark'}`);\n if (isInitialized) {\n document.documentElement.classList.add('no-animations');\n }\n document.documentElement.classList.add(`theme-${theme}`);\n if (themeColorTag) {\n themeColorTag.setAttribute('content', isDarkTheme ? '#212121' : '#fff');\n }\n\n setTimeout(() => {\n document.documentElement.classList.remove('no-animations');\n }, ENABLE_ANIMATION_DELAY_MS);\n\n isInitialized = true;\n\n if (shouldAnimate) {\n animateSingle(() => {\n const t = Math.min((Date.now() - startAt) / DURATION_MS, 1);\n\n applyColorAnimationStep(startIndex, endIndex, transition(t));\n\n return t < 1;\n });\n } else {\n applyColorAnimationStep(startIndex, endIndex);\n }\n};\n\nfunction transition(t: number) {\n return 1 - ((1 - t) ** 3.5);\n}\n\nfunction hexToRgb(hex: string): RGBAColor {\n const result = HEX_COLOR_REGEX.exec(hex)!;\n\n return {\n r: parseInt(result[1], 16),\n g: parseInt(result[2], 16),\n b: parseInt(result[3], 16),\n a: result[4] !== undefined ? parseInt(result[4], 16) : undefined,\n };\n}\n\nfunction applyColorAnimationStep(startIndex: number, endIndex: number, interpolationRatio: number = 1) {\n colors.forEach(({ property, colors: propertyColors }) => {\n const r = Math.round(lerp(propertyColors[startIndex].r, propertyColors[endIndex].r, interpolationRatio));\n const g = Math.round(lerp(propertyColors[startIndex].g, propertyColors[endIndex].g, interpolationRatio));\n const b = Math.round(lerp(propertyColors[startIndex].b, propertyColors[endIndex].b, interpolationRatio));\n const a = propertyColors[startIndex].a !== undefined\n ? Math.round(lerp(propertyColors[startIndex].a!, propertyColors[endIndex].a!, interpolationRatio))\n : undefined;\n\n document.documentElement.style.setProperty(property, a !== undefined\n ? `rgba(${r},${g},${b},${a / 255})`\n : `rgb(${r},${g},${b})`);\n });\n}\n","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","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 { isWebpSupported } from './environment';\nimport { dataUriToBlob, blobToDataUri } from './files';\nimport { pause } from './schedulers';\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 Worker(new URL('../lib/webp/webp_wasm.worker.js', import.meta.url)) 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 if (!worker.requests) {\n worker.requests = new Map();\n }\n\n worker.requests.set(url, resolve);\n worker.postMessage({ id: url, blob });\n });\n}\n","import { APP_VERSION } from '../config';\nimport { getGlobal } from '../lib/teact/teactn';\nimport { hasStoredSession } from './sessions';\n\nconst WEBSYNC_URLS = [\n 't.me',\n 'telegram.me',\n].map((domain) => `//${domain}/_websync_?`);\nconst WEBSYNC_VERSION = `${APP_VERSION} Z`;\nconst WEBSYNC_KEY = 'tgme_sync';\nconst WEBSYNC_TIMEOUT = 86400;\n\nconst getTs = () => {\n return Math.floor(Number(new Date()) / 1000);\n};\n\nconst saveSync = (authed: boolean) => {\n const ts = getTs();\n localStorage.setItem(WEBSYNC_KEY, JSON.stringify({\n canRedirect: authed,\n ts,\n }));\n};\n\nlet lastTimeout: NodeJS.Timeout | undefined;\n\nexport const forceWebsync = (authed: boolean) => {\n const currentTs = getTs();\n\n const { canRedirect, ts } = JSON.parse(localStorage.getItem(WEBSYNC_KEY) || '{}');\n\n if (canRedirect !== authed || ts + WEBSYNC_TIMEOUT <= currentTs) {\n return Promise.all(WEBSYNC_URLS.map((url) => {\n return new Promise<void>((resolve, reject) => {\n const script = document.createElement('script');\n\n const removeElement = () => !!document.body.removeChild(script);\n\n script.src = url + new URLSearchParams({\n authed: Number(authed).toString(),\n version: WEBSYNC_VERSION,\n });\n\n document.body.appendChild(script);\n\n script.onload = () => {\n saveSync(authed);\n removeElement();\n if (lastTimeout) {\n clearTimeout(lastTimeout);\n lastTimeout = undefined;\n }\n startWebsync();\n resolve();\n };\n\n script.onerror = () => {\n removeElement();\n reject();\n };\n });\n }));\n } else {\n return Promise.resolve();\n }\n};\n\nexport function startWebsync() {\n if (lastTimeout !== undefined) return;\n const currentTs = getTs();\n\n const { ts } = JSON.parse(localStorage.getItem(WEBSYNC_KEY) || '{}');\n\n const timeout = WEBSYNC_TIMEOUT - (currentTs - ts);\n\n lastTimeout = setTimeout(() => {\n const { authState } = getGlobal();\n\n const authed = authState === 'authorizationStateReady' || hasStoredSession(true);\n forceWebsync(authed);\n }, Math.max(0, timeout * 1000));\n}\n","import { throttle } from './schedulers';\nimport {\n MOBILE_SCREEN_LANDSCAPE_MAX_HEIGHT,\n MOBILE_SCREEN_LANDSCAPE_MAX_WIDTH,\n MOBILE_SCREEN_MAX_WIDTH,\n} from '../config';\nimport { IS_IOS, IS_SINGLE_COLUMN_LAYOUT } from './environment';\n\ntype IDimensions = {\n width: number;\n height: number;\n};\n\nconst IS_LANDSCAPE = IS_SINGLE_COLUMN_LAYOUT && isLandscape();\n\nconst initialHeight = window.innerHeight;\nlet windowSize = updateSizes();\nlet isRefreshDisabled = false;\n\nfunction disableRefresh() {\n isRefreshDisabled = true;\n}\n\nfunction enableRefresh() {\n isRefreshDisabled = false;\n}\n\nconst handleResize = throttle(() => {\n windowSize = updateSizes();\n\n if (!isRefreshDisabled && (\n isMobileScreen() !== IS_SINGLE_COLUMN_LAYOUT\n || (IS_SINGLE_COLUMN_LAYOUT && IS_LANDSCAPE !== isLandscape())\n )) {\n window.location.reload();\n }\n}, 250, true);\n\nwindow.addEventListener('resize', handleResize);\nwindow.addEventListener('orientationchange', handleResize);\n\nexport function updateSizes(): IDimensions {\n const vh = window.innerHeight * 0.01;\n\n document.documentElement.style.setProperty('--vh', `${vh}px`);\n\n return {\n width: window.innerWidth,\n height: window.innerHeight,\n };\n}\n\nfunction isMobileScreen() {\n return windowSize.width <= MOBILE_SCREEN_MAX_WIDTH || (\n windowSize.width <= MOBILE_SCREEN_LANDSCAPE_MAX_WIDTH && windowSize.height <= MOBILE_SCREEN_LANDSCAPE_MAX_HEIGHT\n );\n}\n\nfunction isLandscape() {\n if (IS_IOS) {\n return window.matchMedia('(orientation: landscape)').matches;\n }\n\n // eslint-disable-next-line max-len\n // Source: https://web.archive.org/web/20160509220835/http://blog.abouthalf.com/development/orientation-media-query-challenges-in-android-browsers/\n // Feature is marked as deprecated now, but it is still supported\n // https://developer.mozilla.org/en-US/docs/Web/CSS/@media/device-aspect-ratio#browser_compatibility\n return window.matchMedia('screen and (min-device-aspect-ratio: 1/1) and (orientation: landscape)').matches;\n}\n\nexport default {\n get: () => windowSize,\n getIsKeyboardVisible: () => initialHeight > windowSize.height,\n disableRefresh,\n enableRefresh,\n};\n","// The module cache\nvar __webpack_module_cache__ = {};\n\n// The require function\nfunction __webpack_require__(moduleId) {\n\t// Check if module is in cache\n\tvar cachedModule = __webpack_module_cache__[moduleId];\n\tif (cachedModule !== undefined) {\n\t\treturn cachedModule.exports;\n\t}\n\t// Create a new module (and put it into the cache)\n\tvar module = __webpack_module_cache__[moduleId] = {\n\t\t// no module.id needed\n\t\t// no module.loaded needed\n\t\texports: {}\n\t};\n\n\t// Execute the module function\n\t__webpack_modules__[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n\t// Return the exports of the module\n\treturn module.exports;\n}\n\n// expose the modules object (__webpack_modules__)\n__webpack_require__.m = __webpack_modules__;\n\n","// getDefaultExport function for compatibility with non-harmony modules\n__webpack_require__.n = (module) => {\n\tvar getter = module && module.__esModule ?\n\t\t() => (module['default']) :\n\t\t() => (module);\n\t__webpack_require__.d(getter, { a: getter });\n\treturn getter;\n};","// define getter functions for harmony exports\n__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n\t\tif(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n\t\t\tObject.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n\t\t}\n\t}\n};","__webpack_require__.f = {};\n// This file contains only the entry chunk.\n// The chunk loading function for additional chunks\n__webpack_require__.e = (chunkId) => {\n\treturn Promise.all(Object.keys(__webpack_require__.f).reduce((promises, key) => {\n\t\t__webpack_require__.f[key](chunkId, promises);\n\t\treturn promises;\n\t}, []));\n};","// This function allow to reference async chunks\n__webpack_require__.u = (chunkId) => {\n\t// return url for filenames based on template\n\treturn \"\" + chunkId + \".\" + {\"99\":\"f03a947e6e336feffec8\",\"133\":\"fe2caa1aacfc535ba551\",\"146\":\"c7894c08fd3a8dd34c76\",\"161\":\"286d0207d962142ad548\",\"280\":\"957bc0f63bbdadfc93d0\",\"354\":\"5270669aa5fd75f75c91\",\"370\":\"f0e1d539833f435a084c\",\"472\":\"21e5264f606f2b525030\",\"501\":\"4f81824af70a9a03da7e\",\"524\":\"d71181c13283185f9659\",\"536\":\"55dc7dd4ab42a2c9f037\",\"745\":\"9316c5c2b711c39a20a5\",\"915\":\"8fb9f0f20311fa368dc5\",\"923\":\"dd6db4a0988b82d6fbea\",\"941\":\"74ee93d332e344855ed7\",\"993\":\"f0aad9f6787f211b4e51\"}[chunkId] + \".js\";\n};","// This function allow to reference all chunks\n__webpack_require__.miniCssF = (chunkId) => {\n\t// return url for filenames based on template\n\treturn \"\" + chunkId + \".\" + {\"133\":\"fe2caa1aacfc535ba551\",\"146\":\"c7894c08fd3a8dd34c76\",\"280\":\"957bc0f63bbdadfc93d0\",\"472\":\"21e5264f606f2b525030\",\"923\":\"dd6db4a0988b82d6fbea\"}[chunkId] + \".css\";\n};","__webpack_require__.g = (function() {\n\tif (typeof globalThis === 'object') return globalThis;\n\ttry {\n\t\treturn this || new Function('return this')();\n\t} catch (e) {\n\t\tif (typeof window === 'object') return window;\n\t}\n})();","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","var scriptUrl;\nif (__webpack_require__.g.importScripts) scriptUrl = __webpack_require__.g.location + \"\";\nvar document = __webpack_require__.g.document;\nif (!scriptUrl && document) {\n\tif (document.currentScript)\n\t\tscriptUrl = document.currentScript.src\n\tif (!scriptUrl) {\n\t\tvar scripts = document.getElementsByTagName(\"script\");\n\t\tif(scripts.length) scriptUrl = scripts[scripts.length - 1].src\n\t}\n}\n// When supporting browsers where an automatic publicPath is not supported you must specify an output.publicPath manually via configuration\n// or pass an empty string (\"\") and set the __webpack_public_path__ variable from your code to use your own logic.\nif (!scriptUrl) throw new Error(\"Automatic publicPath is not supported in this browser\");\nscriptUrl = scriptUrl.replace(/#.*$/, \"\").replace(/\\?.*$/, \"\").replace(/\\/[^\\/]+$/, \"/\");\n__webpack_require__.p = scriptUrl;","__webpack_require__.b = document.baseURI || self.location.href;\n\n// object to store loaded and loading chunks\n// undefined = chunk not loaded, null = chunk preloaded/prefetched\n// [resolve, reject, Promise] = chunk loading, 0 = chunk loaded\nvar installedChunks = {\n\t179: 0\n};\n\n__webpack_require__.f.j = (chunkId, promises) => {\n\t\t// JSONP chunk loading for javascript\n\t\tvar installedChunkData = __webpack_require__.o(installedChunks, chunkId) ? installedChunks[chunkId] : undefined;\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\tif(true) { // all chunks have JS\n\t\t\t\t\t// setup Promise in chunk cache\n\t\t\t\t\tvar promise = new Promise((resolve, reject) => (installedChunkData = installedChunks[chunkId] = [resolve, reject]));\n\t\t\t\t\tpromises.push(installedChunkData[2] = promise);\n\n\t\t\t\t\t// start chunk loading\n\t\t\t\t\tvar url = __webpack_require__.p + __webpack_require__.u(chunkId);\n\t\t\t\t\t// create error before stack unwound to get useful stacktrace later\n\t\t\t\t\tvar error = new Error();\n\t\t\t\t\tvar loadingEnded = (event) => {\n\t\t\t\t\t\tif(__webpack_require__.o(installedChunks, chunkId)) {\n\t\t\t\t\t\t\tinstalledChunkData = installedChunks[chunkId];\n\t\t\t\t\t\t\tif(installedChunkData !== 0) installedChunks[chunkId] = undefined;\n\t\t\t\t\t\t\tif(installedChunkData) {\n\t\t\t\t\t\t\t\tvar errorType = event && (event.type === 'load' ? 'missing' : event.type);\n\t\t\t\t\t\t\t\tvar realSrc = event && event.target && event.target.src;\n\t\t\t\t\t\t\t\terror.message = 'Loading chunk ' + chunkId + ' failed.\\n(' + errorType + ': ' + realSrc + ')';\n\t\t\t\t\t\t\t\terror.name = 'ChunkLoadError';\n\t\t\t\t\t\t\t\terror.type = errorType;\n\t\t\t\t\t\t\t\terror.request = realSrc;\n\t\t\t\t\t\t\t\tinstalledChunkData[1](error);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t};\n\t\t\t\t\t__webpack_require__.l(url, loadingEnded, \"chunk-\" + chunkId, chunkId);\n\t\t\t\t} else installedChunks[chunkId] = 0;\n\t\t\t}\n\t\t}\n};\n\n// no prefetching\n\n// no preloaded\n\n// no HMR\n\n// no HMR manifest\n\n// no on chunks loaded\n\n// install a JSONP callback for chunk loading\nvar webpackJsonpCallback = (parentChunkLoadingFunction, data) => {\n\tvar [chunkIds, moreModules, runtime] = data;\n\t// add \"moreModules\" to the modules object,\n\t// then flag all \"chunkIds\" as loaded and fire callback\n\tvar moduleId, chunkId, i = 0;\n\tfor(moduleId in moreModules) {\n\t\tif(__webpack_require__.o(moreModules, moduleId)) {\n\t\t\t__webpack_require__.m[moduleId] = moreModules[moduleId];\n\t\t}\n\t}\n\tif(runtime) var result = runtime(__webpack_require__);\n\tif(parentChunkLoadingFunction) parentChunkLoadingFunction(data);\n\tfor(;i < chunkIds.length; i++) {\n\t\tchunkId = chunkIds[i];\n\t\tif(__webpack_require__.o(installedChunks, chunkId) && installedChunks[chunkId]) {\n\t\t\tinstalledChunks[chunkId][0]();\n\t\t}\n\t\tinstalledChunks[chunkIds[i]] = 0;\n\t}\n\n}\n\nvar chunkLoadingGlobal = self[\"webpackChunktelegram_t\"] = self[\"webpackChunktelegram_t\"] || [];\nchunkLoadingGlobal.forEach(webpackJsonpCallback.bind(null, 0));\nchunkLoadingGlobal.push = webpackJsonpCallback.bind(null, chunkLoadingGlobal.push.bind(chunkLoadingGlobal));","import { DEBUG } from '../config';\nimport { getDispatch } from '../lib/teact/teactn';\nimport { IS_ANDROID, IS_IOS, IS_SERVICE_WORKER_SUPPORTED } from './environment';\nimport { notifyClientReady, playNotificationSound } from './notifications';\n\ntype WorkerAction = {\n type: string;\n payload: Record<string, any>;\n};\n\nfunction handleWorkerMessage(e: MessageEvent) {\n const action: WorkerAction = e.data;\n if (!action.type) return;\n const dispatch = getDispatch();\n switch (action.type) {\n case 'focusMessage':\n if (dispatch.focusMessage) {\n dispatch.focusMessage(action.payload);\n }\n break;\n case 'playNotificationSound':\n playNotificationSound(action.payload.id);\n break;\n }\n}\n\nfunction subscribeToWorker() {\n navigator.serviceWorker.removeEventListener('message', handleWorkerMessage);\n navigator.serviceWorker.addEventListener('message', handleWorkerMessage);\n // Notify web worker that client is ready to receive messages\n notifyClientReady();\n}\n\nif (IS_SERVICE_WORKER_SUPPORTED) {\n window.addEventListener('load', async () => {\n try {\n await navigator.serviceWorker.register(new URL('../serviceWorker.ts', import.meta.url));\n\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('[SW] ServiceWorker registered');\n }\n\n await navigator.serviceWorker.ready;\n\n if (navigator.serviceWorker.controller) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('[SW] ServiceWorker ready');\n }\n subscribeToWorker();\n } else {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error('[SW] ServiceWorker not available');\n }\n\n if (!IS_IOS && !IS_ANDROID) {\n getDispatch().showDialog({ data: { message: 'SERVICE_WORKER_DISABLED', hasErrorKey: true } });\n }\n }\n } catch (err) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error('[SW] ServiceWorker registration failed: ', err);\n }\n }\n });\n window.addEventListener('focus', async () => {\n await navigator.serviceWorker.ready;\n subscribeToWorker();\n });\n}\n","import { GlobalState } from './types';\nimport { NewChatMembersProgress } from '../types';\n\nimport {\n ANIMATION_LEVEL_DEFAULT, DARK_THEME_PATTERN_COLOR, DEFAULT_MESSAGE_TEXT_SIZE_PX, DEFAULT_PATTERN_COLOR,\n IOS_DEFAULT_MESSAGE_TEXT_SIZE_PX, MACOS_DEFAULT_MESSAGE_TEXT_SIZE_PX,\n} from '../config';\nimport { IS_IOS, IS_MAC_OS } from '../util/environment';\n\nexport const INITIAL_STATE: GlobalState = {\n isLeftColumnShown: true,\n isChatInfoShown: false,\n newChatMembersProgress: NewChatMembersProgress.Closed,\n uiReadyState: 0,\n serverTimeOffset: 0,\n\n authRememberMe: true,\n\n blocked: {\n ids: [],\n totalCount: 0,\n },\n\n users: {\n byId: {},\n },\n\n chats: {\n listIds: {},\n isFullyLoaded: {},\n orderedPinnedIds: {},\n totalCount: {},\n byId: {},\n },\n\n messages: {\n byChatId: {},\n messageLists: [],\n },\n\n scheduledMessages: {\n byChatId: {},\n },\n\n chatFolders: {\n byId: {},\n activeChatFolder: 0,\n },\n\n fileUploads: {\n byMessageLocalId: {},\n },\n\n recentEmojis: ['grinning', 'kissing_heart', 'christmas_tree', 'brain', 'trophy'],\n\n stickers: {\n setsById: {},\n added: {},\n recent: {\n stickers: [],\n },\n favorite: {\n stickers: [],\n },\n greeting: {\n stickers: [],\n },\n featured: {\n setIds: [],\n },\n search: {},\n forEmoji: {},\n },\n\n emojiKeywords: {},\n\n gifs: {\n saved: {},\n search: {},\n },\n\n inlineBots: {\n isLoading: false,\n byUsername: {},\n },\n\n globalSearch: {},\n\n userSearch: {},\n\n localTextSearch: {\n byChatThreadKey: {},\n },\n\n localMediaSearch: {\n byChatId: {},\n },\n\n management: {\n byChatId: {},\n },\n\n topPeers: {},\n\n topInlineBots: {},\n\n mediaViewer: {},\n\n audioPlayer: {},\n\n forwardMessages: {},\n\n pollResults: {},\n\n payment: {},\n\n notifications: [],\n\n dialogs: [],\n\n activeSessions: [],\n\n settings: {\n byKey: {\n theme: 'light',\n shouldUseSystemTheme: true,\n messageTextSize: IS_IOS\n ? IOS_DEFAULT_MESSAGE_TEXT_SIZE_PX\n : (IS_MAC_OS ? MACOS_DEFAULT_MESSAGE_TEXT_SIZE_PX : DEFAULT_MESSAGE_TEXT_SIZE_PX),\n animationLevel: ANIMATION_LEVEL_DEFAULT,\n messageSendKeyCombo: 'enter',\n shouldAutoDownloadMediaFromContacts: true,\n shouldAutoDownloadMediaInPrivateChats: true,\n shouldAutoDownloadMediaInGroups: true,\n shouldAutoDownloadMediaInChannels: true,\n hasWebNotifications: true,\n hasPushNotifications: true,\n notificationSoundVolume: 5,\n shouldAutoPlayGifs: true,\n shouldAutoPlayVideos: true,\n shouldSuggestStickers: true,\n shouldLoopStickers: true,\n language: 'en',\n },\n themes: {\n light: {\n isBlurred: true,\n patternColor: DEFAULT_PATTERN_COLOR,\n },\n dark: {\n isBlurred: true,\n patternColor: DARK_THEME_PATTERN_COLOR,\n },\n },\n privacy: {},\n notifyExceptions: {},\n },\n\n twoFaSettings: {},\n\n shouldShowContextMenuHint: true,\n};\n","import {\n addCallback, addReducer, getGlobal, removeCallback,\n} from '../lib/teact/teactn';\n\nimport { GlobalState } from './types';\nimport { MAIN_THREAD_ID } from '../api/types';\n\nimport { onBeforeUnload, onIdle, throttle } from '../util/schedulers';\nimport {\n DEBUG,\n GLOBAL_STATE_CACHE_DISABLED,\n GLOBAL_STATE_CACHE_KEY,\n GLOBAL_STATE_CACHE_CHAT_LIST_LIMIT,\n MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN,\n GLOBAL_STATE_CACHE_USER_LIST_LIMIT,\n} from '../config';\nimport { IS_SINGLE_COLUMN_LAYOUT } from '../util/environment';\nimport { ANIMATION_END_EVENT, ANIMATION_START_EVENT } from '../hooks/useHeavyAnimationCheck';\nimport { pick } from '../util/iteratees';\nimport { selectCurrentMessageList } from '../modules/selectors';\nimport { hasStoredSession } from '../util/sessions';\nimport { INITIAL_STATE } from './initial';\n\nconst UPDATE_THROTTLE = 5000;\n\nconst updateCacheThrottled = throttle(() => onIdle(updateCache), UPDATE_THROTTLE, false);\n\nlet isCaching = false;\nlet isHeavyAnimating = false;\nlet unsubscribeFromBeforeUnload: NoneToVoidFunction | undefined;\n\nsetupHeavyAnimationListeners();\n\nexport function initCache() {\n if (GLOBAL_STATE_CACHE_DISABLED) {\n return;\n }\n\n addReducer('saveSession', () => {\n if (isCaching) {\n return;\n }\n\n setupCaching();\n });\n\n addReducer('reset', () => {\n localStorage.removeItem(GLOBAL_STATE_CACHE_KEY);\n\n if (!isCaching) {\n return;\n }\n\n clearCaching();\n });\n}\n\nexport function loadCache(initialState: GlobalState) {\n if (GLOBAL_STATE_CACHE_DISABLED) {\n return undefined;\n }\n\n if (hasStoredSession(true)) {\n setupCaching();\n\n return readCache(initialState);\n } else {\n clearCaching();\n\n return undefined;\n }\n}\n\nfunction setupCaching() {\n isCaching = true;\n unsubscribeFromBeforeUnload = onBeforeUnload(updateCache, true);\n window.addEventListener('blur', updateCache);\n addCallback(updateCacheThrottled);\n}\n\nfunction clearCaching() {\n isCaching = false;\n removeCallback(updateCacheThrottled);\n window.removeEventListener('blur', updateCache);\n if (unsubscribeFromBeforeUnload) {\n unsubscribeFromBeforeUnload();\n }\n}\n\nfunction readCache(initialState: GlobalState) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.time('global-state-cache-read');\n }\n\n const json = localStorage.getItem(GLOBAL_STATE_CACHE_KEY);\n const cached = json ? JSON.parse(json) as GlobalState : undefined;\n\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.timeEnd('global-state-cache-read');\n }\n\n if (cached) {\n // Pre-fill defaults in nested objects which may be missing in older cache\n cached.settings.byKey = {\n ...initialState.settings.byKey,\n ...cached.settings.byKey,\n };\n cached.settings.themes = {\n ...initialState.settings.themes,\n ...cached.settings.themes,\n };\n cached.chatFolders = {\n ...initialState.chatFolders,\n ...cached.chatFolders,\n };\n\n if (!cached.messages.messageLists) {\n cached.messages.messageLists = initialState.messages.messageLists;\n }\n\n if (!cached.stickers.greeting) {\n cached.stickers.greeting = initialState.stickers.greeting;\n }\n }\n\n return {\n ...initialState,\n ...cached,\n };\n}\n\nfunction updateCache() {\n if (!isCaching || isHeavyAnimating) {\n return;\n }\n\n const global = getGlobal();\n\n if (global.isLoggingOut) {\n return;\n }\n\n const reducedGlobal: GlobalState = {\n ...INITIAL_STATE,\n ...pick(global, [\n 'authState',\n 'authPhoneNumber',\n 'authRememberMe',\n 'authNearestCountry',\n 'currentUserId',\n 'contactList',\n 'topPeers',\n 'topInlineBots',\n 'recentEmojis',\n 'push',\n 'shouldShowContextMenuHint',\n ]),\n isChatInfoShown: reduceShowChatInfo(global),\n users: reduceUsers(global),\n chats: reduceChats(global),\n messages: reduceMessages(global),\n globalSearch: {\n recentlyFoundChatIds: global.globalSearch.recentlyFoundChatIds,\n },\n settings: reduceSettings(global),\n chatFolders: reduceChatFolders(global),\n };\n\n const json = JSON.stringify(reducedGlobal);\n localStorage.setItem(GLOBAL_STATE_CACHE_KEY, json);\n}\n\nfunction reduceShowChatInfo(global: GlobalState): boolean {\n return window.innerWidth > MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN\n ? global.isChatInfoShown\n : false;\n}\n\nfunction reduceUsers(global: GlobalState): GlobalState['users'] {\n const { users: { byId, selectedId } } = global;\n const idsToSave = [\n ...(global.chats.listIds.active || []).slice(0, GLOBAL_STATE_CACHE_CHAT_LIST_LIMIT).filter((cid) => cid > 0),\n ...Object.keys(byId),\n ].slice(0, GLOBAL_STATE_CACHE_USER_LIST_LIMIT);\n\n return {\n byId: pick(byId, idsToSave as number[]),\n selectedId: window.innerWidth > MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN ? selectedId : undefined,\n };\n}\n\nfunction reduceChats(global: GlobalState): GlobalState['chats'] {\n const chatIdsToSave = [\n ...(global.chats.listIds.active || []).slice(0, GLOBAL_STATE_CACHE_CHAT_LIST_LIMIT),\n ];\n const { chatId: currentChatId } = selectCurrentMessageList(global) || {};\n\n return {\n ...global.chats,\n byId: pick(global.chats.byId, currentChatId ? [...chatIdsToSave, currentChatId] : chatIdsToSave),\n listIds: {\n active: chatIdsToSave,\n },\n isFullyLoaded: {},\n orderedPinnedIds: {\n active: global.chats.orderedPinnedIds.active,\n },\n };\n}\n\nfunction reduceMessages(global: GlobalState): GlobalState['messages'] {\n const byChatId: GlobalState['messages']['byChatId'] = {};\n const { chatId: currentChatId } = selectCurrentMessageList(global) || {};\n\n const chatIdsToSave = [\n ...(global.chats.listIds.active || []).slice(0, GLOBAL_STATE_CACHE_CHAT_LIST_LIMIT),\n ...(currentChatId ? [currentChatId] : []),\n ];\n chatIdsToSave.forEach((chatId) => {\n const current = global.messages.byChatId[chatId];\n if (!current) {\n return;\n }\n\n const mainThread = current.threadsById[MAIN_THREAD_ID];\n if (!mainThread || !mainThread.viewportIds) {\n return;\n }\n\n byChatId[chatId] = {\n byId: pick(current.byId, mainThread.viewportIds),\n threadsById: {\n [MAIN_THREAD_ID]: mainThread,\n },\n };\n });\n\n const currentMessageList = selectCurrentMessageList(global);\n\n return {\n byChatId,\n messageLists: !currentMessageList || IS_SINGLE_COLUMN_LAYOUT ? [] : [{\n ...currentMessageList,\n threadId: MAIN_THREAD_ID,\n type: 'thread',\n }],\n };\n}\n\nfunction reduceSettings(global: GlobalState): GlobalState['settings'] {\n const { byKey, themes } = global.settings;\n\n return {\n byKey,\n themes,\n privacy: {},\n notifyExceptions: {},\n };\n}\n\nfunction reduceChatFolders(global: GlobalState): GlobalState['chatFolders'] {\n return {\n ...global.chatFolders,\n activeChatFolder: 0,\n };\n}\n\nfunction setupHeavyAnimationListeners() {\n document.addEventListener(ANIMATION_START_EVENT, () => {\n isHeavyAnimating = true;\n });\n document.addEventListener(ANIMATION_END_EVENT, () => {\n isHeavyAnimating = false;\n });\n}\n","import { addReducer } from '../lib/teact/teactn';\n\nimport { INITIAL_STATE } from './initial';\nimport { initCache, loadCache } from './cache';\nimport { cloneDeep } from '../util/iteratees';\n\ninitCache();\n\naddReducer('init', () => {\n const initial = cloneDeep(INITIAL_STATE);\n return loadCache(initial) || initial;\n});\n","const STORAGE_KEY = 'tt-active-tab';\nconst INTERVAL = 2000;\n\nconst tabKey = String(Date.now() + Math.random());\n\nlocalStorage.setItem(STORAGE_KEY, tabKey);\n\nlet callback: NoneToVoidFunction;\n\nconst interval = window.setInterval(() => {\n if (callback && localStorage.getItem(STORAGE_KEY) !== tabKey) {\n callback();\n clearInterval(interval);\n }\n}, INTERVAL);\n\nexport function addActiveTabChangeListener(_callback: NoneToVoidFunction) {\n callback = _callback;\n}\n","const SITE_FONTS = ['400 1em Roboto', '500 1em Roboto'];\n\nexport default function preloadFonts() {\n if ('fonts' in document) {\n return Promise.all(SITE_FONTS.map((font) => document.fonts.load(font)));\n }\n\n return undefined;\n}\n","import React, { FC, useEffect } from '../../lib/teact/teact';\nimport { getGlobal, withGlobal } from '../../lib/teact/teactn';\n\nimport { ApiMediaFormat } from '../../api/types';\nimport { GlobalActions, GlobalState } from '../../global/types';\n\nimport { getChatAvatarHash } from '../../modules/helpers/chats'; // Direct import for better module splitting\nimport useFlag from '../../hooks/useFlag';\nimport useShowTransition from '../../hooks/useShowTransition';\nimport { pause } from '../../util/schedulers';\nimport { preloadImage } from '../../util/files';\nimport preloadFonts from '../../util/fonts';\nimport * as mediaLoader from '../../util/mediaLoader';\nimport { Bundles, loadModule } from '../../util/moduleLoader';\nimport { pick } from '../../util/iteratees';\nimport buildClassName from '../../util/buildClassName';\n\nimport './UiLoader.scss';\n\n// @ts-ignore\nimport telegramLogoPath from '../../assets/telegram-logo.svg';\n// @ts-ignore\nimport monkeyPath from '../../assets/monkey.svg';\nimport { selectIsRightColumnShown, selectTheme } from '../../modules/selectors';\n\ntype OwnProps = {\n page: 'main' | 'authCode' | 'authPassword' | 'authPhoneNumber' | 'authQrCode';\n children: any;\n};\n\ntype StateProps = Pick<GlobalState, 'uiReadyState' | 'shouldSkipHistoryAnimations'> & {\n hasCustomBackground?: boolean;\n hasCustomBackgroundColor: boolean;\n isRightColumnShown?: boolean;\n};\n\ntype DispatchProps = Pick<GlobalActions, 'setIsUiReady'>;\n\nconst MAX_PRELOAD_DELAY = 700;\nconst SECOND_STATE_DELAY = 1000;\nconst AVATARS_TO_PRELOAD = 10;\n\nfunction preloadAvatars() {\n const { listIds, byId } = getGlobal().chats;\n if (!listIds.active) {\n return undefined;\n }\n\n return Promise.all(listIds.active.slice(0, AVATARS_TO_PRELOAD).map((chatId) => {\n const chat = byId[chatId];\n if (!chat) {\n return undefined;\n }\n\n const avatarHash = getChatAvatarHash(chat);\n if (!avatarHash) {\n return undefined;\n }\n\n return mediaLoader.fetch(avatarHash, ApiMediaFormat.DataUri);\n }));\n}\n\nconst preloadTasks = {\n main: () => Promise.all([\n loadModule(Bundles.Main, 'Main')\n .then(preloadFonts),\n preloadAvatars(),\n ]),\n authPhoneNumber: () => Promise.all([\n preloadFonts(),\n preloadImage(telegramLogoPath),\n ]),\n authCode: () => preloadImage(monkeyPath),\n authPassword: () => preloadImage(monkeyPath),\n authQrCode: preloadFonts,\n};\n\nconst UiLoader: FC<OwnProps & StateProps & DispatchProps> = ({\n page,\n children,\n hasCustomBackground,\n hasCustomBackgroundColor,\n isRightColumnShown,\n shouldSkipHistoryAnimations,\n setIsUiReady,\n}) => {\n const [isReady, markReady] = useFlag();\n const {\n shouldRender: shouldRenderMask, transitionClassNames,\n } = useShowTransition(!isReady, undefined, true);\n\n useEffect(() => {\n let timeout: number | undefined;\n\n const safePreload = async () => {\n try {\n await preloadTasks[page]();\n } catch (err) {\n // Do nothing\n }\n };\n\n Promise.race([\n pause(MAX_PRELOAD_DELAY),\n safePreload(),\n ]).then(() => {\n markReady();\n setIsUiReady({ uiReadyState: 1 });\n\n timeout = window.setTimeout(() => {\n setIsUiReady({ uiReadyState: 2 });\n }, SECOND_STATE_DELAY);\n });\n\n return () => {\n if (timeout) {\n clearTimeout(timeout);\n timeout = undefined;\n }\n\n setIsUiReady({ uiReadyState: 0 });\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n\n return (\n <div id=\"UiLoader\">\n {children}\n {shouldRenderMask && !shouldSkipHistoryAnimations && (\n <div className={buildClassName('mask', transitionClassNames)}>\n {page === 'main' ? (\n <>\n <div className=\"left\" />\n <div\n className={buildClassName(\n 'middle',\n hasCustomBackground && 'custom-bg-image',\n hasCustomBackgroundColor && 'custom-bg-color',\n isRightColumnShown && 'with-right-column',\n )}\n />\n {isRightColumnShown && <div className=\"right\" />}\n </>\n ) : (\n <div className=\"blank\" />\n )}\n </div>\n )}\n </div>\n );\n};\n\nexport default withGlobal<OwnProps>(\n (global): StateProps => {\n const theme = selectTheme(global);\n const { background, backgroundColor } = global.settings.themes[theme] || {};\n\n return {\n shouldSkipHistoryAnimations: global.shouldSkipHistoryAnimations,\n uiReadyState: global.uiReadyState,\n hasCustomBackground: Boolean(background),\n hasCustomBackgroundColor: Boolean(backgroundColor),\n isRightColumnShown: selectIsRightColumnShown(global),\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, ['setIsUiReady']),\n)(UiLoader);\n","import * as langProvider from '../util/langProvider';\nimport { useState } from '../lib/teact/teact';\n\nexport default (langCode: string | undefined, key: string): string | undefined => {\n const [translation, setTranslation] = useState<string>();\n\n if (langCode) {\n langProvider\n .getTranslationForLangString(langCode, key)\n .then(setTranslation);\n }\n\n return translation;\n};\n","import { LangCode } from '../../../types';\n\nexport function getSuggestedLanguage() {\n let suggestedLanguage = navigator.language;\n\n if (suggestedLanguage && suggestedLanguage !== 'pt-br') {\n suggestedLanguage = suggestedLanguage.substr(0, 2);\n }\n\n return suggestedLanguage as LangCode;\n}\n","import React, {\n FC, useState, memo, useCallback, useRef,\n} from '../../lib/teact/teact';\n\nimport { ANIMATION_END_DELAY } from '../../config';\nimport { countryList } from '../../util/phoneNumber';\nimport searchWords from '../../util/searchWords';\nimport buildClassName from '../../util/buildClassName';\nimport renderText from '../common/helpers/renderText';\nimport useLang from '../../hooks/useLang';\n\nimport DropdownMenu from '../ui/DropdownMenu';\nimport MenuItem from '../ui/MenuItem';\nimport Spinner from '../ui/Spinner';\n\nimport './CountryCodeInput.scss';\n\ntype OwnProps = {\n id: string;\n value?: Country;\n isLoading?: boolean;\n onChange: (value: Country) => void;\n};\n\nconst MENU_HIDING_DURATION = 200 + ANIMATION_END_DELAY;\nconst SELECT_TIMEOUT = 50;\n\nconst CountryCodeInput: FC<OwnProps> = ({\n id,\n value,\n isLoading,\n onChange,\n}) => {\n const lang = useLang();\n // eslint-disable-next-line no-null/no-null\n const inputRef = useRef<HTMLInputElement>(null);\n\n const [filter, setFilter] = useState<string | undefined>();\n const [filteredList, setFilteredList] = useState(countryList);\n\n function updateFilter(filterValue?: string) {\n setFilter(filterValue);\n setFilteredList(getFilteredList(filterValue));\n }\n\n const handleChange = useCallback((e: React.SyntheticEvent<HTMLElement>) => {\n const { countryId } = (e.currentTarget.firstElementChild as HTMLDivElement).dataset;\n const country = countryList.find((c) => c.id === countryId);\n\n if (country) {\n onChange(country);\n }\n\n setTimeout(() => updateFilter(undefined), MENU_HIDING_DURATION);\n }, [onChange]);\n\n const handleInput = useCallback((e: React.FormEvent<HTMLInputElement>) => {\n updateFilter(e.currentTarget.value);\n }, []);\n\n const handleInputKeyDown = useCallback((e: React.KeyboardEvent<HTMLInputElement>) => {\n if (e.keyCode !== 8) {\n return;\n }\n\n const target = e.currentTarget;\n if (value && filter === undefined) {\n target.value = '';\n }\n\n updateFilter(target.value);\n }, [filter, value]);\n\n const CodeInput: FC<{ onTrigger: () => void; isOpen?: boolean }> = ({ onTrigger, isOpen }) => {\n const handleTrigger = () => {\n if (isOpen) {\n return;\n }\n\n setTimeout(() => {\n inputRef.current!.select();\n }, SELECT_TIMEOUT);\n\n onTrigger();\n\n const formEl = document.getElementById('auth-phone-number-form')!;\n formEl.scrollTo({ top: formEl.scrollHeight, behavior: 'smooth' });\n };\n\n const inputValue = filter !== undefined\n ? filter\n : (value && value.name) || '';\n\n return (\n <div className={buildClassName('input-group', value && 'touched')}>\n <input\n ref={inputRef}\n className={buildClassName('form-control', isOpen && 'focus')}\n type=\"text\"\n id={id}\n value={inputValue}\n autoComplete=\"off\"\n onClick={handleTrigger}\n onFocus={handleTrigger}\n onInput={handleInput}\n onKeyDown={handleInputKeyDown}\n />\n <label>{lang('Login.SelectCountry.Title')}</label>\n {isLoading ? (\n <Spinner color=\"black\" />\n ) : (\n <i onClick={handleTrigger} className={buildClassName('css-icon-down', isOpen && 'open')} />\n )}\n </div>\n );\n };\n\n return (\n <DropdownMenu\n className=\"CountryCodeInput\"\n trigger={CodeInput}\n >\n {filteredList.map((country: Country) => (\n <MenuItem\n key={country.id}\n className={value && country.id === value.id ? 'selected' : ''}\n onClick={handleChange}\n >\n <span data-country-id={country.id} />\n <span className=\"country-flag\">{renderText(country.flag, ['hq_emoji'])}</span>\n <span className=\"country-name\">{country.name}</span>\n <span className=\"country-code\">{country.code}</span>\n </MenuItem>\n ))}\n {!filteredList.length && (\n <MenuItem\n key=\"no-results\"\n className=\"no-results\"\n disabled\n >\n <span>{lang('lng_country_none')}</span>\n </MenuItem>\n )}\n </DropdownMenu>\n );\n};\n\nfunction getFilteredList(filter = ''): Country[] {\n return filter.length\n ? countryList.filter((country) => searchWords(country.name, filter))\n : countryList;\n}\n\nexport default memo(CountryCodeInput);\n","import { ChangeEvent } from 'react';\n\n// @ts-ignore\nimport monkeyPath from '../../assets/monkey.svg';\n\nimport React, {\n FC, memo, useCallback, useEffect, useLayoutEffect, useRef, useState,\n} from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { GlobalActions, GlobalState } from '../../global/types';\nimport { LangCode } from '../../types';\n\nimport { IS_SAFARI, IS_TOUCH_ENV } from '../../util/environment';\nimport { preloadImage } from '../../util/files';\nimport preloadFonts from '../../util/fonts';\nimport { pick } from '../../util/iteratees';\nimport { formatPhoneNumber, getCountryById, getCountryFromPhoneNumber } from '../../util/phoneNumber';\nimport { setLanguage } from '../../util/langProvider';\nimport useLang from '../../hooks/useLang';\nimport useFlag from '../../hooks/useFlag';\nimport useLangString from '../../hooks/useLangString';\nimport { getSuggestedLanguage } from './helpers/getSuggestedLanguage';\n\nimport Button from '../ui/Button';\nimport Checkbox from '../ui/Checkbox';\nimport InputText from '../ui/InputText';\nimport Loading from '../ui/Loading';\nimport CountryCodeInput from './CountryCodeInput';\n\ntype StateProps = Pick<GlobalState, (\n 'connectionState' | 'authState' |\n 'authPhoneNumber' | 'authIsLoading' | 'authIsLoadingQrCode' | 'authError' | 'authRememberMe' | 'authNearestCountry'\n)> & {\n language?: LangCode;\n};\ntype DispatchProps = Pick<GlobalActions, (\n 'setAuthPhoneNumber' | 'setAuthRememberMe' | 'loadNearestCountry' | 'clearAuthError' | 'goToAuthQrCode' |\n 'setSettingOption'\n)>;\n\nconst MIN_NUMBER_LENGTH = 7;\n\nlet isPreloadInitiated = false;\n\nconst AuthPhoneNumber: FC<StateProps & DispatchProps> = ({\n connectionState,\n authState,\n authPhoneNumber,\n authIsLoading,\n authIsLoadingQrCode,\n authError,\n authRememberMe,\n authNearestCountry,\n language,\n setAuthPhoneNumber,\n setAuthRememberMe,\n loadNearestCountry,\n clearAuthError,\n goToAuthQrCode,\n setSettingOption,\n}) => {\n const lang = useLang();\n // eslint-disable-next-line no-null/no-null\n const inputRef = useRef<HTMLInputElement>(null);\n const suggestedLanguage = getSuggestedLanguage();\n\n const continueText = useLangString(suggestedLanguage, 'ContinueOnThisLanguage');\n const [country, setCountry] = useState<Country | undefined>();\n const [phoneNumber, setPhoneNumber] = useState<string | undefined>();\n const [isTouched, setIsTouched] = useState(false);\n const [lastSelection, setLastSelection] = useState<[number, number] | undefined>();\n const [isLoading, markIsLoading, unmarkIsLoading] = useFlag();\n\n const fullNumber = country ? `${country.code} ${phoneNumber || ''}` : phoneNumber;\n const canSubmit = fullNumber && fullNumber.replace(/[^\\d]+/g, '').length >= MIN_NUMBER_LENGTH;\n\n useEffect(() => {\n if (!IS_TOUCH_ENV) {\n inputRef.current!.focus();\n }\n }, [country]);\n\n useEffect(() => {\n if (connectionState === 'connectionStateReady' && !authNearestCountry) {\n loadNearestCountry();\n }\n }, [connectionState, authNearestCountry, loadNearestCountry]);\n\n useEffect(() => {\n if (authNearestCountry && !country && !isTouched) {\n setCountry(getCountryById(authNearestCountry));\n }\n }, [country, authNearestCountry, isTouched]);\n\n const parseFullNumber = useCallback((newFullNumber: string) => {\n if (!newFullNumber.length) {\n setPhoneNumber('');\n }\n\n const suggestedCountry = getCountryFromPhoneNumber(newFullNumber);\n\n // Any phone numbers should be allowed, in some cases ignoring formatting\n const selectedCountry = !country\n || (suggestedCountry && suggestedCountry.id !== country.id)\n || (!suggestedCountry && newFullNumber.length)\n ? suggestedCountry\n : country;\n\n if (!country || !selectedCountry || (selectedCountry && selectedCountry.code !== country.code)) {\n setCountry(selectedCountry);\n }\n\n setPhoneNumber(formatPhoneNumber(newFullNumber, selectedCountry));\n }, [country]);\n\n const handleLangChange = useCallback(() => {\n markIsLoading();\n\n void setLanguage(suggestedLanguage, () => {\n unmarkIsLoading();\n\n setSettingOption({ language: suggestedLanguage });\n });\n }, [markIsLoading, setSettingOption, suggestedLanguage, unmarkIsLoading]);\n\n useEffect(() => {\n if (phoneNumber === undefined && authPhoneNumber) {\n parseFullNumber(authPhoneNumber);\n }\n }, [authPhoneNumber, phoneNumber, parseFullNumber]);\n\n useLayoutEffect(() => {\n if (inputRef.current && lastSelection) {\n inputRef.current.setSelectionRange(...lastSelection);\n }\n }, [lastSelection]);\n\n const isJustPastedRef = useRef(false);\n const handlePaste = useCallback(() => {\n isJustPastedRef.current = true;\n requestAnimationFrame(() => {\n isJustPastedRef.current = false;\n });\n }, []);\n\n const handlePhoneNumberChange = useCallback((e: ChangeEvent<HTMLInputElement>) => {\n if (authError) {\n clearAuthError();\n }\n\n // This is for further screens. We delay it until user input to speed up the initial loading.\n if (!isPreloadInitiated) {\n isPreloadInitiated = true;\n preloadFonts();\n void preloadImage(monkeyPath);\n }\n\n const { value, selectionStart, selectionEnd } = e.target;\n setLastSelection(\n selectionStart && selectionEnd && selectionEnd < value.length\n ? [selectionStart, selectionEnd]\n : undefined,\n );\n\n setIsTouched(true);\n\n const shouldFixSafariAutoComplete = (\n IS_SAFARI && country && fullNumber !== undefined\n && value.length - fullNumber.length > 1 && !isJustPastedRef.current\n );\n parseFullNumber(shouldFixSafariAutoComplete ? `${country!.code} ${value}` : value);\n }, [authError, clearAuthError, country, fullNumber, parseFullNumber]);\n\n const handleKeepSessionChange = useCallback((e: ChangeEvent<HTMLInputElement>) => {\n setAuthRememberMe(e.target.checked);\n }, [setAuthRememberMe]);\n\n function handleSubmit(event: React.FormEvent<HTMLFormElement>) {\n event.preventDefault();\n\n if (authIsLoading) {\n return;\n }\n\n if (canSubmit) {\n setAuthPhoneNumber({ phoneNumber: fullNumber });\n }\n }\n\n const isAuthReady = authState === 'authorizationStateWaitPhoneNumber';\n\n return (\n <div id=\"auth-phone-number-form\" className=\"custom-scroll\">\n <div className=\"auth-form\">\n <div id=\"logo\" />\n <h2>Telegram</h2>\n <p className=\"note\">{lang('StartText')}</p>\n <form action=\"\" onSubmit={handleSubmit}>\n <CountryCodeInput\n id=\"sign-in-phone-code\"\n value={country}\n isLoading={!authNearestCountry && !country}\n onChange={setCountry}\n />\n <InputText\n ref={inputRef}\n id=\"sign-in-phone-number\"\n label={lang('Login.PhonePlaceholder')}\n value={fullNumber}\n error={authError && lang(authError)}\n inputMode=\"tel\"\n onChange={handlePhoneNumberChange}\n onPaste={IS_SAFARI ? handlePaste : undefined}\n />\n <Checkbox\n id=\"sign-in-keep-session\"\n label=\"Keep me signed in\"\n checked={Boolean(authRememberMe)}\n onChange={handleKeepSessionChange}\n />\n {canSubmit && (\n isAuthReady ? (\n <Button type=\"submit\" ripple isLoading={authIsLoading}>{lang('Login.Next')}</Button>\n ) : (\n <Loading />\n )\n )}\n {isAuthReady && (\n <Button isText ripple isLoading={authIsLoadingQrCode} onClick={goToAuthQrCode}>\n {lang('Login.QR.Login')}\n </Button>\n )}\n {suggestedLanguage && suggestedLanguage !== language && continueText && (\n <Button isText isLoading={isLoading} onClick={handleLangChange}>{continueText}</Button>\n )}\n </form>\n </div>\n </div>\n );\n};\n\nexport default memo(withGlobal(\n (global): StateProps => {\n const {\n settings: { byKey: { language } },\n } = global;\n\n return {\n ...pick(global, [\n 'connectionState',\n 'authState',\n 'authPhoneNumber',\n 'authIsLoading',\n 'authIsLoadingQrCode',\n 'authError',\n 'authRememberMe',\n 'authNearestCountry',\n ]),\n language,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'setAuthPhoneNumber',\n 'setAuthRememberMe',\n 'clearAuthError',\n 'loadNearestCountry',\n 'goToAuthQrCode',\n 'setSettingOption',\n ]),\n)(AuthPhoneNumber));\n","import React, { FC, memo } from '../../lib/teact/teact';\nimport { Bundles } from '../../util/moduleLoader';\n\nimport useModuleLoader from '../../hooks/useModuleLoader';\nimport Loading from '../ui/Loading';\n\nconst AuthCodeAsync: FC = () => {\n const AuthCode = useModuleLoader(Bundles.Auth, 'AuthCode');\n\n return AuthCode ? <AuthCode /> : <Loading />;\n};\n\nexport default memo(AuthCodeAsync);\n","import React, { FC, memo } from '../../lib/teact/teact';\nimport { Bundles } from '../../util/moduleLoader';\n\nimport useModuleLoader from '../../hooks/useModuleLoader';\nimport Loading from '../ui/Loading';\n\nconst AuthPasswordAsync: FC = () => {\n const AuthPassword = useModuleLoader(Bundles.Auth, 'AuthPassword');\n\n return AuthPassword ? <AuthPassword /> : <Loading />;\n};\n\nexport default memo(AuthPasswordAsync);\n","import React, { FC, memo } from '../../lib/teact/teact';\nimport { Bundles } from '../../util/moduleLoader';\n\nimport useModuleLoader from '../../hooks/useModuleLoader';\nimport Loading from '../ui/Loading';\n\nconst AuthRegisterAsync: FC = () => {\n const AuthRegister = useModuleLoader(Bundles.Auth, 'AuthRegister');\n\n return AuthRegister ? <AuthRegister /> : <Loading />;\n};\n\nexport default memo(AuthRegisterAsync);\n","/*\n jquery-qrcode v0.14.0 - https://larsjung.de/jquery-qrcode/ */\n'use strict';let G=null;class H{}H.render=function(w,B){G(w,B)};self.QrCreator=H;\n(function(w){function B(t,c,a,e){var b={},h=w(a,c);h.u(t);h.J();e=e||0;var r=h.h(),d=h.h()+2*e;b.text=t;b.level=c;b.version=a;b.O=d;b.a=function(b,a){b-=e;a-=e;return 0>b||b>=r||0>a||a>=r?!1:h.a(b,a)};return b}function C(t,c,a,e,b,h,r,d,g,x){function u(b,a,f,c,d,r,g){b?(t.lineTo(a+r,f+g),t.arcTo(a,f,c,d,h)):t.lineTo(a,f)}r?t.moveTo(c+h,a):t.moveTo(c,a);u(d,e,a,e,b,-h,0);u(g,e,b,c,b,0,-h);u(x,c,b,c,a,h,0);u(r,c,a,e,a,0,h)}function z(t,c,a,e,b,h,r,d,g,x){function u(b,a,c,d){t.moveTo(b+c,a);t.lineTo(b,\na);t.lineTo(b,a+d);t.arcTo(b,a,b+c,a,h)}r&&u(c,a,h,h);d&&u(e,a,-h,h);g&&u(e,b,-h,-h);x&&u(c,b,h,-h)}function A(t,c){var a=c.fill;if(\"string\"===typeof a)t.fillStyle=a;else{var e=a.type,b=a.colorStops;a=a.position.map((b)=>Math.round(b*c.size));if(\"linear-gradient\"===e)var h=t.createLinearGradient.apply(t,a);else if(\"radial-gradient\"===e)h=t.createRadialGradient.apply(t,a);else throw Error(\"Unsupported fill\");b.forEach(([b,a])=>{h.addColorStop(b,a)});t.fillStyle=h}}function y(t,c){a:{var a=c.text,e=\nc.v,b=c.N,h=c.K,r=c.P;b=Math.max(1,b||1);for(h=Math.min(40,h||40);b<=h;b+=1)try{var d=B(a,e,b,r);break a}catch(J){}d=void 0}if(!d)return null;a=t.getContext(\"2d\");c.background&&(a.fillStyle=c.background,a.fillRect(c.left,c.top,c.size,c.size));e=d.O;h=c.size/e;a.beginPath();for(r=0;r<e;r+=1)for(b=0;b<e;b+=1){var g=a,x=c.left+b*h,u=c.top+r*h,p=r,q=b,f=d.a,k=x+h,m=u+h,D=p-1,E=p+1,n=q-1,l=q+1,y=Math.floor(Math.min(.5,Math.max(0,c.R))*h),v=f(p,q),I=f(D,n),w=f(D,q);D=f(D,l);var F=f(p,l);l=f(E,l);q=f(E,\nq);E=f(E,n);p=f(p,n);x=Math.round(x);u=Math.round(u);k=Math.round(k);m=Math.round(m);v?C(g,x,u,k,m,y,!w&&!p,!w&&!F,!q&&!F,!q&&!p):z(g,x,u,k,m,y,w&&p&&I,w&&F&&D,q&&F&&l,q&&p&&E)}A(a,c);a.fill();return t}var v={minVersion:1,maxVersion:40,ecLevel:\"L\",left:0,top:0,size:200,fill:\"#000\",background:null,text:\"no text\",radius:.5,quiet:0};G=function(t,c){var a={};Object.assign(a,v,t);a.N=a.minVersion;a.K=a.maxVersion;a.v=a.ecLevel;a.left=a.left;a.top=a.top;a.size=a.size;a.fill=a.fill;a.background=a.background;\na.text=a.text;a.R=a.radius;a.P=a.quiet;if(c instanceof HTMLCanvasElement){if(c.width!==a.size||c.height!==a.size)c.width=a.size,c.height=a.size;c.getContext(\"2d\").clearRect(0,0,c.width,c.height);y(c,a)}else t=document.createElement(\"canvas\"),t.width=a.size,t.height=a.size,a=y(t,a),c.appendChild(a)}})(function(){function w(c){var a=C.s(c);return{S:function(){return 4},b:function(){return a.length},write:function(c){for(var b=0;b<a.length;b+=1)c.put(a[b],8)}}}function B(){var c=[],a=0,e={B:function(){return c},\nc:function(b){return 1==(c[Math.floor(b/8)]>>>7-b%8&1)},put:function(b,h){for(var a=0;a<h;a+=1)e.m(1==(b>>>h-a-1&1))},f:function(){return a},m:function(b){var h=Math.floor(a/8);c.length<=h&&c.push(0);b&&(c[h]|=128>>>a%8);a+=1}};return e}function C(c,a){function e(b,h){for(var a=-1;7>=a;a+=1)if(!(-1>=b+a||d<=b+a))for(var c=-1;7>=c;c+=1)-1>=h+c||d<=h+c||(r[b+a][h+c]=0<=a&&6>=a&&(0==c||6==c)||0<=c&&6>=c&&(0==a||6==a)||2<=a&&4>=a&&2<=c&&4>=c?!0:!1)}function b(b,a){for(var f=d=4*c+17,k=Array(f),m=0;m<\nf;m+=1){k[m]=Array(f);for(var p=0;p<f;p+=1)k[m][p]=null}r=k;e(0,0);e(d-7,0);e(0,d-7);f=y.G(c);for(k=0;k<f.length;k+=1)for(m=0;m<f.length;m+=1){p=f[k];var q=f[m];if(null==r[p][q])for(var n=-2;2>=n;n+=1)for(var l=-2;2>=l;l+=1)r[p+n][q+l]=-2==n||2==n||-2==l||2==l||0==n&&0==l}for(f=8;f<d-8;f+=1)null==r[f][6]&&(r[f][6]=0==f%2);for(f=8;f<d-8;f+=1)null==r[6][f]&&(r[6][f]=0==f%2);f=y.w(h<<3|a);for(k=0;15>k;k+=1)m=!b&&1==(f>>k&1),r[6>k?k:8>k?k+1:d-15+k][8]=m,r[8][8>k?d-k-1:9>k?15-k:14-k]=m;r[d-8][8]=!b;if(7<=\nc){f=y.A(c);for(k=0;18>k;k+=1)m=!b&&1==(f>>k&1),r[Math.floor(k/3)][k%3+d-8-3]=m;for(k=0;18>k;k+=1)m=!b&&1==(f>>k&1),r[k%3+d-8-3][Math.floor(k/3)]=m}if(null==g){b=t.I(c,h);f=B();for(k=0;k<x.length;k+=1)m=x[k],f.put(4,4),f.put(m.b(),y.f(4,c)),m.write(f);for(k=m=0;k<b.length;k+=1)m+=b[k].j;if(f.f()>8*m)throw Error(\"code length overflow. (\"+f.f()+\">\"+8*m+\")\");for(f.f()+4<=8*m&&f.put(0,4);0!=f.f()%8;)f.m(!1);for(;!(f.f()>=8*m);){f.put(236,8);if(f.f()>=8*m)break;f.put(17,8)}var u=0;m=k=0;p=Array(b.length);\nq=Array(b.length);for(n=0;n<b.length;n+=1){var v=b[n].j,w=b[n].o-v;k=Math.max(k,v);m=Math.max(m,w);p[n]=Array(v);for(l=0;l<p[n].length;l+=1)p[n][l]=255&f.B()[l+u];u+=v;l=y.C(w);v=z(p[n],l.b()-1).l(l);q[n]=Array(l.b()-1);for(l=0;l<q[n].length;l+=1)w=l+v.b()-q[n].length,q[n][l]=0<=w?v.c(w):0}for(l=f=0;l<b.length;l+=1)f+=b[l].o;f=Array(f);for(l=u=0;l<k;l+=1)for(n=0;n<b.length;n+=1)l<p[n].length&&(f[u]=p[n][l],u+=1);for(l=0;l<m;l+=1)for(n=0;n<b.length;n+=1)l<q[n].length&&(f[u]=q[n][l],u+=1);g=f}b=g;f=\n-1;k=d-1;m=7;p=0;a=y.F(a);for(q=d-1;0<q;q-=2)for(6==q&&--q;;){for(n=0;2>n;n+=1)null==r[k][q-n]&&(l=!1,p<b.length&&(l=1==(b[p]>>>m&1)),a(k,q-n)&&(l=!l),r[k][q-n]=l,--m,-1==m&&(p+=1,m=7));k+=f;if(0>k||d<=k){k-=f;f=-f;break}}}var h=A[a],r=null,d=0,g=null,x=[],u={u:function(b){b=w(b);x.push(b);g=null},a:function(b,a){if(0>b||d<=b||0>a||d<=a)throw Error(b+\",\"+a);return r[b][a]},h:function(){return d},J:function(){for(var a=0,h=0,c=0;8>c;c+=1){b(!0,c);var d=y.D(u);if(0==c||a>d)a=d,h=c}b(!1,h)}};return u}\nfunction z(c,a){if(\"undefined\"==typeof c.length)throw Error(c.length+\"/\"+a);var e=function(){for(var b=0;b<c.length&&0==c[b];)b+=1;for(var r=Array(c.length-b+a),d=0;d<c.length-b;d+=1)r[d]=c[d+b];return r}(),b={c:function(b){return e[b]},b:function(){return e.length},multiply:function(a){for(var h=Array(b.b()+a.b()-1),c=0;c<b.b();c+=1)for(var g=0;g<a.b();g+=1)h[c+g]^=v.i(v.g(b.c(c))+v.g(a.c(g)));return z(h,0)},l:function(a){if(0>b.b()-a.b())return b;for(var c=v.g(b.c(0))-v.g(a.c(0)),h=Array(b.b()),\ng=0;g<b.b();g+=1)h[g]=b.c(g);for(g=0;g<a.b();g+=1)h[g]^=v.i(v.g(a.c(g))+c);return z(h,0).l(a)}};return b}C.s=function(c){for(var a=[],e=0;e<c.length;e++){var b=c.charCodeAt(e);128>b?a.push(b):2048>b?a.push(192|b>>6,128|b&63):55296>b||57344<=b?a.push(224|b>>12,128|b>>6&63,128|b&63):(e++,b=65536+((b&1023)<<10|c.charCodeAt(e)&1023),a.push(240|b>>18,128|b>>12&63,128|b>>6&63,128|b&63))}return a};var A={L:1,M:0,Q:3,H:2},y=function(){function c(b){for(var a=0;0!=b;)a+=1,b>>>=1;return a}var a=[[],[6,18],\n[6,22],[6,26],[6,30],[6,34],[6,22,38],[6,24,42],[6,26,46],[6,28,50],[6,30,54],[6,32,58],[6,34,62],[6,26,46,66],[6,26,48,70],[6,26,50,74],[6,30,54,78],[6,30,56,82],[6,30,58,86],[6,34,62,90],[6,28,50,72,94],[6,26,50,74,98],[6,30,54,78,102],[6,28,54,80,106],[6,32,58,84,110],[6,30,58,86,114],[6,34,62,90,118],[6,26,50,74,98,122],[6,30,54,78,102,126],[6,26,52,78,104,130],[6,30,56,82,108,134],[6,34,60,86,112,138],[6,30,58,86,114,142],[6,34,62,90,118,146],[6,30,54,78,102,126,150],[6,24,50,76,102,128,154],\n[6,28,54,80,106,132,158],[6,32,58,84,110,136,162],[6,26,54,82,110,138,166],[6,30,58,86,114,142,170]],e={w:function(b){for(var a=b<<10;0<=c(a)-c(1335);)a^=1335<<c(a)-c(1335);return(b<<10|a)^21522},A:function(b){for(var a=b<<12;0<=c(a)-c(7973);)a^=7973<<c(a)-c(7973);return b<<12|a},G:function(b){return a[b-1]},F:function(b){switch(b){case 0:return function(b,a){return 0==(b+a)%2};case 1:return function(b){return 0==b%2};case 2:return function(b,a){return 0==a%3};case 3:return function(b,a){return 0==\n(b+a)%3};case 4:return function(b,a){return 0==(Math.floor(b/2)+Math.floor(a/3))%2};case 5:return function(b,a){return 0==b*a%2+b*a%3};case 6:return function(b,a){return 0==(b*a%2+b*a%3)%2};case 7:return function(b,a){return 0==(b*a%3+(b+a)%2)%2};default:throw Error(\"bad maskPattern:\"+b);}},C:function(b){for(var a=z([1],0),c=0;c<b;c+=1)a=a.multiply(z([1,v.i(c)],0));return a},f:function(b,a){if(4!=b||1>a||40<a)throw Error(\"mode: \"+b+\"; type: \"+a);return 10>a?8:16},D:function(b){for(var a=b.h(),c=0,\nd=0;d<a;d+=1)for(var g=0;g<a;g+=1){for(var e=0,t=b.a(d,g),p=-1;1>=p;p+=1)if(!(0>d+p||a<=d+p))for(var q=-1;1>=q;q+=1)0>g+q||a<=g+q||(0!=p||0!=q)&&t==b.a(d+p,g+q)&&(e+=1);5<e&&(c+=3+e-5)}for(d=0;d<a-1;d+=1)for(g=0;g<a-1;g+=1)if(e=0,b.a(d,g)&&(e+=1),b.a(d+1,g)&&(e+=1),b.a(d,g+1)&&(e+=1),b.a(d+1,g+1)&&(e+=1),0==e||4==e)c+=3;for(d=0;d<a;d+=1)for(g=0;g<a-6;g+=1)b.a(d,g)&&!b.a(d,g+1)&&b.a(d,g+2)&&b.a(d,g+3)&&b.a(d,g+4)&&!b.a(d,g+5)&&b.a(d,g+6)&&(c+=40);for(g=0;g<a;g+=1)for(d=0;d<a-6;d+=1)b.a(d,g)&&!b.a(d+\n1,g)&&b.a(d+2,g)&&b.a(d+3,g)&&b.a(d+4,g)&&!b.a(d+5,g)&&b.a(d+6,g)&&(c+=40);for(g=e=0;g<a;g+=1)for(d=0;d<a;d+=1)b.a(d,g)&&(e+=1);return c+=Math.abs(100*e/a/a-50)/5*10}};return e}(),v=function(){for(var c=Array(256),a=Array(256),e=0;8>e;e+=1)c[e]=1<<e;for(e=8;256>e;e+=1)c[e]=c[e-4]^c[e-5]^c[e-6]^c[e-8];for(e=0;255>e;e+=1)a[c[e]]=e;return{g:function(b){if(1>b)throw Error(\"glog(\"+b+\")\");return a[b]},i:function(b){for(;0>b;)b+=255;for(;256<=b;)b-=255;return c[b]}}}(),t=function(){function c(b,c){switch(c){case A.L:return a[4*\n(b-1)];case A.M:return a[4*(b-1)+1];case A.Q:return a[4*(b-1)+2];case A.H:return a[4*(b-1)+3]}}var a=[[1,26,19],[1,26,16],[1,26,13],[1,26,9],[1,44,34],[1,44,28],[1,44,22],[1,44,16],[1,70,55],[1,70,44],[2,35,17],[2,35,13],[1,100,80],[2,50,32],[2,50,24],[4,25,9],[1,134,108],[2,67,43],[2,33,15,2,34,16],[2,33,11,2,34,12],[2,86,68],[4,43,27],[4,43,19],[4,43,15],[2,98,78],[4,49,31],[2,32,14,4,33,15],[4,39,13,1,40,14],[2,121,97],[2,60,38,2,61,39],[4,40,18,2,41,19],[4,40,14,2,41,15],[2,146,116],[3,58,36,\n2,59,37],[4,36,16,4,37,17],[4,36,12,4,37,13],[2,86,68,2,87,69],[4,69,43,1,70,44],[6,43,19,2,44,20],[6,43,15,2,44,16],[4,101,81],[1,80,50,4,81,51],[4,50,22,4,51,23],[3,36,12,8,37,13],[2,116,92,2,117,93],[6,58,36,2,59,37],[4,46,20,6,47,21],[7,42,14,4,43,15],[4,133,107],[8,59,37,1,60,38],[8,44,20,4,45,21],[12,33,11,4,34,12],[3,145,115,1,146,116],[4,64,40,5,65,41],[11,36,16,5,37,17],[11,36,12,5,37,13],[5,109,87,1,110,88],[5,65,41,5,66,42],[5,54,24,7,55,25],[11,36,12,7,37,13],[5,122,98,1,123,99],[7,73,\n45,3,74,46],[15,43,19,2,44,20],[3,45,15,13,46,16],[1,135,107,5,136,108],[10,74,46,1,75,47],[1,50,22,15,51,23],[2,42,14,17,43,15],[5,150,120,1,151,121],[9,69,43,4,70,44],[17,50,22,1,51,23],[2,42,14,19,43,15],[3,141,113,4,142,114],[3,70,44,11,71,45],[17,47,21,4,48,22],[9,39,13,16,40,14],[3,135,107,5,136,108],[3,67,41,13,68,42],[15,54,24,5,55,25],[15,43,15,10,44,16],[4,144,116,4,145,117],[17,68,42],[17,50,22,6,51,23],[19,46,16,6,47,17],[2,139,111,7,140,112],[17,74,46],[7,54,24,16,55,25],[34,37,13],[4,\n151,121,5,152,122],[4,75,47,14,76,48],[11,54,24,14,55,25],[16,45,15,14,46,16],[6,147,117,4,148,118],[6,73,45,14,74,46],[11,54,24,16,55,25],[30,46,16,2,47,17],[8,132,106,4,133,107],[8,75,47,13,76,48],[7,54,24,22,55,25],[22,45,15,13,46,16],[10,142,114,2,143,115],[19,74,46,4,75,47],[28,50,22,6,51,23],[33,46,16,4,47,17],[8,152,122,4,153,123],[22,73,45,3,74,46],[8,53,23,26,54,24],[12,45,15,28,46,16],[3,147,117,10,148,118],[3,73,45,23,74,46],[4,54,24,31,55,25],[11,45,15,31,46,16],[7,146,116,7,147,117],\n[21,73,45,7,74,46],[1,53,23,37,54,24],[19,45,15,26,46,16],[5,145,115,10,146,116],[19,75,47,10,76,48],[15,54,24,25,55,25],[23,45,15,25,46,16],[13,145,115,3,146,116],[2,74,46,29,75,47],[42,54,24,1,55,25],[23,45,15,28,46,16],[17,145,115],[10,74,46,23,75,47],[10,54,24,35,55,25],[19,45,15,35,46,16],[17,145,115,1,146,116],[14,74,46,21,75,47],[29,54,24,19,55,25],[11,45,15,46,46,16],[13,145,115,6,146,116],[14,74,46,23,75,47],[44,54,24,7,55,25],[59,46,16,1,47,17],[12,151,121,7,152,122],[12,75,47,26,76,48],\n[39,54,24,14,55,25],[22,45,15,41,46,16],[6,151,121,14,152,122],[6,75,47,34,76,48],[46,54,24,10,55,25],[2,45,15,64,46,16],[17,152,122,4,153,123],[29,74,46,14,75,47],[49,54,24,10,55,25],[24,45,15,46,46,16],[4,152,122,18,153,123],[13,74,46,32,75,47],[48,54,24,14,55,25],[42,45,15,32,46,16],[20,147,117,4,148,118],[40,75,47,7,76,48],[43,54,24,22,55,25],[10,45,15,67,46,16],[19,148,118,6,149,119],[18,75,47,31,76,48],[34,54,24,34,55,25],[20,45,15,61,46,16]],e={I:function(b,a){var e=c(b,a);if(\"undefined\"==\ntypeof e)throw Error(\"bad rs block @ typeNumber:\"+b+\"/errorCorrectLevel:\"+a);b=e.length/3;a=[];for(var d=0;d<b;d+=1)for(var g=e[3*d],h=e[3*d+1],t=e[3*d+2],p=0;p<g;p+=1){var q=t,f={};f.o=h;f.j=q;a.push(f)}return a}};return e}();return C}());\nexport default QrCreator;\n//# sourceMappingURL=qr-creator.min.js.map\n","import QrCreator from 'qr-creator';\nimport React, {\n FC, useEffect, useRef, memo, useCallback,\n} from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { GlobalState, GlobalActions } from '../../global/types';\nimport { LangCode } from '../../types';\n\nimport { pick } from '../../util/iteratees';\nimport { setLanguage } from '../../util/langProvider';\nimport renderText from '../common/helpers/renderText';\nimport useLangString from '../../hooks/useLangString';\nimport useFlag from '../../hooks/useFlag';\nimport useLang from '../../hooks/useLang';\nimport { getSuggestedLanguage } from './helpers/getSuggestedLanguage';\n\nimport Loading from '../ui/Loading';\nimport Button from '../ui/Button';\n\ntype StateProps = Pick<GlobalState, 'connectionState' | 'authState' | 'authQrCode'> & {\n language?: LangCode;\n};\ntype DispatchProps = Pick<GlobalActions, (\n 'returnToAuthPhoneNumber' | 'setSettingOption'\n)>;\n\nconst DATA_PREFIX = 'tg://login?token=';\n\nconst AuthCode: FC<StateProps & DispatchProps> = ({\n connectionState,\n authState,\n authQrCode,\n language,\n returnToAuthPhoneNumber,\n setSettingOption,\n}) => {\n const suggestedLanguage = getSuggestedLanguage();\n const lang = useLang();\n // eslint-disable-next-line no-null/no-null\n const qrCodeRef = useRef<HTMLDivElement>(null);\n const continueText = useLangString(suggestedLanguage, 'ContinueOnThisLanguage');\n const [isLoading, markIsLoading, unmarkIsLoading] = useFlag();\n\n useEffect(() => {\n if (!authQrCode || connectionState !== 'connectionStateReady') {\n return;\n }\n\n const container = qrCodeRef.current!;\n\n container.innerHTML = '';\n container.classList.remove('pre-animate');\n\n QrCreator.render({\n text: `${DATA_PREFIX}${authQrCode.token}`,\n radius: 0.5,\n ecLevel: 'M',\n fill: '#4E96D4',\n size: 280,\n }, container);\n }, [connectionState, authQrCode]);\n\n const handleLangChange = useCallback(() => {\n markIsLoading();\n\n void setLanguage(suggestedLanguage, () => {\n unmarkIsLoading();\n\n setSettingOption({ language: suggestedLanguage });\n });\n }, [markIsLoading, setSettingOption, suggestedLanguage, unmarkIsLoading]);\n\n const isAuthReady = authState === 'authorizationStateWaitQrCode';\n\n return (\n <div id=\"auth-qr-form\" className=\"custom-scroll\">\n <div className=\"auth-form qr\">\n {authQrCode ? (\n <div key=\"qr-container\" className=\"qr-container pre-animate\" ref={qrCodeRef} />\n ) : (\n <div key=\"qr-loading\" className=\"qr-loading\"><Loading /></div>\n )}\n <h3>{lang('Login.QR.Title')}</h3>\n <ol>\n <li><span>{lang('Login.QR.Help1')}</span></li>\n <li><span>{renderText(lang('Login.QR.Help2'), ['simple_markdown'])}</span></li>\n <li><span>{lang('Login.QR.Help3')}</span></li>\n </ol>\n {isAuthReady && (\n <Button isText onClick={returnToAuthPhoneNumber}>{lang('Login.QR.Cancel')}</Button>\n )}\n {suggestedLanguage && suggestedLanguage !== language && continueText && (\n <Button isText isLoading={isLoading} onClick={handleLangChange}>{continueText}</Button>\n )}\n </div>\n </div>\n );\n};\n\nexport default memo(withGlobal(\n (global): StateProps => {\n const {\n connectionState, authState, authQrCode, settings: { byKey: { language } },\n } = global;\n\n return {\n connectionState,\n authState,\n authQrCode,\n language,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'returnToAuthPhoneNumber', 'setSettingOption',\n ]),\n)(AuthCode));\n","import React, { FC, useEffect, memo } from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { GlobalActions, GlobalState } from '../../global/types';\n\nimport '../../modules/actions/initial';\nimport { pick } from '../../util/iteratees';\nimport { PLATFORM_ENV } from '../../util/environment';\nimport windowSize from '../../util/windowSize';\nimport useHistoryBack from '../../hooks/useHistoryBack';\n\nimport UiLoader from '../common/UiLoader';\nimport AuthPhoneNumber from './AuthPhoneNumber';\nimport AuthCode from './AuthCode.async';\nimport AuthPassword from './AuthPassword.async';\nimport AuthRegister from './AuthRegister.async';\nimport AuthQrCode from './AuthQrCode';\n\nimport './Auth.scss';\n\ntype StateProps = Pick<GlobalState, 'authState'>;\ntype DispatchProps = Pick<GlobalActions, 'reset' | 'initApi' | 'returnToAuthPhoneNumber' | 'goToAuthQrCode'>;\n\nconst Auth: FC<StateProps & DispatchProps> = ({\n authState, reset, initApi, returnToAuthPhoneNumber, goToAuthQrCode,\n}) => {\n useEffect(() => {\n reset();\n initApi();\n }, [reset, initApi]);\n\n const isMobile = PLATFORM_ENV === 'iOS' || PLATFORM_ENV === 'Android';\n\n const handleChangeAuthorizationMethod = () => {\n if (!isMobile) {\n goToAuthQrCode();\n } else {\n returnToAuthPhoneNumber();\n }\n };\n\n useHistoryBack(\n (!isMobile && authState === 'authorizationStateWaitPhoneNumber')\n || (isMobile && authState === 'authorizationStateWaitQrCode'), handleChangeAuthorizationMethod,\n );\n\n // Prevent refresh when rotating device\n useEffect(() => {\n windowSize.disableRefresh();\n\n return () => {\n windowSize.enableRefresh();\n };\n }, []);\n\n switch (authState) {\n case 'authorizationStateWaitCode':\n return <UiLoader page=\"authCode\" key=\"authCode\"><AuthCode /></UiLoader>;\n case 'authorizationStateWaitPassword':\n return <UiLoader page=\"authPassword\" key=\"authPassword\"><AuthPassword /></UiLoader>;\n case 'authorizationStateWaitRegistration':\n return <AuthRegister />;\n case 'authorizationStateWaitPhoneNumber':\n return <UiLoader page=\"authPhoneNumber\" key=\"authPhoneNumber\"><AuthPhoneNumber /></UiLoader>;\n case 'authorizationStateWaitQrCode':\n return <UiLoader page=\"authQrCode\" key=\"authQrCode\"><AuthQrCode /></UiLoader>;\n default:\n return isMobile\n ? <UiLoader page=\"authPhoneNumber\" key=\"authPhoneNumber\"><AuthPhoneNumber /></UiLoader>\n : <UiLoader page=\"authQrCode\" key=\"authQrCode\"><AuthQrCode /></UiLoader>;\n }\n};\n\nexport default memo(withGlobal(\n (global): StateProps => pick(global, ['authState']),\n (global, actions): DispatchProps => pick(actions, ['reset', 'initApi', 'returnToAuthPhoneNumber', 'goToAuthQrCode']),\n)(Auth));\n","import React, { FC, memo } from '../../lib/teact/teact';\nimport { Bundles } from '../../util/moduleLoader';\n\nimport useModuleLoader from '../../hooks/useModuleLoader';\n\nconst MainAsync: FC = () => {\n const Main = useModuleLoader(Bundles.Main, 'Main');\n\n return Main ? <Main /> : undefined;\n};\n\nexport default memo(MainAsync);\n","import React, { FC } from '../../lib/teact/teact';\n\nimport Button from '../ui/Button';\n\nimport appInactivePath from '../../assets/app-inactive.png';\nimport './AppInactive.scss';\n\nconst AppInactive: FC = () => {\n const handleReload = () => {\n window.location.reload();\n };\n\n return (\n <div id=\"AppInactive\">\n <div className=\"content\">\n <img src={appInactivePath} alt=\"\" />\n <h3 className=\"title\">Such error, many tabs</h3>\n <div className=\"description\">\n Telegram supports only one active tab with the app.\n <br />\n Please reload this page to continue using this tab or close it.\n </div>\n <div className=\"actions\">\n <Button isText ripple onClick={handleReload}>Reload app</Button>\n </div>\n </div>\n </div>\n );\n};\n\nexport default AppInactive;\n","import { FC, useEffect } from './lib/teact/teact';\nimport React, { withGlobal } from './lib/teact/teactn';\n\nimport { GlobalActions, GlobalState } from './global/types';\n\nimport { INACTIVE_MARKER, PAGE_TITLE } from './config';\nimport { pick } from './util/iteratees';\nimport { updateSizes } from './util/windowSize';\nimport { addActiveTabChangeListener } from './util/activeTabMonitor';\nimport useFlag from './hooks/useFlag';\n\nimport Auth from './components/auth/Auth';\nimport UiLoader from './components/common/UiLoader';\nimport Main from './components/main/Main.async';\nimport AppInactive from './components/main/AppInactive';\nimport { hasStoredSession } from './util/sessions';\n// import Test from './components/test/TestNoRedundancy';\n\ntype StateProps = Pick<GlobalState, 'authState'>;\ntype DispatchProps = Pick<GlobalActions, 'disconnect'>;\n\nconst App: FC<StateProps & DispatchProps> = ({ authState, disconnect }) => {\n const [isInactive, markInactive] = useFlag(false);\n\n useEffect(() => {\n updateSizes();\n addActiveTabChangeListener(() => {\n disconnect();\n document.title = `${PAGE_TITLE}${INACTIVE_MARKER}`;\n\n markInactive();\n });\n }, [disconnect, markInactive]);\n\n // return <Test />;\n\n if (isInactive) {\n return <AppInactive />;\n }\n\n if (authState) {\n switch (authState) {\n case 'authorizationStateWaitPhoneNumber':\n case 'authorizationStateWaitCode':\n case 'authorizationStateWaitPassword':\n case 'authorizationStateWaitRegistration':\n case 'authorizationStateWaitQrCode':\n return <Auth />;\n case 'authorizationStateClosed':\n case 'authorizationStateClosing':\n case 'authorizationStateLoggingOut':\n case 'authorizationStateReady':\n return renderMain();\n }\n }\n\n return hasStoredSession(true) ? renderMain() : <Auth />;\n};\n\nfunction renderMain() {\n return (\n <UiLoader page=\"main\" key=\"main\">\n <Main />\n </UiLoader>\n );\n}\n\nexport default withGlobal(\n (global): StateProps => pick(global, ['authState']),\n (setGlobal, actions): DispatchProps => pick(actions, ['disconnect']),\n)(App);\n","import './util/handleError';\nimport './util/setupServiceWorker';\n\nimport React, { getDispatch, getGlobal } from './lib/teact/teactn';\nimport TeactDOM from './lib/teact/teact-dom';\n\nimport './global';\n\nimport { DEBUG } from './config';\n\nimport App from './App';\n\nimport './styles/index.scss';\n\nif (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('>>> INIT');\n}\n\ngetDispatch().init();\n\nif (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('>>> START INITIAL RENDER');\n}\n\nTeactDOM.render(\n <App />,\n document.getElementById('root'),\n);\n\nif (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('>>> FINISH INITIAL RENDER');\n}\n\ndocument.addEventListener('dblclick', () => {\n // eslint-disable-next-line no-console\n console.log('GLOBAL STATE', getGlobal());\n});\n"],"names":["leafPrototypes","getProto","inProgress","dataWebpackPrefix","loadStylesheet","installedCssChunks","worker","requestStates","Map","requestStatesByCallback","initApi","onUpdate","initialArgs","DEBUG","console","log","Worker","URL","addEventListener","data","type","update","requestState","get","messageId","error","reject","resolve","response","callback","callbackArgs","subscribeToWorker","makeRequest","args","callApi","fnName","name","warn","cancelApiProgress","progressCallback","isCanceled","postMessage","message","generateIdFor","payload","promise","Promise","Object","assign","pop","set","catch","finally","delete","ApiMediaFormat","ApiMessageEntityTypes","MAIN_THREAD_ID","MESSAGE_DELETED","base","maxint","adapt","delta","numpoints","firsttime","k","Math","floor","decode","input","preserveCase","output","case_flags","input_length","length","n","out","i","bias","basic","j","ic","oldi","w","digit","t","len","lastIndexOf","charCodeAt","RangeError","push","cp","splice","String","fromCharCode","toUpperCase","value","join","utf16","ensureProtocol","url","includes","getDomain","href","decodedHref","decodeURI","match","domain","replace","domain_array","split","s","slice","convertPunycode","memo","text","className","children","isRtl","toggleSafeLinkModal","openTelegramLink","getDispatch","content","isNotSafe","handleClick","useCallback","e","ctrlKey","altKey","shiftKey","metaKey","RE_TME_LINK","RE_TME_INVITE_LINK","preventDefault","classNames","buildClassName","title","target","rel","onClick","dir","getFileSizeString","bytes","ONE_GIGABYTE","toFixed","ONE_MEGABYTE","getDocumentExtension","document","fileName","mimeType","getFileExtension","indexOf","getColorFromExtension","extension","getDocumentHasPreview","Boolean","previewBlobUrl","thumbnail","RE_EMOJI_ONLY","RegExp","twemojiRegex","DETECT_UP_TO","emojiCount","withGlobal","undefined","setGlobal","actions","pick","sender","openUserInfo","id","Link","focusMessage","handleMessageClick","chatId","openChat","renderActionMessageText","lang","actionOrigin","targetUsers","targetMessage","targetChatId","options","action","translationValues","amount","currency","textOptions","maxTextLength","processed","unprocessed","processPlaceholder","formatCurrency","code","isEmbedded","origin","asPlain","isChat","chat","trimText","getChatTitle","renderText","renderChatContent","renderUserContent","renderOriginContent","map","user","filter","getMessageSummaryText","photo","video","sticker","getMessageContent","showQuotes","messageText","isGif","renderMessageContent","invoice","renderProductContent","renderMigratedContent","trim","getUserFullName","placeholder","replaceValue","placeholderPosition","substring","Array","isArray","forEach","index","RE_LETTER_OR_DIGIT","SIMPLE_MARKDOWN_REGEX","part","filters","params","reduce","textParts","divEl","createElement","result","innerText","innerHTML","escapeHtml","EMOJI_REGEX","replaceEmojis","addLineBreaks","highlight","lowerCaseText","toLowerCase","queryPosition","nextSymbol","newParts","links","RE_LINK","nextLink","shift","lastIndex","startsWith","username","endsWith","addLinks","replaceSimpleMarkdown","size","IS_EMOJI_SUPPORTED","parts","emojis","emojiResult","emoji","nativeToUnfified","removeVS16s","src","alt","line","source","trimmedLine","trimLeft","indentLength","repeat","RE_LINK_TEMPLATE","RE_MENTION_TEMPLATE","entities","entityResult","entity","global","userId","userOrChat","selectUser","openChatByUsername","ref","onContextMenu","onMouseDown","onMouseEnter","onMouseLeave","onFocus","color","round","pill","fluid","isText","isLoading","ariaLabel","download","disabled","ripple","faded","tabIndex","elementRef","useRef","isClicked","setIsClicked","useState","fullClassName","setTimeout","handleMouseDown","label","subLabel","checked","blocking","onChange","onCheck","useLang","handleChange","event","currentTarget","trigger","positionX","positionY","footer","forceOpen","onOpen","onClose","menuRef","dropdownRef","isOpen","setIsOpen","onKeyDown","menu","current","keyCode","focusedElement","activeElement","elementChildren","from","focus","onTrigger","containerRef","autoClose","shouldSkipTransition","success","readOnly","autoComplete","inputMode","maxLength","onInput","onKeyPress","onBlur","onPaste","labelText","htmlFor","withBackground","style","noCloseOnBackdrop","onCloseAnimationEnd","backdropContainerRef","transitionClassNames","useShowTransition","useEffect","captureEscKeyListener","useHistoryBack","useEffectWithPrevDeps","prevIsOpen","dispatchHeavyAnimationEvent","handleKeyDown","useKeyboardListNavigation","useVirtualBackdrop","bubbleClassName","props","icon","destructive","stopPropagation","window","location","role","ripples","setRipples","cleanUpDebounced","useMemo","debounce","button","container","position","getBoundingClientRect","rippleSize","offsetWidth","x","clientX","y","clientY","requestAnimationFrame","PAGE_TITLE","INACTIVE_MARKER","APP_NAME","process","APP_VERSION","DEBUG_MORE","IS_TEST","DEBUG_ALERT_MSG","SESSION_USER_KEY","LEGACY_SESSION_KEY","GLOBAL_STATE_CACHE_DISABLED","GLOBAL_STATE_CACHE_KEY","GLOBAL_STATE_CACHE_CHAT_LIST_LIMIT","GLOBAL_STATE_CACHE_USER_LIST_LIMIT","MEDIA_CACHE_DISABLED","MEDIA_CACHE_NAME","MEDIA_CACHE_NAME_AVATARS","MEDIA_PROGRESSIVE_CACHE_NAME","CUSTOM_BG_CACHE_NAME","LANG_CACHE_NAME","TRANSPARENT_PIXEL","isBigScreen","innerHeight","MIN_PASSWORD_LENGTH","MESSAGE_LIST_SENSITIVE_AREA","MESSAGE_LIST_SLICE","MESSAGE_LIST_VIEWPORT_LIMIT","CHAT_HEIGHT_PX","CHAT_LIST_SLICE","CHAT_LIST_LOAD_SLICE","SHARED_MEDIA_SLICE","MESSAGE_SEARCH_SLICE","GLOBAL_SEARCH_SLICE","MEMBERS_SLICE","MEMBERS_LOAD_SLICE","PROFILE_SENSITIVE_AREA","TOP_CHAT_MESSAGES_PRELOAD_LIMIT","ALL_CHATS_PRELOAD_DISABLED","ANIMATION_LEVEL_MIN","ANIMATION_LEVEL_MAX","ANIMATION_LEVEL_DEFAULT","DEFAULT_MESSAGE_TEXT_SIZE_PX","IOS_DEFAULT_MESSAGE_TEXT_SIZE_PX","MACOS_DEFAULT_MESSAGE_TEXT_SIZE_PX","DRAFT_DEBOUNCE","EDITABLE_INPUT_ID","EDITABLE_INPUT_MODAL_ID","SAFE_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN","SAFE_SCREEN_WIDTH_FOR_CHAT_INFO","MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN","MIN_SCREEN_WIDTH_FOR_STATIC_LEFT_COLUMN","MOBILE_SCREEN_MAX_WIDTH","MOBILE_SCREEN_LANDSCAPE_MAX_WIDTH","MOBILE_SCREEN_LANDSCAPE_MAX_HEIGHT","LOCAL_MESSAGE_ID_BASE","ANIMATION_END_DELAY","FAST_SMOOTH_MAX_DISTANCE","FAST_SMOOTH_MIN_DURATION","FAST_SMOOTH_MAX_DURATION","FAST_SMOOTH_SHORT_TRANSITION_MAX_DISTANCE","STICKER_SIZE_INLINE_DESKTOP_FACTOR","Set","STICKER_SIZE_INLINE_MOBILE_FACTOR","STICKER_SIZE_AUTH","STICKER_SIZE_AUTH_MOBILE","STICKER_SIZE_PICKER","STICKER_SIZE_GENERAL_SETTINGS","STICKER_SIZE_PICKER_HEADER","STICKER_SIZE_SEARCH","STICKER_SIZE_MODAL","STICKER_SIZE_TWO_FA","STICKER_SIZE_DISCUSSION_GROUPS","STICKER_SIZE_FOLDER_SETTINGS","STICKER_SIZE_INLINE_BOT_RESULT","MEMOJI_STICKER_ID","BASE_EMOJI_KEYWORD_LANG","MENU_TRANSITION_DURATION","SLIDE_TRANSITION_DURATION","CONTENT_TYPES_FOR_QUICK_UPLOAD","SERVICE_NOTIFICATIONS_USER_ID","ALL_FOLDER_ID","ARCHIVED_FOLDER_ID","MAX_MEDIA_FILES_FOR_ALBUM","MAX_ACTIVE_PINNED_CHATS","SCHEDULED_WHEN_ONLINE","DEFAULT_LANG_CODE","DEFAULT_LANG_PACK","LANG_PACKS","TIPS_USERNAME","LOCALIZED_TIPS","FEEDBACK_URL","LIGHT_THEME_BG_COLOR","DARK_THEME_BG_COLOR","DARK_THEME_PATTERN_COLOR","DEFAULT_PATTERN_COLOR","cb","dependencies","debugKey","prevDeps","usePrevious","initial","setValue","setTrigger","ANIMATION_START_EVENT","ANIMATION_END_EVENT","timeout","isAnimating","duration","dispatchEvent","Event","clearTimeout","handleAnimationStart","handleAnimationEnd","removeEventListener","LOCATION_HASH","hash","historyState","currentIndex","nextStateIndexToReplace","isHistoryAltered","isDisabled","isEdge","currentIndexes","disableHistoryBack","handleTouchEnd","isActive","onBack","onForward","currentState","shouldReplaceNext","hashes","indexRef","isForward","prevIsActive","isClosed","indexHashRef","prevHashes","isHashChangedFromEvent","isForceClose","prev","history","pushState","state","last","realDelta","indexLast","findIndex","l","go","replaceState","back","handlePopState","currIndex","disableHistoryAnimations","hasChanged","areSortedArraysEqual","forceClose","IS_IOS","touches","pageX","innerWidth","pathname","onSelectWithEnter","itemSelector","noCaptureFocus","focusedIndex","setFocusedIndex","element","querySelectorAll","newIndex","item","forceUpdate","useForceUpdate","useOnChange","langProvider","bundleName","moduleName","noLoad","autoUpdate","module","getModuleFromMemory","addLoadListener","loadModule","then","some","d","next","shouldSkipUndefined","onCloseTransitionEnd","noOpenTransition","noCloseTransition","setIsClosed","closeTimeoutRef","hasOpenClassName","setHasOpenClassName","shouldHaveOpenClassName","isClosing","shouldRender","handleEvent","contains","classList","NON_BUBBLEABLE_EVENTS","delegationRegistry","delegatedEventsByElement","documentEventCounters","propName","handler","asCapture","eventName","resolveEventName","canUseEventDelegation","resolveDelegationRegistryForName","existing","newSet","resolveDelegatedEventsForElement","add","addDelegatedListener","removeDelegatedListener","tagName","realEventName","has","removeAllDelegatedListeners","eventNames","realEvent","events","furtherCallsPrevented","Proxy","p","Reflect","body","parentNode","FILTERED_ATTRIBUTES","HTML_ATTRIBUTES","MAPPED_ATTRIBUTES","autoPlay","headsByElement","renderWithVirtual","parentEl","$current","$new","$parent","skipComponentUpdate","forceIndex","fragment","moveDirection","isComponentElement","hasElementChanged","componentInstance","renderComponent","updateComponent","isMounted","setupComponentUpdateListener","initComponent","node","createNode","setTarget","childNodes","insertBefore","appendChild","removeChild","getTarget","unmountTree","replaceChild","areComponents","isRealElement","nextSibling","currentKeys","keys","newKeys","key","removeAttribute","addAttribute","oldValue","newValue","updateAttribute","updateAttributes","currentEl","teactFastList","$newChild","currentRemainingIndex","remainingByKey","acc","$currentChild","newChildKey","$element","order","teactOrderKey","fragmentQueue","fragmentIndex","newChildren","currentPreservedIndex","currentChildInfo","concat","flushFragmentQueue","shouldMoveNode","isMovingDown","renderFastListChildren","max","createDocumentFragment","renderChildren","mountComponent","$firstChild","isEmptyElement","createTextNode","isTextElement","tag","$child","$fragmentChild","Error","cssText","setAttribute","render","headId","getAttribute","$head","VirtualElementTypesEnum","Fragment","Symbol","renderingInstance","Empty","Text","isTagElement","Tag","Component","flatten","parsedChildren","hooks","cursor","byCursor","effects","memos","buildComponentElement","createComponentInstance","dropEmptyTail","buildChildElement","buildTagElement","isEmptyPlaceholder","child","DEBUG_components","newRenderedValue","DEBUG_startAt","componentName","renderCount","renderTimes","performance","now","renderTime","err","handleError","renderedValue","newChild","$old","hook","cleanup","effect","nextValue","setter","helpGc","prepareComponentForFrame","prepareForFrame","throttleWithPrimaryRaf","throttleWithRaf","forceUpdateComponent","currentElement","DEBUG_contentComponentName","useLayoutEffectBase","schedulerFn","exec","dependency","causedBy","res","prevValue","fastRaf","useLayoutEffect","onTickEnd","resolver","getUnequalProps","newCallback","areEqual","arePropsShallowEqual","propsRef","renderedRef","orderBy","values","React","currentGlobal","reducers","callbacks","containers","mapStateToProps","mapReducersToProps","ownProps","mappedProps","newMappedProps","Number","isNaN","DEBUG_componentName","areMappedPropsChanged","DEBUG_updates","updateTime","runCallbacks","runCallbacksThrottled","newGlobal","noThrottle","getGlobal","addReducer","reducer","onDispatch","addCallback","removeCallback","TeactNContainer","vs16RegExp","zeroWidthJoiner","rawEmoji","importLegacySession","clearLegacySessions","apiUpdate","userAgent","navigator","platform","PLATFORM_ENV","sessionData","loadStoredSession","phoneNumber","authIsLoading","authError","password","file","firstName","lastName","authIsLoadingQrCode","storeSession","currentUserId","clearStoredSession","unsubscribe","forceWebsync","reset","cacheApi","langCachePrefix","langCacheVersion","updateAppBadge","init","connectionState","authNearestCountry","deviceToken","subscribedAt","Date","buildInputPrivacyRules","visibility","allowedIds","deniedIds","users","byId","usersById","chats","chatsById","rules","collectUsers","isChatPrivate","accessHash","collectChats","allowedUsers","allowedChats","blockedUsers","blockedChats","bio","about","profileEdit","progress","ProfileEditProgress","currentUser","updateUser","fullInfo","isUsernameAvailable","settings","loadedWallpapers","wallpapers","createObjectURL","slug","UPLOADING_WALLPAPER_SLUG","wallpaper","firstWallpaper","withLocalMedia","addUsers","buildCollectionByKey","updateChats","blocked","ids","blockedIds","totalCount","contactId","addBlockedContact","removeBlockedContact","activeSessions","session","isCurrent","serverTimeOffset","addNotifyExceptions","replaceSettings","peerType","isSilent","shouldShowPreviews","updateNotifySettings","hasPushNotifications","hasWebNotifications","byKey","subscribe","hasContactJoinedNotifications","languages","phoneNumberSettings","lastSeenSettings","profilePhotoSettings","forwardsSettings","chatInviteSettings","all","privacy","lastSeen","profilePhoto","forwards","chatInvite","privacyKey","allowUserIds","allowChatIds","blockUserIds","blockChatIds","isAllowList","contactsIds","isSensitiveEnabled","selectNotifySettings","setLanguage","language","onUpdateApiReady","wasAuthReady","authState","authorizationState","isLoggingOut","authIsCodeViaApp","isCodeViaApp","authHint","hint","authQrCode","qrCode","lastSyncTime","onUpdateAuthorizationState","onUpdateAuthorizationError","sync","signOut","onUpdateConnectionState","authRememberMe","isEmpty","mainDcId","saveSession","onUpdateSession","onUpdateServerTimeOffset","sessionUserAuth","localStorage","getItem","userAuth","JSON","parse","setItem","stringify","updateSessionUserId","onUpdateCurrentUser","paymentShippingError","getShippingError","addPaymentError","showDialog","hasErrorKey","handleSystemThemeChange","currentThemeMatch","documentElement","currentTheme","nextTheme","selectTheme","animationLevel","switchTheme","mql","matchMedia","addListener","subscribeToSystemThemeChange","messageTextSize","theme","setProperty","toString","IS_TOUCH_ENV","startWebsync","IS_SAFARI","IS_ANDROID","IS_MAC_OS","uiReadyState","remove","authPhoneNumber","shouldSkipHistoryAnimations","replaceThemeSettings","FOREVER_BANNED_DATE","isChatGroup","isChatBasicGroup","isChatSuperGroup","isChatChannel","isCommonBoxChat","getChatTypeString","getPrivateChatUserId","isSelf","getChatDescription","getChatLink","inviteLink","getChatAvatarHash","owner","avatarHash","isChatSummaryOnly","lastMessage","isChatAdmin","adminRights","getHasAdminRight","isUserRightBanned","currentUserBannedRights","defaultBannedRights","getCanPostInChat","threadId","isRestricted","migratedTo","isNotJoined","isCreator","getAllowedAttachmentOptions","isChatWithBot","canAttachMedia","canAttachPolls","canSendStickers","canSendGifs","canAttachEmbedLinks","isAdmin","getMessageSendingRestrictionReason","sendMessages","untilDate","formatDateToString","formatTime","getChatSlowModeOptions","slowMode","getChatOrder","joinDate","draftDate","date","isChatArchived","folderId","selectIsChatMuted","notifySettings","notifyExceptions","isMuted","hasPrivateChatsNotifications","hasBroadcastNotifications","hasGroupNotifications","selectShouldShowMessagePreview","hasPrivateChatsMessagePreview","hasBroadcastMessagePreview","hasGroupMessagePreview","getCanDeleteChat","prepareFolderListIds","folder","chatIdsCache","excludedChatIds","includedChatIds","pinnedChatIds","isListed","excludeArchived","excludeMuted","unreadMentionsCount","unreadCount","hasUnreadMark","excludeRead","privateChatUser","bots","contacts","isContact","nonContacts","groups","channels","filterChatFolder","prepareChatList","listIds","orderedPinnedIds","folderType","chatFilter","listedChats","listIdsSet","pinnedChats","otherChats","getFolderUnreadDialogs","unreadDialogsCount","total","hasActiveDialogs","getFolderDescriptionText","emoticon","description","pinnedIds","getFolderChatsCount","chatOrUser","getMessageSenderName","getUserFirstOrLastName","sortChatIds","chatIds","shouldPrioritizeVerified","priorityIds","priority","isVerified","CONTENT_NOT_SUPPORTED","getMessageKey","parseMessageKey","getMessageOriginalId","previousLocalId","noEmoji","audio","voice","contact","poll","truncatedText","substr","groupedId","getMessageAudioCaption","summary","question","getMessageText","webPage","getMessageCustomShape","isRound","parseEmojiOnlyString","getMessageSingleEmoji","getFirstLinkInMessage","link","find","offset","isOwnMessage","isOutgoing","isReplyMessage","replyToMessageId","isForwardedMessage","forwardInfo","isActionMessage","isServiceNotificationMessage","isMessageLocal","isAnonymousOwnMessage","senderId","getSenderTitle","getSendingState","sendingState","isHistoryClearMessage","performer","hasMessageMedia","getMessagePhoto","getMessageVideo","getMessageDocument","getMessageSticker","getMessageContact","getMessagePoll","getMessageAction","getMessageAudio","getMessageVoice","getMessageRoundVideo","isMessageDocumentPhoto","mediaType","isMessageDocumentVideo","getMessageInvoice","getMessageWebPage","getMessageWebPagePhoto","getMessageWebPageVideo","getMessageMediaThumbDataUri","media","getMessageMediaThumbnail","dataUri","getMessageMediaHash","webPagePhoto","webPageVideo","messageVideo","messagePhoto","hasMessageLocalBlobUrl","getVideoOrAudioBaseHash","IS_PROGRESSIVE_SUPPORTED","getMessageMediaFormat","fullVideo","isAnimated","IS_OPUS_SUPPORTED","getMessageFileName","getMessageFileSize","blobUrl","getChatMediaMessageIds","messages","listedIds","isFromSharedMedia","getMessageContentIds","reverse","getPhotoFullDimensions","sizes","getPhotoInlineDimensions","getVideoDimensions","width","height","getMediaTransferState","isDownloadNeeded","isUploading","isTransferring","transferProgress","messageIds","contentType","validator","matchLinkInMessageText","getMediaDuration","buildChatThreadKey","STRIPE_ERRORS","missing_payment_information","field","invalid_number","number","exp_year","exp_month","invalid_expiry_year","invalid_expiry_month","cvc","invalid_cvc","getStripeError","param","USER_COLOR_KEYS","isDeletedUser","getUserStatus","status","wasOnline","getTime","wasOnlineDate","diff","today","setHours","yesterday","setDate","getDate","formatFullDate","isUserOnline","isUserBot","sortUserIds","userIds","expires","getUserColorKey","peer","abs","replaceChatListIds","newIds","updateChatListIds","idsUpdate","replaceChats","newById","getUpdatedChat","chatUpdate","shouldOmitMinInfo","isMin","updatedChat","omit","photos","updateChat","updatedById","updatedChats","addChats","addedById","isAdded","addedChats","updateChatListType","listType","currentListIds","listTypeKey","currentFolderList","updateChatListSecondaryInfo","info","totalCountKey","totalChatCount","isFullyLoaded","updateCurrentMessageList","shouldReplaceHistory","messageLists","newMessageLists","replaceChatMessages","updateMessageStore","byChatId","threadsById","replaceThreadParam","paramName","threadUpdate","updateThread","addMessages","addedByChatId","messagesByChatId","addChatMessagesById","selectChatMessages","every","newId","updateChatMessage","messageUpdate","updatedMessage","updateScheduledMessage","selectScheduledMessages","replaceScheduledMessages","deleteChatMessages","deletedForwardedPosts","pickTruthy","isLinkedChannelPost","threadInfo","selectThreadInfo","selectListedIds","outlyingIds","selectOutlyingIds","viewportIds","selectViewportIds","selectPinnedIds","newMessageCount","messagesCount","currentMessageList","selectCurrentMessageList","canDeleteCurrentThread","currentThreadId","fromChatId","fromMessageId","originalPost","selectChatMessage","deleteChatScheduledMessages","scheduledIds","selectScheduledIds","updateListedIds","orderHistoryIds","updateOutlyingIds","sort","a","b","addViewportId","safeReplaceViewportIds","newViewportIds","updateThreadInfo","newThreadInfo","updateThreadInfos","updates","scheduledMessages","updateScheduledMessages","updateFocusedMessage","noHighlight","isResizingContainer","focusedMessage","updateFocusDirection","direction","enterMessageSelectMode","selectedMessages","prototype","toggleMessageSelection","messageListType","childMessageIds","withShift","oldSelectedMessages","selectMessageIdsByGroupId","selectedMessageIds","newMessageIds","newSelectedMessageIds","selectCurrentMessageIds","prevIndex","min","to","unique","exitMessageSelectMode","updateStickerSets","category","sets","resultIds","updatedSets","stickerSet","stickers","setsById","setIds","updateStickerSet","stickerSetId","currentStickerSet","updateGifSearch","isNew","results","nextOffset","currentResults","gifs","search","newResults","currentIds","gif","replaceAnimatedEmojis","animatedEmojis","updateStickersForEmoji","remoteStickers","allStickers","selectStickersForEmoji","uniqueIds","forEmoji","rebuildStickersForEmoji","replaceUsers","getUpdatedUser","userUpdate","updatedUser","updateContactList","updatedUsers","contactUserIds","contactList","newContactUserIds","updateUsers","addedUsers","updateSelectedUserId","selectedId","deleteUser","MEMO_EMPTY_ARRAY","updateUserSearch","searchStatePartial","userSearch","updateUserSearchFetchingStatus","newState","fetchingStatus","updateUserBlockedState","isBlocked","getComplexKey","updateGlobalSearch","globalSearch","updateGlobalSearchContent","currentContent","updateGlobalSearchResults","newFoundMessages","nextRate","resultsByType","newFoundMessagesById","foundIdsForType","foundIds","updateGlobalSearchFetchingStatus","prevFoundIds","newFoundIds","foundOrPrevFoundIds","nextOffsetId","replaceLocalTextSearch","chatThreadKey","searchParams","localTextSearch","byChatThreadKey","updateLocalTextSearch","query","replaceLocalTextSearchResults","updateLocalTextSearchResults","orderFoundIds","replaceLocalMediaSearch","localMediaSearch","updateLocalMediaSearchType","currentType","updateLocalMediaSearchResults","replaceLocalMediaSearchResults","updateManagementProgress","management","updateManagement","newSettings","themes","notifyException","exceptionData","addNotifyException","updateTwoFaSettings","twoFaSettings","updateShippingOptions","shippingOptions","payment","setRequestInfoId","requestId","setPaymentStep","step","setInvoiceMessageInfo","isTest","photoUrl","invoiceContent","setStripeCardInfo","cardInfo","stripeCredentials","setPaymentForm","form","setReceipt","receipt","messageInvoice","clearPayment","closeInvoice","isPaymentModalOpen","selectIsUserBlocked","selectNotifyExceptions","selectChat","selectChatUser","selectIsChatWithSelf","selectIsChatWithBot","selectSupportChat","isSupport","selectChatOnlineCount","members","onlineCount","selectChatBot","selectIsChatBotNotStarted","bot","messageInfo","selectAreActiveChatsLoaded","active","selectIsChatListed","targetList","list","selectChatListType","selectChatFolder","chatFolders","selectIsChatPinned","archived","chatFoldersById","selectChatByUsername","usernameLowered","selectCountNotMutedUnread","activeChatIds","selectCurrentStickerSearch","selectCurrentGifSearch","selectStickerSet","selectStickerSetByShortName","shortName","stickerSets","stickersForEmoji","packs","selectAnimatedEmoji","cleanedEmoji","selectCurrentChat","selectThreadParam","thread","selectScrollOffset","selectReplyingToId","selectEditingId","selectEditingScheduledId","selectDraft","selectNoWebPage","selectFirstMessageId","selectReplyStack","selectThreadOriginChat","originChannelId","selectThreadTopMessageId","topMessageId","selectThreadByMessage","replyToTopMessageId","isMessageInCurrentMessageList","selectIsViewportNewest","lastMessageId","chatMessages","selectScheduledMessage","selectEditingMessage","selectChatMessageByPollId","pollId","messageWithPoll","selectFocusedMessageId","focusedChatId","selectIsMessageFocused","focusedId","selectOutgoingStatus","isScheduledList","lastReadOutboxMessageId","selectIsMessageUnread","selectSender","selectForwardedSender","isChannelPost","senderUserId","selectAllowedMessageActions","isPrivate","isChatWithSelf","isBasicGroup","isSuperGroup","isChannel","isServiceNotification","isOwn","isAction","isMessageEditable","viaBotId","canReply","hasPinPermission","canPin","canUnpin","pinnedMessageIds","canDelete","canReport","canDeleteForAll","canEdit","canForward","hasSticker","hasFavoriteSticker","favorite","selectIsStickerFavorite","canFaveSticker","canUnfaveSticker","canCopy","canCopyLink","canSelect","noOptions","ability","selectCanDeleteSelectedMessages","messageActions","selectCanReportSelectedMessages","selectUploadProgress","fileTransfer","fileUploads","byMessageLocalId","selectRealLastReadId","lastReadInboxMessageId","Infinity","selectFirstUnreadId","lastReadId","found","isFromScheduled","selectIsForwardModalOpen","forwardMessages","isModalShown","selectCommonBoxChatId","fromLastMessage","selectIsInSelectMode","selectIsMessageSelected","selectForwardedMessageIdsByGroupId","selectIsDocumentGroupSelected","selectedIds","groupIds","selectSelectedMessagesCount","selectNewestMessageWithBotKeyboardButtons","findLast","keyboardButtons","replyHideMessageId","shouldHideKeyboardButtons","selectShouldAutoLoadMedia","shouldAutoDownloadMediaFromContacts","shouldAutoDownloadMediaInPrivateChats","shouldAutoDownloadMediaInGroups","shouldAutoDownloadMediaInChannels","selectIsUserOrChatContact","selectShouldAutoPlayMedia","shouldAutoPlayVideos","shouldAutoPlayGifs","asGif","selectShouldLoopStickers","shouldLoopStickers","selectCurrentTextSearch","currentSearch","selectCurrentMediaSearchPeerId","currentProfileUserId","selectCurrentMediaSearch","peerId","selectManagement","selectCurrentManagementType","selectIsMediaViewerOpen","mediaViewer","avatarOwnerId","selectRightColumnContentKey","isChatInfoShown","newChatMembersProgress","isAddingChatMembersShown","NewChatMembersProgress","isPollResults","pollResults","selectIsPollResultsOpen","isSearch","IS_SINGLE_COLUMN_LAYOUT","isManagement","currentManagement","selectCurrentManagement","isStickerSearch","isGifSearch","currentChatId","areActiveChatsLoaded","isUserInfo","isChatInfo","RightColumnContent","selectIsRightColumnShown","shouldUseSystemTheme","getSystemTheme","selectCurrentGlobalSearchQuery","selectPaymentChatId","selectPaymentMessageId","selectPaymentFormId","formId","selectPaymentRequestId","selectProviderPublishableKey","nativeParams","publishableKey","selectStripeCredentials","LoadMoreDirection","FocusDirection","SettingsScreens","LeftColumnContent","GlobalSearchContent","MediaViewerOrigin","ChatCreationProgress","ManagementProgress","ProfileState","PaymentStep","ManagementScreens","currentInstance","animateSingle","tick","instance","isCancelled","animate","setAppBadge","currentProps","newProps","currentKeysLength","prop","self","caches","Type","async","fetch","cacheName","request","Request","cache","open","Blob","blob","headers","Json","json","save","cacheData","Response","put","clear","captureKeyboardListener","onEsc","keyToHandlerName","Enter","Backspace","Delete","Esc","Escape","ArrowUp","ArrowDown","ArrowLeft","ArrowRight","Tab","handlers","onEnter","onDelete","onBackspace","onUp","onDown","onLeft","onRight","onTab","captureKeyboardListeners","hasActiveHandlers","handlerName","currentEventHandlers","releaseKeyboardListener","keyHandlers","WEEKDAYS_FULL","MONTHS_FULL","MONTHS_FULL_LOWERCASE","month","getDayStart","datetime","getDayStartAt","toYearMonth","timestamp","getFullYear","getMonth","toIsoString","getHours","padStart","getMinutes","formatPastTimeShort","weekAgo","getDay","withYear","format","formatDate","formatMonthAndYear","isShort","formatHumanDate","noWeekdays","lowerFirst","upperFirst","weekAhead","weekDay","day","monthIndex","formatMediaDateTime","formatMediaDuration","hours","minutes","seconds","string","formatVoiceRecordDuration","durationInMs","milliseconds","locale","toLocaleString","year","isValidDate","MAX_MONTH_IN_YEAR","parseDateString","matchStringDate","matchEuropeStringDate","matchNumberDate","dateParts","timestampPlusDay","MILISECONDS_IN_DAY","str","EXCLUDE_EMOJIS","unifiedToNative","unified","codePoints","parseInt","fromCodePoint","pairs","uncompressEmoji","emojiData","categories","emojiRaw","names","native","image","isWebpSupportedCache","isWebpSupported","webp","Image","handleLoadOrError","onload","onerror","hasWebp","systemThemeCache","matches","os","test","getPlatform","IS_PWA","standalone","referrer","IS_TABLET_COLUMN_LAYOUT","IS_VOICE_RECORDING_SUPPORTED","mediaDevices","AudioContext","webkitAudioContext","IS_SERVICE_WORKER_SUPPORTED","Audio","canPlayType","IS_CANVAS_FILTER_SUPPORTED","getContext","LAYERS_ANIMATION_NAME","DPR","devicePixelRatio","MASK_IMAGE_DISABLED","dataUriToBlob","arr","mime","bstr","atob","u8arr","Uint8Array","blobToDataUri","reader","FileReader","readAsDataURL","blobToFile","File","lastModified","preloadImage","img","preloadVideo","volume","onloadedmetadata","createPosterForVideo","race","pause","onseeked","videoWidth","videoHeight","canvas","drawImage","toDataURL","currentTime","fetchBlob","imgToCanvas","constructor","fileBits","rest","super","this","totalPrice","Intl","NumberFormat","store","random","hasOwnProperty","READABLE_ERROR_MESSAGES","CHAT_RESTRICTED","CHAT_WRITE_FORBIDDEN","CHAT_SEND_POLL_FORBIDDEN","CHAT_SEND_STICKERS_FORBIDDEN","CHAT_SEND_GIFS_FORBIDDEN","CHAT_SEND_MEDIA_FORBIDDEN","CHAT_LINK_EXISTS","SLOWMODE_WAIT_X","USER_BANNED_IN_CHANNEL","USER_IS_BLOCKED","YOU_BLOCKED_USER","IMAGE_PROCESS_FAILED","MEDIA_EMPTY","MEDIA_INVALID","PHOTO_EXT_INVALID","PHOTO_INVALID_DIMENSIONS","PHOTO_SAVE_FILE_INVALID","MESSAGE_DELETE_FORBIDDEN","MESSAGE_POLL_CLOSED","MESSAGE_EDIT_TIME_EXPIRED","CHAT_ADMIN_REQUIRED","PINNED_DIALOGS_TOO_MUCH","DIALOG_FILTERS_TOO_MUCH","CHANNEL_PRIVATE","MEDIA_CAPTION_TOO_LONG","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","LINK_NOT_MODIFIED","SERVICE_WORKER_DISABLED","CAPTION_TOO_LONG_PLEASE_REMOVE_CHARACTERS","FRESH_RESET_AUTHORISATION_FORBIDDEN","BOTS_TOO_MUCH","BOT_GROUPS_BLOCKED","USERS_TOO_MUCH","USER_CHANNELS_TOO_MUCH","USER_KICKED","USER_NOT_MUTUAL_CONTACT","USER_PRIVACY_RESTRICTED","INVITE_HASH_EMPTY","INVITE_HASH_EXPIRED","INVITE_HASH_INVALID","CHANNELS_TOO_MUCH","USER_ALREADY_PARTICIPANT","SCHEDULE_DATE_INVALID","WALLPAPER_DIMENSIONS_INVALID","SHIPPING_ERRORS","getReadableErrorText","isSlowMode","textParams","extraPartIndex","errorMessage","handleErrorEvent","ErrorEvent","reason","throttle","alert","collection","member","mapValues","newByKey","object","stringKeys","orderKey","mode","mode1","mode2","orderKey1","orderKey2","aValue1","bValue1","aValue2","bValue2","aValue","bValue","array","compact","array1","array2","areSortedArraysIntersecting","findIntersectionWithSet","chunkSize","cloneDeep","predicate","SUBSTITUTION_REGEX","PLURAL_OPTIONS","PLURAL_RULES","en","ar","ca","de","es","fa","fr","it","ko","ms","nl","pl","pt_BR","ru","tr","uk","uz","langPack","fallbackLangPack","createCallbackManager","currentLangCode","getTranslation","cacheValue","cached","langString","processTranslation","importFallbackLangPack","getTranslationForLangString","langCode","translateString","remoteLangPack","remote","fetchRemoteString","withFallback","newLangPack","sourceLangPacks","fetchRemote","langInfo","rtl","default","template","optionIndex","getPluralOption","translationSlices","initialValue","processTemplate","formatInteger","SAMPLE_RATE","oggToWav","opusData","arrayBuffer","typedArray","decoderWorker","wavWorker","onmessage","command","buffers","buffer","page","terminate","wavBitDepth","wavSampleRate","decoderSampleRate","outputBufferSampleRate","pages","asCacheApiType","memoryCache","fetchPromises","mediaFormat","onProgress","progressiveUrl","getProgressive","mediaPng","webpToPng","prepared","prepareMedia","mediaSource","MediaSource","streamUrl","sourceBuffer","addSourceBuffer","endOfStream","appendBuffer","revokeObjectURL","fetchFromCacheOrRemote","getFromMemory","cancelProgress","mediaData","serviceWorker","fullSize","controller","Bundles","LOAD_PROMISES","MEMORY_CACHE","Auth","Main","Extra","handleBundleLoad","bundle","listeners","listener","getDeviceToken","subscription","toJSON","endpoint","checkIfPushSupported","ServiceWorkerRegistration","Notification","permission","soundPlayed","playNotificationSound","notificationSoundVolume","once","play","requestPermission","unsubscribeFromPush","dispatch","deleteDeviceToken","serviceWorkerRegistration","ready","pushManager","getSubscription","areSettingsLoaded","checkIfShouldResubscribe","userVisibleOnly","setDeviceToken","DOMException","ABORT_ERR","handledNotifications","pendingNotifications","flushNotifications","groupLimit","count","groupId","showNotification","group","badge","vibrate","notification","onclick","close","onshow","showNewMessageNotification","isActiveChat","resultSettings","resultExceptions","loadNotificationSettings","hasFocus","checkIfShouldNotify","messageSender","messageAction","actionTargetMessage","targetUserIds","actionTargetUserIds","actionTargetChatId","actionTargetUsers","privateChatUserId","senderName","getNotificationContent","imageHash","mediaLoader","getAvatar","handleNotification","notifyClientReady","formatsCache","defaultPhoneNumberFormat","flag","phoneFormat","formatValue","phoneNumberFormat","phoneNumberGroups","getPhoneNumberFormat","getCountryById","countryList","c","getCountryFromPhoneNumber","possibleCountries","country","formatPhoneNumber","_","p1","p2","p3","p4","p5","separator","formatPhoneNumberWithCode","numberWithPlus","fn","shouldRunFirst","shouldRunLast","waitingTimeout","interval","isPending","_args","setInterval","clearInterval","throttleWith","fastPrimaryRaf","waiting","onIdle","requestIdleCallback","rafPromise","fastRafCallbacks","fastRafPrimaryCallbacks","beforeUnloadCallbacks","isPrimary","currentCallbacks","currentPrimaryCallbacks","onBeforeUnload","isLast","unshift","RE_NOT_LETTER","searchWords","haystack","needle","haystackWords","needleWord","haystackWord","promisifyRequest","oncomplete","onsuccess","onabort","defaultGetStoreFunc","defaultGetStore","dbName","storeName","dbp","userAgentData","indexedDB","databases","intervalId","tryIdb","onupgradeneeded","createObjectStore","txMode","db","transaction","objectStore","createStore","DC_IDS","hasStoredSession","withLegacy","userAuthJson","dcID","dcId","removeItem","sessionId","sessionJson","customStore","idb","idbKeys","items","openCursor","continue","eachCursor","isInitialized","HEX_COLOR_REGEX","lerp","start","end","interpolationRatio","colors","themeColors","property","hexToRgb","withAnimation","isDarkTheme","shouldAnimate","startIndex","endIndex","startAt","themeColorTag","querySelector","applyColorAnimationStep","transition","hex","r","g","propertyColors","formatFixedNumber","formatIntegerCompact","views","getFirstLetters","phrase","word","EMPTY_IMAGE_DATA_URI","initWebpWorker","wasmReady","requests","getDecodePromise","ImageData","putImageData","toBlob","createPng","webpToPngBase64","pngBlob","handleLibWebpMessage","WEBSYNC_URLS","WEBSYNC_VERSION","WEBSYNC_KEY","getTs","lastTimeout","authed","currentTs","canRedirect","ts","script","removeElement","URLSearchParams","version","saveSync","IS_LANDSCAPE","isLandscape","initialHeight","windowSize","updateSizes","isRefreshDisabled","handleResize","reload","vh","getIsKeyboardVisible","disableRefresh","enableRefresh","__webpack_module_cache__","__webpack_require__","moduleId","cachedModule","exports","__webpack_modules__","call","m","getter","__esModule","getPrototypeOf","obj","ns","create","def","getOwnPropertyNames","definition","o","defineProperty","enumerable","f","chunkId","promises","u","miniCssF","globalThis","Function","done","needAttach","scripts","getElementsByTagName","charset","nc","onScriptComplete","doneFns","bind","head","toStringTag","scriptUrl","importScripts","currentScript","fullhref","existingLinkTags","dataHref","existingStyleTags","findStylesheet","linkTag","errorType","realHref","createStylesheet","miniCss","baseURI","installedChunks","installedChunkData","realSrc","webpackJsonpCallback","parentChunkLoadingFunction","chunkIds","moreModules","runtime","chunkLoadingGlobal","handleWorkerMessage","register","INITIAL_STATE","isLeftColumnShown","activeChatFolder","recentEmojis","added","recent","greeting","featured","emojiKeywords","saved","inlineBots","byUsername","topPeers","topInlineBots","audioPlayer","notifications","dialogs","messageSendKeyCombo","shouldSuggestStickers","light","isBlurred","patternColor","dark","shouldShowContextMenuHint","updateCacheThrottled","updateCache","unsubscribeFromBeforeUnload","isCaching","isHeavyAnimating","setupCaching","clearCaching","reducedGlobal","reduceShowChatInfo","reduceUsers","reduceChats","reduceMessages","recentlyFoundChatIds","reduceSettings","reduceChatFolders","idsToSave","cid","chatIdsToSave","mainThread","initialState","time","timeEnd","readCache","loadCache","STORAGE_KEY","tabKey","SITE_FONTS","preloadFonts","font","fonts","load","preloadAvatars","preloadTasks","main","telegramLogoPath","authCode","monkeyPath","authPassword","background","backgroundColor","hasCustomBackground","hasCustomBackgroundColor","isRightColumnShown","setIsUiReady","isReady","markReady","useFlag","shouldRenderMask","safePreload","translation","setTranslation","getSuggestedLanguage","suggestedLanguage","MENU_HIDING_DURATION","inputRef","setFilter","filteredList","setFilteredList","updateFilter","filterValue","getFilteredList","countryId","firstElementChild","dataset","handleInput","handleInputKeyDown","DropdownMenu","handleTrigger","select","formEl","getElementById","scrollTo","top","scrollHeight","behavior","inputValue","Spinner","MenuItem","isPreloadInitiated","setAuthPhoneNumber","setAuthRememberMe","loadNearestCountry","clearAuthError","goToAuthQrCode","setSettingOption","continueText","useLangString","setCountry","setPhoneNumber","isTouched","setIsTouched","lastSelection","setLastSelection","markIsLoading","unmarkIsLoading","fullNumber","canSubmit","parseFullNumber","newFullNumber","suggestedCountry","selectedCountry","handleLangChange","setSelectionRange","isJustPastedRef","handlePaste","handlePhoneNumberChange","selectionStart","selectionEnd","shouldFixSafariAutoComplete","handleKeepSessionChange","isAuthReady","onSubmit","InputText","Checkbox","Button","Loading","AuthCode","useModuleLoader","AuthPassword","AuthRegister","G","H","B","QrCreator","h","J","level","O","C","lineTo","arcTo","moveTo","z","v","N","K","P","fillStyle","fillRect","left","beginPath","q","D","E","R","I","F","fill","colorStops","createLinearGradient","apply","createRadialGradient","addColorStop","A","minVersion","maxVersion","ecLevel","radius","quiet","HTMLCanvasElement","clearRect","write","S","multiply","L","M","Q","returnToAuthPhoneNumber","qrCodeRef","token","isMobile","AuthQrCode","appInactivePath","renderMain","disconnect","isInactive","markInactive","TeactDOM"],"sourceRoot":""} |