'use client'; import { Fragment, useEffect, useRef, useState } from 'react'; import MessageInput from './MessageInput'; import MessageBox from './MessageBox'; import MessageBoxLoading from './MessageBoxLoading'; import { useChat } from '@/lib/hooks/useChat'; const Chat = () => { 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 = () => { if (dividerRef.current) { setDividerWidth(dividerRef.current.offsetWidth); } }; 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 (messages.length === 1) { document.title = `${messages[0].query.substring(0, 30)} - Perplexica`; } if (sections.length > lastScrolledRef.current) { scroll(); lastScrolledRef.current = sections.length; } }, [messages]); return (
{sections.map((section, i) => { const isLast = i === sections.length - 1; return ( {!isLast && (
)} ); })} {loading && !messageAppeared && }
{dividerWidth > 0 && (
)}
); }; export default Chat;