import React, { forwardRef, useCallback, useEffect, useImperativeHandle, useMemo, useRef } from 'react'; import { FlatList, StyleSheet, Text, View } from 'react-native'; import { EnxAction, EnxChatTheme, EnxMessage, EnxSuggestionType } from '../types'; import { MessageCell } from './MessageCell'; import { TypingBubble } from './TypingBubble'; /** Imperative handle exposed to the parent via ref. */ export interface ChatListHandle { scrollToBottom: (animated: boolean) => void; } type Item = | { kind: 'header'; key: string; label: string } | { kind: 'message'; key: string; message: EnxMessage } | { kind: 'typing'; key: string }; const dayKey = (d: Date): string => `${d.getFullYear()}-${d.getMonth() + 1}-${d.getDate()}`; const dayText = (d: Date): string => { const now = new Date(); const t0 = new Date(now.getFullYear(), now.getMonth(), now.getDate()).getTime(); const t1 = t0 - 86400000; const d0 = new Date(d.getFullYear(), d.getMonth(), d.getDate()).getTime(); if (d0 === t0) return 'Today'; if (d0 === t1) return 'Yesterday'; return d.toLocaleDateString(); }; export const ChatList = forwardRef< ChatListHandle, { messages: EnxMessage[]; isTyping: boolean; theme: EnxChatTheme; onSuggestionTap?: (titles: string[], type: EnxSuggestionType) => void; onActionTap?: (action: EnxAction) => void; } >(({ messages, isTyping, theme, onSuggestionTap, onActionTap }, ref) => { const listRef = useRef | null>(null); const scrollToBottom = useCallback((animated: boolean): void => { listRef.current?.scrollToEnd({ animated }); }, []); // Let the parent (ChatWidget) call scrollToBottom directly — needed so the // keyboard-appear / keyboard-dismiss events can force a scroll without // relying on onLayout which fires before the FlatList metrics settle. useImperativeHandle(ref, () => ({ scrollToBottom }), [scrollToBottom]); const data = useMemo(() => { const out: Item[] = []; let prev = ''; messages.forEach((m, i) => { const key = dayKey(m.timestamp); if (key !== prev) { prev = key; out.push({ kind: 'header', key: `h-${key}-${i}`, label: dayText(m.timestamp) }); } out.push({ kind: 'message', key: `m-${m.id ?? i}`, message: m }); }); if (isTyping) out.push({ kind: 'typing', key: 'typing' }); return out; }, [messages, isTyping]); useEffect(() => { // Trigger immediate and delayed scrolls to handle fast consecutive updates. scrollToBottom(true); const t = setTimeout(() => scrollToBottom(true), 80); return () => clearTimeout(t); }, [data.length, isTyping, scrollToBottom]); return ( item.key} contentContainerStyle={styles.content} /** Without this, the first tap on a choice only dismisses the input keyboard; the handler runs on the second tap. */ keyboardShouldPersistTaps="handled" keyboardDismissMode="on-drag" removeClippedSubviews={false} onContentSizeChange={() => { scrollToBottom(true); }} onLayout={() => { // Instant snap whenever the list is resized (e.g. new message, orientation // change). Keyboard-triggered scrolls are handled explicitly in ChatWidget // via the imperative ref so the timing is tied to the LayoutAnimation. scrollToBottom(false); }} renderItem={({ item }) => { if (item.kind === 'header') { return ( {item.label} ); } if (item.kind === 'typing') { return ( ); } return ; }} /> ); }); const styles = StyleSheet.create({ content: { paddingVertical: 8 }, headWrap: { alignItems: 'center', marginVertical: 8 }, headChip: { backgroundColor: 'rgba(0,0,0,0.3)', borderRadius: 14, paddingHorizontal: 12, paddingVertical: 4 }, headTxt: { color: '#fff', fontSize: 12, fontWeight: '500' }, typingRow: { paddingHorizontal: 8, marginVertical: 4, flexDirection: 'row', justifyContent: 'flex-start' }, typingBubble: { maxWidth: '76%', borderRadius: 16, borderBottomLeftRadius: 4, overflow: 'hidden' }, });