Fixed entire calendar layout + chat layout + chat history

This commit is contained in:
c-d-p
2025-04-21 15:36:59 +02:00
parent 9e8e179a94
commit c158ff4e0e
37 changed files with 1050 additions and 285 deletions

View File

@@ -1,14 +1,14 @@
// src/screens/CalendarScreen.tsx
import React from 'react';
import { View, StyleSheet } from 'react-native';
// Import SafeAreaView
import { StyleSheet, View, SafeAreaView } from 'react-native';
import { useTheme, FAB } from 'react-native-paper';
import { useNavigation } from '@react-navigation/native';
import { StackNavigationProp } from '@react-navigation/stack';
import CustomCalendarView from '../components/calendar/CustomCalendarView'; // Import the new custom view
import CustomCalendarView from '../components/calendar/CustomCalendarView';
import { AppStackParamList } from '../navigation/AppNavigator';
// Define navigation prop type
type CalendarScreenNavigationProp = StackNavigationProp<AppStackParamList, 'Calendar'>;
const CalendarScreen = () => {
@@ -16,29 +16,45 @@ const CalendarScreen = () => {
const navigation = useNavigation<CalendarScreenNavigationProp>();
const styles = StyleSheet.create({
container: { flex: 1, backgroundColor: theme.colors.background },
// Style for SafeAreaView to ensure it fills the screen
safeArea: {
flex: 1,
backgroundColor: theme.colors.background, // Apply background here
},
// Container inside SafeAreaView might not need flex: 1 anymore,
// but keep it to ensure CustomCalendarView fills the safe area
container: {
flex: 1,
position: 'relative' // Often added for absolute children, though View defaults to relative
},
fab: {
position: 'absolute',
margin: 16,
right: 0,
bottom: 0,
// Change from margin: 16, right: 0, bottom: 0
// Explicitly set distance from the bottom/right edges of the SAFE AREA
right: 16,
bottom: 16, // Adjust this value if needed (e.g., 20 or 24) for more padding
backgroundColor: theme.colors.primary,
zIndex: 10,
},
});
return (
<View style={styles.container}>
{/* Replace the old Calendar and FlatList with the new CustomCalendarView */}
<CustomCalendarView />
// Use SafeAreaView as the outermost component
<SafeAreaView style={styles.safeArea}>
{/* Keep this inner View for structure if needed, or potentially remove */}
{/* if CustomCalendarView handles its own layout fully */}
<View style={styles.container}>
<CustomCalendarView />
{/* Keep the FAB for creating new events */}
<FAB
style={styles.fab}
icon="plus"
onPress={() => navigation.navigate('EventForm')} // Navigate without eventId for creation
color={theme.colors.onPrimary || '#ffffff'} // Ensure icon color contrasts
/>
</View>
{/* FAB is now positioned relative to the SafeAreaView's padded area */}
<FAB
style={styles.fab}
icon="plus"
onPress={() => navigation.navigate('EventForm')}
color={theme.colors.onPrimary || '#ffffff'}
/>
</View>
</SafeAreaView>
);
};

View File

@@ -1,5 +1,5 @@
// src/screens/ChatScreen.tsx
import React, { useState, useCallback, useRef } from 'react';
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 { SafeAreaView } from 'react-native-safe-area-context';
@@ -13,25 +13,68 @@ interface Message {
timestamp: Date;
}
// Define the expected structure for the API response
// Define the expected structure for the API response from /nlp/process-command
interface NlpResponse {
responses: string[]; // Expecting an array of response strings
responses: string[];
}
// Define the expected structure for the API response from /nlp/history
interface ChatHistoryResponse {
id: number;
sender: 'user' | 'ai';
text: string;
timestamp: string; // Backend sends ISO string
}
const ChatScreen = () => {
const theme = useTheme();
const [messages, setMessages] = useState<Message[]>([]);
const [inputText, setInputText] = useState('');
const [isLoading, setIsLoading] = useState(false); // To show activity indicator while AI responds
const [isLoading, setIsLoading] = useState(false);
const [isHistoryLoading, setIsHistoryLoading] = useState(true); // Add state for history loading
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) return; // Don't send empty messages
if (!trimmedText || isLoading) return; // Prevent sending while loading
const userMessage: Message = {
id: Date.now().toString() + '-user',
id: Date.now().toString() + '-user', // Temporary frontend ID
text: trimmedText,
sender: 'user',
timestamp: new Date(),
@@ -39,6 +82,7 @@ const ChatScreen = () => {
// Add user message optimistically
setMessages(prevMessages => [...prevMessages, userMessage]);
setInputText('');
setIsLoading(true);
@@ -48,7 +92,6 @@ const ChatScreen = () => {
// --- Call Backend API ---
try {
console.log(`[ChatScreen] Sending to /nlp/process-command: ${trimmedText}`);
// Expect the backend to return an object with a 'responses' array
const response = await apiClient.post<NlpResponse>('/nlp/process-command', { user_input: trimmedText });
console.log("[ChatScreen] Received response:", response.data);
@@ -56,14 +99,13 @@ const ChatScreen = () => {
if (response.data && Array.isArray(response.data.responses) && response.data.responses.length > 0) {
response.data.responses.forEach((responseText, index) => {
aiResponses.push({
id: `${Date.now()}-ai-${index}`, // Ensure unique IDs
text: responseText || "...", // Handle potential empty strings
id: `${Date.now()}-ai-${index}`, // Temporary frontend ID
text: responseText || "...",
sender: 'ai',
timestamp: new Date(),
});
});
} else {
// Handle cases where the response format is unexpected or empty
console.warn("[ChatScreen] Received invalid or empty responses array:", response.data);
aiResponses.push({
id: Date.now().toString() + '-ai-fallback',
@@ -92,7 +134,7 @@ const ChatScreen = () => {
}
// --- End API Call ---
}, [inputText]); // Keep inputText as dependency
}, [inputText, isLoading, messages]); // Add isLoading and messages to dependency array
const handleKeyPress = (e: NativeSyntheticEvent<TextInputKeyPressEventData>) => {
if (e.nativeEvent.key === 'Enter' && !(e.nativeEvent as any).shiftKey) {
@@ -118,29 +160,44 @@ const ChatScreen = () => {
};
const styles = StyleSheet.create({
container: {
container: { // For SafeAreaView
flex: 1,
backgroundColor: theme.colors.background,
},
listContainer: {
keyboardAvoidingContainer: { // Style for KAV
flex: 1,
},
listContainer: { // Container for the list, should take up available space
flex: 1,
},
messageList: {
messageList: { // Padding for the list content itself
paddingHorizontal: 10,
paddingVertical: 10,
},
inputContainer: {
inputContainer: { // Input container should stick to the bottom
flexDirection: 'row',
alignItems: 'center',
padding: 8,
alignItems: 'center', // Align items vertically in the center
paddingHorizontal: 8, // Add horizontal padding
paddingVertical: 8, // Add some vertical padding
borderTopWidth: StyleSheet.hairlineWidth,
borderTopColor: theme.colors.outlineVariant,
backgroundColor: theme.colors.elevation.level2, // Slightly elevated background
backgroundColor: theme.colors.background, // Or theme.colors.surface
},
textInput: {
flex: 1,
flex: 1, // Take available horizontal space
marginRight: 8,
backgroundColor: theme.colors.surface, // Use surface color for input background
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
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',
},
messageBubble: {
maxWidth: '80%',
@@ -166,47 +223,66 @@ const ChatScreen = () => {
}
});
// Optionally, 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>
);
}
return (
<SafeAreaView style={styles.container} edges={['bottom', 'left', 'right']}>
<KeyboardAvoidingView
style={{ flex: 1 }}
behavior={Platform.OS === "ios" ? "padding" : "height"}
keyboardVerticalOffset={Platform.OS === "ios" ? 90 : 0} // Adjust as needed
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
>
<View style={styles.listContainer}>
<FlatList
ref={flatListRef}
data={messages}
renderItem={renderMessage}
keyExtractor={(item) => item.id}
contentContainerStyle={styles.messageList}
onContentSizeChange={() => flatListRef.current?.scrollToEnd({ animated: false })} // Scroll on initial load/size change
onLayout={() => flatListRef.current?.scrollToEnd({ animated: false })} // Scroll on layout change
/>
</View>
{/* List container takes available space */}
<View style={styles.listContainer}>
<FlatList
ref={flatListRef}
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 })}
/>
</View>
<View style={styles.inputContainer}>
<TextInput
style={styles.textInput}
value={inputText}
onChangeText={setInputText}
placeholder="Type your message..."
mode="outlined" // Or "flat"
multiline
onKeyPress={handleKeyPress}
blurOnSubmit={false}
disabled={isLoading}
/>
<IconButton
icon="send"
size={24}
onPress={handleSend}
disabled={!inputText.trim() || isLoading}
mode="contained"
iconColor={theme.colors.onPrimary}
containerColor={theme.colors.primary}
/>
</View>
{/* Input container is last, outside the list's flex */}
<View style={styles.inputContainer}>
<TextInput
style={styles.textInput}
value={inputText}
onChangeText={setInputText}
placeholder="Type your message..."
mode="outlined" // Keep outlined or flat as preferred
multiline
onKeyPress={handleKeyPress}
blurOnSubmit={false} // Keep false for multiline + send button
disabled={isLoading}
dense // Try making the input slightly smaller vertically
/>
<IconButton
icon="send"
size={24}
onPress={handleSend}
disabled={!inputText.trim() || isLoading}
mode="contained"
iconColor={theme.colors.onPrimary}
containerColor={theme.colors.primary}
style={styles.sendButton} // Apply style for alignment
/>
</View>
</KeyboardAvoidingView>
</SafeAreaView>
);