import React, { useRef, useState, useEffect } from "react"; import { ScrollView, StyleSheet, RefreshControl, View } from "react-native"; import type { NativeScrollEvent, NativeSyntheticEvent } from "react-native"; import type { OperoChatMessage } from "../types"; import { OperoChatBubble } from "./OperoChatBubble"; import { OperoScrollToBottom } from "./OperoScrollToBottom"; export interface OperoChatMessagesProps { messages: OperoChatMessage[]; customStyles?: any; onRefresh?: () => void; refreshing?: boolean; onReaction?: ( messageId: string, reactionType: "thumbs_up" | "thumbs_down", ) => void; } export const OperoChatMessages: React.FC = ({ messages, customStyles, onRefresh, refreshing = false, onReaction, }) => { const styles = createStyles(); const scrollViewRef = useRef(null); const [showScrollButton, setShowScrollButton] = useState(false); const [contentHeight, setContentHeight] = useState(0); const [scrollViewHeight, setScrollViewHeight] = useState(0); const isAtBottomRef = useRef(true); // Check if assistant message is streaming const isStreaming = messages.some( (msg) => msg.role === "assistant" && msg.isStreaming, ); // Auto-scroll when new content arrives if user was already at bottom useEffect(() => { if (isAtBottomRef.current) { scrollToBottom(); } }, [messages]); // Show scroll button when streaming OR when user scrolls up useEffect(() => { if (isStreaming) { if (!isAtBottomRef.current) { setShowScrollButton(true); } } else { if (!isAtBottomRef.current && contentHeight > scrollViewHeight) { setShowScrollButton(true); } else { setShowScrollButton(false); } } }, [isStreaming, contentHeight, scrollViewHeight]); const scrollToBottom = () => { scrollViewRef.current?.scrollToEnd({ animated: true }); isAtBottomRef.current = true; setShowScrollButton(false); }; const handleScroll = (event: NativeSyntheticEvent) => { const { contentOffset, contentSize, layoutMeasurement } = event.nativeEvent; const isAtBottom = contentOffset.y + layoutMeasurement.height >= contentSize.height - 20; // 20px threshold isAtBottomRef.current = isAtBottom; // Update state for button visibility setContentHeight(contentSize.height); setScrollViewHeight(layoutMeasurement.height); if (isAtBottom) { setShowScrollButton(false); } else if (isStreaming || contentSize.height > layoutMeasurement.height) { setShowScrollButton(true); } }; return ( ) : undefined } automaticallyAdjustKeyboardInsets={true} keyboardShouldPersistTaps="handled" onScroll={handleScroll} scrollEventThrottle={16} > {messages.map((message) => ( ))} ); }; const createStyles = () => StyleSheet.create({ wrapper: { flex: 1, position: "relative", }, container: { flex: 1, backgroundColor: "transparent", }, contentContainer: { paddingHorizontal: 16, paddingVertical: 12, paddingBottom: 20, // Extra padding at bottom for better scrolling }, });