[V0.3] Working dashboard calendar module
This commit is contained in:
@@ -1,9 +1,20 @@
|
||||
// src/screens/ChatScreen.tsx
|
||||
import React, { useState, useCallback, useRef, useEffect } from 'react';
|
||||
import { View, StyleSheet, FlatList, KeyboardAvoidingView, Platform, TextInput as RNTextInput, NativeSyntheticEvent, TextInputKeyPressEventData } from 'react-native';
|
||||
import { Text, useTheme, TextInput, Button, IconButton, PaperProvider } from 'react-native-paper';
|
||||
import {
|
||||
View,
|
||||
StyleSheet,
|
||||
FlatList,
|
||||
KeyboardAvoidingView,
|
||||
Platform,
|
||||
TextInput as RNTextInput, // Keep if needed for specific props, otherwise can remove
|
||||
NativeSyntheticEvent,
|
||||
TextInputKeyPressEventData,
|
||||
ActivityIndicator // Import ActivityIndicator
|
||||
} from 'react-native';
|
||||
import { Text, useTheme, TextInput, IconButton } from 'react-native-paper';
|
||||
import { SafeAreaView } from 'react-native-safe-area-context';
|
||||
import apiClient from '../api/client'; // Import the apiClient
|
||||
import { useRoute, RouteProp } from '@react-navigation/native'; // Import useRoute and RouteProp
|
||||
|
||||
// Define the structure for a message
|
||||
interface Message {
|
||||
@@ -26,73 +37,49 @@ interface ChatHistoryResponse {
|
||||
timestamp: string; // Backend sends ISO string
|
||||
}
|
||||
|
||||
// Define the type for the navigation route parameters
|
||||
type RootStackParamList = {
|
||||
Chat: { // Assuming 'Chat' is the name of the route for this screen
|
||||
initialQuestion?: string; // Make initialQuestion optional
|
||||
};
|
||||
// Add other routes here if needed
|
||||
};
|
||||
|
||||
type ChatScreenRouteProp = RouteProp<RootStackParamList, 'Chat'>;
|
||||
|
||||
const ChatScreen = () => {
|
||||
const theme = useTheme();
|
||||
const route = useRoute<ChatScreenRouteProp>(); // Get route params
|
||||
const initialQuestion = route.params?.initialQuestion; // Extract initialQuestion
|
||||
|
||||
const [messages, setMessages] = useState<Message[]>([]);
|
||||
const [inputText, setInputText] = useState('');
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [isHistoryLoading, setIsHistoryLoading] = useState(true); // Add state for history loading
|
||||
const [isLoading, setIsLoading] = useState(false); // Loading state for sending messages
|
||||
const [isHistoryLoading, setIsHistoryLoading] = useState(true); // Loading state for initial history fetch
|
||||
const flatListRef = useRef<FlatList>(null);
|
||||
|
||||
// --- Load messages from backend API on mount ---
|
||||
useEffect(() => {
|
||||
const loadHistory = async () => {
|
||||
setIsHistoryLoading(true);
|
||||
try {
|
||||
console.log("[ChatScreen] Fetching chat history from /nlp/history");
|
||||
const response = await apiClient.get<ChatHistoryResponse[]>('/nlp/history');
|
||||
console.log("[ChatScreen] Received history:", response.data);
|
||||
|
||||
if (response.data && Array.isArray(response.data)) {
|
||||
// Map backend response to frontend Message format
|
||||
const historyMessages = response.data.map((msg) => ({
|
||||
id: msg.id.toString(), // Convert backend ID to string for keyExtractor
|
||||
text: msg.text,
|
||||
sender: msg.sender,
|
||||
timestamp: new Date(msg.timestamp), // Convert ISO string to Date
|
||||
}));
|
||||
setMessages(historyMessages);
|
||||
} else {
|
||||
console.warn("[ChatScreen] Received invalid history data:", response.data);
|
||||
setMessages([]); // Set to empty array if data is invalid
|
||||
}
|
||||
} catch (error: any) {
|
||||
console.error("Failed to load chat history from backend:", error.response?.data || error.message || error);
|
||||
// Optionally, show an error message to the user
|
||||
// For now, just start with an empty chat
|
||||
setMessages([]);
|
||||
} finally {
|
||||
setIsHistoryLoading(false);
|
||||
}
|
||||
};
|
||||
loadHistory();
|
||||
}, []); // Empty dependency array ensures this runs only once on mount
|
||||
|
||||
// Function to handle sending a message
|
||||
const handleSend = useCallback(async () => {
|
||||
const trimmedText = inputText.trim();
|
||||
if (!trimmedText || isLoading) return; // Prevent sending while loading
|
||||
// --- Function to send a message to the backend --- (Extracted logic)
|
||||
const sendMessageToApi = useCallback(async (textToSend: string) => {
|
||||
if (!textToSend) return; // Don't send empty messages
|
||||
|
||||
const userMessage: Message = {
|
||||
id: Date.now().toString() + '-user', // Temporary frontend ID
|
||||
text: trimmedText,
|
||||
text: textToSend,
|
||||
sender: 'user',
|
||||
timestamp: new Date(),
|
||||
};
|
||||
|
||||
// Add user message optimistically
|
||||
setMessages(prevMessages => [...prevMessages, userMessage]);
|
||||
|
||||
setInputText('');
|
||||
setIsLoading(true);
|
||||
|
||||
// Scroll to bottom after sending user message
|
||||
// Scroll to bottom after adding user message
|
||||
setTimeout(() => flatListRef.current?.scrollToEnd({ animated: true }), 100);
|
||||
|
||||
// --- Call Backend API ---
|
||||
try {
|
||||
console.log(`[ChatScreen] Sending to /nlp/process-command: ${trimmedText}`);
|
||||
const response = await apiClient.post<NlpResponse>('/nlp/process-command', { user_input: trimmedText });
|
||||
console.log(`[ChatScreen] Sending to /nlp/process-command: ${textToSend}`);
|
||||
const response = await apiClient.post<NlpResponse>('/nlp/process-command', { user_input: textToSend });
|
||||
console.log("[ChatScreen] Received response:", response.data);
|
||||
|
||||
const aiResponses: Message[] = [];
|
||||
@@ -100,7 +87,7 @@ const ChatScreen = () => {
|
||||
response.data.responses.forEach((responseText, index) => {
|
||||
aiResponses.push({
|
||||
id: `${Date.now()}-ai-${index}`, // Temporary frontend ID
|
||||
text: responseText || "...",
|
||||
text: responseText || "...", // Handle potentially empty strings
|
||||
sender: 'ai',
|
||||
timestamp: new Date(),
|
||||
});
|
||||
@@ -109,7 +96,7 @@ const ChatScreen = () => {
|
||||
console.warn("[ChatScreen] Received invalid or empty responses array:", response.data);
|
||||
aiResponses.push({
|
||||
id: Date.now().toString() + '-ai-fallback',
|
||||
text: "Sorry, I didn't get a valid response.",
|
||||
text: "Sorry, I couldn't process that properly.",
|
||||
sender: 'ai',
|
||||
timestamp: new Date(),
|
||||
});
|
||||
@@ -133,13 +120,92 @@ const ChatScreen = () => {
|
||||
setTimeout(() => flatListRef.current?.scrollToEnd({ animated: true }), 100);
|
||||
}
|
||||
// --- End API Call ---
|
||||
// NOTE: Removed `messages` from dependency array to prevent potential loops.
|
||||
// State updates within useCallback using the functional form `setMessages(prev => ...)`
|
||||
// don't require the state itself as a dependency.
|
||||
}, []);
|
||||
|
||||
}, [inputText, isLoading, messages]); // Add isLoading and messages to dependency array
|
||||
// --- Load messages from backend API on mount & handle initial question ---
|
||||
useEffect(() => {
|
||||
let isMounted = true; // Flag to prevent state updates on unmounted component
|
||||
|
||||
const loadHistoryAndSendInitial = async () => {
|
||||
console.log("[ChatScreen] Component mounted. Loading history...");
|
||||
setIsHistoryLoading(true);
|
||||
let historyLoadedSuccessfully = false;
|
||||
try {
|
||||
const response = await apiClient.get<ChatHistoryResponse[]>('/nlp/history');
|
||||
if (isMounted) {
|
||||
console.log("[ChatScreen] Received history:", response.data);
|
||||
if (response.data && Array.isArray(response.data)) {
|
||||
const historyMessages = response.data.map((msg) => ({
|
||||
id: msg.id.toString(),
|
||||
text: msg.text,
|
||||
sender: msg.sender,
|
||||
timestamp: new Date(msg.timestamp),
|
||||
}));
|
||||
setMessages(historyMessages);
|
||||
historyLoadedSuccessfully = true; // Mark history as loaded
|
||||
} else {
|
||||
console.warn("[ChatScreen] Received invalid history data:", response.data);
|
||||
setMessages([]);
|
||||
}
|
||||
}
|
||||
} catch (error: any) {
|
||||
if (isMounted) {
|
||||
console.error("Failed to load chat history:", error.response?.data || error.message || error);
|
||||
setMessages([]); // Clear messages on error
|
||||
}
|
||||
} finally {
|
||||
if (isMounted) {
|
||||
setIsHistoryLoading(false);
|
||||
console.log("[ChatScreen] History loading finished. History loaded:", historyLoadedSuccessfully);
|
||||
// Send initial question *after* history load attempt, if provided
|
||||
if (initialQuestion) {
|
||||
console.log("[ChatScreen] Initial question provided:", initialQuestion);
|
||||
// Check if the initial question is already the last message from history (simple check)
|
||||
const lastMessageText = messages[messages.length - 1]?.text;
|
||||
if (lastMessageText !== initialQuestion) {
|
||||
console.log("[ChatScreen] Sending initial question now.");
|
||||
// Use a timeout to ensure history state update is processed before sending
|
||||
setTimeout(() => sendMessageToApi(initialQuestion), 0);
|
||||
} else {
|
||||
console.log("[ChatScreen] Initial question seems to match last history message, not sending again.");
|
||||
}
|
||||
} else {
|
||||
console.log("[ChatScreen] No initial question provided.");
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
loadHistoryAndSendInitial();
|
||||
|
||||
return () => {
|
||||
isMounted = false; // Cleanup function to set flag on unmount
|
||||
console.log("[ChatScreen] Component unmounted.");
|
||||
};
|
||||
// Run only once on mount. `initialQuestion` is stable after mount.
|
||||
// `sendMessageToApi` is memoized by useCallback.
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [initialQuestion, sendMessageToApi]);
|
||||
|
||||
// Function to handle sending a message via input button
|
||||
const handleSend = useCallback(async () => {
|
||||
const trimmedText = inputText.trim();
|
||||
if (!trimmedText || isLoading) return;
|
||||
|
||||
setInputText(''); // Clear input immediately
|
||||
await sendMessageToApi(trimmedText); // Use the extracted function
|
||||
|
||||
}, [inputText, isLoading, sendMessageToApi]);
|
||||
|
||||
// Function to handle Enter key press for sending
|
||||
const handleKeyPress = (e: NativeSyntheticEvent<TextInputKeyPressEventData>) => {
|
||||
// Check if Enter is pressed without Shift key
|
||||
if (e.nativeEvent.key === 'Enter' && !(e.nativeEvent as any).shiftKey) {
|
||||
e.preventDefault(); // Prevent new line
|
||||
handleSend();
|
||||
e.preventDefault(); // Prevent default behavior (like newline)
|
||||
handleSend(); // Trigger send action
|
||||
}
|
||||
};
|
||||
|
||||
@@ -164,6 +230,12 @@ const ChatScreen = () => {
|
||||
flex: 1,
|
||||
backgroundColor: theme.colors.background,
|
||||
},
|
||||
loadingContainer: { // Centering container for loading indicator
|
||||
flex: 1,
|
||||
justifyContent: 'center',
|
||||
alignItems: 'center',
|
||||
backgroundColor: theme.colors.background,
|
||||
},
|
||||
keyboardAvoidingContainer: { // Style for KAV
|
||||
flex: 1,
|
||||
},
|
||||
@@ -181,39 +253,33 @@ const ChatScreen = () => {
|
||||
paddingVertical: 8, // Add some vertical padding
|
||||
borderTopWidth: StyleSheet.hairlineWidth,
|
||||
borderTopColor: theme.colors.outlineVariant,
|
||||
backgroundColor: theme.colors.background, // Or theme.colors.surface
|
||||
backgroundColor: theme.colors.surface, // Use surface color for input area
|
||||
},
|
||||
textInput: {
|
||||
flex: 1, // Take available horizontal space
|
||||
marginRight: 8,
|
||||
backgroundColor: theme.colors.surface,
|
||||
paddingTop: 10, // Keep the vertical alignment fix for placeholder
|
||||
paddingHorizontal: 10,
|
||||
// Add some vertical padding inside the input itself
|
||||
paddingVertical: Platform.OS === 'ios' ? 10 : 5, // Adjust padding for different platforms if needed
|
||||
backgroundColor: theme.colors.surface, // Match container background
|
||||
// Remove explicit padding if mode="outlined" handles it well
|
||||
maxHeight: 100, // Optional: prevent input from getting too tall with multiline
|
||||
},
|
||||
sendButton: {
|
||||
marginVertical: 4, // Adjust vertical alignment if needed
|
||||
// Ensure button doesn't shrink
|
||||
height: 40, // Match TextInput height approx.
|
||||
justifyContent: 'center',
|
||||
margin: 0, // Remove default margins if IconButton has them
|
||||
},
|
||||
messageBubble: {
|
||||
maxWidth: '80%',
|
||||
padding: 10,
|
||||
borderRadius: 15,
|
||||
padding: 12, // Slightly larger padding
|
||||
borderRadius: 18, // More rounded corners
|
||||
marginBottom: 10,
|
||||
},
|
||||
userBubble: {
|
||||
alignSelf: 'flex-end',
|
||||
backgroundColor: theme.colors.primary,
|
||||
borderBottomRightRadius: 5,
|
||||
borderBottomRightRadius: 5, // Keep the chat bubble tail effect
|
||||
},
|
||||
aiBubble: {
|
||||
alignSelf: 'flex-start',
|
||||
backgroundColor: theme.colors.surfaceVariant,
|
||||
borderBottomLeftRadius: 5,
|
||||
borderBottomLeftRadius: 5, // Keep the chat bubble tail effect
|
||||
},
|
||||
timestamp: {
|
||||
fontSize: 10,
|
||||
@@ -223,13 +289,12 @@ const ChatScreen = () => {
|
||||
}
|
||||
});
|
||||
|
||||
// Optionally, show a loading indicator while history loads
|
||||
// Show a loading indicator while history loads
|
||||
if (isHistoryLoading) {
|
||||
return (
|
||||
<SafeAreaView style={styles.container} edges={['bottom', 'left', 'right']}>
|
||||
<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
|
||||
<Text>Loading chat history...</Text>
|
||||
</View>
|
||||
<SafeAreaView style={styles.loadingContainer} edges={['bottom', 'left', 'right']}>
|
||||
<ActivityIndicator animating={true} size="large" color={theme.colors.primary} />
|
||||
<Text style={{ marginTop: 10, color: theme.colors.onBackground }}>Loading chat history...</Text>
|
||||
</SafeAreaView>
|
||||
);
|
||||
}
|
||||
@@ -237,13 +302,9 @@ const ChatScreen = () => {
|
||||
return (
|
||||
<SafeAreaView style={styles.container} edges={['bottom', 'left', 'right']}>
|
||||
<KeyboardAvoidingView
|
||||
style={styles.keyboardAvoidingContainer} // Use style with flex: 1
|
||||
// Use 'padding' for both iOS and Android
|
||||
behavior={Platform.OS === "ios" ? "padding" : "padding"}
|
||||
// Remove keyboardVerticalOffset for Android when using padding.
|
||||
// Keep iOS offset if needed (e.g., for header).
|
||||
// Assuming headerHeight might be needed for iOS, otherwise set to 0.
|
||||
keyboardVerticalOffset={Platform.OS === "ios" ? 60 : 0} // Example iOS offset, adjust if necessary
|
||||
style={styles.keyboardAvoidingContainer}
|
||||
behavior={Platform.OS === "ios" ? "padding" : "height"} // Use height for Android if padding causes issues
|
||||
keyboardVerticalOffset={Platform.OS === "ios" ? 60 : 0} // Adjust as needed
|
||||
>
|
||||
{/* List container takes available space */}
|
||||
<View style={styles.listContainer}>
|
||||
@@ -252,9 +313,11 @@ const ChatScreen = () => {
|
||||
data={messages}
|
||||
renderItem={renderMessage}
|
||||
keyExtractor={(item) => item.id}
|
||||
contentContainerStyle={styles.messageList} // Padding inside the scrollable content
|
||||
onContentSizeChange={() => flatListRef.current?.scrollToEnd({ animated: false })}
|
||||
onLayout={() => flatListRef.current?.scrollToEnd({ animated: false })}
|
||||
contentContainerStyle={styles.messageList}
|
||||
// Optimization: remove onContentSizeChange/onLayout if not strictly needed for scrolling
|
||||
// onContentSizeChange={() => flatListRef.current?.scrollToEnd({ animated: false })}
|
||||
// onLayout={() => flatListRef.current?.scrollToEnd({ animated: false })}
|
||||
// Consider initialScrollIndex or other props if performance is an issue
|
||||
/>
|
||||
</View>
|
||||
|
||||
@@ -264,13 +327,14 @@ const ChatScreen = () => {
|
||||
style={styles.textInput}
|
||||
value={inputText}
|
||||
onChangeText={setInputText}
|
||||
placeholder="Type your message..."
|
||||
mode="outlined" // Keep outlined or flat as preferred
|
||||
placeholder="Ask MAIA..."
|
||||
mode="outlined"
|
||||
multiline
|
||||
onKeyPress={handleKeyPress}
|
||||
onKeyPress={handleKeyPress} // Use onKeyPress for web/desktop-like Enter behavior
|
||||
blurOnSubmit={false} // Keep false for multiline + send button
|
||||
disabled={isLoading}
|
||||
dense // Try making the input slightly smaller vertically
|
||||
disabled={isLoading} // Disable input while AI is responding
|
||||
outlineStyle={{ borderRadius: 20 }} // Make input more rounded
|
||||
dense // Reduce vertical padding
|
||||
/>
|
||||
<IconButton
|
||||
icon="send"
|
||||
@@ -280,7 +344,8 @@ const ChatScreen = () => {
|
||||
mode="contained"
|
||||
iconColor={theme.colors.onPrimary}
|
||||
containerColor={theme.colors.primary}
|
||||
style={styles.sendButton} // Apply style for alignment
|
||||
style={styles.sendButton}
|
||||
animated // Add subtle animation
|
||||
/>
|
||||
</View>
|
||||
</KeyboardAvoidingView>
|
||||
|
||||
Reference in New Issue
Block a user