mirror of
https://github.com/danog/telegram-tt.git
synced 2025-01-21 21:01:29 +01:00
1 line
812 KiB
Plaintext
1 line
812 KiB
Plaintext
{"version":3,"file":"main.5d541361716aa3cbce72.js","mappings":"uBACIA,EADAC,ECAAC,EACAC,ECwCAC,EASAC,E,wFC/BJ,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,mBAsEhC,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,KAA2B,OACzC,MAAM,IAAIW,MAAJ,UAAUZ,EAAKM,aAAf,aAAU,EAAYO,aArF9BC,CAAkBtB,GAEW,QAAzBC,EAAYsB,UAiIlBC,OAAOjB,iBAAiB,SAAS,KAC1BkB,IAELC,YAAW,IAAMD,KAAoB,SA/HhCE,EAAY,CACjBlB,KAAM,UACNmB,KAAM,CAAC3B,KAIJ,SAAS4B,EAAiCC,KAAcF,GAC7D,IAAKjC,EAMH,YALIO,EAAAA,IAEFC,QAAQ4B,KAAK,2BAMjB,MAAMC,EAAUL,EAAY,CAC1BlB,KAAM,aACNwB,KAAMH,EACNF,KAAAA,IA0BF,OAtBI1B,EAAAA,IACF,WACE,UASyB8B,EAKvB,MAAOE,MAfX,GAqBKF,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AAU,WACb,mBAAC4nF,GAAA,EAAD,CAAQx2E,QAAM,EAACK,QAAM,EAAClQ,QAfT,KACnBrH,OAAOgC,SAASC,WAcV,iBCqCV,SAASmvF,KACP,OACE,mBAAC,EAAD,CAAU1iB,KAAK,OAAOn/C,IAAI,QACxB,mBAAC,GAAD,OAKN,UAAerZ,EAAAA,EAAAA,KACZC,IAAuB+kC,EAAAA,EAAAA,IAAK/kC,EAAQ,CAAC,eADxC,EAhD4B,EAAGoqB,UAAAA,MAC7B,MAAM,WAAE8wD,IAAelrF,EAAAA,EAAAA,OAEhBsrD,EAAY6/B,IAAgBhkF,EAAAA,EAAAA,IAAQ,GAc3C,IAZAG,EAAAA,EAAAA,KAAU,MACR+xE,EAAAA,EAAAA,KfTF9/E,EeU6B,KACzB2xF,IACAxpF,SAASX,MAAS,GAAEqW,EAAAA,KAAaC,EAAAA,KAEjC8zE,OAED,CAACD,EAAYC,IAIZ7/B,EACF,OAAO,mBAAC,GAAD,MAGT,GAAIlxB,EACF,OAAQA,GACN,IAAK,oCACL,IAAK,6BACL,IAAK,iCACL,IAAK,qCACL,IAAK,+BACH,OAAO,mBAAC,GAAD,MACT,IAAK,2BACL,IAAK,4BACL,IAAK,+BACL,IAAK,0BACH,OAAO6wD,KAIb,OAAOxW,EAAAA,EAAAA,KAAiB,GAAQwW,KAAe,mBAAC,GAAD,SC3C7C1yF,EAAAA,IAEFC,QAAQC,IAAI,aAGduH,EAAAA,EAAAA,MAAck0B,OAEV37B,EAAAA,IAEFC,QAAQC,IAAI,4BAGd2yF,EAAAA,EAAAA,OACE,mBAAC,GAAD,MACA1pF,SAASgjF,eAAe,SAGtBnsF,EAAAA,IAEFC,QAAQC,IAAI,6BAGdiJ,SAAS9I,iBAAiB,YAAY,KAEpCJ,QAAQ4B,KAAK,gBAAgBu3B,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/spoiler/Spoiler.tsx","webpack://telegram-t/./src/components/common/helpers/renderMessageText.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/messageSummary.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/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/reducers/messages.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/callbacks.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/oggToWav.ts","webpack://telegram-t/./src/util/mediaLoader.ts","webpack://telegram-t/./src/util/memo.ts","webpack://telegram-t/./src/util/memoized.ts","webpack://telegram-t/./src/util/moduleLoader.ts","webpack://telegram-t/./src/util/notifications.ts","webpack://telegram-t/./src/util/permanentWebVersion.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 = {\"126\":1,\"133\":1,\"409\":1,\"472\":1,\"532\":1,\"913\":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 { Api } from '../../../lib/gramjs';\nimport { ApiInitialArgs, ApiOnProgress, OnApiUpdate } from '../../types';\nimport { Methods, MethodArgs, MethodResponse } from '../methods/types';\nimport { WorkerMessageEvent, 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 const promise = makeRequest({\n type: 'callMethod',\n name: fnName,\n args,\n });\n\n // Some TypeScript magic to make sure `VirtualClass` is never returned from any method\n if (DEBUG) {\n (async () => {\n try {\n type ForbiddenTypes =\n Api.VirtualClass<any>\n | (Api.VirtualClass<any> | undefined)[];\n type ForbiddenResponses =\n ForbiddenTypes\n | (AnyLiteral & { [k: string]: ForbiddenTypes });\n\n // Unwrap all chained promises\n const response = await promise;\n // Make sure responses do not include `VirtualClass` instances\n const allowedResponse: Exclude<typeof response, ForbiddenResponses> = response;\n // Suppress \"unused variable\" constraint\n void allowedResponse;\n } catch (err) {\n // Do noting\n }\n })();\n }\n\n return promise 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 new Error(data.error?.message);\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<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\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', () => {\n void ensureWorkerPing();\n // Sometimes a single check is not enough\n setTimeout(() => ensureWorkerPing(), 1000);\n });\n}\n\nasync function ensureWorkerPing() {\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","// 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 | ArrayBuffer;\nexport type ApiPreparedMedia = 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 Spoiler = 'MessageEntitySpoiler',\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 reactors?: {\n nextOffset?: string;\n count: number;\n reactions: ApiUserReaction[];\n };\n reactions?: ApiReactions;\n}\n\nexport interface ApiReactions {\n canSeeList?: boolean;\n results: ApiReactionCount[];\n recentReactions?: ApiUserReaction[];\n}\n\nexport interface ApiUserReaction {\n userId: string;\n reaction: string;\n}\n\nexport interface ApiReactionCount {\n isChosen?: boolean;\n count: number;\n reaction: string;\n}\n\nexport interface ApiAvailableReaction {\n selectAnimation?: ApiDocument;\n staticIcon?: ApiDocument;\n centerIcon?: ApiDocument;\n aroundAnimation?: ApiDocument;\n reaction: string;\n title: string;\n isInactive?: 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' | 'requestSelfContact' | '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, getMessageSummaryText,\n getUserFullName,\n} from '../../../modules/helpers';\nimport trimText from '../../../util/trimText';\nimport { formatCurrency } from '../../../util/formatCurrency';\nimport { renderMessageSummary, 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 actionOriginUser?: ApiUser,\n actionOriginChat?: 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 actionOriginUser ? (\n (!options.isEmbedded && renderUserContent(actionOriginUser, options.asPlain)) || NBSP\n\n ) : actionOriginChat ? (\n (!options.isEmbedded && renderChatContent(lang, actionOriginChat, 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 { maxTextLength, isEmbedded, asPlain } = options;\n\n const text = asPlain\n ? [trimText(getMessageSummaryText(lang, message), maxTextLength)]\n : renderMessageSummary(lang, message, undefined, undefined, maxTextLength, true);\n const {\n photo, video, document, sticker,\n } = getMessageContent(message);\n\n const showQuotes = isEmbedded && text && !photo && !video && !document && !sticker;\n let messageText = text;\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 && messageText) {\n return (showQuotes ? ['«', ...messageText, '»'] : messageText).join('');\n }\n\n if (showQuotes) {\n return (\n <span>\n «\n <MessageLink className=\"action-link\" message={message}>{messageText}</MessageLink>\n »\n </span>\n );\n }\n\n return (\n <MessageLink className=\"action-link\" message={message}>{messageText}</MessageLink>\n );\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 { MouseEvent as ReactMouseEvent } from 'react';\nimport React, {\n FC, memo, useCallback, useEffect,\n} from '../../../lib/teact/teact';\n\nimport { createClassNameBuilder } from '../../../util/buildClassName';\nimport useFlag from '../../../hooks/useFlag';\n\nimport './Spoiler.scss';\n\ntype OwnProps = {\n children?: React.ReactNode;\n messageId?: number;\n};\n\nconst AUTO_HIDE_TIMEOUT = 5000; // 5s\n\nconst actionsByMessageId: Map<number, {\n reveal: VoidFunction;\n conceal: VoidFunction;\n}[]> = new Map();\n\nconst buildClassName = createClassNameBuilder('Spoiler');\n\nconst Spoiler: FC<OwnProps> = ({\n children,\n messageId,\n}) => {\n const [isRevealed, reveal, conceal] = useFlag();\n\n const handleClick = useCallback((e: ReactMouseEvent<HTMLDivElement, MouseEvent>) => {\n e.preventDefault();\n e.stopPropagation();\n\n actionsByMessageId.get(messageId!)?.forEach((actions) => actions.reveal());\n\n setTimeout(() => {\n actionsByMessageId.get(messageId!)?.forEach((actions) => actions.conceal());\n conceal();\n }, AUTO_HIDE_TIMEOUT);\n }, [conceal, messageId]);\n\n useEffect(() => {\n if (!messageId) {\n return undefined;\n }\n\n if (actionsByMessageId.has(messageId)) {\n actionsByMessageId.get(messageId)!.push({ reveal, conceal });\n } else {\n actionsByMessageId.set(messageId, [{ reveal, conceal }]);\n }\n\n return () => {\n actionsByMessageId.delete(messageId);\n };\n }, [conceal, handleClick, isRevealed, messageId, reveal]);\n\n return (\n <span\n className={buildClassName(\n '&',\n !isRevealed && 'concealed',\n !isRevealed && Boolean(messageId) && 'animated',\n )}\n onClick={messageId && !isRevealed ? handleClick : undefined}\n >\n <span className={buildClassName('content')}>\n {children}\n </span>\n </span>\n );\n};\n\nexport default memo(Spoiler);\n","import { MouseEvent } from 'react';\nimport React from '../../../lib/teact/teact';\nimport { getDispatch } from '../../../lib/teact/teactn';\n\nimport { ApiMessageEntity, ApiMessageEntityTypes, ApiMessage } from '../../../api/types';\n\nimport {\n getMessageSummaryText,\n getMessageSummaryDescription,\n getMessageSummaryEmoji,\n getMessageText,\n TRUNCATED_SUMMARY_LENGTH,\n} from '../../../modules/helpers';\nimport renderText, { TextFilter } from './renderText';\n\nimport MentionLink from '../../middle/message/MentionLink';\nimport SafeLink from '../SafeLink';\nimport Spoiler from '../spoiler/Spoiler';\nimport { LangFn } from '../../../hooks/useLang';\n\nexport type TextPart =\n string\n | Element;\n\nexport function renderMessageSummary(\n lang: LangFn,\n message: ApiMessage,\n noEmoji = false,\n highlight?: string,\n truncateLength = TRUNCATED_SUMMARY_LENGTH,\n shouldAddEllipsis?: boolean,\n): TextPart[] {\n const hasSpoilers = message.content.text?.entities?.some((l) => l.type === ApiMessageEntityTypes.Spoiler);\n if (!hasSpoilers) {\n let text = getMessageSummaryText(lang, message, noEmoji, truncateLength);\n if (shouldAddEllipsis) {\n text += '...';\n }\n\n if (highlight) {\n return renderText(text, ['emoji', 'highlight'], {\n highlight,\n });\n } else {\n return renderText(text);\n }\n }\n\n const text = renderMessageText(message, highlight, undefined, true, truncateLength);\n const emoji = !noEmoji && getMessageSummaryEmoji(message);\n const emojiWithSpace = emoji ? `${emoji} ` : '';\n const description = getMessageSummaryDescription(lang, message, text);\n return [\n emojiWithSpace,\n ...(Array.isArray(description) ? description : [description]),\n shouldAddEllipsis && '...',\n ].filter(Boolean);\n}\n\nexport function renderMessageText(\n message: ApiMessage,\n highlight?: string,\n shouldRenderHqEmoji?: boolean,\n isSimple?: boolean,\n truncateLength?: number,\n) {\n const formattedText = message.content.text;\n\n if (!formattedText || !formattedText.text) {\n const rawText = getMessageText(message);\n return rawText ? [rawText] : undefined;\n }\n const { text, entities } = formattedText;\n\n return renderTextWithEntities(\n truncateLength ? text.substr(0, truncateLength) : text,\n entities,\n highlight,\n shouldRenderHqEmoji,\n undefined,\n message.id,\n isSimple,\n );\n}\n\ninterface IOrganizedEntity {\n entity: ApiMessageEntity;\n organizedIndexes: Set<number>;\n nestedEntities: IOrganizedEntity[];\n}\n\nfunction organizeEntity(\n entity: ApiMessageEntity,\n index: number,\n entities: ApiMessageEntity[],\n organizedEntityIndexes: Set<number>,\n): IOrganizedEntity | undefined {\n const { offset, length } = entity;\n const organizedIndexes = new Set([index]);\n\n if (organizedEntityIndexes.has(index)) {\n return undefined;\n }\n\n // Determine any nested entities inside current entity\n const nestedEntities: IOrganizedEntity[] = [];\n const parsedNestedEntities = entities\n .filter((e, i) => i > index && e.offset >= offset && e.offset < offset + length)\n .map((e) => organizeEntity(e, entities.indexOf(e), entities, organizedEntityIndexes))\n .filter<IOrganizedEntity>(Boolean as any);\n\n parsedNestedEntities.forEach((parsedEntity) => {\n let isChanged = false;\n\n parsedEntity.organizedIndexes.forEach((organizedIndex) => {\n if (!isChanged && !organizedIndexes.has(organizedIndex)) {\n isChanged = true;\n }\n\n organizedIndexes.add(organizedIndex);\n });\n\n if (isChanged) {\n nestedEntities.push(parsedEntity);\n }\n });\n\n return {\n entity,\n organizedIndexes,\n nestedEntities,\n };\n}\n\n// Organize entities in a tree-like structure to better represent how the text will be displayed\nfunction organizeEntities(entities: ApiMessageEntity[]) {\n const organizedEntityIndexes: Set<number> = new Set();\n const organizedEntities: IOrganizedEntity[] = [];\n\n entities.forEach((entity, index) => {\n if (organizedEntityIndexes.has(index)) {\n return;\n }\n\n const organizedEntity = organizeEntity(entity, index, entities, organizedEntityIndexes);\n if (organizedEntity) {\n organizedEntity.organizedIndexes.forEach((organizedIndex) => {\n organizedEntityIndexes.add(organizedIndex);\n });\n\n organizedEntities.push(organizedEntity);\n }\n });\n\n return organizedEntities;\n}\n\nexport function renderTextWithEntities(\n text: string,\n entities?: ApiMessageEntity[],\n highlight?: string,\n shouldRenderHqEmoji?: boolean,\n shouldRenderAsHtml?: boolean,\n messageId?: number,\n isSimple?: boolean,\n) {\n if (!entities || !entities.length) {\n return renderMessagePart(text, highlight, shouldRenderHqEmoji, shouldRenderAsHtml, isSimple);\n }\n\n const result: TextPart[] = [];\n let deleteLineBreakAfterPre = false;\n\n const organizedEntities = organizeEntities(entities);\n\n // Recursive function to render regular and nested entities\n function renderEntity(\n textPartStart: number,\n textPartEnd: number,\n organizedEntity: IOrganizedEntity,\n isLastEntity: boolean,\n ) {\n const renderResult: TextPart[] = [];\n const { entity, nestedEntities } = organizedEntity;\n const { offset, length, type } = entity;\n\n // Render text before the entity\n let textBefore = text.substring(textPartStart, offset);\n const textBeforeLength = textBefore.length;\n if (textBefore) {\n if (deleteLineBreakAfterPre && textBefore.length > 0 && textBefore[0] === '\\n') {\n textBefore = textBefore.substr(1);\n deleteLineBreakAfterPre = false;\n }\n if (textBefore) {\n renderResult.push(...renderMessagePart(\n textBefore, highlight, shouldRenderHqEmoji, shouldRenderAsHtml, isSimple,\n ) as TextPart[]);\n }\n }\n\n const entityStartIndex = textPartStart + textBeforeLength;\n const entityEndIndex = entityStartIndex + length;\n\n let entityContent: TextPart = text.substring(offset, offset + length);\n const nestedEntityContent: TextPart[] = [];\n\n if (deleteLineBreakAfterPre && entityContent.length > 0 && entityContent[0] === '\\n') {\n entityContent = entityContent.substr(1);\n deleteLineBreakAfterPre = false;\n }\n\n if (type === ApiMessageEntityTypes.Pre) {\n deleteLineBreakAfterPre = true;\n }\n\n // Render nested entities, if any\n if (nestedEntities.length) {\n let nestedIndex = entityStartIndex;\n\n nestedEntities.forEach((nestedEntity, nestedEntityIndex) => {\n const {\n renderResult: nestedResult,\n entityEndIndex: nestedEntityEndIndex,\n } = renderEntity(\n nestedIndex,\n entityEndIndex,\n nestedEntity,\n nestedEntityIndex === nestedEntities.length - 1,\n );\n\n nestedEntityContent.push(...nestedResult);\n nestedIndex = nestedEntityEndIndex;\n });\n }\n\n // Render the entity itself\n const newEntity = shouldRenderAsHtml\n ? processEntityAsHtml(entity, entityContent, nestedEntityContent)\n : processEntity(entity, entityContent, nestedEntityContent, highlight, messageId, isSimple);\n\n if (Array.isArray(newEntity)) {\n renderResult.push(...newEntity);\n } else {\n renderResult.push(newEntity);\n }\n\n // Render text after the entity, if it is the last entity in the text,\n // or the last nested entity inside of another entity\n if (isLastEntity && entityEndIndex < textPartEnd) {\n let textAfter = text.substring(entityEndIndex, textPartEnd);\n if (deleteLineBreakAfterPre && textAfter.length > 0 && textAfter[0] === '\\n') {\n textAfter = textAfter.substring(1);\n }\n if (textAfter) {\n renderResult.push(...renderMessagePart(\n textAfter, highlight, shouldRenderHqEmoji, shouldRenderAsHtml, isSimple,\n ) as TextPart[]);\n }\n }\n\n return {\n renderResult,\n entityEndIndex,\n };\n }\n\n // Process highest-level entities\n let index = 0;\n\n organizedEntities.forEach((entity, arrayIndex) => {\n const { renderResult, entityEndIndex } = renderEntity(\n index,\n text.length,\n entity,\n arrayIndex === organizedEntities.length - 1,\n );\n\n result.push(...renderResult);\n index = entityEndIndex;\n });\n\n return result;\n}\n\nfunction processEntity(\n entity: ApiMessageEntity,\n entityContent: TextPart,\n nestedEntityContent: TextPart[],\n highlight?: string,\n messageId?: number,\n isSimple?: boolean,\n) {\n const entityText = typeof entityContent === 'string' && entityContent;\n const renderedContent = nestedEntityContent.length ? nestedEntityContent : entityContent;\n\n function renderNestedMessagePart() {\n return renderMessagePart(\n renderedContent, highlight, undefined, undefined, isSimple,\n );\n }\n\n if (!entityText) {\n return renderNestedMessagePart();\n }\n\n if (isSimple) {\n const text = renderNestedMessagePart();\n if (entity.type === ApiMessageEntityTypes.Spoiler) {\n return <Spoiler>{text}</Spoiler>;\n }\n return text;\n }\n\n switch (entity.type) {\n case ApiMessageEntityTypes.Bold:\n return <strong>{renderNestedMessagePart()}</strong>;\n case ApiMessageEntityTypes.Blockquote:\n return <blockquote>{renderNestedMessagePart()}</blockquote>;\n case ApiMessageEntityTypes.BotCommand:\n return (\n <a\n onClick={handleBotCommandClick}\n className=\"text-entity-link\"\n dir=\"auto\"\n >\n {renderNestedMessagePart()}\n </a>\n );\n case ApiMessageEntityTypes.Hashtag:\n return (\n <a\n onClick={handleHashtagClick}\n className=\"text-entity-link\"\n dir=\"auto\"\n >\n {renderNestedMessagePart()}\n </a>\n );\n case ApiMessageEntityTypes.Cashtag:\n return (\n <a\n onClick={handleHashtagClick}\n className=\"text-entity-link\"\n dir=\"auto\"\n >\n {renderNestedMessagePart()}\n </a>\n );\n case ApiMessageEntityTypes.Code:\n return <code className=\"text-entity-code\">{renderNestedMessagePart()}</code>;\n case ApiMessageEntityTypes.Email:\n return (\n <a\n href={`mailto:${entityText}`}\n target=\"_blank\"\n rel=\"noopener noreferrer\"\n className=\"text-entity-link\"\n dir=\"auto\"\n >\n {renderNestedMessagePart()}\n </a>\n );\n case ApiMessageEntityTypes.Italic:\n return <em>{renderNestedMessagePart()}</em>;\n case ApiMessageEntityTypes.MentionName:\n return (\n <MentionLink userId={entity.userId}>\n {renderNestedMessagePart()}\n </MentionLink>\n );\n case ApiMessageEntityTypes.Mention:\n return (\n <MentionLink username={entityText}>\n {renderNestedMessagePart()}\n </MentionLink>\n );\n case ApiMessageEntityTypes.Phone:\n return (\n <a\n href={`tel:${entityText}`}\n className=\"text-entity-link\"\n dir=\"auto\"\n >\n {renderNestedMessagePart()}\n </a>\n );\n case ApiMessageEntityTypes.Pre:\n return <pre className=\"text-entity-pre\">{renderNestedMessagePart()}</pre>;\n case ApiMessageEntityTypes.Strike:\n return <del>{renderNestedMessagePart()}</del>;\n case ApiMessageEntityTypes.TextUrl:\n case ApiMessageEntityTypes.Url:\n return (\n <SafeLink\n url={getLinkUrl(entityText, entity)}\n text={entityText}\n >\n {renderNestedMessagePart()}\n </SafeLink>\n );\n case ApiMessageEntityTypes.Underline:\n return <ins>{renderNestedMessagePart()}</ins>;\n case ApiMessageEntityTypes.Spoiler:\n return <Spoiler messageId={messageId}>{renderNestedMessagePart()}</Spoiler>;\n default:\n return renderNestedMessagePart();\n }\n}\n\nfunction renderMessagePart(\n content: TextPart | TextPart[],\n highlight?: string,\n shouldRenderHqEmoji?: boolean,\n shouldRenderAsHtml?: boolean,\n isSimple?: boolean,\n) {\n if (Array.isArray(content)) {\n const result: TextPart[] = [];\n\n content.forEach((c) => {\n result.push(...renderMessagePart(c, highlight, shouldRenderHqEmoji, shouldRenderAsHtml, isSimple));\n });\n\n return result;\n }\n\n if (shouldRenderAsHtml) {\n return renderText(content, ['escape_html', 'emoji_html', 'br_html']);\n }\n\n const emojiFilter = shouldRenderHqEmoji ? 'hq_emoji' : 'emoji';\n\n const filters: TextFilter[] = [emojiFilter];\n if (!isSimple) {\n filters.push('br');\n }\n\n if (highlight) {\n return renderText(content, filters.concat('highlight'), { highlight });\n } else {\n return renderText(content, filters);\n }\n}\n\nfunction getLinkUrl(entityContent: string, entity: ApiMessageEntity) {\n const { type, url } = entity;\n return type === ApiMessageEntityTypes.TextUrl && url ? url : entityContent;\n}\n\nfunction handleBotCommandClick(e: MouseEvent<HTMLAnchorElement>) {\n getDispatch().sendBotCommand({ command: e.currentTarget.innerText });\n}\n\nfunction handleHashtagClick(e: MouseEvent<HTMLAnchorElement>) {\n getDispatch().setLocalTextSearchQuery({ query: e.currentTarget.innerText });\n getDispatch().searchTextMessagesLocal();\n}\n\nfunction processEntityAsHtml(\n entity: ApiMessageEntity,\n entityContent: TextPart,\n nestedEntityContent: TextPart[],\n) {\n const rawEntityText = typeof entityContent === 'string' && entityContent;\n\n const renderedContent = nestedEntityContent.length\n ? nestedEntityContent.join('')\n : renderText(entityContent, ['escape_html', 'emoji_html', 'br_html']).join('');\n\n if (!rawEntityText) {\n return renderedContent;\n }\n\n switch (entity.type) {\n case ApiMessageEntityTypes.Bold:\n return `<b>${renderedContent}</b>`;\n case ApiMessageEntityTypes.Italic:\n return `<i>${renderedContent}</i>`;\n case ApiMessageEntityTypes.Underline:\n return `<u>${renderedContent}</u>`;\n case ApiMessageEntityTypes.Code:\n return `<code class=\"text-entity-code\">${renderedContent}</code>`;\n case ApiMessageEntityTypes.Pre:\n return `\\`\\`\\`<br/>${renderedContent}<br/>\\`\\`\\``;\n case ApiMessageEntityTypes.Strike:\n return `<del>${renderedContent}</del>`;\n case ApiMessageEntityTypes.MentionName:\n return `<a\n class=\"text-entity-link\"\n data-entity-type=\"${ApiMessageEntityTypes.MentionName}\"\n data-user-id=\"${entity.userId}\"\n contenteditable=\"false\"\n dir=\"auto\"\n >${renderedContent}</a>`;\n case ApiMessageEntityTypes.Url:\n case ApiMessageEntityTypes.TextUrl:\n return `<a\n class=\"text-entity-link\"\n href=${getLinkUrl(rawEntityText, entity)}\n data-entity-type=\"${entity.type}\"\n dir=\"auto\"\n >${renderedContent}</a>`;\n case ApiMessageEntityTypes.Spoiler:\n return `<span\n class=\"spoiler\"\n data-entity-type=\"${ApiMessageEntityTypes.Spoiler}\"\n >${renderedContent}</span>`;\n default:\n return renderedContent;\n }\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';\nimport { compact } from '../../../util/iteratees';\n\nimport MentionLink from '../../middle/message/MentionLink';\nimport SafeLink from '../SafeLink';\n\ntype TextPart = string | Element;\nexport type TextFilter = (\n 'escape_html' | 'hq_emoji' | 'emoji' | 'emoji_html' | 'br' | 'br_html' | 'highlight' | 'links' |\n 'simple_markdown' | 'simple_markdown_html'\n);\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<TextFilter> = ['emoji'],\n params?: { highlight: string | undefined },\n): TextPart[] {\n if (typeof part !== 'string') {\n return [part];\n }\n\n return compact(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?: (\n 'primary' | 'secondary' | 'gray' | 'danger' | 'translucent' | 'translucent-white' | 'translucent-black' | 'dark'\n );\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 {\n ChangeEvent, FormEvent, RefObject,\n} 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';\nimport buildClassName from '../../util/buildClassName';\n\nimport './Loading.scss';\n\ntype OwnProps = {\n color?: 'blue' | 'white' | 'black' | 'yellow';\n backgroundColor?: 'light' | 'dark';\n onClick?: NoneToVoidFunction;\n};\n\nconst Loading: FC<OwnProps> = ({ color = 'blue', backgroundColor, onClick }) => {\n return (\n <div className={buildClassName('Loading', onClick && 'interactive')} onClick={onClick}>\n <Spinner color={color} backgroundColor={backgroundColor} />\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 bubbleStyle?: string;\n transformOriginX?: number;\n transformOriginY?: number;\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 bubbleStyle,\n children,\n transformOriginX,\n transformOriginY,\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 (isOpen || (!isOpen && prevIsOpen === true)) {\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 const transformOriginYStyle = transformOriginY !== undefined ? `${transformOriginY}px` : undefined;\n const transformOriginXStyle = transformOriginX !== undefined ? `${transformOriginX}px` : undefined;\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: ${transformOriginXStyle || positionX} ${transformOriginYStyle || positionY};${\n bubbleStyle || ''}`}\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' | 'yellow';\n backgroundColor?: 'light' | 'dark';\n}> = ({\n color = 'blue',\n backgroundColor,\n}) => {\n return (\n <div className={buildClassName('Spinner', color, backgroundColor && 'with-background', `bg-${backgroundColor}`)}>\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;\nexport const REACTION_LIST_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\nexport const CONTENT_NOT_SUPPORTED = 'The message is not supported on this version of Telegram.';\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\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 isDisabled = false,\n) => {\n useEffect(() => {\n if (isDisabled) {\n return undefined;\n }\n\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 }, [isDisabled, 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 useEffect(() => {\n if (!autoUpdate) {\n return undefined;\n }\n\n return addLoadListener(forceUpdate);\n }, [autoUpdate, forceUpdate]);\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 const exec = () => {\n setIsClosed(true);\n\n if (onCloseTransitionEnd) {\n onCloseTransitionEnd();\n }\n\n closeTimeoutRef.current = undefined;\n };\n\n if (noCloseTransition) {\n exec();\n } else {\n closeTimeoutRef.current = window.setTimeout(exec, CLOSE_DURATION);\n }\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;\ntype DelegationRegistry = Map<HTMLElement, Handler>;\n\nconst NON_BUBBLEABLE_EVENTS = new Set(['scroll', 'mouseenter', 'mouseleave']);\n\nconst documentEventCounters: Record<string, number> = {};\nconst delegationRegistryByEventType: Record<string, DelegationRegistry> = {};\nconst delegatedEventTypesByElement = new Map<HTMLElement, Set<string>>();\n\nexport function addEventListener(element: HTMLElement, propName: string, handler: Handler, asCapture = false) {\n const eventType = resolveEventType(propName, element);\n if (canUseEventDelegation(eventType, element, asCapture)) {\n addDelegatedListener(eventType, element, handler);\n } else {\n element.addEventListener(eventType, handler, asCapture);\n }\n}\n\nexport function removeEventListener(element: HTMLElement, propName: string, handler: Handler, asCapture = false) {\n const eventType = resolveEventType(propName, element);\n if (canUseEventDelegation(eventType, element, asCapture)) {\n removeDelegatedListener(eventType, element);\n } else {\n element.removeEventListener(eventType, handler, asCapture);\n }\n}\n\nfunction resolveEventType(propName: string, element: HTMLElement) {\n const eventType = propName\n .replace(/^on/, '')\n .replace(/Capture$/, '').toLowerCase();\n\n if (eventType === '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 (eventType === 'doubleclick') {\n return 'dblclick';\n }\n\n // Replace focus/blur by their \"bubbleable\" versions\n if (eventType === 'focus') {\n return 'focusin';\n }\n\n if (eventType === 'blur') {\n return 'focusout';\n }\n\n return eventType;\n}\n\nfunction canUseEventDelegation(realEventType: string, element: HTMLElement, asCapture: boolean) {\n return (\n !asCapture\n && !NON_BUBBLEABLE_EVENTS.has(realEventType)\n && element.tagName !== 'VIDEO'\n && element.tagName !== 'IFRAME'\n );\n}\n\nfunction addDelegatedListener(eventType: string, element: HTMLElement, handler: Handler) {\n if (!documentEventCounters[eventType]) {\n documentEventCounters[eventType] = 0;\n document.addEventListener(eventType, handleEvent);\n }\n\n resolveDelegationRegistry(eventType).set(element, handler);\n resolveDelegatedEventTypes(element).add(eventType);\n documentEventCounters[eventType]++;\n}\n\nfunction removeDelegatedListener(eventType: string, element: HTMLElement) {\n documentEventCounters[eventType]--;\n if (!documentEventCounters[eventType]) {\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(eventType, handleEvent);\n }\n\n delegationRegistryByEventType[eventType].delete(element);\n delegatedEventTypesByElement.get(element)!.delete(eventType);\n}\n\nexport function removeAllDelegatedListeners(element: HTMLElement) {\n const eventTypes = delegatedEventTypesByElement.get(element);\n if (!eventTypes) {\n return;\n }\n\n eventTypes.forEach((eventType) => removeDelegatedListener(eventType, element));\n delegatedEventTypesByElement.delete(element);\n}\n\nfunction handleEvent(realEvent: Event) {\n const events = delegationRegistryByEventType[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 resolveDelegationRegistry(eventType: string) {\n if (!delegationRegistryByEventType[eventType]) {\n delegationRegistryByEventType[eventType] = new Map();\n }\n\n return delegationRegistryByEventType[eventType];\n}\n\nfunction resolveDelegatedEventTypes(element: HTMLElement) {\n const existing = delegatedEventTypesByElement.get(element);\n if (existing) {\n return existing;\n }\n\n const newSet = new Set<string>();\n delegatedEventTypesByElement.set(element, newSet);\n\n return newSet;\n}\n\nif (DEBUG) {\n document.addEventListener('dblclick', () => {\n const documentListenersCount = Object.keys(documentEventCounters).length;\n const delegatedHandlersCount1 = Object.values(documentEventCounters)\n .reduce((acc, counter) => acc + counter, 0);\n const delegationRegistriesCount = Object.keys(delegationRegistryByEventType).length;\n const delegatedHandlersCount2 = Object.values(delegationRegistryByEventType)\n .reduce((acc, delegationRegistry) => acc + delegationRegistry.size, 0);\n const delegationElementsCount = delegatedEventTypesByElement.size;\n const delegatedEventTypesCount = Array.from(delegatedEventTypesByElement.values())\n .reduce((acc, eventTypes) => acc + eventTypes.size, 0);\n\n // eslint-disable-next-line no-console\n console.warn('DELEGATED EVENTS STATS', {\n delegatedHandlersCount1,\n delegatedHandlersCount2,\n delegatedEventTypesCount,\n delegationRegistriesCount,\n delegationElementsCount,\n documentListenersCount,\n });\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 const currentTarget = getTarget($current);\n\n if (!areComponents) {\n setTarget($new, currentTarget!);\n setTarget($current, undefined as any); // Help GC\n\n if ('props' in $current && 'props' in $new) {\n $new.props.ref = $current.props.ref;\n }\n }\n\n if (isRealElement($current) && isRealElement($new)) {\n if (moveDirection) {\n const node = currentTarget!;\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, currentTarget as HTMLElement);\n }\n\n $new.children = renderChildren(\n $current,\n $new,\n areComponents ? parentEl : currentTarget 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;\nconst DEBUG_SILENT_RENDERS_FOR = new Set(['TeactMemoWrapper', 'TeactNContainer', 'Button', 'ListItem', 'MenuItem']);\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.warn('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 (!DEBUG_SILENT_RENDERS_FOR.has(componentName)) {\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 (isComponentElement($element)) {\n unmountComponent($element.componentInstance);\n } else {\n if (isTagElement($element)) {\n if ($element.target) {\n removeAllDelegatedListeners($element.target as HTMLElement);\n }\n\n if ($element.props.ref) {\n $element.props.ref.current = undefined; // Help GC\n }\n }\n\n if ($element.target) {\n $element.target = undefined; // Help GC\n }\n\n if (!isRealElement($element)) {\n return;\n }\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 // We need to clean refs before running effect cleanups\n componentInstance.hooks.memos.byCursor.forEach((memoContainer) => {\n memoContainer.current = undefined;\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 componentInstance.hooks.effects.byCursor.forEach((hook) => {\n hook.cleanup = undefined;\n hook.effect = undefined as any;\n hook.dependencies = undefined;\n });\n\n componentInstance.hooks.state.byCursor.forEach((hook) => {\n hook.value = undefined;\n hook.nextValue = undefined;\n hook.setter = undefined as any;\n });\n\n componentInstance.hooks.memos.byCursor.forEach((hook) => {\n hook.dependencies = undefined as any;\n });\n\n componentInstance.hooks = undefined as any;\n componentInstance.$element = undefined as any;\n componentInstance.renderedValue = undefined;\n componentInstance.Component = undefined as any;\n componentInstance.props = undefined as any;\n componentInstance.forceUpdate = undefined;\n componentInstance.onUpdate = undefined;\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(`[Teact] Effect \"${debugKey}\" caused by dependencies.`, causedBy.join(', '));\n }\n\n primarySchedulerFn(execCleanup);\n schedulerFn(exec);\n }\n } else {\n if (debugKey) {\n // eslint-disable-next-line no-console\n console.log(`[Teact] Effect \"${debugKey}\" caused by missing dependencies.`);\n }\n\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.warn(\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\naddReducer('loadAppConfig', () => {\n (async () => {\n const appConfig = await callApi('fetchAppConfig');\n\n if (!appConfig) return;\n\n setGlobal({\n ...getGlobal(),\n appConfig,\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 if (connectionState === global.connectionState) {\n return;\n }\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';\nimport { ensurePermanentWebVersion } from '../../../util/permanentWebVersion';\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\n switchTheme(theme, animationLevel === ANIMATION_LEVEL_MAX);\n\n ensurePermanentWebVersion();\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(lang, untilDate * 1000)],\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, ApiReactions, ApiUser,\n} from '../../api/types';\nimport { LangFn } from '../../hooks/useLang';\n\nimport {\n CONTENT_NOT_SUPPORTED,\n LOCAL_MESSAGE_ID_BASE,\n RE_LINK_TEMPLATE,\n SERVICE_NOTIFICATIONS_USER_ID,\n} from '../../config';\nimport { getUserFullName } from './users';\nimport { IS_OPUS_SUPPORTED, isWebpSupported } from '../../util/environment';\nimport { getChatTitle, isUserId } from './chats';\nimport parseEmojiOnlyString from '../../components/common/helpers/parseEmojiOnlyString';\n\nconst RE_LINK = new RegExp(RE_LINK_TEMPLATE, 'i');\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 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 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\nexport function areReactionsEmpty(reactions: ApiReactions) {\n return !reactions.results.some((l) => l.count > 0);\n}\n","import { LangFn } from '../../hooks/useLang';\nimport { ApiMessage, ApiMessageEntityTypes } from '../../api/types';\nimport type { TextPart } from '../../components/common/helpers/renderMessageText';\nimport { CONTENT_NOT_SUPPORTED } from '../../config';\nimport { getMessageText } from './messages';\n\nconst SPOILER_CHARS = ['⠺', '⠵', '⠞', '⠟'];\nexport const TRUNCATED_SUMMARY_LENGTH = 80;\n\nexport function getMessageSummaryText(\n lang: LangFn,\n message: ApiMessage,\n noEmoji = false,\n truncateLength = TRUNCATED_SUMMARY_LENGTH,\n) {\n const emoji = !noEmoji && getMessageSummaryEmoji(message);\n const emojiWithSpace = emoji ? `${emoji} ` : '';\n const text = getMessageTextWithSpoilers(message)?.substr(0, truncateLength);\n const description = getMessageSummaryDescription(lang, message, text);\n\n return `${emojiWithSpace}${description}`;\n}\n\nexport function getMessageTextWithSpoilers(message: ApiMessage) {\n const text = getMessageText(message);\n if (!text) {\n return undefined;\n }\n\n const { entities } = message.content.text || {};\n if (!entities?.length) {\n return text;\n }\n\n return entities.reduce((accText, { type, offset, length }) => {\n if (type !== ApiMessageEntityTypes.Spoiler) {\n return accText;\n }\n\n const spoiler = generateBrailleSpoiler(length);\n\n return `${accText.substr(0, offset)}${spoiler}${accText.substr(offset + length, accText.length)}`;\n }, text);\n}\n\nexport function getMessageSummaryEmoji(message: ApiMessage) {\n const {\n photo, video, audio, voice, document, sticker, poll,\n } = message.content;\n\n if (message.groupedId || photo) {\n return '🖼';\n }\n\n if (video) {\n return '📹';\n }\n\n if (sticker) {\n return sticker.emoji;\n }\n\n if (audio) {\n return '🎧';\n }\n\n if (voice) {\n return '🎤';\n }\n\n if (document) {\n return '📎';\n }\n\n if (poll) {\n return '📊';\n }\n\n return undefined;\n}\n\nexport function getMessageSummaryDescription(lang: LangFn, message: ApiMessage, truncatedText?: string | TextPart[]) {\n const {\n text, photo, video, audio, voice, document, sticker, contact, poll, invoice,\n } = message.content;\n\n if (message.groupedId) {\n return truncatedText || lang('lng_in_dlg_album');\n }\n\n if (photo) {\n return truncatedText || lang('AttachPhoto');\n }\n\n if (video) {\n return truncatedText || lang(video.isGif ? 'AttachGif' : 'AttachVideo');\n }\n\n if (sticker) {\n return lang('AttachSticker').trim();\n }\n\n if (audio) {\n return getMessageAudioCaption(message) || lang('AttachMusic');\n }\n\n if (voice) {\n return truncatedText || lang('AttachAudio');\n }\n\n if (document) {\n return truncatedText || document.fileName;\n }\n\n if (contact) {\n return lang('AttachContact');\n }\n\n if (poll) {\n return poll.summary.question;\n }\n\n if (invoice) {\n return 'Invoice';\n }\n\n if (text) {\n return truncatedText;\n }\n\n return CONTENT_NOT_SUPPORTED;\n}\n\nexport function generateBrailleSpoiler(length: number) {\n return new Array(length)\n .fill(undefined)\n .map(() => SPOILER_CHARS[Math.floor(Math.random() * SPOILER_CHARS.length)])\n .join('');\n}\n\nfunction getMessageAudioCaption(message: ApiMessage) {\n const { audio, text } = message.content;\n\n return (audio && [audio.title, audio.performer].filter(Boolean).join(' — ')) || (text?.text);\n}\n","import {\n ApiAudio, ApiMediaFormat, ApiMessage, ApiMessageSearchType, ApiPhoto, ApiVideo, ApiDimensions,\n} from '../../api/types';\n\nimport { IS_OPUS_SUPPORTED, IS_PROGRESSIVE_SUPPORTED, IS_SAFARI } from '../../util/environment';\nimport { getMessageKey, isMessageLocal, matchLinkInMessageText } from './messages';\nimport { getDocumentHasPreview } from '../../components/common/helpers/documentInfo';\n\ntype Target =\n 'micro'\n | 'pictogram'\n | 'inline'\n | 'viewerPreview'\n | 'viewerFull'\n | 'download';\n\nexport function getMessageContent(message: ApiMessage) {\n return message.content;\n}\n\nexport function hasMessageMedia(message: ApiMessage) {\n return Boolean((\n getMessagePhoto(message)\n || getMessageVideo(message)\n || getMessageDocument(message)\n || getMessageSticker(message)\n || getMessageContact(message)\n || getMessagePoll(message)\n || getMessageAction(message)\n || getMessageAudio(message)\n || getMessageVoice(message)\n ));\n}\n\nexport function getMessagePhoto(message: ApiMessage) {\n return message.content.photo;\n}\n\nexport function getMessageVideo(message: ApiMessage) {\n return message.content.video;\n}\n\nexport function getMessageRoundVideo(message: ApiMessage) {\n const { video } = message.content;\n\n return video?.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): 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(lang, wasOnlineDate));\n }\n\n // yesterday\n const yesterday = new Date();\n yesterday.setDate(now.getDate() - 1);\n yesterday.setHours(0, 0, 0, 0);\n const serverYesterday = new Date(yesterday.getTime() + serverTimeOffset * 1000);\n if (wasOnlineDate > serverYesterday) {\n return lang('LastSeen.YesterdayAt', formatTime(lang, wasOnlineDate));\n }\n\n return lang('LastSeen.AtDate', formatFullDate(lang, wasOnlineDate));\n }\n\n case 'userStatusOnline': {\n return lang('Online');\n }\n\n case 'userStatusRecently': {\n return lang('Lately');\n }\n\n default:\n return undefined;\n }\n}\n\nexport function isUserOnline(user: ApiUser, 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(\n userIds: string[],\n usersById: Record<string, ApiUser>,\n query?: string,\n currentUserId?: string,\n savedMessagesLang?: string,\n) {\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 = id === currentUserId ? savedMessagesLang : 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 { 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 deleteContact(global: GlobalState, userId: string): GlobalState {\n const { byId } = global.users;\n const { userIds } = global.contactList || {};\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, {\n ...byId,\n [userId]: {\n ...byId[userId],\n isContact: undefined,\n },\n });\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, ManagementState } from '../../types';\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 {\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 { 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';\nimport memoized from '../../util/memoized';\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\nconst selectCountNotMutedUnreadMemo = memoized((\n activeChatIds: GlobalState['chats']['listIds']['active'],\n chatsById: GlobalState['chats']['byId'],\n notifySettings: GlobalState['settings']['byKey'],\n notifyExceptions: GlobalState['settings']['notifyExceptions'],\n) => {\n return activeChatIds?.reduce((acc, chatId) => {\n const chat = chatsById[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) || 0;\n});\n\n// Still slow but at least memoized\nexport function selectCountNotMutedUnreadOptimized(global: GlobalState) {\n return selectCountNotMutedUnreadMemo(\n global.chats.listIds.active,\n global.chats.byId,\n selectNotifySettings(global),\n selectNotifyExceptions(global),\n );\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 // Favorites\n global.stickers.favorite.stickers.forEach((sticker) => {\n if (sticker.emoji === emoji) stickersForEmoji.push(sticker);\n });\n\n // Added sets\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\nfunction cleanEmoji(emoji: string) {\n // Some emojis (❤️ for example) with a service symbol 'VARIATION SELECTOR-16' are not recognized as animated\n return emoji.replace('\\ufe0f', '');\n}\n\nexport function selectAnimatedEmoji(global: GlobalState, emoji: string) {\n const { animatedEmojis } = global;\n if (!animatedEmojis || !animatedEmojis.stickers) {\n return undefined;\n }\n\n const cleanedEmoji = cleanEmoji(emoji);\n\n return animatedEmojis.stickers.find((sticker) => sticker.emoji === emoji || sticker.emoji === cleanedEmoji);\n}\n\nexport function selectAnimatedEmojiEffect(global: GlobalState, emoji: string) {\n const { animatedEmojiEffects } = global;\n if (!animatedEmojiEffects || !animatedEmojiEffects.stickers) {\n return undefined;\n }\n\n const cleanedEmoji = cleanEmoji(emoji);\n\n return animatedEmojiEffects.stickers.find((sticker) => sticker.emoji === emoji || sticker.emoji === cleanedEmoji);\n}\n\nexport function selectAnimatedEmojiSound(global: GlobalState, emoji: string) {\n return global?.appConfig?.emojiSounds[cleanEmoji(emoji)];\n}\n\nexport function selectLocalAnimatedEmoji(global: GlobalState, emoji: string) {\n const cleanedEmoji = cleanEmoji(emoji);\n\n return cleanedEmoji === '🍑' ? 'Peach' : (cleanedEmoji === '🍆' ? 'Eggplant' : undefined);\n}\n\nexport function selectLocalAnimatedEmojiEffect(emoji: string) {\n return emoji === 'Eggplant' ? 'Cumshot' : undefined;\n}\n\nexport function selectLocalAnimatedEmojiEffectByName(name: string) {\n return name === 'Cumshot' ? '🍆' : undefined;\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 selectHasProtectedMessage(global: GlobalState, chatId: string, messageIds?: number[]) {\n if (selectChat(global, chatId)?.isProtected) {\n return true;\n }\n\n if (!messageIds) {\n return false;\n }\n\n const messages = selectChatMessages(global, chatId);\n\n return messageIds.some((messageId) => messages[messageId]?.isProtected);\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\nexport function selectDefaultReaction(global: GlobalState, chatId: string) {\n if (chatId === SERVICE_NOTIFICATIONS_USER_ID) return undefined;\n\n const isPrivate = isUserId(chatId);\n const defaultReaction = global.appConfig?.defaultReaction;\n const { availableReactions } = global;\n if (!defaultReaction || !availableReactions?.some(\n (l) => l.reaction === defaultReaction && !l.isInactive,\n )) {\n return undefined;\n }\n\n if (isPrivate) {\n return defaultReaction;\n }\n\n const enabledReactions = selectChat(global, chatId)?.fullInfo?.enabledReactions;\n if (!enabledReactions?.includes(defaultReaction)) {\n return undefined;\n }\n\n return defaultReaction;\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 ApiChatInviteImporter,\n ApiExportedInvite,\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 isConnectionStatusMinimized: 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 QuickReaction,\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 interface ManagementState {\n isActive: boolean;\n nextScreen?: ManagementScreens;\n isUsernameAvailable?: boolean;\n error?: string;\n invites?: ApiExportedInvite[];\n revokedInvites?: ApiExportedInvite[];\n editingInvite?: ApiExportedInvite;\n inviteInfo?: {\n invite: ApiExportedInvite;\n importers?: ApiChatInviteImporter[];\n };\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 ChatNewAdminRights,\n GroupMembers,\n GroupAddAdmins,\n Invites,\n EditInvite,\n Reactions,\n InviteInfo,\n JoinRequests,\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 if (!instance!.isCancelled && tick()) {\n fastRaf(() => {\n animateSingle(tick, instance);\n });\n }\n}\n\nexport function animate(tick: Function) {\n if (tick()) {\n fastRaf(() => {\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)[];\ntype PartsWithGlobals = (string | false | undefined | string[])[];\n\nexport default function buildClassName(...parts: Parts) {\n return parts.filter(Boolean).join(' ');\n}\n\nexport function createClassNameBuilder(componentName: string) {\n return (elementName: string, ...modifiers: PartsWithGlobals) => {\n const baseName = elementName === '&' ? componentName : `${componentName}__${elementName}`;\n\n return modifiers.reduce<string[]>((acc, modifier) => {\n if (modifier) {\n // A bit hacky way to pass global class names\n if (Array.isArray(modifier)) {\n acc.push(...modifier);\n } else {\n acc.push(`${baseName}--${modifier}`);\n }\n }\n\n return acc;\n }, [baseName]).join(' ');\n };\n}\n","// eslint-disable-next-line no-restricted-globals\nconst cacheApi = self.caches;\n\nexport enum Type {\n Text,\n Blob,\n Json,\n}\n\nexport async function fetch(\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 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","export function createCallbackManager() {\n const callbacks: AnyToVoidFunction[] = [];\n\n function addCallback(cb: AnyToVoidFunction) {\n callbacks.push(cb);\n\n return () => {\n removeCallback(cb);\n };\n }\n\n function removeCallback(cb: AnyToVoidFunction) {\n const index = callbacks.indexOf(cb);\n if (index !== -1) {\n callbacks.splice(index, 1);\n }\n }\n\n function runCallbacks(...args: any[]) {\n callbacks.forEach((callback) => {\n callback(...args);\n });\n }\n\n return {\n runCallbacks,\n addCallback,\n removeCallback,\n };\n}\n","import 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 isToday(date: Date) {\n return getDayStart(new Date()) === getDayStart(date);\n}\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(lang: LangFn, datetime: number | Date) {\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(lang, date);\n }\n\n const weekAgo = new Date(today);\n weekAgo.setDate(today.getDate() - 7);\n if (date >= weekAgo) {\n return lang(`Weekday.Short${WEEKDAYS_FULL[date.getDay()]}`);\n }\n\n const withYear = date.getFullYear() !== today.getFullYear();\n const format = (\n lang(withYear ? 'formatDateScheduleYear' : 'formatDateSchedule')\n || (withYear ? 'd MMM yyyy' : 'd MMM')\n );\n\n return formatDate(lang, date, format);\n}\n\nexport function formatFullDate(lang: LangFn, datetime: number | Date) {\n const date = typeof datetime === 'number' ? new Date(datetime) : datetime;\n const format = lang('formatterYearMax') || 'dd.MM.yyyy';\n\n return formatDate(lang, date, format);\n}\n\nexport function formatMonthAndYear(lang: LangFn, date: Date, isShort = false) {\n const format = lang(isShort ? 'formatterMonthYear2' : 'formatterMonthYear') || 'MMM yyyy';\n\n return formatDate(lang, date, format);\n}\n\nexport function formatCountdown(\n lang: LangFn,\n msLeft: number,\n) {\n const days = Math.floor(msLeft / MILLISECONDS_IN_DAY);\n if (msLeft < 0) {\n return 0;\n } else if (days < 1) {\n return formatMediaDuration(msLeft / 1000);\n } else if (days < 7) {\n return lang('Days', days);\n } else if (days < 30) {\n return lang('Weeks', Math.floor(days / 7));\n } else if (days < 365) {\n return lang('Months', Math.floor(days / 30));\n } else {\n return lang('Years', Math.floor(days / 365));\n }\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 // Workaround for https://bugs.telegram.org/c/5777\n .replace(/'de'/g, 'de');\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(lang, date)}`;\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[^\\ufe0f]/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\n// `canPlayType(VIDEO_MOV_TYPE)` returns false negative at least for macOS Chrome and iOS Safari\nexport const IS_MOV_SUPPORTED = true;\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 ADMINS_TOO_MUCH: 'There are too many admins',\n ADMIN_RANK_EMOJI_NOT_ALLOWED: 'An admin rank cannot contain emojis',\n ADMIN_RANK_INVALID: 'The specified admin rank is invalid',\n FRESH_CHANGE_ADMINS_FORBIDDEN: 'You were just elected admin, you can\\'t add or modify other admins yet',\n INPUT_USER_DEACTIVATED: 'The specified user was deleted',\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","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 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.Blob,\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<ApiPreparedMedia> {\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<ApiPreparedMedia>;\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<ApiPreparedMedia>;\n}\n\nexport function getFromMemory(url: string) {\n return memoryCache.get(url) as ApiPreparedMedia;\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: Exclude<ApiParsedMedia, ArrayBuffer>): 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 { areSortedArraysEqual } from './iteratees';\n\nconst cache = new WeakMap<AnyFunction, {\n lastArgs: any[];\n lastResult: any;\n}>();\n\nexport default function memoized<T extends AnyFunction>(fn: T) {\n return (...args: Parameters<T>): ReturnType<T> => {\n const cached = cache.get(fn);\n if (cached && areSortedArraysEqual(cached.lastArgs, args)) {\n return cached.lastResult;\n }\n\n const result = fn(...args);\n cache.set(fn, { lastArgs: args, lastResult: result });\n return result;\n };\n}\n","import { DEBUG } from '../config';\nimport { createCallbackManager } from './callbacks';\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\nconst { addCallback, runCallbacks } = createCallbackManager();\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(runCallbacks);\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\nexport const addLoadListener = addCallback;\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 isChat = chat && (isChatChannel(chat) || message.senderId === message.chatId);\n\n body = renderActionMessageText(\n getTranslation,\n message,\n !isChat ? messageSender : undefined,\n isChat ? chat : undefined,\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(imageHash);\n if (!mediaData) {\n await mediaLoader.fetch(imageHash, ApiMediaFormat.BlobUrl);\n mediaData = mediaLoader.getFromMemory(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","const PERMANENT_VERSION_KEY = 'kz_version';\nconst AVAILABLE_VERSIONS = ['Z', 'K'] as const;\nconst DEFAULT_VERSION = 'Z';\n\nexport function setPermanentWebVersion(version: typeof AVAILABLE_VERSIONS[number]) {\n localStorage.setItem(PERMANENT_VERSION_KEY, JSON.stringify(version));\n}\n\nexport function ensurePermanentWebVersion() {\n if (!hasPermanentWebVersion()) {\n setPermanentWebVersion(DEFAULT_VERSION);\n }\n}\n\nfunction hasPermanentWebVersion() {\n const json = localStorage.getItem(PERMANENT_VERSION_KEY);\n if (!json) {\n return false;\n }\n\n try {\n const version = JSON.parse(json);\n return AVAILABLE_VERSIONS.includes(version);\n } catch (err) {\n return false;\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';\nimport { fastRaf } from './schedulers';\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 fastRaf(() => {\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 });\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\nexport function clearWebsync() {\n localStorage.removeItem(WEBSYNC_KEY);\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 + \".\" + {\"99\":\"f03a947e6e336feffec8\",\"126\":\"129922d54e1dc5a7281c\",\"133\":\"7666a477f9a9de9a6afc\",\"161\":\"286d0207d962142ad548\",\"354\":\"dc598b05561e076e4338\",\"409\":\"8ade632d34e500adc543\",\"472\":\"21e5264f606f2b525030\",\"501\":\"72ce4b6e27f459e194cd\",\"524\":\"b6a2a2691c19d470d1c4\",\"532\":\"66536f2ea3d7d59eed59\",\"536\":\"55dc7dd4ab42a2c9f037\",\"626\":\"5c298967bb89444bf628\",\"745\":\"9316c5c2b711c39a20a5\",\"830\":\"a1eb7d5b23d725462a70\",\"884\":\"c52ae54ffc18c87b8d51\",\"913\":\"ca3fe796cb4dca4e375d\",\"915\":\"0588cdc78683d0e9bbbc\",\"941\":\"af78f3bce54c121af22b\",\"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 + \".\" + {\"126\":\"129922d54e1dc5a7281c\",\"133\":\"7666a477f9a9de9a6afc\",\"409\":\"8ade632d34e500adc543\",\"472\":\"21e5264f606f2b525030\",\"532\":\"66536f2ea3d7d59eed59\",\"913\":\"ca3fe796cb4dca4e375d\"}[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 isConnectionStatusMinimized: 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 activeReactions: {},\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 if (!cached.activeReactions) {\n cached.activeReactions = {};\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 availableReactions: reduceAvailableReactions(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\nfunction reduceAvailableReactions(global: GlobalState): GlobalState['availableReactions'] {\n return global.availableReactions\n ?.map((r) => pick(r, ['reaction', 'staticIcon', 'title', 'isInactive']));\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","Error","message","subscribeToWorker","platform","window","ensureWorkerPing","setTimeout","makeRequest","args","callApi","fnName","warn","promise","name","err","cancelApiProgress","progressCallback","isCanceled","postMessage","generateIdFor","payload","Promise","Object","assign","pop","set","catch","finally","delete","startedAt","Date","now","async","race","pause","then","location","reload","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","actionOriginUser","actionOriginChat","targetUsers","targetMessage","targetChatId","options","action","translationValues","amount","currency","call","textOptions","maxTextLength","processed","unprocessed","undefined","includes","processPlaceholder","formatCurrency","code","isEmbedded","renderUserContent","asPlain","chat","trimText","getChatTitle","renderText","renderChatContent","map","user","filter","getMessageSummaryText","renderMessageSummary","photo","video","sticker","getMessageContent","showQuotes","messageText","isGif","renderMessageContent","invoice","renderProductContent","renderMigratedContent","trim","renderGroupCallContent","getUserFullName","placeholder","replaceValue","placeholderPosition","substring","Array","isArray","forEach","index","actionsByMessageId","createClassNameBuilder","isRevealed","reveal","conceal","useFlag","stopPropagation","actions","useEffect","has","noEmoji","highlight","truncateLength","TRUNCATED_SUMMARY_LENGTH","shouldAddEllipsis","entities","some","l","renderMessageText","emoji","getMessageSummaryEmoji","emojiWithSpace","description","getMessageSummaryDescription","shouldRenderHqEmoji","isSimple","formattedText","rawText","getMessageText","renderTextWithEntities","substr","organizeEntity","entity","organizedEntityIndexes","offset","organizedIndexes","Set","nestedEntities","parsedEntity","isChanged","organizedIndex","add","organizeEntities","organizedEntities","organizedEntity","shouldRenderAsHtml","renderMessagePart","result","deleteLineBreakAfterPre","renderEntity","textPartStart","textPartEnd","isLastEntity","renderResult","textBefore","textBeforeLength","entityStartIndex","entityEndIndex","entityContent","nestedEntityContent","nestedIndex","nestedEntity","nestedEntityIndex","nestedResult","nestedEntityEndIndex","newEntity","rawEntityText","renderedContent","userId","getLinkUrl","processEntityAsHtml","entityText","renderNestedMessagePart","handleBotCommandClick","handleHashtagClick","MentionLink","username","SafeLink","processEntity","textAfter","arrayIndex","c","filters","concat","sendBotCommand","command","currentTarget","innerText","setLocalTextSearchQuery","query","searchTextMessagesLocal","RE_LETTER_OR_DIGIT","SIMPLE_MARKDOWN_REGEX","part","params","compact","reduce","textParts","divEl","createElement","innerHTML","escapeHtml","EMOJI_REGEX","replaceEmojis","addLineBreaks","lowerCaseText","toLowerCase","queryPosition","nextSymbol","newParts","links","RE_LINK","nextLink","shift","lastIndex","startsWith","endsWith","addLinks","replaceSimpleMarkdown","size","IS_EMOJI_SUPPORTED","parts","fixNonStandardEmoji","emojis","emojiResult","nativeToUnified","removeVS16s","src","alt","splittenParts","line","source","trimmedLine","trimLeft","indentLength","repeat","RE_LINK_TEMPLATE","RE_MENTION_TEMPLATE","entityResult","preventMessageInputBlur","withBubbling","IS_IOS","activeElement","EDITABLE_INPUT_ID","preventMessageInputBlurWithBubbling","withGlobal","global","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","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","backgroundColor","bubbleStyle","transformOriginX","transformOriginY","noCloseOnBackdrop","onCloseAnimationEnd","backdropContainerRef","transitionClassNames","useShowTransition","captureEscKeyListener","useHistoryBack","useEffectWithPrevDeps","prevIsOpen","dispatchHeavyAnimationEvent","handleKeyDown","useKeyboardListNavigation","useVirtualBackdrop","bubbleClassName","transformOriginYStyle","transformOriginXStyle","props","icon","destructive","origin","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","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","CONTENT_NOT_SUPPORTED","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","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","isDisabled","removeEventListener","isHeavyAnimating","duration","onEnd","clearTimeout","dispatchEvent","Event","LOCATION_HASH","hash","PATH_BASE","pathname","search","historyState","currentIndex","nextStateIndexToReplace","isHistoryAltered","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","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","d","next","shouldSkipUndefined","onCloseTransitionEnd","noOpenTransition","noCloseTransition","setIsClosed","closeTimeoutRef","hasOpenClassName","setHasOpenClassName","exec","shouldHaveOpenClassName","isClosing","shouldRender","handleEvent","contains","classList","NON_BUBBLEABLE_EVENTS","documentEventCounters","delegationRegistryByEventType","delegatedEventTypesByElement","propName","handler","asCapture","eventType","resolveEventType","canUseEventDelegation","resolveDelegationRegistry","existing","newSet","resolveDelegatedEventTypes","addDelegatedListener","removeDelegatedListener","tagName","realEventType","removeAllDelegatedListeners","eventTypes","realEvent","events","furtherCallsPrevented","Proxy","p","Reflect","body","parentNode","documentListenersCount","keys","delegatedHandlersCount1","values","acc","counter","delegationRegistriesCount","delegatedHandlersCount2","delegationRegistry","delegationElementsCount","delegatedEventTypesCount","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","newKeys","key","currentValue","newValue","cssText","removeAttribute","setAttribute","updateAttributes","currentEl","teactFastList","$newChild","currentRemainingIndex","remainingByKey","$currentChild","isKeyPresent","newChildKey","$element","order","teactOrderKey","fragmentQueue","fragmentIndex","newChildren","currentPreservedIndex","currentChildInfo","flushFragmentQueue","shouldMoveNode","isMovingDown","renderFastListChildren","max","createDocumentFragment","renderChildren","mountComponent","$firstChild","isEmptyElement","createTextNode","isTextElement","tag","$child","$fragmentChild","__html","render","headId","getAttribute","$head","VirtualElementTypesEnum","Fragment","Symbol","DEBUG_SILENT_RENDERS_FOR","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","memoContainer","cleanup","hook","effect","nextValue","setter","helpGc","prepareComponentForFrame","prepareForFrame","throttleWithPrimaryRaf","throttleWithRaf","forceUpdateComponent","currentElement","DEBUG_contentComponentName","useLayoutEffectBase","schedulerFn","primarySchedulerFn","execCleanup","dependency","causedBy","res","prevValue","fastRaf","fastRafPrimary","useLayoutEffect","onTickEnd","onTickEndPrimary","resolver","getUnequalProps","newCallback","areEqual","arePropsShallowEqual","propsRef","renderedRef","orderBy","React","currentGlobal","reducers","callbacks","containers","mapStateToProps","ownProps","mappedProps","newMappedProps","Number","isNaN","DEBUG_componentName","areMappedPropsChanged","DEBUG_updates","updateTime","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","isUserId","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","appConfig","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","ensurePermanentWebVersion","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","pinnedIds","getFolderChatsCount","getMessageSenderName","getUserFirstOrLastName","sortChatIds","chatIds","shouldPrioritizeVerified","priorityIds","priority","isVerified","filterChatsByName","searchWords","prepareSearchWordsForNeedle","getMessageKey","msgId","buildMessageKey","parseMessageKey","getMessageOriginalId","previousLocalId","audio","voice","poll","webPage","contact","getMessageCustomShape","isRound","parseEmojiOnlyString","getMessageSingleEmoji","getFirstLinkInMessage","link","find","isOwnMessage","isOutgoing","isReplyMessage","replyToMessageId","isForwardedMessage","forwardInfo","isActionMessage","isServiceNotificationMessage","isAnonymousOwnMessage","senderId","getSenderTitle","getSendingState","sendingState","isMessageLocal","isHistoryClearMessage","getMessageContentFilename","isAnimated","isWebpSupported","baseFilename","IS_OPUS_SUPPORTED","areReactionsEmpty","reactions","results","count","SPOILER_CHARS","getMessageTextWithSpoilers","accText","spoiler","fill","random","generateBrailleSpoiler","groupedId","truncatedText","performer","getMessageAudioCaption","summary","question","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","savedMessagesLang","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","updateStickerSets","category","sets","resultIds","updatedSets","stickerSet","stickers","setsById","setIds","updateStickerSet","stickerSetId","currentStickerSet","updateGifSearch","isNew","nextOffset","currentResults","gifs","newResults","currentIds","gif","replaceAnimatedEmojis","animatedEmojis","updateStickersForEmoji","remoteStickers","allStickers","selectStickersForEmoji","uniqueIds","unique","forEmoji","rebuildStickersForEmoji","replaceUsers","updateContactList","updatedUsers","contactUserIds","contactList","newContactUserIds","userUpdate","updatedUser","getUpdatedUser","updateUsers","updateSelectedUserId","selectedId","deleteContact","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","every","newId","updateGlobalSearchFetchingStatus","prevFoundIds","newFoundIds","prototype","foundOrPrevFoundIds","nextOffsetId","replaceLocalTextSearch","chatThreadKey","searchParams","localTextSearch","byChatThreadKey","updateLocalTextSearch","replaceLocalTextSearchResults","updateLocalTextSearchResults","orderFoundIds","replaceLocalMediaSearch","localMediaSearch","byChatId","updateLocalMediaSearchType","currentType","updateLocalMediaSearchResults","replaceLocalMediaSearchResults","sort","a","b","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","updateCurrentMessageList","shouldReplaceHistory","messageLists","newMessageLists","replaceChatMessages","updateMessageStore","threadsById","replaceThreadParam","paramName","threadUpdate","updateThread","addMessages","addedByChatId","messagesByChatId","addChatMessagesById","selectChatMessages","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","addViewportId","safeReplaceViewportIds","newViewportIds","updateThreadInfo","newThreadInfo","updateThreadInfos","updates","scheduledMessages","updateScheduledMessages","updateFocusedMessage","noHighlight","isResizingContainer","focusedMessage","updateSponsoredMessage","sponsoredByChatId","updateFocusDirection","direction","enterMessageSelectMode","selectedMessages","toggleMessageSelection","messageListType","childMessageIds","withShift","oldSelectedMessages","selectMessageIdsByGroupId","selectedMessageIds","newMessageIds","newSelectedMessageIds","selectCurrentMessageIds","prevIndex","min","to","exitMessageSelectMode","updateThreadUnreadFromForwardedMessage","originMessage","lastMessageId","isDeleting","channelPostId","threadInfoOld","selectChat","selectChatUser","selectIsChatWithSelf","selectIsChatWithBot","selectSupportChat","isSupport","selectChatOnlineCount","members","onlineCount","selectChatBot","selectIsChatBotNotStarted","bot","messageInfo","selectAreActiveChatsLoaded","selectIsChatListed","targetList","list","selectChatFolder","chatFolders","selectIsChatPinned","chatFoldersById","selectChatByUsername","usernameLowered","selectCountNotMutedUnreadMemo","memoized","activeChatIds","selectCountNotMutedUnreadOptimized","selectNotifyExceptions","selectIsServiceChatReady","selectSendAs","sendAsId","selectCurrentStickerSearch","selectCurrentGifSearch","selectStickerSet","selectStickerSetByShortName","shortName","stickerSets","stickersForEmoji","favorite","packs","cleanEmoji","selectAnimatedEmoji","cleanedEmoji","selectAnimatedEmojiEffect","animatedEmojiEffects","selectAnimatedEmojiSound","emojiSounds","selectLocalAnimatedEmoji","selectLocalAnimatedEmojiEffect","selectLocalAnimatedEmojiEffectByName","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","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","selectHasProtectedMessage","selectSponsoredMessage","expiresAt","selectDefaultReaction","defaultReaction","availableReactions","reaction","isInactive","enabledReactions","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","elementName","modifiers","baseName","modifier","self","caches","Type","fetch","cacheName","isHtmlAllowed","request","Request","cache","open","headers","Blob","blob","shouldRecreate","resolvedType","Json","json","save","cacheData","Response","put","clear","createCallbackManager","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","MILLISECONDS_IN_DAY","isToday","getDayStart","datetime","getDayStartAt","toYearMonth","timestamp","getFullYear","getMonth","toIsoString","hours","getHours","marker","padStart","getMinutes","formatPastTimeShort","weekAgo","getDay","withYear","format","formatDate","formatMonthAndYear","isShort","formatCountdown","msLeft","days","formatMediaDuration","formatHumanDate","noWeekdays","isUpperFirst","upperFirst","lowerFirst","weekAhead","weekDay","day","monthIndex","formatMediaDateTime","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","str","EXCLUDE_EMOJIS","EMOJI_EXCEPTIONS","unifiedToNative","unified","codePoints","parseInt","fromCodePoint","regex","replacement","pairs","uncompressEmoji","emojiData","categories","emojiRaw","names","native","image","isoToEmoji","iso","test","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","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","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","ADMINS_TOO_MUCH","ADMIN_RANK_EMOJI_NOT_ALLOWED","ADMIN_RANK_INVALID","FRESH_CHANGE_ADMINS_FORBIDDEN","INPUT_USER_DEACTIVATED","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","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","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","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","WeakMap","fn","lastArgs","lastResult","Bundles","LOAD_PROMISES","MEMORY_CACHE","Auth","Main","Extra","Calls","bundle","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","isChat","senderName","getNotificationContent","imageHash","mediaLoader","getAvatar","badge","vibrate","onclick","close","onshow","closeMessageNotifications","notifyClientReady","PERMANENT_VERSION_KEY","AVAILABLE_VERSIONS","setPermanentWebVersion","version","hasPermanentWebVersion","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","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","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","saveSync","clearWebsync","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","isConnectionStatusMinimized","light","isBlurred","patternColor","dark","activeReactions","shouldShowContextMenuHint","updateCacheThrottled","updateCache","unsubscribeFromBeforeUnload","isCaching","setupCaching","clearCaching","reducedGlobal","reduceShowChatInfo","reduceUsers","reduceChats","reduceMessages","recentlyFoundChatIds","reduceSettings","reduceChatFolders","reduceGroupCalls","reduceAvailableReactions","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","hasCustomBackground","hasCustomBackgroundColor","isRightColumnShown","leftColumnWidth","setIsUiReady","isReady","markReady","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","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","markInactive","TeactDOM"],"sourceRoot":""} |