telegram-tt/dist/0.a8b862c02078ad50eb28.js.map
Alexander Zinchuk d22e46ee51 [Build]
2021-06-12 20:37:48 +03:00

1 line
377 KiB
Plaintext
Raw Blame History

This file contains ambiguous Unicode characters

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

{"version":3,"sources":["webpack:///./src/components/ui/ListItem.tsx","webpack:///./src/hooks/useIntersectionObserver.ts","webpack:///./src/hooks/useMedia.ts","webpack:///./src/components/common/PrivateChatInfo.tsx","webpack:///./src/components/ui/Modal.tsx","webpack:///./src/util/trapFocus.ts","webpack:///./src/components/ui/Transition.tsx","webpack:///./src/components/common/Avatar.tsx","webpack:///./src/components/ui/InfiniteScroll.tsx","webpack:///./src/hooks/useTransitionForMedia.ts","webpack:///./src/components/common/helpers/mediaDimensions.ts","webpack:///./src/components/common/AnimatedSticker.tsx","webpack:///./src/components/ui/ConfirmDialog.tsx","webpack:///./src/components/common/NothingFound.tsx","webpack:///./src/hooks/useHistoryBack.ts","webpack:///./src/components/right/hooks/useAsyncRendering.ts","webpack:///./src/hooks/useMediaWithDownloadProgress.ts","webpack:///./src/components/ui/ProgressSpinner.tsx","webpack:///./src/components/ui/Portal.ts","webpack:///./src/components/common/GroupChatInfo.tsx","webpack:///./src/util/fastSmoothScroll.ts","webpack:///./src/components/ui/Radio.tsx","webpack:///./src/components/ui/RadioGroup.tsx","webpack:///./src/hooks/useInfiniteScroll.ts","webpack:///./src/components/common/AnimatedEmoji.tsx","webpack:///./src/util/focusEditableElement.ts","webpack:///./src/hooks/useBackgroundMode.ts","webpack:///./src/util/captureEvents.ts","webpack:///./src/components/common/VerifiedIcon.tsx","webpack:///./src/util/cycleRestrict.ts","webpack:///./src/hooks/useCurrentOrPrev.ts","webpack:///./src/util/safePlay.ts","webpack:///./src/hooks/useBuffering.ts","webpack:///./src/components/middle/composer/helpers/parseMessageInput.ts","webpack:///./src/components/middle/composer/DropTarget.tsx","webpack:///./src/components/middle/composer/DropArea.tsx","webpack:///./src/components/common/PickerSelectedItem.tsx","webpack:///./src/util/fastSmoothScrollHorizontal.ts","webpack:///./src/hooks/useHorizontalScroll.ts","webpack:///./src/hooks/useEnsureMessage.ts","webpack:///./src/hooks/useContextMenuHandlers.ts","webpack:///./src/components/common/helpers/renderMessageText.tsx","webpack:///./src/hooks/useVideoCleanup.ts","webpack:///./src/util/clipboard.ts","webpack:///./src/components/ui/SearchInput.tsx","webpack:///./src/util/resetScroll.ts","webpack:///./src/components/common/TypingStatus.tsx","webpack:///./src/components/common/DeleteChatModal.tsx","webpack:///./src/util/patchSafariProgressiveAudio.ts","webpack:///./src/hooks/useLayoutEffectWithPrevDeps.ts","webpack:///./src/components/common/Document.tsx","webpack:///./src/components/common/StickerSetModal.async.tsx","webpack:///./src/hooks/useCanvasBlur.ts","webpack:///./src/lib/fastBlur.js","webpack:///./src/components/middle/composer/TextFormatter.tsx","webpack:///./src/components/common/Media.tsx","webpack:///./src/components/common/Audio.tsx","webpack:///./src/util/waveform.ts","webpack:///./src/components/common/helpers/waveform.ts","webpack:///./src/components/ui/Tab.tsx","webpack:///./src/components/ui/TabList.tsx","webpack:///./src/util/getReadableErrorText.ts","webpack:///./src/hooks/useChatContextActions.ts","webpack:///./src/components/common/LastMessageMeta.tsx","webpack:///./src/components/common/MessageOutgoingStatus.tsx","webpack:///./src/hooks/useContextMenuPosition.ts","webpack:///./src/components/ui/ShowTransition.tsx","webpack:///./src/hooks/usePrevDuringAnimation.ts","webpack:///./src/hooks/useAudioPlayer.ts","webpack:///./src/util/audioPlayer.ts","webpack:///./src/util/download.ts","webpack:///./src/components/common/File.tsx","webpack:///./src/components/ui/Notification.tsx","webpack:///./src/components/middle/composer/helpers/selection.ts","webpack:///./src/components/middle/composer/hooks/useEmojiTooltip.ts","webpack:///./src/components/middle/composer/EmojiTooltip.async.tsx","webpack:///./src/components/middle/composer/MessageInput.tsx","webpack:///./src/components/common/WebLink.tsx","webpack:///./src/components/left/main/hooks/useChatAnimationType.ts","webpack:///./src/components/left/main/Badge.tsx","webpack:///./src/components/left/main/Chat.tsx","webpack:///./src/components/left/main/ChatList.tsx","webpack:///./src/components/middle/composer/hooks/useMentionTooltip.ts","webpack:///./src/components/middle/composer/helpers/searchUserName.ts","webpack:///./src/hooks/useBlur.ts","webpack:///./src/hooks/useBlurSync.ts"],"names":["ListItem","props","ref","buttonRef","icon","className","style","children","disabled","ripple","narrow","inactive","focus","destructive","multiline","isStatic","contextActions","onClick","containerRef","useRef","isContextMenuOpen","contextMenuPosition","handleBeforeContextMenu","handleContextMenu","handleContextMenuClose","handleContextMenuHide","useContextMenuHandlers","getTriggerElement","useCallback","current","getRootElement","closest","getMenuElement","querySelector","positionX","positionY","menuStyle","useContextMenuPosition","handleClick","e","handleMouseDown","IS_TOUCH_ENV","button","lang","useLang","fullClassName","buildClassName","dir","isRtl","undefined","role","tabIndex","onMouseDown","onContextMenu","isOpen","autoClose","onClose","onCloseAnimationEnd","map","action","key","title","handler","useIntersectionObserver","rootRef","throttleMs","debounceMs","shouldSkipFirst","margin","threshold","isDisabled","rootCallback","controllerRef","rootCallbackRef","isFrozenRef","onUnfreezeRef","freeze","unfreeze","useHeavyAnimationCheck","useEffect","observer","disconnect","callbacks","clear","observe","target","targetCallback","Map","entriesAccumulator","observerCallbackSync","entries","Array","from","values","forEach","entry","callback","get","scheduler","throttle","debounce","observerCallback","IntersectionObserver","set","root","rootMargin","initController","controller","delete","unobserve","useOnIntersect","targetRef","useIsIntersecting","isIntersecting","setIsIntersecting","useState","mediaHash","noLoad","mediaFormat","ApiMediaFormat","BlobUrl","cacheBuster","delay","mediaData","mediaLoader","forceUpdate","useForceUpdate","startedAt","Date","now","then","spentTime","setTimeout","memo","withGlobal","global","userId","forceShowSelf","lastSyncTime","user","selectUser","isSavedMessages","isSelf","areMessagesLoaded","Boolean","selectChatMessages","setGlobal","actions","pick","typingStatus","avatarSize","status","withMediaViewer","withUsername","withFullInfo","withUpdatingStatus","noStatusOrTyping","noRtl","loadFullUser","openMediaViewer","id","fullName","getUserFullName","handleAvatarViewerOpen","hasPhoto","stopPropagation","avatarOwnerId","origin","MediaViewerOrigin","ProfileAvatar","MiddleHeaderAvatar","size","renderText","isVerified","isUserOnline","username","getUserStatus","Modal","header","hasCloseButton","noBackdrop","onEnter","isClosedWithHistory","setIsClosedWithHistory","noAnimations","setNoAnimations","isFirstRender","setIsFirstRender","shouldRender","transitionClassNames","useShowTransition","modalRef","captureKeyboardListeners","onEsc","element","handleKeyDown","preventDefault","focusableElements","querySelectorAll","length","currentFocusedIndex","findIndex","em","isSameNode","document","activeElement","newFocusedIndex","shiftKey","addEventListener","removeEventListener","trapFocus","useHistoryBack","event","noAnimation","previousHistoryState","type","useOnChange","HistoryWrapper","pushState","back","useEffectWithPrevDeps","prevIsOpen","body","classList","toggle","dispatchHeavyAnimationEvent","remove","Portal","Button","round","color","ariaLabel","ANIMATION_DURATION","slide","fade","IS_MOBILE_SCREEN","reveal","CLEANED_UP","Symbol","animationLevel","settings","byKey","activeKey","name","direction","renderCount","shouldRestoreHeight","shouldCleanup","onStart","onStop","rendersRef","prevActiveKey","usePrevious","activateTimeoutRef","activeKeyChanged","useLayoutEffect","cleanup","container","childElements","add","childNodes","clearTimeout","isBackwards","keys","Object","Number","prevActiveIndex","indexOf","activeIndex","node","i","HTMLElement","width","offsetWidth","scrollBy","left","behavior","ANIMATION_END_DELAY","requestAnimationFrame","window","scrollLeft","height","clientHeight","flexBasis","renders","contents","fill","render","chat","text","withOnlineStatus","isDeleted","isDeletedUser","imageHash","getChatAvatarHash","dataUri","useMedia","DataUri","shouldRenderFullMedia","useTransitionForMedia","content","src","alt","decoding","userFullName","getFirstLetters","getChatTitle","isChatPrivate","isOnline","getUserColorKey","senderId","data-test-sender-id","IS_TEST","InfiniteScroll","onLoadMore","onScroll","onKeyDown","items","itemSelector","preloadBackwards","sensitiveArea","noScrollRestore","noScrollRestoreOnTop","noFastList","stateRef","loadMoreBackwards","loadMoreForwards","useMemo","LoadMoreDirection","Backwards","Forwards","scrollHeight","state","newScrollTop","listItemElements","currentAnchor","includes","scrollTop","getBoundingClientRect","top","currentAnchorTop","nextAnchor","resetScroll","isScrollTopJustUpdated","handleScroll","listLength","offsetHeight","isNearTop","offsetTop","isNearBottom","isUpdated","nextAnchorTop","newAnchorTop","offsetParent","teactFastList","SPEED","fast","slow","speed","noAnimate","isMediaLoaded","willAnimate","shouldRenderThumb","setShouldRenderThumb","MEDIA_VIEWER_MEDIA_QUERY","REM","parseInt","getComputedStyle","documentElement","fontSize","ROUND_VIDEO_DIMENSIONS","AVATAR_FULL_DIMENSIONS","DEFAULT_MEDIA_DIMENSIONS","cachedMaxWidth","getAvailableWidth","fromOwnMessage","isForwarded","isWebPagePhoto","extraPaddingRem","regularMaxWidth","Math","min","floor","innerWidth","getMaxMessageWidthRem","calculateDimensionsForMessageMedia","isGif","aspectRatio","calculateDimensions","getAvailableHeight","getMediaViewerAvailableDimensions","withFooter","isVideo","mql","matchMedia","windowWidth","windowHeight","windowSize","occupiedHeightRem","matches","calculateInlineImageDimensions","photo","getPhotoInlineDimensions","calculateVideoDimensions","video","getVideoDimensions","getPictogramDimensions","getDocumentThumbnailDimensions","smaller","getStickerDimensions","sticker","baseWidth","STICKER_SIZE_INLINE_MOBILE_FACTOR","STICKER_SIZE_INLINE_DESKTOP_FACTOR","calculatedHeight","calculateMediaViewerDimensions","availableWidth","availableHeight","mediaWidth","mediaHeight","calculatedWidth","lottiePromise","RLottie","async","ensureLottie","default","animationData","play","playSegment","noLoop","quality","isLowPriority","onLoad","animation","setAnimation","wasPlaying","isFrozen","playRef","playSegmentRef","exec","newAnimation","setSpeed","fastRaf","destroy","playAnimation","shouldRestart","goToAndPlay","pauseAnimation","pause","freezeAnimation","isPlaying","unfreezeAnimation","unfreezeAnimationOnRaf","useBackgroundMode","textParts","confirmLabel","confirmHandler","confirmIsDestructive","isButtonsInOneRow","split","textPart","isText","description","isEdge","onTouchStart","x","touches","pageX","onTouchEnd","onPopState","isHistoryChangedByUser","states","IS_IOS","console","log","useAsyncRendering","dependencies","shouldRenderRef","timeoutRef","isStreaming","Stream","IS_PROGRESSIVE_SUPPORTED","Progressive","downloadProgress","setDownloadProgress","startedAtRef","handleProgress","progress","RADIUSES","s","m","l","xl","square","transparent","noCross","radius","circleRadius","STROKE_WIDTH","borderRadius","circumference","PI","svg","firstElementChild","strokeDashOffset","max","setAttribute","toString","innerHTML","containerId","elementRef","createElement","appendChild","TeactDOM","removeChild","chatId","selectChat","onlineCount","selectChatOnlineCount","withChatType","loadFullChat","isSuperGroup","isChatSuperGroup","isMin","isRestricted","getChatTypeString","handle","groupStatus","chatTypeString","membersCount","getGroupStatus","onlineStatus","renderStatusOrTyping","isAnimating","fastSmoothScroll","position","maxDistance","forceDirection","forceDuration","forceCurrentContainerHeight","FocusDirection","Static","scrollIntoView","block","offset","Up","Down","elementTop","elementHeight","containerHeight","targetContainerHeight","dataset","normalHeight","path","remainingPath","duration","abs","startAt","animateSingle","t","currentPath","transition","scrollWithJs","isAnimatingScroll","label","subLabel","value","checked","hidden","isLoading","onChange","Spinner","options","selected","loadingOption","handleChange","currentTarget","option","getViewportSlice","sourceIds","offsetId","listSlice","index","indexForDirection","to","newViewportIds","slice","areSomeLocal","areAllLocal","listIds","forceFullPreload","lastParamsRef","viewportIdsRef","prevListIds","prevIsDisabled","areSortedArraysEqual","viewportIds","getMore","AnimatedEmoji","isInline","observeIntersection","isAnimationLoaded","markAnimationLoaded","useFlag","localMediaHash","previewBlobUrl","Lottie","playKey","setPlayKey","String","random","STICKER_SIZE_TWO_FA","focusEditableElement","force","selection","getSelection","range","createRange","lastChild","nodeValue","setStart","removeAllRanges","addRange","onBlur","onFocus","hasFocus","SwipeDirection","captureEvents","captureEvent","currentSwipeAxis","hasMoved","onCapture","excludedClosestSelector","onMove","onRelease","pageY","withCursor","dragOffsetX","dragOffsetY","onDrag","onSwipe","xAbs","yAbs","Left","Right","processSwipe","passive","VerifiedIcon","cycleRestrict","useCurrentOrPrev","shouldSkipUndefined","shouldForceCurrent","prev","mediaEl","catch","err","DEBUG","warn","noInitiallyBuffered","isBuffered","setIsBuffered","bufferedProgress","setBufferedProgress","setIsBufferedDebounced","handleBuffering","media","isSafariPatchInProgress","buffered","end","readyState","currentTime","bufferingHandlers","onLoadedData","onPlaying","onLoadStart","onPause","onTimeUpdate","onProgress","checkBuffering","ENTITY_CLASS_BY_NODE_NAME","B","ApiMessageEntityTypes","Bold","STRONG","I","Italic","EM","U","Underline","S","Strike","STRIKE","DEL","CODE","Code","PRE","Pre","BLOCKQUOTE","Blockquote","parseMessageInput","html","fragment","parsedHtml","IS_EMOJI_SUPPORTED","replace","parseMarkdown","innerText","trim","textIndex","recursionDeepness","entities","addEntity","entity","rawText","nodeName","anchor","entityType","MentionName","href","startsWith","Email","Phone","textContent","TextUrl","Url","getEntityTypeFromNode","rawIndex","substring","url","getEntityDataFromNode","push","hasChildNodes","isQuick","onFileSelect","isHovered","markHovered","unmarkHovered","onDrop","onDragEnter","onDragLeave","relatedTarget","toTarget","DropAreaState","withQuick","onHide","hideTimeoutRef","prevWithQuick","captureEscKeyListener","handleFilesDrop","dataTransfer","dt","files","handleQuickFilesDrop","handleDragLeave","fromTarget","onDragOver","chatOrUserId","isMinimized","canClose","clickArg","iconElement","titleText","getUserFirstOrLastName","fastSmoothScrollHorizontal","containerWidth","scrollWidth","animate","scrollTo","deltaX","deltaY","messageId","message","replyOriginForId","loadMessage","getDispatch","loadMessageThrottled","throttled","contextMenuCounter","isMenuDisabled","shouldDisableOnLink","setIsContextMenuOpen","setContextMenuPosition","clientX","y","clientY","timer","clearLongPressTimer","startLongPressTimer","contains","originalEvent","cancelClickOnce","stopImmediatePropagation","emulateContextMenuEvent","renderMessageText","highlight","shouldRenderHqEmoji","formattedText","getMessageText","renderTextWithEntities","organizeEntities","organizedEntityIndexes","Set","organizedEntities","has","organizedEntity","organizeEntity","organizedIndexes","nestedEntities","filter","organizedIndex","shouldRenderAsHtml","renderMessagePart","result","deleteLineBreakAfterPre","organizedEntites","renderEntity","textPartStart","textPartEnd","isLastEntity","renderResult","textBefore","textBeforeLength","substr","entityStartIndex","entityEndIndex","entityContent","nestedEntityContent","nestedIndex","nestedEntity","nestedEntityIndex","nestedResult","nestedEntityEndIndex","newEntity","rawEntityText","renderedContent","join","getLinkUrl","processEntityAsHtml","entityText","BotCommand","handleBotCommandClick","Hashtag","Cashtag","handleHashtagClick","rel","Mention","processEntity","isArray","textAfter","arrayIndex","c","emojiFilter","sendBotCommand","command","setLocalTextSearchQuery","query","searchTextMessagesLocal","useVideoCleanup","videoRef","videoEl","load","CLIPBOARD_ITEM_SUPPORTED","navigator","clipboard","ClipboardItem","textCopyEl","copyTextToClipboard","str","rangeToRestore","rangeCount","getRangeAt","select","execCommand","copyImageToClipboard","imageUrl","canvas","ctx","getContext","imageEl","Image","onload","img","drawImage","toBlob","copyBlobToClipboard","pngBlob","write","error","parentContainerClassName","inputId","focused","placeholder","onReset","inputRef","isInputFocused","markInputFocused","unmarkInputFocused","blur","overflow","typingUser","typingUserName","isPrivateChat","isChatWithSelf","selectIsChatWithSelf","canDeleteForAll","contactName","getPrivateChatUserId","isChannel","isChatChannel","isBasicGroup","isChatBasicGroup","leaveChannel","deleteHistory","deleteChannel","chatTitle","handleDeleteMessageForAll","maxId","lastMessage","shouldDeleteForAll","handleDeleteChat","isCreator","patchSafariProgressiveAudio","audioEl","patchedForSafari","patchForSafariInProgress","paused","once","cb","prevDeps","uploadProgress","withDate","datetime","sender","isSelected","isSelectable","onCancelUpload","onDateClick","extension","getDocumentExtension","fileName","timestamp","isDownloadAllowed","setIsDownloadAllowed","useMediaWithDownloadProgress","getMessageMediaHash","isUploading","isTransferring","transferProgress","getMediaTransferState","hasPreview","getDocumentHasPreview","thumbDataUri","getMessageMediaThumbDataUri","localBlobUrl","previewData","isAllowed","handleDateClick","download","thumbnailDataUri","StickerSetModal","useModuleLoader","Bundles","Extra","useCanvasBlur","withRaf","canvasRef","processBlur","alpha","IS_CANVAS_FILTER_SUPPORTED","RADIUS","fastBlur","mul_table","shg_table","boxBlurCanvasRGB","context","top_x","top_y","iterations","isNaN","imageData","getImageData","pixels","data","rsum","gsum","bsum","p","p1","p2","yp","yi","yw","wm","hm","rad1","r","g","b","mul_sum","shg_sum","vmin","vmax","putImageData","TEXT_FORMAT_BY_TAG_NAME","anchorPosition","selectedRange","linkUrlInputRef","isLinkControlOpen","openLinkControl","closeLinkControl","linkUrl","setLinkUrl","isEditingLink","setIsEditingLink","inputClassName","setInputClassName","selectedTextFormats","setSelectedTextFormats","useVirtualBackdrop","selectedFormats","parentElement","commonAncestorContainer","EDITABLE_INPUT_ID","textFormat","tagName","getSelectedText","getSelectedElement","updateInputStyles","input","getFormatButtonClassName","some","fKey","monospace","strikethrough","handleBoldText","bold","handleItalicText","italic","handleUnderlineText","underline","handleStrikethroughText","replaceWith","handleMonospaceText","handleLinkUrlConfirm","formattedLinkUrl","restoreSelection","KeyK","KeyB","KeyU","KeyI","KeyM","KeyS","code","altKey","ctrlKey","metaKey","linkUrlConfirmClassName","autoComplete","inputMode","idPrefix","mediaBlobUrl","getMessageVideo","formatMediaDuration","MIN_SPIKES","MAX_SPIKES","renderSeekline","playProgress","handleStartSeek","handleSeek","handleStopSeek","onMouseMove","onMouseUp","theme","senderTitle","renderingFor","date","onPlay","onReadMedia","audio","voice","isMediaUnread","isVoice","isSeeking","isActivated","setIsActivated","shouldDownload","getMessageMediaFormat","useBuffering","playPause","setCurrentTime","useAudioPlayer","getMessageKey","getMediaDuration","isMessageLocal","shouldRenderSpinner","spinnerClassNames","handleButtonClick","seekBar","seekHandlers","isOwn","isOwnMessage","renderedWaveform","waveform","fillColor","fillOwnColor","progressFillColor","progressFillOwnColor","durationFactor","spikesCount","decodedWaveform","encoded5bit","bitsCount","valuesCount","bitsData","byteIndex","bitShift","lastByteIndex","lastBitShift","lastValue","decodeWaveform","Uint8Array","spikes","peak","fitCount","newData","springFactor","leftFiller","rightFiller","idx","val","interpolateArray","fillStyle","progressFillStyle","scale","item","globalAlpha","spikeHeight","beginPath","moveTo","arcTo","closePath","roundedRectangle","toDataURL","renderWaveformToDataUri","draggable","renderWaveform","buttonClassNames","showSeekline","contentClassName","ProgressSpinner","getFirstLine","Link","formatPastTimeShort","performer","getSecondLine","formatMediaDateTime","renderAudio","renderVoice","active","badgeCount","isBadgeActive","previousActiveTab","tabRef","tab","indicator","currentIndicator","shiftLeft","offsetLeft","scaleFactor","clientWidth","transform","tabs","activeTab","big","onSwitchTab","useHorizontalScroll","activeTabElement","newLeft","READABLE_ERROR_MESSAGES","CHAT_RESTRICTED","CHAT_WRITE_FORBIDDEN","CHAT_SEND_POLL_FORBIDDEN","CHAT_SEND_STICKERS_FORBIDDEN","CHAT_SEND_GIFS_FORBIDDEN","CHAT_SEND_MEDIA_FORBIDDEN","CHAT_LINK_EXISTS","SLOWMODE_WAIT_X","USER_BANNED_IN_CHANNEL","USER_IS_BLOCKED","YOU_BLOCKED_USER","IMAGE_PROCESS_FAILED","MEDIA_EMPTY","MEDIA_INVALID","PHOTO_EXT_INVALID","PHOTO_INVALID_DIMENSIONS","PHOTO_SAVE_FILE_INVALID","MESSAGE_DELETE_FORBIDDEN","MESSAGE_POLL_CLOSED","MESSAGE_EDIT_TIME_EXPIRED","CHAT_ADMIN_REQUIRED","PINNED_DIALOGS_TOO_MUCH","DIALOG_FILTERS_TOO_MUCH","CHANNEL_PRIVATE","MEDIA_CAPTION_TOO_LONG","ADDRESS_STREET_LINE1_INVALID","ADDRESS_STREET_LINE2_INVALID","ADDRESS_CITY_INVALID","ADDRESS_COUNTRY_INVALID","ADDRESS_POSTCODE_INVALID","ADDRESS_STATE_INVALID","REQ_INFO_NAME_INVALID","REQ_INFO_PHONE_INVALID","REQ_INFO_EMAIL_INVALID","LINK_NOT_MODIFIED","SERVICE_WORKER_DISABLED","CAPTION_TOO_LONG_PLEASE_REMOVE_CHARACTERS","FRESH_RESET_AUTHORISATION_FORBIDDEN","BOTS_TOO_MUCH","BOT_GROUPS_BLOCKED","USERS_TOO_MUCH","USER_CHANNELS_TOO_MUCH","USER_KICKED","USER_NOT_MUTUAL_CONTACT","USER_PRIVACY_RESTRICTED","INVITE_HASH_EMPTY","INVITE_HASH_EXPIRED","INVITE_HASH_INVALID","CHANNELS_TOO_MUCH","USER_ALREADY_PARTICIPANT","getReadableErrorText","isSlowMode","textParams","extraPartIndex","errorMessage","reduce","acc","privateChatUser","handleDelete","folderId","isPinned","toggleChatPinned","updateChatMutedState","toggleChatArchived","toggleChatUnread","actionUnreadMark","unreadCount","hasUnreadMark","actionPin","actionMute","isMuted","actionArchive","isChatArchived","getCanDeleteChat","outgoingStatus","Keys","extraPaddingX","extraTopPadding","setPositionX","setPositionY","setStyle","triggerEl","emptyRect","menuEl","rootEl","triggerRect","menuRect","rootRect","ShowTransition","isCustom","prevChildren","fromChildrenRef","usePrevDuringAnimation","isCurrentPresent","isPrevPresent","trackId","originalDuration","handlers","onInit","shouldPlay","onForcePlay","noPlaylist","setIsPlaying","isPlayingSync","setPlayProgress","register","eventName","proxy","isFinite","prevShouldPlay","prevSrc","audioProxy","tracks","currentTrackId","queue","stopCurrentAudio","currentTrack","Audio","handleEvent","nextTrackId","openAudioPlayer","parseMessageKey","nextTrack","safePlay","Proxy","createAudio","preload","IS_SAFARI","time","shouldRemoveFromQueue","track","h","filename","link","click","shouldSpinnerRender","getColorFromExtension","sizeString","getFileSizeString","onDismiss","setIsOpen","timerRef","closeAndDismiss","handleMouseEnter","handleMouseLeave","onMouseEnter","onMouseLeave","isSelectionInsideInput","selectionRange","parentNode","emojiDataPromise","emojiRawData","emojiData","RE_NOT_EMOJI_SEARCH","useEmojiTooltip","recentEmojiIds","onUpdateHtml","markIsOpen","unmarkIsOpen","emojiIds","setEmojiIds","filteredEmojis","setFilteredEmojis","recentEmojis","emojiId","emojis","uncompressEmoji","ensureEmojiData","tempEl","lastSymbol","lastWord","pop","test","toLowerCase","getEmojiCode","matched","names","find","insertEmoji","textEmoji","atIndex","lastIndexOf","messageInput","getElementById","isEmojiTooltipOpen","closeEmojiTooltip","EmojiTooltip","MAX_INPUT_HEIGHT","currentChatId","threadId","selectCurrentMessageList","messageSendKeyCombo","replyingToId","selectReplyingToId","noTabCapture","isPollModalOpen","payment","isPaymentModalOpen","editableInputId","shouldSetFocus","shouldSupressFocus","shouldSupressTextFormatter","onUpdate","onSupressedFocus","onSend","editLastMessage","replyToNextMessage","cloneRef","isContextMenuOpenRef","isTextFormatterOpen","openTextFormatter","closeTextFormatter","textFormatterAnchorPosition","setTextFormatterAnchorPosition","setSelectedRange","updateInputHeight","useLayoutEffectWithPrevDeps","prevHtml","focusInput","handleCloseTextFormatter","empty","clearSelection","checkSelection","selectedText","parseEmojiOnlyString","START_TO_END","selectionRect","inputRect","willSend","clone","currentHeight","newHeight","transitionDuration","captureFirstTab","onTab","supressFocus","contentEditable","targetIndexDelta","handleKeyUp","IS_ANDROID","closeContextMenuMouseListener","closeContextMenuKeyListener","handleMouseUp","onTouchCancel","onMessageClick","linkData","getMessageWebPage","getFirstLinkInMessage","domain","messageText","getMessageSummaryText","siteName","handleMessageClick","displayUrl","truncatedDescription","trimText","data-initial","ChatAnimationTypes","isShown","renderContent","unreadMentionsCount","formatIntegerCompact","FolderTypeToListType","replyToMessageId","isOutgoing","lastMessageSender","lastMessageAction","getMessageAction","actionTargetMessage","selectChatMessage","targetUserId","actionTargetUserId","targetChatId","actionTargetChatId","privateChatUserId","messageListType","selectIsChatMuted","selectNotifySettings","selectNotifyExceptions","lastMessageOutgoingStatus","selectOutgoingStatus","actionTargetUser","draft","selectDraft","MAIN_THREAD_ID","orderDiff","animationType","openChat","focusLastMessage","isDeleteModalOpen","openDeleteModal","closeDeleteModal","isAction","isActionMessage","useEnsureMessage","mediaThumbnail","getMessageSticker","isRoundVideo","getMessageRoundVideo","Opacity","opacity","Move","useChatContextActions","Avatar","LastMessageMeta","TypingStatus","actionOrigin","renderActionMessageText","asPlain","senderName","getMessageSenderName","blobUrl","renderMessageSummary","renderLastMessageOrTyping","DeleteChatModal","folderType","chats","byId","chatsById","orderedPinnedIds","users","usersById","currentThreadId","listType","chatFolder","selectChatFolder","isInDiscussionThread","notifySettings","notifyExceptions","noChatsText","isActive","loadMoreChats","preloadTopChatMessages","currentListIds","currentPinnedIds","prepareFolderListIds","orderById","orderedIds","newChatArrays","prepareChatList","singleList","pinnedChats","otherChats","newOrderedIds","prevOrderById","orderDiffById","mapValues","order","Infinity","loadMoreOfType","useInfiniteScroll","CHAT_LIST_SLICE","ALL_CHATS_PRELOAD_DISABLED","chatArrays","getAnimationType","movesUp","movesDown","orderDiffIds","numberOfUp","numberOfDown","None","useChatAnimationType","digit","match","nextId","viewportOffset","pinnedOffset","CHAT_HEIGHT_PX","teactOrderKey","getChatOrder","renderChats","Loading","RE_NOT_USERNAME_SEARCH","useMentionTooltip","canSuggestMembers","groupChatMembers","currentUserId","currentFilter","setCurrentFilter","filteredMembers","setFilteredMembers","getFilteredMembers","usernameLowered","fullNameLowered","filterLowered","searchWords","searchUserName","usernameFilter","getUsernameFilter","membersToMention","insertMention","forceFocus","insertedHtml","isMentionTooltipOpen","mentionFilter","closeMentionTooltip","mentionFilteredMembers","cache","useBlurSync","blurredRef","isChanged","imgToCanvas","blurredAsync","blurredDataUri","useBlur"],"mappings":"wGACA,kFA2LeA,IAjJiBC,IAC9B,MAAM,IACJC,EADI,UAEJC,EAFI,KAGJC,EAHI,UAIJC,EAJI,MAKJC,EALI,SAMJC,EANI,SAOJC,EAPI,OAQJC,EARI,OASJC,EATI,SAUJC,EAVI,MAWJC,EAXI,YAYJC,EAZI,UAaJC,EAbI,SAcJC,EAdI,eAeJC,EAfI,QAgBJC,GACEhB,EAGJ,IAAIiB,EAAeC,YAAuB,MACtCjB,IACFgB,EAAehB,GAGjB,MAAM,kBACJkB,EADI,oBACeC,EADf,wBAEJC,EAFI,kBAEqBC,EAFrB,uBAGJC,EAHI,sBAGoBC,GACtBC,YAAuBR,GAAeF,GAEpCW,EAAoBC,YAA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,IAAIsM,QAAWtP,GACvE6a,EAAa3c,cACb0G,EAAcC,cAqCpB,OAnCIgW,EAAWjc,SAAWyC,IACxB+L,aAAayN,EAAWjc,SACxBic,EAAWjc,aAAUoB,GAGvB8B,YAAU,KACR,IAAKwN,GAAWmwC,EAAW7gD,SAAWyC,EACpC,OAGF,MAAM2yB,EAAM,IAAIF,MAEhBE,EAAID,OAAS,KACX,MAAML,EAASisB,YAAY3rB,GAC3ByF,YAAS/F,EAAOE,WAAW,MAAO,EAAG,EAAGF,EAAO3lB,MAAO2lB,EAAOllB,OAzBpD,EACI,GAyBb,MAAMqxC,EAAiBnsB,EAAO2Q,YAE9Bob,EAAW7gD,QAAUihD,EACrBj7C,IAEI26C,EAAM73C,MA7BO,KA8Bf63C,EAAMr9C,QAERq9C,EAAMj8C,IAAIgM,EAASuwC,IAGjBp7C,EACFoW,EAAWjc,QAAU0P,OAAOnJ,WAAW,KACrC6uB,EAAIpkB,IAAMN,GACT7K,GAEHuvB,EAAIpkB,IAAMN,GAEX,CAACA,EAAS7K,EAAOG,EAAavD,IAE1Bo+C,EAAW7gD,QCdGkhD,CAAQxwC,QAAWtP,EAAW+F,QAAQ05C,EAAW7gD,UAEtE,OAAO6gD,EAAW7gD,UAAa8gD,GAAaE,GAAiBtwC,QAAWtP,I","file":"0.a8b862c02078ad50eb28.js","sourcesContent":["import { RefObject } from 'react';\nimport React, { FC, useRef, useCallback } from '../../lib/teact/teact';\n\nimport { IS_TOUCH_ENV } from '../../util/environment';\nimport buildClassName from '../../util/buildClassName';\nimport useContextMenuHandlers from '../../hooks/useContextMenuHandlers';\nimport useContextMenuPosition from '../../hooks/useContextMenuPosition';\nimport useLang from '../../hooks/useLang';\n\nimport RippleEffect from './RippleEffect';\nimport Menu from './Menu';\nimport MenuItem from './MenuItem';\n\nimport './ListItem.scss';\n\ntype OnClickHandler = (e: React.MouseEvent<HTMLDivElement>) => void;\n\ntype MenuItemContextAction = {\n title: string;\n icon: string;\n destructive?: boolean;\n handler?: () => void;\n};\n\ntype OwnProps = {\n ref?: RefObject<HTMLDivElement>;\n buttonRef?: RefObject<HTMLDivElement>;\n icon?: string;\n className?: string;\n style?: string;\n children: any;\n disabled?: boolean;\n ripple?: boolean;\n narrow?: boolean;\n inactive?: boolean;\n focus?: boolean;\n destructive?: boolean;\n multiline?: boolean;\n isStatic?: boolean;\n contextActions?: MenuItemContextAction[];\n onClick?: OnClickHandler;\n};\n\nconst ListItem: FC<OwnProps> = (props) => {\n const {\n ref,\n buttonRef,\n icon,\n className,\n style,\n children,\n disabled,\n ripple,\n narrow,\n inactive,\n focus,\n destructive,\n multiline,\n isStatic,\n contextActions,\n onClick,\n } = props;\n\n // eslint-disable-next-line no-null/no-null\n let containerRef = useRef<HTMLDivElement>(null);\n if (ref) {\n containerRef = ref;\n }\n\n const {\n isContextMenuOpen, contextMenuPosition,\n handleBeforeContextMenu, handleContextMenu,\n handleContextMenuClose, handleContextMenuHide,\n } = useContextMenuHandlers(containerRef, !contextActions);\n\n const getTriggerElement = useCallback(() => containerRef.current, []);\n\n const getRootElement = useCallback(\n () => containerRef.current!.closest('.custom-scroll'),\n [],\n );\n\n const getMenuElement = useCallback(\n () => containerRef.current!.querySelector('.ListItem-context-menu .bubble'),\n [],\n );\n\n const { positionX, positionY, style: menuStyle } = useContextMenuPosition(\n contextMenuPosition,\n getTriggerElement,\n getRootElement,\n getMenuElement,\n );\n\n const handleClick = useCallback((e: React.MouseEvent<HTMLDivElement, MouseEvent>) => {\n if (disabled || !onClick) {\n return;\n }\n onClick(e);\n }, [disabled, onClick]);\n\n const handleMouseDown = useCallback((e: React.MouseEvent<HTMLDivElement, MouseEvent>) => {\n if (inactive || IS_TOUCH_ENV) {\n return;\n }\n if (contextActions && (e.button === 2 || !onClick)) {\n handleBeforeContextMenu(e);\n }\n if (e.button === 0) {\n if (!onClick) {\n handleContextMenu(e);\n } else {\n handleClick(e);\n }\n }\n }, [inactive, contextActions, onClick, handleBeforeContextMenu, handleContextMenu, handleClick]);\n\n const lang = useLang();\n\n const fullClassName = buildClassName(\n 'ListItem',\n className,\n !isStatic && 'no-selection',\n ripple && 'has-ripple',\n narrow && 'narrow',\n disabled && 'disabled',\n inactive && 'inactive',\n contextMenuPosition && 'has-menu-open',\n focus && 'focus',\n destructive && 'destructive',\n multiline && 'multiline',\n isStatic && 'is-static',\n );\n\n return (\n <div\n ref={containerRef}\n className={fullClassName}\n dir={lang.isRtl ? 'rtl' : undefined}\n // @ts-ignore\n style={style}\n >\n <div\n className=\"ListItem-button\"\n role=\"button\"\n ref={buttonRef}\n tabIndex={0}\n onClick={!inactive && IS_TOUCH_ENV ? handleClick : undefined}\n onMouseDown={handleMouseDown}\n onContextMenu={!inactive && contextActions ? handleContextMenu : undefined}\n >\n {icon && (\n <i className={`icon-${icon}`} />\n )}\n {multiline && (<div className=\"multiline-item\">{children}</div>)}\n {!multiline && children}\n {!disabled && !inactive && ripple && (\n <RippleEffect />\n )}\n </div>\n {contextActions && contextMenuPosition !== undefined && (\n <Menu\n isOpen={isContextMenuOpen}\n positionX={positionX}\n positionY={positionY}\n style={menuStyle}\n className=\"ListItem-context-menu\"\n autoClose\n onClose={handleContextMenuClose}\n onCloseAnimationEnd={handleContextMenuHide}\n >\n {contextActions.map((action) => (\n <MenuItem\n key={action.title}\n icon={action.icon}\n destructive={action.destructive}\n disabled={!action.handler}\n onClick={action.handler}\n >\n {action.title}\n </MenuItem>\n ))}\n </Menu>\n )}\n </div>\n );\n};\n\nexport default ListItem;\n","import { RefObject } from 'react';\nimport {\n useEffect, useRef, useCallback, useState,\n} from '../lib/teact/teact';\n\nimport { throttle, debounce } from '../util/schedulers';\nimport useHeavyAnimationCheck from './useHeavyAnimationCheck';\n\ntype TargetCallback = (entry: IntersectionObserverEntry) => void;\ntype RootCallback = (entries: IntersectionObserverEntry[]) => void;\ntype ObserveCleanup = NoneToVoidFunction;\nexport type ObserveFn = (target: HTMLElement, targetCallback?: TargetCallback) => ObserveCleanup;\n\ninterface IntersectionController {\n observer: IntersectionObserver;\n callbacks: Map<HTMLElement, TargetCallback>;\n}\n\ninterface Response {\n observe: ObserveFn;\n freeze: NoneToVoidFunction;\n unfreeze: NoneToVoidFunction;\n}\n\nexport function useIntersectionObserver({\n rootRef,\n throttleMs,\n debounceMs,\n shouldSkipFirst,\n margin,\n threshold,\n isDisabled,\n}: {\n rootRef: RefObject<HTMLDivElement>;\n throttleMs?: number;\n debounceMs?: number;\n shouldSkipFirst?: boolean;\n margin?: number;\n threshold?: number | number[];\n isDisabled?: boolean;\n}, rootCallback?: RootCallback): Response {\n const controllerRef = useRef<IntersectionController>();\n const rootCallbackRef = useRef<RootCallback>();\n const isFrozenRef = useRef<boolean>();\n const onUnfreezeRef = useRef<NoneToVoidFunction>();\n\n rootCallbackRef.current = rootCallback;\n\n const freeze = useCallback(() => {\n isFrozenRef.current = true;\n }, []);\n\n const unfreeze = useCallback(() => {\n isFrozenRef.current = false;\n\n if (onUnfreezeRef.current) {\n onUnfreezeRef.current();\n onUnfreezeRef.current = undefined;\n }\n }, []);\n\n useHeavyAnimationCheck(freeze, unfreeze);\n\n useEffect(() => {\n if (isDisabled) {\n return undefined;\n }\n\n return () => {\n if (controllerRef.current) {\n controllerRef.current.observer.disconnect();\n controllerRef.current.callbacks.clear();\n controllerRef.current = undefined;\n }\n };\n }, [isDisabled]);\n\n function initController() {\n const callbacks = new Map();\n const entriesAccumulator = new Map<Element, IntersectionObserverEntry>();\n const observerCallbackSync = () => {\n const entries = Array.from(entriesAccumulator.values());\n\n entries.forEach((entry: IntersectionObserverEntry) => {\n const callback = callbacks.get(entry.target);\n if (callback) {\n callback!(entry, entries);\n }\n });\n\n if (rootCallbackRef.current) {\n rootCallbackRef.current(entries);\n }\n\n entriesAccumulator.clear();\n };\n const scheduler = throttleMs ? throttle : debounceMs ? debounce : undefined;\n const observerCallback = scheduler\n ? scheduler(observerCallbackSync, (throttleMs || debounceMs)!, !shouldSkipFirst)\n : observerCallbackSync;\n const observer = new IntersectionObserver(\n (entries) => {\n entries.forEach((entry) => {\n entriesAccumulator.set(entry.target, entry);\n });\n\n if (isFrozenRef.current) {\n onUnfreezeRef.current = () => {\n observerCallback();\n };\n } else {\n observerCallback();\n }\n },\n {\n root: rootRef.current,\n rootMargin: margin ? `${margin}px` : undefined,\n threshold,\n },\n );\n\n controllerRef.current = { observer, callbacks };\n }\n\n const observe = useCallback((target, targetCallback) => {\n if (!controllerRef.current) {\n initController();\n }\n\n const controller = controllerRef.current!;\n controller.observer.observe(target);\n\n if (targetCallback) {\n controller.callbacks.set(target, targetCallback);\n }\n\n return () => {\n if (targetCallback) {\n controller.callbacks.delete(target);\n }\n\n controller.observer.unobserve(target);\n };\n // Arguments should never change\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [isDisabled]);\n\n return { observe, freeze, unfreeze };\n}\n\nexport function useOnIntersect(\n targetRef: RefObject<HTMLDivElement>, observe?: ObserveFn, callback?: TargetCallback,\n) {\n useEffect(() => {\n return observe ? observe(targetRef.current!, callback) : undefined;\n // Arguments should never change\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n}\n\nexport function useIsIntersecting(\n targetRef: RefObject<HTMLDivElement>, observe?: ObserveFn, callback?: TargetCallback,\n) {\n const [isIntersecting, setIsIntersecting] = useState(!observe);\n\n useOnIntersect(targetRef, observe, (entry) => {\n setIsIntersecting(entry.isIntersecting);\n\n if (callback) {\n callback(entry);\n }\n });\n\n return isIntersecting;\n}\n","import { useEffect } from '../lib/teact/teact';\n\nimport { ApiMediaFormat } from '../api/types';\n\nimport * as mediaLoader from '../util/mediaLoader';\nimport useForceUpdate from './useForceUpdate';\n\nexport default <T extends ApiMediaFormat = ApiMediaFormat.BlobUrl>(\n mediaHash: string | false | undefined,\n noLoad = false,\n // @ts-ignore (workaround for \"could be instantiated with a different subtype\" issue)\n mediaFormat: T = ApiMediaFormat.BlobUrl,\n cacheBuster?: number,\n delay?: number | false,\n) => {\n const mediaData = mediaHash ? mediaLoader.getFromMemory<T>(mediaHash) : undefined;\n const forceUpdate = useForceUpdate();\n\n useEffect(() => {\n if (!noLoad && mediaHash && !mediaData) {\n const startedAt = Date.now();\n\n mediaLoader.fetch(mediaHash, mediaFormat).then(() => {\n const spentTime = Date.now() - startedAt;\n if (!delay || spentTime >= delay) {\n forceUpdate();\n } else {\n setTimeout(forceUpdate, delay - spentTime);\n }\n });\n }\n }, [noLoad, mediaHash, mediaData, mediaFormat, cacheBuster, forceUpdate, delay]);\n\n return mediaData;\n};\n","import { MouseEvent as ReactMouseEvent } from 'react';\nimport React, {\n FC, useEffect, useCallback, memo,\n} from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { ApiUser, ApiTypingStatus } from '../../api/types';\nimport { GlobalActions, GlobalState } from '../../global/types';\nimport { MediaViewerOrigin } from '../../types';\n\nimport { selectChatMessages, selectUser } from '../../modules/selectors';\nimport { getUserFullName, getUserStatus, isUserOnline } from '../../modules/helpers';\nimport renderText from './helpers/renderText';\nimport { pick } from '../../util/iteratees';\nimport useLang from '../../hooks/useLang';\n\nimport Avatar from './Avatar';\nimport VerifiedIcon from './VerifiedIcon';\nimport TypingStatus from './TypingStatus';\n\ntype OwnProps = {\n userId: number;\n typingStatus?: ApiTypingStatus;\n avatarSize?: 'tiny' | 'small' | 'medium' | 'large' | 'jumbo';\n forceShowSelf?: boolean;\n status?: string;\n withMediaViewer?: boolean;\n withUsername?: boolean;\n withFullInfo?: boolean;\n withUpdatingStatus?: boolean;\n noStatusOrTyping?: boolean;\n noRtl?: boolean;\n};\n\ntype StateProps = {\n user?: ApiUser;\n isSavedMessages?: boolean;\n areMessagesLoaded: boolean;\n} & Pick<GlobalState, 'lastSyncTime'>;\n\ntype DispatchProps = Pick<GlobalActions, 'loadFullUser' | 'openMediaViewer'>;\n\nconst PrivateChatInfo: FC<OwnProps & StateProps & DispatchProps> = ({\n typingStatus,\n avatarSize = 'medium',\n status,\n withMediaViewer,\n withUsername,\n withFullInfo,\n withUpdatingStatus,\n noStatusOrTyping,\n noRtl,\n user,\n isSavedMessages,\n areMessagesLoaded,\n lastSyncTime,\n loadFullUser,\n openMediaViewer,\n}) => {\n const { id: userId } = user || {};\n const fullName = getUserFullName(user);\n\n useEffect(() => {\n if (withFullInfo && lastSyncTime && userId) {\n loadFullUser({ userId });\n }\n }, [userId, loadFullUser, lastSyncTime, withFullInfo]);\n\n const handleAvatarViewerOpen = useCallback((e: ReactMouseEvent<HTMLDivElement, MouseEvent>, hasPhoto: boolean) => {\n if (user && hasPhoto) {\n e.stopPropagation();\n openMediaViewer({\n avatarOwnerId: user.id,\n origin: avatarSize === 'jumbo' ? MediaViewerOrigin.ProfileAvatar : MediaViewerOrigin.MiddleHeaderAvatar,\n });\n }\n }, [user, avatarSize, openMediaViewer]);\n\n const lang = useLang();\n\n if (!user) {\n return undefined;\n }\n\n function renderStatusOrTyping() {\n if (status) {\n return (\n <span className=\"status\" dir=\"auto\">{status}</span>\n );\n }\n\n if (withUpdatingStatus && !areMessagesLoaded) {\n return (\n <span className=\"status\" dir=\"auto\">{lang('Updating')}</span>\n );\n }\n\n if (!user) {\n return undefined;\n }\n\n if (typingStatus) {\n return <TypingStatus typingStatus={typingStatus} />;\n }\n\n return (\n <div className={`status ${isUserOnline(user) ? 'online' : ''}`}>\n {withUsername && user.username && <span className=\"handle\">{user.username}</span>}\n <span className=\"user-status\" dir=\"auto\">{getUserStatus(lang, user)}</span>\n </div>\n );\n }\n\n return (\n <div className=\"ChatInfo\" dir={!noRtl && lang.isRtl ? 'rtl' : undefined}>\n <Avatar\n key={user.id}\n size={avatarSize}\n user={user}\n isSavedMessages={isSavedMessages}\n onClick={withMediaViewer ? handleAvatarViewerOpen : undefined}\n />\n <div className=\"info\">\n {isSavedMessages ? (\n <div className=\"title\">\n <h3>{lang('SavedMessages')}</h3>\n </div>\n ) : (\n <div className=\"title\">\n <h3 dir=\"auto\">{fullName && renderText(fullName)}</h3>\n {user && user.isVerified && <VerifiedIcon />}\n </div>\n )}\n {(status || (!isSavedMessages && !noStatusOrTyping)) && renderStatusOrTyping()}\n </div>\n </div>\n );\n};\n\nexport default memo(withGlobal<OwnProps>(\n (global, { userId, forceShowSelf }): StateProps => {\n const { lastSyncTime } = global;\n const user = selectUser(global, userId);\n const isSavedMessages = !forceShowSelf && user && user.isSelf;\n const areMessagesLoaded = Boolean(selectChatMessages(global, userId));\n\n return {\n lastSyncTime, user, isSavedMessages, areMessagesLoaded,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, ['loadFullUser', 'openMediaViewer']),\n)(PrivateChatInfo));\n","import React, {\n FC, useEffect, useRef, useState,\n} from '../../lib/teact/teact';\n\nimport { HistoryWrapper } from '../../util/history';\nimport captureKeyboardListeners from '../../util/captureKeyboardListeners';\nimport trapFocus from '../../util/trapFocus';\nimport buildClassName from '../../util/buildClassName';\nimport { dispatchHeavyAnimationEvent } from '../../hooks/useHeavyAnimationCheck';\nimport useShowTransition from '../../hooks/useShowTransition';\nimport useEffectWithPrevDeps from '../../hooks/useEffectWithPrevDeps';\nimport useLang from '../../hooks/useLang';\nimport useHistoryBack from '../../hooks/useHistoryBack';\nimport useOnChange from '../../hooks/useOnChange';\n\nimport Button from './Button';\nimport Portal from './Portal';\n\nimport './Modal.scss';\n\nconst ANIMATION_DURATION = 200;\n\ntype OwnProps = {\n title?: string;\n className?: string;\n isOpen?: boolean;\n header?: FC;\n hasCloseButton?: boolean;\n noBackdrop?: boolean;\n children: any;\n onClose: () => void;\n onCloseAnimationEnd?: () => void;\n onEnter?: () => void;\n};\n\nconst Modal: FC<OwnProps> = (props) => {\n const {\n title,\n className,\n isOpen,\n header,\n hasCloseButton,\n noBackdrop,\n children,\n onClose,\n onCloseAnimationEnd,\n onEnter,\n } = props;\n const [isClosedWithHistory, setIsClosedWithHistory] = useState(false);\n const [noAnimations, setNoAnimations] = useState(false);\n const [isFirstRender, setIsFirstRender] = useState(true);\n const {\n shouldRender,\n transitionClassNames,\n } = useShowTransition(isOpen, onCloseAnimationEnd, noAnimations, undefined, noAnimations);\n // eslint-disable-next-line no-null/no-null\n const modalRef = useRef<HTMLDivElement>(null);\n\n useEffect(() => (isOpen\n ? captureKeyboardListeners({ onEsc: onClose, onEnter })\n : undefined), [isOpen, onClose, onEnter]);\n useEffect(() => (isOpen && modalRef.current ? trapFocus(modalRef.current) : undefined), [isOpen]);\n\n useHistoryBack((event, noAnimation, previousHistoryState) => {\n if (previousHistoryState && previousHistoryState.type === 'modal') {\n setIsClosedWithHistory(true);\n if (noAnimation) {\n setNoAnimations(true);\n setTimeout(() => setNoAnimations(false), ANIMATION_DURATION);\n }\n onClose();\n }\n });\n\n useOnChange(() => {\n if (isFirstRender) {\n setIsFirstRender(false);\n return;\n }\n if (isOpen) {\n HistoryWrapper.pushState({\n type: 'modal',\n });\n } else if (!isClosedWithHistory) {\n HistoryWrapper.back();\n } else {\n setIsClosedWithHistory(false);\n }\n }, [isOpen]);\n\n useEffectWithPrevDeps(([prevIsOpen]) => {\n document.body.classList.toggle('has-open-dialog', isOpen);\n\n if (isOpen || (!isOpen && prevIsOpen !== undefined)) {\n dispatchHeavyAnimationEvent(ANIMATION_DURATION);\n }\n\n return () => {\n document.body.classList.remove('has-open-dialog');\n };\n }, [isOpen]);\n\n const lang = useLang();\n\n if (!shouldRender) {\n return undefined;\n }\n\n function renderHeader() {\n if (header) {\n return header;\n }\n\n if (!title) {\n return undefined;\n }\n\n return (\n <div className=\"modal-header\">\n {hasCloseButton && (\n <Button\n round\n color=\"translucent\"\n size=\"smaller\"\n ariaLabel={lang('Close')}\n onClick={onClose}\n >\n <i className=\"icon-close\" />\n </Button>\n )}\n <div className=\"modal-title\">{title}</div>\n </div>\n );\n }\n\n const fullClassName = buildClassName(\n 'Modal',\n className,\n transitionClassNames,\n noBackdrop && 'transparent-backdrop',\n );\n\n return (\n <Portal>\n <div\n ref={modalRef}\n className={fullClassName}\n tabIndex={-1}\n role=\"dialog\"\n >\n <div className=\"modal-container\">\n <div className=\"modal-backdrop\" onClick={onClose} />\n <div className=\"modal-dialog\">\n {renderHeader()}\n <div className=\"modal-content custom-scroll\">\n {children}\n </div>\n </div>\n </div>\n </div>\n </Portal>\n );\n};\n\nexport default Modal;\n","export default function trapFocus(element: HTMLElement) {\n function handleKeyDown(e: KeyboardEvent) {\n if (e.key !== 'Tab') {\n return;\n }\n\n e.preventDefault();\n e.stopPropagation();\n\n const focusableElements = Array.from(\n element.querySelectorAll('button, [href], input, select, textarea, [tabindex]:not([tabindex=\"-1\"])'),\n ) as HTMLElement[];\n if (!focusableElements.length) {\n return;\n }\n\n const currentFocusedIndex = focusableElements.findIndex((em) => em.isSameNode(document.activeElement));\n let newFocusedIndex = 0;\n if (currentFocusedIndex >= 0) {\n if (e.shiftKey) {\n newFocusedIndex = currentFocusedIndex > 0\n ? currentFocusedIndex - 1\n : focusableElements.length - 1;\n } else {\n newFocusedIndex = currentFocusedIndex < focusableElements.length - 1\n ? currentFocusedIndex + 1\n : 0;\n }\n }\n\n focusableElements[newFocusedIndex].focus();\n }\n\n document.addEventListener('keydown', handleKeyDown, false);\n\n return () => {\n document.removeEventListener('keydown', handleKeyDown, false);\n };\n}\n","import { RefObject } from 'react';\nimport React, {\n FC, useLayoutEffect, useRef,\n} from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { ANIMATION_END_DELAY } from '../../config';\nimport { IS_MOBILE_SCREEN } from '../../util/environment';\nimport useForceUpdate from '../../hooks/useForceUpdate';\nimport usePrevious from '../../hooks/usePrevious';\nimport buildClassName from '../../util/buildClassName';\nimport { dispatchHeavyAnimationEvent } from '../../hooks/useHeavyAnimationCheck';\n\nimport './Transition.scss';\n\ntype ChildrenFn = (isActive: boolean, isFrom: boolean) => any;\ntype OwnProps = {\n ref?: RefObject<HTMLDivElement>;\n activeKey: number;\n name: (\n 'none' | 'slide' | 'slide-reversed' | 'mv-slide' | 'slide-fade' | 'zoom-fade' | 'scroll-slide' | 'slide-layers'\n | 'fade' | 'push-slide' | 'reveal'\n );\n direction?: 'auto' | 'inverse' | 1 | -1;\n renderCount?: number;\n shouldRestoreHeight?: boolean;\n shouldCleanup?: boolean;\n id?: string;\n className?: string;\n onStart?: () => void;\n onStop?: () => void;\n children: ChildrenFn;\n};\n\ntype StateProps = {\n animationLevel: number;\n};\n\nexport const ANIMATION_DURATION = {\n slide: 450,\n 'slide-reversed': 450,\n 'mv-slide': 400,\n 'slide-fade': 400,\n 'zoom-fade': 150,\n 'scroll-slide': 500,\n fade: 150,\n 'slide-layers': IS_MOBILE_SCREEN ? 450 : 300,\n 'push-slide': 300,\n reveal: 350,\n};\n\nconst CLEANED_UP = Symbol('CLEANED_UP');\n\nconst Transition: FC<OwnProps & StateProps> = ({\n ref,\n activeKey,\n name,\n direction = 'auto',\n renderCount,\n shouldRestoreHeight,\n shouldCleanup,\n id,\n className,\n onStart,\n onStop,\n children,\n animationLevel,\n}) => {\n // eslint-disable-next-line no-null/no-null\n let containerRef = useRef<HTMLDivElement>(null);\n if (ref) {\n containerRef = ref;\n }\n\n const rendersRef = useRef<Record<number, ChildrenFn | typeof CLEANED_UP>>({});\n const prevActiveKey = usePrevious<any>(activeKey);\n const activateTimeoutRef = useRef<number>();\n const forceUpdate = useForceUpdate();\n\n const activeKeyChanged = prevActiveKey !== undefined && activeKey !== prevActiveKey;\n\n if (!renderCount && activeKeyChanged) {\n rendersRef.current = { [prevActiveKey]: rendersRef.current[prevActiveKey] };\n }\n\n rendersRef.current[activeKey] = children;\n\n useLayoutEffect(() => {\n function cleanup() {\n if (!shouldCleanup) {\n return;\n }\n\n rendersRef.current = { [prevActiveKey]: CLEANED_UP };\n forceUpdate();\n }\n\n const container = containerRef.current!;\n\n const childElements = container.children;\n if (childElements.length === 1 && !activeKeyChanged) {\n childElements[0].classList.add('active');\n\n return;\n }\n\n const childNodes = Array.from(container.childNodes);\n\n if (!activeKeyChanged || !childNodes.length) {\n return;\n }\n\n if (activateTimeoutRef.current) {\n clearTimeout(activateTimeoutRef.current);\n activateTimeoutRef.current = undefined;\n }\n\n const isBackwards = (\n direction === -1\n || (direction === 'auto' && prevActiveKey > activeKey)\n || (direction === 'inverse' && prevActiveKey < activeKey)\n );\n\n container.classList.remove('animating');\n container.classList.toggle('backwards', isBackwards);\n\n const keys = Object.keys(rendersRef.current).map(Number);\n const prevActiveIndex = renderCount ? prevActiveKey : keys.indexOf(prevActiveKey);\n const activeIndex = renderCount ? activeKey : keys.indexOf(activeKey);\n\n if (name === 'none' || animationLevel === 0) {\n childNodes.forEach((node, i) => {\n if (node instanceof HTMLElement) {\n node.classList.remove('from', 'through', 'to');\n node.classList.toggle('active', i === activeIndex);\n }\n });\n\n cleanup();\n\n return;\n }\n\n childNodes.forEach((node, i) => {\n if (node instanceof HTMLElement) {\n node.classList.remove('active');\n node.classList.toggle('from', i === prevActiveIndex);\n node.classList.toggle('through', (\n (i > prevActiveIndex && i < activeIndex) || (i < prevActiveIndex && i > activeIndex)\n ));\n node.classList.toggle('to', i === activeIndex);\n }\n });\n\n if (name === 'scroll-slide') {\n const width = container.offsetWidth;\n container.scrollBy({\n left: activeIndex > prevActiveIndex ? width : -width,\n behavior: 'smooth',\n });\n }\n\n if (animationLevel > 0) {\n dispatchHeavyAnimationEvent(ANIMATION_DURATION[name] + ANIMATION_END_DELAY);\n }\n\n requestAnimationFrame(() => {\n container.classList.add('animating');\n\n activateTimeoutRef.current = window.setTimeout(() => {\n requestAnimationFrame(() => {\n container.classList.remove('animating', 'backwards');\n\n childNodes.forEach((node, i) => {\n if (node instanceof HTMLElement) {\n node.classList.remove('from', 'through', 'to');\n node.classList.toggle('active', i === activeIndex);\n }\n });\n\n if (name === 'scroll-slide') {\n container.scrollLeft = activeKey * container.offsetWidth;\n }\n\n if (shouldRestoreHeight) {\n const activeElement = container.querySelector<HTMLDivElement>('.active');\n\n if (activeElement) {\n activeElement.style.height = 'auto';\n container.style.height = `${activeElement.clientHeight}px`;\n }\n }\n\n cleanup();\n\n if (onStop) {\n onStop();\n }\n });\n }, ANIMATION_DURATION[name] + ANIMATION_END_DELAY);\n\n if (onStart) {\n onStart();\n }\n });\n }, [\n activeKey,\n prevActiveKey,\n activeKeyChanged,\n direction,\n name,\n onStart,\n onStop,\n renderCount,\n shouldRestoreHeight,\n shouldCleanup,\n animationLevel,\n forceUpdate,\n ]);\n\n useLayoutEffect(() => {\n if (shouldRestoreHeight) {\n const container = containerRef.current!;\n const activeElement = container.querySelector<HTMLDivElement>('.active')\n || container.querySelector<HTMLDivElement>('.from');\n\n if (activeElement) {\n activeElement.style.height = 'auto';\n container.style.height = `${activeElement.clientHeight}px`;\n container.style.flexBasis = `${activeElement.clientHeight}px`;\n }\n }\n }, [shouldRestoreHeight, children]);\n\n const renders = rendersRef.current;\n const collection = Object.keys(renderCount ? new Array(renderCount).fill(undefined) : renders).map(Number);\n const contents = collection.map((key) => {\n const render = renders[key];\n\n return (\n typeof render === 'function' ? <div key={key}>{render(key === activeKey, key === prevActiveKey)}</div> : undefined\n );\n });\n\n const fullClassName = buildClassName(\n 'Transition',\n className,\n animationLevel === 0 && name === 'scroll-slide' ? 'slide' : name,\n );\n\n return (\n <div ref={containerRef} id={id} className={fullClassName}>\n {contents}\n </div>\n );\n};\n\nexport default withGlobal<OwnProps>((global) => {\n const { animationLevel } = global.settings.byKey;\n return { animationLevel };\n})(Transition);\n","import { MouseEvent as ReactMouseEvent } from 'react';\nimport React, { FC, useCallback, memo } from '../../lib/teact/teact';\n\nimport { ApiUser, ApiChat, ApiMediaFormat } from '../../api/types';\n\nimport { IS_TEST } from '../../config';\nimport {\n getChatAvatarHash, getChatTitle, isChatPrivate,\n getUserFullName, isUserOnline, isDeletedUser, getUserColorKey,\n} from '../../modules/helpers';\nimport { getFirstLetters } from '../../util/textFormat';\nimport buildClassName from '../../util/buildClassName';\nimport renderText from './helpers/renderText';\nimport useMedia from '../../hooks/useMedia';\nimport useTransitionForMedia from '../../hooks/useTransitionForMedia';\nimport useLang from '../../hooks/useLang';\n\nimport './Avatar.scss';\n\ntype OwnProps = {\n className?: string;\n size?: 'micro' | 'tiny' | 'small' | 'medium' | 'large' | 'jumbo';\n withOnlineStatus?: boolean;\n chat?: ApiChat;\n user?: ApiUser;\n text?: string;\n isSavedMessages?: boolean;\n lastSyncTime?: number;\n onClick?: (e: ReactMouseEvent<HTMLDivElement, MouseEvent>, hasPhoto: boolean) => void;\n};\n\nconst Avatar: FC<OwnProps> = ({\n className,\n size = 'large',\n chat,\n user,\n text,\n withOnlineStatus,\n isSavedMessages,\n lastSyncTime,\n onClick,\n}) => {\n const isDeleted = user && isDeletedUser(user);\n let imageHash: string | undefined;\n\n if (!isSavedMessages && !isDeleted) {\n if (user) {\n imageHash = getChatAvatarHash(user);\n } else if (chat) {\n imageHash = getChatAvatarHash(chat);\n }\n }\n\n const dataUri = useMedia(imageHash, false, ApiMediaFormat.DataUri, lastSyncTime);\n const { shouldRenderFullMedia, transitionClassNames } = useTransitionForMedia(dataUri, 'slow');\n\n const lang = useLang();\n\n let content: string | undefined = '';\n\n if (isSavedMessages) {\n content = <i className=\"icon-avatar-saved-messages\" />;\n } else if (isDeleted) {\n content = <i className=\"icon-avatar-deleted-account\" />;\n } else if (shouldRenderFullMedia) {\n content = <img src={dataUri} className={`${transitionClassNames} avatar-media`} alt=\"\" decoding=\"async\" />;\n } else if (user) {\n const userFullName = getUserFullName(user);\n content = userFullName ? getFirstLetters(userFullName, 2) : undefined;\n } else if (chat) {\n const title = getChatTitle(lang, chat);\n content = title && getFirstLetters(title, isChatPrivate(chat.id) ? 2 : 1);\n } else if (text) {\n content = getFirstLetters(text, 2);\n }\n\n const isOnline = !isSavedMessages && user && isUserOnline(user);\n const fullClassName = buildClassName(\n `Avatar size-${size}`,\n className,\n `color-bg-${getUserColorKey(user || chat)}`,\n isSavedMessages && 'saved-messages',\n isDeleted && 'deleted-account',\n withOnlineStatus && isOnline && 'online',\n onClick && 'interactive',\n (!isSavedMessages && !shouldRenderFullMedia) && 'no-photo',\n );\n\n const handleClick = useCallback((e: ReactMouseEvent<HTMLDivElement, MouseEvent>) => {\n if (onClick) {\n onClick(e, isSavedMessages || shouldRenderFullMedia);\n }\n }, [onClick, isSavedMessages, shouldRenderFullMedia]);\n\n const senderId = (user || chat) && (user || chat)!.id;\n\n return (\n <div className={fullClassName} onClick={handleClick} data-test-sender-id={IS_TEST ? senderId : undefined}>\n {typeof content === 'string' ? renderText(content, [size === 'jumbo' ? 'hq_emoji' : 'emoji']) : content}\n </div>\n );\n};\n\nexport default memo(Avatar);\n","import { RefObject, UIEvent } from 'react';\nimport { LoadMoreDirection } from '../../types';\n\nimport React, {\n FC, useCallback, useEffect, useLayoutEffect, useMemo, useRef,\n} from '../../lib/teact/teact';\n\nimport { debounce } from '../../util/schedulers';\nimport resetScroll from '../../util/resetScroll';\n\ntype OwnProps = {\n ref?: RefObject<HTMLDivElement>;\n className?: string;\n onLoadMore?: ({ direction }: { direction: LoadMoreDirection }) => void;\n onScroll?: (e: UIEvent<HTMLDivElement>) => void;\n onKeyDown?: (e: React.KeyboardEvent<any>) => void;\n items?: any[];\n itemSelector?: string;\n preloadBackwards?: number;\n sensitiveArea?: number;\n noScrollRestore?: boolean;\n noScrollRestoreOnTop?: boolean;\n noFastList?: boolean;\n cacheBuster?: any;\n children: any;\n};\n\nconst DEFAULT_LIST_SELECTOR = '.ListItem';\nconst DEFAULT_PRELOAD_BACKWARDS = 20;\nconst DEFAULT_SENSITIVE_AREA = 800;\n\nconst InfiniteScroll: FC<OwnProps> = ({\n ref,\n className,\n onLoadMore,\n onScroll,\n onKeyDown,\n items,\n itemSelector = DEFAULT_LIST_SELECTOR,\n preloadBackwards = DEFAULT_PRELOAD_BACKWARDS,\n sensitiveArea = DEFAULT_SENSITIVE_AREA,\n // Used to turn off restoring scroll position (e.g. for frequently re-ordered chat or user lists)\n noScrollRestore = false,\n noScrollRestoreOnTop = false,\n noFastList,\n // Used to re-query `listItemElements` if rendering is delayed by transition\n cacheBuster,\n children,\n}: OwnProps) => {\n // eslint-disable-next-line no-null/no-null\n let containerRef = useRef<HTMLDivElement>(null);\n if (ref) {\n containerRef = ref;\n }\n\n const stateRef = useRef<{\n listItemElements: NodeListOf<HTMLDivElement>;\n isScrollTopJustUpdated: boolean;\n currentAnchor: HTMLDivElement | undefined;\n currentAnchorTop: number;\n }>({} as any);\n\n const [loadMoreBackwards, loadMoreForwards] = useMemo(() => {\n if (!onLoadMore) {\n return [];\n }\n\n return [\n debounce(() => onLoadMore({ direction: LoadMoreDirection.Backwards }), 1000, true, false),\n debounce(() => onLoadMore({ direction: LoadMoreDirection.Forwards }), 1000, true, false),\n ];\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [onLoadMore, items]);\n\n // Initial preload\n useEffect(() => {\n if (!loadMoreBackwards) {\n return;\n }\n\n if (preloadBackwards > 0 && (!items || items.length < preloadBackwards)) {\n loadMoreBackwards();\n return;\n }\n\n const { scrollHeight, clientHeight } = containerRef.current!;\n if (clientHeight && scrollHeight <= clientHeight) {\n loadMoreBackwards();\n }\n }, [items, loadMoreBackwards, preloadBackwards]);\n\n // Restore `scrollTop` after adding items\n useLayoutEffect(() => {\n const container = containerRef.current!;\n const state = stateRef.current;\n\n state.listItemElements = container.querySelectorAll<HTMLDivElement>(itemSelector);\n\n let newScrollTop;\n\n if (state.currentAnchor && Array.from(state.listItemElements).includes(state.currentAnchor)) {\n const { scrollTop } = container;\n const newAnchorTop = state.currentAnchor.getBoundingClientRect().top;\n newScrollTop = scrollTop + (newAnchorTop - state.currentAnchorTop);\n } else {\n const nextAnchor = state.listItemElements[0];\n if (nextAnchor) {\n state.currentAnchor = nextAnchor;\n state.currentAnchorTop = nextAnchor.getBoundingClientRect().top;\n }\n }\n\n if (noScrollRestore) {\n return;\n }\n\n if (noScrollRestoreOnTop && container.scrollTop === 0) {\n return;\n }\n\n resetScroll(container, newScrollTop);\n\n state.isScrollTopJustUpdated = true;\n }, [items, itemSelector, noScrollRestore, noScrollRestoreOnTop, cacheBuster]);\n\n const handleScroll = useCallback((e: UIEvent<HTMLDivElement>) => {\n if (loadMoreForwards && loadMoreBackwards) {\n const {\n listItemElements, isScrollTopJustUpdated, currentAnchor, currentAnchorTop,\n } = stateRef.current;\n\n if (isScrollTopJustUpdated) {\n stateRef.current.isScrollTopJustUpdated = false;\n return;\n }\n\n const listLength = listItemElements.length;\n const container = containerRef.current!;\n const { scrollTop, scrollHeight, offsetHeight } = container;\n const top = listLength ? listItemElements[0].offsetTop : 0;\n const isNearTop = scrollTop <= top + sensitiveArea;\n const bottom = listLength\n ? listItemElements[listLength - 1].offsetTop + listItemElements[listLength - 1].offsetHeight\n : scrollHeight;\n const isNearBottom = bottom - (scrollTop + offsetHeight) <= sensitiveArea;\n let isUpdated = false;\n\n if (isNearTop) {\n const nextAnchor = listItemElements[0];\n if (nextAnchor) {\n const nextAnchorTop = nextAnchor.getBoundingClientRect().top;\n const newAnchorTop = currentAnchor && currentAnchor.offsetParent && currentAnchor !== nextAnchor\n ? currentAnchor.getBoundingClientRect().top\n : nextAnchorTop;\n const isMovingUp = (\n currentAnchor && currentAnchorTop !== undefined && newAnchorTop > currentAnchorTop\n );\n\n if (isMovingUp) {\n stateRef.current.currentAnchor = nextAnchor;\n stateRef.current.currentAnchorTop = nextAnchorTop;\n isUpdated = true;\n resetScroll(container);\n loadMoreForwards();\n }\n }\n }\n\n if (isNearBottom) {\n const nextAnchor = listItemElements[listLength - 1];\n if (nextAnchor) {\n const nextAnchorTop = nextAnchor.getBoundingClientRect().top;\n const newAnchorTop = currentAnchor && currentAnchor.offsetParent && currentAnchor !== nextAnchor\n ? currentAnchor.getBoundingClientRect().top\n : nextAnchorTop;\n const isMovingDown = (\n currentAnchor && currentAnchorTop !== undefined && newAnchorTop < currentAnchorTop\n );\n\n if (isMovingDown) {\n stateRef.current.currentAnchor = nextAnchor;\n stateRef.current.currentAnchorTop = nextAnchorTop;\n isUpdated = true;\n resetScroll(container);\n loadMoreBackwards();\n }\n }\n }\n\n if (!isUpdated) {\n if (currentAnchor && currentAnchor.offsetParent) {\n stateRef.current.currentAnchorTop = currentAnchor.getBoundingClientRect().top;\n } else {\n const nextAnchor = listItemElements[0];\n\n if (nextAnchor) {\n stateRef.current.currentAnchor = nextAnchor;\n stateRef.current.currentAnchorTop = nextAnchor.getBoundingClientRect().top;\n }\n }\n }\n }\n\n if (onScroll) {\n onScroll(e);\n }\n }, [loadMoreBackwards, loadMoreForwards, onScroll, sensitiveArea]);\n\n return (\n <div\n ref={containerRef}\n className={className}\n onScroll={handleScroll}\n teactFastList={!noFastList}\n onKeyDown={onKeyDown}\n >\n {children}\n </div>\n );\n};\n\nexport default InfiniteScroll;\n","import { useEffect, useRef, useState } from '../lib/teact/teact';\n\nimport useShowTransition from './useShowTransition';\n\nconst SPEED = {\n fast: 200,\n slow: 350,\n};\n\nexport default (mediaData?: any, speed: keyof typeof SPEED = 'fast', noAnimate = false) => {\n const isMediaLoaded = Boolean(mediaData);\n const willAnimate = !useRef(isMediaLoaded).current && !noAnimate;\n const [shouldRenderThumb, setShouldRenderThumb] = useState(!isMediaLoaded);\n\n const {\n shouldRender: shouldRenderFullMedia,\n transitionClassNames,\n } = useShowTransition(isMediaLoaded, undefined, !willAnimate, speed);\n\n useEffect(() => {\n if (shouldRenderFullMedia) {\n if (willAnimate) {\n setTimeout(() => {\n setShouldRenderThumb(false);\n }, SPEED[speed]);\n } else {\n setShouldRenderThumb(false);\n }\n }\n }, [willAnimate, shouldRenderFullMedia, speed]);\n\n return {\n shouldRenderThumb,\n shouldRenderFullMedia,\n transitionClassNames,\n };\n};\n","import { ApiPhoto, ApiVideo, ApiSticker } from '../../../api/types';\nimport { getPhotoInlineDimensions, getVideoDimensions, IDimensions } from '../../../modules/helpers';\nimport windowSize from '../../../util/windowSize';\nimport { IS_MOBILE_SCREEN } from '../../../util/environment';\nimport { STICKER_SIZE_INLINE_DESKTOP_FACTOR, STICKER_SIZE_INLINE_MOBILE_FACTOR } from '../../../config';\n\nexport const MEDIA_VIEWER_MEDIA_QUERY = '(max-height: 640px)';\nexport const REM = parseInt(getComputedStyle(document.documentElement).fontSize, 10);\nexport const ROUND_VIDEO_DIMENSIONS = 200;\nexport const AVATAR_FULL_DIMENSIONS = { width: 640, height: 640 };\n\nconst DEFAULT_MEDIA_DIMENSIONS: IDimensions = { width: 100, height: 100 };\nconst LIKE_STICKER_ID = '1258816259753933';\nconst MOBILE_SCREEN_MAX_MESSAGE_SCREEN_WIDTH = 0.69;\n\nlet cachedMaxWidth: number | undefined;\n\nfunction getMaxMessageWidthRem(fromOwnMessage: boolean) {\n const regularMaxWidth = fromOwnMessage ? 30 : 29;\n if (!IS_MOBILE_SCREEN) {\n return regularMaxWidth;\n }\n\n // @optimization Limitation: changing device screen width not supported\n if (!cachedMaxWidth) {\n cachedMaxWidth = Math.min(\n regularMaxWidth,\n Math.floor(window.innerWidth * MOBILE_SCREEN_MAX_MESSAGE_SCREEN_WIDTH) / REM,\n );\n }\n\n return cachedMaxWidth;\n}\n\nfunction getAvailableWidth(\n fromOwnMessage: boolean,\n isForwarded?: boolean,\n isWebPagePhoto?: boolean,\n) {\n const extraPaddingRem = isForwarded || isWebPagePhoto ? 1.625 : 0;\n const availableWidthRem = getMaxMessageWidthRem(fromOwnMessage) - extraPaddingRem;\n\n return availableWidthRem * REM;\n}\n\nfunction getAvailableHeight(isGif?: boolean, aspectRatio?: number) {\n if (\n isGif && aspectRatio\n && aspectRatio >= 0.75 && aspectRatio <= 1.25\n ) {\n return 20 * REM;\n }\n\n return 27 * REM;\n}\n\nfunction calculateDimensionsForMessageMedia({\n width,\n height,\n fromOwnMessage,\n isForwarded,\n isWebPagePhoto,\n isGif,\n}: {\n width: number;\n height: number;\n fromOwnMessage: boolean;\n isForwarded?: boolean;\n isWebPagePhoto?: boolean;\n isGif?: boolean;\n}): IDimensions {\n const aspectRatio = height / width;\n const availableWidth = getAvailableWidth(fromOwnMessage, isForwarded, isWebPagePhoto);\n const availableHeight = getAvailableHeight(isGif, aspectRatio);\n\n return calculateDimensions(availableWidth, availableHeight, width, height);\n}\n\nexport function getMediaViewerAvailableDimensions(withFooter: boolean, isVideo: boolean): IDimensions {\n const mql = window.matchMedia(MEDIA_VIEWER_MEDIA_QUERY);\n const { width: windowWidth, height: windowHeight } = windowSize.get();\n let occupiedHeightRem = isVideo && mql.matches ? 10 : 8.25;\n if (withFooter) {\n occupiedHeightRem = mql.matches ? 10 : 15;\n }\n\n return {\n width: windowWidth,\n height: windowHeight - occupiedHeightRem * REM,\n };\n}\n\nexport function calculateInlineImageDimensions(\n photo: ApiPhoto,\n fromOwnMessage: boolean,\n isForwarded?: boolean,\n isWebPagePhoto?: boolean,\n) {\n const { width, height } = getPhotoInlineDimensions(photo) || DEFAULT_MEDIA_DIMENSIONS;\n\n return calculateDimensionsForMessageMedia({\n width,\n height,\n fromOwnMessage,\n isForwarded,\n isWebPagePhoto,\n });\n}\n\nexport function calculateVideoDimensions(\n video: ApiVideo,\n fromOwnMessage: boolean,\n isForwarded?: boolean,\n) {\n const { width, height } = getVideoDimensions(video) || DEFAULT_MEDIA_DIMENSIONS;\n\n return calculateDimensionsForMessageMedia({\n width,\n height,\n fromOwnMessage,\n isForwarded,\n isGif: video.isGif,\n });\n}\n\nexport function getPictogramDimensions(): IDimensions {\n return {\n width: 2 * REM,\n height: 2 * REM,\n };\n}\n\nexport function getDocumentThumbnailDimensions(smaller?: boolean): IDimensions {\n if (smaller) {\n return {\n width: 3 * REM,\n height: 3 * REM,\n };\n }\n\n return {\n width: 3.375 * REM,\n height: 3.375 * REM,\n };\n}\n\nexport function getStickerDimensions(sticker: ApiSticker): IDimensions {\n const { width } = sticker;\n let { height } = sticker;\n\n // For some reason this sticker has some weird `height` value\n if (sticker.id === LIKE_STICKER_ID) {\n height = width;\n }\n\n const aspectRatio = (height && width) && height / width;\n const baseWidth = (IS_MOBILE_SCREEN ? STICKER_SIZE_INLINE_MOBILE_FACTOR : STICKER_SIZE_INLINE_DESKTOP_FACTOR) * REM;\n const calculatedHeight = aspectRatio ? baseWidth * aspectRatio : baseWidth;\n\n if (aspectRatio && calculatedHeight > baseWidth) {\n return {\n width: Math.round(baseWidth / aspectRatio),\n height: baseWidth,\n };\n }\n\n return {\n width: baseWidth,\n height: calculatedHeight,\n };\n}\n\nexport function calculateMediaViewerDimensions(\n { width, height }: IDimensions, withFooter: boolean, isVideo: boolean = false,\n): IDimensions {\n const { width: availableWidth, height: availableHeight } = getMediaViewerAvailableDimensions(withFooter, isVideo);\n\n return calculateDimensions(availableWidth, availableHeight, width, height);\n}\n\nexport function calculateDimensions(\n availableWidth: number,\n availableHeight: number,\n mediaWidth: number,\n mediaHeight: number,\n): IDimensions {\n const aspectRatio = mediaHeight / mediaWidth;\n const calculatedWidth = Math.min(mediaWidth, availableWidth);\n const calculatedHeight = Math.round(calculatedWidth * aspectRatio);\n\n if (calculatedHeight > availableHeight) {\n return {\n width: Math.round(availableHeight / aspectRatio),\n height: availableHeight,\n };\n }\n\n return {\n width: calculatedWidth,\n height: Math.round(calculatedWidth * aspectRatio),\n };\n}\n","import React, {\n FC, useEffect, useRef, memo, useCallback, useState,\n} from '../../lib/teact/teact';\n\nimport { fastRaf } from '../../util/schedulers';\nimport buildClassName from '../../util/buildClassName';\nimport useHeavyAnimationCheck from '../../hooks/useHeavyAnimationCheck';\nimport useBackgroundMode from '../../hooks/useBackgroundMode';\n\ntype OwnProps = {\n className?: string;\n id: string;\n animationData: AnyLiteral;\n play?: boolean | string;\n playSegment?: [number, number];\n speed?: number;\n noLoop?: boolean;\n size: number;\n quality?: number;\n isLowPriority?: boolean;\n onLoad?: NoneToVoidFunction;\n};\n\ntype RLottieClass = typeof import('../../lib/rlottie/RLottie').default;\ntype RLottieInstance = import('../../lib/rlottie/RLottie').default;\nlet lottiePromise: Promise<RLottieClass>;\nlet RLottie: RLottieClass;\n\n// Time supposed for judges to measure \"Transferred Size\" in Dev Tools\nconst LOTTIE_LOAD_DELAY = 5000;\n\nasync function ensureLottie() {\n if (!lottiePromise) {\n lottiePromise = import('../../lib/rlottie/RLottie') as unknown as Promise<RLottieClass>;\n RLottie = (await lottiePromise as any).default;\n }\n\n return lottiePromise;\n}\n\nsetTimeout(ensureLottie, LOTTIE_LOAD_DELAY);\n\nconst AnimatedSticker: FC<OwnProps> = ({\n className,\n id,\n animationData,\n play,\n playSegment,\n speed,\n noLoop,\n size,\n quality,\n isLowPriority,\n onLoad,\n}) => {\n const [animation, setAnimation] = useState<RLottieInstance>();\n // eslint-disable-next-line no-null/no-null\n const container = useRef<HTMLDivElement>(null);\n const wasPlaying = useRef(false);\n const isFrozen = useRef(false);\n\n const playRef = useRef();\n playRef.current = play;\n const playSegmentRef = useRef<[number, number]>();\n playSegmentRef.current = playSegment;\n\n useEffect(() => {\n if (animation || !animationData) {\n return;\n }\n\n const exec = () => {\n if (!container.current) {\n return;\n }\n\n const newAnimation = new RLottie(\n id,\n container.current,\n animationData,\n {\n noLoop,\n size,\n quality,\n isLowPriority,\n },\n onLoad,\n );\n\n if (speed) {\n newAnimation.setSpeed(speed);\n }\n\n setAnimation(newAnimation);\n };\n\n if (RLottie) {\n exec();\n } else {\n ensureLottie().then(() => {\n fastRaf(() => {\n if (container.current) {\n exec();\n }\n });\n });\n }\n }, [animation, animationData, id, isLowPriority, noLoop, onLoad, quality, size, speed]);\n\n useEffect(() => {\n return () => {\n if (animation) {\n animation.destroy();\n }\n };\n }, [animation]);\n\n const playAnimation = useCallback((shouldRestart = false) => {\n if (animation && (playRef.current || playSegmentRef.current)) {\n if (playSegmentRef.current) {\n animation.playSegment(playSegmentRef.current);\n } else if (shouldRestart) {\n animation.goToAndPlay(0);\n } else {\n animation.play();\n }\n }\n }, [animation]);\n\n const pauseAnimation = useCallback(() => {\n if (!animation) {\n return;\n }\n\n animation.pause();\n }, [animation]);\n\n const freezeAnimation = useCallback(() => {\n isFrozen.current = true;\n\n if (!animation) {\n return;\n }\n\n if (!wasPlaying.current) {\n wasPlaying.current = animation.isPlaying();\n }\n\n pauseAnimation();\n }, [animation, pauseAnimation]);\n\n const unfreezeAnimation = useCallback(() => {\n if (wasPlaying.current) {\n playAnimation();\n }\n\n wasPlaying.current = false;\n isFrozen.current = false;\n }, [playAnimation]);\n\n const unfreezeAnimationOnRaf = useCallback(() => {\n fastRaf(unfreezeAnimation);\n }, [unfreezeAnimation]);\n\n useEffect(() => {\n if (!animation) {\n return;\n }\n\n if (play || playSegment) {\n if (isFrozen.current) {\n wasPlaying.current = true;\n } else {\n playAnimation(noLoop);\n }\n } else {\n // eslint-disable-next-line no-lonely-if\n if (isFrozen.current) {\n wasPlaying.current = false;\n } else {\n pauseAnimation();\n }\n }\n }, [animation, play, playSegment, noLoop, playAnimation, pauseAnimation]);\n\n useHeavyAnimationCheck(freezeAnimation, unfreezeAnimation);\n // Pausing frame may not happen in background\n // so we need to make sure it happens right after focusing,\n // then we can play again.\n useBackgroundMode(freezeAnimation, unfreezeAnimationOnRaf);\n\n const fullClassName = buildClassName('AnimatedSticker', className);\n\n const style = size ? `width: ${size}px; height: ${size}px;` : undefined;\n\n return (\n <div\n ref={container}\n className={fullClassName}\n // @ts-ignore\n style={style}\n />\n );\n};\n\nexport default memo(AnimatedSticker);\n","import React, { FC, memo } from '../../lib/teact/teact';\n\nimport useLang from '../../hooks/useLang';\nimport { TextPart } from '../common/helpers/renderMessageText';\n\nimport Modal from './Modal';\nimport Button from './Button';\n\ntype OwnProps = {\n isOpen: boolean;\n onClose: () => void;\n onCloseAnimationEnd?: () => void;\n title?: string;\n header?: FC;\n textParts?: TextPart[];\n text?: string;\n confirmLabel?: string;\n confirmHandler: () => void;\n confirmIsDestructive?: boolean;\n isButtonsInOneRow?: boolean;\n};\n\nconst ConfirmDialog: FC<OwnProps> = ({\n isOpen,\n onClose,\n onCloseAnimationEnd,\n title,\n header,\n text,\n textParts,\n confirmLabel = 'Confirm',\n confirmHandler,\n confirmIsDestructive,\n isButtonsInOneRow,\n}) => {\n const lang = useLang();\n\n return (\n <Modal\n className=\"confirm\"\n title={title}\n header={header}\n isOpen={isOpen}\n onClose={onClose}\n onCloseAnimationEnd={onCloseAnimationEnd}\n onEnter={confirmHandler}\n >\n {text && text.split('\\\\n').map((textPart) => (\n <p>{textPart}</p>\n ))}\n {textParts}\n <div className={isButtonsInOneRow ? 'dialog-buttons mt-2' : ''}>\n <Button\n className=\"confirm-dialog-button\"\n isText\n onClick={confirmHandler}\n color={confirmIsDestructive ? 'danger' : 'primary'}\n >\n {confirmLabel}\n </Button>\n <Button className=\"confirm-dialog-button\" isText onClick={onClose}>{lang('Cancel')}</Button>\n </div>\n </Modal>\n );\n};\n\nexport default memo(ConfirmDialog);\n","import React, { FC, memo } from '../../lib/teact/teact';\n\nimport buildClassName from '../../util/buildClassName';\nimport useShowTransition from '../../hooks/useShowTransition';\nimport renderText from './helpers/renderText';\nimport useLang from '../../hooks/useLang';\n\nimport './NothingFound.scss';\n\ninterface OwnProps {\n text?: string;\n description?: string;\n}\n\nconst DEFAULT_TEXT = 'Nothing found.';\n\nconst NothingFound: FC<OwnProps> = ({ text = DEFAULT_TEXT, description }) => {\n const lang = useLang();\n const { transitionClassNames } = useShowTransition(true);\n\n return (\n <div className={buildClassName('NothingFound', transitionClassNames, description && 'with-description')}>\n {text}\n {description && <p className=\"description\">{renderText(lang(description), ['br'])}</p>}\n </div>\n );\n};\n\nexport default memo(NothingFound);\n","// This is unsafe and can be not chained as `popstate` event is asynchronous\n\nimport { useEffect } from '../lib/teact/teact';\nimport { IS_IOS } from '../util/environment';\nimport { HistoryWrapper } from '../util/history';\n\ntype HistoryBackFunction = ((event: PopStateEvent, noAnimation: boolean, previousHistoryState: any) => void);\n\n// Carefully selected by swiping and observing visual changes\n// TODO: may be different on other devices such as iPad, maybe take dpi into account?\nconst SAFARI_EDGE_BACK_GESTURE_LIMIT = 60;\nconst SAFARI_EDGE_BACK_GESTURE_DURATION = 200;\nlet isEdge = false;\n\nconst onTouchStart = (event: TouchEvent) => {\n const x = event.touches[0].pageX;\n\n if (x <= SAFARI_EDGE_BACK_GESTURE_LIMIT || x >= window.innerWidth - SAFARI_EDGE_BACK_GESTURE_LIMIT) {\n isEdge = true;\n }\n};\n\nconst onTouchEnd = () => {\n if (isEdge) {\n setTimeout(() => {\n isEdge = false;\n }, SAFARI_EDGE_BACK_GESTURE_DURATION);\n }\n};\n\nif (IS_IOS) {\n // eslint-disable-next-line no-console\n console.log('Adding event listeners for useHistoryBack');\n window.addEventListener('touchstart', onTouchStart);\n window.addEventListener('touchend', onTouchEnd);\n}\n\nexport default function useHistoryBack(handler: NoneToVoidFunction | HistoryBackFunction) {\n const onPopState = (event: PopStateEvent) => {\n // Check if the event was caused by History API call or the user\n if (!HistoryWrapper.isHistoryChangedByUser) {\n // HACK: Handle multiple event listeners.\n // onTickChange doesn't work on Safari for some reason\n setTimeout(() => {\n HistoryWrapper.isHistoryChangedByUser = true;\n }, 0);\n return;\n }\n handler(event, isEdge, HistoryWrapper.states[HistoryWrapper.states.length - 1]);\n };\n\n\n useEffect(() => {\n window.addEventListener('popstate', onPopState);\n\n return () => {\n window.removeEventListener('popstate', onPopState);\n };\n });\n}\n","import { useEffect, useRef } from '../../../lib/teact/teact';\n\nimport useOnChange from '../../../hooks/useOnChange';\nimport useForceUpdate from '../../../hooks/useForceUpdate';\n\nexport default function useAsyncRendering<T extends any[]>(dependencies: T, delay?: number) {\n const isDisabled = delay === undefined;\n const shouldRenderRef = useRef(isDisabled);\n const timeoutRef = useRef<number>();\n const forceUpdate = useForceUpdate();\n\n useOnChange(() => {\n if (isDisabled) {\n return;\n }\n\n shouldRenderRef.current = false;\n\n if (timeoutRef.current) {\n clearTimeout(timeoutRef.current);\n timeoutRef.current = undefined;\n }\n }, dependencies);\n\n useEffect(() => {\n if (isDisabled || shouldRenderRef.current) {\n return;\n }\n\n const exec = () => {\n shouldRenderRef.current = true;\n forceUpdate();\n };\n\n if (delay! > 0) {\n timeoutRef.current = window.setTimeout(exec, delay);\n } else {\n exec();\n }\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, dependencies);\n\n return shouldRenderRef.current;\n}\n","import {\n useEffect, useMemo, useRef, useState,\n} from '../lib/teact/teact';\n\nimport { IS_PROGRESSIVE_SUPPORTED } from '../util/environment';\nimport { ApiMediaFormat } from '../api/types';\nimport { throttle } from '../util/schedulers';\nimport * as mediaLoader from '../util/mediaLoader';\nimport useForceUpdate from './useForceUpdate';\n\nconst STREAMING_PROGRESS = 0.75;\nconst STREAMING_TIMEOUT = 1500;\nconst PROGRESS_THROTTLE = 500;\n\nexport default <T extends ApiMediaFormat = ApiMediaFormat.BlobUrl>(\n mediaHash: string | undefined,\n noLoad = false,\n // @ts-ignore (workaround for \"could be instantiated with a different subtype\" issue)\n mediaFormat: T = ApiMediaFormat.BlobUrl,\n cacheBuster?: number,\n delay?: number | false,\n) => {\n const mediaData = mediaHash ? mediaLoader.getFromMemory<T>(mediaHash) : undefined;\n const isStreaming = mediaFormat === ApiMediaFormat.Stream || (\n IS_PROGRESSIVE_SUPPORTED && mediaFormat === ApiMediaFormat.Progressive\n );\n const forceUpdate = useForceUpdate();\n const [downloadProgress, setDownloadProgress] = useState(mediaData && !isStreaming ? 1 : 0);\n const startedAtRef = useRef<number>();\n\n const handleProgress = useMemo(() => {\n return throttle((progress: number) => {\n if (!delay || (Date.now() - startedAtRef.current! > delay)) {\n setDownloadProgress(progress);\n }\n }, PROGRESS_THROTTLE, true);\n }, [delay]);\n\n useEffect(() => {\n if (!noLoad && mediaHash) {\n if (!mediaData) {\n setDownloadProgress(0);\n\n if (startedAtRef.current) {\n mediaLoader.cancelProgress(handleProgress);\n }\n\n startedAtRef.current = Date.now();\n\n mediaLoader.fetch(mediaHash, mediaFormat, handleProgress).then(() => {\n const spentTime = Date.now() - startedAtRef.current!;\n startedAtRef.current = undefined;\n\n if (!delay || spentTime >= delay) {\n forceUpdate();\n } else {\n setTimeout(forceUpdate, delay - spentTime);\n }\n });\n } else if (isStreaming) {\n setTimeout(() => {\n setDownloadProgress(STREAMING_PROGRESS);\n }, STREAMING_TIMEOUT);\n }\n }\n }, [noLoad, mediaHash, mediaData, mediaFormat, cacheBuster, forceUpdate, isStreaming, delay, handleProgress]);\n\n useEffect(() => {\n if (noLoad && startedAtRef.current) {\n mediaLoader.cancelProgress(handleProgress);\n setDownloadProgress(0);\n }\n }, [handleProgress, noLoad]);\n\n return { mediaData, downloadProgress };\n};\n","import React, {\n FC, useEffect, useRef, memo,\n} from '../../lib/teact/teact';\n\nimport buildClassName from '../../util/buildClassName';\n\nimport './ProgressSpinner.scss';\n\nconst RADIUSES = {\n s: 22, m: 25, l: 28, xl: 20,\n};\nconst STROKE_WIDTH = 2;\nconst MIN_PROGRESS = 0.05;\nconst MAX_PROGRESS = 1;\n\nconst ProgressSpinner: FC<{\n progress?: number;\n size?: 's' | 'm' | 'l' | 'xl';\n square?: boolean;\n transparent?: boolean;\n noCross?: boolean;\n onClick?: (e: React.MouseEvent<HTMLElement, MouseEvent>) => void;\n}> = ({\n progress = 0,\n size = 'l',\n square,\n transparent,\n noCross,\n onClick,\n}) => {\n const radius = RADIUSES[size];\n const circleRadius = radius - STROKE_WIDTH * 2;\n const borderRadius = radius - 1;\n const circumference = circleRadius * 2 * Math.PI;\n // eslint-disable-next-line no-null/no-null\n const container = useRef<HTMLDivElement>(null);\n\n useEffect(() => {\n if (!container.current) {\n return;\n }\n\n const svg = container.current.firstElementChild;\n const strokeDashOffset = circumference - Math.min(Math.max(MIN_PROGRESS, progress), MAX_PROGRESS) * circumference;\n\n if (!svg) {\n container.current.innerHTML = `<svg\n viewBox=\"0 0 ${borderRadius * 2} ${borderRadius * 2}\"\n height=\"${borderRadius * 2}\"\n width=\"${borderRadius * 2}\"\n >\n <circle\n stroke=\"white\"\n fill=\"transparent\"\n stroke-width=${STROKE_WIDTH}\n stroke-dasharray=\"${circumference} ${circumference}\"}\n stroke-dashoffset=\"${strokeDashOffset}\"\n stroke-linecap=\"round\"\n r=${circleRadius}\n cx=${borderRadius}\n cy=${borderRadius}\n />\n </svg>`;\n } else {\n (svg.firstElementChild as SVGElement).setAttribute('stroke-dashoffset', strokeDashOffset.toString());\n }\n }, [container, circumference, borderRadius, circleRadius, progress]);\n\n const className = buildClassName(\n `ProgressSpinner size-${size}`,\n transparent && 'transparent',\n square && 'square',\n noCross && 'no-cross',\n );\n\n return (\n <div\n ref={container}\n className={className}\n onClick={onClick}\n />\n );\n};\n\nexport default memo(ProgressSpinner);\n","import { FC, useRef, useLayoutEffect } from '../../lib/teact/teact';\nimport TeactDOM from '../../lib/teact/teact-dom';\n\ntype OwnProps = {\n containerId?: string;\n className?: string;\n children: any;\n};\n\nconst Portal: FC<OwnProps> = ({ containerId, className, children }) => {\n const elementRef = useRef(document.createElement('div'));\n\n useLayoutEffect(() => {\n const container = document.querySelector<HTMLDivElement>(containerId || '#portals');\n if (!container) {\n return undefined;\n }\n\n const element = elementRef.current;\n if (className) {\n element.classList.add(className);\n }\n\n container.appendChild(element);\n\n return () => {\n TeactDOM.render(undefined, element);\n container.removeChild(element);\n };\n }, [className, containerId]);\n\n return TeactDOM.render(children, elementRef.current);\n};\n\nexport default Portal;\n","import { MouseEvent as ReactMouseEvent } from 'react';\nimport React, {\n FC, useEffect, useCallback, memo,\n} from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { ApiChat, ApiTypingStatus } from '../../api/types';\nimport { GlobalActions, GlobalState } from '../../global/types';\nimport { MediaViewerOrigin } from '../../types';\n\nimport {\n getChatTypeString,\n getChatTitle,\n isChatSuperGroup,\n} from '../../modules/helpers';\nimport { selectChat, selectChatMessages, selectChatOnlineCount } from '../../modules/selectors';\nimport renderText from './helpers/renderText';\nimport { pick } from '../../util/iteratees';\nimport useLang, { LangFn } from '../../hooks/useLang';\n\nimport Avatar from './Avatar';\nimport VerifiedIcon from './VerifiedIcon';\nimport TypingStatus from './TypingStatus';\n\ntype OwnProps = {\n chatId: number;\n typingStatus?: ApiTypingStatus;\n avatarSize?: 'small' | 'medium' | 'large' | 'jumbo';\n withMediaViewer?: boolean;\n withUsername?: boolean;\n withFullInfo?: boolean;\n withUpdatingStatus?: boolean;\n withChatType?: boolean;\n noRtl?: boolean;\n};\n\ntype StateProps = {\n chat?: ApiChat;\n onlineCount?: number;\n areMessagesLoaded: boolean;\n} & Pick<GlobalState, 'lastSyncTime'>;\n\ntype DispatchProps = Pick<GlobalActions, 'loadFullChat' | 'openMediaViewer'>;\n\nconst GroupChatInfo: FC<OwnProps & StateProps & DispatchProps> = ({\n typingStatus,\n avatarSize = 'medium',\n withMediaViewer,\n withUsername,\n withFullInfo,\n withUpdatingStatus,\n withChatType,\n noRtl,\n chat,\n onlineCount,\n areMessagesLoaded,\n lastSyncTime,\n loadFullChat,\n openMediaViewer,\n}) => {\n const isSuperGroup = chat && isChatSuperGroup(chat);\n const { id: chatId, isMin, isRestricted } = chat || {};\n\n useEffect(() => {\n if (chatId && !isMin && withFullInfo && lastSyncTime) {\n loadFullChat({ chatId });\n }\n }, [chatId, isMin, lastSyncTime, withFullInfo, loadFullChat, isSuperGroup]);\n\n const handleAvatarViewerOpen = useCallback((e: ReactMouseEvent<HTMLDivElement, MouseEvent>, hasPhoto: boolean) => {\n if (chat && hasPhoto) {\n e.stopPropagation();\n openMediaViewer({\n avatarOwnerId: chat.id,\n origin: avatarSize === 'jumbo' ? MediaViewerOrigin.ProfileAvatar : MediaViewerOrigin.MiddleHeaderAvatar,\n });\n }\n }, [chat, avatarSize, openMediaViewer]);\n\n const lang = useLang();\n\n if (!chat) {\n return undefined;\n }\n\n function renderStatusOrTyping() {\n if (withUpdatingStatus && !areMessagesLoaded && !isRestricted) {\n return (\n <span className=\"status\" dir=\"auto\">{lang('Updating')}</span>\n );\n }\n\n if (!chat) {\n return undefined;\n }\n\n if (typingStatus) {\n return <TypingStatus typingStatus={typingStatus} />;\n }\n\n if (withChatType) {\n return (\n <div className=\"status\" dir=\"auto\">{lang(getChatTypeString(chat))}</div>\n );\n }\n\n const handle = withUsername ? chat.username : undefined;\n const groupStatus = getGroupStatus(lang, chat);\n const onlineStatus = onlineCount ? `, ${lang('OnlineCount', onlineCount, 'i')}` : undefined;\n\n return (\n <div className=\"status\">\n {handle && <span className=\"handle\">{handle}</span>}\n <span className=\"group-status\">{groupStatus}</span>\n {onlineStatus && <span className=\"online-status\">{onlineStatus}</span>}\n </div>\n );\n }\n\n return (\n <div className=\"ChatInfo\" dir={!noRtl && lang.isRtl ? 'rtl' : undefined}>\n <Avatar\n key={chat.id}\n size={avatarSize}\n chat={chat}\n onClick={withMediaViewer ? handleAvatarViewerOpen : undefined}\n />\n <div className=\"info\">\n <div className=\"title\">\n <h3 dir=\"auto\">{renderText(getChatTitle(lang, chat))}</h3>\n {chat.isVerified && <VerifiedIcon />}\n </div>\n {renderStatusOrTyping()}\n </div>\n </div>\n );\n};\n\nfunction getGroupStatus(lang: LangFn, chat: ApiChat) {\n const chatTypeString = lang(getChatTypeString(chat));\n const { membersCount } = chat;\n\n if (chat.isRestricted) {\n return chatTypeString === 'Channel' ? 'channel is inaccessible' : 'group is inaccessible';\n }\n\n if (!membersCount) {\n return chatTypeString;\n }\n\n return chatTypeString === 'Channel'\n ? lang('Subscribers', membersCount, 'i')\n : lang('Members', membersCount, 'i');\n}\n\nexport default memo(withGlobal<OwnProps>(\n (global, { chatId }): StateProps => {\n const { lastSyncTime } = global;\n const chat = selectChat(global, chatId);\n const onlineCount = chat ? selectChatOnlineCount(global, chat) : undefined;\n const areMessagesLoaded = Boolean(selectChatMessages(global, chatId));\n\n return {\n lastSyncTime, chat, onlineCount, areMessagesLoaded,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, ['loadFullChat', 'openMediaViewer']),\n)(GroupChatInfo));\n","import { FocusDirection } from '../types';\n\nimport { dispatchHeavyAnimationEvent } from '../hooks/useHeavyAnimationCheck';\nimport { fastRaf } from './schedulers';\nimport { animateSingle } from './animation';\n\nconst MAX_DISTANCE = 1500;\nconst MIN_JS_DURATION = 250;\nconst MAX_JS_DURATION = 600;\n\nlet isAnimating = false;\n\nexport default function fastSmoothScroll(\n container: HTMLElement,\n element: HTMLElement,\n position: ScrollLogicalPosition,\n margin = 0,\n maxDistance = MAX_DISTANCE,\n forceDirection?: FocusDirection,\n forceDuration?: number,\n forceCurrentContainerHeight?: boolean,\n) {\n if (forceDirection === FocusDirection.Static) {\n element.scrollIntoView({ block: position });\n\n return;\n }\n\n const { offsetTop } = element;\n\n if (forceDirection === undefined) {\n const offset = offsetTop - container.scrollTop;\n\n if (offset < -maxDistance) {\n container.scrollTop += (offset + maxDistance);\n } else if (offset > maxDistance) {\n container.scrollTop += (offset - maxDistance);\n }\n } else if (forceDirection === FocusDirection.Up) {\n container.scrollTop = offsetTop + maxDistance;\n } else if (forceDirection === FocusDirection.Down) {\n container.scrollTop = Math.max(0, offsetTop - maxDistance);\n }\n\n isAnimating = true;\n fastRaf(() => {\n scrollWithJs(container, element, position, margin, forceDuration, forceCurrentContainerHeight);\n });\n}\n\nexport function isAnimatingScroll() {\n return isAnimating;\n}\n\nfunction scrollWithJs(\n container: HTMLElement,\n element: HTMLElement,\n position: ScrollLogicalPosition,\n margin = 0,\n forceDuration?: number,\n forceCurrentContainerHeight?: boolean,\n) {\n const { offsetTop: elementTop, offsetHeight: elementHeight } = element;\n const { scrollTop, offsetHeight: containerHeight, scrollHeight } = container;\n const targetContainerHeight = !forceCurrentContainerHeight && container.dataset.normalHeight\n ? Number(container.dataset.normalHeight)\n : containerHeight;\n\n let path!: number;\n\n switch (position) {\n case 'start':\n path = (elementTop - margin) - scrollTop;\n break;\n case 'end':\n path = (elementTop + elementHeight + margin) - (scrollTop + targetContainerHeight);\n break;\n // 'nearest' is not supported yet\n case 'nearest':\n case 'center':\n path = elementHeight < targetContainerHeight\n ? (elementTop + elementHeight / 2) - (scrollTop + targetContainerHeight / 2)\n : (elementTop - margin) - scrollTop;\n break;\n }\n\n if (path < 0) {\n const remainingPath = -scrollTop;\n path = Math.max(path, remainingPath);\n } else if (path > 0) {\n const remainingPath = scrollHeight - (scrollTop + targetContainerHeight);\n path = Math.min(path, remainingPath);\n }\n\n const target = container.scrollTop + path;\n const duration = forceDuration || (\n MIN_JS_DURATION + (Math.abs(path) / MAX_DISTANCE) * (MAX_JS_DURATION - MIN_JS_DURATION)\n );\n const startAt = Date.now();\n\n dispatchHeavyAnimationEvent(duration);\n animateSingle(() => {\n const t = Math.min((Date.now() - startAt) / duration, 1);\n\n const currentPath = path * (1 - transition(t));\n container.scrollTop = Math.round(target - currentPath);\n\n isAnimating = t < 1;\n\n return isAnimating;\n });\n}\n\nfunction transition(t: number) {\n return 1 - ((1 - t) ** 3.5);\n}\n","import { ChangeEvent } from 'react';\nimport React, { FC, memo } from '../../lib/teact/teact';\n\nimport buildClassName from '../../util/buildClassName';\nimport useLang from '../../hooks/useLang';\n\nimport Spinner from './Spinner';\n\nimport './Radio.scss';\n\ntype OwnProps = {\n id?: string;\n name: string;\n label: string;\n subLabel?: string;\n value: string;\n checked: boolean;\n disabled?: boolean;\n hidden?: boolean;\n isLoading?: boolean;\n onChange: (e: ChangeEvent<HTMLInputElement>) => void;\n};\n\nconst Radio: FC<OwnProps> = ({\n id,\n label,\n subLabel,\n value,\n name,\n checked,\n disabled,\n hidden,\n isLoading,\n onChange,\n}) => {\n const lang = useLang();\n const className = buildClassName(\n 'Radio',\n disabled && 'disabled',\n hidden && 'hidden-widget',\n isLoading && 'loading',\n );\n\n return (\n <label className={className} dir={lang.isRtl ? 'rtl' : undefined}>\n <input\n type=\"radio\"\n name={name}\n value={value}\n id={id}\n checked={checked}\n onChange={onChange}\n disabled={disabled || hidden}\n />\n <div className=\"Radio-main\">\n <span className=\"label\" dir=\"auto\">{label}</span>\n {subLabel && <span className=\"subLabel\" dir=\"auto\">{subLabel}</span>}\n </div>\n {isLoading && <Spinner />}\n </label>\n );\n};\n\nexport default memo(Radio);\n","import { ChangeEvent } from 'react';\nimport React, { FC, useCallback, memo } from '../../lib/teact/teact';\n\nimport Radio from './Radio';\n\ntype IRadioOption = {\n label: string;\n subLabel?: string;\n value: string;\n hidden?: boolean;\n};\n\ntype OwnProps = {\n id?: string;\n name: string;\n options: IRadioOption[];\n selected?: string;\n disabled?: boolean;\n loadingOption?: string;\n onChange: (value: string) => void;\n};\n\nconst RadioGroup: FC<OwnProps> = ({\n id,\n name,\n options,\n selected,\n disabled,\n loadingOption,\n onChange,\n}) => {\n const handleChange = useCallback((event: ChangeEvent<HTMLInputElement>) => {\n const { value } = event.currentTarget;\n onChange(value);\n }, [onChange]);\n\n return (\n <div id={id} className=\"radio-group\">\n {options.map((option) => (\n <Radio\n name={name}\n label={option.label}\n subLabel={option.subLabel}\n value={option.value}\n checked={option.value === selected}\n hidden={option.hidden}\n disabled={disabled}\n isLoading={loadingOption ? loadingOption === option.value : undefined}\n onChange={handleChange}\n />\n ))}\n </div>\n );\n};\n\nexport default memo(RadioGroup);\n","import { useCallback, useEffect, useRef } from '../lib/teact/teact';\nimport { LoadMoreDirection } from '../types';\n\nimport { areSortedArraysEqual } from '../util/iteratees';\nimport useForceUpdate from './useForceUpdate';\nimport usePrevious from './usePrevious';\n\ntype GetMore = (args: { direction: LoadMoreDirection }) => void;\ntype LoadMoreBackwards = (args: { offsetId?: number }) => void;\n\nconst DEFAULT_LIST_SLICE = 30;\n\nexport default (\n loadMoreBackwards?: LoadMoreBackwards,\n listIds?: number[],\n isDisabled = false,\n listSlice = DEFAULT_LIST_SLICE,\n forceFullPreload = false,\n): [number[]?, GetMore?] => {\n const lastParamsRef = useRef<{\n direction?: LoadMoreDirection;\n offsetId?: number;\n }>();\n\n const viewportIdsRef = useRef<number[] | undefined>((() => {\n // Only run once to initialize\n if (!listIds || lastParamsRef.current) {\n return undefined;\n }\n\n const { newViewportIds } = getViewportSlice(listIds, listIds[0], LoadMoreDirection.Forwards, listSlice);\n return newViewportIds;\n })());\n\n const forceUpdate = useForceUpdate();\n\n const prevListIds = usePrevious(listIds);\n const prevIsDisabled = usePrevious(isDisabled);\n if (listIds && !isDisabled && (listIds !== prevListIds || isDisabled !== prevIsDisabled)) {\n const { offsetId = listIds[0], direction = LoadMoreDirection.Forwards } = lastParamsRef.current || {};\n const { newViewportIds } = getViewportSlice(listIds, offsetId, direction, listSlice);\n\n if (!viewportIdsRef.current || !areSortedArraysEqual(viewportIdsRef.current, newViewportIds)) {\n viewportIdsRef.current = newViewportIds;\n }\n }\n\n useEffect(() => {\n if (listIds && !isDisabled && loadMoreBackwards && forceFullPreload) {\n const viewportIds = viewportIdsRef.current!;\n loadMoreBackwards({ offsetId: viewportIds[viewportIds.length - 1] });\n }\n }, [listIds, isDisabled, loadMoreBackwards, forceFullPreload]);\n\n const getMore: GetMore = useCallback(({ direction }: { direction: LoadMoreDirection }) => {\n const viewportIds = viewportIdsRef.current;\n\n const offsetId = viewportIds\n ? direction === LoadMoreDirection.Backwards ? viewportIds[viewportIds.length - 1] : viewportIds[0]\n : undefined;\n\n if (!listIds) {\n if (loadMoreBackwards) {\n loadMoreBackwards({ offsetId });\n }\n\n return;\n }\n\n lastParamsRef.current = { ...lastParamsRef.current, direction, offsetId };\n\n const {\n newViewportIds, areSomeLocal, areAllLocal,\n } = getViewportSlice(listIds, offsetId, direction, listSlice);\n\n if (areSomeLocal && !(viewportIds && areSortedArraysEqual(viewportIds, newViewportIds))) {\n viewportIdsRef.current = newViewportIds;\n forceUpdate();\n }\n\n if (!areAllLocal && loadMoreBackwards) {\n loadMoreBackwards({ offsetId });\n }\n }, [listIds, listSlice, loadMoreBackwards, forceUpdate]);\n\n return isDisabled ? [listIds] : [viewportIdsRef.current, getMore];\n};\n\nfunction getViewportSlice(\n sourceIds: number[],\n offsetId = 0,\n direction: LoadMoreDirection,\n listSlice: number,\n) {\n const { length } = sourceIds;\n const index = sourceIds.indexOf(offsetId);\n const isForwards = direction === LoadMoreDirection.Forwards;\n const indexForDirection = isForwards ? index : (index + 1) || length;\n const from = Math.max(0, indexForDirection - listSlice);\n const to = indexForDirection + listSlice - 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.Forwards:\n areSomeLocal = indexForDirection > 0;\n areAllLocal = from >= 0;\n break;\n case LoadMoreDirection.Backwards:\n areSomeLocal = indexForDirection < length;\n areAllLocal = to <= length - 1;\n break;\n }\n\n return { newViewportIds, areSomeLocal, areAllLocal };\n}\n","import React, {\n FC, useCallback, useRef, useState,\n} from '../../lib/teact/teact';\n\nimport { ApiMediaFormat, ApiSticker } from '../../api/types';\n\nimport { STICKER_SIZE_TWO_FA } from '../../config';\nimport { getStickerDimensions } from './helpers/mediaDimensions';\nimport { ObserveFn, useIsIntersecting } from '../../hooks/useIntersectionObserver';\nimport useMedia from '../../hooks/useMedia';\nimport useTransitionForMedia from '../../hooks/useTransitionForMedia';\nimport useFlag from '../../hooks/useFlag';\n\nimport AnimatedSticker from './AnimatedSticker';\n\nimport './AnimatedEmoji.scss';\n\ntype OwnProps = {\n sticker: ApiSticker;\n observeIntersection?: ObserveFn;\n isInline?: boolean;\n lastSyncTime?: number;\n};\n\nconst QUALITY = 1;\nconst RESIZE_FACTOR = 0.5;\n\nconst AnimatedEmoji: FC<OwnProps> = ({\n sticker, isInline = false, observeIntersection, lastSyncTime,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const ref = useRef<HTMLDivElement>(null);\n\n const [isAnimationLoaded, markAnimationLoaded] = useFlag();\n const localMediaHash = `sticker${sticker.id}`;\n\n const isIntersecting = useIsIntersecting(ref, observeIntersection);\n\n const previewBlobUrl = useMedia(`${localMediaHash}?size=m`, !isIntersecting, ApiMediaFormat.BlobUrl, lastSyncTime);\n const { transitionClassNames } = useTransitionForMedia(previewBlobUrl, 'slow');\n\n const mediaData = useMedia(localMediaHash, !isIntersecting, ApiMediaFormat.Lottie, lastSyncTime);\n const isMediaLoaded = Boolean(mediaData);\n\n const [playKey, setPlayKey] = useState(String(Math.random()));\n const handleClick = useCallback(() => {\n setPlayKey(String(Math.random()));\n }, []);\n\n let width: number;\n if (isInline) {\n width = getStickerDimensions(sticker).width * RESIZE_FACTOR;\n } else {\n width = STICKER_SIZE_TWO_FA;\n }\n\n const style = `width: ${width}px; height: ${width}px;`;\n\n return (\n <div\n ref={ref}\n className=\"AnimatedEmoji media-inner\"\n // @ts-ignore\n style={style}\n onClick={handleClick}\n >\n {previewBlobUrl && !isAnimationLoaded && (\n <img src={previewBlobUrl} className={transitionClassNames} alt=\"\" />\n )}\n {isMediaLoaded && (\n <AnimatedSticker\n key={localMediaHash}\n id={localMediaHash}\n animationData={mediaData as AnyLiteral}\n size={width}\n quality={QUALITY}\n play={isIntersecting && playKey}\n noLoop\n onLoad={markAnimationLoaded}\n />\n )}\n </div>\n );\n};\n\nexport default AnimatedEmoji;\n","export default function focusEditableElement(element: HTMLElement, force?: boolean) {\n if (!force && element === document.activeElement) {\n return;\n }\n const selection = window.getSelection()!;\n const range = document.createRange();\n\n if (!element.lastChild || !element.lastChild.nodeValue) {\n element.focus();\n return;\n }\n\n range.setStart(element.lastChild, element.lastChild.nodeValue.length);\n selection.removeAllRanges();\n selection.addRange(range);\n}\n","import { useEffect } from '../lib/teact/teact';\n\nexport default (\n onBlur: AnyToVoidFunction,\n onFocus: AnyToVoidFunction,\n) => {\n useEffect(() => {\n if (!document.hasFocus()) {\n onBlur();\n }\n\n window.addEventListener('blur', onBlur);\n window.addEventListener('focus', onFocus);\n\n return () => {\n window.removeEventListener('focus', onFocus);\n window.removeEventListener('blur', onBlur);\n };\n }, [onBlur, onFocus]);\n};\n","export enum SwipeDirection {\n Up,\n Down,\n Left,\n Right,\n}\n\ninterface CaptureOptions {\n onCapture?: (e: MouseEvent | TouchEvent) => void;\n onRelease?: (e: MouseEvent | TouchEvent) => void;\n onDrag?: (\n e: MouseEvent | TouchEvent,\n captureEvent: MouseEvent | TouchEvent,\n params: {\n dragOffsetX: number;\n dragOffsetY: number;\n },\n ) => void;\n onSwipe?: (e: Event, direction: SwipeDirection) => void;\n onClick?: (e: MouseEvent | TouchEvent) => void;\n excludedClosestSelector?: string;\n withCursor?: boolean;\n}\n\n// https://stackoverflow.com/questions/11287877/how-can-i-get-e-offsetx-on-mobile-ipad\n// Android does not have this value, and iOS has it but as read-only\nexport interface RealTouchEvent extends TouchEvent {\n pageX?: number;\n pageY?: number;\n}\n\ntype TSwipeAxis = 'x' | 'y' | undefined;\n\nconst MOVED_THRESHOLD = 15;\nconst SWIPE_THRESHOLD = 50;\n\nexport function captureEvents(element: HTMLElement, options: CaptureOptions) {\n let captureEvent: MouseEvent | RealTouchEvent | undefined;\n let hasMoved = false;\n let currentSwipeAxis: TSwipeAxis;\n\n function onCapture(e: MouseEvent | RealTouchEvent) {\n if (options.excludedClosestSelector && (\n (e.target as HTMLElement).matches(options.excludedClosestSelector)\n || (e.target as HTMLElement).closest(options.excludedClosestSelector)\n )) {\n return;\n }\n\n captureEvent = e;\n\n if (e.type === 'mousedown') {\n document.addEventListener('mousemove', onMove);\n document.addEventListener('mouseup', onRelease);\n } else if (e.type === 'touchstart') {\n document.addEventListener('touchmove', onMove);\n document.addEventListener('touchend', onRelease);\n document.addEventListener('touchcancel', onRelease);\n\n if ('touches' in e) {\n if (e.pageX === undefined) {\n e.pageX = e.touches[0].pageX;\n }\n\n if (e.pageY === undefined) {\n e.pageY = e.touches[0].pageY;\n }\n }\n }\n\n document.body.classList.add('no-selection');\n if (options.withCursor) {\n document.body.classList.add('cursor-grabbing');\n }\n\n if (options.onCapture) {\n options.onCapture(e);\n }\n }\n\n function onRelease(e: MouseEvent | TouchEvent) {\n if (captureEvent) {\n if (options.withCursor) {\n document.body.classList.remove('cursor-grabbing');\n }\n document.body.classList.remove('no-selection');\n\n document.removeEventListener('mouseup', onRelease);\n document.removeEventListener('mousemove', onMove);\n document.removeEventListener('touchcancel', onRelease);\n document.removeEventListener('touchend', onRelease);\n document.removeEventListener('touchmove', onMove);\n\n captureEvent = undefined;\n\n if (hasMoved) {\n if (options.onRelease) {\n options.onRelease(e);\n }\n } else if (options.onClick) {\n options.onClick(e);\n }\n }\n\n hasMoved = false;\n currentSwipeAxis = undefined;\n }\n\n function onMove(e: MouseEvent | RealTouchEvent) {\n if (captureEvent) {\n if (e.type === 'touchmove' && ('touches' in e)) {\n if (e.pageX === undefined) {\n e.pageX = e.touches[0].pageX;\n }\n\n if (e.pageY === undefined) {\n e.pageY = e.touches[0].pageY;\n }\n }\n\n const dragOffsetX = e.pageX! - captureEvent.pageX!;\n const dragOffsetY = e.pageY! - captureEvent.pageY!;\n\n if (Math.abs(dragOffsetX) >= MOVED_THRESHOLD || Math.abs(dragOffsetY) >= MOVED_THRESHOLD) {\n hasMoved = true;\n }\n\n if (options.onDrag) {\n e.preventDefault();\n options.onDrag(e, captureEvent, { dragOffsetX, dragOffsetY });\n }\n\n if (options.onSwipe) {\n onSwipe(e, dragOffsetX, dragOffsetY);\n }\n }\n }\n\n function onSwipe(e: Event, dragOffsetX: number, dragOffsetY: number) {\n if (!currentSwipeAxis) {\n const xAbs = Math.abs(dragOffsetX);\n const yAbs = Math.abs(dragOffsetY);\n\n if (dragOffsetX && dragOffsetY) {\n const ratio = Math.max(xAbs, yAbs) / Math.min(xAbs, yAbs);\n // Diagonal swipe\n if (ratio < 2) {\n return;\n }\n }\n\n if (xAbs >= SWIPE_THRESHOLD) {\n currentSwipeAxis = 'x';\n } else if (yAbs >= SWIPE_THRESHOLD) {\n currentSwipeAxis = 'y';\n }\n }\n\n processSwipe(e, currentSwipeAxis, dragOffsetX, dragOffsetY, options.onSwipe!);\n }\n\n element.addEventListener('mousedown', onCapture);\n element.addEventListener('touchstart', onCapture, { passive: true });\n\n return () => {\n element.removeEventListener('mousedown', onCapture);\n element.removeEventListener('touchstart', onCapture);\n };\n}\n\nfunction processSwipe(\n e: Event,\n currentSwipeAxis:TSwipeAxis,\n dragOffsetX: number,\n dragOffsetY: number,\n onSwipe: (e: Event, direction: SwipeDirection) => void,\n) {\n if (currentSwipeAxis === 'x') {\n if (dragOffsetX < 0) {\n onSwipe(e, SwipeDirection.Left);\n } else {\n onSwipe(e, SwipeDirection.Right);\n }\n } else if (currentSwipeAxis === 'y') {\n if (dragOffsetY < 0) {\n onSwipe(e, SwipeDirection.Up);\n } else {\n onSwipe(e, SwipeDirection.Down);\n }\n }\n}\n","import React, { FC } from '../../lib/teact/teact';\n\nimport './VerifiedIcon.scss';\n\nconst VerifiedIcon: FC = () => {\n return (\n <span className=\"VerifiedIcon\" />\n );\n};\n\nexport default VerifiedIcon;\n","export default function cycleRestrict(length: number, index: number) {\n return index - Math.floor(index / length) * length;\n}\n","import usePrevious from './usePrevious';\n\nexport default function useCurrentOrPrev<T extends any>(\n current: T, shouldSkipUndefined = false, shouldForceCurrent = false,\n): T | undefined {\n const prev = usePrevious(current, shouldSkipUndefined);\n\n // eslint-disable-next-line no-null/no-null\n return shouldForceCurrent || (current !== null && current !== undefined) ? current : prev;\n}\n","import { DEBUG } from '../config';\n\nexport default (mediaEl: HTMLMediaElement) => {\n mediaEl.play().catch((err) => {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.warn(err);\n }\n });\n};\n","import React, { useCallback, useMemo, useState } from '../lib/teact/teact';\nimport { debounce } from '../util/schedulers';\nimport { isSafariPatchInProgress } from '../util/patchSafariProgressiveAudio';\n\ntype BufferingEvent = (e: Event | React.SyntheticEvent<HTMLMediaElement>) => void;\n\nconst MIN_READY_STATE = 3;\n// Avoid flickering when re-mounting previously buffered video\nconst DEBOUNCE = 200;\n\nexport default (noInitiallyBuffered = false) => {\n const [isBuffered, setIsBuffered] = useState(!noInitiallyBuffered);\n const [bufferedProgress, setBufferedProgress] = useState(0);\n\n const setIsBufferedDebounced = useMemo(() => {\n return debounce(setIsBuffered, DEBOUNCE, false, true);\n }, []);\n\n const handleBuffering = useCallback<BufferingEvent>((e) => {\n const media = e.currentTarget as HTMLMediaElement;\n\n if (!isSafariPatchInProgress(media)) {\n if (media.buffered.length) {\n setBufferedProgress(media.buffered.end(0) / media.duration);\n }\n\n setIsBufferedDebounced(media.readyState >= MIN_READY_STATE || media.currentTime > 0);\n }\n }, [setIsBufferedDebounced]);\n\n const bufferingHandlers = {\n onLoadedData: handleBuffering,\n onPlaying: handleBuffering,\n onLoadStart: handleBuffering, // Needed for Safari to start\n onPause: handleBuffering, // Needed for Chrome when seeking\n onTimeUpdate: handleBuffering, // Needed for audio buffering progress\n onProgress: handleBuffering, // Needed for video buffering progress\n };\n\n return {\n isBuffered,\n bufferedProgress,\n bufferingHandlers,\n checkBuffering(element: HTMLMediaElement) {\n setIsBufferedDebounced(element.readyState >= MIN_READY_STATE);\n },\n };\n};\n","import { ApiMessageEntity, ApiMessageEntityTypes, ApiFormattedText } from '../../../../api/types';\nimport { IS_EMOJI_SUPPORTED } from '../../../../util/environment';\n\nconst ENTITY_CLASS_BY_NODE_NAME: Record<string, string> = {\n B: ApiMessageEntityTypes.Bold,\n STRONG: ApiMessageEntityTypes.Bold,\n I: ApiMessageEntityTypes.Italic,\n EM: ApiMessageEntityTypes.Italic,\n U: ApiMessageEntityTypes.Underline,\n S: ApiMessageEntityTypes.Strike,\n STRIKE: ApiMessageEntityTypes.Strike,\n DEL: ApiMessageEntityTypes.Strike,\n CODE: ApiMessageEntityTypes.Code,\n PRE: ApiMessageEntityTypes.Pre,\n BLOCKQUOTE: ApiMessageEntityTypes.Blockquote,\n};\n\nconst MAX_TAG_DEEPNESS = 3;\nconst MAX_MESSAGE_LENGTH = 4096;\n\nexport default function parseMessageInput(html: string): ApiFormattedText {\n const fragment = document.createElement('div');\n fragment.innerHTML = parseMarkdown(html);\n const text = fragment.innerText.trim().replace(/\\u200b+/g, '').slice(0, MAX_MESSAGE_LENGTH);\n let textIndex = 0;\n let recursionDeepness = 0;\n const entities: ApiMessageEntity[] = [];\n\n function addEntity(node: ChildNode) {\n const { index, entity } = getEntityDataFromNode(node, text, textIndex);\n\n if (entity) {\n textIndex = index;\n entities.push(entity);\n } else if (node.textContent) {\n textIndex += node.textContent.length;\n }\n\n if (node.hasChildNodes() && recursionDeepness <= MAX_TAG_DEEPNESS) {\n recursionDeepness += 1;\n Array.from(node.childNodes).forEach(addEntity);\n }\n }\n\n Array.from(fragment.childNodes).forEach((node) => {\n recursionDeepness = 1;\n addEntity(node);\n });\n\n return {\n text,\n entities: entities.length ? entities : undefined,\n };\n}\n\nfunction parseMarkdown(html: string) {\n let parsedHtml = html.slice(0);\n\n if (!IS_EMOJI_SUPPORTED) {\n // Emojis\n parsedHtml = parsedHtml.replace(/<img[^>]+alt=\"([^\"]+)\"[^>]*>/gm, '$1');\n } else {\n parsedHtml = parsedHtml.replace(/<span\\s+class=\"font-emoji\">([^<]*)<\\/span>/g, '$1');\n }\n // Strip redundant <span> tags\n parsedHtml = parsedHtml.replace(/<\\/?span([^>]*)?>/g, '');\n\n // Strip redundant nbsp's\n parsedHtml = parsedHtml.replace(/&nbsp;/g, ' ');\n\n // Replace <br> with newline\n parsedHtml = parsedHtml.replace(/<br([^>]*)?>/g, '\\n');\n\n // Strip redundant <div> tags\n parsedHtml = parsedHtml.replace(/<\\/div>(\\s*)<div>/g, '\\n');\n parsedHtml = parsedHtml.replace(/<div>/g, '\\n');\n parsedHtml = parsedHtml.replace(/<\\/div>/g, '');\n\n // Pre\n parsedHtml = parsedHtml.replace(/^`{3}(.*[\\n\\r][^]*?^)`{3}/gm, '<pre>$1</pre>');\n parsedHtml = parsedHtml.replace(/[`]{3}([^`]+)[`]{3}/g, '<pre>$1</pre>');\n\n // Code\n parsedHtml = parsedHtml.replace(/[`]{1}([^`\\n]+)[`]{1}/g, '<code>$1</code>');\n\n // Other simple markdown\n parsedHtml = parsedHtml.replace(/[*]{2}([^*\\n]+)[*]{2}/g, '<b>$1</b>');\n parsedHtml = parsedHtml.replace(/[*]{1}([^*\\n]+)[*]{1}/g, '<i>$1</i>');\n parsedHtml = parsedHtml.replace(/[~]{2}([^~\\n]+)[~]{2}/g, '<s>$1</s>');\n\n return parsedHtml;\n}\n\nfunction getEntityDataFromNode(\n node: ChildNode,\n rawText: string,\n textIndex: number,\n): { index: number; entity?: ApiMessageEntity } {\n const type = getEntityTypeFromNode(node);\n if (!type || !node.textContent) {\n return {\n index: textIndex,\n entity: undefined,\n };\n }\n\n const rawIndex = rawText.indexOf(node.textContent, textIndex);\n // In some cases, last text entity ends with a newline (which gets trimmed from `rawText`).\n // In this case, `rawIndex` would return `-1`, so we use `textIndex` instead.\n const index = rawIndex >= 0 ? rawIndex : textIndex;\n const offset = rawText.substring(0, index).length;\n const { length } = rawText.substring(index, index + node.textContent.length);\n\n let url: string | undefined;\n let userId: number | undefined;\n if (type === ApiMessageEntityTypes.TextUrl) {\n url = (node as HTMLAnchorElement).href;\n }\n if (type === ApiMessageEntityTypes.MentionName) {\n userId = Number((node as HTMLAnchorElement).dataset.userId);\n }\n\n return {\n index,\n entity: {\n type,\n offset,\n length,\n ...(url && { url }),\n ...(userId && { userId }),\n },\n };\n}\n\nfunction getEntityTypeFromNode(node: ChildNode) {\n if (ENTITY_CLASS_BY_NODE_NAME[node.nodeName]) {\n return ENTITY_CLASS_BY_NODE_NAME[node.nodeName];\n }\n\n if (node.nodeName === 'A') {\n const anchor = node as HTMLAnchorElement;\n if (anchor.dataset.entityType === ApiMessageEntityTypes.MentionName) {\n return ApiMessageEntityTypes.MentionName;\n }\n if (anchor.href.startsWith('mailto:')) {\n return ApiMessageEntityTypes.Email;\n }\n if (anchor.href.startsWith('tel:')) {\n return ApiMessageEntityTypes.Phone;\n }\n if (anchor.href !== anchor.textContent) {\n return ApiMessageEntityTypes.TextUrl;\n }\n\n return ApiMessageEntityTypes.Url;\n }\n\n if (node.nodeName === 'SPAN') {\n return (node as HTMLElement).dataset.entityType;\n }\n\n return undefined;\n}\n","import React, { FC, memo } from '../../../lib/teact/teact';\n\nimport useFlag from '../../../hooks/useFlag';\nimport buildClassName from '../../../util/buildClassName';\n\nimport './DropTarget.scss';\n\nexport type OwnProps = {\n isQuick?: boolean;\n onFileSelect: (e: React.DragEvent<HTMLDivElement>) => void;\n};\n\nconst DropTarget: FC<OwnProps> = ({ isQuick, onFileSelect }) => {\n const [isHovered, markHovered, unmarkHovered] = useFlag();\n\n const handleDragEnter = () => { markHovered(); };\n const handleDragLeave = (e: React.DragEvent<HTMLDivElement>) => {\n const { relatedTarget: toTarget } = e;\n\n if (toTarget) {\n e.stopPropagation();\n }\n\n unmarkHovered();\n };\n\n const className = buildClassName(\n 'DropTarget',\n isHovered && 'hovered',\n );\n\n return (\n <div\n className={className}\n onDrop={onFileSelect}\n onDragEnter={handleDragEnter}\n onDragLeave={handleDragLeave}\n >\n <div className=\"target-content\">\n <div className={`icon icon-${isQuick ? 'photo' : 'document'}`} />\n <div className=\"title\">Drop files here to send them</div>\n <div className=\"description\">{isQuick ? 'in a quick way' : 'without compression'}</div>\n </div>\n </div>\n );\n};\n\nexport default memo(DropTarget);\n","import React, {\n FC, memo, useCallback, useEffect, useRef,\n} from '../../../lib/teact/teact';\n\nimport useShowTransition from '../../../hooks/useShowTransition';\nimport buildClassName from '../../../util/buildClassName';\n\nimport captureEscKeyListener from '../../../util/captureEscKeyListener';\nimport usePrevious from '../../../hooks/usePrevious';\n\nimport DropTarget from './DropTarget';\n\nimport './DropArea.scss';\n\nexport type OwnProps = {\n isOpen: boolean;\n withQuick?: boolean;\n onHide: NoneToVoidFunction;\n onFileSelect: (files: File[], isQuick: boolean) => void;\n};\n\nexport enum DropAreaState {\n None = 'none',\n Document = 'document',\n QuickFile = 'quick_file',\n}\n\nconst DROP_LEAVE_TIMEOUT_MS = 150;\n\nconst DropArea: FC<OwnProps> = ({\n isOpen, withQuick, onHide, onFileSelect,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const hideTimeoutRef = useRef<number>(null);\n const prevWithQuick = usePrevious(withQuick);\n const { shouldRender, transitionClassNames } = useShowTransition(isOpen);\n\n useEffect(() => (isOpen ? captureEscKeyListener(onHide) : undefined), [isOpen, onHide]);\n\n const handleFilesDrop = useCallback((e: React.DragEvent<HTMLDivElement>) => {\n const { dataTransfer: dt } = e;\n\n if (dt.files && dt.files.length > 0) {\n onHide();\n onFileSelect(Array.from(dt.files), false);\n }\n }, [onFileSelect, onHide]);\n\n const handleQuickFilesDrop = useCallback((e: React.DragEvent<HTMLDivElement>) => {\n const { dataTransfer: dt } = e;\n\n if (dt.files && dt.files.length > 0) {\n onHide();\n onFileSelect(Array.from(dt.files), true);\n }\n }, [onFileSelect, onHide]);\n\n const handleDragLeave = useCallback((e: React.DragEvent<HTMLDivElement>) => {\n e.stopPropagation();\n\n const { target: fromTarget, relatedTarget: toTarget } = e;\n\n // Esc button pressed during drag event\n if ((fromTarget as HTMLDivElement).matches('.DropTarget, .DropArea') && !toTarget) {\n hideTimeoutRef.current = window.setTimeout(() => {\n onHide();\n }, DROP_LEAVE_TIMEOUT_MS);\n }\n }, [onHide]);\n\n const handleDragOver = () => {\n if (hideTimeoutRef.current) {\n window.clearTimeout(hideTimeoutRef.current);\n }\n };\n\n if (!shouldRender) {\n return undefined;\n }\n\n const className = buildClassName(\n 'DropArea',\n transitionClassNames,\n );\n\n return (\n <div className={className} onDragLeave={handleDragLeave} onDragOver={handleDragOver} onDrop={onHide}>\n <DropTarget onFileSelect={handleFilesDrop} />\n {(withQuick || prevWithQuick) && <DropTarget onFileSelect={handleQuickFilesDrop} isQuick />}\n </div>\n );\n};\n\nexport default memo(DropArea);\n","import React, { FC, memo } from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { ApiChat, ApiUser } from '../../api/types';\n\nimport { selectChat, selectUser } from '../../modules/selectors';\nimport { getChatTitle, getUserFirstOrLastName, isChatPrivate } from '../../modules/helpers';\nimport renderText from './helpers/renderText';\nimport buildClassName from '../../util/buildClassName';\nimport useLang from '../../hooks/useLang';\n\nimport Avatar from './Avatar';\n\nimport './PickerSelectedItem.scss';\n\ntype OwnProps = {\n chatOrUserId?: number;\n icon?: string;\n title?: string;\n isMinimized?: boolean;\n canClose?: boolean;\n onClick: (arg: any) => void;\n clickArg: any;\n className?: string;\n};\n\ntype StateProps = {\n chat?: ApiChat;\n user?: ApiUser;\n};\n\nconst PickerSelectedItem: FC<OwnProps & StateProps> = ({\n icon,\n title,\n isMinimized,\n canClose,\n onClick,\n clickArg,\n chat,\n user,\n className,\n}) => {\n const lang = useLang();\n\n let iconElement: any;\n let titleText: any;\n\n if (icon && title) {\n iconElement = (\n <div className=\"item-icon\">\n <i className={`icon-${icon}`} />\n </div>\n );\n\n titleText = title;\n } else if (chat || user) {\n iconElement = (\n <Avatar\n chat={chat}\n user={user}\n size=\"small\"\n isSavedMessages={user && user.isSelf}\n />\n );\n\n const name = !chat || (user && !user.isSelf)\n ? getUserFirstOrLastName(user)\n : getChatTitle(lang, chat, user);\n\n titleText = name ? renderText(name) : undefined;\n }\n\n const fullClassName = buildClassName(\n 'PickerSelectedItem',\n className,\n isMinimized && 'minimized',\n canClose && 'closeable',\n );\n\n return (\n <div\n className={fullClassName}\n onClick={() => onClick(clickArg)}\n title={isMinimized ? titleText : undefined}\n dir={lang.isRtl ? 'rtl' : undefined}\n >\n {iconElement}\n {!isMinimized && (\n <div className=\"item-name\" dir=\"auto\">\n {titleText}\n </div>\n )}\n {canClose && (\n <div className=\"item-remove\">\n <i className=\"icon-close\" />\n </div>\n )}\n </div>\n );\n};\n\nexport default memo(withGlobal<OwnProps>(\n (global, { chatOrUserId }): StateProps => {\n if (!chatOrUserId) {\n return {};\n }\n\n const chat = chatOrUserId ? selectChat(global, chatOrUserId) : undefined;\n const user = isChatPrivate(chatOrUserId) ? selectUser(global, chatOrUserId) : undefined;\n\n return {\n chat,\n user,\n };\n },\n)(PickerSelectedItem));\n","import { fastRaf } from './schedulers';\nimport { animate } from './animation';\nimport { IS_IOS } from './environment';\n\nconst DURATION = 450;\n\nexport default function fastSmoothScrollHorizontal(container: HTMLElement, left: number) {\n // Native way seems to be smoother in Chrome\n if (!IS_IOS) {\n container.scrollTo({ left, behavior: 'smooth' });\n } else {\n fastRaf(() => {\n scrollWithJs(container, left);\n });\n }\n}\n\nfunction scrollWithJs(container: HTMLElement, left: number) {\n const { scrollLeft, offsetWidth: containerWidth, scrollWidth } = container;\n let path = left - scrollLeft;\n\n if (path < 0) {\n const remainingPath = -scrollLeft;\n path = Math.max(path, remainingPath);\n } else if (path > 0) {\n const remainingPath = scrollWidth - (scrollLeft + containerWidth);\n path = Math.min(path, remainingPath);\n }\n\n const target = container.scrollLeft + path;\n const startAt = Date.now();\n\n animate(() => {\n const t = Math.min((Date.now() - startAt) / DURATION, 1);\n\n const currentPath = path * (1 - transition(t));\n container.scrollLeft = Math.round(target - currentPath);\n\n return t < 1;\n });\n}\n\nfunction transition(t: number) {\n return 1 - ((1 - t) ** 3.5);\n}\n","import { RefObject } from 'react';\nimport { useEffect } from '../lib/teact/teact';\n\nexport default (containerRef: RefObject<HTMLElement>, isDisabled?: boolean) => {\n useEffect(() => {\n const container = containerRef.current;\n if (!container) {\n return undefined;\n }\n\n function handleScroll(e: WheelEvent) {\n // Ignore horizontal scroll and let it work natively (e.g. on touchpad)\n if (!e.deltaX) {\n container!.scrollLeft += e.deltaY / 4;\n }\n }\n\n container.addEventListener('wheel', handleScroll, { passive: true });\n\n return () => {\n container.removeEventListener('wheel', handleScroll);\n };\n }, [containerRef, isDisabled]);\n};\n","import { useEffect, useMemo } from '../lib/teact/teact';\nimport { getDispatch } from '../lib/teact/teactn';\n\nimport { ApiMessage } from '../api/types';\n\nimport { throttle } from '../util/schedulers';\n\nexport default (\n chatId: number,\n messageId?: number,\n message?: ApiMessage,\n replyOriginForId?: number,\n) => {\n const { loadMessage } = getDispatch();\n const loadMessageThrottled = useMemo(() => {\n const throttled = throttle(loadMessage, 500, true);\n return () => {\n throttled({ chatId, messageId, replyOriginForId });\n };\n }, [loadMessage, chatId, messageId, replyOriginForId]);\n\n useEffect(() => {\n if (messageId && !message) {\n loadMessageThrottled();\n }\n });\n};\n","import { RefObject } from 'react';\nimport { useState, useEffect, useCallback } from '../lib/teact/teact';\n\nimport { IAnchorPosition } from '../types';\nimport { IS_TOUCH_ENV, IS_MOBILE_SCREEN } from '../util/environment';\n\nconst LONG_TAP_DURATION_MS = 250;\nconst SELECTION_ANIMATION_DURATION_MS = 200;\n\nlet contextMenuCounter = 0;\n\nfunction checkIsDisabledForMobile() {\n return IS_MOBILE_SCREEN\n && window.document.body.classList.contains('enable-symbol-menu-transforms');\n}\n\nexport default (\n elementRef: RefObject<HTMLElement>,\n isMenuDisabled?: boolean,\n shouldDisableOnLink?: boolean,\n) => {\n const [isContextMenuOpen, setIsContextMenuOpen] = useState(false);\n const [contextMenuPosition, setContextMenuPosition] = useState<IAnchorPosition | undefined>(undefined);\n\n const handleBeforeContextMenu = useCallback((e: React.MouseEvent) => {\n if (!isMenuDisabled && e.button === 2) {\n document.body.classList.add('no-selection');\n }\n }, [isMenuDisabled]);\n\n const handleContextMenu = useCallback((e: React.MouseEvent) => {\n document.body.classList.remove('no-selection');\n\n if (isMenuDisabled || (shouldDisableOnLink && (e.target as HTMLElement).matches('a.text-entity-link[href]'))) {\n return;\n }\n e.preventDefault();\n\n if (contextMenuPosition) {\n return;\n }\n document.body.classList.remove('no-selection');\n if (contextMenuCounter === 0) {\n document.body.classList.add('has-context-menu');\n }\n contextMenuCounter++;\n\n setIsContextMenuOpen(true);\n setContextMenuPosition({ x: e.clientX, y: e.clientY });\n }, [isMenuDisabled, shouldDisableOnLink, contextMenuPosition]);\n\n const handleContextMenuClose = useCallback(() => {\n setIsContextMenuOpen(false);\n }, []);\n\n const handleContextMenuHide = useCallback(() => {\n setContextMenuPosition(undefined);\n document.body.classList.remove('no-selection');\n\n setTimeout(() => {\n contextMenuCounter--;\n if (contextMenuCounter === 0) {\n document.body.classList.remove('has-context-menu');\n }\n }, SELECTION_ANIMATION_DURATION_MS);\n }, []);\n\n // Support context menu on touch-devices\n useEffect(() => {\n if (isMenuDisabled || !IS_TOUCH_ENV) {\n return undefined;\n }\n\n const element = elementRef.current;\n if (!element) {\n return undefined;\n }\n\n let timer: number | undefined;\n\n const clearLongPressTimer = () => {\n if (timer) {\n clearTimeout(timer);\n timer = undefined;\n }\n };\n\n const emulateContextMenuEvent = (originalEvent: TouchEvent) => {\n clearLongPressTimer();\n\n const { clientX, clientY } = originalEvent.touches[0];\n\n if (contextMenuPosition) {\n return;\n }\n\n // temporarily intercept and clear the next click\n element.addEventListener('touchend', function cancelClickOnce(e) {\n element.removeEventListener('touchend', cancelClickOnce, true);\n e.stopImmediatePropagation();\n e.preventDefault();\n e.stopPropagation();\n }, true);\n\n document.body.classList.add('no-selection');\n setIsContextMenuOpen(true);\n setContextMenuPosition({ x: clientX, y: clientY });\n };\n\n const startLongPressTimer = (e: TouchEvent) => {\n if (isMenuDisabled || checkIsDisabledForMobile()) {\n return;\n }\n clearLongPressTimer();\n\n timer = window.setTimeout(() => emulateContextMenuEvent(e), LONG_TAP_DURATION_MS);\n };\n\n // @perf Consider event delegation\n element.addEventListener('touchstart', startLongPressTimer, { passive: true });\n element.addEventListener('touchcancel', clearLongPressTimer, true);\n element.addEventListener('touchend', clearLongPressTimer, true);\n element.addEventListener('touchmove', clearLongPressTimer, { passive: true });\n\n return () => {\n clearLongPressTimer();\n element.removeEventListener('touchstart', startLongPressTimer);\n element.removeEventListener('touchcancel', clearLongPressTimer, true);\n element.removeEventListener('touchend', clearLongPressTimer, true);\n element.removeEventListener('touchmove', clearLongPressTimer);\n };\n }, [contextMenuPosition, isMenuDisabled, elementRef]);\n\n return {\n isContextMenuOpen,\n contextMenuPosition,\n handleBeforeContextMenu,\n handleContextMenu,\n handleContextMenuClose,\n handleContextMenuHide,\n };\n};\n","import { MouseEvent } from 'react';\nimport React from '../../../lib/teact/teact';\nimport { getDispatch } from '../../../lib/teact/teactn';\n\nimport { ApiMessageEntity, ApiMessageEntityTypes, ApiMessage } from '../../../api/types';\n\nimport { getMessageText } from '../../../modules/helpers';\nimport renderText from './renderText';\n\nimport MentionLink from '../../middle/message/MentionLink';\nimport SafeLink from '../SafeLink';\n\nexport type TextPart = string | Element;\n\nexport function renderMessageText(message: ApiMessage, highlight?: string, shouldRenderHqEmoji?: boolean) {\n const formattedText = message.content.text;\n\n if (!formattedText || !formattedText.text) {\n const rawText = getMessageText(message);\n return rawText ? [rawText] : undefined;\n }\n const { text, entities } = formattedText;\n\n return renderTextWithEntities(text, entities, highlight, shouldRenderHqEmoji);\n}\n\ninterface IOrganizedEntity {\n entity: ApiMessageEntity;\n organizedIndexes: Set<number>;\n nestedEntities: IOrganizedEntity[];\n}\n\nfunction organizeEntity(\n entity: ApiMessageEntity,\n index: number,\n entities: ApiMessageEntity[],\n organizedEntityIndexes: Set<number>,\n): IOrganizedEntity | undefined {\n const { offset, length } = entity;\n const organizedIndexes = new Set([index]);\n\n if (organizedEntityIndexes.has(index)) {\n return undefined;\n }\n\n // Determine any nested entities inside current entity\n const nestedEntities = entities\n .filter((e, i) => i > index && e.offset >= offset && e.offset < offset + length)\n .map((e) => organizeEntity(e, entities.indexOf(e), entities, organizedEntityIndexes))\n .filter<IOrganizedEntity>(Boolean as any);\n\n nestedEntities.forEach((e) => e.organizedIndexes.forEach((i) => organizedIndexes.add(i)));\n\n return {\n entity,\n organizedIndexes,\n nestedEntities,\n };\n}\n\n// Organize entities in a tree-like structure to better represent how the text will be displayed\nfunction organizeEntities(entities: ApiMessageEntity[]) {\n const organizedEntityIndexes: Set<number> = new Set();\n const organizedEntities: IOrganizedEntity[] = [];\n\n entities.forEach((entity, index) => {\n if (organizedEntityIndexes.has(index)) {\n return;\n }\n\n const organizedEntity = organizeEntity(entity, index, entities, organizedEntityIndexes);\n if (organizedEntity) {\n organizedEntity.organizedIndexes.forEach((organizedIndex) => {\n organizedEntityIndexes.add(organizedIndex);\n });\n\n organizedEntities.push(organizedEntity);\n }\n });\n\n return organizedEntities;\n}\n\nexport function renderTextWithEntities(\n text: string,\n entities?: ApiMessageEntity[],\n highlight?: string,\n shouldRenderHqEmoji?: boolean,\n shouldRenderAsHtml?: boolean,\n) {\n if (!entities || !entities.length) {\n return renderMessagePart(text, highlight, shouldRenderHqEmoji, shouldRenderAsHtml);\n }\n\n const result: TextPart[] = [];\n let deleteLineBreakAfterPre = false;\n\n const organizedEntites = organizeEntities(entities);\n\n // Recursive function to render regular and nested entities\n function renderEntity(\n textPartStart: number,\n textPartEnd: number,\n organizedEntity: IOrganizedEntity,\n isLastEntity: boolean,\n ) {\n const renderResult: TextPart[] = [];\n const { entity, nestedEntities } = organizedEntity;\n const { offset, length, type } = entity;\n\n // Render text before the entity\n let textBefore = text.substring(textPartStart, offset);\n const textBeforeLength = textBefore.length;\n if (textBefore) {\n if (deleteLineBreakAfterPre && textBefore.length > 0 && textBefore[0] === '\\n') {\n textBefore = textBefore.substr(1);\n deleteLineBreakAfterPre = false;\n }\n if (textBefore) {\n renderResult.push(...renderMessagePart(\n textBefore, highlight, shouldRenderHqEmoji, shouldRenderAsHtml,\n ) as TextPart[]);\n }\n }\n\n const entityStartIndex = textPartStart + textBeforeLength;\n const entityEndIndex = entityStartIndex + length;\n\n let entityContent: TextPart = text.substring(offset, offset + length);\n const nestedEntityContent: TextPart[] = [];\n\n if (deleteLineBreakAfterPre && entityContent.length > 0 && entityContent[0] === '\\n') {\n entityContent = entityContent.substr(1);\n deleteLineBreakAfterPre = false;\n }\n\n if (type === ApiMessageEntityTypes.Pre) {\n deleteLineBreakAfterPre = true;\n }\n\n // Render nested entities, if any\n if (nestedEntities.length) {\n let nestedIndex = entityStartIndex;\n\n nestedEntities.forEach((nestedEntity, nestedEntityIndex) => {\n const {\n renderResult: nestedResult,\n entityEndIndex: nestedEntityEndIndex,\n } = renderEntity(\n nestedIndex,\n entityEndIndex,\n nestedEntity,\n nestedEntityIndex === nestedEntities.length - 1,\n );\n\n nestedEntityContent.push(...nestedResult);\n nestedIndex = nestedEntityEndIndex;\n });\n }\n\n // Render the entity itself\n const newEntity = shouldRenderAsHtml\n ? processEntityAsHtml(entity, entityContent, nestedEntityContent)\n : processEntity(entity, entityContent, nestedEntityContent);\n\n if (Array.isArray(newEntity)) {\n renderResult.push(...newEntity);\n } else {\n renderResult.push(newEntity);\n }\n\n // Render text after the entity, if it is the last entity in the text,\n // or the last nested entity inside of another entity\n if (isLastEntity && entityEndIndex < textPartEnd) {\n let textAfter = text.substring(entityEndIndex, textPartEnd);\n if (deleteLineBreakAfterPre && textAfter.length > 0 && textAfter[0] === '\\n') {\n textAfter = textAfter.substring(1);\n }\n if (textAfter) {\n renderResult.push(...renderMessagePart(\n textAfter, highlight, shouldRenderHqEmoji, shouldRenderAsHtml,\n ) as TextPart[]);\n }\n }\n\n return {\n renderResult,\n entityEndIndex,\n };\n }\n\n // Process highest-level entities\n let index = 0;\n\n organizedEntites.forEach((entity, arrayIndex) => {\n const { renderResult, entityEndIndex } = renderEntity(\n index,\n text.length,\n entity,\n arrayIndex === organizedEntites.length - 1,\n );\n\n result.push(...renderResult);\n index = entityEndIndex;\n });\n\n return result;\n}\n\nfunction processEntity(\n entity: ApiMessageEntity,\n entityContent: TextPart,\n nestedEntityContent: TextPart[],\n) {\n const entityText = typeof entityContent === 'string' && entityContent;\n const renderedContent = nestedEntityContent.length ? nestedEntityContent : entityContent;\n\n if (!entityText) {\n return renderMessagePart(renderedContent);\n }\n\n switch (entity.type) {\n case ApiMessageEntityTypes.Bold:\n return <strong>{renderMessagePart(renderedContent)}</strong>;\n case ApiMessageEntityTypes.Blockquote:\n return <blockquote>{renderMessagePart(renderedContent)}</blockquote>;\n case ApiMessageEntityTypes.BotCommand:\n return (\n <a\n onClick={handleBotCommandClick}\n className=\"text-entity-link\"\n dir=\"auto\"\n >\n {renderMessagePart(renderedContent)}\n </a>\n );\n case ApiMessageEntityTypes.Hashtag:\n return (\n <a\n onClick={handleHashtagClick}\n className=\"text-entity-link\"\n dir=\"auto\"\n >\n {renderMessagePart(renderedContent)}\n </a>\n );\n case ApiMessageEntityTypes.Cashtag:\n return (\n <a\n onClick={handleHashtagClick}\n className=\"text-entity-link\"\n dir=\"auto\"\n >\n {renderMessagePart(renderedContent)}\n </a>\n );\n case ApiMessageEntityTypes.Code:\n return <code className=\"text-entity-code\">{renderMessagePart(renderedContent)}</code>;\n case ApiMessageEntityTypes.Email:\n return (\n <a\n href={`mailto:${entityText}`}\n target=\"_blank\"\n rel=\"noopener noreferrer\"\n className=\"text-entity-link\"\n dir=\"auto\"\n >\n {renderMessagePart(renderedContent)}\n </a>\n );\n case ApiMessageEntityTypes.Italic:\n return <em>{renderMessagePart(renderedContent)}</em>;\n case ApiMessageEntityTypes.MentionName:\n return (\n <MentionLink userId={entity.userId}>\n {renderMessagePart(renderedContent)}\n </MentionLink>\n );\n case ApiMessageEntityTypes.Mention:\n return (\n <MentionLink username={entityText}>\n {renderMessagePart(renderedContent)}\n </MentionLink>\n );\n case ApiMessageEntityTypes.Phone:\n return (\n <a\n href={`tel:${entityText}`}\n className=\"text-entity-link\"\n dir=\"auto\"\n >\n {renderMessagePart(renderedContent)}\n </a>\n );\n case ApiMessageEntityTypes.Pre:\n return <pre className=\"text-entity-pre\">{renderMessagePart(renderedContent)}</pre>;\n case ApiMessageEntityTypes.Strike:\n return <del>{renderMessagePart(renderedContent)}</del>;\n case ApiMessageEntityTypes.TextUrl:\n case ApiMessageEntityTypes.Url:\n return (\n <SafeLink\n url={getLinkUrl(entityText, entity)}\n text={entityText}\n >\n {renderMessagePart(renderedContent)}\n </SafeLink>\n );\n case ApiMessageEntityTypes.Underline:\n return <ins>{renderMessagePart(renderedContent)}</ins>;\n default:\n return renderMessagePart(renderedContent);\n }\n}\n\nfunction renderMessagePart(\n content: TextPart | TextPart[],\n highlight?: string,\n shouldRenderHqEmoji?: boolean,\n shouldRenderAsHtml?: boolean,\n) {\n if (Array.isArray(content)) {\n const result: TextPart[] = [];\n\n content.forEach((c) => {\n result.push(...renderMessagePart(c, highlight, shouldRenderHqEmoji, shouldRenderAsHtml));\n });\n\n return result;\n }\n\n if (shouldRenderAsHtml) {\n return renderText(content, ['escape_html', 'emoji_html', 'br_html']);\n }\n\n const emojiFilter = shouldRenderHqEmoji ? 'hq_emoji' : 'emoji';\n\n if (highlight) {\n return renderText(content, [emojiFilter, 'br', 'highlight'], { highlight });\n } else {\n return renderText(content, [emojiFilter, 'br']);\n }\n}\n\nfunction getLinkUrl(entityContent: string, entity: ApiMessageEntity) {\n const { type, url } = entity;\n return type === ApiMessageEntityTypes.TextUrl && url ? url : entityContent;\n}\n\nfunction handleBotCommandClick(e: MouseEvent<HTMLAnchorElement>) {\n getDispatch().sendBotCommand({ command: e.currentTarget.innerText });\n}\n\nfunction handleHashtagClick(e: MouseEvent<HTMLAnchorElement>) {\n getDispatch().setLocalTextSearchQuery({ query: e.currentTarget.innerText });\n getDispatch().searchTextMessagesLocal();\n}\n\nfunction processEntityAsHtml(\n entity: ApiMessageEntity,\n entityContent: TextPart,\n nestedEntityContent: TextPart[],\n) {\n const rawEntityText = typeof entityContent === 'string' && entityContent;\n\n const renderedContent = nestedEntityContent.length\n ? nestedEntityContent.join('')\n : renderText(entityContent, ['emoji_html', 'br_html']).join('');\n\n if (!rawEntityText) {\n return renderedContent;\n }\n\n switch (entity.type) {\n case ApiMessageEntityTypes.Bold:\n return `<b>${renderedContent}</b>`;\n case ApiMessageEntityTypes.Italic:\n return `<i>${renderedContent}</i>`;\n case ApiMessageEntityTypes.Underline:\n return `<u>${renderedContent}</u>`;\n case ApiMessageEntityTypes.Code:\n return `<code class=\"text-entity-code\">${renderedContent}</code>`;\n case ApiMessageEntityTypes.Pre:\n return `\\`\\`\\`<br/>${renderedContent}<br/>\\`\\`\\``;\n case ApiMessageEntityTypes.Strike:\n return `<del>${renderedContent}</del>`;\n case ApiMessageEntityTypes.MentionName:\n return `<a\n class=\"text-entity-link\"\n data-entity-type=\"${ApiMessageEntityTypes.MentionName}\"\n data-user-id=\"${entity.userId}\"\n contenteditable=\"false\"\n dir=\"auto\"\n >${renderedContent}</a>`;\n case ApiMessageEntityTypes.Url:\n case ApiMessageEntityTypes.TextUrl:\n return `<a\n class=\"text-entity-link\"\n href=${getLinkUrl(rawEntityText, entity)}\n data-entity-type=\"${entity.type}\"\n dir=\"auto\"\n >${renderedContent}</a>`;\n default:\n return renderedContent;\n }\n}\n","import { RefObject } from 'react';\nimport { useEffect } from '../lib/teact/teact';\nimport { fastRaf } from '../util/schedulers';\n\n// Fix for memory leak when unmounting video element\nexport default function useVideoCleanup(videoRef: RefObject<HTMLVideoElement>, dependencies: any[]) {\n useEffect(() => {\n const videoEl = videoRef.current;\n\n return () => {\n if (videoEl) {\n fastRaf(() => {\n videoEl.pause();\n videoEl.src = '';\n videoEl.load();\n });\n }\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, dependencies);\n}\n","import { DEBUG } from '../config';\n\nexport const CLIPBOARD_ITEM_SUPPORTED = navigator.clipboard && window.ClipboardItem;\n\nconst textCopyEl = document.createElement('textarea');\ntextCopyEl.setAttribute('readonly', '');\ntextCopyEl.tabIndex = -1;\ntextCopyEl.className = 'visually-hidden';\n\nexport const copyTextToClipboard = (str: string): void => {\n textCopyEl.value = str;\n document.body.appendChild(textCopyEl);\n const selection = document.getSelection();\n\n if (selection) {\n // Store previous selection\n const rangeToRestore = selection.rangeCount > 0 && selection.getRangeAt(0);\n textCopyEl.select();\n document.execCommand('copy');\n // Restore the original selection\n if (rangeToRestore) {\n selection.removeAllRanges();\n selection.addRange(rangeToRestore);\n }\n }\n\n document.body.removeChild(textCopyEl);\n};\n\nexport const copyImageToClipboard = (imageUrl: string) => {\n const canvas = document.createElement('canvas');\n const ctx = canvas.getContext('2d');\n const imageEl = new Image();\n imageEl.onload = (e: Event) => {\n if (ctx && e.currentTarget) {\n const img = e.currentTarget as HTMLImageElement;\n canvas.width = img.width;\n canvas.height = img.height;\n ctx.drawImage(img, 0, 0, img.width, img.height);\n canvas.toBlob(copyBlobToClipboard, 'image/png', 1);\n }\n };\n\n imageEl.src = imageUrl;\n};\n\nasync function copyBlobToClipboard(pngBlob: Blob | null) {\n if (!pngBlob || !CLIPBOARD_ITEM_SUPPORTED) {\n return;\n }\n\n try {\n await navigator.clipboard.write([\n new window.ClipboardItem({\n [pngBlob.type]: pngBlob,\n }),\n ]);\n } catch (error) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error(error);\n }\n }\n}\n","import { RefObject } from 'react';\nimport React, {\n FC, useRef, useEffect, memo, useCallback,\n} from '../../lib/teact/teact';\n\nimport buildClassName from '../../util/buildClassName';\nimport useFlag from '../../hooks/useFlag';\nimport useLang from '../../hooks/useLang';\n\nimport Loading from './Loading';\nimport Button from './Button';\n\nimport './SearchInput.scss';\n\ntype OwnProps = {\n ref?: RefObject<HTMLInputElement>;\n children?: any;\n parentContainerClassName?: string;\n className?: string;\n inputId?: string;\n value?: string;\n focused?: boolean;\n isLoading?: boolean;\n placeholder?: string;\n disabled?: boolean;\n canClose?: boolean;\n onChange: (value: string) => void;\n onReset?: NoneToVoidFunction;\n onFocus?: NoneToVoidFunction;\n onBlur?: NoneToVoidFunction;\n};\n\nconst SearchInput: FC<OwnProps> = ({\n ref,\n children,\n parentContainerClassName,\n value,\n inputId,\n className,\n focused,\n isLoading,\n placeholder,\n disabled,\n canClose,\n onChange,\n onReset,\n onFocus,\n onBlur,\n}) => {\n // eslint-disable-next-line no-null/no-null\n let inputRef = useRef<HTMLInputElement>(null);\n if (ref) {\n inputRef = ref;\n }\n\n const [isInputFocused, markInputFocused, unmarkInputFocused] = useFlag(focused);\n\n useEffect(() => {\n if (!inputRef.current) {\n return;\n }\n\n if (focused) {\n inputRef.current.focus();\n } else {\n inputRef.current.blur();\n }\n }, [focused, placeholder]); // Trick for setting focus when selecting a contact to search for\n\n const lang = useLang();\n\n function handleChange(event: React.ChangeEvent<HTMLInputElement>) {\n const { currentTarget } = event;\n onChange(currentTarget.value);\n }\n\n function handleFocus() {\n markInputFocused();\n if (onFocus) {\n onFocus();\n }\n }\n\n function handleBlur() {\n unmarkInputFocused();\n if (onBlur) {\n onBlur();\n }\n }\n\n const handleKeyDown = useCallback((e: React.KeyboardEvent) => {\n if (e.key === 'ArrowDown') {\n const element = document.querySelector(`.${parentContainerClassName} .ListItem-button`) as HTMLElement;\n if (element) {\n element.focus();\n }\n }\n }, [parentContainerClassName]);\n\n return (\n <div\n className={buildClassName('SearchInput', className, isInputFocused && 'has-focus')}\n dir={lang.isRtl ? 'rtl' : undefined}\n >\n {children}\n <input\n ref={inputRef}\n id={inputId}\n type=\"text\"\n dir=\"auto\"\n placeholder={placeholder || lang('Search')}\n className=\"form-control\"\n value={value}\n disabled={disabled}\n onChange={handleChange}\n onFocus={handleFocus}\n onBlur={handleBlur}\n onKeyDown={handleKeyDown}\n />\n <i className=\"icon-search\" />\n {isLoading && (\n <Loading />\n )}\n {!isLoading && (value || canClose) && onReset && (\n <Button\n round\n size=\"tiny\"\n color=\"translucent\"\n onClick={onReset}\n >\n <span className=\"icon-close\" />\n </Button>\n )}\n </div>\n );\n};\n\nexport default memo(SearchInput);\n","import { IS_IOS } from './environment';\n\nexport default (container: HTMLDivElement, scrollTop?: number) => {\n if (IS_IOS) {\n container.style.overflow = 'hidden';\n }\n\n if (scrollTop !== undefined) {\n container.scrollTop = scrollTop;\n }\n\n if (IS_IOS) {\n container.style.overflow = '';\n }\n};\n","import React, { FC, memo } from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { ApiUser, ApiTypingStatus } from '../../api/types';\n\nimport { selectUser } from '../../modules/selectors';\nimport { getUserFirstOrLastName } from '../../modules/helpers';\nimport renderText from './helpers/renderText';\nimport useLang from '../../hooks/useLang';\n\nimport './TypingStatus.scss';\n\ntype OwnProps = {\n typingStatus: ApiTypingStatus;\n};\n\ntype StateProps = {\n typingUser?: ApiUser;\n};\n\nconst TypingStatus: FC<OwnProps & StateProps> = ({ typingStatus, typingUser }) => {\n const lang = useLang();\n const typingUserName = typingUser && !typingUser.isSelf && getUserFirstOrLastName(typingUser);\n\n return (\n <p className=\"typing-status\" dir={lang.isRtl ? 'rtl' : 'auto'}>\n {typingUserName && (\n <span className=\"sender-name\" dir=\"auto\">{renderText(typingUserName)}</span>\n )}\n {/* fix for translation \"username _is_ typing\" */}\n {lang(typingStatus.action).replace('{user}', '').trim()}\n <span className=\"ellipsis\" />\n </p>\n );\n};\n\nexport default memo(withGlobal<OwnProps>(\n (global, { typingStatus }): StateProps => {\n if (!typingStatus.userId) {\n return {};\n }\n\n const typingUser = selectUser(global, typingStatus.userId);\n\n return { typingUser };\n },\n)(TypingStatus));\n","import React, { FC, useCallback, memo } from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { ApiChat } from '../../api/types';\nimport { GlobalActions } from '../../global/types';\n\nimport { selectIsChatWithSelf, selectUser } from '../../modules/selectors';\nimport {\n isChatPrivate,\n getUserFirstOrLastName,\n getPrivateChatUserId,\n isChatBasicGroup,\n isChatSuperGroup,\n isChatChannel,\n getChatTitle,\n} from '../../modules/helpers';\nimport { pick } from '../../util/iteratees';\nimport useLang from '../../hooks/useLang';\nimport renderText from './helpers/renderText';\n\nimport Avatar from './Avatar';\nimport Modal from '../ui/Modal';\nimport Button from '../ui/Button';\n\nimport './DeleteChatModal.scss';\n\nexport type OwnProps = {\n isOpen: boolean;\n chat: ApiChat;\n onClose: () => void;\n};\n\ntype StateProps = {\n isChannel: boolean;\n isChatWithSelf?: boolean;\n isPrivateChat: boolean;\n isBasicGroup: boolean;\n isSuperGroup: boolean;\n canDeleteForAll?: boolean;\n contactName?: string;\n};\n\ntype DispatchProps = Pick<GlobalActions, 'leaveChannel' | 'deleteHistory' | 'deleteChannel'>;\n\nconst DeleteChatModal: FC<OwnProps & StateProps & DispatchProps> = ({\n isOpen,\n chat,\n isChannel,\n isPrivateChat,\n isChatWithSelf,\n isBasicGroup,\n isSuperGroup,\n canDeleteForAll,\n contactName,\n onClose,\n leaveChannel,\n deleteHistory,\n deleteChannel,\n}) => {\n const lang = useLang();\n const chatTitle = getChatTitle(lang, chat);\n\n const handleDeleteMessageForAll = useCallback(() => {\n deleteHistory({ chatId: chat.id, maxId: chat.lastMessage!.id, shouldDeleteForAll: true });\n onClose();\n }, [deleteHistory, chat.id, chat.lastMessage, onClose]);\n\n const handleDeleteChat = useCallback(() => {\n if (isPrivateChat || isBasicGroup) {\n deleteHistory({ chatId: chat.id, maxId: chat.lastMessage!.id, shouldDeleteForAll: false });\n } else if ((isChannel || isSuperGroup) && !chat.isCreator) {\n leaveChannel({ chatId: chat.id });\n } else if ((isChannel || isSuperGroup) && chat.isCreator) {\n deleteChannel({ chatId: chat.id });\n }\n onClose();\n }, [\n isPrivateChat,\n isBasicGroup,\n isChannel,\n isSuperGroup,\n chat.isCreator,\n chat.lastMessage,\n chat.id,\n onClose,\n deleteHistory,\n leaveChannel,\n deleteChannel,\n ]);\n\n function renderHeader() {\n return (\n <div className=\"modal-header\" dir={lang.isRtl ? 'rtl' : undefined}>\n <Avatar\n size=\"tiny\"\n chat={chat}\n isSavedMessages={isChatWithSelf}\n />\n <h3 className=\"modal-title\">{lang(renderTitle())}</h3>\n </div>\n );\n }\n\n function renderTitle() {\n if (isChannel && !chat.isCreator) {\n return 'LeaveChannel';\n }\n\n if (isChannel && chat.isCreator) {\n return 'ChannelDelete';\n }\n\n if (isBasicGroup || isSuperGroup) {\n return 'Group.LeaveGroup';\n }\n\n return 'DeleteChatUser';\n }\n\n function renderMessage() {\n if (isChannel && chat.isCreator) {\n return <p>{renderText(lang('ChatList.DeleteAndLeaveGroupConfirmation', chatTitle), ['simple_markdown'])}</p>;\n }\n\n if ((isChannel && !chat.isCreator) || isBasicGroup || isSuperGroup) {\n return <p>{renderText(lang('ChannelLeaveAlertWithName', chatTitle), ['simple_markdown'])}</p>;\n }\n\n return <p>{renderText(lang('ChatList.DeleteChatConfirmation', contactName), ['simple_markdown'])}</p>;\n }\n\n function renderActionText() {\n if (isChannel && !chat.isCreator) {\n return 'LeaveChannel';\n }\n if (isChannel && chat.isCreator) {\n return 'Chat.Input.Delete';\n }\n\n if (isBasicGroup || isSuperGroup) {\n return 'Group.LeaveGroup';\n }\n\n return canDeleteForAll ? 'ChatList.DeleteForCurrentUser' : 'Delete';\n }\n\n return (\n <Modal\n isOpen={isOpen}\n onClose={onClose}\n className=\"DeleteChatModal\"\n header={renderHeader()}\n >\n {renderMessage()}\n {canDeleteForAll && (\n <Button color=\"danger\" className=\"confirm-dialog-button\" isText onClick={handleDeleteMessageForAll}>\n {contactName ? lang('ChatList.DeleteForEveryone', contactName) : lang('DeleteForAll')}\n </Button>\n )}\n <Button color=\"danger\" className=\"confirm-dialog-button\" isText onClick={handleDeleteChat}>\n {lang(renderActionText())}\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, { chat }): StateProps => {\n const isPrivateChat = isChatPrivate(chat.id);\n const isChatWithSelf = selectIsChatWithSelf(global, chat.id);\n const canDeleteForAll = (isPrivateChat && !isChatWithSelf);\n const contactName = chat && isChatPrivate(chat.id)\n ? getUserFirstOrLastName(selectUser(global, getPrivateChatUserId(chat)!))\n : undefined;\n\n return {\n isPrivateChat,\n isChatWithSelf,\n isChannel: isChatChannel(chat),\n isBasicGroup: isChatBasicGroup(chat),\n isSuperGroup: isChatSuperGroup(chat),\n canDeleteForAll,\n contactName,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, ['leaveChannel', 'deleteHistory', 'deleteChannel']),\n)(DeleteChatModal));\n","/*\n * Thanks to Ace Monkey for this mind-blowing patch.\n */\n\nexport function patchSafariProgressiveAudio(audioEl: HTMLAudioElement) {\n if (audioEl.dataset.patchedForSafari) {\n return;\n }\n\n audioEl.addEventListener('play', () => {\n const t = audioEl.currentTime;\n\n function onProgress() {\n if (!audioEl.buffered.length) {\n return;\n }\n\n audioEl.dataset.patchForSafariInProgress = 'true';\n audioEl.currentTime = audioEl.duration - 1;\n audioEl.addEventListener('progress', () => {\n delete audioEl.dataset.patchForSafariInProgress;\n audioEl.currentTime = t;\n if (audioEl.paused) {\n audioEl.play();\n }\n }, { once: true });\n\n audioEl.removeEventListener('progress', onProgress);\n }\n\n audioEl.addEventListener('progress', onProgress);\n }, { once: true });\n\n audioEl.dataset.patchedForSafari = 'true';\n}\n\nexport function isSafariPatchInProgress(audioEl: HTMLAudioElement) {\n return Boolean(audioEl.dataset.patchForSafariInProgress);\n}\n","import { useLayoutEffect } from '../lib/teact/teact';\nimport usePrevious from './usePrevious';\n\nexport default <T extends any[], PT = T>(cb: (args: PT) => void, dependencies: T) => {\n const prevDeps = usePrevious<T>(dependencies);\n return useLayoutEffect(() => {\n // @ts-ignore (workaround for \"could be instantiated with a different subtype\" issue)\n cb(prevDeps || []);\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, dependencies);\n};\n","import React, {\n FC, useCallback, useEffect, useState, memo, useRef,\n} from '../../lib/teact/teact';\n\nimport { ApiMessage } from '../../api/types';\n\nimport { getDocumentExtension, getDocumentHasPreview } from './helpers/documentInfo';\nimport { getMediaTransferState, getMessageMediaHash, getMessageMediaThumbDataUri } from '../../modules/helpers';\nimport { ObserveFn, useIsIntersecting } from '../../hooks/useIntersectionObserver';\nimport useMediaWithDownloadProgress from '../../hooks/useMediaWithDownloadProgress';\nimport useMedia from '../../hooks/useMedia';\nimport download from '../../util/download';\n\nimport File from './File';\n\ntype OwnProps = {\n message: ApiMessage;\n observeIntersection?: ObserveFn;\n smaller?: boolean;\n isSelected?: boolean;\n isSelectable?: boolean;\n uploadProgress?: number;\n withDate?: boolean;\n datetime?: number;\n className?: string;\n sender?: string;\n onCancelUpload?: () => void;\n onDateClick?: (messageId: number, chatId: number) => void;\n};\n\nconst Document: FC<OwnProps> = ({\n message,\n observeIntersection,\n smaller,\n uploadProgress,\n withDate,\n datetime,\n className,\n sender,\n isSelected,\n isSelectable,\n onCancelUpload,\n onDateClick,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const ref = useRef<HTMLDivElement>(null);\n\n const document = message.content.document!;\n const extension = getDocumentExtension(document) || '';\n const { fileName, size, timestamp } = document;\n\n const isIntersecting = useIsIntersecting(ref, observeIntersection);\n\n const [isDownloadAllowed, setIsDownloadAllowed] = useState(false);\n const {\n mediaData, downloadProgress,\n } = useMediaWithDownloadProgress(getMessageMediaHash(message, 'download'), !isDownloadAllowed);\n const {\n isUploading, isTransferring, transferProgress,\n } = getMediaTransferState(message, uploadProgress || downloadProgress, isDownloadAllowed);\n\n const hasPreview = getDocumentHasPreview(document);\n const thumbDataUri = hasPreview ? getMessageMediaThumbDataUri(message) : undefined;\n const localBlobUrl = hasPreview ? document.previewBlobUrl : undefined;\n const previewData = useMedia(getMessageMediaHash(message, 'pictogram'), !isIntersecting);\n\n const handleClick = useCallback(() => {\n if (isUploading) {\n if (onCancelUpload) {\n onCancelUpload();\n }\n } else {\n setIsDownloadAllowed((isAllowed) => !isAllowed);\n }\n }, [isUploading, onCancelUpload]);\n\n const handleDateClick = useCallback(() => {\n onDateClick!(message.id, message.chatId);\n }, [onDateClick, message.id, message.chatId]);\n\n useEffect(() => {\n if (isDownloadAllowed && mediaData) {\n download(mediaData, fileName);\n setIsDownloadAllowed(false);\n }\n }, [fileName, mediaData, isDownloadAllowed]);\n\n return (\n <File\n ref={ref}\n name={fileName}\n extension={extension}\n size={size}\n timestamp={withDate ? datetime || timestamp : undefined}\n thumbnailDataUri={thumbDataUri}\n previewData={localBlobUrl || previewData}\n smaller={smaller}\n isTransferring={isTransferring}\n isUploading={isUploading}\n transferProgress={transferProgress}\n className={className}\n sender={sender}\n isSelectable={isSelectable}\n isSelected={isSelected}\n onClick={handleClick}\n onDateClick={onDateClick ? handleDateClick : undefined}\n />\n );\n};\n\nexport default memo(Document);\n","import React, { FC, memo } from '../../lib/teact/teact';\nimport { OwnProps } from './StickerSetModal';\nimport { Bundles } from '../../util/moduleLoader';\n\nimport useModuleLoader from '../../hooks/useModuleLoader';\n\nconst StickerSetModalAsync: FC<OwnProps> = (props) => {\n const { isOpen } = props;\n const StickerSetModal = useModuleLoader(Bundles.Extra, 'StickerSetModal', !isOpen);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return StickerSetModal ? <StickerSetModal {...props} /> : undefined;\n};\n\nexport default memo(StickerSetModalAsync);\n","import { useEffect, useRef } from '../lib/teact/teact';\n\nimport fastBlur from '../lib/fastBlur';\nimport useForceUpdate from './useForceUpdate';\nimport { IS_CANVAS_FILTER_SUPPORTED } from '../util/environment';\n\nconst RADIUS = 2;\nconst ITERATIONS = 2;\n\nexport default function useCanvasBlur(dataUri?: string, isDisabled = false, withRaf?: boolean) {\n // eslint-disable-next-line no-null/no-null\n const canvasRef = useRef<HTMLCanvasElement>(null);\n const forceUpdate = useForceUpdate();\n\n useEffect(() => {\n const canvas = canvasRef.current;\n\n if (!dataUri || !canvas || isDisabled) {\n return;\n }\n\n const img = new Image();\n\n const processBlur = () => {\n canvas.width = img.width;\n canvas.height = img.height;\n\n const ctx = canvas.getContext('2d', { alpha: false })!;\n\n if (IS_CANVAS_FILTER_SUPPORTED) {\n ctx.filter = `blur(${RADIUS}px)`;\n }\n\n ctx.drawImage(img, -RADIUS * 2, -RADIUS * 2, canvas.width + RADIUS * 4, canvas.height + RADIUS * 4);\n\n if (!IS_CANVAS_FILTER_SUPPORTED) {\n fastBlur(ctx, 0, 0, canvas.width, canvas.height, RADIUS, ITERATIONS);\n }\n };\n\n img.onload = () => {\n if (withRaf) {\n requestAnimationFrame(processBlur);\n } else {\n processBlur();\n }\n };\n\n img.src = dataUri;\n }, [canvasRef, dataUri, forceUpdate, isDisabled, withRaf]);\n\n return canvasRef;\n}\n","/* eslint-disable no-nested-ternary */\n/* eslint-disable no-bitwise */\n/* eslint-disable no-multi-assign */\n/* eslint-disable no-cond-assign */\n/* eslint-disable no-param-reassign */\n/* eslint-disable prefer-const */\n/* eslint-disable eqeqeq */\n\n/*\nSuperfast Blur - a fast Box Blur For Canvas\n\nVersion: 0.5\nAuthor: Mario Klingemann\nContact: mario@quasimondo.com\nWebsite: http://www.quasimondo.com/BoxBlurForCanvas\nTwitter: @quasimondo\n\nIn case you find this class useful - especially in commercial projects -\nI am not totally unhappy for a small donation to my PayPal account\nmario@quasimondo.de\n\nOr support me on flattr:\nhttps://flattr.com/thing/140066/Superfast-Blur-a-pretty-fast-Box-Blur-Effect-for-CanvasJavascript\n\nCopyright (c) 2011 Mario Klingemann\n\nPermission is hereby granted, free of charge, to any person\nobtaining a copy of this software and associated documentation\nfiles (the \"Software\"), to deal in the Software without\nrestriction, including without limitation the rights to use,\ncopy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the\nSoftware is furnished to do so, subject to the following\nconditions:\n\nThe above copyright notice and this permission notice shall be\nincluded in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES\nOF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\nNONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\nHOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\nWHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\nFROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\nOTHER DEALINGS IN THE SOFTWARE.\n*/\n\n// eslint-disable-next-line max-len\nconst mul_table = [1, 57, 41, 21, 203, 34, 97, 73, 227, 91, 149, 62, 105, 45, 39, 137, 241, 107, 3, 173, 39, 71, 65, 238, 219, 101, 187, 87, 81, 151, 141, 133, 249, 117, 221, 209, 197, 187, 177, 169, 5, 153, 73, 139, 133, 127, 243, 233, 223, 107, 103, 99, 191, 23, 177, 171, 165, 159, 77, 149, 9, 139, 135, 131, 253, 245, 119, 231, 224, 109, 211, 103, 25, 195, 189, 23, 45, 175, 171, 83, 81, 79, 155, 151, 147, 9, 141, 137, 67, 131, 129, 251, 123, 30, 235, 115, 113, 221, 217, 53, 13, 51, 50, 49, 193, 189, 185, 91, 179, 175, 43, 169, 83, 163, 5, 79, 155, 19, 75, 147, 145, 143, 35, 69, 17, 67, 33, 65, 255, 251, 247, 243, 239, 59, 29, 229, 113, 111, 219, 27, 213, 105, 207, 51, 201, 199, 49, 193, 191, 47, 93, 183, 181, 179, 11, 87, 43, 85, 167, 165, 163, 161, 159, 157, 155, 77, 19, 75, 37, 73, 145, 143, 141, 35, 138, 137, 135, 67, 33, 131, 129, 255, 63, 250, 247, 61, 121, 239, 237, 117, 29, 229, 227, 225, 111, 55, 109, 216, 213, 211, 209, 207, 205, 203, 201, 199, 197, 195, 193, 48, 190, 47, 93, 185, 183, 181, 179, 178, 176, 175, 173, 171, 85, 21, 167, 165, 41, 163, 161, 5, 79, 157, 78, 154, 153, 19, 75, 149, 74, 147, 73, 144, 143, 71, 141, 140, 139, 137, 17, 135, 134, 133, 66, 131, 65, 129, 1];\n// eslint-disable-next-line max-len\nconst shg_table = [0, 9, 10, 10, 14, 12, 14, 14, 16, 15, 16, 15, 16, 15, 15, 17, 18, 17, 12, 18, 16, 17, 17, 19, 19, 18, 19, 18, 18, 19, 19, 19, 20, 19, 20, 20, 20, 20, 20, 20, 15, 20, 19, 20, 20, 20, 21, 21, 21, 20, 20, 20, 21, 18, 21, 21, 21, 21, 20, 21, 17, 21, 21, 21, 22, 22, 21, 22, 22, 21, 22, 21, 19, 22, 22, 19, 20, 22, 22, 21, 21, 21, 22, 22, 22, 18, 22, 22, 21, 22, 22, 23, 22, 20, 23, 22, 22, 23, 23, 21, 19, 21, 21, 21, 23, 23, 23, 22, 23, 23, 21, 23, 22, 23, 18, 22, 23, 20, 22, 23, 23, 23, 21, 22, 20, 22, 21, 22, 24, 24, 24, 24, 24, 22, 21, 24, 23, 23, 24, 21, 24, 23, 24, 22, 24, 24, 22, 24, 24, 22, 23, 24, 24, 24, 20, 23, 22, 23, 24, 24, 24, 24, 24, 24, 24, 23, 21, 23, 22, 23, 24, 24, 24, 22, 24, 24, 24, 23, 22, 24, 24, 25, 23, 25, 25, 23, 24, 25, 25, 24, 22, 25, 25, 25, 24, 23, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 23, 25, 23, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 24, 22, 25, 25, 23, 25, 25, 20, 24, 25, 24, 25, 25, 22, 24, 25, 24, 25, 24, 25, 25, 24, 25, 25, 25, 25, 22, 25, 25, 25, 24, 25, 24, 25, 18];\n\nexport default function boxBlurCanvasRGB(context, top_x, top_y, width, height, radius, iterations) {\n if (Number.isNaN(radius) || radius < 1) return;\n\n radius |= 0;\n\n if (Number.isNaN(iterations)) iterations = 1;\n iterations |= 0;\n if (iterations > 3) iterations = 3;\n if (iterations < 1) iterations = 1;\n\n const imageData = context.getImageData(top_x, top_y, width, height);\n\n const pixels = imageData.data;\n\n let rsum;\n let gsum;\n let bsum;\n let x;\n let y;\n let i;\n let p;\n let p1;\n let p2;\n let yp;\n let yi;\n let yw;\n let wm = width - 1;\n let hm = height - 1;\n let rad1 = radius + 1;\n\n let r = [];\n let g = [];\n let b = [];\n\n let mul_sum = mul_table[radius];\n let shg_sum = shg_table[radius];\n\n let vmin = [];\n let vmax = [];\n\n while (iterations-- > 0) {\n yw = yi = 0;\n\n for (y = 0; y < height; y++) {\n rsum = pixels[yw] * rad1;\n gsum = pixels[yw + 1] * rad1;\n bsum = pixels[yw + 2] * rad1;\n\n for (i = 1; i <= radius; i++) {\n p = yw + (((i > wm ? wm : i)) << 2);\n rsum += pixels[p++];\n gsum += pixels[p++];\n bsum += pixels[p++];\n }\n\n for (x = 0; x < width; x++) {\n r[yi] = rsum;\n g[yi] = gsum;\n b[yi] = bsum;\n\n if (y == 0) {\n vmin[x] = ((p = x + rad1) < wm ? p : wm) << 2;\n vmax[x] = ((p = x - radius) > 0 ? p << 2 : 0);\n }\n\n p1 = yw + vmin[x];\n p2 = yw + vmax[x];\n\n rsum += pixels[p1++] - pixels[p2++];\n gsum += pixels[p1++] - pixels[p2++];\n bsum += pixels[p1++] - pixels[p2++];\n\n yi++;\n }\n yw += (width << 2);\n }\n\n for (x = 0; x < width; x++) {\n yp = x;\n rsum = r[yp] * rad1;\n gsum = g[yp] * rad1;\n bsum = b[yp] * rad1;\n\n for (i = 1; i <= radius; i++) {\n yp += (i > hm ? 0 : width);\n rsum += r[yp];\n gsum += g[yp];\n bsum += b[yp];\n }\n\n yi = x << 2;\n for (y = 0; y < height; y++) {\n pixels[yi] = (rsum * mul_sum) >>> shg_sum;\n pixels[yi + 1] = (gsum * mul_sum) >>> shg_sum;\n pixels[yi + 2] = (bsum * mul_sum) >>> shg_sum;\n\n if (x == 0) {\n vmin[y] = ((p = y + rad1) < hm ? p : hm) * width;\n vmax[y] = ((p = y - radius) > 0 ? p * width : 0);\n }\n\n p1 = x + vmin[y];\n p2 = x + vmax[y];\n\n rsum += r[p1] - r[p2];\n gsum += g[p1] - g[p2];\n bsum += b[p1] - b[p2];\n\n yi += width << 2;\n }\n }\n }\n\n context.putImageData(imageData, top_x, top_y);\n}\n","import React, {\n FC, memo, useCallback, useEffect, useRef, useState,\n} from '../../../lib/teact/teact';\n\nimport { IAnchorPosition } from '../../../types';\n\nimport { EDITABLE_INPUT_ID } from '../../../config';\nimport buildClassName from '../../../util/buildClassName';\nimport captureEscKeyListener from '../../../util/captureEscKeyListener';\nimport useShowTransition from '../../../hooks/useShowTransition';\nimport useVirtualBackdrop from '../../../hooks/useVirtualBackdrop';\nimport useFlag from '../../../hooks/useFlag';\nimport useLang from '../../../hooks/useLang';\n\nimport Button from '../../ui/Button';\n\nimport './TextFormatter.scss';\n\nexport type OwnProps = {\n isOpen: boolean;\n anchorPosition?: IAnchorPosition;\n selectedRange?: Range;\n onClose: () => void;\n};\n\ninterface ISelectedTextFormats {\n bold?: boolean;\n italic?: boolean;\n underline?: boolean;\n strikethrough?: boolean;\n monospace?: boolean;\n}\n\nconst TEXT_FORMAT_BY_TAG_NAME: Record<string, keyof ISelectedTextFormats> = {\n B: 'bold',\n STRONG: 'bold',\n I: 'italic',\n EM: 'italic',\n U: 'underline',\n DEL: 'strikethrough',\n CODE: 'monospace',\n};\n\nconst TextFormatter: FC<OwnProps> = ({\n isOpen,\n anchorPosition,\n selectedRange,\n onClose,\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 linkUrlInputRef = useRef<HTMLInputElement>(null);\n const { shouldRender, transitionClassNames } = useShowTransition(isOpen);\n const [isLinkControlOpen, openLinkControl, closeLinkControl] = useFlag();\n const [linkUrl, setLinkUrl] = useState('');\n const [isEditingLink, setIsEditingLink] = useState(false);\n const [inputClassName, setInputClassName] = useState<string | undefined>();\n const [selectedTextFormats, setSelectedTextFormats] = useState<ISelectedTextFormats>({});\n\n useEffect(() => (isOpen ? captureEscKeyListener(onClose) : undefined), [isOpen, onClose]);\n useVirtualBackdrop(\n isOpen,\n containerRef,\n onClose,\n );\n\n useEffect(() => {\n if (isLinkControlOpen) {\n linkUrlInputRef.current!.focus();\n } else {\n setLinkUrl('');\n setIsEditingLink(false);\n }\n }, [isLinkControlOpen]);\n\n useEffect(() => {\n if (!shouldRender) {\n closeLinkControl();\n setSelectedTextFormats({});\n setInputClassName(undefined);\n }\n }, [closeLinkControl, shouldRender]);\n\n useEffect(() => {\n if (!isOpen || !selectedRange) {\n return;\n }\n\n const selectedFormats: ISelectedTextFormats = {};\n let { parentElement } = selectedRange.commonAncestorContainer;\n while (parentElement && parentElement.id !== EDITABLE_INPUT_ID) {\n const textFormat = TEXT_FORMAT_BY_TAG_NAME[parentElement.tagName];\n if (textFormat) {\n selectedFormats[textFormat] = true;\n }\n\n parentElement = parentElement.parentElement;\n }\n\n setSelectedTextFormats(selectedFormats);\n }, [isOpen, selectedRange, openLinkControl]);\n\n function restoreSelection() {\n if (!selectedRange) {\n return;\n }\n\n const selection = window.getSelection();\n if (selection) {\n selection.removeAllRanges();\n selection.addRange(selectedRange);\n }\n }\n\n const getSelectedText = useCallback(() => {\n if (!selectedRange) {\n return undefined;\n }\n\n return selectedRange.toString();\n }, [selectedRange]);\n\n const getSelectedElement = useCallback(() => {\n if (!selectedRange) {\n return undefined;\n }\n\n return selectedRange.commonAncestorContainer.parentElement;\n }, [selectedRange]);\n\n function updateInputStyles() {\n const input = linkUrlInputRef.current;\n if (!input) {\n return;\n }\n\n const { offsetWidth, scrollWidth, scrollLeft } = input;\n if (scrollWidth <= offsetWidth) {\n setInputClassName(undefined);\n return;\n }\n\n let className = '';\n if (scrollLeft < scrollWidth - offsetWidth) {\n className = 'mask-right';\n }\n if (scrollLeft > 0) {\n className += ' mask-left';\n }\n\n setInputClassName(className);\n }\n\n function handleLinkUrlChange(e: React.ChangeEvent<HTMLInputElement>) {\n setLinkUrl(e.target.value);\n updateInputStyles();\n }\n\n function getFormatButtonClassName(key: keyof ISelectedTextFormats) {\n if (selectedTextFormats[key]) {\n return 'active';\n }\n\n if (key === 'monospace' || key === 'strikethrough') {\n if (Object.keys(selectedTextFormats).some(\n (fKey) => fKey !== key && !!selectedTextFormats[fKey as keyof ISelectedTextFormats],\n )) {\n return 'disabled';\n }\n } else if (selectedTextFormats.monospace || selectedTextFormats.strikethrough) {\n return 'disabled';\n }\n\n return undefined;\n }\n\n const handleBoldText = useCallback(() => {\n setSelectedTextFormats((selectedFormats) => {\n // Somehow re-applying 'bold' command to already bold text doesn't work\n document.execCommand(selectedFormats.bold ? 'removeFormat' : 'bold');\n Object.keys(selectedFormats).forEach((key) => {\n if ((key === 'italic' || key === 'underline') && !!selectedFormats[key]) {\n document.execCommand(key);\n }\n });\n\n return {\n ...selectedFormats,\n bold: !selectedFormats.bold,\n };\n });\n }, []);\n\n const handleItalicText = useCallback(() => {\n document.execCommand('italic');\n setSelectedTextFormats((selectedFormats) => ({\n ...selectedFormats,\n italic: !selectedFormats.italic,\n }));\n }, []);\n\n const handleUnderlineText = useCallback(() => {\n document.execCommand('underline');\n setSelectedTextFormats((selectedFormats) => ({\n ...selectedFormats,\n underline: !selectedFormats.underline,\n }));\n }, []);\n\n const handleStrikethroughText = useCallback(() => {\n if (selectedTextFormats.strikethrough) {\n const element = getSelectedElement();\n if (\n !selectedRange\n || !element\n || element.tagName !== 'DEL'\n || !element.textContent\n ) {\n return;\n }\n\n element.replaceWith(element.textContent);\n setSelectedTextFormats((selectedFormats) => ({\n ...selectedFormats,\n strikethrough: false,\n }));\n\n return;\n }\n\n const text = getSelectedText();\n document.execCommand('insertHTML', false, `<del>${text}</del>`);\n onClose();\n }, [\n getSelectedElement, getSelectedText, onClose,\n selectedRange, selectedTextFormats.strikethrough,\n ]);\n\n const handleMonospaceText = useCallback(() => {\n if (selectedTextFormats.monospace) {\n const element = getSelectedElement();\n if (\n !selectedRange\n || !element\n || element.tagName !== 'CODE'\n || !element.textContent\n ) {\n return;\n }\n\n element.replaceWith(element.textContent);\n setSelectedTextFormats((selectedFormats) => ({\n ...selectedFormats,\n monospace: false,\n }));\n return;\n }\n\n const text = getSelectedText();\n document.execCommand('insertHTML', false, `<code class=\"text-entity-code\" dir=\"auto\">${text}</code>`);\n onClose();\n }, [\n getSelectedElement, getSelectedText, onClose,\n selectedRange, selectedTextFormats.monospace,\n ]);\n\n function handleLinkUrlConfirm() {\n const formattedLinkUrl = linkUrl.includes('://') ? linkUrl : `http://${linkUrl}`;\n\n if (isEditingLink) {\n const element = getSelectedElement();\n if (!element || element.tagName !== 'A') {\n return;\n }\n\n (element as HTMLAnchorElement).href = formattedLinkUrl;\n\n onClose();\n return;\n }\n\n const text = getSelectedText();\n restoreSelection();\n document.execCommand(\n 'insertHTML',\n false,\n `<a href=${formattedLinkUrl} class=\"text-entity-link\" dir=\"auto\">${text}</a>`,\n );\n onClose();\n }\n\n const handleKeyDown = useCallback((e: KeyboardEvent) => {\n const HANDLERS_BY_KEY_CODE: Record<string, AnyToVoidFunction> = {\n KeyK: openLinkControl,\n KeyB: handleBoldText,\n KeyU: handleUnderlineText,\n KeyI: handleItalicText,\n KeyM: handleMonospaceText,\n KeyS: handleStrikethroughText,\n };\n\n const handler = HANDLERS_BY_KEY_CODE[e.code];\n\n if (\n e.altKey\n || !(e.ctrlKey || e.metaKey)\n || !handler\n ) {\n return;\n }\n\n e.preventDefault();\n e.stopPropagation();\n handler();\n }, [\n handleBoldText, handleItalicText, handleUnderlineText,\n handleMonospaceText, handleStrikethroughText,\n openLinkControl,\n ]);\n\n useEffect(() => {\n if (isOpen) {\n document.addEventListener('keydown', handleKeyDown);\n }\n\n return () => document.removeEventListener('keydown', handleKeyDown);\n }, [isOpen, handleKeyDown]);\n\n const lang = useLang();\n\n function handleContainerKeyDown(e: React.KeyboardEvent<HTMLDivElement>) {\n if (e.key === 'Enter' && isLinkControlOpen) {\n handleLinkUrlConfirm();\n e.preventDefault();\n }\n }\n\n if (!shouldRender) {\n return undefined;\n }\n\n const className = buildClassName(\n 'TextFormatter',\n transitionClassNames,\n isLinkControlOpen && 'link-control-shown',\n );\n\n const linkUrlConfirmClassName = buildClassName(\n 'TextFormatter-link-url-confirm',\n !!linkUrl.length && 'shown',\n );\n\n const style = anchorPosition\n ? `left: ${anchorPosition.x}px; top: ${anchorPosition.y}px;--text-formatter-left: ${anchorPosition.x}px;`\n : '';\n\n return (\n <div\n ref={containerRef}\n className={className}\n // @ts-ignore Teact feature\n style={style}\n onKeyDown={handleContainerKeyDown}\n >\n <div className=\"TextFormatter-buttons\">\n <Button\n color=\"translucent\"\n ariaLabel=\"Bold text\"\n className={getFormatButtonClassName('bold')}\n onClick={handleBoldText}\n >\n <i className=\"icon-bold\" />\n </Button>\n <Button\n color=\"translucent\"\n ariaLabel=\"Italic text\"\n className={getFormatButtonClassName('italic')}\n onClick={handleItalicText}\n >\n <i className=\"icon-italic\" />\n </Button>\n <Button\n color=\"translucent\"\n ariaLabel=\"Underlined text\"\n className={getFormatButtonClassName('underline')}\n onClick={handleUnderlineText}\n >\n <i className=\"icon-underlined\" />\n </Button>\n <Button\n color=\"translucent\"\n ariaLabel=\"Strikethrough text\"\n className={getFormatButtonClassName('strikethrough')}\n onClick={handleStrikethroughText}\n >\n <i className=\"icon-strikethrough\" />\n </Button>\n <Button\n color=\"translucent\"\n ariaLabel=\"Monospace text\"\n className={getFormatButtonClassName('monospace')}\n onClick={handleMonospaceText}\n >\n <i className=\"icon-monospace\" />\n </Button>\n <div className=\"TextFormatter-divider\" />\n <Button color=\"translucent\" ariaLabel={lang('TextFormat.AddLinkTitle')} onClick={openLinkControl}>\n <i className=\"icon-link\" />\n </Button>\n </div>\n\n <div className=\"TextFormatter-link-control\">\n <div className=\"TextFormatter-buttons\">\n <Button color=\"translucent\" ariaLabel={lang('Cancel')} onClick={closeLinkControl}>\n <i className=\"icon-arrow-left\" />\n </Button>\n <div className=\"TextFormatter-divider\" />\n\n <div\n className={buildClassName('TextFormatter-link-url-input-wrapper', inputClassName)}\n >\n <input\n ref={linkUrlInputRef}\n className=\"TextFormatter-link-url-input\"\n type=\"text\"\n value={linkUrl}\n placeholder=\"Enter URL...\"\n autoComplete=\"off\"\n inputMode=\"url\"\n dir=\"auto\"\n onChange={handleLinkUrlChange}\n onScroll={updateInputStyles}\n />\n </div>\n\n <div className={linkUrlConfirmClassName}>\n <div className=\"TextFormatter-divider\" />\n <Button\n color=\"translucent\"\n ariaLabel={lang('Save')}\n className=\"color-primary\"\n onClick={handleLinkUrlConfirm}\n >\n <i className=\"icon-check\" />\n </Button>\n </div>\n </div>\n </div>\n </div>\n );\n};\n\nexport default memo(TextFormatter);\n","import React, { FC, memo, useCallback } from '../../lib/teact/teact';\n\nimport { ApiMessage } from '../../api/types';\n\nimport { formatMediaDuration } from '../../util/dateFormat';\nimport {\n getMessageMediaHash,\n getMessageMediaThumbDataUri,\n getMessageVideo,\n} from '../../modules/helpers';\nimport useMedia from '../../hooks/useMedia';\nimport useTransitionForMedia from '../../hooks/useTransitionForMedia';\n\nimport './Media.scss';\n\ntype OwnProps = {\n message: ApiMessage;\n idPrefix?: string;\n onClick?: (messageId: number, chatId: number) => void;\n};\n\nconst Media: FC<OwnProps> = ({ message, idPrefix = 'shared-media', onClick }) => {\n const handleClick = useCallback(() => {\n onClick!(message.id, message.chatId);\n }, [message.id, message.chatId, onClick]);\n\n const thumbDataUri = getMessageMediaThumbDataUri(message);\n const mediaBlobUrl = useMedia(getMessageMediaHash(message, 'pictogram'));\n const {\n shouldRenderThumb, shouldRenderFullMedia, transitionClassNames,\n } = useTransitionForMedia(mediaBlobUrl, 'slow');\n\n const video = getMessageVideo(message);\n\n return (\n <div id={`${idPrefix}${message.id}`} className=\"Media scroll-item\" onClick={onClick ? handleClick : undefined}>\n {shouldRenderThumb && (\n <img src={thumbDataUri} alt=\"\" />\n )}\n {shouldRenderFullMedia && (\n <img src={mediaBlobUrl} className={`${transitionClassNames} full-media`} alt=\"\" />\n )}\n {video && <span className=\"video-duration\">{video.isGif ? 'GIF' : formatMediaDuration(video.duration)}</span>}\n </div>\n );\n};\n\nexport default memo(Media);\n","import React, {\n FC, memo, useCallback, useEffect, useMemo, useRef, useState,\n} from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport {\n ApiAudio, ApiMessage, ApiVoice,\n} from '../../api/types';\nimport { ISettings } from '../../types';\n\nimport { IS_MOBILE_SCREEN } from '../../util/environment';\nimport { formatMediaDateTime, formatMediaDuration, formatPastTimeShort } from '../../util/dateFormat';\nimport {\n getMediaDuration,\n getMediaTransferState,\n getMessageKey,\n getMessageMediaFormat,\n getMessageMediaHash,\n isMessageLocal,\n isOwnMessage,\n} from '../../modules/helpers';\nimport { renderWaveformToDataUri } from './helpers/waveform';\nimport buildClassName from '../../util/buildClassName';\nimport renderText from './helpers/renderText';\nimport { decodeWaveform, interpolateArray } from '../../util/waveform';\nimport useMediaWithDownloadProgress from '../../hooks/useMediaWithDownloadProgress';\nimport useShowTransition from '../../hooks/useShowTransition';\nimport useBuffering from '../../hooks/useBuffering';\nimport useAudioPlayer from '../../hooks/useAudioPlayer';\nimport useLang, { LangFn } from '../../hooks/useLang';\n\nimport Button from '../ui/Button';\nimport ProgressSpinner from '../ui/ProgressSpinner';\nimport Link from '../ui/Link';\n\nimport './Audio.scss';\n\ntype OwnProps = {\n message: ApiMessage;\n senderTitle?: string;\n uploadProgress?: number;\n renderingFor?: 'searchResult' | 'sharedMedia';\n date?: number;\n lastSyncTime?: number;\n className?: string;\n isSelectable?: boolean;\n isSelected?: boolean;\n onPlay: (messageId: number, chatId: number) => void;\n onReadMedia?: () => void;\n onCancelUpload?: () => void;\n onDateClick?: (messageId: number, chatId: number) => void;\n};\n\ntype StateProps = {\n theme: ISettings['theme'];\n};\n\ninterface ISeekMethods {\n handleStartSeek: (e: React.MouseEvent<HTMLElement>) => void;\n handleSeek: (e: React.MouseEvent<HTMLElement>) => void;\n handleStopSeek: () => void;\n}\n\nconst AVG_VOICE_DURATION = 30;\nconst MIN_SPIKES = IS_MOBILE_SCREEN ? 20 : 25;\nconst MAX_SPIKES = IS_MOBILE_SCREEN ? 50 : 75;\n// This is needed for browsers requiring user interaction before playing.\nconst PRELOAD = true;\n\nconst Audio: FC<OwnProps & StateProps> = ({\n theme,\n message,\n senderTitle,\n uploadProgress,\n renderingFor,\n date,\n lastSyncTime,\n className,\n isSelectable,\n isSelected,\n onPlay,\n onReadMedia,\n onCancelUpload,\n onDateClick,\n}) => {\n const { content: { audio, voice }, isMediaUnread } = message;\n const isVoice = Boolean(voice);\n const isSeeking = useRef<boolean>(false);\n const lang = useLang();\n\n const [isActivated, setIsActivated] = useState(false);\n const shouldDownload = (isActivated || PRELOAD) && lastSyncTime;\n\n const { mediaData, downloadProgress } = useMediaWithDownloadProgress(\n getMessageMediaHash(message, 'inline'),\n !shouldDownload,\n getMessageMediaFormat(message, 'inline'),\n );\n\n function handleForcePlay() {\n setIsActivated(true);\n onPlay(message.id, message.chatId);\n }\n\n const {\n isBuffered, bufferedProgress, bufferingHandlers, checkBuffering,\n } = useBuffering();\n\n const {\n isPlaying, playProgress, playPause, setCurrentTime, duration,\n } = useAudioPlayer(\n getMessageKey(message),\n getMediaDuration(message)!,\n mediaData,\n bufferingHandlers,\n checkBuffering,\n isActivated,\n handleForcePlay,\n isMessageLocal(message),\n );\n\n useEffect(() => {\n setIsActivated(isPlaying);\n }, [isPlaying]);\n\n const {\n isUploading, isTransferring, transferProgress,\n } = getMediaTransferState(message, uploadProgress || downloadProgress, isActivated && !isBuffered);\n\n const {\n shouldRender: shouldRenderSpinner,\n transitionClassNames: spinnerClassNames,\n } = useShowTransition(isTransferring);\n\n const handleButtonClick = useCallback(() => {\n if (isUploading) {\n if (onCancelUpload) {\n onCancelUpload();\n }\n\n return;\n }\n\n if (!isPlaying) {\n onPlay(message.id, message.chatId);\n }\n\n setIsActivated(!isActivated);\n playPause();\n }, [isPlaying, isUploading, message.id, message.chatId, onCancelUpload, onPlay, playPause, isActivated]);\n\n useEffect(() => {\n if (isPlaying && onReadMedia && isMediaUnread) {\n onReadMedia();\n }\n }, [isPlaying, isMediaUnread, onReadMedia]);\n\n const handleSeek = useCallback((e: React.MouseEvent<HTMLElement>) => {\n if (isSeeking.current) {\n const seekBar = e.currentTarget.closest('.seekline,.waveform');\n if (seekBar) {\n const { width, left } = seekBar.getBoundingClientRect();\n setCurrentTime(duration * ((e.clientX - left) / width));\n }\n }\n }, [duration, setCurrentTime]);\n\n const handleStartSeek = useCallback((e: React.MouseEvent<HTMLElement>) => {\n isSeeking.current = true;\n handleSeek(e);\n }, [handleSeek]);\n\n const handleStopSeek = useCallback(() => {\n isSeeking.current = false;\n }, []);\n\n const handleDateClick = useCallback(() => {\n onDateClick!(message.id, message.chatId);\n }, [onDateClick, message.id, message.chatId]);\n\n function getFirstLine() {\n if (isVoice) {\n return senderTitle || 'Voice';\n }\n\n const { title, fileName } = audio!;\n\n return title || fileName;\n }\n\n function getSecondLine() {\n if (isVoice) {\n return formatMediaDuration(voice!.duration);\n }\n\n const { performer } = audio!;\n\n return (\n <>\n {performer && renderText(performer)}\n {performer && senderTitle && <span>&bull;</span>}\n {senderTitle && renderText(senderTitle)}\n </>\n );\n }\n\n const seekHandlers = { handleStartSeek, handleSeek, handleStopSeek };\n const isOwn = isOwnMessage(message);\n const renderedWaveform = useMemo(\n () => voice && renderWaveform(voice, playProgress, isOwn, seekHandlers, theme),\n [voice, playProgress, isOwn, seekHandlers, theme],\n );\n\n const fullClassName = buildClassName(\n 'Audio media-inner',\n className,\n isOwn && !renderingFor && 'own',\n renderingFor && 'bigger',\n isSelected && 'audio-is-selected',\n );\n\n const buttonClassNames = ['toggle-play'];\n if (shouldRenderSpinner) {\n buttonClassNames.push('loading');\n } else if (isPlaying) {\n buttonClassNames.push('pause');\n } else if (!isPlaying) {\n buttonClassNames.push('play');\n }\n\n const showSeekline = isPlaying || (playProgress > 0 && playProgress < 1);\n const contentClassName = buildClassName('content', showSeekline && 'with-seekline');\n\n function renderSearchResult() {\n return (\n <>\n <div className={contentClassName}>\n <div className=\"content-row\">\n <p className=\"title\" dir=\"auto\">{renderText(getFirstLine())}</p>\n\n <div className=\"message-date\">\n {date && (\n <Link\n className=\"date\"\n onClick={handleDateClick}\n >\n {formatPastTimeShort(lang, date * 1000)}\n </Link>\n )}\n </div>\n </div>\n\n {showSeekline && renderSeekline(playProgress, bufferedProgress, seekHandlers)}\n {!showSeekline && (\n <p className=\"duration\" dir=\"auto\">\n {playProgress > 0 ? `${formatMediaDuration(duration * playProgress)} / ` : undefined}\n {getSecondLine()}\n </p>\n )}\n </div>\n </>\n );\n }\n\n return (\n <div className={fullClassName} dir={lang.isRtl ? 'rtl' : undefined}>\n {isSelectable && (\n <div className=\"message-select-control\">\n {isSelected && <i className=\"icon-select\" />}\n </div>\n )}\n <Button\n round\n ripple={!IS_MOBILE_SCREEN}\n size={renderingFor ? 'smaller' : 'tiny'}\n className={buttonClassNames.join(' ')}\n ariaLabel={isPlaying ? 'Pause audio' : 'Play audio'}\n onClick={handleButtonClick}\n isRtl={lang.isRtl}\n >\n <i className=\"icon-play\" />\n <i className=\"icon-pause\" />\n </Button>\n {shouldRenderSpinner && (\n <div className={buildClassName('media-loading', spinnerClassNames)}>\n <ProgressSpinner\n progress={transferProgress}\n transparent\n size={renderingFor ? 'm' : 's'}\n onClick={handleButtonClick}\n />\n </div>\n )}\n {renderingFor === 'searchResult' && renderSearchResult()}\n {renderingFor !== 'searchResult' && audio && renderAudio(\n lang, audio, isPlaying, playProgress, bufferedProgress, seekHandlers, date,\n onDateClick ? handleDateClick : undefined,\n )}\n {renderingFor !== 'searchResult' && voice && renderVoice(voice, renderedWaveform, isMediaUnread)}\n </div>\n );\n};\n\nfunction renderAudio(\n lang: LangFn,\n audio: ApiAudio,\n isPlaying: boolean,\n playProgress: number,\n bufferedProgress: number,\n seekHandlers: ISeekMethods,\n date?: number,\n handleDateClick?: () => void,\n) {\n const {\n title, performer, duration, fileName,\n } = audio;\n const showSeekline = isPlaying || (playProgress > 0 && playProgress < 1);\n\n return (\n <div className=\"content\">\n <p className=\"title\" dir=\"auto\">{renderText(title || fileName)}</p>\n {showSeekline && renderSeekline(playProgress, bufferedProgress, seekHandlers)}\n {!showSeekline && (\n <div className=\"meta\" dir=\"auto\">\n <span className=\"performer\">{renderText(performer || 'Unknown')}</span>\n {date && (\n <>\n {' '}\n &bull;\n {' '}\n <Link className=\"date\" onClick={handleDateClick}>{formatMediaDateTime(lang, date * 1000)}</Link>\n </>\n )}\n </div>\n )}\n <p className=\"duration\" dir=\"auto\">\n {playProgress > 0 ? `${formatMediaDuration(duration * playProgress)} / ` : undefined}\n {formatMediaDuration(duration)}\n </p>\n </div>\n );\n}\n\nfunction renderVoice(voice: ApiVoice, renderedWaveform: any, isMediaUnread?: boolean) {\n return (\n <div className=\"content\">\n {renderedWaveform}\n <p className=\"voice-duration\" dir=\"auto\">\n {formatMediaDuration(voice.duration)}\n {isMediaUnread && <span>&bull;</span>}\n </p>\n </div>\n );\n}\n\nfunction renderWaveform(\n voice: ApiVoice,\n playProgress = 0,\n isOwn = false,\n { handleStartSeek, handleSeek, handleStopSeek }: ISeekMethods,\n theme: ISettings['theme'],\n) {\n const { waveform, duration } = voice;\n\n if (!waveform) {\n return undefined;\n }\n\n const fillColor = theme === 'dark' ? '#494B75' : '#CBCBCB';\n const fillOwnColor = theme === 'dark' ? '#C69C85' : '#B0DEA6';\n const progressFillColor = theme === 'dark' ? '#868DF5' : '#54a3e6';\n const progressFillOwnColor = theme === 'dark' ? '#FFFFFF' : '#53ad53';\n const durationFactor = Math.min(duration / AVG_VOICE_DURATION, 1);\n const spikesCount = Math.round(MIN_SPIKES + (MAX_SPIKES - MIN_SPIKES) * durationFactor);\n const decodedWaveform = decodeWaveform(new Uint8Array(waveform));\n const { data: spikes, peak } = interpolateArray(decodedWaveform, spikesCount);\n const { src, width, height } = renderWaveformToDataUri(spikes, playProgress, {\n peak,\n fillStyle: isOwn ? fillOwnColor : fillColor,\n progressFillStyle: isOwn ? progressFillOwnColor : progressFillColor,\n });\n\n return (\n // eslint-disable-next-line jsx-a11y/no-noninteractive-element-interactions\n <img\n src={src}\n alt=\"\"\n width={width}\n height={height}\n className=\"waveform\"\n draggable={false}\n onMouseDown={handleStartSeek}\n onMouseMove={handleSeek}\n onMouseUp={handleStopSeek}\n />\n );\n}\n\nfunction renderSeekline(\n playProgress: number,\n bufferedProgress: number,\n { handleStartSeek, handleSeek, handleStopSeek }: ISeekMethods,\n) {\n return (\n <div\n className=\"seekline no-selection\"\n onMouseDown={handleStartSeek}\n onMouseMove={handleSeek}\n onMouseUp={handleStopSeek}\n >\n <span className=\"seekline-buffered-progress\">\n <i\n // @ts-ignore\n style={`transform: translateX(${bufferedProgress * 100}%)`}\n />\n </span>\n <span className=\"seekline-play-progress\">\n <i\n // @ts-ignore\n style={`transform: translateX(${playProgress * 100}%)`}\n />\n </span>\n <span className=\"seekline-thumb\">\n <i\n // @ts-ignore\n style={`transform: translateX(${playProgress * 100}%)`}\n />\n </span>\n </div>\n );\n}\n\nexport default memo(withGlobal<OwnProps>((global) => ({ theme: global.settings.byKey.theme }))(Audio));\n","/* eslint-disable no-bitwise */\n\n// eslint-disable-next-line max-len\n// Ref: https://github.com/telegramdesktop/tdesktop/blob/0743e71ab6b928d2ee5bae1aed991849b1e2b291/Telegram/SourceFiles/data/data_document.cpp#L1018\nexport function decodeWaveform(encoded5bit: Uint8Array) {\n const bitsCount = encoded5bit.length * 8;\n const valuesCount = Math.floor(bitsCount / 5);\n if (!valuesCount) {\n return [];\n }\n\n // Read each 5 bit of encoded5bit as 0-31 unsigned char.\n // We count the index of the byte in which the desired 5-bit sequence starts.\n // And then we read a uint16 starting from that byte to guarantee to get all of those 5 bits.\n //\n // BUT! if it is the last byte we have, we're not allowed to read a uint16 starting with it.\n // Because it will be an overflow (we'll access one byte after the available memory).\n // We see, that only the last 5 bits could start in the last available byte and be problematic.\n // So we read in a general way all the entries in a general way except the last one.\n const result = Array(valuesCount);\n const bitsData = encoded5bit;\n for (let i = 0, l = valuesCount - 1; i !== l; ++i) {\n const byteIndex = Math.floor((i * 5) / 8);\n const bitShift = Math.floor((i * 5) % 8);\n const value = bitsData[byteIndex] + (bitsData[byteIndex + 1] << 8);\n result[i] = ((value >> bitShift) & 0x1F);\n }\n const lastByteIndex = Math.floor(((valuesCount - 1) * 5) / 8);\n const lastBitShift = Math.floor(((valuesCount - 1) * 5) % 8);\n const lastValue = bitsData[lastByteIndex] + (bitsData[lastByteIndex + 1] << 8);\n result[valuesCount - 1] = (lastValue >> lastBitShift) & 0x1F;\n\n return result;\n}\n\nexport function interpolateArray(data: number[], fitCount: number) {\n let peak = 0;\n const newData = new Array(fitCount);\n const springFactor = data.length / fitCount;\n const leftFiller = data[0];\n const rightFiller = data[data.length - 1];\n for (let i = 0; i < fitCount; i++) {\n const idx = Math.floor(i * springFactor);\n const val = ((data[idx - 1] ?? leftFiller) + (data[idx] ?? leftFiller) + (data[idx + 1] ?? rightFiller)) / 3;\n newData[i] = val;\n if (peak < val) {\n peak = val;\n }\n }\n return { data: newData, peak };\n}\n","type IWaveformProps = {\n peak: number;\n fillStyle: string;\n progressFillStyle: string;\n};\n\nconst SPIKE_WIDTH = 2;\nconst SPIKE_STEP = 4;\nconst SPIKE_RADIUS = 1;\nconst HEIGHT = 23;\n\nexport function renderWaveformToDataUri(\n spikes: number[],\n progress: number,\n {\n peak, fillStyle, progressFillStyle,\n }: IWaveformProps,\n) {\n const width = spikes.length * SPIKE_STEP;\n const height = HEIGHT;\n\n const canvas = document.createElement('canvas');\n canvas.width = width * 2;\n canvas.height = height * 2;\n canvas.style.width = `${width}px`;\n canvas.style.height = `${height}px`;\n\n const ctx = canvas.getContext('2d')!;\n ctx.scale(2, 2);\n\n spikes.forEach((item, i) => {\n ctx.globalAlpha = (i / spikes.length >= progress) ? 0.5 : 1;\n ctx.fillStyle = progress > i / spikes.length ? progressFillStyle : fillStyle;\n const spikeHeight = Math.max(2, HEIGHT * (item / Math.max(1, peak)));\n roundedRectangle(ctx, i * SPIKE_STEP, height, SPIKE_WIDTH, spikeHeight, SPIKE_RADIUS);\n ctx.fill();\n });\n\n return {\n src: canvas.toDataURL(),\n width,\n height,\n };\n}\n\nfunction roundedRectangle(\n ctx: CanvasRenderingContext2D, x: number, y: number, width: number, height: number, radius: number,\n) {\n if (width < 2 * radius) {\n radius = width / 2;\n }\n if (height < 2 * radius) {\n radius = height / 2;\n }\n\n ctx.beginPath();\n ctx.moveTo(x + radius, y);\n ctx.arcTo(x + width, y, x + width, y - height, radius);\n ctx.arcTo(x + width, y - height, x, y - height, radius);\n ctx.arcTo(x, y - height, x, y, radius);\n ctx.arcTo(x, y, x + width, y, radius);\n ctx.closePath();\n}\n","import React, {\n FC, useLayoutEffect, useRef, memo,\n} from '../../lib/teact/teact';\n\nimport buildClassName from '../../util/buildClassName';\n\nimport './Tab.scss';\n\ntype OwnProps = {\n className?: string;\n title: string;\n active?: boolean;\n badgeCount?: number;\n isBadgeActive?: boolean;\n previousActiveTab?: number;\n onClick: (arg: number) => void;\n clickArg: number;\n};\n\nconst Tab: FC<OwnProps> = ({\n className,\n title,\n active,\n badgeCount,\n isBadgeActive,\n previousActiveTab,\n onClick,\n clickArg,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const tabRef = useRef<HTMLButtonElement>(null);\n\n useLayoutEffect(() => {\n if (!active || previousActiveTab === undefined) {\n return;\n }\n\n const tab = tabRef.current!;\n const indicator = tab.querySelector('i')!;\n const currentIndicator = tab.parentElement!.children[previousActiveTab].querySelector('i')!;\n\n currentIndicator.classList.remove('animate');\n indicator.classList.remove('animate');\n\n // We move and resize our indicator so it repeats the position and size of the previous one.\n const shiftLeft = currentIndicator.parentElement!.offsetLeft - indicator.parentElement!.offsetLeft;\n const scaleFactor = currentIndicator.clientWidth / indicator.clientWidth;\n indicator.style.transform = `translate3d(${shiftLeft}px, 0, 0) scale3d(${scaleFactor}, 1, 1)`;\n\n // 3 AFs needed here to synchronize animations with Transition component\n requestAnimationFrame(() => {\n requestAnimationFrame(() => {\n requestAnimationFrame(() => {\n // Now we remove the transform to let it animate to its own position and size.\n indicator.classList.add('animate');\n indicator.style.transform = 'none';\n });\n });\n });\n }, [active, previousActiveTab]);\n\n return (\n <button\n type=\"button\"\n className={buildClassName('Tab', className, active && 'active')}\n onClick={() => onClick(clickArg)}\n ref={tabRef}\n >\n <span>\n {title}\n {!!badgeCount && (\n <span className={buildClassName('badge', isBadgeActive && 'active')}>{badgeCount}</span>\n )}\n <i />\n </span>\n </button>\n );\n};\n\nexport default memo(Tab);\n","import React, {\n FC, memo, useRef, useEffect,\n} from '../../lib/teact/teact';\n\nimport fastSmoothScrollHorizontal from '../../util/fastSmoothScrollHorizontal';\nimport usePrevious from '../../hooks/usePrevious';\nimport useHorizontalScroll from '../../hooks/useHorizontalScroll';\nimport useLang from '../../hooks/useLang';\n\nimport Tab from './Tab';\n\nimport './TabList.scss';\n\nexport type TabWithProperties = {\n title: string;\n badgeCount?: number;\n isBadgeActive?: boolean;\n};\n\ntype OwnProps = {\n tabs: readonly TabWithProperties[];\n activeTab: number;\n big?: boolean;\n onSwitchTab: (index: number) => void;\n};\n\nconst TAB_SCROLL_THRESHOLD_PX = 16;\n\nconst TabList: FC<OwnProps> = ({\n tabs, activeTab, big, onSwitchTab,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const containerRef = useRef<HTMLDivElement>(null);\n const previousActiveTab = usePrevious(activeTab);\n\n useHorizontalScroll(containerRef);\n\n // Scroll container to place active tab in the center\n useEffect(() => {\n const container = containerRef.current!;\n if (container.scrollWidth <= container.offsetWidth) {\n return;\n }\n\n const activeTabElement = container.querySelector('.Tab.active') as HTMLElement | null;\n if (activeTabElement) {\n const newLeft = activeTabElement.offsetLeft - (container.offsetWidth / 2) + (activeTabElement.offsetWidth / 2);\n\n // Prevent scrolling by only a couple of pixels, which doesn't look smooth\n if (Math.abs(newLeft - container.scrollLeft) < TAB_SCROLL_THRESHOLD_PX) {\n return;\n }\n\n fastSmoothScrollHorizontal(container, newLeft);\n }\n }, [activeTab]);\n\n const lang = useLang();\n\n return (\n <div\n className={`TabList no-selection no-scrollbar ${big ? 'big' : ''}`}\n ref={containerRef}\n dir={lang.isRtl ? 'rtl' : undefined}\n >\n {tabs.map((tab, i) => (\n <Tab\n key={tab.title}\n title={lang(tab.title)}\n active={i === activeTab}\n badgeCount={tab.badgeCount}\n isBadgeActive={tab.isBadgeActive}\n previousActiveTab={previousActiveTab}\n onClick={onSwitchTab}\n clickArg={i}\n />\n ))}\n </div>\n );\n};\n\nexport default memo(TabList);\n","import { ApiError } from '../api/types';\n\nconst READABLE_ERROR_MESSAGES: Record<string, string> = {\n CHAT_RESTRICTED: 'You can\\'t send messages in this chat, you were restricted',\n CHAT_WRITE_FORBIDDEN: 'You can\\'t write in this chat',\n CHAT_SEND_POLL_FORBIDDEN: 'You can\\'t create polls in this chat',\n CHAT_SEND_STICKERS_FORBIDDEN: 'You can\\'t send stickers in this chat',\n CHAT_SEND_GIFS_FORBIDDEN: 'You can\\'t send gifs in this chat',\n CHAT_SEND_MEDIA_FORBIDDEN: 'You can\\'t send media in this chat',\n CHAT_LINK_EXISTS: 'The chat is public, you can\\'t hide the history to new users',\n // eslint-disable-next-line max-len\n SLOWMODE_WAIT_X: 'Slowmode is enabled in this chat: you must wait for the specified number of seconds before sending another message to the chat.',\n USER_BANNED_IN_CHANNEL: 'You\\'re banned from sending messages in supergroups / channels',\n USER_IS_BLOCKED: 'You were blocked by this user',\n YOU_BLOCKED_USER: 'You blocked this user',\n IMAGE_PROCESS_FAILED: 'Failure while processing image',\n MEDIA_EMPTY: 'The provided media object is invalid',\n MEDIA_INVALID: 'Media invalid',\n PHOTO_EXT_INVALID: 'The extension of the photo is invalid',\n PHOTO_INVALID_DIMENSIONS: 'The photo dimensions are invalid',\n PHOTO_SAVE_FILE_INVALID: 'Internal issues, try again later',\n // eslint-disable-next-line max-len\n MESSAGE_DELETE_FORBIDDEN: 'You can\\'t delete one of the messages you tried to delete, most likely because it is a service message.',\n MESSAGE_POLL_CLOSED: 'Poll closed',\n MESSAGE_EDIT_TIME_EXPIRED: 'You can\\'t edit this message anymore.',\n CHAT_ADMIN_REQUIRED: 'You must be an admin in this chat to do this',\n PINNED_DIALOGS_TOO_MUCH: 'Sorry, you can only pin 5 chats to the top',\n DIALOG_FILTERS_TOO_MUCH: 'Sorry, you can\\'t have more than 10 folders',\n CHANNEL_PRIVATE: 'This channel is private',\n MEDIA_CAPTION_TOO_LONG: 'The provided caption is too long',\n ADDRESS_STREET_LINE1_INVALID: 'The address you provided is not valid',\n ADDRESS_STREET_LINE2_INVALID: 'The address you provided is not valid',\n ADDRESS_CITY_INVALID: 'The city you provided is not valid',\n ADDRESS_COUNTRY_INVALID: 'The country you provided is not valid',\n ADDRESS_POSTCODE_INVALID: 'The postcode you provided is not valid',\n ADDRESS_STATE_INVALID: 'The state you provided is not valid',\n REQ_INFO_NAME_INVALID: 'The name you provided is not valid',\n REQ_INFO_PHONE_INVALID: 'The phone you provided is not valid',\n REQ_INFO_EMAIL_INVALID: 'The email you provided is not valid',\n // TODO Bring back after fixing the weird bug\n // CHANNEL_INVALID: 'An error occurred. Please try again later',\n LINK_NOT_MODIFIED: 'This discussion is already linked to the channel',\n\n // Non-API errors\n SERVICE_WORKER_DISABLED: 'Service Worker is disabled. Please reload the page without holding <Shift> key.',\n // eslint-disable-next-line max-len\n CAPTION_TOO_LONG_PLEASE_REMOVE_CHARACTERS: 'The provided caption is too long. Please remove {EXTRA_CHARS_COUNT} character{PLURAL_S}.',\n // eslint-disable-next-line max-len\n FRESH_RESET_AUTHORISATION_FORBIDDEN: 'You cant logout other sessions if less than 24 hours have passed since you logged on the current session',\n\n BOTS_TOO_MUCH: 'There are too many bots in this chat/channel',\n BOT_GROUPS_BLOCKED: 'This bot can\\'t be added to groups',\n USERS_TOO_MUCH: 'The maximum number of users has been exceeded',\n USER_CHANNELS_TOO_MUCH: 'One of the users you tried to add is already in too many channels/supergroups',\n USER_KICKED: 'This user was kicked from this supergroup/channel',\n USER_NOT_MUTUAL_CONTACT: 'The provided user is not a mutual contact',\n USER_PRIVACY_RESTRICTED: 'The user\\'s privacy settings do not allow you to do this',\n INVITE_HASH_EMPTY: 'The invite hash is empty',\n INVITE_HASH_EXPIRED: 'The invite link has expired',\n INVITE_HASH_INVALID: 'The invite hash is invalid',\n CHANNELS_TOO_MUCH: 'You have joined too many channels/supergroups',\n USER_ALREADY_PARTICIPANT: 'You already in the group',\n};\n\nexport default function getReadableErrorText(error: ApiError) {\n const { message, isSlowMode, textParams } = error;\n // Currently Telegram API doesn't return `SLOWMODE_WAIT_X` error as described in the docs\n if (isSlowMode) {\n const extraPartIndex = message.indexOf(' (caused by');\n return extraPartIndex > 0 ? message.substring(0, extraPartIndex) : message;\n }\n let errorMessage = READABLE_ERROR_MESSAGES[message];\n if (errorMessage && textParams) {\n errorMessage = Object.keys(textParams).reduce((acc, current) => {\n return acc.replace(current, textParams[current]);\n }, errorMessage as string);\n }\n return errorMessage;\n}\n","import { useMemo } from '../lib/teact/teact';\nimport { getDispatch } from '../lib/teact/teactn';\nimport { ApiChat, ApiUser } from '../api/types';\nimport {\n isChatArchived, getCanDeleteChat, isChatPrivate, isChatChannel,\n} from '../modules/helpers';\nimport useLang from './useLang';\n\nexport default ({\n chat,\n privateChatUser,\n handleDelete,\n folderId,\n isPinned,\n}: {\n chat: ApiChat | undefined;\n privateChatUser: ApiUser | undefined;\n handleDelete: () => void;\n folderId?: number;\n isPinned?: boolean;\n}) => {\n const lang = useLang();\n\n const {\n toggleChatPinned,\n updateChatMutedState,\n toggleChatArchived,\n toggleChatUnread,\n } = getDispatch();\n\n return useMemo(() => {\n if (!chat) {\n return undefined;\n }\n\n const isChatWithSelf = privateChatUser && privateChatUser.isSelf;\n\n const actionUnreadMark = chat.unreadCount || chat.hasUnreadMark\n ? { title: lang('MarkAsRead'), icon: 'readchats', handler: () => toggleChatUnread({ id: chat.id }) }\n : { title: lang('MarkAsUnread'), icon: 'unread', handler: () => toggleChatUnread({ id: chat.id }) };\n\n const actionPin = isPinned\n ? {\n title: lang('UnpinFromTop'),\n icon: 'unpin',\n handler: () => toggleChatPinned({ id: chat.id, folderId }),\n }\n : { title: lang('PinToTop'), icon: 'pin', handler: () => toggleChatPinned({ id: chat.id, folderId }) };\n\n const actionMute = chat.isMuted\n ? {\n title: lang('ChatList.Unmute'),\n icon: 'unmute',\n handler: () => updateChatMutedState({ chatId: chat.id, isMuted: false }),\n }\n : {\n title: lang('ChatList.Mute'),\n icon: 'mute',\n handler: () => updateChatMutedState({ chatId: chat.id, isMuted: true }),\n };\n\n const actionArchive = isChatArchived(chat)\n ? { title: lang('Unarchive'), icon: 'unarchive', handler: () => toggleChatArchived({ id: chat.id }) }\n : { title: lang('Archive'), icon: 'archive', handler: () => toggleChatArchived({ id: chat.id }) };\n\n const actionDelete = {\n title: isChatPrivate(chat.id)\n ? lang('Delete')\n : lang(getCanDeleteChat(chat)\n ? 'DeleteChat'\n : (isChatChannel(chat) ? 'LeaveChannel' : 'Group.LeaveGroup')),\n icon: 'delete',\n destructive: true,\n handler: handleDelete,\n };\n\n return [\n actionUnreadMark,\n actionPin,\n ...(!isChatWithSelf ? [\n actionMute,\n actionArchive,\n ] : []),\n actionDelete,\n ];\n }, [\n chat, privateChatUser, lang, isPinned, handleDelete, toggleChatUnread, toggleChatPinned, folderId,\n updateChatMutedState, toggleChatArchived,\n ]);\n};\n","import React, { FC, memo } from '../../lib/teact/teact';\n\nimport { ApiMessage, ApiMessageOutgoingStatus } from '../../api/types';\n\nimport { formatPastTimeShort } from '../../util/dateFormat';\nimport useLang from '../../hooks/useLang';\n\nimport MessageOutgoingStatus from './MessageOutgoingStatus';\n\nimport './LastMessageMeta.scss';\n\ntype OwnProps = {\n message: ApiMessage;\n outgoingStatus?: ApiMessageOutgoingStatus;\n};\n\nconst LastMessageMeta: FC<OwnProps> = ({ message, outgoingStatus }) => {\n const lang = useLang();\n return (\n <div className=\"LastMessageMeta\">\n {outgoingStatus && (\n <MessageOutgoingStatus status={outgoingStatus} />\n )}\n <span className=\"time\">{formatPastTimeShort(lang, message.date * 1000)}</span>\n </div>\n );\n};\n\nexport default memo(LastMessageMeta);\n","import React, { FC, memo } from '../../lib/teact/teact';\n\nimport { ApiMessageOutgoingStatus } from '../../api/types';\n\nimport Transition from '../ui/Transition';\n\nimport './MessageOutgoingStatus.scss';\n\ntype OwnProps = {\n status: ApiMessageOutgoingStatus;\n};\n\nenum Keys {\n failed, pending, succeeded, read,\n}\n\nconst MessageOutgoingStatus: FC<OwnProps> = ({ status }) => {\n return (\n <div className=\"MessageOutgoingStatus\">\n <Transition name=\"reveal\" activeKey={Keys[status]}>\n {() => (\n <i className={`icon-message-${status}`} />\n )}\n </Transition>\n </div>\n );\n};\n\nexport default memo(MessageOutgoingStatus);\n","import { useState, useEffect } from '../lib/teact/teact';\nimport { IAnchorPosition } from '../types';\n\nexport default (\n anchor: IAnchorPosition | undefined,\n getTriggerElement: () => HTMLElement | null,\n getRootElement: () => HTMLElement | null,\n getMenuElement: () => HTMLElement | null,\n extraPaddingX = 0,\n extraTopPadding = 0,\n) => {\n const [positionX, setPositionX] = useState<'right' | 'left'>('right');\n const [positionY, setPositionY] = useState<'top' | 'bottom'>('bottom');\n const [style, setStyle] = useState('');\n\n useEffect(() => {\n const triggerEl = getTriggerElement();\n if (!anchor || !triggerEl) {\n return;\n }\n\n let { x, y } = anchor;\n const emptyRect = {\n width: 0, left: 0, height: 0, top: 0,\n };\n\n const menuEl = getMenuElement();\n const rootEl = getRootElement();\n\n const triggerRect = triggerEl.getBoundingClientRect();\n const menuRect = menuEl ? { width: menuEl.offsetWidth, height: menuEl.offsetHeight } : emptyRect;\n const rootRect = rootEl ? rootEl.getBoundingClientRect() : emptyRect;\n\n if (x + menuRect.width + extraPaddingX < rootRect.width + rootRect.left) {\n setPositionX('left');\n x += 3;\n } else if (x - menuRect.width > 0) {\n setPositionX('right');\n x -= 3;\n } else {\n setPositionX('left');\n x = 16;\n }\n\n if (y + menuRect.height < rootRect.height + rootRect.top) {\n setPositionY('top');\n } else {\n setPositionY('bottom');\n\n if (y - menuRect.height < rootRect.top + extraTopPadding) {\n y = rootRect.top + extraTopPadding + menuRect.height;\n }\n }\n\n setStyle(`left: ${x - triggerRect.left}px; top: ${y - triggerRect.top}px;`);\n }, [\n anchor, extraPaddingX, extraTopPadding,\n getMenuElement, getRootElement, getTriggerElement,\n ]);\n\n return {\n positionX,\n positionY,\n style,\n };\n};\n","import React, { FC, useRef } from '../../lib/teact/teact';\n\nimport useShowTransition from '../../hooks/useShowTransition';\nimport usePrevious from '../../hooks/usePrevious';\nimport buildClassName from '../../util/buildClassName';\n\ntype ChildrenFn = () => any;\n\ntype OwnProps = {\n isOpen: boolean;\n isCustom?: boolean;\n id?: string;\n className?: string;\n onClick?: (e: React.MouseEvent<HTMLElement, MouseEvent>) => void;\n children: ChildrenFn;\n};\n\nconst ShowTransition: FC<OwnProps> = ({\n isOpen, isCustom, id, className, onClick, children,\n}) => {\n const { shouldRender, transitionClassNames } = useShowTransition(\n isOpen, undefined, undefined, isCustom ? false : undefined,\n );\n const prevIsOpen = usePrevious(isOpen);\n const prevChildren = usePrevious(children);\n const fromChildrenRef = useRef<ChildrenFn>();\n\n if (prevIsOpen && !isOpen) {\n fromChildrenRef.current = prevChildren;\n }\n\n return (\n shouldRender && (\n <div id={id} className={buildClassName(className, transitionClassNames)} onClick={onClick}>\n {isOpen ? children() : fromChildrenRef.current!()}\n </div>\n )\n );\n};\n\nexport default ShowTransition;\n","import { useRef } from '../lib/teact/teact';\n\nimport usePrevious from './usePrevious';\nimport useForceUpdate from './useForceUpdate';\nimport useOnChange from './useOnChange';\n\nexport default function usePrevDuringAnimation(current: any, duration?: number) {\n const prev = usePrevious(current, true);\n const timeoutRef = useRef<number>();\n const forceUpdate = useForceUpdate();\n // eslint-disable-next-line no-null/no-null\n const isCurrentPresent = current !== undefined && current !== null;\n // eslint-disable-next-line no-null/no-null\n const isPrevPresent = prev !== undefined && prev !== null;\n\n if (isCurrentPresent && timeoutRef.current) {\n clearTimeout(timeoutRef.current);\n timeoutRef.current = undefined;\n }\n\n useOnChange(() => {\n // When `current` becomes empty\n if (duration && !isCurrentPresent && isPrevPresent && !timeoutRef.current) {\n timeoutRef.current = window.setTimeout(() => {\n timeoutRef.current = undefined;\n forceUpdate();\n }, duration);\n }\n }, [current]);\n\n return !timeoutRef.current || !duration || isCurrentPresent ? current : prev;\n}\n","import {\n useCallback, useEffect, useRef, useState,\n} from '../lib/teact/teact';\n\nimport { register } from '../util/audioPlayer';\nimport useEffectWithPrevDeps from './useEffectWithPrevDeps';\nimport { isSafariPatchInProgress } from '../util/patchSafariProgressiveAudio';\nimport useOnChange from './useOnChange';\n\ntype Handler = (e: Event) => void;\n\nexport default (\n trackId: string,\n originalDuration: number, // Sometimes incorrect for voice messages\n src?: string,\n handlers?: Record<string, Handler>,\n onInit?: (element: HTMLAudioElement) => void,\n shouldPlay = false,\n onForcePlay?: NoneToVoidFunction,\n noPlaylist = false,\n) => {\n // eslint-disable-next-line no-null/no-null\n const controllerRef = useRef<ReturnType<typeof register>>(null);\n\n const [isPlaying, setIsPlaying] = useState(false);\n let isPlayingSync = isPlaying;\n\n const [playProgress, setPlayProgress] = useState<number>(0);\n\n useOnChange(() => {\n controllerRef.current = register(trackId, (eventName, e) => {\n switch (eventName) {\n case 'onPlay':\n setIsPlaying(true);\n break;\n case 'onPause':\n setIsPlaying(false);\n break;\n case 'onTimeUpdate': {\n const { proxy } = controllerRef.current!;\n const duration = proxy.duration && Number.isFinite(proxy.duration) ? proxy.duration : originalDuration;\n setPlayProgress(proxy.currentTime / duration);\n break;\n }\n }\n\n if (handlers && handlers[eventName]) {\n handlers[eventName](e);\n }\n }, onForcePlay);\n\n const { proxy } = controllerRef.current!;\n\n if (!isPlaying && !proxy.paused) {\n setIsPlaying(true);\n isPlayingSync = true;\n }\n\n if (onInit) {\n onInit(proxy);\n }\n }, [trackId]);\n\n const {\n play, pause, setCurrentTime, proxy, destroy,\n } = controllerRef.current!;\n const duration = proxy.duration && Number.isFinite(proxy.duration) ? proxy.duration : originalDuration;\n\n // RAF progress\n useEffect(() => {\n if (duration && !isSafariPatchInProgress(proxy)) {\n setPlayProgress(proxy.currentTime / duration);\n }\n }, [duration, playProgress, proxy]);\n\n // Cleanup\n useEffect(() => () => {\n destroy(noPlaylist);\n }, [destroy, noPlaylist]);\n\n // Autoplay once `src` is present\n useEffectWithPrevDeps(([prevShouldPlay, prevSrc]) => {\n if (prevShouldPlay === shouldPlay && src === prevSrc) {\n return;\n }\n\n // When paused by another player\n if (proxy.src && proxy.paused) {\n return;\n }\n\n if (shouldPlay && src && !isPlaying) {\n play(src);\n }\n }, [shouldPlay, src, isPlaying, play, proxy.src, proxy.paused]);\n\n const playPause = useCallback(() => {\n if (isPlaying) {\n pause();\n } else if (src) {\n play(src);\n }\n }, [src, pause, play, isPlaying]);\n\n return {\n isPlaying: isPlayingSync,\n playProgress,\n playPause,\n setCurrentTime,\n audioProxy: proxy,\n duration,\n };\n};\n","import { IS_SAFARI } from './environment';\nimport safePlay from './safePlay';\nimport { patchSafariProgressiveAudio, isSafariPatchInProgress } from './patchSafariProgressiveAudio';\nimport { getDispatch } from '../lib/teact/teactn';\nimport { parseMessageKey } from '../modules/helpers';\n\ntype Handler = (eventName: string, e: Event) => void;\n\ninterface Track {\n audio: HTMLAudioElement;\n proxy: HTMLAudioElement;\n handlers: Handler[];\n onForcePlay?: NoneToVoidFunction;\n}\n\nconst tracks = new Map<string, Track>();\nlet queue: string[] = [];\n\nlet currentTrackId: string | undefined;\n\nfunction createAudio(trackId: string, onForcePlay?: NoneToVoidFunction) {\n const audio = new Audio();\n\n function handleEvent(eventName: string) {\n return (e: Event) => {\n if (!tracks.has(trackId)) {\n return;\n }\n\n if (isSafariPatchInProgress(audio)) {\n return;\n }\n\n tracks.get(trackId)!.handlers.forEach((handler) => {\n handler(eventName, e);\n });\n };\n }\n\n audio.addEventListener('timeupdate', handleEvent('onTimeUpdate'));\n audio.addEventListener('play', handleEvent('onPlay'));\n audio.addEventListener('pause', handleEvent('onPause'));\n audio.addEventListener('loadstart', handleEvent('onLoadStart'));\n audio.addEventListener('loadeddata', handleEvent('onLoadedData'));\n audio.addEventListener('playing', handleEvent('onPlaying'));\n audio.addEventListener('ended', () => {\n if (isSafariPatchInProgress(audio)) {\n return;\n }\n\n const nextTrackId = queue[queue.indexOf(trackId) + 1];\n if (!nextTrackId) {\n return;\n }\n\n if (!tracks.has(nextTrackId)) {\n // A bit hacky way to continue playlist when switching chat\n getDispatch().openAudioPlayer(parseMessageKey(nextTrackId));\n\n return;\n }\n\n const nextTrack = tracks.get(nextTrackId)!;\n\n if (nextTrack.onForcePlay) {\n nextTrack.onForcePlay();\n }\n\n currentTrackId = nextTrackId;\n\n if (nextTrack.audio.src) {\n safePlay(nextTrack.audio);\n }\n });\n\n return {\n audio,\n proxy: new Proxy(audio, {\n get: (origin, key: keyof HTMLAudioElement) => origin[key],\n }),\n handlers: [],\n onForcePlay,\n };\n}\n\nexport function stopCurrentAudio() {\n const currentTrack = currentTrackId && tracks.get(currentTrackId);\n if (currentTrack) {\n currentTrack.audio.pause();\n }\n}\n\nexport function register(trackId: string, handler: Handler, onForcePlay?: NoneToVoidFunction) {\n if (!tracks.has(trackId)) {\n tracks.set(trackId, createAudio(trackId, onForcePlay));\n\n if (!queue.includes(trackId)) {\n queue.push(trackId);\n }\n }\n\n const { audio, proxy, handlers } = tracks.get(trackId)!;\n\n handlers.push(handler);\n\n return {\n play(src: string) {\n if (currentTrackId && currentTrackId !== trackId) {\n tracks.get(currentTrackId)!.audio.pause();\n }\n\n currentTrackId = trackId;\n\n if (!audio.src) {\n audio.src = src;\n audio.preload = 'auto';\n\n if (src.includes('/progressive/') && IS_SAFARI) {\n patchSafariProgressiveAudio(audio);\n }\n }\n\n safePlay(audio);\n },\n\n pause() {\n if (currentTrackId === trackId) {\n audio.pause();\n }\n },\n\n setCurrentTime(time: number) {\n if (currentTrackId === trackId) {\n audio.currentTime = time;\n }\n },\n\n proxy,\n\n destroy(shouldRemoveFromQueue = false) {\n const track = tracks.get(trackId);\n if (!track) {\n return;\n }\n\n track.handlers = track.handlers.filter((h) => h !== handler);\n\n if (!track.handlers.length) {\n track.audio.pause();\n tracks.delete(trackId);\n\n if (shouldRemoveFromQueue) {\n queue = queue.filter((id) => id !== trackId);\n }\n\n if (trackId === currentTrackId) {\n currentTrackId = undefined;\n }\n }\n },\n };\n}\n","export default function download(url: string, filename: string) {\n const link = document.createElement('a');\n link.href = url;\n link.download = filename;\n link.click();\n}\n","import { RefObject } from 'react';\nimport React, { FC, memo, useRef } from '../../lib/teact/teact';\n\nimport useShowTransition from '../../hooks/useShowTransition';\nimport useTransitionForMedia from '../../hooks/useTransitionForMedia';\nimport buildClassName from '../../util/buildClassName';\nimport { formatMediaDateTime, formatPastTimeShort } from '../../util/dateFormat';\nimport { getColorFromExtension, getFileSizeString } from './helpers/documentInfo';\nimport { getDocumentThumbnailDimensions } from './helpers/mediaDimensions';\nimport renderText from './helpers/renderText';\nimport useLang from '../../hooks/useLang';\n\nimport ProgressSpinner from '../ui/ProgressSpinner';\nimport Link from '../ui/Link';\n\nimport './File.scss';\n\ntype OwnProps = {\n ref?: RefObject<HTMLDivElement>;\n name: string;\n extension?: string;\n size: number;\n timestamp?: number;\n sender?: string;\n thumbnailDataUri?: string;\n previewData?: string;\n className?: string;\n smaller?: boolean;\n isTransferring?: boolean;\n isUploading?: boolean;\n isSelectable?: boolean;\n isSelected?: boolean;\n transferProgress?: number;\n onClick?: () => void;\n onDateClick?: (e: React.MouseEvent<HTMLAnchorElement>) => void;\n};\n\nconst File: FC<OwnProps> = ({\n ref,\n name,\n size,\n extension = '',\n timestamp,\n sender,\n thumbnailDataUri,\n previewData,\n className,\n smaller,\n isTransferring,\n isUploading,\n isSelectable,\n isSelected,\n transferProgress,\n onClick,\n onDateClick,\n}) => {\n const lang = useLang();\n // eslint-disable-next-line no-null/no-null\n let elementRef = useRef<HTMLDivElement>(null);\n if (ref) {\n elementRef = ref;\n }\n\n const {\n shouldRender: shouldSpinnerRender,\n transitionClassNames: spinnerClassNames,\n } = useShowTransition(isTransferring, undefined, true);\n const color = getColorFromExtension(extension);\n const sizeString = getFileSizeString(size);\n\n const {\n shouldRenderThumb, shouldRenderFullMedia, transitionClassNames,\n } = useTransitionForMedia(previewData, 'slow');\n const { width, height } = getDocumentThumbnailDimensions(smaller);\n\n const fullClassName = buildClassName(\n 'File',\n className,\n smaller && 'smaller',\n onClick && !isUploading && 'interactive',\n isSelected && 'file-is-selected',\n );\n\n return (\n <div ref={elementRef} className={fullClassName} dir={lang.isRtl ? 'rtl' : undefined}>\n {isSelectable && (\n <div className=\"message-select-control\">\n {isSelected && <i className=\"icon-select\" />}\n </div>\n )}\n <div className=\"file-icon-container\" onClick={isUploading ? undefined : onClick}>\n {thumbnailDataUri || previewData ? (\n <div className=\"file-preview media-inner\">\n {shouldRenderThumb && (\n <img\n src={thumbnailDataUri}\n width={width}\n height={height}\n className=\"thumbnail\"\n alt=\"\"\n />\n )}\n {shouldRenderFullMedia && (\n <img\n src={previewData}\n className={`full-media ${transitionClassNames}`}\n width={width}\n height={height}\n alt=\"\"\n />\n )}\n </div>\n ) : (\n <div className={`file-icon ${color}`}>\n {extension.length <= 4 && (\n <span className=\"file-ext\" dir=\"auto\">{extension}</span>\n )}\n </div>\n )}\n {shouldSpinnerRender && (\n <div className={buildClassName('file-progress', color, spinnerClassNames)}>\n <ProgressSpinner\n progress={transferProgress}\n size={smaller ? 's' : 'm'}\n onClick={isUploading ? onClick : undefined}\n />\n </div>\n )}\n {onClick && <i className={buildClassName('icon-download', shouldSpinnerRender && 'hidden')} />}\n </div>\n <div className=\"file-info\">\n <div className=\"file-title\" dir=\"auto\">{renderText(name)}</div>\n <div className=\"file-subtitle\" dir=\"auto\">\n <span>\n {isTransferring && transferProgress ? `${Math.round(transferProgress * 100)}%` : sizeString}\n </span>\n {sender && <span className=\"file-sender\">{renderText(sender)}</span>}\n {!sender && timestamp && (\n <>\n {' '}\n <Link onClick={onDateClick}>{formatMediaDateTime(lang, timestamp * 1000)}</Link>\n </>\n )}\n </div>\n </div>\n {sender && timestamp && (\n <Link onClick={onDateClick}>{formatPastTimeShort(lang, timestamp * 1000)}</Link>\n )}\n </div>\n );\n};\n\nexport default memo(File);\n","import React, {\n FC,\n memo,\n useCallback,\n useEffect,\n useRef,\n useState,\n} from '../../lib/teact/teact';\n\nimport { ANIMATION_END_DELAY } from '../../config';\nimport useShowTransition from '../../hooks/useShowTransition';\nimport { TextPart } from '../common/helpers/renderMessageText';\nimport buildClassName from '../../util/buildClassName';\nimport captureEscKeyListener from '../../util/captureEscKeyListener';\n\nimport Portal from './Portal';\n\nimport './Notification.scss';\n\ntype OwnProps = {\n containerId?: string;\n message: TextPart[];\n duration?: number;\n onDismiss: () => void;\n};\n\nconst DEFAULT_DURATION = 3000;\nconst ANIMATION_DURATION = 150;\n\nconst Notification: FC<OwnProps> = ({\n message, duration = DEFAULT_DURATION, containerId, onDismiss,\n}) => {\n const [isOpen, setIsOpen] = useState(true);\n // eslint-disable-next-line no-null/no-null\n const timerRef = useRef<number | undefined>(null);\n\n const { transitionClassNames } = useShowTransition(isOpen);\n\n const closeAndDismiss = useCallback(() => {\n setIsOpen(false);\n setTimeout(onDismiss, ANIMATION_DURATION + ANIMATION_END_DELAY);\n }, [onDismiss]);\n\n useEffect(() => (isOpen ? captureEscKeyListener(closeAndDismiss) : undefined), [isOpen, closeAndDismiss]);\n\n useEffect(() => {\n timerRef.current = window.setTimeout(closeAndDismiss, duration);\n\n return () => {\n if (timerRef.current) {\n clearTimeout(timerRef.current);\n timerRef.current = undefined;\n }\n };\n }, [duration, closeAndDismiss]);\n\n const handleMouseEnter = useCallback(() => {\n if (timerRef.current) {\n clearTimeout(timerRef.current);\n timerRef.current = undefined;\n }\n }, []);\n\n const handleMouseLeave = useCallback(() => {\n timerRef.current = window.setTimeout(closeAndDismiss, duration);\n }, [duration, closeAndDismiss]);\n\n return (\n <Portal className=\"Notification-container\" containerId={containerId}>\n <div\n className={buildClassName('Notification', transitionClassNames)}\n onClick={closeAndDismiss}\n onMouseEnter={handleMouseEnter}\n onMouseLeave={handleMouseLeave}\n >\n <div className=\"content\">\n {message}\n </div>\n </div>\n </Portal>\n );\n};\n\nexport default memo(Notification);\n","import { EDITABLE_INPUT_ID } from '../../../../config';\n\nconst MAX_NESTING_PARENTS = 5;\n\nexport function isSelectionInsideInput(selectionRange: Range) {\n const { commonAncestorContainer } = selectionRange;\n let parentNode: HTMLElement | null = commonAncestorContainer as HTMLElement;\n let iterations = 1;\n while (parentNode && parentNode.id !== EDITABLE_INPUT_ID && iterations < MAX_NESTING_PARENTS) {\n parentNode = parentNode.parentElement;\n iterations++;\n }\n\n return Boolean(parentNode && parentNode.id === EDITABLE_INPUT_ID);\n}\n","import {\n useCallback, useEffect, useMemo, useState,\n} from '../../../../lib/teact/teact';\n\nimport { EDITABLE_INPUT_ID } from '../../../../config';\nimport { IS_MOBILE_SCREEN } from '../../../../util/environment';\nimport {\n EmojiData, EmojiModule, EmojiRawData, uncompressEmoji,\n} from '../../../../util/emoji';\nimport useFlag from '../../../../hooks/useFlag';\nimport focusEditableElement from '../../../../util/focusEditableElement';\n\nlet emojiDataPromise: Promise<EmojiModule>;\nlet emojiRawData: EmojiRawData;\nlet emojiData: EmojiData;\n\nconst RE_NOT_EMOJI_SEARCH = /[^-_:\\p{L}\\p{N}]+/iu;\nconst EMOJIS_LIMIT = 36;\n\nexport default function useEmojiTooltip(\n isAllowed: boolean,\n html: string,\n recentEmojiIds: string[],\n inputId = EDITABLE_INPUT_ID,\n onUpdateHtml: (html: string) => void,\n) {\n const [isOpen, markIsOpen, unmarkIsOpen] = useFlag();\n const [emojiIds, setEmojiIds] = useState<string[]>([]);\n const [filteredEmojis, setFilteredEmojis] = useState<Emoji[]>([]);\n\n const recentEmojis = useMemo(\n () => {\n if (!emojiIds.length || !recentEmojiIds.length) {\n return [];\n }\n\n return recentEmojiIds\n .map((emojiId) => emojiData.emojis[emojiId])\n .filter<Emoji>(Boolean as any);\n },\n [emojiIds, recentEmojiIds],\n );\n\n // Initialize data on first render.\n useEffect(() => {\n const exec = () => {\n setEmojiIds(Object.keys(emojiData.emojis));\n };\n\n if (emojiData) {\n exec();\n } else {\n ensureEmojiData()\n .then(exec);\n }\n }, []);\n\n useEffect(() => {\n if (!isAllowed || !html || !emojiIds.length) {\n unmarkIsOpen();\n return;\n }\n\n const code = getEmojiCode(html);\n if (!code) {\n setFilteredEmojis([]);\n unmarkIsOpen();\n return;\n }\n\n const filter = code.substr(1);\n const matched = filter === ''\n ? recentEmojis\n : emojiIds\n .filter((emojiId) => emojiData.emojis[emojiId].names.find((name) => name.includes(filter)))\n .slice(0, EMOJIS_LIMIT)\n .map((emojiId) => emojiData.emojis[emojiId]);\n\n if (matched.length) {\n markIsOpen();\n setFilteredEmojis(matched);\n } else {\n unmarkIsOpen();\n }\n }, [emojiIds, html, isAllowed, markIsOpen, recentEmojis, unmarkIsOpen]);\n\n const insertEmoji = useCallback((textEmoji: string) => {\n const atIndex = html.lastIndexOf(':');\n if (atIndex !== -1) {\n onUpdateHtml(`${html.substr(0, atIndex)}${textEmoji}`);\n const messageInput = document.getElementById(inputId)!;\n if (!IS_MOBILE_SCREEN) {\n requestAnimationFrame(() => {\n focusEditableElement(messageInput, true);\n });\n }\n }\n\n unmarkIsOpen();\n }, [html, inputId, onUpdateHtml, unmarkIsOpen]);\n\n return {\n isEmojiTooltipOpen: isOpen,\n closeEmojiTooltip: unmarkIsOpen,\n filteredEmojis,\n insertEmoji,\n };\n}\n\nfunction getEmojiCode(html: string) {\n const tempEl = document.createElement('div');\n tempEl.innerHTML = html.replace('<br>', '\\n');\n const text = tempEl.innerText;\n\n const lastSymbol = text[text.length - 1];\n const lastWord = text.split(RE_NOT_EMOJI_SEARCH).pop();\n\n if (\n !text.length || RE_NOT_EMOJI_SEARCH.test(lastSymbol)\n || !lastWord || !lastWord.startsWith(':')\n ) {\n return undefined;\n }\n\n return lastWord.toLowerCase();\n}\n\nasync function ensureEmojiData() {\n if (!emojiDataPromise) {\n emojiDataPromise = import('emoji-data-ios/emoji-data.json') as unknown as Promise<EmojiModule>;\n emojiRawData = (await emojiDataPromise).default;\n\n emojiData = uncompressEmoji(emojiRawData);\n }\n\n return emojiDataPromise;\n}\n","import React, { FC, memo } from '../../../lib/teact/teact';\nimport { OwnProps } from './EmojiTooltip';\nimport { Bundles } from '../../../util/moduleLoader';\n\nimport useModuleLoader from '../../../hooks/useModuleLoader';\n\nconst EmojiTooltipAsync: FC<OwnProps> = (props) => {\n const { isOpen } = props;\n const EmojiTooltip = useModuleLoader(Bundles.Extra, 'EmojiTooltip', !isOpen);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return EmojiTooltip ? <EmojiTooltip {...props} /> : undefined;\n};\n\nexport default memo(EmojiTooltipAsync);\n","import { ChangeEvent } from 'react';\nimport React, {\n FC, useEffect, useRef, memo, useState, useCallback,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../../global/types';\nimport { IAnchorPosition, ISettings } from '../../../types';\n\nimport { EDITABLE_INPUT_ID } from '../../../config';\nimport { selectCurrentMessageList, selectReplyingToId } from '../../../modules/selectors';\nimport { debounce } from '../../../util/schedulers';\nimport focusEditableElement from '../../../util/focusEditableElement';\nimport buildClassName from '../../../util/buildClassName';\nimport { pick } from '../../../util/iteratees';\nimport {\n IS_ANDROID, IS_IOS, IS_MOBILE_SCREEN, IS_TOUCH_ENV,\n} from '../../../util/environment';\nimport captureKeyboardListeners from '../../../util/captureKeyboardListeners';\nimport useLayoutEffectWithPrevDeps from '../../../hooks/useLayoutEffectWithPrevDeps';\nimport useFlag from '../../../hooks/useFlag';\nimport parseEmojiOnlyString from '../../common/helpers/parseEmojiOnlyString';\nimport { isSelectionInsideInput } from './helpers/selection';\nimport useLang from '../../../hooks/useLang';\n\nimport TextFormatter from './TextFormatter';\n\nconst CONTEXT_MENU_CLOSE_DELAY_MS = 100;\n// Focus slows down animation, also it breaks transition layout in Chrome\nconst FOCUS_DELAY_MS = 350;\nconst TRANSITION_DURATION_FACTOR = 50;\n\ntype OwnProps = {\n id: string;\n editableInputId?: string;\n html: string;\n placeholder: string;\n shouldSetFocus: boolean;\n shouldSupressFocus?: boolean;\n shouldSupressTextFormatter?: boolean;\n onUpdate: (html: string) => void;\n onSupressedFocus?: () => void;\n onSend: () => void;\n};\n\ntype StateProps = {\n currentChatId?: number;\n replyingToId?: number;\n noTabCapture?: boolean;\n messageSendKeyCombo?: ISettings['messageSendKeyCombo'];\n};\n\ntype DispatchProps = Pick<GlobalActions, 'editLastMessage' | 'replyToNextMessage'>;\n\nconst MAX_INPUT_HEIGHT = IS_MOBILE_SCREEN ? 256 : 416;\nconst TAB_INDEX_PRIORITY_TIMEOUT = 2000;\nconst TEXT_FORMATTER_SAFE_AREA_PX = 90;\n// For some reason Safari inserts `<br>` after user removes text from input\nconst SAFARI_BR = '<br>';\n\nfunction clearSelection() {\n const selection = window.getSelection();\n if (!selection) {\n return;\n }\n\n if (selection.removeAllRanges) {\n selection.removeAllRanges();\n } else if (selection.empty) {\n selection.empty();\n }\n}\n\nconst MessageInput: FC<OwnProps & StateProps & DispatchProps> = ({\n id,\n editableInputId,\n html,\n placeholder,\n shouldSetFocus,\n shouldSupressFocus,\n shouldSupressTextFormatter,\n onUpdate,\n onSupressedFocus,\n onSend,\n currentChatId,\n replyingToId,\n noTabCapture,\n messageSendKeyCombo,\n editLastMessage,\n replyToNextMessage,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const inputRef = useRef<HTMLDivElement>(null);\n // eslint-disable-next-line no-null/no-null\n const cloneRef = useRef<HTMLDivElement>(null);\n\n const lang = useLang();\n const isContextMenuOpenRef = useRef(false);\n const [isTextFormatterOpen, openTextFormatter, closeTextFormatter] = useFlag();\n const [textFormatterAnchorPosition, setTextFormatterAnchorPosition] = useState<IAnchorPosition>();\n const [selectedRange, setSelectedRange] = useState<Range>();\n\n useEffect(() => {\n updateInputHeight(false);\n }, []);\n\n useLayoutEffectWithPrevDeps(([prevHtml]) => {\n if (html !== inputRef.current!.innerHTML) {\n inputRef.current!.innerHTML = html;\n }\n\n if (html !== cloneRef.current!.innerHTML) {\n cloneRef.current!.innerHTML = html;\n }\n\n if (prevHtml !== undefined && prevHtml !== html) {\n updateInputHeight(!html.length);\n }\n }, [html]);\n\n const focusInput = useCallback(() => {\n // Avoid focusing during animation\n if (inputRef.current!.closest('.from, .to')) {\n setTimeout(focusInput, FOCUS_DELAY_MS);\n return;\n }\n\n focusEditableElement(inputRef.current!);\n }, []);\n\n const handleCloseTextFormatter = useCallback(() => {\n closeTextFormatter();\n clearSelection();\n }, [closeTextFormatter]);\n\n function checkSelection() {\n // Disable the formatter on iOS devices for now.\n if (IS_IOS) {\n return;\n }\n\n const selection = window.getSelection();\n if (!selection || !selection.rangeCount || isContextMenuOpenRef.current) {\n closeTextFormatter();\n return;\n }\n\n const selectionRange = selection.getRangeAt(0);\n const selectedText = selectionRange.toString().trim();\n if (\n shouldSupressTextFormatter\n || !isSelectionInsideInput(selectionRange)\n || !selectedText\n || parseEmojiOnlyString(selectedText)\n || !selectionRange.START_TO_END\n ) {\n closeTextFormatter();\n return;\n }\n\n const selectionRect = selectionRange.getBoundingClientRect();\n const inputRect = inputRef.current!.getBoundingClientRect();\n\n let x = (selectionRect.left + selectionRect.width / 2) - inputRect.left;\n\n if (x < TEXT_FORMATTER_SAFE_AREA_PX) {\n x = TEXT_FORMATTER_SAFE_AREA_PX;\n } else if (x > inputRect.width - TEXT_FORMATTER_SAFE_AREA_PX) {\n x = inputRect.width - TEXT_FORMATTER_SAFE_AREA_PX;\n }\n\n setTextFormatterAnchorPosition({\n x,\n y: selectionRect.top - inputRect.top,\n });\n\n setSelectedRange(selectionRange);\n openTextFormatter();\n }\n\n function handleMouseDown(event: React.MouseEvent<HTMLDivElement, MouseEvent>) {\n function handleMouseUp() {\n checkSelection();\n\n event.target.removeEventListener('mouseup', handleMouseUp);\n }\n\n if (event.button !== 2) {\n event.target.addEventListener('mouseup', handleMouseUp);\n return;\n }\n\n if (isContextMenuOpenRef.current === true) {\n return;\n }\n\n isContextMenuOpenRef.current = true;\n\n function closeContextMenuMouseListener() {\n setTimeout(() => {\n isContextMenuOpenRef.current = false;\n }, CONTEXT_MENU_CLOSE_DELAY_MS);\n\n window.removeEventListener('mouseup', closeContextMenuMouseListener);\n }\n\n function closeContextMenuKeyListener(e: KeyboardEvent) {\n if (e.key !== 'Esc' && e.key !== 'Escape') {\n return;\n }\n\n setTimeout(() => {\n isContextMenuOpenRef.current = false;\n }, CONTEXT_MENU_CLOSE_DELAY_MS);\n\n window.removeEventListener('keydown', closeContextMenuKeyListener);\n }\n\n document.addEventListener('mousedown', closeContextMenuMouseListener);\n document.addEventListener('keydown', closeContextMenuKeyListener);\n }\n\n function handleKeyDown(e: React.KeyboardEvent<HTMLDivElement>) {\n function handleKeyUp() {\n checkSelection();\n\n e.target.removeEventListener('keyup', handleKeyUp);\n }\n\n if (e.metaKey) {\n const targetIndexDelta = e.key === 'ArrowDown' ? 1 : e.key === 'ArrowUp' ? -1 : undefined;\n if (targetIndexDelta) {\n e.preventDefault();\n\n replyToNextMessage({ targetIndexDelta });\n return;\n }\n }\n\n if (e.key === 'Enter' && !e.shiftKey) {\n if (\n !(IS_IOS || IS_ANDROID)\n && (\n (messageSendKeyCombo === 'enter' && !e.shiftKey)\n || (messageSendKeyCombo === 'ctrl-enter' && (e.ctrlKey || e.metaKey))\n )\n ) {\n e.preventDefault();\n\n closeTextFormatter();\n onSend();\n }\n } else if (e.key === 'ArrowUp' && !html.length && !e.metaKey) {\n e.preventDefault();\n editLastMessage();\n } else {\n e.target.addEventListener('keyup', handleKeyUp);\n }\n }\n\n function handleTouchSelection() {\n if (!IS_ANDROID) {\n return;\n }\n\n checkSelection();\n }\n\n function handleChange(e: ChangeEvent<HTMLDivElement>) {\n const { innerHTML, textContent } = e.currentTarget;\n\n onUpdate(innerHTML === SAFARI_BR ? '' : innerHTML);\n\n // Reset focus on the input to remove any active styling when input is cleared\n if (!IS_TOUCH_ENV && (!textContent || !textContent.length)) {\n const selection = window.getSelection()!;\n if (selection) {\n inputRef.current!.blur();\n selection.removeAllRanges();\n focusEditableElement(inputRef.current!, true);\n }\n }\n }\n\n function stopEvent(e: React.MouseEvent<HTMLDivElement, MouseEvent>) {\n if (!IS_ANDROID) {\n return;\n }\n\n e.preventDefault();\n e.stopPropagation();\n }\n\n function updateInputHeight(willSend = false) {\n const input = inputRef.current!;\n const clone = cloneRef.current!;\n const currentHeight = Number(input.style.height.replace('px', ''));\n const newHeight = Math.min(clone.scrollHeight, MAX_INPUT_HEIGHT);\n if (newHeight === currentHeight) {\n return;\n }\n\n const transitionDuration = Math.round(\n TRANSITION_DURATION_FACTOR * Math.log(Math.abs(newHeight - currentHeight)),\n );\n\n const exec = () => {\n input.style.height = `${newHeight}px`;\n input.style.transitionDuration = `${transitionDuration}ms`;\n input.classList.toggle('overflown', clone.scrollHeight > MAX_INPUT_HEIGHT);\n };\n\n if (willSend) {\n // Sync with sending animation\n requestAnimationFrame(exec);\n } else {\n exec();\n }\n }\n\n useEffect(() => {\n if (IS_TOUCH_ENV) {\n return;\n }\n\n focusInput();\n }, [currentChatId, focusInput, replyingToId, shouldSetFocus]);\n\n useEffect(() => {\n if (noTabCapture) {\n return undefined;\n }\n\n const captureFirstTab = debounce((e: KeyboardEvent) => {\n if (e.key === 'Tab') {\n e.preventDefault();\n requestAnimationFrame(focusInput);\n }\n }, TAB_INDEX_PRIORITY_TIMEOUT, true, false);\n\n return captureKeyboardListeners({ onTab: captureFirstTab });\n }, [focusInput, noTabCapture]);\n\n useEffect(() => {\n const input = inputRef.current!;\n\n function supressFocus() {\n input.blur();\n }\n\n if (shouldSupressFocus) {\n input.addEventListener('focus', supressFocus);\n }\n\n return () => {\n input.removeEventListener('focus', supressFocus);\n };\n }, [shouldSupressFocus]);\n\n const className = buildClassName(\n 'form-control custom-scroll',\n html.length > 0 && 'touched',\n shouldSupressFocus && 'focus-disabled',\n );\n\n return (\n <div id={id} onClick={shouldSupressFocus ? onSupressedFocus : undefined} dir={lang.isRtl ? 'rtl' : undefined}>\n <div\n ref={inputRef}\n id={editableInputId || EDITABLE_INPUT_ID}\n className={className}\n contentEditable\n dir=\"auto\"\n onClick={focusInput}\n onChange={handleChange}\n onKeyDown={handleKeyDown}\n onMouseDown={handleMouseDown}\n onContextMenu={stopEvent}\n onTouchCancel={handleTouchSelection}\n />\n <div ref={cloneRef} className={buildClassName(className, 'clone')} dir=\"auto\" />\n <span className=\"placeholder-text\" dir=\"auto\">{placeholder}</span>\n <TextFormatter\n isOpen={isTextFormatterOpen}\n anchorPosition={textFormatterAnchorPosition}\n selectedRange={selectedRange}\n onClose={handleCloseTextFormatter}\n />\n </div>\n );\n};\n\nexport default memo(withGlobal<OwnProps>(\n (global): StateProps => {\n const { chatId: currentChatId, threadId } = selectCurrentMessageList(global) || {};\n const { messageSendKeyCombo } = global.settings.byKey;\n\n return {\n currentChatId,\n messageSendKeyCombo,\n replyingToId: currentChatId && threadId ? selectReplyingToId(global, currentChatId, threadId) : undefined,\n noTabCapture: global.isPollModalOpen || global.payment.isPaymentModalOpen,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, ['editLastMessage', 'replyToNextMessage']),\n)(MessageInput));\n","import React, { FC, memo, useCallback } from '../../lib/teact/teact';\n\nimport { ApiMessage, ApiWebPage } from '../../api/types';\n\nimport { getFirstLinkInMessage, getMessageSummaryText, getMessageWebPage } from '../../modules/helpers';\nimport buildClassName from '../../util/buildClassName';\nimport trimText from '../../util/trimText';\nimport renderText from './helpers/renderText';\nimport { formatPastTimeShort } from '../../util/dateFormat';\nimport useLang from '../../hooks/useLang';\n\nimport Media from './Media';\nimport Link from '../ui/Link';\nimport SafeLink from './SafeLink';\n\nimport './WebLink.scss';\n\nconst MAX_TEXT_LENGTH = 170; // symbols\n\ntype OwnProps = {\n message: ApiMessage;\n senderTitle?: string;\n onMessageClick: (messageId: number, chatId: number) => void;\n};\n\nconst WebLink: FC<OwnProps> = ({ message, senderTitle, onMessageClick }) => {\n const lang = useLang();\n\n let linkData: ApiWebPage | undefined = getMessageWebPage(message);\n\n if (!linkData) {\n const link = getFirstLinkInMessage(message);\n if (link) {\n const { url, domain } = link;\n const messageText = getMessageSummaryText(lang, message);\n\n linkData = {\n siteName: domain.replace(/^www./, ''),\n url: url.includes('://') ? url : url.includes('@') ? `mailto:${url}` : `http://${url}`,\n description: messageText !== url ? messageText : undefined,\n } as ApiWebPage;\n }\n }\n\n const handleMessageClick = useCallback(() => {\n onMessageClick(message.id, message.chatId);\n }, [onMessageClick, message.id, message.chatId]);\n\n if (!linkData) {\n return undefined;\n }\n\n const {\n siteName,\n url,\n displayUrl,\n title,\n description,\n photo,\n } = linkData;\n\n const truncatedDescription = !senderTitle && trimText(description, MAX_TEXT_LENGTH);\n\n const className = buildClassName(\n 'WebLink scroll-item',\n !photo && 'without-photo',\n );\n\n return (\n <div\n className={className}\n data-initial={(siteName || displayUrl)[0]}\n dir={lang.isRtl ? 'rtl' : undefined}\n >\n {photo && (\n <Media message={message} />\n )}\n <div className=\"content\">\n <Link isRtl={lang.isRtl} className=\"site-title\" onClick={handleMessageClick}>\n {renderText(title || siteName || displayUrl)}\n </Link>\n {truncatedDescription && (\n <Link isRtl={lang.isRtl} className=\"site-description\" onClick={handleMessageClick}>\n {renderText(truncatedDescription)}\n </Link>\n )}\n <SafeLink\n url={url}\n className=\"site-name\"\n text=\"\"\n isRtl={lang.isRtl}\n >\n {url.replace('mailto:', '') || displayUrl}\n </SafeLink>\n {senderTitle && <div className=\"sender-name\">{renderText(senderTitle)}</div>}\n </div>\n {senderTitle && (\n <div className=\"message-date\">\n <Link\n className=\"date\"\n onClick={handleMessageClick}\n isRtl={lang.isRtl}\n >\n {formatPastTimeShort(lang, message.date * 1000)}\n </Link>\n </div>\n )}\n </div>\n );\n};\n\nexport default memo(WebLink);\n","import { useCallback } from '../../../../lib/teact/teact';\n\nexport enum ChatAnimationTypes {\n Move,\n Opacity,\n None,\n}\n\nexport function useChatAnimationType(orderDiffById: Record<number, number>) {\n const movesUp = useCallback((id: number) => orderDiffById[id] < 0, [orderDiffById]);\n const movesDown = useCallback((id: number) => orderDiffById[id] > 0, [orderDiffById]);\n\n const orderDiffIds = Object.keys(orderDiffById).map(Number);\n const numberOfUp = orderDiffIds.filter(movesUp).length;\n const numberOfDown = orderDiffIds.filter(movesDown).length;\n\n return useCallback((chatId: number): ChatAnimationTypes => {\n const orderDiff = orderDiffById[chatId];\n\n if (orderDiff === 0) {\n return ChatAnimationTypes.None;\n }\n\n if (\n orderDiff === Infinity\n || orderDiff === -Infinity\n || (movesUp(chatId) && numberOfUp <= numberOfDown)\n || (movesDown(chatId) && numberOfDown < numberOfUp)\n ) {\n return ChatAnimationTypes.Opacity;\n }\n\n return ChatAnimationTypes.Move;\n }, [movesDown, movesUp, numberOfDown, numberOfUp, orderDiffById]);\n}\n","import React, { FC, memo } from '../../../lib/teact/teact';\n\nimport { ApiChat } from '../../../api/types';\n\nimport { formatIntegerCompact } from '../../../util/textFormat';\nimport buildClassName from '../../../util/buildClassName';\n\nimport ShowTransition from '../../ui/ShowTransition';\n\nimport './Badge.scss';\n\ntype OwnProps = {\n chat: ApiChat;\n isPinned?: boolean;\n isMuted?: boolean;\n};\n\nconst Badge: FC<OwnProps> = ({ chat, isPinned, isMuted }) => {\n const isShown = Boolean(chat.unreadCount || chat.hasUnreadMark || isPinned);\n const className = buildClassName(\n 'Badge',\n isMuted && 'muted',\n isPinned && 'pinned',\n Boolean(chat.unreadCount || chat.hasUnreadMark) && 'unread',\n );\n\n function renderContent() {\n if (chat.unreadCount) {\n if (chat.unreadMentionsCount) {\n return (\n <div className=\"Badge-wrapper\">\n <div className=\"Badge mention\">\n <i className=\"icon-mention\" />\n </div>\n <div className={className}>\n {formatIntegerCompact(chat.unreadCount)}\n </div>\n </div>\n );\n }\n\n return (\n <div className={className}>\n {formatIntegerCompact(chat.unreadCount)}\n </div>\n );\n } else if (chat.hasUnreadMark) {\n return (\n <div className={className} />\n );\n } else if (isPinned) {\n return (\n <div className={className}>\n <i className=\"icon-pinned-chat\" />\n </div>\n );\n }\n\n return undefined;\n }\n\n return (\n <ShowTransition isCustom className=\"Badge-transition\" isOpen={isShown}>\n {renderContent}\n </ShowTransition>\n );\n};\n\nexport default memo(Badge);\n","import React, {\n FC, memo, useCallback, useLayoutEffect, useRef,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport useLang, { LangFn } from '../../../hooks/useLang';\n\nimport { GlobalActions, MessageListType } from '../../../global/types';\nimport {\n ApiChat, ApiUser, ApiMessage, ApiMessageOutgoingStatus, ApiFormattedText, MAIN_THREAD_ID,\n} from '../../../api/types';\n\nimport { ANIMATION_END_DELAY } from '../../../config';\nimport { IS_MOBILE_SCREEN } from '../../../util/environment';\nimport {\n getChatTitle,\n isChatPrivate,\n isActionMessage,\n getPrivateChatUserId,\n getMessageAction,\n getMessageSenderName,\n isChatChannel,\n getMessageMediaHash,\n getMessageSummaryText,\n getMessageMediaThumbDataUri,\n getMessageVideo,\n getMessageSticker,\n selectIsChatMuted,\n getMessageRoundVideo,\n} from '../../../modules/helpers';\nimport {\n selectChat, selectUser, selectChatMessage, selectOutgoingStatus, selectDraft, selectCurrentMessageList,\n selectNotifySettings, selectNotifyExceptions,\n} from '../../../modules/selectors';\nimport { renderActionMessageText } from '../../common/helpers/renderActionMessageText';\nimport renderText from '../../common/helpers/renderText';\nimport { fastRaf } from '../../../util/schedulers';\nimport buildClassName from '../../../util/buildClassName';\nimport { pick } from '../../../util/iteratees';\nimport useEnsureMessage from '../../../hooks/useEnsureMessage';\nimport useChatContextActions from '../../../hooks/useChatContextActions';\nimport useFlag from '../../../hooks/useFlag';\nimport useMedia from '../../../hooks/useMedia';\nimport { ChatAnimationTypes } from './hooks';\n\nimport Avatar from '../../common/Avatar';\nimport VerifiedIcon from '../../common/VerifiedIcon';\nimport TypingStatus from '../../common/TypingStatus';\nimport LastMessageMeta from '../../common/LastMessageMeta';\nimport DeleteChatModal from '../../common/DeleteChatModal';\nimport ListItem from '../../ui/ListItem';\nimport Badge from './Badge';\n\nimport './Chat.scss';\n\ntype OwnProps = {\n style?: string;\n chatId: number;\n folderId?: number;\n orderDiff: number;\n animationType: ChatAnimationTypes;\n isSelected: boolean;\n isPinned?: boolean;\n};\n\ntype StateProps = {\n chat?: ApiChat;\n isMuted?: boolean;\n privateChatUser?: ApiUser;\n actionTargetUser?: ApiUser;\n actionTargetMessage?: ApiMessage;\n actionTargetChatId?: number;\n lastMessageSender?: ApiUser;\n lastMessageOutgoingStatus?: ApiMessageOutgoingStatus;\n draft?: ApiFormattedText;\n messageListType?: MessageListType;\n animationLevel?: number;\n lastSyncTime?: number;\n};\n\ntype DispatchProps = Pick<GlobalActions, 'openChat' | 'focusLastMessage'>;\n\nconst ANIMATION_DURATION = 200;\n\nconst Chat: FC<OwnProps & StateProps & DispatchProps> = ({\n style,\n chatId,\n folderId,\n orderDiff,\n animationType,\n isSelected,\n isPinned,\n chat,\n isMuted,\n privateChatUser,\n actionTargetUser,\n lastMessageSender,\n lastMessageOutgoingStatus,\n actionTargetMessage,\n actionTargetChatId,\n draft,\n messageListType,\n animationLevel,\n lastSyncTime,\n openChat,\n focusLastMessage,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const ref = useRef<HTMLDivElement>(null);\n\n const [isDeleteModalOpen, openDeleteModal, closeDeleteModal] = useFlag();\n\n const { lastMessage, typingStatus } = chat || {};\n const isAction = lastMessage && isActionMessage(lastMessage);\n\n useEnsureMessage(chatId, isAction ? lastMessage!.replyToMessageId : undefined, actionTargetMessage);\n\n const mediaThumbnail = lastMessage && !getMessageSticker(lastMessage)\n ? getMessageMediaThumbDataUri(lastMessage)\n : undefined;\n const mediaBlobUrl = useMedia(lastMessage ? getMessageMediaHash(lastMessage, 'micro') : undefined);\n const isRoundVideo = Boolean(lastMessage && getMessageRoundVideo(lastMessage));\n\n // Sets animation excess values when `orderDiff` changes and then resets excess values to animate.\n useLayoutEffect(() => {\n if (animationLevel === 0) {\n return;\n }\n\n const element = ref.current!;\n\n // TODO Refactor animation: create `useListAnimation` that owns `orderDiff` and `animationType`\n if (animationType === ChatAnimationTypes.Opacity) {\n element.style.opacity = '0';\n\n fastRaf(() => {\n element.classList.add('animate-opacity');\n element.style.opacity = '1';\n });\n } else if (animationType === ChatAnimationTypes.Move) {\n element.style.transform = `translate3d(0, ${-orderDiff * 100}%, 0)`;\n\n fastRaf(() => {\n element.classList.add('animate-transform');\n element.style.transform = '';\n });\n } else {\n return;\n }\n\n setTimeout(() => {\n fastRaf(() => {\n element.classList.remove('animate-opacity', 'animate-transform');\n element.style.opacity = '';\n element.style.transform = '';\n });\n }, ANIMATION_DURATION + ANIMATION_END_DELAY);\n }, [animationLevel, orderDiff, animationType]);\n\n const handleClick = useCallback(() => {\n openChat({ id: chatId });\n\n if (isSelected && messageListType === 'thread') {\n focusLastMessage();\n }\n }, [\n isSelected,\n messageListType,\n openChat,\n chatId,\n focusLastMessage,\n ]);\n\n const contextActions = useChatContextActions({\n chat,\n privateChatUser,\n handleDelete: openDeleteModal,\n folderId,\n isPinned,\n });\n\n const lang = useLang();\n\n if (!chat) {\n return undefined;\n }\n\n function renderLastMessageOrTyping() {\n if (typingStatus && lastMessage && typingStatus.timestamp > lastMessage.date * 1000) {\n return <TypingStatus typingStatus={typingStatus} />;\n }\n\n if (draft && draft.text.length) {\n return (\n <p className=\"last-message\" dir=\"auto\">\n <span className=\"draft\">{lang('Draft')}</span>\n {renderText(draft.text)}\n </p>\n );\n }\n\n if (!lastMessage) {\n return undefined;\n }\n\n if (isAction) {\n const actionOrigin = chat && (isChatChannel(chat) || lastMessage.senderId === lastMessage.chatId)\n ? chat\n : lastMessageSender;\n\n return (\n <p className=\"last-message\" dir=\"auto\">\n {renderText(renderActionMessageText(\n lang,\n lastMessage,\n actionOrigin,\n actionTargetUser,\n actionTargetMessage,\n actionTargetChatId,\n { asPlain: true },\n ) as string)}\n </p>\n );\n }\n\n const senderName = getMessageSenderName(lang, chatId, lastMessageSender);\n\n return (\n <p className=\"last-message\" dir=\"auto\">\n {senderName && (\n <>\n <span className=\"sender-name\">{renderText(senderName)}</span>\n <span className=\"colon\">:</span>\n </>\n )}\n {renderMessageSummary(lang, lastMessage!, mediaBlobUrl || mediaThumbnail, isRoundVideo)}\n </p>\n );\n }\n\n const className = buildClassName(\n 'Chat chat-item-clickable',\n isChatPrivate(chatId) ? 'private' : 'group',\n isSelected && !IS_MOBILE_SCREEN && 'selected',\n );\n\n return (\n <ListItem\n ref={ref}\n className={className}\n style={style}\n ripple={!IS_MOBILE_SCREEN}\n contextActions={contextActions}\n onClick={handleClick}\n >\n <div className=\"status\">\n <Avatar\n chat={chat}\n user={privateChatUser}\n withOnlineStatus\n isSavedMessages={privateChatUser && privateChatUser.isSelf}\n lastSyncTime={lastSyncTime}\n />\n </div>\n <div className=\"info\">\n <div className=\"title\">\n <h3>{renderText(getChatTitle(lang, chat, privateChatUser))}</h3>\n {chat.isVerified && <VerifiedIcon />}\n {isMuted && <i className=\"icon-muted-chat\" />}\n {chat.lastMessage && (\n <LastMessageMeta message={chat.lastMessage} outgoingStatus={lastMessageOutgoingStatus} />\n )}\n </div>\n <div className=\"subtitle\">\n {renderLastMessageOrTyping()}\n <Badge chat={chat} isPinned={isPinned} isMuted={isMuted} />\n </div>\n </div>\n <DeleteChatModal\n isOpen={isDeleteModalOpen}\n onClose={closeDeleteModal}\n chat={chat}\n />\n </ListItem>\n );\n};\n\nfunction renderMessageSummary(lang: LangFn, message: ApiMessage, blobUrl?: string, isRoundVideo?: boolean) {\n if (!blobUrl) {\n return renderText(getMessageSummaryText(lang, message));\n }\n\n return (\n <span className=\"media-preview\">\n <img src={blobUrl} alt=\"\" className={isRoundVideo ? 'round' : undefined} />\n {getMessageVideo(message) && <i className=\"icon-play\" />}\n {renderText(getMessageSummaryText(lang, message, true))}\n </span>\n );\n}\n\nexport default memo(withGlobal<OwnProps>(\n (global, { chatId }): StateProps => {\n const chat = selectChat(global, chatId);\n if (!chat || !chat.lastMessage) {\n return {};\n }\n\n const { senderId, replyToMessageId, isOutgoing } = chat.lastMessage;\n const lastMessageSender = senderId ? selectUser(global, senderId) : undefined;\n const lastMessageAction = getMessageAction(chat.lastMessage);\n const actionTargetMessage = lastMessageAction && replyToMessageId\n ? selectChatMessage(global, chat.id, replyToMessageId)\n : undefined;\n const { targetUserId: actionTargetUserId, targetChatId: actionTargetChatId } = lastMessageAction || {};\n const privateChatUserId = getPrivateChatUserId(chat);\n const { type: messageListType } = selectCurrentMessageList(global) || {};\n\n return {\n chat,\n isMuted: selectIsChatMuted(chat, selectNotifySettings(global), selectNotifyExceptions(global)),\n lastMessageSender,\n ...(isOutgoing && { lastMessageOutgoingStatus: selectOutgoingStatus(global, chat.lastMessage) }),\n ...(privateChatUserId && { privateChatUser: selectUser(global, privateChatUserId) }),\n ...(actionTargetUserId && { actionTargetUser: selectUser(global, actionTargetUserId) }),\n actionTargetChatId,\n actionTargetMessage,\n draft: selectDraft(global, chatId, MAIN_THREAD_ID),\n messageListType,\n animationLevel: global.settings.byKey.animationLevel,\n lastSyncTime: global.lastSyncTime,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'openChat',\n 'focusLastMessage',\n ]),\n)(Chat));\n","import React, {\n FC, memo, useMemo, useCallback, useEffect,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../../global/types';\nimport {\n ApiChat, ApiChatFolder, ApiUser, MAIN_THREAD_ID,\n} from '../../../api/types';\nimport { NotifyException, NotifySettings } from '../../../types';\n\nimport { ALL_CHATS_PRELOAD_DISABLED, CHAT_HEIGHT_PX, CHAT_LIST_SLICE } from '../../../config';\nimport { IS_ANDROID } from '../../../util/environment';\nimport usePrevious from '../../../hooks/usePrevious';\nimport { mapValues, pick } from '../../../util/iteratees';\nimport { getChatOrder, prepareChatList, prepareFolderListIds } from '../../../modules/helpers';\nimport {\n selectChatFolder, selectCurrentMessageList, selectNotifyExceptions, selectNotifySettings,\n} from '../../../modules/selectors';\nimport useInfiniteScroll from '../../../hooks/useInfiniteScroll';\nimport { useChatAnimationType } from './hooks';\n\nimport InfiniteScroll from '../../ui/InfiniteScroll';\nimport Loading from '../../ui/Loading';\nimport Chat from './Chat';\n\ntype OwnProps = {\n folderType: 'all' | 'archived' | 'folder';\n folderId?: number;\n noChatsText?: string;\n isActive: boolean;\n};\n\ntype StateProps = {\n chatsById: Record<number, ApiChat>;\n usersById: Record<number, ApiUser>;\n chatFolder?: ApiChatFolder;\n listIds?: number[];\n currentChatId?: number;\n orderedPinnedIds?: number[];\n lastSyncTime?: number;\n isInDiscussionThread?: boolean;\n notifySettings: NotifySettings;\n notifyExceptions?: Record<number, NotifyException>;\n};\n\ntype DispatchProps = Pick<GlobalActions, 'loadMoreChats' | 'preloadTopChatMessages' | 'openChat'>;\n\nenum FolderTypeToListType {\n 'all' = 'active',\n 'archived' = 'archived'\n}\n\nconst ChatList: FC<OwnProps & StateProps & DispatchProps> = ({\n folderType,\n folderId,\n noChatsText = 'Chat list is empty.',\n isActive,\n chatFolder,\n chatsById,\n usersById,\n listIds,\n currentChatId,\n orderedPinnedIds,\n lastSyncTime,\n isInDiscussionThread,\n notifySettings,\n notifyExceptions,\n loadMoreChats,\n preloadTopChatMessages,\n openChat,\n}) => {\n const [currentListIds, currentPinnedIds] = useMemo(() => {\n return folderType === 'folder' && chatFolder\n ? prepareFolderListIds(chatsById, usersById, chatFolder, notifySettings, notifyExceptions)\n : [listIds, orderedPinnedIds];\n }, [folderType, chatFolder, chatsById, usersById, notifySettings, notifyExceptions, listIds, orderedPinnedIds]);\n\n const [orderById, orderedIds] = useMemo(() => {\n if (!currentListIds || (folderType === 'folder' && !chatFolder)) {\n return [];\n }\n const newChatArrays = prepareChatList(chatsById, currentListIds, currentPinnedIds, folderType);\n const singleList = [...newChatArrays.pinnedChats, ...newChatArrays.otherChats];\n const newOrderedIds = singleList.map(({ id }) => id);\n const newOrderById = singleList.reduce((acc, chat, i) => {\n acc[chat.id] = i;\n return acc;\n }, {} as Record<string, number>);\n\n return [newOrderById, newOrderedIds];\n }, [currentListIds, currentPinnedIds, folderType, chatFolder, chatsById]);\n\n const prevOrderById = usePrevious(orderById);\n\n const orderDiffById = orderById && prevOrderById\n ? mapValues(orderById, (order, id) => {\n return order - (prevOrderById[id] !== undefined ? prevOrderById[id] : Infinity);\n })\n : {};\n\n const loadMoreOfType = useCallback(() => {\n loadMoreChats({ listType: folderType === 'archived' ? 'archived' : 'active' });\n }, [loadMoreChats, folderType]);\n\n const [viewportIds, getMore] = useInfiniteScroll(\n lastSyncTime ? loadMoreOfType : undefined,\n orderedIds,\n undefined,\n CHAT_LIST_SLICE,\n folderType === 'all' && !ALL_CHATS_PRELOAD_DISABLED,\n );\n\n // TODO Refactor to not call `prepareChatList` twice\n const chatArrays = viewportIds && prepareChatList(chatsById, viewportIds, currentPinnedIds, folderType);\n\n useEffect(() => {\n if (lastSyncTime && folderType === 'all') {\n preloadTopChatMessages();\n }\n }, [lastSyncTime, folderType, preloadTopChatMessages]);\n\n const getAnimationType = useChatAnimationType(orderDiffById);\n\n function renderChats() {\n const viewportOffset = orderedIds!.indexOf(viewportIds![0]);\n const pinnedOffset = viewportOffset + chatArrays!.pinnedChats.length;\n\n return (\n <div\n className=\"scroll-container\"\n // @ts-ignore\n style={IS_ANDROID ? `height: ${orderedIds!.length * CHAT_HEIGHT_PX}px` : undefined}\n teactFastList\n >\n {chatArrays!.pinnedChats.map(({ id }, i) => (\n <Chat\n key={id}\n teactOrderKey={i}\n chatId={id}\n isPinned\n folderId={folderId}\n isSelected={id === currentChatId && !isInDiscussionThread}\n animationType={getAnimationType(id)}\n orderDiff={orderDiffById[id]}\n // @ts-ignore\n style={`top: ${(viewportOffset + i) * CHAT_HEIGHT_PX}px;`}\n />\n ))}\n {chatArrays!.otherChats.map((chat, i) => (\n <Chat\n key={chat.id}\n teactOrderKey={getChatOrder(chat)}\n chatId={chat.id}\n folderId={folderId}\n isSelected={chat.id === currentChatId && !isInDiscussionThread}\n animationType={getAnimationType(chat.id)}\n orderDiff={orderDiffById[chat.id]}\n // @ts-ignore\n style={`top: ${(pinnedOffset + i) * CHAT_HEIGHT_PX}px;`}\n />\n ))}\n </div>\n );\n }\n\n useEffect(() => {\n const handleKeyDown = (e: KeyboardEvent) => {\n if (isActive && orderedIds) {\n if (e.ctrlKey && e.code.startsWith('Digit')) {\n const [, digit] = e.code.match(/Digit(\\d)/) || [];\n if (!digit) return;\n\n const position = Number(digit) - 1;\n if (position > orderedIds.length - 1) return;\n\n openChat({ id: orderedIds[position] });\n }\n\n if (e.altKey) {\n const targetIndexDelta = e.key === 'ArrowDown' ? 1 : e.key === 'ArrowUp' ? -1 : undefined;\n if (!targetIndexDelta) return;\n\n if (!currentChatId) {\n e.preventDefault();\n openChat({ id: orderedIds[0] });\n return;\n }\n\n const position = orderedIds.indexOf(currentChatId);\n\n if (position === -1) {\n return;\n }\n const nextId = orderedIds[position + targetIndexDelta];\n\n e.preventDefault();\n openChat({ id: nextId });\n }\n }\n };\n\n document.addEventListener('keydown', handleKeyDown, false);\n\n return () => {\n document.removeEventListener('keydown', handleKeyDown, false);\n };\n });\n\n return (\n <InfiniteScroll\n className=\"chat-list custom-scroll\"\n items={viewportIds}\n onLoadMore={getMore}\n preloadBackwards={CHAT_LIST_SLICE}\n noFastList\n noScrollRestore\n >\n {viewportIds && viewportIds.length && chatArrays ? (\n renderChats()\n ) : viewportIds && !viewportIds.length ? (\n <div className=\"no-results\">{noChatsText}</div>\n ) : (\n <Loading key=\"loading\" />\n )}\n </InfiniteScroll>\n );\n};\n\nexport default memo(withGlobal<OwnProps>(\n (global, { folderType, folderId }): StateProps => {\n const {\n chats: {\n listIds,\n byId: chatsById,\n orderedPinnedIds,\n },\n users: { byId: usersById },\n lastSyncTime,\n } = global;\n const { chatId: currentChatId, threadId: currentThreadId } = selectCurrentMessageList(global) || {};\n\n const listType = folderType !== 'folder' ? FolderTypeToListType[folderType] : undefined;\n const chatFolder = folderId ? selectChatFolder(global, folderId) : undefined;\n\n return {\n chatsById,\n usersById,\n currentChatId,\n lastSyncTime,\n ...(listType ? {\n listIds: listIds[listType],\n orderedPinnedIds: orderedPinnedIds[listType],\n } : {\n chatFolder,\n }),\n isInDiscussionThread: currentThreadId !== MAIN_THREAD_ID,\n notifySettings: selectNotifySettings(global),\n notifyExceptions: selectNotifyExceptions(global),\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'loadMoreChats',\n 'preloadTopChatMessages',\n 'openChat',\n ]),\n)(ChatList));\n","import { useCallback, useEffect, useState } from '../../../../lib/teact/teact';\n\nimport { ApiMessageEntityTypes, ApiChatMember, ApiUser } from '../../../../api/types';\nimport { EDITABLE_INPUT_ID } from '../../../../config';\nimport { getUserFirstOrLastName } from '../../../../modules/helpers';\nimport searchUserName from '../helpers/searchUserName';\nimport { IS_MOBILE_SCREEN } from '../../../../util/environment';\nimport focusEditableElement from '../../../../util/focusEditableElement';\nimport useFlag from '../../../../hooks/useFlag';\n\nconst RE_NOT_USERNAME_SEARCH = /[^@_\\d\\wа-яё]+/i;\n\nexport default function useMentionTooltip(\n canSuggestMembers: boolean | undefined,\n html: string,\n onUpdateHtml: (html: string) => void,\n inputId: string = EDITABLE_INPUT_ID,\n groupChatMembers?: ApiChatMember[],\n currentUserId?: number,\n usersById?: Record<number, ApiUser>,\n) {\n const [isOpen, markIsOpen, unmarkIsOpen] = useFlag();\n const [currentFilter, setCurrentFilter] = useState('');\n const [filteredMembers, setFilteredMembers] = useState<ApiChatMember[]>([]);\n\n const getFilteredMembers = useCallback((filter) => {\n if (!groupChatMembers || !usersById) {\n return undefined;\n }\n\n return groupChatMembers.filter(({ userId }) => {\n const user = usersById[userId];\n if (userId === currentUserId || !user) {\n return false;\n }\n\n return !filter || searchUserName(filter, user);\n });\n }, [groupChatMembers, currentUserId, usersById]);\n\n useEffect(() => {\n if (!canSuggestMembers || !html.length) {\n unmarkIsOpen();\n return;\n }\n\n const usernameFilter = getUsernameFilter(html);\n\n if (usernameFilter) {\n const filter = usernameFilter ? usernameFilter.substr(1) : '';\n const membersToMention = getFilteredMembers(filter);\n if (membersToMention && membersToMention.length) {\n markIsOpen();\n setCurrentFilter(filter);\n setFilteredMembers(membersToMention);\n } else {\n unmarkIsOpen();\n }\n } else {\n unmarkIsOpen();\n }\n }, [canSuggestMembers, html, getFilteredMembers, markIsOpen, unmarkIsOpen]);\n\n const insertMention = useCallback((user: ApiUser, forceFocus = false) => {\n if (!user.username && !getUserFirstOrLastName(user)) {\n return;\n }\n\n const insertedHtml = user.username\n ? `@${user.username}`\n : `<a\n class=\"text-entity-link\"\n data-entity-type=\"${ApiMessageEntityTypes.MentionName}\"\n data-user-id=\"${user.id}\"\n contenteditable=\"false\"\n dir=\"auto\"\n >${getUserFirstOrLastName(user)}</a>`;\n\n const atIndex = html.lastIndexOf('@');\n if (atIndex !== -1) {\n onUpdateHtml(`${html.substr(0, atIndex)}${insertedHtml}&nbsp;`);\n const messageInput = document.getElementById(inputId)!;\n if (!IS_MOBILE_SCREEN) {\n requestAnimationFrame(() => {\n focusEditableElement(messageInput, forceFocus);\n });\n }\n }\n\n unmarkIsOpen();\n }, [html, inputId, onUpdateHtml, unmarkIsOpen]);\n\n return {\n isMentionTooltipOpen: isOpen,\n mentionFilter: currentFilter,\n closeMentionTooltip: unmarkIsOpen,\n insertMention,\n mentionFilteredMembers: filteredMembers,\n };\n}\n\nfunction getUsernameFilter(html: string) {\n const tempEl = document.createElement('div');\n tempEl.innerHTML = html;\n const text = tempEl.innerText;\n\n const lastSymbol = text[text.length - 1];\n const lastWord = text.split(RE_NOT_USERNAME_SEARCH).pop();\n\n if (\n !text.length || RE_NOT_USERNAME_SEARCH.test(lastSymbol)\n || !lastWord || !lastWord.startsWith('@')\n ) {\n return undefined;\n }\n\n return lastWord;\n}\n","import { ApiUser } from '../../../../api/types';\nimport { getUserFullName } from '../../../../modules/helpers';\nimport searchWords from '../../../../util/searchWords';\n\n// TODO: Support cyrillic translit search\nexport default function searchUserName(filter: string, user: ApiUser) {\n const usernameLowered = user.username.toLowerCase();\n const fullName = getUserFullName(user);\n const fullNameLowered = fullName && fullName.toLowerCase();\n const filterLowered = filter.toLowerCase();\n\n return usernameLowered.startsWith(filterLowered) || (\n fullNameLowered && searchWords(fullNameLowered, filterLowered)\n );\n}\n","import { useEffect, useRef } from '../lib/teact/teact';\n\nimport fastBlur from '../lib/fastBlur';\nimport { imgToCanvas } from '../util/files';\nimport useForceUpdate from './useForceUpdate';\n\nconst RADIUS = 2;\nconst ITERATIONS = 2;\nconst MAX_CACHE_SIZE = 1000;\n\nconst cache = new Map<string, string>();\n\nexport default function useBlur(dataUri?: string, isDisabled = false, delay?: number) {\n const blurredRef = useRef<string | undefined>(dataUri ? cache.get(dataUri) : undefined);\n const timeoutRef = useRef<number>();\n const forceUpdate = useForceUpdate();\n\n if (timeoutRef.current && isDisabled) {\n clearTimeout(timeoutRef.current);\n timeoutRef.current = undefined;\n }\n\n useEffect(() => {\n if (!dataUri || blurredRef.current || isDisabled) {\n return;\n }\n\n const img = new Image();\n\n img.onload = () => {\n const canvas = imgToCanvas(img);\n fastBlur(canvas.getContext('2d'), 0, 0, canvas.width, canvas.height, RADIUS, ITERATIONS);\n const blurredDataUri = canvas.toDataURL();\n\n blurredRef.current = blurredDataUri;\n forceUpdate();\n\n if (cache.size >= MAX_CACHE_SIZE) {\n cache.clear();\n }\n cache.set(dataUri, blurredDataUri);\n };\n\n if (delay) {\n timeoutRef.current = window.setTimeout(() => {\n img.src = dataUri;\n }, delay);\n } else {\n img.src = dataUri;\n }\n }, [dataUri, delay, forceUpdate, isDisabled]);\n\n return blurredRef.current;\n}\n","import { useRef } from '../lib/teact/teact';\n\nimport fastBlur from '../lib/fastBlur';\nimport useOnChange from './useOnChange';\nimport useBlur from './useBlur';\nimport { imgToCanvas } from '../util/files';\n\nconst RADIUS = 2;\nconst ITERATIONS = 2;\n\nexport default function useBlurSync(dataUri: string | false | undefined) {\n const blurredRef = useRef<string>();\n\n let isChanged = false;\n\n useOnChange(() => {\n isChanged = true;\n\n blurredRef.current = undefined;\n\n if (!dataUri) {\n return;\n }\n\n const img = new Image();\n img.src = dataUri;\n if (!img.width) {\n return;\n }\n\n const canvas = imgToCanvas(img);\n fastBlur(canvas.getContext('2d'), 0, 0, canvas.width, canvas.height, RADIUS, ITERATIONS);\n\n blurredRef.current = canvas.toDataURL();\n }, [dataUri]);\n\n // Sometimes `Image` do not manage to load synchronously,\n // so we fall back the non-blurred variant and prepare the async one at least for the next time\n const blurredAsync = useBlur(dataUri || undefined, Boolean(blurredRef.current));\n\n return blurredRef.current || (!isChanged && blurredAsync) || dataUri || undefined;\n}\n"],"sourceRoot":""}