diff --git a/src/components/Chat.tsx b/src/components/Chat.tsx index 22e0a48..56c13e6 100644 --- a/src/components/Chat.tsx +++ b/src/components/Chat.tsx @@ -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(null); const messageEnd = useRef(null); + const lastScrolledRef = useRef(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 (
@@ -58,7 +64,7 @@ const Chat = () => { const isLast = i === sections.length - 1; return ( - +