import { html, useRef, useEffect } from '../lib/preact.js'; import { getUserMessageBg } from '../utils/status.js'; import { MessageBubble, filterDisplayMessages } from './MessageBubble.js'; export function ChatMessages({ messages, status }) { const containerRef = useRef(null); const userBgClass = getUserMessageBg(status); const wasAtBottomRef = useRef(true); const prevMessagesLenRef = useRef(0); // Scroll to bottom on initial mount useEffect(() => { const container = containerRef.current; if (!container) return; // Always scroll to bottom on first render container.scrollTop = container.scrollHeight; }, []); // Check if scrolled to bottom before render useEffect(() => { const container = containerRef.current; if (!container) return; const checkScroll = () => { const threshold = 50; const isAtBottom = container.scrollHeight - container.scrollTop - container.clientHeight < threshold; wasAtBottomRef.current = isAtBottom; }; container.addEventListener('scroll', checkScroll); return () => container.removeEventListener('scroll', checkScroll); }, []); // Scroll to bottom on new messages if user was at bottom useEffect(() => { const container = containerRef.current; if (!container || !messages) return; const hasNewMessages = messages.length > prevMessagesLenRef.current; prevMessagesLenRef.current = messages.length; if (hasNewMessages && wasAtBottomRef.current) { container.scrollTop = container.scrollHeight; } }, [messages]); if (!messages || messages.length === 0) { return html`