mirror of
https://github.com/danog/telegram-tt.git
synced 2024-11-27 12:55:11 +01:00
1 line
768 KiB
Plaintext
1 line
768 KiB
Plaintext
{"version":3,"file":"main.a370659192d9281c47be.js","mappings":"uBACIA,EADAC,ECAAC,EACAC,ECwCAC,EASAC,E,wFChCJ,IAAIC,EACJ,MAAMC,EAAgB,IAAIC,IACpBC,EAA0B,IAAID,IAI7B,SAASE,EAAQC,EAAuBC,GAe7C,OAdKN,IACCO,EAAAA,IAEFC,QAAQC,IAAI,yBAGdT,EAAS,IAAIU,OAAO,IAAIC,IAAI,mBA6ChC,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,SACzC,UAAAb,EAAcgB,IAAIJ,EAAKK,kBAAvB,mBAAmCK,gBAAnC,mBAAiDV,EAAKW,mBACjD,GAAkB,mBAAdX,EAAKC,KACd,MAAMD,EAAKM,SA5DbM,CAAkBpB,GAEW,QAAzBC,EAAYoB,UAuGlBC,OAAOf,iBAAiB,SAASgB,UAC/B,UACQC,QAAQC,KAAK,CACjBC,EAAY,CAAEjB,KAAM,UACpBkB,EAAAA,EAAAA,IA9HqB,KA8HOC,MAAK,IAAMJ,QAAQT,OAAO,IAAIc,MAAM,6BAElE,MAAOC,GAEP3B,QAAQW,MAAMgB,GAEVC,KAAKC,MAAQC,GAnIQ,KAoIvBX,OAAOY,SAASC,cA7GfT,EAAY,CACjBjB,KAAM,UACN2B,KAAM,CAACnC,KAIJ,SAASoC,EAAiCC,KAAcF,GAC7D,GAAKzC,EASL,OAAO+B,EAAY,CACjBjB,KAAM,aACN8B,KAAMD,EACN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,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/GroupCallLink.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/helpers/preventMessageInputBlur.ts","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/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/modules/selectors/settings.ts","webpack://telegram-t/./src/modules/selectors/users.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/ensureProtocol.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/phoneNumber.ts","webpack://telegram-t/./src/util/routing.ts","webpack://telegram-t/./src/util/schedulers.ts","webpack://telegram-t/./src/util/searchWords.ts","webpack://telegram-t/./src/util/serverTime.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 = {\"87\":1,\"133\":1,\"301\":1,\"472\":1,\"532\":1,\"886\":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';\nimport { pause } from '../../../util/schedulers';\n\ntype RequestStates = {\n messageId: string;\n resolve: Function;\n reject: Function;\n callback?: AnyToVoidFunction;\n};\n\nconst HEALTH_CHECK_TIMEOUT = 150;\nconst HEALTH_CHECK_MIN_DELAY = 5 * 1000; // 5 sec\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 if (initialArgs.platform === 'iOS') {\n setupIosHealthCheck();\n }\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 requestStates.get(data.messageId)?.callback?.(...data.callbackArgs);\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 (('args' in payload) && 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\nconst startedAt = Date.now();\n\n// Workaround for iOS sometimes stops interacting with worker\nfunction setupIosHealthCheck() {\n window.addEventListener('focus', async () => {\n try {\n await Promise.race([\n makeRequest({ type: 'ping' }),\n pause(HEALTH_CHECK_TIMEOUT).then(() => Promise.reject(new Error('HEALTH_CHECK_TIMEOUT'))),\n ]);\n } catch (err) {\n // eslint-disable-next-line no-console\n console.error(err);\n\n if (Date.now() - startedAt >= HEALTH_CHECK_MIN_DELAY) {\n window.location.reload();\n }\n }\n });\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 BlobUrl,\n Lottie,\n Progressive,\n Stream,\n}\n\nexport type ApiParsedMedia = string | Blob | AnyLiteral | ArrayBuffer;\nexport type ApiPreparedMedia = string | AnyLiteral;\nexport type ApiMediaFormatToPrepared<T> = T extends ApiMediaFormat.Lottie ? AnyLiteral : string;\n","import { ApiGroupCall } from './calls';\n\nexport 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 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 id: string;\n size: number;\n mimeType: string;\n fileName: string;\n duration: number;\n performer?: string;\n title?: string;\n thumbnailSizes?: ApiPhotoSize[];\n}\n\nexport interface ApiVoice {\n id: string;\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: string;\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?: string[];\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?: string[];\n targetChatId?: string;\n type: 'historyClear' | 'contactSignUp' | 'chatCreate' | 'other';\n photo?: ApiPhoto;\n amount?: number;\n currency?: string;\n translationValues: string[];\n call?: Partial<ApiGroupCall>;\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 date: number;\n isChannelPost: boolean;\n channelPostId?: number;\n isLinkedChannelPost?: boolean;\n fromChatId?: string;\n senderUserId?: string;\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?: string;\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: string;\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?: string;\n replyToChatId?: string;\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 editDate?: number;\n isMentioned?: 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?: string;\n threadInfo?: ApiThreadInfo;\n adminTitle?: string;\n isScheduled?: boolean;\n shouldHideKeyboardButtons?: boolean;\n isFromScheduled?: boolean;\n seenByUserIds?: string[];\n isProtected?: boolean;\n}\n\nexport interface ApiThreadInfo {\n threadId: number;\n chatId: string;\n topMessageId?: number;\n originChannelId?: string;\n messagesCount: number;\n lastMessageId?: number;\n lastReadInboxMessageId?: number;\n recentReplierIds?: string[];\n}\n\nexport type ApiMessageOutgoingStatus = 'read' | 'succeeded' | 'pending' | 'failed';\n\nexport type ApiSponsoredMessage = {\n chatId?: string;\n randomId: string;\n isBot?: boolean;\n channelPostId?: number;\n startParam?: string;\n chatInviteHash?: string;\n chatInviteTitle?: string;\n text: ApiFormattedText;\n expiresAt: number;\n};\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' | 'voice' | '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 type ApiSendMessageAction = {\n type: 'cancel' | 'typing' | 'recordAudio' | 'chooseSticker';\n};\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 {\n DEBUG, RE_TG_LINK, RE_TME_LINK,\n} from '../../config';\nimport buildClassName from '../../util/buildClassName';\nimport { ensureProtocol } from '../../util/ensureProtocol';\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_TG_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 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';\n\nimport { ApiChat, ApiUser } from '../../api/types';\n\nimport buildClassName from '../../util/buildClassName';\n\nimport Link from '../ui/Link';\nimport { getDispatch } from '../../lib/teact/teactn';\n\ntype OwnProps = {\n className?: string;\n sender?: ApiUser | ApiChat;\n children: any;\n};\n\nconst UserLink: FC<OwnProps> = ({\n className, sender, children,\n}) => {\n const { openUserInfo } = getDispatch();\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 UserLink;\n","import React, { FC, useCallback } from '../../lib/teact/teact';\nimport { getDispatch } from '../../lib/teact/teactn';\n\nimport { ApiMessage } from '../../api/types';\n\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\nconst MessageLink: FC<OwnProps> = ({\n className, message, children,\n}) => {\n const { focusMessage } = getDispatch();\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 MessageLink;\n","import React, { FC, useCallback } from '../../lib/teact/teact';\nimport { getDispatch } from '../../lib/teact/teactn';\n\nimport buildClassName from '../../util/buildClassName';\n\nimport Link from '../ui/Link';\n\ntype OwnProps = {\n className?: string;\n chatId?: string;\n children: any;\n};\n\nconst ChatLink: FC<OwnProps> = ({\n className, chatId, children,\n}) => {\n const { openChat } = getDispatch();\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 ChatLink;\n","import React, { FC, useCallback } from '../../lib/teact/teact';\n\nimport { ApiGroupCall } from '../../api/types';\n\nimport buildClassName from '../../util/buildClassName';\n\nimport Link from '../ui/Link';\nimport { getDispatch } from '../../lib/teact/teactn';\n\ntype OwnProps = {\n className?: string;\n groupCall?: Partial<ApiGroupCall>;\n children: any;\n};\n\nconst GroupCallLink: FC<OwnProps> = ({\n className, groupCall, children,\n}) => {\n const { joinGroupCall } = getDispatch();\n\n const handleClick = useCallback(() => {\n if (groupCall) {\n joinGroupCall({ id: groupCall.id, accessHash: groupCall.accessHash });\n }\n }, [groupCall, joinGroupCall]);\n\n if (!groupCall) {\n return children;\n }\n\n return (\n <Link className={buildClassName('GroupCallLink', className)} onClick={handleClick}>{children}</Link>\n );\n};\n\nexport default GroupCallLink;\n","import React from '../../../lib/teact/teact';\n\nimport {\n ApiChat, ApiMessage, ApiUser, ApiGroupCall,\n} from '../../../api/types';\nimport { LangFn } from '../../../hooks/useLang';\nimport {\n getChatTitle,\n getMessageContent,\n getMessageSummaryText,\n getUserFullName,\n isUserId,\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';\nimport GroupCallLink from '../GroupCallLink';\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?: string,\n options: ActionMessageTextOptions = {},\n) {\n if (!message.content.action) {\n return [];\n }\n const {\n text, translationValues, amount, currency, call,\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 if (call) {\n return renderGroupCallContent(call, content);\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 isUserId(origin.id)\n ? renderUserContent(origin as ApiUser, asPlain)\n : renderChatContent(lang, origin as ApiChat, asPlain);\n}\n\nfunction renderGroupCallContent(groupCall: Partial<ApiGroupCall>, text: TextPart[]): string | TextPart | undefined {\n return (\n <GroupCallLink groupCall={groupCall}>\n {text}\n </GroupCallLink>\n );\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: string, 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 { fixNonStandardEmoji, nativeToUnified } 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 result.push(part);\n return result;\n }\n\n divEl.innerText = part;\n result.push(divEl.innerHTML);\n\n return result;\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 result.push(part);\n return result;\n }\n\n part = fixNonStandardEmoji(part);\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 = nativeToUnified(removeVS16s(emoji));\n if (!code) return emojiResult;\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: TextPart[], part) => {\n if (typeof part !== 'string') {\n result.push(part);\n return result;\n }\n\n const splittenParts = 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\n return [...result, ...splittenParts];\n }, []);\n}\n\nfunction addHighlight(textParts: TextPart[], highlight: string | undefined): TextPart[] {\n return textParts.reduce((result, part) => {\n if (typeof part !== 'string' || !highlight) {\n result.push(part);\n return result;\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 result.push(part);\n return result;\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 result.push(part);\n return result;\n }\n\n const links = part.match(RE_LINK);\n if (!links || !links.length) {\n result.push(part);\n return result;\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 result.push(part);\n return result;\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 from '../../../lib/teact/teact';\n\nimport { EDITABLE_INPUT_ID } from '../../../config';\nimport { IS_IOS } from '../../../util/environment';\n\nexport function preventMessageInputBlur(e: React.MouseEvent<HTMLElement>, withBubbling = false) {\n if (\n IS_IOS\n || !document.activeElement\n || document.activeElement.id !== EDITABLE_INPUT_ID\n || (!withBubbling && e.target !== e.currentTarget)\n ) {\n return;\n }\n\n e.preventDefault();\n}\n\nexport function preventMessageInputBlurWithBubbling(e: React.MouseEvent<HTMLElement>) {\n preventMessageInputBlur(e, true);\n}\n","import React, { FC } from '../../../lib/teact/teact';\nimport { getDispatch, withGlobal } from '../../../lib/teact/teactn';\n\nimport { ApiChat, ApiUser } from '../../../api/types';\n\nimport { selectUser } from '../../../modules/selectors';\n\ntype OwnProps = {\n userId?: string;\n username?: string;\n children: any;\n};\n\ntype StateProps = {\n userOrChat?: ApiUser | ApiChat;\n};\n\nconst MentionLink: FC<OwnProps & StateProps> = ({\n username,\n userOrChat,\n children,\n}) => {\n const {\n openChat,\n openChatByUsername,\n } = getDispatch();\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)(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 backgroundImage?: string;\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 withClickPropagation?: 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 backgroundImage,\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 withClickPropagation,\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 backgroundImage && 'with-image',\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 if (!withClickPropagation) e.preventDefault();\n if (!disabled && onMouseDown) {\n onMouseDown(e);\n }\n }, [onMouseDown, disabled, withClickPropagation]);\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 // @ts-ignore\n style={backgroundImage ? `background-image: url(${backgroundImage})` : 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';\nimport renderText from '../common/helpers/renderText';\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\">{renderText(label)}</span>\n {subLabel && <span className=\"subLabel\" dir=\"auto\">{renderText(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';\nimport { preventMessageInputBlurWithBubbling } from '../middle/helpers/preventMessageInputBlur';\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 menuStyle?: 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 menuStyle,\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\" onMouseDown={preventMessageInputBlurWithBubbling} />\n )}\n <div\n ref={menuRef}\n className={bubbleClassName}\n // @ts-ignore teact feature\n style={`transform-origin: ${positionY} ${positionX};${menuStyle || ''}`}\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-v7';\nexport const ASSET_CACHE_NAME = 'tt-assets';\nexport const AUTODOWNLOAD_FILESIZE_MB_LIMITS = [1, 5, 10, 50, 100, 500];\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_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;\nexport const COMMON_CHATS_LIMIT = 100;\nexport const GROUP_CALL_PARTICIPANTS_LIMIT = 100;\n\nexport const TOP_CHAT_MESSAGES_PRELOAD_LIMIT = 20;\nexport const ALL_CHATS_PRELOAD_DISABLED = false;\n\nexport const SPONSORED_MESSAGE_CACHE_MS = 300000; // 5 min\n\nexport const DEFAULT_VOLUME = 1;\nexport const DEFAULT_PLAYBACK_RATE = 1;\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\nexport const SEND_MESSAGE_ACTION_INTERVAL = 3000; // 3s\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;\nexport const TMP_CHAT_ID = '0';\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 VIDEO_MOV_TYPE = 'video/quicktime';\n\nexport const SUPPORTED_IMAGE_CONTENT_TYPES = new Set([\n 'image/png', 'image/gif', 'image/jpeg',\n]);\n\nexport const SUPPORTED_VIDEO_CONTENT_TYPES = new Set([\n 'video/mp4', // video/quicktime added dynamically in environment.ts\n]);\n\nexport const CONTENT_TYPES_WITH_PREVIEW = new Set([\n ...SUPPORTED_IMAGE_CONTENT_TYPES,\n ...SUPPORTED_VIDEO_CONTENT_TYPES,\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_TG_LINK = /^tg:(\\/\\/)?([?=&\\d\\w_-]+)?/gm;\nexport const RE_TME_LINK = /^(?:https?:\\/\\/)?(?:t\\.me\\/)/gm;\n\n// eslint-disable-next-line max-len\nexport const COUNTRIES_WITH_12H_TIME_FORMAT = new Set(['AU', 'BD', 'CA', 'CO', 'EG', 'HN', 'IE', 'IN', 'JO', 'MX', 'MY', 'NI', 'NZ', 'PH', 'PK', 'SA', 'SV', 'US']);\n\n// MTProto constants\nexport const SERVICE_NOTIFICATIONS_USER_ID = '777000';\nexport const REPLIES_USER_ID = '1271266957'; // TODO For Test connection ID must be equal to 708513\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// TODO Get values from `getConfig` method once it's available\nexport const SEEN_BY_MEMBERS_CHAT_MAX = 50;\nexport const SEEN_BY_MEMBERS_EXPIRE = 604680; // One week - 2 min\n\n// Group calls\nexport const GROUP_CALL_VOLUME_MULTIPLIER = 100;\nexport const GROUP_CALL_DEFAULT_VOLUME = 100 * GROUP_CALL_VOLUME_MULTIPLIER;\nexport const ENABLE_THUMBNAIL_VIDEO = false;\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\nconst ANIMATION_START_EVENT = 'tt-event-heavy-animation-start';\nconst ANIMATION_END_EVENT = 'tt-event-heavy-animation-end';\n\nlet timeout: number | undefined;\nlet isAnimating = false;\n\n// Make sure to end even if end callback was not called (which was some hardly-reproducible bug)\nconst AUTO_END_TIMEOUT = 1000;\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\nexport function isHeavyAnimating() {\n return isAnimating;\n}\n\nexport function dispatchHeavyAnimationEvent(duration = AUTO_END_TIMEOUT) {\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 // Race condition may happen if another `dispatchHeavyAnimationEvent` is called before `onEnd`\n function onEnd() {\n if (timeout) {\n clearTimeout(timeout);\n timeout = undefined;\n }\n\n isAnimating = false;\n document.dispatchEvent(new Event(ANIMATION_END_EVENT));\n }\n\n timeout = window.setTimeout(onEnd, duration);\n\n return onEnd;\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\ntype HistoryState = {\n currentIndex: number;\n nextStateIndexToReplace: number;\n isHistoryAltered: boolean;\n isDisabled: boolean;\n isEdge: boolean;\n currentIndexes: number[];\n};\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;\nconst PATH_BASE = `${window.location.pathname}${window.location.search}`;\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 }, '', PATH_BASE);\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 (\n historyState.currentIndexes.includes(historyState.nextStateIndexToReplace - 1)\n && window.history.state.index !== 0\n && historyState.nextStateIndexToReplace === index\n && !shouldReplaceNext\n )\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 setTimeout(() => {\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 }, 0);\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 }, '', `${PATH_BASE}#${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', 'role']);\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 if (props[key] !== undefined) {\n setAttribute(element, key, props[key]);\n }\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 // eslint-disable-next-line no-null/no-null\n if (DEBUG && isRealElement($newChild) && (key === undefined || key === null)) {\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 // eslint-disable-next-line no-null/no-null\n const isKeyPresent = key !== undefined && key !== null;\n\n // First we handle removed children\n if (isKeyPresent && !newKeys.has(key)) {\n renderWithVirtual(currentEl, $currentChild, undefined, $new, -1);\n\n return acc;\n } else if (!isKeyPresent) {\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 const currentValue = $current.props[key];\n const newValue = $new.props[key];\n\n if (\n currentValue !== undefined\n && (\n newValue === undefined\n || (currentValue !== newValue && key.startsWith('on'))\n )\n ) {\n removeAttribute(element, key, currentValue);\n }\n });\n\n newKeys.forEach((key) => {\n const currentValue = $current.props[key];\n const newValue = $new.props[key];\n\n if (newValue !== undefined && newValue !== currentValue) {\n setAttribute(element, key, newValue);\n }\n });\n}\n\nfunction setAttribute(element: HTMLElement, key: string, value: any) {\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 === 'dangerouslySetInnerHTML') {\n // eslint-disable-next-line no-underscore-dangle\n element.innerHTML = value.__html;\n } else if (key.startsWith('on')) {\n addEventListener(element, key, value, key.endsWith('Capture'));\n } else if (key.startsWith('data-') || key.startsWith('aria-') || 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 === 'dangerouslySetInnerHTML') {\n element.innerHTML = '';\n } else if (key.startsWith('on')) {\n removeEventListener(element, key, value, key.endsWith('Capture'));\n } else if (key.startsWith('data-') || key.startsWith('aria-') || 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\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, fastRafPrimary, onTickEnd, onTickEndPrimary, 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 = FC & {\n DEBUG_contentComponentName?: string;\n};\n\nexport enum VirtualElementTypesEnum {\n Empty,\n Text,\n Tag,\n Component,\n}\n\ninterface VirtualElementEmpty {\n type: VirtualElementTypesEnum.Empty;\n target?: Node;\n}\n\ninterface VirtualElementText {\n type: VirtualElementTypesEnum.Text;\n target?: Node;\n value: string;\n}\n\nexport interface VirtualElementTag {\n type: VirtualElementTypesEnum.Tag;\n target?: Node;\n tag: string;\n props: Props;\n children: VirtualElementChildren;\n}\n\nexport interface VirtualElementComponent {\n type: VirtualElementTypesEnum.Component;\n componentInstance: ComponentInstance;\n props: Props;\n children: VirtualElementChildren;\n}\n\nexport type StateHookSetter<T> = (newValue: ((current: T) => T) | T) => void;\n\ninterface ComponentInstance {\n $element: VirtualElementComponent;\n Component: FC;\n name: string;\n props: Props;\n renderedValue?: any;\n isMounted: boolean;\n hooks: {\n state: {\n cursor: number;\n byCursor: {\n value: any;\n nextValue: any;\n setter: StateHookSetter<any>;\n }[];\n };\n effects: {\n cursor: number;\n byCursor: {\n effect: () => void;\n dependencies?: any[];\n cleanup?: Function;\n }[];\n };\n memos: {\n cursor: number;\n byCursor: {\n current: any;\n dependencies: any[];\n }[];\n };\n };\n 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\nconst DEBUG_RENDER_THRESHOLD = 7;\nconst DEBUG_EFFECT_THRESHOLD = 7;\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 duration = performance.now() - DEBUG_startAt!;\n const componentName = componentInstance.name;\n if (duration > DEBUG_RENDER_THRESHOLD) {\n // eslint-disable-next-line no-console\n console.warn(`[Teact] Slow component render: ${componentName}, ${Math.round(duration)} ms`);\n }\n DEBUG_components[componentName].renderTimes.push(duration);\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 primarySchedulerFn: 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 function execCleanup() {\n if (!componentInstance.isMounted) {\n return;\n }\n\n const { cleanup } = byCursor[cursor];\n if (typeof cleanup === 'function') {\n try {\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 cleanup();\n\n if (DEBUG) {\n const duration = performance.now() - DEBUG_startAt!;\n const componentName = componentInstance.name;\n if (duration > DEBUG_EFFECT_THRESHOLD) {\n // eslint-disable-next-line no-console\n console.warn(\n `[Teact] Slow cleanup at effect cursor #${cursor}: ${componentName}, ${Math.round(duration)} ms`,\n );\n }\n }\n } catch (err) {\n handleError(err);\n }\n }\n }\n\n function exec() {\n if (!componentInstance.isMounted) {\n return;\n }\n\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 byCursor[cursor].cleanup = effect() as Function;\n\n if (DEBUG) {\n const duration = performance.now() - DEBUG_startAt!;\n const componentName = componentInstance.name;\n if (duration > DEBUG_EFFECT_THRESHOLD) {\n // eslint-disable-next-line no-console\n console.warn(`[Teact] Slow effect at cursor #${cursor}: ${componentName}, ${Math.round(duration)} ms`);\n }\n }\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 primarySchedulerFn(execCleanup);\n schedulerFn(exec);\n }\n } else {\n primarySchedulerFn(execCleanup);\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, fastRafPrimary, effect, dependencies, debugKey);\n}\n\nexport function useLayoutEffect(effect: () => Function | void, dependencies?: any[], debugKey?: string) {\n return useLayoutEffectBase(onTickEnd, onTickEndPrimary, 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[], debugKey?: string): F {\n // eslint-disable-next-line react-hooks/exhaustive-deps\n return useMemo(() => newCallback, dependencies, debugKey);\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 { fastRaf, throttleWithTickEnd } from '../../util/schedulers';\nimport arePropsShallowEqual, { getUnequalProps } from '../../util/arePropsShallowEqual';\nimport { orderBy } from '../../util/iteratees';\nimport {\n GlobalState, GlobalActions, ActionTypes, DispatchOptions,\n} from '../../global/types';\nimport { handleError } from '../../util/handleError';\nimport { isHeavyAnimating } from '../../hooks/useHeavyAnimationCheck';\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);\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 ownProps: Props;\n mappedProps?: Props;\n forceUpdate: Function;\n areMappedPropsChanged: boolean;\n DEBUG_updates: number;\n DEBUG_componentName: string;\n}>();\n\nconst runCallbacksThrottled = throttleWithTickEnd(runCallbacks);\n\nfunction runCallbacks(forceOnHeavyAnimation = false) {\n if (!forceOnHeavyAnimation && isHeavyAnimating()) {\n fastRaf(runCallbacksThrottled);\n return;\n }\n\n callbacks.forEach((cb) => cb(currentGlobal));\n}\n\nexport function setGlobal(newGlobal?: GlobalState, options?: DispatchOptions) {\n if (typeof newGlobal === 'object' && newGlobal !== currentGlobal) {\n currentGlobal = newGlobal;\n if (options?.forceSyncOnIOs) {\n runCallbacks(true);\n } else {\n runCallbacksThrottled(options?.forceOnHeavyAnimation);\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, options?: DispatchOptions) {\n if (reducers[name]) {\n reducers[name].forEach((reducer) => {\n const newGlobal = reducer(currentGlobal, actions, payload);\n if (newGlobal) {\n setGlobal(newGlobal, options);\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, ownProps, mappedProps, forceUpdate,\n } = container;\n\n let newMappedProps;\n\n try {\n newMappedProps = mapStateToProps(currentGlobal, ownProps);\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, options?: DispatchOptions) => {\n onDispatch(name, payload, options);\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) {\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 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 = mapStateToProps(currentGlobal, props);\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 { IS_MOV_SUPPORTED, 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 isTest: window.location.search.includes('test'),\n isMovSupported: IS_MOV_SUPPORTED,\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, InputPrivacyRules, InputPrivacyContact,\n UPLOADING_WALLPAPER_SLUG,\n} from '../../../types';\n\nimport { COUNTRIES_WITH_12H_TIME_FORMAT } from '../../../config';\nimport { callApi } from '../../../api/gramjs';\nimport { buildCollectionByKey } from '../../../util/iteratees';\nimport { subscribe, unsubscribe } from '../../../util/notifications';\nimport { setTimeFormat } from '../../../util/langProvider';\nimport { selectUser } from '../../selectors';\nimport {\n addUsers, addBlockedContact, updateChats, updateUser, removeBlockedContact, replaceSettings, updateNotifySettings,\n addNotifyExceptions,\n} from '../../reducers';\nimport { isUserId } 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');\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?.length) {\n newGlobal = addUsers(newGlobal, buildCollectionByKey(result.users, 'id'));\n }\n if (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 = isUserId(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: string[];\n deniedIds: string[];\n}): InputPrivacyRules {\n const {\n users: { byId: usersById },\n chats: { byId: chatsById },\n } = global;\n\n const rules: InputPrivacyRules = {\n visibility,\n };\n let users: InputPrivacyContact[];\n let chats: InputPrivacyContact[];\n\n const collectUsers = (userId: string) => {\n if (!isUserId(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: string) => {\n if (isUserId(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 InputPrivacyContact[];\n chats = allowedIds.map(collectChats).filter(Boolean) as InputPrivacyContact[];\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 InputPrivacyContact[];\n chats = deniedIds.map(collectChats).filter(Boolean) as InputPrivacyContact[];\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\naddReducer('loadCountryList', (global, actions, payload = {}) => {\n let { langCode } = payload;\n if (!langCode) langCode = global.settings.byKey.language;\n\n (async () => {\n const countryList = await callApi('fetchCountryList', { langCode });\n if (!countryList) return;\n\n setGlobal({\n ...getGlobal(),\n countryList,\n });\n })();\n});\n\naddReducer('ensureTimeFormat', (global, actions) => {\n if (global.authNearestCountry) {\n const timeFormat = COUNTRIES_WITH_12H_TIME_FORMAT.has(global.authNearestCountry.toUpperCase()) ? '12h' : '24h';\n actions.setSettingOption({ timeFormat });\n setTimeFormat(timeFormat);\n }\n\n (async () => {\n if (getGlobal().settings.byKey.wasTimeFormatSetManually) {\n return;\n }\n\n const nearestCountryCode = await callApi('fetchNearestCountry');\n if (nearestCountryCode) {\n const timeFormat = COUNTRIES_WITH_12H_TIME_FORMAT.has(nearestCountryCode.toUpperCase()) ? '12h' : '24h';\n actions.setSettingOption({ timeFormat });\n setTimeFormat(timeFormat);\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 });\n }\n\n break;\n }\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: string) {\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_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 if (IS_SAFARI) {\n document.body.classList.add('is-safari');\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 }, { forceSyncOnIOs: 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 { GlobalState } from '../../global/types';\nimport { NotifyException, NotifySettings } from '../../types';\nimport { LangFn } from '../../hooks/useLang';\n\nimport { ARCHIVED_FOLDER_ID, REPLIES_USER_ID } from '../../config';\nimport { orderBy } from '../../util/iteratees';\nimport { getUserFirstOrLastName } from './users';\nimport { formatDateToString, formatTime } from '../../util/dateFormat';\nimport { prepareSearchWordsForNeedle } from '../../util/searchWords';\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 isUserId(entityId: string) {\n // Workaround for old-fashioned IDs stored locally\n if (typeof entityId === 'number') {\n return entityId > 0;\n }\n\n return !entityId.startsWith('-');\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 isChatWithRepliesBot(chatId: string) {\n return chatId === REPLIES_USER_ID;\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?.[key])\n || (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 || isChatWithRepliesBot(chat.id)) {\n return false;\n }\n\n if (chat.isCreator) {\n return true;\n }\n\n if (isUserId(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')) && (!isUserId(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,\n currentUserBannedRights?: ApiChatBannedRights,\n defaultBannedRights?: ApiChatBannedRights,\n) {\n if (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, lang)],\n ),\n )\n : lang('Channel.Persmission.Denied.SendMessages.Forever');\n }\n\n if (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(chat.joinDate || 0, chat.draftDate || 0, chat.lastMessage?.date || 0);\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<string, 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 || (isUserId(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<string, 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 (isUserId(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 allListIds: GlobalState['chats']['listIds'],\n chatsById: Record<string, ApiChat>,\n usersById: Record<string, ApiUser>,\n folder: ApiChatFolder,\n notifySettings: NotifySettings,\n notifyExceptions?: Record<number, NotifyException>,\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 = ([] as string[]).concat(allListIds.active || [], allListIds.archived || [])\n .filter((id) => {\n const chat = chatsById[id];\n return chat && filterChatFolder(\n chat,\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\n// This function is the most expensive in the project, so any possible optimizations are welcome\nfunction filterChatFolder(\n chat: ApiChat,\n folder: ApiChatFolder,\n usersById: Record<string, ApiUser>,\n notifySettings: NotifySettings,\n notifyExceptions?: Record<number, NotifyException>,\n excludedChatIds?: Set<string>,\n includedChatIds?: Set<string>,\n pinnedChatIds?: Set<string>,\n) {\n if (!chat.isListed) {\n return false;\n }\n\n const { id: chatId, type, unreadMentionsCount } = chat;\n\n if (excludedChatIds?.has(chatId)) {\n return false;\n }\n\n if (includedChatIds?.has(chatId)) {\n return true;\n }\n\n if (pinnedChatIds?.has(chatId)) {\n return true;\n }\n\n if (folder.excludeArchived && chat.folderId === ARCHIVED_FOLDER_ID) {\n return false;\n }\n\n if (folder.excludeRead && !chat.unreadCount && !unreadMentionsCount && !chat.hasUnreadMark) {\n return false;\n }\n\n if (folder.excludeMuted && !unreadMentionsCount && selectIsChatMuted(chat, notifySettings, notifyExceptions)) {\n return false;\n }\n\n if (type === 'chatTypePrivate') {\n const user = usersById[chatId];\n if (user) {\n const { type: userType, isContact } = user;\n\n if (userType === 'userTypeBot') {\n if (folder.bots) {\n return true;\n }\n } else {\n if (folder.contacts && isContact) {\n return true;\n }\n\n if (folder.nonContacts && !isContact) {\n return true;\n }\n }\n }\n } else if (type === 'chatTypeChannel') {\n return !!folder.channels;\n } else if (type === 'chatTypeBasicGroup' || type === 'chatTypeSuperGroup') {\n return !!folder.groups;\n }\n\n return false;\n}\n\nexport function prepareChatList(\n chatsById: Record<string, ApiChat>,\n listIds: string[],\n orderedPinnedIds?: string[],\n folderType: 'all' | 'archived' | 'folder' = 'all',\n noOrder = false,\n) {\n const listIdsSet = new Set(listIds);\n const orderedPinnedIdsSet = orderedPinnedIds ? new Set(orderedPinnedIds) : undefined;\n\n const pinnedChats = orderedPinnedIds?.reduce((acc, id) => {\n const chat = chatsById[id];\n\n if (chat && listIdsSet.has(chat.id) && checkChat(chat, folderType)) {\n acc.push(chat);\n }\n\n return acc;\n }, [] as ApiChat[]) || [];\n\n const otherChats = listIds.reduce((acc, id) => {\n const chat = chatsById[id];\n\n if (chat && (!orderedPinnedIdsSet || !orderedPinnedIdsSet.has(chat.id)) && checkChat(chat, folderType)) {\n acc.push(chat);\n }\n\n return acc;\n }, [] as ApiChat[]);\n\n return {\n pinnedChats,\n otherChats: noOrder ? otherChats : orderBy(otherChats, getChatOrder, 'desc'),\n };\n}\n\nfunction checkChat(chat: ApiChat, folderType: 'all' | 'archived' | 'folder') {\n return (\n chat.lastMessage && !chat.migratedTo && !chat.isRestricted && !chat.isNotJoined\n && !(folderType === 'all' && chat.folderId === ARCHIVED_FOLDER_ID)\n && !(folderType === 'archived' && chat.folderId !== ARCHIVED_FOLDER_ID)\n );\n}\n\nexport function reduceChatList(\n chatArrays: { pinnedChats: ApiChat[]; otherChats: ApiChat[] },\n filteredIds: string[],\n) {\n const filteredIdsSet = new Set(filteredIds);\n\n return {\n pinnedChats: chatArrays.pinnedChats.filter(({ id }) => filteredIdsSet.has(id)),\n otherChats: chatArrays.otherChats.filter(({ id }) => filteredIdsSet.has(id)),\n };\n}\n\nexport function getFolderUnreadDialogs(\n allListIds: GlobalState['chats']['listIds'],\n chatsById: Record<string, ApiChat>,\n usersById: Record<string, ApiUser>,\n folder: ApiChatFolder,\n notifySettings: NotifySettings,\n notifyExceptions?: Record<number, NotifyException>,\n) {\n const [listIds] = prepareFolderListIds(allListIds, chatsById, usersById, folder, notifySettings, notifyExceptions);\n\n let hasActiveDialogs = false;\n const unreadDialogsCount = listIds.reduce((acc, id) => {\n const chat = chatsById[id];\n if (!chat?.lastMessage || chat?.isRestricted || chat?.isNotJoined) {\n return acc;\n }\n\n const isUnread = chat.unreadCount || chat.hasUnreadMark;\n\n if (isUnread) {\n acc++;\n }\n\n if (!hasActiveDialogs && (\n chat.unreadMentionsCount || (isUnread && !selectIsChatMuted(chat, notifySettings, notifyExceptions))\n )) {\n hasActiveDialogs = true;\n }\n\n return acc;\n }, 0);\n\n return {\n unreadDialogsCount,\n hasActiveDialogs,\n };\n}\n\nexport function getFolderDescriptionText(\n lang: LangFn,\n allListIds: GlobalState['chats']['listIds'],\n chatsById: Record<string, ApiChat>,\n usersById: Record<string, ApiUser>,\n folder: ApiChatFolder,\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?.length)\n || (includedChatIds?.length)\n ) {\n const length = getFolderChatsCount(allListIds, chatsById, usersById, folder, 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 allListIds: GlobalState['chats']['listIds'],\n chatsById: Record<string, ApiChat>,\n usersById: Record<string, ApiUser>,\n folder: ApiChatFolder,\n notifySettings: NotifySettings,\n notifyExceptions?: Record<string, NotifyException>,\n) {\n const [listIds, pinnedIds] = prepareFolderListIds(\n allListIds, chatsById, usersById, folder, notifySettings, notifyExceptions,\n );\n const { pinnedChats, otherChats } = prepareChatList(chatsById, listIds, pinnedIds, 'folder', true);\n return pinnedChats.length + otherChats.length;\n}\n\nexport function getMessageSenderName(lang: LangFn, chatId: string, sender?: ApiUser) {\n if (!sender || isUserId(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: string[],\n chatsById: Record<string, ApiChat>,\n shouldPrioritizeVerified = false,\n priorityIds?: string[],\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\nexport function filterChatsByName(\n lang: LangFn,\n chatIds: string[],\n chatsById: Record<string, ApiChat>,\n query?: string,\n currentUserId?: string,\n) {\n if (!query) {\n return chatIds;\n }\n\n const searchWords = prepareSearchWordsForNeedle(query);\n\n return chatIds.filter((id) => {\n const chat = chatsById[id];\n if (!chat) {\n return false;\n }\n\n return searchWords(getChatTitle(lang, chat, undefined, id === currentUserId));\n });\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 { getUserFullName } from './users';\nimport { isWebpSupported, IS_OPUS_SUPPORTED } from '../../util/environment';\nimport { getChatTitle, isUserId } from './chats';\nimport parseEmojiOnlyString from '../../components/common/helpers/parseEmojiOnlyString';\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 type MessageKey = `msg${string}-${number}`;\n\nexport function getMessageKey(message: ApiMessage): MessageKey {\n const { chatId, id } = message;\n\n return buildMessageKey(chatId, id);\n}\n\nexport function buildMessageKey(chatId: string, msgId: number): MessageKey {\n return `msg${chatId}-${msgId}`;\n}\n\nexport function parseMessageKey(key: MessageKey) {\n const match = key.match(/^msg(-?\\d+)-(\\d+)/)!;\n\n return { chatId: 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?.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?.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 && Math.round(message.id) !== message.id;\n}\n\nexport function isAnonymousOwnMessage(message: ApiMessage) {\n return Boolean(message.senderId) && !isUserId(message.senderId!) && isOwnMessage(message);\n}\n\nexport function getSenderTitle(lang: LangFn, sender: ApiUser | ApiChat) {\n return isUserId(sender.id) ? 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);\n}\n\nexport function getMessageContentFilename(message: ApiMessage) {\n const { content } = message;\n\n const video = content.webPage ? content.webPage.video : content.video;\n const photo = content.webPage ? content.webPage.photo : content.photo;\n const document = content.webPage ? content.webPage.document : content.document;\n if (document) {\n return document.fileName;\n }\n\n if (video) {\n return video.fileName;\n }\n\n if (content.sticker) {\n const extension = content.sticker.isAnimated ? 'tgs' : isWebpSupported() ? 'webp' : 'png';\n return `${content.sticker.id}.${extension}`;\n }\n\n if (content.audio) {\n return content.audio.fileName;\n }\n\n const baseFilename = getMessageKey(message);\n\n if (photo) {\n return `${baseFilename}.jpg`;\n }\n\n if (content.voice) {\n return IS_OPUS_SUPPORTED ? `${baseFilename}.ogg` : `${baseFilename}.wav`;\n }\n\n return baseFilename;\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?.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 return getMessageWebPage(message)?.photo;\n}\n\nexport function getMessageWebPageDocument(message: ApiMessage) {\n return getMessageWebPage(message)?.document;\n}\n\nexport function getMessageWebPageVideo(message: ApiMessage): ApiVideo | undefined {\n return getMessageWebPage(message)?.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 return getMessageMediaThumbnail(message)?.dataUri;\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 mediaId = (messagePhoto || messageVideo || sticker || audio || voice || document)!.id;\n const base = `${getMessageKey(message)}${mediaId ? `:${mediaId}` : ''}`;\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 case 'download':\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 case 'viewerFull':\n case 'download':\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 case 'inline':\n return base;\n case 'download':\n return `${base}?download`;\n }\n }\n\n if (audio) {\n switch (target) {\n case 'micro':\n case 'pictogram':\n return getAudioHasCover(audio) ? `${base}?size=m` : undefined;\n case 'inline':\n return getVideoOrAudioBaseHash(audio, base);\n case 'download':\n return `${base}?download`;\n }\n }\n\n if (voice) {\n switch (target) {\n case 'micro':\n case 'pictogram':\n return undefined;\n case 'inline':\n return base;\n case 'download':\n return `${base}?download`;\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 getAudioHasCover(media: ApiAudio) {\n return media.thumbnailSizes && media.thumbnailSizes.length > 0;\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?.blobUrl) || (video?.blobUrl) || (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, isLoadNeeded = false) {\n const isUploading = isMessageLocal(message);\n const isTransferring = isUploading || isLoadNeeded;\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 'voice':\n validator = (message: ApiMessage) => {\n const video = getMessageVideo(message);\n return getMessageVoice(message) || (video && video.isRound);\n };\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: string, 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, ApiUserStatus } 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';\nimport { getServerTime } from '../../util/serverTime';\nimport { prepareSearchWordsForNeedle } from '../../util/searchWords';\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(\n lang: LangFn, user: ApiUser, userStatus: ApiUserStatus | undefined, serverTimeOffset: number,\n) {\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 (!userStatus) {\n return '';\n }\n\n switch (userStatus.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 } = userStatus;\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, lang));\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, lang));\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, userStatus?: ApiUserStatus) {\n const { id, type } = user;\n\n if (!userStatus) {\n return false;\n }\n\n if (id === SERVICE_NOTIFICATIONS_USER_ID) {\n return false;\n }\n\n return userStatus.type === 'userStatusOnline' && type !== 'userTypeBot';\n}\n\nexport function isDeletedUser(user: ApiUser) {\n if (user.noStatus || 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 getCanAddContact(user: ApiUser) {\n return !user.isContact && !isUserBot(user);\n}\n\nexport function sortUserIds(\n userIds: string[],\n usersById: Record<string, ApiUser>,\n userStatusesById: Record<string, ApiUserStatus>,\n priorityIds?: string[],\n serverTimeOffset = 0,\n) {\n return orderBy(userIds, (id) => {\n const now = getServerTime(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 const userStatus = userStatusesById[id];\n if (!user || !userStatus) {\n return 0;\n }\n\n if (userStatus.type === 'userStatusOnline') {\n return userStatus.expires;\n } else if (userStatus.type === 'userStatusOffline' && userStatus.wasOnline) {\n return userStatus.wasOnline;\n }\n\n switch (userStatus.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\nexport function filterUsersByName(userIds: string[], usersById: Record<string, ApiUser>, query?: string) {\n if (!query) {\n return userIds;\n }\n\n const searchWords = prepareSearchWordsForNeedle(query);\n\n return userIds.filter((id) => {\n const user = usersById[id];\n if (!user) {\n return false;\n }\n\n const name = getUserFullName(user);\n return (name && searchWords(name)) || searchWords(user.username);\n });\n}\n\nexport function getUserIdDividend(userId: string) {\n // Workaround for old-fashioned IDs stored locally\n if (typeof userId === 'number') {\n return Math.abs(userId);\n }\n\n return Math.abs(Number(userId));\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 ? getUserIdDividend(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';\nimport { selectChatListType } from '../selectors';\n\nexport function replaceChatListIds(\n global: GlobalState,\n type: 'active' | 'archived',\n newIds: string[] | 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: string[]): GlobalState {\n const { [type]: listIds } = global.chats.listIds;\n const newIds = 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<string, ApiChat>): GlobalState {\n return {\n ...global,\n chats: {\n ...global.chats,\n byId: newById,\n },\n };\n}\n\nexport function updateChat(\n global: GlobalState, chatId: string, chatUpdate: Partial<ApiChat>, photo?: ApiPhoto,\n): GlobalState {\n const { byId } = global.chats;\n\n const updatedChat = getUpdatedChat(global, chatId, chatUpdate, photo);\n if (!updatedChat) {\n return global;\n }\n\n return replaceChats(global, {\n ...byId,\n [chatId]: updatedChat,\n });\n}\n\nexport function updateChats(global: GlobalState, newById: Record<string, ApiChat>): GlobalState {\n const updatedById = Object.keys(newById).reduce((acc: Record<string, ApiChat>, id) => {\n const updatedChat = getUpdatedChat(global, id, newById[id]);\n if (updatedChat) {\n acc[id] = updatedChat;\n }\n\n return acc;\n }, {});\n\n global = replaceChats(global, {\n ...global.chats.byId,\n ...updatedById,\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, newById: Record<string, ApiChat>): GlobalState {\n const { byId } = global.chats;\n let isUpdated = false;\n\n const addedById = Object.keys(newById).reduce<Record<string, ApiChat>>((acc, id) => {\n if (!byId[id] || (byId[id].isMin && !newById[id].isMin)) {\n const updatedChat = getUpdatedChat(global, id, newById[id]);\n if (updatedChat) {\n acc[id] = updatedChat;\n if (!isUpdated) {\n isUpdated = true;\n }\n }\n }\n return acc;\n }, {});\n\n if (!isUpdated) {\n return global;\n }\n\n global = replaceChats(global, {\n ...byId,\n ...addedById,\n });\n\n return global;\n}\n\n// @optimization Don't spread/unspread global for each element, do it in a batch\nfunction getUpdatedChat(\n global: GlobalState, chatId: string, chatUpdate: Partial<ApiChat>, photo?: ApiPhoto,\n) {\n const { byId } = global.chats;\n const chat = byId[chatId];\n const shouldOmitMinInfo = chatUpdate.isMin && chat && !chat.isMin;\n const updatedChat: ApiChat = {\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 undefined;\n }\n\n return updatedChat;\n}\n\nexport function updateChatListType(\n global: GlobalState,\n chatId: string,\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?: string[];\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\nexport function leaveChat(global: GlobalState, leftChatId: string): GlobalState {\n const listType = selectChatListType(global, leftChatId);\n if (!listType) {\n return global;\n }\n\n const { [listType]: listIds } = global.chats.listIds;\n\n if (listIds) {\n global = replaceChatListIds(global, listType, listIds.filter((listId) => listId !== leftChatId));\n }\n\n global = updateChat(global, leftChatId, { isNotJoined: true });\n\n return global;\n}\n","import {\n GlobalState, MessageList, MessageListType, Thread,\n} from '../../global/types';\nimport {\n ApiMessage, ApiSponsoredMessage, ApiThreadInfo, MAIN_THREAD_ID,\n} from '../../api/types';\nimport { FocusDirection } from '../../types';\n\nimport {\n IS_TEST, MESSAGE_LIST_SLICE, MESSAGE_LIST_VIEWPORT_LIMIT, TMP_CHAT_ID,\n} from '../../config';\nimport {\n selectListedIds,\n selectChatMessages,\n selectViewportIds,\n selectOutlyingIds,\n selectPinnedIds,\n selectThreadInfo,\n selectMessageIdsByGroupId,\n selectScheduledMessages,\n selectScheduledIds,\n selectCurrentMessageIds,\n selectChatMessage,\n selectCurrentMessageList,\n} from '../selectors';\nimport {\n areSortedArraysEqual, omit, pickTruthy, unique,\n} from '../../util/iteratees';\n\ntype MessageStoreSections = {\n byId: Record<number, ApiMessage>;\n threadsById: Record<number, Thread>;\n};\n\nexport function updateCurrentMessageList(\n global: GlobalState,\n chatId: string | 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: string, newById: Record<number, ApiMessage>): GlobalState {\n return updateMessageStore(global, chatId, {\n byId: newById,\n });\n}\n\nfunction updateThread(\n global: GlobalState, chatId: string, threadId: number, threadUpdate: Partial<Thread>,\n): GlobalState {\n const current = global.messages.byChatId[chatId];\n\n return updateMessageStore(global, chatId, {\n threadsById: {\n ...(current?.threadsById),\n [threadId]: {\n ...(current?.threadsById[threadId]),\n ...threadUpdate,\n },\n },\n });\n}\n\nfunction updateMessageStore(\n global: GlobalState, chatId: string, 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: string, 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<string, Record<number, ApiMessage>>);\n\n Object.keys(addedByChatId).forEach((chatId) => {\n global = addChatMessagesById(global, chatId, addedByChatId[chatId]);\n });\n\n return global;\n}\n\nexport function addChatMessagesById(\n global: GlobalState, chatId: string, 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: string, 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: string, 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 });\n}\n\nexport function deleteChatMessages(\n global: GlobalState,\n chatId: string,\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?.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?.messagesCount;\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?.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: string,\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);\n\n return global;\n}\n\nexport function updateListedIds(\n global: GlobalState,\n chatId: string,\n threadId: number,\n idsUpdate: number[],\n): GlobalState {\n const listedIds = selectListedIds(global, chatId, threadId);\n const newIds = 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: string,\n threadId: number,\n idsUpdate: number[],\n): GlobalState {\n const outlyingIds = selectOutlyingIds(global, chatId, threadId);\n const newIds = 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: string,\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: string,\n threadId: number,\n newViewportIds: number[],\n): GlobalState {\n const currentIds = selectViewportIds(global, chatId, threadId) || [];\n const newIds = orderHistoryIds(newViewportIds);\n\n return replaceThreadParam(\n global,\n chatId,\n threadId,\n 'viewportIds',\n areSortedArraysEqual(currentIds, newIds) ? currentIds : newIds,\n );\n}\n\nexport function updateThreadInfo(\n global: GlobalState, chatId: string, 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: string, 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: string, newById: Record<number, ApiMessage>,\n): GlobalState {\n return updateScheduledMessages(global, chatId, {\n byId: newById,\n });\n}\n\nfunction updateScheduledMessages(\n global: GlobalState, chatId: string, update: Partial<{ byId: Record<number, ApiMessage> }>,\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?: string, 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 updateSponsoredMessage(\n global: GlobalState, chatId: string, message: ApiSponsoredMessage,\n): GlobalState {\n return {\n ...global,\n messages: {\n ...global.messages,\n sponsoredByChatId: {\n ...global.messages.sponsoredByChatId,\n [chatId]: message,\n },\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: string,\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: string,\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\nexport function updateThreadUnreadFromForwardedMessage(\n global: GlobalState,\n originMessage: ApiMessage,\n chatId: string,\n lastMessageId: number,\n isDeleting?: boolean,\n) {\n const { channelPostId, fromChatId } = originMessage.forwardInfo || {};\n if (channelPostId && fromChatId) {\n const threadInfoOld = selectThreadInfo(global, chatId, channelPostId);\n if (threadInfoOld) {\n global = replaceThreadParam(global, chatId, channelPostId, 'threadInfo', {\n ...threadInfoOld,\n lastMessageId,\n messagesCount: threadInfoOld.messagesCount + (isDeleting ? -1 : 1),\n });\n }\n }\n return global;\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: string,\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?: string,\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, ApiUserStatus } from '../../api/types';\n\nimport { omit, pick } from '../../util/iteratees';\nimport { MEMO_EMPTY_ARRAY } from '../../util/memo';\n\nexport function replaceUsers(global: GlobalState, newById: Record<string, ApiUser>): GlobalState {\n return {\n ...global,\n users: {\n ...global.users,\n byId: newById,\n },\n };\n}\n\nfunction updateContactList(global: GlobalState, updatedUsers: ApiUser[]): GlobalState {\n const { userIds: contactUserIds } = global.contactList || {};\n\n if (!contactUserIds) return global;\n\n const newContactUserIds = updatedUsers\n .filter((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 userIds: [\n ...newContactUserIds,\n ...contactUserIds,\n ],\n },\n };\n}\n\nexport function updateUser(global: GlobalState, userId: string, userUpdate: Partial<ApiUser>): GlobalState {\n const { byId } = global.users;\n\n const updatedUser = getUpdatedUser(global, userId, userUpdate);\n if (!updatedUser) {\n return global;\n }\n\n global = updateContactList(global, [updatedUser]);\n\n return replaceUsers(global, {\n ...byId,\n [userId]: updatedUser,\n });\n}\n\nexport function updateUsers(global: GlobalState, newById: Record<string, ApiUser>): GlobalState {\n const updatedById = Object.keys(newById).reduce((acc: Record<string, ApiUser>, id) => {\n const updatedUser = getUpdatedUser(global, id, newById[id]);\n if (updatedUser) {\n acc[id] = updatedUser;\n }\n\n return acc;\n }, {});\n\n global = replaceUsers(global, {\n ...global.users.byId,\n ...updatedById,\n });\n\n global = updateContactList(global, Object.values(updatedById));\n\n return global;\n}\n\n// @optimization Allows to avoid redundant updates which cause a lot of renders\nexport function addUsers(global: GlobalState, newById: Record<string, ApiUser>): GlobalState {\n const { byId } = global.users;\n let isUpdated = false;\n\n const addedById = Object.keys(newById).reduce<Record<string, ApiUser>>((acc, id) => {\n if (!byId[id] || (byId[id].isMin && !newById[id].isMin)) {\n const updatedUser = getUpdatedUser(global, id, newById[id]);\n if (updatedUser) {\n acc[id] = updatedUser;\n if (!isUpdated) {\n isUpdated = true;\n }\n }\n }\n return acc;\n }, {});\n\n if (!isUpdated) {\n return global;\n }\n\n global = replaceUsers(global, {\n ...byId,\n ...addedById,\n });\n\n global = updateContactList(global, Object.values(addedById));\n\n return global;\n}\n\n// @optimization Don't spread/unspread global for each element, do it in a batch\nfunction getUpdatedUser(global: GlobalState, userId: string, userUpdate: Partial<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 undefined;\n }\n\n return updatedUser;\n}\n\nexport function updateSelectedUserId(global: GlobalState, selectedId?: string): 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: string): GlobalState {\n const { byId } = global.users;\n const { userIds } = global.contactList || {};\n delete byId[userId];\n\n global = {\n ...global,\n contactList: {\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: string, 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\nexport function replaceUserStatuses(global: GlobalState, newById: Record<string, ApiUserStatus>): GlobalState {\n return {\n ...global,\n users: {\n ...global.users,\n statusesById: newById,\n },\n };\n}\n\n// @optimization Allows to avoid redundant updates which cause a lot of renders\nexport function addUserStatuses(global: GlobalState, newById: Record<string, ApiUserStatus>): GlobalState {\n const { statusesById } = global.users;\n\n const newKeys = Object.keys(newById).filter((id) => !statusesById[id]);\n if (!newKeys.length) {\n return global;\n }\n\n global = replaceUserStatuses(global, {\n ...statusesById,\n ...pick(newById, newKeys),\n });\n\n return global;\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?.[type]?.foundIds;\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: string,\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: string,\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: string,\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?.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: string,\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: string,\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: string,\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: string,\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?.[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: string, 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: string, 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: string): 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: string): 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 { ApiChat, MAIN_THREAD_ID } from '../../api/types';\nimport { GlobalState } from '../../global/types';\n\nimport {\n getPrivateChatUserId, isChatChannel, isUserId, isHistoryClearMessage, isUserBot, isUserOnline, selectIsChatMuted,\n} from '../helpers';\nimport { selectUser } from './users';\nimport {\n ALL_FOLDER_ID, ARCHIVED_FOLDER_ID, MEMBERS_LOAD_SLICE, SERVICE_NOTIFICATIONS_USER_ID,\n} from '../../config';\nimport { selectNotifyExceptions, selectNotifySettings } from './settings';\n\nexport function selectChat(global: GlobalState, chatId: string): 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: string) {\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 (isUserId(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 (\n userId !== global.currentUserId\n && global.users.byId[userId]\n && isUserOnline(global.users.byId[userId], global.users.statusesById[userId])\n ) {\n return onlineCount + 1;\n }\n\n return onlineCount;\n }, 0);\n}\n\nexport function selectChatBot(global: GlobalState, chatId: string) {\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: string) {\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: string, 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: string): '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: string, 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\n// Slow, not to be used in `withGlobal`\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 const notifySettings = selectNotifySettings(global);\n const notifyExceptions = selectNotifyExceptions(global);\n\n return activeChatIds.reduce((acc, chatId) => {\n const chat = chats[chatId];\n\n if (\n chat\n && chat.unreadCount\n && chat.isListed\n && !chat.isNotJoined\n && !chat.isRestricted\n && (chat.unreadMentionsCount || !selectIsChatMuted(chat, notifySettings, notifyExceptions))\n ) {\n return acc + chat.unreadCount;\n }\n\n return acc;\n }, 0);\n}\n\nexport function selectIsServiceChatReady(global: GlobalState) {\n return Boolean(selectChat(global, SERVICE_NOTIFICATIONS_USER_ID));\n}\n\nexport function selectSendAs(global: GlobalState, chatId: string) {\n const chat = selectChat(global, chatId);\n if (!chat) return undefined;\n\n const id = chat?.fullInfo?.sendAsId;\n if (!id) return undefined;\n\n return selectUser(global, id) || selectChat(global, id);\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, SERVICE_NOTIFICATIONS_USER_ID } from '../../config';\nimport {\n selectChat, selectIsChatWithBot, selectIsChatWithSelf,\n} from './chats';\nimport { selectIsUserOrChatContact, selectUser } from './users';\nimport {\n getSendingState,\n isChatChannel,\n isMessageLocal,\n isUserId,\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 getMessagePhoto,\n getMessageAudio,\n getMessageVoice,\n getMessageDocument,\n getMessageWebPagePhoto,\n} from '../helpers';\nimport { findLast } from '../../util/iteratees';\nimport { selectIsStickerFavorite } from './symbols';\nimport { getServerTime } from '../../util/serverTime';\nimport { MEMO_EMPTY_ARRAY } from '../../util/memo';\n\nconst MESSAGE_EDIT_ALLOWED_TIME = 172800; // 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: string) {\n return global.messages.byChatId[chatId]?.byId;\n}\n\nexport function selectScheduledMessages(global: GlobalState, chatId: string) {\n return global.scheduledMessages.byChatId[chatId]?.byId;\n}\n\nexport function selectThreadParam<K extends keyof Thread>(\n global: GlobalState,\n chatId: string,\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: string, threadId: number) {\n return selectThreadParam(global, chatId, threadId, 'listedIds');\n}\n\nexport function selectOutlyingIds(global: GlobalState, chatId: string, threadId: number) {\n return selectThreadParam(global, chatId, threadId, 'outlyingIds');\n}\n\nexport function selectCurrentMessageIds(\n global: GlobalState, chatId: string, 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: string, threadId: number) {\n return selectThreadParam(global, chatId, threadId, 'viewportIds');\n}\n\nexport function selectPinnedIds(global: GlobalState, chatId: string) {\n return selectThreadParam(global, chatId, MAIN_THREAD_ID, 'pinnedIds');\n}\n\nexport function selectScheduledIds(global: GlobalState, chatId: string) {\n return selectThreadParam(global, chatId, MAIN_THREAD_ID, 'scheduledIds');\n}\n\nexport function selectScrollOffset(global: GlobalState, chatId: string, threadId: number) {\n return selectThreadParam(global, chatId, threadId, 'scrollOffset');\n}\n\nexport function selectReplyingToId(global: GlobalState, chatId: string, threadId: number) {\n return selectThreadParam(global, chatId, threadId, 'replyingToId');\n}\n\nexport function selectEditingId(global: GlobalState, chatId: string, threadId: number) {\n return selectThreadParam(global, chatId, threadId, 'editingId');\n}\n\nexport function selectEditingScheduledId(global: GlobalState, chatId: string) {\n return selectThreadParam(global, chatId, MAIN_THREAD_ID, 'editingScheduledId');\n}\n\nexport function selectDraft(global: GlobalState, chatId: string, threadId: number) {\n return selectThreadParam(global, chatId, threadId, 'draft');\n}\n\nexport function selectNoWebPage(global: GlobalState, chatId: string, threadId: number) {\n return selectThreadParam(global, chatId, threadId, 'noWebPage');\n}\n\nexport function selectThreadInfo(global: GlobalState, chatId: string, threadId: number) {\n return selectThreadParam(global, chatId, threadId, 'threadInfo');\n}\n\nexport function selectFirstMessageId(global: GlobalState, chatId: string, threadId: number) {\n return selectThreadParam(global, chatId, threadId, 'firstMessageId');\n}\n\nexport function selectReplyStack(global: GlobalState, chatId: string, threadId: number) {\n return selectThreadParam(global, chatId, threadId, 'replyStack');\n}\n\nexport function selectThreadOriginChat(global: GlobalState, chatId: string, 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: string, 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: string, 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: string, 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: string, 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: string, messageId: number) {\n const chatMessages = selectChatMessages(global, chatId);\n\n return chatMessages ? chatMessages[messageId] : undefined;\n}\n\nexport function selectScheduledMessage(global: GlobalState, chatId: string, messageId: number) {\n const chatMessages = selectScheduledMessages(global, chatId);\n\n return chatMessages ? chatMessages[messageId] : undefined;\n}\n\nexport function selectEditingMessage(\n global: GlobalState, chatId: string, 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: string) {\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 isUserId(senderId) ? 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) || selectChat(global, forwardInfo.senderUserId);\n }\n\n return undefined;\n}\n\nexport function selectAllowedMessageActions(global: GlobalState, message: ApiMessage, threadId: number) {\n const chat = selectChat(global, message.chatId);\n if (!chat || chat.isRestricted) {\n return {};\n }\n\n const isPrivate = isUserId(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 isLocal = isMessageLocal(message);\n const isServiceNotification = isServiceNotificationMessage(message);\n const isOwn = isOwnMessage(message);\n const isAction = isActionMessage(message);\n const { content } = message;\n\n const canEditMessagesIndefinitely = isChatWithSelf\n || (isSuperGroup && getHasAdminRight(chat, 'pinMessages'))\n || (isChannel && getHasAdminRight(chat, 'editMessages'));\n const isMessageEditable = (\n (\n canEditMessagesIndefinitely\n || getServerTime(global.serverTimeOffset) - message.date < MESSAGE_EDIT_ALLOWED_TIME\n ) && !(\n content.sticker || content.contact || content.poll || content.action || content.audio\n || (content.video?.isRound)\n )\n && !isForwardedMessage(message)\n && !message.viaBotId\n );\n\n const canReply = !isLocal && !isServiceNotification && getCanPostInChat(chat, threadId);\n\n const hasPinPermission = isPrivate || (\n chat.isCreator\n || (!isChannel && !isUserRightBanned(chat, 'pinMessages'))\n || getHasAdminRight(chat, 'pinMessages')\n );\n\n let canPin = !isLocal && !isServiceNotification && !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 = !isLocal && !isServiceNotification && (\n isPrivate\n || isOwn\n || isBasicGroup\n || chat.isCreator\n || getHasAdminRight(chat, 'deleteMessages')\n );\n\n const canReport = !isPrivate && !isOwn;\n\n const canDeleteForAll = canDelete && (\n (isPrivate && !isChatWithSelf)\n || (isBasicGroup && (\n isOwn || getHasAdminRight(chat, 'deleteMessages') || chat.isCreator\n ))\n );\n\n const canEdit = !isLocal && !isAction && isMessageEditable && (\n isOwn\n || (isChannel && (chat.isCreator || getHasAdminRight(chat, 'editMessages')))\n );\n\n const canForward = !isLocal && !isAction;\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\n const canDownload = Boolean(content.webPage?.document || content.webPage?.video || content.webPage?.photo\n || content.audio || content.voice || content.photo || content.video || content.document || content.sticker);\n\n const noOptions = [\n canReply,\n canEdit,\n canPin,\n canUnpin,\n canReport,\n canDelete,\n canDeleteForAll,\n canForward,\n canFaveSticker,\n canUnfaveSticker,\n canCopy,\n canCopyLink,\n canSelect,\n canDownload,\n ].every((ability) => !ability);\n\n return {\n noOptions,\n canReply,\n canEdit,\n canPin,\n canUnpin,\n canReport,\n canDelete,\n canDeleteForAll,\n canForward,\n canFaveSticker,\n canUnfaveSticker,\n canCopy,\n canCopyLink,\n canSelect,\n canDownload,\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 selectCanDownloadSelectedMessages(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.some((actions) => actions.canDownload);\n}\n\nexport function selectIsDownloading(global: GlobalState, message: ApiMessage) {\n const activeInChat = global.activeDownloads.byChatId[message.chatId];\n return activeInChat ? activeInChat.includes(message.id) : false;\n}\n\nexport function selectActiveDownloadIds(global: GlobalState, chatId: string) {\n return global.activeDownloads.byChatId[chatId] || MEMO_EMPTY_ARRAY;\n}\n\nexport function selectUploadProgress(global: GlobalState, message: ApiMessage) {\n return global.fileUploads.byMessageLocalId[message.previousLocalId || message.id]?.progress;\n}\n\nexport function selectRealLastReadId(global: GlobalState, chatId: string, 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: string, 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\n || (threadInfo.lastMessageId !== undefined && 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 const lastReadServiceNotificationId = chatId === SERVICE_NOTIFICATIONS_USER_ID\n ? global.serviceNotifications.reduce((max, notification) => {\n return !notification.isUnread && notification.id > max ? notification.id : max;\n }, -1)\n : -1;\n\n function findAfterLastReadId(listIds: number[]) {\n return listIds.find((id) => {\n return (\n (!lastReadId || id > lastReadId)\n && byId[id]\n && (!byId[id].isOutgoing || byId[id].isFromScheduled)\n && id > lastReadServiceNotificationId\n );\n });\n }\n\n if (outlyingIds) {\n const found = findAfterLastReadId(outlyingIds);\n if (found) {\n return found;\n }\n }\n\n if (listedIds) {\n const found = findAfterLastReadId(listedIds);\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 Object.keys(byChatId).find((chatId) => {\n const chat = selectChat(global, 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: string, 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: string, 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: string, 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: string,\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 selectCanAutoLoadMedia(global: GlobalState, message: ApiMessage) {\n const chat = selectChat(global, message.chatId);\n if (!chat) {\n return undefined;\n }\n\n const sender = selectSender(global, message);\n\n const isPhoto = Boolean(getMessagePhoto(message) || getMessageWebPagePhoto(message));\n const isVideo = Boolean(getMessageVideo(message) || getMessageWebPageVideo(message));\n const isFile = Boolean(getMessageAudio(message) || getMessageVoice(message) || getMessageDocument(message));\n\n const {\n canAutoLoadPhotoFromContacts,\n canAutoLoadPhotoInPrivateChats,\n canAutoLoadPhotoInGroups,\n canAutoLoadPhotoInChannels,\n canAutoLoadVideoFromContacts,\n canAutoLoadVideoInPrivateChats,\n canAutoLoadVideoInGroups,\n canAutoLoadVideoInChannels,\n canAutoLoadFileFromContacts,\n canAutoLoadFileInPrivateChats,\n canAutoLoadFileInGroups,\n canAutoLoadFileInChannels,\n } = global.settings.byKey;\n\n if (isPhoto) {\n return canAutoLoadMedia({\n global,\n chat,\n sender,\n canAutoLoadMediaFromContacts: canAutoLoadPhotoFromContacts,\n canAutoLoadMediaInPrivateChats: canAutoLoadPhotoInPrivateChats,\n canAutoLoadMediaInGroups: canAutoLoadPhotoInGroups,\n canAutoLoadMediaInChannels: canAutoLoadPhotoInChannels,\n });\n }\n\n if (isVideo) {\n return canAutoLoadMedia({\n global,\n chat,\n sender,\n canAutoLoadMediaFromContacts: canAutoLoadVideoFromContacts,\n canAutoLoadMediaInPrivateChats: canAutoLoadVideoInPrivateChats,\n canAutoLoadMediaInGroups: canAutoLoadVideoInGroups,\n canAutoLoadMediaInChannels: canAutoLoadVideoInChannels,\n });\n }\n\n if (isFile) {\n return canAutoLoadMedia({\n global,\n chat,\n sender,\n canAutoLoadMediaFromContacts: canAutoLoadFileFromContacts,\n canAutoLoadMediaInPrivateChats: canAutoLoadFileInPrivateChats,\n canAutoLoadMediaInGroups: canAutoLoadFileInGroups,\n canAutoLoadMediaInChannels: canAutoLoadFileInChannels,\n });\n }\n\n return true;\n}\n\nfunction canAutoLoadMedia({\n global,\n chat,\n sender,\n canAutoLoadMediaFromContacts,\n canAutoLoadMediaInPrivateChats,\n canAutoLoadMediaInGroups,\n canAutoLoadMediaInChannels,\n}: {\n global: GlobalState;\n chat: ApiChat;\n canAutoLoadMediaFromContacts: boolean;\n canAutoLoadMediaInPrivateChats: boolean;\n canAutoLoadMediaInGroups: boolean;\n canAutoLoadMediaInChannels: boolean;\n sender?: ApiChat | ApiUser;\n}) {\n const isMediaFromContact = Boolean(sender && (\n sender.id === global.currentUserId || selectIsUserOrChatContact(global, sender)\n ));\n\n return Boolean(\n (isMediaFromContact && canAutoLoadMediaFromContacts)\n || (!isMediaFromContact && canAutoLoadMediaInPrivateChats && isUserId(chat.id))\n || (canAutoLoadMediaInGroups && isChatGroup(chat))\n || (canAutoLoadMediaInChannels && isChatChannel(chat)),\n );\n}\n\nexport function selectCanAutoPlayMedia(global: GlobalState, message: ApiMessage) {\n const video = getMessageVideo(message) || getMessageWebPageVideo(message);\n if (!video) {\n return undefined;\n }\n\n const {\n canAutoPlayVideos,\n canAutoPlayGifs,\n } = global.settings.byKey;\n\n const asGif = video.isGif || video.isRound;\n\n return (canAutoPlayVideos && !asGif) || (canAutoPlayGifs && asGif);\n}\n\nexport function selectShouldLoopStickers(global: GlobalState) {\n return global.settings.byKey.shouldLoopStickers;\n}\n\nexport function selectLastServiceNotification(global: GlobalState) {\n const { serviceNotifications } = global;\n const maxId = Math.max(...serviceNotifications.map(({ id }) => id));\n\n return serviceNotifications.find(({ id }) => id === maxId);\n}\n\nexport function selectIsMessageProtected(global: GlobalState, message?: ApiMessage) {\n return message ? message.isProtected || selectChat(global, message.chatId)?.isProtected : false;\n}\n\nexport function selectSponsoredMessage(global: GlobalState, chatId: string) {\n const chat = selectChat(global, chatId);\n const message = chat && isChatChannel(chat) ? global.messages.sponsoredByChatId[chatId] : undefined;\n\n return message && message.expiresAt >= Math.round(Date.now() / 1000) ? message : undefined;\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, isUserId } from '../helpers';\n\nexport function selectManagement(global: GlobalState, chatId: string) {\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 (isUserId(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 { 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 { GlobalState } from '../../global/types';\nimport { ApiChat, ApiUser, ApiUserStatus } from '../../api/types';\n\nexport function selectUser(global: GlobalState, userId: string): ApiUser | undefined {\n return global.users.byId[userId];\n}\n\nexport function selectUserStatus(global: GlobalState, userId: string): ApiUserStatus | undefined {\n return global.users.statusesById[userId];\n}\n\nexport function selectIsUserBlocked(global: GlobalState, userId: string) {\n const user = selectUser(global, userId);\n\n return 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 {\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 type TimeFormat = '24h' | '12h';\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 canAutoLoadPhotoFromContacts: boolean;\n canAutoLoadPhotoInPrivateChats: boolean;\n canAutoLoadPhotoInGroups: boolean;\n canAutoLoadPhotoInChannels: boolean;\n canAutoLoadVideoFromContacts: boolean;\n canAutoLoadVideoInPrivateChats: boolean;\n canAutoLoadVideoInGroups: boolean;\n canAutoLoadVideoInChannels: boolean;\n canAutoLoadFileFromContacts: boolean;\n canAutoLoadFileInPrivateChats: boolean;\n canAutoLoadFileInGroups: boolean;\n canAutoLoadFileInChannels: boolean;\n autoLoadFileMaxSizeMb: number;\n canAutoPlayGifs: boolean;\n canAutoPlayVideos: boolean;\n shouldSuggestStickers: boolean;\n shouldLoopStickers: boolean;\n hasPassword?: boolean;\n languages?: ApiLanguage[];\n language: LangCode;\n isSensitiveEnabled?: boolean;\n canChangeSensitive?: boolean;\n timeFormat: TimeFormat;\n wasTimeFormatSetManually: boolean;\n}\n\nexport interface ApiPrivacySettings {\n visibility: PrivacyVisibility;\n allowUserIds: string[];\n allowChatIds: string[];\n blockUserIds: string[];\n blockChatIds: string[];\n}\n\nexport interface InputPrivacyContact {\n id: string;\n accessHash?: string;\n}\n\nexport interface InputPrivacyRules {\n visibility: PrivacyVisibility;\n allowedUsers?: InputPrivacyContact[];\n allowedChats?: InputPrivacyContact[];\n blockedUsers?: InputPrivacyContact[];\n blockedChats?: InputPrivacyContact[];\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 DataStorage,\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 SettingsAvatar,\n MiddleHeaderAvatar,\n Album,\n ScheduledAlbum,\n SearchResult,\n}\n\nexport enum AudioOrigin {\n Inline,\n SharedMedia,\n Search,\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' | 'commonChats' | 'media' | 'documents' | 'links' | 'audio' | 'voice';\nexport type SharedMediaType = 'media' | 'documents' | 'links' | 'audio' | 'voice';\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: string;\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\nexport type TimingFn = (t: number) => number;\n\nexport type AnimateNumberProps = {\n to: number | number[];\n from: number | number[];\n duration: number;\n onUpdate: (value: any) => void;\n timing?: TimingFn;\n onEnd?: () => void;\n};\n\nexport const timingFunctions = {\n linear: (t: number) => t,\n easeIn: (t: number) => t ** 1.675,\n easeOut: (t: number) => 1 - (1 - t ** 1.675),\n easeInOut: (t: number) => 0.5 * (Math.sin((t - 0.5) * Math.PI) + 1),\n easeInQuad: (t: number) => t * t,\n easeOutQuad: (t: number) => t * (2 - t),\n easeInOutQuad: (t: number) => (t < 0.5 ? 2 * t * t : -1 + (4 - 2 * t) * t),\n easeInCubic: (t: number) => t * t * t,\n easeOutCubic: (t: number) => (--t) * t * t + 1,\n easeInOutCubic: (t: number) => (t < 0.5 ? 4 * t * t * t : (t - 1) * (2 * t - 2) * (2 * t - 2) + 1),\n easeInQuart: (t: number) => t * t * t * t,\n easeOutQuart: (t: number) => 1 - (--t) * t * t * t,\n easeInOutQuart: (t: number) => (t < 0.5 ? 8 * t * t * t * t : 1 - 8 * (--t) * t * t * t),\n easeInQuint: (t: number) => t * t * t * t * t,\n easeOutQuint: (t: number) => 1 + (--t) * t * t * t * t,\n easeInOutQuint: (t: number) => (t < 0.5 ? 16 * t * t * t * t * t : 1 + 16 * (--t) * t * t * t * t),\n};\n\nexport function animateNumber({\n timing = timingFunctions.linear,\n onUpdate,\n duration,\n onEnd,\n from,\n to,\n}: AnimateNumberProps) {\n const t0 = Date.now();\n let canceled = false;\n\n animate(() => {\n if (canceled) return false;\n const t1 = Date.now();\n let t = (t1 - t0) / duration;\n if (t > 1) t = 1;\n const progress = timing(t);\n if (typeof from === 'number' && typeof to === 'number') {\n onUpdate(from + ((to - from) * progress));\n } else if (Array.isArray(from) && Array.isArray(to)) {\n const result = from.map((f, i) => f + ((to[i] - f) * progress));\n onUpdate(result);\n }\n if (t === 1 && onEnd) onEnd();\n return t < 1;\n });\n\n return () => {\n canceled = true;\n if (onEnd) onEnd();\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(\n cacheName: string, key: string, type: Type, isHtmlAllowed = false,\n) {\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 const contentType = response.headers.get('Content-Type');\n\n switch (type) {\n case Type.Text:\n return await response.text();\n case Type.Blob: {\n // Ignore deprecated data-uri avatars\n if (key.startsWith('avatar') && contentType && contentType.startsWith('text')) {\n return undefined;\n }\n\n const blob = await response.blob();\n\n // Safari does not return correct Content-Type header for webp images.\n if (key.startsWith('sticker')) {\n return new Blob([blob], { type: 'image/webp' });\n }\n\n const shouldRecreate = !blob.type || (!isHtmlAllowed && blob.type.includes('html'));\n // iOS Safari fails to preserve `type` in cache\n let resolvedType = blob.type || contentType;\n\n if (!(shouldRecreate && resolvedType)) {\n return blob;\n }\n\n // Prevent HTML-in-video attacks (for files that were cached before fix)\n if (!isHtmlAllowed) {\n resolvedType = resolvedType.replace(/html/gi, '');\n }\n\n return new Blob([blob], { type: resolvedType });\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 MILLISECONDS_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\n// @optimization `toLocaleTimeString` is avoided because of bad performance\nexport function formatTime(datetime: number | Date, lang: LangFn) {\n const date = typeof datetime === 'number' ? new Date(datetime) : datetime;\n const timeFormat = lang.timeFormat || '24h';\n\n let hours = date.getHours();\n let marker = '';\n if (timeFormat === '12h') {\n marker = hours >= 12 ? ' PM' : ' AM';\n hours = hours > 12 ? hours % 12 : hours;\n }\n\n return `${String(hours).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}${marker}`;\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, lang);\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(\n lang: LangFn,\n datetime: number | Date,\n isShort = false,\n noWeekdays = false,\n isUpperFirst?: boolean,\n) {\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 (isUpperFirst || !isShort ? upperFirst : lowerFirst)(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 (isUpperFirst || !isShort ? upperFirst : lowerFirst)(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 const weekDayString = isShort ? lang(`Weekday.Short${weekDay}`) : lang(`Weekday.${weekDay}`);\n\n return (isUpperFirst || !isShort ? upperFirst : lowerFirst)(weekDayString);\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 (isUpperFirst || !isShort ? upperFirst : lowerFirst)(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(\n lang: LangFn,\n datetime: number | Date,\n isUpperFirst?: boolean,\n) {\n const date = typeof datetime === 'number' ? new Date(datetime) : datetime;\n\n return `${formatHumanDate(lang, date, true, undefined, isUpperFirst)}, ${formatTime(date, lang)}`;\n}\n\nexport function formatMediaDuration(duration: number, maxValue?: 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 const maxHours = maxValue ? Math.floor(maxValue / 3600) : 0;\n const maxMinutes = maxValue ? Math.floor((maxValue % 3600) / 60) : 0;\n let string = '';\n if (hours > 0 || maxHours > 0) {\n string += `${String(hours).padStart(2, '0')}:`;\n string += `${String(minutes).padStart(2, '0')}:`;\n } else if (maxMinutes >= 10) {\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(datetime: Date | number, locale = 'en-US') {\n const date = typeof datetime === 'number' ? new Date(datetime) : datetime;\n return date.toLocaleString(\n locale,\n {\n year: 'numeric',\n month: 'short',\n day: 'numeric',\n },\n );\n}\n\nexport function formatDateTimeToString(datetime: Date | number, locale = 'en-US') {\n const date = typeof datetime === 'number' ? new Date(datetime) : datetime;\n return date.toLocaleString(\n locale,\n {\n year: 'numeric',\n month: 'short',\n day: 'numeric',\n hour: 'numeric',\n minute: 'numeric',\n second: '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 + MILLISECONDS_IN_DAY / 1000;\n}\n\nfunction lowerFirst(str: string) {\n return `${str[0].toLowerCase()}${str.slice(1)}`;\n}\n\nfunction upperFirst(str: string) {\n return `${str[0].toUpperCase()}${str.slice(1)}`;\n}\n","import EMOJI_REGEX from '../lib/twemojiRegex';\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\nconst ISO_FLAGS_OFFSET = 127397;\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\n// Non-standard variations of emojis, used on some devices\nconst EMOJI_EXCEPTIONS: [string | RegExp, string][] = [\n [/\\u{1f3f3}\\u200d\\u{1f308}/gu, '\\u{1f3f3}\\ufe0f\\u200d\\u{1f308}'], // 🏳🌈\n [/\\u{1f3f3}\\u200d\\u26a7\\ufe0f/gu, '\\u{1f3f3}\\ufe0f\\u200d\\u26a7\\ufe0f'], // 🏳️⚧️\n [/\\u{1f937}\\u200d\\u2642/gu, '\\u{1f937}\\u200d\\u2642\\ufe0f'], // 🤷♂️\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 fixNonStandardEmoji(text: string) {\n // Non-standard sequences typically parsed as separate emojis, so no need to fix text without any\n if (!text.match(EMOJI_REGEX)) return text;\n // eslint-disable-next-line no-restricted-syntax\n for (const [regex, replacement] of EMOJI_EXCEPTIONS) {\n text = text.replace(regex, replacement);\n }\n\n return text;\n}\n\nexport function nativeToUnified(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\nexport function isoToEmoji(iso: string) {\n const code = iso.toUpperCase();\n\n if (!/^[A-Z]{2}$/.test(code)) return iso;\n const codePoints = [...code].map((c) => c.codePointAt(0)! + ISO_FLAGS_OFFSET);\n return String.fromCodePoint(...codePoints);\n}\n","export function ensureProtocol(url?: string) {\n if (!url) {\n return undefined;\n }\n\n // HTTP was chosen by default as a fix for https://bugs.telegram.org/c/10712.\n // It is also the default protocol in the official TDesktop client.\n return url.includes('://') ? url : `http://${url}`;\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.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 SUPPORTED_VIDEO_CONTENT_TYPES,\n VIDEO_MOV_TYPE,\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 = (\n window.matchMedia('(display-mode: standalone)').matches\n || (window.navigator as any).standalone\n || document.referrer.includes('android-app://')\n);\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 = Boolean(\n navigator.mediaDevices && 'getUserMedia' in navigator.mediaDevices && (\n window.AudioContext || (window as any).webkitAudioContext\n ),\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 IS_REQUEST_FULLSCREEN_SUPPORTED = 'requestFullscreen' in document.createElement('div');\nexport const ARE_CALLS_SUPPORTED = !navigator.userAgent.includes('Firefox');\nexport const LAYERS_ANIMATION_NAME = IS_ANDROID ? 'slide-fade' : IS_IOS ? 'slide-layers' : 'push-slide';\n\nconst TEST_VIDEO = document.createElement('video');\nexport const IS_MOV_SUPPORTED = Boolean(\n TEST_VIDEO.canPlayType(VIDEO_MOV_TYPE).replace('no', '')\n || IS_IOS, // IOS reports '', but still plays .mov files\n);\n\nif (IS_MOV_SUPPORTED) SUPPORTED_VIDEO_CONTENT_TYPES.add(VIDEO_MOV_TYPE);\n\nexport const DPR = window.devicePixelRatio || 1;\n\nexport const MASK_IMAGE_DISABLED = true;\n\nexport const IS_SCROLL_PATCH_NEEDED = !IS_MAC_OS && !IS_IOS && !IS_ANDROID;\n\n// Smaller area reduces scroll jumps caused by `patchChromiumScroll`\nexport const MESSAGE_LIST_SENSITIVE_AREA = IS_SCROLL_PATCH_NEEDED ? 300 : 750;\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 MESSAGE_TOO_LONG: 'Message is too long',\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 MESSAGE_TOO_LONG_PLEASE_REMOVE_CHARACTERS: 'The provided message 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?.message) || err}\\n${err?.stack}`);\n }\n}\n","type CollectionByKey<Member> = Record<number | string, Member>;\n\ntype OrderDirection =\n 'asc'\n | '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 orderRule: (keyof T) | OrderCallback<T> | ((keyof T) | OrderCallback<T>)[],\n mode: OrderDirection | [OrderDirection, OrderDirection] = 'asc',\n): T[] {\n function compareValues(a: T, b: T, currentOrderRule: (keyof T) | OrderCallback<T>, isAsc: boolean) {\n const aValue = (typeof currentOrderRule === 'function' ? currentOrderRule(a) : a[currentOrderRule]) || 0;\n const bValue = (typeof currentOrderRule === 'function' ? currentOrderRule(b) : b[currentOrderRule]) || 0;\n\n return isAsc ? aValue - bValue : bValue - aValue;\n }\n\n if (Array.isArray(orderRule)) {\n const [mode1, mode2] = Array.isArray(mode) ? mode : [mode, mode];\n const [orderRule1, orderRule2] = orderRule;\n const isAsc1 = mode1 === 'asc';\n const isAsc2 = mode2 === 'asc';\n\n return collection.sort((a, b) => {\n return compareValues(a, b, orderRule1, isAsc1) || compareValues(a, b, orderRule2, isAsc2);\n });\n }\n\n const isAsc = mode === 'asc';\n return collection.sort((a, b) => {\n return compareValues(a, b, orderRule, isAsc);\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\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, TimeFormat } 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 timeFormat?: TimeFormat;\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;\nlet currentTimeFormat: TimeFormat | 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?.[key]) || (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: ApiLangString | undefined = 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, timeFormat } = getGlobal().settings.byKey;\n const langInfo = languages?.find((l) => l.langCode === langCode);\n getTranslation.isRtl = Boolean(langInfo?.rtl);\n getTranslation.code = langCode;\n getTranslation.timeFormat = timeFormat;\n\n if (callback) {\n callback();\n }\n\n runCallbacks();\n}\n\nexport function setTimeFormat(timeFormat: TimeFormat) {\n if (timeFormat && timeFormat === currentTimeFormat) {\n return;\n }\n\n currentTimeFormat = timeFormat;\n getTranslation.timeFormat = timeFormat;\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<ApiLangString | undefined> {\n const remote = await callApi('fetchLangStrings', {\n langPack: remoteLangPack,\n langCode,\n keys: [key],\n });\n\n if (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,\n} from '../config';\nimport { callApi, cancelApiProgress } from '../api/gramjs';\nimport * as cacheApi from './cacheApi';\nimport { fetchBlob } from './files';\nimport { IS_OPUS_SUPPORTED, IS_PROGRESSIVE_SUPPORTED, isWebpSupported } from './environment';\nimport { oggToWav } from './oggToWav';\nimport { webpToPng } from './webpToPng';\n\nconst asCacheApiType = {\n [ApiMediaFormat.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>>();\nconst progressCallbacks = new Map<string, Map<string, ApiOnProgress>>();\nconst cancellableCallbacks = new Map<string, ApiOnProgress>();\n\nexport function fetch<T extends ApiMediaFormat>(\n url: string,\n mediaFormat: T,\n isHtmlAllowed = false,\n onProgress?: ApiOnProgress,\n callbackUniqueId?: string,\n): Promise<ApiMediaFormatToPrepared<T>> {\n if (mediaFormat === ApiMediaFormat.Progressive) {\n return (\n IS_PROGRESSIVE_SUPPORTED\n ? getProgressive(url)\n : fetch(url, ApiMediaFormat.BlobUrl, isHtmlAllowed, onProgress, callbackUniqueId)\n ) as Promise<ApiMediaFormatToPrepared<T>>;\n }\n\n if (!fetchPromises.has(url)) {\n const promise = fetchFromCacheOrRemote(url, mediaFormat, isHtmlAllowed)\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 progressCallbacks.delete(url);\n cancellableCallbacks.delete(url);\n });\n\n fetchPromises.set(url, promise);\n }\n\n if (onProgress && callbackUniqueId) {\n let activeCallbacks = progressCallbacks.get(url);\n if (!activeCallbacks) {\n activeCallbacks = new Map<string, ApiOnProgress>();\n progressCallbacks.set(url, activeCallbacks);\n }\n activeCallbacks.set(callbackUniqueId, onProgress);\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 progressCallbacks.forEach((map, url) => {\n map.forEach((callback) => {\n if (callback === progressCallback) {\n const parentCallback = cancellableCallbacks.get(url);\n if (!parentCallback) return;\n\n cancelApiProgress(parentCallback);\n cancellableCallbacks.delete(url);\n progressCallbacks.delete(url);\n }\n });\n });\n}\n\nexport function removeCallback(url: string, callbackUniqueId: string) {\n const callbacks = progressCallbacks.get(url);\n if (!callbacks) return;\n callbacks.delete(callbackUniqueId);\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(\n url: string, mediaFormat: ApiMediaFormat, isHtmlAllowed: boolean,\n) {\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]!, isHtmlAllowed);\n\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 const onProgress = makeOnProgress(url, mediaSource, sourceBuffer);\n cancellableCallbacks.set(url, onProgress);\n\n void callApi('downloadMedia', { url, mediaFormat }, onProgress);\n });\n\n memoryCache.set(url, streamUrl);\n return streamUrl;\n }\n\n const onProgress = makeOnProgress(url);\n cancellableCallbacks.set(url, onProgress);\n\n const remote = await callApi('downloadMedia', { url, mediaFormat, isHtmlAllowed }, onProgress);\n if (!remote) {\n throw new Error(`Failed to fetch media ${url}`);\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 = media.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 makeOnProgress(url: string, mediaSource?: MediaSource, sourceBuffer?: SourceBuffer) {\n const onProgress: ApiOnProgress = (progress: number, arrayBuffer: ArrayBuffer) => {\n progressCallbacks.get(url)?.forEach((callback) => {\n callback(progress);\n if (callback.isCanceled) onProgress.isCanceled = true;\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 return onProgress;\n}\n\nfunction prepareMedia(mediaData: ApiParsedMedia): ApiPreparedMedia {\n if (mediaData instanceof Blob) {\n return URL.createObjectURL(mediaData);\n }\n\n return mediaData;\n}\n\nif (IS_PROGRESSIVE_SUPPORTED) {\n navigator.serviceWorker.addEventListener('message', async (e) => {\n const { type, messageId, params } = e.data as {\n type: string;\n messageId: string;\n params: { url: string; start: number; end: number };\n };\n\n if (type !== 'requestPart') {\n return;\n }\n\n const result = await callApi('downloadMedia', { mediaFormat: ApiMediaFormat.Progressive, ...params });\n if (!result) {\n return;\n }\n\n const { arrayBuffer, mimeType, fullSize } = result;\n\n navigator.serviceWorker.controller!.postMessage({\n type: 'partResponse',\n messageId,\n result: {\n arrayBuffer,\n mimeType,\n fullSize,\n },\n }, [arrayBuffer!]);\n });\n}\n","export const MEMO_EMPTY_ARRAY = [];\n","import { DEBUG } from '../config';\n\nexport enum Bundles {\n Auth,\n Main,\n Extra,\n Calls,\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 [Bundles.Calls]: typeof import('../bundles/calls');\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 case Bundles.Calls:\n LOAD_PROMISES[Bundles.Calls] = import('../bundles/calls');\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 { DEBUG, IS_TEST } 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 soundPlayedIds = new Set<string>();\n\nexport async function playNotifySound(id?: string, volume?: number) {\n if (id !== undefined && soundPlayedIds.has(id)) return;\n const { notificationSoundVolume } = selectNotifySettings(getGlobal());\n const currentVolume = volume ? volume / 10 : notificationSoundVolume / 10;\n if (currentVolume === 0) return;\n\n const audio = new Audio('./notification.mp3');\n audio.volume = currentVolume;\n audio.setAttribute('mozaudiochannel', 'notification');\n if (id !== undefined) {\n audio.addEventListener('ended', () => {\n soundPlayedIds.add(id);\n }, { once: true });\n\n setTimeout(() => {\n soundPlayedIds.delete(id);\n }, soundPlayedDelay);\n }\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 playNotifySoundDebounced = debounce(playNotifySound, 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 selectNotifySettings(getGlobal());\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 selectNotifySettings(getGlobal());\n\n let global = replaceSettings(getGlobal(), resultSettings);\n if (resultExceptions) {\n global = addNotifyExceptions(global, resultExceptions);\n }\n setGlobal(global);\n areSettingsLoaded = true;\n return selectNotifySettings(global);\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) {\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\n return !document.hasFocus();\n}\n\nfunction getNotificationContent(chat: ApiChat, message: ApiMessage) {\n const global = getGlobal();\n const {\n senderId,\n replyToMessageId,\n } = message;\n\n const messageSender = senderId ? selectUser(global, senderId) : undefined;\n const messageAction = getMessageAction(message as ApiMessage);\n const actionTargetMessage = messageAction && replyToMessageId\n ? selectChatMessage(global, chat.id, replyToMessageId)\n : undefined;\n const {\n targetUserIds: actionTargetUserIds,\n targetChatId: actionTargetChatId,\n } = messageAction || {};\n\n const actionTargetUsers = actionTargetUserIds\n ? actionTargetUserIds.map((userId) => selectUser(global, userId))\n .filter<ApiUser>(Boolean as any)\n : undefined;\n const privateChatUserId = getPrivateChatUserId(chat);\n const privateChatUser = privateChatUserId ? selectUser(global, privateChatUserId) : undefined;\n\n let body: string;\n if (selectShouldShowMessagePreview(chat, selectNotifySettings(global), selectNotifyExceptions(global))) {\n if (isActionMessage(message)) {\n const actionOrigin = chat && (isChatChannel(chat) || message.senderId === message.chatId)\n ? chat\n : messageSender;\n body = renderActionMessageText(\n getTranslation,\n message,\n actionOrigin,\n actionTargetUsers,\n actionTargetMessage,\n actionTargetChatId,\n { asPlain: true },\n ) as string;\n } else {\n const senderName = getMessageSenderName(getTranslation, chat.id, messageSender);\n const summary = getMessageSummaryText(getTranslation, message);\n\n body = senderName ? `${senderName}: ${summary}` : summary;\n }\n } else {\n body = 'New message';\n }\n\n return {\n title: getChatTitle(getTranslation, chat, privateChatUser),\n body,\n };\n}\n\nasync function getAvatar(chat: ApiChat) {\n const imageHash = getChatAvatarHash(chat);\n if (!imageHash) return undefined;\n let mediaData = mediaLoader.getFromMemory<ApiMediaFormat.BlobUrl>(imageHash);\n if (!mediaData) {\n await mediaLoader.fetch(imageHash, ApiMediaFormat.BlobUrl);\n mediaData = mediaLoader.getFromMemory<ApiMediaFormat.BlobUrl>(imageHash);\n }\n return mediaData;\n}\n\nexport async function notifyAboutNewMessage({\n chat,\n message,\n}: { chat: ApiChat; message: Partial<ApiMessage> }) {\n const { hasWebNotifications } = await loadNotificationSettings();\n if (!checkIfShouldNotify(chat)) return;\n const areNotificationsSupported = checkIfNotificationsSupported();\n if (!hasWebNotifications || !areNotificationsSupported) {\n // only play sound if web notifications are disabled\n playNotifySoundDebounced(String(message.id) || chat.id);\n return;\n }\n if (!areNotificationsSupported) return;\n if (!message.id) return;\n\n const {\n title,\n body,\n } = getNotificationContent(chat, message as ApiMessage);\n\n const icon = await getAvatar(chat);\n\n if (checkIfPushSupported()) {\n if (navigator.serviceWorker?.controller) {\n // notify service worker about new message notification\n navigator.serviceWorker.controller.postMessage({\n type: 'newMessageNotification',\n payload: {\n title,\n body,\n icon,\n chatId: chat.id,\n messageId: message.id,\n },\n });\n }\n } else {\n const dispatch = getDispatch();\n const options: NotificationOptions = {\n body,\n icon,\n badge: icon,\n tag: String(message.id),\n };\n\n if ('vibrate' in navigator) {\n options.vibrate = [200, 100, 200];\n }\n\n const notification = new Notification(title, options);\n\n notification.onclick = () => {\n notification.close();\n dispatch.focusMessage({\n chatId: chat.id,\n messageId: message.id,\n });\n if (window.focus) {\n window.focus();\n }\n };\n\n // Play sound when notification is displayed\n notification.onshow = () => {\n playNotifySoundDebounced(String(message.id) || chat.id);\n };\n }\n}\n\nexport function closeMessageNotifications(payload: { chatId: string; lastReadInboxMessageId?: number }) {\n if (IS_TEST || !navigator.serviceWorker?.controller) return;\n navigator.serviceWorker.controller.postMessage({\n type: 'closeMessageNotifications',\n payload,\n });\n}\n\n// Notify service worker that client is fully loaded\nexport function notifyClientReady() {\n if (!navigator.serviceWorker?.controller) return;\n navigator.serviceWorker.controller.postMessage({\n type: 'clientReady',\n });\n}\n","import { ApiCountryCode } from '../api/types';\nimport { flatten } from './iteratees';\n\nconst PATTERN_PLACEHOLDER = 'X';\nconst DEFAULT_PATTERN = 'XXX XXX XXX XXX';\n\nexport function getCountryCodesByIso(phoneCodeList: ApiCountryCode[], iso: string) {\n return phoneCodeList.filter((country) => country.iso2 === iso);\n}\n\nexport function getCountryFromPhoneNumber(phoneCodeList: ApiCountryCode[], input = '') {\n let phoneNumber = input.replace(/[^\\d+]+/g, '');\n if (phoneNumber.startsWith('+')) {\n phoneNumber = phoneNumber.substr(1);\n }\n\n const possibleCountries = phoneCodeList\n .filter((country) => phoneNumber.startsWith(country.countryCode));\n const codesWithPrefix: { code: string; country: ApiCountryCode }[] = flatten(possibleCountries\n .map((country) => (country.prefixes || ['']).map((prefix) => {\n return {\n code: `${country.countryCode}${prefix}`,\n country,\n };\n })));\n\n const bestMatches = codesWithPrefix\n .filter(({ code }) => phoneNumber.startsWith(code))\n .sort((a, b) => a.code.length - b.code.length);\n\n return bestMatches[bestMatches.length - 1]?.country;\n}\n\nexport function formatPhoneNumber(input: string, country?: ApiCountryCode) {\n let phoneNumber = input.replace(/[^\\d]+/g, '');\n if (country) {\n phoneNumber = phoneNumber.substr(country.countryCode.length);\n } else if (input.startsWith('+')) {\n return input;\n }\n const pattern = getBestPattern(phoneNumber, country?.patterns);\n\n const result: string[] = []; // Result character array\n let j = 0; // Position inside pattern\n for (let i = 0; i < phoneNumber.length; i++) {\n while (pattern[j] !== PATTERN_PLACEHOLDER && j < pattern.length) {\n result.push(pattern[j]);\n if (pattern[j] === phoneNumber[i]) { // If pattern contains digits, move input position too\n i++;\n if (i === phoneNumber.length) break; // But don't overdo it, or it will insert full pattern unexpectedly\n }\n j++;\n }\n\n result.push(phoneNumber[i]); // For placeholder characters, setting current input digit\n j++;\n }\n\n return result.join('');\n}\n\nfunction getBestPattern(numberWithoutCode: string, patterns?: string[]) {\n if (!patterns || patterns.length === 0) return DEFAULT_PATTERN;\n if (patterns.length === 1) return patterns[0];\n\n const defaultPattern = patterns.find((pattern) => pattern.startsWith(PATTERN_PLACEHOLDER)) || DEFAULT_PATTERN;\n\n const bestMatches = patterns.filter((pattern) => {\n const stripped = pattern.replace(/[^\\dX]+/g, '');\n if (stripped.startsWith(PATTERN_PLACEHOLDER)) return false; // Don't consider default number format here\n for (let i = 0; i < numberWithoutCode.length; i++) {\n if (i > stripped.length - 1 || (stripped[i] !== PATTERN_PLACEHOLDER && stripped[i] !== numberWithoutCode[i])) {\n return false;\n }\n }\n return true;\n });\n\n // Playing it safe: if not sure, use default for that region\n return bestMatches.length === 1 ? bestMatches[0] : defaultPattern;\n}\n\nexport function formatPhoneNumberWithCode(phoneCodeList: ApiCountryCode[], phoneNumber: string) {\n const numberWithPlus = phoneNumber.startsWith('+') ? phoneNumber : `+${phoneNumber}`;\n const country = getCountryFromPhoneNumber(phoneCodeList, numberWithPlus);\n if (!country) {\n return numberWithPlus;\n }\n return `+${country.countryCode} ${formatPhoneNumber(numberWithPlus, country)}`;\n}\n","import { MessageList, MessageListType } from '../global/types';\nimport { MAIN_THREAD_ID } from '../api/types';\n\nexport const createMessageHash = (messageList: MessageList): string => (\n messageList.chatId.toString()\n + (messageList.type !== 'thread' ? `_${messageList.type}`\n : (messageList.threadId !== -1 ? `_${messageList.threadId}` : ''))\n);\n\nexport const parseLocationHash = (value: string): MessageList | undefined => {\n if (!value) return undefined;\n\n const [chatId, typeOrThreadId] = value.replace(/^#/, '').split('_');\n\n if (!chatId) return undefined;\n\n const isType = ['thread', 'pinned', 'scheduled'].includes(typeOrThreadId);\n\n return {\n chatId,\n type: !!typeOrThreadId && isType ? (typeOrThreadId as MessageListType) : 'thread',\n threadId: !!typeOrThreadId && !isType ? Number(typeOrThreadId) : MAIN_THREAD_ID,\n };\n};\n","type Scheduler =\n typeof requestAnimationFrame\n | typeof onTickEnd\n | typeof runNow;\n\nexport function debounce<F extends AnyToVoidFunction>(\n fn: F,\n ms: number,\n shouldRunFirst = true,\n shouldRunLast = true,\n) {\n let waitingTimeout: number | undefined;\n\n return (...args: Parameters<F>) => {\n if (waitingTimeout) {\n clearTimeout(waitingTimeout);\n waitingTimeout = undefined;\n } else if (shouldRunFirst) {\n fn(...args);\n }\n\n // eslint-disable-next-line no-restricted-globals\n waitingTimeout = self.setTimeout(() => {\n if (shouldRunLast) {\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 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 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(fastRafPrimary, 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 fn(...args);\n });\n }\n };\n}\n\nexport function onIdle(cb: NoneToVoidFunction, timeout?: number) {\n // eslint-disable-next-line no-restricted-globals\n if (self.requestIdleCallback) {\n // eslint-disable-next-line no-restricted-globals\n self.requestIdleCallback(cb, { timeout });\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 fastRafPrimary(callback: NoneToVoidFunction) {\n fastRaf(callback, true);\n}\n\nlet onTickEndCallbacks: NoneToVoidFunction[] | undefined;\nlet onTickEndPrimaryCallbacks: NoneToVoidFunction[] | undefined;\n\nexport function onTickEnd(callback: NoneToVoidFunction, isPrimary = false) {\n if (!onTickEndCallbacks) {\n onTickEndCallbacks = isPrimary ? [] : [callback];\n onTickEndPrimaryCallbacks = isPrimary ? [callback] : [];\n\n Promise.resolve().then(() => {\n const currentCallbacks = onTickEndCallbacks!;\n const currentPrimaryCallbacks = onTickEndPrimaryCallbacks!;\n onTickEndCallbacks = undefined;\n onTickEndPrimaryCallbacks = undefined;\n currentPrimaryCallbacks.forEach((cb) => cb());\n currentCallbacks.forEach((cb) => cb());\n });\n } else if (isPrimary) {\n onTickEndPrimaryCallbacks!.push(callback);\n } else {\n onTickEndCallbacks.push(callback);\n }\n}\n\nexport function onTickEndPrimary(callback: NoneToVoidFunction) {\n onTickEnd(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 | string[]) {\n if (!haystack || !needle) {\n return false;\n }\n\n const needleWords = typeof needle === 'string' ? needle.toLowerCase().split(RE_NOT_LETTER) : needle;\n const haystackLower = haystack.toLowerCase();\n\n // @optimization\n if (needleWords.length === 1 && !haystackLower.includes(needleWords[0])) {\n return false;\n }\n\n let haystackWords: string[];\n\n return needleWords.every((needleWord) => {\n if (!haystackLower.includes(needleWord)) {\n return false;\n }\n\n if (!haystackWords) {\n haystackWords = haystackLower.split(RE_NOT_LETTER);\n }\n\n return haystackWords.some((haystackWord) => haystackWord.startsWith(needleWord));\n });\n}\n\nexport function prepareSearchWordsForNeedle(needle: string) {\n const needleWords = needle.toLowerCase().split(RE_NOT_LETTER);\n\n return (haystack: string) => searchWords(haystack, needleWords);\n}\n","export const getServerTime = (serverTimeOffset: number) => {\n return Math.floor(Date.now() / 1000) + serverTimeOffset;\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?: string) {\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\n if (hashes) {\n Object.keys(hashes).map(Number).forEach((dcId) => {\n localStorage.setItem(`dc${dcId}_hash`, JSON.stringify(hashes[dcId]));\n });\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: string };\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;\nconst RGB_VARIABLES = new Set([\n '--color-primary-shade',\n '--color-text-secondary',\n]);\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 if (RGB_VARIABLES.has(property)) {\n document.documentElement.style.setProperty(`${property}-rgb`, `${r},${g},${b}`);\n }\n });\n}\n","import EMOJI_REGEX from '../lib/twemojiRegex';\nimport { fixNonStandardEmoji } from './emoji';\n\nexport 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) => {\n if (!word.length) return '';\n word = fixNonStandardEmoji(word);\n const emojis = word.match(EMOJI_REGEX);\n if (emojis && word.startsWith(emojis[0])) {\n return emojis[0];\n }\n return word.match(/./u)![0].toUpperCase();\n })\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, dataUri: string): Promise<string> {\n if (isWebpSupported() || dataUri.substr(0, 15) !== 'data:image/webp') {\n return dataUri;\n }\n\n initWebpWorker();\n\n const pngBlob = await webpToPng(key, dataUriToBlob(dataUri));\n\n if (!pngBlob) {\n throw new Error(`Can't convert webp to png. Url: ${dataUri}`);\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, DEBUG } 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 (DEBUG) {\n return;\n }\n\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('orientationchange', handleResize);\nif (IS_IOS) {\n window.visualViewport.addEventListener('resize', handleResize);\n} else {\n window.addEventListener('resize', handleResize);\n}\n\nexport function updateSizes(): IDimensions {\n let height: number;\n if (IS_IOS) {\n height = window.visualViewport.height + window.visualViewport.pageTop;\n } else {\n height = window.innerHeight;\n }\n const vh = height * 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 + \".\" + {\"87\":\"f9efe67c5df9f5da39e2\",\"99\":\"f03a947e6e336feffec8\",\"133\":\"42b7d5ed8329409ab320\",\"161\":\"286d0207d962142ad548\",\"301\":\"1f369c31b0862e5bbb87\",\"354\":\"5a3212a48341fe482e1e\",\"472\":\"21e5264f606f2b525030\",\"501\":\"72ce4b6e27f459e194cd\",\"524\":\"bb18f0820dd431486c23\",\"532\":\"0ac3c86599df5cf0b45e\",\"536\":\"55dc7dd4ab42a2c9f037\",\"739\":\"091045a7bd9587161776\",\"745\":\"9316c5c2b711c39a20a5\",\"884\":\"0aacd0fcecc50a0aec87\",\"886\":\"3dd0d770ecb4bdf3aed4\",\"915\":\"0588cdc78683d0e9bbbc\",\"927\":\"fd5c9ce4522d0a6d85a8\",\"941\":\"5a6cedb5afef94338282\",\"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 + \".\" + {\"87\":\"f9efe67c5df9f5da39e2\",\"133\":\"42b7d5ed8329409ab320\",\"301\":\"1f369c31b0862e5bbb87\",\"472\":\"21e5264f606f2b525030\",\"532\":\"0ac3c86599df5cf0b45e\",\"886\":\"3dd0d770ecb4bdf3aed4\"}[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\tif(chunkIds.some((id) => (installedChunks[id] !== 0))) {\n\t\tfor(moduleId in moreModules) {\n\t\t\tif(__webpack_require__.o(moreModules, moduleId)) {\n\t\t\t\t__webpack_require__.m[moduleId] = moreModules[moduleId];\n\t\t\t}\n\t\t}\n\t\tif(runtime) var result = runtime(__webpack_require__);\n\t}\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, DEBUG_MORE } from '../config';\nimport { getDispatch } from '../lib/teact/teactn';\nimport { IS_ANDROID, IS_IOS, IS_SERVICE_WORKER_SUPPORTED } from './environment';\nimport { notifyClientReady, playNotifySoundDebounced } 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 (DEBUG_MORE) {\n // eslint-disable-next-line no-console\n console.log('[SW] Message from worker', action);\n }\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 playNotifySoundDebounced(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 DEFAULT_PLAYBACK_RATE,\n DEFAULT_VOLUME,\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 countryList: {\n phoneCodes: [],\n general: [],\n },\n\n blocked: {\n ids: [],\n totalCount: 0,\n },\n\n users: {\n byId: {},\n statusesById: {},\n },\n\n chats: {\n listIds: {},\n isFullyLoaded: {},\n orderedPinnedIds: {},\n totalCount: {},\n byId: {},\n },\n\n messages: {\n byChatId: {},\n messageLists: [],\n sponsoredByChatId: {},\n },\n\n groupCalls: {\n byId: {},\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 volume: DEFAULT_VOLUME,\n playbackRate: DEFAULT_PLAYBACK_RATE,\n isMuted: false,\n },\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 canAutoLoadPhotoFromContacts: true,\n canAutoLoadPhotoInPrivateChats: true,\n canAutoLoadPhotoInGroups: true,\n canAutoLoadPhotoInChannels: true,\n canAutoLoadVideoFromContacts: true,\n canAutoLoadVideoInPrivateChats: true,\n canAutoLoadVideoInGroups: true,\n canAutoLoadVideoInChannels: true,\n canAutoLoadFileFromContacts: false,\n canAutoLoadFileInPrivateChats: false,\n canAutoLoadFileInGroups: false,\n canAutoLoadFileInChannels: false,\n autoLoadFileMaxSizeMb: 10,\n hasWebNotifications: true,\n hasPushNotifications: true,\n notificationSoundVolume: 5,\n canAutoPlayGifs: true,\n canAutoPlayVideos: true,\n shouldSuggestStickers: true,\n shouldLoopStickers: true,\n language: 'en',\n timeFormat: '24h',\n wasTimeFormatSetManually: false,\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 activeDownloads: {\n byChatId: {},\n },\n\n serviceNotifications: [],\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 DEFAULT_VOLUME,\n DEFAULT_PLAYBACK_RATE,\n} from '../config';\nimport { IS_SINGLE_COLUMN_LAYOUT } from '../util/environment';\nimport { isHeavyAnimating } from '../hooks/useHeavyAnimationCheck';\nimport { pick } from '../util/iteratees';\nimport { selectCurrentMessageList } from '../modules/selectors';\nimport { hasStoredSession } from '../util/sessions';\nimport { INITIAL_STATE } from './initial';\nimport { parseLocationHash } from '../util/routing';\nimport { LOCATION_HASH } from '../hooks/useHistoryBack';\nimport { isUserId } from '../modules/helpers';\n\nconst UPDATE_THROTTLE = 5000;\n\nconst updateCacheThrottled = throttle(() => onIdle(updateCache), UPDATE_THROTTLE, false);\n\nlet isCaching = false;\nlet unsubscribeFromBeforeUnload: NoneToVoidFunction | undefined;\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): GlobalState | undefined {\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): 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 migrateCache(cached, initialState);\n }\n\n const newState = {\n ...initialState,\n ...cached,\n };\n\n const parsedMessageList = !IS_SINGLE_COLUMN_LAYOUT ? parseLocationHash(LOCATION_HASH) : undefined;\n\n return {\n ...newState,\n messages: {\n ...newState.messages,\n messageLists: parsedMessageList ? [parsedMessageList] : [],\n },\n };\n}\n\nfunction migrateCache(cached: GlobalState, initialState: GlobalState) {\n if ('shouldAutoDownloadMediaFromContacts' in cached.settings.byKey) {\n const {\n shouldAutoDownloadMediaFromContacts,\n shouldAutoDownloadMediaInPrivateChats,\n shouldAutoDownloadMediaInGroups,\n shouldAutoDownloadMediaInChannels,\n shouldAutoPlayVideos,\n shouldAutoPlayGifs,\n ...rest\n } = cached.settings.byKey;\n\n cached.settings.byKey = {\n ...rest,\n canAutoLoadPhotoFromContacts: shouldAutoDownloadMediaFromContacts,\n canAutoLoadVideoFromContacts: shouldAutoDownloadMediaFromContacts,\n canAutoLoadPhotoInPrivateChats: shouldAutoDownloadMediaInPrivateChats,\n canAutoLoadVideoInPrivateChats: shouldAutoDownloadMediaInPrivateChats,\n canAutoLoadPhotoInGroups: shouldAutoDownloadMediaInGroups,\n canAutoLoadVideoInGroups: shouldAutoDownloadMediaInGroups,\n canAutoLoadPhotoInChannels: shouldAutoDownloadMediaInChannels,\n canAutoLoadVideoInChannels: shouldAutoDownloadMediaInChannels,\n canAutoPlayVideos: shouldAutoPlayVideos,\n canAutoPlayGifs: shouldAutoPlayGifs,\n };\n }\n\n cached.settings.byKey = {\n ...initialState.settings.byKey,\n ...cached.settings.byKey,\n };\n\n cached.settings.themes = {\n ...initialState.settings.themes,\n ...cached.settings.themes,\n };\n\n cached.chatFolders = {\n ...initialState.chatFolders,\n ...cached.chatFolders,\n };\n\n if (!cached.stickers.greeting) {\n cached.stickers.greeting = initialState.stickers.greeting;\n }\n\n if (!cached.activeDownloads) {\n cached.activeDownloads = {\n byChatId: {},\n };\n }\n\n if (!cached.serviceNotifications) {\n cached.serviceNotifications = [];\n }\n\n if (cached.audioPlayer.volume === undefined) {\n cached.audioPlayer.volume = DEFAULT_VOLUME;\n }\n\n if (cached.audioPlayer.playbackRate === undefined) {\n cached.audioPlayer.playbackRate = DEFAULT_PLAYBACK_RATE;\n }\n\n if (!cached.groupCalls) {\n cached.groupCalls = initialState.groupCalls;\n }\n\n if (!cached.users.statusesById) {\n cached.users.statusesById = {};\n }\n\n if (!cached.messages.sponsoredByChatId) {\n cached.messages.sponsoredByChatId = {};\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 'leftColumnWidth',\n 'serviceNotifications',\n ]),\n audioPlayer: {\n volume: global.audioPlayer.volume,\n playbackRate: global.audioPlayer.playbackRate,\n isMuted: global.audioPlayer.isMuted,\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 groupCalls: reduceGroupCalls(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, statusesById, selectedId } } = global;\n const chatIds = (global.chats.listIds.active || []).slice(0, GLOBAL_STATE_CACHE_CHAT_LIST_LIMIT).filter(isUserId);\n const userIds = Object.keys(byId);\n const idsToSave = chatIds.concat(userIds).slice(0, GLOBAL_STATE_CACHE_USER_LIST_LIMIT);\n\n return {\n byId: pick(byId, idsToSave),\n statusesById: pick(statusesById, idsToSave),\n selectedId: window.innerWidth > MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN ? selectedId : undefined,\n };\n}\n\nfunction reduceChats(global: GlobalState): GlobalState['chats'] {\n const newListIds = (global.chats.listIds.active || []).slice(0, GLOBAL_STATE_CACHE_CHAT_LIST_LIMIT);\n const { chatId: currentChatId } = selectCurrentMessageList(global) || {};\n const idsToSave = newListIds.concat(currentChatId ? [currentChatId] : []);\n\n return {\n ...global.chats,\n byId: pick(global.chats.byId, idsToSave),\n listIds: {\n active: newListIds,\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 chatIds = (global.chats.listIds.active || []).slice(0, GLOBAL_STATE_CACHE_CHAT_LIST_LIMIT);\n const chatIdsToSave = chatIds.concat(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 return {\n byChatId,\n messageLists: [],\n sponsoredByChatId: {},\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 reduceGroupCalls(global: GlobalState): GlobalState['groupCalls'] {\n return {\n ...global.groupCalls,\n byId: {},\n activeGroupCallId: undefined,\n isGroupCallPanelHidden: undefined,\n isFallbackConfirmOpen: undefined,\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 { getDispatch, getGlobal, withGlobal } from '../../lib/teact/teactn';\n\nimport { ApiMediaFormat } from '../../api/types';\nimport { 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 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 =\n Pick<GlobalState, 'uiReadyState' | 'shouldSkipHistoryAnimations'>\n & {\n hasCustomBackground?: boolean;\n hasCustomBackgroundColor: boolean;\n isRightColumnShown?: boolean;\n leftColumnWidth?: number;\n };\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.BlobUrl);\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> = ({\n page,\n children,\n hasCustomBackground,\n hasCustomBackgroundColor,\n isRightColumnShown,\n shouldSkipHistoryAnimations,\n leftColumnWidth,\n}) => {\n const { setIsUiReady } = getDispatch();\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\n className=\"left\"\n // @ts-ignore teact feature\n style={leftColumnWidth ? `width: ${leftColumnWidth}px` : undefined}\n />\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 leftColumnWidth: global.leftColumnWidth,\n };\n },\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';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { ApiCountryCode } from '../../api/types';\n\nimport { ANIMATION_END_DELAY } from '../../config';\nimport { prepareSearchWordsForNeedle } from '../../util/searchWords';\nimport buildClassName from '../../util/buildClassName';\nimport renderText from '../common/helpers/renderText';\nimport useLang from '../../hooks/useLang';\nimport { isoToEmoji } from '../../util/emoji';\nimport useOnChange from '../../hooks/useOnChange';\n\nimport DropdownMenu from '../ui/DropdownMenu';\nimport MenuItem from '../ui/MenuItem';\nimport Spinner from '../ui/Spinner';\n\nimport './CountryCodeInput.scss';\n\ntype StateProps = {\n phoneCodeList: ApiCountryCode[];\n};\n\ntype OwnProps = {\n id: string;\n value?: ApiCountryCode;\n isLoading?: boolean;\n onChange: (value: ApiCountryCode) => void;\n};\n\nconst MENU_HIDING_DURATION = 200 + ANIMATION_END_DELAY;\nconst SELECT_TIMEOUT = 50;\n\nconst CountryCodeInput: FC<OwnProps & StateProps> = ({\n id,\n value,\n isLoading,\n onChange,\n phoneCodeList,\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<ApiCountryCode[]>([]);\n\n const updateFilter = useCallback((filterValue?: string) => {\n setFilter(filterValue);\n setFilteredList(getFilteredList(phoneCodeList, filterValue));\n }, [phoneCodeList]);\n\n useOnChange(([prevPhoneCodeList]) => {\n if (prevPhoneCodeList?.length === 0 && phoneCodeList.length > 0) {\n updateFilter(filter);\n }\n }, [phoneCodeList, updateFilter]);\n\n const handleChange = useCallback((country: ApiCountryCode) => {\n onChange(country);\n\n setTimeout(() => updateFilter(undefined), MENU_HIDING_DURATION);\n }, [onChange, updateFilter]);\n\n const handleInput = useCallback((e: React.FormEvent<HTMLInputElement>) => {\n updateFilter(e.currentTarget.value);\n }, [updateFilter]);\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, updateFilter, 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 handleCodeInput = (e: React.FormEvent<HTMLInputElement>) => {\n handleInput(e);\n handleTrigger();\n };\n\n const inputValue = filter ?? (value?.name || value?.defaultName || '');\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={handleCodeInput}\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\n .map((country: ApiCountryCode) => (\n <MenuItem\n key={country.iso2}\n className={value && country.iso2 === value.iso2 ? 'selected' : ''}\n onClick={() => handleChange(country)}\n >\n <span className=\"country-flag\">{renderText(isoToEmoji(country.iso2), ['hq_emoji'])}</span>\n <span className=\"country-name\">{country.name || country.defaultName}</span>\n <span className=\"country-code\">{country.countryCode}</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(countryList: ApiCountryCode[], filter = ''): ApiCountryCode[] {\n if (!filter.length) {\n return countryList;\n }\n\n const searchWords = prepareSearchWordsForNeedle(filter);\n\n return countryList.filter((country) => (\n searchWords(country.defaultName) || (country.name && searchWords(country.name))\n ));\n}\n\nexport default memo(withGlobal<OwnProps>(\n (global): StateProps => {\n const { countryList: { phoneCodes: phoneCodeList } } = global;\n return {\n phoneCodeList,\n };\n },\n)(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 { getDispatch, withGlobal } from '../../lib/teact/teactn';\n\nimport { GlobalState } from '../../global/types';\nimport { LangCode } from '../../types';\nimport { ApiCountryCode } from '../../api/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, getCountryCodesByIso, 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' |\n 'authIsLoadingQrCode' | 'authError' |\n 'authRememberMe' | 'authNearestCountry'\n)> & {\n language?: LangCode;\n phoneCodeList: ApiCountryCode[];\n};\n\nconst MIN_NUMBER_LENGTH = 7;\n\nlet isPreloadInitiated = false;\n\nconst AuthPhoneNumber: FC<StateProps> = ({\n connectionState,\n authState,\n authPhoneNumber,\n authIsLoading,\n authIsLoadingQrCode,\n authError,\n authRememberMe,\n authNearestCountry,\n phoneCodeList,\n language,\n}) => {\n const {\n setAuthPhoneNumber,\n setAuthRememberMe,\n loadNearestCountry,\n loadCountryList,\n clearAuthError,\n goToAuthQrCode,\n setSettingOption,\n } = getDispatch();\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<ApiCountryCode | 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.countryCode} ${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 (connectionState === 'connectionStateReady') {\n loadCountryList({ langCode: language });\n }\n }, [connectionState, language, loadCountryList]);\n\n useEffect(() => {\n if (authNearestCountry && phoneCodeList && !country && !isTouched) {\n setCountry(getCountryCodesByIso(phoneCodeList, authNearestCountry)[0]);\n }\n }, [country, authNearestCountry, isTouched, phoneCodeList]);\n\n const parseFullNumber = useCallback((newFullNumber: string) => {\n if (!newFullNumber.length) {\n setPhoneNumber('');\n }\n\n const suggestedCountry = phoneCodeList && getCountryFromPhoneNumber(phoneCodeList, newFullNumber);\n\n // Any phone numbers should be allowed, in some cases ignoring formatting\n const selectedCountry = !country\n || (suggestedCountry && suggestedCountry.iso2 !== country.iso2)\n || (!suggestedCountry && newFullNumber.length)\n ? suggestedCountry\n : country;\n\n if (!country || !selectedCountry || (selectedCountry && selectedCountry.iso2 !== country.iso2)) {\n setCountry(selectedCountry);\n }\n setPhoneNumber(formatPhoneNumber(newFullNumber, selectedCountry));\n }, [phoneCodeList, 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 handleCountryChange = useCallback((value: ApiCountryCode) => {\n setCountry(value);\n setPhoneNumber('');\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!.countryCode} ${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={handleCountryChange}\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 countryList: { phoneCodes: phoneCodeList },\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 phoneCodeList,\n };\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 { getDispatch, withGlobal } from '../../lib/teact/teactn';\n\nimport { GlobalState } from '../../global/types';\nimport { LangCode } from '../../types';\n\nimport { DEFAULT_LANG_CODE } from '../../config';\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 =\n Pick<GlobalState, 'connectionState' | 'authState' | 'authQrCode'>\n & {\n language?: LangCode;\n };\n\nconst DATA_PREFIX = 'tg://login?token=';\n\nconst AuthCode: FC<StateProps> = ({\n connectionState,\n authState,\n authQrCode,\n language,\n}) => {\n const {\n returnToAuthPhoneNumber,\n setSettingOption,\n } = getDispatch();\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 useEffect(() => {\n if (connectionState === 'connectionStateReady') {\n void setLanguage(DEFAULT_LANG_CODE);\n }\n }, [connectionState]);\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)(AuthCode));\n","import React, { FC, useEffect, memo } from '../../lib/teact/teact';\nimport { getDispatch, withGlobal } from '../../lib/teact/teactn';\n\nimport { 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'>;\n\nconst Auth: FC<StateProps> = ({\n authState,\n}) => {\n const {\n reset, initApi, returnToAuthPhoneNumber, goToAuthQrCode,\n } = getDispatch();\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)(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, { getDispatch, withGlobal } from './lib/teact/teactn';\n\nimport { 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'>;\n\nconst App: FC<StateProps> = ({ authState }) => {\n const { disconnect } = getDispatch();\n\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)(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.warn('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","platform","window","async","Promise","race","makeRequest","pause","then","Error","err","Date","now","startedAt","location","reload","args","callApi","fnName","name","warn","cancelApiProgress","progressCallback","isCanceled","postMessage","message","generateIdFor","payload","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","getDomain","url","href","ensureProtocol","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_TG_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","sender","openUserInfo","id","Link","focusMessage","handleMessageClick","chatId","openChat","groupCall","joinGroupCall","accessHash","renderActionMessageText","lang","actionOrigin","targetUsers","targetMessage","targetChatId","options","action","translationValues","amount","currency","call","textOptions","maxTextLength","processed","unprocessed","undefined","includes","processPlaceholder","formatCurrency","code","isEmbedded","origin","asPlain","isUserId","renderUserContent","chat","trimText","getChatTitle","renderText","renderChatContent","renderOriginContent","map","user","filter","getMessageSummaryText","photo","video","sticker","getMessageContent","showQuotes","messageText","isGif","renderMessageContent","invoice","renderProductContent","renderMigratedContent","trim","renderGroupCallContent","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","fixNonStandardEmoji","emojis","emojiResult","emoji","nativeToUnified","removeVS16s","src","alt","splittenParts","line","source","trimmedLine","trimLeft","indentLength","repeat","RE_LINK_TEMPLATE","RE_MENTION_TEMPLATE","entities","entityResult","entity","preventMessageInputBlur","withBubbling","IS_IOS","activeElement","EDITABLE_INPUT_ID","currentTarget","preventMessageInputBlurWithBubbling","withGlobal","global","userId","userOrChat","selectUser","openChatByUsername","ref","onContextMenu","onMouseDown","onMouseEnter","onMouseLeave","onFocus","color","backgroundImage","round","pill","fluid","isText","isLoading","ariaLabel","download","disabled","ripple","faded","tabIndex","withClickPropagation","elementRef","useRef","isClicked","setIsClicked","useState","fullClassName","setTimeout","handleMouseDown","style","label","subLabel","checked","blocking","onChange","onCheck","useLang","handleChange","event","trigger","positionX","positionY","footer","forceOpen","onOpen","onClose","menuRef","dropdownRef","isOpen","setIsOpen","onKeyDown","menu","current","keyCode","focusedElement","elementChildren","from","focus","onTrigger","containerRef","autoClose","shouldSkipTransition","success","readOnly","autoComplete","inputMode","maxLength","onInput","onKeyPress","onBlur","onPaste","labelText","htmlFor","withBackground","menuStyle","noCloseOnBackdrop","onCloseAnimationEnd","backdropContainerRef","transitionClassNames","useShowTransition","useEffect","captureEscKeyListener","useHistoryBack","useEffectWithPrevDeps","prevIsOpen","dispatchHeavyAnimationEvent","handleKeyDown","useKeyboardListNavigation","useVirtualBackdrop","bubbleClassName","props","icon","destructive","stopPropagation","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","AUTODOWNLOAD_FILESIZE_MB_LIMITS","isBigScreen","innerHeight","MIN_PASSWORD_LENGTH","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","DEFAULT_VOLUME","DEFAULT_PLAYBACK_RATE","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","SEND_MESSAGE_ACTION_INTERVAL","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","TMP_CHAT_ID","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","VIDEO_MOV_TYPE","SUPPORTED_IMAGE_CONTENT_TYPES","SUPPORTED_VIDEO_CONTENT_TYPES","CONTENT_TYPES_WITH_PREVIEW","COUNTRIES_WITH_12H_TIME_FORMAT","SERVICE_NOTIFICATIONS_USER_ID","REPLIES_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","SEEN_BY_MEMBERS_CHAT_MAX","SEEN_BY_MEMBERS_EXPIRE","GROUP_CALL_VOLUME_MULTIPLIER","GROUP_CALL_DEFAULT_VOLUME","ENABLE_THUMBNAIL_VIDEO","cb","dependencies","debugKey","prevDeps","usePrevious","initial","setValue","setTrigger","ANIMATION_START_EVENT","ANIMATION_END_EVENT","timeout","isAnimating","handleAnimationStart","handleAnimationEnd","removeEventListener","isHeavyAnimating","duration","onEnd","clearTimeout","dispatchEvent","Event","LOCATION_HASH","hash","PATH_BASE","pathname","search","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","touches","pageX","innerWidth","onSelectWithEnter","itemSelector","noCaptureFocus","focusedIndex","setFocusedIndex","element","querySelectorAll","newIndex","item","forceUpdate","useForceUpdate","useOnChange","langProvider","bundleName","moduleName","noLoad","autoUpdate","module","getModuleFromMemory","addLoadListener","loadModule","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","currentValue","newValue","cssText","removeAttribute","setAttribute","updateAttributes","currentEl","teactFastList","$newChild","currentRemainingIndex","remainingByKey","acc","$currentChild","isKeyPresent","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","__html","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","handleError","renderedValue","newChild","$old","hook","cleanup","effect","nextValue","setter","helpGc","prepareComponentForFrame","prepareForFrame","throttleWithPrimaryRaf","throttleWithRaf","forceUpdateComponent","currentElement","DEBUG_contentComponentName","useLayoutEffectBase","schedulerFn","primarySchedulerFn","execCleanup","exec","dependency","causedBy","res","prevValue","fastRaf","fastRafPrimary","useLayoutEffect","onTickEnd","onTickEndPrimary","resolver","getUnequalProps","newCallback","areEqual","arePropsShallowEqual","propsRef","renderedRef","orderBy","values","React","currentGlobal","reducers","callbacks","containers","mapStateToProps","ownProps","mappedProps","newMappedProps","Number","isNaN","DEBUG_componentName","areMappedPropsChanged","DEBUG_updates","updateTime","actions","runCallbacksThrottled","throttleWithTickEnd","runCallbacks","forceOnHeavyAnimation","setGlobal","newGlobal","forceSyncOnIOs","getGlobal","addReducer","reducer","onDispatch","addCallback","removeCallback","TeactNContainer","vs16RegExp","zeroWidthJoiner","rawEmoji","importLegacySession","clearLegacySessions","apiUpdate","userAgent","navigator","PLATFORM_ENV","sessionData","loadStoredSession","isTest","isMovSupported","IS_MOV_SUPPORTED","phoneNumber","authIsLoading","authError","password","file","firstName","lastName","authIsLoadingQrCode","storeSession","currentUserId","clearStoredSession","unsubscribe","forceWebsync","reset","cacheApi","langCachePrefix","langCacheVersion","updateAppBadge","init","connectionState","authNearestCountry","deviceToken","subscribedAt","buildInputPrivacyRules","visibility","allowedIds","deniedIds","users","byId","usersById","chats","chatsById","rules","collectUsers","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","langCode","language","countryList","timeFormat","setSettingOption","setTimeFormat","wasTimeFormatSetManually","nearestCountryCode","selectNotifySettings","setLanguage","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","handleSystemThemeChange","currentThemeMatch","documentElement","currentTheme","nextTheme","selectTheme","animationLevel","switchTheme","mql","matchMedia","addListener","subscribeToSystemThemeChange","messageTextSize","theme","setProperty","toString","IS_TOUCH_ENV","startWebsync","IS_ANDROID","IS_MAC_OS","IS_SAFARI","uiReadyState","remove","authPhoneNumber","shouldSkipHistoryAnimations","replaceThemeSettings","FOREVER_BANNED_DATE","entityId","isChatGroup","isChatBasicGroup","isChatSuperGroup","isChatChannel","isCommonBoxChat","isChatWithRepliesBot","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","allListIds","folder","excludedChatIds","includedChatIds","pinnedChatIds","active","archived","isListed","unreadMentionsCount","excludeArchived","excludeRead","unreadCount","hasUnreadMark","excludeMuted","userType","isContact","bots","contacts","nonContacts","channels","groups","filterChatFolder","prepareChatList","listIds","orderedPinnedIds","folderType","noOrder","listIdsSet","orderedPinnedIdsSet","pinnedChats","checkChat","otherChats","reduceChatList","chatArrays","filteredIds","filteredIdsSet","getFolderUnreadDialogs","hasActiveDialogs","unreadDialogsCount","isUnread","getFolderDescriptionText","emoticon","description","pinnedIds","getFolderChatsCount","getMessageSenderName","getUserFirstOrLastName","sortChatIds","chatIds","shouldPrioritizeVerified","priorityIds","priority","isVerified","filterChatsByName","query","searchWords","prepareSearchWordsForNeedle","CONTENT_NOT_SUPPORTED","getMessageKey","msgId","buildMessageKey","parseMessageKey","getMessageOriginalId","previousLocalId","noEmoji","audio","voice","contact","poll","truncatedText","substr","groupedId","performer","getMessageAudioCaption","summary","question","getMessageText","webPage","getMessageCustomShape","isRound","parseEmojiOnlyString","getMessageSingleEmoji","getFirstLinkInMessage","link","find","offset","isOwnMessage","isOutgoing","isReplyMessage","replyToMessageId","isForwardedMessage","forwardInfo","isActionMessage","isServiceNotificationMessage","isAnonymousOwnMessage","senderId","getSenderTitle","getSendingState","sendingState","isMessageLocal","isHistoryClearMessage","getMessageContentFilename","isAnimated","isWebpSupported","baseFilename","IS_OPUS_SUPPORTED","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","mediaId","hasMessageLocalBlobUrl","getVideoOrAudioBaseHash","getAudioHasCover","IS_PROGRESSIVE_SUPPORTED","thumbnailSizes","getMessageMediaFormat","fullVideo","getMessageFileName","getMessageFileSize","blobUrl","getChatMediaMessageIds","messages","listedIds","isFromSharedMedia","getMessageContentIds","reverse","getPhotoFullDimensions","sizes","getPhotoInlineDimensions","getVideoDimensions","width","height","getMediaTransferState","isLoadNeeded","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","userStatus","wasOnline","getTime","wasOnlineDate","diff","today","setHours","yesterday","setDate","getDate","formatFullDate","isUserOnline","noStatus","isUserBot","getCanAddContact","sortUserIds","userIds","userStatusesById","getServerTime","expires","filterUsersByName","getUserIdDividend","abs","getUserColorKey","peer","replaceChatListIds","newIds","updateChatListIds","idsUpdate","replaceChats","newById","updateChat","chatUpdate","updatedChat","getUpdatedChat","updatedById","addChats","isUpdated","addedById","isMin","shouldOmitMinInfo","omit","photos","updateChatListType","listType","currentListIds","listTypeKey","currentFolderList","updateChatListSecondaryInfo","info","totalCountKey","totalChatCount","isFullyLoaded","leaveChat","leftChatId","selectChatListType","listId","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","currentIds","updateThreadInfo","newThreadInfo","updateThreadInfos","updates","scheduledMessages","updateScheduledMessages","updateFocusedMessage","noHighlight","isResizingContainer","focusedMessage","updateSponsoredMessage","sponsoredByChatId","updateFocusDirection","direction","enterMessageSelectMode","selectedMessages","prototype","toggleMessageSelection","messageListType","childMessageIds","withShift","oldSelectedMessages","selectMessageIdsByGroupId","selectedMessageIds","newMessageIds","newSelectedMessageIds","selectCurrentMessageIds","prevIndex","min","to","unique","exitMessageSelectMode","updateThreadUnreadFromForwardedMessage","originMessage","lastMessageId","isDeleting","channelPostId","threadInfoOld","updateStickerSets","category","sets","resultIds","updatedSets","stickerSet","stickers","setsById","setIds","updateStickerSet","stickerSetId","currentStickerSet","updateGifSearch","isNew","results","nextOffset","currentResults","gifs","newResults","gif","replaceAnimatedEmojis","animatedEmojis","updateStickersForEmoji","remoteStickers","allStickers","selectStickersForEmoji","uniqueIds","forEmoji","rebuildStickersForEmoji","replaceUsers","updateContactList","updatedUsers","contactUserIds","contactList","newContactUserIds","userUpdate","updatedUser","getUpdatedUser","updateUsers","updateSelectedUserId","selectedId","deleteUser","MEMO_EMPTY_ARRAY","updateUserSearch","searchStatePartial","userSearch","updateUserSearchFetchingStatus","newState","fetchingStatus","updateUserBlockedState","isBlocked","replaceUserStatuses","statusesById","addUserStatuses","pick","getComplexKey","updateGlobalSearch","globalSearch","updateGlobalSearchContent","currentContent","updateGlobalSearchResults","newFoundMessages","nextRate","resultsByType","newFoundMessagesById","foundIdsForType","foundIds","updateGlobalSearchFetchingStatus","prevFoundIds","newFoundIds","foundOrPrevFoundIds","nextOffsetId","replaceLocalTextSearch","chatThreadKey","searchParams","localTextSearch","byChatThreadKey","updateLocalTextSearch","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","photoUrl","invoiceContent","setStripeCardInfo","cardInfo","stripeCredentials","setPaymentForm","form","setReceipt","receipt","messageInvoice","clearPayment","closeInvoice","isPaymentModalOpen","selectChat","selectChatUser","selectIsChatWithSelf","selectIsChatWithBot","selectSupportChat","isSupport","selectChatOnlineCount","members","onlineCount","selectChatBot","selectIsChatBotNotStarted","bot","messageInfo","selectAreActiveChatsLoaded","selectIsChatListed","targetList","list","selectChatFolder","chatFolders","selectIsChatPinned","chatFoldersById","selectChatByUsername","usernameLowered","selectCountNotMutedUnread","activeChatIds","selectNotifyExceptions","selectIsServiceChatReady","selectSendAs","sendAsId","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","chatMessages","selectScheduledMessage","selectEditingMessage","selectChatMessageByPollId","pollId","messageWithPoll","selectFocusedMessageId","focusedChatId","selectIsMessageFocused","focusedId","selectOutgoingStatus","isScheduledList","lastReadOutboxMessageId","selectIsMessageUnread","selectSender","selectForwardedSender","isChannelPost","senderUserId","selectAllowedMessageActions","isPrivate","isChatWithSelf","isBasicGroup","isSuperGroup","isChannel","isLocal","isServiceNotification","isOwn","isAction","isMessageEditable","viaBotId","canReply","hasPinPermission","canPin","canUnpin","pinnedMessageIds","canDelete","canReport","canDeleteForAll","canEdit","canForward","hasSticker","hasFavoriteSticker","favorite","selectIsStickerFavorite","canFaveSticker","canUnfaveSticker","canCopy","canCopyLink","canSelect","canDownload","noOptions","ability","selectCanDeleteSelectedMessages","messageActions","selectCanReportSelectedMessages","selectCanDownloadSelectedMessages","selectIsDownloading","activeInChat","activeDownloads","selectActiveDownloadIds","selectUploadProgress","fileUploads","byMessageLocalId","selectRealLastReadId","lastReadInboxMessageId","Infinity","selectFirstUnreadId","lastReadId","lastReadServiceNotificationId","serviceNotifications","notification","findAfterLastReadId","isFromScheduled","found","selectIsForwardModalOpen","forwardMessages","isModalShown","selectCommonBoxChatId","fromLastMessage","selectIsInSelectMode","selectIsMessageSelected","selectForwardedMessageIdsByGroupId","selectIsDocumentGroupSelected","selectedIds","groupIds","selectSelectedMessagesCount","selectNewestMessageWithBotKeyboardButtons","findLast","keyboardButtons","replyHideMessageId","shouldHideKeyboardButtons","selectCanAutoLoadMedia","isPhoto","isVideo","isFile","canAutoLoadPhotoFromContacts","canAutoLoadPhotoInPrivateChats","canAutoLoadPhotoInGroups","canAutoLoadPhotoInChannels","canAutoLoadVideoFromContacts","canAutoLoadVideoInPrivateChats","canAutoLoadVideoInGroups","canAutoLoadVideoInChannels","canAutoLoadFileFromContacts","canAutoLoadFileInPrivateChats","canAutoLoadFileInGroups","canAutoLoadFileInChannels","canAutoLoadMedia","canAutoLoadMediaFromContacts","canAutoLoadMediaInPrivateChats","canAutoLoadMediaInGroups","canAutoLoadMediaInChannels","isMediaFromContact","selectIsUserOrChatContact","selectCanAutoPlayMedia","canAutoPlayVideos","canAutoPlayGifs","asGif","selectShouldLoopStickers","shouldLoopStickers","selectLastServiceNotification","maxId","selectIsMessageProtected","isProtected","selectSponsoredMessage","expiresAt","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","selectUserStatus","selectIsUserBlocked","LoadMoreDirection","FocusDirection","SettingsScreens","LeftColumnContent","GlobalSearchContent","MediaViewerOrigin","AudioOrigin","ChatCreationProgress","ManagementProgress","ProfileState","PaymentStep","ManagementScreens","currentInstance","animateSingle","tick","instance","isCancelled","animate","timingFunctions","linear","easeIn","easeOut","easeInOut","sin","PI","easeInQuad","easeOutQuad","easeInOutQuad","easeInCubic","easeOutCubic","easeInOutCubic","easeInQuart","easeOutQuart","easeInOutQuart","easeInQuint","easeOutQuint","easeInOutQuint","animateNumber","timing","t0","canceled","f","setAppBadge","currentProps","newProps","currentKeysLength","prop","self","caches","Type","fetch","cacheName","isHtmlAllowed","request","Request","cache","open","headers","Blob","blob","shouldRecreate","resolvedType","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","hours","getHours","marker","padStart","getMinutes","formatPastTimeShort","weekAgo","getDay","withYear","format","formatDate","formatMonthAndYear","isShort","formatHumanDate","noWeekdays","isUpperFirst","upperFirst","lowerFirst","weekAhead","weekDay","day","monthIndex","formatMediaDateTime","formatMediaDuration","maxValue","minutes","seconds","maxHours","maxMinutes","string","formatVoiceRecordDuration","durationInMs","milliseconds","locale","toLocaleString","year","formatDateTimeToString","hour","minute","second","isValidDate","MAX_MONTH_IN_YEAR","parseDateString","matchStringDate","matchEuropeStringDate","matchNumberDate","dateParts","timestampPlusDay","MILLISECONDS_IN_DAY","str","EXCLUDE_EMOJIS","EMOJI_EXCEPTIONS","unifiedToNative","unified","codePoints","parseInt","fromCodePoint","regex","replacement","pairs","uncompressEmoji","emojiData","categories","emojiRaw","names","native","image","isoToEmoji","iso","test","c","codePointAt","isWebpSupportedCache","webp","Image","handleLoadOrError","onload","onerror","hasWebp","systemThemeCache","matches","os","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","IS_REQUEST_FULLSCREEN_SUPPORTED","ARE_CALLS_SUPPORTED","LAYERS_ANIMATION_NAME","TEST_VIDEO","DPR","devicePixelRatio","MASK_IMAGE_DISABLED","IS_SCROLL_PATCH_NEEDED","MESSAGE_LIST_SENSITIVE_AREA","dataUriToBlob","arr","mime","bstr","atob","u8arr","Uint8Array","blobToDataUri","reader","FileReader","readAsDataURL","blobToFile","File","lastModified","preloadImage","img","preloadVideo","volume","onloadedmetadata","createPosterForVideo","onseeked","videoWidth","videoHeight","canvas","drawImage","toDataURL","currentTime","fetchBlob","fetchFile","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","MESSAGE_TOO_LONG","SERVICE_WORKER_DISABLED","MESSAGE_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","orderRule","mode","compareValues","currentOrderRule","isAsc","aValue","bValue","mode1","mode2","orderRule1","orderRule2","isAsc1","isAsc2","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","currentTimeFormat","getTranslation","cacheValue","cached","langString","processTranslation","importFallbackLangPack","getTranslationForLangString","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","progressCallbacks","cancellableCallbacks","mediaFormat","onProgress","callbackUniqueId","progressiveUrl","getProgressive","mediaPng","webpToPng","prepared","prepareMedia","mediaSource","MediaSource","streamUrl","sourceBuffer","addSourceBuffer","makeOnProgress","revokeObjectURL","fetchFromCacheOrRemote","activeCallbacks","getFromMemory","cancelProgress","parentCallback","endOfStream","appendBuffer","mediaData","serviceWorker","fullSize","controller","Bundles","LOAD_PROMISES","MEMORY_CACHE","Auth","Main","Extra","Calls","handleBundleLoad","bundle","listeners","listener","getDeviceToken","subscription","toJSON","endpoint","checkIfPushSupported","ServiceWorkerRegistration","Notification","permission","soundPlayedIds","playNotifySound","notificationSoundVolume","currentVolume","once","play","playNotifySoundDebounced","requestPermission","unsubscribeFromPush","dispatch","deleteDeviceToken","serviceWorkerRegistration","ready","pushManager","getSubscription","areSettingsLoaded","checkIfShouldResubscribe","userVisibleOnly","setDeviceToken","DOMException","ABORT_ERR","notifyAboutNewMessage","resultSettings","resultExceptions","loadNotificationSettings","hasFocus","checkIfShouldNotify","areNotificationsSupported","messageSender","messageAction","actionTargetMessage","targetUserIds","actionTargetUserIds","actionTargetChatId","actionTargetUsers","privateChatUserId","privateChatUser","senderName","getNotificationContent","imageHash","mediaLoader","getAvatar","badge","vibrate","onclick","close","onshow","closeMessageNotifications","notifyClientReady","PATTERN_PLACEHOLDER","DEFAULT_PATTERN","getCountryCodesByIso","phoneCodeList","country","iso2","getCountryFromPhoneNumber","possibleCountries","countryCode","bestMatches","prefixes","prefix","formatPhoneNumber","pattern","numberWithoutCode","patterns","defaultPattern","stripped","getBestPattern","formatPhoneNumberWithCode","numberWithPlus","createMessageHash","messageList","parseLocationHash","typeOrThreadId","isType","fn","shouldRunFirst","shouldRunLast","waitingTimeout","interval","isPending","_args","setInterval","clearInterval","throttleWith","waiting","onIdle","requestIdleCallback","rafPromise","fastRafCallbacks","fastRafPrimaryCallbacks","onTickEndCallbacks","onTickEndPrimaryCallbacks","beforeUnloadCallbacks","isPrimary","currentCallbacks","currentPrimaryCallbacks","onBeforeUnload","isLast","unshift","RE_NOT_LETTER","haystack","needle","needleWords","haystackLower","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","RGB_VARIABLES","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","count","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","visualViewport","pageTop","vh","getIsKeyboardVisible","disableRefresh","enableRefresh","__webpack_module_cache__","__webpack_require__","moduleId","cachedModule","exports","__webpack_modules__","m","getter","__esModule","getPrototypeOf","obj","ns","create","def","getOwnPropertyNames","definition","o","defineProperty","enumerable","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","hasErrorKey","INITIAL_STATE","isLeftColumnShown","phoneCodes","general","groupCalls","activeChatFolder","recentEmojis","added","recent","greeting","featured","emojiKeywords","saved","inlineBots","byUsername","topPeers","topInlineBots","audioPlayer","playbackRate","notifications","dialogs","messageSendKeyCombo","autoLoadFileMaxSizeMb","shouldSuggestStickers","light","isBlurred","patternColor","dark","shouldShowContextMenuHint","updateCacheThrottled","updateCache","unsubscribeFromBeforeUnload","isCaching","setupCaching","clearCaching","reducedGlobal","reduceShowChatInfo","reduceUsers","reduceChats","reduceMessages","recentlyFoundChatIds","reduceSettings","reduceChatFolders","reduceGroupCalls","idsToSave","newListIds","mainThread","activeGroupCallId","isGroupCallPanelHidden","isFallbackConfirmOpen","initialState","time","timeEnd","shouldAutoDownloadMediaFromContacts","shouldAutoDownloadMediaInPrivateChats","shouldAutoDownloadMediaInGroups","shouldAutoDownloadMediaInChannels","shouldAutoPlayVideos","shouldAutoPlayGifs","migrateCache","parsedMessageList","readCache","loadCache","STORAGE_KEY","tabKey","SITE_FONTS","preloadFonts","font","fonts","load","preloadAvatars","preloadTasks","main","telegramLogoPath","authCode","monkeyPath","authPassword","background","backgroundColor","hasCustomBackground","hasCustomBackgroundColor","isRightColumnShown","leftColumnWidth","setIsUiReady","isReady","markReady","useFlag","shouldRenderMask","safePreload","translation","setTranslation","getSuggestedLanguage","suggestedLanguage","MENU_HIDING_DURATION","inputRef","setFilter","filteredList","setFilteredList","updateFilter","filterValue","defaultName","getFilteredList","prevPhoneCodeList","handleInput","handleInputKeyDown","DropdownMenu","handleTrigger","select","formEl","getElementById","scrollTo","top","scrollHeight","behavior","inputValue","Spinner","MenuItem","isPreloadInitiated","setAuthPhoneNumber","setAuthRememberMe","loadNearestCountry","loadCountryList","clearAuthError","goToAuthQrCode","continueText","useLangString","setCountry","setPhoneNumber","isTouched","setIsTouched","lastSelection","setLastSelection","markIsLoading","unmarkIsLoading","fullNumber","canSubmit","parseFullNumber","newFullNumber","suggestedCountry","selectedCountry","handleLangChange","setSelectionRange","isJustPastedRef","handlePaste","handleCountryChange","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":""} |