mirror of
https://github.com/danog/telegram-tt.git
synced 2024-12-02 09:37:47 +01:00
1 line
986 KiB
Plaintext
1 line
986 KiB
Plaintext
{"version":3,"file":"main.7657ba879d5da38b7ec7.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,UAiIlBC,OAAOjB,iBAAiB,SAAS,KAC1BkB,IAELC,YAAW,IAAMD,KAAoB,SA/HhCE,EAAY,CACjBlB,KAAM,UACNmB,KAAM,CAAC3B,KAIJ,SAAS4B,EAAiCC,GAC/C,IAAKnC,EAMH,YALIO,EAAAA,IAEFC,QAAQ4B,KAAK,2BAJiE,2BAArBH,EAAqB,iCAArBA,EAAqB,kBAUlF,MAAMI,EAAUL,EAAY,CAC1BlB,KAAM,aACNwB,KAAMH,EACNF,KAAAA,IA0BF,OAtBI1B,EAAA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BmZ,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) && typeof payload.args[1] === 'function') {\n const callback = payload.args.pop() as AnyToVoidFunction;\n requestState.callback = callback;\n requestStatesByCallback.set(callback, requestState);\n }\n\n requestStates.set(messageId, requestState);\n\n promise\n .catch(() => undefined)\n .finally(() => {\n requestStates.delete(messageId);\n\n if (requestState.callback) {\n requestStatesByCallback.delete(requestState.callback);\n }\n });\n\n worker.postMessage(payload);\n\n return promise;\n}\n\nconst startedAt = Date.now();\n\n// Workaround for iOS sometimes stops interacting with worker\nfunction setupIosHealthCheck() {\n window.addEventListener('focus', () => {\n void ensureWorkerPing();\n // Sometimes a single check is not enough\n setTimeout(() => ensureWorkerPing(), 1000);\n });\n}\n\nasync function ensureWorkerPing() {\n 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 content.push(...processed);\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 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=\"button\"\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!;\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:(\\/\\/)?([?=&\\d\\w_-]+)?/;\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\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 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\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 getChatOrder(chat: ApiChat) {\n return Math.max(chat.joinDate || 0, chat.draftDate || 0, chat.lastMessage?.date || 0);\n}\n\nexport function isChatArchived(chat: ApiChat) {\n return chat.folderId === ARCHIVED_FOLDER_ID;\n}\n\nexport function selectIsChatMuted(\n chat: ApiChat, notifySettings: NotifySettings, notifyExceptions: Record<string, NotifyException> = {},\n) {\n // If this chat is in exceptions they take precedence\n if (notifyExceptions[chat.id] && notifyExceptions[chat.id].isMuted !== undefined) {\n return notifyExceptions[chat.id].isMuted;\n }\n\n return (\n chat.isMuted\n || (isUserId(chat.id) && !notifySettings.hasPrivateChatsNotifications)\n || (isChatChannel(chat) && !notifySettings.hasBroadcastNotifications)\n || (isChatGroup(chat) && !notifySettings.hasGroupNotifications)\n );\n}\n\nexport function selectShouldShowMessagePreview(\n chat: ApiChat, notifySettings: NotifySettings, notifyExceptions: Record<string, NotifyException> = {},\n) {\n const {\n hasPrivateChatsMessagePreview = true,\n hasBroadcastMessagePreview = true,\n hasGroupMessagePreview = true,\n } = notifySettings;\n // If this chat is in exceptions they take precedence\n if (notifyExceptions[chat.id] && notifyExceptions[chat.id].shouldShowPreviews !== undefined) {\n return notifyExceptions[chat.id].shouldShowPreviews;\n }\n\n return (isUserId(chat.id) && hasPrivateChatsMessagePreview)\n || (isChatChannel(chat) && hasBroadcastMessagePreview)\n || (isChatGroup(chat) && hasGroupMessagePreview);\n}\n\nexport function getCanDeleteChat(chat: ApiChat) {\n return isChatBasicGroup(chat) || ((isChatSuperGroup(chat) || isChatChannel(chat)) && chat.isCreator);\n}\n\nexport function 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 case 'userTypeDeleted':\n case 'userTypeUnknown': {\n return 'Deleted account';\n }\n }\n\n return undefined;\n}\n\nexport function getUserStatus(\n lang: LangFn, user: ApiUser, userStatus: ApiUserStatus | undefined, serverTimeOffset: number,\n) {\n if (user.id === SERVICE_NOTIFICATIONS_USER_ID) {\n return lang('ServiceNotifications').toLowerCase();\n }\n\n if (user.type && user.type === 'userTypeBot') {\n return lang('Bot');\n }\n\n if (!userStatus) {\n return '';\n }\n\n switch (userStatus.type) {\n case 'userStatusEmpty': {\n return lang('ALongTimeAgo');\n }\n\n case 'userStatusLastMonth': {\n return lang('WithinAMonth');\n }\n\n case 'userStatusLastWeek': {\n return lang('WithinAWeek');\n }\n\n case 'userStatusOffline': {\n const { wasOnline } = userStatus;\n\n if (!wasOnline) return lang('LastSeen.Offline');\n\n const now = new Date(new Date().getTime() + serverTimeOffset * 1000);\n const wasOnlineDate = new Date(wasOnline * 1000);\n\n if (wasOnlineDate >= now) {\n return lang('LastSeen.JustNow');\n }\n\n const diff = new Date(now.getTime() - wasOnlineDate.getTime());\n\n // within a minute\n if (diff.getTime() / 1000 < 60) {\n return lang('LastSeen.JustNow');\n }\n\n // within an hour\n if (diff.getTime() / 1000 < 60 * 60) {\n const minutes = Math.floor(diff.getTime() / 1000 / 60);\n return lang('LastSeen.MinutesAgo', minutes);\n }\n\n // today\n const today = new Date();\n today.setHours(0, 0, 0, 0);\n const serverToday = new Date(today.getTime() + serverTimeOffset * 1000);\n if (wasOnlineDate > serverToday) {\n // up to 6 hours ago\n if (diff.getTime() / 1000 < 6 * 60 * 60) {\n const hours = Math.floor(diff.getTime() / 1000 / 60 / 60);\n return lang('LastSeen.HoursAgo', hours);\n }\n\n // other\n return lang('LastSeen.TodayAt', formatTime(lang, wasOnlineDate));\n }\n\n // yesterday\n const yesterday = new Date();\n yesterday.setDate(now.getDate() - 1);\n yesterday.setHours(0, 0, 0, 0);\n const serverYesterday = new Date(yesterday.getTime() + serverTimeOffset * 1000);\n if (wasOnlineDate > serverYesterday) {\n return lang('LastSeen.YesterdayAt', formatTime(lang, wasOnlineDate));\n }\n\n return lang('LastSeen.AtDate', formatFullDate(lang, wasOnlineDate));\n }\n\n case 'userStatusOnline': {\n return lang('Online');\n }\n\n case 'userStatusRecently': {\n return lang('Lately');\n }\n\n default:\n return undefined;\n }\n}\n\nexport function isUserOnline(user: ApiUser, userStatus?: ApiUserStatus) {\n const { id, type } = user;\n\n if (!userStatus) {\n return false;\n }\n\n if (id === SERVICE_NOTIFICATIONS_USER_ID) {\n return false;\n }\n\n return userStatus.type === 'userStatusOnline' && type !== 'userTypeBot';\n}\n\nexport function isDeletedUser(user: ApiUser) {\n if (user.noStatus || user.type === 'userTypeBot' || user.id === SERVICE_NOTIFICATIONS_USER_ID) {\n return false;\n }\n\n return user.type === 'userTypeDeleted'\n || user.type === 'userTypeUnknown';\n}\n\nexport function isUserBot(user: ApiUser) {\n return user.type === 'userTypeBot';\n}\n\nexport function getCanAddContact(user: ApiUser) {\n return !user.isContact && !isUserBot(user);\n}\n\nexport function sortUserIds(\n userIds: string[],\n usersById: Record<string, ApiUser>,\n userStatusesById: Record<string, ApiUserStatus>,\n priorityIds?: string[],\n serverTimeOffset = 0,\n) {\n return orderBy(userIds, (id) => {\n const now = getServerTime(serverTimeOffset);\n\n if (priorityIds && priorityIds.includes(id)) {\n // Assuming that online status expiration date can't be as far as two days from now,\n // this should place prioritized on top of the list.\n // Then we subtract index of `id` in `priorityIds` to preserve selected order\n return now + (48 * 60 * 60) - (priorityIds.length - priorityIds.indexOf(id));\n }\n\n const user = usersById[id];\n const userStatus = userStatusesById[id];\n if (!user || !userStatus) {\n return 0;\n }\n\n if (userStatus.type === 'userStatusOnline') {\n return userStatus.expires;\n } else if (userStatus.type === 'userStatusOffline' && userStatus.wasOnline) {\n return userStatus.wasOnline;\n }\n\n switch (userStatus.type) {\n case 'userStatusRecently':\n return now - 60 * 60 * 24;\n case 'userStatusLastWeek':\n return now - 60 * 60 * 24 * 7;\n case 'userStatusLastMonth':\n return now - 60 * 60 * 24 * 7 * 30;\n default:\n return 0;\n }\n }, 'desc');\n}\n\nexport function filterUsersByName(\n userIds: string[],\n usersById: Record<string, ApiUser>,\n query?: string,\n currentUserId?: string,\n savedMessagesLang?: string,\n) {\n if (!query) {\n return userIds;\n }\n\n const searchWords = prepareSearchWordsForNeedle(query);\n\n return userIds.filter((id) => {\n const user = usersById[id];\n if (!user) {\n return false;\n }\n\n const name = id === currentUserId ? savedMessagesLang : getUserFullName(user);\n return (name && searchWords(name)) || searchWords(user.username);\n });\n}\n\nexport function getUserIdDividend(userId: string) {\n // Workaround for old-fashioned IDs stored locally\n if (typeof userId === 'number') {\n return Math.abs(userId);\n }\n\n return Math.abs(Number(userId));\n}\n\n// eslint-disable-next-line max-len\n// https://github.com/telegramdesktop/tdesktop/blob/371510cfe23b0bd226de8c076bc49248fbe40c26/Telegram/SourceFiles/data/data_peer.cpp#L53\nexport function getUserColorKey(peer: ApiUser | ApiChat | undefined) {\n const index = peer ? getUserIdDividend(peer.id) % 7 : 0;\n\n return USER_COLOR_KEYS[index];\n}\n","import { 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 { ApiAttachMenuPeerType, 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 selectAttachMenuPeerType(global: GlobalState, chatId: string) : ApiAttachMenuPeerType | undefined {\n const chat = selectChat(global, chatId);\n if (!chat) return undefined;\n\n const bot = selectBot(global, chatId);\n if (bot) {\n return 'bot';\n }\n\n const user = selectChatUser(global, chat);\n if (user) {\n return 'private';\n }\n\n if (isChatChannel(chat)) {\n return 'channel';\n }\n\n return 'chat';\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.openChatWithText?.chatId === chatId) {\n return global.openChatWithText.text;\n }\n return undefined;\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, switchBotInline } = global;\n return Boolean(switchBotInline || 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, isHidden }) => !isHidden && 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} from './teact';\nimport {\n hasElementChanged,\n isComponentElement,\n isTagElement,\n isParentElement,\n isTextElement,\n isEmptyElement,\n mountComponent,\n renderComponent,\n unmountComponent,\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 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) {\n $new = initComponent(parentEl, $new as VirtualElementComponent, $parent, index) as typeof $new;\n mountComponentChildren(parentEl, $new as VirtualElementComponent, { 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) {\n $new = initComponent(parentEl, $new as VirtualElementComponent, $parent, index) as typeof $new;\n remount(parentEl, $current, undefined);\n mountComponentChildren(parentEl, $new as VirtualElementComponent, { 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 if (isComponent) {\n ($new as VirtualElementComponent).children = renderChildren(\n $current,\n $new as VirtualElementComponent,\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 mountComponentChildren(parentEl: HTMLElement, $element: VirtualElementComponent, options: {\n nextSibling?: ChildNode;\n fragment?: DocumentFragment;\n}) {\n $element.children = $element.children.map(($child, i) => {\n return renderWithVirtual(parentEl, undefined, $child, $element, i, options);\n });\n}\n\nfunction unmountComponentChildren(parentEl: HTMLElement, $element: VirtualElementComponent) {\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 if (isComponentElement($current)) {\n unmountComponent($current.componentInstance);\n unmountComponentChildren(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\n if ($element.props.ref) {\n $element.props.ref.current = undefined; // Help GC\n }\n }\n\n if ($element.target) {\n $element.target = undefined; // Help GC\n }\n\n if (!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)) {\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 ($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;\n\n // eslint-disable-next-line no-null/no-null\n if (DEBUG && isParentElement($newChild) && (key === undefined || key === null)) {\n // eslint-disable-next-line no-console\n console.warn('Missing `key` in `teactFastList`');\n }\n\n return key;\n }),\n );\n\n // 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: VirtualElementParent, $new: VirtualElementParent, 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}\n\ninterface VirtualElementEmpty {\n type: VirtualElementTypesEnum.Empty;\n target?: Node;\n}\n\ninterface VirtualElementText {\n type: VirtualElementTypesEnum.Text;\n target?: Node;\n value: string;\n}\n\nexport interface VirtualElementTag {\n type: VirtualElementTypesEnum.Tag;\n target?: Node;\n tag: string;\n props: Props;\n children: VirtualElementChildren;\n}\n\nexport interface VirtualElementComponent {\n type: VirtualElementTypesEnum.Component;\n componentInstance: ComponentInstance;\n props: Props;\n children: VirtualElementChildren;\n}\n\nexport type StateHookSetter<T> = (newValue: ((current: T) => T) | T) => void;\n\ninterface ComponentInstance {\n $element: VirtualElementComponent;\n Component: FC;\n name: string;\n props: Props;\n renderedValue?: any;\n isMounted: boolean;\n hooks: {\n state: {\n cursor: number;\n byCursor: {\n value: any;\n nextValue: any;\n setter: StateHookSetter<any>;\n }[];\n };\n effects: {\n cursor: number;\n byCursor: {\n effect: () => void;\n dependencies?: 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;\nexport type VirtualElementParent =\n VirtualElementTag\n | VirtualElementComponent;\nexport type VirtualElementChildren = VirtualElement[];\nexport type VirtualElementReal = Exclude<VirtualElement, VirtualElementComponent>;\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 isParentElement($element: VirtualElement): $element is VirtualElementParent {\n return isTagElement($element) || isComponentElement($element);\n}\n\nfunction createElement(\n source: string | FC | typeof Fragment,\n props: Props,\n ...children: any[]\n): VirtualElementParent | VirtualElementChildren {\n if (!props) {\n props = {};\n }\n\n children = children.flat();\n\n if (source === Fragment) {\n return children;\n } else if (typeof source === 'function') {\n return createComponentInstance(source, props, children);\n } else {\n return buildTagElement(source, props, children);\n }\n}\n\nfunction createComponentInstance(Component: FC, props: Props, children: any[]): VirtualElementComponent {\n let parsedChildren: any | any[] | undefined;\n if (children.length === 0) {\n parsedChildren = undefined;\n } else if (children.length === 1) {\n [parsedChildren] = children;\n } else {\n parsedChildren = children;\n }\n\n const componentInstance: ComponentInstance = {\n $element: {} as VirtualElementComponent,\n Component,\n name: Component.name,\n props: {\n ...props,\n ...(parsedChildren && { children: parsedChildren }),\n },\n isMounted: false,\n hooks: {\n state: {\n cursor: 0,\n byCursor: [],\n },\n effects: {\n cursor: 0,\n byCursor: [],\n },\n memos: {\n cursor: 0,\n byCursor: [],\n },\n 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 const builtChildren = dropEmptyTail(children).map(buildChildElement);\n\n return {\n type: VirtualElementTypesEnum.Component,\n componentInstance,\n props: componentInstance.props,\n children: builtChildren.length ? builtChildren : [buildEmptyElement()],\n };\n}\n\nfunction buildTagElement(tag: string, props: Props, children: any[]): VirtualElementTag {\n return {\n type: VirtualElementTypesEnum.Tag,\n tag,\n props,\n children: dropEmptyTail(children).map(buildChildElement),\n };\n}\n\n// We only need placeholders in the middle of collection (to ensure other elements order).\nfunction dropEmptyTail(children: any[]) {\n let i = children.length - 1;\n\n for (; i >= 0; i--) {\n if (!isEmptyPlaceholder(children[i])) {\n break;\n }\n }\n\n return i + 1 < children.length ? children.slice(0, i + 1) : children;\n}\n\nfunction isEmptyPlaceholder(child: any) {\n // eslint-disable-next-line no-null/no-null\n return child === false || child === null || child === undefined;\n}\n\nfunction buildChildElement(child: any): VirtualElement {\n if (isEmptyPlaceholder(child)) {\n return buildEmptyElement();\n } else if (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 { ALL_FOLDER_ID, ARCHIVED_FOLDER_ID, DEBUG } 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\n return {\n id,\n type,\n isListed: Boolean(lastMessage && !isRestricted && !isNotJoined && !migratedTo),\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 can’t logout other sessions if less than 24 hours have passed since you logged on the current session',\n\n BOTS_TOO_MUCH: 'There are too many bots in this chat/channel',\n BOT_GROUPS_BLOCKED: 'This bot can\\'t be added to groups',\n USERS_TOO_MUCH: 'The maximum number of users has been exceeded',\n USER_CHANNELS_TOO_MUCH: 'One of the users you tried to add is already in too many channels/supergroups',\n USER_KICKED: 'This user was kicked from this supergroup/channel',\n USER_NOT_MUTUAL_CONTACT: 'The provided user is not a mutual contact',\n USER_PRIVACY_RESTRICTED: 'The user\\'s privacy settings do not allow you to do this',\n INVITE_HASH_EMPTY: 'The invite hash is empty',\n INVITE_HASH_EXPIRED: 'The invite link has expired',\n INVITE_HASH_INVALID: 'The invite hash is invalid',\n CHANNELS_TOO_MUCH: 'You have joined too many channels/supergroups',\n USER_ALREADY_PARTICIPANT: 'You already in the group',\n SCHEDULE_DATE_INVALID: 'Invalid schedule date provided',\n WALLPAPER_DIMENSIONS_INVALID: 'The wallpaper dimensions are invalid, please select another file',\n ADMINS_TOO_MUCH: 'There are too many admins',\n ADMIN_RANK_EMOJI_NOT_ALLOWED: 'An admin rank cannot contain emojis',\n ADMIN_RANK_INVALID: 'The specified admin rank is invalid',\n FRESH_CHANGE_ADMINS_FORBIDDEN: 'You were just elected admin, you can\\'t add or modify other admins yet',\n INPUT_USER_DEACTIVATED: 'The specified user was deleted',\n 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;\nconst PLURAL_RULES = {\n /* eslint-disable max-len */\n en: (n: number) => (n !== 1 ? 6 : 2),\n ar: (n: number) => (n === 0 ? 1 : n === 1 ? 2 : n === 2 ? 3 : n % 100 >= 3 && n % 100 <= 10 ? 4 : n % 100 >= 11 ? 5 : 6),\n ca: (n: number) => (n !== 1 ? 6 : 2),\n de: (n: number) => (n !== 1 ? 6 : 2),\n es: (n: number) => (n !== 1 ? 6 : 2),\n fa: (n: number) => (n > 1 ? 6 : 2),\n fr: (n: number) => (n > 1 ? 6 : 2),\n id: () => 0,\n it: (n: number) => (n !== 1 ? 6 : 2),\n ko: () => 0,\n ms: () => 0,\n nl: (n: number) => (n !== 1 ? 6 : 2),\n pl: (n: number) => (n === 1 ? 2 : n % 10 >= 2 && n % 10 <= 4 && (n % 100 < 10 || n % 100 >= 20) ? 4 : 5),\n pt_BR: (n: number) => (n > 1 ? 6 : 2),\n ru: (n: number) => (n % 10 === 1 && n % 100 !== 11 ? 2 : n % 10 >= 2 && n % 10 <= 4 && (n % 100 < 10 || n % 100 >= 20) ? 4 : 5),\n tr: (n: number) => (n > 1 ? 6 : 2),\n uk: (n: number) => (n % 10 === 1 && n % 100 !== 11 ? 2 : n % 10 >= 2 && n % 10 <= 4 && (n % 100 < 10 || n % 100 >= 20) ? 4 : 5),\n uz: (n: number) => (n > 1 ? 6 : 2),\n /* eslint-enable max-len */\n};\n\nconst cache = new Map<string, string>();\n\nlet langPack: ApiLangPack | undefined;\nlet fallbackLangPack: ApiLangPack | undefined;\n\nconst {\n addCallback,\n removeCallback,\n runCallbacks,\n} = createCallbackManager();\n\nexport { addCallback, removeCallback };\n\nlet currentLangCode: string | undefined;\nlet currentTimeFormat: TimeFormat | undefined;\n\nexport const getTranslation: LangFn = (key: string, value?: any, format?: 'i') => {\n if (value !== undefined) {\n const cacheValue = Array.isArray(value) ? JSON.stringify(value) : value;\n const cached = cache.get(`${key}_${cacheValue}_${format}`);\n if (cached) {\n return cached;\n }\n }\n\n if (!langPack && !fallbackLangPack) {\n return key;\n }\n\n const langString = (langPack?.[key]) || (fallbackLangPack?.[key]);\n if (!langString) {\n if (!fallbackLangPack) {\n void importFallbackLangPack();\n }\n\n return key;\n }\n\n return processTranslation(langString, key, value, format);\n};\n\nexport async function getTranslationForLangString(langCode: string, key: string) {\n let translateString: ApiLangString | undefined = await cacheApi.fetch(\n LANG_CACHE_NAME,\n `${DEFAULT_LANG_PACK}_${langCode}_${key}`,\n cacheApi.Type.Json,\n );\n\n if (!translateString) {\n translateString = await fetchRemoteString(DEFAULT_LANG_PACK, langCode, key);\n }\n\n return processTranslation(translateString, key);\n}\n\nexport async function setLanguage(langCode: LangCode, callback?: NoneToVoidFunction, withFallback = false) {\n if (langPack && langCode === currentLangCode) {\n if (callback) {\n callback();\n }\n\n return;\n }\n\n let newLangPack = await cacheApi.fetch(LANG_CACHE_NAME, langCode, cacheApi.Type.Json);\n if (!newLangPack) {\n if (withFallback) {\n await importFallbackLangPack();\n }\n\n newLangPack = await fetchRemote(langCode);\n if (!newLangPack) {\n return;\n }\n }\n\n cache.clear();\n\n currentLangCode = langCode;\n langPack = newLangPack;\n document.documentElement.lang = langCode;\n\n const { languages, timeFormat } = getGlobal().settings.byKey;\n const langInfo = languages?.find((l) => l.langCode === langCode);\n getTranslation.isRtl = Boolean(langInfo?.rtl);\n getTranslation.code = langCode;\n getTranslation.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\":\"0796e416b8e4205b6bf5\",\"1627\":\"c1c005ef2bed8d1b9561\",\"1641\":\"d99075923e2b8c9e5f72\",\"1699\":\"258d1e759822ec152b75\",\"1752\":\"272d78459ec80c5b3dba\",\"1879\":\"60ac065c7d88c4f46b54\",\"1915\":\"c5b3f01035517153521f\",\"1917\":\"2928ac2003a7061dc059\",\"1933\":\"b2033cfa79d272a8fe62\",\"1954\":\"d569fdd7ba86d9776a5c\",\"1967\":\"3cec93c3a4dcd79e0488\",\"1989\":\"834f949acc5977e509ff\",\"2001\":\"8c68420c13854bbc24fe\",\"2002\":\"8481843cd3d445486865\",\"2054\":\"9c1890f62ccae40eeec2\",\"2098\":\"890557cbbc0c46a9f08f\",\"2137\":\"3af5405dff8273180346\",\"2138\":\"fbfb10a62455b7b043b7\",\"2243\":\"f82c54d3a849d4a487b4\",\"2251\":\"2bf10b1f578543d75e54\",\"2342\":\"f8d4331788cc89a2b694\",\"2369\":\"d952921438994721f7d0\",\"2390\":\"d7ecc2f228aef9b009e4\",\"2537\":\"94c17bfafc8acf1a9cd2\",\"2690\":\"4d73e3084ae3a2a6f64c\",\"2741\":\"9f3aba6b2cd0b453f9a5\",\"2767\":\"2121cd909c7aa572c7fd\",\"2853\":\"c4ae910d407f42b72912\",\"2892\":\"b8b8cd5c2b1df51e3492\",\"2993\":\"170c842b0634392ba2d1\",\"3041\":\"cee99fa771a138a9b3a8\",\"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\":\"408ec342d58a3508516f\",\"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\":\"4c9628f9719b8f99bdfc\",\"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\":\"14db86bdb3fa2f2f5a72\",\"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\":\"c16f7302196aa916c103\",\"7963\":\"8b010994867f46020df9\",\"8063\":\"627d5ae10e2e502e9e38\",\"8090\":\"31460a17f3f5829c1290\",\"8138\":\"9b29a768a035996247bd\",\"8208\":\"9a2d0eeec5f8bb07cdd3\",\"8294\":\"12b38bd567e102c27c8e\",\"8369\":\"c6ae120b122d07384b7d\",\"8401\":\"a8ba266b7a79ef7dfe1d\",\"8435\":\"5f667e46d196564970b9\",\"8505\":\"f588195fa145445de93b\",\"8530\":\"a4d7f28c015d01eaf776\",\"8663\":\"3215036b0069a8dcc16e\",\"8688\":\"5e6f5f3c14f691c0367c\",\"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\":\"57ec7e06ca8e8e86d23c\",\"9970\":\"253d98d0960ae30de3ea\"}[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\":\"cee99fa771a138a9b3a8\",\"3472\":\"615d222fdc0dcfa591d8\",\"3779\":\"408ec342d58a3508516f\",\"5769\":\"14db86bdb3fa2f2f5a72\",\"8688\":\"5e6f5f3c14f691c0367c\",\"8878\":\"a7b117d54d54258e5f26\",\"9954\":\"57ec7e06ca8e8e86d23c\"}[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 const manifest = document.getElementById('the-manifest-placeholder');\n if (!manifest) {\n return;\n }\n\n const url = `site${IS_MAC_OS ? '_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","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","trim","renderGroupCallContent","invoice","getMessageSummaryText","messageSummary","renderMessageSummary","trimText","getUserFullName","renderText","chat","getChatTitle","placeholder","replaceValue","placeholderPosition","substring","Array","isArray","forEach","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","part","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","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","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","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","noStatus","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","selectAttachMenuPeerType","selectBot","selectIsChatBotNotStarted","messageInfo","selectAreActiveChatsLoaded","active","selectIsChatListed","targetList","list","selectChatFolder","selectIsChatPinned","archived","chatFoldersById","selectChatByUsername","usernameLowered","selectIsServiceChatReady","selectSendAs","sendAsId","selectRequestedText","openChatWithText","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","notification","findAfterLastReadId","isFromScheduled","found","selectIsForwardModalOpen","switchBotInline","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","isHidden","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","hasElementChanged","updateComponent","componentInstance","isMounted","setupComponentUpdateListener","newTarget","mountComponentChildren","initComponent","createNode","insertBefore","remount","getNextSibling","renderChildren","$currentAsReal","isTagElement","$newAsTag","updateAttributes","$element","mountComponent","$firstChild","renderComponent","$child","isEmptyElement","createTextNode","isTextElement","tag","processControlled","defaultChecked","processUncontrolledOnMount","componentNextSibling","unmountComponent","unmountComponentChildren","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","createComponentInstance","buildTagElement","parsedChildren","hooks","cursor","byCursor","effects","memos","refs","buildComponentElement","builtChildren","dropEmptyTail","buildChildElement","buildEmptyElement","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","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","ca","de","es","fa","fr","it","ko","nl","pl","pt_BR","ru","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":""} |