[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>
|
||||
|
||||
@@ -1,18 +1,212 @@
|
||||
// src/screens/DashboardScreen.tsx
|
||||
import React from 'react';
|
||||
import { View, StyleSheet } from 'react-native';
|
||||
import { Text, useTheme } from 'react-native-paper';
|
||||
import React, { useState, useEffect } from 'react'; // Added useEffect
|
||||
import { View, StyleSheet, ScrollView } from 'react-native'; // Added ScrollView
|
||||
import { Text, TextInput, Button, useTheme, Card, List, Divider } from 'react-native-paper'; // Added Card, List, Divider
|
||||
import { useNavigation } from '@react-navigation/native';
|
||||
import { StackNavigationProp } from '@react-navigation/stack';
|
||||
import { format, addDays, startOfDay, isSameDay, parseISO, endOfDay } from 'date-fns'; // Added date-fns imports
|
||||
import { getCalendarEvents } from '../api/calendar';
|
||||
import { CalendarEvent } from '../types/calendar';
|
||||
|
||||
|
||||
// Placeholder for the TODO component
|
||||
const TodoComponent = () => (
|
||||
<View style={{ marginVertical: 10, padding: 10, borderWidth: 1, borderColor: 'grey' }}>
|
||||
<Text>TODO Component Placeholder</Text>
|
||||
</View>
|
||||
);
|
||||
|
||||
// --- Calendar Preview Component Implementation ---
|
||||
const CalendarPreview = () => {
|
||||
const theme = useTheme();
|
||||
const [eventsByDay, setEventsByDay] = useState<{ [key: string]: CalendarEvent[] }>({});
|
||||
const today = startOfDay(new Date());
|
||||
const days = [today, addDays(today, 1), addDays(today, 2)];
|
||||
|
||||
useEffect(() => {
|
||||
const fetchAndProcessEvents = async () => {
|
||||
try {
|
||||
// Fetch events for the entire 3-day range once
|
||||
const endDate = endOfDay(addDays(today, 2)); // Calculate end date to include the whole day
|
||||
const allEvents = await getCalendarEvents(today, endDate); // Fetch events until the end of the third day
|
||||
|
||||
// Process events: Group by day
|
||||
const groupedEvents: { [key: string]: CalendarEvent[] } = {};
|
||||
days.forEach(day => {
|
||||
const dayStr = format(day, 'yyyy-MM-dd');
|
||||
// Filter events for the current day and sort them
|
||||
groupedEvents[dayStr] = allEvents
|
||||
.filter(event => isSameDay(parseISO(event.start), day))
|
||||
.sort((a, b) => parseISO(a.start).getTime() - parseISO(b.start).getTime());
|
||||
});
|
||||
setEventsByDay(groupedEvents);
|
||||
} catch (error) {
|
||||
console.error("Failed to fetch calendar events:", error);
|
||||
// Optionally, set an error state here to display to the user
|
||||
}
|
||||
};
|
||||
fetchAndProcessEvents();
|
||||
}, []); // Run once on mount
|
||||
|
||||
const formatDateHeader = (date: Date): string => {
|
||||
if (isSameDay(date, today)) return `Today, ${format(date, 'MMMM d')}`;
|
||||
if (isSameDay(date, addDays(today, 1))) return `Tomorrow, ${format(date, 'MMMM d')}`;
|
||||
return format(date, 'EEEE, MMMM d');
|
||||
};
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
card: {
|
||||
marginVertical: 8,
|
||||
backgroundColor: theme.colors.background,
|
||||
},
|
||||
dayHeader: {
|
||||
fontSize: 16,
|
||||
fontWeight: 'bold',
|
||||
paddingLeft: 16,
|
||||
paddingTop: 12,
|
||||
paddingBottom: 8,
|
||||
color: theme.colors.primary,
|
||||
},
|
||||
listItem: {
|
||||
paddingVertical: 4, // Reduce padding slightly
|
||||
},
|
||||
eventTime: {
|
||||
fontSize: 14,
|
||||
color: theme.colors.onSurfaceVariant, // Ensure contrast
|
||||
},
|
||||
eventTitle: {
|
||||
fontSize: 15,
|
||||
color: theme.colors.onSurface,
|
||||
},
|
||||
noEventsText: {
|
||||
paddingLeft: 16,
|
||||
paddingBottom: 12,
|
||||
fontStyle: 'italic',
|
||||
color: theme.colors.onSurfaceDisabled,
|
||||
},
|
||||
divider: {
|
||||
marginHorizontal: 16,
|
||||
}
|
||||
});
|
||||
|
||||
return (
|
||||
<Card style={styles.card} elevation={1}>
|
||||
<Card.Content style={{ paddingHorizontal: 0, paddingVertical: 0 }}>
|
||||
{days.map((day, index) => {
|
||||
const dayStr = format(day, 'yyyy-MM-dd');
|
||||
const dailyEvents = eventsByDay[dayStr] || [];
|
||||
return (
|
||||
<View key={dayStr}>
|
||||
<Text style={styles.dayHeader}>{formatDateHeader(day)}</Text>
|
||||
{dailyEvents.length > 0 ? (
|
||||
dailyEvents.map((event, eventIndex) => (
|
||||
<React.Fragment key={event.id}>
|
||||
<List.Item
|
||||
title={event.title}
|
||||
titleStyle={styles.eventTitle}
|
||||
description={format(parseISO(event.start), 'p')} // Format time like '1:30 PM'
|
||||
descriptionStyle={styles.eventTime}
|
||||
style={styles.listItem}
|
||||
left={props => <List.Icon {...props} icon="circle-small" />} // Simple indicator
|
||||
/>
|
||||
{eventIndex < dailyEvents.length - 1 && <Divider style={styles.divider} />}
|
||||
</React.Fragment>
|
||||
))
|
||||
) : (
|
||||
<Text style={styles.noEventsText}>No events scheduled.</Text>
|
||||
)}
|
||||
{/* Add divider between days, except after the last day */}
|
||||
{index < days.length - 1 && <Divider style={{marginTop: 8}} />}
|
||||
</View>
|
||||
);
|
||||
})}
|
||||
</Card.Content>
|
||||
</Card>
|
||||
);
|
||||
};
|
||||
// --- End Calendar Preview Component ---
|
||||
|
||||
// Define the type for the navigation stack parameters
|
||||
// Ensure this matches the navigator's configuration
|
||||
type RootStackParamList = {
|
||||
Dashboard: undefined; // No params expected for Dashboard itself
|
||||
Chat: { initialQuestion?: string }; // Chat screen expects an optional initialQuestion
|
||||
// Add other screens in your stack here
|
||||
};
|
||||
|
||||
// Define the specific navigation prop type for DashboardScreen
|
||||
type DashboardScreenNavigationProp = StackNavigationProp<RootStackParamList, 'Dashboard'>;
|
||||
|
||||
const DashboardScreen = () => {
|
||||
const theme = useTheme();
|
||||
// Use the specific navigation prop type
|
||||
const navigation = useNavigation<DashboardScreenNavigationProp>();
|
||||
const [question, setQuestion] = useState('');
|
||||
|
||||
const handleQuestionSubmit = () => {
|
||||
const trimmedQuestion = question.trim();
|
||||
if (trimmedQuestion) {
|
||||
// Navigate to ChatScreen, passing the question as a param
|
||||
navigation.navigate('Chat', { initialQuestion: trimmedQuestion });
|
||||
// console.log('Navigating to ChatScreen with question:', question); // Keep for debugging if needed
|
||||
setQuestion(''); // Clear input after submission
|
||||
}
|
||||
};
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
container: { flex: 1, alignItems: 'center', justifyContent: 'center', padding: 16, backgroundColor: theme.colors.background },
|
||||
text: { fontSize: 20, color: theme.colors.text }
|
||||
container: {
|
||||
flex: 1,
|
||||
// alignItems: 'center', // Keep removed
|
||||
justifyContent: 'flex-start',
|
||||
padding: 16,
|
||||
backgroundColor: theme.colors.background
|
||||
},
|
||||
title: {
|
||||
fontSize: 24,
|
||||
fontWeight: 'bold',
|
||||
marginBottom: 20,
|
||||
color: theme.colors.primary, // Use theme color
|
||||
alignSelf: 'center' // Center the title
|
||||
},
|
||||
inputContainer: {
|
||||
marginBottom: 20,
|
||||
},
|
||||
textInput: {
|
||||
marginBottom: 10,
|
||||
},
|
||||
scrollViewContent: {
|
||||
paddingBottom: 20, // Add padding at the bottom of the scroll view
|
||||
}
|
||||
});
|
||||
|
||||
return (
|
||||
<View style={styles.container}>
|
||||
<Text style={styles.text}>Dashboard</Text>
|
||||
</View>
|
||||
// Wrap content in ScrollView to handle potential overflow
|
||||
<ScrollView style={{ flex: 1, backgroundColor: theme.colors.background }} contentContainerStyle={styles.scrollViewContent}>
|
||||
<View style={styles.container}>
|
||||
<Text style={styles.title}>Dashboard</Text>
|
||||
|
||||
{/* AI Question Input */}
|
||||
<View style={styles.inputContainer}>
|
||||
<TextInput
|
||||
label="Ask MAIA anything..."
|
||||
value={question}
|
||||
onChangeText={setQuestion}
|
||||
mode="outlined" // Use outlined style for better visibility
|
||||
style={styles.textInput}
|
||||
onSubmitEditing={handleQuestionSubmit} // Allow submission via keyboard
|
||||
/>
|
||||
<Button mode="contained" onPress={handleQuestionSubmit}>
|
||||
Ask
|
||||
</Button>
|
||||
</View>
|
||||
|
||||
{/* Calendar Preview */}
|
||||
<CalendarPreview />
|
||||
|
||||
{/* TODO Component */}
|
||||
<TodoComponent />
|
||||
</View>
|
||||
</ScrollView>
|
||||
);
|
||||
};
|
||||
|
||||
|
||||
Reference in New Issue
Block a user