import React from 'react'; import { ScrollArea } from '@/components/ui/scroll-area'; import { InView } from 'react-intersection-observer'; import { Message } from '@/components/messages/message'; import { useWorkspace } from '@/contexts/workspace'; interface MessageListProps { nodeId: string; } export const MessageList = ({ nodeId }: MessageListProps) => { const workspace = useWorkspace(); const nodes = workspace.getNodes(); const messages = nodes.filter( (node) => node.type === 'message' && node.parentId === nodeId, ); const viewportRef = React.useRef(null); const containerRef = React.useRef(null); const observerRef = React.useRef(null); const scrollPosition = React.useRef(0); const bottomRef = React.useRef(null); const bottomVisibleRef = React.useRef(false); const shouldScrollToBottom = React.useRef(true); React.useEffect(() => { if (bottomRef.current && scrollPosition.current == 0) { bottomRef.current.scrollIntoView(); } if (containerRef.current && viewportRef.current) { // observe resize of container when new messages are appended or internal elements are loaded (e.g. images) observerRef.current = new ResizeObserver(() => { if (!viewportRef.current) { return; } if (shouldScrollToBottom) { bottomRef.current?.scrollIntoView(); } else { viewportRef.current.scrollTop = viewportRef.current.scrollHeight - scrollPosition.current; } }); observerRef.current.observe(containerRef.current); return () => { if (observerRef.current) { observerRef.current.disconnect(); } }; } return () => {}; }, [nodeId]); const handleScroll = () => { if (viewportRef.current) { scrollPosition.current = viewportRef.current.scrollHeight - viewportRef.current.scrollTop; shouldScrollToBottom.current = bottomVisibleRef.current; } }; return ( { // if (inView && hasPrevious && !isLoadingPrevious) { // loadPrevious(50); // } }} > {/*
*/} {/* {isLoadingPrevious && }*/} {/*
*/}
{messages.map((message, index) => { const previousMessage = index > 0 ? messages[index - 1] : null; const currentMessageDate = new Date(message.createdAt); const previousMessageDate = previousMessage ? new Date(previousMessage.createdAt) : null; const showDate = !previousMessageDate || currentMessageDate.getDate() !== previousMessageDate.getDate(); return ( {showDate && (
{currentMessageDate.toDateString()}
)} ); })}
{ bottomVisibleRef.current = inView; }} >
); };