telegram-tt/dist/3.b7d1e22369add742c79e.js.map
Alexander Zinchuk 6fc73cb18a [Build]
2021-06-15 02:22:50 +03:00

1 line
917 KiB
Plaintext

{"version":3,"sources":["webpack:///./src/components/mediaViewer/helpers/ghostAnimation.ts","webpack:///./src/components/mediaViewer/SenderInfo.tsx","webpack:///./src/components/mediaViewer/MediaViewerActions.tsx","webpack:///./src/components/mediaViewer/MediaViewerFooter.tsx","webpack:///./src/hooks/useFullscreen.ts","webpack:///./src/components/mediaViewer/helpers/formatFileSize.ts","webpack:///./src/components/mediaViewer/VideoPlayerControls.tsx","webpack:///./src/components/mediaViewer/VideoPlayer.tsx","webpack:///./src/components/mediaViewer/ZoomControls.tsx","webpack:///./src/components/mediaViewer/PanZoom.tsx","webpack:///./src/components/mediaViewer/MediaViewer.tsx","webpack:///./src/components/main/ForwardPicker.tsx","webpack:///./src/components/main/Errors.tsx","webpack:///./src/components/main/Notifications.tsx","webpack:///./src/components/main/SafeLinkModal.tsx","webpack:///./src/components/common/CalendarModal.tsx","webpack:///./src/components/main/HistoryCalendar.tsx","webpack:///./src/components/common/DeleteMessageModal.tsx","webpack:///./src/components/common/PinMessageModal.tsx","webpack:///./src/components/common/UnpinAllMessagesModal.tsx","webpack:///./src/components/middle/DeleteSelectedMessagesModal.tsx","webpack:///./src/components/middle/MessageSelectToolbar.tsx","webpack:///./src/hooks/useSelectWithEnter.ts","webpack:///./src/components/left/search/LeftSearchResultChat.tsx","webpack:///./src/components/left/search/RecentContacts.tsx","webpack:///./src/components/left/search/ChatMessage.tsx","webpack:///./src/components/left/search/DateSuggest.tsx","webpack:///./src/components/left/search/ChatResults.tsx","webpack:///./src/components/left/search/ChatMessageResults.tsx","webpack:///./src/components/left/search/helpers/createMapStateToProps.ts","webpack:///./src/components/left/search/MediaResults.tsx","webpack:///./src/components/left/search/helpers/getSenderName.ts","webpack:///./src/components/left/search/LinkResults.tsx","webpack:///./src/components/left/search/FileResults.tsx","webpack:///./src/components/left/search/AudioResults.tsx","webpack:///./src/components/left/search/LeftSearch.tsx","webpack:///./src/hooks/useReducer.ts","webpack:///./src/hooks/reducers/useFoldersReducer.ts","webpack:///./src/hooks/reducers/useTwoFaReducer.ts","webpack:///./src/components/left/settings/SettingsHeader.tsx","webpack:///./src/components/left/settings/SettingsMain.tsx","webpack:///./src/components/ui/FloatingActionButton.tsx","webpack:///./src/components/common/UsernameInput.tsx","webpack:///./src/components/left/settings/SettingsEditProfile.tsx","webpack:///./src/components/left/settings/folders/SettingsFoldersMain.tsx","webpack:///./src/components/ui/ShowMoreButton.tsx","webpack:///./src/components/left/settings/folders/SettingsFoldersEdit.tsx","webpack:///./src/components/left/settings/folders/SettingsFoldersChatsPicker.tsx","webpack:///./src/components/left/settings/folders/SettingsFoldersChatFilters.tsx","webpack:///./src/components/left/settings/folders/SettingsFolders.tsx","webpack:///./src/components/ui/RangeSlider.tsx","webpack:///./src/components/middle/composer/StickerSetCoverAnimated.tsx","webpack:///./src/components/middle/composer/StickerSetCover.tsx","webpack:///./src/components/common/StickerButton.tsx","webpack:///./src/components/left/settings/SettingsStickerSet.tsx","webpack:///./src/components/left/settings/SettingsGeneral.tsx","webpack:///./src/util/systemFilesDialog.ts","webpack:///./src/util/colors.ts","webpack:///./src/components/left/settings/WallpaperTile.tsx","webpack:///./src/components/left/settings/SettingsGeneralBackground.tsx","webpack:///./src/components/left/settings/SettingsGeneralBackgroundColor.tsx","webpack:///./src/components/left/settings/SettingsNotifications.tsx","webpack:///./src/components/left/settings/SettingsPrivacy.tsx","webpack:///./src/components/left/settings/SettingsLanguage.tsx","webpack:///./src/components/left/settings/helper/privacy.ts","webpack:///./src/components/left/settings/SettingsPrivacyVisibility.tsx","webpack:///./src/components/left/settings/SettingsPrivacyActiveSessions.tsx","webpack:///./src/components/left/settings/SettingsPrivacyBlockedUsers.tsx","webpack:///./src/components/left/settings/twoFa/SettingsTwoFaEnabled.tsx","webpack:///./src/components/left/settings/twoFa/SettingsTwoFaPassword.tsx","webpack:///./src/components/left/settings/twoFa/SettingsTwoFaStart.tsx","webpack:///./src/components/left/settings/twoFa/SettingsTwoFaSkippableForm.tsx","webpack:///./src/components/left/settings/twoFa/SettingsTwoFaCongratulations.tsx","webpack:///./src/components/left/settings/twoFa/SettingsTwoFaEmailCode.tsx","webpack:///./src/components/left/settings/twoFa/SettingsTwoFa.tsx","webpack:///./src/components/common/Picker.tsx","webpack:///./src/components/left/settings/SettingsPrivacyVisibilityExceptionList.tsx","webpack:///./src/components/left/settings/Settings.tsx","webpack:///./src/components/left/main/ContactList.tsx","webpack:///./src/components/left/newChat/NewChatStep1.tsx","webpack:///./src/components/left/newChat/NewChatStep2.tsx","webpack:///./src/components/left/newChat/NewChat.tsx","webpack:///./src/components/left/ArchivedChats.tsx","webpack:///./src/util/scrollLock.ts","webpack:///./src/components/middle/message/helpers/copyOptions.ts","webpack:///./src/components/middle/message/MessageContextMenu.tsx","webpack:///./src/components/middle/message/ContextMenuContainer.tsx","webpack:///./src/components/common/StickerSetModal.tsx","webpack:///./src/components/middle/HeaderMenuContainer.tsx","webpack:///./src/components/middle/MobileSearch.tsx","webpack:///./src/util/findInViewport.ts","webpack:///./src/util/isFullyVisible.ts","webpack:///./src/components/middle/composer/MentionTooltip.tsx","webpack:///./src/components/middle/composer/AttachmentModal.tsx","webpack:///./src/components/middle/composer/PollModal.tsx","webpack:///./src/hooks/useMouseInside.ts","webpack:///./src/components/middle/composer/EmojiButton.tsx","webpack:///./src/components/middle/composer/EmojiCategory.tsx","webpack:///./src/components/middle/composer/EmojiPicker.tsx","webpack:///./src/components/middle/composer/StickerSet.tsx","webpack:///./src/components/middle/composer/StickerPicker.tsx","webpack:///./src/components/common/GifButton.tsx","webpack:///./src/components/middle/composer/GifPicker.tsx","webpack:///./src/components/middle/composer/SymbolMenuFooter.tsx","webpack:///./src/components/middle/composer/SymbolMenu.tsx","webpack:///./src/components/middle/composer/AttachMenu.tsx","webpack:///./src/components/middle/composer/StickerTooltip.tsx","webpack:///./src/components/middle/composer/BotKeyboardMenu.tsx","webpack:///./src/components/middle/composer/CustomSendMenu.tsx","webpack:///./src/components/middle/composer/EmojiTooltip.tsx","webpack:///./src/components/right/RightSearch.tsx","webpack:///./src/components/right/StickerSetResult.tsx","webpack:///./src/components/right/StickerSearch.tsx","webpack:///./src/components/right/GifSearch.tsx","webpack:///./src/components/right/PollAnswerResults.tsx","webpack:///./src/components/right/PollResults.tsx","webpack:///./src/components/right/management/ManageUser.tsx","webpack:///./src/components/right/management/ManageGroup.tsx","webpack:///./src/components/right/management/ManageGroupPermissions.tsx","webpack:///./src/components/right/management/ManageGroupRemovedUsers.tsx","webpack:///./src/components/right/management/ManageChannel.tsx","webpack:///./src/components/right/management/ManageChatPrivacyType.tsx","webpack:///./src/components/right/management/ManageDiscussion.tsx","webpack:///./src/components/right/management/ManageGroupUserPermissions.tsx","webpack:///./src/components/right/management/ManageChatAdministrators.tsx","webpack:///./src/components/right/management/ManageGroupRecentActions.tsx","webpack:///./src/components/right/management/ManageGroupAdminRights.tsx","webpack:///./src/components/right/management/ManageGroupMembers.tsx","webpack:///./src/components/right/management/ManageGroupUserPermissionsCreate.tsx","webpack:///./src/components/right/management/Management.tsx","webpack:///./src/components/middle/helpers/getCurrencySign.ts","webpack:///./src/components/common/helpers/detectCardType.ts","webpack:///./src/hooks/reducers/usePaymentReducer.ts","webpack:///./src/hooks/useFocusAfterAnimation.tsx","webpack:///./src/components/ui/Select.tsx","webpack:///./src/components/payment/ShippingInfo.tsx","webpack:///./src/components/payment/Shipping.tsx","webpack:///./src/components/payment/Checkout.tsx","webpack:///./src/components/payment/ExpiryInput.tsx","webpack:///./src/components/middle/helpers/inputFormatters.ts","webpack:///./src/assets/mastercard.svg","webpack:///./src/assets/visa.svg","webpack:///./src/components/payment/CardInput.tsx","webpack:///./src/components/payment/PaymentInfo.tsx","webpack:///./src/components/payment/PaymentModal.tsx","webpack:///./src/components/payment/ReceiptModal.tsx","webpack:///./src/components/common/helpers/animatedAssets.ts","webpack:///./src/assets/TwoFactorSetupMonkeyIdle.tgs","webpack:///./src/assets/TwoFactorSetupMonkeyTracking.tgs","webpack:///./src/assets/TwoFactorSetupMonkeyClose.tgs","webpack:///./src/assets/TwoFactorSetupMonkeyPeek.tgs","webpack:///./src/assets/FoldersAll.tgs","webpack:///./src/assets/FoldersNew.tgs","webpack:///./src/assets/DiscussionGroupsDucks.tgs","webpack:///./src/components/ui/CropModal.tsx","webpack:///./src/components/ui/AvatarEditable.tsx","webpack:///./src/components/common/PasswordMonkey.tsx","webpack:///./src/components/common/PasswordForm.tsx"],"names":["animateOpening","hasFooter","origin","bestImageData","message","mediaEl","fromImage","getNodes","width","windowWidth","windowSize","get","mediaSize","isVideo","photo","video","webPage","getMessageContent","Boolean","getVideoDimensions","getPhotoFullDimensions","AVATAR_FULL_DIMENSIONS","availableWidth","height","availableHeight","getMediaViewerAvailableDimensions","toWidth","toHeight","calculateDimensions","toLeft","toTop","mql","window","matchMedia","MEDIA_VIEWER_MEDIA_QUERY","topOffsetRem","matches","REM","getTopOffset","top","fromTop","left","fromLeft","fromWidth","fromHeight","getBoundingClientRect","MediaViewerOrigin","SharedMedia","Album","ScheduledAlbum","SearchResult","includes","uncovered","realWidth","realHeight","size","Math","max","srcWidth","srcHeight","uncover","fromTranslateX","fromTranslateY","fromScaleX","fromScaleY","ghost","createGhost","applyStyles","transform","applyShape","document","body","classList","add","requestAnimationFrame","appendChild","style","firstChild","objectFit","remove","clearShape","setTimeout","contains","removeChild","ANIMATION_END_DELAY","animateClosing","container","toImage","getElementById","querySelector","targetTop","el","display","rect","windowHeight","isElementInViewport","shouldFadeOut","Inline","ScheduledInline","isMessageImageFullyVisible","existingGhost","getElementsByClassName","ProfileAvatar","transition","transformOrigin","opacity","source","shouldAppendProfileInfo","createElement","img","Image","src","HTMLVideoElement","poster","profileInfo","cloneNode","imageEl","messageListElement","imgOffsetTop","offsetTop","closest","id","parentElement","scrollTop","offsetHeight","element","styles","Object","assign","containerSelector","mediaSelector","MiddleHeaderAvatar","mediaEls","querySelectorAll","length","withGlobal","global","chatId","messageId","isAvatar","sender","isChatPrivate","selectUser","selectChat","selectChatMessage","selectSender","setGlobal","actions","pick","closeMediaViewer","focusMessage","handleFocusMessage","useCallback","lang","useLang","isFromChat","senderTitle","getSenderTitle","className","onClick","Avatar","key","chat","user","dir","renderText","formatMediaDateTime","date","MediaViewerActions","mediaData","isZoomed","fileName","onCloseMediaViewer","onForward","onZoomToggle","isVideoDownloadAllowed","setIsVideoDownloadAllowed","useState","videoMediaHash","getMessageMediaHash","undefined","videoBlobUrl","downloadProgress","useMediaWithDownloadProgress","useEffect","download","handleVideoDownloadClick","e","stopPropagation","isAllowed","MenuButton","useMemo","onTrigger","isOpen","Button","round","color","ariaLabel","IS_MOBILE_SCREEN","DropdownMenu","trigger","positionX","MenuItem","icon","href","ProgressSpinner","progress","noCross","MediaViewerFooter","text","isHideable","isMultiline","setIsMultiline","footerContent","checkIsMultiline","clientHeight","handleResize","throttle","addEventListener","removeEventListener","prop","fullscreenElement","mozFullScreenElement","webkitFullscreenElement","getBrowserFullscreenElementProp","units","bytes","number","floor","log","toFixed","stopEvent","VideoPlayerControls","bufferedProgress","currentTime","duration","fileSize","isForceVisible","isForceMobileVersion","isPlayed","isFullscreenSupported","isFullscreen","onChangeFullscreen","onPlayPause","onSeek","isVisible","setVisibility","timeout","clearTimeout","downloadedPercent","totalSize","percentagePlayed","percentageBuffered","min","step","type","onInput","value","renderSeekLine","ripple","formatMediaDuration","renderTime","formatFileSize","memo","url","isGif","posterData","posterSize","isMediaViewerOpen","noPlay","onClose","videoRef","useRef","setIsPlayed","IS_TOUCH_ENV","IS_IOS","setCurrentTime","isControlsVisible","setIsControlsVisible","setFullscreen","exitFullscreen","elRef","setIsFullscreen","useLayoutEffect","listener","listenerEnter","listenerExit","current","PLATFORM_ENV","requestFullscreen","webkitRequestFullscreen","webkitEnterFullscreen","mozRequestFullScreen","mozCancelFullScreen","webkitCancelFullScreen","webkitExitFullscreen","useFullscreenStatus","isBuffered","bufferingHandlers","useBuffering","shouldRender","shouldRenderSpinner","transitionClassNames","spinnerClassNames","useShowTransition","pause","safePlay","togglePlayState","play","useVideoCleanup","handleMouseOver","handleMouseOut","handleTimeUpdate","currentTarget","handleEnded","handleFullscreenChange","handleSeek","Number","target","toggleControls","togglePayingStateBySpace","wrapperStyle","videoStyle","onMouseOver","onMouseOut","ref","autoPlay","playsInline","loop","muted","onEnded","onTimeUpdate","join","square","isShown","onChangeZoom","prevIsShown","usePrevious","inputRef","zoomLevel","setZoomLevel","isSeeking","handleStartSeek","handleStopSeek","buildClassName","disabled","onChange","onMouseDown","onMouseUp","INITIAL_MATRIX","SCALE_VALUES","1","1.5","2","2.5","3","children","noWrap","canPan","panDeltaX","panDeltaY","onPan","tunedZoomLevel","isDragging","setIsDragging","dragData","setDragData","dx","dy","x","y","matrixData","setMatrixData","panWrapperRef","panContainerRef","newZoomLevel","newPandx","newPandy","newMatrixData","areSortedArraysEqual","oldScale","wrapper","image","wrapperRect","imageRect","newImgWidth","newImgHeight","newImgX","newImgY","calculateSafeZoneOnZoom","toString","preventDefault","newDragData","pageX","pageY","onMouseMove","deltaX","deltaY","getNewMatrixData","renderPhoto","blobUrl","imageSize","canDrag","alt","draggable","Spinner","threadId","avatarOwnerId","profilePhotoIndex","mediaViewer","animationLevel","settings","byKey","senderId","avatarOwner","chatMessages","collectionIds","selectScheduledMessage","selectScheduledMessages","selectChatMessages","selectOutlyingIds","selectListedIds","currentSearch","selectCurrentMediaSearch","foundIds","resultsByType","media","openMediaViewer","openForwardMenu","animationKey","webPagePhoto","getMessageWebPagePhoto","getMessagePhoto","getMessageVideo","isWebPagePhoto","isPhoto","isFromSharedMedia","isFromSearch","slideAnimation","headerAnimation","isGhostAnimation","getMessageMediaFilename","prevSenderId","canPanZoomWrap","setCanPanZoomWrap","setIsZoomed","panDelta","setPanDelta","messageIds","getChatMediaMessageIds","selectedMediaMessageIndex","indexOf","isFirst","isLast","getMediaHash","full","photos","getChatAvatarHash","blobUrlPictogram","useMedia","ApiMediaFormat","BlobUrl","previewMediaHash","blobUrlPreview","startsWith","DataUri","fullMediaData","getMessageMediaFormat","localBlobUrl","thumbDataUri","useBlurSync","getMessageMediaThumbDataUri","photoDimensions","videoDimensions","toggle","forceUpdate","useForceUpdate","addListener","removeListener","prevMessage","prevOrigin","prevAvatarOwner","prevBestImageData","dispatchHeavyAnimationEvent","textParts","renderMessageText","timer","closeZoom","handleZoomToggle","handleZoomValue","level","canCloseZoom","close","handleFooterClick","handleForward","fromChatId","captureEscKeyListener","stopCurrentAudio","getMessageId","fromId","direction","index","selectPreviousMedia","selectNextMedia","handleKeyDown","shouldCloseOnVideo","captureEvents","excludedClosestSelector","onSwipe","SwipeDirection","Right","Left","handlePan","renderSlide","isActive","calculateMediaViewerDimensions","renderSenderInfo","ShowTransition","isRtl","Transition","activeKey","name","aria-label","chats","byId","chatsById","listIds","currentUserId","activeListIds","active","archivedListIds","archived","setForwardChatId","exitForwardMode","loadMoreChats","filter","setFilter","focus","blur","chatIds","sortChatIds","getCanPostInChat","MAIN_THREAD_ID","searchWords","getChatTitle","viewportIds","getMore","useInfiniteScroll","handleFilterChange","containerRef","useKeyboardListNavigation","modalHeader","InputText","onKeyDown","placeholder","Modal","header","InfiniteScroll","items","onLoadMore","noScrollRestore","map","ListItem","PrivateChatInfo","status","userId","GroupChatInfo","Loading","getErrorHeader","error","isSlowMode","errors","dismissError","title","getReadableErrorText","isText","notifications","dismissNotification","Notification","onDismiss","toggleSafeLinkModal","handleOpen","open","handleDismiss","renderingUrl","useCurrentOrPrev","ConfirmDialog","confirmLabel","confirmHandler","WEEKDAY_LETTERS","isDisabledDay","year","month","day","minDate","maxDate","selectedDay","Date","fixedMinDate","getFullYear","getMonth","getDate","fixedMaxDate","formatInputTime","String","padStart","selectedAt","maxAt","isFutureMode","isPastMode","withTimePicker","submitButtonLabel","secondButtonLabel","onSubmit","onSecondButtonClick","now","defaultSelectedDate","selectedDate","setSelectedDate","selectedHours","setSelectedHours","getHours","selectedMinutes","setSelectedMinutes","getMinutes","currentYear","currentMonth","currentDate","shouldDisableNextMonth","shouldDisablePrevMonth","calendarGrid","grid","setFullYear","setMonth","setDate","monthStartDay","getDay","i","push","gridDate","buildCalendarGrid","handleChangeHours","replace","hours","getTime","setHours","hoursStr","handleChangeMinutes","minutes","setMinutes","minutesStr","formatMonthAndYear","d","dateCopy","letter","role","tabIndex","handleDateSelect","inputMode","formatHumanDate","formatTime","formatSubmitLabel","historyCalendarSelectedAt","searchMessagesByDate","closeHistoryCalendar","handleJumpToDate","timestamp","valueOf","isSchedule","selectCurrentMessageList","canDeleteForAll","selectAllowedMessageActions","contactName","getUserFirstOrLastName","getPrivateChatUserId","willDeleteForCurrentUserOnly","isChatBasicGroup","willDeleteForAll","isChatSuperGroup","album","deleteMessages","deleteScheduledMessages","handleDeleteMessageForAll","messages","shouldDeleteForAll","handleDeleteMessageForSelf","onEnter","isPrivateChat","isChatWithSelf","selectIsChatWithSelf","isChannel","isChatChannel","isGroup","isSuperGroup","canPinForAll","pinMessage","handlePinMessageForAll","isUnpin","handlePinMessage","isOneSide","isSilent","pinnedMessagesCount","onUnpin","selectedMessageIds","selectedMessages","selectCanDeleteSelectedMessages","selectCurrentChat","exitMessageSelectMode","messageListType","canDelete","selectedMessagesCount","selectSelectedMessagesCount","canDeleteMessages","canPost","openForwardMenuForSelectedMessages","isDeleteModalOpen","openDeleteModal","closeDeleteModal","useFlag","captureKeyboardListeners","onBackspace","onDelete","onEsc","prevSelectedMessagesCount","renderingSelectedMessagesCount","formattedMessagesCount","destructive","onSelect","buttonRef","activeElement","privateChatUserId","privateChatUser","isPinned","selectIsChatPinned","withUsername","contextActions","useChatContextActions","handleDelete","handleClick","useSelectWithEnter","avatarSize","DeleteChatModal","runThrottled","cb","userIds","topUserIds","topPeers","usersById","users","recentlyFoundChatIds","globalSearch","onReset","loadTopUsers","loadContactList","openChat","addRecentlyFoundChatId","clearRecentlyFoundChats","topUsersRef","useHorizontalScroll","lastSyncTime","searchQuery","mediaThumbnail","mediaBlobUrl","isRoundVideo","getMessageRoundVideo","withOnlineStatus","isSavedMessages","isSelf","isVerified","VerifiedIcon","Link","formatPastTimeShort","getMessageSummaryText","highlight","renderMessageSummary","searchDate","suggestions","match","formatDateToString","suggestion","latestYear","getSuggestionsFromDate","localContactIds","contactList","fetchingStatus","globalResults","localResults","globalChatIds","globalUserIds","localChatIds","localUserIds","byChatId","globalMessagesByChatId","dateSearchQuery","onSearchDateSelect","searchMessagesGlobal","setGlobalSearchChatId","shouldShowMoreLocal","setShouldShowMoreLocal","shouldShowMoreGlobal","setShouldShowMoreGlobal","handleLoadMore","LoadMoreDirection","Backwards","query","handleChatClick","handlePickerItemClick","MEMO_EMPTY_ARRAY","foundContactIds","fullName","getUserFullName","username","unique","foundMessages","split","sort","a","b","handleClickShowMoreLocal","handleClickShowMoreGlobal","nothingFound","noScrollRestoreOnTop","noFastList","NothingFound","description","PickerSelectedItem","chatOrUserId","clickArg","createMapStateToProps","props","currentType","isVoice","isLoading","searchChatId","handleSelectMedia","canRenderContents","useAsyncRendering","SLIDE_TRANSITION_DURATION","isMediaGrid","isMessageList","classNames","itemSelector","Media","idPrefix","getSenderName","senderName","isChatGroup","handleMessageFocus","shouldDrawDateDivider","toYearMonth","WebLink","onMessageClick","getMessageDocument","Document","withDate","datetime","smaller","onDateClick","openAudioPlayer","handlePlayAudio","Audio","renderingFor","onPlay","TABS","GlobalSearchContent","ChatList","Links","Files","Music","Voice","CHAT_TABS","slice","TRANSITION_RENDER_COUNT","keys","currentContent","setGlobalSearchContent","setGlobalSearchDate","activeTab","setActiveTab","parseDateString","handleSwitchTab","tab","content","handleSearchDateSelect","TabList","tabs","onSwitchTab","renderCount","useReducer","reducer","initialState","reducerRef","state","setState","action","currentState","INCLUDED_CHAT_TYPES","EXCLUDED_CHAT_TYPES","INCLUDE_FILTER_FIELDS","EXCLUDE_FILTER_FIELDS","selectChatFilters","mode","selectTemp","selectedChatIds","selectedChatTypes","includedChatIds","includeFilters","folder","excludedChatIds","excludeFilters","getSuggestedFolderName","filters","values","bots","groups","channels","contacts","nonContacts","INITIAL_STATE","chatFilter","foldersReducer","payload","isTouched","omit","folderId","currentPassword","password","hint","email","twoFaReducer","currentScreen","editedFolderId","onSaveFilter","signOut","deleteChatFolder","isSignOutDialogOpen","setIsSignOutDialogOpen","isDeleteFolderDialogOpen","setIsDeleteFolderDialogOpen","openSignOutConfirmation","closeSignOutConfirmation","openDeleteFolderConfirmation","closeDeleteFolderConfirmation","handleSignOutMessage","handleDeleteFolderMessage","SettingsMenuButton","SettingsScreens","EditProfile","General","Notifications","Privacy","Language","GeneralChatBackground","GeneralChatBackgroundColor","PrivacyPhoneNumber","PrivacyLastSeen","PrivacyProfilePhoto","PrivacyForwarding","PrivacyGroupChats","PrivacyPhoneNumberAllowedContacts","PrivacyLastSeenAllowedContacts","PrivacyProfilePhotoAllowedContacts","PrivacyForwardingAllowedContacts","PrivacyGroupChatsAllowedContacts","PrivacyPhoneNumberDeniedContacts","PrivacyLastSeenDeniedContacts","PrivacyProfilePhotoDeniedContacts","PrivacyForwardingDeniedContacts","PrivacyGroupChatsDeniedContacts","PrivacyActiveSessions","PrivacyBlockedUsers","TwoFaDisabled","TwoFaEnabled","TwoFaNewPassword","TwoFaChangePasswordNew","TwoFaChangePasswordConfirm","TwoFaNewPasswordConfirm","TwoFaNewPasswordHint","TwoFaChangePasswordHint","TwoFaNewPasswordEmail","TwoFaRecoveryEmail","TwoFaNewPasswordEmailCode","TwoFaRecoveryEmailCode","TwoFaCongratulations","TwoFaChangePasswordCurrent","TwoFaTurnOff","TwoFaRecoveryEmailCurrentPassword","Folders","FoldersCreateFolder","FoldersEditFolder","FoldersIncludedChats","FoldersExcludedChats","renderHeaderContent","confirmIsDestructive","currentUser","onScreenSelect","formatPhoneNumberWithCode","phoneNumber","FloatingActionButton","buttonClassName","LINK_PREFIX_REGEX","USERNAME_REGEX","runDebouncedForCheckUsername","debounce","currentUsername","asLink","isUsernameAvailable","checkUsername","setUsername","langPrefix","label","usernameSuccess","usernameError","test","handleUsernameChange","newUsername","trim","isValid","isUsernameValid","success","readOnly","profileEdit","firstName","currentFirstName","lastName","currentLastName","fullInfo","bio","currentBio","currentAvatarHash","loadCurrentUser","updateProfile","isUsernameTouched","setIsUsernameTouched","isProfileFieldsTouched","setIsProfileFieldsTouched","setError","setPhoto","setFirstName","setLastName","setBio","currentAvatarBlobUrl","ProfileEditProgress","InProgress","isUsernameError","isSaveButtonShown","Complete","handlePhotoChange","newPhoto","handleFirstNameChange","handleLastNameChange","handleBioChange","handleProfileSave","trimmedFirstName","trimmedLastName","trimmedBio","AvatarEditable","UsernameInput","runThrottledForLoadRecommended","orderedIds","orderedFolderIds","foldersById","recommended","recommendedChatFolders","chatFolders","notifySettings","selectNotifySettings","notifyExceptions","selectNotifyExceptions","onCreateFolder","onEditFolder","loadRecommendedChatFolders","addChatFolder","showError","animationData","setAnimationData","isAnimationLoaded","setIsAnimationLoaded","handleAnimationLoad","getAnimationData","then","handleCreateFolder","userFolders","subtitle","getFolderDescriptionText","handleCreateFolderFromRecommended","AnimatedSticker","STICKER_SIZE_FOLDER_SETTINGS","noLoop","onLoad","pill","fluid","narrow","multiline","ShowMoreButton","count","itemName","itemPluralName","ERROR_NO_TITLE","ERROR_NO_CHATS","loadedActiveChatIds","loadedArchivedChatIds","dispatch","onAddIncludedChats","onAddExcludedChats","editChatFolder","isIncludedChatsListExpanded","setIsIncludedChatsListExpanded","isExcludedChatsListExpanded","setIsExcludedChatsListExpanded","includedChatTypes","excludedChatTypes","visibleIncludedChatIds","visibleExcludedChatIds","allLoadedChatsSet","Set","loadedIncludedChatIds","findIntersectionWithSet","loadedExcludedChatIds","listType","renderChats","visibleChatIds","isExpanded","leftChatsCount","clickHandler","chatType","find","typeKey","inactive","renderChatType","event","folderUpdate","selectedIds","filterValue","onSelectedIdsChange","onSelectedChatTypesChange","onFilterChange","chatTypes","shouldMinimize","hasMaxChats","handleItemClick","newSelectedIds","splice","handleChatTypeClick","newSelectedChatTypes","selectedType","isMinimized","canClose","Checkbox","checked","isSelected","withChatType","orderedPinnedIds","archivedPinnedIds","activeChatArrays","prepareChatList","archivedChatArrays","pinnedChats","otherChats","displayedIds","newFilter","handleSelectedIdsChange","ids","handleSelectedChatTypesChange","newFilters","forEach","handleReset","handleEditFolder","handleAddIncludedChats","handleAddExcludedChats","options","range","handleChange","trackWidth","possibleValuesLength","option","STICKER_SIZE_PICKER_HEADER","stickerSet","observeIntersection","isIntersecting","useIsIntersecting","mediaHash","lottieData","Lottie","shouldRenderFullMedia","useTransitionForMedia","getFirstLetters","hasThumbnail","sticker","noAnimate","onUnfaveClick","localMediaHash","stickerSelector","thumbnail","dataUri","previewBlobUrl","shouldPlay","isAnimated","markLoaded","unmarkLoaded","canAnimatedPlay","shouldRenderThumb","shouldRenderPreview","previewTransitionClassNames","fullClassName","emoji","data-sticker-id","isLowPriority","stickers","firstSticker","STICKER_SIZE_GENERAL_SETTINGS","ANIMATION_LEVEL_OPTIONS","stickerSetIds","added","setIds","stickerSetsById","setsById","messageTextSize","messageSendKeyCombo","shouldAutoDownloadMediaFromContacts","shouldAutoDownloadMediaInPrivateChats","shouldAutoDownloadMediaInGroups","shouldAutoDownloadMediaInChannels","shouldAutoPlayGifs","shouldAutoPlayVideos","shouldSuggestStickers","shouldLoopStickers","setSettingOption","loadStickerSets","loadAddedStickers","stickerSettingsRef","observe","observeIntersectionForCovers","useIntersectionObserver","rootRef","isModalOpen","openModal","closeModal","setSticker","KEYBOARD_SEND_OPTIONS","subLabel","IS_MAC_OS","handleAnimationLevelChange","newLevel","_","handleMessageTextSizeChange","newSize","documentElement","setProperty","handleStickerSetClick","stickerSets","installedDate","RadioGroup","selected","onCheck","isChecked","fromSticker","fileSelector","openSystemFilesDialog","accept","callback","noMultiple","setAttribute","removeAttribute","onchange","click","hex2rgb","param","parseInt","substring","rgb2hex","p0","p1","p2","rgb2hsb","r","g","h","s","v","hsb2rgb","f","p","q","t","getPatternColor","rgbColor","hue","saturation","wallpaper","theme","slug","thumbRef","useCanvasBlur","isDownloadAllowed","setIsDownloadAllowed","fullMedia","wasDownloadDisabled","UPLOADING_WALLPAPER_SLUG","cacheKeyRef","handleSelect","blob","fetchBlob","cacheApi","CUSTOM_BG_CACHE_NAME","background","isBlurred","themes","loadedWallpapers","loadWallpapers","uploadWallpaper","setThemeSettings","themeRef","handleFileSelect","files","handleUploadWallpaper","handleSetColor","handleResetToDefault","backgroundColor","patternColor","DARK_THEME_PATTERN_COLOR","DEFAULT_PATTERN_COLOR","handleWallPaperSelect","currentWallpaper","async","defaultRGB","data","rgb","canvas","context","getContext","preloadImage","naturalHeight","naturalWidth","offsetWidth","drawImage","getImageData","blockSize","getAverageColor","handleWallPaperBlurChange","isUploading","DEFAULT_HSB","PREDEFINED_COLORS","hsb2positions","hsb","rects","colorPosition","colorRect","huePosition","hueRect","positions2hsb","colorPickerRef","huePickerRef","isFirstRunRef","setHsb","getInitialHsb","hsbRef","markIsDragging","unmarkIsDragging","rgbInput","setRgbInput","hexInput","setHexInput","rectsRef","colorCtxRef","offsetLeft","handleColorDrag","handleHueDrag","onCapture","onDrag","onRelease","withCursor","hex","hueHex","w","ctx","imgData","createImageData","pixels","col","perY","st","ed","perX","putImageData","drawColor","drawHue","handleRgbChange","rgbValue","channel","handleHexChange","hexValue","handlePredefinedColorClick","dataset","data-color","hasPrivateChatsNotifications","hasPrivateChatsMessagePreview","hasGroupNotifications","hasGroupMessagePreview","hasBroadcastNotifications","hasBroadcastMessagePreview","hasContactJoinedNotifications","loadNotificationSettings","updateContactSignUpNotification","updateNotificationSettings","handleSettingsChange","peerType","setting","currentIsSilent","currentShouldShowPreviews","shouldShowPreviews","handleContactNotificationChange","hasPassword","privacy","blocked","activeSessions","blockedCount","totalCount","sessionsCount","visibilityPrivacyPhoneNumber","visibility","visibilityPrivacyLastSeen","lastSeen","visibilityPrivacyProfilePhoto","profilePhoto","visibilityPrivacyForwarding","forwards","visibilityPrivacyGroupChats","chatInvite","loadPrivacySettings","loadBlockedContacts","loadAuthorizations","getVisibilityValue","languages","language","loadLanguages","selectedLanguage","setSelectedLanguage","markIsLoading","unmarkIsLoading","langCode","setLanguage","currentLangCode","navigator","toLowerCase","shortLangCode","substr","nativeName","buildOptions","loadingOption","getPrivacyKey","screen","privacySettings","allowUserIds","allowChatIds","blockUserIds","blockChatIds","setPrivacyVisibility","visibilityOptions","exceptionLists","shouldShowDenied","shouldShowAllowed","privacyKey","headerText","descriptionText","allowedContactsScreen","deniedContactsScreen","allowedCount","reduce","result","membersCount","blockCount","handleVisibilityChange","getLocation","session","region","country","getDeviceEnvironment","deviceModel","platform","systemVersion","terminateAuthorization","terminateAllAuthorizations","isConfirmTerminateAllDialogOpen","openConfirmTerminateAllDialog","closeConfirmTerminateAllDialog","handleTerminateSessionClick","hash","handleTerminateAllSessions","currentSession","isCurrent","otherSessions","renderSession","handler","dateActive","appName","ip","sessions","chatsByIds","usersByIds","blockedIds","unblockContact","handleUnblockClick","contactId","viewportOffset","isPrivate","CHAT_HEIGHT_PX","renderContact","animatedEmoji","selectAnimatedEmoji","AnimatedEmoji","expectedPassword","submitLabel","clearError","validationError","setValidationError","shouldShowPassword","setShouldShowPassword","handleSubmit","newPassword","handleClearError","PasswordMonkey","isBig","isPasswordVisible","PasswordForm","onChangePasswordVisibility","onStart","FOCUS_DELAY_TIMEOUT_MS","shouldConfirm","setValue","isConfirmShown","markIsConfirmShown","unmarkIsConfirmShown","codeLength","twoFaSettings","waitingEmailCodeLength","newValue","updatePassword","checkPassword","clearTwoFaError","updateRecoveryEmail","provideTwoFaEmailCode","clearPassword","handleStartWizard","handleNewPassword","handleNewPasswordConfirm","handleNewPasswordHint","handleNewPasswordEmail","onSuccess","handleChangePasswordCurrent","handleChangePasswordNew","handleChangePasswordConfirm","handleChangePasswordHint","handleTurnOff","handleRecoveryEmailCurrentPassword","handleRecoveryEmail","handleEmailCode","code","itemIds","filterPlaceholder","notFoundText","searchInputId","getCurrentPrivacySettings","isAllowList","setPrivacySettings","selectedContactIds","setSearchQuery","isSubmitShown","setIsSubmitShown","newSelectedContactIds","setNewSelectedContactIds","handleSelectedContactIdsChange","contactsIds","foldersState","foldersDispatch","twoFaState","twoFaDispatch","handleSaveFilter","renderCurrentSection","Main","renderCurrentSectionContent","contactIds","resultIds","sortUserIds","forceShowSelf","isSearching","selectedMemberIds","onSelectedMemberIdsChange","onNextStep","setGlobalSearchQuery","handleNextStep","creationProgress","creationError","chatCreation","memberIds","createGroupChat","createChannel","setTitle","about","setAbout","ChatCreationProgress","handleTitleChange","handleDescriptionChange","handleCreateGroup","handleCreateChannel","renderedError","RENDER_COUNT","LeftColumnContent","onContentChange","newChatMemberIds","setNewChatMemberIds","NewChannelStep2","NewGroupStep2","NewChannelStep1","NewGroupStep1","folderType","noChatsText","IGNORED_KEYS","Down","ArrowDown","Up","ArrowUp","ArrowLeft","ArrowRight","PageUp","PageDown","End","Home","Tab","preventDefaultForScrollKeys","disableScrolling","passive","ontouchmove","onkeydown","enableScrolling","getCopyLabel","hasSelection","canImageBeCopied","MessageContextMenu","anchor","canSendNow","canReschedule","canReply","canEdit","canPin","canUnpin","canForward","canFaveSticker","canUnfaveSticker","canCopy","canCopyLink","canSelect","onReply","onEdit","onPin","onFaveSticker","onUnfaveSticker","onSend","onReschedule","onCloseAnimationEnd","onCopyLink","copyOptions","afterEffect","getMessageText","CLIPBOARD_ITEM_SUPPORTED","selection","getSelection","mediaLoader","copyImageToClipboard","anchorNode","parentNode","clipboardText","copyTextToClipboard","getMessageCopyOptions","getTriggerElement","getRootElement","getMenuElement","positionY","useContextMenuPosition","Menu","noOptions","isScheduled","setReplyingToId","setEditingId","faveSticker","unfaveSticker","toggleMessageSelection","sendScheduledMessages","rescheduleMessage","loadMessageLink","isMenuOpen","setIsMenuOpen","setIsDeleteModalOpen","isPinModalOpen","setIsPinModalOpen","isCalendarOpen","openCalendar","closeCalendar","closeMenu","closePinModal","handleCloseCalendar","handleReply","handleEdit","handlePin","handleUnpin","handleFaveSticker","handleUnfaveSticker","handleSelectMessage","params","childMessageIds","withShift","handleScheduledMessageSend","handleOpenCalendar","handleRescheduleMessage","scheduledAt","handleCopyLink","scheduledMaxDate","getDayStartAt","selectStickerSet","stickerSetId","loadStickers","toggleStickerSet","sendMessage","throttleMs","isDisabled","stickerSetAccessHash","isPreloadedGlobally","handleButtonClick","hasCloseButton","STICKER_SIZE_MODAL","isRestricted","isMuted","canDeleteChat","getCanDeleteChat","canSubscribe","canSearch","canMute","canLeave","onSubscribeChannel","onSearchClick","updateChatMutedState","enterMessageSelectMode","handleToggleMuteClick","handleSubscribe","handleSearch","handleSelectMessages","Portal","runDebouncedForSearch","results","selectCurrentTextSearch","isHistoryCalendarOpen","setLocalTextSearchQuery","searchTextMessagesLocal","closeLocalTextSearch","openHistoryCalendar","focusedIndex","setFocusedIndex","visualViewport","mainEl","pageTop","Array","from","input","div","contentEditable","handleMessageSearchQueryChange","newQuery","handleUp","newFocusIndex","handleDown","SearchInput","findInViewport","selectorOrElements","margin","isDense","shouldContainBottom","isHorizontal","viewportY1","viewportY2","allElements","visibleIndexes","isFound","y1","y2","isFullyVisible","onInsertUserName","filteredChatMembers","getSelectedIndex","newIndex","cycleRestrict","selectedMentionIndex","setSelectedMentionIndex","handleArrowKey","handleUserSelect","forceFocus","handleSelectMention","member","onUp","onDown","onTab","first","position","fastSmoothScroll","setItemVisible","prevChatMembers","renderedChatMembers","attachments","caption","canSuggestMembers","groupChatMembers","recentEmojis","onCaptionUpdate","addRecentEmoji","loadEmojiKeywords","onFileAppend","onClear","hideTimeoutRef","prevAttachments","renderingAttachments","isHovered","markHovered","unmarkHovered","isQuick","every","quick","isMentionTooltipOpen","mentionFilter","closeMentionTooltip","insertMention","mentionFilteredMembers","useMentionTooltip","EDITABLE_INPUT_MODAL_ID","isEmojiTooltipOpen","closeEmojiTooltip","filteredEmojis","insertEmoji","useEmojiTooltip","sendAttachments","handleFilesDrop","dataTransfer","newFiles","file","CONTENT_TYPES_FOR_QUICK_UPLOAD","areAllPhotos","mimeType","areAllVideos","renderHeader","onDragEnter","onDrop","onDragOver","onDragLeave","relatedTarget","toTarget","fromTarget","data-attach-description","attachment","File","filename","extension","getFileExtension","previewData","emojis","onEmojiSelect","MessageInput","html","editableInputId","onUpdate","shouldSetFocus","questionInputRef","optionsListRef","solutionRef","question","setQuestion","setOptions","isAnonymous","setIsAnonymous","isMultipleAnswers","setIsMultipleAnswers","isQuizMode","setIsQuizMode","solution","setSolution","correctOption","setCorrectOption","hasErrors","setHasErrors","focusInput","solutionEl","innerHTML","addNewOption","newOptions","list","scrollHeight","scrollTo","behavior","handleCreate","questionTrimmed","optionsTrimmed","o","summary","answers","correct","isPublic","multipleChoice","quiz","entities","parseMessageInput","correctAnswers","solutionEntities","updateOption","removeOption","handleCorrectOptionChange","handleIsAnonymousChange","handleMultipleAnswersChange","handleQuizModeChange","handleKeyPress","keyCode","getQuestionError","getOptionsError","renderOptions","onKeyPress","renderQuizNoOptionError","hidden","closeTimeout","useMouseInside","menuCloseTimeout","isMouseInside","native","names","IS_EMOJI_SUPPORTED","loading","category","allEmojis","useOnIntersect","emojisPerRow","ceil","displayedEmoji","ICONS_BY_CATEGORY","recent","people","nature","foods","activity","places","objects","symbols","flags","categoryIntersections","emojiDataPromise","emojiRawData","emojiData","headerRef","categories","setCategories","setEmojis","activeCategoryIndex","setActiveCategoryIndex","entries","entry","intersectingWithIndexes","newLeft","HEADER_BUTTON_WIDTH","fastSmoothScrollHorizontal","allCategories","themeCategories","unshift","exec","default","uncompressEmoji","ensureEmojiData","selectCategory","categoryEl","handleEmojiSelect","MENU_TRANSITION_DURATION","containerClassName","faded","STICKER_MARGIN","loadAndPlay","onStickerSelect","onStickerUnfave","stickersPerRow","STICKER_SIZE_PICKER","stickerSetIntersections","favorite","recentStickers","favoriteStickers","addedSetIds","canSendStickers","loadRecentStickers","loadFavoriteStickers","addRecentSticker","activeSetIndex","setActiveSetIndex","areAddedLoaded","allSets","noPopulatedSets","set","stickerSetEl","handleStickerSelect","handleStickerUnfave","gif","videoData","shouldRenderVideo","preload","savedGifs","gifs","saved","canSendGifs","onGifSelect","loadSavedGifs","debounceMs","SymbolMenuTabs","SYMBOL_MENU_TAB_TITLES","SYMBOL_MENU_TAB_ICONS","Emoji","Stickers","GIFs","onRemoveSymbol","onSearchOpen","renderTabButton","handleSearchOpen","isActivated","allowedAttachmentOptions","setRecentEmojis","handleMouseEnter","handleMouseLeave","fastRaf","recentEmojisRef","renderContent","isFrom","onMouseEnter","onMouseLeave","noCloseOnBackdrop","onFileSelect","onPollCreate","handleQuickSelect","handleDocumentSelect","canAttachMedia","canAttachPolls","autoClose","forEmoji","clearStickersForEmoji","prevStickers","displayedStickers","clickInlineButton","keyboardButtons","row","button","onSilentSend","onScheduleSend","listEmojis","usePrevDuringAnimation","selectedIndex","setSelectedIndex","emojisCount","handleSelectEmoji","onLeft","onRight","messagesById","foundResults","senderUser","getGlobal","senderChat","forwardInfo","isChannelPost","orderBy","preloadBackwards","LastMessageMeta","selectShouldLoopStickers","isSomeModalOpen","onModalToggle","isAdded","areStickersLoaded","useOnChange","coverStickerIds","covers","otherStickers","handleAddClick","canRenderStickers","STICKER_SIZE_SEARCH","selectCurrentStickerSearch","featured","featuredIds","loadFeaturedStickers","setIsModalOpen","selectCurrentGifSearch","isChatWithBot","selectIsChatWithBot","searchMoreGifs","setGifSearchQuery","getAllowedAttachmentOptions","handleGifClick","hasResults","answer","voters","offsets","pollResults","offset","answerVote","totalVoters","loadPollOptionResults","closePollResults","prevVotersCount","votersCount","setIsLoading","areVotersLoaded","limit","shouldResetVoters","handleViewMoreClick","handleMemberClick","noStatusOrTyping","leftVotersCount","renderViewMoreButton","total","getMessagePoll","resultsByOption","buildCollectionByKey","management","updateContact","deleteUser","deleteHistory","closeManagement","isDeleteDialogOpen","openDeleteDialog","closeDeleteDialog","currentIsMuted","isNotificationsEnabled","setIsNotificationsEnabled","ManagementProgress","handleNotificationChange","handleDeleteContact","withFullInfo","hasLinkedChannel","linkedChatId","isBasicGroup","canChangeInfo","getHasAdminRight","canBanUsers","togglePreHistoryHidden","updateChat","leaveChannel","deleteChannel","currentTitle","currentAbout","imageHash","handleClickEditType","ManagementScreens","ChatPrivacyType","handleClickDiscussion","Discussion","handleClickPermissions","GroupPermissions","handleClickAdministrators","ChatAdministrators","handleSetPhoto","handleAboutChange","handleUpdateGroup","trimmedTitle","trimmedAbout","handleClickMembers","GroupMembers","handleTogglePreHistory","isPreHistoryHidden","isEnabled","enabledPermissionsCount","defaultBannedRights","sendStickers","sendGifs","adminsCount","adminMembers","handleDeleteGroup","isCreator","formatInteger","onChatMemberSelect","updateChatDefaultBannedRights","permissions","setPermissions","havePermissionChanged","setHavePermissionChanged","handleRemovedUsersClick","GroupRemovedUsers","handleAddExceptionClick","GroupUserPermissionsCreate","handleExceptionMemberClick","promotedByUserId","GroupUserPermissions","handlePermissionChange","getUpdatedPermissionValue","handleSavePermissions","bannedRights","removedUsersCount","kickedMembers","exceptionMembers","members","getMemberExceptions","langKey","getLangKeyForBannedRightKey","translatedString","sendMessages","blocking","sendMedia","sendPolls","embedLinks","inviteUsers","pinMessages","changeInfo","updateChatMemberBannedRights","removedMembers","getRemovedBy","kickedByUserId","kickedByUser","getContextActions","isSignaturesShown","toggleSignatures","hasLinkedChat","handleUpdateChannel","handleToggleSignatures","handleClickSubscribers","ChannelSubscribers","handleDeleteChannel","selectManagement","checkPublicLink","updatePublicLink","updatePrivateLink","privateLink","inviteLink","privacyType","setPrivacyType","isRevokeConfirmDialogOpen","openRevokeConfirmDialog","closeRevokeConfirmDialog","canUpdate","handleOptionChange","handleSave","handleRevokePrivateLink","langPrefix1","langPrefix2","SafeLink","forDiscussionIds","linkedChat","loadGroupsForDiscussion","linkDiscussionGroup","unlinkDiscussionGroup","linkedGroupId","setLinkedGroupId","isConfirmUnlinkGroupDialogOpen","openConfirmUnlinkGroupDialog","closeConfirmUnlinkGroupDialog","isConfirmLinkGroupDialogOpen","openConfirmLinkGroupDialog","closeConfirmLinkGroupDialog","handleUnlinkGroupSessions","channelId","Initial","handleLinkGroupSessions","renderLinkGroupHeader","linkedGroup","renderLinkGroupConfirmText","hasPrivateLink","STICKER_SIZE_DISCUSSION_GROUPS","teactFastList","teactOrderKey","isButtonsInOneRow","isPromotedByCurrentUser","isFormFullyDisabled","selectedChatMemberId","isBanConfirmationDialogOpen","openBanConfirmationDialog","closeBanConfirmationDialog","selectedChatMember","handleBanFromGroup","viewMessages","getControlIsDisabled","isOwner","handleAdminMemberClick","ChatAdminRights","getMemberStatus","promotedByUser","GroupRecentActions","updateChatAdmin","setIsTouched","isDismissConfirmationDialogOpen","openDismissConfirmationDialog","closeDismissConfirmationDialog","customTitle","setCustomTitle","adminRights","handleDismissAdmin","memberStatus","handleCustomTitleChange","postMessages","editMessages","banUsers","addAdmins","anonymous","maxLength","openUserInfo","memberId","managementType","selectCurrentManagementType","CURRENCIES","USD","EUR","GBP","JPY","RUB","UAH","INR","AED","getCurrencySign","currency","VISA","MASTERCARD1","MASTERCARD2","CardType","cards","Default","Visa","Mastercard","detectCardType","cardNumber","streetLine1","streetLine2","city","countryIso2","postCode","phone","shipping","cardholder","expiry","cvv","billingCountry","billingZip","saveInfo","saveCredentials","formErrors","getBillingCountry","countryCode","countryList","useFocusAfterAnimation","animationDuration","hasArrow","labelText","htmlFor","needEmail","needPhone","needName","needAddress","phoneRef","selectCountryRef","handleAddress1Change","handleAddress2Change","handleCityChange","handleStateChange","handleCountryChange","handlePostCodeChange","handleFullNameChange","handleEmailChange","handlePhoneChange","handleSaveInfoChange","shippingOptions","handleShippingSelect","amount","renderPaymentItem","main","renderCheckoutItem","invoiceContent","prices","shippingPrices","checkoutInfo","totalPrice","photoUrl","paymentMethod","paymentProvider","shippingAddress","shippingMethod","item","expiryInputRef","charAt","parts","formatCardExpiry","cardNumberRef","cardType","setCardType","newCardType","formatCardNumber","cardIcon","mastercardIconPath","visaIconPath","getCardIcon","canSaveCredentials","needCardholderName","needCountry","needZip","handleCardNumberChange","handleCardholderChange","toUpperCase","handleExpiryChange","handleCvvChange","handleBillingPostCodeChange","handleChangeSaveCredentials","savedInfo","invoice","nativeProvider","nativeParams","passwordMissing","payment","isProviderError","nameRequested","phoneRequested","emailRequested","shippingAddressRequested","flexible","phoneToProvider","emailToProvider","globalErrors","validateRequestedInfo","sendPaymentForm","setPaymentStep","sendCredentialsInfo","clearPaymentError","paymentState","paymentDispatch","currencySign","field","fieldError","getShippingError","handleErrorModalClose","PaymentStep","Checkout","shippingOption","getShippingPrices","totalPrices","concat","acc","cur","getTotalPrice","detectCardTypeText","findShippingOption","getCheckoutInfo","validateRequest","requestInfo","getRequestInfo","sendCredentials","credentials","expiryMonth","expiryYear","zip","getCredentials","sendForm","shippingOptionId","setStep","nextStep","ShippingInfo","Shipping","PaymentInfo","buttonText","cuurentStep","renderModalContent","renderError","optionId","receipt","mapedPrices","info","totalAmount","credentialsTitle","fullAddress","ANIMATED_STICKERS_PATHS","MonkeyIdle","MonkeyTracking","MonkeyClose","MonkeyPeek","FoldersAll","FoldersNew","DiscussionGroups","path","location","cropperResultOptions","quality","format","circle","Croppie","croppiePromise","cropper","isCroppieReady","setIsCroppieReady","imgFile","cropContainer","enableZoom","boundary","viewport","blobToDataUri","bind","err","DEBUG","console","initCropper","ensureCroppie","croppedImg","blobToFile","selectedFile","setSelectedFile","croppedBlobUrl","setCroppedBlobUrl","labelClassName","URL","revokeObjectURL","createObjectURL","SEGMENT_COVER_EYES","SEGMENT_UNCOVER_EYE","SEGMENT_COVER_EYE","STICKER_SIZE","STICKER_SIZE_AUTH_MOBILE","STICKER_SIZE_AUTH","closeMonkeyData","setCloseMonkeyData","peekMonkeyData","setPeekMonkeyData","isFirstMonkeyLoaded","setIsFirstMonkeyLoaded","isPeekShown","setIsPeekShown","handleFirstMonkeyLoad","STICKER_SIZE_TWO_FA","playSegment","onInputChange","setPassword","canSubmit","setCanSubmit","select","autoComplete","MIN_PASSWORD_LENGTH"],"mapp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aAAS,GAgD3C,OA9CAO,YAAU,KACH0F,KACHjM,WAAW,KACTiQ,EAASnD,QAAS0P,SACjB89B,IAEJ,IAEH/zC,YAAU,KACJiY,GACF/e,sBAAsB,KACpBwQ,EAASnD,QAAS0P,QAClBvM,EAASnD,QAASksE,YAGrB,CAACx6D,IAgCF,0BAAMqU,OAAO,GAAGzR,SAblB,SAAsBqgB,GACpBA,EAAMnuB,iBAEFyb,GAIA+pD,GACF13D,EAASyT,IAK6BokD,aAAa,OACnD,yBACEp0E,UAAW0L,YAAe,6BAA8BskB,GAAY,UAAWrW,GAAS,SACxFrZ,IAAKX,EAAK6W,MAAQ,WAAQlV,GAE1B,2BACEiJ,IAAKa,EACLpL,UAAU,eACViG,KAAMovC,EAAoB,OAAS,WACnC13C,GAAG,mBACHwI,MAAO6pB,GAAY,GACnBokD,aAAa,mBACbxoE,SA1CR,SAA0B/J,GACpB8X,GACFg7B,IAGF,MAAM,OAAE3qC,GAAWnI,EACnBmyE,EAAYhqE,EAAO7D,OACnB+tE,EAAalqE,EAAO7D,MAAM3H,QAAU61E,KAChCN,GACFA,EAAc/pE,EAAO7D,QAkCjB7F,IAAI,SAEN,+BAAQqZ,GAASsW,GAAQrX,GACzB,yBACE5Y,UAAU,kBACVC,QAnCR,WACEs1C,GAA4BF,IAmCtBp2B,KAAK,SACLC,SAAU,EACVnF,MAAM,8BAEN,uBAAG/Z,UAAWq1C,EAAoB,WAAa,sBAGlD4+B,GACC,kBAAC,IAAD,CAAQhuE,KAAK,SAASI,QAAM,EAAC6jB,UAAWA,GACrCwqB,O","file":"3.b7d1e22369add742c79e.js","sourcesContent":["import { ApiMessage } from '../../../api/types';\nimport { MediaViewerOrigin } from '../../../types';\n\nimport { ANIMATION_END_DELAY } from '../../../config';\nimport { getMessageContent, getPhotoFullDimensions, getVideoDimensions } from '../../../modules/helpers';\nimport {\n AVATAR_FULL_DIMENSIONS,\n calculateDimensions,\n getMediaViewerAvailableDimensions,\n MEDIA_VIEWER_MEDIA_QUERY,\n REM,\n} from '../../common/helpers/mediaDimensions';\n\nimport windowSize from '../../../util/windowSize';\n\nconst ANIMATION_DURATION = 200;\n\nexport function animateOpening(\n hasFooter: boolean, origin: MediaViewerOrigin, bestImageData: string, message?: ApiMessage,\n) {\n const { mediaEl: fromImage } = getNodes(origin, message);\n if (!fromImage) {\n return;\n }\n\n const { width: windowWidth } = windowSize.get();\n\n let isVideo = false;\n let mediaSize;\n if (message) {\n const { photo, video, webPage } = getMessageContent(message);\n isVideo = Boolean(video);\n mediaSize = video ? getVideoDimensions(video)! : getPhotoFullDimensions((photo || webPage!.photo)!)!;\n } else {\n mediaSize = AVATAR_FULL_DIMENSIONS;\n }\n\n // eslint-disable-next-line max-len\n const {\n width: availableWidth, height: availableHeight,\n } = getMediaViewerAvailableDimensions(hasFooter, isVideo);\n const { width: toWidth, height: toHeight } = calculateDimensions(\n availableWidth, availableHeight, mediaSize.width, mediaSize.height,\n );\n const toLeft = (windowWidth - toWidth) / 2;\n const toTop = getTopOffset(hasFooter) + (availableHeight - toHeight) / 2;\n\n let {\n top: fromTop, left: fromLeft, width: fromWidth, height: fromHeight,\n } = fromImage.getBoundingClientRect();\n\n if ([\n MediaViewerOrigin.SharedMedia,\n MediaViewerOrigin.Album,\n MediaViewerOrigin.ScheduledAlbum,\n MediaViewerOrigin.SearchResult,\n ].includes(origin)) {\n const uncovered = uncover(toWidth, toHeight, fromTop, fromLeft, fromWidth, fromHeight);\n fromTop = uncovered.top;\n fromLeft = uncovered.left;\n fromWidth = uncovered.width;\n fromHeight = uncovered.height;\n }\n\n const fromTranslateX = (fromLeft + fromWidth / 2) - (toLeft + toWidth / 2);\n const fromTranslateY = (fromTop + fromHeight / 2) - (toTop + toHeight / 2);\n const fromScaleX = fromWidth / toWidth;\n const fromScaleY = fromHeight / toHeight;\n\n const ghost = createGhost(bestImageData || fromImage);\n applyStyles(ghost, {\n top: `${toTop}px`,\n left: `${toLeft}px`,\n width: `${toWidth}px`,\n height: `${toHeight}px`,\n transform: `translate3d(${fromTranslateX}px, ${fromTranslateY}px, 0) scale(${fromScaleX}, ${fromScaleY})`,\n });\n applyShape(ghost, origin);\n\n document.body.classList.add('ghost-animating');\n\n requestAnimationFrame(() => {\n document.body.appendChild(ghost);\n\n requestAnimationFrame(() => {\n ghost.style.transform = '';\n clearShape(ghost);\n\n setTimeout(() => {\n requestAnimationFrame(() => {\n if (document.body.contains(ghost)) {\n document.body.removeChild(ghost);\n }\n document.body.classList.remove('ghost-animating');\n });\n }, ANIMATION_DURATION + ANIMATION_END_DELAY);\n });\n });\n}\n\nexport function animateClosing(origin: MediaViewerOrigin, bestImageData: string, message?: ApiMessage) {\n const { container, mediaEl: toImage } = getNodes(origin, message);\n if (!toImage) {\n return;\n }\n\n const fromImage = document.getElementById('MediaViewer')!.querySelector<HTMLImageElement>(\n '.active .media-viewer-content img, .active .media-viewer-content video',\n );\n if (!fromImage || !toImage) {\n return;\n }\n\n const {\n top: fromTop, left: fromLeft, width: fromWidth, height: fromHeight,\n } = fromImage.getBoundingClientRect();\n const {\n top: targetTop, left: toLeft, width: toWidth, height: toHeight,\n } = toImage.getBoundingClientRect();\n\n let toTop = targetTop;\n if (!isElementInViewport(container)) {\n const { height: windowHeight } = windowSize.get();\n toTop = targetTop < fromTop ? -toHeight : windowHeight;\n }\n\n const fromTranslateX = (fromLeft + fromWidth / 2) - (toLeft + toWidth / 2);\n const fromTranslateY = (fromTop + fromHeight / 2) - (toTop + toHeight / 2);\n let fromScaleX = fromWidth / toWidth;\n let fromScaleY = fromHeight / toHeight;\n\n const shouldFadeOut = (\n [MediaViewerOrigin.Inline, MediaViewerOrigin.ScheduledInline].includes(origin)\n && !isMessageImageFullyVisible(container, toImage)\n ) || (\n [MediaViewerOrigin.Album, MediaViewerOrigin.ScheduledAlbum].includes(origin)\n && !isMessageImageFullyVisible(container, toImage)\n );\n\n if ([\n MediaViewerOrigin.SharedMedia,\n MediaViewerOrigin.Album,\n MediaViewerOrigin.ScheduledAlbum,\n MediaViewerOrigin.SearchResult,\n ].includes(origin)) {\n if (fromScaleX > fromScaleY) {\n fromScaleX = fromScaleY;\n } else if (fromScaleY > fromScaleX) {\n fromScaleY = fromScaleX;\n }\n }\n\n const existingGhost = document.getElementsByClassName('ghost')[0] as HTMLDivElement;\n\n const ghost = existingGhost || createGhost(bestImageData || toImage, origin === MediaViewerOrigin.ProfileAvatar);\n if (!existingGhost) {\n applyStyles(ghost, {\n top: `${toTop}px`,\n left: `${toLeft}px`,\n width: `${toWidth}px`,\n height: `${toHeight}px`,\n transform: `translate3d(${fromTranslateX}px, ${fromTranslateY}px, 0) scale(${fromScaleX}, ${fromScaleY})`,\n });\n }\n\n requestAnimationFrame(() => {\n if (existingGhost) {\n const {\n top,\n left,\n width,\n height,\n } = existingGhost.getBoundingClientRect();\n const scaleX = width / toWidth;\n const scaleY = height / toHeight;\n\n applyStyles(ghost, {\n transition: 'none',\n top: `${toTop}px`,\n left: `${toLeft}px`,\n transformOrigin: 'top left',\n transform: `translate3d(${left - toLeft}px, ${top - toTop}px, 0) scale(${scaleX}, ${scaleY})`,\n width: `${toWidth}px`,\n height: `${toHeight}px`,\n });\n }\n document.body.classList.add('ghost-animating');\n if (!existingGhost) document.body.appendChild(ghost);\n\n requestAnimationFrame(() => {\n if (existingGhost) {\n existingGhost.style.transition = '';\n }\n\n ghost.style.transform = '';\n\n if (shouldFadeOut) {\n ghost.style.opacity = '0';\n }\n\n applyShape(ghost, origin);\n\n setTimeout(() => {\n requestAnimationFrame(() => {\n if (document.body.contains(ghost)) {\n document.body.removeChild(ghost);\n }\n document.body.classList.remove('ghost-animating');\n });\n }, ANIMATION_DURATION + ANIMATION_END_DELAY);\n });\n });\n}\n\nfunction createGhost(source: string | HTMLImageElement | HTMLVideoElement, shouldAppendProfileInfo = false) {\n const ghost = document.createElement('div');\n ghost.classList.add('ghost');\n\n const img = new Image();\n\n if (typeof source === 'string') {\n img.src = source;\n } else if (source instanceof HTMLVideoElement) {\n img.src = source.poster;\n } else {\n img.src = source.src;\n }\n\n ghost.appendChild(img);\n\n if (shouldAppendProfileInfo) {\n ghost.classList.add('ProfileInfo');\n const profileInfo = document.querySelector('#RightColumn .ProfileInfo .info');\n if (profileInfo) {\n ghost.appendChild(profileInfo.cloneNode(true));\n }\n }\n\n return ghost;\n}\n\nfunction uncover(realWidth: number, realHeight: number, top: number, left: number, width: number, height: number) {\n if (realWidth === realHeight) {\n const size = Math.max(width, height) * (realWidth / realHeight);\n left -= (size - width) / 2;\n top -= (size - height) / 2;\n width = size;\n height = size;\n } else if (realWidth > realHeight) {\n const srcWidth = width;\n width = height * (realWidth / realHeight);\n left -= (width - srcWidth) / 2;\n } else if (realHeight > realWidth) {\n const srcHeight = height;\n height = width * (realHeight / realWidth);\n top -= (height - srcHeight) / 2;\n }\n\n return {\n top, left, width, height,\n };\n}\n\nfunction isElementInViewport(el: HTMLElement) {\n if (el.style.display === 'none') {\n return false;\n }\n\n const rect = el.getBoundingClientRect();\n const { height: windowHeight } = windowSize.get();\n\n return (rect.top <= windowHeight) && ((rect.top + rect.height) >= 0);\n}\n\nfunction isMessageImageFullyVisible(container: HTMLElement, imageEl: HTMLElement) {\n const messageListElement = document.querySelector<HTMLDivElement>('.active > .MessageList')!;\n let imgOffsetTop = container.offsetTop + imageEl.closest<HTMLDivElement>('.content-inner, .WebPage')!.offsetTop;\n if (container.id.includes('album-media-')) {\n imgOffsetTop += container.parentElement!.offsetTop + container.closest<HTMLDivElement>('.Message')!.offsetTop;\n }\n\n return imgOffsetTop > messageListElement.scrollTop\n && imgOffsetTop + imageEl.offsetHeight < messageListElement.scrollTop + messageListElement.offsetHeight;\n}\n\nfunction getTopOffset(hasFooter: boolean) {\n const mql = window.matchMedia(MEDIA_VIEWER_MEDIA_QUERY);\n let topOffsetRem = 4.125;\n if (hasFooter) {\n topOffsetRem += mql.matches ? 0.875 : 3.375;\n }\n\n return topOffsetRem * REM;\n}\n\nfunction applyStyles(element: HTMLElement, styles: Record<string, string>) {\n Object.assign(element.style, styles);\n}\n\nfunction getNodes(origin: MediaViewerOrigin, message?: ApiMessage) {\n let containerSelector;\n let mediaSelector;\n\n switch (origin) {\n case MediaViewerOrigin.Album:\n case MediaViewerOrigin.ScheduledAlbum:\n containerSelector = `.active > .MessageList #album-media-${message!.id}`;\n mediaSelector = '.full-media';\n break;\n\n case MediaViewerOrigin.SharedMedia:\n containerSelector = `#shared-media${message!.id}`;\n mediaSelector = 'img';\n break;\n\n case MediaViewerOrigin.SearchResult:\n containerSelector = `#search-media${message!.id}`;\n mediaSelector = 'img';\n break;\n\n case MediaViewerOrigin.MiddleHeaderAvatar:\n containerSelector = '.MiddleHeader .ChatInfo .Avatar';\n mediaSelector = 'img.avatar-media';\n break;\n\n case MediaViewerOrigin.ProfileAvatar:\n containerSelector = '#RightColumn .ProfileInfo .active .ProfilePhoto';\n mediaSelector = 'img.avatar-media';\n break;\n\n case MediaViewerOrigin.ScheduledInline:\n case MediaViewerOrigin.Inline:\n default:\n containerSelector = `.active > .MessageList #message${message!.id}`;\n mediaSelector = '.message-content .full-media, .message-content .thumbnail';\n }\n\n const container = document.querySelector<HTMLElement>(containerSelector)!;\n const mediaEls = container && container.querySelectorAll<HTMLImageElement | HTMLVideoElement>(mediaSelector);\n\n return {\n container,\n mediaEl: mediaEls && mediaEls[mediaEls.length - 1],\n };\n}\n\nfunction applyShape(ghost: HTMLDivElement, origin: MediaViewerOrigin) {\n switch (origin) {\n case MediaViewerOrigin.Album:\n case MediaViewerOrigin.ScheduledAlbum:\n case MediaViewerOrigin.Inline:\n case MediaViewerOrigin.ScheduledInline:\n ghost.classList.add('rounded-corners');\n break;\n\n case MediaViewerOrigin.SharedMedia:\n case MediaViewerOrigin.ProfileAvatar:\n case MediaViewerOrigin.SearchResult:\n (ghost.firstChild as HTMLElement).style.objectFit = 'cover';\n break;\n\n case MediaViewerOrigin.MiddleHeaderAvatar:\n ghost.classList.add('circle');\n break;\n }\n}\n\nfunction clearShape(ghost: HTMLDivElement) {\n (ghost.firstChild as HTMLElement).style.objectFit = 'default';\n ghost.classList.remove('rounded-corners', 'circle');\n}\n","import React, { FC, useCallback } from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../global/types';\nimport { ApiChat, ApiMessage, ApiUser } from '../../api/types';\n\nimport { getSenderTitle, isChatPrivate } from '../../modules/helpers';\nimport { formatMediaDateTime } from '../../util/dateFormat';\nimport renderText from '../common/helpers/renderText';\nimport {\n selectChat,\n selectChatMessage,\n selectSender,\n selectUser,\n} from '../../modules/selectors';\nimport { pick } from '../../util/iteratees';\nimport useLang from '../../hooks/useLang';\n\nimport Avatar from '../common/Avatar';\n\nimport './SenderInfo.scss';\n\ntype OwnProps = {\n chatId?: number;\n messageId?: number;\n isAvatar?: boolean;\n};\n\ntype StateProps = {\n sender?: ApiUser | ApiChat;\n message?: ApiMessage;\n};\n\ntype DispatchProps = Pick<GlobalActions, 'closeMediaViewer' | 'focusMessage'>;\n\nconst SenderInfo: FC<OwnProps & StateProps & DispatchProps> = ({\n chatId, messageId, sender, isAvatar, message, closeMediaViewer, focusMessage,\n}) => {\n const handleFocusMessage = useCallback(() => {\n closeMediaViewer();\n focusMessage({ chatId, messageId });\n }, [chatId, focusMessage, messageId, closeMediaViewer]);\n\n const lang = useLang();\n\n if (!sender || (!message && !isAvatar)) {\n return undefined;\n }\n\n const isFromChat = sender.id < 0;\n const senderTitle = getSenderTitle(lang, sender);\n\n return (\n <div className=\"SenderInfo\" onClick={handleFocusMessage}>\n {isFromChat ? (\n <Avatar key={sender.id} size=\"medium\" chat={sender as ApiChat} />\n ) : (\n <Avatar key={sender.id} size=\"medium\" user={sender as ApiUser} />\n )}\n <div className=\"meta\">\n <div className=\"title\" dir=\"auto\">\n {senderTitle && renderText(senderTitle)}\n </div>\n <div className=\"date\" dir=\"auto\">\n {isAvatar ? lang('lng_mediaview_profile_photo') : formatMediaDateTime(lang, message!.date * 1000)}\n </div>\n </div>\n </div>\n );\n};\n\nexport default withGlobal<OwnProps>(\n (global, { chatId, messageId, isAvatar }): StateProps => {\n if (isAvatar && chatId) {\n return {\n sender: isChatPrivate(chatId) ? selectUser(global, chatId) : selectChat(global, chatId),\n };\n }\n\n if (!messageId || !chatId) {\n return {};\n }\n\n const message = selectChatMessage(global, chatId, messageId);\n\n return {\n message,\n sender: message && selectSender(global, message),\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, ['closeMediaViewer', 'focusMessage']),\n)(SenderInfo);\n","import React, {\n FC, useCallback, useEffect, useMemo, useState,\n} from '../../lib/teact/teact';\n\nimport { ApiMessage } from '../../api/types';\n\nimport { IS_MOBILE_SCREEN } from '../../util/environment';\nimport download from '../../util/download';\nimport { getMessageMediaHash } from '../../modules/helpers';\nimport useMediaWithDownloadProgress from '../../hooks/useMediaWithDownloadProgress';\nimport useLang from '../../hooks/useLang';\n\nimport Button from '../ui/Button';\nimport DropdownMenu from '../ui/DropdownMenu';\nimport MenuItem from '../ui/MenuItem';\nimport ProgressSpinner from '../ui/ProgressSpinner';\n\nimport './MediaViewerActions.scss';\n\ntype OwnProps = {\n mediaData?: string;\n isVideo: boolean;\n isZoomed: boolean;\n message?: ApiMessage;\n fileName?: string;\n isAvatar?: boolean;\n onCloseMediaViewer: NoneToVoidFunction;\n onForward: NoneToVoidFunction;\n onZoomToggle: NoneToVoidFunction;\n};\n\nconst MediaViewerActions: FC<OwnProps> = ({\n mediaData,\n isVideo,\n isZoomed,\n message,\n fileName,\n isAvatar,\n onCloseMediaViewer,\n onForward,\n onZoomToggle,\n}) => {\n const [isVideoDownloadAllowed, setIsVideoDownloadAllowed] = useState(false);\n const videoMediaHash = isVideo && message ? getMessageMediaHash(message, 'download') : undefined;\n const {\n mediaData: videoBlobUrl, downloadProgress,\n } = useMediaWithDownloadProgress(videoMediaHash, !isVideoDownloadAllowed);\n\n // Download with browser when fully loaded\n useEffect(() => {\n if (isVideoDownloadAllowed && videoBlobUrl) {\n download(videoBlobUrl, fileName!);\n setIsVideoDownloadAllowed(false);\n }\n }, [fileName, videoBlobUrl, isVideoDownloadAllowed]);\n\n // Cancel download on slide change\n useEffect(() => {\n setIsVideoDownloadAllowed(false);\n }, [videoMediaHash]);\n\n const handleVideoDownloadClick = useCallback((e: React.SyntheticEvent<HTMLElement>) => {\n e.stopPropagation();\n setIsVideoDownloadAllowed((isAllowed) => !isAllowed);\n }, []);\n\n const lang = useLang();\n\n const MenuButton: FC<{ onTrigger: () => void; isOpen?: boolean }> = useMemo(() => {\n return ({ onTrigger, isOpen }) => (\n <Button\n round\n size=\"smaller\"\n color=\"translucent\"\n className={isOpen ? 'active' : undefined}\n onClick={onTrigger}\n ariaLabel=\"More actions\"\n >\n <i className=\"icon-more\" />\n </Button>\n );\n }, []);\n\n if (IS_MOBILE_SCREEN) {\n return (\n <div className=\"MediaViewerActions-mobile\">\n <DropdownMenu\n trigger={MenuButton}\n positionX=\"right\"\n >\n {!isAvatar && (\n <MenuItem\n icon=\"forward\"\n onClick={onForward}\n >\n {lang('Forward')}\n </MenuItem>\n )}\n {isVideo ? (\n <MenuItem\n icon={isVideoDownloadAllowed ? 'close' : 'download'}\n onClick={handleVideoDownloadClick}\n >\n {isVideoDownloadAllowed ? `${Math.round(downloadProgress * 100)}% Downloading...` : 'Download'}\n </MenuItem>\n ) : (\n <MenuItem\n icon=\"download\"\n href={mediaData}\n download={fileName}\n >\n {lang('AccActionDownload')}\n </MenuItem>\n )}\n </DropdownMenu>\n {isVideoDownloadAllowed && <ProgressSpinner progress={downloadProgress} size=\"s\" noCross />}\n </div>\n );\n }\n\n return (\n <div className=\"MediaViewerActions\">\n {!isAvatar && (\n <>\n <Button\n round\n size=\"smaller\"\n color=\"translucent-white\"\n ariaLabel={lang('Forward')}\n onClick={onForward}\n >\n <i className=\"icon-forward\" />\n </Button>\n </>\n )}\n {isVideo ? (\n <Button\n round\n size=\"smaller\"\n color=\"translucent-white\"\n ariaLabel={lang('AccActionDownload')}\n onClick={handleVideoDownloadClick}\n >\n {isVideoDownloadAllowed ? (\n <ProgressSpinner progress={downloadProgress} size=\"s\" onClick={handleVideoDownloadClick} />\n ) : (\n <i className=\"icon-download\" />\n )}\n </Button>\n ) : (\n <Button\n href={mediaData}\n download={fileName}\n round\n size=\"smaller\"\n color=\"translucent-white\"\n ariaLabel={lang('AccActionDownload')}\n >\n <i className=\"icon-download\" />\n </Button>\n )}\n <Button\n round\n size=\"smaller\"\n color=\"translucent-white\"\n ariaLabel={isZoomed ? 'Zoom Out' : 'Zoom In'}\n onClick={onZoomToggle}\n >\n <i className={isZoomed ? 'icon-zoom-out' : 'icon-zoom-in'} />\n </Button>\n <Button\n round\n size=\"smaller\"\n color=\"translucent-white\"\n ariaLabel={lang('Close')}\n onClick={onCloseMediaViewer}\n >\n <i className=\"icon-close\" />\n </Button>\n </div>\n );\n};\n\nexport default MediaViewerActions;\n","import React, { FC, useEffect, useState } from '../../lib/teact/teact';\nimport { throttle } from '../../util/schedulers';\nimport { TextPart } from '../common/helpers/renderMessageText';\nimport { REM } from '../common/helpers/mediaDimensions';\n\nimport './MediaViewerFooter.scss';\n\nconst RESIZE_THROTTLE_MS = 500;\n\ntype OwnProps = {\n text: TextPart | TextPart[];\n onClick: () => void;\n isHideable: boolean;\n};\n\nconst MediaViewerFooter: FC<OwnProps> = ({ text = '', isHideable, onClick }) => {\n const [isMultiline, setIsMultiline] = useState(false);\n useEffect(() => {\n const footerContent = document.querySelector('.MediaViewerFooter .media-text') as HTMLDivElement | null;\n\n const checkIsMultiline = () => {\n const height = footerContent ? footerContent.clientHeight : 0;\n\n setIsMultiline(height > REM * 2);\n };\n\n // First run for initial detection of multiline footer text\n checkIsMultiline();\n\n const handleResize = throttle(checkIsMultiline, RESIZE_THROTTLE_MS, true);\n\n window.addEventListener('resize', handleResize, false);\n\n return () => {\n window.removeEventListener('resize', handleResize, false);\n };\n }, []);\n\n function stopEvent(e: React.MouseEvent<HTMLDivElement, MouseEvent>) {\n if (text) {\n e.stopPropagation();\n }\n }\n\n return (\n <div className={`MediaViewerFooter ${isHideable ? 'hideable' : ''}`} onClick={stopEvent}>\n {text && (\n <div className=\"media-viewer-footer-content\" onClick={onClick}>\n <p className={`media-text custom-scroll ${isMultiline ? 'multiline' : ''}`} dir=\"auto\">{text}</p>\n </div>\n )}\n </div>\n );\n};\n\nexport default MediaViewerFooter;\n","import { useLayoutEffect, useState } from '../lib/teact/teact';\nimport { PLATFORM_ENV } from '../util/environment';\n\ntype RefType = {\n current: HTMLElement | null;\n};\n\ntype ReturnType = [boolean, () => void, () => void] | [false];\ntype CallbackType = (isPlayed: boolean) => void;\n\nconst prop = getBrowserFullscreenElementProp();\n\nexport default function useFullscreenStatus(elRef: RefType, setIsPlayed: CallbackType): ReturnType {\n const [isFullscreen, setIsFullscreen] = useState(Boolean(prop && document[prop]));\n\n const setFullscreen = () => {\n if (!elRef.current || !(prop || PLATFORM_ENV === 'iOS')) {\n return;\n }\n\n if (elRef.current.requestFullscreen) {\n elRef.current.requestFullscreen();\n } else if (elRef.current.webkitRequestFullscreen) {\n elRef.current.webkitRequestFullscreen();\n } else if (elRef.current.webkitEnterFullscreen) {\n elRef.current.webkitEnterFullscreen();\n } else if (elRef.current.mozRequestFullScreen) {\n elRef.current.mozRequestFullScreen();\n }\n\n setIsFullscreen(true);\n };\n\n const exitFullscreen = () => {\n if (!elRef.current) {\n return;\n }\n\n if (document.exitFullscreen) {\n document.exitFullscreen();\n } else if (document.mozCancelFullScreen) {\n document.mozCancelFullScreen();\n } else if (document.webkitCancelFullScreen) {\n document.webkitCancelFullScreen();\n } else if (document.webkitExitFullscreen) {\n document.webkitExitFullscreen();\n }\n\n setIsFullscreen(false);\n };\n\n useLayoutEffect(() => {\n const listener = () => { setIsFullscreen(Boolean(prop && document[prop])); };\n const listenerEnter = () => { setIsFullscreen(true); };\n const listenerExit = () => {\n setIsFullscreen(false);\n setIsPlayed(false);\n };\n const video = elRef.current;\n\n document.addEventListener('fullscreenchange', listener, false);\n document.addEventListener('webkitfullscreenchange', listener, false);\n document.addEventListener('mozfullscreenchange', listener, false);\n\n if (video) {\n video.addEventListener('webkitbeginfullscreen', listenerEnter, false);\n video.addEventListener('webkitendfullscreen', listenerExit, false);\n }\n\n return () => {\n document.removeEventListener('fullscreenchange', listener, false);\n document.removeEventListener('webkitfullscreenchange', listener, false);\n document.removeEventListener('mozfullscreenchange', listener, false);\n if (video) {\n video.removeEventListener('webkitbeginfullscreen', listenerEnter, false);\n video.removeEventListener('webkitendfullscreen', listenerExit, false);\n }\n };\n // eslint-disable-next-line\n }, []);\n\n if (!prop && PLATFORM_ENV !== 'iOS') {\n return [false];\n }\n\n return [isFullscreen, setFullscreen, exitFullscreen];\n}\n\nfunction getBrowserFullscreenElementProp() {\n if (typeof document.fullscreenElement !== 'undefined') {\n return 'fullscreenElement';\n } else if (typeof document.mozFullScreenElement !== 'undefined') {\n return 'mozFullScreenElement';\n } else if (typeof document.webkitFullscreenElement !== 'undefined') {\n return 'webkitFullscreenElement';\n }\n\n return '';\n}\n","const units = ['bytes', 'kB', 'MB', 'GB', 'TB', 'PB'];\n\nexport default (bytes: number) => {\n const number = bytes === 0 ? 0 : Math.floor(Math.log(bytes) / Math.log(1024));\n\n return `${(bytes / 1024 ** Math.floor(number)).toFixed(1)} ${units[number]}`;\n};\n","import React, { FC, useState, useEffect } from '../../lib/teact/teact';\n\nimport { IS_MOBILE_SCREEN } from '../../util/environment';\nimport { formatMediaDuration } from '../../util/dateFormat';\nimport formatFileSize from './helpers/formatFileSize';\nimport useLang from '../../hooks/useLang';\n\nimport Button from '../ui/Button';\n\nimport './VideoPlayerControls.scss';\n\ntype IProps = {\n bufferedProgress: number;\n currentTime: number;\n duration: number;\n fileSize: number;\n isForceVisible: boolean;\n isForceMobileVersion?: boolean;\n isPlayed: boolean;\n isFullscreenSupported: boolean;\n isFullscreen: boolean;\n onChangeFullscreen: (e: React.MouseEvent<HTMLButtonElement, MouseEvent>) => void;\n onPlayPause: (e: React.MouseEvent<HTMLButtonElement, MouseEvent>) => void;\n onSeek: OnChangeHandler;\n};\n\ntype OnChangeHandler = (e: React.ChangeEvent<HTMLInputElement>) => void;\n\nconst stopEvent = (e: React.MouseEvent<HTMLElement>) => {\n e.stopPropagation();\n};\n\nconst HIDE_CONTROLS_TIMEOUT_MS = 800;\n\nconst VideoPlayerControls: FC<IProps> = ({\n bufferedProgress,\n currentTime,\n duration,\n fileSize,\n isForceVisible,\n isForceMobileVersion,\n isPlayed,\n isFullscreenSupported,\n isFullscreen,\n onChangeFullscreen,\n onPlayPause,\n onSeek,\n}) => {\n const [isVisible, setVisibility] = useState(true);\n\n useEffect(() => {\n if (isForceVisible) {\n setVisibility(isForceVisible);\n }\n }, [isForceVisible]);\n\n useEffect(() => {\n let timeout: number | undefined;\n\n if (!isForceVisible) {\n if (IS_MOBILE_SCREEN) {\n setVisibility(false);\n } else {\n timeout = window.setTimeout(() => {\n setVisibility(false);\n }, HIDE_CONTROLS_TIMEOUT_MS);\n }\n }\n\n return () => {\n if (timeout) {\n window.clearTimeout(timeout);\n }\n };\n }, [isForceVisible]);\n\n useEffect(() => {\n if (isVisible || isForceVisible) {\n document.body.classList.add('video-controls-visible');\n }\n\n return () => {\n document.body.classList.remove('video-controls-visible');\n };\n }, [isForceVisible, isVisible]);\n\n const lang = useLang();\n\n if (!isVisible && !isForceVisible) {\n return undefined;\n }\n\n return (\n <div className={`VideoPlayerControls ${isForceMobileVersion ? 'mobile' : ''}`} onClick={stopEvent}>\n {renderSeekLine(currentTime, duration, bufferedProgress, onSeek)}\n <Button\n ariaLabel={lang('AccActionPlay')}\n size=\"tiny\"\n ripple={!IS_MOBILE_SCREEN}\n color=\"translucent-white\"\n className=\"play\"\n onClick={onPlayPause}\n >\n <i className={isPlayed ? 'icon-pause' : 'icon-play'} />\n </Button>\n {renderTime(currentTime, duration)}\n {bufferedProgress < 1 && renderFileSize(bufferedProgress, fileSize)}\n {isFullscreenSupported && (\n <Button\n ariaLabel=\"Fullscreen\"\n size=\"tiny\"\n color=\"translucent-white\"\n className=\"fullscreen\"\n onClick={onChangeFullscreen}\n >\n <i className={`${isFullscreen ? 'icon-smallscreen' : 'icon-fullscreen'}`} />\n </Button>\n )}\n </div>\n );\n};\n\nfunction renderTime(currentTime: number, duration: number) {\n return (\n <div className=\"player-time\">\n {`${formatMediaDuration(currentTime)} / ${formatMediaDuration(duration)}`}\n </div>\n );\n}\n\nfunction renderFileSize(downloadedPercent: number, totalSize: number) {\n return (\n <div className=\"player-file-size\">\n {`${formatFileSize(totalSize * downloadedPercent)} / ${formatFileSize(totalSize)}`}\n </div>\n );\n}\n\nfunction renderSeekLine(currentTime: number, duration: number, bufferedProgress: number, onSeek: OnChangeHandler) {\n const percentagePlayed = (currentTime / duration) * 100;\n const percentageBuffered = bufferedProgress * 100;\n\n return (\n <div className=\"player-seekline\">\n <div className=\"player-seekline-track\">\n <div\n className=\"player-seekline-buffered\"\n // @ts-ignore teact feature\n style={`width: ${percentageBuffered || 0}%`}\n />\n <div\n className=\"player-seekline-played\"\n // @ts-ignore teact feature\n style={`width: ${percentagePlayed || 0}%`}\n />\n <input\n min=\"0\"\n max=\"100\"\n step={0.01}\n type=\"range\"\n onInput={onSeek}\n className=\"player-seekline-input\"\n value={percentagePlayed || 0}\n />\n </div>\n </div>\n );\n}\n\nexport default VideoPlayerControls;\n","import React, {\n FC, memo, useCallback, useEffect, useRef, useState,\n} from '../../lib/teact/teact';\n\nimport { IDimensions } from '../../modules/helpers';\n\nimport { IS_IOS, IS_MOBILE_SCREEN, IS_TOUCH_ENV } from '../../util/environment';\nimport useShowTransition from '../../hooks/useShowTransition';\nimport useBuffering from '../../hooks/useBuffering';\nimport useFullscreenStatus from '../../hooks/useFullscreen';\nimport useVideoCleanup from '../../hooks/useVideoCleanup';\nimport safePlay from '../../util/safePlay';\n\nimport VideoPlayerControls from './VideoPlayerControls';\nimport ProgressSpinner from '../ui/ProgressSpinner';\n\nimport './VideoPlayer.scss';\n\ntype OwnProps = {\n url?: string;\n isGif?: boolean;\n posterData?: string;\n posterSize?: IDimensions;\n downloadProgress?: number;\n fileSize: number;\n isMediaViewerOpen?: boolean;\n noPlay?: boolean;\n onClose: (e: React.MouseEvent<HTMLElement, MouseEvent>) => void;\n};\n\nconst MOBILE_VERSION_CONTROL_WIDTH = 400;\n\nconst VideoPlayer: FC<OwnProps> = ({\n url,\n isGif,\n posterData,\n posterSize,\n downloadProgress,\n fileSize,\n isMediaViewerOpen,\n noPlay,\n onClose,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const videoRef = useRef<HTMLVideoElement>(null);\n const [isPlayed, setIsPlayed] = useState(!IS_TOUCH_ENV || !IS_IOS);\n const [currentTime, setCurrentTime] = useState(0);\n const [isControlsVisible, setIsControlsVisible] = useState(true);\n\n const [isFullscreen, setFullscreen, exitFullscreen] = useFullscreenStatus(videoRef, setIsPlayed);\n\n const { isBuffered, bufferedProgress, bufferingHandlers } = useBuffering();\n const {\n shouldRender: shouldRenderSpinner,\n transitionClassNames: spinnerClassNames,\n } = useShowTransition(!isBuffered, undefined, undefined, 'slow');\n\n useEffect(() => {\n if (noPlay || !isMediaViewerOpen) {\n videoRef.current!.pause();\n } else if (url && !IS_TOUCH_ENV) {\n // Chrome does not automatically start playing when `url` becomes available (even with `autoPlay`),\n // so we force it here. Contrary, iOS does not allow to call `play` without mouse event,\n // so we need to use `autoPlay` instead to allow pre-buffering.\n safePlay(videoRef.current!);\n }\n }, [noPlay, isMediaViewerOpen, url]);\n\n useEffect(() => {\n if (videoRef.current!.currentTime === videoRef.current!.duration) {\n setCurrentTime(0);\n setIsPlayed(false);\n } else {\n setCurrentTime(videoRef.current!.currentTime);\n }\n }, [currentTime]);\n\n const togglePlayState = useCallback((e: React.MouseEvent<HTMLElement, MouseEvent> | KeyboardEvent) => {\n e.stopPropagation();\n if (isPlayed) {\n videoRef.current!.pause();\n setIsPlayed(false);\n } else {\n videoRef.current!.play();\n setIsPlayed(true);\n }\n }, [isPlayed]);\n\n useVideoCleanup(videoRef, []);\n\n const handleMouseOver = useCallback(() => {\n setIsControlsVisible(true);\n }, []);\n\n const handleMouseOut = useCallback(() => {\n setIsControlsVisible(false);\n }, []);\n\n const handleTimeUpdate = useCallback((e: React.SyntheticEvent<HTMLVideoElement>) => {\n setCurrentTime(e.currentTarget.currentTime);\n }, []);\n\n const handleEnded = useCallback(() => {\n setCurrentTime(0);\n setIsPlayed(false);\n }, []);\n\n const handleFullscreenChange = useCallback(() => {\n if (isFullscreen && exitFullscreen) {\n exitFullscreen();\n } else if (!isFullscreen && setFullscreen) {\n setFullscreen();\n }\n }, [exitFullscreen, isFullscreen, setFullscreen]);\n\n const handleSeek = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {\n e.stopPropagation();\n\n videoRef.current!.currentTime = (Number(e.target.value) * videoRef.current!.duration) / 100;\n }, []);\n\n const toggleControls = useCallback((e: React.MouseEvent<HTMLDivElement>) => {\n e.stopPropagation();\n setIsControlsVisible(!isControlsVisible);\n }, [isControlsVisible]);\n\n useEffect(() => {\n const togglePayingStateBySpace = (e: KeyboardEvent) => {\n if (e.key === 'Enter' || e.key === ' ') {\n togglePlayState(e);\n }\n };\n\n document.addEventListener('keydown', togglePayingStateBySpace, false);\n\n return () => {\n document.removeEventListener('keydown', togglePayingStateBySpace, false);\n };\n }, [togglePlayState]);\n\n const wrapperStyle = posterSize && `width: ${posterSize.width}px; height: ${posterSize.height}px`;\n const videoStyle = `background-image: url(${posterData})`;\n\n return (\n <div\n className=\"VideoPlayer\"\n onClick={!isGif && IS_MOBILE_SCREEN ? toggleControls : undefined}\n onMouseOver={!isGif ? handleMouseOver : undefined}\n onMouseOut={!isGif ? handleMouseOut : undefined}\n >\n <div\n // @ts-ignore\n style={wrapperStyle}\n >\n {/* eslint-disable-next-line jsx-a11y/media-has-caption */}\n <video\n ref={videoRef}\n autoPlay={IS_TOUCH_ENV}\n playsInline\n loop={isGif}\n // This is to force auto playing on mobiles\n muted={isGif}\n id=\"media-viewer-video\"\n // @ts-ignore\n style={videoStyle}\n onEnded={handleEnded}\n // eslint-disable-next-line react/jsx-props-no-spreading\n {...bufferingHandlers}\n onTimeUpdate={handleTimeUpdate}\n >\n {url && <source src={url} />}\n </video>\n </div>\n {shouldRenderSpinner && (\n <div className={['spinner-container', spinnerClassNames].join(' ')}>\n {!isBuffered && <div className=\"buffering\">Buffering...</div>}\n <ProgressSpinner\n size=\"xl\"\n progress={isBuffered ? 1 : downloadProgress}\n square\n onClick={onClose}\n />\n </div>\n )}\n {!isGif && !shouldRenderSpinner && (\n <VideoPlayerControls\n isPlayed={isPlayed}\n bufferedProgress={bufferedProgress}\n currentTime={currentTime}\n isFullscreenSupported={Boolean(setFullscreen)}\n isFullscreen={isFullscreen}\n fileSize={fileSize}\n duration={videoRef.current ? videoRef.current.duration : 0}\n isForceVisible={!isPlayed || isControlsVisible}\n isForceMobileVersion={posterSize && posterSize.width < MOBILE_VERSION_CONTROL_WIDTH}\n onSeek={handleSeek}\n onChangeFullscreen={handleFullscreenChange}\n onPlayPause={togglePlayState}\n />\n )}\n </div>\n );\n};\n\nexport default memo(VideoPlayer);\n","import React, {\n FC, memo, useCallback, useEffect, useRef, useState,\n} from '../../lib/teact/teact';\n\nimport { IS_MOBILE_SCREEN } from '../../util/environment';\nimport buildClassName from '../../util/buildClassName';\nimport usePrevious from '../../hooks/usePrevious';\nimport useShowTransition from '../../hooks/useShowTransition';\nimport useLang from '../../hooks/useLang';\n\nimport Button from '../ui/Button';\n\nimport './ZoomControls.scss';\n\ntype OwnProps = {\n isShown: boolean;\n onChangeZoom: (level: number, canCloseZoom?: boolean) => void;\n};\n\nexport const MAX_ZOOM_LEVEL = 3;\nexport const MIN_ZOOM_LEVEL = 1;\nconst ONE_STEP_PERCENT = 100 / (MAX_ZOOM_LEVEL - MIN_ZOOM_LEVEL);\nconst RESET_ZOOM_LEVEL = 1.5;\n\nconst ZoomControls: FC<OwnProps> = ({ isShown, onChangeZoom }) => {\n const { transitionClassNames } = useShowTransition(isShown);\n const prevIsShown = usePrevious<boolean>(isShown);\n // eslint-disable-next-line no-null/no-null\n const inputRef = useRef<HTMLInputElement>(null);\n const [zoomLevel, setZoomLevel] = useState(1);\n const isSeeking = useRef<boolean>(false);\n\n useEffect(() => {\n if (isShown && !prevIsShown) {\n setZoomLevel(RESET_ZOOM_LEVEL);\n }\n }, [isShown, prevIsShown]);\n\n const handleZoomOut = () => {\n if (inputRef.current) {\n setZoomLevel(Math.max(MIN_ZOOM_LEVEL, zoomLevel - 0.5));\n }\n };\n\n const handleZoomIn = () => {\n if (inputRef.current) {\n setZoomLevel(Math.min(MAX_ZOOM_LEVEL, zoomLevel + 0.5));\n }\n };\n\n const handleStartSeek = useCallback(() => {\n isSeeking.current = true;\n }, []);\n\n const handleStopSeek = useCallback(() => {\n isSeeking.current = false;\n if (zoomLevel === 1) {\n onChangeZoom(zoomLevel, !isSeeking.current);\n }\n }, [onChangeZoom, zoomLevel]);\n\n const handleSeeklineChange = (e:React.ChangeEvent<HTMLInputElement>) => {\n setZoomLevel(Math.min(MAX_ZOOM_LEVEL, Math.max(Number(e.target.value), MIN_ZOOM_LEVEL)));\n };\n\n useEffect(() => {\n onChangeZoom(zoomLevel, !isSeeking.current);\n }, [zoomLevel, onChangeZoom]);\n\n const lang = useLang();\n\n const className = buildClassName(\n 'ZoomControls',\n transitionClassNames,\n );\n\n return (\n <div className={className}>\n <Button\n disabled={zoomLevel === MIN_ZOOM_LEVEL}\n size=\"tiny\"\n color=\"translucent-white\"\n ariaLabel={lang('ZoomOut')}\n className=\"zoom-out\"\n ripple={!IS_MOBILE_SCREEN}\n onClick={handleZoomOut}\n >\n <i className=\"icon-zoom-out\" />\n </Button>\n <Button\n disabled={zoomLevel === MAX_ZOOM_LEVEL}\n size=\"tiny\"\n color=\"translucent-white\"\n ariaLabel=\"Zoom In\"\n className=\"zoom-in\"\n ripple={!IS_MOBILE_SCREEN}\n onClick={handleZoomIn}\n >\n <i className=\"icon-zoom-in\" />\n </Button>\n <div className=\"seekline\">\n <div className=\"seekline-track\">\n <div\n className=\"seekline-played\"\n // @ts-ignore teact feature\n style={`width: ${(zoomLevel - 1) * ONE_STEP_PERCENT}%`}\n />\n <input\n ref={inputRef}\n min={MIN_ZOOM_LEVEL}\n max={MAX_ZOOM_LEVEL}\n step=\"0.5\"\n value={zoomLevel}\n type=\"range\"\n className=\"seekline-input\"\n onChange={handleSeeklineChange}\n onMouseDown={handleStartSeek}\n onMouseUp={handleStopSeek}\n />\n </div>\n </div>\n </div>\n );\n};\n\nexport default memo(ZoomControls);\n","/*\n @source https://github.com/ajainarayanan/react-pan-zoom\n\n Heavily inspired/lifted from this idea: https://stackoverflow.com/a/39311435/661768\n without jqueryUI or jquery dependency.\n*/\nimport React, {\n FC, memo, useEffect, useRef, useState,\n} from '../../lib/teact/teact';\n\nimport { areSortedArraysEqual } from '../../util/iteratees';\n\nimport './PanZoom.scss';\n\nexport interface IDragData {\n x: number;\n y: number;\n dx: number;\n dy: number;\n}\n\nexport interface OwnProps {\n children: any;\n className?: string;\n noWrap: boolean;\n canPan: boolean;\n zoomLevel: number;\n panDeltaX: number;\n panDeltaY: number;\n onPan?: (x: number, y: number) => void;\n}\n\nconst INITIAL_MATRIX = [\n 1, 0, 0, 1, 0, 0,\n];\n\nconst SCALE_VALUES = {\n 1: 1,\n 1.5: 1.5,\n 2: 2.2,\n 2.5: 3.3,\n 3: 5.5,\n};\n\nconst ZOOM_SAFE_AREA = 150;\n\nfunction calculateSafeZoneOnZoom(oldScale: number, matrixData: number[], wrapper: HTMLDivElement | null) {\n const image = wrapper && wrapper.querySelector('.active img');\n if (!wrapper || !image) {\n return matrixData;\n }\n const wrapperRect = wrapper.getBoundingClientRect();\n const imageRect = image.getBoundingClientRect();\n\n const newImgWidth = (imageRect.width / oldScale) * matrixData[0];\n const newImgHeight = (imageRect.height / oldScale) * matrixData[3];\n const newImgX = (wrapperRect.width - newImgWidth) / 2 + matrixData[4];\n const newImgY = (wrapperRect.height - newImgHeight) / 2 + matrixData[5];\n if (wrapperRect.width && wrapperRect.width - ZOOM_SAFE_AREA < newImgX) {\n matrixData[4] -= newImgX + wrapperRect.width - ZOOM_SAFE_AREA;\n } else if (newImgWidth && newImgWidth + newImgX < ZOOM_SAFE_AREA) {\n matrixData[4] -= newImgWidth + newImgX - ZOOM_SAFE_AREA;\n }\n if (wrapperRect.height && wrapperRect.height - ZOOM_SAFE_AREA < newImgY) {\n matrixData[5] -= newImgY + wrapperRect.height - ZOOM_SAFE_AREA;\n } else if (newImgHeight && newImgHeight + newImgY < ZOOM_SAFE_AREA) {\n matrixData[5] -= newImgHeight + newImgY - ZOOM_SAFE_AREA;\n }\n\n return matrixData;\n}\n\nconst PanZoom: FC<OwnProps> = ({\n children,\n className,\n noWrap,\n canPan,\n zoomLevel,\n panDeltaX,\n panDeltaY,\n onPan,\n}) => {\n const tunedZoomLevel = SCALE_VALUES[zoomLevel as keyof typeof SCALE_VALUES] || zoomLevel;\n const [isDragging, setIsDragging] = useState<boolean>(false);\n const [dragData, setDragData] = useState<IDragData>({\n dx: panDeltaX, dy: panDeltaY, x: 0, y: 0,\n });\n // [zoom, skew, skew, zoom, dx, dy] - see https://developer.mozilla.org/en-US/docs/Web/CSS/transform-function/matrix()\n const [matrixData, setMatrixData] = useState<number[]>(INITIAL_MATRIX);\n // Used to set cursor while moving.\n // eslint-disable-next-line no-null/no-null\n const panWrapperRef = useRef<HTMLDivElement>(null);\n // Used to set transform for pan.\n // eslint-disable-next-line no-null/no-null\n const panContainerRef = useRef<HTMLDivElement>(null);\n\n useEffect(() => {\n const newZoomLevel = tunedZoomLevel || matrixData[0];\n const newPandx = panDeltaX || matrixData[4];\n const newPandy = panDeltaY || matrixData[5];\n\n const newMatrixData = [...matrixData];\n if (matrixData[0] !== newZoomLevel) {\n newMatrixData[0] = newZoomLevel || newMatrixData[0];\n newMatrixData[3] = newZoomLevel || newMatrixData[3];\n }\n if (matrixData[4] !== newPandx) {\n newMatrixData[4] = newPandx;\n }\n if (matrixData[5] !== newPandy) {\n newMatrixData[5] = newPandy;\n }\n\n if (!areSortedArraysEqual(matrixData, newMatrixData)) {\n setMatrixData(calculateSafeZoneOnZoom(matrixData[0], newMatrixData, panWrapperRef.current));\n }\n // eslint-disable-next-line\n }, [panDeltaX, panDeltaY, tunedZoomLevel]);\n\n useEffect(() => {\n if (!canPan) {\n setMatrixData(INITIAL_MATRIX);\n }\n }, [canPan]);\n\n useEffect(() => {\n if (panContainerRef.current) {\n panContainerRef.current.style.transform = `matrix(${matrixData.toString()})`;\n }\n }, [noWrap, matrixData]);\n\n const handleMouseDown = (e: React.MouseEvent<EventTarget>) => {\n if (!canPan) {\n return;\n }\n\n e.stopPropagation();\n e.preventDefault();\n\n const offsetX = matrixData[4];\n const offsetY = matrixData[5];\n const newDragData: IDragData = {\n dx: offsetX,\n dy: offsetY,\n x: e.pageX,\n y: e.pageY,\n };\n setDragData(newDragData);\n setIsDragging(true);\n\n if (panWrapperRef.current) {\n panWrapperRef.current.classList.add('move');\n }\n };\n\n const handleMouseUp = () => {\n setIsDragging(false);\n\n if (panWrapperRef.current) {\n panWrapperRef.current.classList.remove('move');\n }\n\n if (onPan) {\n onPan(matrixData[4], matrixData[5]);\n }\n };\n\n function getNewMatrixData(x: number, y: number): number[] {\n const newMatrixData = [...matrixData];\n const deltaX = dragData.x - x;\n const deltaY = dragData.y - y;\n newMatrixData[4] = dragData.dx - deltaX;\n newMatrixData[5] = dragData.dy - deltaY;\n\n return newMatrixData;\n }\n\n const handleMouseMove = (e: React.MouseEvent<EventTarget>) => {\n if (isDragging) {\n const newMatrixData = getNewMatrixData(e.pageX, e.pageY);\n setMatrixData(newMatrixData);\n\n if (panContainerRef.current) {\n panContainerRef.current.style.transform = `matrix(${matrixData.toString()})`;\n }\n }\n };\n\n if (noWrap) {\n return children;\n }\n\n return (\n <div\n ref={panWrapperRef}\n className={`pan-wrapper ${className || ''}`}\n onMouseDown={handleMouseDown}\n onMouseUp={handleMouseUp}\n onMouseMove={handleMouseMove}\n >\n <div\n ref={panContainerRef}\n className=\"pan-container\"\n >\n {children}\n </div>\n </div>\n );\n};\n\nexport default memo(PanZoom);\n","import React, {\n FC, memo, useCallback, useEffect, useMemo, useRef, useState,\n} from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../global/types';\nimport {\n ApiChat, ApiMediaFormat, ApiMessage, ApiUser,\n} from '../../api/types';\nimport { MediaViewerOrigin } from '../../types';\n\nimport { ANIMATION_END_DELAY } from '../../config';\nimport { IS_IOS, IS_MOBILE_SCREEN, IS_TOUCH_ENV } from '../../util/environment';\nimport {\n AVATAR_FULL_DIMENSIONS,\n MEDIA_VIEWER_MEDIA_QUERY,\n calculateMediaViewerDimensions,\n} from '../common/helpers/mediaDimensions';\nimport {\n selectChat,\n selectChatMessage,\n selectChatMessages,\n selectCurrentMediaSearch,\n selectListedIds,\n selectOutlyingIds,\n selectScheduledMessage,\n selectScheduledMessages,\n selectUser,\n} from '../../modules/selectors';\nimport {\n getChatAvatarHash,\n getChatMediaMessageIds,\n getMessageMediaFilename,\n getMessageMediaFormat,\n getMessageMediaHash,\n getMessageMediaThumbDataUri,\n getMessagePhoto,\n getMessageVideo,\n getMessageWebPagePhoto,\n getPhotoFullDimensions,\n getVideoDimensions,\n IDimensions,\n} from '../../modules/helpers';\nimport { pick } from '../../util/iteratees';\nimport { captureEvents, SwipeDirection } from '../../util/captureEvents';\nimport captureEscKeyListener from '../../util/captureEscKeyListener';\nimport { stopCurrentAudio } from '../../util/audioPlayer';\nimport useForceUpdate from '../../hooks/useForceUpdate';\nimport useMedia from '../../hooks/useMedia';\nimport useMediaWithDownloadProgress from '../../hooks/useMediaWithDownloadProgress';\nimport useBlurSync from '../../hooks/useBlurSync';\nimport usePrevious from '../../hooks/usePrevious';\nimport { dispatchHeavyAnimationEvent } from '../../hooks/useHeavyAnimationCheck';\nimport { renderMessageText } from '../common/helpers/renderMessageText';\nimport { animateClosing, animateOpening } from './helpers/ghostAnimation';\nimport useLang from '../../hooks/useLang';\n\nimport Spinner from '../ui/Spinner';\nimport ShowTransition from '../ui/ShowTransition';\nimport Transition from '../ui/Transition';\nimport Button from '../ui/Button';\nimport SenderInfo from './SenderInfo';\nimport MediaViewerActions from './MediaViewerActions';\nimport MediaViewerFooter from './MediaViewerFooter';\nimport VideoPlayer from './VideoPlayer';\nimport ZoomControls from './ZoomControls';\nimport PanZoom from './PanZoom';\n\nimport './MediaViewer.scss';\n\ntype StateProps = {\n chatId?: number;\n threadId?: number;\n messageId?: number;\n senderId?: number;\n origin?: MediaViewerOrigin;\n avatarOwner?: ApiChat | ApiUser;\n profilePhotoIndex?: number;\n message?: ApiMessage;\n chatMessages?: Record<number, ApiMessage>;\n collectionIds?: number[];\n animationLevel: 0 | 1 | 2;\n};\n\ntype DispatchProps = Pick<GlobalActions, 'openMediaViewer' | 'closeMediaViewer' | 'openForwardMenu' | 'focusMessage'>;\n\nconst ANIMATION_DURATION = 350;\n\nconst MediaViewer: FC<StateProps & DispatchProps> = ({\n chatId,\n threadId,\n messageId,\n senderId,\n origin,\n avatarOwner,\n profilePhotoIndex,\n message,\n chatMessages,\n collectionIds,\n openMediaViewer,\n closeMediaViewer,\n openForwardMenu,\n focusMessage,\n animationLevel,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const animationKey = useRef<number>(null);\n const isOpen = Boolean(avatarOwner || messageId);\n const webPagePhoto = message ? getMessageWebPagePhoto(message) : undefined;\n const photo = message ? getMessagePhoto(message) : undefined;\n const video = message ? getMessageVideo(message) : undefined;\n const isWebPagePhoto = Boolean(webPagePhoto);\n const isPhoto = Boolean(photo || webPagePhoto);\n const isVideo = Boolean(video);\n const isGif = video ? video.isGif : undefined;\n const isFromSharedMedia = origin === MediaViewerOrigin.SharedMedia;\n const isFromSearch = origin === MediaViewerOrigin.SearchResult;\n const slideAnimation = animationLevel >= 1 ? 'mv-slide' : 'none';\n const headerAnimation = animationLevel === 2 ? 'slide-fade' : 'none';\n const isGhostAnimation = animationLevel === 2;\n const fileName = avatarOwner\n ? `avatar${avatarOwner.id}-${profilePhotoIndex}.jpg`\n : message && getMessageMediaFilename(message);\n const prevSenderId = usePrevious<number | undefined>(senderId);\n const [canPanZoomWrap, setCanPanZoomWrap] = useState(false);\n const [isZoomed, setIsZoomed] = useState<boolean>(false);\n const [zoomLevel, setZoomLevel] = useState<number>(1);\n const [panDelta, setPanDelta] = useState({ x: 0, y: 0 });\n\n const messageIds = useMemo(() => {\n return isWebPagePhoto && messageId\n ? [messageId]\n : getChatMediaMessageIds(chatMessages || {}, collectionIds || [], isFromSharedMedia);\n }, [isWebPagePhoto, messageId, chatMessages, collectionIds, isFromSharedMedia]);\n\n const selectedMediaMessageIndex = messageId ? messageIds.indexOf(messageId) : -1;\n const isFirst = selectedMediaMessageIndex === 0 || selectedMediaMessageIndex === -1;\n const isLast = selectedMediaMessageIndex === messageIds.length - 1 || selectedMediaMessageIndex === -1;\n if (isOpen && (!prevSenderId || prevSenderId !== senderId || !animationKey.current)) {\n animationKey.current = selectedMediaMessageIndex;\n }\n\n function getMediaHash(full?: boolean) {\n if (avatarOwner && profilePhotoIndex !== undefined) {\n const { photos } = avatarOwner;\n return photos && photos[profilePhotoIndex]\n ? `photo${photos[profilePhotoIndex].id}?size=c`\n : getChatAvatarHash(avatarOwner, full ? 'big' : 'normal');\n }\n\n return message && getMessageMediaHash(message, full ? 'viewerFull' : 'viewerPreview');\n }\n\n const blobUrlPictogram = useMedia(\n message && (isFromSharedMedia || isFromSearch) && getMessageMediaHash(message, 'pictogram'),\n undefined,\n ApiMediaFormat.BlobUrl,\n undefined,\n isGhostAnimation && ANIMATION_DURATION,\n );\n const previewMediaHash = getMediaHash();\n const blobUrlPreview = useMedia(\n previewMediaHash,\n undefined,\n avatarOwner && previewMediaHash && previewMediaHash.startsWith('profilePhoto')\n ? ApiMediaFormat.DataUri\n : ApiMediaFormat.BlobUrl,\n undefined,\n isGhostAnimation && ANIMATION_DURATION,\n );\n const { mediaData: fullMediaData, downloadProgress } = useMediaWithDownloadProgress(\n getMediaHash(true),\n undefined,\n message && getMessageMediaFormat(message, 'viewerFull'),\n undefined,\n isGhostAnimation && ANIMATION_DURATION,\n );\n\n const localBlobUrl = (photo || video) ? (photo || video)!.blobUrl : undefined;\n let bestImageData = (!isVideo && (localBlobUrl || fullMediaData)) || blobUrlPreview || blobUrlPictogram;\n const thumbDataUri = useBlurSync(!bestImageData && message && getMessageMediaThumbDataUri(message));\n if (!bestImageData && origin !== MediaViewerOrigin.SearchResult) {\n bestImageData = thumbDataUri;\n }\n\n const photoDimensions = isPhoto ? getPhotoFullDimensions((\n isWebPagePhoto ? getMessageWebPagePhoto(message!) : getMessagePhoto(message!)\n )!) : undefined;\n const videoDimensions = isVideo ? getVideoDimensions(getMessageVideo(message!)!) : undefined;\n\n useEffect(() => {\n if (!IS_MOBILE_SCREEN) {\n return;\n }\n\n document.body.classList.toggle('is-media-viewer-open', isOpen);\n }, [isOpen]);\n\n const forceUpdate = useForceUpdate();\n useEffect(() => {\n const mql = window.matchMedia(MEDIA_VIEWER_MEDIA_QUERY);\n if (typeof mql.addEventListener === 'function') {\n mql.addEventListener('change', forceUpdate);\n } else if (typeof mql.addListener === 'function') {\n mql.addListener(forceUpdate);\n }\n\n return () => {\n if (typeof mql.removeEventListener === 'function') {\n mql.removeEventListener('change', forceUpdate);\n } else if (typeof mql.removeListener === 'function') {\n mql.removeListener(forceUpdate);\n }\n };\n }, [forceUpdate]);\n\n const prevMessage = usePrevious<ApiMessage | undefined>(message);\n const prevOrigin = usePrevious(origin);\n const prevAvatarOwner = usePrevious<ApiChat | ApiUser | undefined>(avatarOwner);\n const prevBestImageData = usePrevious(bestImageData);\n useEffect(() => {\n if (isGhostAnimation && isOpen && !prevMessage && !prevAvatarOwner) {\n dispatchHeavyAnimationEvent(ANIMATION_DURATION + ANIMATION_END_DELAY);\n const textParts = message ? renderMessageText(message) : undefined;\n const hasFooter = Boolean(textParts);\n animateOpening(hasFooter, origin!, bestImageData!, message);\n }\n\n if (isGhostAnimation && !isOpen && (prevMessage || prevAvatarOwner)) {\n dispatchHeavyAnimationEvent(ANIMATION_DURATION + ANIMATION_END_DELAY);\n animateClosing(prevOrigin!, prevBestImageData!, prevMessage || undefined);\n }\n }, [\n isGhostAnimation, isOpen, origin, prevOrigin,\n message, prevMessage, prevAvatarOwner, bestImageData, prevBestImageData,\n ]);\n\n useEffect(() => {\n let timer: number | undefined;\n\n if (isZoomed) {\n setCanPanZoomWrap(true);\n } else {\n timer = window.setTimeout(() => {\n setCanPanZoomWrap(false);\n }, ANIMATION_DURATION);\n }\n\n return () => {\n if (timer) {\n window.clearTimeout(timer);\n }\n };\n }, [isZoomed]);\n\n const closeZoom = () => {\n setIsZoomed(false);\n setZoomLevel(1);\n setPanDelta({ x: 0, y: 0 });\n };\n\n const handleZoomToggle = useCallback(() => {\n setIsZoomed(!isZoomed);\n setZoomLevel(!isZoomed ? 1.5 : 1);\n if (isZoomed) {\n setPanDelta({ x: 0, y: 0 });\n }\n }, [isZoomed]);\n\n const handleZoomValue = useCallback((level: number, canCloseZoom = false) => {\n setZoomLevel(level);\n if (level === 1 && canCloseZoom) {\n closeZoom();\n }\n }, []);\n\n const close = useCallback(() => {\n closeMediaViewer();\n closeZoom();\n }, [closeMediaViewer]);\n\n const handleFooterClick = useCallback(() => {\n close();\n focusMessage({ chatId, threadId, messageId });\n }, [close, chatId, threadId, focusMessage, messageId]);\n\n const handleForward = useCallback(() => {\n openForwardMenu({ fromChatId: chatId, messageIds: [messageId] });\n closeZoom();\n }, [openForwardMenu, chatId, messageId]);\n\n useEffect(() => (isOpen ? captureEscKeyListener(() => {\n if (isZoomed) {\n closeZoom();\n } else {\n close();\n }\n }) : undefined), [close, isOpen, isZoomed]);\n\n useEffect(() => {\n if (isVideo && !isGif) {\n stopCurrentAudio();\n }\n }, [isGif, isVideo]);\n\n const getMessageId = useCallback((fromId: number, direction: number): number => {\n let index = messageIds.indexOf(fromId);\n if ((direction === -1 && index > 0) || (direction === 1 && index < messageIds.length - 1)) {\n index += direction;\n }\n\n return messageIds[index];\n }, [messageIds]);\n\n const selectPreviousMedia = useCallback(() => {\n if (isFirst) {\n return;\n }\n\n openMediaViewer({\n chatId,\n threadId,\n messageId: messageId ? getMessageId(messageId, -1) : undefined,\n origin,\n });\n }, [chatId, threadId, getMessageId, isFirst, messageId, openMediaViewer, origin]);\n\n const selectNextMedia = useCallback(() => {\n if (isLast) {\n return;\n }\n\n openMediaViewer({\n chatId,\n threadId,\n messageId: messageId ? getMessageId(messageId, 1) : undefined,\n origin,\n });\n }, [chatId, threadId, getMessageId, isLast, messageId, openMediaViewer, origin]);\n\n useEffect(() => {\n const handleKeyDown = (e: KeyboardEvent) => {\n switch (e.key) {\n case 'Left': // IE/Edge specific value\n case 'ArrowLeft':\n selectPreviousMedia();\n break;\n\n case 'Right': // IE/Edge specific value\n case 'ArrowRight':\n selectNextMedia();\n break;\n }\n };\n\n document.addEventListener('keydown', handleKeyDown, false);\n\n return () => {\n document.removeEventListener('keydown', handleKeyDown, false);\n };\n });\n\n // Support for swipe gestures and closing on click\n useEffect(() => {\n const element = document.querySelector<HTMLDivElement>('.slide-container > .active, .slide-container > .to');\n if (!element) {\n return undefined;\n }\n\n const shouldCloseOnVideo = isGif && !IS_IOS;\n\n return captureEvents(element, {\n // eslint-disable-next-line max-len\n excludedClosestSelector: `.backdrop, .navigation, .media-viewer-head, .media-viewer-footer${!shouldCloseOnVideo ? ', .VideoPlayer' : ''}`,\n onClick: () => {\n if (!isZoomed) {\n close();\n }\n },\n onSwipe: IS_TOUCH_ENV ? (e, direction) => {\n if (direction === SwipeDirection.Right) {\n selectPreviousMedia();\n } else if (direction === SwipeDirection.Left) {\n selectNextMedia();\n } else {\n close();\n }\n } : undefined,\n });\n }, [close, isGif, isZoomed, selectNextMedia, selectPreviousMedia, canPanZoomWrap]);\n\n const handlePan = useCallback((x: number, y: number) => {\n setPanDelta({ x, y });\n }, []);\n\n const lang = useLang();\n\n function renderSlide(isActive: boolean) {\n if (avatarOwner) {\n return (\n <div key={chatId} className=\"media-viewer-content\">\n {renderPhoto(\n fullMediaData || blobUrlPreview,\n calculateMediaViewerDimensions(AVATAR_FULL_DIMENSIONS, false),\n !IS_MOBILE_SCREEN && !isZoomed,\n )}\n </div>\n );\n } else if (message) {\n const textParts = renderMessageText(message);\n const hasFooter = Boolean(textParts);\n\n return (\n <div key={messageId} className={`media-viewer-content ${hasFooter ? 'has-footer' : ''}`}>\n {isPhoto && renderPhoto(\n localBlobUrl || fullMediaData || blobUrlPreview || blobUrlPictogram,\n message && calculateMediaViewerDimensions(photoDimensions!, hasFooter),\n !IS_MOBILE_SCREEN && !isZoomed,\n )}\n {isVideo && (\n <VideoPlayer\n key={messageId}\n url={localBlobUrl || fullMediaData}\n isGif={isGif}\n posterData={bestImageData}\n posterSize={message && calculateMediaViewerDimensions(videoDimensions!, hasFooter, true)}\n downloadProgress={downloadProgress}\n fileSize={video!.size}\n isMediaViewerOpen={isOpen}\n noPlay={!isActive}\n onClose={close}\n />\n )}\n {textParts && (\n <MediaViewerFooter\n text={textParts}\n onClick={handleFooterClick}\n isHideable={isVideo}\n />\n )}\n </div>\n );\n }\n\n return undefined;\n }\n\n function renderSenderInfo() {\n return (\n <SenderInfo\n key={avatarOwner ? avatarOwner.id : messageId}\n chatId={avatarOwner ? avatarOwner.id : chatId}\n messageId={messageId}\n isAvatar={Boolean(avatarOwner)}\n />\n );\n }\n\n return (\n <ShowTransition\n id=\"MediaViewer\"\n className={isZoomed ? 'zoomed' : ''}\n isOpen={isOpen}\n >\n {() => (\n <>\n <div className=\"media-viewer-head\" dir={lang.isRtl ? 'rtl' : undefined}>\n {IS_MOBILE_SCREEN && (\n <Button\n className=\"media-viewer-close\"\n round\n size=\"smaller\"\n color=\"translucent-white\"\n ariaLabel={lang('Close')}\n onClick={close}\n >\n <i className=\"icon-close\" />\n </Button>\n )}\n <Transition activeKey={animationKey.current!} name={headerAnimation}>\n {renderSenderInfo}\n </Transition>\n <MediaViewerActions\n mediaData={fullMediaData || blobUrlPreview}\n isVideo={isVideo}\n isZoomed={isZoomed}\n message={message}\n fileName={fileName}\n onCloseMediaViewer={close}\n onForward={handleForward}\n onZoomToggle={handleZoomToggle}\n isAvatar={Boolean(avatarOwner)}\n />\n </div>\n <PanZoom\n noWrap={!canPanZoomWrap}\n canPan={isZoomed}\n panDeltaX={panDelta.x}\n panDeltaY={panDelta.y}\n zoomLevel={zoomLevel}\n onPan={handlePan}\n >\n <Transition\n className=\"slide-container\"\n activeKey={selectedMediaMessageIndex}\n name={slideAnimation}\n >\n {renderSlide}\n </Transition>\n </PanZoom>\n {!isFirst && (\n <button\n type=\"button\"\n className={`navigation prev ${isVideo && !isGif && 'inline'}`}\n aria-label={lang('AccDescrPrevious')}\n dir={lang.isRtl ? 'rtl' : undefined}\n onClick={selectPreviousMedia}\n />\n )}\n {!isLast && (\n <button\n type=\"button\"\n className={`navigation next ${isVideo && !isGif && 'inline'}`}\n aria-label={lang('Next')}\n dir={lang.isRtl ? 'rtl' : undefined}\n onClick={selectNextMedia}\n />\n )}\n <ZoomControls\n isShown={isZoomed}\n onChangeZoom={handleZoomValue}\n />\n </>\n )}\n </ShowTransition>\n );\n};\n\nfunction renderPhoto(blobUrl?: string, imageSize?: IDimensions, canDrag?: boolean) {\n return blobUrl\n ? (\n <img\n src={blobUrl}\n alt=\"\"\n // @ts-ignore teact feature\n style={imageSize ? `width: ${imageSize.width}px` : ''}\n draggable={Boolean(canDrag)}\n />\n )\n : (\n <div\n className=\"spinner-wrapper\"\n // @ts-ignore teact feature\n style={imageSize ? `width: ${imageSize.width}px` : ''}\n >\n <Spinner color=\"white\" />\n </div>\n );\n}\n\nexport default memo(withGlobal(\n (global): StateProps => {\n const {\n chatId, threadId, messageId, avatarOwnerId, profilePhotoIndex, origin,\n } = global.mediaViewer;\n const {\n animationLevel,\n } = global.settings.byKey;\n\n if (origin === MediaViewerOrigin.SearchResult) {\n if (!(chatId && messageId)) {\n return { animationLevel };\n }\n\n const message = selectChatMessage(global, chatId, messageId);\n if (!message) {\n return { animationLevel };\n }\n\n return {\n chatId,\n messageId,\n senderId: message.senderId,\n origin,\n message,\n animationLevel,\n };\n }\n\n if (avatarOwnerId) {\n const sender = selectUser(global, avatarOwnerId) || selectChat(global, avatarOwnerId);\n\n return {\n messageId: -1,\n senderId: avatarOwnerId,\n avatarOwner: sender,\n profilePhotoIndex: profilePhotoIndex || 0,\n animationLevel,\n origin,\n };\n }\n\n if (!(chatId && threadId && messageId)) {\n return { animationLevel };\n }\n\n let message: ApiMessage | undefined;\n if (origin && [MediaViewerOrigin.ScheduledAlbum, MediaViewerOrigin.ScheduledInline].includes(origin)) {\n message = selectScheduledMessage(global, chatId, messageId);\n } else {\n message = selectChatMessage(global, chatId, messageId);\n }\n\n if (!message) {\n return { animationLevel };\n }\n\n let chatMessages: Record<number, ApiMessage> | undefined;\n\n if (origin && [MediaViewerOrigin.ScheduledAlbum, MediaViewerOrigin.ScheduledInline].includes(origin)) {\n chatMessages = selectScheduledMessages(global, chatId);\n } else {\n chatMessages = selectChatMessages(global, chatId);\n }\n let collectionIds: number[] | undefined;\n\n if (origin === MediaViewerOrigin.Inline || origin === MediaViewerOrigin.Album) {\n collectionIds = selectOutlyingIds(global, chatId, threadId) || selectListedIds(global, chatId, threadId);\n } else if (origin === MediaViewerOrigin.SharedMedia) {\n const currentSearch = selectCurrentMediaSearch(global);\n const { foundIds } = (currentSearch && currentSearch.resultsByType && currentSearch.resultsByType.media) || {};\n collectionIds = foundIds;\n }\n\n return {\n chatId,\n threadId,\n messageId,\n senderId: message.senderId,\n origin,\n message,\n chatMessages,\n collectionIds,\n animationLevel,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'openMediaViewer', 'closeMediaViewer', 'openForwardMenu', 'focusMessage',\n ]),\n)(MediaViewer));\n","import React, {\n FC, useMemo, useState, memo, useRef, useEffect, useCallback,\n} from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../global/types';\nimport { ApiChat, MAIN_THREAD_ID } from '../../api/types';\n\nimport { IS_MOBILE_SCREEN } from '../../util/environment';\nimport {\n getCanPostInChat, getChatTitle, isChatPrivate, sortChatIds,\n} from '../../modules/helpers';\nimport searchWords from '../../util/searchWords';\nimport { pick } from '../../util/iteratees';\nimport useInfiniteScroll from '../../hooks/useInfiniteScroll';\nimport useLang from '../../hooks/useLang';\nimport useKeyboardListNavigation from '../../hooks/useKeyboardListNavigation';\n\nimport Loading from '../ui/Loading';\nimport Modal from '../ui/Modal';\nimport InputText from '../ui/InputText';\nimport Button from '../ui/Button';\nimport InfiniteScroll from '../ui/InfiniteScroll';\nimport ListItem from '../ui/ListItem';\nimport PrivateChatInfo from '../common/PrivateChatInfo';\nimport GroupChatInfo from '../common/GroupChatInfo';\n\nimport './ForwardPicker.scss';\n\nexport type OwnProps = {\n isOpen: boolean;\n};\n\ntype StateProps = {\n chatsById: Record<number, ApiChat>;\n activeListIds?: number[];\n archivedListIds?: number[];\n orderedPinnedIds?: number[];\n currentUserId?: number;\n};\n\ntype DispatchProps = Pick<GlobalActions, 'setForwardChatId' | 'exitForwardMode' | 'loadMoreChats'>;\n\n// Focus slows down animation, also it breaks transition layout in Chrome\nconst FOCUS_DELAY_MS = 500;\nconst MODAL_HIDE_DELAY_MS = 300;\n\nconst ForwardPicker: FC<OwnProps & StateProps & DispatchProps> = ({\n chatsById,\n activeListIds,\n archivedListIds,\n currentUserId,\n isOpen,\n setForwardChatId,\n exitForwardMode,\n loadMoreChats,\n}) => {\n const [filter, setFilter] = useState('');\n // eslint-disable-next-line no-null/no-null\n const inputRef = useRef<HTMLInputElement>(null);\n\n const lang = useLang();\n\n useEffect(() => {\n if (isOpen) {\n if (!IS_MOBILE_SCREEN) {\n setTimeout(() => {\n requestAnimationFrame(() => {\n if (inputRef.current) {\n inputRef.current.focus();\n }\n });\n }, FOCUS_DELAY_MS);\n }\n } else {\n if (inputRef.current) {\n inputRef.current.blur();\n }\n\n setTimeout(() => {\n setFilter('');\n }, MODAL_HIDE_DELAY_MS);\n }\n }, [isOpen]);\n\n const chatIds = useMemo(() => {\n const listIds = [\n ...activeListIds || [],\n ...archivedListIds || [],\n ];\n\n return sortChatIds([\n ...listIds.filter((id) => {\n const chat = chatsById[id];\n if (!chat) {\n return true;\n }\n\n if (!getCanPostInChat(chat, MAIN_THREAD_ID)) {\n return false;\n }\n\n if (!filter) {\n return true;\n }\n\n return searchWords(getChatTitle(lang, chatsById[id], undefined, id === currentUserId), filter);\n }),\n ], chatsById, undefined, currentUserId ? [currentUserId] : undefined);\n }, [activeListIds, archivedListIds, chatsById, currentUserId, filter, lang]);\n\n const [viewportIds, getMore] = useInfiniteScroll(loadMoreChats, chatIds, Boolean(filter));\n\n const handleFilterChange = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {\n setFilter(e.currentTarget.value);\n }, []);\n\n // eslint-disable-next-line no-null/no-null\n const containerRef = useRef<HTMLDivElement>(null);\n const handleKeyDown = useKeyboardListNavigation(containerRef, isOpen, (index) => {\n if (viewportIds) {\n setForwardChatId({ id: viewportIds[index] });\n }\n }, '.ListItem-button', true);\n\n const modalHeader = (\n <div className=\"modal-header\" dir={lang.isRtl ? 'rtl' : undefined}>\n <Button\n round\n color=\"translucent\"\n size=\"smaller\"\n ariaLabel={lang('Close')}\n onClick={exitForwardMode}\n >\n <i className=\"icon-close\" />\n </Button>\n <InputText\n ref={inputRef}\n value={filter}\n onChange={handleFilterChange}\n onKeyDown={handleKeyDown}\n placeholder={lang('ForwardTo')}\n />\n </div>\n );\n\n return (\n <Modal\n isOpen={isOpen}\n onClose={exitForwardMode}\n className=\"ForwardPicker\"\n header={modalHeader}\n >\n {viewportIds && viewportIds.length ? (\n <InfiniteScroll\n className=\"picker-list custom-scroll\"\n items={viewportIds}\n onLoadMore={getMore}\n noScrollRestore={Boolean(filter)}\n ref={containerRef}\n onKeyDown={handleKeyDown}\n >\n {viewportIds.map((id) => (\n <ListItem\n key={id}\n className=\"chat-item-clickable force-rounded-corners\"\n onClick={() => setForwardChatId({ id })}\n >\n {isChatPrivate(id) ? (\n <PrivateChatInfo status={id === currentUserId ? lang('SavedMessagesInfo') : undefined} userId={id} />\n ) : (\n <GroupChatInfo chatId={id} />\n )}\n </ListItem>\n ))}\n </InfiniteScroll>\n ) : viewportIds && !viewportIds.length ? (\n <p className=\"no-results\">Sorry, nothing found.</p>\n ) : (\n <Loading />\n )}\n </Modal>\n );\n};\n\nexport default memo(withGlobal<OwnProps>(\n (global): StateProps => {\n const {\n chats: {\n byId: chatsById,\n listIds,\n },\n currentUserId,\n } = global;\n\n return {\n chatsById,\n activeListIds: listIds.active,\n archivedListIds: listIds.archived,\n currentUserId,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, ['setForwardChatId', 'exitForwardMode', 'loadMoreChats']),\n)(ForwardPicker));\n","import React, { FC, memo } from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../global/types';\nimport { ApiError } from '../../api/types';\n\nimport getReadableErrorText from '../../util/getReadableErrorText';\nimport { pick } from '../../util/iteratees';\nimport useLang from '../../hooks/useLang';\n\nimport Modal from '../ui/Modal';\nimport Button from '../ui/Button';\n\nimport './Errors.scss';\n\ntype StateProps = {\n errors: ApiError[];\n};\n\ntype DispatchProps = Pick<GlobalActions, 'dismissError'>;\n\nconst Errors: FC<StateProps & DispatchProps> = ({ errors, dismissError }) => {\n const lang = useLang();\n\n if (!errors.length) {\n return undefined;\n }\n\n return (\n <div id=\"Errors\">\n {errors.map((error) => (\n <Modal\n isOpen\n onClose={dismissError}\n className=\"error\"\n title={getErrorHeader(error)}\n >\n <p>{getReadableErrorText(error)}</p>\n <Button isText onClick={dismissError}>{lang('OK')}</Button>\n </Modal>\n ))}\n </div>\n );\n};\n\nfunction getErrorHeader(error: ApiError) {\n if (error.isSlowMode) {\n return 'Slowmode enabled';\n }\n\n return 'Something went wrong';\n}\n\nexport default memo(withGlobal(\n (global): StateProps => pick(global, ['errors']),\n (setGlobal, actions): DispatchProps => pick(actions, ['dismissError']),\n)(Errors));\n","import React, { FC, memo } from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../global/types';\nimport { ApiNotification } from '../../api/types';\n\nimport { pick } from '../../util/iteratees';\n\nimport Notification from '../ui/Notification';\nimport renderText from '../common/helpers/renderText';\n\ntype StateProps = {\n notifications: ApiNotification[];\n};\n\ntype DispatchProps = Pick<GlobalActions, 'dismissNotification'>;\n\nconst Notifications: FC<StateProps & DispatchProps> = ({ notifications, dismissNotification }) => {\n if (!notifications.length) {\n return undefined;\n }\n\n return (\n <div id=\"Notifications\">\n {notifications.map(({ message }) => (\n <Notification\n message={renderText(message, ['emoji', 'br', 'links'])}\n onDismiss={dismissNotification}\n />\n ))}\n </div>\n );\n};\n\nexport default memo(withGlobal(\n (global): StateProps => pick(global, ['notifications']),\n (setGlobal, actions): DispatchProps => pick(actions, ['dismissNotification']),\n)(Notifications));\n","import React, { FC, memo, useCallback } from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../global/types';\n\nimport { pick } from '../../util/iteratees';\nimport renderText from '../common/helpers/renderText';\nimport useLang from '../../hooks/useLang';\nimport useCurrentOrPrev from '../../hooks/useCurrentOrPrev';\n\nimport ConfirmDialog from '../ui/ConfirmDialog';\n\nexport type OwnProps = {\n url?: string;\n};\n\ntype DispatchProps = Pick<GlobalActions, 'toggleSafeLinkModal'>;\n\nconst SafeLinkModal: FC<OwnProps & DispatchProps> = ({ url, toggleSafeLinkModal }) => {\n const lang = useLang();\n\n const handleOpen = useCallback(() => {\n window.open(url);\n toggleSafeLinkModal({ url: undefined });\n }, [toggleSafeLinkModal, url]);\n\n const handleDismiss = useCallback(() => {\n toggleSafeLinkModal({ url: undefined });\n }, [toggleSafeLinkModal]);\n\n const renderingUrl = useCurrentOrPrev(url);\n\n return (\n <ConfirmDialog\n isOpen={Boolean(url)}\n onClose={handleDismiss}\n title={lang('OpenUrlTitle')}\n textParts={renderText(lang('OpenUrlAlert2', renderingUrl), ['links'])}\n confirmLabel={lang('OpenUrlTitle')}\n confirmHandler={handleOpen}\n />\n );\n};\n\nexport default memo(withGlobal<OwnProps>(\n undefined,\n (setGlobal, actions): DispatchProps => pick(actions, ['toggleSafeLinkModal']),\n)(SafeLinkModal));\n","import React, {\n FC, memo, useState, useEffect, useMemo, useCallback,\n} from '../../lib/teact/teact';\n\nimport buildClassName from '../../util/buildClassName';\nimport {\n formatMonthAndYear, formatHumanDate, formatTime,\n} from '../../util/dateFormat';\nimport { IS_MOBILE_SCREEN } from '../../util/environment';\nimport useLang, { LangFn } from '../../hooks/useLang';\n\nimport Modal from '../ui/Modal';\nimport Button from '../ui/Button';\n\nimport './CalendarModal.scss';\n\nexport type OwnProps = {\n selectedAt?: number;\n maxAt?: number;\n isFutureMode?: boolean;\n isPastMode?: boolean;\n isOpen: boolean;\n withTimePicker?: boolean;\n submitButtonLabel?: string;\n secondButtonLabel?: string;\n onClose: () => void;\n onSubmit: (date: Date) => void;\n onSecondButtonClick?: NoneToVoidFunction;\n};\n\nconst WEEKDAY_LETTERS = ['M', 'T', 'W', 'T', 'F', 'S', 'S'];\n\nconst CalendarModal: FC<OwnProps> = ({\n selectedAt,\n maxAt,\n isFutureMode,\n isPastMode,\n isOpen,\n withTimePicker,\n submitButtonLabel,\n secondButtonLabel,\n onClose,\n onSubmit,\n onSecondButtonClick,\n}) => {\n const lang = useLang();\n const now = new Date();\n const defaultSelectedDate = useMemo(() => (selectedAt ? new Date(selectedAt) : new Date()), [selectedAt]);\n const maxDate = maxAt ? new Date(maxAt) : undefined;\n\n const [selectedDate, setSelectedDate] = useState<Date>(defaultSelectedDate);\n const [selectedHours, setSelectedHours] = useState<string>(\n formatInputTime(defaultSelectedDate.getHours()),\n );\n const [selectedMinutes, setSelectedMinutes] = useState<string>(\n formatInputTime(defaultSelectedDate.getMinutes()),\n );\n\n const currentYear = selectedDate.getFullYear();\n const currentMonth = selectedDate.getMonth();\n const currentDate = selectedDate.getDate();\n\n useEffect(() => {\n if (isOpen) {\n setSelectedDate(defaultSelectedDate);\n }\n }, [isOpen, defaultSelectedDate]);\n\n const shouldDisableNextMonth = (isPastMode && currentYear >= now.getFullYear() && currentMonth >= now.getMonth())\n || (maxDate && currentYear >= maxDate.getFullYear() && currentMonth >= maxDate.getMonth());\n const shouldDisablePrevMonth = isFutureMode && currentYear <= now.getFullYear() && currentMonth <= now.getMonth();\n\n const calendarGrid = useMemo(() => (\n buildCalendarGrid(currentYear, currentMonth)\n ), [currentMonth, currentYear]);\n\n function handlePrevMonth() {\n setSelectedDate((d) => {\n const dateCopy = new Date(d);\n dateCopy.setMonth(dateCopy.getMonth() - 1);\n\n return dateCopy;\n });\n }\n\n function handleNextMonth() {\n setSelectedDate((d) => {\n const dateCopy = new Date(d);\n dateCopy.setMonth(dateCopy.getMonth() + 1);\n\n return dateCopy;\n });\n }\n\n function handleDateSelect(date: number) {\n setSelectedDate((d) => {\n const dateCopy = new Date(d);\n dateCopy.setDate(date);\n\n return dateCopy;\n });\n }\n\n function handleSubmit() {\n onSubmit(selectedDate);\n }\n\n const handleChangeHours = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {\n const value = e.target.value.replace(/[^\\d]+/g, '');\n if (!value.length) {\n setSelectedHours('');\n e.target.value = '';\n return;\n }\n\n const hours = Math.max(0, Math.min(Number(value), 23));\n\n const date = new Date(selectedDate.getTime());\n date.setHours(hours);\n setSelectedDate(date);\n\n const hoursStr = formatInputTime(hours);\n setSelectedHours(hoursStr);\n e.target.value = hoursStr;\n }, [selectedDate]);\n\n const handleChangeMinutes = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {\n const value = e.target.value.replace(/[^\\d]+/g, '');\n if (!value.length) {\n setSelectedMinutes('');\n e.target.value = '';\n return;\n }\n\n const minutes = Math.max(0, Math.min(Number(value), 59));\n\n const date = new Date(selectedDate.getTime());\n date.setMinutes(minutes);\n setSelectedDate(date);\n\n const minutesStr = formatInputTime(minutes);\n setSelectedMinutes(minutesStr);\n e.target.value = minutesStr;\n }, [selectedDate]);\n\n function renderTimePicker() {\n return (\n <div className=\"timepicker\">\n <input\n type=\"text\"\n className=\"form-control\"\n inputMode=\"decimal\"\n value={selectedHours}\n onChange={handleChangeHours}\n />\n :\n <input\n type=\"text\"\n className=\"form-control\"\n inputMode=\"decimal\"\n value={selectedMinutes}\n onChange={handleChangeMinutes}\n />\n </div>\n );\n }\n\n return (\n <Modal\n isOpen={isOpen}\n onClose={onClose}\n className=\"CalendarModal\"\n >\n <div className=\"container\">\n <div className=\"month-selector\">\n <Button\n round\n size=\"smaller\"\n color=\"translucent\"\n onClick={onClose}\n >\n <i className=\"icon-close\" />\n </Button>\n\n <h4>\n {formatMonthAndYear(lang, selectedDate, IS_MOBILE_SCREEN)}\n </h4>\n\n <Button\n round\n size=\"smaller\"\n color=\"translucent\"\n disabled={shouldDisablePrevMonth}\n onClick={!shouldDisablePrevMonth ? handlePrevMonth : undefined}\n >\n <i className=\"icon-previous\" />\n </Button>\n\n <Button\n round\n size=\"smaller\"\n color=\"translucent\"\n disabled={shouldDisableNextMonth}\n onClick={!shouldDisableNextMonth ? handleNextMonth : undefined}\n >\n <i className=\"icon-next\" />\n </Button>\n </div>\n </div>\n\n <div className=\"calendar-wrapper\">\n <div className=\"calendar-grid\">\n {WEEKDAY_LETTERS.map((letter) => (\n <div className=\"day-button faded weekday\">\n <span>{letter}</span>\n </div>\n ))}\n {calendarGrid.map((gridDate) => (\n <div\n role=\"button\"\n tabIndex={0}\n onClick={() => handleDateSelect(gridDate)}\n className={buildClassName(\n 'day-button',\n isDisabledDay(\n currentYear, currentMonth, gridDate, isFutureMode ? now : undefined, isPastMode ? now : maxDate,\n )\n ? 'disabled'\n : `${gridDate ? 'clickable' : ''}`,\n gridDate === currentDate && 'selected',\n )}\n >\n {!!gridDate && (\n <span>{gridDate}</span>\n )}\n </div>\n ))}\n </div>\n </div>\n\n {withTimePicker && renderTimePicker()}\n\n <div className=\"footer\">\n <Button onClick={handleSubmit}>\n {withTimePicker ? formatSubmitLabel(lang, selectedDate) : submitButtonLabel}\n </Button>\n {secondButtonLabel && (\n <Button onClick={onSecondButtonClick} isText>\n {secondButtonLabel}\n </Button>\n )}\n </div>\n </Modal>\n );\n};\n\nfunction buildCalendarGrid(year: number, month: number) {\n const grid: number[] = [];\n\n const date = new Date();\n date.setFullYear(year);\n date.setMonth(month);\n date.setDate(1);\n\n const monthStartDay = date.getDay();\n // Fill empty cells\n for (let i = 1; i < monthStartDay; i++) {\n grid.push(0);\n }\n\n while (date.getMonth() === month) {\n const gridDate = date.getDate();\n grid.push(gridDate);\n date.setDate(gridDate + 1);\n }\n\n return grid;\n}\n\nfunction isDisabledDay(year: number, month: number, day: number, minDate?: Date, maxDate?: Date) {\n const selectedDay = new Date(year, month, day, 0, 0, 0, 0);\n const fixedMinDate = minDate && new Date(minDate.getFullYear(), minDate.getMonth(), minDate.getDate(), 0, 0, 0, 0);\n const fixedMaxDate = maxDate && new Date(maxDate.getFullYear(), maxDate.getMonth(), maxDate.getDate(), 0, 0, 0, 0);\n\n if (fixedMaxDate && selectedDay > fixedMaxDate) {\n return true;\n } else if (fixedMinDate && selectedDay < fixedMinDate) {\n return true;\n }\n\n return false;\n}\n\nfunction formatInputTime(value: string | number) {\n return String(value).padStart(2, '0');\n}\n\nfunction formatSubmitLabel(lang: LangFn, date: Date) {\n const day = formatHumanDate(lang, date, true);\n\n if (day === 'Today') {\n return lang('Conversation.ScheduleMessage.SendToday', formatTime(date));\n }\n\n return lang('Conversation.ScheduleMessage.SendOn', day).replace('%@', formatTime(date));\n}\n\nexport default memo(CalendarModal);\n","import React, { FC, memo, useCallback } from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../global/types';\n\nimport { pick } from '../../util/iteratees';\nimport useLang from '../../hooks/useLang';\n\nimport CalendarModal from '../common/CalendarModal';\n\nexport type OwnProps = {\n isOpen: boolean;\n};\n\ntype StateProps = {\n selectedAt?: number;\n};\n\ntype DispatchProps = Pick<GlobalActions, 'searchMessagesByDate' | 'closeHistoryCalendar'>;\n\nconst HistoryCalendar: FC<OwnProps & StateProps & DispatchProps> = ({\n isOpen, selectedAt, searchMessagesByDate, closeHistoryCalendar,\n}) => {\n const handleJumpToDate = useCallback((date: Date) => {\n searchMessagesByDate({ timestamp: date.valueOf() / 1000 });\n closeHistoryCalendar();\n }, [closeHistoryCalendar, searchMessagesByDate]);\n\n const lang = useLang();\n\n return (\n <CalendarModal\n isOpen={isOpen}\n selectedAt={selectedAt}\n isPastMode\n submitButtonLabel={lang('JumpToDate')}\n onClose={closeHistoryCalendar}\n onSubmit={handleJumpToDate}\n />\n );\n};\n\nexport default memo(withGlobal<OwnProps>(\n (global): StateProps => {\n return {\n selectedAt: global.historyCalendarSelectedAt,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'searchMessagesByDate', 'closeHistoryCalendar',\n ]),\n)(HistoryCalendar));\n","import React, { FC, useCallback, memo } from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { ApiMessage } from '../../api/types';\nimport { IAlbum } from '../../types';\n\nimport { GlobalActions } from '../../global/types';\n\nimport {\n selectAllowedMessageActions,\n selectChat,\n selectCurrentMessageList,\n selectUser,\n} from '../../modules/selectors';\nimport {\n isChatPrivate,\n getUserFirstOrLastName,\n getPrivateChatUserId,\n isChatBasicGroup,\n isChatSuperGroup,\n} from '../../modules/helpers';\nimport renderText from './helpers/renderText';\nimport { pick } from '../../util/iteratees';\nimport useLang from '../../hooks/useLang';\n\nimport Modal from '../ui/Modal';\nimport Button from '../ui/Button';\n\nexport type OwnProps = {\n isOpen: boolean;\n isSchedule: boolean;\n message: ApiMessage;\n album?: IAlbum;\n onClose: () => void;\n};\n\ntype StateProps = {\n canDeleteForAll?: boolean;\n contactName?: string;\n willDeleteForCurrentUserOnly?: boolean;\n willDeleteForAll?: boolean;\n};\n\ntype DispatchProps = Pick<GlobalActions, 'deleteMessages' | 'deleteScheduledMessages'>;\n\nconst DeleteMessageModal: FC<OwnProps & StateProps & DispatchProps> = ({\n isOpen,\n isSchedule,\n message,\n album,\n canDeleteForAll,\n contactName,\n willDeleteForCurrentUserOnly,\n willDeleteForAll,\n onClose,\n deleteMessages,\n deleteScheduledMessages,\n}) => {\n const handleDeleteMessageForAll = useCallback(() => {\n const messageIds = album && album.messages\n ? album.messages.map(({ id }) => id)\n : [message.id];\n deleteMessages({ messageIds, shouldDeleteForAll: true });\n onClose();\n }, [deleteMessages, message.id, onClose, album]);\n\n const handleDeleteMessageForSelf = useCallback(() => {\n const messageIds = album && album.messages\n ? album.messages.map(({ id }) => id)\n : [message.id];\n if (isSchedule) {\n deleteScheduledMessages({ messageIds });\n } else {\n deleteMessages({\n messageIds,\n shouldDeleteForAll: false,\n });\n }\n onClose();\n }, [album, message.id, isSchedule, onClose, deleteScheduledMessages, deleteMessages]);\n\n const lang = useLang();\n\n return (\n <Modal\n isOpen={isOpen}\n onClose={onClose}\n onEnter={isOpen && !canDeleteForAll ? handleDeleteMessageForSelf : undefined}\n className=\"delete\"\n title={lang('DeleteSingleMessagesTitle')}\n >\n <p>{lang('AreYouSureDeleteSingleMessage')}</p>\n {willDeleteForCurrentUserOnly && (\n <p>{lang('lng_delete_for_me_chat_hint')}</p>\n )}\n {willDeleteForAll && (\n <p>{lang('lng_delete_for_everyone_hint', 1, 'i')}</p>\n )}\n {canDeleteForAll && (\n <Button color=\"danger\" className=\"confirm-dialog-button\" isText onClick={handleDeleteMessageForAll}>\n {contactName && lang('Conversation.DeleteMessagesFor', renderText(contactName))}\n {!contactName && lang('Conversation.DeleteMessagesForEveryone')}\n </Button>\n )}\n <Button color=\"danger\" className=\"confirm-dialog-button\" isText onClick={handleDeleteMessageForSelf}>\n {lang(canDeleteForAll ? 'ChatList.DeleteForCurrentUser' : 'Delete')}\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, { message, isSchedule }): StateProps => {\n const { threadId } = selectCurrentMessageList(global) || {};\n const { canDeleteForAll } = (threadId && selectAllowedMessageActions(global, message, threadId)) || {};\n const chat = selectChat(global, message.chatId);\n const contactName = chat && isChatPrivate(chat.id)\n ? getUserFirstOrLastName(selectUser(global, getPrivateChatUserId(chat)!))\n : undefined;\n\n const willDeleteForCurrentUserOnly = chat && isChatBasicGroup(chat) && !canDeleteForAll;\n const willDeleteForAll = chat && isChatSuperGroup(chat);\n\n return {\n canDeleteForAll: !isSchedule && canDeleteForAll,\n contactName,\n willDeleteForCurrentUserOnly,\n willDeleteForAll,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'deleteMessages', 'deleteScheduledMessages',\n ]),\n)(DeleteMessageModal));\n","import React, { FC, useCallback, memo } from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../global/types';\n\nimport { selectChat, selectIsChatWithSelf, selectUser } from '../../modules/selectors';\nimport {\n isChatPrivate,\n getUserFirstOrLastName,\n getPrivateChatUserId,\n isChatBasicGroup,\n isChatSuperGroup,\n isChatChannel,\n} from '../../modules/helpers';\nimport { pick } from '../../util/iteratees';\nimport useLang from '../../hooks/useLang';\n\nimport Modal from '../ui/Modal';\nimport Button from '../ui/Button';\n\nexport type OwnProps = {\n isOpen: boolean;\n chatId: number;\n messageId: number;\n onClose: () => void;\n};\n\ntype StateProps = {\n isChannel: boolean;\n isPrivateChat: boolean;\n isChatWithSelf: boolean;\n isGroup: boolean;\n isSuperGroup: boolean;\n canPinForAll: boolean;\n contactName?: string;\n};\n\ntype DispatchProps = Pick<GlobalActions, 'pinMessage'>;\n\nconst PinMessageModal: FC<OwnProps & StateProps & DispatchProps> = ({\n isOpen,\n messageId,\n chatId,\n isChannel,\n isGroup,\n isSuperGroup,\n canPinForAll,\n contactName,\n onClose,\n pinMessage,\n}) => {\n const handlePinMessageForAll = useCallback(() => {\n pinMessage({\n chatId, messageId, isUnpin: false,\n });\n onClose();\n }, [pinMessage, chatId, messageId, onClose]);\n\n const handlePinMessage = useCallback(() => {\n pinMessage({\n chatId, messageId, isUnpin: false, isOneSide: true, isSilent: true,\n });\n onClose();\n }, [chatId, messageId, onClose, pinMessage]);\n\n const lang = useLang();\n\n function renderMessage() {\n if (isChannel) {\n return lang('PinMessageAlertChannel');\n }\n\n if (isGroup || isSuperGroup) {\n return lang('PinMessageAlert');\n }\n\n return lang('PinMessageAlertChat');\n }\n\n return (\n <Modal\n isOpen={isOpen}\n onClose={onClose}\n className=\"pin\"\n title={lang('PinMessageAlertTitle')}\n >\n <p>{renderMessage()}</p>\n <Button className=\"confirm-dialog-button\" isText onClick={handlePinMessage}>\n {lang('DialogPin')}\n </Button>\n {canPinForAll && (\n <Button className=\"confirm-dialog-button\" isText onClick={handlePinMessageForAll}>\n {contactName\n ? lang('Conversation.PinMessagesFor', contactName)\n : lang('Conversation.PinMessageAlert.PinAndNotifyMembers')}\n </Button>\n )}\n <Button className=\"confirm-dialog-button\" isText onClick={onClose}>{lang('Cancel')}</Button>\n </Modal>\n );\n};\n\nexport default memo(withGlobal<OwnProps>(\n (global, { chatId }): StateProps => {\n const isPrivateChat = isChatPrivate(chatId);\n const isChatWithSelf = selectIsChatWithSelf(global, chatId);\n const chat = selectChat(global, chatId);\n const isChannel = !!chat && isChatChannel(chat);\n const isGroup = !!chat && isChatBasicGroup(chat);\n const isSuperGroup = !!chat && isChatSuperGroup(chat);\n const canPinForAll = (isPrivateChat && !isChatWithSelf) || isSuperGroup || isGroup;\n const contactName = chat && isChatPrivate(chat.id)\n ? getUserFirstOrLastName(selectUser(global, getPrivateChatUserId(chat)!))\n : undefined;\n\n return {\n isPrivateChat,\n isChatWithSelf,\n isChannel,\n isGroup,\n isSuperGroup,\n canPinForAll,\n contactName,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, ['pinMessage']),\n)(PinMessageModal));\n","import React, { FC, memo } from '../../lib/teact/teact';\n\nimport useLang from '../../hooks/useLang';\n\nimport Modal from '../ui/Modal';\nimport Button from '../ui/Button';\n\nexport type OwnProps = {\n isOpen: boolean;\n chatId?: number;\n pinnedMessagesCount?: number;\n onClose: () => void;\n onUnpin: () => void;\n};\n\nconst UnpinAllMessagesModal: FC<OwnProps> = ({\n isOpen,\n pinnedMessagesCount = 0,\n onClose,\n onUnpin,\n}) => {\n const lang = useLang();\n\n return (\n <Modal\n isOpen={isOpen}\n onClose={onClose}\n className=\"unpin-all\"\n title={lang('Chat.PanelUnpinAllMessages')}\n >\n <p>{lang('Chat.UnpinAllMessagesConfirmation', pinnedMessagesCount, 'i')}</p>\n <Button className=\"confirm-dialog-button\" isText onClick={onUnpin}>\n {lang('DialogUnpin')}\n </Button>\n <Button className=\"confirm-dialog-button\" isText onClick={onClose}>{lang('Cancel')}</Button>\n </Modal>\n );\n};\n\nexport default memo(UnpinAllMessagesModal);\n","import React, { FC, useCallback, memo } from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../global/types';\n\nimport { selectCanDeleteSelectedMessages, selectCurrentChat, selectUser } from '../../modules/selectors';\nimport {\n isChatPrivate,\n getUserFirstOrLastName,\n getPrivateChatUserId,\n isChatBasicGroup,\n isChatSuperGroup,\n} from '../../modules/helpers';\nimport renderText from '../common/helpers/renderText';\nimport { pick } from '../../util/iteratees';\nimport useLang from '../../hooks/useLang';\n\nimport Modal from '../ui/Modal';\nimport Button from '../ui/Button';\n\nexport type OwnProps = {\n isOpen: boolean;\n isSchedule: boolean;\n onClose: () => void;\n};\n\ntype StateProps = {\n selectedMessageIds?: number[];\n canDeleteForAll?: boolean;\n contactName?: string;\n willDeleteForCurrentUserOnly?: boolean;\n willDeleteForAll?: boolean;\n};\n\ntype DispatchProps = Pick<GlobalActions, 'deleteMessages' | 'exitMessageSelectMode' | 'deleteScheduledMessages'>;\n\nconst DeleteSelectedMessagesModal: FC<OwnProps & StateProps & DispatchProps> = ({\n isOpen,\n isSchedule,\n selectedMessageIds,\n canDeleteForAll,\n contactName,\n willDeleteForCurrentUserOnly,\n willDeleteForAll,\n onClose,\n deleteMessages,\n deleteScheduledMessages,\n exitMessageSelectMode,\n}) => {\n const handleDeleteMessageForAll = useCallback(() => {\n deleteMessages({ messageIds: selectedMessageIds, shouldDeleteForAll: true });\n exitMessageSelectMode();\n onClose();\n }, [deleteMessages, exitMessageSelectMode, selectedMessageIds, onClose]);\n\n const handleDeleteMessageForSelf = useCallback(() => {\n if (isSchedule) {\n deleteScheduledMessages({ messageIds: selectedMessageIds });\n } else {\n deleteMessages({ messageIds: selectedMessageIds, shouldDeleteForAll: false });\n }\n\n exitMessageSelectMode();\n onClose();\n }, [\n isSchedule, exitMessageSelectMode, onClose, deleteScheduledMessages, selectedMessageIds, deleteMessages,\n ]);\n\n const lang = useLang();\n\n if (!selectedMessageIds) {\n return undefined;\n }\n\n return (\n <Modal\n isOpen={isOpen}\n onClose={onClose}\n onEnter={canDeleteForAll ? undefined : handleDeleteMessageForSelf}\n className=\"delete\"\n title={lang('Conversation.DeleteManyMessages')}\n >\n <p>{lang('AreYouSureDeleteFewMessages')}</p>\n {willDeleteForCurrentUserOnly && (\n <p>This will delete them just for you, not for other participants in the chat.</p>\n )}\n {willDeleteForAll && (\n <p>This will delete them for everyone in this chat.</p>\n )}\n {canDeleteForAll && (\n <Button color=\"danger\" className=\"confirm-dialog-button\" isText onClick={handleDeleteMessageForAll}>\n {contactName\n ? lang('ChatList.DeleteForEveryone', renderText(contactName))\n : lang('Conversation.DeleteMessagesForEveryone')}\n </Button>\n )}\n <Button color=\"danger\" className=\"confirm-dialog-button\" isText onClick={handleDeleteMessageForSelf}>\n {lang(canDeleteForAll ? 'ChatList.DeleteForCurrentUser' : 'Delete')}\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, { isSchedule }): StateProps => {\n const { messageIds: selectedMessageIds } = global.selectedMessages || {};\n const { canDeleteForAll } = selectCanDeleteSelectedMessages(global);\n const chat = selectCurrentChat(global);\n const contactName = chat && isChatPrivate(chat.id)\n ? getUserFirstOrLastName(selectUser(global, getPrivateChatUserId(chat)!))\n : undefined;\n\n const willDeleteForCurrentUserOnly = chat && isChatBasicGroup(chat) && !canDeleteForAll;\n const willDeleteForAll = chat && isChatSuperGroup(chat);\n\n return {\n selectedMessageIds,\n canDeleteForAll: !isSchedule && canDeleteForAll,\n contactName,\n willDeleteForCurrentUserOnly,\n willDeleteForAll,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'deleteMessages',\n 'deleteScheduledMessages',\n 'exitMessageSelectMode',\n ]),\n)(DeleteSelectedMessagesModal));\n","import React, { FC, memo, useEffect } from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { GlobalActions, MessageListType } from '../../global/types';\n\nimport {\n selectCanDeleteSelectedMessages,\n selectCurrentMessageList,\n selectSelectedMessagesCount,\n} from '../../modules/selectors';\nimport { pick } from '../../util/iteratees';\nimport useFlag from '../../hooks/useFlag';\nimport captureKeyboardListeners from '../../util/captureKeyboardListeners';\nimport buildClassName from '../../util/buildClassName';\nimport usePrevious from '../../hooks/usePrevious';\nimport useLang from '../../hooks/useLang';\n\nimport Button from '../ui/Button';\nimport MenuItem from '../ui/MenuItem';\n\nimport DeleteSelectedMessagesModal from './DeleteSelectedMessagesModal';\n\nimport './MessageSelectToolbar.scss';\n\nexport type OwnProps = {\n isActive?: boolean;\n canPost?: boolean;\n messageListType?: MessageListType;\n};\n\ntype StateProps = {\n isSchedule: boolean;\n selectedMessagesCount?: number;\n canDeleteMessages?: boolean;\n};\n\ntype DispatchProps = Pick<GlobalActions, 'exitMessageSelectMode' | 'openForwardMenuForSelectedMessages'>;\n\nconst MessageSelectToolbar: FC<OwnProps & StateProps & DispatchProps> = ({\n canPost,\n isActive,\n messageListType,\n isSchedule,\n selectedMessagesCount,\n canDeleteMessages,\n exitMessageSelectMode,\n openForwardMenuForSelectedMessages,\n}) => {\n const [isDeleteModalOpen, openDeleteModal, closeDeleteModal] = useFlag();\n\n useEffect(() => {\n return isActive && !isDeleteModalOpen\n ? captureKeyboardListeners({\n onBackspace: openDeleteModal,\n onDelete: openDeleteModal,\n onEsc: exitMessageSelectMode,\n })\n : undefined;\n }, [isActive, isDeleteModalOpen, openDeleteModal, exitMessageSelectMode]);\n\n const prevSelectedMessagesCount = usePrevious(selectedMessagesCount || undefined, true);\n const renderingSelectedMessagesCount = isActive ? selectedMessagesCount : prevSelectedMessagesCount;\n\n const lang = useLang();\n\n const formattedMessagesCount = lang('VoiceOver.Chat.MessagesSelected', renderingSelectedMessagesCount);\n\n const className = buildClassName(\n 'MessageSelectToolbar',\n canPost && 'with-composer',\n isActive && 'shown',\n );\n\n return (\n <div className={className}>\n <div className=\"MessageSelectToolbar-inner\">\n <Button\n color=\"translucent\"\n round\n onClick={exitMessageSelectMode}\n ariaLabel=\"Exit select mode\"\n >\n <i className=\"icon-close\" />\n </Button>\n <span className=\"MessageSelectToolbar-count\" title={formattedMessagesCount}>\n {formattedMessagesCount}\n </span>\n\n {!!selectedMessagesCount && (\n <div className=\"MessageSelectToolbar-actions\">\n {messageListType !== 'scheduled' && (\n <MenuItem\n icon=\"forward\"\n ariaLabel=\"Forward Messages\"\n onClick={openForwardMenuForSelectedMessages}\n >\n <span className=\"item-text\">\n {lang('Forward')}\n </span>\n </MenuItem>\n )}\n <MenuItem\n destructive\n icon=\"delete\"\n onClick={openDeleteModal}\n disabled={!canDeleteMessages}\n ariaLabel={lang('EditAdminGroupDeleteMessages')}\n >\n <span className=\"item-text\">\n {lang('Delete')}\n </span>\n </MenuItem>\n </div>\n )}\n </div>\n <DeleteSelectedMessagesModal\n isOpen={isDeleteModalOpen}\n isSchedule={isSchedule}\n onClose={closeDeleteModal}\n />\n </div>\n );\n};\n\nexport default memo(withGlobal<OwnProps>(\n (global): StateProps => {\n const { type: messageListType } = selectCurrentMessageList(global) || {};\n const { canDelete } = selectCanDeleteSelectedMessages(global);\n\n return {\n isSchedule: messageListType === 'scheduled',\n selectedMessagesCount: selectSelectedMessagesCount(global),\n canDeleteMessages: canDelete,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, ['exitMessageSelectMode', 'openForwardMenuForSelectedMessages']),\n)(MessageSelectToolbar));\n","import { useCallback, useEffect, useRef } from '../lib/teact/teact';\n\nexport default (\n onSelect: NoneToVoidFunction,\n) => {\n // eslint-disable-next-line no-null/no-null\n const buttonRef = useRef<HTMLDivElement>(null);\n\n const handleKeyDown = useCallback((e: KeyboardEvent) => {\n if (e.key !== 'Enter') return;\n const isFocused = buttonRef.current === document.activeElement;\n\n if (isFocused) {\n onSelect();\n }\n }, [onSelect]);\n\n useEffect(() => {\n window.addEventListener('keydown', handleKeyDown, false);\n\n return () => window.removeEventListener('keydown', handleKeyDown);\n }, [handleKeyDown]);\n\n return buttonRef;\n};\n","import React, {\n FC, memo,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { ApiChat, ApiUser } from '../../../api/types';\n\nimport useChatContextActions from '../../../hooks/useChatContextActions';\nimport useFlag from '../../../hooks/useFlag';\nimport { isChatPrivate, getPrivateChatUserId } from '../../../modules/helpers';\nimport { selectChat, selectUser, selectIsChatPinned } from '../../../modules/selectors';\nimport useSelectWithEnter from '../../../hooks/useSelectWithEnter';\n\nimport PrivateChatInfo from '../../common/PrivateChatInfo';\nimport GroupChatInfo from '../../common/GroupChatInfo';\nimport DeleteChatModal from '../../common/DeleteChatModal';\nimport ListItem from '../../ui/ListItem';\n\ntype OwnProps = {\n chatId: number;\n withUsername?: boolean;\n onClick: (id: number) => void;\n};\n\ntype StateProps = {\n chat?: ApiChat;\n privateChatUser?: ApiUser;\n isPinned?: boolean;\n};\n\nconst LeftSearchResultChat: FC<OwnProps & StateProps> = ({\n chatId,\n chat,\n privateChatUser,\n isPinned,\n withUsername,\n onClick,\n}) => {\n const [isDeleteModalOpen, openDeleteModal, closeDeleteModal] = useFlag();\n\n const contextActions = useChatContextActions({\n chat,\n privateChatUser,\n isPinned,\n handleDelete: openDeleteModal,\n });\n\n const handleClick = () => {\n onClick(chatId);\n };\n\n const buttonRef = useSelectWithEnter(handleClick);\n\n if (!chat) {\n return undefined;\n }\n\n return (\n <ListItem\n className=\"chat-item-clickable search-result\"\n onClick={handleClick}\n contextActions={contextActions}\n buttonRef={buttonRef}\n >\n {isChatPrivate(chatId) ? (\n <PrivateChatInfo userId={chatId} withUsername={withUsername} avatarSize=\"large\" />\n ) : (\n <GroupChatInfo chatId={chatId} withUsername={withUsername} avatarSize=\"large\" />\n )}\n <DeleteChatModal\n isOpen={isDeleteModalOpen}\n onClose={closeDeleteModal}\n chat={chat}\n />\n </ListItem>\n );\n};\n\nexport default memo(withGlobal<OwnProps>(\n (global, { chatId }): StateProps => {\n const chat = selectChat(global, chatId);\n const privateChatUserId = chat && getPrivateChatUserId(chat);\n const privateChatUser = privateChatUserId ? selectUser(global, privateChatUserId) : undefined;\n const isPinned = selectIsChatPinned(global, chatId);\n\n return {\n chat,\n privateChatUser,\n isPinned,\n };\n },\n)(LeftSearchResultChat));\n","import React, {\n FC, useEffect, useCallback, useRef, memo,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../../global/types';\nimport { ApiUser } from '../../../api/types';\n\nimport { getUserFirstOrLastName } from '../../../modules/helpers';\nimport renderText from '../../common/helpers/renderText';\nimport { throttle } from '../../../util/schedulers';\nimport { pick } from '../../../util/iteratees';\nimport useHorizontalScroll from '../../../hooks/useHorizontalScroll';\nimport useLang from '../../../hooks/useLang';\n\nimport Avatar from '../../common/Avatar';\nimport Button from '../../ui/Button';\nimport LeftSearchResultChat from './LeftSearchResultChat';\n\nimport './RecentContacts.scss';\n\ntype OwnProps = {\n onReset: () => void;\n};\n\ntype StateProps = {\n topUserIds?: number[];\n usersById: Record<number, ApiUser>;\n recentlyFoundChatIds?: number[];\n};\n\ntype DispatchProps = Pick<GlobalActions, (\n 'loadTopUsers' | 'loadContactList' | 'openChat' | 'addRecentlyFoundChatId' | 'clearRecentlyFoundChats'\n)>;\n\nconst SEARCH_CLOSE_TIMEOUT_MS = 250;\nconst NBSP = '\\u00A0';\n\nconst runThrottled = throttle((cb) => cb(), 60000, true);\n\nconst RecentContacts: FC<OwnProps & StateProps & DispatchProps> = ({\n topUserIds, usersById, recentlyFoundChatIds,\n onReset, loadTopUsers, loadContactList, openChat,\n addRecentlyFoundChatId, clearRecentlyFoundChats,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const topUsersRef = useRef<HTMLDivElement>(null);\n\n // Due to the parent Transition, this component never gets unmounted,\n // that's why we use throttled API call on every update.\n useEffect(() => {\n runThrottled(() => {\n loadTopUsers();\n // Loading full contact list for quick local search before user enters the query\n loadContactList();\n });\n }, [loadTopUsers, loadContactList]);\n\n useHorizontalScroll(topUsersRef, !topUserIds);\n\n const handleClick = useCallback(\n (id: number) => {\n openChat({ id });\n onReset();\n setTimeout(() => {\n addRecentlyFoundChatId({ id });\n }, SEARCH_CLOSE_TIMEOUT_MS);\n },\n [openChat, addRecentlyFoundChatId, onReset],\n );\n\n const lang = useLang();\n\n return (\n <div className=\"RecentContacts custom-scroll\">\n {topUserIds && (\n <div className=\"top-peers-section\" dir={lang.isRtl ? 'rtl' : undefined}>\n <div ref={topUsersRef} className=\"top-peers no-selection\">\n {topUserIds.map((userId) => (\n <div className=\"top-peer-item\" onClick={() => handleClick(userId)} dir={lang.isRtl ? 'rtl' : undefined}>\n <Avatar user={usersById[userId]} />\n <div className=\"top-peer-name\">{renderText(getUserFirstOrLastName(usersById[userId]) || NBSP)}</div>\n </div>\n ))}\n </div>\n </div>\n )}\n {recentlyFoundChatIds && (\n <div className=\"search-section pt-1\">\n <h3 className=\"section-heading mt-0 recent-chats-header\" dir={lang.isRtl ? 'rtl' : undefined}>\n {lang('Recent')}\n\n <Button\n round\n size=\"smaller\"\n color=\"translucent\"\n ariaLabel=\"Clear recent chats\"\n onClick={clearRecentlyFoundChats}\n isRtl={lang.isRtl}\n >\n <i className=\"icon-close\" />\n </Button>\n </h3>\n {recentlyFoundChatIds.map((id) => (\n <LeftSearchResultChat\n chatId={id}\n onClick={handleClick}\n />\n ))}\n </div>\n )}\n </div>\n );\n};\n\nexport default memo(withGlobal<OwnProps>(\n (global): StateProps => {\n const { userIds: topUserIds } = global.topPeers;\n const usersById = global.users.byId;\n const { recentlyFoundChatIds } = global.globalSearch;\n\n return {\n topUserIds,\n usersById,\n recentlyFoundChatIds,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'loadTopUsers',\n 'loadContactList',\n 'openChat',\n 'addRecentlyFoundChatId',\n 'clearRecentlyFoundChats',\n ]),\n)(RecentContacts));\n","import React, {\n FC, memo, useCallback,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../../global/types';\nimport {\n ApiChat, ApiUser, ApiMessage, ApiMessageOutgoingStatus,\n} from '../../../api/types';\n\nimport { IS_MOBILE_SCREEN } from '../../../util/environment';\nimport {\n getChatTitle,\n getPrivateChatUserId,\n getMessageMediaHash,\n getMessageSummaryText,\n getMessageMediaThumbDataUri,\n getMessageVideo,\n getMessageRoundVideo,\n} from '../../../modules/helpers';\nimport { selectChat, selectUser } from '../../../modules/selectors';\nimport renderText from '../../common/helpers/renderText';\nimport { pick } from '../../../util/iteratees';\nimport useMedia from '../../../hooks/useMedia';\nimport { formatPastTimeShort } from '../../../util/dateFormat';\nimport useLang, { LangFn } from '../../../hooks/useLang';\nimport useSelectWithEnter from '../../../hooks/useSelectWithEnter';\n\nimport Avatar from '../../common/Avatar';\nimport VerifiedIcon from '../../common/VerifiedIcon';\nimport ListItem from '../../ui/ListItem';\nimport Link from '../../ui/Link';\n\nimport './ChatMessage.scss';\n\ntype OwnProps = {\n searchQuery?: string;\n message: ApiMessage;\n chatId: number;\n};\n\ntype StateProps = {\n chat?: ApiChat;\n privateChatUser?: ApiUser;\n lastMessageOutgoingStatus?: ApiMessageOutgoingStatus;\n lastSyncTime?: number;\n};\n\ntype DispatchProps = Pick<GlobalActions, 'focusMessage'>;\n\nconst ChatMessage: FC<OwnProps & StateProps & DispatchProps> = ({\n message,\n searchQuery,\n chatId,\n chat,\n privateChatUser,\n focusMessage,\n lastSyncTime,\n}) => {\n const mediaThumbnail = getMessageMediaThumbDataUri(message);\n const mediaBlobUrl = useMedia(getMessageMediaHash(message, 'micro'));\n const isRoundVideo = Boolean(getMessageRoundVideo(message));\n\n const handleClick = useCallback(() => {\n focusMessage({ chatId, messageId: message.id });\n }, [chatId, focusMessage, message.id]);\n\n const lang = useLang();\n\n const buttonRef = useSelectWithEnter(handleClick);\n\n if (!chat) {\n return undefined;\n }\n\n return (\n <ListItem\n className=\"ChatMessage chat-item-clickable\"\n ripple={!IS_MOBILE_SCREEN}\n onClick={handleClick}\n buttonRef={buttonRef}\n >\n <Avatar\n chat={chat}\n user={privateChatUser}\n withOnlineStatus\n isSavedMessages={privateChatUser && privateChatUser.isSelf}\n lastSyncTime={lastSyncTime}\n />\n <div className=\"info\">\n <div className=\"info-row\">\n <div className=\"title\">\n <h3 dir=\"auto\">{renderText(getChatTitle(lang, chat, privateChatUser))}</h3>\n {chat.isVerified && <VerifiedIcon />}\n </div>\n <div className=\"message-date\">\n <Link className=\"date\">\n {formatPastTimeShort(lang, message.date * 1000)}\n </Link>\n </div>\n\n </div>\n <div className=\"subtitle\">\n <div className=\"message\" dir=\"auto\">\n {renderMessageSummary(lang, message, mediaBlobUrl || mediaThumbnail, searchQuery, isRoundVideo)}\n </div>\n </div>\n </div>\n </ListItem>\n );\n};\n\nfunction renderMessageSummary(\n lang: LangFn, message: ApiMessage, blobUrl?: string, searchQuery?: string, isRoundVideo?: boolean,\n) {\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), ['emoji', 'highlight'], { highlight: searchQuery })}\n </span>\n );\n}\n\nexport default memo(withGlobal<OwnProps>(\n (global, { chatId }): StateProps => {\n const chat = selectChat(global, chatId);\n if (!chat) {\n return {};\n }\n\n const privateChatUserId = getPrivateChatUserId(chat);\n\n return {\n chat,\n ...(privateChatUserId && { privateChatUser: selectUser(global, privateChatUserId) }),\n lastSyncTime: global.lastSyncTime,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'focusMessage',\n ]),\n)(ChatMessage));\n","import React, { FC, memo, useMemo } from '../../../lib/teact/teact';\nimport { formatDateToString } from '../../../util/dateFormat';\n\nimport './DateSuggest.scss';\n\nconst SUGGESTION_COUNT = 8;\n\nexport type OwnProps = {\n searchDate: string;\n onSelect: (value: Date) => void;\n};\n\nconst DateSuggest: FC<OwnProps> = ({\n searchDate, onSelect,\n}) => {\n const suggestions = useMemo(() => getSuggestionsFromDate(searchDate), [searchDate]);\n return (\n <section className=\"DateSuggest custom-scroll custom-scroll-x\">\n {suggestions.map(({ date, text }) => {\n return (\n <div\n onClick={() => onSelect(date)}\n className=\"date-item\"\n key={text}\n >\n <i className=\"icon-calendar\" />\n <span>{text}</span>\n </div>\n );\n })}\n </section>\n );\n};\n\nfunction getSuggestionsFromDate(searchDate: string) {\n const hasYear = searchDate.match(/^\\d{2,4}-\\d{2}-\\d{2}$/g);\n if (hasYear) {\n const date = new Date(searchDate);\n return [{ date, text: formatDateToString(date) }];\n }\n\n const suggestion = [];\n const currentDate = new Date();\n const currentYear = currentDate.getFullYear();\n const latestYear = currentDate.getTime() > (new Date(`${currentYear}-${searchDate}`)).getTime()\n ? currentYear\n : currentYear - 1;\n\n for (let i = 0; i < SUGGESTION_COUNT; i++) {\n const date = new Date(`${latestYear - i}-${searchDate}`);\n suggestion.push({ date, text: formatDateToString(date) });\n }\n\n return suggestion;\n}\n\nexport default memo(DateSuggest);\n","import React, {\n FC, memo, useCallback, useMemo, useState,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { ApiUser, ApiChat, ApiMessage } from '../../../api/types';\nimport { GlobalActions } from '../../../global/types';\nimport { LoadMoreDirection } from '../../../types';\n\nimport { IS_MOBILE_SCREEN } from '../../../util/environment';\nimport searchWords from '../../../util/searchWords';\nimport { unique, pick } from '../../../util/iteratees';\nimport { getUserFullName, getMessageSummaryText, sortChatIds } from '../../../modules/helpers';\nimport { MEMO_EMPTY_ARRAY } from '../../../util/memo';\nimport { throttle } from '../../../util/schedulers';\nimport useLang from '../../../hooks/useLang';\n\nimport InfiniteScroll from '../../ui/InfiniteScroll';\nimport LeftSearchResultChat from './LeftSearchResultChat';\nimport RecentContacts from './RecentContacts';\nimport ChatMessage from './ChatMessage';\nimport DateSuggest from './DateSuggest';\nimport Link from '../../ui/Link';\nimport NothingFound from '../../common/NothingFound';\nimport PickerSelectedItem from '../../common/PickerSelectedItem';\n\nexport type OwnProps = {\n searchQuery?: string;\n dateSearchQuery?: string;\n searchDate?: number;\n onReset: () => void;\n onSearchDateSelect: (value: Date) => void;\n};\n\ntype StateProps = {\n currentUserId?: number;\n localContactIds?: number[];\n localChatIds?: number[];\n localUserIds?: number[];\n globalChatIds?: number[];\n globalUserIds?: number[];\n foundIds?: string[];\n globalMessagesByChatId?: Record<number, { byId: Record<number, ApiMessage> }>;\n chatsById: Record<number, ApiChat>;\n usersById: Record<number, ApiUser>;\n fetchingStatus?: { chats?: boolean; messages?: boolean };\n lastSyncTime?: number;\n};\n\ntype DispatchProps = Pick<GlobalActions, (\n 'openChat' | 'addRecentlyFoundChatId' | 'searchMessagesGlobal' | 'setGlobalSearchChatId'\n)>;\n\nconst MIN_QUERY_LENGTH_FOR_GLOBAL_SEARCH = 4;\nconst LESS_LIST_ITEMS_AMOUNT = 3;\n\nconst runThrottled = throttle((cb) => cb(), 500, true);\n\nconst ChatResults: FC<OwnProps & StateProps & DispatchProps> = ({\n searchQuery, searchDate, dateSearchQuery, currentUserId,\n localContactIds, localChatIds, localUserIds, globalChatIds, globalUserIds,\n foundIds, globalMessagesByChatId, chatsById, usersById, fetchingStatus, lastSyncTime,\n onReset, onSearchDateSelect, openChat, addRecentlyFoundChatId, searchMessagesGlobal, setGlobalSearchChatId,\n}) => {\n const lang = useLang();\n\n const [shouldShowMoreLocal, setShouldShowMoreLocal] = useState<boolean>(false);\n const [shouldShowMoreGlobal, setShouldShowMoreGlobal] = useState<boolean>(false);\n\n const handleLoadMore = useCallback(({ direction }: { direction: LoadMoreDirection }) => {\n if (lastSyncTime && direction === LoadMoreDirection.Backwards) {\n runThrottled(() => {\n searchMessagesGlobal({\n type: 'text',\n query: searchQuery,\n });\n });\n }\n }, [lastSyncTime, searchMessagesGlobal, searchQuery]);\n\n const handleChatClick = useCallback(\n (id: number) => {\n openChat({ id });\n\n if (id !== currentUserId) {\n addRecentlyFoundChatId({ id });\n }\n\n if (!IS_MOBILE_SCREEN) {\n onReset();\n }\n },\n [currentUserId, openChat, addRecentlyFoundChatId, onReset],\n );\n\n const handlePickerItemClick = useCallback((id: number) => {\n setGlobalSearchChatId({ id });\n }, [setGlobalSearchChatId]);\n\n const localResults = useMemo(() => {\n if (!searchQuery || (searchQuery.startsWith('@') && searchQuery.length < 2)) {\n return MEMO_EMPTY_ARRAY;\n }\n\n const foundContactIds = localContactIds\n ? localContactIds.filter((id) => {\n const user = usersById[id];\n if (!user) {\n return false;\n }\n\n const fullName = getUserFullName(user);\n return (fullName && searchWords(fullName, searchQuery)) || searchWords(user.username, searchQuery);\n })\n : [];\n\n return [\n ...(currentUserId && searchWords(lang('SavedMessages'), searchQuery) ? [currentUserId] : []),\n ...sortChatIds(unique([\n ...foundContactIds,\n ...(localChatIds || []),\n ...(localUserIds || []),\n ]), chatsById),\n ];\n }, [searchQuery, localContactIds, currentUserId, lang, localChatIds, localUserIds, chatsById, usersById]);\n\n const globalResults = useMemo(() => {\n if (!searchQuery || searchQuery.length < MIN_QUERY_LENGTH_FOR_GLOBAL_SEARCH || !globalChatIds || !globalUserIds) {\n return MEMO_EMPTY_ARRAY;\n }\n\n return sortChatIds(unique([...globalChatIds, ...globalUserIds]), chatsById, true);\n }, [chatsById, globalChatIds, globalUserIds, searchQuery]);\n\n const foundMessages = useMemo(() => {\n if ((!searchQuery && !searchDate) || !foundIds || foundIds.length === 0) {\n return MEMO_EMPTY_ARRAY;\n }\n\n return foundIds\n .map((id) => {\n const [chatId, messageId] = id.split('_').map(Number);\n\n return (\n globalMessagesByChatId && globalMessagesByChatId[chatId] && globalMessagesByChatId[chatId].byId[messageId]\n );\n })\n .filter<ApiMessage>(Boolean as any)\n .sort((a, b) => b.date - a.date);\n }, [foundIds, globalMessagesByChatId, searchQuery, searchDate]);\n\n const handleClickShowMoreLocal = useCallback(() => {\n setShouldShowMoreLocal(!shouldShowMoreLocal);\n }, [shouldShowMoreLocal]);\n\n const handleClickShowMoreGlobal = useCallback(() => {\n setShouldShowMoreGlobal(!shouldShowMoreGlobal);\n }, [shouldShowMoreGlobal]);\n\n function renderFoundMessage(message: ApiMessage) {\n const text = getMessageSummaryText(lang, message);\n const chat = chatsById[message.chatId];\n\n if (!text || !chat) {\n return undefined;\n }\n\n return (\n <ChatMessage\n chatId={message.chatId}\n message={message}\n searchQuery={searchQuery}\n />\n );\n }\n\n const nothingFound = fetchingStatus && !fetchingStatus.chats && !fetchingStatus.messages\n && !localResults.length && !globalResults.length && !foundMessages.length;\n\n if (!searchQuery && !searchDate) {\n return <RecentContacts onReset={onReset} />;\n }\n\n return (\n <InfiniteScroll\n className=\"LeftSearch custom-scroll\"\n items={foundMessages}\n onLoadMore={handleLoadMore}\n // To prevent scroll jumps caused by delayed local results rendering\n noScrollRestoreOnTop\n noFastList\n >\n {dateSearchQuery && (\n <div className=\"chat-selection no-selection no-scrollbar\">\n <DateSuggest\n searchDate={dateSearchQuery}\n onSelect={onSearchDateSelect}\n />\n </div>\n )}\n {nothingFound && (\n <NothingFound\n text={lang('ChatList.Search.NoResults')}\n description={lang('ChatList.Search.NoResultsDescription')}\n />\n )}\n {!!localResults.length && (\n <div className=\"chat-selection no-selection no-scrollbar\" dir={lang.isRtl ? 'rtl' : undefined}>\n {localResults.map((id) => (\n <PickerSelectedItem\n chatOrUserId={id}\n onClick={handlePickerItemClick}\n clickArg={id}\n />\n ))}\n </div>\n )}\n {!!localResults.length && (\n <div className=\"search-section\">\n <h3 className=\"section-heading\" dir={lang.isRtl ? 'auto' : undefined}>\n {localResults.length > LESS_LIST_ITEMS_AMOUNT && (\n <Link onClick={handleClickShowMoreLocal}>\n {lang(shouldShowMoreLocal ? 'ChatList.Search.ShowLess' : 'ChatList.Search.ShowMore')}\n </Link>\n )}\n {lang('DialogList.SearchSectionDialogs')}\n </h3>\n {localResults.map((id, index) => {\n if (!shouldShowMoreLocal && index >= LESS_LIST_ITEMS_AMOUNT) {\n return undefined;\n }\n\n return (\n <LeftSearchResultChat\n chatId={id}\n onClick={handleChatClick}\n />\n );\n })}\n </div>\n )}\n {!!globalResults.length && (\n <div className=\"search-section\">\n <h3 className=\"section-heading\" dir={lang.isRtl ? 'auto' : undefined}>\n {globalResults.length > LESS_LIST_ITEMS_AMOUNT && (\n <Link onClick={handleClickShowMoreGlobal}>\n {lang(shouldShowMoreGlobal ? 'ChatList.Search.ShowLess' : 'ChatList.Search.ShowMore')}\n </Link>\n )}\n {lang('DialogList.SearchSectionGlobal')}\n </h3>\n {globalResults.map((id, index) => {\n if (!shouldShowMoreGlobal && index >= LESS_LIST_ITEMS_AMOUNT) {\n return undefined;\n }\n\n return (\n <LeftSearchResultChat\n chatId={id}\n withUsername\n onClick={handleChatClick}\n />\n );\n })}\n </div>\n )}\n {!!foundMessages.length && (\n <div className=\"search-section\">\n <h3 className=\"section-heading\" dir={lang.isRtl ? 'auto' : undefined}>{lang('SearchMessages')}</h3>\n {foundMessages.map(renderFoundMessage)}\n </div>\n )}\n </InfiniteScroll>\n );\n};\n\nexport default memo(withGlobal<OwnProps>(\n (global): StateProps => {\n const { byId: chatsById } = global.chats;\n const { byId: usersById } = global.users;\n\n const { userIds: localContactIds } = global.contactList || {};\n\n if (!localContactIds) {\n return {\n chatsById,\n usersById,\n };\n }\n\n const { currentUserId, messages, lastSyncTime } = global;\n const {\n fetchingStatus, globalResults, localResults, resultsByType,\n } = global.globalSearch;\n const { chatIds: globalChatIds, userIds: globalUserIds } = globalResults || {};\n const { chatIds: localChatIds, userIds: localUserIds } = localResults || {};\n const { byChatId: globalMessagesByChatId } = messages;\n const { foundIds } = (resultsByType && resultsByType.text) || {};\n\n return {\n currentUserId,\n localContactIds,\n localChatIds,\n localUserIds,\n globalChatIds,\n globalUserIds,\n foundIds,\n globalMessagesByChatId,\n chatsById,\n usersById,\n fetchingStatus,\n lastSyncTime,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'openChat',\n 'addRecentlyFoundChatId',\n 'searchMessagesGlobal',\n 'setGlobalSearchChatId',\n ]),\n)(ChatResults));\n","import React, {\n FC, memo, useCallback, useMemo,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { ApiChat, ApiMessage } from '../../../api/types';\nimport { GlobalActions } from '../../../global/types';\nimport { LoadMoreDirection } from '../../../types';\n\nimport { pick } from '../../../util/iteratees';\nimport { getMessageSummaryText } from '../../../modules/helpers';\nimport { MEMO_EMPTY_ARRAY } from '../../../util/memo';\nimport { throttle } from '../../../util/schedulers';\nimport useLang from '../../../hooks/useLang';\n\nimport InfiniteScroll from '../../ui/InfiniteScroll';\nimport ChatMessage from './ChatMessage';\nimport NothingFound from '../../common/NothingFound';\nimport DateSuggest from './DateSuggest';\n\nexport type OwnProps = {\n searchQuery?: string;\n dateSearchQuery?: string;\n onReset: () => void;\n onSearchDateSelect: (value: Date) => void;\n};\n\ntype StateProps = {\n currentUserId?: number;\n foundIds?: string[];\n globalMessagesByChatId?: Record<number, { byId: Record<number, ApiMessage> }>;\n chatsById: Record<number, ApiChat>;\n fetchingStatus?: { chats?: boolean; messages?: boolean };\n lastSyncTime?: number;\n};\n\ntype DispatchProps = Pick<GlobalActions, ('searchMessagesGlobal')>;\n\nconst runThrottled = throttle((cb) => cb(), 500, true);\n\nconst ChatMessageResults: FC<OwnProps & StateProps & DispatchProps> = ({\n searchQuery,\n currentUserId,\n dateSearchQuery,\n foundIds,\n globalMessagesByChatId,\n chatsById,\n fetchingStatus,\n lastSyncTime,\n searchMessagesGlobal,\n onSearchDateSelect,\n}) => {\n const lang = useLang();\n const handleLoadMore = useCallback(({ direction }: { direction: LoadMoreDirection }) => {\n if (lastSyncTime && direction === LoadMoreDirection.Backwards) {\n runThrottled(() => {\n searchMessagesGlobal({\n type: 'text',\n query: searchQuery,\n chatId: currentUserId,\n });\n });\n }\n }, [currentUserId, lastSyncTime, searchMessagesGlobal, searchQuery]);\n\n const foundMessages = useMemo(() => {\n if (!foundIds || foundIds.length === 0) {\n return MEMO_EMPTY_ARRAY;\n }\n\n return foundIds\n .map((id) => {\n const [chatId, messageId] = id.split('_').map(Number);\n\n return (\n globalMessagesByChatId && globalMessagesByChatId[chatId] && globalMessagesByChatId[chatId].byId[messageId]\n );\n })\n .filter<ApiMessage>(Boolean as any)\n .sort((a, b) => b.date - a.date);\n }, [foundIds, globalMessagesByChatId]);\n\n function renderFoundMessage(message: ApiMessage) {\n const text = getMessageSummaryText(lang, message);\n const chat = chatsById[message.chatId];\n\n if (!text || !chat) {\n return undefined;\n }\n\n return (\n <ChatMessage\n chatId={message.chatId}\n message={message}\n searchQuery={searchQuery}\n />\n );\n }\n\n const nothingFound = fetchingStatus && !fetchingStatus.chats && !fetchingStatus.messages && !foundMessages.length;\n\n return (\n <div className=\"LeftSearch\">\n <InfiniteScroll\n className=\"search-content custom-scroll chat-list\"\n items={foundMessages}\n onLoadMore={handleLoadMore}\n noFastList\n >\n {dateSearchQuery && (\n <div className=\"chat-selection no-selection no-scrollbar\">\n <DateSuggest\n searchDate={dateSearchQuery}\n onSelect={onSearchDateSelect}\n />\n </div>\n )}\n {nothingFound && (\n <NothingFound\n text={lang('ChatList.Search.NoResults')}\n description={lang('ChatList.Search.NoResultsDescription')}\n />\n )}\n {!!foundMessages.length && foundMessages.map(renderFoundMessage)}\n </InfiniteScroll>\n </div>\n );\n};\n\nexport default memo(withGlobal<OwnProps>(\n (global): StateProps => {\n const { byId: chatsById } = global.chats;\n const { currentUserId, messages: { byChatId: globalMessagesByChatId }, lastSyncTime } = global;\n const { fetchingStatus, resultsByType } = global.globalSearch;\n\n const { foundIds } = (resultsByType && resultsByType.text) || {};\n\n return {\n currentUserId,\n foundIds,\n globalMessagesByChatId,\n chatsById,\n fetchingStatus,\n lastSyncTime,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, ['searchMessagesGlobal']),\n)(ChatMessageResults));\n","import { GlobalState } from '../../../../global/types';\nimport {\n ApiChat, ApiGlobalMessageSearchType, ApiMessage, ApiUser,\n} from '../../../../api/types';\n\nexport type StateProps = {\n isLoading?: boolean;\n chatsById: Record<number, ApiChat>;\n usersById: Record<number, ApiUser>;\n globalMessagesByChatId?: Record<number, { byId: Record<number, ApiMessage> }>;\n foundIds?: string[];\n lastSyncTime?: number;\n searchChatId?: number;\n};\n\nexport function createMapStateToProps(type: ApiGlobalMessageSearchType) {\n return (global: GlobalState, props: any) => {\n const { byId: chatsById } = global.chats;\n const { byId: usersById } = global.users;\n const {\n fetchingStatus, resultsByType, chatId,\n } = global.globalSearch;\n\n // One component is used for two different types of results.\n // The differences between them are only in the isVoice property.\n // The rest of the search results use their own personal components.\n const currentType = type !== 'audio' ? type : (props && props.isVoice ? 'voice' : 'audio');\n\n const { byChatId: globalMessagesByChatId } = global.messages;\n const { foundIds } = (resultsByType && resultsByType[currentType]) || {};\n\n return {\n isLoading: foundIds === undefined\n || (fetchingStatus ? Boolean(fetchingStatus.chats || fetchingStatus.messages) : false),\n chatsById,\n usersById,\n globalMessagesByChatId,\n foundIds,\n searchChatId: chatId,\n lastSyncTime: global.lastSyncTime,\n };\n };\n}\n","import React, {\n FC, memo, useCallback, useMemo,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../../global/types';\nimport { LoadMoreDirection, MediaViewerOrigin } from '../../../types';\n\nimport { MEMO_EMPTY_ARRAY } from '../../../util/memo';\nimport { SLIDE_TRANSITION_DURATION } from '../../../config';\nimport { createMapStateToProps, StateProps } from './helpers/createMapStateToProps';\nimport { pick } from '../../../util/iteratees';\nimport buildClassName from '../../../util/buildClassName';\nimport { throttle } from '../../../util/schedulers';\nimport useLang from '../../../hooks/useLang';\nimport useAsyncRendering from '../../right/hooks/useAsyncRendering';\n\nimport InfiniteScroll from '../../ui/InfiniteScroll';\nimport Media from '../../common/Media';\nimport ChatMessage from './ChatMessage';\nimport NothingFound from '../../common/NothingFound';\nimport Loading from '../../ui/Loading';\n\nexport type OwnProps = {\n searchQuery?: string;\n};\n\ntype DispatchProps = Pick<GlobalActions, ('searchMessagesGlobal' | 'openMediaViewer')>;\n\nconst CURRENT_TYPE = 'media';\nconst runThrottled = throttle((cb) => cb(), 500, true);\n\nconst MediaResults: FC<OwnProps & StateProps & DispatchProps> = ({\n searchQuery,\n searchChatId,\n isLoading,\n globalMessagesByChatId,\n foundIds,\n lastSyncTime,\n searchMessagesGlobal,\n openMediaViewer,\n}) => {\n const lang = useLang();\n\n const handleLoadMore = useCallback(({ direction }: { direction: LoadMoreDirection }) => {\n if (lastSyncTime && direction === LoadMoreDirection.Backwards) {\n runThrottled(() => {\n searchMessagesGlobal({\n type: CURRENT_TYPE,\n query: searchQuery,\n chatId: searchChatId,\n });\n });\n }\n }, [lastSyncTime, searchMessagesGlobal, searchQuery, searchChatId]);\n\n const foundMessages = useMemo(() => {\n if (!foundIds || !globalMessagesByChatId) {\n return MEMO_EMPTY_ARRAY;\n }\n\n return foundIds.map((id) => {\n const [chatId, messageId] = id.split('_').map(Number);\n\n return globalMessagesByChatId[chatId] && globalMessagesByChatId[chatId].byId[messageId];\n }).filter(Boolean);\n }, [globalMessagesByChatId, foundIds]);\n\n const handleSelectMedia = useCallback((messageId: number, chatId: number) => {\n openMediaViewer({\n chatId,\n messageId,\n origin: MediaViewerOrigin.SearchResult,\n });\n }, [openMediaViewer]);\n\n function renderGallery() {\n return (\n <div className=\"media-list\" dir={lang.isRtl ? 'rtl' : undefined}>\n {foundMessages.map((message) => (\n <Media\n key={message.id}\n idPrefix=\"search-media\"\n message={message}\n onClick={handleSelectMedia}\n />\n ))}\n </div>\n );\n }\n\n function renderSearchResult() {\n return foundMessages.map((message) => (\n <ChatMessage\n key={message.id}\n chatId={message.chatId}\n message={message}\n />\n ));\n }\n\n const canRenderContents = useAsyncRendering([searchQuery], SLIDE_TRANSITION_DURATION) && !isLoading;\n const isMediaGrid = canRenderContents && foundIds && foundIds.length > 0 && !searchQuery;\n const isMessageList = canRenderContents && foundIds && foundIds.length > 0 && searchQuery;\n\n const classNames = buildClassName(\n 'search-content custom-scroll',\n isMessageList && 'chat-list',\n );\n\n return (\n <div className=\"LeftSearch\">\n <InfiniteScroll\n className={classNames}\n items={foundMessages}\n itemSelector={!searchQuery ? '.Media' : '.ListItem'}\n onLoadMore={handleLoadMore}\n noFastList\n >\n {!canRenderContents && <Loading />}\n {canRenderContents && (!foundIds || foundIds.length === 0) && (\n <NothingFound\n text={lang('ChatList.Search.NoResults')}\n description={lang('ChatList.Search.NoResultsDescription')}\n />\n )}\n {isMediaGrid && renderGallery()}\n {isMessageList && renderSearchResult()}\n </InfiniteScroll>\n </div>\n );\n};\n\nexport default memo(withGlobal<OwnProps>(\n createMapStateToProps(CURRENT_TYPE),\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'searchMessagesGlobal',\n 'openMediaViewer',\n ]),\n)(MediaResults));\n","import { ApiChat, ApiMessage, ApiUser } from '../../../../api/types';\nimport {\n getChatTitle,\n getSenderTitle,\n isChatPrivate,\n isChatGroup,\n} from '../../../../modules/helpers';\nimport { LangFn } from '../../../../hooks/useLang';\n\nexport function getSenderName(\n lang: LangFn, message: ApiMessage, chatsById: Record<number, ApiChat>, usersById: Record<number, ApiUser>,\n) {\n const { senderId } = message;\n if (!senderId) {\n return undefined;\n }\n\n const sender = isChatPrivate(senderId) ? usersById[senderId] : chatsById[senderId];\n\n let senderName = getSenderTitle(lang, sender);\n\n const chat = chatsById[message.chatId];\n if (chat) {\n if (isChatPrivate(senderId) && (sender as ApiUser).isSelf) {\n senderName = `${lang('FromYou')} → ${getChatTitle(lang, chat)}`;\n } else if (isChatGroup(chat)) {\n senderName += ` → ${getChatTitle(lang, chat)}`;\n }\n }\n\n return senderName;\n}\n","import React, {\n FC, memo, useCallback, useMemo,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../../global/types';\nimport { LoadMoreDirection } from '../../../types';\n\nimport { SLIDE_TRANSITION_DURATION } from '../../../config';\nimport { MEMO_EMPTY_ARRAY } from '../../../util/memo';\nimport { createMapStateToProps, StateProps } from './helpers/createMapStateToProps';\nimport { pick } from '../../../util/iteratees';\nimport { formatMonthAndYear, toYearMonth } from '../../../util/dateFormat';\nimport { getSenderName } from './helpers/getSenderName';\nimport { throttle } from '../../../util/schedulers';\nimport useAsyncRendering from '../../right/hooks/useAsyncRendering';\nimport useLang from '../../../hooks/useLang';\n\nimport InfiniteScroll from '../../ui/InfiniteScroll';\nimport WebLink from '../../common/WebLink';\nimport NothingFound from '../../common/NothingFound';\nimport Loading from '../../ui/Loading';\n\nexport type OwnProps = {\n searchQuery?: string;\n};\n\ntype DispatchProps = Pick<GlobalActions, ('searchMessagesGlobal' | 'focusMessage')>;\n\nconst CURRENT_TYPE = 'links';\nconst runThrottled = throttle((cb) => cb(), 500, true);\n\nconst LinkResults: FC<OwnProps & StateProps & DispatchProps> = ({\n searchQuery,\n searchChatId,\n isLoading,\n chatsById,\n usersById,\n globalMessagesByChatId,\n foundIds,\n lastSyncTime,\n searchMessagesGlobal,\n focusMessage,\n}) => {\n const lang = useLang();\n const handleLoadMore = useCallback(({ direction }: { direction: LoadMoreDirection }) => {\n if (lastSyncTime && direction === LoadMoreDirection.Backwards) {\n runThrottled(() => {\n searchMessagesGlobal({\n type: CURRENT_TYPE,\n query: searchQuery,\n chatId: searchChatId,\n });\n });\n }\n }, [lastSyncTime, searchMessagesGlobal, searchQuery, searchChatId]);\n\n const foundMessages = useMemo(() => {\n if (!foundIds || !globalMessagesByChatId) {\n return MEMO_EMPTY_ARRAY;\n }\n\n return foundIds.map((id) => {\n const [chatId, messageId] = id.split('_').map(Number);\n\n return globalMessagesByChatId[chatId] && globalMessagesByChatId[chatId].byId[messageId];\n }).filter(Boolean);\n }, [globalMessagesByChatId, foundIds]);\n\n const handleMessageFocus = useCallback((messageId: number, chatId: number) => {\n focusMessage({ chatId, messageId });\n }, [focusMessage]);\n\n function renderList() {\n return foundMessages.map((message, index) => {\n const shouldDrawDateDivider = index === 0\n || toYearMonth(message.date) !== toYearMonth(foundMessages[index - 1].date);\n return (\n <div\n className=\"ListItem\"\n dir={lang.isRtl ? 'rtl' : undefined}\n key={message.id}\n >\n {shouldDrawDateDivider && (\n <p className=\"section-heading\" dir={lang.isRtl ? 'rtl' : undefined}>\n {formatMonthAndYear(lang, new Date(message.date * 1000))}\n </p>\n )}\n <WebLink\n key={message.id}\n message={message}\n senderTitle={getSenderName(lang, message, chatsById, usersById)}\n onMessageClick={handleMessageFocus}\n />\n </div>\n );\n });\n }\n\n const canRenderContents = useAsyncRendering([searchQuery], SLIDE_TRANSITION_DURATION) && !isLoading;\n\n return (\n <div className=\"LeftSearch\">\n <InfiniteScroll\n className=\"search-content documents-list custom-scroll\"\n items={foundMessages}\n onLoadMore={handleLoadMore}\n noFastList\n >\n {!canRenderContents && <Loading />}\n {canRenderContents && (!foundIds || foundIds.length === 0) && (\n <NothingFound\n text={lang('ChatList.Search.NoResults')}\n description={lang('ChatList.Search.NoResultsDescription')}\n />\n )}\n {canRenderContents && foundIds && foundIds.length > 0 && renderList()}\n </InfiniteScroll>\n </div>\n );\n};\n\nexport default memo(withGlobal<OwnProps>(\n createMapStateToProps(CURRENT_TYPE),\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'searchMessagesGlobal',\n 'focusMessage',\n ]),\n)(LinkResults));\n","import React, {\n FC, memo, useCallback, useMemo,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { ApiMessage } from '../../../api/types';\nimport { GlobalActions } from '../../../global/types';\nimport { LoadMoreDirection } from '../../../types';\n\nimport { SLIDE_TRANSITION_DURATION } from '../../../config';\nimport { MEMO_EMPTY_ARRAY } from '../../../util/memo';\nimport { createMapStateToProps, StateProps } from './helpers/createMapStateToProps';\nimport { pick } from '../../../util/iteratees';\nimport { formatMonthAndYear, toYearMonth } from '../../../util/dateFormat';\nimport { getSenderName } from './helpers/getSenderName';\nimport { throttle } from '../../../util/schedulers';\nimport { getMessageDocument } from '../../../modules/helpers';\nimport useAsyncRendering from '../../right/hooks/useAsyncRendering';\nimport useLang from '../../../hooks/useLang';\n\nimport Document from '../../common/Document';\nimport InfiniteScroll from '../../ui/InfiniteScroll';\nimport NothingFound from '../../common/NothingFound';\nimport Loading from '../../ui/Loading';\n\nexport type OwnProps = {\n searchQuery?: string;\n};\n\ntype DispatchProps = Pick<GlobalActions, ('searchMessagesGlobal' | 'focusMessage')>;\n\nconst CURRENT_TYPE = 'documents';\nconst runThrottled = throttle((cb) => cb(), 500, true);\n\nconst FileResults: FC<OwnProps & StateProps & DispatchProps> = ({\n searchQuery,\n searchChatId,\n isLoading,\n chatsById,\n usersById,\n globalMessagesByChatId,\n foundIds,\n lastSyncTime,\n searchMessagesGlobal,\n focusMessage,\n}) => {\n const lang = useLang();\n const handleLoadMore = useCallback(({ direction }: { direction: LoadMoreDirection }) => {\n if (lastSyncTime && direction === LoadMoreDirection.Backwards) {\n runThrottled(() => {\n searchMessagesGlobal({\n type: CURRENT_TYPE,\n query: searchQuery,\n chatId: searchChatId,\n });\n });\n }\n }, [lastSyncTime, searchMessagesGlobal, searchQuery, searchChatId]);\n\n const foundMessages = useMemo(() => {\n if (!foundIds || !globalMessagesByChatId) {\n return MEMO_EMPTY_ARRAY;\n }\n\n return foundIds.map((id) => {\n const [chatId, messageId] = id.split('_').map(Number);\n const message = globalMessagesByChatId[chatId] && globalMessagesByChatId[chatId].byId[messageId];\n\n return message && getMessageDocument(message) ? message : undefined;\n }).filter(Boolean) as ApiMessage[];\n }, [globalMessagesByChatId, foundIds]);\n\n const handleMessageFocus = useCallback((messageId: number, chatId: number) => {\n focusMessage({ chatId, messageId });\n }, [focusMessage]);\n\n function renderList() {\n return foundMessages.map((message, index) => {\n const shouldDrawDateDivider = index === 0\n || toYearMonth(message.date) !== toYearMonth(foundMessages[index - 1].date);\n return (\n <div\n className=\"ListItem\"\n key={message.id}\n >\n {shouldDrawDateDivider && (\n <p className=\"section-heading\">{formatMonthAndYear(lang, new Date(message.date * 1000))}</p>\n )}\n <Document\n message={message}\n withDate\n datetime={message.date}\n smaller\n sender={getSenderName(lang, message, chatsById, usersById)}\n className=\"scroll-item\"\n onDateClick={handleMessageFocus}\n />\n </div>\n );\n });\n }\n\n const canRenderContents = useAsyncRendering([searchQuery], SLIDE_TRANSITION_DURATION) && !isLoading;\n\n return (\n <div className=\"LeftSearch\">\n <InfiniteScroll\n className=\"search-content documents-list custom-scroll\"\n items={foundMessages}\n onLoadMore={handleLoadMore}\n noFastList\n >\n {!canRenderContents && <Loading />}\n {canRenderContents && (!foundIds || foundIds.length === 0) && (\n <NothingFound\n text={lang('ChatList.Search.NoResults')}\n description={lang('ChatList.Search.NoResultsDescription')}\n />\n )}\n {canRenderContents && foundIds && foundIds.length > 0 && renderList()}\n </InfiniteScroll>\n </div>\n );\n};\n\nexport default memo(withGlobal<OwnProps>(\n createMapStateToProps(CURRENT_TYPE),\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'searchMessagesGlobal',\n 'focusMessage',\n ]),\n)(FileResults));\n","import React, {\n FC, memo, useCallback, useMemo,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../../global/types';\nimport { LoadMoreDirection } from '../../../types';\n\nimport { SLIDE_TRANSITION_DURATION } from '../../../config';\nimport { MEMO_EMPTY_ARRAY } from '../../../util/memo';\nimport { createMapStateToProps, StateProps } from './helpers/createMapStateToProps';\nimport { pick } from '../../../util/iteratees';\nimport { formatMonthAndYear, toYearMonth } from '../../../util/dateFormat';\nimport { getSenderName } from './helpers/getSenderName';\nimport { throttle } from '../../../util/schedulers';\nimport useAsyncRendering from '../../right/hooks/useAsyncRendering';\nimport useLang from '../../../hooks/useLang';\n\nimport InfiniteScroll from '../../ui/InfiniteScroll';\nimport Audio from '../../common/Audio';\nimport NothingFound from '../../common/NothingFound';\nimport Loading from '../../ui/Loading';\n\nexport type OwnProps = {\n isVoice?: boolean;\n searchQuery?: string;\n};\n\ntype DispatchProps = Pick<GlobalActions, ('searchMessagesGlobal' | 'focusMessage' | 'openAudioPlayer')>;\n\nconst runThrottled = throttle((cb) => cb(), 500, true);\n\nconst AudioResults: FC<OwnProps & StateProps & DispatchProps> = ({\n isVoice,\n searchQuery,\n searchChatId,\n isLoading,\n chatsById,\n usersById,\n globalMessagesByChatId,\n foundIds,\n lastSyncTime,\n searchMessagesGlobal,\n focusMessage,\n openAudioPlayer,\n}) => {\n const lang = useLang();\n const currentType = isVoice ? 'voice' : 'audio';\n const handleLoadMore = useCallback(({ direction }: { direction: LoadMoreDirection }) => {\n if (lastSyncTime && direction === LoadMoreDirection.Backwards) {\n runThrottled(() => {\n searchMessagesGlobal({\n type: currentType,\n query: searchQuery,\n chatId: searchChatId,\n });\n });\n }\n }, [currentType, lastSyncTime, searchMessagesGlobal, searchQuery, searchChatId]);\n\n const foundMessages = useMemo(() => {\n if (!foundIds || !globalMessagesByChatId) {\n return MEMO_EMPTY_ARRAY;\n }\n\n return foundIds.map((id) => {\n const [chatId, messageId] = id.split('_').map(Number);\n\n return globalMessagesByChatId[chatId] && globalMessagesByChatId[chatId].byId[messageId];\n }).filter(Boolean);\n }, [globalMessagesByChatId, foundIds]);\n\n const handleMessageFocus = useCallback((messageId: number, chatId: number) => {\n focusMessage({ chatId, messageId });\n }, [focusMessage]);\n\n const handlePlayAudio = useCallback((messageId: number, chatId: number) => {\n openAudioPlayer({ chatId, messageId });\n }, [openAudioPlayer]);\n\n function renderList() {\n return foundMessages.map((message, index) => {\n const shouldDrawDateDivider = index === 0\n || toYearMonth(message.date) !== toYearMonth(foundMessages[index - 1].date);\n return (\n <div\n className=\"ListItem\"\n key={message.id}\n >\n {shouldDrawDateDivider && (\n <p className=\"section-heading\" dir={lang.isRtl ? 'rtl' : undefined}>\n {formatMonthAndYear(lang, new Date(message.date * 1000))}\n </p>\n )}\n <Audio\n key={message.id}\n message={message}\n renderingFor=\"searchResult\"\n senderTitle={getSenderName(lang, message, chatsById, usersById)}\n date={message.date}\n lastSyncTime={lastSyncTime}\n className=\"scroll-item\"\n onPlay={handlePlayAudio}\n onDateClick={handleMessageFocus}\n />\n </div>\n );\n });\n }\n\n const canRenderContents = useAsyncRendering([searchQuery], SLIDE_TRANSITION_DURATION) && !isLoading;\n\n return (\n <div className=\"LeftSearch\">\n <InfiniteScroll\n className=\"search-content documents-list custom-scroll\"\n items={foundMessages}\n onLoadMore={handleLoadMore}\n noFastList\n >\n {!canRenderContents && <Loading />}\n {canRenderContents && (!foundIds || foundIds.length === 0) && (\n <NothingFound\n text={lang('ChatList.Search.NoResults')}\n description={lang('ChatList.Search.NoResultsDescription')}\n />\n )}\n {canRenderContents && foundIds && foundIds.length > 0 && renderList()}\n </InfiniteScroll>\n </div>\n );\n};\n\nexport default memo(withGlobal<OwnProps>(\n createMapStateToProps('audio'),\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'searchMessagesGlobal',\n 'focusMessage',\n 'openAudioPlayer',\n ]),\n)(AudioResults));\n","import React, {\n FC, memo, useCallback, useState, useMemo, useRef,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../../global/types';\nimport { GlobalSearchContent } from '../../../types';\n\nimport { pick } from '../../../util/iteratees';\nimport { parseDateString } from '../../../util/dateFormat';\nimport useKeyboardListNavigation from '../../../hooks/useKeyboardListNavigation';\nimport useLang from '../../../hooks/useLang';\n\nimport TabList from '../../ui/TabList';\nimport Transition from '../../ui/Transition';\nimport ChatResults from './ChatResults';\nimport UserChatResults from './ChatMessageResults';\nimport MediaResults from './MediaResults';\nimport LinkResults from './LinkResults';\nimport FileResults from './FileResults';\nimport AudioResults from './AudioResults';\n\nimport './LeftSearch.scss';\n\nexport type OwnProps = {\n searchQuery?: string;\n searchDate?: number;\n isActive: boolean;\n onReset: () => void;\n};\n\ntype StateProps = {\n currentContent?: GlobalSearchContent;\n chatId?: number;\n};\n\ntype DispatchProps = Pick<GlobalActions, ('setGlobalSearchContent' | 'setGlobalSearchDate')>;\n\nconst TABS = [\n { type: GlobalSearchContent.ChatList, title: 'SearchAllChatsShort' },\n { type: GlobalSearchContent.Media, title: 'SharedMediaTab2' },\n { type: GlobalSearchContent.Links, title: 'SharedLinksTab2' },\n { type: GlobalSearchContent.Files, title: 'SharedFilesTab2' },\n { type: GlobalSearchContent.Music, title: 'SharedMusicTab2' },\n { type: GlobalSearchContent.Voice, title: 'SharedVoiceTab2' },\n];\n\nconst CHAT_TABS = [\n { type: GlobalSearchContent.ChatList, title: 'All Messages' },\n ...TABS.slice(1),\n];\n\nconst TRANSITION_RENDER_COUNT = Object.keys(GlobalSearchContent).length / 2;\n\nconst LeftSearch: FC<OwnProps & StateProps & DispatchProps> = ({\n searchQuery,\n searchDate,\n isActive,\n currentContent = GlobalSearchContent.ChatList,\n chatId,\n setGlobalSearchContent,\n setGlobalSearchDate,\n onReset,\n}) => {\n const lang = useLang();\n const [activeTab, setActiveTab] = useState(0);\n const dateSearchQuery = useMemo(() => parseDateString(searchQuery), [searchQuery]);\n\n const handleSwitchTab = useCallback((index: number) => {\n const tab = TABS[index];\n setGlobalSearchContent({ content: tab.type });\n setActiveTab(index);\n }, [setGlobalSearchContent]);\n\n const handleSearchDateSelect = useCallback((value: Date) => {\n setGlobalSearchDate({ date: value.getTime() / 1000 });\n }, [setGlobalSearchDate]);\n\n // eslint-disable-next-line no-null/no-null\n const containerRef = useRef<HTMLDivElement>(null);\n const handleKeyDown = useKeyboardListNavigation(containerRef, isActive, undefined, '.ListItem-button', true);\n\n return (\n <div className=\"LeftSearch\" ref={containerRef} onKeyDown={handleKeyDown}>\n <TabList activeTab={activeTab} tabs={chatId ? CHAT_TABS : TABS} onSwitchTab={handleSwitchTab} />\n <Transition\n name={lang.isRtl ? 'slide-reversed' : 'slide'}\n renderCount={TRANSITION_RENDER_COUNT}\n activeKey={currentContent}\n >\n {() => {\n switch (currentContent) {\n case GlobalSearchContent.ChatList:\n if (chatId) {\n return (\n <UserChatResults\n searchQuery={searchQuery}\n dateSearchQuery={dateSearchQuery}\n onReset={onReset}\n onSearchDateSelect={handleSearchDateSelect}\n />\n );\n }\n return (\n <ChatResults\n searchQuery={searchQuery}\n searchDate={searchDate}\n dateSearchQuery={dateSearchQuery}\n onReset={onReset}\n onSearchDateSelect={handleSearchDateSelect}\n />\n );\n case GlobalSearchContent.Media:\n return <MediaResults searchQuery={searchQuery} />;\n case GlobalSearchContent.Links:\n return <LinkResults searchQuery={searchQuery} />;\n case GlobalSearchContent.Files:\n return <FileResults searchQuery={searchQuery} />;\n case GlobalSearchContent.Music:\n return (\n <AudioResults\n key=\"audio\"\n searchQuery={searchQuery}\n />\n );\n case GlobalSearchContent.Voice:\n return (\n <AudioResults\n key=\"voice\"\n isVoice\n searchQuery={searchQuery}\n />\n );\n default:\n return undefined;\n }\n }}\n </Transition>\n </div>\n );\n};\n\nexport default memo(withGlobal<OwnProps>(\n (global): StateProps => {\n const { currentContent, chatId } = global.globalSearch;\n\n return { currentContent, chatId };\n },\n (setGlobal, actions): DispatchProps => pick(actions, ['setGlobalSearchContent', 'setGlobalSearchDate']),\n)(LeftSearch));\n","import { useState, useCallback, useRef } from '../lib/teact/teact';\n\nexport type ReducerAction<Actions> = { type: Actions; payload?: any };\nexport type StateReducer<State, Actions> = (state: State, action: ReducerAction<Actions>) => State;\nexport type Dispatch<Actions> = (action: ReducerAction<Actions>) => void;\n\nexport default function useReducer<State, Actions>(\n reducer: StateReducer<State, Actions>,\n initialState: State,\n) {\n const reducerRef = useRef(reducer);\n const [state, setState] = useState<State>(initialState);\n\n const dispatch = useCallback((action: ReducerAction<Actions>) => {\n setState((currentState) => reducerRef.current(currentState, action));\n }, []);\n\n return [\n state,\n dispatch,\n ] as [State, Dispatch<Actions>];\n}\n","import useReducer, { StateReducer, Dispatch } from '../useReducer';\nimport { ApiChatFolder } from '../../api/types';\nimport { pick, omit } from '../../util/iteratees';\n\nexport type FolderChatType = {\n icon: string;\n title: string;\n key: keyof Pick<ApiChatFolder, (\n 'contacts' | 'nonContacts' | 'groups' | 'channels' | 'bots' |\n 'excludeMuted' | 'excludeArchived' | 'excludeRead'\n )>;\n};\n\nexport const INCLUDED_CHAT_TYPES: FolderChatType[] = [\n { icon: 'user', title: 'FilterContacts', key: 'contacts' },\n { icon: 'non-contacts', title: 'FilterNonContacts', key: 'nonContacts' },\n { icon: 'group', title: 'FilterGroups', key: 'groups' },\n { icon: 'channel', title: 'FilterChannels', key: 'channels' },\n { icon: 'bots', title: 'FilterBots', key: 'bots' },\n];\n\nexport const EXCLUDED_CHAT_TYPES: FolderChatType[] = [\n { icon: 'mute', title: 'FilterMuted', key: 'excludeMuted' },\n { icon: 'archive', title: 'FilterArchived', key: 'excludeArchived' },\n { icon: 'readchats', title: 'FilterRead', key: 'excludeRead' },\n];\n\nconst INCLUDE_FILTER_FIELDS: Array<keyof FolderIncludeFilters> = [\n 'includedChatIds', 'bots', 'channels', 'groups', 'contacts', 'nonContacts',\n];\nconst EXCLUDE_FILTER_FIELDS: Array<keyof FolderExcludeFilters> = [\n 'excludedChatIds', 'excludeArchived', 'excludeMuted', 'excludeRead',\n];\n\nexport function selectChatFilters(state: FoldersState, mode: 'included' | 'excluded', selectTemp?: boolean) {\n let selectedChatIds: number[] = [];\n let selectedChatTypes: FolderChatType['key'][] = [];\n\n if (mode === 'included') {\n const {\n includedChatIds,\n ...includeFilters\n } = selectTemp\n ? state.includeFilters || {}\n : pick(\n state.folder,\n INCLUDE_FILTER_FIELDS,\n );\n\n selectedChatIds = includedChatIds || [];\n selectedChatTypes = (Object.keys(includeFilters) as Array<keyof typeof includeFilters>)\n .filter((key) => Boolean(includeFilters[key]));\n } else {\n const {\n excludedChatIds,\n ...excludeFilters\n } = selectTemp\n ? state.excludeFilters || {}\n : pick(\n state.folder,\n EXCLUDE_FILTER_FIELDS,\n );\n\n selectedChatIds = excludedChatIds || [];\n selectedChatTypes = (Object.keys(excludeFilters) as Array<keyof typeof excludeFilters>)\n .filter((key) => Boolean(excludeFilters[key]));\n }\n\n return {\n selectedChatIds,\n selectedChatTypes,\n };\n}\n\nfunction getSuggestedFolderName(includeFilters?: FolderIncludeFilters) {\n if (includeFilters) {\n const {\n includedChatIds,\n ...filters\n } = includeFilters;\n\n if (\n Object.values(filters).filter(Boolean).length > 1\n || (includedChatIds && includedChatIds.length)\n ) {\n return '';\n }\n\n if (filters.bots) {\n return 'Bots';\n } else if (filters.groups) {\n return 'Groups';\n } else if (filters.channels) {\n return 'Channels';\n } else if (filters.contacts) {\n return 'Contacts';\n } else if (filters.nonContacts) {\n return 'Non-Contacts';\n }\n }\n\n return '';\n}\n\ntype FolderIncludeFilters = Pick<ApiChatFolder, (\n 'includedChatIds' | 'bots' | 'channels' | 'groups' | 'contacts' | 'nonContacts'\n)>;\ntype FolderExcludeFilters = Pick<ApiChatFolder, 'excludedChatIds' | 'excludeArchived' | 'excludeMuted' | 'excludeRead'>;\n\nexport type FoldersState = {\n mode: 'create' | 'edit';\n isLoading?: boolean;\n isTouched?: boolean;\n error?: string;\n folderId?: number;\n chatFilter: string;\n folder: Omit<ApiChatFolder, 'id' | 'description' | 'emoticon'>;\n includeFilters?: FolderIncludeFilters;\n excludeFilters?: FolderExcludeFilters;\n};\nexport type FoldersActions = (\n 'setTitle' | 'saveFilters' | 'editFolder' | 'reset' | 'setChatFilter' | 'setIsLoading' | 'setError' |\n 'editIncludeFilters' | 'editExcludeFilters' | 'setIncludeFilters' | 'setExcludeFilters'\n);\nexport type FolderEditDispatch = Dispatch<FoldersActions>;\n\nconst INITIAL_STATE: FoldersState = {\n mode: 'create',\n chatFilter: '',\n folder: {\n title: '',\n includedChatIds: [],\n excludedChatIds: [],\n },\n};\n\nconst foldersReducer: StateReducer<FoldersState, FoldersActions> = (\n state,\n action,\n) => {\n switch (action.type) {\n case 'setTitle':\n return {\n ...state,\n folder: {\n ...state.folder,\n title: action.payload,\n },\n isTouched: true,\n };\n case 'editIncludeFilters':\n return {\n ...state,\n includeFilters: pick(\n state.folder,\n INCLUDE_FILTER_FIELDS,\n ),\n };\n case 'editExcludeFilters':\n return {\n ...state,\n excludeFilters: pick(\n state.folder,\n EXCLUDE_FILTER_FIELDS,\n ),\n };\n case 'setIncludeFilters':\n return {\n ...state,\n includeFilters: action.payload,\n chatFilter: '',\n };\n case 'setExcludeFilters':\n return {\n ...state,\n excludeFilters: action.payload,\n chatFilter: '',\n };\n case 'saveFilters':\n if (state.includeFilters) {\n return {\n ...state,\n folder: {\n ...omit(state.folder, INCLUDE_FILTER_FIELDS),\n title: state.folder.title ? state.folder.title : getSuggestedFolderName(state.includeFilters),\n ...state.includeFilters,\n },\n includeFilters: undefined,\n chatFilter: '',\n isTouched: true,\n };\n } else if (state.excludeFilters) {\n return {\n ...state,\n folder: {\n ...omit(state.folder, EXCLUDE_FILTER_FIELDS),\n ...state.excludeFilters,\n },\n excludeFilters: undefined,\n chatFilter: '',\n isTouched: true,\n };\n } else {\n return state;\n }\n case 'editFolder': {\n const { id: folderId, description, ...folder } = action.payload;\n\n return {\n mode: 'edit',\n folderId,\n folder,\n chatFilter: '',\n };\n }\n case 'setChatFilter': {\n return {\n ...state,\n chatFilter: action.payload,\n };\n }\n case 'setIsLoading': {\n return {\n ...state,\n isLoading: action.payload,\n };\n }\n case 'setError': {\n return {\n ...state,\n error: action.payload,\n };\n }\n case 'reset':\n return INITIAL_STATE;\n default:\n return state;\n }\n};\n\nexport default () => {\n return useReducer(foldersReducer, INITIAL_STATE);\n};\n","import useReducer, { StateReducer, Dispatch } from '../useReducer';\n\nexport type TwoFaActions = (\n 'setCurrentPassword' | 'setPassword' | 'setHint' | 'setEmail' | 'reset'\n);\nexport type TwoFaDispatch = Dispatch<TwoFaActions>;\n\nexport type TwoFaState = {\n currentPassword: string;\n password: string;\n hint: string;\n email: string;\n};\n\nconst INITIAL_STATE: TwoFaState = {\n currentPassword: '',\n password: '',\n hint: '',\n email: '',\n};\n\nconst twoFaReducer: StateReducer<TwoFaState, TwoFaActions> = (\n state,\n action,\n) => {\n switch (action.type) {\n case 'setCurrentPassword':\n return {\n ...state,\n currentPassword: action.payload,\n };\n\n case 'setPassword':\n return {\n ...state,\n password: action.payload,\n };\n\n case 'setHint':\n return {\n ...state,\n hint: action.payload,\n };\n\n case 'setEmail':\n return {\n ...state,\n email: action.payload,\n };\n\n case 'reset':\n return INITIAL_STATE;\n\n default:\n return state;\n }\n};\n\nexport default () => {\n return useReducer(twoFaReducer, INITIAL_STATE);\n};\n","import React, {\n FC, useCallback, useMemo, memo, useState,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../../global/types';\nimport { SettingsScreens } from '../../../types';\n\nimport { IS_MOBILE_SCREEN } from '../../../util/environment';\nimport { pick } from '../../../util/iteratees';\nimport useLang from '../../../hooks/useLang';\n\nimport DropdownMenu from '../../ui/DropdownMenu';\nimport MenuItem from '../../ui/MenuItem';\nimport Button from '../../ui/Button';\nimport ConfirmDialog from '../../ui/ConfirmDialog';\n\ntype OwnProps = {\n currentScreen: SettingsScreens;\n editedFolderId?: number;\n onReset: () => void;\n onSaveFilter: () => void;\n};\n\ntype DispatchProps = Pick<GlobalActions, 'signOut' | 'deleteChatFolder'>;\n\nconst SettingsHeader: FC<OwnProps & DispatchProps> = ({\n currentScreen,\n editedFolderId,\n onReset,\n onSaveFilter,\n signOut,\n deleteChatFolder,\n}) => {\n const [isSignOutDialogOpen, setIsSignOutDialogOpen] = useState(false);\n const [isDeleteFolderDialogOpen, setIsDeleteFolderDialogOpen] = useState(false);\n\n const openSignOutConfirmation = useCallback(() => {\n setIsSignOutDialogOpen(true);\n }, []);\n\n const closeSignOutConfirmation = useCallback(() => {\n setIsSignOutDialogOpen(false);\n }, []);\n\n const openDeleteFolderConfirmation = useCallback(() => {\n setIsDeleteFolderDialogOpen(true);\n }, []);\n\n const closeDeleteFolderConfirmation = useCallback(() => {\n setIsDeleteFolderDialogOpen(false);\n }, []);\n\n const handleSignOutMessage = useCallback(() => {\n closeSignOutConfirmation();\n signOut();\n }, [closeSignOutConfirmation, signOut]);\n\n const handleDeleteFolderMessage = useCallback(() => {\n closeDeleteFolderConfirmation();\n deleteChatFolder({ id: editedFolderId });\n onReset();\n }, [editedFolderId, closeDeleteFolderConfirmation, deleteChatFolder, onReset]);\n\n const SettingsMenuButton: FC<{ onTrigger: () => void; isOpen?: boolean }> = useMemo(() => {\n return ({ onTrigger, isOpen }) => (\n <Button\n round\n ripple={!IS_MOBILE_SCREEN}\n size=\"smaller\"\n color=\"translucent\"\n className={isOpen ? 'active' : ''}\n onClick={onTrigger}\n ariaLabel=\"More actions\"\n >\n <i className=\"icon-more\" />\n </Button>\n );\n }, []);\n\n const lang = useLang();\n\n function renderHeaderContent() {\n switch (currentScreen) {\n case SettingsScreens.EditProfile:\n return <h3>{lang('lng_settings_information')}</h3>;\n case SettingsScreens.General:\n return <h3>{lang('General')}</h3>;\n case SettingsScreens.Notifications:\n return <h3>{lang('Notifications')}</h3>;\n case SettingsScreens.Privacy:\n return <h3>{lang('PrivacySettings')}</h3>;\n case SettingsScreens.Language:\n return <h3>{lang('Language')}</h3>;\n\n case SettingsScreens.GeneralChatBackground:\n return <h3>{lang('ChatBackground')}</h3>;\n case SettingsScreens.GeneralChatBackgroundColor:\n return <h3>{lang('SetColor')}</h3>;\n\n case SettingsScreens.PrivacyPhoneNumber:\n return <h3>{lang('PrivacyPhone')}</h3>;\n case SettingsScreens.PrivacyLastSeen:\n return <h3>{lang('PrivacyLastSeen')}</h3>;\n case SettingsScreens.PrivacyProfilePhoto:\n return <h3>{lang('Privacy.ProfilePhoto')}</h3>;\n case SettingsScreens.PrivacyForwarding:\n return <h3>{lang('PrivacyForwards')}</h3>;\n case SettingsScreens.PrivacyGroupChats:\n return <h3>{lang('AutodownloadGroupChats')}</h3>;\n case SettingsScreens.PrivacyPhoneNumberAllowedContacts:\n case SettingsScreens.PrivacyLastSeenAllowedContacts:\n case SettingsScreens.PrivacyProfilePhotoAllowedContacts:\n case SettingsScreens.PrivacyForwardingAllowedContacts:\n case SettingsScreens.PrivacyGroupChatsAllowedContacts:\n return <h3>{lang('AlwaysShareWith')}</h3>;\n case SettingsScreens.PrivacyPhoneNumberDeniedContacts:\n case SettingsScreens.PrivacyLastSeenDeniedContacts:\n case SettingsScreens.PrivacyProfilePhotoDeniedContacts:\n case SettingsScreens.PrivacyForwardingDeniedContacts:\n case SettingsScreens.PrivacyGroupChatsDeniedContacts:\n return <h3>{lang('NeverShareWith')}</h3>;\n\n case SettingsScreens.PrivacyActiveSessions:\n return <h3>{lang('SessionsTitle')}</h3>;\n case SettingsScreens.PrivacyBlockedUsers:\n return <h3>{lang('BlockedUsers')}</h3>;\n\n case SettingsScreens.TwoFaDisabled:\n case SettingsScreens.TwoFaEnabled:\n return <h3>{lang('TwoStepVerification')}</h3>;\n case SettingsScreens.TwoFaNewPassword:\n case SettingsScreens.TwoFaChangePasswordNew:\n case SettingsScreens.TwoFaChangePasswordConfirm:\n return <h3>{lang('EnterPassword')}</h3>;\n case SettingsScreens.TwoFaNewPasswordConfirm:\n return <h3>{lang('PleaseReEnterPassword')}</h3>;\n case SettingsScreens.TwoFaNewPasswordHint:\n case SettingsScreens.TwoFaChangePasswordHint:\n return <h3>{lang('PasswordHint')}</h3>;\n case SettingsScreens.TwoFaNewPasswordEmail:\n case SettingsScreens.TwoFaRecoveryEmail:\n return <h3>{lang('RecoveryEmailTitle')}</h3>;\n case SettingsScreens.TwoFaNewPasswordEmailCode:\n case SettingsScreens.TwoFaRecoveryEmailCode:\n return <h3>Recovery Email Code</h3>;\n case SettingsScreens.TwoFaCongratulations:\n return <h3>{lang('TwoStepVerificationPasswordSet')}</h3>;\n case SettingsScreens.TwoFaChangePasswordCurrent:\n case SettingsScreens.TwoFaTurnOff:\n case SettingsScreens.TwoFaRecoveryEmailCurrentPassword:\n return <h3>{lang('PleaseEnterCurrentPassword')}</h3>;\n\n case SettingsScreens.Folders:\n return <h3>{lang('Filters')}</h3>;\n case SettingsScreens.FoldersCreateFolder:\n return <h3>{lang('FilterNew')}</h3>;\n case SettingsScreens.FoldersEditFolder:\n return (\n <div className=\"settings-main-header\">\n <h3>{lang('FilterEdit')}</h3>\n\n {editedFolderId && (\n <DropdownMenu\n className=\"settings-more-menu\"\n trigger={SettingsMenuButton}\n positionX=\"right\"\n >\n <MenuItem icon=\"delete\" destructive onClick={openDeleteFolderConfirmation}>\n Delete Folder\n </MenuItem>\n </DropdownMenu>\n )}\n </div>\n );\n case SettingsScreens.FoldersIncludedChats:\n case SettingsScreens.FoldersExcludedChats:\n return (\n <div className=\"settings-main-header\">\n {currentScreen === SettingsScreens.FoldersIncludedChats ? (\n <h3>{lang('FilterInclude')}</h3>\n ) : (\n <h3>{lang('FilterExclude')}</h3>\n )}\n\n <Button\n round\n size=\"smaller\"\n color=\"translucent\"\n className=\"color-primary\"\n onClick={onSaveFilter}\n ariaLabel={lang('AutoDeleteConfirm')}\n >\n <i className=\"icon-check\" />\n </Button>\n </div>\n );\n\n default:\n return (\n <div className=\"settings-main-header\">\n <h3>{lang('SETTINGS')}</h3>\n\n <DropdownMenu\n className=\"settings-more-menu\"\n trigger={SettingsMenuButton}\n positionX=\"right\"\n >\n <MenuItem icon=\"logout\" onClick={openSignOutConfirmation}>{lang('LogOutTitle')}</MenuItem>\n </DropdownMenu>\n </div>\n );\n }\n }\n\n return (\n <div className=\"left-header\">\n <Button\n round\n size=\"smaller\"\n color=\"translucent\"\n onClick={onReset}\n ariaLabel={lang('AccDescrGoBack')}\n >\n <i className=\"icon-arrow-left\" />\n </Button>\n {renderHeaderContent()}\n <ConfirmDialog\n isOpen={isSignOutDialogOpen}\n onClose={closeSignOutConfirmation}\n text=\"Are you sure you want to log out?\"\n confirmLabel=\"Log Out\"\n confirmHandler={handleSignOutMessage}\n confirmIsDestructive\n />\n <ConfirmDialog\n isOpen={isDeleteFolderDialogOpen}\n onClose={closeDeleteFolderConfirmation}\n text=\"Are you sure you want to delete this folder?\"\n confirmLabel=\"Delete\"\n confirmHandler={handleDeleteFolderMessage}\n confirmIsDestructive\n />\n </div>\n );\n};\n\nexport default memo(withGlobal<OwnProps>(\n undefined,\n (setGlobal, actions): DispatchProps => pick(actions, ['signOut', 'deleteChatFolder']),\n)(SettingsHeader));\n","import React, { FC, memo } from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { SettingsScreens } from '../../../types';\nimport { ApiUser } from '../../../api/types';\n\nimport { selectUser } from '../../../modules/selectors';\nimport { getUserFullName } from '../../../modules/helpers';\nimport { formatPhoneNumberWithCode } from '../../../util/phoneNumber';\nimport useLang from '../../../hooks/useLang';\n\nimport ListItem from '../../ui/ListItem';\nimport Avatar from '../../common/Avatar';\n\ntype OwnProps = {\n onScreenSelect: (screen: SettingsScreens) => void;\n};\n\ntype StateProps = {\n currentUser?: ApiUser;\n};\n\nconst SettingsMain: FC<OwnProps & StateProps> = ({\n onScreenSelect,\n currentUser,\n}) => {\n const lang = useLang();\n\n return (\n <div className=\"settings-content custom-scroll\">\n <div className=\"settings-main-menu\">\n {currentUser && (\n <div className=\"settings-current-user\">\n <Avatar user={currentUser} size=\"jumbo\" />\n <p className=\"name\">{getUserFullName(currentUser)}</p>\n <p className=\"phone\">{formatPhoneNumberWithCode(currentUser.phoneNumber)}</p>\n </div>\n )}\n <ListItem\n icon=\"edit\"\n onClick={() => onScreenSelect(SettingsScreens.EditProfile)}\n >\n {lang('lng_settings_information')}\n </ListItem>\n <ListItem\n icon=\"folder\"\n onClick={() => onScreenSelect(SettingsScreens.Folders)}\n >\n {lang('Filters')}\n </ListItem>\n <ListItem\n icon=\"settings\"\n onClick={() => onScreenSelect(SettingsScreens.General)}\n >\n {lang('Telegram.GeneralSettingsViewController')}\n </ListItem>\n <ListItem\n icon=\"unmute\"\n onClick={() => onScreenSelect(SettingsScreens.Notifications)}\n >\n {lang('Notifications')}\n </ListItem>\n <ListItem\n icon=\"lock\"\n onClick={() => onScreenSelect(SettingsScreens.Privacy)}\n >\n {lang('PrivacySettings')}\n </ListItem>\n <ListItem\n icon=\"language\"\n onClick={() => onScreenSelect(SettingsScreens.Language)}\n >\n {lang('Language')}\n </ListItem>\n </div>\n </div>\n );\n};\n\nexport default memo(withGlobal<OwnProps>(\n (global): StateProps => {\n const { currentUserId } = global;\n\n return {\n currentUser: currentUserId ? selectUser(global, currentUserId) : undefined,\n };\n },\n)(SettingsMain));\n","import React, { FC } from '../../lib/teact/teact';\n\nimport buildClassName from '../../util/buildClassName';\n\nimport Button, { OwnProps as ButtonProps } from './Button';\n\nimport './FloatingActionButton.scss';\n\ntype OwnProps = {\n isShown: boolean;\n className?: string;\n color?: ButtonProps['color'];\n ariaLabel?: ButtonProps['ariaLabel'];\n disabled?: boolean;\n onClick: () => void;\n children: any;\n};\n\nconst FloatingActionButton: FC<OwnProps> = ({\n isShown,\n className,\n color = 'primary',\n ariaLabel,\n disabled,\n onClick,\n children,\n}) => {\n const buttonClassName = buildClassName(\n 'FloatingActionButton',\n isShown && 'revealed',\n className,\n );\n\n return (\n <Button\n className={buttonClassName}\n color={color}\n round\n disabled={disabled}\n onClick={isShown && !disabled ? onClick : undefined}\n ariaLabel={ariaLabel}\n tabIndex={-1}\n >\n {children}\n </Button>\n );\n};\n\nexport default FloatingActionButton;\n","import { ChangeEvent } from 'react';\nimport React, {\n FC, useState, useCallback, memo, useEffect, useMemo,\n} from '../../lib/teact/teact';\n\nimport { debounce } from '../../util/schedulers';\nimport useLang from '../../hooks/useLang';\n\nimport InputText from '../ui/InputText';\n\ntype OwnProps = {\n currentUsername?: string;\n asLink?: boolean;\n isLoading?: boolean;\n isUsernameAvailable?: boolean;\n checkUsername: AnyToVoidFunction;\n onChange: (value: string | false) => void;\n};\n\nconst MIN_USERNAME_LENGTH = 5;\nconst MAX_USERNAME_LENGTH = 32;\nconst LINK_PREFIX = 'https://t.me/';\nconst LINK_PREFIX_REGEX = /https:\\/\\/t\\.me\\/?/i;\nconst USERNAME_REGEX = /^([a-zA-Z0-9_]+)$/;\n\nconst runDebouncedForCheckUsername = debounce((cb) => cb(), 250, false);\n\nfunction isUsernameValid(username: string) {\n return username.length >= MIN_USERNAME_LENGTH\n && username.length <= MAX_USERNAME_LENGTH\n && USERNAME_REGEX.test(username);\n}\n\nconst SettingsEditProfile: FC<OwnProps> = ({\n currentUsername,\n asLink,\n isLoading,\n isUsernameAvailable,\n checkUsername,\n onChange,\n}) => {\n const [username, setUsername] = useState(currentUsername || '');\n\n const lang = useLang();\n const langPrefix = asLink ? 'SetUrl' : 'Username';\n const label = asLink ? lang('SetUrlPlaceholder') : lang('Username');\n\n const [usernameSuccess, usernameError] = useMemo(() => {\n if (!username.length) {\n return [];\n }\n\n if (username.length < MIN_USERNAME_LENGTH) {\n return [undefined, `${label} is too short`];\n }\n if (username.length > MAX_USERNAME_LENGTH) {\n return [undefined, `${label} is too long`];\n }\n if (!USERNAME_REGEX.test(username)) {\n return [undefined, `${label} contains invalid characters`];\n }\n\n if (isUsernameAvailable === undefined) {\n return [];\n }\n\n // Variable `isUsernameAvailable` is initialized with `undefined`, so a strict false check is required\n return [\n isUsernameAvailable ? lang(`${langPrefix}Available`, 'Username') : undefined,\n isUsernameAvailable === false ? lang(`${langPrefix}InUse`) : undefined,\n ];\n }, [username, isUsernameAvailable, lang, langPrefix, label]);\n\n useEffect(() => {\n setUsername(currentUsername || '');\n }, [asLink, currentUsername]);\n\n const handleUsernameChange = useCallback((e: ChangeEvent<HTMLInputElement>) => {\n const newUsername = e.target.value.trim().replace(LINK_PREFIX_REGEX, '');\n setUsername(newUsername);\n e.target.value = `${asLink ? LINK_PREFIX : ''}${newUsername}`;\n\n const isValid = isUsernameValid(newUsername);\n\n if (isValid) {\n runDebouncedForCheckUsername(() => {\n checkUsername({ username: newUsername });\n });\n }\n\n if (onChange) {\n onChange(isValid ? newUsername : false);\n }\n }, [asLink, checkUsername, onChange]);\n\n return (\n <InputText\n value={`${asLink ? LINK_PREFIX : ''}${username}`}\n onChange={handleUsernameChange}\n label={label}\n error={usernameError}\n success={usernameSuccess}\n readOnly={isLoading}\n />\n );\n};\n\nexport default memo(SettingsEditProfile);\n","import { ChangeEvent } from 'react';\nimport React, {\n FC, useState, useCallback, memo, useEffect, useMemo,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { ApiMediaFormat } from '../../../api/types';\nimport { GlobalActions } from '../../../global/types';\nimport { ProfileEditProgress } from '../../../types';\n\nimport { throttle } from '../../../util/schedulers';\nimport { pick } from '../../../util/iteratees';\nimport { selectUser } from '../../../modules/selectors';\nimport { getChatAvatarHash } from '../../../modules/helpers';\nimport useMedia from '../../../hooks/useMedia';\nimport useLang from '../../../hooks/useLang';\n\nimport AvatarEditable from '../../ui/AvatarEditable';\nimport FloatingActionButton from '../../ui/FloatingActionButton';\nimport Spinner from '../../ui/Spinner';\nimport InputText from '../../ui/InputText';\nimport renderText from '../../common/helpers/renderText';\nimport UsernameInput from '../../common/UsernameInput';\n\ntype StateProps = {\n currentAvatarHash?: string;\n currentFirstName?: string;\n currentLastName?: string;\n currentBio?: string;\n currentUsername?: string;\n progress?: ProfileEditProgress;\n isUsernameAvailable?: boolean;\n};\n\ntype DispatchProps = Pick<GlobalActions, (\n 'loadCurrentUser' | 'updateProfile' | 'checkUsername'\n)>;\n\nconst runThrottled = throttle((cb) => cb(), 60000, true);\n\nconst MAX_BIO_LENGTH = 70;\n\nconst ERROR_FIRST_NAME_MISSING = 'Please provide your first name';\nconst ERROR_BIO_TOO_LONG = 'Bio can\\' be longer than 70 characters';\n\nconst SettingsEditProfile: FC<StateProps & DispatchProps> = ({\n currentAvatarHash,\n currentFirstName,\n currentLastName,\n currentBio,\n currentUsername,\n progress,\n isUsernameAvailable,\n loadCurrentUser,\n updateProfile,\n checkUsername,\n}) => {\n const [isUsernameTouched, setIsUsernameTouched] = useState(false);\n const [isProfileFieldsTouched, setIsProfileFieldsTouched] = useState(false);\n const [error, setError] = useState<string | undefined>();\n\n const [photo, setPhoto] = useState<File | undefined>();\n const [firstName, setFirstName] = useState(currentFirstName || '');\n const [lastName, setLastName] = useState(currentLastName || '');\n const [bio, setBio] = useState(currentBio || '');\n const [username, setUsername] = useState<string | false>(currentUsername || '');\n\n const currentAvatarBlobUrl = useMedia(currentAvatarHash, false, ApiMediaFormat.BlobUrl);\n\n const isLoading = progress === ProfileEditProgress.InProgress;\n const isUsernameError = username === false;\n\n const isSaveButtonShown = useMemo(() => {\n if (isUsernameError) {\n return false;\n }\n\n return Boolean(photo) || isProfileFieldsTouched || isUsernameAvailable === true;\n }, [photo, isProfileFieldsTouched, isUsernameError, isUsernameAvailable]);\n\n // Due to the parent Transition, this component never gets unmounted,\n // that's why we use throttled API call on every update.\n useEffect(() => {\n runThrottled(() => {\n loadCurrentUser();\n });\n }, [loadCurrentUser]);\n\n useEffect(() => {\n setPhoto(undefined);\n }, [currentAvatarBlobUrl]);\n\n useEffect(() => {\n setFirstName(currentFirstName || '');\n setLastName(currentLastName || '');\n setBio(currentBio || '');\n }, [currentFirstName, currentLastName, currentBio]);\n\n useEffect(() => {\n setUsername(currentUsername || '');\n }, [currentUsername]);\n\n useEffect(() => {\n if (progress === ProfileEditProgress.Complete) {\n setIsProfileFieldsTouched(false);\n setIsUsernameTouched(false);\n setError(undefined);\n }\n }, [progress]);\n\n const handlePhotoChange = useCallback((newPhoto: File) => {\n setPhoto(newPhoto);\n }, []);\n\n const handleFirstNameChange = useCallback((e: ChangeEvent<HTMLInputElement>) => {\n setFirstName(e.target.value);\n setIsProfileFieldsTouched(true);\n }, []);\n\n const handleLastNameChange = useCallback((e: ChangeEvent<HTMLInputElement>) => {\n setLastName(e.target.value);\n setIsProfileFieldsTouched(true);\n }, []);\n\n const handleBioChange = useCallback((e: ChangeEvent<HTMLInputElement>) => {\n setBio(e.target.value);\n setIsProfileFieldsTouched(true);\n }, []);\n\n const handleUsernameChange = useCallback((value: string | false) => {\n setUsername(value);\n setIsUsernameTouched(true);\n }, []);\n\n const handleProfileSave = useCallback(() => {\n const trimmedFirstName = firstName.trim();\n const trimmedLastName = lastName.trim();\n const trimmedBio = bio.trim();\n\n if (!trimmedFirstName.length) {\n setError(ERROR_FIRST_NAME_MISSING);\n return;\n }\n\n if (trimmedBio.length > MAX_BIO_LENGTH) {\n setError(ERROR_BIO_TOO_LONG);\n return;\n }\n\n updateProfile({\n photo,\n ...(isProfileFieldsTouched && {\n firstName: trimmedFirstName,\n lastName: trimmedLastName,\n bio: trimmedBio,\n }),\n ...(isUsernameTouched && {\n username,\n }),\n });\n }, [\n photo,\n firstName, lastName, bio, isProfileFieldsTouched,\n username, isUsernameTouched,\n updateProfile,\n ]);\n\n const lang = useLang();\n\n return (\n <div className=\"settings-fab-wrapper\">\n <div className=\"settings-content custom-scroll\">\n <div className=\"settings-edit-profile\">\n <AvatarEditable\n currentAvatarBlobUrl={currentAvatarBlobUrl}\n onChange={handlePhotoChange}\n title=\"Edit your profile photo\"\n disabled={isLoading}\n />\n <InputText\n value={firstName}\n onChange={handleFirstNameChange}\n label={lang('FirstName')}\n disabled={isLoading}\n error={error === ERROR_FIRST_NAME_MISSING ? error : undefined}\n />\n <InputText\n value={lastName}\n onChange={handleLastNameChange}\n label={lang('LastName')}\n disabled={isLoading}\n />\n <InputText\n value={bio}\n onChange={handleBioChange}\n label={lang('UserBio')}\n disabled={isLoading}\n error={error === ERROR_BIO_TOO_LONG ? error : undefined}\n />\n\n <p className=\"settings-item-description\" dir={lang.isRtl ? 'rtl' : undefined}>\n {renderText(lang('lng_settings_about_bio'), ['br', 'simple_markdown'])}\n </p>\n </div>\n\n <div className=\"settings-item\">\n <h4 className=\"settings-item-header\" dir={lang.isRtl ? 'rtl' : undefined}>{lang('Username')}</h4>\n\n <UsernameInput\n currentUsername={username || ''}\n isLoading={isLoading}\n isUsernameAvailable={isUsernameAvailable}\n checkUsername={checkUsername}\n onChange={handleUsernameChange}\n />\n\n <p className=\"settings-item-description\" dir={lang.isRtl ? 'rtl' : undefined}>\n {renderText(lang('UsernameHelp'), ['br', 'simple_markdown'])}\n </p>\n {username && (\n <p className=\"settings-item-description\" dir={lang.isRtl ? 'rtl' : undefined}>\n {lang('lng_username_link')}<br />\n <span className=\"username-link\">https://t.me/{username}</span>\n </p>\n )}\n </div>\n </div>\n\n <FloatingActionButton\n isShown={isSaveButtonShown}\n onClick={handleProfileSave}\n disabled={isLoading}\n ariaLabel=\"Save changes\"\n >\n {isLoading ? (\n <Spinner color=\"white\" />\n ) : (\n <i className=\"icon-check\" />\n )}\n </FloatingActionButton>\n </div>\n );\n};\n\nexport default memo(withGlobal(\n (global): StateProps => {\n const { currentUserId } = global;\n const { progress, isUsernameAvailable } = global.profileEdit || {};\n const currentUser = currentUserId ? selectUser(global, currentUserId) : undefined;\n\n if (!currentUser) {\n return {\n progress,\n isUsernameAvailable,\n };\n }\n\n const {\n firstName: currentFirstName,\n lastName: currentLastName,\n username: currentUsername,\n fullInfo,\n } = currentUser;\n const { bio: currentBio } = fullInfo || {};\n const currentAvatarHash = getChatAvatarHash(currentUser);\n\n return {\n currentAvatarHash,\n currentFirstName,\n currentLastName,\n currentBio,\n currentUsername,\n progress,\n isUsernameAvailable,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'loadCurrentUser',\n 'updateProfile',\n 'checkUsername',\n ]),\n)(SettingsEditProfile));\n","import React, {\n FC, memo, useMemo, useCallback, useState, useEffect,\n} from '../../../../lib/teact/teact';\nimport { withGlobal } from '../../../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../../../global/types';\nimport { ApiChatFolder, ApiChat, ApiUser } from '../../../../api/types';\nimport { NotifyException, NotifySettings } from '../../../../types';\n\nimport { STICKER_SIZE_FOLDER_SETTINGS } from '../../../../config';\nimport { pick } from '../../../../util/iteratees';\nimport { selectNotifyExceptions, selectNotifySettings } from '../../../../modules/selectors';\nimport { throttle } from '../../../../util/schedulers';\nimport getAnimationData from '../../../common/helpers/animatedAssets';\nimport { getFolderDescriptionText } from '../../../../modules/helpers';\nimport useLang from '../../../../hooks/useLang';\n\nimport ListItem from '../../../ui/ListItem';\nimport Button from '../../../ui/Button';\nimport Loading from '../../../ui/Loading';\nimport AnimatedSticker from '../../../common/AnimatedSticker';\n\ntype OwnProps = {\n onCreateFolder: () => void;\n onEditFolder: (folder: ApiChatFolder) => void;\n};\n\ntype StateProps = {\n chatsById: Record<number, ApiChat>;\n usersById: Record<number, ApiUser>;\n orderedFolderIds?: number[];\n foldersById: Record<number, ApiChatFolder>;\n recommendedChatFolders?: ApiChatFolder[];\n notifySettings: NotifySettings;\n notifyExceptions?: Record<number, NotifyException>;\n};\n\ntype DispatchProps = Pick<GlobalActions, 'loadRecommendedChatFolders' | 'addChatFolder' | 'showError'>;\n\nconst runThrottledForLoadRecommended = throttle((cb) => cb(), 60000, true);\n\nconst MAX_ALLOWED_FOLDERS = 10;\n\nconst SettingsFoldersMain: FC<OwnProps & StateProps & DispatchProps> = ({\n onCreateFolder,\n onEditFolder,\n chatsById,\n usersById,\n orderedFolderIds,\n foldersById,\n recommendedChatFolders,\n notifySettings,\n notifyExceptions,\n loadRecommendedChatFolders,\n addChatFolder,\n showError,\n}) => {\n const [animationData, setAnimationData] = useState<Record<string, any>>();\n const [isAnimationLoaded, setIsAnimationLoaded] = useState(false);\n const handleAnimationLoad = useCallback(() => setIsAnimationLoaded(true), []);\n\n useEffect(() => {\n if (!animationData) {\n getAnimationData('FoldersAll').then(setAnimationData);\n }\n }, [animationData]);\n\n // Due to the parent Transition, this component never gets unmounted,\n // that's why we use throttled API call on every update.\n useEffect(() => {\n runThrottledForLoadRecommended(() => {\n loadRecommendedChatFolders();\n });\n }, [loadRecommendedChatFolders]);\n\n const handleCreateFolder = useCallback(() => {\n if (Object.keys(foldersById).length >= MAX_ALLOWED_FOLDERS) {\n showError({\n error: {\n message: 'DIALOG_FILTERS_TOO_MUCH',\n },\n });\n\n return;\n }\n\n onCreateFolder();\n }, [foldersById, showError, onCreateFolder]);\n\n const lang = useLang();\n\n const userFolders = useMemo(() => {\n if (!orderedFolderIds) {\n return undefined;\n }\n\n const chatIds = Object.keys(chatsById).map(Number);\n\n return orderedFolderIds.map((id) => {\n const folder = foldersById[id];\n\n return {\n id: folder.id,\n title: folder.title,\n subtitle: getFolderDescriptionText(\n lang, chatsById, usersById, folder, chatIds, notifySettings, notifyExceptions,\n ),\n };\n });\n }, [orderedFolderIds, chatsById, foldersById, usersById, notifySettings, notifyExceptions, lang]);\n\n const handleCreateFolderFromRecommended = useCallback((folder: ApiChatFolder) => {\n if (Object.keys(foldersById).length >= MAX_ALLOWED_FOLDERS) {\n showError({\n error: {\n message: 'DIALOG_FILTERS_TOO_MUCH',\n },\n });\n\n return;\n }\n\n addChatFolder({ folder });\n }, [foldersById, addChatFolder, showError]);\n\n return (\n <div className=\"settings-content custom-scroll\">\n <div className=\"settings-content-header\">\n <div className=\"settings-content-icon\">\n {animationData && (\n <AnimatedSticker\n id=\"settingsFoldersMain\"\n size={STICKER_SIZE_FOLDER_SETTINGS}\n animationData={animationData}\n play={isAnimationLoaded}\n noLoop\n onLoad={handleAnimationLoad}\n />\n )}\n </div>\n\n <p className=\"settings-item-description mb-3\" dir=\"auto\">\n {lang('CreateNewFilterInfo')}\n </p>\n\n <Button\n // TODO: Refactor button component to handle icon placemenet with props\n className=\"with-icon mb-2\"\n color=\"primary\"\n size=\"smaller\"\n pill\n fluid\n onClick={handleCreateFolder}\n isRtl={lang.isRtl}\n >\n <i className=\"icon-add\" />\n {lang('CreateNewFilter')}\n </Button>\n </div>\n\n <div className=\"settings-item pt-3\">\n <h4 className=\"settings-item-header mb-3\" dir={lang.isRtl ? 'rtl' : undefined}>{lang('Filters')}</h4>\n\n {userFolders && userFolders.length ? userFolders.map((folder) => (\n <ListItem\n className=\"mb-2\"\n narrow\n multiline\n onClick={() => onEditFolder(foldersById[folder.id])}\n >\n <span className=\"title\">{folder.title}</span>\n <span className=\"subtitle\">{folder.subtitle}</span>\n </ListItem>\n )) : userFolders && !userFolders.length ? (\n <p className=\"settings-item-description my-4\" dir=\"auto\">\n You have no folders yet.\n </p>\n ) : <Loading />}\n </div>\n\n {(recommendedChatFolders && !!recommendedChatFolders.length) && (\n <div className=\"settings-item pt-3\">\n <h4 className=\"settings-item-header mb-3\" dir={lang.isRtl ? 'rtl' : undefined}>\n {lang('FilterRecommended')}\n </h4>\n\n {recommendedChatFolders.map((folder) => (\n <ListItem\n className=\"mb-2\"\n narrow\n onClick={() => handleCreateFolderFromRecommended(folder)}\n >\n <div className=\"settings-folders-recommended-item\">\n <div className=\"multiline-item\">\n <span className=\"title\">{folder.title}</span>\n <span className=\"subtitle\">{folder.description}</span>\n </div>\n\n <Button\n className=\"px-3\"\n color=\"primary\"\n size=\"tiny\"\n pill\n fluid\n isRtl={lang.isRtl}\n >\n {lang('Add')}\n </Button>\n </div>\n </ListItem>\n ))}\n </div>\n )}\n </div>\n );\n};\n\nexport default memo(withGlobal<OwnProps>(\n (global): StateProps => {\n const {\n chats: { byId: chatsById },\n users: { byId: usersById },\n } = global;\n\n const {\n orderedIds: orderedFolderIds,\n byId: foldersById,\n recommended: recommendedChatFolders,\n } = global.chatFolders;\n\n return {\n chatsById,\n usersById,\n orderedFolderIds,\n foldersById,\n recommendedChatFolders,\n notifySettings: selectNotifySettings(global),\n notifyExceptions: selectNotifyExceptions(global),\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, ['loadRecommendedChatFolders', 'addChatFolder', 'showError']),\n)(SettingsFoldersMain));\n","import React, { FC } from '../../lib/teact/teact';\n\nimport useLang from '../../hooks/useLang';\n\nimport Button from './Button';\n\nimport './ShowMoreButton.scss';\n\ntype OwnProps = {\n count: number;\n itemName: string;\n itemPluralName?: string;\n isLoading?: boolean;\n onClick: () => void;\n};\n\nconst ShowMoreButton: FC<OwnProps> = ({\n count,\n itemName,\n itemPluralName,\n isLoading,\n onClick,\n}) => {\n const lang = useLang();\n\n return (\n <Button\n className=\"ShowMoreButton\"\n color=\"translucent\"\n size=\"smaller\"\n isText\n isLoading={isLoading}\n isRtl={lang.isRtl}\n onClick={onClick}\n >\n <i className=\"icon-down\" />\n Show {count} more {count > 1 ? itemPluralName || `${itemName}s` : itemName}\n </Button>\n );\n};\n\nexport default ShowMoreButton;\n","import React, {\n FC, memo, useCallback, useState, useEffect, useMemo,\n} from '../../../../lib/teact/teact';\nimport { withGlobal } from '../../../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../../../global/types';\n\nimport { STICKER_SIZE_FOLDER_SETTINGS } from '../../../../config';\nimport { pick, findIntersectionWithSet } from '../../../../util/iteratees';\nimport { isChatPrivate } from '../../../../modules/helpers';\nimport getAnimationData from '../../../common/helpers/animatedAssets';\nimport {\n FoldersState,\n FolderEditDispatch,\n INCLUDED_CHAT_TYPES,\n EXCLUDED_CHAT_TYPES,\n selectChatFilters,\n} from '../../../../hooks/reducers/useFoldersReducer';\nimport useLang from '../../../../hooks/useLang';\n\nimport ListItem from '../../../ui/ListItem';\nimport AnimatedSticker from '../../../common/AnimatedSticker';\nimport InputText from '../../../ui/InputText';\nimport PrivateChatInfo from '../../../common/PrivateChatInfo';\nimport GroupChatInfo from '../../../common/GroupChatInfo';\nimport FloatingActionButton from '../../../ui/FloatingActionButton';\nimport Spinner from '../../../ui/Spinner';\nimport ShowMoreButton from '../../../ui/ShowMoreButton';\n\ntype OwnProps = {\n state: FoldersState;\n dispatch: FolderEditDispatch;\n onAddIncludedChats: () => void;\n onAddExcludedChats: () => void;\n onReset: () => void;\n};\n\ntype StateProps = {\n loadedActiveChatIds?: number[];\n loadedArchivedChatIds?: number[];\n};\n\ntype DispatchProps = Pick<GlobalActions, 'editChatFolder' | 'addChatFolder' | 'loadMoreChats'>;\n\nconst SUBMIT_TIMEOUT = 500;\n\nconst INITIAL_CHATS_LIMIT = 5;\n\nconst ERROR_NO_TITLE = 'Please provide a title for this folder.';\nconst ERROR_NO_CHATS = 'Please select at least one chat for this folder.';\n\nconst SettingsFoldersEdit: FC<OwnProps & StateProps & DispatchProps> = ({\n state,\n dispatch,\n onAddIncludedChats,\n onAddExcludedChats,\n onReset,\n loadedActiveChatIds,\n loadedArchivedChatIds,\n editChatFolder,\n addChatFolder,\n loadMoreChats,\n}) => {\n const [animationData, setAnimationData] = useState<Record<string, any>>();\n const [isAnimationLoaded, setIsAnimationLoaded] = useState(false);\n const handleAnimationLoad = useCallback(() => setIsAnimationLoaded(true), []);\n\n const [isIncludedChatsListExpanded, setIsIncludedChatsListExpanded] = useState(false);\n const [isExcludedChatsListExpanded, setIsExcludedChatsListExpanded] = useState(false);\n\n const {\n selectedChatIds: includedChatIds,\n selectedChatTypes: includedChatTypes,\n } = selectChatFilters(state, 'included');\n const {\n selectedChatIds: excludedChatIds,\n selectedChatTypes: excludedChatTypes,\n } = selectChatFilters(state, 'excluded');\n\n useEffect(() => {\n if (!animationData) {\n getAnimationData('FoldersNew').then(setAnimationData);\n }\n }, [animationData]);\n\n useEffect(() => {\n setIsIncludedChatsListExpanded(false);\n setIsExcludedChatsListExpanded(false);\n }, [state.folderId]);\n\n const [visibleIncludedChatIds, visibleExcludedChatIds] = useMemo(() => {\n const allLoadedChatsSet = new Set([\n ...loadedActiveChatIds || [],\n ...loadedArchivedChatIds || [],\n ]);\n\n const loadedIncludedChatIds = findIntersectionWithSet(includedChatIds, allLoadedChatsSet);\n const loadedExcludedChatIds = findIntersectionWithSet(excludedChatIds, allLoadedChatsSet);\n\n return [\n isIncludedChatsListExpanded\n ? loadedIncludedChatIds\n : loadedIncludedChatIds.slice(0, INITIAL_CHATS_LIMIT - includedChatTypes.length),\n isExcludedChatsListExpanded\n ? loadedExcludedChatIds\n : loadedExcludedChatIds.slice(0, INITIAL_CHATS_LIMIT - excludedChatTypes.length),\n ];\n }, [\n excludedChatIds, includedChatIds, includedChatTypes, excludedChatTypes,\n isExcludedChatsListExpanded, isIncludedChatsListExpanded,\n loadedActiveChatIds, loadedArchivedChatIds,\n ]);\n\n useEffect(() => {\n if (\n visibleIncludedChatIds.length < includedChatIds.length\n || visibleExcludedChatIds.length < excludedChatIds.length\n ) {\n loadMoreChats({ listType: 'active' });\n }\n }, [\n loadMoreChats,\n excludedChatIds.length,\n includedChatIds.length,\n visibleExcludedChatIds.length,\n visibleIncludedChatIds.length,\n ]);\n\n const lang = useLang();\n\n function handleChange(event: React.ChangeEvent<HTMLInputElement>) {\n const { currentTarget } = event;\n dispatch({ type: 'setTitle', payload: currentTarget.value.trim() });\n }\n\n function handleSubmit() {\n const { title } = state.folder;\n\n if (!title) {\n dispatch({ type: 'setError', payload: ERROR_NO_TITLE });\n return;\n }\n\n if (!includedChatIds.length && !Object.keys(includedChatTypes).length) {\n dispatch({ type: 'setError', payload: ERROR_NO_CHATS });\n return;\n }\n\n dispatch({ type: 'setIsLoading', payload: true });\n if (state.mode === 'edit') {\n editChatFolder({ id: state.folderId, folderUpdate: state.folder });\n } else {\n addChatFolder({ folder: state.folder });\n }\n\n setTimeout(() => {\n onReset();\n }, SUBMIT_TIMEOUT);\n }\n\n function renderChatType(key: string, mode: 'included' | 'excluded') {\n const chatType = mode === 'included'\n ? INCLUDED_CHAT_TYPES.find(({ key: typeKey }) => typeKey === key)\n : EXCLUDED_CHAT_TYPES.find(({ key: typeKey }) => typeKey === key);\n\n if (!chatType) {\n return undefined;\n }\n\n return (\n <ListItem\n key={chatType.key}\n className=\"settings-folders-list-item mb-1\"\n icon={chatType.icon}\n narrow\n inactive\n >\n {lang(chatType.title)}\n </ListItem>\n );\n }\n\n function renderChats(mode: 'included' | 'excluded') {\n const selectedChatTypes = mode === 'included' ? includedChatTypes : excludedChatTypes;\n const visibleChatIds = mode === 'included' ? visibleIncludedChatIds : visibleExcludedChatIds;\n\n const isExpanded = mode === 'included' ? isIncludedChatsListExpanded : isExcludedChatsListExpanded;\n const allChatIds = mode === 'included' ? includedChatIds : excludedChatIds;\n const leftChatsCount = allChatIds.length - selectedChatTypes.length - visibleChatIds.length;\n const clickHandler = mode === 'included'\n ? () => setIsIncludedChatsListExpanded(true)\n : () => setIsExcludedChatsListExpanded(true);\n\n return (\n <>\n {selectedChatTypes.map((key) => renderChatType(key, mode))}\n {visibleChatIds.map((id) => (\n <ListItem\n className=\"settings-folders-list-item mb-1\"\n narrow\n inactive\n >\n {isChatPrivate(id) ? (\n <PrivateChatInfo avatarSize=\"small\" userId={id} />\n ) : (\n <GroupChatInfo avatarSize=\"small\" chatId={id} />\n )}\n </ListItem>\n ))}\n {(!isExpanded && leftChatsCount > 0) && (\n <ShowMoreButton\n count={leftChatsCount}\n itemName=\"chat\"\n onClick={clickHandler}\n />\n )}\n </>\n );\n }\n\n return (\n <div className=\"settings-fab-wrapper\">\n <div className=\"settings-content custom-scroll\">\n <div className=\"settings-content-header\">\n <div className=\"settings-content-icon\">\n {animationData && (\n <AnimatedSticker\n id=\"settingsFoldersEdit\"\n size={STICKER_SIZE_FOLDER_SETTINGS}\n animationData={animationData}\n play={isAnimationLoaded && String(state.folderId)}\n noLoop\n onLoad={handleAnimationLoad}\n />\n )}\n </div>\n\n {state.mode === 'create' && (\n <p className=\"settings-item-description mb-3\" dir={lang.isRtl ? 'rtl' : undefined}>\n {lang('FilterIncludeInfo')}\n </p>\n )}\n\n <InputText\n className=\"mb-0\"\n label={lang('FilterNameHint')}\n value={state.folder.title}\n onChange={handleChange}\n error={state.error && state.error === ERROR_NO_TITLE ? ERROR_NO_TITLE : undefined}\n />\n </div>\n\n <div className=\"settings-item no-border pt-3\">\n {state.error && state.error === ERROR_NO_CHATS && (\n <p className=\"settings-item-description color-danger mb-2\" dir={lang.isRtl ? 'rtl' : undefined}>\n {state.error}\n </p>\n )}\n\n <h4 className=\"settings-item-header mb-3\" dir={lang.isRtl ? 'rtl' : undefined}>{lang('FilterInclude')}</h4>\n\n <ListItem\n className=\"settings-folders-list-item color-primary mb-0\"\n icon=\"add\"\n onClick={onAddIncludedChats}\n >\n {lang('FilterAddChats')}\n </ListItem>\n\n {renderChats('included')}\n </div>\n\n <div className=\"settings-item no-border pt-3\">\n <h4 className=\"settings-item-header mb-3\" dir={lang.isRtl ? 'rtl' : undefined}>{lang('FilterExclude')}</h4>\n\n <ListItem\n className=\"settings-folders-list-item color-primary mb-0\"\n icon=\"add\"\n onClick={onAddExcludedChats}\n >\n {lang('FilterAddChats')}\n </ListItem>\n\n {renderChats('excluded')}\n </div>\n </div>\n\n <FloatingActionButton\n isShown={!!state.isTouched}\n disabled={state.isLoading}\n onClick={handleSubmit}\n ariaLabel={state.mode === 'edit' ? 'Save changes' : 'Create folder'}\n >\n {state.isLoading ? (\n <Spinner color=\"white\" />\n ) : (\n <i className=\"icon-check\" />\n )}\n </FloatingActionButton>\n </div>\n );\n};\n\nexport default memo(withGlobal<OwnProps>(\n (global): StateProps => {\n const { listIds } = global.chats;\n\n return {\n loadedActiveChatIds: listIds.active,\n loadedArchivedChatIds: listIds.archived,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, ['editChatFolder', 'addChatFolder', 'loadMoreChats']),\n)(SettingsFoldersEdit));\n","import React, {\n FC, useCallback, useRef, useEffect, memo,\n} from '../../../../lib/teact/teact';\n\nimport { isChatPrivate } from '../../../../modules/helpers';\nimport {\n INCLUDED_CHAT_TYPES,\n EXCLUDED_CHAT_TYPES,\n FolderChatType,\n} from '../../../../hooks/reducers/useFoldersReducer';\nimport useInfiniteScroll from '../../../../hooks/useInfiniteScroll';\nimport useLang from '../../../../hooks/useLang';\n\nimport Checkbox from '../../../ui/Checkbox';\nimport InputText from '../../../ui/InputText';\nimport ListItem from '../../../ui/ListItem';\nimport PrivateChatInfo from '../../../common/PrivateChatInfo';\nimport GroupChatInfo from '../../../common/GroupChatInfo';\nimport PickerSelectedItem from '../../../common/PickerSelectedItem';\nimport InfiniteScroll from '../../../ui/InfiniteScroll';\nimport Loading from '../../../ui/Loading';\n\nimport '../../../common/Picker.scss';\nimport './SettingsFoldersChatsPicker.scss';\n\ntype OwnProps = {\n mode: 'included' | 'excluded';\n chatIds: number[];\n selectedIds: number[];\n selectedChatTypes: string[];\n filterValue?: string;\n onSelectedIdsChange: (ids: number[]) => void;\n onSelectedChatTypesChange: (types: string[]) => void;\n onFilterChange: (value: string) => void;\n onLoadMore: () => void;\n};\n\n// Focus slows down animation, also it breaks transition layout in Chrome\nconst FOCUS_DELAY_MS = 500;\n\nconst MAX_CHATS = 100;\nconst MAX_FULL_ITEMS = 10;\nconst ALWAYS_FULL_ITEMS_COUNT = 5;\n\nconst SettingsFoldersChatsPicker: FC<OwnProps> = ({\n mode,\n chatIds,\n selectedIds,\n selectedChatTypes,\n filterValue,\n onSelectedIdsChange,\n onSelectedChatTypesChange,\n onFilterChange,\n onLoadMore,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const inputRef = useRef<HTMLInputElement>(null);\n const chatTypes = mode === 'included' ? INCLUDED_CHAT_TYPES : EXCLUDED_CHAT_TYPES;\n const shouldMinimize = selectedIds.length + selectedChatTypes.length > MAX_FULL_ITEMS;\n const hasMaxChats = selectedIds.length >= MAX_CHATS;\n\n useEffect(() => {\n setTimeout(() => {\n requestAnimationFrame(() => {\n inputRef.current!.focus();\n });\n }, FOCUS_DELAY_MS);\n }, []);\n\n const handleItemClick = useCallback((id: number) => {\n const newSelectedIds = [...selectedIds];\n if (newSelectedIds.includes(id)) {\n newSelectedIds.splice(newSelectedIds.indexOf(id), 1);\n } else {\n newSelectedIds.push(id);\n }\n onSelectedIdsChange(newSelectedIds);\n }, [selectedIds, onSelectedIdsChange]);\n\n const handleChatTypeClick = useCallback((key: FolderChatType['key']) => {\n const newSelectedChatTypes = [...selectedChatTypes];\n if (newSelectedChatTypes.includes(key)) {\n newSelectedChatTypes.splice(newSelectedChatTypes.indexOf(key), 1);\n } else {\n newSelectedChatTypes.push(key);\n }\n onSelectedChatTypesChange(newSelectedChatTypes);\n }, [selectedChatTypes, onSelectedChatTypesChange]);\n\n const handleFilterChange = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {\n const { value } = e.currentTarget;\n onFilterChange(value);\n }, [onFilterChange]);\n\n const lang = useLang();\n\n function renderSelectedChatType(key: string) {\n const selectedType = chatTypes.find(({ key: typeKey }) => key === typeKey);\n if (!selectedType) {\n return undefined;\n }\n\n return (\n <PickerSelectedItem\n icon={selectedType.icon}\n title={lang(selectedType.title)}\n isMinimized={shouldMinimize}\n canClose\n onClick={handleChatTypeClick}\n clickArg={selectedType.key}\n />\n );\n }\n\n function renderChatType(type: FolderChatType) {\n return (\n <ListItem\n key={type.key}\n className=\"chat-item-clickable picker-list-item chat-type-item\"\n onClick={() => handleChatTypeClick(type.key)}\n ripple\n >\n <i className={`icon-${type.icon}`} />\n <h3 className=\"chat-type\" dir=\"auto\">{lang(type.title)}</h3>\n <Checkbox\n label=\"\"\n checked={selectedChatTypes.includes(type.key)}\n round\n />\n </ListItem>\n );\n }\n\n function renderItem(id: number) {\n const isSelected = selectedIds.includes(id);\n\n return (\n <ListItem\n key={id}\n className=\"chat-item-clickable picker-list-item chat-item\"\n onClick={() => handleItemClick(id)}\n ripple\n disabled={!isSelected && hasMaxChats}\n >\n {isChatPrivate(id) ? (\n <PrivateChatInfo userId={id} />\n ) : (\n <GroupChatInfo chatId={id} withChatType />\n )}\n <Checkbox\n label=\"\"\n checked={isSelected}\n round\n />\n </ListItem>\n );\n }\n\n const [viewportIds, getMore] = useInfiniteScroll(onLoadMore, chatIds, Boolean(filterValue));\n\n return (\n <div className=\"Picker SettingsFoldersChatsPicker\">\n <div className=\"picker-header custom-scroll\">\n {selectedChatTypes.map(renderSelectedChatType)}\n {selectedIds.map((id, i) => (\n <PickerSelectedItem\n chatOrUserId={id}\n isMinimized={shouldMinimize && i < selectedIds.length - ALWAYS_FULL_ITEMS_COUNT}\n canClose\n onClick={handleItemClick}\n clickArg={id}\n />\n ))}\n {!hasMaxChats ? (\n <InputText\n ref={inputRef}\n value={filterValue}\n onChange={handleFilterChange}\n placeholder={lang('Search')}\n />\n ) : (\n <p className=\"max-items-reached\" dir=\"auto\">\n {`Sorry, you can't add more than ${MAX_CHATS} chats.`}\n </p>\n )}\n </div>\n <InfiniteScroll\n className=\"picker-list custom-scroll\"\n itemSelector=\".chat-item\"\n items={viewportIds}\n onLoadMore={getMore}\n >\n {(!viewportIds || !viewportIds.length || viewportIds.includes(chatIds[0])) && (\n <>\n <h4 key=\"header1\" className=\"settings-item-header\" dir={lang.isRtl ? 'rtl' : undefined}>\n {lang('FilterChatTypes')}\n </h4>\n {chatTypes.map(renderChatType)}\n <div key=\"divider\" className=\"picker-list-divider\" />\n <h4 key=\"header2\" className=\"settings-item-header\" dir={lang.isRtl ? 'rtl' : undefined}>\n {lang('FilterChats')}\n </h4>\n </>\n )}\n\n {viewportIds && viewportIds.length ? (\n viewportIds.map(renderItem)\n ) : viewportIds && !viewportIds.length ? (\n <p className=\"no-results\" key=\"no-results\">Sorry, nothing found.</p>\n ) : (\n <Loading key=\"loading\" />\n )}\n </InfiniteScroll>\n </div>\n );\n};\n\nexport default memo(SettingsFoldersChatsPicker);\n","import React, {\n FC, memo, useMemo, useCallback,\n} from '../../../../lib/teact/teact';\nimport { withGlobal } from '../../../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../../../global/types';\nimport { ApiChat } from '../../../../api/types';\n\nimport useLang from '../../../../hooks/useLang';\nimport { pick } from '../../../../util/iteratees';\nimport searchWords from '../../../../util/searchWords';\nimport { prepareChatList, getChatTitle } from '../../../../modules/helpers';\nimport {\n FoldersState,\n FolderEditDispatch,\n selectChatFilters,\n} from '../../../../hooks/reducers/useFoldersReducer';\n\nimport SettingsFoldersChatsPicker from './SettingsFoldersChatsPicker';\n\nimport Loading from '../../../ui/Loading';\n\ntype OwnProps = {\n mode: 'included' | 'excluded';\n state: FoldersState;\n dispatch: FolderEditDispatch;\n};\n\ntype StateProps = {\n chatsById: Record<number, ApiChat>;\n listIds?: number[];\n orderedPinnedIds?: number[];\n archivedListIds?: number[];\n archivedPinnedIds?: number[];\n};\n\ntype DispatchProps = Pick<GlobalActions, 'loadMoreChats'>;\n\nconst SettingsFoldersChatFilters: FC<OwnProps & StateProps & DispatchProps> = ({\n mode,\n state,\n dispatch,\n chatsById,\n listIds,\n orderedPinnedIds,\n archivedListIds,\n archivedPinnedIds,\n loadMoreChats,\n}) => {\n const { chatFilter } = state;\n const { selectedChatIds, selectedChatTypes } = selectChatFilters(state, mode, true);\n\n const lang = useLang();\n const chats = useMemo(() => {\n const activeChatArrays = listIds\n ? prepareChatList(chatsById, listIds, orderedPinnedIds, 'all')\n : undefined;\n const archivedChatArrays = archivedListIds\n ? prepareChatList(chatsById, archivedListIds, archivedPinnedIds, 'archived')\n : undefined;\n\n if (!activeChatArrays && !archivedChatArrays) {\n return undefined;\n }\n\n return [\n ...(activeChatArrays\n ? [...activeChatArrays.pinnedChats, ...activeChatArrays.otherChats]\n : []\n ),\n ...(archivedChatArrays ? archivedChatArrays.otherChats : []),\n ];\n }, [chatsById, listIds, orderedPinnedIds, archivedListIds, archivedPinnedIds]);\n\n const displayedIds = useMemo(() => {\n if (!chats) {\n return undefined;\n }\n\n return chats\n .filter((chat) => (\n !chatFilter\n || searchWords(getChatTitle(lang, chat), chatFilter)\n || selectedChatIds.includes(chat.id)\n ))\n .map(({ id }) => id);\n }, [chats, chatFilter, lang, selectedChatIds]);\n\n const handleFilterChange = useCallback((newFilter: string) => {\n dispatch({\n type: 'setChatFilter',\n payload: newFilter,\n });\n }, [dispatch]);\n\n const handleSelectedIdsChange = useCallback((ids: number[]) => {\n if (mode === 'included') {\n dispatch({\n type: 'setIncludeFilters',\n payload: { ...state.includeFilters, includedChatIds: ids },\n });\n } else {\n dispatch({\n type: 'setExcludeFilters',\n payload: { ...state.excludeFilters, excludedChatIds: ids },\n });\n }\n }, [mode, state, dispatch]);\n\n const handleSelectedChatTypesChange = useCallback((keys: string[]) => {\n const newFilters: Record<string, boolean> = {};\n keys.forEach((key) => {\n newFilters[key] = true;\n });\n\n if (mode === 'included') {\n dispatch({\n type: 'setIncludeFilters',\n payload: {\n includedChatIds: selectedChatIds,\n ...newFilters,\n },\n });\n } else {\n dispatch({\n type: 'setExcludeFilters',\n payload: {\n excludedChatIds: selectedChatIds,\n ...newFilters,\n },\n });\n }\n }, [mode, selectedChatIds, dispatch]);\n\n if (!displayedIds) {\n return <Loading />;\n }\n\n return (\n <SettingsFoldersChatsPicker\n mode={mode}\n chatIds={displayedIds}\n selectedIds={selectedChatIds}\n selectedChatTypes={selectedChatTypes}\n filterValue={chatFilter}\n onSelectedIdsChange={handleSelectedIdsChange}\n onSelectedChatTypesChange={handleSelectedChatTypesChange}\n onFilterChange={handleFilterChange}\n onLoadMore={loadMoreChats}\n />\n );\n};\n\nexport default memo(withGlobal<OwnProps>(\n (global): StateProps => {\n const {\n chats: {\n byId: chatsById,\n listIds,\n orderedPinnedIds,\n },\n } = global;\n\n return {\n chatsById,\n listIds: listIds.active,\n orderedPinnedIds: orderedPinnedIds.active,\n archivedPinnedIds: orderedPinnedIds.archived,\n archivedListIds: listIds.archived,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, ['loadMoreChats']),\n)(SettingsFoldersChatFilters));\n","import React, { FC, memo, useCallback } from '../../../../lib/teact/teact';\n\nimport { ApiChatFolder } from '../../../../api/types';\nimport { SettingsScreens } from '../../../../types';\n\nimport { FoldersState, FolderEditDispatch } from '../../../../hooks/reducers/useFoldersReducer';\n\nimport SettingsFoldersMain from './SettingsFoldersMain';\nimport SettingsFoldersEdit from './SettingsFoldersEdit';\nimport SettingsFoldersChatFilters from './SettingsFoldersChatFilters';\n\nimport './SettingsFolders.scss';\n\nconst TRANSITION_DURATION = 200;\n\nexport type OwnProps = {\n currentScreen: SettingsScreens;\n state: FoldersState;\n dispatch: FolderEditDispatch;\n onScreenSelect: (screen: SettingsScreens) => void;\n onReset: () => void;\n};\n\nconst SettingsFolders: FC<OwnProps> = ({\n currentScreen,\n state,\n dispatch,\n onScreenSelect,\n onReset,\n}) => {\n const handleReset = useCallback(() => {\n if (\n currentScreen === SettingsScreens.FoldersCreateFolder\n || currentScreen === SettingsScreens.FoldersEditFolder\n ) {\n setTimeout(() => {\n dispatch({ type: 'reset' });\n }, TRANSITION_DURATION);\n }\n\n if (\n currentScreen === SettingsScreens.FoldersIncludedChats\n || currentScreen === SettingsScreens.FoldersExcludedChats\n ) {\n if (state.mode === 'create') {\n onScreenSelect(SettingsScreens.FoldersCreateFolder);\n } else {\n onScreenSelect(SettingsScreens.FoldersEditFolder);\n }\n return;\n }\n\n onReset();\n }, [\n state.mode, dispatch,\n currentScreen, onReset, onScreenSelect,\n ]);\n\n const handleCreateFolder = useCallback(() => {\n dispatch({ type: 'reset' });\n onScreenSelect(SettingsScreens.FoldersCreateFolder);\n }, [onScreenSelect, dispatch]);\n\n const handleEditFolder = useCallback((folder: ApiChatFolder) => {\n dispatch({ type: 'editFolder', payload: folder });\n onScreenSelect(SettingsScreens.FoldersEditFolder);\n }, [dispatch, onScreenSelect]);\n\n const handleAddIncludedChats = useCallback(() => {\n dispatch({ type: 'editIncludeFilters' });\n onScreenSelect(SettingsScreens.FoldersIncludedChats);\n }, [dispatch, onScreenSelect]);\n\n const handleAddExcludedChats = useCallback(() => {\n dispatch({ type: 'editExcludeFilters' });\n onScreenSelect(SettingsScreens.FoldersExcludedChats);\n }, [dispatch, onScreenSelect]);\n\n switch (currentScreen) {\n case SettingsScreens.Folders:\n return (\n <SettingsFoldersMain\n onCreateFolder={handleCreateFolder}\n onEditFolder={handleEditFolder}\n />\n );\n case SettingsScreens.FoldersCreateFolder:\n case SettingsScreens.FoldersEditFolder:\n return (\n <SettingsFoldersEdit\n state={state}\n dispatch={dispatch}\n onAddIncludedChats={handleAddIncludedChats}\n onAddExcludedChats={handleAddExcludedChats}\n onReset={handleReset}\n />\n );\n case SettingsScreens.FoldersIncludedChats:\n return (\n <SettingsFoldersChatFilters\n mode=\"included\"\n state={state}\n dispatch={dispatch}\n />\n );\n case SettingsScreens.FoldersExcludedChats:\n return (\n <SettingsFoldersChatFilters\n mode=\"excluded\"\n state={state}\n dispatch={dispatch}\n />\n );\n\n default:\n return undefined;\n }\n};\n\nexport default memo(SettingsFolders);\n","import { ChangeEvent } from 'react';\nimport React, {\n FC, useCallback, useMemo, memo,\n} from '../../lib/teact/teact';\n\nimport buildClassName from '../../util/buildClassName';\nimport useLang from '../../hooks/useLang';\n\nimport './RangeSlider.scss';\n\ntype OwnProps = {\n options?: string[];\n range?: { min: number; max: number; step?: number };\n label?: string;\n value: number;\n disabled?: boolean;\n onChange: (value: number) => void;\n};\n\nconst RangeSlider: FC<OwnProps> = ({\n options,\n range,\n label,\n value,\n disabled,\n onChange,\n}) => {\n const lang = useLang();\n const handleChange = useCallback((event: ChangeEvent<HTMLInputElement>) => {\n onChange(Number(event.currentTarget.value));\n }, [onChange]);\n\n const className = buildClassName(\n 'RangeSlider',\n disabled && 'disabled',\n );\n\n const trackWidth = useMemo(() => {\n if (options) {\n return (value / (options.length - 1)) * 100;\n } else if (range) {\n const possibleValuesLength = (range.max - range.min) / (range.step || 1);\n return ((value - range.min) / possibleValuesLength) * 100;\n }\n return 0;\n }, [value, options, range]);\n\n const [min, max, step] = useMemo(() => {\n if (options) {\n return [0, options.length - 1, 1];\n } else if (range) {\n return [range.min, range.max, range.step || 1];\n }\n\n return [0, 0, 0];\n }, [range, options]);\n\n return (\n <div className={className}>\n {label && (\n <div className=\"slider-top-row\" dir={lang.isRtl ? 'rtl' : undefined}>\n <span className=\"label\" dir=\"auto\">{label}</span>\n {range && (\n <span className=\"value\" dir=\"auto\">{value}</span>\n )}\n </div>\n )}\n <div className=\"slider-main\">\n <div\n className=\"slider-fill-track\"\n // @ts-ignore\n style={`width: ${trackWidth}%`}\n />\n <input\n min={min}\n max={max}\n value={value}\n step={step}\n type=\"range\"\n onChange={handleChange}\n />\n {options && (\n <div className=\"slider-options\">\n {options.map((option, index) => (\n <div\n className={buildClassName('slider-option no-selection', index === value && 'active')}\n onClick={() => onChange(index)}\n >\n {option}\n </div>\n ))}\n </div>\n )}\n </div>\n </div>\n );\n};\n\nexport default memo(RangeSlider);\n","import React, { FC, memo, useRef } from '../../../lib/teact/teact';\n\nimport { ApiMediaFormat, ApiStickerSet } from '../../../api/types';\n\nimport { STICKER_SIZE_PICKER_HEADER } from '../../../config';\nimport { ObserveFn, useIsIntersecting } from '../../../hooks/useIntersectionObserver';\nimport useMedia from '../../../hooks/useMedia';\nimport useTransitionForMedia from '../../../hooks/useTransitionForMedia';\nimport { getFirstLetters } from '../../../util/textFormat';\n\nimport AnimatedSticker from '../../common/AnimatedSticker';\n\ntype OwnProps = {\n size?: number;\n stickerSet: ApiStickerSet;\n observeIntersection: ObserveFn;\n};\n\nconst StickerSetCoverAnimated: FC<OwnProps> = ({\n size = STICKER_SIZE_PICKER_HEADER,\n stickerSet,\n observeIntersection,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const ref = useRef<HTMLDivElement>(null);\n\n const isIntersecting = useIsIntersecting(ref, observeIntersection);\n\n const mediaHash = `stickerSet${stickerSet.id}`;\n const lottieData = useMedia(mediaHash, !isIntersecting, ApiMediaFormat.Lottie);\n const { shouldRenderFullMedia, transitionClassNames } = useTransitionForMedia(lottieData, 'slow');\n\n return (\n <div ref={ref} className=\"sticker-set-cover\">\n {!shouldRenderFullMedia && getFirstLetters(stickerSet.title, 2)}\n {shouldRenderFullMedia && lottieData && (\n <AnimatedSticker\n id={mediaHash}\n size={size}\n animationData={lottieData}\n className={transitionClassNames}\n />\n )}\n </div>\n );\n};\n\nexport default memo(StickerSetCoverAnimated);\n","import React, { FC, memo, useRef } from '../../../lib/teact/teact';\n\nimport { ApiStickerSet } from '../../../api/types';\n\nimport { ObserveFn, useIsIntersecting } from '../../../hooks/useIntersectionObserver';\nimport useMedia from '../../../hooks/useMedia';\nimport useTransitionForMedia from '../../../hooks/useTransitionForMedia';\nimport { getFirstLetters } from '../../../util/textFormat';\n\ntype OwnProps = {\n stickerSet: ApiStickerSet;\n observeIntersection: ObserveFn;\n};\n\nconst StickerSetCover: FC<OwnProps> = ({ stickerSet, observeIntersection }) => {\n // eslint-disable-next-line no-null/no-null\n const ref = useRef<HTMLDivElement>(null);\n\n const isIntersecting = useIsIntersecting(ref, observeIntersection);\n\n const mediaData = useMedia(stickerSet.hasThumbnail && `stickerSet${stickerSet.id}`, !isIntersecting);\n const { shouldRenderFullMedia, transitionClassNames } = useTransitionForMedia(mediaData, 'slow');\n\n return (\n <div ref={ref} className=\"sticker-set-cover\">\n {!shouldRenderFullMedia && getFirstLetters(stickerSet.title, 2)}\n {shouldRenderFullMedia && (\n <img src={mediaData} className={transitionClassNames} alt=\"\" />\n )}\n </div>\n );\n};\n\nexport default memo(StickerSetCover);\n","import { MouseEvent as ReactMouseEvent } from 'react';\nimport React, {\n FC, memo, useEffect, useRef,\n} from '../../lib/teact/teact';\n\nimport { ApiMediaFormat, ApiSticker } from '../../api/types';\n\nimport { useIsIntersecting, ObserveFn } from '../../hooks/useIntersectionObserver';\nimport useMedia from '../../hooks/useMedia';\nimport useTransitionForMedia from '../../hooks/useTransitionForMedia';\nimport useFlag from '../../hooks/useFlag';\nimport buildClassName from '../../util/buildClassName';\n\nimport AnimatedSticker from './AnimatedSticker';\nimport Button from '../ui/Button';\n\nimport './StickerButton.scss';\n\ntype OwnProps = {\n sticker: ApiSticker;\n size: number;\n observeIntersection: ObserveFn;\n noAnimate?: boolean;\n title?: string;\n className?: string;\n onClick?: (arg: any) => void;\n clickArg?: any;\n onUnfaveClick?: (sticker: ApiSticker) => void;\n};\n\nconst StickerButton: FC<OwnProps> = ({\n sticker, size, observeIntersection, noAnimate, title, className, onClick, clickArg, onUnfaveClick,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const ref = useRef<HTMLDivElement>(null);\n\n const localMediaHash = `sticker${sticker.id}`;\n const stickerSelector = `sticker-button-${sticker.id}`;\n\n const isIntersecting = useIsIntersecting(ref, observeIntersection);\n\n const thumbDataUri = sticker.thumbnail ? sticker.thumbnail.dataUri : undefined;\n const previewBlobUrl = useMedia(`${localMediaHash}?size=m`, !isIntersecting, ApiMediaFormat.BlobUrl);\n\n const shouldPlay = isIntersecting && !noAnimate;\n const lottieData = useMedia(sticker.isAnimated && localMediaHash, !shouldPlay, ApiMediaFormat.Lottie);\n const [isAnimationLoaded, markLoaded, unmarkLoaded] = useFlag(Boolean(lottieData));\n const canAnimatedPlay = isAnimationLoaded && shouldPlay;\n\n const {\n shouldRenderThumb,\n shouldRenderFullMedia: shouldRenderPreview,\n transitionClassNames: previewTransitionClassNames,\n } = useTransitionForMedia(previewBlobUrl || canAnimatedPlay, 'slow');\n\n // To avoid flickering\n useEffect(() => {\n if (!shouldPlay) {\n unmarkLoaded();\n }\n }, [unmarkLoaded, shouldPlay]);\n\n function handleClick() {\n if (onClick) {\n onClick(clickArg);\n }\n }\n\n function handleUnfaveClick(e: ReactMouseEvent<HTMLButtonElement, MouseEvent>) {\n e.stopPropagation();\n e.preventDefault();\n\n onUnfaveClick!(sticker);\n }\n\n const fullClassName = buildClassName(\n 'StickerButton',\n sticker.isAnimated && 'animated',\n stickerSelector,\n className,\n );\n\n const style = shouldRenderThumb && thumbDataUri ? `background-image: url('${thumbDataUri}');` : '';\n\n return (\n <div\n ref={ref}\n className={fullClassName}\n title={title || (sticker && sticker.emoji)}\n // @ts-ignore\n style={style}\n data-sticker-id={sticker.id}\n onClick={handleClick}\n >\n {shouldRenderPreview && !canAnimatedPlay && (\n // eslint-disable-next-line jsx-a11y/alt-text\n <img src={previewBlobUrl} className={previewTransitionClassNames} />\n )}\n {shouldPlay && lottieData && (\n <AnimatedSticker\n id={localMediaHash}\n animationData={lottieData}\n play\n size={size}\n isLowPriority\n onLoad={markLoaded}\n />\n )}\n {onUnfaveClick && (\n <Button\n className=\"sticker-unfave-button\"\n color=\"dark\"\n round\n onClick={handleUnfaveClick}\n >\n <i className=\"icon-close\" />\n </Button>\n )}\n </div>\n );\n};\n\nexport default memo(StickerButton);\n","import React, {\n FC, memo,\n} from '../../../lib/teact/teact';\nimport { ApiSticker, ApiStickerSet } from '../../../api/types';\n\nimport { STICKER_SIZE_GENERAL_SETTINGS } from '../../../config';\nimport { ObserveFn } from '../../../hooks/useIntersectionObserver';\nimport useLang from '../../../hooks/useLang';\n\nimport ListItem from '../../ui/ListItem';\nimport Button from '../../ui/Button';\nimport StickerSetCoverAnimated from '../../middle/composer/StickerSetCoverAnimated';\nimport StickerSetCover from '../../middle/composer/StickerSetCover';\nimport StickerButton from '../../common/StickerButton';\n\nimport './SettingsStickerSet.scss';\n\ntype OwnProps = {\n stickerSet?: ApiStickerSet;\n observeIntersection: ObserveFn;\n onClick: (value: ApiSticker) => void;\n};\n\nconst SettingsStickerSet: FC<OwnProps> = ({\n stickerSet,\n observeIntersection,\n onClick,\n}) => {\n const lang = useLang();\n\n if (!stickerSet || !stickerSet.stickers) {\n return undefined;\n }\n\n const firstSticker = stickerSet.stickers && stickerSet.stickers[0];\n\n if (stickerSet.hasThumbnail || !firstSticker) {\n return (\n <ListItem\n narrow\n className=\"SettingsStickerSet\"\n inactive={!firstSticker}\n onClick={() => firstSticker && onClick(firstSticker)}\n >\n <Button\n ariaLabel={stickerSet.title}\n color=\"translucent\"\n isRtl={lang.isRtl}\n >\n {stickerSet.isAnimated ? (\n <StickerSetCoverAnimated\n size={STICKER_SIZE_GENERAL_SETTINGS}\n stickerSet={stickerSet}\n observeIntersection={observeIntersection}\n />\n ) : (\n <StickerSetCover\n stickerSet={stickerSet}\n observeIntersection={observeIntersection}\n />\n )}\n </Button>\n <div className=\"multiline-menu-item\">\n <div className=\"title\">{stickerSet.title}</div>\n <div className=\"subtitle\">{lang('StickerPack.StickerCount', stickerSet.count, 'i')}</div>\n </div>\n </ListItem>\n );\n } else {\n return (\n <ListItem\n narrow\n className=\"SettingsStickerSet\"\n onClick={() => onClick(firstSticker)}\n >\n <StickerButton\n sticker={firstSticker}\n size={STICKER_SIZE_GENERAL_SETTINGS}\n title={stickerSet.title}\n observeIntersection={observeIntersection}\n />\n <div className=\"multiline-menu-item\">\n <div className=\"title\">{stickerSet.title}</div>\n <div className=\"subtitle\">{lang('StickerPack.StickerCount', stickerSet.count, 'i')}</div>\n </div>\n </ListItem>\n );\n }\n};\n\nexport default memo(SettingsStickerSet);\n","import React, {\n FC, useCallback, memo, useEffect, useRef, useState,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../../global/types';\nimport { SettingsScreens, ISettings } from '../../../types';\nimport { ApiSticker, ApiStickerSet } from '../../../api/types';\n\nimport { IS_MAC_OS, IS_TOUCH_ENV } from '../../../util/environment';\nimport { pick } from '../../../util/iteratees';\nimport useLang from '../../../hooks/useLang';\nimport useFlag from '../../../hooks/useFlag';\nimport { useIntersectionObserver } from '../../../hooks/useIntersectionObserver';\n\nimport ListItem from '../../ui/ListItem';\nimport RangeSlider from '../../ui/RangeSlider';\nimport Checkbox from '../../ui/Checkbox';\nimport RadioGroup from '../../ui/RadioGroup';\nimport SettingsStickerSet from './SettingsStickerSet';\nimport StickerSetModal from '../../common/StickerSetModal.async';\n\ntype OwnProps = {\n onScreenSelect: (screen: SettingsScreens) => void;\n};\n\ntype StateProps = ISettings['byKey'] & {\n stickerSetIds?: string[];\n stickerSetsById?: Record<string, ApiStickerSet>;\n};\n\ntype DispatchProps = Pick<GlobalActions, 'setSettingOption' | 'loadStickerSets' | 'loadAddedStickers'>;\n\nconst ANIMATION_LEVEL_OPTIONS = [\n 'Solid and Steady',\n 'Nice and Fast',\n 'Lots of Stuff',\n];\n\nconst SettingsGeneral: FC<OwnProps & StateProps & DispatchProps> = ({\n onScreenSelect,\n stickerSetIds,\n stickerSetsById,\n messageTextSize,\n animationLevel,\n messageSendKeyCombo,\n shouldAutoDownloadMediaFromContacts,\n shouldAutoDownloadMediaInPrivateChats,\n shouldAutoDownloadMediaInGroups,\n shouldAutoDownloadMediaInChannels,\n shouldAutoPlayGifs,\n shouldAutoPlayVideos,\n shouldSuggestStickers,\n shouldLoopStickers,\n setSettingOption,\n loadStickerSets,\n loadAddedStickers,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const stickerSettingsRef = useRef<HTMLDivElement>(null);\n const { observe: observeIntersectionForCovers } = useIntersectionObserver({ rootRef: stickerSettingsRef });\n const [isModalOpen, openModal, closeModal] = useFlag();\n const [sticker, setSticker] = useState<ApiSticker>();\n\n const lang = useLang();\n\n const KEYBOARD_SEND_OPTIONS = !IS_TOUCH_ENV ? [\n { value: 'enter', label: lang('lng_settings_send_enter'), subLabel: 'New line by Shift + Enter' },\n {\n value: 'ctrl-enter',\n label: lang(IS_MAC_OS ? 'lng_settings_send_cmdenter' : 'lng_settings_send_ctrlenter'),\n subLabel: 'New line by Enter',\n },\n ] : undefined;\n\n useEffect(() => {\n loadStickerSets();\n }, [loadStickerSets]);\n\n useEffect(() => {\n if (stickerSetIds && stickerSetIds.length) {\n loadAddedStickers();\n }\n }, [stickerSetIds, loadAddedStickers]);\n\n const handleAnimationLevelChange = useCallback((newLevel: number) => {\n ANIMATION_LEVEL_OPTIONS.forEach((_, i) => {\n document.body.classList.toggle(`animation-level-${i}`, newLevel === i);\n });\n\n setSettingOption({ animationLevel: newLevel });\n }, [setSettingOption]);\n\n const handleMessageTextSizeChange = useCallback((newSize: number) => {\n document.documentElement.style.setProperty('--message-text-size', `${newSize}px`);\n\n setSettingOption({ messageTextSize: newSize });\n }, [setSettingOption]);\n\n const handleStickerSetClick = useCallback((value: ApiSticker) => {\n setSticker(value);\n openModal();\n }, [openModal]);\n\n const stickerSets = stickerSetIds && stickerSetIds.map((id: string) => {\n return stickerSetsById && stickerSetsById[id] && stickerSetsById[id].installedDate ? stickerSetsById[id] : false;\n }).filter(Boolean);\n\n return (\n <div className=\"settings-content custom-scroll\">\n <div className=\"settings-item pt-3\">\n <h4 className=\"settings-item-header\" dir={lang.isRtl ? 'rtl' : undefined}>{lang('SETTINGS')}</h4>\n\n <RangeSlider\n label={lang('TextSize')}\n // TODO Remove memo-killer\n range={{ min: 12, max: 20 }}\n value={messageTextSize}\n onChange={handleMessageTextSizeChange}\n />\n\n <ListItem\n icon=\"photo\"\n onClick={() => onScreenSelect(SettingsScreens.GeneralChatBackground)}\n >\n {lang('ChatBackground')}\n </ListItem>\n </div>\n\n <div className=\"settings-item\">\n <h4 className=\"settings-item-header\" dir={lang.isRtl ? 'rtl' : undefined}>\n Animation Level\n </h4>\n <p className=\"settings-item-description\" dir={lang.isRtl ? 'rtl' : undefined}>\n Choose the desired animations amount.\n </p>\n\n <RangeSlider\n options={ANIMATION_LEVEL_OPTIONS}\n value={animationLevel}\n onChange={handleAnimationLevelChange}\n />\n </div>\n\n {KEYBOARD_SEND_OPTIONS && (\n <div className=\"settings-item\">\n <h4 className=\"settings-item-header\" dir={lang.isRtl ? 'rtl' : undefined}>{lang('Keyboard')}</h4>\n\n <RadioGroup\n name=\"keyboard-send-settings\"\n options={KEYBOARD_SEND_OPTIONS}\n onChange={(value) => setSettingOption({ messageSendKeyCombo: value })}\n selected={messageSendKeyCombo}\n />\n </div>\n )}\n\n <div className=\"settings-item\">\n <h4 className=\"settings-item-header\" dir={lang.isRtl ? 'rtl' : undefined}>{lang('AutoDownloadMedia')}</h4>\n\n <Checkbox\n label={lang('Contacts')}\n checked={shouldAutoDownloadMediaFromContacts}\n onCheck={(isChecked) => setSettingOption({ shouldAutoDownloadMediaFromContacts: isChecked })}\n />\n <Checkbox\n label={lang('AutodownloadPrivateChats')}\n checked={shouldAutoDownloadMediaInPrivateChats}\n onCheck={(isChecked) => setSettingOption({ shouldAutoDownloadMediaInPrivateChats: isChecked })}\n />\n <Checkbox\n label={lang('AutodownloadGroupChats')}\n checked={shouldAutoDownloadMediaInGroups}\n onCheck={(isChecked) => setSettingOption({ shouldAutoDownloadMediaInGroups: isChecked })}\n />\n <Checkbox\n label={lang('FilterChannels')}\n checked={shouldAutoDownloadMediaInChannels}\n onCheck={(isChecked) => setSettingOption({ shouldAutoDownloadMediaInChannels: isChecked })}\n />\n </div>\n\n <div className=\"settings-item\">\n <h4 className=\"settings-item-header\" dir={lang.isRtl ? 'rtl' : undefined}>{lang('AutoplayMedia')}</h4>\n\n <Checkbox\n label={lang('GifsTab2')}\n checked={shouldAutoPlayGifs}\n onCheck={(isChecked) => setSettingOption({ shouldAutoPlayGifs: isChecked })}\n />\n <Checkbox\n label={lang('VideosTitle')}\n checked={shouldAutoPlayVideos}\n onCheck={(isChecked) => setSettingOption({ shouldAutoPlayVideos: isChecked })}\n />\n </div>\n\n <div className=\"settings-item\">\n <h4 className=\"settings-item-header\" dir={lang.isRtl ? 'rtl' : undefined}>{lang('AccDescrStickers')}</h4>\n\n <Checkbox\n label={lang('SuggestStickers')}\n checked={shouldSuggestStickers}\n onCheck={(isChecked) => setSettingOption({ shouldSuggestStickers: isChecked })}\n />\n <Checkbox\n label={lang('LoopAnimatedStickers')}\n checked={shouldLoopStickers}\n onCheck={(isChecked) => setSettingOption({ shouldLoopStickers: isChecked })}\n />\n\n <div className=\"mt-4\" ref={stickerSettingsRef}>\n {stickerSets && stickerSets.map((stickerSet: ApiStickerSet) => (\n <SettingsStickerSet\n key={stickerSet.id}\n stickerSet={stickerSet}\n observeIntersection={observeIntersectionForCovers}\n onClick={handleStickerSetClick}\n />\n ))}\n </div>\n {sticker && (\n <StickerSetModal\n isOpen={isModalOpen}\n fromSticker={sticker}\n onClose={closeModal}\n />\n )}\n </div>\n </div>\n );\n};\n\nexport default memo(withGlobal<OwnProps>(\n (global): StateProps => {\n return {\n ...pick(global.settings.byKey,\n [\n 'messageTextSize',\n 'animationLevel',\n 'messageSendKeyCombo',\n 'shouldAutoDownloadMediaFromContacts',\n 'shouldAutoDownloadMediaInPrivateChats',\n 'shouldAutoDownloadMediaInGroups',\n 'shouldAutoDownloadMediaInChannels',\n 'shouldAutoPlayGifs',\n 'shouldAutoPlayVideos',\n 'shouldSuggestStickers',\n 'shouldLoopStickers',\n ]),\n stickerSetIds: global.stickers.added.setIds,\n stickerSetsById: global.stickers.setsById,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'setSettingOption', 'loadStickerSets', 'loadAddedStickers',\n ]),\n)(SettingsGeneral));\n","let fileSelector: HTMLInputElement;\n\nexport function openSystemFilesDialog(accept = '*', callback: (e: Event) => void, noMultiple = false) {\n if (!fileSelector) {\n fileSelector = document.createElement('input');\n fileSelector.setAttribute('type', 'file');\n }\n\n fileSelector.setAttribute('accept', accept);\n\n if (noMultiple) {\n fileSelector.removeAttribute('multiple');\n } else {\n fileSelector.setAttribute('multiple', 'multiple');\n }\n\n // eslint-disable-next-line no-null/no-null\n fileSelector.onchange = null;\n fileSelector.value = '';\n fileSelector.onchange = callback;\n\n fileSelector.click();\n}\n","/* eslint-disable eqeqeq */\n/* eslint-disable prefer-template */\n/* eslint-disable prefer-const */\n/* eslint-disable prefer-destructuring */\n/* eslint-disable one-var */\n/* eslint-disable one-var-declaration-per-line */\n\nimport { preloadImage } from './files';\n\n/**\n * HEX > RGB\n * input: 'xxxxxx' (ex. 'ed15fa') case-insensitive\n * output: [r, g, b] ([0-255, 0-255, 0-255])\n */\nexport function hex2rgb(param: string): [number, number, number] {\n return [\n parseInt(param.substring(0, 2), 16),\n parseInt(param.substring(2, 4), 16),\n parseInt(param.substring(4, 6), 16),\n ];\n}\n\n/**\n * RGB > HEX\n * input: [r, g, b] ([0-255, 0-255, 0-255])\n * output: 'xxxxxx' (ex. 'ff0000')\n */\nexport function rgb2hex(param: [number, number, number]) {\n const p0 = param[0].toString(16);\n const p1 = param[1].toString(16);\n const p2 = param[2].toString(16);\n return (p0.length == 1 ? '0' + p0 : p0) + (p1.length == 1 ? '0' + p1 : p1) + (p2.length == 1 ? '0' + p2 : p2);\n}\n\n/**\n * Converts an RGB color value to HSV. Conversion formula\n * adapted from http://en.wikipedia.org/wiki/HSV_color_space.\n * Assumes r, g, and b are contained in the set [0, 255] and\n * returns h, s, and v in the set [0, 1].\n *\n * @param Number r The red color value\n * @param Number g The green color value\n * @param Number b The blue color value\n * @return Array The HSV representation\n */\nexport function rgb2hsb([r, g, b]: [number, number, number]): [number, number, number] {\n r /= 255;\n g /= 255;\n b /= 255;\n\n let max = Math.max(r, g, b), min = Math.min(r, g, b);\n let h!: number, s: number, v: number = max;\n\n let d = max - min;\n s = max == 0 ? 0 : d / max;\n\n if (max == min) {\n h = 0; // achromatic\n } else {\n switch (max) {\n case r:\n h = (g - b) / d + (g < b ? 6 : 0);\n break;\n case g:\n h = (b - r) / d + 2;\n break;\n case b:\n h = (r - g) / d + 4;\n break;\n }\n\n h /= 6;\n }\n\n return [h, s, v];\n}\n\n/**\n * Converts an HSV color value to RGB. Conversion formula\n * adapted from http://en.wikipedia.org/wiki/HSV_color_space.\n * Assumes h, s, and v are contained in the set [0, 1] and\n * returns r, g, and b in the set [0, 255].\n *\n * @param Number h The hue\n * @param Number s The saturation\n * @param Number v The value\n * @return Array The RGB representation\n */\nexport function hsb2rgb([h, s, v]: [number, number, number]): [number, number, number] {\n let r!: number, g!: number, b!: number;\n\n let i = Math.floor(h * 6);\n let f = h * 6 - i;\n let p = v * (1 - s);\n let q = v * (1 - f * s);\n let t = v * (1 - (1 - f) * s);\n\n switch (i % 6) {\n case 0:\n r = v;\n g = t;\n b = p;\n break;\n case 1:\n r = q;\n g = v;\n b = p;\n break;\n case 2:\n r = p;\n g = v;\n b = t;\n break;\n case 3:\n r = p;\n g = q;\n b = v;\n break;\n case 4:\n r = t;\n g = p;\n b = v;\n break;\n case 5:\n r = v;\n g = p;\n b = q;\n break;\n }\n\n return [\n Math.round(r * 255),\n Math.round(g * 255),\n Math.round(b * 255),\n ];\n}\n\nexport async function getAverageColor(url: string): Promise<[number, number, number]> {\n // Only visit every 5 pixels\n const blockSize = 5;\n const defaultRGB: [number, number, number] = [0, 0, 0];\n let data;\n let width;\n let height;\n let i = -4;\n let length;\n let rgb: [number, number, number] = [0, 0, 0];\n let count = 0;\n\n const canvas = document.createElement('canvas');\n const context = canvas.getContext && canvas.getContext('2d');\n if (!context) {\n return defaultRGB;\n }\n\n const image = await preloadImage(url);\n height = image.naturalHeight || image.offsetHeight || image.height;\n width = image.naturalWidth || image.offsetWidth || image.width;\n canvas.height = height;\n canvas.width = width;\n\n context.drawImage(image, 0, 0);\n\n try {\n data = context.getImageData(0, 0, width, height);\n } catch (e) {\n return defaultRGB;\n }\n\n length = data.data.length;\n\n // eslint-disable-next-line no-cond-assign\n while ((i += blockSize * 4) < length) {\n ++count;\n rgb[0] += data.data[i];\n rgb[1] += data.data[i + 1];\n rgb[2] += data.data[i + 2];\n }\n\n rgb[0] = Math.floor(rgb[0] / count);\n rgb[1] = Math.floor(rgb[1] / count);\n rgb[2] = Math.floor(rgb[2] / count);\n\n return rgb;\n}\n\n// eslint-disable-next-line max-len\n// Function was adapted from https://github.com/telegramdesktop/tdesktop/blob/35ff621b5b52f7e3553fb0f990ea13ade7101b8e/Telegram/SourceFiles/data/data_wall_paper.cpp#L518\nexport function getPatternColor(rgbColor: [number, number, number]) {\n let [hue, saturation, value] = rgb2hsb(rgbColor);\n\n saturation = Math.min(1, saturation + 0.05 + 0.1 * (1 - saturation));\n value = value > 0.5\n ? Math.max(0, value * 0.65)\n : Math.max(0, Math.min(1, 1 - value * 0.65));\n\n return `hsla(${hue * 360}, ${saturation * 100}%, ${value * 100}%, .4)`;\n}\n","import React, {\n FC, memo, useCallback, useEffect, useState, useRef,\n} from '../../../lib/teact/teact';\nimport { ApiWallpaper } from '../../../api/types';\nimport { ThemeKey, UPLOADING_WALLPAPER_SLUG } from '../../../types';\n\nimport { CUSTOM_BG_CACHE_NAME } from '../../../config';\nimport * as cacheApi from '../../../util/cacheApi';\nimport { fetchBlob } from '../../../util/files';\nimport useTransitionForMedia from '../../../hooks/useTransitionForMedia';\nimport buildClassName from '../../../util/buildClassName';\nimport useMedia from '../../../hooks/useMedia';\nimport useMediaWithDownloadProgress from '../../../hooks/useMediaWithDownloadProgress';\nimport useShowTransition from '../../../hooks/useShowTransition';\nimport usePrevious from '../../../hooks/usePrevious';\nimport useCanvasBlur from '../../../hooks/useCanvasBlur';\n\nimport ProgressSpinner from '../../ui/ProgressSpinner';\n\nimport './WallpaperTile.scss';\n\ntype OwnProps = {\n wallpaper: ApiWallpaper;\n theme: ThemeKey;\n isSelected: boolean;\n onClick: (slug: string) => void;\n};\n\nconst WallpaperTile: FC<OwnProps> = ({\n wallpaper,\n theme,\n isSelected,\n onClick,\n}) => {\n const { slug, document } = wallpaper;\n const localMediaHash = `wallpaper${document.id!}`;\n const localBlobUrl = document.previewBlobUrl;\n const previewBlobUrl = useMedia(`${localMediaHash}?size=m`);\n const thumbRef = useCanvasBlur(\n document.thumbnail && document.thumbnail.dataUri,\n Boolean(previewBlobUrl),\n true,\n );\n const {\n shouldRenderThumb, shouldRenderFullMedia, transitionClassNames,\n } = useTransitionForMedia(previewBlobUrl || localBlobUrl, 'slow');\n const [isDownloadAllowed, setIsDownloadAllowed] = useState(false);\n const {\n mediaData: fullMedia, downloadProgress,\n } = useMediaWithDownloadProgress(localMediaHash, !isDownloadAllowed);\n const wasDownloadDisabled = usePrevious(isDownloadAllowed) === false;\n const { shouldRender: shouldRenderSpinner, transitionClassNames: spinnerClassNames } = useShowTransition(\n (isDownloadAllowed && !fullMedia) || slug === UPLOADING_WALLPAPER_SLUG,\n undefined,\n wasDownloadDisabled,\n 'slow',\n );\n // To prevent triggering of the effect for useCallback\n const cacheKeyRef = useRef<string>();\n cacheKeyRef.current = theme;\n\n const handleSelect = useCallback(() => {\n (async () => {\n const blob = await fetchBlob(fullMedia!);\n await cacheApi.save(CUSTOM_BG_CACHE_NAME, cacheKeyRef.current!, blob);\n onClick(slug);\n })();\n }, [fullMedia, onClick, slug]);\n\n useEffect(() => {\n if (fullMedia) {\n handleSelect();\n }\n }, [fullMedia, handleSelect]);\n\n const handleClick = useCallback(() => {\n if (fullMedia) {\n handleSelect();\n } else {\n setIsDownloadAllowed((isAllowed) => !isAllowed);\n }\n }, [fullMedia, handleSelect]);\n\n const className = buildClassName(\n 'WallpaperTile',\n isSelected && 'selected',\n );\n\n return (\n <div className={className} onClick={handleClick}>\n <div className=\"media-inner\">\n {shouldRenderThumb && (\n <canvas\n ref={thumbRef}\n className=\"thumbnail\"\n />\n )}\n {shouldRenderFullMedia && (\n <img\n src={previewBlobUrl || localBlobUrl}\n className={`full-media ${transitionClassNames}`}\n alt=\"\"\n />\n )}\n {shouldRenderSpinner && (\n <div className={buildClassName('spinner-container', spinnerClassNames)}>\n <ProgressSpinner progress={downloadProgress} onClick={handleClick} />\n </div>\n )}\n </div>\n </div>\n );\n};\n\nexport default memo(WallpaperTile);\n","import React, {\n FC, memo, useEffect, useCallback, useRef,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../../global/types';\nimport { SettingsScreens, ThemeKey, UPLOADING_WALLPAPER_SLUG } from '../../../types';\nimport { ApiWallpaper } from '../../../api/types';\n\nimport { DARK_THEME_PATTERN_COLOR, DEFAULT_PATTERN_COLOR } from '../../../config';\nimport { pick } from '../../../util/iteratees';\nimport { throttle } from '../../../util/schedulers';\nimport { openSystemFilesDialog } from '../../../util/systemFilesDialog';\nimport { getAverageColor, getPatternColor, rgb2hex } from '../../../util/colors';\nimport useLang from '../../../hooks/useLang';\n\nimport ListItem from '../../ui/ListItem';\nimport Checkbox from '../../ui/Checkbox';\nimport Loading from '../../ui/Loading';\nimport WallpaperTile from './WallpaperTile';\n\nimport './SettingsGeneralBackground.scss';\n\ntype OwnProps = {\n onScreenSelect: (screen: SettingsScreens) => void;\n};\n\ntype StateProps = {\n background?: string;\n isBlurred?: boolean;\n loadedWallpapers?: ApiWallpaper[];\n theme: ThemeKey;\n};\n\ntype DispatchProps = Pick<GlobalActions, (\n 'loadWallpapers' | 'uploadWallpaper' | 'setThemeSettings'\n)>;\n\nconst SUPPORTED_TYPES = 'image/jpeg';\n\nconst runThrottled = throttle((cb) => cb(), 60000, true);\n\nconst SettingsGeneralBackground: FC<OwnProps & StateProps & DispatchProps> = ({\n onScreenSelect,\n background,\n isBlurred,\n loadedWallpapers,\n theme,\n loadWallpapers,\n uploadWallpaper,\n setThemeSettings,\n}) => {\n const themeRef = useRef<string>();\n themeRef.current = theme;\n // Due to the parent Transition, this component never gets unmounted,\n // that's why we use throttled API call on every update.\n useEffect(() => {\n runThrottled(() => {\n loadWallpapers();\n });\n }, [loadWallpapers]);\n\n const handleFileSelect = useCallback((e: Event) => {\n const { files } = e.target as HTMLInputElement;\n\n if (files && files.length > 0) {\n uploadWallpaper(files[0]);\n }\n }, [uploadWallpaper]);\n\n const handleUploadWallpaper = useCallback(() => {\n openSystemFilesDialog(SUPPORTED_TYPES, handleFileSelect, true);\n }, [handleFileSelect]);\n\n const handleSetColor = useCallback(() => {\n onScreenSelect(SettingsScreens.GeneralChatBackgroundColor);\n }, [onScreenSelect]);\n\n const handleResetToDefault = useCallback(() => {\n setThemeSettings({\n theme,\n background: undefined,\n backgroundColor: undefined,\n isBlurred: true,\n patternColor: theme === 'dark' ? DARK_THEME_PATTERN_COLOR : DEFAULT_PATTERN_COLOR,\n });\n }, [setThemeSettings, theme]);\n\n const handleWallPaperSelect = useCallback((slug: string) => {\n setThemeSettings({ theme: themeRef.current, background: slug });\n const currentWallpaper = loadedWallpapers && loadedWallpapers.find((wallpaper) => wallpaper.slug === slug);\n if (currentWallpaper && currentWallpaper.document.thumbnail) {\n getAverageColor(currentWallpaper.document.thumbnail.dataUri)\n .then((color) => {\n const patternColor = getPatternColor(color);\n const rgbColor = `#${rgb2hex(color)}`;\n setThemeSettings({ theme: themeRef.current, backgroundColor: rgbColor, patternColor });\n });\n }\n }, [loadedWallpapers, setThemeSettings]);\n\n const handleWallPaperBlurChange = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {\n setThemeSettings({ theme: themeRef.current, isBlurred: e.target.checked });\n }, [setThemeSettings]);\n\n const lang = useLang();\n\n const isUploading = loadedWallpapers && loadedWallpapers[0] && loadedWallpapers[0].slug === UPLOADING_WALLPAPER_SLUG;\n\n return (\n <div className=\"SettingsGeneralBackground settings-content custom-scroll\">\n <div className=\"settings-item pt-3\">\n <ListItem\n icon=\"camera-add\"\n className=\"mb-0\"\n disabled={isUploading}\n onClick={handleUploadWallpaper}\n >\n {lang('UploadImage')}\n </ListItem>\n\n <ListItem\n icon=\"colorize\"\n className=\"mb-0\"\n onClick={handleSetColor}\n >\n {lang('SetColor')}\n </ListItem>\n\n <ListItem icon=\"favorite\" onClick={handleResetToDefault}>\n {lang('ThemeResetToDefaults')}\n </ListItem>\n\n <Checkbox\n label={lang('BackgroundBlurred')}\n checked={Boolean(isBlurred)}\n onChange={handleWallPaperBlurChange}\n />\n </div>\n\n {loadedWallpapers ? (\n <div className=\"settings-wallpapers\">\n {loadedWallpapers.map((wallpaper) => (\n <WallpaperTile\n wallpaper={wallpaper}\n theme={theme}\n isSelected={background === wallpaper.slug}\n onClick={handleWallPaperSelect}\n />\n ))}\n </div>\n ) : (\n <Loading />\n )}\n </div>\n );\n};\n\nexport default memo(withGlobal<OwnProps>(\n (global): StateProps => {\n const { theme } = global.settings.byKey;\n const { background, isBlurred } = global.settings.themes[theme] || {};\n const { loadedWallpapers } = global.settings;\n\n return {\n background,\n isBlurred,\n loadedWallpapers,\n theme,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'loadWallpapers', 'uploadWallpaper', 'setThemeSettings',\n ]),\n)(SettingsGeneralBackground));\n","import { ChangeEvent, MutableRefObject, RefObject } from 'react';\nimport React, {\n FC, memo, useCallback, useEffect, useRef, useState,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../../global/types';\nimport { SettingsScreens, ThemeKey } from '../../../types';\n\nimport { pick } from '../../../util/iteratees';\nimport {\n getPatternColor, hex2rgb, hsb2rgb, rgb2hex, rgb2hsb,\n} from '../../../util/colors';\nimport { captureEvents, RealTouchEvent } from '../../../util/captureEvents';\nimport useFlag from '../../../hooks/useFlag';\nimport buildClassName from '../../../util/buildClassName';\n\nimport InputText from '../../ui/InputText';\n\nimport './SettingsGeneralBackgroundColor.scss';\n\ntype OwnProps = {\n onScreenSelect: (screen: SettingsScreens) => void;\n};\n\ntype StateProps = {\n backgroundColor?: string;\n theme: ThemeKey;\n};\n\ntype DispatchProps = Pick<GlobalActions, 'setThemeSettings'>;\n\ninterface CanvasRects {\n colorRect: {\n offsetLeft: number;\n top: number;\n width: number;\n height: number;\n };\n hueRect: {\n offsetLeft: number;\n width: number;\n };\n}\n\nconst DEFAULT_HSB = rgb2hsb(hex2rgb('e6ebee'));\nconst PREDEFINED_COLORS = [\n '#e6ebee', '#b2cee1', '#008dd0', '#c6e7cb', '#c4e1a6', '#60b16e',\n '#ccd0af', '#a6a997', '#7a7072', '#fdd7af', '#fdb76e', '#dd8851',\n];\n\nconst SettingsGeneralBackground: FC<OwnProps & StateProps & DispatchProps> = ({\n theme,\n backgroundColor,\n setThemeSettings,\n}) => {\n const themeRef = useRef<string>();\n themeRef.current = theme;\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 colorPickerRef = useRef<HTMLDivElement>(null);\n // eslint-disable-next-line no-null/no-null\n const huePickerRef = useRef<HTMLDivElement>(null);\n const isFirstRunRef = useRef(true);\n\n const [hsb, setHsb] = useState(getInitialHsb(backgroundColor));\n // Cache for drag handlers\n const hsbRef = useRef(hsb);\n useEffect(() => {\n hsbRef.current = hsb;\n }, [hsb]);\n\n const [isDragging, markIsDragging, unmarkIsDragging] = useFlag();\n const [rgbInput, setRgbInput] = useState('');\n const [hexInput, setHexInput] = useState('');\n\n const rectsRef = useRef<CanvasRects>();\n const colorCtxRef = useRef<CanvasRenderingContext2D>();\n\n // Setup: cache rects, subscribe for drag events\n useEffect(() => {\n // We use `offsetLeft` instead of `left` to support screen transition\n const colorRect = {\n offsetLeft: colorPickerRef.current!.offsetLeft,\n ...pick(colorPickerRef.current!.getBoundingClientRect(), ['top', 'width', 'height']),\n };\n const hueRect = {\n offsetLeft: huePickerRef.current!.offsetLeft,\n ...pick(huePickerRef.current!.getBoundingClientRect(), ['width']),\n };\n\n rectsRef.current = { colorRect, hueRect };\n\n function handleColorDrag(e: MouseEvent | RealTouchEvent) {\n const colorPosition = [\n Math.min(Math.max(0, e.pageX! - colorRect.offsetLeft), colorRect.width - 1),\n Math.min(Math.max(0, e.pageY! - colorRect.top + containerRef.current!.scrollTop), colorRect.height - 1),\n ];\n\n const { huePosition } = hsb2positions(hsbRef.current, rectsRef.current!);\n\n setHsb(positions2hsb({ colorPosition, huePosition }, rectsRef.current!));\n markIsDragging();\n }\n\n captureEvents(colorPickerRef.current!, {\n onCapture: handleColorDrag,\n onDrag: handleColorDrag,\n onRelease: unmarkIsDragging,\n onClick: unmarkIsDragging,\n withCursor: true,\n });\n\n function handleHueDrag(e: MouseEvent | RealTouchEvent) {\n const { colorPosition } = hsb2positions(hsbRef.current, rectsRef.current!);\n const huePosition = Math.min(Math.max(0, e.pageX! - hueRect.offsetLeft), hueRect.width - 1);\n\n setHsb(positions2hsb({ colorPosition, huePosition }, rectsRef.current!));\n markIsDragging();\n }\n\n captureEvents(huePickerRef.current!, {\n onCapture: handleHueDrag,\n onDrag: handleHueDrag,\n onRelease: unmarkIsDragging,\n onClick: unmarkIsDragging,\n withCursor: true,\n });\n }, [markIsDragging, unmarkIsDragging]);\n\n const { colorPosition = [0, 0], huePosition = 0 } = rectsRef.current ? hsb2positions(hsb, rectsRef.current) : {};\n const hex = rgb2hex(hsb2rgb(hsb));\n const hue = hsb[0];\n const hueHex = rgb2hex(hsb2rgb([hue, 1, 1]));\n\n // Save value and update inputs when HSL changes\n useEffect(() => {\n const rgb = hsb2rgb(hsb);\n const color = `#${rgb2hex(rgb)}`;\n\n setRgbInput(rgb.join(', '));\n setHexInput(color);\n\n if (!isFirstRunRef.current) {\n const patternColor = getPatternColor(rgb);\n setThemeSettings({\n theme: themeRef.current,\n background: undefined,\n backgroundColor: color,\n patternColor,\n });\n }\n isFirstRunRef.current = false;\n }, [hsb, setThemeSettings]);\n\n // Redraw color picker when hue changes\n useEffect(() => {\n drawColor(colorPickerRef.current!.firstChild as HTMLCanvasElement, hue, colorCtxRef, rectsRef);\n }, [hue]);\n\n // Initially draw hue picker\n useEffect(() => {\n drawHue(huePickerRef.current!.firstChild as HTMLCanvasElement);\n }, []);\n\n const handleRgbChange = useCallback((e: ChangeEvent<HTMLInputElement>) => {\n const rgbValue = e.currentTarget.value.replace(/[^\\d, ]/g, '').slice(0, 13);\n\n if (rgbValue.match(/^\\d{1,3},\\s?\\d{1,3},\\s?\\d{1,3}$/)) {\n const rgb = rgbValue.split(',').map((channel) => Number(channel.trim())) as [number, number, number];\n setHsb(rgb2hsb(rgb));\n }\n\n e.currentTarget.value = rgbValue;\n }, []);\n\n const handleHexChange = useCallback((e: ChangeEvent<HTMLInputElement>) => {\n const hexValue = e.currentTarget.value.replace(/[^0-9a-fA-F]/g, '').slice(0, 6);\n\n if (hexValue.match(/^#?[0-9a-fA-F]{6}$/)) {\n setHsb(rgb2hsb(hex2rgb(hexValue.replace('#', ''))));\n }\n\n e.currentTarget.value = hexValue;\n }, []);\n\n const handlePredefinedColorClick = useCallback((e: React.MouseEvent<HTMLInputElement>) => {\n setHsb(rgb2hsb(hex2rgb(e.currentTarget.dataset.color!.replace('#', ''))));\n }, []);\n\n const className = buildClassName(\n 'SettingsGeneralBackgroundColor settings-content custom-scroll',\n isDragging && 'is-dragging',\n );\n\n return (\n <div ref={containerRef} className={className}>\n <div className=\"settings-item pt-3\">\n <div ref={colorPickerRef} className=\"color-picker\">\n <canvas />\n <div\n className=\"handle\"\n // @ts-ignore\n style={`transform: translate(${colorPosition[0]}px, ${colorPosition[1]}px); background-color: #${hex};`}\n />\n </div>\n <div ref={huePickerRef} className=\"hue-picker\">\n <canvas />\n <div\n className=\"handle\"\n // @ts-ignore\n style={`transform: translateX(${huePosition}px); background-color: #${hueHex};`}\n />\n </div>\n <div className=\"tools\">\n <InputText value={hexInput} label=\"HEX\" onChange={handleHexChange} />\n <InputText value={rgbInput} label=\"RGB\" onChange={handleRgbChange} />\n </div>\n </div>\n <div className=\"predefined-colors\">\n {PREDEFINED_COLORS.map((color) => (\n <div\n className={color === `#${hex}` ? 'active' : undefined}\n data-color={color}\n // @ts-ignore\n style={`background-color: ${color};`}\n onClick={handlePredefinedColorClick}\n />\n ))}\n </div>\n </div>\n );\n};\n\nfunction getInitialHsb(backgroundColor?: string) {\n return backgroundColor && backgroundColor.startsWith('#')\n ? rgb2hsb(hex2rgb(backgroundColor.replace('#', '')))\n : DEFAULT_HSB;\n}\n\nfunction hsb2positions(hsb: [number, number, number], rects: CanvasRects) {\n return {\n colorPosition: [\n Math.round((hsb[1]) * (rects.colorRect.width - 1)),\n Math.round((1 - hsb[2]) * (rects.colorRect.height - 1)),\n ],\n huePosition: Math.round(hsb[0] * (rects.hueRect.width - 1)),\n };\n}\n\nfunction positions2hsb(\n { colorPosition, huePosition }: { colorPosition: number[]; huePosition: number },\n rects: CanvasRects,\n): [number, number, number] {\n return [\n huePosition / (rects.hueRect.width - 1),\n colorPosition[0] / (rects.colorRect.width - 1),\n 1 - colorPosition[1] / (rects.colorRect.height - 1),\n ];\n}\n\nfunction drawColor(\n canvas: HTMLCanvasElement,\n hue: number,\n colorCtxRef: MutableRefObject<CanvasRenderingContext2D | undefined>,\n rectsRef: RefObject<CanvasRects | undefined>,\n) {\n let w: number;\n let h: number;\n let ctx: CanvasRenderingContext2D;\n\n if (!colorCtxRef.current || !rectsRef.current) {\n // First run\n w = canvas.offsetWidth;\n h = canvas.offsetHeight;\n ctx = canvas.getContext('2d')!;\n\n canvas.width = w;\n canvas.height = h;\n\n colorCtxRef.current = ctx;\n } else {\n w = rectsRef.current.colorRect.width;\n h = rectsRef.current.colorRect.height;\n ctx = colorCtxRef.current;\n }\n\n const imgData = ctx!.createImageData(w, h);\n const pixels = imgData.data;\n const col = hsb2rgb([hue, 1, 1]);\n\n let index = 0;\n\n for (let y = 0; y < h; y++) {\n const perY = 1 - y / (h - 1);\n const st = [255 * perY, 255 * perY, 255 * perY];\n const ed = [col[0] * perY, col[1] * perY, col[2] * perY];\n for (let x = 0; x < w; x++) {\n const perX = x / (w - 1);\n pixels[index++] = st[0] + (ed[0] - st[0]) * perX;\n pixels[index++] = st[1] + (ed[1] - st[1]) * perX;\n pixels[index++] = st[2] + (ed[2] - st[2]) * perX;\n pixels[index++] = 255;\n }\n }\n\n ctx!.putImageData(imgData, 0, 0);\n}\n\nfunction drawHue(canvas: HTMLCanvasElement) {\n const w = canvas.offsetWidth;\n const h = 1;\n canvas.width = w;\n canvas.height = h;\n const ctx = canvas.getContext('2d')!;\n\n const imgData = ctx.createImageData(w, h);\n const pixels = imgData.data;\n\n let index = 0;\n\n for (let x = 0; x < w; x++) {\n const hue = x / (w - 1);\n const rgb = hsb2rgb([hue, 1, 1]);\n /* eslint-disable prefer-destructuring */\n pixels[index++] = rgb[0];\n pixels[index++] = rgb[1];\n pixels[index++] = rgb[2];\n /* eslint-enable prefer-destructuring */\n pixels[index++] = 255;\n }\n\n ctx.putImageData(imgData, 0, 0);\n}\n\nexport default memo(withGlobal<OwnProps>(\n (global): StateProps => {\n const { theme } = global.settings.byKey;\n const { backgroundColor } = global.settings.themes[theme] || {};\n return {\n backgroundColor,\n theme,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, ['setThemeSettings']),\n)(SettingsGeneralBackground));\n","import { ChangeEvent } from 'react';\nimport React, {\n FC, memo, useCallback, useEffect,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../../global/types';\n\nimport { pick } from '../../../util/iteratees';\nimport useLang from '../../../hooks/useLang';\n\nimport Checkbox from '../../ui/Checkbox';\n\ntype StateProps = {\n hasPrivateChatsNotifications: boolean;\n hasPrivateChatsMessagePreview: boolean;\n hasGroupNotifications: boolean;\n hasGroupMessagePreview: boolean;\n hasBroadcastNotifications: boolean;\n hasBroadcastMessagePreview: boolean;\n hasContactJoinedNotifications: boolean;\n};\n\ntype DispatchProps = Pick<GlobalActions, (\n 'loadNotificationSettings' | 'updateContactSignUpNotification' | 'updateNotificationSettings'\n)>;\n\nconst SettingsNotifications: FC<StateProps & DispatchProps> = ({\n hasPrivateChatsNotifications,\n hasPrivateChatsMessagePreview,\n hasGroupNotifications,\n hasGroupMessagePreview,\n hasBroadcastNotifications,\n hasBroadcastMessagePreview,\n hasContactJoinedNotifications,\n loadNotificationSettings,\n updateContactSignUpNotification,\n updateNotificationSettings,\n}) => {\n useEffect(() => {\n loadNotificationSettings();\n }, [loadNotificationSettings]);\n\n const handleSettingsChange = useCallback((\n e: ChangeEvent<HTMLInputElement>,\n peerType: 'contact' | 'group' | 'broadcast',\n setting: 'silent' | 'showPreviews',\n ) => {\n const currentIsSilent = peerType === 'contact'\n ? !hasPrivateChatsNotifications\n : !(peerType === 'group' ? hasGroupNotifications : hasBroadcastNotifications);\n const currentShouldShowPreviews = peerType === 'contact'\n ? hasPrivateChatsMessagePreview\n : (peerType === 'group' ? hasGroupMessagePreview : hasBroadcastMessagePreview);\n\n updateNotificationSettings({\n peerType,\n ...(setting === 'silent' && { isSilent: !e.target.checked, shouldShowPreviews: currentShouldShowPreviews }),\n ...(setting === 'showPreviews' && { shouldShowPreviews: e.target.checked, isSilent: currentIsSilent }),\n });\n }, [\n hasBroadcastMessagePreview, hasBroadcastNotifications,\n hasGroupMessagePreview, hasGroupNotifications,\n hasPrivateChatsMessagePreview, hasPrivateChatsNotifications,\n updateNotificationSettings,\n ]);\n\n const handleContactNotificationChange = useCallback((e: ChangeEvent<HTMLInputElement>) => {\n updateContactSignUpNotification({\n isSilent: !e.target.checked,\n });\n }, [updateContactSignUpNotification]);\n\n const lang = useLang();\n\n return (\n <div className=\"settings-content custom-scroll\">\n <div className=\"settings-item\">\n <h4 className=\"settings-item-header\" dir={lang.isRtl ? 'rtl' : undefined}>\n {lang('AutodownloadPrivateChats')}\n </h4>\n\n <Checkbox\n label={lang('NotificationsForPrivateChats')}\n subLabel={lang(hasPrivateChatsNotifications ? 'NotificationsEnabled' : 'NotificationsDisabled')}\n checked={hasPrivateChatsNotifications}\n onChange={(e) => { handleSettingsChange(e, 'contact', 'silent'); }}\n />\n <Checkbox\n label={lang('MessagePreview')}\n subLabel={lang(hasPrivateChatsMessagePreview ? 'PreviewEnabled' : 'PreviewDisabled')}\n checked={hasPrivateChatsMessagePreview}\n onChange={(e) => { handleSettingsChange(e, 'contact', 'showPreviews'); }}\n />\n </div>\n\n <div className=\"settings-item\">\n <h4 className=\"settings-item-header\" dir={lang.isRtl ? 'rtl' : undefined}>{lang('FilterGroups')}</h4>\n\n <Checkbox\n label={lang('NotificationsForGroups')}\n subLabel={lang(hasGroupNotifications ? 'NotificationsEnabled' : 'NotificationsDisabled')}\n checked={hasGroupNotifications}\n onChange={(e) => { handleSettingsChange(e, 'group', 'silent'); }}\n />\n <Checkbox\n label={lang('MessagePreview')}\n subLabel={lang(hasGroupMessagePreview ? 'PreviewEnabled' : 'PreviewDisabled')}\n checked={hasGroupMessagePreview}\n onChange={(e) => { handleSettingsChange(e, 'group', 'showPreviews'); }}\n />\n </div>\n\n <div className=\"settings-item\">\n <h4 className=\"settings-item-header\" dir={lang.isRtl ? 'rtl' : undefined}>{lang('FilterChannels')}</h4>\n\n <Checkbox\n label={lang('NotificationsForChannels')}\n subLabel={lang(hasBroadcastNotifications ? 'NotificationsEnabled' : 'NotificationsDisabled')}\n checked={hasBroadcastNotifications}\n onChange={(e) => { handleSettingsChange(e, 'broadcast', 'silent'); }}\n />\n <Checkbox\n label={lang('MessagePreview')}\n subLabel={lang(hasBroadcastMessagePreview ? 'PreviewEnabled' : 'PreviewDisabled')}\n checked={hasBroadcastMessagePreview}\n onChange={(e) => { handleSettingsChange(e, 'broadcast', 'showPreviews'); }}\n />\n </div>\n\n <div className=\"settings-item\">\n <h4 className=\"settings-item-header\" dir={lang.isRtl ? 'rtl' : undefined}>{lang('PhoneOther')}</h4>\n\n <Checkbox\n label={lang('ContactJoined')}\n checked={hasContactJoinedNotifications}\n onChange={handleContactNotificationChange}\n />\n </div>\n </div>\n );\n};\n\nexport default memo(withGlobal((global): StateProps => {\n return {\n hasPrivateChatsNotifications: Boolean(global.settings.byKey.hasPrivateChatsNotifications),\n hasPrivateChatsMessagePreview: Boolean(global.settings.byKey.hasPrivateChatsMessagePreview),\n hasGroupNotifications: Boolean(global.settings.byKey.hasGroupNotifications),\n hasGroupMessagePreview: Boolean(global.settings.byKey.hasGroupMessagePreview),\n hasBroadcastNotifications: Boolean(global.settings.byKey.hasBroadcastNotifications),\n hasBroadcastMessagePreview: Boolean(global.settings.byKey.hasBroadcastMessagePreview),\n hasContactJoinedNotifications: Boolean(global.settings.byKey.hasContactJoinedNotifications),\n };\n},\n(setGlobal, actions): DispatchProps => pick(actions, [\n 'loadNotificationSettings',\n 'updateContactSignUpNotification',\n 'updateNotificationSettings',\n]))(SettingsNotifications));\n","import React, { FC, memo, useEffect } from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../../global/types';\nimport { PrivacyVisibility, SettingsScreens } from '../../../types';\n\nimport { pick } from '../../../util/iteratees';\nimport useLang from '../../../hooks/useLang';\n\nimport ListItem from '../../ui/ListItem';\n\ntype OwnProps = {\n onScreenSelect: (screen: SettingsScreens) => void;\n};\n\ntype StateProps = {\n hasPassword?: boolean;\n blockedCount: number;\n sessionsCount: number;\n visibilityPrivacyPhoneNumber?: PrivacyVisibility;\n visibilityPrivacyLastSeen?: PrivacyVisibility;\n visibilityPrivacyProfilePhoto?: PrivacyVisibility;\n visibilityPrivacyForwarding?: PrivacyVisibility;\n visibilityPrivacyGroupChats?: PrivacyVisibility;\n};\n\ntype DispatchProps = Pick<GlobalActions, 'loadBlockedContacts' | 'loadAuthorizations' | 'loadPrivacySettings'>;\n\nconst SettingsPrivacy: FC<OwnProps & StateProps & DispatchProps> = ({\n onScreenSelect,\n hasPassword,\n blockedCount,\n sessionsCount,\n visibilityPrivacyPhoneNumber,\n visibilityPrivacyLastSeen,\n visibilityPrivacyProfilePhoto,\n visibilityPrivacyForwarding,\n visibilityPrivacyGroupChats,\n loadPrivacySettings,\n loadBlockedContacts,\n loadAuthorizations,\n}) => {\n useEffect(() => {\n loadBlockedContacts();\n loadAuthorizations();\n loadPrivacySettings();\n }, [loadBlockedContacts, loadAuthorizations, loadPrivacySettings]);\n\n const lang = useLang();\n\n function getVisibilityValue(visibility?: PrivacyVisibility) {\n switch (visibility) {\n case 'everybody':\n return lang('P2PEverybody');\n\n case 'contacts':\n return lang('P2PContacts');\n\n case 'nobody':\n return lang('P2PNobody');\n }\n\n return undefined;\n }\n\n return (\n <div className=\"settings-content custom-scroll\">\n <div className=\"settings-item pt-3\">\n <ListItem\n icon=\"delete-user\"\n narrow\n onClick={() => onScreenSelect(SettingsScreens.PrivacyBlockedUsers)}\n >\n <div className=\"multiline-menu-item\">\n <span className=\"title\">{lang('BlockedUsers')}</span>\n {blockedCount > 0 && (\n <span className=\"subtitle\" dir=\"auto\">\n {lang('Users', blockedCount)}\n </span>\n )}\n </div>\n </ListItem>\n <ListItem\n icon=\"lock\"\n narrow\n onClick={() => onScreenSelect(\n hasPassword ? SettingsScreens.TwoFaEnabled : SettingsScreens.TwoFaDisabled,\n )}\n >\n <div className=\"multiline-menu-item\">\n <span className=\"title\">{lang('TwoStepVerification')}</span>\n <span className=\"subtitle\" dir=\"auto\">\n {lang(hasPassword ? 'PasswordOn' : 'PasswordOff')}\n </span>\n </div>\n </ListItem>\n <ListItem\n icon=\"active-sessions\"\n narrow\n onClick={() => onScreenSelect(SettingsScreens.PrivacyActiveSessions)}\n >\n <div className=\"multiline-menu-item\">\n <span className=\"title\">{lang('SessionsTitle')}</span>\n {sessionsCount > 0 && (\n <span className=\"subtitle\" dir=\"auto\">\n {sessionsCount === 1 ? '1 session' : `${sessionsCount} sessions`}\n </span>\n )}\n </div>\n </ListItem>\n </div>\n\n <div className=\"settings-item\">\n <h4 className=\"settings-item-header mb-4\" dir={lang.isRtl ? 'rtl' : undefined}>{lang('PrivacyTitle')}</h4>\n\n <ListItem\n narrow\n onClick={() => onScreenSelect(SettingsScreens.PrivacyPhoneNumber)}\n >\n <div className=\"multiline-menu-item\">\n <span className=\"title\">{lang('PrivacyPhoneTitle')}</span>\n <span className=\"subtitle\" dir=\"auto\">\n {getVisibilityValue(visibilityPrivacyPhoneNumber)}\n </span>\n </div>\n </ListItem>\n <ListItem\n narrow\n onClick={() => onScreenSelect(SettingsScreens.PrivacyLastSeen)}\n >\n <div className=\"multiline-menu-item\">\n <span className=\"title\">{lang('LastSeenTitle')}</span>\n <span className=\"subtitle\" dir=\"auto\">\n {getVisibilityValue(visibilityPrivacyLastSeen)}\n </span>\n </div>\n </ListItem>\n <ListItem\n narrow\n onClick={() => onScreenSelect(SettingsScreens.PrivacyProfilePhoto)}\n >\n <div className=\"multiline-menu-item\">\n <span className=\"title\">{lang('PrivacyProfilePhotoTitle')}</span>\n <span className=\"subtitle\" dir=\"auto\">\n {getVisibilityValue(visibilityPrivacyProfilePhoto)}\n </span>\n </div>\n </ListItem>\n <ListItem\n narrow\n onClick={() => onScreenSelect(SettingsScreens.PrivacyForwarding)}\n >\n <div className=\"multiline-menu-item\">\n <span className=\"title\">{lang('PrivacyForwardsTitle')}</span>\n <span className=\"subtitle\" dir=\"auto\">\n {getVisibilityValue(visibilityPrivacyForwarding)}\n </span>\n </div>\n </ListItem>\n <ListItem\n narrow\n onClick={() => onScreenSelect(SettingsScreens.PrivacyGroupChats)}\n >\n <div className=\"multiline-menu-item\">\n <span className=\"title\">{lang('WhoCanAddMe')}</span>\n <span className=\"subtitle\" dir=\"auto\">\n {getVisibilityValue(visibilityPrivacyGroupChats)}\n </span>\n </div>\n </ListItem>\n </div>\n </div>\n );\n};\n\nexport default memo(withGlobal<OwnProps>(\n (global): StateProps => {\n const {\n settings: {\n byKey: { hasPassword },\n privacy,\n },\n blocked,\n activeSessions,\n } = global;\n\n return {\n hasPassword,\n blockedCount: blocked.totalCount,\n sessionsCount: activeSessions.length,\n visibilityPrivacyPhoneNumber: privacy.phoneNumber && privacy.phoneNumber.visibility,\n visibilityPrivacyLastSeen: privacy.lastSeen && privacy.lastSeen.visibility,\n visibilityPrivacyProfilePhoto: privacy.profilePhoto && privacy.profilePhoto.visibility,\n visibilityPrivacyForwarding: privacy.forwards && privacy.forwards.visibility,\n visibilityPrivacyGroupChats: privacy.chatInvite && privacy.chatInvite.visibility,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'loadBlockedContacts', 'loadAuthorizations', 'loadPrivacySettings',\n ]),\n)(SettingsPrivacy));\n","import React, {\n FC, memo, useCallback, useEffect, useMemo, useState,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../../global/types';\nimport { ISettings } from '../../../types';\nimport { ApiLanguage } from '../../../api/types';\n\nimport { setLanguage } from '../../../util/langProvider';\nimport { pick } from '../../../util/iteratees';\n\nimport RadioGroup from '../../ui/RadioGroup';\nimport Loading from '../../ui/Loading';\nimport useFlag from '../../../hooks/useFlag';\n\ntype StateProps = Pick<ISettings, 'languages' | 'language'>;\n\ntype DispatchProps = Pick<GlobalActions, 'loadLanguages' | 'setSettingOption'>;\n\nconst SettingsLanguage: FC<StateProps & DispatchProps> = ({\n languages,\n language,\n loadLanguages,\n setSettingOption,\n}) => {\n const [selectedLanguage, setSelectedLanguage] = useState<string>(language);\n const [isLoading, markIsLoading, unmarkIsLoading] = useFlag();\n\n // TODO Throttle\n useEffect(() => {\n loadLanguages();\n }, [loadLanguages]);\n\n const handleChange = useCallback((langCode: string) => {\n setSelectedLanguage(langCode);\n markIsLoading();\n\n setLanguage(langCode, () => {\n unmarkIsLoading();\n\n setSettingOption({ language: langCode });\n });\n }, [markIsLoading, unmarkIsLoading, setSettingOption]);\n\n const options = useMemo(() => {\n return languages ? buildOptions(languages) : undefined;\n }, [languages]);\n\n return (\n <div className=\"settings-content settings-item settings-language custom-scroll\">\n {options ? (\n <RadioGroup\n name=\"keyboard-send-settings\"\n options={options}\n selected={selectedLanguage}\n loadingOption={isLoading ? selectedLanguage : undefined}\n onChange={handleChange}\n />\n ) : (\n <Loading />\n )}\n </div>\n );\n};\n\nfunction buildOptions(languages: ApiLanguage[]) {\n const currentLangCode = (window.navigator.language || 'en').toLowerCase();\n const shortLangCode = currentLangCode.substr(0, 2);\n\n return languages.map(({ langCode, nativeName, name }) => ({\n value: langCode,\n label: nativeName,\n subLabel: name,\n })).sort((a) => {\n return currentLangCode && (a.value === currentLangCode || a.value === shortLangCode) ? -1 : 0;\n });\n}\n\nexport default memo(withGlobal(\n (global): StateProps => {\n return {\n languages: global.settings.byKey.languages,\n language: global.settings.byKey.language,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'loadLanguages', 'setSettingOption',\n ]),\n)(SettingsLanguage));\n","import { ApiPrivacyKey, SettingsScreens } from '../../../../types';\n\nexport function getPrivacyKey(screen: SettingsScreens): ApiPrivacyKey | undefined {\n switch (screen) {\n case SettingsScreens.PrivacyPhoneNumber:\n case SettingsScreens.PrivacyPhoneNumberAllowedContacts:\n case SettingsScreens.PrivacyPhoneNumberDeniedContacts:\n return 'phoneNumber';\n case SettingsScreens.PrivacyLastSeen:\n case SettingsScreens.PrivacyLastSeenAllowedContacts:\n case SettingsScreens.PrivacyLastSeenDeniedContacts:\n return 'lastSeen';\n case SettingsScreens.PrivacyProfilePhoto:\n case SettingsScreens.PrivacyProfilePhotoAllowedContacts:\n case SettingsScreens.PrivacyProfilePhotoDeniedContacts:\n return 'profilePhoto';\n case SettingsScreens.PrivacyForwarding:\n case SettingsScreens.PrivacyForwardingAllowedContacts:\n case SettingsScreens.PrivacyForwardingDeniedContacts:\n return 'forwards';\n case SettingsScreens.PrivacyGroupChats:\n case SettingsScreens.PrivacyGroupChatsAllowedContacts:\n case SettingsScreens.PrivacyGroupChatsDeniedContacts:\n return 'chatInvite';\n }\n\n return undefined;\n}\n","import React, {\n FC, memo, useCallback, useMemo,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../../global/types';\nimport { ApiChat, ApiUser } from '../../../api/types';\nimport { ApiPrivacySettings, SettingsScreens } from '../../../types';\n\nimport useLang from '../../../hooks/useLang';\nimport { pick } from '../../../util/iteratees';\n\nimport ListItem from '../../ui/ListItem';\nimport RadioGroup from '../../ui/RadioGroup';\nimport { getPrivacyKey } from './helper/privacy';\n\ntype OwnProps = {\n screen: SettingsScreens;\n onScreenSelect: (screen: SettingsScreens) => void;\n};\n\ntype StateProps = Partial<ApiPrivacySettings> & {\n chatsById?: Record<number, ApiChat>;\n usersById?: Record<number, ApiUser>;\n};\n\ntype DispatchProps = Pick<GlobalActions, 'setPrivacyVisibility'>;\n\nconst SettingsPrivacyVisibility: FC<OwnProps & StateProps & DispatchProps> = ({\n screen,\n onScreenSelect,\n visibility,\n allowUserIds,\n allowChatIds,\n blockUserIds,\n blockChatIds,\n chatsById,\n setPrivacyVisibility,\n}) => {\n const lang = useLang();\n\n const visibilityOptions = useMemo(() => {\n switch (screen) {\n case SettingsScreens.PrivacyProfilePhoto:\n case SettingsScreens.PrivacyGroupChats:\n return [\n { value: 'everybody', label: lang('P2PEverybody') },\n { value: 'contacts', label: lang('P2PContacts') },\n ];\n\n default:\n return [\n { value: 'everybody', label: lang('P2PEverybody') },\n { value: 'contacts', label: lang('P2PContacts') },\n { value: 'nobody', label: lang('P2PNobody') },\n ];\n }\n }, [lang, screen]);\n\n const exceptionLists = {\n shouldShowDenied: visibility !== 'nobody',\n shouldShowAllowed: visibility !== 'everybody',\n };\n\n const privacyKey = getPrivacyKey(screen);\n\n const headerText = useMemo(() => {\n switch (screen) {\n case SettingsScreens.PrivacyPhoneNumber:\n return lang('PrivacyPhoneTitle');\n case SettingsScreens.PrivacyLastSeen:\n return lang('LastSeenTitle');\n case SettingsScreens.PrivacyProfilePhoto:\n return lang('PrivacyProfilePhotoTitle');\n case SettingsScreens.PrivacyForwarding:\n return lang('PrivacyForwardsTitle');\n case SettingsScreens.PrivacyGroupChats:\n return lang('WhoCanAddMe');\n default:\n return undefined;\n }\n }, [lang, screen]);\n\n const descriptionText = useMemo(() => {\n switch (screen) {\n case SettingsScreens.PrivacyLastSeen:\n return lang('CustomHelp');\n default:\n return undefined;\n }\n }, [lang, screen]);\n\n const allowedContactsScreen = (() => {\n switch (screen) {\n case SettingsScreens.PrivacyPhoneNumber:\n return SettingsScreens.PrivacyPhoneNumberAllowedContacts;\n case SettingsScreens.PrivacyLastSeen:\n return SettingsScreens.PrivacyLastSeenAllowedContacts;\n case SettingsScreens.PrivacyProfilePhoto:\n return SettingsScreens.PrivacyProfilePhotoAllowedContacts;\n case SettingsScreens.PrivacyForwarding:\n return SettingsScreens.PrivacyForwardingAllowedContacts;\n default:\n return SettingsScreens.PrivacyGroupChatsAllowedContacts;\n }\n })();\n\n const deniedContactsScreen = (() => {\n switch (screen) {\n case SettingsScreens.PrivacyPhoneNumber:\n return SettingsScreens.PrivacyPhoneNumberDeniedContacts;\n case SettingsScreens.PrivacyLastSeen:\n return SettingsScreens.PrivacyLastSeenDeniedContacts;\n case SettingsScreens.PrivacyProfilePhoto:\n return SettingsScreens.PrivacyProfilePhotoDeniedContacts;\n case SettingsScreens.PrivacyForwarding:\n return SettingsScreens.PrivacyForwardingDeniedContacts;\n default:\n return SettingsScreens.PrivacyGroupChatsDeniedContacts;\n }\n })();\n\n const allowedCount = useMemo(() => {\n if (!allowUserIds || !allowChatIds || !chatsById) {\n return 0;\n }\n\n return allowChatIds.reduce((result, chatId) => {\n return result + (chatsById[chatId] ? chatsById[chatId].membersCount! : 0);\n }, allowUserIds.length);\n }, [allowChatIds, allowUserIds, chatsById]);\n\n const blockCount = useMemo(() => {\n if (!blockUserIds || !blockChatIds || !chatsById) {\n return 0;\n }\n\n return blockChatIds.reduce((result, chatId) => {\n return result + (chatsById[chatId] ? chatsById[chatId].membersCount! : 0);\n }, blockUserIds.length);\n }, [blockChatIds, blockUserIds, chatsById]);\n\n const handleVisibilityChange = useCallback((value) => {\n setPrivacyVisibility({\n privacyKey,\n visibility: value,\n });\n }, [privacyKey, setPrivacyVisibility]);\n\n return (\n <div className=\"settings-content custom-scroll\">\n <div className=\"settings-item\">\n <h4 className=\"settings-item-header\" dir={lang.isRtl ? 'rtl' : undefined}>{headerText}</h4>\n\n <RadioGroup\n name={`visibility-${privacyKey}`}\n options={visibilityOptions}\n onChange={handleVisibilityChange}\n selected={visibility}\n />\n\n {descriptionText && (\n <p className=\"settings-item-description-larger\" dir={lang.isRtl ? 'rtl' : undefined}>{descriptionText}</p>\n )}\n </div>\n\n <div className=\"settings-item\">\n <h4 className=\"settings-item-header mb-4\" dir={lang.isRtl ? 'rtl' : undefined}>{lang('PrivacyExceptions')}</h4>\n\n {exceptionLists.shouldShowAllowed && (\n <ListItem\n narrow\n icon=\"add-user\"\n onClick={() => { onScreenSelect(allowedContactsScreen); }}\n >\n <div className=\"multiline-menu-item full-size\">\n {allowedCount > 0 && <span className=\"date\" dir=\"auto\">+{allowedCount}</span>}\n <span className=\"title\">{lang('AlwaysShareWith')}</span>\n <span className=\"subtitle\">{lang('EditAdminAddUsers')}</span>\n </div>\n </ListItem>\n )}\n {exceptionLists.shouldShowDenied && (\n <ListItem\n narrow\n icon=\"delete-user\"\n onClick={() => { onScreenSelect(deniedContactsScreen); }}\n >\n <div className=\"multiline-menu-item full-size\">\n {blockCount > 0 && <span className=\"date\" dir=\"auto\">&minus;{blockCount}</span>}\n <span className=\"title\">{lang('NeverShareWith')}</span>\n <span className=\"subtitle\">{lang('EditAdminAddUsers')}</span>\n </div>\n </ListItem>\n )}\n </div>\n </div>\n );\n};\n\nexport default memo(withGlobal<OwnProps>(\n (global, { screen }): StateProps => {\n let privacySettings: ApiPrivacySettings | undefined;\n\n const {\n chats: { byId: chatsById },\n settings: { privacy },\n } = global;\n\n switch (screen) {\n case SettingsScreens.PrivacyPhoneNumber:\n privacySettings = privacy.phoneNumber;\n break;\n\n case SettingsScreens.PrivacyLastSeen:\n privacySettings = privacy.lastSeen;\n break;\n\n case SettingsScreens.PrivacyProfilePhoto:\n privacySettings = privacy.profilePhoto;\n break;\n\n case SettingsScreens.PrivacyForwarding:\n privacySettings = privacy.forwards;\n break;\n\n case SettingsScreens.PrivacyGroupChats:\n privacySettings = privacy.chatInvite;\n break;\n }\n\n if (!privacySettings) {\n return {};\n }\n\n return {\n ...privacySettings,\n chatsById,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, ['setPrivacyVisibility']),\n)(SettingsPrivacyVisibility));\n","import React, {\n FC, memo, useCallback, useEffect, useMemo,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../../global/types';\nimport { ApiSession } from '../../../api/types';\n\nimport { pick } from '../../../util/iteratees';\nimport { formatPastTimeShort } from '../../../util/dateFormat';\nimport useFlag from '../../../hooks/useFlag';\nimport useLang from '../../../hooks/useLang';\n\nimport ListItem from '../../ui/ListItem';\nimport ConfirmDialog from '../../ui/ConfirmDialog';\n\ntype StateProps = {\n activeSessions: ApiSession[];\n};\n\ntype DispatchProps = Pick<GlobalActions, (\n 'loadAuthorizations' | 'terminateAuthorization' | 'terminateAllAuthorizations'\n)>;\n\nconst SettingsPrivacyActiveSessions: FC<StateProps & DispatchProps> = ({\n activeSessions,\n loadAuthorizations,\n terminateAuthorization,\n terminateAllAuthorizations,\n}) => {\n const [isConfirmTerminateAllDialogOpen, openConfirmTerminateAllDialog, closeConfirmTerminateAllDialog] = useFlag();\n useEffect(() => {\n loadAuthorizations();\n }, [loadAuthorizations]);\n\n const handleTerminateSessionClick = useCallback((hash: string) => {\n terminateAuthorization({ hash });\n }, [terminateAuthorization]);\n\n const handleTerminateAllSessions = useCallback(() => {\n closeConfirmTerminateAllDialog();\n terminateAllAuthorizations();\n }, [closeConfirmTerminateAllDialog, terminateAllAuthorizations]);\n\n const currentSession = useMemo(() => {\n return activeSessions.find((session) => session.isCurrent);\n }, [activeSessions]);\n\n const otherSessions = useMemo(() => {\n return activeSessions.filter((session) => !session.isCurrent);\n }, [activeSessions]);\n\n const lang = useLang();\n\n function renderCurrentSession(session: ApiSession) {\n return (\n <div className=\"settings-item\">\n <h4 className=\"settings-item-header mb-4\" dir={lang.isRtl ? 'rtl' : undefined}>\n {lang('AuthSessions.CurrentSession')}\n </h4>\n\n <ListItem narrow inactive>\n <div className=\"multiline-menu-item\" dir=\"auto\">\n <span className=\"title\" dir=\"auto\">{session.appName}</span>\n <span className=\"subtitle black tight\">{getDeviceEnvironment(session)}</span>\n <span className=\"subtitle\">{session.ip} - {getLocation(session)}</span>\n </div>\n </ListItem>\n\n <ListItem\n className=\"destructive mb-0\"\n icon=\"stop\"\n ripple\n narrow\n onClick={openConfirmTerminateAllDialog}\n >\n {lang('TerminateAllSessions')}\n </ListItem>\n </div>\n );\n }\n\n function renderOtherSessions(sessions: ApiSession[]) {\n return (\n <div className=\"settings-item\">\n <h4 className=\"settings-item-header mb-4\" dir={lang.isRtl ? 'rtl' : undefined}>Other Sessions</h4>\n\n {sessions.map(renderSession)}\n </div>\n );\n }\n\n function renderSession(session: ApiSession) {\n return (\n <ListItem\n key={session.hash}\n ripple\n narrow\n contextActions={[{\n title: 'Terminate',\n icon: 'stop',\n handler: () => {\n handleTerminateSessionClick(session.hash);\n },\n }]}\n >\n <div className=\"multiline-menu-item full-size\" dir=\"auto\">\n <span className=\"date\">{formatPastTimeShort(lang, session.dateActive * 1000)}</span>\n <span className=\"title\">{session.appName}</span>\n <span className=\"subtitle black tight\">{getDeviceEnvironment(session)}</span>\n <span className=\"subtitle\">{session.ip} - {getLocation(session)}</span>\n </div>\n </ListItem>\n );\n }\n\n return (\n <div className=\"settings-content custom-scroll\">\n {currentSession && renderCurrentSession(currentSession)}\n\n {otherSessions && renderOtherSessions(otherSessions)}\n\n {otherSessions && (\n <ConfirmDialog\n isOpen={isConfirmTerminateAllDialogOpen}\n onClose={closeConfirmTerminateAllDialog}\n text=\"Are you sure you want to terminate all other sessions?\"\n confirmLabel=\"Terminate All Other Sessions\"\n confirmHandler={handleTerminateAllSessions}\n confirmIsDestructive\n />\n )};\n </div>\n );\n};\n\nfunction getLocation(session: ApiSession) {\n return [session.region, session.country].filter(Boolean).join(', ');\n}\n\nfunction getDeviceEnvironment(session: ApiSession) {\n return `${session.deviceModel}${session.deviceModel ? ', ' : ''} ${session.platform} ${session.systemVersion}`;\n}\n\nexport default memo(withGlobal(\n (global): StateProps => {\n return {\n activeSessions: global.activeSessions,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'loadAuthorizations', 'terminateAuthorization', 'terminateAllAuthorizations',\n ]),\n)(SettingsPrivacyActiveSessions));\n","import React, {\n FC, memo, useCallback,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../../global/types';\nimport { ApiChat, ApiUser } from '../../../api/types';\n\nimport { CHAT_HEIGHT_PX } from '../../../config';\nimport { formatPhoneNumberWithCode } from '../../../util/phoneNumber';\nimport { pick } from '../../../util/iteratees';\nimport {\n getChatTitle, getUserFullName, isChatPrivate,\n} from '../../../modules/helpers';\nimport renderText from '../../common/helpers/renderText';\nimport buildClassName from '../../../util/buildClassName';\nimport useLang from '../../../hooks/useLang';\n\nimport ListItem from '../../ui/ListItem';\nimport FloatingActionButton from '../../ui/FloatingActionButton';\nimport Avatar from '../../common/Avatar';\nimport Loading from '../../ui/Loading';\n\ntype StateProps = {\n chatsByIds: Record<number, ApiChat>;\n usersByIds: Record<number, ApiUser>;\n blockedIds: number[];\n};\n\ntype DispatchProps = Pick<GlobalActions, 'unblockContact'>;\n\nconst SettingsPrivacyBlockedUsers: FC<StateProps & DispatchProps> = ({\n chatsByIds,\n usersByIds,\n blockedIds,\n unblockContact,\n}) => {\n const handleUnblockClick = useCallback((contactId: number) => {\n unblockContact({ contactId });\n }, [unblockContact]);\n\n const lang = useLang();\n\n function renderContact(contactId: number, i: number, viewportOffset: number) {\n const isPrivate = isChatPrivate(contactId);\n const user = isPrivate ? usersByIds[contactId] : undefined;\n const chat = !isPrivate ? chatsByIds[contactId] : undefined;\n\n const className = buildClassName(\n 'Chat chat-item-clickable blocked-list-item',\n isPrivate ? 'private' : 'group',\n );\n\n return (\n <ListItem\n key={contactId}\n className={className}\n ripple\n narrow\n contextActions={[{\n title: 'Unblock',\n icon: 'unlock',\n handler: () => {\n handleUnblockClick(contactId);\n },\n }]}\n style={`top: ${(viewportOffset + i) * CHAT_HEIGHT_PX}px;`}\n >\n <Avatar size=\"medium\" user={user} chat={chat} />\n <div className=\"contact-info\" dir=\"auto\">\n <h3 dir=\"auto\">{renderText((isPrivate ? getUserFullName(user) : getChatTitle(lang, chat!)) || '')}</h3>\n {user && user.phoneNumber && (\n <div className=\"contact-phone\" dir=\"auto\">{formatPhoneNumberWithCode(user.phoneNumber)}</div>\n )}\n {user && !user.phoneNumber && user.username && (\n <div className=\"contact-username\" dir=\"auto\">@{user.username}</div>\n )}\n </div>\n </ListItem>\n );\n }\n\n return (\n <div className=\"settings-fab-wrapper\">\n <div className=\"settings-content infinite-scroll\">\n <div className=\"settings-item\">\n <p className=\"settings-item-description-larger mt-0 mb-2\" dir={lang.isRtl ? 'rtl' : undefined}>\n {lang('BlockedUsersInfo')}\n </p>\n </div>\n\n <div className=\"chat-list custom-scroll\">\n {blockedIds && blockedIds.length ? (\n <div className=\"scroll-container\">\n {blockedIds!.map((contactId, i) => renderContact(contactId, i, 0))}\n </div>\n ) : blockedIds && !blockedIds.length ? (\n <div className=\"no-results\" dir=\"auto\">\n List is empty\n </div>\n ) : (\n <Loading key=\"loading\" />\n )}\n </div>\n </div>\n\n <FloatingActionButton\n isShown\n onClick={() => {\n }}\n className=\"not-implemented\"\n ariaLabel=\"Add a blocked user\"\n >\n <i className=\"icon-add\" />\n </FloatingActionButton>\n </div>\n );\n};\n\n\nexport default memo(withGlobal(\n (global): StateProps => {\n const {\n chats: {\n byId: chatsByIds,\n },\n users: {\n byId: usersByIds,\n },\n blocked: {\n ids,\n },\n } = global;\n\n return {\n chatsByIds,\n usersByIds,\n blockedIds: ids,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, ['unblockContact']),\n)(SettingsPrivacyBlockedUsers));\n","import React, { FC, memo } from '../../../../lib/teact/teact';\nimport { withGlobal } from '../../../../lib/teact/teactn';\n\nimport { ApiSticker } from '../../../../api/types';\nimport { SettingsScreens } from '../../../../types';\n\nimport { selectAnimatedEmoji } from '../../../../modules/selectors';\nimport useLang from '../../../../hooks/useLang';\n\nimport ListItem from '../../../ui/ListItem';\nimport AnimatedEmoji from '../../../common/AnimatedEmoji';\nimport renderText from '../../../common/helpers/renderText';\n\ntype OwnProps = {\n onScreenSelect: (screen: SettingsScreens) => void;\n};\n\ntype StateProps = {\n animatedEmoji: ApiSticker;\n};\n\nconst SettingsTwoFaEnabled: FC<OwnProps & StateProps> = ({ animatedEmoji, onScreenSelect }) => {\n const lang = useLang();\n\n return (\n <div className=\"settings-content two-fa custom-scroll\">\n <div className=\"settings-content-header\">\n <AnimatedEmoji sticker={animatedEmoji} />\n\n <p className=\"settings-item-description mb-3\" dir=\"auto\">\n {renderText(lang('EnabledPasswordText'), ['br'])}\n </p>\n </div>\n\n <div className=\"settings-item pt-0 no-border\">\n <ListItem\n icon=\"edit\"\n onClick={() => onScreenSelect(SettingsScreens.TwoFaChangePasswordCurrent)}\n >\n {lang('ChangePassword')}\n </ListItem>\n <ListItem\n icon=\"password-off\"\n onClick={() => onScreenSelect(SettingsScreens.TwoFaTurnOff)}\n >\n {lang('TurnPasswordOff')}\n </ListItem>\n <ListItem\n icon=\"email\"\n onClick={() => onScreenSelect(SettingsScreens.TwoFaRecoveryEmailCurrentPassword)}\n >\n {lang('SetRecoveryEmail')}\n </ListItem>\n </div>\n </div>\n );\n};\n\nexport default memo(withGlobal<OwnProps>((global) => {\n return {\n animatedEmoji: selectAnimatedEmoji(global, '🔐'),\n };\n})(SettingsTwoFaEnabled));\n","import React, {\n FC, memo, useCallback, useState,\n} from '../../../../lib/teact/teact';\n\nimport useLang from '../../../../hooks/useLang';\n\nimport PasswordMonkey from '../../../common/PasswordMonkey';\nimport PasswordForm from '../../../common/PasswordForm';\n\ntype OwnProps = {\n error?: string;\n isLoading?: boolean;\n expectedPassword?: string;\n placeholder?: string;\n hint?: string;\n submitLabel?: string;\n clearError?: NoneToVoidFunction;\n onSubmit: (password: string) => void;\n};\n\nconst EQUAL_PASSWORD_ERROR = 'Passwords Should Be Equal';\n\nconst SettingsTwoFaPassword: FC<OwnProps> = ({\n error,\n isLoading,\n expectedPassword,\n placeholder = 'Current Password',\n hint,\n submitLabel,\n clearError,\n onSubmit,\n}) => {\n const [validationError, setValidationError] = useState<string>('');\n const [shouldShowPassword, setShouldShowPassword] = useState(false);\n\n const handleSubmit = useCallback((newPassword) => {\n if (expectedPassword && newPassword !== expectedPassword) {\n setValidationError(EQUAL_PASSWORD_ERROR);\n } else {\n onSubmit(newPassword);\n }\n }, [onSubmit, expectedPassword]);\n\n const handleClearError = useCallback(() => {\n if (clearError) {\n clearError();\n }\n setValidationError('');\n }, [clearError]);\n\n const lang = useLang();\n\n return (\n <div className=\"settings-content two-fa custom-scroll\">\n <div className=\"settings-content-header\">\n <PasswordMonkey isBig isPasswordVisible={shouldShowPassword} />\n </div>\n\n <div className=\"settings-item pt-0 no-border\">\n <PasswordForm\n error={validationError || error}\n hint={hint}\n placeholder={placeholder}\n submitLabel={submitLabel || lang('Next')}\n clearError={handleClearError}\n isLoading={isLoading}\n isPasswordVisible={shouldShowPassword}\n onChangePasswordVisibility={setShouldShowPassword}\n onSubmit={handleSubmit}\n />\n </div>\n </div>\n );\n};\n\nexport default memo(SettingsTwoFaPassword);\n","import React, { FC, memo } from '../../../../lib/teact/teact';\nimport { withGlobal } from '../../../../lib/teact/teactn';\n\nimport { ApiSticker } from '../../../../api/types';\n\nimport { selectAnimatedEmoji } from '../../../../modules/selectors';\nimport useLang from '../../../../hooks/useLang';\n\nimport Button from '../../../ui/Button';\nimport AnimatedEmoji from '../../../common/AnimatedEmoji';\n\ntype OwnProps = {\n onStart: NoneToVoidFunction;\n};\n\ntype StateProps = {\n animatedEmoji: ApiSticker;\n};\n\nconst SettingsTwoFaStart: FC<OwnProps & StateProps> = ({ animatedEmoji, onStart }) => {\n const lang = useLang();\n\n return (\n <div className=\"settings-content two-fa custom-scroll\">\n <div className=\"settings-content-header\">\n <AnimatedEmoji sticker={animatedEmoji} />\n\n <p className=\"settings-item-description mb-3\" dir=\"auto\">\n {lang('SetAdditionalPasswordInfo')}\n </p>\n </div>\n\n <div className=\"settings-item pt-0 no-border\">\n <Button onClick={onStart}>{lang('EditAdminTransferSetPassword')}</Button>\n </div>\n </div>\n );\n};\n\nexport default memo(withGlobal<OwnProps>((global) => {\n return {\n animatedEmoji: selectAnimatedEmoji(global, '🔐'),\n };\n})(SettingsTwoFaStart));\n","import React, {\n FC, memo, useEffect, useRef, useState,\n} from '../../../../lib/teact/teact';\nimport { withGlobal } from '../../../../lib/teact/teactn';\n\nimport { ApiSticker } from '../../../../api/types';\n\nimport { IS_MOBILE_SCREEN, IS_TOUCH_ENV } from '../../../../util/environment';\nimport { selectAnimatedEmoji } from '../../../../modules/selectors';\nimport useFlag from '../../../../hooks/useFlag';\nimport useLang from '../../../../hooks/useLang';\n\nimport Button from '../../../ui/Button';\nimport Modal from '../../../ui/Modal';\nimport AnimatedEmoji from '../../../common/AnimatedEmoji';\nimport InputText from '../../../ui/InputText';\nimport renderText from '../../../common/helpers/renderText';\n\ntype OwnProps = {\n icon: 'hint' | 'email';\n type?: 'text' | 'email';\n isLoading?: boolean;\n error?: string;\n placeholder: string;\n shouldConfirm?: boolean;\n clearError?: NoneToVoidFunction;\n onSubmit: (value?: string) => void;\n};\n\ntype StateProps = {\n animatedEmoji: ApiSticker;\n};\n\nconst FOCUS_DELAY_TIMEOUT_MS = IS_MOBILE_SCREEN ? 550 : 400;\n\nconst SettingsTwoFaSkippableForm: FC<OwnProps & StateProps> = ({\n animatedEmoji,\n type = 'text',\n isLoading,\n error,\n placeholder,\n shouldConfirm,\n clearError,\n onSubmit,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const inputRef = useRef<HTMLInputElement>(null);\n\n const [value, setValue] = useState<string>('');\n const [isConfirmShown, markIsConfirmShown, unmarkIsConfirmShown] = useFlag(false);\n\n useEffect(() => {\n if (!IS_TOUCH_ENV) {\n setTimeout(() => {\n inputRef.current!.focus();\n }, FOCUS_DELAY_TIMEOUT_MS);\n }\n }, []);\n\n const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {\n if (error && clearError) {\n clearError();\n }\n\n setValue(e.target.value);\n };\n\n const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {\n e.preventDefault();\n\n if (!inputRef.current) {\n return;\n }\n\n onSubmit(value);\n };\n\n const handleSkip = () => {\n onSubmit();\n };\n\n const handleSkipConfirm = () => {\n unmarkIsConfirmShown();\n onSubmit();\n };\n\n const lang = useLang();\n\n return (\n <div className=\"settings-content two-fa custom-scroll\">\n <div className=\"settings-content-header\">\n <AnimatedEmoji sticker={animatedEmoji} />\n </div>\n\n <div className=\"settings-item pt-0 no-border\">\n <form action=\"\" onSubmit={handleSubmit}>\n <InputText\n ref={inputRef}\n value={value}\n inputMode={type}\n label={placeholder}\n error={error}\n onChange={handleInputChange}\n />\n\n {value ? (\n <Button type=\"submit\" isLoading={isLoading} ripple>{lang('Continue')}</Button>\n ) : (\n <Button\n isText\n isLoading={isLoading}\n ripple\n onClick={shouldConfirm ? markIsConfirmShown : handleSkip}\n >\n {lang('YourEmailSkip')}\n </Button>\n )}\n </form>\n {shouldConfirm && (\n <Modal\n className=\"narrow\"\n isOpen={isConfirmShown}\n title={lang('YourEmailSkipWarning')}\n onClose={unmarkIsConfirmShown}\n >\n {renderText(lang('YourEmailSkipWarningText'), ['br', 'simple_markdown'])}\n <div className=\"dialog-buttons\">\n <Button\n color=\"danger\"\n ripple\n isText\n className=\"confirm-dialog-button\"\n onClick={handleSkipConfirm}\n >\n {lang('YourEmailSkip')}\n </Button>\n <Button\n color=\"primary\"\n ripple\n isText\n className=\"confirm-dialog-button\"\n onClick={unmarkIsConfirmShown}\n >\n {lang('Cancel')}\n </Button>\n </div>\n </Modal>\n )}\n </div>\n </div>\n );\n};\n\nexport default memo(withGlobal<OwnProps>((global, { icon }) => {\n return {\n animatedEmoji: selectAnimatedEmoji(global, icon === 'email' ? '💌' : '💡'),\n };\n})(SettingsTwoFaSkippableForm));\n","import React, { FC, memo } from '../../../../lib/teact/teact';\nimport { withGlobal } from '../../../../lib/teact/teactn';\n\nimport { ApiSticker } from '../../../../api/types';\nimport { SettingsScreens } from '../../../../types';\n\nimport { selectAnimatedEmoji } from '../../../../modules/selectors';\nimport useLang from '../../../../hooks/useLang';\n\nimport Button from '../../../ui/Button';\nimport AnimatedEmoji from '../../../common/AnimatedEmoji';\n\ntype OwnProps = {\n onScreenSelect: (screen: SettingsScreens) => void;\n};\n\ntype StateProps = {\n animatedEmoji: ApiSticker;\n};\n\nconst SettingsTwoFaCongratulations: FC<OwnProps & StateProps> = ({ animatedEmoji, onScreenSelect }) => {\n const lang = useLang();\n\n const handleClick = () => {\n onScreenSelect(SettingsScreens.Privacy);\n };\n\n return (\n <div className=\"settings-content two-fa custom-scroll\">\n <div className=\"settings-content-header\">\n <AnimatedEmoji sticker={animatedEmoji} />\n\n <p className=\"settings-item-description mb-3\" dir=\"auto\">\n {lang('TwoStepVerificationPasswordSetInfo')}\n </p>\n </div>\n\n <div className=\"settings-item pt-0 no-border\">\n <Button onClick={handleClick}>{lang('TwoStepVerificationPasswordReturnSettings')}</Button>\n </div>\n </div>\n );\n};\n\nexport default memo(withGlobal<OwnProps>((global) => {\n return {\n animatedEmoji: selectAnimatedEmoji(global, '🥳'),\n };\n})(SettingsTwoFaCongratulations));\n","import React, {\n FC, memo, useEffect, useRef, useState,\n} from '../../../../lib/teact/teact';\nimport { withGlobal } from '../../../../lib/teact/teactn';\n\nimport { ApiSticker } from '../../../../api/types';\n\nimport { IS_MOBILE_SCREEN, IS_TOUCH_ENV } from '../../../../util/environment';\nimport { selectAnimatedEmoji } from '../../../../modules/selectors';\nimport useLang from '../../../../hooks/useLang';\n\nimport AnimatedEmoji from '../../../common/AnimatedEmoji';\nimport InputText from '../../../ui/InputText';\nimport Loading from '../../../ui/Loading';\n\ntype OwnProps = {\n isLoading?: boolean;\n error?: string;\n clearError: NoneToVoidFunction;\n onSubmit: (hint: string) => void;\n};\n\ntype StateProps = {\n animatedEmoji: ApiSticker;\n codeLength: number;\n};\n\nconst FOCUS_DELAY_TIMEOUT_MS = IS_MOBILE_SCREEN ? 550 : 400;\n\nconst SettingsTwoFaEmailCode: FC<OwnProps & StateProps> = ({\n animatedEmoji,\n codeLength,\n isLoading,\n error,\n clearError,\n onSubmit,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const inputRef = useRef<HTMLInputElement>(null);\n\n const [value, setValue] = useState<string>('');\n\n useEffect(() => {\n if (!IS_TOUCH_ENV) {\n setTimeout(() => {\n inputRef.current!.focus();\n }, FOCUS_DELAY_TIMEOUT_MS);\n }\n }, []);\n\n const lang = useLang();\n\n const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {\n if (error && clearError) {\n clearError();\n }\n\n const newValue = e.target.value.slice(0, codeLength);\n\n if (newValue.length === codeLength) {\n onSubmit(newValue);\n }\n\n setValue(newValue);\n e.target.value = newValue;\n };\n\n return (\n <div className=\"settings-content two-fa custom-scroll\">\n <div className=\"settings-content-header\">\n <AnimatedEmoji sticker={animatedEmoji} />\n </div>\n\n <div className=\"settings-item pt-0 no-border\">\n <InputText\n value={value}\n ref={inputRef}\n inputMode=\"decimal\"\n label={lang('YourEmailCode')}\n error={error}\n onChange={handleInputChange}\n />\n {isLoading && <Loading />}\n </div>\n </div>\n );\n};\n\nexport default memo(withGlobal<OwnProps>((global) => {\n return {\n animatedEmoji: selectAnimatedEmoji(global, '💌'),\n codeLength: global.twoFaSettings.waitingEmailCodeLength,\n };\n})(SettingsTwoFaEmailCode));\n","import React, {\n FC, memo, useCallback, useEffect,\n} from '../../../../lib/teact/teact';\nimport { withGlobal } from '../../../../lib/teact/teactn';\n\nimport { GlobalActions, GlobalState } from '../../../../global/types';\nimport { SettingsScreens } from '../../../../types';\n\nimport { pick } from '../../../../util/iteratees';\nimport { TwoFaDispatch, TwoFaState } from '../../../../hooks/reducers/useTwoFaReducer';\nimport useLang from '../../../../hooks/useLang';\n\nimport SettingsTwoFaEnabled from './SettingsTwoFaEnabled';\nimport SettingsTwoFaPassword from './SettingsTwoFaPassword';\nimport SettingsTwoFaStart from './SettingsTwoFaStart';\nimport SettingsTwoFaSkippableForm from './SettingsTwoFaSkippableForm';\nimport SettingsTwoFaCongratulations from './SettingsTwoFaCongratulations';\nimport SettingsTwoFaEmailCode from './SettingsTwoFaEmailCode';\n\nexport type OwnProps = {\n state: TwoFaState;\n currentScreen: SettingsScreens;\n dispatch: TwoFaDispatch;\n onScreenSelect: (screen: SettingsScreens) => void;\n};\n\ntype StateProps = GlobalState['twoFaSettings'];\n\ntype DispatchProps = Pick<GlobalActions, (\n 'updatePassword' | 'updateRecoveryEmail' | 'clearPassword' | 'provideTwoFaEmailCode' |\n 'checkPassword' | 'clearTwoFaError'\n)>;\n\nconst SettingsTwoFa: FC<OwnProps & StateProps & DispatchProps> = ({\n currentScreen,\n state,\n hint,\n isLoading,\n error,\n waitingEmailCodeLength,\n dispatch,\n onScreenSelect,\n updatePassword,\n checkPassword,\n clearTwoFaError,\n updateRecoveryEmail,\n provideTwoFaEmailCode,\n clearPassword,\n}) => {\n useEffect(() => {\n if (waitingEmailCodeLength) {\n if (currentScreen === SettingsScreens.TwoFaNewPasswordEmail) {\n onScreenSelect(SettingsScreens.TwoFaNewPasswordEmailCode);\n } else if (currentScreen === SettingsScreens.TwoFaRecoveryEmail) {\n onScreenSelect(SettingsScreens.TwoFaRecoveryEmailCode);\n }\n }\n }, [currentScreen, onScreenSelect, waitingEmailCodeLength]);\n\n const handleStartWizard = useCallback(() => {\n dispatch({ type: 'reset' });\n onScreenSelect(SettingsScreens.TwoFaNewPassword);\n }, [dispatch, onScreenSelect]);\n\n const handleNewPassword = useCallback((value: string) => {\n dispatch({ type: 'setPassword', payload: value });\n onScreenSelect(SettingsScreens.TwoFaNewPasswordConfirm);\n }, [dispatch, onScreenSelect]);\n\n const handleNewPasswordConfirm = useCallback(() => {\n onScreenSelect(SettingsScreens.TwoFaNewPasswordHint);\n }, [onScreenSelect]);\n\n const handleNewPasswordHint = useCallback((value?: string) => {\n dispatch({ type: 'setHint', payload: value });\n onScreenSelect(SettingsScreens.TwoFaNewPasswordEmail);\n }, [dispatch, onScreenSelect]);\n\n const handleNewPasswordEmail = useCallback((value?: string) => {\n dispatch({ type: 'setEmail', payload: value });\n updatePassword({\n ...state,\n email: value,\n onSuccess: () => {\n onScreenSelect(SettingsScreens.TwoFaCongratulations);\n },\n });\n }, [dispatch, onScreenSelect, state, updatePassword]);\n\n const handleChangePasswordCurrent = useCallback((value: string) => {\n dispatch({ type: 'setCurrentPassword', payload: value });\n checkPassword({\n currentPassword: value,\n onSuccess: () => {\n onScreenSelect(SettingsScreens.TwoFaChangePasswordNew);\n },\n });\n }, [checkPassword, dispatch, onScreenSelect]);\n\n const handleChangePasswordNew = useCallback((value: string) => {\n dispatch({ type: 'setPassword', payload: value });\n onScreenSelect(SettingsScreens.TwoFaChangePasswordConfirm);\n }, [dispatch, onScreenSelect]);\n\n const handleChangePasswordConfirm = useCallback(() => {\n onScreenSelect(SettingsScreens.TwoFaChangePasswordHint);\n }, [onScreenSelect]);\n\n const handleChangePasswordHint = useCallback((value?: string) => {\n dispatch({ type: 'setHint', payload: value });\n updatePassword({\n ...state,\n hint: value,\n onSuccess: () => {\n onScreenSelect(SettingsScreens.TwoFaCongratulations);\n },\n });\n }, [dispatch, onScreenSelect, state, updatePassword]);\n\n const handleTurnOff = useCallback((value: string) => {\n clearPassword({\n currentPassword: value,\n onSuccess: () => {\n onScreenSelect(SettingsScreens.Privacy);\n },\n });\n }, [clearPassword, onScreenSelect]);\n\n const handleRecoveryEmailCurrentPassword = useCallback((value: string) => {\n dispatch({ type: 'setCurrentPassword', payload: value });\n checkPassword({\n currentPassword: value,\n onSuccess: () => {\n onScreenSelect(SettingsScreens.TwoFaRecoveryEmail);\n },\n });\n }, [checkPassword, dispatch, onScreenSelect]);\n\n const handleRecoveryEmail = useCallback((value?: string) => {\n dispatch({ type: 'setEmail', payload: value });\n updateRecoveryEmail({\n ...state,\n email: value,\n onSuccess: () => {\n onScreenSelect(SettingsScreens.TwoFaCongratulations);\n },\n });\n }, [dispatch, onScreenSelect, state, updateRecoveryEmail]);\n\n const handleEmailCode = useCallback((code: string) => {\n provideTwoFaEmailCode({ code });\n }, [provideTwoFaEmailCode]);\n\n const lang = useLang();\n\n switch (currentScreen) {\n case SettingsScreens.TwoFaDisabled:\n return (\n <SettingsTwoFaStart\n onStart={handleStartWizard}\n />\n );\n\n case SettingsScreens.TwoFaNewPassword:\n return (\n <SettingsTwoFaPassword\n placeholder={lang('EnterPassword')}\n submitLabel={lang('Continue')}\n onSubmit={handleNewPassword}\n />\n );\n\n case SettingsScreens.TwoFaNewPasswordConfirm:\n return (\n <SettingsTwoFaPassword\n expectedPassword={state.password}\n placeholder={lang('PleaseReEnterPassword')}\n submitLabel={lang('Continue')}\n onSubmit={handleNewPasswordConfirm}\n />\n );\n\n case SettingsScreens.TwoFaNewPasswordHint:\n return (\n <SettingsTwoFaSkippableForm\n icon=\"hint\"\n placeholder={lang('PasswordHintPlaceholder')}\n onSubmit={handleNewPasswordHint}\n />\n );\n\n case SettingsScreens.TwoFaNewPasswordEmail:\n return (\n <SettingsTwoFaSkippableForm\n icon=\"email\"\n type=\"email\"\n isLoading={isLoading}\n error={error}\n clearError={clearTwoFaError}\n placeholder={lang('RecoveryEmailTitle')}\n shouldConfirm\n onSubmit={handleNewPasswordEmail}\n />\n );\n\n case SettingsScreens.TwoFaNewPasswordEmailCode:\n return (\n <SettingsTwoFaEmailCode\n isLoading={isLoading}\n error={error}\n clearError={clearTwoFaError}\n onSubmit={handleEmailCode}\n />\n );\n\n case SettingsScreens.TwoFaCongratulations:\n return (\n <SettingsTwoFaCongratulations\n onScreenSelect={onScreenSelect}\n />\n );\n\n case SettingsScreens.TwoFaEnabled:\n return (\n <SettingsTwoFaEnabled\n onScreenSelect={onScreenSelect}\n />\n );\n\n case SettingsScreens.TwoFaChangePasswordCurrent:\n return (\n <SettingsTwoFaPassword\n isLoading={isLoading}\n error={error}\n clearError={clearTwoFaError}\n hint={hint}\n onSubmit={handleChangePasswordCurrent}\n />\n );\n\n case SettingsScreens.TwoFaChangePasswordNew:\n return (\n <SettingsTwoFaPassword\n placeholder={lang('PleaseEnterNewFirstPassword')}\n onSubmit={handleChangePasswordNew}\n />\n );\n\n case SettingsScreens.TwoFaChangePasswordConfirm:\n return (\n <SettingsTwoFaPassword\n expectedPassword={state.password}\n placeholder={lang('PleaseReEnterPassword')}\n onSubmit={handleChangePasswordConfirm}\n />\n );\n\n case SettingsScreens.TwoFaChangePasswordHint:\n return (\n <SettingsTwoFaSkippableForm\n isLoading={isLoading}\n error={error}\n clearError={clearTwoFaError}\n icon=\"hint\"\n placeholder={lang('PasswordHintPlaceholder')}\n onSubmit={handleChangePasswordHint}\n />\n );\n\n case SettingsScreens.TwoFaTurnOff:\n return (\n <SettingsTwoFaPassword\n isLoading={isLoading}\n error={error}\n clearError={clearTwoFaError}\n hint={hint}\n onSubmit={handleTurnOff}\n />\n );\n\n case SettingsScreens.TwoFaRecoveryEmailCurrentPassword:\n return (\n <SettingsTwoFaPassword\n isLoading={isLoading}\n error={error}\n clearError={clearTwoFaError}\n hint={hint}\n onSubmit={handleRecoveryEmailCurrentPassword}\n />\n );\n\n case SettingsScreens.TwoFaRecoveryEmail:\n return (\n <SettingsTwoFaSkippableForm\n icon=\"email\"\n type=\"email\"\n placeholder={lang('RecoveryEmailTitle')}\n onSubmit={handleRecoveryEmail}\n />\n );\n\n case SettingsScreens.TwoFaRecoveryEmailCode:\n return (\n <SettingsTwoFaEmailCode\n isLoading={isLoading}\n error={error}\n clearError={clearTwoFaError}\n onSubmit={handleEmailCode}\n />\n );\n\n default:\n return undefined;\n }\n};\n\nexport default memo(withGlobal<OwnProps>(\n (global): StateProps => ({ ...global.twoFaSettings }),\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'updatePassword', 'updateRecoveryEmail', 'clearPassword', 'provideTwoFaEmailCode',\n 'checkPassword', 'clearTwoFaError',\n ]),\n)(SettingsTwoFa));\n","import React, {\n FC, useCallback, useRef, useEffect, memo,\n} from '../../lib/teact/teact';\n\nimport { isChatPrivate } from '../../modules/helpers';\n\nimport InfiniteScroll from '../ui/InfiniteScroll';\nimport Checkbox from '../ui/Checkbox';\nimport InputText from '../ui/InputText';\nimport ListItem from '../ui/ListItem';\nimport PrivateChatInfo from './PrivateChatInfo';\nimport GroupChatInfo from './GroupChatInfo';\nimport PickerSelectedItem from './PickerSelectedItem';\nimport useInfiniteScroll from '../../hooks/useInfiniteScroll';\nimport useLang from '../../hooks/useLang';\n\nimport Loading from '../ui/Loading';\n\nimport './Picker.scss';\n\ntype OwnProps = {\n itemIds: number[];\n selectedIds: number[];\n filterValue?: string;\n filterPlaceholder?: string;\n notFoundText?: string;\n searchInputId?: string;\n isLoading?: boolean;\n onSelectedIdsChange: (ids: number[]) => void;\n onFilterChange: (value: string) => void;\n onLoadMore?: () => void;\n};\n\n// Focus slows down animation, also it breaks transition layout in Chrome\nconst FOCUS_DELAY_MS = 500;\n\nconst MAX_FULL_ITEMS = 10;\nconst ALWAYS_FULL_ITEMS_COUNT = 5;\n\nconst Picker: FC<OwnProps> = ({\n itemIds,\n selectedIds,\n filterValue,\n filterPlaceholder,\n notFoundText,\n searchInputId,\n isLoading,\n onSelectedIdsChange,\n onFilterChange,\n onLoadMore,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const inputRef = useRef<HTMLInputElement>(null);\n const shouldMinimize = selectedIds.length > MAX_FULL_ITEMS;\n\n useEffect(() => {\n setTimeout(() => {\n requestAnimationFrame(() => {\n inputRef.current!.focus();\n });\n }, FOCUS_DELAY_MS);\n }, []);\n\n const handleItemClick = useCallback((id: number) => {\n const newSelectedIds = [...selectedIds];\n if (newSelectedIds.includes(id)) {\n newSelectedIds.splice(newSelectedIds.indexOf(id), 1);\n } else {\n newSelectedIds.push(id);\n }\n onSelectedIdsChange(newSelectedIds);\n onFilterChange('');\n }, [selectedIds, onSelectedIdsChange, onFilterChange]);\n\n const handleFilterChange = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {\n const { value } = e.currentTarget;\n onFilterChange(value);\n }, [onFilterChange]);\n\n const [viewportIds, getMore] = useInfiniteScroll(onLoadMore, itemIds, Boolean(filterValue));\n\n const lang = useLang();\n\n return (\n <div className=\"Picker\">\n <div className=\"picker-header custom-scroll\" dir={lang.isRtl ? 'rtl' : undefined}>\n {selectedIds.map((id, i) => (\n <PickerSelectedItem\n chatOrUserId={id}\n isMinimized={shouldMinimize && i < selectedIds.length - ALWAYS_FULL_ITEMS_COUNT}\n canClose\n onClick={handleItemClick}\n clickArg={id}\n />\n ))}\n <InputText\n id={searchInputId}\n ref={inputRef}\n value={filterValue}\n onChange={handleFilterChange}\n placeholder={filterPlaceholder || lang('SelectChat')}\n />\n </div>\n\n {viewportIds && viewportIds.length ? (\n <InfiniteScroll\n className=\"picker-list custom-scroll\"\n items={viewportIds}\n onLoadMore={getMore}\n >\n {viewportIds.map((id) => (\n <ListItem\n key={id}\n className=\"chat-item-clickable picker-list-item\"\n onClick={() => handleItemClick(id)}\n ripple\n >\n <Checkbox label=\"\" checked={selectedIds.includes(id)} />\n {isChatPrivate(id) ? (\n <PrivateChatInfo userId={id} />\n ) : (\n <GroupChatInfo chatId={id} />\n )}\n </ListItem>\n ))}\n </InfiniteScroll>\n ) : !isLoading && viewportIds && !viewportIds.length ? (\n <p className=\"no-results\">{notFoundText || 'Sorry, nothing found.'}</p>\n ) : (\n <Loading />\n )}\n </div>\n );\n};\n\nexport default memo(Picker);\n","import React, {\n FC, memo, useCallback, useMemo, useState,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalActions, GlobalState } from '../../../global/types';\nimport { ApiChat } from '../../../api/types';\nimport { ApiPrivacySettings, SettingsScreens } from '../../../types';\n\nimport useLang from '../../../hooks/useLang';\nimport { pick } from '../../../util/iteratees';\nimport searchWords from '../../../util/searchWords';\nimport { getPrivacyKey } from './helper/privacy';\nimport {\n getChatTitle, isChatGroup, isChatPrivate, prepareChatList,\n} from '../../../modules/helpers';\n\nimport Picker from '../../common/Picker';\nimport FloatingActionButton from '../../ui/FloatingActionButton';\n\nexport type OwnProps = {\n isAllowList?: boolean;\n screen: SettingsScreens;\n onScreenSelect: (screen: SettingsScreens) => void;\n};\n\ntype StateProps = {\n currentUserId?: number;\n chatsById: Record<number, ApiChat>;\n listIds?: number[];\n orderedPinnedIds?: number[];\n archivedListIds?: number[];\n archivedPinnedIds?: number[];\n settings?: ApiPrivacySettings;\n};\n\ntype DispatchProps = Pick<GlobalActions, 'setPrivacySettings'>;\n\nconst SettingsPrivacyVisibilityExceptionList: FC<OwnProps & StateProps & DispatchProps> = ({\n currentUserId,\n isAllowList,\n screen,\n settings,\n chatsById,\n listIds,\n orderedPinnedIds,\n archivedListIds,\n archivedPinnedIds,\n setPrivacySettings,\n onScreenSelect,\n}) => {\n const lang = useLang();\n\n const selectedContactIds = useMemo(() => {\n if (!settings) {\n return [];\n }\n\n if (isAllowList) {\n return [...settings.allowUserIds, ...settings.allowChatIds];\n } else {\n return [...settings.blockUserIds, ...settings.blockChatIds];\n }\n }, [isAllowList, settings]);\n const [searchQuery, setSearchQuery] = useState<string>('');\n const [isSubmitShown, setIsSubmitShown] = useState<boolean>(false);\n const [newSelectedContactIds, setNewSelectedContactIds] = useState<number[]>(selectedContactIds);\n\n const chats = useMemo(() => {\n const activeChatArrays = listIds\n ? prepareChatList(chatsById, listIds, orderedPinnedIds, 'all')\n : undefined;\n const archivedChatArrays = archivedListIds\n ? prepareChatList(chatsById, archivedListIds, archivedPinnedIds, 'archived')\n : undefined;\n\n if (!activeChatArrays && !archivedChatArrays) {\n return undefined;\n }\n\n return [\n ...(activeChatArrays\n ? [\n ...activeChatArrays.pinnedChats,\n ...activeChatArrays.otherChats,\n ]\n : []\n ),\n ...(archivedChatArrays ? archivedChatArrays.otherChats : []),\n ];\n }, [chatsById, listIds, orderedPinnedIds, archivedListIds, archivedPinnedIds]);\n\n const displayedIds = useMemo(() => {\n if (!chats) {\n return undefined;\n }\n\n return chats\n .filter((chat) => (\n ((isChatPrivate(chat.id) && chat.id !== currentUserId) || isChatGroup(chat))\n && (\n !searchQuery\n || searchWords(getChatTitle(lang, chat), searchQuery)\n || selectedContactIds.includes(chat.id)\n )\n ))\n .map(({ id }) => id);\n }, [chats, currentUserId, lang, searchQuery, selectedContactIds]);\n\n const handleSelectedContactIdsChange = useCallback((value: number[]) => {\n setNewSelectedContactIds(value);\n setIsSubmitShown(true);\n }, []);\n\n const handleSubmit = useCallback(() => {\n setPrivacySettings({\n privacyKey: getPrivacyKey(screen),\n isAllowList: Boolean(isAllowList),\n contactsIds: newSelectedContactIds,\n });\n\n onScreenSelect(SettingsScreens.Privacy);\n }, [isAllowList, newSelectedContactIds, onScreenSelect, screen, setPrivacySettings]);\n\n return (\n <div className=\"NewChat-inner step-1\">\n <Picker\n itemIds={displayedIds || []}\n selectedIds={newSelectedContactIds}\n filterValue={searchQuery}\n filterPlaceholder={isAllowList ? lang('AlwaysShareWithPlaceholder') : lang('NeverShareWithPlaceholder')}\n searchInputId=\"new-group-picker-search\"\n onSelectedIdsChange={handleSelectedContactIdsChange}\n onFilterChange={setSearchQuery}\n />\n\n <FloatingActionButton\n isShown={isSubmitShown}\n onClick={handleSubmit}\n ariaLabel={isAllowList ? lang('AlwaysShareWithTitle') : lang('NeverShareWithTitle')}\n >\n <i className=\"icon-arrow-right\" />\n </FloatingActionButton>\n </div>\n );\n};\n\nfunction getCurrentPrivacySettings(global: GlobalState, screen: SettingsScreens) {\n const { privacy } = global.settings;\n switch (screen) {\n case SettingsScreens.PrivacyPhoneNumberAllowedContacts:\n case SettingsScreens.PrivacyPhoneNumberDeniedContacts:\n return privacy.phoneNumber;\n case SettingsScreens.PrivacyLastSeenAllowedContacts:\n case SettingsScreens.PrivacyLastSeenDeniedContacts:\n return privacy.lastSeen;\n case SettingsScreens.PrivacyProfilePhotoAllowedContacts:\n case SettingsScreens.PrivacyProfilePhotoDeniedContacts:\n return privacy.profilePhoto;\n case SettingsScreens.PrivacyForwardingAllowedContacts:\n case SettingsScreens.PrivacyForwardingDeniedContacts:\n return privacy.forwards;\n case SettingsScreens.PrivacyGroupChatsDeniedContacts:\n case SettingsScreens.PrivacyGroupChatsAllowedContacts:\n return privacy.chatInvite;\n }\n\n return undefined;\n}\n\nexport default memo(withGlobal<OwnProps>(\n (global, { screen }): StateProps => {\n const {\n chats: {\n byId: chatsById,\n listIds,\n orderedPinnedIds,\n },\n currentUserId,\n } = global;\n\n return {\n currentUserId,\n chatsById,\n listIds: listIds.active,\n orderedPinnedIds: orderedPinnedIds.active,\n archivedPinnedIds: orderedPinnedIds.archived,\n archivedListIds: listIds.archived,\n settings: getCurrentPrivacySettings(global, screen),\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, ['setPrivacySettings']),\n)(SettingsPrivacyVisibilityExceptionList));\n","import React, { FC, memo, useCallback } from '../../../lib/teact/teact';\n\nimport { SettingsScreens } from '../../../types';\n\nimport { IS_MOBILE_SCREEN } from '../../../util/environment';\nimport useFoldersReducer from '../../../hooks/reducers/useFoldersReducer';\nimport useTwoFaReducer from '../../../hooks/reducers/useTwoFaReducer';\n\nimport Transition from '../../ui/Transition';\nimport SettingsHeader from './SettingsHeader';\nimport SettingsMain from './SettingsMain';\nimport SettingsEditProfile from './SettingsEditProfile';\nimport SettingsFolders from './folders/SettingsFolders';\nimport SettingsGeneral from './SettingsGeneral';\nimport SettingsGeneralBackground from './SettingsGeneralBackground';\nimport SettingsGeneralBackgroundColor from './SettingsGeneralBackgroundColor';\nimport SettingsNotifications from './SettingsNotifications';\nimport SettingsPrivacy from './SettingsPrivacy';\nimport SettingsLanguage from './SettingsLanguage';\nimport SettingsPrivacyVisibility from './SettingsPrivacyVisibility';\nimport SettingsPrivacyActiveSessions from './SettingsPrivacyActiveSessions';\nimport SettingsPrivacyBlockedUsers from './SettingsPrivacyBlockedUsers';\nimport SettingsTwoFa from './twoFa/SettingsTwoFa';\nimport SettingsPrivacyVisibilityExceptionList from './SettingsPrivacyVisibilityExceptionList';\n\nimport './Settings.scss';\n\nconst TRANSITION_RENDER_COUNT = Object.keys(SettingsScreens).length / 2;\nconst TRANSITION_DURATION = 200;\n\nexport type OwnProps = {\n currentScreen: SettingsScreens;\n onScreenSelect: (screen: SettingsScreens) => void;\n onReset: () => void;\n};\n\nconst Settings: FC<OwnProps> = ({\n currentScreen,\n onScreenSelect,\n onReset,\n}) => {\n const [foldersState, foldersDispatch] = useFoldersReducer();\n const [twoFaState, twoFaDispatch] = useTwoFaReducer();\n\n const handleReset = useCallback(() => {\n if (\n currentScreen === SettingsScreens.FoldersCreateFolder\n || currentScreen === SettingsScreens.FoldersEditFolder\n ) {\n setTimeout(() => {\n foldersDispatch({ type: 'reset' });\n }, TRANSITION_DURATION);\n }\n\n if (\n currentScreen === SettingsScreens.FoldersIncludedChats\n || currentScreen === SettingsScreens.FoldersExcludedChats\n ) {\n if (foldersState.mode === 'create') {\n onScreenSelect(SettingsScreens.FoldersCreateFolder);\n } else {\n onScreenSelect(SettingsScreens.FoldersEditFolder);\n }\n return;\n }\n\n onReset();\n }, [\n foldersState.mode, foldersDispatch,\n currentScreen, onReset, onScreenSelect,\n ]);\n\n const handleSaveFilter = useCallback(() => {\n foldersDispatch({ type: 'saveFilters' });\n handleReset();\n }, [foldersDispatch, handleReset]);\n\n function renderCurrentSectionContent() {\n switch (currentScreen) {\n case SettingsScreens.Main:\n return (\n <SettingsMain onScreenSelect={onScreenSelect} />\n );\n case SettingsScreens.EditProfile:\n return (\n <SettingsEditProfile />\n );\n case SettingsScreens.General:\n return (\n <SettingsGeneral onScreenSelect={onScreenSelect} />\n );\n case SettingsScreens.Notifications:\n return (\n <SettingsNotifications />\n );\n case SettingsScreens.Privacy:\n return (\n <SettingsPrivacy onScreenSelect={onScreenSelect} />\n );\n case SettingsScreens.Language:\n return (\n <SettingsLanguage />\n );\n case SettingsScreens.GeneralChatBackground:\n return (\n <SettingsGeneralBackground onScreenSelect={onScreenSelect} />\n );\n case SettingsScreens.GeneralChatBackgroundColor:\n return (\n <SettingsGeneralBackgroundColor onScreenSelect={onScreenSelect} />\n );\n case SettingsScreens.PrivacyActiveSessions:\n return (\n <SettingsPrivacyActiveSessions />\n );\n case SettingsScreens.PrivacyBlockedUsers:\n return (\n <SettingsPrivacyBlockedUsers />\n );\n case SettingsScreens.PrivacyPhoneNumber:\n case SettingsScreens.PrivacyLastSeen:\n case SettingsScreens.PrivacyProfilePhoto:\n case SettingsScreens.PrivacyForwarding:\n case SettingsScreens.PrivacyGroupChats:\n return (\n <SettingsPrivacyVisibility screen={currentScreen} onScreenSelect={onScreenSelect} />\n );\n\n case SettingsScreens.PrivacyPhoneNumberAllowedContacts:\n case SettingsScreens.PrivacyLastSeenAllowedContacts:\n case SettingsScreens.PrivacyProfilePhotoAllowedContacts:\n case SettingsScreens.PrivacyForwardingAllowedContacts:\n case SettingsScreens.PrivacyGroupChatsAllowedContacts:\n return (\n <SettingsPrivacyVisibilityExceptionList\n isAllowList\n screen={currentScreen}\n onScreenSelect={onScreenSelect}\n />\n );\n\n case SettingsScreens.PrivacyPhoneNumberDeniedContacts:\n case SettingsScreens.PrivacyLastSeenDeniedContacts:\n case SettingsScreens.PrivacyProfilePhotoDeniedContacts:\n case SettingsScreens.PrivacyForwardingDeniedContacts:\n case SettingsScreens.PrivacyGroupChatsDeniedContacts:\n return (\n <SettingsPrivacyVisibilityExceptionList\n screen={currentScreen}\n onScreenSelect={onScreenSelect}\n />\n );\n\n case SettingsScreens.Folders:\n case SettingsScreens.FoldersCreateFolder:\n case SettingsScreens.FoldersEditFolder:\n case SettingsScreens.FoldersIncludedChats:\n case SettingsScreens.FoldersExcludedChats:\n return (\n <SettingsFolders\n currentScreen={currentScreen}\n state={foldersState}\n dispatch={foldersDispatch}\n onScreenSelect={onScreenSelect}\n onReset={handleReset}\n />\n );\n\n case SettingsScreens.TwoFaDisabled:\n case SettingsScreens.TwoFaNewPassword:\n case SettingsScreens.TwoFaNewPasswordConfirm:\n case SettingsScreens.TwoFaNewPasswordHint:\n case SettingsScreens.TwoFaNewPasswordEmail:\n case SettingsScreens.TwoFaNewPasswordEmailCode:\n case SettingsScreens.TwoFaCongratulations:\n case SettingsScreens.TwoFaEnabled:\n case SettingsScreens.TwoFaChangePasswordCurrent:\n case SettingsScreens.TwoFaChangePasswordNew:\n case SettingsScreens.TwoFaChangePasswordConfirm:\n case SettingsScreens.TwoFaChangePasswordHint:\n case SettingsScreens.TwoFaTurnOff:\n case SettingsScreens.TwoFaRecoveryEmailCurrentPassword:\n case SettingsScreens.TwoFaRecoveryEmail:\n case SettingsScreens.TwoFaRecoveryEmailCode:\n return (\n <SettingsTwoFa\n currentScreen={currentScreen}\n state={twoFaState}\n dispatch={twoFaDispatch}\n onScreenSelect={onScreenSelect}\n />\n );\n\n default:\n return undefined;\n }\n }\n\n function renderCurrentSection() {\n return (\n <>\n <SettingsHeader\n currentScreen={currentScreen}\n onReset={handleReset}\n onSaveFilter={handleSaveFilter}\n editedFolderId={foldersState.folderId}\n />\n {renderCurrentSectionContent()}\n </>\n );\n }\n\n return (\n <Transition\n id=\"Settings\"\n name={IS_MOBILE_SCREEN ? 'slide-layers' : 'push-slide'}\n activeKey={currentScreen}\n renderCount={TRANSITION_RENDER_COUNT}\n >\n {renderCurrentSection}\n </Transition>\n );\n};\n\nexport default memo(Settings);\n","import React, {\n FC, useEffect, useCallback, useMemo, memo,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../../global/types';\nimport { ApiUser } from '../../../api/types';\n\nimport { IS_MOBILE_SCREEN } from '../../../util/environment';\nimport { throttle } from '../../../util/schedulers';\nimport searchWords from '../../../util/searchWords';\nimport { pick } from '../../../util/iteratees';\nimport { getUserFullName, sortUserIds } from '../../../modules/helpers';\nimport useInfiniteScroll from '../../../hooks/useInfiniteScroll';\n\nimport PrivateChatInfo from '../../common/PrivateChatInfo';\nimport InfiniteScroll from '../../ui/InfiniteScroll';\nimport ListItem from '../../ui/ListItem';\nimport Loading from '../../ui/Loading';\n\nexport type OwnProps = {\n filter: string;\n};\n\ntype StateProps = {\n usersById: Record<number, ApiUser>;\n contactIds?: number[];\n};\n\ntype DispatchProps = Pick<GlobalActions, 'loadContactList' | 'openChat'>;\n\nconst runThrottled = throttle((cb) => cb(), 60000, true);\n\nconst ContactList: FC<OwnProps & StateProps & DispatchProps> = ({\n filter, usersById, contactIds, loadContactList, openChat,\n}) => {\n // Due to the parent Transition, this component never gets unmounted,\n // that's why we use throttled API call on every update.\n useEffect(() => {\n runThrottled(() => {\n loadContactList();\n });\n });\n\n const handleClick = useCallback(\n (id: number) => {\n openChat({ id });\n },\n [openChat],\n );\n\n const listIds = useMemo(() => {\n if (!contactIds) {\n return undefined;\n }\n\n const resultIds = filter ? contactIds.filter((id) => {\n const user = usersById[id];\n if (!user) {\n return false;\n }\n const fullName = getUserFullName(user);\n return fullName && searchWords(fullName, filter);\n }) : contactIds;\n\n return sortUserIds(resultIds, usersById);\n }, [filter, usersById, contactIds]);\n\n const [viewportIds, getMore] = useInfiniteScroll(undefined, listIds, Boolean(filter));\n\n return (\n <InfiniteScroll items={viewportIds} onLoadMore={getMore} className=\"chat-list custom-scroll\">\n {viewportIds && viewportIds.length ? (\n viewportIds.map((id) => (\n <ListItem\n key={id}\n className=\"chat-item-clickable\"\n onClick={() => handleClick(id)}\n ripple={!IS_MOBILE_SCREEN}\n >\n <PrivateChatInfo userId={id} forceShowSelf avatarSize=\"large\" />\n </ListItem>\n ))\n ) : viewportIds && !viewportIds.length ? (\n <p className=\"no-results\" key=\"no-results\" dir=\"auto\">\n {filter.length ? 'No contacts matched your search.' : 'Contact list is empty.'}\n </p>\n ) : (\n <Loading key=\"loading\" />\n )}\n </InfiniteScroll>\n );\n};\n\nexport default memo(withGlobal<OwnProps>(\n (global): StateProps => {\n const { userIds: contactIds } = global.contactList || {};\n const { byId: usersById } = global.users;\n\n return {\n usersById,\n contactIds,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, ['loadContactList', 'openChat']),\n)(ContactList));\n","import React, {\n FC, useCallback, useEffect, useMemo, memo,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../../global/types';\nimport { ApiChat, ApiUser } from '../../../api/types';\n\nimport { pick, unique } from '../../../util/iteratees';\nimport { throttle } from '../../../util/schedulers';\nimport searchWords from '../../../util/searchWords';\nimport { getUserFullName, sortChatIds } from '../../../modules/helpers';\nimport useLang from '../../../hooks/useLang';\n\nimport Picker from '../../common/Picker';\nimport FloatingActionButton from '../../ui/FloatingActionButton';\nimport Button from '../../ui/Button';\n\nexport type OwnProps = {\n isChannel?: boolean;\n selectedMemberIds: number[];\n onSelectedMemberIdsChange: (ids: number[]) => void;\n onNextStep: () => void;\n onReset: () => void;\n};\n\ntype StateProps = {\n currentUserId?: number;\n usersById: Record<number, ApiUser>;\n chatsById: Record<number, ApiChat>;\n localContactIds?: number[];\n searchQuery?: string;\n isSearching?: boolean;\n localUserIds?: number[];\n globalUserIds?: number[];\n};\n\ntype DispatchProps = Pick<GlobalActions, 'loadContactList' | 'setGlobalSearchQuery'>;\n\nconst runThrottled = throttle((cb) => cb(), 60000, true);\n\nconst NewChatStep1: FC<OwnProps & StateProps & DispatchProps> = ({\n isChannel,\n selectedMemberIds,\n onSelectedMemberIdsChange,\n onNextStep,\n onReset,\n currentUserId,\n usersById,\n chatsById,\n localContactIds,\n searchQuery,\n isSearching,\n localUserIds,\n globalUserIds,\n loadContactList,\n setGlobalSearchQuery,\n}) => {\n // Due to the parent Transition, this component never gets unmounted,\n // that's why we use throttled API call on every update.\n useEffect(() => {\n runThrottled(() => {\n loadContactList();\n });\n });\n\n const handleFilterChange = useCallback((query: string) => {\n setGlobalSearchQuery({ query });\n }, [setGlobalSearchQuery]);\n\n const displayedIds = useMemo(() => {\n const contactIds = localContactIds\n ? sortChatIds(localContactIds.filter((id) => id !== currentUserId), chatsById)\n : [];\n\n if (!searchQuery) {\n return contactIds;\n }\n\n const foundContactIds = contactIds.filter((id) => {\n const user = usersById[id];\n if (!user) {\n return false;\n }\n const fullName = getUserFullName(user);\n return fullName && searchWords(fullName, searchQuery);\n });\n\n return sortChatIds(\n unique([\n ...foundContactIds,\n ...(localUserIds || []),\n ...(globalUserIds || []),\n ]),\n chatsById,\n false,\n selectedMemberIds,\n );\n }, [\n localContactIds, searchQuery, localUserIds, globalUserIds, usersById, chatsById, selectedMemberIds, currentUserId,\n ]);\n\n const handleNextStep = useCallback(() => {\n if (selectedMemberIds.length || isChannel) {\n setGlobalSearchQuery({ query: '' });\n onNextStep();\n }\n }, [selectedMemberIds.length, isChannel, setGlobalSearchQuery, onNextStep]);\n\n const lang = useLang();\n\n return (\n <div className=\"NewChat step-1\">\n <div className=\"left-header\">\n <Button\n round\n size=\"smaller\"\n color=\"translucent\"\n onClick={onReset}\n ariaLabel=\"Return to Chat List\"\n >\n <i className=\"icon-arrow-left\" />\n </Button>\n <h3>{lang('GroupAddMembers')}</h3>\n </div>\n <div className=\"NewChat-inner step-1\">\n <Picker\n itemIds={displayedIds}\n selectedIds={selectedMemberIds}\n filterValue={searchQuery}\n filterPlaceholder={lang('SendMessageTo')}\n searchInputId=\"new-group-picker-search\"\n isLoading={isSearching}\n onSelectedIdsChange={onSelectedMemberIdsChange}\n onFilterChange={handleFilterChange}\n />\n\n <FloatingActionButton\n isShown={Boolean(selectedMemberIds.length || isChannel)}\n onClick={handleNextStep}\n ariaLabel={isChannel ? 'Continue To Channel Info' : 'Continue To Group Info'}\n >\n <i className=\"icon-arrow-right\" />\n </FloatingActionButton>\n </div>\n </div>\n );\n};\n\nexport default memo(withGlobal<OwnProps>(\n (global): StateProps => {\n const { userIds: localContactIds } = global.contactList || {};\n const { byId: usersById } = global.users;\n const { byId: chatsById } = global.chats;\n const { currentUserId } = global;\n\n const {\n query: searchQuery,\n fetchingStatus,\n globalResults,\n localResults,\n } = global.globalSearch;\n const { userIds: globalUserIds } = globalResults || {};\n const { userIds: localUserIds } = localResults || {};\n\n return {\n currentUserId,\n usersById,\n chatsById,\n localContactIds,\n searchQuery,\n isSearching: fetchingStatus && fetchingStatus.chats,\n globalUserIds,\n localUserIds,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, ['loadContactList', 'setGlobalSearchQuery']),\n)(NewChatStep1));\n","import React, {\n FC, useState, useCallback, useEffect, memo,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../../global/types';\nimport { ChatCreationProgress } from '../../../types';\n\nimport { pick } from '../../../util/iteratees';\nimport useLang from '../../../hooks/useLang';\n\nimport InputText from '../../ui/InputText';\nimport FloatingActionButton from '../../ui/FloatingActionButton';\nimport Spinner from '../../ui/Spinner';\nimport AvatarEditable from '../../ui/AvatarEditable';\nimport Button from '../../ui/Button';\nimport ListItem from '../../ui/ListItem';\nimport PrivateChatInfo from '../../common/PrivateChatInfo';\n\nexport type OwnProps = {\n isChannel?: boolean;\n memberIds: number[];\n onReset: (forceReturnToChatList?: boolean) => void;\n};\n\ntype StateProps = {\n creationProgress?: ChatCreationProgress;\n creationError?: string;\n};\n\ntype DispatchProps = Pick<GlobalActions, 'createGroupChat' | 'createChannel'>;\n\n// TODO @implement\nconst MAX_USERS_FOR_LEGACY_CHAT = 199; // Accounting for current user\n\nconst NewChatStep2: FC<OwnProps & StateProps & DispatchProps> = ({\n isChannel,\n memberIds,\n onReset,\n creationProgress,\n creationError,\n createGroupChat,\n createChannel,\n}) => {\n const lang = useLang();\n\n const [title, setTitle] = useState('');\n const [about, setAbout] = useState('');\n const [photo, setPhoto] = useState<File | undefined>();\n const [error, setError] = useState<string | undefined>();\n\n const chatTitleEmptyError = 'Chat title can\\'t be empty';\n const channelTitleEmptyError = 'Channel title can\\'t be empty';\n const chatTooManyUsersError = 'Sorry, creating supergroups is not yet supported';\n\n const isLoading = creationProgress === ChatCreationProgress.InProgress;\n\n const handleTitleChange = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {\n const { value } = e.currentTarget;\n const newValue = value.replace(/^\\s+/, '');\n\n setTitle(newValue);\n\n if (newValue !== value) {\n e.currentTarget.value = newValue;\n }\n }, []);\n\n const handleDescriptionChange = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {\n setAbout(e.currentTarget.value);\n }, []);\n\n const handleCreateGroup = useCallback(() => {\n if (!title.length) {\n setError(chatTitleEmptyError);\n return;\n }\n\n if (memberIds.length > MAX_USERS_FOR_LEGACY_CHAT) {\n setError(chatTooManyUsersError);\n return;\n }\n\n createGroupChat({\n title,\n photo,\n memberIds,\n });\n }, [title, memberIds, createGroupChat, photo, chatTitleEmptyError, chatTooManyUsersError]);\n\n const handleCreateChannel = useCallback(() => {\n if (!title.length) {\n setError(channelTitleEmptyError);\n return;\n }\n\n createChannel({\n title,\n about,\n photo,\n memberIds,\n });\n }, [title, createChannel, about, photo, memberIds, channelTitleEmptyError]);\n\n useEffect(() => {\n if (creationProgress === ChatCreationProgress.Complete) {\n onReset(true);\n }\n }, [creationProgress, onReset]);\n\n const renderedError = creationError || (\n error !== chatTitleEmptyError && error !== channelTitleEmptyError\n ? error\n : undefined\n );\n\n return (\n <div className=\"NewChat\">\n <div className=\"left-header\">\n <Button\n round\n size=\"smaller\"\n color=\"translucent\"\n onClick={() => onReset()}\n ariaLabel=\"Return to member selection\"\n >\n <i className=\"icon-arrow-left\" />\n </Button>\n <h3>{lang(isChannel ? 'NewChannel' : 'NewGroup')}</h3>\n </div>\n <div className=\"NewChat-inner step-2\">\n <AvatarEditable\n onChange={setPhoto}\n title={lang('AddPhoto')}\n />\n <InputText\n value={title}\n onChange={handleTitleChange}\n label={lang(isChannel ? 'EnterChannelName' : 'GroupName')}\n error={error === chatTitleEmptyError || error === channelTitleEmptyError ? error : undefined}\n />\n {isChannel && (\n <>\n <InputText\n value={about}\n onChange={handleDescriptionChange}\n label={lang('DescriptionOptionalPlaceholder')}\n />\n <p className=\"note\">{lang('DescriptionInfo')}</p>\n </>\n )}\n\n {renderedError && (\n <p className=\"error\">{renderedError}</p>\n )}\n\n {memberIds.length > 0 && (\n <>\n <h3 className=\"chat-members-heading\">{lang('GroupInfo.ParticipantCount', memberIds.length, 'i')}</h3>\n\n <div className=\"chat-members-list custom-scroll\">\n {memberIds.map((id) => (\n <ListItem inactive className=\"chat-item-clickable\">\n <PrivateChatInfo userId={id} />\n </ListItem>\n ))}\n </div>\n </>\n )}\n </div>\n\n <FloatingActionButton\n isShown={title.length !== 0}\n onClick={isChannel ? handleCreateChannel : handleCreateGroup}\n disabled={isLoading}\n ariaLabel={isChannel ? lang('ChannelIntro.CreateChannel') : 'Create Group'}\n >\n {isLoading ? (\n <Spinner color=\"white\" />\n ) : (\n <i className=\"icon-arrow-right\" />\n )}\n </FloatingActionButton>\n </div>\n );\n};\n\nexport default memo(withGlobal<OwnProps>(\n (global): StateProps => {\n const {\n progress: creationProgress,\n error: creationError,\n } = global.chatCreation || {};\n\n return {\n creationProgress,\n creationError,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'createGroupChat', 'createChannel',\n ]),\n)(NewChatStep2));\n","import React, {\n FC, memo, useCallback, useState,\n} from '../../../lib/teact/teact';\n\nimport { LeftColumnContent } from '../../../types';\n\nimport { IS_MOBILE_SCREEN } from '../../../util/environment';\n\nimport Transition from '../../ui/Transition';\nimport NewChatStep1 from './NewChatStep1';\nimport NewChatStep2 from './NewChatStep2';\n\nimport './NewChat.scss';\n\nexport type OwnProps = {\n isChannel?: boolean;\n content: LeftColumnContent;\n onContentChange: (content: LeftColumnContent) => void;\n onReset: () => void;\n};\n\nconst RENDER_COUNT = Object.keys(LeftColumnContent).length / 2;\n\nconst NewChat: FC<OwnProps> = ({\n isChannel = false,\n content,\n onContentChange,\n onReset,\n}) => {\n const [newChatMemberIds, setNewChatMemberIds] = useState<number[]>([]);\n\n const handleNextStep = useCallback(() => {\n onContentChange(isChannel ? LeftColumnContent.NewChannelStep2 : LeftColumnContent.NewGroupStep2);\n }, [isChannel, onContentChange]);\n\n return (\n <Transition\n id=\"NewChat\"\n name={IS_MOBILE_SCREEN ? 'slide-layers' : 'push-slide'}\n renderCount={RENDER_COUNT}\n activeKey={content}\n >\n {() => {\n switch (content) {\n case LeftColumnContent.NewChannelStep1:\n case LeftColumnContent.NewGroupStep1:\n return (\n <NewChatStep1\n isChannel={isChannel}\n selectedMemberIds={newChatMemberIds}\n onSelectedMemberIdsChange={setNewChatMemberIds}\n onNextStep={handleNextStep}\n onReset={onReset}\n />\n );\n case LeftColumnContent.NewChannelStep2:\n case LeftColumnContent.NewGroupStep2:\n return (\n <NewChatStep2\n isChannel={isChannel}\n memberIds={newChatMemberIds}\n onReset={onReset}\n />\n );\n default:\n return undefined;\n }\n }}\n </Transition>\n );\n};\n\nexport default memo(NewChat);\n","import React, { FC, memo } from '../../lib/teact/teact';\n\nimport useLang from '../../hooks/useLang';\n\nimport Button from '../ui/Button';\nimport ChatList from './main/ChatList';\n\nimport './ArchivedChats.scss';\n\nexport type OwnProps = {\n isActive: boolean;\n onReset: () => void;\n};\n\nconst ArchivedChats: FC<OwnProps> = ({ isActive, onReset }) => {\n const lang = useLang();\n\n return (\n <div className=\"ArchivedChats\">\n <div className=\"left-header\">\n <Button\n round\n size=\"smaller\"\n color=\"translucent\"\n onClick={onReset}\n ariaLabel=\"Return to chat list\"\n >\n <i className=\"icon-arrow-left\" />\n </Button>\n <h3>{lang('ArchivedChats')}</h3>\n </div>\n <ChatList folderType=\"archived\" noChatsText=\"Archive is empty.\" isActive={isActive} />\n </div>\n );\n};\n\nexport default memo(ArchivedChats);\n","const IGNORED_KEYS: Record<string, boolean> = {\n Down: true,\n ArrowDown: true,\n Up: true,\n ArrowUp: true,\n Left: true,\n ArrowLeft: true,\n Right: true,\n ArrowRight: true,\n ' ': true,\n PageUp: true,\n PageDown: true,\n End: true,\n Home: true,\n Tab: true,\n};\n\nconst preventDefault = (e: Event) => {\n e.preventDefault();\n};\n\nfunction preventDefaultForScrollKeys(e: KeyboardEvent) {\n if (IGNORED_KEYS[e.key]) {\n preventDefault(e);\n }\n}\n\nexport function disableScrolling() {\n // Disable scrolling in Chrome\n document.addEventListener('wheel', preventDefault, { passive: false });\n window.ontouchmove = preventDefault; // mobile\n document.onkeydown = preventDefaultForScrollKeys;\n}\n\nexport function enableScrolling() {\n document.removeEventListener('wheel', preventDefault); // Enable scrolling in Chrome\n // eslint-disable-next-line no-null/no-null\n window.ontouchmove = null;\n // eslint-disable-next-line no-null/no-null\n document.onkeydown = null;\n}\n","import { ApiMediaFormat, ApiMessage } from '../../../../api/types';\n\nimport * as mediaLoader from '../../../../util/mediaLoader';\nimport { getMessageMediaHash, getMessagePhoto, getMessageText } from '../../../../modules/helpers';\nimport { CLIPBOARD_ITEM_SUPPORTED, copyImageToClipboard, copyTextToClipboard } from '../../../../util/clipboard';\n\ntype ICopyOptions = {\n label: string;\n handler: () => void;\n}[];\n\nexport function getMessageCopyOptions(\n message: ApiMessage, afterEffect?: () => void, onCopyLink?: () => void,\n): ICopyOptions {\n const options: ICopyOptions = [];\n const text = getMessageText(message);\n const photo = getMessagePhoto(message);\n const mediaHash = getMessageMediaHash(message, 'inline')!;\n const canImageBeCopied = photo && mediaHash && CLIPBOARD_ITEM_SUPPORTED;\n const selection = window.getSelection();\n\n if (canImageBeCopied) {\n options.push({\n label: 'lng_context_copy_image',\n handler: () => {\n mediaLoader.fetch(mediaHash, ApiMediaFormat.BlobUrl).then(copyImageToClipboard);\n\n if (afterEffect) {\n afterEffect();\n }\n },\n });\n }\n\n if (text) {\n // Detect if the user has selection in the current message\n const hasSelection = Boolean((\n selection\n && selection.anchorNode\n && selection.anchorNode.parentNode\n && (selection.anchorNode.parentNode as HTMLElement).closest('.Message .content-inner')\n && selection.toString().replace(/(?:\\r\\n|\\r|\\n)/g, '') !== ''\n ));\n\n options.push({\n label: getCopyLabel(hasSelection, canImageBeCopied),\n handler: () => {\n const clipboardText = hasSelection && selection ? selection.toString() : text;\n copyTextToClipboard(clipboardText);\n\n if (afterEffect) {\n afterEffect();\n }\n },\n });\n }\n\n if (onCopyLink) {\n options.push({\n label: 'lng_context_copy_message_link',\n handler: () => {\n onCopyLink();\n\n if (afterEffect) {\n afterEffect();\n }\n },\n });\n }\n\n return options;\n}\n\nfunction getCopyLabel(hasSelection: boolean, canImageBeCopied: boolean): string {\n if (hasSelection) {\n return 'lng_context_copy_selected';\n }\n\n if (canImageBeCopied) {\n return 'lng_context_copy_text';\n }\n\n return 'Copy';\n}\n","import React, { FC, useCallback, useEffect } from '../../../lib/teact/teact';\n\nimport { ApiMessage } from '../../../api/types';\nimport { IAnchorPosition } from '../../../types';\n\nimport { getMessageCopyOptions } from './helpers/copyOptions';\nimport useContextMenuPosition from '../../../hooks/useContextMenuPosition';\nimport { dispatchHeavyAnimationEvent } from '../../../hooks/useHeavyAnimationCheck';\nimport useLang from '../../../hooks/useLang';\n\nimport Menu from '../../ui/Menu';\nimport MenuItem from '../../ui/MenuItem';\n\nimport './MessageContextMenu.scss';\n\ntype OwnProps = {\n isOpen: boolean;\n anchor: IAnchorPosition;\n message: ApiMessage;\n canSendNow?: boolean;\n canReschedule?: boolean;\n canReply?: boolean;\n canPin?: boolean;\n canUnpin?: boolean;\n canDelete?: boolean;\n canEdit?: boolean;\n canForward?: boolean;\n canFaveSticker?: boolean;\n canUnfaveSticker?: boolean;\n canCopy?: boolean;\n canCopyLink?: boolean;\n canSelect?: boolean;\n onReply: () => void;\n onEdit: () => void;\n onPin: () => void;\n onUnpin: () => void;\n onForward: () => void;\n onDelete: () => void;\n onFaveSticker: () => void;\n onUnfaveSticker: () => void;\n onSelect: () => void;\n onSend: () => void;\n onReschedule: () => void;\n onClose: () => void;\n onCloseAnimationEnd?: () => void;\n onCopyLink?: () => void;\n};\n\nconst ANIMATION_DURATION = 200;\nconst SCROLLBAR_WIDTH = 10;\n\nconst MessageContextMenu: FC<OwnProps> = ({\n isOpen,\n message,\n anchor,\n canSendNow,\n canReschedule,\n canReply,\n canEdit,\n canPin,\n canUnpin,\n canDelete,\n canForward,\n canFaveSticker,\n canUnfaveSticker,\n canCopy,\n canCopyLink,\n canSelect,\n onReply,\n onEdit,\n onPin,\n onUnpin,\n onForward,\n onDelete,\n onFaveSticker,\n onUnfaveSticker,\n onSelect,\n onSend,\n onReschedule,\n onClose,\n onCloseAnimationEnd,\n onCopyLink,\n}) => {\n useEffect(() => {\n dispatchHeavyAnimationEvent(ANIMATION_DURATION);\n }, [isOpen]);\n\n const copyOptions = getMessageCopyOptions(message, onClose, canCopyLink ? onCopyLink : undefined);\n\n const getTriggerElement = useCallback(() => {\n return document.querySelector(`.active > .MessageList div[data-message-id=\"${message.id}\"]`);\n }, [message.id]);\n\n const getRootElement = useCallback(\n () => document.querySelector('.active > .MessageList'),\n [],\n );\n\n const getMenuElement = useCallback(\n () => document.querySelector('.MessageContextMenu .bubble'),\n [],\n );\n\n const { positionX, positionY, style } = useContextMenuPosition(\n anchor,\n getTriggerElement,\n getRootElement,\n getMenuElement,\n SCROLLBAR_WIDTH,\n (document.querySelector('.MiddleHeader') as HTMLElement).offsetHeight,\n );\n\n const lang = useLang();\n\n return (\n <Menu\n isOpen={isOpen}\n positionX={positionX}\n positionY={positionY}\n style={style}\n className=\"MessageContextMenu fluid\"\n onClose={onClose}\n onCloseAnimationEnd={onCloseAnimationEnd}\n >\n {canSendNow && <MenuItem icon=\"send-outline\" onClick={onSend}>{lang('MessageScheduleSend')}</MenuItem>}\n {canReschedule && (\n <MenuItem icon=\"schedule\" onClick={onReschedule}>{lang('MessageScheduleEditTime')}</MenuItem>\n )}\n {canReply && <MenuItem icon=\"reply\" onClick={onReply}>{lang('Reply')}</MenuItem>}\n {canEdit && <MenuItem icon=\"edit\" onClick={onEdit}>{lang('Edit')}</MenuItem>}\n {canFaveSticker && (\n <MenuItem icon=\"favorite\" onClick={onFaveSticker}>{lang('AddToFavorites')}</MenuItem>\n )}\n {canUnfaveSticker && (\n <MenuItem icon=\"favorite\" onClick={onUnfaveSticker}>{lang('Stickers.RemoveFromFavorites')}</MenuItem>\n )}\n {canCopy && copyOptions.map((options) => (\n <MenuItem key={options.label} icon=\"copy\" onClick={options.handler}>{lang(options.label)}</MenuItem>\n ))}\n {canPin && <MenuItem icon=\"pin\" onClick={onPin}>{lang('DialogPin')}</MenuItem>}\n {canUnpin && <MenuItem icon=\"unpin\" onClick={onUnpin}>{lang('DialogUnpin')}</MenuItem>}\n {canForward && <MenuItem icon=\"forward\" onClick={onForward}>{lang('Forward')}</MenuItem>}\n {canSelect && <MenuItem icon=\"select\" onClick={onSelect}>{lang('Common.Select')}</MenuItem>}\n {canDelete && <MenuItem destructive icon=\"delete\" onClick={onDelete}>{lang('Delete')}</MenuItem>}\n </Menu>\n );\n};\n\nexport default MessageContextMenu;\n","import React, {\n FC, memo, useCallback, useEffect, useState,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalActions, MessageListType } from '../../../global/types';\nimport { ApiMessage } from '../../../api/types';\nimport { IAlbum, IAnchorPosition } from '../../../types';\nimport { selectAllowedMessageActions, selectCurrentMessageList } from '../../../modules/selectors';\nimport { disableScrolling, enableScrolling } from '../../../util/scrollLock';\nimport { pick } from '../../../util/iteratees';\nimport useShowTransition from '../../../hooks/useShowTransition';\nimport useFlag from '../../../hooks/useFlag';\n\nimport DeleteMessageModal from '../../common/DeleteMessageModal';\nimport PinMessageModal from '../../common/PinMessageModal';\nimport MessageContextMenu from './MessageContextMenu';\nimport CalendarModal from '../../common/CalendarModal';\nimport { getDayStartAt } from '../../../util/dateFormat';\n\nexport type OwnProps = {\n isOpen: boolean;\n message: ApiMessage;\n album?: IAlbum;\n anchor: IAnchorPosition;\n messageListType: MessageListType;\n onClose: () => void;\n onCloseAnimationEnd: () => void;\n};\n\ntype StateProps = {\n noOptions?: boolean;\n canSendNow?: boolean;\n canReschedule?: boolean;\n canReply?: boolean;\n canPin?: boolean;\n canUnpin?: boolean;\n canDelete?: boolean;\n canEdit?: boolean;\n canForward?: boolean;\n canFaveSticker?: boolean;\n canUnfaveSticker?: boolean;\n canCopy?: boolean;\n canCopyLink?: boolean;\n canSelect?: boolean;\n};\n\ntype DispatchProps = Pick<GlobalActions, (\n 'setReplyingToId' | 'setEditingId' | 'pinMessage' | 'openForwardMenu' |\n 'faveSticker' | 'unfaveSticker' | 'toggleMessageSelection' | 'sendScheduledMessages' | 'rescheduleMessage' |\n 'loadMessageLink'\n)>;\n\nconst ContextMenuContainer: FC<OwnProps & StateProps & DispatchProps> = ({\n isOpen,\n messageListType,\n message,\n album,\n anchor,\n onClose,\n onCloseAnimationEnd,\n noOptions,\n canSendNow,\n canReschedule,\n canReply,\n canPin,\n canUnpin,\n canDelete,\n canEdit,\n canForward,\n canFaveSticker,\n canUnfaveSticker,\n canCopy,\n canCopyLink,\n canSelect,\n setReplyingToId,\n setEditingId,\n pinMessage,\n openForwardMenu,\n faveSticker,\n unfaveSticker,\n toggleMessageSelection,\n sendScheduledMessages,\n rescheduleMessage,\n loadMessageLink,\n}) => {\n const { transitionClassNames } = useShowTransition(isOpen, onCloseAnimationEnd, undefined, false);\n const [isMenuOpen, setIsMenuOpen] = useState(true);\n const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false);\n const [isPinModalOpen, setIsPinModalOpen] = useState(false);\n const [isCalendarOpen, openCalendar, closeCalendar] = useFlag();\n\n const handleDelete = useCallback(() => {\n setIsMenuOpen(false);\n setIsDeleteModalOpen(true);\n }, []);\n\n const closeMenu = useCallback(() => {\n setIsMenuOpen(false);\n onClose();\n }, [onClose]);\n\n const closeDeleteModal = useCallback(() => {\n setIsDeleteModalOpen(false);\n onClose();\n }, [onClose]);\n\n const closePinModal = useCallback(() => {\n setIsPinModalOpen(false);\n onClose();\n }, [onClose]);\n\n const handleCloseCalendar = useCallback(() => {\n closeCalendar();\n onClose();\n }, [closeCalendar, onClose]);\n\n const handleReply = useCallback(() => {\n setReplyingToId({ messageId: message.id });\n closeMenu();\n }, [setReplyingToId, message.id, closeMenu]);\n\n const handleEdit = useCallback(() => {\n setEditingId({ messageId: message.id });\n closeMenu();\n }, [setEditingId, message.id, closeMenu]);\n\n const handlePin = useCallback(() => {\n setIsMenuOpen(false);\n setIsPinModalOpen(true);\n }, []);\n\n const handleUnpin = useCallback(() => {\n pinMessage({ messageId: message.id, isUnpin: true });\n closeMenu();\n }, [pinMessage, message.id, closeMenu]);\n\n const handleForward = useCallback(() => {\n closeMenu();\n if (album && album.messages) {\n const messageIds = album.messages.map(({ id }) => id);\n openForwardMenu({ fromChatId: message.chatId, messageIds });\n } else {\n openForwardMenu({ fromChatId: message.chatId, messageIds: [message.id] });\n }\n }, [openForwardMenu, message, closeMenu, album]);\n\n const handleFaveSticker = useCallback(() => {\n closeMenu();\n faveSticker({ sticker: message.content.sticker });\n }, [closeMenu, message.content.sticker, faveSticker]);\n\n const handleUnfaveSticker = useCallback(() => {\n closeMenu();\n unfaveSticker({ sticker: message.content.sticker });\n }, [closeMenu, message.content.sticker, unfaveSticker]);\n\n const handleSelectMessage = useCallback(() => {\n const params = album && album.messages\n ? {\n messageId: message.id,\n childMessageIds: album.messages.map(({ id }) => id),\n withShift: false,\n }\n : { messageId: message.id, withShift: false };\n\n toggleMessageSelection(params);\n closeMenu();\n }, [closeMenu, message.id, toggleMessageSelection, album]);\n\n const handleScheduledMessageSend = useCallback(() => {\n sendScheduledMessages({ chatId: message.chatId, id: message.id });\n closeMenu();\n }, [closeMenu, message.chatId, message.id, sendScheduledMessages]);\n\n const handleOpenCalendar = useCallback(() => {\n setIsMenuOpen(false);\n openCalendar();\n }, [openCalendar]);\n\n const handleRescheduleMessage = useCallback((date: Date) => {\n rescheduleMessage({\n chatId: message.chatId,\n messageId: message.id,\n scheduledAt: Math.round(date.getTime() / 1000),\n });\n }, [message.chatId, message.id, rescheduleMessage]);\n\n const handleCopyLink = useCallback(() => {\n loadMessageLink({\n messageId: message.id,\n chatId: message.chatId,\n });\n closeMenu();\n }, [closeMenu, loadMessageLink, message.chatId, message.id]);\n\n useEffect(() => {\n disableScrolling();\n\n return enableScrolling;\n }, []);\n\n if (noOptions) {\n closeMenu();\n\n return undefined;\n }\n\n const scheduledMaxDate = new Date();\n scheduledMaxDate.setFullYear(scheduledMaxDate.getFullYear() + 1);\n\n return (\n <div className={['ContextMenuContainer', transitionClassNames].join(' ')}>\n <MessageContextMenu\n message={message}\n isOpen={isMenuOpen}\n anchor={anchor}\n canSendNow={canSendNow}\n canReschedule={canReschedule}\n canReply={canReply}\n canDelete={canDelete}\n canPin={canPin}\n canUnpin={canUnpin}\n canEdit={canEdit}\n canForward={canForward}\n canFaveSticker={canFaveSticker}\n canUnfaveSticker={canUnfaveSticker}\n canCopy={canCopy}\n canCopyLink={canCopyLink}\n canSelect={canSelect}\n onReply={handleReply}\n onEdit={handleEdit}\n onPin={handlePin}\n onUnpin={handleUnpin}\n onForward={handleForward}\n onDelete={handleDelete}\n onFaveSticker={handleFaveSticker}\n onUnfaveSticker={handleUnfaveSticker}\n onSelect={handleSelectMessage}\n onSend={handleScheduledMessageSend}\n onReschedule={handleOpenCalendar}\n onClose={closeMenu}\n onCopyLink={handleCopyLink}\n />\n <DeleteMessageModal\n isOpen={isDeleteModalOpen}\n isSchedule={messageListType === 'scheduled'}\n onClose={closeDeleteModal}\n album={album}\n message={message}\n />\n <PinMessageModal\n isOpen={isPinModalOpen}\n messageId={message.id}\n chatId={message.chatId}\n onClose={closePinModal}\n />\n <CalendarModal\n isOpen={isCalendarOpen}\n withTimePicker\n selectedAt={message.date * 1000}\n maxAt={getDayStartAt(scheduledMaxDate)}\n isFutureMode\n onClose={handleCloseCalendar}\n onSubmit={handleRescheduleMessage}\n />\n </div>\n );\n};\n\nexport default memo(withGlobal<OwnProps>(\n (global, { message, messageListType }): StateProps => {\n const { threadId } = selectCurrentMessageList(global) || {};\n const {\n noOptions,\n canReply,\n canPin,\n canUnpin,\n canDelete,\n canEdit,\n canForward,\n canFaveSticker,\n canUnfaveSticker,\n canCopy,\n canCopyLink,\n canSelect,\n } = (threadId && selectAllowedMessageActions(global, message, threadId)) || {};\n const isPinned = messageListType === 'pinned';\n const isScheduled = messageListType === 'scheduled';\n\n return {\n noOptions,\n canSendNow: isScheduled,\n canReschedule: isScheduled,\n canReply: !isPinned && !isScheduled && canReply,\n canPin: !isScheduled && canPin,\n canUnpin: !isScheduled && canUnpin,\n canDelete,\n canEdit: !isPinned && canEdit,\n canForward: !isScheduled && canForward,\n canFaveSticker: !isScheduled && canFaveSticker,\n canUnfaveSticker: !isScheduled && canUnfaveSticker,\n canCopy,\n canCopyLink: !isScheduled && canCopyLink,\n canSelect,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'setReplyingToId',\n 'setEditingId',\n 'pinMessage',\n 'openForwardMenu',\n 'faveSticker',\n 'unfaveSticker',\n 'toggleMessageSelection',\n 'sendScheduledMessages',\n 'rescheduleMessage',\n 'loadMessageLink',\n ]),\n)(ContextMenuContainer));\n","import React, {\n FC, memo, useCallback, useEffect, useRef,\n} from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { ApiSticker, ApiStickerSet } from '../../api/types';\nimport { GlobalActions } from '../../global/types';\n\nimport { STICKER_SIZE_MODAL } from '../../config';\nimport { pick } from '../../util/iteratees';\nimport { selectStickerSet } from '../../modules/selectors';\nimport { useIntersectionObserver } from '../../hooks/useIntersectionObserver';\nimport useLang from '../../hooks/useLang';\n\nimport Modal from '../ui/Modal';\nimport Button from '../ui/Button';\nimport Loading from '../ui/Loading';\nimport StickerButton from './StickerButton';\n\nimport './StickerSetModal.scss';\n\nexport type OwnProps = {\n isOpen: boolean;\n fromSticker: ApiSticker;\n onClose: () => void;\n};\n\ntype StateProps = {\n stickerSet?: ApiStickerSet;\n};\n\ntype DispatchProps = Pick<GlobalActions, 'loadStickers' | 'toggleStickerSet' | 'sendMessage'>;\n\nconst INTERSECTION_THROTTLE = 200;\n\nconst StickerSetModal: FC<OwnProps & StateProps & DispatchProps> = ({\n isOpen,\n fromSticker,\n stickerSet,\n onClose,\n loadStickers,\n toggleStickerSet,\n sendMessage,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const containerRef = useRef<HTMLDivElement>(null);\n const lang = useLang();\n\n const {\n observe: observeIntersection,\n } = useIntersectionObserver({ rootRef: containerRef, throttleMs: INTERSECTION_THROTTLE, isDisabled: !isOpen });\n\n useEffect(() => {\n if (isOpen) {\n const { stickerSetId, stickerSetAccessHash } = fromSticker;\n loadStickers({ stickerSetId, stickerSetAccessHash });\n }\n }, [isOpen, fromSticker, loadStickers]);\n\n const handleSelect = useCallback((sticker: ApiSticker) => {\n sticker = {\n ...sticker,\n isPreloadedGlobally: true,\n };\n\n sendMessage({ sticker });\n onClose();\n }, [onClose, sendMessage]);\n\n const handleButtonClick = useCallback(() => {\n toggleStickerSet({ stickerSetId: fromSticker.stickerSetId });\n onClose();\n }, [fromSticker.stickerSetId, onClose, toggleStickerSet]);\n\n return (\n <Modal\n className=\"StickerSetModal\"\n isOpen={isOpen}\n onClose={onClose}\n hasCloseButton\n title={stickerSet ? stickerSet.title : lang('AccDescrStickerSet')}\n >\n {stickerSet && stickerSet.stickers ? (\n <>\n <div ref={containerRef} className=\"stickers custom-scroll\">\n {stickerSet.stickers.map((sticker) => (\n <StickerButton\n sticker={sticker}\n size={STICKER_SIZE_MODAL}\n observeIntersection={observeIntersection}\n onClick={handleSelect}\n clickArg={sticker}\n />\n ))}\n </div>\n <div className=\"button-wrapper\">\n <Button\n size=\"smaller\"\n fluid\n color={stickerSet.installedDate ? 'danger' : 'primary'}\n onClick={handleButtonClick}\n >\n {lang(\n stickerSet.installedDate ? 'StickerPack.RemoveStickerCount' : 'StickerPack.AddStickerCount',\n stickerSet.count,\n 'i',\n )}\n </Button>\n </div>\n </>\n ) : (\n <Loading />\n )}\n </Modal>\n );\n};\n\nexport default memo(withGlobal(\n (global, { fromSticker }: OwnProps) => {\n return { stickerSet: selectStickerSet(global, fromSticker.stickerSetId) };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'loadStickers',\n 'toggleStickerSet',\n 'sendMessage',\n ]),\n)(StickerSetModal));\n","import React, {\n FC, memo, useCallback, useEffect, useState,\n} from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../global/types';\nimport { ApiChat } from '../../api/types';\nimport { IAnchorPosition } from '../../types';\n\nimport { IS_MOBILE_SCREEN } from '../../util/environment';\nimport { disableScrolling, enableScrolling } from '../../util/scrollLock';\nimport { selectChat } from '../../modules/selectors';\nimport { pick } from '../../util/iteratees';\nimport { isChatPrivate, getCanDeleteChat } from '../../modules/helpers';\nimport useShowTransition from '../../hooks/useShowTransition';\nimport useLang from '../../hooks/useLang';\n\nimport Portal from '../ui/Portal';\nimport Menu from '../ui/Menu';\nimport MenuItem from '../ui/MenuItem';\nimport DeleteChatModal from '../common/DeleteChatModal';\n\nimport './HeaderMenuContainer.scss';\n\ntype DispatchProps = Pick<GlobalActions, 'updateChatMutedState' | 'enterMessageSelectMode'>;\n\nexport type OwnProps = {\n chatId: number;\n threadId: number;\n isOpen: boolean;\n anchor: IAnchorPosition;\n isChannel?: boolean;\n canSubscribe?: boolean;\n canSearch?: boolean;\n canMute?: boolean;\n canSelect?: boolean;\n canLeave?: boolean;\n onSubscribeChannel: () => void;\n onSearchClick: () => void;\n onClose: () => void;\n onCloseAnimationEnd: () => void;\n};\n\ntype StateProps = {\n chat?: ApiChat;\n isPrivate?: boolean;\n isMuted?: boolean;\n canDeleteChat?: boolean;\n};\n\nconst HeaderMenuContainer: FC<OwnProps & StateProps & DispatchProps> = ({\n chatId,\n isOpen,\n anchor,\n isChannel,\n canSubscribe,\n canSearch,\n canMute,\n canSelect,\n canLeave,\n chat,\n isPrivate,\n isMuted,\n canDeleteChat,\n onSubscribeChannel,\n onSearchClick,\n onClose,\n onCloseAnimationEnd,\n updateChatMutedState,\n enterMessageSelectMode,\n}) => {\n const [isMenuOpen, setIsMenuOpen] = useState(true);\n const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false);\n const { x, y } = anchor;\n\n useShowTransition(isOpen, onCloseAnimationEnd, undefined, false);\n\n const handleDelete = useCallback(() => {\n setIsMenuOpen(false);\n setIsDeleteModalOpen(true);\n }, []);\n\n const closeMenu = useCallback(() => {\n setIsMenuOpen(false);\n onClose();\n }, [onClose]);\n\n const closeDeleteModal = useCallback(() => {\n setIsDeleteModalOpen(false);\n onClose();\n }, [onClose]);\n\n const handleToggleMuteClick = useCallback(() => {\n updateChatMutedState({ chatId, isMuted: !isMuted });\n closeMenu();\n }, [chatId, closeMenu, isMuted, updateChatMutedState]);\n\n const handleSubscribe = useCallback(() => {\n onSubscribeChannel();\n closeMenu();\n }, [closeMenu, onSubscribeChannel]);\n\n const handleSearch = useCallback(() => {\n onSearchClick();\n closeMenu();\n }, [closeMenu, onSearchClick]);\n\n const handleSelectMessages = useCallback(() => {\n enterMessageSelectMode();\n closeMenu();\n }, [closeMenu, enterMessageSelectMode]);\n\n useEffect(() => {\n disableScrolling();\n\n return enableScrolling;\n }, []);\n\n const lang = useLang();\n\n return (\n <Portal>\n <div className=\"HeaderMenuContainer\">\n <Menu\n isOpen={isMenuOpen}\n positionX=\"right\"\n style={`left: ${x}px;top: ${y}px;`}\n onClose={closeMenu}\n >\n {IS_MOBILE_SCREEN && canSubscribe && (\n <MenuItem\n icon={isChannel ? 'channel' : 'group'}\n onClick={handleSubscribe}\n >\n {lang(isChannel ? 'Subscribe' : 'Join Group')}\n </MenuItem>\n )}\n {IS_MOBILE_SCREEN && canSearch && (\n <MenuItem\n icon=\"search\"\n onClick={handleSearch}\n >\n {lang('Search')}\n </MenuItem>\n )}\n {canMute && (\n <MenuItem\n icon={isMuted ? 'unmute' : 'mute'}\n onClick={handleToggleMuteClick}\n >\n {lang(isMuted ? 'ChatsUnmute' : 'ChatsMute')}\n </MenuItem>\n )}\n {canSelect && (\n <MenuItem\n icon=\"select\"\n onClick={handleSelectMessages}\n >\n {lang('ReportSelectMessages')}\n </MenuItem>\n )}\n {canLeave && (\n <MenuItem\n destructive\n icon=\"delete\"\n onClick={handleDelete}\n >\n {lang(isPrivate\n ? 'Delete'\n : (canDeleteChat ? 'GroupInfo.DeleteAndExit' : (isChannel ? 'LeaveChannel' : 'Group.LeaveGroup')))}\n </MenuItem>\n )}\n </Menu>\n {chat && (\n <DeleteChatModal\n isOpen={isDeleteModalOpen}\n onClose={closeDeleteModal}\n chat={chat}\n />\n )}\n </div>\n </Portal>\n );\n};\n\nexport default memo(withGlobal<OwnProps>(\n (global, { chatId }): StateProps => {\n const chat = selectChat(global, chatId);\n if (!chat || chat.isRestricted) {\n return {};\n }\n\n return {\n chat,\n isMuted: chat.isMuted,\n isPrivate: isChatPrivate(chat.id),\n canDeleteChat: getCanDeleteChat(chat),\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'updateChatMutedState',\n 'enterMessageSelectMode',\n ]),\n)(HeaderMenuContainer));\n","import React, {\n FC, memo, useCallback, useEffect, useRef, useState, useLayoutEffect,\n} from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { ApiChat } from '../../api/types';\nimport { GlobalActions } from '../../global/types';\n\nimport { debounce } from '../../util/schedulers';\nimport { selectCurrentTextSearch, selectCurrentChat } from '../../modules/selectors';\nimport { pick } from '../../util/iteratees';\nimport { getDayStartAt } from '../../util/dateFormat';\n\nimport Button from '../ui/Button';\nimport SearchInput from '../ui/SearchInput';\n\nimport './MobileSearch.scss';\n\nexport type OwnProps = {\n isActive: boolean;\n};\n\ntype StateProps = {\n isActive?: boolean;\n chat?: ApiChat;\n query?: string;\n totalCount?: number;\n foundIds?: number[];\n isHistoryCalendarOpen?: boolean;\n};\n\ntype DispatchProps = Pick<GlobalActions, (\n 'setLocalTextSearchQuery' | 'searchTextMessagesLocal' | 'closeLocalTextSearch' | 'openHistoryCalendar' |\n 'focusMessage'\n)>;\n\nconst runDebouncedForSearch = debounce((cb) => cb(), 200, false);\n\nconst MobileSearchFooter: FC<StateProps & DispatchProps> = ({\n isActive,\n chat,\n query,\n totalCount,\n foundIds,\n isHistoryCalendarOpen,\n setLocalTextSearchQuery,\n searchTextMessagesLocal,\n focusMessage,\n closeLocalTextSearch,\n openHistoryCalendar,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const inputRef = useRef<HTMLInputElement>(null);\n const [focusedIndex, setFocusedIndex] = useState(0);\n\n // Fix for iOS keyboard\n useEffect(() => {\n const { visualViewport } = window as any;\n if (!visualViewport) {\n return undefined;\n }\n\n const mainEl = document.getElementById('Main') as HTMLDivElement;\n const handleResize = () => {\n const { activeElement } = document;\n if (activeElement && (activeElement === inputRef.current)) {\n const { pageTop, height } = visualViewport;\n mainEl.style.transform = `translateY(${pageTop}px)`;\n mainEl.style.height = `${height}px`;\n document.documentElement.scrollTop = pageTop;\n } else {\n mainEl.style.transform = '';\n mainEl.style.height = '';\n }\n };\n\n visualViewport.addEventListener('resize', handleResize);\n\n return () => {\n visualViewport.removeEventListener('resize', handleResize);\n };\n }, []);\n\n // Focus message\n useEffect(() => {\n if (chat && foundIds && foundIds.length) {\n focusMessage({ chatId: chat.id, messageId: foundIds[foundIds.length - 1] });\n setFocusedIndex(0);\n } else {\n setFocusedIndex(-1);\n }\n }, [chat, focusMessage, foundIds]);\n\n // Disable native up/down buttons on iOS\n useEffect(() => {\n Array.from(document.querySelectorAll<HTMLInputElement>('input')).forEach((input) => {\n input.disabled = Boolean(isActive && input !== inputRef.current);\n });\n\n Array.from(document.querySelectorAll<HTMLDivElement>('div[contenteditable]')).forEach((div) => {\n div.contentEditable = isActive ? 'false' : 'true';\n });\n }, [isActive]);\n\n // Blur on exit\n useEffect(() => {\n if (!isActive) {\n inputRef.current!.blur();\n }\n }, [isActive]);\n\n useLayoutEffect(() => {\n const searchInput = document.querySelector<HTMLInputElement>('#MobileSearch input')!;\n searchInput.blur();\n }, [isHistoryCalendarOpen]);\n\n const handleMessageSearchQueryChange = useCallback((newQuery: string) => {\n setLocalTextSearchQuery({ query: newQuery });\n\n if (newQuery.length) {\n runDebouncedForSearch(searchTextMessagesLocal);\n }\n }, [searchTextMessagesLocal, setLocalTextSearchQuery]);\n\n const handleUp = useCallback(() => {\n if (chat && foundIds) {\n const newFocusIndex = focusedIndex + 1;\n focusMessage({ chatId: chat.id, messageId: foundIds[foundIds.length - 1 - newFocusIndex] });\n setFocusedIndex(newFocusIndex);\n }\n }, [chat, focusedIndex, focusMessage, foundIds]);\n\n const handleDown = useCallback(() => {\n if (chat && foundIds) {\n const newFocusIndex = focusedIndex - 1;\n focusMessage({ chatId: chat.id, messageId: foundIds[foundIds.length - 1 - newFocusIndex] });\n setFocusedIndex(newFocusIndex);\n }\n }, [chat, focusedIndex, focusMessage, foundIds]);\n\n return (\n <div id=\"MobileSearch\" className={isActive ? 'active' : ''}>\n <div className=\"header\">\n <Button\n size=\"smaller\"\n round\n color=\"translucent\"\n onClick={closeLocalTextSearch}\n >\n <i className=\"icon-arrow-left\" />\n </Button>\n <SearchInput\n ref={inputRef}\n value={query}\n onChange={handleMessageSearchQueryChange}\n />\n </div>\n <div className=\"footer\">\n <div className=\"counter\">\n {query ? (\n foundIds && foundIds.length ? (\n `${focusedIndex + 1} of ${totalCount}`\n ) : foundIds && !foundIds.length ? (\n 'No results'\n ) : (\n ''\n )\n ) : (\n <Button\n round\n size=\"smaller\"\n color=\"translucent\"\n onClick={() => openHistoryCalendar({ selectedAt: getDayStartAt(Date.now()) })}\n ariaLabel=\"Search messages by date\"\n >\n <i className=\"icon-calendar\" />\n </Button>\n )}\n </div>\n <Button\n round\n size=\"smaller\"\n color=\"translucent\"\n onClick={handleUp}\n disabled={!foundIds || !foundIds.length || focusedIndex === foundIds.length - 1}\n >\n <i className=\"icon-up\" />\n </Button>\n <Button\n round\n size=\"smaller\"\n color=\"translucent\"\n onClick={handleDown}\n disabled={!foundIds || !foundIds.length || focusedIndex === 0}\n >\n <i className=\"icon-down\" />\n </Button>\n </div>\n </div>\n );\n};\n\nexport default memo(withGlobal<OwnProps>(\n (global): StateProps => {\n const chat = selectCurrentChat(global);\n if (!chat) {\n return {};\n }\n\n const { query, results } = selectCurrentTextSearch(global) || {};\n const { totalCount, foundIds } = results || {};\n\n return {\n chat,\n query,\n totalCount,\n foundIds,\n isHistoryCalendarOpen: Boolean(global.historyCalendarSelectedAt),\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'setLocalTextSearchQuery',\n 'searchTextMessagesLocal',\n 'focusMessage',\n 'closeLocalTextSearch',\n 'openHistoryCalendar',\n ]),\n)(MobileSearchFooter));\n","export default function findInViewport(\n container: HTMLElement,\n selectorOrElements: string | NodeListOf<HTMLElement>,\n margin = 0,\n isDense = false,\n shouldContainBottom = false,\n isHorizontal = false,\n) {\n const viewportY1 = container[isHorizontal ? 'scrollLeft' : 'scrollTop'];\n const viewportY2 = viewportY1 + container[isHorizontal ? 'offsetWidth' : 'offsetHeight'];\n const allElements = typeof selectorOrElements === 'string'\n ? container.querySelectorAll<HTMLElement>(selectorOrElements)\n : selectorOrElements;\n const { length } = allElements;\n const visibleIndexes: number[] = [];\n let isFound = false;\n\n for (let i = 0; i < length; i++) {\n const element = allElements[i];\n const y1 = element[isHorizontal ? 'offsetLeft' : 'offsetTop'];\n const y2 = y1 + element[isHorizontal ? 'offsetWidth' : 'offsetHeight'];\n const isVisible = shouldContainBottom\n ? y2 >= viewportY1 - margin && y2 <= viewportY2 + margin\n : y1 <= viewportY2 + margin && y2 >= viewportY1 - margin;\n\n if (isVisible) {\n visibleIndexes.push(i);\n isFound = true;\n } else if (isFound && !isDense) {\n break;\n }\n }\n\n return { allElements, visibleIndexes };\n}\n","function isFullyVisible(container: HTMLElement, element: HTMLElement, isHorizontal = false) {\n const viewportY1 = container[isHorizontal ? 'scrollLeft' : 'scrollTop'];\n const viewportY2 = viewportY1 + container[isHorizontal ? 'offsetWidth' : 'offsetHeight'];\n const y1 = element[isHorizontal ? 'offsetLeft' : 'offsetTop'];\n const y2 = y1 + element[isHorizontal ? 'offsetWidth' : 'offsetHeight'];\n return y1 > viewportY1 && y2 < viewportY2;\n}\n\nexport default isFullyVisible;\n","import React, {\n FC, useCallback, useEffect, useState, useRef, memo,\n} from '../../../lib/teact/teact';\nimport usePrevious from '../../../hooks/usePrevious';\n\nimport { ApiChatMember, ApiUser } from '../../../api/types';\n\nimport useShowTransition from '../../../hooks/useShowTransition';\nimport buildClassName from '../../../util/buildClassName';\nimport captureKeyboardListeners from '../../../util/captureKeyboardListeners';\nimport findInViewport from '../../../util/findInViewport';\nimport isFullyVisible from '../../../util/isFullyVisible';\nimport fastSmoothScroll from '../../../util/fastSmoothScroll';\nimport cycleRestrict from '../../../util/cycleRestrict';\n\nimport ListItem from '../../ui/ListItem';\nimport PrivateChatInfo from '../../common/PrivateChatInfo';\n\nimport './MentionTooltip.scss';\n\nconst VIEWPORT_MARGIN = 8;\nconst SCROLL_MARGIN = 10;\n\nfunction setItemVisible(index: number, containerRef: Record<string, any>) {\n const container = containerRef.current!;\n if (!container || index < 0) {\n return;\n }\n const { visibleIndexes, allElements } = findInViewport(\n container,\n '.chat-item-clickable',\n VIEWPORT_MARGIN,\n true,\n true,\n );\n if (!allElements.length || !allElements[index]) {\n return;\n }\n const first = visibleIndexes[0];\n if (!visibleIndexes.includes(index)\n || (index === first && !isFullyVisible(container, allElements[first]))) {\n const position = index > visibleIndexes[visibleIndexes.length - 1] ? 'start' : 'end';\n fastSmoothScroll(container, allElements[index], position, SCROLL_MARGIN);\n }\n}\n\nexport type OwnProps = {\n isOpen: boolean;\n filter: string;\n onClose: () => void;\n onInsertUserName: (user: ApiUser, forceFocus?: boolean) => void;\n filteredChatMembers?: ApiChatMember[];\n usersById?: Record<number, ApiUser>;\n};\n\nconst MentionTooltip: FC<OwnProps> = ({\n isOpen,\n filter,\n onClose,\n onInsertUserName,\n usersById,\n filteredChatMembers,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const containerRef = useRef<HTMLDivElement>(null);\n const { shouldRender, transitionClassNames } = useShowTransition(isOpen, undefined, undefined, false);\n\n const getSelectedIndex = useCallback((newIndex: number) => {\n if (!filteredChatMembers) {\n return -1;\n }\n const membersCount = filteredChatMembers!.length;\n return cycleRestrict(membersCount, newIndex);\n }, [filteredChatMembers]);\n\n const [selectedMentionIndex, setSelectedMentionIndex] = useState(-1);\n\n const handleArrowKey = useCallback((value: number, e: KeyboardEvent) => {\n e.preventDefault();\n setSelectedMentionIndex((index) => (getSelectedIndex(index + value)));\n }, [setSelectedMentionIndex, getSelectedIndex]);\n\n const handleUserSelect = useCallback((userId: number, forceFocus = false) => {\n const user = usersById && usersById[userId];\n if (!user) {\n return;\n }\n\n onInsertUserName(user, forceFocus);\n }, [usersById, onInsertUserName]);\n\n const handleSelectMention = useCallback((e: KeyboardEvent) => {\n if (filteredChatMembers && filteredChatMembers.length && selectedMentionIndex > -1) {\n const member = filteredChatMembers[selectedMentionIndex];\n if (member) {\n e.preventDefault();\n handleUserSelect(member.userId, true);\n }\n }\n }, [filteredChatMembers, selectedMentionIndex, handleUserSelect]);\n\n useEffect(() => (isOpen ? captureKeyboardListeners({\n onEsc: onClose,\n onUp: (e: KeyboardEvent) => handleArrowKey(-1, e),\n onDown: (e: KeyboardEvent) => handleArrowKey(1, e),\n onEnter: handleSelectMention,\n onTab: handleSelectMention,\n }) : undefined), [isOpen, onClose, handleArrowKey, handleSelectMention]);\n\n useEffect(() => {\n if (filteredChatMembers && !filteredChatMembers.length) {\n onClose();\n }\n }, [filteredChatMembers, onClose]);\n\n useEffect(() => {\n setSelectedMentionIndex(0);\n }, [filter]);\n\n useEffect(() => {\n setItemVisible(selectedMentionIndex, containerRef);\n }, [selectedMentionIndex]);\n\n const prevChatMembers = usePrevious(\n filteredChatMembers && filteredChatMembers.length\n ? filteredChatMembers\n : undefined,\n shouldRender,\n );\n const renderedChatMembers = filteredChatMembers && !filteredChatMembers.length\n ? prevChatMembers\n : filteredChatMembers;\n\n if (!shouldRender || (renderedChatMembers && !renderedChatMembers.length)) {\n return undefined;\n }\n\n const className = buildClassName(\n 'MentionTooltip composer-tooltip custom-scroll',\n transitionClassNames,\n );\n\n return (\n <div className={className} ref={containerRef}>\n {renderedChatMembers && renderedChatMembers.map(({ userId }, index) => (\n <ListItem\n key={userId}\n className=\"chat-item-clickable scroll-item\"\n onClick={() => handleUserSelect(userId)}\n focus={selectedMentionIndex === index}\n >\n <PrivateChatInfo\n userId={userId}\n avatarSize=\"small\"\n withUsername\n />\n </ListItem>\n ))}\n </div>\n );\n};\n\nexport default memo(MentionTooltip);\n","import React, {\n FC, memo, useCallback, useEffect, useRef,\n} from '../../../lib/teact/teact';\n\nimport { ApiAttachment, ApiChatMember, ApiUser } from '../../../api/types';\nimport { LangCode } from '../../../types';\n\nimport { CONTENT_TYPES_FOR_QUICK_UPLOAD, EDITABLE_INPUT_MODAL_ID } from '../../../config';\nimport { getFileExtension } from '../../common/helpers/documentInfo';\nimport captureEscKeyListener from '../../../util/captureEscKeyListener';\nimport usePrevious from '../../../hooks/usePrevious';\nimport useMentionTooltip from './hooks/useMentionTooltip';\nimport useEmojiTooltip from './hooks/useEmojiTooltip';\nimport useLang from '../../../hooks/useLang';\nimport useFlag from '../../../hooks/useFlag';\n\nimport Button from '../../ui/Button';\nimport Modal from '../../ui/Modal';\nimport File from '../../common/File';\nimport MessageInput from './MessageInput';\nimport MentionTooltip from './MentionTooltip';\nimport EmojiTooltip from './EmojiTooltip.async';\n\nimport './AttachmentModal.scss';\n\nexport type OwnProps = {\n attachments: ApiAttachment[];\n caption: string;\n canSuggestMembers?: boolean;\n canSuggestEmoji?: boolean;\n currentUserId?: number;\n groupChatMembers?: ApiChatMember[];\n usersById?: Record<number, ApiUser>;\n recentEmojis: string[];\n language: LangCode;\n addRecentEmoji: AnyToVoidFunction;\n loadEmojiKeywords: AnyToVoidFunction;\n onCaptionUpdate: (html: string) => void;\n onSend: () => void;\n onFileAppend: (files: File[], isQuick: boolean) => void;\n onClear: () => void;\n};\n\nconst DROP_LEAVE_TIMEOUT_MS = 150;\n\nconst AttachmentModal: FC<OwnProps> = ({\n attachments,\n caption,\n canSuggestMembers,\n groupChatMembers,\n currentUserId,\n usersById,\n recentEmojis,\n language,\n onCaptionUpdate,\n addRecentEmoji,\n loadEmojiKeywords,\n onSend,\n onFileAppend,\n onClear,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const hideTimeoutRef = useRef<number>(null);\n const prevAttachments = usePrevious(attachments);\n const renderingAttachments = attachments.length ? attachments : prevAttachments;\n const isOpen = Boolean(attachments.length);\n const [isHovered, markHovered, unmarkHovered] = useFlag();\n const isQuick = renderingAttachments && renderingAttachments.every((a) => a.quick);\n const lang = useLang();\n\n const {\n isMentionTooltipOpen, mentionFilter,\n closeMentionTooltip, insertMention,\n mentionFilteredMembers,\n } = useMentionTooltip(\n canSuggestMembers && isOpen,\n caption,\n onCaptionUpdate,\n EDITABLE_INPUT_MODAL_ID,\n groupChatMembers,\n currentUserId,\n usersById,\n );\n const {\n isEmojiTooltipOpen, closeEmojiTooltip, filteredEmojis, insertEmoji,\n } = useEmojiTooltip(\n isOpen,\n caption,\n recentEmojis,\n EDITABLE_INPUT_MODAL_ID,\n onCaptionUpdate,\n );\n\n useEffect(() => (isOpen ? captureEscKeyListener(onClear) : undefined), [isOpen, onClear]);\n\n const sendAttachments = useCallback(() => {\n if (isOpen) {\n onSend();\n }\n }, [isOpen, onSend]);\n\n const handleDragLeave = (e: React.DragEvent<HTMLElement>) => {\n const { relatedTarget: toTarget, target: fromTarget } = e;\n\n // Esc button pressed during drag event\n if ((fromTarget as HTMLDivElement).matches('.drop-target') && !toTarget) {\n hideTimeoutRef.current = window.setTimeout(unmarkHovered, DROP_LEAVE_TIMEOUT_MS);\n }\n\n // Prevent DragLeave event from firing when the pointer moves inside the AttachmentModal drop target\n if (fromTarget && (fromTarget as HTMLElement).closest('.AttachmentModal.hovered')) {\n return;\n }\n\n if (toTarget) {\n e.stopPropagation();\n }\n\n unmarkHovered();\n };\n\n const handleFilesDrop = useCallback((e: React.DragEvent<HTMLDivElement>) => {\n e.preventDefault();\n unmarkHovered();\n\n const { dataTransfer: { files } } = e;\n\n if (files && files.length) {\n const newFiles = isQuick\n ? Array.from(files).filter((file) => {\n return file.type && CONTENT_TYPES_FOR_QUICK_UPLOAD.includes(file.type);\n })\n : Array.from(files);\n\n onFileAppend(newFiles, false);\n }\n }, [isQuick, onFileAppend, unmarkHovered]);\n\n function handleDragOver(e: React.MouseEvent<HTMLDivElement, MouseEvent>) {\n e.preventDefault();\n e.stopPropagation();\n\n if (hideTimeoutRef.current) {\n window.clearTimeout(hideTimeoutRef.current);\n }\n }\n\n if (!renderingAttachments) {\n return undefined;\n }\n\n const areAllPhotos = renderingAttachments.every((a) => a.mimeType.startsWith('image/'));\n const areAllVideos = renderingAttachments.every((a) => a.mimeType.startsWith('video/'));\n\n let title = '';\n if (areAllPhotos) {\n title = lang('PreviewSender.SendPhoto', renderingAttachments.length, 'i');\n } else if (areAllVideos) {\n title = lang('PreviewSender.SendVideo', renderingAttachments.length, 'i');\n } else {\n title = lang('PreviewSender.SendFile', renderingAttachments.length, 'i');\n }\n\n function renderHeader() {\n if (!renderingAttachments) {\n return undefined;\n }\n\n return (\n <div className=\"modal-header-condensed\" dir={lang.isRtl ? 'rtl' : undefined}>\n <Button round color=\"translucent\" size=\"smaller\" ariaLabel=\"Cancel attachments\" onClick={onClear}>\n <i className=\"icon-close\" />\n </Button>\n <div className=\"modal-title\">{title}</div>\n <Button\n color=\"primary\"\n size=\"smaller\"\n className=\"modal-action-button\"\n onClick={sendAttachments}\n >\n {lang('Send')}\n </Button>\n </div>\n );\n }\n\n return (\n <Modal\n isOpen={isOpen}\n onClose={onClear}\n header={renderHeader()}\n className={`AttachmentModal ${isHovered ? 'hovered' : ''}`}\n >\n <div\n className=\"drop-target\"\n onDragEnter={markHovered}\n onDrop={handleFilesDrop}\n onDragOver={handleDragOver}\n onDragLeave={handleDragLeave}\n data-attach-description={lang('Preview.Dragging.AddItems', 10)}\n >\n {isQuick ? (\n <div className=\"media-wrapper custom-scroll\">\n {renderingAttachments.map((attachment) => (\n attachment.mimeType.startsWith('image/')\n ? <img src={attachment.blobUrl} alt=\"\" />\n : <video src={attachment.blobUrl} autoPlay muted loop />\n ))}\n </div>\n ) : (\n <div className=\"document-wrapper custom-scroll\">\n {renderingAttachments.map((attachment) => (\n <File\n name={attachment.filename}\n extension={getFileExtension(attachment.filename, attachment.mimeType)}\n previewData={attachment.previewBlobUrl}\n size={attachment.size}\n smaller\n />\n ))}\n </div>\n )}\n\n <div className=\"attachment-caption-wrapper\">\n <MentionTooltip\n isOpen={isMentionTooltipOpen}\n onClose={closeMentionTooltip}\n filter={mentionFilter}\n onInsertUserName={insertMention}\n filteredChatMembers={mentionFilteredMembers}\n usersById={usersById}\n />\n <EmojiTooltip\n isOpen={isEmojiTooltipOpen}\n emojis={filteredEmojis}\n onClose={closeEmojiTooltip}\n language={language}\n onEmojiSelect={insertEmoji}\n addRecentEmoji={addRecentEmoji}\n loadEmojiKeywords={loadEmojiKeywords}\n />\n <MessageInput\n id=\"caption-input-text\"\n html={caption}\n editableInputId={EDITABLE_INPUT_MODAL_ID}\n placeholder={lang('Caption')}\n onUpdate={onCaptionUpdate}\n onSend={onSend}\n shouldSetFocus={isOpen}\n />\n </div>\n </div>\n </Modal>\n );\n};\n\nexport default memo(AttachmentModal);\n","import { ChangeEvent, RefObject } from 'react';\nimport React, {\n FC, memo, useCallback, useEffect, useLayoutEffect, useRef, useState,\n} from '../../../lib/teact/teact';\n\nimport { ApiNewPoll } from '../../../api/types';\n\nimport captureEscKeyListener from '../../../util/captureEscKeyListener';\nimport parseMessageInput from './helpers/parseMessageInput';\nimport useLang from '../../../hooks/useLang';\n\nimport Button from '../../ui/Button';\nimport Modal from '../../ui/Modal';\nimport InputText from '../../ui/InputText';\nimport Checkbox from '../../ui/Checkbox';\nimport RadioGroup from '../../ui/RadioGroup';\n\nimport './PollModal.scss';\n\nexport type OwnProps = {\n isOpen: boolean;\n onSend: (pollSummary: ApiNewPoll) => void;\n onClear: () => void;\n};\n\nconst MAX_LIST_HEIGHT = 320;\nconst MAX_OPTIONS_COUNT = 10;\nconst MAX_OPTION_LENGTH = 100;\nconst MAX_QUESTION_LENGTH = 255;\nconst MAX_SOLUTION_LENGTH = 200;\n\nconst PollModal: FC<OwnProps> = ({ isOpen, onSend, onClear }) => {\n // eslint-disable-next-line no-null/no-null\n const questionInputRef = useRef<HTMLInputElement>(null);\n // eslint-disable-next-line no-null/no-null\n const optionsListRef = useRef<HTMLDivElement>(null);\n // eslint-disable-next-line no-null/no-null\n const solutionRef = useRef<HTMLDivElement>(null);\n\n const [question, setQuestion] = useState<string>('');\n const [options, setOptions] = useState<string[]>(['']);\n const [isAnonymous, setIsAnonymous] = useState(true);\n const [isMultipleAnswers, setIsMultipleAnswers] = useState(false);\n const [isQuizMode, setIsQuizMode] = useState(false);\n const [solution, setSolution] = useState<string>();\n const [correctOption, setCorrectOption] = useState<string>();\n const [hasErrors, setHasErrors] = useState<boolean>(false);\n\n const lang = useLang();\n\n const focusInput = useCallback((ref: RefObject<HTMLInputElement>) => {\n if (isOpen && ref.current) {\n ref.current.focus();\n }\n }, [isOpen]);\n\n useEffect(() => (isOpen ? captureEscKeyListener(onClear) : undefined), [isOpen, onClear]);\n useEffect(() => {\n if (!isOpen) {\n setQuestion('');\n setOptions(['']);\n setIsAnonymous(true);\n setIsMultipleAnswers(false);\n setIsQuizMode(false);\n setSolution('');\n setCorrectOption('');\n setHasErrors(false);\n }\n }, [isOpen]);\n\n useEffect(() => focusInput(questionInputRef), [focusInput, isOpen]);\n\n useLayoutEffect(() => {\n const solutionEl = solutionRef.current;\n\n if (solutionEl && solution !== solutionEl.innerHTML) {\n solutionEl.innerHTML = solution;\n }\n }, [solution]);\n\n const addNewOption = useCallback((newOptions: string[] = []) => {\n setOptions([...newOptions, '']);\n requestAnimationFrame(() => {\n const list = optionsListRef.current;\n if (!list) {\n return;\n }\n\n list.classList.toggle('overflown', list.scrollHeight > MAX_LIST_HEIGHT);\n list.scrollTo({ top: list.scrollHeight, behavior: 'smooth' });\n });\n }, []);\n\n const handleCreate = useCallback(() => {\n setHasErrors(false);\n if (!isOpen) {\n return;\n }\n\n const questionTrimmed = question.trim().substring(0, MAX_QUESTION_LENGTH);\n const optionsTrimmed = options.map((o) => o.trim().substring(0, MAX_OPTION_LENGTH)).filter((o) => o.length);\n\n if (!questionTrimmed || optionsTrimmed.length < 2) {\n setQuestion(questionTrimmed);\n if (optionsTrimmed.length) {\n if (optionsTrimmed.length < 2) {\n addNewOption(optionsTrimmed);\n } else {\n setOptions(optionsTrimmed);\n }\n } else {\n addNewOption();\n }\n setHasErrors(true);\n return;\n }\n\n if (isQuizMode && (!correctOption || !optionsTrimmed[Number(correctOption)])) {\n setHasErrors(true);\n return;\n }\n\n const answers = optionsTrimmed\n .map((text, index) => ({\n text: text.trim(),\n option: String(index),\n ...(String(index) === correctOption && { correct: true }),\n }));\n\n const payload: ApiNewPoll = {\n summary: {\n question: questionTrimmed,\n answers,\n ...(!isAnonymous && { isPublic: true }),\n ...(isMultipleAnswers && { multipleChoice: true }),\n ...(isQuizMode && { quiz: true }),\n },\n };\n\n if (isQuizMode) {\n const { text, entities } = (solution && parseMessageInput(solution.substring(0, MAX_SOLUTION_LENGTH))) || {};\n\n payload.quiz = {\n correctAnswers: [correctOption],\n ...(text && { solution: text }),\n ...(entities && { solutionEntities: entities }),\n };\n }\n\n onSend(payload);\n }, [\n isOpen,\n question,\n options,\n isQuizMode,\n correctOption,\n isAnonymous,\n isMultipleAnswers,\n onSend,\n addNewOption,\n solution,\n ]);\n\n const updateOption = useCallback((index: number, text: string) => {\n const newOptions = [...options];\n newOptions[index] = text;\n if (newOptions[newOptions.length - 1].trim().length && newOptions.length < MAX_OPTIONS_COUNT) {\n addNewOption(newOptions);\n } else {\n setOptions(newOptions);\n }\n }, [options, addNewOption]);\n\n const removeOption = useCallback((index: number) => {\n const newOptions = [...options];\n newOptions.splice(index, 1);\n setOptions(newOptions);\n requestAnimationFrame(() => {\n if (!optionsListRef.current) {\n return;\n }\n\n optionsListRef.current.classList.toggle('overflown', optionsListRef.current.scrollHeight > MAX_LIST_HEIGHT);\n });\n }, [options]);\n\n const handleCorrectOptionChange = useCallback((newValue: string) => {\n setCorrectOption(newValue);\n }, [setCorrectOption]);\n\n const handleIsAnonymousChange = useCallback((e: ChangeEvent<HTMLInputElement>) => {\n setIsAnonymous(e.target.checked);\n }, []);\n\n const handleMultipleAnswersChange = useCallback((e: ChangeEvent<HTMLInputElement>) => {\n setIsMultipleAnswers(e.target.checked);\n }, []);\n\n const handleQuizModeChange = useCallback((e: ChangeEvent<HTMLInputElement>) => {\n setIsQuizMode(e.target.checked);\n }, []);\n\n const handleKeyPress = useCallback((e: React.KeyboardEvent<HTMLDivElement>) => {\n if (e.keyCode === 13) {\n handleCreate();\n }\n }, [handleCreate]);\n\n const getQuestionError = useCallback(() => {\n if (hasErrors && !question.trim().length) {\n return lang('lng_polls_choose_question');\n }\n\n return undefined;\n }, [hasErrors, lang, question]);\n\n const getOptionsError = useCallback((index: number) => {\n const optionsTrimmed = options.map((o) => o.trim()).filter((o) => o.length);\n if (hasErrors && optionsTrimmed.length < 2 && !options[index].trim().length) {\n return lang('lng_polls_choose_answers');\n }\n return undefined;\n }, [hasErrors, lang, options]);\n\n function renderHeader() {\n return (\n <div className=\"modal-header-condensed\">\n <Button round color=\"translucent\" size=\"smaller\" ariaLabel=\"Cancel poll creation\" onClick={onClear}>\n <i className=\"icon-close\" />\n </Button>\n <div className=\"modal-title\">{lang('NewPoll')}</div>\n <Button\n color=\"primary\"\n size=\"smaller\"\n className=\"modal-action-button\"\n onClick={handleCreate}\n >\n {lang('Create')}\n </Button>\n </div>\n );\n }\n\n function renderOptions() {\n return options.map((option, index) => (\n <div className=\"option-wrapper\">\n <InputText\n label={index !== options.length - 1 || options.length === MAX_OPTIONS_COUNT\n ? lang('OptionHint')\n : lang('CreatePoll.AddOption')}\n error={getOptionsError(index)}\n value={option}\n onChange={(e) => updateOption(index, e.currentTarget.value)}\n onKeyPress={handleKeyPress}\n />\n {index !== options.length - 1 && (\n <Button\n className=\"option-remove-button\"\n round\n color=\"translucent\"\n size=\"smaller\"\n ariaLabel={lang('Delete')}\n onClick={() => removeOption(index)}\n >\n <i className=\"icon-close\" />\n </Button>\n )}\n </div>\n ));\n }\n\n function renderRadioOptions() {\n return renderOptions()\n .map((label, index) => ({ value: String(index), label, hidden: index === options.length - 1 }));\n }\n\n function renderQuizNoOptionError() {\n const optionsTrimmed = options.map((o) => o.trim()).filter((o) => o.length);\n\n return isQuizMode && (!correctOption || !optionsTrimmed[Number(correctOption)]) && (\n <p className=\"error\">{lang('lng_polls_choose_correct')}</p>\n );\n }\n\n return (\n <Modal isOpen={isOpen} onClose={onClear} header={renderHeader()} className=\"PollModal\">\n <InputText\n ref={questionInputRef}\n label={lang('AskAQuestion')}\n value={question}\n error={getQuestionError()}\n onChange={(e) => setQuestion(e.currentTarget.value)}\n onKeyPress={handleKeyPress}\n />\n <div className=\"options-divider\" />\n\n <div className=\"options-list custom-scroll\" ref={optionsListRef}>\n <h3 className=\"options-header\">Options</h3>\n\n {hasErrors && renderQuizNoOptionError()}\n {isQuizMode ? (\n <RadioGroup\n name=\"correctOption\"\n options={renderRadioOptions()}\n onChange={handleCorrectOptionChange}\n />\n ) : (\n renderOptions()\n )}\n\n </div>\n\n <div className=\"options-divider\" />\n\n <div className=\"quiz-mode\">\n <Checkbox\n label={lang('PollAnonymous')}\n checked={isAnonymous}\n onChange={handleIsAnonymousChange}\n />\n <Checkbox\n label={lang('PollMultiple')}\n checked={isMultipleAnswers}\n disabled={isQuizMode}\n onChange={handleMultipleAnswersChange}\n />\n <Checkbox\n label={lang('PollQuiz')}\n checked={isQuizMode}\n disabled={isMultipleAnswers}\n onChange={handleQuizModeChange}\n />\n {isQuizMode && (\n <>\n <h3 className=\"options-header\">Solution</h3>\n <div\n ref={solutionRef}\n className=\"form-control\"\n contentEditable\n dir=\"auto\"\n onChange={(e) => setSolution(e.currentTarget.innerHTML)}\n />\n <div className=\"note\">{lang('CreatePoll.ExplanationInfo')}</div>\n </>\n )}\n </div>\n </Modal>\n );\n};\n\nexport default memo(PollModal);\n","import { useCallback, useEffect, useRef } from '../lib/teact/teact';\n\nimport { IS_TOUCH_ENV } from '../util/environment';\n\nconst MENU_CLOSE_TIMEOUT = 250;\nlet closeTimeout: number | undefined;\n\nexport default function useMouseInside(\n isOpen: boolean, onClose: NoneToVoidFunction, menuCloseTimeout = MENU_CLOSE_TIMEOUT,\n) {\n const isMouseInside = useRef(false);\n\n useEffect(() => {\n if (closeTimeout) {\n clearTimeout(closeTimeout);\n closeTimeout = undefined;\n }\n\n if (isOpen && !IS_TOUCH_ENV) {\n closeTimeout = window.setTimeout(() => {\n if (!isMouseInside.current) {\n onClose();\n }\n }, menuCloseTimeout * 2);\n }\n }, [isOpen, menuCloseTimeout, onClose]);\n\n const handleMouseEnter = useCallback(() => {\n isMouseInside.current = true;\n }, []);\n\n const handleMouseLeave = useCallback(() => {\n isMouseInside.current = false;\n\n if (closeTimeout) {\n clearTimeout(closeTimeout);\n closeTimeout = undefined;\n }\n\n closeTimeout = window.setTimeout(() => {\n if (!isMouseInside.current) {\n onClose();\n }\n }, menuCloseTimeout);\n }, [menuCloseTimeout, onClose]);\n\n return [handleMouseEnter, handleMouseLeave];\n}\n","import React, { FC, memo, useCallback } from '../../../lib/teact/teact';\n\nimport { IS_EMOJI_SUPPORTED } from '../../../util/environment';\n\nimport './EmojiButton.scss';\n\ntype OwnProps = {\n emoji: Emoji;\n focus?: boolean;\n onClick: (emoji: string, name: string) => void;\n};\n\nconst EmojiButton: FC<OwnProps> = ({ emoji, focus, onClick }) => {\n const handleClick = useCallback((e: React.MouseEvent<HTMLDivElement, MouseEvent>) => {\n // Preventing safari from losing focus on Composer MessageInput\n e.preventDefault();\n\n onClick(emoji.native, emoji.id);\n }, [emoji, onClick]);\n\n return (\n <div\n className={`EmojiButton ${focus ? 'focus' : ''}`}\n onMouseDown={handleClick}\n title={`:${emoji.names[0]}:`}\n >\n {IS_EMOJI_SUPPORTED\n ? <span className=\"font-emoji\">{emoji.native}</span>\n : <img src={`./img-apple-64/${emoji.image}.png`} alt=\"\" loading=\"lazy\" />}\n </div>\n );\n};\n\nexport default memo(EmojiButton);\n","import React, { FC, memo, useRef } from '../../../lib/teact/teact';\n\nimport { IS_MOBILE_SCREEN } from '../../../util/environment';\nimport buildClassName from '../../../util/buildClassName';\nimport windowSize from '../../../util/windowSize';\nimport { ObserveFn, useOnIntersect } from '../../../hooks/useIntersectionObserver';\nimport useShowTransition from '../../../hooks/useShowTransition';\nimport useLang from '../../../hooks/useLang';\n\nimport EmojiButton from './EmojiButton';\n\nconst EMOJIS_PER_ROW_ON_DESKTOP = 9;\nconst EMOJI_MARGIN = 4;\nconst MOBILE_CONTAINER_PADDING = 8;\nconst EMOJI_SIZE = 40;\n\ntype OwnProps = {\n category: EmojiCategory;\n index: number;\n allEmojis: AllEmojis;\n observeIntersection: ObserveFn;\n shouldRender: boolean;\n onEmojiSelect: (emoji: string, name: string) => void;\n};\n\nconst EmojiCategory: FC<OwnProps> = ({\n category, index, allEmojis, observeIntersection, shouldRender, onEmojiSelect,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const ref = useRef<HTMLDivElement>(null);\n\n useOnIntersect(ref, observeIntersection);\n\n const { transitionClassNames } = useShowTransition(shouldRender, undefined, undefined, 'slow');\n\n const lang = useLang();\n\n const emojisPerRow = IS_MOBILE_SCREEN\n ? Math.floor((windowSize.get().width - MOBILE_CONTAINER_PADDING) / (EMOJI_SIZE + EMOJI_MARGIN))\n : EMOJIS_PER_ROW_ON_DESKTOP;\n const height = Math.ceil(category.emojis.length / emojisPerRow) * (EMOJI_SIZE + EMOJI_MARGIN);\n\n return (\n <div\n ref={ref}\n key={category.id}\n id={`emoji-category-${index}`}\n className=\"symbol-set\"\n >\n <p className=\"symbol-set-name\" dir=\"auto\">\n {lang(category.id === 'recent' ? 'RecentStickers' : `Emoji${index}`)}\n </p>\n <div\n className={buildClassName('symbol-set-container', transitionClassNames)}\n // @ts-ignore\n style={`height: ${height}px;`}\n dir={lang.isRtl ? 'rtl' : undefined}\n >\n {shouldRender && category.emojis.map((name) => {\n const emoji = allEmojis[name];\n // Some emojis have multiple skins and are represented as an Object with emojis for all skins.\n // For now, we select only the first emoji with 'neutral' skin.\n const displayedEmoji = 'id' in emoji ? emoji : emoji[1];\n\n return (\n <EmojiButton\n key={displayedEmoji.id}\n emoji={displayedEmoji}\n onClick={onEmojiSelect}\n />\n );\n })}\n </div>\n </div>\n );\n};\n\nexport default memo(EmojiCategory);\n","import React, {\n FC, useState, useEffect, memo, useRef, useMemo, useCallback,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalState } from '../../../global/types';\n\nimport { MENU_TRANSITION_DURATION } from '../../../config';\nimport { MEMO_EMPTY_ARRAY } from '../../../util/memo';\nimport { IS_MOBILE_SCREEN } from '../../../util/environment';\nimport {\n EmojiModule,\n EmojiRawData,\n EmojiData,\n uncompressEmoji,\n} from '../../../util/emoji';\nimport fastSmoothScroll from '../../../util/fastSmoothScroll';\nimport buildClassName from '../../../util/buildClassName';\nimport { pick } from '../../../util/iteratees';\nimport fastSmoothScrollHorizontal from '../../../util/fastSmoothScrollHorizontal';\nimport useAsyncRendering from '../../right/hooks/useAsyncRendering';\nimport { useIntersectionObserver } from '../../../hooks/useIntersectionObserver';\nimport useHorizontalScroll from '../../../hooks/useHorizontalScroll';\nimport useLang from '../../../hooks/useLang';\n\nimport Button from '../../ui/Button';\nimport Loading from '../../ui/Loading';\nimport EmojiCategory from './EmojiCategory';\n\nimport './EmojiPicker.scss';\n\ntype OwnProps = {\n className?: string;\n onEmojiSelect: (emoji: string, name: string) => void;\n};\n\ntype StateProps = Pick<GlobalState, 'recentEmojis'>;\ntype EmojiCategoryData = { id: string; name: string; emojis: string[] };\n\nconst ICONS_BY_CATEGORY: Record<string, string> = {\n recent: 'icon-recent',\n people: 'icon-smile',\n nature: 'icon-animals',\n foods: 'icon-eats',\n activity: 'icon-sport',\n places: 'icon-car',\n objects: 'icon-lamp',\n symbols: 'icon-language',\n flags: 'icon-flag',\n};\n\nconst OPEN_ANIMATION_DELAY = 200;\n// Only a few categories are above this height.\nconst SMOOTH_SCROLL_DISTANCE = 800;\nconst FOCUS_MARGIN = 50;\nconst HEADER_BUTTON_WIDTH = 42; // px. Includes margins\nconst INTERSECTION_THROTTLE = 200;\n\nconst categoryIntersections: boolean[] = [];\n\nlet emojiDataPromise: Promise<EmojiModule>;\nlet emojiRawData: EmojiRawData;\nlet emojiData: EmojiData;\n\nconst EmojiPicker: FC<OwnProps & StateProps> = ({\n className, onEmojiSelect, recentEmojis,\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 headerRef = useRef<HTMLDivElement>(null);\n\n const [categories, setCategories] = useState<EmojiCategoryData[]>();\n const [emojis, setEmojis] = useState<AllEmojis>();\n const [activeCategoryIndex, setActiveCategoryIndex] = useState(0);\n\n const { observe: observeIntersection } = useIntersectionObserver({\n rootRef: containerRef,\n throttleMs: INTERSECTION_THROTTLE,\n }, (entries) => {\n entries.forEach((entry) => {\n const { id } = entry.target as HTMLDivElement;\n if (!id || !id.startsWith('emoji-category-')) {\n return;\n }\n\n const index = Number(id.replace('emoji-category-', ''));\n categoryIntersections[index] = entry.isIntersecting;\n });\n\n const intersectingWithIndexes = categoryIntersections\n .map((isIntersecting, index) => ({ index, isIntersecting }))\n .filter(({ isIntersecting }) => isIntersecting);\n\n if (!intersectingWithIndexes.length) {\n return;\n }\n\n setActiveCategoryIndex(intersectingWithIndexes[Math.floor(intersectingWithIndexes.length / 2)].index);\n });\n\n useHorizontalScroll(headerRef, !IS_MOBILE_SCREEN);\n\n // Scroll header when active set updates\n useEffect(() => {\n if (!categories) {\n return;\n }\n\n const header = headerRef.current;\n if (!header) {\n return;\n }\n\n const newLeft = activeCategoryIndex * HEADER_BUTTON_WIDTH - header.offsetWidth / 2 + HEADER_BUTTON_WIDTH / 2;\n\n fastSmoothScrollHorizontal(header, newLeft);\n }, [categories, activeCategoryIndex]);\n\n const lang = useLang();\n\n const allCategories = useMemo(() => {\n if (!categories) {\n return MEMO_EMPTY_ARRAY;\n }\n const themeCategories = [...categories];\n if (recentEmojis && recentEmojis.length) {\n themeCategories.unshift({\n id: 'recent',\n name: lang('RecentStickers'),\n emojis: recentEmojis,\n });\n }\n\n return themeCategories;\n }, [categories, lang, recentEmojis]);\n\n // Initialize data on first render.\n useEffect(() => {\n setTimeout(() => {\n const exec = () => {\n setCategories(emojiData.categories);\n\n setEmojis(emojiData.emojis as AllEmojis);\n };\n\n if (emojiData) {\n exec();\n } else {\n ensureEmojiData()\n .then(exec);\n }\n }, OPEN_ANIMATION_DELAY);\n }, []);\n\n const selectCategory = useCallback((index: number) => {\n setActiveCategoryIndex(index);\n const categoryEl = document.getElementById(`emoji-category-${index}`)!;\n fastSmoothScroll(containerRef.current!, categoryEl, 'start', FOCUS_MARGIN, SMOOTH_SCROLL_DISTANCE);\n }, []);\n\n const handleEmojiSelect = useCallback((emoji: string, name: string) => {\n onEmojiSelect(emoji, name);\n }, [onEmojiSelect]);\n\n const canRenderContents = useAsyncRendering([], MENU_TRANSITION_DURATION);\n\n function renderCategoryButton(category: EmojiCategoryData, index: number) {\n const icon = ICONS_BY_CATEGORY[category.id];\n\n return icon && (\n <Button\n className={`symbol-set-button ${index === activeCategoryIndex ? 'activated' : ''}`}\n round\n faded\n color=\"translucent\"\n onClick={() => selectCategory(index)}\n ariaLabel={category.name}\n >\n <i className={icon} />\n </Button>\n );\n }\n\n const containerClassName = buildClassName('EmojiPicker', className);\n\n if (!emojis || !canRenderContents) {\n return (\n <div className={containerClassName}>\n <Loading />\n </div>\n );\n }\n\n return (\n <div className={containerClassName}>\n <div ref={headerRef} className=\"EmojiPicker-header\" dir={lang.isRtl ? 'rtl' : ''}>\n {allCategories.map(renderCategoryButton)}\n </div>\n <div ref={containerRef} className=\"EmojiPicker-main no-selection no-scrollbar\">\n {allCategories.map((category, i) => (\n <EmojiCategory\n category={category}\n index={i}\n allEmojis={emojis}\n observeIntersection={observeIntersection}\n shouldRender={activeCategoryIndex >= i - 1 && activeCategoryIndex <= i + 1}\n onEmojiSelect={handleEmojiSelect}\n />\n ))}\n </div>\n </div>\n );\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\nexport default memo(withGlobal<OwnProps>(\n (global): StateProps => pick(global, ['recentEmojis']),\n)(EmojiPicker));\n","import React, { FC, memo, useRef } from '../../../lib/teact/teact';\n\nimport { ApiSticker } from '../../../api/types';\nimport { StickerSetOrRecent } from '../../../types';\nimport { ObserveFn, useOnIntersect } from '../../../hooks/useIntersectionObserver';\n\nimport { STICKER_SIZE_PICKER } from '../../../config';\nimport { IS_MOBILE_SCREEN } from '../../../util/environment';\nimport windowSize from '../../../util/windowSize';\nimport StickerButton from '../../common/StickerButton';\nimport useShowTransition from '../../../hooks/useShowTransition';\nimport buildClassName from '../../../util/buildClassName';\n\ntype OwnProps = {\n stickerSet: StickerSetOrRecent;\n loadAndPlay: boolean;\n index: number;\n observeIntersection: ObserveFn;\n shouldRender: boolean;\n onStickerSelect: (sticker: ApiSticker) => void;\n onStickerUnfave: (sticker: ApiSticker) => void;\n};\n\nconst STICKERS_PER_ROW_ON_DESKTOP = 5;\nconst STICKER_MARGIN = IS_MOBILE_SCREEN ? 8 : 16;\nconst MOBILE_CONTAINER_PADDING = 8;\n\nconst StickerSet: FC<OwnProps> = ({\n stickerSet,\n loadAndPlay,\n index,\n observeIntersection,\n shouldRender,\n onStickerSelect,\n onStickerUnfave,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const ref = useRef<HTMLDivElement>(null);\n\n useOnIntersect(ref, observeIntersection);\n\n const { transitionClassNames } = useShowTransition(shouldRender, undefined, undefined, 'slow');\n\n const stickersPerRow = IS_MOBILE_SCREEN\n ? Math.floor((windowSize.get().width - MOBILE_CONTAINER_PADDING) / (STICKER_SIZE_PICKER + STICKER_MARGIN))\n : STICKERS_PER_ROW_ON_DESKTOP;\n const height = Math.ceil(stickerSet.count / stickersPerRow) * (STICKER_SIZE_PICKER + STICKER_MARGIN);\n\n return (\n <div\n ref={ref}\n key={stickerSet.id}\n id={`sticker-set-${index}`}\n className=\"symbol-set\"\n >\n <p className=\"symbol-set-name\">{stickerSet.title}</p>\n <div\n className={buildClassName('symbol-set-container', transitionClassNames)}\n // @ts-ignore\n style={`height: ${height}px;`}\n >\n {shouldRender && stickerSet.stickers && stickerSet.stickers.map((sticker) => (\n <StickerButton\n key={sticker.id}\n sticker={sticker}\n size={STICKER_SIZE_PICKER}\n observeIntersection={observeIntersection}\n noAnimate={!loadAndPlay}\n onClick={onStickerSelect}\n clickArg={sticker}\n onUnfaveClick={stickerSet.id === 'favorite' ? onStickerUnfave : undefined}\n />\n ))}\n </div>\n </div>\n );\n};\n\nexport default memo(StickerSet);\n","import React, {\n FC, useState, useEffect, memo, useRef, useMemo, useCallback,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../../global/types';\nimport { ApiStickerSet, ApiSticker } from '../../../api/types';\nimport { StickerSetOrRecent } from '../../../types';\n\nimport { SLIDE_TRANSITION_DURATION, STICKER_SIZE_PICKER_HEADER } from '../../../config';\nimport { MEMO_EMPTY_ARRAY } from '../../../util/memo';\nimport fastSmoothScroll from '../../../util/fastSmoothScroll';\nimport buildClassName from '../../../util/buildClassName';\nimport { pick } from '../../../util/iteratees';\nimport fastSmoothScrollHorizontal from '../../../util/fastSmoothScrollHorizontal';\nimport useAsyncRendering from '../../right/hooks/useAsyncRendering';\nimport { useIntersectionObserver } from '../../../hooks/useIntersectionObserver';\nimport useHorizontalScroll from '../../../hooks/useHorizontalScroll';\nimport useLang from '../../../hooks/useLang';\n\nimport Loading from '../../ui/Loading';\nimport Button from '../../ui/Button';\nimport StickerButton from '../../common/StickerButton';\nimport StickerSet from './StickerSet';\nimport StickerSetCover from './StickerSetCover';\nimport StickerSetCoverAnimated from './StickerSetCoverAnimated';\n\nimport './StickerPicker.scss';\n\ntype OwnProps = {\n className: string;\n loadAndPlay: boolean;\n canSendStickers: boolean;\n onStickerSelect: (sticker: ApiSticker) => void;\n};\n\ntype StateProps = {\n recentStickers: ApiSticker[];\n favoriteStickers: ApiSticker[];\n stickerSetsById: Record<string, ApiStickerSet>;\n addedSetIds?: string[];\n shouldPlay?: boolean;\n};\n\ntype DispatchProps = Pick<GlobalActions, (\n 'loadStickerSets' | 'loadRecentStickers' | 'loadFavoriteStickers' |\n 'addRecentSticker' | 'loadAddedStickers' | 'unfaveSticker'\n)>;\n\nconst SMOOTH_SCROLL_DISTANCE = 500;\nconst HEADER_BUTTON_WIDTH = 52; // px (including margin)\nconst STICKER_INTERSECTION_THROTTLE = 200;\n\nconst stickerSetIntersections: boolean[] = [];\n\nconst StickerPicker: FC<OwnProps & StateProps & DispatchProps> = ({\n className,\n loadAndPlay,\n canSendStickers,\n recentStickers,\n favoriteStickers,\n addedSetIds,\n stickerSetsById,\n shouldPlay,\n onStickerSelect,\n loadStickerSets,\n loadRecentStickers,\n loadFavoriteStickers,\n loadAddedStickers,\n addRecentSticker,\n unfaveSticker,\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 headerRef = useRef<HTMLDivElement>(null);\n const [activeSetIndex, setActiveSetIndex] = useState<number>(0);\n\n const { observe: observeIntersection } = useIntersectionObserver({\n rootRef: containerRef,\n throttleMs: STICKER_INTERSECTION_THROTTLE,\n }, (entries) => {\n entries.forEach((entry) => {\n const { id } = entry.target as HTMLDivElement;\n if (!id || !id.startsWith('sticker-set-')) {\n return;\n }\n\n const index = Number(id.replace('sticker-set-', ''));\n stickerSetIntersections[index] = entry.isIntersecting;\n });\n\n const intersectingWithIndexes = stickerSetIntersections\n .map((isIntersecting, index) => ({ index, isIntersecting }))\n .filter(({ isIntersecting }) => isIntersecting);\n\n if (!intersectingWithIndexes.length) {\n return;\n }\n\n setActiveSetIndex(intersectingWithIndexes[Math.floor(intersectingWithIndexes.length / 2)].index);\n });\n const { observe: observeIntersectionForCovers } = useIntersectionObserver({ rootRef: headerRef });\n\n const lang = useLang();\n\n const areAddedLoaded = Boolean(addedSetIds);\n\n const allSets = useMemo(() => {\n if (!addedSetIds) {\n return MEMO_EMPTY_ARRAY;\n }\n\n return [\n {\n id: 'recent',\n title: lang('RecentStickers'),\n stickers: recentStickers,\n count: recentStickers.length,\n },\n {\n id: 'favorite',\n title: lang('FavoriteStickers'),\n stickers: favoriteStickers,\n count: favoriteStickers.length,\n },\n ...addedSetIds.map((id) => stickerSetsById[id]).filter(Boolean),\n ];\n }, [addedSetIds, lang, recentStickers, favoriteStickers, stickerSetsById]);\n\n const noPopulatedSets = useMemo(() => (\n areAddedLoaded\n && allSets.filter((set) => set.stickers && set.stickers.length).length === 0\n ), [allSets, areAddedLoaded]);\n\n useEffect(() => {\n if (loadAndPlay) {\n loadStickerSets();\n loadRecentStickers();\n loadFavoriteStickers();\n }\n }, [loadAndPlay, loadFavoriteStickers, loadRecentStickers, loadStickerSets]);\n\n useEffect(() => {\n if (addedSetIds && addedSetIds.length) {\n loadAddedStickers();\n }\n }, [addedSetIds, loadAddedStickers]);\n\n useHorizontalScroll(headerRef);\n\n // Scroll container and header when active set changes\n useEffect(() => {\n if (!areAddedLoaded) {\n return;\n }\n\n const header = headerRef.current;\n if (!header) {\n return;\n }\n\n const newLeft = activeSetIndex * HEADER_BUTTON_WIDTH - (header.offsetWidth / 2 - HEADER_BUTTON_WIDTH / 2);\n\n fastSmoothScrollHorizontal(header, newLeft);\n }, [areAddedLoaded, activeSetIndex]);\n\n const selectStickerSet = useCallback((index: number) => {\n setActiveSetIndex(index);\n const stickerSetEl = document.getElementById(`sticker-set-${index}`)!;\n fastSmoothScroll(containerRef.current!, stickerSetEl, 'start', undefined, SMOOTH_SCROLL_DISTANCE);\n }, []);\n\n const handleStickerSelect = useCallback((sticker: ApiSticker) => {\n onStickerSelect(sticker);\n addRecentSticker({ sticker });\n }, [addRecentSticker, onStickerSelect]);\n\n const handleStickerUnfave = useCallback((sticker: ApiSticker) => {\n unfaveSticker({ sticker });\n }, [unfaveSticker]);\n\n const canRenderContents = useAsyncRendering([], SLIDE_TRANSITION_DURATION);\n\n function renderCover(stickerSet: StickerSetOrRecent, index: number) {\n const firstSticker = stickerSet.stickers && stickerSet.stickers[0];\n const buttonClassName = buildClassName(\n 'symbol-set-button sticker-set-button',\n index === activeSetIndex && 'activated',\n );\n\n if (stickerSet.id === 'recent' || stickerSet.id === 'favorite' || stickerSet.hasThumbnail || !firstSticker) {\n return (\n <Button\n key={stickerSet.id}\n className={buttonClassName}\n ariaLabel={stickerSet.title}\n round\n faded={stickerSet.id === 'recent' || stickerSet.id === 'favorite'}\n color=\"translucent\"\n onClick={() => selectStickerSet(index)}\n >\n {stickerSet.id === 'recent' ? (\n <i className=\"icon-recent\" />\n ) : stickerSet.id === 'favorite' ? (\n <i className=\"icon-favorite\" />\n ) : stickerSet.isAnimated ? (\n <StickerSetCoverAnimated\n stickerSet={stickerSet as ApiStickerSet}\n observeIntersection={observeIntersectionForCovers}\n />\n ) : (\n <StickerSetCover\n stickerSet={stickerSet as ApiStickerSet}\n observeIntersection={observeIntersectionForCovers}\n />\n )}\n </Button>\n );\n } else {\n return (\n <StickerButton\n key={stickerSet.id}\n sticker={firstSticker}\n size={STICKER_SIZE_PICKER_HEADER}\n title={stickerSet.title}\n className={buttonClassName}\n observeIntersection={observeIntersectionForCovers}\n onClick={selectStickerSet}\n clickArg={index}\n />\n );\n }\n }\n\n const fullClassName = buildClassName('StickerPicker', className);\n\n if (!areAddedLoaded || !canRenderContents || noPopulatedSets || !canSendStickers) {\n return (\n <div className={fullClassName}>\n {!canSendStickers ? (\n <div className=\"picker-disabled\">Sending stickers is not allowed in this chat.</div>\n ) : noPopulatedSets ? (\n <div className=\"picker-disabled\">You have no saved Stickers.</div>\n ) : (\n <Loading />\n )}\n </div>\n );\n }\n\n return (\n <div className={fullClassName}>\n <div\n ref={headerRef}\n className=\"StickerPicker-header no-selection no-scrollbar\"\n >\n {allSets.map(renderCover)}\n </div>\n <div ref={containerRef} className=\"StickerPicker-main no-scrollbar\">\n {allSets.map((stickerSet, i) => (\n <StickerSet\n key={stickerSet.id}\n stickerSet={stickerSet}\n loadAndPlay={Boolean(shouldPlay && loadAndPlay)}\n index={i}\n observeIntersection={observeIntersection}\n shouldRender={activeSetIndex >= i - 1 && activeSetIndex <= i + 1}\n onStickerSelect={handleStickerSelect}\n onStickerUnfave={handleStickerUnfave}\n />\n ))}\n </div>\n </div>\n );\n};\n\nexport default memo(withGlobal<OwnProps>(\n (global): StateProps => {\n const {\n setsById,\n added,\n recent,\n favorite,\n } = global.stickers;\n\n return {\n recentStickers: recent.stickers,\n favoriteStickers: favorite.stickers,\n stickerSetsById: setsById,\n addedSetIds: added.setIds,\n shouldPlay: global.settings.byKey.shouldLoopStickers,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'loadStickerSets',\n 'loadRecentStickers',\n 'loadFavoriteStickers',\n 'loadAddedStickers',\n 'addRecentSticker',\n 'unfaveSticker',\n ]),\n)(StickerPicker));\n","import React, {\n FC, memo, useCallback, useRef,\n} from '../../lib/teact/teact';\n\nimport { ApiMediaFormat, ApiVideo } from '../../api/types';\n\nimport buildClassName from '../../util/buildClassName';\nimport { ObserveFn, useIsIntersecting } from '../../hooks/useIntersectionObserver';\nimport useMedia from '../../hooks/useMedia';\nimport useTransitionForMedia from '../../hooks/useTransitionForMedia';\nimport useVideoCleanup from '../../hooks/useVideoCleanup';\nimport useBuffering from '../../hooks/useBuffering';\nimport useCanvasBlur from '../../hooks/useCanvasBlur';\n\nimport Spinner from '../ui/Spinner';\n\nimport './GifButton.scss';\n\ntype OwnProps = {\n gif: ApiVideo;\n observeIntersection: ObserveFn;\n isDisabled?: boolean;\n onClick: (gif: ApiVideo) => void;\n};\n\nconst GifButton: FC<OwnProps> = ({\n gif, observeIntersection, isDisabled, onClick,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const ref = useRef<HTMLDivElement>(null);\n // eslint-disable-next-line no-null/no-null\n const videoRef = useRef<HTMLVideoElement>(null);\n\n const hasThumbnail = gif.thumbnail && !!gif.thumbnail.dataUri;\n const localMediaHash = `gif${gif.id}`;\n const isIntersecting = useIsIntersecting(ref, observeIntersection);\n const loadAndPlay = isIntersecting && !isDisabled;\n const previewBlobUrl = useMedia(`${localMediaHash}?size=m`, !loadAndPlay, ApiMediaFormat.BlobUrl);\n const thumbRef = useCanvasBlur(gif.thumbnail && gif.thumbnail.dataUri, Boolean(previewBlobUrl));\n const videoData = useMedia(localMediaHash, !loadAndPlay, ApiMediaFormat.BlobUrl);\n const shouldRenderVideo = Boolean(loadAndPlay && videoData);\n const { transitionClassNames } = useTransitionForMedia(hasThumbnail || previewBlobUrl || videoData, 'slow');\n const { isBuffered, bufferingHandlers } = useBuffering(true);\n const shouldRenderSpinner = loadAndPlay && !isBuffered;\n\n useVideoCleanup(videoRef, [shouldRenderVideo]);\n\n const handleClick = useCallback(\n () => onClick({\n ...gif,\n blobUrl: videoData,\n }),\n [onClick, gif, videoData],\n );\n\n const className = buildClassName(\n 'GifButton',\n gif.width && gif.height && gif.width < gif.height ? 'vertical' : 'horizontal',\n transitionClassNames,\n localMediaHash,\n );\n\n return (\n <div\n ref={ref}\n className={className}\n onClick={handleClick}\n >\n {hasThumbnail && (\n <canvas\n ref={thumbRef}\n className=\"thumbnail\"\n />\n )}\n {!hasThumbnail && previewBlobUrl && (\n <img\n src={previewBlobUrl}\n alt=\"\"\n className=\"thumbnail\"\n />\n )}\n {(shouldRenderVideo || previewBlobUrl) && (\n <video\n ref={videoRef}\n autoPlay\n loop\n muted\n playsInline\n preload=\"none\"\n // eslint-disable-next-line react/jsx-props-no-spreading\n {...bufferingHandlers}\n >\n <source src={videoData} />\n </video>\n )}\n {shouldRenderSpinner && (\n <Spinner color={previewBlobUrl || hasThumbnail ? 'white' : 'black'} />\n )}\n </div>\n );\n};\n\nexport default memo(GifButton);\n","import React, {\n FC, useEffect, memo, useRef,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../../global/types';\nimport { ApiVideo } from '../../../api/types';\n\nimport { SLIDE_TRANSITION_DURATION } from '../../../config';\nimport buildClassName from '../../../util/buildClassName';\nimport { pick } from '../../../util/iteratees';\nimport { useIntersectionObserver } from '../../../hooks/useIntersectionObserver';\nimport useAsyncRendering from '../../right/hooks/useAsyncRendering';\n\nimport Loading from '../../ui/Loading';\nimport GifButton from '../../common/GifButton';\n\nimport './GifPicker.scss';\n\ntype OwnProps = {\n className: string;\n loadAndPlay: boolean;\n canSendGifs: boolean;\n onGifSelect: (gif: ApiVideo) => void;\n};\n\ntype StateProps = {\n savedGifs?: ApiVideo[];\n};\n\ntype DispatchProps = Pick<GlobalActions, 'loadSavedGifs'>;\n\nconst INTERSECTION_DEBOUNCE = 300;\n\nconst GifPicker: FC<OwnProps & StateProps & DispatchProps> = ({\n className,\n loadAndPlay,\n canSendGifs,\n savedGifs,\n onGifSelect,\n loadSavedGifs,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const containerRef = useRef<HTMLDivElement>(null);\n\n const {\n observe: observeIntersection,\n } = useIntersectionObserver({ rootRef: containerRef, debounceMs: INTERSECTION_DEBOUNCE });\n\n useEffect(() => {\n if (loadAndPlay) {\n loadSavedGifs();\n }\n }, [loadAndPlay, loadSavedGifs]);\n\n const canRenderContents = useAsyncRendering([], SLIDE_TRANSITION_DURATION);\n\n return (\n <div ref={containerRef} className={buildClassName('GifPicker no-scrollbar', className)}>\n {!canSendGifs ? (\n <div className=\"picker-disabled\">Sending GIFs is not allowed in this chat.</div>\n ) : canRenderContents && savedGifs && savedGifs.length ? (\n savedGifs.map((gif) => (\n <GifButton\n key={gif.id}\n gif={gif}\n observeIntersection={observeIntersection}\n isDisabled={!loadAndPlay}\n onClick={onGifSelect}\n />\n ))\n ) : canRenderContents && savedGifs ? (\n <div className=\"picker-disabled\">No saved GIFs.</div>\n ) : (\n <Loading />\n )}\n </div>\n );\n};\n\nexport default memo(withGlobal<OwnProps>(\n (global): StateProps => {\n return {\n savedGifs: global.gifs.saved.gifs,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, ['loadSavedGifs']),\n)(GifPicker));\n","import React, { FC, memo, useCallback } from '../../../lib/teact/teact';\n\nimport useLang from '../../../hooks/useLang';\n\nimport Button from '../../ui/Button';\n\ntype OwnProps = {\n activeTab: SymbolMenuTabs;\n onSwitchTab: (tab: SymbolMenuTabs) => void;\n onRemoveSymbol: () => void;\n onSearchOpen: (type: 'stickers' | 'gifs') => void;\n};\n\nexport enum SymbolMenuTabs {\n 'Emoji',\n 'Stickers',\n 'GIFs',\n}\n\n// Getting enum string values for display in Tabs.\n// See: https://www.typescriptlang.org/docs/handbook/enums.html#reverse-mappings\nexport const SYMBOL_MENU_TAB_TITLES = Object.values(SymbolMenuTabs)\n .filter((value): value is string => typeof value === 'string');\n\nconst SYMBOL_MENU_TAB_ICONS = {\n [SymbolMenuTabs.Emoji]: 'icon-smile',\n [SymbolMenuTabs.Stickers]: 'icon-stickers',\n [SymbolMenuTabs.GIFs]: 'icon-gifs',\n};\n\nconst SymbolMenuFooter: FC<OwnProps> = ({\n activeTab, onSwitchTab, onRemoveSymbol, onSearchOpen,\n}) => {\n const lang = useLang();\n\n function renderTabButton(tab: SymbolMenuTabs) {\n return (\n <Button\n className={`symbol-tab-button ${activeTab === tab ? 'activated' : ''}`}\n onClick={() => onSwitchTab(tab)}\n ariaLabel={SYMBOL_MENU_TAB_TITLES[tab]}\n round\n faded\n color=\"translucent\"\n >\n <i className={SYMBOL_MENU_TAB_ICONS[tab]} />\n </Button>\n );\n }\n\n const handleSearchOpen = useCallback(() => {\n onSearchOpen(activeTab === SymbolMenuTabs.Stickers ? 'stickers' : 'gifs');\n }, [activeTab, onSearchOpen]);\n\n function stopPropagation(event: any) {\n event.stopPropagation();\n }\n\n return (\n <div className=\"SymbolMenu-footer\" onClick={stopPropagation} dir={lang.isRtl ? 'rtl' : undefined}>\n {activeTab !== SymbolMenuTabs.Emoji && (\n <Button\n className=\"symbol-search-button\"\n ariaLabel={activeTab === SymbolMenuTabs.Stickers ? 'Search Stickers' : 'Search GIFs'}\n round\n faded\n color=\"translucent\"\n onClick={handleSearchOpen}\n >\n <i className=\"icon-search\" />\n </Button>\n )}\n\n {renderTabButton(SymbolMenuTabs.Emoji)}\n {renderTabButton(SymbolMenuTabs.Stickers)}\n {renderTabButton(SymbolMenuTabs.GIFs)}\n\n {activeTab === SymbolMenuTabs.Emoji && (\n <Button\n className=\"symbol-delete-button\"\n onClick={onRemoveSymbol}\n ariaLabel=\"Remove Symbol\"\n round\n faded\n color=\"translucent\"\n >\n <i className=\"icon-delete-left\" />\n </Button>\n )}\n </div>\n );\n};\n\nexport default memo(SymbolMenuFooter);\n","import React, {\n FC, memo, useCallback, useEffect, useLayoutEffect, useRef, useState,\n} from '../../../lib/teact/teact';\n\nimport { ApiSticker, ApiVideo } from '../../../api/types';\n\nimport { IAllowedAttachmentOptions } from '../../../modules/helpers';\nimport { IS_MOBILE_SCREEN, IS_TOUCH_ENV } from '../../../util/environment';\nimport { fastRaf } from '../../../util/schedulers';\nimport buildClassName from '../../../util/buildClassName';\nimport useShowTransition from '../../../hooks/useShowTransition';\nimport useMouseInside from '../../../hooks/useMouseInside';\nimport useLang from '../../../hooks/useLang';\n\nimport Button from '../../ui/Button';\nimport Menu from '../../ui/Menu';\nimport Transition from '../../ui/Transition';\nimport EmojiPicker from './EmojiPicker';\nimport StickerPicker from './StickerPicker';\nimport GifPicker from './GifPicker';\nimport SymbolMenuFooter, { SYMBOL_MENU_TAB_TITLES, SymbolMenuTabs } from './SymbolMenuFooter';\nimport Portal from '../../ui/Portal';\n\nimport './SymbolMenu.scss';\n\nconst ANIMATION_DURATION = 350;\n\nexport type OwnProps = {\n isOpen: boolean;\n allowedAttachmentOptions: IAllowedAttachmentOptions;\n onLoad: () => void;\n onClose: () => void;\n onEmojiSelect: (emoji: string) => void;\n onStickerSelect: (sticker: ApiSticker) => void;\n onGifSelect: (gif: ApiVideo) => void;\n onRemoveSymbol: () => void;\n onSearchOpen: (type: 'stickers' | 'gifs') => void;\n addRecentEmoji: AnyToVoidFunction;\n};\n\nlet isActivated = false;\n\nconst SymbolMenu: FC<OwnProps> = ({\n isOpen, allowedAttachmentOptions,\n onLoad, onClose,\n onEmojiSelect, onStickerSelect, onGifSelect,\n onRemoveSymbol, onSearchOpen, addRecentEmoji,\n}) => {\n const [activeTab, setActiveTab] = useState<number>(0);\n const [recentEmojis, setRecentEmojis] = useState<string[]>([]);\n\n const [handleMouseEnter, handleMouseLeave] = useMouseInside(isOpen, onClose);\n const { shouldRender, transitionClassNames } = useShowTransition(isOpen, onClose, false, false);\n\n if (!isActivated && isOpen) {\n isActivated = true;\n }\n\n useEffect(() => {\n onLoad();\n }, [onLoad]);\n\n useLayoutEffect(() => {\n if (!IS_MOBILE_SCREEN) {\n return undefined;\n }\n\n if (isOpen) {\n document.body.classList.add('enable-symbol-menu-transforms');\n document.body.classList.add('is-symbol-menu-open');\n }\n\n return () => {\n if (isOpen) {\n fastRaf(() => {\n document.body.classList.remove('is-symbol-menu-open');\n setTimeout(() => {\n document.body.classList.remove('enable-symbol-menu-transforms');\n }, ANIMATION_DURATION);\n });\n }\n };\n }, [isOpen]);\n\n const recentEmojisRef = useRef(recentEmojis);\n recentEmojisRef.current = recentEmojis;\n useEffect(() => {\n if (!recentEmojisRef.current.length) {\n return;\n }\n\n recentEmojisRef.current.forEach((name) => {\n addRecentEmoji({ emoji: name });\n });\n\n setRecentEmojis([]);\n }, [isOpen, activeTab, addRecentEmoji]);\n\n const handleEmojiSelect = useCallback((emoji: string, name: string) => {\n setRecentEmojis((emojis) => {\n return [...emojis, name];\n });\n\n onEmojiSelect(emoji);\n }, [onEmojiSelect]);\n\n const handleSearch = useCallback((type: 'stickers' | 'gifs') => {\n onClose();\n onSearchOpen(type);\n }, [onClose, onSearchOpen]);\n\n const lang = useLang();\n\n const { canSendStickers, canSendGifs } = allowedAttachmentOptions;\n\n function renderContent(isActive: boolean, isFrom: boolean) {\n switch (activeTab) {\n case SymbolMenuTabs.Emoji:\n return (\n <EmojiPicker\n className=\"picker-tab\"\n onEmojiSelect={handleEmojiSelect}\n />\n );\n case SymbolMenuTabs.Stickers:\n return (\n <StickerPicker\n className=\"picker-tab\"\n loadAndPlay={canSendStickers ? isOpen && (isActive || isFrom) : false}\n canSendStickers={canSendStickers}\n onStickerSelect={onStickerSelect}\n />\n );\n case SymbolMenuTabs.GIFs:\n return (\n <GifPicker\n className=\"picker-tab\"\n loadAndPlay={canSendGifs ? isOpen && (isActive || isFrom) : false}\n canSendGifs={canSendGifs}\n onGifSelect={onGifSelect}\n />\n );\n }\n\n return undefined;\n }\n\n function stopPropagation(event: any) {\n event.stopPropagation();\n }\n\n const content = (\n <>\n <div className=\"SymbolMenu-main\" onClick={stopPropagation}>\n {isActivated && (\n <Transition name=\"slide\" activeKey={activeTab} renderCount={SYMBOL_MENU_TAB_TITLES.length}>\n {renderContent}\n </Transition>\n )}\n </div>\n {IS_MOBILE_SCREEN && (\n <Button\n round\n faded\n color=\"translucent\"\n ariaLabel={lang('Close')}\n className=\"symbol-close-button\"\n size=\"tiny\"\n onClick={onClose}\n >\n <i className=\"icon-close\" />\n </Button>\n )}\n <SymbolMenuFooter\n activeTab={activeTab}\n onSwitchTab={setActiveTab}\n onRemoveSymbol={onRemoveSymbol}\n onSearchOpen={handleSearch}\n />\n </>\n );\n\n if (IS_MOBILE_SCREEN) {\n if (!shouldRender) {\n return undefined;\n }\n\n const className = buildClassName(\n 'SymbolMenu mobile-menu',\n transitionClassNames,\n );\n\n return (\n <Portal>\n <div className={className}>\n {content}\n </div>\n </Portal>\n );\n }\n\n return (\n <Menu\n isOpen={isOpen}\n positionX=\"left\"\n positionY=\"bottom\"\n onClose={onClose}\n className=\"SymbolMenu\"\n onCloseAnimationEnd={onClose}\n onMouseEnter={!IS_TOUCH_ENV ? handleMouseEnter : undefined}\n onMouseLeave={!IS_TOUCH_ENV ? handleMouseLeave : undefined}\n noCloseOnBackdrop={!IS_TOUCH_ENV}\n >\n {content}\n </Menu>\n );\n};\n\nexport default memo(SymbolMenu);\n","import React, { FC, memo, useCallback } from '../../../lib/teact/teact';\n\nimport { CONTENT_TYPES_FOR_QUICK_UPLOAD } from '../../../config';\nimport { IS_TOUCH_ENV } from '../../../util/environment';\nimport { openSystemFilesDialog } from '../../../util/systemFilesDialog';\nimport { IAllowedAttachmentOptions } from '../../../modules/helpers';\nimport useMouseInside from '../../../hooks/useMouseInside';\nimport useLang from '../../../hooks/useLang';\n\nimport Menu from '../../ui/Menu';\nimport MenuItem from '../../ui/MenuItem';\n\nimport './AttachMenu.scss';\n\nexport type OwnProps = {\n isOpen: boolean;\n allowedAttachmentOptions: IAllowedAttachmentOptions;\n onFileSelect: (files: File[], isQuick: boolean) => void;\n onPollCreate: () => void;\n onClose: () => void;\n};\n\nconst AttachMenu: FC<OwnProps> = ({\n isOpen, allowedAttachmentOptions, onFileSelect, onPollCreate, onClose,\n}) => {\n const [handleMouseEnter, handleMouseLeave] = useMouseInside(isOpen, onClose);\n\n const handleFileSelect = useCallback((e: Event, isQuick: boolean) => {\n const { files } = e.target as HTMLInputElement;\n\n if (files && files.length > 0) {\n onFileSelect(Array.from(files), isQuick);\n }\n }, [onFileSelect]);\n\n const handleQuickSelect = useCallback(() => {\n openSystemFilesDialog(\n CONTENT_TYPES_FOR_QUICK_UPLOAD,\n (e) => handleFileSelect(e, true),\n );\n }, [handleFileSelect]);\n\n const handleDocumentSelect = useCallback(() => {\n openSystemFilesDialog('*', (e) => handleFileSelect(e, false));\n }, [handleFileSelect]);\n\n const lang = useLang();\n\n const { canAttachMedia, canAttachPolls } = allowedAttachmentOptions;\n\n return (\n <Menu\n isOpen={isOpen}\n autoClose\n positionX=\"right\"\n positionY=\"bottom\"\n onClose={onClose}\n className=\"AttachMenu fluid\"\n onCloseAnimationEnd={onClose}\n onMouseEnter={!IS_TOUCH_ENV ? handleMouseEnter : undefined}\n onMouseLeave={!IS_TOUCH_ENV ? handleMouseLeave : undefined}\n noCloseOnBackdrop={!IS_TOUCH_ENV}\n >\n {/*\n ** Using ternary operator here causes some attributes from first clause\n ** transferring to the fragment content in the second clause\n */}\n {!canAttachMedia && (\n <MenuItem className=\"media-disabled\" disabled>Posting media content is not allowed in this group.</MenuItem>\n )}\n {canAttachMedia && (\n <>\n <MenuItem icon=\"photo\" onClick={handleQuickSelect}>\n {lang('AttachmentMenu.PhotoOrVideo')}\n </MenuItem>\n <MenuItem icon=\"document\" onClick={handleDocumentSelect}>{lang('AttachDocument')}</MenuItem>\n </>\n )}\n {canAttachPolls && (\n <MenuItem icon=\"poll\" onClick={onPollCreate}>{lang('Poll')}</MenuItem>\n )}\n </Menu>\n );\n};\n\nexport default memo(AttachMenu);\n","import React, {\n FC, memo, useEffect, useRef,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { ApiSticker } from '../../../api/types';\nimport { GlobalActions } from '../../../global/types';\n\nimport { STICKER_SIZE_PICKER } from '../../../config';\nimport { IS_TOUCH_ENV } from '../../../util/environment';\nimport buildClassName from '../../../util/buildClassName';\nimport captureEscKeyListener from '../../../util/captureEscKeyListener';\nimport { pick } from '../../../util/iteratees';\nimport { useIntersectionObserver } from '../../../hooks/useIntersectionObserver';\nimport useShowTransition from '../../../hooks/useShowTransition';\nimport usePrevious from '../../../hooks/usePrevious';\n\nimport Loading from '../../ui/Loading';\nimport StickerButton from '../../common/StickerButton';\n\nimport './StickerTooltip.scss';\n\nexport type OwnProps = {\n isOpen: boolean;\n onStickerSelect: (sticker: ApiSticker) => void;\n};\n\ntype StateProps = {\n stickers?: ApiSticker[];\n};\n\ntype DispatchProps = Pick<GlobalActions, 'clearStickersForEmoji'>;\n\nconst INTERSECTION_THROTTLE = 200;\n\nconst StickerTooltip: FC<OwnProps & StateProps & DispatchProps> = ({\n isOpen,\n onStickerSelect,\n stickers,\n clearStickersForEmoji,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const containerRef = useRef<HTMLDivElement>(null);\n const { shouldRender, transitionClassNames } = useShowTransition(isOpen, undefined, undefined, false);\n const prevStickers = usePrevious(stickers, true);\n const displayedStickers = stickers || prevStickers;\n\n const {\n observe: observeIntersection,\n } = useIntersectionObserver({ rootRef: containerRef, throttleMs: INTERSECTION_THROTTLE });\n\n useEffect(() => (isOpen ? captureEscKeyListener(clearStickersForEmoji) : undefined), [isOpen, clearStickersForEmoji]);\n\n const handleMouseEnter = () => {\n document.body.classList.add('no-select');\n };\n\n const handleMouseLeave = () => {\n document.body.classList.remove('no-select');\n };\n\n const className = buildClassName(\n 'StickerTooltip composer-tooltip custom-scroll',\n transitionClassNames,\n !(displayedStickers && displayedStickers.length) && 'hidden',\n );\n\n return (\n <div\n ref={containerRef}\n className={className}\n onMouseEnter={!IS_TOUCH_ENV ? handleMouseEnter : undefined}\n onMouseLeave={!IS_TOUCH_ENV ? handleMouseLeave : undefined}\n >\n {shouldRender && displayedStickers ? (\n displayedStickers.map((sticker) => (\n <StickerButton\n key={sticker.id}\n sticker={sticker}\n size={STICKER_SIZE_PICKER}\n observeIntersection={observeIntersection}\n onClick={onStickerSelect}\n clickArg={sticker}\n />\n ))\n ) : shouldRender ? (\n <Loading />\n ) : undefined}\n </div>\n );\n};\n\nexport default memo(withGlobal<OwnProps>(\n (global): StateProps => {\n const { stickers } = global.stickers.forEmoji;\n\n return { stickers };\n },\n (setGlobal, actions): DispatchProps => pick(actions, ['clearStickersForEmoji']),\n)(StickerTooltip));\n","import React, { FC, memo } from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../../global/types';\nimport { ApiMessage } from '../../../api/types';\n\nimport { IS_TOUCH_ENV } from '../../../util/environment';\nimport { pick } from '../../../util/iteratees';\nimport { selectChatMessage, selectCurrentMessageList } from '../../../modules/selectors';\nimport useMouseInside from '../../../hooks/useMouseInside';\n\nimport Menu from '../../ui/Menu';\nimport Button from '../../ui/Button';\n\nimport './BotKeyboardMenu.scss';\n\nexport type OwnProps = {\n isOpen: boolean;\n messageId: number;\n onClose: NoneToVoidFunction;\n};\n\ntype StateProps = {\n message?: ApiMessage;\n};\n\ntype DispatchProps = Pick<GlobalActions, ('clickInlineButton')>;\n\nconst BotKeyboardMenu: FC<OwnProps & StateProps & DispatchProps> = ({\n isOpen, message, onClose, clickInlineButton,\n}) => {\n const [handleMouseEnter, handleMouseLeave] = useMouseInside(isOpen, onClose);\n\n if (!message || !message.keyboardButtons) {\n return undefined;\n }\n\n return (\n <Menu\n isOpen={isOpen}\n autoClose\n positionX=\"right\"\n positionY=\"bottom\"\n onClose={onClose}\n className=\"KeyboardMenu\"\n onCloseAnimationEnd={onClose}\n onMouseEnter={!IS_TOUCH_ENV ? handleMouseEnter : undefined}\n onMouseLeave={!IS_TOUCH_ENV ? handleMouseLeave : undefined}\n noCloseOnBackdrop={!IS_TOUCH_ENV}\n >\n <div className=\"content\">\n {message.keyboardButtons.map((row) => (\n <div className=\"row\">\n {row.map((button) => (\n <Button\n ripple\n disabled={button.type === 'NOT_SUPPORTED'}\n onClick={() => clickInlineButton({ button })}\n >\n {button.text}\n </Button>\n ))}\n </div>\n ))}\n </div>\n </Menu>\n );\n};\n\nexport default memo(withGlobal<OwnProps>(\n (global, { messageId }): StateProps => {\n const { chatId } = selectCurrentMessageList(global) || {};\n if (!chatId) {\n return {};\n }\n\n return { message: selectChatMessage(global, chatId, messageId) };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'clickInlineButton',\n ]),\n)(BotKeyboardMenu));\n","import React, { FC, memo } from '../../../lib/teact/teact';\n\nimport { IS_TOUCH_ENV } from '../../../util/environment';\nimport useMouseInside from '../../../hooks/useMouseInside';\nimport useLang from '../../../hooks/useLang';\n\nimport Menu from '../../ui/Menu';\nimport MenuItem from '../../ui/MenuItem';\n\nimport './CustomSendMenu.scss';\n\nexport type OwnProps = {\n isOpen: boolean;\n onSilentSend?: NoneToVoidFunction;\n onScheduleSend?: NoneToVoidFunction;\n onClose: NoneToVoidFunction;\n onCloseAnimationEnd?: NoneToVoidFunction;\n};\n\nconst CustomSendMenu: FC<OwnProps> = ({\n isOpen, onSilentSend, onScheduleSend, onClose, onCloseAnimationEnd,\n}) => {\n const [handleMouseEnter, handleMouseLeave] = useMouseInside(isOpen, onClose);\n\n const lang = useLang();\n\n return (\n <Menu\n isOpen={isOpen}\n autoClose\n positionX=\"right\"\n positionY=\"bottom\"\n className=\"CustomSendMenu\"\n onClose={onClose}\n onCloseAnimationEnd={onCloseAnimationEnd}\n onMouseEnter={!IS_TOUCH_ENV ? handleMouseEnter : undefined}\n onMouseLeave={!IS_TOUCH_ENV ? handleMouseLeave : undefined}\n noCloseOnBackdrop={!IS_TOUCH_ENV}\n >\n {onSilentSend && <MenuItem icon=\"mute\" onClick={onSilentSend}>{lang('SendWithoutSound')}</MenuItem>}\n {onScheduleSend && <MenuItem icon=\"schedule\" onClick={onScheduleSend}>{lang('ScheduleMessage')}</MenuItem>}\n </Menu>\n );\n};\n\nexport default memo(CustomSendMenu);\n","import React, {\n FC, memo, useCallback, useEffect, useRef, useState,\n} from '../../../lib/teact/teact';\n\nimport { IS_TOUCH_ENV } from '../../../util/environment';\nimport buildClassName from '../../../util/buildClassName';\nimport cycleRestrict from '../../../util/cycleRestrict';\nimport captureKeyboardListeners from '../../../util/captureKeyboardListeners';\nimport findInViewport from '../../../util/findInViewport';\nimport isFullyVisible from '../../../util/isFullyVisible';\nimport fastSmoothScrollHorizontal from '../../../util/fastSmoothScrollHorizontal';\nimport useShowTransition from '../../../hooks/useShowTransition';\nimport usePrevDuringAnimation from '../../../hooks/usePrevDuringAnimation';\n\nimport Loading from '../../ui/Loading';\nimport EmojiButton from './EmojiButton';\n\nimport './EmojiTooltip.scss';\nimport { LangCode } from '../../../types';\n\nconst VIEWPORT_MARGIN = 8;\nconst EMOJI_BUTTON_WIDTH = 44;\n\nfunction setItemVisible(index: number, containerRef: Record<string, any>) {\n const container = containerRef.current!;\n if (!container) {\n return;\n }\n\n const { visibleIndexes, allElements } = findInViewport(\n container,\n '.EmojiButton',\n VIEWPORT_MARGIN,\n true,\n true,\n true,\n );\n\n if (!allElements.length || !allElements[index]) {\n return;\n }\n const first = visibleIndexes[0];\n if (!visibleIndexes.includes(index)\n || (index === first && !isFullyVisible(container, allElements[first], true))) {\n const position = index > visibleIndexes[visibleIndexes.length - 1] ? 'start' : 'end';\n const newLeft = position === 'start' ? index * EMOJI_BUTTON_WIDTH : 0;\n\n fastSmoothScrollHorizontal(container, newLeft);\n }\n}\n\nexport type OwnProps = {\n isOpen: boolean;\n language: LangCode;\n onEmojiSelect: (text: string) => void;\n onClose: NoneToVoidFunction;\n addRecentEmoji: AnyToVoidFunction;\n loadEmojiKeywords: AnyToVoidFunction;\n emojis: Emoji[];\n};\n\nconst CLOSE_DURATION = 350;\n\nconst EmojiTooltip: FC<OwnProps> = ({\n isOpen,\n language,\n emojis,\n onClose,\n onEmojiSelect,\n addRecentEmoji,\n loadEmojiKeywords,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const containerRef = useRef<HTMLDivElement>(null);\n const { shouldRender, transitionClassNames } = useShowTransition(isOpen, undefined, undefined, false);\n const listEmojis: Emoji[] = usePrevDuringAnimation(emojis.length ? emojis : undefined, CLOSE_DURATION) || [];\n\n const [selectedIndex, setSelectedIndex] = useState(-1);\n\n useEffect(() => {\n loadEmojiKeywords({ language });\n }, [loadEmojiKeywords, language]);\n\n useEffect(() => {\n setSelectedIndex(0);\n }, [emojis]);\n\n useEffect(() => {\n setItemVisible(selectedIndex, containerRef);\n }, [selectedIndex]);\n\n const getSelectedIndex = useCallback((newIndex: number) => {\n if (!emojis.length) {\n return -1;\n }\n\n const emojisCount = emojis.length;\n return cycleRestrict(emojisCount, newIndex);\n }, [emojis]);\n\n\n const handleArrowKey = useCallback((value: number, e: KeyboardEvent) => {\n e.preventDefault();\n setSelectedIndex((index) => (getSelectedIndex(index + value)));\n }, [setSelectedIndex, getSelectedIndex]);\n\n const handleSelectEmoji = useCallback((e: KeyboardEvent) => {\n if (emojis.length && selectedIndex > -1) {\n const emoji = emojis[selectedIndex];\n if (emoji) {\n e.preventDefault();\n onEmojiSelect(emoji.native);\n addRecentEmoji({ emoji: emoji.id });\n }\n }\n }, [addRecentEmoji, emojis, onEmojiSelect, selectedIndex]);\n\n useEffect(() => (isOpen ? captureKeyboardListeners({\n onEsc: onClose,\n onLeft: (e: KeyboardEvent) => handleArrowKey(-1, e),\n onRight: (e: KeyboardEvent) => handleArrowKey(1, e),\n onEnter: handleSelectEmoji,\n }) : undefined), [handleArrowKey, handleSelectEmoji, isOpen, onClose]);\n\n const handleMouseEnter = () => {\n document.body.classList.add('no-select');\n };\n\n const handleMouseLeave = () => {\n document.body.classList.remove('no-select');\n };\n\n const className = buildClassName(\n 'EmojiTooltip composer-tooltip custom-scroll-x',\n transitionClassNames,\n );\n\n return (\n <div\n ref={containerRef}\n className={className}\n onMouseEnter={!IS_TOUCH_ENV ? handleMouseEnter : undefined}\n onMouseLeave={!IS_TOUCH_ENV ? handleMouseLeave : undefined}\n >\n {shouldRender && listEmojis ? (\n listEmojis.map((emoji, index) => (\n <EmojiButton\n key={emoji.id}\n emoji={emoji}\n focus={selectedIndex === index}\n onClick={onEmojiSelect}\n />\n ))\n ) : shouldRender ? (\n <Loading />\n ) : undefined}\n </div>\n );\n};\n\nexport default memo(EmojiTooltip);\n","import React, {\n FC, useMemo, memo, useRef,\n} from '../../lib/teact/teact';\nimport { getGlobal, withGlobal } from '../../lib/teact/teactn';\n\nimport { ApiMessage, ApiUser, ApiChat } from '../../api/types';\nimport { GlobalActions } from '../../global/types';\n\nimport {\n selectUser,\n selectChatMessages,\n selectChat,\n selectCurrentTextSearch,\n} from '../../modules/selectors';\nimport {\n getMessageSummaryText,\n getChatTitle,\n getUserFullName,\n isChatChannel,\n} from '../../modules/helpers';\nimport renderText from '../common/helpers/renderText';\nimport useLang from '../../hooks/useLang';\nimport { orderBy, pick } from '../../util/iteratees';\nimport { MEMO_EMPTY_ARRAY } from '../../util/memo';\nimport useKeyboardListNavigation from '../../hooks/useKeyboardListNavigation';\n\nimport InfiniteScroll from '../ui/InfiniteScroll';\nimport ListItem from '../ui/ListItem';\nimport LastMessageMeta from '../common/LastMessageMeta';\nimport Avatar from '../common/Avatar';\n\nimport './RightSearch.scss';\n\nexport type OwnProps = {\n chatId: number;\n threadId: number;\n};\n\ntype StateProps = {\n chat?: ApiChat;\n messagesById?: Record<number, ApiMessage>;\n query?: string;\n totalCount?: number;\n foundIds?: number[];\n};\n\ntype DispatchProps = Pick<GlobalActions, 'searchTextMessagesLocal' | 'focusMessage'>;\n\ninterface Result {\n message: ApiMessage;\n senderUser?: ApiUser;\n senderChat?: ApiChat;\n onClick: NoneToVoidFunction;\n}\n\nconst RightSearch: FC<OwnProps & StateProps & DispatchProps> = ({\n chatId,\n threadId,\n chat,\n messagesById,\n query,\n totalCount,\n foundIds,\n searchTextMessagesLocal,\n focusMessage,\n}) => {\n const lang = useLang();\n\n const foundResults = useMemo(() => {\n if (!query || !foundIds || !foundIds.length || !messagesById) {\n return MEMO_EMPTY_ARRAY;\n }\n\n const results = foundIds.map((id) => {\n const message = messagesById[id];\n if (!message) {\n return undefined;\n }\n\n const senderUser = message.senderId ? selectUser(getGlobal(), message.senderId) : undefined;\n\n let senderChat;\n if (chat && isChatChannel(chat)) {\n senderChat = chat;\n } else if (message.forwardInfo) {\n const { isChannelPost, fromChatId } = message.forwardInfo;\n senderChat = isChannelPost && fromChatId ? selectChat(getGlobal(), fromChatId) : undefined;\n } else {\n senderChat = message.senderId ? selectChat(getGlobal(), message.senderId) : undefined;\n }\n\n return {\n message,\n senderUser,\n senderChat,\n onClick: () => focusMessage({ chatId, threadId, messageId: id }),\n };\n }).filter(Boolean) as Result[];\n\n return orderBy(results, ({ message }) => message.date, 'desc');\n }, [chatId, threadId, focusMessage, foundIds, chat, messagesById, query]);\n\n const renderSearchResult = ({\n message, senderUser, senderChat, onClick,\n }: Result) => {\n const title = senderChat ? getChatTitle(lang, senderChat) : getUserFullName(senderUser);\n const text = getMessageSummaryText(lang, message);\n\n return (\n <ListItem\n className=\"chat-item-clickable search-result-message m-0\"\n onClick={onClick}\n >\n <Avatar chat={senderChat} user={senderUser} />\n <div className=\"info\">\n <div className=\"title\">\n <h3 dir=\"auto\">{title && renderText(title)}</h3>\n <LastMessageMeta message={message} />\n </div>\n <div className=\"subtitle\" dir=\"auto\">\n {renderText(text, ['emoji', 'highlight'], { highlight: query })}\n </div>\n </div>\n </ListItem>\n );\n };\n\n // eslint-disable-next-line no-null/no-null\n const containerRef = useRef<HTMLDivElement>(null);\n const handleKeyDown = useKeyboardListNavigation(containerRef, true, (index) => {\n if (foundResults && foundResults[index]) {\n foundResults[index].onClick();\n }\n }, '.ListItem-button', true);\n\n return (\n <InfiniteScroll\n className=\"RightSearch custom-scroll\"\n items={foundResults}\n preloadBackwards={0}\n onLoadMore={searchTextMessagesLocal}\n noFastList\n onKeyDown={handleKeyDown}\n ref={containerRef}\n >\n <p className=\"helper-text\" dir=\"auto\">\n {!query ? (\n lang('lng_dlg_search_for_messages')\n ) : (totalCount === 0 || !foundResults.length) ? (\n lang('lng_search_no_results')\n ) : totalCount === 1 ? (\n '1 message found'\n ) : (\n `${(foundResults.length && (totalCount || foundResults.length))} messages found`\n )}\n </p>\n {foundResults.map(renderSearchResult)}\n </InfiniteScroll>\n );\n};\n\nexport default memo(withGlobal<OwnProps>(\n (global, { chatId }): StateProps => {\n const chat = selectChat(global, chatId);\n const messagesById = chat && selectChatMessages(global, chat.id);\n if (!chat || !messagesById) {\n return {};\n }\n\n const { query, results } = selectCurrentTextSearch(global) || {};\n const { totalCount, foundIds } = results || {};\n\n return {\n chat,\n messagesById,\n query,\n totalCount,\n foundIds,\n };\n },\n (global, actions): DispatchProps => pick(actions, ['searchTextMessagesLocal', 'focusMessage']),\n)(RightSearch));\n","import React, {\n FC, useEffect, memo, useMemo, useCallback,\n} from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { ApiStickerSet } from '../../api/types';\nimport { GlobalActions } from '../../global/types';\nimport { ObserveFn } from '../../hooks/useIntersectionObserver';\n\nimport { STICKER_SIZE_SEARCH } from '../../config';\nimport { pick } from '../../util/iteratees';\nimport { selectShouldLoopStickers, selectStickerSet } from '../../modules/selectors';\nimport useFlag from '../../hooks/useFlag';\nimport useOnChange from '../../hooks/useOnChange';\nimport useLang from '../../hooks/useLang';\n\nimport Button from '../ui/Button';\nimport StickerButton from '../common/StickerButton';\nimport StickerSetModal from '../common/StickerSetModal.async';\nimport Spinner from '../ui/Spinner';\n\ntype OwnProps = {\n stickerSetId: string;\n observeIntersection: ObserveFn;\n isSomeModalOpen: boolean;\n onModalToggle: (isOpen: boolean) => void;\n};\n\ntype StateProps = {\n set?: ApiStickerSet;\n shouldPlay?: boolean;\n};\n\ntype DispatchProps = Pick<GlobalActions, 'loadStickers' | 'toggleStickerSet'>;\n\nconst STICKERS_TO_DISPLAY = 5;\n\nconst StickerSetResult: FC<OwnProps & StateProps & DispatchProps> = ({\n stickerSetId, observeIntersection, set, shouldPlay,\n loadStickers, toggleStickerSet, isSomeModalOpen, onModalToggle,\n}) => {\n const lang = useLang();\n const isAdded = set && Boolean(set.installedDate);\n const areStickersLoaded = Boolean(set && set.stickers);\n\n const [isModalOpen, openModal, closeModal] = useFlag();\n\n useOnChange(() => {\n onModalToggle(isModalOpen);\n }, [isModalOpen, onModalToggle]);\n\n const displayedStickers = useMemo(() => {\n if (!set) {\n return [];\n }\n\n const coverStickerIds = (set.covers || []).map(({ id }) => id);\n const otherStickers = set.stickers ? set.stickers.filter(({ id }) => !coverStickerIds.includes(id)) : [];\n\n return [...set.covers || [], ...otherStickers].slice(0, STICKERS_TO_DISPLAY);\n }, [set]);\n\n useEffect(() => {\n // Featured stickers are initialized with one sticker in collection (cover of SickerSet)\n if (!areStickersLoaded && displayedStickers.length < STICKERS_TO_DISPLAY) {\n loadStickers({ stickerSetId });\n }\n }, [areStickersLoaded, displayedStickers.length, loadStickers, stickerSetId]);\n\n const handleAddClick = useCallback(() => {\n toggleStickerSet({ stickerSetId });\n }, [toggleStickerSet, stickerSetId]);\n\n if (!set) {\n return undefined;\n }\n\n const canRenderStickers = displayedStickers.length > 0;\n\n return (\n <div key={set.id} className=\"sticker-set\" dir={lang.isRtl ? 'rtl' : undefined}>\n <div className=\"sticker-set-header\">\n <div className=\"title-wrapper\">\n <h3 className=\"title\" dir=\"auto\">{set.title}</h3>\n <p className=\"count\" dir=\"auto\">{lang('Stickers', set.count, 'i')}</p>\n </div>\n <Button\n className={isAdded ? 'is-added' : undefined}\n color=\"primary\"\n size=\"tiny\"\n pill\n fluid\n onClick={handleAddClick}\n >\n {lang(isAdded ? 'Stickers.Installed' : 'Stickers.Install')}\n </Button>\n </div>\n <div className=\"sticker-set-main\">\n {!canRenderStickers && <Spinner />}\n {canRenderStickers && displayedStickers.map((sticker) => (\n <StickerButton\n sticker={sticker}\n size={STICKER_SIZE_SEARCH}\n observeIntersection={observeIntersection}\n noAnimate={!shouldPlay || isModalOpen || isSomeModalOpen}\n onClick={openModal}\n />\n ))}\n </div>\n {canRenderStickers && (\n <StickerSetModal\n isOpen={isModalOpen}\n fromSticker={displayedStickers[0]}\n onClose={closeModal}\n />\n )}\n </div>\n );\n};\n\nexport default memo(withGlobal<OwnProps>(\n (global, { stickerSetId }): StateProps => {\n return {\n set: selectStickerSet(global, stickerSetId),\n shouldPlay: selectShouldLoopStickers(global),\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, ['loadStickers', 'toggleStickerSet']),\n)(StickerSetResult));\n","import React, {\n FC, memo, useEffect, useRef, useState,\n} from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../global/types';\n\nimport { pick } from '../../util/iteratees';\nimport { throttle } from '../../util/schedulers';\nimport { selectCurrentStickerSearch } from '../../modules/selectors';\nimport { useIntersectionObserver } from '../../hooks/useIntersectionObserver';\nimport useLang from '../../hooks/useLang';\n\nimport Loading from '../ui/Loading';\nimport StickerSetResult from './StickerSetResult';\n\nimport './StickerSearch.scss';\n\ntype StateProps = {\n query?: string;\n featuredIds?: string[];\n resultIds?: string[];\n};\n\ntype DispatchProps = Pick<GlobalActions, 'loadFeaturedStickers'>;\n\nconst INTERSECTION_THROTTLE = 200;\n\nconst runThrottled = throttle((cb) => cb(), 60000, true);\n\nconst StickerSearch: FC<StateProps & DispatchProps> = ({\n query,\n featuredIds,\n resultIds,\n loadFeaturedStickers,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const containerRef = useRef<HTMLDivElement>(null);\n\n const lang = useLang();\n\n const [isModalOpen, setIsModalOpen] = useState(false);\n\n const {\n observe: observeIntersection,\n } = useIntersectionObserver({ rootRef: containerRef, throttleMs: INTERSECTION_THROTTLE });\n\n // Due to the parent Transition, this component never gets unmounted,\n // that's why we use throttled API call on every update.\n useEffect(() => {\n runThrottled(() => {\n loadFeaturedStickers();\n });\n });\n\n function renderContent() {\n if (query === undefined) {\n return undefined;\n }\n\n if (!query && featuredIds) {\n return featuredIds.map((id) => (\n <StickerSetResult\n key={id}\n stickerSetId={id}\n observeIntersection={observeIntersection}\n isSomeModalOpen={isModalOpen}\n onModalToggle={setIsModalOpen}\n />\n ));\n }\n\n if (resultIds) {\n if (!resultIds.length) {\n return <p className=\"helper-text\" dir=\"auto\">Nothing found.</p>;\n }\n\n return resultIds.map((id) => (\n <StickerSetResult\n key={id}\n stickerSetId={id}\n observeIntersection={observeIntersection}\n isSomeModalOpen={isModalOpen}\n onModalToggle={setIsModalOpen}\n />\n ));\n }\n\n return <Loading />;\n }\n\n return (\n <div ref={containerRef} className=\"StickerSearch custom-scroll\" dir={lang.isRtl ? 'rtl' : undefined}>\n {renderContent()}\n </div>\n );\n};\n\nexport default memo(withGlobal(\n (global): StateProps => {\n const currentSearch = selectCurrentStickerSearch(global);\n const { query, resultIds } = currentSearch || {};\n const { featured } = global.stickers;\n\n return {\n query,\n featuredIds: featured.setIds,\n resultIds,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, ['loadFeaturedStickers']),\n)(StickerSearch));\n","import React, {\n FC, memo, useRef, useCallback,\n} from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../global/types';\nimport { ApiChat, ApiVideo } from '../../api/types';\n\nimport { IS_TOUCH_ENV } from '../../util/environment';\nimport {\n selectCurrentGifSearch,\n selectChat,\n selectIsChatWithBot,\n selectCurrentMessageList,\n} from '../../modules/selectors';\nimport { getAllowedAttachmentOptions } from '../../modules/helpers';\nimport { pick } from '../../util/iteratees';\nimport buildClassName from '../../util/buildClassName';\nimport { useIntersectionObserver } from '../../hooks/useIntersectionObserver';\nimport useLang from '../../hooks/useLang';\n\nimport InfiniteScroll from '../ui/InfiniteScroll';\nimport GifButton from '../common/GifButton';\nimport Loading from '../ui/Loading';\n\nimport './GifSearch.scss';\n\ntype StateProps = {\n query?: string;\n results?: ApiVideo[];\n chat?: ApiChat;\n isChatWithBot?: boolean;\n};\n\ntype DispatchProps = Pick<GlobalActions, 'searchMoreGifs' | 'sendMessage' | 'setGifSearchQuery'>;\n\nconst PRELOAD_BACKWARDS = 96; // GIF Search bot results are multiplied by 24\nconst INTERSECTION_DEBOUNCE = 300;\n\nconst GifSearch: FC<StateProps & DispatchProps> = ({\n query,\n results,\n chat,\n isChatWithBot,\n searchMoreGifs,\n sendMessage,\n setGifSearchQuery,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const containerRef = useRef<HTMLDivElement>(null);\n\n const {\n observe: observeIntersection,\n } = useIntersectionObserver({ rootRef: containerRef, debounceMs: INTERSECTION_DEBOUNCE });\n\n const { canSendGifs } = getAllowedAttachmentOptions(chat, isChatWithBot);\n\n const handleGifClick = useCallback((gif: ApiVideo) => {\n if (canSendGifs) {\n sendMessage({ gif });\n }\n\n if (IS_TOUCH_ENV) {\n setGifSearchQuery({ query: undefined });\n }\n }, [canSendGifs, sendMessage, setGifSearchQuery]);\n\n const lang = useLang();\n\n function renderContent() {\n if (query === undefined) {\n return undefined;\n }\n\n if (!results) {\n return (\n <Loading />\n );\n }\n\n if (!results.length) {\n return (\n <p className=\"helper-text\" dir=\"auto\">{lang('NoGIFsFound')}</p>\n );\n }\n\n return results.map((gif) => (\n <GifButton\n key={gif.id}\n gif={gif}\n observeIntersection={observeIntersection}\n onClick={handleGifClick}\n />\n ));\n }\n\n const hasResults = Boolean(query !== undefined && results && results.length);\n\n return (\n <div className=\"GifSearch\" dir={lang.isRtl ? 'rtl' : undefined}>\n <InfiniteScroll\n ref={containerRef}\n className={buildClassName('gif-container custom-scroll', hasResults && 'grid')}\n items={results}\n itemSelector=\".GifButton\"\n preloadBackwards={PRELOAD_BACKWARDS}\n noFastList\n onLoadMore={searchMoreGifs}\n >\n {renderContent()}\n </InfiniteScroll>\n\n </div>\n );\n};\n\nexport default memo(withGlobal(\n (global): StateProps => {\n const currentSearch = selectCurrentGifSearch(global);\n const { query, results } = currentSearch || {};\n const { chatId } = selectCurrentMessageList(global) || {};\n const chat = chatId ? selectChat(global, chatId) : undefined;\n const isChatWithBot = chat ? selectIsChatWithBot(global, chat) : undefined;\n\n return {\n query,\n results,\n chat,\n isChatWithBot,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, ['searchMoreGifs', 'sendMessage', 'setGifSearchQuery']),\n)(GifSearch));\n","import React, {\n FC, useCallback, useState, memo, useEffect,\n} from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport {\n ApiChat,\n ApiMessage,\n ApiPollAnswer,\n ApiPollResult,\n} from '../../api/types';\nimport { GlobalActions } from '../../global/types';\nimport { pick } from '../../util/iteratees';\nimport usePrevious from '../../hooks/usePrevious';\nimport useLang from '../../hooks/useLang';\n\nimport ShowMoreButton from '../ui/ShowMoreButton';\nimport Loading from '../ui/Loading';\nimport ListItem from '../ui/ListItem';\nimport PrivateChatInfo from '../common/PrivateChatInfo';\n\nimport './PollAnswerResults.scss';\n\ntype OwnProps = {\n chat: ApiChat;\n message: ApiMessage;\n answer: ApiPollAnswer;\n answerVote: ApiPollResult;\n totalVoters: number;\n};\n\ntype StateProps = {\n voters?: number[];\n offset: string;\n};\n\ntype DispatchProps = Pick<GlobalActions, 'loadPollOptionResults' | 'openChat' | 'closePollResults'>;\n\nconst INITIAL_LIMIT = 4;\nconst VIEW_MORE_LIMIT = 50;\n\nconst PollAnswerResults: FC<OwnProps & StateProps & DispatchProps> = ({\n chat,\n message,\n answer,\n answerVote,\n totalVoters,\n voters,\n offset,\n loadPollOptionResults,\n openChat,\n closePollResults,\n}) => {\n const prevVotersCount = usePrevious<number>(answerVote.votersCount);\n const [isLoading, setIsLoading] = useState<boolean>(true);\n const areVotersLoaded = Boolean(voters);\n const { option, text } = answer;\n const lang = useLang();\n\n useEffect(() => {\n // For update when new votes arrive or when the user takes back his vote\n if (!areVotersLoaded || prevVotersCount !== answerVote.votersCount) {\n loadPollOptionResults({\n chat, messageId: message.id, option, offset, limit: INITIAL_LIMIT, shouldResetVoters: true,\n });\n }\n // eslint-disable-next-line\n }, [answerVote.votersCount, areVotersLoaded]);\n\n const handleViewMoreClick = useCallback(() => {\n setIsLoading(true);\n loadPollOptionResults({\n chat, messageId: message.id, option, offset, limit: VIEW_MORE_LIMIT,\n });\n }, [chat, loadPollOptionResults, message.id, offset, option]);\n\n useEffect(() => {\n setIsLoading(false);\n }, [voters]);\n\n const handleMemberClick = useCallback((id: number) => {\n openChat({ id });\n closePollResults();\n }, [closePollResults, openChat]);\n\n function renderViewMoreButton() {\n const leftVotersCount = answerVote.votersCount - voters!.length;\n\n return answerVote.votersCount > INITIAL_LIMIT && leftVotersCount > 0 && (\n <ShowMoreButton\n count={leftVotersCount}\n itemName=\"voter\"\n isLoading={isLoading}\n onClick={handleViewMoreClick}\n />\n );\n }\n\n return (\n <div className=\"PollAnswerResults\">\n <div className=\"poll-voters\">\n {voters\n ? voters.map((id) => (\n <ListItem\n key={id}\n className=\"chat-item-clickable\"\n onClick={() => handleMemberClick(id)}\n >\n <PrivateChatInfo\n avatarSize=\"tiny\"\n userId={id}\n forceShowSelf\n noStatusOrTyping\n />\n </ListItem>\n ))\n : <Loading />}\n {voters && renderViewMoreButton()}\n </div>\n <div className=\"answer-head\" dir={lang.isRtl ? 'rtl' : undefined}>\n <span className=\"answer-title\" dir=\"auto\">{text}</span>\n <span className=\"answer-percent\" dir={lang.isRtl ? 'auto' : undefined}>\n {getPercentage(answerVote.votersCount, totalVoters)}%\n </span>\n </div>\n </div>\n );\n};\n\nfunction getPercentage(value: number, total: number) {\n return total > 0 ? ((value / total) * 100).toFixed() : 0;\n}\n\nexport default memo(withGlobal<OwnProps>(\n (global, { answer }: OwnProps): StateProps => {\n const { voters, offsets } = global.pollResults;\n\n return {\n voters: voters && voters[answer.option],\n offset: (offsets && offsets[answer.option]) || '',\n };\n },\n (global, actions): DispatchProps => pick(actions, ['loadPollOptionResults', 'openChat', 'closePollResults']),\n)(PollAnswerResults));\n","import React, { FC, memo } from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { ApiMessage, ApiChat } from '../../api/types';\nimport { selectChat, selectChatMessage } from '../../modules/selectors';\nimport { buildCollectionByKey } from '../../util/iteratees';\nimport { getMessagePoll } from '../../modules/helpers';\nimport useLang from '../../hooks/useLang';\n\nimport PollAnswerResults from './PollAnswerResults';\nimport Loading from '../ui/Loading';\n\nimport './PollResults.scss';\n\ntype StateProps = {\n chat?: ApiChat;\n message?: ApiMessage;\n lastSyncTime?: number;\n};\n\nconst PollResults: FC<StateProps> = ({\n chat,\n message,\n lastSyncTime,\n}) => {\n const lang = useLang();\n if (!message || !chat) {\n return <Loading />;\n }\n\n const { summary, results } = getMessagePoll(message)!;\n if (!results.results) {\n return undefined;\n }\n\n const resultsByOption = buildCollectionByKey(results.results, 'option');\n\n return (\n <div className=\"PollResults\" dir={lang.isRtl ? 'rtl' : undefined}>\n <h3 className=\"poll-question\" dir=\"auto\">{summary.question}</h3>\n <div className=\"poll-results-list custom-scroll\">\n {lastSyncTime && summary.answers.map((answer) => (\n <PollAnswerResults\n key={`${message.id}-${answer.option}`}\n chat={chat}\n message={message}\n answer={answer}\n answerVote={resultsByOption[answer.option]}\n totalVoters={results.totalVoters!}\n />\n ))}\n {!lastSyncTime && <Loading />}\n </div>\n </div>\n );\n};\n\nexport default memo(withGlobal(\n (global): StateProps => {\n const {\n pollResults: { chatId, messageId },\n lastSyncTime,\n } = global;\n\n if (!chatId || !messageId) {\n return {};\n }\n\n const chat = selectChat(global, chatId);\n const message = selectChatMessage(global, chatId, messageId);\n\n return {\n chat,\n message,\n lastSyncTime,\n };\n },\n)(PollResults));\n","import { ChangeEvent } from 'react';\nimport React, {\n FC, memo, useCallback, useEffect, useState,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../../global/types';\nimport { ApiChat, ApiUser } from '../../../api/types';\nimport { ManagementProgress } from '../../../types';\n\nimport { pick } from '../../../util/iteratees';\nimport { selectChat, selectUser } from '../../../modules/selectors';\nimport useFlag from '../../../hooks/useFlag';\nimport useLang from '../../../hooks/useLang';\n\nimport InputText from '../../ui/InputText';\nimport ListItem from '../../ui/ListItem';\nimport Checkbox from '../../ui/Checkbox';\nimport FloatingActionButton from '../../ui/FloatingActionButton';\nimport Spinner from '../../ui/Spinner';\nimport PrivateChatInfo from '../../common/PrivateChatInfo';\nimport ConfirmDialog from '../../ui/ConfirmDialog';\n\nimport './Management.scss';\n\ntype OwnProps = {\n userId: number;\n};\n\ntype StateProps = {\n user?: ApiUser;\n chat: ApiChat;\n progress?: ManagementProgress;\n};\n\ntype DispatchProps = Pick<GlobalActions, (\n 'updateContact' | 'deleteUser' | 'deleteHistory' | 'closeManagement' | 'openChat'\n)>;\n\nconst ERROR_FIRST_NAME_MISSING = 'Please provide first name';\n\nconst ManageUser: FC<OwnProps & StateProps & DispatchProps> = ({\n userId,\n user,\n chat,\n progress,\n updateContact,\n deleteUser,\n deleteHistory,\n closeManagement,\n openChat,\n}) => {\n const [isDeleteDialogOpen, openDeleteDialog, closeDeleteDialog] = useFlag();\n const [isProfileFieldsTouched, setIsProfileFieldsTouched] = useState(false);\n const [error, setError] = useState<string | undefined>();\n const lang = useLang();\n\n const currentFirstName = user ? (user.firstName || '') : '';\n const currentLastName = user ? (user.lastName || '') : '';\n const currentIsMuted = chat ? chat.isMuted : undefined;\n\n const [firstName, setFirstName] = useState(currentFirstName);\n const [lastName, setLastName] = useState(currentLastName);\n const [isNotificationsEnabled, setIsNotificationsEnabled] = useState(!currentIsMuted);\n\n useEffect(() => {\n setIsNotificationsEnabled(!currentIsMuted);\n }, [currentIsMuted]);\n\n useEffect(() => {\n setIsProfileFieldsTouched(false);\n closeDeleteDialog();\n }, [closeDeleteDialog, userId]);\n\n useEffect(() => {\n setFirstName(currentFirstName);\n setLastName(currentLastName);\n }, [currentFirstName, currentLastName, user]);\n\n useEffect(() => {\n if (progress === ManagementProgress.Complete) {\n setIsProfileFieldsTouched(false);\n setError(undefined);\n closeDeleteDialog();\n }\n }, [closeDeleteDialog, progress]);\n\n const handleFirstNameChange = useCallback((e: ChangeEvent<HTMLInputElement>) => {\n setFirstName(e.target.value);\n setIsProfileFieldsTouched(true);\n }, []);\n\n const handleLastNameChange = useCallback((e: ChangeEvent<HTMLInputElement>) => {\n setLastName(e.target.value);\n setIsProfileFieldsTouched(true);\n }, []);\n\n const handleNotificationChange = useCallback((e: ChangeEvent<HTMLInputElement>) => {\n setIsNotificationsEnabled(e.target.checked);\n setIsProfileFieldsTouched(true);\n }, []);\n\n const handleProfileSave = useCallback(() => {\n const trimmedFirstName = firstName.trim();\n const trimmedLastName = lastName.trim();\n\n if (!trimmedFirstName.length) {\n setError(ERROR_FIRST_NAME_MISSING);\n }\n\n updateContact({\n userId,\n isMuted: !isNotificationsEnabled,\n firstName: trimmedFirstName,\n lastName: trimmedLastName,\n });\n }, [firstName, lastName, updateContact, userId, isNotificationsEnabled]);\n\n const handleDeleteContact = useCallback(() => {\n deleteHistory({\n chatId: chat.id,\n shouldDeleteForAll: false,\n });\n deleteUser({ userId });\n closeDeleteDialog();\n closeManagement();\n openChat({ id: undefined });\n }, [chat.id, closeDeleteDialog, closeManagement, deleteHistory, deleteUser, openChat, userId]);\n\n if (!user) {\n return undefined;\n }\n\n const isLoading = progress === ManagementProgress.InProgress;\n\n return (\n <div className=\"Management\">\n <div className=\"custom-scroll\">\n <div className=\"section\">\n <PrivateChatInfo\n userId={user.id}\n avatarSize=\"jumbo\"\n status=\"original name\"\n withFullInfo\n />\n <InputText\n id=\"user-first-name\"\n label={lang('UserInfo.FirstNamePlaceholder')}\n onChange={handleFirstNameChange}\n value={firstName}\n error={error === ERROR_FIRST_NAME_MISSING ? error : undefined}\n />\n <InputText\n id=\"user-last-name\"\n label={lang('UserInfo.LastNamePlaceholder')}\n onChange={handleLastNameChange}\n value={lastName}\n />\n <div className=\"ListItem no-selection narrow\">\n <Checkbox\n checked={isNotificationsEnabled}\n label={lang('Notifications')}\n subLabel={lang(isNotificationsEnabled\n ? 'UserInfo.NotificationsEnabled'\n : 'UserInfo.NotificationsDisabled')}\n onChange={handleNotificationChange}\n />\n </div>\n </div>\n <div className=\"section\">\n <ListItem icon=\"delete\" ripple destructive onClick={openDeleteDialog}>\n {lang('DeleteContact')}\n </ListItem>\n </div>\n </div>\n <FloatingActionButton\n isShown={isProfileFieldsTouched}\n onClick={handleProfileSave}\n disabled={isLoading}\n ariaLabel={lang('Save')}\n >\n {isLoading ? (\n <Spinner color=\"white\" />\n ) : (\n <i className=\"icon-check\" />\n )}\n </FloatingActionButton>\n <ConfirmDialog\n isOpen={isDeleteDialogOpen}\n onClose={closeDeleteDialog}\n text={lang('AreYouSureDeleteContact')}\n confirmLabel={lang('DeleteContact')}\n confirmHandler={handleDeleteContact}\n confirmIsDestructive\n />\n </div>\n );\n};\n\nexport default memo(withGlobal<OwnProps>(\n (global, { userId }): StateProps => {\n const user = selectUser(global, userId);\n const chat = selectChat(global, userId)!;\n const { progress } = global.management;\n\n return {\n user, chat, progress,\n };\n },\n (global, actions): DispatchProps => pick(actions, [\n 'updateContact', 'deleteUser', 'closeManagement', 'openChat', 'deleteHistory',\n ]),\n)(ManageUser));\n","import { ChangeEvent } from 'react';\nimport React, {\n FC, memo, useCallback, useEffect, useMemo, useState,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { ManagementScreens, ManagementProgress } from '../../../types';\nimport { ApiChat, ApiChatBannedRights, ApiMediaFormat } from '../../../api/types';\nimport { GlobalActions } from '../../../global/types';\n\nimport { getChatAvatarHash, getHasAdminRight, isChatBasicGroup } from '../../../modules/helpers';\nimport useMedia from '../../../hooks/useMedia';\nimport useLang from '../../../hooks/useLang';\nimport useFlag from '../../../hooks/useFlag';\nimport { selectChat } from '../../../modules/selectors';\nimport { formatInteger } from '../../../util/textFormat';\nimport { pick } from '../../../util/iteratees';\nimport renderText from '../../common/helpers/renderText';\n\nimport AvatarEditable from '../../ui/AvatarEditable';\nimport InputText from '../../ui/InputText';\nimport ListItem from '../../ui/ListItem';\nimport Checkbox from '../../ui/Checkbox';\nimport Spinner from '../../ui/Spinner';\nimport FloatingActionButton from '../../ui/FloatingActionButton';\nimport ConfirmDialog from '../../ui/ConfirmDialog';\n\nimport './Management.scss';\n\ntype OwnProps = {\n chatId: number;\n onScreenSelect: (screen: ManagementScreens) => void;\n};\n\ntype StateProps = {\n chat: ApiChat;\n progress?: ManagementProgress;\n isBasicGroup: boolean;\n hasLinkedChannel: boolean;\n canChangeInfo?: boolean;\n canBanUsers?: boolean;\n};\n\ntype DispatchProps = Pick<GlobalActions, (\n 'togglePreHistoryHidden' | 'updateChat' | 'closeManagement' |\n 'deleteHistory' | 'leaveChannel' | 'deleteChannel' | 'openChat'\n)>;\n\nconst GROUP_TITLE_EMPTY = 'Group title can\\'t be empty';\n\n// Some checkboxes control multiple rights, and some rights are not controlled from Permissions screen,\n// so we need to define the amount manually\nconst TOTAL_PERMISSIONS_COUNT = 8;\n\nconst ManageGroup: FC<OwnProps & StateProps & DispatchProps> = ({\n chatId,\n chat,\n progress,\n isBasicGroup,\n hasLinkedChannel,\n canChangeInfo,\n canBanUsers,\n onScreenSelect,\n togglePreHistoryHidden,\n updateChat,\n deleteHistory,\n leaveChannel,\n deleteChannel,\n closeManagement,\n openChat,\n}) => {\n const [isDeleteDialogOpen, openDeleteDialog, closeDeleteDialog] = useFlag();\n const currentTitle = chat.title;\n const currentAbout = chat.fullInfo ? (chat.fullInfo.about || '') : '';\n\n const [isProfileFieldsTouched, setIsProfileFieldsTouched] = useState(false);\n const [title, setTitle] = useState(currentTitle);\n const [about, setAbout] = useState(currentAbout);\n const [photo, setPhoto] = useState<File | undefined>();\n const [error, setError] = useState<string | undefined>();\n const imageHash = getChatAvatarHash(chat);\n const currentAvatarBlobUrl = useMedia(imageHash, false, ApiMediaFormat.BlobUrl);\n const lang = useLang();\n\n useEffect(() => {\n if (progress === ManagementProgress.Complete) {\n setIsProfileFieldsTouched(false);\n setError(undefined);\n }\n }, [progress]);\n\n const handleClickEditType = useCallback(() => {\n onScreenSelect(ManagementScreens.ChatPrivacyType);\n }, [onScreenSelect]);\n\n const handleClickDiscussion = useCallback(() => {\n onScreenSelect(ManagementScreens.Discussion);\n }, [onScreenSelect]);\n\n const handleClickPermissions = useCallback(() => {\n onScreenSelect(ManagementScreens.GroupPermissions);\n }, [onScreenSelect]);\n\n const handleClickAdministrators = useCallback(() => {\n onScreenSelect(ManagementScreens.ChatAdministrators);\n }, [onScreenSelect]);\n\n const handleSetPhoto = useCallback((file: File) => {\n setPhoto(file);\n setIsProfileFieldsTouched(true);\n }, []);\n\n const handleTitleChange = useCallback((e: ChangeEvent<HTMLInputElement>) => {\n setTitle(e.target.value);\n setIsProfileFieldsTouched(true);\n }, []);\n\n const handleAboutChange = useCallback((e: ChangeEvent<HTMLInputElement>) => {\n setAbout(e.target.value);\n setIsProfileFieldsTouched(true);\n }, []);\n\n const handleUpdateGroup = useCallback(() => {\n const trimmedTitle = title.trim();\n const trimmedAbout = about.trim();\n\n if (!trimmedTitle.length) {\n setError(GROUP_TITLE_EMPTY);\n return;\n }\n\n updateChat({\n chatId,\n title: trimmedTitle,\n about: trimmedAbout,\n photo,\n });\n }, [about, chatId, photo, title, updateChat]);\n\n const handleClickMembers = useCallback(() => {\n onScreenSelect(ManagementScreens.GroupMembers);\n }, [onScreenSelect]);\n\n const handleTogglePreHistory = useCallback(() => {\n if (!chat.fullInfo) {\n return;\n }\n\n const { isPreHistoryHidden } = chat.fullInfo;\n\n togglePreHistoryHidden({ chatId: chat.id, isEnabled: !isPreHistoryHidden });\n }, [chat, togglePreHistoryHidden]);\n\n const enabledPermissionsCount = useMemo(() => {\n if (!chat.defaultBannedRights) {\n return 0;\n }\n\n let totalCount = [\n 'sendMessages',\n 'sendMedia',\n 'embedLinks',\n 'sendPolls',\n 'changeInfo',\n 'inviteUsers',\n 'pinMessages',\n ].filter(\n (key) => !chat.defaultBannedRights![key as keyof ApiChatBannedRights],\n ).length;\n\n const { sendStickers, sendGifs } = chat.defaultBannedRights;\n\n // These two rights are controlled with a single checkbox\n if (!sendStickers && !sendGifs) {\n totalCount += 1;\n }\n\n return totalCount;\n }, [chat]);\n\n const adminsCount = (chat.fullInfo && chat.fullInfo.adminMembers && chat.fullInfo.adminMembers.length) || 0;\n\n const handleDeleteGroup = useCallback(() => {\n if (isBasicGroup) {\n deleteHistory({ chatId: chat.id, shouldDeleteForAll: false });\n } else if (!chat.isCreator) {\n leaveChannel({ chatId: chat.id });\n } else {\n deleteChannel({ chatId: chat.id });\n }\n closeDeleteDialog();\n closeManagement();\n openChat({ id: undefined });\n }, [\n isBasicGroup, chat.isCreator, chat.id,\n closeDeleteDialog, closeManagement, deleteHistory, leaveChannel, deleteChannel, openChat,\n ]);\n\n if (chat.isRestricted) {\n return undefined;\n }\n\n const isLoading = progress === ManagementProgress.InProgress;\n\n return (\n <div className=\"Management\">\n <div className=\"custom-scroll\">\n <div className=\"section\">\n <AvatarEditable\n currentAvatarBlobUrl={currentAvatarBlobUrl}\n onChange={handleSetPhoto}\n disabled={!canChangeInfo}\n />\n <InputText\n id=\"group-title\"\n label={lang('GroupName')}\n onChange={handleTitleChange}\n value={title}\n error={error === GROUP_TITLE_EMPTY ? error : undefined}\n disabled={!canChangeInfo}\n />\n <InputText\n id=\"group-about\"\n className=\"mb-2\"\n label={lang('DescriptionPlaceholder')}\n onChange={handleAboutChange}\n value={about}\n disabled={!canChangeInfo}\n />\n {chat.isCreator && (\n <ListItem icon=\"lock\" multiline ripple onClick={handleClickEditType}>\n <span className=\"title\">{lang('GroupType')}</span>\n <span className=\"subtitle\">{chat.username ? lang('TypePublic') : lang('TypePrivate')}</span>\n </ListItem>\n )}\n {hasLinkedChannel && (\n <ListItem icon=\"message\" multiline ripple onClick={handleClickDiscussion}>\n <span className=\"title\">{lang('LinkedChannel')}</span>\n <span className=\"subtitle\">{lang('DiscussionUnlink')}</span>\n </ListItem>\n )}\n <ListItem\n icon=\"permissions\"\n multiline\n ripple\n onClick={handleClickPermissions}\n disabled={!canBanUsers}\n >\n <span className=\"title\">{lang('ChannelPermissions')}</span>\n <span className=\"subtitle\" dir=\"auto\">\n {enabledPermissionsCount}/{TOTAL_PERMISSIONS_COUNT}\n </span>\n </ListItem>\n <ListItem icon=\"admin\" multiline ripple onClick={handleClickAdministrators}>\n <span className=\"title\">{lang('ChannelAdministrators')}</span>\n <span className=\"subtitle\">{formatInteger(adminsCount)}</span>\n </ListItem>\n </div>\n <div className=\"section\">\n <ListItem icon=\"group\" multiline ripple onClick={handleClickMembers}>\n <span className=\"title\">{lang('GroupMembers')}</span>\n <span className=\"subtitle\">{formatInteger(chat.membersCount!)}</span>\n </ListItem>\n\n {chat.fullInfo && (\n <div className=\"ListItem narrow no-selection\">\n <Checkbox\n checked={!chat.fullInfo.isPreHistoryHidden}\n label={lang('ChatHistory')}\n onChange={handleTogglePreHistory}\n disabled={!canBanUsers}\n />\n </div>\n )}\n </div>\n <div className=\"section\">\n <ListItem icon=\"delete\" ripple destructive onClick={openDeleteDialog}>\n {lang('DeleteMega')}\n </ListItem>\n </div>\n </div>\n <FloatingActionButton\n isShown={isProfileFieldsTouched}\n onClick={handleUpdateGroup}\n disabled={isLoading}\n ariaLabel={lang('Save')}\n >\n {isLoading ? (\n <Spinner color=\"white\" />\n ) : (\n <i className=\"icon-check\" />\n )}\n </FloatingActionButton>\n <ConfirmDialog\n isOpen={isDeleteDialogOpen}\n onClose={closeDeleteDialog}\n textParts={renderText(\n isBasicGroup || !chat.isCreator\n ? lang('AreYouSureDeleteAndExit')\n : lang('AreYouSureDeleteThisChatWithGroup', chat.title),\n ['br', 'simple_markdown'],\n )}\n confirmLabel={isBasicGroup || !chat.isCreator ? lang('DeleteMega') : lang('DeleteGroupForAll')}\n confirmHandler={handleDeleteGroup}\n confirmIsDestructive\n />\n </div>\n );\n};\n\nexport default memo(withGlobal<OwnProps>(\n (global, { chatId }): StateProps => {\n const chat = selectChat(global, chatId)!;\n const { progress } = global.management;\n const hasLinkedChannel = Boolean(chat.fullInfo && chat.fullInfo.linkedChatId);\n\n return {\n chat,\n progress,\n isBasicGroup: isChatBasicGroup(chat),\n hasLinkedChannel,\n canChangeInfo: getHasAdminRight(chat, 'changeInfo'),\n canBanUsers: getHasAdminRight(chat, 'banUsers'),\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'togglePreHistoryHidden', 'updateChat', 'closeManagement',\n 'deleteHistory', 'leaveChannel', 'deleteChannel', 'openChat',\n ]),\n)(ManageGroup));\n","import React, {\n FC, memo, useCallback, useEffect, useMemo, useState,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { ManagementScreens } from '../../../types';\nimport { ApiChat, ApiChatBannedRights, ApiChatMember } from '../../../api/types';\nimport { GlobalActions } from '../../../global/types';\n\nimport useLang from '../../../hooks/useLang';\nimport { selectChat } from '../../../modules/selectors';\nimport { pick } from '../../../util/iteratees';\n\nimport ListItem from '../../ui/ListItem';\nimport Checkbox from '../../ui/Checkbox';\nimport FloatingActionButton from '../../ui/FloatingActionButton';\nimport Spinner from '../../ui/Spinner';\nimport PrivateChatInfo from '../../common/PrivateChatInfo';\n\ntype OwnProps = {\n chatId: number;\n onScreenSelect: (screen: ManagementScreens) => void;\n onChatMemberSelect: (memberId: number, isPromotedByCurrentUser?: boolean) => void;\n};\n\ntype StateProps = {\n chat?: ApiChat;\n currentUserId?: number;\n};\n\ntype DispatchProps = Pick<GlobalActions, 'updateChatDefaultBannedRights'>;\n\nconst FLOATING_BUTTON_ANIMATION_TIMEOUT_MS = 250;\n\nfunction getLangKeyForBannedRightKey(key: string) {\n switch (key) {\n case 'sendMessages':\n return 'UserRestrictionsNoSend';\n case 'sendMedia':\n return 'UserRestrictionsNoSendMedia';\n case 'sendStickers':\n return 'UserRestrictionsNoSendStickers';\n case 'embedLinks':\n return 'UserRestrictionsNoEmbedLinks';\n case 'sendPolls':\n return 'UserRestrictionsNoSendPolls';\n case 'changeInfo':\n return 'UserRestrictionsNoChangeInfo';\n case 'inviteUsers':\n return 'UserRestrictionsInviteUsers';\n case 'pinMessages':\n return 'UserRestrictionsPinMessages';\n default:\n return undefined;\n }\n}\n\nconst ManageGroupPermissions: FC<OwnProps & StateProps & DispatchProps> = ({\n onScreenSelect,\n onChatMemberSelect,\n chat,\n currentUserId,\n updateChatDefaultBannedRights,\n}) => {\n const [permissions, setPermissions] = useState<ApiChatBannedRights>({});\n const [havePermissionChanged, setHavePermissionChanged] = useState(false);\n const [isLoading, setIsLoading] = useState(false);\n const lang = useLang();\n\n const handleRemovedUsersClick = useCallback(() => {\n onScreenSelect(ManagementScreens.GroupRemovedUsers);\n }, [onScreenSelect]);\n\n const handleAddExceptionClick = useCallback(() => {\n onScreenSelect(ManagementScreens.GroupUserPermissionsCreate);\n }, [onScreenSelect]);\n\n const handleExceptionMemberClick = useCallback((member: ApiChatMember) => {\n onChatMemberSelect(member.userId, member.promotedByUserId === currentUserId);\n onScreenSelect(ManagementScreens.GroupUserPermissions);\n }, [currentUserId, onChatMemberSelect, onScreenSelect]);\n\n useEffect(() => {\n setPermissions((chat && chat.defaultBannedRights) || {});\n setHavePermissionChanged(false);\n setTimeout(() => {\n setIsLoading(false);\n }, FLOATING_BUTTON_ANIMATION_TIMEOUT_MS);\n }, [chat]);\n\n const handlePermissionChange = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {\n const { name } = e.target;\n\n function getUpdatedPermissionValue(value: true | undefined) {\n return value ? undefined : true;\n }\n\n setPermissions((p) => ({\n ...p,\n [name]: getUpdatedPermissionValue(p[name as keyof ApiChatBannedRights]),\n ...(name === 'sendStickers' && {\n sendGifs: getUpdatedPermissionValue(p[name]),\n }),\n }));\n setHavePermissionChanged(true);\n }, []);\n\n const handleSavePermissions = useCallback(() => {\n if (!chat) {\n return;\n }\n\n setIsLoading(true);\n updateChatDefaultBannedRights({ chatId: chat.id, bannedRights: permissions });\n }, [chat, permissions, updateChatDefaultBannedRights]);\n\n const removedUsersCount = useMemo(() => {\n if (!chat || !chat.fullInfo || !chat.fullInfo.kickedMembers) {\n return 0;\n }\n\n return chat.fullInfo.kickedMembers.length;\n }, [chat]);\n\n const exceptionMembers = useMemo(() => {\n if (!chat || !chat.fullInfo || !chat.fullInfo.members) {\n return [];\n }\n\n return chat.fullInfo.members.filter(({ bannedRights }) => !!bannedRights);\n }, [chat]);\n\n const getMemberExceptions = useCallback((member: ApiChatMember) => {\n const { bannedRights } = member;\n if (!bannedRights || !chat) {\n return undefined;\n }\n\n const { defaultBannedRights } = chat;\n\n return Object.keys(bannedRights).reduce((result, key) => {\n if (\n !bannedRights[key as keyof ApiChatBannedRights]\n || (defaultBannedRights && defaultBannedRights[key as keyof ApiChatBannedRights])\n || key === 'sendInline' || key === 'viewMessages' || key === 'sendGames'\n ) {\n return result;\n }\n\n const langKey = getLangKeyForBannedRightKey(key);\n\n if (!langKey) {\n return result;\n }\n\n const translatedString = lang(langKey);\n\n return `${result}${!result.length ? translatedString : `, ${translatedString}`}`;\n }, '');\n }, [chat, lang]);\n\n return (\n <div className=\"Management\">\n <div className=\"custom-scroll\">\n <div className=\"section\">\n <h3 className=\"section-heading\" dir=\"auto\">{lang('ChannelPermissionsHeader')}</h3>\n\n <div className=\"ListItem no-selection\">\n <Checkbox\n name=\"sendMessages\"\n checked={!permissions.sendMessages}\n label={lang('UserRestrictionsSend')}\n blocking\n onChange={handlePermissionChange}\n />\n </div>\n <div className=\"ListItem no-selection\">\n <Checkbox\n name=\"sendMedia\"\n checked={!permissions.sendMedia}\n label={lang('UserRestrictionsSendMedia')}\n blocking\n onChange={handlePermissionChange}\n />\n </div>\n <div className=\"ListItem no-selection\">\n <Checkbox\n name=\"sendStickers\"\n checked={!permissions.sendStickers && !permissions.sendGifs}\n label={lang('UserRestrictionsSendStickers')}\n blocking\n onChange={handlePermissionChange}\n />\n </div>\n <div className=\"ListItem no-selection\">\n <Checkbox\n name=\"sendPolls\"\n checked={!permissions.sendPolls}\n label={lang('UserRestrictionsSendPolls')}\n blocking\n onChange={handlePermissionChange}\n />\n </div>\n <div className=\"ListItem no-selection\">\n <Checkbox\n name=\"embedLinks\"\n checked={!permissions.embedLinks}\n label={lang('UserRestrictionsEmbedLinks')}\n blocking\n onChange={handlePermissionChange}\n />\n </div>\n <div className=\"ListItem no-selection\">\n <Checkbox\n name=\"inviteUsers\"\n checked={!permissions.inviteUsers}\n label={lang('UserRestrictionsInviteUsers')}\n blocking\n onChange={handlePermissionChange}\n />\n </div>\n <div className=\"ListItem no-selection\">\n <Checkbox\n name=\"pinMessages\"\n checked={!permissions.pinMessages}\n label={lang('UserRestrictionsPinMessages')}\n blocking\n onChange={handlePermissionChange}\n />\n </div>\n <div className=\"ListItem no-selection\">\n <Checkbox\n name=\"changeInfo\"\n checked={!permissions.changeInfo}\n label={lang('UserRestrictionsChangeInfo')}\n blocking\n onChange={handlePermissionChange}\n />\n </div>\n </div>\n\n <div className=\"section\">\n <ListItem icon=\"delete-user\" multiline ripple narrow onClick={handleRemovedUsersClick}>\n <span className=\"title\">{lang('ChannelBlockedUsers')}</span>\n <span className=\"subtitle\">{removedUsersCount}</span>\n </ListItem>\n </div>\n\n <div className=\"section\">\n <h3 className=\"section-heading\" dir=\"auto\">{lang('PrivacyExceptions')}</h3>\n\n <ListItem\n icon=\"add-user\"\n ripple\n onClick={handleAddExceptionClick}\n >\n {lang('ChannelAddException')}\n </ListItem>\n\n {exceptionMembers.map((member) => (\n <ListItem\n key={member.userId}\n className=\"chat-item-clickable exceptions-member\"\n ripple\n onClick={() => handleExceptionMemberClick(member)}\n >\n <PrivateChatInfo\n userId={member.userId}\n status={getMemberExceptions(member)}\n />\n </ListItem>\n ))}\n </div>\n </div>\n\n <FloatingActionButton\n isShown={havePermissionChanged}\n onClick={handleSavePermissions}\n ariaLabel={lang('Save')}\n disabled={isLoading}\n >\n {isLoading ? (\n <Spinner color=\"white\" />\n ) : (\n <i className=\"icon-check\" />\n )}\n </FloatingActionButton>\n </div>\n );\n};\n\nexport default memo(withGlobal<OwnProps>(\n (global, { chatId }): StateProps => {\n const chat = selectChat(global, chatId);\n\n return { chat, currentUserId: global.currentUserId };\n },\n (setGlobal, actions): DispatchProps => pick(actions, ['updateChatDefaultBannedRights']),\n)(ManageGroupPermissions));\n","import React, {\n FC, memo, useCallback, useMemo,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { ApiChat, ApiChatMember, ApiUser } from '../../../api/types';\nimport { GlobalActions } from '../../../global/types';\n\nimport { selectChat } from '../../../modules/selectors';\nimport { getUserFullName } from '../../../modules/helpers';\nimport { pick } from '../../../util/iteratees';\nimport useLang from '../../../hooks/useLang';\n\nimport PrivateChatInfo from '../../common/PrivateChatInfo';\nimport ListItem from '../../ui/ListItem';\n\ntype OwnProps = {\n chatId: number;\n};\n\ntype StateProps = {\n chat?: ApiChat;\n usersById: Record<number, ApiUser>;\n};\n\ntype DispatchProps = Pick<GlobalActions, 'updateChatMemberBannedRights'>;\n\nconst ManageGroupRemovedUsers: FC<OwnProps & StateProps & DispatchProps> = ({\n chat,\n usersById,\n updateChatMemberBannedRights,\n}) => {\n const lang = useLang();\n\n const removedMembers = useMemo(() => {\n if (!chat || !chat.fullInfo || !chat.fullInfo.kickedMembers) {\n return [];\n }\n\n return chat.fullInfo.kickedMembers;\n }, [chat]);\n\n const getRemovedBy = useCallback((member: ApiChatMember) => {\n if (!member.kickedByUserId) {\n return undefined;\n }\n\n const kickedByUser = usersById[member.kickedByUserId];\n if (!kickedByUser) {\n return undefined;\n }\n\n return lang('UserRemovedBy', getUserFullName(kickedByUser));\n }, [lang, usersById]);\n\n const getContextActions = useCallback((member: ApiChatMember) => {\n if (!chat) {\n return undefined;\n }\n\n return [{\n title: lang('Unblock'),\n icon: 'delete',\n destructive: true,\n handler: () => updateChatMemberBannedRights({\n chatId: chat.id,\n userId: member.userId,\n bannedRights: {},\n }),\n }];\n }, [lang, chat, updateChatMemberBannedRights]);\n\n return (\n <div className=\"Management\">\n <div className=\"custom-scroll\">\n <div className=\"section\" dir={lang.isRtl ? 'rtl' : undefined}>\n <p className=\"text-muted\">{lang('NoBlockedGroup2')}</p>\n\n {removedMembers.map((member) => (\n <ListItem\n key={member.userId}\n className=\"chat-item-clickable\"\n ripple\n contextActions={getContextActions(member)}\n >\n <PrivateChatInfo\n userId={member.userId}\n status={getRemovedBy(member)}\n />\n </ListItem>\n ))}\n </div>\n </div>\n </div>\n );\n};\n\nexport default memo(withGlobal<OwnProps>(\n (global, { chatId }): StateProps => {\n const chat = selectChat(global, chatId);\n const { byId: usersById } = global.users;\n\n return { chat, usersById };\n },\n (setGlobal, actions): DispatchProps => pick(actions, ['updateChatMemberBannedRights']),\n)(ManageGroupRemovedUsers));\n","import { ChangeEvent } from 'react';\nimport React, {\n FC, memo, useCallback, useEffect, useState,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../../global/types';\nimport { ManagementScreens, ManagementProgress } from '../../../types';\nimport { ApiChat, ApiMediaFormat } from '../../../api/types';\n\nimport { pick } from '../../../util/iteratees';\nimport { getChatAvatarHash, getHasAdminRight } from '../../../modules/helpers';\nimport useMedia from '../../../hooks/useMedia';\nimport useLang from '../../../hooks/useLang';\nimport { selectChat } from '../../../modules/selectors';\n\nimport AvatarEditable from '../../ui/AvatarEditable';\nimport InputText from '../../ui/InputText';\nimport ListItem from '../../ui/ListItem';\nimport Checkbox from '../../ui/Checkbox';\nimport Spinner from '../../ui/Spinner';\nimport FloatingActionButton from '../../ui/FloatingActionButton';\nimport ConfirmDialog from '../../ui/ConfirmDialog';\nimport useFlag from '../../../hooks/useFlag';\n\nimport './Management.scss';\n\ntype OwnProps = {\n chatId: number;\n onScreenSelect: (screen: ManagementScreens) => void;\n};\n\ntype StateProps = {\n chat: ApiChat;\n progress?: ManagementProgress;\n isSignaturesShown: boolean;\n canChangeInfo?: boolean;\n};\n\ntype DispatchProps = Pick<GlobalActions, (\n 'toggleSignatures' | 'updateChat' | 'closeManagement' | 'leaveChannel' | 'deleteChannel' | 'openChat'\n)>;\n\nconst CHANNEL_TITLE_EMPTY = 'Channel title can\\'t be empty';\n\nconst ManageChannel: FC<OwnProps & StateProps & DispatchProps> = ({\n chatId,\n chat,\n progress,\n isSignaturesShown,\n canChangeInfo,\n onScreenSelect,\n updateChat,\n toggleSignatures,\n closeManagement,\n leaveChannel,\n deleteChannel,\n openChat,\n}) => {\n const currentTitle = chat ? (chat.title || '') : '';\n const currentAbout = chat && chat.fullInfo ? (chat.fullInfo.about || '') : '';\n const hasLinkedChat = chat && chat.fullInfo && chat.fullInfo.linkedChatId;\n\n const [isDeleteDialogOpen, openDeleteDialog, closeDeleteDialog] = useFlag();\n const [isProfileFieldsTouched, setIsProfileFieldsTouched] = useState(false);\n const [title, setTitle] = useState(currentTitle);\n const [about, setAbout] = useState(currentAbout);\n const [photo, setPhoto] = useState<File | undefined>();\n const [error, setError] = useState<string | undefined>();\n const imageHash = chat && getChatAvatarHash(chat);\n const currentAvatarBlobUrl = useMedia(imageHash, false, ApiMediaFormat.BlobUrl);\n const lang = useLang();\n\n useEffect(() => {\n if (progress === ManagementProgress.Complete) {\n setIsProfileFieldsTouched(false);\n setError(undefined);\n }\n }, [progress]);\n\n const adminsCount = (chat && chat.fullInfo && chat.fullInfo.adminMembers && chat.fullInfo.adminMembers.length) || 0;\n\n const handleClickEditType = useCallback(() => {\n onScreenSelect(ManagementScreens.ChatPrivacyType);\n }, [onScreenSelect]);\n\n const handleClickDiscussion = useCallback(() => {\n onScreenSelect(ManagementScreens.Discussion);\n }, [onScreenSelect]);\n\n const handleClickAdministrators = useCallback(() => {\n onScreenSelect(ManagementScreens.ChatAdministrators);\n }, [onScreenSelect]);\n\n const handleSetPhoto = useCallback((file: File) => {\n setPhoto(file);\n setIsProfileFieldsTouched(true);\n }, []);\n\n const handleTitleChange = useCallback((e: ChangeEvent<HTMLInputElement>) => {\n setTitle(e.target.value);\n setIsProfileFieldsTouched(true);\n }, []);\n\n const handleAboutChange = useCallback((e: ChangeEvent<HTMLInputElement>) => {\n setAbout(e.target.value);\n setIsProfileFieldsTouched(true);\n }, []);\n\n const handleUpdateChannel = useCallback(() => {\n const trimmedTitle = title.trim();\n const trimmedAbout = about.trim();\n\n if (!trimmedTitle.length) {\n setError(CHANNEL_TITLE_EMPTY);\n return;\n }\n\n updateChat({\n chatId,\n title: trimmedTitle,\n about: trimmedAbout,\n photo,\n });\n }, [about, chatId, photo, title, updateChat]);\n\n const handleToggleSignatures = useCallback(() => {\n toggleSignatures({ chatId, isEnabled: !isSignaturesShown });\n }, [chatId, isSignaturesShown, toggleSignatures]);\n\n const handleClickSubscribers = useCallback(() => {\n onScreenSelect(ManagementScreens.ChannelSubscribers);\n }, [onScreenSelect]);\n\n\n const handleDeleteChannel = useCallback(() => {\n if (chat.isCreator) {\n deleteChannel({ chatId: chat.id });\n } else {\n leaveChannel({ chatId: chat.id });\n }\n\n closeDeleteDialog();\n closeManagement();\n openChat({ id: undefined });\n }, [chat.isCreator, chat.id, closeDeleteDialog, closeManagement, leaveChannel, deleteChannel, openChat]);\n\n if (chat.isRestricted) {\n return undefined;\n }\n\n const isLoading = progress === ManagementProgress.InProgress;\n\n return (\n <div className=\"Management\">\n <div className=\"custom-scroll\">\n <div className=\"section\">\n <AvatarEditable\n currentAvatarBlobUrl={currentAvatarBlobUrl}\n onChange={handleSetPhoto}\n disabled={!canChangeInfo}\n />\n <InputText\n id=\"channel-title\"\n label={lang('EnterChannelName')}\n onChange={handleTitleChange}\n value={title}\n error={error === CHANNEL_TITLE_EMPTY ? error : undefined}\n disabled={!canChangeInfo}\n />\n <InputText\n id=\"channel-about\"\n className=\"mb-2\"\n label={lang('DescriptionPlaceholder')}\n onChange={handleAboutChange}\n value={about}\n disabled={!canChangeInfo}\n />\n {chat.isCreator && (\n <ListItem icon=\"lock\" ripple multiline onClick={handleClickEditType}>\n <span className=\"title\">{lang('ChannelType')}</span>\n <span className=\"subtitle\">{chat.username ? lang('TypePublic') : lang('TypePrivate')}</span>\n </ListItem>\n )}\n <ListItem icon=\"message\" multiline ripple onClick={handleClickDiscussion} disabled={!canChangeInfo}>\n <span className=\"title\">{lang('Discussion')}</span>\n <span className=\"subtitle\">{hasLinkedChat ? lang('DiscussionUnlink') : lang('Add')}</span>\n </ListItem>\n <ListItem icon=\"admin\" multiline ripple onClick={handleClickAdministrators}>\n <span className=\"title\">{lang('ChannelAdministrators')}</span>\n <span className=\"subtitle\">{adminsCount}</span>\n </ListItem>\n <div className=\"ListItem no-selection narrow\">\n <Checkbox\n checked={isSignaturesShown}\n label={lang('ChannelSignMessages')}\n onChange={handleToggleSignatures}\n />\n </div>\n </div>\n <div className=\"section\">\n <ListItem icon=\"group\" multiline ripple onClick={handleClickSubscribers}>\n <span className=\"title\" dir=\"auto\">{lang('ChannelSubscribers')}</span>\n <span className=\"subtitle\" dir=\"auto\">{lang('Subscribers', chat.membersCount!, 'i')}</span>\n </ListItem>\n </div>\n <div className=\"section\">\n <ListItem icon=\"delete\" ripple destructive onClick={openDeleteDialog}>\n {chat.isCreator ? lang('ChannelDelete') : lang('LeaveChannel')}\n </ListItem>\n </div>\n </div>\n <FloatingActionButton\n isShown={isProfileFieldsTouched}\n onClick={handleUpdateChannel}\n disabled={isLoading}\n ariaLabel={lang('Save')}\n >\n {isLoading ? (\n <Spinner color=\"white\" />\n ) : (\n <i className=\"icon-check\" />\n )}\n </FloatingActionButton>\n <ConfirmDialog\n isOpen={isDeleteDialogOpen}\n onClose={closeDeleteDialog}\n text={chat.isCreator ? lang('ChannelDeleteAlert') : lang('ChannelLeaveAlert')}\n confirmLabel={chat.isCreator ? lang('ChannelDelete') : lang('LeaveChannel')}\n confirmHandler={handleDeleteChannel}\n confirmIsDestructive\n />\n </div>\n );\n};\n\nexport default memo(withGlobal<OwnProps>(\n (global, { chatId }): StateProps => {\n const chat = selectChat(global, chatId)!;\n const { progress } = global.management;\n const isSignaturesShown = Boolean(chat && chat.isSignaturesShown);\n\n return {\n chat,\n progress,\n isSignaturesShown,\n canChangeInfo: getHasAdminRight(chat, 'changeInfo'),\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'toggleSignatures', 'updateChat', 'closeManagement', 'leaveChannel', 'deleteChannel', 'openChat',\n ]),\n)(ManageChannel));\n","import React, {\n FC, memo, useCallback, useEffect, useState,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../../global/types';\nimport { ApiChat } from '../../../api/types';\nimport { ManagementProgress } from '../../../types';\n\nimport { selectChat, selectManagement } from '../../../modules/selectors';\nimport { pick } from '../../../util/iteratees';\nimport { isChatChannel } from '../../../modules/helpers';\nimport useFlag from '../../../hooks/useFlag';\nimport useLang from '../../../hooks/useLang';\n\nimport SafeLink from '../../common/SafeLink';\nimport ListItem from '../../ui/ListItem';\nimport RadioGroup from '../../ui/RadioGroup';\nimport Loading from '../../ui/Loading';\nimport Spinner from '../../ui/Spinner';\nimport FloatingActionButton from '../../ui/FloatingActionButton';\nimport UsernameInput from '../../common/UsernameInput';\nimport ConfirmDialog from '../../ui/ConfirmDialog';\n\ntype PrivacyType = 'private' | 'public';\n\ntype OwnProps = {\n chatId: number;\n};\n\ntype StateProps = {\n chat: ApiChat;\n isChannel: boolean;\n progress?: ManagementProgress;\n isUsernameAvailable?: boolean;\n};\n\ntype DispatchProps = Pick<GlobalActions, (\n 'checkPublicLink' | 'updatePublicLink' | 'updatePrivateLink'\n)>;\n\nconst ManageChatPrivacyType: FC<OwnProps & StateProps & DispatchProps> = ({\n chat,\n isChannel,\n progress,\n isUsernameAvailable,\n checkPublicLink,\n updatePublicLink,\n updatePrivateLink,\n}) => {\n const isPublic = Boolean(chat.username);\n const privateLink = chat.fullInfo && chat.fullInfo.inviteLink;\n\n const [privacyType, setPrivacyType] = useState<PrivacyType>(isPublic ? 'public' : 'private');\n const [username, setUsername] = useState();\n const [isRevokeConfirmDialogOpen, openRevokeConfirmDialog, closeRevokeConfirmDialog] = useFlag();\n\n const canUpdate = (\n (privacyType === 'public' && username && isUsernameAvailable)\n || (privacyType === 'private' && isPublic)\n );\n\n useEffect(() => {\n if (privacyType && !privateLink) {\n updatePrivateLink();\n }\n }, [privacyType, privateLink, updatePrivateLink]);\n\n const handleOptionChange = useCallback((value: string) => {\n setPrivacyType(value as PrivacyType);\n }, []);\n\n const handleSave = useCallback(() => {\n updatePublicLink({ username: privacyType === 'public' ? username : '' });\n }, [privacyType, updatePublicLink, username]);\n\n const handleRevokePrivateLink = useCallback(() => {\n closeRevokeConfirmDialog();\n updatePrivateLink();\n }, [closeRevokeConfirmDialog, updatePrivateLink]);\n\n const lang = useLang();\n const langPrefix1 = isChannel ? 'Channel' : 'Mega';\n const langPrefix2 = isChannel ? 'Channel' : 'Group';\n\n const options = [\n { value: 'private', label: lang(`${langPrefix1}Private`), subLabel: lang(`${langPrefix1}PrivateInfo`) },\n { value: 'public', label: lang(`${langPrefix1}Public`), subLabel: lang(`${langPrefix1}PublicInfo`) },\n ];\n\n const isLoading = progress === ManagementProgress.InProgress;\n\n return (\n <div className=\"Management\">\n <div className=\"custom-scroll\">\n <div className=\"section\" dir={lang.isRtl ? 'rtl' : undefined}>\n <h3 className=\"section-heading\">{lang(`${langPrefix2}Type`)}</h3>\n <RadioGroup\n selected={privacyType}\n name=\"channel-type\"\n options={options}\n onChange={handleOptionChange}\n />\n </div>\n {privacyType === 'private' ? (\n <div className=\"section\" dir={lang.isRtl ? 'rtl' : undefined}>\n {privateLink ? (\n <>\n <SafeLink url={privateLink} className=\"group-link\" text={privateLink} />\n <p className=\"section-info\" dir={lang.isRtl ? 'rtl' : undefined}>\n {lang(`${langPrefix1}PrivateLinkHelp`)}\n </p>\n\n <ListItem icon=\"delete\" ripple destructive onClick={openRevokeConfirmDialog}>\n {lang('RevokeLink')}\n </ListItem>\n <ConfirmDialog\n isOpen={isRevokeConfirmDialogOpen}\n onClose={closeRevokeConfirmDialog}\n text={lang('RevokeAlert')}\n confirmLabel={lang('RevokeButton')}\n confirmHandler={handleRevokePrivateLink}\n confirmIsDestructive\n />\n </>\n ) : (\n <Loading />\n )}\n </div>\n ) : (\n <div className=\"section no-border\">\n <UsernameInput\n asLink\n currentUsername={chat.username}\n isLoading={isLoading}\n isUsernameAvailable={isUsernameAvailable}\n checkUsername={checkPublicLink}\n onChange={setUsername}\n />\n <p className=\"section-info\" dir=\"auto\">\n {lang(`${langPrefix2}.Username.CreatePublicLinkHelp`)}\n </p>\n </div>\n )}\n </div>\n <FloatingActionButton\n isShown={canUpdate}\n disabled={isLoading}\n ariaLabel={lang('Save')}\n onClick={handleSave}\n >\n {isLoading ? (\n <Spinner color=\"white\" />\n ) : (\n <i className=\"icon-check\" />\n )}\n </FloatingActionButton>\n </div>\n );\n};\n\nexport default memo(withGlobal<OwnProps>(\n (global, { chatId }): StateProps => {\n const chat = selectChat(global, chatId)!;\n const { isUsernameAvailable } = selectManagement(global, chatId)!;\n\n return {\n chat,\n isChannel: isChatChannel(chat),\n progress: global.management.progress,\n isUsernameAvailable,\n };\n },\n (setGlobal, actions) => pick(actions, [\n 'checkPublicLink', 'updatePublicLink', 'updatePrivateLink',\n ]),\n)(ManageChatPrivacyType));\n","import React, {\n FC, memo, useCallback, useEffect, useState,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../../global/types';\nimport { ApiChat } from '../../../api/types';\nimport { ManagementScreens } from '../../../types';\n\nimport { STICKER_SIZE_DISCUSSION_GROUPS } from '../../../config';\nimport { selectChat } from '../../../modules/selectors';\nimport { pick } from '../../../util/iteratees';\nimport getAnimationData from '../../common/helpers/animatedAssets';\nimport useLang from '../../../hooks/useLang';\n\nimport ListItem from '../../ui/ListItem';\nimport NothingFound from '../../common/NothingFound';\nimport GroupChatInfo from '../../common/GroupChatInfo';\nimport AnimatedSticker from '../../common/AnimatedSticker';\nimport ConfirmDialog from '../../ui/ConfirmDialog';\nimport useFlag from '../../../hooks/useFlag';\nimport renderText from '../../common/helpers/renderText';\nimport Avatar from '../../common/Avatar';\nimport { isChatChannel } from '../../../modules/helpers';\n\ntype OwnProps = {\n chatId: number;\n onScreenSelect: (screen: ManagementScreens) => void;\n};\n\ntype StateProps = {\n chat?: ApiChat;\n chatsByIds: Record<number, ApiChat>;\n linkedChat?: ApiChat;\n forDiscussionIds?: number[];\n isChannel?: boolean;\n};\n\ntype DispatchProps = Pick<GlobalActions, 'loadGroupsForDiscussion' | 'linkDiscussionGroup' | 'unlinkDiscussionGroup'>;\n\nconst ManageDiscussion: FC<OwnProps & StateProps & DispatchProps> = ({\n chat,\n chatId,\n chatsByIds,\n linkedChat,\n forDiscussionIds,\n isChannel,\n onScreenSelect,\n loadGroupsForDiscussion,\n linkDiscussionGroup,\n unlinkDiscussionGroup,\n}) => {\n const [linkedGroupId, setLinkedGroupId] = useState<number>();\n const [animationData, setAnimationData] = useState<Record<string, any>>();\n const [isAnimationLoaded, setIsAnimationLoaded] = useState(false);\n const handleAnimationLoad = useCallback(() => setIsAnimationLoaded(true), []);\n const [isConfirmUnlinkGroupDialogOpen, openConfirmUnlinkGroupDialog, closeConfirmUnlinkGroupDialog] = useFlag();\n const [isConfirmLinkGroupDialogOpen, openConfirmLinkGroupDialog, closeConfirmLinkGroupDialog] = useFlag();\n const lang = useLang();\n const linkedChatId = linkedChat && linkedChat.id;\n\n useEffect(() => {\n loadGroupsForDiscussion();\n }, [loadGroupsForDiscussion]);\n\n useEffect(() => {\n if (!animationData) {\n getAnimationData('DiscussionGroups').then(setAnimationData);\n }\n }, [animationData]);\n\n const handleUnlinkGroupSessions = useCallback(() => {\n closeConfirmUnlinkGroupDialog();\n unlinkDiscussionGroup({ channelId: isChannel ? chatId : linkedChatId });\n if (!isChannel) {\n onScreenSelect(ManagementScreens.Initial);\n }\n }, [closeConfirmUnlinkGroupDialog, unlinkDiscussionGroup, isChannel, chatId, linkedChatId, onScreenSelect]);\n\n const handleLinkGroupSessions = useCallback(() => {\n closeConfirmLinkGroupDialog();\n linkDiscussionGroup({ channelId: chatId, chatId: linkedGroupId });\n }, [closeConfirmLinkGroupDialog, linkDiscussionGroup, chatId, linkedGroupId]);\n\n const onDiscussionClick = (groupId: number) => {\n setLinkedGroupId(groupId);\n openConfirmLinkGroupDialog();\n };\n\n function renderUnlinkGroupHeader() {\n return (\n <div className=\"modal-header\">\n <Avatar\n size=\"tiny\"\n chat={linkedChat}\n />\n <div className=\"modal-title\">\n {lang(isChannel ? 'DiscussionUnlinkGroup' : 'DiscussionUnlinkChannel')}\n </div>\n </div>\n );\n }\n function renderLinkGroupHeader() {\n const linkedGroup = chatsByIds[linkedGroupId];\n\n if (!linkedGroup) {\n return undefined;\n }\n\n return (\n <div className=\"modal-header\">\n <Avatar\n size=\"tiny\"\n chat={linkedGroup}\n />\n <div className=\"modal-title\">\n {lang('Channel.DiscussionGroup.LinkGroup')}\n </div>\n </div>\n );\n }\n\n function renderLinkGroupConfirmText() {\n const linkedGroup = chatsByIds[linkedGroupId];\n\n if (!linkedGroup) {\n return undefined;\n }\n\n if (linkedGroup.hasPrivateLink) {\n return renderText(\n `Do you want to make **${linkedGroup.title}** the discussion board for **${chat!.title}**?`,\n ['br', 'simple_markdown'],\n );\n // return renderText(\n // lang('DiscussionLinkGroupPublicAlert', linkedChat.title, chat!.title),\n // ['br', 'simple_markdown'],\n // );\n }\n\n return renderText(\n // eslint-disable-next-line max-len\n `Do you want to make **${linkedGroup.title}** the discussion board for **${chat!.title}**?\\n\\nAnyone from the channel will be able to see messages in this group.`,\n ['br', 'simple_markdown'],\n );\n // return renderText(\n // lang('DiscussionLinkGroupPrivateAlert', linkedChat.title, chat!.title),\n // ['br', 'simple_markdown'],\n // );\n }\n\n function renderLinkedGroup() {\n return (\n <div>\n <ListItem\n className=\"chat-item-clickable\"\n inactive\n >\n <GroupChatInfo chatId={linkedChat!.id} />\n </ListItem>\n <ListItem\n icon=\"delete\"\n ripple\n destructive\n onClick={openConfirmUnlinkGroupDialog}\n >\n {lang(isChannel ? 'DiscussionUnlinkGroup' : 'DiscussionUnlinkChannel')}\n </ListItem>\n <ConfirmDialog\n isOpen={isConfirmUnlinkGroupDialogOpen}\n onClose={closeConfirmUnlinkGroupDialog}\n header={renderUnlinkGroupHeader()}\n textParts={renderText(\n lang(isChannel ? 'DiscussionUnlinkChannelAlert' : 'DiscussionUnlinkGroupAlert', linkedChat!.title),\n ['br', 'simple_markdown'],\n )}\n confirmLabel={lang(isChannel ? 'DiscussionUnlinkGroup' : 'DiscussionUnlinkChannel')}\n confirmHandler={handleUnlinkGroupSessions}\n confirmIsDestructive\n />\n </div>\n );\n }\n\n function renderDiscussionGroups() {\n return (\n <div>\n <p className=\"section-help\" dir=\"auto\">{lang('DiscussionChannelHelp')}</p>\n\n <div teactFastList>\n <ListItem\n key=\"create-group\"\n icon=\"group\"\n ripple\n teactOrderKey={0}\n className=\"not-implemented\"\n >\n {lang('DiscussionCreateGroup')}\n </ListItem>\n {forDiscussionIds ? (\n forDiscussionIds.map((id, i) => (\n <ListItem\n key={id}\n teactOrderKey={i + 1}\n className=\"chat-item-clickable scroll-item\"\n onClick={() => { onDiscussionClick(id); }}\n >\n <GroupChatInfo chatId={id} />\n </ListItem>\n ))\n ) : (\n <NothingFound key=\"nothing-found\" teactOrderKey={0} text=\"No discussion groups found\" />\n )}\n </div>\n <p className=\"mt-4 mb-0 section-help\" dir=\"auto\">{lang('DiscussionChannelHelp2')}</p>\n <ConfirmDialog\n isOpen={isConfirmLinkGroupDialogOpen}\n onClose={closeConfirmLinkGroupDialog}\n header={renderLinkGroupHeader()}\n textParts={renderLinkGroupConfirmText()}\n confirmLabel={lang('DiscussionLinkGroup')}\n confirmHandler={handleLinkGroupSessions}\n isButtonsInOneRow\n />\n </div>\n );\n }\n\n return (\n <div className=\"Management\">\n <div className=\"custom-scroll\">\n <div className=\"section\">\n <div className=\"section-icon\">\n {animationData && (\n <AnimatedSticker\n id=\"discussionGroupsDucks\"\n size={STICKER_SIZE_DISCUSSION_GROUPS}\n animationData={animationData}\n play={isAnimationLoaded}\n noLoop\n onLoad={handleAnimationLoad}\n />\n )}\n </div>\n {linkedChat && renderLinkedGroup()}\n {!linkedChat && renderDiscussionGroups()}\n </div>\n </div>\n </div>\n );\n};\n\nexport default memo(withGlobal<OwnProps>(\n (global, { chatId }): StateProps => {\n const chat = selectChat(global, chatId);\n const { forDiscussionIds, byId: chatsByIds } = global.chats;\n const linkedChat = chat && chat.fullInfo && chat.fullInfo.linkedChatId\n ? selectChat(global, chat.fullInfo.linkedChatId)\n : undefined;\n\n return {\n chat,\n chatsByIds,\n forDiscussionIds,\n linkedChat,\n isChannel: chat && isChatChannel(chat),\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'loadGroupsForDiscussion', 'linkDiscussionGroup', 'unlinkDiscussionGroup',\n ]),\n)(ManageDiscussion));\n","import React, {\n FC, memo, useCallback, useEffect, useMemo, useState,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { ApiChat, ApiChatBannedRights } from '../../../api/types';\nimport { ManagementScreens } from '../../../types';\nimport { GlobalActions } from '../../../global/types';\n\nimport { pick } from '../../../util/iteratees';\nimport { selectChat } from '../../../modules/selectors';\nimport useLang from '../../../hooks/useLang';\nimport useFlag from '../../../hooks/useFlag';\n\nimport PrivateChatInfo from '../../common/PrivateChatInfo';\nimport ListItem from '../../ui/ListItem';\nimport Checkbox from '../../ui/Checkbox';\nimport FloatingActionButton from '../../ui/FloatingActionButton';\nimport Spinner from '../../ui/Spinner';\nimport ConfirmDialog from '../../ui/ConfirmDialog';\n\ntype OwnProps = {\n chatId: number;\n selectedChatMemberId?: number;\n isPromotedByCurrentUser?: boolean;\n onScreenSelect: (screen: ManagementScreens) => void;\n};\n\ntype StateProps = {\n chat?: ApiChat;\n isFormFullyDisabled?: boolean;\n};\n\ntype DispatchProps = Pick<GlobalActions, 'updateChatMemberBannedRights'>;\n\nconst ManageGroupUserPermissions: FC<OwnProps & StateProps & DispatchProps> = ({\n chat,\n selectedChatMemberId,\n onScreenSelect,\n updateChatMemberBannedRights,\n isFormFullyDisabled,\n}) => {\n const [permissions, setPermissions] = useState<ApiChatBannedRights>({});\n const [havePermissionChanged, setHavePermissionChanged] = useState(false);\n const [isLoading, setIsLoading] = useState(false);\n const [isBanConfirmationDialogOpen, openBanConfirmationDialog, closeBanConfirmationDialog] = useFlag();\n const lang = useLang();\n\n const selectedChatMember = useMemo(() => {\n if (!chat || !chat.fullInfo || !chat.fullInfo.members) {\n return undefined;\n }\n\n return chat.fullInfo.members.find(({ userId }) => userId === selectedChatMemberId);\n }, [chat, selectedChatMemberId]);\n\n useEffect(() => {\n if (chat && chat.fullInfo && selectedChatMemberId && !selectedChatMember) {\n onScreenSelect(ManagementScreens.GroupPermissions);\n }\n }, [chat, onScreenSelect, selectedChatMember, selectedChatMemberId]);\n\n useEffect(() => {\n setPermissions((selectedChatMember && selectedChatMember.bannedRights) || (chat && chat.defaultBannedRights) || {});\n setHavePermissionChanged(false);\n setIsLoading(false);\n }, [chat, selectedChatMember]);\n\n const handlePermissionChange = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {\n const { name } = e.target;\n\n function getUpdatedPermissionValue(value: true | undefined) {\n return value ? undefined : true;\n }\n\n setPermissions((p) => ({\n ...p,\n [name]: getUpdatedPermissionValue(p[name as keyof ApiChatBannedRights]),\n ...(name === 'sendStickers' && {\n sendGifs: getUpdatedPermissionValue(p[name]),\n }),\n }));\n setHavePermissionChanged(true);\n }, []);\n\n const handleSavePermissions = useCallback(() => {\n if (!chat || !selectedChatMemberId) {\n return;\n }\n\n setIsLoading(true);\n updateChatMemberBannedRights({\n chatId: chat.id,\n userId: selectedChatMemberId,\n bannedRights: permissions,\n });\n }, [chat, selectedChatMemberId, permissions, updateChatMemberBannedRights]);\n\n const handleBanFromGroup = useCallback(() => {\n if (!chat || !selectedChatMemberId) {\n return;\n }\n\n updateChatMemberBannedRights({\n chatId: chat.id,\n userId: selectedChatMemberId,\n bannedRights: {\n viewMessages: true,\n },\n });\n }, [chat, selectedChatMemberId, updateChatMemberBannedRights]);\n\n const getControlIsDisabled = useCallback((key: keyof ApiChatBannedRights) => {\n if (isFormFullyDisabled) {\n return true;\n }\n\n if (!chat || !chat.defaultBannedRights) {\n return false;\n }\n\n return chat.defaultBannedRights[key];\n }, [chat, isFormFullyDisabled]);\n\n if (!selectedChatMember) {\n return undefined;\n }\n\n return (\n <div className=\"Management\">\n <div className=\"custom-scroll\">\n <div className=\"section\">\n <ListItem inactive className=\"chat-item-clickable\">\n <PrivateChatInfo userId={selectedChatMember.userId} />\n </ListItem>\n\n <h3 className=\"section-heading mt-4\" dir=\"auto\">{lang('UserRestrictionsCanDo')}</h3>\n\n <div className=\"ListItem no-selection\">\n <Checkbox\n name=\"sendMessages\"\n checked={!permissions.sendMessages}\n label={lang('UserRestrictionsSend')}\n blocking\n disabled={getControlIsDisabled('sendMessages')}\n onChange={handlePermissionChange}\n />\n </div>\n <div className=\"ListItem no-selection\">\n <Checkbox\n name=\"sendMedia\"\n checked={!permissions.sendMedia}\n label={lang('UserRestrictionsSendMedia')}\n blocking\n disabled={getControlIsDisabled('sendMedia')}\n onChange={handlePermissionChange}\n />\n </div>\n <div className=\"ListItem no-selection\">\n <Checkbox\n name=\"sendStickers\"\n checked={!permissions.sendStickers && !permissions.sendGifs}\n label={lang('UserRestrictionsSendStickers')}\n blocking\n disabled={getControlIsDisabled('sendStickers')}\n onChange={handlePermissionChange}\n />\n </div>\n <div className=\"ListItem no-selection\">\n <Checkbox\n name=\"sendPolls\"\n checked={!permissions.sendPolls}\n label={lang('UserRestrictionsSendPolls')}\n blocking\n disabled={getControlIsDisabled('sendPolls')}\n onChange={handlePermissionChange}\n />\n </div>\n <div className=\"ListItem no-selection\">\n <Checkbox\n name=\"embedLinks\"\n checked={!permissions.embedLinks}\n label={lang('UserRestrictionsEmbedLinks')}\n blocking\n disabled={getControlIsDisabled('embedLinks')}\n onChange={handlePermissionChange}\n />\n </div>\n <div className=\"ListItem no-selection\">\n <Checkbox\n name=\"inviteUsers\"\n checked={!permissions.inviteUsers}\n label={lang('UserRestrictionsInviteUsers')}\n blocking\n disabled={getControlIsDisabled('inviteUsers')}\n onChange={handlePermissionChange}\n />\n </div>\n <div className=\"ListItem no-selection\">\n <Checkbox\n name=\"pinMessages\"\n checked={!permissions.pinMessages}\n label={lang('UserRestrictionsPinMessages')}\n blocking\n disabled={getControlIsDisabled('pinMessages')}\n onChange={handlePermissionChange}\n />\n </div>\n <div className=\"ListItem no-selection\">\n <Checkbox\n name=\"changeInfo\"\n checked={!permissions.changeInfo}\n label={lang('UserRestrictionsChangeInfo')}\n blocking\n disabled={getControlIsDisabled('changeInfo')}\n onChange={handlePermissionChange}\n />\n </div>\n </div>\n\n {!isFormFullyDisabled && (\n <div className=\"section\">\n <ListItem icon=\"delete-user\" ripple destructive onClick={openBanConfirmationDialog}>\n {lang('UserRestrictionsBlock')}\n </ListItem>\n </div>\n )}\n </div>\n\n <FloatingActionButton\n isShown={havePermissionChanged}\n onClick={handleSavePermissions}\n ariaLabel={lang('Save')}\n disabled={isLoading}\n >\n {isLoading ? (\n <Spinner color=\"white\" />\n ) : (\n <i className=\"icon-check\" />\n )}\n </FloatingActionButton>\n\n <ConfirmDialog\n isOpen={isBanConfirmationDialogOpen}\n onClose={closeBanConfirmationDialog}\n text=\"Are you sure you want to ban and remove this user from the group?\"\n confirmLabel=\"Remove\"\n confirmHandler={handleBanFromGroup}\n confirmIsDestructive\n />\n </div>\n );\n};\n\n\nexport default memo(withGlobal<OwnProps>(\n (global, { chatId, isPromotedByCurrentUser }): StateProps => {\n const chat = selectChat(global, chatId)!;\n const isFormFullyDisabled = !(chat.isCreator || isPromotedByCurrentUser);\n\n return { chat, isFormFullyDisabled };\n },\n (setGlobal, actions): DispatchProps => pick(actions, ['updateChatMemberBannedRights']),\n)(ManageGroupUserPermissions));\n","import React, {\n FC, memo, useCallback, useMemo,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { ManagementScreens } from '../../../types';\nimport { ApiChat, ApiChatMember, ApiUser } from '../../../api/types';\nimport { getUserFullName, isChatChannel } from '../../../modules/helpers';\n\nimport { selectChat } from '../../../modules/selectors';\nimport useLang from '../../../hooks/useLang';\n\nimport ListItem from '../../ui/ListItem';\nimport PrivateChatInfo from '../../common/PrivateChatInfo';\n\ntype OwnProps = {\n chatId: number;\n onScreenSelect: (screen: ManagementScreens) => void;\n onChatMemberSelect: (memberId: number, isPromotedByCurrentUser?: boolean) => void;\n};\n\ntype StateProps = {\n chat: ApiChat;\n currentUserId?: number;\n isChannel: boolean;\n usersById: Record<number, ApiUser>;\n};\n\nconst ManageChatAdministrators: FC<OwnProps & StateProps> = ({\n chat,\n isChannel,\n currentUserId,\n usersById,\n onScreenSelect,\n onChatMemberSelect,\n}) => {\n const lang = useLang();\n\n function handleRecentActionsClick() {\n onScreenSelect(ManagementScreens.GroupRecentActions);\n }\n\n const adminMembers = useMemo(() => {\n if (!chat.fullInfo || !chat.fullInfo.adminMembers) {\n return [];\n }\n\n return chat.fullInfo.adminMembers.sort((a, b) => {\n if (a.isOwner) {\n return -1;\n } else if (b.isOwner) {\n return 1;\n }\n\n return 0;\n });\n }, [chat]);\n\n const handleAdminMemberClick = useCallback((member: ApiChatMember) => {\n onChatMemberSelect(member.userId, member.promotedByUserId === currentUserId);\n onScreenSelect(ManagementScreens.ChatAdminRights);\n }, [currentUserId, onChatMemberSelect, onScreenSelect]);\n\n const getMemberStatus = useCallback((member: ApiChatMember) => {\n if (member.isOwner) {\n return lang('ChannelCreator');\n }\n\n const promotedByUser = member.promotedByUserId ? usersById[member.promotedByUserId] : undefined;\n\n if (promotedByUser) {\n return lang('EditAdminPromotedBy', getUserFullName(promotedByUser));\n }\n\n return lang('ChannelAdmin');\n }, [lang, usersById]);\n\n return (\n <div className=\"Management\">\n <div className=\"custom-scroll\">\n <div className=\"section\">\n <ListItem icon=\"recent\" multiline ripple onClick={handleRecentActionsClick}>\n <span className=\"title\">{lang('EventLog')}</span>\n <span className=\"subtitle\">{lang(isChannel ? 'EventLogInfoDetailChannel' : 'EventLogInfoDetail')}</span>\n </ListItem>\n </div>\n\n <div className=\"section\" dir={lang.isRtl ? 'rtl' : undefined}>\n <p className=\"text-muted\" dir=\"auto\">\n {isChannel\n ? 'You can add administrators to help you manage your channel.'\n : 'You can add administrators to help you manage your group.'}\n </p>\n\n {adminMembers.map((member) => (\n <ListItem\n key={member.userId}\n className=\"chat-item-clickable\"\n ripple\n onClick={() => handleAdminMemberClick(member)}\n >\n <PrivateChatInfo\n userId={member.userId}\n status={getMemberStatus(member)}\n forceShowSelf\n />\n </ListItem>\n ))}\n </div>\n </div>\n </div>\n );\n};\n\nexport default memo(withGlobal<OwnProps>(\n (global, { chatId }): StateProps => {\n const chat = selectChat(global, chatId)!;\n const { byId: usersById } = global.users;\n\n return {\n chat,\n currentUserId: global.currentUserId,\n isChannel: isChatChannel(chat),\n usersById,\n };\n },\n // (setGlobal, actions): DispatchProps => pick(actions, ['togglePreHistoryHidden', 'updateChat']),\n)(ManageChatAdministrators));\n","import React, {\n FC, memo, useCallback, useMemo,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { ApiChat, ApiChatMember } from '../../../api/types';\nimport useLang from '../../../hooks/useLang';\nimport { selectChat } from '../../../modules/selectors';\n\nimport ListItem from '../../ui/ListItem';\nimport Checkbox from '../../ui/Checkbox';\nimport PrivateChatInfo from '../../common/PrivateChatInfo';\n\ntype OwnProps = {\n chatId: number;\n};\n\ntype StateProps = {\n chat?: ApiChat;\n};\n\nconst ManageGroupRecentActions: FC<OwnProps & StateProps> = ({ chat }) => {\n const lang = useLang();\n\n const adminMembers = useMemo(() => {\n if (!chat || !chat.fullInfo || !chat.fullInfo.adminMembers) {\n return [];\n }\n\n return chat.fullInfo.adminMembers.sort((a, b) => {\n if (a.isOwner) {\n return -1;\n } else if (b.isOwner) {\n return 1;\n }\n\n return 0;\n });\n }, [chat]);\n\n const getMemberStatus = useCallback((member: ApiChatMember) => {\n if (member.isOwner) {\n return lang('ChannelCreator');\n }\n\n return lang('ChannelAdmin');\n }, [lang]);\n\n return (\n <div className=\"Management\">\n <div className=\"custom-scroll\">\n <div className=\"section not-implemented\" dir={lang.isRtl ? 'rtl' : undefined}>\n <h3 className=\"section-heading\" dir=\"auto\">Actions</h3>\n\n <div className=\"ListItem no-selection\">\n <Checkbox\n name=\"changeInfo\"\n checked={!false}\n label={lang('EventLogAllEvents')}\n onChange={undefined}\n />\n </div>\n <div className=\"ListItem no-selection\">\n <Checkbox\n name=\"changeInfo\"\n checked={!false}\n label={lang('EventLogFilterNewAdmins')}\n onChange={undefined}\n />\n </div>\n <div className=\"ListItem no-selection\">\n <Checkbox\n name=\"changeInfo\"\n checked={!false}\n label={lang('EventLogFilterNewMembers')}\n onChange={undefined}\n />\n </div>\n <div className=\"ListItem no-selection\">\n <Checkbox\n name=\"changeInfo\"\n checked={!false}\n label={lang('EventLogFilterChannelInfo')}\n onChange={undefined}\n />\n </div>\n <div className=\"ListItem no-selection\">\n <Checkbox\n name=\"changeInfo\"\n checked={!false}\n label={lang('EventLogFilterDeletedMessages')}\n onChange={undefined}\n />\n </div>\n <div className=\"ListItem no-selection\">\n <Checkbox\n name=\"changeInfo\"\n checked={!false}\n label={lang('EventLogFilterEditedMessages')}\n onChange={undefined}\n />\n </div>\n <div className=\"ListItem no-selection\">\n <Checkbox\n name=\"changeInfo\"\n checked={!false}\n label={lang('EventLogFilterLeavingMembers')}\n onChange={undefined}\n />\n </div>\n </div>\n\n <div className=\"section not-implemented\" dir={lang.isRtl ? 'rtl' : undefined}>\n <h3 className=\"section-heading\" dir=\"auto\">{lang('Channel.Management.Title')}</h3>\n\n <div className=\"ListItem no-selection\">\n <Checkbox\n name=\"changeInfo\"\n checked={!false}\n label={lang('EventLogAllAdmins')}\n onChange={undefined}\n />\n </div>\n\n {adminMembers.map((member) => (\n <ListItem\n key={member.userId}\n className=\"chat-item-clickable picker-list-item\"\n onClick={undefined}\n ripple\n >\n <Checkbox label=\"\" checked={!false} />\n <PrivateChatInfo\n userId={member.userId}\n status={getMemberStatus(member)}\n forceShowSelf\n />\n </ListItem>\n ))}\n </div>\n </div>\n </div>\n );\n};\n\nexport default memo(withGlobal<OwnProps>(\n (global, { chatId }): StateProps => {\n const chat = selectChat(global, chatId);\n\n return { chat };\n },\n)(ManageGroupRecentActions));\n","import React, {\n FC, memo, useCallback, useEffect, useMemo, useState,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { ApiChat, ApiChatAdminRights, ApiUser } from '../../../api/types';\nimport { ManagementScreens } from '../../../types';\nimport { GlobalActions } from '../../../global/types';\n\nimport { pick } from '../../../util/iteratees';\nimport { selectChat } from '../../../modules/selectors';\nimport { getUserFullName, isChatBasicGroup, isChatChannel } from '../../../modules/helpers';\nimport useLang from '../../../hooks/useLang';\nimport useFlag from '../../../hooks/useFlag';\n\nimport PrivateChatInfo from '../../common/PrivateChatInfo';\nimport ListItem from '../../ui/ListItem';\nimport Checkbox from '../../ui/Checkbox';\nimport FloatingActionButton from '../../ui/FloatingActionButton';\nimport Spinner from '../../ui/Spinner';\nimport ConfirmDialog from '../../ui/ConfirmDialog';\nimport InputText from '../../ui/InputText';\n\ntype OwnProps = {\n chatId: number;\n selectedChatMemberId?: number;\n isPromotedByCurrentUser?: boolean;\n onScreenSelect: (screen: ManagementScreens) => void;\n};\n\ntype StateProps = {\n chat: ApiChat;\n usersById: Record<number, ApiUser>;\n currentUserId?: number;\n isChannel: boolean;\n isFormFullyDisabled: boolean;\n};\n\ntype DispatchProps = Pick<GlobalActions, 'updateChatAdmin'>;\n\nconst CUSTOM_TITLE_MAX_LENGTH = 16;\n\nconst ManageGroupAdminRights: FC<OwnProps & StateProps & DispatchProps> = ({\n selectedChatMemberId,\n onScreenSelect,\n chat,\n usersById,\n currentUserId,\n isChannel,\n isFormFullyDisabled,\n updateChatAdmin,\n}) => {\n const [permissions, setPermissions] = useState<ApiChatAdminRights>({});\n const [isTouched, setIsTouched] = useState(false);\n const [isLoading, setIsLoading] = useState(false);\n const [isDismissConfirmationDialogOpen, openDismissConfirmationDialog, closeDismissConfirmationDialog] = useFlag();\n const [customTitle, setCustomTitle] = useState('');\n const lang = useLang();\n\n const selectedChatMember = useMemo(() => {\n if (!chat.fullInfo || !chat.fullInfo.adminMembers) {\n return undefined;\n }\n\n return chat.fullInfo.adminMembers.find(({ userId }) => userId === selectedChatMemberId);\n }, [chat, selectedChatMemberId]);\n\n useEffect(() => {\n if (chat && chat.fullInfo && selectedChatMemberId && !selectedChatMember) {\n onScreenSelect(ManagementScreens.ChatAdministrators);\n }\n }, [chat, onScreenSelect, selectedChatMember, selectedChatMemberId]);\n\n useEffect(() => {\n setPermissions((selectedChatMember && selectedChatMember.adminRights) || {});\n setCustomTitle(((selectedChatMember && selectedChatMember.customTitle) || '').substr(0, CUSTOM_TITLE_MAX_LENGTH));\n setIsTouched(false);\n setIsLoading(false);\n }, [selectedChatMember]);\n\n const handlePermissionChange = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {\n const { name } = e.target;\n\n function getUpdatedPermissionValue(value: true | undefined) {\n return value ? undefined : true;\n }\n\n setPermissions((p) => ({\n ...p,\n [name]: getUpdatedPermissionValue(p[name as keyof ApiChatAdminRights]),\n }));\n setIsTouched(true);\n }, []);\n\n const handleSavePermissions = useCallback(() => {\n if (!selectedChatMemberId) {\n return;\n }\n\n setIsLoading(true);\n updateChatAdmin({\n chatId: chat.id,\n userId: selectedChatMemberId,\n adminRights: permissions,\n customTitle,\n });\n }, [chat, selectedChatMemberId, permissions, customTitle, updateChatAdmin]);\n\n const handleDismissAdmin = useCallback(() => {\n if (!selectedChatMemberId) {\n return;\n }\n\n updateChatAdmin({\n chatId: chat.id,\n userId: selectedChatMemberId,\n adminRights: {},\n });\n closeDismissConfirmationDialog();\n }, [chat.id, closeDismissConfirmationDialog, selectedChatMemberId, updateChatAdmin]);\n\n const getControlIsDisabled = useCallback((key: keyof ApiChatAdminRights) => {\n if (isChatBasicGroup(chat)) {\n return false;\n }\n\n if (isFormFullyDisabled || !chat.adminRights) {\n return true;\n }\n\n return !chat.adminRights![key];\n }, [chat, isFormFullyDisabled]);\n\n const memberStatus = useMemo(() => {\n if (!selectedChatMember) {\n return undefined;\n }\n\n if (selectedChatMember.isOwner) {\n return lang('ChannelCreator');\n }\n\n const promotedByUser = selectedChatMember.promotedByUserId\n ? usersById[selectedChatMember.promotedByUserId]\n : undefined;\n\n if (promotedByUser) {\n return lang('EditAdminPromotedBy', getUserFullName(promotedByUser));\n }\n\n return lang('ChannelAdmin');\n }, [selectedChatMember, usersById, lang]);\n\n const handleCustomTitleChange = useCallback((e) => {\n const { value } = e.target;\n setCustomTitle(value);\n setIsTouched(true);\n }, []);\n\n if (!selectedChatMember) {\n return undefined;\n }\n\n return (\n <div className=\"Management\">\n <div className=\"custom-scroll\">\n <div className=\"section\">\n <ListItem inactive className=\"chat-item-clickable\">\n <PrivateChatInfo\n userId={selectedChatMember.userId}\n status={memberStatus}\n forceShowSelf\n />\n </ListItem>\n\n <h3 className=\"section-heading mt-4\" dir=\"auto\">{lang('EditAdminWhatCanDo')}</h3>\n\n <div className=\"ListItem no-selection\">\n <Checkbox\n name=\"changeInfo\"\n checked={!!permissions.changeInfo}\n label={lang(isChannel ? 'EditAdminChangeChannelInfo' : 'EditAdminChangeGroupInfo')}\n blocking\n disabled={getControlIsDisabled('changeInfo')}\n onChange={handlePermissionChange}\n />\n </div>\n {isChannel && (\n <div className=\"ListItem no-selection\">\n <Checkbox\n name=\"postMessages\"\n checked={!!permissions.postMessages}\n label={lang('EditAdminPostMessages')}\n blocking\n disabled={getControlIsDisabled('postMessages')}\n onChange={handlePermissionChange}\n />\n </div>\n )}\n {isChannel && (\n <div className=\"ListItem no-selection\">\n <Checkbox\n name=\"editMessages\"\n checked={!!permissions.editMessages}\n label={lang('EditAdminEditMessages')}\n blocking\n disabled={getControlIsDisabled('editMessages')}\n onChange={handlePermissionChange}\n />\n </div>\n )}\n <div className=\"ListItem no-selection\">\n <Checkbox\n name=\"deleteMessages\"\n checked={!!permissions.deleteMessages}\n label={lang(isChannel ? 'EditAdminDeleteMessages' : 'EditAdminGroupDeleteMessages')}\n blocking\n disabled={getControlIsDisabled('deleteMessages')}\n onChange={handlePermissionChange}\n />\n </div>\n {!isChannel && (\n <div className=\"ListItem no-selection\">\n <Checkbox\n name=\"banUsers\"\n checked={!!permissions.banUsers}\n label={lang('EditAdminBanUsers')}\n blocking\n disabled={getControlIsDisabled('banUsers')}\n onChange={handlePermissionChange}\n />\n </div>\n )}\n <div className=\"ListItem no-selection\">\n <Checkbox\n name=\"inviteUsers\"\n checked={!!permissions.inviteUsers}\n label={lang('EditAdminAddUsers')}\n blocking\n disabled={getControlIsDisabled('inviteUsers')}\n onChange={handlePermissionChange}\n />\n </div>\n {!isChannel && (\n <div className=\"ListItem no-selection\">\n <Checkbox\n name=\"pinMessages\"\n checked={!!permissions.pinMessages}\n label={lang('EditAdminPinMessages')}\n blocking\n disabled={getControlIsDisabled('pinMessages')}\n onChange={handlePermissionChange}\n />\n </div>\n )}\n <div className=\"ListItem no-selection\">\n <Checkbox\n name=\"addAdmins\"\n checked={!!permissions.addAdmins}\n label={lang('EditAdminAddAdmins')}\n blocking\n disabled={getControlIsDisabled('addAdmins')}\n onChange={handlePermissionChange}\n />\n </div>\n {!isChannel && (\n <div className=\"ListItem no-selection\">\n <Checkbox\n name=\"anonymous\"\n checked={!!permissions.anonymous}\n label={lang('EditAdminSendAnonymously')}\n blocking\n disabled={getControlIsDisabled('anonymous')}\n onChange={handlePermissionChange}\n />\n </div>\n )}\n\n {isFormFullyDisabled && (\n <p className=\"section-info mb-4\" dir=\"auto\">\n {lang('Channel.EditAdmin.CannotEdit')}\n </p>\n )}\n\n {!isChannel && (\n <InputText\n id=\"admin-title\"\n label={lang('EditAdminRank')}\n onChange={handleCustomTitleChange}\n value={customTitle}\n disabled={isFormFullyDisabled}\n maxLength={CUSTOM_TITLE_MAX_LENGTH}\n />\n )}\n\n {currentUserId !== selectedChatMemberId && !isFormFullyDisabled && (\n <ListItem icon=\"delete\" ripple destructive onClick={openDismissConfirmationDialog}>\n {lang('EditAdminRemoveAdmin')}\n </ListItem>\n )}\n </div>\n </div>\n\n <FloatingActionButton\n isShown={isTouched}\n onClick={handleSavePermissions}\n ariaLabel={lang('Save')}\n disabled={isLoading}\n >\n {isLoading ? (\n <Spinner color=\"white\" />\n ) : (\n <i className=\"icon-check\" />\n )}\n </FloatingActionButton>\n\n <ConfirmDialog\n isOpen={isDismissConfirmationDialogOpen}\n onClose={closeDismissConfirmationDialog}\n text=\"Are you sure you want to dismiss this admin?\"\n confirmLabel=\"Dismiss\"\n confirmHandler={handleDismissAdmin}\n confirmIsDestructive\n />\n </div>\n );\n};\n\n\nexport default memo(withGlobal<OwnProps>(\n (global, { chatId, isPromotedByCurrentUser }): StateProps => {\n const chat = selectChat(global, chatId)!;\n const { byId: usersById } = global.users;\n const { currentUserId } = global;\n const isChannel = isChatChannel(chat);\n const isFormFullyDisabled = !(chat.isCreator || isPromotedByCurrentUser);\n\n return {\n chat,\n usersById,\n currentUserId,\n isChannel,\n isFormFullyDisabled,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, ['updateChatAdmin']),\n)(ManageGroupAdminRights));\n","import React, {\n FC, memo, useCallback, useMemo,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { ApiChatMember, ApiUser } from '../../../api/types';\nimport { GlobalActions } from '../../../global/types';\nimport { selectChat } from '../../../modules/selectors';\nimport { sortUserIds, isChatChannel } from '../../../modules/helpers';\nimport { pick } from '../../../util/iteratees';\n\nimport PrivateChatInfo from '../../common/PrivateChatInfo';\nimport NothingFound from '../../common/NothingFound';\nimport ListItem from '../../ui/ListItem';\n\ntype OwnProps = {\n chatId: number;\n};\n\ntype StateProps = {\n usersById: Record<number, ApiUser>;\n members?: ApiChatMember[];\n isChannel?: boolean;\n};\n\ntype DispatchProps = Pick<GlobalActions, 'openUserInfo'>;\n\nconst ManageGroupMembers: FC<OwnProps & StateProps & DispatchProps> = ({\n members,\n usersById,\n isChannel,\n openUserInfo,\n}) => {\n const memberIds = useMemo(() => {\n if (!members || !usersById) {\n return undefined;\n }\n\n return sortUserIds(members.map(({ userId }) => userId), usersById);\n }, [members, usersById]);\n\n const handleMemberClick = useCallback((id: number) => {\n openUserInfo({ id });\n }, [openUserInfo]);\n\n return (\n <div className=\"Management\">\n <div className=\"custom-scroll\">\n <div className=\"section\" teactFastList>\n {memberIds ? (\n memberIds.map((id, i) => (\n <ListItem\n key={id}\n teactOrderKey={i}\n className=\"chat-item-clickable scroll-item\"\n onClick={() => handleMemberClick(id)}\n >\n <PrivateChatInfo userId={id} forceShowSelf />\n </ListItem>\n ))\n ) : (\n <NothingFound\n teactOrderKey={0}\n key=\"nothing-found\"\n text={isChannel ? 'No subscribers found' : 'No members found'}\n />\n )}\n </div>\n </div>\n </div>\n );\n};\n\nexport default memo(withGlobal<OwnProps>(\n (global, { chatId }): StateProps => {\n const chat = selectChat(global, chatId);\n const { byId: usersById } = global.users;\n const members = chat && chat.fullInfo && chat.fullInfo.members;\n const isChannel = chat && isChatChannel(chat);\n\n return {\n members,\n usersById,\n isChannel,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'openUserInfo',\n ]),\n)(ManageGroupMembers));\n","import React, {\n FC, memo, useCallback, useMemo,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { ApiChatMember, ApiUser } from '../../../api/types';\nimport { ManagementScreens } from '../../../types';\n\nimport { selectChat } from '../../../modules/selectors';\nimport { sortUserIds, isChatChannel } from '../../../modules/helpers';\n\nimport PrivateChatInfo from '../../common/PrivateChatInfo';\nimport ListItem from '../../ui/ListItem';\nimport NothingFound from '../../common/NothingFound';\n\ntype OwnProps = {\n chatId: number;\n onScreenSelect: (screen: ManagementScreens) => void;\n onChatMemberSelect: (memberId: number) => void;\n};\n\ntype StateProps = {\n usersById: Record<number, ApiUser>;\n members?: ApiChatMember[];\n isChannel?: boolean;\n};\n\nconst ManageGroupUserPermissionsCreate: FC<OwnProps & StateProps> = ({\n usersById,\n members,\n isChannel,\n onScreenSelect,\n onChatMemberSelect,\n}) => {\n const memberIds = useMemo(() => {\n if (!members || !usersById) {\n return undefined;\n }\n\n return sortUserIds(members.filter((member) => !member.isOwner).map(({ userId }) => userId), usersById);\n }, [members, usersById]);\n\n const handleExceptionMemberClick = useCallback((memberId: number) => {\n onChatMemberSelect(memberId);\n onScreenSelect(ManagementScreens.GroupUserPermissions);\n }, [onChatMemberSelect, onScreenSelect]);\n\n return (\n <div className=\"Management\">\n <div className=\"custom-scroll\">\n <div className=\"section\" teactFastList>\n {memberIds ? (\n memberIds.map((id, i) => (\n <ListItem\n key={id}\n teactOrderKey={i}\n className=\"chat-item-clickable scroll-item\"\n onClick={() => handleExceptionMemberClick(id)}\n >\n <PrivateChatInfo userId={id} forceShowSelf />\n </ListItem>\n ))\n ) : (\n <NothingFound\n teactOrderKey={0}\n key=\"nothing-found\"\n text={isChannel ? 'No subscribers found' : 'No members found'}\n />\n )}\n </div>\n </div>\n </div>\n );\n};\n\n\nexport default memo(withGlobal<OwnProps>(\n (global, { chatId }): StateProps => {\n const chat = selectChat(global, chatId);\n const { byId: usersById } = global.users;\n const members = chat && chat.fullInfo && chat.fullInfo.members;\n const isChannel = chat && isChatChannel(chat);\n\n return {\n members,\n usersById,\n isChannel,\n };\n },\n)(ManageGroupUserPermissionsCreate));\n","import React, { FC, memo } from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { ManagementScreens, ManagementType } from '../../../types';\n\nimport { selectCurrentManagementType } from '../../../modules/selectors';\n\nimport ManageUser from './ManageUser';\nimport ManageGroup from './ManageGroup';\nimport ManageGroupPermissions from './ManageGroupPermissions';\nimport ManageGroupRemovedUsers from './ManageGroupRemovedUsers';\nimport ManageChannel from './ManageChannel';\nimport ManageChatPrivacyType from './ManageChatPrivacyType';\nimport ManageDiscussion from './ManageDiscussion';\nimport ManageGroupUserPermissions from './ManageGroupUserPermissions';\nimport ManageChatAdministrators from './ManageChatAdministrators';\nimport ManageGroupRecentActions from './ManageGroupRecentActions';\nimport ManageGroupAdminRights from './ManageGroupAdminRights';\nimport ManageGroupMembers from './ManageGroupMembers';\nimport ManageGroupUserPermissionsCreate from './ManageGroupUserPermissionsCreate';\n\nexport type OwnProps = {\n chatId: number;\n currentScreen: ManagementScreens;\n selectedChatMemberId?: number;\n isPromotedByCurrentUser?: boolean;\n onScreenSelect: (screen: ManagementScreens) => void;\n onChatMemberSelect: (memberId: number, isPromotedByCurrentUser?: boolean) => void;\n};\n\ntype StateProps = {\n managementType?: ManagementType;\n};\n\nconst Management: FC<OwnProps & StateProps> = ({\n chatId,\n currentScreen,\n selectedChatMemberId,\n isPromotedByCurrentUser,\n onScreenSelect,\n onChatMemberSelect,\n managementType,\n}) => {\n switch (currentScreen) {\n case ManagementScreens.Initial: {\n switch (managementType) {\n case 'user':\n return <ManageUser key={chatId} userId={chatId} />;\n case 'group':\n return <ManageGroup key={chatId} chatId={chatId} onScreenSelect={onScreenSelect} />;\n case 'channel':\n return <ManageChannel key={chatId} chatId={chatId} onScreenSelect={onScreenSelect} />;\n }\n\n break;\n }\n\n case ManagementScreens.ChatPrivacyType:\n return (\n <ManageChatPrivacyType chatId={chatId} />\n );\n\n case ManagementScreens.Discussion:\n return (\n <ManageDiscussion\n chatId={chatId}\n onScreenSelect={onScreenSelect}\n />\n );\n\n case ManagementScreens.GroupPermissions:\n return (\n <ManageGroupPermissions\n chatId={chatId}\n onScreenSelect={onScreenSelect}\n onChatMemberSelect={onChatMemberSelect}\n />\n );\n\n case ManagementScreens.GroupRemovedUsers:\n return (\n <ManageGroupRemovedUsers chatId={chatId} />\n );\n\n case ManagementScreens.GroupUserPermissionsCreate:\n return (\n <ManageGroupUserPermissionsCreate\n chatId={chatId}\n onChatMemberSelect={onChatMemberSelect}\n onScreenSelect={onScreenSelect}\n />\n );\n\n case ManagementScreens.GroupUserPermissions:\n return (\n <ManageGroupUserPermissions\n chatId={chatId}\n selectedChatMemberId={selectedChatMemberId}\n isPromotedByCurrentUser={isPromotedByCurrentUser}\n onScreenSelect={onScreenSelect}\n />\n );\n\n case ManagementScreens.ChatAdministrators:\n return (\n <ManageChatAdministrators\n chatId={chatId}\n onScreenSelect={onScreenSelect}\n onChatMemberSelect={onChatMemberSelect}\n />\n );\n\n case ManagementScreens.GroupRecentActions:\n return (\n <ManageGroupRecentActions\n chatId={chatId}\n />\n );\n\n case ManagementScreens.ChatAdminRights:\n return (\n <ManageGroupAdminRights\n chatId={chatId}\n selectedChatMemberId={selectedChatMemberId}\n isPromotedByCurrentUser={isPromotedByCurrentUser}\n onScreenSelect={onScreenSelect}\n />\n );\n\n case ManagementScreens.ChannelSubscribers:\n case ManagementScreens.GroupMembers:\n return (\n <ManageGroupMembers chatId={chatId} />\n );\n }\n\n return undefined; // Never reached\n};\n\nexport default memo(withGlobal<OwnProps>(\n (global): StateProps => {\n const managementType = selectCurrentManagementType(global);\n\n return {\n managementType,\n };\n },\n)(Management));\n","const CURRENCIES: Record<string, string> = {\n USD: '$',\n EUR: '€',\n GBP: '£',\n JPY: '¥',\n RUB: '₽',\n UAH: '₴',\n INR: '₹',\n AED: 'د.إ',\n};\n\nexport function getCurrencySign(currency: string | undefined): string {\n if (!currency) {\n return '';\n }\n return CURRENCIES[currency] || '';\n}\n","const VISA = /^4[0-9]{12}(?:[0-9]{1,3})?$/;\nconst MASTERCARD1 = /^5[1-5][0-9]{11,14}$/;\nconst MASTERCARD2 = /^2[2-7][0-9]{11,14}$/;\n\nexport enum CardType {\n Default,\n Visa,\n Mastercard,\n}\n\nconst cards: Record<number, string> = {\n [CardType.Default]: '',\n [CardType.Visa]: 'visa',\n [CardType.Mastercard]: 'mastercard',\n};\n\nexport function detectCardType(cardNumber: string): number {\n cardNumber = cardNumber.replace(/\\s/g, '');\n if (VISA.test(cardNumber)) {\n return CardType.Visa;\n }\n if (MASTERCARD1.test(cardNumber) || MASTERCARD2.test(cardNumber)) {\n return CardType.Mastercard;\n }\n return CardType.Default;\n}\n\nexport function detectCardTypeText(cardNumber: string): string {\n const cardType = detectCardType(cardNumber);\n return cards[cardType as number] || '';\n}\n","import useReducer, { StateReducer, Dispatch } from '../useReducer';\nimport { countryList } from '../../util/phoneNumber';\n\nexport type FormState = {\n streetLine1: string;\n streetLine2: string;\n city: string;\n state: string;\n countryIso2: string;\n postCode: string;\n fullName: string;\n email: string;\n phone: string;\n shipping: string;\n cardNumber: string;\n cardholder: string;\n expiry: string;\n cvv: string;\n billingCountry: string;\n billingZip: string;\n saveInfo: boolean;\n saveCredentials: boolean;\n formErrors: Record<string, string>;\n};\n\nexport type FormActions = (\n 'changeAddress1' | 'changeAddress2' | 'changeCity' | 'changeState' | 'changeCountry' |\n 'changePostCode' | 'changeFullName' | 'changeEmail' | 'changePhone' | 'changeShipping' | 'updateUserInfo' |\n 'changeCardNumber' | 'changeCardholder' | 'changeExpiryDate' | 'changeCvvCode' | 'changeBillingCountry' |\n 'changeBillingZip' | 'changeSaveInfo' | 'changeSaveCredentials' | 'setFormErrors'\n);\nexport type FormEditDispatch = Dispatch<FormActions>;\n\nconst INITIAL_STATE: FormState = {\n streetLine1: '',\n streetLine2: '',\n city: '',\n state: '',\n countryIso2: '',\n postCode: '',\n fullName: '',\n email: '',\n phone: '',\n shipping: '',\n cardNumber: '',\n cardholder: '',\n expiry: '',\n cvv: '',\n billingCountry: '',\n billingZip: '',\n saveInfo: true,\n saveCredentials: false,\n formErrors: {},\n};\n\nconst reducer: StateReducer<FormState, FormActions> = (state, action) => {\n switch (action.type) {\n case 'changeAddress1':\n return {\n ...state,\n streetLine1: action.payload,\n formErrors: {\n ...state.formErrors,\n streetLine1: undefined,\n },\n };\n case 'changeAddress2':\n return {\n ...state,\n streetLine2: action.payload,\n formErrors: {\n ...state.formErrors,\n streetLine2: undefined,\n },\n };\n case 'changeCity':\n return {\n ...state,\n city: action.payload,\n formErrors: {\n ...state.formErrors,\n city: undefined,\n },\n };\n case 'changeState':\n return {\n ...state,\n state: action.payload,\n formErrors: {\n ...state.formErrors,\n state: undefined,\n },\n };\n case 'changeCountry':\n return {\n ...state,\n countryIso2: action.payload,\n billingCountry: getBillingCountry(action.payload),\n formErrors: {\n ...state.formErrors,\n countryIso2: undefined,\n },\n };\n case 'changePostCode':\n return {\n ...state,\n postCode: action.payload,\n formErrors: {\n ...state.formErrors,\n postCode: undefined,\n },\n };\n case 'changeFullName':\n return {\n ...state,\n fullName: action.payload,\n formErrors: {\n ...state.formErrors,\n fullName: undefined,\n },\n };\n case 'changeEmail':\n return {\n ...state,\n email: action.payload,\n formErrors: {\n ...state.formErrors,\n email: undefined,\n },\n };\n case 'changePhone':\n return {\n ...state,\n phone: action.payload,\n formErrors: {\n ...state.formErrors,\n phone: undefined,\n },\n };\n case 'changeShipping':\n return { ...state, shipping: action.payload };\n case 'changeCardNumber':\n return {\n ...state,\n cardNumber: action.payload,\n formErrors: {\n ...state.formErrors,\n cardNumber: undefined,\n },\n };\n case 'changeCardholder':\n return {\n ...state,\n cardholder: action.payload,\n formErrors: {\n ...state.formErrors,\n cardholder: undefined,\n },\n };\n case 'changeExpiryDate':\n return {\n ...state,\n expiry: action.payload,\n formErrors: {\n ...state.formErrors,\n expiry: undefined,\n },\n };\n case 'changeCvvCode':\n return {\n ...state,\n cvv: action.payload,\n formErrors: {\n ...state.formErrors,\n cvv: undefined,\n },\n };\n case 'changeBillingCountry':\n return {\n ...state,\n billingCountry: action.payload,\n formErrors: {\n ...state.formErrors,\n billingCountry: undefined,\n },\n };\n case 'changeBillingZip':\n return {\n ...state,\n billingZip: action.payload,\n formErrors: {\n ...state.formErrors,\n billingZip: undefined,\n },\n };\n case 'changeSaveInfo':\n return { ...state, saveInfo: action.payload };\n case 'changeSaveCredentials':\n return { ...state, saveCredentials: action.payload };\n case 'updateUserInfo':\n if (action.payload.countryIso2) {\n return {\n ...state,\n ...action.payload,\n billingCountry: getBillingCountry(action.payload.countryIso2),\n };\n }\n return { ...state, ...action.payload };\n case 'setFormErrors':\n return {\n ...state,\n formErrors: {\n ...state.formErrors,\n ...action.payload,\n },\n };\n default:\n return state;\n }\n};\n\nfunction getBillingCountry(countryCode: string) {\n const country = countryList.find(({ id }) => id === countryCode);\n return country ? country.name : '';\n}\n\nexport default () => {\n return useReducer(reducer, INITIAL_STATE);\n};\n","import { RefObject } from 'react';\n\nimport { IS_TOUCH_ENV } from '../util/environment';\nimport { fastRaf } from '../util/schedulers';\nimport { useEffect } from '../lib/teact/teact';\n\nconst DEFAULT_DURATION = 400;\n\nexport default function useFocusAfterAnimation(\n ref: RefObject<HTMLInputElement>, animationDuration = DEFAULT_DURATION,\n) {\n useEffect(() => {\n if (IS_TOUCH_ENV) {\n return;\n }\n\n setTimeout(() => {\n fastRaf(() => {\n if (ref.current) {\n ref.current.focus();\n }\n });\n }, animationDuration);\n }, [ref, animationDuration]);\n}\n","import { ChangeEvent, RefObject } from 'react';\nimport React, { FC, memo } from '../../lib/teact/teact';\n\n\nimport buildClassName from '../../util/buildClassName';\n\ntype OwnProps = {\n id?: string;\n value?: string;\n label?: string;\n error?: string;\n ref?: RefObject<HTMLSelectElement>;\n hasArrow?: boolean;\n placeholder?: string;\n onChange?: (e: ChangeEvent<HTMLSelectElement>) => void;\n children: any;\n};\n\nconst Select: FC<OwnProps> = (props) => {\n const {\n id,\n value,\n label,\n hasArrow,\n error,\n ref,\n placeholder,\n onChange,\n children,\n } = props;\n const labelText = error || label;\n const fullClassName = buildClassName(\n 'input-group',\n value && 'touched',\n error && 'error',\n labelText && 'with-label',\n hasArrow && 'with-arrow',\n 'input-group',\n );\n\n return (\n <div className={fullClassName}>\n <select\n className=\"form-control\"\n id={id}\n value={value || ''}\n onChange={onChange}\n placeholder={placeholder || label}\n ref={ref}\n >\n {children}\n </select>\n {labelText && id && (\n <label htmlFor={id}>{labelText}</label>\n )}\n </div>\n );\n};\n\nexport default memo(Select);\n","import React, {\n FC, useRef, useCallback, useEffect, memo,\n} from '../../lib/teact/teact';\n\nimport { FormState, FormEditDispatch } from '../../hooks/reducers/usePaymentReducer';\nimport useFocusAfterAnimation from '../../hooks/useFocusAfterAnimation';\nimport useLang from '../../hooks/useLang';\nimport { countryList } from '../../util/phoneNumber';\n\nimport InputText from '../ui/InputText';\nimport Select from '../ui/Select';\nimport Checkbox from '../ui/Checkbox';\n\nimport './ShippingInfo.scss';\n\nexport type OwnProps = {\n state: FormState;\n needEmail: boolean;\n needPhone: boolean;\n needName: boolean;\n needAddress: boolean;\n dispatch: FormEditDispatch;\n};\n\nconst ShippingInfo: FC<OwnProps> = ({\n state,\n needEmail,\n needPhone,\n needName,\n needAddress,\n dispatch,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const inputRef = useRef<HTMLInputElement>(null);\n // eslint-disable-next-line no-null/no-null\n const phoneRef = useRef<HTMLInputElement>(null);\n // eslint-disable-next-line no-null/no-null\n const selectCountryRef = useRef<HTMLSelectElement>(null);\n\n useEffect(() => {\n if (selectCountryRef.current\n && selectCountryRef.current.value !== state.countryIso2) {\n selectCountryRef.current.value = state.countryIso2;\n }\n }, [state.countryIso2]);\n\n const lang = useLang();\n\n useFocusAfterAnimation(inputRef);\n\n const handleAddress1Change = useCallback((e) => {\n dispatch({ type: 'changeAddress1', payload: e.target.value });\n }, [dispatch]);\n\n const handleAddress2Change = useCallback((e) => {\n dispatch({ type: 'changeAddress2', payload: e.target.value });\n }, [dispatch]);\n\n const handleCityChange = useCallback((e) => {\n dispatch({ type: 'changeCity', payload: e.target.value });\n }, [dispatch]);\n\n const handleStateChange = useCallback((e) => {\n dispatch({ type: 'changeState', payload: e.target.value });\n }, [dispatch]);\n\n const handleCountryChange = useCallback((e) => {\n dispatch({ type: 'changeCountry', payload: e.target.value });\n }, [dispatch]);\n\n const handlePostCodeChange = useCallback((e) => {\n dispatch({ type: 'changePostCode', payload: e.target.value });\n }, [dispatch]);\n\n const handleFullNameChange = useCallback((e) => {\n dispatch({ type: 'changeFullName', payload: e.target.value });\n }, [dispatch]);\n\n const handleEmailChange = useCallback((e) => {\n dispatch({ type: 'changeEmail', payload: e.target.value });\n }, [dispatch]);\n\n const handlePhoneChange = useCallback((e) => {\n let { value } = e.target;\n value = `+${value.replace(/\\D/g, '')}`;\n if (phoneRef.current) {\n phoneRef.current.value = value;\n }\n dispatch({ type: 'changePhone', payload: value });\n }, [dispatch]);\n\n const handleSaveInfoChange = useCallback((e) => {\n dispatch({ type: 'changeSaveInfo', payload: e.target.value });\n }, [dispatch]);\n\n const { formErrors } = state;\n return (\n <div className=\"ShippingInfo\">\n <form>\n {needAddress ? (\n <div>\n <h5>{lang('PaymentShippingAddress')}</h5>\n <InputText\n ref={inputRef}\n label=\"Address1 (Street)\"\n onChange={handleAddress1Change}\n value={state.streetLine1}\n inputMode=\"text\"\n error={formErrors.streetLine1}\n />\n <InputText\n label=\"Address2 (Street)\"\n onChange={handleAddress2Change}\n value={state.streetLine2}\n inputMode=\"text\"\n error={formErrors.streetLine2}\n />\n <InputText\n label=\"City\"\n onChange={handleCityChange}\n value={state.city}\n inputMode=\"text\"\n error={formErrors.city}\n />\n <InputText\n label=\"State\"\n onChange={handleStateChange}\n value={state.state}\n inputMode=\"text\"\n error={formErrors.state}\n />\n <Select\n label=\"Country\"\n placeholder=\"Country\"\n onChange={handleCountryChange}\n value={state.countryIso2}\n hasArrow={Boolean(true)}\n id=\"shipping-country\"\n error={formErrors.countryIso2}\n ref={selectCountryRef}\n >\n {countryList.map(({ name, id }) => (\n <option\n value={id}\n className=\"county-item\"\n >\n {name}\n </option>\n ))}\n </Select>\n\n <InputText\n label=\"Post Code\"\n onChange={handlePostCodeChange}\n value={state.postCode}\n inputMode=\"text\"\n error={formErrors.postCode}\n />\n </div>\n ) : undefined}\n { needName || needEmail || needPhone ? (\n <h5>{lang('PaymentShippingReceiver')}</h5>\n ) : undefined }\n { needName && (\n <InputText\n label=\"Full name\"\n onChange={handleFullNameChange}\n value={state.fullName}\n inputMode=\"text\"\n error={formErrors.fullName}\n />\n ) }\n { needEmail && (\n <InputText\n label=\"Email\"\n onChange={handleEmailChange}\n value={state.email}\n inputMode=\"email\"\n error={formErrors.email}\n />\n ) }\n { needPhone && (\n <InputText\n label=\"Phone number\"\n onChange={handlePhoneChange}\n value={state.phone}\n inputMode=\"tel\"\n error={formErrors.phone}\n ref={phoneRef}\n />\n ) }\n <Checkbox\n label={lang('PaymentShippingSave')}\n subLabel={lang('PaymentShippingSaveInfo')}\n checked={Boolean(state.saveInfo)}\n onChange={handleSaveInfoChange}\n />\n </form>\n </div>\n );\n};\n\nexport default memo(ShippingInfo);\n","import React, {\n FC, useCallback, memo, useMemo, useEffect,\n} from '../../lib/teact/teact';\n\nimport { ShippingOption } from '../../types/index';\n\nimport { FormState, FormEditDispatch } from '../../hooks/reducers/usePaymentReducer';\n\nimport RadioGroup from '../ui/RadioGroup';\n\nimport './Shipping.scss';\n\nexport type OwnProps = {\n state: FormState;\n shippingOptions: ShippingOption[];\n currency: string;\n dispatch: FormEditDispatch;\n};\n\nconst Shipping: FC<OwnProps> = ({\n state,\n shippingOptions,\n currency,\n dispatch,\n}) => {\n useEffect(() => {\n if (!shippingOptions || state.shipping) {\n return;\n }\n dispatch({ type: 'changeShipping', payload: shippingOptions[0].id });\n }, [shippingOptions, state.shipping, dispatch]);\n\n const handleShippingSelect = useCallback((value) => {\n dispatch({ type: 'changeShipping', payload: value });\n }, [dispatch]);\n\n const options = useMemo(() => (shippingOptions.map(({ id: value, title: label, amount }) => ({\n label,\n subLabel: `${currency} ${String(amount / 100)}`,\n value,\n }))), [shippingOptions, currency]);\n\n return (\n <div className=\"Shipping\">\n <form>\n <p>Select shipping method</p>\n <RadioGroup\n name=\"shipping-options\"\n options={options}\n onChange={handleShippingSelect}\n selected={state.shipping}\n />\n </form>\n </div>\n );\n};\n\nexport default memo(Shipping);\n","import React, {\n FC, memo,\n} from '../../lib/teact/teact';\n\nimport { Price } from '../../types';\n\nimport './Checkout.scss';\n\nexport type OwnProps = {\n invoiceContent?: {\n title?: string;\n description?: string;\n text?: string;\n photoUrl?: string;\n };\n checkoutInfo?: {\n paymentMethod?: string;\n paymentProvider?: string;\n shippingAddress?: string;\n name?: string;\n phone?: string;\n shippingMethod?: string;\n };\n prices?: Price[];\n totalPrice?: number;\n shippingPrices?: Price[];\n currency?: string;\n};\n\nconst Checkout: FC<OwnProps> = ({\n invoiceContent,\n prices,\n shippingPrices,\n checkoutInfo,\n currency,\n totalPrice,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const { photoUrl, title, text } = (invoiceContent || {});\n const {\n paymentMethod,\n paymentProvider,\n shippingAddress,\n name,\n phone,\n shippingMethod,\n } = (checkoutInfo || {});\n return (\n <div className=\"Checkout\">\n <div className=\"description has-image\">\n { photoUrl && (\n <img src={photoUrl} alt=\"\" />\n )}\n <div className=\"text\">\n <h5>{ title }</h5>\n <p>{ text }</p>\n </div>\n </div>\n <div className=\"price-info\">\n { prices && prices.map((item) => (\n renderPaymentItem(item.label, item.amount, currency, false)\n )) }\n { shippingPrices && shippingPrices.map((item) => (\n renderPaymentItem(item.label, item.amount, currency, false)\n )) }\n { totalPrice !== undefined && (\n renderPaymentItem('Total', totalPrice, currency, true)\n ) }\n </div>\n <div className=\"invoice-info\">\n {paymentMethod && renderCheckoutItem('icon-card', paymentMethod, 'Payment method')}\n {paymentProvider && renderCheckoutItem('stripe-provider', paymentProvider, 'Payment provider')}\n {shippingAddress && renderCheckoutItem('icon-location', shippingAddress, 'Shipping address')}\n {name && renderCheckoutItem('icon-user', name, 'Name')}\n {phone && renderCheckoutItem('icon-phone', phone, 'Phone number')}\n {shippingMethod && renderCheckoutItem('icon-truck', shippingMethod, 'Shipping method')}\n </div>\n </div>\n );\n};\n\nfunction renderPaymentItem(title: string, value: number, currency?: string, main = false) {\n return (\n <div className={`price-info-item ${main ? 'price-info-item-main' : ''}`}>\n <div className=\"title\">\n { title }\n </div>\n <div className=\"value\">\n { `${currency || ''} ${(value / 100).toFixed(2)}` }\n </div>\n </div>\n );\n}\n\nfunction renderCheckoutItem(icon: string, title: string, data: string) {\n return (\n <div className=\"checkout-info-item\">\n <i className={icon}> </i>\n <div className=\"info\">\n <div className=\"title\">\n { title }\n </div>\n <p className=\"data\">\n { data }\n </p>\n </div>\n </div>\n );\n}\n\nexport default memo(Checkout);\n","import React, {\n FC, memo, useCallback, useRef,\n} from '../../lib/teact/teact';\n\nimport { formatCardExpiry } from '../middle/helpers/inputFormatters';\n\nimport InputText from '../ui/InputText';\n\nconst MAX_FIELD_LENGTH = 5;\n\nexport type OwnProps = {\n value: string;\n error?: string;\n onChange: (value: string) => void;\n};\n\nconst ExpiryInput : FC<OwnProps> = ({ value, error, onChange }) => {\n // eslint-disable-next-line no-null/no-null\n const expiryInputRef = useRef<HTMLInputElement>(null);\n\n const handleKeyDown = useCallback((e) => {\n if (e.key === 'Backspace' && value.charAt(value.length - 1) === '/') {\n const newValue = value.slice(0, value.length - 1);\n if (expiryInputRef.current) {\n expiryInputRef.current.value = newValue;\n }\n }\n }, [value]);\n\n const handleChange = useCallback((e) => {\n onChange(formatCardExpiry(e.target.value));\n }, [onChange]);\n\n return (\n <InputText\n label=\"Expiry date\"\n ref={expiryInputRef}\n onChange={handleChange}\n onKeyDown={handleKeyDown}\n value={value}\n error={error}\n inputMode=\"numeric\"\n maxLength={MAX_FIELD_LENGTH}\n />\n );\n};\n\nexport default memo(ExpiryInput);\n","export function formatCardExpiry(input: string) {\n input = input.replace(/[^\\d]/g, '').slice(0, 4);\n const parts = input.match(/.{1,2}/g);\n if (parts && parts[0] && Number(parts[0]) > 12) {\n parts[0] = '12';\n }\n if (parts && parts[0] && parts[0].length === 2 && !parts[1]) {\n parts[1] = '';\n }\n return parts ? parts.join('/') : '';\n}\n\nexport function formatCardNumber(input: string) {\n input = input.replace(/[^\\d]/g, '');\n const parts = input.match(/.{1,4}/g);\n return parts ? parts.join(' ') : '';\n}\n","export default __webpack_public_path__ + \"mastercard.4216118edafe23cc2dec7b8807ba4622.svg\";","export default __webpack_public_path__ + \"visa.e5a7c336e1deb4b92a636e2e053878c4.svg\";","import React, {\n FC, memo, useCallback, useState, useRef, useEffect,\n} from '../../lib/teact/teact';\n\nimport useFocusAfterAnimation from '../../hooks/useFocusAfterAnimation';\nimport { formatCardNumber } from '../middle/helpers/inputFormatters';\nimport { detectCardType, CardType } from '../common/helpers/detectCardType';\n\nimport InputText from '../ui/InputText';\n\nimport './CardInput.scss';\n\n// @ts-ignore\nimport mastercardIconPath from '../../assets/mastercard.svg';\n// @ts-ignore\nimport visaIconPath from '../../assets/visa.svg';\n\nconst CARD_NUMBER_MAX_LENGTH = 23;\n\nexport type OwnProps = {\n value: string;\n error?: string;\n onChange: (value: string) => void;\n};\n\nconst CardInput : FC<OwnProps> = ({ value, error, onChange }) => {\n // eslint-disable-next-line no-null/no-null\n const cardNumberRef = useRef<HTMLInputElement>(null);\n\n useFocusAfterAnimation(cardNumberRef);\n\n const [cardType, setCardType] = useState<number>(CardType.Default);\n useEffect(() => {\n const newCardType = detectCardType(value);\n setCardType(newCardType);\n // eslint-disable-next-line\n }, []);\n\n const handleChange = useCallback((e) => {\n const newValue = formatCardNumber(e.target.value);\n const newCardType = detectCardType(e.target.value);\n setCardType(newCardType);\n onChange(newValue);\n if (cardNumberRef.current) {\n cardNumberRef.current.value = newValue;\n }\n }, [onChange, cardNumberRef]);\n\n const cardIcon = getCardIcon(cardType);\n\n return (\n <div className=\"CardInput\">\n <span className=\"left-addon\">{cardIcon}</span>\n <InputText\n ref={cardNumberRef}\n label=\"Card number\"\n onChange={handleChange}\n value={value}\n inputMode=\"numeric\"\n className={cardType ? 'has-left-addon' : ''}\n error={error}\n maxLength={CARD_NUMBER_MAX_LENGTH}\n />\n </div>\n );\n};\n\nexport default memo(CardInput);\n\nfunction getCardIcon(cardType: CardType) {\n switch (cardType) {\n case CardType.Mastercard:\n return <img src={mastercardIconPath} alt=\"\" />;\n case CardType.Visa:\n return <img src={visaIconPath} alt=\"\" />;\n default:\n return undefined;\n }\n}\n","import React, {\n FC, useCallback, memo, useRef, useEffect,\n} from '../../lib/teact/teact';\n\nimport { FormState, FormEditDispatch } from '../../hooks/reducers/usePaymentReducer';\nimport useLang from '../../hooks/useLang';\nimport { countryList } from '../../util/phoneNumber';\n\nimport InputText from '../ui/InputText';\nimport Checkbox from '../ui/Checkbox';\nimport Select from '../ui/Select';\nimport ExpiryInput from './ExpiryInput';\nimport CardInput from './CardInput';\n\nimport './PaymentInfo.scss';\n\nexport type OwnProps = {\n state: FormState;\n canSaveCredentials: boolean;\n needCardholderName?: boolean;\n needCountry?: boolean;\n needZip?: boolean;\n dispatch: FormEditDispatch;\n};\n\nconst PaymentInfo: FC<OwnProps> = ({\n state,\n canSaveCredentials,\n needCardholderName,\n needCountry,\n needZip,\n dispatch,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const selectCountryRef = useRef<HTMLSelectElement>(null);\n\n useEffect(() => {\n if (selectCountryRef.current\n && selectCountryRef.current.value !== state.billingCountry) {\n selectCountryRef.current.value = state.billingCountry;\n }\n }, [state.billingCountry]);\n\n const handleCardNumberChange = useCallback((value) => {\n dispatch({ type: 'changeCardNumber', payload: value });\n }, [dispatch]);\n\n const handleCardholderChange = useCallback((e) => {\n dispatch({ type: 'changeCardholder', payload: e.target.value.toUpperCase() });\n }, [dispatch]);\n\n const handleExpiryChange = useCallback((value) => {\n dispatch({ type: 'changeExpiryDate', payload: value });\n }, [dispatch]);\n\n const handleCvvChange = useCallback((e) => {\n dispatch({ type: 'changeCvvCode', payload: e.target.value });\n }, [dispatch]);\n\n const handleCountryChange = useCallback((e) => {\n dispatch({ type: 'changeBillingCountry', payload: e.target.value });\n }, [dispatch]);\n\n const handleBillingPostCodeChange = useCallback((e) => {\n dispatch({ type: 'changeBillingZip', payload: e.target.value });\n }, [dispatch]);\n\n const handleChangeSaveCredentials = useCallback((e) => {\n dispatch({ type: 'changeSaveCredentials', payload: e.target.value });\n }, [dispatch]);\n\n const lang = useLang();\n\n const { formErrors = {} } = state;\n\n return (\n <div className=\"PaymentInfo\">\n <form>\n <h5>{lang('PaymentCardTitle')}</h5>\n <CardInput\n onChange={handleCardNumberChange}\n value={state.cardNumber}\n error={formErrors.cardNumber}\n />\n { needCardholderName && (\n <InputText\n label=\"Name on card\"\n onChange={handleCardholderChange}\n value={state.cardholder}\n inputMode=\"text\"\n error={formErrors.cardholder}\n />\n )}\n <section className=\"inline-inputs\">\n <ExpiryInput\n value={state.expiry}\n onChange={handleExpiryChange}\n error={formErrors.expiry}\n />\n <InputText\n label=\"CVV code\"\n onChange={handleCvvChange}\n value={state.cvv}\n inputMode=\"numeric\"\n maxLength={3}\n error={formErrors.cvv}\n />\n </section>\n { needCountry || needZip ? (\n <h5>{lang('PaymentBillingAddress')}</h5>\n ) : undefined }\n { needCountry && (\n <Select\n label=\"Country\"\n placeholder=\"Country\"\n onChange={handleCountryChange}\n value={state.billingCountry}\n hasArrow={Boolean(true)}\n id=\"billing-country\"\n error={formErrors.billingCountry}\n ref={selectCountryRef}\n >\n {\n countryList.map(({ name }) => (\n <option\n value={name}\n className=\"county-item\"\n >\n {name}\n </option>\n ))\n }\n </Select>\n ) }\n { needZip && (\n <InputText\n label=\"Post Code\"\n onChange={handleBillingPostCodeChange}\n value={state.billingZip}\n inputMode=\"text\"\n error={formErrors.billingZip}\n />\n )}\n { canSaveCredentials && (\n <Checkbox\n label={lang('PaymentCardSavePaymentInformation')}\n checked={state.saveCredentials}\n onChange={handleChangeSaveCredentials}\n />\n ) }\n </form>\n </div>\n );\n};\n\nexport default memo(PaymentInfo);\n","import React, {\n FC, memo, useCallback, useEffect, useMemo, useState,\n} from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { GlobalActions, GlobalState } from '../../global/types';\nimport { PaymentStep, ShippingOption, Price } from '../../types';\nimport { ApiError } from '../../api/types';\n\nimport { pick } from '../../util/iteratees';\nimport { getCurrencySign } from '../middle/helpers/getCurrencySign';\nimport { detectCardTypeText } from '../common/helpers/detectCardType';\nimport { getShippingError } from '../../modules/helpers/payments';\nimport usePaymentReducer, { FormState } from '../../hooks/reducers/usePaymentReducer';\nimport useLang from '../../hooks/useLang';\n\nimport ShippingInfo from './ShippingInfo';\nimport Shipping from './Shipping';\nimport Checkout from './Checkout';\nimport PaymentInfo from './PaymentInfo';\nimport Button from '../ui/Button';\nimport Modal from '../ui/Modal';\nimport Transition from '../ui/Transition';\nimport Spinner from '../ui/Spinner';\n\nimport './PaymentModal.scss';\n\nconst DEFAULT_PROVIDER = 'stripe';\n\nexport type OwnProps = {\n isOpen: boolean;\n onClose: () => void;\n};\n\ntype StateProps = {\n nameRequested?: boolean;\n shippingAddressRequested?: boolean;\n phoneRequested?: boolean;\n emailRequested?: boolean;\n flexible?: boolean;\n phoneToProvider?: boolean;\n emailToProvider?: boolean;\n currency?: string;\n prices?: Price[];\n isProviderError: boolean;\n needCardholderName?: boolean;\n needCountry?: boolean;\n needZip?: boolean;\n globalErrors?: ApiError[];\n};\n\ntype GlobalStateProps = Pick<GlobalState['payment'], 'step' | 'shippingOptions' |\n'savedInfo' | 'canSaveCredentials' | 'nativeProvider' | 'passwordMissing' | 'invoiceContent' |\n'error'>;\n\ntype DispatchProps = Pick<GlobalActions, 'validateRequestedInfo' | 'sendPaymentForm' | 'setPaymentStep'\n| 'sendCredentialsInfo' | 'clearPaymentError' >;\n\nconst Invoice: FC<OwnProps & StateProps & GlobalStateProps & DispatchProps> = ({\n isOpen,\n onClose,\n step,\n shippingOptions,\n savedInfo,\n canSaveCredentials,\n nameRequested,\n shippingAddressRequested,\n phoneRequested,\n emailRequested,\n phoneToProvider,\n emailToProvider,\n currency,\n passwordMissing,\n isProviderError,\n invoiceContent,\n nativeProvider,\n prices,\n needCardholderName,\n needCountry,\n needZip,\n error,\n globalErrors,\n validateRequestedInfo,\n sendPaymentForm,\n setPaymentStep,\n sendCredentialsInfo,\n clearPaymentError,\n}) => {\n const [paymentState, paymentDispatch] = usePaymentReducer();\n const currencySign = getCurrencySign(currency);\n const [isLoading, setIsLoading] = useState(false);\n const lang = useLang();\n\n useEffect(() => {\n if (step || error || globalErrors) {\n setIsLoading(false);\n }\n }, [step, error, globalErrors]);\n\n useEffect(() => {\n if (error && error.field) {\n paymentDispatch({\n type: 'setFormErrors',\n payload: {\n [error.field]: error.fieldError,\n },\n });\n return;\n }\n if (globalErrors && globalErrors.length) {\n const errors = getShippingError(globalErrors);\n paymentDispatch({\n type: 'setFormErrors',\n payload: {\n ...errors,\n },\n });\n }\n }, [error, globalErrors, paymentDispatch]);\n\n useEffect(() => {\n if (savedInfo) {\n const {\n name: fullName, phone, email, shippingAddress,\n } = savedInfo;\n paymentDispatch({\n type: 'updateUserInfo',\n payload: {\n fullName,\n phone: phone && phone.charAt(0) !== '+'\n ? `+${phone}`\n : phone,\n email,\n ...(shippingAddress || {}),\n },\n });\n }\n }, [savedInfo, paymentDispatch]);\n\n const handleErrorModalClose = useCallback(() => {\n clearPaymentError();\n }, [clearPaymentError]);\n\n const totalPrice = useMemo(() => {\n if (step !== PaymentStep.Checkout) {\n return 0;\n }\n\n return getTotalPrice(prices, shippingOptions, paymentState.shipping);\n }, [step, paymentState.shipping, prices, shippingOptions]);\n\n const checkoutInfo = useMemo(() => {\n if (step !== PaymentStep.Checkout) {\n return undefined;\n }\n return getCheckoutInfo(paymentState, shippingOptions, nativeProvider || '');\n }, [step, paymentState, shippingOptions, nativeProvider]);\n\n function renderError() {\n if (!error) {\n return undefined;\n }\n return (\n <Modal\n className=\"error\"\n isOpen={Boolean(error)}\n onClose={handleErrorModalClose}\n >\n <h4>{error.description || 'Error'}</h4>\n <p>{error.description || 'Error'}</p>\n <Button\n isText\n onClick={clearPaymentError}\n >\n {lang('OK')}\n </Button>\n </Modal>\n );\n }\n\n function renderModalContent(cuurentStep: PaymentStep) {\n switch (cuurentStep) {\n case PaymentStep.ShippingInfo:\n return (\n <ShippingInfo\n state={paymentState}\n dispatch={paymentDispatch}\n needAddress={Boolean(shippingAddressRequested)}\n needEmail={Boolean(emailRequested || emailToProvider)}\n needPhone={Boolean(phoneRequested || phoneToProvider)}\n needName={Boolean(nameRequested)}\n />\n );\n case PaymentStep.Shipping:\n return (\n <Shipping\n state={paymentState}\n dispatch={paymentDispatch}\n shippingOptions={shippingOptions || []}\n currency={currencySign}\n />\n );\n case PaymentStep.PaymentInfo:\n return (\n <PaymentInfo\n state={paymentState}\n dispatch={paymentDispatch}\n canSaveCredentials={Boolean(!passwordMissing && canSaveCredentials)}\n needCardholderName={needCardholderName}\n needCountry={needCountry}\n needZip={needZip}\n />\n );\n case PaymentStep.Checkout:\n return (\n <Checkout\n prices={prices}\n shippingPrices={paymentState.shipping && shippingOptions\n ? getShippingPrices(shippingOptions, paymentState.shipping)\n : undefined}\n totalPrice={totalPrice}\n invoiceContent={invoiceContent}\n checkoutInfo={checkoutInfo}\n currency={currencySign}\n />\n );\n default:\n return undefined;\n }\n }\n\n const validateRequest = useCallback(() => {\n const { saveInfo } = paymentState;\n const requestInfo = getRequestInfo(paymentState);\n validateRequestedInfo({ requestInfo, saveInfo });\n }, [validateRequestedInfo, paymentState]);\n\n const sendCredentials = useCallback(() => {\n const credentials = getCredentials(paymentState);\n sendCredentialsInfo({\n credentials,\n });\n }, [sendCredentialsInfo, paymentState]);\n\n const sendForm = useCallback(() => {\n sendPaymentForm({\n shippingOptionId: paymentState.shipping,\n saveCredentials: paymentState.saveCredentials,\n });\n }, [sendPaymentForm, paymentState]);\n\n const setStep = useCallback((nextStep) => {\n setPaymentStep({ step: nextStep });\n }, [setPaymentStep]);\n\n const handleButtonClick = useCallback(() => {\n setIsLoading(true);\n switch (step) {\n case PaymentStep.ShippingInfo:\n return validateRequest();\n case PaymentStep.Shipping:\n return setStep(PaymentStep.PaymentInfo);\n case PaymentStep.PaymentInfo:\n return sendCredentials();\n case PaymentStep.Checkout:\n return sendForm();\n default:\n return () => {};\n }\n }, [step, validateRequest, setStep, sendCredentials, sendForm]);\n\n const modalHeader = useMemo(() => {\n switch (step) {\n case PaymentStep.ShippingInfo:\n return lang('PaymentShippingInfo');\n case PaymentStep.Shipping:\n return lang('PaymentShippingMethod');\n case PaymentStep.PaymentInfo:\n return lang('PaymentCardInfo');\n case PaymentStep.Checkout:\n return lang('PaymentCheckout');\n default:\n return '';\n }\n }, [step, lang]);\n\n const buttonText = useMemo(() => {\n switch (step) {\n case PaymentStep.Checkout:\n return lang('Checkout.PayPrice', `${currencySign}${(totalPrice / 100).toFixed(2)}`);\n default:\n return lang('Next');\n }\n }, [step, lang, currencySign, totalPrice]);\n\n if (isProviderError) {\n return (\n <Modal\n className=\"error\"\n isOpen={isOpen}\n onClose={onClose}\n >\n <p>\n Sorry, Telegram T doesn&apos;t support payments with this provider yet. <br />\n Please use one of our mobile apps to do this.\n </p>\n <Button\n isText\n onClick={onClose}\n >\n {lang('OK')}\n </Button>\n </Modal>\n );\n }\n\n return (\n <Modal\n className=\"PaymentModal\"\n isOpen={isOpen}\n onClose={onClose}\n >\n <div className=\"header\" dir={lang.isRtl ? 'rtl' : undefined}>\n <Button\n className=\"close-button\"\n color=\"translucent\"\n round\n size=\"smaller\"\n onClick={onClose}\n ariaLabel=\"Close\"\n >\n <i className=\"icon-close\" />\n </Button>\n <h3>{modalHeader}</h3>\n </div>\n {step !== undefined ? (\n <Transition name=\"slide\" activeKey={step}>\n {() => (\n <div className=\"content custom-scroll\">\n {renderModalContent(step)}\n </div>\n )}\n </Transition>\n ) : (\n <div className=\"empty-content\">\n <Spinner color=\"gray\" />\n </div>\n )}\n <div className=\"footer\">\n <Button\n type=\"submit\"\n onClick={handleButtonClick}\n disabled={isLoading}\n isLoading={isLoading}\n >\n {buttonText}\n </Button>\n </div>\n {error && !error.field && renderError()}\n </Modal>\n );\n};\n\nexport default memo(withGlobal<OwnProps>(\n (global): StateProps & GlobalStateProps => {\n const {\n step,\n shippingOptions,\n savedInfo,\n canSaveCredentials,\n invoice,\n invoiceContent,\n nativeProvider,\n nativeParams,\n passwordMissing,\n error,\n } = global.payment;\n\n const isProviderError = Boolean(invoice && (!nativeProvider || nativeProvider !== DEFAULT_PROVIDER));\n const { needCardholderName, needCountry, needZip } = (nativeParams || {});\n const {\n nameRequested,\n phoneRequested,\n emailRequested,\n shippingAddressRequested,\n flexible,\n phoneToProvider,\n emailToProvider,\n currency,\n prices,\n } = (invoice || {});\n\n return {\n step,\n shippingOptions,\n savedInfo,\n canSaveCredentials,\n nativeProvider,\n passwordMissing,\n nameRequested,\n shippingAddressRequested,\n phoneRequested,\n emailRequested,\n flexible,\n phoneToProvider,\n emailToProvider,\n currency,\n prices,\n isProviderError,\n invoiceContent,\n needCardholderName,\n needCountry,\n needZip,\n error,\n globalErrors: global.errors,\n };\n },\n (setGlobal, actions): DispatchProps => {\n return pick(actions, [\n 'validateRequestedInfo',\n 'sendPaymentForm',\n 'setPaymentStep',\n 'sendCredentialsInfo',\n 'clearPaymentError',\n ]);\n },\n)(Invoice));\n\nfunction findShippingOption(shippingOptions: ShippingOption[], optionId: string) {\n return shippingOptions.find(({ id }) => id === optionId);\n}\n\nfunction getShippingPrices(shippingOptions: ShippingOption[], shippingOption: string) {\n const option = findShippingOption(shippingOptions, shippingOption);\n return option ? option.prices : undefined;\n}\n\nfunction getTotalPrice(prices: Price[] = [], shippingOptions: ShippingOption[] | undefined, shippingOption: string) {\n const shippingPrices = shippingOptions\n ? getShippingPrices(shippingOptions, shippingOption)\n : [];\n let total = 0;\n const totalPrices = prices.concat(shippingPrices || []);\n total = totalPrices.reduce((acc, cur) => {\n return acc + cur.amount;\n }, total);\n return total;\n}\n\nfunction getCheckoutInfo(state: FormState, shippingOptions: ShippingOption[] | undefined, paymentProvider: string) {\n const cardTypeText = detectCardTypeText(state.cardNumber);\n const paymentMethod = `${cardTypeText} *${state.cardNumber.slice(-4)}`;\n const shippingAddress = state.streetLine1\n ? `${state.streetLine1}, ${state.city}, ${state.countryIso2}`\n : undefined;\n const { phone, fullName: name } = state;\n const shippingOption = shippingOptions ? findShippingOption(shippingOptions, state.shipping) : undefined;\n const shippingMethod = shippingOption ? shippingOption.title : undefined;\n return {\n paymentMethod,\n paymentProvider,\n shippingAddress,\n name,\n phone,\n shippingMethod,\n };\n}\n\nfunction getRequestInfo(paymentState: FormState) {\n const {\n streetLine1,\n streetLine2,\n city,\n state,\n countryIso2,\n postCode,\n fullName: name,\n phone,\n email,\n } = paymentState;\n\n const shippingAddress = {\n streetLine1,\n streetLine2,\n city,\n state,\n countryIso2,\n postCode,\n };\n\n return {\n name,\n phone,\n email,\n shippingAddress,\n };\n}\n\nfunction getCredentials(paymentState: FormState) {\n const {\n cardNumber, cardholder, expiry, cvv, billingCountry, billingZip,\n } = paymentState;\n const [expiryMonth, expiryYear] = expiry.split('/');\n const data = {\n cardNumber,\n cardholder,\n expiryMonth,\n expiryYear,\n cvv,\n country: billingCountry,\n zip: billingZip,\n };\n\n return {\n data,\n };\n}\n","import React, {\n FC, memo, useMemo,\n} from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { Price } from '../../types';\nimport { ApiShippingAddress } from '../../api/types/payments';\n\nimport useLang from '../../hooks/useLang';\nimport { getCurrencySign } from '../middle/helpers/getCurrencySign';\n\nimport Checkout from './Checkout';\nimport Modal from '../ui/Modal';\nimport Button from '../ui/Button';\n\nimport './PaymentModal.scss';\n\nexport type OwnProps = {\n isOpen: boolean;\n onClose: () => void;\n};\n\ntype StateProps = {\n prices?: Price[];\n shippingPrices: any;\n totalAmount?: number;\n currency?: string;\n info?: {\n shippingAddress?: ApiShippingAddress;\n phone?: string;\n name?: string;\n };\n photoUrl?: string;\n text?: string;\n title?: string;\n credentialsTitle?: string;\n shippingMethod?: string;\n};\n\nconst ReceiptModal: FC<OwnProps & StateProps> = ({\n isOpen,\n onClose,\n prices,\n shippingPrices,\n totalAmount,\n currency,\n info,\n photoUrl,\n text,\n title,\n credentialsTitle,\n shippingMethod,\n}) => {\n const lang = useLang();\n const currencySign = getCurrencySign(currency);\n const checkoutInfo = useMemo(() => {\n return getCheckoutInfo(credentialsTitle, info, shippingMethod);\n }, [info, shippingMethod, credentialsTitle]);\n return (\n <Modal\n className=\"PaymentModal PaymentModal-receipt\"\n isOpen={isOpen}\n onClose={onClose}\n >\n <div>\n <div className=\"header\" dir={lang.isRtl ? 'rtl' : undefined}>\n <Button\n className=\"close-button\"\n color=\"translucent\"\n round\n size=\"smaller\"\n onClick={onClose}\n ariaLabel=\"Close\"\n >\n <i className=\"icon-close\" />\n </Button>\n <h3> {lang('PaymentReceipt')} </h3>\n </div>\n <div className=\"receipt-content custom-scroll\">\n <Checkout\n prices={prices}\n shippingPrices={shippingPrices}\n totalPrice={totalAmount}\n invoiceContent={{\n photoUrl,\n text,\n title,\n }}\n checkoutInfo={checkoutInfo}\n currency={currencySign}\n />\n </div>\n </div>\n </Modal>\n );\n};\n\nexport default memo(withGlobal<OwnProps>(\n (global): StateProps => {\n const { receipt } = global.payment;\n const {\n currency,\n prices: mapedPrices,\n info,\n totalAmount,\n credentialsTitle,\n shippingPrices,\n shippingMethod,\n photoUrl,\n text,\n title,\n } = (receipt || {});\n\n return {\n currency,\n prices: mapedPrices,\n info,\n totalAmount,\n credentialsTitle,\n shippingPrices,\n shippingMethod,\n photoUrl,\n text,\n title,\n };\n },\n)(ReceiptModal));\n\nfunction getCheckoutInfo(paymentMethod?: string,\n info?:\n { phone?: string;\n name?: string;\n shippingAddress?: ApiShippingAddress;\n },\n shippingMethod?: string) {\n if (!info) {\n return { paymentMethod };\n }\n const { shippingAddress } = info;\n const fullAddress = shippingAddress && shippingAddress.streetLine1\n ? `${shippingAddress.streetLine1}, ${shippingAddress.city}, ${shippingAddress.countryIso2}`\n : undefined;\n const { phone, name } = info;\n return {\n paymentMethod,\n paymentProvider: 'Stripe',\n shippingAddress: fullAddress,\n name,\n phone,\n shippingMethod,\n };\n}\n","import { ApiMediaFormat } from '../../../api/types';\n\nimport * as mediaLoader from '../../../util/mediaLoader';\n\n// @ts-ignore\nimport MonkeyIdle from '../../../assets/TwoFactorSetupMonkeyIdle.tgs';\n// @ts-ignore\nimport MonkeyTracking from '../../../assets/TwoFactorSetupMonkeyTracking.tgs';\n// @ts-ignore\nimport MonkeyClose from '../../../assets/TwoFactorSetupMonkeyClose.tgs';\n// @ts-ignore\nimport MonkeyPeek from '../../../assets/TwoFactorSetupMonkeyPeek.tgs';\n// @ts-ignore\nimport FoldersAll from '../../../assets/FoldersAll.tgs';\n// @ts-ignore\nimport FoldersNew from '../../../assets/FoldersNew.tgs';\n// @ts-ignore\nimport DiscussionGroups from '../../../assets/DiscussionGroupsDucks.tgs';\n\nexport const ANIMATED_STICKERS_PATHS = {\n MonkeyIdle,\n MonkeyTracking,\n MonkeyClose,\n MonkeyPeek,\n FoldersAll,\n FoldersNew,\n DiscussionGroups,\n};\n\nexport default function getAnimationData(name: keyof typeof ANIMATED_STICKERS_PATHS) {\n const path = ANIMATED_STICKERS_PATHS[name].replace(window.location.origin, '');\n\n return mediaLoader.fetch(`file${path}`, ApiMediaFormat.Lottie);\n}\n","export default __webpack_public_path__ + \"TwoFactorSetupMonkeyIdle.dea4a492c144df84ddab778dc8a3f0cd.tgs\";","export default __webpack_public_path__ + \"TwoFactorSetupMonkeyTracking.eb5a7a6f166fb7589c12e6248561fb58.tgs\";","export default __webpack_public_path__ + \"TwoFactorSetupMonkeyClose.604c4c833d322b7e6c3ea19bef058241.tgs\";","export default __webpack_public_path__ + \"TwoFactorSetupMonkeyPeek.1905436b042520363d7e59f5d7f903ab.tgs\";","export default __webpack_public_path__ + \"FoldersAll.3f9f9e243d19f0fbf9aaaff11cbd4572.tgs\";","export default __webpack_public_path__ + \"FoldersNew.9a40d71c0c8be70f5bd14ff2d7bc1593.tgs\";","export default __webpack_public_path__ + \"DiscussionGroupsDucks.9ea453d1be9d1b0ee77a992f8e587485.tgs\";","import React, {\n FC, useEffect, useState, memo,\n} from '../../lib/teact/teact';\n\nimport { DEBUG } from '../../config';\nimport { blobToFile, blobToDataUri } from '../../util/files';\nimport useLang from '../../hooks/useLang';\n\nimport Button from './Button';\nimport Modal from './Modal';\nimport Loading from './Loading';\n\nimport './CropModal.scss';\n\n// Change to 'base64' to get base64-encoded string\nconst cropperResultOptions: Croppie.ResultOptions & { type: 'blob' } = {\n type: 'blob',\n quality: 0.8,\n format: 'jpeg',\n circle: false,\n};\n\ntype ICroppie = typeof import('croppie');\nlet Croppie: ICroppie;\nlet croppiePromise: Promise<{ default: ICroppie }>;\n\nasync function ensureCroppie() {\n if (!croppiePromise) {\n croppiePromise = import('../../lib/croppie') as unknown as Promise<{ default: ICroppie }>;\n Croppie = (await croppiePromise).default;\n }\n\n return croppiePromise;\n}\n\nlet cropper: Croppie;\n\nasync function initCropper(imgFile: File) {\n try {\n const cropContainer = document.getElementById('avatar-crop');\n if (!cropContainer) {\n return;\n }\n\n const { offsetWidth, offsetHeight } = cropContainer;\n\n cropper = new Croppie(cropContainer, {\n enableZoom: true,\n boundary: {\n width: offsetWidth,\n height: offsetHeight,\n },\n viewport: {\n width: offsetWidth - 16,\n height: offsetHeight - 16,\n type: 'circle',\n },\n });\n\n const dataUri = await blobToDataUri(imgFile);\n await cropper.bind({ url: dataUri });\n } catch (err) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error(err);\n }\n }\n}\n\ntype OwnProps = {\n file?: File;\n onChange: (file: File) => void;\n onClose: () => void;\n};\n\nconst CropModal: FC<OwnProps> = ({ file, onChange, onClose }: OwnProps) => {\n const [isCroppieReady, setIsCroppieReady] = useState(false);\n\n useEffect(() => {\n if (!file) {\n return;\n }\n\n if (!isCroppieReady) {\n ensureCroppie().then(() => setIsCroppieReady(true));\n\n return;\n }\n\n initCropper(file);\n }, [file, isCroppieReady]);\n\n const lang = useLang();\n\n async function handleCropClick() {\n if (!cropper) {\n return;\n }\n\n const result: Blob | string = await cropper.result(cropperResultOptions);\n const croppedImg = typeof result === 'string' ? result : blobToFile(result, 'avatar.jpg');\n\n onChange(croppedImg);\n }\n\n return (\n <Modal\n isOpen={Boolean(file)}\n onClose={onClose}\n title=\"Drag to reposition\"\n className=\"CropModal\"\n hasCloseButton\n >\n {isCroppieReady ? (\n <div id=\"avatar-crop\" />\n ) : (\n <Loading />\n )}\n <Button\n className=\"confirm-button\"\n round\n color=\"primary\"\n onClick={handleCropClick}\n ariaLabel={lang('CropImage')}\n >\n <i className=\"icon-check\" />\n </Button>\n </Modal>\n );\n};\n\nexport default memo(CropModal);\n","import { ChangeEvent } from 'react';\nimport React, {\n FC, useState, useEffect, memo,\n} from '../../lib/teact/teact';\n\nimport buildClassName from '../../util/buildClassName';\n\nimport CropModal from './CropModal';\n\nimport './AvatarEditable.scss';\n\ninterface OwnProps {\n title?: string;\n disabled?: boolean;\n currentAvatarBlobUrl?: string;\n onChange: (file: File) => void;\n}\n\nconst AvatarEditable: FC<OwnProps> = ({\n title = 'Change your profile picture',\n disabled,\n currentAvatarBlobUrl,\n onChange,\n}) => {\n const [selectedFile, setSelectedFile] = useState<File | undefined>();\n const [croppedBlobUrl, setCroppedBlobUrl] = useState<string | undefined>(currentAvatarBlobUrl);\n\n useEffect(() => {\n setCroppedBlobUrl(currentAvatarBlobUrl);\n }, [currentAvatarBlobUrl]);\n\n function handleSelectFile(event: ChangeEvent<HTMLInputElement>) {\n const target = event.target as HTMLInputElement;\n\n if (!target || !target.files || !target.files[0]) {\n return;\n }\n\n setSelectedFile(target.files[0]);\n target.value = '';\n }\n\n function handleAvatarCrop(croppedImg: File) {\n setSelectedFile(undefined);\n onChange(croppedImg);\n\n if (croppedBlobUrl) {\n URL.revokeObjectURL(croppedBlobUrl);\n }\n setCroppedBlobUrl(URL.createObjectURL(croppedImg));\n }\n\n function handleModalClose() {\n setSelectedFile(undefined);\n }\n\n const labelClassName = buildClassName(\n croppedBlobUrl && 'filled',\n disabled && 'disabled',\n );\n\n return (\n <div className=\"AvatarEditable\">\n <label\n className={labelClassName}\n role=\"button\"\n tabIndex={0}\n title={title}\n >\n <input\n type=\"file\"\n onChange={handleSelectFile}\n accept=\"image/png, image/jpeg\"\n />\n <i className=\"icon-camera-add\" />\n {croppedBlobUrl && <img src={croppedBlobUrl} alt=\"Avatar\" />}\n </label>\n <CropModal file={selectedFile} onClose={handleModalClose} onChange={handleAvatarCrop} />\n </div>\n );\n};\n\nexport default memo(AvatarEditable);\n","import React, {\n FC, useState, useEffect, useCallback, memo,\n} from '../../lib/teact/teact';\n\nimport { STICKER_SIZE_AUTH, STICKER_SIZE_AUTH_MOBILE, STICKER_SIZE_TWO_FA } from '../../config';\nimport { IS_MOBILE_SCREEN } from '../../util/environment';\nimport getAnimationData from './helpers/animatedAssets';\n\nimport AnimatedSticker from './AnimatedSticker';\n\nimport './PasswordMonkey.scss';\n\ntype OwnProps = {\n isPasswordVisible: boolean;\n isBig?: boolean;\n};\n\nconst PEEK_MONKEY_SHOW_DELAY = 2000;\nconst SEGMENT_COVER_EYES: [number, number] = [0, 50];\nconst SEGMENT_UNCOVER_EYE: [number, number] = [0, 20];\nconst SEGMENT_COVER_EYE: [number, number] = [20, 0];\nconst STICKER_SIZE = IS_MOBILE_SCREEN ? STICKER_SIZE_AUTH_MOBILE : STICKER_SIZE_AUTH;\n\nconst PasswordMonkey: FC<OwnProps> = ({ isPasswordVisible, isBig }) => {\n const [closeMonkeyData, setCloseMonkeyData] = useState<Record<string, any>>();\n const [peekMonkeyData, setPeekMonkeyData] = useState<Record<string, any>>();\n const [isFirstMonkeyLoaded, setIsFirstMonkeyLoaded] = useState(false);\n const [isPeekShown, setIsPeekShown] = useState(false);\n\n useEffect(() => {\n if (!closeMonkeyData) {\n getAnimationData('MonkeyClose').then(setCloseMonkeyData);\n } else {\n setTimeout(() => setIsPeekShown(true), PEEK_MONKEY_SHOW_DELAY);\n }\n }, [closeMonkeyData]);\n\n useEffect(() => {\n if (!peekMonkeyData) {\n getAnimationData('MonkeyPeek').then(setPeekMonkeyData);\n }\n }, [peekMonkeyData]);\n\n const handleFirstMonkeyLoad = useCallback(() => setIsFirstMonkeyLoaded(true), []);\n\n return (\n <div id=\"monkey\" className={isBig ? 'big' : ''}>\n {!isFirstMonkeyLoaded && (\n <div className=\"monkey-preview\" />\n )}\n {closeMonkeyData && (\n <AnimatedSticker\n id=\"closeMonkey\"\n size={isBig ? STICKER_SIZE_TWO_FA : STICKER_SIZE}\n className={isPeekShown ? 'hidden' : 'shown'}\n animationData={closeMonkeyData}\n playSegment={SEGMENT_COVER_EYES}\n noLoop\n onLoad={handleFirstMonkeyLoad}\n />\n )}\n {peekMonkeyData && (\n <AnimatedSticker\n id=\"peekMonkey\"\n size={isBig ? STICKER_SIZE_TWO_FA : STICKER_SIZE}\n className={isPeekShown ? 'shown' : 'hidden'}\n animationData={peekMonkeyData}\n playSegment={isPasswordVisible ? SEGMENT_UNCOVER_EYE : SEGMENT_COVER_EYE}\n noLoop\n />\n )}\n </div>\n );\n};\n\nexport default memo(PasswordMonkey);\n","import { ChangeEvent } from 'react';\nimport React, {\n FC, memo, useEffect, useRef, useState,\n} from '../../lib/teact/teact';\n\nimport { MIN_PASSWORD_LENGTH } from '../../config';\nimport { IS_TOUCH_ENV, IS_MOBILE_SCREEN } from '../../util/environment';\nimport buildClassName from '../../util/buildClassName';\nimport useLang from '../../hooks/useLang';\n\nimport Button from '../ui/Button';\n\ntype OwnProps = {\n submitLabel?: string;\n error?: string;\n hint?: string;\n placeholder?: string;\n isLoading?: boolean;\n isPasswordVisible?: boolean;\n clearError: NoneToVoidFunction;\n onChangePasswordVisibility: (state: boolean) => void;\n onInputChange?: (password: string) => void;\n onSubmit: (password: string) => void;\n};\n\nconst FOCUS_DELAY_TIMEOUT_MS = IS_MOBILE_SCREEN ? 550 : 400;\n\nconst PasswordForm: FC<OwnProps> = ({\n isLoading = false,\n isPasswordVisible,\n error,\n hint,\n placeholder = 'Password',\n submitLabel = 'Next',\n clearError,\n onChangePasswordVisibility,\n onInputChange,\n onSubmit,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const inputRef = useRef<HTMLInputElement>(null);\n const lang = useLang();\n\n const [password, setPassword] = useState('');\n const [canSubmit, setCanSubmit] = useState(false);\n\n useEffect(() => {\n if (!IS_TOUCH_ENV) {\n setTimeout(() => {\n inputRef.current!.focus();\n }, FOCUS_DELAY_TIMEOUT_MS);\n }\n }, []);\n\n useEffect(() => {\n if (error) {\n requestAnimationFrame(() => {\n inputRef.current!.focus();\n inputRef.current!.select();\n });\n }\n }, [error]);\n\n function onPasswordChange(e: ChangeEvent<HTMLInputElement>) {\n if (error) {\n clearError();\n }\n\n const { target } = e;\n setPassword(target.value);\n setCanSubmit(target.value.length >= MIN_PASSWORD_LENGTH);\n if (onInputChange) {\n onInputChange(target.value);\n }\n }\n\n function togglePasswordVisibility() {\n onChangePasswordVisibility(!isPasswordVisible);\n }\n\n function handleSubmit(event: React.FormEvent<HTMLFormElement>) {\n event.preventDefault();\n\n if (isLoading) {\n return;\n }\n\n if (canSubmit) {\n onSubmit(password);\n }\n }\n\n return (\n <form action=\"\" onSubmit={handleSubmit} autoComplete=\"off\">\n <div\n className={buildClassName('input-group password-input', password && 'touched', error && 'error')}\n dir={lang.isRtl ? 'rtl' : undefined}\n >\n <input\n ref={inputRef}\n className=\"form-control\"\n type={isPasswordVisible ? 'text' : 'password'}\n id=\"sign-in-password\"\n value={password || ''}\n autoComplete=\"current-password\"\n onChange={onPasswordChange}\n dir=\"auto\"\n />\n <label>{error || hint || placeholder}</label>\n <div\n className=\"toggle-password\"\n onClick={togglePasswordVisibility}\n role=\"button\"\n tabIndex={0}\n title=\"Toggle password visibility\"\n >\n <i className={isPasswordVisible ? 'icon-eye' : 'icon-eye-closed'} />\n </div>\n </div>\n {canSubmit && (\n <Button type=\"submit\" ripple isLoading={isLoading}>\n {submitLabel}\n </Button>\n )}\n </form>\n );\n};\n\nexport default memo(PasswordForm);\n"],"sourceRoot":""}