diff --git a/src/api/gramjs/apiBuilders/common.ts b/src/api/gramjs/apiBuilders/common.ts index 82e2ab1f..ebc10bfe 100644 --- a/src/api/gramjs/apiBuilders/common.ts +++ b/src/api/gramjs/apiBuilders/common.ts @@ -22,7 +22,7 @@ export function buildApiThumbnailFromStripped( } const realSizes = sizes.filter((s): s is GramJs.PhotoSize => s instanceof GramJs.PhotoSize); - const { w, h } = realSizes && realSizes.length ? realSizes[realSizes.length - 1] : DEFAULT_THUMB_SIZE; + const { w, h } = realSizes.length ? realSizes[realSizes.length - 1] : DEFAULT_THUMB_SIZE; const { bytes } = thumb; const dataUri = bytesToDataUri( !mimeType || mimeType === 'image/jpeg' ? strippedPhotoToJpg(bytes) : bytes, diff --git a/src/api/gramjs/apiBuilders/messages.ts b/src/api/gramjs/apiBuilders/messages.ts index fa976333..0eed19e9 100644 --- a/src/api/gramjs/apiBuilders/messages.ts +++ b/src/api/gramjs/apiBuilders/messages.ts @@ -171,7 +171,7 @@ export function buildApiMessageWithChatId(chatId: number, mtpMessage: UniversalM ...(keyboardButtons && { keyboardButtons, keyboardPlaceholder, isKeyboardSingleUse }), ...(shouldHideKeyboardButtons && { shouldHideKeyboardButtons }), ...(mtpMessage.viaBotId && { viaBotId: mtpMessage.viaBotId }), - ...(replies && replies.comments && { threadInfo: buildThreadInfo(replies, mtpMessage.id, chatId) }), + ...(replies?.comments && { threadInfo: buildThreadInfo(replies, mtpMessage.id, chatId) }), ...(postAuthor && { adminTitle: postAuthor }), }; } @@ -505,7 +505,7 @@ export function buildInvoice(media: GramJs.MessageMediaInvoice): ApiInvoice { return { text, title, - photoUrl: photo && photo.url, + photoUrl: photo?.url, receiptMsgId, amount: Number(totalAmount), currency, diff --git a/src/api/gramjs/apiBuilders/symbols.ts b/src/api/gramjs/apiBuilders/symbols.ts index 8c7cccb5..ca675bc6 100644 --- a/src/api/gramjs/apiBuilders/symbols.ts +++ b/src/api/gramjs/apiBuilders/symbols.ts @@ -34,7 +34,7 @@ export function buildStickerFromDocument(document: GramJs.TypeDocument): ApiStic const stickerSetInfo = stickerAttribute && stickerAttribute.stickerset instanceof GramJs.InputStickerSetID ? stickerAttribute.stickerset : undefined; - const emoji = stickerAttribute ? stickerAttribute.alt : undefined; + const emoji = stickerAttribute?.alt; const isAnimated = document.mimeType === ANIMATED_STICKER_MIME_TYPE; const cachedThumb = document.thumbs && document.thumbs.find( (s): s is GramJs.PhotoCachedSize => s instanceof GramJs.PhotoCachedSize, @@ -83,7 +83,7 @@ export function buildStickerSet(set: GramJs.StickerSet): ApiStickerSet { id: String(id), accessHash: String(accessHash), title, - hasThumbnail: Boolean(thumbs && thumbs.length), + hasThumbnail: Boolean(thumbs?.length), count, hash, shortName, diff --git a/src/api/gramjs/methods/symbols.ts b/src/api/gramjs/methods/symbols.ts index 8f5fd2ae..0c7514b8 100644 --- a/src/api/gramjs/methods/symbols.ts +++ b/src/api/gramjs/methods/symbols.ts @@ -23,7 +23,7 @@ export async function fetchStickerSets({ hash }: { hash: number }) { } allStickers.sets.forEach((stickerSet) => { - if (stickerSet.thumbs && stickerSet.thumbs.length) { + if (stickerSet.thumbs?.length) { localDb.stickerSets[String(stickerSet.id)] = stickerSet; } }); diff --git a/src/api/gramjs/methods/users.ts b/src/api/gramjs/methods/users.ts index 53c27ebe..f2c31233 100644 --- a/src/api/gramjs/methods/users.ts +++ b/src/api/gramjs/methods/users.ts @@ -57,7 +57,7 @@ export async function fetchFullUser({ export async function fetchNearestCountry() { const dcInfo = await invokeRequest(new GramJs.help.GetNearestDc()); - return dcInfo ? dcInfo.country : undefined; + return dcInfo?.country; } export async function fetchTopUsers({ hash = 0 }: { hash?: number }) { diff --git a/src/api/gramjs/updater.ts b/src/api/gramjs/updater.ts index 919c54ac..697ecf84 100644 --- a/src/api/gramjs/updater.ts +++ b/src/api/gramjs/updater.ts @@ -117,7 +117,7 @@ export function updater(update: Update, originRequest?: GramJs.AnyRequest) { // eslint-disable-next-line no-underscore-dangle const entities = update._entities; - if (entities && entities.length) { + if (entities?.length) { entities .filter((e) => e instanceof GramJs.User) .map(buildApiUser) @@ -660,7 +660,7 @@ export function updater(update: Update, originRequest?: GramJs.AnyRequest) { }); } else if (update instanceof GramJs.UpdateUserName) { const updatedUser = localDb.users[update.userId]; - const user = updatedUser && updatedUser.mutualContact && !updatedUser.self + const user = updatedUser?.mutualContact && !updatedUser.self ? pick(update, ['username']) : pick(update, ['firstName', 'lastName', 'username']); @@ -697,7 +697,7 @@ export function updater(update: Update, originRequest?: GramJs.AnyRequest) { return; } - if (_entities && _entities.length) { + if (_entities?.length) { _entities .filter((e) => e instanceof GramJs.User && !e.contact) .forEach((user) => { diff --git a/src/api/gramjs/worker/provider.ts b/src/api/gramjs/worker/provider.ts index 53afd17d..310bd4ff 100644 --- a/src/api/gramjs/worker/provider.ts +++ b/src/api/gramjs/worker/provider.ts @@ -88,10 +88,7 @@ function subscribeToWorker(onUpdate: OnApiUpdate) { } } } else if (data.type === 'methodCallback') { - const requestState = requestStates.get(data.messageId); - if (requestState && requestState.callback) { - requestState.callback(...data.callbackArgs); - } + requestStates.get(data.messageId)?.callback?.(...data.callbackArgs); } else if (data.type === 'unhandledError') { throw data.error; } diff --git a/src/components/auth/CountryCodeInput.tsx b/src/components/auth/CountryCodeInput.tsx index 29a7f274..c9514cea 100644 --- a/src/components/auth/CountryCodeInput.tsx +++ b/src/components/auth/CountryCodeInput.tsx @@ -89,7 +89,7 @@ const CountryCodeInput: FC = ({ const inputValue = filter !== undefined ? filter - : (value && value.name) || ''; + : (value?.name) || ''; return (
diff --git a/src/components/common/AnimatedEmoji.tsx b/src/components/common/AnimatedEmoji.tsx index f282ed1c..a5736938 100644 --- a/src/components/common/AnimatedEmoji.tsx +++ b/src/components/common/AnimatedEmoji.tsx @@ -44,7 +44,7 @@ const AnimatedEmoji: FC = ({ const isIntersecting = useIsIntersecting(ref, observeIntersection); - const thumbDataUri = sticker.thumbnail && sticker.thumbnail.dataUri; + const thumbDataUri = sticker.thumbnail?.dataUri; const previewBlobUrl = useMedia( `${localMediaHash}?size=m`, !isIntersecting && !forceLoadPreview, diff --git a/src/components/common/ChatExtra.tsx b/src/components/common/ChatExtra.tsx index a64e5515..a232e4e6 100644 --- a/src/components/common/ChatExtra.tsx +++ b/src/components/common/ChatExtra.tsx @@ -77,7 +77,7 @@ const ChatExtra: FC = ({ const formattedNumber = phoneNumber && formatPhoneNumberWithCode(phoneNumber); const link = getChatLink(chat); - const description = (fullInfo && fullInfo.bio) || getChatDescription(chat); + const description = (fullInfo?.bio) || getChatDescription(chat); return (
diff --git a/src/components/common/DeleteMessageModal.tsx b/src/components/common/DeleteMessageModal.tsx index b46644dd..8e9fac1e 100644 --- a/src/components/common/DeleteMessageModal.tsx +++ b/src/components/common/DeleteMessageModal.tsx @@ -57,7 +57,7 @@ const DeleteMessageModal: FC = ({ deleteScheduledMessages, }) => { const handleDeleteMessageForAll = useCallback(() => { - const messageIds = album && album.messages + const messageIds = album?.messages ? album.messages.map(({ id }) => id) : [message.id]; deleteMessages({ messageIds, shouldDeleteForAll: true }); @@ -65,7 +65,7 @@ const DeleteMessageModal: FC = ({ }, [deleteMessages, message.id, onClose, album]); const handleDeleteMessageForSelf = useCallback(() => { - const messageIds = album && album.messages + const messageIds = album?.messages ? album.messages.map(({ id }) => id) : [message.id]; if (isSchedule) { diff --git a/src/components/common/GifButton.tsx b/src/components/common/GifButton.tsx index 1838a5f9..ef62ca98 100644 --- a/src/components/common/GifButton.tsx +++ b/src/components/common/GifButton.tsx @@ -38,7 +38,7 @@ const GifButton: FC = ({ const isIntersecting = useIsIntersecting(ref, observeIntersection); const loadAndPlay = isIntersecting && !isDisabled; const previewBlobUrl = useMedia(`${localMediaHash}?size=m`, !loadAndPlay, ApiMediaFormat.BlobUrl); - const thumbRef = useCanvasBlur(gif.thumbnail && gif.thumbnail.dataUri, Boolean(previewBlobUrl)); + const thumbRef = useCanvasBlur(gif.thumbnail?.dataUri, Boolean(previewBlobUrl)); const videoData = useMedia(localMediaHash, !loadAndPlay, ApiMediaFormat.BlobUrl); const shouldRenderVideo = Boolean(loadAndPlay && videoData); const { transitionClassNames } = useTransitionForMedia(hasThumbnail || previewBlobUrl || videoData, 'slow'); diff --git a/src/components/common/Picker.tsx b/src/components/common/Picker.tsx index d6af03ed..2d6bcad8 100644 --- a/src/components/common/Picker.tsx +++ b/src/components/common/Picker.tsx @@ -104,7 +104,7 @@ const Picker: FC = ({ />
- {viewportIds && viewportIds.length ? ( + {viewportIds?.length ? ( = ({ chat={chat} user={user} size="small" - isSavedMessages={user && user.isSelf} + isSavedMessages={user?.isSelf} /> ); diff --git a/src/components/common/PrivateChatInfo.tsx b/src/components/common/PrivateChatInfo.tsx index 1d6507c6..878032f5 100644 --- a/src/components/common/PrivateChatInfo.tsx +++ b/src/components/common/PrivateChatInfo.tsx @@ -130,7 +130,7 @@ const PrivateChatInfo: FC = ({ ) : (

{fullName && renderText(fullName)}

- {user && user.isVerified && } + {user?.isVerified && }
)} {(status || (!isSavedMessages && !noStatusOrTyping)) && renderStatusOrTyping()} diff --git a/src/components/common/ProfileInfo.tsx b/src/components/common/ProfileInfo.tsx index a8133c76..1d512e6b 100644 --- a/src/components/common/ProfileInfo.tsx +++ b/src/components/common/ProfileInfo.tsx @@ -54,7 +54,7 @@ const ProfileInfo: FC = ({ const { id: userId } = user || {}; const { id: chatId } = chat || {}; const fullName = user ? getUserFullName(user) : (chat ? chat.title : ''); - const photos = (user ? user.photos : (chat ? chat.photos : undefined)) || []; + const photos = user?.photos || chat?.photos || []; const slideAnimation = animationLevel >= 1 ? 'slide' : 'none'; const [currentPhotoIndex, setCurrentPhotoIndex] = useState(0); @@ -171,14 +171,14 @@ const ProfileInfo: FC = ({ return ( { isChatChannel(chat!) - ? lang('Subscribers', chat!.membersCount, 'i') - : lang('Members', chat!.membersCount, 'i') + ? lang('Subscribers', chat!.membersCount ?? 0, 'i') + : lang('Members', chat!.membersCount ?? 0, 'i') } ); } - const isVerifiedIconShown = (user && user.isVerified) || (chat && chat.isVerified); + const isVerifiedIconShown = (user || chat)?.isVerified; return (
diff --git a/src/components/common/StickerButton.tsx b/src/components/common/StickerButton.tsx index cd3ea36c..29f613dc 100644 --- a/src/components/common/StickerButton.tsx +++ b/src/components/common/StickerButton.tsx @@ -87,7 +87,7 @@ const StickerButton: FC = ({
= ({ hasCloseButton title={stickerSet ? renderText(stickerSet.title, ['emoji', 'links']) : lang('AccDescrStickerSet')} > - {stickerSet && stickerSet.stickers ? ( + {stickerSet?.stickers ? ( <>
{stickerSet.stickers.map((sticker) => ( diff --git a/src/components/left/main/Chat.tsx b/src/components/left/main/Chat.tsx index 939bf31c..7d5fb09d 100644 --- a/src/components/left/main/Chat.tsx +++ b/src/components/left/main/Chat.tsx @@ -126,7 +126,7 @@ const Chat: FC = ({ const actionTargetUsers = useMemo(() => { return actionTargetUserIds - ? actionTargetUserIds.map((userId) => usersById && usersById[userId]).filter(Boolean as any) + ? actionTargetUserIds.map((userId) => usersById?.[userId]).filter(Boolean as any) : undefined; }, [actionTargetUserIds, usersById]); @@ -205,7 +205,7 @@ const Chat: FC = ({ return ; } - if (draft && draft.text.length) { + if (draft?.text.length) { return (

{lang('Draft')} @@ -273,7 +273,7 @@ const Chat: FC = ({ chat={chat} user={privateChatUser} withOnlineStatus - isSavedMessages={privateChatUser && privateChatUser.isSelf} + isSavedMessages={privateChatUser?.isSelf} lastSyncTime={lastSyncTime} />

diff --git a/src/components/left/main/ChatFolders.tsx b/src/components/left/main/ChatFolders.tsx index 1b0379a8..989b5eb4 100644 --- a/src/components/left/main/ChatFolders.tsx +++ b/src/components/left/main/ChatFolders.tsx @@ -111,7 +111,7 @@ const ChatFolders: FC = ({ { title: lang.code === 'en' ? 'All' : lang('FilterAllChats') }, ...displayedFolders.map((folder) => ({ title: folder.title, - ...(folderCountersById && folderCountersById[folder.id]), + ...(folderCountersById?.[folder.id]), })), ]; }, [displayedFolders, folderCountersById, lang]); @@ -220,7 +220,7 @@ const ChatFolders: FC = ({ return (
- {folderTabs && folderTabs.length ? ( + {folderTabs?.length ? ( ) : shouldRenderPlaceholder ? (
diff --git a/src/components/left/main/ChatList.tsx b/src/components/left/main/ChatList.tsx index baee3d6b..0ee8296d 100644 --- a/src/components/left/main/ChatList.tsx +++ b/src/components/left/main/ChatList.tsx @@ -206,7 +206,7 @@ const ChatList: FC = ({ noFastList noScrollRestore > - {viewportIds && viewportIds.length && chatArrays ? ( + {viewportIds?.length && chatArrays ? ( renderChats() ) : viewportIds && !viewportIds.length ? ( ( diff --git a/src/components/left/main/ContactList.tsx b/src/components/left/main/ContactList.tsx index c5b16f8b..a427eabe 100644 --- a/src/components/left/main/ContactList.tsx +++ b/src/components/left/main/ContactList.tsx @@ -77,7 +77,7 @@ const ContactList: FC = ({ return ( - {viewportIds && viewportIds.length ? ( + {viewportIds?.length ? ( viewportIds.map((id) => ( ( chatsById, localContactIds, searchQuery, - isSearching: fetchingStatus && fetchingStatus.chats, + isSearching: fetchingStatus?.chats, globalUserIds, localUserIds, }; diff --git a/src/components/left/search/AudioResults.tsx b/src/components/left/search/AudioResults.tsx index 2c2ca3df..e59c55da 100644 --- a/src/components/left/search/AudioResults.tsx +++ b/src/components/left/search/AudioResults.tsx @@ -67,7 +67,7 @@ const AudioResults: FC = ({ return foundIds.map((id) => { const [chatId, messageId] = id.split('_').map(Number); - return globalMessagesByChatId[chatId] && globalMessagesByChatId[chatId].byId[messageId]; + return globalMessagesByChatId[chatId]?.byId[messageId]; }).filter(Boolean); }, [globalMessagesByChatId, foundIds]); diff --git a/src/components/left/search/ChatMessage.tsx b/src/components/left/search/ChatMessage.tsx index b759eaea..3e5eb927 100644 --- a/src/components/left/search/ChatMessage.tsx +++ b/src/components/left/search/ChatMessage.tsx @@ -84,7 +84,7 @@ const ChatMessage: FC = ({ chat={chat} user={privateChatUser} withOnlineStatus - isSavedMessages={privateChatUser && privateChatUser.isSelf} + isSavedMessages={privateChatUser?.isSelf} lastSyncTime={lastSyncTime} />
diff --git a/src/components/left/search/ChatMessageResults.tsx b/src/components/left/search/ChatMessageResults.tsx index f085ccfc..a163f1dd 100644 --- a/src/components/left/search/ChatMessageResults.tsx +++ b/src/components/left/search/ChatMessageResults.tsx @@ -72,9 +72,7 @@ const ChatMessageResults: FC = ({ .map((id) => { const [chatId, messageId] = id.split('_').map(Number); - return ( - globalMessagesByChatId && globalMessagesByChatId[chatId] && globalMessagesByChatId[chatId].byId[messageId] - ); + return globalMessagesByChatId?.[chatId]?.byId[messageId]; }) .filter(Boolean as any) .sort((a, b) => b.date - a.date); @@ -133,7 +131,7 @@ export default memo(withGlobal( const { currentUserId, messages: { byChatId: globalMessagesByChatId }, lastSyncTime } = global; const { fetchingStatus, resultsByType } = global.globalSearch; - const { foundIds } = (resultsByType && resultsByType.text) || {}; + const { foundIds } = (resultsByType?.text) || {}; return { currentUserId, diff --git a/src/components/left/search/ChatResults.tsx b/src/components/left/search/ChatResults.tsx index 3c0a6a33..19ddf171 100644 --- a/src/components/left/search/ChatResults.tsx +++ b/src/components/left/search/ChatResults.tsx @@ -144,9 +144,7 @@ const ChatResults: FC = ({ .map((id) => { const [chatId, messageId] = id.split('_').map(Number); - return ( - globalMessagesByChatId && globalMessagesByChatId[chatId] && globalMessagesByChatId[chatId].byId[messageId] - ); + return globalMessagesByChatId?.[chatId]?.byId[messageId]; }) .filter(Boolean as any) .sort((a, b) => b.date - a.date); @@ -300,7 +298,7 @@ export default memo(withGlobal( const { chatIds: globalChatIds, userIds: globalUserIds } = globalResults || {}; const { chatIds: localChatIds, userIds: localUserIds } = localResults || {}; const { byChatId: globalMessagesByChatId } = messages; - const { foundIds } = (resultsByType && resultsByType.text) || {}; + const foundIds = resultsByType?.text?.foundIds; return { currentUserId, diff --git a/src/components/left/search/FileResults.tsx b/src/components/left/search/FileResults.tsx index a219bb7d..94bd67e1 100644 --- a/src/components/left/search/FileResults.tsx +++ b/src/components/left/search/FileResults.tsx @@ -64,7 +64,7 @@ const FileResults: FC = ({ return foundIds.map((id) => { const [chatId, messageId] = id.split('_').map(Number); - const message = globalMessagesByChatId[chatId] && globalMessagesByChatId[chatId].byId[messageId]; + const message = globalMessagesByChatId[chatId]?.byId[messageId]; return message && getMessageDocument(message) ? message : undefined; }).filter(Boolean) as ApiMessage[]; diff --git a/src/components/left/search/LinkResults.tsx b/src/components/left/search/LinkResults.tsx index 7e141c66..0ef35f2e 100644 --- a/src/components/left/search/LinkResults.tsx +++ b/src/components/left/search/LinkResults.tsx @@ -63,7 +63,7 @@ const LinkResults: FC = ({ return foundIds.map((id) => { const [chatId, messageId] = id.split('_').map(Number); - return globalMessagesByChatId[chatId] && globalMessagesByChatId[chatId].byId[messageId]; + return globalMessagesByChatId[chatId]?.byId[messageId]; }).filter(Boolean); }, [globalMessagesByChatId, foundIds]); diff --git a/src/components/left/search/MediaResults.tsx b/src/components/left/search/MediaResults.tsx index 7f60e7df..8af94c62 100644 --- a/src/components/left/search/MediaResults.tsx +++ b/src/components/left/search/MediaResults.tsx @@ -62,7 +62,7 @@ const MediaResults: FC = ({ return foundIds.map((id) => { const [chatId, messageId] = id.split('_').map(Number); - return globalMessagesByChatId[chatId] && globalMessagesByChatId[chatId].byId[messageId]; + return globalMessagesByChatId[chatId]?.byId[messageId]; }).filter(Boolean); }, [globalMessagesByChatId, foundIds]); diff --git a/src/components/left/search/helpers/createMapStateToProps.ts b/src/components/left/search/helpers/createMapStateToProps.ts index 628f6a78..f59438de 100644 --- a/src/components/left/search/helpers/createMapStateToProps.ts +++ b/src/components/left/search/helpers/createMapStateToProps.ts @@ -28,10 +28,10 @@ export function createMapStateToProps(type: ApiGlobalMessageSearchType) { // One component is used for two different types of results. // The differences between them are only in the isVoice property. // The rest of the search results use their own personal components. - const currentType = type !== 'audio' ? type : (props && props.isVoice ? 'voice' : 'audio'); + const currentType = type !== 'audio' ? type : (props?.isVoice ? 'voice' : 'audio'); const { byChatId: globalMessagesByChatId } = global.messages; - const { foundIds } = (resultsByType && resultsByType[currentType]) || {}; + const foundIds = resultsByType?.[currentType]?.foundIds; return { theme: selectTheme(global), diff --git a/src/components/left/settings/SettingsGeneral.tsx b/src/components/left/settings/SettingsGeneral.tsx index fe03ea0b..4af383ec 100644 --- a/src/components/left/settings/SettingsGeneral.tsx +++ b/src/components/left/settings/SettingsGeneral.tsx @@ -97,7 +97,7 @@ const SettingsGeneral: FC = ({ }, [loadStickerSets]); useEffect(() => { - if (stickerSetIds && stickerSetIds.length) { + if (stickerSetIds?.length) { loadAddedStickers(); } }, [stickerSetIds, loadAddedStickers]); @@ -127,7 +127,7 @@ const SettingsGeneral: FC = ({ }, [openModal]); const stickerSets = stickerSetIds && stickerSetIds.map((id: string) => { - return stickerSetsById && stickerSetsById[id] && stickerSetsById[id].installedDate ? stickerSetsById[id] : false; + return stickerSetsById?.[id]?.installedDate ? stickerSetsById[id] : false; }).filter(Boolean as any); useHistoryBack(isActive, onReset, onScreenSelect, SettingsScreens.General); diff --git a/src/components/left/settings/SettingsGeneralBackground.tsx b/src/components/left/settings/SettingsGeneralBackground.tsx index c2bde98a..85d25238 100644 --- a/src/components/left/settings/SettingsGeneralBackground.tsx +++ b/src/components/left/settings/SettingsGeneralBackground.tsx @@ -95,7 +95,7 @@ const SettingsGeneralBackground: FC = ({ const handleWallPaperSelect = useCallback((slug: string) => { setThemeSettings({ theme: themeRef.current, background: slug }); const currentWallpaper = loadedWallpapers && loadedWallpapers.find((wallpaper) => wallpaper.slug === slug); - if (currentWallpaper && currentWallpaper.document.thumbnail) { + if (currentWallpaper?.document.thumbnail) { getAverageColor(currentWallpaper.document.thumbnail.dataUri) .then((color) => { const patternColor = getPatternColor(color); @@ -113,7 +113,7 @@ const SettingsGeneralBackground: FC = ({ useHistoryBack(isActive, onReset, onScreenSelect, SettingsScreens.GeneralChatBackground); - const isUploading = loadedWallpapers && loadedWallpapers[0] && loadedWallpapers[0].slug === UPLOADING_WALLPAPER_SLUG; + const isUploading = loadedWallpapers?.[0] && loadedWallpapers[0].slug === UPLOADING_WALLPAPER_SLUG; return (
diff --git a/src/components/left/settings/SettingsGeneralBackgroundColor.tsx b/src/components/left/settings/SettingsGeneralBackgroundColor.tsx index c80a33e0..0add0584 100644 --- a/src/components/left/settings/SettingsGeneralBackgroundColor.tsx +++ b/src/components/left/settings/SettingsGeneralBackgroundColor.tsx @@ -109,6 +109,8 @@ const SettingsGeneralBackground: FC = ({ setHsb(positions2hsb({ colorPosition, huePosition }, rectsRef.current!)); markIsDragging(); + + return true; } captureEvents(colorPickerRef.current!, { @@ -126,6 +128,8 @@ const SettingsGeneralBackground: FC = ({ setHsb(positions2hsb({ colorPosition, huePosition }, rectsRef.current!)); markIsDragging(); + + return true; } captureEvents(huePickerRef.current!, { diff --git a/src/components/left/settings/SettingsMain.tsx b/src/components/left/settings/SettingsMain.tsx index d14a13c1..4f1d1a6e 100644 --- a/src/components/left/settings/SettingsMain.tsx +++ b/src/components/left/settings/SettingsMain.tsx @@ -36,7 +36,7 @@ const SettingsMain: FC = ({ lastSyncTime, }) => { const lang = useLang(); - const profileId = currentUser ? currentUser.id : undefined; + const profileId = currentUser?.id; useEffect(() => { if (profileId && lastSyncTime) { diff --git a/src/components/left/settings/SettingsPrivacy.tsx b/src/components/left/settings/SettingsPrivacy.tsx index 46390e9e..d3a77f76 100644 --- a/src/components/left/settings/SettingsPrivacy.tsx +++ b/src/components/left/settings/SettingsPrivacy.tsx @@ -227,11 +227,11 @@ export default memo(withGlobal( sessionsCount: activeSessions.length, isSensitiveEnabled, canChangeSensitive, - visibilityPrivacyPhoneNumber: privacy.phoneNumber && privacy.phoneNumber.visibility, - visibilityPrivacyLastSeen: privacy.lastSeen && privacy.lastSeen.visibility, - visibilityPrivacyProfilePhoto: privacy.profilePhoto && privacy.profilePhoto.visibility, - visibilityPrivacyForwarding: privacy.forwards && privacy.forwards.visibility, - visibilityPrivacyGroupChats: privacy.chatInvite && privacy.chatInvite.visibility, + visibilityPrivacyPhoneNumber: privacy.phoneNumber?.visibility, + visibilityPrivacyLastSeen: privacy.lastSeen?.visibility, + visibilityPrivacyProfilePhoto: privacy.profilePhoto?.visibility, + visibilityPrivacyForwarding: privacy.forwards?.visibility, + visibilityPrivacyGroupChats: privacy.chatInvite?.visibility, }; }, (setGlobal, actions): DispatchProps => pick(actions, [ diff --git a/src/components/left/settings/SettingsPrivacyBlockedUsers.tsx b/src/components/left/settings/SettingsPrivacyBlockedUsers.tsx index ca23808b..0ec373bc 100644 --- a/src/components/left/settings/SettingsPrivacyBlockedUsers.tsx +++ b/src/components/left/settings/SettingsPrivacyBlockedUsers.tsx @@ -82,7 +82,7 @@ const SettingsPrivacyBlockedUsers: FC = (

{renderText((isPrivate ? getUserFullName(user) : getChatTitle(lang, chat!)) || '')}

- {user && user.phoneNumber && ( + {user?.phoneNumber && (
{formatPhoneNumberWithCode(user.phoneNumber)}
)} {user && !user.phoneNumber && user.username && ( @@ -103,7 +103,7 @@ const SettingsPrivacyBlockedUsers: FC = (
- {blockedIds && blockedIds.length ? ( + {blockedIds?.length ? (
{blockedIds!.map((contactId, i) => renderContact(contactId, i, 0))}
diff --git a/src/components/left/settings/SettingsStickerSet.tsx b/src/components/left/settings/SettingsStickerSet.tsx index 1f83ada4..b776921f 100644 --- a/src/components/left/settings/SettingsStickerSet.tsx +++ b/src/components/left/settings/SettingsStickerSet.tsx @@ -32,7 +32,7 @@ const SettingsStickerSet: FC = ({ return undefined; } - const firstSticker = stickerSet.stickers && stickerSet.stickers[0]; + const firstSticker = stickerSet.stickers?.[0]; if (stickerSet.hasThumbnail || !firstSticker) { return ( diff --git a/src/components/left/settings/WallpaperTile.tsx b/src/components/left/settings/WallpaperTile.tsx index f56d0d2d..f05cc1b4 100644 --- a/src/components/left/settings/WallpaperTile.tsx +++ b/src/components/left/settings/WallpaperTile.tsx @@ -37,7 +37,7 @@ const WallpaperTile: FC = ({ const localBlobUrl = document.previewBlobUrl; const previewBlobUrl = useMedia(`${localMediaHash}?size=m`); const thumbRef = useCanvasBlur( - document.thumbnail && document.thumbnail.dataUri, + document.thumbnail?.dataUri, Boolean(previewBlobUrl), true, ); diff --git a/src/components/left/settings/folders/SettingsFoldersChatsPicker.tsx b/src/components/left/settings/folders/SettingsFoldersChatsPicker.tsx index fc289d45..74fd67db 100644 --- a/src/components/left/settings/folders/SettingsFoldersChatsPicker.tsx +++ b/src/components/left/settings/folders/SettingsFoldersChatsPicker.tsx @@ -203,7 +203,7 @@ const SettingsFoldersChatsPicker: FC = ({ )} - {viewportIds && viewportIds.length ? ( + {viewportIds?.length ? ( viewportIds.map(renderItem) ) : viewportIds && !viewportIds.length ? (

Sorry, nothing found.

diff --git a/src/components/left/settings/folders/SettingsFoldersEdit.tsx b/src/components/left/settings/folders/SettingsFoldersEdit.tsx index a1119e90..d899f478 100644 --- a/src/components/left/settings/folders/SettingsFoldersEdit.tsx +++ b/src/components/left/settings/folders/SettingsFoldersEdit.tsx @@ -98,8 +98,8 @@ const SettingsFoldersEdit: FC = ({ const [visibleIncludedChatIds, visibleExcludedChatIds] = useMemo(() => { const allLoadedChatsSet = new Set([ - ...loadedActiveChatIds || [], - ...loadedArchivedChatIds || [], + ...(loadedActiveChatIds || []), + ...(loadedArchivedChatIds || []), ]); const loadedIncludedChatIds = findIntersectionWithSet(includedChatIds, allLoadedChatsSet); diff --git a/src/components/left/settings/folders/SettingsFoldersMain.tsx b/src/components/left/settings/folders/SettingsFoldersMain.tsx index ca43f2d8..908e6ed9 100644 --- a/src/components/left/settings/folders/SettingsFoldersMain.tsx +++ b/src/components/left/settings/folders/SettingsFoldersMain.tsx @@ -172,7 +172,7 @@ const SettingsFoldersMain: FC = ({

{lang('Filters')}

- {userFolders && userFolders.length ? userFolders.map((folder) => ( + {userFolders?.length ? userFolders.map((folder) => ( = ({ const chatIds = useMemo(() => { const listIds = [ - ...activeListIds || [], - ...archivedListIds || [], + ...(activeListIds || []), + ...(archivedListIds || []), ]; let priorityIds = pinnedIds || []; @@ -158,7 +158,7 @@ const ForwardPicker: FC = ({ className="ForwardPicker" header={modalHeader} > - {viewportIds && viewportIds.length ? ( + {viewportIds?.length ? ( = ({ const targetUsers = useMemo(() => { return targetUserIds - ? targetUserIds.map((userId) => usersById && usersById[userId]).filter(Boolean as any) + ? targetUserIds.map((userId) => usersById?.[userId]).filter(Boolean as any) : undefined; }, [targetUserIds, usersById]); diff --git a/src/components/middle/ContactGreeting.tsx b/src/components/middle/ContactGreeting.tsx index 94164c39..b918ca9b 100644 --- a/src/components/middle/ContactGreeting.tsx +++ b/src/components/middle/ContactGreeting.tsx @@ -94,7 +94,7 @@ const ContactGreeting: FC = ({ export default memo(withGlobal( (global, { userId }): StateProps => { const { stickers } = global.stickers.greeting; - const sticker = stickers && stickers.length ? stickers[userId % stickers.length] : undefined; + const sticker = stickers?.length ? stickers[userId % stickers.length] : undefined; const chat = selectChat(global, userId); if (!chat) { return {}; diff --git a/src/components/middle/HeaderActions.tsx b/src/components/middle/HeaderActions.tsx index fe9b068f..286edff9 100644 --- a/src/components/middle/HeaderActions.tsx +++ b/src/components/middle/HeaderActions.tsx @@ -208,7 +208,7 @@ export default memo(withGlobal( const chat = selectChat(global, chatId); const isChannel = Boolean(chat && isChatChannel(chat)); - if (chat && chat.isRestricted) { + if (chat?.isRestricted) { return { noMenu: true, }; diff --git a/src/components/middle/MessageList.tsx b/src/components/middle/MessageList.tsx index 070ec430..ffeca5f8 100644 --- a/src/components/middle/MessageList.tsx +++ b/src/components/middle/MessageList.tsx @@ -445,7 +445,7 @@ const MessageList: FC = ({ && (!listItemElementsRef.current || listItemElementsRef.current.length === 0) ) || checkSingleMessageActionByType('contactSignUp', messageGroups) - || (lastMessage && lastMessage.content.action && lastMessage.content.action.type === 'contactSignUp') + || (lastMessage?.content.action && lastMessage.content.action.type === 'contactSignUp') ); const isGroupChatJustCreated = isGroupChat && isCreator && checkSingleMessageActionByType('chatCreate', messageGroups); diff --git a/src/components/middle/MiddleColumn.tsx b/src/components/middle/MiddleColumn.tsx index fe715f97..54e070ee 100644 --- a/src/components/middle/MiddleColumn.tsx +++ b/src/components/middle/MiddleColumn.tsx @@ -436,11 +436,11 @@ export default memo(withGlobal( canPost: !isPinnedMessageList && (!chat || canPost) && !isBotNotStarted, isPinnedMessageList, isScheduledMessageList, - currentUserBannedRights: chat && chat.currentUserBannedRights, - defaultBannedRights: chat && chat.defaultBannedRights, + currentUserBannedRights: chat?.currentUserBannedRights, + defaultBannedRights: chat?.defaultBannedRights, hasPinnedOrAudioMessage: ( threadId !== MAIN_THREAD_ID - || Boolean(pinnedIds && pinnedIds.length) + || Boolean(pinnedIds?.length) || Boolean(audioChatId && audioMessageId) ), pinnedMessagesCount: pinnedIds ? pinnedIds.length : 0, diff --git a/src/components/middle/MiddleHeader.tsx b/src/components/middle/MiddleHeader.tsx index 45a25981..c332cb80 100644 --- a/src/components/middle/MiddleHeader.tsx +++ b/src/components/middle/MiddleHeader.tsx @@ -430,10 +430,10 @@ export default memo(withGlobal( let messagesCount: number | undefined; if (messageListType === 'pinned') { const pinnedIds = selectPinnedIds(global, chatId); - messagesCount = pinnedIds && pinnedIds.length; + messagesCount = pinnedIds?.length; } else if (messageListType === 'scheduled') { const scheduledIds = selectScheduledIds(global, chatId); - messagesCount = scheduledIds && scheduledIds.length; + messagesCount = scheduledIds?.length; } else if (messageListType === 'thread' && threadId !== MAIN_THREAD_ID) { const threadInfo = selectThreadInfo(global, chatId, threadId); if (threadInfo) { @@ -479,7 +479,7 @@ export default memo(withGlobal( } const pinnedMessageIds = selectPinnedIds(global, chatId); - if (pinnedMessageIds && pinnedMessageIds.length) { + if (pinnedMessageIds?.length) { const firstPinnedMessage = messagesById[pinnedMessageIds[0]]; const { canUnpin, diff --git a/src/components/middle/MobileSearch.tsx b/src/components/middle/MobileSearch.tsx index ba2b44a2..c8fa22c4 100644 --- a/src/components/middle/MobileSearch.tsx +++ b/src/components/middle/MobileSearch.tsx @@ -158,7 +158,7 @@ const MobileSearchFooter: FC = ({
{query ? ( - foundIds && foundIds.length ? ( + foundIds?.length ? ( `${focusedIndex + 1} of ${totalCount}` ) : foundIds && !foundIds.length ? ( 'No results' diff --git a/src/components/middle/PinnedMessageNavigation.tsx b/src/components/middle/PinnedMessageNavigation.tsx index e95afeeb..be0d4517 100644 --- a/src/components/middle/PinnedMessageNavigation.tsx +++ b/src/components/middle/PinnedMessageNavigation.tsx @@ -40,7 +40,7 @@ const PinnedMessageNavigation: FC = ({ } = markupParams; const firstChild = containerRef.current.firstElementChild; - if (containerRef && containerRef.current) { + if (containerRef?.current) { const currentElement = containerRef.current; const { style } = currentElement; style.height = `${trackHeight}px`; diff --git a/src/components/middle/composer/AttachmentModal.tsx b/src/components/middle/composer/AttachmentModal.tsx index 117612c2..c6a93aac 100644 --- a/src/components/middle/composer/AttachmentModal.tsx +++ b/src/components/middle/composer/AttachmentModal.tsx @@ -125,7 +125,7 @@ const AttachmentModal: FC = ({ const { dataTransfer: { files } } = e; - if (files && files.length) { + if (files?.length) { const newFiles = isQuick ? Array.from(files).filter((file) => { return file.type && CONTENT_TYPES_FOR_QUICK_UPLOAD.has(file.type); diff --git a/src/components/middle/composer/Composer.tsx b/src/components/middle/composer/Composer.tsx index e22952f7..fab93a6c 100644 --- a/src/components/middle/composer/Composer.tsx +++ b/src/components/middle/composer/Composer.tsx @@ -1097,16 +1097,16 @@ export default memo(withGlobal( withScheduledButton: ( threadId === MAIN_THREAD_ID && messageListType === 'thread' - && Boolean(scheduledIds && scheduledIds.length) + && Boolean(scheduledIds?.length) ), shouldSchedule: messageListType === 'scheduled', botKeyboardMessageId, - botKeyboardPlaceholder: keyboardMessage ? keyboardMessage.keyboardPlaceholder : undefined, + botKeyboardPlaceholder: keyboardMessage?.keyboardPlaceholder, isForwarding: chatId === global.forwardMessages.toChatId, isPollModalOpen: global.isPollModalOpen, stickersForEmoji: global.stickers.forEmoji.stickers, - groupChatMembers: chat && chat.fullInfo && chat.fullInfo.members, - topInlineBotIds: global.topInlineBots && global.topInlineBots.userIds, + groupChatMembers: chat?.fullInfo?.members, + topInlineBotIds: global.topInlineBots?.userIds, currentUserId: global.currentUserId, usersById: global.users.byId, lastSyncTime: global.lastSyncTime, @@ -1115,8 +1115,8 @@ export default memo(withGlobal( isReceiptModalOpen: Boolean(global.payment.receipt), shouldSuggestStickers: global.settings.byKey.shouldSuggestStickers, recentEmojis: global.recentEmojis, - baseEmojiKeywords: baseEmojiKeywords ? baseEmojiKeywords.keywords : undefined, - emojiKeywords: emojiKeywords ? emojiKeywords.keywords : undefined, + baseEmojiKeywords: baseEmojiKeywords?.keywords, + emojiKeywords: emojiKeywords?.keywords, serverTimeOffset: global.serverTimeOffset, inlineBots: global.inlineBots.byUsername, isInlineBotLoading: global.inlineBots.isLoading, diff --git a/src/components/middle/composer/EmojiPicker.tsx b/src/components/middle/composer/EmojiPicker.tsx index cc7d9000..b2ae80d9 100644 --- a/src/components/middle/composer/EmojiPicker.tsx +++ b/src/components/middle/composer/EmojiPicker.tsx @@ -124,7 +124,7 @@ const EmojiPicker: FC = ({ return MEMO_EMPTY_ARRAY; } const themeCategories = [...categories]; - if (recentEmojis && recentEmojis.length) { + if (recentEmojis?.length) { themeCategories.unshift({ id: 'recent', name: lang('RecentStickers'), diff --git a/src/components/middle/composer/InlineBotTooltip.tsx b/src/components/middle/composer/InlineBotTooltip.tsx index f7b7a985..d04555c8 100644 --- a/src/components/middle/composer/InlineBotTooltip.tsx +++ b/src/components/middle/composer/InlineBotTooltip.tsx @@ -92,7 +92,7 @@ const InlineBotTooltip: FC = ({ }, [botId, openChat, startBot, switchPm]); const prevInlineBotResults = usePrevious( - inlineBotResults && inlineBotResults.length + inlineBotResults?.length ? inlineBotResults : undefined, shouldRender, diff --git a/src/components/middle/composer/MentionTooltip.tsx b/src/components/middle/composer/MentionTooltip.tsx index aecadfce..d4586111 100644 --- a/src/components/middle/composer/MentionTooltip.tsx +++ b/src/components/middle/composer/MentionTooltip.tsx @@ -35,7 +35,7 @@ const MentionTooltip: FC = ({ const { shouldRender, transitionClassNames } = useShowTransition(isOpen, undefined, undefined, false); const handleUserSelect = useCallback((userId: number, forceFocus = false) => { - const user = usersById && usersById[userId]; + const user = usersById?.[userId]; if (!user) { return; } @@ -66,7 +66,7 @@ const MentionTooltip: FC = ({ }, [filteredUsers, onClose]); const prevChatMembers = usePrevious( - filteredUsers && filteredUsers.length + filteredUsers?.length ? filteredUsers : undefined, shouldRender, @@ -86,7 +86,7 @@ const MentionTooltip: FC = ({ return (
- {renderedChatMembers && renderedChatMembers.map(({ id }, index) => ( + {renderedChatMembers?.map(({ id }, index) => ( = ({ const noPopulatedSets = useMemo(() => ( areAddedLoaded - && allSets.filter((set) => set.stickers && set.stickers.length).length === 0 + && allSets.filter((set) => set.stickers?.length).length === 0 ), [allSets, areAddedLoaded]); useEffect(() => { @@ -143,7 +143,7 @@ const StickerPicker: FC = ({ }, [loadAndPlay, loadFavoriteStickers, loadRecentStickers, loadStickerSets]); useEffect(() => { - if (addedSetIds && addedSetIds.length) { + if (addedSetIds?.length) { loadAddedStickers(); } }, [addedSetIds, loadAddedStickers]); @@ -184,7 +184,7 @@ const StickerPicker: FC = ({ const canRenderContents = useAsyncRendering([], SLIDE_TRANSITION_DURATION); function renderCover(stickerSet: StickerSetOrRecent, index: number) { - const firstSticker = stickerSet.stickers && stickerSet.stickers[0]; + const firstSticker = stickerSet.stickers?.[0]; const buttonClassName = buildClassName( 'symbol-set-button sticker-set-button', index === activeSetIndex && 'activated', diff --git a/src/components/middle/composer/StickerTooltip.tsx b/src/components/middle/composer/StickerTooltip.tsx index d07946d6..3427b22e 100644 --- a/src/components/middle/composer/StickerTooltip.tsx +++ b/src/components/middle/composer/StickerTooltip.tsx @@ -62,7 +62,7 @@ const StickerTooltip: FC = ({ const className = buildClassName( 'StickerTooltip composer-tooltip custom-scroll', transitionClassNames, - !(displayedStickers && displayedStickers.length) && 'hidden', + !(displayedStickers?.length) && 'hidden', ); return ( diff --git a/src/components/middle/composer/hooks/useClipboardPaste.ts b/src/components/middle/composer/hooks/useClipboardPaste.ts index be673690..30b03474 100644 --- a/src/components/middle/composer/hooks/useClipboardPaste.ts +++ b/src/components/middle/composer/hooks/useClipboardPaste.ts @@ -43,7 +43,7 @@ export default ( } if (pastedText) { - insertTextAndUpdateCursor(pastedText, input ? input.id : undefined); + insertTextAndUpdateCursor(pastedText, input?.id); } } diff --git a/src/components/middle/composer/hooks/useInlineBotTooltip.ts b/src/components/middle/composer/hooks/useInlineBotTooltip.ts index 17a77b10..bbe3de96 100644 --- a/src/components/middle/composer/hooks/useInlineBotTooltip.ts +++ b/src/components/middle/composer/hooks/useInlineBotTooltip.ts @@ -21,7 +21,7 @@ export default function useInlineBotTooltip( const usernameLowered = username.toLowerCase(); const prevQuery = usePrevious(query); const prevUsername = usePrevious(username); - const inlineBotData = inlineBots && inlineBots[usernameLowered]; + const inlineBotData = inlineBots?.[usernameLowered]; const { id: botId, switchPm, @@ -50,7 +50,7 @@ export default function useInlineBotTooltip( }, [offset, chatId, query, queryInlineBot, usernameLowered]); useEffect(() => { - if (isAllowed && botId && (switchPm || (results && results.length))) { + if (isAllowed && botId && (switchPm || (results?.length))) { markIsOpen(); } else { unmarkIsOpen(); diff --git a/src/components/middle/composer/hooks/useMentionTooltip.ts b/src/components/middle/composer/hooks/useMentionTooltip.ts index 31663b1a..b8606e7d 100644 --- a/src/components/middle/composer/hooks/useMentionTooltip.ts +++ b/src/components/middle/composer/hooks/useMentionTooltip.ts @@ -38,7 +38,7 @@ export default function useMentionTooltip( const [usersToMention, setUsersToMention] = useState(); const topInlineBots = useMemo(() => { - return (topInlineBotIds || []).map((id) => usersById && usersById[id]).filter(Boolean as any); + return (topInlineBotIds || []).map((id) => usersById?.[id]).filter(Boolean as any); }, [topInlineBotIds, usersById]); const getFilteredUsers = useCallback((filter, withInlineBots: boolean) => { @@ -83,7 +83,7 @@ export default function useMentionTooltip( }, [canSuggestMembers, html, getFilteredUsers, markIsOpen, unmarkIsOpen]); useEffect(() => { - if (usersToMention && usersToMention.length) { + if (usersToMention?.length) { markIsOpen(); } else { unmarkIsOpen(); diff --git a/src/components/middle/composer/inlineResults/MediaResult.tsx b/src/components/middle/composer/inlineResults/MediaResult.tsx index eba47c5b..823cfdfe 100644 --- a/src/components/middle/composer/inlineResults/MediaResult.tsx +++ b/src/components/middle/composer/inlineResults/MediaResult.tsx @@ -50,7 +50,7 @@ const MediaResult: FC = ({ return (
{shouldRenderThumb && ( - + )} {shouldRenderFullMedia && ( @@ -64,7 +64,7 @@ const MediaResult: FC = ({ return ( 12) { + if (parts?.[0] && Number(parts[0]) > 12) { parts[0] = '12'; } - if (parts && parts[0] && parts[0].length === 2 && !parts[1]) { + if (parts?.[0] && parts[0].length === 2 && !parts[1]) { parts[1] = ''; } return parts ? parts.join('/') : ''; diff --git a/src/components/middle/message/Album.tsx b/src/components/middle/message/Album.tsx index a0f76483..5bb7a359 100644 --- a/src/components/middle/message/Album.tsx +++ b/src/components/middle/message/Album.tsx @@ -59,13 +59,13 @@ const Album: FC = ({ function renderAlbumMessage(message: ApiMessage, index: number) { const { photo, video } = getMessageContent(message); const fileUpload = uploadsById[message.previousLocalId || message.id]; - const uploadProgress = fileUpload ? fileUpload.progress : undefined; + const uploadProgress = fileUpload?.progress; const { dimensions, sides } = albumLayout.layout[index]; if (photo) { const shouldAffectAppendix = hasCustomAppendix && ( // eslint-disable-next-line no-bitwise - isOwn ? index === mediaCount - 1 : Boolean(sides & AlbumRectPart.Left && sides & AlbumRectPart.Bottom) + (isOwn ? index === mediaCount - 1 : Boolean(sides & AlbumRectPart.Left && sides & AlbumRectPart.Bottom)) ); return ( diff --git a/src/components/middle/message/ContextMenuContainer.tsx b/src/components/middle/message/ContextMenuContainer.tsx index 33ebc968..6d068c6a 100644 --- a/src/components/middle/message/ContextMenuContainer.tsx +++ b/src/components/middle/message/ContextMenuContainer.tsx @@ -152,7 +152,7 @@ const ContextMenuContainer: FC = ({ const handleForward = useCallback(() => { closeMenu(); - if (album && album.messages) { + if (album?.messages) { const messageIds = album.messages.map(({ id }) => id); openForwardMenu({ fromChatId: message.chatId, messageIds }); } else { @@ -171,7 +171,7 @@ const ContextMenuContainer: FC = ({ }, [closeMenu, message.content.sticker, unfaveSticker]); const handleSelectMessage = useCallback(() => { - const params = album && album.messages + const params = album?.messages ? { messageId: message.id, childMessageIds: album.messages.map(({ id }) => id), diff --git a/src/components/middle/message/Message.tsx b/src/components/middle/message/Message.tsx index 534d5e89..00b0b227 100644 --- a/src/components/middle/message/Message.tsx +++ b/src/components/middle/message/Message.tsx @@ -290,7 +290,7 @@ const Message: FC = ({ toggleMessageSelection({ messageId, groupedId, - ...(e && e.shiftKey && { withShift: true }), + ...(e?.shiftKey && { withShift: true }), ...(isAlbum && { childMessageIds: album!.messages.map(({ id }) => id) }), }); }, [isLocal, toggleMessageSelection, messageId, isAlbum, album]); @@ -432,9 +432,9 @@ const Message: FC = ({ function renderAvatar() { const isAvatarPeerUser = avatarPeer && isChatPrivate(avatarPeer.id); - const avatarUser = avatarPeer && isAvatarPeerUser ? avatarPeer as ApiUser : undefined; - const avatarChat = avatarPeer && !isAvatarPeerUser ? avatarPeer as ApiChat : undefined; - const hiddenName = !avatarPeer && forwardInfo ? forwardInfo.hiddenUserName : undefined; + const avatarUser = (avatarPeer && isAvatarPeerUser) ? avatarPeer as ApiUser : undefined; + const avatarChat = (avatarPeer && !isAvatarPeerUser) ? avatarPeer as ApiChat : undefined; + const hiddenName = (!avatarPeer && forwardInfo) ? forwardInfo.hiddenUserName : undefined; return ( = ({ if (!asForwarded) { senderColor = `color-${getUserColorKey(senderPeer)}`; } - } else if (forwardInfo && forwardInfo.hiddenUserName) { + } else if (forwardInfo?.hiddenUserName) { senderTitle = forwardInfo.hiddenUserName; } @@ -644,7 +644,7 @@ const Message: FC = ({ )} - {forwardInfo && forwardInfo.isLinkedChannelPost ? ( + {forwardInfo?.isLinkedChannelPost ? ( {lang('DiscussChannel')} ) : message.adminTitle && !isChannel ? ( {message.adminTitle} @@ -795,7 +795,7 @@ export default memo(withGlobal( const chat = selectChat(global, chatId); const isChatWithSelf = selectIsChatWithSelf(global, chatId); const isChannel = chat && isChatChannel(chat); - const chatUsername = chat && chat.username; + const chatUsername = chat?.username; const forceSenderName = !isChatWithSelf && isAnonymousOwnMessage(message); const canShowSender = withSenderName || withAvatar || forceSenderName; @@ -830,7 +830,7 @@ export default memo(withGlobal( const singleEmoji = getMessageSingleEmoji(message); let isSelected: boolean; - if (album && album.messages) { + if (album?.messages) { isSelected = album.messages.every(({ id: messageId }) => selectIsMessageSelected(global, messageId)); } else { isSelected = selectIsMessageSelected(global, id); diff --git a/src/components/middle/message/PollOption.tsx b/src/components/middle/message/PollOption.tsx index cb45f3dc..9bca5779 100644 --- a/src/components/middle/message/PollOption.tsx +++ b/src/components/middle/message/PollOption.tsx @@ -28,7 +28,7 @@ const PollOption: FC = ({ }) => { const result = voteResults && voteResults.find((r) => r.option === answer.option); const correctAnswer = correctResults.length === 0 || correctResults.indexOf(answer.option) !== -1; - const showIcon = (correctResults.length > 0 && correctAnswer) || (result && result.isChosen); + const showIcon = (correctResults.length > 0 && correctAnswer) || (result?.isChosen); const answerPercent = result ? getPercentage(result.votersCount, totalVoters || 0) : 0; const [finalPercent, setFinalPercent] = useState(shouldAnimate ? 0 : answerPercent); // eslint-disable-next-line no-null/no-null diff --git a/src/components/middle/message/Video.tsx b/src/components/middle/message/Video.tsx index b34ec521..c0b2520d 100644 --- a/src/components/middle/message/Video.tsx +++ b/src/components/middle/message/Video.tsx @@ -107,7 +107,7 @@ const Video: FC = ({ setPlayProgress(Math.max(0, e.currentTarget.currentTime - 1)); }, []); - const duration = (videoRef.current && videoRef.current.duration) || video.duration || 0; + const duration = (videoRef.current?.duration) || video.duration || 0; const isOwn = isOwnMessage(message); const isForwarded = isForwardedMessage(message); diff --git a/src/components/middle/message/WebPage.tsx b/src/components/middle/message/WebPage.tsx index 23c18cdd..bb9c99ac 100644 --- a/src/components/middle/message/WebPage.tsx +++ b/src/components/middle/message/WebPage.tsx @@ -43,7 +43,7 @@ const WebPage: FC = ({ const webPage = getMessageWebPage(message); let isSquarePhoto = false; - if (webPage && webPage.photo && !webPage.video) { + if (webPage?.photo && !webPage.video) { const { width, height } = calculateMediaDimensions(message); isSquarePhoto = width === height; } diff --git a/src/components/middle/message/helpers/buildContentClassName.ts b/src/components/middle/message/helpers/buildContentClassName.ts index 7d6a9fb3..e823c6ac 100644 --- a/src/components/middle/message/helpers/buildContentClassName.ts +++ b/src/components/middle/message/helpers/buildContentClassName.ts @@ -49,7 +49,7 @@ export function buildContentClassName( if (customShape) { classNames.push('custom-shape'); - if (video && video.isRound) { + if (video?.isRound) { classNames.push('round'); } diff --git a/src/components/middle/message/helpers/copyOptions.ts b/src/components/middle/message/helpers/copyOptions.ts index 0d919c57..69432db7 100644 --- a/src/components/middle/message/helpers/copyOptions.ts +++ b/src/components/middle/message/helpers/copyOptions.ts @@ -44,9 +44,7 @@ export function getMessageCopyOptions( if (text) { // Detect if the user has selection in the current message const hasSelection = Boolean(( - selection - && selection.anchorNode - && selection.anchorNode.parentNode + selection?.anchorNode?.parentNode && (selection.anchorNode.parentNode as HTMLElement).closest('.Message .content-inner') && selection.toString().replace(/(?:\r\n|\r|\n)/g, '') !== '' )); diff --git a/src/components/middle/message/hocs/withSelectControl.tsx b/src/components/middle/message/hocs/withSelectControl.tsx index d55902c0..a5d76e57 100644 --- a/src/components/middle/message/hocs/withSelectControl.tsx +++ b/src/components/middle/message/hocs/withSelectControl.tsx @@ -40,7 +40,7 @@ export default function withSelectControl(WrappedComponent: FC) { const handleMessageSelect = useCallback((e: ReactMouseEvent) => { e.stopPropagation(); - toggleMessageSelection({ messageId: message.id, withShift: e && e.shiftKey }); + toggleMessageSelection({ messageId: message.id, withShift: e?.shiftKey }); }, [toggleMessageSelection, message]); const newProps = useMemo(() => { diff --git a/src/components/payment/PaymentModal.tsx b/src/components/payment/PaymentModal.tsx index d79fef6b..4f083240 100644 --- a/src/components/payment/PaymentModal.tsx +++ b/src/components/payment/PaymentModal.tsx @@ -93,7 +93,7 @@ const Invoice: FC = ({ }, [step, error]); useEffect(() => { - if (error && error.field) { + if (error?.field) { paymentDispatch({ type: 'setFormErrors', payload: { @@ -416,7 +416,7 @@ function findShippingOption(shippingOptions: ShippingOption[], optionId: string) function getShippingPrices(shippingOptions: ShippingOption[], shippingOption: string) { const option = findShippingOption(shippingOptions, shippingOption); - return option ? option.prices : undefined; + return option?.prices; } function getTotalPrice(prices: Price[] = [], shippingOptions: ShippingOption[] | undefined, shippingOption: string) { @@ -439,7 +439,7 @@ function getCheckoutInfo(state: FormState, shippingOptions: ShippingOption[] | u : undefined; const { phone, fullName: name } = state; const shippingOption = shippingOptions ? findShippingOption(shippingOptions, state.shipping) : undefined; - const shippingMethod = shippingOption ? shippingOption.title : undefined; + const shippingMethod = shippingOption?.title; return { paymentMethod, paymentProvider, diff --git a/src/components/payment/ReceiptModal.tsx b/src/components/payment/ReceiptModal.tsx index ff7153e8..a90ea20b 100644 --- a/src/components/payment/ReceiptModal.tsx +++ b/src/components/payment/ReceiptModal.tsx @@ -136,7 +136,7 @@ function getCheckoutInfo(paymentMethod?: string, return { paymentMethod }; } const { shippingAddress } = info; - const fullAddress = shippingAddress && shippingAddress.streetLine1 + const fullAddress = shippingAddress?.streetLine1 ? `${shippingAddress.streetLine1}, ${shippingAddress.city}, ${shippingAddress.countryIso2}` : undefined; const { phone, name } = info; diff --git a/src/components/right/AddChatMembers.tsx b/src/components/right/AddChatMembers.tsx index 812b174e..0a1bca01 100644 --- a/src/components/right/AddChatMembers.tsx +++ b/src/components/right/AddChatMembers.tsx @@ -186,7 +186,7 @@ export default memo(withGlobal( return { isChannel, - members: chat && chat.fullInfo ? chat.fullInfo.members : undefined, + members: chat?.fullInfo?.members, currentUserId, usersById, chatsById, diff --git a/src/components/right/PollAnswerResults.tsx b/src/components/right/PollAnswerResults.tsx index f5c8de90..8e04c5c7 100644 --- a/src/components/right/PollAnswerResults.tsx +++ b/src/components/right/PollAnswerResults.tsx @@ -136,8 +136,8 @@ export default memo(withGlobal( const { voters, offsets } = global.pollResults; return { - voters: voters && voters[answer.option], - offset: (offsets && offsets[answer.option]) || '', + voters: voters?.[answer.option], + offset: (offsets?.[answer.option]) || '', }; }, (global, actions): DispatchProps => pick(actions, ['loadPollOptionResults', 'openChat', 'closePollResults']), diff --git a/src/components/right/Profile.tsx b/src/components/right/Profile.tsx index 6bd6ed31..f87476d4 100644 --- a/src/components/right/Profile.tsx +++ b/src/components/right/Profile.tsx @@ -438,7 +438,7 @@ export default memo(withGlobal( const isGroup = chat && isChatGroup(chat); const isChannel = chat && isChatChannel(chat); const hasMembersTab = isGroup || (isChannel && isChatAdmin(chat!)); - const members = chat && chat.fullInfo && chat.fullInfo.members; + const members = chat?.fullInfo?.members; const areMembersHidden = hasMembersTab && chat && chat.fullInfo && !chat.fullInfo.canViewMembers; const canAddMembers = hasMembersTab && chat && (getHasAdminRight(chat, 'inviteUsers') || chat.isCreator); const canDeleteMembers = hasMembersTab && chat && (getHasAdminRight(chat, 'banUsers') || chat.isCreator); @@ -463,7 +463,7 @@ export default memo(withGlobal( canDeleteMembers, currentUserId: global.currentUserId, isRightColumnShown: selectIsRightColumnShown(global), - isRestricted: chat && chat.isRestricted, + isRestricted: chat?.isRestricted, lastSyncTime: global.lastSyncTime, serverTimeOffset: global.serverTimeOffset, ...(hasMembersTab && members && { diff --git a/src/components/right/RightSearch.tsx b/src/components/right/RightSearch.tsx index 97f559eb..5ca0be1a 100644 --- a/src/components/right/RightSearch.tsx +++ b/src/components/right/RightSearch.tsx @@ -135,7 +135,7 @@ const RightSearch: FC = ({ // eslint-disable-next-line no-null/no-null const containerRef = useRef(null); const handleKeyDown = useKeyboardListNavigation(containerRef, true, (index) => { - const foundResult = foundResults && foundResults[index === -1 ? 0 : index]; + const foundResult = foundResults?.[index === -1 ? 0 : index]; if (foundResult) { foundResult.onClick(); } diff --git a/src/components/right/StickerSetResult.tsx b/src/components/right/StickerSetResult.tsx index dcac7af9..a58b8e8c 100644 --- a/src/components/right/StickerSetResult.tsx +++ b/src/components/right/StickerSetResult.tsx @@ -41,7 +41,7 @@ const StickerSetResult: FC = ({ }) => { const lang = useLang(); const isAdded = set && Boolean(set.installedDate); - const areStickersLoaded = Boolean(set && set.stickers); + const areStickersLoaded = Boolean(set?.stickers); const [isModalOpen, openModal, closeModal] = useFlag(); @@ -57,7 +57,7 @@ const StickerSetResult: FC = ({ const coverStickerIds = (set.covers || []).map(({ id }) => id); const otherStickers = set.stickers ? set.stickers.filter(({ id }) => !coverStickerIds.includes(id)) : []; - return [...set.covers || [], ...otherStickers].slice(0, STICKERS_TO_DISPLAY); + return [...(set.covers || []), ...otherStickers].slice(0, STICKERS_TO_DISPLAY); }, [set]); useEffect(() => { diff --git a/src/components/right/management/ManageChannel.tsx b/src/components/right/management/ManageChannel.tsx index 48b6230c..ffbfdb8e 100644 --- a/src/components/right/management/ManageChannel.tsx +++ b/src/components/right/management/ManageChannel.tsx @@ -63,8 +63,8 @@ const ManageChannel: FC = ({ isActive, }) => { const currentTitle = chat ? (chat.title || '') : ''; - const currentAbout = chat && chat.fullInfo ? (chat.fullInfo.about || '') : ''; - const hasLinkedChat = chat && chat.fullInfo && chat.fullInfo.linkedChatId; + const currentAbout = chat?.fullInfo ? (chat.fullInfo.about || '') : ''; + const hasLinkedChat = chat?.fullInfo?.linkedChatId; const [isDeleteDialogOpen, openDeleteDialog, closeDeleteDialog] = useFlag(); const [isProfileFieldsTouched, setIsProfileFieldsTouched] = useState(false); @@ -85,7 +85,7 @@ const ManageChannel: FC = ({ } }, [progress]); - const adminsCount = (chat && chat.fullInfo && chat.fullInfo.adminMembers && chat.fullInfo.adminMembers.length) || 0; + const adminsCount = (chat?.fullInfo?.adminMembers?.length) || 0; const handleClickEditType = useCallback(() => { onScreenSelect(ManagementScreens.ChatPrivacyType); @@ -220,7 +220,7 @@ const ManageChannel: FC = ({ onClick={handleClickSubscribers} > {lang('ChannelSubscribers')} - {lang('Subscribers', chat.membersCount!, 'i')} + {lang('Subscribers', chat.membersCount ?? 0, 'i')}
@@ -257,7 +257,7 @@ export default memo(withGlobal( (global, { chatId }): StateProps => { const chat = selectChat(global, chatId)!; const { progress } = global.management; - const isSignaturesShown = Boolean(chat && chat.isSignaturesShown); + const isSignaturesShown = Boolean(chat?.isSignaturesShown); return { chat, diff --git a/src/components/right/management/ManageChatPrivacyType.tsx b/src/components/right/management/ManageChatPrivacyType.tsx index 097fb63d..91c4c3fa 100644 --- a/src/components/right/management/ManageChatPrivacyType.tsx +++ b/src/components/right/management/ManageChatPrivacyType.tsx @@ -54,7 +54,7 @@ const ManageChatPrivacyType: FC = ({ updatePrivateLink, }) => { const isPublic = Boolean(chat.username); - const privateLink = chat.fullInfo && chat.fullInfo.inviteLink; + const privateLink = chat.fullInfo?.inviteLink; const [privacyType, setPrivacyType] = useState(isPublic ? 'public' : 'private'); const [username, setUsername] = useState(); diff --git a/src/components/right/management/ManageDiscussion.tsx b/src/components/right/management/ManageDiscussion.tsx index 997066b4..9e1983c4 100644 --- a/src/components/right/management/ManageDiscussion.tsx +++ b/src/components/right/management/ManageDiscussion.tsx @@ -62,7 +62,7 @@ const ManageDiscussion: FC = ({ const [isConfirmUnlinkGroupDialogOpen, openConfirmUnlinkGroupDialog, closeConfirmUnlinkGroupDialog] = useFlag(); const [isConfirmLinkGroupDialogOpen, openConfirmLinkGroupDialog, closeConfirmLinkGroupDialog] = useFlag(); const lang = useLang(); - const linkedChatId = linkedChat && linkedChat.id; + const linkedChatId = linkedChat?.id; useHistoryBack(isActive, onClose); @@ -261,7 +261,7 @@ export default memo(withGlobal( (global, { chatId }): StateProps => { const chat = selectChat(global, chatId); const { forDiscussionIds, byId: chatsByIds } = global.chats; - const linkedChat = chat && chat.fullInfo && chat.fullInfo.linkedChatId + const linkedChat = chat?.fullInfo?.linkedChatId ? selectChat(global, chat.fullInfo.linkedChatId) : undefined; diff --git a/src/components/right/management/ManageGroup.tsx b/src/components/right/management/ManageGroup.tsx index b0eaeddd..cd60c1df 100644 --- a/src/components/right/management/ManageGroup.tsx +++ b/src/components/right/management/ManageGroup.tsx @@ -185,7 +185,7 @@ const ManageGroup: FC = ({ return totalCount; }, [chat]); - const adminsCount = (chat.fullInfo && chat.fullInfo.adminMembers && chat.fullInfo.adminMembers.length) || 0; + const adminsCount = (chat.fullInfo?.adminMembers?.length) || 0; const handleDeleteGroup = useCallback(() => { if (isBasicGroup) { @@ -273,7 +273,7 @@ const ManageGroup: FC = ({
{lang('GroupMembers')} - {formatInteger(chat.membersCount!)} + {formatInteger(chat.membersCount ?? 0)} {chat.fullInfo && ( @@ -326,7 +326,7 @@ export default memo(withGlobal( (global, { chatId }): StateProps => { const chat = selectChat(global, chatId)!; const { progress } = global.management; - const hasLinkedChannel = Boolean(chat.fullInfo && chat.fullInfo.linkedChatId); + const hasLinkedChannel = Boolean(chat.fullInfo?.linkedChatId); const isBasicGroup = isChatBasicGroup(chat); return { diff --git a/src/components/right/management/ManageGroupAdminRights.tsx b/src/components/right/management/ManageGroupAdminRights.tsx index 74a551f0..ce2d0675 100644 --- a/src/components/right/management/ManageGroupAdminRights.tsx +++ b/src/components/right/management/ManageGroupAdminRights.tsx @@ -73,14 +73,14 @@ const ManageGroupAdminRights: FC = ({ }, [chat, selectedChatMemberId]); useEffect(() => { - if (chat && chat.fullInfo && selectedChatMemberId && !selectedChatMember) { + if (chat?.fullInfo && selectedChatMemberId && !selectedChatMember) { onScreenSelect(ManagementScreens.ChatAdministrators); } }, [chat, onScreenSelect, selectedChatMember, selectedChatMemberId]); useEffect(() => { - setPermissions((selectedChatMember && selectedChatMember.adminRights) || {}); - setCustomTitle(((selectedChatMember && selectedChatMember.customTitle) || '').substr(0, CUSTOM_TITLE_MAX_LENGTH)); + setPermissions((selectedChatMember?.adminRights) || {}); + setCustomTitle(((selectedChatMember?.customTitle) || '').substr(0, CUSTOM_TITLE_MAX_LENGTH)); setIsTouched(false); setIsLoading(false); }, [selectedChatMember]); diff --git a/src/components/right/management/ManageGroupMembers.tsx b/src/components/right/management/ManageGroupMembers.tsx index 3337f413..121ade31 100644 --- a/src/components/right/management/ManageGroupMembers.tsx +++ b/src/components/right/management/ManageGroupMembers.tsx @@ -84,7 +84,7 @@ export default memo(withGlobal( (global, { chatId }): StateProps => { const chat = selectChat(global, chatId); const { byId: usersById } = global.users; - const members = chat && chat.fullInfo && chat.fullInfo.members; + const members = chat?.fullInfo?.members; const isChannel = chat && isChatChannel(chat); return { diff --git a/src/components/right/management/ManageGroupPermissions.tsx b/src/components/right/management/ManageGroupPermissions.tsx index c6c03d02..c7772bed 100644 --- a/src/components/right/management/ManageGroupPermissions.tsx +++ b/src/components/right/management/ManageGroupPermissions.tsx @@ -88,7 +88,7 @@ const ManageGroupPermissions: FC = ({ }, [currentUserId, onChatMemberSelect, onScreenSelect]); useEffect(() => { - setPermissions((chat && chat.defaultBannedRights) || {}); + setPermissions((chat?.defaultBannedRights) || {}); setHavePermissionChanged(false); setTimeout(() => { setIsLoading(false); @@ -148,7 +148,7 @@ const ManageGroupPermissions: FC = ({ return Object.keys(bannedRights).reduce((result, key) => { if ( !bannedRights[key as keyof ApiChatBannedRights] - || (defaultBannedRights && defaultBannedRights[key as keyof ApiChatBannedRights]) + || (defaultBannedRights?.[key as keyof ApiChatBannedRights]) || key === 'sendInline' || key === 'viewMessages' || key === 'sendGames' ) { return result; diff --git a/src/components/right/management/ManageGroupUserPermissions.tsx b/src/components/right/management/ManageGroupUserPermissions.tsx index bc84f94b..6ce13a11 100644 --- a/src/components/right/management/ManageGroupUserPermissions.tsx +++ b/src/components/right/management/ManageGroupUserPermissions.tsx @@ -62,13 +62,13 @@ const ManageGroupUserPermissions: FC = ({ }, [chat, selectedChatMemberId]); useEffect(() => { - if (chat && chat.fullInfo && selectedChatMemberId && !selectedChatMember) { + if (chat?.fullInfo && selectedChatMemberId && !selectedChatMember) { onScreenSelect(ManagementScreens.GroupPermissions); } }, [chat, onScreenSelect, selectedChatMember, selectedChatMemberId]); useEffect(() => { - setPermissions((selectedChatMember && selectedChatMember.bannedRights) || (chat && chat.defaultBannedRights) || {}); + setPermissions((selectedChatMember?.bannedRights) || (chat?.defaultBannedRights) || {}); setHavePermissionChanged(false); setIsLoading(false); }, [chat, selectedChatMember]); diff --git a/src/components/right/management/ManageGroupUserPermissionsCreate.tsx b/src/components/right/management/ManageGroupUserPermissionsCreate.tsx index c28286ba..c1679250 100644 --- a/src/components/right/management/ManageGroupUserPermissionsCreate.tsx +++ b/src/components/right/management/ManageGroupUserPermissionsCreate.tsx @@ -89,7 +89,7 @@ export default memo(withGlobal( (global, { chatId }): StateProps => { const chat = selectChat(global, chatId); const { byId: usersById } = global.users; - const members = chat && chat.fullInfo && chat.fullInfo.members; + const members = chat?.fullInfo?.members; const isChannel = chat && isChatChannel(chat); return { diff --git a/src/components/ui/InfiniteScroll.tsx b/src/components/ui/InfiniteScroll.tsx index 1e11cda6..091f7c34 100644 --- a/src/components/ui/InfiniteScroll.tsx +++ b/src/components/ui/InfiniteScroll.tsx @@ -154,7 +154,7 @@ const InfiniteScroll: FC = ({ const nextAnchor = listItemElements[0]; if (nextAnchor) { const nextAnchorTop = nextAnchor.getBoundingClientRect().top; - const newAnchorTop = currentAnchor && currentAnchor.offsetParent && currentAnchor !== nextAnchor + const newAnchorTop = currentAnchor?.offsetParent && currentAnchor !== nextAnchor ? currentAnchor.getBoundingClientRect().top : nextAnchorTop; const isMovingUp = ( @@ -175,7 +175,7 @@ const InfiniteScroll: FC = ({ const nextAnchor = listItemElements[listLength - 1]; if (nextAnchor) { const nextAnchorTop = nextAnchor.getBoundingClientRect().top; - const newAnchorTop = currentAnchor && currentAnchor.offsetParent && currentAnchor !== nextAnchor + const newAnchorTop = currentAnchor?.offsetParent && currentAnchor !== nextAnchor ? currentAnchor.getBoundingClientRect().top : nextAnchorTop; const isMovingDown = ( @@ -193,7 +193,7 @@ const InfiniteScroll: FC = ({ } if (!isUpdated) { - if (currentAnchor && currentAnchor.offsetParent) { + if (currentAnchor?.offsetParent) { stateRef.current.currentAnchorTop = currentAnchor.getBoundingClientRect().top; } else { const nextAnchor = listItemElements[0]; diff --git a/src/components/ui/Transition.tsx b/src/components/ui/Transition.tsx index 0e242e29..56e42cf5 100644 --- a/src/components/ui/Transition.tsx +++ b/src/components/ui/Transition.tsx @@ -182,7 +182,7 @@ const Transition: FC = ({ } const watchedNode = name === 'mv-slide' - ? childNodes[activeIndex] && childNodes[activeIndex].firstChild + ? childNodes[activeIndex]?.firstChild : name === 'reveal' && isBackwards ? childNodes[prevActiveIndex] : childNodes[activeIndex]; diff --git a/src/hooks/reducers/useFoldersReducer.ts b/src/hooks/reducers/useFoldersReducer.ts index c0a9f295..ef8de215 100644 --- a/src/hooks/reducers/useFoldersReducer.ts +++ b/src/hooks/reducers/useFoldersReducer.ts @@ -81,7 +81,7 @@ function getSuggestedFolderName(includeFilters?: FolderIncludeFilters) { if ( Object.values(filters).filter(Boolean).length > 1 - || (includedChatIds && includedChatIds.length) + || (includedChatIds?.length) ) { return ''; } diff --git a/src/hooks/useAudioPlayer.ts b/src/hooks/useAudioPlayer.ts index 0ea89663..bedb54fe 100644 --- a/src/hooks/useAudioPlayer.ts +++ b/src/hooks/useAudioPlayer.ts @@ -44,9 +44,7 @@ export default ( } } - if (handlers && handlers[eventName]) { - handlers[eventName](e); - } + handlers?.[eventName]?.(e); }, onForcePlay); const { proxy } = controllerRef.current!; diff --git a/src/hooks/useChatContextActions.ts b/src/hooks/useChatContextActions.ts index 104e2340..119fc2b7 100644 --- a/src/hooks/useChatContextActions.ts +++ b/src/hooks/useChatContextActions.ts @@ -37,7 +37,7 @@ export default ({ return undefined; } - const isChatWithSelf = privateChatUser && privateChatUser.isSelf; + const isChatWithSelf = privateChatUser?.isSelf; const actionUnreadMark = chat.unreadCount || chat.hasUnreadMark ? { title: lang('MarkAsRead'), icon: 'readchats', handler: () => toggleChatUnread({ id: chat.id }) } diff --git a/src/hooks/useWebpThumbnail.ts b/src/hooks/useWebpThumbnail.ts index da576c7f..bac5c5cb 100644 --- a/src/hooks/useWebpThumbnail.ts +++ b/src/hooks/useWebpThumbnail.ts @@ -9,10 +9,10 @@ import { getMessageMediaThumbDataUri } from '../modules/helpers'; export default function useWebpThumbnail(message?: ApiMessage) { const thumbnail = message && getMessageMediaThumbDataUri(message); - const { sticker } = (message && message.content) || {}; + const sticker = message?.content?.sticker; const shouldDecodeThumbnail = thumbnail && sticker && !isWebpSupported() && thumbnail.includes('image/webp'); const [thumbnailDecoded, setThumbnailDecoded] = useState(EMPTY_IMAGE_DATA_URI); - const messageId = message && message.id; + const messageId = message?.id; useLayoutEffect(() => { if (!shouldDecodeThumbnail) { diff --git a/src/lib/gramjs/client/auth.ts b/src/lib/gramjs/client/auth.ts index e37a064c..3a81ceb7 100644 --- a/src/lib/gramjs/client/auth.ts +++ b/src/lib/gramjs/client/auth.ts @@ -221,7 +221,7 @@ async function signInUserWithQrCode( await Promise.race([updatePromise, inputPromise]); } catch (err) { if (err.message === 'RESTART_AUTH') { - return signInUser(client, apiCredentials, authParams); + return await signInUser(client, apiCredentials, authParams); } throw err; diff --git a/src/modules/actions/api/chats.ts b/src/modules/actions/api/chats.ts index 474bc757..6be5af0e 100644 --- a/src/modules/actions/api/chats.ts +++ b/src/modules/actions/api/chats.ts @@ -90,7 +90,7 @@ addReducer('openChat', (global, actions, payload) => { const { currentUserId } = global; const chat = selectChat(global, id); - if (chat && chat.hasUnreadMark) { + if (chat?.hasUnreadMark) { actions.toggleChatUnread({ id }); } @@ -162,7 +162,7 @@ addReducer('loadMoreChats', (global, actions, payload) => { const oldestChat = listIds ? listIds .map((id) => global.chats.byId[id]) - .filter((chat) => Boolean(chat && chat.lastMessage) && !selectIsChatPinned(global, chat.id)) + .filter((chat) => Boolean(chat?.lastMessage) && !selectIsChatPinned(global, chat.id)) .sort((chat1, chat2) => (chat1.lastMessage!.date - chat2.lastMessage!.date))[0] : undefined; @@ -402,7 +402,7 @@ addReducer('editChatFolder', (global, actions, payload) => { addReducer('addChatFolder', (global, actions, payload) => { const { folder } = payload!; const { orderedIds } = global.chatFolders; - const maxId = orderedIds && orderedIds.length ? Math.max.apply(Math.max, orderedIds) : ARCHIVED_FOLDER_ID; + const maxId = orderedIds?.length ? Math.max.apply(Math.max, orderedIds) : ARCHIVED_FOLDER_ID; void createChatFolder(folder, maxId); }); @@ -738,7 +738,7 @@ addReducer('unlinkDiscussionGroup', (global, actions, payload) => { } let chat: ApiChat | undefined; - if (channel.fullInfo && channel.fullInfo.linkedChatId) { + if (channel.fullInfo?.linkedChatId) { chat = selectChat(global, channel.fullInfo.linkedChatId); } @@ -768,7 +768,7 @@ addReducer('loadMoreMembers', (global) => { return; } - const offset = (chat.fullInfo && chat.fullInfo.members && chat.fullInfo.members.length) || undefined; + const offset = (chat.fullInfo?.members?.length) || undefined; const result = await callApi('fetchMembers', chat.id, chat.accessHash!, 'recent', offset); if (!result) { return; diff --git a/src/modules/actions/api/globalSearch.ts b/src/modules/actions/api/globalSearch.ts index a59c6dec..5f0f8352 100644 --- a/src/modules/actions/api/globalSearch.ts +++ b/src/modules/actions/api/globalSearch.ts @@ -57,7 +57,7 @@ addReducer('searchMessagesGlobal', (global, actions, payload) => { } = global.globalSearch; const maxDate = date ? timestampPlusDay(date) : date; const { type } = payload; - const { nextOffsetId } = (resultsByType && resultsByType[type as ApiGlobalMessageSearchType]) || {}; + const nextOffsetId = (resultsByType?.[type as ApiGlobalMessageSearchType])?.nextOffsetId; const chat = chatId ? selectChat(global, chatId) : undefined; diff --git a/src/modules/actions/api/localSearch.ts b/src/modules/actions/api/localSearch.ts index 1712ad14..2969135e 100644 --- a/src/modules/actions/api/localSearch.ts +++ b/src/modules/actions/api/localSearch.ts @@ -29,12 +29,12 @@ addReducer('searchTextMessagesLocal', (global) => { } const { query, results } = currentSearch; - const offsetId = results ? results.nextOffsetId : undefined; + const offsetId = results?.nextOffsetId; let topMessageId: number | undefined; if (threadId !== MAIN_THREAD_ID) { const threadInfo = selectThreadInfo(global, chatId!, threadId); - topMessageId = threadInfo ? threadInfo.topMessageId : undefined; + topMessageId = threadInfo?.topMessageId; } void searchTextMessages(chat, threadId, topMessageId, query, offsetId); @@ -53,7 +53,7 @@ addReducer('searchMediaMessagesLocal', (global) => { const { currentType: type, resultsByType } = currentSearch; const currentResults = type && resultsByType && resultsByType[type]; - const offsetId = currentResults ? currentResults.nextOffsetId : undefined; + const offsetId = currentResults?.nextOffsetId; if (!type) { return; diff --git a/src/modules/actions/api/messages.ts b/src/modules/actions/api/messages.ts index f3b9070d..10e5acd7 100644 --- a/src/modules/actions/api/messages.ts +++ b/src/modules/actions/api/messages.ts @@ -420,7 +420,7 @@ addReducer('deleteHistory', (global, actions, payload) => { return; } - const maxId = chat.lastMessage && chat.lastMessage.id; + const maxId = chat.lastMessage?.id; await callApi('deleteHistory', { chat, shouldDeleteForAll, maxId }); diff --git a/src/modules/actions/api/settings.ts b/src/modules/actions/api/settings.ts index b6ad8937..adfee6d6 100644 --- a/src/modules/actions/api/settings.ts +++ b/src/modules/actions/api/settings.ts @@ -197,10 +197,10 @@ addReducer('loadBlockedContacts', () => { let newGlobal = getGlobal(); - if (result.users && result.users.length) { + if (result.users?.length) { newGlobal = addUsers(newGlobal, buildCollectionByKey(result.users, 'id')); } - if (result.chats && result.chats.length) { + if (result.chats?.length) { newGlobal = updateChats(newGlobal, buildCollectionByKey(result.chats, 'id')); } diff --git a/src/modules/actions/api/symbols.ts b/src/modules/actions/api/symbols.ts index 1c00c669..c6ee4440 100644 --- a/src/modules/actions/api/symbols.ts +++ b/src/modules/actions/api/symbols.ts @@ -139,7 +139,7 @@ addReducer('loadEmojiKeywords', (global, actions, payload: { language: LangCode const { language } = payload; let currentEmojiKeywords = global.emojiKeywords[language]; - if (currentEmojiKeywords && currentEmojiKeywords.isLoading) { + if (currentEmojiKeywords?.isLoading) { return; } @@ -186,7 +186,7 @@ addReducer('loadEmojiKeywords', (global, actions, payload: { language: LangCode isLoading: false, version: emojiKeywords.version, keywords: { - ...(currentEmojiKeywords && currentEmojiKeywords.keywords), + ...(currentEmojiKeywords?.keywords), ...emojiKeywords.keywords, }, }, diff --git a/src/modules/actions/api/sync.ts b/src/modules/actions/api/sync.ts index fbde9a2f..b66120ce 100644 --- a/src/modules/actions/api/sync.ts +++ b/src/modules/actions/api/sync.ts @@ -214,7 +214,7 @@ async function loadAndReplaceMessages(savedUsers?: ApiUser[]) { byId, threadsById: { [MAIN_THREAD_ID]: { - ...(currentMessageListInfo && currentMessageListInfo.threadsById[MAIN_THREAD_ID]), + ...(currentMessageListInfo?.threadsById[MAIN_THREAD_ID]), listedIds, viewportIds: listedIds, outlyingIds: undefined, @@ -244,7 +244,7 @@ async function loadAndReplaceMessages(savedUsers?: ApiUser[]) { byId: byIdOrigin, threadsById: { [MAIN_THREAD_ID]: { - ...(currentMessageListInfoOrigin && currentMessageListInfoOrigin.threadsById[MAIN_THREAD_ID]), + ...(currentMessageListInfoOrigin?.threadsById[MAIN_THREAD_ID]), listedIds: listedIdsOrigin, viewportIds: listedIdsOrigin, outlyingIds: undefined, @@ -256,7 +256,7 @@ async function loadAndReplaceMessages(savedUsers?: ApiUser[]) { threadsById: { ...global.messages.byChatId[currentChatId].threadsById, [currentThreadId]: { - ...(currentMessageListInfo && currentMessageListInfo.threadsById[currentThreadId]), + ...(currentMessageListInfo?.threadsById[currentThreadId]), outlyingIds: undefined, }, }, diff --git a/src/modules/actions/apiUpdaters/chats.ts b/src/modules/actions/apiUpdaters/chats.ts index 0d53f439..5cda6604 100644 --- a/src/modules/actions/apiUpdaters/chats.ts +++ b/src/modules/actions/apiUpdaters/chats.ts @@ -166,7 +166,7 @@ addReducer('apiUpdate', (global, actions, update: ApiUpdate) => { ids.forEach((id) => { const chatId = 'channelId' in update ? update.channelId : selectCommonBoxChatId(global, id); const chat = selectChat(global, chatId); - if (chat && chat.unreadMentionsCount) { + if (chat?.unreadMentionsCount) { global = updateChat(global, chatId, { unreadMentionsCount: chat.unreadMentionsCount - 1, }); @@ -326,7 +326,7 @@ addReducer('apiUpdate', (global, actions, update: ApiUpdate) => { } let shouldUpdate = false; - let members = targetChat.fullInfo && targetChat.fullInfo.members + let members = targetChat.fullInfo?.members ? [...targetChat.fullInfo.members] : []; @@ -370,7 +370,7 @@ addReducer('apiUpdate', (global, actions, update: ApiUpdate) => { const { chatId, ids } = update; const chat = global.chats.byId[chatId]; - if (chat && chat.photos) { + if (chat?.photos) { setGlobal(updateChat(global, chatId, { photos: chat.photos.filter((photo) => !ids.includes(photo.id)), })); diff --git a/src/modules/actions/apiUpdaters/messages.ts b/src/modules/actions/apiUpdaters/messages.ts index 691a6e6a..1c92d5ef 100644 --- a/src/modules/actions/apiUpdaters/messages.ts +++ b/src/modules/actions/apiUpdaters/messages.ts @@ -63,7 +63,7 @@ addReducer('apiUpdate', (global, actions, update: ApiUpdate) => { const newMessage = selectChatMessage(global, chatId, id)!; if (isMessageInCurrentMessageList(global, chatId, message as ApiMessage)) { - if (message.isOutgoing && !(message.content && message.content.action)) { + if (message.isOutgoing && !(message.content?.action)) { const currentMessageList = selectCurrentMessageList(global); if (currentMessageList) { // We do not use `actions.focusLastMessage` as it may be set with a delay (see below) @@ -180,8 +180,7 @@ addReducer('apiUpdate', (global, actions, update: ApiUpdate) => { const thread = selectThreadByMessage(global, chatId, message); // For some reason Telegram requires to manually mark outgoing thread messages read - // For some reason Telegram requires to manually mark outgoing thread messages read - if (thread && thread.threadInfo) { + if (thread?.threadInfo) { actions.markMessageListRead({ maxId: message.id }); global = replaceThreadParam(global, chatId, thread.threadInfo.threadId, 'threadInfo', { @@ -325,7 +324,7 @@ addReducer('apiUpdate', (global, actions, update: ApiUpdate) => { const message = selectChatMessageByPollId(global, pollId); - if (message && message.content.poll) { + if (message?.content.poll) { const updatedPoll = { ...message.content.poll, ...pollUpdate }; // Workaround for poll update bug: `chosen` option gets reset when someone votes after current user @@ -474,7 +473,7 @@ function updateListedAndViewportIds(global: GlobalState, actions: GlobalActions, const { threadInfo, firstMessageId } = selectThreadByMessage(global, chatId, message) || {}; const chat = selectChat(global, chatId); - const isUnreadChatNotLoaded = chat && chat.unreadCount && !selectListedIds(global, chatId, MAIN_THREAD_ID); + const isUnreadChatNotLoaded = chat?.unreadCount && !selectListedIds(global, chatId, MAIN_THREAD_ID); global = updateThreadUnread(global, actions, message); @@ -525,7 +524,7 @@ function updateChatLastMessage( force = false, ) { const { chats } = global; - const currentLastMessage = chats.byId[chatId] && chats.byId[chatId].lastMessage; + const currentLastMessage = chats.byId[chatId]?.lastMessage; if (currentLastMessage && !force) { const isSameOrNewer = ( diff --git a/src/modules/actions/ui/messages.ts b/src/modules/actions/ui/messages.ts index bbdb20c5..3e2e9c95 100644 --- a/src/modules/actions/ui/messages.ts +++ b/src/modules/actions/ui/messages.ts @@ -111,11 +111,11 @@ addReducer('replyToNextMessage', (global, actions, payload) => { if (threadId === MAIN_THREAD_ID) { const chat = selectChat(global, chatId); - messageId = chat && chat.lastMessage ? chat.lastMessage.id : undefined; + messageId = chat?.lastMessage?.id; } else { const threadInfo = selectThreadInfo(global, chatId, threadId); - messageId = threadInfo ? threadInfo.lastMessageId : undefined; + messageId = threadInfo?.lastMessageId; } } else { const chatMessageKeys = Object.keys(chatMessages); @@ -228,11 +228,11 @@ addReducer('focusLastMessage', (global, actions) => { if (threadId === MAIN_THREAD_ID) { const chat = selectChat(global, chatId); - lastMessageId = chat && chat.lastMessage ? chat.lastMessage.id : undefined; + lastMessageId = chat?.lastMessage?.id; } else { const threadInfo = selectThreadInfo(global, chatId, threadId); - lastMessageId = threadInfo ? threadInfo.lastMessageId : undefined; + lastMessageId = threadInfo?.lastMessageId; } if (!lastMessageId) { @@ -283,7 +283,7 @@ addReducer('focusMessage', (global, actions, payload) => { if (groupedId !== undefined) { const ids = selectForwardedMessageIdsByGroupId(global, groupedChatId, groupedId); - if (ids && ids.length) { + if (ids?.length) { ([messageId] = ids); } } diff --git a/src/modules/helpers/chats.ts b/src/modules/helpers/chats.ts index 341d6c69..05459997 100644 --- a/src/modules/helpers/chats.ts +++ b/src/modules/helpers/chats.ts @@ -121,8 +121,8 @@ export function getHasAdminRight(chat: ApiChat, key: keyof ApiChatAdminRights) { export function isUserRightBanned(chat: ApiChat, key: keyof ApiChatBannedRights) { return Boolean( - (chat.currentUserBannedRights && chat.currentUserBannedRights[key]) - || (chat.defaultBannedRights && chat.defaultBannedRights[key]), + (chat.currentUserBannedRights?.[key]) + || (chat.defaultBannedRights?.[key]), ); } @@ -183,7 +183,7 @@ export function getAllowedAttachmentOptions(chat?: ApiChat, isChatWithBot = fals export function getMessageSendingRestrictionReason( lang: LangFn, currentUserBannedRights?: ApiChatBannedRights, defaultBannedRights?: ApiChatBannedRights, ) { - if (currentUserBannedRights && currentUserBannedRights.sendMessages) { + if (currentUserBannedRights?.sendMessages) { const { untilDate } = currentUserBannedRights; return untilDate && untilDate < FOREVER_BANNED_DATE ? lang( @@ -196,7 +196,7 @@ export function getMessageSendingRestrictionReason( : lang('Channel.Persmission.Denied.SendMessages.Forever'); } - if (defaultBannedRights && defaultBannedRights.sendMessages) { + if (defaultBannedRights?.sendMessages) { return lang('Channel.Persmission.Denied.SendMessages.DefaultRestrictedText'); } @@ -420,7 +420,7 @@ export function getFolderUnreadDialogs( const listedChats = listIds .map((id) => chatsById[id]) - .filter((chat) => (chat && chat.lastMessage && !chat.isRestricted && !chat.isNotJoined)); + .filter((chat) => (chat?.lastMessage && !chat.isRestricted && !chat.isNotJoined)); const unreadDialogsCount = listedChats .reduce((total, chat) => (chat.unreadCount || chat.hasUnreadMark ? total + 1 : total), 0); @@ -456,8 +456,8 @@ export function getFolderDescriptionText( // we display folder chats count if ( Object.values(filters).filter(Boolean).length > 1 - || (excludedChatIds && excludedChatIds.length) - || (includedChatIds && includedChatIds.length) + || (excludedChatIds?.length) + || (includedChatIds?.length) ) { const length = getFolderChatsCount(chatsById, usersById, folder, chatIdsCache, notifySettings, notifyExceptions); return lang('Chats', length); diff --git a/src/modules/helpers/messageMedia.ts b/src/modules/helpers/messageMedia.ts index 06d2c590..d1edf37c 100644 --- a/src/modules/helpers/messageMedia.ts +++ b/src/modules/helpers/messageMedia.ts @@ -43,7 +43,7 @@ export function getMessageVideo(message: ApiMessage) { export function getMessageRoundVideo(message: ApiMessage) { const { video } = message.content; - return video && video.isRound ? video : undefined; + return video?.isRound ? video : undefined; } export function getMessageAction(message: ApiMessage) { @@ -93,19 +93,15 @@ export function getMessageWebPage(message: ApiMessage) { } export function getMessageWebPagePhoto(message: ApiMessage) { - const webPage = getMessageWebPage(message); - return webPage ? webPage.photo : undefined; + return getMessageWebPage(message)?.photo; } export function getMessageWebPageDocument(message: ApiMessage) { - const webPage = getMessageWebPage(message); - return webPage ? webPage.document : undefined; + return getMessageWebPage(message)?.document; } export function getMessageWebPageVideo(message: ApiMessage): ApiVideo | undefined { - const webPage = getMessageWebPage(message); - if (!webPage) return undefined; - return webPage.video; + return getMessageWebPage(message)?.video; } export function getMessageMediaThumbnail(message: ApiMessage) { @@ -124,9 +120,7 @@ export function getMessageMediaThumbnail(message: ApiMessage) { } export function getMessageMediaThumbDataUri(message: ApiMessage) { - const thumbnail = getMessageMediaThumbnail(message); - - return thumbnail ? thumbnail.dataUri : undefined; + return getMessageMediaThumbnail(message)?.dataUri; } export function getMessageMediaHash( @@ -296,7 +290,7 @@ export function getMessageFileSize(message: ApiMessage) { export function hasMessageLocalBlobUrl(message: ApiMessage) { const { photo, video, document } = message.content; - return (photo && photo.blobUrl) || (video && video.blobUrl) || (document && document.previewBlobUrl); + return (photo?.blobUrl) || (video?.blobUrl) || (document?.previewBlobUrl); } export function getChatMediaMessageIds( diff --git a/src/modules/helpers/messages.ts b/src/modules/helpers/messages.ts index 1dd3407c..61f5ea59 100644 --- a/src/modules/helpers/messages.ts +++ b/src/modules/helpers/messages.ts @@ -103,7 +103,7 @@ export function getMessageCustomShape(message: ApiMessage): boolean | number { text, sticker, photo, video, audio, voice, document, poll, webPage, contact, } = message.content; - if (sticker || (video && video.isRound)) { + if (sticker || (video?.isRound)) { return true; } @@ -132,7 +132,7 @@ export function getFirstLinkInMessage(message: ApiMessage) { const { text } = message.content; let match: RegExpMatchArray | null | undefined; - if (text && text.entities) { + if (text?.entities) { let link = text.entities.find((entity) => entity.type === ApiMessageEntityTypes.TextUrl); if (link) { match = link.url!.match(RE_LINK); @@ -222,5 +222,5 @@ export function isHistoryClearMessage(message: ApiMessage) { export function getMessageAudioCaption(message: ApiMessage) { const { audio, text } = message.content; - return (audio && [audio.title, audio.performer].filter(Boolean).join(' — ')) || (text && text.text); + return (audio && [audio.title, audio.performer].filter(Boolean).join(' — ')) || (text?.text); } diff --git a/src/modules/reducers/chats.ts b/src/modules/reducers/chats.ts index f6a63491..3a22bf84 100644 --- a/src/modules/reducers/chats.ts +++ b/src/modules/reducers/chats.ts @@ -23,7 +23,7 @@ export function replaceChatListIds( export function updateChatListIds(global: GlobalState, type: 'active' | 'archived', idsUpdate: number[]): GlobalState { const { [type]: listIds } = global.chats.listIds; - const newIds = listIds && listIds.length + const newIds = listIds?.length ? idsUpdate.filter((id) => !listIds.includes(id)) : idsUpdate; diff --git a/src/modules/reducers/globalSearch.ts b/src/modules/reducers/globalSearch.ts index e9b4e5b2..ce39c42b 100644 --- a/src/modules/reducers/globalSearch.ts +++ b/src/modules/reducers/globalSearch.ts @@ -38,7 +38,7 @@ export function updateGlobalSearchResults( return result; }, {} as Record); - const foundIdsForType = resultsByType && resultsByType[type] ? resultsByType[type]!.foundIds : undefined; + const foundIdsForType = resultsByType?.[type]?.foundIds; if (foundIdsForType !== undefined && Object.keys(newFoundMessagesById).every( diff --git a/src/modules/reducers/localSearch.ts b/src/modules/reducers/localSearch.ts index 2857118f..ecb23f86 100644 --- a/src/modules/reducers/localSearch.ts +++ b/src/modules/reducers/localSearch.ts @@ -86,7 +86,7 @@ export function updateLocalTextSearchResults( ): GlobalState { const chatThreadKey = buildChatThreadKey(chatId, threadId); const { results } = global.localTextSearch.byChatThreadKey[chatThreadKey] || {}; - const prevFoundIds = (results && results.foundIds) || []; + const prevFoundIds = (results?.foundIds) || []; const foundIds = orderFoundIds(unique(Array.prototype.concat(prevFoundIds, newFoundIds))); const foundOrPrevFoundIds = areSortedArraysEqual(prevFoundIds, foundIds) ? prevFoundIds : foundIds; @@ -150,7 +150,7 @@ export function updateLocalMediaSearchResults( nextOffsetId?: number, ): GlobalState { const { resultsByType } = global.localMediaSearch.byChatId[chatId] || {}; - const prevFoundIds = resultsByType && resultsByType[type] ? resultsByType[type]!.foundIds : []; + const prevFoundIds = resultsByType?.[type] ? resultsByType[type]!.foundIds : []; const foundIds = orderFoundIds(unique(Array.prototype.concat(prevFoundIds, newFoundIds))); const foundOrPrevFoundIds = areSortedArraysEqual(prevFoundIds, foundIds) ? prevFoundIds : foundIds; diff --git a/src/modules/reducers/messages.ts b/src/modules/reducers/messages.ts index 082b6f2d..d8a868e0 100644 --- a/src/modules/reducers/messages.ts +++ b/src/modules/reducers/messages.ts @@ -76,9 +76,9 @@ function updateThread( return updateMessageStore(global, chatId, { threadsById: { - ...(current && current.threadsById), + ...(current?.threadsById), [threadId]: { - ...(current && current.threadsById[threadId]), + ...(current?.threadsById[threadId]), ...threadUpdate, }, }, @@ -196,7 +196,7 @@ export function deleteChatMessages( } const newById = omit(byId, messageIds); const deletedForwardedPosts = Object.values(pickTruthy(byId, messageIds)).filter( - ({ forwardInfo }) => forwardInfo && forwardInfo.isLinkedChannelPost, + ({ forwardInfo }) => forwardInfo?.isLinkedChannelPost, ); const threadIds = Object.keys(global.messages.byChatId[chatId].threadsById).map(Number); @@ -207,7 +207,7 @@ export function deleteChatMessages( let outlyingIds = selectOutlyingIds(global, chatId, threadId); let viewportIds = selectViewportIds(global, chatId, threadId); let pinnedIds = selectPinnedIds(global, chatId); - let newMessageCount = threadInfo ? threadInfo.messagesCount : undefined; + let newMessageCount = threadInfo?.messagesCount; messageIds.forEach((messageId) => { if (listedIds && listedIds.includes(messageId)) { @@ -245,7 +245,7 @@ export function deleteChatMessages( const currentMessageList = selectCurrentMessageList(global); const canDeleteCurrentThread = currentMessageList && currentMessageList.chatId === chatId && currentMessageList.type === 'thread'; - const currentThreadId = currentMessageList && currentMessageList.threadId; + const currentThreadId = currentMessageList?.threadId; deletedForwardedPosts.forEach((message) => { const { fromChatId, fromMessageId } = message.forwardInfo!; @@ -298,7 +298,7 @@ export function updateListedIds( idsUpdate: number[], ): GlobalState { const listedIds = selectListedIds(global, chatId, threadId); - const newIds = listedIds && listedIds.length + const newIds = listedIds?.length ? idsUpdate.filter((id) => !listedIds.includes(id)) : idsUpdate; @@ -319,7 +319,7 @@ export function updateOutlyingIds( idsUpdate: number[], ): GlobalState { const outlyingIds = selectOutlyingIds(global, chatId, threadId); - const newIds = outlyingIds && outlyingIds.length + const newIds = outlyingIds?.length ? idsUpdate.filter((id) => !outlyingIds.includes(id)) : idsUpdate; diff --git a/src/modules/reducers/users.ts b/src/modules/reducers/users.ts index 070d0a44..4d81070b 100644 --- a/src/modules/reducers/users.ts +++ b/src/modules/reducers/users.ts @@ -38,7 +38,7 @@ function updateContactList(global: GlobalState, updatedUsers: ApiUser[]): Global if (!contactUserIds) return global; const newContactUserIds = updatedUsers - .filter((user) => user && user.isContact && !contactUserIds.includes(user.id)) + .filter((user) => user?.isContact && !contactUserIds.includes(user.id)) .map((user) => user.id); if (newContactUserIds.length === 0) return global; diff --git a/src/modules/selectors/messages.ts b/src/modules/selectors/messages.ts index be75a4e6..72a955ea 100644 --- a/src/modules/selectors/messages.ts +++ b/src/modules/selectors/messages.ts @@ -54,15 +54,11 @@ export function selectCurrentChat(global: GlobalState) { } export function selectChatMessages(global: GlobalState, chatId: number) { - const messages = global.messages.byChatId[chatId]; - - return messages ? messages.byId : undefined; + return global.messages.byChatId[chatId]?.byId; } export function selectScheduledMessages(global: GlobalState, chatId: number) { - const messages = global.scheduledMessages.byChatId[chatId]; - - return messages ? messages.byId : undefined; + return global.scheduledMessages.byChatId[chatId]?.byId; } export function selectThreadParam( @@ -364,7 +360,7 @@ export function selectAllowedMessageActions(global: GlobalState, message: ApiMes || getServerTime(global.serverTimeOffset) - message.date < MESSAGE_EDIT_ALLOWED_TIME) && !( content.sticker || content.contact || content.poll || content.action || content.audio - || (content.video && content.video.isRound) + || (content.video?.isRound) ) && !isForwardedMessage(message) && !message.viaBotId @@ -485,9 +481,7 @@ export function selectCanReportSelectedMessages(global: GlobalState) { } export function selectUploadProgress(global: GlobalState, message: ApiMessage) { - const fileTransfer = global.fileUploads.byMessageLocalId[message.previousLocalId || message.id]; - - return fileTransfer ? fileTransfer.progress : undefined; + return global.fileUploads.byMessageLocalId[message.previousLocalId || message.id]?.progress; } export function selectRealLastReadId(global: GlobalState, chatId: number, threadId: number) { diff --git a/src/modules/selectors/users.ts b/src/modules/selectors/users.ts index 98ecf813..a33a43e6 100644 --- a/src/modules/selectors/users.ts +++ b/src/modules/selectors/users.ts @@ -8,7 +8,7 @@ export function selectUser(global: GlobalState, userId: number): ApiUser | undef export function selectIsUserBlocked(global: GlobalState, userId: number) { const user = selectUser(global, userId); - return user && user.fullInfo && user.fullInfo.isBlocked; + return user?.fullInfo?.isBlocked; } // Slow, not to be used in `withGlobal` diff --git a/src/serviceWorker/progressive.ts b/src/serviceWorker/progressive.ts index f176237c..4acf1eee 100644 --- a/src/serviceWorker/progressive.ts +++ b/src/serviceWorker/progressive.ts @@ -44,7 +44,7 @@ export async function respondForProgressive(e: FetchEvent) { if (start === 0 && end === 1) { const match = e.request.url.match(/fileSize=(\d+)&mimeType=([\w/]+)/); const fileSize = match && Number(match[1]); - const mimeType = match && match[2]; + const mimeType = match?.[2]; if (fileSize && mimeType) { return new Response(new Uint8Array(2).buffer, { diff --git a/src/util/WorkerConnector.ts b/src/util/WorkerConnector.ts index a3a1f4f4..77c28835 100644 --- a/src/util/WorkerConnector.ts +++ b/src/util/WorkerConnector.ts @@ -128,9 +128,7 @@ export default class WorkerConnector { } } else if (data.type === 'methodCallback') { const requestState = requestStates.get(data.messageId); - if (requestState && requestState.callback) { - requestState.callback(...data.callbackArgs); - } + requestState?.callback?.(...data.callbackArgs); } else if (data.type === 'unhandledError') { throw data.error; } diff --git a/src/util/environmentSystemTheme.ts b/src/util/environmentSystemTheme.ts index 3430a7a6..1c16393f 100644 --- a/src/util/environmentSystemTheme.ts +++ b/src/util/environmentSystemTheme.ts @@ -1,7 +1,7 @@ import { ThemeKey } from '../types'; let systemThemeCache: ThemeKey = ( - window && window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches + window.matchMedia?.('(prefers-color-scheme: dark)').matches ) ? 'dark' : 'light'; export function getSystemTheme() { diff --git a/src/util/handleError.ts b/src/util/handleError.ts index 9e40c395..ab88c6d6 100644 --- a/src/util/handleError.ts +++ b/src/util/handleError.ts @@ -20,6 +20,6 @@ export function handleError(err: Error) { console.error(err); if (APP_ENV === 'development' || APP_ENV === 'staging') { - throttledAlert(`${DEBUG_ALERT_MSG}\n\n${(err && err.message) || err}\n${err && err.stack}`); + throttledAlert(`${DEBUG_ALERT_MSG}\n\n${(err?.message) || err}\n${err?.stack}`); } } diff --git a/src/util/insertHtmlInSelection.ts b/src/util/insertHtmlInSelection.ts index d08a364f..93ec7d19 100644 --- a/src/util/insertHtmlInSelection.ts +++ b/src/util/insertHtmlInSelection.ts @@ -1,7 +1,7 @@ export default function insertHtmlInSelection(html: string) { const selection = window.getSelection(); - if (selection && selection.getRangeAt && selection.rangeCount) { + if (selection?.getRangeAt && selection.rangeCount) { const range = selection.getRangeAt(0); range.deleteContents(); diff --git a/src/util/langProvider.ts b/src/util/langProvider.ts index 2b73c1e8..30572cad 100644 --- a/src/util/langProvider.ts +++ b/src/util/langProvider.ts @@ -71,7 +71,7 @@ export const getTranslation: LangFn = (key: string, value?: any, format?: 'i') = return key; } - const langString = (langPack && langPack[key]) || (fallbackLangPack && fallbackLangPack[key]); + const langString = (langPack?.[key]) || (fallbackLangPack?.[key]); if (!langString) { if (!fallbackLangPack) { void importFallbackLangPack(); @@ -125,8 +125,8 @@ export async function setLanguage(langCode: LangCode, callback?: NoneToVoidFunct document.documentElement.lang = langCode; const { languages } = getGlobal().settings.byKey; - const langInfo = languages ? languages.find((l) => l.langCode === langCode) : undefined; - getTranslation.isRtl = Boolean(langInfo && langInfo.rtl); + const langInfo = languages?.find((l) => l.langCode === langCode); + getTranslation.isRtl = Boolean(langInfo?.rtl); getTranslation.code = langCode; if (callback) { @@ -164,7 +164,7 @@ async function fetchRemoteString( keys: [key], }); - if (remote && remote.length) { + if (remote?.length) { await cacheApi.save(LANG_CACHE_NAME, `${remoteLangPack}_${langCode}_${key}`, remote[0]); return remote[0];