import { useMutation } from '@tanstack/react-query'; import { AxiosError } from 'axios'; import React, { useState } from 'react'; import { defineMessages, useIntl } from 'react-intl'; import snackbar from 'soapbox/actions/snackbar'; import { HStack, Icon, Input, Stack, Text } from 'soapbox/components/ui'; import { ChatWidgetScreens, useChatContext } from 'soapbox/contexts/chat-context'; import { useAppDispatch, useDebounce } from 'soapbox/hooks'; import { useChats } from 'soapbox/queries/chats'; import { queryClient } from 'soapbox/queries/client'; import useAccountSearch from 'soapbox/queries/search'; import { ChatKeys } from '../../../../queries/chats'; import ChatPaneHeader from '../chat-widget/chat-pane-header'; import { Pane } from '../ui'; import Blankslate from './blankslate'; import EmptyResultsBlankslate from './empty-results-blankslate'; import Results from './results'; const messages = defineMessages({ title: { id: 'chat_search.title', defaultMessage: 'Messages' }, }); const ChatSearch = () => { const debounce = useDebounce; const dispatch = useAppDispatch(); const intl = useIntl(); const { isOpen, changeScreen, toggleChatPane } = useChatContext(); const { getOrCreateChatByAccountId } = useChats(); const [value, setValue] = useState(''); const debouncedValue = debounce(value as string, 300); const { data: accounts, isFetching } = useAccountSearch(debouncedValue); const hasSearchValue = debouncedValue && debouncedValue.length > 0; const hasSearchResults = (accounts || []).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) => { changeScreen(ChatWidgetScreens.CHAT, response.data.id); queryClient.invalidateQueries(ChatKeys.chatSearch()); }, }); const renderBody = () => { if (hasSearchResults) { return ( { handleClickOnSearchResult.mutate(id); clearValue(); }} /> ); } else if (hasSearchValue && !hasSearchResults && !isFetching) { return ; } else { return ; } }; const clearValue = () => { if (hasSearchValue) { setValue(''); } }; return ( {intl.formatMessage(messages.title)} } isOpen={isOpen} isToggleable={false} onToggle={toggleChatPane} /> {isOpen ? (
setValue(event.target.value)} theme='search' append={ } />
{renderBody()}
) : null}
); }; export default ChatSearch;