Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

3029: Proposal #3083

Closed
wants to merge 7 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
62 changes: 46 additions & 16 deletions web/src/components/ChatConversation.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

import ChatMessageModel from 'shared/api/models/ChatMessageModel'

import ChatMessage from './ChatMessage'
import ChatMessage, { Message } from './ChatMessage'

const Container = styled.div`
font-size: ${props => props.theme.fonts.hintFontSize};
Expand All @@ -15,6 +15,10 @@
margin-bottom: 12px;
`

const TypingIndicator = styled(Message)`
width: max-content;
`

const ErrorSendingStatus = styled.div`
background-color: ${props => props.theme.colors.invalidInput};
border-radius: 5px;
Expand All @@ -29,39 +33,65 @@
className?: string
}

const TYPING_INDICATOR_TIMEOUT = 60000

const ChatConversation = ({ messages, hasError, className }: ChatConversationProps): ReactElement => {
const { t } = useTranslation('chat')
const [messagesCount, setMessagesCount] = useState(0)
const [typingIndicatorVisible, setTypingIndicatorVisible] = useState(false)
const messagesEndRef = useRef<HTMLDivElement>(null)
const isLastMessageFromUser = messages[messages.length - 1]?.userIsAuthor
const hasOnlyReceivedInfoMessage = messages.filter(message => !message.userIsAuthor).length === 1
const waitingForAnswer = isLastMessageFromUser || hasOnlyReceivedInfoMessage

useEffect(() => {
if (messagesCount < messages.length) {
messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' })
setMessagesCount(messages.length)
}
}, [messages, messagesCount])

return (
<Container className={className}>
{messages.length > 0 ? (
<>
{!hasError && <InitialMessage>{t('initialMessage')}</InitialMessage>}
{messages.map((message, index) => (
<ChatMessage
message={message}
key={message.id}
showIcon={messages[index - 1]?.userIsAuthor !== message.userIsAuthor}
/>
))}
<div ref={messagesEndRef} />
</>
) : (
useEffect(() => {
if (!waitingForAnswer) {
return () => undefined
}
setTypingIndicatorVisible(true)

const typingIndicatorTimeout = setTimeout(() => {
setTypingIndicatorVisible(false)
}, TYPING_INDICATOR_TIMEOUT)

return () => clearTimeout(typingIndicatorTimeout)
}, [waitingForAnswer])

if (messages.length === 0) {
return (
<Container className={className}>
<div>
<b>{t('conversationTitle')}</b>
<br />
{t('conversationText')}
</div>
</Container>
)
}

return (
<Container className={className}>
{!hasError && <InitialMessage>{t('initialMessage')}</InitialMessage>}
{messages.map((message, index) => (
<ChatMessage
message={message}
key={message.id}
showIcon={messages[index - 1]?.userIsAuthor !== message.userIsAuthor}
/>
))}
{typingIndicatorVisible && (
<TypingIndicator>
<strong>...</strong>
</TypingIndicator>
)}
<div ref={messagesEndRef} />

Check warning on line 94 in web/src/components/ChatConversation.tsx

View check run for this annotation

CodeScene Delta Analysis / CodeScene Cloud Delta Analysis (main)

❌ New issue: Complex Method

ChatConversation has a cyclomatic complexity of 11, threshold = 10. This function has many conditional statements (e.g. if, for, while), leading to lower code health. Avoid adding more conditionals and code to it without refactoring.
{hasError && <ErrorSendingStatus role='alert'>{t('errorMessage')}</ErrorSendingStatus>}
</Container>
)
Expand Down
2 changes: 1 addition & 1 deletion web/src/components/ChatMessage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import { ChatBot, ChatPerson } from '../assets'
import RemoteContent from './RemoteContent'
import Icon from './base/Icon'

const Message = styled.div`
export const Message = styled.div`
border-radius: 5px;
padding: 8px;
border: 1px solid ${props => props.theme.colors.textDecorationColor};
Expand Down
34 changes: 33 additions & 1 deletion web/src/components/__tests__/ChatConversation.spec.tsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { act } from '@testing-library/react'
import React from 'react'

import ChatMessageModel from 'shared/api/models/ChatMessageModel'
Expand All @@ -7,6 +8,7 @@ import ChatConversation from '../ChatConversation'

jest.mock('react-i18next')
window.HTMLElement.prototype.scrollIntoView = jest.fn()
jest.useFakeTimers()

const render = (messages: ChatMessageModel[], hasError: boolean) =>
renderWithRouterAndTheme(<ChatConversation messages={messages} hasError={hasError} />)
Expand All @@ -21,10 +23,22 @@ describe('ChatConversation', () => {
}),
new ChatMessageModel({
id: 2,
body: 'Willkommen in der Integreat Chat Testumgebung auf Deutsch. Unser Team antwortet werktags, während unser Chatbot zusammenfassende Antworten aus verlinkten Artikeln liefert, die Sie zur Überprüfung wichtiger Informationen lesen sollten.',
userIsAuthor: false,
automaticAnswer: true,
}),
new ChatMessageModel({
id: 3,
body: 'Informationen zu Ihrer Frage finden Sie auf folgenden Seiten:',
userIsAuthor: false,
automaticAnswer: false,
}),
new ChatMessageModel({
id: 4,
body: 'Wie kann ich mein Deutsch verbessern?',
userIsAuthor: true,
automaticAnswer: false,
}),
]

it('should display welcome text if conversation has not started', () => {
Expand All @@ -37,11 +51,29 @@ describe('ChatConversation', () => {
const { getByText, getByTestId } = render(testMessages, false)
expect(getByText('chat:initialMessage')).toBeTruthy()
expect(getByTestId(testMessages[0]!.id)).toBeTruthy()
expect(getByTestId(testMessages[2]!.id)).toBeTruthy()
})

it('should display typing indicator before the initial automatic answer and after for 60 seconds', () => {
const { getByText, queryByText, getByTestId } = render(testMessages, false)
expect(getByTestId(testMessages[0]!.id)).toBeTruthy()
expect(getByText('...')).toBeTruthy()
expect(getByTestId(testMessages[1]!.id)).toBeTruthy()
expect(getByText('...')).toBeTruthy()

act(() => jest.runAllTimers())
expect(queryByText('...')).toBeNull()
})

it('should display typing indicator after opening the chatbot with existing conversation for unanswered user message', () => {
const { queryByText, getByTestId } = render(testMessages, false)
expect(getByTestId(testMessages[3]!.id)).toBeTruthy()
act(() => jest.runAllTimers())
expect(queryByText('...')).toBeNull()
})

it('should display error messages if error occurs', () => {
const { getByText } = render([], true)
const { getByText } = render(testMessages, true)
expect(getByText('chat:errorMessage')).toBeTruthy()
})
})
Loading