2023-02-13 16:31:18 -05:00
|
|
|
import React, { useEffect, useState, useRef } from 'react';
|
2023-02-13 13:32:54 -05:00
|
|
|
import useDidMountEffect from '~/hooks/useDidMountEffect';
|
2023-02-05 19:41:24 -05:00
|
|
|
import Message from './Message';
|
2023-02-13 16:31:18 -05:00
|
|
|
import ScrollToBottom from './ScrollToBottom';
|
2023-02-05 19:41:24 -05:00
|
|
|
|
2023-02-13 18:02:29 -05:00
|
|
|
const Messages = ({ messages }) => {
|
2023-02-13 16:31:18 -05:00
|
|
|
const [showScrollButton, setShowScrollButton] = useState(false);
|
2023-02-13 18:02:29 -05:00
|
|
|
const scrollableRef = useRef(null);
|
|
|
|
|
const messagesEndRef = useRef(null);
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
useEffect(() => {
|
|
|
|
|
const scrollable = scrollableRef.current;
|
|
|
|
|
const hasScrollbar = scrollable.scrollHeight > scrollable.clientHeight;
|
|
|
|
|
setShowScrollButton(hasScrollbar);
|
|
|
|
|
}, [scrollableRef]);
|
2023-02-05 19:41:24 -05:00
|
|
|
|
|
|
|
|
const scrollToBottom = () => {
|
|
|
|
|
messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
|
|
|
|
|
};
|
|
|
|
|
|
2023-02-13 16:31:18 -05:00
|
|
|
const handleScroll = (e) => {
|
|
|
|
|
const bottom = e.target.scrollHeight - e.target.scrollTop === e.target.clientHeight;
|
|
|
|
|
if (bottom) {
|
|
|
|
|
setShowScrollButton(false);
|
|
|
|
|
} else {
|
|
|
|
|
setShowScrollButton(true);
|
|
|
|
|
}
|
2023-02-13 18:02:29 -05:00
|
|
|
};
|
2023-02-13 16:31:18 -05:00
|
|
|
|
|
|
|
|
const scrollHandler = (e) => {
|
|
|
|
|
e.preventDefault();
|
|
|
|
|
scrollToBottom();
|
|
|
|
|
};
|
2023-02-05 19:41:24 -05:00
|
|
|
|
|
|
|
|
return (
|
2023-02-13 18:02:29 -05:00
|
|
|
<div
|
|
|
|
|
className="flex-1 overflow-y-auto "
|
|
|
|
|
ref={scrollableRef}
|
|
|
|
|
onScroll={handleScroll}
|
|
|
|
|
>
|
2023-02-08 22:58:24 -05:00
|
|
|
{/* <div className="flex-1 overflow-hidden"> */}
|
2023-02-13 18:02:29 -05:00
|
|
|
<div className="h-full dark:bg-gray-800">
|
|
|
|
|
<div className="flex h-full flex-col items-center text-sm dark:bg-gray-800">
|
|
|
|
|
{messages.map((message, i) => (
|
|
|
|
|
<Message
|
|
|
|
|
key={i}
|
|
|
|
|
sender={message.sender}
|
|
|
|
|
text={message.text}
|
|
|
|
|
last={i === messages.length - 1}
|
|
|
|
|
error={!!message.error ? true : false}
|
2023-02-08 09:15:47 -05:00
|
|
|
/>
|
2023-02-13 18:02:29 -05:00
|
|
|
))}
|
|
|
|
|
{showScrollButton && <ScrollToBottom scrollHandler={scrollHandler} />}
|
|
|
|
|
<div
|
|
|
|
|
className="group h-32 w-full flex-shrink-0 dark:border-gray-900/50 dark:bg-gray-800 md:h-48"
|
|
|
|
|
ref={messagesEndRef}
|
|
|
|
|
/>
|
2023-02-08 09:15:47 -05:00
|
|
|
</div>
|
2023-02-13 18:02:29 -05:00
|
|
|
</div>
|
2023-02-08 22:58:24 -05:00
|
|
|
{/* </div> */}
|
2023-02-05 19:41:24 -05:00
|
|
|
</div>
|
|
|
|
|
);
|
2023-02-13 18:02:29 -05:00
|
|
|
};
|
|
|
|
|
|
|
|
|
|
export default Messages
|