telegram-tt/dist/main.47a60be301fe1683cb44.js.map
Alexander Zinchuk 6338f238f3 [Build]
2022-09-25 11:39:09 +02:00

1 line
992 KiB
Plaintext
Raw Blame History

This file contains ambiguous Unicode characters

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

{"version":3,"file":"main.47a60be301fe1683cb44.js","mappings":"uBACIA,EADAC,ECAAC,EACAC,ECwCAC,EASAC,E,4FC/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,oBAsEhC,SAA2BN,GACzBL,EAAOY,iBAAiB,WAAW,IAAkC,IAAjC,KAAEC,GAA+B,EACnE,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,UAmIlBC,OAAOjB,iBAAiB,SAAS,KAC1BkB,IAELC,YAAW,IAAMD,KAAoB,SAjIhCE,EAAY,CACjBlB,KAAM,UACNmB,KAAM,CAAC3B,KAIJ,SAAS4B,EAAiCC,GAC/C,IAAKnC,EAMH,YALIO,EAAAA,IAEFC,QAAQ4B,KAAK,2BAJiE,2BAArBH,EAAqB,iCAAr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AS,YAGzEC,OC7IL37G,EAAAA,IAEFC,QAAQC,IAAI,YAGVwoF,EAAAA,KACF0N,EAAAA,EAAAA,MAEFnqF,EAAAA,EAAAA,MAAa2sB,OAET54B,EAAAA,IAEFC,QAAQC,IAAI,4BCxBC,WACb,IAAK6iC,EAAAA,GACH,OAGF,MAAM64E,EAAWjtG,SAASomG,eAAe,4BACzC,IAAK6G,EACH,OAGF,MAAM5wG,EAAO,aAAYhL,EAAAA,GAAQ,OAAS,iBAC1C47G,EAASl5E,aAAa,OAAQ13B,GDgBhC6wG,GAEAC,EAAAA,EAAAA,OACE,mBAAC,GAAD,MACAntG,SAASomG,eAAe,SAGtB/0G,EAAAA,IAEFC,QAAQC,IAAI,6BAGVF,EAAAA,IACF2O,SAAStO,iBAAiB,YAAY,KAEpCJ,QAAQ4B,KAAK,gBAAgBoZ,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/components/common/AnimatedIcon.tsx","webpack://telegram-t/./src/components/common/AnimatedSticker.tsx","webpack://telegram-t/./src/lib/punycode.js","webpack://telegram-t/./src/components/common/SafeLink.tsx","webpack://telegram-t/./src/components/common/helpers/animatedAssets.ts","webpack://telegram-t/./src/components/common/helpers/documentInfo.ts","webpack://telegram-t/./src/components/common/helpers/parseEmojiOnlyString.ts","webpack://telegram-t/./src/components/common/UserLink.tsx","webpack://telegram-t/./src/components/common/MessageLink.tsx","webpack://telegram-t/./src/components/common/ChatLink.tsx","webpack://telegram-t/./src/components/common/GroupCallLink.tsx","webpack://telegram-t/./src/components/common/helpers/renderActionMessageText.tsx","webpack://telegram-t/./src/components/common/helpers/renderMessageText.ts","webpack://telegram-t/./src/components/common/helpers/renderText.tsx","webpack://telegram-t/./src/components/common/spoiler/Spoiler.tsx","webpack://telegram-t/./src/hooks/useEnsureCustomEmoji.ts","webpack://telegram-t/./src/components/common/hooks/useCustomEmoji.ts","webpack://telegram-t/./src/components/common/CustomEmoji.tsx","webpack://telegram-t/./src/components/common/code/CodeOverlay.module.scss?733a","webpack://telegram-t/./src/components/common/code/CodeOverlay.tsx","webpack://telegram-t/./src/components/common/code/PreBlock.tsx","webpack://telegram-t/./src/components/common/code/CodeBlock.tsx","webpack://telegram-t/./src/components/common/helpers/renderTextWithEntities.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.module.scss?2387","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/components/ui/Transition.tsx","webpack://telegram-t/./src/config.ts","webpack://telegram-t/./src/global/actions/api/initial.ts","webpack://telegram-t/./src/global/actions/api/settings.ts","webpack://telegram-t/./src/global/actions/apiUpdaters/initial.ts","webpack://telegram-t/./src/global/actions/ui/initial.ts","webpack://telegram-t/./src/global/actions/ui/settings.ts","webpack://telegram-t/./src/global/cache.ts","webpack://telegram-t/./src/global/helpers/chats.ts","webpack://telegram-t/./src/global/helpers/messages.ts","webpack://telegram-t/./src/global/helpers/reactions.ts","webpack://telegram-t/./src/global/helpers/messageSummary.ts","webpack://telegram-t/./src/global/helpers/messageMedia.ts","webpack://telegram-t/./src/global/helpers/localSearch.ts","webpack://telegram-t/./src/global/helpers/payments.ts","webpack://telegram-t/./src/global/helpers/bots.ts","webpack://telegram-t/./src/global/helpers/media.ts","webpack://telegram-t/./src/global/helpers/users.ts","webpack://telegram-t/./src/global/index.ts","webpack://telegram-t/./src/global/initialState.ts","webpack://telegram-t/./src/global/reducers/chats.ts","webpack://telegram-t/./src/global/reducers/symbols.ts","webpack://telegram-t/./src/global/reducers/users.ts","webpack://telegram-t/./src/global/reducers/globalSearch.ts","webpack://telegram-t/./src/global/reducers/localSearch.ts","webpack://telegram-t/./src/global/reducers/management.ts","webpack://telegram-t/./src/global/reducers/settings.ts","webpack://telegram-t/./src/global/reducers/twoFaSettings.ts","webpack://telegram-t/./src/global/reducers/passcode.ts","webpack://telegram-t/./src/global/reducers/payments.ts","webpack://telegram-t/./src/global/reducers/statistics.ts","webpack://telegram-t/./src/global/reducers/messages.ts","webpack://telegram-t/./src/global/selectors/chats.ts","webpack://telegram-t/./src/global/selectors/symbols.ts","webpack://telegram-t/./src/global/selectors/messages.ts","webpack://telegram-t/./src/global/selectors/localSearch.ts","webpack://telegram-t/./src/global/selectors/statistics.ts","webpack://telegram-t/./src/global/selectors/management.ts","webpack://telegram-t/./src/global/selectors/ui.ts","webpack://telegram-t/./src/global/selectors/globalSearch.ts","webpack://telegram-t/./src/global/selectors/payments.ts","webpack://telegram-t/./src/global/selectors/settings.ts","webpack://telegram-t/./src/global/selectors/users.ts","webpack://telegram-t/./src/hooks/useAsync.ts","webpack://telegram-t/./src/hooks/useBackgroundMode.ts","webpack://telegram-t/./src/hooks/useCurrentOrPrev.ts","webpack://telegram-t/./src/hooks/useDebouncedCallback.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/useIntersectionObserver.ts","webpack://telegram-t/./src/hooks/useKeyboardListNavigation.ts","webpack://telegram-t/./src/hooks/useLang.ts","webpack://telegram-t/./src/hooks/useMedia.ts","webpack://telegram-t/./src/hooks/useMediaTransition.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/useThumbnail.ts","webpack://telegram-t/./src/hooks/useVirtualBackdrop.ts","webpack://telegram-t/./src/hooks/useWindowSize.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/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/buildStyle.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/clipboard.ts","webpack://telegram-t/./src/util/cssAnimationEndListeners.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/folderManager.ts","webpack://telegram-t/./src/util/forceReflow.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/installPrompt.ts","webpack://telegram-t/./src/util/iteratees.ts","webpack://telegram-t/./src/util/langProvider.ts","webpack://telegram-t/./src/util/math.ts","webpack://telegram-t/./src/util/oggToWav.ts","webpack://telegram-t/./src/util/mediaLoader.ts","webpack://telegram-t/./src/util/memo.ts","webpack://telegram-t/./src/util/moduleLoader.ts","webpack://telegram-t/./src/util/notifications.ts","webpack://telegram-t/./src/util/passcode.ts","webpack://telegram-t/./src/util/phoneNumber.ts","webpack://telegram-t/./src/util/routing.ts","webpack://telegram-t/./src/util/safePlay.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/index.js","webpack://telegram-t/./node_modules/safari-14-idb-fix/dist/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/./src/util/withCache.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/init.ts","webpack://telegram-t/./src/util/activeTabMonitor.ts","webpack://telegram-t/./src/util/fonts.ts","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/./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/LockScreen.async.tsx","webpack://telegram-t/./src/components/main/AppInactive.tsx","webpack://telegram-t/./src/components/common/UiLoader.module.scss?03f6","webpack://telegram-t/./src/components/common/UiLoader.tsx","webpack://telegram-t/./src/App.tsx","webpack://telegram-t/./src/index.tsx","webpack://telegram-t/./src/util/updateWebmanifest.ts"],"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 = {\"3041\":1,\"3472\":1,\"3779\":1,\"5769\":1,\"8688\":1,\"8878\":1,\"9954\":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 type { Api } from '../../../lib/gramjs';\nimport type { ApiInitialArgs, ApiOnProgress, OnApiUpdate } from '../../types';\nimport type { Methods, MethodArgs, MethodResponse } from '../methods/types';\nimport type { 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 && 'name' in payload && typeof payload.args[1] === 'function') {\n payload.withCallback = true;\n\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 let isResolved = false;\n\n try {\n await Promise.race([\n makeRequest({ type: 'ping' }),\n pause(HEALTH_CHECK_TIMEOUT)\n .then(() => (isResolved ? undefined : 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 } finally {\n isResolved = true;\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 Progressive,\n Stream,\n DownloadUrl,\n Text,\n}\n\nexport type ApiParsedMedia = string | Blob | ArrayBuffer;\nexport type ApiPreparedMedia = string;\n","import type { ApiWebDocument } from './bots';\nimport type { ApiGroupCall, PhoneCallAction } from './calls';\nimport type { ApiChat } from './chats';\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 ApiVideoSize extends ApiDimensions {\n type: 'u' | 'v';\n videoStartTs: number;\n size: number;\n}\n\nexport interface ApiThumbnail extends ApiDimensions {\n dataUri: string;\n}\n\nexport interface ApiPhoto {\n id: string;\n thumbnail?: ApiThumbnail;\n isVideo?: boolean;\n sizes: ApiPhotoSize[];\n videoSizes?: ApiVideoSize[];\n blobUrl?: string;\n}\n\nexport interface ApiSticker {\n id: string;\n stickerSetInfo: ApiStickerSetInfo;\n emoji?: string;\n isCustomEmoji?: boolean;\n isLottie: boolean;\n isVideo: boolean;\n width?: number;\n height?: number;\n thumbnail?: ApiThumbnail;\n isPreloadedGlobally?: boolean;\n hasEffect?: boolean;\n isFree?: boolean;\n}\n\nexport interface ApiStickerSet {\n archived?: true;\n isLottie?: true;\n isVideos?: true;\n isEmoji?: 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\ntype ApiStickerSetInfoShortName = {\n shortName: string;\n};\n\ntype ApiStickerSetInfoId = {\n id: string;\n accessHash: string;\n};\n\ntype ApiStickerSetInfoMissing = {\n isMissing: true;\n};\n\nexport type ApiStickerSetInfo = ApiStickerSetInfoShortName | ApiStickerSetInfoId | ApiStickerSetInfoMissing;\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 isMin?: true;\n results?: ApiPollResult[];\n totalVoters?: number;\n recentVoterIds?: string[];\n solution?: string;\n solutionEntities?: ApiMessageEntity[];\n };\n}\n\n// First type used for state, second - for API requests\nexport type ApiInputInvoice = {\n chatId: string;\n messageId: number;\n} | {\n slug: string;\n};\n\nexport type ApiRequestInputInvoice = {\n chat: ApiChat;\n messageId: number;\n} | {\n slug: string;\n};\n\nexport interface ApiInvoice {\n text: string;\n title: string;\n photo?: ApiWebDocument;\n amount: number;\n currency: string;\n receiptMsgId?: number;\n isTest?: boolean;\n isRecurring?: boolean;\n recurringTermsUrl?: string;\n}\n\ninterface ApiGeoPoint {\n long: number;\n lat: number;\n accessHash: string;\n accuracyRadius?: number;\n}\n\ninterface ApiGeo {\n type: 'geo';\n geo: ApiGeoPoint;\n}\n\ninterface ApiVenue {\n type: 'venue';\n geo: ApiGeoPoint;\n title: string;\n address: string;\n provider: string;\n venueId: string;\n venueType: string;\n}\n\ninterface ApiGeoLive {\n type: 'geoLive';\n geo: ApiGeoPoint;\n heading?: number;\n period: number;\n}\n\nexport type ApiLocation = ApiGeo | ApiVenue | ApiGeoLive;\n\nexport type ApiGame = {\n title: string;\n description: string;\n photo?: ApiPhoto;\n shortName: string;\n id: string;\n accessHash: string;\n document?: ApiDocument;\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 phoneCall?: PhoneCallAction;\n score?: number;\n months?: number;\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 type ApiMessageEntityDefault = {\n type: Exclude<\n `${ApiMessageEntityTypes}`,\n `${ApiMessageEntityTypes.Pre}` | `${ApiMessageEntityTypes.TextUrl}` | `${ApiMessageEntityTypes.MentionName}` |\n `${ApiMessageEntityTypes.CustomEmoji}`\n >;\n offset: number;\n length: number;\n};\n\nexport type ApiMessageEntityPre = {\n type: ApiMessageEntityTypes.Pre;\n offset: number;\n length: number;\n language?: string;\n};\n\nexport type ApiMessageEntityTextUrl = {\n type: ApiMessageEntityTypes.TextUrl;\n offset: number;\n length: number;\n url: string;\n};\n\nexport type ApiMessageEntityMentionName = {\n type: ApiMessageEntityTypes.MentionName;\n offset: number;\n length: number;\n userId: string;\n};\n\nexport type ApiMessageEntityCustomEmoji = {\n type: ApiMessageEntityTypes.CustomEmoji;\n offset: number;\n length: number;\n documentId: string;\n};\n\nexport type ApiMessageEntity = ApiMessageEntityDefault | ApiMessageEntityPre | ApiMessageEntityTextUrl |\nApiMessageEntityMentionName | ApiMessageEntityCustomEmoji;\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 CustomEmoji = 'MessageEntityCustomEmoji',\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 location?: ApiLocation;\n game?: ApiGame;\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 forwards?: 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 transcriptionId?: string;\n isTranscriptionError?: 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 isBig?: boolean;\n isUnread?: boolean;\n}\n\nexport interface ApiReactionCount {\n isChosen?: boolean;\n count: number;\n reaction: string;\n}\n\nexport interface ApiAvailableReaction {\n selectAnimation?: ApiDocument;\n activateAnimation?: ApiDocument;\n effectAnimation?: ApiDocument;\n staticIcon?: ApiDocument;\n centerIcon?: ApiDocument;\n aroundAnimation?: ApiDocument;\n reaction: string;\n title: string;\n isInactive?: boolean;\n isPremium?: 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 isRecommended?: boolean;\n isBot?: boolean;\n channelPostId?: number;\n startParam?: string;\n chatInviteHash?: string;\n chatInviteTitle?: string;\n text: ApiFormattedText;\n expiresAt: number;\n};\n\n// KeyboardButtons\n\ninterface ApiKeyboardButtonSimple {\n type: 'unsupported' | 'buy' | 'command' | 'requestPhone' | 'game';\n text: string;\n}\n\ninterface ApiKeyboardButtonReceipt {\n type: 'receipt';\n text: string;\n receiptMessageId: number;\n}\n\ninterface ApiKeyboardButtonUrl {\n type: 'url';\n text: string;\n url: string;\n}\n\ninterface ApiKeyboardButtonSimpleWebView {\n type: 'simpleWebView';\n text: string;\n url: string;\n}\n\ninterface ApiKeyboardButtonWebView {\n type: 'webView';\n text: string;\n url: string;\n}\n\ninterface ApiKeyboardButtonCallback {\n type: 'callback';\n text: string;\n data: string;\n}\n\ninterface ApiKeyboardButtonRequestPoll {\n type: 'requestPoll';\n text: string;\n isQuiz?: boolean;\n}\n\ninterface ApiKeyboardButtonSwitchBotInline {\n type: 'switchBotInline';\n text: string;\n query: string;\n isSamePeer?: boolean;\n}\n\ninterface ApiKeyboardButtonUserProfile {\n type: 'userProfile';\n text: string;\n userId: string;\n}\n\ninterface ApiKeyboardButtonUrlAuth {\n type: 'urlAuth';\n text: string;\n url: string;\n buttonId: number;\n}\n\nexport type ApiTranscription = {\n text: string;\n isPending?: boolean;\n transcriptionId: string;\n};\n\nexport type ApiKeyboardButton = (\n ApiKeyboardButtonSimple\n | ApiKeyboardButtonReceipt\n | ApiKeyboardButtonUrl\n | ApiKeyboardButtonCallback\n | ApiKeyboardButtonRequestPoll\n | ApiKeyboardButtonSwitchBotInline\n | ApiKeyboardButtonUserProfile\n | ApiKeyboardButtonWebView\n | ApiKeyboardButtonSimpleWebView\n | ApiKeyboardButtonUrlAuth\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' | 'illegalDrugs' | 'personalDetails' | 'other';\n\nexport type ApiSendMessageAction = {\n type: 'cancel' | 'typing' | 'recordAudio' | 'chooseSticker' | 'playingGame';\n};\n\nexport type ApiThemeParameters = {\n bg_color: string;\n text_color: string;\n hint_color: string;\n link_color: string;\n button_color: string;\n button_text_color: string;\n secondary_bg_color: string;\n};\n\nexport const MAIN_THREAD_ID = -1;\n\n// `Symbol` can not be transferred from worker\nexport const MESSAGE_DELETED = 'MESSAGE_DELETED';\n","import React, {\n memo, useCallback, useState,\n} from '../../lib/teact/teact';\n\nimport type { OwnProps as AnimatedStickerProps } from './AnimatedSticker';\n\nimport buildClassName from '../../util/buildClassName';\nimport useMediaTransition from '../../hooks/useMediaTransition';\nimport useFlag from '../../hooks/useFlag';\n\nimport AnimatedSticker from './AnimatedSticker';\n\nconst DEFAULT_SIZE = 150;\n\nexport type OwnProps =\n Partial<AnimatedStickerProps>\n & { noTransition?: boolean; nonInteractive?: boolean };\n\nconst loadedAnimationUrls = new Set();\n\nfunction AnimatedIcon(props: OwnProps) {\n const {\n size = DEFAULT_SIZE,\n play = true,\n noLoop = true,\n className,\n noTransition,\n nonInteractive,\n onLoad,\n onClick,\n ...otherProps\n } = props;\n const { tgsUrl } = props;\n\n const key = `${tgsUrl}_${size}`;\n const [isAnimationLoaded, markAnimationLoaded] = useFlag(loadedAnimationUrls.has(key));\n const transitionClassNames = useMediaTransition(noTransition || isAnimationLoaded);\n\n const handleLoad = useCallback(() => {\n markAnimationLoaded();\n loadedAnimationUrls.add(key);\n\n onLoad?.();\n }, [key, markAnimationLoaded, onLoad]);\n\n const [playKey, setPlayKey] = useState(String(Math.random()));\n\n const handleClick = useCallback(() => {\n if (play === true) {\n setPlayKey(String(Math.random()));\n }\n\n onClick?.();\n }, [onClick, play]);\n\n return (\n <AnimatedSticker\n className={buildClassName(className, transitionClassNames)}\n size={size}\n play={play === true ? playKey : play}\n noLoop={noLoop}\n onClick={!nonInteractive ? handleClick : undefined}\n onLoad={handleLoad}\n /* eslint-disable-next-line react/jsx-props-no-spreading */\n {...otherProps}\n />\n );\n}\n\nexport default memo(AnimatedIcon);\n","import type { RefObject } from 'react';\nimport type { FC } from '../../lib/teact/teact';\n\nimport React, {\n useEffect, useRef, memo, useCallback, useState,\n} from '../../lib/teact/teact';\n\nimport { fastRaf } from '../../util/schedulers';\nimport buildClassName from '../../util/buildClassName';\nimport buildStyle from '../../util/buildStyle';\nimport useHeavyAnimationCheck from '../../hooks/useHeavyAnimationCheck';\nimport useBackgroundMode from '../../hooks/useBackgroundMode';\n\nexport type OwnProps = {\n ref?: RefObject<HTMLDivElement>;\n className?: string;\n style?: string;\n tgsUrl?: string;\n play?: boolean | string;\n playSegment?: [number, number];\n speed?: number;\n noLoop?: boolean;\n size: number;\n quality?: number;\n isLowPriority?: boolean;\n forceOnHeavyAnimation?: boolean;\n color?: [number, number, number];\n onClick?: NoneToVoidFunction;\n onLoad?: NoneToVoidFunction;\n onEnded?: NoneToVoidFunction;\n};\n\ntype RLottieClass = typeof import('../../lib/rlottie/RLottie').default;\ntype RLottieInstance = import('../../lib/rlottie/RLottie').default;\nlet lottiePromise: Promise<RLottieClass>;\nlet RLottie: RLottieClass;\n\n// Time for the main interface to completely load\nconst LOTTIE_LOAD_DELAY = 3000;\n\nasync function ensureLottie() {\n if (!lottiePromise) {\n lottiePromise = import('../../lib/rlottie/RLottie') as unknown as Promise<RLottieClass>;\n RLottie = (await lottiePromise as any).default;\n }\n\n return lottiePromise;\n}\n\nsetTimeout(ensureLottie, LOTTIE_LOAD_DELAY);\n\nconst AnimatedSticker: FC<OwnProps> = ({\n ref,\n className,\n style,\n tgsUrl,\n play,\n playSegment,\n speed,\n noLoop,\n size,\n quality,\n isLowPriority,\n color,\n forceOnHeavyAnimation,\n onClick,\n onLoad,\n onEnded,\n}) => {\n // eslint-disable-next-line no-null/no-null\n let containerRef = useRef<HTMLDivElement>(null);\n if (ref) {\n containerRef = ref;\n }\n\n const [animation, setAnimation] = useState<RLottieInstance>();\n const wasPlaying = useRef(false);\n const isFrozen = useRef(false);\n const isFirstRender = useRef(true);\n\n const playRef = useRef();\n playRef.current = play;\n const playSegmentRef = useRef<[number, number]>();\n playSegmentRef.current = playSegment;\n\n useEffect(() => {\n if (animation || !tgsUrl) {\n return;\n }\n\n const exec = () => {\n if (!containerRef.current) {\n return;\n }\n\n const newAnimation = new RLottie(\n containerRef.current,\n tgsUrl,\n {\n noLoop,\n size,\n quality,\n isLowPriority,\n },\n onLoad,\n color,\n onEnded,\n );\n\n if (speed) {\n newAnimation.setSpeed(speed);\n }\n\n setAnimation(newAnimation);\n };\n\n if (RLottie) {\n exec();\n } else {\n ensureLottie().then(() => {\n fastRaf(() => {\n if (containerRef.current) {\n exec();\n }\n });\n });\n }\n }, [color, animation, tgsUrl, isLowPriority, noLoop, onLoad, quality, size, speed, onEnded]);\n\n useEffect(() => {\n if (!animation) return;\n\n animation.setColor(color);\n }, [color, animation]);\n\n useEffect(() => {\n return () => {\n if (animation) {\n animation.destroy();\n }\n };\n }, [animation]);\n\n const playAnimation = useCallback((shouldRestart = false) => {\n if (animation && (playRef.current || playSegmentRef.current)) {\n if (playSegmentRef.current) {\n animation.playSegment(playSegmentRef.current);\n } else {\n animation.play(shouldRestart);\n }\n }\n }, [animation]);\n\n const pauseAnimation = useCallback(() => {\n if (!animation) {\n return;\n }\n\n animation.pause();\n }, [animation]);\n\n const freezeAnimation = useCallback(() => {\n isFrozen.current = true;\n\n if (!animation) {\n return;\n }\n\n if (!wasPlaying.current) {\n wasPlaying.current = animation.isPlaying();\n }\n\n pauseAnimation();\n }, [animation, pauseAnimation]);\n\n const unfreezeAnimation = useCallback(() => {\n if (wasPlaying.current) {\n playAnimation(noLoop);\n }\n\n wasPlaying.current = false;\n isFrozen.current = false;\n }, [noLoop, playAnimation]);\n\n const unfreezeAnimationOnRaf = useCallback(() => {\n fastRaf(unfreezeAnimation);\n }, [unfreezeAnimation]);\n\n useEffect(() => {\n if (!animation) {\n return;\n }\n if (play || playSegment) {\n if (isFrozen.current) {\n wasPlaying.current = true;\n } else {\n playAnimation(noLoop);\n }\n } else {\n // eslint-disable-next-line no-lonely-if\n if (isFrozen.current) {\n wasPlaying.current = false;\n } else {\n pauseAnimation();\n }\n }\n }, [animation, play, playSegment, noLoop, playAnimation, pauseAnimation]);\n\n useEffect(() => {\n if (animation) {\n if (isFirstRender.current) {\n isFirstRender.current = false;\n } else if (tgsUrl) {\n animation.changeData(tgsUrl);\n playAnimation();\n }\n }\n }, [playAnimation, animation, tgsUrl]);\n\n useHeavyAnimationCheck(freezeAnimation, unfreezeAnimation, forceOnHeavyAnimation);\n // Pausing frame may not happen in background\n // so we need to make sure it happens right after focusing,\n // then we can play again.\n useBackgroundMode(freezeAnimation, unfreezeAnimationOnRaf);\n\n return (\n <div\n ref={containerRef}\n className={buildClassName('AnimatedSticker', className)}\n style={buildStyle(\n size !== undefined && `width: ${size}px; height: ${size}px;`,\n onClick && 'cursor: pointer',\n style,\n )}\n onClick={onClick}\n />\n );\n};\n\nexport default memo(AnimatedSticker);\n","/* eslint-disable no-nested-ternary */\n/* eslint-disable no-bitwise */\n/* eslint-disable @typescript-eslint/naming-convention */\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 type { FC } from '../../lib/teact/teact';\nimport React, { memo, useCallback } from '../../lib/teact/teact';\nimport { getActions } from '../../global';\nimport convertPunycode from '../../lib/punycode';\n\nimport {\n DEBUG,\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?: React.ReactNode;\n isRtl?: boolean;\n};\n\nconst SafeLink: FC<OwnProps> = ({\n url,\n text,\n className,\n children,\n isRtl,\n}) => {\n const { openUrl } = getActions();\n\n const content = children || text;\n const isSafe = url === content;\n\n const handleClick = useCallback((e: React.MouseEvent<HTMLAnchorElement, MouseEvent>) => {\n if (!url) return true;\n e.preventDefault();\n openUrl({ url, shouldSkipModal: isSafe });\n\n return false;\n }, [isSafe, openUrl, 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.replace(/%%/g, '%25'));\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 MonkeyIdle from '../../../assets/tgs/monkeys/TwoFactorSetupMonkeyIdle.tgs';\nimport MonkeyTracking from '../../../assets/tgs/monkeys/TwoFactorSetupMonkeyTracking.tgs';\nimport MonkeyClose from '../../../assets/tgs/monkeys/TwoFactorSetupMonkeyClose.tgs';\nimport MonkeyPeek from '../../../assets/tgs/monkeys/TwoFactorSetupMonkeyPeek.tgs';\n\nimport FoldersAll from '../../../assets/tgs/settings/FoldersAll.tgs';\nimport FoldersNew from '../../../assets/tgs/settings/FoldersNew.tgs';\nimport DiscussionGroups from '../../../assets/tgs/settings/DiscussionGroupsDucks.tgs';\nimport Lock from '../../../assets/tgs/settings/Lock.tgs';\nimport Congratulations from '../../../assets/tgs/settings/Congratulations.tgs';\nimport Experimental from '../../../assets/tgs/settings/Experimental.tgs';\n\nimport CameraFlip from '../../../assets/tgs/calls/CameraFlip.tgs';\nimport HandFilled from '../../../assets/tgs/calls/HandFilled.tgs';\nimport HandOutline from '../../../assets/tgs/calls/HandOutline.tgs';\nimport Speaker from '../../../assets/tgs/calls/Speaker.tgs';\nimport VoiceAllowTalk from '../../../assets/tgs/calls/VoiceAllowTalk.tgs';\nimport VoiceMini from '../../../assets/tgs/calls/VoiceMini.tgs';\nimport VoiceMuted from '../../../assets/tgs/calls/VoiceMuted.tgs';\nimport VoiceOutlined from '../../../assets/tgs/calls/VoiceOutlined.tgs';\n\nimport Peach from '../../../assets/tgs/animatedEmojis/Peach.tgs';\nimport Eggplant from '../../../assets/tgs/animatedEmojis/Eggplant.tgs';\nimport Cumshot from '../../../assets/tgs/animatedEmojis/Cumshot.tgs';\n\nimport JoinRequest from '../../../assets/tgs/invites/Requests.tgs';\nimport Invite from '../../../assets/tgs/invites/Invite.tgs';\n\nimport QrPlane from '../../../assets/tgs/auth/QrPlane.tgs';\n\nexport const LOCAL_TGS_URLS = {\n MonkeyIdle,\n MonkeyTracking,\n MonkeyClose,\n MonkeyPeek,\n FoldersAll,\n FoldersNew,\n DiscussionGroups,\n Lock,\n CameraFlip,\n HandFilled,\n HandOutline,\n Speaker,\n VoiceAllowTalk,\n VoiceMini,\n VoiceMuted,\n VoiceOutlined,\n Peach,\n Eggplant,\n Cumshot,\n JoinRequest,\n Invite,\n QrPlane,\n Congratulations,\n Experimental,\n};\n","import type { ApiDocument } from '../../../api/types';\n\nconst ONE_GIGABYTE = 1024 * 1024 * 1024;\nconst ONE_MEGABYTE = 1024 * 1024;\n\nexport function getFileSizeString(bytes: number) {\n if (bytes > (ONE_GIGABYTE / 2)) {\n return `${(bytes / ONE_GIGABYTE).toFixed(1)} GB`;\n }\n if (bytes > (ONE_MEGABYTE / 2)) {\n return `${(bytes / ONE_MEGABYTE).toFixed(1)} MB`;\n }\n return `${(bytes / (1024)).toFixed(1)} KB`;\n}\n\nexport function getDocumentExtension(document: ApiDocument) {\n const { fileName, mimeType } = document;\n\n return getFileExtension(fileName, mimeType);\n}\n\nexport function getFileExtension(fileName: string, mimeType: string) {\n if (fileName && fileName.indexOf('.') !== -1) {\n return fileName.split('.').pop();\n } else {\n return mimeType.split('/').pop();\n }\n}\n\nexport function getColorFromExtension(extension: string) {\n switch (extension) {\n case 'apk':\n case 'xls':\n case 'xlsx':\n return 'green';\n case 'zip':\n case 'rar':\n case '7z':\n case 'tar':\n case 'gz':\n case 'ppt':\n case 'pptx':\n return 'orange';\n case 'pdf':\n case 'xps':\n return 'red';\n default:\n return 'default';\n }\n}\n\nexport function getDocumentHasPreview(document: ApiDocument) {\n return Boolean(document.previewBlobUrl || document.thumbnail);\n}\n","import 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\nconst parseEmojiOnlyString = (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\nexport default parseEmojiOnlyString;\n","import type { FC } from '../../lib/teact/teact';\nimport React, { useCallback } from '../../lib/teact/teact';\n\nimport type { ApiChat, ApiUser } from '../../api/types';\n\nimport buildClassName from '../../util/buildClassName';\n\nimport Link from '../ui/Link';\nimport { getActions } from '../../global';\n\ntype OwnProps = {\n className?: string;\n sender?: ApiUser | ApiChat;\n children: React.ReactNode;\n};\n\nconst UserLink: FC<OwnProps> = ({\n className, sender, children,\n}) => {\n const { openChat } = getActions();\n\n const handleClick = useCallback(() => {\n if (sender) {\n openChat({ id: sender.id });\n }\n }, [sender, openChat]);\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 type { FC } from '../../lib/teact/teact';\nimport React, { useCallback } from '../../lib/teact/teact';\nimport { getActions } from '../../global';\n\nimport type { 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: React.ReactNode;\n};\n\nconst MessageLink: FC<OwnProps> = ({\n className, message, children,\n}) => {\n const { focusMessage } = getActions();\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 type { FC } from '../../lib/teact/teact';\nimport React, { useCallback } from '../../lib/teact/teact';\nimport { getActions } from '../../global';\n\nimport buildClassName from '../../util/buildClassName';\n\nimport Link from '../ui/Link';\n\ntype OwnProps = {\n className?: string;\n chatId?: string;\n children: React.ReactNode;\n};\n\nconst ChatLink: FC<OwnProps> = ({\n className, chatId, children,\n}) => {\n const { openChat } = getActions();\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 type { FC } from '../../lib/teact/teact';\nimport React, { useCallback } from '../../lib/teact/teact';\n\nimport type { ApiGroupCall } from '../../api/types';\n\nimport buildClassName from '../../util/buildClassName';\n\nimport Link from '../ui/Link';\nimport { getActions } from '../../global';\n\ntype OwnProps = {\n className?: string;\n groupCall?: Partial<ApiGroupCall>;\n children: React.ReactNode;\n};\n\nconst GroupCallLink: FC<OwnProps> = ({\n className, groupCall, children,\n}) => {\n const { joinGroupCall } = getActions();\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 type {\n ApiChat, ApiMessage, ApiUser, ApiGroupCall,\n} from '../../../api/types';\nimport type { TextPart } from '../../../types';\n\nimport type { LangFn } from '../../../hooks/useLang';\nimport {\n getChatTitle,\n getMessageSummaryText,\n getUserFullName,\n} from '../../../global/helpers';\nimport trimText from '../../../util/trimText';\nimport { formatCurrency } from '../../../util/formatCurrency';\nimport { renderMessageSummary } 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 RenderOptions {\n asPlainText?: boolean;\n asTextWithSpoilers?: boolean;\n}\n\nconst MAX_LENGTH = 32;\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: RenderOptions = {},\n) {\n if (!message.content.action) {\n return [];\n }\n\n const {\n text, translationValues, amount, currency, call, score,\n } = message.content.action;\n const content: TextPart[] = [];\n const noLinks = options.asPlainText || options.asTextWithSpoilers;\n const translationKey = text === 'Chat.Service.Group.UpdatedPinnedMessage1' && !targetMessage\n ? 'Message.PinnedGenericMessage'\n : text;\n let unprocessed = lang(translationKey, translationValues?.length ? translationValues : undefined);\n if (translationKey.includes('ScoredInGame')) { // Translation hack for games\n unprocessed = unprocessed.replace('un1', '%action_origin%').replace('un2', '%message%');\n }\n if (translationKey === 'ActionGiftOutbound') { // Translation hack for Premium Gift\n unprocessed = unprocessed.replace('un2', '%gift_payment_amount%').replace(/\\*\\*/g, '');\n }\n if (translationKey === 'ActionGiftInbound') { // Translation hack for Premium Gift\n unprocessed = unprocessed\n .replace('un1', '%action_origin%')\n .replace('un2', '%gift_payment_amount%')\n .replace(/\\*\\*/g, '');\n }\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 renderUserContent(actionOriginUser, noLinks) || NBSP\n ) : actionOriginChat ? (\n renderChatContent(lang, actionOriginChat, noLinks) || NBSP\n ) : 'User',\n );\n\n unprocessed = processed.pop() as string;\n content.push(...processed);\n\n if (unprocessed.includes('%gift_payment_amount%')) {\n processed = processPlaceholder(\n unprocessed,\n '%gift_payment_amount%',\n formatCurrency(amount!, currency!, lang.code),\n );\n unprocessed = processed.pop() as string;\n content.push(...processed);\n }\n\n if (unprocessed.includes('%score%')) {\n processed = processPlaceholder(\n unprocessed,\n '%score%',\n score!.toString(),\n );\n unprocessed = processed.pop() as string;\n content.push(...processed);\n }\n\n processed = processPlaceholder(\n unprocessed,\n '%target_user%',\n targetUsers\n ? targetUsers.map((user) => renderUserContent(user, noLinks)).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, options)\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, noLinks)\n : 'another chat',\n );\n processed.forEach((part) => {\n content.push(...renderText(part));\n });\n\n if (options.asPlainText) {\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: RenderOptions = {}) {\n const { asPlainText, asTextWithSpoilers } = options;\n\n if (asPlainText) {\n return getMessageSummaryText(lang, message, undefined, MAX_LENGTH);\n }\n\n const messageSummary = renderMessageSummary(lang, message, undefined, undefined, MAX_LENGTH);\n\n if (asTextWithSpoilers) {\n return (\n <span>{messageSummary}</span>\n );\n }\n\n return (\n <MessageLink className=\"action-link\" message={message}>{messageSummary}</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, noLinks?: boolean): string | TextPart | undefined {\n const text = trimText(getUserFullName(sender), MAX_LENGTH);\n\n if (noLinks) {\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, noLinks?: boolean): string | TextPart | undefined {\n const text = trimText(getChatTitle(lang, chat), MAX_LENGTH);\n\n if (noLinks) {\n return text;\n }\n\n return <ChatLink className=\"action-link\" chatId={chat.id}>{chat && renderText(text!)}</ChatLink>;\n}\n\nfunction renderMigratedContent(chatId: string, noLinks?: boolean): string | TextPart | undefined {\n const text = 'another chat';\n\n if (noLinks) {\n return text;\n }\n\n return <ChatLink className=\"action-link underlined-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 type { ApiMessage } from '../../../api/types';\nimport { ApiMessageEntityTypes } from '../../../api/types';\nimport type { TextPart } from '../../../types';\nimport type { ObserveFn } from '../../../hooks/useIntersectionObserver';\nimport type { LangFn } from '../../../hooks/useLang';\n\nimport {\n getMessageSummaryDescription,\n getMessageSummaryEmoji,\n getMessageSummaryText,\n getMessageText,\n TRUNCATED_SUMMARY_LENGTH,\n} from '../../../global/helpers';\nimport renderText from './renderText';\nimport { renderTextWithEntities } from './renderTextWithEntities';\nimport trimText from '../../../util/trimText';\n\nexport function renderMessageText(\n message: ApiMessage,\n highlight?: string,\n shouldRenderHqEmoji?: boolean,\n isSimple?: boolean,\n truncateLength?: number,\n isProtected?: boolean,\n observeIntersection?: ObserveFn,\n) {\n const { text, entities } = message.content.text || {};\n\n if (!text) {\n const contentNotSupportedText = getMessageText(message);\n return contentNotSupportedText ? [trimText(contentNotSupportedText, truncateLength)] : undefined;\n }\n\n return renderTextWithEntities(\n trimText(text, truncateLength),\n entities,\n highlight,\n shouldRenderHqEmoji,\n undefined,\n message.id,\n isSimple,\n isProtected,\n observeIntersection,\n );\n}\n\nexport function renderMessageSummary(\n lang: LangFn,\n message: ApiMessage,\n noEmoji = false,\n highlight?: string,\n truncateLength = TRUNCATED_SUMMARY_LENGTH,\n observeIntersection?: ObserveFn,\n): TextPart[] {\n const { entities } = message.content.text || {};\n\n const hasSpoilers = entities?.some((e) => e.type === ApiMessageEntityTypes.Spoiler);\n const hasCustomEmoji = entities?.some((e) => e.type === ApiMessageEntityTypes.CustomEmoji);\n if (!hasSpoilers && !hasCustomEmoji) {\n const text = trimText(getMessageSummaryText(lang, message, noEmoji), truncateLength);\n\n if (highlight) {\n return renderText(text, ['emoji', 'highlight'], { highlight });\n } else {\n return renderText(text);\n }\n }\n\n const emoji = !noEmoji && getMessageSummaryEmoji(message);\n const emojiWithSpace = emoji ? `${emoji} ` : '';\n\n const text = renderMessageText(\n message, highlight, undefined, true, truncateLength, undefined, observeIntersection,\n );\n const description = getMessageSummaryDescription(lang, message, text);\n\n return [\n ...renderText(emojiWithSpace),\n ...(Array.isArray(description) ? description : [description]),\n ].filter<TextPart>(Boolean);\n}\n","import React from '../../../lib/teact/teact';\nimport EMOJI_REGEX from '../../../lib/twemojiRegex';\n\nimport type { TextPart } from '../../../types';\n\nimport { RE_LINK_TEMPLATE, RE_MENTION_TEMPLATE } from '../../../config';\nimport { IS_EMOJI_SUPPORTED } from '../../../util/environment';\nimport {\n fixNonStandardEmoji,\n handleEmojiLoad,\n LOADED_EMOJIS,\n nativeToUnifiedExtendedWithCache,\n} 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\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: TextPart[], 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 }, []);\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: TextPart[], part: TextPart) => {\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: string[] = part.match(EMOJI_REGEX) || [];\n result.push(parts[0]);\n\n return emojis.reduce((emojiResult: TextPart[], emoji, i) => {\n const code = nativeToUnifiedExtendedWithCache(emoji);\n if (!code) return emojiResult;\n const src = `./img-apple-${size === 'big' ? '160' : '64'}/${code}.png`;\n const className = buildClassName(\n 'emoji',\n size === 'small' && 'emoji-small',\n );\n\n if (type === 'jsx') {\n const isLoaded = LOADED_EMOJIS.has(src);\n\n emojiResult.push(\n <img\n src={src}\n className={`${className}${!isLoaded ? ' opacity-transition slow shown' : ''}`}\n alt={emoji}\n data-path={src}\n onLoad={!isLoaded ? handleEmojiLoad : undefined}\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<TextPart[]>((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 }, []);\n}\n\nconst RE_LINK = new RegExp(`${RE_LINK_TEMPLATE}|${RE_MENTION_TEMPLATE}`, 'ig');\n\nfunction addLinks(textParts: TextPart[]): TextPart[] {\n return textParts.reduce<TextPart[]>((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 }, []);\n}\n\nfunction replaceSimpleMarkdown(textParts: TextPart[], type: 'jsx' | 'html'): TextPart[] {\n return textParts.reduce<TextPart[]>((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 }, []);\n}\n\nexport function areLinesWrapping(text: string, element: HTMLElement) {\n const lines = (text.trim().match(/\\n/g) || '').length + 1;\n const { lineHeight } = getComputedStyle(element);\n const lineHeightParsed = parseFloat(lineHeight.split('px')[0]);\n\n return element.clientHeight >= (lines + 1) * lineHeightParsed;\n}\n","import type { MouseEvent as ReactMouseEvent } from 'react';\nimport type { FC } from '../../../lib/teact/teact';\nimport React, {\n memo, useCallback, useEffect, useRef,\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 READING_SYMBOLS_PER_SECOND = 23; // Heuristics\nconst MIN_HIDE_TIMEOUT = 5000; // 5s\nconst MAX_HIDE_TIMEOUT = 60000; // 1m\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 // eslint-disable-next-line no-null/no-null\n const contentRef = useRef<HTMLDivElement>(null);\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 const contentLength = contentRef.current!.innerText.length;\n const readingMs = Math.round(contentLength / READING_SYMBOLS_PER_SECOND) * 1000;\n const timeoutMs = Math.max(MIN_HIDE_TIMEOUT, Math.min(readingMs, MAX_HIDE_TIMEOUT));\n\n setTimeout(() => {\n actionsByMessageId.get(messageId!)?.forEach((actions) => actions.conceal());\n conceal();\n }, timeoutMs);\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')} ref={contentRef}>\n {children}\n </span>\n </span>\n );\n};\n\nexport default memo(Spoiler);\n","import { getActions, getGlobal } from '../global';\nimport { throttle } from '../util/schedulers';\n\nconst LOAD_QUEUE = new Set<string>();\nconst RENDER_HISTORY = new Set<string>();\nconst THROTTLE = 200;\n\nconst loadFromQueue = throttle(() => {\n getActions().loadCustomEmojis({\n ids: [...LOAD_QUEUE],\n });\n\n LOAD_QUEUE.clear();\n}, THROTTLE, false);\n\nconst updateLastRendered = throttle(() => {\n getActions().updateLastRenderedCustomEmojis({\n ids: [...RENDER_HISTORY].reverse(),\n });\n\n RENDER_HISTORY.clear();\n}, THROTTLE, false);\n\nexport default function useEnsureCustomEmoji(id: string) {\n RENDER_HISTORY.add(id);\n updateLastRendered();\n\n if (getGlobal().customEmojis.byId[id]) {\n return;\n }\n LOAD_QUEUE.add(id);\n loadFromQueue();\n}\n","import { useCallback, useEffect, useState } from '../../../lib/teact/teact';\nimport { addCallback } from '../../../lib/teact/teactn';\nimport { getGlobal } from '../../../global';\n\nimport type { GlobalState } from '../../../global/types';\nimport type { ApiSticker } from '../../../api/types';\n\nconst handlers = new Set<AnyToVoidFunction>();\n\nlet prevGlobal: GlobalState | undefined;\n\naddCallback((global: GlobalState) => {\n const customEmojiById = global.customEmojis.byId;\n\n if (customEmojiById === prevGlobal?.customEmojis.byId) {\n return;\n }\n\n for (const handler of handlers) {\n handler();\n }\n\n prevGlobal = global;\n});\n\nexport default function useCustomEmoji(documentId: string) {\n const [customEmoji, setCustomEmoji] = useState<ApiSticker | undefined>(getGlobal().customEmojis.byId[documentId]);\n\n const handleGlobalChange = useCallback(() => {\n setCustomEmoji(getGlobal().customEmojis.byId[documentId]);\n }, [documentId]);\n\n useEffect(() => {\n if (!documentId) return;\n handleGlobalChange();\n }, [documentId, handleGlobalChange]);\n\n useEffect(() => {\n if (customEmoji) return undefined;\n handlers.add(handleGlobalChange);\n\n return () => {\n handlers.delete(handleGlobalChange);\n };\n }, [customEmoji, documentId, handleGlobalChange]);\n\n return customEmoji;\n}\n","import React, {\n memo, useEffect, useMemo, useRef,\n} from '../../lib/teact/teact';\n\nimport type { FC, TeactNode } from '../../lib/teact/teact';\nimport type { ObserveFn } from '../../hooks/useIntersectionObserver';\n\nimport { IS_WEBM_SUPPORTED } from '../../util/environment';\nimport renderText from './helpers/renderText';\nimport safePlay from '../../util/safePlay';\n\nimport useMedia from '../../hooks/useMedia';\nimport useEnsureCustomEmoji from '../../hooks/useEnsureCustomEmoji';\nimport { useIsIntersecting } from '../../hooks/useIntersectionObserver';\nimport useThumbnail from '../../hooks/useThumbnail';\nimport useCustomEmoji from './hooks/useCustomEmoji';\n\nimport AnimatedSticker from './AnimatedSticker';\n\ntype OwnProps = {\n documentId: string;\n children?: TeactNode;\n observeIntersection?: ObserveFn;\n};\n\nconst STICKER_SIZE = 24;\n\nconst CustomEmojiInner: FC<OwnProps> = ({\n documentId,\n children,\n observeIntersection,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const ref = useRef<HTMLDivElement>(null);\n // An alternative to `withGlobal` to avoid adding numerous global containers\n const customEmoji = useCustomEmoji(documentId);\n const mediaHash = customEmoji && `sticker${customEmoji.id}`;\n const mediaData = useMedia(mediaHash);\n const thumbDataUri = useThumbnail(customEmoji);\n\n const isIntersecting = useIsIntersecting(ref, observeIntersection);\n\n useEnsureCustomEmoji(documentId);\n\n useEffect(() => {\n if (!customEmoji?.isVideo) return;\n const video = ref.current?.querySelector('video');\n if (!video || isIntersecting === !video.paused) return;\n\n if (isIntersecting) {\n safePlay(video);\n } else {\n video.pause();\n }\n }, [customEmoji, isIntersecting]);\n\n const content = useMemo(() => {\n if (!customEmoji || (!thumbDataUri && !mediaData)) {\n return (children && renderText(children, ['emoji']));\n }\n if (!mediaData || (customEmoji.isVideo && !IS_WEBM_SUPPORTED)) {\n return (\n <img src={thumbDataUri} alt={customEmoji.emoji} />\n );\n }\n if (!customEmoji.isVideo && !customEmoji.isLottie) {\n return (\n <img src={mediaData} alt={customEmoji.emoji} />\n );\n }\n if (customEmoji.isVideo) {\n return (\n <video\n playsInline\n muted\n autoPlay={isIntersecting}\n loop\n src={mediaData}\n />\n );\n }\n return (\n <AnimatedSticker\n size={STICKER_SIZE}\n tgsUrl={mediaData}\n play={isIntersecting}\n isLowPriority\n />\n );\n }, [children, customEmoji, isIntersecting, mediaData, thumbDataUri]);\n\n return (\n <div ref={ref} className=\"text-entity-custom-emoji emoji\">\n {content}\n </div>\n );\n};\n\nexport default memo(CustomEmojiInner);\n","// extracted by mini-css-extract-plugin\nexport default {\"overlay\":\"SwhO2lEtk47g68_ixpDe\",\"copy\":\"deqdY4TS7mStC8qkslV4\",\"wrap\":\"iEZTJnlmMCct8jJztTx8\",\"wrapOn\":\"B4kEjXkw8Sse9g0Xv_OO\",\"content\":\"d09hp4fxFTuFw1emBUDA\",\"hidden\":\"We_Wcr7YvkkUM8ICjRAs\"};","import type { FC } from '../../../lib/teact/teact';\nimport React, {\n memo, useCallback, useEffect, useRef, useState,\n} from '../../../lib/teact/teact';\nimport { getActions } from '../../../global';\n\nimport { copyTextToClipboard } from '../../../util/clipboard';\nimport buildClassName from '../../../util/buildClassName';\nimport { areLinesWrapping } from '../helpers/renderText';\n\nimport useWindowSize from '../../../hooks/useWindowSize';\nimport useLang from '../../../hooks/useLang';\n\nimport styles from './CodeOverlay.module.scss';\n\nexport type OwnProps = {\n className?: string;\n text: string;\n noCopy?: boolean;\n onWordWrapToggle?: (wrap: boolean) => void;\n};\n\nconst CodeOverlay: FC<OwnProps> = ({\n text, className, noCopy, onWordWrapToggle,\n}) => {\n const { showNotification } = getActions();\n // eslint-disable-next-line no-null/no-null\n const ref = useRef<HTMLDivElement>(null);\n const windowSize = useWindowSize();\n const lang = useLang();\n const [isWordWrap, setIsWordWrap] = useState(true);\n const [withWordWrapButton, setWithWordWrapButton] = useState(false);\n\n const checkWordWrap = useCallback(() => {\n const isWrap = areLinesWrapping(text, ref.current!.parentElement!);\n setWithWordWrapButton(isWrap);\n }, [text]);\n\n useEffect(() => {\n if (isWordWrap) {\n checkWordWrap();\n }\n }, [checkWordWrap, isWordWrap, text, windowSize]);\n\n const handleCopy = useCallback(() => {\n copyTextToClipboard(text);\n showNotification({\n message: lang('TextCopied'),\n });\n }, [lang, showNotification, text]);\n\n const handleWordWrapClick = useCallback(() => {\n setIsWordWrap(!isWordWrap);\n onWordWrapToggle?.(!isWordWrap);\n }, [isWordWrap, onWordWrapToggle]);\n\n const contentClass = buildClassName(styles.content, !withWordWrapButton && noCopy && styles.hidden);\n const overlayClass = buildClassName(styles.overlay, className);\n const wrapClass = buildClassName(styles.wrap, isWordWrap && styles.wrapOn);\n\n return (\n <div className={overlayClass} ref={ref}>\n <div className={contentClass}>\n {withWordWrapButton && (\n <div className={wrapClass} onClick={handleWordWrapClick} title=\"Word Wrap\">\n <i className=\"icon-word-wrap\" />\n </div>\n )}\n {!noCopy && (\n <div className={styles.copy} onClick={handleCopy} title={lang('Copy')}>\n <i className=\"icon-copy\" />\n </div>\n )}\n </div>\n </div>\n );\n};\n\nexport default memo(CodeOverlay);\n","import type { FC } from '../../../lib/teact/teact';\nimport React, { memo, useCallback, useState } from '../../../lib/teact/teact';\n\nimport buildClassName from '../../../util/buildClassName';\n\nimport CodeOverlay from './CodeOverlay';\n\ntype OwnProps = {\n text: string;\n noCopy?: boolean;\n};\n\nconst PreBlock: FC<OwnProps> = ({ text, noCopy }) => {\n const [isWordWrap, setWordWrap] = useState(true);\n\n const handleWordWrapToggle = useCallback((wrap) => {\n setWordWrap(wrap);\n }, []);\n\n const blockClass = buildClassName('text-entity-pre', !isWordWrap && 'no-word-wrap');\n\n return (\n <pre className={blockClass}>\n <div className=\"pre-code custom-scroll-x\">{text}</div>\n <CodeOverlay\n text={text}\n className=\"code-overlay\"\n onWordWrapToggle={handleWordWrapToggle}\n noCopy={noCopy}\n />\n </pre>\n );\n};\n\nexport default memo(PreBlock);\n","import type { FC } from '../../../lib/teact/teact';\nimport React, { memo, useCallback, useState } from '../../../lib/teact/teact';\n\nimport buildClassName from '../../../util/buildClassName';\n\nimport useAsync from '../../../hooks/useAsync';\n\nimport PreBlock from './PreBlock';\nimport CodeOverlay from './CodeOverlay';\n\nimport './CodeBlock.scss';\n\nexport type OwnProps = {\n text: string;\n language?: string;\n noCopy?: boolean;\n};\n\nconst CodeBlock: FC<OwnProps> = ({ text, language, noCopy }) => {\n const [isWordWrap, setWordWrap] = useState(true);\n\n const { result: highlighted } = useAsync(() => {\n if (!language) return Promise.resolve(undefined);\n return import('../../../util/highlightCode')\n .then((lib) => lib.default(text, language));\n }, [language, text]);\n\n const handleWordWrapToggle = useCallback((wrap) => {\n setWordWrap(wrap);\n }, []);\n\n if (!highlighted) {\n return <PreBlock text={text} noCopy={noCopy} />;\n }\n\n const blockClass = buildClassName('code-block', !isWordWrap && 'no-word-wrap');\n\n return (\n <pre className={blockClass}>\n {highlighted}\n <CodeOverlay\n text={text}\n className=\"code-overlay\"\n onWordWrapToggle={handleWordWrapToggle}\n noCopy={noCopy}\n />\n </pre>\n );\n};\n\nexport default memo(CodeBlock);\n","import React from '../../../lib/teact/teact';\nimport { getActions } from '../../../global';\n\nimport type { TextPart } from '../../../types';\nimport type { ApiFormattedText, ApiMessageEntity } from '../../../api/types';\nimport { ApiMessageEntityTypes } from '../../../api/types';\nimport type { ObserveFn } from '../../../hooks/useIntersectionObserver';\nimport type { TextFilter } from './renderText';\n\nimport buildClassName from '../../../util/buildClassName';\nimport renderText from './renderText';\nimport { copyTextToClipboard } from '../../../util/clipboard';\nimport { getTranslation } from '../../../util/langProvider';\n\nimport MentionLink from '../../middle/message/MentionLink';\nimport SafeLink from '../SafeLink';\nimport Spoiler from '../spoiler/Spoiler';\nimport CustomEmoji from '../CustomEmoji';\nimport CodeBlock from '../code/CodeBlock';\n\ninterface IOrganizedEntity {\n entity: ApiMessageEntity;\n organizedIndexes: Set<number>;\n nestedEntities: IOrganizedEntity[];\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 isProtected?: boolean,\n observeIntersection?: ObserveFn,\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(\n entity, entityContent, nestedEntityContent, highlight, messageId, isSimple, isProtected, observeIntersection,\n );\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\nexport function getTextWithEntitiesAsHtml(formattedText?: ApiFormattedText) {\n const { text, entities } = formattedText || {};\n if (!text) {\n return '';\n }\n\n const result = renderTextWithEntities(\n text,\n entities,\n undefined,\n undefined,\n true,\n );\n\n if (Array.isArray(result)) {\n return result.join('');\n }\n\n return result;\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\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\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\nfunction processEntity(\n entity: ApiMessageEntity,\n entityContent: TextPart,\n nestedEntityContent: TextPart[],\n highlight?: string,\n messageId?: number,\n isSimple?: boolean,\n isProtected?: boolean,\n observeIntersection?: ObserveFn,\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\n if (entity.type === ApiMessageEntityTypes.CustomEmoji) {\n return (\n <CustomEmoji documentId={entity.documentId} observeIntersection={observeIntersection}>\n {renderNestedMessagePart()}\n </CustomEmoji>\n );\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 (\n <code\n className={buildClassName('text-entity-code', !isProtected && 'clickable')}\n onClick={!isProtected ? handleCodeClick : undefined}\n role=\"textbox\"\n tabIndex={0}\n >\n {renderNestedMessagePart()}\n </code>\n );\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 <CodeBlock text={entityText} language={entity.language} noCopy={isProtected} />;\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 case ApiMessageEntityTypes.CustomEmoji:\n return (\n <CustomEmoji documentId={entity.documentId} observeIntersection={observeIntersection}>\n {renderNestedMessagePart()}\n </CustomEmoji>\n );\n default:\n return renderNestedMessagePart();\n }\n}\n\nfunction processEntityAsHtml(\n entity: ApiMessageEntity,\n entityContent: TextPart,\n nestedEntityContent: TextPart[],\n) {\n const rawEntityText = typeof entityContent === 'string' ? entityContent : undefined;\n\n // Prevent adding newlines when editing\n const content = entity.type === ApiMessageEntityTypes.Pre ? (entityContent as string).trimEnd() : entityContent;\n\n const renderedContent = nestedEntityContent.length\n ? nestedEntityContent.join('')\n : renderText(content, ['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 `\\`\\`\\`${entity.language || ''}<br/>${renderedContent}<br/>\\`\\`\\`<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\nfunction getLinkUrl(entityContent: string, entity: ApiMessageEntity) {\n const { type } = entity;\n return type === ApiMessageEntityTypes.TextUrl && entity.url ? entity.url : entityContent;\n}\n\nfunction handleBotCommandClick(e: React.MouseEvent<HTMLAnchorElement>) {\n getActions().sendBotCommand({ command: e.currentTarget.innerText });\n}\n\nfunction handleHashtagClick(e: React.MouseEvent<HTMLAnchorElement>) {\n getActions().setLocalTextSearchQuery({ query: e.currentTarget.innerText });\n getActions().searchTextMessagesLocal();\n}\n\nfunction handleCodeClick(e: React.MouseEvent<HTMLElement>) {\n copyTextToClipboard(e.currentTarget.innerText);\n getActions().showNotification({\n message: getTranslation('TextCopied'),\n });\n}\n","import type 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 type { FC } from '../../../lib/teact/teact';\nimport React from '../../../lib/teact/teact';\nimport { getActions, withGlobal } from '../../../global';\n\nimport type { ApiChat, ApiUser } from '../../../api/types';\n\nimport { selectUser } from '../../../global/selectors';\n\ntype OwnProps = {\n userId?: string;\n username?: string;\n children: React.ReactNode;\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 } = getActions();\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 type { MouseEvent as ReactMouseEvent, RefObject } from 'react';\n\nimport type { FC } from '../../lib/teact/teact';\nimport React, { useRef, useCallback, useState } from '../../lib/teact/teact';\n\nimport buildClassName from '../../util/buildClassName';\nimport buildStyle from '../../util/buildStyle';\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: React.ReactNode;\n size?: 'default' | 'smaller' | 'tiny';\n color?: (\n 'primary' | 'secondary' | 'gray' | 'danger' | 'translucent' | 'translucent-white' | 'translucent-black' | 'dark'\n );\n backgroundImage?: string;\n id?: string;\n className?: string;\n round?: boolean;\n pill?: boolean;\n fluid?: boolean;\n isText?: boolean;\n isLoading?: boolean;\n ariaLabel?: string;\n ariaControls?: string;\n hasPopup?: boolean;\n href?: string;\n download?: string;\n disabled?: boolean;\n allowDisabledClick?: boolean;\n ripple?: boolean;\n faded?: boolean;\n tabIndex?: number;\n isRtl?: boolean;\n isShiny?: boolean;\n withPremiumGradient?: boolean;\n noPreventDefault?: boolean;\n shouldStopPropagation?: boolean;\n style?: string;\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 id,\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 isShiny,\n withPremiumGradient,\n ariaLabel,\n ariaControls,\n hasPopup,\n href,\n download,\n disabled,\n allowDisabledClick,\n ripple,\n faded,\n tabIndex,\n isRtl,\n noPreventDefault,\n shouldStopPropagation,\n style,\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 allowDisabledClick && 'click-allowed',\n isText && 'text',\n isLoading && 'loading',\n ripple && 'has-ripple',\n faded && 'faded',\n isClicked && 'clicked',\n backgroundImage && 'with-image',\n isShiny && 'shiny',\n withPremiumGradient && 'premium',\n );\n\n const handleClick = useCallback((e: ReactMouseEvent<HTMLButtonElement, MouseEvent>) => {\n if ((allowDisabledClick || !disabled) && onClick) {\n onClick(e);\n }\n\n if (shouldStopPropagation) e.stopPropagation();\n\n setIsClicked(true);\n setTimeout(() => {\n setIsClicked(false);\n }, CLICKED_TIMEOUT);\n }, [allowDisabledClick, disabled, onClick, shouldStopPropagation]);\n\n const handleMouseDown = useCallback((e: ReactMouseEvent<HTMLButtonElement>) => {\n if (!noPreventDefault) e.preventDefault();\n\n if ((allowDisabledClick || !disabled) && onMouseDown) {\n onMouseDown(e);\n }\n }, [allowDisabledClick, disabled, noPreventDefault, onMouseDown]);\n\n if (href) {\n return (\n <a\n ref={elementRef as RefObject<HTMLAnchorElement>}\n id={id}\n className={fullClassName}\n href={href}\n title={ariaLabel}\n download={download}\n tabIndex={tabIndex}\n dir={isRtl ? 'rtl' : undefined}\n aria-label={ariaLabel}\n aria-controls={ariaControls}\n style={style}\n >\n {children}\n {!disabled && ripple && (\n <RippleEffect />\n )}\n </a>\n );\n }\n\n return (\n <button\n ref={elementRef as RefObject<HTMLButtonElement>}\n id={id}\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 aria-controls={ariaControls}\n aria-haspopup={hasPopup}\n title={ariaLabel}\n tabIndex={tabIndex}\n dir={isRtl ? 'rtl' : undefined}\n style={buildStyle(backgroundImage && `background-image: url(${backgroundImage})`)}\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 type { ChangeEvent } from 'react';\nimport type { FC, TeactNode } from '../../lib/teact/teact';\nimport React, { 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: TeactNode;\n subLabel?: string;\n checked: boolean;\n disabled?: boolean;\n tabIndex?: number;\n round?: boolean;\n blocking?: boolean;\n isLoading?: boolean;\n withCheckedCallback?: boolean;\n className?: string;\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 tabIndex,\n disabled,\n round,\n blocking,\n isLoading,\n className,\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 labelClassName = buildClassName(\n 'Checkbox',\n disabled && 'disabled',\n round && 'round',\n isLoading && 'loading',\n blocking && 'blocking',\n className,\n );\n\n return (\n <label className={labelClassName} 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 tabIndex={tabIndex}\n onChange={handleChange}\n />\n <div className=\"Checkbox-main\">\n <span className=\"label\" dir=\"auto\">{typeof label === 'string' ? renderText(label) : 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 type { FC } from '../../lib/teact/teact';\nimport React, { useState, useRef, useCallback } 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: React.ReactNode;\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 = useCallback(() => {\n setIsOpen(false);\n if (onClose) onClose();\n }, [onClose]);\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 || Boolean(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 type {\n ChangeEvent, FormEvent, RefObject,\n} from 'react';\nimport type { FC } from '../../lib/teact/teact';\nimport React, { 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 tabIndex?: number;\n teactExperimentControlled?: boolean;\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 tabIndex,\n teactExperimentControlled,\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 tabIndex={tabIndex}\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 aria-label={labelText}\n teactExperimentControlled={teactExperimentControlled}\n />\n {labelText && (\n <label htmlFor={id}>{labelText}</label>\n )}\n </div>\n );\n};\n\nexport default memo(InputText);\n","// extracted by mini-css-extract-plugin\nexport default {\"link\":\"h_qmZuKBrM7SWOEcmH68\",\"isPrimary\":\"iZ_WxIDQyqM2SOYqu4Y8\"};","import type { FC } from '../../lib/teact/teact';\nimport React, { useCallback } from '../../lib/teact/teact';\n\nimport buildClassName from '../../util/buildClassName';\n\nimport styles from './Link.module.scss';\n\ntype OwnProps = {\n children: React.ReactNode;\n className?: string;\n isRtl?: boolean;\n isPrimary?: boolean;\n onClick?: (e: React.MouseEvent<HTMLAnchorElement>) => void;\n};\n\nconst Link: FC<OwnProps> = ({\n children, isPrimary, 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(styles.link, className, isPrimary && styles.isPrimary)}\n dir={isRtl ? 'rtl' : 'auto'}\n onClick={onClick ? handleClick : undefined}\n >\n {children}\n </a>\n );\n};\n\nexport default Link;\n","import type { FC } from '../../lib/teact/teact';\nimport React, { 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 type { RefObject } from 'react';\nimport type { FC } from '../../lib/teact/teact';\nimport React, { 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 buildStyle from '../../util/buildStyle';\nimport { dispatchHeavyAnimationEvent } from '../../hooks/useHeavyAnimationCheck';\nimport useHistoryBack from '../../hooks/useHistoryBack';\nimport { preventMessageInputBlurWithBubbling } from '../middle/helpers/preventMessageInputBlur';\nimport { IS_BACKDROP_BLUR_SUPPORTED, IS_COMPACT_MENU } from '../../util/environment';\n\nimport './Menu.scss';\n\ntype OwnProps = {\n ref?: RefObject<HTMLDivElement>;\n containerRef?: RefObject<HTMLElement>;\n isOpen: boolean;\n id?: string;\n className?: string;\n style?: string;\n bubbleStyle?: string;\n ariaLabelledBy?: 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 noCompact?: 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: React.ReactNode;\n};\n\nconst ANIMATION_DURATION = 200;\n\nconst Menu: FC<OwnProps> = ({\n ref,\n containerRef,\n isOpen,\n id,\n className,\n style,\n bubbleStyle,\n ariaLabelledBy,\n children,\n transformOriginX,\n transformOriginY,\n positionX = 'left',\n positionY = 'top',\n autoClose = false,\n footer,\n noCloseOnBackdrop = false,\n noCompact,\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 ? captureEscKeyListener(onClose) : undefined),\n [isOpen, onClose],\n );\n\n useHistoryBack({\n isActive: isOpen,\n onBack: onClose,\n shouldBeReplaced: true,\n });\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 id={id}\n className={buildClassName(\n 'Menu no-selection',\n !noCompact && IS_COMPACT_MENU && 'compact',\n !IS_BACKDROP_BLUR_SUPPORTED && 'no-blur',\n className,\n )}\n style={style}\n aria-labelledby={ariaLabelledBy}\n role={ariaLabelledBy ? 'menu' : undefined}\n onKeyDown={isOpen ? handleKeyDown : undefined}\n onMouseEnter={onMouseEnter}\n onMouseLeave={isOpen ? onMouseLeave : undefined}\n >\n {isOpen && (\n // This only prevents click events triggering on underlying elements\n <div className=\"backdrop\" onMouseDown={preventMessageInputBlurWithBubbling} />\n )}\n <div\n role=\"presentation\"\n ref={menuRef}\n className={bubbleClassName}\n style={buildStyle(\n `transform-origin: ${transformOriginXStyle || positionX} ${transformOriginYStyle || positionY}`,\n bubbleStyle,\n )}\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 type { FC } from '../../lib/teact/teact';\nimport React, { useCallback } from '../../lib/teact/teact';\n\nimport { IS_TEST } from '../../config';\nimport buildClassName from '../../util/buildClassName';\nimport useLang from '../../hooks/useLang';\nimport { IS_COMPACT_MENU } from '../../util/environment';\n\nimport './MenuItem.scss';\n\ntype OnClickHandler = (e: React.SyntheticEvent<HTMLDivElement | HTMLAnchorElement>) => void;\n\ntype OwnProps = {\n icon?: string;\n customIcon?: React.ReactNode;\n className?: string;\n children: React.ReactNode;\n onClick?: OnClickHandler;\n onContextMenu?: (e: React.UIEvent) => void;\n href?: string;\n download?: string;\n disabled?: boolean;\n destructive?: boolean;\n ariaLabel?: string;\n withWrap?: boolean;\n};\n\nconst MenuItem: FC<OwnProps> = (props) => {\n const {\n icon,\n customIcon,\n className,\n children,\n onClick,\n href,\n download,\n disabled,\n destructive,\n ariaLabel,\n withWrap,\n onContextMenu,\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 IS_COMPACT_MENU && 'compact',\n withWrap && 'wrap',\n );\n\n const content = (\n <>\n {!customIcon && icon && (\n <i className={`icon-${icon}`} data-char={icon.startsWith('char-') ? icon.replace('char-', '') : undefined} />\n )}\n {customIcon}\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) || IS_TEST ? '_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=\"menuitem\"\n tabIndex={0}\n className={fullClassName}\n onClick={handleClick}\n onKeyDown={handleKeyDown}\n onContextMenu={onContextMenu}\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 type { FC } from '../../lib/teact/teact';\nimport React, {\n 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 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 type { FC } from '../../lib/teact/teact';\nimport React 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","import type { RefObject } from 'react';\nimport type { FC } from '../../lib/teact/teact';\nimport React, { useLayoutEffect, useRef } from '../../lib/teact/teact';\nimport { getGlobal } from '../../global';\nimport type { GlobalState } from '../../global/types';\n\nimport { ANIMATION_LEVEL_MIN } from '../../config';\nimport buildClassName from '../../util/buildClassName';\nimport forceReflow from '../../util/forceReflow';\nimport { waitForAnimationEnd, waitForTransitionEnd } from '../../util/cssAnimationEndListeners';\nimport useForceUpdate from '../../hooks/useForceUpdate';\nimport usePrevious from '../../hooks/usePrevious';\nimport { dispatchHeavyAnimationEvent } from '../../hooks/useHeavyAnimationCheck';\n\nimport './Transition.scss';\n\nexport type ChildrenFn = (isActive: boolean, isFrom: boolean, currentKey: number) => React.ReactNode;\nexport type TransitionProps = {\n ref?: RefObject<HTMLDivElement>;\n activeKey: number;\n name: (\n 'none' | 'slide' | 'slide-rtl' | 'mv-slide' | 'slide-fade' | 'zoom-fade' | 'slide-layers'\n | 'fade' | 'push-slide' | 'reveal' | 'slide-optimized' | 'slide-optimized-rtl'\n );\n direction?: 'auto' | 'inverse' | 1 | -1;\n renderCount?: number;\n shouldRestoreHeight?: boolean;\n shouldCleanup?: boolean;\n cleanupExceptionKey?: number;\n isDisabled?: boolean;\n id?: string;\n className?: string;\n onStart?: NoneToVoidFunction;\n onStop?: NoneToVoidFunction;\n children: React.ReactNode | ChildrenFn;\n};\n\nconst classNames = {\n active: 'Transition__slide--active',\n};\n\nconst Transition: FC<TransitionProps> = ({\n ref,\n activeKey,\n name,\n direction = 'auto',\n renderCount,\n shouldRestoreHeight,\n shouldCleanup,\n cleanupExceptionKey,\n id,\n className,\n onStart,\n onStop,\n children,\n}) => {\n // No need for a container to update on change\n const { animationLevel } = getGlobal().settings.byKey;\n const currentKeyRef = useRef<number>();\n\n // eslint-disable-next-line no-null/no-null\n let containerRef = useRef<HTMLDivElement>(null);\n if (ref) {\n containerRef = ref;\n }\n\n const rendersRef = useRef<Record<number, React.ReactNode | ChildrenFn>>({});\n const prevActiveKey = usePrevious<any>(activeKey);\n const forceUpdate = useForceUpdate();\n\n const activeKeyChanged = prevActiveKey !== undefined && activeKey !== prevActiveKey;\n\n if (!renderCount && activeKeyChanged) {\n rendersRef.current = { [prevActiveKey]: rendersRef.current[prevActiveKey] };\n }\n\n rendersRef.current[activeKey] = children;\n\n useLayoutEffect(() => {\n function cleanup() {\n if (!shouldCleanup) {\n return;\n }\n\n const preservedRender = cleanupExceptionKey !== undefined ? rendersRef.current[cleanupExceptionKey] : undefined;\n\n rendersRef.current = preservedRender ? { [cleanupExceptionKey!]: preservedRender } : {};\n\n forceUpdate();\n }\n\n const container = containerRef.current!;\n\n const childElements = container.children;\n if (childElements.length === 1 && !activeKeyChanged) {\n if (name.startsWith('slide-optimized')) {\n (childElements[0] as HTMLElement).style.transition = 'none';\n (childElements[0] as HTMLElement).style.transform = 'translate3d(0, 0, 0)';\n }\n\n childElements[0].classList.add(classNames.active);\n\n return;\n }\n\n const childNodes = Array.from(container.childNodes);\n\n if (!activeKeyChanged || !childNodes.length) {\n return;\n }\n\n currentKeyRef.current = activeKey;\n\n const isBackwards = (\n direction === -1\n || (direction === 'auto' && prevActiveKey > activeKey)\n || (direction === 'inverse' && prevActiveKey < activeKey)\n );\n\n const keys = Object.keys(rendersRef.current).map(Number);\n const prevActiveIndex = renderCount ? prevActiveKey : keys.indexOf(prevActiveKey);\n const activeIndex = renderCount ? activeKey : keys.indexOf(activeKey);\n\n if (name === 'slide-optimized' || name === 'slide-optimized-rtl') {\n performSlideOptimized(\n animationLevel,\n name,\n isBackwards,\n cleanup,\n activeKey,\n currentKeyRef,\n container,\n shouldRestoreHeight,\n onStart,\n onStop,\n childNodes[activeIndex] as HTMLElement,\n childNodes[prevActiveIndex] as HTMLElement,\n );\n\n return;\n }\n\n container.classList.remove('animating');\n container.classList.toggle('backwards', isBackwards);\n\n if (name === 'none' || animationLevel === ANIMATION_LEVEL_MIN) {\n childNodes.forEach((node, i) => {\n if (node instanceof HTMLElement) {\n node.classList.remove('from', 'through', 'to');\n node.classList.toggle(classNames.active, i === activeIndex);\n }\n });\n\n cleanup();\n\n return;\n }\n\n childNodes.forEach((node, i) => {\n if (node instanceof HTMLElement) {\n node.classList.remove(classNames.active);\n node.classList.toggle('from', i === prevActiveIndex);\n node.classList.toggle('through', (\n (i > prevActiveIndex && i < activeIndex) || (i < prevActiveIndex && i > activeIndex)\n ));\n node.classList.toggle('to', i === activeIndex);\n }\n });\n\n const dispatchHeavyAnimationStop = dispatchHeavyAnimationEvent();\n\n requestAnimationFrame(() => {\n container.classList.add('animating');\n\n onStart?.();\n\n function onAnimationEnd() {\n requestAnimationFrame(() => {\n if (activeKey !== currentKeyRef.current) {\n return;\n }\n\n container.classList.remove('animating', 'backwards');\n\n childNodes.forEach((node, i) => {\n if (node instanceof HTMLElement) {\n node.classList.remove('from', 'through', 'to');\n node.classList.toggle(classNames.active, i === activeIndex);\n }\n });\n\n if (shouldRestoreHeight) {\n const activeElement = container.querySelector<HTMLDivElement>(`.${classNames.active}`);\n\n if (activeElement) {\n activeElement.style.height = 'auto';\n container.style.height = `${activeElement.clientHeight}px`;\n }\n }\n\n onStop?.();\n dispatchHeavyAnimationStop();\n cleanup();\n });\n }\n\n const watchedNode = name === 'mv-slide'\n ? childNodes[activeIndex]?.firstChild\n : name === 'reveal' && isBackwards\n ? childNodes[prevActiveIndex]\n : childNodes[activeIndex];\n\n if (watchedNode) {\n waitForAnimationEnd(watchedNode, onAnimationEnd);\n } else {\n onAnimationEnd();\n }\n });\n }, [\n activeKey,\n prevActiveKey,\n activeKeyChanged,\n direction,\n name,\n onStart,\n onStop,\n renderCount,\n shouldRestoreHeight,\n shouldCleanup,\n cleanupExceptionKey,\n animationLevel,\n forceUpdate,\n ]);\n\n useLayoutEffect(() => {\n if (shouldRestoreHeight) {\n const container = containerRef.current!;\n const activeElement = container.querySelector<HTMLDivElement>(`.${classNames.active}`)\n || container.querySelector<HTMLDivElement>('.from');\n\n if (activeElement) {\n activeElement.style.height = 'auto';\n container.style.height = `${activeElement.clientHeight}px`;\n container.style.flexBasis = `${activeElement.clientHeight}px`;\n }\n }\n }, [shouldRestoreHeight, children]);\n\n const renders = rendersRef.current;\n const renderKeys = Object.keys(renderCount ? new Array(renderCount).fill(undefined) : renders).map(Number);\n const contents = renderKeys.map((key) => {\n const render = renders[key];\n if (!render) {\n return undefined;\n }\n\n return (\n <div key={key} teactOrderKey={key}>{\n typeof render === 'function'\n ? render(key === activeKey, key === prevActiveKey, activeKey)\n : render\n }\n </div>\n );\n });\n\n return (\n <div\n ref={containerRef}\n id={id}\n className={buildClassName('Transition', className, name)}\n teactFastList={!renderCount}\n >\n {contents}\n </div>\n );\n};\n\nexport default Transition;\n\nfunction performSlideOptimized(\n animationLevel: GlobalState['settings']['byKey']['animationLevel'],\n name: 'slide-optimized' | 'slide-optimized-rtl',\n isBackwards: boolean,\n cleanup: NoneToVoidFunction,\n activeKey: number,\n currentKeyRef: { current: number | undefined },\n container: HTMLElement,\n shouldRestoreHeight?: boolean,\n onStart?: NoneToVoidFunction,\n onStop?: NoneToVoidFunction,\n toSlide?: HTMLElement,\n fromSlide?: HTMLElement,\n) {\n if (!fromSlide || !toSlide) {\n return;\n }\n\n if (animationLevel === ANIMATION_LEVEL_MIN) {\n fromSlide.style.transition = 'none';\n fromSlide.style.transform = '';\n fromSlide.classList.remove(classNames.active);\n\n toSlide.style.transition = 'none';\n toSlide.style.transform = 'translate3d(0, 0, 0)';\n toSlide.classList.add(classNames.active);\n\n cleanup();\n\n return;\n }\n\n if (name === 'slide-optimized-rtl') {\n isBackwards = !isBackwards;\n }\n\n const dispatchHeavyAnimationStop = dispatchHeavyAnimationEvent();\n\n requestAnimationFrame(() => {\n onStart?.();\n\n fromSlide.style.transition = 'none';\n fromSlide.style.transform = 'translate3d(0, 0, 0)';\n\n toSlide.style.transition = 'none';\n toSlide.style.transform = `translate3d(${isBackwards ? '-' : ''}100%, 0, 0)`;\n\n forceReflow(toSlide);\n\n fromSlide.style.transition = '';\n fromSlide.style.transform = `translate3d(${isBackwards ? '' : '-'}100%, 0, 0)`;\n\n toSlide.style.transition = '';\n toSlide.style.transform = 'translate3d(0, 0, 0)';\n\n fromSlide.classList.remove(classNames.active);\n toSlide.classList.add(classNames.active);\n\n waitForTransitionEnd(fromSlide, () => {\n if (activeKey !== currentKeyRef.current) {\n return;\n }\n\n fromSlide.style.transition = 'none';\n fromSlide.style.transform = '';\n\n if (shouldRestoreHeight) {\n toSlide.style.height = 'auto';\n container.style.height = `${toSlide.clientHeight}px`;\n }\n\n onStop?.();\n dispatchHeavyAnimationStop();\n cleanup();\n });\n });\n}\n","import type { ApiLimitType } from './global/types';\n\nexport const APP_NAME = process.env.APP_NAME || 'Telegram WebZ';\nexport const APP_VERSION = process.env.APP_VERSION!;\nexport const RELEASE_DATETIME = process.env.RELEASE_DATETIME;\n\nexport const PRODUCTION_HOSTNAME = 'web.telegram.org';\n\nexport const DEBUG = process.env.APP_ENV !== 'production';\nexport const DEBUG_MORE = false;\n\nexport const IS_MOCKED_CLIENT = process.env.APP_MOCKED_CLIENT === '1';\nexport const IS_TEST = process.env.APP_ENV === 'test';\nexport const IS_PERF = process.env.APP_ENV === 'perf';\nexport const IS_BETA = process.env.APP_ENV === 'staging';\n\nexport const BETA_CHANGELOG_URL = 'https://telegra.ph/WebZ-Beta-04-01';\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 PAGE_TITLE = 'Telegram';\nexport const INACTIVE_MARKER = ' [Inactive]';\n\nexport const DEBUG_PAYMENT_SMART_GLOCAL = false;\n\nexport const SESSION_USER_KEY = 'user_auth';\nexport const LEGACY_SESSION_KEY = 'GramJs:sessionId';\nexport const PASSCODE_CACHE_NAME = 'tt-passcode';\n\nexport const GLOBAL_STATE_CACHE_DISABLED = false;\nexport const GLOBAL_STATE_CACHE_KEY = 'tt-global-state';\nexport const GLOBAL_STATE_CACHE_USER_LIST_LIMIT = 500;\nexport const GLOBAL_STATE_CACHE_CHAT_LIST_LIMIT = 200;\nexport const GLOBAL_STATE_CACHE_CHATS_WITH_MESSAGES_LIMIT = 30;\nexport const GLOBAL_STATE_CACHE_CUSTOM_EMOJI_LIMIT = 150;\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-v13';\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;\nexport const REACTION_UNREAD_SLICE = 100;\nexport const MENTION_UNREAD_SLICE = 100;\n\nexport const TOP_CHAT_MESSAGES_PRELOAD_LIMIT = 20;\n\nexport const SPONSORED_MESSAGE_CACHE_MS = 300000; // 5 min\n\nexport const DEFAULT_VOLUME = 1;\nexport const DEFAULT_PLAYBACK_RATE = 1;\nexport const PLAYBACK_RATE_FOR_AUDIO_MIN_DURATION = 20 * 60; // 20 min\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// eslint-disable-next-line max-len\nexport const EDITABLE_INPUT_CSS_SELECTOR = `.messages-layout .Transition__slide--active #${EDITABLE_INPUT_ID}, .messages-layout .Transition > .to #${EDITABLE_INPUT_ID}`;\n\nexport const CUSTOM_APPENDIX_ATTRIBUTE = 'data-has-custom-appendix';\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 MAX_SCREEN_WIDTH_FOR_EXPAND_PINNED_MESSAGES = 1340; // 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_MIN_ID = 1e11; // `Date.now()` is always used as base\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 LOCK_SCREEN_ANIMATION_DURATION_MS = 200;\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 EMOJI_SIZE_PICKER = 40;\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 EMOJI_SIZE_MODAL = 40;\nexport const STICKER_SIZE_TWO_FA = 160;\nexport const STICKER_SIZE_PASSCODE = 160;\nexport const STICKER_SIZE_DISCUSSION_GROUPS = 140;\nexport const STICKER_SIZE_FOLDER_SETTINGS = 100;\nexport const STICKER_SIZE_INLINE_BOT_RESULT = 100;\nexport const STICKER_SIZE_JOIN_REQUESTS = 140;\nexport const STICKER_SIZE_INVITES = 140;\nexport const RECENT_STICKERS_LIMIT = 20;\nexport const RECENT_SYMBOL_SET_ID = 'recent';\nexport const FAVORITE_SYMBOL_SET_ID = 'favorite';\nexport const CHAT_STICKER_SET_ID = 'chatStickers';\nexport const PREMIUM_STICKER_SET_ID = 'premium';\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';\nexport const VIDEO_WEBM_TYPE = 'video/webm';\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 SUPPORTED_AUDIO_CONTENT_TYPES = new Set([\n 'audio/mp3',\n 'audio/ogg',\n 'audio/wav',\n 'audio/mpeg',\n 'audio/flac',\n 'audio/aac',\n 'audio/m4a',\n 'audio/mp4',\n 'audio/x-m4a',\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:(\\/\\/)?/;\nexport const RE_TME_LINK = /^(https?:\\/\\/)?([-a-zA-Z0-9@:%_+~#=]{1,32}\\.)?t\\.me/;\nexport const RE_TELEGRAM_LINK = /^(https?:\\/\\/)?telegram\\.org\\//;\nexport const TME_LINK_PREFIX = 'https://t.me/';\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\nexport const API_CHAT_TYPES = ['bots', 'channels', 'chats', 'users'] as const;\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 FEEDBACK_URL = 'https://bugs.telegram.org/?tag_ids=41&sort=time';\n\nexport const LIGHT_THEME_BG_COLOR = '#99BA92';\nexport const DARK_THEME_BG_COLOR = '#0F0F0F';\nexport const DEFAULT_PATTERN_COLOR = '#4A8E3A8C';\nexport const DARK_THEME_PATTERN_COLOR = '#0A0A0A8C';\nexport const MAX_UPLOAD_FILEPART_SIZE = 524288;\n\n// Group calls\nexport const GROUP_CALL_VOLUME_MULTIPLIER = 100;\nexport const GROUP_CALL_DEFAULT_VOLUME = 100 * GROUP_CALL_VOLUME_MULTIPLIER;\nexport const GROUP_CALL_THUMB_VIDEO_DISABLED = true;\n\nexport const DEFAULT_LIMITS: Record<ApiLimitType, readonly [number, number]> = {\n uploadMaxFileparts: [4000, 8000],\n stickersFaved: [5, 10],\n savedGifs: [200, 400],\n dialogFiltersChats: [100, 200],\n dialogFilters: [10, 20],\n dialogFolderPinned: [5, 10],\n captionLength: [1024, 2048],\n channels: [500, 1000],\n channelsPublic: [10, 20],\n aboutLength: [70, 140],\n};\n","import {\n addActionHandler, getActions, getGlobal, setGlobal,\n} from '../../index';\n\nimport { initApi, callApi } from '../../../api/gramjs';\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 LOCK_SCREEN_ANIMATION_DURATION_MS,\n} from '../../../config';\nimport {\n IS_MOV_SUPPORTED, IS_WEBM_SUPPORTED, MAX_BUFFER_SIZE, PLATFORM_ENV,\n} 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';\nimport { clearGlobalForLockScreen, updatePasscodeSettings } from '../../reducers';\nimport { clearEncryptedSession, encryptSession, forgetPasscode } from '../../../util/passcode';\nimport { serializeGlobal } from '../../cache';\n\naddActionHandler('initApi', async (global, actions) => {\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 isWebmSupported: IS_WEBM_SUPPORTED,\n maxBufferSize: MAX_BUFFER_SIZE,\n });\n});\n\naddActionHandler('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\naddActionHandler('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\naddActionHandler('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\naddActionHandler('uploadProfilePhoto', (global, actions, payload) => {\n const { file } = payload!;\n\n void callApi('uploadProfilePhoto', file);\n});\n\naddActionHandler('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\naddActionHandler('returnToAuthPhoneNumber', (global) => {\n void callApi('restartAuth');\n\n return {\n ...global,\n authError: undefined,\n };\n});\n\naddActionHandler('goToAuthQrCode', (global) => {\n void callApi('restartAuthWithQr');\n\n return {\n ...global,\n authIsLoadingQrCode: true,\n authError: undefined,\n };\n});\n\naddActionHandler('saveSession', (global, actions, payload) => {\n if (global.passcode.isScreenLocked) {\n return;\n }\n\n const { sessionData } = payload;\n if (sessionData) {\n storeSession(payload.sessionData, global.currentUserId);\n } else {\n clearStoredSession();\n }\n});\n\naddActionHandler('signOut', async (_global, actions, payload) => {\n if ('hangUp' in actions) actions.hangUp();\n if ('leaveGroupCall' in actions) actions.leaveGroupCall();\n\n try {\n await unsubscribe();\n await callApi('destroy');\n await forceWebsync(false);\n } catch (err) {\n // Do nothing\n }\n\n getActions().reset();\n\n if (payload?.forceInitApi) {\n getActions().initApi();\n }\n});\n\naddActionHandler('reset', () => {\n clearStoredSession();\n clearEncryptedSession();\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 getActions().init();\n});\n\naddActionHandler('disconnect', () => {\n void callApi('disconnect');\n});\n\naddActionHandler('loadNearestCountry', async (global) => {\n if (global.connectionState !== 'connectionStateReady') {\n return;\n }\n\n const authNearestCountry = await callApi('fetchNearestCountry');\n\n setGlobal({\n ...getGlobal(),\n authNearestCountry,\n });\n});\n\naddActionHandler('setDeviceToken', (global, actions, deviceToken) => {\n return {\n ...global,\n push: {\n deviceToken,\n subscribedAt: Date.now(),\n },\n };\n});\n\naddActionHandler('deleteDeviceToken', (global) => {\n return {\n ...global,\n push: undefined,\n };\n});\n\naddActionHandler('lockScreen', async (global) => {\n const sessionJson = JSON.stringify({ ...loadStoredSession(), userId: global.currentUserId });\n const globalJson = serializeGlobal(global);\n\n await encryptSession(sessionJson, globalJson);\n forgetPasscode();\n clearStoredSession();\n updateAppBadge(0);\n\n global = getGlobal();\n setGlobal(updatePasscodeSettings(\n global,\n {\n isScreenLocked: true,\n invalidAttemptsCount: 0,\n },\n ));\n\n setTimeout(() => {\n setGlobal(clearGlobalForLockScreen(getGlobal()));\n }, LOCK_SCREEN_ANIMATION_DURATION_MS);\n\n try {\n await unsubscribe();\n await callApi('destroy', true);\n } catch (err) {\n // Do nothing\n }\n});\n","import { addActionHandler, getGlobal, setGlobal } from '../../index';\n\nimport type { GlobalState } from '../../types';\nimport type {\n ApiPrivacyKey, PrivacyVisibility, InputPrivacyRules, InputPrivacyContact,\n} from '../../../types';\nimport {\n ProfileEditProgress,\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\naddActionHandler('updateProfile', async (global, actions, payload) => {\n const {\n photo, firstName, lastName, bio: about, username,\n } = payload!;\n\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\naddActionHandler('checkUsername', async (global, actions, payload) => {\n const { username } = payload!;\n\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\naddActionHandler('loadWallpapers', 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\naddActionHandler('uploadWallpaper', async (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 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\naddActionHandler('loadBlockedContacts', async (global) => {\n const result = await callApi('fetchBlockedContacts');\n if (!result) {\n return;\n }\n\n global = getGlobal();\n\n if (result.users?.length) {\n global = addUsers(global, buildCollectionByKey(result.users, 'id'));\n }\n if (result.chats?.length) {\n global = updateChats(global, buildCollectionByKey(result.chats, 'id'));\n }\n\n global = {\n ...global,\n blocked: {\n ...global.blocked,\n ids: [...(global.blocked.ids || []), ...result.blockedIds],\n totalCount: result.totalCount,\n },\n };\n\n setGlobal(global);\n});\n\naddActionHandler('blockContact', async (global, actions, payload) => {\n const { contactId, accessHash } = payload!;\n\n const result = await callApi('blockContact', contactId, accessHash);\n if (!result) {\n return;\n }\n\n setGlobal(addBlockedContact(getGlobal(), contactId));\n});\n\naddActionHandler('unblockContact', async (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 const result = await callApi('unblockContact', contactId, accessHash);\n if (!result) {\n return;\n }\n\n setGlobal(removeBlockedContact(getGlobal(), contactId));\n});\n\naddActionHandler('loadNotificationExceptions', async (global) => {\n const { serverTimeOffset } = global;\n\n const result = await callApi('fetchNotificationExceptions', { serverTimeOffset });\n if (!result) {\n return;\n }\n\n setGlobal(addNotifyExceptions(getGlobal(), result));\n});\n\naddActionHandler('loadNotificationSettings', async (global) => {\n const { serverTimeOffset } = global;\n const result = await callApi('fetchNotificationSettings', {\n serverTimeOffset,\n });\n if (!result) {\n return;\n }\n\n setGlobal(replaceSettings(getGlobal(), result));\n});\n\naddActionHandler('updateNotificationSettings', async (global, actions, payload) => {\n const { peerType, isSilent, shouldShowPreviews } = payload!;\n\n const result = await callApi('updateNotificationSettings', peerType, { isSilent, shouldShowPreviews });\n if (!result) {\n return;\n }\n\n setGlobal(updateNotifySettings(getGlobal(), peerType, isSilent, shouldShowPreviews));\n});\n\naddActionHandler('updateWebNotificationSettings', (global, actions, payload) => {\n setGlobal(replaceSettings(global, payload));\n\n const { hasPushNotifications, hasWebNotifications } = global.settings.byKey;\n if (hasWebNotifications && hasPushNotifications) {\n void subscribe();\n } else {\n void unsubscribe();\n }\n});\n\naddActionHandler('updateContactSignUpNotification', async (global, actions, payload) => {\n const { isSilent } = payload!;\n\n const result = await callApi('updateContactSignUpNotification', isSilent);\n if (!result) {\n return;\n }\n\n setGlobal(replaceSettings(getGlobal(), { hasContactJoinedNotifications: !isSilent }));\n});\n\naddActionHandler('loadLanguages', async () => {\n const result = await callApi('fetchLanguages');\n if (!result) {\n return;\n }\n\n setGlobal(replaceSettings(getGlobal(), { languages: result }));\n});\n\naddActionHandler('loadPrivacySettings', async (global) => {\n const [\n phoneNumberSettings,\n lastSeenSettings,\n profilePhotoSettings,\n forwardsSettings,\n chatInviteSettings,\n phoneCallSettings,\n phoneP2PSettings,\n voiceMessagesSettings,\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 callApi('fetchPrivacySettings', 'phoneCall'),\n callApi('fetchPrivacySettings', 'phoneP2P'),\n callApi('fetchPrivacySettings', 'voiceMessages'),\n ]);\n\n if (\n !phoneNumberSettings\n || !lastSeenSettings\n || !profilePhotoSettings\n || !forwardsSettings\n || !chatInviteSettings\n || !phoneCallSettings\n || !phoneP2PSettings\n || !voiceMessagesSettings\n ) {\n return;\n }\n\n global = getGlobal();\n setGlobal({\n ...global,\n settings: {\n ...global.settings,\n privacy: {\n ...global.settings.privacy,\n phoneNumber: phoneNumberSettings,\n lastSeen: lastSeenSettings,\n profilePhoto: profilePhotoSettings,\n forwards: forwardsSettings,\n chatInvite: chatInviteSettings,\n phoneCall: phoneCallSettings,\n phoneP2P: phoneP2PSettings,\n voiceMessages: voiceMessagesSettings,\n },\n },\n });\n});\n\naddActionHandler('setPrivacyVisibility', async (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 const result = await callApi('setPrivacySettings', privacyKey, rules);\n if (!result) {\n return;\n }\n\n global = getGlobal();\n\n setGlobal({\n ...global,\n settings: {\n ...global.settings,\n privacy: {\n ...global.settings.privacy,\n [privacyKey]: result,\n },\n },\n });\n});\n\naddActionHandler('setPrivacySettings', async (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 const result = await callApi('setPrivacySettings', privacyKey, rules);\n if (!result) {\n return;\n }\n\n global = getGlobal();\n\n setGlobal({\n ...global,\n settings: {\n ...global.settings,\n privacy: {\n ...global.settings.privacy,\n [privacyKey]: result,\n },\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\naddActionHandler('updateIsOnline', (global, actions, payload) => {\n callApi('updateIsOnline', payload);\n});\n\naddActionHandler('loadContentSettings', async () => {\n const result = await callApi('fetchContentSettings');\n if (!result) return;\n\n setGlobal(replaceSettings(getGlobal(), result));\n});\n\naddActionHandler('updateContentSettings', async (global, actions, payload) => {\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\naddActionHandler('loadCountryList', async (global, actions, payload = {}) => {\n let { langCode } = payload;\n if (!langCode) langCode = global.settings.byKey.language;\n\n const countryList = await callApi('fetchCountryList', { langCode });\n if (!countryList) return;\n\n setGlobal({\n ...getGlobal(),\n countryList,\n });\n});\n\naddActionHandler('ensureTimeFormat', async (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 if (global.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\naddActionHandler('loadAppConfig', async () => {\n const appConfig = await callApi('fetchAppConfig');\n if (!appConfig) return;\n\n setGlobal({\n ...getGlobal(),\n appConfig,\n });\n});\n\naddActionHandler('loadGlobalPrivacySettings', async () => {\n const globalSettings = await callApi('fetchGlobalPrivacySettings');\n if (!globalSettings) {\n return;\n }\n\n setGlobal(replaceSettings(getGlobal(), {\n shouldArchiveAndMuteNewNonContact: globalSettings.shouldArchiveAndMuteNewNonContact,\n }));\n});\n\naddActionHandler('updateGlobalPrivacySettings', async (global, actions, payload) => {\n const { shouldArchiveAndMuteNewNonContact } = payload;\n setGlobal(replaceSettings(getGlobal(), { shouldArchiveAndMuteNewNonContact }));\n\n const result = await callApi('updateGlobalPrivacySettings', { shouldArchiveAndMuteNewNonContact });\n\n setGlobal(replaceSettings(getGlobal(), {\n shouldArchiveAndMuteNewNonContact: !result\n ? !shouldArchiveAndMuteNewNonContact\n : result.shouldArchiveAndMuteNewNonContact,\n }));\n});\n","import {\n addActionHandler, getActions, getGlobal, setGlobal,\n} from '../../index';\n\nimport type { GlobalState } from '../../types';\n\nimport type {\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, shouldClosePaymentModal } from '../../../util/getReadableErrorText';\n\naddActionHandler('apiUpdate', (global, actions, update) => {\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 (shouldClosePaymentModal(update.error)) {\n actions.closePaymentModal();\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 });\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 === 'connectionStateBroken') {\n // When mounting Auth `initApi` will be called from an effect. Otherwise, we force it here.\n const isOnAuth = !global.authState || [\n 'authorizationStateWaitPhoneNumber',\n 'authorizationStateWaitCode',\n 'authorizationStateWaitPassword',\n 'authorizationStateWaitRegistration',\n 'authorizationStateWaitQrCode',\n ].includes(global.authState);\n\n getActions().signOut({ forceInitApi: isOnAuth });\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 getActions().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 { addActionHandler, getGlobal, setGlobal } from '../../index';\n\nimport { ANIMATION_LEVEL_MAX } from '../../../config';\nimport {\n IS_ANDROID, IS_IOS, IS_MAC_OS, IS_SAFARI, IS_TOUCH_ENV,\n} from '../../../util/environment';\nimport { setLanguage } from '../../../util/langProvider';\nimport switchTheme from '../../../util/switchTheme';\nimport { selectTheme } from '../../selectors';\nimport { startWebsync } from '../../../util/websync';\n\nconst HISTORY_ANIMATION_DURATION = 450;\n\nsubscribeToSystemThemeChange();\n\naddActionHandler('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 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\naddActionHandler('setInstallPrompt', (global, actions, payload) => {\n const { canInstall } = payload;\n return {\n ...global,\n canInstall,\n };\n});\n\naddActionHandler('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\naddActionHandler('setAuthPhoneNumber', (global, actions, payload) => {\n const { phoneNumber } = payload!;\n\n return {\n ...global,\n authPhoneNumber: phoneNumber,\n };\n});\n\naddActionHandler('setAuthRememberMe', (global, actions, payload) => {\n return {\n ...global,\n authRememberMe: Boolean(payload),\n };\n});\n\naddActionHandler('clearAuthError', (global) => {\n return {\n ...global,\n authError: undefined,\n };\n});\n\naddActionHandler('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 { addActionHandler } from '../../index';\nimport type { ISettings, IThemeSettings, ThemeKey } from '../../../types';\nimport { replaceSettings, replaceThemeSettings } from '../../reducers';\n\naddActionHandler('setSettingOption', (global, actions, payload?: Partial<ISettings>) => {\n return replaceSettings(global, payload);\n});\n\naddActionHandler('setThemeSettings', (global, actions, payload: { theme: ThemeKey } & Partial<IThemeSettings>) => {\n const { theme, ...settings } = payload;\n\n return replaceThemeSettings(global, theme, settings);\n});\n\naddActionHandler('requestNextSettingsScreen', (global, actions, nextScreen) => {\n return {\n ...global,\n settings: {\n ...global.settings,\n nextScreen,\n },\n };\n});\n","import { addCallback, removeCallback } from '../lib/teact/teactn';\n\nimport { addActionHandler, getGlobal } from './index';\n\nimport type { 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_USER_LIST_LIMIT,\n GLOBAL_STATE_CACHE_CHAT_LIST_LIMIT,\n GLOBAL_STATE_CACHE_CHATS_WITH_MESSAGES_LIMIT,\n GLOBAL_STATE_CACHE_CUSTOM_EMOJI_LIMIT,\n ALL_FOLDER_ID,\n ARCHIVED_FOLDER_ID,\n MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN,\n DEFAULT_VOLUME,\n DEFAULT_PLAYBACK_RATE,\n DEFAULT_PATTERN_COLOR,\n DEFAULT_LIMITS,\n} from '../config';\nimport { IS_SINGLE_COLUMN_LAYOUT } from '../util/environment';\nimport { isHeavyAnimating } from '../hooks/useHeavyAnimationCheck';\nimport { pick, unique } from '../util/iteratees';\nimport {\n selectCurrentChat,\n selectCurrentMessageList,\n selectVisibleUsers,\n} from './selectors';\nimport { hasStoredSession } from '../util/sessions';\nimport { INITIAL_STATE } from './initialState';\nimport { parseLocationHash } from '../util/routing';\nimport { isUserId } from './helpers';\nimport { getOrderedIds } from '../util/folderManager';\nimport { clearGlobalForLockScreen } from './reducers';\nimport { encryptSession } from '../util/passcode';\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 const resetCache = () => {\n localStorage.removeItem(GLOBAL_STATE_CACHE_KEY);\n\n if (!isCaching) {\n return;\n }\n\n clearCaching();\n };\n\n addActionHandler('saveSession', () => {\n if (isCaching) {\n return;\n }\n\n setupCaching();\n });\n\n addActionHandler('reset', resetCache);\n}\n\nexport function loadCache(initialState: GlobalState): GlobalState | undefined {\n if (GLOBAL_STATE_CACHE_DISABLED) {\n return undefined;\n }\n\n const cache = readCache(initialState);\n\n if (cache.passcode.hasPasscode || hasStoredSession(true)) {\n setupCaching();\n\n return cache;\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() : undefined;\n\n return {\n ...newState,\n messages: {\n ...newState.messages,\n messageLists: parsedMessageList ? [parsedMessageList] : [],\n },\n };\n}\n\nexport function migrateCache(cached: GlobalState, initialState: GlobalState) {\n // Migrate from legacy setting names\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 // Pre-fill settings with defaults\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.stickers.premium) {\n cached.stickers.premium = initialState.stickers.premium;\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.mediaViewer.volume === undefined) {\n cached.mediaViewer.volume = DEFAULT_VOLUME;\n }\n\n if (cached.mediaViewer.playbackRate === undefined) {\n cached.mediaViewer.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 if (!cached.pollModal) {\n cached.pollModal = {\n isOpen: false,\n };\n }\n\n if (!cached.attachMenu) {\n cached.attachMenu = {\n bots: {},\n };\n }\n\n if (!cached.trustedBotIds) {\n cached.trustedBotIds = [];\n }\n\n if (!cached.passcode) {\n cached.passcode = {};\n }\n\n if (cached.activeSessions?.byHash === undefined) {\n cached.activeSessions = {\n byHash: {},\n orderedHashes: [],\n };\n }\n\n if (!cached.activeWebSessions) {\n cached.activeWebSessions = {\n byHash: {},\n orderedHashes: [],\n };\n }\n\n if (!cached.transcriptions) {\n cached.transcriptions = {};\n }\n\n if (cached.appConfig && !cached.appConfig.limits) {\n cached.appConfig.limits = DEFAULT_LIMITS;\n }\n\n if (!cached.customEmojis) {\n cached.customEmojis = {\n added: {},\n byId: {},\n lastRendered: [],\n };\n }\n\n if (!cached.stickers.premiumSet) {\n cached.stickers.premiumSet = {\n stickers: [],\n };\n }\n\n // TODO Remove in Jan 2023 (this was re-designed but can be hardcoded in cache)\n const { light: lightTheme } = cached.settings.themes;\n if (lightTheme?.patternColor === 'rgba(90, 110, 70, 0.6)' || !lightTheme?.patternColor) {\n cached.settings.themes.light = {\n ...lightTheme,\n patternColor: DEFAULT_PATTERN_COLOR,\n };\n }\n\n cached.serviceNotifications.forEach((notification) => {\n const { isHidden } = notification as any;\n if (isHidden) {\n notification.isDeleted = isHidden;\n }\n });\n}\n\nfunction updateCache() {\n const global = getGlobal();\n if (!isCaching || global.isLoggingOut || isHeavyAnimating()) {\n return;\n }\n\n forceUpdateCache();\n}\n\nexport function forceUpdateCache(noEncrypt = false) {\n const global = getGlobal();\n const { hasPasscode, isScreenLocked } = global.passcode;\n const serializedGlobal = serializeGlobal(global);\n\n if (hasPasscode) {\n if (!isScreenLocked && !noEncrypt) {\n void encryptSession(undefined, serializedGlobal);\n }\n\n const serializedGlobalClean = JSON.stringify(clearGlobalForLockScreen(global));\n localStorage.setItem(GLOBAL_STATE_CACHE_KEY, serializedGlobalClean);\n\n return;\n }\n\n localStorage.setItem(GLOBAL_STATE_CACHE_KEY, serializedGlobal);\n}\n\nexport function serializeGlobal(global: GlobalState) {\n const reducedGlobal: GlobalState = {\n ...INITIAL_STATE,\n ...pick(global, [\n 'appConfig',\n 'authState',\n 'authPhoneNumber',\n 'authRememberMe',\n 'authNearestCountry',\n 'currentUserId',\n 'contactList',\n 'topPeers',\n 'topInlineBots',\n 'recentEmojis',\n 'recentCustomEmojis',\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 customEmojis: reduceCustomEmojis(global),\n mediaViewer: {\n volume: global.mediaViewer.volume,\n playbackRate: global.mediaViewer.playbackRate,\n isMuted: global.mediaViewer.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 isCallPanelVisible: undefined,\n trustedBotIds: global.trustedBotIds,\n passcode: pick(global.passcode, [\n 'isScreenLocked',\n 'hasPasscode',\n 'invalidAttemptsCount',\n ]),\n };\n\n return JSON.stringify(reducedGlobal);\n}\n\nfunction reduceCustomEmojis(global: GlobalState): GlobalState['customEmojis'] {\n const { lastRendered, byId } = global.customEmojis;\n const idsToSave = lastRendered.slice(0, GLOBAL_STATE_CACHE_CUSTOM_EMOJI_LIMIT);\n const byIdToSave = pick(byId, idsToSave);\n\n return {\n byId: byIdToSave,\n lastRendered: idsToSave,\n added: {},\n };\n}\n\nfunction reduceShowChatInfo(global: GlobalState): boolean {\n return window.innerWidth > MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN\n ? global.isChatInfoShown\n : false;\n}\n\nfunction reduceUsers(global: GlobalState): GlobalState['users'] {\n const { users: { byId, statusesById }, currentUserId } = global;\n const { chatId: currentChatId } = selectCurrentMessageList(global) || {};\n const visibleUserIds = selectVisibleUsers(global)?.map(({ id }) => id);\n\n const idsToSave = unique([\n ...currentUserId ? [currentUserId] : [],\n ...currentChatId && isUserId(currentChatId) ? [currentChatId] : [],\n ...visibleUserIds || [],\n ...global.topPeers.userIds || [],\n ...getOrderedIds(ALL_FOLDER_ID)?.filter(isUserId) || [],\n ...getOrderedIds(ARCHIVED_FOLDER_ID)?.filter(isUserId) || [],\n ...global.contactList?.userIds || [],\n ...global.globalSearch.recentlyFoundChatIds?.filter(isUserId) || [],\n ...Object.keys(byId),\n ]).slice(0, GLOBAL_STATE_CACHE_USER_LIST_LIMIT);\n\n return {\n byId: pick(byId, idsToSave),\n statusesById: pick(statusesById, idsToSave),\n };\n}\n\nfunction reduceChats(global: GlobalState): GlobalState['chats'] {\n const { chats: { byId }, currentUserId } = global;\n const currentChat = selectCurrentChat(global);\n const idsToSave = unique([\n ...currentUserId ? [currentUserId] : [],\n ...currentChat ? [currentChat.id] : [],\n ...getOrderedIds(ALL_FOLDER_ID) || [],\n ...getOrderedIds(ARCHIVED_FOLDER_ID) || [],\n ...global.globalSearch.recentlyFoundChatIds || [],\n ...Object.keys(byId),\n ]).slice(0, GLOBAL_STATE_CACHE_CHAT_LIST_LIMIT);\n\n return {\n ...global.chats,\n isFullyLoaded: {},\n byId: pick(global.chats.byId, idsToSave),\n };\n}\n\nfunction reduceMessages(global: GlobalState): GlobalState['messages'] {\n const { currentUserId } = global;\n const byChatId: GlobalState['messages']['byChatId'] = {};\n const { chatId: currentChatId, threadId, type } = selectCurrentMessageList(global) || {};\n const chatIdsToSave = [\n ...currentChatId ? [currentChatId] : [],\n ...currentUserId ? [currentUserId] : [],\n ...getOrderedIds(ALL_FOLDER_ID)?.slice(0, GLOBAL_STATE_CACHE_CHATS_WITH_MESSAGES_LIMIT) || [],\n ];\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: currentChatId && threadId && type ? [{ chatId: currentChatId, threadId, type }] : [],\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 };\n}\n\nfunction reduceAvailableReactions(global: GlobalState): GlobalState['availableReactions'] {\n return global.availableReactions\n ?.map((r) => pick(r, ['reaction', 'staticIcon', 'title', 'isInactive']));\n}\n","import type {\n ApiChat,\n ApiUser,\n ApiChatBannedRights,\n ApiChatAdminRights,\n ApiChatFolder,\n} from '../../api/types';\nimport {\n MAIN_THREAD_ID,\n} from '../../api/types';\n\nimport type { NotifyException, NotifySettings } from '../../types';\nimport type { LangFn } from '../../hooks/useLang';\n\nimport { ARCHIVED_FOLDER_ID, REPLIES_USER_ID, TME_LINK_PREFIX } from '../../config';\nimport { orderBy } from '../../util/iteratees';\nimport { getUserFirstOrLastName } from './users';\nimport { formatDateToString, formatTime } from '../../util/dateFormat';\nimport { prepareSearchWordsForNeedle } from '../../util/searchWords';\nimport { getVideoAvatarMediaHash } from './media';\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 `${TME_LINK_PREFIX}${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 type: 'photo' | 'video' = 'photo',\n) {\n if (!owner.avatarHash) {\n return undefined;\n }\n const { fullInfo } = owner;\n\n if (type === 'video') {\n if (fullInfo?.profilePhoto?.isVideo) {\n return getVideoAvatarMediaHash(fullInfo.profilePhoto);\n }\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.isForbidden || 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 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 getFolderDescriptionText(lang: LangFn, folder: ApiChatFolder, chatsCount?: number) {\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 chatsCount !== undefined && (\n Object.values(filters).filter(Boolean).length > 1\n || (excludedChatIds?.length)\n || (includedChatIds?.length)\n )) {\n return lang('Chats', chatsCount);\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\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 type {\n ApiChat, ApiMessage, ApiMessageEntityTextUrl, ApiReactions, ApiUser,\n} from '../../api/types';\nimport { ApiMessageEntityTypes } from '../../api/types';\nimport type { LangFn } from '../../hooks/useLang';\n\nimport {\n CONTENT_NOT_SUPPORTED,\n LOCAL_MESSAGE_MIN_ID,\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';\nimport { getGlobal } from '../index';\n\nconst RE_LINK = new RegExp(RE_LINK_TEMPLATE, 'i');\n\nexport type MessageKey = `msg${string}-${number}`;\n\nexport function getMessageHtmlId(messageId: number) {\n return `message${messageId.toString().replace('.', '-')}`;\n}\n\nexport function getMessageKey(message: ApiMessage): MessageKey {\n const { chatId, id, previousLocalId } = message;\n\n return buildMessageKey(chatId, isServiceNotificationMessage(message) ? previousLocalId || id : 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 getMessageTranscription(message: ApiMessage) {\n const { transcriptionId } = message;\n const global = getGlobal();\n\n return transcriptionId && global.transcriptions[transcriptionId]?.text;\n}\n\nexport function getMessageText(message: ApiMessage) {\n const {\n text, sticker, photo, video, audio, voice, document, poll, webPage, contact, invoice, location,\n game, action,\n } = message.content;\n\n if (text) {\n return text.text;\n }\n\n if (sticker || photo || video || audio || voice || document\n || contact || poll || webPage || invoice || location || game || action?.phoneCall) {\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 || text.entities?.length || 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) || text.entities?.length) {\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 const firstTextUrl = text.entities.find((entity): entity is ApiMessageEntityTextUrl => (\n entity.type === ApiMessageEntityTypes.TextUrl\n ));\n if (firstTextUrl) {\n match = firstTextUrl.url.match(RE_LINK);\n }\n\n if (!match) {\n const firstUrl = text.entities.find((entity) => entity.type === ApiMessageEntityTypes.Url);\n if (firstUrl) {\n const { offset, length } = firstUrl;\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 Boolean(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_MIN_ID;\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.isLottie ? 'tgs' : content.sticker.isVideo\n ? 'webm' : 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\nexport function isGeoLiveExpired(message: ApiMessage, timestamp = Date.now() / 1000) {\n const { location } = message.content;\n if (location?.type !== 'geoLive') return false;\n return (timestamp - (message.date || 0) >= location.period);\n}\n\nexport function getMessageSingleInlineButton(message: ApiMessage) {\n return message.inlineButtons?.length === 1\n && message.inlineButtons[0].length === 1\n && message.inlineButtons[0][0];\n}\n","import type { ApiMessage, ApiReactions } from '../../api/types';\nimport type { GlobalState } from '../types';\n\nexport function getMessageRecentReaction(message: Partial<ApiMessage>) {\n return message.isOutgoing ? message.reactions?.recentReactions?.[0] : undefined;\n}\nexport function checkIfHasUnreadReactions(global: GlobalState, reactions: ApiReactions) {\n const { currentUserId } = global;\n return reactions?.recentReactions?.some(\n ({ isUnread, userId }) => isUnread && userId !== currentUserId,\n );\n}\n","import type { ApiMessage } from '../../api/types';\nimport { ApiMessageEntityTypes } from '../../api/types';\nimport { CONTENT_NOT_SUPPORTED } from '../../config';\n\nimport type { TextPart } from '../../types';\nimport type { LangFn } from '../../hooks/useLang';\n\nimport trimText from '../../util/trimText';\nimport { getMessageText, getMessageTranscription } from './messages';\nimport { getMessageRecentReaction } from './reactions';\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 noReactions = true,\n isExtended = false,\n) {\n const emoji = !noEmoji && getMessageSummaryEmoji(message, noReactions);\n const emojiWithSpace = emoji ? `${emoji} ` : '';\n const text = trimText(getMessageTextWithSpoilers(message), truncateLength);\n const description = getMessageSummaryDescription(lang, message, text, noReactions, isExtended);\n\n return `${emojiWithSpace}${description}`;\n}\n\nexport function getMessageTextWithSpoilers(message: ApiMessage) {\n const transcription = getMessageTranscription(message);\n\n const textWithoutTranscription = getMessageText(message);\n if (!textWithoutTranscription) {\n return transcription;\n }\n\n const { entities } = message.content.text || {};\n if (!entities?.length) {\n return transcription ? `${transcription}\\n${textWithoutTranscription}` : textWithoutTranscription;\n }\n\n const text = entities.reduce((accText, {\n type,\n offset,\n length,\n }) => {\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 }, textWithoutTranscription);\n\n return transcription ? `${transcription}\\n${text}` : text;\n}\n\nexport function getMessageSummaryEmoji(message: ApiMessage, noReactions = true) {\n const {\n photo,\n video,\n audio,\n voice,\n document,\n sticker,\n 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 const reaction = !noReactions && getMessageRecentReaction(message);\n if (reaction) {\n return reaction.reaction;\n }\n\n return undefined;\n}\n\nexport function getMessageSummaryDescription(\n lang: LangFn,\n message: ApiMessage,\n truncatedText?: string | TextPart[],\n noReactions = true,\n isExtended = false,\n) {\n const {\n text,\n photo,\n video,\n audio,\n voice,\n document,\n sticker,\n contact,\n poll,\n invoice,\n location,\n game,\n } = message.content;\n\n let summary: string | TextPart[] | undefined;\n\n if (message.groupedId) {\n summary = truncatedText || lang('lng_in_dlg_album');\n }\n\n if (photo) {\n summary = truncatedText || lang('AttachPhoto');\n }\n\n if (video) {\n summary = truncatedText || lang(video.isGif ? 'AttachGif' : 'AttachVideo');\n }\n\n if (sticker) {\n summary = lang('AttachSticker').trim();\n }\n\n if (audio) {\n summary = getMessageAudioCaption(message) || lang('AttachMusic');\n }\n\n if (voice) {\n summary = truncatedText || lang('AttachAudio');\n }\n\n if (document) {\n summary = isExtended ? document.fileName : (truncatedText || document.fileName);\n }\n\n if (contact) {\n summary = lang('AttachContact');\n }\n\n if (poll) {\n summary = poll.summary.question;\n }\n\n if (invoice) {\n summary = `${lang('PaymentInvoice')}: ${invoice.text}`;\n }\n\n if (text) {\n if (isExtended && summary) {\n summary += `\\n${truncatedText}`;\n } else {\n summary = truncatedText;\n }\n }\n\n if (location?.type === 'geo' || location?.type === 'venue') {\n summary = lang('Message.Location');\n }\n\n if (location?.type === 'geoLive') {\n summary = lang('Message.LiveLocation');\n }\n\n if (game) {\n summary = `🎮 ${game.title}`;\n }\n\n const reaction = !noReactions && getMessageRecentReaction(message);\n if (summary && reaction) {\n summary = `to your \"${summary}\"`;\n }\n\n return summary || 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 {\n audio,\n text,\n } = message.content;\n\n return (audio && [audio.title, audio.performer].filter(Boolean)\n .join(' — ')) || (text?.text);\n}\n","import type {\n ApiAudio,\n ApiDimensions,\n ApiDocument,\n ApiGame,\n ApiLocation,\n ApiMessage,\n ApiMessageSearchType,\n ApiPhoto,\n ApiVideo,\n ApiWebDocument,\n} from '../../api/types';\nimport { ApiMediaFormat } from '../../api/types';\n\nimport {\n IS_OPFS_SUPPORTED,\n IS_OPUS_SUPPORTED,\n IS_PROGRESSIVE_SUPPORTED,\n IS_SAFARI,\n MAX_BUFFER_SIZE,\n} 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 getMessageLocation(message: ApiMessage) {\n return message.content.location;\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 getDocumentMediaHash(document: ApiDocument) {\n return `document${document.id}`;\n}\n\nexport function buildStaticMapHash(\n geo: ApiLocation['geo'],\n width: number,\n height: number,\n zoom: number,\n scale: number,\n) {\n const {\n long, lat, accessHash, accuracyRadius,\n } = geo;\n\n // eslint-disable-next-line max-len\n return `staticMap:${accessHash}?lat=${lat}&long=${long}&w=${width}&h=${height}&zoom=${zoom}&scale=${scale}&accuracyRadius=${accuracyRadius}`;\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 const content = messagePhoto || messageVideo || sticker || audio || voice || document;\n\n if (!content) {\n return undefined;\n }\n\n const mediaId = content.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\nexport function getWebDocumentHash(webDocument?: ApiWebDocument) {\n if (!webDocument) return undefined;\n return `webDocument:${webDocument.url}`;\n}\n\nexport function getGamePreviewPhotoHash(game: ApiGame) {\n const { photo } = game;\n\n if (photo) {\n return `photo${photo.id}?size=x`;\n }\n\n return undefined;\n}\n\nexport function getGamePreviewVideoHash(game: ApiGame) {\n const { document } = game;\n\n if (document) {\n return `document${document.id}`;\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 video, audio, voice, document,\n } = message.content;\n const fullVideo = video || getMessageWebPageVideo(message);\n const size = (video || audio || document)?.size!;\n if (target === 'download') {\n if (IS_PROGRESSIVE_SUPPORTED && size > MAX_BUFFER_SIZE && !IS_OPFS_SUPPORTED) {\n return ApiMediaFormat.DownloadUrl;\n }\n return ApiMediaFormat.BlobUrl;\n }\n\n if (fullVideo && IS_PROGRESSIVE_SUPPORTED && (\n target === 'viewerFull' || target === 'inline'\n )) {\n return ApiMediaFormat.Progressive;\n }\n\n 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 return getMessageContentIds(messages, listedIds, isFromSharedMedia ? 'media' : 'inlineMedia');\n}\n\nexport function getPhotoFullDimensions(photo: Pick<ApiPhoto, 'sizes' | 'thumbnail'>): 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: Pick<ApiPhoto, 'sizes' | 'thumbnail'>): 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 type { 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 type { ApiPhoto } from '../../api/types';\n\nexport function getBotCoverMediaHash(photo: ApiPhoto) {\n return `photo${photo.id}?size=x`;\n}\n","import type { ApiPhoto } from '../../api/types';\n\nexport function getVideoAvatarMediaHash(photo: ApiPhoto) {\n return `videoAvatar${photo.id}?size=u`;\n}\n","import type { 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 type { LangFn } from '../../hooks/useLang';\nimport { getServerTime } from '../../util/serverTime';\nimport { prepareSearchWordsForNeedle } from '../../util/searchWords';\nimport { formatPhoneNumber } from '../../util/phoneNumber';\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 if (user.phoneNumber) {\n return `+${formatPhoneNumber(user.phoneNumber)}`;\n }\n\n break;\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 return (user.type === 'userTypeDeleted' || user.type === 'userTypeUnknown')\n && user.id !== SERVICE_NOTIFICATIONS_USER_ID;\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 { typify } from '../lib/teact/teactn';\nimport type { GlobalState, ActionPayloads, NonTypedActionNames } from './types';\n\nconst typed = typify<GlobalState, ActionPayloads, NonTypedActionNames>();\n\nexport const getGlobal = typed.getGlobal;\nexport const setGlobal = typed.setGlobal;\nexport const getActions = typed.getActions;\nexport const addActionHandler = typed.addActionHandler;\nexport const withGlobal = typed.withGlobal;\n","import type { 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 isUpdateAvailable: false,\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', 'duck', 'cherries'],\n recentCustomEmojis: ['5377305978079288312'],\n\n stickers: {\n setsById: {},\n added: {},\n recent: {\n stickers: [],\n },\n favorite: {\n stickers: [],\n },\n greeting: {\n stickers: [],\n },\n premium: {\n stickers: [],\n },\n premiumSet: {\n stickers: [],\n },\n featured: {\n setIds: [],\n },\n search: {},\n forEmoji: {},\n },\n\n customEmojis: {\n lastRendered: [],\n byId: {},\n added: {},\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 volume: DEFAULT_VOLUME,\n playbackRate: DEFAULT_PLAYBACK_RATE,\n isMuted: false,\n },\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 byHash: {},\n orderedHashes: [],\n },\n\n activeWebSessions: {\n byHash: {},\n orderedHashes: [],\n },\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: true,\n shouldArchiveAndMuteNewNonContact: 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 passcode: {},\n activeReactions: {},\n\n shouldShowContextMenuHint: true,\n\n activeDownloads: {\n byChatId: {},\n },\n\n serviceNotifications: [],\n\n statistics: {\n byChatId: {},\n },\n\n pollModal: {\n isOpen: false,\n },\n\n trustedBotIds: [],\n\n attachMenu: {\n bots: {},\n },\n\n transcriptions: {},\n};\n","import type { GlobalState } from '../types';\nimport type { ApiChat, ApiChatMember, ApiPhoto } from '../../api/types';\n\nimport { ARCHIVED_FOLDER_ID } from '../../config';\nimport { areSortedArraysEqual, 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 noOmitUnreadReactionCount = false,\n): GlobalState {\n const { byId } = global.chats;\n\n const updatedChat = getUpdatedChat(global, chatId, chatUpdate, photo, noOmitUnreadReactionCount);\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 noOmitUnreadReactionCount = false,\n) {\n const { byId } = global.chats;\n const chat = byId[chatId];\n const shouldOmitMinInfo = chatUpdate.isMin && chat && !chat.isMin;\n\n chatUpdate = noOmitUnreadReactionCount\n ? chatUpdate : omit(chatUpdate, ['unreadReactionsCount']);\n const updatedChat: ApiChat = {\n ...chat,\n ...(shouldOmitMinInfo\n ? omit(chatUpdate, ['isMin', 'accessHash'])\n : 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\nexport function addChatMembers(global: GlobalState, chat: ApiChat, membersToAdd: ApiChatMember[]): GlobalState {\n const currentMembers = chat.fullInfo?.members;\n const newMemberIds = new Set(membersToAdd.map((m) => m.userId));\n const updatedMembers = [\n ...currentMembers?.filter((m) => !newMemberIds.has(m.userId)) || [],\n ...membersToAdd,\n ];\n const currentIds = currentMembers?.map(({ userId }) => userId) || [];\n const updatedIds = updatedMembers.map(({ userId }) => userId);\n\n if (areSortedArraysEqual(currentIds, updatedIds)) {\n return global;\n }\n\n return updateChat(global, chat.id, {\n fullInfo: {\n ...chat.fullInfo,\n members: updatedMembers,\n },\n });\n}\n","import type { GlobalState } from '../types';\nimport type { 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 const regularSetIds = sets.filter((set) => !set.isEmoji).map((set) => set.id);\n const addedEmojiSetIds = category === 'added' ? sets.filter((set) => set.isEmoji).map((set) => set.id) : [];\n const customEmojis = sets.filter((set) => set.isEmoji)\n .map((set) => set.stickers)\n .flat()\n .filter(Boolean);\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 : {\n setIds: [\n ...(global.stickers[category].setIds || []),\n ...regularSetIds,\n ],\n }\n ),\n },\n },\n customEmojis: {\n ...global.customEmojis,\n added: {\n ...global.customEmojis.added,\n hash,\n setIds: [\n ...(global.customEmojis.added.setIds || []),\n ...addedEmojiSetIds,\n ],\n },\n byId: {\n ...global.customEmojis.byId,\n ...buildCollectionByKey(customEmojis, 'id'),\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 const isCustomEmoji = update.isEmoji || currentStickerSet.isEmoji;\n const addedSets = (isCustomEmoji ? global.customEmojis.added.setIds : global.stickers.added.setIds) || [];\n let setIds: string[] = addedSets;\n if (update.installedDate && addedSets && !addedSets.includes(stickerSetId)) {\n setIds = [stickerSetId, ...setIds];\n }\n\n if (!update.installedDate && addedSets?.includes(stickerSetId)) {\n setIds = setIds.filter((id) => id !== stickerSetId);\n }\n\n const customEmojiById = isCustomEmoji && currentStickerSet.stickers\n && buildCollectionByKey(currentStickerSet.stickers, 'id');\n\n return {\n ...global,\n stickers: {\n ...global.stickers,\n added: {\n ...global.stickers.added,\n ...(!isCustomEmoji && { setIds }),\n },\n setsById: {\n ...global.stickers.setsById,\n [stickerSetId]: {\n ...currentStickerSet,\n ...update,\n },\n },\n },\n customEmojis: {\n ...global.customEmojis,\n byId: {\n ...global.customEmojis.byId,\n ...customEmojiById,\n },\n added: {\n ...global.customEmojis.added,\n ...(isCustomEmoji && { setIds }),\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 if (global.stickers.forEmoji) {\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\n return global;\n}\n","import type { GlobalState } from '../types';\nimport type { ApiUser, ApiUserStatus } from '../../api/types';\n\nimport { omit, pick } from '../../util/iteratees';\nimport { MEMO_EMPTY_ARRAY } from '../../util/memo';\nimport { updateChat } from './chats';\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 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 global = replaceUsers(global, {\n ...byId,\n [userId]: {\n ...byId[userId],\n isContact: undefined,\n },\n });\n\n return updateChat(global, userId, {\n settings: undefined,\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\nexport function closeNewContactDialog(global: GlobalState): GlobalState {\n return {\n ...global,\n newContact: undefined,\n };\n}\n","import type { GlobalState } from '../types';\nimport type { GlobalSearchContent } from '../../types';\nimport type { 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 type { GlobalState } from '../types';\nimport type { ApiMessageSearchType } from '../../api/types';\n\nimport { areSortedArraysEqual, unique } from '../../util/iteratees';\nimport type { 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) => b - a);\n}\n","import type { GlobalState } from '../types';\nimport type { 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 type { GlobalState } from '../types';\nimport type {\n ISettings, IThemeSettings, ThemeKey, NotifyException,\n} from '../../types';\nimport type { 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\n// eslint-disable-next-line consistent-return\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}\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 type { GlobalState } from '../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 type { GlobalState } from '../types';\nimport { INITIAL_STATE } from '../initialState';\n\nexport function updatePasscodeSettings(\n global: GlobalState,\n update: GlobalState['passcode'],\n): GlobalState {\n return {\n ...global,\n passcode: {\n ...global.passcode,\n ...update,\n },\n };\n}\n\nexport function clearPasscodeSettings(global: GlobalState): GlobalState {\n return {\n ...global,\n passcode: {},\n };\n}\n\nexport function clearGlobalForLockScreen(global: GlobalState): GlobalState {\n const {\n theme,\n shouldUseSystemTheme,\n animationLevel,\n language,\n } = global.settings.byKey;\n\n return {\n ...INITIAL_STATE,\n passcode: global.passcode,\n settings: {\n ...INITIAL_STATE.settings,\n byKey: {\n ...INITIAL_STATE.settings.byKey,\n theme,\n shouldUseSystemTheme,\n animationLevel,\n language,\n },\n },\n };\n}\n","import type { GlobalState } from '../types';\nimport type { ShippingOption, PaymentStep } from '../../types';\nimport type {\n ApiInvoice, ApiMessage, ApiPaymentForm, ApiReceipt,\n} 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 setInvoiceInfo(global: GlobalState, invoice: ApiInvoice): GlobalState {\n const {\n title,\n text,\n amount,\n currency,\n isTest,\n photo,\n isRecurring,\n recurringTermsUrl,\n } = invoice;\n\n return {\n ...global,\n payment: {\n ...global.payment,\n invoiceContent: {\n title,\n text,\n photo,\n amount,\n currency,\n isTest,\n isRecurring,\n recurringTermsUrl,\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 setSmartGlocalCardInfo(\n global: GlobalState,\n cardInfo: { type: string; token: string },\n): GlobalState {\n return {\n ...global,\n payment: {\n ...global.payment,\n smartGlocalCredentials: {\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 setConfirmPaymentUrl(global: GlobalState, url?: string): GlobalState {\n return {\n ...global,\n payment: {\n ...global.payment,\n confirmPaymentUrl: url,\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 {\n photo, text, title,\n } = (messageInvoice || {});\n\n return {\n ...global,\n payment: {\n ...global.payment,\n receipt: {\n ...receipt,\n photo,\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 type { GlobalState } from '../types';\nimport type {\n ApiChannelStatistics, ApiGroupStatistics, ApiMessageStatistics, StatisticsGraph,\n} from '../../api/types';\n\nexport function updateStatistics(\n global: GlobalState, chatId: string, statistics: ApiChannelStatistics | ApiGroupStatistics,\n): GlobalState {\n return {\n ...global,\n statistics: {\n byChatId: {\n ...global.statistics.byChatId,\n [chatId]: statistics,\n },\n },\n };\n}\n\nexport function updateMessageStatistics(\n global: GlobalState, statistics: ApiMessageStatistics,\n): GlobalState {\n return {\n ...global,\n statistics: {\n ...global.statistics,\n currentMessage: statistics,\n },\n };\n}\n\nexport function updateStatisticsGraph(\n global: GlobalState, chatId: string, name: string, update: StatisticsGraph,\n): GlobalState {\n return {\n ...global,\n statistics: {\n ...global.statistics,\n byChatId: {\n ...global.statistics.byChatId,\n [chatId]: {\n ...(global.statistics.byChatId[chatId] || {}),\n [name]: update,\n },\n },\n },\n };\n}\n","import type {\n GlobalState, MessageList, MessageListType, Thread,\n} from '../types';\nimport type { ApiMessage, ApiSponsoredMessage, ApiThreadInfo } from '../../api/types';\nimport { MAIN_THREAD_ID } from '../../api/types';\nimport type { FocusDirection } from '../../types';\n\nimport {\n IS_MOCKED_CLIENT,\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 && !IS_MOCKED_CLIENT)) {\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\nexport function 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 type { ApiChatType, ApiChat } from '../../api/types';\nimport { MAIN_THREAD_ID } from '../../api/types';\nimport type { GlobalState } from '../types';\n\nimport {\n getPrivateChatUserId, isChatChannel, isUserId, isHistoryClearMessage, isUserBot, isUserOnline,\n} from '../helpers';\nimport { selectBot, selectUser } from './users';\nimport {\n ALL_FOLDER_ID, ARCHIVED_FOLDER_ID, MEMBERS_LOAD_SLICE, SERVICE_NOTIFICATIONS_USER_ID,\n} from '../../config';\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 selectIsTrustedBot(global: GlobalState, botId: string) {\n const bot = selectUser(global, botId);\n return bot && (bot.isVerified || global.trustedBotIds.includes(botId));\n}\n\nexport function selectChatType(global: GlobalState, chatId: string) : ApiChatType | undefined {\n const chat = selectChat(global, chatId);\n if (!chat) return undefined;\n\n const bot = selectBot(global, chatId);\n if (bot) {\n return 'bots';\n }\n\n const user = selectChatUser(global, chat);\n if (user) {\n return 'users';\n }\n\n if (isChatChannel(chat)) {\n return 'channels';\n }\n\n return 'chats';\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 Boolean(active?.includes(chatId));\n }\n\n if (folderId === ARCHIVED_FOLDER_ID) {\n return Boolean(archived?.includes(chatId));\n }\n\n const { byId: chatFoldersById } = global.chatFolders;\n\n const { pinnedChatIds } = chatFoldersById[folderId] || {};\n return Boolean(pinnedChatIds?.includes(chatId));\n}\n\n// Slow, not to be used in `withGlobal`\nexport function selectChatByUsername(global: GlobalState, username: string) {\n const usernameLowered = username.toLowerCase();\n return Object.values(global.chats.byId).find(\n (chat) => chat.username && chat.username.toLowerCase() === usernameLowered,\n );\n}\n\nexport function 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\nexport function selectRequestedText(global: GlobalState, chatId: string) {\n if (global.requestedDraft?.chatId === chatId) {\n return global.requestedDraft.text;\n }\n return undefined;\n}\n\nexport function filterChatIdsByType(global: GlobalState, chatIds: string[], filter: readonly ApiChatType[]) {\n return chatIds.filter((id) => {\n const type = selectChatType(global, id);\n if (!type) {\n return false;\n }\n return filter.includes(type);\n });\n}\n","import type { GlobalState } from '../types';\nimport type { ApiStickerSetInfo, ApiSticker, ApiStickerSet } from '../../api/types';\n\nimport { selectIsCurrentUserPremium } from './users';\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 | ApiStickerSetInfo) {\n if (typeof id === 'string') {\n return global.stickers.setsById[id];\n }\n\n if ('id' in id) {\n return global.stickers.setsById[id.id];\n }\n\n if ('isMissing' in id) return undefined;\n\n return Object.values(global.stickers.setsById).find(({ shortName }) => (\n shortName.toLowerCase() === id.shortName.toLowerCase()\n ));\n}\n\nexport function selectStickersForEmoji(global: GlobalState, emoji: string) {\n const addedSets = global.stickers.added.setIds;\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 addedSets?.forEach((id) => {\n const packs = global.stickers.setsById[id].packs;\n if (!packs) {\n return;\n }\n\n stickersForEmoji = stickersForEmoji.concat(packs[emoji] || [], packs[cleanEmoji(emoji)] || []);\n });\n return stickersForEmoji;\n}\n\nexport function selectCustomEmojiForEmoji(global: GlobalState, emoji: string) {\n const isCurrentUserPremium = selectIsCurrentUserPremium(global);\n const addedCustomSets = global.customEmojis.added.setIds;\n let customEmojiForEmoji: ApiSticker[] = [];\n\n // Added sets\n addedCustomSets?.forEach((id) => {\n const packs = global.stickers.setsById[id].packs;\n if (!packs) {\n return;\n }\n\n customEmojiForEmoji = customEmojiForEmoji.concat(packs[emoji] || [], packs[cleanEmoji(emoji)] || []);\n });\n return isCurrentUserPremium ? customEmojiForEmoji : customEmojiForEmoji.filter(({ isFree }) => isFree);\n}\n\nexport function selectIsSetPremium(stickerSet: ApiStickerSet) {\n return stickerSet.isEmoji && stickerSet.stickers?.some((sticker) => !sticker.isFree);\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 type { GlobalState, MessageListType, Thread } from '../types';\nimport type {\n ApiChat,\n ApiStickerSetInfo,\n ApiMessage,\n ApiMessageEntityCustomEmoji,\n ApiMessageOutgoingStatus,\n ApiUser,\n} from '../../api/types';\nimport {\n MAIN_THREAD_ID,\n ApiMessageEntityTypes,\n} from '../../api/types';\n\nimport { LOCAL_MESSAGE_MIN_ID, REPLIES_USER_ID, SERVICE_NOTIFICATIONS_USER_ID } from '../../config';\nimport {\n selectChat, selectChatBot, selectIsChatWithBot, selectIsChatWithSelf,\n} from './chats';\nimport { selectIsUserOrChatContact, selectUser, selectUserStatus } 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 getMessageOriginalId,\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 selectEditingDraft(global: GlobalState, chatId: string, threadId: number) {\n return selectThreadParam(global, chatId, threadId, 'editingDraft');\n}\n\nexport function selectEditingScheduledId(global: GlobalState, chatId: string) {\n return selectThreadParam(global, chatId, MAIN_THREAD_ID, 'editingScheduledId');\n}\n\nexport function selectEditingScheduledDraft(global: GlobalState, chatId: string) {\n return selectThreadParam(global, chatId, MAIN_THREAD_ID, 'editingScheduledDraft');\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 selectIsMessageInCurrentMessageList(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_MIN_ID && !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 selectReplySender(global: GlobalState, message: ApiMessage, isForwarded = false) {\n if (isForwarded) {\n const { senderUserId, hiddenUserName } = message.forwardInfo || {};\n if (senderUserId) {\n return isUserId(senderUserId) ? selectUser(global, senderUserId) : selectChat(global, senderUserId);\n }\n if (hiddenUserName) return undefined;\n }\n\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) || content.location\n )\n && !isForwardedMessage(message)\n && !message.viaBotId\n && !chat.isForbidden\n );\n\n const canReply = !isLocal && !isServiceNotification && !chat.isForbidden && 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 && !chat.isForbidden && (\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 canSaveGif = message.content.video?.isGif;\n\n const poll = content.poll;\n const canRevote = !poll?.summary.closed && !poll?.summary.quiz && poll?.results.results?.some((r) => r.isChosen);\n const canClosePoll = isOwn && poll && !poll.summary.closed;\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 canSaveGif,\n canRevote,\n canClosePoll,\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 canSaveGif,\n canRevote,\n canClosePoll,\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[getMessageOriginalId(message)]?.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, isDeleted }) => !isDeleted && 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\n// Slow, not to be used in `withGlobal`\nexport function selectVisibleUsers(global: GlobalState) {\n const { chatId, threadId } = selectCurrentMessageList(global) || {};\n if (!chatId || !threadId) {\n return undefined;\n }\n\n const messageIds = selectThreadParam(global, chatId, threadId, 'viewportIds');\n if (!messageIds) {\n return undefined;\n }\n\n return messageIds.map((messageId) => {\n const { senderId } = selectChatMessage(global, chatId, messageId) || {};\n return senderId ? selectUser(global, senderId) : undefined;\n }).filter(Boolean);\n}\n\nexport function selectShouldSchedule(global: GlobalState) {\n return selectCurrentMessageList(global)?.type === 'scheduled';\n}\n\nexport function selectCanScheduleUntilOnline(global: GlobalState, id: string) {\n const isChatWithSelf = selectIsChatWithSelf(global, id);\n const chatBot = id === REPLIES_USER_ID && selectChatBot(global, id);\n return Boolean(\n !isChatWithSelf && !chatBot && isUserId(id) && selectUserStatus(global, id)?.wasOnline,\n );\n}\n\nexport function selectCustomEmojis(message: ApiMessage) {\n const entities = message.content.text?.entities;\n return entities?.filter((entity): entity is ApiMessageEntityCustomEmoji => (\n entity.type === ApiMessageEntityTypes.CustomEmoji\n ));\n}\n\nexport function selectMessageCustomEmojiSets(\n global: GlobalState, message: ApiMessage,\n): ApiStickerSetInfo[] | undefined {\n const customEmojis = selectCustomEmojis(message);\n if (!customEmojis) return MEMO_EMPTY_ARRAY;\n const documents = customEmojis.map((entity) => global.customEmojis.byId[entity.documentId]);\n // If some emoji still loading, do not return empty array\n if (!documents.every(Boolean)) return undefined;\n const sets = documents.map((doc) => doc.stickerSetInfo);\n const setsWithoutDuplicates = sets.reduce((acc, set) => {\n if ('shortName' in set) {\n if (acc.some((s) => 'shortName' in s && s.shortName === set.shortName)) {\n return acc;\n }\n }\n\n if ('id' in set) {\n if (acc.some((s) => 'id' in s && s.id === set.id)) {\n return acc;\n }\n }\n acc.push(set); // Optimization\n return acc;\n }, [] as ApiStickerSetInfo[]);\n return setsWithoutDuplicates;\n}\n\nexport function selectForwardsContainVoiceMessages(global: GlobalState) {\n const { messageIds, fromChatId } = global.forwardMessages;\n if (!messageIds) return false;\n const chatMessages = selectChatMessages(global, fromChatId!);\n return messageIds.some((messageId) => {\n const message = chatMessages[messageId];\n return Boolean(message.content.voice) || message.content.video?.isRound;\n });\n}\n","import type { GlobalState } from '../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 selectCurrentMediaSearch(global: GlobalState) {\n const { chatId } = selectCurrentMessageList(global) || {};\n if (!chatId) {\n return undefined;\n }\n\n return global.localMediaSearch.byChatId[chatId];\n}\n","import type { GlobalState } from '../types';\n\nimport { selectCurrentMessageList } from './messages';\nimport { selectChat } from './chats';\n\nexport function selectStatistics(global: GlobalState, chatId: string) {\n return global.statistics.byChatId[chatId];\n}\n\nexport function selectIsStatisticsShown(global: GlobalState) {\n if (!global.isStatisticsShown) {\n return false;\n }\n\n const { chatId: currentChatId } = selectCurrentMessageList(global) || {};\n const chat = currentChatId ? selectChat(global, currentChatId) : undefined;\n\n return chat?.fullInfo?.canViewStatistics;\n}\n\nexport function selectIsMessageStatisticsShown(global: GlobalState) {\n if (!global.isStatisticsShown) {\n return false;\n }\n\n return Boolean(global.statistics.currentMessageId);\n}\n","import type { GlobalState } from '../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 type { GlobalState } from '../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 { selectIsStatisticsShown, selectIsMessageStatisticsShown } from './statistics';\nimport { selectCurrentManagement } from './management';\n\nexport function selectIsMediaViewerOpen(global: GlobalState) {\n const { mediaViewer } = global;\n return Boolean(mediaViewer.mediaId || mediaViewer.avatarOwnerId);\n}\n\nexport function selectRightColumnContentKey(global: GlobalState) {\n return selectIsPollResultsOpen(global) ? (\n RightColumnContent.PollResults\n ) : !IS_SINGLE_COLUMN_LAYOUT && selectCurrentTextSearch(global) ? (\n RightColumnContent.Search\n ) : selectCurrentManagement(global) ? (\n RightColumnContent.Management\n ) : selectIsMessageStatisticsShown(global) ? (\n RightColumnContent.MessageStatistics\n ) : selectIsStatisticsShown(global) ? (\n RightColumnContent.Statistics\n ) : selectCurrentStickerSearch(global).query !== undefined ? (\n RightColumnContent.StickerSearch\n ) : selectCurrentGifSearch(global).query !== undefined ? (\n RightColumnContent.GifSearch\n ) : global.newChatMembersProgress !== NewChatMembersProgress.Closed ? (\n RightColumnContent.AddingMembers\n ) : global.isChatInfoShown && selectCurrentMessageList(global) ? (\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 type { GlobalState } from '../types';\n\nexport function selectCurrentGlobalSearchQuery(global: GlobalState) {\n return global.globalSearch.query;\n}\n","import type { GlobalState } from '../types';\n\nexport function selectPaymentInputInvoice(global: GlobalState) {\n return global.payment.inputInvoice;\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?.publishableKey;\n}\n\nexport function selectProviderPublicToken(global: GlobalState) {\n return global.payment.nativeParams?.publicToken;\n}\n\nexport function selectStripeCredentials(global: GlobalState) {\n return global.payment.stripeCredentials;\n}\n\nexport function selectSmartGlocalCredentials(global: GlobalState) {\n return global.payment.smartGlocalCredentials;\n}\n","import type { GlobalState } from '../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 type { GlobalState } from '../types';\nimport type { ApiChat, ApiUser, ApiUserStatus } from '../../api/types';\nimport { isUserBot } from '../helpers';\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\nexport function selectIsCurrentUserPremium(global: GlobalState) {\n if (!global.currentUserId) return false;\n\n return Boolean(global.users.byId[global.currentUserId].isPremium);\n}\n\nexport function selectIsPremiumPurchaseBlocked(global: GlobalState) {\n return global.appConfig?.isPremiumPurchaseBlocked ?? true;\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\n// Slow, not to be used in `withGlobal`\nexport function selectUserByPhoneNumber(global: GlobalState, phoneNumber: string) {\n const phoneNumberCleaned = phoneNumber.replace(/[^0-9]/g, '');\n\n return Object.values(global.users.byId).find((user) => user?.phoneNumber === phoneNumberCleaned);\n}\n\nexport function selectIsUserOrChatContact(global: GlobalState, userOrChat: ApiUser | ApiChat) {\n return global.contactList && global.contactList.userIds.includes(userOrChat.id);\n}\n\nexport function selectBot(global: GlobalState, userId: string): ApiUser | undefined {\n const user = selectUser(global, userId);\n if (!user || !isUserBot(user)) {\n return undefined;\n }\n\n return user;\n}\n","import { useEffect, useState } from '../lib/teact/teact';\n\nconst useAsync = <T>(fn: () => Promise<T>, deps: any[], defaultValue?: T) => {\n const [isLoading, setIsLoading] = useState<boolean>(false);\n const [error, setError] = useState<Error | undefined>();\n const [result, setResult] = useState<T | undefined>(defaultValue);\n useEffect(() => {\n setIsLoading(true);\n let wasCancelled = false;\n fn().then((res) => {\n if (wasCancelled) return;\n setIsLoading(false);\n setResult(res);\n }, (err) => {\n if (wasCancelled) return;\n setIsLoading(false);\n setError(err);\n });\n return () => {\n wasCancelled = true;\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, deps);\n return { isLoading, error, result };\n};\n\nexport default useAsync;\n","import { useEffect } from '../lib/teact/teact';\n\nexport default function useBackgroundMode(\n onBlur?: AnyToVoidFunction,\n onFocus?: AnyToVoidFunction,\n) {\n useEffect(() => {\n if (onBlur && !document.hasFocus()) {\n onBlur();\n }\n\n if (onBlur) {\n window.addEventListener('blur', onBlur);\n }\n\n if (onFocus) {\n window.addEventListener('focus', onFocus);\n }\n\n return () => {\n if (onFocus) {\n window.removeEventListener('focus', onFocus);\n }\n\n if (onBlur) {\n window.removeEventListener('blur', onBlur);\n }\n };\n }, [onBlur, onFocus]);\n}\n","import usePrevious from './usePrevious';\n\nexport default function useCurrentOrPrev<T extends any>(\n current: T, shouldSkipUndefined = false, shouldForceCurrent = false,\n): T | undefined {\n const prev = usePrevious(current, shouldSkipUndefined);\n\n // eslint-disable-next-line no-null/no-null\n return shouldForceCurrent || (current !== null && current !== undefined) ? current : prev;\n}\n","import { useCallback, useMemo } from '../lib/teact/teact';\n\nimport { debounce } from '../util/schedulers';\n\nexport default function useDebouncedCallback<T extends AnyToVoidFunction>(\n fn: T,\n deps: any[],\n ms: number,\n noFirst?: boolean,\n noLast?: boolean,\n) {\n // eslint-disable-next-line react-hooks/exhaustive-deps\n const fnMemo = useCallback(fn, deps);\n\n return useMemo(() => {\n return debounce(fnMemo, ms, !noFirst, !noLast);\n }, [fnMemo, ms, noFirst, noLast]);\n}\n","import { useEffect } from '../lib/teact/teact';\nimport usePrevious from './usePrevious';\n\nconst useEffectWithPrevDeps = <T extends readonly any[]>(\n cb: (args: T | readonly []) => void, dependencies: T, debugKey?: string,\n) => {\n const prevDeps = usePrevious<T>(dependencies);\n return useEffect(() => {\n return cb(prevDeps || []);\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, dependencies, debugKey);\n};\n\nexport default useEffectWithPrevDeps;\n","import { useCallback, useState } from '../lib/teact/teact';\n\nconst useFlag = (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\nexport default useFlag;\n","import { useCallback, useState } from '../lib/teact/teact';\n\nconst useForceUpdate = () => {\n const [, setTrigger] = useState<boolean>(false);\n\n return useCallback(() => {\n setTrigger((trigger) => !trigger);\n }, []);\n};\n\nexport default useForceUpdate;\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\nconst useHeavyAnimationCheck = (\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\nexport default useHeavyAnimationCheck;\n","import useOnChange from './useOnChange';\nimport { useEffect, useRef } from '../lib/teact/teact';\nimport { IS_TEST } from '../config';\nimport { fastRaf } from '../util/schedulers';\nimport { IS_IOS } from '../util/environment';\nimport { getActions } from '../lib/teact/teactn';\n\nexport const LOCATION_HASH = window.location.hash;\nconst PATH_BASE = `${window.location.pathname}${window.location.search}`;\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;\n\ntype HistoryRecord = {\n index: number;\n // Should this record be replaced by the next record (for example Menu)\n shouldBeReplaced?: boolean;\n // Mark this record as replaced by the next record. Only used to check if needed to perform effectBack\n markReplaced?: VoidFunction;\n onBack?: VoidFunction;\n // Set if the element is closed in the UI, but not in the real history\n isClosed?: boolean;\n};\n\ntype HistoryOperationGo = {\n type: 'go';\n delta: number;\n};\n\ntype HistoryOperationState = {\n type: 'pushState' | 'replaceState';\n data: any;\n hash?: string;\n};\n\ntype HistoryOperation = HistoryOperationGo | HistoryOperationState;\n\n// Needed to dismiss any 'trashed' history records from the previous page reloads.\nconst historyUniqueSessionId = Number(new Date());\n// Reflects real history state, but also contains information on which records should be replaced by the next record and\n// which records are deferred to close on the next operation\nlet historyState: HistoryRecord[];\n// Reflects current real history index\nlet historyCursor: number;\n// If we alter real history programmatically, the popstate event will be fired, which we don't need\nlet isAlteringHistory = false;\n// Unfortunately Safari doesn't really like when there's 2+ consequent history operations in one frame, so we need\n// to delay them to the next raf\nlet deferredHistoryOperations: HistoryOperation[] = [];\nlet deferredPopstateOperations: HistoryOperationState[] = [];\nlet isSafariGestureAnimation = false;\n\n// Do not remove: used for history unit tests\nif (IS_TEST) {\n (window as any).TEST_getHistoryState = () => historyState;\n (window as any).TEST_getHistoryCursor = () => historyCursor;\n}\n\nfunction 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 isSafariGestureAnimation = true;\n }\n}\n\nfunction handleTouchEnd() {\n if (!isSafariGestureAnimation) {\n return;\n }\n\n setTimeout(() => {\n isSafariGestureAnimation = false;\n }, SAFARI_EDGE_BACK_GESTURE_DURATION);\n}\n\nif (IS_IOS) {\n window.addEventListener('touchstart', handleTouchStart);\n window.addEventListener('touchend', handleTouchEnd);\n window.addEventListener('popstate', handleTouchEnd);\n}\n\nfunction applyDeferredHistoryOperations() {\n const goOperations = deferredHistoryOperations.filter((op) => op.type === 'go') as HistoryOperationGo[];\n const stateOperations = deferredHistoryOperations.filter((op) => op.type !== 'go') as HistoryOperationState[];\n const goCount = goOperations.reduce((acc, op) => acc + op.delta, 0);\n\n deferredHistoryOperations = [];\n\n if (goCount) {\n window.history.go(goCount);\n\n // If we have some `state` operations after the `go` operations, we need to wait until the popstate event\n // so the order of operations is correctly preserved\n if (stateOperations.length) {\n deferredPopstateOperations.push(...stateOperations);\n return;\n }\n }\n\n processStateOperations(stateOperations);\n}\n\nfunction processStateOperations(stateOperations: HistoryOperationState[]) {\n stateOperations.forEach((op) => window.history[op.type](op.data, '', op.hash));\n}\n\nfunction deferHistoryOperation(historyOperation: HistoryOperation) {\n if (!deferredHistoryOperations.length) fastRaf(applyDeferredHistoryOperations);\n deferredHistoryOperations.push(historyOperation);\n}\n\n// Resets history to the `root` state\nfunction resetHistory() {\n historyCursor = 0;\n historyState = [{\n index: 0,\n onBack: () => window.history.back(),\n }];\n\n window.history.replaceState({ index: 0, historyUniqueSessionId }, PATH_BASE);\n}\n\nresetHistory();\n\nfunction cleanupClosed(alreadyClosedCount = 1) {\n let countClosed = alreadyClosedCount;\n for (let i = historyCursor - 1; i > 0; i--) {\n if (!historyState[i].isClosed) break;\n countClosed++;\n }\n if (countClosed) {\n isAlteringHistory = true;\n deferHistoryOperation({\n type: 'go',\n delta: -countClosed,\n });\n }\n return countClosed;\n}\n\nfunction cleanupTrashedState() {\n // Navigation to previous page reload, state of which was trashed by reload\n for (let i = historyState.length - 1; i > 0; i--) {\n if (historyState[i].isClosed) {\n continue;\n }\n if (isSafariGestureAnimation) {\n getActions().disableHistoryAnimations();\n }\n historyState[i].onBack?.();\n }\n\n resetHistory();\n}\n\nwindow.addEventListener('popstate', ({ state }: PopStateEvent) => {\n if (isAlteringHistory) {\n isAlteringHistory = false;\n if (deferredPopstateOperations.length) {\n processStateOperations(deferredPopstateOperations);\n deferredPopstateOperations = [];\n }\n return;\n }\n\n if (!state) {\n cleanupTrashedState();\n\n if (!window.location.hash) {\n return;\n }\n return;\n }\n\n const { index, historyUniqueSessionId: previousUniqueSessionId } = state;\n if (previousUniqueSessionId !== historyUniqueSessionId) {\n cleanupTrashedState();\n return;\n }\n\n // New real history state matches the old virtual one. Not possible in theory, but in practice we have Safari\n if (index === historyCursor) {\n return;\n }\n\n if (index < historyCursor) {\n // Navigating back\n let alreadyClosedCount = 0;\n for (let i = historyCursor; i > index - alreadyClosedCount; i--) {\n if (historyState[i].isClosed) {\n alreadyClosedCount++;\n continue;\n }\n if (isSafariGestureAnimation) {\n getActions().disableHistoryAnimations();\n }\n historyState[i].onBack?.();\n }\n\n const countClosed = cleanupClosed(alreadyClosedCount);\n historyCursor += index - historyCursor - countClosed;\n\n // Can happen when we have deferred a real back for some element (for example Menu), closed via UI,\n // pressed back button and caused a pushState.\n if (historyCursor < 0) {\n historyCursor = 0;\n }\n } else if (index > historyCursor) {\n // Forward navigation is not yet supported\n isAlteringHistory = true;\n deferHistoryOperation({\n type: 'go',\n delta: -(index - historyCursor),\n });\n }\n});\n\nexport default function useHistoryBack({\n isActive,\n shouldBeReplaced,\n hash,\n onBack,\n}: {\n isActive?: boolean;\n shouldBeReplaced?: boolean;\n hash?: string;\n title?: string;\n onBack: VoidFunction;\n}) {\n // Active index of the record\n const indexRef = useRef<number>();\n const wasReplaced = useRef(false);\n\n const isFirstRender = useRef(true);\n\n const pushState = (forceReplace = false) => {\n // Check if the old state should be replaced\n const shouldReplace = forceReplace || historyState[historyCursor].shouldBeReplaced;\n indexRef.current = shouldReplace ? historyCursor : ++historyCursor;\n\n historyCursor = indexRef.current;\n\n // Mark the previous record as replaced so effectBack doesn't perform back operation on the new record\n const previousRecord = historyState[indexRef.current];\n if (previousRecord && !previousRecord.isClosed) {\n previousRecord.markReplaced?.();\n }\n\n historyState[indexRef.current] = {\n index: indexRef.current,\n onBack,\n shouldBeReplaced,\n markReplaced: () => {\n wasReplaced.current = true;\n },\n };\n\n // Delete forward navigation in the virtual history. Not really needed, just looks better when debugging `logState`\n for (let i = indexRef.current + 1; i < historyState.length; i++) {\n delete historyState[i];\n }\n\n deferHistoryOperation({\n type: shouldReplace ? 'replaceState' : 'pushState',\n data: {\n index: indexRef.current,\n historyUniqueSessionId,\n },\n hash: hash ? `#${hash}` : undefined,\n });\n };\n\n const processBack = () => {\n // Only process back on open records\n if (indexRef.current && historyState[indexRef.current] && !wasReplaced.current) {\n historyState[indexRef.current].isClosed = true;\n wasReplaced.current = true;\n if (indexRef.current === historyCursor && !shouldBeReplaced) {\n historyCursor -= cleanupClosed();\n }\n }\n };\n\n // Process back navigation when element is unmounted\n useEffect(() => {\n isFirstRender.current = false;\n return () => {\n if (!isActive || wasReplaced.current) return;\n processBack();\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n\n useOnChange(() => {\n if (isFirstRender.current && !isActive) return;\n\n if (isActive) {\n pushState();\n } else {\n processBack();\n }\n }, [isActive]);\n}\n","import type { RefObject } from 'react';\nimport {\n useEffect, useRef, useCallback, useState,\n} from '../lib/teact/teact';\n\nimport { throttle, debounce } from '../util/schedulers';\nimport useHeavyAnimationCheck from './useHeavyAnimationCheck';\n\ntype TargetCallback = (entry: IntersectionObserverEntry) => void;\ntype RootCallback = (entries: IntersectionObserverEntry[]) => void;\ntype ObserveCleanup = NoneToVoidFunction;\nexport type ObserveFn = (target: HTMLElement, targetCallback?: TargetCallback) => ObserveCleanup;\n\ninterface IntersectionController {\n observer: IntersectionObserver;\n callbacks: Map<HTMLElement, TargetCallback>;\n}\n\ninterface Response {\n observe: ObserveFn;\n freeze: NoneToVoidFunction;\n unfreeze: NoneToVoidFunction;\n}\n\nexport function useIntersectionObserver({\n rootRef,\n throttleMs,\n debounceMs,\n shouldSkipFirst,\n margin,\n threshold,\n isDisabled,\n}: {\n rootRef: RefObject<HTMLDivElement>;\n throttleMs?: number;\n debounceMs?: number;\n shouldSkipFirst?: boolean;\n margin?: number;\n threshold?: number | number[];\n isDisabled?: boolean;\n}, rootCallback?: RootCallback): Response {\n const controllerRef = useRef<IntersectionController>();\n const rootCallbackRef = useRef<RootCallback>();\n const freezeFlagsRef = useRef(0);\n const onUnfreezeRef = useRef<NoneToVoidFunction>();\n\n rootCallbackRef.current = rootCallback;\n\n const freeze = useCallback(() => {\n freezeFlagsRef.current++;\n }, []);\n\n const unfreeze = useCallback(() => {\n if (!freezeFlagsRef.current) {\n return;\n }\n\n freezeFlagsRef.current--;\n\n if (!freezeFlagsRef.current && onUnfreezeRef.current) {\n onUnfreezeRef.current();\n onUnfreezeRef.current = undefined;\n }\n }, []);\n\n useHeavyAnimationCheck(freeze, unfreeze);\n\n useEffect(() => {\n if (isDisabled) {\n return undefined;\n }\n\n return () => {\n if (controllerRef.current) {\n controllerRef.current.observer.disconnect();\n controllerRef.current.callbacks.clear();\n controllerRef.current = undefined;\n }\n };\n }, [isDisabled]);\n\n function initController() {\n const callbacks = new Map();\n const entriesAccumulator = new Map<Element, IntersectionObserverEntry>();\n const observerCallbackSync = () => {\n const entries = Array.from(entriesAccumulator.values());\n\n entries.forEach((entry: IntersectionObserverEntry) => {\n const callback = callbacks.get(entry.target);\n if (callback) {\n callback!(entry, entries);\n }\n });\n\n if (rootCallbackRef.current) {\n rootCallbackRef.current(entries);\n }\n\n entriesAccumulator.clear();\n };\n const scheduler = throttleMs ? throttle : debounceMs ? debounce : undefined;\n const observerCallback = scheduler\n ? scheduler(observerCallbackSync, (throttleMs || debounceMs)!, !shouldSkipFirst)\n : observerCallbackSync;\n const observer = new IntersectionObserver(\n (entries) => {\n entries.forEach((entry) => {\n entriesAccumulator.set(entry.target, entry);\n });\n\n if (freezeFlagsRef.current) {\n onUnfreezeRef.current = () => {\n observerCallback();\n };\n } else {\n observerCallback();\n }\n },\n {\n root: rootRef.current,\n rootMargin: margin ? `${margin}px` : undefined,\n threshold,\n },\n );\n\n controllerRef.current = { observer, callbacks };\n }\n\n const observe = useCallback((target, targetCallback) => {\n if (!controllerRef.current) {\n initController();\n }\n\n const controller = controllerRef.current!;\n controller.observer.observe(target);\n\n if (targetCallback) {\n controller.callbacks.set(target, targetCallback);\n }\n\n return () => {\n if (targetCallback) {\n controller.callbacks.delete(target);\n }\n\n controller.observer.unobserve(target);\n };\n // Arguments should never change\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [isDisabled]);\n\n return { observe, freeze, unfreeze };\n}\n\nexport function useOnIntersect(\n targetRef: RefObject<HTMLDivElement>, observe?: ObserveFn, callback?: TargetCallback,\n) {\n useEffect(() => {\n return observe ? observe(targetRef.current!, callback) : undefined;\n // Arguments should never change\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n}\n\nexport function useIsIntersecting(\n targetRef: RefObject<HTMLDivElement>, observe?: ObserveFn, callback?: TargetCallback,\n) {\n const [isIntersecting, setIsIntersecting] = useState(!observe);\n\n useOnIntersect(targetRef, observe, (entry) => {\n setIsIntersecting(entry.isIntersecting);\n\n if (callback) {\n callback(entry);\n }\n });\n\n return isIntersecting;\n}\n","import type { RefObject } from 'react';\nimport { useState, useCallback, useEffect } from '../lib/teact/teact';\n\nconst useKeyboardListNavigation = (\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\nexport default useKeyboardListNavigation;\n","import * as langProvider from '../util/langProvider';\nimport useForceUpdate from './useForceUpdate';\nimport useOnChange from './useOnChange';\n\nexport type LangFn = typeof langProvider.getTranslation;\n\nconst useLang = (): LangFn => {\n const forceUpdate = useForceUpdate();\n\n useOnChange(() => {\n return langProvider.addCallback(forceUpdate);\n }, [forceUpdate]);\n\n return langProvider.getTranslation;\n};\n\nexport default useLang;\n","import { useEffect } from '../lib/teact/teact';\n\nimport { ApiMediaFormat } from '../api/types';\n\nimport * as mediaLoader from '../util/mediaLoader';\nimport useForceUpdate from './useForceUpdate';\n\nconst useMedia = (\n mediaHash: string | false | undefined,\n noLoad = false,\n mediaFormat = ApiMediaFormat.BlobUrl,\n cacheBuster?: number,\n delay?: number | false,\n) => {\n const mediaData = mediaHash ? mediaLoader.getFromMemory(mediaHash) : undefined;\n const forceUpdate = useForceUpdate();\n\n useEffect(() => {\n if (!noLoad && mediaHash && !mediaData) {\n const startedAt = Date.now();\n\n mediaLoader.fetch(mediaHash, mediaFormat).then(() => {\n const spentTime = Date.now() - startedAt;\n if (!delay || spentTime >= delay) {\n forceUpdate();\n } else {\n setTimeout(forceUpdate, delay - spentTime);\n }\n });\n }\n }, [noLoad, mediaHash, mediaData, mediaFormat, cacheBuster, forceUpdate, delay]);\n\n return mediaData;\n};\n\nexport default useMedia;\n","import useShowTransition from './useShowTransition';\n\nexport default function useMediaTransition(mediaData?: any) {\n const isMediaReady = Boolean(mediaData);\n const { transitionClassNames } = useShowTransition(isMediaReady, undefined, isMediaReady, 'slow');\n\n return transitionClassNames;\n}\n","import { useEffect } from '../lib/teact/teact';\n\nimport type { BundleModules, Bundles } from '../util/moduleLoader';\nimport { getModuleFromMemory, loadModule, addLoadListener } from '../util/moduleLoader';\n\nimport useForceUpdate from './useForceUpdate';\n\nconst useModuleLoader = <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\nexport default useModuleLoader;\n","import usePrevious from './usePrevious';\n\nconst useOnChange = <T extends readonly any[]>(cb: (args: T | readonly []) => void, dependencies: T) => {\n const prevDeps = usePrevious<T>(dependencies);\n if (!prevDeps || dependencies.some((d, i) => d !== prevDeps[i])) {\n cb(prevDeps || []);\n }\n};\n\nexport default useOnChange;\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\nconst useShowTransition = (\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 hasShownClass: shouldRender,\n hasOpenClass: shouldHaveOpenClassName,\n };\n};\n\nexport default useShowTransition;\n","import { useLayoutEffect, useMemo, useState } from '../lib/teact/teact';\n\nimport type { ApiMessage, ApiSticker } from '../api/types';\n\nimport { DEBUG } from '../config';\nimport { isWebpSupported } from '../util/environment';\nimport { EMPTY_IMAGE_DATA_URI, webpToPngBase64 } from '../util/webpToPng';\nimport { getMessageMediaThumbDataUri } from '../global/helpers';\nimport { selectTheme } from '../global/selectors';\nimport { getGlobal } from '../global';\n\nexport default function useThumbnail(media?: ApiMessage | ApiSticker) {\n const isMessage = media && 'content' in media;\n const thumbDataUri = isMessage ? getMessageMediaThumbDataUri(media) : media?.thumbnail?.dataUri;\n const sticker = isMessage ? media.content?.sticker : media;\n const shouldDecodeThumbnail = thumbDataUri && sticker && !isWebpSupported() && thumbDataUri.includes('image/webp');\n const [thumbnailDecoded, setThumbnailDecoded] = useState(EMPTY_IMAGE_DATA_URI);\n const id = media?.id;\n\n useLayoutEffect(() => {\n if (!shouldDecodeThumbnail) {\n return;\n }\n\n webpToPngBase64(`b64-${id}`, thumbDataUri!)\n .then(setThumbnailDecoded)\n .catch((err) => {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error(err);\n }\n });\n }, [id, shouldDecodeThumbnail, thumbDataUri]);\n\n // TODO Find a way to update thumbnail on theme change\n const theme = selectTheme(getGlobal());\n\n const dataUri = useMemo(() => {\n const uri = shouldDecodeThumbnail ? thumbnailDecoded : thumbDataUri;\n if (!uri || theme !== 'dark') return uri;\n\n return uri.replace('<svg', '<svg fill=\"white\"');\n }, [shouldDecodeThumbnail, thumbDataUri, thumbnailDecoded, theme]);\n\n return dataUri;\n}\n","import type { 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 { useEffect, useState } from '../lib/teact/teact';\nimport type { ApiDimensions } from '../api/types';\n\nimport { throttle } from '../util/schedulers';\nimport windowSize from '../util/windowSize';\nimport useDebouncedCallback from './useDebouncedCallback';\n\nconst THROTTLE = 250;\n\nconst useWindowSize = () => {\n const [size, setSize] = useState<ApiDimensions>(windowSize.get());\n const [isResizing, setIsResizing] = useState(false);\n const setIsResizingDebounced = useDebouncedCallback(setIsResizing, [], THROTTLE, true);\n\n useEffect(() => {\n const throttledSetIsResizing = throttle(() => {\n setIsResizing(true);\n }, THROTTLE, true);\n\n const throttledSetSize = throttle(() => {\n setSize(windowSize.get());\n setIsResizingDebounced(false);\n }, THROTTLE, false);\n\n const handleResize = () => {\n throttledSetIsResizing();\n throttledSetSize();\n };\n\n window.addEventListener('resize', handleResize);\n\n return () => {\n window.removeEventListener('resize', handleResize);\n };\n }, [setIsResizingDebounced]);\n\n return { ...size, isResizing };\n};\n\nexport default useWindowSize;\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', 'load']);\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 type {\n VirtualElement,\n VirtualElementComponent,\n VirtualElementTag,\n VirtualElementParent,\n VirtualElementChildren,\n VirtualElementReal,\n VirtualElementFragment,\n} from './teact';\nimport {\n hasElementChanged,\n isComponentElement,\n isTagElement,\n isParentElement,\n isTextElement,\n isEmptyElement,\n mountComponent,\n renderComponent,\n unmountComponent,\n isFragmentElement,\n} from './teact';\nimport generateIdFor from '../../util/generateIdFor';\nimport { DEBUG } from '../../config';\nimport { addEventListener, removeAllDelegatedListeners, removeEventListener } from './dom-events';\nimport { unique } from '../../util/iteratees';\n\ntype VirtualDomHead = {\n children: [VirtualElement] | [];\n};\n\nconst FILTERED_ATTRIBUTES = new Set(['key', 'ref', 'teactFastList', 'teactOrderKey']);\nconst HTML_ATTRIBUTES = new Set(['dir', 'role', 'form']);\nconst CONTROLLABLE_TAGS = ['INPUT', 'TEXTAREA', 'SELECT'];\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 | undefined, parentEl: HTMLElement) {\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 const $newElement = renderWithVirtual(parentEl, $head.children[0], $element, $head, 0);\n $head.children = $newElement ? [$newElement] : [];\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<T extends VirtualElement | undefined>(\n parentEl: HTMLElement,\n $current: VirtualElement | undefined,\n $new: T,\n $parent: VirtualElementParent | VirtualDomHead,\n index: number,\n options: {\n skipComponentUpdate?: boolean;\n nextSibling?: ChildNode;\n fragment?: DocumentFragment;\n } = {},\n): T {\n const { skipComponentUpdate, fragment } = options;\n let { nextSibling } = options;\n\n const isCurrentComponent = $current && isComponentElement($current);\n const isNewComponent = $new && isComponentElement($new);\n const $newAsReal = $new as VirtualElementReal;\n\n const isCurrentFragment = $current && !isCurrentComponent && isFragmentElement($current);\n const isNewFragment = $new && !isNewComponent && isFragmentElement($new);\n\n if (\n !skipComponentUpdate\n && isCurrentComponent && isNewComponent\n && !hasElementChanged($current!, $new!)\n ) {\n $new = updateComponent($current, $new as VirtualElementComponent) as typeof $new;\n }\n\n // Parent element may have changed, so we need to update the listener closure.\n if (!skipComponentUpdate && isNewComponent && ($new as VirtualElementComponent).componentInstance.isMounted) {\n setupComponentUpdateListener(parentEl, $new as VirtualElementComponent, $parent, index);\n }\n\n if ($current === $new) {\n return $new;\n }\n\n if (DEBUG && $new) {\n const newTarget = 'target' in $new && $new.target;\n if (newTarget && (!$current || ('target' in $current && newTarget !== $current.target))) {\n throw new Error('[Teact] Cached virtual element was moved within tree');\n }\n }\n\n if (!$current && $new) {\n if (isNewComponent || isNewFragment) {\n if (isNewComponent) {\n $new = initComponent(parentEl, $new as VirtualElementComponent, $parent, index) as typeof $new;\n }\n\n mountChildren(parentEl, $new as VirtualElementComponent | VirtualElementFragment, { nextSibling, fragment });\n } else {\n const node = createNode($newAsReal);\n $newAsReal.target = node;\n insertBefore(fragment || parentEl, node, nextSibling);\n }\n } else if ($current && !$new) {\n remount(parentEl, $current, undefined);\n } else if ($current && $new) {\n if (hasElementChanged($current, $new)) {\n if (!nextSibling) {\n nextSibling = getNextSibling($current);\n }\n\n if (isNewComponent || isNewFragment) {\n if (isNewComponent) {\n $new = initComponent(parentEl, $new as VirtualElementComponent, $parent, index) as typeof $new;\n }\n\n remount(parentEl, $current, undefined);\n mountChildren(parentEl, $new as VirtualElementComponent | VirtualElementFragment, { nextSibling, fragment });\n } else {\n const node = createNode($newAsReal);\n $newAsReal.target = node;\n remount(parentEl, $current, node, nextSibling);\n }\n } else {\n const isComponent = isCurrentComponent && isNewComponent;\n const isFragment = isCurrentFragment && isNewFragment;\n\n if (isComponent || isFragment) {\n ($new as VirtualElementComponent | VirtualElementFragment).children = renderChildren(\n $current,\n $new as VirtualElementComponent | VirtualElementFragment,\n parentEl,\n nextSibling,\n );\n } else {\n const $currentAsReal = $current as VirtualElementReal;\n const currentTarget = $currentAsReal.target!;\n\n $newAsReal.target = currentTarget;\n $currentAsReal.target = undefined; // Help GC\n\n const isTag = isTagElement($current);\n if (isTag) {\n const $newAsTag = $new as VirtualElementTag;\n\n $newAsTag.props.ref = $current.props.ref;\n\n if (nextSibling) {\n insertBefore(parentEl, currentTarget, nextSibling);\n }\n\n updateAttributes($current, $newAsTag, currentTarget as HTMLElement);\n\n $newAsTag.children = renderChildren(\n $current,\n $newAsTag,\n currentTarget as HTMLElement,\n );\n }\n }\n }\n }\n\n return $new;\n}\n\nfunction initComponent(\n parentEl: HTMLElement,\n $element: VirtualElementComponent,\n $parent: VirtualElementParent | VirtualDomHead,\n index: number,\n) {\n const { componentInstance } = $element;\n\n if (!componentInstance.isMounted) {\n $element = mountComponent(componentInstance);\n setupComponentUpdateListener(parentEl, $element, $parent, index);\n\n const $firstChild = $element.children[0];\n if (isComponentElement($firstChild)) {\n $element.children = [initComponent(parentEl, $firstChild, $element, 0)];\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 parentEl: HTMLElement,\n $element: VirtualElementComponent,\n $parent: VirtualElementParent | VirtualDomHead,\n index: number,\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 );\n };\n}\n\nfunction mountChildren(\n parentEl: HTMLElement,\n $element: VirtualElementComponent | VirtualElementFragment,\n options: {\n nextSibling?: ChildNode;\n fragment?: DocumentFragment;\n },\n) {\n $element.children = $element.children.map(($child, i) => {\n return renderWithVirtual(parentEl, undefined, $child, $element, i, options);\n });\n}\n\nfunction unmountChildren(parentEl: HTMLElement, $element: VirtualElementComponent | VirtualElementFragment) {\n $element.children.forEach(($child) => {\n renderWithVirtual(parentEl, $child, undefined, $element, -1);\n });\n}\n\nfunction createNode($element: VirtualElementReal): Node {\n if (isEmptyElement($element)) {\n return document.createTextNode('');\n }\n\n if (isTextElement($element)) {\n return document.createTextNode($element.value);\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 processControlled(tag, props);\n\n Object.entries(props).forEach(([key, value]) => {\n if (props[key] !== undefined) {\n setAttribute(element, key, value);\n }\n });\n\n processUncontrolledOnMount(element, props);\n\n $element.children = children.map(($child, i) => (\n renderWithVirtual(element, undefined, $child, $element, i)\n ));\n\n return element;\n}\n\nfunction remount(\n parentEl: HTMLElement,\n $current: VirtualElement,\n node: Node | undefined,\n componentNextSibling?: ChildNode,\n) {\n const isComponent = isComponentElement($current);\n const isFragment = !isComponent && isFragmentElement($current);\n\n if (isComponent || isFragment) {\n if (isComponent) {\n unmountComponent($current.componentInstance);\n }\n\n unmountChildren(parentEl, $current);\n\n if (node) {\n insertBefore(parentEl, node, componentNextSibling);\n }\n } else {\n if (node) {\n parentEl.replaceChild(node, $current.target!);\n } else {\n parentEl.removeChild($current.target!);\n }\n\n unmountRealTree($current);\n }\n}\n\nexport function unmountRealTree($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 if ($element.props.ref?.current === $element.target) {\n $element.props.ref.current = undefined;\n }\n }\n }\n\n if ($element.target) {\n $element.target = undefined; // Help GC\n }\n\n if (!isParentElement($element)) {\n return;\n }\n }\n\n $element.children.forEach(unmountRealTree);\n}\n\nfunction insertBefore(parentEl: HTMLElement | DocumentFragment, node: Node, nextSibling?: ChildNode) {\n if (nextSibling) {\n parentEl.insertBefore(node, nextSibling);\n } else {\n parentEl.appendChild(node);\n }\n}\n\nfunction getNextSibling($current: VirtualElement): ChildNode | undefined {\n if (isComponentElement($current) || isFragmentElement($current)) {\n const lastChild = $current.children[$current.children.length - 1];\n return getNextSibling(lastChild);\n }\n\n const target = $current.target!;\n const { nextSibling } = target;\n return nextSibling || undefined;\n}\n\nfunction renderChildren(\n $current: VirtualElementParent, $new: VirtualElementParent, currentEl: HTMLElement, nextSibling?: ChildNode,\n) {\n if (DEBUG) {\n DEBUG_checkKeyUniqueness($new.children);\n }\n\n if (('props' in $new) && $new.props.teactFastList) {\n return renderFastListChildren($current, $new, currentEl);\n }\n\n const currentChildrenLength = $current.children.length;\n const newChildrenLength = $new.children.length;\n const maxLength = Math.max(currentChildrenLength, newChildrenLength);\n const newChildren = [];\n\n const fragment = newChildrenLength > currentChildrenLength ? document.createDocumentFragment() : undefined;\n const lastCurrentChild = $current.children[currentChildrenLength - 1];\n const fragmentNextSibling = nextSibling || (\n newChildrenLength > currentChildrenLength && lastCurrentChild ? getNextSibling(lastCurrentChild) : undefined\n );\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 >= currentChildrenLength ? { fragment } : { nextSibling },\n );\n\n if ($newChild) {\n newChildren.push($newChild);\n }\n }\n\n if (fragment) {\n insertBefore(currentEl, fragment, fragmentNextSibling);\n }\n\n return newChildren;\n}\n\n// This function allows to prepend/append a bunch of new DOM nodes to the top/bottom of preserved ones.\n// It also allows to selectively move particular preserved nodes within their DOM list.\nfunction renderFastListChildren($current: VirtualElementParent, $new: VirtualElementParent, currentEl: HTMLElement) {\n const newKeys = new Set(\n $new.children.map(($newChild) => {\n const key = 'props' in $newChild ? $newChild.props.key : undefined;\n\n if (DEBUG && isParentElement($newChild)) {\n // eslint-disable-next-line no-null/no-null\n if (key === undefined || key === null) {\n // eslint-disable-next-line no-console\n console.warn('Missing `key` in `teactFastList`');\n }\n\n if (isFragmentElement($newChild)) {\n throw new Error('[Teact] Fragment can not be child of container with `teactFastList`');\n }\n }\n\n return key;\n }),\n );\n\n // Build a collection of old children that also remain in the new list\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 process 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 // Otherwise, we just remove it\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 orderKey: 'props' in $currentChild ? $currentChild.props.teactOrderKey : undefined,\n };\n return acc;\n }, {} as Record<string, { $element: VirtualElement; index: number; orderKey?: number }>);\n\n let newChildren: VirtualElement[] = [];\n\n let fragmentElements: 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 if (!fragmentElements) {\n fragmentElements = [];\n fragmentIndex = i;\n }\n\n fragmentElements.push($newChild);\n return;\n }\n\n // This prepends new children to the top\n if (fragmentElements) {\n newChildren = newChildren.concat(renderFragment(fragmentElements, fragmentIndex!, currentEl, $new));\n fragmentElements = undefined;\n fragmentIndex = undefined;\n }\n\n // Now we check if a preserved node was moved within preserved list\n const newOrderKey = 'props' in $newChild ? $newChild.props.teactOrderKey : undefined;\n // That is indicated by a changed `teactOrderKey` value\n const shouldMoveNode = (\n currentChildInfo.index !== currentPreservedIndex && currentChildInfo.orderKey !== newOrderKey\n );\n const isMovingDown = shouldMoveNode && currentPreservedIndex > currentChildInfo.index;\n\n if (!shouldMoveNode || isMovingDown) {\n currentPreservedIndex++;\n }\n\n newChildren.push(\n renderWithVirtual(currentEl, currentChildInfo.$element, $newChild, $new, i, {\n // `+ 1` is needed because before moving down the node still takes place above\n nextSibling: shouldMoveNode ? currentEl.childNodes[isMovingDown ? i + 1 : i] : undefined,\n }),\n );\n });\n\n // This appends new children to the bottom\n if (fragmentElements) {\n newChildren = newChildren.concat(renderFragment(fragmentElements, fragmentIndex!, currentEl, $new));\n }\n\n return newChildren;\n}\n\nfunction renderFragment(\n elements: VirtualElement[], fragmentIndex: number, parentEl: HTMLElement, $parent: VirtualElementParent,\n) {\n const nextSibling = parentEl.childNodes[fragmentIndex];\n\n if (elements.length === 1) {\n return [renderWithVirtual(parentEl, undefined, elements[0], $parent, fragmentIndex, { nextSibling })];\n }\n\n const fragment = document.createDocumentFragment();\n const newChildren = elements.map(($element, i) => (\n renderWithVirtual(parentEl, undefined, $element, $parent, fragmentIndex + i, { fragment })\n ));\n\n insertBefore(parentEl, fragment, nextSibling);\n\n return newChildren;\n}\n\nfunction processControlled(tag: string, props: AnyLiteral) {\n // TODO Remove after tests\n if (!props.teactExperimentControlled) {\n return;\n }\n\n const isValueControlled = props.value !== undefined;\n const isCheckedControlled = props.checked !== undefined;\n const isControlled = (isValueControlled || isCheckedControlled) && CONTROLLABLE_TAGS.includes(tag.toUpperCase());\n if (!isControlled) {\n return;\n }\n\n const {\n value, checked, onInput, onChange,\n } = props;\n\n props.onChange = undefined;\n props.onInput = (e: React.ChangeEvent<HTMLInputElement>) => {\n onInput?.(e);\n onChange?.(e);\n\n if (value !== undefined) {\n e.currentTarget.value = value;\n }\n\n if (checked !== undefined) {\n e.currentTarget.checked = checked;\n }\n };\n}\n\nfunction processUncontrolledOnMount(element: HTMLElement, props: AnyLiteral) {\n if (!CONTROLLABLE_TAGS.includes(element.tagName)) {\n return;\n }\n\n if (props.defaultValue) {\n setAttribute(element, 'value', props.defaultValue);\n }\n\n if (props.defaultChecked) {\n setAttribute(element, 'checked', props.defaultChecked);\n }\n}\n\nfunction updateAttributes($current: VirtualElementTag, $new: VirtualElementTag, element: HTMLElement) {\n processControlled(element.tagName, $new.props);\n\n const currentEntries = Object.entries($current.props);\n const newEntries = Object.entries($new.props);\n\n currentEntries.forEach(([key, currentValue]) => {\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 newEntries.forEach(([key, newValue]) => {\n const currentValue = $current.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 if ((element as HTMLInputElement).value !== value) {\n (element as HTMLInputElement).value = value;\n }\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: VirtualElementParent | VirtualDomHead) {\n DEBUG_virtualTreeSize += $current.children.length;\n\n $current.children.forEach(($child) => {\n if (isParentElement($child)) {\n DEBUG_addToVirtualTreeSize($child);\n }\n });\n}\n\n// eslint-disable-next-line @typescript-eslint/naming-convention\nfunction DEBUG_checkKeyUniqueness(children: VirtualElementChildren) {\n const firstChild = children[0];\n if (firstChild && 'props' in firstChild && firstChild.props.key !== undefined) {\n const keys = children.reduce((acc: any[], child) => {\n if ('props' in child && child.props.key) {\n acc.push(child.props.key);\n }\n\n return acc;\n }, []);\n\n if (keys.length !== unique(keys).length) {\n throw new Error('[Teact] Children keys are not unique');\n }\n }\n}\n\nconst TeactDOM = { render };\nexport default TeactDOM;\n","import type { ReactElement } from 'react';\nimport { DEBUG, DEBUG_MORE } from '../../config';\nimport {\n fastRaf, fastRafPrimary, onTickEnd, onTickEndPrimary, throttleWithPrimaryRaf, throttleWithRaf,\n} from '../../util/schedulers';\nimport { orderBy } from '../../util/iteratees';\nimport { getUnequalProps } from '../../util/arePropsShallowEqual';\nimport { handleError } from '../../util/handleError';\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 Fragment,\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 interface VirtualElementFragment {\n type: VirtualElementTypesEnum.Fragment;\n target?: Node;\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?: readonly any[];\n cleanup?: Function;\n }[];\n };\n memos: {\n cursor: number;\n byCursor: {\n value: any;\n dependencies: any[];\n }[];\n };\n refs: {\n cursor: number;\n byCursor: {\n current: 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\n | VirtualElementFragment;\nexport type VirtualElementParent =\n VirtualElementTag\n | VirtualElementComponent\n | VirtualElementFragment;\nexport type VirtualElementChildren = VirtualElement[];\nexport type VirtualElementReal = Exclude<VirtualElement, VirtualElementComponent | VirtualElementFragment>;\n\n// Compatibility with JSX types\nexport type TeactNode =\n ReactElement\n | string\n | number\n | boolean\n | TeactNode[];\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 isFragmentElement($element: VirtualElement): $element is VirtualElementFragment {\n return $element.type === VirtualElementTypesEnum.Fragment;\n}\n\nexport function isParentElement($element: VirtualElement): $element is VirtualElementParent {\n return isTagElement($element) || isComponentElement($element) || isFragmentElement($element);\n}\n\nfunction createElement(\n source: string | FC | typeof Fragment,\n props: Props,\n ...children: any[]\n): VirtualElementParent | VirtualElementChildren {\n children = children.flat();\n\n if (source === Fragment) {\n return buildFragmentElement(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 buildFragmentElement(children: any[]): VirtualElementFragment {\n return {\n type: VirtualElementTypesEnum.Fragment,\n children: dropEmptyTail(children, true).map(buildChildElement),\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 refs: {\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 return {\n type: VirtualElementTypesEnum.Component,\n componentInstance,\n props: componentInstance.props,\n children: dropEmptyTail(children, true).map(buildChildElement),\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[], noEmpty = false) {\n let i = children.length - 1;\n\n for (; i >= 0; i--) {\n if (!isEmptyPlaceholder(children[i])) {\n break;\n }\n }\n\n if (i === children.length - 1) {\n return children;\n }\n\n if (i === -1 && noEmpty) {\n return children.slice(0, 1);\n }\n\n return children.slice(0, i + 1);\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 (isParentElement(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 componentInstance.hooks.refs.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: any) {\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 children = Array.isArray(newRenderedValue) ? newRenderedValue : [newRenderedValue];\n componentInstance.$element = buildComponentElement(componentInstance, children);\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 mountComponent(componentInstance: ComponentInstance) {\n renderComponent(componentInstance);\n componentInstance.isMounted = true;\n return componentInstance.$element;\n}\n\nexport function unmountComponent(componentInstance: ComponentInstance) {\n if (!componentInstance.isMounted) {\n return;\n }\n\n componentInstance.hooks.effects.byCursor.forEach((effect) => {\n if (effect.cleanup) {\n try {\n effect.cleanup();\n } catch (err: any) {\n handleError(err);\n } finally {\n effect.cleanup = undefined;\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.value = undefined as any;\n hook.dependencies = undefined as any;\n });\n\n componentInstance.hooks.refs.byCursor.forEach((hook) => {\n hook.current = 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 useState<T>(initial?: T, debugKey?: string): [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 debugKey\n ? `State update for ${debugKey}, next value: `\n : `State 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?: readonly 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 (!cleanup) {\n return;\n }\n\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: any) {\n handleError(err);\n } finally {\n byCursor[cursor].cleanup = undefined;\n }\n }\n\n function exec() {\n if (!componentInstance.isMounted) {\n return;\n }\n\n execCleanup();\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 const result = effect();\n if (typeof result === 'function') {\n byCursor[cursor].cleanup = result;\n }\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]?.cleanup,\n };\n\n renderingInstance.hooks.effects.cursor++;\n}\n\nexport function useEffect(effect: () => Function | void, dependencies?: readonly any[], debugKey?: string) {\n return useLayoutEffectBase(fastRaf, fastRafPrimary, effect, dependencies, debugKey);\n}\n\nexport function useLayoutEffect(effect: () => Function | void, dependencies?: readonly 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 { value } = 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 value = resolver();\n }\n\n byCursor[cursor] = {\n value,\n dependencies,\n };\n\n renderingInstance.hooks.memos.cursor++;\n\n return value;\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 const { cursor, byCursor } = renderingInstance.hooks.refs;\n if (!byCursor[cursor]) {\n byCursor[cursor] = {\n current: initial,\n };\n }\n\n renderingInstance.hooks.refs.cursor++;\n\n return byCursor[cursor];\n}\n\nexport function memo<T extends FC>(Component: T, debugKey?: string) {\n return function TeactMemoWrapper(props: Props) {\n // eslint-disable-next-line react-hooks/exhaustive-deps\n return useMemo(() => createElement(Component, props), Object.values(props), debugKey);\n } as T;\n}\n\nexport default {\n createElement,\n Fragment,\n};\n","import type { FC, FC_withDebug, Props } from './teact';\nimport React, { useEffect, useState } 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 { handleError } from '../../util/handleError';\nimport { isHeavyAnimating } from '../../hooks/useHeavyAnimationCheck';\n\nexport default React;\n\ntype GlobalState =\n AnyLiteral\n & { DEBUG_capturedId?: number };\ntype ActionNames = string;\ntype ActionPayload = any;\n\ninterface ActionOptions {\n forceOnHeavyAnimation?: boolean;\n // Workaround for iOS gesture history navigation\n forceSyncOnIOs?: boolean;\n}\n\ntype Actions = Record<ActionNames, (payload?: ActionPayload, options?: ActionOptions) => void>;\n\ntype ActionHandler = (\n global: GlobalState,\n actions: Actions,\n payload: any,\n) => GlobalState | void | Promise<void>;\n\ntype MapStateToProps<OwnProps = undefined> = ((global: GlobalState, ownProps: OwnProps) => AnyLiteral);\n\nlet currentGlobal = {} as GlobalState;\n\n// eslint-disable-next-line @typescript-eslint/naming-convention\nlet DEBUG_currentCapturedId: number | undefined;\n// eslint-disable-next-line @typescript-eslint/naming-convention\nconst DEBUG_releaseCapturedIdThrottled = throttleWithTickEnd(() => {\n DEBUG_currentCapturedId = undefined;\n});\n\nconst actionHandlers: Record<string, ActionHandler[]> = {};\nconst callbacks: Function[] = [updateContainers];\nconst actions = {} as Actions;\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?: ActionOptions) {\n if (typeof newGlobal === 'object' && newGlobal !== currentGlobal) {\n if (DEBUG) {\n if (newGlobal.DEBUG_capturedId && newGlobal.DEBUG_capturedId !== DEBUG_currentCapturedId) {\n throw new Error('[TeactN.setGlobal] Attempt to set an outdated global');\n }\n\n DEBUG_currentCapturedId = undefined;\n }\n\n currentGlobal = newGlobal;\n if (options?.forceSyncOnIOs) {\n runCallbacks(true);\n } else {\n runCallbacksThrottled(options?.forceOnHeavyAnimation);\n }\n }\n}\n\nexport function getGlobal() {\n if (DEBUG) {\n DEBUG_currentCapturedId = Math.random();\n currentGlobal = {\n ...currentGlobal,\n DEBUG_capturedId: DEBUG_currentCapturedId,\n };\n DEBUG_releaseCapturedIdThrottled();\n }\n\n return currentGlobal;\n}\n\nexport function getActions() {\n return actions;\n}\n\nlet actionQueue: NoneToVoidFunction[] = [];\n\nfunction handleAction(name: string, payload?: ActionPayload, options?: ActionOptions) {\n actionQueue.push(() => {\n actionHandlers[name]?.forEach((handler) => {\n const response = handler(DEBUG ? getGlobal() : currentGlobal, actions, payload);\n if (!response || typeof response.then === 'function') {\n return;\n }\n\n setGlobal(response as GlobalState, options);\n });\n });\n\n if (actionQueue.length === 1) {\n try {\n while (actionQueue.length) {\n actionQueue[0]();\n actionQueue.shift();\n }\n } finally {\n actionQueue = [];\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: any) {\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 addActionHandler(name: ActionNames, handler: ActionHandler) {\n if (!actionHandlers[name]) {\n actionHandlers[name] = [];\n\n actions[name] = (payload?: ActionPayload, options?: ActionOptions) => {\n handleAction(name, payload, options);\n };\n }\n\n actionHandlers[name].push(handler);\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: any) {\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\nexport function typify<ProjectGlobalState, ActionPayloads, NonTypedActionNames extends string = never>() {\n type NonTypedActionPayloads = {\n [ActionName in NonTypedActionNames]: ActionPayload;\n };\n\n type ProjectActionTypes =\n ActionPayloads\n & NonTypedActionPayloads;\n\n type ProjectActionNames = keyof ProjectActionTypes;\n\n type ProjectActions = {\n [ActionName in ProjectActionNames]: (\n payload?: ProjectActionTypes[ActionName],\n options?: ActionOptions,\n ) => void;\n };\n\n type ActionHandlers = {\n [ActionName in keyof ProjectActionTypes]: (\n global: ProjectGlobalState,\n actions: ProjectActions,\n payload: ProjectActionTypes[ActionName],\n ) => ProjectGlobalState | void | Promise<void>;\n };\n\n return {\n getGlobal: getGlobal as () => ProjectGlobalState,\n setGlobal: setGlobal as (state: ProjectGlobalState, options?: ActionOptions) => void,\n getActions: getActions as () => ProjectActions,\n addActionHandler: addActionHandler as <ActionName extends ProjectActionNames>(\n name: ActionName,\n handler: ActionHandlers[ActionName],\n ) => void,\n withGlobal: withGlobal as <OwnProps>(\n mapStateToProps: ((global: ProjectGlobalState, ownProps: OwnProps) => AnyLiteral),\n ) => (Component: FC) => FC<OwnProps>,\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 f8312f3 12.03.2022\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]|\\ud83e\\udef1\\ud83c\\udffb\\u200d\\ud83e\\udef2\\ud83c[\\udffc-\\udfff]|\\ud83e\\udef1\\ud83c\\udffc\\u200d\\ud83e\\udef2\\ud83c[\\udffb\\udffd-\\udfff]|\\ud83e\\udef1\\ud83c\\udffd\\u200d\\ud83e\\udef2\\ud83c[\\udffb\\udffc\\udffe\\udfff]|\\ud83e\\udef1\\ud83c\\udffe\\u200d\\ud83e\\udef2\\ud83c[\\udffb-\\udffd\\udfff]|\\ud83e\\udef1\\ud83c\\udfff\\u200d\\ud83e\\udef2\\ud83c[\\udffb-\\udffe]|\\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]|\\ud83e\\udd1d\\ud83c[\\udffb-\\udfff]|\\ud83d[\\udc6b-\\udc6d\\udc8f\\udc91]|\\ud83e\\udd1d)|(?:\\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\\udec3-\\udec5\\udef0-\\udef6]|[\\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\\udedd-\\udedf\\udeeb\\udeec\\udef4-\\udefc\\udfe0-\\udfeb\\udff0]|\\ud83e[\\udd0d\\udd0e\\udd10-\\udd17\\udd20-\\udd25\\udd27-\\udd2f\\udd3a\\udd3c\\udd3f-\\udd45\\udd47-\\udd76\\udd78-\\uddb4\\uddb7\\uddba\\uddbc-\\uddcc\\uddd0\\uddde-\\uddff\\ude70-\\ude74\\ude78-\\ude7c\\ude80-\\ude86\\ude90-\\udeac\\udeb0-\\udeba\\udec0-\\udec2\\uded0-\\uded9\\udee0-\\udee7]|[\\u23e9-\\u23ec\\u23f0\\u23f3\\u267e\\u26ce\\u2705\\u2728\\u274c\\u274e\\u2753-\\u2755\\u2795-\\u2797\\u27b0\\u27bf\\ue50a])|\\ufe0f/g;\n","import type { TeactNode } from '../lib/teact/teact';\nimport type {\n ApiBotInlineMediaResult, ApiBotInlineResult, ApiBotInlineSwitchPm,\n ApiChatInviteImporter,\n ApiExportedInvite,\n ApiLanguage, ApiMessage, ApiShippingAddress, ApiStickerSet, ApiWebDocument,\n} from '../api/types';\n\nexport type TextPart = TeactNode;\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';\nexport type AnimationLevel = 0 | 1 | 2;\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: AnimationLevel;\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 shouldArchiveAndMuteNewNonContact?: 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 photo?: ApiWebDocument;\n text?: string;\n title?: string;\n}\n\nexport enum SettingsScreens {\n Main,\n EditProfile,\n Notifications,\n DataStorage,\n Language,\n ActiveSessions,\n General,\n GeneralChatBackground,\n GeneralChatBackgroundColor,\n Privacy,\n PrivacyPhoneNumber,\n PrivacyLastSeen,\n PrivacyProfilePhoto,\n PrivacyPhoneCall,\n PrivacyPhoneP2P,\n PrivacyForwarding,\n PrivacyVoiceMessages,\n PrivacyGroupChats,\n PrivacyPhoneNumberAllowedContacts,\n PrivacyPhoneNumberDeniedContacts,\n PrivacyLastSeenAllowedContacts,\n PrivacyLastSeenDeniedContacts,\n PrivacyProfilePhotoAllowedContacts,\n PrivacyProfilePhotoDeniedContacts,\n PrivacyPhoneCallAllowedContacts,\n PrivacyPhoneCallDeniedContacts,\n PrivacyPhoneP2PAllowedContacts,\n PrivacyPhoneP2PDeniedContacts,\n PrivacyForwardingAllowedContacts,\n PrivacyForwardingDeniedContacts,\n PrivacyVoiceMessagesAllowedContacts,\n PrivacyVoiceMessagesDeniedContacts,\n PrivacyGroupChatsAllowedContacts,\n PrivacyGroupChatsDeniedContacts,\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 ActiveWebsites,\n PasscodeDisabled,\n PasscodeNewPasscode,\n PasscodeNewPasscodeConfirm,\n PasscodeEnabled,\n PasscodeChangePasscodeCurrent,\n PasscodeChangePasscodeNew,\n PasscodeChangePasscodeConfirm,\n PasscodeTurnOff,\n PasscodeCongratulations,\n Experimental,\n Stickers,\n QuickReaction,\n CustomEmoji,\n}\n\nexport type StickerSetOrRecent = Pick<ApiStickerSet, (\n 'id' | 'title' | 'count' | 'stickers' | 'hasThumbnail' | 'isLottie' | 'isVideos' | 'isEmoji' | 'installedDate'\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 Search,\n Management,\n Statistics,\n MessageStatistics,\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 requesters?: 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' | 'voiceMessages' |\n'forwards' | 'chatInvite' | 'phoneCall' | 'phoneP2P';\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 ConfirmPayment,\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 ChannelRemovedUsers,\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 * 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 ** 3,\n easeOutCubic: (t: number) => (--t) * t * t + 1,\n easeInOutCubic: (t: number) => (t < 0.5 ? 4 * t ** 3 : (t - 1) * (2 * t - 2) * (2 * t - 2) + 1),\n easeInQuart: (t: number) => t ** 4,\n easeOutQuart: (t: number) => 1 - (--t) * t ** 3,\n easeInOutQuart: (t: number) => (t < 0.5 ? 8 * t ** 4 : 1 - 8 * (--t) * t ** 3),\n easeInQuint: (t: number) => t ** 5,\n easeOutQuint: (t: number) => 1 + (--t) * t ** 4,\n easeInOutQuint: (t: number) => (t < 0.5 ? 16 * t ** 5 : 1 + 16 * (--t) * t ** 4),\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[])[];\ntype ClassNameBuilder =\n ((elementName: string, ...modifiers: PartsWithGlobals) => string)\n & Record<string, 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 }) as ClassNameBuilder;\n}\n","type Parts = (string | false | undefined)[];\n\nexport default function buildStyle(...parts: Parts) {\n return parts.filter(Boolean).join(';');\n}\n","// eslint-disable-next-line no-restricted-globals\nconst cacheApi = self.caches;\n\nexport enum Type {\n Text,\n Blob,\n Json,\n ArrayBuffer,\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 case Type.ArrayBuffer:\n return await response.arrayBuffer();\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 | ArrayBuffer | string) {\n if (!cacheApi) {\n return undefined;\n }\n\n try {\n const cacheData = typeof data === 'string' || data instanceof Blob || data instanceof ArrayBuffer\n ? data\n : 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 remove(cacheName: string, key: string) {\n try {\n if (!cacheApi) {\n return undefined;\n }\n\n const cache = await cacheApi.open(cacheName);\n return await cache.delete(key);\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 function hasCallbacks() {\n return Boolean(callbacks.length);\n }\n\n return {\n runCallbacks,\n addCallback,\n removeCallback,\n hasCallbacks,\n };\n}\n\nexport type CallbackManager = ReturnType<typeof createCallbackManager>;\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 { DEBUG } from '../config';\n\nexport const CLIPBOARD_ITEM_SUPPORTED = window.navigator.clipboard && window.ClipboardItem;\n\nconst textCopyEl = document.createElement('textarea');\ntextCopyEl.setAttribute('readonly', '');\ntextCopyEl.tabIndex = -1;\ntextCopyEl.className = 'visually-hidden';\n\nexport const copyTextToClipboard = (str: string): void => {\n textCopyEl.value = str;\n document.body.appendChild(textCopyEl);\n const selection = document.getSelection();\n\n if (selection) {\n // Store previous selection\n const rangeToRestore = selection.rangeCount > 0 && selection.getRangeAt(0);\n textCopyEl.select();\n document.execCommand('copy');\n // Restore the original selection\n if (rangeToRestore) {\n selection.removeAllRanges();\n selection.addRange(rangeToRestore);\n }\n }\n\n document.body.removeChild(textCopyEl);\n};\n\nexport const copyImageToClipboard = (imageUrl?: string) => {\n if (!imageUrl) return;\n const canvas = document.createElement('canvas');\n const ctx = canvas.getContext('2d');\n const imageEl = new Image();\n imageEl.onload = (e: Event) => {\n if (ctx && e.currentTarget) {\n const img = e.currentTarget as HTMLImageElement;\n canvas.width = img.width;\n canvas.height = img.height;\n ctx.drawImage(img, 0, 0, img.width, img.height);\n canvas.toBlob(copyBlobToClipboard, 'image/png', 1);\n }\n };\n\n imageEl.src = imageUrl;\n};\n\nasync function copyBlobToClipboard(pngBlob: Blob | null) {\n if (!pngBlob || !CLIPBOARD_ITEM_SUPPORTED) {\n return;\n }\n\n try {\n await window.navigator.clipboard.write?.([\n new ClipboardItem({\n [pngBlob.type]: pngBlob,\n }),\n ]);\n } catch (error) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error(error);\n }\n }\n}\n","// Sometimes event is fired earlier than animation completes\nconst ANIMATION_END_DELAY = 50;\n\nexport function waitForTransitionEnd(node: Node, handler: NoneToVoidFunction, propertyName?: string) {\n waitForEndEvent('transitionend', node, handler, propertyName);\n}\n\nexport function waitForAnimationEnd(node: Node, handler: NoneToVoidFunction, animationName?: string) {\n waitForEndEvent('animationend', node, handler, animationName);\n}\n\nfunction waitForEndEvent(\n eventType: 'transitionend' | 'animationend',\n node: Node,\n handler: NoneToVoidFunction,\n detailedName?: string,\n) {\n let isHandled = false;\n\n node.addEventListener(eventType, function handleAnimationEnd(e: TransitionEvent | AnimationEvent) {\n if (isHandled || e.target !== e.currentTarget) {\n return;\n }\n\n if (detailedName && (\n (e instanceof TransitionEvent && e.propertyName === detailedName)\n || (e instanceof AnimationEvent && e.animationName === detailedName)\n )) {\n return;\n }\n\n isHandled = true;\n\n node.removeEventListener(eventType, handleAnimationEnd as EventListener);\n\n setTimeout(() => {\n handler();\n }, ANIMATION_END_DELAY);\n } as EventListener);\n}\n","import type { LangFn } from '../hooks/useLang';\nimport withCache from './withCache';\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 getDayStartAt(new Date()) === getDayStartAt(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 noYear = date.getFullYear() === today.getFullYear();\n\n return formatDateToString(date, lang.code, noYear);\n}\n\nexport function formatFullDate(lang: LangFn, datetime: number | Date) {\n return formatDateToString(datetime, lang.code, false, 'numeric');\n}\n\nexport function formatMonthAndYear(lang: LangFn, date: Date, isShort = false) {\n return formatDateToString(date, lang.code, false, isShort ? 'short' : 'long', true);\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 formatCountdownShort(lang: LangFn, msLeft: number) {\n if (msLeft < 60 * 1000) {\n return Math.ceil(msLeft / 1000);\n } else if (msLeft < 60 * 60 * 1000) {\n return Math.ceil(msLeft / (60 * 1000));\n } else if (msLeft < MILLISECONDS_IN_DAY) {\n return lang('MessageTimer.ShortHours', Math.ceil(msLeft / (60 * 60 * 1000)));\n } else {\n return lang('MessageTimer.ShortDays', Math.ceil(msLeft / MILLISECONDS_IN_DAY));\n }\n}\n\nexport function formatLastUpdated(lang: LangFn, currentTime: number, lastUpdated = currentTime) {\n const seconds = currentTime - lastUpdated;\n if (seconds < 60) {\n return lang('LiveLocationUpdated.JustNow');\n } else if (seconds < 60 * 60) {\n return lang('LiveLocationUpdated.MinutesAgo', Math.floor(seconds / 60));\n } else {\n return lang('LiveLocationUpdated.TodayAt', formatTime(lang, lastUpdated));\n }\n}\n\ntype DurationType = 'Seconds' | 'Minutes' | 'Hours' | 'Days' | 'Weeks';\n\nexport function formatTimeDuration(lang: LangFn, duration: number, showLast = 2) {\n if (!duration) {\n return undefined;\n }\n\n const durationRecords: { duration: number; type: DurationType }[] = [];\n const labels = [\n { multiplier: 1, type: 'Seconds' },\n { multiplier: 60, type: 'Minutes' },\n { multiplier: 60, type: 'Hours' },\n { multiplier: 24, type: 'Days' },\n { multiplier: 7, type: 'Weeks' },\n ] as Array<{ multiplier: number; type: DurationType }>;\n let t = 1;\n labels.forEach((label, idx) => {\n t *= label.multiplier;\n\n if (duration < t) {\n return;\n }\n\n const modulus = labels[idx === (labels.length - 1) ? idx : idx + 1].multiplier!;\n durationRecords.push({\n duration: Math.floor((duration / t) % modulus),\n type: label.type,\n });\n });\n\n const out = durationRecords.slice(-showLast).reverse();\n for (let i = out.length - 1; i >= 0; --i) {\n if (out[i].duration === 0) {\n out.splice(i, 1);\n }\n }\n\n // TODO In arabic we don't use \",\" as delimiter rather we use \"and\" each time\n return out.map((l) => lang(l.type, l.duration, 'i')).join(', ');\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 noYear = date.getFullYear() === today.getFullYear();\n const formattedDate = formatDateToString(date, lang.code, noYear, isShort ? 'short' : 'long');\n\n return (isUpperFirst || !isShort ? upperFirst : lowerFirst)(formattedDate);\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\nconst formatDayToStringWithCache = withCache((\n dayStartAt: number,\n locale: string,\n noYear?: boolean,\n monthFormat: 'short' | 'long' | 'numeric' = 'short',\n noDay?: boolean,\n) => {\n return new Date(dayStartAt).toLocaleString(\n locale,\n {\n year: noYear ? undefined : 'numeric',\n month: monthFormat,\n day: noDay ? undefined : 'numeric',\n },\n );\n});\n\nexport function formatDateToString(\n datetime: Date | number,\n locale = 'en-US',\n noYear = false,\n monthFormat: 'short' | 'long' | 'numeric' = 'short',\n noDay = false,\n) {\n const date = typeof datetime === 'number' ? new Date(datetime) : datetime;\n const dayStartAt = getDayStartAt(date);\n\n return formatDayToStringWithCache(dayStartAt, locale, noYear, monthFormat, noDay);\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, { removeVS16s } from '../lib/twemojiRegex';\nimport withCache from './withCache';\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 const LOADED_EMOJIS = new Set<string>();\n\nexport function handleEmojiLoad(event: React.SyntheticEvent<HTMLImageElement>) {\n event.currentTarget.classList.add('open');\n LOADED_EMOJIS.add(event.currentTarget.dataset.path!);\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\nfunction nativeToUnifiedExtended(emoji: string) {\n return nativeToUnified(removeVS16s(emoji));\n}\n\nexport const nativeToUnifiedExtendedWithCache = withCache(nativeToUnifiedExtended);\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 type { 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 CONTENT_TYPES_WITH_PREVIEW,\n PRODUCTION_HOSTNAME,\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 IS_PRODUCTION_HOST = window.location.host === PRODUCTION_HOSTNAME;\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 window.navigator.mediaDevices && 'getUserMedia' in window.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) && isLastEmojiVersionSupported();\nexport const IS_SERVICE_WORKER_SUPPORTED = 'serviceWorker' in navigator;\n// TODO Consider failed service worker\nexport const IS_PROGRESSIVE_SUPPORTED = IS_SERVICE_WORKER_SUPPORTED;\nexport const IS_STREAMING_SUPPORTED = 'MediaSource' in window;\nexport const IS_OPUS_SUPPORTED = Boolean((new Audio()).canPlayType('audio/ogg; codecs=opus'));\nexport const IS_CANVAS_FILTER_SUPPORTED = (\n !IS_TEST && 'filter' in (document.createElement('canvas').getContext('2d') || {})\n);\nexport const IS_REQUEST_FULLSCREEN_SUPPORTED = 'requestFullscreen' in document.createElement('div');\nexport const ARE_CALLS_SUPPORTED = !navigator.userAgent.includes('Firefox');\nexport const LAYERS_ANIMATION_NAME = IS_ANDROID ? 'slide-fade' : IS_IOS ? 'slide-layers' : 'push-slide';\n\nconst TEST_VIDEO = document.createElement('video');\n// `canPlayType(VIDEO_MOV_TYPE)` returns false negative at least for macOS Chrome and iOS Safari\nexport const IS_MOV_SUPPORTED = Boolean(\n TEST_VIDEO.canPlayType(VIDEO_MOV_TYPE).replace('no', '') || IS_IOS || IS_MAC_OS,\n);\n\nif (IS_MOV_SUPPORTED) {\n SUPPORTED_VIDEO_CONTENT_TYPES.add(VIDEO_MOV_TYPE);\n CONTENT_TYPES_WITH_PREVIEW.add(VIDEO_MOV_TYPE);\n}\n\nexport const IS_WEBM_SUPPORTED = Boolean(TEST_VIDEO.canPlayType('video/webm; codecs=\"vp9\"').replace('no', ''))\n && !(IS_MAC_OS && IS_SAFARI); // Safari on MacOS has some issues with WebM\n\nexport const DPR = window.devicePixelRatio || 1;\n\nexport const MASK_IMAGE_DISABLED = true;\nexport const IS_OPFS_SUPPORTED = Boolean(navigator.storage?.getDirectory);\nif (IS_OPFS_SUPPORTED) {\n // Clear old contents\n (async () => {\n try {\n const directory = await navigator.storage.getDirectory();\n await directory.removeEntry('downloads', { recursive: true });\n } catch {\n // Ignore\n }\n })();\n}\n\nexport const IS_BACKDROP_BLUR_SUPPORTED = !IS_TEST && (\n CSS.supports('backdrop-filter: blur()') || CSS.supports('-webkit-backdrop-filter: blur()')\n);\nexport const IS_COMPACT_MENU = !IS_TOUCH_ENV;\nexport const IS_SCROLL_PATCH_NEEDED = !IS_MAC_OS && !IS_IOS && !IS_ANDROID;\nexport const IS_INSTALL_PROMPT_SUPPORTED = 'onbeforeinstallprompt' in window;\n\n// Smaller area reduces scroll jumps caused by `patchChromiumScroll`\nexport const MESSAGE_LIST_SENSITIVE_AREA = IS_SCROLL_PATCH_NEEDED ? 300 : 750;\n\nexport const MAX_BUFFER_SIZE = (IS_ANDROID || IS_IOS ? 512 : 2000) * 1024 ** 2; // 512 OR 2000 MB\n\n// TODO Turn on later as `!IS_IOS && !IS_ANDROID`\nexport const VIDEO_AVATARS_DISABLED = true;\n\nfunction isLastEmojiVersionSupported() {\n const ALLOWABLE_CALCULATION_ERROR_SIZE = 5;\n const inlineEl = document.createElement('span');\n inlineEl.classList.add('emoji-test-element');\n document.body.appendChild(inlineEl);\n\n inlineEl.innerText = '🫱🏻'; // Emoji from 14.0 version\n const newEmojiWidth = inlineEl.offsetWidth;\n inlineEl.innerText = '❤️'; // Emoji from 1.0 version\n const legacyEmojiWidth = inlineEl.offsetWidth;\n\n document.body.removeChild(inlineEl);\n\n return Math.abs(newEmojiWidth - legacyEmojiWidth) < ALLOWABLE_CALCULATION_ERROR_SIZE;\n}\n","import { pause } from './schedulers';\n\n// Polyfill for Safari: `File` is not available in web worker\nif (typeof File === 'undefined') {\n // eslint-disable-next-line no-global-assign, no-restricted-globals, func-names\n self.File = class extends Blob {\n name: string;\n\n constructor(fileBits: BlobPart[], fileName: string, options?: FilePropertyBag) {\n if (options) {\n const { type, ...rest } = options;\n super(fileBits, { type });\n Object.assign(this, rest);\n } else {\n super(fileBits);\n }\n\n this.name = fileName;\n }\n } as typeof File;\n}\n\nexport function dataUriToBlob(dataUri: string) {\n const arr = dataUri.split(',');\n const mime = arr[0].match(/:(.*?);/)![1];\n const bstr = atob(arr[1]);\n let n = bstr.length;\n const u8arr = new Uint8Array(n);\n\n while (n--) {\n u8arr[n] = bstr.charCodeAt(n);\n }\n\n return new Blob([u8arr], { type: mime });\n}\n\nexport function blobToDataUri(blob: Blob): Promise<string> {\n return new Promise((resolve, reject) => {\n const reader = new FileReader();\n\n reader.onload = (e: ProgressEvent<FileReader>) => {\n const { result } = e.target || {};\n if (typeof result === 'string') {\n resolve(result);\n }\n\n reject(new Error('Failed to read blob'));\n };\n\n reader.onerror = reject;\n reader.readAsDataURL(blob);\n });\n}\n\nexport function blobToFile(blob: Blob, fileName: string) {\n return new File([blob], fileName, {\n lastModified: Date.now(),\n type: blob.type,\n });\n}\n\nexport function preloadImage(url: string): Promise<HTMLImageElement> {\n return new Promise((resolve, reject) => {\n const img = new Image();\n img.onload = () => resolve(img);\n img.onerror = reject;\n img.src = url;\n });\n}\n\nexport function preloadVideo(url: string): Promise<HTMLVideoElement> {\n return new Promise((resolve, reject) => {\n const video = document.createElement('video');\n video.volume = 0;\n video.onloadedmetadata = () => resolve(video);\n video.onerror = reject;\n video.src = url;\n });\n}\n\nexport async function createPosterForVideo(url: string): Promise<string | undefined> {\n const video = await preloadVideo(url);\n\n return Promise.race([\n pause(2000) as Promise<undefined>,\n new Promise<string | 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 { addCallback } from '../lib/teact/teactn';\nimport { addActionHandler, getGlobal } from '../global';\n\nimport type { GlobalState } from '../global/types';\nimport type { NotifyException, NotifySettings } from '../types';\nimport type { ApiChat, ApiChatFolder, ApiUser } from '../api/types';\n\nimport {\n ALL_FOLDER_ID, ARCHIVED_FOLDER_ID, DEBUG, SERVICE_NOTIFICATIONS_USER_ID,\n} from '../config';\nimport { selectNotifySettings, selectNotifyExceptions } from '../global/selectors';\nimport { selectIsChatMuted } from '../global/helpers';\nimport { onIdle, throttle } from './schedulers';\nimport { areSortedArraysEqual, unique } from './iteratees';\nimport arePropsShallowEqual from './arePropsShallowEqual';\nimport type { CallbackManager } from './callbacks';\nimport { createCallbackManager } from './callbacks';\n\ninterface FolderSummary {\n id: number;\n listIds?: Set<string>;\n orderedPinnedIds?: string[];\n contacts?: true;\n nonContacts?: true;\n groups?: true;\n channels?: true;\n bots?: true;\n excludeMuted?: true;\n excludeRead?: true;\n excludeArchived?: true;\n excludedChatIds?: Set<string>;\n includedChatIds?: Set<string>;\n pinnedChatIds?: Set<string>;\n}\n\ninterface ChatSummary {\n id: string;\n type: ApiChat['type'];\n isListed: boolean;\n isArchived: boolean;\n isMuted: boolean;\n isUnread: boolean;\n unreadCount?: number;\n unreadMentionsCount?: number;\n order: number;\n isUserBot?: boolean;\n isUserContact?: boolean;\n}\n\nconst UPDATE_THROTTLE = 500;\nconst DEBUG_DURATION_LIMIT = 6;\n\nconst initials = buildInitials();\n\nlet prevGlobal: {\n allFolderListIds?: GlobalState['chats']['listIds']['active'];\n allFolderPinnedIds?: GlobalState['chats']['orderedPinnedIds']['active'];\n archivedFolderListIds?: GlobalState['chats']['listIds']['archived'];\n archivedFolderPinnedIds?: GlobalState['chats']['orderedPinnedIds']['archived'];\n isAllFolderFullyLoaded?: boolean;\n isArchivedFolderFullyLoaded?: boolean;\n chatsById: Record<string, ApiChat>;\n foldersById: Record<string, ApiChatFolder>;\n usersById: Record<string, ApiUser>;\n notifySettings: NotifySettings;\n notifyExceptions?: Record<number, NotifyException>;\n} = initials.prevGlobal;\n\nlet prepared: {\n folderSummariesById: Record<string, FolderSummary>;\n chatSummariesById: Map<string, ChatSummary>;\n folderIdsByChatId: Record<string, number[]>;\n chatIdsByFolderId: Record<number, Set<string> | undefined>;\n isOrderedListJustPatched: Record<number, boolean | undefined>;\n} = initials.prepared;\n\nlet results: {\n orderedIdsByFolderId: Record<string, string[] | undefined>;\n pinnedCountByFolderId: Record<string, number | undefined>; // Also watched by `callbacks.orderedIdsByFolderId`\n chatsCountByFolderId: Record<string, number | undefined>;\n unreadCountersByFolderId: Record<string, {\n chatsCount: number;\n notificationsCount: number;\n } | undefined>;\n} = initials.results;\n\nlet callbacks: {\n orderedIdsByFolderId: Record<number, CallbackManager>;\n chatsCountByFolderId: CallbackManager;\n unreadCountersByFolderId: CallbackManager;\n} = initials.callbacks;\n\nconst updateFolderManagerThrottled = throttle(() => {\n onIdle(() => {\n updateFolderManager(getGlobal());\n });\n}, UPDATE_THROTTLE);\n\nlet inited = false;\n\n/* Getters */\n\nexport function init() {\n inited = true;\n\n addCallback(updateFolderManagerThrottled);\n addActionHandler('reset', reset);\n\n updateFolderManager(getGlobal());\n}\n\nexport function getOrderedIds(folderId: number) {\n if (!inited) init();\n\n return results.orderedIdsByFolderId[folderId];\n}\n\nexport function getPinnedChatsCount(folderId: number) {\n if (!inited) init();\n\n return results.pinnedCountByFolderId[folderId] || 0;\n}\n\nexport function getChatsCount() {\n if (!inited) init();\n\n return results.chatsCountByFolderId;\n}\n\nexport function getUnreadCounters() {\n if (!inited) init();\n\n return results.unreadCountersByFolderId;\n}\n\nexport function getAllNotificationsCount() {\n return getUnreadCounters()[ALL_FOLDER_ID]?.notificationsCount || 0;\n}\n\nexport function getOrderKey(chatId: string) {\n return prepared.chatSummariesById.get(chatId)!.order;\n}\n\n/* Callback managers */\n\nexport function addOrderedIdsCallback(folderId: number, callback: (orderedIds: string[]) => void) {\n if (!callbacks.orderedIdsByFolderId[folderId]) {\n callbacks.orderedIdsByFolderId[folderId] = createCallbackManager();\n }\n\n return callbacks.orderedIdsByFolderId[folderId].addCallback(callback);\n}\n\nexport function addChatsCountCallback(callback: (chatsCount: typeof results.chatsCountByFolderId) => void) {\n return callbacks.chatsCountByFolderId.addCallback(callback);\n}\n\nexport function addUnreadCountersCallback(callback: (unreadCounters: typeof results.unreadCountersByFolderId) => void) {\n return callbacks.unreadCountersByFolderId.addCallback(callback);\n}\n\n/* Global update handlers */\n\nfunction updateFolderManager(global: GlobalState) {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n let DEBUG_startedAt: number;\n if (DEBUG) {\n DEBUG_startedAt = performance.now();\n }\n\n const isAllFolderChanged = Boolean(\n global.chats.listIds.active\n && isMainFolderChanged(ALL_FOLDER_ID, global.chats.listIds.active, global.chats.orderedPinnedIds.active),\n );\n const isArchivedFolderChanged = Boolean(\n global.chats.listIds.archived\n && isMainFolderChanged(ARCHIVED_FOLDER_ID, global.chats.listIds.archived, global.chats.orderedPinnedIds.archived),\n );\n const isAllFullyLoadedChanged = global.chats.isFullyLoaded.active !== prevGlobal.isAllFolderFullyLoaded;\n const isArchivedFullyLoadedChanged = global.chats.isFullyLoaded.archived !== prevGlobal.isArchivedFolderFullyLoaded;\n\n const areFoldersChanged = global.chatFolders.byId !== prevGlobal.foldersById;\n const areChatsChanged = global.chats.byId !== prevGlobal.chatsById;\n const areUsersChanged = global.users.byId !== prevGlobal.usersById;\n const areNotifySettingsChanged = selectNotifySettings(global) !== prevGlobal.notifySettings;\n const areNotifyExceptionsChanged = selectNotifyExceptions(global) !== prevGlobal.notifyExceptions;\n\n let affectedFolderIds: number[] = [];\n\n if (isAllFullyLoadedChanged || isArchivedFullyLoadedChanged) {\n affectedFolderIds = affectedFolderIds.concat(\n updateFullyLoaded(global, isArchivedFullyLoadedChanged),\n );\n }\n\n if (!(\n isAllFolderChanged || isArchivedFolderChanged || areFoldersChanged\n || areChatsChanged || areUsersChanged || areNotifySettingsChanged || areNotifyExceptionsChanged\n )\n ) {\n if (affectedFolderIds.length) {\n updateResults(affectedFolderIds);\n }\n\n return;\n }\n\n const prevAllFolderListIds = prevGlobal.allFolderListIds;\n const prevArchivedFolderListIds = prevGlobal.archivedFolderListIds;\n\n updateFolders(global, isAllFolderChanged, isArchivedFolderChanged, areFoldersChanged);\n\n affectedFolderIds = affectedFolderIds.concat(updateChats(\n global,\n areFoldersChanged || isAllFolderChanged || isArchivedFolderChanged,\n areNotifySettingsChanged,\n areNotifyExceptionsChanged,\n prevAllFolderListIds,\n prevArchivedFolderListIds,\n ));\n\n updateResults(unique(affectedFolderIds));\n\n if (DEBUG) {\n const duration = performance.now() - DEBUG_startedAt!;\n if (duration > DEBUG_DURATION_LIMIT) {\n // eslint-disable-next-line no-console\n console.warn(`Slow \\`updateFolderManager\\`: ${Math.round(duration)} ms`);\n }\n }\n}\n\nfunction isMainFolderChanged(folderId: number, newListIds?: string[], newPinnedIds?: string[]) {\n const currentListIds = folderId === ALL_FOLDER_ID\n ? prevGlobal.allFolderListIds\n : prevGlobal.archivedFolderListIds;\n const currentPinnedIds = folderId === ALL_FOLDER_ID\n ? prevGlobal.allFolderPinnedIds\n : prevGlobal.archivedFolderPinnedIds;\n\n return currentListIds !== newListIds || currentPinnedIds !== newPinnedIds;\n}\n\nfunction updateFullyLoaded(\n global: GlobalState,\n isArchivedFullyLoadedChanged = false,\n) {\n let affectedFolderIds = [];\n\n if (isArchivedFullyLoadedChanged) {\n affectedFolderIds.push(ARCHIVED_FOLDER_ID);\n }\n\n const isAllFolderFullyLoaded = global.chats.isFullyLoaded.active;\n const isArchivedFolderFullyLoaded = global.chats.isFullyLoaded.archived;\n\n if (isAllFolderFullyLoaded && isArchivedFolderFullyLoaded) {\n const emptyFolderIds = Object.keys(prepared.folderSummariesById)\n .filter((folderId) => !results.orderedIdsByFolderId[folderId])\n .map(Number);\n\n affectedFolderIds = affectedFolderIds.concat(emptyFolderIds);\n }\n\n prevGlobal.isAllFolderFullyLoaded = isAllFolderFullyLoaded;\n prevGlobal.isArchivedFolderFullyLoaded = isArchivedFolderFullyLoaded;\n\n return affectedFolderIds;\n}\n\nfunction updateFolders(\n global: GlobalState, isAllFolderChanged: boolean, isArchivedFolderChanged: boolean, areFoldersChanged: boolean,\n) {\n const changedFolders = [];\n\n if (isAllFolderChanged) {\n const newListIds = global.chats.listIds.active!;\n const newPinnedIds = global.chats.orderedPinnedIds.active;\n\n prepared.folderSummariesById[ALL_FOLDER_ID] = buildFolderSummaryFromMainList(\n ALL_FOLDER_ID, newListIds, newPinnedIds,\n );\n\n prevGlobal.allFolderListIds = newListIds;\n prevGlobal.allFolderPinnedIds = newPinnedIds;\n\n changedFolders.push(ALL_FOLDER_ID);\n }\n\n if (isArchivedFolderChanged) {\n const newListIds = global.chats.listIds.archived!;\n const newPinnedIds = global.chats.orderedPinnedIds.archived;\n\n prepared.folderSummariesById[ARCHIVED_FOLDER_ID] = buildFolderSummaryFromMainList(\n ARCHIVED_FOLDER_ID, newListIds, newPinnedIds,\n );\n\n prevGlobal.archivedFolderListIds = newListIds;\n prevGlobal.archivedFolderPinnedIds = newPinnedIds;\n\n changedFolders.push(ARCHIVED_FOLDER_ID);\n }\n\n if (areFoldersChanged) {\n const newFoldersById = global.chatFolders.byId;\n\n Object.values(newFoldersById).forEach((folder) => {\n if (folder === prevGlobal.foldersById[folder.id]) {\n return;\n }\n\n prepared.folderSummariesById[folder.id] = buildFolderSummary(folder);\n\n changedFolders.push(folder.id);\n });\n\n prevGlobal.foldersById = newFoldersById;\n }\n\n return changedFolders;\n}\n\nfunction buildFolderSummaryFromMainList(\n folderId: number, listIds: string[], orderedPinnedIds?: string[],\n): FolderSummary {\n return {\n id: folderId,\n listIds: new Set(listIds),\n orderedPinnedIds,\n pinnedChatIds: new Set(orderedPinnedIds),\n };\n}\n\nfunction buildFolderSummary(folder: ApiChatFolder): FolderSummary {\n return {\n ...folder,\n orderedPinnedIds: folder.pinnedChatIds,\n excludedChatIds: folder.excludedChatIds ? new Set(folder.excludedChatIds) : undefined,\n includedChatIds: folder.excludedChatIds ? new Set(folder.includedChatIds) : undefined,\n pinnedChatIds: folder.excludedChatIds ? new Set(folder.pinnedChatIds) : undefined,\n };\n}\n\nfunction updateChats(\n global: GlobalState,\n areFoldersChanged: boolean,\n areNotifySettingsChanged: boolean,\n areNotifyExceptionsChanged: boolean,\n prevAllFolderListIds?: string[],\n prevArchivedFolderListIds?: string[],\n) {\n const newChatsById = global.chats.byId;\n const newUsersById = global.users.byId;\n const newNotifySettings = selectNotifySettings(global);\n const newNotifyExceptions = selectNotifyExceptions(global);\n const folderSummaries = Object.values(prepared.folderSummariesById);\n const affectedFolderIds = new Set<number>();\n\n const newAllFolderListIds = global.chats.listIds.active;\n const newArchivedFolderListIds = global.chats.listIds.archived;\n let allIds = [...newAllFolderListIds || [], ...newArchivedFolderListIds || []];\n if (newAllFolderListIds !== prevAllFolderListIds || newArchivedFolderListIds !== prevArchivedFolderListIds) {\n allIds = unique(allIds.concat(prevAllFolderListIds || [], prevArchivedFolderListIds || []));\n }\n\n allIds.forEach((chatId) => {\n const chat = newChatsById[chatId];\n\n if (\n !areFoldersChanged\n && !areNotifySettingsChanged\n && !areNotifyExceptionsChanged\n && chat === prevGlobal.chatsById[chatId]\n && newUsersById[chatId] === prevGlobal.usersById[chatId]\n ) {\n return;\n }\n\n let newFolderIds: number[];\n if (chat) {\n const currentSummary = prepared.chatSummariesById.get(chatId);\n const newSummary = buildChatSummary(chat, newNotifySettings, newNotifyExceptions, newUsersById[chatId]);\n if (!areFoldersChanged && currentSummary && arePropsShallowEqual(newSummary, currentSummary)) {\n return;\n }\n\n prepared.chatSummariesById.set(chatId, newSummary);\n\n newFolderIds = buildChatFolderIds(newSummary, folderSummaries);\n newFolderIds.forEach((folderId) => {\n affectedFolderIds.add(folderId);\n });\n } else {\n prepared.chatSummariesById.delete(chatId);\n newFolderIds = [];\n }\n\n const currentFolderIds = prepared.folderIdsByChatId[chatId] || [];\n if (areSortedArraysEqual(newFolderIds, currentFolderIds)) {\n return;\n }\n\n const deletedFolderIds = updateListsForChat(chatId, currentFolderIds, newFolderIds);\n deletedFolderIds.forEach((folderId) => {\n affectedFolderIds.add(folderId);\n });\n });\n\n prevGlobal.chatsById = newChatsById;\n prevGlobal.usersById = newUsersById;\n prevGlobal.notifySettings = newNotifySettings;\n prevGlobal.notifyExceptions = newNotifyExceptions;\n\n return Array.from(affectedFolderIds);\n}\n\nfunction buildChatSummary(\n chat: ApiChat,\n notifySettings: NotifySettings,\n notifyExceptions?: Record<number, NotifyException>,\n user?: ApiUser,\n): ChatSummary {\n const {\n id, type, lastMessage, isRestricted, isNotJoined, migratedTo, folderId,\n unreadCount, unreadMentionsCount, hasUnreadMark,\n joinDate, draftDate,\n } = chat;\n\n const userInfo = type === 'chatTypePrivate' && user;\n const shouldHideServiceChat = chat.id === SERVICE_NOTIFICATIONS_USER_ID && (\n !chat.lastMessage || chat.lastMessage.content.action?.type === 'historyClear'\n );\n\n return {\n id,\n type,\n isListed: Boolean(!isRestricted && !isNotJoined && !migratedTo && !shouldHideServiceChat),\n isArchived: folderId === ARCHIVED_FOLDER_ID,\n isMuted: selectIsChatMuted(chat, notifySettings, notifyExceptions),\n isUnread: Boolean(unreadCount || unreadMentionsCount || hasUnreadMark),\n unreadCount,\n unreadMentionsCount,\n order: Math.max(joinDate || 0, draftDate || 0, lastMessage?.date || 0),\n isUserBot: userInfo ? userInfo.type === 'userTypeBot' : undefined,\n isUserContact: userInfo ? userInfo.isContact : undefined,\n };\n}\n\nfunction buildChatFolderIds(chatSummary: ChatSummary, folderSummaries: FolderSummary[]) {\n return folderSummaries.reduce<number[]>((acc, folderSummary) => {\n if (isChatInFolder(chatSummary, folderSummary)) {\n acc.push(folderSummary.id);\n }\n\n return acc;\n }, []).sort();\n}\n\nfunction isChatInFolder(\n chatSummary: ChatSummary,\n folderSummary: FolderSummary,\n) {\n if (!chatSummary.isListed) {\n return false;\n }\n\n const { id: chatId, type } = chatSummary;\n\n if (folderSummary.listIds) {\n if (\n (chatSummary.isArchived && folderSummary.id === ALL_FOLDER_ID)\n || (!chatSummary.isArchived && folderSummary.id === ARCHIVED_FOLDER_ID)\n ) {\n return false;\n }\n\n return folderSummary.listIds.has(chatId);\n }\n\n if (folderSummary.excludedChatIds?.has(chatId)) {\n return false;\n }\n\n if (folderSummary.includedChatIds?.has(chatId)) {\n return true;\n }\n\n if (folderSummary.pinnedChatIds?.has(chatId)) {\n return true;\n }\n\n if (folderSummary.excludeArchived && chatSummary.isArchived) {\n return false;\n }\n\n if (folderSummary.excludeRead && !chatSummary.isUnread) {\n return false;\n }\n\n if (folderSummary.excludeMuted && chatSummary.isMuted && !chatSummary.unreadMentionsCount) {\n return false;\n }\n\n if (type === 'chatTypePrivate') {\n if (chatSummary.isUserBot) {\n if (folderSummary.bots) {\n return true;\n }\n } else {\n if (folderSummary.contacts && chatSummary.isUserContact) {\n return true;\n }\n\n if (folderSummary.nonContacts && !chatSummary.isUserContact) {\n return true;\n }\n }\n } else if (type === 'chatTypeChannel') {\n return Boolean(folderSummary.channels);\n } else if (type === 'chatTypeBasicGroup' || type === 'chatTypeSuperGroup') {\n return Boolean(folderSummary.groups);\n }\n\n return false;\n}\n\nfunction updateListsForChat(chatId: string, currentFolderIds: number[], newFolderIds: number[]) {\n const currentFolderIdsSet = new Set(currentFolderIds);\n const newFolderIdsSet = new Set(newFolderIds);\n const deletedFolderIds: number[] = [];\n\n unique([...currentFolderIds, ...newFolderIds]).forEach((folderId) => {\n let currentFolderOrderedIds = results.orderedIdsByFolderId[folderId];\n\n if (currentFolderIdsSet.has(folderId) && !newFolderIdsSet.has(folderId)) {\n prepared.chatIdsByFolderId[folderId]!.delete(chatId);\n\n deletedFolderIds.push(folderId);\n\n if (currentFolderOrderedIds) {\n currentFolderOrderedIds = currentFolderOrderedIds.filter((id) => id !== chatId);\n prepared.isOrderedListJustPatched[folderId] = true;\n }\n } else if (!currentFolderIdsSet.has(folderId) && newFolderIdsSet.has(folderId)) {\n if (!prepared.chatIdsByFolderId[folderId]) {\n prepared.chatIdsByFolderId[folderId] = new Set();\n }\n\n prepared.chatIdsByFolderId[folderId]!.add(chatId);\n\n if (currentFolderOrderedIds) {\n currentFolderOrderedIds.push(chatId);\n prepared.isOrderedListJustPatched[folderId] = true;\n }\n }\n\n results.orderedIdsByFolderId[folderId] = currentFolderOrderedIds;\n });\n\n prepared.folderIdsByChatId[chatId] = newFolderIds;\n\n return deletedFolderIds;\n}\n\nfunction updateResults(affectedFolderIds: number[]) {\n let wasUnreadCountersChanged = false;\n let wasChatsCountChanged = false;\n\n Array.from(affectedFolderIds).forEach((folderId) => {\n const { pinnedCount: newPinnedCount, orderedIds: newOrderedIds } = buildFolderOrderedIds(folderId);\n // When signed out\n if (!newOrderedIds) {\n return;\n }\n\n const currentOrderedIds = results.orderedIdsByFolderId[folderId];\n const currentPinnedCount = results.pinnedCountByFolderId[folderId];\n const areOrderedIdsChanged = (\n !currentOrderedIds\n || currentPinnedCount === undefined || currentPinnedCount !== newPinnedCount\n || prepared.isOrderedListJustPatched[folderId]\n || !areSortedArraysEqual(newOrderedIds, currentOrderedIds)\n );\n if (areOrderedIdsChanged) {\n prepared.isOrderedListJustPatched[folderId] = false;\n results.orderedIdsByFolderId[folderId] = newOrderedIds;\n results.pinnedCountByFolderId[folderId] = newPinnedCount;\n callbacks.orderedIdsByFolderId[folderId]?.runCallbacks(newOrderedIds);\n }\n\n const currentChatsCount = results.chatsCountByFolderId[folderId];\n const newChatsCount = newOrderedIds.length;\n if (!wasChatsCountChanged) {\n wasChatsCountChanged = currentChatsCount !== newChatsCount;\n }\n results.chatsCountByFolderId[folderId] = newChatsCount;\n\n const currentUnreadCounters = results.unreadCountersByFolderId[folderId];\n const newUnreadCounters = buildFolderUnreadCounters(folderId);\n if (!wasUnreadCountersChanged) {\n wasUnreadCountersChanged = (\n !currentUnreadCounters || !arePropsShallowEqual(newUnreadCounters, currentUnreadCounters)\n );\n }\n results.unreadCountersByFolderId[folderId] = newUnreadCounters;\n });\n\n if (wasChatsCountChanged) {\n // We need to update the entire object as it will be returned from a hook\n const newValue = { ...results.chatsCountByFolderId };\n results.chatsCountByFolderId = newValue;\n callbacks.chatsCountByFolderId.runCallbacks(newValue);\n }\n\n if (wasUnreadCountersChanged) {\n // We need to update the entire object as it will be returned from a hook\n const newValue = { ...results.unreadCountersByFolderId };\n results.unreadCountersByFolderId = newValue;\n callbacks.unreadCountersByFolderId.runCallbacks(newValue);\n }\n}\n\nfunction buildFolderOrderedIds(folderId: number) {\n const folderSummary = prepared.folderSummariesById[folderId];\n if (!folderSummary) {\n return {};\n }\n\n const { orderedPinnedIds, pinnedChatIds } = folderSummary;\n const {\n chatSummariesById,\n chatIdsByFolderId: { [folderId]: chatIds },\n } = prepared;\n const {\n orderedIdsByFolderId: { [folderId]: prevOrderedIds },\n } = results;\n\n const sortedPinnedIds = chatIds ? orderedPinnedIds?.filter((id) => chatIds.has(id)) : orderedPinnedIds;\n const allListIds = prevOrderedIds || (chatIds && Array.from(chatIds)) || [];\n const notPinnedIds = pinnedChatIds ? allListIds.filter((id) => !pinnedChatIds.has(id)) : allListIds;\n const sortedNotPinnedIds = notPinnedIds.sort((chatId1: string, chatId2: string) => {\n return chatSummariesById.get(chatId2)!.order - chatSummariesById.get(chatId1)!.order;\n });\n\n return {\n pinnedCount: sortedPinnedIds?.length || 0,\n orderedIds: [\n ...(sortedPinnedIds || []),\n ...sortedNotPinnedIds,\n ],\n };\n}\n\nfunction buildFolderUnreadCounters(folderId: number) {\n const {\n chatSummariesById,\n } = prepared;\n const {\n orderedIdsByFolderId: { [folderId]: orderedIds },\n } = results;\n\n return orderedIds!.reduce((newUnreadCounters, chatId) => {\n const chatSummary = chatSummariesById.get(chatId);\n if (!chatSummary) {\n return newUnreadCounters;\n }\n\n if (chatSummary.isUnread) {\n newUnreadCounters.chatsCount++;\n\n if (chatSummary.unreadMentionsCount) {\n newUnreadCounters.notificationsCount += chatSummary.unreadMentionsCount;\n }\n\n if (!chatSummary.isMuted) {\n if (chatSummary.unreadCount) {\n newUnreadCounters.notificationsCount += chatSummary.unreadCount;\n } else if (!chatSummary.unreadMentionsCount) {\n newUnreadCounters.notificationsCount += 1; // Manually marked unread\n }\n }\n }\n\n return newUnreadCounters;\n }, {\n chatsCount: 0,\n notificationsCount: 0,\n });\n}\n\nfunction buildInitials() {\n return {\n prevGlobal: {\n foldersById: {},\n chatsById: {},\n usersById: {},\n notifySettings: {} as NotifySettings,\n notifyExceptions: {},\n },\n\n prepared: {\n folderSummariesById: {},\n chatSummariesById: new Map(),\n folderIdsByChatId: {},\n chatIdsByFolderId: {},\n isOrderedListJustPatched: {},\n },\n\n results: {\n orderedIdsByFolderId: {},\n pinnedCountByFolderId: {},\n chatsCountByFolderId: {},\n unreadCountersByFolderId: {},\n },\n\n callbacks: {\n orderedIdsByFolderId: {},\n chatsCountByFolderId: createCallbackManager(),\n unreadCountersByFolderId: createCallbackManager(),\n },\n };\n}\n\nfunction reset() {\n const newInitials = buildInitials();\n\n prevGlobal = newInitials.prevGlobal;\n prepared = newInitials.prepared;\n results = newInitials.results;\n callbacks = newInitials.callbacks;\n}\n","// Used before applying CSS transition\nexport default function forceReflow(element: HTMLElement) {\n // eslint-disable-next-line @typescript-eslint/no-unused-expressions\n element.offsetWidth;\n}\n","import type { 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(totalPrice / 10 ** getCurrencyExp(currency));\n}\n\nfunction getCurrencyExp(currency: string) {\n if (currency === 'CLF') {\n return 4;\n }\n if (['BHD', 'IQD', 'JOD', 'KWD', 'LYD', 'OMR', 'TND'].includes(currency)) {\n return 3;\n }\n if ([\n 'BIF', 'BYR', 'CLP', 'CVE', 'DJF', 'GNF', 'ISK', 'JPY', 'KMF', 'KRW', 'MGA', 'PYG', 'RWF', 'UGX', 'UYI',\n 'VND', 'VUV', 'XAF', 'XOF', 'XPF',\n ].includes(currency)) {\n return 0;\n }\n if (currency === 'MRO') {\n return 1;\n }\n return 2;\n}\n","const generateIdFor = (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\nexport default generateIdFor;\n","import type { ApiError, ApiFieldError } from '../api/types';\n\nimport { DEBUG } from '../config';\n\nconst READABLE_ERROR_MESSAGES: Record<string, string> = {\n CHAT_RESTRICTED: 'You can\\'t send messages in this chat, you were restricted',\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 PINNED_DIALOGS_TOO_MUCH: 'Sorry, you can only pin 5 chats to the top',\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 // eslint-disable-next-line max-len\n SERVICE_WORKER_DISABLED: 'Service Worker is disabled. Streaming media may not be supported. Try reloading 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 cant 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 BOT_PRECHECKOUT_TIMEOUT: 'The request for payment has expired',\n};\n\nif (DEBUG) {\n READABLE_ERROR_MESSAGES.CHAT_WRITE_FORBIDDEN = 'You can\\'t write in this chat';\n READABLE_ERROR_MESSAGES.CHAT_ADMIN_REQUIRED = 'You must be an admin in this chat to do this';\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\nconst FINAL_PAYMENT_ERRORS = new Set([\n 'BOT_PRECHECKOUT_FAILED',\n 'PAYMENT_FAILED',\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\nexport function shouldClosePaymentModal(error: ApiError): boolean {\n return FINAL_PAYMENT_ERRORS.has(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 // https://stackoverflow.com/questions/49384120/resizeobserver-loop-limit-exceeded\n if (e instanceof ErrorEvent && e.message === 'ResizeObserver loop limit exceeded') {\n return;\n }\n\n e.preventDefault();\n\n handleError(e instanceof ErrorEvent ? (e.error || e.message) : 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","import { getActions } from '../global';\n\nlet promptInstall: () => Promise<void>;\n\nexport function setupBeforeInstallPrompt() {\n window.addEventListener('beforeinstallprompt', (e: any) => {\n promptInstall = async () => {\n e.prompt();\n const userChoice = await e.userChoice;\n const isInstalled = userChoice.outcome === 'accepted';\n\n if (!isInstalled) return;\n getActions().setInstallPrompt({ canInstall: false });\n };\n getActions().setInstallPrompt({ canInstall: true });\n });\n}\n\nexport function getPromptInstall() {\n return promptInstall;\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 unique<T extends any>(array: T[]): T[] {\n return Array.from(new Set(array));\n}\n\nexport function uniqueByField<T extends any>(array: T[], field: keyof T): T[] {\n return [...new Map(array.map((item) => [item[field], item])).values()];\n}\n\nexport function compact<T extends any>(array: T[]) {\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<T extends any>(array: T[], chunkSize: number) {\n const result: T[][] = [];\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 '../global';\n\nimport type { ApiLangPack, ApiLangString } from '../api/types';\nimport type { 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 langName?: string;\n timeFormat?: TimeFormat;\n}\n\nconst SUBSTITUTION_REGEX = /%\\d?\\$?[sdf@]/g;\nconst PLURAL_OPTIONS = ['value', 'zeroValue', 'oneValue', 'twoValue', 'fewValue', 'manyValue', 'otherValue'] as const;\n// Some rules edited from https://github.com/eemeli/make-plural/blob/master/packages/plurals/cardinals.js\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 be: (n: number) => {\n const s = String(n).split('.'); const t0 = Number(s[0]) === n; const n10 = t0 && Number(s[0].slice(-1)); const n100 = t0 && Number(s[0].slice(-2));\n return n10 === 1 && n100 !== 11 ? 2\n : (n10 >= 2 && n10 <= 4) && (n100 < 12 || n100 > 14) ? 4\n : (t0 && n10 === 0) || (n10 >= 5 && n10 <= 9) || (n100 >= 11 && n100 <= 14) ? 5\n : 6;\n },\n ca: (n: number) => (n !== 1 ? 6 : 2),\n cs: (n: number) => {\n const s = String(n).split('.'); const i = Number(s[0]); const v0 = !s[1];\n return n === 1 && v0 ? 2 : (i >= 2 && i <= 4) && v0 ? 4 : !v0 ? 5 : 6;\n },\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 fi: (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 hr: (n: number) => {\n const s = String(n).split('.'); const i = s[0]; const f = s[1] || ''; const v0 = !s[1]; const i10 = Number(i.slice(-1));\n const i100 = Number(i.slice(-2)); const f10 = Number(f.slice(-1)); const f100 = Number(f.slice(-2));\n return (v0 && i10 === 1 && i100 !== 11) || (f10 === 1 && f100 !== 11) ? 2\n : (v0 && (i10 >= 2 && i10 <= 4) && (i100 < 12 || i100 > 14)) || ((f10 >= 2 && f10 <= 4) && (f100 < 12 || f100 > 14)) ? 4\n : 6;\n },\n hu: (n: number) => (n > 1 ? 6 : 2),\n ko: () => 0,\n ms: () => 0,\n nb: (n: number) => (n > 1 ? 6 : 2),\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 sk: (n: number) => {\n const s = String(n).split('.'); const i = Number(s[0]); const v0 = !s[1];\n return n === 1 && v0 ? 2 : (i >= 2 && i <= 4) && v0 ? 4 : !v0 ? 5 : 6;\n },\n sr: (n: number) => {\n const s = String(n).split('.'); const i = s[0]; const f = s[1] || ''; const v0 = !s[1]; const i10 = Number(i.slice(-1));\n const i100 = Number(i.slice(-2)); const f10 = Number(f.slice(-1)); const f100 = Number(f.slice(-2));\n return (v0 && i10 === 1 && i100 !== 11) || (f10 === 1 && f100 !== 11) ? 2\n : (v0 && (i10 >= 2 && i10 <= 4) && (i100 < 12 || i100 > 14)) || ((f10 >= 2 && f10 <= 4) && (f100 < 12 || f100 > 14)) ? 4\n : 6;\n },\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.langName = langInfo?.nativeName;\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 preferredPluralOption = typeof value === 'number' ? getPluralOption(value) : 'value';\n const template = langString ? (\n langString[preferredPluralOption] || langString.otherValue || langString.value\n ) : undefined;\n if (!template || !template.trim()) {\n const parts = key.split('.');\n\n return parts[parts.length - 1];\n }\n\n if (value !== undefined) {\n const formattedValue = format === 'i' ? formatInteger(value) : value;\n const result = processTemplate(template, formattedValue);\n const cacheValue = Array.isArray(value) ? JSON.stringify(value) : value;\n cache.set(`${key}_${cacheValue}_${format}`, result);\n return result;\n }\n\n return template;\n}\n","export const clamp = (num: number, min: number, max: number) => (Math.min(max, Math.max(min, num)));\nexport const isBetween = (num: number, min: number, max: number) => (num >= min && num <= max);\nexport const round = (num: number, decimals: number = 0) => Math.round(num * 10 ** decimals) / 10 ** decimals;\nexport const lerp = (start: number, end: number, interpolationRatio: number) => {\n return (1 - interpolationRatio) * start + interpolationRatio * end;\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 type {\n ApiOnProgress,\n ApiParsedMedia,\n ApiPreparedMedia,\n} from '../api/types';\nimport {\n ApiMediaFormat,\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 {\n IS_OPUS_SUPPORTED, IS_PROGRESSIVE_SUPPORTED, isWebpSupported,\n} from './environment';\nimport { oggToWav } from './oggToWav';\nimport { webpToPng } from './webpToPng';\n\nconst asCacheApiType = {\n [ApiMediaFormat.BlobUrl]: cacheApi.Type.Blob,\n [ApiMediaFormat.Text]: cacheApi.Type.Text,\n [ApiMediaFormat.DownloadUrl]: undefined,\n [ApiMediaFormat.Progressive]: undefined,\n [ApiMediaFormat.Stream]: undefined,\n};\n\nconst PROGRESSIVE_URL_PREFIX = './progressive/';\nconst URL_DOWNLOAD_PREFIX = './download/';\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 (mediaFormat === ApiMediaFormat.DownloadUrl) {\n return (\n IS_PROGRESSIVE_SUPPORTED\n ? getDownloadUrl(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\nfunction getDownloadUrl(url: string) {\n return Promise.resolve(`${URL_DOWNLOAD_PREFIX}${url}`);\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 { 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(/* webpackChunkName: \"BundleAuth\" */ '../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(/* webpackChunkName: \"BundleMain\" */ '../bundles/main');\n break;\n case Bundles.Extra:\n LOAD_PROMISES[Bundles.Extra] = import(/* webpackChunkName: \"BundleExtra\" */ '../bundles/extra');\n break;\n case Bundles.Calls:\n LOAD_PROMISES[Bundles.Calls] = import(/* webpackChunkName: \"BundleCalls\" */ '../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 type {\n ApiChat, ApiMessage, ApiPhoneCall, ApiUser, ApiUserReaction,\n} from '../api/types';\nimport { ApiMediaFormat } from '../api/types';\nimport { renderActionMessageText } from '../components/common/helpers/renderActionMessageText';\nimport { APP_NAME, DEBUG, IS_TEST } from '../config';\nimport { getActions, getGlobal, setGlobal } from '../global';\nimport {\n getChatAvatarHash,\n getChatTitle,\n getMessageAction,\n getMessageRecentReaction,\n getMessageSenderName,\n getMessageSummaryText,\n getPrivateChatUserId, getUserFullName,\n isActionMessage,\n isChatChannel,\n selectIsChatMuted,\n selectShouldShowMessagePreview,\n} from '../global/helpers';\nimport { addNotifyExceptions, replaceSettings } from '../global/reducers';\nimport {\n selectChatMessage,\n selectCurrentMessageList,\n selectNotifyExceptions,\n selectNotifySettings,\n selectUser,\n} from '../global/selectors';\nimport { IS_SERVICE_WORKER_SUPPORTED, IS_TOUCH_ENV } from './environment';\nimport { getTranslation } from './langProvider';\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 = getActions();\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 getActions()\n .setDeviceToken(deviceToken);\n } catch (error: any) {\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 // On touch devices show notifications when chat is not active\n if (IS_TOUCH_ENV) {\n const {\n chatId,\n type,\n } = selectCurrentMessageList(global) || {};\n return !(chatId === chat.id && type === 'thread');\n }\n // On desktop show notifications when window is not focused\n return !document.hasFocus();\n}\n\nfunction getNotificationContent(chat: ApiChat, message: ApiMessage, reaction?: ApiUserReaction) {\n const global = getGlobal();\n const {\n replyToMessageId,\n } = message;\n let {\n senderId,\n } = message;\n if (reaction) senderId = reaction.userId;\n\n const { isScreenLocked } = global.passcode;\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 (\n !isScreenLocked\n && selectShouldShowMessagePreview(chat, selectNotifySettings(global), selectNotifyExceptions(global))\n ) {\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 { asPlainText: true },\n ) as string;\n } else {\n const senderName = getMessageSenderName(getTranslation, chat.id, messageSender);\n const summary = getMessageSummaryText(getTranslation, message, false, 60, false);\n\n body = senderName ? `${senderName}: ${summary}` : summary;\n }\n } else {\n body = 'New message';\n }\n\n return {\n title: isScreenLocked ? APP_NAME : getChatTitle(getTranslation, chat, privateChatUser),\n body,\n };\n}\n\nasync function getAvatar(chat: ApiChat | ApiUser) {\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 notifyAboutCall({\n call, user,\n}: {\n call: ApiPhoneCall; user: ApiUser;\n}) {\n const { hasWebNotifications } = await loadNotificationSettings();\n if (document.hasFocus() || !hasWebNotifications) return;\n const areNotificationsSupported = checkIfNotificationsSupported();\n if (!areNotificationsSupported) return;\n\n const icon = await getAvatar(user);\n\n const options: NotificationOptions = {\n body: getUserFullName(user),\n icon,\n badge: icon,\n tag: `call_${call.id}`,\n };\n\n if ('vibrate' in navigator) {\n options.vibrate = [200, 100, 200];\n }\n\n const notification = new Notification(getTranslation('VoipIncoming'), options);\n\n notification.onclick = () => {\n notification.close();\n if (window.focus) {\n window.focus();\n }\n };\n}\n\nexport async function notifyAboutMessage({\n chat,\n message,\n isReaction = false,\n}: { chat: ApiChat; message: Partial<ApiMessage>; isReaction?: boolean }) {\n const { hasWebNotifications } = await loadNotificationSettings();\n if (!checkIfShouldNotify(chat)) return;\n const areNotificationsSupported = checkIfNotificationsSupported();\n if (!hasWebNotifications || !areNotificationsSupported) {\n // Do not play notification sound for reactions if web notifications are disabled\n if (isReaction) return;\n // Only play sound if web notifications are disabled\n playNotifySoundDebounced(String(message.id) || chat.id);\n return;\n }\n if (!areNotificationsSupported) return;\n\n if (!message.id) return;\n\n const activeReaction = getMessageRecentReaction(message);\n // Do not notify about reactions on messages that are not outgoing\n if (isReaction && !activeReaction) return;\n\n const icon = await getAvatar(chat);\n\n const {\n title,\n body,\n } = getNotificationContent(chat, message as ApiMessage, activeReaction);\n\n if (checkIfPushSupported()) {\n if (navigator.serviceWorker?.controller) {\n // notify service worker about new message notification\n navigator.serviceWorker.controller.postMessage({\n type: 'showMessageNotification',\n payload: {\n title,\n body,\n icon,\n chatId: chat.id,\n messageId: message.id,\n shouldReplaceHistory: true,\n reaction: activeReaction?.reaction,\n },\n });\n }\n } else {\n const dispatch = getActions();\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 shouldReplaceHistory: true,\n });\n if (window.focus) {\n window.focus();\n }\n };\n\n // Play sound when notification is displayed\n notification.onshow = () => {\n // TODO Remove when reaction badges are implemented\n if (isReaction) return;\n playNotifySoundDebounced(String(message.id) || chat.id);\n };\n }\n}\n\nexport function closeMessageNotifications(payload: { chatId: string; lastReadInboxMessageId?: number }) {\n if (IS_TEST || !navigator.serviceWorker?.controller) return;\n navigator.serviceWorker.controller.postMessage({\n type: 'closeMessageNotifications',\n payload,\n });\n}\n\n// Notify service worker that client is fully loaded\nexport function notifyClientReady() {\n if (!navigator.serviceWorker?.controller) return;\n navigator.serviceWorker.controller.postMessage({\n type: 'clientReady',\n });\n}\n","import * as cacheApi from './cacheApi';\nimport { PASSCODE_CACHE_NAME } from '../config';\n\nconst IV_LENGTH = 12;\nconst SALT = 'harder better faster stronger';\n\nlet currentPasscodeHash: ArrayBuffer | undefined;\n\nexport async function setupPasscode(passcode: string) {\n currentPasscodeHash = await sha256(passcode);\n}\n\nexport async function encryptSession(sessionJson?: string, globalJson?: string) {\n if (!currentPasscodeHash) {\n throw new Error('[api/passcode] Missing current passcode');\n }\n\n await Promise.all([\n (async () => {\n if (!sessionJson) return;\n\n const sessionEncrypted = await aesEncrypt(sessionJson, currentPasscodeHash);\n await store('sessionEncrypted', sessionEncrypted);\n })(),\n (async () => {\n if (!globalJson) return;\n\n const globalEncrypted = await aesEncrypt(globalJson, currentPasscodeHash);\n await store('globalEncrypted', globalEncrypted);\n })(),\n ]);\n}\n\nexport async function decryptSession(passcode: string) {\n const passcodeHash = await sha256(passcode);\n\n const [sessionEncrypted, globalEncrypted] = await Promise.all([\n load('sessionEncrypted'),\n load('globalEncrypted'),\n ]);\n\n if (!sessionEncrypted || !globalEncrypted) {\n throw new Error('[api/passcode] Missing required stored fields');\n }\n\n const [sessionJson, globalJson] = await Promise.all([\n aesDecrypt(sessionEncrypted, passcodeHash),\n aesDecrypt(globalEncrypted, passcodeHash),\n ]);\n\n currentPasscodeHash = passcodeHash;\n\n return { sessionJson, globalJson };\n}\n\nexport function forgetPasscode() {\n currentPasscodeHash = undefined;\n}\n\nexport function clearEncryptedSession() {\n forgetPasscode();\n return cacheApi.clear(PASSCODE_CACHE_NAME);\n}\n\nfunction sha256(plaintext: string) {\n return crypto.subtle.digest('SHA-256', new TextEncoder().encode(`${plaintext}${SALT}`));\n}\n\nasync function store(key: string, value: ArrayBuffer) {\n await cacheApi.save(PASSCODE_CACHE_NAME, key, value);\n}\n\nfunction load(key: string) {\n return cacheApi.fetch(PASSCODE_CACHE_NAME, key, cacheApi.Type.ArrayBuffer);\n}\n\nasync function aesEncrypt(plaintext: string, pwHash: ArrayBuffer) {\n const iv = crypto.getRandomValues(new Uint8Array(IV_LENGTH));\n const alg = { name: 'AES-GCM', iv };\n const key = await crypto.subtle.importKey('raw', pwHash, alg, false, ['encrypt']);\n const ptUint8 = new TextEncoder().encode(plaintext);\n const ctBuffer = await crypto.subtle.encrypt(alg, key, ptUint8);\n const ct = new Uint8Array(ctBuffer);\n const result = new Uint8Array(IV_LENGTH + ct.length);\n result.set(iv, 0);\n result.set(ct, IV_LENGTH);\n return result.buffer;\n}\n\nasync function aesDecrypt(data: ArrayBuffer, pwHash: ArrayBuffer) {\n const dataArray = new Uint8Array(data);\n const iv = dataArray.slice(0, IV_LENGTH);\n const alg = { name: 'AES-GCM', iv };\n const key = await crypto.subtle.importKey('raw', pwHash, alg, false, ['decrypt']);\n const ct = dataArray.slice(IV_LENGTH);\n const plainBuffer = await crypto.subtle.decrypt(alg, key, ct);\n\n return new TextDecoder().decode(plainBuffer);\n}\n","import type { ApiCountryCode } from '../api/types';\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 }[] = possibleCountries\n .map((country) => (country.prefixes || ['']).map((prefix) => {\n return {\n code: `${country.countryCode}${prefix}`,\n country,\n };\n }))\n .flat();\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 if (!input) {\n return '';\n }\n\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 if (!phoneNumber) {\n return '';\n }\n\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 type { MessageListType } from '../global/types';\nimport { MAIN_THREAD_ID } from '../api/types';\nimport { LOCATION_HASH } from '../hooks/useHistoryBack';\n\nexport const createMessageHash = (chatId: string, type: string, threadId: number): string => (\n chatId.toString()\n + (type !== 'thread' ? `_${type}`\n : (threadId !== -1 ? `_${threadId}` : ''))\n);\n\nexport function parseLocationHash() {\n if (!LOCATION_HASH) return undefined;\n\n const [chatId, typeOrThreadId] = LOCATION_HASH.replace(/^#/, '').split('_');\n if (!chatId?.match(/^-?\\d+$/)) return undefined;\n\n const isType = ['thread', 'pinned', 'scheduled'].includes(typeOrThreadId);\n\n return {\n chatId,\n type: Boolean(typeOrThreadId) && isType ? (typeOrThreadId as MessageListType) : 'thread',\n threadId: Boolean(typeOrThreadId) && !isType ? Number(typeOrThreadId) : MAIN_THREAD_ID,\n };\n}\n","import { DEBUG } from '../config';\n\nconst safePlay = (mediaEl: HTMLMediaElement) => {\n mediaEl.play().catch((err) => {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.warn(err, mediaEl);\n }\n });\n};\n\nexport default safePlay;\n","type Scheduler =\n typeof requestAnimationFrame\n | typeof onTickEnd;\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 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\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 = /[^\\p{L}\\p{M}]+/ui;\n} catch (e) {\n // Support for older versions of firefox\n RE_NOT_LETTER = /[^\\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 * Delete multiple keys at once.\n *\n * @param keys List of keys to delete.\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction delMany(keys, customStore = defaultGetStore()) {\n return customStore('readwrite', (store) => {\n keys.forEach((key) => 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(store, callback) {\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 * 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 return customStore('readonly', (store) => {\n // Fast path for modern browsers\n if (store.getAllKeys) {\n return promisifyRequest(store.getAllKeys());\n }\n const items = [];\n return eachCursor(store, (cursor) => items.push(cursor.key)).then(() => items);\n });\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 return customStore('readonly', (store) => {\n // Fast path for modern browsers\n if (store.getAll) {\n return promisifyRequest(store.getAll());\n }\n const items = [];\n return eachCursor(store, (cursor) => items.push(cursor.value)).then(() => items);\n });\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 return customStore('readonly', (store) => {\n // Fast path for modern browsers\n // (although, hopefully we'll get a simpler path some day)\n if (store.getAll && store.getAllKeys) {\n return Promise.all([\n promisifyRequest(store.getAllKeys()),\n promisifyRequest(store.getAll()),\n ]).then(([keys, values]) => keys.map((key, i) => [key, values[i]]));\n }\n const items = [];\n return customStore('readonly', (store) => eachCursor(store, (cursor) => items.push([cursor.key, cursor.value])).then(() => items));\n });\n}\n\nexport { clear, createStore, del, delMany, entries, get, getMany, keys, promisifyRequest, set, setMany, update, values };\n","/**\n * Work around Safari 14 IndexedDB open bug.\n *\n * Safari has a horrible bug where IDB requests can hang while the browser is starting up. https://bugs.webkit.org/show_bug.cgi?id=226547\n * The only solution is to keep nudging it until it's awake.\n */\nfunction idbReady() {\n var 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 var intervalId;\n return new Promise(function (resolve) {\n var tryIdb = function () { return indexedDB.databases().finally(resolve); };\n intervalId = setInterval(tryIdb, 100);\n tryIdb();\n }).finally(function () { return clearInterval(intervalId); });\n}\n\nexport default idbReady;\n","import * as idb from 'idb-keyval';\n\nimport type { ApiSessionData } from '../api/types';\n\nimport {\n DEBUG, GLOBAL_STATE_CACHE_KEY, LEGACY_SESSION_KEY, SESSION_USER_KEY,\n} 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 if (checkSessionLocked()) {\n return true;\n }\n\n const userAuthJson = localStorage.getItem(SESSION_USER_KEY);\n if (!userAuthJson) {\n return false;\n }\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 ...DC_IDS.map((dcId) => `dc${dcId}_server_salt`),\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 if (!userAuth) {\n return undefined;\n }\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\nfunction checkSessionLocked() {\n const stateFromCache = JSON.parse(localStorage.getItem(GLOBAL_STATE_CACHE_KEY) || '{}');\n\n return Boolean(stateFromCache?.passcode?.isScreenLocked);\n}\n","import type { ISettings } from '../types';\n\nimport { animateSingle } from './animation';\nimport { fastRaf } from './schedulers';\n\nimport themeColors from '../styles/themes.json';\nimport { lerp } from './math';\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 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\nconst switchTheme = (theme: ISettings['theme'], withAnimation: boolean) => {\n const themeClassName = `theme-${theme}`;\n if (document.documentElement.classList.contains(themeClassName)) {\n return;\n }\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(themeClassName);\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\nexport default switchTheme;\n","import type { LangFn } from '../hooks/useLang';\nimport EMOJI_REGEX from '../lib/twemojiRegex';\nimport { fixNonStandardEmoji } from './emoji';\nimport withCache from './withCache';\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 const getFirstLetters = withCache((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\nconst FILE_SIZE_UNITS = ['B', 'KB', 'MB', 'GB'];\nexport function formatFileSize(lang: LangFn, bytes: number, decimals = 1): string {\n if (bytes === 0) {\n return lang('FileSize.B', 0);\n }\n\n const k = 1024;\n const i = Math.floor(Math.log(bytes) / Math.log(k));\n const value = (bytes / (k ** i)).toFixed(Math.max(decimals, 0));\n\n return lang(`FileSize.${FILE_SIZE_UNITS[i]}`, value);\n}\n","export default function trimText<T extends string | undefined>(text: T, length?: number) {\n if (!text || !length || text.length <= length) {\n return text;\n }\n\n return `${text.substring(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, IS_MOCKED_CLIENT } from '../config';\nimport { getGlobal } from '../global';\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 if (IS_MOCKED_CLIENT) return undefined;\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 = () => Boolean(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 currentWindowSize = updateSizes();\nlet isRefreshDisabled = false;\n\nfunction disableRefresh() {\n isRefreshDisabled = true;\n}\n\nfunction enableRefresh() {\n isRefreshDisabled = false;\n}\n\nconst handleResize = throttle(() => {\n currentWindowSize = 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 currentWindowSize.width <= MOBILE_SCREEN_MAX_WIDTH || (\n currentWindowSize.width <= MOBILE_SCREEN_LANDSCAPE_MAX_WIDTH\n && currentWindowSize.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\nconst windowSize = {\n get: () => currentWindowSize,\n getIsKeyboardVisible: () => initialHeight > currentWindowSize.height,\n disableRefresh,\n enableRefresh,\n};\n\nexport default windowSize;\n","const cache = new WeakMap<AnyFunction, Map<string, any>>();\n\nexport default function withCache<T extends AnyFunction>(fn: T) {\n return (...args: Parameters<T>): ReturnType<T> => {\n let fnCache = cache.get(fn);\n const cacheKey = args.map(String).join('_');\n\n if (fnCache) {\n const cached = fnCache.get(cacheKey);\n if (cached) {\n return cached;\n }\n } else {\n fnCache = new Map();\n cache.set(fn, fnCache);\n }\n\n const newValue = fn(...args);\n\n fnCache.set(cacheKey, newValue);\n\n return newValue;\n };\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 + \".\" + {\"67\":\"b87adfdac989dff54cd1\",\"143\":\"e2c1115f073082dddbdf\",\"154\":\"8c2ff697b6d4cafdb776\",\"191\":\"1fa0f260d53e7abfe9ed\",\"209\":\"ca4daa9ff624b3bf5614\",\"212\":\"e663b8258cc54ba69359\",\"244\":\"ae966e72f128eda340fc\",\"256\":\"ff0f01bea01003a78a3c\",\"370\":\"5addeb3fc94386c23602\",\"483\":\"35b0f80df29ece6559a6\",\"625\":\"c4bfccd5c44b3331f5a7\",\"713\":\"894ffda65a82196537e1\",\"730\":\"2e172af489ed6ff0e496\",\"831\":\"f5c222cee9c1b1b68852\",\"905\":\"60ca606f19ffdd6d94a4\",\"958\":\"c56f02be3f4f5db2aedf\",\"1098\":\"4a6d3970af492938a672\",\"1142\":\"59a69270adc0978a6156\",\"1161\":\"9bcab8bec6aedc27da89\",\"1276\":\"07f8a81b011d56580ad6\",\"1360\":\"1a681d99506a88d29942\",\"1402\":\"35efd1623401c0a6ada2\",\"1418\":\"a8ffdf6d23ac65ebfa95\",\"1437\":\"53e04fe5063aee60d350\",\"1514\":\"64267b1f36585be79543\",\"1516\":\"cbee85824600e7b98e69\",\"1627\":\"c1c005ef2bed8d1b9561\",\"1641\":\"d99075923e2b8c9e5f72\",\"1699\":\"258d1e759822ec152b75\",\"1752\":\"272d78459ec80c5b3dba\",\"1879\":\"60ac065c7d88c4f46b54\",\"1915\":\"c5b3f01035517153521f\",\"1917\":\"2928ac2003a7061dc059\",\"1933\":\"b2033cfa79d272a8fe62\",\"1954\":\"d569fdd7ba86d9776a5c\",\"1967\":\"3cec93c3a4dcd79e0488\",\"2001\":\"8c68420c13854bbc24fe\",\"2002\":\"8481843cd3d445486865\",\"2054\":\"9c1890f62ccae40eeec2\",\"2098\":\"890557cbbc0c46a9f08f\",\"2137\":\"3af5405dff8273180346\",\"2138\":\"fbfb10a62455b7b043b7\",\"2243\":\"f82c54d3a849d4a487b4\",\"2251\":\"2bf10b1f578543d75e54\",\"2305\":\"c31559f1364c234c62a5\",\"2342\":\"f8d4331788cc89a2b694\",\"2369\":\"d952921438994721f7d0\",\"2390\":\"d7ecc2f228aef9b009e4\",\"2537\":\"94c17bfafc8acf1a9cd2\",\"2690\":\"4d73e3084ae3a2a6f64c\",\"2741\":\"9f3aba6b2cd0b453f9a5\",\"2767\":\"2121cd909c7aa572c7fd\",\"2853\":\"c4ae910d407f42b72912\",\"2892\":\"b8b8cd5c2b1df51e3492\",\"2993\":\"7edbe42f18b94ec35761\",\"3041\":\"3651667772714402881a\",\"3075\":\"9c2f4f4a3c19eb56b751\",\"3076\":\"a7f6caf93b4b88180a6f\",\"3098\":\"448b2ceaf9f37e849d7e\",\"3108\":\"8f30bf9e3324a376f4ee\",\"3124\":\"076a04e3a1b8d27db111\",\"3147\":\"5a6cc01866d92675c748\",\"3163\":\"6761cefaf572d1748946\",\"3268\":\"7cace4f58c3fac9c74da\",\"3280\":\"c61f120392215be6557a\",\"3288\":\"4a69264995d9f806de13\",\"3309\":\"620314c64d80c35257fc\",\"3311\":\"2ff5c61aa4212045c410\",\"3404\":\"70f366c6fa25f799e549\",\"3408\":\"25202d3ff038f4194bd9\",\"3411\":\"8f5d1095651d61b8f424\",\"3420\":\"3a5367f73895e3c3c1f4\",\"3472\":\"615d222fdc0dcfa591d8\",\"3488\":\"54332bf5929df0077432\",\"3505\":\"58e185c3b757b41576a2\",\"3539\":\"498df8847f9f9d5a0937\",\"3585\":\"3853a59a7d0336a03fde\",\"3588\":\"d6cc0e28e0d962d3157c\",\"3656\":\"279c48ec3d47a9000fa9\",\"3698\":\"3541c155e1b629af7d33\",\"3779\":\"0b77df2f0fdb505d6e71\",\"3800\":\"96da4150cdeeba708556\",\"3848\":\"ee699a3ab25cc6ca726d\",\"3863\":\"d5fde682a12d7aa54672\",\"3866\":\"df9f4de3c91bbda53861\",\"3881\":\"8521d06f92c7b8b273ce\",\"3894\":\"9ec589a8d0b8850ef326\",\"3936\":\"a3325e628347fac10d84\",\"3966\":\"097d0a2dd03e55cf7c46\",\"4037\":\"af37477886b6cfd1194e\",\"4039\":\"bcd470032085a33ee54b\",\"4231\":\"d59a6f0c70fb98d4bcf0\",\"4276\":\"9240959928e16f250f8f\",\"4303\":\"58ff7d91e35a9b3c2756\",\"4314\":\"0d8ed2badacc96e873cb\",\"4334\":\"e493d976600a04c160e4\",\"4408\":\"0fb28033cf23ddbc23a6\",\"4484\":\"ba496a0faf977e32f6ef\",\"4536\":\"acd06cb972eebae2e5e4\",\"4566\":\"5eb1a1b10803fa99c22d\",\"4569\":\"385b6cf4a46b7115c2db\",\"4646\":\"7ebe551cdd0f4b9c9e92\",\"4685\":\"88d39506fe34588ed78d\",\"4686\":\"125b32545c1a0a0d5d3e\",\"4710\":\"0a0b5e901cf0b5d6fd93\",\"4713\":\"5a4b08652c0d22593258\",\"4723\":\"38c6e4a29e0fdfa7afa8\",\"4747\":\"a51da29105f71545b275\",\"4753\":\"17105da93bd7006f8573\",\"4835\":\"0964f1a24a6398e35c12\",\"4838\":\"71c5c5739a3ed2bad3ee\",\"4850\":\"bc9242dc125cb10484bc\",\"4933\":\"c0f777add150aed6dd31\",\"4973\":\"9e1f1935e024e1bf929d\",\"4986\":\"962334f1a027906974fd\",\"5040\":\"99ef443d75bf87559776\",\"5060\":\"7cd173e6b1393947bb3b\",\"5066\":\"d9d0cb326f6f7d743f3a\",\"5099\":\"655521533cb48ebec54c\",\"5119\":\"090f02fee771b8f5e65c\",\"5204\":\"55dc1f02973adc8b29ab\",\"5239\":\"73400cf76a319169f599\",\"5246\":\"32626d81771d640604dd\",\"5281\":\"0b7b900d2540db49ae8f\",\"5297\":\"01b37c1c033b4b7c5732\",\"5309\":\"ba1a5dde297758458683\",\"5344\":\"5c9eaedbce0a63ae3e63\",\"5368\":\"892f890338957f00fc23\",\"5386\":\"9f0180dc5c168ff288bf\",\"5434\":\"249f262bbc62d09db4f0\",\"5474\":\"aedf972792d2c11b7940\",\"5588\":\"56e673e74137435b5023\",\"5603\":\"0302646e1ffabe87d525\",\"5699\":\"78a750acf4e0fff43bde\",\"5745\":\"53fc0ce876a7dce21370\",\"5769\":\"b3dc0ee7170367f52dfe\",\"5855\":\"c34458d02e95d2ec3d71\",\"5930\":\"9dcde09591068799ffc3\",\"5993\":\"7a57e87ff9a577929387\",\"5999\":\"3b1c15d4285915dddc03\",\"6052\":\"ca3c1bee89e20d16318d\",\"6146\":\"e892062054e79d879e6b\",\"6220\":\"4626eab605f1f3f5fae7\",\"6284\":\"412fe22eb5e792b8236b\",\"6297\":\"a40c32123d663a5d397e\",\"6346\":\"3a08cef57225b5dd0723\",\"6401\":\"65204bd5a1f1d34e1fdc\",\"6483\":\"49cb2949d98e5010ceff\",\"6548\":\"6abe878180ff54087f58\",\"6642\":\"765cb88c978f7f6366d8\",\"6688\":\"a5a6ef9c1044e440d8aa\",\"6770\":\"260c086c5e5b2e226e40\",\"6798\":\"a48f1b663374c1fcdf24\",\"6839\":\"7574ee59f6159101b320\",\"6889\":\"94df7712273c4f61ab30\",\"6892\":\"1bf37b40183987140fc9\",\"6931\":\"5d8b023307c7a880a8f1\",\"6941\":\"7a0e1012e31f72681952\",\"6969\":\"d2b2e882f924d7d5e877\",\"6972\":\"45d9b899b7178fdb92c1\",\"7049\":\"6f2636c871a83f167b6e\",\"7052\":\"d8a4a1431f93b64b9a87\",\"7119\":\"03b2ee63b97712464a63\",\"7125\":\"57c858da5d4ff67e8141\",\"7316\":\"2a3dfa1eba460895cf64\",\"7388\":\"7bec01a290d868ba2d42\",\"7501\":\"9f45796679951ac21293\",\"7551\":\"6e574d5a75cf073215df\",\"7556\":\"701477404ee235a07786\",\"7794\":\"5d3eabab5ee771b3e859\",\"7799\":\"690560cf65f3d985dde5\",\"7897\":\"01558917b3d0fc1d388f\",\"7941\":\"7394fb0b394c9ee95fb1\",\"7963\":\"8b010994867f46020df9\",\"8063\":\"627d5ae10e2e502e9e38\",\"8090\":\"743a785a5fe6a9841aeb\",\"8138\":\"9b29a768a035996247bd\",\"8208\":\"9a2d0eeec5f8bb07cdd3\",\"8294\":\"12b38bd567e102c27c8e\",\"8369\":\"c6ae120b122d07384b7d\",\"8401\":\"a8ba266b7a79ef7dfe1d\",\"8422\":\"cfa7884f5b7ee933b6c3\",\"8435\":\"5f667e46d196564970b9\",\"8505\":\"f588195fa145445de93b\",\"8530\":\"a4d7f28c015d01eaf776\",\"8663\":\"3215036b0069a8dcc16e\",\"8688\":\"6cda6506154e2e3e5b90\",\"8709\":\"51c7b7103b230d767ea7\",\"8812\":\"a39ba81372544f20ba3f\",\"8815\":\"fd39d74554c793313d5b\",\"8822\":\"3e199b60162d8b8314aa\",\"8878\":\"a7b117d54d54258e5f26\",\"8913\":\"1773658335e9a4527e40\",\"9071\":\"c587e7d4b0df5f41a587\",\"9125\":\"221d966328061801dce3\",\"9223\":\"b65193470f36938b0d9b\",\"9227\":\"c34f2b1661736507d402\",\"9285\":\"3aedc94598376aee9274\",\"9328\":\"545adb935b7615fd8d16\",\"9338\":\"cf9b08f5551ab6096a70\",\"9375\":\"40298b58e46ff66877d6\",\"9379\":\"5f47d04a09f26df77d30\",\"9400\":\"9f2f9a821c3a64e5473d\",\"9486\":\"66f6169ec02590019bbf\",\"9535\":\"35b32969dfafdbc17a45\",\"9536\":\"52b3efcf5de741667a33\",\"9565\":\"05a813d6f1c60da0196b\",\"9606\":\"f9fa653821fc0f019fad\",\"9623\":\"a319f64448a91c662f4d\",\"9635\":\"01582125f331f7f89adb\",\"9641\":\"8b340949ffd52cb38c60\",\"9657\":\"376f100fba6d94cfca1b\",\"9682\":\"730455c56a4729444e9d\",\"9783\":\"6fb3455cb9b01926cb10\",\"9822\":\"ec3817f08021427f5550\",\"9954\":\"836adcc6b64f2d9ed43a\"}[chunkId] + \".js\";\n};","// This function allow to reference async chunks\n__webpack_require__.miniCssF = (chunkId) => {\n\t// return url for filenames based on template\n\treturn \"\" + ({\"3041\":\"BundleAuth\",\"3779\":\"BundleExtra\",\"5769\":\"BundleMain\",\"9954\":\"BundleCalls\"}[chunkId] || chunkId) + \".\" + {\"3041\":\"3651667772714402881a\",\"3472\":\"615d222fdc0dcfa591d8\",\"3779\":\"0b77df2f0fdb505d6e71\",\"5769\":\"b3dc0ee7170367f52dfe\",\"8688\":\"6cda6506154e2e3e5b90\",\"8878\":\"a7b117d54d54258e5f26\",\"9954\":\"836adcc6b64f2d9ed43a\"}[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[chunkId] = 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, IS_TEST } from '../config';\nimport { getActions } from '../global';\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 = getActions();\n const payload = action.payload;\n switch (action.type) {\n case 'focusMessage':\n if (dispatch.focusMessage) {\n dispatch.focusMessage(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 if (!navigator.serviceWorker.controller) {\n const registrations = await navigator.serviceWorker.getRegistrations();\n if (registrations.length) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('[SW] Hard reload detected, re-enabling Service Worker');\n }\n await Promise.all(registrations.map((r) => r.unregister()));\n }\n }\n\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 && !IS_TEST) {\n getActions().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 { addActionHandler } from './index';\n\nimport { INITIAL_STATE } from './initialState';\nimport { IS_MOCKED_CLIENT } from '../config';\nimport { initCache, loadCache } from './cache';\nimport { cloneDeep } from '../util/iteratees';\nimport { updatePasscodeSettings } from './reducers';\nimport { clearStoredSession } from '../util/sessions';\n\ninitCache();\n\naddActionHandler('init', () => {\n const initial = cloneDeep(INITIAL_STATE);\n let global = loadCache(initial) || initial;\n if (IS_MOCKED_CLIENT) global.authState = 'authorizationStateReady';\n\n const { hasPasscode, isScreenLocked } = global.passcode;\n if (hasPasscode && !isScreenLocked) {\n global = updatePasscodeSettings(global, {\n isScreenLocked: true,\n });\n\n clearStoredSession();\n }\n\n return global;\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 * as langProvider from '../util/langProvider';\nimport { useState } from '../lib/teact/teact';\n\nconst useLangString = (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\nexport default useLangString;\n","import type { 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 type { FC } from '../../lib/teact/teact';\nimport React, {\n useState, memo, useCallback, useRef,\n} from '../../lib/teact/teact';\nimport { withGlobal } from '../../global';\n\nimport type { 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 }> = useCallback(({ 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 }, [filter, handleInput, handleInputKeyDown, id, isLoading, lang, value]);\n\n return (\n <DropdownMenu\n className=\"CountryCodeInput\"\n trigger={CodeInput}\n >\n {filteredList\n .map((country: ApiCountryCode) => (\n <MenuItem\n key={`${country.iso2}-${country.countryCode}`}\n className={value && country.iso2 === value.iso2 ? 'selected' : ''}\n // eslint-disable-next-line react/jsx-no-bind\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 type { ChangeEvent } from 'react';\n\nimport monkeyPath from '../../assets/monkey.svg';\n\nimport type { FC } from '../../lib/teact/teact';\nimport React, {\n memo, useCallback, useEffect, useLayoutEffect, useRef, useState,\n} from '../../lib/teact/teact';\nimport { getActions, withGlobal } from '../../global';\n\nimport type { GlobalState } from '../../global/types';\nimport type { LangCode } from '../../types';\nimport type { 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 } = getActions();\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 <h1>Telegram</h1>\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 type { FC } from '../../lib/teact/teact';\nimport React, { 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 type { FC } from '../../lib/teact/teact';\nimport React, { 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 type { FC } from '../../lib/teact/teact';\nimport React, { memo } from '../../lib/teact/teact';\nimport { Bundles } from '../../util/moduleLoader';\n\nimport useModuleLoader from '../../hooks/useModuleLoader';\nimport Loading from '../ui/Loading';\n\nconst AuthRegisterAsync: FC = () => {\n const AuthRegister = useModuleLoader(Bundles.Auth, 'AuthRegister');\n\n return AuthRegister ? <AuthRegister /> : <Loading />;\n};\n\nexport default memo(AuthRegisterAsync);\n","import React, {\n useEffect, useRef, memo, useCallback,\n} from '../../lib/teact/teact';\nimport { getActions, withGlobal } from '../../global';\n\nimport type { FC } from '../../lib/teact/teact';\nimport type { GlobalState } from '../../global/types';\nimport type { LangCode } from '../../types';\n\nimport { DEFAULT_LANG_CODE } from '../../config';\nimport { LOCAL_TGS_URLS } from '../common/helpers/animatedAssets';\nimport { setLanguage } from '../../util/langProvider';\nimport buildClassName from '../../util/buildClassName';\nimport renderText from '../common/helpers/renderText';\nimport { getSuggestedLanguage } from './helpers/getSuggestedLanguage';\n\nimport useLangString from '../../hooks/useLangString';\nimport useFlag from '../../hooks/useFlag';\nimport useLang from '../../hooks/useLang';\nimport useMediaTransition from '../../hooks/useMediaTransition';\nimport useAsync from '../../hooks/useAsync';\n\nimport Loading from '../ui/Loading';\nimport Button from '../ui/Button';\nimport AnimatedIcon from '../common/AnimatedIcon';\n\nimport blankUrl from '../../assets/blank.png';\n\ntype StateProps =\n Pick<GlobalState, 'connectionState' | 'authState' | 'authQrCode'>\n & { language?: LangCode };\n\nconst DATA_PREFIX = 'tg://login?token=';\nconst QR_SIZE = 280;\nconst QR_PLANE_SIZE = 54;\n\nlet qrCodeStylingPromise: Promise<typeof import('qr-code-styling')>;\n\nfunction ensureQrCodeStyling() {\n if (!qrCodeStylingPromise) {\n qrCodeStylingPromise = import('qr-code-styling');\n }\n return qrCodeStylingPromise;\n}\n\nconst AuthCode: FC<StateProps> = ({\n connectionState,\n authState,\n authQrCode,\n language,\n}) => {\n const {\n returnToAuthPhoneNumber,\n setSettingOption,\n } = getActions();\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 const [isQrMounted, markQrMounted, unmarkQrMounted] = useFlag();\n\n const { result: qrCode } = useAsync(async () => {\n const QrCodeStyling = (await ensureQrCodeStyling()).default;\n return new QrCodeStyling({\n width: QR_SIZE,\n height: QR_SIZE,\n image: blankUrl,\n margin: 10,\n type: 'svg',\n dotsOptions: {\n type: 'rounded',\n },\n cornersSquareOptions: {\n type: 'extra-rounded',\n },\n imageOptions: {\n imageSize: 0.4,\n margin: 8,\n },\n qrOptions: {\n errorCorrectionLevel: 'M',\n },\n });\n }, []);\n\n const transitionClassNames = useMediaTransition(isQrMounted);\n\n useEffect(() => {\n if (!authQrCode || !qrCode) {\n return () => {\n unmarkQrMounted();\n };\n }\n\n if (connectionState !== 'connectionStateReady') {\n return undefined;\n }\n\n const container = qrCodeRef.current!;\n const data = `${DATA_PREFIX}${authQrCode.token}`;\n\n qrCode.update({\n data,\n });\n\n if (!isQrMounted) {\n qrCode.append(container);\n markQrMounted();\n }\n return undefined;\n }, [connectionState, authQrCode, isQrMounted, markQrMounted, unmarkQrMounted, qrCode]);\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 <div className=\"qr-outer\">\n <div\n className={buildClassName('qr-inner', transitionClassNames)}\n key=\"qr-inner\"\n >\n <div\n key=\"qr-container\"\n className=\"qr-container\"\n ref={qrCodeRef}\n style={`width: ${QR_SIZE}px; height: ${QR_SIZE}px`}\n />\n <AnimatedIcon\n tgsUrl={LOCAL_TGS_URLS.QrPlane}\n size={QR_PLANE_SIZE}\n className=\"qr-plane\"\n nonInteractive\n noLoop={false}\n />\n </div>\n {!isQrMounted && <div className=\"qr-loading\"><Loading /></div>}\n </div>\n <h1>{lang('Login.QR.Title')}</h1>\n <ol>\n <li><span>{lang('Login.QR.Help1')}</span></li>\n <li><span>{renderText(lang('Login.QR2.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 type { FC } from '../../lib/teact/teact';\nimport React, { useEffect, memo } from '../../lib/teact/teact';\nimport { getActions, withGlobal } from '../../global';\n\nimport type { GlobalState } from '../../global/types';\n\nimport '../../global/actions/initial';\nimport { pick } from '../../util/iteratees';\nimport { PLATFORM_ENV } from '../../util/environment';\nimport windowSize from '../../util/windowSize';\nimport useHistoryBack from '../../hooks/useHistoryBack';\nimport useCurrentOrPrev from '../../hooks/useCurrentOrPrev';\n\nimport Transition from '../ui/Transition';\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 OwnProps = {\n isActive: boolean;\n};\n\ntype StateProps = Pick<GlobalState, 'authState'>;\n\nconst Auth: FC<OwnProps & StateProps> = ({\n isActive, authState,\n}) => {\n const {\n reset, initApi, returnToAuthPhoneNumber, goToAuthQrCode,\n } = getActions();\n\n useEffect(() => {\n if (isActive) {\n reset();\n initApi();\n }\n }, [isActive, 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 isActive: (!isMobile && authState === 'authorizationStateWaitPhoneNumber')\n || (isMobile && authState === 'authorizationStateWaitQrCode'),\n onBack: handleChangeAuthorizationMethod,\n });\n\n // Prevent refresh when rotating device\n useEffect(() => {\n windowSize.disableRefresh();\n\n return () => {\n windowSize.enableRefresh();\n };\n }, []);\n\n // For animation purposes\n const renderingAuthState = useCurrentOrPrev(\n authState !== 'authorizationStateReady' ? authState : undefined,\n true,\n );\n\n function getScreen() {\n switch (renderingAuthState) {\n case 'authorizationStateWaitCode':\n return <AuthCode />;\n case 'authorizationStateWaitPassword':\n return <AuthPassword />;\n case 'authorizationStateWaitRegistration':\n return <AuthRegister />;\n case 'authorizationStateWaitPhoneNumber':\n return <AuthPhoneNumber />;\n case 'authorizationStateWaitQrCode':\n return <AuthQrCode />;\n default:\n return isMobile ? <AuthPhoneNumber /> : <AuthQrCode />;\n }\n }\n\n function getActiveKey() {\n switch (renderingAuthState) {\n case 'authorizationStateWaitCode':\n return 0;\n case 'authorizationStateWaitPassword':\n return 1;\n case 'authorizationStateWaitRegistration':\n return 2;\n case 'authorizationStateWaitPhoneNumber':\n return 3;\n case 'authorizationStateWaitQrCode':\n return 4;\n default:\n return isMobile ? 3 : 4;\n }\n }\n\n return (\n <Transition activeKey={getActiveKey()} name=\"fade\" className=\"Auth\">\n {getScreen()}\n </Transition>\n );\n};\n\nexport default memo(withGlobal<OwnProps>(\n (global): StateProps => pick(global, ['authState']),\n)(Auth));\n","import type { FC } from '../../lib/teact/teact';\nimport React, { 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 type { FC } from '../../lib/teact/teact';\nimport React, { memo } from '../../lib/teact/teact';\nimport { Bundles } from '../../util/moduleLoader';\n\nimport type { OwnProps } from './LockScreen';\n\nimport useModuleLoader from '../../hooks/useModuleLoader';\n\nconst LockScreenAsync: FC<OwnProps> = (props) => {\n const { isLocked } = props;\n const LockScreen = useModuleLoader(Bundles.Main, 'LockScreen', !isLocked);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return LockScreen ? <LockScreen {...props} /> : undefined;\n};\n\nexport default memo(LockScreenAsync);\n","import type { FC } from '../../lib/teact/teact';\nimport React, { useCallback } 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 = useCallback(() => {\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}>\n Reload app\n </Button>\n </div>\n </div>\n </div>\n );\n};\n\nexport default AppInactive;\n","// extracted by mini-css-extract-plugin\nexport default {\"bg\":\"KD2TsjdEc_LBLsR_ReWT\",\"mask\":\"dDIGwEoHlINzvf7LzGwy\",\"main\":\"jxcLmQWl6IklxyLBcFsv\",\"left\":\"s_eiw3FJDNGVyMHHEr_w\",\"middle\":\"v5WSHYkqrlK9GvmSI1zN\",\"right\":\"BlQSOI0qSg9HDzgQGwdw\",\"blank\":\"J5QD898gcautir6pK9xA\"};","import React, { useEffect } from '../../lib/teact/teact';\nimport { getActions, getGlobal, withGlobal } from '../../global';\n\nimport { ApiMediaFormat } from '../../api/types';\nimport type { GlobalState } from '../../global/types';\nimport type { ThemeKey } from '../../types';\nimport type { FC } from '../../lib/teact/teact';\n\nimport { getChatAvatarHash } from '../../global/helpers/chats'; // Direct import for better module splitting\nimport { selectIsRightColumnShown, selectTheme, selectIsCurrentUserPremium } from '../../global/selectors';\nimport { DARK_THEME_BG_COLOR, LIGHT_THEME_BG_COLOR } from '../../config';\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 styles from './UiLoader.module.scss';\n\nimport telegramLogoPath from '../../assets/telegram-logo.svg';\nimport reactionThumbsPath from '../../assets/reaction-thumbs.png';\nimport premiumReactionThumbsPath from '../../assets/reaction-thumbs-premium.png';\nimport lockPreviewPath from '../../assets/lock.png';\nimport monkeyPath from '../../assets/monkey.svg';\n\nexport type UiLoaderPage =\n 'main'\n | 'lock'\n | 'inactive'\n | 'authCode'\n | 'authPassword'\n | 'authPhoneNumber'\n | 'authQrCode';\n\ntype OwnProps = {\n page?: UiLoaderPage;\n children: React.ReactNode;\n};\n\ntype StateProps = Pick<GlobalState, 'uiReadyState' | 'shouldSkipHistoryAnimations'> & {\n isRightColumnShown?: boolean;\n leftColumnWidth?: number;\n theme: ThemeKey;\n isCurrentUserPremium?: boolean;\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: (isCurrentUserPremium: boolean) => Promise.all([\n loadModule(Bundles.Main, 'Main')\n .then(preloadFonts),\n preloadAvatars(),\n preloadImage(isCurrentUserPremium ? premiumReactionThumbsPath : reactionThumbsPath),\n ]),\n authPhoneNumber: () => Promise.all([\n preloadFonts(),\n preloadImage(telegramLogoPath),\n ]),\n authCode: () => preloadImage(monkeyPath),\n authPassword: () => preloadImage(monkeyPath),\n authQrCode: preloadFonts,\n lock: () => Promise.all([\n preloadFonts(),\n preloadImage(lockPreviewPath),\n ]),\n inactive: () => {\n },\n};\n\nconst UiLoader: FC<OwnProps & StateProps> = ({\n page,\n children,\n isRightColumnShown,\n shouldSkipHistoryAnimations,\n leftColumnWidth,\n theme,\n isCurrentUserPremium,\n}) => {\n const { setIsUiReady } = getActions();\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!](isCurrentUserPremium!);\n } catch (err) {\n // Do nothing\n }\n };\n\n Promise.race([\n pause(MAX_PRELOAD_DELAY),\n page ? safePreload() : Promise.resolve(),\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\n id=\"UiLoader\"\n className={styles.bg}\n style={`--theme-background-color: ${theme === 'dark' ? DARK_THEME_BG_COLOR : LIGHT_THEME_BG_COLOR}`}\n >\n {children}\n {shouldRenderMask && !shouldSkipHistoryAnimations && Boolean(page) && (\n <div className={buildClassName(styles.mask, transitionClassNames)}>\n {page === 'main' ? (\n <div className={styles.main}>\n <div\n className={styles.left}\n style={leftColumnWidth ? `width: ${leftColumnWidth}px` : undefined}\n />\n <div className={buildClassName(styles.middle, styles.bg)} />\n {isRightColumnShown && <div className={styles.right} />}\n </div>\n ) : (page === 'inactive' || page === 'lock') ? (\n <div className={buildClassName(styles.blank, styles.bg)} />\n ) : (\n <div className={styles.blank} />\n )}\n </div>\n )}\n </div>\n );\n};\n\nexport default withGlobal<OwnProps>(\n (global): StateProps => {\n const theme = selectTheme(global);\n\n return {\n shouldSkipHistoryAnimations: global.shouldSkipHistoryAnimations,\n uiReadyState: global.uiReadyState,\n isRightColumnShown: selectIsRightColumnShown(global),\n leftColumnWidth: global.leftColumnWidth,\n theme,\n isCurrentUserPremium: selectIsCurrentUserPremium(global),\n };\n },\n)(UiLoader);\n","import type { FC } from './lib/teact/teact';\nimport React, { useEffect } from './lib/teact/teact';\nimport { getActions, withGlobal } from './global';\n\nimport type { GlobalState } from './global/types';\nimport type { UiLoaderPage } from './components/common/UiLoader';\n\nimport { INACTIVE_MARKER, PAGE_TITLE } from './config';\nimport { PLATFORM_ENV } from './util/environment';\nimport { updateSizes } from './util/windowSize';\nimport { addActiveTabChangeListener } from './util/activeTabMonitor';\nimport { hasStoredSession } from './util/sessions';\nimport buildClassName from './util/buildClassName';\nimport useFlag from './hooks/useFlag';\nimport usePrevious from './hooks/usePrevious';\n\nimport Auth from './components/auth/Auth';\nimport Main from './components/main/Main.async';\nimport LockScreen from './components/main/LockScreen.async';\nimport AppInactive from './components/main/AppInactive';\nimport Transition from './components/ui/Transition';\nimport UiLoader from './components/common/UiLoader';\n// import Test from './components/test/TestNoRedundancy';\n\ntype StateProps = {\n authState: GlobalState['authState'];\n isScreenLocked?: boolean;\n hasPasscode?: boolean;\n};\n\nenum AppScreens {\n auth,\n lock,\n main,\n inactive,\n}\n\nconst App: FC<StateProps> = ({\n authState,\n isScreenLocked,\n hasPasscode,\n}) => {\n const { disconnect } = getActions();\n\n const [isInactive, markInactive] = useFlag(false);\n const isMobile = PLATFORM_ENV === 'iOS' || PLATFORM_ENV === 'Android';\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 // Prevent drop on elements that do not accept it\n useEffect(() => {\n const body = document.body;\n const handleDrag = (e: DragEvent) => {\n e.preventDefault();\n if (!e.dataTransfer) return;\n if (!(e.target as HTMLElement).dataset.dropzone) {\n e.dataTransfer.dropEffect = 'none';\n } else {\n e.dataTransfer.dropEffect = 'copy';\n }\n };\n const handleDrop = (e: DragEvent) => {\n e.preventDefault();\n };\n body.addEventListener('drop', handleDrop);\n body.addEventListener('dragover', handleDrag);\n body.addEventListener('dragenter', handleDrag);\n\n return () => {\n body.removeEventListener('drop', handleDrop);\n body.removeEventListener('dragover', handleDrag);\n body.removeEventListener('dragenter', handleDrag);\n };\n }, []);\n\n // return <Test />;\n\n let activeKey: number;\n let page: UiLoaderPage | undefined;\n\n if (isInactive) {\n activeKey = AppScreens.inactive;\n } else if (isScreenLocked) {\n page = 'lock';\n activeKey = AppScreens.lock;\n } else if (authState) {\n switch (authState) {\n case 'authorizationStateWaitPhoneNumber':\n page = 'authPhoneNumber';\n activeKey = AppScreens.auth;\n break;\n case 'authorizationStateWaitCode':\n page = 'authCode';\n activeKey = AppScreens.auth;\n break;\n case 'authorizationStateWaitPassword':\n page = 'authPassword';\n activeKey = AppScreens.auth;\n break;\n case 'authorizationStateWaitRegistration':\n activeKey = AppScreens.auth;\n break;\n case 'authorizationStateWaitQrCode':\n page = 'authQrCode';\n activeKey = AppScreens.auth;\n break;\n case 'authorizationStateClosed':\n case 'authorizationStateClosing':\n case 'authorizationStateLoggingOut':\n case 'authorizationStateReady':\n page = 'main';\n activeKey = AppScreens.main;\n break;\n }\n } else if (hasStoredSession(true)) {\n page = 'main';\n activeKey = AppScreens.main;\n } else if (hasPasscode) {\n activeKey = AppScreens.lock;\n } else {\n page = isMobile ? 'authPhoneNumber' : 'authQrCode';\n activeKey = AppScreens.auth;\n }\n\n const prevActiveKey = usePrevious(activeKey);\n\n // eslint-disable-next-line consistent-return\n function renderContent(isActive: boolean) {\n switch (activeKey) {\n case AppScreens.auth:\n return <Auth isActive={isActive} />;\n case AppScreens.main:\n return <Main />;\n case AppScreens.lock:\n return <LockScreen isLocked={isScreenLocked} />;\n case AppScreens.inactive:\n return <AppInactive />;\n }\n }\n\n return (\n <UiLoader key=\"Loader\" page={page}>\n <Transition\n name=\"fade\"\n activeKey={activeKey}\n shouldCleanup\n className={buildClassName(\n 'full-height',\n (activeKey === AppScreens.auth || prevActiveKey === AppScreens.auth) && 'is-auth',\n )}\n >\n {renderContent}\n </Transition>\n </UiLoader>\n );\n};\n\nexport default withGlobal(\n (global): StateProps => {\n return {\n authState: global.authState,\n isScreenLocked: global.passcode?.isScreenLocked,\n hasPasscode: global.passcode?.hasPasscode,\n };\n },\n)(App);\n","import './util/handleError';\nimport './util/setupServiceWorker';\n\nimport React from './lib/teact/teact';\nimport TeactDOM from './lib/teact/teact-dom';\n\nimport { getActions, getGlobal } from './global';\nimport updateWebmanifest from './util/updateWebmanifest';\nimport { setupBeforeInstallPrompt } from './util/installPrompt';\nimport { IS_INSTALL_PROMPT_SUPPORTED } from './util/environment';\nimport './global/init';\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\nif (IS_INSTALL_PROMPT_SUPPORTED) {\n setupBeforeInstallPrompt();\n}\ngetActions().init();\n\nif (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('>>> START INITIAL RENDER');\n}\n\nupdateWebmanifest();\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\nif (DEBUG) {\n document.addEventListener('dblclick', () => {\n // eslint-disable-next-line no-console\n console.warn('GLOBAL STATE', getGlobal());\n });\n}\n","// Original idea was found here\n// https://medium.com/@alshakero/how-to-setup-your-web-app-manifest-dynamically-using-javascript-f7fbee899a61\n\nimport { DEBUG } from '../config';\nimport { IS_MAC_OS } from './environment';\n\nexport default function updateWebmanifest() {\n if (!IS_MAC_OS) {\n return;\n }\n\n const manifest = document.getElementById('the-manifest-placeholder');\n if (!manifest) {\n return;\n }\n\n const url = `site_apple${DEBUG ? '_dev' : ''}.webmanifest`;\n manifest.setAttribute('href', url);\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","withCallback","pop","set","catch","finally","delete","startedAt","Date","now","async","isResolved","race","pause","then","undefined","location","reload","ApiMediaFormat","ApiMessageEntityTypes","MAIN_THREAD_ID","MESSAGE_DELETED","DEFAULT_SIZE","loadedAnimationUrls","Set","memo","props","size","play","noLoop","className","noTransition","nonInteractive","onLoad","onClick","otherProps","tgsUrl","key","isAnimationLoaded","markAnimationLoaded","useFlag","has","transitionClassNames","useMediaTransition","handleLoad","useCallback","add","playKey","setPlayKey","useState","String","Math","random","handleClick","buildClassName","lottiePromise","RLottie","ensureLottie","default","ref","style","playSegment","speed","quality","isLowPriority","color","forceOnHeavyAnimation","onEnded","containerRef","useRef","animation","setAnimation","wasPlaying","isFrozen","isFirstRender","playRef","current","playSegmentRef","useEffect","exec","newAnimation","setSpeed","fastRaf","setColor","destroy","playAnimation","shouldRestart","pauseAnimation","freezeAnimation","isPlaying","unfreezeAnimation","unfreezeAnimationOnRaf","changeData","useHeavyAnimationCheck","useBackgroundMode","buildStyle","base","maxint","adapt","delta","numpoints","firsttime","k","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","fromCharCode","toUpperCase","value","join","utf16","getDomain","url","href","ensureProtocol","decodedHref","decodeURI","replace","match","domain","domain_array","split","s","slice","convertPunycode","text","children","isRtl","openUrl","getActions","content","isSafe","e","preventDefault","shouldSkipModal","classNames","title","target","rel","dir","LOCAL_TGS_URLS","MonkeyIdle","MonkeyTracking","MonkeyClose","MonkeyPeek","FoldersAll","FoldersNew","DiscussionGroups","Lock","CameraFlip","HandFilled","HandOutline","Speaker","VoiceAllowTalk","VoiceMini","VoiceMuted","VoiceOutlined","Peach","Eggplant","Cumshot","JoinRequest","Invite","QrPlane","Congratulations","Experimental","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","openChat","id","Link","focusMessage","handleMessageClick","chatId","groupCall","joinGroupCall","accessHash","MAX_LENGTH","NBSP","renderActionMessageText","lang","actionOriginUser","actionOriginChat","targetUsers","targetMessage","targetChatId","options","action","translationValues","amount","currency","call","score","noLinks","asPlainText","asTextWithSpoilers","translationKey","processed","unprocessed","includes","processPlaceholder","formatCurrency","code","renderUserContent","renderChatContent","toString","map","user","filter","renderMessageContent","renderProductContent","renderMigratedContent","forEach","part","renderText","trim","renderGroupCallContent","invoice","getMessageSummaryText","messageSummary","renderMessageSummary","trimText","getUserFullName","chat","getChatTitle","placeholder","replaceValue","placeholderPosition","substring","Array","isArray","index","renderMessageText","highlight","shouldRenderHqEmoji","isSimple","truncateLength","isProtected","observeIntersection","entities","contentNotSupportedText","getMessageText","renderTextWithEntities","noEmoji","TRUNCATED_SUMMARY_LENGTH","hasSpoilers","some","hasCustomEmoji","emoji","getMessageSummaryEmoji","emojiWithSpace","description","getMessageSummaryDescription","RE_LETTER_OR_DIGIT","SIMPLE_MARKDOWN_REGEX","filters","params","compact","reduce","escapeHtml","EMOJI_REGEX","replaceEmojis","addLineBreaks","addHighlight","addLinks","replaceSimpleMarkdown","textParts","divEl","createElement","result","innerText","innerHTML","IS_EMOJI_SUPPORTED","parts","fixNonStandardEmoji","emojis","emojiResult","nativeToUnifiedExtendedWithCache","src","isLoaded","LOADED_EMOJIS","alt","handleEmojiLoad","splittenParts","line","source","trimmedLine","trimLeft","indentLength","repeat","lowerCaseText","toLowerCase","queryPosition","nextSymbol","newParts","RE_LINK","RE_LINK_TEMPLATE","RE_MENTION_TEMPLATE","links","nextLink","shift","lastIndex","startsWith","username","endsWith","entityResult","entity","areLinesWrapping","element","lines","lineHeight","getComputedStyle","lineHeightParsed","parseFloat","clientHeight","actionsByMessageId","createClassNameBuilder","contentRef","isRevealed","reveal","conceal","stopPropagation","actions","contentLength","readingMs","round","timeoutMs","max","min","LOAD_QUEUE","RENDER_HISTORY","loadFromQueue","throttle","loadCustomEmojis","ids","clear","updateLastRendered","updateLastRenderedCustomEmojis","reverse","handlers","prevGlobal","addCallback","global","customEmojis","byId","handler","documentId","customEmoji","setCustomEmoji","getGlobal","handleGlobalChange","useCustomEmoji","mediaHash","mediaData","useMedia","thumbDataUri","useThumbnail","isIntersecting","useIsIntersecting","isVideo","video","querySelector","paused","safePlay","useMemo","IS_WEBM_SUPPORTED","isLottie","playsInline","muted","autoPlay","loop","AnimatedSticker","noCopy","onWordWrapToggle","showNotification","windowSize","useWindowSize","useLang","isWordWrap","setIsWordWrap","withWordWrapButton","setWithWordWrapButton","checkWordWrap","isWrap","parentElement","handleCopy","copyTextToClipboard","handleWordWrapClick","contentClass","overlayClass","wrapClass","setWordWrap","handleWordWrapToggle","wrap","blockClass","language","highlighted","useAsync","lib","shouldRenderAsHtml","renderMessagePart","deleteLineBreakAfterPre","organizedEntities","organizedEntityIndexes","organizedEntity","organizeEntity","organizedIndexes","organizedIndex","organizeEntities","renderEntity","textPartStart","textPartEnd","isLastEntity","renderResult","nestedEntities","offset","textBefore","textBeforeLength","substr","entityStartIndex","entityEndIndex","entityContent","nestedEntityContent","nestedIndex","nestedEntity","nestedEntityIndex","nestedResult","nestedEntityEndIndex","newEntity","rawEntityText","trimEnd","renderedContent","userId","getLinkUrl","processEntityAsHtml","entityText","renderNestedMessagePart","CustomEmoji","handleBotCommandClick","handleHashtagClick","handleCodeClick","role","tabIndex","MentionLink","SafeLink","processEntity","textAfter","arrayIndex","getTextWithEntitiesAsHtml","formattedText","c","concat","parsedEntity","isChanged","sendBotCommand","command","currentTarget","setLocalTextSearchQuery","query","searchTextMessagesLocal","getTranslation","preventMessageInputBlur","withBubbling","IS_IOS","activeElement","EDITABLE_INPUT_ID","preventMessageInputBlurWithBubbling","withGlobal","userOrChat","selectUser","openChatByUsername","onContextMenu","onMouseDown","onMouseEnter","onMouseLeave","onFocus","backgroundImage","pill","fluid","isText","isLoading","isShiny","withPremiumGradient","ariaLabel","ariaControls","hasPopup","download","disabled","allowDisabledClick","ripple","faded","noPreventDefault","shouldStopPropagation","elementRef","isClicked","setIsClicked","fullClassName","handleMouseDown","label","subLabel","checked","blocking","onChange","onCheck","handleChange","event","labelClassName","trigger","positionX","positionY","footer","forceOpen","onOpen","onClose","menuRef","dropdownRef","isOpen","setIsOpen","handleClose","onKeyDown","menu","keyCode","focusedElement","elementChildren","from","focus","onTrigger","autoClose","shouldSkipTransition","success","readOnly","autoComplete","inputMode","maxLength","teactExperimentControlled","onInput","onKeyPress","onBlur","onPaste","labelText","htmlFor","isPrimary","backgroundColor","bubbleStyle","ariaLabelledBy","transformOriginX","transformOriginY","noCloseOnBackdrop","noCompact","onCloseAnimationEnd","backdropContainerRef","useShowTransition","captureEscKeyListener","useHistoryBack","isActive","onBack","shouldBeReplaced","useEffectWithPrevDeps","prevIsOpen","dispatchHeavyAnimationEvent","handleKeyDown","useKeyboardListNavigation","useVirtualBackdrop","bubbleClassName","transformOriginYStyle","transformOriginXStyle","IS_COMPACT_MENU","IS_BACKDROP_BLUR_SUPPORTED","icon","customIcon","destructive","withWrap","origin","IS_TEST","ripples","setRipples","cleanUpDebounced","debounce","button","container","position","getBoundingClientRect","rippleSize","offsetWidth","x","clientX","y","clientY","requestAnimationFrame","activeKey","direction","renderCount","shouldRestoreHeight","shouldCleanup","cleanupExceptionKey","onStart","onStop","animationLevel","settings","byKey","currentKeyRef","rendersRef","prevActiveKey","usePrevious","forceUpdate","useForceUpdate","activeKeyChanged","useLayoutEffect","cleanup","preservedRender","childElements","transition","transform","classList","childNodes","isBackwards","keys","Number","prevActiveIndex","activeIndex","toSlide","fromSlide","ANIMATION_LEVEL_MIN","remove","dispatchHeavyAnimationStop","forceReflow","waitForTransitionEnd","height","performSlideOptimized","toggle","node","HTMLElement","onAnimationEnd","watchedNode","firstChild","waitForAnimationEnd","flexBasis","renders","contents","fill","render","teactOrderKey","teactFastList","APP_NAME","APP_VERSION","process","RELEASE_DATETIME","PRODUCTION_HOSTNAME","DEBUG_MORE","IS_MOCKED_CLIENT","IS_BETA","BETA_CHANGELOG_URL","DEBUG_ALERT_MSG","PAGE_TITLE","INACTIVE_MARKER","DEBUG_PAYMENT_SMART_GLOCAL","SESSION_USER_KEY","LEGACY_SESSION_KEY","PASSCODE_CACHE_NAME","GLOBAL_STATE_CACHE_DISABLED","GLOBAL_STATE_CACHE_KEY","GLOBAL_STATE_CACHE_USER_LIST_LIMIT","GLOBAL_STATE_CACHE_CHAT_LIST_LIMIT","GLOBAL_STATE_CACHE_CHATS_WITH_MESSAGES_LIMIT","GLOBAL_STATE_CACHE_CUSTOM_EMOJI_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","DEFAULT_VOLUME","DEFAULT_PLAYBACK_RATE","PLAYBACK_RATE_FOR_AUDIO_MIN_DURATION","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","EDITABLE_INPUT_CSS_SELECTOR","CUSTOM_APPENDIX_ATTRIBUTE","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","MAX_SCREEN_WIDTH_FOR_EXPAND_PINNED_MESSAGES","MOBILE_SCREEN_MAX_WIDTH","MOBILE_SCREEN_LANDSCAPE_MAX_WIDTH","MOBILE_SCREEN_LANDSCAPE_MAX_HEIGHT","LOCAL_MESSAGE_MIN_ID","TMP_CHAT_ID","ANIMATION_END_DELAY","FAST_SMOOTH_MAX_DISTANCE","FAST_SMOOTH_MIN_DURATION","FAST_SMOOTH_MAX_DURATION","FAST_SMOOTH_SHORT_TRANSITION_MAX_DISTANCE","LOCK_SCREEN_ANIMATION_DURATION_MS","STICKER_SIZE_INLINE_DESKTOP_FACTOR","STICKER_SIZE_INLINE_MOBILE_FACTOR","STICKER_SIZE_AUTH","STICKER_SIZE_AUTH_MOBILE","STICKER_SIZE_PICKER","EMOJI_SIZE_PICKER","STICKER_SIZE_GENERAL_SETTINGS","STICKER_SIZE_PICKER_HEADER","STICKER_SIZE_SEARCH","STICKER_SIZE_MODAL","EMOJI_SIZE_MODAL","STICKER_SIZE_TWO_FA","STICKER_SIZE_PASSCODE","STICKER_SIZE_DISCUSSION_GROUPS","STICKER_SIZE_FOLDER_SETTINGS","STICKER_SIZE_INLINE_BOT_RESULT","STICKER_SIZE_JOIN_REQUESTS","STICKER_SIZE_INVITES","RECENT_SYMBOL_SET_ID","FAVORITE_SYMBOL_SET_ID","CHAT_STICKER_SET_ID","PREMIUM_STICKER_SET_ID","BASE_EMOJI_KEYWORD_LANG","MENU_TRANSITION_DURATION","SLIDE_TRANSITION_DURATION","VIDEO_MOV_TYPE","SUPPORTED_IMAGE_CONTENT_TYPES","SUPPORTED_VIDEO_CONTENT_TYPES","SUPPORTED_AUDIO_CONTENT_TYPES","CONTENT_TYPES_WITH_PREVIEW","CONTENT_NOT_SUPPORTED","RE_TG_LINK","RE_TME_LINK","RE_TELEGRAM_LINK","TME_LINK_PREFIX","COUNTRIES_WITH_12H_TIME_FORMAT","API_CHAT_TYPES","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","FEEDBACK_URL","LIGHT_THEME_BG_COLOR","DARK_THEME_BG_COLOR","DEFAULT_PATTERN_COLOR","DARK_THEME_PATTERN_COLOR","MAX_UPLOAD_FILEPART_SIZE","GROUP_CALL_VOLUME_MULTIPLIER","GROUP_CALL_DEFAULT_VOLUME","GROUP_CALL_THUMB_VIDEO_DISABLED","DEFAULT_LIMITS","uploadMaxFileparts","stickersFaved","savedGifs","dialogFiltersChats","dialogFilters","dialogFolderPinned","captionLength","channels","channelsPublic","aboutLength","addActionHandler","importLegacySession","clearLegacySessions","apiUpdate","userAgent","navigator","PLATFORM_ENV","sessionData","loadStoredSession","isTest","search","isMovSupported","IS_MOV_SUPPORTED","isWebmSupported","maxBufferSize","MAX_BUFFER_SIZE","phoneNumber","authIsLoading","authError","password","file","firstName","lastName","authIsLoadingQrCode","passcode","isScreenLocked","storeSession","currentUserId","clearStoredSession","_global","hangUp","leaveGroupCall","unsubscribe","forceWebsync","reset","forceInitApi","clearEncryptedSession","cacheApi","langCachePrefix","langCacheVersion","updateAppBadge","init","connectionState","authNearestCountry","setGlobal","deviceToken","subscribedAt","sessionJson","JSON","stringify","globalJson","serializeGlobal","encryptSession","forgetPasscode","updatePasscodeSettings","invalidAttemptsCount","clearGlobalForLockScreen","buildInputPrivacyRules","visibility","allowedIds","deniedIds","users","usersById","chats","chatsById","rules","collectUsers","isUserId","collectChats","allowedUsers","allowedChats","blockedUsers","blockedChats","photo","bio","about","profileEdit","progress","ProfileEditProgress","currentUser","updateUser","fullInfo","isUsernameAvailable","loadedWallpapers","wallpapers","createObjectURL","slug","UPLOADING_WALLPAPER_SLUG","wallpaper","firstWallpaper","withLocalMedia","addUsers","buildCollectionByKey","updateChats","blocked","blockedIds","totalCount","contactId","addBlockedContact","removeBlockedContact","serverTimeOffset","addNotifyExceptions","replaceSettings","peerType","isSilent","shouldShowPreviews","updateNotifySettings","hasPushNotifications","hasWebNotifications","subscribe","hasContactJoinedNotifications","languages","phoneNumberSettings","lastSeenSettings","profilePhotoSettings","forwardsSettings","chatInviteSettings","phoneCallSettings","phoneP2PSettings","voiceMessagesSettings","all","privacy","lastSeen","profilePhoto","forwards","chatInvite","phoneCall","phoneP2P","voiceMessages","privacyKey","allowUserIds","allowChatIds","blockUserIds","blockChatIds","isAllowList","contactsIds","isSensitiveEnabled","langCode","countryList","timeFormat","setSettingOption","setTimeFormat","wasTimeFormatSetManually","nearestCountryCode","appConfig","globalSettings","shouldArchiveAndMuteNewNonContact","selectNotifySettings","setLanguage","onUpdateApiReady","wasAuthReady","authState","authorizationState","isLoggingOut","authIsCodeViaApp","isCodeViaApp","authHint","hint","authQrCode","qrCode","onUpdateAuthorizationState","onUpdateAuthorizationError","isOnAuth","signOut","onUpdateConnectionState","authRememberMe","isEmpty","mainDcId","saveSession","onUpdateSession","onUpdateServerTimeOffset","sessionUserAuth","localStorage","getItem","userAuth","parse","setItem","updateSessionUserId","onUpdateCurrentUser","paymentShippingError","getShippingError","addPaymentError","shouldClosePaymentModal","closePaymentModal","showDialog","handleSystemThemeChange","currentThemeMatch","documentElement","currentTheme","nextTheme","selectTheme","switchTheme","mql","matchMedia","addListener","subscribeToSystemThemeChange","messageTextSize","theme","setProperty","setAttribute","body","IS_TOUCH_ENV","startWebsync","IS_ANDROID","IS_MAC_OS","IS_SAFARI","canInstall","uiReadyState","authPhoneNumber","shouldSkipHistoryAnimations","forceSyncOnIOs","replaceThemeSettings","nextScreen","updateCacheThrottled","onIdle","updateCache","unsubscribeFromBeforeUnload","isCaching","initCache","setupCaching","removeItem","clearCaching","loadCache","initialState","cache","time","json","cached","timeEnd","migrateCache","newState","parsedMessageList","IS_SINGLE_COLUMN_LAYOUT","parseLocationHash","messages","messageLists","readCache","hasPasscode","hasStoredSession","onBeforeUnload","removeCallback","removeEventListener","shouldAutoDownloadMediaFromContacts","shouldAutoDownloadMediaInPrivateChats","shouldAutoDownloadMediaInGroups","shouldAutoDownloadMediaInChannels","shouldAutoPlayVideos","shouldAutoPlayGifs","rest","canAutoLoadPhotoFromContacts","canAutoLoadVideoFromContacts","canAutoLoadPhotoInPrivateChats","canAutoLoadVideoInPrivateChats","canAutoLoadPhotoInGroups","canAutoLoadVideoInGroups","canAutoLoadPhotoInChannels","canAutoLoadVideoInChannels","canAutoPlayVideos","canAutoPlayGifs","themes","chatFolders","stickers","greeting","premium","activeDownloads","byChatId","serviceNotifications","audioPlayer","volume","playbackRate","mediaViewer","groupCalls","statusesById","sponsoredByChatId","activeReactions","pollModal","attachMenu","bots","trustedBotIds","activeSessions","byHash","orderedHashes","activeWebSessions","transcriptions","limits","added","lastRendered","premiumSet","light","lightTheme","patternColor","notification","isHidden","isDeleted","isHeavyAnimating","forceUpdateCache","noEncrypt","serializedGlobal","serializedGlobalClean","reducedGlobal","INITIAL_STATE","pick","isMuted","reduceCustomEmojis","isChatInfoShown","reduceShowChatInfo","reduceUsers","reduceChats","reduceMessages","globalSearch","recentlyFoundChatIds","reduceSettings","reduceChatFolders","reduceGroupCalls","availableReactions","reduceAvailableReactions","isCallPanelVisible","idsToSave","innerWidth","currentChatId","selectCurrentMessageList","visibleUserIds","selectVisibleUsers","unique","topPeers","userIds","getOrderedIds","contactList","currentChat","selectCurrentChat","isFullyLoaded","threadId","mainThread","threadsById","viewportIds","notifyExceptions","activeChatFolder","activeGroupCallId","r","FOREVER_BANNED_DATE","VERIFIED_PRIORITY_BASE","PINNED_PRIORITY_BASE","entityId","isChatGroup","isChatBasicGroup","isChatSuperGroup","isChatChannel","isCommonBoxChat","isChatWithRepliesBot","getChatTypeString","getPrivateChatUserId","isSelf","getChatDescription","getChatLink","inviteLink","getChatAvatarHash","owner","avatarHash","getVideoAvatarMediaHash","isChatSummaryOnly","lastMessage","isChatAdmin","adminRights","getHasAdminRight","isUserRightBanned","currentUserBannedRights","defaultBannedRights","getCanPostInChat","isRestricted","isForbidden","migratedTo","isNotJoined","isCreator","getAllowedAttachmentOptions","isChatWithBot","canAttachMedia","canAttachPolls","canSendStickers","canSendGifs","canAttachEmbedLinks","isAdmin","getMessageSendingRestrictionReason","sendMessages","untilDate","formatDateToString","formatTime","getChatSlowModeOptions","slowMode","isChatArchived","folderId","selectIsChatMuted","notifySettings","hasPrivateChatsNotifications","hasBroadcastNotifications","hasGroupNotifications","selectShouldShowMessagePreview","hasPrivateChatsMessagePreview","hasBroadcastMessagePreview","hasGroupMessagePreview","getCanDeleteChat","getFolderDescriptionText","folder","chatsCount","emoticon","pinnedChatIds","excludedChatIds","includedChatIds","excludeArchived","excludeMuted","excludeRead","values","groups","contacts","nonContacts","getMessageSenderName","getUserFirstOrLastName","sortChatIds","chatIds","shouldPrioritizeVerified","priorityIds","orderBy","priority","date","isVerified","filterChatsByName","searchWords","prepareSearchWordsForNeedle","getMessageHtmlId","getMessageKey","previousLocalId","msgId","buildMessageKey","isServiceNotificationMessage","parseMessageKey","getMessageOriginalId","sticker","audio","voice","poll","webPage","contact","game","getMessageCustomShape","isRound","parseEmojiOnlyString","getMessageSingleEmoji","getFirstLinkInMessage","firstTextUrl","find","firstUrl","isOwnMessage","isOutgoing","isReplyMessage","replyToMessageId","isForwardedMessage","forwardInfo","isActionMessage","isAnonymousOwnMessage","senderId","getSenderTitle","getSendingState","sendingState","isMessageLocal","isHistoryClearMessage","getMessageContentFilename","isWebpSupported","baseFilename","IS_OPUS_SUPPORTED","areReactionsEmpty","reactions","results","l","count","isGeoLiveExpired","timestamp","period","getMessageSingleInlineButton","inlineButtons","getMessageRecentReaction","recentReactions","checkIfHasUnreadReactions","isUnread","SPOILER_CHARS","noReactions","isExtended","getMessageTextWithSpoilers","transcription","transcriptionId","getMessageTranscription","textWithoutTranscription","accText","spoiler","generateBrailleSpoiler","groupedId","reaction","truncatedText","summary","isGif","getMessageAudioCaption","question","performer","getMessageContent","hasMessageMedia","getMessagePhoto","getMessageVideo","getMessageDocument","getMessageSticker","getMessageContact","getMessagePoll","getMessageAction","getMessageAudio","getMessageVoice","getMessageRoundVideo","isMessageDocumentPhoto","mediaType","isMessageDocumentVideo","getMessageInvoice","getMessageLocation","getMessageWebPage","getMessageWebPagePhoto","getMessageWebPageVideo","getMessageMediaThumbDataUri","media","getMessageMediaThumbnail","dataUri","getDocumentMediaHash","buildStaticMapHash","geo","width","zoom","scale","long","lat","accuracyRadius","getMessageMediaHash","webPagePhoto","webPageVideo","messageVideo","messagePhoto","mediaId","hasMessageLocalBlobUrl","getVideoOrAudioBaseHash","getAudioHasCover","getWebDocumentHash","webDocument","getGamePreviewPhotoHash","getGamePreviewVideoHash","IS_PROGRESSIVE_SUPPORTED","thumbnailSizes","getMessageMediaFormat","fullVideo","IS_OPFS_SUPPORTED","getMessageFileName","getMessageFileSize","blobUrl","getChatMediaMessageIds","listedIds","isFromSharedMedia","getMessageContentIds","getPhotoFullDimensions","sizes","getPhotoInlineDimensions","getVideoDimensions","getMediaTransferState","isLoadNeeded","isUploading","isTransferring","transferProgress","messageIds","contentType","validator","matchLinkInMessageText","getMediaDuration","duration","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","getBotCoverMediaHash","USER_COLOR_KEYS","isDeletedUser","formatPhoneNumber","getUserStatus","userStatus","wasOnline","getTime","wasOnlineDate","diff","today","setHours","yesterday","setDate","getDate","formatFullDate","isUserOnline","isUserBot","getCanAddContact","isContact","sortUserIds","userStatusesById","getServerTime","expires","filterUsersByName","savedMessagesLang","getUserIdDividend","abs","getUserColorKey","peer","typed","typify","isLeftColumnShown","newChatMembersProgress","NewChatMembersProgress","isUpdateAvailable","phoneCodes","general","listIds","orderedPinnedIds","scheduledMessages","fileUploads","byMessageLocalId","recentEmojis","recentCustomEmojis","setsById","recent","favorite","featured","setIds","forEmoji","emojiKeywords","gifs","saved","inlineBots","byUsername","userSearch","localTextSearch","byChatThreadKey","localMediaSearch","management","topInlineBots","forwardMessages","pollResults","payment","notifications","dialogs","shouldUseSystemTheme","messageSendKeyCombo","canAutoLoadFileFromContacts","canAutoLoadFileInPrivateChats","canAutoLoadFileInGroups","canAutoLoadFileInChannels","autoLoadFileMaxSizeMb","notificationSoundVolume","shouldSuggestStickers","shouldLoopStickers","isConnectionStatusMinimized","isBlurred","dark","twoFaSettings","shouldShowContextMenuHint","statistics","replaceChatListIds","newIds","updateChatListIds","idsUpdate","replaceChats","newById","updateChat","chatUpdate","noOmitUnreadReactionCount","updatedChat","getUpdatedChat","updatedById","acc","addChats","isUpdated","addedById","isMin","shouldOmitMinInfo","omit","photos","updateChatListType","listType","currentListIds","listTypeKey","currentFolderList","updateChatListSecondaryInfo","info","totalCountKey","totalChatCount","leaveChat","leftChatId","selectChatListType","listId","addChatMembers","membersToAdd","currentMembers","members","newMemberIds","m","updatedMembers","currentIds","updatedIds","areSortedArraysEqual","updateStickerSets","category","hash","sets","resultIds","updatedSets","stickerSet","existing","regularSetIds","isEmoji","addedEmojiSetIds","flat","updateStickerSet","stickerSetId","currentStickerSet","isCustomEmoji","addedSets","installedDate","customEmojiById","updateGifSearch","isNew","nextOffset","currentResults","newResults","gif","replaceAnimatedEmojis","animatedEmojis","updateStickersForEmoji","remoteStickers","allStickers","selectStickersForEmoji","uniqueIds","rebuildStickersForEmoji","replaceUsers","updateContactList","updatedUsers","contactUserIds","newContactUserIds","userUpdate","updatedUser","getUpdatedUser","updateUsers","deleteContact","MEMO_EMPTY_ARRAY","updateUserSearch","searchStatePartial","updateUserSearchFetchingStatus","fetchingStatus","updateUserBlockedState","isBlocked","replaceUserStatuses","addUserStatuses","newKeys","closeNewContactDialog","newContact","getComplexKey","updateGlobalSearch","updateGlobalSearchContent","currentContent","updateGlobalSearchResults","newFoundMessages","nextRate","resultsByType","newFoundMessagesById","foundIdsForType","foundIds","every","newId","updateGlobalSearchFetchingStatus","prevFoundIds","newFoundIds","prototype","foundOrPrevFoundIds","nextOffsetId","replaceLocalTextSearch","chatThreadKey","searchParams","updateLocalTextSearch","replaceLocalTextSearchResults","updateLocalTextSearchResults","orderFoundIds","replaceLocalMediaSearch","updateLocalMediaSearchType","currentType","updateLocalMediaSearchResults","replaceLocalMediaSearchResults","sort","a","b","updateManagementProgress","updateManagement","newSettings","notifyException","exceptionData","addNotifyException","updateTwoFaSettings","clearPasscodeSettings","updateShippingOptions","shippingOptions","setRequestInfoId","requestId","setPaymentStep","step","setInvoiceInfo","isRecurring","recurringTermsUrl","invoiceContent","setStripeCardInfo","cardInfo","stripeCredentials","setSmartGlocalCardInfo","smartGlocalCredentials","setPaymentForm","form","setConfirmPaymentUrl","confirmPaymentUrl","setReceipt","receipt","messageInvoice","clearPayment","closeInvoice","isPaymentModalOpen","updateStatistics","updateMessageStatistics","currentMessage","updateStatisticsGraph","updateCurrentMessageList","shouldReplaceHistory","newMessageLists","last","replaceChatMessages","updateMessageStore","updateThread","threadUpdate","replaceThreadParam","paramName","newValue","addMessages","addedByChatId","messagesByChatId","addChatMessagesById","selectChatMessages","updateChatMessage","messageUpdate","updatedMessage","updateScheduledMessage","selectScheduledMessages","replaceScheduledMessages","deleteChatMessages","deletedForwardedPosts","pickTruthy","isLinkedChannelPost","threadInfo","selectThreadInfo","selectListedIds","outlyingIds","selectOutlyingIds","selectViewportIds","pinnedIds","selectPinnedIds","newMessageCount","messagesCount","currentMessageList","canDeleteCurrentThread","currentThreadId","fromChatId","fromMessageId","originalPost","selectChatMessage","deleteChatScheduledMessages","scheduledIds","selectScheduledIds","updateListedIds","orderHistoryIds","updateOutlyingIds","addViewportId","safeReplaceViewportIds","newViewportIds","updateThreadInfo","newThreadInfo","updateThreadInfos","updates","updateScheduledMessages","updateFocusedMessage","noHighlight","isResizingContainer","focusedMessage","updateSponsoredMessage","updateFocusDirection","enterMessageSelectMode","selectedMessages","toggleMessageSelection","messageListType","childMessageIds","withShift","oldSelectedMessages","selectMessageIdsByGroupId","selectedMessageIds","newMessageIds","newSelectedMessageIds","selectCurrentMessageIds","prevIndex","currentIndex","to","exitMessageSelectMode","updateThreadUnreadFromForwardedMessage","originMessage","lastMessageId","isDeleting","channelPostId","threadInfoOld","selectChat","selectChatUser","selectIsChatWithSelf","selectIsChatWithBot","selectSupportChat","isSupport","selectChatOnlineCount","onlineCount","selectChatBot","selectIsTrustedBot","botId","bot","selectChatType","selectBot","selectIsChatBotNotStarted","messageInfo","selectAreActiveChatsLoaded","active","selectIsChatListed","targetList","list","selectChatFolder","selectIsChatPinned","archived","chatFoldersById","selectChatByUsername","usernameLowered","selectIsServiceChatReady","selectSendAs","sendAsId","selectRequestedText","requestedDraft","filterChatIdsByType","selectCurrentStickerSearch","selectCurrentGifSearch","selectStickerSet","shortName","stickersForEmoji","packs","cleanEmoji","selectIsSetPremium","isFree","selectAnimatedEmoji","cleanedEmoji","selectAnimatedEmojiEffect","animatedEmojiEffects","selectAnimatedEmojiSound","emojiSounds","selectLocalAnimatedEmoji","selectLocalAnimatedEmojiEffect","selectLocalAnimatedEmojiEffectByName","selectThreadParam","thread","selectScrollOffset","selectReplyingToId","selectEditingId","selectEditingDraft","selectEditingScheduledId","selectEditingScheduledDraft","selectDraft","selectNoWebPage","selectFirstMessageId","selectReplyStack","selectThreadOriginChat","originChannelId","selectThreadTopMessageId","topMessageId","selectThreadByMessage","replyToTopMessageId","selectIsMessageInCurrentMessageList","selectIsViewportNewest","chatMessages","selectScheduledMessage","selectEditingMessage","selectChatMessageByPollId","pollId","messageWithPoll","selectFocusedMessageId","focusedChatId","selectIsMessageFocused","focusedId","selectIsMessageUnread","lastReadOutboxMessageId","selectOutgoingStatus","isScheduledList","selectSender","selectReplySender","isForwarded","senderUserId","hiddenUserName","selectForwardedSender","isChannelPost","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","canSaveGif","canRevote","closed","quiz","isChosen","canClosePoll","noOptions","ability","selectCanDeleteSelectedMessages","messageActions","selectCanReportSelectedMessages","selectCanDownloadSelectedMessages","selectIsDownloading","activeInChat","selectActiveDownloadIds","selectUploadProgress","selectRealLastReadId","lastReadInboxMessageId","Infinity","selectFirstUnreadId","lastReadId","lastReadServiceNotificationId","findAfterLastReadId","isFromScheduled","found","selectIsForwardModalOpen","isModalShown","selectCommonBoxChatId","fromLastMessage","selectIsInSelectMode","selectIsMessageSelected","selectForwardedMessageIdsByGroupId","selectIsDocumentGroupSelected","selectedIds","groupIds","selectSelectedMessagesCount","selectNewestMessageWithBotKeyboardButtons","findLast","keyboardButtons","replyHideMessageId","shouldHideKeyboardButtons","selectCanAutoLoadMedia","isPhoto","isFile","canAutoLoadMedia","canAutoLoadMediaFromContacts","canAutoLoadMediaInPrivateChats","canAutoLoadMediaInGroups","canAutoLoadMediaInChannels","isMediaFromContact","selectIsUserOrChatContact","selectCanAutoPlayMedia","asGif","selectShouldLoopStickers","selectLastServiceNotification","maxId","selectIsMessageProtected","selectHasProtectedMessage","selectSponsoredMessage","expiresAt","selectDefaultReaction","defaultReaction","isInactive","enabledReactions","selectShouldSchedule","selectCanScheduleUntilOnline","chatBot","selectUserStatus","selectMessageCustomEmojiSets","selectCustomEmojis","documents","doc","stickerSetInfo","selectForwardsContainVoiceMessages","selectCurrentTextSearch","currentSearch","selectCurrentMediaSearch","selectStatistics","selectManagement","selectCurrentManagementType","selectIsMediaViewerOpen","avatarOwnerId","selectRightColumnContentKey","selectIsPollResultsOpen","RightColumnContent","currentManagement","selectCurrentManagement","isStatisticsShown","currentMessageId","selectIsMessageStatisticsShown","canViewStatistics","selectIsStatisticsShown","selectIsRightColumnShown","getSystemTheme","selectCurrentGlobalSearchQuery","selectPaymentInputInvoice","inputInvoice","selectPaymentFormId","formId","selectPaymentRequestId","selectProviderPublishableKey","nativeParams","publishableKey","selectProviderPublicToken","publicToken","selectStripeCredentials","selectSmartGlocalCredentials","selectNotifyExceptions","selectIsUserBlocked","selectIsCurrentUserPremium","isPremium","selectIsPremiumPurchaseBlocked","isPremiumPurchaseBlocked","selectUserByPhoneNumber","phoneNumberCleaned","fn","deps","defaultValue","setIsLoading","setError","setResult","wasCancelled","res","hasFocus","useCurrentOrPrev","shouldSkipUndefined","shouldForceCurrent","prev","useDebouncedCallback","ms","noFirst","noLast","fnMemo","cb","dependencies","debugKey","prevDeps","initial","setValue","setTrue","setFalse","setTrigger","ANIMATION_START_EVENT","ANIMATION_END_EVENT","timeout","isAnimating","onEnd","clearTimeout","dispatchEvent","Event","handleAnimationStart","handleAnimationEnd","isDisabled","LOCATION_HASH","PATH_BASE","pathname","historyUniqueSessionId","historyState","historyCursor","isAlteringHistory","deferredHistoryOperations","deferredPopstateOperations","isSafariGestureAnimation","handleTouchEnd","applyDeferredHistoryOperations","goOperations","op","stateOperations","goCount","history","go","processStateOperations","deferHistoryOperation","historyOperation","resetHistory","back","replaceState","cleanupClosed","alreadyClosedCount","countClosed","isClosed","cleanupTrashedState","disableHistoryAnimations","indexRef","wasReplaced","processBack","useOnChange","shouldReplace","previousRecord","markReplaced","pushState","TEST_getHistoryState","TEST_getHistoryCursor","touches","pageX","state","previousUniqueSessionId","useIntersectionObserver","rootCallback","rootRef","throttleMs","debounceMs","shouldSkipFirst","margin","threshold","controllerRef","rootCallbackRef","freezeFlagsRef","onUnfreezeRef","freeze","unfreeze","observer","disconnect","callbacks","observe","targetCallback","entriesAccumulator","observerCallbackSync","entries","entry","scheduler","observerCallback","IntersectionObserver","root","rootMargin","initController","controller","unobserve","useOnIntersect","targetRef","setIsIntersecting","onSelectWithEnter","itemSelector","noCaptureFocus","focusedIndex","setFocusedIndex","querySelectorAll","newIndex","item","langProvider","noLoad","mediaFormat","cacheBuster","delay","mediaLoader","spentTime","isMediaReady","bundleName","moduleName","autoUpdate","module","getModuleFromMemory","addLoadListener","loadModule","d","next","onCloseTransitionEnd","noOpenTransition","noCloseTransition","setIsClosed","closeTimeoutRef","hasOpenClassName","setHasOpenClassName","shouldHaveOpenClassName","isClosing","shouldRender","hasShownClass","hasOpenClass","isMessage","shouldDecodeThumbnail","thumbnailDecoded","setThumbnailDecoded","EMPTY_IMAGE_DATA_URI","webpToPngBase64","uri","handleEvent","contains","setSize","isResizing","setIsResizing","setIsResizingDebounced","throttledSetIsResizing","throttledSetSize","handleResize","NON_BUBBLEABLE_EVENTS","documentEventCounters","delegationRegistryByEventType","delegatedEventTypesByElement","resolveEventType","propName","eventType","tagName","canUseEventDelegation","realEventType","asCapture","addDelegatedListener","resolveDelegationRegistry","newSet","resolveDelegatedEventTypes","removeDelegatedListener","realEvent","events","furtherCallsPrevented","Proxy","p","Reflect","parentNode","documentListenersCount","delegatedHandlersCount1","counter","delegationRegistriesCount","delegatedHandlersCount2","delegationRegistry","delegationElementsCount","delegatedEventTypesCount","eventTypes","FILTERED_ATTRIBUTES","HTML_ATTRIBUTES","CONTROLLABLE_TAGS","MAPPED_ATTRIBUTES","headsByElement","renderWithVirtual","parentEl","$current","$new","$parent","skipComponentUpdate","fragment","nextSibling","isCurrentComponent","isComponentElement","isNewComponent","$newAsReal","isCurrentFragment","isFragmentElement","isNewFragment","hasElementChanged","updateComponent","componentInstance","isMounted","setupComponentUpdateListener","newTarget","initComponent","mountChildren","createNode","insertBefore","remount","getNextSibling","isFragment","renderChildren","$currentAsReal","isTagElement","$newAsTag","updateAttributes","$element","mountComponent","$firstChild","renderComponent","$child","isEmptyElement","createTextNode","isTextElement","tag","processControlled","defaultChecked","processUncontrolledOnMount","componentNextSibling","isComponent","unmountComponent","unmountChildren","replaceChild","removeChild","unmountRealTree","removeAllDelegatedListeners","isParentElement","appendChild","currentEl","child","DEBUG_checkKeyUniqueness","$newChild","currentRemainingIndex","remainingByKey","$currentChild","isKeyPresent","newChildKey","orderKey","fragmentElements","fragmentIndex","newChildren","currentPreservedIndex","currentChildInfo","renderFragment","newOrderKey","shouldMoveNode","isMovingDown","renderFastListChildren","currentChildrenLength","newChildrenLength","createDocumentFragment","lastCurrentChild","fragmentNextSibling","elements","isValueControlled","isCheckedControlled","currentEntries","newEntries","currentValue","cssText","removeAttribute","__html","headId","getAttribute","$head","$newElement","VirtualElementTypesEnum","Fragment","Symbol","DEBUG_SILENT_RENDERS_FOR","renderingInstance","Empty","Text","Tag","Component","buildFragmentElement","createComponentInstance","buildTagElement","dropEmptyTail","buildChildElement","parsedChildren","hooks","cursor","byCursor","effects","memos","refs","buildComponentElement","noEmpty","isEmptyPlaceholder","DEBUG_components","newRenderedValue","DEBUG_startAt","componentName","renderTimes","performance","handleError","renderedValue","$old","effect","hook","nextValue","setter","helpGc","prepareComponentForFrame","prepareForFrame","throttleWithPrimaryRaf","throttleWithRaf","forceUpdateComponent","currentElement","DEBUG_contentComponentName","useLayoutEffectBase","schedulerFn","primarySchedulerFn","execCleanup","dependency","causedBy","prevValue","fastRafPrimary","onTickEnd","onTickEndPrimary","resolver","getUnequalProps","newCallback","DEBUG_currentCapturedId","currentGlobal","DEBUG_releaseCapturedIdThrottled","throttleWithTickEnd","actionHandlers","containers","mapStateToProps","ownProps","mappedProps","newMappedProps","isNaN","DEBUG_componentName","arePropsShallowEqual","areMappedPropsChanged","DEBUG_updates","updateTime","runCallbacksThrottled","runCallbacks","newGlobal","DEBUG_capturedId","actionQueue","handleAction","TeactNContainer","vs16RegExp","zeroWidthJoiner","removeVS16s","rawEmoji","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","unreadCount","setAppBadge","currentProps","newProps","currentKeys","currentKeysLength","prop","elementName","baseName","modifiers","modifier","self","caches","Type","fetch","cacheName","isHtmlAllowed","request","Request","open","headers","Blob","blob","shouldRecreate","resolvedType","Json","ArrayBuffer","arrayBuffer","save","cacheData","Response","put","createCallbackManager","hasCallbacks","captureKeyboardListener","onEsc","keyToHandlerName","Enter","Backspace","Delete","Esc","Escape","ArrowUp","ArrowDown","ArrowLeft","ArrowRight","Tab","onEnter","onDelete","onBackspace","onUp","onDown","onLeft","onRight","onTab","captureKeyboardListeners","hasActiveHandlers","handlerName","currentEventHandlers","findIndex","releaseKeyboardListener","keyHandlers","CLIPBOARD_ITEM_SUPPORTED","clipboard","ClipboardItem","textCopyEl","str","selection","getSelection","rangeToRestore","rangeCount","getRangeAt","select","execCommand","removeAllRanges","addRange","copyImageToClipboard","imageUrl","canvas","ctx","getContext","imageEl","Image","onload","img","drawImage","toBlob","copyBlobToClipboard","pngBlob","write","propertyName","waitForEndEvent","animationName","detailedName","isHandled","TransitionEvent","AnimationEvent","WEEKDAYS_FULL","MONTHS_FULL_LOWERCASE","month","MILLISECONDS_IN_DAY","isToday","getDayStartAt","getDayStart","datetime","toYearMonth","getFullYear","getMonth","toIsoString","hours","getHours","marker","padStart","getMinutes","formatPastTimeShort","weekAgo","getDay","noYear","formatMonthAndYear","isShort","formatCountdown","msLeft","days","formatMediaDuration","formatCountdownShort","ceil","formatLastUpdated","currentTime","lastUpdated","seconds","formatTimeDuration","showLast","durationRecords","labels","multiplier","idx","modulus","formatHumanDate","noWeekdays","isUpperFirst","upperFirst","lowerFirst","weekAhead","weekDay","formattedDate","formatMediaDateTime","maxValue","minutes","maxHours","maxMinutes","string","formatVoiceRecordDuration","durationInMs","milliseconds","formatDayToStringWithCache","withCache","dayStartAt","locale","monthFormat","noDay","toLocaleString","year","day","formatDateTimeToString","hour","minute","second","isValidDate","MAX_MONTH_IN_YEAR","parseDateString","matchStringDate","matchEuropeStringDate","matchNumberDate","dateParts","monthIndex","timestampPlusDay","EXCLUDE_EMOJIS","EMOJI_EXCEPTIONS","unifiedToNative","unified","codePoints","parseInt","fromCodePoint","dataset","path","regex","replacement","pairs","nativeToUnified","uncompressEmoji","emojiData","categories","emojiRaw","names","native","image","isoToEmoji","iso","test","codePointAt","isWebpSupportedCache","webp","handleLoadOrError","onerror","hasWebp","systemThemeCache","matches","IS_PRODUCTION_HOST","host","os","getPlatform","IS_PWA","standalone","referrer","IS_TABLET_COLUMN_LAYOUT","IS_VOICE_RECORDING_SUPPORTED","mediaDevices","AudioContext","webkitAudioContext","inlineEl","newEmojiWidth","legacyEmojiWidth","isLastEmojiVersionSupported","IS_SERVICE_WORKER_SUPPORTED","Audio","canPlayType","IS_CANVAS_FILTER_SUPPORTED","IS_REQUEST_FULLSCREEN_SUPPORTED","ARE_CALLS_SUPPORTED","LAYERS_ANIMATION_NAME","TEST_VIDEO","DPR","devicePixelRatio","MASK_IMAGE_DISABLED","storage","getDirectory","directory","removeEntry","recursive","CSS","supports","IS_SCROLL_PATCH_NEEDED","IS_INSTALL_PROMPT_SUPPORTED","MESSAGE_LIST_SENSITIVE_AREA","VIDEO_AVATARS_DISABLED","dataUriToBlob","arr","mime","bstr","atob","u8arr","Uint8Array","blobToDataUri","reader","FileReader","readAsDataURL","blobToFile","File","lastModified","preloadImage","preloadVideo","onloadedmetadata","createPosterForVideo","onseeked","videoWidth","videoHeight","toDataURL","fetchBlob","imgToCanvas","constructor","fileBits","super","this","initials","buildInitials","prepared","updateFolderManagerThrottled","updateFolderManager","inited","orderedIdsByFolderId","getPinnedChatsCount","pinnedCountByFolderId","getChatsCount","chatsCountByFolderId","getUnreadCounters","unreadCountersByFolderId","getAllNotificationsCount","notificationsCount","getOrderKey","chatSummariesById","order","addOrderedIdsCallback","addChatsCountCallback","addUnreadCountersCallback","DEBUG_startedAt","isAllFolderChanged","isMainFolderChanged","isArchivedFolderChanged","isAllFullyLoadedChanged","isAllFolderFullyLoaded","isArchivedFullyLoadedChanged","isArchivedFolderFullyLoaded","areFoldersChanged","foldersById","areChatsChanged","areUsersChanged","areNotifySettingsChanged","areNotifyExceptionsChanged","affectedFolderIds","emptyFolderIds","folderSummariesById","updateFullyLoaded","updateResults","prevAllFolderListIds","allFolderListIds","prevArchivedFolderListIds","archivedFolderListIds","changedFolders","newListIds","newPinnedIds","buildFolderSummaryFromMainList","allFolderPinnedIds","archivedFolderPinnedIds","newFoldersById","buildFolderSummary","updateFolders","newChatsById","newUsersById","newNotifySettings","newNotifyExceptions","folderSummaries","newAllFolderListIds","newArchivedFolderListIds","allIds","newFolderIds","currentSummary","newSummary","unreadMentionsCount","hasUnreadMark","joinDate","draftDate","userInfo","shouldHideServiceChat","isListed","isArchived","isUserContact","buildChatSummary","chatSummary","folderSummary","isChatInFolder","buildChatFolderIds","currentFolderIds","folderIdsByChatId","deletedFolderIds","currentFolderIdsSet","newFolderIdsSet","currentFolderOrderedIds","chatIdsByFolderId","isOrderedListJustPatched","updateListsForChat","currentPinnedIds","wasUnreadCountersChanged","wasChatsCountChanged","pinnedCount","newPinnedCount","orderedIds","newOrderedIds","prevOrderedIds","sortedPinnedIds","allListIds","sortedNotPinnedIds","chatId1","chatId2","buildFolderOrderedIds","currentOrderedIds","currentPinnedCount","currentChatsCount","newChatsCount","currentUnreadCounters","newUnreadCounters","buildFolderUnreadCounters","newInitials","totalPrice","Intl","NumberFormat","format","getCurrencyExp","store","hasOwnProperty","READABLE_ERROR_MESSAGES","CHAT_RESTRICTED","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","PINNED_DIALOGS_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","BOT_PRECHECKOUT_TIMEOUT","CHAT_WRITE_FORBIDDEN","CHAT_ADMIN_REQUIRED","SHIPPING_ERRORS","FINAL_PAYMENT_ERRORS","getReadableErrorText","isSlowMode","textParams","extraPartIndex","errorMessage","handleErrorEvent","ErrorEvent","reason","alert","promptInstall","setupBeforeInstallPrompt","prompt","userChoice","outcome","setInstallPrompt","getPromptInstall","collection","member","mapValues","newByKey","object","stringKeys","orderRule","mode","compareValues","currentOrderRule","isAsc","aValue","bValue","mode1","mode2","orderRule1","orderRule2","isAsc1","isAsc2","array","uniqueByField","array1","array2","areSortedArraysIntersecting","findIntersectionWithSet","chunkSize","cloneDeep","predicate","SUBSTITUTION_REGEX","PLURAL_OPTIONS","PLURAL_RULES","en","ar","be","n10","n100","ca","cs","v0","de","es","fa","fi","fr","it","hr","i10","i100","f10","f100","hu","ko","nb","nl","pl","ru","sk","sr","tr","uk","uz","langPack","fallbackLangPack","currentLangCode","currentTimeFormat","cacheValue","langString","processTranslation","importFallbackLangPack","getTranslationForLangString","translateString","remoteLangPack","remote","fetchRemoteString","withFallback","newLangPack","fetchRemote","langInfo","rtl","langName","nativeName","sourceLangPacks","preferredPluralOption","optionIndex","getPluralOption","template","otherValue","translationSlices","initialValue","processTemplate","formatInteger","clamp","num","isBetween","decimals","lerp","start","end","interpolationRatio","SAMPLE_RATE","oggToWav","opusData","typedArray","decoderWorker","wavWorker","onmessage","buffers","buffer","page","terminate","wavBitDepth","wavSampleRate","decoderSampleRate","outputBufferSampleRate","pages","asCacheApiType","memoryCache","fetchPromises","progressCallbacks","cancellableCallbacks","onProgress","callbackUniqueId","getProgressive","getDownloadUrl","fetchFromCacheOrRemote","activeCallbacks","getFromMemory","cancelProgress","parentCallback","progressiveUrl","mediaPng","webpToPng","prepareMedia","mediaSource","MediaSource","streamUrl","sourceBuffer","addSourceBuffer","makeOnProgress","revokeObjectURL","endOfStream","appendBuffer","serviceWorker","fullSize","Bundles","LOAD_PROMISES","MEMORY_CACHE","Auth","Main","Extra","Calls","bundle","getDeviceToken","subscription","toJSON","endpoint","checkIfPushSupported","ServiceWorkerRegistration","Notification","permission","checkIfNotificationsSupported","soundPlayedIds","playNotifySound","currentVolume","once","playNotifySoundDebounced","requestPermission","unsubscribeFromPush","dispatch","deleteDeviceToken","serviceWorkerRegistration","ready","pushManager","getSubscription","areSettingsLoaded","loadNotificationSettings","resultSettings","resultExceptions","checkIfShouldResubscribe","userVisibleOnly","setDeviceToken","DOMException","ABORT_ERR","getAvatar","imageHash","notifyAboutCall","badge","vibrate","onclick","close","notifyAboutMessage","isReaction","checkIfShouldNotify","areNotificationsSupported","activeReaction","messageSender","messageAction","actionTargetMessage","targetUserIds","actionTargetUserIds","actionTargetChatId","actionTargetUsers","privateChatUserId","privateChatUser","isChat","senderName","getNotificationContent","onshow","closeMessageNotifications","notifyClientReady","currentPasscodeHash","setupPasscode","sha256","sessionEncrypted","aesEncrypt","globalEncrypted","decryptSession","passcodeHash","load","aesDecrypt","plaintext","crypto","subtle","digest","TextEncoder","encode","pwHash","iv","getRandomValues","alg","importKey","ptUint8","ctBuffer","encrypt","ct","dataArray","plainBuffer","decrypt","TextDecoder","PATTERN_PLACEHOLDER","DEFAULT_PATTERN","getCountryCodesByIso","phoneCodeList","country","iso2","getCountryFromPhoneNumber","possibleCountries","countryCode","codesWithPrefix","prefixes","prefix","bestMatches","pattern","numberWithoutCode","patterns","defaultPattern","stripped","getBestPattern","formatPhoneNumberWithCode","numberWithPlus","createMessageHash","typeOrThreadId","isType","mediaEl","waitingTimeout","shouldRunFirst","shouldRunLast","interval","isPending","_args","setInterval","clearInterval","throttleWith","waiting","requestIdleCallback","rafPromise","fastRafCallbacks","fastRafPrimaryCallbacks","onTickEndCallbacks","onTickEndPrimaryCallbacks","beforeUnloadCallbacks","currentCallbacks","currentPrimaryCallbacks","isLast","unshift","RE_NOT_LETTER","haystack","needle","needleWords","haystackLower","haystackWords","needleWord","haystackWord","promisifyRequest","oncomplete","onsuccess","onabort","defaultGetStoreFunc","defaultGetStore","dbName","storeName","dbp","userAgentData","indexedDB","databases","tryIdb","intervalId","onupgradeneeded","createObjectStore","txMode","db","transaction","objectStore","createStore","DC_IDS","withLegacy","checkSessionLocked","userAuthJson","dcID","hashes","dcId","sessionId","customStore","idb","idbKeys","getAllKeys","items","openCursor","continue","eachCursor","stateFromCache","isInitialized","HEX_COLOR_REGEX","RGB_VARIABLES","colors","themeColors","property","hexToRgb","hex","g","applyColorAnimationStep","startIndex","endIndex","propertyColors","withAnimation","themeClassName","isDarkTheme","shouldAnimate","startAt","themeColorTag","formatFixedNumber","formatIntegerCompact","views","getFirstLetters","phrase","word","FILE_SIZE_UNITS","formatFileSize","initWebpWorker","wasmReady","requests","getDecodePromise","ImageData","putImageData","createPng","handleLibWebpMessage","WEBSYNC_URLS","WEBSYNC_VERSION","WEBSYNC_KEY","getTs","lastTimeout","authed","currentTs","canRedirect","ts","script","removeElement","URLSearchParams","version","saveSync","clearWebsync","IS_LANDSCAPE","isLandscape","initialHeight","currentWindowSize","updateSizes","isRefreshDisabled","visualViewport","pageTop","vh","getIsKeyboardVisible","disableRefresh","enableRefresh","WeakMap","fnCache","cacheKey","__webpack_module_cache__","__webpack_require__","moduleId","cachedModule","exports","__webpack_modules__","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","registrations","getRegistrations","unregister","register","hasErrorKey","STORAGE_KEY","tabKey","SITE_FONTS","preloadFonts","font","fonts","translation","setTranslation","getSuggestedLanguage","suggestedLanguage","MENU_HIDING_DURATION","inputRef","setFilter","filteredList","setFilteredList","updateFilter","filterValue","defaultName","getFilteredList","prevPhoneCodeList","handleInput","handleInputKeyDown","CodeInput","handleTrigger","formEl","getElementById","scrollTo","top","scrollHeight","behavior","inputValue","Spinner","DropdownMenu","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","monkeyPath","selectionStart","selectionEnd","shouldFixSafariAutoComplete","handleKeepSessionChange","isAuthReady","onSubmit","InputText","Checkbox","Button","Loading","AuthCode","useModuleLoader","AuthPassword","AuthRegister","qrCodeStylingPromise","returnToAuthPhoneNumber","qrCodeRef","isQrMounted","markQrMounted","unmarkQrMounted","QrCodeStyling","blankUrl","dotsOptions","cornersSquareOptions","imageOptions","imageSize","qrOptions","errorCorrectionLevel","token","append","AnimatedIcon","isMobile","renderingAuthState","Transition","getActiveKey","AuthQrCode","getScreen","isLocked","LockScreen","handleReload","appInactivePath","preloadAvatars","preloadTasks","main","isCurrentUserPremium","premiumReactionThumbsPath","reactionThumbsPath","telegramLogoPath","authCode","authPassword","lock","lockPreviewPath","inactive","isRightColumnShown","leftColumnWidth","setIsUiReady","isReady","markReady","shouldRenderMask","safePreload","styles","AppScreens","markInactive","handleDrag","dataTransfer","dropzone","dropEffect","handleDrop","auth","renderContent","manifest","updateWebmanifest","TeactDOM"],"sourceRoot":""}