From 50de65864803e835c0ee796324cca627577834c1 Mon Sep 17 00:00:00 2001
From: lunars97 <alekbarova.aizhana@gmail.com>
Date: Wed, 29 Jan 2025 09:21:46 +0100
Subject: [PATCH] Add typing indicator for automatic replies in chat

---
 web/src/components/ChatConversation.tsx | 30 +++++++++++++++++++++++++
 1 file changed, 30 insertions(+)

diff --git a/web/src/components/ChatConversation.tsx b/web/src/components/ChatConversation.tsx
index 283f451ef9..05078b7b2a 100644
--- a/web/src/components/ChatConversation.tsx
+++ b/web/src/components/ChatConversation.tsx
@@ -15,6 +15,15 @@ const InitialMessage = styled.div`
   margin-bottom: 12px;
 `
 
+const TypingIndicator = styled.div`
+  text-align: center;
+  border-radius: 5px;
+  padding: 8px;
+  width: 20px;
+  border: 1px solid ${props => props.theme.colors.textDecorationColor};
+  font-size: ${props => props.theme.fonts.contentFontSize};
+`
+
 const ErrorSendingStatus = styled.div`
   background-color: ${props => props.theme.colors.invalidInput};
   border-radius: 5px;
@@ -29,10 +38,14 @@ type ChatConversationProps = {
   className?: string
 }
 
+const TIMEOUT = 60000
+
 const ChatConversation = ({ messages, hasError, className }: ChatConversationProps): ReactElement => {
   const { t } = useTranslation('chat')
   const [messagesCount, setMessagesCount] = useState(0)
+  const [showTypingIndicator, setShowTypingIndicator] = useState(false)
   const messagesEndRef = useRef<HTMLDivElement>(null)
+  const lastMessage = messages[messages.length - 1]
 
   useEffect(() => {
     if (messagesCount < messages.length) {
@@ -41,6 +54,18 @@ const ChatConversation = ({ messages, hasError, className }: ChatConversationPro
     }
   }, [messages, messagesCount])
 
+  useEffect(() => {
+    if (!lastMessage?.userIsAuthor && lastMessage?.isAutomaticAnswer) {
+      setShowTypingIndicator(true)
+
+      const hideIndicatorTimer = setTimeout(() => {
+        setShowTypingIndicator(false)
+      }, TIMEOUT)
+
+      return () => clearTimeout(hideIndicatorTimer)
+    }
+  }, [lastMessage?.id, lastMessage?.isAutomaticAnswer, lastMessage?.userIsAuthor, messages.length]) // Correct dependencies
+
   return (
     <Container className={className}>
       {messages.length > 0 ? (
@@ -53,6 +78,11 @@ const ChatConversation = ({ messages, hasError, className }: ChatConversationPro
               showIcon={messages[index - 1]?.userIsAuthor !== message.userIsAuthor}
             />
           ))}
+          {showTypingIndicator && (
+            <TypingIndicator>
+              <strong>...</strong>
+            </TypingIndicator>
+          )}
           <div ref={messagesEndRef} />
         </>
       ) : (