import { useMutation } from '@tanstack/react-query'; import { AxiosError } from 'axios'; import sumBy from 'lodash/sumBy'; import React, { useState } from 'react'; import { defineMessages, useIntl } from 'react-intl'; import snackbar from 'soapbox/actions/snackbar'; import { Avatar, HStack, Icon, Input, Stack, Text } from 'soapbox/components/ui'; import VerificationBadge from 'soapbox/components/verification_badge'; import { useChatContext } from 'soapbox/contexts/chat-context'; import { useAppDispatch, useDebounce } from 'soapbox/hooks'; import { useChats } from 'soapbox/queries/chats'; import useAccountSearch from 'soapbox/queries/search'; import ChatList from '../chat-list'; import ChatPaneHeader from '../chat-pane-header'; import ChatWindow from '../chat-window'; import { Pane } from '../ui'; const messages = defineMessages({ searchPlaceholder: { id: 'chats.search_placeholder', defaultMessage: 'Type a name' }, }); const ChatPane = () => { const intl = useIntl(); const dispatch = useAppDispatch(); const debounce = useDebounce; const { chat, setChat, isOpen, toggleChatPane } = useChatContext(); const { chatsQuery: { data: chats }, getOrCreateChatByAccountId } = useChats(); const [value, setValue] = useState(); const debouncedValue = debounce(value as string, 300); const { data: accounts } = useAccountSearch(debouncedValue); const unreadCount = sumBy(chats, (chat) => chat.unread); const isSearching = accounts && accounts.length > 0; const hasSearchValue = value && value.length > 0; const handleClickOnSearchResult = useMutation((accountId: string) => { return getOrCreateChatByAccountId(accountId); }, { onError: (error: AxiosError) => { const data = error.response?.data as any; dispatch(snackbar.error(data?.error)); }, onSuccess: (response) => { setChat(response.data); }, }); const clearValue = () => { if (hasSearchValue) { setValue(''); } }; const renderBody = () => { if (isSearching) { return ( {accounts.map((account: any) => ( ))} ); } else { return setChat(chat)} useWindowScroll={false} />; } }; // Active chat if (chat?.id) { return ( ); } return ( {isOpen ? (
setValue(event.target.value)} isSearch append={ } />
{renderBody()}
) : null}
); }; export default ChatPane;