quick fix to autoscroll on chat window

This commit is contained in:
c-d-p
2025-04-21 20:25:16 +02:00
parent 4f57df8101
commit 5df6ae35cc

View File

@@ -72,10 +72,6 @@ const ChatScreen = () => {
// Add user message optimistically // Add user message optimistically
setMessages(prevMessages => [...prevMessages, userMessage]); setMessages(prevMessages => [...prevMessages, userMessage]);
setIsLoading(true); setIsLoading(true);
// Scroll to bottom after adding user message
setTimeout(() => flatListRef.current?.scrollToEnd({ animated: true }), 100);
// --- Call Backend API --- // --- Call Backend API ---
try { try {
console.log(`[ChatScreen] Sending to /nlp/process-command: ${textToSend}`); console.log(`[ChatScreen] Sending to /nlp/process-command: ${textToSend}`);
@@ -116,14 +112,9 @@ const ChatScreen = () => {
setMessages(prevMessages => [...prevMessages, errorResponse]); setMessages(prevMessages => [...prevMessages, errorResponse]);
} finally { } finally {
setIsLoading(false); setIsLoading(false);
// Scroll to bottom after receiving AI message(s)
setTimeout(() => flatListRef.current?.scrollToEnd({ animated: true }), 100);
} }
// --- End API Call --- // --- End API Call ---
// NOTE: Removed `messages` from dependency array to prevent potential loops. }, []); // Dependencies are correct
// State updates within useCallback using the functional form `setMessages(prev => ...)`
// don't require the state itself as a dependency.
}, []);
// --- Load messages from backend API on mount & handle initial question --- // --- Load messages from backend API on mount & handle initial question ---
useEffect(() => { useEffect(() => {
@@ -146,6 +137,8 @@ const ChatScreen = () => {
})); }));
setMessages(historyMessages); setMessages(historyMessages);
historyLoadedSuccessfully = true; // Mark history as loaded historyLoadedSuccessfully = true; // Mark history as loaded
// ADDED BACK: Scroll after initial history is set, with a delay
setTimeout(() => flatListRef.current?.scrollToEnd({ animated: false }), 100);
} else { } else {
console.warn("[ChatScreen] Received invalid history data:", response.data); console.warn("[ChatScreen] Received invalid history data:", response.data);
setMessages([]); setMessages([]);
@@ -163,15 +156,18 @@ const ChatScreen = () => {
// Send initial question *after* history load attempt, if provided // Send initial question *after* history load attempt, if provided
if (initialQuestion) { if (initialQuestion) {
console.log("[ChatScreen] Initial question provided:", initialQuestion); console.log("[ChatScreen] Initial question provided:", initialQuestion);
// Check if the initial question is already the last message from history (simple check) // Use functional update form of setMessages to get the latest state
const lastMessageText = messages[messages.length - 1]?.text; setMessages(currentMessages => {
if (lastMessageText !== initialQuestion) { const lastMessageText = currentMessages[currentMessages.length - 1]?.text;
console.log("[ChatScreen] Sending initial question now."); if (lastMessageText !== initialQuestion) {
// Use a timeout to ensure history state update is processed before sending console.log("[ChatScreen] Sending initial question now.");
setTimeout(() => sendMessageToApi(initialQuestion), 0); // Use a timeout to ensure history state update is processed before sending
} else { setTimeout(() => sendMessageToApi(initialQuestion), 0);
console.log("[ChatScreen] Initial question seems to match last history message, not sending again."); } else {
} console.log("[ChatScreen] Initial question seems to match last history message, not sending again.");
}
return currentMessages; // Return the state unchanged if not sending
});
} else { } else {
console.log("[ChatScreen] No initial question provided."); console.log("[ChatScreen] No initial question provided.");
} }
@@ -185,8 +181,7 @@ const ChatScreen = () => {
isMounted = false; // Cleanup function to set flag on unmount isMounted = false; // Cleanup function to set flag on unmount
console.log("[ChatScreen] Component unmounted."); console.log("[ChatScreen] Component unmounted.");
}; };
// Run only once on mount. `initialQuestion` is stable after mount. // Dependencies are correct
// `sendMessageToApi` is memoized by useCallback.
// eslint-disable-next-line react-hooks/exhaustive-deps // eslint-disable-next-line react-hooks/exhaustive-deps
}, [initialQuestion, sendMessageToApi]); }, [initialQuestion, sendMessageToApi]);
@@ -314,10 +309,8 @@ const ChatScreen = () => {
renderItem={renderMessage} renderItem={renderMessage}
keyExtractor={(item) => item.id} keyExtractor={(item) => item.id}
contentContainerStyle={styles.messageList} contentContainerStyle={styles.messageList}
// Optimization: remove onContentSizeChange/onLayout if not strictly needed for scrolling // ADDED: Scroll to end when content size changes
// onContentSizeChange={() => flatListRef.current?.scrollToEnd({ animated: false })} onContentSizeChange={() => flatListRef.current?.scrollToEnd({ animated: false })}
// onLayout={() => flatListRef.current?.scrollToEnd({ animated: false })}
// Consider initialScrollIndex or other props if performance is an issue
/> />
</View> </View>