feat(chat): prevent auto-scroll unless message sent

This commit is contained in:
ItzCrazyKns
2025-11-23 19:46:02 +05:30
parent b7b280637f
commit d5f62f2dca

View File

@@ -7,11 +7,12 @@ import MessageBoxLoading from './MessageBoxLoading';
import { useChat } from '@/lib/hooks/useChat';
const Chat = () => {
const { sections, chatTurns, loading, messageAppeared } = useChat();
const { sections, loading, messageAppeared, messages } = useChat();
const [dividerWidth, setDividerWidth] = useState(0);
const dividerRef = useRef<HTMLDivElement | null>(null);
const messageEnd = useRef<HTMLDivElement | null>(null);
const lastScrolledRef = useRef<number>(0);
useEffect(() => {
const updateDividerWidth = () => {
@@ -22,35 +23,40 @@ const Chat = () => {
updateDividerWidth();
const resizeObserver = new ResizeObserver(() => {
updateDividerWidth();
});
const currentRef = dividerRef.current;
if (currentRef) {
resizeObserver.observe(currentRef);
}
window.addEventListener('resize', updateDividerWidth);
return () => {
if (currentRef) {
resizeObserver.unobserve(currentRef);
}
resizeObserver.disconnect();
window.removeEventListener('resize', updateDividerWidth);
};
}, []);
}, [sections.length]);
useEffect(() => {
const scroll = () => {
messageEnd.current?.scrollIntoView({ behavior: 'auto' });
};
if (chatTurns.length === 1) {
document.title = `${chatTurns[0].content.substring(0, 30)} - Perplexica`;
if (messages.length === 1) {
document.title = `${messages[0].query.substring(0, 30)} - Perplexica`;
}
const messageEndBottom =
messageEnd.current?.getBoundingClientRect().bottom ?? 0;
const distanceFromMessageEnd = window.innerHeight - messageEndBottom;
if (distanceFromMessageEnd >= -100) {
if (sections.length > lastScrolledRef.current) {
scroll();
lastScrolledRef.current = sections.length;
}
if (chatTurns[chatTurns.length - 1]?.role === 'user') {
scroll();
}
}, [chatTurns]);
}, [messages]);
return (
<div className="flex flex-col space-y-6 pt-8 pb-44 lg:pb-32 sm:mx-4 md:mx-8">
@@ -58,7 +64,7 @@ const Chat = () => {
const isLast = i === sections.length - 1;
return (
<Fragment key={section.userMessage.messageId}>
<Fragment key={section.message.messageId}>
<MessageBox
section={section}
sectionIndex={i}