[V0.2] WORKING Working calendar and AI with full frontend.

This commit is contained in:
c-d-p
2025-04-20 12:12:35 +02:00
parent ee86374da6
commit 6cee996fb3
27 changed files with 996 additions and 488 deletions

View File

@@ -1,435 +1,42 @@
// src/screens/CalendarScreen.tsx
import React, { useState, useEffect, useMemo, useCallback } from 'react';
import { View, StyleSheet, FlatList, TouchableOpacity } from 'react-native'; // Import TouchableOpacity
import { Calendar, DateData, LocaleConfig, CalendarProps, MarkingProps } from 'react-native-calendars';
import { Text, useTheme, ActivityIndicator, List, Divider, FAB } from 'react-native-paper'; // Import FAB
import { useNavigation } from '@react-navigation/native'; // Import useNavigation
import {
format,
parseISO,
startOfMonth,
endOfMonth, // Need endOfMonth
getYear,
getMonth,
eachDayOfInterval, // Crucial for period marking
isSameDay, // Helper for comparisons
isValid, // Check if dates are valid
} from 'date-fns';
import React from 'react';
import { View, StyleSheet } from 'react-native';
import { useTheme, FAB } from 'react-native-paper';
import { useNavigation } from '@react-navigation/native';
import { StackNavigationProp } from '@react-navigation/stack';
import { getCalendarEvents } from '../api/calendar';
import { CalendarEvent } from '../types/calendar'; // Use updated type
import { AppStackParamList } from '../navigation/AppNavigator'; // Import navigation param list type
import { StackNavigationProp } from '@react-navigation/stack'; // Import StackNavigationProp
// Optional: Configure locale
// LocaleConfig.locales['en'] = { ... }; LocaleConfig.defaultLocale = 'en';
import CustomCalendarView from '../components/calendar/CustomCalendarView'; // Import the new custom view
import { AppStackParamList } from '../navigation/AppNavigator';
// Define navigation prop type
type CalendarScreenNavigationProp = StackNavigationProp<AppStackParamList, 'Calendar'>; // Adjust 'Calendar' if your route name is different
const getTodayDateString = () => format(new Date(), 'yyyy-MM-dd');
type CalendarScreenNavigationProp = StackNavigationProp<AppStackParamList, 'Calendar'>;
const CalendarScreen = () => {
const theme = useTheme();
const navigation = useNavigation<CalendarScreenNavigationProp>(); // Use the hook with the correct type
const todayString = useMemo(getTodayDateString, []);
const navigation = useNavigation<CalendarScreenNavigationProp>();
const [selectedDate, setSelectedDate] = useState<string>(todayString);
const [currentMonthData, setCurrentMonthData] = useState<DateData | null>(null);
// Store events fetched from API *directly*
// We process them for marking and display separately
const [rawEvents, setRawEvents] = useState<CalendarEvent[]>([]);
// Store events keyed by date *for the list display*
const [eventsByDate, setEventsByDate] = useState<{ [key: string]: CalendarEvent[] }>({});
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
// --- Fetching Logic ---
const fetchEventsForMonth = useCallback(async (date: Date | DateData) => {
console.log("[CAM] fetchevents start");
setIsLoading(true);
setError(null);
const targetYear = 'year' in date ? date.year : getYear(date);
const targetMonth = 'month' in date ? date.month : getMonth(date) + 1;
if (isLoading && currentMonthData?.year === targetYear && currentMonthData?.month === targetMonth) {
return;
}
if ('dateString' in date) {
setCurrentMonthData(date);
} else {
// If called with Date, create approximate DateData
const dateObj = date instanceof Date ? date : new Date(date.timestamp);
setCurrentMonthData({
year: targetYear,
month: targetMonth,
dateString: format(dateObj, 'yyyy-MM-dd'),
day: dateObj.getDate(),
timestamp: dateObj.getTime(),
});
}
try {
console.log(`Fetching events potentially overlapping ${targetYear}-${targetMonth}`);
const fetchedEvents = await getCalendarEvents(targetYear, targetMonth);
setRawEvents(fetchedEvents); // Store the raw events for period marking
// Process events for the daily list view
const newEventsByDate: { [key: string]: CalendarEvent[] } = {};
fetchedEvents.forEach(event => {
// --- Check for valid START date string ---
if (typeof event.start !== 'string') {
console.warn(`Event ${event.id} has invalid start date type:`, event.start);
return; // Skip this event
}
// --- End check ---
const startDate = parseISO(event.start);
// --- Check if START date is valid after parsing ---
if (!isValid(startDate)) {
console.warn(`Invalid start date found in event ${event.id}:`, event.start);
return; // Skip invalid events
}
// --- Handle potentially null END date ---
// If end is null or not a string, treat it as the same as start date
const endDate = typeof event.end === 'string' && isValid(parseISO(event.end)) ? parseISO(event.end) : startDate;
// Ensure end date is not before start date (could happen with invalid data or timezone issues)
const endForInterval = endDate < startDate ? startDate : endDate;
const intervalDates = eachDayOfInterval({ start: startDate, end: endForInterval });
intervalDates.forEach(dayInInterval => {
const dateKey = format(dayInInterval, 'yyyy-MM-dd');
if (!newEventsByDate[dateKey]) {
newEventsByDate[dateKey] = [];
}
// Avoid duplicates if an event is already added for this key
if (!newEventsByDate[dateKey].some(e => e.id === event.id)) {
newEventsByDate[dateKey].push(event);
}
});
});
setEventsByDate(newEventsByDate); // Update state for list view
} catch (err) {
setError('Failed to load calendar events.');
setRawEvents([]); // Clear events on error
setEventsByDate({});
console.error(err);
} finally {
setIsLoading(false);
console.log("[CAM] isLoading:", isLoading);
}
}, [isLoading, currentMonthData]); // Include dependencies
// --- Initial Fetch ---
useEffect(() => {
const performInitialLoad = async () => {
console.log("[CalendarScreen] Performing initial load.");
setIsLoading(true);
setError(null);
const initialDate = parseISO(todayString);
const targetYear = getYear(initialDate);
const targetMonth = getMonth(initialDate) + 1;
setCurrentMonthData({
year: targetYear,
month: targetMonth,
dateString: todayString,
day: initialDate.getDate(),
timestamp: initialDate.getTime(),
});
try {
const fetchedEvents = await getCalendarEvents(targetYear, targetMonth);
const newEventsByDate: {[key: string]: CalendarEvent[] } = {};
fetchedEvents.forEach(event => {
// --- Check for valid START date string ---
if (typeof event.start !== 'string') {
console.warn(`Event ${event.id} has invalid start date type during initial load:`, event.start);
return; // Skip this event
}
// --- End check ---
const startDate = parseISO(event.start);
// --- Check if START date is valid after parsing ---
if (!isValid(startDate)) {
console.warn(`Invalid start date found in event ${event.id} during initial load:`, event.start);
return; // Skip invalid events
}
// --- Handle potentially null END date ---
// If end is null or not a string, treat it as the same as start date
const endDate = typeof event.end === 'string' && isValid(parseISO(event.end)) ? parseISO(event.end) : startDate;
// Ensure end date is not before start date
const endForInterval = endDate < startDate ? startDate : endDate;
const intervalDates = eachDayOfInterval({ start: startDate, end: endForInterval });
intervalDates.forEach(dayInInterval => {
const dateKey = format(dayInInterval, 'yyyy-MM-dd');
if (!newEventsByDate[dateKey]) {
newEventsByDate[dateKey] = [];
}
// Avoid duplicates if an event is already added for this key
if (!newEventsByDate[dateKey].some(e => e.id === event.id)) {
newEventsByDate[dateKey].push(event);
}
});
});
setRawEvents(fetchedEvents);
setEventsByDate(newEventsByDate);
} catch (err) {
setError('Failed to load initial calendar events.');
setRawEvents([]);
setEventsByDate({});
console.error(err);
} finally {
setIsLoading(false);
}
};
performInitialLoad();
}, [todayString]);
// --- Callbacks for Calendar ---
const onDayPress = useCallback((day: DateData) => {
setSelectedDate(day.dateString);
}, []);
const onMonthChange = useCallback((month: DateData) => {
if (!currentMonthData || month.year !== currentMonthData.year || month.month !== currentMonthData.month) {
console.log("[CAM] CAlling fetchevents");
fetchEventsForMonth(month);
} else {
setCurrentMonthData(month); // Just update the current data if same month
}
}, [fetchEventsForMonth, currentMonthData]);
// --- Calculate Marked Dates (Period Marking) ---
const markedDates = useMemo(() => {
const marks: { [key: string]: MarkingProps } = {}; // Use MarkingProps type
rawEvents.forEach(event => {
// --- Check for valid START date string ---
if (typeof event.start !== 'string') {
console.warn(`Event ${event.id} has invalid start date type in markedDates:`, event.start);
return; // Skip this event
}
// --- End check ---
const startDate = parseISO(event.start);
// --- Check if START date is valid after parsing ---
if (!isValid(startDate)) {
console.warn(`Invalid start date found for marking in event ${event.id}:`, event.start);
return; // Skip invalid events
}
// --- Handle potentially null END date ---
// If end is null or not a string, treat it as the same as start date
const endDate = typeof event.end === 'string' && isValid(parseISO(event.end)) ? parseISO(event.end) : startDate;
const eventColor = event.color || theme.colors.primary; // Use event color or default
// Ensure end date is not before start date
const endForInterval = endDate < startDate ? startDate : endDate;
const intervalDates = eachDayOfInterval({ start: startDate, end: endForInterval });
intervalDates.forEach((dateInInterval, index) => {
const dateString = format(dateInInterval, 'yyyy-MM-dd');
const isStartingDay = index === 0;
const isEndingDay = index === intervalDates.length - 1;
const marking: MarkingProps = {
color: eventColor,
textColor: theme.colors.onPrimary || '#ffffff', // Text color within the period mark
};
if (isStartingDay) {
marking.startingDay = true;
}
if (isEndingDay) {
marking.endingDay = true;
}
// Handle single-day events (both start and end)
if (intervalDates.length === 1) {
marking.startingDay = true;
marking.endingDay = true;
}
// Merge markings if multiple events overlap on the same day
marks[dateString] = {
...(marks[dateString] || {}), // Keep existing marks
...marking,
// Ensure start/end flags aren't overwritten by non-start/end marks
startingDay: marks[dateString]?.startingDay || marking.startingDay,
endingDay: marks[dateString]?.endingDay || marking.endingDay,
};
});
});
// Add selected day marking (merge with period marking)
if (selectedDate) {
marks[selectedDate] = {
...(marks[selectedDate] || {}),
selected: true,
color: marks[selectedDate]?.color || theme.colors.primary,
textColor: theme.colors.onPrimary || '#ffffff',
// If selected, don't let it look like starting/ending unless it truly is
startingDay: marks[selectedDate]?.startingDay && marks[selectedDate]?.selected,
endingDay: marks[selectedDate]?.endingDay && marks[selectedDate]?.selected,
};
}
marks[todayString] = {
...(marks[todayString] || {}),
dotColor: theme.colors.secondary,
};
return marks;
}, [rawEvents, selectedDate, theme.colors, theme.dark, todayString]); // Include theme.dark if colors change
// --- Render Event Item ---
const renderEventItem = ({ item }: { item: CalendarEvent }) => {
// --- Check for valid START date string ---
if (typeof item.start !== 'string') {
console.warn(`Event ${item.id} has invalid start date type for rendering:`, item.start);
return null; // Don't render item with invalid start date
}
const startDate = parseISO(item.start);
if (!isValid(startDate)) {
console.warn(`Invalid start date found for rendering event ${item.id}:`, item.start);
return null; // Don't render item with invalid start date
}
// --- Handle potentially null END date ---
const hasValidEndDate = typeof item.end === 'string' && isValid(parseISO(item.end));
const endDate = hasValidEndDate ? parseISO(item.end) : startDate;
let description = item.description || '';
const timePrefix = `Time: ${format(startDate, 'p')}`;
const dateRangePrefix = `${format(startDate, 'MMM d')} - ${format(endDate, 'MMM d')}`;
// Show date range only if end date is valid and different from start date
if (hasValidEndDate && !isSameDay(startDate, endDate)) {
description = `${dateRangePrefix}${item.description ? `\n${item.description}` : ''}`;
} else {
// Otherwise, show start time
description = `${timePrefix}${item.description ? `\n${item.description}` : ''}`;
}
return (
<TouchableOpacity onPress={() => navigation.navigate('EventForm', { eventId: item.id })}>
<List.Item
title={item.title}
description={description}
left={props => <List.Icon {...props} icon="circle-slice-8" color={item.color || theme.colors.primary} />}
style={styles.eventItem}
titleStyle={{ color: theme.colors.text }}
descriptionStyle={{ color: theme.colors.textSecondary }}
descriptionNumberOfLines={3}
/>
</TouchableOpacity>
);
}
// --- Styles ---
const styles = StyleSheet.create({
container: { flex: 1, backgroundColor: theme.colors.background },
calendar: { /* ... */ },
loadingContainer: { height: 100, justifyContent: 'center', alignItems: 'center' },
eventListContainer: { flex: 1, paddingHorizontal: 16, paddingTop: 10 },
eventListHeader: { fontSize: 16, fontWeight: 'bold', color: theme.colors.text, marginBottom: 10, marginTop: 10 },
eventItem: { backgroundColor: theme.colors.surface, marginBottom: 8, borderRadius: theme.roundness },
noEventsText: { textAlign: 'center', marginTop: 20, color: theme.colors.textSecondary, fontSize: 16 },
errorText: { textAlign: 'center', marginTop: 20, color: theme.colors.error, fontSize: 16 },
fab: { // Style for the FAB
fab: {
position: 'absolute',
margin: 16,
right: 0,
bottom: 0,
backgroundColor: theme.colors.primary, // Use theme color
backgroundColor: theme.colors.primary,
},
});
// --- Calendar Theme ---
const calendarTheme: CalendarProps['theme'] = { // Use CalendarProps['theme'] for stricter typing
backgroundColor: theme.colors.background,
calendarBackground: theme.colors.surface,
textSectionTitleColor: theme.colors.primary,
selectedDayBackgroundColor: theme.colors.secondary, // Make selection distinct?
selectedDayTextColor: theme.colors.background, // Text on selection
todayTextColor: theme.colors.secondary, // Today's date number color
dayTextColor: theme.colors.text,
textDisabledColor: theme.colors.disabled,
dotColor: theme.colors.secondary, // Color for the explicit 'today' dot
selectedDotColor: theme.colors.primary,
arrowColor: theme.colors.primary,
monthTextColor: theme.colors.text,
indicatorColor: theme.colors.primary,
textDayFontWeight: '300',
textMonthFontWeight: 'bold',
textDayHeaderFontWeight: '500',
textDayFontSize: 16,
textMonthFontSize: 18,
textDayHeaderFontSize: 14,
// Period marking text color is handled by 'textColor' within the mark itself
'stylesheet.calendar.header': { // Example of deeper theme customization if needed
week: {
marginTop: 5,
flexDirection: 'row',
justifyContent: 'space-around'
}
}
};
// Get events for the *selected* date from the processed map
const eventsForSelectedDate = eventsByDate[selectedDate] || [];
return (
<View style={styles.container}>
<Calendar
key={theme.dark ? 'dark-calendar-period' : 'light-calendar-period'} // Change key if theme changes
style={styles.calendar}
theme={calendarTheme}
current={format(currentMonthData ? new Date(currentMonthData.timestamp) : new Date(), 'yyyy-MM-dd')} // Ensure current reflects viewed month
onDayPress={onDayPress}
onMonthChange={onMonthChange}
markedDates={markedDates}
markingType={'period'} // *** SET MARKING TYPE TO PERIOD ***
firstDay={1} // Optional: Start week on Monday
/>
{/* Replace the old Calendar and FlatList with the new CustomCalendarView */}
<CustomCalendarView />
{isLoading && <ActivityIndicator animating={true} color={theme.colors.primary} size="large" style={styles.loadingContainer} />}
{error && !isLoading && <Text style={styles.errorText}>{error}</Text>}
{!isLoading && !error && (
<View style={styles.eventListContainer}>
<Text style={styles.eventListHeader}>
Events for {selectedDate === todayString ? 'Today' : format(parseISO(selectedDate), 'MMMM d, yyyy')}
</Text>
{eventsForSelectedDate.length > 0 ? (
<FlatList
data={eventsForSelectedDate}
renderItem={renderEventItem}
keyExtractor={(item) => item.id + item.start} // Key needs to be unique if event appears on multiple days in list potentially
ItemSeparatorComponent={() => <View style={{ height: 5 }} />}
/>
) : (
<Text style={styles.noEventsText}>No events scheduled for this day.</Text>
)}
</View>
)}
{/* Add FAB for creating new events */}
{/* 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 with background
color={theme.colors.onPrimary || '#ffffff'} // Ensure icon color contrasts
/>
</View>
);

View File

@@ -2,7 +2,8 @@
import React, { useState, useEffect, useCallback } from 'react';
// Add Platform import
import { View, StyleSheet, ScrollView, Alert, TouchableOpacity, Platform } from 'react-native';
import { TextInput, Button, useTheme, Text, ActivityIndicator, HelperText } from 'react-native-paper';
// Add Chip
import { TextInput, Button, useTheme, Text, ActivityIndicator, HelperText, Chip } from 'react-native-paper';
import { useNavigation, useRoute, RouteProp } from '@react-navigation/native';
// Conditionally import DateTimePickerModal only if not on web
// Note: This dynamic import might not work as expected depending on the bundler setup.
@@ -34,6 +35,8 @@ const EventFormScreen = () => {
const [endDate, setEndDate] = useState<Date | null>(null);
const [color, setColor] = useState(''); // Basic color input for now
const [location, setLocation] = useState(''); // Add location state
const [tags, setTags] = useState<string[]>([]); // Add tags state
const [currentTagInput, setCurrentTagInput] = useState(''); // State for tag input field
// Add state for raw web date input
const [webStartDateInput, setWebStartDateInput] = useState<string>('');
@@ -60,6 +63,7 @@ const EventFormScreen = () => {
setDescription(event.description || '');
setColor(event.color || ''); // Use optional color
setLocation(event.location || ''); // Set location state
setTags(event.tags || []); // Load tags or default to empty array
// Ensure dates are Date objects
if (event.start && isValid(parseISO(event.start))) {
const parsedDate = parseISO(event.start);
@@ -112,6 +116,7 @@ const EventFormScreen = () => {
setEndDate(null);
setWebEndDateInput('');
}
setTags([]); // Ensure tags start empty for new event
} else {
// Default start date to now if creating without a selected date
const now = new Date();
@@ -119,6 +124,7 @@ const EventFormScreen = () => {
setWebStartDateInput(formatForWebInput(now)); // Init web input
setEndDate(null);
setWebEndDateInput('');
setTags([]); // Ensure tags start empty for new event
}
}, [eventId, selectedDate]);
@@ -275,6 +281,7 @@ const EventFormScreen = () => {
end: endDate ? endDate.toISOString() : null,
location: location.trim() || null, // Include location
color: color.trim() || null, // Include color
tags: tags.length > 0 ? tags : null, // Include tags, send null if empty
};
try {
@@ -344,6 +351,18 @@ const EventFormScreen = () => {
}
};
// --- Tag Handling Logic ---
const handleAddTag = () => {
const newTag = currentTagInput.trim();
if (newTag && !tags.includes(newTag)) {
setTags([...tags, newTag]);
setCurrentTagInput(''); // Clear input after adding
}
};
const handleRemoveTag = (tagToRemove: string) => {
setTags(tags.filter(tag => tag !== tagToRemove));
};
if (isLoading && !title) { // Show loading indicator only during initial fetch
return <ActivityIndicator animating={true} style={styles.loading} />;
@@ -435,6 +454,35 @@ const EventFormScreen = () => {
placeholder={theme.colors.primary} // Show default color hint
/>
{/* --- Tags Input --- */}
<View style={styles.tagInputContainer}>
<TextInput
label="Add Tag"
value={currentTagInput}
onChangeText={setCurrentTagInput}
mode="outlined"
style={styles.tagInput}
onSubmitEditing={handleAddTag} // Allow adding tag by pressing enter/submit
/>
{/* Wrap Button text in <Text> */}
<Button onPress={handleAddTag} mode="contained" style={styles.addTagButton} icon="plus">
<Text>Add</Text>
</Button>
</View>
<View style={styles.tagsDisplayContainer}>
{tags.map((tag, index) => (
<Chip
key={index}
icon="close" // Use close icon for removal
onPress={() => handleRemoveTag(tag)} // Use onPress for removal
style={styles.tagChip}
mode="flat" // Use flat mode for less emphasis
>
{tag}
</Chip>
))}
</View>
<Button
mode="contained"
onPress={handleSave}
@@ -514,6 +562,33 @@ const styles = StyleSheet.create({
textAlign: 'center',
marginBottom: 10,
},
tagInputContainer: {
flexDirection: 'row',
alignItems: 'center',
marginBottom: 5,
},
tagInput: {
flex: 1,
marginRight: 8,
},
addTagButton: {
// Adjust height or padding if needed to align with text input
},
tagsDisplayContainer: {
flexDirection: 'row',
flexWrap: 'wrap',
marginBottom: 15, // Add some space below the tags
},
tagChip: {
marginRight: 5,
marginBottom: 5,
// backgroundColor: theme.colors.secondaryContainer, // Optional: Style chips
},
errorText: {
color: 'red', // Use theme.colors.error in practice
textAlign: 'center',
marginBottom: 10,
},
});
export default EventFormScreen;