LibreChat/src/components/main/Messages.jsx

92 lines
2.6 KiB
React
Raw Normal View History

import React, { useEffect, useState, useRef } from 'react';
import Message from './Message';
import ScrollToBottom from './ScrollToBottom';
import { CSSTransition } from 'react-transition-group';
2023-02-13 18:02:29 -05:00
const Messages = ({ messages }) => {
const [showScrollButton, setShowScrollButton] = useState(false);
2023-02-13 18:02:29 -05:00
const scrollableRef = useRef(null);
const messagesEndRef = useRef(null);
useEffect(() => {
const timeoutId = setTimeout(() => {
const scrollable = scrollableRef.current;
const hasScrollbar = scrollable.scrollHeight > scrollable.clientHeight;
setShowScrollButton(hasScrollbar);
}, 850);
return () => {
clearTimeout(timeoutId);
};
}, []);
const scrollToBottom = () => {
messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
setShowScrollButton(false);
};
const handleScroll = () => {
const { scrollTop, scrollHeight, clientHeight } = scrollableRef.current;
const diff = Math.abs(scrollHeight - scrollTop);
const bottom =
diff === clientHeight || (diff <= clientHeight + 25 && diff >= clientHeight - 25);
if (bottom) {
setShowScrollButton(false);
} else {
setShowScrollButton(true);
}
2023-02-13 18:02:29 -05:00
};
let timeoutId = null;
const debouncedHandleScroll = () => {
clearTimeout(timeoutId);
timeoutId = setTimeout(handleScroll, 100);
};
const scrollHandler = (e) => {
e.preventDefault();
scrollToBottom();
};
return (
2023-02-13 18:02:29 -05:00
<div
className="flex-1 overflow-y-auto "
ref={scrollableRef}
onScroll={debouncedHandleScroll}
2023-02-13 18:02:29 -05:00
>
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}
scrollToBottom={i === messages.length - 1 ? scrollToBottom : null}
/>
2023-02-13 18:02:29 -05:00
))}
<CSSTransition
in={showScrollButton}
timeout={650}
classNames="scroll-down"
unmountOnExit={false}
appear
>
{(state) => showScrollButton && <ScrollToBottom scrollHandler={scrollHandler} />}
</CSSTransition>
2023-02-13 18:02:29 -05:00
<div
className="group h-32 w-full flex-shrink-0 dark:border-gray-900/50 dark:bg-gray-800 md:h-48"
ref={messagesEndRef}
/>
</div>
2023-02-13 18:02:29 -05:00
</div>
2023-02-08 22:58:24 -05:00
{/* </div> */}
</div>
);
2023-02-13 18:02:29 -05:00
};
export default Messages;