mirror of
https://github.com/danog/telegram-tt.git
synced 2024-12-15 10:47:04 +01:00
1 line
1020 KiB
Plaintext
1 line
1020 KiB
Plaintext
{"version":3,"file":"325.53d45e666a3e8d50e525.js","mappings":"qNAoDO,SAASA,EAAqBC,GACnC,MAAM,OAAEC,EAAF,SAAUC,IAAaC,EAAAA,EAAAA,IAAyBH,IAAW,GACjE,OAAKC,GAAWC,GAIhBF,GAASI,EAAAA,EAAAA,IAAsBJ,EAAQC,EAAQC,GAAU,GACzDF,GAASK,EAAAA,EAAAA,IAA8BL,EAAQC,EAAQC,OAAUI,IAJxDN,GA3CXO,EAAAA,EAAAA,IAAW,uBAAwBP,IACjC,MAAM,OAAEC,EAAF,SAAUC,IAAaC,EAAAA,EAAAA,IAAyBH,IAAW,GACjE,GAAKC,GAAWC,EAIhB,OAAOE,EAAAA,EAAAA,IAAsBJ,EAAQC,EAAQC,GAAU,OAGzDK,EAAAA,EAAAA,IAAW,uBAAwBR,IAEnCQ,EAAAA,EAAAA,IAAW,2BAA2B,CAACP,EAAQQ,EAASC,KACtD,MAAM,OAAER,EAAF,SAAUC,IAAaC,EAAAA,EAAAA,IAAyBH,IAAW,GACjE,IAAKC,IAAWC,EACd,OAGF,MAAM,MAAEQ,GAAUD,EACZE,GAAgBC,EAAAA,EAAAA,IAAmBX,EAAQC,IACzCQ,MAAOG,GAAiBb,EAAOc,gBAAgBC,gBAAgBJ,IAAkB,GAQzF,OANID,IAAUG,IACZb,GAASK,EAAAA,EAAAA,IAA8BL,EAAQC,EAAQC,EAAUc,EAAAA,KAG1DZ,EAAAA,EAAAA,IAAsBJ,EAAQC,EAAQC,GAAU,EAAMQ,OAKjEH,EAAAA,EAAAA,IAAW,2BAA2B,CAACP,EAAQQ,EAASC,KACtD,MAAM,OAAER,IAAWE,EAAAA,EAAAA,IAAyBH,IAAW,GACvD,IAAKC,EACH,OAGF,MAAM,UAAEgB,GAAcR,EACtB,OAAOS,EAAAA,EAAAA,IAA2BlB,EAAQC,EAAQg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AAD,MACA,mBAAC,GAAD,MACA,mBAAC,GAAD,CAAazgE,OAAQy+D,IACrB,mBAAC,GAAD,CAAez+D,OAAQ2+D,IACvB,mBAAC,GAAD,CAAe3+D,OAAQ6+D,IACvB,mBAAC,GAAD,CAAS7+D,OAAQ8+D,IAChBxiD,GAAgB,mBAAC,GAAD,CAAa7qC,IAAK6qC,EAAax4C,GAAImG,QAASqyC,EAAc90C,OAAQu3F,EAAa5kD,MAAI,IACpG,mBAAC,GAAD,CAAehqC,IAAKC,IACpB,mBAAC,GAAD,CAAiB4vB,OAAQg/D,IACzB,mBAAC,KAAD,CACEh/D,OAAQh6B,QAAQshB,GAChB+hB,QAASm3D,EACTtuF,oBAAqBoV,IAEvB,mBAACw5E,GAAD,WC7QFp2E,EAAAA,IAEFC,QAAQC,IAAI,gCAGTxiB,EAAAA,EAAAA,MAAYohC,kBACfp4B,EAAAA,EAAAA,MAAc2vF,W","sources":["webpack://telegram-t/./src/modules/actions/ui/localSearch.ts","webpack://telegram-t/./src/modules/actions/ui/chats.ts","webpack://telegram-t/./src/modules/actions/ui/messages.ts","webpack://telegram-t/./src/versionNotification.txt","webpack://telegram-t/./src/modules/actions/ui/globalSearch.ts","webpack://telegram-t/./src/modules/actions/ui/stickerSearch.ts","webpack://telegram-t/./src/modules/actions/ui/users.ts","webpack://telegram-t/./src/modules/actions/ui/misc.ts","webpack://telegram-t/./src/modules/actions/ui/payments.ts","webpack://telegram-t/./src/util/deeplink.ts","webpack://telegram-t/./src/modules/actions/api/chats.ts","webpack://telegram-t/./src/modules/actions/api/messages.ts","webpack://telegram-t/./src/modules/actions/api/symbols.ts","webpack://telegram-t/./src/modules/actions/api/globalSearch.ts","webpack://telegram-t/./src/modules/actions/api/localSearch.ts","webpack://telegram-t/./src/modules/actions/api/management.ts","webpack://telegram-t/./src/modules/actions/api/sync.ts","webpack://telegram-t/./src/modules/actions/api/users.ts","webpack://telegram-t/./src/modules/reducers/bots.ts","webpack://telegram-t/./src/modules/actions/api/bots.ts","webpack://telegram-t/./src/modules/actions/api/twoFaSettings.ts","webpack://telegram-t/./src/modules/actions/api/payments.ts","webpack://telegram-t/./src/util/requestQuery.ts","webpack://telegram-t/./src/modules/actions/apiUpdaters/chats.ts","webpack://telegram-t/./src/modules/actions/apiUpdaters/messages.ts","webpack://telegram-t/./src/modules/actions/apiUpdaters/users.ts","webpack://telegram-t/./src/modules/actions/apiUpdaters/symbols.ts","webpack://telegram-t/./src/modules/actions/apiUpdaters/misc.ts","webpack://telegram-t/./src/modules/actions/apiUpdaters/settings.ts","webpack://telegram-t/./src/modules/actions/apiUpdaters/twoFaSettings.ts","webpack://telegram-t/./src/hooks/useBeforeUnload.ts","webpack://telegram-t/./src/hooks/usePreventPinchZoomGesture.ts","webpack://telegram-t/./src/hooks/useBrowserOnline.ts","webpack://telegram-t/./src/components/left/main/LeftMainHeader.tsx","webpack://telegram-t/./src/components/left/ConnectionState.tsx","webpack://telegram-t/./src/components/left/main/ChatFolders.tsx","webpack://telegram-t/./src/hooks/useThrottledMemo.ts","webpack://telegram-t/./src/hooks/useThrottle.ts","webpack://telegram-t/./src/components/left/search/LeftSearch.async.tsx","webpack://telegram-t/./src/components/left/main/ContactList.async.tsx","webpack://telegram-t/./src/components/left/NewChatButton.tsx","webpack://telegram-t/./src/components/left/main/LeftMain.tsx","webpack://telegram-t/./src/components/left/settings/Settings.async.tsx","webpack://telegram-t/./src/components/left/newChat/NewChat.async.tsx","webpack://telegram-t/./src/components/left/ArchivedChats.async.tsx","webpack://telegram-t/./src/components/left/LeftColumn.tsx","webpack://telegram-t/./src/hooks/useResize.ts","webpack://telegram-t/./src/hooks/useWindowSize.ts","webpack://telegram-t/./src/components/middle/helpers/calculateMiddleFooterTransforms.ts","webpack://telegram-t/./src/components/middle/HeaderMenuContainer.async.tsx","webpack://telegram-t/./src/components/middle/HeaderActions.tsx","webpack://telegram-t/./src/hooks/useWebpThumbnail.ts","webpack://telegram-t/./src/components/middle/PinnedMessageNavigation.tsx","webpack://telegram-t/./src/components/middle/HeaderPinnedMessage.tsx","webpack://telegram-t/./src/util/imageResize.ts","webpack://telegram-t/./src/hooks/useMessageMediaMetadata.ts","webpack://telegram-t/./src/hooks/useAsync.ts","webpack://telegram-t/./src/components/middle/AudioPlayer.tsx","webpack://telegram-t/./src/components/middle/MiddleHeader.tsx","webpack://telegram-t/./src/components/middle/helpers/groupMessages.ts","webpack://telegram-t/./src/components/middle/hooks/useMessageObservers.ts","webpack://telegram-t/./src/components/middle/message/helpers/buildContentClassName.ts","webpack://telegram-t/./src/components/middle/message/helpers/mediaDimensions.ts","webpack://telegram-t/./src/components/middle/message/helpers/calculateAlbumLayout.ts","webpack://telegram-t/./src/components/middle/message/helpers/calculateAuthorWidth.ts","webpack://telegram-t/./src/components/middle/message/hooks/useFocusMessage.ts","webpack://telegram-t/./src/components/middle/message/ContextMenuContainer.async.tsx","webpack://telegram-t/./src/components/middle/ActionMessage.tsx","webpack://telegram-t/./src/components/common/EmbeddedMessage.tsx","webpack://telegram-t/./src/components/middle/message/MessageMeta.tsx","webpack://telegram-t/./src/components/middle/message/Sticker.tsx","webpack://telegram-t/./src/components/middle/message/hooks/useBlurredMediaThumbRef.ts","webpack://telegram-t/./src/components/middle/message/helpers/getCustomAppendixBg.ts","webpack://telegram-t/./src/components/middle/message/Photo.tsx","webpack://telegram-t/./src/hooks/useHeavyAnimationCheckForVideo.ts","webpack://telegram-t/./src/components/middle/message/hooks/usePauseOnInactive.ts","webpack://telegram-t/./src/components/middle/message/Video.tsx","webpack://telegram-t/./src/components/middle/message/Contact.tsx","webpack://telegram-t/./src/components/middle/message/PollOption.tsx","webpack://telegram-t/./src/components/middle/message/Poll.tsx","webpack://telegram-t/./src/components/middle/message/WebPage.tsx","webpack://telegram-t/./src/components/middle/message/Invoice.tsx","webpack://telegram-t/./src/components/middle/message/hocs/withSelectControl.tsx","webpack://telegram-t/./src/components/middle/message/Album.tsx","webpack://telegram-t/./src/components/middle/message/RoundVideo.tsx","webpack://telegram-t/./src/components/middle/message/InlineButtons.tsx","webpack://telegram-t/./src/components/middle/message/CommentButton.tsx","webpack://telegram-t/./src/components/middle/message/Message.tsx","webpack://telegram-t/./src/components/middle/message/hooks/useOuterHandlers.ts","webpack://telegram-t/./src/components/middle/message/hooks/useInnerHandlers.ts","webpack://telegram-t/./src/components/middle/MessageListContent.tsx","webpack://telegram-t/./src/components/middle/hooks/useScrollHooks.ts","webpack://telegram-t/./src/components/middle/ContactGreeting.tsx","webpack://telegram-t/./src/components/middle/NoMessages.tsx","webpack://telegram-t/./src/components/middle/MessageList.tsx","webpack://telegram-t/./src/components/middle/hooks/useStickyDates.ts","webpack://telegram-t/./src/components/middle/ScrollDownButton.tsx","webpack://telegram-t/./src/components/middle/composer/helpers/buildAttachment.ts","webpack://telegram-t/./src/components/middle/composer/helpers/applyIosAutoCapitalizationFix.ts","webpack://telegram-t/./node_modules/opus-recorder/dist/encoderWorker.min.js","webpack://telegram-t/./src/util/voiceRecording.ts","webpack://telegram-t/./src/components/middle/composer/hooks/useVoiceRecording.ts","webpack://telegram-t/./src/components/middle/composer/hooks/useClipboardPaste.ts","webpack://telegram-t/./src/components/middle/composer/helpers/getMessageTextAsHtml.ts","webpack://telegram-t/./src/components/middle/composer/hooks/useDraft.ts","webpack://telegram-t/./src/components/middle/composer/hooks/useInlineBotTooltip.ts","webpack://telegram-t/./src/components/middle/composer/hooks/useBotCommandTooltip.ts","webpack://telegram-t/./src/components/common/DeleteMessageModal.async.tsx","webpack://telegram-t/./src/components/ui/ResponsiveHoverButton.tsx","webpack://telegram-t/./src/components/middle/composer/AttachMenu.async.tsx","webpack://telegram-t/./src/components/middle/composer/SymbolMenu.async.tsx","webpack://telegram-t/./src/components/middle/composer/InlineBotTooltip.async.tsx","webpack://telegram-t/./src/components/middle/composer/MentionTooltip.async.tsx","webpack://telegram-t/./src/components/middle/composer/CustomSendMenu.async.tsx","webpack://telegram-t/./src/components/middle/composer/StickerTooltip.async.tsx","webpack://telegram-t/./src/components/middle/composer/BotCommandTooltip.async.tsx","webpack://telegram-t/./src/components/middle/composer/BotKeyboardMenu.tsx","webpack://telegram-t/./src/components/middle/composer/ComposerEmbeddedMessage.tsx","webpack://telegram-t/./src/components/middle/composer/AttachmentModal.async.tsx","webpack://telegram-t/./src/components/middle/composer/BotCommandMenu.async.tsx","webpack://telegram-t/./src/components/middle/composer/PollModal.async.tsx","webpack://telegram-t/./src/components/middle/composer/DropArea.async.tsx","webpack://telegram-t/./src/components/middle/composer/WebPagePreview.tsx","webpack://telegram-t/./src/components/common/CalendarModal.async.tsx","webpack://telegram-t/./src/components/middle/composer/Composer.tsx","webpack://telegram-t/./src/components/middle/composer/hooks/useStickerTooltip.ts","webpack://telegram-t/./src/util/insertHtmlInSelection.ts","webpack://telegram-t/./src/util/deleteLastCharacterOutsideSelection.ts","webpack://telegram-t/./src/components/middle/composer/hooks/useEditing.ts","webpack://telegram-t/./src/components/middle/MobileSearch.async.tsx","webpack://telegram-t/./src/components/middle/MessageSelectToolbar.async.tsx","webpack://telegram-t/./src/components/common/UnpinAllMessagesModal.async.tsx","webpack://telegram-t/./src/components/payment/PaymentModal.async.tsx","webpack://telegram-t/./src/components/payment/ReceiptModal.async.tsx","webpack://telegram-t/./src/components/middle/MiddleColumn.tsx","webpack://telegram-t/./src/hooks/useCustomBackground.ts","webpack://telegram-t/./src/components/right/RightHeader.tsx","webpack://telegram-t/./src/components/right/hooks/useProfileViewportIds.ts","webpack://telegram-t/./src/components/right/hooks/useProfileState.ts","webpack://telegram-t/./src/components/right/DeleteMemberModal.tsx","webpack://telegram-t/./src/components/right/Profile.tsx","webpack://telegram-t/./src/components/right/hooks/useTransitionFixes.ts","webpack://telegram-t/./src/hooks/useCacheBuster.ts","webpack://telegram-t/./src/components/right/RightSearch.async.tsx","webpack://telegram-t/./src/components/right/management/Management.async.tsx","webpack://telegram-t/./src/components/right/StickerSearch.async.tsx","webpack://telegram-t/./src/components/right/GifSearch.async.tsx","webpack://telegram-t/./src/components/right/PollResults.async.tsx","webpack://telegram-t/./src/components/right/AddChatMembers.tsx","webpack://telegram-t/./src/components/right/RightColumn.tsx","webpack://telegram-t/./src/components/mediaViewer/MediaViewer.async.tsx","webpack://telegram-t/./src/util/download.ts","webpack://telegram-t/./src/components/main/DownloadManager.tsx","webpack://telegram-t/./src/components/main/Notifications.async.tsx","webpack://telegram-t/./src/components/main/Dialogs.async.tsx","webpack://telegram-t/./src/components/main/ForwardPicker.async.tsx","webpack://telegram-t/./src/components/main/SafeLinkModal.async.tsx","webpack://telegram-t/./src/components/main/HistoryCalendar.async.tsx","webpack://telegram-t/./src/components/main/Main.tsx","webpack://telegram-t/./src/bundles/main.ts"],"sourcesContent":["import { addReducer } from '../../../lib/teact/teactn';\n\nimport {\n updateLocalTextSearch,\n replaceLocalTextSearchResults,\n updateLocalMediaSearchType,\n} from '../../reducers';\nimport { MEMO_EMPTY_ARRAY } from '../../../util/memo';\nimport { selectCurrentMessageList } from '../../selectors';\nimport { buildChatThreadKey } from '../../helpers';\nimport { GlobalState } from '../../../global/types';\n\naddReducer('openLocalTextSearch', (global) => {\n const { chatId, threadId } = selectCurrentMessageList(global) || {};\n if (!chatId || !threadId) {\n return undefined;\n }\n\n return updateLocalTextSearch(global, chatId, threadId, true);\n});\n\naddReducer('closeLocalTextSearch', closeLocalTextSearch);\n\naddReducer('setLocalTextSearchQuery', (global, actions, payload) => {\n const { chatId, threadId } = selectCurrentMessageList(global) || {};\n if (!chatId || !threadId) {\n return undefined;\n }\n\n const { query } = payload!;\n const chatThreadKey = buildChatThreadKey(chatId, threadId);\n const { query: currentQuery } = global.localTextSearch.byChatThreadKey[chatThreadKey] || {};\n\n if (query !== currentQuery) {\n global = replaceLocalTextSearchResults(global, chatId, threadId, MEMO_EMPTY_ARRAY);\n }\n\n global = updateLocalTextSearch(global, chatId, threadId, true, query);\n\n return global;\n});\n\naddReducer('setLocalMediaSearchType', (global, actions, payload) => {\n const { chatId } = selectCurrentMessageList(global) || {};\n if (!chatId) {\n return undefined;\n }\n\n const { mediaType } = payload!;\n return updateLocalMediaSearchType(global, chatId, mediaType);\n});\n\nexport function closeLocalTextSearch(global: GlobalState): GlobalState {\n const { chatId, threadId } = selectCurrentMessageList(global) || {};\n if (!chatId || !threadId) {\n return global;\n }\n\n global = updateLocalTextSearch(global, chatId, threadId, false);\n global = replaceLocalTextSearchResults(global, chatId, threadId, undefined);\n return global;\n}\n","import { addReducer, setGlobal } from '../../../lib/teact/teactn';\n\nimport {\n exitMessageSelectMode, replaceThreadParam, updateCurrentMessageList,\n} from '../../reducers';\nimport { selectCurrentMessageList } from '../../selectors';\nimport { closeLocalTextSearch } from './localSearch';\n\naddReducer('openChat', (global, actions, payload) => {\n const {\n id, threadId = -1, type = 'thread', shouldReplaceHistory = false,\n } = payload!;\n\n const currentMessageList = selectCurrentMessageList(global);\n\n if (!currentMessageList\n || (\n currentMessageList.chatId !== id\n || currentMessageList.threadId !== threadId\n || currentMessageList.type !== type\n )) {\n global = replaceThreadParam(global, id, threadId, 'replyStack', []);\n global = exitMessageSelectMode(global);\n global = closeLocalTextSearch(global);\n\n global = {\n ...global,\n messages: {\n ...global.messages,\n contentToBeScheduled: undefined,\n },\n ...(id !== global.forwardMessages.toChatId && {\n forwardMessages: {},\n }),\n };\n\n setGlobal(global);\n }\n\n return updateCurrentMessageList(global, id, threadId, type, shouldReplaceHistory);\n});\n\naddReducer('openPreviousChat', (global) => {\n return updateCurrentMessageList(global, undefined);\n});\n\naddReducer('openChatWithInfo', (global, actions, payload) => {\n setGlobal({\n ...global,\n isChatInfoShown: true,\n });\n\n actions.openChat(payload);\n});\n\naddReducer('resetChatCreation', (global) => {\n return {\n ...global,\n chatCreation: undefined,\n };\n});\n\naddReducer('setNewChatMembersDialogState', (global, actions, payload) => {\n return {\n ...global,\n newChatMembersProgress: payload,\n };\n});\n\naddReducer('openNextChat', (global, actions, payload) => {\n const { targetIndexDelta, orderedIds } = payload;\n\n const { chatId } = selectCurrentMessageList(global) || {};\n\n if (!chatId) {\n actions.openChat({ id: orderedIds[0] });\n return;\n }\n\n const position = orderedIds.indexOf(chatId);\n\n if (position === -1) {\n return;\n }\n const nextId = orderedIds[position + targetIndexDelta];\n\n actions.openChat({ id: nextId, shouldReplaceHistory: true });\n});\n","import { addReducer, getGlobal, setGlobal } from '../../../lib/teact/teactn';\n\nimport { ApiMessage, MAIN_THREAD_ID } from '../../../api/types';\nimport { FocusDirection } from '../../../types';\n\nimport {\n ANIMATION_END_DELAY,\n APP_VERSION,\n FAST_SMOOTH_MAX_DURATION,\n SERVICE_NOTIFICATIONS_USER_ID,\n} from '../../../config';\nimport { IS_TOUCH_ENV } from '../../../util/environment';\nimport {\n enterMessageSelectMode,\n toggleMessageSelection,\n exitMessageSelectMode,\n replaceThreadParam,\n updateFocusDirection,\n updateFocusedMessage,\n} from '../../reducers';\nimport {\n selectCurrentChat,\n selectViewportIds,\n selectIsRightColumnShown,\n selectCurrentMessageList,\n selectChat,\n selectThreadInfo,\n selectChatMessages,\n selectAllowedMessageActions,\n selectMessageIdsByGroupId,\n selectForwardedMessageIdsByGroupId,\n selectIsViewportNewest,\n selectReplyingToId,\n selectReplyStack,\n} from '../../selectors';\nimport { findLast } from '../../../util/iteratees';\nimport { getServerTime } from '../../../util/serverTime';\n\n// @ts-ignore\nimport versionNotification from '../../../versionNotification.txt';\nimport parseMessageInput from '../../../util/parseMessageInput';\n\nconst FOCUS_DURATION = 1500;\nconst FOCUS_NO_HIGHLIGHT_DURATION = FAST_SMOOTH_MAX_DURATION + ANIMATION_END_DELAY;\nconst POLL_RESULT_OPEN_DELAY_MS = 450;\nconst SERVICE_NOTIFICATIONS_MAX_AMOUNT = 1e3;\n\nlet blurTimeout: number | undefined;\n\naddReducer('setScrollOffset', (global, actions, payload) => {\n const { chatId, threadId, scrollOffset } = payload!;\n\n return replaceThreadParam(global, chatId, threadId, 'scrollOffset', scrollOffset);\n});\n\naddReducer('setReplyingToId', (global, actions, payload) => {\n const { messageId } = payload!;\n const currentMessageList = selectCurrentMessageList(global);\n if (!currentMessageList) {\n return undefined;\n }\n const { chatId, threadId } = currentMessageList;\n\n return replaceThreadParam(global, chatId, threadId, 'replyingToId', messageId);\n});\n\naddReducer('setEditingId', (global, actions, payload) => {\n const { messageId } = payload!;\n const currentMessageList = selectCurrentMessageList(global);\n if (!currentMessageList) {\n return undefined;\n }\n\n const { chatId, threadId, type } = currentMessageList;\n const paramName = type === 'scheduled' ? 'editingScheduledId' : 'editingId';\n\n return replaceThreadParam(global, chatId, threadId, paramName, messageId);\n});\n\naddReducer('editLastMessage', (global) => {\n const { chatId, threadId } = selectCurrentMessageList(global) || {};\n if (!chatId || !threadId) {\n return undefined;\n }\n\n const chatMessages = selectChatMessages(global, chatId);\n const viewportIds = selectViewportIds(global, chatId, threadId);\n if (!chatMessages || !viewportIds) {\n return undefined;\n }\n\n const lastOwnEditableMessageId = findLast(viewportIds, (id) => {\n return Boolean(chatMessages[id] && selectAllowedMessageActions(global, chatMessages[id], threadId).canEdit);\n });\n\n if (!lastOwnEditableMessageId) {\n return undefined;\n }\n\n return replaceThreadParam(global, chatId, threadId, 'editingId', lastOwnEditableMessageId);\n});\n\naddReducer('replyToNextMessage', (global, actions, payload) => {\n const { targetIndexDelta } = payload;\n const { chatId, threadId } = selectCurrentMessageList(global) || {};\n if (!chatId || !threadId) {\n return;\n }\n\n const chatMessages = selectChatMessages(global, chatId);\n const viewportIds = selectViewportIds(global, chatId, threadId);\n if (!chatMessages || !viewportIds) {\n return;\n }\n\n const replyingToId = selectReplyingToId(global, chatId, threadId);\n const isLatest = selectIsViewportNewest(global, chatId, threadId);\n\n let messageId: number | undefined;\n\n if (!isLatest || !replyingToId) {\n if (threadId === MAIN_THREAD_ID) {\n const chat = selectChat(global, chatId);\n\n messageId = chat?.lastMessage?.id;\n } else {\n const threadInfo = selectThreadInfo(global, chatId, threadId);\n\n messageId = threadInfo?.lastMessageId;\n }\n } else {\n const chatMessageKeys = Object.keys(chatMessages);\n const indexOfCurrent = chatMessageKeys.indexOf(replyingToId.toString());\n const newIndex = indexOfCurrent + targetIndexDelta;\n messageId = newIndex <= chatMessageKeys.length + 1 && newIndex >= 0\n ? Number(chatMessageKeys[newIndex])\n : undefined;\n }\n actions.setReplyingToId({ messageId });\n actions.focusMessage({\n chatId, threadId, messageId,\n });\n});\n\naddReducer('openMediaViewer', (global, actions, payload) => {\n const {\n chatId, threadId, messageId, avatarOwnerId, profilePhotoIndex, origin,\n } = payload!;\n\n return {\n ...global,\n mediaViewer: {\n chatId,\n threadId,\n messageId,\n avatarOwnerId,\n profilePhotoIndex,\n origin,\n },\n forwardMessages: {},\n };\n});\n\naddReducer('closeMediaViewer', (global) => {\n return {\n ...global,\n mediaViewer: {},\n };\n});\n\naddReducer('openAudioPlayer', (global, actions, payload) => {\n const {\n chatId, threadId, messageId, origin, volume, playbackRate, isMuted,\n } = payload!;\n\n return {\n ...global,\n audioPlayer: {\n chatId,\n threadId,\n messageId,\n origin,\n volume: volume || global.audioPlayer.volume,\n playbackRate: playbackRate || global.audioPlayer.playbackRate,\n isMuted: isMuted || global.audioPlayer.isMuted,\n },\n };\n});\n\naddReducer('setAudioPlayerVolume', (global, actions, payload) => {\n const {\n volume,\n } = payload!;\n\n return {\n ...global,\n audioPlayer: {\n ...global.audioPlayer,\n volume,\n },\n };\n});\n\naddReducer('setAudioPlayerPlaybackRate', (global, actions, payload) => {\n const {\n playbackRate,\n } = payload!;\n\n return {\n ...global,\n audioPlayer: {\n ...global.audioPlayer,\n playbackRate,\n },\n };\n});\n\naddReducer('setAudioPlayerMuted', (global, actions, payload) => {\n const {\n isMuted,\n } = payload!;\n\n return {\n ...global,\n audioPlayer: {\n ...global.audioPlayer,\n isMuted,\n },\n };\n});\n\naddReducer('closeAudioPlayer', (global) => {\n return {\n ...global,\n audioPlayer: {\n volume: global.audioPlayer.volume,\n playbackRate: global.audioPlayer.playbackRate,\n isMuted: global.audioPlayer.isMuted,\n },\n };\n});\n\naddReducer('openPollResults', (global, actions, payload) => {\n const { chatId, messageId } = payload!;\n\n const shouldOpenInstantly = selectIsRightColumnShown(global);\n\n if (!shouldOpenInstantly) {\n window.setTimeout(() => {\n const newGlobal = getGlobal();\n\n setGlobal({\n ...newGlobal,\n pollResults: {\n chatId,\n messageId,\n voters: {},\n },\n });\n }, POLL_RESULT_OPEN_DELAY_MS);\n } else if (chatId !== global.pollResults.chatId || messageId !== global.pollResults.messageId) {\n setGlobal({\n ...global,\n pollResults: {\n chatId,\n messageId,\n voters: {},\n },\n });\n }\n});\n\naddReducer('closePollResults', (global) => {\n setGlobal({\n ...global,\n pollResults: {},\n });\n});\n\naddReducer('focusLastMessage', (global, actions) => {\n const currentMessageList = selectCurrentMessageList(global);\n if (!currentMessageList) {\n return;\n }\n\n const { chatId, threadId } = currentMessageList;\n\n let lastMessageId: number | undefined;\n if (threadId === MAIN_THREAD_ID) {\n const chat = selectChat(global, chatId);\n\n lastMessageId = chat?.lastMessage?.id;\n } else {\n const threadInfo = selectThreadInfo(global, chatId, threadId);\n\n lastMessageId = threadInfo?.lastMessageId;\n }\n\n if (!lastMessageId) {\n return;\n }\n\n actions.focusMessage({\n chatId, threadId, messageId: lastMessageId, noHighlight: true,\n });\n});\n\naddReducer('focusNextReply', (global, actions) => {\n const currentMessageList = selectCurrentMessageList(global);\n if (!currentMessageList) {\n return undefined;\n }\n\n const { chatId, threadId } = currentMessageList;\n\n const replyStack = selectReplyStack(global, chatId, threadId);\n\n if (!replyStack || replyStack.length === 0) {\n actions.focusLastMessage();\n } else {\n const messageId = replyStack.pop();\n\n global = replaceThreadParam(global, chatId, threadId, 'replyStack', [...replyStack]);\n\n setGlobal(global);\n\n actions.focusMessage({\n chatId,\n threadId,\n messageId,\n });\n }\n\n return undefined;\n});\n\naddReducer('focusMessage', (global, actions, payload) => {\n const {\n chatId, threadId = MAIN_THREAD_ID, messageListType = 'thread', noHighlight, groupedId, groupedChatId,\n replyMessageId, isResizingContainer,\n } = payload!;\n\n let { messageId } = payload!;\n\n if (groupedId !== undefined) {\n const ids = selectForwardedMessageIdsByGroupId(global, groupedChatId, groupedId);\n if (ids?.length) {\n ([messageId] = ids);\n }\n }\n\n const currentMessageList = selectCurrentMessageList(global);\n const shouldSwitchChat = !currentMessageList || (\n chatId !== currentMessageList.chatId\n || threadId !== currentMessageList.threadId\n || messageListType !== currentMessageList.type\n );\n\n if (blurTimeout) {\n clearTimeout(blurTimeout);\n blurTimeout = undefined;\n }\n blurTimeout = window.setTimeout(() => {\n let newGlobal = getGlobal();\n newGlobal = updateFocusedMessage(newGlobal);\n newGlobal = updateFocusDirection(newGlobal);\n setGlobal(newGlobal);\n }, noHighlight ? FOCUS_NO_HIGHLIGHT_DURATION : FOCUS_DURATION);\n\n global = updateFocusedMessage(global, chatId, messageId, noHighlight, isResizingContainer);\n global = updateFocusDirection(global, undefined);\n\n if (replyMessageId) {\n const replyStack = selectReplyStack(global, chatId, threadId) || [];\n global = replaceThreadParam(global, chatId, threadId, 'replyStack', [...replyStack, replyMessageId]);\n }\n\n if (shouldSwitchChat) {\n global = updateFocusDirection(global, FocusDirection.Static);\n }\n\n const viewportIds = selectViewportIds(global, chatId, threadId);\n if (viewportIds && viewportIds.includes(messageId)) {\n setGlobal(global);\n actions.openChat({ id: chatId, threadId });\n return undefined;\n }\n\n if (shouldSwitchChat) {\n global = replaceThreadParam(global, chatId, threadId, 'viewportIds', undefined);\n }\n\n global = replaceThreadParam(global, chatId, threadId, 'outlyingIds', undefined);\n\n if (viewportIds && !shouldSwitchChat) {\n const direction = messageId > viewportIds[0] ? FocusDirection.Down : FocusDirection.Up;\n global = updateFocusDirection(global, direction);\n }\n\n setGlobal(global);\n\n actions.openChat({ id: chatId, threadId });\n actions.loadViewportMessages();\n return undefined;\n});\n\naddReducer('openForwardMenu', (global, actions, payload) => {\n const { fromChatId, messageIds, groupedId } = payload!;\n let groupedMessageIds;\n if (groupedId) {\n groupedMessageIds = selectMessageIdsByGroupId(global, fromChatId, groupedId);\n }\n return {\n ...global,\n forwardMessages: {\n fromChatId,\n messageIds: groupedMessageIds || messageIds,\n isModalShown: true,\n },\n };\n});\n\naddReducer('exitForwardMode', (global) => {\n setGlobal({\n ...global,\n forwardMessages: {},\n });\n});\n\naddReducer('setForwardChatId', (global, actions, payload) => {\n const { id } = payload!;\n\n setGlobal({\n ...global,\n forwardMessages: {\n ...global.forwardMessages,\n toChatId: id,\n isModalShown: false,\n },\n });\n\n actions.openChat({ id });\n actions.closeMediaViewer();\n actions.exitMessageSelectMode();\n});\n\naddReducer('openForwardMenuForSelectedMessages', (global, actions) => {\n if (!global.selectedMessages) {\n return;\n }\n\n const { chatId: fromChatId, messageIds } = global.selectedMessages;\n\n actions.openForwardMenu({ fromChatId, messageIds });\n});\n\naddReducer('cancelMessageMediaDownload', (global, actions, payload) => {\n const { message } = payload!;\n\n const byChatId = global.activeDownloads.byChatId[message.chatId];\n if (!byChatId || !byChatId.length) return;\n\n setGlobal({\n ...global,\n activeDownloads: {\n byChatId: {\n ...global.activeDownloads.byChatId,\n [message.chatId]: byChatId.filter((id) => id !== message.id),\n },\n },\n });\n});\n\naddReducer('downloadMessageMedia', (global, actions, payload) => {\n const { message } = payload!;\n if (!message) return;\n\n setGlobal({\n ...global,\n activeDownloads: {\n byChatId: {\n ...global.activeDownloads.byChatId,\n [message.chatId]: [...(global.activeDownloads.byChatId[message.chatId] || []), message.id],\n },\n },\n });\n});\n\naddReducer('downloadSelectedMessages', (global, actions) => {\n if (!global.selectedMessages) {\n return;\n }\n\n const { chatId, messageIds } = global.selectedMessages;\n const { threadId } = selectCurrentMessageList(global) || {};\n\n const chatMessages = selectChatMessages(global, chatId);\n if (!chatMessages || !threadId) return;\n const messages = messageIds.map((id) => chatMessages[id])\n .filter((message) => selectAllowedMessageActions(global, message, threadId).canDownload);\n messages.forEach((message) => actions.downloadMessageMedia({ message }));\n});\n\naddReducer('enterMessageSelectMode', (global, actions, payload) => {\n const { messageId } = payload || {};\n const openChat = selectCurrentChat(global);\n if (!openChat) {\n return global;\n }\n\n return enterMessageSelectMode(global, openChat.id, messageId);\n});\n\naddReducer('toggleMessageSelection', (global, actions, payload) => {\n const {\n messageId,\n groupedId,\n childMessageIds,\n withShift,\n } = payload!;\n const currentMessageList = selectCurrentMessageList(global);\n if (!currentMessageList) {\n return;\n }\n\n const { chatId, threadId, type: messageListType } = currentMessageList;\n\n global = toggleMessageSelection(\n global, chatId, threadId, messageListType, messageId, groupedId, childMessageIds, withShift,\n );\n\n setGlobal(global);\n\n if (global.shouldShowContextMenuHint) {\n actions.disableContextMenuHint();\n actions.showNotification({\n // eslint-disable-next-line max-len\n message: `To **edit** or **reply**, close this menu. Then ${IS_TOUCH_ENV ? 'long tap' : 'right click'} on a message.`,\n });\n }\n});\n\naddReducer('disableContextMenuHint', (global) => {\n if (!global.shouldShowContextMenuHint) {\n return undefined;\n }\n\n return {\n ...global,\n shouldShowContextMenuHint: false,\n };\n});\n\naddReducer('exitMessageSelectMode', exitMessageSelectMode);\n\naddReducer('openPollModal', (global) => {\n return {\n ...global,\n isPollModalOpen: true,\n };\n});\n\naddReducer('closePollModal', (global) => {\n return {\n ...global,\n isPollModalOpen: false,\n };\n});\n\naddReducer('checkVersionNotification', (global, actions) => {\n const currentVersion = APP_VERSION.split('.').slice(0, 2).join('.');\n const { serviceNotifications } = global;\n\n if (serviceNotifications.find(({ version }) => version === currentVersion)) {\n return;\n }\n\n const message: Omit<ApiMessage, 'id'> = {\n chatId: SERVICE_NOTIFICATIONS_USER_ID,\n date: getServerTime(global.serverTimeOffset),\n content: {\n text: parseMessageInput(versionNotification),\n },\n isOutgoing: false,\n };\n\n actions.createServiceNotification({\n message,\n version: currentVersion,\n });\n});\n\naddReducer('createServiceNotification', (global, actions, payload) => {\n const { message, version } = payload;\n const { serviceNotifications } = global;\n const serviceChat = selectChat(global, SERVICE_NOTIFICATIONS_USER_ID)!;\n\n const maxId = Math.max(\n serviceChat.lastMessage?.id || 0,\n ...serviceNotifications.map(({ id }) => id),\n );\n const fractionalPart = (serviceNotifications.length + 1) / SERVICE_NOTIFICATIONS_MAX_AMOUNT;\n // The fractional ID is made of the largest integer ID and an incremented fractional part\n const id = Math.floor(maxId) + fractionalPart;\n\n message.id = id;\n\n const serviceNotification = {\n id,\n message,\n version,\n isUnread: true,\n };\n\n setGlobal({\n ...global,\n serviceNotifications: [\n ...serviceNotifications.slice(-SERVICE_NOTIFICATIONS_MAX_AMOUNT),\n serviceNotification,\n ],\n });\n\n actions.apiUpdate({\n '@type': 'newMessage',\n id: message.id,\n chatId: message.chatId,\n message,\n });\n});\n","export default \"**Telegram Web Z was updated to version alpha 1.22**\\n\\n👏 **Harder**\\n· Messages you forward can now be sent as Scheduled Messages.\\n· Groups you have in common with another user are now listed on their Profile.\\n· Added text and image previews for the WebZ URL.\\n\\n🤩 **Better**\\n· Notifications are no longer shown when the app is in the foreground.\\n· Various UI improvements.\\n\\n🚀 **Faster**\\n· Fixed some minor memory leaks.\\n\\n💪 **Stronger**\\n· Fixed opening unread comments on posts.\\n· Fixed notifications opening the browser instead of the installed app.\\n· Fixed missing Sticker Search section.\\n· Fixed flickering when sending a message to an empty channel.\\n· Fixed ESG panel sometimes being stuck.\\n· Fixed app freezes when formatting text.\\n· Fixed issues when creating a group.\\n\";","import { addReducer } from '../../../lib/teact/teactn';\n\nimport { updateGlobalSearch, updateGlobalSearchContent } from '../../reducers';\n\nconst MAX_RECENTLY_FOUND_IDS = 10;\n\naddReducer('setGlobalSearchQuery', (global, actions, payload) => {\n const { query } = payload!;\n const { chatId } = global.globalSearch;\n\n return updateGlobalSearch(global, {\n globalResults: {},\n localResults: {},\n resultsByType: undefined,\n ...(query ? { fetchingStatus: { chats: !chatId, messages: true } } : { fetchingStatus: undefined }),\n query,\n });\n});\n\naddReducer('addRecentlyFoundChatId', (global, actions, payload) => {\n const { id } = payload!;\n const { recentlyFoundChatIds } = global.globalSearch;\n\n if (!recentlyFoundChatIds) {\n return updateGlobalSearch(global, { recentlyFoundChatIds: [id] });\n }\n\n const newRecentIds = recentlyFoundChatIds.filter((chatId) => chatId !== id);\n newRecentIds.unshift(id);\n if (newRecentIds.length > MAX_RECENTLY_FOUND_IDS) {\n newRecentIds.pop();\n }\n\n return updateGlobalSearch(global, { recentlyFoundChatIds: newRecentIds });\n});\n\naddReducer('clearRecentlyFoundChats', (global) => {\n return updateGlobalSearch(global, { recentlyFoundChatIds: undefined });\n});\n\naddReducer('setGlobalSearchContent', (global, actions, payload) => {\n const { content } = payload!;\n\n return updateGlobalSearchContent(global, content);\n});\n\naddReducer('setGlobalSearchChatId', (global, actions, payload) => {\n const { id } = payload!;\n\n return updateGlobalSearch(global, { chatId: id, query: undefined, resultsByType: undefined });\n});\n","import { addReducer } from '../../../lib/teact/teactn';\n\naddReducer('setStickerSearchQuery', (global, actions, payload) => {\n const { query } = payload!;\n\n return {\n ...global,\n stickers: {\n ...global.stickers,\n search: {\n query,\n resultIds: undefined,\n },\n },\n };\n});\n\naddReducer('setGifSearchQuery', (global, actions, payload) => {\n const { query } = payload!;\n\n return {\n ...global,\n gifs: {\n ...global.gifs,\n search: {\n query,\n offsetId: undefined,\n results: undefined,\n },\n },\n };\n});\n","import { addReducer } from '../../../lib/teact/teactn';\n\nimport { GlobalState } from '../../../global/types';\n\nimport { updateSelectedUserId, updateUserSearch } from '../../reducers';\n\naddReducer('openUserInfo', (global, actions, payload) => {\n const { id } = payload!;\n\n actions.openChat({ id });\n});\n\nconst clearSelectedUserId = (global: GlobalState) => updateSelectedUserId(global, undefined);\n\naddReducer('openChat', clearSelectedUserId);\n\naddReducer('setUserSearchQuery', (global, actions, payload) => {\n const { query } = payload!;\n\n return updateUserSearch(global, {\n globalUserIds: undefined,\n localUserIds: undefined,\n fetchingStatus: Boolean(query),\n query,\n });\n});\n","import { addReducer } from '../../../lib/teact/teactn';\n\nimport { GlobalState } from '../../../global/types';\nimport { ApiError } from '../../../api/types';\n\nimport { IS_SINGLE_COLUMN_LAYOUT, IS_TABLET_COLUMN_LAYOUT } from '../../../util/environment';\nimport getReadableErrorText from '../../../util/getReadableErrorText';\nimport { selectCurrentMessageList } from '../../selectors';\nimport generateIdFor from '../../../util/generateIdFor';\n\nconst MAX_STORED_EMOJIS = 18; // Represents two rows of recent emojis\n\naddReducer('toggleChatInfo', (global) => {\n return {\n ...global,\n isChatInfoShown: !global.isChatInfoShown,\n };\n});\n\naddReducer('setLeftColumnWidth', (global, actions, payload) => {\n const leftColumnWidth = payload;\n\n return {\n ...global,\n leftColumnWidth,\n };\n});\n\naddReducer('resetLeftColumnWidth', (global) => {\n return {\n ...global,\n leftColumnWidth: undefined,\n };\n});\n\naddReducer('toggleManagement', (global): GlobalState | undefined => {\n const { chatId } = selectCurrentMessageList(global) || {};\n\n if (!chatId) {\n return undefined;\n }\n\n return {\n ...global,\n management: {\n byChatId: {\n ...global.management.byChatId,\n [chatId]: {\n ...global.management.byChatId[chatId],\n isActive: !(global.management.byChatId[chatId] || {}).isActive,\n },\n },\n },\n };\n});\n\naddReducer('closeManagement', (global): GlobalState | undefined => {\n const { chatId } = selectCurrentMessageList(global) || {};\n\n if (!chatId) {\n return undefined;\n }\n\n return {\n ...global,\n management: {\n byChatId: {\n ...global.management.byChatId,\n [chatId]: {\n ...global.management.byChatId[chatId],\n isActive: false,\n },\n },\n },\n };\n});\n\naddReducer('openChat', (global) => {\n if (!IS_SINGLE_COLUMN_LAYOUT && !IS_TABLET_COLUMN_LAYOUT) {\n return undefined;\n }\n\n return {\n ...global,\n isLeftColumnShown: global.messages.messageLists.length === 0,\n };\n});\n\naddReducer('toggleLeftColumn', (global) => {\n return {\n ...global,\n isLeftColumnShown: !global.isLeftColumnShown,\n };\n});\n\naddReducer('addRecentEmoji', (global, action, payload) => {\n const { emoji } = payload!;\n const { recentEmojis } = global;\n if (!recentEmojis) {\n return {\n ...global,\n recentEmojis: [emoji],\n };\n }\n\n const newEmojis = recentEmojis.filter((e) => e !== emoji);\n newEmojis.unshift(emoji);\n if (newEmojis.length > MAX_STORED_EMOJIS) {\n newEmojis.pop();\n }\n\n return {\n ...global,\n recentEmojis: newEmojis,\n };\n});\n\naddReducer('addRecentSticker', (global, action, payload) => {\n const { sticker } = payload!;\n const { recent } = global.stickers;\n if (!recent) {\n return {\n ...global,\n stickers: {\n ...global.stickers,\n recent: {\n hash: '0',\n stickers: [sticker],\n },\n },\n };\n }\n\n const newStickers = recent.stickers.filter((s) => s.id !== sticker.id);\n newStickers.unshift(sticker);\n\n return {\n ...global,\n stickers: {\n ...global.stickers,\n recent: {\n ...recent,\n stickers: newStickers,\n },\n },\n };\n});\n\naddReducer('showNotification', (global, actions, payload) => {\n const notification = payload!;\n notification.localId = generateIdFor({});\n\n const newNotifications = [...global.notifications];\n const existingNotificationIndex = newNotifications.findIndex((n) => n.message === notification.message);\n if (existingNotificationIndex !== -1) {\n newNotifications.splice(existingNotificationIndex, 1);\n }\n\n newNotifications.push(notification);\n\n return {\n ...global,\n notifications: newNotifications,\n };\n});\n\naddReducer('dismissNotification', (global, actions, payload) => {\n const newNotifications = global.notifications.filter(({ localId }) => localId !== payload.localId);\n\n return {\n ...global,\n notifications: newNotifications,\n };\n});\n\naddReducer('showDialog', (global, actions, payload) => {\n const { data } = payload!;\n\n // Filter out errors that we don't want to show to the user\n if ('message' in data && data.hasErrorKey && !getReadableErrorText(data)) {\n return global;\n }\n\n const newDialogs = [...global.dialogs];\n if ('message' in data) {\n const existingErrorIndex = newDialogs.findIndex((err) => (err as ApiError).message === data.message);\n if (existingErrorIndex !== -1) {\n newDialogs.splice(existingErrorIndex, 1);\n }\n }\n\n newDialogs.push(data);\n\n return {\n ...global,\n dialogs: newDialogs,\n };\n});\n\naddReducer('dismissDialog', (global) => {\n const newDialogs = [...global.dialogs];\n\n newDialogs.pop();\n\n return {\n ...global,\n dialogs: newDialogs,\n };\n});\n\naddReducer('toggleSafeLinkModal', (global, actions, payload) => {\n const { url: safeLinkModalUrl } = payload;\n\n return {\n ...global,\n safeLinkModalUrl,\n };\n});\n\naddReducer('openHistoryCalendar', (global, actions, payload) => {\n const { selectedAt } = payload;\n\n return {\n ...global,\n historyCalendarSelectedAt: selectedAt,\n };\n});\n\naddReducer('closeHistoryCalendar', (global) => {\n return {\n ...global,\n historyCalendarSelectedAt: undefined,\n };\n});\n","import { addReducer } from '../../../lib/teact/teactn';\n\nimport { clearPayment, closeInvoice } from '../../reducers';\n\naddReducer('openPaymentModal', (global, actions, payload) => {\n const { chatId, messageId } = payload;\n return {\n ...global,\n payment: {\n ...global.payment,\n chatId,\n messageId,\n isPaymentModalOpen: true,\n },\n };\n});\n\naddReducer('closePaymentModal', (global) => {\n const newGlobal = clearPayment(global);\n return closeInvoice(newGlobal);\n});\n\naddReducer('addPaymentError', (global, actions, payload) => {\n const { error } = payload!;\n\n return {\n ...global,\n payment: {\n ...global.payment,\n error,\n },\n };\n});\n","import { getDispatch } from '../lib/teact/teactn';\n\ntype DeepLinkMethod = 'resolve' | 'login' | 'passport' | 'settings' | 'join' | 'addstickers' | 'setlanguage' |\n'addtheme' | 'confirmphone' | 'socks' | 'proxy' | 'privatepost' | 'bg' | 'share' | 'msg' | 'msg_url';\n\nexport const processDeepLink = (url: string) => {\n const { protocol, searchParams, pathname } = new URL(url);\n\n if (protocol !== 'tg:') return;\n\n const {\n openChatByInvite,\n openChatByUsername,\n openStickerSetShortName,\n focusMessage,\n } = getDispatch();\n\n const method = pathname.replace(/^\\/\\//, '') as DeepLinkMethod;\n const params: Record<string, string> = {};\n searchParams.forEach((value, key) => {\n params[key] = value;\n });\n\n switch (method) {\n case 'resolve': {\n const { domain, post, comment } = params;\n\n if (domain !== 'telegrampassport') {\n openChatByUsername({\n username: domain,\n messageId: Number(post),\n commentId: Number(comment),\n });\n }\n break;\n }\n case 'privatepost': {\n const {\n post, channel,\n } = params;\n\n focusMessage({\n chatId: -Number(channel),\n id: post,\n });\n break;\n }\n case 'bg': {\n // const {\n // slug, color, rotation, mode, intensity, bg_color: bgColor, gradient,\n // } = params;\n break;\n }\n case 'join': {\n const { invite } = params;\n\n openChatByInvite({ hash: invite });\n break;\n }\n case 'addstickers': {\n const { set } = params;\n\n openStickerSetShortName({\n stickerSetShortName: set,\n });\n break;\n }\n case 'share':\n case 'msg': {\n // const { url, text } = params;\n break;\n }\n case 'login': {\n // const { code, token } = params;\n break;\n }\n default:\n // Unsupported deeplink\n\n break;\n }\n};\n","import {\n addReducer, getDispatch, getGlobal, setGlobal,\n} from '../../../lib/teact/teactn';\n\nimport {\n ApiChat, ApiUser, ApiChatFolder, MAIN_THREAD_ID,\n} from '../../../api/types';\nimport { NewChatMembersProgress, ChatCreationProgress, ManagementProgress } from '../../../types';\nimport { GlobalActions } from '../../../global/types';\n\nimport {\n ARCHIVED_FOLDER_ID,\n TOP_CHAT_MESSAGES_PRELOAD_LIMIT,\n CHAT_LIST_LOAD_SLICE,\n TIPS_USERNAME,\n LOCALIZED_TIPS,\n RE_TG_LINK,\n SERVICE_NOTIFICATIONS_USER_ID,\n TMP_CHAT_ID,\n} from '../../../config';\nimport { callApi } from '../../../api/gramjs';\nimport {\n addChats,\n addUsers,\n replaceThreadParam,\n updateChatListIds,\n updateChats,\n updateChat,\n updateChatListSecondaryInfo,\n updateManagementProgress,\n leaveChat,\n} from '../../reducers';\nimport {\n selectChat,\n selectUser,\n selectChatListType,\n selectIsChatPinned,\n selectChatFolder,\n selectSupportChat,\n selectChatByUsername,\n selectThreadTopMessageId,\n selectCurrentMessageList,\n selectThreadInfo, selectCurrentChat, selectLastServiceNotification,\n} from '../../selectors';\nimport { buildCollectionByKey } from '../../../util/iteratees';\nimport { debounce, pause, throttle } from '../../../util/schedulers';\nimport {\n isChatSummaryOnly, isChatArchived, prepareChatList, isChatBasicGroup,\n} from '../../helpers';\nimport { processDeepLink } from '../../../util/deeplink';\n\nconst TOP_CHAT_MESSAGES_PRELOAD_INTERVAL = 100;\nconst CHATS_PRELOAD_INTERVAL = 300;\n\nconst runThrottledForLoadChats = throttle((cb) => cb(), CHATS_PRELOAD_INTERVAL, true);\nconst runThrottledForLoadTopChats = throttle((cb) => cb(), 3000, true);\nconst runDebouncedForLoadFullChat = debounce((cb) => cb(), 500, false, true);\n\naddReducer('preloadTopChatMessages', (global, actions) => {\n (async () => {\n const preloadedChatIds: string[] = [];\n\n for (let i = 0; i < TOP_CHAT_MESSAGES_PRELOAD_LIMIT; i++) {\n await pause(TOP_CHAT_MESSAGES_PRELOAD_INTERVAL);\n\n const {\n byId,\n listIds: { active: listIds },\n orderedPinnedIds: { active: orderedPinnedIds },\n } = getGlobal().chats;\n if (!listIds) {\n return;\n }\n\n const { chatId: currentChatId } = selectCurrentMessageList(global) || {};\n const { pinnedChats, otherChats } = prepareChatList(byId, listIds, orderedPinnedIds);\n const topChats = [...pinnedChats, ...otherChats];\n const chatToPreload = topChats.find(({ id }) => id !== currentChatId && !preloadedChatIds.includes(id));\n if (!chatToPreload) {\n return;\n }\n\n preloadedChatIds.push(chatToPreload.id);\n\n actions.loadViewportMessages({ chatId: chatToPreload.id, threadId: MAIN_THREAD_ID });\n }\n })();\n});\n\naddReducer('openChat', (global, actions, payload) => {\n const { id, threadId } = payload!;\n const { currentUserId } = global;\n const chat = selectChat(global, id);\n\n if (chat?.hasUnreadMark) {\n actions.toggleChatUnread({ id });\n }\n\n // Please telegram send us some updates about linked chat 🙏\n if (chat && chat.lastMessage && chat.lastMessage.threadInfo) {\n actions.requestThreadInfoUpdate({\n chatId: chat.lastMessage.threadInfo.chatId,\n threadId: chat.lastMessage.threadInfo.threadId,\n });\n }\n\n if (!chat) {\n if (id === currentUserId) {\n void callApi('fetchChat', { type: 'self' });\n } else {\n const user = selectUser(global, id);\n if (user) {\n void callApi('fetchChat', { type: 'user', user });\n }\n }\n } else if (isChatSummaryOnly(chat) && !chat.isMin) {\n actions.requestChatUpdate({ chatId: id });\n }\n\n if (threadId !== MAIN_THREAD_ID) {\n const topMessageId = selectThreadTopMessageId(global, id, threadId);\n if (!topMessageId) {\n actions.requestThreadInfoUpdate({ chatId: id, threadId });\n }\n }\n});\n\naddReducer('openLinkedChat', (global, actions, payload) => {\n const { id } = payload!;\n const chat = selectChat(global, id);\n if (!chat) {\n return;\n }\n\n (async () => {\n const chatFullInfo = await callApi('fetchFullChat', chat);\n\n if (chatFullInfo?.fullInfo?.linkedChatId) {\n actions.openChat({ id: chatFullInfo.fullInfo.linkedChatId });\n }\n })();\n});\n\naddReducer('focusMessageInComments', (global, actions, payload) => {\n const { chatId, threadId, messageId } = payload!;\n const chat = selectChat(global, chatId);\n if (!chat) {\n return;\n }\n\n (async () => {\n const result = await callApi('requestThreadInfoUpdate', { chat, threadId });\n if (!result) {\n return;\n }\n\n actions.focusMessage({ chatId, threadId, messageId });\n })();\n});\n\naddReducer('openSupportChat', (global, actions) => {\n const chat = selectSupportChat(global);\n if (chat) {\n actions.openChat({ id: chat.id, shouldReplaceHistory: true });\n return;\n }\n\n actions.openChat({ id: TMP_CHAT_ID, shouldReplaceHistory: true });\n\n (async () => {\n const result = await callApi('fetchChat', { type: 'support' });\n if (result) {\n actions.openChat({ id: result.chatId, shouldReplaceHistory: true });\n }\n })();\n});\n\naddReducer('openTipsChat', (global, actions, payload) => {\n const { langCode } = payload;\n\n const usernamePostfix = langCode === 'pt-br'\n ? 'BR'\n : LOCALIZED_TIPS.includes(langCode) ? (langCode as string).toUpperCase() : '';\n\n actions.openChatByUsername({ username: `${TIPS_USERNAME}${usernamePostfix}` });\n});\n\naddReducer('loadMoreChats', (global, actions, payload) => {\n const { listType = 'active' } = payload!;\n const listIds = global.chats.listIds[listType as ('active' | 'archived')];\n const isFullyLoaded = global.chats.isFullyLoaded[listType as ('active' | 'archived')];\n\n if (isFullyLoaded) {\n return;\n }\n\n const oldestChat = listIds\n ? listIds\n .map((id) => global.chats.byId[id])\n .filter((chat) => Boolean(chat?.lastMessage) && !selectIsChatPinned(global, chat.id))\n .sort((chat1, chat2) => (chat1.lastMessage!.date - chat2.lastMessage!.date))[0]\n : undefined;\n\n if (oldestChat) {\n runThrottledForLoadChats(() => loadChats(listType, oldestChat.id, oldestChat.lastMessage!.date));\n } else {\n runThrottledForLoadChats(() => loadChats(listType));\n }\n});\n\naddReducer('preloadArchivedChats', () => {\n (async () => {\n while (!getGlobal().chats.isFullyLoaded.archived) {\n const currentGlobal = getGlobal();\n const listIds = currentGlobal.chats.listIds.archived;\n const oldestChat = listIds\n ? listIds\n .map((id) => currentGlobal.chats.byId[id])\n .filter((chat) => Boolean(chat?.lastMessage) && !selectIsChatPinned(currentGlobal, chat.id))\n .sort((chat1, chat2) => (chat1.lastMessage!.date - chat2.lastMessage!.date))[0]\n : undefined;\n\n await loadChats('archived', oldestChat?.id, oldestChat?.lastMessage!.date);\n await pause(CHATS_PRELOAD_INTERVAL);\n }\n })();\n});\n\naddReducer('loadFullChat', (global, actions, payload) => {\n const { chatId, force } = payload!;\n const chat = selectChat(global, chatId);\n if (!chat) {\n return;\n }\n\n if (force) {\n loadFullChat(chat);\n } else {\n runDebouncedForLoadFullChat(() => loadFullChat(chat));\n }\n});\n\naddReducer('loadTopChats', () => {\n runThrottledForLoadTopChats(() => loadChats('active'));\n});\n\naddReducer('requestChatUpdate', (global, actions, payload) => {\n const { serverTimeOffset } = global;\n const { chatId } = payload!;\n const chat = selectChat(global, chatId);\n if (!chat) {\n return;\n }\n\n void callApi('requestChatUpdate', {\n chat,\n serverTimeOffset,\n ...(chatId === SERVICE_NOTIFICATIONS_USER_ID && {\n lastLocalMessage: selectLastServiceNotification(global)?.message,\n }),\n });\n});\n\naddReducer('updateChatMutedState', (global, actions, payload) => {\n const { serverTimeOffset } = global;\n const { chatId, isMuted } = payload!;\n const chat = selectChat(global, chatId);\n if (!chat) {\n return;\n }\n\n setGlobal(updateChat(global, chatId, { isMuted }));\n void callApi('updateChatMutedState', { chat, isMuted, serverTimeOffset });\n});\n\naddReducer('createChannel', (global, actions, payload) => {\n const {\n title, about, photo, memberIds,\n } = payload!;\n\n const members = (memberIds as string[])\n .map((id) => selectUser(global, id))\n .filter<ApiUser>(Boolean as any);\n\n void createChannel(title, members, about, photo);\n});\n\naddReducer('joinChannel', (global, actions, payload) => {\n const { chatId } = payload!;\n const chat = selectChat(global, chatId);\n if (!chat) {\n return;\n }\n\n const { id: channelId, accessHash } = chat;\n\n if (channelId && accessHash) {\n void callApi('joinChannel', { channelId, accessHash });\n }\n});\n\naddReducer('deleteChatUser', (global, actions, payload) => {\n const { chatId, userId }: { chatId: string; userId: string } = payload!;\n const chat = selectChat(global, chatId);\n const user = selectUser(global, userId);\n if (!chat || !user) {\n return;\n }\n\n global = leaveChat(global, chatId);\n setGlobal(global);\n\n if (selectCurrentMessageList(global)?.chatId === chatId) {\n actions.openChat({ id: undefined });\n }\n\n void callApi('deleteChatUser', { chat, user });\n});\n\naddReducer('deleteChat', (global, actions, payload) => {\n const { chatId }: { chatId: string } = payload!;\n const chat = selectChat(global, chatId);\n if (!chat) {\n return;\n }\n\n global = leaveChat(global, chatId);\n setGlobal(global);\n\n if (selectCurrentMessageList(global)?.chatId === chatId) {\n actions.openChat({ id: undefined });\n }\n\n void callApi('deleteChat', { chatId: chat.id });\n});\n\naddReducer('leaveChannel', (global, actions, payload) => {\n const { chatId } = payload!;\n const chat = selectChat(global, chatId);\n if (!chat) {\n return;\n }\n\n global = leaveChat(global, chatId);\n setGlobal(global);\n\n if (selectCurrentMessageList(global)?.chatId === chatId) {\n actions.openChat({ id: undefined });\n }\n\n const { id: channelId, accessHash } = chat;\n if (channelId && accessHash) {\n void callApi('leaveChannel', { channelId, accessHash });\n }\n});\n\naddReducer('deleteChannel', (global, actions, payload) => {\n const { chatId } = payload!;\n const chat = selectChat(global, chatId);\n if (!chat) {\n return;\n }\n\n global = leaveChat(global, chatId);\n setGlobal(global);\n\n if (selectCurrentMessageList(global)?.chatId === chatId) {\n actions.openChat({ id: undefined });\n }\n\n const { id: channelId, accessHash } = chat;\n if (channelId && accessHash) {\n void callApi('deleteChannel', { channelId, accessHash });\n }\n});\n\naddReducer('createGroupChat', (global, actions, payload) => {\n const { title, memberIds, photo } = payload!;\n const members = (memberIds as string[])\n .map((id) => selectUser(global, id))\n .filter<ApiUser>(Boolean as any);\n\n void createGroupChat(title, members, photo);\n});\n\naddReducer('toggleChatPinned', (global, actions, payload) => {\n const { id, folderId } = payload!;\n const chat = selectChat(global, id);\n if (!chat) {\n return;\n }\n\n if (folderId) {\n const folder = selectChatFolder(global, folderId);\n if (folder) {\n const shouldBePinned = !selectIsChatPinned(global, id, folderId);\n\n const { pinnedChatIds, includedChatIds } = folder;\n const newPinnedIds = shouldBePinned\n ? [id, ...(pinnedChatIds || [])]\n : (pinnedChatIds || []).filter((pinnedId) => pinnedId !== id);\n\n // With both Pin and Unpin we need to re-add a user to the included group\n const newIncludedChatIds = [id, ...includedChatIds];\n\n void callApi('editChatFolder', {\n id: folderId,\n folderUpdate: {\n ...folder,\n pinnedChatIds: newPinnedIds,\n includedChatIds: newIncludedChatIds,\n },\n });\n }\n } else {\n const listType = selectChatListType(global, id);\n const isPinned = selectIsChatPinned(global, id, listType === 'archived' ? ARCHIVED_FOLDER_ID : undefined);\n void callApi('toggleChatPinned', { chat, shouldBePinned: !isPinned });\n }\n});\n\naddReducer('toggleChatArchived', (global, actions, payload) => {\n const { id } = payload!;\n const chat = selectChat(global, id);\n if (chat) {\n void callApi('toggleChatArchived', {\n chat,\n folderId: isChatArchived(chat) ? 0 : ARCHIVED_FOLDER_ID,\n });\n }\n});\n\naddReducer('loadChatFolders', () => {\n void loadChatFolders();\n});\n\naddReducer('loadRecommendedChatFolders', () => {\n void loadRecommendedChatFolders();\n});\n\naddReducer('editChatFolders', (global, actions, payload) => {\n const { chatId, idsToRemove, idsToAdd } = payload!;\n\n (idsToRemove as number[]).forEach(async (id) => {\n const folder = selectChatFolder(global, id);\n if (folder) {\n await callApi('editChatFolder', {\n id,\n folderUpdate: {\n ...folder,\n pinnedChatIds: folder.pinnedChatIds?.filter((pinnedId) => pinnedId !== chatId),\n includedChatIds: folder.includedChatIds.filter((includedId) => includedId !== chatId),\n },\n });\n }\n });\n\n (idsToAdd as number[]).forEach(async (id) => {\n const folder = selectChatFolder(global, id);\n if (folder) {\n await callApi('editChatFolder', {\n id,\n folderUpdate: {\n ...folder,\n includedChatIds: folder.includedChatIds.concat(chatId),\n },\n });\n }\n });\n});\n\naddReducer('editChatFolder', (global, actions, payload) => {\n const { id, folderUpdate } = payload!;\n const folder = selectChatFolder(global, id);\n\n if (folder) {\n void callApi('editChatFolder', {\n id,\n folderUpdate: {\n id,\n emoticon: folder.emoticon,\n pinnedChatIds: folder.pinnedChatIds,\n ...folderUpdate,\n },\n });\n }\n});\n\naddReducer('addChatFolder', (global, actions, payload) => {\n const { folder } = payload!;\n const { orderedIds } = global.chatFolders;\n const maxId = orderedIds?.length ? Math.max.apply(Math.max, orderedIds) : ARCHIVED_FOLDER_ID;\n\n void createChatFolder(folder, maxId);\n});\n\naddReducer('deleteChatFolder', (global, actions, payload) => {\n const { id } = payload!;\n const folder = selectChatFolder(global, id);\n\n if (folder) {\n void deleteChatFolder(id);\n }\n});\n\naddReducer('toggleChatUnread', (global, actions, payload) => {\n const { id } = payload!;\n const { serverTimeOffset } = global;\n const chat = selectChat(global, id);\n if (chat) {\n if (chat.unreadCount) {\n void callApi('markMessageListRead', { serverTimeOffset, chat, threadId: MAIN_THREAD_ID });\n } else {\n void callApi('toggleDialogUnread', {\n chat,\n hasUnreadMark: !chat.hasUnreadMark,\n });\n }\n }\n});\n\naddReducer('openChatByInvite', (global, actions, payload) => {\n const { hash } = payload!;\n\n (async () => {\n const result = await callApi('openChatByInvite', hash);\n if (!result) {\n return;\n }\n\n actions.openChat({ id: result.chatId });\n })();\n});\n\naddReducer('openTelegramLink', (global, actions, payload) => {\n const { url } = payload!;\n if (url.match(RE_TG_LINK)) {\n processDeepLink(url.match(RE_TG_LINK)[0]);\n return;\n }\n\n const uri = new URL(url.startsWith('http') ? url : `https://${url}`);\n const [part1, part2, part3] = uri.pathname.split('/').filter(Boolean).map((l) => decodeURI(l));\n const params = Object.fromEntries(uri.searchParams);\n\n let hash: string | undefined;\n if (part1 === 'joinchat') {\n hash = part2;\n }\n\n if (part1.startsWith(' ') || part1.startsWith('+')) {\n hash = part1.substr(1, part1.length - 1);\n }\n\n if (hash) {\n actions.openChatByInvite({ hash });\n return;\n }\n\n if (part1 === 'addstickers') {\n actions.openStickerSetShortName({\n stickerSetShortName: part2,\n });\n return;\n }\n\n const chatOrChannelPostId = part2 ? Number(part2) : undefined;\n const messageId = part3 ? Number(part3) : undefined;\n const commentId = params.comment ? Number(params.comment) : undefined;\n if (part1 === 'c' && chatOrChannelPostId && messageId) {\n actions.focusMessage({\n chatId: -chatOrChannelPostId,\n messageId,\n });\n } else {\n actions.openChatByUsername({\n username: part1,\n messageId: messageId || chatOrChannelPostId,\n commentId,\n });\n }\n});\n\naddReducer('acceptInviteConfirmation', (global, actions, payload) => {\n const { hash } = payload!;\n (async () => {\n const result = await callApi('importChatInvite', { hash });\n if (!result) {\n return;\n }\n\n actions.openChat({ id: result.id });\n })();\n});\n\naddReducer('openChatByUsername', (global, actions, payload) => {\n const { username, messageId, commentId } = payload!;\n\n (async () => {\n const chat = selectCurrentChat(global);\n\n if (!commentId) {\n if (chat && chat.username === username) {\n actions.focusMessage({ chatId: chat.id, messageId });\n return;\n }\n await openChatByUsername(actions, username, messageId);\n return;\n }\n\n const { chatId, type } = selectCurrentMessageList(global) || {};\n const usernameChat = selectChatByUsername(global, username);\n if (chatId && usernameChat && type === 'thread') {\n const threadInfo = selectThreadInfo(global, chatId, messageId);\n\n if (threadInfo && threadInfo.chatId === chatId) {\n actions.focusMessage({\n chatId: threadInfo.chatId,\n threadId: threadInfo.threadId,\n messageId: commentId,\n });\n return;\n }\n }\n\n if (!messageId) return;\n\n await openCommentsByUsername(actions, username, messageId, commentId);\n })();\n});\n\naddReducer('togglePreHistoryHidden', (global, actions, payload) => {\n const { chatId, isEnabled } = payload!;\n let chat = selectChat(global, chatId);\n\n if (!chat) {\n return;\n }\n\n (async () => {\n if (isChatBasicGroup(chat)) {\n chat = await callApi('migrateChat', chat);\n\n if (!chat) {\n return;\n }\n\n actions.openChat({ id: chat.id });\n }\n\n void callApi('togglePreHistoryHidden', { chat, isEnabled });\n })();\n});\n\naddReducer('updateChatDefaultBannedRights', (global, actions, payload) => {\n const { chatId, bannedRights } = payload!;\n const chat = selectChat(global, chatId);\n\n if (!chat) {\n return;\n }\n\n void callApi('updateChatDefaultBannedRights', { chat, bannedRights });\n});\n\naddReducer('updateChatMemberBannedRights', (global, actions, payload) => {\n const { chatId, userId, bannedRights } = payload!;\n let chat = selectChat(global, chatId);\n const user = selectUser(global, userId);\n\n if (!chat || !user) {\n return;\n }\n\n (async () => {\n if (isChatBasicGroup(chat)) {\n chat = await callApi('migrateChat', chat);\n\n if (!chat) {\n return;\n }\n\n actions.openChat({ id: chat.id });\n }\n\n await callApi('updateChatMemberBannedRights', { chat, user, bannedRights });\n\n const newGlobal = getGlobal();\n const chatAfterUpdate = selectChat(newGlobal, chatId);\n\n if (!chatAfterUpdate || !chatAfterUpdate.fullInfo) {\n return;\n }\n\n const { members, kickedMembers } = chatAfterUpdate.fullInfo;\n\n const isBanned = !!bannedRights.viewMessages;\n const isUnblocked = !Object.keys(bannedRights).length;\n\n setGlobal(updateChat(newGlobal, chatId, {\n fullInfo: {\n ...chatAfterUpdate.fullInfo,\n ...(members && isBanned && {\n members: members.filter((m) => m.userId !== userId),\n }),\n ...(members && !isBanned && {\n members: members.map((m) => (\n m.userId === userId\n ? { ...m, bannedRights }\n : m\n )),\n }),\n ...(isUnblocked && kickedMembers && {\n kickedMembers: kickedMembers.filter((m) => m.userId !== userId),\n }),\n },\n }));\n })();\n});\n\naddReducer('updateChatAdmin', (global, actions, payload) => {\n const {\n chatId, userId, adminRights, customTitle,\n } = payload!;\n let chat = selectChat(global, chatId);\n const user = selectUser(global, userId);\n\n if (!chat || !user) {\n return;\n }\n\n (async () => {\n if (isChatBasicGroup(chat)) {\n chat = await callApi('migrateChat', chat);\n\n if (!chat) {\n return;\n }\n\n actions.openChat({ id: chat.id });\n }\n\n await callApi('updateChatAdmin', {\n chat, user, adminRights, customTitle,\n });\n\n const newGlobal = getGlobal();\n const chatAfterUpdate = selectChat(newGlobal, chatId);\n\n if (!chatAfterUpdate || !chatAfterUpdate.fullInfo) {\n return;\n }\n\n const { adminMembers } = chatAfterUpdate.fullInfo;\n\n const isDismissed = !Object.keys(adminRights).length;\n\n setGlobal(updateChat(newGlobal, chatId, {\n fullInfo: {\n ...chatAfterUpdate.fullInfo,\n ...(adminMembers && isDismissed && {\n adminMembers: adminMembers.filter((m) => m.userId !== userId),\n }),\n ...(adminMembers && !isDismissed && {\n adminMembers: adminMembers.map((m) => (\n m.userId === userId\n ? { ...m, adminRights, customTitle }\n : m\n )),\n }),\n },\n }));\n })();\n});\n\naddReducer('updateChat', (global, actions, payload) => {\n const {\n chatId, title, about, photo,\n } = payload!;\n\n const chat = selectChat(global, chatId);\n if (!chat) {\n return;\n }\n\n (async () => {\n setGlobal(updateManagementProgress(getGlobal(), ManagementProgress.InProgress));\n\n await Promise.all([\n chat.title !== title\n ? callApi('updateChatTitle', chat, title)\n : undefined,\n chat.fullInfo && chat.fullInfo.about !== about\n ? callApi('updateChatAbout', chat, about)\n : undefined,\n photo\n ? callApi('editChatPhoto', { chatId, accessHash: chat.accessHash, photo })\n : undefined,\n ]);\n\n setGlobal(updateManagementProgress(getGlobal(), ManagementProgress.Complete));\n })();\n});\n\naddReducer('toggleSignatures', (global, actions, payload) => {\n const { chatId, isEnabled } = payload!;\n const chat = selectChat(global, chatId);\n\n if (!chat) {\n return;\n }\n\n void callApi('toggleSignatures', { chat, isEnabled });\n});\n\naddReducer('loadGroupsForDiscussion', () => {\n (async () => {\n const groups = await callApi('fetchGroupsForDiscussion');\n if (!groups) {\n return;\n }\n\n const addedById = groups.reduce((result, group) => {\n if (group) {\n result[group.id] = group;\n }\n\n return result;\n }, {} as Record<string, ApiChat>);\n\n const global = addChats(getGlobal(), addedById);\n setGlobal({\n ...global,\n chats: {\n ...global.chats,\n forDiscussionIds: Object.keys(addedById),\n },\n });\n })();\n});\n\naddReducer('linkDiscussionGroup', (global, actions, payload) => {\n const { channelId, chatId } = payload!;\n\n const channel = selectChat(global, channelId);\n let chat = selectChat(global, chatId);\n if (!channel || !chat) {\n return;\n }\n\n (async () => {\n if (isChatBasicGroup(chat)) {\n chat = await callApi('migrateChat', chat);\n\n if (!chat) {\n return;\n }\n\n actions.openChat({ id: chat.id });\n }\n\n let { fullInfo } = chat;\n if (!fullInfo) {\n const fullChat = await callApi('fetchFullChat', chat);\n if (!fullChat) {\n return;\n }\n\n fullInfo = fullChat.fullInfo;\n }\n\n if (fullInfo.isPreHistoryHidden) {\n await callApi('togglePreHistoryHidden', { chat, isEnabled: false });\n }\n\n void callApi('setDiscussionGroup', { channel, chat });\n })();\n});\n\naddReducer('unlinkDiscussionGroup', (global, actions, payload) => {\n const { channelId } = payload!;\n\n const channel = selectChat(global, channelId);\n if (!channel) {\n return;\n }\n\n let chat: ApiChat | undefined;\n if (channel.fullInfo?.linkedChatId) {\n chat = selectChat(global, channel.fullInfo.linkedChatId);\n }\n\n (async () => {\n await callApi('setDiscussionGroup', { channel });\n if (chat) {\n loadFullChat(chat);\n }\n })();\n});\n\naddReducer('setActiveChatFolder', (global, actions, payload) => {\n return {\n ...global,\n chatFolders: {\n ...global.chatFolders,\n activeChatFolder: payload,\n },\n };\n});\n\naddReducer('loadMoreMembers', (global) => {\n (async () => {\n const { chatId } = selectCurrentMessageList(global) || {};\n const chat = chatId ? selectChat(global, chatId) : undefined;\n if (!chat || isChatBasicGroup(chat)) {\n return;\n }\n\n const offset = (chat.fullInfo?.members?.length) || undefined;\n const result = await callApi('fetchMembers', chat.id, chat.accessHash!, 'recent', offset);\n if (!result) {\n return;\n }\n\n const { members, users } = result;\n if (!members || !members.length) {\n return;\n }\n\n global = getGlobal();\n global = addUsers(global, buildCollectionByKey(users, 'id'));\n global = updateChat(global, chat.id, {\n fullInfo: {\n ...chat.fullInfo,\n members: [\n ...((chat.fullInfo || {}).members || []),\n ...(members || []),\n ],\n },\n });\n setGlobal(global);\n })();\n});\n\naddReducer('addChatMembers', (global, actions, payload) => {\n const { chatId, memberIds } = payload;\n const chat = selectChat(global, chatId);\n const users = (memberIds as string[]).map((userId) => selectUser(global, userId)).filter<ApiUser>(Boolean as any);\n\n if (!chat || !users.length) {\n return;\n }\n\n actions.setNewChatMembersDialogState(NewChatMembersProgress.Loading);\n (async () => {\n await callApi('addChatMembers', chat, users);\n actions.setNewChatMembersDialogState(NewChatMembersProgress.Closed);\n loadFullChat(chat);\n })();\n});\n\naddReducer('deleteChatMember', (global, actions, payload) => {\n const { chatId, userId } = payload;\n const chat = selectChat(global, chatId);\n const user = selectUser(global, userId);\n\n if (!chat || !user) {\n return;\n }\n\n (async () => {\n await callApi('deleteChatMember', chat, user);\n loadFullChat(chat);\n })();\n});\n\nasync function loadChats(listType: 'active' | 'archived', offsetId?: string, offsetDate?: number) {\n let global = getGlobal();\n\n const result = await callApi('fetchChats', {\n limit: CHAT_LIST_LOAD_SLICE,\n offsetDate,\n archived: listType === 'archived',\n withPinned: global.chats.orderedPinnedIds[listType] === undefined,\n serverTimeOffset: global.serverTimeOffset,\n lastLocalServiceMessage: selectLastServiceNotification(global)?.message,\n });\n\n if (!result) {\n return;\n }\n\n const { chatIds } = result;\n\n if (chatIds.length > 0 && chatIds[0] === offsetId) {\n chatIds.shift();\n }\n\n global = getGlobal();\n\n global = addUsers(global, buildCollectionByKey(result.users, 'id'));\n global = updateChats(global, buildCollectionByKey(result.chats, 'id'));\n global = updateChatListIds(global, listType, chatIds);\n global = updateChatListSecondaryInfo(global, listType, result);\n\n Object.keys(result.draftsById).forEach((chatId) => {\n global = replaceThreadParam(\n global, chatId, MAIN_THREAD_ID, 'draft', result.draftsById[chatId],\n );\n });\n\n Object.keys(result.replyingToById).forEach((chatId) => {\n global = replaceThreadParam(\n global, chatId, MAIN_THREAD_ID, 'replyingToId', result.replyingToById[chatId],\n );\n });\n\n if (chatIds.length === 0 && !global.chats.isFullyLoaded[listType]) {\n global = {\n ...global,\n chats: {\n ...global.chats,\n isFullyLoaded: {\n ...global.chats.isFullyLoaded,\n [listType]: true,\n },\n },\n };\n }\n\n setGlobal(global);\n}\n\nasync function loadFullChat(chat: ApiChat) {\n const result = await callApi('fetchFullChat', chat);\n if (!result) {\n return;\n }\n\n const { users, fullInfo } = result;\n\n let global = getGlobal();\n if (users) {\n global = addUsers(global, buildCollectionByKey(users, 'id'));\n }\n global = updateChat(global, chat.id, { fullInfo });\n\n setGlobal(global);\n}\n\nasync function createChannel(title: string, users: ApiUser[], about?: string, photo?: File) {\n setGlobal({\n ...getGlobal(),\n chatCreation: {\n progress: ChatCreationProgress.InProgress,\n },\n });\n\n const createdChannel = await callApi('createChannel', { title, about, users });\n if (!createdChannel) {\n return;\n }\n\n const { id: channelId, accessHash } = createdChannel;\n\n let global = getGlobal();\n global = updateChat(global, channelId, createdChannel);\n global = {\n ...global,\n chatCreation: {\n ...global.chatCreation,\n progress: createdChannel ? ChatCreationProgress.Complete : ChatCreationProgress.Error,\n },\n };\n setGlobal(global);\n getDispatch().openChat({ id: channelId, shouldReplaceHistory: true });\n\n if (channelId && accessHash && photo) {\n await callApi('editChatPhoto', { chatId: channelId, accessHash, photo });\n }\n}\n\nasync function createGroupChat(title: string, users: ApiUser[], photo?: File) {\n setGlobal({\n ...getGlobal(),\n chatCreation: {\n progress: ChatCreationProgress.InProgress,\n },\n });\n\n try {\n const createdChat = await callApi('createGroupChat', {\n title,\n users,\n });\n\n if (!createdChat) {\n return;\n }\n\n const { id: chatId } = createdChat;\n\n let global = getGlobal();\n global = updateChat(global, chatId, createdChat);\n global = {\n ...global,\n chatCreation: {\n ...global.chatCreation,\n progress: createdChat ? ChatCreationProgress.Complete : ChatCreationProgress.Error,\n },\n };\n setGlobal(global);\n getDispatch()\n .openChat({\n id: chatId,\n shouldReplaceHistory: true,\n });\n\n if (chatId && photo) {\n await callApi('editChatPhoto', {\n chatId,\n photo,\n });\n }\n } catch (e) {\n if (e.message === 'USERS_TOO_FEW') {\n const global = getGlobal();\n setGlobal({\n ...global,\n chatCreation: {\n ...global.chatCreation,\n progress: ChatCreationProgress.Error,\n error: 'CreateGroupError',\n },\n });\n }\n }\n}\n\nasync function loadChatFolders() {\n const chatFolders = await callApi('fetchChatFolders');\n\n if (chatFolders) {\n const global = getGlobal();\n\n setGlobal({\n ...global,\n chatFolders: {\n ...global.chatFolders,\n ...chatFolders,\n },\n });\n }\n}\n\nasync function loadRecommendedChatFolders() {\n const recommendedChatFolders = await callApi('fetchRecommendedChatFolders');\n\n if (recommendedChatFolders) {\n const global = getGlobal();\n\n setGlobal({\n ...global,\n chatFolders: {\n ...global.chatFolders,\n recommended: recommendedChatFolders,\n },\n });\n }\n}\n\nasync function createChatFolder(folder: ApiChatFolder, maxId: number) {\n // Clear fields from recommended folders\n const { id: recommendedId, description, ...newFolder } = folder;\n\n await callApi('editChatFolder', {\n id: maxId + 1,\n folderUpdate: {\n id: maxId + 1,\n ...newFolder,\n },\n });\n\n if (!description) {\n return;\n }\n\n const global = getGlobal();\n const { recommended } = global.chatFolders;\n\n if (recommended) {\n setGlobal({\n ...global,\n chatFolders: {\n ...global.chatFolders,\n recommended: recommended.filter(({ id }) => id !== recommendedId),\n },\n });\n }\n}\n\nasync function deleteChatFolder(id: number) {\n await callApi('deleteChatFolder', id);\n}\n\nasync function fetchChatByUsername(\n username: string,\n) {\n const global = getGlobal();\n const localChat = selectChatByUsername(global, username);\n if (localChat && !localChat.isMin) {\n return localChat;\n }\n\n const chat = await callApi('getChatByUsername', username);\n if (!chat) {\n return undefined;\n }\n\n setGlobal(updateChat(getGlobal(), chat.id, chat));\n\n return chat;\n}\n\nasync function openChatByUsername(\n actions: GlobalActions,\n username: string,\n channelPostId?: number,\n) {\n // Open temporary empty chat to make the click response feel faster\n actions.openChat({ id: TMP_CHAT_ID });\n\n const chat = await fetchChatByUsername(username);\n\n if (!chat) {\n actions.openPreviousChat();\n actions.showNotification({ message: 'User does not exist' });\n return;\n }\n\n if (channelPostId) {\n actions.focusMessage({ chatId: chat.id, messageId: channelPostId });\n } else {\n actions.openChat({ id: chat.id });\n }\n}\n\nasync function openCommentsByUsername(\n actions: GlobalActions,\n username: string,\n messageId: number,\n commentId: number,\n) {\n actions.openChat({ id: TMP_CHAT_ID });\n\n const chat = await fetchChatByUsername(username);\n\n if (!chat) return;\n\n const global = getGlobal();\n\n const threadInfo = selectThreadInfo(global, chat.id, messageId);\n let discussionChatId: string | undefined;\n\n if (!threadInfo) {\n const result = await callApi('requestThreadInfoUpdate', { chat, threadId: messageId });\n if (!result) return;\n\n discussionChatId = result.discussionChatId;\n } else {\n discussionChatId = threadInfo.chatId;\n }\n\n if (!discussionChatId) return;\n\n actions.focusMessage({\n chatId: discussionChatId,\n threadId: messageId,\n messageId: Number(commentId),\n });\n}\n","import { addReducer, getGlobal, setGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../../global/types';\nimport {\n ApiAttachment,\n ApiChat,\n ApiMessage,\n ApiMessageEntity,\n ApiNewPoll,\n ApiOnProgress,\n ApiSticker,\n ApiVideo,\n MAIN_THREAD_ID,\n MESSAGE_DELETED,\n} from '../../../api/types';\nimport { LoadMoreDirection } from '../../../types';\n\nimport { MAX_MEDIA_FILES_FOR_ALBUM, MESSAGE_LIST_SLICE, SERVICE_NOTIFICATIONS_USER_ID } from '../../../config';\nimport { IS_IOS } from '../../../util/environment';\nimport { callApi, cancelApiProgress } from '../../../api/gramjs';\nimport {\n areSortedArraysIntersecting, buildCollectionByKey, split, unique,\n} from '../../../util/iteratees';\nimport {\n addUsers,\n addChatMessagesById,\n replaceThreadParam,\n safeReplaceViewportIds,\n updateChatMessage,\n addChats,\n updateListedIds,\n updateOutlyingIds,\n replaceScheduledMessages,\n updateThreadInfos,\n updateChat,\n updateThreadUnreadFromForwardedMessage,\n} from '../../reducers';\nimport {\n selectChat,\n selectChatMessage,\n selectCurrentMessageList,\n selectFocusedMessageId,\n selectCurrentChat,\n selectListedIds,\n selectOutlyingIds,\n selectViewportIds,\n selectRealLastReadId,\n selectReplyingToId,\n selectEditingId,\n selectDraft,\n selectThreadOriginChat,\n selectThreadTopMessageId,\n selectEditingScheduledId,\n selectEditingMessage,\n selectScheduledMessage,\n selectNoWebPage,\n selectFirstUnreadId,\n} from '../../selectors';\nimport { debounce, rafPromise } from '../../../util/schedulers';\nimport { isServiceNotificationMessage } from '../../helpers';\n\nconst uploadProgressCallbacks = new Map<number, ApiOnProgress>();\n\nconst runDebouncedForMarkRead = debounce((cb) => cb(), 500, false);\n\naddReducer('loadViewportMessages', (global, actions, payload) => {\n const {\n direction = LoadMoreDirection.Around,\n isBudgetPreload = false,\n } = payload || {};\n\n let { chatId, threadId } = payload || {};\n\n if (!chatId) {\n const currentMessageList = selectCurrentMessageList(global);\n if (!currentMessageList) {\n return undefined;\n }\n\n chatId = currentMessageList.chatId;\n threadId = currentMessageList.threadId;\n }\n\n const chat = selectChat(global, chatId);\n // TODO Revise if `chat.isRestricted` check is needed\n if (!chat || chat.isRestricted) {\n return undefined;\n }\n\n const viewportIds = selectViewportIds(global, chatId, threadId);\n const listedIds = selectListedIds(global, chatId, threadId);\n const outlyingIds = selectOutlyingIds(global, chatId, threadId);\n\n if (!viewportIds || !viewportIds.length || direction === LoadMoreDirection.Around) {\n const offsetId = selectFocusedMessageId(global, chatId) || selectRealLastReadId(global, chatId, threadId);\n const isOutlying = Boolean(offsetId && listedIds && !listedIds.includes(offsetId));\n const historyIds = (isOutlying ? outlyingIds : listedIds) || [];\n const {\n newViewportIds, areSomeLocal, areAllLocal,\n } = getViewportSlice(historyIds, offsetId, LoadMoreDirection.Around);\n\n if (areSomeLocal && newViewportIds.length >= MESSAGE_LIST_SLICE) {\n global = safeReplaceViewportIds(global, chatId, threadId, newViewportIds);\n }\n\n if (!areAllLocal) {\n void loadViewportMessages(chat, threadId, offsetId, LoadMoreDirection.Around, isOutlying, isBudgetPreload);\n }\n } else {\n const offsetId = direction === LoadMoreDirection.Backwards ? viewportIds[0] : viewportIds[viewportIds.length - 1];\n const isOutlying = Boolean(outlyingIds);\n const historyIds = (isOutlying ? outlyingIds : listedIds)!;\n const {\n newViewportIds, areSomeLocal, areAllLocal,\n } = getViewportSlice(historyIds, offsetId, direction);\n\n if (areSomeLocal) {\n global = safeReplaceViewportIds(global, chatId, threadId, newViewportIds);\n }\n\n void loadWithBudget(actions, areAllLocal, isOutlying, isBudgetPreload, chat, threadId, direction, offsetId);\n\n if (isBudgetPreload) {\n return undefined;\n }\n }\n\n return global;\n});\n\nasync function loadWithBudget(\n actions: GlobalActions,\n areAllLocal: boolean, isOutlying: boolean, isBudgetPreload: boolean,\n chat: ApiChat, threadId: number, direction: LoadMoreDirection, offsetId?: number,\n) {\n if (!areAllLocal) {\n await loadViewportMessages(\n chat, threadId, offsetId, direction, isOutlying, isBudgetPreload,\n );\n }\n\n if (!isBudgetPreload) {\n // Let reducer return and update global\n await Promise.resolve();\n actions.loadViewportMessages({\n chatId: chat.id, threadId, direction, isBudgetPreload: true,\n });\n }\n}\n\naddReducer('loadMessage', (global, actions, payload) => {\n const {\n chatId, messageId, replyOriginForId, threadUpdate,\n } = payload!;\n const chat = selectChat(global, chatId);\n\n if (!chat) {\n return;\n }\n\n (async () => {\n const message = await loadMessage(chat, messageId, replyOriginForId);\n if (message && threadUpdate) {\n const { lastMessageId, isDeleting } = threadUpdate;\n\n setGlobal(updateThreadUnreadFromForwardedMessage(\n getGlobal(),\n message,\n chatId,\n lastMessageId,\n isDeleting,\n ));\n }\n })();\n});\n\naddReducer('sendMessage', (global, actions, payload) => {\n const currentMessageList = selectCurrentMessageList(global);\n if (!currentMessageList) {\n return undefined;\n }\n\n const { chatId, threadId, type } = currentMessageList;\n\n if (type === 'scheduled' && !payload.scheduledAt) {\n return {\n ...global,\n messages: {\n ...global.messages,\n contentToBeScheduled: payload,\n },\n };\n }\n\n const chat = selectChat(global, chatId)!;\n\n actions.setReplyingToId({ messageId: undefined });\n actions.clearWebPagePreview({ chatId, threadId, value: false });\n\n const params = {\n ...payload,\n chat,\n replyingTo: selectReplyingToId(global, chatId, threadId),\n noWebPage: selectNoWebPage(global, chatId, threadId),\n };\n\n const isSingle = !payload.attachments || payload.attachments.length <= 1;\n const isGrouped = !isSingle && payload.attachments && payload.attachments.length > 1;\n\n if (isSingle) {\n const { attachments, ...restParams } = params;\n sendMessage({\n ...restParams,\n attachment: attachments ? attachments[0] : undefined,\n });\n } else if (isGrouped) {\n const {\n text, entities, attachments, ...commonParams\n } = params;\n const groupedAttachments = split(attachments, MAX_MEDIA_FILES_FOR_ALBUM);\n for (let i = 0; i < groupedAttachments.length; i++) {\n const [firstAttachment, ...restAttachments] = groupedAttachments[i];\n const groupedId = `${Date.now()}${i}`;\n\n sendMessage({\n ...commonParams,\n text: i === 0 ? text : undefined,\n entities: i === 0 ? entities : undefined,\n attachment: firstAttachment,\n groupedId: restAttachments.length > 0 ? groupedId : undefined,\n });\n\n restAttachments.forEach((attachment: ApiAttachment) => {\n sendMessage({\n ...commonParams,\n attachment,\n groupedId,\n });\n });\n }\n } else {\n const {\n text, entities, attachments, replyingTo, ...commonParams\n } = params;\n\n if (text) {\n sendMessage({\n ...commonParams,\n text,\n entities,\n replyingTo,\n });\n }\n\n attachments.forEach((attachment: ApiAttachment) => {\n sendMessage({\n ...commonParams,\n attachment,\n });\n });\n }\n\n return undefined;\n});\n\naddReducer('editMessage', (global, actions, payload) => {\n const { serverTimeOffset } = global;\n const { text, entities } = payload!;\n\n const currentMessageList = selectCurrentMessageList(global);\n if (!currentMessageList) {\n return;\n }\n\n const { chatId, threadId, type: messageListType } = currentMessageList;\n const chat = selectChat(global, chatId);\n const message = selectEditingMessage(global, chatId, threadId, messageListType);\n if (!chat || !message) {\n return;\n }\n\n void callApi('editMessage', {\n chat, message, text, entities, noWebPage: selectNoWebPage(global, chatId, threadId), serverTimeOffset,\n });\n\n actions.setEditingId({ messageId: undefined });\n});\n\naddReducer('cancelSendingMessage', (global, actions, payload) => {\n const { chatId, messageId } = payload!;\n const message = selectChatMessage(global, chatId, messageId);\n const progressCallback = message && uploadProgressCallbacks.get(message.previousLocalId || message.id);\n if (progressCallback) {\n cancelApiProgress(progressCallback);\n }\n\n actions.apiUpdate({\n '@type': 'deleteMessages',\n ids: [messageId],\n chatId,\n });\n});\n\naddReducer('saveDraft', (global, actions, payload) => {\n const { chatId, threadId, draft } = payload!;\n if (!draft) {\n return undefined;\n }\n\n const { text, entities } = draft;\n const chat = selectChat(global, chatId)!;\n\n if (threadId === MAIN_THREAD_ID) {\n void callApi('saveDraft', {\n chat,\n text,\n entities,\n replyToMsgId: selectReplyingToId(global, chatId, threadId),\n });\n }\n\n global = replaceThreadParam(global, chatId, threadId, 'draft', draft);\n global = updateChat(global, chatId, { draftDate: Math.round(Date.now() / 1000) });\n\n return global;\n});\n\naddReducer('clearDraft', (global, actions, payload) => {\n const { chatId, threadId, localOnly } = payload!;\n if (!selectDraft(global, chatId, threadId)) {\n return undefined;\n }\n\n const chat = selectChat(global, chatId)!;\n\n if (!localOnly && threadId === MAIN_THREAD_ID) {\n void callApi('clearDraft', chat);\n }\n\n global = replaceThreadParam(global, chatId, threadId, 'draft', undefined);\n global = updateChat(global, chatId, { draftDate: undefined });\n\n return global;\n});\n\naddReducer('toggleMessageWebPage', (global, actions, payload) => {\n const { chatId, threadId, noWebPage } = payload!;\n\n return replaceThreadParam(global, chatId, threadId, 'noWebPage', noWebPage);\n});\n\naddReducer('pinMessage', (global, actions, payload) => {\n const chat = selectCurrentChat(global);\n if (!chat) {\n return;\n }\n\n const {\n messageId, isUnpin, isOneSide, isSilent,\n } = payload!;\n\n void callApi('pinMessage', {\n chat, messageId, isUnpin, isOneSide, isSilent,\n });\n});\n\naddReducer('unpinAllMessages', (global, actions, payload) => {\n const chat = selectChat(global, payload.chatId);\n if (!chat) {\n return;\n }\n\n void unpinAllMessages(chat);\n});\n\nasync function unpinAllMessages(chat: ApiChat) {\n await callApi('unpinAllMessages', { chat });\n let global = getGlobal();\n global = replaceThreadParam(global, chat.id, MAIN_THREAD_ID, 'pinnedIds', []);\n setGlobal(global);\n}\n\naddReducer('deleteMessages', (global, actions, payload) => {\n const { messageIds, shouldDeleteForAll } = payload!;\n const currentMessageList = selectCurrentMessageList(global);\n if (!currentMessageList) {\n return;\n }\n const { chatId, threadId } = currentMessageList;\n const chat = selectChat(global, chatId)!;\n\n void callApi('deleteMessages', { chat, messageIds, shouldDeleteForAll });\n\n const editingId = selectEditingId(global, chatId, threadId);\n if (messageIds.includes(editingId)) {\n actions.setEditingId({ messageId: undefined });\n }\n});\n\naddReducer('deleteScheduledMessages', (global, actions, payload) => {\n const { messageIds } = payload!;\n const currentMessageList = selectCurrentMessageList(global);\n if (!currentMessageList) {\n return;\n }\n\n const { chatId } = currentMessageList;\n const chat = selectChat(global, chatId)!;\n\n void callApi('deleteScheduledMessages', { chat, messageIds });\n\n const editingId = selectEditingScheduledId(global, chatId);\n if (messageIds.includes(editingId)) {\n actions.setEditingId({ messageId: undefined });\n }\n});\n\naddReducer('deleteHistory', (global, actions, payload) => {\n (async () => {\n const { chatId, shouldDeleteForAll } = payload!;\n const chat = selectChat(global, chatId);\n if (!chat) {\n return;\n }\n\n const maxId = chat.lastMessage?.id;\n\n await callApi('deleteHistory', { chat, shouldDeleteForAll, maxId });\n\n const activeChat = selectCurrentMessageList(global);\n if (activeChat && activeChat.chatId === chatId) {\n actions.openChat({ id: undefined });\n }\n })();\n});\n\naddReducer('reportMessages', (global, actions, payload) => {\n (async () => {\n const {\n messageIds, reason, description,\n } = payload!;\n const currentMessageList = selectCurrentMessageList(global);\n if (!currentMessageList) {\n return;\n }\n\n const { chatId } = currentMessageList;\n const chat = selectChat(global, chatId)!;\n\n const result = await callApi('reportMessages', {\n peer: chat, messageIds, reason, description,\n });\n\n actions.showNotification({\n message: result\n ? 'Thank you! Your report will be reviewed by our team.'\n : 'Error occured while submiting report. Please, try again later.',\n });\n })();\n});\n\naddReducer('markMessageListRead', (global, actions, payload) => {\n const { serverTimeOffset } = global;\n const currentMessageList = selectCurrentMessageList(global);\n if (!currentMessageList) {\n return undefined;\n }\n\n const { chatId, threadId } = currentMessageList;\n const chat = selectThreadOriginChat(global, chatId, threadId);\n if (!chat) {\n return undefined;\n }\n\n const { maxId } = payload!;\n\n runDebouncedForMarkRead(() => {\n void callApi('markMessageListRead', {\n serverTimeOffset, chat, threadId, maxId,\n });\n });\n\n // TODO Support local marking read for threads\n if (threadId !== MAIN_THREAD_ID) {\n return undefined;\n }\n\n if (chatId === SERVICE_NOTIFICATIONS_USER_ID) {\n global = {\n ...global,\n serviceNotifications: global.serviceNotifications.map((notification) => {\n return notification.isUnread && notification.id <= maxId ? { ...notification, isUnread: false } : notification;\n }),\n };\n }\n\n const viewportIds = selectViewportIds(global, chatId, threadId);\n const minId = selectFirstUnreadId(global, chatId, threadId);\n if (!viewportIds || !minId || !chat.unreadCount) {\n return global;\n }\n\n const readCount = countSortedIds(viewportIds!, minId, maxId);\n if (!readCount) {\n return global;\n }\n\n return updateChat(global, chatId, {\n lastReadInboxMessageId: maxId,\n unreadCount: Math.max(0, chat.unreadCount - readCount),\n });\n});\n\naddReducer('markMessagesRead', (global, actions, payload) => {\n const chat = selectCurrentChat(global);\n if (!chat) {\n return;\n }\n\n const { messageIds } = payload!;\n\n void callApi('markMessagesRead', { chat, messageIds });\n});\n\naddReducer('loadWebPagePreview', (global, actions, payload) => {\n const { text } = payload!;\n void loadWebPagePreview(text);\n});\n\naddReducer('clearWebPagePreview', (global) => {\n if (!global.webPagePreview) {\n return undefined;\n }\n\n return {\n ...global,\n webPagePreview: undefined,\n };\n});\n\naddReducer('sendPollVote', (global, actions, payload) => {\n const { chatId, messageId, options } = payload!;\n const chat = selectChat(global, chatId);\n\n if (chat) {\n void callApi('sendPollVote', { chat, messageId, options });\n }\n});\n\naddReducer('loadPollOptionResults', (global, actions, payload) => {\n const {\n chat, messageId, option, offset, limit, shouldResetVoters,\n } = payload!;\n\n void loadPollOptionResults(chat, messageId, option, offset, limit, shouldResetVoters);\n});\n\naddReducer('forwardMessages', (global, action, payload) => {\n const { fromChatId, messageIds, toChatId } = global.forwardMessages;\n const fromChat = fromChatId ? selectChat(global, fromChatId) : undefined;\n const toChat = toChatId ? selectChat(global, toChatId) : undefined;\n const messages = fromChatId && messageIds\n ? messageIds\n .sort((a, b) => a - b)\n .map((id) => selectChatMessage(global, fromChatId, id)).filter<ApiMessage>(Boolean as any)\n : undefined;\n\n if (!fromChat || !toChat || !messages) {\n return;\n }\n\n const { isSilent, scheduledAt } = payload;\n\n const realMessages = messages.filter((m) => !isServiceNotificationMessage(m));\n if (realMessages.length) {\n void callApi('forwardMessages', {\n fromChat,\n toChat,\n messages: realMessages,\n serverTimeOffset: getGlobal().serverTimeOffset,\n isSilent,\n scheduledAt,\n });\n }\n\n messages\n .filter((m) => isServiceNotificationMessage(m))\n .forEach((message) => {\n const { text, entities } = message.content.text || {};\n const { sticker, poll } = message.content;\n\n void sendMessage({\n chat: toChat,\n text,\n entities,\n sticker,\n poll,\n isSilent,\n scheduledAt,\n });\n });\n\n setGlobal({\n ...getGlobal(),\n forwardMessages: {},\n });\n});\n\naddReducer('loadScheduledHistory', (global, actions, payload) => {\n const { chatId } = payload;\n const chat = selectChat(global, chatId);\n if (!chat) {\n return;\n }\n\n void loadScheduledHistory(chat);\n});\n\naddReducer('sendScheduledMessages', (global, actions, payload) => {\n const {\n chatId, id,\n } = payload!;\n\n const chat = selectChat(global, chatId);\n\n if (!chat) {\n return;\n }\n\n void callApi('sendScheduledMessages', {\n chat,\n ids: [id],\n });\n});\n\naddReducer('rescheduleMessage', (global, actions, payload) => {\n const {\n chatId, messageId, scheduledAt,\n } = payload!;\n\n const chat = selectChat(global, chatId);\n const message = chat && selectScheduledMessage(global, chat.id, messageId);\n if (!chat || !message) {\n return;\n }\n\n void callApi('rescheduleMessage', {\n chat,\n message,\n scheduledAt,\n });\n});\n\naddReducer('requestThreadInfoUpdate', (global, actions, payload) => {\n const { chatId, threadId } = payload;\n const chat = selectThreadOriginChat(global, chatId, threadId);\n if (!chat) {\n return;\n }\n\n void callApi('requestThreadInfoUpdate', { chat, threadId });\n});\n\nasync function loadWebPagePreview(message: string) {\n const webPagePreview = await callApi('fetchWebPagePreview', { message });\n\n setGlobal({\n ...getGlobal(),\n webPagePreview,\n });\n}\n\nasync function loadViewportMessages(\n chat: ApiChat,\n threadId: number,\n offsetId: number | undefined,\n direction: LoadMoreDirection,\n isOutlying = false,\n isBudgetPreload = false,\n) {\n const chatId = chat.id;\n\n let addOffset: number | undefined;\n switch (direction) {\n case LoadMoreDirection.Backwards:\n addOffset = undefined;\n break;\n case LoadMoreDirection.Around:\n addOffset = -(Math.round(MESSAGE_LIST_SLICE / 2) + 1);\n break;\n case LoadMoreDirection.Forwards:\n addOffset = -(MESSAGE_LIST_SLICE + 1);\n break;\n }\n\n const result = await callApi('fetchMessages', {\n chat: selectThreadOriginChat(getGlobal(), chatId, threadId)!,\n offsetId,\n addOffset,\n limit: MESSAGE_LIST_SLICE,\n threadId,\n });\n\n if (!result) {\n return;\n }\n\n const {\n messages, users, chats, threadInfos,\n } = result;\n\n let global = getGlobal();\n\n const localMessages = chatId === SERVICE_NOTIFICATIONS_USER_ID\n ? global.serviceNotifications.map(({ message }) => message)\n : [];\n const allMessages = ([] as ApiMessage[]).concat(messages, localMessages);\n const byId = buildCollectionByKey(allMessages, 'id');\n const ids = Object.keys(byId).map(Number);\n\n global = addChatMessagesById(global, chatId, byId);\n global = isOutlying\n ? updateOutlyingIds(global, chatId, threadId, ids)\n : updateListedIds(global, chatId, threadId, ids);\n\n global = addUsers(global, buildCollectionByKey(users, 'id'));\n global = addChats(global, buildCollectionByKey(chats, 'id'));\n global = updateThreadInfos(global, chatId, threadInfos);\n\n let listedIds = selectListedIds(global, chatId, threadId);\n const outlyingIds = selectOutlyingIds(global, chatId, threadId);\n\n if (isOutlying && listedIds && outlyingIds) {\n if (!outlyingIds.length || areSortedArraysIntersecting(listedIds, outlyingIds)) {\n global = updateListedIds(global, chatId, threadId, outlyingIds);\n listedIds = selectListedIds(global, chatId, threadId);\n global = replaceThreadParam(global, chatId, threadId, 'outlyingIds', undefined);\n isOutlying = false;\n }\n }\n\n if (!isBudgetPreload) {\n const historyIds = isOutlying ? outlyingIds! : listedIds!;\n const { newViewportIds } = getViewportSlice(historyIds, offsetId, direction);\n global = safeReplaceViewportIds(global, chatId, threadId, newViewportIds!);\n }\n\n setGlobal(global);\n}\n\nasync function loadMessage(chat: ApiChat, messageId: number, replyOriginForId: number) {\n const result = await callApi('fetchMessage', { chat, messageId });\n if (!result) {\n return undefined;\n }\n\n if (result === MESSAGE_DELETED) {\n if (replyOriginForId) {\n let global = getGlobal();\n const replyMessage = selectChatMessage(global, chat.id, replyOriginForId);\n global = updateChatMessage(global, chat.id, replyOriginForId, {\n ...replyMessage,\n replyToMessageId: undefined,\n });\n setGlobal(global);\n }\n\n return undefined;\n }\n\n let global = getGlobal();\n global = updateChatMessage(global, chat.id, messageId, result.message);\n global = addUsers(global, buildCollectionByKey(result.users, 'id'));\n setGlobal(global);\n\n return result.message;\n}\n\nfunction findClosestIndex(sourceIds: number[], offsetId: number) {\n if (offsetId < sourceIds[0]) {\n return 0;\n }\n\n if (offsetId > sourceIds[sourceIds.length - 1]) {\n return sourceIds.length - 1;\n }\n\n return sourceIds.findIndex((id, i) => (\n id === offsetId\n || (id < offsetId && sourceIds[i + 1] > offsetId)\n ));\n}\n\nfunction getViewportSlice(\n sourceIds: number[],\n offsetId: number | undefined,\n direction: LoadMoreDirection,\n) {\n const { length } = sourceIds;\n const index = offsetId ? findClosestIndex(sourceIds, offsetId) : -1;\n const isBackwards = direction === LoadMoreDirection.Backwards;\n const indexForDirection = isBackwards ? index : (index + 1) || length;\n const from = indexForDirection - MESSAGE_LIST_SLICE;\n const to = indexForDirection + MESSAGE_LIST_SLICE - 1;\n const newViewportIds = sourceIds.slice(Math.max(0, from), to + 1);\n\n let areSomeLocal;\n let areAllLocal;\n switch (direction) {\n case LoadMoreDirection.Backwards:\n areSomeLocal = indexForDirection > 0;\n areAllLocal = from >= 0;\n break;\n case LoadMoreDirection.Forwards:\n areSomeLocal = indexForDirection < length;\n areAllLocal = to <= length - 1;\n break;\n case LoadMoreDirection.Around:\n default:\n areSomeLocal = newViewportIds.length > 0;\n areAllLocal = newViewportIds.length === MESSAGE_LIST_SLICE;\n break;\n }\n\n return { newViewportIds, areSomeLocal, areAllLocal };\n}\n\nasync function sendMessage(params: {\n chat: ApiChat;\n text?: string;\n entities?: ApiMessageEntity[];\n replyingTo?: number;\n attachment?: ApiAttachment;\n sticker?: ApiSticker;\n gif?: ApiVideo;\n poll?: ApiNewPoll;\n serverTimeOffset?: number;\n isSilent?: boolean;\n scheduledAt?: number;\n}) {\n let localId: number | undefined;\n const progressCallback = params.attachment ? (progress: number, messageLocalId: number) => {\n if (!uploadProgressCallbacks.has(messageLocalId)) {\n localId = messageLocalId;\n uploadProgressCallbacks.set(messageLocalId, progressCallback!);\n }\n\n const global = getGlobal();\n\n setGlobal({\n ...global,\n fileUploads: {\n byMessageLocalId: {\n ...global.fileUploads.byMessageLocalId,\n [messageLocalId]: { progress },\n },\n },\n });\n } : undefined;\n\n // @optimization\n if (params.replyingTo || IS_IOS) {\n await rafPromise();\n }\n\n const global = getGlobal();\n params.serverTimeOffset = global.serverTimeOffset;\n const currentMessageList = selectCurrentMessageList(global);\n if (!currentMessageList) {\n return;\n }\n const { threadId } = currentMessageList;\n\n if (!params.replyingTo && threadId !== MAIN_THREAD_ID) {\n params.replyingTo = selectThreadTopMessageId(global, params.chat.id, threadId)!;\n }\n\n await callApi('sendMessage', params, progressCallback);\n\n if (progressCallback && localId) {\n uploadProgressCallbacks.delete(localId);\n }\n}\n\nasync function loadPollOptionResults(\n chat: ApiChat,\n messageId: number,\n option: string,\n offset?: string,\n limit?: number,\n shouldResetVoters?: boolean,\n) {\n const result = await callApi('loadPollOptionResults', {\n chat, messageId, option, offset, limit,\n });\n\n if (!result) {\n return;\n }\n\n let global = getGlobal();\n\n global = addUsers(global, buildCollectionByKey(result.users, 'id'));\n const { voters } = global.pollResults;\n\n setGlobal({\n ...global,\n pollResults: {\n ...global.pollResults,\n voters: {\n ...voters,\n [option]: unique([\n ...(!shouldResetVoters && voters && voters[option] ? voters[option] : []),\n ...(result && result.users.map((user) => user.id)),\n ]),\n },\n offsets: {\n ...(global.pollResults.offsets ? global.pollResults.offsets : {}),\n [option]: result.nextOffset || '',\n },\n },\n });\n}\n\naddReducer('loadPinnedMessages', (global, actions, payload) => {\n const { chatId } = payload;\n const chat = selectChat(global, chatId);\n if (!chat) {\n return;\n }\n\n void loadPinnedMessages(chat);\n});\n\nasync function loadPinnedMessages(chat: ApiChat) {\n const result = await callApi('fetchPinnedMessages', { chat });\n if (!result) {\n return;\n }\n\n const { messages, chats, users } = result;\n\n const byId = buildCollectionByKey(messages, 'id');\n const ids = Object.keys(byId).map(Number).sort((a, b) => b - a);\n\n let global = getGlobal();\n global = addChatMessagesById(global, chat.id, byId);\n global = replaceThreadParam(global, chat.id, MAIN_THREAD_ID, 'pinnedIds', ids);\n global = addUsers(global, buildCollectionByKey(users, 'id'));\n global = addChats(global, buildCollectionByKey(chats, 'id'));\n setGlobal(global);\n}\n\nasync function loadScheduledHistory(chat: ApiChat) {\n const result = await callApi('fetchScheduledHistory', { chat });\n if (!result) {\n return;\n }\n\n const { messages } = result;\n\n const byId = buildCollectionByKey(messages, 'id');\n const ids = Object.keys(byId).map(Number).sort((a, b) => b - a);\n\n let global = getGlobal();\n global = replaceScheduledMessages(global, chat.id, byId);\n global = replaceThreadParam(global, chat.id, MAIN_THREAD_ID, 'scheduledIds', ids);\n setGlobal(global);\n}\n\nfunction countSortedIds(ids: number[], from: number, to: number) {\n let count = 0;\n\n for (let i = 0, l = ids.length; i < l; i++) {\n if (ids[i] >= from && ids[i] <= to) {\n count++;\n }\n\n if (ids[i] >= to) {\n break;\n }\n }\n\n return count;\n}\n","import { addReducer, getGlobal, setGlobal } from '../../../lib/teact/teactn';\n\nimport { ApiSticker } from '../../../api/types';\nimport { LangCode } from '../../../types';\nimport { callApi } from '../../../api/gramjs';\nimport { pause, throttle } from '../../../util/schedulers';\nimport {\n updateStickerSets,\n updateStickerSet,\n replaceAnimatedEmojis,\n updateGifSearch,\n updateStickersForEmoji,\n rebuildStickersForEmoji,\n} from '../../reducers';\nimport searchWords from '../../../util/searchWords';\nimport { selectStickerSet } from '../../selectors';\n\nconst ADDED_SETS_THROTTLE = 500;\nconst ADDED_SETS_THROTTLE_CHUNK = 50;\n\nconst searchThrottled = throttle((cb) => cb(), 500, false);\n\naddReducer('loadStickerSets', (global) => {\n const { hash } = global.stickers.added || {};\n void loadStickerSets(hash);\n});\n\naddReducer('loadAddedStickers', (global, actions) => {\n const { setIds: addedSetIds } = global.stickers.added;\n if (!addedSetIds || !addedSetIds.length) {\n return;\n }\n\n (async () => {\n for (let i = 0; i < addedSetIds.length; i++) {\n actions.loadStickers({ stickerSetId: addedSetIds[i] });\n\n if (i % ADDED_SETS_THROTTLE_CHUNK === 0 && i > 0) {\n await pause(ADDED_SETS_THROTTLE);\n }\n }\n })();\n});\n\naddReducer('loadRecentStickers', (global) => {\n const { hash } = global.stickers.recent || {};\n void loadRecentStickers(hash);\n});\n\naddReducer('loadFavoriteStickers', (global) => {\n const { hash } = global.stickers.favorite || {};\n void loadFavoriteStickers(hash);\n});\n\naddReducer('loadGreetingStickers', (global) => {\n const { hash } = global.stickers.greeting || {};\n\n (async () => {\n const greeting = await callApi('fetchStickersForEmoji', { emoji: '👋⭐️', hash });\n\n if (!greeting) {\n return;\n }\n\n const newGlobal = getGlobal();\n\n setGlobal({\n ...newGlobal,\n stickers: {\n ...newGlobal.stickers,\n greeting: {\n hash: greeting.hash,\n stickers: greeting.stickers.filter((sticker) => sticker.emoji === '👋'),\n },\n },\n });\n })();\n});\n\naddReducer('loadFeaturedStickers', (global) => {\n const { hash } = global.stickers.featured || {};\n void loadFeaturedStickers(hash);\n});\n\naddReducer('loadStickers', (global, actions, payload) => {\n const { stickerSetId, stickerSetShortName } = payload!;\n let { stickerSetAccessHash } = payload!;\n\n if (!stickerSetAccessHash && !stickerSetShortName) {\n const stickerSet = selectStickerSet(global, stickerSetId);\n if (!stickerSet) {\n return;\n }\n\n stickerSetAccessHash = stickerSet.accessHash;\n }\n\n void loadStickers(stickerSetId, stickerSetAccessHash, stickerSetShortName);\n});\n\naddReducer('loadAnimatedEmojis', () => {\n void loadAnimatedEmojis();\n});\n\naddReducer('loadSavedGifs', (global) => {\n const { hash } = global.gifs.saved;\n void loadSavedGifs(hash);\n});\n\naddReducer('faveSticker', (global, actions, payload) => {\n const { sticker } = payload!;\n\n if (sticker) {\n void callApi('faveSticker', { sticker });\n }\n});\n\naddReducer('unfaveSticker', (global, actions, payload) => {\n const { sticker } = payload!;\n\n if (sticker) {\n void unfaveSticker(sticker);\n }\n});\n\naddReducer('toggleStickerSet', (global, actions, payload) => {\n const { stickerSetId } = payload!;\n const stickerSet = selectStickerSet(global, stickerSetId);\n if (!stickerSet) {\n return;\n }\n\n const { accessHash, installedDate } = stickerSet;\n\n void callApi(!installedDate ? 'installStickerSet' : 'uninstallStickerSet', { stickerSetId, accessHash });\n});\n\naddReducer('loadEmojiKeywords', (global, actions, payload: { language: LangCode }) => {\n const { language } = payload;\n\n let currentEmojiKeywords = global.emojiKeywords[language];\n if (currentEmojiKeywords?.isLoading) {\n return;\n }\n\n setGlobal({\n ...global,\n emojiKeywords: {\n ...global.emojiKeywords,\n [language]: {\n ...currentEmojiKeywords,\n isLoading: true,\n },\n },\n });\n\n (async () => {\n const emojiKeywords = await callApi('fetchEmojiKeywords', {\n language,\n fromVersion: currentEmojiKeywords ? currentEmojiKeywords.version : 0,\n });\n\n global = getGlobal();\n currentEmojiKeywords = global.emojiKeywords[language];\n\n if (!emojiKeywords) {\n setGlobal({\n ...global,\n emojiKeywords: {\n ...global.emojiKeywords,\n [language]: {\n ...currentEmojiKeywords,\n isLoading: false,\n },\n },\n });\n\n return;\n }\n\n setGlobal({\n ...global,\n emojiKeywords: {\n ...global.emojiKeywords,\n [language]: {\n isLoading: false,\n version: emojiKeywords.version,\n keywords: {\n ...(currentEmojiKeywords?.keywords),\n ...emojiKeywords.keywords,\n },\n },\n },\n });\n })();\n});\n\nasync function loadStickerSets(hash?: string) {\n const addedStickers = await callApi('fetchStickerSets', { hash });\n if (!addedStickers) {\n return;\n }\n\n setGlobal(updateStickerSets(\n getGlobal(),\n 'added',\n addedStickers.hash,\n addedStickers.sets,\n ));\n}\n\nasync function loadRecentStickers(hash?: string) {\n const recentStickers = await callApi('fetchRecentStickers', { hash });\n if (!recentStickers) {\n return;\n }\n\n const global = getGlobal();\n\n setGlobal({\n ...global,\n stickers: {\n ...global.stickers,\n recent: recentStickers,\n },\n });\n}\n\nasync function loadFavoriteStickers(hash?: string) {\n const favoriteStickers = await callApi('fetchFavoriteStickers', { hash });\n if (!favoriteStickers) {\n return;\n }\n\n const global = getGlobal();\n\n setGlobal({\n ...global,\n stickers: {\n ...global.stickers,\n favorite: favoriteStickers,\n },\n });\n}\n\nasync function loadFeaturedStickers(hash?: string) {\n const featuredStickers = await callApi('fetchFeaturedStickers', { hash });\n if (!featuredStickers) {\n return;\n }\n\n setGlobal(updateStickerSets(\n getGlobal(),\n 'featured',\n featuredStickers.hash,\n featuredStickers.sets,\n ));\n}\n\nasync function loadStickers(stickerSetId: string, accessHash: string, stickerSetShortName?: string) {\n const stickerSet = await callApi(\n 'fetchStickers',\n { stickerSetShortName, stickerSetId, accessHash },\n );\n if (!stickerSet) {\n return;\n }\n\n const { set, stickers, packs } = stickerSet;\n\n let global = getGlobal();\n\n global = updateStickerSet(global, set.id, { ...set, stickers, packs });\n\n const currentEmoji = global.stickers.forEmoji.emoji;\n if (currentEmoji && packs[currentEmoji]) {\n global = rebuildStickersForEmoji(global);\n }\n\n setGlobal(global);\n}\n\nasync function loadAnimatedEmojis() {\n const stickerSet = await callApi('fetchAnimatedEmojis');\n if (!stickerSet) {\n return;\n }\n\n const { set, stickers } = stickerSet;\n\n setGlobal(replaceAnimatedEmojis(getGlobal(), { ...set, stickers }));\n}\n\nfunction unfaveSticker(sticker: ApiSticker) {\n const global = getGlobal();\n\n // Remove sticker preemptively to get instant feedback when user removes sticker\n // from favorites while in Sticker Picker\n setGlobal({\n ...global,\n stickers: {\n ...global.stickers,\n favorite: {\n ...global.stickers.favorite,\n stickers: global.stickers.favorite.stickers.filter(({ id }) => id !== sticker.id),\n },\n },\n });\n\n void callApi('faveSticker', { sticker, unfave: true });\n}\n\naddReducer('setStickerSearchQuery', (global, actions, payload) => {\n const { query } = payload!;\n\n if (query) {\n void searchThrottled(() => {\n searchStickers(query);\n });\n }\n});\n\naddReducer('setGifSearchQuery', (global, actions, payload) => {\n const { query } = payload!;\n\n if (typeof query === 'string') {\n void searchThrottled(() => {\n searchGifs(query);\n });\n }\n});\n\naddReducer('searchMoreGifs', (global) => {\n const { query, offset } = global.gifs.search;\n\n if (typeof query === 'string') {\n void searchThrottled(() => {\n searchGifs(query, offset);\n });\n }\n});\n\naddReducer('loadStickersForEmoji', (global, actions, payload) => {\n const { emoji } = payload!;\n const { hash } = global.stickers.forEmoji;\n\n void searchThrottled(() => {\n loadStickersForEmoji(emoji, hash);\n });\n});\n\naddReducer('clearStickersForEmoji', (global) => {\n return {\n ...global,\n stickers: {\n ...global.stickers,\n forEmoji: {},\n },\n };\n});\n\naddReducer('openStickerSetShortName', (global, actions, payload) => {\n const { stickerSetShortName } = payload!;\n return {\n ...global,\n openedStickerSetShortName: stickerSetShortName,\n };\n});\n\nasync function searchStickers(query: string, hash?: string) {\n const result = await callApi('searchStickers', { query, hash });\n\n if (!result) {\n return;\n }\n\n const global = getGlobal();\n const { setsById, added } = global.stickers;\n\n const resultIds = result.sets.map(({ id }) => id);\n\n if (added.setIds) {\n added.setIds.forEach((id) => {\n if (!resultIds.includes(id)) {\n const { title } = setsById[id] || {};\n if (title && searchWords(title, query)) {\n resultIds.unshift(id);\n }\n }\n });\n }\n\n setGlobal(updateStickerSets(\n global,\n 'search',\n result.hash,\n result.sets,\n resultIds,\n ));\n}\n\nasync function searchGifs(query: string, offset?: string) {\n const result = await callApi('searchGifs', { query, offset });\n if (!result) {\n return;\n }\n\n setGlobal(updateGifSearch(getGlobal(), !offset, result.gifs, result.nextOffset));\n}\n\nasync function loadSavedGifs(hash?: string) {\n const savedGifs = await callApi('fetchSavedGifs', { hash });\n if (!savedGifs) {\n return;\n }\n\n const global = getGlobal();\n\n setGlobal({\n ...global,\n gifs: {\n ...global.gifs,\n saved: savedGifs,\n },\n });\n}\n\nasync function loadStickersForEmoji(emoji: string, hash?: string) {\n let global = getGlobal();\n setGlobal({\n ...global,\n stickers: {\n ...global.stickers,\n forEmoji: {\n ...global.stickers.forEmoji,\n emoji,\n },\n },\n });\n\n const result = await callApi('fetchStickersForEmoji', { emoji, hash });\n\n global = getGlobal();\n\n if (!result || global.stickers.forEmoji.emoji !== emoji) {\n return;\n }\n\n global = updateStickersForEmoji(global, emoji, result.stickers, result.hash);\n\n setGlobal(global);\n}\n","import { addReducer, getGlobal, setGlobal } from '../../../lib/teact/teactn';\n\nimport { callApi } from '../../../api/gramjs';\nimport { ApiChat, ApiGlobalMessageSearchType } from '../../../api/types';\n\nimport {\n addChats,\n addMessages,\n addUsers,\n updateGlobalSearch,\n updateGlobalSearchFetchingStatus,\n updateGlobalSearchResults,\n} from '../../reducers';\nimport { throttle } from '../../../util/schedulers';\nimport { selectChat, selectCurrentGlobalSearchQuery } from '../../selectors';\nimport { buildCollectionByKey } from '../../../util/iteratees';\nimport { GLOBAL_SEARCH_SLICE } from '../../../config';\nimport { timestampPlusDay } from '../../../util/dateFormat';\n\nconst searchThrottled = throttle((cb) => cb(), 500, false);\n\naddReducer('setGlobalSearchQuery', (global, actions, payload) => {\n const { chatId } = global.globalSearch;\n const { query } = payload!;\n\n if (query && !chatId) {\n void searchThrottled(() => {\n searchChats(query);\n });\n }\n});\n\naddReducer('setGlobalSearchDate', (global, actions, payload) => {\n const { date } = payload!;\n const maxDate = date ? timestampPlusDay(date) : date;\n const newGlobal = updateGlobalSearch(global, {\n date,\n query: '',\n resultsByType: {\n ...global.globalSearch.resultsByType,\n text: {\n totalCount: undefined,\n foundIds: [],\n nextOffsetId: 0,\n },\n },\n });\n setGlobal(newGlobal);\n const { chatId } = global.globalSearch;\n const chat = chatId ? selectChat(global, chatId) : undefined;\n searchMessagesGlobal('', 'text', undefined, chat, maxDate, date);\n});\n\naddReducer('searchMessagesGlobal', (global, actions, payload) => {\n const {\n query, resultsByType, chatId, date,\n } = global.globalSearch;\n const maxDate = date ? timestampPlusDay(date) : date;\n const { type } = payload;\n const nextOffsetId = (resultsByType?.[type as ApiGlobalMessageSearchType])?.nextOffsetId;\n\n const chat = chatId ? selectChat(global, chatId) : undefined;\n\n searchMessagesGlobal(query, type, nextOffsetId, chat, maxDate, date);\n});\n\nasync function searchChats(query: string) {\n const result = await callApi('searchChats', { query });\n\n let global = getGlobal();\n const currentSearchQuery = selectCurrentGlobalSearchQuery(global);\n if (!result || !currentSearchQuery || (query !== currentSearchQuery)) {\n setGlobal(updateGlobalSearchFetchingStatus(global, { chats: false }));\n return;\n }\n\n const {\n localChats, localUsers, globalChats, globalUsers,\n } = result;\n\n if (localChats.length || globalChats.length) {\n global = addChats(global, buildCollectionByKey([...localChats, ...globalChats], 'id'));\n }\n\n if (localUsers.length || globalUsers.length) {\n global = addUsers(global, buildCollectionByKey([...localUsers, ...globalUsers], 'id'));\n }\n\n global = updateGlobalSearchFetchingStatus(global, { chats: false });\n global = updateGlobalSearch(global, {\n localResults: {\n chatIds: localChats.map(({ id }) => id),\n userIds: localUsers.map(({ id }) => id),\n },\n globalResults: {\n ...global.globalSearch.globalResults,\n chatIds: globalChats.map(({ id }) => id),\n userIds: globalUsers.map(({ id }) => id),\n },\n });\n\n setGlobal(global);\n}\n\nasync function searchMessagesGlobal(\n query = '', type: ApiGlobalMessageSearchType, offsetRate?: number, chat?: ApiChat, maxDate?: number, minDate?: number,\n) {\n let result;\n\n if (chat) {\n const localResult = await callApi('searchMessagesLocal', {\n chatOrUser: chat,\n query,\n type,\n limit: GLOBAL_SEARCH_SLICE,\n offsetId: offsetRate,\n minDate,\n maxDate,\n });\n\n if (localResult) {\n const {\n messages, users, totalCount, nextOffsetId,\n } = localResult;\n\n result = {\n messages,\n users,\n chats: [],\n totalCount,\n nextRate: nextOffsetId,\n };\n }\n } else {\n result = await callApi('searchMessagesGlobal', {\n query,\n offsetRate,\n limit: GLOBAL_SEARCH_SLICE,\n type,\n maxDate,\n minDate,\n });\n }\n\n let global = getGlobal();\n const currentSearchQuery = selectCurrentGlobalSearchQuery(global);\n if (!result || (query !== '' && query !== currentSearchQuery)) {\n setGlobal(updateGlobalSearchFetchingStatus(global, { messages: false }));\n return;\n }\n\n const {\n messages, users, chats, totalCount, nextRate,\n } = result;\n\n if (chats.length) {\n global = addChats(global, buildCollectionByKey(chats, 'id'));\n }\n\n if (users.length) {\n global = addUsers(global, buildCollectionByKey(users, 'id'));\n }\n\n if (messages.length) {\n global = addMessages(global, messages);\n }\n\n global = updateGlobalSearchResults(\n global,\n messages,\n totalCount,\n type,\n nextRate,\n );\n\n setGlobal(global);\n}\n","import {\n addReducer, getDispatch, getGlobal, setGlobal,\n} from '../../../lib/teact/teactn';\n\nimport { ApiChat, ApiUser, MAIN_THREAD_ID } from '../../../api/types';\n\nimport { MESSAGE_SEARCH_SLICE, SHARED_MEDIA_SLICE } from '../../../config';\nimport { callApi } from '../../../api/gramjs';\nimport {\n selectCurrentTextSearch,\n selectCurrentMediaSearchPeerId,\n selectCurrentMediaSearch, selectCurrentMessageList, selectChat, selectThreadInfo,\n} from '../../selectors';\nimport { buildCollectionByKey } from '../../../util/iteratees';\nimport {\n addChatMessagesById,\n addUsers,\n updateLocalMediaSearchResults,\n updateLocalTextSearchResults,\n} from '../../reducers';\nimport { SharedMediaType } from '../../../types';\n\naddReducer('searchTextMessagesLocal', (global) => {\n const { chatId, threadId } = selectCurrentMessageList(global) || {};\n const chat = chatId ? selectChat(global, chatId) : undefined;\n const currentSearch = selectCurrentTextSearch(global);\n if (!chat || !currentSearch || !threadId) {\n return;\n }\n\n const { query, results } = currentSearch;\n const offsetId = results?.nextOffsetId;\n\n let topMessageId: number | undefined;\n if (threadId !== MAIN_THREAD_ID) {\n const threadInfo = selectThreadInfo(global, chatId!, threadId);\n topMessageId = threadInfo?.topMessageId;\n }\n\n void searchTextMessages(chat, threadId, topMessageId, query, offsetId);\n});\n\naddReducer('searchMediaMessagesLocal', (global) => {\n const peerId = selectCurrentMediaSearchPeerId(global);\n const chatOrUser = peerId\n ? global.users.byId[peerId] || global.chats.byId[peerId]\n : undefined;\n const currentSearch = selectCurrentMediaSearch(global);\n\n if (!chatOrUser || !currentSearch) {\n return;\n }\n\n const { currentType: type, resultsByType } = currentSearch;\n const currentResults = type && resultsByType && resultsByType[type];\n const offsetId = currentResults?.nextOffsetId;\n\n if (!type) {\n return;\n }\n\n void searchSharedMedia(chatOrUser, type, offsetId);\n});\n\naddReducer('searchMessagesByDate', (global, actions, payload) => {\n const { timestamp } = payload!;\n\n const { chatId } = selectCurrentMessageList(global) || {};\n if (!chatId) {\n return;\n }\n\n const chat = selectChat(global, chatId);\n if (!chat) {\n return;\n }\n\n void searchMessagesByDate(chat, timestamp);\n});\n\nasync function searchTextMessages(\n chatOrUser: ApiChat,\n threadId: number,\n topMessageId?: number,\n query?: string,\n offsetId?: number,\n) {\n const result = await callApi('searchMessagesLocal', {\n chatOrUser,\n type: 'text',\n query,\n topMessageId,\n limit: MESSAGE_SEARCH_SLICE,\n offsetId,\n });\n\n if (!result) {\n return;\n }\n\n const {\n messages, users, totalCount, nextOffsetId,\n } = result;\n\n const byId = buildCollectionByKey(messages, 'id');\n const newFoundIds = Object.keys(byId).map(Number);\n\n let global = getGlobal();\n\n const currentSearch = selectCurrentTextSearch(global);\n if (!currentSearch || (query && query !== currentSearch.query)) {\n return;\n }\n\n global = addChatMessagesById(global, chatOrUser.id, byId);\n global = addUsers(global, buildCollectionByKey(users, 'id'));\n global = updateLocalTextSearchResults(global, chatOrUser.id, threadId, newFoundIds, totalCount, nextOffsetId);\n setGlobal(global);\n}\n\nasync function searchSharedMedia(\n chatOrUser: ApiChat | ApiUser,\n type: SharedMediaType,\n offsetId?: number,\n) {\n const result = await callApi('searchMessagesLocal', {\n chatOrUser,\n type,\n limit: SHARED_MEDIA_SLICE,\n offsetId,\n });\n\n if (!result) {\n return;\n }\n\n const {\n messages, users, totalCount, nextOffsetId,\n } = result;\n\n const byId = buildCollectionByKey(messages, 'id');\n const newFoundIds = Object.keys(byId).map(Number);\n\n let global = getGlobal();\n\n const currentSearch = selectCurrentMediaSearch(global);\n if (!currentSearch) {\n return;\n }\n\n global = addChatMessagesById(global, chatOrUser.id, byId);\n global = addUsers(global, buildCollectionByKey(users, 'id'));\n global = updateLocalMediaSearchResults(global, chatOrUser.id, type, newFoundIds, totalCount, nextOffsetId);\n setGlobal(global);\n}\n\n/**\n * @param timestamp start of target date in seconds\n */\nasync function searchMessagesByDate(chat: ApiChat, timestamp: number) {\n const messageId = await callApi('findFirstMessageIdAfterDate', {\n chat,\n timestamp,\n });\n\n if (!messageId) {\n return;\n }\n\n getDispatch().focusMessage({\n chatId: chat.id,\n messageId,\n });\n}\n","import { addReducer, getGlobal, setGlobal } from '../../../lib/teact/teactn';\n\nimport { ManagementProgress } from '../../../types';\nimport { callApi } from '../../../api/gramjs';\nimport { updateManagement, updateManagementProgress } from '../../reducers';\nimport { selectChat, selectCurrentMessageList } from '../../selectors';\nimport { isChatBasicGroup } from '../../helpers';\n\naddReducer('checkPublicLink', (global, actions, payload) => {\n const { chatId } = selectCurrentMessageList(global) || {};\n if (!chatId) {\n return;\n }\n\n // No need to check the username if already in progress\n if (global.management.progress === ManagementProgress.InProgress) {\n return;\n }\n\n const { username } = payload!;\n\n (async () => {\n global = updateManagementProgress(global, ManagementProgress.InProgress);\n global = updateManagement(global, chatId, { isUsernameAvailable: undefined });\n setGlobal(global);\n\n const isUsernameAvailable = await callApi('checkChatUsername', { username })!;\n\n global = getGlobal();\n global = updateManagementProgress(\n global, isUsernameAvailable ? ManagementProgress.Complete : ManagementProgress.Error,\n );\n global = updateManagement(global, chatId, { isUsernameAvailable });\n setGlobal(global);\n })();\n});\n\naddReducer('updatePublicLink', (global, actions, payload) => {\n const { chatId } = selectCurrentMessageList(global) || {};\n let chat = chatId && selectChat(global, chatId);\n if (!chatId || !chat) {\n return;\n }\n\n const { username } = payload!;\n\n (async () => {\n global = updateManagementProgress(global, ManagementProgress.InProgress);\n setGlobal(global);\n\n if (isChatBasicGroup(chat)) {\n chat = await callApi('migrateChat', chat);\n\n if (!chat) {\n return;\n }\n\n actions.openChat({ id: chat.id });\n }\n\n const result = await callApi('setChatUsername', { chat, username });\n\n global = getGlobal();\n global = updateManagementProgress(global, result ? ManagementProgress.Complete : ManagementProgress.Error);\n global = updateManagement(global, chatId, { isUsernameAvailable: undefined });\n setGlobal(global);\n })();\n});\n\naddReducer('updatePrivateLink', (global) => {\n const { chatId } = selectCurrentMessageList(global) || {};\n const chat = chatId && selectChat(global, chatId);\n if (!chatId || !chat) {\n return;\n }\n\n callApi('updatePrivateLink', { chat });\n});\n","import {\n addReducer, getGlobal, setGlobal, getDispatch,\n} from '../../../lib/teact/teactn';\n\nimport {\n ApiChat, ApiFormattedText, ApiMessage, ApiUser, MAIN_THREAD_ID,\n} from '../../../api/types';\nimport { GlobalActions } from '../../../global/types';\n\nimport {\n CHAT_LIST_LOAD_SLICE, DEBUG, MESSAGE_LIST_SLICE, SERVICE_NOTIFICATIONS_USER_ID,\n} from '../../../config';\nimport { callApi } from '../../../api/gramjs';\nimport { buildCollectionByKey } from '../../../util/iteratees';\nimport { updateAppBadge } from '../../../util/appBadge';\nimport {\n replaceChatListIds,\n replaceChats,\n replaceUsers,\n updateUsers,\n updateChats,\n updateChatListSecondaryInfo,\n updateThreadInfos,\n replaceThreadParam,\n updateListedIds,\n safeReplaceViewportIds,\n addChatMessagesById,\n} from '../../reducers';\nimport {\n selectUser,\n selectChat,\n selectCurrentMessageList,\n selectDraft,\n selectChatMessage,\n selectThreadInfo,\n selectCountNotMutedUnread,\n selectLastServiceNotification,\n} from '../../selectors';\nimport { isUserId } from '../../helpers';\n\naddReducer('sync', (global, actions) => {\n void sync(actions.afterSync);\n});\n\naddReducer('afterSync', (global, actions) => {\n void afterSync(actions);\n});\n\nasync function sync(afterSyncCallback: () => void) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('>>> START SYNC');\n }\n\n await callApi('fetchCurrentUser');\n\n // This fetches only active chats and clears archived chats, which will be fetched in `afterSync`\n const savedUsers = await loadAndReplaceChats();\n await loadAndReplaceMessages(savedUsers);\n\n setGlobal({\n ...getGlobal(),\n lastSyncTime: Date.now(),\n });\n\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('>>> FINISH SYNC');\n }\n\n afterSyncCallback();\n}\n\nasync function afterSync(actions: GlobalActions) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('>>> START AFTER-SYNC');\n }\n\n actions.loadFavoriteStickers();\n\n await Promise.all([\n loadAndUpdateUsers(),\n loadAndReplaceArchivedChats(),\n ]);\n\n await callApi('fetchCurrentUser');\n\n updateAppBadge(selectCountNotMutedUnread(getGlobal()));\n\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('>>> FINISH AFTER-SYNC');\n }\n}\n\nasync function loadAndReplaceChats() {\n let global = getGlobal();\n\n const result = await callApi('fetchChats', {\n limit: CHAT_LIST_LOAD_SLICE,\n withPinned: true,\n serverTimeOffset: global.serverTimeOffset,\n lastLocalServiceMessage: selectLastServiceNotification(global)?.message,\n });\n\n if (!result) {\n return undefined;\n }\n\n global = getGlobal();\n\n const { recentlyFoundChatIds } = global.globalSearch;\n const { userIds: contactIds } = global.contactList || {};\n const { currentUserId } = global;\n\n const savedPrivateChatIds = [\n ...(recentlyFoundChatIds || []),\n ...(contactIds || []),\n ...(currentUserId ? [currentUserId] : []),\n ];\n\n const savedUsers = savedPrivateChatIds\n .map((id) => selectUser(global, id))\n .filter<ApiUser>(Boolean as any);\n\n const savedChats = savedPrivateChatIds\n .map((id) => selectChat(global, id))\n .filter<ApiChat>(Boolean as any);\n\n const { chatId: currentChatId } = selectCurrentMessageList(global) || {};\n if (currentChatId) {\n const selectedChat = selectChat(global, currentChatId);\n if (selectedChat && !savedPrivateChatIds.includes(currentChatId)) {\n savedChats.push(selectedChat);\n }\n\n if (isUserId(currentChatId)) {\n const selectedChatUser = selectUser(global, currentChatId);\n if (selectedChatUser && !savedPrivateChatIds.includes(currentChatId)) {\n savedUsers.push(selectedChatUser);\n }\n }\n }\n\n savedUsers.push(...result.users);\n savedChats.push(...result.chats);\n\n global = replaceChats(global, buildCollectionByKey(savedChats, 'id'));\n global = replaceChatListIds(global, 'active', result.chatIds);\n\n global = {\n ...global,\n chats: {\n ...global.chats,\n },\n };\n\n global = updateChatListSecondaryInfo(global, 'active', result);\n\n Object.keys(result.draftsById).forEach((chatId) => {\n global = replaceThreadParam(global, chatId, MAIN_THREAD_ID, 'draft', result.draftsById[chatId]);\n });\n\n Object.keys(result.replyingToById).forEach((chatId) => {\n global = replaceThreadParam(\n global, chatId, MAIN_THREAD_ID, 'replyingToId', result.replyingToById[chatId],\n );\n });\n\n setGlobal(global);\n\n if (currentChatId && !global.chats.byId[currentChatId]) {\n getDispatch().openChat({ id: undefined });\n }\n\n return savedUsers;\n}\n\nasync function loadAndReplaceArchivedChats() {\n const result = await callApi('fetchChats', {\n limit: CHAT_LIST_LOAD_SLICE,\n archived: true,\n withPinned: true,\n serverTimeOffset: getGlobal().serverTimeOffset,\n });\n\n if (!result) {\n return;\n }\n\n let global = getGlobal();\n global = updateUsers(global, buildCollectionByKey(result.users, 'id'));\n global = updateChats(global, buildCollectionByKey(result.chats, 'id'));\n global = replaceChatListIds(global, 'archived', result.chatIds);\n global = updateChatListSecondaryInfo(global, 'archived', result);\n setGlobal(global);\n}\n\nasync function loadAndReplaceMessages(savedUsers?: ApiUser[]) {\n let areMessagesLoaded = false;\n let users = savedUsers || [];\n\n let global = getGlobal();\n const { chatId: currentChatId, threadId: currentThreadId } = selectCurrentMessageList(global) || {};\n\n // Memoize drafts\n const draftChatIds = Object.keys(global.messages.byChatId);\n const draftsByChatId = draftChatIds.reduce<Record<string, ApiFormattedText>>((acc, chatId) => {\n const draft = selectDraft(global, chatId, MAIN_THREAD_ID);\n if (draft) {\n acc[chatId] = draft;\n }\n\n return acc;\n }, {});\n\n if (currentChatId) {\n const result = await loadTopMessages(global.chats.byId[currentChatId]);\n global = getGlobal();\n const { chatId: newCurrentChatId } = selectCurrentMessageList(global) || {};\n const threadInfo = currentThreadId && selectThreadInfo(global, currentChatId, currentThreadId);\n\n if (result && newCurrentChatId === currentChatId) {\n const currentMessageListInfo = global.messages.byChatId[currentChatId];\n const localMessages = currentChatId === SERVICE_NOTIFICATIONS_USER_ID\n ? global.serviceNotifications.map(({ message }) => message)\n : [];\n const allMessages = ([] as ApiMessage[]).concat(result.messages, localMessages);\n const byId = buildCollectionByKey(allMessages, 'id');\n const listedIds = Object.keys(byId).map(Number);\n\n global = {\n ...global,\n messages: {\n ...global.messages,\n byChatId: {},\n },\n };\n\n global = addChatMessagesById(global, currentChatId, byId);\n global = updateListedIds(global, currentChatId, MAIN_THREAD_ID, listedIds);\n global = safeReplaceViewportIds(global, currentChatId, MAIN_THREAD_ID, listedIds);\n\n if (currentThreadId && threadInfo && threadInfo.originChannelId) {\n const { originChannelId } = threadInfo;\n const currentMessageListInfoOrigin = global.messages.byChatId[originChannelId];\n const resultOrigin = await loadTopMessages(global.chats.byId[originChannelId]);\n if (resultOrigin) {\n const byIdOrigin = buildCollectionByKey(resultOrigin.messages, 'id');\n const listedIdsOrigin = Object.keys(byIdOrigin).map(Number);\n\n global = {\n ...global,\n messages: {\n ...global.messages,\n byChatId: {\n ...global.messages.byChatId,\n [threadInfo.originChannelId]: {\n byId: byIdOrigin,\n threadsById: {\n [MAIN_THREAD_ID]: {\n ...(currentMessageListInfoOrigin?.threadsById[MAIN_THREAD_ID]),\n listedIds: listedIdsOrigin,\n viewportIds: listedIdsOrigin,\n outlyingIds: undefined,\n },\n },\n },\n [currentChatId]: {\n ...global.messages.byChatId[currentChatId],\n threadsById: {\n ...global.messages.byChatId[currentChatId].threadsById,\n [currentThreadId]: {\n ...(currentMessageListInfo?.threadsById[currentThreadId]),\n outlyingIds: undefined,\n },\n },\n },\n },\n },\n };\n }\n }\n\n global = updateChats(global, buildCollectionByKey(result.chats, 'id'));\n global = updateThreadInfos(global, currentChatId, result.threadInfos);\n\n areMessagesLoaded = true;\n users = Array.prototype.concat(users, result.users);\n }\n }\n\n if (!areMessagesLoaded) {\n global = {\n ...global,\n messages: {\n ...global.messages,\n byChatId: {},\n },\n };\n }\n\n // Restore drafts\n Object.keys(draftsByChatId).forEach((chatId) => {\n global = replaceThreadParam(global, chatId, MAIN_THREAD_ID, 'draft', draftsByChatId[chatId]);\n });\n\n if (savedUsers) {\n global = replaceUsers(global, buildCollectionByKey(users, 'id'));\n } else if (users) {\n // If `fetchChats` has failed for some reason, we don't have saved chats, thus we can not replace\n global = updateUsers(global, buildCollectionByKey(users, 'id'));\n }\n\n setGlobal(global);\n\n const { chatId: audioChatId, messageId: audioMessageId } = global.audioPlayer;\n if (audioChatId && audioMessageId && !selectChatMessage(global, audioChatId, audioMessageId)) {\n getDispatch().closeAudioPlayer();\n }\n}\n\nasync function loadAndUpdateUsers() {\n let global = getGlobal();\n const { recentlyFoundChatIds } = global.globalSearch;\n const { userIds: contactIds } = global.contactList || {};\n if (\n (!contactIds || !contactIds.length)\n && (!recentlyFoundChatIds || !recentlyFoundChatIds.length)\n ) {\n return;\n }\n\n const users = [\n ...(recentlyFoundChatIds || []),\n ...(contactIds || []),\n ].map((id) => selectUser(global, id)).filter<ApiUser>(Boolean as any);\n\n const updatedUsers = await callApi('fetchUsers', { users });\n if (!updatedUsers) {\n return;\n }\n\n global = getGlobal();\n global = updateUsers(global, buildCollectionByKey(updatedUsers, 'id'));\n setGlobal(global);\n}\n\nfunction loadTopMessages(chat: ApiChat) {\n return callApi('fetchMessages', {\n chat,\n threadId: MAIN_THREAD_ID,\n offsetId: chat.lastReadInboxMessageId,\n addOffset: -(Math.round(MESSAGE_LIST_SLICE / 2) + 1),\n limit: MESSAGE_LIST_SLICE,\n });\n}\n","import {\n addReducer, getDispatch, getGlobal, setGlobal,\n} from '../../../lib/teact/teactn';\n\nimport { ApiUser } from '../../../api/types';\nimport { ManagementProgress } from '../../../types';\n\nimport { debounce, throttle } from '../../../util/schedulers';\nimport { buildCollectionByKey, pick, unique } from '../../../util/iteratees';\nimport { isUserBot, isUserId } from '../../helpers';\nimport { callApi } from '../../../api/gramjs';\nimport { selectChat, selectCurrentMessageList, selectUser } from '../../selectors';\nimport {\n addChats, addUsers, updateChat, updateManagementProgress, updateUser, updateUsers,\n updateUserSearch, updateUserSearchFetchingStatus,\n} from '../../reducers';\nimport { getServerTime } from '../../../util/serverTime';\n\nconst runDebouncedForFetchFullUser = debounce((cb) => cb(), 500, false, true);\nconst TOP_PEERS_REQUEST_COOLDOWN = 60; // 1 min\nconst runThrottledForSearch = throttle((cb) => cb(), 500, false);\n\naddReducer('loadFullUser', (global, actions, payload) => {\n const { userId } = payload!;\n const user = selectUser(global, userId);\n if (!user) {\n return;\n }\n\n const { id, accessHash } = user;\n\n runDebouncedForFetchFullUser(() => callApi('fetchFullUser', { id, accessHash }));\n});\n\naddReducer('loadUser', (global, actions, payload) => {\n const { userId } = payload!;\n const user = selectUser(global, userId);\n if (!user) {\n return;\n }\n\n (async () => {\n const updatedUsers = await callApi('fetchUsers', { users: [user] });\n if (!updatedUsers) {\n return;\n }\n\n global = getGlobal();\n global = updateUsers(global, buildCollectionByKey(updatedUsers, 'id'));\n setGlobal(global);\n })();\n});\n\naddReducer('loadTopUsers', (global) => {\n const { topPeers: { lastRequestedAt } } = global;\n\n if (!lastRequestedAt || getServerTime(global.serverTimeOffset) - lastRequestedAt > TOP_PEERS_REQUEST_COOLDOWN) {\n void loadTopUsers();\n }\n});\n\naddReducer('loadContactList', () => {\n void loadContactList();\n});\n\naddReducer('loadCurrentUser', () => {\n void callApi('fetchCurrentUser');\n});\n\naddReducer('loadCommonChats', (global) => {\n const { chatId } = selectCurrentMessageList(global) || {};\n const user = chatId ? selectUser(global, chatId) : undefined;\n if (!user || isUserBot(user) || user.commonChats?.isFullyLoaded) {\n return;\n }\n\n (async () => {\n const maxId = user.commonChats?.maxId;\n const result = await callApi('fetchCommonChats', user.id, user.accessHash!, maxId);\n if (!result) {\n return;\n }\n\n const { chats, chatIds, isFullyLoaded } = result;\n\n global = getGlobal();\n if (chats.length) {\n global = addChats(global, buildCollectionByKey(chats, 'id'));\n }\n global = updateUser(global, user.id, {\n commonChats: {\n maxId: chatIds.length ? chatIds[chatIds.length - 1] : '0',\n ids: unique((user.commonChats?.ids || []).concat(chatIds)),\n isFullyLoaded,\n },\n });\n setGlobal(global);\n })();\n});\n\naddReducer('updateContact', (global, actions, payload) => {\n const {\n userId, isMuted, firstName, lastName,\n } = payload!;\n\n void updateContact(userId, isMuted, firstName, lastName);\n});\n\naddReducer('deleteUser', (global, actions, payload) => {\n const { userId } = payload!;\n\n void deleteUser(userId);\n});\n\nasync function loadTopUsers() {\n const result = await callApi('fetchTopUsers');\n if (!result) {\n return;\n }\n\n const { ids, users } = result;\n\n let global = getGlobal();\n global = addUsers(global, buildCollectionByKey(users, 'id'));\n global = {\n ...global,\n topPeers: {\n ...global.topPeers,\n userIds: ids,\n lastRequestedAt: getServerTime(global.serverTimeOffset),\n },\n };\n setGlobal(global);\n}\n\nasync function loadContactList() {\n const contactList = await callApi('fetchContactList');\n if (!contactList) {\n return;\n }\n\n let global = addUsers(getGlobal(), buildCollectionByKey(contactList.users, 'id'));\n global = addChats(global, buildCollectionByKey(contactList.chats, 'id'));\n\n // Sort contact list by Last Name (or First Name), with latin names being placed first\n const getCompareString = (user: ApiUser) => (user.lastName || user.firstName || '');\n const collator = new Intl.Collator('en-US');\n\n const sortedUsers = contactList.users.sort((a, b) => (\n collator.compare(getCompareString(a), getCompareString(b))\n )).filter((user) => !user.isSelf);\n\n setGlobal({\n ...global,\n contactList: {\n userIds: sortedUsers.map((user) => user.id),\n },\n });\n}\n\nasync function updateContact(\n userId: string,\n isMuted: boolean,\n firstName: string,\n lastName?: string,\n) {\n const global = getGlobal();\n const user = selectUser(global, userId);\n if (!user) {\n return;\n }\n\n getDispatch().updateChatMutedState({ chatId: userId, isMuted });\n\n setGlobal(updateManagementProgress(getGlobal(), ManagementProgress.InProgress));\n\n let result;\n if (user.phoneNumber) {\n result = await callApi('updateContact', { phone: user.phoneNumber, firstName, lastName });\n } else {\n const { id, accessHash } = user;\n result = await callApi('addContact', {\n id,\n accessHash,\n phoneNumber: '',\n firstName,\n lastName,\n });\n }\n\n if (result) {\n setGlobal(updateUser(\n getGlobal(),\n user.id,\n {\n firstName,\n lastName,\n },\n ));\n }\n\n setGlobal(updateManagementProgress(getGlobal(), ManagementProgress.Complete));\n}\n\nasync function deleteUser(userId: string) {\n const global = getGlobal();\n const user = selectUser(global, userId);\n\n if (!user) {\n return;\n }\n\n const { id, accessHash } = user;\n\n await callApi('deleteUser', { id, accessHash });\n}\n\naddReducer('loadProfilePhotos', (global, actions, payload) => {\n const { profileId } = payload!;\n const isPrivate = isUserId(profileId);\n const user = isPrivate ? selectUser(global, profileId) : undefined;\n const chat = !isPrivate ? selectChat(global, profileId) : undefined;\n\n if (!user && !chat) {\n return;\n }\n\n (async () => {\n const result = await callApi('fetchProfilePhotos', user, chat);\n if (!result || !result.photos) {\n return;\n }\n\n let newGlobal = getGlobal();\n if (isPrivate) {\n newGlobal = updateUser(newGlobal, profileId, { photos: result.photos });\n } else {\n newGlobal = addUsers(newGlobal, buildCollectionByKey(result.users!, 'id'));\n newGlobal = updateChat(newGlobal, profileId, { photos: result.photos });\n }\n\n setGlobal(newGlobal);\n })();\n});\n\naddReducer('setUserSearchQuery', (global, actions, payload) => {\n const { query } = payload!;\n\n if (!query) return;\n\n void runThrottledForSearch(() => {\n searchUsers(query);\n });\n});\n\naddReducer('addContact', (global, actions, payload) => {\n const { userId } = payload!;\n const user = selectUser(global, userId);\n if (!user) {\n return;\n }\n\n void callApi('addContact', pick(user, ['id', 'accessHash', 'firstName', 'lastName', 'phoneNumber']));\n});\n\nasync function searchUsers(query: string) {\n const result = await callApi('searchChats', { query });\n\n let global = getGlobal();\n const currentSearchQuery = global.userSearch.query;\n\n if (!result || !currentSearchQuery || (query !== currentSearchQuery)) {\n setGlobal(updateUserSearchFetchingStatus(global, false));\n return;\n }\n\n const { localUsers, globalUsers } = result;\n\n let localUserIds;\n let globalUserIds;\n if (localUsers.length) {\n global = addUsers(global, buildCollectionByKey(localUsers, 'id'));\n localUserIds = localUsers.map(({ id }) => id);\n }\n if (globalUsers.length) {\n global = addUsers(global, buildCollectionByKey(globalUsers, 'id'));\n globalUserIds = globalUsers.map(({ id }) => id);\n }\n\n global = updateUserSearchFetchingStatus(global, false);\n global = updateUserSearch(global, { localUserIds, globalUserIds });\n\n setGlobal(global);\n}\n","import { GlobalState } from '../../global/types';\nimport { InlineBotSettings } from '../../types';\n\nexport function replaceInlineBotSettings(\n global: GlobalState, username: string, inlineBotSettings: InlineBotSettings | false,\n): GlobalState {\n return {\n ...global,\n inlineBots: {\n ...global.inlineBots,\n byUsername: {\n ...global.inlineBots.byUsername,\n [username]: inlineBotSettings,\n },\n },\n };\n}\n\nexport function replaceInlineBotsIsLoading(global: GlobalState, isLoading: boolean): GlobalState {\n return {\n ...global,\n inlineBots: {\n ...global.inlineBots,\n isLoading,\n },\n };\n}\n","import {\n addReducer, getDispatch, getGlobal, setGlobal,\n} from '../../../lib/teact/teactn';\n\nimport { ApiChat } from '../../../api/types';\nimport { InlineBotSettings } from '../../../types';\n\nimport {\n RE_TG_LINK, RE_TME_LINK,\n} from '../../../config';\nimport { callApi } from '../../../api/gramjs';\nimport {\n selectChat, selectChatBot, selectChatMessage, selectCurrentChat, selectCurrentMessageList,\n selectReplyingToId, selectUser,\n} from '../../selectors';\nimport { addChats, addUsers, removeBlockedContact } from '../../reducers';\nimport { buildCollectionByKey } from '../../../util/iteratees';\nimport { debounce } from '../../../util/schedulers';\nimport { replaceInlineBotSettings, replaceInlineBotsIsLoading } from '../../reducers/bots';\nimport { getServerTime } from '../../../util/serverTime';\n\nconst TOP_PEERS_REQUEST_COOLDOWN = 60; // 1 min\nconst runDebouncedForSearch = debounce((cb) => cb(), 500, false);\n\naddReducer('clickInlineButton', (global, actions, payload) => {\n const { button } = payload;\n\n switch (button.type) {\n case 'command':\n actions.sendBotCommand({ command: button.value });\n break;\n case 'url':\n if (button.value.match(RE_TME_LINK) || button.value.match(RE_TG_LINK)) {\n actions.openTelegramLink({ url: button.value });\n } else {\n actions.toggleSafeLinkModal({ url: button.value });\n }\n break;\n case 'callback': {\n const chat = selectCurrentChat(global);\n if (!chat) {\n return;\n }\n\n void answerCallbackButton(chat, button.messageId, button.value);\n break;\n }\n case 'requestPoll':\n actions.openPollModal();\n break;\n case 'buy': {\n const chat = selectCurrentChat(global);\n const { messageId, value } = button;\n if (!chat) {\n return;\n }\n\n if (value) {\n actions.getReceipt({ receiptMessageId: value, chatId: chat.id, messageId });\n } else {\n actions.getPaymentForm({ chat, messageId });\n actions.setInvoiceMessageInfo(selectChatMessage(global, chat.id, messageId));\n actions.openPaymentModal({ chatId: chat.id, messageId });\n }\n break;\n }\n }\n});\n\naddReducer('sendBotCommand', (global, actions, payload) => {\n const { command, chatId } = payload;\n const { currentUserId } = global;\n const chat = chatId ? selectChat(global, chatId) : selectCurrentChat(global);\n const currentMessageList = selectCurrentMessageList(global);\n\n if (!currentUserId || !chat || !currentMessageList) {\n return;\n }\n\n const { threadId } = currentMessageList;\n actions.setReplyingToId({ messageId: undefined });\n actions.clearWebPagePreview({ chatId: chat.id, threadId, value: false });\n\n void sendBotCommand(chat, currentUserId, command, selectReplyingToId(global, chat.id, threadId));\n});\n\naddReducer('restartBot', (global, actions, payload) => {\n const { chatId } = payload;\n const { currentUserId } = global;\n const chat = selectCurrentChat(global);\n const bot = currentUserId && selectChatBot(global, chatId);\n if (!currentUserId || !chat || !bot) {\n return;\n }\n\n (async () => {\n const result = await callApi('unblockContact', bot.id, bot.accessHash);\n if (!result) {\n return;\n }\n\n setGlobal(removeBlockedContact(getGlobal(), bot.id));\n void sendBotCommand(chat, currentUserId, '/start');\n })();\n});\n\naddReducer('loadTopInlineBots', (global) => {\n const { lastRequestedAt } = global.topInlineBots;\n\n if (lastRequestedAt && getServerTime(global.serverTimeOffset) - lastRequestedAt < TOP_PEERS_REQUEST_COOLDOWN) {\n return;\n }\n\n (async () => {\n const result = await callApi('fetchTopInlineBots');\n if (!result) {\n return;\n }\n\n const { ids, users } = result;\n\n let newGlobal = getGlobal();\n newGlobal = addUsers(newGlobal, buildCollectionByKey(users, 'id'));\n newGlobal = {\n ...newGlobal,\n topInlineBots: {\n ...newGlobal.topInlineBots,\n userIds: ids,\n lastRequestedAt: getServerTime(global.serverTimeOffset),\n },\n };\n setGlobal(newGlobal);\n })();\n});\n\naddReducer('queryInlineBot', ((global, actions, payload) => {\n const {\n chatId, username, query, offset,\n } = payload;\n\n (async () => {\n let inlineBotData = global.inlineBots.byUsername[username];\n\n if (inlineBotData === false) {\n return;\n }\n\n if (inlineBotData === undefined) {\n const { user: inlineBot, chat } = await callApi('fetchInlineBot', { username }) || {};\n global = getGlobal();\n if (!inlineBot || !chat) {\n setGlobal(replaceInlineBotSettings(global, username, false));\n return;\n }\n\n global = addUsers(global, { [inlineBot.id]: inlineBot });\n global = addChats(global, { [chat.id]: chat });\n inlineBotData = {\n id: inlineBot.id,\n query: '',\n offset: '',\n switchPm: undefined,\n canLoadMore: true,\n results: [],\n };\n\n global = replaceInlineBotSettings(global, username, inlineBotData);\n setGlobal(global);\n }\n\n if (query === inlineBotData.query && !inlineBotData.canLoadMore) {\n return;\n }\n\n void runDebouncedForSearch(() => {\n searchInlineBot({\n username,\n inlineBotData: inlineBotData as InlineBotSettings,\n chatId,\n query,\n offset,\n });\n });\n })();\n}));\n\naddReducer('sendInlineBotResult', (global, actions, payload) => {\n const { id, queryId } = payload;\n const currentMessageList = selectCurrentMessageList(global);\n\n if (!currentMessageList || !id) {\n return;\n }\n\n const { chatId, threadId } = currentMessageList;\n\n const chat = selectChat(global, chatId)!;\n\n actions.setReplyingToId({ messageId: undefined });\n actions.clearWebPagePreview({ chatId, threadId, value: false });\n\n void callApi('sendInlineBotResult', {\n chat,\n resultId: id,\n queryId,\n replyingTo: selectReplyingToId(global, chatId, threadId),\n });\n});\n\naddReducer('resetInlineBot', (global, actions, payload) => {\n const { username } = payload;\n\n let inlineBotData = global.inlineBots.byUsername[username];\n\n if (!inlineBotData) {\n return;\n }\n\n inlineBotData = {\n id: inlineBotData.id,\n query: '',\n offset: '',\n switchPm: undefined,\n canLoadMore: true,\n results: [],\n };\n\n setGlobal(replaceInlineBotSettings(global, username, inlineBotData));\n});\n\naddReducer('startBot', (global, actions, payload) => {\n const { botId, param } = payload;\n\n const bot = selectUser(global, botId);\n if (!bot) {\n return;\n }\n\n (async () => {\n await callApi('startBot', {\n bot,\n startParam: param,\n });\n })();\n});\n\nasync function searchInlineBot({\n username,\n inlineBotData,\n chatId,\n query,\n offset,\n}: {\n username: string;\n inlineBotData: InlineBotSettings;\n chatId: string;\n query: string;\n offset?: string;\n}) {\n let global = getGlobal();\n const bot = selectUser(global, inlineBotData.id);\n const chat = selectChat(global, chatId);\n if (!bot || !chat) {\n return;\n }\n\n const shouldReplaceSettings = inlineBotData.query !== query;\n global = replaceInlineBotsIsLoading(global, true);\n global = replaceInlineBotSettings(global, username, {\n ...inlineBotData,\n query,\n ...(shouldReplaceSettings && { offset: undefined, results: [] }),\n });\n setGlobal(global);\n\n const result = await callApi('fetchInlineBotResults', {\n bot,\n chat,\n query,\n offset: shouldReplaceSettings ? undefined : offset,\n });\n\n const newInlineBotData = global.inlineBots.byUsername[username];\n global = replaceInlineBotsIsLoading(getGlobal(), false);\n if (!result || !newInlineBotData || query !== newInlineBotData.query) {\n setGlobal(global);\n return;\n }\n\n const currentIds = new Set((newInlineBotData.results || []).map((data) => data.id));\n const newResults = result.results.filter((data) => !currentIds.has(data.id));\n\n global = replaceInlineBotSettings(global, username, {\n ...newInlineBotData,\n help: result.help,\n ...(newResults.length && { isGallery: result.isGallery }),\n ...(result.switchPm && { switchPm: result.switchPm }),\n canLoadMore: result.results.length > 0 && Boolean(result.nextOffset),\n results: newInlineBotData.offset === '' || newInlineBotData.offset === result.nextOffset\n ? result.results\n : (newInlineBotData.results || []).concat(newResults),\n offset: newResults.length ? result.nextOffset : '',\n });\n\n setGlobal(global);\n}\n\nasync function sendBotCommand(chat: ApiChat, currentUserId: string, command: string, replyingTo?: number) {\n await callApi('sendMessage', {\n chat,\n text: command,\n replyingTo,\n });\n}\n\nasync function answerCallbackButton(chat: ApiChat, messageId: number, data: string) {\n const result = await callApi('answerCallbackButton', {\n chatId: chat.id,\n accessHash: chat.accessHash,\n messageId,\n data,\n });\n\n if (!result) {\n return;\n }\n\n const { showDialog, showNotification, toggleSafeLinkModal } = getDispatch();\n const { message, alert: isError, url } = result;\n\n if (isError) {\n showDialog({ data: { message: message || 'Error' } });\n } else if (message) {\n showNotification({ message });\n } else if (url) {\n toggleSafeLinkModal({ url });\n }\n}\n","import { addReducer, getGlobal, setGlobal } from '../../../lib/teact/teactn';\n\nimport { callApi } from '../../../api/gramjs';\nimport { replaceSettings, updateTwoFaSettings } from '../../reducers';\n\naddReducer('loadPasswordInfo', () => {\n (async () => {\n const result = await callApi('getPasswordInfo');\n if (!result) {\n return;\n }\n\n let global = getGlobal();\n global = replaceSettings(global, { hasPassword: result.hasPassword });\n global = updateTwoFaSettings(global, { hint: result.hint });\n setGlobal(global);\n })();\n});\n\naddReducer('checkPassword', (global, actions, payload) => {\n const { currentPassword, onSuccess } = payload;\n\n setGlobal(updateTwoFaSettings(global, { isLoading: true, error: undefined }));\n\n (async () => {\n const isSuccess = await callApi('checkPassword', currentPassword);\n\n setGlobal(updateTwoFaSettings(getGlobal(), { isLoading: false }));\n\n if (isSuccess) {\n onSuccess();\n }\n })();\n});\n\naddReducer('clearPassword', (global, actions, payload) => {\n const { currentPassword, onSuccess } = payload;\n\n setGlobal(updateTwoFaSettings(global, { isLoading: true, error: undefined }));\n\n (async () => {\n const isSuccess = await callApi('clearPassword', currentPassword);\n\n setGlobal(updateTwoFaSettings(getGlobal(), { isLoading: false }));\n\n if (isSuccess) {\n onSuccess();\n }\n })();\n});\n\naddReducer('updatePassword', (global, actions, payload) => {\n const {\n currentPassword, password, hint, email, onSuccess,\n } = payload;\n\n setGlobal(updateTwoFaSettings(global, { isLoading: true, error: undefined }));\n\n (async () => {\n const isSuccess = await callApi('updatePassword', currentPassword, password, hint, email);\n\n setGlobal(updateTwoFaSettings(getGlobal(), { isLoading: false }));\n\n if (isSuccess) {\n onSuccess();\n }\n })();\n});\n\naddReducer('updateRecoveryEmail', (global, actions, payload) => {\n const {\n currentPassword, email, onSuccess,\n } = payload;\n\n setGlobal(updateTwoFaSettings(global, { isLoading: true, error: undefined }));\n\n (async () => {\n const isSuccess = await callApi('updateRecoveryEmail', currentPassword, email);\n\n setGlobal(updateTwoFaSettings(getGlobal(), { isLoading: false, waitingEmailCodeLength: undefined }));\n\n if (isSuccess) {\n onSuccess();\n }\n })();\n});\n\naddReducer('provideTwoFaEmailCode', (global, actions, payload) => {\n const { code } = payload;\n\n void callApi('provideRecoveryEmailCode', code);\n});\n\naddReducer('clearTwoFaError', (global) => {\n return updateTwoFaSettings(global, { error: undefined });\n});\n","import { addReducer, getGlobal, setGlobal } from '../../../lib/teact/teactn';\n\nimport { PaymentStep } from '../../../types';\nimport { ApiChat } from '../../../api/types';\n\nimport {\n selectPaymentMessageId,\n selectPaymentRequestId,\n selectProviderPublishableKey,\n selectStripeCredentials,\n selectChatMessage,\n selectPaymentChatId,\n selectChat,\n selectPaymentFormId,\n} from '../../selectors';\nimport { callApi } from '../../../api/gramjs';\nimport { getStripeError } from '../../helpers';\nimport { buildQueryString } from '../../../util/requestQuery';\n\nimport {\n updateShippingOptions,\n setPaymentStep,\n setRequestInfoId,\n setPaymentForm,\n setStripeCardInfo,\n setInvoiceMessageInfo,\n setReceipt,\n clearPayment,\n closeInvoice,\n} from '../../reducers';\n\naddReducer('validateRequestedInfo', (global, actions, payload) => {\n const { requestInfo, saveInfo } = payload;\n const chatId = selectPaymentChatId(global);\n const chat = chatId && selectChat(global, chatId);\n const messageId = selectPaymentMessageId(global);\n if (!chat || !messageId) {\n return;\n }\n void validateRequestedInfo(chat, messageId, requestInfo, saveInfo);\n});\n\nasync function validateRequestedInfo(chat: ApiChat, messageId: number, requestInfo: any, shouldSave?: true) {\n const result = await callApi('validateRequestedInfo', {\n chat, messageId, requestInfo, shouldSave,\n });\n if (!result) {\n return;\n }\n\n const { id, shippingOptions } = result;\n if (!id) {\n return;\n }\n\n let global = setRequestInfoId(getGlobal(), id);\n if (shippingOptions) {\n global = updateShippingOptions(global, shippingOptions);\n global = setPaymentStep(global, PaymentStep.Shipping);\n } else {\n global = setPaymentStep(global, PaymentStep.PaymentInfo);\n }\n setGlobal(global);\n}\n\naddReducer('getPaymentForm', (global, actions, payload) => {\n const { chat, messageId } = payload;\n if (!chat || !messageId) {\n return;\n }\n void getPaymentForm(chat, messageId);\n});\n\nasync function getPaymentForm(chat: ApiChat, messageId: number) {\n const result = await callApi('getPaymentForm', { chat, messageId });\n if (!result) {\n return;\n }\n let global = setPaymentForm(getGlobal(), result);\n let step = PaymentStep.PaymentInfo;\n if (global.payment.invoice\n && (global.payment.invoice.shippingAddressRequested\n || global.payment.invoice.nameRequested\n || global.payment.invoice.phoneRequested\n || global.payment.invoice.emailRequested)) {\n step = PaymentStep.ShippingInfo;\n }\n global = setPaymentStep(global, step);\n setGlobal(global);\n}\n\naddReducer('getReceipt', (global, actions, payload) => {\n const { receiptMessageId, chatId, messageId } = payload;\n const chat = chatId && selectChat(global, chatId);\n if (!messageId || !receiptMessageId || !chat) {\n return;\n }\n\n void getReceipt(chat, messageId, receiptMessageId);\n});\n\nasync function getReceipt(chat: ApiChat, messageId: number, receiptMessageId: number) {\n const result = await callApi('getReceipt', chat, receiptMessageId);\n if (!result) {\n return;\n }\n\n let global = getGlobal();\n const message = selectChatMessage(global, chat.id, messageId);\n global = setReceipt(global, result, message);\n setGlobal(global);\n}\n\naddReducer('clearPaymentError', (global) => {\n setGlobal({\n ...global,\n payment: {\n ...global.payment,\n error: undefined,\n },\n });\n});\n\naddReducer('clearReceipt', (global) => {\n setGlobal({\n ...global,\n payment: {\n ...global.payment,\n receipt: undefined,\n },\n });\n});\n\naddReducer('sendCredentialsInfo', (global, actions, payload) => {\n const publishableKey = selectProviderPublishableKey(global);\n if (!publishableKey) {\n return;\n }\n const { credentials } = payload;\n const { data } = credentials;\n void sendStripeCredentials(data, publishableKey);\n});\n\naddReducer('sendPaymentForm', (global, actions, payload) => {\n const { shippingOptionId, saveCredentials } = payload;\n const chatId = selectPaymentChatId(global);\n const chat = chatId && selectChat(global, chatId);\n const messageId = selectPaymentMessageId(global);\n const formId = selectPaymentFormId(global);\n const requestInfoId = selectPaymentRequestId(global);\n const publishableKey = selectProviderPublishableKey(global);\n const stripeCredentials = selectStripeCredentials(global);\n if (!chat || !messageId || !publishableKey || !formId) {\n return;\n }\n\n void sendPaymentForm(chat, messageId, formId, {\n save: saveCredentials,\n data: stripeCredentials,\n }, requestInfoId, shippingOptionId);\n});\n\nasync function sendStripeCredentials(\n data: {\n cardNumber: string;\n cardholder?: string;\n expiryMonth: string;\n expiryYear: string;\n cvv: string;\n country: string;\n zip: string;\n },\n publishableKey: string,\n) {\n const query = buildQueryString({\n 'card[number]': data.cardNumber,\n 'card[exp_month]': data.expiryMonth,\n 'card[exp_year]': data.expiryYear,\n 'card[cvc]': data.cvv,\n 'card[address_zip]': data.zip,\n 'card[address_country]': data.country,\n });\n\n const response = await fetch(`https://api.stripe.com/v1/tokens${query}`, {\n method: 'POST',\n credentials: 'same-origin',\n headers: {\n 'Content-Type': 'application/x-www-form-urlencoded',\n Authorization: `Bearer ${publishableKey}`,\n },\n });\n const result = await response.json();\n if (result.error) {\n const error = getStripeError(result.error);\n const global = getGlobal();\n setGlobal({\n ...global,\n payment: {\n ...global.payment,\n error: {\n ...error,\n },\n },\n });\n return;\n }\n let global = setStripeCardInfo(getGlobal(), {\n type: result.type,\n id: result.id,\n });\n global = setPaymentStep(global, PaymentStep.Checkout);\n setGlobal(global);\n}\n\nasync function sendPaymentForm(\n chat: ApiChat,\n messageId: number,\n formId: string,\n credentials: any,\n requestedInfoId?: string,\n shippingOptionId?: string,\n) {\n const result = await callApi('sendPaymentForm', {\n chat, messageId, formId, credentials, requestedInfoId, shippingOptionId,\n });\n if (result) {\n const global = clearPayment(getGlobal());\n setGlobal(closeInvoice(global));\n }\n}\n\naddReducer('setPaymentStep', (global, actions, payload = {}) => {\n return setPaymentStep(global, payload.step || PaymentStep.ShippingInfo);\n});\n\naddReducer('setInvoiceMessageInfo', (global, actions, payload) => {\n return setInvoiceMessageInfo(global, payload);\n});\n","export function buildQueryString(data: Record<string, string>) {\n const query = Object.keys(data).map((k) => `${k}=${data[k]}`).join('&');\n return query.length > 0 ? `?${query}` : '';\n}\n","import { addReducer, getGlobal, setGlobal } from '../../../lib/teact/teactn';\n\nimport { ApiUpdate, MAIN_THREAD_ID } from '../../../api/types';\n\nimport { ARCHIVED_FOLDER_ID, MAX_ACTIVE_PINNED_CHATS } from '../../../config';\nimport { pick } from '../../../util/iteratees';\nimport { closeMessageNotifications, notifyAboutNewMessage } from '../../../util/notifications';\nimport { updateAppBadge } from '../../../util/appBadge';\nimport {\n updateChat,\n updateChatListIds,\n updateChatListType,\n replaceThreadParam,\n leaveChat,\n} from '../../reducers';\nimport {\n selectChat,\n selectCommonBoxChatId,\n selectIsChatListed,\n selectChatListType,\n selectCurrentMessageList,\n selectCountNotMutedUnread,\n} from '../../selectors';\nimport { throttle } from '../../../util/schedulers';\n\nconst TYPING_STATUS_CLEAR_DELAY = 6000; // 6 seconds\n// Enough to animate and mark as read in Message List\nconst CURRENT_CHAT_UNREAD_DELAY = 1500;\n\nconst runThrottledForUpdateAppBadge = throttle((cb) => cb(), 500, true);\n\naddReducer('apiUpdate', (global, actions, update: ApiUpdate) => {\n switch (update['@type']) {\n case 'updateChat': {\n if (!update.noTopChatsRequest && !selectIsChatListed(global, update.id)) {\n // Chat can appear in dialogs list.\n actions.loadTopChats();\n }\n\n const newGlobal = updateChat(global, update.id, update.chat, update.newProfilePhoto);\n setGlobal(newGlobal);\n\n runThrottledForUpdateAppBadge(() => updateAppBadge(selectCountNotMutedUnread(getGlobal())));\n\n if (update.chat.id) {\n closeMessageNotifications({\n chatId: update.chat.id,\n lastReadInboxMessageId: update.chat.lastReadInboxMessageId,\n });\n }\n break;\n }\n\n case 'updateChatJoin': {\n const listType = selectChatListType(global, update.id);\n if (!listType) {\n break;\n }\n\n global = updateChatListIds(global, listType, [update.id]);\n global = updateChat(global, update.id, { isNotJoined: false });\n setGlobal(global);\n\n const chat = selectChat(global, update.id);\n if (chat) {\n actions.requestChatUpdate({ chatId: chat.id });\n }\n break;\n }\n\n case 'updateChatLeave': {\n setGlobal(leaveChat(global, update.id));\n\n break;\n }\n\n case 'updateChatInbox': {\n setGlobal(updateChat(global, update.id, update.chat));\n\n runThrottledForUpdateAppBadge(() => updateAppBadge(selectCountNotMutedUnread(getGlobal())));\n\n break;\n }\n\n case 'updateChatTypingStatus': {\n const { id, typingStatus } = update;\n setGlobal(updateChat(global, id, { typingStatus }));\n\n setTimeout(() => {\n const newGlobal = getGlobal();\n const chat = selectChat(newGlobal, id);\n if (chat && typingStatus && chat.typingStatus && chat.typingStatus.timestamp === typingStatus.timestamp) {\n setGlobal(updateChat(newGlobal, id, { typingStatus: undefined }));\n }\n }, TYPING_STATUS_CLEAR_DELAY);\n\n break;\n }\n\n case 'newMessage': {\n const { message } = update;\n const { chatId: currentChatId, threadId, type: messageListType } = selectCurrentMessageList(global) || {};\n\n if (message.senderId === global.currentUserId && !message.isFromScheduled) {\n return;\n }\n\n const chat = selectChat(global, update.chatId);\n if (!chat) {\n return;\n }\n\n const isActiveChat = (\n messageListType === 'thread'\n && threadId === MAIN_THREAD_ID\n && update.chatId === currentChatId\n );\n\n if (isActiveChat) {\n setTimeout(() => {\n actions.requestChatUpdate({ chatId: update.chatId });\n }, CURRENT_CHAT_UNREAD_DELAY);\n } else {\n setGlobal(updateChat(global, update.chatId, {\n unreadCount: chat.unreadCount ? chat.unreadCount + 1 : 1,\n ...(update.message.hasUnreadMention && {\n unreadMentionsCount: chat.unreadMentionsCount ? chat.unreadMentionsCount + 1 : 1,\n }),\n }));\n }\n\n updateAppBadge(selectCountNotMutedUnread(getGlobal()));\n notifyAboutNewMessage({\n chat,\n message,\n });\n\n break;\n }\n\n case 'updateCommonBoxMessages':\n case 'updateChannelMessages': {\n const { ids, messageUpdate } = update;\n if (messageUpdate.hasUnreadMention !== false) {\n return;\n }\n\n ids.forEach((id) => {\n const chatId = ('channelId' in update ? update.channelId : selectCommonBoxChatId(global, id))!;\n const chat = selectChat(global, chatId);\n if (chat?.unreadMentionsCount) {\n global = updateChat(global, chatId, {\n unreadMentionsCount: chat.unreadMentionsCount - 1,\n });\n }\n });\n\n setGlobal(global);\n\n break;\n }\n\n case 'updateChatFullInfo': {\n const { fullInfo } = update;\n const targetChat = global.chats.byId[update.id];\n if (!targetChat) {\n return;\n }\n\n setGlobal(updateChat(global, update.id, {\n fullInfo: {\n ...targetChat.fullInfo,\n ...fullInfo,\n },\n }));\n\n break;\n }\n\n case 'updatePinnedChatIds': {\n const { ids, folderId } = update;\n\n const listType = folderId === ARCHIVED_FOLDER_ID ? 'archived' : 'active';\n\n global = {\n ...global,\n chats: {\n ...global.chats,\n orderedPinnedIds: {\n ...global.chats.orderedPinnedIds,\n [listType]: ids.length ? ids : undefined,\n },\n },\n };\n\n setGlobal(global);\n\n break;\n }\n\n case 'updateChatPinned': {\n const { id, isPinned } = update;\n const listType = selectChatListType(global, id);\n if (listType) {\n const { [listType]: orderedPinnedIds } = global.chats.orderedPinnedIds;\n\n let newOrderedPinnedIds = orderedPinnedIds || [];\n if (!isPinned) {\n newOrderedPinnedIds = newOrderedPinnedIds.filter((pinnedId) => pinnedId !== id);\n } else if (!newOrderedPinnedIds.includes(id)) {\n // When moving pinned chats to archive, active ordered pinned ids don't get updated\n // (to preserve chat pinned state when it returns from archive)\n // If user already has max pinned chats, we should check for orderedIds\n // that don't point to listed chats\n if (listType === 'active' && newOrderedPinnedIds.length >= MAX_ACTIVE_PINNED_CHATS) {\n const listIds = global.chats.listIds.active;\n newOrderedPinnedIds = newOrderedPinnedIds.filter((pinnedId) => listIds && listIds.includes(pinnedId));\n }\n\n newOrderedPinnedIds = [id, ...newOrderedPinnedIds];\n }\n\n global = {\n ...global,\n chats: {\n ...global.chats,\n orderedPinnedIds: {\n ...global.chats.orderedPinnedIds,\n [listType]: newOrderedPinnedIds.length ? newOrderedPinnedIds : undefined,\n },\n },\n };\n }\n\n setGlobal(global);\n\n break;\n }\n\n case 'updateChatListType': {\n const { id, folderId } = update;\n\n setGlobal(updateChatListType(global, id, folderId));\n\n break;\n }\n\n case 'updateChatFolder': {\n const { id, folder } = update;\n const { byId: chatFoldersById, orderedIds } = global.chatFolders;\n\n const newChatFoldersById = folder\n ? { ...chatFoldersById, [id]: folder }\n : pick(\n chatFoldersById,\n Object.keys(chatFoldersById).map(Number).filter((folderId) => folderId !== id),\n );\n\n const newOrderedIds = folder\n ? orderedIds && orderedIds.includes(id) ? orderedIds : [...(orderedIds || []), id]\n : orderedIds ? orderedIds.filter((orderedId) => orderedId !== id) : undefined;\n\n setGlobal({\n ...global,\n chatFolders: {\n ...global.chatFolders,\n byId: newChatFoldersById,\n orderedIds: newOrderedIds,\n },\n });\n\n break;\n }\n\n case 'updateChatFoldersOrder': {\n const { orderedIds } = update;\n\n setGlobal({\n ...global,\n chatFolders: {\n ...global.chatFolders,\n orderedIds,\n },\n });\n\n break;\n }\n\n case 'updateRecommendedChatFolders': {\n const { folders } = update;\n\n setGlobal({\n ...global,\n chatFolders: {\n ...global.chatFolders,\n recommended: folders,\n },\n });\n\n break;\n }\n\n case 'updateChatMembers': {\n const targetChat = global.chats.byId[update.id];\n const { replacedMembers, addedMember, deletedMemberId } = update;\n if (!targetChat) {\n return;\n }\n\n let shouldUpdate = false;\n let members = targetChat.fullInfo?.members\n ? [...targetChat.fullInfo.members]\n : [];\n\n if (replacedMembers) {\n members = replacedMembers;\n shouldUpdate = true;\n } else if (addedMember) {\n if (\n !members.length\n || !members.some((m) => m.userId === addedMember.userId)\n ) {\n members.push(addedMember);\n shouldUpdate = true;\n }\n } else if (members.length && deletedMemberId) {\n const deleteIndex = members.findIndex((m) => m.userId === deletedMemberId);\n if (deleteIndex > -1) {\n members.slice(deleteIndex, 1);\n shouldUpdate = true;\n }\n }\n\n if (shouldUpdate) {\n const adminMembers = members.filter(({ isOwner, isAdmin }) => isOwner || isAdmin);\n // TODO Kicked members?\n\n setGlobal(updateChat(global, update.id, {\n membersCount: members.length,\n fullInfo: {\n ...targetChat.fullInfo,\n members,\n adminMembers,\n },\n }));\n }\n\n break;\n }\n\n case 'deleteProfilePhotos': {\n const { chatId, ids } = update;\n const chat = global.chats.byId[chatId];\n\n if (chat?.photos) {\n setGlobal(updateChat(global, chatId, {\n photos: chat.photos.filter((photo) => !ids.includes(photo.id)),\n }));\n }\n break;\n }\n\n case 'draftMessage': {\n const {\n chatId, formattedText, date, replyingToId,\n } = update;\n const chat = global.chats.byId[chatId];\n\n if (chat) {\n global = replaceThreadParam(global, chatId, MAIN_THREAD_ID, 'draft', formattedText);\n global = replaceThreadParam(global, chatId, MAIN_THREAD_ID, 'replyingToId', replyingToId);\n global = updateChat(global, chatId, { draftDate: date });\n\n setGlobal(global);\n }\n break;\n }\n\n case 'showInvite': {\n const { data } = update;\n\n actions.showDialog({ data });\n break;\n }\n }\n});\n","import { addReducer, getGlobal, setGlobal } from '../../../lib/teact/teactn';\n\nimport {\n ApiUpdate, ApiMessage, ApiPollResult, ApiThreadInfo, MAIN_THREAD_ID,\n} from '../../../api/types';\n\nimport { unique } from '../../../util/iteratees';\nimport {\n updateChat,\n deleteChatMessages,\n updateChatMessage,\n updateListedIds,\n addViewportId,\n updateThreadInfo,\n replaceThreadParam,\n updateScheduledMessage,\n deleteChatScheduledMessages,\n updateThreadUnreadFromForwardedMessage,\n} from '../../reducers';\nimport { GlobalActions, GlobalState } from '../../../global/types';\nimport {\n selectChatMessage,\n selectChatMessages,\n selectIsViewportNewest,\n selectListedIds,\n selectChatMessageByPollId,\n selectCommonBoxChatId,\n selectIsChatListed,\n selectThreadInfo,\n selectThreadByMessage,\n selectPinnedIds,\n selectScheduledMessage,\n selectScheduledMessages,\n isMessageInCurrentMessageList,\n selectScheduledIds,\n selectCurrentMessageList,\n selectViewportIds,\n selectFirstUnreadId,\n selectChat,\n selectIsChatWithBot,\n selectIsServiceChatReady,\n} from '../../selectors';\nimport { getMessageContent, isUserId, isMessageLocal } from '../../helpers';\n\nconst ANIMATION_DELAY = 350;\n\naddReducer('apiUpdate', (global, actions, update: ApiUpdate) => {\n switch (update['@type']) {\n case 'newMessage': {\n const {\n chatId, id, message, shouldForceReply,\n } = update;\n global = updateWithLocalMedia(global, chatId, id, message);\n global = updateListedAndViewportIds(global, actions, message as ApiMessage);\n\n if (message.threadInfo) {\n global = updateThreadInfo(\n global,\n message.threadInfo.chatId,\n message.threadInfo.threadId,\n message.threadInfo,\n );\n }\n\n setGlobal(global);\n\n const newMessage = selectChatMessage(global, chatId, id)!;\n\n if (isMessageInCurrentMessageList(global, chatId, message as ApiMessage)) {\n if (message.isOutgoing && !(message.content?.action)) {\n const currentMessageList = selectCurrentMessageList(global);\n if (currentMessageList) {\n // We do not use `actions.focusLastMessage` as it may be set with a delay (see below)\n actions.focusMessage({\n chatId,\n threadId: currentMessageList.threadId,\n messageId: message.id,\n noHighlight: true,\n isResizingContainer: true,\n });\n }\n }\n\n const { threadInfo } = selectThreadByMessage(global, chatId, message as ApiMessage) || {};\n if (threadInfo) {\n actions.requestThreadInfoUpdate({ chatId, threadId: threadInfo.threadId });\n }\n\n // @perf Wait until scroll animation finishes or simply rely on delivery status update (which is itself delayed)\n if (!isMessageLocal(message as ApiMessage)) {\n setTimeout(() => {\n let delayedGlobal = getGlobal();\n if (shouldForceReply) {\n delayedGlobal = replaceThreadParam(delayedGlobal, chatId, MAIN_THREAD_ID, 'replyingToId', id);\n }\n setGlobal(updateChatLastMessage(delayedGlobal, chatId, newMessage));\n }, ANIMATION_DELAY);\n }\n } else {\n setGlobal(updateChatLastMessage(getGlobal(), chatId, newMessage));\n }\n\n // Edge case: New message in an old (not loaded) chat.\n if (!selectIsChatListed(global, chatId)) {\n actions.loadTopChats();\n }\n\n break;\n }\n\n case 'newScheduledMessage': {\n const { chatId, id, message } = update;\n\n global = updateWithLocalMedia(global, chatId, id, message, true);\n\n const scheduledIds = selectScheduledIds(global, chatId) || [];\n global = replaceThreadParam(global, chatId, MAIN_THREAD_ID, 'scheduledIds', unique([...scheduledIds, id]));\n\n setGlobal(global);\n\n break;\n }\n\n case 'updateMessage': {\n const { chatId, id, message } = update;\n\n const currentMessage = selectChatMessage(global, chatId, id);\n if (!currentMessage) {\n return;\n }\n\n global = updateWithLocalMedia(global, chatId, id, message);\n\n const newMessage = selectChatMessage(global, chatId, id)!;\n if (message.threadInfo) {\n global = updateThreadInfo(\n global,\n message.threadInfo.chatId,\n message.threadInfo.threadId,\n message.threadInfo,\n );\n }\n global = updateChatLastMessage(global, chatId, newMessage);\n\n setGlobal(global);\n\n // Scroll down if bot message height is changed with an updated inline keyboard.\n // A drawback: this will scroll down even if the previous scroll was not at bottom.\n const chat = selectChat(global, chatId);\n if (\n chat\n && !message.isOutgoing\n && chat.lastMessage?.id === message.id\n && selectIsChatWithBot(global, chat)\n && isMessageInCurrentMessageList(global, chatId, message as ApiMessage)\n && selectIsViewportNewest(global, chatId, message.threadInfo?.threadId || MAIN_THREAD_ID)\n ) {\n actions.focusLastMessage();\n }\n\n break;\n }\n\n case 'updateScheduledMessage': {\n const { chatId, id, message } = update;\n\n const currentMessage = selectScheduledMessage(global, chatId, id);\n if (!currentMessage) {\n return;\n }\n\n global = updateWithLocalMedia(global, chatId, id, message, true);\n const ids = Object.keys(selectScheduledMessages(global, chatId) || {}).map(Number).sort((a, b) => b - a);\n global = replaceThreadParam(global, chatId, MAIN_THREAD_ID, 'scheduledIds', ids);\n setGlobal(global);\n\n break;\n }\n\n case 'updateMessageSendSucceeded': {\n const { chatId, localId, message } = update;\n\n global = updateListedAndViewportIds(global, actions, message as ApiMessage);\n\n const currentMessage = selectChatMessage(global, chatId, localId);\n\n global = deleteChatMessages(global, chatId, [localId]);\n\n // Edge case for \"Send When Online\"\n if (message.isScheduled) {\n global = deleteChatScheduledMessages(global, chatId, [localId]);\n }\n\n global = updateChatMessage(global, chatId, message.id, {\n ...currentMessage,\n ...message,\n previousLocalId: localId,\n });\n\n const newMessage = selectChatMessage(global, chatId, message.id)!;\n global = updateChatLastMessage(global, chatId, newMessage);\n\n const thread = selectThreadByMessage(global, chatId, message);\n // For some reason Telegram requires to manually mark outgoing thread messages read\n if (thread?.threadInfo) {\n actions.markMessageListRead({ maxId: message.id });\n\n global = replaceThreadParam(global, chatId, thread.threadInfo.threadId, 'threadInfo', {\n ...thread.threadInfo,\n lastMessageId: message.id,\n lastReadInboxMessageId: message.id,\n });\n }\n\n setGlobal(global);\n\n break;\n }\n\n case 'updateScheduledMessageSendSucceeded': {\n const { chatId, localId, message } = update;\n const scheduledIds = selectScheduledIds(global, chatId) || [];\n global = replaceThreadParam(global, chatId, MAIN_THREAD_ID, 'scheduledIds', [...scheduledIds, message.id]);\n\n const currentMessage = selectScheduledMessage(global, chatId, localId);\n\n global = deleteChatScheduledMessages(global, chatId, [localId]);\n global = updateScheduledMessage(global, chatId, message.id, {\n ...currentMessage,\n ...message,\n previousLocalId: localId,\n });\n\n setGlobal(global);\n break;\n }\n\n case 'updatePinnedIds': {\n const { chatId, isPinned, messageIds } = update;\n\n const currentPinnedIds = selectPinnedIds(global, chatId) || [];\n const newPinnedIds = isPinned\n ? [...currentPinnedIds, ...messageIds].sort((a, b) => b - a)\n : currentPinnedIds.filter((id) => !messageIds.includes(id));\n\n setGlobal(replaceThreadParam(global, chatId, MAIN_THREAD_ID, 'pinnedIds', newPinnedIds));\n\n break;\n }\n\n case 'updateThreadInfo': {\n const {\n chatId, threadId, threadInfo, firstMessageId,\n } = update;\n\n const currentThreadInfo = selectThreadInfo(global, chatId, threadId);\n const newTheadInfo = {\n ...currentThreadInfo,\n ...threadInfo,\n };\n\n if (!newTheadInfo.threadId) {\n return;\n }\n\n global = updateThreadInfo(global, chatId, threadId, newTheadInfo as ApiThreadInfo);\n\n if (firstMessageId) {\n global = replaceThreadParam(global, chatId, threadId, 'firstMessageId', firstMessageId);\n }\n\n setGlobal(global);\n\n break;\n }\n\n case 'resetMessages': {\n const { id: chatId } = update;\n const messagesById = selectChatMessages(global, chatId);\n\n if (messagesById && !isUserId(chatId)) {\n global = deleteChatMessages(global, chatId, Object.keys(messagesById).map(Number));\n setGlobal(global);\n actions.loadFullChat({ chatId, force: true });\n }\n\n break;\n }\n\n case 'deleteMessages': {\n const { ids, chatId } = update;\n\n deleteMessages(chatId, ids, actions, global);\n break;\n }\n\n case 'deleteScheduledMessages': {\n const { ids, chatId } = update;\n\n deleteScheduledMessages(chatId, ids, actions, global);\n break;\n }\n\n case 'deleteHistory': {\n const { chatId } = update;\n const chatMessages = global.messages.byChatId[chatId];\n if (chatMessages) {\n const ids = Object.keys(chatMessages.byId).map(Number);\n deleteMessages(chatId, ids, actions, global);\n } else {\n actions.requestChatUpdate({ chatId });\n }\n\n break;\n }\n\n case 'updateCommonBoxMessages': {\n const { ids, messageUpdate } = update;\n\n ids.forEach((id) => {\n const chatId = selectCommonBoxChatId(global, id);\n if (chatId) {\n global = updateChatMessage(global, chatId, id, messageUpdate);\n }\n });\n\n setGlobal(global);\n\n break;\n }\n\n case 'updateChannelMessages': {\n const { channelId, ids, messageUpdate } = update;\n\n ids.forEach((id) => {\n global = updateChatMessage(global, channelId, id, messageUpdate);\n });\n\n setGlobal(global);\n\n break;\n }\n\n case 'updateMessagePoll': {\n const { pollId, pollUpdate } = update;\n\n const message = selectChatMessageByPollId(global, pollId);\n\n if (message?.content.poll) {\n const updatedPoll = { ...message.content.poll, ...pollUpdate };\n\n // Workaround for poll update bug: `chosen` option gets reset when someone votes after current user\n const { results: updatedResults } = updatedPoll.results || {};\n if (updatedResults && !updatedResults.some(((result) => result.isChosen))) {\n const { results } = message.content.poll.results;\n const chosenAnswers = results && results.filter((result) => result.isChosen);\n if (chosenAnswers) {\n chosenAnswers.forEach((chosenAnswer) => {\n const chosenAnswerIndex = updatedResults.findIndex((result) => result.option === chosenAnswer.option);\n if (chosenAnswerIndex >= 0) {\n updatedPoll.results.results![chosenAnswerIndex].isChosen = true;\n }\n });\n }\n }\n\n setGlobal(updateChatMessage(\n global,\n message.chatId,\n message.id,\n {\n content: {\n ...message.content,\n poll: updatedPoll,\n },\n },\n ));\n }\n break;\n }\n\n case 'updateMessagePollVote': {\n const { pollId, userId, options } = update;\n const message = selectChatMessageByPollId(global, pollId);\n if (!message || !message.content.poll || !message.content.poll.results) {\n break;\n }\n\n const { poll } = message.content;\n\n const { recentVoterIds, totalVoters, results } = poll.results;\n const newRecentVoterIds = recentVoterIds ? [...recentVoterIds] : [];\n const newTotalVoters = totalVoters ? totalVoters + 1 : 1;\n const newResults = results ? [...results] : [];\n\n newRecentVoterIds.push(userId);\n\n options.forEach((option) => {\n const targetOption = newResults.find((result) => result.option === option);\n const targetOptionIndex = newResults.findIndex((result) => result.option === option);\n const updatedOption: ApiPollResult = targetOption ? { ...targetOption } : { option, votersCount: 0 };\n\n updatedOption.votersCount += 1;\n if (userId === global.currentUserId) {\n updatedOption.isChosen = true;\n }\n\n if (targetOptionIndex) {\n newResults[targetOptionIndex] = updatedOption;\n } else {\n newResults.push(updatedOption);\n }\n });\n\n setGlobal(updateChatMessage(\n global,\n message.chatId,\n message.id,\n {\n content: {\n ...message.content,\n poll: {\n ...poll,\n results: {\n ...poll.results,\n recentVoterIds: newRecentVoterIds,\n totalVoters: newTotalVoters,\n results: newResults,\n },\n },\n },\n },\n ));\n\n break;\n }\n\n case 'updateServiceNotification': {\n const { message } = update;\n\n if (selectIsServiceChatReady(global)) {\n actions.createServiceNotification({ message });\n }\n\n break;\n }\n }\n});\n\nfunction updateWithLocalMedia(\n global: GlobalState, chatId: string, id: number, message: Partial<ApiMessage>, isScheduled = false,\n) {\n // Preserve locally uploaded media.\n const currentMessage = isScheduled\n ? selectScheduledMessage(global, chatId, id)\n : selectChatMessage(global, chatId, id);\n if (currentMessage && message.content) {\n const {\n photo, video, sticker, document,\n } = getMessageContent(currentMessage);\n if (photo && message.content.photo) {\n message.content.photo.blobUrl = photo.blobUrl;\n message.content.photo.thumbnail = photo.thumbnail;\n } else if (video && message.content.video) {\n message.content.video.blobUrl = video.blobUrl;\n } else if (sticker && message.content.sticker) {\n message.content.sticker.isPreloadedGlobally = sticker.isPreloadedGlobally;\n } else if (document && message.content.document) {\n message.content.document.previewBlobUrl = document.previewBlobUrl;\n }\n }\n\n return isScheduled\n ? updateScheduledMessage(global, chatId, id, message)\n : updateChatMessage(global, chatId, id, message);\n}\n\nfunction updateThreadUnread(global: GlobalState, actions: GlobalActions, message: ApiMessage, isDeleting?: boolean) {\n const { chatId } = message;\n\n const { threadInfo } = selectThreadByMessage(global, chatId, message) || {};\n\n if (!threadInfo && message.replyToMessageId) {\n const originMessage = selectChatMessage(global, chatId, message.replyToMessageId);\n if (originMessage) {\n global = updateThreadUnreadFromForwardedMessage(global, originMessage, chatId, message.id, isDeleting);\n } else {\n actions.loadMessage({\n chatId,\n messageId: message.replyToMessageId,\n threadUpdate: {\n isDeleting,\n lastMessageId: message.id,\n },\n });\n }\n }\n\n return global;\n}\n\nfunction updateListedAndViewportIds(global: GlobalState, actions: GlobalActions, message: ApiMessage) {\n const { id, chatId } = message;\n\n const { threadInfo, firstMessageId } = selectThreadByMessage(global, chatId, message) || {};\n\n const chat = selectChat(global, chatId);\n const isUnreadChatNotLoaded = chat?.unreadCount && !selectListedIds(global, chatId, MAIN_THREAD_ID);\n\n global = updateThreadUnread(global, actions, message);\n\n if (threadInfo) {\n if (firstMessageId || !isMessageLocal(message)) {\n global = updateListedIds(global, chatId, threadInfo.threadId, [id]);\n\n if (selectIsViewportNewest(global, chatId, threadInfo.threadId)) {\n global = addViewportId(global, chatId, threadInfo.threadId, id);\n\n if (!firstMessageId) {\n global = replaceThreadParam(global, chatId, threadInfo.threadId, 'firstMessageId', message.id);\n }\n }\n }\n\n global = replaceThreadParam(global, chatId, threadInfo.threadId, 'threadInfo', {\n ...threadInfo,\n lastMessageId: message.id,\n messagesCount: threadInfo.messagesCount + 1,\n });\n }\n\n if (isUnreadChatNotLoaded) {\n return global;\n }\n\n global = updateListedIds(global, chatId, MAIN_THREAD_ID, [id]);\n\n if (selectIsViewportNewest(global, chatId, MAIN_THREAD_ID)) {\n // Always keep the first unread message in the viewport list\n const firstUnreadId = selectFirstUnreadId(global, chatId, MAIN_THREAD_ID);\n const newGlobal = addViewportId(global, chatId, MAIN_THREAD_ID, id);\n const newViewportIds = selectViewportIds(newGlobal, chatId, MAIN_THREAD_ID);\n\n if (!firstUnreadId || newViewportIds!.includes(firstUnreadId)) {\n global = newGlobal;\n }\n }\n\n return global;\n}\n\nfunction updateChatLastMessage(\n global: GlobalState,\n chatId: string,\n message: ApiMessage,\n force = false,\n) {\n const { chats } = global;\n const currentLastMessage = chats.byId[chatId]?.lastMessage;\n\n if (currentLastMessage && !force) {\n const isSameOrNewer = (\n currentLastMessage.id === message.id || currentLastMessage.id === message.previousLocalId\n ) || message.id > currentLastMessage.id;\n\n if (!isSameOrNewer) {\n return global;\n }\n }\n\n return updateChat(global, chatId, { lastMessage: message });\n}\n\nfunction findLastMessage(global: GlobalState, chatId: string) {\n const byId = selectChatMessages(global, chatId);\n const listedIds = selectListedIds(global, chatId, MAIN_THREAD_ID);\n\n if (!byId || !listedIds) {\n return undefined;\n }\n\n let i = listedIds.length;\n while (i--) {\n const message = byId[listedIds[i]];\n if (!message.isDeleting) {\n return message;\n }\n }\n\n return undefined;\n}\n\nfunction deleteMessages(chatId: string | undefined, ids: number[], actions: GlobalActions, global: GlobalState) {\n // Channel update\n\n if (chatId) {\n ids.forEach((id) => {\n global = updateChatMessage(global, chatId, id, {\n isDeleting: true,\n });\n\n const newLastMessage = findLastMessage(global, chatId);\n if (newLastMessage) {\n global = updateChatLastMessage(global, chatId, newLastMessage, true);\n }\n });\n\n setGlobal(global);\n\n actions.requestChatUpdate({ chatId });\n\n const threadIdsToUpdate: number[] = [];\n\n ids.forEach((id) => {\n const message = selectChatMessage(global, chatId, id);\n if (!message) {\n return;\n }\n\n global = updateThreadUnread(global, actions, message, true);\n\n const { threadInfo } = selectThreadByMessage(global, chatId, message) || {};\n if (threadInfo) {\n threadIdsToUpdate.push(threadInfo.threadId);\n }\n });\n\n setGlobal(global);\n\n setTimeout(() => {\n setGlobal(deleteChatMessages(getGlobal(), chatId, ids));\n\n unique(threadIdsToUpdate).forEach((threadId) => {\n actions.requestThreadInfoUpdate({ chatId, threadId });\n });\n }, ANIMATION_DELAY);\n\n return;\n }\n\n // Common box update\n\n const chatsIdsToUpdate: string[] = [];\n\n ids.forEach((id) => {\n const commonBoxChatId = selectCommonBoxChatId(global, id);\n if (commonBoxChatId) {\n chatsIdsToUpdate.push(commonBoxChatId);\n\n global = updateChatMessage(global, commonBoxChatId, id, {\n isDeleting: true,\n });\n\n const newLastMessage = findLastMessage(global, commonBoxChatId);\n if (newLastMessage) {\n global = updateChatLastMessage(global, commonBoxChatId, newLastMessage, true);\n }\n\n setTimeout(() => {\n setGlobal(deleteChatMessages(getGlobal(), commonBoxChatId, [id]));\n }, ANIMATION_DELAY);\n }\n });\n\n setGlobal(global);\n\n unique(chatsIdsToUpdate).forEach((id) => {\n actions.requestChatUpdate({ chatId: id });\n });\n}\n\nfunction deleteScheduledMessages(\n chatId: string | undefined, ids: number[], actions: GlobalActions, global: GlobalState,\n) {\n if (!chatId) {\n return;\n }\n\n ids.forEach((id) => {\n global = updateScheduledMessage(global, chatId, id, {\n isDeleting: true,\n });\n });\n\n setGlobal(global);\n\n setTimeout(() => {\n global = deleteChatScheduledMessages(getGlobal(), chatId, ids);\n const scheduledMessages = selectScheduledMessages(global, chatId);\n global = replaceThreadParam(\n global, chatId, MAIN_THREAD_ID, 'scheduledIds', Object.keys(scheduledMessages || {}).map(Number),\n );\n setGlobal(global);\n }, ANIMATION_DELAY);\n}\n","import { addReducer, getGlobal, setGlobal } from '../../../lib/teact/teactn';\n\nimport { ApiUpdate, ApiUserStatus } from '../../../api/types';\n\nimport { deleteUser, updateUser } from '../../reducers';\nimport { throttle } from '../../../util/schedulers';\n\nconst STATUS_UPDATE_THROTTLE = 3000;\n\nconst flushStatusUpdatesThrottled = throttle(flushStatusUpdates, STATUS_UPDATE_THROTTLE, true);\n\nlet pendingStatusUpdates: [string, ApiUserStatus][] = [];\n\nfunction scheduleStatusUpdate(userId: string, statusUpdate: ApiUserStatus) {\n pendingStatusUpdates.push([userId, statusUpdate]);\n flushStatusUpdatesThrottled();\n}\n\nfunction flushStatusUpdates() {\n let global = getGlobal();\n pendingStatusUpdates.forEach(([userId, statusUpdate]) => {\n global = updateUser(global, userId, {\n status: statusUpdate,\n });\n });\n setGlobal(global);\n\n pendingStatusUpdates = [];\n}\n\naddReducer('apiUpdate', (global, actions, update: ApiUpdate) => {\n switch (update['@type']) {\n case 'deleteUser': {\n return deleteUser(global, update.id);\n }\n\n case 'updateUser': {\n return updateUser(global, update.id, update.user);\n }\n\n case 'updateUserStatus': {\n // Status updates come very often so we throttle them\n scheduleStatusUpdate(update.userId, update.status);\n return undefined;\n }\n\n case 'updateUserFullInfo': {\n const { id, fullInfo } = update;\n const targetUser = global.users.byId[id];\n if (!targetUser) {\n return undefined;\n }\n\n return updateUser(global, id, {\n fullInfo: {\n ...targetUser.fullInfo,\n ...fullInfo,\n },\n });\n }\n }\n\n return undefined;\n});\n","import { addReducer } from '../../../lib/teact/teactn';\n\nimport { ApiUpdate } from '../../../api/types';\n\nimport { updateStickerSet } from '../../reducers';\n\naddReducer('apiUpdate', (global, actions, update: ApiUpdate) => {\n switch (update['@type']) {\n case 'updateStickerSet': {\n return updateStickerSet(global, update.id, update.stickerSet);\n }\n }\n\n return undefined;\n});\n","import {\n addReducer, getGlobal, setGlobal,\n} from '../../../lib/teact/teactn';\n\nimport { ApiUpdate } from '../../../api/types';\nimport { ApiPrivacyKey } from '../../../types';\n\nimport { addBlockedContact, removeBlockedContact } from '../../reducers';\n\naddReducer('apiUpdate', (global, actions, update: ApiUpdate) => {\n switch (update['@type']) {\n case 'updatePeerBlocked':\n if (update.isBlocked) {\n return addBlockedContact(getGlobal(), update.id);\n } else {\n return removeBlockedContact(getGlobal(), update.id);\n }\n\n case 'updateResetContactList':\n setGlobal({\n ...getGlobal(),\n contactList: {\n userIds: [],\n },\n });\n break;\n\n case 'updateFavoriteStickers':\n actions.loadFavoriteStickers();\n break;\n\n case 'updatePrivacy':\n global.settings.privacy[update.key as ApiPrivacyKey] = update.rules;\n break;\n }\n\n return undefined;\n});\n","import { addReducer, setGlobal } from '../../../lib/teact/teactn';\n\nimport { ApiUpdate } from '../../../api/types';\nimport { GlobalState } from '../../../global/types';\nimport { addNotifyException, updateChat, updateNotifySettings } from '../../reducers';\n\naddReducer('apiUpdate', (global, actions, update: ApiUpdate): GlobalState | undefined => {\n switch (update['@type']) {\n case 'updateNotifySettings': {\n return updateNotifySettings(global, update.peerType, update.isSilent, update.shouldShowPreviews);\n }\n\n case 'updateNotifyExceptions': {\n const {\n chatId, isMuted, isSilent, shouldShowPreviews,\n } = update;\n const chat = global.chats.byId[chatId];\n\n if (chat) {\n global = updateChat(global, chatId, { isMuted });\n }\n\n setGlobal(addNotifyException(global, chatId, { isMuted, isSilent, shouldShowPreviews }));\n break;\n }\n }\n\n return undefined;\n});\n","import { addReducer } from '../../../lib/teact/teactn';\n\nimport { ApiUpdate } from '../../../api/types';\nimport { GlobalState } from '../../../global/types';\n\naddReducer('apiUpdate', (global, actions, update: ApiUpdate): GlobalState | undefined => {\n switch (update['@type']) {\n case 'updateTwoFaStateWaitCode': {\n return {\n ...global,\n twoFaSettings: {\n ...global.twoFaSettings,\n isLoading: false,\n waitingEmailCodeLength: update.length,\n },\n };\n }\n\n case 'updateTwoFaError': {\n return {\n ...global,\n twoFaSettings: {\n ...global.twoFaSettings,\n error: update.message,\n },\n };\n }\n }\n\n return undefined;\n});\n","import { useEffect } from '../lib/teact/teact';\n\nimport { onBeforeUnload } from '../util/schedulers';\n\nexport default function useBeforeUnload(callback: AnyToVoidFunction) {\n useEffect(() => {\n return onBeforeUnload(callback);\n }, [callback]);\n}\n","import { useEffect } from '../lib/teact/teact';\nimport { IS_IOS, IS_PWA, IS_TOUCH_ENV } from '../util/environment';\n\nconst metaViewport = document.querySelector('meta[name=\"viewport\"]');\nconst defaultViewportContent = metaViewport?.getAttribute('content') || '';\nconst allowedZoomViewportContent = 'width=device-width, initial-scale=1, shrink-to-fit=no, viewport-fit=cover';\n\nexport default function usePreventPinchZoomGesture(isDisabled = false) {\n useEffect(() => {\n if (!IS_TOUCH_ENV) {\n return undefined;\n }\n\n if (isDisabled) {\n // Clean viewport content from values values that disable the ability to zoom a webpage\n // https://web.dev/meta-viewport/\n metaViewport?.setAttribute('content', allowedZoomViewportContent);\n return undefined;\n }\n\n metaViewport?.setAttribute('content', defaultViewportContent);\n\n // Since iOS 10 `user-scaleable=no` is disabled in Safari for iOS,\n // this is only applicable for the browser and does not apply to the PWA mode.\n // https://newbedev.com/how-do-you-disable-viewport-zooming-on-mobile-safari\n if (IS_IOS && !IS_PWA) {\n document.addEventListener('gesturestart', preventEvent);\n }\n\n return () => {\n metaViewport?.setAttribute('content', 'width=device-width, initial-scale=1, shrink-to-fit=no');\n if (IS_IOS && !IS_PWA) {\n document.removeEventListener('gesturestart', preventEvent);\n }\n };\n }, [isDisabled]);\n}\n\nfunction preventEvent(e: Event) {\n e.preventDefault();\n}\n","import { useEffect, useState } from '../lib/teact/teact';\n\nexport default function useBrowserOnline() {\n const [isOnline, setIsOnline] = useState(window.navigator.onLine);\n\n useEffect(() => {\n function handleChange() {\n setIsOnline(window.navigator.onLine);\n }\n\n window.addEventListener('online', handleChange);\n window.addEventListener('offline', handleChange);\n\n return () => {\n window.removeEventListener('offline', handleChange);\n window.removeEventListener('online', handleChange);\n };\n }, []);\n\n return isOnline;\n}\n","import React, {\n FC, useCallback, useMemo, memo,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../../global/types';\nimport { LeftColumnContent, ISettings } from '../../../types';\nimport { ApiChat } from '../../../api/types';\n\nimport {\n ANIMATION_LEVEL_MAX, APP_NAME, APP_VERSION, FEEDBACK_URL,\n} from '../../../config';\nimport { IS_SINGLE_COLUMN_LAYOUT } from '../../../util/environment';\nimport buildClassName from '../../../util/buildClassName';\nimport { pick } from '../../../util/iteratees';\nimport { isChatArchived } from '../../../modules/helpers';\nimport { formatDateToString } from '../../../util/dateFormat';\nimport { selectTheme } from '../../../modules/selectors';\nimport switchTheme from '../../../util/switchTheme';\nimport useLang from '../../../hooks/useLang';\nimport { disableHistoryBack } from '../../../hooks/useHistoryBack';\n\nimport DropdownMenu from '../../ui/DropdownMenu';\nimport MenuItem from '../../ui/MenuItem';\nimport Button from '../../ui/Button';\nimport SearchInput from '../../ui/SearchInput';\nimport PickerSelectedItem from '../../common/PickerSelectedItem';\nimport Switcher from '../../ui/Switcher';\n\nimport './LeftMainHeader.scss';\n\ntype OwnProps = {\n content: LeftColumnContent;\n contactsFilter: string;\n shouldSkipTransition?: boolean;\n onSearchQuery: (query: string) => void;\n onSelectSettings: () => void;\n onSelectContacts: () => void;\n onSelectArchived: () => void;\n onReset: () => void;\n};\n\ntype StateProps = {\n searchQuery?: string;\n isLoading: boolean;\n currentUserId?: string;\n globalSearchChatId?: string;\n searchDate?: number;\n theme: ISettings['theme'];\n animationLevel: 0 | 1 | 2;\n chatsById?: Record<string, ApiChat>;\n};\n\ntype DispatchProps = Pick<GlobalActions, (\n 'openChat' | 'openTipsChat' | 'setGlobalSearchDate' | 'setGlobalSearchChatId' | 'setSettingOption'\n)>;\n\nconst ANIMATION_LEVEL_OPTIONS = [0, 1, 2];\n\nconst PRODUCTION_HOSTNAME = 'web.telegram.org';\nconst LEGACY_VERSION_URL = 'https://web.telegram.org/?legacy=1';\nconst WEBK_VERSION_URL = 'https://web.telegram.org/k/';\nconst PERMANENT_VERSION_KEY = 'kz_version';\n\nconst LeftMainHeader: FC<OwnProps & StateProps & DispatchProps> = ({\n content,\n contactsFilter,\n onSearchQuery,\n onSelectSettings,\n onSelectContacts,\n onSelectArchived,\n setGlobalSearchChatId,\n onReset,\n searchQuery,\n isLoading,\n shouldSkipTransition,\n currentUserId,\n globalSearchChatId,\n searchDate,\n theme,\n animationLevel,\n chatsById,\n openChat,\n openTipsChat,\n setGlobalSearchDate,\n setSettingOption,\n}) => {\n const lang = useLang();\n const hasMenu = content === LeftColumnContent.ChatList;\n const clearedDateSearchParam = { date: undefined };\n const clearedChatSearchParam = { id: undefined };\n const selectedSearchDate = useMemo(() => {\n return searchDate\n ? formatDateToString(new Date(searchDate * 1000))\n : undefined;\n }, [searchDate]);\n const archivedUnreadChatsCount = useMemo(() => {\n if (!hasMenu || !chatsById) {\n return 0;\n }\n\n return Object.values(chatsById).reduce((total, chat) => {\n if (!isChatArchived(chat)) {\n return total;\n }\n\n return chat.unreadCount ? total + 1 : total;\n }, 0);\n }, [hasMenu, chatsById]);\n\n const withOtherVersions = window.location.hostname === PRODUCTION_HOSTNAME;\n\n const MainButton: FC<{ onTrigger: () => void; isOpen?: boolean }> = useMemo(() => {\n return ({ onTrigger, isOpen }) => (\n <Button\n round\n ripple={hasMenu && !IS_SINGLE_COLUMN_LAYOUT}\n size=\"smaller\"\n color=\"translucent\"\n className={isOpen ? 'active' : ''}\n onClick={hasMenu ? onTrigger : () => onReset()}\n ariaLabel={hasMenu ? lang('AccDescrOpenMenu2') : 'Return to chat list'}\n >\n <div className={buildClassName(\n 'animated-menu-icon',\n !hasMenu && 'state-back',\n shouldSkipTransition && 'no-animation',\n )}\n />\n </Button>\n );\n }, [hasMenu, lang, onReset, shouldSkipTransition]);\n\n const handleSearchFocus = useCallback(() => {\n if (!searchQuery) {\n onSearchQuery('');\n }\n }, [searchQuery, onSearchQuery]);\n\n const handleSelectSaved = useCallback(() => {\n openChat({ id: currentUserId, shouldReplaceHistory: true });\n }, [currentUserId, openChat]);\n\n const handleDarkModeToggle = useCallback((e: React.SyntheticEvent<HTMLElement>) => {\n e.stopPropagation();\n const newTheme = theme === 'light' ? 'dark' : 'light';\n\n setSettingOption({ theme: newTheme });\n setSettingOption({ shouldUseSystemTheme: false });\n switchTheme(newTheme, animationLevel === ANIMATION_LEVEL_MAX);\n }, [animationLevel, setSettingOption, theme]);\n\n const handleAnimationLevelChange = useCallback((e: React.SyntheticEvent<HTMLElement>) => {\n e.stopPropagation();\n\n const newLevel = animationLevel === 0 ? 2 : 0;\n ANIMATION_LEVEL_OPTIONS.forEach((_, i) => {\n document.body.classList.toggle(`animation-level-${i}`, newLevel === i);\n });\n\n setSettingOption({ animationLevel: newLevel });\n }, [animationLevel, setSettingOption]);\n\n const handleSwitchToWebK = () => {\n localStorage.setItem(PERMANENT_VERSION_KEY, JSON.stringify('K'));\n disableHistoryBack();\n };\n\n const handleOpenTipsChat = () => {\n openTipsChat({ langCode: lang.code });\n };\n\n const isSearchFocused = (\n Boolean(globalSearchChatId)\n || content === LeftColumnContent.GlobalSearch\n || content === LeftColumnContent.Contacts\n );\n\n const searchInputPlaceholder = content === LeftColumnContent.Contacts\n ? lang('SearchFriends')\n : lang('Search');\n\n return (\n <div className=\"LeftMainHeader\">\n <div id=\"LeftMainHeader\" className=\"left-header\">\n <DropdownMenu\n trigger={MainButton}\n footer={`${APP_NAME} alpha ${APP_VERSION}`}\n >\n <MenuItem\n icon=\"saved-messages\"\n onClick={handleSelectSaved}\n >\n {lang('SavedMessages')}\n </MenuItem>\n <MenuItem\n icon=\"archive\"\n onClick={onSelectArchived}\n >\n <span className=\"menu-item-name\">{lang('ArchivedChats')}</span>\n {archivedUnreadChatsCount > 0 && (\n <div className=\"archived-badge\">{archivedUnreadChatsCount}</div>\n )}\n </MenuItem>\n <MenuItem\n icon=\"user\"\n onClick={onSelectContacts}\n >\n {lang('Contacts')}\n </MenuItem>\n <MenuItem\n icon=\"settings\"\n onClick={onSelectSettings}\n >\n {lang('Settings')}\n </MenuItem>\n <MenuItem\n icon=\"darkmode\"\n onClick={handleDarkModeToggle}\n >\n <span className=\"menu-item-name\">{lang('lng_menu_night_mode')}</span>\n <Switcher\n id=\"darkmode\"\n label={lang(theme === 'dark' ? 'lng_settings_disable_night_theme' : 'lng_settings_enable_night_theme')}\n checked={theme === 'dark'}\n noAnimation\n />\n </MenuItem>\n <MenuItem\n icon=\"animations\"\n onClick={handleAnimationLevelChange}\n >\n <span className=\"menu-item-name capitalize\">{lang('Appearance.Animations').toLowerCase()}</span>\n <Switcher\n id=\"animations\"\n label=\"Toggle Animations\"\n checked={animationLevel > 0}\n />\n </MenuItem>\n <MenuItem\n icon=\"help\"\n onClick={handleOpenTipsChat}\n >\n {lang('TelegramFeatures')}\n </MenuItem>\n <MenuItem\n icon=\"bug\"\n href={FEEDBACK_URL}\n >\n Report Bug\n </MenuItem>\n {withOtherVersions && (\n <>\n <MenuItem\n icon=\"char-K\"\n href={WEBK_VERSION_URL}\n onClick={handleSwitchToWebK}\n >\n Switch to K Version\n </MenuItem>\n <MenuItem\n icon=\"char-W\"\n href={LEGACY_VERSION_URL}\n onClick={disableHistoryBack}\n >\n Switch to Old Version\n </MenuItem>\n </>\n )}\n </DropdownMenu>\n <SearchInput\n inputId=\"telegram-search-input\"\n parentContainerClassName=\"LeftSearch\"\n className={globalSearchChatId || searchDate ? 'with-picker-item' : ''}\n value={contactsFilter || searchQuery}\n focused={isSearchFocused}\n isLoading={isLoading}\n placeholder={searchInputPlaceholder}\n autoComplete=\"off\"\n canClose={Boolean(globalSearchChatId || searchDate)}\n onChange={onSearchQuery}\n onReset={onReset}\n onFocus={handleSearchFocus}\n >\n {selectedSearchDate && (\n <PickerSelectedItem\n icon=\"calendar\"\n title={selectedSearchDate}\n canClose\n isMinimized={Boolean(globalSearchChatId)}\n className=\"search-date\"\n onClick={setGlobalSearchDate}\n clickArg={clearedDateSearchParam}\n />\n )}\n {globalSearchChatId && (\n <PickerSelectedItem\n chatOrUserId={globalSearchChatId}\n onClick={setGlobalSearchChatId}\n canClose\n clickArg={clearedChatSearchParam}\n />\n )}\n </SearchInput>\n </div>\n </div>\n );\n};\n\nexport default memo(withGlobal<OwnProps>(\n (global): StateProps => {\n const {\n query: searchQuery, fetchingStatus, chatId, date,\n } = global.globalSearch;\n const { currentUserId } = global;\n const { byId: chatsById } = global.chats;\n const { animationLevel } = global.settings.byKey;\n\n return {\n searchQuery,\n isLoading: fetchingStatus ? Boolean(fetchingStatus.chats || fetchingStatus.messages) : false,\n currentUserId,\n chatsById,\n globalSearchChatId: chatId,\n searchDate: date,\n theme: selectTheme(global),\n animationLevel,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'openChat',\n 'openTipsChat',\n 'setGlobalSearchDate',\n 'setGlobalSearchChatId',\n 'setSettingOption',\n ]),\n)(LeftMainHeader));\n","import React, { memo, FC } from '../../lib/teact/teact';\n\nimport { GlobalState } from '../../global/types';\n\nimport useLang from '../../hooks/useLang';\n\nimport Spinner from '../ui/Spinner';\n\nimport './ConnectionState.scss';\n\ntype StateProps = Pick<GlobalState, 'connectionState'>;\n\nconst ConnectionState: FC<StateProps> = () => {\n const lang = useLang();\n\n return (\n <div id=\"ConnectionState\" dir={lang.isRtl ? 'rtl' : undefined}>\n <Spinner color=\"black\" />\n <div className=\"state-text\">{lang('WaitingForNetwork')}</div>\n </div>\n );\n};\n\nexport default memo(ConnectionState);\n","import React, {\n FC, memo, useCallback, useEffect, useMemo, useRef,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { ApiChat, ApiChatFolder, ApiUser } from '../../../api/types';\nimport { GlobalActions } from '../../../global/types';\nimport { NotifyException, NotifySettings, SettingsScreens } from '../../../types';\nimport { FolderEditDispatch } from '../../../hooks/reducers/useFoldersReducer';\n\nimport { IS_TOUCH_ENV } from '../../../util/environment';\nimport { buildCollectionByKey, pick } from '../../../util/iteratees';\nimport { captureEvents, SwipeDirection } from '../../../util/captureEvents';\nimport { getFolderUnreadDialogs } from '../../../modules/helpers';\nimport { selectNotifyExceptions, selectNotifySettings } from '../../../modules/selectors';\nimport useShowTransition from '../../../hooks/useShowTransition';\nimport buildClassName from '../../../util/buildClassName';\nimport useThrottledMemo from '../../../hooks/useThrottledMemo';\nimport useLang from '../../../hooks/useLang';\nimport useHistoryBack from '../../../hooks/useHistoryBack';\nimport captureEscKeyListener from '../../../util/captureEscKeyListener';\n\nimport Transition from '../../ui/Transition';\nimport TabList from '../../ui/TabList';\nimport ChatList from './ChatList';\n\ntype OwnProps = {\n onScreenSelect: (screen: SettingsScreens) => void;\n foldersDispatch: FolderEditDispatch;\n};\n\ntype StateProps = {\n chatsById: Record<string, ApiChat>;\n usersById: Record<string, ApiUser>;\n chatFoldersById: Record<number, ApiChatFolder>;\n notifySettings: NotifySettings;\n notifyExceptions?: Record<number, NotifyException>;\n orderedFolderIds?: number[];\n activeChatFolder: number;\n currentUserId?: string;\n lastSyncTime?: number;\n shouldSkipHistoryAnimations?: boolean;\n};\n\ntype DispatchProps = Pick<GlobalActions, 'loadChatFolders' | 'setActiveChatFolder' | 'openChat'>;\n\nconst INFO_THROTTLE = 3000;\nconst SAVED_MESSAGES_HOTKEY = '0';\n\nconst ChatFolders: FC<OwnProps & StateProps & DispatchProps> = ({\n chatsById,\n usersById,\n chatFoldersById,\n notifySettings,\n notifyExceptions,\n orderedFolderIds,\n activeChatFolder,\n currentUserId,\n lastSyncTime,\n shouldSkipHistoryAnimations,\n foldersDispatch,\n onScreenSelect,\n loadChatFolders,\n setActiveChatFolder,\n openChat,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const transitionRef = useRef<HTMLDivElement>(null);\n\n const lang = useLang();\n\n useEffect(() => {\n if (lastSyncTime) {\n loadChatFolders();\n }\n }, [lastSyncTime, loadChatFolders]);\n\n const displayedFolders = useMemo(() => {\n return orderedFolderIds\n ? orderedFolderIds.map((id) => chatFoldersById[id] || {}).filter(Boolean)\n : undefined;\n }, [chatFoldersById, orderedFolderIds]);\n\n const folderCountersById = useThrottledMemo(() => {\n if (!displayedFolders || !displayedFolders.length) {\n return undefined;\n }\n\n const chatIds = Object.keys(chatsById);\n const counters = displayedFolders.map((folder) => {\n const {\n unreadDialogsCount, hasActiveDialogs,\n } = getFolderUnreadDialogs(chatsById, usersById, folder, chatIds, notifySettings, notifyExceptions) || {};\n\n return {\n id: folder.id,\n badgeCount: unreadDialogsCount,\n isBadgeActive: hasActiveDialogs,\n };\n });\n\n return buildCollectionByKey(counters, 'id');\n }, INFO_THROTTLE, [displayedFolders, chatsById, usersById, notifySettings, notifyExceptions]);\n\n const folderTabs = useMemo(() => {\n if (!displayedFolders || !displayedFolders.length) {\n return undefined;\n }\n\n return [\n { title: lang.code === 'en' ? 'All' : lang('FilterAllChats') },\n ...displayedFolders.map((folder) => ({\n title: folder.title,\n ...(folderCountersById?.[folder.id]),\n })),\n ];\n }, [displayedFolders, folderCountersById, lang]);\n\n const handleSwitchTab = useCallback((index: number) => {\n setActiveChatFolder(index);\n }, [setActiveChatFolder]);\n\n // Prevent `activeTab` pointing at non-existing folder after update\n useEffect(() => {\n if (!folderTabs || !folderTabs.length) {\n return;\n }\n\n if (activeChatFolder >= folderTabs.length) {\n setActiveChatFolder(0);\n }\n }, [activeChatFolder, folderTabs, setActiveChatFolder]);\n\n useEffect(() => {\n if (!transitionRef.current || !IS_TOUCH_ENV || !folderTabs || !folderTabs.length) {\n return undefined;\n }\n\n return captureEvents(transitionRef.current, {\n selectorToPreventScroll: '.chat-list',\n onSwipe: ((e, direction) => {\n if (direction === SwipeDirection.Left) {\n setActiveChatFolder(Math.min(activeChatFolder + 1, folderTabs.length - 1));\n return true;\n } else if (direction === SwipeDirection.Right) {\n setActiveChatFolder(Math.max(0, activeChatFolder - 1));\n return true;\n }\n\n return false;\n }),\n });\n }, [activeChatFolder, folderTabs, setActiveChatFolder]);\n\n const isNotInAllTabRef = useRef();\n isNotInAllTabRef.current = activeChatFolder !== 0;\n useEffect(() => (isNotInAllTabRef.current ? captureEscKeyListener(() => {\n if (isNotInAllTabRef.current) {\n setActiveChatFolder(0);\n }\n }) : undefined), [activeChatFolder, setActiveChatFolder]);\n\n useHistoryBack(activeChatFolder !== 0, () => setActiveChatFolder(0));\n\n useEffect(() => {\n const handleKeyDown = (e: KeyboardEvent) => {\n if (e.ctrlKey && e.shiftKey && e.code.startsWith('Digit') && folderTabs) {\n const [, digit] = e.code.match(/Digit(\\d)/) || [];\n if (!digit) return;\n\n if (digit === SAVED_MESSAGES_HOTKEY) {\n openChat({ id: currentUserId, shouldReplaceHistory: true });\n return;\n }\n\n const folder = Number(digit) - 1;\n if (folder > folderTabs.length - 1) return;\n\n setActiveChatFolder(folder);\n e.preventDefault();\n }\n };\n\n document.addEventListener('keydown', handleKeyDown, true);\n\n return () => {\n document.removeEventListener('keydown', handleKeyDown, true);\n };\n });\n\n const {\n shouldRender: shouldRenderPlaceholder, transitionClassNames,\n } = useShowTransition(!orderedFolderIds, undefined, true);\n\n function renderCurrentTab(isActive: boolean) {\n const activeFolder = Object.values(chatFoldersById)\n .find(({ title }) => title === folderTabs![activeChatFolder].title);\n\n if (!activeFolder || activeChatFolder === 0) {\n return (\n <ChatList\n folderType=\"all\"\n isActive={isActive}\n foldersDispatch={foldersDispatch}\n onScreenSelect={onScreenSelect}\n />\n );\n }\n\n return (\n <ChatList\n folderType=\"folder\"\n folderId={activeFolder.id}\n isActive={isActive}\n onScreenSelect={onScreenSelect}\n foldersDispatch={foldersDispatch}\n />\n );\n }\n\n return (\n <div className=\"ChatFolders\">\n {folderTabs?.length ? (\n <TabList tabs={folderTabs} activeTab={activeChatFolder} onSwitchTab={handleSwitchTab} />\n ) : shouldRenderPlaceholder ? (\n <div className={buildClassName('tabs-placeholder', transitionClassNames)} />\n ) : undefined}\n <Transition\n ref={transitionRef}\n name={shouldSkipHistoryAnimations ? 'none' : lang.isRtl ? 'slide-reversed' : 'slide'}\n activeKey={activeChatFolder}\n renderCount={folderTabs ? folderTabs.length : undefined}\n >\n {renderCurrentTab}\n </Transition>\n </div>\n );\n};\n\nexport default memo(withGlobal<OwnProps>(\n (global): StateProps => {\n const {\n chats: { byId: chatsById },\n users: { byId: usersById },\n chatFolders: {\n byId: chatFoldersById,\n orderedIds: orderedFolderIds,\n activeChatFolder,\n },\n currentUserId,\n lastSyncTime,\n shouldSkipHistoryAnimations,\n } = global;\n\n return {\n chatsById,\n usersById,\n chatFoldersById,\n orderedFolderIds,\n lastSyncTime,\n notifySettings: selectNotifySettings(global),\n notifyExceptions: selectNotifyExceptions(global),\n activeChatFolder,\n currentUserId,\n shouldSkipHistoryAnimations,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'loadChatFolders',\n 'setActiveChatFolder',\n 'openChat',\n ]),\n)(ChatFolders));\n","import { useState } from '../lib/teact/teact';\n\nimport useThrottle from './useThrottle';\nimport useOnChange from './useOnChange';\nimport useHeavyAnimationCheck from './useHeavyAnimationCheck';\nimport useFlag from './useFlag';\n\nexport default <R extends any, D extends any[]>(resolverFn: () => R, ms: number, dependencies: D) => {\n const runThrottled = useThrottle(ms, true);\n const [value, setValue] = useState<R>();\n const [isFrozen, freeze, unfreeze] = useFlag();\n\n useHeavyAnimationCheck(freeze, unfreeze);\n\n useOnChange(() => {\n if (isFrozen) {\n return;\n }\n\n runThrottled(() => {\n setValue(resolverFn());\n });\n }, dependencies.concat([isFrozen]));\n\n return value;\n};\n","import { useMemo } from '../lib/teact/teact';\n\nimport { throttle } from '../util/schedulers';\n\nexport default (ms: number, noFirst = false) => {\n return useMemo(() => {\n return throttle((cb) => cb(), ms, !noFirst);\n }, [ms, noFirst]);\n};\n","import React, { FC, memo } from '../../../lib/teact/teact';\nimport { Bundles } from '../../../util/moduleLoader';\nimport { OwnProps } from './LeftSearch';\n\nimport useModuleLoader from '../../../hooks/useModuleLoader';\nimport Loading from '../../ui/Loading';\n\nconst LeftSearchAsync: FC<OwnProps> = (props) => {\n const LeftSearch = useModuleLoader(Bundles.Extra, 'LeftSearch');\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return LeftSearch ? <LeftSearch {...props} /> : <Loading />;\n};\n\nexport default memo(LeftSearchAsync);\n","import React, { FC, memo } from '../../../lib/teact/teact';\nimport { Bundles } from '../../../util/moduleLoader';\nimport { OwnProps } from './ContactList';\n\nimport useModuleLoader from '../../../hooks/useModuleLoader';\nimport Loading from '../../ui/Loading';\n\nconst ContactListAsync: FC<OwnProps> = (props) => {\n const ContactList = useModuleLoader(Bundles.Extra, 'ContactList');\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return ContactList ? <ContactList {...props} /> : <Loading />;\n};\n\nexport default memo(ContactListAsync);\n","import React, {\n FC, useCallback, useState, useEffect, memo,\n} from '../../lib/teact/teact';\n\nimport buildClassName from '../../util/buildClassName';\nimport useLang from '../../hooks/useLang';\n\nimport Button from '../ui/Button';\nimport Menu from '../ui/Menu';\nimport MenuItem from '../ui/MenuItem';\n\nimport './NewChatButton.scss';\n\nconst MENU_CLOSE_DELAY_MS = 750;\nlet closeTimeout: number | undefined;\n\ntype OwnProps = {\n isShown: boolean;\n onNewPrivateChat: () => void;\n onNewChannel: () => void;\n onNewGroup: () => void;\n};\n\nconst NewChatButton: FC<OwnProps> = ({\n isShown,\n onNewPrivateChat,\n onNewChannel,\n onNewGroup,\n}) => {\n const [isMenuOpen, setIsMenuOpen] = useState(false);\n\n useEffect(() => {\n if (!isShown) {\n setIsMenuOpen(false);\n }\n }, [isShown]);\n\n const lang = useLang();\n\n const fabClassName = buildClassName(\n 'NewChatButton',\n isShown && 'revealed',\n isMenuOpen && 'menu-is-open',\n );\n\n const toggleIsMenuOpen = () => {\n setIsMenuOpen(!isMenuOpen);\n };\n\n const handleClose = () => {\n setIsMenuOpen(false);\n };\n\n const handleMouseEnter = useCallback(() => {\n if (closeTimeout) {\n clearTimeout(closeTimeout);\n closeTimeout = undefined;\n }\n }, []);\n\n const handleMouseLeave = useCallback(() => {\n if (closeTimeout) {\n clearTimeout(closeTimeout);\n closeTimeout = undefined;\n }\n\n closeTimeout = window.setTimeout(() => {\n setIsMenuOpen(false);\n }, MENU_CLOSE_DELAY_MS);\n }, []);\n\n return (\n <div\n className={fabClassName}\n onMouseEnter={handleMouseEnter}\n onMouseLeave={handleMouseLeave}\n >\n <Button\n round\n color=\"primary\"\n className={isMenuOpen ? 'active' : ''}\n onClick={toggleIsMenuOpen}\n ariaLabel={lang(isMenuOpen ? 'Close' : 'NewMessageTitle')}\n tabIndex={-1}\n >\n <i className=\"icon-new-chat-filled\" />\n <i className=\"icon-close\" />\n </Button>\n <Menu\n isOpen={isMenuOpen}\n positionX=\"right\"\n positionY=\"bottom\"\n autoClose\n onClose={handleClose}\n >\n <MenuItem icon=\"channel\" onClick={onNewChannel}>{lang('NewChannel')}</MenuItem>\n <MenuItem icon=\"group\" onClick={onNewGroup}>{lang('NewGroup')}</MenuItem>\n <MenuItem icon=\"user\" onClick={onNewPrivateChat}>{lang('NewMessageTitle')}</MenuItem>\n </Menu>\n </div>\n );\n};\n\nexport default memo(NewChatButton);\n","import React, {\n FC, useState, useRef, useCallback, useEffect,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalState } from '../../../global/types';\nimport { LeftColumnContent, SettingsScreens } from '../../../types';\nimport { FolderEditDispatch } from '../../../hooks/reducers/useFoldersReducer';\n\nimport { IS_TOUCH_ENV } from '../../../util/environment';\nimport { pick } from '../../../util/iteratees';\nimport buildClassName from '../../../util/buildClassName';\nimport useBrowserOnline from '../../../hooks/useBrowserOnline';\nimport useFlag from '../../../hooks/useFlag';\nimport useShowTransition from '../../../hooks/useShowTransition';\nimport useLang from '../../../hooks/useLang';\n\nimport Transition from '../../ui/Transition';\nimport LeftMainHeader from './LeftMainHeader';\nimport ConnectionState from '../ConnectionState';\nimport ChatFolders from './ChatFolders';\nimport LeftSearch from '../search/LeftSearch.async';\nimport ContactList from './ContactList.async';\nimport NewChatButton from '../NewChatButton';\nimport ShowTransition from '../../ui/ShowTransition';\nimport Button from '../../ui/Button';\n\nimport './LeftMain.scss';\n\ntype OwnProps = {\n content: LeftColumnContent;\n searchQuery?: string;\n searchDate?: number;\n contactsFilter: string;\n shouldSkipTransition?: boolean;\n foldersDispatch: FolderEditDispatch;\n onSearchQuery: (query: string) => void;\n onContentChange: (content: LeftColumnContent) => void;\n onScreenSelect: (screen: SettingsScreens) => void;\n onReset: () => void;\n};\n\ntype StateProps = Pick<GlobalState, 'connectionState'>;\n\nconst TRANSITION_RENDER_COUNT = Object.keys(LeftColumnContent).length / 2;\nconst BUTTON_CLOSE_DELAY_MS = 250;\nconst APP_OUTDATED_TIMEOUT = 3 * 24 * 60 * 60 * 1000; // 3 days\n\nlet closeTimeout: number | undefined;\n\nconst LeftMain: FC<OwnProps & StateProps> = ({\n content,\n searchQuery,\n searchDate,\n contactsFilter,\n shouldSkipTransition,\n foldersDispatch,\n onSearchQuery,\n onContentChange,\n onScreenSelect,\n onReset,\n connectionState,\n}) => {\n const [isNewChatButtonShown, setIsNewChatButtonShown] = useState(IS_TOUCH_ENV);\n\n const isBrowserOnline = useBrowserOnline();\n const isConnecting = !isBrowserOnline || connectionState === 'connectionStateConnecting';\n\n const isMouseInside = useRef(false);\n\n const handleSelectSettings = useCallback(() => {\n onContentChange(LeftColumnContent.Settings);\n }, [onContentChange]);\n\n const handleSelectContacts = useCallback(() => {\n onContentChange(LeftColumnContent.Contacts);\n }, [onContentChange]);\n\n const handleSelectNewChannel = useCallback(() => {\n onContentChange(LeftColumnContent.NewChannelStep1);\n }, [onContentChange]);\n\n const handleSelectNewGroup = useCallback(() => {\n onContentChange(LeftColumnContent.NewGroupStep1);\n }, [onContentChange]);\n\n const handleSelectArchived = useCallback(() => {\n onContentChange(LeftColumnContent.Archived);\n }, [onContentChange]);\n\n const handleMouseEnter = useCallback(() => {\n if (content !== LeftColumnContent.ChatList) {\n return;\n }\n isMouseInside.current = true;\n setIsNewChatButtonShown(true);\n }, [content]);\n\n const handleMouseLeave = useCallback(() => {\n isMouseInside.current = false;\n\n if (closeTimeout) {\n clearTimeout(closeTimeout);\n closeTimeout = undefined;\n }\n\n closeTimeout = window.setTimeout(() => {\n if (!isMouseInside.current) {\n setIsNewChatButtonShown(false);\n }\n }, BUTTON_CLOSE_DELAY_MS);\n }, []);\n\n useEffect(() => {\n let autoCloseTimeout: number | undefined;\n if (content !== LeftColumnContent.ChatList) {\n autoCloseTimeout = window.setTimeout(() => {\n setIsNewChatButtonShown(false);\n }, BUTTON_CLOSE_DELAY_MS);\n } else if (isMouseInside.current || IS_TOUCH_ENV) {\n setIsNewChatButtonShown(true);\n }\n\n return () => {\n if (autoCloseTimeout) {\n clearTimeout(autoCloseTimeout);\n autoCloseTimeout = undefined;\n }\n };\n }, [content]);\n\n const [shouldRenderUpdateButton, updateButtonClassNames, handleUpdateClick] = useAppOutdatedCheck();\n\n const lang = useLang();\n\n return (\n <div\n id=\"LeftColumn-main\"\n onMouseEnter={!IS_TOUCH_ENV ? handleMouseEnter : undefined}\n onMouseLeave={!IS_TOUCH_ENV ? handleMouseLeave : undefined}\n >\n <LeftMainHeader\n content={content}\n contactsFilter={contactsFilter}\n onSearchQuery={onSearchQuery}\n onSelectSettings={handleSelectSettings}\n onSelectContacts={handleSelectContacts}\n onSelectArchived={handleSelectArchived}\n onReset={onReset}\n shouldSkipTransition={shouldSkipTransition}\n />\n <ShowTransition isOpen={isConnecting} isCustom className=\"connection-state-wrapper opacity-transition slow\">\n {() => <ConnectionState />}\n </ShowTransition>\n <Transition\n name={shouldSkipTransition ? 'none' : 'zoom-fade'}\n renderCount={TRANSITION_RENDER_COUNT}\n activeKey={content}\n shouldCleanup\n cleanupExceptionKey={LeftColumnContent.ChatList}\n className={isConnecting ? 'pull-down' : undefined}\n >\n {(isActive) => {\n switch (content) {\n case LeftColumnContent.ChatList:\n return <ChatFolders onScreenSelect={onScreenSelect} foldersDispatch={foldersDispatch} />;\n case LeftColumnContent.GlobalSearch:\n return (\n <LeftSearch\n searchQuery={searchQuery}\n searchDate={searchDate}\n isActive={isActive}\n onReset={onReset}\n />\n );\n case LeftColumnContent.Contacts:\n return <ContactList filter={contactsFilter} isActive={isActive} onReset={onReset} />;\n default:\n return undefined;\n }\n }}\n </Transition>\n {shouldRenderUpdateButton && (\n <Button\n fluid\n pill\n className={buildClassName('btn-update', updateButtonClassNames)}\n onClick={handleUpdateClick}\n >\n {lang('lng_update_telegram')}\n </Button>\n )}\n <NewChatButton\n isShown={isNewChatButtonShown}\n onNewPrivateChat={handleSelectContacts}\n onNewChannel={handleSelectNewChannel}\n onNewGroup={handleSelectNewGroup}\n />\n </div>\n );\n};\n\nfunction useAppOutdatedCheck() {\n const [isAppOutdated, markIsAppOutdated] = useFlag(false);\n\n useEffect(() => {\n const timeout = window.setTimeout(markIsAppOutdated, APP_OUTDATED_TIMEOUT);\n\n return () => {\n clearTimeout(timeout);\n };\n }, [markIsAppOutdated]);\n\n const { shouldRender, transitionClassNames } = useShowTransition(isAppOutdated);\n\n const handleUpdateClick = () => {\n window.location.reload();\n };\n\n return [shouldRender, transitionClassNames, handleUpdateClick] as const;\n}\n\nexport default withGlobal<OwnProps>(\n (global): StateProps => pick(global, ['connectionState']),\n)(LeftMain);\n","import React, { FC, memo } from '../../../lib/teact/teact';\nimport { Bundles } from '../../../util/moduleLoader';\n\nimport { OwnProps } from './Settings';\n\nimport useModuleLoader from '../../../hooks/useModuleLoader';\nimport Loading from '../../ui/Loading';\n\nconst SettingsAsync: FC<OwnProps> = (props) => {\n const Settings = useModuleLoader(Bundles.Extra, 'Settings');\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return Settings ? <Settings {...props} /> : <Loading />;\n};\n\nexport default memo(SettingsAsync);\n","import React, { FC, memo } from '../../../lib/teact/teact';\nimport { Bundles } from '../../../util/moduleLoader';\n\nimport { OwnProps } from './NewChat';\n\nimport useModuleLoader from '../../../hooks/useModuleLoader';\nimport Loading from '../../ui/Loading';\n\nconst NewChatAsync: FC<OwnProps> = (props) => {\n const NewChat = useModuleLoader(Bundles.Extra, 'NewChat');\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return NewChat ? <NewChat {...props} /> : <Loading />;\n};\n\nexport default memo(NewChatAsync);\n","import React, { FC, memo } from '../../lib/teact/teact';\nimport { OwnProps } from './ArchivedChats';\nimport { Bundles } from '../../util/moduleLoader';\n\nimport useModuleLoader from '../../hooks/useModuleLoader';\nimport Loading from '../ui/Loading';\n\nconst ArchivedChatsAsync: FC<OwnProps> = (props) => {\n const ArchivedChats = useModuleLoader(Bundles.Extra, 'ArchivedChats');\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return ArchivedChats ? <ArchivedChats {...props} /> : <Loading />;\n};\n\nexport default memo(ArchivedChatsAsync);\n","import React, {\n FC, memo, useCallback, useEffect, useRef, useState,\n} from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../global/types';\nimport { LeftColumnContent, SettingsScreens } from '../../types';\n\nimport { LAYERS_ANIMATION_NAME } from '../../util/environment';\nimport captureEscKeyListener from '../../util/captureEscKeyListener';\nimport { pick } from '../../util/iteratees';\nimport useFoldersReducer from '../../hooks/reducers/useFoldersReducer';\nimport { useResize } from '../../hooks/useResize';\n\nimport Transition from '../ui/Transition';\nimport LeftMain from './main/LeftMain';\nimport Settings from './settings/Settings.async';\nimport NewChat from './newChat/NewChat.async';\nimport ArchivedChats from './ArchivedChats.async';\n\nimport './LeftColumn.scss';\n\ntype StateProps = {\n searchQuery?: string;\n searchDate?: number;\n activeChatFolder: number;\n shouldSkipHistoryAnimations?: boolean;\n leftColumnWidth?: number;\n};\n\ntype DispatchProps = Pick<GlobalActions, (\n 'setGlobalSearchQuery' | 'setGlobalSearchChatId' | 'resetChatCreation' | 'setGlobalSearchDate' |\n 'loadPasswordInfo' | 'clearTwoFaError' | 'setLeftColumnWidth' | 'resetLeftColumnWidth'\n)>;\n\nenum ContentType {\n Main,\n // eslint-disable-next-line @typescript-eslint/no-shadow\n Settings,\n Archived,\n // eslint-disable-next-line no-shadow\n NewGroup,\n // eslint-disable-next-line no-shadow\n NewChannel,\n}\n\nconst RENDER_COUNT = Object.keys(ContentType).length / 2;\nconst RESET_TRANSITION_DELAY_MS = 250;\n\nconst LeftColumn: FC<StateProps & DispatchProps> = ({\n searchQuery,\n searchDate,\n activeChatFolder,\n shouldSkipHistoryAnimations,\n leftColumnWidth,\n setGlobalSearchQuery,\n setGlobalSearchChatId,\n resetChatCreation,\n setGlobalSearchDate,\n loadPasswordInfo,\n clearTwoFaError,\n setLeftColumnWidth,\n resetLeftColumnWidth,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const resizeRef = useRef<HTMLDivElement>(null);\n const [content, setContent] = useState<LeftColumnContent>(LeftColumnContent.ChatList);\n const [settingsScreen, setSettingsScreen] = useState(SettingsScreens.Main);\n const [contactsFilter, setContactsFilter] = useState<string>('');\n const [foldersState, foldersDispatch] = useFoldersReducer();\n\n // Used to reset child components in background.\n const [lastResetTime, setLastResetTime] = useState<number>(0);\n\n let contentType: ContentType = ContentType.Main;\n switch (content) {\n case LeftColumnContent.Archived:\n contentType = ContentType.Archived;\n break;\n case LeftColumnContent.Settings:\n contentType = ContentType.Settings;\n break;\n case LeftColumnContent.NewChannelStep1:\n case LeftColumnContent.NewChannelStep2:\n contentType = ContentType.NewChannel;\n break;\n case LeftColumnContent.NewGroupStep1:\n case LeftColumnContent.NewGroupStep2:\n contentType = ContentType.NewGroup;\n break;\n }\n\n const handleReset = useCallback((forceReturnToChatList?: boolean) => {\n if (content === LeftColumnContent.NewGroupStep2\n && !forceReturnToChatList\n ) {\n setContent(LeftColumnContent.NewGroupStep1);\n return;\n }\n\n if (content === LeftColumnContent.NewChannelStep2\n && !forceReturnToChatList\n ) {\n setContent(LeftColumnContent.NewChannelStep1);\n return;\n }\n\n if (content === LeftColumnContent.NewGroupStep1) {\n const pickerSearchInput = document.getElementById('new-group-picker-search');\n if (pickerSearchInput) {\n pickerSearchInput.blur();\n }\n }\n\n if (content === LeftColumnContent.Settings) {\n switch (settingsScreen) {\n case SettingsScreens.EditProfile:\n case SettingsScreens.Folders:\n case SettingsScreens.General:\n case SettingsScreens.Notifications:\n case SettingsScreens.DataStorage:\n case SettingsScreens.Privacy:\n case SettingsScreens.Language:\n setSettingsScreen(SettingsScreens.Main);\n return;\n\n case SettingsScreens.GeneralChatBackground:\n setSettingsScreen(SettingsScreens.General);\n return;\n case SettingsScreens.GeneralChatBackgroundColor:\n setSettingsScreen(SettingsScreens.GeneralChatBackground);\n return;\n\n case SettingsScreens.PrivacyPhoneNumber:\n case SettingsScreens.PrivacyLastSeen:\n case SettingsScreens.PrivacyProfilePhoto:\n case SettingsScreens.PrivacyForwarding:\n case SettingsScreens.PrivacyGroupChats:\n case SettingsScreens.PrivacyActiveSessions:\n case SettingsScreens.PrivacyBlockedUsers:\n case SettingsScreens.TwoFaDisabled:\n case SettingsScreens.TwoFaEnabled:\n case SettingsScreens.TwoFaCongratulations:\n setSettingsScreen(SettingsScreens.Privacy);\n return;\n case SettingsScreens.PrivacyPhoneNumberAllowedContacts:\n case SettingsScreens.PrivacyPhoneNumberDeniedContacts:\n setSettingsScreen(SettingsScreens.PrivacyPhoneNumber);\n return;\n case SettingsScreens.PrivacyLastSeenAllowedContacts:\n case SettingsScreens.PrivacyLastSeenDeniedContacts:\n setSettingsScreen(SettingsScreens.PrivacyLastSeen);\n return;\n case SettingsScreens.PrivacyProfilePhotoAllowedContacts:\n case SettingsScreens.PrivacyProfilePhotoDeniedContacts:\n setSettingsScreen(SettingsScreens.PrivacyProfilePhoto);\n return;\n case SettingsScreens.PrivacyForwardingAllowedContacts:\n case SettingsScreens.PrivacyForwardingDeniedContacts:\n setSettingsScreen(SettingsScreens.PrivacyForwarding);\n return;\n case SettingsScreens.PrivacyGroupChatsAllowedContacts:\n case SettingsScreens.PrivacyGroupChatsDeniedContacts:\n setSettingsScreen(SettingsScreens.PrivacyGroupChats);\n return;\n case SettingsScreens.TwoFaNewPassword:\n setSettingsScreen(SettingsScreens.TwoFaDisabled);\n return;\n case SettingsScreens.TwoFaNewPasswordConfirm:\n setSettingsScreen(SettingsScreens.TwoFaNewPassword);\n return;\n case SettingsScreens.TwoFaNewPasswordHint:\n setSettingsScreen(SettingsScreens.TwoFaNewPasswordConfirm);\n return;\n case SettingsScreens.TwoFaNewPasswordEmail:\n setSettingsScreen(SettingsScreens.TwoFaNewPasswordHint);\n return;\n case SettingsScreens.TwoFaNewPasswordEmailCode:\n setSettingsScreen(SettingsScreens.TwoFaNewPasswordEmail);\n return;\n case SettingsScreens.TwoFaChangePasswordCurrent:\n case SettingsScreens.TwoFaTurnOff:\n case SettingsScreens.TwoFaRecoveryEmailCurrentPassword:\n setSettingsScreen(SettingsScreens.TwoFaEnabled);\n return;\n case SettingsScreens.TwoFaChangePasswordNew:\n setSettingsScreen(SettingsScreens.TwoFaChangePasswordCurrent);\n return;\n case SettingsScreens.TwoFaChangePasswordConfirm:\n setSettingsScreen(SettingsScreens.TwoFaChangePasswordNew);\n return;\n case SettingsScreens.TwoFaChangePasswordHint:\n setSettingsScreen(SettingsScreens.TwoFaChangePasswordConfirm);\n return;\n case SettingsScreens.TwoFaRecoveryEmail:\n setSettingsScreen(SettingsScreens.TwoFaRecoveryEmailCurrentPassword);\n return;\n case SettingsScreens.TwoFaRecoveryEmailCode:\n setSettingsScreen(SettingsScreens.TwoFaRecoveryEmail);\n return;\n\n case SettingsScreens.FoldersCreateFolder:\n case SettingsScreens.FoldersEditFolder:\n setSettingsScreen(SettingsScreens.Folders);\n return;\n\n case SettingsScreens.FoldersIncludedChatsFromChatList:\n case SettingsScreens.FoldersExcludedChatsFromChatList:\n setSettingsScreen(SettingsScreens.FoldersEditFolderFromChatList);\n return;\n\n case SettingsScreens.FoldersEditFolderFromChatList:\n setContent(LeftColumnContent.ChatList);\n setSettingsScreen(SettingsScreens.Main);\n return;\n default:\n break;\n }\n }\n\n if (content === LeftColumnContent.ChatList && activeChatFolder === 0) {\n setContent(LeftColumnContent.GlobalSearch);\n return;\n }\n\n setContent(LeftColumnContent.ChatList);\n setContactsFilter('');\n setGlobalSearchQuery({ query: '' });\n setGlobalSearchDate({ date: undefined });\n setGlobalSearchChatId({ id: undefined });\n resetChatCreation();\n setTimeout(() => {\n setLastResetTime(Date.now());\n }, RESET_TRANSITION_DELAY_MS);\n }, [\n content, activeChatFolder, settingsScreen, setGlobalSearchQuery, setGlobalSearchDate, setGlobalSearchChatId,\n resetChatCreation,\n ]);\n\n const handleSearchQuery = useCallback((query: string) => {\n if (content === LeftColumnContent.Contacts) {\n setContactsFilter(query);\n return;\n }\n\n setContent(LeftColumnContent.GlobalSearch);\n\n if (query !== searchQuery) {\n setGlobalSearchQuery({ query });\n }\n }, [content, searchQuery, setGlobalSearchQuery]);\n\n useEffect(\n () => (content !== LeftColumnContent.ChatList || activeChatFolder === 0\n ? captureEscKeyListener(() => handleReset())\n : undefined),\n [activeChatFolder, content, handleReset],\n );\n\n useEffect(() => {\n clearTwoFaError();\n\n if (settingsScreen === SettingsScreens.Privacy) {\n loadPasswordInfo();\n }\n }, [clearTwoFaError, loadPasswordInfo, settingsScreen]);\n\n const {\n initResize, resetResize, handleMouseUp,\n } = useResize(resizeRef, setLeftColumnWidth, resetLeftColumnWidth, leftColumnWidth);\n\n const handleSettingsScreenSelect = (screen: SettingsScreens) => {\n setContent(LeftColumnContent.Settings);\n setSettingsScreen(screen);\n };\n\n return (\n <div\n id=\"LeftColumn\"\n ref={resizeRef}\n >\n <Transition\n name={shouldSkipHistoryAnimations ? 'none' : LAYERS_ANIMATION_NAME}\n renderCount={RENDER_COUNT}\n activeKey={contentType}\n shouldCleanup\n cleanupExceptionKey={ContentType.Main}\n >\n {(isActive) => {\n switch (contentType) {\n case ContentType.Archived:\n return (\n <ArchivedChats\n isActive={isActive}\n onReset={handleReset}\n onContentChange={setContent}\n />\n );\n case ContentType.Settings:\n return (\n <Settings\n isActive={isActive}\n currentScreen={settingsScreen}\n foldersState={foldersState}\n foldersDispatch={foldersDispatch}\n onScreenSelect={handleSettingsScreenSelect}\n onReset={handleReset}\n shouldSkipTransition={shouldSkipHistoryAnimations}\n />\n );\n case ContentType.NewChannel:\n return (\n <NewChat\n key={lastResetTime}\n isActive={isActive}\n isChannel\n content={content}\n onContentChange={setContent}\n onReset={handleReset}\n />\n );\n case ContentType.NewGroup:\n return (\n <NewChat\n key={lastResetTime}\n isActive={isActive}\n content={content}\n onContentChange={setContent}\n onReset={handleReset}\n />\n );\n default:\n return (\n <LeftMain\n content={content}\n searchQuery={searchQuery}\n searchDate={searchDate}\n contactsFilter={contactsFilter}\n foldersDispatch={foldersDispatch}\n onContentChange={setContent}\n onSearchQuery={handleSearchQuery}\n onScreenSelect={handleSettingsScreenSelect}\n onReset={handleReset}\n shouldSkipTransition={shouldSkipHistoryAnimations}\n />\n );\n }\n }}\n </Transition>\n <div\n className=\"resize-handle\"\n onMouseDown={initResize}\n onMouseUp={handleMouseUp}\n onDoubleClick={resetResize}\n />\n </div>\n );\n};\n\nexport default memo(withGlobal(\n (global): StateProps => {\n const {\n globalSearch: {\n query,\n date,\n },\n chatFolders: {\n activeChatFolder,\n },\n shouldSkipHistoryAnimations,\n leftColumnWidth,\n } = global;\n return {\n searchQuery: query, searchDate: date, activeChatFolder, shouldSkipHistoryAnimations, leftColumnWidth,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'setGlobalSearchQuery', 'setGlobalSearchChatId', 'resetChatCreation', 'setGlobalSearchDate',\n 'loadPasswordInfo', 'clearTwoFaError', 'setLeftColumnWidth', 'resetLeftColumnWidth',\n ]),\n)(LeftColumn));\n","import { RefObject } from 'react';\nimport { useState, useEffect } from '../lib/teact/teact';\nimport useFlag from './useFlag';\n\nexport const useResize = (\n elementRef: RefObject<HTMLElement>,\n onResize: (width: number) => void,\n onReset: NoneToVoidFunction,\n initialWidth?: number,\n) => {\n const [isActive, markIsActive, unmarkIsActive] = useFlag();\n const [initialMouseX, setInitialMouseX] = useState<number>();\n const [initialElementWidth, setInitialElementWidth] = useState<number>();\n\n useEffect(() => {\n if (!elementRef.current || !initialWidth) {\n return;\n }\n\n elementRef.current.style.width = `${initialWidth}px`;\n }, [elementRef, initialWidth]);\n\n const handleMouseUp = () => {\n document.body.classList.remove('no-selection', 'cursor-ew-resize');\n };\n\n const initResize = (event: React.MouseEvent<HTMLElement, MouseEvent>) => {\n document.body.classList.add('no-selection', 'cursor-ew-resize');\n\n setInitialMouseX(event.clientX);\n setInitialElementWidth(elementRef.current!.offsetWidth);\n markIsActive();\n };\n\n const resetResize = (event: React.MouseEvent<HTMLElement, MouseEvent>) => {\n event.preventDefault();\n elementRef.current!.style.width = '';\n onReset();\n };\n\n useEffect(() => {\n if (!isActive) return;\n\n const handleMouseMove = (event: MouseEvent) => {\n const newWidth = Math.ceil(initialElementWidth + event.clientX - initialMouseX);\n elementRef.current!.style.width = `${newWidth}px`;\n };\n\n const stopDrag = () => {\n handleMouseUp();\n document.removeEventListener('mousemove', handleMouseMove, false);\n document.removeEventListener('mouseup', stopDrag, false);\n document.removeEventListener('blur', stopDrag, false);\n onResize(elementRef.current!.offsetWidth);\n unmarkIsActive();\n };\n\n document.addEventListener('mousemove', handleMouseMove, false);\n document.addEventListener('mouseup', stopDrag, false);\n document.addEventListener('blur', stopDrag, false);\n }, [initialElementWidth, initialMouseX, elementRef, onResize, isActive, unmarkIsActive]);\n\n return { initResize, resetResize, handleMouseUp };\n};\n","import { useEffect, useState } from '../lib/teact/teact';\n\nimport { throttle } from '../util/schedulers';\nimport windowSize from '../util/windowSize';\nimport { ApiDimensions } from '../api/types';\n\nconst THROTTLE = 250;\n\nexport default () => {\n const [size, setSize] = useState<ApiDimensions>(windowSize.get());\n\n useEffect(() => {\n const handleResize = throttle(() => {\n setSize(windowSize.get());\n }, THROTTLE, false);\n\n window.addEventListener('resize', handleResize);\n\n return () => {\n window.removeEventListener('resize', handleResize);\n };\n }, []);\n\n return size;\n};\n","import {\n MIN_SCREEN_WIDTH_FOR_STATIC_LEFT_COLUMN,\n MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN,\n MOBILE_SCREEN_MAX_WIDTH,\n} from '../../../config';\n\nconst REM = 16; // px\nconst MAX_TOOLBAR_WIDTH = 32 * REM;\nconst MAX_MESSAGES_LIST_WIDTH = 45.5 * REM;\nconst SIDE_COLUMN_MAX_WIDTH = 26.5 * REM;\nconst MIN_LEFT_COLUMN_WIDTH = 18 * REM;\nconst UNPIN_BUTTON_WIDTH = 16.125 * REM;\n\nexport default function calculateMiddleFooterTransforms(windowWidth: number, canPost?: boolean) {\n const sidePadding = windowWidth <= MOBILE_SCREEN_MAX_WIDTH\n ? REM\n : 2 * REM;\n const messageListWidth = getMessageListWidth(windowWidth);\n const sendButtonWidth = windowWidth <= MOBILE_SCREEN_MAX_WIDTH\n ? 3.375 * REM\n : 4 * REM;\n\n const composerWidth = canPost\n ? messageListWidth - sidePadding - sendButtonWidth\n : messageListWidth - sidePadding;\n const toolbarWidth = windowWidth > MOBILE_SCREEN_MAX_WIDTH\n ? Math.min(messageListWidth - sidePadding, MAX_TOOLBAR_WIDTH)\n : messageListWidth - sidePadding;\n\n const composerHiddenScale = toolbarWidth / composerWidth;\n const toolbarHiddenScale = composerWidth / toolbarWidth;\n const unpinHiddenScale = toolbarWidth / UNPIN_BUTTON_WIDTH;\n const toolbarForUnpinHiddenScale = UNPIN_BUTTON_WIDTH / toolbarWidth;\n\n const composerTranslateX = canPost\n ? (sendButtonWidth / 2) * toolbarHiddenScale\n : 0;\n\n const toolbarTranslateX = canPost\n ? (sendButtonWidth / 2) * -1 * composerHiddenScale\n : 0;\n\n return {\n composerHiddenScale,\n toolbarHiddenScale,\n composerTranslateX,\n toolbarTranslateX,\n unpinHiddenScale,\n toolbarForUnpinHiddenScale,\n };\n}\n\nfunction getMessageListWidth(windowWidth: number) {\n if (windowWidth > MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN) {\n const leftColumnWidth = Math.min(\n Math.max(windowWidth * 0.25, MIN_LEFT_COLUMN_WIDTH),\n SIDE_COLUMN_MAX_WIDTH,\n );\n\n const rightColumnWidth = Math.min(\n windowWidth * 0.25,\n SIDE_COLUMN_MAX_WIDTH,\n );\n\n return Math.min(\n windowWidth - leftColumnWidth - rightColumnWidth,\n MAX_MESSAGES_LIST_WIDTH,\n );\n }\n\n if (windowWidth > MIN_SCREEN_WIDTH_FOR_STATIC_LEFT_COLUMN) {\n const leftColumnWidth = Math.min(\n Math.max(windowWidth * 0.4, MIN_LEFT_COLUMN_WIDTH),\n SIDE_COLUMN_MAX_WIDTH,\n );\n\n return Math.min(\n windowWidth - leftColumnWidth,\n MAX_MESSAGES_LIST_WIDTH,\n );\n }\n\n if (windowWidth > MAX_MESSAGES_LIST_WIDTH) {\n return MAX_MESSAGES_LIST_WIDTH;\n }\n\n return windowWidth;\n}\n","import React, { FC, memo } from '../../lib/teact/teact';\nimport { OwnProps } from './HeaderMenuContainer';\nimport { Bundles } from '../../util/moduleLoader';\n\nimport useModuleLoader from '../../hooks/useModuleLoader';\n\nconst HeaderMenuContainerAsync: FC<OwnProps> = (props) => {\n const { isOpen } = props;\n const HeaderMenuContainer = useModuleLoader(Bundles.Extra, 'HeaderMenuContainer', !isOpen);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return HeaderMenuContainer ? <HeaderMenuContainer {...props} /> : undefined;\n};\n\nexport default memo(HeaderMenuContainerAsync);\n","import React, {\n FC,\n memo,\n useRef,\n useCallback,\n useState,\n} from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { GlobalActions, MessageListType } from '../../global/types';\nimport { MAIN_THREAD_ID } from '../../api/types';\nimport { IAnchorPosition } from '../../types';\n\nimport { IS_SINGLE_COLUMN_LAYOUT } from '../../util/environment';\nimport { pick } from '../../util/iteratees';\nimport { isChatChannel, isChatSuperGroup } from '../../modules/helpers';\nimport {\n selectChat,\n selectChatBot,\n selectIsUserBlocked,\n selectIsChatBotNotStarted,\n selectIsChatWithSelf,\n selectIsInSelectMode,\n selectIsRightColumnShown,\n} from '../../modules/selectors';\nimport useLang from '../../hooks/useLang';\n\nimport Button from '../ui/Button';\nimport HeaderMenuContainer from './HeaderMenuContainer.async';\n\ninterface OwnProps {\n chatId: string;\n threadId: number;\n messageListType: MessageListType;\n canExpandActions: boolean;\n}\n\ninterface StateProps {\n noMenu?: boolean;\n isChannel?: boolean;\n isRightColumnShown?: boolean;\n canStartBot?: boolean;\n canRestartBot?: boolean;\n canSubscribe?: boolean;\n canSearch?: boolean;\n canMute?: boolean;\n canLeave?: boolean;\n}\n\ntype DispatchProps = Pick<GlobalActions, 'joinChannel' | 'sendBotCommand' | 'openLocalTextSearch' | 'restartBot'>;\n\n// Chrome breaks layout when focusing input during transition\nconst SEARCH_FOCUS_DELAY_MS = 400;\n\nconst HeaderActions: FC<OwnProps & StateProps & DispatchProps> = ({\n chatId,\n threadId,\n noMenu,\n isChannel,\n canStartBot,\n canRestartBot,\n canSubscribe,\n canSearch,\n canMute,\n canLeave,\n isRightColumnShown,\n canExpandActions,\n joinChannel,\n sendBotCommand,\n openLocalTextSearch,\n restartBot,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const menuButtonRef = useRef<HTMLButtonElement>(null);\n const [isMenuOpen, setIsMenuOpen] = useState(false);\n const [menuPosition, setMenuPosition] = useState<IAnchorPosition | undefined>(undefined);\n\n const handleHeaderMenuOpen = useCallback(() => {\n setIsMenuOpen(true);\n const rect = menuButtonRef.current!.getBoundingClientRect();\n setMenuPosition({ x: rect.right, y: rect.bottom });\n }, []);\n\n const handleHeaderMenuClose = useCallback(() => {\n setIsMenuOpen(false);\n }, []);\n\n const handleHeaderMenuHide = useCallback(() => {\n setMenuPosition(undefined);\n }, []);\n\n const handleSubscribeClick = useCallback(() => {\n joinChannel({ chatId });\n }, [joinChannel, chatId]);\n\n const handleStartBot = useCallback(() => {\n sendBotCommand({ command: '/start' });\n }, [sendBotCommand]);\n\n const handleRestartBot = useCallback(() => {\n restartBot({ chatId });\n }, [chatId, restartBot]);\n\n const handleSearchClick = useCallback(() => {\n openLocalTextSearch();\n\n if (IS_SINGLE_COLUMN_LAYOUT) {\n // iOS requires synchronous focus on user event.\n const searchInput = document.querySelector<HTMLInputElement>('#MobileSearch input')!;\n searchInput.focus();\n } else {\n setTimeout(() => {\n const searchInput = document.querySelector<HTMLInputElement>('.RightHeader .SearchInput input');\n if (searchInput) {\n searchInput.focus();\n }\n }, SEARCH_FOCUS_DELAY_MS);\n }\n }, [openLocalTextSearch]);\n\n const lang = useLang();\n\n return (\n <div className=\"HeaderActions\">\n {!IS_SINGLE_COLUMN_LAYOUT && canExpandActions && canSubscribe && (\n <Button\n size=\"tiny\"\n ripple\n fluid\n onClick={handleSubscribeClick}\n >\n {lang(isChannel ? 'ProfileJoinChannel' : 'ProfileJoinGroup')}\n </Button>\n )}\n {!IS_SINGLE_COLUMN_LAYOUT && canExpandActions && canStartBot && (\n <Button\n size=\"tiny\"\n ripple\n fluid\n onClick={handleStartBot}\n >\n {lang('BotStart')}\n </Button>\n )}\n {!IS_SINGLE_COLUMN_LAYOUT && canExpandActions && canRestartBot && (\n <Button\n size=\"tiny\"\n ripple\n fluid\n onClick={handleRestartBot}\n >\n {lang('BotRestart')}\n </Button>\n )}\n {!IS_SINGLE_COLUMN_LAYOUT && canSearch && (\n <Button\n round\n ripple={isRightColumnShown}\n color=\"translucent\"\n size=\"smaller\"\n onClick={handleSearchClick}\n ariaLabel=\"Search in this chat\"\n >\n <i className=\"icon-search\" />\n </Button>\n )}\n <Button\n ref={menuButtonRef}\n className={isMenuOpen ? 'active' : ''}\n round\n ripple={!IS_SINGLE_COLUMN_LAYOUT}\n size=\"smaller\"\n color=\"translucent\"\n disabled={noMenu}\n ariaLabel=\"More actions\"\n onClick={handleHeaderMenuOpen}\n >\n <i className=\"icon-more\" />\n </Button>\n {menuPosition && (\n <HeaderMenuContainer\n chatId={chatId}\n threadId={threadId}\n isOpen={isMenuOpen}\n anchor={menuPosition}\n withExtraActions={IS_SINGLE_COLUMN_LAYOUT || !canExpandActions}\n isChannel={isChannel}\n canStartBot={canStartBot}\n canRestartBot={canRestartBot}\n canSubscribe={canSubscribe}\n canSearch={canSearch}\n canMute={canMute}\n canLeave={canLeave}\n onSubscribeChannel={handleSubscribeClick}\n onSearchClick={handleSearchClick}\n onClose={handleHeaderMenuClose}\n onCloseAnimationEnd={handleHeaderMenuHide}\n />\n )}\n </div>\n );\n};\n\nexport default memo(withGlobal<OwnProps>(\n (global, { chatId, threadId, messageListType }): StateProps => {\n const chat = selectChat(global, chatId);\n const isChannel = Boolean(chat && isChatChannel(chat));\n\n if (chat?.isRestricted || selectIsInSelectMode(global)) {\n return {\n noMenu: true,\n };\n }\n\n const bot = selectChatBot(global, chatId);\n const isChatWithSelf = selectIsChatWithSelf(global, chatId);\n const isMainThread = messageListType === 'thread' && threadId === MAIN_THREAD_ID;\n const isDiscussionThread = messageListType === 'thread' && threadId !== MAIN_THREAD_ID;\n const isRightColumnShown = selectIsRightColumnShown(global);\n\n const canRestartBot = Boolean(bot && selectIsUserBlocked(global, bot.id));\n const canStartBot = !canRestartBot && Boolean(selectIsChatBotNotStarted(global, chatId));\n const canSubscribe = Boolean(\n isMainThread && chat && (isChannel || isChatSuperGroup(chat)) && chat.isNotJoined,\n );\n const canSearch = isMainThread || isDiscussionThread;\n const canMute = isMainThread && !isChatWithSelf && !canSubscribe;\n const canLeave = isMainThread && !canSubscribe;\n\n return {\n noMenu: false,\n isChannel,\n isRightColumnShown,\n canStartBot,\n canRestartBot,\n canSubscribe,\n canSearch,\n canMute,\n canLeave,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'joinChannel', 'sendBotCommand', 'openLocalTextSearch', 'restartBot',\n ]),\n)(HeaderActions));\n","import { useLayoutEffect, useState } from '../lib/teact/teact';\n\nimport { ApiMessage } 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 '../modules/helpers';\n\nexport default function useWebpThumbnail(message?: ApiMessage) {\n const thumbDataUri = message && getMessageMediaThumbDataUri(message);\n const sticker = message?.content?.sticker;\n const shouldDecodeThumbnail = thumbDataUri && sticker && !isWebpSupported() && thumbDataUri.includes('image/webp');\n const [thumbnailDecoded, setThumbnailDecoded] = useState(EMPTY_IMAGE_DATA_URI);\n const messageId = message?.id;\n\n useLayoutEffect(() => {\n if (!shouldDecodeThumbnail) {\n return;\n }\n\n webpToPngBase64(`b64-${messageId}`, thumbDataUri!)\n .then(setThumbnailDecoded)\n .catch((err) => {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error(err);\n }\n });\n }, [messageId, shouldDecodeThumbnail, thumbDataUri]);\n\n return shouldDecodeThumbnail ? thumbnailDecoded : thumbDataUri;\n}\n","import React, {\n FC,\n useRef,\n useEffect,\n useMemo,\n memo,\n} from '../../lib/teact/teact';\n\nimport buildClassName from '../../util/buildClassName';\n\ntype OwnProps = {\n count: number;\n index: number;\n};\n\nconst BORDER_MASK_LEVEL = 4;\n\nconst PinnedMessageNavigation: FC<OwnProps> = ({\n count, index,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const containerRef = useRef<HTMLDivElement>(null);\n\n const markupParams = useMemo(() => {\n return calculateMarkup(count, index);\n }, [count, index]);\n\n useEffect(() => {\n if (!containerRef.current) {\n return;\n }\n\n const {\n trackHeight,\n trackTranslateY,\n markHeight,\n markTranslateY,\n clipPathId,\n clipPath,\n } = markupParams;\n\n const firstChild = containerRef.current.firstElementChild;\n if (containerRef?.current) {\n const currentElement = containerRef.current;\n const { style } = currentElement;\n style.height = `${trackHeight}px`;\n style.transform = `translateY(-${trackTranslateY}px)`;\n style.clipPath = `url(\"#${clipPathId}\")`;\n const svg = currentElement.querySelector('svg');\n const div = currentElement.querySelector('div');\n const defs = currentElement.querySelector('defs');\n if (!svg) {\n if (firstChild) {\n firstChild.innerHTML = `<svg height=\"0\" width=\"0\"><defs> ${clipPath} </defs></svg>`;\n }\n }\n if (defs) {\n defs.innerHTML = clipPath;\n }\n if (div) {\n div.style.height = `${markHeight}px`;\n div.style.transform = `translateY(${markTranslateY}px)`;\n }\n }\n }, [markupParams]);\n\n if (count === 1) {\n return (\n <div className=\"pinned-message-border\">\n <div\n className=\"pinned-message-border-wrapper-1\"\n ref={containerRef}\n />\n </div>\n );\n }\n\n const {\n trackHeight, trackTranslateY, markHeight, markTranslateY, clipPathId,\n } = markupParams;\n\n return (\n <div className={buildClassName('pinned-message-border', count > BORDER_MASK_LEVEL && 'pinned-message-border-mask')}>\n <div\n className=\"pinned-message-border-wrapper\"\n ref={containerRef}\n // @ts-ignore\n style={\n `clip-path: url(\"#${clipPathId}\"); width: 2px;\n height: ${trackHeight}px; transform: translateY(-${trackTranslateY}px);`\n }\n >\n <span />\n <div\n className=\"pinned-message-border-mark\"\n // @ts-ignore\n style={`height: ${markHeight}px; transform: translateY(${markTranslateY}px);`}\n />\n </div>\n </div>\n );\n};\n\nfunction calculateMarkup(count: number, index: number) {\n const reverseIndex = count - index - 1;\n const barHeight = getBarHeight(count);\n const markHeight = getMarkHeight(count, reverseIndex);\n const trackHeight = getTrackHeight(count, barHeight);\n\n const clipPathId = `clipPath${count}`;\n const clipPath = getClipPath(clipPathId, barHeight, count);\n\n const markTranslateY = getMarkTranslateY(reverseIndex, barHeight, count);\n const trackTranslateY = getTrackTranslateY(reverseIndex, count, barHeight, trackHeight);\n return {\n markHeight,\n clipPath,\n markTranslateY,\n trackTranslateY,\n trackHeight,\n clipPathId,\n };\n}\n\nfunction getBarHeight(count: number): number {\n let barHeight = 8;\n if (count === 1) {\n barHeight = 36;\n } else if (count === 2) {\n barHeight = 17;\n } else if (count === 3) {\n barHeight = 11;\n } else if (count === 4) {\n barHeight = 7.5;\n } else if (count > 3) {\n barHeight = 7.5;\n }\n\n return barHeight;\n}\n\nfunction getMarkHeight(count: number, index: number) {\n let barHeight = 36;\n if (count === 1) {\n barHeight = 36;\n } else if (count === 2) {\n barHeight = 17;\n } else if (count === 3) {\n barHeight = index === 1 ? 12 : 11;\n } else if (count === 4) {\n barHeight = 7.5;\n } else if (count > 3) {\n barHeight = 7.5;\n }\n\n return barHeight;\n}\n\nfunction getTrackHeight(count: number, barHeight: number) {\n return count <= 3 ? 36 : barHeight * count + 2 * (count - 1);\n}\n\nfunction getClipPath(id: string, barHeight: number, count: number) {\n const radius = 1;\n\n let d = '';\n if (count === 3) {\n d = drawRect(0, 0, 2, barHeight, radius)\n + drawRect(0, 12, 2, barHeight + 1, radius)\n + drawRect(0, 25, 2, barHeight, radius);\n } else {\n for (let i = 0; i < count; i++) {\n d += drawRect(0, (barHeight + 2) * i, 2, barHeight, radius);\n }\n }\n\n return (\n `<clipPath id=\"${id}\">\n <path d=\"${d}\" />\n </clipPath>`\n );\n}\n\nfunction drawRect(x: number, y: number, width: number, height: number, radius: number) {\n return `M${x},${y + radius}a${radius},${radius},0,0,1,\n ${width},0v${height - 2 * radius}a${radius},${radius},0,0,1,${-width},0Z`;\n}\n\nfunction getMarkTranslateY(index: number, barHeight: number, count: number) {\n if (count === 1) {\n return 0;\n } else if (count === 2) {\n return index === 0 ? 0 : barHeight + 2;\n }\n\n if (count === 3) {\n if (index === 0) {\n return 0;\n } else if (index === 1) {\n return 12;\n }\n\n return 25;\n } else {\n return (barHeight + 2) * index;\n }\n}\n\nfunction getTrackTranslateY(index: number, count: number, barHeight: number, trackHeight: number) {\n if (count <= 4) {\n return 0;\n }\n\n if (index <= 1) {\n return 0;\n } else if (index >= count - 2) {\n return trackHeight - 36;\n }\n\n return (barHeight + 4) / 2 + (index - 2) * (barHeight + 2);\n}\n\nexport default memo(PinnedMessageNavigation);\n","import React, { FC, memo, useCallback } from '../../lib/teact/teact';\n\nimport { ApiMessage } from '../../api/types';\n\nimport { getPictogramDimensions } from '../common/helpers/mediaDimensions';\nimport { getMessageMediaHash, getMessageSummaryText } from '../../modules/helpers';\nimport renderText from '../common/helpers/renderText';\nimport useMedia from '../../hooks/useMedia';\nimport useWebpThumbnail from '../../hooks/useWebpThumbnail';\n\nimport ConfirmDialog from '../ui/ConfirmDialog';\nimport Button from '../ui/Button';\nimport RippleEffect from '../ui/RippleEffect';\nimport buildClassName from '../../util/buildClassName';\nimport useFlag from '../../hooks/useFlag';\nimport useLang from '../../hooks/useLang';\n\nimport PinnedMessageNavigation from './PinnedMessageNavigation';\n\ntype OwnProps = {\n message: ApiMessage;\n index: number;\n count: number;\n customTitle?: string;\n className?: string;\n onUnpinMessage?: (id: number) => void;\n onClick?: () => void;\n onAllPinnedClick?: () => void;\n};\n\nconst HeaderPinnedMessage: FC<OwnProps> = ({\n message, count, index, customTitle, className, onUnpinMessage, onClick, onAllPinnedClick,\n}) => {\n const lang = useLang();\n const mediaThumbnail = useWebpThumbnail(message);\n const mediaBlobUrl = useMedia(getMessageMediaHash(message, 'pictogram'));\n\n const text = getMessageSummaryText(lang, message, Boolean(mediaThumbnail));\n const [isUnpinDialogOpen, openUnpinDialog, closeUnpinDialog] = useFlag();\n\n const handleUnpinMessage = useCallback(() => {\n closeUnpinDialog();\n\n if (onUnpinMessage) {\n onUnpinMessage(message.id);\n }\n }, [closeUnpinDialog, onUnpinMessage, message.id]);\n\n return (\n <div className={buildClassName('HeaderPinnedMessage-wrapper', className)}>\n {count > 1 && (\n <Button\n round\n size=\"smaller\"\n color=\"translucent\"\n className=\"pin-list-button\"\n ariaLabel={lang('EventLogFilterPinnedMessages')}\n onClick={onAllPinnedClick}\n >\n <i className=\"icon-pin-list\" />\n </Button>\n )}\n {onUnpinMessage && (\n <Button\n round\n size=\"smaller\"\n color=\"translucent\"\n ariaLabel={lang('UnpinMessageAlertTitle')}\n className=\"unpin-button\"\n onClick={openUnpinDialog}\n >\n <i className=\"icon-close\" />\n </Button>\n )}\n <ConfirmDialog\n isOpen={isUnpinDialogOpen}\n onClose={closeUnpinDialog}\n text=\"Would you like to unpin this message?\"\n confirmLabel=\"Unpin\"\n confirmHandler={handleUnpinMessage}\n />\n <div className=\"HeaderPinnedMessage\" onClick={onClick} dir={lang.isRtl ? 'rtl' : undefined}>\n <PinnedMessageNavigation\n count={count}\n index={index}\n />\n {mediaThumbnail && renderPictogram(mediaThumbnail, mediaBlobUrl)}\n <div className=\"message-text\">\n <div className=\"title\" dir=\"auto\">\n {customTitle || `${lang('PinnedMessage')} ${index > 0 ? `#${count - index}` : ''}`}\n </div>\n <p dir=\"auto\">{renderText(text)}</p>\n </div>\n\n <RippleEffect />\n </div>\n </div>\n );\n};\n\nfunction renderPictogram(thumbDataUri: string, blobUrl?: string) {\n const { width, height } = getPictogramDimensions();\n\n return (\n <img src={blobUrl || thumbDataUri} width={width} height={height} alt=\"\" />\n );\n}\n\nexport default memo(HeaderPinnedMessage);\n","export function scaleImage(image: string | Blob, ratio: number, outputType: string = 'image/png'): Promise<string> {\n const url = image instanceof Blob ? URL.createObjectURL(image) : image;\n const img = new Image();\n return new Promise((resolve) => {\n img.onload = () => {\n scale(img, img.width * ratio, img.height * ratio, outputType)\n .then((blob) => URL.createObjectURL(blob))\n .then(resolve)\n .finally(() => {\n if (image instanceof Blob) {\n URL.revokeObjectURL(url); // Revoke blob url that we created\n }\n });\n };\n img.src = url;\n });\n}\n\nexport function resizeImage(\n image: string | Blob, width: number, height: number, outputType: string = 'image/png',\n): Promise<string> {\n const url = image instanceof Blob ? URL.createObjectURL(image) : image;\n const img = new Image();\n return new Promise((resolve) => {\n img.onload = () => {\n scale(img, width, height, outputType)\n .then((blob) => URL.createObjectURL(blob))\n .then(resolve)\n .finally(() => {\n if (image instanceof Blob) {\n URL.revokeObjectURL(url); // Revoke blob url that we created\n }\n });\n };\n img.src = url;\n });\n}\n\nasync function scale(\n img: HTMLImageElement, width: number, height: number, outputType: string = 'image/png',\n) {\n // Safari does not have built-in resize method with quality control\n if ('createImageBitmap' in window) {\n try {\n const bitmap = await window.createImageBitmap(img,\n { resizeWidth: width, resizeHeight: height, resizeQuality: 'high' });\n if (bitmap.height !== height || bitmap.width !== width) {\n throw new Error('Image bitmap resize not supported!'); // FF93 added support for options, but not resize\n }\n return await new Promise((res) => {\n const canvas = document.createElement('canvas');\n canvas.width = bitmap.width;\n canvas.height = bitmap.height;\n const ctx = canvas.getContext('bitmaprenderer');\n if (ctx) {\n ctx.transferFromImageBitmap(bitmap);\n } else {\n canvas.getContext('2d')!.drawImage(bitmap, 0, 0);\n }\n canvas.toBlob(res, outputType);\n });\n } catch (e) {\n // Fallback. Firefox below 93 does not recognize `createImageBitmap` with 2 parameters\n return steppedScale(img, width, height, undefined, outputType);\n }\n } else {\n return steppedScale(img, width, height, undefined, outputType);\n }\n}\n\nfunction steppedScale(\n img: HTMLImageElement, width: number, height: number, step: number = 0.5, outputType: string = 'image/png',\n): Promise<Blob | null> {\n const canvas = document.createElement('canvas');\n const ctx = canvas.getContext('2d')!;\n const oc = document.createElement('canvas');\n const octx = oc.getContext('2d')!;\n\n canvas.width = width;\n canvas.height = height;\n\n if (img.width * step > width) { // For performance avoid unnecessary drawing\n const mul = 1 / step;\n let cur = {\n width: Math.floor(img.width * step),\n height: Math.floor(img.height * step),\n };\n\n oc.width = cur.width;\n oc.height = cur.height;\n\n octx.drawImage(img, 0, 0, cur.width, cur.height);\n\n while (cur.width * step > width) {\n cur = {\n width: Math.floor(cur.width * step),\n height: Math.floor(cur.height * step),\n };\n octx.drawImage(oc, 0, 0, cur.width * mul, cur.height * mul, 0, 0, cur.width, cur.height);\n }\n\n ctx.drawImage(oc, 0, 0, cur.width, cur.height, 0, 0, canvas.width, canvas.height);\n } else {\n ctx.drawImage(img, 0, 0, canvas.width, canvas.height);\n }\n\n return new Promise((resolve) => {\n canvas.toBlob(resolve, outputType);\n });\n}\n","import { useMemo } from '../lib/teact/teact';\n\nimport {\n ApiAudio, ApiChat, ApiMessage, ApiUser, ApiVoice,\n} from '../api/types';\n\nimport useMedia from './useMedia';\nimport { useAsync } from './useAsync';\nimport {\n getAudioHasCover, getChatAvatarHash, getChatTitle, getMessageContent, getMessageMediaHash, getSenderTitle,\n} from '../modules/helpers';\nimport { getTranslation } from '../util/langProvider';\nimport { buildMediaMetadata } from '../util/mediaSession';\nimport { scaleImage, resizeImage } from '../util/imageResize';\nimport { AVATAR_FULL_DIMENSIONS } from '../components/common/helpers/mediaDimensions';\n\n// @ts-ignore\nimport telegramLogoPath from '../assets/telegram-logo-filled.svg';\n\nconst LOGO_DIMENSIONS = { width: 200, height: 200 };\nconst MINIMAL_SIZE = 115; // spec says 100, but on Chrome 93 it's not showing\n\n// TODO Add support for video in future\nexport default (message: ApiMessage, sender?: ApiUser | ApiChat, chat?: ApiChat): MediaMetadata | undefined => {\n const { audio, voice } = getMessageContent(message);\n const title = audio ? (audio.title || audio.fileName) : voice ? 'Voice message' : '';\n const artist = (audio && audio.performer) || (sender && getSenderTitle(getTranslation, sender));\n const album = (chat && getChatTitle(getTranslation, chat)) || 'Telegram';\n\n const audioCoverHash = (audio && getAudioHasCover(audio) && getMessageMediaHash(message, 'pictogram'));\n const avatarHash = sender && getChatAvatarHash(sender, 'big');\n const hash = (audio && audioCoverHash) || (voice && avatarHash);\n const media = useMedia(hash);\n\n const size = useMemo(() => {\n return getCoverSize(audio, voice, media);\n }, [audio, media, voice]);\n const { result: url } = useAsync(() => makeGoodArtwork(media, size), [media, size], telegramLogoPath);\n return useMemo(() => {\n return buildMediaMetadata({\n title,\n artist,\n album,\n artwork: [{ src: url }],\n });\n }, [album, artist, title, url]);\n};\n\nfunction makeGoodArtwork(url?: string, size?: { width: number; height: number }): Promise<string> {\n if (!url) return Promise.resolve(telegramLogoPath);\n if (!size) return resizeImage(url, MINIMAL_SIZE, MINIMAL_SIZE);\n const min = Math.min(size.width, size.height);\n if (min < MINIMAL_SIZE) {\n const ratio = MINIMAL_SIZE / min;\n return scaleImage(url, ratio);\n }\n return Promise.resolve(url);\n}\n\nfunction getCoverSize(audio?: ApiAudio, voice?: ApiVoice, url?: string) {\n if (!url) return LOGO_DIMENSIONS;\n if (audio) {\n if (!audio.thumbnailSizes || audio.thumbnailSizes.length === 0) return undefined;\n const preferred = audio.thumbnailSizes.find((size) => size.type === 'm');\n return preferred || audio.thumbnailSizes[0]; // Sometimes `m` is not present\n }\n\n if (voice) {\n return AVATAR_FULL_DIMENSIONS;\n }\n\n return undefined;\n}\n","import { useEffect, useState } from '../lib/teact/teact';\n\nexport const 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","import React, { FC, useCallback, useMemo } from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { AudioOrigin } from '../../types';\nimport { GlobalActions } from '../../global/types';\nimport {\n ApiAudio, ApiChat, ApiMessage, ApiUser,\n} from '../../api/types';\n\nimport { IS_IOS, IS_SINGLE_COLUMN_LAYOUT, IS_TOUCH_ENV } from '../../util/environment';\n\nimport * as mediaLoader from '../../util/mediaLoader';\nimport {\n getMediaDuration, getMessageContent, getMessageMediaHash, getSenderTitle,\n} from '../../modules/helpers';\nimport { selectChat, selectSender } from '../../modules/selectors';\nimport { pick } from '../../util/iteratees';\nimport renderText from '../common/helpers/renderText';\nimport useAudioPlayer from '../../hooks/useAudioPlayer';\nimport buildClassName from '../../util/buildClassName';\nimport useLang from '../../hooks/useLang';\nimport useMessageMediaMetadata from '../../hooks/useMessageMediaMetadata';\nimport { makeTrackId } from '../../util/audioPlayer';\nimport { clearMediaSession } from '../../util/mediaSession';\n\nimport RippleEffect from '../ui/RippleEffect';\nimport Button from '../ui/Button';\nimport RangeSlider from '../ui/RangeSlider';\n\nimport './AudioPlayer.scss';\n\ntype OwnProps = {\n message: ApiMessage;\n origin?: AudioOrigin;\n className?: string;\n noUi?: boolean;\n};\n\ntype StateProps = {\n sender?: ApiChat | ApiUser;\n chat?: ApiChat;\n volume: number;\n playbackRate: number;\n isMuted: boolean;\n};\n\ntype DispatchProps = Pick<GlobalActions, (\n 'focusMessage' |\n 'closeAudioPlayer' |\n 'setAudioPlayerVolume' |\n 'setAudioPlayerPlaybackRate' |\n 'setAudioPlayerMuted'\n)>;\n\nconst FAST_PLAYBACK_RATE = 1.8;\n\nconst AudioPlayer: FC<OwnProps & StateProps & DispatchProps> = ({\n message,\n origin = AudioOrigin.Inline,\n className,\n noUi,\n sender,\n chat,\n volume,\n playbackRate,\n isMuted,\n setAudioPlayerVolume,\n setAudioPlayerPlaybackRate,\n setAudioPlayerMuted,\n focusMessage,\n closeAudioPlayer,\n}) => {\n const lang = useLang();\n const { audio, voice, video } = getMessageContent(message);\n const isVoice = Boolean(voice || video);\n const senderName = sender ? getSenderTitle(lang, sender) : undefined;\n const mediaData = mediaLoader.getFromMemory(getMessageMediaHash(message, 'inline')!) as (string | undefined);\n const mediaMetadata = useMessageMediaMetadata(message, sender, chat);\n\n const {\n playPause,\n stop,\n isPlaying,\n requestNextTrack,\n requestPreviousTrack,\n isFirst,\n isLast,\n setVolume,\n toggleMuted,\n setPlaybackRate,\n } = useAudioPlayer(\n makeTrackId(message),\n getMediaDuration(message)!,\n isVoice ? 'voice' : 'audio',\n origin,\n mediaData,\n undefined,\n mediaMetadata,\n undefined,\n true,\n undefined,\n undefined,\n true,\n true,\n );\n\n const handleClick = useCallback(() => {\n focusMessage({ chatId: message.chatId, messageId: message.id });\n }, [focusMessage, message.chatId, message.id]);\n\n const handleClose = useCallback(() => {\n if (isPlaying) {\n playPause();\n }\n closeAudioPlayer();\n clearMediaSession();\n stop();\n }, [closeAudioPlayer, isPlaying, playPause, stop]);\n\n const handleVolumeChange = useCallback((value: number) => {\n setAudioPlayerVolume({ volume: value / 100 });\n setAudioPlayerMuted({ isMuted: false });\n\n setVolume(value / 100);\n }, [setAudioPlayerMuted, setAudioPlayerVolume, setVolume]);\n\n const handleVolumeClick = useCallback(() => {\n if (IS_TOUCH_ENV && !IS_IOS) return;\n toggleMuted();\n setAudioPlayerMuted({ isMuted: !isMuted });\n }, [isMuted, setAudioPlayerMuted, toggleMuted]);\n\n const handlePlaybackClick = useCallback(() => {\n if (playbackRate === 1) {\n setPlaybackRate(FAST_PLAYBACK_RATE);\n setAudioPlayerPlaybackRate({ playbackRate: FAST_PLAYBACK_RATE });\n } else {\n setPlaybackRate(1);\n setAudioPlayerPlaybackRate({ playbackRate: 1 });\n }\n }, [playbackRate, setAudioPlayerPlaybackRate, setPlaybackRate]);\n\n const volumeIcon = useMemo(() => {\n if (volume === 0 || isMuted) return 'icon-muted';\n if (volume < 0.3) return 'icon-volume-1';\n if (volume < 0.6) return 'icon-volume-2';\n return 'icon-volume-3';\n }, [volume, isMuted]);\n\n if (noUi) {\n return undefined;\n }\n\n return (\n <div className={buildClassName('AudioPlayer', className)} dir={lang.isRtl ? 'rtl' : undefined}>\n <Button\n round\n ripple={!IS_SINGLE_COLUMN_LAYOUT}\n color=\"translucent\"\n size=\"smaller\"\n className=\"player-button\"\n disabled={isFirst}\n onClick={requestPreviousTrack}\n ariaLabel=\"Previous track\"\n >\n <i className=\"icon-skip-previous\" />\n </Button>\n <Button\n round\n ripple={!IS_SINGLE_COLUMN_LAYOUT}\n color=\"translucent\"\n size=\"smaller\"\n className={buildClassName('toggle-play', 'player-button', isPlaying ? 'pause' : 'play')}\n onClick={playPause}\n ariaLabel={isPlaying ? 'Pause audio' : 'Play audio'}\n >\n <i className=\"icon-play\" />\n <i className=\"icon-pause\" />\n </Button>\n <Button\n round\n ripple={!IS_SINGLE_COLUMN_LAYOUT}\n color=\"translucent\"\n size=\"smaller\"\n className=\"player-button\"\n disabled={isLast}\n onClick={requestNextTrack}\n ariaLabel=\"Next track\"\n >\n <i className=\"icon-skip-next\" />\n </Button>\n\n <div className=\"AudioPlayer-content\" onClick={handleClick}>\n {audio ? renderAudio(audio) : renderVoice(lang('AttachAudio'), senderName)}\n <RippleEffect />\n </div>\n\n <Button\n round\n className=\"player-button volume-button\"\n color=\"translucent\"\n size=\"smaller\"\n ariaLabel=\"Volume\"\n withClickPropagation\n >\n <i className={volumeIcon} onClick={handleVolumeClick} />\n {!IS_IOS && (\n <>\n <div className=\"volume-slider-spacer\" />\n <div className=\"volume-slider\">\n <RangeSlider value={isMuted ? 0 : volume * 100} onChange={handleVolumeChange} />\n </div>\n </>\n )}\n </Button>\n\n {isVoice && (\n <Button\n round\n className={buildClassName('playback-button', playbackRate !== 1 && 'applied')}\n color=\"translucent\"\n size=\"smaller\"\n ariaLabel=\"Playback Rate\"\n ripple={!IS_SINGLE_COLUMN_LAYOUT}\n onClick={handlePlaybackClick}\n >\n <span className=\"playback-button-inner\">2Х</span>\n </Button>\n )}\n\n <Button\n round\n className=\"player-close\"\n color=\"translucent\"\n size=\"smaller\"\n onClick={handleClose}\n ariaLabel=\"Close player\"\n >\n <i className=\"icon-close\" />\n </Button>\n </div>\n );\n};\n\nfunction renderAudio(audio: ApiAudio) {\n const { title, performer, fileName } = audio;\n\n return (\n <>\n <div className=\"title\" dir=\"auto\">{renderText(title || fileName)}</div>\n {performer && (\n <div className=\"subtitle\" dir=\"auto\">{renderText(performer)}</div>\n )}\n </>\n );\n}\n\nfunction renderVoice(subtitle: string, senderName?: string) {\n return (\n <>\n <div className=\"title\" dir=\"auto\">{senderName && renderText(senderName)}</div>\n <div className=\"subtitle\" dir=\"auto\">{subtitle}</div>\n </>\n );\n}\n\nexport default withGlobal<OwnProps>(\n (global, { message }): StateProps => {\n const sender = selectSender(global, message);\n const chat = selectChat(global, message.chatId);\n const { volume, playbackRate, isMuted } = global.audioPlayer;\n\n return {\n sender,\n chat,\n volume,\n playbackRate,\n isMuted,\n };\n },\n (setGlobal, actions): DispatchProps => pick(\n actions,\n ['focusMessage', 'closeAudioPlayer', 'setAudioPlayerVolume', 'setAudioPlayerPlaybackRate', 'setAudioPlayerMuted'],\n ),\n)(AudioPlayer);\n","import React, {\n FC, useCallback, useMemo, memo, useEffect, useRef, useState,\n} from '../../lib/teact/teact';\nimport { getGlobal, withGlobal } from '../../lib/teact/teactn';\nimport cycleRestrict from '../../util/cycleRestrict';\n\nimport { GlobalActions, MessageListType } from '../../global/types';\nimport {\n ApiMessage,\n ApiChat,\n ApiUser,\n ApiTypingStatus,\n MAIN_THREAD_ID, ApiUpdateConnectionStateType,\n} from '../../api/types';\n\nimport {\n MIN_SCREEN_WIDTH_FOR_STATIC_LEFT_COLUMN,\n MOBILE_SCREEN_MAX_WIDTH,\n EDITABLE_INPUT_ID,\n MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN,\n SAFE_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN,\n SAFE_SCREEN_WIDTH_FOR_CHAT_INFO,\n} from '../../config';\nimport { IS_SINGLE_COLUMN_LAYOUT, IS_TABLET_COLUMN_LAYOUT } from '../../util/environment';\nimport {\n isUserId,\n getMessageKey,\n getChatTitle,\n getSenderTitle,\n} from '../../modules/helpers';\nimport {\n selectChat,\n selectChatMessage,\n selectAllowedMessageActions,\n selectIsRightColumnShown,\n selectThreadTopMessageId,\n selectThreadInfo,\n selectChatMessages,\n selectPinnedIds,\n selectIsChatWithSelf,\n selectForwardedSender,\n selectScheduledIds,\n selectIsInSelectMode,\n selectIsChatWithBot,\n selectCountNotMutedUnread,\n} from '../../modules/selectors';\nimport useEnsureMessage from '../../hooks/useEnsureMessage';\nimport useWindowSize from '../../hooks/useWindowSize';\nimport useShowTransition from '../../hooks/useShowTransition';\nimport useCurrentOrPrev from '../../hooks/useCurrentOrPrev';\nimport { pick } from '../../util/iteratees';\nimport { formatIntegerCompact } from '../../util/textFormat';\nimport buildClassName from '../../util/buildClassName';\nimport useLang from '../../hooks/useLang';\nimport useBrowserOnline from '../../hooks/useBrowserOnline';\n\nimport PrivateChatInfo from '../common/PrivateChatInfo';\nimport GroupChatInfo from '../common/GroupChatInfo';\nimport Transition from '../ui/Transition';\nimport Button from '../ui/Button';\nimport HeaderActions from './HeaderActions';\nimport HeaderPinnedMessage from './HeaderPinnedMessage';\nimport AudioPlayer from './AudioPlayer';\n\nimport './MiddleHeader.scss';\n\nconst ANIMATION_DURATION = 350;\nconst BACK_BUTTON_INACTIVE_TIME = 450;\n\ntype OwnProps = {\n chatId: string;\n threadId: number;\n messageListType: MessageListType;\n isReady?: boolean;\n};\n\ntype StateProps = {\n chat?: ApiChat;\n pinnedMessageIds?: number[] | number;\n messagesById?: Record<number, ApiMessage>;\n canUnpin?: boolean;\n topMessageSender?: ApiChat | ApiUser;\n typingStatus?: ApiTypingStatus;\n isSelectModeActive?: boolean;\n isLeftColumnShown?: boolean;\n isRightColumnShown?: boolean;\n audioMessage?: ApiMessage;\n chatsById?: Record<string, ApiChat>;\n messagesCount?: number;\n isChatWithSelf?: boolean;\n isChatWithBot?: boolean;\n lastSyncTime?: number;\n shouldSkipHistoryAnimations?: boolean;\n currentTransitionKey: number;\n connectionState?: ApiUpdateConnectionStateType;\n};\n\ntype DispatchProps = Pick<GlobalActions, (\n 'openChatWithInfo' | 'pinMessage' | 'focusMessage' | 'openChat' | 'openPreviousChat' | 'loadPinnedMessages' |\n 'toggleLeftColumn' | 'exitMessageSelectMode'\n)>;\n\nconst MiddleHeader: FC<OwnProps & StateProps & DispatchProps> = ({\n chatId,\n threadId,\n messageListType,\n isReady,\n pinnedMessageIds,\n messagesById,\n canUnpin,\n topMessageSender,\n typingStatus,\n isSelectModeActive,\n isLeftColumnShown,\n isRightColumnShown,\n audioMessage,\n chat,\n chatsById,\n messagesCount,\n isChatWithSelf,\n isChatWithBot,\n lastSyncTime,\n shouldSkipHistoryAnimations,\n currentTransitionKey,\n connectionState,\n openChatWithInfo,\n pinMessage,\n focusMessage,\n openChat,\n openPreviousChat,\n loadPinnedMessages,\n toggleLeftColumn,\n exitMessageSelectMode,\n}) => {\n const lang = useLang();\n const isBackButtonActive = useRef(true);\n\n const [pinnedMessageIndex, setPinnedMessageIndex] = useState(0);\n const pinnedMessageId = Array.isArray(pinnedMessageIds) ? pinnedMessageIds[pinnedMessageIndex] : pinnedMessageIds;\n const pinnedMessage = messagesById && pinnedMessageId ? messagesById[pinnedMessageId] : undefined;\n const pinnedMessagesCount = Array.isArray(pinnedMessageIds)\n ? pinnedMessageIds.length : (pinnedMessageIds ? 1 : undefined);\n const chatTitleLength = chat && getChatTitle(lang, chat).length;\n const topMessageTitle = topMessageSender ? getSenderTitle(lang, topMessageSender) : undefined;\n\n useEffect(() => {\n if (threadId === MAIN_THREAD_ID && lastSyncTime && isReady) {\n loadPinnedMessages({ chatId });\n }\n }, [chatId, loadPinnedMessages, lastSyncTime, threadId, isReady]);\n\n // Reset pinned index when switching chats and pinning/unpinning\n useEffect(() => {\n setPinnedMessageIndex(0);\n }, [pinnedMessageIds]);\n\n useEnsureMessage(chatId, pinnedMessageId, pinnedMessage);\n\n const { width: windowWidth } = useWindowSize();\n\n const isLeftColumnHideable = windowWidth <= MIN_SCREEN_WIDTH_FOR_STATIC_LEFT_COLUMN;\n const shouldShowCloseButton = IS_TABLET_COLUMN_LAYOUT && isLeftColumnShown;\n\n // eslint-disable-next-line no-null/no-null\n const componentRef = useRef<HTMLDivElement>(null);\n const shouldAnimateTools = useRef<boolean>(true);\n\n const handleHeaderClick = useCallback(() => {\n openChatWithInfo({ id: chatId });\n }, [openChatWithInfo, chatId]);\n\n const handleUnpinMessage = useCallback((messageId: number) => {\n pinMessage({ chatId, messageId, isUnpin: true });\n }, [pinMessage, chatId]);\n\n const handlePinnedMessageClick = useCallback((): void => {\n if (pinnedMessage) {\n focusMessage({ chatId: pinnedMessage.chatId, threadId, messageId: pinnedMessage.id });\n\n const newIndex = cycleRestrict(pinnedMessagesCount || 1, pinnedMessageIndex + 1);\n setPinnedMessageIndex(newIndex);\n }\n }, [pinnedMessage, focusMessage, threadId, pinnedMessagesCount, pinnedMessageIndex]);\n\n const handleAllPinnedClick = useCallback(() => {\n openChat({ id: chatId, threadId: MAIN_THREAD_ID, type: 'pinned' });\n }, [openChat, chatId]);\n\n const setBackButtonActive = useCallback(() => {\n setTimeout(() => {\n isBackButtonActive.current = true;\n }, BACK_BUTTON_INACTIVE_TIME);\n }, []);\n\n const handleBackClick = useCallback((e: React.MouseEvent<HTMLElement, MouseEvent>) => {\n if (!isBackButtonActive.current) return;\n\n // Workaround for missing UI when quickly clicking the Back button\n isBackButtonActive.current = false;\n if (IS_SINGLE_COLUMN_LAYOUT) {\n const messageInput = document.getElementById(EDITABLE_INPUT_ID);\n if (messageInput) {\n messageInput.blur();\n }\n }\n\n if (isSelectModeActive) {\n exitMessageSelectMode();\n setBackButtonActive();\n return;\n }\n\n if (threadId === MAIN_THREAD_ID && messageListType === 'thread' && currentTransitionKey === 0) {\n if (IS_SINGLE_COLUMN_LAYOUT || shouldShowCloseButton) {\n e.stopPropagation(); // Stop propagation to prevent chat re-opening on tablets\n openChat({ id: undefined });\n } else {\n toggleLeftColumn();\n }\n\n setBackButtonActive();\n\n return;\n }\n\n openPreviousChat();\n setBackButtonActive();\n }, [\n threadId, messageListType, currentTransitionKey, isSelectModeActive, openPreviousChat, shouldShowCloseButton,\n openChat, toggleLeftColumn, exitMessageSelectMode, setBackButtonActive,\n ]);\n\n const unreadCount = useMemo(() => {\n if (!isLeftColumnHideable || !chatsById) {\n return undefined;\n }\n\n return selectCountNotMutedUnread(getGlobal()) || undefined;\n }, [isLeftColumnHideable, chatsById]);\n\n const canToolsCollideWithChatInfo = (\n windowWidth >= MIN_SCREEN_WIDTH_FOR_STATIC_LEFT_COLUMN\n && windowWidth < SAFE_SCREEN_WIDTH_FOR_CHAT_INFO\n ) || (\n windowWidth > MOBILE_SCREEN_MAX_WIDTH\n && windowWidth < MIN_SCREEN_WIDTH_FOR_STATIC_LEFT_COLUMN\n && (!chatTitleLength || chatTitleLength > 30)\n );\n const shouldUseStackedToolsClass = canToolsCollideWithChatInfo || (\n windowWidth > MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN\n && windowWidth < SAFE_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN\n );\n\n const {\n shouldRender: shouldRenderAudioPlayer,\n transitionClassNames: audioPlayerClassNames,\n } = useShowTransition(Boolean(audioMessage));\n\n const renderingAudioMessage = useCurrentOrPrev(audioMessage);\n\n const {\n shouldRender: shouldRenderPinnedMessage,\n transitionClassNames: pinnedMessageClassNames,\n } = useShowTransition(Boolean(pinnedMessage));\n\n const renderingPinnedMessage = useCurrentOrPrev(pinnedMessage, true);\n const renderingPinnedMessagesCount = useCurrentOrPrev(pinnedMessagesCount, true);\n const renderingCanUnpin = useCurrentOrPrev(canUnpin, true);\n const renderingPinnedMessageTitle = useCurrentOrPrev(topMessageTitle);\n\n const canRevealTools = (shouldRenderPinnedMessage && renderingPinnedMessage)\n || (shouldRenderAudioPlayer && renderingAudioMessage);\n\n // Logic for transition to and from custom display of AudioPlayer/PinnedMessage on smaller screens\n useEffect(() => {\n const componentEl = componentRef.current;\n if (!componentEl) {\n return;\n }\n\n if (!shouldUseStackedToolsClass || !canRevealTools) {\n componentEl.classList.remove('tools-stacked', 'animated');\n shouldAnimateTools.current = true;\n return;\n }\n\n if (isRightColumnShown || canToolsCollideWithChatInfo) {\n if (shouldAnimateTools.current) {\n componentEl.classList.add('tools-stacked', 'animated');\n shouldAnimateTools.current = false;\n }\n\n // Remove animation class to prevent it messing up the show transitions\n setTimeout(() => {\n componentEl.classList.remove('animated');\n }, ANIMATION_DURATION);\n } else {\n componentEl.classList.remove('tools-stacked');\n shouldAnimateTools.current = true;\n }\n }, [shouldUseStackedToolsClass, canRevealTools, canToolsCollideWithChatInfo, isRightColumnShown]);\n\n const isBrowserOnline = useBrowserOnline();\n const isConnecting = (!isBrowserOnline || connectionState === 'connectionStateConnecting')\n && (IS_SINGLE_COLUMN_LAYOUT || (IS_TABLET_COLUMN_LAYOUT && !shouldShowCloseButton));\n\n function renderInfo() {\n if (isConnecting) {\n return (\n <>\n {renderBackButton()}\n <h3>\n {lang('WaitingForNetwork')}\n </h3>\n </>\n );\n }\n return (\n messageListType === 'thread' && threadId === MAIN_THREAD_ID ? (\n renderMainThreadInfo()\n ) : messageListType === 'thread' ? (\n <>\n {renderBackButton()}\n <h3>\n {lang('CommentsCount', messagesCount, 'i')}\n </h3>\n </>\n ) : messageListType === 'pinned' ? (\n <>\n {renderBackButton()}\n <h3>\n {lang('PinnedMessagesCount', messagesCount, 'i')}\n </h3>\n </>\n ) : messageListType === 'scheduled' ? (\n <>\n {renderBackButton()}\n <h3>\n {isChatWithSelf ? lang('Reminders') : lang('messages', messagesCount, 'i')}\n </h3>\n </>\n ) : undefined\n );\n }\n\n function renderMainThreadInfo() {\n return (\n <>\n {(isLeftColumnHideable || currentTransitionKey > 0) && renderBackButton(shouldShowCloseButton, true)}\n <div className=\"chat-info-wrapper\" onClick={handleHeaderClick}>\n {isUserId(chatId) ? (\n <PrivateChatInfo\n userId={chatId}\n typingStatus={typingStatus}\n withFullInfo={isChatWithBot}\n withMediaViewer\n withUpdatingStatus\n noRtl\n />\n ) : (\n <GroupChatInfo\n chatId={chatId}\n typingStatus={typingStatus}\n noRtl\n withMediaViewer\n withFullInfo\n withUpdatingStatus\n />\n )}\n </div>\n </>\n );\n }\n\n function renderBackButton(asClose = false, withUnreadCount = false) {\n return (\n <div className=\"back-button\">\n <Button\n round\n size=\"smaller\"\n color=\"translucent\"\n onClick={handleBackClick}\n ariaLabel={lang(asClose ? 'Close' : 'Back')}\n >\n <div className={buildClassName('animated-close-icon', !asClose && 'state-back')} />\n </Button>\n {withUnreadCount && unreadCount && (\n <div className=\"unread-count active\">\n {formatIntegerCompact(unreadCount)}\n </div>\n )}\n </div>\n );\n }\n\n const isAudioPlayerRendered = Boolean(shouldRenderAudioPlayer && renderingAudioMessage);\n\n return (\n <div className=\"MiddleHeader\" ref={componentRef}>\n <Transition\n name={shouldSkipHistoryAnimations ? 'none' : 'slide-fade'}\n activeKey={isConnecting ? Infinity : currentTransitionKey}\n >\n {renderInfo}\n </Transition>\n\n {shouldRenderPinnedMessage && renderingPinnedMessage && (\n <HeaderPinnedMessage\n key={chatId}\n message={renderingPinnedMessage}\n count={renderingPinnedMessagesCount || 0}\n index={pinnedMessageIndex}\n customTitle={renderingPinnedMessageTitle}\n className={buildClassName(pinnedMessageClassNames, isAudioPlayerRendered && 'full-width')}\n onUnpinMessage={renderingCanUnpin ? handleUnpinMessage : undefined}\n onClick={handlePinnedMessageClick}\n onAllPinnedClick={handleAllPinnedClick}\n />\n )}\n <div className=\"header-tools\">\n {isAudioPlayerRendered && (\n <AudioPlayer\n key={getMessageKey(renderingAudioMessage!)}\n message={renderingAudioMessage!}\n className={audioPlayerClassNames}\n />\n )}\n <HeaderActions\n chatId={chatId}\n threadId={threadId}\n messageListType={messageListType}\n canExpandActions={!isAudioPlayerRendered}\n />\n </div>\n </div>\n );\n};\n\nexport default memo(withGlobal<OwnProps>(\n (global, { chatId, threadId, messageListType }): StateProps => {\n const { isLeftColumnShown, lastSyncTime, shouldSkipHistoryAnimations } = global;\n const { byId: chatsById } = global.chats;\n const chat = selectChat(global, chatId);\n\n const { typingStatus } = chat || {};\n\n const { chatId: audioChatId, messageId: audioMessageId } = global.audioPlayer;\n const audioMessage = audioChatId && audioMessageId\n ? selectChatMessage(global, audioChatId, audioMessageId)\n : undefined;\n\n let messagesCount: number | undefined;\n if (messageListType === 'pinned') {\n const pinnedIds = selectPinnedIds(global, chatId);\n messagesCount = pinnedIds?.length;\n } else if (messageListType === 'scheduled') {\n const scheduledIds = selectScheduledIds(global, chatId);\n messagesCount = scheduledIds?.length;\n } else if (messageListType === 'thread' && threadId !== MAIN_THREAD_ID) {\n const threadInfo = selectThreadInfo(global, chatId, threadId);\n messagesCount = threadInfo?.messagesCount || 0;\n }\n\n const state: StateProps = {\n typingStatus,\n isLeftColumnShown,\n isRightColumnShown: selectIsRightColumnShown(global),\n isSelectModeActive: selectIsInSelectMode(global),\n audioMessage,\n chat,\n chatsById,\n messagesCount,\n isChatWithSelf: selectIsChatWithSelf(global, chatId),\n isChatWithBot: chat && selectIsChatWithBot(global, chat),\n lastSyncTime,\n shouldSkipHistoryAnimations,\n currentTransitionKey: Math.max(0, global.messages.messageLists.length - 1),\n connectionState: global.connectionState,\n };\n\n const messagesById = selectChatMessages(global, chatId);\n if (messageListType !== 'thread' || !messagesById) {\n return state;\n }\n\n Object.assign(state, { messagesById });\n\n if (threadId !== MAIN_THREAD_ID) {\n const pinnedMessageId = selectThreadTopMessageId(global, chatId, threadId);\n const message = pinnedMessageId ? selectChatMessage(global, chatId, pinnedMessageId) : undefined;\n const topMessageSender = message ? selectForwardedSender(global, message) : undefined;\n\n return {\n ...state,\n pinnedMessageIds: pinnedMessageId,\n canUnpin: false,\n topMessageSender,\n };\n }\n\n const pinnedMessageIds = selectPinnedIds(global, chatId);\n if (pinnedMessageIds?.length) {\n const firstPinnedMessage = messagesById[pinnedMessageIds[0]];\n const {\n canUnpin,\n } = (firstPinnedMessage && selectAllowedMessageActions(global, firstPinnedMessage, threadId)) || {};\n\n return {\n ...state,\n pinnedMessageIds,\n canUnpin,\n };\n }\n\n return state;\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'openChatWithInfo',\n 'pinMessage',\n 'focusMessage',\n 'openChat',\n 'openPreviousChat',\n 'loadPinnedMessages',\n 'toggleLeftColumn',\n 'exitMessageSelectMode',\n ]),\n)(MiddleHeader));\n","import { ApiMessage } from '../../../api/types';\nimport { IAlbum } from '../../../types';\n\nimport { getDayStart } from '../../../util/dateFormat';\nimport { isActionMessage } from '../../../modules/helpers';\n\ntype SenderGroup = (ApiMessage | IAlbum)[];\n\nconst GROUP_INTERVAL_SECONDS = 600; // 10 minutes\n\nexport type MessageDateGroup = {\n originalDate: number;\n datetime: number;\n senderGroups: SenderGroup[];\n};\n\nexport function isAlbum(messageOrAlbum: ApiMessage | IAlbum): messageOrAlbum is IAlbum {\n return 'albumId' in messageOrAlbum;\n}\n\nexport function groupMessages(messages: ApiMessage[], firstUnreadId?: number) {\n let currentSenderGroup: SenderGroup = [];\n let currentDateGroup = {\n originalDate: messages[0].date,\n datetime: Number(getDayStart(messages[0].date * 1000)),\n senderGroups: [currentSenderGroup],\n };\n let currentAlbum: IAlbum | undefined;\n\n const dateGroups: MessageDateGroup[] = [currentDateGroup];\n\n messages.forEach((message, index) => {\n if (message.isInAlbum) {\n if (!currentAlbum) {\n currentAlbum = {\n albumId: message.groupedId!,\n messages: [message],\n mainMessage: message,\n };\n } else {\n currentAlbum.messages.push(message);\n if (message.content.text) {\n currentAlbum.mainMessage = message;\n }\n }\n } else {\n currentSenderGroup.push(message);\n }\n\n const nextMessage = messages[index + 1];\n\n if (\n currentAlbum\n && (!nextMessage || !nextMessage.groupedId || nextMessage.groupedId !== currentAlbum.albumId)\n ) {\n currentSenderGroup.push(currentAlbum);\n currentAlbum = undefined;\n }\n if (nextMessage) {\n const nextMessageDayStartsAt = Number(getDayStart(nextMessage.date * 1000));\n if (currentDateGroup.datetime !== nextMessageDayStartsAt) {\n currentDateGroup = {\n originalDate: nextMessage.date,\n datetime: nextMessageDayStartsAt,\n senderGroups: [],\n };\n dateGroups.push(currentDateGroup);\n\n currentSenderGroup = [];\n currentDateGroup.senderGroups.push(currentSenderGroup);\n } else if (\n nextMessage.id === firstUnreadId\n || message.senderId !== nextMessage.senderId\n || message.isOutgoing !== nextMessage.isOutgoing\n || isActionMessage(message)\n || isActionMessage(nextMessage)\n || (\n message.forwardInfo && nextMessage.forwardInfo\n && (\n message.forwardInfo.senderUserId !== nextMessage.forwardInfo.senderUserId\n || message.forwardInfo.fromChatId !== nextMessage.forwardInfo.fromChatId\n || message.forwardInfo.hiddenUserName !== nextMessage.forwardInfo.hiddenUserName\n )\n )\n || message.inlineButtons\n || nextMessage.inlineButtons\n || (nextMessage.date - message.date) > GROUP_INTERVAL_SECONDS\n ) {\n currentSenderGroup = [];\n currentDateGroup.senderGroups.push(currentSenderGroup);\n }\n }\n });\n\n return dateGroups;\n}\n","import { RefObject } from 'react';\nimport { getDispatch } from '../../../lib/teact/teactn';\n\nimport { MessageListType } from '../../../global/types';\n\nimport { IS_ANDROID, IS_SINGLE_COLUMN_LAYOUT } from '../../../util/environment';\nimport { useIntersectionObserver } from '../../../hooks/useIntersectionObserver';\nimport useBackgroundMode from '../../../hooks/useBackgroundMode';\n\nconst INTERSECTION_THROTTLE_FOR_MEDIA = IS_ANDROID ? 1000 : 350;\nconst INTERSECTION_MARGIN_FOR_MEDIA = IS_SINGLE_COLUMN_LAYOUT ? 300 : 500;\nconst INTERSECTION_THROTTLE_FOR_READING = 150;\n\nexport default function useMessageObservers(\n type: MessageListType,\n containerRef: RefObject<HTMLDivElement>,\n memoFirstUnreadIdRef: { current: number | undefined },\n) {\n const { markMessageListRead, markMessagesRead } = getDispatch();\n\n const {\n observe: observeIntersectionForMedia,\n } = useIntersectionObserver({\n rootRef: containerRef,\n throttleMs: INTERSECTION_THROTTLE_FOR_MEDIA,\n margin: INTERSECTION_MARGIN_FOR_MEDIA,\n });\n\n const {\n observe: observeIntersectionForReading, freeze: freezeForReading, unfreeze: unfreezeForReading,\n } = useIntersectionObserver({\n rootRef: containerRef,\n throttleMs: INTERSECTION_THROTTLE_FOR_READING,\n noAutoFreeze: true,\n }, (entries) => {\n if (type !== 'thread') {\n return;\n }\n\n let maxId = 0;\n const mentionIds: number[] = [];\n\n entries.forEach((entry) => {\n const { isIntersecting, target } = entry;\n\n if (!isIntersecting) {\n return;\n }\n\n const { dataset } = target as HTMLDivElement;\n\n const messageId = Number(dataset.lastMessageId || dataset.messageId);\n if (messageId > maxId) {\n maxId = messageId;\n }\n\n if (dataset.hasUnreadMention) {\n mentionIds.push(messageId);\n }\n });\n\n if (memoFirstUnreadIdRef.current && maxId >= memoFirstUnreadIdRef.current) {\n markMessageListRead({ maxId });\n }\n\n if (mentionIds.length) {\n markMessagesRead({ messageIds: mentionIds });\n }\n });\n\n useBackgroundMode(freezeForReading, unfreezeForReading);\n\n const { observe: observeIntersectionForAnimatedStickers } = useIntersectionObserver({\n rootRef: containerRef,\n throttleMs: INTERSECTION_THROTTLE_FOR_MEDIA,\n });\n\n return {\n observeIntersectionForMedia,\n observeIntersectionForReading,\n observeIntersectionForAnimatedStickers,\n };\n}\n","import { ApiMessage } from '../../../../api/types';\n\nimport { getMessageContent } from '../../../../modules/helpers';\n\nexport function isEmojiOnlyMessage(customShape?: boolean | number) {\n return typeof customShape === 'number';\n}\n\nexport function buildContentClassName(\n message: ApiMessage,\n {\n hasReply,\n customShape,\n isLastInGroup,\n asForwarded,\n hasThread,\n forceSenderName,\n hasComments,\n hasActionButton,\n }: {\n hasReply?: boolean;\n customShape?: boolean | number;\n isLastInGroup?: boolean;\n asForwarded?: boolean;\n hasThread?: boolean;\n forceSenderName?: boolean;\n hasComments?: boolean;\n hasActionButton?: boolean;\n } = {},\n) {\n const {\n text, photo, video, audio, voice, document, poll, webPage, contact,\n } = getMessageContent(message);\n\n const classNames = ['message-content'];\n const isMedia = photo || video;\n const isMediaWithNoText = isMedia && !text;\n const isViaBot = Boolean(message.viaBotId);\n\n if (isEmojiOnlyMessage(customShape)) {\n classNames.push(`emoji-only emoji-only-${customShape}`);\n } else if (text) {\n classNames.push('text');\n }\n\n if (hasActionButton) {\n classNames.push('has-action-button');\n }\n\n if (customShape) {\n classNames.push('custom-shape');\n if (video?.isRound) {\n classNames.push('round');\n }\n\n if (hasComments) {\n classNames.push('has-comments');\n }\n }\n if (photo || video) {\n classNames.push('media');\n } else if (audio) {\n classNames.push('audio');\n } else if (voice) {\n classNames.push('voice');\n } else if (document) {\n classNames.push('document');\n } else if (contact) {\n classNames.push('contact');\n } else if (poll) {\n classNames.push('poll');\n } else if (webPage) {\n classNames.push('web-page');\n\n if (webPage.photo || webPage.video) {\n classNames.push('media');\n }\n }\n\n if (asForwarded && !customShape) {\n classNames.push('is-forwarded');\n }\n\n if (hasReply) {\n classNames.push('is-reply');\n }\n\n if (hasThread) {\n classNames.push('has-replies');\n }\n\n if (isViaBot) {\n classNames.push('is-via-bot');\n }\n\n if (forceSenderName) {\n classNames.push('force-sender-name');\n }\n\n if (!customShape) {\n classNames.push('has-shadow');\n\n if (isMedia && hasComments) {\n classNames.push('has-background');\n }\n\n if (hasReply || asForwarded || !isMediaWithNoText || isViaBot || forceSenderName) {\n classNames.push('has-solid-background');\n }\n\n if (isLastInGroup && (photo || !isMediaWithNoText)) {\n classNames.push('has-appendix');\n }\n }\n\n return classNames.join(' ');\n}\n","import { ApiMessage } from '../../../../api/types';\nimport { calculateInlineImageDimensions, calculateVideoDimensions } from '../../../common/helpers/mediaDimensions';\nimport {\n getMessageText,\n getMessagePhoto,\n getMessageWebPagePhoto,\n isForwardedMessage,\n isOwnMessage,\n getMessageVideo,\n} from '../../../../modules/helpers';\n\nconst MIN_MEDIA_WIDTH = 100;\nconst MIN_MEDIA_WIDTH_WITH_COMMENTS = 238;\nconst MIN_MEDIA_WIDTH_WITH_TEXT = 175;\nconst MIN_MEDIA_WIDTH_WITH_TEXT_AND_COMMENTS = 238;\nconst MIN_MEDIA_HEIGHT = 90;\nconst SMALL_IMAGE_THRESHOLD = 12;\n\nexport function getMinMediaWidth(hasText?: boolean, hasCommentButton?: boolean) {\n return hasText\n ? (hasCommentButton ? MIN_MEDIA_WIDTH_WITH_TEXT_AND_COMMENTS : MIN_MEDIA_WIDTH_WITH_TEXT)\n : (hasCommentButton ? MIN_MEDIA_WIDTH_WITH_COMMENTS : MIN_MEDIA_WIDTH);\n}\n\nexport function calculateMediaDimensions(message: ApiMessage, noAvatars?: boolean) {\n const isOwn = isOwnMessage(message);\n const isForwarded = isForwardedMessage(message);\n const photo = getMessagePhoto(message) || getMessageWebPagePhoto(message);\n const video = getMessageVideo(message);\n\n const isWebPagePhoto = Boolean(getMessageWebPagePhoto(message));\n const { width, height } = photo\n ? calculateInlineImageDimensions(photo, isOwn, isForwarded, isWebPagePhoto, noAvatars)\n : calculateVideoDimensions(video!, isOwn, isForwarded, noAvatars);\n\n const hasText = Boolean(getMessageText(message));\n const minMediaWidth = getMinMediaWidth(hasText);\n\n let stretchFactor = 1;\n if (width < minMediaWidth && minMediaWidth - width < SMALL_IMAGE_THRESHOLD) {\n stretchFactor = minMediaWidth / width;\n }\n if (height * stretchFactor < MIN_MEDIA_HEIGHT && MIN_MEDIA_HEIGHT - height * stretchFactor < SMALL_IMAGE_THRESHOLD) {\n stretchFactor = MIN_MEDIA_HEIGHT / height;\n }\n\n const finalWidth = Math.round(width * stretchFactor);\n const finalHeight = Math.round(height * stretchFactor);\n\n return {\n width: finalWidth,\n height: finalHeight,\n isSmall: finalWidth < minMediaWidth || finalHeight < MIN_MEDIA_HEIGHT,\n };\n}\n","/* eslint-disable no-bitwise */\n// Based on\n// https://github.com/telegramdesktop/tdesktop/blob/dev/Telegram/SourceFiles/ui/grouped_layout.cpp\n// https://github.com/overtake/TelegramSwift/blob/master/Telegram-Mac/GroupedLayout.swift#L83\n\nimport { IAlbum } from '../../../../types';\nimport { ApiMessage, ApiDimensions } from '../../../../api/types';\n\nimport { getAvailableWidth, REM } from '../../../common/helpers/mediaDimensions';\nimport { calculateMediaDimensions } from './mediaDimensions';\n\nexport const AlbumRectPart = {\n None: 0,\n Top: 1,\n Right: 2,\n Bottom: 4,\n Left: 8,\n};\n\ntype IAttempt = {\n lineCounts: number[];\n heights: number[];\n};\nexport type IMediaDimensions = {\n width: number;\n height: number;\n x: number;\n y: number;\n};\ntype IMediaLayout = {\n dimensions: IMediaDimensions;\n sides: number;\n};\ntype ILayoutParams = {\n ratios: number[];\n proportions: string;\n averageRatio: number;\n maxWidth: number;\n minWidth: number;\n maxHeight: number;\n spacing: number;\n};\nexport type IAlbumLayout = {\n layout: IMediaLayout[];\n containerStyle: ApiDimensions;\n};\n\nfunction getRatios(messages: ApiMessage[]) {\n return messages.map(\n (message) => {\n const dimensions = calculateMediaDimensions(message) as ApiDimensions;\n\n return dimensions.width / dimensions.height;\n },\n );\n}\n\nfunction getProportions(ratios: number[]) {\n return ratios.map((ratio) => (ratio > 1.2 ? 'w' : (ratio < 0.8 ? 'n' : 'q'))).join('');\n}\n\nfunction getAverageRatio(ratios: number[]) {\n return ratios.reduce((result, ratio) => ratio + result, 1) / ratios.length;\n}\n\nfunction accumulate(list: number[], initValue: number) {\n return list.reduce((accumulator, item) => accumulator + item, initValue);\n}\n\nfunction clamp(num: number, low: number, high: number) {\n return num < low ? low : (num > high ? high : num);\n}\n\nfunction cropRatios(ratios: number[], averageRatio: number) {\n return ratios.map((ratio) => (averageRatio > 1.1 ? clamp(ratio, 1, 2.75) : clamp(ratio, 0.6667, 1)));\n}\n\nfunction calculateContainerSize(layout: IMediaLayout[]) {\n const styles: ApiDimensions = { width: 0, height: 0 };\n layout.forEach(({\n dimensions,\n sides,\n }) => {\n if (sides & AlbumRectPart.Right) {\n styles.width = dimensions.width + dimensions.x;\n }\n if (sides & AlbumRectPart.Bottom) {\n styles.height = dimensions.height + dimensions.y;\n }\n });\n\n return styles;\n}\n\nexport function calculateAlbumLayout(\n isOwn: boolean,\n isForwarded: boolean,\n noAvatars: boolean,\n album: IAlbum,\n): IAlbumLayout {\n const spacing = 2;\n const ratios = getRatios(album.messages);\n const proportions = getProportions(ratios);\n const averageRatio = getAverageRatio(ratios);\n const albumCount = ratios.length;\n const forceCalc = ratios.some((ratio) => ratio > 2);\n const maxWidth = getAvailableWidth(isOwn, isForwarded, false, noAvatars) - (isForwarded ? 2.5 : 0) * REM;\n const maxHeight = maxWidth;\n\n let layout;\n\n const params = {\n ratios,\n proportions,\n averageRatio,\n maxWidth,\n minWidth: 100,\n maxHeight,\n spacing,\n };\n\n if (albumCount >= 5 || forceCalc) {\n layout = layoutWithComplexLayouter(params);\n } else if (albumCount === 2) {\n layout = layoutTwo(params);\n } else if (albumCount === 3) {\n layout = layoutThree(params);\n } else {\n layout = layoutFour(params);\n }\n\n return {\n layout,\n containerStyle: calculateContainerSize(layout),\n };\n}\n\nfunction layoutWithComplexLayouter({\n ratios: originalRatios,\n averageRatio,\n maxWidth,\n minWidth,\n spacing,\n maxHeight = (4 * maxWidth) / 3,\n}: ILayoutParams) {\n const ratios = cropRatios(originalRatios, averageRatio);\n const count = originalRatios.length;\n const result = new Array(count);\n const attempts: IAttempt[] = [];\n\n const multiHeight = (offset: number, attemptCount: number) => {\n const attemptRatios = ratios.slice(offset, offset + attemptCount);\n const sum = accumulate(attemptRatios, 0);\n\n return (maxWidth - (attemptCount - 1) * spacing) / sum;\n };\n\n const pushAttempt = (lineCounts: number[]) => {\n const heights: number[] = [];\n let offset = 0;\n lineCounts.forEach((currentCount) => {\n heights.push(multiHeight(offset, currentCount));\n offset += currentCount;\n });\n\n attempts.push({\n lineCounts,\n heights,\n });\n };\n\n for (let first = 1; first !== count; ++first) {\n const second = count - first;\n if (first <= 3 && second <= 3) {\n pushAttempt([first, second]);\n }\n }\n\n for (let first = 1; first !== count - 1; ++first) {\n for (let second = 1; second !== count - first; ++second) {\n const third = count - first - second;\n if (first <= 3 && second <= (averageRatio < 0.85 ? 4 : 3) && third <= 3) {\n pushAttempt([first, second, third]);\n }\n }\n }\n\n for (let first = 1; first !== count - 1; ++first) {\n for (let second = 1; second !== count - first; ++second) {\n for (let third = 1; third !== count - first - second; ++third) {\n const fourth = count - first - second - third;\n if (first <= 3 && second <= 3 && third <= 3 && fourth <= 4) {\n pushAttempt([first, second, third, fourth]);\n }\n }\n }\n }\n\n let optimalAttempt: IAttempt | undefined;\n let optimalDiff = 0;\n for (let i = 0; i < attempts.length; i++) {\n const {\n heights,\n lineCounts,\n } = attempts[i];\n const lineCount = lineCounts.length;\n const totalHeight = accumulate(heights, 0) + spacing * (lineCount - 1);\n const minLineHeight = Math.min(...heights);\n const bad1 = minLineHeight < minWidth ? 1.5 : 1;\n const bad2 = (() => {\n for (let line = 1; line !== lineCount; ++line) {\n if (lineCounts[line - 1] > lineCounts[line]) {\n return 1.5;\n }\n }\n\n return 1;\n })();\n const diff = Math.abs(totalHeight - maxHeight) * bad1 * bad2;\n\n if (!optimalAttempt || diff < optimalDiff) {\n optimalAttempt = attempts[i];\n optimalDiff = diff;\n }\n }\n\n const optimalCounts = optimalAttempt!.lineCounts;\n const optimalHeights = optimalAttempt!.heights;\n const rowCount = optimalCounts.length;\n let index = 0;\n let y = 0;\n for (let row = 0; row !== rowCount; ++row) {\n const colCount = optimalCounts[row];\n const lineHeight = optimalHeights[row];\n const height = Math.round(lineHeight);\n let x = 0;\n\n for (let col = 0; col !== colCount; ++col) {\n const sides = AlbumRectPart.None\n | (row === 0 ? AlbumRectPart.Top : AlbumRectPart.None)\n | (row === rowCount - 1 ? AlbumRectPart.Bottom : AlbumRectPart.None)\n | (col === 0 ? AlbumRectPart.Left : AlbumRectPart.None)\n | (col === colCount - 1 ? AlbumRectPart.Right : AlbumRectPart.None);\n const ratio = ratios[index];\n const width = col === colCount - 1 ? maxWidth - x : Math.round(ratio * lineHeight);\n result[index] = {\n dimensions: {\n x,\n y,\n width,\n height,\n },\n sides,\n };\n x += width + spacing;\n ++index;\n }\n y += height + spacing;\n }\n\n return result;\n}\n\nfunction layoutTwo(params: ILayoutParams) {\n const {\n ratios,\n proportions,\n averageRatio,\n } = params;\n return proportions === 'ww' && averageRatio > 1.4 && ratios[1] - ratios[0] < 0.2\n ? layoutTwoTopBottom(params)\n : proportions === 'ww' || proportions === 'qq'\n ? layoutTwoLeftRightEqual(params)\n : layoutTwoLeftRight(params);\n}\n\nfunction layoutTwoTopBottom(params: ILayoutParams) {\n const {\n ratios,\n maxWidth,\n spacing,\n maxHeight,\n } = params;\n const height = Math.round(Math.min(maxWidth / ratios[0], Math.min(maxWidth / ratios[1], (maxHeight - spacing) / 2)));\n\n return [{\n dimensions: {\n x: 0,\n y: 0,\n width: maxWidth,\n height,\n },\n sides: AlbumRectPart.Left | AlbumRectPart.Top | AlbumRectPart.Right,\n }, {\n dimensions: {\n x: 0,\n y: height + spacing,\n width: maxWidth,\n height,\n },\n sides: AlbumRectPart.Left | AlbumRectPart.Bottom | AlbumRectPart.Right,\n }];\n}\n\nfunction layoutTwoLeftRightEqual(params: ILayoutParams) {\n const {\n ratios,\n maxWidth,\n spacing,\n maxHeight,\n } = params;\n const width = (maxWidth - spacing) / 2;\n const height = Math.round(Math.min(width / ratios[0], Math.min(width / ratios[1], maxHeight)));\n return [{\n dimensions: {\n x: 0,\n y: 0,\n width,\n height,\n },\n sides: AlbumRectPart.Top | AlbumRectPart.Left | AlbumRectPart.Bottom,\n }, {\n dimensions: {\n x: width + spacing,\n y: 0,\n width,\n height,\n },\n sides: AlbumRectPart.Top | AlbumRectPart.Right | AlbumRectPart.Bottom,\n }];\n}\n\nfunction layoutTwoLeftRight(params: ILayoutParams) {\n const {\n ratios,\n minWidth,\n maxWidth,\n spacing,\n maxHeight,\n } = params;\n const minimalWidth = Math.round(1.5 * minWidth);\n const secondWidth = Math.min(\n Math.round(\n Math.max(\n 0.4 * (maxWidth - spacing),\n (maxWidth - spacing) / ratios[0] / (1 / ratios[0] + 1 / ratios[1]),\n ),\n ),\n maxWidth - spacing - minimalWidth,\n );\n const firstWidth = maxWidth - secondWidth - spacing;\n const height = Math.min(maxHeight, Math.round(Math.min(firstWidth / ratios[0], secondWidth / ratios[1])));\n\n return [{\n dimensions: {\n x: 0,\n y: 0,\n width: firstWidth,\n height,\n },\n sides: AlbumRectPart.Top | AlbumRectPart.Left | AlbumRectPart.Bottom,\n }, {\n dimensions: {\n x: firstWidth + spacing,\n y: 0,\n width: secondWidth,\n height,\n },\n sides: AlbumRectPart.Top | AlbumRectPart.Right | AlbumRectPart.Bottom,\n }];\n}\n\nfunction layoutThree(params: ILayoutParams) {\n const { proportions } = params;\n\n return proportions[0] === 'n'\n ? layoutThreeLeftAndOther(params)\n : layoutThreeTopAndOther(params);\n}\n\nfunction layoutThreeLeftAndOther(params: ILayoutParams) {\n const {\n maxHeight,\n spacing,\n ratios,\n maxWidth,\n minWidth,\n } = params;\n const firstHeight = maxHeight;\n const thirdHeight = Math.round(\n Math.min(\n (maxHeight - spacing) / 2,\n (ratios[1] * (maxWidth - spacing)) / (ratios[2] + ratios[1]),\n ),\n );\n const secondHeight = firstHeight - thirdHeight - spacing;\n const rightWidth = Math.max(\n minWidth,\n Math.round(\n Math.min(\n (maxWidth - spacing) / 2,\n Math.min(\n thirdHeight * ratios[2],\n secondHeight * ratios[1],\n ),\n ),\n ),\n );\n const leftWidth = Math.min(Math.round(firstHeight * ratios[0]), maxWidth - spacing - rightWidth);\n\n return [{\n dimensions: {\n x: 0,\n y: 0,\n width: leftWidth,\n height: firstHeight,\n },\n sides: AlbumRectPart.Top | AlbumRectPart.Left | AlbumRectPart.Bottom,\n }, {\n dimensions: {\n x: leftWidth + spacing,\n y: 0,\n width: rightWidth,\n height: secondHeight,\n },\n sides: AlbumRectPart.Top | AlbumRectPart.Right,\n }, {\n dimensions: {\n x: leftWidth + spacing,\n y: secondHeight + spacing,\n width: rightWidth,\n height: thirdHeight,\n },\n sides: AlbumRectPart.Bottom | AlbumRectPart.Right,\n }];\n}\n\nfunction layoutThreeTopAndOther(params: ILayoutParams) {\n const {\n maxWidth,\n ratios,\n maxHeight,\n spacing,\n } = params;\n const firstWidth = maxWidth;\n const firstHeight = Math.round(Math.min(firstWidth / ratios[0], 0.66 * (maxHeight - spacing)));\n const secondWidth = (maxWidth - spacing) / 2;\n const secondHeight = Math.min(\n maxHeight - firstHeight - spacing,\n Math.round(Math.min(\n secondWidth / ratios[1],\n secondWidth / ratios[2],\n )),\n );\n const thirdWidth = firstWidth - secondWidth - spacing;\n\n return [{\n dimensions: {\n x: 0,\n y: 0,\n width: firstWidth,\n height: firstHeight,\n },\n sides: AlbumRectPart.Left | AlbumRectPart.Top | AlbumRectPart.Right,\n }, {\n dimensions: {\n x: 0,\n y: firstHeight + spacing,\n width: secondWidth,\n height: secondHeight,\n },\n sides: AlbumRectPart.Bottom | AlbumRectPart.Left,\n }, {\n dimensions: {\n x: secondWidth + spacing,\n y: firstHeight + spacing,\n width: thirdWidth,\n height: secondHeight,\n },\n sides: AlbumRectPart.Bottom | AlbumRectPart.Right,\n }];\n}\n\nfunction layoutFour(params: ILayoutParams) {\n const { proportions } = params;\n\n return proportions[0] === 'w'\n ? layoutFourTopAndOther(params)\n : layoutFourLeftAndOther(params);\n}\n\nfunction layoutFourTopAndOther({\n maxWidth,\n ratios,\n spacing,\n maxHeight,\n minWidth,\n}: ILayoutParams) {\n const w = maxWidth;\n const h0 = Math.round(Math.min(w / ratios[0], 0.66 * (maxHeight - spacing)));\n const h = Math.round((maxWidth - 2 * spacing) / (ratios[1] + ratios[2] + ratios[3]));\n const w0 = Math.max(minWidth, Math.round(Math.min(0.4 * (maxWidth - 2 * spacing), h * ratios[1])));\n const w2 = Math.round(Math.max(Math.max(minWidth, 0.33 * (maxWidth - 2 * spacing)), h * ratios[3]));\n const w1 = w - w0 - w2 - 2 * spacing;\n const h1 = Math.min(maxHeight - h0 - spacing, h);\n\n return [{\n dimensions: {\n x: 0,\n y: 0,\n width: w,\n height: h0,\n },\n sides: AlbumRectPart.Left | AlbumRectPart.Top | AlbumRectPart.Right,\n }, {\n dimensions: {\n x: 0,\n y: h0 + spacing,\n width: w0,\n height: h1,\n },\n sides: AlbumRectPart.Bottom | AlbumRectPart.Left,\n }, {\n dimensions: {\n x: w0 + spacing,\n y: h0 + spacing,\n width: w1,\n height: h1,\n },\n sides: AlbumRectPart.Bottom,\n }, {\n dimensions: {\n x: w0 + spacing + w1 + spacing,\n y: h0 + spacing,\n width: w2,\n height: h1,\n },\n sides: AlbumRectPart.Right | AlbumRectPart.Bottom,\n }];\n}\n\nfunction layoutFourLeftAndOther({\n maxHeight,\n ratios,\n maxWidth,\n spacing,\n minWidth,\n}: ILayoutParams) {\n const h = maxHeight;\n const w0 = Math.round(Math.min(h * ratios[0], 0.6 * (maxWidth - spacing)));\n const w = Math.round((maxHeight - 2 * spacing) / (1 / ratios[1] + 1 / ratios[2] + 1 / ratios[3]));\n const h0 = Math.round(w / ratios[1]);\n const h1 = Math.round(w / ratios[2]);\n const h2 = h - h0 - h1 - 2 * spacing;\n const w1 = Math.max(minWidth, Math.min(maxWidth - w0 - spacing, w));\n\n return [{\n dimensions: {\n x: 0,\n y: 0,\n width: w0,\n height: h,\n },\n sides: AlbumRectPart.Top | AlbumRectPart.Left | AlbumRectPart.Bottom,\n }, {\n dimensions: {\n x: w0 + spacing,\n y: 0,\n width: w1,\n height: h0,\n },\n sides: AlbumRectPart.Top | AlbumRectPart.Right,\n }, {\n dimensions: {\n x: w0 + spacing,\n y: h0 + spacing,\n width: w1,\n height: h1,\n },\n sides: AlbumRectPart.Right,\n }, {\n dimensions: {\n x: w0 + spacing,\n y: h0 + h1 + 2 * spacing,\n width: w1,\n height: h2,\n },\n sides: AlbumRectPart.Bottom | AlbumRectPart.Right,\n }];\n}\n","import { IS_IOS } from '../../../../util/environment';\n\nlet element: HTMLSpanElement | undefined;\n\nexport default function calculateAuthorWidth(text: string) {\n if (!element) {\n element = document.createElement('span');\n // eslint-disable-next-line max-len\n element.style.font = IS_IOS\n // eslint-disable-next-line max-len\n ? '400 12px system-ui, -apple-system, BlinkMacSystemFont, \"Roboto\", \"Apple Color Emoji\", \"Helvetica Neue\", sans-serif'\n : '400 12px \"Roboto\", -apple-system, \"Apple Color Emoji\", BlinkMacSystemFont, \"Helvetica Neue\", sans-serif';\n element.style.whiteSpace = 'nowrap';\n element.style.position = 'absolute';\n element.style.left = '-999px';\n element.style.opacity = '.01';\n document.body.appendChild(element);\n }\n\n element.innerHTML = text;\n\n return element.offsetWidth;\n}\n","import { FocusDirection } from '../../../../types';\n\nimport { useLayoutEffect } from '../../../../lib/teact/teact';\nimport fastSmoothScroll from '../../../../util/fastSmoothScroll';\n\n// This is used when the viewport was replaced.\nconst RELOCATED_FOCUS_OFFSET = 1000;\nconst FOCUS_MARGIN = 20;\n\nexport default function useFocusMessage(\n elementRef: { current: HTMLDivElement | null },\n chatId: string,\n isFocused?: boolean,\n focusDirection?: FocusDirection,\n noFocusHighlight?: boolean,\n isResizingContainer?: boolean,\n) {\n useLayoutEffect(() => {\n if (isFocused && elementRef.current) {\n const messagesContainer = elementRef.current.closest<HTMLDivElement>('.MessageList')!;\n\n fastSmoothScroll(\n messagesContainer,\n elementRef.current,\n // `noFocusHighlight` always called from “scroll-to-bottom” buttons\n noFocusHighlight ? 'end' : 'centerOrTop',\n FOCUS_MARGIN,\n focusDirection !== undefined ? RELOCATED_FOCUS_OFFSET : undefined,\n focusDirection,\n undefined,\n isResizingContainer,\n );\n }\n }, [elementRef, chatId, isFocused, focusDirection, noFocusHighlight, isResizingContainer]);\n}\n","import React, { FC, memo } from '../../../lib/teact/teact';\nimport { OwnProps } from './ContextMenuContainer';\nimport { Bundles } from '../../../util/moduleLoader';\n\nimport useModuleLoader from '../../../hooks/useModuleLoader';\n\nconst ContextMenuContainerAsync: FC<OwnProps> = (props) => {\n const { isOpen } = props;\n const ContextMenuContainer = useModuleLoader(Bundles.Extra, 'ContextMenuContainer', !isOpen);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return ContextMenuContainer ? <ContextMenuContainer {...props} /> : undefined;\n};\n\nexport default memo(ContextMenuContainerAsync);\n","import React, {\n FC, memo, useEffect, useMemo, useRef,\n} from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { ApiUser, ApiMessage, ApiChat } from '../../api/types';\nimport { FocusDirection } from '../../types';\n\nimport {\n selectUser,\n selectChatMessage,\n selectIsMessageFocused,\n selectChat,\n} from '../../modules/selectors';\nimport { isChatChannel } from '../../modules/helpers';\nimport buildClassName from '../../util/buildClassName';\nimport renderText from '../common/helpers/renderText';\nimport { renderActionMessageText } from '../common/helpers/renderActionMessageText';\nimport useEnsureMessage from '../../hooks/useEnsureMessage';\nimport useContextMenuHandlers from '../../hooks/useContextMenuHandlers';\nimport { ObserveFn, useOnIntersect } from '../../hooks/useIntersectionObserver';\nimport useFocusMessage from './message/hooks/useFocusMessage';\nimport useLang from '../../hooks/useLang';\n\nimport ContextMenuContainer from './message/ContextMenuContainer.async';\nimport useFlag from '../../hooks/useFlag';\nimport useShowTransition from '../../hooks/useShowTransition';\nimport { preventMessageInputBlur } from './helpers/preventMessageInputBlur';\n\ntype OwnProps = {\n message: ApiMessage;\n observeIntersection?: ObserveFn;\n isEmbedded?: boolean;\n appearanceOrder?: number;\n isLastInList?: boolean;\n};\n\ntype StateProps = {\n usersById: Record<string, ApiUser>;\n sender?: ApiUser | ApiChat;\n targetUserIds?: string[];\n targetMessage?: ApiMessage;\n targetChatId?: string;\n isFocused: boolean;\n focusDirection?: FocusDirection;\n noFocusHighlight?: boolean;\n};\n\nconst APPEARANCE_DELAY = 10;\n\nconst ActionMessage: FC<OwnProps & StateProps> = ({\n message,\n observeIntersection,\n isEmbedded,\n appearanceOrder = 0,\n isLastInList,\n usersById,\n sender,\n targetUserIds,\n targetMessage,\n targetChatId,\n isFocused,\n focusDirection,\n noFocusHighlight,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const ref = useRef<HTMLDivElement>(null);\n\n useOnIntersect(ref, observeIntersection);\n useEnsureMessage(message.chatId, message.replyToMessageId, targetMessage);\n useFocusMessage(ref, message.chatId, isFocused, focusDirection, noFocusHighlight);\n\n const lang = useLang();\n\n const noAppearanceAnimation = appearanceOrder <= 0;\n const [isShown, markShown] = useFlag(noAppearanceAnimation);\n useEffect(() => {\n if (noAppearanceAnimation) {\n return;\n }\n\n setTimeout(markShown, appearanceOrder * APPEARANCE_DELAY);\n }, [appearanceOrder, markShown, noAppearanceAnimation]);\n const { transitionClassNames } = useShowTransition(isShown, undefined, noAppearanceAnimation, false);\n\n const targetUsers = useMemo(() => {\n return targetUserIds\n ? targetUserIds.map((userId) => usersById?.[userId]).filter<ApiUser>(Boolean as any)\n : undefined;\n }, [targetUserIds, usersById]);\n\n const content = renderActionMessageText(\n lang,\n message,\n sender,\n targetUsers,\n targetMessage,\n targetChatId,\n isEmbedded ? { isEmbedded: true, asPlain: true } : undefined,\n );\n const {\n isContextMenuOpen, contextMenuPosition,\n handleBeforeContextMenu, handleContextMenu,\n handleContextMenuClose, handleContextMenuHide,\n } = useContextMenuHandlers(ref);\n const isContextMenuShown = contextMenuPosition !== undefined;\n\n const handleMouseDown = (e: React.MouseEvent<HTMLDivElement, MouseEvent>) => {\n preventMessageInputBlur(e);\n handleBeforeContextMenu(e);\n };\n\n if (isEmbedded) {\n return <span className=\"embedded-action-message\">{renderText(content as string)}</span>;\n }\n\n const className = buildClassName(\n 'ActionMessage message-list-item',\n isFocused && !noFocusHighlight && 'focused',\n isContextMenuShown && 'has-menu-open',\n isLastInList && 'last-in-list',\n transitionClassNames,\n );\n\n return (\n <div\n ref={ref}\n id={`message${message.id}`}\n className={className}\n data-message-id={message.id}\n onMouseDown={handleMouseDown}\n onContextMenu={handleContextMenu}\n >\n <span>{content}</span>\n {contextMenuPosition && (\n <ContextMenuContainer\n isOpen={isContextMenuOpen}\n anchor={contextMenuPosition}\n message={message}\n messageListType=\"thread\"\n onClose={handleContextMenuClose}\n onCloseAnimationEnd={handleContextMenuHide}\n />\n )}\n </div>\n );\n};\n\nexport default memo(withGlobal<OwnProps>(\n (global, { message }): StateProps => {\n const { byId: usersById } = global.users;\n const userId = message.senderId;\n const { targetUserIds, targetChatId } = message.content.action || {};\n const targetMessageId = message.replyToMessageId;\n const targetMessage = targetMessageId\n ? selectChatMessage(global, message.chatId, targetMessageId)\n : undefined;\n\n const isFocused = selectIsMessageFocused(global, message);\n const { direction: focusDirection, noHighlight: noFocusHighlight } = (isFocused && global.focusedMessage) || {};\n\n const chat = selectChat(global, message.chatId);\n const sender = chat && (isChatChannel(chat) || userId === message.chatId)\n ? chat\n : userId ? selectUser(global, userId) : undefined;\n\n return {\n usersById,\n sender,\n targetChatId,\n targetUserIds,\n targetMessage,\n isFocused,\n ...(isFocused && { focusDirection, noFocusHighlight }),\n };\n },\n)(ActionMessage));\n","import React, { FC, useRef } from '../../lib/teact/teact';\n\nimport { ApiUser, ApiMessage, ApiChat } from '../../api/types';\n\nimport {\n getMessageMediaHash,\n isActionMessage,\n getMessageSummaryText,\n getSenderTitle,\n getMessageRoundVideo,\n} from '../../modules/helpers';\nimport renderText from './helpers/renderText';\nimport { getPictogramDimensions } from './helpers/mediaDimensions';\nimport buildClassName from '../../util/buildClassName';\nimport { ObserveFn, useIsIntersecting } from '../../hooks/useIntersectionObserver';\nimport useMedia from '../../hooks/useMedia';\nimport useWebpThumbnail from '../../hooks/useWebpThumbnail';\nimport useLang from '../../hooks/useLang';\n\nimport ActionMessage from '../middle/ActionMessage';\n\nimport './EmbeddedMessage.scss';\n\ntype OwnProps = {\n observeIntersection?: ObserveFn;\n className?: string;\n message?: ApiMessage;\n sender?: ApiUser | ApiChat;\n title?: string;\n customText?: string;\n onClick: NoneToVoidFunction;\n};\n\nconst NBSP = '\\u00A0';\n\nconst EmbeddedMessage: FC<OwnProps> = ({\n className,\n message,\n sender,\n title,\n customText,\n observeIntersection,\n onClick,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const ref = useRef<HTMLDivElement>(null);\n const isIntersecting = useIsIntersecting(ref, observeIntersection);\n\n const mediaBlobUrl = useMedia(message && getMessageMediaHash(message, 'pictogram'), !isIntersecting);\n const pictogramId = message && `sticker-reply-thumb${message.id}`;\n const mediaThumbnail = useWebpThumbnail(message);\n const isRoundVideo = Boolean(message && getMessageRoundVideo(message));\n\n const lang = useLang();\n\n const senderTitle = sender && getSenderTitle(lang, sender);\n\n return (\n <div\n ref={ref}\n className={buildClassName('EmbeddedMessage', className)}\n onClick={message ? onClick : undefined}\n >\n {mediaThumbnail && renderPictogram(pictogramId, mediaThumbnail, mediaBlobUrl, isRoundVideo)}\n <div className=\"message-text\">\n <p dir=\"auto\">\n {!message ? (\n customText || NBSP\n ) : isActionMessage(message) ? (\n <ActionMessage message={message} isEmbedded />\n ) : (\n renderText(getMessageSummaryText(lang, message, Boolean(mediaThumbnail)))\n )}\n </p>\n <div className=\"message-title\" dir=\"auto\">{renderText(senderTitle || title || NBSP)}</div>\n </div>\n </div>\n );\n};\n\nfunction renderPictogram(\n id: string | undefined,\n thumbDataUri: string,\n blobUrl?: string,\n isRoundVideo?: boolean,\n) {\n const { width, height } = getPictogramDimensions();\n\n return (\n <img\n id={id}\n src={blobUrl || thumbDataUri}\n width={width}\n height={height}\n alt=\"\"\n className={isRoundVideo ? 'round' : ''}\n />\n );\n}\n\nexport default EmbeddedMessage;\n","import React, { FC, memo } from '../../../lib/teact/teact';\n\nimport { ApiMessage, ApiMessageOutgoingStatus } from '../../../api/types';\n\nimport { formatTime } from '../../../util/dateFormat';\nimport { formatIntegerCompact } from '../../../util/textFormat';\n\nimport MessageOutgoingStatus from '../../common/MessageOutgoingStatus';\nimport renderText from '../../common/helpers/renderText';\nimport useLang from '../../../hooks/useLang';\n\nimport './MessageMeta.scss';\n\ntype OwnProps = {\n message: ApiMessage;\n outgoingStatus?: ApiMessageOutgoingStatus;\n signature?: string;\n onClick: (e: React.MouseEvent<HTMLDivElement, MouseEvent>) => void;\n};\n\nconst MessageMeta: FC<OwnProps> = ({\n message, outgoingStatus, signature, onClick,\n}) => {\n const lang = useLang();\n\n return (\n <span className=\"MessageMeta\" dir={lang.isRtl ? 'rtl' : 'ltr'} onClick={onClick}>\n {Boolean(message.views) && (\n <>\n <span className=\"message-views\">\n {formatIntegerCompact(message.views!)}\n </span>\n <i className=\"icon-channelviews\" />\n </>\n )}\n {signature && (\n <span className=\"message-signature\">{renderText(signature)}</span>\n )}\n <span className=\"message-time\">\n {message.isEdited && `${lang('EditedMessage')} `}\n {formatTime(message.date * 1000, lang)}\n </span>\n {outgoingStatus && (\n <MessageOutgoingStatus status={outgoingStatus} />\n )}\n </span>\n );\n};\n\nexport default memo(MessageMeta);\n","import React, { FC, useRef } from '../../../lib/teact/teact';\n\nimport { ApiMessage } from '../../../api/types';\n\nimport { MEMOJI_STICKER_ID } from '../../../config';\nimport { getStickerDimensions } from '../../common/helpers/mediaDimensions';\nimport { getMessageMediaFormat, getMessageMediaHash } from '../../../modules/helpers';\nimport buildClassName from '../../../util/buildClassName';\nimport { ObserveFn, useIsIntersecting } from '../../../hooks/useIntersectionObserver';\nimport useMedia from '../../../hooks/useMedia';\nimport useMediaTransition from '../../../hooks/useMediaTransition';\nimport useFlag from '../../../hooks/useFlag';\nimport useWebpThumbnail from '../../../hooks/useWebpThumbnail';\n\nimport AnimatedSticker from '../../common/AnimatedSticker';\nimport StickerSetModal from '../../common/StickerSetModal.async';\n\nimport './Sticker.scss';\n\ntype OwnProps = {\n message: ApiMessage;\n observeIntersection: ObserveFn;\n observeIntersectionForPlaying: ObserveFn;\n shouldLoop?: boolean;\n lastSyncTime?: number;\n};\n\nconst Sticker: FC<OwnProps> = ({\n message, observeIntersection, observeIntersectionForPlaying, shouldLoop, lastSyncTime,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const ref = useRef<HTMLDivElement>(null);\n\n const [isModalOpen, openModal, closeModal] = useFlag();\n\n const sticker = message.content.sticker!;\n const { isAnimated, stickerSetId } = sticker;\n const isMemojiSticker = stickerSetId === MEMOJI_STICKER_ID;\n\n const shouldLoad = useIsIntersecting(ref, observeIntersection);\n const shouldPlay = useIsIntersecting(ref, observeIntersectionForPlaying);\n\n const mediaHash = sticker.isPreloadedGlobally ? `sticker${sticker.id}` : getMessageMediaHash(message, 'inline')!;\n const thumbDataUri = useWebpThumbnail(message);\n const mediaData = useMedia(\n mediaHash,\n !shouldLoad,\n getMessageMediaFormat(message, 'inline', true),\n lastSyncTime,\n );\n\n const isMediaLoaded = Boolean(mediaData);\n const [isAnimationLoaded, markAnimationLoaded] = useFlag(isMediaLoaded);\n const isMediaReady = isAnimated ? isAnimationLoaded : isMediaLoaded;\n const transitionClassNames = useMediaTransition(isMediaReady);\n\n const { width, height } = getStickerDimensions(sticker);\n const thumbClassName = buildClassName('thumbnail', !thumbDataUri && 'empty');\n\n const stickerClassName = buildClassName(\n 'Sticker media-inner',\n isMemojiSticker && 'inactive',\n );\n\n return (\n <div ref={ref} className={stickerClassName} onClick={!isMemojiSticker ? openModal : undefined}>\n {!isMediaReady && (\n <img\n id={`sticker-thumb-${message.id}`}\n src={thumbDataUri}\n width={width}\n height={height}\n alt=\"\"\n className={thumbClassName}\n />\n )}\n {!isAnimated && (\n <img\n id={`sticker-${message.id}`}\n src={mediaData as string}\n width={width}\n height={height}\n alt=\"\"\n className={buildClassName('full-media', transitionClassNames)}\n />\n )}\n {isAnimated && isMediaLoaded && (\n <AnimatedSticker\n key={mediaHash}\n className={buildClassName('full-media', transitionClassNames)}\n id={mediaHash}\n animationData={mediaData as AnyLiteral}\n size={width}\n play={shouldPlay}\n noLoop={!shouldLoop}\n onLoad={markAnimationLoaded}\n />\n )}\n <StickerSetModal\n isOpen={isModalOpen}\n fromSticker={sticker}\n onClose={closeModal}\n />\n </div>\n );\n};\n\nexport default Sticker;\n","import { ApiMessage } from '../../../../api/types';\n\nimport { IS_CANVAS_FILTER_SUPPORTED, IS_SINGLE_COLUMN_LAYOUT } from '../../../../util/environment';\nimport { getMessageMediaThumbDataUri } from '../../../../modules/helpers';\nimport useCanvasBlur from '../../../../hooks/useCanvasBlur';\n\nexport default function useBlurredMediaThumbRef(message: ApiMessage, fullMediaData?: string) {\n return useCanvasBlur(\n getMessageMediaThumbDataUri(message),\n Boolean(fullMediaData),\n IS_SINGLE_COLUMN_LAYOUT && !IS_CANVAS_FILTER_SUPPORTED,\n );\n}\n","import { ISettings } from '../../../../types';\n\nconst SELECTED_APPENDIX_COLORS = {\n dark: {\n outgoing: 'rgb(135,116,225)',\n incoming: 'rgb(33,33,33)',\n },\n light: {\n outgoing: 'rgb(238,255,222)',\n incoming: 'rgb(255,255,255)',\n },\n};\n\nexport default function getCustomAppendixBg(\n src: string, isOwn: boolean, inSelectMode?: boolean, isSelected?: boolean, theme?: ISettings['theme'],\n) {\n if (isSelected) {\n return Promise.resolve(SELECTED_APPENDIX_COLORS[theme || 'light'][isOwn ? 'outgoing' : 'incoming']);\n }\n return getAppendixColorFromImage(src, isOwn);\n}\n\nasync function getAppendixColorFromImage(src: string, isOwn: boolean) {\n const img = new Image();\n img.src = src;\n\n if (!img.width) {\n await new Promise((resolve) => {\n img.onload = resolve;\n });\n }\n\n const canvas = document.createElement('canvas');\n const ctx = canvas.getContext('2d')!;\n\n canvas.width = img.width;\n canvas.height = img.height;\n\n ctx.drawImage(img, 0, 0, img.width, img.height);\n\n const x = isOwn ? img.width - 1 : 0;\n const y = img.height - 1;\n\n const pixel = Array.from(ctx.getImageData(x, y, 1, 1).data);\n return `rgba(${pixel.join(',')})`;\n}\n","import React, {\n FC, useCallback, useLayoutEffect, useRef, useState,\n} from '../../../lib/teact/teact';\n\nimport { ApiMessage } from '../../../api/types';\nimport { ISettings } from '../../../types';\nimport { IMediaDimensions } from './helpers/calculateAlbumLayout';\n\nimport {\n getMessagePhoto,\n getMessageWebPagePhoto,\n getMessageMediaHash,\n getMediaTransferState,\n isOwnMessage,\n} from '../../../modules/helpers';\nimport { ObserveFn, useIsIntersecting } from '../../../hooks/useIntersectionObserver';\nimport useMediaWithLoadProgress from '../../../hooks/useMediaWithLoadProgress';\nimport useShowTransition from '../../../hooks/useShowTransition';\nimport useBlurredMediaThumbRef from './hooks/useBlurredMediaThumbRef';\nimport usePrevious from '../../../hooks/usePrevious';\nimport useMediaTransition from '../../../hooks/useMediaTransition';\nimport buildClassName from '../../../util/buildClassName';\nimport getCustomAppendixBg from './helpers/getCustomAppendixBg';\nimport { calculateMediaDimensions } from './helpers/mediaDimensions';\n\nimport ProgressSpinner from '../../ui/ProgressSpinner';\n\nexport type OwnProps = {\n id?: string;\n message: ApiMessage;\n observeIntersection?: ObserveFn;\n noAvatars?: boolean;\n canAutoLoad?: boolean;\n isInSelectMode?: boolean;\n isSelected?: boolean;\n uploadProgress?: number;\n size?: 'inline' | 'pictogram';\n shouldAffectAppendix?: boolean;\n dimensions?: IMediaDimensions & { isSmall?: boolean };\n nonInteractive?: boolean;\n isDownloading: boolean;\n theme: ISettings['theme'];\n onClick?: (id: number) => void;\n onCancelUpload?: (message: ApiMessage) => void;\n};\n\nconst CUSTOM_APPENDIX_ATTRIBUTE = 'data-has-custom-appendix';\n\nconst Photo: FC<OwnProps> = ({\n id,\n message,\n observeIntersection,\n noAvatars,\n canAutoLoad,\n isInSelectMode,\n isSelected,\n uploadProgress,\n size = 'inline',\n dimensions,\n nonInteractive,\n shouldAffectAppendix,\n isDownloading,\n theme,\n onClick,\n onCancelUpload,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const ref = useRef<HTMLDivElement>(null);\n\n const photo = (getMessagePhoto(message) || getMessageWebPagePhoto(message))!;\n const localBlobUrl = photo.blobUrl;\n\n const isIntersecting = useIsIntersecting(ref, observeIntersection);\n\n const [isLoadAllowed, setIsLoadAllowed] = useState(canAutoLoad);\n const shouldLoad = isLoadAllowed && isIntersecting;\n const {\n mediaData, loadProgress,\n } = useMediaWithLoadProgress(getMessageMediaHash(message, size), !shouldLoad);\n const fullMediaData = localBlobUrl || mediaData;\n const thumbRef = useBlurredMediaThumbRef(message, fullMediaData);\n\n const {\n loadProgress: downloadProgress,\n } = useMediaWithLoadProgress(getMessageMediaHash(message, 'download'), !isDownloading);\n\n const {\n isUploading, isTransferring, transferProgress,\n } = getMediaTransferState(\n message,\n uploadProgress || (isDownloading ? downloadProgress : loadProgress),\n shouldLoad && !fullMediaData,\n );\n const wasLoadDisabled = usePrevious(isLoadAllowed) === false;\n\n const transitionClassNames = useMediaTransition(fullMediaData);\n const {\n shouldRender: shouldRenderSpinner,\n transitionClassNames: spinnerClassNames,\n } = useShowTransition(isTransferring, undefined, wasLoadDisabled, 'slow');\n const {\n shouldRender: shouldRenderDownloadButton,\n transitionClassNames: downloadButtonClassNames,\n } = useShowTransition(!fullMediaData && !isLoadAllowed);\n\n const handleClick = useCallback(() => {\n if (isUploading) {\n if (onCancelUpload) {\n onCancelUpload(message);\n }\n } else if (!fullMediaData) {\n setIsLoadAllowed((isAllowed) => !isAllowed);\n } else if (onClick) {\n onClick(message.id);\n }\n }, [fullMediaData, isUploading, message, onCancelUpload, onClick]);\n\n const isOwn = isOwnMessage(message);\n useLayoutEffect(() => {\n if (!shouldAffectAppendix) {\n return;\n }\n\n const contentEl = ref.current!.closest<HTMLDivElement>('.message-content')!;\n\n if (fullMediaData) {\n getCustomAppendixBg(fullMediaData, isOwn, isInSelectMode, isSelected, theme).then((appendixBg) => {\n contentEl.style.setProperty('--appendix-bg', appendixBg);\n contentEl.setAttribute(CUSTOM_APPENDIX_ATTRIBUTE, '');\n });\n } else {\n contentEl.classList.add('has-appendix-thumb');\n }\n }, [fullMediaData, isOwn, shouldAffectAppendix, isInSelectMode, isSelected, theme]);\n\n const { width, height, isSmall } = dimensions || calculateMediaDimensions(message, noAvatars);\n\n const className = buildClassName(\n 'media-inner',\n !isUploading && !nonInteractive && 'interactive',\n isSmall && 'small-image',\n width === height && 'square-image',\n );\n\n const style = dimensions\n ? `width: ${width}px; height: ${height}px; left: ${dimensions.x}px; top: ${dimensions.y}px;`\n : '';\n\n return (\n <div\n id={id}\n ref={ref}\n className={className}\n // @ts-ignore teact feature\n style={style}\n onClick={isUploading ? undefined : handleClick}\n >\n <canvas\n ref={thumbRef}\n className=\"thumbnail\"\n // @ts-ignore teact feature\n style={`width: ${width}px; height: ${height}px`}\n />\n <img\n src={fullMediaData}\n className={`full-media ${transitionClassNames}`}\n width={width}\n height={height}\n alt=\"\"\n />\n {shouldRenderSpinner && !shouldRenderDownloadButton && (\n <div className={`media-loading ${spinnerClassNames}`}>\n <ProgressSpinner progress={transferProgress} onClick={isUploading ? handleClick : undefined} />\n </div>\n )}\n {shouldRenderDownloadButton && <i className={buildClassName('icon-download', downloadButtonClassNames)} />}\n {isTransferring && (\n <span className=\"message-transfer-progress\">{Math.round(transferProgress * 100)}%</span>\n )}\n </div>\n );\n};\n\nexport default Photo;\n","import { RefObject } from 'react';\nimport { useCallback, useRef } from '../lib/teact/teact';\n\nimport useHeavyAnimationCheck from './useHeavyAnimationCheck';\nimport safePlay from '../util/safePlay';\n\nexport default function useHeavyAnimationCheckForVideo(playerRef: RefObject<HTMLVideoElement>, shouldPlay: boolean) {\n const shouldPlayRef = useRef();\n shouldPlayRef.current = shouldPlay;\n\n const pause = useCallback(() => {\n if (playerRef.current) {\n playerRef.current.pause();\n }\n }, [playerRef]);\n\n const play = useCallback(() => {\n if (playerRef.current && shouldPlayRef.current) {\n safePlay(playerRef.current);\n }\n }, [playerRef]);\n\n useHeavyAnimationCheck(pause, play);\n}\n","import { useCallback, useRef } from '../../../../lib/teact/teact';\nimport { fastRaf } from '../../../../util/schedulers';\nimport useBackgroundMode from '../../../../hooks/useBackgroundMode';\nimport safePlay from '../../../../util/safePlay';\n\nexport default (playerRef: { current: HTMLVideoElement | null }, isPlayAllowed = false) => {\n const wasPlaying = useRef(false);\n const isFrozen = useRef(false);\n\n const freezePlaying = useCallback(() => {\n isFrozen.current = true;\n\n if (!isPlayAllowed || !playerRef.current) {\n return;\n }\n\n if (!wasPlaying.current) {\n wasPlaying.current = !playerRef.current.paused;\n }\n\n playerRef.current.pause();\n }, [isPlayAllowed, playerRef]);\n\n const unfreezePlaying = useCallback(() => {\n // At this point HTMLVideoElement can be unmounted from the DOM\n if (isPlayAllowed && playerRef.current && wasPlaying.current && document.body.contains(playerRef.current)) {\n safePlay(playerRef.current);\n }\n\n wasPlaying.current = false;\n isFrozen.current = false;\n }, [isPlayAllowed, playerRef]);\n\n const unfreezePlayingOnRaf = useCallback(() => {\n fastRaf(unfreezePlaying);\n }, [unfreezePlaying]);\n\n if (!document.hasFocus()) {\n freezePlaying();\n }\n\n useBackgroundMode(freezePlaying, unfreezePlayingOnRaf);\n};\n","import React, {\n FC, useCallback, useRef, useState,\n} from '../../../lib/teact/teact';\nimport { getDispatch } from '../../../lib/teact/teactn';\n\nimport { ApiMediaFormat, ApiMessage } from '../../../api/types';\nimport { IMediaDimensions } from './helpers/calculateAlbumLayout';\n\nimport { formatMediaDuration } from '../../../util/dateFormat';\nimport buildClassName from '../../../util/buildClassName';\nimport { calculateVideoDimensions } from '../../common/helpers/mediaDimensions';\nimport {\n getMediaTransferState,\n getMessageMediaFormat,\n getMessageMediaHash,\n getMessageVideo,\n getMessageWebPageVideo,\n isForwardedMessage,\n isOwnMessage,\n} from '../../../modules/helpers';\nimport { ObserveFn, useIsIntersecting } from '../../../hooks/useIntersectionObserver';\nimport useMediaWithLoadProgress from '../../../hooks/useMediaWithLoadProgress';\nimport useMedia from '../../../hooks/useMedia';\nimport useShowTransition from '../../../hooks/useShowTransition';\nimport usePrevious from '../../../hooks/usePrevious';\nimport useBuffering from '../../../hooks/useBuffering';\nimport useHeavyAnimationCheckForVideo from '../../../hooks/useHeavyAnimationCheckForVideo';\nimport useVideoCleanup from '../../../hooks/useVideoCleanup';\nimport usePauseOnInactive from './hooks/usePauseOnInactive';\nimport useBlurredMediaThumbRef from './hooks/useBlurredMediaThumbRef';\n\nimport ProgressSpinner from '../../ui/ProgressSpinner';\n\nexport type OwnProps = {\n id?: string;\n message: ApiMessage;\n observeIntersection: ObserveFn;\n noAvatars?: boolean;\n canAutoLoad?: boolean;\n canAutoPlay?: boolean;\n uploadProgress?: number;\n dimensions?: IMediaDimensions;\n lastSyncTime?: number;\n isDownloading: boolean;\n onClick?: (id: number) => void;\n onCancelUpload?: (message: ApiMessage) => void;\n};\n\nconst Video: FC<OwnProps> = ({\n id,\n message,\n observeIntersection,\n noAvatars,\n canAutoLoad,\n canAutoPlay,\n uploadProgress,\n lastSyncTime,\n dimensions,\n onClick,\n onCancelUpload,\n isDownloading,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const ref = useRef<HTMLDivElement>(null);\n // eslint-disable-next-line no-null/no-null\n const videoRef = useRef<HTMLVideoElement>(null);\n\n const video = (getMessageVideo(message) || getMessageWebPageVideo(message))!;\n const localBlobUrl = video.blobUrl;\n\n const isIntersecting = useIsIntersecting(ref, observeIntersection);\n\n const [isLoadAllowed, setIsLoadAllowed] = useState(canAutoLoad);\n const shouldLoad = Boolean(isLoadAllowed && isIntersecting && lastSyncTime);\n const [isPlayAllowed, setIsPlayAllowed] = useState(canAutoPlay);\n\n const previewBlobUrl = useMedia(\n getMessageMediaHash(message, 'pictogram'),\n !(isIntersecting && lastSyncTime),\n getMessageMediaFormat(message, 'pictogram'),\n lastSyncTime,\n );\n const { transitionClassNames: previewClassNames } = useShowTransition(\n Boolean(previewBlobUrl),\n undefined,\n undefined,\n 'slow',\n );\n\n const { mediaData, loadProgress } = useMediaWithLoadProgress(\n getMessageMediaHash(message, 'inline'),\n !shouldLoad,\n getMessageMediaFormat(message, 'inline'),\n lastSyncTime,\n );\n const fullMediaData = localBlobUrl || mediaData;\n const isInline = Boolean(isIntersecting && fullMediaData);\n // Thumbnail is always rendered so we can only disable blur if we have preview\n const thumbRef = useBlurredMediaThumbRef(message, previewBlobUrl);\n\n const { loadProgress: downloadProgress } = useMediaWithLoadProgress(\n getMessageMediaHash(message, 'download'),\n !isDownloading,\n ApiMediaFormat.BlobUrl,\n lastSyncTime,\n );\n\n const { isBuffered, bufferingHandlers } = useBuffering(!canAutoLoad);\n const { isUploading, isTransferring, transferProgress } = getMediaTransferState(\n message,\n uploadProgress || (isDownloading ? downloadProgress : loadProgress),\n (shouldLoad && !isBuffered) || isDownloading,\n );\n const wasLoadDisabled = usePrevious(isLoadAllowed) === false;\n const {\n shouldRender: shouldRenderSpinner,\n transitionClassNames: spinnerClassNames,\n } = useShowTransition(isTransferring, undefined, wasLoadDisabled);\n const {\n shouldRender: shouldRenderPlayButton,\n transitionClassNames: playButtonClassNames,\n } = useShowTransition(isLoadAllowed && !isPlayAllowed && !shouldRenderSpinner);\n\n const [playProgress, setPlayProgress] = useState<number>(0);\n const handleTimeUpdate = useCallback((e: React.SyntheticEvent<HTMLVideoElement>) => {\n setPlayProgress(Math.max(0, e.currentTarget.currentTime - 1));\n }, []);\n\n const duration = (videoRef.current?.duration) || video.duration || 0;\n\n const isOwn = isOwnMessage(message);\n const isForwarded = isForwardedMessage(message);\n const { width, height } = dimensions || calculateVideoDimensions(video, isOwn, isForwarded, noAvatars);\n\n useHeavyAnimationCheckForVideo(videoRef, Boolean(isInline && canAutoPlay));\n usePauseOnInactive(videoRef, isPlayAllowed);\n useVideoCleanup(videoRef, [isInline]);\n\n const handleClick = useCallback(() => {\n if (isUploading) {\n if (onCancelUpload) {\n onCancelUpload(message);\n }\n } else if (isDownloading) {\n getDispatch().cancelMessageMediaDownload({ message });\n } else if (!fullMediaData) {\n setIsLoadAllowed((isAllowed) => !isAllowed);\n } else if (fullMediaData && !isPlayAllowed) {\n setIsPlayAllowed(true);\n videoRef.current!.play();\n } else if (onClick) {\n onClick(message.id);\n }\n }, [isUploading, isDownloading, fullMediaData, isPlayAllowed, onClick, onCancelUpload, message]);\n\n const className = buildClassName('media-inner dark', !isUploading && 'interactive');\n const style = dimensions\n ? `width: ${width}px; height: ${height}px; left: ${dimensions.x}px; top: ${dimensions.y}px;`\n : '';\n\n return (\n <div\n ref={ref}\n id={id}\n className={className}\n // @ts-ignore teact feature\n style={style}\n onClick={isUploading ? undefined : handleClick}\n >\n <canvas\n ref={thumbRef}\n className=\"thumbnail\"\n // @ts-ignore teact feature\n style={`width: ${width}px; height: ${height}px;`}\n />\n <img\n src={previewBlobUrl}\n className={buildClassName('thumbnail', previewClassNames)}\n // @ts-ignore teact feature\n style={`width: ${width}px; height: ${height}px;`}\n alt=\"\"\n />\n {isInline && (\n <video\n ref={videoRef}\n className=\"full-media\"\n width={width}\n height={height}\n autoPlay={isPlayAllowed}\n muted\n loop\n playsInline\n // eslint-disable-next-line react/jsx-props-no-spreading\n {...bufferingHandlers}\n onTimeUpdate={handleTimeUpdate}\n >\n <source src={fullMediaData} />\n </video>\n )}\n {shouldRenderPlayButton && <i className={buildClassName('icon-large-play', playButtonClassNames)} />}\n {shouldRenderSpinner && (\n <div className={buildClassName('media-loading', spinnerClassNames)}>\n <ProgressSpinner progress={transferProgress} onClick={handleClick} />\n </div>\n )}\n {!isLoadAllowed && (\n <i className=\"icon-download\" />\n )}\n {isTransferring ? (\n <span className=\"message-transfer-progress\">\n {(isUploading || isDownloading) ? `${Math.round(transferProgress * 100)}%` : '...'}\n </span>\n ) : (\n <div className=\"message-media-duration\">\n {video.isGif ? 'GIF' : formatMediaDuration(Math.max(duration - playProgress, 0))}\n </div>\n )}\n </div>\n );\n};\n\nexport default Video;\n","import React, { FC, useCallback } from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../../global/types';\nimport { ApiUser, ApiContact, ApiCountryCode } from '../../../api/types';\n\nimport { selectUser } from '../../../modules/selectors';\nimport { formatPhoneNumberWithCode } from '../../../util/phoneNumber';\n\nimport Avatar from '../../common/Avatar';\n\nimport './Contact.scss';\nimport { pick } from '../../../util/iteratees';\nimport buildClassName from '../../../util/buildClassName';\n\ntype OwnProps = {\n contact: ApiContact;\n};\n\ntype StateProps = {\n user?: ApiUser;\n phoneCodeList: ApiCountryCode[];\n};\n\ntype DispatchProps = Pick<GlobalActions, 'openUserInfo'>;\n\nconst Contact: FC<OwnProps & StateProps & DispatchProps> = ({\n contact, user, openUserInfo, phoneCodeList,\n}) => {\n const {\n firstName,\n lastName,\n phoneNumber,\n userId,\n } = contact;\n\n const handleClick = useCallback(() => {\n openUserInfo({ id: userId });\n }, [openUserInfo, userId]);\n\n return (\n <div\n className={buildClassName('Contact', Boolean(userId) && 'interactive')}\n onClick={userId ? handleClick : undefined}\n >\n <Avatar size=\"large\" user={user} text={firstName || lastName} />\n <div className=\"contact-info\">\n <div className=\"contact-name\">{firstName} {lastName}</div>\n <div className=\"contact-phone\">{formatPhoneNumberWithCode(phoneCodeList, phoneNumber)}</div>\n </div>\n </div>\n );\n};\n\nexport default withGlobal<OwnProps>(\n (global, { contact }): StateProps => {\n const { countryList: { phoneCodes: phoneCodeList } } = global;\n return {\n user: selectUser(global, contact.userId),\n phoneCodeList,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'openUserInfo',\n ]),\n)(Contact);\n","import React, {\n FC, useState, useEffect, useRef,\n} from '../../../lib/teact/teact';\n\nimport { ApiPollAnswer, ApiPollResult } from '../../../api/types';\n\nimport buildClassName from '../../../util/buildClassName';\nimport renderText from '../../common/helpers/renderText';\n\nimport './PollOption.scss';\n\ntype OwnProps = {\n answer: ApiPollAnswer;\n voteResults?: ApiPollResult[];\n totalVoters?: number;\n maxVotersCount?: number;\n correctResults: string[];\n shouldAnimate: boolean;\n};\n\nconst PollOption: FC<OwnProps> = ({\n answer,\n voteResults,\n totalVoters,\n maxVotersCount,\n correctResults,\n shouldAnimate,\n}) => {\n const result = voteResults && voteResults.find((r) => r.option === answer.option);\n const correctAnswer = correctResults.length === 0 || correctResults.indexOf(answer.option) !== -1;\n const showIcon = (correctResults.length > 0 && correctAnswer) || (result?.isChosen);\n const answerPercent = result ? getPercentage(result.votersCount, totalVoters || 0) : 0;\n const [finalPercent, setFinalPercent] = useState(shouldAnimate ? 0 : answerPercent);\n // eslint-disable-next-line no-null/no-null\n const lineRef = useRef<HTMLDivElement>(null);\n const lineWidth = result ? getPercentage(result.votersCount, maxVotersCount || 0) : 0;\n const isAnimationDoesNotStart = finalPercent < answerPercent;\n\n useEffect(() => {\n if (shouldAnimate) {\n setFinalPercent(answerPercent);\n }\n }, [shouldAnimate, answerPercent]);\n\n useEffect(() => {\n const lineEl = lineRef.current;\n\n if (lineEl && shouldAnimate) {\n const svgEl = lineEl.firstElementChild;\n\n const style = isAnimationDoesNotStart ? '' : 'stroke-dasharray: 100% 200%; stroke-dashoffset: -44';\n if (!svgEl) {\n lineEl.innerHTML = `\n <svg class=\"poll-line\" xmlns=\"http://www.w3.org/2000/svg\" style=\"${style}\">\n <path d=\"M4.47 5.33v13.6a9 9 0 009 9h13\"/>\n </svg>`;\n } else {\n svgEl.setAttribute('style', style);\n }\n }\n }, [isAnimationDoesNotStart, shouldAnimate]);\n\n if (!voteResults || !result) {\n return undefined;\n }\n\n const lineStyle = `width: ${lineWidth}%; transform:scaleX(${isAnimationDoesNotStart ? 0 : 1})`;\n\n return (\n <div className=\"PollOption\" dir=\"ltr\">\n <div className={`poll-option-share ${answerPercent === '100' ? 'limit-width' : ''}`}>\n {answerPercent}%\n {showIcon && (\n <span className={buildClassName(\n 'poll-option-chosen',\n !correctAnswer && 'wrong',\n shouldAnimate && 'animate',\n )}\n >\n <i className={correctAnswer ? 'icon-check' : 'icon-close'} />\n </span>\n )}\n </div>\n <div className=\"poll-option-right\">\n <div className=\"poll-option-text\" dir=\"auto\">\n {renderText(answer.text)}\n </div>\n <div className={buildClassName('poll-option-answer', showIcon && !correctAnswer && 'wrong')}>\n <div className=\"poll-option-corner\" ref={lineRef} />\n <div\n className=\"poll-option-line\"\n // @ts-ignore\n style={lineStyle}\n />\n </div>\n </div>\n </div>\n );\n};\n\nfunction getPercentage(value: number, total: number) {\n return total > 0 ? ((value / total) * 100).toFixed() : 0;\n}\n\nexport default PollOption;\n","import React, {\n FC,\n useCallback,\n useEffect,\n useState,\n memo,\n useMemo,\n useRef,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../../global/types';\nimport {\n ApiMessage, ApiPoll, ApiUser, ApiPollAnswer,\n} from '../../../api/types';\n\nimport { pick } from '../../../util/iteratees';\nimport renderText from '../../common/helpers/renderText';\nimport { renderTextWithEntities } from '../../common/helpers/renderMessageText';\nimport { formatMediaDuration } from '../../../util/dateFormat';\nimport useLang, { LangFn } from '../../../hooks/useLang';\n\nimport CheckboxGroup from '../../ui/CheckboxGroup';\nimport RadioGroup from '../../ui/RadioGroup';\nimport Avatar from '../../common/Avatar';\nimport Button from '../../ui/Button';\nimport Notification from '../../ui/Notification';\nimport PollOption from './PollOption';\n\nimport './Poll.scss';\n\ntype OwnProps = {\n message: ApiMessage;\n poll: ApiPoll;\n onSendVote: (options: string[]) => void;\n};\n\ntype StateProps = {\n recentVoterIds?: number[];\n usersById: Record<string, ApiUser>;\n serverTimeOffset: number;\n};\n\ntype DispatchProps = Pick<GlobalActions, ('loadMessage' | 'openPollResults')>;\n\nconst SOLUTION_CONTAINER_ID = '#middle-column-portals';\nconst SOLUTION_DURATION = 5000;\nconst NBSP = '\\u00A0';\n\nconst Poll: FC<OwnProps & StateProps & DispatchProps> = ({\n message,\n poll,\n recentVoterIds,\n usersById,\n loadMessage,\n onSendVote,\n openPollResults,\n serverTimeOffset,\n}) => {\n const { id: messageId, chatId } = message;\n const { summary, results } = poll;\n const [isSubmitting, setIsSubmitting] = useState<boolean>(false);\n const [chosenOptions, setChosenOptions] = useState<string[]>([]);\n const [isSolutionShown, setIsSolutionShown] = useState<boolean>(false);\n const [wasSubmitted, setWasSubmitted] = useState<boolean>(false);\n const [closePeriod, setClosePeriod] = useState<number>(\n !summary.closed && summary.closeDate && summary.closeDate > 0\n ? Math.min(summary.closeDate - Math.floor(Date.now() / 1000) + serverTimeOffset, summary.closePeriod!)\n : 0,\n );\n // eslint-disable-next-line no-null/no-null\n const countdownRef = useRef<HTMLDivElement>(null);\n const { results: voteResults, totalVoters } = results;\n const hasVoted = voteResults && voteResults.some((r) => r.isChosen);\n const canVote = !summary.closed && !hasVoted;\n const canViewResult = !canVote && summary.isPublic && Number(results.totalVoters) > 0;\n const isMultiple = canVote && summary.multipleChoice;\n const maxVotersCount = voteResults ? Math.max(...voteResults.map((r) => r.votersCount)) : totalVoters;\n const correctResults = voteResults ? voteResults.reduce((answers: string[], r) => {\n if (r.isCorrect) {\n answers.push(r.option);\n }\n\n return answers;\n }, []) : [];\n const answers = summary.answers.map((a) => ({\n label: a.text,\n value: a.option,\n hidden: Boolean(summary.quiz && summary.closePeriod && closePeriod <= 0),\n }));\n\n useEffect(() => {\n if (\n isSubmitting\n && poll.results.results\n && poll.results.results.some((result) => result.isChosen)\n ) {\n setIsSubmitting(false);\n }\n }, [isSubmitting, poll.results.results]);\n\n useEffect(() => {\n if (closePeriod > 0) {\n setTimeout(() => setClosePeriod(closePeriod - 1), 1000);\n }\n\n const countdownEl = countdownRef.current;\n\n if (countdownEl) {\n const circumference = 6 * 2 * Math.PI;\n const svgEl = countdownEl.lastElementChild;\n const timerEl = countdownEl.firstElementChild;\n if (closePeriod <= 5) {\n countdownEl.classList.add('hurry-up');\n }\n\n if (!svgEl || !timerEl) {\n countdownEl.innerHTML = `\n <span>${formatMediaDuration(closePeriod)}</span>\n <svg width=\"16px\" height=\"16px\">\n <circle cx=\"8\" cy=\"8\" r=\"6\" class=\"poll-countdown-progress\" transform=\"rotate(-90, 8, 8)\"\n stroke-dasharray=\"${circumference} ${circumference}\"\n stroke-dashoffset=\"0\"\n />\n </svg>`;\n } else {\n const strokeDashOffset = ((summary.closePeriod! - closePeriod) / summary.closePeriod!) * circumference;\n timerEl.textContent = formatMediaDuration(closePeriod);\n (svgEl.firstElementChild as SVGElement).setAttribute('stroke-dashoffset', `-${strokeDashOffset}`);\n }\n }\n }, [closePeriod, summary.closePeriod]);\n\n useEffect(() => {\n if (summary.quiz && (closePeriod <= 0 || (hasVoted && !summary.closed))) {\n loadMessage({ chatId, messageId });\n }\n }, [chatId, closePeriod, hasVoted, loadMessage, messageId, summary.closed, summary.quiz]);\n\n // If the client time is not synchronized, the poll must be updated after the closePeriod time has expired.\n useEffect(() => {\n let timer: number | undefined;\n\n if (summary.quiz && !summary.closed && summary.closePeriod && summary.closePeriod > 0) {\n timer = window.setTimeout(() => {\n loadMessage({ chatId, messageId });\n }, summary.closePeriod * 1000);\n }\n\n return () => {\n if (timer) {\n window.clearTimeout(timer);\n }\n };\n }, [canVote, chatId, loadMessage, messageId, summary.closePeriod, summary.closed, summary.quiz]);\n\n const recentVoters = useMemo(() => {\n return recentVoterIds ? recentVoterIds.reduce((result: ApiUser[], id) => {\n const user = usersById[id];\n if (user) {\n result.push(user);\n }\n\n return result;\n }, []) : [];\n }, [usersById, recentVoterIds]);\n\n const handleRadioChange = useCallback(\n (option: string) => {\n setChosenOptions([option]);\n setIsSubmitting(true);\n setWasSubmitted(true);\n onSendVote([option]);\n }, [onSendVote],\n );\n\n const handleCheckboxChange = useCallback(\n (options: string[]) => {\n setChosenOptions(options);\n }, [],\n );\n\n const handleVoteClick = useCallback(\n () => {\n setIsSubmitting(true);\n setWasSubmitted(true);\n onSendVote(chosenOptions);\n }, [onSendVote, chosenOptions],\n );\n\n const handleViewResultsClick = useCallback(\n () => {\n openPollResults({ chatId, messageId });\n }, [chatId, messageId, openPollResults],\n );\n\n const handleSolutionShow = useCallback(() => {\n setIsSolutionShown(true);\n }, []);\n\n const handleSolutionHide = useCallback(() => {\n setIsSolutionShown(false);\n setWasSubmitted(false);\n }, []);\n\n // Show the solution to quiz if the answer was incorrect\n useEffect(() => {\n if (wasSubmitted && hasVoted && summary.quiz && results.results && poll.results.solution) {\n const correctResult = results.results.find((r) => r.isChosen && r.isCorrect);\n if (!correctResult) {\n setIsSolutionShown(true);\n }\n }\n }, [hasVoted, wasSubmitted, results.results, summary.quiz, poll.results.solution]);\n\n const lang = useLang();\n\n function renderResultOption(answer: ApiPollAnswer) {\n return (\n <PollOption\n key={answer.option}\n shouldAnimate={wasSubmitted}\n answer={answer}\n voteResults={voteResults}\n totalVoters={totalVoters}\n maxVotersCount={maxVotersCount}\n correctResults={correctResults}\n />\n );\n }\n\n function renderRecentVoters() {\n return (\n recentVoters.length > 0 && (\n <div className=\"poll-recent-voters\">\n {recentVoters.map((user) => (\n <Avatar\n size=\"micro\"\n user={user}\n />\n ))}\n </div>\n )\n );\n }\n\n function renderSolution() {\n return (\n isSolutionShown && poll.results.solution && (\n <Notification\n message={renderTextWithEntities(poll.results.solution, poll.results.solutionEntities)}\n duration={SOLUTION_DURATION}\n onDismiss={handleSolutionHide}\n containerId={SOLUTION_CONTAINER_ID}\n />\n )\n );\n }\n\n return (\n <div className=\"Poll\" dir={lang.isRtl ? 'auto' : 'ltr'}>\n {renderSolution()}\n <div className=\"poll-question\">{renderText(summary.question, ['emoji', 'br'])}</div>\n <div className=\"poll-type\">\n {lang(getPollTypeString(summary))}\n {renderRecentVoters()}\n {closePeriod > 0 && canVote && <div ref={countdownRef} className=\"poll-countdown\" />}\n {summary.quiz && poll.results.solution && !canVote && (\n <Button\n round\n size=\"tiny\"\n color=\"translucent\"\n className=\"poll-quiz-help\"\n disabled={isSolutionShown}\n onClick={handleSolutionShow}\n ariaLabel=\"Show Solution\"\n >\n <i className=\"icon-lamp\" />\n </Button>\n )}\n </div>\n {canVote && (\n <div className=\"poll-answers\">\n {isMultiple\n ? (\n <CheckboxGroup\n options={answers}\n onChange={handleCheckboxChange}\n disabled={message.isScheduled || isSubmitting}\n loadingOptions={isSubmitting ? chosenOptions : undefined}\n round\n />\n )\n : (\n <RadioGroup\n name={`poll-${messageId}`}\n options={answers}\n onChange={handleRadioChange}\n disabled={message.isScheduled || isSubmitting}\n loadingOption={isSubmitting ? chosenOptions[0] : undefined}\n />\n )}\n </div>\n )}\n {!canVote && (\n <div className=\"poll-results\">\n {summary.answers.map(renderResultOption)}\n </div>\n )}\n {!canViewResult && !isMultiple && (\n <div className=\"poll-voters-count\">{getReadableVotersCount(lang, summary.quiz, results.totalVoters)}</div>\n )}\n {isMultiple && (\n <Button\n isText\n disabled={chosenOptions.length === 0}\n size=\"tiny\"\n onClick={handleVoteClick}\n >\n {lang('PollSubmitVotes')}\n </Button>\n )}\n {canViewResult && (\n <Button\n isText\n size=\"tiny\"\n onClick={handleViewResultsClick}\n >\n {lang('PollViewResults')}\n </Button>\n )}\n </div>\n );\n};\n\nfunction getPollTypeString(summary: ApiPoll['summary']) {\n // When we just created the poll, some properties don't exist.\n if (typeof summary.isPublic === 'undefined') {\n return NBSP;\n }\n\n if (summary.quiz) {\n return summary.isPublic ? 'QuizPoll' : 'AnonymousQuizPoll';\n }\n\n if (summary.closed) {\n return 'FinalResults';\n }\n\n return summary.isPublic ? 'PublicPoll' : 'AnonymousPoll';\n}\n\nfunction getReadableVotersCount(lang: LangFn, isQuiz: true | undefined, count?: number) {\n if (!count) {\n return lang(isQuiz ? 'Chat.Quiz.TotalVotesEmpty' : 'Chat.Poll.TotalVotesResultEmpty');\n }\n\n return lang(isQuiz ? 'Answer' : 'Vote', count, 'i');\n}\n\nexport default memo(withGlobal<OwnProps>(\n (global, { poll }) => {\n const { recentVoterIds } = poll.results;\n const { serverTimeOffset, users: { byId: usersById } } = global;\n if (!recentVoterIds || recentVoterIds.length === 0) {\n return {};\n }\n\n return {\n recentVoterIds,\n usersById,\n serverTimeOffset,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, ['loadMessage', 'openPollResults']),\n)(Poll));\n","import React, { FC, memo, useCallback } from '../../../lib/teact/teact';\n\nimport { ApiMessage } from '../../../api/types';\nimport { ObserveFn } from '../../../hooks/useIntersectionObserver';\nimport { ISettings } from '../../../types';\n\nimport { getMessageWebPage } from '../../../modules/helpers';\nimport { calculateMediaDimensions } from './helpers/mediaDimensions';\nimport renderText from '../../common/helpers/renderText';\nimport trimText from '../../../util/trimText';\nimport buildClassName from '../../../util/buildClassName';\n\nimport SafeLink from '../../common/SafeLink';\nimport Photo from './Photo';\nimport Video from './Video';\n\nimport './WebPage.scss';\n\nconst MAX_TEXT_LENGTH = 170; // symbols\n\ntype OwnProps = {\n message: ApiMessage;\n observeIntersection?: ObserveFn;\n noAvatars?: boolean;\n canAutoLoad?: boolean;\n canAutoPlay?: boolean;\n inPreview?: boolean;\n lastSyncTime?: number;\n isDownloading?: boolean;\n theme: ISettings['theme'];\n onMediaClick?: () => void;\n onCancelMediaTransfer?: () => void;\n};\n\nconst WebPage: FC<OwnProps> = ({\n message,\n observeIntersection,\n noAvatars,\n canAutoLoad,\n canAutoPlay,\n inPreview,\n lastSyncTime,\n isDownloading = false,\n theme,\n onMediaClick,\n onCancelMediaTransfer,\n}) => {\n const webPage = getMessageWebPage(message);\n\n let isSquarePhoto = false;\n if (webPage?.photo && !webPage.video) {\n const { width, height } = calculateMediaDimensions(message);\n isSquarePhoto = width === height;\n }\n\n const handleMediaClick = useCallback(() => {\n onMediaClick!();\n }, [onMediaClick]);\n\n if (!webPage) {\n return undefined;\n }\n\n const {\n siteName,\n url,\n displayUrl,\n title,\n description,\n photo,\n video,\n } = webPage;\n const isMediaInteractive = (photo || video) && onMediaClick && !isSquarePhoto;\n const truncatedDescription = trimText(description, MAX_TEXT_LENGTH);\n\n const className = buildClassName(\n 'WebPage',\n isSquarePhoto && 'with-square-photo',\n !photo && !video && !inPreview && 'without-media',\n video && 'with-video',\n );\n\n return (\n <div\n className={className}\n data-initial={(siteName || displayUrl)[0]}\n dir=\"auto\"\n >\n {photo && !video && (\n <Photo\n message={message}\n observeIntersection={observeIntersection}\n noAvatars={noAvatars}\n canAutoLoad={canAutoLoad}\n size={isSquarePhoto ? 'pictogram' : 'inline'}\n nonInteractive={!isMediaInteractive}\n onClick={isMediaInteractive ? handleMediaClick : undefined}\n onCancelUpload={onCancelMediaTransfer}\n isDownloading={isDownloading}\n theme={theme}\n />\n )}\n <div className=\"WebPage-text\">\n <SafeLink className=\"site-name\" url={url} text={siteName || displayUrl} />\n {!inPreview && title && (\n <p className=\"site-title\">{renderText(title)}</p>\n )}\n {truncatedDescription && (\n <p className=\"site-description\">{renderText(truncatedDescription, ['emoji', 'br'])}</p>\n )}\n </div>\n {!inPreview && video && (\n <Video\n message={message}\n observeIntersection={observeIntersection!}\n noAvatars={noAvatars}\n canAutoLoad={canAutoLoad}\n canAutoPlay={canAutoPlay}\n lastSyncTime={lastSyncTime}\n onClick={isMediaInteractive ? handleMediaClick : undefined}\n onCancelUpload={onCancelMediaTransfer}\n isDownloading={isDownloading}\n />\n )}\n </div>\n );\n};\n\nexport default memo(WebPage);\n","import React, { FC, memo } from '../../../lib/teact/teact';\n\nimport { ApiMessage } from '../../../api/types';\n\nimport { getMessageInvoice } from '../../../modules/helpers';\nimport { formatCurrency } from '../../../util/formatCurrency';\nimport renderText from '../../common/helpers/renderText';\nimport useLang from '../../../hooks/useLang';\n\nimport './Invoice.scss';\n\ntype OwnProps = {\n message: ApiMessage;\n};\n\nconst Invoice: FC<OwnProps> = ({\n message,\n}) => {\n const lang = useLang();\n const invoice = getMessageInvoice(message);\n\n const {\n title,\n text,\n amount,\n currency,\n isTest,\n photoUrl,\n } = invoice!;\n\n return (\n <div\n className=\"Invoice\"\n >\n {title && (\n <p className=\"title\">{renderText(title)}</p>\n )}\n {text && (\n <p>{renderText(text, ['emoji', 'br'])}</p>\n )}\n <div className={`description ${photoUrl ? 'has-image' : ''}`}>\n {photoUrl && (\n <img\n className=\"invoice-image\"\n src={photoUrl}\n alt=\"\"\n />\n )}\n <p className=\"description-text\">\n {formatCurrency(amount, currency, lang.code)}\n {isTest && <span>{lang('PaymentTestInvoice')}</span>}\n </p>\n </div>\n </div>\n );\n};\n\nexport default memo(Invoice);\n","import { MouseEvent as ReactMouseEvent } from 'react';\nimport React, {\n FC,\n useCallback,\n useMemo,\n memo,\n} from '../../../../lib/teact/teact';\nimport { withGlobal } from '../../../../lib/teact/teactn';\n\nimport { OwnProps as PhotoProps } from '../Photo';\nimport { OwnProps as VideoProps } from '../Video';\n\nimport buildClassName from '../../../../util/buildClassName';\nimport { GlobalActions } from '../../../../global/types';\nimport {\n selectIsInSelectMode,\n selectIsMessageSelected,\n} from '../../../../modules/selectors';\n\nimport { pick } from '../../../../util/iteratees';\n\ntype OwnProps = PhotoProps & VideoProps;\n\ntype StateProps = {\n isInSelectMode?: boolean;\n isSelected?: boolean;\n};\n\ntype DispatchProps = Pick<GlobalActions, ('toggleMessageSelection')>;\n\nexport default function withSelectControl(WrappedComponent: FC) {\n const ComponentWithSelectControl: FC<OwnProps & StateProps & DispatchProps> = (props) => {\n const {\n isInSelectMode,\n isSelected,\n message,\n toggleMessageSelection,\n dimensions,\n } = props;\n\n const handleMessageSelect = useCallback((e: ReactMouseEvent<HTMLDivElement, MouseEvent>) => {\n e.stopPropagation();\n toggleMessageSelection({ messageId: message.id, withShift: e?.shiftKey });\n }, [toggleMessageSelection, message]);\n\n const newProps = useMemo(() => {\n return {\n ...props,\n isInSelectMode,\n isSelected,\n dimensions: {\n ...props.dimensions,\n x: 0,\n y: 0,\n },\n onClick: isInSelectMode ? undefined : props.onClick,\n };\n }, [props, isInSelectMode, isSelected]);\n\n return (\n <div\n className={\n buildClassName(\n 'album-item-select-wrapper',\n isSelected && 'is-selected',\n )\n }\n // @ts-ignore\n style={dimensions ? `left: ${dimensions.x}px; top: ${dimensions.y}px;` : ''}\n onClick={isInSelectMode ? handleMessageSelect : undefined}\n >\n {isInSelectMode && (\n <div className=\"message-select-control\">\n {isSelected && (\n <i className=\"icon-select\" />\n )}\n </div>\n )}\n {/* eslint-disable-next-line react/jsx-props-no-spreading */}\n <WrappedComponent {...newProps} />\n </div>\n );\n };\n\n return memo(withGlobal<OwnProps>(\n (global, ownProps) => {\n const { message } = ownProps;\n return {\n isInSelectMode: selectIsInSelectMode(global),\n isSelected: selectIsMessageSelected(global, message.id),\n };\n },\n (setGlobal, actions) => pick(actions, [\n 'toggleMessageSelection',\n ]),\n )(ComponentWithSelectControl));\n}\n","import React, { FC, useCallback } from '../../../lib/teact/teact';\n\nimport { GlobalActions, GlobalState } from '../../../global/types';\nimport { ApiMessage } from '../../../api/types';\nimport { IAlbum, ISettings } from '../../../types';\nimport { AlbumRectPart, IAlbumLayout } from './helpers/calculateAlbumLayout';\n\nimport { getMessageContent } from '../../../modules/helpers';\nimport { withGlobal } from '../../../lib/teact/teactn';\nimport { pick } from '../../../util/iteratees';\nimport withSelectControl from './hocs/withSelectControl';\nimport { ObserveFn } from '../../../hooks/useIntersectionObserver';\nimport { selectActiveDownloadIds, selectTheme } from '../../../modules/selectors';\n\nimport Photo from './Photo';\nimport Video from './Video';\n\nimport './Album.scss';\n\nconst PhotoWithSelect = withSelectControl(Photo);\nconst VideoWithSelect = withSelectControl(Video);\n\ntype OwnProps = {\n album: IAlbum;\n observeIntersection: ObserveFn;\n canAutoLoad?: boolean;\n canAutoPlay?: boolean;\n hasCustomAppendix?: boolean;\n lastSyncTime?: number;\n isOwn: boolean;\n albumLayout: IAlbumLayout;\n onMediaClick: (messageId: number) => void;\n};\n\ntype StateProps = {\n theme: ISettings['theme'];\n uploadsById: GlobalState['fileUploads']['byMessageLocalId'];\n activeDownloadIds: number[];\n};\n\ntype DispatchProps = Pick<GlobalActions, 'cancelSendingMessage'>;\n\nconst Album: FC<OwnProps & StateProps & DispatchProps> = ({\n album,\n observeIntersection,\n canAutoLoad,\n canAutoPlay,\n hasCustomAppendix,\n lastSyncTime,\n isOwn,\n albumLayout,\n onMediaClick,\n uploadsById,\n activeDownloadIds,\n theme,\n cancelSendingMessage,\n}) => {\n const mediaCount = album.messages.length;\n\n const handleCancelUpload = useCallback((message: ApiMessage) => {\n cancelSendingMessage({ chatId: message.chatId, messageId: message.id });\n }, [cancelSendingMessage]);\n\n function renderAlbumMessage(message: ApiMessage, index: number) {\n const { photo, video } = getMessageContent(message);\n const fileUpload = uploadsById[message.previousLocalId || message.id];\n const uploadProgress = fileUpload?.progress;\n const { dimensions, sides } = albumLayout.layout[index];\n\n if (photo) {\n const shouldAffectAppendix = hasCustomAppendix && (\n // eslint-disable-next-line no-bitwise\n (isOwn ? index === mediaCount - 1 : Boolean(sides & AlbumRectPart.Left && sides & AlbumRectPart.Bottom))\n );\n\n return (\n <PhotoWithSelect\n id={`album-media-${message.id}`}\n message={message}\n observeIntersection={observeIntersection}\n canAutoLoad={canAutoLoad}\n shouldAffectAppendix={shouldAffectAppendix}\n uploadProgress={uploadProgress}\n dimensions={dimensions}\n onClick={onMediaClick}\n onCancelUpload={handleCancelUpload}\n isDownloading={activeDownloadIds.includes(message.id)}\n theme={theme}\n />\n );\n } else if (video) {\n return (\n <VideoWithSelect\n id={`album-media-${message.id}`}\n message={message}\n observeIntersection={observeIntersection}\n canAutoLoad={canAutoLoad}\n canAutoPlay={canAutoPlay}\n uploadProgress={uploadProgress}\n lastSyncTime={lastSyncTime}\n dimensions={dimensions}\n onClick={onMediaClick}\n onCancelUpload={handleCancelUpload}\n isDownloading={activeDownloadIds.includes(message.id)}\n theme={theme}\n />\n );\n }\n\n return undefined;\n }\n\n const { width: containerWidth, height: containerHeight } = albumLayout.containerStyle;\n\n return (\n <div\n className=\"Album\"\n // @ts-ignore\n style={`width: ${containerWidth}px; height: ${containerHeight}px;`}\n >\n {album.messages.map(renderAlbumMessage)}\n </div>\n );\n};\n\nexport default withGlobal<OwnProps>(\n (global, { album }): StateProps => {\n const { chatId } = album.mainMessage;\n const theme = selectTheme(global);\n const activeDownloadIds = selectActiveDownloadIds(global, chatId);\n return {\n theme,\n uploadsById: global.fileUploads.byMessageLocalId,\n activeDownloadIds,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'cancelSendingMessage',\n ]),\n)(Album);\n","import React, {\n FC,\n useCallback,\n useEffect,\n useRef,\n useState,\n} from '../../../lib/teact/teact';\nimport { getDispatch } from '../../../lib/teact/teactn';\n\nimport { ApiMediaFormat, ApiMessage } from '../../../api/types';\n\nimport { ROUND_VIDEO_DIMENSIONS_PX } from '../../common/helpers/mediaDimensions';\nimport { getMessageMediaFormat, getMessageMediaHash } from '../../../modules/helpers';\nimport { formatMediaDuration } from '../../../util/dateFormat';\nimport buildClassName from '../../../util/buildClassName';\nimport { stopCurrentAudio } from '../../../util/audioPlayer';\nimport safePlay from '../../../util/safePlay';\nimport { fastRaf } from '../../../util/schedulers';\nimport { ObserveFn, useIsIntersecting } from '../../../hooks/useIntersectionObserver';\nimport useMediaWithLoadProgress from '../../../hooks/useMediaWithLoadProgress';\nimport useShowTransition from '../../../hooks/useShowTransition';\nimport useMediaTransition from '../../../hooks/useMediaTransition';\nimport usePrevious from '../../../hooks/usePrevious';\nimport useBuffering from '../../../hooks/useBuffering';\nimport useHeavyAnimationCheckForVideo from '../../../hooks/useHeavyAnimationCheckForVideo';\nimport useVideoCleanup from '../../../hooks/useVideoCleanup';\nimport usePauseOnInactive from './hooks/usePauseOnInactive';\nimport useBlurredMediaThumbRef from './hooks/useBlurredMediaThumbRef';\n\nimport ProgressSpinner from '../../ui/ProgressSpinner';\n\nimport './RoundVideo.scss';\n\ntype OwnProps = {\n message: ApiMessage;\n observeIntersection: ObserveFn;\n canAutoLoad?: boolean;\n lastSyncTime?: number;\n isDownloading?: boolean;\n};\n\nlet currentOnRelease: NoneToVoidFunction;\n\nfunction createCapture(onRelease: NoneToVoidFunction) {\n return () => {\n if (currentOnRelease) {\n currentOnRelease();\n }\n\n currentOnRelease = onRelease;\n };\n}\n\nconst RoundVideo: FC<OwnProps> = ({\n message,\n observeIntersection,\n canAutoLoad,\n lastSyncTime,\n isDownloading,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const ref = useRef<HTMLDivElement>(null);\n // eslint-disable-next-line no-null/no-null\n const playingProgressRef = useRef<HTMLDivElement>(null);\n // eslint-disable-next-line no-null/no-null\n const playerRef = useRef<HTMLVideoElement>(null);\n\n const video = message.content.video!;\n\n const isIntersecting = useIsIntersecting(ref, observeIntersection);\n\n const [isLoadAllowed, setIsLoadAllowed] = useState(canAutoLoad);\n const shouldLoad = Boolean(isLoadAllowed && isIntersecting && lastSyncTime);\n const { mediaData, loadProgress } = useMediaWithLoadProgress(\n getMessageMediaHash(message, 'inline'),\n !shouldLoad,\n getMessageMediaFormat(message, 'inline'),\n lastSyncTime,\n );\n\n const { loadProgress: downloadProgress } = useMediaWithLoadProgress(\n getMessageMediaHash(message, 'download'),\n !isDownloading,\n ApiMediaFormat.BlobUrl,\n lastSyncTime,\n );\n const thumbRef = useBlurredMediaThumbRef(message, mediaData);\n\n const { isBuffered, bufferingHandlers } = useBuffering();\n const isTransferring = (isLoadAllowed && !isBuffered) || isDownloading;\n const wasLoadDisabled = usePrevious(isLoadAllowed) === false;\n\n const transitionClassNames = useMediaTransition(mediaData);\n const {\n shouldRender: shouldSpinnerRender,\n transitionClassNames: spinnerClassNames,\n } = useShowTransition(isTransferring || !isBuffered, undefined, wasLoadDisabled);\n\n const [isActivated, setIsActivated] = useState<boolean>(false);\n const [progress, setProgress] = useState<number>(0);\n\n useEffect(() => {\n if (!isActivated) {\n return;\n }\n\n const svgCenter = ROUND_VIDEO_DIMENSIONS_PX / 2;\n const svgMargin = 6;\n const circumference = (svgCenter - svgMargin) * 2 * Math.PI;\n const strokeDashOffset = circumference - progress * circumference;\n\n const playerEl = playerRef.current!;\n const playingProgressEl = playingProgressRef.current!;\n const svgEl = playingProgressEl.firstElementChild;\n\n if (!svgEl) {\n playingProgressEl.innerHTML = `\n <svg width=\"${ROUND_VIDEO_DIMENSIONS_PX}px\" height=\"${ROUND_VIDEO_DIMENSIONS_PX}px\">\n <circle cx=\"${svgCenter}\" cy=\"${svgCenter}\" r=\"${svgCenter - svgMargin}\" class=\"progress-circle\"\n transform=\"rotate(-90, ${svgCenter}, ${svgCenter})\"\n stroke-dasharray=\"${circumference} ${circumference}\"\n stroke-dashoffset=\"${circumference}\"\n />\n </svg>`;\n } else {\n (svgEl.firstElementChild as SVGElement).setAttribute('stroke-dashoffset', strokeDashOffset.toString());\n }\n\n setProgress(playerEl.currentTime / playerEl.duration);\n }, [isActivated, progress]);\n\n const shouldPlay = Boolean(mediaData && isIntersecting);\n\n const stopPlaying = () => {\n setIsActivated(false);\n setProgress(0);\n safePlay(playerRef.current!);\n\n fastRaf(() => {\n playingProgressRef.current!.innerHTML = '';\n });\n };\n\n const capturePlaying = createCapture(stopPlaying);\n\n useEffect(() => {\n if (!playerRef.current) {\n return;\n }\n\n if (shouldPlay) {\n safePlay(playerRef.current);\n } else {\n playerRef.current.pause();\n }\n }, [shouldPlay]);\n\n useHeavyAnimationCheckForVideo(playerRef, shouldPlay);\n usePauseOnInactive(playerRef, Boolean(mediaData));\n useVideoCleanup(playerRef, [mediaData]);\n\n const handleClick = useCallback(() => {\n if (!mediaData) {\n setIsLoadAllowed((isAllowed) => !isAllowed);\n\n return;\n }\n\n if (isDownloading) {\n getDispatch().cancelMessageMediaDownload({ message });\n return;\n }\n\n const playerEl = playerRef.current!;\n if (isActivated) {\n if (playerEl.paused) {\n safePlay(playerEl);\n stopCurrentAudio();\n } else {\n playerEl.pause();\n }\n } else {\n capturePlaying();\n // Pause is a workaround for iOS Safari – otherwise it stops video after several frames\n playerEl.pause();\n playerEl.currentTime = 0;\n safePlay(playerEl);\n stopCurrentAudio();\n\n setIsActivated(true);\n }\n }, [capturePlaying, isActivated, isDownloading, mediaData, message]);\n\n const handleTimeUpdate = useCallback((e: React.UIEvent<HTMLVideoElement>) => {\n const playerEl = e.currentTarget;\n\n setProgress(playerEl.currentTime / playerEl.duration);\n }, []);\n\n const videoClassName = buildClassName('full-media', transitionClassNames);\n\n return (\n <div\n ref={ref}\n className=\"RoundVideo media-inner\"\n onClick={handleClick}\n >\n <div className=\"thumbnail-wrapper\">\n <canvas\n ref={thumbRef}\n className=\"thumbnail\"\n // @ts-ignore teact feature\n style={`width: ${ROUND_VIDEO_DIMENSIONS_PX}px; height: ${ROUND_VIDEO_DIMENSIONS_PX}px`}\n />\n </div>\n {mediaData && (\n <div className=\"video-wrapper\">\n {/* eslint-disable-next-line jsx-a11y/media-has-caption */}\n <video\n ref={playerRef}\n className={videoClassName}\n width={ROUND_VIDEO_DIMENSIONS_PX}\n height={ROUND_VIDEO_DIMENSIONS_PX}\n autoPlay\n muted={!isActivated}\n loop={!isActivated}\n playsInline\n onEnded={isActivated ? stopPlaying : undefined}\n // eslint-disable-next-line react/jsx-props-no-spreading\n {...bufferingHandlers}\n onTimeUpdate={isActivated ? handleTimeUpdate : undefined}\n >\n <source src={mediaData} />\n </video>\n </div>\n )}\n <div className=\"progress\" ref={playingProgressRef} />\n {shouldSpinnerRender && (\n <div className={`media-loading ${spinnerClassNames}`}>\n <ProgressSpinner progress={isDownloading ? downloadProgress : loadProgress} />\n </div>\n )}\n {!mediaData && !isLoadAllowed && (\n <i className=\"icon-download\" />\n )}\n <div className=\"message-media-duration\">\n {isActivated ? formatMediaDuration(playerRef.current!.currentTime) : formatMediaDuration(video.duration)}\n {(!isActivated || playerRef.current!.paused) && <i className=\"icon-muted\" />}\n </div>\n </div>\n );\n};\n\nexport default RoundVideo;\n","import React, { FC } from '../../../lib/teact/teact';\n\nimport { ApiKeyboardButton, ApiMessage } from '../../../api/types';\n\nimport { RE_TME_LINK } from '../../../config';\nimport renderText from '../../common/helpers/renderText';\nimport useLang from '../../../hooks/useLang';\n\nimport Button from '../../ui/Button';\n\nimport './InlineButtons.scss';\n\ntype OwnProps = {\n message: ApiMessage;\n onClick: ({ button }: { button: ApiKeyboardButton }) => void;\n};\n\nconst InlineButtons: FC<OwnProps> = ({ message, onClick }) => {\n const lang = useLang();\n\n return (\n <div className=\"InlineButtons\">\n {message.inlineButtons!.map((row) => (\n <div className=\"row\">\n {row.map((button) => (\n <Button\n size=\"tiny\"\n ripple\n disabled={button.type === 'NOT_SUPPORTED'}\n onClick={() => onClick({ button })}\n >\n {renderText(lang(button.text))}\n {button.type === 'buy' && <i className=\"icon-card\" />}\n {button.type === 'url' && !button.value!.match(RE_TME_LINK) && <i className=\"icon-arrow-right\" />}\n </Button>\n ))}\n </div>\n ))}\n </div>\n );\n};\n\nexport default InlineButtons;\n","import React, {\n FC, memo, useCallback,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport {\n ApiChat, ApiMessage, ApiThreadInfo, ApiUser,\n} from '../../../api/types';\nimport { GlobalActions } from '../../../global/types';\n\nimport { pick } from '../../../util/iteratees';\nimport { isUserId } from '../../../modules/helpers';\nimport { formatIntegerCompact } from '../../../util/textFormat';\nimport buildClassName from '../../../util/buildClassName';\nimport { selectThreadInfo } from '../../../modules/selectors';\nimport useLang from '../../../hooks/useLang';\n\nimport Avatar from '../../common/Avatar';\n\nimport './CommentButton.scss';\n\ntype OwnProps = {\n message: ApiMessage;\n disabled?: boolean;\n};\n\ntype StateProps = {\n threadInfo: ApiThreadInfo;\n usersById?: Record<string, ApiUser>;\n chatsById?: Record<string, ApiChat>;\n};\n\ntype DispatchProps = Pick<GlobalActions, 'openChat'>;\n\nconst CommentButton: FC<OwnProps & StateProps & DispatchProps> = ({\n disabled,\n threadInfo,\n usersById,\n chatsById,\n openChat,\n}) => {\n const lang = useLang();\n const {\n threadId, chatId, messagesCount, lastMessageId, lastReadInboxMessageId, recentReplierIds,\n } = threadInfo;\n\n const handleClick = useCallback(() => {\n openChat({ id: chatId, threadId });\n }, [openChat, chatId, threadId]);\n\n if (messagesCount === undefined) {\n return undefined;\n }\n\n const recentRepliers = recentReplierIds && recentReplierIds.map((peerId) => {\n return isUserId(peerId) ? usersById![peerId] : chatsById![peerId];\n }).filter(Boolean);\n\n function renderRecentRepliers() {\n return (\n recentRepliers && recentRepliers.length > 0 && (\n <div className=\"recent-repliers\" dir={lang.isRtl ? 'rtl' : 'ltr'}>\n {recentRepliers.map((user) => (\n <Avatar\n key={user.id}\n size=\"small\"\n user={isUserId(user.id) ? user as ApiUser : undefined}\n chat={!isUserId(user.id) ? user as ApiChat : undefined}\n />\n ))}\n </div>\n )\n );\n }\n\n const hasUnread = Boolean(lastReadInboxMessageId && lastMessageId && lastReadInboxMessageId < lastMessageId);\n\n return (\n <div\n data-cnt={formatIntegerCompact(messagesCount)}\n className={buildClassName('CommentButton', hasUnread && 'has-unread', disabled && 'disabled')}\n dir={lang.isRtl ? 'rtl' : 'ltr'}\n onClick={handleClick}\n >\n <i className=\"icon-comments-sticker\" />\n {(!recentRepliers || recentRepliers.length === 0) && <i className=\"icon-comments\" />}\n {renderRecentRepliers()}\n <div className=\"label\" dir=\"auto\">\n {messagesCount ? lang('Comments', messagesCount, 'i') : lang('LeaveAComment')}\n </div>\n <i className=\"icon-next\" />\n </div>\n );\n};\n\nexport default memo(withGlobal<OwnProps>(\n (global, { message }) => {\n const { threadId, chatId } = message.threadInfo!;\n\n const threadInfo = selectThreadInfo(global, chatId, threadId) || message.threadInfo!;\n const { byId: usersById } = global.users;\n const { byId: chatsById } = global.chats;\n\n return {\n threadInfo,\n usersById,\n chatsById,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'openChat',\n ]),\n)(CommentButton));\n","import React, {\n FC,\n memo,\n useCallback,\n useEffect,\n useLayoutEffect,\n useMemo,\n useRef,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalActions, MessageListType } from '../../../global/types';\nimport {\n ApiMessage,\n ApiMessageOutgoingStatus,\n ApiUser,\n ApiChat,\n ApiSticker,\n} from '../../../api/types';\nimport {\n AudioOrigin, FocusDirection, IAlbum, ISettings,\n} from '../../../types';\n\nimport { IS_ANDROID, IS_TOUCH_ENV } from '../../../util/environment';\nimport { pick } from '../../../util/iteratees';\nimport {\n selectChat,\n selectChatMessage,\n selectUploadProgress,\n selectIsChatWithSelf,\n selectOutgoingStatus,\n selectUser,\n selectIsMessageFocused,\n selectCurrentTextSearch,\n selectAnimatedEmoji,\n selectIsInSelectMode,\n selectIsMessageSelected,\n selectIsDocumentGroupSelected,\n selectSender,\n selectForwardedSender,\n selectThreadTopMessageId,\n selectCanAutoLoadMedia,\n selectCanAutoPlayMedia,\n selectShouldLoopStickers,\n selectTheme,\n selectAllowedMessageActions,\n selectIsDownloading,\n} from '../../../modules/selectors';\nimport {\n getMessageContent,\n isOwnMessage,\n isReplyMessage,\n isAnonymousOwnMessage,\n isMessageLocal,\n isUserId,\n isChatWithRepliesBot,\n getMessageCustomShape,\n isChatChannel,\n getMessageSingleEmoji,\n getSenderTitle,\n getUserColorKey,\n} from '../../../modules/helpers';\nimport buildClassName from '../../../util/buildClassName';\nimport useEnsureMessage from '../../../hooks/useEnsureMessage';\nimport useContextMenuHandlers from '../../../hooks/useContextMenuHandlers';\nimport { renderMessageText } from '../../common/helpers/renderMessageText';\nimport { ROUND_VIDEO_DIMENSIONS_PX } from '../../common/helpers/mediaDimensions';\nimport { buildContentClassName, isEmojiOnlyMessage } from './helpers/buildContentClassName';\nimport { getMinMediaWidth, calculateMediaDimensions } from './helpers/mediaDimensions';\nimport { calculateAlbumLayout } from './helpers/calculateAlbumLayout';\nimport renderText from '../../common/helpers/renderText';\nimport calculateAuthorWidth from './helpers/calculateAuthorWidth';\nimport { ObserveFn, useOnIntersect } from '../../../hooks/useIntersectionObserver';\nimport useLang from '../../../hooks/useLang';\nimport useShowTransition from '../../../hooks/useShowTransition';\nimport useFlag from '../../../hooks/useFlag';\nimport useFocusMessage from './hooks/useFocusMessage';\nimport useOuterHandlers from './hooks/useOuterHandlers';\nimport useInnerHandlers from './hooks/useInnerHandlers';\n\nimport Button from '../../ui/Button';\nimport Avatar from '../../common/Avatar';\nimport EmbeddedMessage from '../../common/EmbeddedMessage';\nimport Document from '../../common/Document';\nimport Audio from '../../common/Audio';\nimport MessageMeta from './MessageMeta';\nimport ContextMenuContainer from './ContextMenuContainer.async';\nimport Sticker from './Sticker';\nimport AnimatedEmoji from '../../common/AnimatedEmoji';\nimport Photo from './Photo';\nimport Video from './Video';\nimport Contact from './Contact';\nimport Poll from './Poll';\nimport WebPage from './WebPage';\nimport Invoice from './Invoice';\nimport Album from './Album';\nimport RoundVideo from './RoundVideo';\nimport InlineButtons from './InlineButtons';\nimport CommentButton from './CommentButton';\n\nimport './Message.scss';\n\ntype MessagePositionProperties = {\n isFirstInGroup: boolean;\n isLastInGroup: boolean;\n isFirstInDocumentGroup: boolean;\n isLastInDocumentGroup: boolean;\n isLastInList: boolean;\n};\n\ntype OwnProps =\n {\n message: ApiMessage;\n observeIntersectionForBottom: ObserveFn;\n observeIntersectionForMedia: ObserveFn;\n observeIntersectionForAnimatedStickers: ObserveFn;\n album?: IAlbum;\n noAvatars?: boolean;\n withAvatar?: boolean;\n withSenderName?: boolean;\n threadId: number;\n messageListType: MessageListType;\n noComments: boolean;\n appearanceOrder: number;\n }\n & MessagePositionProperties;\n\ntype StateProps = {\n theme: ISettings['theme'];\n forceSenderName?: boolean;\n chatUsername?: string;\n sender?: ApiUser | ApiChat;\n originSender?: ApiUser | ApiChat;\n botSender?: ApiUser;\n isThreadTop?: boolean;\n shouldHideReply?: boolean;\n replyMessage?: ApiMessage;\n replyMessageSender?: ApiUser | ApiChat;\n outgoingStatus?: ApiMessageOutgoingStatus;\n uploadProgress?: number;\n isFocused?: boolean;\n focusDirection?: FocusDirection;\n noFocusHighlight?: boolean;\n isResizingContainer?: boolean;\n isForwarding?: boolean;\n isChatWithSelf?: boolean;\n isRepliesChat?: boolean;\n isChannel?: boolean;\n canReply?: boolean;\n lastSyncTime?: number;\n highlight?: string;\n isSingleEmoji?: boolean;\n animatedEmoji?: ApiSticker;\n isInSelectMode?: boolean;\n isSelected?: boolean;\n isGroupSelected?: boolean;\n isDownloading: boolean;\n threadId?: number;\n isPinnedList?: boolean;\n canAutoLoadMedia?: boolean;\n canAutoPlayMedia?: boolean;\n shouldLoopStickers?: boolean;\n autoLoadFileMaxSizeMb: number;\n};\n\ntype DispatchProps = Pick<GlobalActions, 'toggleMessageSelection' | 'clickInlineButton' | 'disableContextMenuHint'>;\n\nconst NBSP = '\\u00A0';\nconst GROUP_MESSAGE_HOVER_ATTRIBUTE = 'data-is-document-group-hover';\n// eslint-disable-next-line max-len\nconst APPENDIX_OWN = '<svg width=\"9\" height=\"20\" xmlns=\"http://www.w3.org/2000/svg\"><defs><filter x=\"-50%\" y=\"-14.7%\" width=\"200%\" height=\"141.2%\" filterUnits=\"objectBoundingBox\" id=\"a\"><feOffset dy=\"1\" in=\"SourceAlpha\" result=\"shadowOffsetOuter1\"/><feGaussianBlur stdDeviation=\"1\" in=\"shadowOffsetOuter1\" result=\"shadowBlurOuter1\"/><feColorMatrix values=\"0 0 0 0 0.0621962482 0 0 0 0 0.138574144 0 0 0 0 0.185037364 0 0 0 0.15 0\" in=\"shadowBlurOuter1\"/></filter></defs><g fill=\"none\" fill-rule=\"evenodd\"><path d=\"M6 17H0V0c.193 2.84.876 5.767 2.05 8.782.904 2.325 2.446 4.485 4.625 6.48A1 1 0 016 17z\" fill=\"#000\" filter=\"url(#a)\"/><path d=\"M6 17H0V0c.193 2.84.876 5.767 2.05 8.782.904 2.325 2.446 4.485 4.625 6.48A1 1 0 016 17z\" fill=\"#EEFFDE\" class=\"corner\"/></g></svg>';\n// eslint-disable-next-line max-len\nconst APPENDIX_NOT_OWN = '<svg width=\"9\" height=\"20\" xmlns=\"http://www.w3.org/2000/svg\"><defs><filter x=\"-50%\" y=\"-14.7%\" width=\"200%\" height=\"141.2%\" filterUnits=\"objectBoundingBox\" id=\"a\"><feOffset dy=\"1\" in=\"SourceAlpha\" result=\"shadowOffsetOuter1\"/><feGaussianBlur stdDeviation=\"1\" in=\"shadowOffsetOuter1\" result=\"shadowBlurOuter1\"/><feColorMatrix values=\"0 0 0 0 0.0621962482 0 0 0 0 0.138574144 0 0 0 0 0.185037364 0 0 0 0.15 0\" in=\"shadowBlurOuter1\"/></filter></defs><g fill=\"none\" fill-rule=\"evenodd\"><path d=\"M3 17h6V0c-.193 2.84-.876 5.767-2.05 8.782-.904 2.325-2.446 4.485-4.625 6.48A1 1 0 003 17z\" fill=\"#000\" filter=\"url(#a)\"/><path d=\"M3 17h6V0c-.193 2.84-.876 5.767-2.05 8.782-.904 2.325-2.446 4.485-4.625 6.48A1 1 0 003 17z\" fill=\"#FFF\" class=\"corner\"/></g></svg>';\nconst APPEARANCE_DELAY = 10;\nconst NO_MEDIA_CORNERS_THRESHOLD = 18;\n\nconst Message: FC<OwnProps & StateProps & DispatchProps> = ({\n message,\n chatUsername,\n observeIntersectionForBottom,\n observeIntersectionForMedia,\n observeIntersectionForAnimatedStickers,\n album,\n noAvatars,\n withAvatar,\n withSenderName,\n noComments,\n appearanceOrder,\n isFirstInGroup,\n isLastInGroup,\n isFirstInDocumentGroup,\n isLastInDocumentGroup,\n isLastInList,\n theme,\n forceSenderName,\n sender,\n originSender,\n botSender,\n isThreadTop,\n shouldHideReply,\n replyMessage,\n replyMessageSender,\n outgoingStatus,\n uploadProgress,\n isFocused,\n focusDirection,\n noFocusHighlight,\n isResizingContainer,\n isForwarding,\n isChatWithSelf,\n isRepliesChat,\n isChannel,\n canReply,\n lastSyncTime,\n highlight,\n animatedEmoji,\n isInSelectMode,\n isSelected,\n isGroupSelected,\n threadId,\n messageListType,\n isPinnedList,\n isDownloading,\n canAutoLoadMedia,\n canAutoPlayMedia,\n shouldLoopStickers,\n autoLoadFileMaxSizeMb,\n toggleMessageSelection,\n clickInlineButton,\n disableContextMenuHint,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const ref = useRef<HTMLDivElement>(null);\n // eslint-disable-next-line no-null/no-null\n const bottomMarkerRef = useRef<HTMLDivElement>(null);\n // eslint-disable-next-line no-null/no-null\n const appendixRef = useRef<HTMLDivElement>(null);\n const lang = useLang();\n\n useOnIntersect(bottomMarkerRef, observeIntersectionForBottom);\n\n const {\n isContextMenuOpen, contextMenuPosition,\n handleBeforeContextMenu, handleContextMenu: onContextMenu,\n handleContextMenuClose, handleContextMenuHide,\n } = useContextMenuHandlers(ref, IS_TOUCH_ENV && isInSelectMode, true, IS_ANDROID);\n\n useEffect(() => {\n if (isContextMenuOpen) {\n disableContextMenuHint();\n }\n }, [isContextMenuOpen, disableContextMenuHint]);\n\n const noAppearanceAnimation = appearanceOrder <= 0;\n const [isShown, markShown] = useFlag(noAppearanceAnimation);\n useEffect(() => {\n if (noAppearanceAnimation) {\n return;\n }\n\n setTimeout(markShown, appearanceOrder * APPEARANCE_DELAY);\n }, [appearanceOrder, markShown, noAppearanceAnimation]);\n const { transitionClassNames } = useShowTransition(isShown, undefined, noAppearanceAnimation, false);\n\n const { id: messageId, chatId, threadInfo } = message;\n\n const isLocal = isMessageLocal(message);\n const isOwn = isOwnMessage(message);\n const isScheduled = messageListType === 'scheduled' || message.isScheduled;\n const hasReply = isReplyMessage(message) && !shouldHideReply;\n const hasThread = Boolean(threadInfo) && messageListType === 'thread';\n const { forwardInfo, viaBotId } = message;\n const asForwarded = (\n forwardInfo && (!isChatWithSelf || isScheduled) && !isRepliesChat && !forwardInfo.isLinkedChannelPost\n );\n const isInDocumentGroup = Boolean(message.groupedId) && !message.isInAlbum;\n const isAlbum = Boolean(album) && album!.messages.length > 1;\n const {\n text, photo, video, audio, voice, document, sticker, contact, poll, webPage, invoice,\n } = getMessageContent(message);\n const customShape = getMessageCustomShape(message);\n const textParts = renderMessageText(message, highlight, isEmojiOnlyMessage(customShape));\n const isContextMenuShown = contextMenuPosition !== undefined;\n const signature = (\n (isChannel && message.adminTitle) || (forwardInfo && !asForwarded && forwardInfo.adminTitle) || undefined\n );\n const metaSafeAuthorWidth = useMemo(() => {\n return signature ? calculateAuthorWidth(signature) : undefined;\n }, [signature]);\n const canShowActionButton = (\n !(isContextMenuShown || isInSelectMode || isForwarding)\n && (!isInDocumentGroup || isLastInDocumentGroup)\n );\n const canForward = isChannel && !isScheduled;\n const canFocus = Boolean(isPinnedList\n || (forwardInfo\n && (forwardInfo.isChannelPost || (isChatWithSelf && !isOwn) || isRepliesChat)\n && forwardInfo.fromMessageId\n ));\n const avatarPeer = forwardInfo && (isChatWithSelf || isRepliesChat || !sender) ? originSender : sender;\n const senderPeer = forwardInfo ? originSender : sender;\n\n const selectMessage = useCallback((e?: React.MouseEvent<HTMLDivElement, MouseEvent>, groupedId?: string) => {\n toggleMessageSelection({\n messageId,\n groupedId,\n ...(e?.shiftKey && { withShift: true }),\n ...(isAlbum && { childMessageIds: album!.messages.map(({ id }) => id) }),\n });\n }, [toggleMessageSelection, messageId, isAlbum, album]);\n\n const {\n handleMouseDown,\n handleClick,\n handleContextMenu,\n handleDoubleClick,\n handleContentDoubleClick,\n isSwiped,\n } = useOuterHandlers(\n selectMessage,\n ref,\n messageId,\n isAlbum,\n Boolean(isInSelectMode),\n Boolean(canReply),\n onContextMenu,\n handleBeforeContextMenu,\n );\n\n const {\n handleAvatarClick,\n handleSenderClick,\n handleViaBotClick,\n handleReplyClick,\n handleMediaClick,\n handleAudioPlay,\n handleAlbumMediaClick,\n handleMetaClick,\n handleReadMedia,\n handleCancelUpload,\n handleVoteSend,\n handleGroupForward,\n handleForward,\n handleFocus,\n handleFocusForwarded,\n handleDocumentGroupSelectAll,\n } = useInnerHandlers(\n lang,\n selectMessage,\n message,\n chatId,\n threadId,\n isInDocumentGroup,\n Boolean(isScheduled),\n isRepliesChat,\n album,\n avatarPeer,\n senderPeer,\n botSender,\n );\n\n const containerClassName = buildClassName(\n 'Message message-list-item',\n isFirstInGroup && 'first-in-group',\n isLastInGroup && 'last-in-group',\n isFirstInDocumentGroup && 'first-in-document-group',\n isLastInDocumentGroup && 'last-in-document-group',\n isLastInList && 'last-in-list',\n isOwn && 'own',\n Boolean(message.views) && 'has-views',\n message.isEdited && 'was-edited',\n hasReply && 'has-reply',\n isContextMenuShown && 'has-menu-open',\n isFocused && !noFocusHighlight && 'focused',\n isForwarding && 'is-forwarding',\n message.isDeleting && 'is-deleting',\n isInDocumentGroup && 'is-in-document-group',\n isAlbum && 'is-album',\n message.hasUnreadMention && 'has-unread-mention',\n isSelected && 'is-selected',\n isInSelectMode && 'is-in-selection-mode',\n isThreadTop && 'is-thread-top',\n Boolean(message.inlineButtons) && 'has-inline-buttons',\n isSwiped && 'is-swiped',\n transitionClassNames,\n );\n const contentClassName = buildContentClassName(message, {\n hasReply,\n customShape,\n isLastInGroup,\n asForwarded,\n hasThread,\n forceSenderName,\n hasComments: message.threadInfo && message.threadInfo.messagesCount > 0,\n hasActionButton: canForward || canFocus,\n });\n const withCommentButton = message.threadInfo && (!isInDocumentGroup || isLastInDocumentGroup)\n && messageListType === 'thread' && !noComments;\n const withAppendix = contentClassName.includes('has-appendix');\n\n useEnsureMessage(\n isRepliesChat && message.replyToChatId ? message.replyToChatId : chatId,\n hasReply ? message.replyToMessageId : undefined,\n replyMessage,\n message.id,\n );\n useFocusMessage(ref, chatId, isFocused, focusDirection, noFocusHighlight, isResizingContainer);\n useLayoutEffect(() => {\n if (!appendixRef.current) {\n return;\n }\n\n appendixRef.current.innerHTML = isOwn ? APPENDIX_OWN : APPENDIX_NOT_OWN;\n }, [isOwn, withAppendix]);\n\n let style = '';\n let calculatedWidth;\n let noMediaCorners = false;\n const albumLayout = useMemo(() => {\n return isAlbum ? calculateAlbumLayout(isOwn, Boolean(asForwarded), Boolean(noAvatars), album!) : undefined;\n }, [isAlbum, isOwn, asForwarded, noAvatars, album]);\n\n const extraPadding = asForwarded ? 28 : 0;\n if (!isAlbum && (photo || video)) {\n let width: number | undefined;\n if (photo) {\n width = calculateMediaDimensions(message, noAvatars).width;\n } else if (video) {\n if (video.isRound) {\n width = ROUND_VIDEO_DIMENSIONS_PX;\n } else {\n width = calculateMediaDimensions(message, noAvatars).width;\n }\n }\n\n if (width) {\n calculatedWidth = Math.max(getMinMediaWidth(Boolean(text), withCommentButton), width);\n if (calculatedWidth - width > NO_MEDIA_CORNERS_THRESHOLD) {\n noMediaCorners = true;\n }\n }\n } else if (albumLayout) {\n calculatedWidth = Math.max(getMinMediaWidth(Boolean(text), withCommentButton), albumLayout.containerStyle.width);\n if (calculatedWidth - albumLayout.containerStyle.width > NO_MEDIA_CORNERS_THRESHOLD) {\n noMediaCorners = true;\n }\n }\n\n if (calculatedWidth) {\n style = `width: ${calculatedWidth + extraPadding}px`;\n }\n\n function renderAvatar() {\n const isAvatarPeerUser = avatarPeer && isUserId(avatarPeer.id);\n const avatarUser = (avatarPeer && isAvatarPeerUser) ? avatarPeer as ApiUser : undefined;\n const avatarChat = (avatarPeer && !isAvatarPeerUser) ? avatarPeer as ApiChat : undefined;\n const hiddenName = (!avatarPeer && forwardInfo) ? forwardInfo.hiddenUserName : undefined;\n\n return (\n <Avatar\n size=\"small\"\n user={avatarUser}\n chat={avatarChat}\n text={hiddenName}\n lastSyncTime={lastSyncTime}\n onClick={(avatarUser || avatarChat) ? handleAvatarClick : undefined}\n />\n );\n }\n\n function renderContent() {\n const className = buildClassName(\n 'content-inner',\n asForwarded && !customShape && 'forwarded-message',\n hasReply && 'reply-message',\n noMediaCorners && 'no-media-corners',\n );\n const hasCustomAppendix = isLastInGroup && !textParts && !asForwarded && !hasThread;\n const shouldInlineMeta = !webPage && !animatedEmoji && textParts;\n const textContentClass = buildClassName(\n 'text-content',\n shouldInlineMeta && 'with-meta',\n outgoingStatus && 'with-outgoing-icon',\n );\n\n return (\n <div className={className} onDoubleClick={handleContentDoubleClick} dir=\"auto\">\n {renderSenderName()}\n {hasReply && (\n <EmbeddedMessage\n message={replyMessage}\n sender={replyMessageSender}\n observeIntersection={observeIntersectionForMedia}\n onClick={handleReplyClick}\n />\n )}\n {sticker && (\n <Sticker\n message={message}\n observeIntersection={observeIntersectionForMedia}\n observeIntersectionForPlaying={observeIntersectionForAnimatedStickers}\n shouldLoop={shouldLoopStickers}\n lastSyncTime={lastSyncTime}\n />\n )}\n {animatedEmoji && (\n <AnimatedEmoji\n size=\"small\"\n sticker={animatedEmoji}\n observeIntersection={observeIntersectionForMedia}\n lastSyncTime={lastSyncTime}\n forceLoadPreview={isLocal}\n />\n )}\n {isAlbum && (\n <Album\n album={album!}\n albumLayout={albumLayout!}\n observeIntersection={observeIntersectionForMedia}\n canAutoLoad={canAutoLoadMedia}\n canAutoPlay={canAutoPlayMedia}\n isOwn={isOwn}\n hasCustomAppendix={hasCustomAppendix}\n lastSyncTime={lastSyncTime}\n onMediaClick={handleAlbumMediaClick}\n />\n )}\n {!isAlbum && photo && (\n <Photo\n message={message}\n observeIntersection={observeIntersectionForMedia}\n noAvatars={noAvatars}\n canAutoLoad={canAutoLoadMedia}\n uploadProgress={uploadProgress}\n shouldAffectAppendix={hasCustomAppendix}\n onClick={handleMediaClick}\n onCancelUpload={handleCancelUpload}\n isDownloading={isDownloading}\n theme={theme}\n />\n )}\n {!isAlbum && video && video.isRound && (\n <RoundVideo\n message={message}\n observeIntersection={observeIntersectionForMedia}\n canAutoLoad={canAutoLoadMedia}\n lastSyncTime={lastSyncTime}\n isDownloading={isDownloading}\n />\n )}\n {!isAlbum && video && !video.isRound && (\n <Video\n message={message}\n observeIntersection={observeIntersectionForMedia}\n noAvatars={noAvatars}\n canAutoLoad={canAutoLoadMedia}\n canAutoPlay={canAutoPlayMedia}\n uploadProgress={uploadProgress}\n lastSyncTime={lastSyncTime}\n onClick={handleMediaClick}\n onCancelUpload={handleCancelUpload}\n isDownloading={isDownloading}\n />\n )}\n {(audio || voice) && (\n <Audio\n theme={theme}\n message={message}\n origin={AudioOrigin.Inline}\n uploadProgress={uploadProgress}\n lastSyncTime={lastSyncTime}\n isSelectable={isInDocumentGroup}\n isSelected={isSelected}\n onPlay={handleAudioPlay}\n onReadMedia={voice && (!isOwn || isChatWithSelf) ? handleReadMedia : undefined}\n onCancelUpload={handleCancelUpload}\n isDownloading={isDownloading}\n />\n )}\n {document && (\n <Document\n message={message}\n observeIntersection={observeIntersectionForMedia}\n canAutoLoad={canAutoLoadMedia}\n autoLoadFileMaxSizeMb={autoLoadFileMaxSizeMb}\n uploadProgress={uploadProgress}\n isSelectable={isInDocumentGroup}\n isSelected={isSelected}\n onMediaClick={handleMediaClick}\n onCancelUpload={handleCancelUpload}\n isDownloading={isDownloading}\n />\n )}\n {contact && (\n <Contact contact={contact} />\n )}\n {poll && (\n <Poll message={message} poll={poll} onSendVote={handleVoteSend} />\n )}\n {!animatedEmoji && textParts && (\n <p className={textContentClass} dir=\"auto\">\n {textParts}\n {shouldInlineMeta && (\n <MessageMeta\n message={message}\n outgoingStatus={outgoingStatus}\n signature={signature}\n onClick={handleMetaClick}\n />\n )}\n </p>\n )}\n {webPage && (\n <WebPage\n message={message}\n observeIntersection={observeIntersectionForMedia}\n noAvatars={noAvatars}\n canAutoLoad={canAutoLoadMedia}\n canAutoPlay={canAutoPlayMedia}\n lastSyncTime={lastSyncTime}\n onMediaClick={handleMediaClick}\n onCancelMediaTransfer={handleCancelUpload}\n isDownloading={isDownloading}\n theme={theme}\n />\n )}\n {invoice && <Invoice message={message} />}\n </div>\n );\n }\n\n function renderSenderName() {\n const shouldRender = !(customShape && !viaBotId) && (\n (withSenderName && !photo && !video) || asForwarded || viaBotId || forceSenderName\n ) && (!isInDocumentGroup || isFirstInDocumentGroup) && !(hasReply && customShape);\n\n if (!shouldRender) {\n return undefined;\n }\n\n let senderTitle;\n let senderColor;\n if (senderPeer && !(customShape && viaBotId)) {\n senderTitle = getSenderTitle(lang, senderPeer);\n\n if (!asForwarded) {\n senderColor = `color-${getUserColorKey(senderPeer)}`;\n }\n } else if (forwardInfo?.hiddenUserName) {\n senderTitle = forwardInfo.hiddenUserName;\n }\n\n return (\n <div className=\"message-title\" dir=\"ltr\">\n {senderTitle ? (\n <span\n className={buildClassName('interactive', senderColor)}\n onClick={handleSenderClick}\n dir=\"auto\"\n >\n {renderText(senderTitle)}\n </span>\n ) : !botSender ? (\n NBSP\n ) : undefined}\n {botSender && (\n <>\n <span className=\"via\">{lang('ViaBot')}</span>\n <span\n className=\"interactive\"\n onClick={handleViaBotClick}\n >\n {renderText(`@${botSender.username}`)}\n </span>\n </>\n )}\n {forwardInfo?.isLinkedChannelPost ? (\n <span className=\"admin-title\" dir=\"auto\">{lang('DiscussChannel')}</span>\n ) : message.adminTitle && !isChannel ? (\n <span className=\"admin-title\" dir=\"auto\">{message.adminTitle}</span>\n ) : undefined}\n </div>\n );\n }\n\n return (\n <div\n ref={ref}\n id={`message${messageId}`}\n className={containerClassName}\n // @ts-ignore teact feature\n style={metaSafeAuthorWidth ? `--meta-safe-author-width: ${metaSafeAuthorWidth}px` : undefined}\n data-message-id={messageId}\n onMouseDown={handleMouseDown}\n onClick={handleClick}\n onContextMenu={handleContextMenu}\n onDoubleClick={handleDoubleClick}\n onMouseEnter={isInDocumentGroup && !isLastInDocumentGroup ? handleDocumentGroupMouseEnter : undefined}\n onMouseLeave={isInDocumentGroup && !isLastInDocumentGroup ? handleDocumentGroupMouseLeave : undefined}\n >\n <div\n ref={bottomMarkerRef}\n className=\"bottom-marker\"\n data-message-id={messageId}\n data-last-message-id={album ? album.messages[album.messages.length - 1].id : undefined}\n data-has-unread-mention={message.hasUnreadMention}\n />\n {!isInDocumentGroup && (\n <div className=\"message-select-control\">\n {isSelected && <i className=\"icon-select\" />}\n </div>\n )}\n {isLastInDocumentGroup && (\n <div\n className={buildClassName('message-select-control group-select', isGroupSelected && 'is-selected')}\n onClick={handleDocumentGroupSelectAll}\n >\n {isGroupSelected && (\n <i className=\"icon-select\" />\n )}\n </div>\n )}\n {withAvatar && renderAvatar()}\n <div\n className={buildClassName('message-content-wrapper', contentClassName.includes('text') && 'can-select-text')}\n >\n <div\n className={contentClassName}\n // @ts-ignore\n style={style}\n dir=\"auto\"\n >\n {asForwarded && !customShape && (!isInDocumentGroup || isFirstInDocumentGroup) && (\n <div className=\"message-title\">{lang('ForwardedMessage')}</div>\n )}\n {renderContent()}\n {(!isInDocumentGroup || isLastInDocumentGroup) && !(!webPage && !animatedEmoji && textParts) && (\n <MessageMeta\n message={message}\n outgoingStatus={outgoingStatus}\n signature={signature}\n onClick={handleMetaClick}\n />\n )}\n {canShowActionButton && canForward ? (\n <Button\n className=\"message-action-button\"\n color=\"translucent-white\"\n round\n size=\"tiny\"\n ariaLabel={lang('lng_context_forward_msg')}\n onClick={isLastInDocumentGroup ? handleGroupForward : handleForward}\n >\n <i className=\"icon-share-filled\" />\n </Button>\n ) : canShowActionButton && canFocus ? (\n <Button\n className=\"message-action-button\"\n color=\"translucent-white\"\n round\n size=\"tiny\"\n ariaLabel=\"Focus message\"\n onClick={isPinnedList ? handleFocus : handleFocusForwarded}\n >\n <i className=\"icon-arrow-right\" />\n </Button>\n ) : undefined}\n {withCommentButton && <CommentButton message={message} disabled={noComments} />}\n {withAppendix && <div className=\"svg-appendix\" ref={appendixRef} />}\n </div>\n {message.inlineButtons && (\n <InlineButtons message={message} onClick={clickInlineButton} />\n )}\n </div>\n {contextMenuPosition && (\n <ContextMenuContainer\n isOpen={isContextMenuOpen}\n anchor={contextMenuPosition}\n message={message}\n album={album}\n chatUsername={chatUsername}\n messageListType={messageListType}\n onClose={handleContextMenuClose}\n onCloseAnimationEnd={handleContextMenuHide}\n />\n )}\n </div>\n );\n};\n\nfunction handleDocumentGroupMouseEnter(e: React.MouseEvent<HTMLDivElement>) {\n const lastGroupElement = getLastElementInDocumentGroup(e.currentTarget);\n if (lastGroupElement) {\n lastGroupElement.setAttribute(GROUP_MESSAGE_HOVER_ATTRIBUTE, '');\n }\n}\n\nfunction handleDocumentGroupMouseLeave(e: React.MouseEvent<HTMLDivElement>) {\n const lastGroupElement = getLastElementInDocumentGroup(e.currentTarget);\n if (lastGroupElement) {\n lastGroupElement.removeAttribute(GROUP_MESSAGE_HOVER_ATTRIBUTE);\n }\n}\n\nfunction getLastElementInDocumentGroup(element: Element) {\n let current: Element | null = element;\n\n do {\n current = current.nextElementSibling;\n } while (current && !current.classList.contains('last-in-document-group'));\n\n return current;\n}\n\nexport default memo(withGlobal<OwnProps>(\n (global, ownProps): StateProps => {\n const { focusedMessage, forwardMessages, lastSyncTime } = global;\n const {\n message, album, withSenderName, withAvatar, threadId, messageListType,\n } = ownProps;\n const {\n id, chatId, viaBotId, replyToChatId, replyToMessageId, isOutgoing,\n } = message;\n\n const chat = selectChat(global, chatId);\n const isChatWithSelf = selectIsChatWithSelf(global, chatId);\n const isRepliesChat = isChatWithRepliesBot(chatId);\n const isChannel = chat && isChatChannel(chat);\n const chatUsername = chat?.username;\n\n const forceSenderName = !isChatWithSelf && isAnonymousOwnMessage(message);\n const canShowSender = withSenderName || withAvatar || forceSenderName;\n const sender = selectSender(global, message);\n const originSender = selectForwardedSender(global, message);\n const botSender = viaBotId ? selectUser(global, viaBotId) : undefined;\n\n const threadTopMessageId = threadId ? selectThreadTopMessageId(global, chatId, threadId) : undefined;\n const isThreadTop = message.id === threadTopMessageId;\n\n const shouldHideReply = replyToMessageId === threadTopMessageId;\n const replyMessage = replyToMessageId && !shouldHideReply\n ? selectChatMessage(global, isRepliesChat && replyToChatId ? replyToChatId : chatId, replyToMessageId)\n : undefined;\n const replyMessageSender = replyMessage && selectSender(global, replyMessage);\n\n const uploadProgress = selectUploadProgress(global, message);\n const isFocused = messageListType === 'thread' && (\n album\n ? album.messages.some((m) => selectIsMessageFocused(global, m))\n : selectIsMessageFocused(global, message)\n );\n\n const {\n direction: focusDirection, noHighlight: noFocusHighlight, isResizingContainer,\n } = (isFocused && focusedMessage) || {};\n\n const isForwarding = forwardMessages.messageIds && forwardMessages.messageIds.includes(id);\n\n const { query: highlight } = selectCurrentTextSearch(global) || {};\n\n const singleEmoji = getMessageSingleEmoji(message);\n let isSelected: boolean;\n\n if (album?.messages) {\n isSelected = album.messages.every(({ id: messageId }) => selectIsMessageSelected(global, messageId));\n } else {\n isSelected = selectIsMessageSelected(global, id);\n }\n\n const { canReply } = (messageListType === 'thread' && selectAllowedMessageActions(global, message, threadId)) || {};\n const isDownloading = selectIsDownloading(global, message);\n\n return {\n theme: selectTheme(global),\n chatUsername,\n forceSenderName,\n sender: canShowSender ? sender : undefined,\n originSender,\n botSender,\n shouldHideReply,\n isThreadTop,\n replyMessage,\n replyMessageSender,\n isFocused,\n isForwarding,\n isChatWithSelf,\n isRepliesChat,\n isChannel,\n canReply,\n lastSyncTime,\n highlight,\n isSingleEmoji: Boolean(singleEmoji),\n animatedEmoji: singleEmoji ? selectAnimatedEmoji(global, singleEmoji) : undefined,\n isInSelectMode: selectIsInSelectMode(global),\n isSelected,\n isGroupSelected: (\n !!message.groupedId && !message.isInAlbum && selectIsDocumentGroupSelected(global, chatId, message.groupedId)\n ),\n threadId,\n isDownloading,\n isPinnedList: messageListType === 'pinned',\n canAutoLoadMedia: chat ? selectCanAutoLoadMedia(global, message, chat, sender) : undefined,\n canAutoPlayMedia: selectCanAutoPlayMedia(global, message),\n autoLoadFileMaxSizeMb: global.settings.byKey.autoLoadFileMaxSizeMb,\n shouldLoopStickers: selectShouldLoopStickers(global),\n ...(isOutgoing && { outgoingStatus: selectOutgoingStatus(global, message, messageListType === 'scheduled') }),\n ...(typeof uploadProgress === 'number' && { uploadProgress }),\n ...(isFocused && { focusDirection, noFocusHighlight, isResizingContainer }),\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'toggleMessageSelection',\n 'clickInlineButton',\n 'disableContextMenuHint',\n ]),\n)(Message));\n","import { RefObject } from 'react';\nimport React, { useEffect } from '../../../../lib/teact/teact';\nimport { getDispatch } from '../../../../lib/teact/teactn';\n\nimport { IS_ANDROID, IS_TOUCH_ENV } from '../../../../util/environment';\nimport windowSize from '../../../../util/windowSize';\nimport { captureEvents, SwipeDirection } from '../../../../util/captureEvents';\nimport useFlag from '../../../../hooks/useFlag';\nimport { preventMessageInputBlur } from '../../helpers/preventMessageInputBlur';\n\nconst ANDROID_KEYBOARD_HIDE_DELAY_MS = 350;\nconst SWIPE_ANIMATION_DURATION = 150;\n\nexport default function useOuterHandlers(\n selectMessage: (e?: React.MouseEvent<HTMLDivElement, MouseEvent>, groupedId?: string) => void,\n containerRef: RefObject<HTMLDivElement>,\n messageId: number,\n isAlbum: boolean,\n isInSelectMode: boolean,\n canReply: boolean,\n onContextMenu: (e: React.MouseEvent) => void,\n handleBeforeContextMenu: (e: React.MouseEvent) => void,\n) {\n const { setReplyingToId } = getDispatch();\n\n const [isSwiped, markSwiped, unmarkSwiped] = useFlag();\n\n function handleMouseDown(e: React.MouseEvent<HTMLDivElement, MouseEvent>) {\n preventMessageInputBlur(e);\n handleBeforeContextMenu(e);\n }\n\n function handleClick(e: React.MouseEvent<HTMLDivElement, MouseEvent>) {\n if (isInSelectMode) {\n selectMessage(e);\n } else if (IS_ANDROID) {\n const target = e.target as HTMLDivElement;\n if (!target.classList.contains('text-content') && !target.classList.contains('Message')) {\n return;\n }\n\n if (windowSize.getIsKeyboardVisible()) {\n setTimeout(() => {\n onContextMenu(e);\n }, ANDROID_KEYBOARD_HIDE_DELAY_MS);\n } else {\n onContextMenu(e);\n }\n }\n }\n\n function handleContextMenu(e: React.MouseEvent<HTMLDivElement, MouseEvent>) {\n if (IS_ANDROID) {\n if ((e.target as HTMLElement).matches('a[href]')) {\n return;\n }\n\n e.preventDefault();\n selectMessage();\n } else {\n onContextMenu(e);\n }\n }\n\n function handleContainerDoubleClick() {\n setReplyingToId({ messageId });\n }\n\n function stopPropagation(e: React.MouseEvent<HTMLDivElement, MouseEvent>) {\n e.stopPropagation();\n }\n\n useEffect(() => {\n if (!IS_TOUCH_ENV || isInSelectMode || !canReply) {\n return undefined;\n }\n\n let startedAt: number | undefined;\n return captureEvents(containerRef.current!, {\n selectorToPreventScroll: '.MessageList',\n onSwipe: ((e, direction) => {\n if (direction === SwipeDirection.Left) {\n if (!startedAt) {\n startedAt = Date.now();\n }\n\n markSwiped();\n\n return true;\n }\n\n return false;\n }),\n onRelease: () => {\n if (!startedAt) {\n return;\n }\n\n setReplyingToId({ messageId });\n\n setTimeout(unmarkSwiped, Math.max(0, SWIPE_ANIMATION_DURATION - (Date.now() - startedAt)));\n startedAt = undefined;\n },\n });\n }, [containerRef, isInSelectMode, messageId, setReplyingToId, markSwiped, unmarkSwiped, canReply]);\n\n return {\n handleMouseDown: !isInSelectMode ? handleMouseDown : undefined,\n handleClick,\n handleContextMenu: !isInSelectMode ? handleContextMenu : undefined,\n handleDoubleClick: !isInSelectMode ? handleContainerDoubleClick : undefined,\n handleContentDoubleClick: !IS_TOUCH_ENV ? stopPropagation : undefined,\n isSwiped,\n };\n}\n","import React, { useCallback } from '../../../../lib/teact/teact';\nimport { getDispatch } from '../../../../lib/teact/teactn';\n\nimport { isUserId } from '../../../../modules/helpers';\nimport { AudioOrigin, IAlbum, MediaViewerOrigin } from '../../../../types';\nimport {\n ApiChat, ApiMessage, ApiUser, MAIN_THREAD_ID,\n} from '../../../../api/types';\nimport { LangFn } from '../../../../hooks/useLang';\n\nexport default function useInnerHandlers(\n lang: LangFn,\n selectMessage: (e: React.MouseEvent<HTMLDivElement, MouseEvent>, groupedId?: string) => void,\n message: ApiMessage,\n chatId: string,\n threadId: number,\n isInDocumentGroup: boolean,\n isScheduled?: boolean,\n isChatWithRepliesBot?: boolean,\n album?: IAlbum,\n avatarPeer?: ApiUser | ApiChat,\n senderPeer?: ApiUser | ApiChat,\n botSender?: ApiUser,\n) {\n const {\n openUserInfo, openChat, showNotification, focusMessage, openMediaViewer, openAudioPlayer,\n markMessagesRead, cancelSendingMessage, sendPollVote, openForwardMenu, focusMessageInComments,\n } = getDispatch();\n\n const {\n id: messageId, forwardInfo, replyToMessageId, replyToChatId, replyToTopMessageId, groupedId,\n } = message;\n\n const handleAvatarClick = useCallback(() => {\n if (!avatarPeer) {\n return;\n }\n\n if (isUserId(avatarPeer.id)) {\n openUserInfo({ id: avatarPeer.id });\n } else {\n openChat({ id: avatarPeer.id });\n }\n }, [avatarPeer, openUserInfo, openChat]);\n\n const handleSenderClick = useCallback(() => {\n if (!senderPeer) {\n showNotification({ message: lang('HidAccount') });\n\n return;\n }\n\n if (isUserId(senderPeer.id)) {\n openUserInfo({ id: senderPeer.id });\n } else {\n openChat({ id: senderPeer.id });\n }\n }, [senderPeer, showNotification, lang, openUserInfo, openChat]);\n\n const handleViaBotClick = useCallback(() => {\n if (!botSender) {\n return;\n }\n\n openUserInfo({ id: botSender.id });\n }, [botSender, openUserInfo]);\n\n const handleReplyClick = useCallback((): void => {\n focusMessage({\n chatId: isChatWithRepliesBot && replyToChatId ? replyToChatId : chatId,\n threadId,\n messageId: replyToMessageId,\n replyMessageId: isChatWithRepliesBot && replyToChatId ? undefined : messageId,\n });\n }, [focusMessage, isChatWithRepliesBot, replyToChatId, chatId, threadId, replyToMessageId, messageId]);\n\n const handleMediaClick = useCallback((): void => {\n openMediaViewer({\n chatId, threadId, messageId, origin: isScheduled ? MediaViewerOrigin.ScheduledInline : MediaViewerOrigin.Inline,\n });\n }, [chatId, threadId, messageId, openMediaViewer, isScheduled]);\n\n const handleAudioPlay = useCallback((): void => {\n openAudioPlayer({ chatId, messageId, origin: AudioOrigin.Inline });\n }, [chatId, messageId, openAudioPlayer]);\n\n const handleAlbumMediaClick = useCallback((albumMessageId: number): void => {\n openMediaViewer({\n chatId,\n threadId,\n messageId: albumMessageId,\n origin: isScheduled ? MediaViewerOrigin.ScheduledAlbum : MediaViewerOrigin.Album,\n });\n }, [chatId, threadId, openMediaViewer, isScheduled]);\n\n const handleReadMedia = useCallback((): void => {\n markMessagesRead({ messageIds: [messageId] });\n }, [messageId, markMessagesRead]);\n\n const handleCancelUpload = useCallback(() => {\n cancelSendingMessage({ chatId, messageId });\n }, [cancelSendingMessage, chatId, messageId]);\n\n const handleVoteSend = useCallback((options: string[]) => {\n sendPollVote({ chatId, messageId, options });\n }, [chatId, messageId, sendPollVote]);\n\n const handleGroupForward = useCallback(() => {\n openForwardMenu({ fromChatId: chatId, groupedId });\n }, [openForwardMenu, chatId, groupedId]);\n\n const handleForward = useCallback(() => {\n if (album && album.messages) {\n const messageIds = album.messages.map(({ id }) => id);\n openForwardMenu({ fromChatId: chatId, messageIds });\n } else {\n openForwardMenu({ fromChatId: chatId, messageIds: [messageId] });\n }\n }, [album, openForwardMenu, chatId, messageId]);\n\n const handleFocus = useCallback(() => {\n focusMessage({\n chatId, threadId: MAIN_THREAD_ID, messageId,\n });\n }, [focusMessage, chatId, messageId]);\n\n const handleFocusForwarded = useCallback(() => {\n if (isInDocumentGroup) {\n focusMessage({\n chatId: forwardInfo!.fromChatId, groupedId, groupedChatId: chatId,\n });\n return;\n }\n\n if (isChatWithRepliesBot && replyToChatId) {\n focusMessageInComments({\n chatId: replyToChatId,\n threadId: replyToTopMessageId,\n messageId: forwardInfo!.fromMessageId,\n });\n } else {\n focusMessage({\n chatId: forwardInfo!.fromChatId, messageId: forwardInfo!.fromMessageId,\n });\n }\n }, [\n isInDocumentGroup, isChatWithRepliesBot, replyToChatId, focusMessage, forwardInfo, groupedId, chatId,\n focusMessageInComments, replyToTopMessageId,\n ]);\n\n const selectWithGroupedId = useCallback((e: React.MouseEvent<HTMLDivElement, MouseEvent>) => {\n e.stopPropagation();\n\n selectMessage(e, groupedId);\n }, [selectMessage, groupedId]);\n\n return {\n handleAvatarClick,\n handleSenderClick,\n handleViaBotClick,\n handleReplyClick,\n handleMediaClick,\n handleAudioPlay,\n handleAlbumMediaClick,\n handleMetaClick: selectWithGroupedId,\n handleReadMedia,\n handleCancelUpload,\n handleVoteSend,\n handleGroupForward,\n handleForward,\n handleFocus,\n handleFocusForwarded,\n handleDocumentGroupSelectAll: selectWithGroupedId,\n };\n}\n","import { RefObject } from 'react';\nimport React, { FC, memo } from '../../lib/teact/teact';\n\nimport { MessageListType } from '../../global/types';\n\nimport { SCHEDULED_WHEN_ONLINE } from '../../config';\nimport buildClassName from '../../util/buildClassName';\nimport { compact, flatten } from '../../util/iteratees';\nimport { formatHumanDate } from '../../util/dateFormat';\nimport { getMessageOriginalId, isActionMessage, isOwnMessage } from '../../modules/helpers';\nimport useLang from '../../hooks/useLang';\nimport { isAlbum, MessageDateGroup } from './helpers/groupMessages';\nimport { preventMessageInputBlur } from './helpers/preventMessageInputBlur';\nimport useScrollHooks from './hooks/useScrollHooks';\nimport useMessageObservers from './hooks/useMessageObservers';\n\nimport Message from './message/Message';\nimport ActionMessage from './ActionMessage';\n\ninterface OwnProps {\n messageIds: number[];\n messageGroups: MessageDateGroup[];\n isViewportNewest: boolean;\n isUnread: boolean;\n withUsers: boolean;\n noAvatars: boolean;\n containerRef: RefObject<HTMLDivElement>;\n anchorIdRef: { current: string | undefined };\n memoUnreadDividerBeforeIdRef: { current: number | undefined };\n memoFirstUnreadIdRef: { current: number | undefined };\n threadId: number;\n type: MessageListType;\n isActive: boolean;\n threadTopMessageId: number | undefined;\n hasLinkedChat: boolean | undefined;\n isSchedule: boolean;\n noAppearanceAnimation: boolean;\n onFabToggle: AnyToVoidFunction;\n onNotchToggle: AnyToVoidFunction;\n openHistoryCalendar: Function;\n}\n\nconst UNREAD_DIVIDER_CLASS = 'unread-divider';\n\nconst MessageListContent: FC<OwnProps> = ({\n messageIds,\n messageGroups,\n isViewportNewest,\n isUnread,\n withUsers,\n noAvatars,\n containerRef,\n anchorIdRef,\n memoUnreadDividerBeforeIdRef,\n memoFirstUnreadIdRef,\n threadId,\n type,\n isActive,\n threadTopMessageId,\n hasLinkedChat,\n isSchedule,\n noAppearanceAnimation,\n onFabToggle,\n onNotchToggle,\n openHistoryCalendar,\n}) => {\n const {\n observeIntersectionForMedia,\n observeIntersectionForReading,\n observeIntersectionForAnimatedStickers,\n } = useMessageObservers(type, containerRef, memoFirstUnreadIdRef);\n\n const {\n backwardsTriggerRef,\n forwardsTriggerRef,\n fabTriggerRef,\n } = useScrollHooks(\n type,\n containerRef,\n messageIds,\n isViewportNewest,\n isUnread,\n onFabToggle,\n onNotchToggle,\n isActive,\n );\n\n const lang = useLang();\n\n const unreadDivider = (\n <div className={buildClassName(UNREAD_DIVIDER_CLASS, 'local-action-message')} key=\"unread-messages\">\n <span>{lang('UnreadMessages')}</span>\n </div>\n );\n\n const messageCountToAnimate = noAppearanceAnimation ? 0 : messageGroups.reduce((acc, messageGroup) => {\n return acc + flatten(messageGroup.senderGroups).length;\n }, 0);\n let appearanceIndex = 0;\n\n const dateGroups = messageGroups.map((\n dateGroup: MessageDateGroup,\n dateGroupIndex: number,\n dateGroupsArray: MessageDateGroup[],\n ) => {\n const senderGroups = dateGroup.senderGroups.map((\n senderGroup,\n senderGroupIndex,\n senderGroupsArray,\n ) => {\n if (senderGroup.length === 1 && !isAlbum(senderGroup[0]) && isActionMessage(senderGroup[0])) {\n const message = senderGroup[0];\n const isLastInList = (\n senderGroupIndex === senderGroupsArray.length - 1\n && dateGroupIndex === dateGroupsArray.length - 1\n );\n\n return compact([\n message.id === memoUnreadDividerBeforeIdRef.current && unreadDivider,\n <ActionMessage\n key={message.id}\n message={message}\n observeIntersection={observeIntersectionForReading}\n appearanceOrder={messageCountToAnimate - ++appearanceIndex}\n isLastInList={isLastInList}\n />,\n ]);\n }\n\n let currentDocumentGroupId: string | undefined;\n\n return flatten(senderGroup.map((\n messageOrAlbum,\n messageIndex,\n ) => {\n const message = isAlbum(messageOrAlbum) ? messageOrAlbum.mainMessage : messageOrAlbum;\n const album = isAlbum(messageOrAlbum) ? messageOrAlbum : undefined;\n const isOwn = isOwnMessage(message);\n const isMessageAlbum = isAlbum(messageOrAlbum);\n const nextMessage = senderGroup[messageIndex + 1];\n\n if (message.previousLocalId && anchorIdRef.current === `message${message.previousLocalId}`) {\n anchorIdRef.current = `message${message.id}`;\n }\n\n const documentGroupId = !isMessageAlbum && message.groupedId ? message.groupedId : undefined;\n const nextDocumentGroupId = nextMessage && !isAlbum(nextMessage) ? nextMessage.groupedId : undefined;\n\n const position = {\n isFirstInGroup: messageIndex === 0,\n isLastInGroup: messageIndex === senderGroup.length - 1,\n isFirstInDocumentGroup: Boolean(documentGroupId && documentGroupId !== currentDocumentGroupId),\n isLastInDocumentGroup: Boolean(documentGroupId && documentGroupId !== nextDocumentGroupId),\n isLastInList: (\n messageIndex === senderGroup.length - 1\n && senderGroupIndex === senderGroupsArray.length - 1\n && dateGroupIndex === dateGroupsArray.length - 1\n ),\n };\n\n currentDocumentGroupId = documentGroupId;\n\n const originalId = getMessageOriginalId(message);\n // Scheduled messages can have local IDs in the middle of the list,\n // and keys should be ordered, so we prefix it with a date.\n // However, this may lead to issues if server date is not synchronized with the local one.\n const key = type !== 'scheduled' ? originalId : `${message.date}_${originalId}`;\n\n return compact([\n message.id === memoUnreadDividerBeforeIdRef.current && unreadDivider,\n <Message\n key={key}\n message={message}\n observeIntersectionForBottom={observeIntersectionForReading}\n observeIntersectionForMedia={observeIntersectionForMedia}\n observeIntersectionForAnimatedStickers={observeIntersectionForAnimatedStickers}\n album={album}\n noAvatars={noAvatars}\n withAvatar={position.isLastInGroup && withUsers && !isOwn && !(message.id === threadTopMessageId)}\n withSenderName={position.isFirstInGroup && withUsers && !isOwn}\n threadId={threadId}\n messageListType={type}\n noComments={hasLinkedChat === false}\n appearanceOrder={messageCountToAnimate - ++appearanceIndex}\n isFirstInGroup={position.isFirstInGroup}\n isLastInGroup={position.isLastInGroup}\n isFirstInDocumentGroup={position.isFirstInDocumentGroup}\n isLastInDocumentGroup={position.isLastInDocumentGroup}\n isLastInList={position.isLastInList}\n />,\n message.id === threadTopMessageId && (\n <div className=\"local-action-message\" key=\"discussion-started\">\n <span>{lang('DiscussionStarted')}</span>\n </div>\n ),\n ]);\n }));\n });\n\n return (\n <div\n className=\"message-date-group\"\n key={dateGroup.datetime}\n onMouseDown={preventMessageInputBlur}\n teactFastList\n >\n <div\n className={buildClassName('sticky-date', !isSchedule && 'interactive')}\n key=\"date-header\"\n onMouseDown={preventMessageInputBlur}\n onClick={!isSchedule ? () => openHistoryCalendar({ selectedAt: dateGroup.datetime }) : undefined}\n >\n <span dir=\"auto\">\n {isSchedule && dateGroup.originalDate === SCHEDULED_WHEN_ONLINE && (\n lang('MessageScheduledUntilOnline')\n )}\n {isSchedule && dateGroup.originalDate !== SCHEDULED_WHEN_ONLINE && (\n lang('MessageScheduledOn', formatHumanDate(lang, dateGroup.datetime, undefined, true))\n )}\n {!isSchedule && formatHumanDate(lang, dateGroup.datetime)}\n </span>\n </div>\n {flatten(senderGroups)}\n </div>\n );\n });\n\n return (\n <div className=\"messages-container\" teactFastList>\n <div ref={backwardsTriggerRef} key=\"backwards-trigger\" className=\"backwards-trigger\" />\n {flatten(dateGroups)}\n <div\n ref={forwardsTriggerRef}\n key=\"forwards-trigger\"\n className=\"forwards-trigger\"\n />\n <div\n ref={fabTriggerRef}\n key=\"fab-trigger\"\n className=\"fab-trigger\"\n />\n </div>\n );\n};\n\nexport default memo(MessageListContent);\n","import { RefObject } from 'react';\nimport { getDispatch } from '../../../lib/teact/teactn';\nimport { useMemo, useRef } from '../../../lib/teact/teact';\n\nimport { LoadMoreDirection } from '../../../types';\nimport { MessageListType } from '../../../global/types';\n\nimport { debounce } from '../../../util/schedulers';\nimport { useIntersectionObserver, useOnIntersect } from '../../../hooks/useIntersectionObserver';\nimport { LOCAL_MESSAGE_ID_BASE, MESSAGE_LIST_SENSITIVE_AREA } from '../../../config';\nimport resetScroll from '../../../util/resetScroll';\nimport useOnChange from '../../../hooks/useOnChange';\n\nconst FAB_THRESHOLD = 50;\nconst TOOLS_FREEZE_TIMEOUT = 100;\n\nexport default function useScrollHooks(\n type: MessageListType,\n containerRef: RefObject<HTMLDivElement>,\n messageIds: number[],\n isViewportNewest: boolean,\n isUnread: boolean,\n onFabToggle: AnyToVoidFunction,\n onNotchToggle: AnyToVoidFunction,\n isActive: boolean,\n) {\n const { loadViewportMessages } = getDispatch();\n\n const [loadMoreBackwards, loadMoreForwards] = useMemo(\n () => (type === 'thread' ? [\n debounce(() => loadViewportMessages({ direction: LoadMoreDirection.Backwards }), 1000, true, false),\n debounce(() => loadViewportMessages({ direction: LoadMoreDirection.Forwards }), 1000, true, false),\n ] : []),\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [loadViewportMessages, messageIds],\n );\n\n // eslint-disable-next-line no-null/no-null\n const backwardsTriggerRef = useRef<HTMLDivElement>(null);\n // eslint-disable-next-line no-null/no-null\n const forwardsTriggerRef = useRef<HTMLDivElement>(null);\n // eslint-disable-next-line no-null/no-null\n const fabTriggerRef = useRef<HTMLDivElement>(null);\n\n function toggleScrollTools() {\n if (!isActive) return;\n\n if (!messageIds || !messageIds.length) {\n onFabToggle(false);\n onNotchToggle(false);\n return;\n }\n\n if (!isViewportNewest) {\n onFabToggle(true);\n onNotchToggle(true);\n return;\n }\n\n const { offsetHeight, scrollHeight, scrollTop } = containerRef.current!;\n const scrollBottom = Math.round(scrollHeight - scrollTop - offsetHeight);\n const isNearBottom = scrollBottom <= FAB_THRESHOLD;\n const isAtBottom = scrollBottom <= 0;\n\n onFabToggle(isUnread ? !isAtBottom : !isNearBottom);\n onNotchToggle(!isAtBottom);\n }\n\n const {\n observe: observeIntersection,\n } = useIntersectionObserver({\n rootRef: containerRef,\n margin: MESSAGE_LIST_SENSITIVE_AREA,\n }, (entries) => {\n if (!loadMoreForwards || !loadMoreBackwards) {\n return;\n }\n\n // Loading history while sending a message can return the same message and cause ambiguity\n const isFirstMessageLocal = messageIds[0] >= LOCAL_MESSAGE_ID_BASE;\n if (isFirstMessageLocal) {\n return;\n }\n\n const triggerEntry = entries.find(({ isIntersecting }) => isIntersecting);\n if (!triggerEntry) {\n return;\n }\n\n const { target } = triggerEntry;\n\n if (target.className === 'backwards-trigger') {\n resetScroll(containerRef.current!);\n loadMoreBackwards();\n } else if (target.className === 'forwards-trigger') {\n resetScroll(containerRef.current!);\n loadMoreForwards();\n }\n });\n\n useOnIntersect(backwardsTriggerRef, observeIntersection);\n useOnIntersect(forwardsTriggerRef, observeIntersection);\n\n const {\n observe: observeIntersectionForFab,\n freeze: freezeForFab,\n unfreeze: unfreezeForFab,\n } = useIntersectionObserver({\n rootRef: containerRef,\n margin: FAB_THRESHOLD,\n }, toggleScrollTools);\n\n useOnIntersect(fabTriggerRef, observeIntersectionForFab);\n\n const {\n observe: observeIntersectionForNotch,\n freeze: freezeForNotch,\n unfreeze: unfreezeForNotch,\n } = useIntersectionObserver({\n rootRef: containerRef,\n }, toggleScrollTools);\n\n useOnIntersect(fabTriggerRef, observeIntersectionForNotch);\n\n // Workaround for FAB and notch flickering with tall incoming message\n useOnChange(() => {\n freezeForFab();\n freezeForNotch();\n\n setTimeout(() => {\n unfreezeForNotch();\n unfreezeForFab();\n }, TOOLS_FREEZE_TIMEOUT);\n }, [messageIds]);\n\n return { backwardsTriggerRef, forwardsTriggerRef, fabTriggerRef };\n}\n","import React, {\n FC, memo, useCallback, useEffect, useRef,\n} from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../global/types';\nimport { ApiSticker, ApiUpdateConnectionStateType } from '../../api/types';\n\nimport { pick } from '../../util/iteratees';\nimport { selectChat } from '../../modules/selectors';\nimport { useIntersectionObserver } from '../../hooks/useIntersectionObserver';\nimport useLang from '../../hooks/useLang';\nimport { getUserIdDividend } from '../../modules/helpers';\n\nimport StickerButton from '../common/StickerButton';\n\nimport './ContactGreeting.scss';\n\ntype OwnProps = {\n userId: string;\n};\n\ntype StateProps = {\n sticker?: ApiSticker;\n lastUnreadMessageId?: number;\n connectionState?: ApiUpdateConnectionStateType;\n};\n\ntype DispatchProps = Pick<GlobalActions, 'loadGreetingStickers' | 'sendMessage' | 'markMessageListRead'>;\n\nconst INTERSECTION_DEBOUNCE_MS = 200;\n\nconst ContactGreeting: FC<OwnProps & StateProps & DispatchProps> = ({\n sticker,\n connectionState,\n lastUnreadMessageId,\n loadGreetingStickers,\n sendMessage,\n markMessageListRead,\n}) => {\n const lang = useLang();\n // eslint-disable-next-line no-null/no-null\n const containerRef = useRef<HTMLDivElement>(null);\n const {\n observe: observeIntersection,\n } = useIntersectionObserver({\n rootRef: containerRef,\n debounceMs: INTERSECTION_DEBOUNCE_MS,\n });\n useEffect(() => {\n if (sticker || connectionState !== 'connectionStateReady') {\n return;\n }\n\n loadGreetingStickers();\n }, [connectionState, loadGreetingStickers, sticker]);\n\n useEffect(() => {\n if (connectionState === 'connectionStateReady' && lastUnreadMessageId) {\n markMessageListRead({ maxId: lastUnreadMessageId });\n }\n }, [connectionState, markMessageListRead, lastUnreadMessageId]);\n\n const handleStickerSelect = useCallback((selectedSticker: ApiSticker) => {\n selectedSticker = {\n ...selectedSticker,\n isPreloadedGlobally: true,\n };\n sendMessage({ sticker: selectedSticker });\n }, [sendMessage]);\n\n return (\n <div className=\"ContactGreeting\" ref={containerRef}>\n <div className=\"wrapper\">\n <p className=\"title\" dir=\"auto\">{lang('Conversation.EmptyPlaceholder')}</p>\n <p className=\"description\" dir=\"auto\">{lang('Conversation.GreetingText')}</p>\n\n <div className=\"sticker\">\n {sticker && (\n <StickerButton\n sticker={sticker}\n onClick={handleStickerSelect}\n clickArg={sticker}\n observeIntersection={observeIntersection}\n size={160}\n className=\"large\"\n />\n )}\n </div>\n </div>\n </div>\n );\n};\n\nexport default memo(withGlobal<OwnProps>(\n (global, { userId }): StateProps => {\n const { stickers } = global.stickers.greeting;\n const dividend = getUserIdDividend(userId) + getUserIdDividend(global.currentUserId!);\n const sticker = stickers?.length ? stickers[dividend % stickers.length] : undefined;\n const chat = selectChat(global, userId);\n if (!chat) {\n return {};\n }\n\n return {\n sticker,\n lastUnreadMessageId: chat.lastMessage && chat.lastMessage.id !== chat.lastReadInboxMessageId\n ? chat.lastMessage.id\n : undefined,\n connectionState: global.connectionState,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'loadGreetingStickers', 'sendMessage', 'markMessageListRead',\n ]),\n)(ContactGreeting));\n","import React, { FC, memo } from '../../lib/teact/teact';\n\nimport { MessageListType } from '../../global/types';\n\nimport useLang, { LangFn } from '../../hooks/useLang';\n\nimport './NoMessages.scss';\n\ntype OwnProps = {\n chatId: string;\n isChatWithSelf?: boolean;\n type: MessageListType;\n isGroupChatJustCreated?: boolean;\n};\n\nconst NoMessages: FC<OwnProps> = ({\n isChatWithSelf, type, isGroupChatJustCreated,\n}) => {\n const lang = useLang();\n\n if (type === 'scheduled') {\n return renderScheduled(lang);\n }\n\n if (isChatWithSelf) {\n return renderSavedMessages(lang);\n }\n\n if (isGroupChatJustCreated) {\n return renderGroup(lang);\n }\n\n return (\n <div className=\"empty\"><span>{lang('NoMessages')}</span></div>\n );\n};\n\nfunction renderScheduled(lang: LangFn) {\n return (\n <div className=\"empty\"><span>{lang('ScheduledMessages.EmptyPlaceholder')}</span></div>\n );\n}\n\nfunction renderSavedMessages(lang: LangFn) {\n return (\n <div className=\"NoMessages\">\n <div className=\"wrapper\">\n <i className=\"icon icon-cloud-download\" />\n <h3 className=\"title\">{lang('Conversation.CloudStorageInfo.Title')}</h3>\n <ul className=\"description\">\n <li>{lang('Conversation.ClousStorageInfo.Description1')}</li>\n <li>{lang('Conversation.ClousStorageInfo.Description2')}</li>\n <li>{lang('Conversation.ClousStorageInfo.Description3')}</li>\n <li>{lang('Conversation.ClousStorageInfo.Description4')}</li>\n </ul>\n </div>\n </div>\n );\n}\n\nfunction renderGroup(lang: LangFn) {\n return (\n <div className=\"NoMessages\">\n <div className=\"wrapper\" dir={lang.isRtl ? 'rtl' : undefined}>\n <h3 className=\"title\">{lang('EmptyGroupInfo.Title')}</h3>\n <p className=\"description\">{lang('EmptyGroupInfo.Subtitle')}</p>\n <ul className=\"list-checkmarks\">\n <li>{lang('EmptyGroupInfo.Line1')}</li>\n <li>{lang('EmptyGroupInfo.Line2')}</li>\n <li>{lang('EmptyGroupInfo.Line3')}</li>\n <li>{lang('EmptyGroupInfo.Line4')}</li>\n </ul>\n </div>\n </div>\n );\n}\n\nexport default memo(NoMessages);\n","import React, {\n FC, memo, useCallback, useEffect, useMemo, useRef, useState,\n} from '../../lib/teact/teact';\nimport { getGlobal, withGlobal } from '../../lib/teact/teactn';\n\nimport {\n ApiMessage, ApiRestrictionReason, MAIN_THREAD_ID,\n} from '../../api/types';\nimport { GlobalActions, MessageListType } from '../../global/types';\nimport { LoadMoreDirection } from '../../types';\n\nimport { ANIMATION_END_DELAY, LOCAL_MESSAGE_ID_BASE, MESSAGE_LIST_SLICE } from '../../config';\nimport {\n selectChatMessages,\n selectIsViewportNewest,\n selectFirstUnreadId,\n selectFocusedMessageId,\n selectChat,\n selectIsInSelectMode,\n selectIsChatWithSelf,\n selectChatBot,\n selectIsChatBotNotStarted,\n selectScrollOffset,\n selectThreadTopMessageId,\n selectFirstMessageId,\n selectScheduledMessages,\n selectCurrentMessageIds,\n} from '../../modules/selectors';\nimport {\n isChatChannel,\n isUserId,\n isChatWithRepliesBot,\n isChatGroup,\n} from '../../modules/helpers';\nimport { orderBy, pick } from '../../util/iteratees';\nimport { fastRaf, debounce, onTickEnd } from '../../util/schedulers';\nimport useLayoutEffectWithPrevDeps from '../../hooks/useLayoutEffectWithPrevDeps';\nimport useEffectWithPrevDeps from '../../hooks/useEffectWithPrevDeps';\nimport buildClassName from '../../util/buildClassName';\nimport { groupMessages } from './helpers/groupMessages';\nimport { preventMessageInputBlur } from './helpers/preventMessageInputBlur';\nimport useOnChange from '../../hooks/useOnChange';\nimport useStickyDates from './hooks/useStickyDates';\nimport { dispatchHeavyAnimationEvent } from '../../hooks/useHeavyAnimationCheck';\nimport resetScroll from '../../util/resetScroll';\nimport fastSmoothScroll, { isAnimatingScroll } from '../../util/fastSmoothScroll';\nimport renderText from '../common/helpers/renderText';\nimport useLang from '../../hooks/useLang';\nimport useWindowSize from '../../hooks/useWindowSize';\n\nimport Loading from '../ui/Loading';\nimport MessageListContent from './MessageListContent';\nimport ContactGreeting from './ContactGreeting';\nimport NoMessages from './NoMessages';\n\nimport './MessageList.scss';\n\ntype OwnProps = {\n chatId: string;\n threadId: number;\n type: MessageListType;\n canPost: boolean;\n isReady: boolean;\n isActive: boolean;\n onFabToggle: (shouldShow: boolean) => void;\n onNotchToggle: (shouldShow: boolean) => void;\n hasTools?: boolean;\n};\n\ntype StateProps = {\n isChatLoaded?: boolean;\n isChannelChat?: boolean;\n isGroupChat?: boolean;\n isChatWithSelf?: boolean;\n isRepliesChat?: boolean;\n isCreator?: boolean;\n isBot?: boolean;\n messageIds?: number[];\n messagesById?: Record<number, ApiMessage>;\n firstUnreadId?: number;\n isViewportNewest?: boolean;\n isRestricted?: boolean;\n restrictionReason?: ApiRestrictionReason;\n focusingId?: number;\n isSelectModeActive?: boolean;\n animationLevel?: number;\n lastMessage?: ApiMessage;\n botDescription?: string;\n threadTopMessageId?: number;\n threadFirstMessageId?: number;\n hasLinkedChat?: boolean;\n};\n\ntype DispatchProps = Pick<GlobalActions, 'loadViewportMessages' | 'setScrollOffset' | 'openHistoryCalendar'>;\n\nconst BOTTOM_THRESHOLD = 20;\nconst UNREAD_DIVIDER_TOP = 10;\nconst UNREAD_DIVIDER_TOP_WITH_TOOLS = 60;\nconst SCROLL_DEBOUNCE = 200;\nconst FOCUSING_DURATION = 1000;\nconst BOTTOM_FOCUS_MARGIN = 20;\nconst SELECT_MODE_ANIMATION_DURATION = 200;\nconst UNREAD_DIVIDER_CLASS = 'unread-divider';\n\nconst runDebouncedForScroll = debounce((cb) => cb(), SCROLL_DEBOUNCE, false);\n\nconst MessageList: FC<OwnProps & StateProps & DispatchProps> = ({\n chatId,\n threadId,\n type,\n hasTools,\n onFabToggle,\n onNotchToggle,\n isChatLoaded,\n isChannelChat,\n isGroupChat,\n canPost,\n isReady,\n isActive,\n isChatWithSelf,\n isRepliesChat,\n isCreator,\n isBot,\n messageIds,\n messagesById,\n firstUnreadId,\n isViewportNewest,\n threadFirstMessageId,\n isRestricted,\n restrictionReason,\n focusingId,\n isSelectModeActive,\n loadViewportMessages,\n setScrollOffset,\n lastMessage,\n botDescription,\n threadTopMessageId,\n hasLinkedChat,\n openHistoryCalendar,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const containerRef = useRef<HTMLDivElement>(null);\n\n // We update local cached `scrollOffsetRef` when opening chat.\n // Then we update global version every second on scrolling.\n const scrollOffsetRef = useRef<number>((type === 'thread' && selectScrollOffset(getGlobal(), chatId, threadId)) || 0);\n const anchorIdRef = useRef<string>();\n const anchorTopRef = useRef<number>();\n const listItemElementsRef = useRef<HTMLDivElement[]>();\n const memoFirstUnreadIdRef = useRef<number>();\n const memoUnreadDividerBeforeIdRef = useRef<number | undefined>();\n const memoFocusingIdRef = useRef<number>();\n const isScrollTopJustUpdatedRef = useRef(false);\n const shouldAnimateAppearanceRef = useRef(Boolean(lastMessage));\n\n const [containerHeight, setContainerHeight] = useState<number | undefined>();\n\n const areMessagesLoaded = Boolean(messageIds);\n\n useOnChange(() => {\n // We only need it first time when message list appears\n if (areMessagesLoaded) {\n onTickEnd(() => {\n shouldAnimateAppearanceRef.current = false;\n });\n }\n }, [areMessagesLoaded]);\n\n // Updated every time (to be used from intersection callback closure)\n useOnChange(() => {\n memoFirstUnreadIdRef.current = firstUnreadId;\n }, [firstUnreadId]);\n\n // Updated only once when messages are loaded (as we want the unread divider to keep its position)\n useOnChange(() => {\n if (areMessagesLoaded) {\n memoUnreadDividerBeforeIdRef.current = memoFirstUnreadIdRef.current;\n }\n }, [areMessagesLoaded]);\n\n useOnChange(() => {\n memoFocusingIdRef.current = focusingId;\n }, [focusingId]);\n\n const messageGroups = useMemo(() => {\n if (!messageIds || !messagesById) {\n return undefined;\n }\n\n const viewportIds = threadTopMessageId && (!messageIds[0] || threadFirstMessageId === messageIds[0])\n ? [threadTopMessageId, ...messageIds]\n : messageIds;\n\n if (!viewportIds.length) {\n return undefined;\n }\n\n const listedMessages = viewportIds.map((id) => messagesById[id]).filter(Boolean);\n return groupMessages(orderBy(listedMessages, ['date', 'id']), memoUnreadDividerBeforeIdRef.current);\n }, [messageIds, messagesById, threadFirstMessageId, threadTopMessageId]);\n\n const loadMoreAround = useMemo(() => {\n if (type !== 'thread') {\n return undefined;\n }\n\n return debounce(() => loadViewportMessages({ direction: LoadMoreDirection.Around }), 1000, true, false);\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [loadViewportMessages, messageIds]);\n\n const { isScrolled, updateStickyDates } = useStickyDates();\n\n const handleScroll = useCallback(() => {\n if (isScrollTopJustUpdatedRef.current) {\n isScrollTopJustUpdatedRef.current = false;\n return;\n }\n\n const container = containerRef.current!;\n\n if (!memoFocusingIdRef.current) {\n updateStickyDates(container, hasTools);\n }\n\n runDebouncedForScroll(() => {\n fastRaf(() => {\n if (!container.parentElement) {\n return;\n }\n\n scrollOffsetRef.current = container.scrollHeight - container.scrollTop;\n\n if (type === 'thread') {\n setScrollOffset({ chatId, threadId, scrollOffset: scrollOffsetRef.current });\n }\n });\n });\n }, [updateStickyDates, hasTools, type, setScrollOffset, chatId, threadId]);\n\n // Container resize observer (caused by Composer reply/webpage panels)\n useEffect(() => {\n if (!('ResizeObserver' in window) || process.env.APP_ENV === 'perf') {\n return undefined;\n }\n\n const observer = new ResizeObserver(([entry]) => {\n // During animation\n if (!(entry.target as HTMLDivElement).offsetParent) {\n return;\n }\n\n setContainerHeight(entry.contentRect.height);\n });\n\n observer.observe(containerRef.current!);\n\n return () => {\n observer.disconnect();\n };\n }, []);\n\n // Memorize height for scroll animation\n const { height: windowHeight } = useWindowSize();\n\n useEffect(() => {\n if (isReady) {\n containerRef.current!.dataset.normalHeight = String(containerRef.current!.offsetHeight);\n }\n }, [windowHeight, isReady, canPost]);\n\n // Initial message loading\n useEffect(() => {\n if (!loadMoreAround || !isChatLoaded || isRestricted || focusingId) {\n return;\n }\n\n // Loading history while sending a message can return the same message and cause ambiguity\n const isLastMessageLocal = messageIds && messageIds[messageIds.length - 1] >= LOCAL_MESSAGE_ID_BASE;\n if (isLastMessageLocal) {\n return;\n }\n\n const container = containerRef.current!;\n\n if (!messageIds || (\n messageIds.length < MESSAGE_LIST_SLICE / 2\n && (container.firstElementChild as HTMLDivElement).clientHeight <= container.offsetHeight\n )) {\n loadMoreAround();\n }\n }, [isChatLoaded, messageIds, loadMoreAround, focusingId, isRestricted]);\n\n // Remember scroll position before repositioning it\n useOnChange(() => {\n if (!messageIds || !listItemElementsRef.current || !isReady) {\n return;\n }\n\n const preservedItemElements = listItemElementsRef.current\n .filter((element) => messageIds.includes(Number(element.dataset.messageId)));\n\n // We avoid the very first item as it may be a partly-loaded album\n // and also because it may be removed when messages limit is reached\n const anchor = preservedItemElements[1] || preservedItemElements[0];\n if (!anchor) {\n return;\n }\n\n anchorIdRef.current = anchor.id;\n anchorTopRef.current = anchor.getBoundingClientRect().top;\n // This should match deps for `useLayoutEffectWithPrevDeps` below\n }, [messageIds, isViewportNewest, containerHeight, hasTools, isReady]);\n\n // Handles updated message list, takes care of scroll repositioning\n useLayoutEffectWithPrevDeps(([\n prevMessageIds, prevIsViewportNewest, prevContainerHeight,\n ]: [\n typeof messageIds, typeof isViewportNewest, typeof containerHeight,\n ]) => {\n const container = containerRef.current!;\n listItemElementsRef.current = Array.from(container.querySelectorAll<HTMLDivElement>('.message-list-item'));\n\n // During animation\n if (!container.offsetParent) {\n return;\n }\n\n // Add extra height when few messages to allow smooth scroll animation. Uses assumption that `parentElement`\n // is a Transition slide and its CSS class can not be reset in a declarative way.\n const shouldForceScroll = (\n isViewportNewest\n && (messageIds && messageIds.length < MESSAGE_LIST_SLICE / 2)\n && !container.parentElement!.classList.contains('force-messages-scroll')\n && (container.firstElementChild as HTMLDivElement)!.clientHeight <= container.offsetHeight * 2\n );\n\n if (shouldForceScroll) {\n container.parentElement!.classList.add('force-messages-scroll');\n\n setTimeout(() => {\n if (container.parentElement) {\n container.parentElement.classList.remove('force-messages-scroll');\n }\n }, FOCUSING_DURATION);\n }\n\n const hasLastMessageChanged = (\n messageIds && prevMessageIds && messageIds[messageIds.length - 1] !== prevMessageIds[prevMessageIds.length - 1]\n );\n const hasViewportShifted = (\n messageIds?.[0] !== prevMessageIds?.[0] && messageIds?.length === (MESSAGE_LIST_SLICE / 2 + 1)\n );\n const wasMessageAdded = hasLastMessageChanged && !hasViewportShifted;\n const isAlreadyFocusing = messageIds && memoFocusingIdRef.current === messageIds[messageIds.length - 1];\n\n const { scrollTop, scrollHeight, offsetHeight } = container;\n const scrollOffset = scrollOffsetRef.current!;\n const lastItemElement = listItemElementsRef.current[listItemElementsRef.current.length - 1];\n\n let bottomOffset = scrollOffset - (prevContainerHeight || offsetHeight);\n if (wasMessageAdded) {\n // If two new messages come at once (e.g. when bot responds) then the first message will update `scrollOffset`\n // right away (before animation) which creates inconsistency until the animation completes. To workaround that,\n // we calculate `isAtBottom` with a \"buffer\" of the latest message height (this is approximate).\n const lastItemHeight = lastItemElement ? lastItemElement.offsetHeight : 0;\n bottomOffset -= lastItemHeight;\n }\n const isAtBottom = isViewportNewest && prevIsViewportNewest && bottomOffset <= BOTTOM_THRESHOLD;\n\n let newScrollTop!: number;\n\n if (wasMessageAdded && isAtBottom && !isAlreadyFocusing) {\n if (lastItemElement) {\n fastRaf(() => {\n fastSmoothScroll(\n container,\n lastItemElement,\n 'end',\n BOTTOM_FOCUS_MARGIN,\n );\n });\n }\n\n newScrollTop = scrollHeight - offsetHeight;\n scrollOffsetRef.current = Math.max(Math.ceil(scrollHeight - newScrollTop), offsetHeight);\n\n // Scroll still needs to be restored after container resize\n if (!shouldForceScroll) {\n return;\n }\n }\n\n if (process.env.APP_ENV === 'perf') {\n // eslint-disable-next-line no-console\n console.time('scrollTop');\n }\n\n const isResized = prevContainerHeight !== undefined && prevContainerHeight !== containerHeight;\n const anchor = anchorIdRef.current && document.getElementById(anchorIdRef.current);\n const unreadDivider = (\n !anchor\n && memoUnreadDividerBeforeIdRef.current\n && container.querySelector<HTMLDivElement>(`.${UNREAD_DIVIDER_CLASS}`)\n );\n\n if (isAtBottom && isResized) {\n if (isAnimatingScroll()) {\n return;\n }\n\n newScrollTop = scrollHeight - offsetHeight;\n } else if (anchor) {\n const newAnchorTop = anchor.getBoundingClientRect().top;\n newScrollTop = scrollTop + (newAnchorTop - (anchorTopRef.current || 0));\n } else if (unreadDivider) {\n newScrollTop = Math.min(\n unreadDivider.offsetTop - (hasTools ? UNREAD_DIVIDER_TOP_WITH_TOOLS : UNREAD_DIVIDER_TOP),\n scrollHeight - scrollOffset,\n );\n } else {\n newScrollTop = scrollHeight - scrollOffset;\n }\n\n resetScroll(container, Math.ceil(newScrollTop));\n\n if (!memoFocusingIdRef.current) {\n isScrollTopJustUpdatedRef.current = true;\n fastRaf(() => {\n isScrollTopJustUpdatedRef.current = false;\n });\n }\n\n scrollOffsetRef.current = Math.max(Math.ceil(scrollHeight - newScrollTop), offsetHeight);\n\n if (process.env.APP_ENV === 'perf') {\n // eslint-disable-next-line no-console\n console.timeEnd('scrollTop');\n }\n // This should match deps for `useOnChange` above\n }, [messageIds, isViewportNewest, containerHeight, hasTools]);\n\n useEffectWithPrevDeps(([prevIsSelectModeActive]) => {\n if (prevIsSelectModeActive !== undefined) {\n dispatchHeavyAnimationEvent(SELECT_MODE_ANIMATION_DURATION + ANIMATION_END_DELAY);\n }\n }, [isSelectModeActive]);\n\n const lang = useLang();\n\n const isPrivate = Boolean(chatId && isUserId(chatId));\n const withUsers = Boolean((!isPrivate && !isChannelChat) || isChatWithSelf || isRepliesChat);\n const noAvatars = Boolean(!withUsers || isChannelChat);\n const shouldRenderGreeting = isUserId(chatId) && !isChatWithSelf && !isBot\n && (\n (\n !messageGroups && !lastMessage && messageIds\n // Used to avoid flickering when deleting a greeting that has just been sent\n && (!listItemElementsRef.current || listItemElementsRef.current.length === 0)\n )\n || (messageIds?.length === 1 && messagesById?.[messageIds[0]]?.content.action?.type === 'contactSignUp')\n || (lastMessage?.content?.action?.type === 'contactSignUp')\n );\n\n const isGroupChatJustCreated = isGroupChat && isCreator\n && messageIds?.length === 1 && messagesById?.[messageIds[0]]?.content.action?.type === 'chatCreate';\n\n const className = buildClassName(\n 'MessageList custom-scroll',\n noAvatars && 'no-avatars',\n !canPost && 'no-composer',\n type === 'pinned' && 'type-pinned',\n isSelectModeActive && 'select-mode-active',\n isScrolled && 'scrolled',\n !isReady && 'is-animating',\n );\n\n return (\n <div\n ref={containerRef}\n className={className}\n onScroll={handleScroll}\n onMouseDown={preventMessageInputBlur}\n >\n {isRestricted ? (\n <div className=\"empty\">\n <span>\n {restrictionReason ? restrictionReason.text : `This is a private ${isChannelChat ? 'channel' : 'chat'}`}\n </span>\n </div>\n ) : botDescription ? (\n <div className=\"empty\"><span>{renderText(lang(botDescription), ['br', 'emoji', 'links'])}</span></div>\n ) : shouldRenderGreeting ? (\n <ContactGreeting userId={chatId} />\n ) : messageIds && (!messageGroups || isGroupChatJustCreated) ? (\n <NoMessages\n chatId={chatId}\n type={type}\n isChatWithSelf={isChatWithSelf}\n isGroupChatJustCreated={isGroupChatJustCreated}\n />\n ) : ((messageIds && messageGroups) || lastMessage) ? (\n <MessageListContent\n messageIds={messageIds || [lastMessage!.id]}\n messageGroups={messageGroups || groupMessages([lastMessage!])}\n isViewportNewest={Boolean(isViewportNewest)}\n isUnread={Boolean(firstUnreadId)}\n withUsers={withUsers}\n noAvatars={noAvatars}\n containerRef={containerRef}\n anchorIdRef={anchorIdRef}\n memoUnreadDividerBeforeIdRef={memoUnreadDividerBeforeIdRef}\n memoFirstUnreadIdRef={memoFirstUnreadIdRef}\n threadId={threadId}\n type={type}\n isActive={isActive}\n threadTopMessageId={threadTopMessageId}\n hasLinkedChat={hasLinkedChat}\n isSchedule={messageGroups ? type === 'scheduled' : false}\n noAppearanceAnimation={!messageGroups || !shouldAnimateAppearanceRef.current}\n onFabToggle={onFabToggle}\n onNotchToggle={onNotchToggle}\n openHistoryCalendar={openHistoryCalendar}\n />\n ) : (\n <Loading color=\"white\" />\n )}\n </div>\n );\n};\n\nexport default memo(withGlobal<OwnProps>(\n (global, { chatId, threadId, type }): StateProps => {\n const chat = selectChat(global, chatId);\n if (!chat) {\n return {};\n }\n\n const messageIds = selectCurrentMessageIds(global, chatId, threadId, type);\n const messagesById = type === 'scheduled'\n ? selectScheduledMessages(global, chatId)\n : selectChatMessages(global, chatId);\n const threadTopMessageId = selectThreadTopMessageId(global, chatId, threadId);\n\n if (\n threadId !== MAIN_THREAD_ID\n && !(messagesById && threadTopMessageId && messagesById[threadTopMessageId])\n ) {\n return {};\n }\n\n const { isRestricted, restrictionReason, lastMessage } = chat;\n const focusingId = selectFocusedMessageId(global, chatId);\n\n const withLastMessageWhenPreloading = (\n threadId === MAIN_THREAD_ID\n && !messageIds && !chat.unreadCount && !focusingId && lastMessage && !lastMessage.groupedId\n );\n\n const chatBot = selectChatBot(global, chatId)!;\n let botDescription: string | undefined;\n if (selectIsChatBotNotStarted(global, chatId)) {\n if (chatBot.fullInfo) {\n botDescription = chatBot.fullInfo.botDescription || 'NoMessages';\n } else {\n botDescription = 'Updating bot info...';\n }\n }\n\n return {\n isChatLoaded: true,\n isRestricted,\n restrictionReason,\n isChannelChat: isChatChannel(chat),\n isGroupChat: isChatGroup(chat),\n isCreator: chat.isCreator,\n isChatWithSelf: selectIsChatWithSelf(global, chatId),\n isRepliesChat: isChatWithRepliesBot(chatId),\n isBot: Boolean(chatBot),\n messageIds,\n messagesById,\n firstUnreadId: selectFirstUnreadId(global, chatId, threadId),\n isViewportNewest: type !== 'thread' || selectIsViewportNewest(global, chatId, threadId),\n threadFirstMessageId: selectFirstMessageId(global, chatId, threadId),\n focusingId,\n isSelectModeActive: selectIsInSelectMode(global),\n botDescription,\n threadTopMessageId,\n hasLinkedChat: chat.fullInfo && ('linkedChatId' in chat.fullInfo)\n ? Boolean(chat.fullInfo.linkedChatId)\n : undefined,\n ...(withLastMessageWhenPreloading && { lastMessage }),\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'loadViewportMessages',\n 'setScrollOffset',\n 'openHistoryCalendar',\n ]),\n)(MessageList));\n","import { useCallback } from '../../../lib/teact/teact';\n\nimport { fastRaf } from '../../../util/schedulers';\nimport useDebounce from '../../../hooks/useDebounce';\nimport useFlag from '../../../hooks/useFlag';\n\nconst DEBOUNCE = 1000;\nconst STICKY_TOP = 10;\nconst STICKY_TOP_WITH_TOOLS = 60;\n\nexport default function useStickyDates() {\n // For some reason we can not synchronously hide a sticky element (from `useLayoutEffect`) when chat opens\n // so we will add `position: sticky` only after first scroll. There would be no animation on the first show though.\n const [isScrolled, markIsScrolled] = useFlag(false);\n\n const runDebounced = useDebounce(DEBOUNCE, false);\n\n const updateStickyDates = useCallback((container: HTMLDivElement, hasTools?: boolean) => {\n markIsScrolled();\n\n if (!document.body.classList.contains('is-scrolling-messages')) {\n fastRaf(() => {\n document.body.classList.add('is-scrolling-messages');\n });\n }\n\n runDebounced(() => {\n fastRaf(() => {\n const currentStuck = document.querySelector('.stuck');\n if (currentStuck) {\n currentStuck.classList.remove('stuck');\n }\n\n const stuckDateEl = findStuckDate(container, hasTools);\n if (stuckDateEl) {\n stuckDateEl.classList.add('stuck');\n }\n\n document.body.classList.remove('is-scrolling-messages');\n });\n });\n }, [markIsScrolled, runDebounced]);\n\n return {\n isScrolled,\n updateStickyDates,\n };\n}\n\nfunction findStuckDate(container: HTMLElement, hasTools?: boolean) {\n const allElements = container.querySelectorAll<HTMLDivElement>('.sticky-date');\n const containerTop = container.scrollTop;\n\n return Array.from(allElements).find((el) => {\n const { offsetTop, offsetHeight } = el;\n const top = offsetTop - containerTop;\n return -offsetHeight <= top && top <= (hasTools ? STICKY_TOP_WITH_TOOLS : STICKY_TOP);\n });\n}\n","import React, {\n FC, useCallback, memo, useRef,\n} from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { GlobalActions, MessageListType } from '../../global/types';\nimport { MAIN_THREAD_ID } from '../../api/types';\n\nimport { selectChat, selectCurrentMessageList } from '../../modules/selectors';\nimport { formatIntegerCompact } from '../../util/textFormat';\nimport buildClassName from '../../util/buildClassName';\nimport { pick } from '../../util/iteratees';\nimport fastSmoothScroll from '../../util/fastSmoothScroll';\nimport useLang from '../../hooks/useLang';\n\nimport Button from '../ui/Button';\n\nimport './ScrollDownButton.scss';\n\ntype OwnProps = {\n isShown: boolean;\n canPost?: boolean;\n withExtraShift?: boolean;\n};\n\ntype StateProps = {\n messageListType?: MessageListType;\n unreadCount?: number;\n};\n\ntype DispatchProps = Pick<GlobalActions, 'focusNextReply'>;\n\nconst FOCUS_MARGIN = 20;\n\nconst ScrollDownButton: FC<OwnProps & StateProps & DispatchProps> = ({\n isShown,\n canPost,\n messageListType,\n unreadCount,\n withExtraShift,\n focusNextReply,\n}) => {\n const lang = useLang();\n // eslint-disable-next-line no-null/no-null\n const elementRef = useRef<HTMLDivElement>(null);\n\n const handleClick = useCallback(() => {\n if (!isShown) {\n return;\n }\n\n if (messageListType === 'thread') {\n focusNextReply();\n } else {\n const messagesContainer = elementRef.current!.parentElement!.querySelector<HTMLDivElement>('.MessageList')!;\n const messageElements = messagesContainer.querySelectorAll<HTMLDivElement>('.message-list-item');\n const lastMessageElement = messageElements[messageElements.length - 1];\n if (!lastMessageElement) {\n return;\n }\n\n fastSmoothScroll(messagesContainer, lastMessageElement, 'end', FOCUS_MARGIN);\n }\n }, [isShown, messageListType, focusNextReply]);\n\n const fabClassName = buildClassName(\n 'ScrollDownButton',\n isShown && 'revealed',\n !canPost && 'no-composer',\n withExtraShift && 'with-extra-shift',\n );\n\n return (\n <div ref={elementRef} className={fabClassName}>\n <div className=\"ScrollDownButton-inner\">\n <Button\n color=\"secondary\"\n round\n onClick={handleClick}\n ariaLabel={lang('AccDescrPageDown')}\n >\n <i className=\"icon-arrow-down\" />\n </Button>\n {Boolean(unreadCount) && (\n <div className=\"unread-count\">{formatIntegerCompact(unreadCount!)}</div>\n )}\n </div>\n </div>\n );\n};\n\nexport default memo(withGlobal<OwnProps>(\n (global): StateProps => {\n const currentMessageList = selectCurrentMessageList(global);\n if (!currentMessageList) {\n return {};\n }\n\n const { chatId, threadId, type: messageListType } = currentMessageList;\n const chat = selectChat(global, chatId);\n\n return {\n messageListType,\n unreadCount: chat && threadId === MAIN_THREAD_ID && messageListType === 'thread' ? chat.unreadCount : undefined,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, ['focusNextReply']),\n)(ScrollDownButton));\n","import { ApiAttachment } from '../../../../api/types';\nimport { SUPPORTED_IMAGE_CONTENT_TYPES, SUPPORTED_VIDEO_CONTENT_TYPES } from '../../../../config';\nimport {\n preloadImage,\n preloadVideo,\n createPosterForVideo,\n fetchBlob,\n} from '../../../../util/files';\nimport { scaleImage } from '../../../../util/imageResize';\n\nconst MAX_QUICK_IMG_SIZE = 1280; // px\nconst FILE_EXT_REGEX = /\\.[^/.]+$/;\n\nexport default async function buildAttachment(\n filename: string, blob: Blob, isQuick: boolean, options?: Partial<ApiAttachment>,\n): Promise<ApiAttachment> {\n const blobUrl = URL.createObjectURL(blob);\n const { type: mimeType, size } = blob;\n let quick;\n let previewBlobUrl;\n\n if (SUPPORTED_IMAGE_CONTENT_TYPES.has(mimeType)) {\n if (isQuick) {\n const img = await preloadImage(blobUrl);\n const { width, height } = img;\n\n if (width > MAX_QUICK_IMG_SIZE || height > MAX_QUICK_IMG_SIZE || mimeType !== 'image/jpeg') {\n const resizedUrl = await scaleImage(blobUrl, MAX_QUICK_IMG_SIZE / Math.max(width, height), 'image/jpeg');\n URL.revokeObjectURL(blobUrl);\n const newBlob = await fetchBlob(resizedUrl);\n return buildAttachment(filename, newBlob, true, options);\n }\n\n if (mimeType === 'image/jpeg') {\n filename = filename.replace(FILE_EXT_REGEX, '.jpg');\n }\n\n quick = { width, height };\n } else {\n previewBlobUrl = blobUrl;\n }\n } else if (SUPPORTED_VIDEO_CONTENT_TYPES.has(mimeType)) {\n const { videoWidth: width, videoHeight: height, duration } = await preloadVideo(blobUrl);\n quick = { width, height, duration };\n\n previewBlobUrl = await createPosterForVideo(blobUrl);\n }\n\n return {\n blobUrl,\n filename,\n mimeType,\n size,\n quick,\n previewBlobUrl,\n ...options,\n };\n}\n","import { IS_IOS } from '../../../../util/environment';\n\nlet resetInput: HTMLInputElement;\n\nif (IS_IOS) {\n resetInput = document.createElement('input');\n resetInput.classList.add('for-ios-autocapitalization-fix');\n document.body.appendChild(resetInput);\n}\n\n// https://stackoverflow.com/a/55652503\nexport default function applyIosAutoCapitalizationFix(inputEl: HTMLElement) {\n resetInput.focus();\n inputEl.focus();\n}\n","export default __webpack_public_path__ + \"c0155344d336103c2b6a0b28cc510750.js\";","// @ts-ignore\nimport encoderPath from 'file-loader!opus-recorder/dist/encoderWorker.min';\n\nexport type Result = { blob: Blob; duration: number; waveform: number[] };\n\ninterface IOpusRecorder extends Omit<MediaRecorder, 'start' | 'ondataavailable'> {\n new(options: AnyLiteral): IOpusRecorder;\n\n start(stream?: MediaStreamAudioSourceNode): void;\n\n sourceNode: MediaStreamAudioSourceNode;\n\n ondataavailable: (typedArray: Uint8Array) => void;\n}\n\nconst MIN_RECORDING_TIME = 1000;\nconst POLYFILL_OPTIONS = { encoderPath, reuseWorker: true };\nconst BLOB_PARAMS = { type: 'audio/ogg' };\nconst FFT_SIZE = 64;\nconst MIN_VOLUME = 0.1;\n\nlet opusRecorderPromise: Promise<{ default: IOpusRecorder }>;\nlet OpusRecorder: IOpusRecorder;\nlet mediaRecorder: IOpusRecorder;\n\nexport async function init() {\n if (!opusRecorderPromise) {\n // @ts-ignore\n opusRecorderPromise = import('opus-recorder');\n OpusRecorder = (await opusRecorderPromise).default;\n mediaRecorder = new OpusRecorder(POLYFILL_OPTIONS);\n }\n\n return opusRecorderPromise;\n}\n\nexport async function start(analyzerCallback: Function) {\n await startMediaRecorder();\n\n const startedAt = Date.now();\n let pausedAt: number;\n const chunks: Uint8Array[] = [];\n const waveform: number[] = [];\n\n mediaRecorder.ondataavailable = (typedArray) => {\n chunks.push(typedArray);\n };\n\n const releaseAnalyzer = subscribeToAnalyzer(mediaRecorder, (volume: number) => {\n waveform.push(volume * 255);\n analyzerCallback(volume);\n });\n\n return {\n stop: () => new Promise<Result>((resolve, reject) => {\n mediaRecorder.onstop = () => {\n resolve({\n blob: new Blob(chunks, BLOB_PARAMS),\n duration: Math.round(((pausedAt || Date.now()) - startedAt) / 1000),\n waveform,\n });\n };\n mediaRecorder.onerror = reject;\n\n const delayStop = Math.max(0, startedAt + MIN_RECORDING_TIME - Date.now());\n setTimeout(() => {\n mediaRecorder.stop();\n releaseAnalyzer();\n }, delayStop);\n }),\n pause: () => {\n const delayStop = Math.max(0, startedAt + MIN_RECORDING_TIME - Date.now());\n setTimeout(() => {\n mediaRecorder.pause();\n pausedAt = Date.now();\n releaseAnalyzer();\n }, delayStop);\n },\n };\n}\n\nasync function startMediaRecorder() {\n await init();\n await mediaRecorder.start();\n}\n\nfunction subscribeToAnalyzer(recorder: IOpusRecorder, cb: Function) {\n const source = recorder.sourceNode;\n const analyser = source.context.createAnalyser();\n analyser.fftSize = FFT_SIZE;\n source.connect(analyser);\n\n const dataLength = analyser.frequencyBinCount;\n const dataArray = new Uint8Array(dataLength);\n let isDestroyed = false;\n\n function tick() {\n if (isDestroyed) {\n return;\n }\n\n analyser.getByteFrequencyData(dataArray);\n\n const sum = dataArray.reduce((acc, current) => acc + current, 0);\n const mean = (sum / dataLength);\n const volume = mean / 255;\n\n cb(volume < MIN_VOLUME ? 0 : volume);\n\n requestAnimationFrame(tick);\n }\n\n tick();\n\n return () => {\n isDestroyed = true;\n };\n}\n","import {\n useCallback, useEffect, useRef, useState,\n} from '../../../../lib/teact/teact';\n\nimport { IS_SAFARI, IS_VOICE_RECORDING_SUPPORTED } from '../../../../util/environment';\nimport * as voiceRecording from '../../../../util/voiceRecording';\nimport captureEscKeyListener from '../../../../util/captureEscKeyListener';\n\ntype ActiveVoiceRecording = { stop: () => Promise<voiceRecording.Result>; pause: NoneToVoidFunction } | undefined;\n\nexport default () => {\n // eslint-disable-next-line no-null/no-null\n const recordButtonRef = useRef<HTMLButtonElement>(null);\n const [activeVoiceRecording, setActiveVoiceRecording] = useState<ActiveVoiceRecording>();\n const startRecordTimeRef = useRef<number>();\n const [currentRecordTime, setCurrentRecordTime] = useState<number | undefined>();\n\n useEffect(() => {\n // Preloading worker fixes silent first record on iOS\n if (IS_SAFARI && IS_VOICE_RECORDING_SUPPORTED) {\n void voiceRecording.init();\n }\n }, []);\n\n const startRecordingVoice = useCallback(async () => {\n try {\n const { stop, pause } = await voiceRecording.start((tickVolume: number) => {\n if (recordButtonRef.current) {\n if (startRecordTimeRef.current && Date.now() % 4 === 0) {\n recordButtonRef.current.style.boxShadow = `0 0 0 ${(tickVolume || 0) * 50}px rgba(0,0,0,.15)`;\n }\n setCurrentRecordTime(Date.now());\n }\n });\n startRecordTimeRef.current = Date.now();\n setCurrentRecordTime(Date.now());\n\n setActiveVoiceRecording({ stop, pause });\n } catch (err) {\n // eslint-disable-next-line no-console\n console.error(err);\n }\n }, []);\n\n const pauseRecordingVoice = useCallback(() => {\n if (!activeVoiceRecording) {\n return undefined;\n }\n\n if (recordButtonRef.current) {\n recordButtonRef.current.style.boxShadow = 'none';\n }\n\n try {\n return activeVoiceRecording!.pause();\n } catch (err) {\n // eslint-disable-next-line no-console\n console.error(err);\n return undefined;\n }\n }, [activeVoiceRecording]);\n\n const stopRecordingVoice = useCallback(() => {\n if (!activeVoiceRecording) {\n return undefined;\n }\n\n setActiveVoiceRecording(undefined);\n startRecordTimeRef.current = undefined;\n setCurrentRecordTime(undefined);\n if (recordButtonRef.current) {\n recordButtonRef.current.style.boxShadow = 'none';\n }\n try {\n return activeVoiceRecording!.stop();\n } catch (err) {\n // eslint-disable-next-line no-console\n console.error(err);\n return undefined;\n }\n }, [activeVoiceRecording]);\n\n useEffect(() => {\n return activeVoiceRecording ? captureEscKeyListener(stopRecordingVoice) : undefined;\n }, [activeVoiceRecording, stopRecordingVoice]);\n\n return {\n startRecordingVoice,\n pauseRecordingVoice,\n stopRecordingVoice,\n activeVoiceRecording,\n currentRecordTime,\n recordButtonRef,\n startRecordTimeRef,\n };\n};\n","import { StateHookSetter, useEffect } from '../../../../lib/teact/teact';\nimport { ApiAttachment, ApiMessage } from '../../../../api/types';\n\nimport buildAttachment from '../helpers/buildAttachment';\nimport { EDITABLE_INPUT_ID, EDITABLE_INPUT_MODAL_ID } from '../../../../config';\n\nconst CLIPBOARD_ACCEPTED_TYPES = ['image/png', 'image/jpeg', 'image/gif'];\nconst MAX_MESSAGE_LENGTH = 4096;\n\nexport default (\n insertTextAndUpdateCursor: (text: string, inputId?: string) => void,\n setAttachments: StateHookSetter<ApiAttachment[]>,\n editedMessage: ApiMessage | undefined,\n) => {\n useEffect(() => {\n async function handlePaste(e: ClipboardEvent) {\n if (!e.clipboardData) {\n return;\n }\n\n const input = document.activeElement;\n if (input && ![EDITABLE_INPUT_ID, EDITABLE_INPUT_MODAL_ID].includes(input.id)) {\n return;\n }\n\n const { items } = e.clipboardData;\n const media = Array.from(items)\n .find((item) => CLIPBOARD_ACCEPTED_TYPES.includes(item.type) && item.kind === 'file');\n const file = media && media.getAsFile();\n const pastedText = e.clipboardData.getData('text').substring(0, MAX_MESSAGE_LENGTH);\n\n e.preventDefault();\n\n if (!file && !pastedText) {\n return;\n }\n\n if (file && !editedMessage) {\n const attachment = await buildAttachment(file.name, file, true);\n setAttachments((attachments) => [\n ...attachments,\n attachment,\n ]);\n }\n\n if (pastedText) {\n insertTextAndUpdateCursor(pastedText, input?.id);\n }\n }\n\n document.addEventListener('paste', handlePaste, false);\n\n return () => {\n document.removeEventListener('paste', handlePaste, false);\n };\n }, [insertTextAndUpdateCursor, editedMessage, setAttachments]);\n};\n","import { ApiFormattedText } from '../../../../api/types';\nimport { renderTextWithEntities } from '../../../common/helpers/renderMessageText';\n\nexport default function getMessageTextAsHtml(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","import { useCallback, useEffect, useMemo } from '../../../../lib/teact/teact';\n\nimport { ApiFormattedText, ApiMessage } from '../../../../api/types';\nimport { GlobalActions } from '../../../../global/types';\n\nimport { DRAFT_DEBOUNCE, EDITABLE_INPUT_ID } from '../../../../config';\nimport usePrevious from '../../../../hooks/usePrevious';\nimport { debounce } from '../../../../util/schedulers';\nimport focusEditableElement from '../../../../util/focusEditableElement';\nimport parseMessageInput from '../../../../util/parseMessageInput';\nimport getMessageTextAsHtml from '../helpers/getMessageTextAsHtml';\nimport useBackgroundMode from '../../../../hooks/useBackgroundMode';\nimport useBeforeUnload from '../../../../hooks/useBeforeUnload';\nimport { IS_TOUCH_ENV } from '../../../../util/environment';\n\n// Used to avoid running debounced callbacks when chat changes.\nlet currentChatId: string | undefined;\nlet currentThreadId: number | undefined;\n\nexport default (\n draft: ApiFormattedText | undefined,\n chatId: string,\n threadId: number,\n html: string,\n htmlRef: { current: string },\n setHtml: (html: string) => void,\n editedMessage: ApiMessage | undefined,\n saveDraft: GlobalActions['saveDraft'],\n clearDraft: GlobalActions['clearDraft'],\n) => {\n const updateDraft = useCallback((draftChatId: string, draftThreadId: number) => {\n if (htmlRef.current.length && !editedMessage) {\n saveDraft({ chatId: draftChatId, threadId: draftThreadId, draft: parseMessageInput(htmlRef.current!) });\n } else {\n clearDraft({ chatId: draftChatId, threadId: draftThreadId });\n }\n }, [clearDraft, editedMessage, htmlRef, saveDraft]);\n\n // eslint-disable-next-line react-hooks/exhaustive-deps\n const runDebouncedForSaveDraft = useMemo(() => debounce((cb) => cb(), DRAFT_DEBOUNCE, false), [chatId]);\n\n const prevChatId = usePrevious(chatId);\n const prevThreadId = usePrevious(threadId);\n\n // Save draft on chat change\n useEffect(() => {\n currentChatId = chatId;\n currentThreadId = threadId;\n\n return () => {\n currentChatId = undefined;\n currentThreadId = undefined;\n\n updateDraft(chatId, threadId);\n };\n }, [chatId, threadId, updateDraft]);\n\n // Restore draft on chat change\n useEffect(() => {\n if (chatId === prevChatId && threadId === prevThreadId) {\n return;\n }\n\n if (!draft) {\n return;\n }\n\n setHtml(getMessageTextAsHtml(draft));\n\n if (!IS_TOUCH_ENV) {\n requestAnimationFrame(() => {\n const messageInput = document.getElementById(EDITABLE_INPUT_ID)!;\n focusEditableElement(messageInput, true);\n });\n }\n }, [chatId, threadId, draft, setHtml, updateDraft, prevChatId, prevThreadId]);\n\n // Update draft when input changes\n const prevHtml = usePrevious(html);\n useEffect(() => {\n if (!chatId || !threadId || prevChatId !== chatId || prevThreadId !== threadId || prevHtml === html) {\n return;\n }\n\n if (html.length) {\n runDebouncedForSaveDraft(() => {\n if (currentChatId !== chatId || currentThreadId !== threadId) {\n return;\n }\n\n updateDraft(chatId, threadId);\n });\n } else {\n updateDraft(chatId, threadId);\n }\n }, [chatId, html, prevChatId, prevHtml, prevThreadId, runDebouncedForSaveDraft, threadId, updateDraft]);\n\n const handleBlur = useCallback(() => {\n if (chatId && threadId) {\n updateDraft(chatId, threadId);\n }\n }, [chatId, threadId, updateDraft]);\n\n useBackgroundMode(handleBlur);\n useBeforeUnload(handleBlur);\n};\n","import { useCallback, useEffect } from '../../../../lib/teact/teact';\nimport { getDispatch } from '../../../../lib/teact/teactn';\nimport { InlineBotSettings } from '../../../../types';\nimport useFlag from '../../../../hooks/useFlag';\nimport usePrevious from '../../../../hooks/usePrevious';\n\nconst tempEl = document.createElement('div');\nconst INLINE_BOT_QUERY_REGEXP = /^@([a-z0-9_]{1,32})[\\u00A0\\u0020]+(.*)/i;\nconst HAS_NEW_LINE = /^@([a-z0-9_]{1,32})[\\u00A0\\u0020]+\\n{2,}/i;\n\nexport default function useInlineBotTooltip(\n isAllowed: boolean,\n chatId: string,\n html: string,\n inlineBots?: Record<string, false | InlineBotSettings>,\n) {\n const [isOpen, markIsOpen, unmarkIsOpen] = useFlag();\n const text = getPlainText(html);\n const { queryInlineBot, resetInlineBot } = getDispatch();\n const { username, query, canShowHelp } = parseStartWithUsernameString(text);\n const usernameLowered = username.toLowerCase();\n const prevQuery = usePrevious(query);\n const prevUsername = usePrevious(username);\n const inlineBotData = inlineBots?.[usernameLowered];\n const {\n id: botId,\n switchPm,\n offset,\n results,\n isGallery,\n help,\n } = inlineBotData || {};\n\n useEffect(() => {\n if (prevQuery !== query) {\n unmarkIsOpen();\n }\n }, [prevQuery, query, unmarkIsOpen]);\n\n useEffect(() => {\n if (isAllowed && usernameLowered && chatId) {\n queryInlineBot({ chatId, username: usernameLowered, query });\n }\n }, [query, isAllowed, queryInlineBot, chatId, usernameLowered]);\n\n const loadMore = useCallback(() => {\n queryInlineBot({\n chatId, username: usernameLowered, query, offset,\n });\n }, [offset, chatId, query, queryInlineBot, usernameLowered]);\n\n useEffect(() => {\n if (isAllowed && botId && (switchPm || (results?.length))) {\n markIsOpen();\n } else {\n unmarkIsOpen();\n }\n }, [botId, isAllowed, markIsOpen, results, switchPm, unmarkIsOpen]);\n\n if (prevUsername !== username) {\n resetInlineBot({ username: prevUsername });\n }\n\n return {\n isOpen,\n closeTooltip: unmarkIsOpen,\n loadMore,\n username,\n id: botId,\n isGallery,\n switchPm,\n results,\n help: canShowHelp && help ? `@${username} ${help}` : undefined,\n };\n}\n\nfunction getPlainText(html: string) {\n tempEl.innerHTML = html.replace(/<br>/g, '\\n');\n\n return tempEl.innerText;\n}\n\nfunction parseStartWithUsernameString(text: string) {\n const result = text.match(INLINE_BOT_QUERY_REGEXP);\n if (!result) {\n return { username: '', query: '', canShowHelp: false };\n }\n\n return {\n username: result[1],\n query: result[2],\n canShowHelp: result[2] === '' && !text.match(HAS_NEW_LINE),\n };\n}\n","import {\n useCallback, useEffect, useState,\n} from '../../../../lib/teact/teact';\n\nimport { ApiBotCommand } from '../../../../api/types';\n\nimport { prepareForRegExp } from '../helpers/prepareForRegExp';\nimport { throttle } from '../../../../util/schedulers';\nimport useFlag from '../../../../hooks/useFlag';\n\nconst runThrottled = throttle((cb) => cb(), 500, true);\nconst RE_COMMAND = /^[\\w@]{1,32}\\s?/i;\n\nexport default function useBotCommandTooltip(\n isAllowed: boolean,\n html: string,\n botCommands?: ApiBotCommand[] | false,\n chatBotCommands?: ApiBotCommand[],\n) {\n const [isOpen, markIsOpen, unmarkIsOpen] = useFlag();\n const [filteredBotCommands, setFilteredBotCommands] = useState<ApiBotCommand[] | undefined>();\n\n const getFilteredCommands = useCallback((filter) => {\n if (!botCommands && !chatBotCommands) {\n setFilteredBotCommands(undefined);\n\n return;\n }\n\n runThrottled(() => {\n const nextFilteredBotCommands = (botCommands || chatBotCommands || [])\n .filter(({ command }) => !filter || command.includes(filter));\n setFilteredBotCommands(\n nextFilteredBotCommands && nextFilteredBotCommands.length ? nextFilteredBotCommands : undefined,\n );\n });\n }, [botCommands, chatBotCommands]);\n\n useEffect(() => {\n if (!isAllowed || !html.length) {\n unmarkIsOpen();\n return;\n }\n\n const shouldShowCommands = html.startsWith('/');\n\n if (shouldShowCommands) {\n const filter = prepareForRegExp(html.substr(1)).match(RE_COMMAND);\n getFilteredCommands(filter ? filter[0] : '');\n } else {\n unmarkIsOpen();\n }\n }, [getFilteredCommands, html, isAllowed, unmarkIsOpen]);\n\n useEffect(() => {\n if (filteredBotCommands && filteredBotCommands.length) {\n markIsOpen();\n } else {\n unmarkIsOpen();\n }\n }, [filteredBotCommands, markIsOpen, unmarkIsOpen]);\n\n return {\n isOpen,\n close: unmarkIsOpen,\n filteredBotCommands,\n };\n}\n","import React, { FC, memo } from '../../lib/teact/teact';\nimport { OwnProps } from './DeleteMessageModal';\nimport { Bundles } from '../../util/moduleLoader';\n\nimport useModuleLoader from '../../hooks/useModuleLoader';\n\nconst DeleteMessageModalAsync: FC<OwnProps> = (props) => {\n const { isOpen } = props;\n const DeleteMessageModal = useModuleLoader(Bundles.Extra, 'DeleteMessageModal', !isOpen);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return DeleteMessageModal ? <DeleteMessageModal {...props} /> : undefined;\n};\n\nexport default memo(DeleteMessageModalAsync);\n","import React, {\n FC, useRef, useCallback, memo,\n} from '../../lib/teact/teact';\n\nimport { IS_TOUCH_ENV } from '../../util/environment';\n\nimport Button, { OwnProps as ButtonProps } from './Button';\n\ntype OwnProps = {\n onActivate: NoneToVoidFunction;\n} & Omit<ButtonProps, (\n 'onClick' | 'onMouseDown' |\n 'onMouseEnter' | 'onMouseLeave' |\n 'onFocus'\n)>;\n\nconst BUTTON_ACTIVATE_DELAY = 200;\nlet openTimeout: number | undefined;\nlet isFirstTimeActivation = true;\n\nconst ResponsiveHoverButton: FC<OwnProps> = ({ onActivate, ...buttonProps }) => {\n const isMouseInside = useRef(false);\n\n const handleMouseEnter = useCallback(() => {\n isMouseInside.current = true;\n\n // This is used to counter additional delay caused by asynchronous module loading\n if (isFirstTimeActivation) {\n isFirstTimeActivation = false;\n onActivate();\n return;\n }\n\n if (openTimeout) {\n clearTimeout(openTimeout);\n openTimeout = undefined;\n }\n openTimeout = window.setTimeout(() => {\n if (isMouseInside.current) {\n onActivate();\n }\n }, BUTTON_ACTIVATE_DELAY);\n }, [onActivate]);\n\n const handleMouseLeave = useCallback(() => {\n isMouseInside.current = false;\n }, []);\n\n return (\n <Button\n // eslint-disable-next-line react/jsx-props-no-spreading\n {...buttonProps}\n onMouseEnter={!IS_TOUCH_ENV ? handleMouseEnter : undefined}\n onMouseLeave={!IS_TOUCH_ENV ? handleMouseLeave : undefined}\n onClick={IS_TOUCH_ENV ? onActivate : undefined}\n />\n );\n};\n\nexport default memo(ResponsiveHoverButton);\n","import React, { FC, memo } from '../../../lib/teact/teact';\nimport { OwnProps } from './AttachMenu';\nimport { Bundles } from '../../../util/moduleLoader';\n\nimport useModuleLoader from '../../../hooks/useModuleLoader';\n\nconst AttachMenuAsync: FC<OwnProps> = (props) => {\n const { isOpen } = props;\n const AttachMenu = useModuleLoader(Bundles.Extra, 'AttachMenu', !isOpen);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return AttachMenu ? <AttachMenu {...props} /> : undefined;\n};\n\nexport default memo(AttachMenuAsync);\n","import React, { FC, memo } from '../../../lib/teact/teact';\nimport { OwnProps } from './SymbolMenu';\nimport { Bundles } from '../../../util/moduleLoader';\n\nimport useModuleLoader from '../../../hooks/useModuleLoader';\n\nconst SymbolMenuAsync: FC<OwnProps> = (props) => {\n const { isOpen } = props;\n const SymbolMenu = useModuleLoader(Bundles.Extra, 'SymbolMenu', !isOpen);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return SymbolMenu ? <SymbolMenu {...props} /> : undefined;\n};\n\nexport default memo(SymbolMenuAsync);\n","import React, { FC, memo } from '../../../lib/teact/teact';\nimport { OwnProps } from './InlineBotTooltip';\nimport { Bundles } from '../../../util/moduleLoader';\n\nimport useModuleLoader from '../../../hooks/useModuleLoader';\n\nconst InlineBotTooltipAsync: FC<OwnProps> = (props) => {\n const { isOpen } = props;\n const InlineBotTooltip = useModuleLoader(Bundles.Extra, 'InlineBotTooltip', !isOpen);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return InlineBotTooltip ? <InlineBotTooltip {...props} /> : undefined;\n};\n\nexport default memo(InlineBotTooltipAsync);\n","import React, { FC, memo } from '../../../lib/teact/teact';\nimport { OwnProps } from './MentionTooltip';\nimport { Bundles } from '../../../util/moduleLoader';\n\nimport useModuleLoader from '../../../hooks/useModuleLoader';\n\nconst MentionTooltipAsync: FC<OwnProps> = (props) => {\n const { isOpen } = props;\n const MentionTooltip = useModuleLoader(Bundles.Extra, 'MentionTooltip', !isOpen);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return MentionTooltip ? <MentionTooltip {...props} /> : undefined;\n};\n\nexport default memo(MentionTooltipAsync);\n","import React, { FC, memo } from '../../../lib/teact/teact';\nimport { OwnProps } from './CustomSendMenu';\nimport { Bundles } from '../../../util/moduleLoader';\n\nimport useModuleLoader from '../../../hooks/useModuleLoader';\n\nconst CustomSendMenuAsync: FC<OwnProps> = (props) => {\n const { isOpen } = props;\n const CustomSend = useModuleLoader(Bundles.Extra, 'CustomSendMenu', !isOpen);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return CustomSend ? <CustomSend {...props} /> : undefined;\n};\n\nexport default memo(CustomSendMenuAsync);\n","import React, { FC } from '../../../lib/teact/teact';\nimport { OwnProps } from './StickerTooltip';\nimport { Bundles } from '../../../util/moduleLoader';\n\nimport useModuleLoader from '../../../hooks/useModuleLoader';\n\nconst StickerTooltipAsync: FC<OwnProps> = (props) => {\n const { isOpen } = props;\n const StickerTooltip = useModuleLoader(Bundles.Extra, 'StickerTooltip', !isOpen);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return StickerTooltip ? <StickerTooltip {...props} /> : undefined;\n};\n\nexport default StickerTooltipAsync;\n","import React, { FC, memo } from '../../../lib/teact/teact';\nimport { OwnProps } from './BotCommandTooltip';\nimport { Bundles } from '../../../util/moduleLoader';\n\nimport useModuleLoader from '../../../hooks/useModuleLoader';\n\nconst BotCommandTooltipAsync: FC<OwnProps> = (props) => {\n const { isOpen } = props;\n const BotCommandTooltip = useModuleLoader(Bundles.Extra, 'BotCommandTooltip', !isOpen);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return BotCommandTooltip ? <BotCommandTooltip {...props} /> : undefined;\n};\n\nexport default memo(BotCommandTooltipAsync);\n","import React, { FC, memo, useEffect } from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../../global/types';\nimport { ApiMessage } from '../../../api/types';\n\nimport { IS_TOUCH_ENV } from '../../../util/environment';\nimport { pick } from '../../../util/iteratees';\nimport { selectChatMessage, selectCurrentMessageList } from '../../../modules/selectors';\nimport useMouseInside from '../../../hooks/useMouseInside';\nimport useFlag from '../../../hooks/useFlag';\n\nimport Menu from '../../ui/Menu';\nimport Button from '../../ui/Button';\n\nimport './BotKeyboardMenu.scss';\n\nexport type OwnProps = {\n isOpen: boolean;\n messageId: number;\n onClose: NoneToVoidFunction;\n};\n\ntype StateProps = {\n message?: ApiMessage;\n};\n\ntype DispatchProps = Pick<GlobalActions, ('clickInlineButton')>;\n\nconst BotKeyboardMenu: FC<OwnProps & StateProps & DispatchProps> = ({\n isOpen, message, onClose, clickInlineButton,\n}) => {\n const [handleMouseEnter, handleMouseLeave] = useMouseInside(isOpen, onClose);\n const { isKeyboardSingleUse } = message || {};\n const [forceOpen, markForceOpen, unmarkForceOpen] = useFlag(true);\n\n const handleClose = () => {\n unmarkForceOpen();\n onClose();\n };\n\n useEffect(() => {\n markForceOpen();\n }, [markForceOpen, message]);\n\n if (!message || !message.keyboardButtons) {\n return undefined;\n }\n\n return (\n <Menu\n isOpen={isOpen || forceOpen}\n autoClose={isKeyboardSingleUse}\n positionX=\"right\"\n positionY=\"bottom\"\n onClose={handleClose}\n className=\"BotKeyboardMenu\"\n onCloseAnimationEnd={handleClose}\n onMouseEnter={!IS_TOUCH_ENV ? handleMouseEnter : undefined}\n onMouseLeave={!IS_TOUCH_ENV ? handleMouseLeave : undefined}\n >\n <div className=\"content\">\n {message.keyboardButtons.map((row) => (\n <div className=\"row\">\n {row.map((button) => (\n <Button\n ripple\n disabled={button.type === 'NOT_SUPPORTED'}\n onClick={() => clickInlineButton({ button })}\n >\n {button.text}\n </Button>\n ))}\n </div>\n ))}\n </div>\n </Menu>\n );\n};\n\nexport default memo(withGlobal<OwnProps>(\n (global, { messageId }): StateProps => {\n const { chatId } = selectCurrentMessageList(global) || {};\n if (!chatId) {\n return {};\n }\n\n return { message: selectChatMessage(global, chatId, messageId) };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'clickInlineButton',\n ]),\n)(BotKeyboardMenu));\n","import React, {\n FC, memo, useCallback, useEffect,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../../global/types';\nimport { ApiChat, ApiMessage, ApiUser } from '../../../api/types';\n\nimport {\n selectChat,\n selectChatMessage,\n selectSender,\n selectForwardedSender,\n selectUser,\n selectCurrentMessageList,\n selectReplyingToId,\n selectEditingId,\n selectEditingScheduledId,\n selectEditingMessage,\n} from '../../../modules/selectors';\nimport captureEscKeyListener from '../../../util/captureEscKeyListener';\nimport { pick } from '../../../util/iteratees';\nimport useAsyncRendering from '../../right/hooks/useAsyncRendering';\nimport useShowTransition from '../../../hooks/useShowTransition';\nimport buildClassName from '../../../util/buildClassName';\nimport { isUserId } from '../../../modules/helpers';\n\nimport Button from '../../ui/Button';\nimport EmbeddedMessage from '../../common/EmbeddedMessage';\n\nimport './ComposerEmbeddedMessage.scss';\n\ntype StateProps = {\n replyingToId?: number;\n editingId?: number;\n message?: ApiMessage;\n sender?: ApiUser | ApiChat;\n shouldAnimate?: boolean;\n forwardedMessagesCount?: number;\n};\n\ntype DispatchProps = Pick<GlobalActions, 'setReplyingToId' | 'setEditingId' | 'focusMessage' | 'exitForwardMode'>;\n\nconst FORWARD_RENDERING_DELAY = 300;\n\nconst ComposerEmbeddedMessage: FC<StateProps & DispatchProps> = ({\n replyingToId,\n editingId,\n message,\n sender,\n shouldAnimate,\n forwardedMessagesCount,\n setReplyingToId,\n setEditingId,\n focusMessage,\n exitForwardMode,\n}) => {\n const isShown = Boolean(\n ((replyingToId || editingId) && message)\n || (sender && forwardedMessagesCount),\n );\n const canAnimate = useAsyncRendering(\n [forwardedMessagesCount],\n forwardedMessagesCount ? FORWARD_RENDERING_DELAY : undefined,\n );\n\n const {\n shouldRender, transitionClassNames,\n } = useShowTransition(canAnimate && isShown, undefined, !shouldAnimate, undefined, !shouldAnimate);\n\n const clearEmbedded = useCallback(() => {\n if (replyingToId) {\n setReplyingToId({ messageId: undefined });\n } else if (editingId) {\n setEditingId({ messageId: undefined });\n } else if (forwardedMessagesCount) {\n exitForwardMode();\n }\n }, [replyingToId, editingId, forwardedMessagesCount, setReplyingToId, setEditingId, exitForwardMode]);\n\n useEffect(() => (isShown ? captureEscKeyListener(clearEmbedded) : undefined), [isShown, clearEmbedded]);\n\n const handleMessageClick = useCallback((): void => {\n focusMessage({ chatId: message!.chatId, messageId: message!.id });\n }, [focusMessage, message]);\n\n const className = buildClassName('ComposerEmbeddedMessage', transitionClassNames);\n\n const customText = forwardedMessagesCount && forwardedMessagesCount > 1\n ? `${forwardedMessagesCount} forwarded messages`\n : undefined;\n\n if (!shouldRender) {\n return undefined;\n }\n\n return (\n <div className={className}>\n <div>\n <Button round faded color=\"translucent\" ariaLabel=\"Cancel replying\" onClick={clearEmbedded}>\n <i className=\"icon-close\" />\n </Button>\n <EmbeddedMessage\n className=\"inside-input\"\n message={message}\n sender={sender}\n customText={customText}\n title={editingId ? 'Edit Message' : undefined}\n onClick={handleMessageClick}\n />\n </div>\n </div>\n );\n};\n\nexport default memo(withGlobal(\n (global): StateProps => {\n const { chatId, threadId, type: messageListType } = selectCurrentMessageList(global) || {};\n if (!chatId || !threadId || !messageListType) {\n return {};\n }\n\n const {\n currentUserId,\n forwardMessages: { fromChatId, toChatId, messageIds: forwardMessageIds },\n } = global;\n\n const replyingToId = selectReplyingToId(global, chatId, threadId);\n const editingId = messageListType === 'scheduled'\n ? selectEditingScheduledId(global, chatId)\n : selectEditingId(global, chatId, threadId);\n const shouldAnimate = global.settings.byKey.animationLevel >= 1;\n const isForwarding = toChatId === chatId;\n\n let message;\n if (replyingToId) {\n message = selectChatMessage(global, chatId, replyingToId);\n } else if (editingId) {\n message = selectEditingMessage(global, chatId, threadId, messageListType);\n } else if (isForwarding && forwardMessageIds!.length === 1) {\n message = selectChatMessage(global, fromChatId!, forwardMessageIds![0]);\n }\n\n let sender: ApiChat | ApiUser | undefined;\n if (replyingToId && message) {\n const { forwardInfo } = message;\n const isChatWithSelf = chatId === currentUserId;\n\n if (forwardInfo && (forwardInfo.isChannelPost || isChatWithSelf)) {\n sender = selectForwardedSender(global, message);\n }\n\n if (!sender) {\n sender = selectSender(global, message);\n }\n } else if (isForwarding) {\n sender = isUserId(fromChatId!) ? selectUser(global, fromChatId!) : selectChat(global, fromChatId!);\n }\n\n return {\n replyingToId,\n editingId,\n message,\n sender,\n shouldAnimate,\n forwardedMessagesCount: isForwarding ? forwardMessageIds!.length : undefined,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'setReplyingToId',\n 'setEditingId',\n 'focusMessage',\n 'exitForwardMode',\n ]),\n)(ComposerEmbeddedMessage));\n","import React, { FC, memo } from '../../../lib/teact/teact';\nimport { OwnProps } from './AttachmentModal';\nimport { Bundles } from '../../../util/moduleLoader';\n\nimport useModuleLoader from '../../../hooks/useModuleLoader';\n\nconst AttachmentModalAsync: FC<OwnProps> = (props) => {\n const { attachments } = props;\n const AttachmentModal = useModuleLoader(Bundles.Extra, 'AttachmentModal', !attachments.length);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return AttachmentModal ? <AttachmentModal {...props} /> : undefined;\n};\n\nexport default memo(AttachmentModalAsync);\n","import React, { FC, memo } from '../../../lib/teact/teact';\nimport { OwnProps } from './BotCommandMenu';\nimport { Bundles } from '../../../util/moduleLoader';\n\nimport useModuleLoader from '../../../hooks/useModuleLoader';\n\nconst BotCommandMenuAsync: FC<OwnProps> = (props) => {\n const { isOpen } = props;\n const BotCommandMenu = useModuleLoader(Bundles.Extra, 'BotCommandMenu', !isOpen);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return BotCommandMenu ? <BotCommandMenu {...props} /> : undefined;\n};\n\nexport default memo(BotCommandMenuAsync);\n","import React, { FC, memo } from '../../../lib/teact/teact';\nimport { OwnProps } from './PollModal';\nimport { Bundles } from '../../../util/moduleLoader';\n\nimport useModuleLoader from '../../../hooks/useModuleLoader';\n\nconst PollModalAsync: FC<OwnProps> = (props) => {\n const { isOpen } = props;\n const PollModal = useModuleLoader(Bundles.Extra, 'PollModal', !isOpen);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return PollModal ? <PollModal {...props} /> : undefined;\n};\n\nexport default memo(PollModalAsync);\n","import React, { FC, memo } from '../../../lib/teact/teact';\nimport { OwnProps } from './DropArea';\nimport { Bundles } from '../../../util/moduleLoader';\n\nimport useModuleLoader from '../../../hooks/useModuleLoader';\n\nconst DropAreaAsync: FC<OwnProps> = (props) => {\n const { isOpen } = props;\n const DropArea = useModuleLoader(Bundles.Extra, 'DropArea', !isOpen);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return DropArea ? <DropArea {...props} /> : undefined;\n};\n\nexport default memo(DropAreaAsync);\nexport { DropAreaState } from './DropArea';\n","import React, {\n FC, memo, useEffect, useMemo,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../../global/types';\nimport { ApiMessage, ApiMessageEntityTypes, ApiWebPage } from '../../../api/types';\nimport { ISettings } from '../../../types';\n\nimport { RE_LINK_TEMPLATE } from '../../../config';\nimport { selectNoWebPage, selectTheme } from '../../../modules/selectors';\nimport { pick } from '../../../util/iteratees';\nimport parseMessageInput from '../../../util/parseMessageInput';\nimport useOnChange from '../../../hooks/useOnChange';\nimport useShowTransition from '../../../hooks/useShowTransition';\nimport useCurrentOrPrev from '../../../hooks/useCurrentOrPrev';\nimport buildClassName from '../../../util/buildClassName';\n\nimport WebPage from '../message/WebPage';\nimport Button from '../../ui/Button';\n\nimport './WebPagePreview.scss';\n\ntype OwnProps = {\n chatId: string;\n threadId: number;\n messageText: string;\n disabled?: boolean;\n};\n\ntype StateProps = {\n webPagePreview?: ApiWebPage;\n noWebPage?: boolean;\n theme: ISettings['theme'];\n};\ntype DispatchProps = Pick<GlobalActions, 'loadWebPagePreview' | 'clearWebPagePreview' | 'toggleMessageWebPage'>;\n\nconst RE_LINK = new RegExp(RE_LINK_TEMPLATE, 'i');\n\nconst WebPagePreview: FC<OwnProps & StateProps & DispatchProps> = ({\n chatId,\n threadId,\n messageText,\n disabled,\n webPagePreview,\n noWebPage,\n theme,\n loadWebPagePreview,\n clearWebPagePreview,\n toggleMessageWebPage,\n}) => {\n const link = useMemo(() => {\n const { text, entities } = parseMessageInput(messageText);\n\n const linkEntity = entities && entities.find(({ type }) => type === ApiMessageEntityTypes.TextUrl);\n if (linkEntity) {\n return linkEntity.url;\n }\n\n const textMatch = text.match(RE_LINK);\n if (textMatch) {\n return textMatch[0];\n }\n\n return undefined;\n }, [messageText]);\n\n useEffect(() => {\n if (link) {\n loadWebPagePreview({ text: link });\n } else {\n clearWebPagePreview();\n toggleMessageWebPage({ chatId, threadId });\n }\n }, [chatId, toggleMessageWebPage, clearWebPagePreview, link, loadWebPagePreview, threadId]);\n\n useOnChange(() => {\n clearWebPagePreview();\n toggleMessageWebPage({ chatId, threadId });\n }, [chatId]);\n\n const isShown = Boolean(webPagePreview && messageText.length && !noWebPage && !disabled);\n const { shouldRender, transitionClassNames } = useShowTransition(isShown);\n\n const renderingWebPage = useCurrentOrPrev(webPagePreview, true);\n\n if (!shouldRender || !renderingWebPage) {\n return undefined;\n }\n\n const handleClearWebpagePreview = () => {\n toggleMessageWebPage({ chatId, threadId, noWebPage: true });\n };\n\n // TODO Refactor so `WebPage` can be used without message\n const { photo, ...webPageWithoutPhoto } = renderingWebPage;\n const messageStub = {\n content: {\n webPage: webPageWithoutPhoto,\n },\n } as ApiMessage;\n\n return (\n <div className={buildClassName('WebPagePreview', transitionClassNames)}>\n <div>\n <Button round faded color=\"translucent\" ariaLabel=\"Clear Webpage Preview\" onClick={handleClearWebpagePreview}>\n <i className=\"icon-close\" />\n </Button>\n <WebPage message={messageStub} inPreview theme={theme} />\n </div>\n </div>\n );\n};\n\nexport default memo(withGlobal<OwnProps>(\n (global, { chatId, threadId }): StateProps => {\n const noWebPage = selectNoWebPage(global, chatId, threadId);\n return {\n theme: selectTheme(global),\n webPagePreview: global.webPagePreview,\n noWebPage,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'loadWebPagePreview', 'clearWebPagePreview', 'toggleMessageWebPage',\n ]),\n)(WebPagePreview));\n","import React, { FC, memo } from '../../lib/teact/teact';\nimport { OwnProps } from './CalendarModal';\nimport { Bundles } from '../../util/moduleLoader';\n\nimport useModuleLoader from '../../hooks/useModuleLoader';\n\nconst CalendarModalAsync: FC<OwnProps> = (props) => {\n const { isOpen } = props;\n const CalendarModal = useModuleLoader(Bundles.Extra, 'CalendarModal', !isOpen);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return CalendarModal ? <CalendarModal {...props} /> : undefined;\n};\n\nexport default memo(CalendarModalAsync);\n","import React, {\n FC, memo, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalActions, GlobalState, MessageListType } from '../../../global/types';\nimport {\n ApiAttachment,\n ApiBotInlineResult,\n ApiBotInlineMediaResult,\n ApiSticker,\n ApiVideo,\n ApiNewPoll,\n ApiMessage,\n ApiFormattedText,\n ApiChat,\n ApiChatMember,\n ApiUser,\n MAIN_THREAD_ID,\n ApiBotCommand,\n} from '../../../api/types';\nimport { InlineBotSettings } from '../../../types';\n\nimport {\n BASE_EMOJI_KEYWORD_LANG, EDITABLE_INPUT_ID, REPLIES_USER_ID, SCHEDULED_WHEN_ONLINE,\n} from '../../../config';\nimport { IS_VOICE_RECORDING_SUPPORTED, IS_SINGLE_COLUMN_LAYOUT, IS_IOS } from '../../../util/environment';\nimport {\n selectChat,\n selectIsRightColumnShown,\n selectIsInSelectMode,\n selectNewestMessageWithBotKeyboardButtons,\n selectDraft,\n selectScheduledIds,\n selectEditingMessage,\n selectIsChatWithSelf,\n selectChatBot,\n selectChatUser,\n selectChatMessage,\n} from '../../../modules/selectors';\nimport {\n getAllowedAttachmentOptions,\n getChatSlowModeOptions,\n isUserId,\n isChatAdmin,\n} from '../../../modules/helpers';\nimport { formatMediaDuration, formatVoiceRecordDuration, getDayStartAt } from '../../../util/dateFormat';\nimport focusEditableElement from '../../../util/focusEditableElement';\nimport parseMessageInput from '../../../util/parseMessageInput';\nimport buildAttachment from './helpers/buildAttachment';\nimport renderText from '../../common/helpers/renderText';\nimport insertHtmlInSelection from '../../../util/insertHtmlInSelection';\nimport deleteLastCharacterOutsideSelection from '../../../util/deleteLastCharacterOutsideSelection';\nimport { pick } from '../../../util/iteratees';\nimport buildClassName from '../../../util/buildClassName';\nimport windowSize from '../../../util/windowSize';\nimport { isSelectionInsideInput } from './helpers/selection';\nimport applyIosAutoCapitalizationFix from './helpers/applyIosAutoCapitalizationFix';\nimport { getServerTime } from '../../../util/serverTime';\n\nimport useFlag from '../../../hooks/useFlag';\nimport useVoiceRecording from './hooks/useVoiceRecording';\nimport useClipboardPaste from './hooks/useClipboardPaste';\nimport useDraft from './hooks/useDraft';\nimport useEditing from './hooks/useEditing';\nimport usePrevious from '../../../hooks/usePrevious';\nimport useStickerTooltip from './hooks/useStickerTooltip';\nimport useEmojiTooltip from './hooks/useEmojiTooltip';\nimport useMentionTooltip from './hooks/useMentionTooltip';\nimport useContextMenuHandlers from '../../../hooks/useContextMenuHandlers';\nimport useLang from '../../../hooks/useLang';\nimport useInlineBotTooltip from './hooks/useInlineBotTooltip';\nimport useBotCommandTooltip from './hooks/useBotCommandTooltip';\n\nimport DeleteMessageModal from '../../common/DeleteMessageModal.async';\nimport Button from '../../ui/Button';\nimport ResponsiveHoverButton from '../../ui/ResponsiveHoverButton';\nimport Spinner from '../../ui/Spinner';\nimport AttachMenu from './AttachMenu.async';\nimport SymbolMenu from './SymbolMenu.async';\nimport InlineBotTooltip from './InlineBotTooltip.async';\nimport MentionTooltip from './MentionTooltip.async';\nimport CustomSendMenu from './CustomSendMenu.async';\nimport StickerTooltip from './StickerTooltip.async';\nimport EmojiTooltip from './EmojiTooltip.async';\nimport BotCommandTooltip from './BotCommandTooltip.async';\nimport BotKeyboardMenu from './BotKeyboardMenu';\nimport MessageInput from './MessageInput';\nimport ComposerEmbeddedMessage from './ComposerEmbeddedMessage';\nimport AttachmentModal from './AttachmentModal.async';\nimport BotCommandMenu from './BotCommandMenu.async';\nimport PollModal from './PollModal.async';\nimport DropArea, { DropAreaState } from './DropArea.async';\nimport WebPagePreview from './WebPagePreview';\nimport Portal from '../../ui/Portal';\nimport CalendarModal from '../../common/CalendarModal.async';\n\nimport './Composer.scss';\n\ntype OwnProps = {\n chatId: string;\n threadId: number;\n messageListType: MessageListType;\n dropAreaState: string;\n isReady: boolean;\n onDropHide: NoneToVoidFunction;\n};\n\ntype StateProps = {\n editingMessage?: ApiMessage;\n chat?: ApiChat;\n draft?: ApiFormattedText;\n isChatWithBot?: boolean;\n isChatWithSelf?: boolean;\n isRightColumnShown?: boolean;\n isSelectModeActive?: boolean;\n isForwarding?: boolean;\n isPollModalOpen?: boolean;\n botKeyboardMessageId?: number;\n botKeyboardPlaceholder?: string;\n withScheduledButton?: boolean;\n shouldSchedule?: boolean;\n canScheduleUntilOnline?: boolean;\n stickersForEmoji?: ApiSticker[];\n groupChatMembers?: ApiChatMember[];\n currentUserId?: string;\n usersById?: Record<string, ApiUser>;\n recentEmojis: string[];\n lastSyncTime?: number;\n contentToBeScheduled?: GlobalState['messages']['contentToBeScheduled'];\n shouldSuggestStickers?: boolean;\n baseEmojiKeywords?: Record<string, string[]>;\n emojiKeywords?: Record<string, string[]>;\n serverTimeOffset: number;\n topInlineBotIds?: string[];\n isInlineBotLoading: boolean;\n inlineBots?: Record<string, false | InlineBotSettings>;\n botCommands?: ApiBotCommand[] | false;\n chatBotCommands?: ApiBotCommand[];\n} & Pick<GlobalState, 'connectionState'>;\n\ntype DispatchProps = Pick<GlobalActions, (\n 'sendMessage' | 'editMessage' | 'saveDraft' | 'forwardMessages' |\n 'clearDraft' | 'showDialog' | 'setStickerSearchQuery' | 'setGifSearchQuery' |\n 'openPollModal' | 'closePollModal' | 'loadScheduledHistory' | 'openChat' |\n 'addRecentEmoji' | 'sendInlineBotResult'\n)>;\n\nenum MainButtonState {\n Send = 'send',\n Record = 'record',\n Edit = 'edit',\n}\n\nconst VOICE_RECORDING_FILENAME = 'wonderful-voice-message.ogg';\n// When voice recording is active, composer placeholder will hide to prevent overlapping\nconst SCREEN_WIDTH_TO_HIDE_PLACEHOLDER = 600; // px\n\nconst MOBILE_KEYBOARD_HIDE_DELAY_MS = 100;\nconst SELECT_MODE_TRANSITION_MS = 200;\nconst MESSAGE_MAX_LENGTH = 4096;\nconst CAPTION_MAX_LENGTH = 1024;\nconst SENDING_ANIMATION_DURATION = 350;\n// eslint-disable-next-line max-len\nconst APPENDIX = '<svg width=\"9\" height=\"20\" xmlns=\"http://www.w3.org/2000/svg\"><defs><filter x=\"-50%\" y=\"-14.7%\" width=\"200%\" height=\"141.2%\" filterUnits=\"objectBoundingBox\" id=\"a\"><feOffset dy=\"1\" in=\"SourceAlpha\" result=\"shadowOffsetOuter1\"/><feGaussianBlur stdDeviation=\"1\" in=\"shadowOffsetOuter1\" result=\"shadowBlurOuter1\"/><feColorMatrix values=\"0 0 0 0 0.0621962482 0 0 0 0 0.138574144 0 0 0 0 0.185037364 0 0 0 0.15 0\" in=\"shadowBlurOuter1\"/></filter></defs><g fill=\"none\" fill-rule=\"evenodd\"><path d=\"M6 17H0V0c.193 2.84.876 5.767 2.05 8.782.904 2.325 2.446 4.485 4.625 6.48A1 1 0 016 17z\" fill=\"#000\" filter=\"url(#a)\"/><path d=\"M6 17H0V0c.193 2.84.876 5.767 2.05 8.782.904 2.325 2.446 4.485 4.625 6.48A1 1 0 016 17z\" fill=\"#FFF\" class=\"corner\"/></g></svg>';\n\nconst Composer: FC<OwnProps & StateProps & DispatchProps> = ({\n dropAreaState,\n shouldSchedule,\n canScheduleUntilOnline,\n isReady,\n onDropHide,\n editingMessage,\n chatId,\n threadId,\n messageListType,\n draft,\n chat,\n connectionState,\n isChatWithBot,\n isChatWithSelf,\n isRightColumnShown,\n isSelectModeActive,\n isForwarding,\n isPollModalOpen,\n botKeyboardMessageId,\n botKeyboardPlaceholder,\n withScheduledButton,\n stickersForEmoji,\n groupChatMembers,\n topInlineBotIds,\n currentUserId,\n usersById,\n lastSyncTime,\n contentToBeScheduled,\n shouldSuggestStickers,\n baseEmojiKeywords,\n emojiKeywords,\n serverTimeOffset,\n recentEmojis,\n inlineBots,\n isInlineBotLoading,\n botCommands,\n chatBotCommands,\n sendMessage,\n editMessage,\n saveDraft,\n clearDraft,\n showDialog,\n setStickerSearchQuery,\n setGifSearchQuery,\n forwardMessages,\n openPollModal,\n closePollModal,\n loadScheduledHistory,\n openChat,\n addRecentEmoji,\n sendInlineBotResult,\n}) => {\n const lang = useLang();\n\n // eslint-disable-next-line no-null/no-null\n const appendixRef = useRef<HTMLDivElement>(null);\n const [html, setHtml] = useState<string>('');\n const lastMessageSendTimeSeconds = useRef<number>();\n const prevDropAreaState = usePrevious(dropAreaState);\n const [isCalendarOpen, openCalendar, closeCalendar] = useFlag();\n const [\n scheduledMessageArgs, setScheduledMessageArgs,\n ] = useState<GlobalState['messages']['contentToBeScheduled'] | undefined>();\n const { width: windowWidth } = windowSize.get();\n\n // Cache for frequently updated state\n const htmlRef = useRef<string>(html);\n useEffect(() => {\n htmlRef.current = html;\n }, [html]);\n\n useEffect(() => {\n lastMessageSendTimeSeconds.current = undefined;\n }, [chatId]);\n\n useEffect(() => {\n if (chatId && lastSyncTime && threadId === MAIN_THREAD_ID && isReady) {\n loadScheduledHistory({ chatId });\n }\n }, [isReady, chatId, loadScheduledHistory, lastSyncTime, threadId]);\n\n useLayoutEffect(() => {\n if (!appendixRef.current) return;\n\n appendixRef.current.innerHTML = APPENDIX;\n }, []);\n\n useEffect(() => {\n if (contentToBeScheduled) {\n setScheduledMessageArgs(contentToBeScheduled);\n openCalendar();\n }\n }, [contentToBeScheduled, openCalendar]);\n\n const [attachments, setAttachments] = useState<ApiAttachment[]>([]);\n\n const [isBotKeyboardOpen, openBotKeyboard, closeBotKeyboard] = useFlag();\n const [isBotCommandMenuOpen, openBotCommandMenu, closeBotCommandMenu] = useFlag();\n const [isAttachMenuOpen, openAttachMenu, closeAttachMenu] = useFlag();\n const [isSymbolMenuOpen, openSymbolMenu, closeSymbolMenu] = useFlag();\n const [isDeleteModalOpen, openDeleteModal, closeDeleteModal] = useFlag();\n const [isSymbolMenuLoaded, onSymbolMenuLoadingComplete] = useFlag();\n const [isHoverDisabled, disableHover, enableHover] = useFlag();\n\n const {\n startRecordingVoice,\n stopRecordingVoice,\n pauseRecordingVoice,\n activeVoiceRecording,\n currentRecordTime,\n recordButtonRef: mainButtonRef,\n startRecordTimeRef,\n } = useVoiceRecording();\n\n const mainButtonState = editingMessage\n ? MainButtonState.Edit\n : !IS_VOICE_RECORDING_SUPPORTED || activeVoiceRecording || (html && !attachments.length) || isForwarding\n ? MainButtonState.Send\n : MainButtonState.Record;\n const canShowCustomSendMenu = !shouldSchedule;\n\n const {\n isMentionTooltipOpen, closeMentionTooltip, insertMention, mentionFilteredUsers,\n } = useMentionTooltip(\n !attachments.length,\n html,\n setHtml,\n undefined,\n groupChatMembers,\n topInlineBotIds,\n currentUserId,\n usersById,\n );\n\n const {\n isOpen: isInlineBotTooltipOpen,\n id: inlineBotId,\n isGallery: isInlineBotTooltipGallery,\n switchPm: inlineBotSwitchPm,\n results: inlineBotResults,\n closeTooltip: closeInlineBotTooltip,\n help: inlineBotHelp,\n loadMore: loadMoreForInlineBot,\n } = useInlineBotTooltip(\n Boolean(!attachments.length && lastSyncTime),\n chatId,\n html,\n inlineBots,\n );\n\n const {\n isOpen: isBotCommandTooltipOpen,\n close: closeBotCommandTooltip,\n filteredBotCommands: botTooltipCommands,\n } = useBotCommandTooltip(\n Boolean((botCommands && botCommands.length) || (chatBotCommands && chatBotCommands.length)),\n html,\n botCommands,\n chatBotCommands,\n );\n\n const {\n isContextMenuOpen: isCustomSendMenuOpen,\n handleContextMenu,\n handleContextMenuClose,\n handleContextMenuHide,\n } = useContextMenuHandlers(mainButtonRef, !(mainButtonState === MainButtonState.Send && canShowCustomSendMenu));\n\n const allowedAttachmentOptions = useMemo(() => {\n return getAllowedAttachmentOptions(chat, isChatWithBot);\n }, [chat, isChatWithBot]);\n\n const isAdmin = chat && isChatAdmin(chat);\n const slowMode = getChatSlowModeOptions(chat);\n\n const { isStickerTooltipOpen, closeStickerTooltip } = useStickerTooltip(\n Boolean(shouldSuggestStickers && allowedAttachmentOptions.canSendStickers && !attachments.length),\n html,\n stickersForEmoji,\n !isReady,\n );\n const {\n isEmojiTooltipOpen, closeEmojiTooltip, filteredEmojis, insertEmoji,\n } = useEmojiTooltip(\n Boolean(shouldSuggestStickers && allowedAttachmentOptions.canSendStickers && !attachments.length),\n html,\n recentEmojis,\n undefined,\n setHtml,\n baseEmojiKeywords,\n emojiKeywords,\n !isReady,\n );\n\n const insertTextAndUpdateCursor = useCallback((text: string, inputId: string = EDITABLE_INPUT_ID) => {\n const selection = window.getSelection()!;\n const messageInput = document.getElementById(inputId)!;\n const newHtml = renderText(text, ['escape_html', 'emoji_html', 'br_html'])\n .join('')\n .replace(/\\u200b+/g, '\\u200b');\n\n if (selection.rangeCount) {\n const selectionRange = selection.getRangeAt(0);\n if (isSelectionInsideInput(selectionRange, inputId)) {\n insertHtmlInSelection(newHtml);\n messageInput.dispatchEvent(new Event('input', { bubbles: true }));\n return;\n }\n }\n\n setHtml(`${htmlRef.current!}${newHtml}`);\n\n // If selection is outside of input, set cursor at the end of input\n requestAnimationFrame(() => {\n focusEditableElement(messageInput);\n });\n }, []);\n\n const removeSymbol = useCallback(() => {\n const selection = window.getSelection()!;\n\n if (selection.rangeCount) {\n const selectionRange = selection.getRangeAt(0);\n if (isSelectionInsideInput(selectionRange, EDITABLE_INPUT_ID)) {\n document.execCommand('delete', false);\n return;\n }\n }\n\n setHtml(deleteLastCharacterOutsideSelection(htmlRef.current!));\n }, []);\n\n const resetComposer = useCallback((shouldPreserveInput = false) => {\n if (!shouldPreserveInput) {\n setHtml('');\n }\n setAttachments([]);\n closeStickerTooltip();\n closeCalendar();\n setScheduledMessageArgs(undefined);\n closeMentionTooltip();\n closeEmojiTooltip();\n\n if (IS_SINGLE_COLUMN_LAYOUT) {\n // @optimization\n setTimeout(() => closeSymbolMenu(), SENDING_ANIMATION_DURATION);\n } else {\n closeSymbolMenu();\n }\n }, [closeStickerTooltip, closeCalendar, closeMentionTooltip, closeEmojiTooltip, closeSymbolMenu]);\n\n // Handle chat change (ref is used to avoid redundant effect calls)\n const stopRecordingVoiceRef = useRef<typeof stopRecordingVoice>();\n stopRecordingVoiceRef.current = stopRecordingVoice;\n useEffect(() => {\n return () => {\n stopRecordingVoiceRef.current!();\n resetComposer();\n };\n }, [chatId, resetComposer, stopRecordingVoiceRef]);\n\n const handleEditComplete = useEditing(htmlRef, setHtml, editingMessage, resetComposer, openDeleteModal, editMessage);\n useDraft(draft, chatId, threadId, html, htmlRef, setHtml, editingMessage, saveDraft, clearDraft);\n useClipboardPaste(insertTextAndUpdateCursor, setAttachments, editingMessage);\n\n const handleFileSelect = useCallback(async (files: File[], isQuick: boolean) => {\n setAttachments(await Promise.all(files.map((file) => buildAttachment(file.name, file, isQuick))));\n }, []);\n\n const handleAppendFiles = useCallback(async (files: File[], isQuick: boolean) => {\n setAttachments([\n ...attachments,\n ...await Promise.all(files.map((file) => buildAttachment(file.name, file, isQuick))),\n ]);\n }, [attachments]);\n\n const handleClearAttachment = useCallback(() => {\n setAttachments([]);\n }, []);\n\n const handleSend = useCallback(async (isSilent = false, scheduledAt?: number) => {\n if (connectionState !== 'connectionStateReady') {\n return;\n }\n\n let currentAttachments = attachments;\n\n if (activeVoiceRecording) {\n const record = await stopRecordingVoice();\n if (record) {\n const { blob, duration, waveform } = record;\n currentAttachments = [await buildAttachment(\n VOICE_RECORDING_FILENAME,\n blob,\n false,\n { voice: { duration, waveform } },\n )];\n }\n }\n\n const { text, entities } = parseMessageInput(htmlRef.current!);\n\n if (!currentAttachments.length && !text && !isForwarding) {\n return;\n }\n\n const maxLength = currentAttachments.length ? CAPTION_MAX_LENGTH : MESSAGE_MAX_LENGTH;\n if (text?.length > maxLength) {\n const extraLength = text.length - maxLength;\n showDialog({\n data: {\n message: 'MESSAGE_TOO_LONG_PLEASE_REMOVE_CHARACTERS',\n textParams: {\n '{EXTRA_CHARS_COUNT}': extraLength,\n '{PLURAL_S}': extraLength > 1 ? 's' : '',\n },\n hasErrorKey: true,\n },\n });\n\n return;\n }\n\n const messageInput = document.getElementById(EDITABLE_INPUT_ID)!;\n\n if (currentAttachments.length || text) {\n if (slowMode && !isAdmin) {\n const nowSeconds = getServerTime(serverTimeOffset);\n const secondsSinceLastMessage = lastMessageSendTimeSeconds.current\n && Math.floor(nowSeconds - lastMessageSendTimeSeconds.current);\n const nextSendDateNotReached = slowMode.nextSendDate && slowMode.nextSendDate > nowSeconds;\n\n if (\n (secondsSinceLastMessage && secondsSinceLastMessage < slowMode.seconds)\n || nextSendDateNotReached\n ) {\n const secondsRemaining = nextSendDateNotReached\n ? slowMode.nextSendDate! - nowSeconds\n : slowMode.seconds - secondsSinceLastMessage!;\n showDialog({\n data: {\n message: lang('SlowModeHint', formatMediaDuration(secondsRemaining)),\n isSlowMode: true,\n hasErrorKey: false,\n },\n });\n\n messageInput.blur();\n\n return;\n }\n }\n\n sendMessage({\n text,\n entities,\n attachments: currentAttachments,\n scheduledAt,\n isSilent,\n });\n }\n\n if (isForwarding) {\n forwardMessages({\n scheduledAt,\n isSilent,\n });\n }\n\n lastMessageSendTimeSeconds.current = getServerTime(serverTimeOffset);\n\n clearDraft({ chatId, localOnly: true });\n\n if (IS_IOS && messageInput === document.activeElement) {\n applyIosAutoCapitalizationFix(messageInput);\n }\n\n // Wait until message animation starts\n requestAnimationFrame(() => {\n resetComposer();\n });\n }, [\n connectionState, attachments, activeVoiceRecording, isForwarding, clearDraft, chatId, serverTimeOffset,\n resetComposer, stopRecordingVoice, showDialog, slowMode, isAdmin, sendMessage, forwardMessages, lang,\n ]);\n\n const handleActivateBotCommandMenu = useCallback(() => {\n closeSymbolMenu();\n openBotCommandMenu();\n }, [closeSymbolMenu, openBotCommandMenu]);\n\n const handleActivateSymbolMenu = useCallback(() => {\n closeBotCommandMenu();\n openSymbolMenu();\n }, [closeBotCommandMenu, openSymbolMenu]);\n\n const handleStickerSelect = useCallback((sticker: ApiSticker, shouldPreserveInput = false) => {\n sticker = {\n ...sticker,\n isPreloadedGlobally: true,\n };\n\n if (shouldSchedule) {\n setScheduledMessageArgs({ sticker });\n openCalendar();\n } else {\n sendMessage({ sticker });\n requestAnimationFrame(() => {\n resetComposer(shouldPreserveInput);\n });\n }\n }, [shouldSchedule, openCalendar, sendMessage, resetComposer]);\n\n const handleGifSelect = useCallback((gif: ApiVideo) => {\n if (shouldSchedule) {\n setScheduledMessageArgs({ gif });\n openCalendar();\n } else {\n sendMessage({ gif });\n requestAnimationFrame(() => {\n resetComposer(true);\n });\n }\n }, [shouldSchedule, openCalendar, sendMessage, resetComposer]);\n\n const handleInlineBotSelect = useCallback((inlineResult: ApiBotInlineResult | ApiBotInlineMediaResult) => {\n if (connectionState !== 'connectionStateReady') {\n return;\n }\n\n sendInlineBotResult({\n id: inlineResult.id,\n queryId: inlineResult.queryId,\n });\n\n const messageInput = document.getElementById(EDITABLE_INPUT_ID)!;\n if (IS_IOS && messageInput === document.activeElement) {\n applyIosAutoCapitalizationFix(messageInput);\n }\n\n clearDraft({ chatId, localOnly: true });\n requestAnimationFrame(() => {\n resetComposer();\n });\n }, [chatId, clearDraft, connectionState, resetComposer, sendInlineBotResult]);\n\n const handleBotCommandSelect = useCallback(() => {\n clearDraft({ chatId, localOnly: true });\n requestAnimationFrame(() => {\n resetComposer();\n });\n }, [chatId, clearDraft, resetComposer]);\n\n const handlePollSend = useCallback((poll: ApiNewPoll) => {\n if (shouldSchedule) {\n setScheduledMessageArgs({ poll });\n closePollModal();\n openCalendar();\n } else {\n sendMessage({ poll });\n closePollModal();\n }\n }, [closePollModal, openCalendar, sendMessage, shouldSchedule]);\n\n const handleSilentSend = useCallback(() => {\n if (shouldSchedule) {\n setScheduledMessageArgs({ isSilent: true });\n openCalendar();\n } else {\n void handleSend(true);\n }\n }, [handleSend, openCalendar, shouldSchedule]);\n\n const handleMessageSchedule = useCallback((date: Date, isWhenOnline = false) => {\n const { isSilent, ...restArgs } = scheduledMessageArgs || {};\n\n // Scheduled time can not be less than 10 seconds in future\n const scheduledAt = Math.round(Math.max(date.getTime(), Date.now() + 60 * 1000) / 1000)\n + (isWhenOnline ? 0 : serverTimeOffset);\n\n if (!scheduledMessageArgs || Object.keys(restArgs).length === 0) {\n void handleSend(!!isSilent, scheduledAt);\n } else {\n sendMessage({\n ...scheduledMessageArgs,\n scheduledAt,\n });\n requestAnimationFrame(() => {\n resetComposer();\n });\n }\n closeCalendar();\n }, [closeCalendar, handleSend, resetComposer, scheduledMessageArgs, sendMessage, serverTimeOffset]);\n\n const handleMessageScheduleUntilOnline = useCallback(() => {\n handleMessageSchedule(new Date(SCHEDULED_WHEN_ONLINE * 1000), true);\n }, [handleMessageSchedule]);\n\n const handleCloseCalendar = useCallback(() => {\n closeCalendar();\n setScheduledMessageArgs(undefined);\n }, [closeCalendar]);\n\n const handleSearchOpen = useCallback((type: 'stickers' | 'gifs') => {\n if (type === 'stickers') {\n setStickerSearchQuery({ query: '' });\n setGifSearchQuery({ query: undefined });\n } else {\n setGifSearchQuery({ query: '' });\n setStickerSearchQuery({ query: undefined });\n }\n }, [setStickerSearchQuery, setGifSearchQuery]);\n\n const handleSymbolMenuOpen = useCallback(() => {\n const messageInput = document.getElementById(EDITABLE_INPUT_ID)!;\n\n if (!IS_SINGLE_COLUMN_LAYOUT || messageInput !== document.activeElement) {\n openSymbolMenu();\n return;\n }\n\n messageInput.blur();\n setTimeout(() => {\n closeBotCommandMenu();\n openSymbolMenu();\n }, MOBILE_KEYBOARD_HIDE_DELAY_MS);\n }, [openSymbolMenu, closeBotCommandMenu]);\n\n const handleAllScheduledClick = useCallback(() => {\n openChat({ id: chatId, threadId, type: 'scheduled' });\n }, [openChat, chatId, threadId]);\n\n useEffect(() => {\n if (isRightColumnShown && IS_SINGLE_COLUMN_LAYOUT) {\n closeSymbolMenu();\n }\n }, [isRightColumnShown, closeSymbolMenu]);\n\n useEffect(() => {\n if (!isReady) return;\n\n if (isSelectModeActive) {\n disableHover();\n } else {\n setTimeout(() => {\n enableHover();\n }, SELECT_MODE_TRANSITION_MS);\n }\n }, [isSelectModeActive, enableHover, disableHover, isReady]);\n\n const mainButtonHandler = useCallback(() => {\n switch (mainButtonState) {\n case MainButtonState.Send:\n if (shouldSchedule) {\n if (activeVoiceRecording) {\n pauseRecordingVoice();\n }\n openCalendar();\n } else {\n void handleSend();\n }\n break;\n case MainButtonState.Record:\n void startRecordingVoice();\n break;\n case MainButtonState.Edit:\n handleEditComplete();\n break;\n default:\n break;\n }\n }, [\n mainButtonState, shouldSchedule, startRecordingVoice, handleEditComplete,\n activeVoiceRecording, openCalendar, pauseRecordingVoice, handleSend,\n ]);\n\n const areVoiceMessagesNotAllowed = mainButtonState === MainButtonState.Record\n && !allowedAttachmentOptions.canAttachMedia;\n\n const prevEditedMessage = usePrevious(editingMessage, true);\n const renderedEditedMessage = editingMessage || prevEditedMessage;\n\n const scheduledDefaultDate = new Date();\n scheduledDefaultDate.setSeconds(0);\n scheduledDefaultDate.setMilliseconds(0);\n\n const scheduledMaxDate = new Date();\n scheduledMaxDate.setFullYear(scheduledMaxDate.getFullYear() + 1);\n\n let sendButtonAriaLabel = 'SendMessage';\n switch (mainButtonState) {\n case MainButtonState.Edit:\n sendButtonAriaLabel = 'Save edited message';\n break;\n case MainButtonState.Record:\n sendButtonAriaLabel = areVoiceMessagesNotAllowed\n ? 'Conversation.DefaultRestrictedMedia'\n : 'AccDescrVoiceMessage';\n }\n\n const className = buildClassName(\n 'Composer',\n !isSelectModeActive && 'shown',\n isHoverDisabled && 'hover-disabled',\n );\n\n const symbolMenuButtonClassName = buildClassName(\n 'mobile-symbol-menu-button',\n !isReady && 'not-ready',\n isSymbolMenuLoaded\n ? (isSymbolMenuOpen && 'menu-opened')\n : (isSymbolMenuOpen && 'is-loading'),\n );\n\n const onSend = mainButtonState === MainButtonState.Edit\n ? handleEditComplete\n : (shouldSchedule ? openCalendar : handleSend);\n\n return (\n <div className={className}>\n {allowedAttachmentOptions.canAttachMedia && isReady && (\n <Portal containerId=\"#middle-column-portals\">\n <DropArea\n isOpen={dropAreaState !== DropAreaState.None}\n withQuick={[dropAreaState, prevDropAreaState].includes(DropAreaState.QuickFile)}\n onHide={onDropHide}\n onFileSelect={handleFileSelect}\n />\n </Portal>\n )}\n <AttachmentModal\n attachments={attachments}\n caption={attachments.length ? html : ''}\n groupChatMembers={groupChatMembers}\n currentUserId={currentUserId}\n usersById={usersById}\n recentEmojis={recentEmojis}\n isReady={isReady}\n onCaptionUpdate={setHtml}\n baseEmojiKeywords={baseEmojiKeywords}\n emojiKeywords={emojiKeywords}\n addRecentEmoji={addRecentEmoji}\n onSend={shouldSchedule ? openCalendar : handleSend}\n onFileAppend={handleAppendFiles}\n onClear={handleClearAttachment}\n />\n <PollModal\n isOpen={Boolean(isPollModalOpen)}\n onClear={closePollModal}\n onSend={handlePollSend}\n />\n {renderedEditedMessage && (\n <DeleteMessageModal\n isOpen={isDeleteModalOpen}\n isSchedule={messageListType === 'scheduled'}\n onClose={closeDeleteModal}\n message={renderedEditedMessage}\n />\n )}\n <MentionTooltip\n isOpen={isMentionTooltipOpen}\n onClose={closeMentionTooltip}\n onInsertUserName={insertMention}\n filteredUsers={mentionFilteredUsers}\n usersById={usersById}\n />\n <InlineBotTooltip\n isOpen={isInlineBotTooltipOpen}\n botId={inlineBotId}\n allowedAttachmentOptions={allowedAttachmentOptions}\n isGallery={isInlineBotTooltipGallery}\n inlineBotResults={inlineBotResults}\n switchPm={inlineBotSwitchPm}\n onSelectResult={handleInlineBotSelect}\n loadMore={loadMoreForInlineBot}\n onClose={closeInlineBotTooltip}\n />\n <BotCommandTooltip\n isOpen={isBotCommandTooltipOpen}\n withUsername={Boolean(chatBotCommands)}\n botCommands={botTooltipCommands}\n onClick={handleBotCommandSelect}\n onClose={closeBotCommandTooltip}\n />\n <div id=\"message-compose\">\n <div className=\"svg-appendix\" ref={appendixRef} />\n <ComposerEmbeddedMessage />\n <WebPagePreview\n chatId={chatId}\n threadId={threadId}\n messageText={!attachments.length ? html : ''}\n disabled={!allowedAttachmentOptions.canAttachEmbedLinks}\n />\n <div className=\"message-input-wrapper\">\n {isChatWithBot && botCommands !== false && !activeVoiceRecording && !editingMessage && (\n <ResponsiveHoverButton\n className={buildClassName('bot-commands', isBotCommandMenuOpen && 'activated')}\n round\n disabled={botCommands === undefined}\n color=\"translucent\"\n onActivate={handleActivateBotCommandMenu}\n ariaLabel=\"Open bot command keyboard\"\n >\n <i className=\"icon-bot-commands-filled\" />\n </ResponsiveHoverButton>\n )}\n {IS_SINGLE_COLUMN_LAYOUT ? (\n <Button\n className={symbolMenuButtonClassName}\n round\n color=\"translucent\"\n onClick={isSymbolMenuOpen ? closeSymbolMenu : handleSymbolMenuOpen}\n ariaLabel=\"Choose emoji, sticker or GIF\"\n >\n <i className=\"icon-smile\" />\n <i className=\"icon-keyboard\" />\n {isSymbolMenuOpen && !isSymbolMenuLoaded && <Spinner color=\"gray\" />}\n </Button>\n ) : (\n <ResponsiveHoverButton\n className={isSymbolMenuOpen ? 'activated' : ''}\n round\n color=\"translucent\"\n onActivate={handleActivateSymbolMenu}\n ariaLabel=\"Choose emoji, sticker or GIF\"\n >\n <i className=\"icon-smile\" />\n </ResponsiveHoverButton>\n )}\n <MessageInput\n id=\"message-input-text\"\n html={!attachments.length ? html : ''}\n placeholder={\n activeVoiceRecording && windowWidth <= SCREEN_WIDTH_TO_HIDE_PLACEHOLDER\n ? ''\n : botKeyboardPlaceholder || lang('Message')\n }\n forcedPlaceholder={inlineBotHelp}\n shouldSetFocus={!attachments.length}\n shouldSuppressFocus={IS_SINGLE_COLUMN_LAYOUT && isSymbolMenuOpen}\n shouldSuppressTextFormatter={isEmojiTooltipOpen || isMentionTooltipOpen || isInlineBotTooltipOpen}\n onUpdate={setHtml}\n onSend={onSend}\n onSuppressedFocus={closeSymbolMenu}\n />\n {isInlineBotLoading && Boolean(inlineBotId) && (\n <Spinner color=\"gray\" />\n )}\n {withScheduledButton && (\n <Button\n round\n faded\n className=\"scheduled-button\"\n color=\"translucent\"\n onClick={handleAllScheduledClick}\n ariaLabel=\"Open scheduled messages\"\n >\n <i className=\"icon-schedule\" />\n </Button>\n )}\n {botKeyboardMessageId && !activeVoiceRecording && !editingMessage && (\n <ResponsiveHoverButton\n className={isBotKeyboardOpen ? 'activated' : ''}\n round\n color=\"translucent\"\n onActivate={openBotKeyboard}\n ariaLabel=\"Open bot command keyboard\"\n >\n <i className=\"icon-bot-command\" />\n </ResponsiveHoverButton>\n )}\n {!activeVoiceRecording && !editingMessage && (\n <ResponsiveHoverButton\n className={isAttachMenuOpen ? 'activated' : ''}\n round\n color=\"translucent\"\n onActivate={openAttachMenu}\n ariaLabel=\"Add an attachment\"\n >\n <i className=\"icon-attach\" />\n </ResponsiveHoverButton>\n )}\n {activeVoiceRecording && currentRecordTime && (\n <span className=\"recording-state\">\n {formatVoiceRecordDuration(currentRecordTime - startRecordTimeRef.current!)}\n </span>\n )}\n <StickerTooltip\n isOpen={isStickerTooltipOpen}\n onStickerSelect={handleStickerSelect}\n />\n <EmojiTooltip\n isOpen={isEmojiTooltipOpen}\n emojis={filteredEmojis}\n onClose={closeEmojiTooltip}\n onEmojiSelect={insertEmoji}\n addRecentEmoji={addRecentEmoji}\n />\n <AttachMenu\n isOpen={isAttachMenuOpen}\n allowedAttachmentOptions={allowedAttachmentOptions}\n onFileSelect={handleFileSelect}\n onPollCreate={openPollModal}\n onClose={closeAttachMenu}\n />\n {botKeyboardMessageId && (\n <BotKeyboardMenu\n messageId={botKeyboardMessageId}\n isOpen={isBotKeyboardOpen}\n onClose={closeBotKeyboard}\n />\n )}\n {botCommands && (\n <BotCommandMenu\n isOpen={isBotCommandMenuOpen}\n botCommands={botCommands}\n onClose={closeBotCommandMenu}\n />\n )}\n <SymbolMenu\n isOpen={isSymbolMenuOpen}\n allowedAttachmentOptions={allowedAttachmentOptions}\n onLoad={onSymbolMenuLoadingComplete}\n onClose={closeSymbolMenu}\n onEmojiSelect={insertTextAndUpdateCursor}\n onStickerSelect={handleStickerSelect}\n onGifSelect={handleGifSelect}\n onRemoveSymbol={removeSymbol}\n onSearchOpen={handleSearchOpen}\n addRecentEmoji={addRecentEmoji}\n />\n </div>\n </div>\n {activeVoiceRecording && (\n <Button\n round\n color=\"danger\"\n className=\"cancel\"\n onClick={stopRecordingVoice}\n ariaLabel=\"Cancel voice recording\"\n >\n <i className=\"icon-delete\" />\n </Button>\n )}\n <Button\n ref={mainButtonRef}\n round\n color=\"secondary\"\n className={buildClassName(mainButtonState, !isReady && 'not-ready', activeVoiceRecording && 'recording')}\n disabled={areVoiceMessagesNotAllowed}\n ariaLabel={lang(sendButtonAriaLabel)}\n onClick={mainButtonHandler}\n onContextMenu={\n mainButtonState === MainButtonState.Send && canShowCustomSendMenu ? handleContextMenu : undefined\n }\n >\n <i className=\"icon-send\" />\n <i className=\"icon-microphone-alt\" />\n <i className=\"icon-check\" />\n </Button>\n {canShowCustomSendMenu && (\n <CustomSendMenu\n isOpen={isCustomSendMenuOpen}\n onSilentSend={!isChatWithSelf ? handleSilentSend : undefined}\n onScheduleSend={!shouldSchedule ? openCalendar : undefined}\n onClose={handleContextMenuClose}\n onCloseAnimationEnd={handleContextMenuHide}\n />\n )}\n <CalendarModal\n isOpen={isCalendarOpen}\n withTimePicker\n selectedAt={scheduledDefaultDate.getTime()}\n maxAt={getDayStartAt(scheduledMaxDate)}\n isFutureMode\n secondButtonLabel={canScheduleUntilOnline ? lang('Schedule.SendWhenOnline') : undefined}\n onClose={handleCloseCalendar}\n onSubmit={handleMessageSchedule}\n onSecondButtonClick={canScheduleUntilOnline ? handleMessageScheduleUntilOnline : undefined}\n />\n </div>\n );\n};\n\nexport default memo(withGlobal<OwnProps>(\n (global, { chatId, threadId, messageListType }): StateProps => {\n const chat = selectChat(global, chatId);\n const chatUser = chat && selectChatUser(global, chat);\n const chatBot = chatId !== REPLIES_USER_ID ? selectChatBot(global, chatId) : undefined;\n const isChatWithBot = Boolean(chatBot);\n const isChatWithSelf = selectIsChatWithSelf(global, chatId);\n const messageWithActualBotKeyboard = isChatWithBot && selectNewestMessageWithBotKeyboardButtons(global, chatId);\n const scheduledIds = selectScheduledIds(global, chatId);\n const { language, shouldSuggestStickers } = global.settings.byKey;\n const baseEmojiKeywords = global.emojiKeywords[BASE_EMOJI_KEYWORD_LANG];\n const emojiKeywords = language !== BASE_EMOJI_KEYWORD_LANG ? global.emojiKeywords[language] : undefined;\n const botKeyboardMessageId = messageWithActualBotKeyboard ? messageWithActualBotKeyboard.id : undefined;\n const keyboardMessage = botKeyboardMessageId ? selectChatMessage(global, chatId, botKeyboardMessageId) : undefined;\n\n return {\n editingMessage: selectEditingMessage(global, chatId, threadId, messageListType),\n connectionState: global.connectionState,\n draft: selectDraft(global, chatId, threadId),\n chat,\n isChatWithBot,\n isChatWithSelf,\n canScheduleUntilOnline: (\n !isChatWithSelf && !isChatWithBot\n && (chat && chatUser && isUserId(chatId) && chatUser.status && Boolean(chatUser.status.wasOnline))\n ),\n isRightColumnShown: selectIsRightColumnShown(global),\n isSelectModeActive: selectIsInSelectMode(global),\n withScheduledButton: (\n threadId === MAIN_THREAD_ID\n && messageListType === 'thread'\n && Boolean(scheduledIds?.length)\n ),\n shouldSchedule: messageListType === 'scheduled',\n botKeyboardMessageId,\n botKeyboardPlaceholder: keyboardMessage?.keyboardPlaceholder,\n isForwarding: chatId === global.forwardMessages.toChatId,\n isPollModalOpen: global.isPollModalOpen,\n stickersForEmoji: global.stickers.forEmoji.stickers,\n groupChatMembers: chat?.fullInfo?.members,\n topInlineBotIds: global.topInlineBots?.userIds,\n currentUserId: global.currentUserId,\n usersById: global.users.byId,\n lastSyncTime: global.lastSyncTime,\n contentToBeScheduled: global.messages.contentToBeScheduled,\n shouldSuggestStickers,\n recentEmojis: global.recentEmojis,\n baseEmojiKeywords: baseEmojiKeywords?.keywords,\n emojiKeywords: emojiKeywords?.keywords,\n serverTimeOffset: global.serverTimeOffset,\n inlineBots: global.inlineBots.byUsername,\n isInlineBotLoading: global.inlineBots.isLoading,\n chatBotCommands: chat && chat.fullInfo && chat.fullInfo.botCommands,\n botCommands: chatBot && chatBot.fullInfo ? (chatBot.fullInfo.botCommands || false) : undefined,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'sendMessage',\n 'editMessage',\n 'saveDraft',\n 'clearDraft',\n 'showDialog',\n 'setStickerSearchQuery',\n 'setGifSearchQuery',\n 'forwardMessages',\n 'openPollModal',\n 'closePollModal',\n 'loadScheduledHistory',\n 'openChat',\n 'addRecentEmoji',\n 'sendInlineBotResult',\n ]),\n)(Composer));\n","import { useEffect, useMemo } from '../../../../lib/teact/teact';\nimport { getDispatch } from '../../../../lib/teact/teactn';\n\nimport { ApiSticker } from '../../../../api/types';\n\nimport { IS_EMOJI_SUPPORTED } from '../../../../util/environment';\n\nimport parseEmojiOnlyString from '../../../common/helpers/parseEmojiOnlyString';\nimport { prepareForRegExp } from '../helpers/prepareForRegExp';\n\nexport default function useStickerTooltip(\n isAllowed: boolean,\n html: string,\n stickers?: ApiSticker[],\n isDisabled = false,\n) {\n const cleanHtml = useMemo(() => prepareForRegExp(html).trim(), [html]);\n const { loadStickersForEmoji, clearStickersForEmoji } = getDispatch();\n const isSingleEmoji = (\n (IS_EMOJI_SUPPORTED && parseEmojiOnlyString(cleanHtml) === 1)\n || (!IS_EMOJI_SUPPORTED && Boolean(html.match(/^<img.[^>]*?>$/g)))\n );\n const hasStickers = Boolean(stickers) && isSingleEmoji;\n\n useEffect(() => {\n if (isDisabled) return;\n\n if (isAllowed && isSingleEmoji) {\n loadStickersForEmoji({ emoji: cleanHtml });\n } else if (hasStickers || !isSingleEmoji) {\n clearStickersForEmoji();\n }\n // We omit `hasStickers` here to prevent re-fetching after manually closing tooltip (via <Esc>).\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [html, isSingleEmoji, clearStickersForEmoji, loadStickersForEmoji, isAllowed, isDisabled]);\n\n return {\n isStickerTooltipOpen: hasStickers,\n closeStickerTooltip: clearStickersForEmoji,\n };\n}\n","export default function insertHtmlInSelection(html: string) {\n const selection = window.getSelection();\n\n if (selection?.getRangeAt && selection.rangeCount) {\n const range = selection.getRangeAt(0);\n range.deleteContents();\n\n const fragment = range.createContextualFragment(html);\n const lastInsertedNode = fragment.lastChild;\n range.insertNode(fragment);\n if (lastInsertedNode) {\n range.setStartAfter(lastInsertedNode);\n range.setEndAfter(lastInsertedNode);\n } else {\n range.collapse(false);\n }\n selection.removeAllRanges();\n selection.addRange(range);\n }\n}\n","export default function deleteLastCharacterOutsideSelection(html: string) {\n const tempInput = document.createElement('div');\n tempInput.contentEditable = 'true';\n tempInput.style.position = 'absolute';\n tempInput.style.left = '-10000px';\n tempInput.style.top = '-10000px';\n tempInput.innerHTML = html;\n document.body.appendChild(tempInput);\n let element = tempInput.lastChild!;\n\n if (element.lastChild) {\n // Selects the last and the deepest child of the element.\n while (element.lastChild) {\n element = element.lastChild;\n }\n }\n\n // Gets length of the element's content.\n const textLength = element.textContent!.length;\n const range = document.createRange();\n const selection = window.getSelection()!;\n\n // Sets selection position to the end of the element.\n range.setStart(element, textLength);\n range.setEnd(element, textLength);\n selection.removeAllRanges();\n selection.addRange(range);\n document.execCommand('delete', false);\n\n const result = tempInput.innerHTML;\n document.body.removeChild(tempInput);\n\n return result;\n}\n","import { useCallback, useEffect } from '../../../../lib/teact/teact';\n\nimport { ApiMessage } from '../../../../api/types';\nimport { GlobalActions } from '../../../../global/types';\n\nimport { EDITABLE_INPUT_ID } from '../../../../config';\nimport parseMessageInput from '../../../../util/parseMessageInput';\nimport getMessageTextAsHtml from '../helpers/getMessageTextAsHtml';\nimport focusEditableElement from '../../../../util/focusEditableElement';\nimport { hasMessageMedia } from '../../../../modules/helpers';\n\nexport default (\n htmlRef: { current: string },\n setHtml: (html: string) => void,\n editedMessage: ApiMessage | undefined,\n resetComposer: () => void,\n openDeleteModal: () => void,\n editMessage: GlobalActions['editMessage'],\n) => {\n // TODO useOnChange\n // Handle editing message\n useEffect(() => {\n if (!editedMessage) {\n setHtml('');\n return;\n }\n\n setHtml(getMessageTextAsHtml(editedMessage.content.text));\n\n requestAnimationFrame(() => {\n const messageInput = document.getElementById(EDITABLE_INPUT_ID)!;\n focusEditableElement(messageInput, true);\n });\n }, [editedMessage, setHtml]);\n\n const handleEditComplete = useCallback(() => {\n const { text, entities } = parseMessageInput(htmlRef.current!);\n\n if (!editedMessage) {\n return;\n }\n\n if (!text && !hasMessageMedia(editedMessage)) {\n openDeleteModal();\n return;\n }\n\n editMessage({\n messageId: editedMessage.id,\n text,\n entities,\n });\n\n resetComposer();\n }, [editMessage, editedMessage, htmlRef, openDeleteModal, resetComposer]);\n\n return handleEditComplete;\n};\n","import React, { FC, memo } from '../../lib/teact/teact';\nimport { OwnProps } from './MobileSearch';\nimport { Bundles } from '../../util/moduleLoader';\n\nimport useModuleLoader from '../../hooks/useModuleLoader';\n\nconst MobileSearchAsync: FC<OwnProps> = (props) => {\n const { isActive } = props;\n const MobileSearch = useModuleLoader(Bundles.Extra, 'MobileSearch', !isActive, true);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return MobileSearch ? <MobileSearch {...props} /> : undefined;\n};\n\nexport default memo(MobileSearchAsync);\n","import React, { FC, memo } from '../../lib/teact/teact';\nimport { Bundles } from '../../util/moduleLoader';\nimport { OwnProps } from './MessageSelectToolbar';\n\nimport useModuleLoader from '../../hooks/useModuleLoader';\n\nconst MessageSelectToolbarAsync: FC<OwnProps> = (props) => {\n const { isActive } = props;\n const MessageSelectToolbar = useModuleLoader(Bundles.Extra, 'MessageSelectToolbar', !isActive);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return MessageSelectToolbar ? <MessageSelectToolbar {...props} /> : undefined;\n};\n\nexport default memo(MessageSelectToolbarAsync);\n","import React, { FC, memo } from '../../lib/teact/teact';\nimport { OwnProps } from './UnpinAllMessagesModal';\nimport { Bundles } from '../../util/moduleLoader';\n\nimport useModuleLoader from '../../hooks/useModuleLoader';\n\nconst UnpinAllMessagesModalAsync: FC<OwnProps> = (props) => {\n const { isOpen } = props;\n const UnpinAllMessagesModal = useModuleLoader(Bundles.Extra, 'UnpinAllMessagesModal', !isOpen);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return UnpinAllMessagesModal ? <UnpinAllMessagesModal {...props} /> : undefined;\n};\n\nexport default memo(UnpinAllMessagesModalAsync);\n","import React, { FC, memo } from '../../lib/teact/teact';\nimport { OwnProps } from './PaymentModal';\nimport { Bundles } from '../../util/moduleLoader';\n\nimport useModuleLoader from '../../hooks/useModuleLoader';\n\nconst PaymentModalAsync: FC<OwnProps> = (props) => {\n const { isOpen } = props;\n const PaymentModal = useModuleLoader(Bundles.Extra, 'PaymentModal', !isOpen);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return PaymentModal ? <PaymentModal {...props} /> : undefined;\n};\n\nexport default memo(PaymentModalAsync);\n","import React, { FC, memo } from '../../lib/teact/teact';\nimport { OwnProps } from './ReceiptModal';\nimport { Bundles } from '../../util/moduleLoader';\n\nimport useModuleLoader from '../../hooks/useModuleLoader';\n\nconst ReceiptModalAsync: FC<OwnProps> = (props) => {\n const { isOpen } = props;\n const ReceiptModal = useModuleLoader(Bundles.Extra, 'ReceiptModal', !isOpen);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return ReceiptModal ? <ReceiptModal {...props} /> : undefined;\n};\n\nexport default memo(ReceiptModalAsync);\n","import React, {\n FC, useEffect, useState, memo, useMemo, useCallback,\n} from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { ApiChatBannedRights, MAIN_THREAD_ID } from '../../api/types';\nimport { GlobalActions, MessageListType, MessageList as GlobalMessageList } from '../../global/types';\nimport { ThemeKey } from '../../types';\n\nimport {\n MIN_SCREEN_WIDTH_FOR_STATIC_LEFT_COLUMN,\n MOBILE_SCREEN_MAX_WIDTH,\n MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN,\n SAFE_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN,\n SAFE_SCREEN_WIDTH_FOR_CHAT_INFO,\n ANIMATION_LEVEL_MAX,\n ANIMATION_END_DELAY,\n DARK_THEME_BG_COLOR,\n LIGHT_THEME_BG_COLOR,\n ANIMATION_LEVEL_MIN,\n SUPPORTED_IMAGE_CONTENT_TYPES,\n} from '../../config';\nimport {\n IS_SINGLE_COLUMN_LAYOUT,\n IS_TABLET_COLUMN_LAYOUT,\n IS_TOUCH_ENV,\n MASK_IMAGE_DISABLED,\n} from '../../util/environment';\nimport { DropAreaState } from './composer/DropArea';\nimport {\n selectChat,\n selectCurrentMessageList,\n selectCurrentTextSearch,\n selectIsChatBotNotStarted,\n selectIsInSelectMode,\n selectIsRightColumnShown,\n selectPinnedIds,\n selectTheme,\n} from '../../modules/selectors';\nimport { getCanPostInChat, getMessageSendingRestrictionReason, isUserId } from '../../modules/helpers';\nimport captureEscKeyListener from '../../util/captureEscKeyListener';\nimport { pick } from '../../util/iteratees';\nimport buildClassName from '../../util/buildClassName';\nimport useCustomBackground from '../../hooks/useCustomBackground';\nimport useWindowSize from '../../hooks/useWindowSize';\nimport usePrevDuringAnimation from '../../hooks/usePrevDuringAnimation';\nimport calculateMiddleFooterTransforms from './helpers/calculateMiddleFooterTransforms';\nimport useLang from '../../hooks/useLang';\nimport useHistoryBack from '../../hooks/useHistoryBack';\nimport { createMessageHash } from '../../util/routing';\n\nimport Transition from '../ui/Transition';\nimport MiddleHeader from './MiddleHeader';\nimport MessageList from './MessageList';\nimport ScrollDownButton from './ScrollDownButton';\nimport Composer from './composer/Composer';\nimport Button from '../ui/Button';\nimport MobileSearch from './MobileSearch.async';\nimport MessageSelectToolbar from './MessageSelectToolbar.async';\nimport UnpinAllMessagesModal from '../common/UnpinAllMessagesModal.async';\nimport PaymentModal from '../payment/PaymentModal.async';\nimport ReceiptModal from '../payment/ReceiptModal.async';\n\nimport './MiddleColumn.scss';\n\ntype StateProps = {\n chatId?: string;\n threadId?: number;\n messageListType?: MessageListType;\n isPrivate?: boolean;\n isPinnedMessageList?: boolean;\n isScheduledMessageList?: boolean;\n canPost?: boolean;\n currentUserBannedRights?: ApiChatBannedRights;\n defaultBannedRights?: ApiChatBannedRights;\n hasPinnedOrAudioMessage?: boolean;\n pinnedMessagesCount?: number;\n theme: ThemeKey;\n customBackground?: string;\n backgroundColor?: string;\n patternColor?: string;\n isLeftColumnShown?: boolean;\n isRightColumnShown?: boolean;\n isBackgroundBlurred?: boolean;\n isMobileSearchActive?: boolean;\n isSelectModeActive?: boolean;\n isPaymentModalOpen?: boolean;\n isReceiptModalOpen?: boolean;\n animationLevel?: number;\n shouldSkipHistoryAnimations?: boolean;\n currentTransitionKey: number;\n messageLists?: GlobalMessageList[];\n};\n\ntype DispatchProps = Pick<GlobalActions, (\n 'openChat' | 'unpinAllMessages' | 'loadUser' | 'closeLocalTextSearch' | 'exitMessageSelectMode' |\n 'closePaymentModal' | 'clearReceipt'\n)>;\n\nconst CLOSE_ANIMATION_DURATION = IS_SINGLE_COLUMN_LAYOUT ? 450 + ANIMATION_END_DELAY : undefined;\n\nfunction isImage(item: DataTransferItem) {\n return item.kind === 'file' && item.type && SUPPORTED_IMAGE_CONTENT_TYPES.has(item.type);\n}\n\nconst MiddleColumn: FC<StateProps & DispatchProps> = ({\n chatId,\n threadId,\n messageListType,\n isPrivate,\n isPinnedMessageList,\n messageLists,\n canPost,\n currentUserBannedRights,\n defaultBannedRights,\n hasPinnedOrAudioMessage,\n pinnedMessagesCount,\n customBackground,\n theme,\n backgroundColor,\n patternColor,\n isLeftColumnShown,\n isRightColumnShown,\n isBackgroundBlurred,\n isMobileSearchActive,\n isSelectModeActive,\n isPaymentModalOpen,\n isReceiptModalOpen,\n animationLevel,\n shouldSkipHistoryAnimations,\n currentTransitionKey,\n openChat,\n unpinAllMessages,\n loadUser,\n closeLocalTextSearch,\n exitMessageSelectMode,\n closePaymentModal,\n clearReceipt,\n}) => {\n const { width: windowWidth } = useWindowSize();\n\n const lang = useLang();\n const [dropAreaState, setDropAreaState] = useState(DropAreaState.None);\n const [isFabShown, setIsFabShown] = useState<boolean | undefined>();\n const [isNotchShown, setIsNotchShown] = useState<boolean | undefined>();\n const [isUnpinModalOpen, setIsUnpinModalOpen] = useState(false);\n const [isReady, setIsReady] = useState(!IS_SINGLE_COLUMN_LAYOUT || animationLevel === ANIMATION_LEVEL_MIN);\n\n const hasTools = hasPinnedOrAudioMessage && (\n windowWidth < MOBILE_SCREEN_MAX_WIDTH\n || (\n isRightColumnShown && windowWidth > MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN\n && windowWidth < SAFE_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN\n ) || (\n windowWidth >= MIN_SCREEN_WIDTH_FOR_STATIC_LEFT_COLUMN\n && windowWidth < SAFE_SCREEN_WIDTH_FOR_CHAT_INFO\n )\n );\n\n const renderingChatId = usePrevDuringAnimation(chatId, CLOSE_ANIMATION_DURATION);\n const renderingThreadId = usePrevDuringAnimation(threadId, CLOSE_ANIMATION_DURATION);\n const renderingMessageListType = usePrevDuringAnimation(messageListType, CLOSE_ANIMATION_DURATION);\n const renderingCanPost = usePrevDuringAnimation(canPost, CLOSE_ANIMATION_DURATION);\n const renderingHasTools = usePrevDuringAnimation(hasTools, CLOSE_ANIMATION_DURATION);\n const renderingIsFabShown = usePrevDuringAnimation(isFabShown, CLOSE_ANIMATION_DURATION);\n\n useEffect(() => {\n return chatId\n ? captureEscKeyListener(() => {\n openChat({ id: undefined });\n })\n : undefined;\n }, [chatId, openChat]);\n\n useEffect(() => {\n setDropAreaState(DropAreaState.None);\n setIsFabShown(undefined);\n setIsNotchShown(undefined);\n }, [chatId]);\n\n useEffect(() => {\n if (animationLevel === ANIMATION_LEVEL_MIN) {\n setIsReady(true);\n }\n }, [animationLevel]);\n\n // Fix for mobile virtual keyboard\n useEffect(() => {\n const { visualViewport } = window as any;\n if (!visualViewport) {\n return undefined;\n }\n\n const handleResize = () => {\n if (window.visualViewport.height !== document.documentElement.clientHeight) {\n document.body.classList.add('keyboard-visible');\n } else {\n document.body.classList.remove('keyboard-visible');\n }\n };\n\n visualViewport.addEventListener('resize', handleResize);\n\n return () => {\n visualViewport.removeEventListener('resize', handleResize);\n };\n }, []);\n\n const handleTransitionEnd = (e: React.TransitionEvent<HTMLDivElement>) => {\n if (e.propertyName === 'transform' && e.target === e.currentTarget) {\n setIsReady(Boolean(chatId));\n }\n };\n\n useEffect(() => {\n if (isPrivate) {\n loadUser({ userId: chatId });\n }\n }, [chatId, isPrivate, loadUser]);\n\n const handleDragEnter = useCallback((e: React.DragEvent<HTMLDivElement>) => {\n if (IS_TOUCH_ENV) {\n return;\n }\n\n const { items } = e.dataTransfer || {};\n const shouldDrawQuick = items && Array.from(items)\n // Filter unnecessary element for drag and drop images in Firefox (https://github.com/Ajaxy/telegram-tt/issues/49)\n // https://developer.mozilla.org/en-US/docs/Web/API/HTML_Drag_and_Drop_API/Recommended_drag_types#image\n .filter((item) => item.type !== 'text/uri-list')\n // As of September 2021, native clients suggest \"send quick, but compressed\" only for images\n .every(isImage);\n\n setDropAreaState(shouldDrawQuick ? DropAreaState.QuickFile : DropAreaState.Document);\n }, []);\n\n const handleHideDropArea = useCallback(() => {\n setDropAreaState(DropAreaState.None);\n }, []);\n\n const handleOpenUnpinModal = useCallback(() => {\n setIsUnpinModalOpen(true);\n }, []);\n\n const closeUnpinModal = useCallback(() => {\n setIsUnpinModalOpen(false);\n }, []);\n\n const handleUnpinAllMessages = useCallback(() => {\n unpinAllMessages({ chatId });\n closeUnpinModal();\n openChat({ id: chatId });\n }, [unpinAllMessages, openChat, closeUnpinModal, chatId]);\n\n const handleTabletFocus = useCallback(() => {\n openChat({ id: chatId });\n }, [openChat, chatId]);\n\n const customBackgroundValue = useCustomBackground(theme, customBackground);\n\n const className = buildClassName(\n renderingHasTools && 'has-header-tools',\n customBackground && 'custom-bg-image',\n backgroundColor && 'custom-bg-color',\n customBackground && isBackgroundBlurred && 'blurred',\n MASK_IMAGE_DISABLED ? 'mask-image-disabled' : 'mask-image-enabled',\n );\n\n const messagingDisabledClassName = buildClassName(\n 'messaging-disabled',\n !isSelectModeActive && 'shown',\n );\n\n const messageSendingRestrictionReason = getMessageSendingRestrictionReason(\n lang, currentUserBannedRights, defaultBannedRights,\n );\n\n // CSS Variables calculation doesn't work properly with transforms, so we calculate transform values in JS\n const {\n composerHiddenScale, toolbarHiddenScale,\n composerTranslateX, toolbarTranslateX,\n unpinHiddenScale, toolbarForUnpinHiddenScale,\n } = useMemo(\n () => calculateMiddleFooterTransforms(windowWidth, renderingCanPost),\n [renderingCanPost, windowWidth],\n );\n\n const footerClassName = buildClassName(\n 'middle-column-footer',\n !renderingCanPost && 'no-composer',\n renderingCanPost && isNotchShown && !isSelectModeActive && 'with-notch',\n );\n\n const closeChat = () => {\n openChat({ id: undefined }, true);\n };\n\n useHistoryBack(renderingChatId && renderingThreadId,\n closeChat, undefined, undefined, undefined,\n messageLists ? messageLists.map(createMessageHash) : []);\n\n useHistoryBack(isMobileSearchActive, closeLocalTextSearch);\n useHistoryBack(isSelectModeActive, exitMessageSelectMode);\n\n const isMessagingDisabled = Boolean(!isPinnedMessageList && !renderingCanPost && messageSendingRestrictionReason);\n\n return (\n <div\n id=\"MiddleColumn\"\n className={className}\n onTransitionEnd={handleTransitionEnd}\n // @ts-ignore teact-feature\n style={`\n --composer-hidden-scale: ${composerHiddenScale};\n --toolbar-hidden-scale: ${toolbarHiddenScale};\n --unpin-hidden-scale: ${unpinHiddenScale};\n --toolbar-unpin-hidden-scale: ${toolbarForUnpinHiddenScale};\n --composer-translate-x: ${composerTranslateX}px;\n --toolbar-translate-x: ${toolbarTranslateX}px;\n --pattern-color: ${patternColor};\n --theme-background-color:\n ${backgroundColor || (theme === 'dark' ? DARK_THEME_BG_COLOR : LIGHT_THEME_BG_COLOR)};\n `}\n onClick={(IS_TABLET_COLUMN_LAYOUT && isLeftColumnShown) ? handleTabletFocus : undefined}\n >\n <div\n id=\"middle-column-bg\"\n // @ts-ignore\n style={customBackgroundValue ? `--custom-background: ${customBackgroundValue}` : undefined}\n />\n <div id=\"middle-column-portals\" />\n {renderingChatId && renderingThreadId && (\n <>\n <div className=\"messages-layout\" onDragEnter={renderingCanPost ? handleDragEnter : undefined}>\n <MiddleHeader\n chatId={renderingChatId}\n threadId={renderingThreadId}\n messageListType={renderingMessageListType}\n isReady={isReady}\n />\n <Transition\n name={shouldSkipHistoryAnimations ? 'none' : animationLevel === ANIMATION_LEVEL_MAX ? 'slide' : 'fade'}\n activeKey={currentTransitionKey}\n shouldCleanup\n >\n {(isActive) => (\n <>\n <MessageList\n key={`${renderingChatId}-${renderingThreadId}-${renderingMessageListType}`}\n chatId={renderingChatId}\n threadId={renderingThreadId}\n type={renderingMessageListType}\n canPost={renderingCanPost}\n hasTools={renderingHasTools}\n onFabToggle={setIsFabShown}\n onNotchToggle={setIsNotchShown}\n isReady={isReady}\n isActive={isActive}\n />\n <div className={footerClassName}>\n {renderingCanPost && (\n <Composer\n chatId={renderingChatId}\n threadId={renderingThreadId}\n messageListType={renderingMessageListType}\n dropAreaState={dropAreaState}\n onDropHide={handleHideDropArea}\n isReady={isReady}\n />\n )}\n {isPinnedMessageList && (\n <div className=\"unpin-button-container\" dir={lang.isRtl ? 'rtl' : undefined}>\n <Button\n size=\"tiny\"\n fluid\n color=\"secondary\"\n className=\"unpin-all-button\"\n onClick={handleOpenUnpinModal}\n >\n <i className=\"icon-unpin\" />\n <span>{lang('Chat.Pinned.UnpinAll', pinnedMessagesCount, 'i')}</span>\n </Button>\n </div>\n )}\n {isMessagingDisabled && (\n <div className={messagingDisabledClassName}>\n <div className=\"messaging-disabled-inner\">\n <span>\n {messageSendingRestrictionReason}\n </span>\n </div>\n </div>\n )}\n <MessageSelectToolbar\n messageListType={renderingMessageListType}\n isActive={isSelectModeActive}\n canPost={renderingCanPost}\n />\n <PaymentModal\n isOpen={Boolean(isPaymentModalOpen)}\n onClose={closePaymentModal}\n />\n <ReceiptModal\n isOpen={Boolean(isReceiptModalOpen)}\n onClose={clearReceipt}\n />\n </div>\n </>\n )}\n </Transition>\n\n <ScrollDownButton\n isShown={renderingIsFabShown}\n canPost={renderingCanPost}\n withExtraShift={isMessagingDisabled || isSelectModeActive || isPinnedMessageList}\n />\n </div>\n {IS_SINGLE_COLUMN_LAYOUT && <MobileSearch isActive={Boolean(isMobileSearchActive)} />}\n </>\n )}\n {chatId && (\n <UnpinAllMessagesModal\n isOpen={isUnpinModalOpen}\n chatId={chatId}\n pinnedMessagesCount={pinnedMessagesCount}\n onClose={closeUnpinModal}\n onUnpin={handleUnpinAllMessages}\n />\n )}\n </div>\n );\n};\n\nexport default memo(withGlobal(\n (global): StateProps => {\n const theme = selectTheme(global);\n const {\n isBlurred: isBackgroundBlurred, background: customBackground, backgroundColor, patternColor,\n } = global.settings.themes[theme] || {};\n\n const { messageLists } = global.messages;\n const currentMessageList = selectCurrentMessageList(global);\n const { isLeftColumnShown, chats: { listIds } } = global;\n\n const state: StateProps = {\n theme,\n customBackground,\n backgroundColor,\n patternColor,\n isLeftColumnShown,\n isRightColumnShown: selectIsRightColumnShown(global),\n isBackgroundBlurred,\n isMobileSearchActive: Boolean(IS_SINGLE_COLUMN_LAYOUT && selectCurrentTextSearch(global)),\n isSelectModeActive: selectIsInSelectMode(global),\n isPaymentModalOpen: global.payment.isPaymentModalOpen,\n isReceiptModalOpen: Boolean(global.payment.receipt),\n animationLevel: global.settings.byKey.animationLevel,\n currentTransitionKey: Math.max(0, global.messages.messageLists.length - 1),\n };\n\n if (!currentMessageList || !listIds.active) {\n return state;\n }\n\n const { chatId, threadId, type: messageListType } = currentMessageList;\n const chat = selectChat(global, chatId);\n const pinnedIds = selectPinnedIds(global, chatId);\n const { chatId: audioChatId, messageId: audioMessageId } = global.audioPlayer;\n\n const canPost = chat && getCanPostInChat(chat, threadId);\n const isBotNotStarted = selectIsChatBotNotStarted(global, chatId);\n const isPinnedMessageList = messageListType === 'pinned';\n const isScheduledMessageList = messageListType === 'scheduled';\n\n return {\n ...state,\n chatId,\n threadId,\n messageListType,\n isPrivate: isUserId(chatId),\n canPost: !isPinnedMessageList && (!chat || canPost) && !isBotNotStarted,\n isPinnedMessageList,\n isScheduledMessageList,\n currentUserBannedRights: chat?.currentUserBannedRights,\n defaultBannedRights: chat?.defaultBannedRights,\n hasPinnedOrAudioMessage: (\n threadId !== MAIN_THREAD_ID\n || Boolean(pinnedIds?.length)\n || Boolean(audioChatId && audioMessageId)\n ),\n pinnedMessagesCount: pinnedIds ? pinnedIds.length : 0,\n shouldSkipHistoryAnimations: global.shouldSkipHistoryAnimations,\n messageLists,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'openChat', 'unpinAllMessages', 'loadUser', 'closeLocalTextSearch', 'exitMessageSelectMode',\n 'closePaymentModal', 'clearReceipt',\n ]),\n)(MiddleColumn));\n","import { useEffect, useState } from '../lib/teact/teact';\n\nimport { ThemeKey } from '../types';\n\nimport { CUSTOM_BG_CACHE_NAME } from '../config';\nimport * as cacheApi from '../util/cacheApi';\nimport { preloadImage } from '../util/files';\n\nexport default (theme: ThemeKey, settingValue?: string) => {\n const [value, setValue] = useState(settingValue);\n\n useEffect(() => {\n if (!settingValue) {\n return;\n }\n\n if (settingValue.startsWith('#')) {\n setValue(settingValue);\n } else {\n cacheApi.fetch(CUSTOM_BG_CACHE_NAME, theme, cacheApi.Type.Blob)\n .then((blob) => {\n const url = URL.createObjectURL(blob);\n preloadImage(url)\n .then(() => {\n setValue(`url(${url})`);\n });\n });\n }\n }, [settingValue, theme]);\n\n return settingValue ? value : undefined;\n};\n","import React, {\n FC, memo, useCallback, useEffect, useRef, useState,\n} from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../global/types';\nimport { ManagementScreens, ProfileState } from '../../types';\n\nimport { IS_SINGLE_COLUMN_LAYOUT } from '../../util/environment';\nimport { debounce } from '../../util/schedulers';\nimport { pick } from '../../util/iteratees';\nimport buildClassName from '../../util/buildClassName';\nimport {\n selectChat,\n selectCurrentGifSearch,\n selectCurrentStickerSearch,\n selectCurrentTextSearch,\n selectIsChatWithSelf,\n selectUser,\n} from '../../modules/selectors';\nimport {\n getCanAddContact,\n isChatAdmin,\n isChatChannel,\n isUserId,\n} from '../../modules/helpers';\nimport useCurrentOrPrev from '../../hooks/useCurrentOrPrev';\nimport useLang from '../../hooks/useLang';\n\nimport SearchInput from '../ui/SearchInput';\nimport Button from '../ui/Button';\nimport Transition from '../ui/Transition';\nimport './RightHeader.scss';\nimport { getDayStartAt } from '../../util/dateFormat';\n\ntype OwnProps = {\n chatId?: string;\n isColumnOpen?: boolean;\n isProfile?: boolean;\n isSearch?: boolean;\n isManagement?: boolean;\n isStickerSearch?: boolean;\n isGifSearch?: boolean;\n isPollResults?: boolean;\n isAddingChatMembers?: boolean;\n shouldSkipAnimation?: boolean;\n profileState?: ProfileState;\n managementScreen?: ManagementScreens;\n onClose: () => void;\n};\n\ntype StateProps = {\n canAddContact?: boolean;\n canManage?: boolean;\n isChannel?: boolean;\n userId?: string;\n messageSearchQuery?: string;\n stickerSearchQuery?: string;\n gifSearchQuery?: string;\n};\n\ntype DispatchProps = Pick<GlobalActions, (\n 'setLocalTextSearchQuery' | 'setStickerSearchQuery' | 'setGifSearchQuery' |\n 'searchTextMessagesLocal' | 'toggleManagement' | 'openHistoryCalendar' | 'addContact'\n)>;\n\nconst COLUMN_CLOSE_DELAY_MS = 300;\nconst runDebouncedForSearch = debounce((cb) => cb(), 200, false);\n\nenum HeaderContent {\n Profile,\n MemberList,\n SharedMedia,\n Search,\n Management,\n ManageInitial,\n ManageChannelSubscribers,\n ManageChatAdministrators,\n ManageChatPrivacyType,\n ManageDiscussion,\n ManageGroupPermissions,\n ManageGroupRemovedUsers,\n ManageGroupUserPermissionsCreate,\n ManageGroupUserPermissions,\n ManageGroupRecentActions,\n ManageGroupAdminRights,\n ManageGroupMembers,\n StickerSearch,\n GifSearch,\n PollResults,\n AddingMembers,\n}\n\nconst RightHeader: FC<OwnProps & StateProps & DispatchProps> = ({\n isColumnOpen,\n isProfile,\n isSearch,\n isManagement,\n isStickerSearch,\n isGifSearch,\n isPollResults,\n isAddingChatMembers,\n profileState,\n managementScreen,\n canAddContact,\n userId,\n canManage,\n isChannel,\n onClose,\n messageSearchQuery,\n stickerSearchQuery,\n gifSearchQuery,\n setLocalTextSearchQuery,\n setStickerSearchQuery,\n setGifSearchQuery,\n searchTextMessagesLocal,\n toggleManagement,\n openHistoryCalendar,\n shouldSkipAnimation,\n addContact,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const backButtonRef = useRef<HTMLDivElement>(null);\n\n const handleMessageSearchQueryChange = useCallback((query: string) => {\n setLocalTextSearchQuery({ query });\n\n if (query.length) {\n runDebouncedForSearch(searchTextMessagesLocal);\n }\n }, [searchTextMessagesLocal, setLocalTextSearchQuery]);\n\n const handleStickerSearchQueryChange = useCallback((query: string) => {\n setStickerSearchQuery({ query });\n }, [setStickerSearchQuery]);\n\n const handleGifSearchQueryChange = useCallback((query: string) => {\n setGifSearchQuery({ query });\n }, [setGifSearchQuery]);\n\n const handleAddContact = useCallback(() => {\n addContact({ userId });\n }, [addContact, userId]);\n\n const [shouldSkipTransition, setShouldSkipTransition] = useState(!isColumnOpen);\n\n useEffect(() => {\n setTimeout(() => {\n setShouldSkipTransition(!isColumnOpen);\n }, COLUMN_CLOSE_DELAY_MS);\n }, [isColumnOpen]);\n\n const lang = useLang();\n const contentKey = isProfile ? (\n profileState === ProfileState.Profile ? (\n HeaderContent.Profile\n ) : profileState === ProfileState.SharedMedia ? (\n HeaderContent.SharedMedia\n ) : profileState === ProfileState.MemberList ? (\n HeaderContent.MemberList\n ) : -1 // Never reached\n ) : isSearch ? (\n HeaderContent.Search\n ) : isPollResults ? (\n HeaderContent.PollResults\n ) : isStickerSearch ? (\n HeaderContent.StickerSearch\n ) : isGifSearch ? (\n HeaderContent.GifSearch\n ) : isAddingChatMembers ? (\n HeaderContent.AddingMembers\n ) : isManagement ? (\n managementScreen === ManagementScreens.Initial ? (\n HeaderContent.ManageInitial\n ) : managementScreen === ManagementScreens.ChatPrivacyType ? (\n HeaderContent.ManageChatPrivacyType\n ) : managementScreen === ManagementScreens.Discussion ? (\n HeaderContent.ManageDiscussion\n ) : managementScreen === ManagementScreens.ChannelSubscribers ? (\n HeaderContent.ManageChannelSubscribers\n ) : managementScreen === ManagementScreens.GroupPermissions ? (\n HeaderContent.ManageGroupPermissions\n ) : managementScreen === ManagementScreens.ChatAdministrators ? (\n HeaderContent.ManageChatAdministrators\n ) : managementScreen === ManagementScreens.GroupRemovedUsers ? (\n HeaderContent.ManageGroupRemovedUsers\n ) : managementScreen === ManagementScreens.GroupUserPermissionsCreate ? (\n HeaderContent.ManageGroupUserPermissionsCreate\n ) : managementScreen === ManagementScreens.GroupUserPermissions ? (\n HeaderContent.ManageGroupUserPermissions\n ) : managementScreen === ManagementScreens.GroupRecentActions ? (\n HeaderContent.ManageGroupRecentActions\n ) : managementScreen === ManagementScreens.ChatAdminRights ? (\n HeaderContent.ManageGroupAdminRights\n ) : managementScreen === ManagementScreens.GroupMembers ? (\n HeaderContent.ManageGroupMembers\n ) : undefined // Never reached\n ) : undefined; // When column is closed\n\n const renderingContentKey = useCurrentOrPrev(contentKey, true) ?? -1;\n\n function renderHeaderContent() {\n if (renderingContentKey === -1) {\n return undefined;\n }\n\n switch (renderingContentKey) {\n case HeaderContent.PollResults:\n return <h3>{lang('PollResults')}</h3>;\n case HeaderContent.Search:\n return (\n <>\n <SearchInput\n parentContainerClassName=\"RightSearch\"\n value={messageSearchQuery}\n onChange={handleMessageSearchQueryChange}\n />\n <Button\n round\n size=\"smaller\"\n color=\"translucent\"\n onClick={() => openHistoryCalendar({ selectedAt: getDayStartAt(Date.now()) })}\n ariaLabel=\"Search messages by date\"\n >\n <i className=\"icon-calendar\" />\n </Button>\n </>\n );\n case HeaderContent.AddingMembers:\n return <h3>{lang('GroupAddMembers')}</h3>;\n case HeaderContent.ManageInitial:\n return <h3>{lang('Edit')}</h3>;\n case HeaderContent.ManageChatPrivacyType:\n return <h3>{lang(isChannel ? 'ChannelTypeHeader' : 'GroupTypeHeader')}</h3>;\n case HeaderContent.ManageDiscussion:\n return <h3>{lang('Discussion')}</h3>;\n case HeaderContent.ManageChatAdministrators:\n return <h3>{lang('ChannelAdministrators')}</h3>;\n case HeaderContent.ManageGroupRecentActions:\n return <h3>{lang('Group.Info.AdminLog')}</h3>;\n case HeaderContent.ManageGroupAdminRights:\n return <h3>{lang('EditAdminRights')}</h3>;\n case HeaderContent.ManageGroupPermissions:\n return <h3>{lang('ChannelPermissions')}</h3>;\n case HeaderContent.ManageGroupRemovedUsers:\n return <h3>{lang('ChannelBlockedUsers')}</h3>;\n case HeaderContent.ManageGroupUserPermissionsCreate:\n return <h3>{lang('ChannelAddException')}</h3>;\n case HeaderContent.ManageGroupUserPermissions:\n return <h3>{lang('UserRestrictions')}</h3>;\n case HeaderContent.StickerSearch:\n return (\n <SearchInput\n value={stickerSearchQuery}\n placeholder={lang('SearchStickersHint')}\n autoFocusSearch\n onChange={handleStickerSearchQueryChange}\n />\n );\n case HeaderContent.GifSearch:\n return (\n <SearchInput\n value={gifSearchQuery}\n placeholder={lang('SearchGifsTitle')}\n autoFocusSearch\n onChange={handleGifSearchQueryChange}\n />\n );\n case HeaderContent.SharedMedia:\n return <h3>{lang('SharedMedia')}</h3>;\n case HeaderContent.ManageChannelSubscribers:\n return <h3>{lang('ChannelSubscribers')}</h3>;\n case HeaderContent.MemberList:\n case HeaderContent.ManageGroupMembers:\n return <h3>{lang('GroupMembers')}</h3>;\n default:\n return (\n <>\n <h3>Profile</h3>\n <section className=\"tools\">\n {canAddContact && (\n <Button\n round\n color=\"translucent\"\n size=\"smaller\"\n ariaLabel={lang('AddContact')}\n onClick={handleAddContact}\n >\n <i className=\"icon-add-user\" />\n </Button>\n )}\n {canManage && (\n <Button\n round\n color=\"translucent\"\n size=\"smaller\"\n ariaLabel={lang('Edit')}\n onClick={toggleManagement}\n >\n <i className=\"icon-edit\" />\n </Button>\n )}\n </section>\n </>\n );\n }\n }\n\n const isBackButton = (\n IS_SINGLE_COLUMN_LAYOUT\n || contentKey === HeaderContent.SharedMedia\n || contentKey === HeaderContent.MemberList\n || contentKey === HeaderContent.AddingMembers\n || isManagement\n );\n\n const buttonClassName = buildClassName(\n 'animated-close-icon',\n isBackButton && 'state-back',\n (shouldSkipTransition || shouldSkipAnimation) && 'no-transition',\n );\n\n return (\n <div className=\"RightHeader\">\n <Button\n className=\"close-button\"\n round\n color=\"translucent\"\n size=\"smaller\"\n onClick={onClose}\n ariaLabel={isBackButton ? lang('Common.Back') : lang('Common.Close')}\n >\n <div ref={backButtonRef} className={buttonClassName} />\n </Button>\n <Transition\n name={(shouldSkipTransition || shouldSkipAnimation) ? 'none' : 'slide-fade'}\n activeKey={renderingContentKey}\n >\n {renderHeaderContent}\n </Transition>\n </div>\n );\n};\n\nexport default memo(withGlobal<OwnProps>(\n (global, { chatId, isProfile, isManagement }): StateProps => {\n const { query: messageSearchQuery } = selectCurrentTextSearch(global) || {};\n const { query: stickerSearchQuery } = selectCurrentStickerSearch(global) || {};\n const { query: gifSearchQuery } = selectCurrentGifSearch(global) || {};\n const chat = chatId ? selectChat(global, chatId) : undefined;\n const isChannel = chat && isChatChannel(chat);\n const user = isProfile && chatId && isUserId(chatId) ? selectUser(global, chatId) : undefined;\n\n const canAddContact = user && getCanAddContact(user);\n const canManage = Boolean(\n !isManagement\n && isProfile\n && !canAddContact\n && chat\n && !selectIsChatWithSelf(global, chat.id)\n // chat.isCreator is for Basic Groups\n && (isUserId(chat.id) || ((isChatAdmin(chat) || chat.isCreator) && !chat.isNotJoined)),\n );\n\n return {\n canManage,\n canAddContact,\n isChannel,\n userId: user?.id,\n messageSearchQuery,\n stickerSearchQuery,\n gifSearchQuery,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'setLocalTextSearchQuery',\n 'setStickerSearchQuery',\n 'setGifSearchQuery',\n 'searchTextMessagesLocal',\n 'toggleManagement',\n 'openHistoryCalendar',\n 'addContact',\n ]),\n)(RightHeader));\n","import { useMemo, useRef } from '../../../lib/teact/teact';\n\nimport {\n ApiChat, ApiChatMember, ApiMessage, ApiUser,\n} from '../../../api/types';\nimport { ProfileTabType, SharedMediaType } from '../../../types';\n\nimport { MEMBERS_SLICE, MESSAGE_SEARCH_SLICE, SHARED_MEDIA_SLICE } from '../../../config';\nimport { getMessageContentIds, sortChatIds, sortUserIds } from '../../../modules/helpers';\nimport useOnChange from '../../../hooks/useOnChange';\nimport useInfiniteScroll from '../../../hooks/useInfiniteScroll';\n\nexport default function useProfileViewportIds(\n isRightColumnShown: boolean,\n loadMoreMembers: AnyToVoidFunction,\n loadCommonChats: AnyToVoidFunction,\n searchMessages: AnyToVoidFunction,\n tabType: ProfileTabType,\n mediaSearchType?: SharedMediaType,\n groupChatMembers?: ApiChatMember[],\n commonChatIds?: string[],\n usersById?: Record<string, ApiUser>,\n chatsById?: Record<string, ApiChat>,\n chatMessages?: Record<number, ApiMessage>,\n foundIds?: number[],\n chatId?: string,\n lastSyncTime?: number,\n serverTimeOffset = 0,\n) {\n const resultType = tabType === 'members' || !mediaSearchType ? tabType : mediaSearchType;\n\n const memberIds = useMemo(() => {\n if (!groupChatMembers || !usersById) {\n return undefined;\n }\n\n return sortUserIds(groupChatMembers.map(({ userId }) => userId), usersById, undefined, serverTimeOffset);\n }, [groupChatMembers, serverTimeOffset, usersById]);\n\n const chatIds = useMemo(() => {\n if (!commonChatIds || !chatsById) {\n return undefined;\n }\n\n return sortChatIds(commonChatIds, chatsById, true);\n }, [chatsById, commonChatIds]);\n\n const [memberViewportIds, getMoreMembers, noProfileInfoForMembers] = useInfiniteScrollForLoadableItems(\n resultType, loadMoreMembers, lastSyncTime, memberIds,\n );\n\n const [commonChatViewportIds, getMoreCommonChats, noProfileInfoForCommonChats] = useInfiniteScrollForLoadableItems(\n resultType, loadCommonChats, lastSyncTime, chatIds,\n );\n\n const [mediaViewportIds, getMoreMedia, noProfileInfoForMedia] = useInfiniteScrollForSharedMedia(\n 'media', resultType, searchMessages, lastSyncTime, chatMessages, foundIds,\n );\n\n const [documentViewportIds, getMoreDocuments, noProfileInfoForDocuments] = useInfiniteScrollForSharedMedia(\n 'documents', resultType, searchMessages, lastSyncTime, chatMessages, foundIds,\n );\n\n const [linkViewportIds, getMoreLinks, noProfileInfoForLinks] = useInfiniteScrollForSharedMedia(\n 'links', resultType, searchMessages, lastSyncTime, chatMessages, foundIds,\n );\n\n const [audioViewportIds, getMoreAudio, noProfileInfoForAudio] = useInfiniteScrollForSharedMedia(\n 'audio', resultType, searchMessages, lastSyncTime, chatMessages, foundIds,\n );\n\n const [voiceViewportIds, getMoreVoices, noProfileInfoForVoices] = useInfiniteScrollForSharedMedia(\n 'voice', resultType, searchMessages, lastSyncTime, chatMessages, foundIds,\n );\n\n let viewportIds: number[] | string[] | undefined;\n let getMore: AnyToVoidFunction | undefined;\n let noProfileInfo = false;\n\n switch (resultType) {\n case 'members':\n viewportIds = memberViewportIds;\n getMore = getMoreMembers;\n noProfileInfo = noProfileInfoForMembers;\n break;\n case 'commonChats':\n viewportIds = commonChatViewportIds;\n getMore = getMoreCommonChats;\n noProfileInfo = noProfileInfoForCommonChats;\n break;\n case 'media':\n viewportIds = mediaViewportIds;\n getMore = getMoreMedia;\n noProfileInfo = noProfileInfoForMedia;\n break;\n case 'documents':\n viewportIds = documentViewportIds;\n getMore = getMoreDocuments;\n noProfileInfo = noProfileInfoForDocuments;\n break;\n case 'links':\n viewportIds = linkViewportIds;\n getMore = getMoreLinks;\n noProfileInfo = noProfileInfoForLinks;\n break;\n case 'audio':\n viewportIds = audioViewportIds;\n getMore = getMoreAudio;\n noProfileInfo = noProfileInfoForAudio;\n break;\n case 'voice':\n viewportIds = voiceViewportIds;\n getMore = getMoreVoices;\n noProfileInfo = noProfileInfoForVoices;\n break;\n }\n\n return [resultType, viewportIds, getMore, noProfileInfo] as const;\n}\n\nfunction useInfiniteScrollForLoadableItems(\n currentResultType?: ProfileTabType,\n handleLoadMore?: AnyToVoidFunction,\n lastSyncTime?: number,\n itemIds?: string[],\n) {\n const [viewportIds, getMore] = useInfiniteScroll(\n lastSyncTime ? handleLoadMore : undefined,\n itemIds,\n undefined,\n MEMBERS_SLICE,\n );\n\n const isOnTop = !viewportIds || !itemIds || viewportIds[0] === itemIds[0];\n\n return [viewportIds, getMore, !isOnTop] as const;\n}\n\nfunction useInfiniteScrollForSharedMedia(\n forSharedMediaType: SharedMediaType,\n currentResultType?: ProfileTabType,\n handleLoadMore?: AnyToVoidFunction,\n lastSyncTime?: number,\n chatMessages?: Record<number, ApiMessage>,\n foundIds?: number[],\n) {\n const messageIdsRef = useRef<number[]>();\n\n useOnChange(() => {\n if (currentResultType === forSharedMediaType && chatMessages && foundIds) {\n messageIdsRef.current = getMessageContentIds(\n chatMessages,\n foundIds,\n forSharedMediaType,\n ).reverse();\n }\n }, [chatMessages, foundIds, currentResultType, forSharedMediaType]);\n\n const [viewportIds, getMore] = useInfiniteScroll(\n lastSyncTime ? handleLoadMore : undefined,\n messageIdsRef.current,\n undefined,\n forSharedMediaType === 'media' ? SHARED_MEDIA_SLICE : MESSAGE_SEARCH_SLICE,\n );\n\n const isOnTop = !viewportIds || !messageIdsRef.current || viewportIds[0] === messageIdsRef.current[0];\n\n return [viewportIds, getMore, !isOnTop] as const;\n}\n","import { useCallback, useEffect } from '../../../lib/teact/teact';\n\nimport { ProfileState } from '../../../types';\n\nimport fastSmoothScroll from '../../../util/fastSmoothScroll';\nimport { throttle } from '../../../util/schedulers';\nimport useEffectWithPrevDeps from '../../../hooks/useEffectWithPrevDeps';\n\nconst TRANSITION_DURATION = 300;\nconst PROGRAMMATIC_SCROLL_TIMEOUT_MS = 350;\n\nconst runThrottledForScroll = throttle((cb) => cb(), 250, false);\n\nlet isScrollingProgrammatically = false;\n\nexport default function useProfileState(\n containerRef: { current: HTMLDivElement | null },\n tabType: string,\n profileState: ProfileState,\n onProfileStateChange: (state: ProfileState) => void,\n) {\n // Scroll to tabs if needed\n useEffectWithPrevDeps(([prevTabType]) => {\n if (prevTabType && prevTabType !== tabType) {\n const container = containerRef.current!;\n const tabsEl = container.querySelector<HTMLDivElement>('.TabList')!;\n if (container.scrollTop < tabsEl.offsetTop) {\n onProfileStateChange(tabType === 'members' ? ProfileState.MemberList : ProfileState.SharedMedia);\n isScrollingProgrammatically = true;\n fastSmoothScroll(container, tabsEl, 'start', undefined, undefined, undefined, TRANSITION_DURATION);\n setTimeout(() => {\n isScrollingProgrammatically = false;\n }, PROGRAMMATIC_SCROLL_TIMEOUT_MS);\n }\n }\n }, [tabType, onProfileStateChange]);\n\n // Scroll to top\n useEffectWithPrevDeps(([prevProfileState]) => {\n if (profileState !== ProfileState.Profile || profileState === prevProfileState) {\n return;\n }\n\n const container = containerRef.current;\n if (!container) {\n return;\n }\n\n const tabListEl = container.querySelector<HTMLDivElement>('.TabList');\n if (!tabListEl) {\n return;\n }\n\n isScrollingProgrammatically = true;\n fastSmoothScroll(\n container,\n container.firstElementChild as HTMLElement,\n 'start',\n undefined,\n container.offsetHeight * 2,\n );\n\n setTimeout(() => {\n isScrollingProgrammatically = false;\n }, PROGRAMMATIC_SCROLL_TIMEOUT_MS);\n\n onProfileStateChange(profileState);\n }, [profileState]);\n\n const determineProfileState = useCallback(() => {\n const container = containerRef.current;\n if (!container) {\n return;\n }\n\n const tabListEl = container.querySelector<HTMLDivElement>('.TabList');\n if (!tabListEl) {\n return;\n }\n\n let state: ProfileState = ProfileState.Profile;\n if (container.scrollTop >= tabListEl.offsetTop) {\n state = tabType === 'members'\n ? ProfileState.MemberList\n : ProfileState.SharedMedia;\n }\n\n onProfileStateChange(state);\n }, [containerRef, onProfileStateChange, tabType]);\n\n // Determine profile state when switching tabs\n useEffect(() => {\n if (isScrollingProgrammatically) {\n return;\n }\n\n determineProfileState();\n }, [determineProfileState, tabType]);\n\n // Determine profile state when scrolling\n const handleScroll = useCallback(() => {\n if (isScrollingProgrammatically) {\n return;\n }\n\n runThrottledForScroll(determineProfileState);\n }, [determineProfileState]);\n\n return { handleScroll };\n}\n","import React, { FC, useCallback, memo } from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../global/types';\nimport { ApiChat } from '../../api/types';\n\nimport { pick } from '../../util/iteratees';\nimport { selectCurrentChat, selectUser } from '../../modules/selectors';\nimport { getUserFirstOrLastName } from '../../modules/helpers';\nimport renderText from '../common/helpers/renderText';\nimport useLang from '../../hooks/useLang';\n\nimport Modal from '../ui/Modal';\nimport Button from '../ui/Button';\n\nexport type OwnProps = {\n isOpen: boolean;\n userId?: string;\n onClose: () => void;\n};\n\ntype StateProps = {\n chat?: ApiChat;\n contactName?: string;\n};\n\ntype DispatchProps = Pick<GlobalActions, 'deleteChatMember'>;\n\nconst DeleteMemberModal: FC<OwnProps & StateProps & DispatchProps> = ({\n isOpen,\n chat,\n userId,\n contactName,\n onClose,\n deleteChatMember,\n}) => {\n const lang = useLang();\n\n const handleDeleteChatMember = useCallback(() => {\n deleteChatMember({ chatId: chat!.id, userId });\n onClose();\n }, [chat, deleteChatMember, onClose, userId]);\n\n if (!chat || !userId) {\n return undefined;\n }\n\n return (\n <Modal\n isOpen={isOpen}\n onClose={onClose}\n onEnter={handleDeleteChatMember}\n className=\"delete\"\n title={lang('GroupRemoved.Remove')}\n >\n <p>{renderText(lang('PeerInfo.Confirm.RemovePeer', contactName))}</p>\n <Button color=\"danger\" className=\"confirm-dialog-button\" isText onClick={handleDeleteChatMember}>\n {lang('lng_box_remove')}\n </Button>\n <Button className=\"confirm-dialog-button\" isText onClick={onClose}>{lang('Cancel')}</Button>\n </Modal>\n );\n};\n\nexport default memo(withGlobal<OwnProps>(\n (global, { userId }): StateProps => {\n const chat = selectCurrentChat(global);\n const user = userId && selectUser(global, userId);\n const contactName = user ? getUserFirstOrLastName(user) : undefined;\n\n return {\n chat,\n contactName,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, ['deleteChatMember']),\n)(DeleteMemberModal));\n","import React, {\n FC, useCallback, useEffect, useMemo, useRef, useState, memo,\n} from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport {\n ApiMessage,\n ApiChatMember,\n ApiUser,\n ApiChat,\n MAIN_THREAD_ID,\n} from '../../api/types';\nimport { GlobalActions } from '../../global/types';\nimport {\n NewChatMembersProgress, ISettings, MediaViewerOrigin, ProfileState, ProfileTabType, SharedMediaType, AudioOrigin,\n} from '../../types';\n\nimport {\n MEMBERS_SLICE,\n PROFILE_SENSITIVE_AREA,\n SHARED_MEDIA_SLICE,\n SLIDE_TRANSITION_DURATION,\n} from '../../config';\nimport { IS_TOUCH_ENV } from '../../util/environment';\nimport {\n getHasAdminRight, isChatAdmin, isChatChannel, isChatGroup, isUserBot, isUserId,\n} from '../../modules/helpers';\nimport {\n selectChatMessages,\n selectChat,\n selectCurrentMediaSearch,\n selectIsRightColumnShown,\n selectTheme,\n selectActiveDownloadIds,\n selectUser,\n} from '../../modules/selectors';\nimport { pick } from '../../util/iteratees';\nimport { captureEvents, SwipeDirection } from '../../util/captureEvents';\nimport { getSenderName } from '../left/search/helpers/getSenderName';\nimport useCacheBuster from '../../hooks/useCacheBuster';\nimport useProfileViewportIds from './hooks/useProfileViewportIds';\nimport useProfileState from './hooks/useProfileState';\nimport useTransitionFixes from './hooks/useTransitionFixes';\nimport useAsyncRendering from './hooks/useAsyncRendering';\nimport useLang from '../../hooks/useLang';\n\nimport Transition from '../ui/Transition';\nimport InfiniteScroll from '../ui/InfiniteScroll';\nimport TabList from '../ui/TabList';\nimport Spinner from '../ui/Spinner';\nimport ListItem from '../ui/ListItem';\nimport PrivateChatInfo from '../common/PrivateChatInfo';\nimport ProfileInfo from '../common/ProfileInfo';\nimport Document from '../common/Document';\nimport Audio from '../common/Audio';\nimport ChatExtra from '../common/ChatExtra';\nimport Media from '../common/Media';\nimport WebLink from '../common/WebLink';\nimport NothingFound from '../common/NothingFound';\nimport FloatingActionButton from '../ui/FloatingActionButton';\nimport DeleteMemberModal from './DeleteMemberModal';\nimport GroupChatInfo from '../common/GroupChatInfo';\n\nimport './Profile.scss';\n\ntype OwnProps = {\n chatId: string;\n userId?: string;\n profileState: ProfileState;\n onProfileStateChange: (state: ProfileState) => void;\n};\n\ntype StateProps = {\n theme: ISettings['theme'];\n isChannel?: boolean;\n currentUserId?: string;\n resolvedUserId?: string;\n chatMessages?: Record<number, ApiMessage>;\n foundIds?: number[];\n mediaSearchType?: SharedMediaType;\n hasCommonChatsTab?: boolean;\n hasMembersTab?: boolean;\n areMembersHidden?: boolean;\n canAddMembers?: boolean;\n canDeleteMembers?: boolean;\n members?: ApiChatMember[];\n commonChatIds?: string[];\n chatsById: Record<string, ApiChat>;\n usersById: Record<string, ApiUser>;\n isRightColumnShown: boolean;\n isRestricted?: boolean;\n lastSyncTime?: number;\n serverTimeOffset: number;\n activeDownloadIds: number[];\n};\n\ntype DispatchProps = Pick<GlobalActions, (\n 'setLocalMediaSearchType' | 'loadMoreMembers' | 'searchMediaMessagesLocal' | 'openMediaViewer' | 'loadCommonChats' |\n 'openAudioPlayer' | 'openUserInfo' | 'focusMessage' | 'loadProfilePhotos' | 'setNewChatMembersDialogState' |\n 'openChat'\n)>;\n\nconst TABS = [\n { type: 'media', title: 'SharedMediaTab2' },\n { type: 'documents', title: 'SharedFilesTab2' },\n { type: 'links', title: 'SharedLinksTab2' },\n { type: 'audio', title: 'SharedMusicTab2' },\n { type: 'voice', title: 'SharedVoiceTab2' },\n];\n\nconst HIDDEN_RENDER_DELAY = 1000;\n\nconst Profile: FC<OwnProps & StateProps & DispatchProps> = ({\n chatId,\n profileState,\n onProfileStateChange,\n theme,\n isChannel,\n resolvedUserId,\n currentUserId,\n chatMessages,\n foundIds,\n mediaSearchType,\n hasCommonChatsTab,\n hasMembersTab,\n areMembersHidden,\n canAddMembers,\n canDeleteMembers,\n commonChatIds,\n members,\n usersById,\n chatsById,\n isRightColumnShown,\n isRestricted,\n lastSyncTime,\n activeDownloadIds,\n serverTimeOffset,\n setLocalMediaSearchType,\n loadMoreMembers,\n loadCommonChats,\n openChat,\n searchMediaMessagesLocal,\n openMediaViewer,\n openAudioPlayer,\n openUserInfo,\n focusMessage,\n loadProfilePhotos,\n setNewChatMembersDialogState,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const containerRef = useRef<HTMLDivElement>(null);\n // eslint-disable-next-line no-null/no-null\n const transitionRef = useRef<HTMLDivElement>(null);\n const lang = useLang();\n const [activeTab, setActiveTab] = useState(0);\n const [deletingUserId, setDeletingUserId] = useState<string | undefined>();\n\n const tabs = useMemo(() => ([\n ...(hasMembersTab ? [{\n type: 'members', title: isChannel ? 'ChannelSubscribers' : 'GroupMembers',\n }] : []),\n ...TABS,\n ...(hasCommonChatsTab ? [{\n type: 'commonChats', title: 'SharedGroupsTab2',\n }] : []),\n ]), [hasCommonChatsTab, hasMembersTab, isChannel]);\n const tabType = tabs[activeTab].type as ProfileTabType;\n\n const [resultType, viewportIds, getMore, noProfileInfo] = useProfileViewportIds(\n isRightColumnShown, loadMoreMembers, loadCommonChats, searchMediaMessagesLocal, tabType, mediaSearchType, members,\n commonChatIds, usersById, chatsById, chatMessages, foundIds, chatId, lastSyncTime, serverTimeOffset,\n );\n const activeKey = tabs.findIndex(({ type }) => type === resultType);\n\n const { handleScroll } = useProfileState(containerRef, tabType, profileState, onProfileStateChange);\n\n const { applyTransitionFix, releaseTransitionFix } = useTransitionFixes(containerRef);\n\n const [cacheBuster, resetCacheBuster] = useCacheBuster();\n\n const handleTransitionStop = useCallback(() => {\n releaseTransitionFix();\n resetCacheBuster();\n }, [releaseTransitionFix, resetCacheBuster]);\n\n const handleNewMemberDialogOpen = useCallback(() => {\n setNewChatMembersDialogState(NewChatMembersProgress.InProgress);\n }, [setNewChatMembersDialogState]);\n\n // Update search type when switching tabs\n useEffect(() => {\n setLocalMediaSearchType({ mediaType: tabType });\n }, [setLocalMediaSearchType, tabType]);\n\n const profileId = resolvedUserId || chatId;\n\n useEffect(() => {\n if (lastSyncTime) {\n loadProfilePhotos({ profileId });\n }\n }, [loadProfilePhotos, profileId, lastSyncTime]);\n\n const handleSelectMedia = useCallback((messageId: number) => {\n openMediaViewer({\n chatId: profileId,\n threadId: MAIN_THREAD_ID,\n messageId,\n origin: MediaViewerOrigin.SharedMedia,\n });\n }, [profileId, openMediaViewer]);\n\n const handlePlayAudio = useCallback((messageId: number) => {\n openAudioPlayer({ chatId: profileId, messageId, origin: AudioOrigin.SharedMedia });\n }, [profileId, openAudioPlayer]);\n\n const handleMemberClick = useCallback((id: string) => {\n openUserInfo({ id });\n }, [openUserInfo]);\n\n const handleMessageFocus = useCallback((messageId: number) => {\n focusMessage({ chatId: profileId, messageId });\n }, [profileId, focusMessage]);\n\n const handleDeleteMembersModalClose = useCallback(() => {\n setDeletingUserId(undefined);\n }, []);\n\n useEffect(() => {\n if (!transitionRef.current || !IS_TOUCH_ENV) {\n return undefined;\n }\n\n return captureEvents(transitionRef.current, {\n selectorToPreventScroll: '.Profile',\n onSwipe: ((e, direction) => {\n if (direction === SwipeDirection.Left) {\n setActiveTab(Math.min(activeTab + 1, tabs.length - 1));\n return true;\n } else if (direction === SwipeDirection.Right) {\n setActiveTab(Math.max(0, activeTab - 1));\n return true;\n }\n\n return false;\n }),\n });\n }, [activeTab, tabs.length]);\n\n let renderingDelay;\n const isFirstTab = resultType === 'members' || (!hasMembersTab && resultType === 'media');\n // @optimization Used to unparallelize rendering of message list and profile media\n if (isFirstTab) {\n renderingDelay = !isRightColumnShown ? HIDDEN_RENDER_DELAY : 0;\n // @optimization Used to delay first render of secondary tabs while animating\n } else if (!viewportIds) {\n renderingDelay = SLIDE_TRANSITION_DURATION;\n }\n const canRenderContents = useAsyncRendering([chatId, resultType], renderingDelay);\n\n function getMemberContextAction(memberId: string) {\n return memberId === currentUserId || !canDeleteMembers ? undefined : [{\n title: lang('lng_context_remove_from_group'),\n icon: 'stop',\n handler: () => {\n setDeletingUserId(memberId);\n },\n }];\n }\n\n function renderSharedMedia() {\n if (!viewportIds || !canRenderContents || !chatMessages) {\n // This is just a single-frame delay, so we do not show spinner\n const noSpinner = isFirstTab && viewportIds && !canRenderContents;\n\n return (\n <div className=\"content empty-list\">\n {!noSpinner && <Spinner />}\n </div>\n );\n }\n\n if (!viewportIds.length) {\n let text: string;\n\n switch (resultType) {\n case 'members':\n text = areMembersHidden ? 'You have no access to group members list.' : 'No members found';\n break;\n case 'commonChats':\n text = lang('NoGroupsInCommon');\n break;\n case 'documents':\n text = lang('lng_media_file_empty');\n break;\n case 'links':\n text = lang('lng_media_link_empty');\n break;\n case 'audio':\n text = lang('lng_media_song_empty');\n break;\n case 'voice':\n text = lang('lng_media_audio_empty');\n break;\n default:\n text = lang('SharedMedia.EmptyTitle');\n }\n\n return (\n <div className=\"content empty-list\">\n <NothingFound text={text} />\n </div>\n );\n }\n\n return (\n <div\n className={`content ${resultType}-list`}\n dir={lang.isRtl && resultType === 'media' ? 'rtl' : undefined}\n teactFastList\n >\n {resultType === 'media' ? (\n (viewportIds as number[])!.map((id) => chatMessages[id] && (\n <Media\n key={id}\n message={chatMessages[id]}\n onClick={handleSelectMedia}\n />\n ))\n ) : resultType === 'documents' ? (\n (viewportIds as number[])!.map((id) => chatMessages[id] && (\n <Document\n key={id}\n message={chatMessages[id]}\n withDate\n smaller\n className=\"scroll-item\"\n onDateClick={handleMessageFocus}\n isDownloading={activeDownloadIds.includes(id)}\n />\n ))\n ) : resultType === 'links' ? (\n (viewportIds as number[])!.map((id) => chatMessages[id] && (\n <WebLink\n key={id}\n message={chatMessages[id]}\n onMessageClick={handleMessageFocus}\n />\n ))\n ) : resultType === 'audio' ? (\n (viewportIds as number[])!.map((id) => chatMessages[id] && (\n <Audio\n key={id}\n theme={theme}\n message={chatMessages[id]}\n origin={AudioOrigin.SharedMedia}\n date={chatMessages[id].date}\n lastSyncTime={lastSyncTime}\n className=\"scroll-item\"\n onPlay={handlePlayAudio}\n onDateClick={handleMessageFocus}\n isDownloading={activeDownloadIds.includes(id)}\n />\n ))\n ) : resultType === 'voice' ? (\n (viewportIds as number[])!.map((id) => chatMessages[id] && (\n <Audio\n key={id}\n theme={theme}\n message={chatMessages[id]}\n senderTitle={getSenderName(lang, chatMessages[id], chatsById, usersById)}\n origin={AudioOrigin.SharedMedia}\n date={chatMessages[id].date}\n lastSyncTime={lastSyncTime}\n className=\"scroll-item\"\n onPlay={handlePlayAudio}\n onDateClick={handleMessageFocus}\n isDownloading={activeDownloadIds.includes(id)}\n />\n ))\n ) : resultType === 'members' ? (\n (viewportIds as string[])!.map((id, i) => (\n <ListItem\n key={id}\n teactOrderKey={i}\n className=\"chat-item-clickable scroll-item small-icon\"\n onClick={() => handleMemberClick(id)}\n contextActions={getMemberContextAction(id)}\n >\n <PrivateChatInfo userId={id} forceShowSelf />\n </ListItem>\n ))\n ) : resultType === 'commonChats' ? (\n (viewportIds as string[])!.map((id, i) => (\n <ListItem\n key={id}\n teactOrderKey={i}\n className=\"chat-item-clickable scroll-item small-icon\"\n onClick={() => openChat({ id })}\n >\n <GroupChatInfo chatId={id} />\n </ListItem>\n ))\n ) : undefined}\n </div>\n );\n }\n\n return (\n <InfiniteScroll\n ref={containerRef}\n className=\"Profile custom-scroll\"\n itemSelector={buildInfiniteScrollItemSelector(resultType)}\n items={canRenderContents ? viewportIds : undefined}\n cacheBuster={cacheBuster}\n sensitiveArea={PROFILE_SENSITIVE_AREA}\n preloadBackwards={canRenderContents ? (resultType === 'members' ? MEMBERS_SLICE : SHARED_MEDIA_SLICE) : 0}\n // To prevent scroll jumps caused by reordering member list\n noScrollRestoreOnTop\n noFastList\n onLoadMore={getMore}\n onScroll={handleScroll}\n >\n {!noProfileInfo && renderProfileInfo(chatId, resolvedUserId)}\n {!isRestricted && (\n <div\n className=\"shared-media\"\n >\n <Transition\n ref={transitionRef}\n name={lang.isRtl ? 'slide-reversed' : 'slide'}\n activeKey={activeKey}\n renderCount={tabs.length}\n shouldRestoreHeight\n className=\"shared-media-transition\"\n onStart={applyTransitionFix}\n onStop={handleTransitionStop}\n >\n {renderSharedMedia}\n </Transition>\n <TabList big activeTab={activeTab} tabs={tabs} onSwitchTab={setActiveTab} />\n </div>\n )}\n\n {canAddMembers && (\n <FloatingActionButton\n isShown={resultType === 'members'}\n onClick={handleNewMemberDialogOpen}\n ariaLabel={lang('lng_channel_add_users')}\n >\n <i className=\"icon-add-user-filled\" />\n </FloatingActionButton>\n )}\n {canDeleteMembers && (\n <DeleteMemberModal\n isOpen={Boolean(deletingUserId)}\n userId={deletingUserId}\n onClose={handleDeleteMembersModalClose}\n />\n )}\n </InfiniteScroll>\n );\n};\n\nfunction renderProfileInfo(chatId: string, resolvedUserId?: string) {\n return (\n <div className=\"profile-info\">\n <ProfileInfo userId={resolvedUserId || chatId} />\n <ChatExtra chatOrUserId={resolvedUserId || chatId} />\n </div>\n );\n}\n\nfunction buildInfiniteScrollItemSelector(resultType: string) {\n return [\n // Used on first render\n `.shared-media-transition > div:only-child > .${resultType}-list > .scroll-item`,\n // Used after transition\n `.shared-media-transition > div.active > .${resultType}-list > .scroll-item`,\n ].join(', ');\n}\n\nexport default memo(withGlobal<OwnProps>(\n (global, { chatId, userId }): StateProps => {\n const chat = selectChat(global, chatId);\n\n const chatMessages = selectChatMessages(global, userId || chatId);\n const { currentType: mediaSearchType, resultsByType } = selectCurrentMediaSearch(global) || {};\n const { foundIds } = (resultsByType && mediaSearchType && resultsByType[mediaSearchType]) || {};\n\n const { byId: usersById } = global.users;\n const { byId: chatsById } = global.chats;\n\n const isGroup = chat && isChatGroup(chat);\n const isChannel = chat && isChatChannel(chat);\n const hasMembersTab = isGroup || (isChannel && isChatAdmin(chat!));\n const members = chat?.fullInfo?.members;\n const areMembersHidden = hasMembersTab && chat && chat.fullInfo && !chat.fullInfo.canViewMembers;\n const canAddMembers = hasMembersTab && chat && (getHasAdminRight(chat, 'inviteUsers') || chat.isCreator);\n const canDeleteMembers = hasMembersTab && chat && (getHasAdminRight(chat, 'banUsers') || chat.isCreator);\n\n const activeDownloadIds = selectActiveDownloadIds(global, chatId);\n\n let hasCommonChatsTab;\n let resolvedUserId;\n let user;\n if (userId) {\n resolvedUserId = userId;\n } else if (isUserId(chatId)) {\n resolvedUserId = chatId;\n }\n if (resolvedUserId) {\n user = selectUser(global, resolvedUserId);\n hasCommonChatsTab = user && !user.isSelf && !isUserBot(user);\n }\n\n return {\n theme: selectTheme(global),\n isChannel,\n resolvedUserId,\n chatMessages,\n foundIds,\n mediaSearchType,\n hasCommonChatsTab,\n hasMembersTab,\n areMembersHidden,\n canAddMembers,\n canDeleteMembers,\n currentUserId: global.currentUserId,\n isRightColumnShown: selectIsRightColumnShown(global),\n isRestricted: chat?.isRestricted,\n lastSyncTime: global.lastSyncTime,\n serverTimeOffset: global.serverTimeOffset,\n activeDownloadIds,\n usersById,\n chatsById,\n ...(hasMembersTab && members && { members }),\n ...(hasCommonChatsTab && user && { commonChatIds: user.commonChats?.ids }),\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'setLocalMediaSearchType',\n 'loadMoreMembers',\n 'searchMediaMessagesLocal',\n 'openMediaViewer',\n 'openAudioPlayer',\n 'openUserInfo',\n 'focusMessage',\n 'loadProfilePhotos',\n 'setNewChatMembersDialogState',\n 'loadCommonChats',\n 'openChat',\n ]),\n)(Profile));\n","import { useCallback, useEffect } from '../../../lib/teact/teact';\n\nexport default function useTransitionFixes(\n containerRef: { current: HTMLDivElement | null },\n transitionElSelector = '.Transition.shared-media-transition',\n) {\n // Set `min-height` for shared media container to prevent jumping when switching tabs\n useEffect(() => {\n function setMinHeight() {\n const container = containerRef.current!;\n const transitionEl = container.querySelector<HTMLDivElement>(transitionElSelector);\n const tabsEl = container.querySelector<HTMLDivElement>('.TabList');\n if (transitionEl && tabsEl) {\n transitionEl.style.minHeight = `${container.offsetHeight - tabsEl.offsetHeight}px`;\n }\n }\n\n setMinHeight();\n\n window.addEventListener('resize', setMinHeight, false);\n\n return () => {\n window.removeEventListener('resize', setMinHeight, false);\n };\n }, [containerRef, transitionElSelector]);\n\n // Workaround for scrollable content flickering during animation.\n const applyTransitionFix = useCallback(() => {\n const container = containerRef.current!;\n if (container.style.overflowY !== 'hidden') {\n const scrollBarWidth = container.offsetWidth - container.clientWidth;\n container.style.overflowY = 'hidden';\n container.style.marginRight = `${scrollBarWidth}px`;\n }\n }, [containerRef]);\n\n const releaseTransitionFix = useCallback(() => {\n const container = containerRef.current!;\n container.style.overflowY = 'scroll';\n container.style.marginRight = '0';\n }, [containerRef]);\n\n return { applyTransitionFix, releaseTransitionFix };\n}\n","import { useCallback, useState } from '../lib/teact/teact';\n\nexport default () => {\n const [cacheBuster, setCacheBuster] = useState<boolean>(false);\n\n const updateCacheBuster = useCallback(() => {\n setCacheBuster((current) => !current);\n }, []);\n\n return [cacheBuster, updateCacheBuster] as const;\n};\n","import React, { FC, memo } from '../../lib/teact/teact';\nimport { OwnProps } from './RightSearch';\nimport { Bundles } from '../../util/moduleLoader';\n\nimport useModuleLoader from '../../hooks/useModuleLoader';\nimport Loading from '../ui/Loading';\n\nconst RightSearchAsync: FC<OwnProps> = (props) => {\n const RightSearch = useModuleLoader(Bundles.Extra, 'RightSearch');\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return RightSearch ? <RightSearch {...props} /> : <Loading />;\n};\n\nexport default memo(RightSearchAsync);\n","import React, { FC, memo } from '../../../lib/teact/teact';\nimport { Bundles } from '../../../util/moduleLoader';\n\nimport { OwnProps } from './Management';\n\nimport useModuleLoader from '../../../hooks/useModuleLoader';\n\nimport Loading from '../../ui/Loading';\n\nconst ManagementAsync: FC<OwnProps> = (props) => {\n const Management = useModuleLoader(Bundles.Extra, 'Management');\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return Management ? <Management {...props} /> : <Loading />;\n};\n\nexport default memo(ManagementAsync);\n","import React, { FC, memo } from '../../lib/teact/teact';\nimport { Bundles } from '../../util/moduleLoader';\n\nimport useModuleLoader from '../../hooks/useModuleLoader';\nimport Loading from '../ui/Loading';\n\nconst StickerSearchAsync: FC = () => {\n const StickerSearch = useModuleLoader(Bundles.Extra, 'StickerSearch');\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return StickerSearch ? <StickerSearch /> : <Loading />;\n};\n\nexport default memo(StickerSearchAsync);\n","import React, { FC, memo } from '../../lib/teact/teact';\nimport { Bundles } from '../../util/moduleLoader';\n\nimport useModuleLoader from '../../hooks/useModuleLoader';\nimport Loading from '../ui/Loading';\n\nconst GifSearchAsync: FC = () => {\n const GifSearch = useModuleLoader(Bundles.Extra, 'GifSearch');\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return GifSearch ? <GifSearch /> : <Loading />;\n};\n\nexport default memo(GifSearchAsync);\n","import React, { FC, memo } from '../../lib/teact/teact';\nimport { Bundles } from '../../util/moduleLoader';\n\nimport useModuleLoader from '../../hooks/useModuleLoader';\nimport Loading from '../ui/Loading';\n\nconst PollResultsAsync: FC = () => {\n const PollResults = useModuleLoader(Bundles.Extra, 'PollResults');\n\n return PollResults ? <PollResults /> : <Loading />;\n};\n\nexport default memo(PollResultsAsync);\n","import React, {\n FC, useCallback, useMemo, memo, useState, useEffect,\n} from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../global/types';\nimport {\n ApiChat, ApiChatMember, ApiUpdateConnectionStateType, ApiUser,\n} from '../../api/types';\nimport { NewChatMembersProgress } from '../../types';\n\nimport { pick, unique } from '../../util/iteratees';\nimport { selectChat } from '../../modules/selectors';\nimport searchWords from '../../util/searchWords';\nimport {\n getUserFullName, isChatChannel, isUserBot, sortChatIds,\n} from '../../modules/helpers';\nimport useLang from '../../hooks/useLang';\nimport usePrevious from '../../hooks/usePrevious';\nimport useHistoryBack from '../../hooks/useHistoryBack';\n\nimport Picker from '../common/Picker';\nimport FloatingActionButton from '../ui/FloatingActionButton';\nimport Spinner from '../ui/Spinner';\n\nimport './AddChatMembers.scss';\n\nexport type OwnProps = {\n chatId: string;\n isActive: boolean;\n onNextStep: (memberIds: string[]) => void;\n onClose: NoneToVoidFunction;\n};\n\ntype StateProps = {\n connectionState?: ApiUpdateConnectionStateType;\n isChannel?: boolean;\n members?: ApiChatMember[];\n currentUserId?: string;\n usersById: Record<string, ApiUser>;\n chatsById: Record<string, ApiChat>;\n localContactIds?: string[];\n searchQuery?: string;\n isLoading: boolean;\n isSearching?: boolean;\n localUserIds?: string[];\n globalUserIds?: string[];\n};\n\ntype DispatchProps = Pick<GlobalActions, 'loadContactList' | 'setUserSearchQuery'>;\n\nconst AddChatMembers: FC<OwnProps & StateProps & DispatchProps> = ({\n isChannel,\n connectionState,\n members,\n onNextStep,\n currentUserId,\n usersById,\n chatsById,\n localContactIds,\n isLoading,\n searchQuery,\n isSearching,\n localUserIds,\n globalUserIds,\n setUserSearchQuery,\n onClose,\n isActive,\n loadContactList,\n}) => {\n const lang = useLang();\n const [selectedMemberIds, setSelectedMemberIds] = useState<string[]>([]);\n const prevSelectedMemberIds = usePrevious(selectedMemberIds);\n const noPickerScrollRestore = prevSelectedMemberIds === selectedMemberIds;\n\n useEffect(() => {\n if (isActive && connectionState === 'connectionStateReady') {\n loadContactList();\n }\n }, [connectionState, isActive, loadContactList]);\n\n useHistoryBack(isActive, onClose);\n\n const memberIds = useMemo(() => {\n return members ? members.map((member) => member.userId) : [];\n }, [members]);\n\n const handleFilterChange = useCallback((query: string) => {\n setUserSearchQuery({ query });\n }, [setUserSearchQuery]);\n\n const displayedIds = useMemo(() => {\n const contactIds = localContactIds\n ? sortChatIds(localContactIds.filter((id) => id !== currentUserId), chatsById)\n : [];\n\n if (!searchQuery) {\n return contactIds.filter((id) => !memberIds.includes(id));\n }\n\n const foundContactIds = contactIds.filter((id) => {\n const user = usersById[id];\n if (!user) {\n return false;\n }\n const fullName = getUserFullName(user);\n return fullName && searchWords(fullName, searchQuery);\n });\n\n return sortChatIds(\n unique([\n ...foundContactIds,\n ...(localUserIds || []),\n ...(globalUserIds || []),\n ]).filter((contactId) => {\n const user = usersById[contactId];\n\n // The user can be added to the chat if the following conditions are met:\n // the user has not yet been added to the current chat\n // AND (it is not found (user from global search) OR it is not a bot OR it is a bot,\n // but the current chat is not a channel AND the appropriate permission is set).\n return !memberIds.includes(contactId)\n && (!user || !isUserBot(user) || (!isChannel && user.canBeInvitedToGroup));\n }),\n chatsById,\n );\n }, [\n localContactIds, chatsById, searchQuery, localUserIds, globalUserIds,\n currentUserId, usersById, memberIds, isChannel,\n ]);\n\n const handleNextStep = useCallback(() => {\n if (selectedMemberIds.length) {\n setUserSearchQuery({ query: '' });\n onNextStep(selectedMemberIds);\n }\n }, [selectedMemberIds, setUserSearchQuery, onNextStep]);\n\n return (\n <div className=\"AddChatMembers\">\n <div className=\"AddChatMembers-inner\">\n <Picker\n itemIds={displayedIds}\n selectedIds={selectedMemberIds}\n filterValue={searchQuery}\n filterPlaceholder={lang('lng_channel_add_users')}\n searchInputId=\"new-members-picker-search\"\n isLoading={isSearching}\n onSelectedIdsChange={setSelectedMemberIds}\n onFilterChange={handleFilterChange}\n noScrollRestore={noPickerScrollRestore}\n />\n\n <FloatingActionButton\n isShown={Boolean(selectedMemberIds.length)}\n disabled={isLoading}\n ariaLabel={lang('lng_channel_add_users')}\n onClick={handleNextStep}\n >\n {isLoading ? (\n <Spinner color=\"white\" />\n ) : (\n <i className=\"icon-arrow-right\" />\n )}\n </FloatingActionButton>\n </div>\n </div>\n );\n};\n\nexport default memo(withGlobal<OwnProps>(\n (global, { chatId }): StateProps => {\n const chat = selectChat(global, chatId);\n const { userIds: localContactIds } = global.contactList || {};\n const { byId: usersById } = global.users;\n const { byId: chatsById } = global.chats;\n const { currentUserId, newChatMembersProgress, connectionState } = global;\n const isChannel = chat && isChatChannel(chat);\n\n const {\n query: searchQuery,\n fetchingStatus,\n globalUserIds,\n localUserIds,\n } = global.userSearch;\n\n return {\n isChannel,\n members: chat?.fullInfo?.members,\n currentUserId,\n usersById,\n chatsById,\n localContactIds,\n searchQuery,\n isSearching: fetchingStatus,\n isLoading: newChatMembersProgress === NewChatMembersProgress.Loading,\n globalUserIds,\n localUserIds,\n connectionState,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, ['loadContactList', 'setUserSearchQuery']),\n)(AddChatMembers));\n","import React, {\n FC, memo, useCallback, useEffect, useState,\n} from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../global/types';\nimport {\n ManagementScreens, NewChatMembersProgress, ProfileState, RightColumnContent,\n} from '../../types';\n\nimport { MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN } from '../../config';\nimport captureEscKeyListener from '../../util/captureEscKeyListener';\nimport { pick } from '../../util/iteratees';\nimport {\n selectAreActiveChatsLoaded,\n selectCurrentMessageList,\n selectRightColumnContentKey,\n} from '../../modules/selectors';\nimport useLayoutEffectWithPrevDeps from '../../hooks/useLayoutEffectWithPrevDeps';\nimport useWindowSize from '../../hooks/useWindowSize';\nimport useCurrentOrPrev from '../../hooks/useCurrentOrPrev';\nimport useHistoryBack from '../../hooks/useHistoryBack';\n\nimport RightHeader from './RightHeader';\nimport Profile from './Profile';\nimport Transition from '../ui/Transition';\nimport RightSearch from './RightSearch.async';\nimport Management from './management/Management.async';\nimport StickerSearch from './StickerSearch.async';\nimport GifSearch from './GifSearch.async';\nimport PollResults from './PollResults.async';\nimport AddChatMembers from './AddChatMembers';\n\nimport './RightColumn.scss';\n\ntype StateProps = {\n contentKey?: RightColumnContent;\n chatId?: string;\n threadId?: number;\n currentProfileUserId?: string;\n isChatSelected: boolean;\n shouldSkipHistoryAnimations?: boolean;\n};\n\ntype DispatchProps = Pick<GlobalActions, (\n 'toggleChatInfo' | 'toggleManagement' | 'openUserInfo' | 'setNewChatMembersDialogState' |\n 'closeLocalTextSearch' | 'closePollResults' | 'addChatMembers' |\n 'setStickerSearchQuery' | 'setGifSearchQuery'\n)>;\n\nconst COLUMN_CLOSE_DELAY_MS = 300;\nconst MAIN_SCREENS_COUNT = Object.keys(RightColumnContent).length / 2;\nconst MANAGEMENT_SCREENS_COUNT = Object.keys(ManagementScreens).length / 2;\n\nfunction blurSearchInput() {\n const searchInput = document.querySelector('.RightHeader .SearchInput input') as HTMLInputElement;\n if (searchInput) {\n searchInput.blur();\n }\n}\n\nconst RightColumn: FC<StateProps & DispatchProps> = ({\n contentKey,\n chatId,\n threadId,\n currentProfileUserId,\n isChatSelected,\n toggleChatInfo,\n toggleManagement,\n openUserInfo,\n closeLocalTextSearch,\n setStickerSearchQuery,\n setGifSearchQuery,\n closePollResults,\n addChatMembers,\n setNewChatMembersDialogState,\n shouldSkipHistoryAnimations,\n}) => {\n const { width: windowWidth } = useWindowSize();\n const [profileState, setProfileState] = useState<ProfileState>(ProfileState.Profile);\n const [managementScreen, setManagementScreen] = useState<ManagementScreens>(ManagementScreens.Initial);\n const [selectedChatMemberId, setSelectedChatMemberId] = useState<string | undefined>();\n const [isPromotedByCurrentUser, setIsPromotedByCurrentUser] = useState<boolean | undefined>();\n const isScrolledDown = profileState !== ProfileState.Profile;\n\n const isOpen = contentKey !== undefined;\n const isProfile = contentKey === RightColumnContent.ChatInfo || contentKey === RightColumnContent.UserInfo;\n const isSearch = contentKey === RightColumnContent.Search;\n const isManagement = contentKey === RightColumnContent.Management;\n const isStickerSearch = contentKey === RightColumnContent.StickerSearch;\n const isGifSearch = contentKey === RightColumnContent.GifSearch;\n const isPollResults = contentKey === RightColumnContent.PollResults;\n const isAddingChatMembers = contentKey === RightColumnContent.AddingMembers;\n const isOverlaying = windowWidth <= MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN;\n\n const [shouldSkipTransition, setShouldSkipTransition] = useState(!isOpen);\n\n const renderingContentKey = useCurrentOrPrev(contentKey, true, !isChatSelected) ?? -1;\n\n const close = useCallback((shouldScrollUp = true) => {\n switch (contentKey) {\n case RightColumnContent.AddingMembers:\n setNewChatMembersDialogState(NewChatMembersProgress.Closed);\n break;\n case RightColumnContent.ChatInfo:\n if (isScrolledDown && shouldScrollUp) {\n setProfileState(ProfileState.Profile);\n break;\n }\n toggleChatInfo(undefined, true);\n break;\n case RightColumnContent.UserInfo:\n if (isScrolledDown && shouldScrollUp) {\n setProfileState(ProfileState.Profile);\n break;\n }\n openUserInfo({ id: undefined }, true);\n break;\n case RightColumnContent.Management: {\n switch (managementScreen) {\n case ManagementScreens.Initial:\n toggleManagement();\n break;\n case ManagementScreens.ChatPrivacyType:\n case ManagementScreens.Discussion:\n case ManagementScreens.GroupPermissions:\n case ManagementScreens.GroupType:\n case ManagementScreens.ChatAdministrators:\n case ManagementScreens.ChannelSubscribers:\n case ManagementScreens.GroupMembers:\n setManagementScreen(ManagementScreens.Initial);\n break;\n case ManagementScreens.GroupUserPermissionsCreate:\n case ManagementScreens.GroupRemovedUsers:\n case ManagementScreens.GroupUserPermissions:\n setManagementScreen(ManagementScreens.GroupPermissions);\n setSelectedChatMemberId(undefined);\n setIsPromotedByCurrentUser(undefined);\n break;\n case ManagementScreens.ChatAdminRights:\n case ManagementScreens.GroupRecentActions:\n setManagementScreen(ManagementScreens.ChatAdministrators);\n break;\n }\n\n break;\n }\n case RightColumnContent.Search: {\n blurSearchInput();\n closeLocalTextSearch();\n break;\n }\n case RightColumnContent.StickerSearch:\n blurSearchInput();\n setStickerSearchQuery({ query: undefined });\n break;\n case RightColumnContent.GifSearch: {\n blurSearchInput();\n setGifSearchQuery({ query: undefined });\n break;\n }\n case RightColumnContent.PollResults:\n closePollResults();\n break;\n }\n }, [\n contentKey, isScrolledDown, toggleChatInfo, openUserInfo, closePollResults, setNewChatMembersDialogState,\n managementScreen, toggleManagement, closeLocalTextSearch, setStickerSearchQuery, setGifSearchQuery,\n ]);\n\n const handleSelectChatMember = useCallback((memberId, isPromoted) => {\n setSelectedChatMemberId(memberId);\n setIsPromotedByCurrentUser(isPromoted);\n }, []);\n\n const handleAppendingChatMembers = useCallback((memberIds: string[]) => {\n addChatMembers({ chatId, memberIds });\n }, [addChatMembers, chatId]);\n\n useEffect(() => (isOpen ? captureEscKeyListener(close) : undefined), [isOpen, close]);\n\n useEffect(() => {\n setTimeout(() => {\n setShouldSkipTransition(!isOpen);\n }, COLUMN_CLOSE_DELAY_MS);\n }, [isOpen]);\n\n // Close Right Column when it transforms into overlayed state on screen resize\n useEffect(() => {\n if (isOpen && isOverlaying) {\n close();\n }\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [isOverlaying]);\n\n // We need to clear profile state and management screen state, when changing chats\n useLayoutEffectWithPrevDeps(([prevContentKey, prevChatId]) => {\n if (\n (prevContentKey === RightColumnContent.ChatInfo && contentKey === RightColumnContent.UserInfo)\n || (prevContentKey === RightColumnContent.UserInfo && contentKey === RightColumnContent.ChatInfo)\n || (prevChatId !== chatId)\n ) {\n setProfileState(ProfileState.Profile);\n setManagementScreen(ManagementScreens.Initial);\n }\n }, [contentKey, chatId]);\n\n useHistoryBack(isChatSelected && (contentKey === RightColumnContent.ChatInfo\n || contentKey === RightColumnContent.UserInfo || contentKey === RightColumnContent.Management\n || contentKey === RightColumnContent.AddingMembers),\n () => close(false), toggleChatInfo);\n\n // eslint-disable-next-line consistent-return\n function renderContent(isActive: boolean) {\n if (renderingContentKey === -1) {\n return undefined;\n }\n\n switch (renderingContentKey) {\n case RightColumnContent.AddingMembers:\n return (\n <AddChatMembers\n chatId={chatId!}\n onNextStep={handleAppendingChatMembers}\n isActive={isOpen && isActive}\n onClose={close}\n />\n );\n case RightColumnContent.ChatInfo:\n case RightColumnContent.UserInfo:\n return (\n <Profile\n key={currentProfileUserId || chatId!}\n chatId={chatId!}\n userId={currentProfileUserId}\n profileState={profileState}\n onProfileStateChange={setProfileState}\n />\n );\n case RightColumnContent.Search:\n return <RightSearch chatId={chatId!} threadId={threadId!} onClose={close} isActive={isOpen && isActive} />;\n case RightColumnContent.Management:\n return (\n <Management\n chatId={chatId!}\n currentScreen={managementScreen}\n isPromotedByCurrentUser={isPromotedByCurrentUser}\n selectedChatMemberId={selectedChatMemberId}\n onScreenSelect={setManagementScreen}\n onChatMemberSelect={handleSelectChatMember}\n isActive={isOpen && isActive}\n onClose={close}\n />\n );\n\n case RightColumnContent.StickerSearch:\n return <StickerSearch onClose={close} isActive={isOpen && isActive} />;\n case RightColumnContent.GifSearch:\n return <GifSearch onClose={close} isActive={isOpen && isActive} />;\n case RightColumnContent.PollResults:\n return <PollResults onClose={close} isActive={isOpen && isActive} />;\n }\n }\n\n return (\n <div\n id=\"RightColumn-wrapper\"\n className={!isChatSelected ? 'is-hidden' : undefined}\n >\n {isOverlaying && (\n <div className=\"overlay-backdrop\" onClick={close} />\n )}\n <div id=\"RightColumn\">\n <RightHeader\n chatId={chatId}\n isColumnOpen={isOpen}\n isProfile={isProfile}\n isSearch={isSearch}\n isManagement={isManagement}\n isStickerSearch={isStickerSearch}\n isGifSearch={isGifSearch}\n isPollResults={isPollResults}\n isAddingChatMembers={isAddingChatMembers}\n profileState={profileState}\n managementScreen={managementScreen}\n onClose={close}\n shouldSkipAnimation={shouldSkipTransition || shouldSkipHistoryAnimations}\n />\n <Transition\n name={(shouldSkipTransition || shouldSkipHistoryAnimations) ? 'none' : 'zoom-fade'}\n renderCount={MAIN_SCREENS_COUNT + MANAGEMENT_SCREENS_COUNT}\n activeKey={isManagement ? MAIN_SCREENS_COUNT + managementScreen : renderingContentKey}\n shouldCleanup\n cleanupExceptionKey={RightColumnContent.ChatInfo}\n >\n {renderContent}\n </Transition>\n </div>\n </div>\n );\n};\n\nexport default memo(withGlobal(\n (global): StateProps => {\n const { chatId, threadId } = selectCurrentMessageList(global) || {};\n const areActiveChatsLoaded = selectAreActiveChatsLoaded(global);\n\n return {\n contentKey: selectRightColumnContentKey(global),\n chatId,\n threadId,\n currentProfileUserId: global.users.selectedId,\n isChatSelected: Boolean(chatId && areActiveChatsLoaded),\n shouldSkipHistoryAnimations: global.shouldSkipHistoryAnimations,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'openUserInfo',\n 'toggleChatInfo',\n 'toggleManagement',\n 'closeLocalTextSearch',\n 'setStickerSearchQuery',\n 'setGifSearchQuery',\n 'closePollResults',\n 'addChatMembers',\n 'setNewChatMembersDialogState',\n ]),\n)(RightColumn));\n","import React, { FC, memo } from '../../lib/teact/teact';\n\nimport { Bundles } from '../../util/moduleLoader';\nimport useModuleLoader from '../../hooks/useModuleLoader';\n\ninterface OwnProps {\n isOpen: boolean;\n}\n\nconst MediaViewerAsync: FC<OwnProps> = ({ isOpen }) => {\n const MediaViewer = useModuleLoader(Bundles.Extra, 'MediaViewer', !isOpen);\n\n return MediaViewer ? <MediaViewer /> : undefined;\n};\n\nexport default memo(MediaViewerAsync);\n","export default function download(url: string, filename: string) {\n const link = document.createElement('a');\n link.href = url;\n link.download = filename;\n try {\n link.click();\n } catch (err) {\n // eslint-disable-next-line no-console\n console.error(err); // Suppress redundant \"Blob loading failed\" error popup on IOS\n }\n}\n","import { FC, memo, useEffect } from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { GlobalActions, Thread } from '../../global/types';\nimport { ApiMediaFormat, ApiMessage } from '../../api/types';\n\nimport * as mediaLoader from '../../util/mediaLoader';\nimport download from '../../util/download';\nimport {\n getMessageContentFilename, getMessageMediaHash,\n} from '../../modules/helpers';\nimport { pick } from '../../util/iteratees';\n\ntype StateProps = {\n activeDownloads: Record<number, number[]>;\n messages: Record<number, {\n byId: Record<number, ApiMessage>;\n threadsById: Record<number, Thread>;\n }>;\n};\n\ntype DispatchProps = Pick<GlobalActions, 'cancelMessageMediaDownload'>;\n\nconst startedDownloads = new Set<string>();\n\nconst DownloadsManager: FC<StateProps & DispatchProps> = ({\n activeDownloads,\n messages,\n cancelMessageMediaDownload,\n}) => {\n useEffect(() => {\n Object.entries(activeDownloads).forEach(([chatId, messageIds]) => {\n const activeMessages = messageIds.map((id) => messages[Number(chatId)].byId[id]);\n activeMessages.forEach((message) => {\n const downloadHash = getMessageMediaHash(message, 'download');\n if (!downloadHash) {\n cancelMessageMediaDownload({ message });\n return;\n }\n\n if (!startedDownloads.has(downloadHash)) {\n const mediaData = mediaLoader.getFromMemory<ApiMediaFormat.BlobUrl>(downloadHash);\n if (mediaData) {\n startedDownloads.delete(downloadHash);\n download(mediaData, getMessageContentFilename(message));\n cancelMessageMediaDownload({ message });\n return;\n }\n\n mediaLoader.fetch(downloadHash, ApiMediaFormat.BlobUrl, true).then((result) => {\n startedDownloads.delete(downloadHash);\n if (result) {\n download(result, getMessageContentFilename(message));\n }\n cancelMessageMediaDownload({ message });\n });\n\n startedDownloads.add(downloadHash);\n }\n });\n });\n }, [\n cancelMessageMediaDownload,\n messages,\n activeDownloads,\n ]);\n\n return undefined;\n};\n\nexport default memo(withGlobal(\n (global): StateProps => {\n const activeDownloads = global.activeDownloads.byChatId;\n const messages = global.messages.byChatId;\n return {\n activeDownloads,\n messages,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, ['cancelMessageMediaDownload']),\n)(DownloadsManager));\n","import React, { FC, memo } from '../../lib/teact/teact';\nimport { Bundles } from '../../util/moduleLoader';\n\nimport useModuleLoader from '../../hooks/useModuleLoader';\n\nconst NotificationsAsync: FC = ({ isOpen }) => {\n const Notifications = useModuleLoader(Bundles.Extra, 'Notifications', !isOpen);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return Notifications ? <Notifications /> : undefined;\n};\n\nexport default memo(NotificationsAsync);\n","import React, { FC, memo } from '../../lib/teact/teact';\nimport { Bundles } from '../../util/moduleLoader';\n\nimport useModuleLoader from '../../hooks/useModuleLoader';\n\nconst DialogsAsync: FC = ({ isOpen }) => {\n const Dialogs = useModuleLoader(Bundles.Extra, 'Dialogs', !isOpen);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return Dialogs ? <Dialogs /> : undefined;\n};\n\nexport default memo(DialogsAsync);\n","import React, { FC, memo } from '../../lib/teact/teact';\nimport { Bundles } from '../../util/moduleLoader';\nimport { OwnProps } from './ForwardPicker';\n\nimport useModuleLoader from '../../hooks/useModuleLoader';\n\nconst ForwardPickerAsync: FC<OwnProps> = (props) => {\n const { isOpen } = props;\n const ForwardPicker = useModuleLoader(Bundles.Extra, 'ForwardPicker', !isOpen);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return ForwardPicker ? <ForwardPicker {...props} /> : undefined;\n};\n\nexport default memo(ForwardPickerAsync);\n","import React, { FC, memo } from '../../lib/teact/teact';\nimport { Bundles } from '../../util/moduleLoader';\n\nimport { OwnProps } from './SafeLinkModal';\n\nimport useModuleLoader from '../../hooks/useModuleLoader';\n\nconst SafeLinkModalAsync: FC<OwnProps> = (props) => {\n const { url } = props;\n const SafeLinkModal = useModuleLoader(Bundles.Extra, 'SafeLinkModal', !url);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return SafeLinkModal ? <SafeLinkModal {...props} /> : undefined;\n};\n\nexport default memo(SafeLinkModalAsync);\n","import React, { FC, memo } from '../../lib/teact/teact';\nimport { Bundles } from '../../util/moduleLoader';\n\nimport { OwnProps } from './HistoryCalendar';\n\nimport useModuleLoader from '../../hooks/useModuleLoader';\n\nconst HistoryCalendarAsync: FC<OwnProps> = (props) => {\n const { isOpen } = props;\n const HistoryCalendar = useModuleLoader(Bundles.Extra, 'HistoryCalendar', !isOpen);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return HistoryCalendar ? <HistoryCalendar {...props} /> : undefined;\n};\n\nexport default memo(HistoryCalendarAsync);\n","import React, {\n FC, useEffect, memo, useCallback,\n} from '../../lib/teact/teact';\nimport { getGlobal, withGlobal } from '../../lib/teact/teactn';\n\nimport { AudioOrigin, LangCode } from '../../types';\nimport { GlobalActions } from '../../global/types';\nimport { ApiMessage } from '../../api/types';\n\nimport '../../modules/actions/all';\nimport {\n BASE_EMOJI_KEYWORD_LANG, DEBUG, INACTIVE_MARKER, PAGE_TITLE,\n} from '../../config';\nimport { pick } from '../../util/iteratees';\nimport {\n selectChatMessage,\n selectCountNotMutedUnread,\n selectIsForwardModalOpen,\n selectIsMediaViewerOpen,\n selectIsRightColumnShown,\n selectIsServiceChatReady,\n} from '../../modules/selectors';\nimport { dispatchHeavyAnimationEvent } from '../../hooks/useHeavyAnimationCheck';\nimport buildClassName from '../../util/buildClassName';\nimport { fastRaf } from '../../util/schedulers';\nimport { waitForTransitionEnd } from '../../util/cssAnimationEndListeners';\nimport useShowTransition from '../../hooks/useShowTransition';\nimport useBackgroundMode from '../../hooks/useBackgroundMode';\nimport useBeforeUnload from '../../hooks/useBeforeUnload';\nimport useOnChange from '../../hooks/useOnChange';\nimport usePreventPinchZoomGesture from '../../hooks/usePreventPinchZoomGesture';\nimport { processDeepLink } from '../../util/deeplink';\nimport { LOCATION_HASH } from '../../hooks/useHistoryBack';\n\nimport LeftColumn from '../left/LeftColumn';\nimport MiddleColumn from '../middle/MiddleColumn';\nimport RightColumn from '../right/RightColumn';\nimport MediaViewer from '../mediaViewer/MediaViewer.async';\nimport AudioPlayer from '../middle/AudioPlayer';\nimport DownloadManager from './DownloadManager';\nimport Notifications from './Notifications.async';\nimport Dialogs from './Dialogs.async';\nimport ForwardPicker from './ForwardPicker.async';\nimport SafeLinkModal from './SafeLinkModal.async';\nimport HistoryCalendar from './HistoryCalendar.async';\nimport StickerSetModal from '../common/StickerSetModal.async';\n\nimport './Main.scss';\n\ntype StateProps = {\n lastSyncTime?: number;\n isLeftColumnShown: boolean;\n isRightColumnShown: boolean;\n isMediaViewerOpen: boolean;\n isForwardModalOpen: boolean;\n hasNotifications: boolean;\n hasDialogs: boolean;\n audioMessage?: ApiMessage;\n audioOrigin?: AudioOrigin;\n safeLinkModalUrl?: string;\n isHistoryCalendarOpen: boolean;\n shouldSkipHistoryAnimations?: boolean;\n openedStickerSetShortName?: string;\n isServiceChatReady?: boolean;\n animationLevel: number;\n language?: LangCode;\n wasTimeFormatSetManually?: boolean;\n};\n\ntype DispatchProps = Pick<GlobalActions, (\n 'loadAnimatedEmojis' | 'loadNotificationSettings' | 'loadNotificationExceptions' | 'updateIsOnline' |\n 'loadTopInlineBots' | 'loadEmojiKeywords' | 'openStickerSetShortName' |\n 'loadCountryList' | 'ensureTimeFormat' | 'checkVersionNotification'\n)>;\n\nconst NOTIFICATION_INTERVAL = 1000;\n\nlet notificationInterval: number | undefined;\n\n// eslint-disable-next-line @typescript-eslint/naming-convention\nlet DEBUG_isLogged = false;\n\nconst Main: FC<StateProps & DispatchProps> = ({\n lastSyncTime,\n isLeftColumnShown,\n isRightColumnShown,\n isMediaViewerOpen,\n isForwardModalOpen,\n hasNotifications,\n hasDialogs,\n audioMessage,\n audioOrigin,\n safeLinkModalUrl,\n isHistoryCalendarOpen,\n shouldSkipHistoryAnimations,\n openedStickerSetShortName,\n isServiceChatReady,\n animationLevel,\n language,\n wasTimeFormatSetManually,\n loadAnimatedEmojis,\n loadNotificationSettings,\n loadNotificationExceptions,\n updateIsOnline,\n loadTopInlineBots,\n loadEmojiKeywords,\n loadCountryList,\n ensureTimeFormat,\n openStickerSetShortName,\n checkVersionNotification,\n}) => {\n if (DEBUG && !DEBUG_isLogged) {\n DEBUG_isLogged = true;\n // eslint-disable-next-line no-console\n console.log('>>> RENDER MAIN');\n }\n\n // Initial API calls\n useEffect(() => {\n if (lastSyncTime) {\n updateIsOnline(true);\n loadAnimatedEmojis();\n loadNotificationSettings();\n loadNotificationExceptions();\n loadTopInlineBots();\n\n loadEmojiKeywords({ language: BASE_EMOJI_KEYWORD_LANG });\n if (language !== BASE_EMOJI_KEYWORD_LANG) {\n loadEmojiKeywords({ language });\n }\n\n loadCountryList({ langCode: language });\n }\n }, [\n lastSyncTime, loadAnimatedEmojis, loadNotificationExceptions, loadNotificationSettings, updateIsOnline,\n loadTopInlineBots, loadEmojiKeywords, loadCountryList, language,\n ]);\n\n useEffect(() => {\n if (lastSyncTime && isServiceChatReady) {\n checkVersionNotification();\n }\n }, [lastSyncTime, isServiceChatReady, checkVersionNotification]);\n\n useEffect(() => {\n if (lastSyncTime && !wasTimeFormatSetManually) {\n ensureTimeFormat();\n }\n }, [lastSyncTime, wasTimeFormatSetManually, ensureTimeFormat]);\n\n useEffect(() => {\n if (lastSyncTime && LOCATION_HASH.startsWith('#?tgaddr=')) {\n processDeepLink(decodeURIComponent(LOCATION_HASH.substr('#?tgaddr='.length)));\n }\n }, [lastSyncTime]);\n\n const {\n transitionClassNames: middleColumnTransitionClassNames,\n } = useShowTransition(!isLeftColumnShown, undefined, true, undefined, shouldSkipHistoryAnimations);\n\n const {\n transitionClassNames: rightColumnTransitionClassNames,\n } = useShowTransition(isRightColumnShown, undefined, true, undefined, shouldSkipHistoryAnimations);\n\n const className = buildClassName(\n middleColumnTransitionClassNames.replace(/([\\w-]+)/g, 'middle-column-$1'),\n rightColumnTransitionClassNames.replace(/([\\w-]+)/g, 'right-column-$1'),\n shouldSkipHistoryAnimations && 'history-animation-disabled',\n );\n\n // Dispatch heavy transition event when opening middle column\n useOnChange(([prevIsLeftColumnShown]) => {\n if (prevIsLeftColumnShown === undefined || animationLevel === 0) {\n return;\n }\n\n const dispatchHeavyAnimationEnd = dispatchHeavyAnimationEvent();\n\n waitForTransitionEnd(document.getElementById('MiddleColumn')!, dispatchHeavyAnimationEnd);\n }, [isLeftColumnShown]);\n\n // Dispatch heavy transition event and add body class when opening right column\n useOnChange(([prevIsRightColumnShown]) => {\n if (prevIsRightColumnShown === undefined || animationLevel === 0) {\n return;\n }\n\n fastRaf(() => {\n document.body.classList.add('animating-right-column');\n });\n\n const dispatchHeavyAnimationEnd = dispatchHeavyAnimationEvent();\n\n waitForTransitionEnd(document.getElementById('RightColumn')!, () => {\n dispatchHeavyAnimationEnd();\n\n fastRaf(() => {\n document.body.classList.remove('animating-right-column');\n });\n });\n }, [isRightColumnShown]);\n\n const handleBlur = useCallback(() => {\n updateIsOnline(false);\n\n const initialUnread = selectCountNotMutedUnread(getGlobal());\n let index = 0;\n\n clearInterval(notificationInterval);\n notificationInterval = window.setInterval(() => {\n if (document.title.includes(INACTIVE_MARKER)) {\n updateIcon(false);\n return;\n }\n\n if (index % 2 === 0) {\n const newUnread = selectCountNotMutedUnread(getGlobal()) - initialUnread;\n if (newUnread > 0) {\n updatePageTitle(`${newUnread} notification${newUnread > 1 ? 's' : ''}`);\n updateIcon(true);\n }\n } else {\n updatePageTitle(PAGE_TITLE);\n updateIcon(false);\n }\n\n index++;\n }, NOTIFICATION_INTERVAL);\n }, [updateIsOnline]);\n\n const handleFocus = useCallback(() => {\n updateIsOnline(true);\n\n clearInterval(notificationInterval);\n notificationInterval = undefined;\n\n if (!document.title.includes(INACTIVE_MARKER)) {\n updatePageTitle(PAGE_TITLE);\n }\n\n updateIcon(false);\n }, [updateIsOnline]);\n\n const handleStickerSetModalClose = useCallback(() => {\n openStickerSetShortName({ stickerSetShortName: undefined });\n }, [openStickerSetShortName]);\n\n // Online status and browser tab indicators\n useBackgroundMode(handleBlur, handleFocus);\n useBeforeUnload(handleBlur);\n\n usePreventPinchZoomGesture(isMediaViewerOpen);\n\n function stopEvent(e: React.MouseEvent<HTMLDivElement, MouseEvent>) {\n e.preventDefault();\n e.stopPropagation();\n }\n\n return (\n <div id=\"Main\" className={className} onDrop={stopEvent} onDragOver={stopEvent}>\n <LeftColumn />\n <MiddleColumn />\n <RightColumn />\n <MediaViewer isOpen={isMediaViewerOpen} />\n <ForwardPicker isOpen={isForwardModalOpen} />\n <Notifications isOpen={hasNotifications} />\n <Dialogs isOpen={hasDialogs} />\n {audioMessage && <AudioPlayer key={audioMessage.id} message={audioMessage} origin={audioOrigin} noUi />}\n <SafeLinkModal url={safeLinkModalUrl} />\n <HistoryCalendar isOpen={isHistoryCalendarOpen} />\n <StickerSetModal\n isOpen={Boolean(openedStickerSetShortName)}\n onClose={handleStickerSetModalClose}\n stickerSetShortName={openedStickerSetShortName}\n />\n <DownloadManager />\n </div>\n );\n};\n\nfunction updateIcon(asUnread: boolean) {\n document.querySelectorAll<HTMLLinkElement>('link[rel=\"icon\"]')\n .forEach((link) => {\n if (asUnread) {\n if (!link.href.includes('favicon-unread')) {\n link.href = link.href.replace('favicon', 'favicon-unread');\n }\n } else {\n link.href = link.href.replace('favicon-unread', 'favicon');\n }\n });\n}\n\n// For some reason setting `document.title` to the same value\n// causes increment of Chrome Dev Tools > Performance Monitor > DOM Nodes counter\nfunction updatePageTitle(nextTitle: string) {\n if (document.title !== nextTitle) {\n document.title = nextTitle;\n }\n}\n\nexport default memo(withGlobal(\n (global): StateProps => {\n const { settings: { byKey: { animationLevel, language, wasTimeFormatSetManually } } } = global;\n const { chatId: audioChatId, messageId: audioMessageId, origin } = global.audioPlayer;\n const audioMessage = audioChatId && audioMessageId\n ? selectChatMessage(global, audioChatId, audioMessageId)\n : undefined;\n\n return {\n lastSyncTime: global.lastSyncTime,\n isLeftColumnShown: global.isLeftColumnShown,\n isRightColumnShown: selectIsRightColumnShown(global),\n isMediaViewerOpen: selectIsMediaViewerOpen(global),\n isForwardModalOpen: selectIsForwardModalOpen(global),\n hasNotifications: Boolean(global.notifications.length),\n hasDialogs: Boolean(global.dialogs.length),\n audioMessage,\n audioOrigin: origin,\n safeLinkModalUrl: global.safeLinkModalUrl,\n isHistoryCalendarOpen: Boolean(global.historyCalendarSelectedAt),\n shouldSkipHistoryAnimations: global.shouldSkipHistoryAnimations,\n openedStickerSetShortName: global.openedStickerSetShortName,\n isServiceChatReady: selectIsServiceChatReady(global),\n animationLevel,\n language,\n wasTimeFormatSetManually,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'loadAnimatedEmojis', 'loadNotificationSettings', 'loadNotificationExceptions', 'updateIsOnline',\n 'loadTopInlineBots', 'loadEmojiKeywords', 'openStickerSetShortName', 'loadCountryList', 'ensureTimeFormat',\n 'checkVersionNotification',\n ]),\n)(Main));\n","import { getDispatch, getGlobal } from '../lib/teact/teactn';\n\nimport { DEBUG } from '../config';\n\nexport { default as Main } from '../components/main/Main';\n\nif (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('>>> FINISH LOAD MAIN BUNDLE');\n}\n\nif (!getGlobal().connectionState) {\n getDispatch().initApi();\n}\n"],"names":["closeLocalTextSearch","global","chatId","threadId","selectCurrentMessageList","updateLocalTextSearch","replaceLocalTextSearchResults","undefined","addReducer","actions","payload","query","chatThreadKey","buildChatThreadKey","currentQuery","localTextSearch","byChatThreadKey","MEMO_EMPTY_ARRAY","mediaType","updateLocalMediaSearchType","id","type","shouldReplaceHistory","currentMessageList","replaceThreadParam","exitMessageSelectMode","messages","contentToBeScheduled","forwardMessages","toChatId","setGlobal","updateCurrentMessageList","isChatInfoShown","openChat","chatCreation","newChatMembersProgress","targetIndexDelta","orderedIds","position","indexOf","nextId","FOCUS_NO_HIGHLIGHT_DURATION","FAST_SMOOTH_MAX_DURATION","ANIMATION_END_DELAY","blurTimeout","scrollOffset","messageId","paramName","chatMessages","selectChatMessages","viewportIds","selectViewportIds","lastOwnEditableMessageId","findLast","Boolean","selectAllowedMessageActions","canEdit","replyingToId","selectReplyingToId","selectIsViewportNewest","chatMessageKeys","Object","keys","newIndex","toString","length","Number","MAIN_THREAD_ID","chat","selectChat","lastMessage","threadInfo","selectThreadInfo","lastMessageId","setReplyingToId","focusMessage","avatarOwnerId","profilePhotoIndex","origin","mediaViewer","volume","playbackRate","isMuted","audioPlayer","selectIsRightColumnShown","pollResults","voters","window","setTimeout","newGlobal","getGlobal","noHighlight","replyStack","selectReplyStack","pop","focusLastMessage","messageListType","groupedId","groupedChatId","replyMessageId","isResizingContainer","ids","selectForwardedMessageIdsByGroupId","shouldSwitchChat","clearTimeout","updateFocusedMessage","updateFocusDirection","FocusDirection","includes","direction","loadViewportMessages","fromChatId","messageIds","groupedMessageIds","selectMessageIdsByGroupId","isModalShown","closeMediaViewer","selectedMessages","openForwardMenu","message","byChatId","activeDownloads","filter","map","canDownload","forEach","downloadMessageMedia","selectCurrentChat","enterMessageSelectMode","childMessageIds","withShift","toggleMessageSelection","shouldShowContextMenuHint","disableContextMenuHint","showNotification","IS_TOUCH_ENV","isPollModalOpen","currentVersion","APP_VERSION","slice","join","serviceNotifications","find","version","SERVICE_NOTIFICATIONS_USER_ID","date","getServerTime","serverTimeOffset","content","text","parseMessageInput","isOutgoing","createServiceNotification","serviceChat","maxId","Math","max","fractionalPart","floor","serviceNotification","isUnread","apiUpdate","globalSearch","updateGlobalSearch","globalResults","localResults","resultsByType","fetchingStatus","chats","recentlyFoundChatIds","newRecentIds","unshift","updateGlobalSearchContent","stickers","search","resultIds","gifs","offsetId","results","updateSelectedUserId","updateUserSearch","globalUserIds","localUserIds","leftColumnWidth","management","isActive","IS_SINGLE_COLUMN_LAYOUT","IS_TABLET_COLUMN_LAYOUT","isLeftColumnShown","messageLists","action","emoji","recentEmojis","newEmojis","e","sticker","recent","hash","newStickers","s","notification","localId","generateIdFor","newNotifications","notifications","existingNotificationIndex","findIndex","n","splice","push","data","hasErrorKey","getReadableErrorText","newDialogs","dialogs","existingErrorIndex","err","url","safeLinkModalUrl","selectedAt","historyCalendarSelectedAt","payment","isPaymentModalOpen","clearPayment","closeInvoice","error","processDeepLink","protocol","searchParams","pathname","URL","openChatByInvite","openChatByUsername","openStickerSetShortName","getDispatch","method","replace","params","value","key","domain","post","comment","username","commentId","channel","invite","set","stickerSetShortName","runThrottledForLoadChats","throttle","cb","runThrottledForLoadTopChats","runDebouncedForLoadFullChat","debounce","async","loadChats","listType","offsetDate","result","callApi","limit","CHAT_LIST_LOAD_SLICE","archived","withPinned","orderedPinnedIds","lastLocalServiceMessage","selectLastServiceNotification","chatIds","shift","addUsers","buildCollectionByKey","users","updateChats","updateChatListIds","updateChatListSecondaryInfo","draftsById","replyingToById","isFullyLoaded","loadFullChat","fullInfo","updateChat","fetchChatByUsername","localChat","selectChatByUsername","isMin","preloadedChatIds","i","TOP_CHAT_MESSAGES_PRELOAD_LIMIT","pause","byId","listIds","active","currentChatId","pinnedChats","otherChats","prepareChatList","chatToPreload","currentUserId","hasUnreadMark","toggleChatUnread","requestThreadInfoUpdate","isChatSummaryOnly","requestChatUpdate","user","selectUser","selectThreadTopMessageId","chatFullInfo","linkedChatId","selectSupportChat","TMP_CHAT_ID","langCode","usernamePostfix","LOCALIZED_TIPS","toUpperCase","TIPS_USERNAME","oldestChat","selectIsChatPinned","sort","chat1","chat2","currentGlobal","force","lastLocalMessage","title","about","photo","memberIds","progress","ChatCreationProgress","createdChannel","channelId","accessHash","createChannel","userId","leaveChat","createdChat","createGroupChat","folderId","folder","selectChatFolder","shouldBePinned","pinnedChatIds","includedChatIds","newPinnedIds","pinnedId","newIncludedChatIds","folderUpdate","selectChatListType","isPinned","ARCHIVED_FOLDER_ID","isChatArchived","chatFolders","loadChatFolders","recommendedChatFolders","recommended","loadRecommendedChatFolders","idsToRemove","idsToAdd","includedId","concat","emoticon","recommendedId","description","newFolder","createChatFolder","apply","deleteChatFolder","unreadCount","match","RE_TG_LINK","uri","startsWith","part1","part2","part3","split","l","decodeURI","fromEntries","substr","chatOrChannelPostId","channelPostId","openPreviousChat","usernameChat","discussionChatId","openCommentsByUsername","isEnabled","isChatBasicGroup","bannedRights","chatAfterUpdate","members","kickedMembers","isBanned","viewMessages","isUnblocked","m","adminRights","customTitle","adminMembers","isDismissed","updateManagementProgress","ManagementProgress","Promise","all","groups","addedById","reduce","group","addChats","forDiscussionIds","fullChat","isPreHistoryHidden","activeChatFolder","offset","setNewChatMembersDialogState","NewChatMembersProgress","uploadProgressCallbacks","Map","runDebouncedForMarkRead","isOutlying","isBudgetPreload","addOffset","LoadMoreDirection","round","MESSAGE_LIST_SLICE","selectThreadOriginChat","threadInfos","localMessages","allMessages","addChatMessagesById","updateOutlyingIds","updateListedIds","updateThreadInfos","listedIds","selectListedIds","outlyingIds","selectOutlyingIds","areSortedArraysIntersecting","historyIds","newViewportIds","getViewportSlice","safeReplaceViewportIds","sourceIds","index","findClosestIndex","indexForDirection","from","to","areSomeLocal","areAllLocal","sendMessage","progressCallback","attachment","messageLocalId","has","fileUploads","byMessageLocalId","replyingTo","IS_IOS","rafPromise","delete","isRestricted","resolve","loadWithBudget","selectFocusedMessageId","selectRealLastReadId","replyOriginForId","threadUpdate","MESSAGE_DELETED","replyMessage","selectChatMessage","updateChatMessage","replyToMessageId","loadMessage","isDeleting","updateThreadUnreadFromForwardedMessage","scheduledAt","clearWebPagePreview","noWebPage","selectNoWebPage","isSingle","attachments","isGrouped","restParams","entities","commonParams","groupedAttachments","MAX_MEDIA_FILES_FOR_ALBUM","firstAttachment","restAttachments","Date","now","selectEditingMessage","setEditingId","get","previousLocalId","cancelApiProgress","draft","replyToMsgId","draftDate","localOnly","selectDraft","isUnpin","isOneSide","isSilent","unpinAllMessages","shouldDeleteForAll","editingId","selectEditingId","selectEditingScheduledId","activeChat","reason","peer","minId","selectFirstUnreadId","readCount","count","countSortedIds","lastReadInboxMessageId","webPagePreview","loadWebPagePreview","options","option","shouldResetVoters","unique","offsets","nextOffset","loadPollOptionResults","fromChat","toChat","a","b","realMessages","isServiceNotificationMessage","poll","replaceScheduledMessages","loadScheduledHistory","selectScheduledMessage","loadPinnedMessages","searchThrottled","searchGifs","updateGifSearch","added","addedStickers","updateStickerSets","sets","loadStickerSets","setIds","addedSetIds","loadStickers","stickerSetId","recentStickers","loadRecentStickers","favorite","favoriteStickers","loadFavoriteStickers","greeting","featured","featuredStickers","loadFeaturedStickers","stickerSetAccessHash","stickerSet","selectStickerSet","packs","updateStickerSet","currentEmoji","forEmoji","rebuildStickersForEmoji","replaceAnimatedEmojis","loadAnimatedEmojis","saved","savedGifs","loadSavedGifs","unfave","unfaveSticker","installedDate","language","currentEmojiKeywords","emojiKeywords","isLoading","fromVersion","keywords","searchStickers","setsById","searchWords","updateStickersForEmoji","loadStickersForEmoji","openedStickerSetShortName","searchMessagesGlobal","offsetRate","maxDate","minDate","localResult","chatOrUser","GLOBAL_SEARCH_SLICE","totalCount","nextOffsetId","nextRate","currentSearchQuery","selectCurrentGlobalSearchQuery","updateGlobalSearchFetchingStatus","addMessages","updateGlobalSearchResults","localChats","localUsers","globalChats","globalUsers","userIds","searchChats","timestampPlusDay","foundIds","currentSearch","selectCurrentTextSearch","topMessageId","MESSAGE_SEARCH_SLICE","newFoundIds","updateLocalTextSearchResults","searchTextMessages","peerId","selectCurrentMediaSearchPeerId","selectCurrentMediaSearch","currentType","currentResults","SHARED_MEDIA_SLICE","updateLocalMediaSearchResults","searchSharedMedia","timestamp","searchMessagesByDate","updateManagement","isUsernameAvailable","loadAndReplaceArchivedChats","updateUsers","replaceChatListIds","loadAndUpdateUsers","contactIds","contactList","updatedUsers","loadTopMessages","afterSyncCallback","DEBUG","console","log","savedUsers","savedPrivateChatIds","savedChats","selectedChat","isUserId","selectedChatUser","replaceChats","loadAndReplaceChats","areMessagesLoaded","currentThreadId","draftsByChatId","acc","newCurrentChatId","currentMessageListInfo","originChannelId","currentMessageListInfoOrigin","resultOrigin","byIdOrigin","listedIdsOrigin","threadsById","Array","prototype","replaceUsers","audioChatId","audioMessageId","closeAudioPlayer","loadAndReplaceMessages","lastSyncTime","sync","afterSync","updateAppBadge","selectCountNotMutedUnread","runDebouncedForFetchFullUser","runThrottledForSearch","replaceInlineBotSettings","inlineBotSettings","inlineBots","byUsername","replaceInlineBotsIsLoading","topPeers","lastRequestedAt","loadTopUsers","getCompareString","lastName","firstName","collator","Intl","Collator","sortedUsers","compare","isSelf","loadContactList","isUserBot","commonChats","updateUser","updateChatMutedState","phoneNumber","phone","updateContact","deleteUser","profileId","isPrivate","photos","userSearch","updateUserSearchFetchingStatus","searchUsers","pick","runDebouncedForSearch","sendBotCommand","command","button","RE_TME_LINK","openTelegramLink","toggleSafeLinkModal","showDialog","alert","isError","answerCallbackButton","openPollModal","getReceipt","receiptMessageId","getPaymentForm","setInvoiceMessageInfo","openPaymentModal","bot","selectChatBot","removeBlockedContact","topInlineBots","inlineBotData","inlineBot","switchPm","canLoadMore","shouldReplaceSettings","newInlineBotData","currentIds","Set","newResults","help","isGallery","searchInlineBot","queryId","resultId","botId","param","startParam","replaceSettings","hasPassword","updateTwoFaSettings","hint","currentPassword","onSuccess","isSuccess","password","email","waitingEmailCodeLength","code","requestInfo","saveInfo","selectPaymentChatId","selectPaymentMessageId","shouldSave","shippingOptions","setRequestInfoId","updateShippingOptions","setPaymentStep","PaymentStep","validateRequestedInfo","setPaymentForm","step","invoice","shippingAddressRequested","nameRequested","phoneRequested","emailRequested","setReceipt","receipt","publishableKey","selectProviderPublishableKey","credentials","k","buildQueryString","cardNumber","expiryMonth","expiryYear","cvv","zip","country","response","fetch","headers","Authorization","json","getStripeError","setStripeCardInfo","sendStripeCredentials","shippingOptionId","saveCredentials","formId","selectPaymentFormId","requestInfoId","selectPaymentRequestId","stripeCredentials","selectStripeCredentials","requestedInfoId","sendPaymentForm","save","runThrottledForUpdateAppBadge","update","noTopChatsRequest","selectIsChatListed","loadTopChats","newProfilePhoto","closeMessageNotifications","isNotJoined","typingStatus","senderId","isFromScheduled","hasUnreadMention","unreadMentionsCount","notifyAboutNewMessage","messageUpdate","selectCommonBoxChatId","targetChat","newOrderedPinnedIds","MAX_ACTIVE_PINNED_CHATS","updateChatListType","chatFoldersById","newChatFoldersById","newOrderedIds","orderedId","folders","replacedMembers","addedMember","deletedMemberId","shouldUpdate","some","deleteIndex","isOwner","isAdmin","membersCount","formattedText","ANIMATION_DELAY","updateWithLocalMedia","isScheduled","currentMessage","video","document","getMessageContent","blobUrl","thumbnail","isPreloadedGlobally","previewBlobUrl","updateScheduledMessage","updateThreadUnread","selectThreadByMessage","originMessage","updateListedAndViewportIds","firstMessageId","isUnreadChatNotLoaded","isMessageLocal","addViewportId","messagesCount","firstUnreadId","updateChatLastMessage","currentLastMessage","findLastMessage","deleteMessages","newLastMessage","threadIdsToUpdate","deleteChatMessages","chatsIdsToUpdate","commonBoxChatId","shouldForceReply","updateThreadInfo","newMessage","isMessageInCurrentMessageList","delayedGlobal","scheduledIds","selectScheduledIds","selectIsChatWithBot","selectScheduledMessages","deleteChatScheduledMessages","thread","markMessageListRead","currentPinnedIds","selectPinnedIds","newTheadInfo","messagesById","scheduledMessages","deleteScheduledMessages","pollId","pollUpdate","selectChatMessageByPollId","updatedPoll","updatedResults","isChosen","chosenAnswers","chosenAnswer","chosenAnswerIndex","recentVoterIds","totalVoters","newRecentVoterIds","newTotalVoters","targetOption","targetOptionIndex","updatedOption","votersCount","selectIsServiceChatReady","flushStatusUpdatesThrottled","pendingStatusUpdates","statusUpdate","status","targetUser","isBlocked","addBlockedContact","settings","privacy","rules","updateNotifySettings","peerType","shouldShowPreviews","addNotifyException","twoFaSettings","useBeforeUnload","callback","useEffect","onBeforeUnload","metaViewport","querySelector","defaultViewportContent","getAttribute","preventEvent","preventDefault","useBrowserOnline","isOnline","setIsOnline","useState","navigator","onLine","handleChange","addEventListener","removeEventListener","ANIMATION_LEVEL_OPTIONS","memo","withGlobal","searchQuery","chatsById","animationLevel","byKey","globalSearchChatId","searchDate","theme","selectTheme","contactsFilter","onSearchQuery","onSelectSettings","onSelectContacts","onSelectArchived","setGlobalSearchChatId","onReset","shouldSkipTransition","openTipsChat","setGlobalSearchDate","setSettingOption","lang","useLang","hasMenu","LeftColumnContent","selectedSearchDate","useMemo","formatDateToString","archivedUnreadChatsCount","values","total","withOtherVersions","location","hostname","MainButton","onTrigger","isOpen","Button","ripple","size","color","className","onClick","ariaLabel","buildClassName","handleSearchFocus","useCallback","handleSelectSaved","handleDarkModeToggle","stopPropagation","newTheme","shouldUseSystemTheme","switchTheme","ANIMATION_LEVEL_MAX","handleAnimationLevelChange","newLevel","_","body","classList","toggle","isSearchFocused","searchInputPlaceholder","DropdownMenu","trigger","footer","APP_NAME","MenuItem","icon","Switcher","label","checked","noAnimation","toLowerCase","href","FEEDBACK_URL","localStorage","setItem","JSON","stringify","disableHistoryBack","SearchInput","inputId","parentContainerClassName","focused","placeholder","autoComplete","canClose","onChange","onFocus","PickerSelectedItem","isMinimized","clickArg","chatOrUserId","dir","isRtl","Spinner","usersById","orderedFolderIds","shouldSkipHistoryAnimations","notifySettings","selectNotifySettings","notifyExceptions","selectNotifyExceptions","foldersDispatch","onScreenSelect","setActiveChatFolder","transitionRef","useRef","displayedFolders","folderCountersById","resolverFn","ms","dependencies","runThrottled","noFirst","useThrottle","setValue","isFrozen","freeze","unfreeze","useFlag","useHeavyAnimationCheck","useOnChange","useThrottledMemo","counters","unreadDialogsCount","hasActiveDialogs","getFolderUnreadDialogs","badgeCount","isBadgeActive","folderTabs","handleSwitchTab","current","captureEvents","selectorToPreventScroll","onSwipe","SwipeDirection","min","isNotInAllTabRef","captureEscKeyListener","useHistoryBack","handleKeyDown","ctrlKey","shiftKey","digit","shouldRender","shouldRenderPlaceholder","transitionClassNames","useShowTransition","renderCurrentTab","activeFolder","ChatList","folderType","TabList","tabs","activeTab","onSwitchTab","Transition","ref","name","activeKey","renderCount","props","LeftSearch","useModuleLoader","Bundles","Loading","ContactList","closeTimeout","isShown","onNewPrivateChat","onNewChannel","onNewGroup","isMenuOpen","setIsMenuOpen","fabClassName","handleMouseEnter","handleMouseLeave","onMouseEnter","onMouseLeave","tabIndex","Menu","positionX","positionY","autoClose","onClose","TRANSITION_RENDER_COUNT","onContentChange","connectionState","isNewChatButtonShown","setIsNewChatButtonShown","isConnecting","isMouseInside","handleSelectSettings","handleSelectContacts","handleSelectNewChannel","handleSelectNewGroup","handleSelectArchived","autoCloseTimeout","shouldRenderUpdateButton","updateButtonClassNames","handleUpdateClick","isAppOutdated","markIsAppOutdated","timeout","reload","useAppOutdatedCheck","ShowTransition","isCustom","shouldCleanup","cleanupExceptionKey","fluid","pill","Settings","NewChat","ArchivedChats","ContentType","RENDER_COUNT","setGlobalSearchQuery","resetChatCreation","loadPasswordInfo","clearTwoFaError","setLeftColumnWidth","resetLeftColumnWidth","resizeRef","setContent","settingsScreen","setSettingsScreen","SettingsScreens","setContactsFilter","foldersState","useFoldersReducer","lastResetTime","setLastResetTime","contentType","Main","Archived","NewChannel","NewGroup","handleReset","forceReturnToChatList","pickerSearchInput","getElementById","blur","handleSearchQuery","initResize","resetResize","handleMouseUp","elementRef","onResize","initialWidth","markIsActive","unmarkIsActive","initialMouseX","setInitialMouseX","initialElementWidth","setInitialElementWidth","style","width","remove","handleMouseMove","event","newWidth","ceil","clientX","stopDrag","offsetWidth","add","useResize","handleSettingsScreenSelect","screen","LAYERS_ANIMATION_NAME","currentScreen","isChannel","onMouseDown","onMouseUp","onDoubleClick","setSize","windowSize","handleResize","MAX_MESSAGES_LIST_WIDTH","HeaderMenuContainer","isChatChannel","selectIsInSelectMode","noMenu","isChatWithSelf","selectIsChatWithSelf","isMainThread","isDiscussionThread","isRightColumnShown","canRestartBot","selectIsUserBlocked","canStartBot","selectIsChatBotNotStarted","canSubscribe","isChatSuperGroup","canSearch","canMute","canLeave","canExpandActions","joinChannel","openLocalTextSearch","restartBot","menuButtonRef","menuPosition","setMenuPosition","handleHeaderMenuOpen","rect","getBoundingClientRect","x","right","y","bottom","handleHeaderMenuClose","handleHeaderMenuHide","handleSubscribeClick","handleStartBot","handleRestartBot","handleSearchClick","focus","searchInput","disabled","anchor","withExtraActions","onSubscribeChannel","onSearchClick","onCloseAnimationEnd","useWebpThumbnail","thumbDataUri","getMessageMediaThumbDataUri","shouldDecodeThumbnail","isWebpSupported","thumbnailDecoded","setThumbnailDecoded","EMPTY_IMAGE_DATA_URI","useLayoutEffect","webpToPngBase64","then","catch","drawRect","height","radius","containerRef","markupParams","reverseIndex","barHeight","getBarHeight","markHeight","getMarkHeight","trackHeight","getTrackHeight","clipPathId","clipPath","d","getClipPath","markTranslateY","getMarkTranslateY","trackTranslateY","getTrackTranslateY","calculateMarkup","firstChild","firstElementChild","currentElement","transform","svg","div","defs","innerHTML","onUnpinMessage","onAllPinnedClick","mediaThumbnail","mediaBlobUrl","useMedia","getMessageMediaHash","getMessageSummaryText","isUnpinDialogOpen","openUnpinDialog","closeUnpinDialog","handleUnpinMessage","ConfirmDialog","confirmLabel","confirmHandler","getPictogramDimensions","src","alt","renderPictogram","renderText","RippleEffect","scaleImage","image","ratio","outputType","Blob","createObjectURL","img","Image","onload","scale","blob","finally","revokeObjectURL","steppedScale","bitmap","createImageBitmap","resizeWidth","resizeHeight","resizeQuality","Error","res","canvas","createElement","ctx","getContext","transferFromImageBitmap","drawImage","toBlob","oc","octx","mul","cur","LOGO_DIMENSIONS","MINIMAL_SIZE","sender","audio","voice","fileName","artist","performer","getSenderTitle","getTranslation","album","getChatTitle","audioCoverHash","getAudioHasCover","avatarHash","getChatAvatarHash","media","thumbnailSizes","AVATAR_FULL_DIMENSIONS","getCoverSize","fn","deps","defaultValue","setIsLoading","setError","setResult","wasCancelled","telegramLogoPath","resizeImage","makeGoodArtwork","useAsync","buildMediaMetadata","artwork","selectSender","AudioOrigin","noUi","setAudioPlayerVolume","setAudioPlayerPlaybackRate","setAudioPlayerMuted","isVoice","senderName","mediaData","mediaLoader","mediaMetadata","useMessageMediaMetadata","playPause","stop","isPlaying","requestNextTrack","requestPreviousTrack","isFirst","isLast","setVolume","toggleMuted","setPlaybackRate","useAudioPlayer","makeTrackId","getMediaDuration","handleClick","handleClose","clearMediaSession","handleVolumeChange","handleVolumeClick","handlePlaybackClick","volumeIcon","renderAudio","subtitle","renderVoice","withClickPropagation","RangeSlider","audioMessage","pinnedIds","state","isSelectModeActive","isChatWithBot","currentTransitionKey","assign","pinnedMessageId","topMessageSender","selectForwardedSender","pinnedMessageIds","canUnpin","firstPinnedMessage","isReady","openChatWithInfo","pinMessage","toggleLeftColumn","isBackButtonActive","pinnedMessageIndex","setPinnedMessageIndex","isArray","pinnedMessage","pinnedMessagesCount","chatTitleLength","topMessageTitle","useEnsureMessage","windowWidth","useWindowSize","isLeftColumnHideable","MIN_SCREEN_WIDTH_FOR_STATIC_LEFT_COLUMN","shouldShowCloseButton","componentRef","shouldAnimateTools","handleHeaderClick","handlePinnedMessageClick","cycleRestrict","handleAllPinnedClick","setBackButtonActive","handleBackClick","messageInput","EDITABLE_INPUT_ID","canToolsCollideWithChatInfo","SAFE_SCREEN_WIDTH_FOR_CHAT_INFO","MOBILE_SCREEN_MAX_WIDTH","shouldUseStackedToolsClass","MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN","SAFE_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN","shouldRenderAudioPlayer","audioPlayerClassNames","renderingAudioMessage","useCurrentOrPrev","shouldRenderPinnedMessage","pinnedMessageClassNames","renderingPinnedMessage","renderingPinnedMessagesCount","renderingCanUnpin","renderingPinnedMessageTitle","canRevealTools","componentEl","renderInfo","renderBackButton","PrivateChatInfo","withFullInfo","withMediaViewer","withUpdatingStatus","noRtl","GroupChatInfo","asClose","withUnreadCount","formatIntegerCompact","isAudioPlayerRendered","Infinity","getMessageKey","isAlbum","messageOrAlbum","groupMessages","currentAlbum","currentSenderGroup","currentDateGroup","originalDate","datetime","getDayStart","senderGroups","dateGroups","isInAlbum","mainMessage","albumId","nextMessage","nextMessageDayStartsAt","isActionMessage","forwardInfo","senderUserId","hiddenUserName","inlineButtons","INTERSECTION_THROTTLE_FOR_MEDIA","IS_ANDROID","INTERSECTION_MARGIN_FOR_MEDIA","isEmojiOnlyMessage","customShape","getMinMediaWidth","hasText","hasCommentButton","calculateMediaDimensions","noAvatars","isOwn","isOwnMessage","isForwarded","isForwardedMessage","getMessagePhoto","getMessageWebPagePhoto","getMessageVideo","isWebPagePhoto","calculateInlineImageDimensions","calculateVideoDimensions","minMediaWidth","getMessageText","stretchFactor","finalWidth","finalHeight","isSmall","accumulate","list","initValue","accumulator","item","clamp","num","low","high","calculateContainerSize","layout","styles","dimensions","sides","calculateAlbumLayout","ratios","proportions","getProportions","averageRatio","getAverageRatio","albumCount","forceCalc","maxWidth","getAvailableWidth","REM","minWidth","maxHeight","spacing","originalRatios","cropRatios","attempts","pushAttempt","lineCounts","heights","currentCount","attemptCount","sum","multiHeight","first","second","third","fourth","optimalAttempt","optimalDiff","lineCount","totalHeight","bad1","bad2","line","diff","abs","optimalCounts","optimalHeights","rowCount","row","colCount","lineHeight","col","layoutWithComplexLayouter","AlbumRectPart","layoutTwoTopBottom","layoutTwoLeftRightEqual","minimalWidth","secondWidth","firstWidth","layoutTwoLeftRight","layoutTwo","firstHeight","thirdHeight","secondHeight","rightWidth","leftWidth","layoutThreeLeftAndOther","layoutThreeTopAndOther","layoutThree","w","h0","h","w0","w2","w1","h1","layoutFourTopAndOther","h2","layoutFourLeftAndOther","layoutFour","containerStyle","element","calculateAuthorWidth","font","whiteSpace","left","opacity","appendChild","useFocusMessage","isFocused","focusDirection","noFocusHighlight","messagesContainer","closest","fastSmoothScroll","ContextMenuContainer","targetUserIds","targetChatId","targetMessageId","targetMessage","selectIsMessageFocused","focusedMessage","observeIntersection","isEmbedded","appearanceOrder","isLastInList","useOnIntersect","noAppearanceAnimation","markShown","targetUsers","renderActionMessageText","asPlain","isContextMenuOpen","contextMenuPosition","handleBeforeContextMenu","handleContextMenu","handleContextMenuClose","handleContextMenuHide","useContextMenuHandlers","isContextMenuShown","preventMessageInputBlur","onContextMenu","customText","isIntersecting","useIsIntersecting","pictogramId","isRoundVideo","getMessageRoundVideo","senderTitle","outgoingStatus","signature","views","isEdited","formatTime","MessageOutgoingStatus","observeIntersectionForPlaying","shouldLoop","isModalOpen","openModal","closeModal","isAnimated","isMemojiSticker","MEMOJI_STICKER_ID","shouldLoad","shouldPlay","mediaHash","getMessageMediaFormat","isMediaLoaded","isAnimationLoaded","markAnimationLoaded","isMediaReady","useMediaTransition","getStickerDimensions","thumbClassName","stickerClassName","AnimatedSticker","animationData","play","noLoop","onLoad","fromSticker","useBlurredMediaThumbRef","fullMediaData","useCanvasBlur","IS_CANVAS_FILTER_SUPPORTED","SELECTED_APPENDIX_COLORS","dark","outgoing","incoming","light","canAutoLoad","isInSelectMode","isSelected","uploadProgress","nonInteractive","shouldAffectAppendix","isDownloading","onCancelUpload","localBlobUrl","isLoadAllowed","setIsLoadAllowed","loadProgress","useMediaWithLoadProgress","thumbRef","downloadProgress","isUploading","isTransferring","transferProgress","getMediaTransferState","wasLoadDisabled","usePrevious","shouldRenderSpinner","spinnerClassNames","shouldRenderDownloadButton","downloadButtonClassNames","isAllowed","contentEl","inSelectMode","getImageData","getAppendixColorFromImage","getCustomAppendixBg","appendixBg","setProperty","setAttribute","ProgressSpinner","useHeavyAnimationCheckForVideo","playerRef","shouldPlayRef","safePlay","isPlayAllowed","wasPlaying","freezePlaying","paused","unfreezePlaying","contains","unfreezePlayingOnRaf","fastRaf","hasFocus","useBackgroundMode","canAutoPlay","videoRef","getMessageWebPageVideo","setIsPlayAllowed","previewClassNames","isInline","ApiMediaFormat","isBuffered","bufferingHandlers","useBuffering","shouldRenderPlayButton","playButtonClassNames","playProgress","setPlayProgress","handleTimeUpdate","currentTarget","currentTime","duration","usePauseOnInactive","useVideoCleanup","cancelMessageMediaDownload","autoPlay","muted","loop","playsInline","onTimeUpdate","isGif","formatMediaDuration","contact","countryList","phoneCodes","phoneCodeList","openUserInfo","Avatar","formatPhoneNumberWithCode","getPercentage","toFixed","answer","voteResults","maxVotersCount","correctResults","shouldAnimate","r","correctAnswer","showIcon","answerPercent","finalPercent","setFinalPercent","lineRef","lineWidth","isAnimationDoesNotStart","lineEl","svgEl","lineStyle","onSendVote","openPollResults","summary","isSubmitting","setIsSubmitting","chosenOptions","setChosenOptions","isSolutionShown","setIsSolutionShown","wasSubmitted","setWasSubmitted","closePeriod","setClosePeriod","closed","closeDate","countdownRef","hasVoted","canVote","canViewResult","isPublic","isMultiple","multipleChoice","answers","isCorrect","hidden","quiz","countdownEl","circumference","PI","lastElementChild","timerEl","strokeDashOffset","textContent","timer","recentVoters","handleRadioChange","handleCheckboxChange","handleVoteClick","handleViewResultsClick","handleSolutionShow","handleSolutionHide","solution","Notification","renderTextWithEntities","solutionEntities","onDismiss","containerId","question","getPollTypeString","CheckboxGroup","loadingOptions","RadioGroup","loadingOption","isQuiz","getReadableVotersCount","isText","inPreview","onMediaClick","onCancelMediaTransfer","webPage","getMessageWebPage","isSquarePhoto","handleMediaClick","siteName","displayUrl","isMediaInteractive","truncatedDescription","trimText","SafeLink","getMessageInvoice","amount","currency","isTest","photoUrl","formatCurrency","withSelectControl","WrappedComponent","ownProps","selectIsMessageSelected","handleMessageSelect","newProps","PhotoWithSelect","Photo","VideoWithSelect","Video","activeDownloadIds","selectActiveDownloadIds","uploadsById","hasCustomAppendix","albumLayout","cancelSendingMessage","mediaCount","handleCancelUpload","containerWidth","containerHeight","fileUpload","currentOnRelease","playingProgressRef","shouldSpinnerRender","isActivated","setIsActivated","setProgress","svgCenter","ROUND_VIDEO_DIMENSIONS_PX","playerEl","playingProgressEl","stopPlaying","capturePlaying","onRelease","stopCurrentAudio","videoClassName","onEnded","recentReplierIds","recentRepliers","hasUnread","GROUP_MESSAGE_HOVER_ATTRIBUTE","handleDocumentGroupMouseEnter","lastGroupElement","getLastElementInDocumentGroup","handleDocumentGroupMouseLeave","removeAttribute","nextElementSibling","withSenderName","withAvatar","viaBotId","replyToChatId","isRepliesChat","isChatWithRepliesBot","chatUsername","forceSenderName","isAnonymousOwnMessage","canShowSender","originSender","botSender","threadTopMessageId","isThreadTop","shouldHideReply","replyMessageSender","selectUploadProgress","isForwarding","highlight","singleEmoji","getMessageSingleEmoji","every","canReply","selectIsDownloading","isSingleEmoji","animatedEmoji","selectAnimatedEmoji","isGroupSelected","selectIsDocumentGroupSelected","isPinnedList","canAutoLoadMedia","selectCanAutoLoadMedia","canAutoPlayMedia","selectCanAutoPlayMedia","autoLoadFileMaxSizeMb","shouldLoopStickers","selectShouldLoopStickers","selectOutgoingStatus","observeIntersectionForBottom","observeIntersectionForMedia","observeIntersectionForAnimatedStickers","noComments","isFirstInGroup","isLastInGroup","isFirstInDocumentGroup","isLastInDocumentGroup","clickInlineButton","bottomMarkerRef","appendixRef","isLocal","hasReply","isReplyMessage","hasThread","asForwarded","isLinkedChannelPost","isInDocumentGroup","getMessageCustomShape","textParts","renderMessageText","adminTitle","metaSafeAuthorWidth","canShowActionButton","canForward","canFocus","isChannelPost","fromMessageId","avatarPeer","senderPeer","selectMessage","handleMouseDown","handleDoubleClick","handleContentDoubleClick","isSwiped","markSwiped","unmarkSwiped","startedAt","target","matches","useOuterHandlers","handleAvatarClick","handleSenderClick","handleViaBotClick","handleReplyClick","handleAudioPlay","handleAlbumMediaClick","handleMetaClick","handleReadMedia","handleVoteSend","handleGroupForward","handleForward","handleFocus","handleFocusForwarded","handleDocumentGroupSelectAll","openMediaViewer","openAudioPlayer","markMessagesRead","sendPollVote","focusMessageInComments","replyToTopMessageId","MediaViewerOrigin","albumMessageId","selectWithGroupedId","useInnerHandlers","containerClassName","contentClassName","hasComments","hasActionButton","classNames","isMedia","isMediaWithNoText","isViaBot","isRound","buildContentClassName","withCommentButton","withAppendix","calculatedWidth","noMediaCorners","extraPadding","isAvatarPeerUser","avatarUser","avatarChat","hiddenName","renderAvatar","shouldInlineMeta","textContentClass","senderColor","getUserColorKey","renderSenderName","AnimatedEmoji","forceLoadPreview","Audio","isSelectable","onPlay","onReadMedia","Document","renderContent","messageGroups","isViewportNewest","withUsers","anchorIdRef","memoUnreadDividerBeforeIdRef","memoFirstUnreadIdRef","hasLinkedChat","isSchedule","onFabToggle","onNotchToggle","openHistoryCalendar","observeIntersectionForReading","observe","useIntersectionObserver","rootRef","throttleMs","margin","freezeForReading","unfreezeForReading","noAutoFreeze","entries","mentionIds","entry","dataset","useMessageObservers","backwardsTriggerRef","forwardsTriggerRef","fabTriggerRef","loadMoreBackwards","loadMoreForwards","toggleScrollTools","offsetHeight","scrollHeight","scrollTop","scrollBottom","isAtBottom","MESSAGE_LIST_SENSITIVE_AREA","LOCAL_MESSAGE_ID_BASE","triggerEntry","resetScroll","observeIntersectionForFab","freezeForFab","unfreezeForFab","observeIntersectionForNotch","freezeForNotch","unfreezeForNotch","useScrollHooks","unreadDivider","messageCountToAnimate","messageGroup","flatten","appearanceIndex","dateGroup","dateGroupIndex","dateGroupsArray","senderGroup","senderGroupIndex","senderGroupsArray","compact","currentDocumentGroupId","messageIndex","isMessageAlbum","documentGroupId","nextDocumentGroupId","originalId","getMessageOriginalId","teactFastList","SCHEDULED_WHEN_ONLINE","formatHumanDate","dividend","getUserIdDividend","lastUnreadMessageId","loadGreetingStickers","debounceMs","handleStickerSelect","selectedSticker","StickerButton","isGroupChatJustCreated","renderScheduled","renderSavedMessages","renderGroup","runDebouncedForScroll","selectCurrentMessageIds","restrictionReason","focusingId","withLastMessageWhenPreloading","chatBot","botDescription","isChatLoaded","isChannelChat","isGroupChat","isChatGroup","isCreator","isBot","threadFirstMessageId","selectFirstMessageId","hasTools","canPost","setScrollOffset","scrollOffsetRef","selectScrollOffset","anchorTopRef","listItemElementsRef","memoFocusingIdRef","isScrollTopJustUpdatedRef","shouldAnimateAppearanceRef","setContainerHeight","onTickEnd","listedMessages","orderBy","loadMoreAround","isScrolled","updateStickyDates","markIsScrolled","runDebounced","useDebounce","container","currentStuck","stuckDateEl","allElements","querySelectorAll","containerTop","el","offsetTop","top","findStuckDate","useStickyDates","handleScroll","parentElement","observer","ResizeObserver","offsetParent","contentRect","disconnect","windowHeight","normalHeight","String","clientHeight","preservedItemElements","useLayoutEffectWithPrevDeps","prevMessageIds","prevIsViewportNewest","prevContainerHeight","shouldForceScroll","hasLastMessageChanged","hasViewportShifted","wasMessageAdded","isAlreadyFocusing","lastItemElement","bottomOffset","newScrollTop","isResized","isAnimatingScroll","useEffectWithPrevDeps","prevIsSelectModeActive","dispatchHeavyAnimationEvent","shouldRenderGreeting","onScroll","withExtraShift","focusNextReply","messageElements","lastMessageElement","MAX_QUICK_IMG_SIZE","FILE_EXT_REGEX","buildAttachment","filename","isQuick","mimeType","quick","SUPPORTED_IMAGE_CONTENT_TYPES","preloadImage","resizedUrl","fetchBlob","SUPPORTED_VIDEO_CONTENT_TYPES","videoWidth","videoHeight","preloadVideo","createPosterForVideo","resetInput","applyIosAutoCapitalizationFix","inputEl","POLYFILL_OPTIONS","encoderPath","reuseWorker","BLOB_PARAMS","opusRecorderPromise","OpusRecorder","mediaRecorder","init","default","start","analyzerCallback","startMediaRecorder","pausedAt","chunks","waveform","ondataavailable","typedArray","releaseAnalyzer","recorder","source","sourceNode","analyser","context","createAnalyser","fftSize","connect","dataLength","frequencyBinCount","dataArray","Uint8Array","isDestroyed","tick","getByteFrequencyData","requestAnimationFrame","subscribeToAnalyzer","reject","onstop","onerror","delayStop","CLIPBOARD_ACCEPTED_TYPES","getMessageTextAsHtml","tempEl","INLINE_BOT_QUERY_REGEXP","HAS_NEW_LINE","RE_COMMAND","DeleteMessageModal","openTimeout","isFirstTimeActivation","onActivate","buttonProps","AttachMenu","SymbolMenu","InlineBotTooltip","MentionTooltip","CustomSend","StickerTooltip","BotCommandTooltip","useMouseInside","isKeyboardSingleUse","forceOpen","markForceOpen","unmarkForceOpen","keyboardButtons","forwardMessageIds","forwardedMessagesCount","exitForwardMode","canAnimate","useAsyncRendering","clearEmbedded","handleMessageClick","faded","AttachmentModal","BotCommandMenu","PollModal","DropArea","RE_LINK","RegExp","RE_LINK_TEMPLATE","messageText","toggleMessageWebPage","link","linkEntity","ApiMessageEntityTypes","textMatch","renderingWebPage","webPageWithoutPhoto","messageStub","CalendarModal","MainButtonState","chatUser","selectChatUser","REPLIES_USER_ID","messageWithActualBotKeyboard","selectNewestMessageWithBotKeyboardButtons","shouldSuggestStickers","baseEmojiKeywords","BASE_EMOJI_KEYWORD_LANG","botKeyboardMessageId","keyboardMessage","editingMessage","canScheduleUntilOnline","wasOnline","withScheduledButton","shouldSchedule","botKeyboardPlaceholder","keyboardPlaceholder","stickersForEmoji","groupChatMembers","topInlineBotIds","isInlineBotLoading","chatBotCommands","botCommands","dropAreaState","onDropHide","editMessage","saveDraft","clearDraft","setStickerSearchQuery","setGifSearchQuery","closePollModal","addRecentEmoji","sendInlineBotResult","html","setHtml","lastMessageSendTimeSeconds","prevDropAreaState","isCalendarOpen","openCalendar","closeCalendar","scheduledMessageArgs","setScheduledMessageArgs","htmlRef","setAttachments","isBotKeyboardOpen","openBotKeyboard","closeBotKeyboard","isBotCommandMenuOpen","openBotCommandMenu","closeBotCommandMenu","isAttachMenuOpen","openAttachMenu","closeAttachMenu","isSymbolMenuOpen","openSymbolMenu","closeSymbolMenu","isDeleteModalOpen","openDeleteModal","closeDeleteModal","isSymbolMenuLoaded","onSymbolMenuLoadingComplete","isHoverDisabled","disableHover","enableHover","startRecordingVoice","stopRecordingVoice","pauseRecordingVoice","activeVoiceRecording","currentRecordTime","recordButtonRef","mainButtonRef","startRecordTimeRef","setActiveVoiceRecording","setCurrentRecordTime","IS_SAFARI","IS_VOICE_RECORDING_SUPPORTED","voiceRecording","tickVolume","boxShadow","useVoiceRecording","mainButtonState","Edit","Send","Record","canShowCustomSendMenu","isMentionTooltipOpen","closeMentionTooltip","insertMention","mentionFilteredUsers","useMentionTooltip","isInlineBotTooltipOpen","inlineBotId","isInlineBotTooltipGallery","inlineBotSwitchPm","inlineBotResults","closeTooltip","closeInlineBotTooltip","inlineBotHelp","loadMore","loadMoreForInlineBot","markIsOpen","unmarkIsOpen","innerText","getPlainText","queryInlineBot","resetInlineBot","canShowHelp","parseStartWithUsernameString","usernameLowered","prevQuery","prevUsername","useInlineBotTooltip","isBotCommandTooltipOpen","close","closeBotCommandTooltip","filteredBotCommands","botTooltipCommands","setFilteredBotCommands","getFilteredCommands","nextFilteredBotCommands","prepareForRegExp","useBotCommandTooltip","isCustomSendMenuOpen","allowedAttachmentOptions","getAllowedAttachmentOptions","isChatAdmin","slowMode","getChatSlowModeOptions","isStickerTooltipOpen","closeStickerTooltip","isDisabled","cleanHtml","trim","clearStickersForEmoji","IS_EMOJI_SUPPORTED","parseEmojiOnlyString","hasStickers","useStickerTooltip","canSendStickers","isEmojiTooltipOpen","closeEmojiTooltip","filteredEmojis","insertEmoji","useEmojiTooltip","insertTextAndUpdateCursor","selection","getSelection","newHtml","rangeCount","selectionRange","getRangeAt","isSelectionInsideInput","range","deleteContents","fragment","createContextualFragment","lastInsertedNode","lastChild","insertNode","setStartAfter","setEndAfter","collapse","removeAllRanges","addRange","insertHtmlInSelection","dispatchEvent","Event","bubbles","focusEditableElement","removeSymbol","execCommand","tempInput","contentEditable","textLength","createRange","setStart","setEnd","removeChild","deleteLastCharacterOutsideSelection","resetComposer","shouldPreserveInput","stopRecordingVoiceRef","handleEditComplete","editedMessage","hasMessageMedia","useEditing","updateDraft","draftChatId","draftThreadId","runDebouncedForSaveDraft","DRAFT_DEBOUNCE","prevChatId","prevThreadId","prevHtml","handleBlur","useDraft","handlePaste","clipboardData","input","activeElement","EDITABLE_INPUT_MODAL_ID","items","kind","file","getAsFile","pastedText","getData","substring","useClipboardPaste","handleFileSelect","files","handleAppendFiles","handleClearAttachment","handleSend","currentAttachments","record","maxLength","extraLength","textParams","nowSeconds","secondsSinceLastMessage","nextSendDateNotReached","nextSendDate","seconds","secondsRemaining","isSlowMode","handleActivateBotCommandMenu","handleActivateSymbolMenu","handleGifSelect","gif","handleInlineBotSelect","inlineResult","handleBotCommandSelect","handlePollSend","handleSilentSend","handleMessageSchedule","isWhenOnline","restArgs","getTime","handleMessageScheduleUntilOnline","handleCloseCalendar","handleSearchOpen","handleSymbolMenuOpen","handleAllScheduledClick","mainButtonHandler","areVoiceMessagesNotAllowed","canAttachMedia","prevEditedMessage","renderedEditedMessage","scheduledDefaultDate","setSeconds","setMilliseconds","scheduledMaxDate","setFullYear","getFullYear","sendButtonAriaLabel","symbolMenuButtonClassName","onSend","Portal","DropAreaState","withQuick","onHide","onFileSelect","caption","onCaptionUpdate","onFileAppend","onClear","onInsertUserName","filteredUsers","onSelectResult","withUsername","canAttachEmbedLinks","MessageInput","forcedPlaceholder","shouldSetFocus","shouldSuppressFocus","shouldSuppressTextFormatter","onUpdate","onSuppressedFocus","formatVoiceRecordDuration","onStickerSelect","emojis","onEmojiSelect","onPollCreate","onGifSelect","onRemoveSymbol","onSearchOpen","onSilentSend","onScheduleSend","withTimePicker","maxAt","getDayStartAt","isFutureMode","secondButtonLabel","onSubmit","onSecondButtonClick","MobileSearch","MessageSelectToolbar","UnpinAllMessagesModal","PaymentModal","ReceiptModal","CLOSE_ANIMATION_DURATION","isImage","isBlurred","isBackgroundBlurred","background","customBackground","backgroundColor","patternColor","themes","isMobileSearchActive","isReceiptModalOpen","getCanPostInChat","isBotNotStarted","isPinnedMessageList","isScheduledMessageList","currentUserBannedRights","defaultBannedRights","hasPinnedOrAudioMessage","loadUser","closePaymentModal","clearReceipt","setDropAreaState","isFabShown","setIsFabShown","isNotchShown","setIsNotchShown","isUnpinModalOpen","setIsUnpinModalOpen","setIsReady","ANIMATION_LEVEL_MIN","renderingChatId","usePrevDuringAnimation","renderingThreadId","renderingMessageListType","renderingCanPost","renderingHasTools","renderingIsFabShown","visualViewport","documentElement","handleDragEnter","dataTransfer","shouldDrawQuick","handleHideDropArea","handleOpenUnpinModal","closeUnpinModal","handleUnpinAllMessages","handleTabletFocus","customBackgroundValue","settingValue","cacheApi","CUSTOM_BG_CACHE_NAME","Type","useCustomBackground","MASK_IMAGE_DISABLED","messagingDisabledClassName","messageSendingRestrictionReason","getMessageSendingRestrictionReason","composerHiddenScale","toolbarHiddenScale","composerTranslateX","toolbarTranslateX","unpinHiddenScale","toolbarForUnpinHiddenScale","sidePadding","messageListWidth","rightColumnWidth","getMessageListWidth","sendButtonWidth","composerWidth","toolbarWidth","calculateMiddleFooterTransforms","footerClassName","createMessageHash","isMessagingDisabled","onTransitionEnd","propertyName","DARK_THEME_BG_COLOR","LIGHT_THEME_BG_COLOR","onDragEnter","onUnpin","HeaderContent","isProfile","isManagement","messageSearchQuery","stickerSearchQuery","selectCurrentStickerSearch","gifSearchQuery","selectCurrentGifSearch","canAddContact","getCanAddContact","canManage","isColumnOpen","isSearch","isStickerSearch","isGifSearch","isPollResults","isAddingChatMembers","profileState","managementScreen","setLocalTextSearchQuery","searchTextMessagesLocal","toggleManagement","shouldSkipAnimation","addContact","backButtonRef","handleMessageSearchQueryChange","handleStickerSearchQueryChange","handleGifSearchQueryChange","handleAddContact","setShouldSkipTransition","contentKey","ProfileState","Profile","SharedMedia","MemberList","Search","PollResults","StickerSearch","GifSearch","AddingMembers","ManagementScreens","ManageInitial","ManageChatPrivacyType","ManageDiscussion","ManageChannelSubscribers","ManageGroupPermissions","ManageChatAdministrators","ManageGroupRemovedUsers","ManageGroupUserPermissionsCreate","ManageGroupUserPermissions","ManageGroupRecentActions","ManageGroupAdminRights","ManageGroupMembers","renderingContentKey","renderHeaderContent","autoFocusSearch","isBackButton","buttonClassName","useInfiniteScrollForLoadableItems","currentResultType","handleLoadMore","itemIds","getMore","useInfiniteScroll","MEMBERS_SLICE","useInfiniteScrollForSharedMedia","forSharedMediaType","messageIdsRef","getMessageContentIds","reverse","runThrottledForScroll","isScrollingProgrammatically","contactName","getUserFirstOrLastName","deleteChatMember","handleDeleteChatMember","Modal","onEnter","TABS","buildInfiniteScrollItemSelector","resultType","mediaSearchType","isGroup","hasMembersTab","areMembersHidden","canViewMembers","canAddMembers","getHasAdminRight","canDeleteMembers","hasCommonChatsTab","resolvedUserId","commonChatIds","onProfileStateChange","setLocalMediaSearchType","loadMoreMembers","loadCommonChats","searchMediaMessagesLocal","loadProfilePhotos","setActiveTab","deletingUserId","setDeletingUserId","tabType","noProfileInfo","searchMessages","sortUserIds","sortChatIds","memberViewportIds","getMoreMembers","noProfileInfoForMembers","commonChatViewportIds","getMoreCommonChats","noProfileInfoForCommonChats","mediaViewportIds","getMoreMedia","noProfileInfoForMedia","documentViewportIds","getMoreDocuments","noProfileInfoForDocuments","linkViewportIds","getMoreLinks","noProfileInfoForLinks","audioViewportIds","getMoreAudio","noProfileInfoForAudio","voiceViewportIds","getMoreVoices","noProfileInfoForVoices","useProfileViewportIds","prevTabType","tabsEl","prevProfileState","determineProfileState","tabListEl","useProfileState","applyTransitionFix","releaseTransitionFix","transitionElSelector","setMinHeight","transitionEl","minHeight","overflowY","scrollBarWidth","clientWidth","marginRight","useTransitionFixes","cacheBuster","resetCacheBuster","setCacheBuster","useCacheBuster","handleTransitionStop","handleNewMemberDialogOpen","handleSelectMedia","handlePlayAudio","handleMemberClick","handleMessageFocus","handleDeleteMembersModalClose","renderingDelay","isFirstTab","SLIDE_TRANSITION_DURATION","canRenderContents","renderSharedMedia","noSpinner","NothingFound","Media","withDate","smaller","onDateClick","WebLink","onMessageClick","getSenderName","ListItem","teactOrderKey","contextActions","memberId","handler","forceShowSelf","InfiniteScroll","itemSelector","sensitiveArea","PROFILE_SENSITIVE_AREA","preloadBackwards","noScrollRestoreOnTop","noFastList","onLoadMore","ProfileInfo","ChatExtra","renderProfileInfo","shouldRestoreHeight","onStart","onStop","big","FloatingActionButton","RightSearch","Management","localContactIds","isSearching","onNextStep","setUserSearchQuery","selectedMemberIds","setSelectedMemberIds","noPickerScrollRestore","member","handleFilterChange","displayedIds","foundContactIds","fullName","getUserFullName","contactId","canBeInvitedToGroup","handleNextStep","Picker","selectedIds","filterValue","filterPlaceholder","searchInputId","onSelectedIdsChange","onFilterChange","noScrollRestore","MAIN_SCREENS_COUNT","RightColumnContent","MANAGEMENT_SCREENS_COUNT","blurSearchInput","areActiveChatsLoaded","selectAreActiveChatsLoaded","selectRightColumnContentKey","currentProfileUserId","selectedId","isChatSelected","toggleChatInfo","closePollResults","addChatMembers","setProfileState","setManagementScreen","selectedChatMemberId","setSelectedChatMemberId","isPromotedByCurrentUser","setIsPromotedByCurrentUser","isScrolledDown","isOverlaying","shouldScrollUp","handleSelectChatMember","isPromoted","handleAppendingChatMembers","onChatMemberSelect","prevContentKey","MediaViewer","download","click","startedDownloads","downloadHash","getMessageContentFilename","Notifications","Dialogs","ForwardPicker","SafeLinkModal","HistoryCalendar","notificationInterval","DEBUG_isLogged","updateIcon","asUnread","updatePageTitle","nextTitle","wasTimeFormatSetManually","isMediaViewerOpen","selectIsMediaViewerOpen","isForwardModalOpen","selectIsForwardModalOpen","hasNotifications","hasDialogs","audioOrigin","isHistoryCalendarOpen","isServiceChatReady","loadNotificationSettings","loadNotificationExceptions","updateIsOnline","loadTopInlineBots","loadEmojiKeywords","loadCountryList","ensureTimeFormat","checkVersionNotification","LOCATION_HASH","decodeURIComponent","middleColumnTransitionClassNames","rightColumnTransitionClassNames","prevIsLeftColumnShown","dispatchHeavyAnimationEnd","waitForTransitionEnd","prevIsRightColumnShown","initialUnread","clearInterval","setInterval","INACTIVE_MARKER","newUnread","PAGE_TITLE","handleStickerSetModalClose","stopEvent","IS_PWA","usePreventPinchZoomGesture","onDrop","onDragOver","DownloadManager","initApi"],"sourceRoot":""} |