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

119
backend/alembic.ini Normal file
View File

@@ -0,0 +1,119 @@
# A generic, single database configuration.
[alembic]
# path to migration scripts
# Use forward slashes (/) also on windows to provide an os agnostic path
script_location = alembic
# template used to generate migration file names; The default value is %%(rev)s_%%(slug)s
# Uncomment the line below if you want the files to be prepended with date and time
# see https://alembic.sqlalchemy.org/en/latest/tutorial.html#editing-the-ini-file
# for all available tokens
# file_template = %%(year)d_%%(month).2d_%%(day).2d_%%(hour).2d%%(minute).2d-%%(rev)s_%%(slug)s
# sys.path path, will be prepended to sys.path if present.
# defaults to the current working directory.
prepend_sys_path = .
# timezone to use when rendering the date within the migration file
# as well as the filename.
# If specified, requires the python>=3.9 or backports.zoneinfo library and tzdata library.
# Any required deps can installed by adding `alembic[tz]` to the pip requirements
# string value is passed to ZoneInfo()
# leave blank for localtime
# timezone =
# max length of characters to apply to the "slug" field
# truncate_slug_length = 40
# set to 'true' to run the environment during
# the 'revision' command, regardless of autogenerate
# revision_environment = false
# set to 'true' to allow .pyc and .pyo files without
# a source .py file to be detected as revisions in the
# versions/ directory
# sourceless = false
# version location specification; This defaults
# to alembic/versions. When using multiple version
# directories, initial revisions must be specified with --version-path.
# The path separator used here should be the separator specified by "version_path_separator" below.
# version_locations = %(here)s/bar:%(here)s/bat:alembic/versions
# version path separator; As mentioned above, this is the character used to split
# version_locations. The default within new alembic.ini files is "os", which uses os.pathsep.
# If this key is omitted entirely, it falls back to the legacy behavior of splitting on spaces and/or commas.
# Valid values for version_path_separator are:
#
# version_path_separator = :
# version_path_separator = ;
# version_path_separator = space
# version_path_separator = newline
#
# Use os.pathsep. Default configuration used for new projects.
version_path_separator = os
# set to 'true' to search source files recursively
# in each "version_locations" directory
# new in Alembic version 1.10
# recursive_version_locations = false
# the output encoding used when revision files
# are written from script.py.mako
# output_encoding = utf-8
# sqlalchemy.url = driver://user:pass@localhost/dbname
sqlalchemy.url = postgresql://maia:maia@localhost:5432/maia
[post_write_hooks]
# post_write_hooks defines scripts or Python functions that are run
# on newly generated revision scripts. See the documentation for further
# detail and examples
# format using "black" - use the console_scripts runner, against the "black" entrypoint
# hooks = black
# black.type = console_scripts
# black.entrypoint = black
# black.options = -l 79 REVISION_SCRIPT_FILENAME
# lint with attempts to fix using "ruff" - use the exec runner, execute a binary
# hooks = ruff
# ruff.type = exec
# ruff.executable = %(here)s/.venv/bin/ruff
# ruff.options = check --fix REVISION_SCRIPT_FILENAME
# Logging configuration
[loggers]
keys = root,sqlalchemy,alembic
[handlers]
keys = console
[formatters]
keys = generic
[logger_root]
level = WARNING
handlers = console
qualname =
[logger_sqlalchemy]
level = WARNING
handlers =
qualname = sqlalchemy.engine
[logger_alembic]
level = INFO
handlers =
qualname = alembic
[handler_console]
class = StreamHandler
args = (sys.stderr,)
level = NOTSET
formatter = generic
[formatter_generic]
format = %(levelname)-5.5s [%(name)s] %(message)s
datefmt = %H:%M:%S

1
backend/alembic/README Normal file
View File

@@ -0,0 +1 @@
Generic single-database configuration.

Binary file not shown.

97
backend/alembic/env.py Normal file
View File

@@ -0,0 +1,97 @@
import os
import sys
from logging.config import fileConfig
from sqlalchemy import engine_from_config
from sqlalchemy import pool
from alembic import context
# --- Add project root to sys.path ---
# This assumes alembic/env.py is one level down from the project root (backend/)
PROJECT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, PROJECT_DIR)
# -----------------------------------
# --- Import Base and Models ---
from core.database import Base # Import your Base
# Import all your models here so Base registers them
from modules.auth.models import User # Example: Import User model
from modules.calendar.models import CalendarEvent # Example: Import CalendarEvent model
from modules.nlp.models import ChatMessage # Import the new ChatMessage model
# Add imports for any other models you have
# ----------------------------
# this is the Alembic Config object, which provides
# access to the values within the .ini file in use.
config = context.config
# Interpret the config file for Python logging.
# This line sets up loggers basically.
if config.config_file_name is not None:
fileConfig(config.config_file_name)
# add your model's MetaData object here
# for 'autogenerate' support
# from myapp import mymodel
# target_metadata = mymodel.Base.metadata
# --- Set target_metadata ---
target_metadata = Base.metadata
# ---------------------------
# other values from the config, defined by the needs of env.py,
# can be acquired:
# my_important_option = config.get_main_option("my_important_option")
# ... etc.
def run_migrations_offline() -> None:
"""Run migrations in 'offline' mode.
This configures the context with just a URL
and not an Engine, though an Engine is acceptable
here as well. By skipping the Engine creation
we don't even need a DBAPI to be available.
Calls to context.execute() here emit the given string to the
script output.
"""
url = config.get_main_option("sqlalchemy.url")
context.configure(
url=url,
target_metadata=target_metadata,
literal_binds=True,
dialect_opts={"paramstyle": "named"},
)
with context.begin_transaction():
context.run_migrations()
def run_migrations_online() -> None:
"""Run migrations in 'online' mode.
In this scenario we need to create an Engine
and associate a connection with the context.
"""
connectable = engine_from_config(
config.get_section(config.config_ini_section, {}),
prefix="sqlalchemy.",
poolclass=pool.NullPool,
)
with connectable.connect() as connection:
context.configure(
connection=connection, target_metadata=target_metadata
)
with context.begin_transaction():
context.run_migrations()
if context.is_offline_mode():
run_migrations_offline()
else:
run_migrations_online()

View File

@@ -0,0 +1,28 @@
"""${message}
Revision ID: ${up_revision}
Revises: ${down_revision | comma,n}
Create Date: ${create_date}
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
${imports if imports else ""}
# revision identifiers, used by Alembic.
revision: str = ${repr(up_revision)}
down_revision: Union[str, None] = ${repr(down_revision)}
branch_labels: Union[str, Sequence[str], None] = ${repr(branch_labels)}
depends_on: Union[str, Sequence[str], None] = ${repr(depends_on)}
def upgrade() -> None:
"""Upgrade schema."""
${upgrades if upgrades else "pass"}
def downgrade() -> None:
"""Downgrade schema."""
${downgrades if downgrades else "pass"}

View File

@@ -0,0 +1,32 @@
"""Initial migration with existing tables
Revision ID: 69069d6184b3
Revises:
Create Date: 2025-04-21 01:14:33.233195
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision: str = '69069d6184b3'
down_revision: Union[str, None] = None
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None
def upgrade() -> None:
"""Upgrade schema."""
# ### commands auto generated by Alembic - please adjust! ###
pass
# ### end Alembic commands ###
def downgrade() -> None:
"""Downgrade schema."""
# ### commands auto generated by Alembic - please adjust! ###
pass
# ### end Alembic commands ###

View File

@@ -17,6 +17,10 @@ def get_engine():
raise ValueError("DB_URL is not set in Settings.")
print(f"Connecting to database at {settings.DB_URL}")
_engine = create_engine(settings.DB_URL)
try:
_engine.connect()
except Exception as e:
raise Exception("Database connection failed. Is the database server running?")
Base.metadata.create_all(_engine) # Create tables here
return _engine

View File

@@ -38,6 +38,7 @@ app.add_middleware(
allow_origins=[
"http://localhost:8081", # Keep for web testing if needed
"http://192.168.1.9:8081", # Add your mobile device/emulator origin (adjust port if needed)
"http://192.168.255.221:8081",
# Add other origins if necessary, e.g., production frontend URL
],
allow_credentials=True,

View File

@@ -57,4 +57,4 @@ class CalendarEventResponse(CalendarEventBase):
return v
class Config:
from_attributes = True # Changed from orm_mode
from_attributes = True

Binary file not shown.

View File

@@ -7,13 +7,13 @@ from core.database import get_db
from modules.auth.dependencies import get_current_user
from modules.auth.models import User
from modules.nlp.service import process_request, ask_ai
# Import the response schema
# Import the new service functions and Enum
from modules.nlp.service import process_request, ask_ai, save_chat_message, get_chat_history, MessageSender
# Import the response schema and the new ChatMessage model for response type hinting
from modules.nlp.schemas import ProcessCommandRequest, ProcessCommandResponse
from modules.nlp.models import ChatMessage # Import ChatMessage model
from modules.calendar.service import create_calendar_event, get_calendar_events, update_calendar_event, delete_calendar_event
# Import the CalendarEvent *model* for type hinting
from modules.calendar.models import CalendarEvent
# Import the CalendarEvent Pydantic schemas for data validation
from modules.calendar.schemas import CalendarEventCreate, CalendarEventUpdate
router = APIRouter(prefix="/nlp", tags=["nlp"])
@@ -35,9 +35,14 @@ def format_calendar_events(events: List[CalendarEvent]) -> List[str]:
@router.post("/process-command", response_model=ProcessCommandResponse)
def process_command(request_data: ProcessCommandRequest, current_user: User = Depends(get_current_user), db: Session = Depends(get_db)):
"""
Process the user command, execute the action, and return user-friendly responses.
Process the user command, save messages, execute action, save response, and return user-friendly responses.
"""
user_input = request_data.user_input
# --- Save User Message ---
save_chat_message(db, user_id=current_user.id, sender=MessageSender.USER, text=user_input)
# ------------------------
command_data = process_request(user_input)
intent = command_data["intent"]
params = command_data["params"]
@@ -45,10 +50,19 @@ def process_command(request_data: ProcessCommandRequest, current_user: User = De
responses = [response_text] # Start with the initial response
# --- Save Initial AI Response ---
# Save the first response generated by process_request
save_chat_message(db, user_id=current_user.id, sender=MessageSender.AI, text=response_text)
# -----------------------------
if intent == "error":
raise HTTPException(status_code=400, detail=response_text)
# Don't raise HTTPException here if we want to save the error message
# Instead, return the error response directly
# save_chat_message(db, user_id=current_user.id, sender=MessageSender.AI, text=response_text) # Already saved above
return ProcessCommandResponse(responses=responses)
if intent == "clarification_needed" or intent == "unknown":
# save_chat_message(db, user_id=current_user.id, sender=MessageSender.AI, text=response_text) # Already saved above
return ProcessCommandResponse(responses=responses)
try:
@@ -56,48 +70,100 @@ def process_command(request_data: ProcessCommandRequest, current_user: User = De
case "ask_ai":
ai_answer = ask_ai(**params)
responses.append(ai_answer)
# --- Save Additional AI Response ---
save_chat_message(db, user_id=current_user.id, sender=MessageSender.AI, text=ai_answer)
# ---------------------------------
return ProcessCommandResponse(responses=responses)
case "get_calendar_events":
# get_calendar_events returns List[CalendarEvent models]
events: List[CalendarEvent] = get_calendar_events(db, current_user.id, **params)
responses.extend(format_calendar_events(events))
formatted_responses = format_calendar_events(events)
responses.extend(formatted_responses)
# --- Save Additional AI Responses ---
for resp in formatted_responses:
save_chat_message(db, user_id=current_user.id, sender=MessageSender.AI, text=resp)
# ----------------------------------
return ProcessCommandResponse(responses=responses)
case "add_calendar_event":
# Validate input with Pydantic schema
event_data = CalendarEventCreate(**params)
created_event = create_calendar_event(db, current_user.id, event_data)
start_str = created_event.start.strftime("%Y-%m-%d %H:%M") if created_event.start else "No start time"
title = created_event.title or "Untitled Event"
responses.append(f"Added: {title} starting at {start_str}.")
add_response = f"Added: {title} starting at {start_str}."
responses.append(add_response)
# --- Save Additional AI Response ---
save_chat_message(db, user_id=current_user.id, sender=MessageSender.AI, text=add_response)
# ---------------------------------
return ProcessCommandResponse(responses=responses)
case "update_calendar_event":
event_id = params.pop('event_id', None)
if event_id is None:
raise HTTPException(status_code=400, detail="Event ID is required for update.")
# Validate input with Pydantic schema
# Save the error message before raising
error_msg = "Event ID is required for update."
save_chat_message(db, user_id=current_user.id, sender=MessageSender.AI, text=error_msg)
raise HTTPException(status_code=400, detail=error_msg)
event_data = CalendarEventUpdate(**params)
updated_event = update_calendar_event(db, current_user.id, event_id, event_data=event_data)
title = updated_event.title or "Untitled Event"
responses.append(f"Updated event ID {updated_event.id}: {title}.")
update_response = f"Updated event ID {updated_event.id}: {title}."
responses.append(update_response)
# --- Save Additional AI Response ---
save_chat_message(db, user_id=current_user.id, sender=MessageSender.AI, text=update_response)
# ---------------------------------
return ProcessCommandResponse(responses=responses)
case "delete_calendar_event":
event_id = params.get('event_id')
if event_id is None:
raise HTTPException(status_code=400, detail="Event ID is required for delete.")
# Save the error message before raising
error_msg = "Event ID is required for delete."
save_chat_message(db, user_id=current_user.id, sender=MessageSender.AI, text=error_msg)
raise HTTPException(status_code=400, detail=error_msg)
delete_calendar_event(db, current_user.id, event_id)
responses.append(f"Deleted event ID {event_id}.")
delete_response = f"Deleted event ID {event_id}."
responses.append(delete_response)
# --- Save Additional AI Response ---
save_chat_message(db, user_id=current_user.id, sender=MessageSender.AI, text=delete_response)
# ---------------------------------
return ProcessCommandResponse(responses=responses)
case _:
print(f"Warning: Unhandled intent '{intent}' reached api.py match statement.")
# The initial response_text was already saved
return ProcessCommandResponse(responses=responses)
except HTTPException as http_exc:
# Don't save again if already saved before raising
if http_exc.status_code != 400 or ('event_id' not in http_exc.detail.lower()):
save_chat_message(db, user_id=current_user.id, sender=MessageSender.AI, text=http_exc.detail)
raise http_exc
except Exception as e:
print(f"Error executing intent '{intent}': {e}")
return ProcessCommandResponse(responses=["Sorry, I encountered an error while trying to perform that action."])
error_response = "Sorry, I encountered an error while trying to perform that action."
# --- Save Final Error AI Response ---
save_chat_message(db, user_id=current_user.id, sender=MessageSender.AI, text=error_response)
# ----------------------------------
return ProcessCommandResponse(responses=[error_response])
# --- New Endpoint for Chat History ---
# Define a Pydantic schema for the response (optional but good practice)
from pydantic import BaseModel
from datetime import datetime
class ChatMessageResponse(BaseModel):
id: int
sender: MessageSender # Use the enum directly
text: str
timestamp: datetime
class Config:
from_attributes = True # Allow Pydantic to work with ORM models
@router.get("/history", response_model=List[ChatMessageResponse])
def read_chat_history(current_user: User = Depends(get_current_user), db: Session = Depends(get_db)):
"""Retrieves the last 50 chat messages for the current user."""
history = get_chat_history(db, user_id=current_user.id, limit=50)
return history
# -------------------------------------

View File

@@ -0,0 +1,23 @@
\
# /home/cdp/code/MAIA/backend/modules/nlp/models.py
from sqlalchemy import Column, Integer, String, Text, DateTime, ForeignKey, Enum as SQLEnum
from sqlalchemy.orm import relationship
from sqlalchemy.sql import func
import enum
from core.database import Base
class MessageSender(enum.Enum):
USER = "user"
AI = "ai"
class ChatMessage(Base):
__tablename__ = "chat_messages"
id = Column(Integer, primary_key=True, index=True)
user_id = Column(Integer, ForeignKey("users.id"), nullable=False, index=True)
sender = Column(SQLEnum(MessageSender), nullable=False)
text = Column(Text, nullable=False)
timestamp = Column(DateTime(timezone=True), server_default=func.now())
owner = relationship("User") # Relationship to the User model

View File

@@ -1,8 +1,14 @@
# modules/nlp/service.py
from sqlalchemy.orm import Session
from sqlalchemy import desc # Import desc for ordering
from google import genai
import json
from datetime import datetime, timezone
from typing import List # Import List
# Import the new model and Enum
from .models import ChatMessage, MessageSender
# from core.config import settings
# client = genai.Client(api_key=settings.GOOGLE_API_KEY)
@@ -70,6 +76,27 @@ Here is some context for you:
Here is the user request:
"""
# --- Chat History Service Functions ---
def save_chat_message(db: Session, user_id: int, sender: MessageSender, text: str):
"""Saves a chat message to the database."""
db_message = ChatMessage(user_id=user_id, sender=sender, text=text)
db.add(db_message)
db.commit()
db.refresh(db_message)
return db_message
def get_chat_history(db: Session, user_id: int, limit: int = 50) -> List[ChatMessage]:
"""Retrieves the last 'limit' chat messages for a user."""
return db.query(ChatMessage)\
.filter(ChatMessage.user_id == user_id)\
.order_by(desc(ChatMessage.timestamp))\
.limit(limit)\
.all()[::-1] # Reverse to get oldest first for display order
# --- Existing NLP Service Functions ---
def process_request(request: str):
"""
Process the user request using the Google GenAI API.

View File

@@ -43,3 +43,4 @@ tzdata==2025.2
uvicorn==0.34.1
vine==5.1.0
wcwidth==0.2.13
alembic

View File

@@ -19,7 +19,8 @@
"adaptiveIcon": {
"foregroundImage": "./assets/adaptive-icon.png",
"backgroundColor": "#ffffff"
}
},
"softwareKeyboardLayoutMode": "resize"
},
"web": {
"favicon": "./assets/favicon.png"

View File

@@ -9,7 +9,7 @@
"version": "1.0.0",
"dependencies": {
"@expo/metro-runtime": "~4.0.1",
"@react-native-async-storage/async-storage": "1.23.1",
"@react-native-async-storage/async-storage": "^1.23.1",
"@react-native-community/datetimepicker": "8.2.0",
"@react-navigation/bottom-tabs": "^7.3.10",
"@react-navigation/native": "^7.1.6",
@@ -17,7 +17,7 @@
"async-storage": "^0.1.0",
"axios": "^1.8.4",
"date-fns": "^4.1.0",
"expo": "~52.0.46",
"expo": "^52.0.46",
"expo-font": "~13.0.4",
"expo-secure-store": "~14.0.1",
"expo-splash-screen": "~0.29.24",

View File

@@ -10,15 +10,18 @@
},
"dependencies": {
"@expo/metro-runtime": "~4.0.1",
"@react-native-async-storage/async-storage": "1.23.1",
"@react-native-async-storage/async-storage": "^1.23.1",
"@react-native-community/datetimepicker": "8.2.0",
"@react-navigation/bottom-tabs": "^7.3.10",
"@react-navigation/native": "^7.1.6",
"@react-navigation/native-stack": "^7.3.10",
"async-storage": "^0.1.0",
"axios": "^1.8.4",
"date-fns": "^4.1.0",
"expo": "~52.0.46",
"expo": "^52.0.46",
"expo-font": "~13.0.4",
"expo-secure-store": "~14.0.1",
"expo-splash-screen": "~0.29.24",
"expo-status-bar": "~2.0.1",
"react": "18.3.1",
"react-dom": "18.3.1",
@@ -30,10 +33,7 @@
"react-native-safe-area-context": "4.12.0",
"react-native-screens": "~4.4.0",
"react-native-vector-icons": "^10.2.0",
"react-native-web": "~0.19.13",
"@react-native-community/datetimepicker": "8.2.0",
"expo-font": "~13.0.4",
"expo-splash-screen": "~0.29.24"
"react-native-web": "~0.19.13"
},
"devDependencies": {
"@babel/core": "^7.25.2",

View File

@@ -5,7 +5,8 @@ import * as SecureStore from 'expo-secure-store';
import AsyncStorage from '@react-native-async-storage/async-storage';
const API_BASE_URL = process.env.EXPO_PUBLIC_API_URL || 'http://192.168.1.9:8000/api'; // Use your machine's IP
const API_BASE_URL = process.env.EXPO_PUBLIC_API_URL || 'http://192.168.255.221:8000/api'; // Use your machine's IP
// const API_BASE_URL = process.env.EXPO_PUBLIC_API_URL || 'http://192.168.1.9:8000/api'; // Use your machine's IP
// const API_BASE_URL = process.env.EXPO_PUBLIC_API_URL || 'http://localhost:8000/api'; // Use your machine's IP
const TOKEN_KEY = 'maia_access_token';

View File

@@ -1,6 +1,6 @@
// src/components/calendar/CalendarDayCell.tsx
import React from 'react';
import { View, StyleSheet, Dimensions, ScrollView } from 'react-native';
import { View, StyleSheet, ScrollView } from 'react-native'; // Removed Dimensions unless used elsewhere
import { Text, useTheme } from 'react-native-paper';
import { format, isToday } from 'date-fns';
@@ -11,56 +11,100 @@ interface CalendarDayCellProps {
date: Date;
events: CalendarEvent[];
isCurrentMonth?: boolean; // Optional, mainly for month view styling
height?: number; // Optional fixed height
width?: number; // Optional fixed width
}
const dateNumberSize = 24; // Define a size for the circle/text container
const CalendarDayCell: React.FC<CalendarDayCellProps> = ({ date, events, isCurrentMonth = true, height, width }) => {
const theme = useTheme();
const today = isToday(date);
const dateNumber = format(date, 'd');
// --- Define styles inside the component to access theme ---
const styles = StyleSheet.create({
cell: {
flex: width ? undefined : 1, // Use flex=1 if no width is provided
flex: width ? undefined : 1,
width: width,
height: height,
borderWidth: 0.5,
borderTopWidth: 0,
borderColor: theme.colors.outlineVariant,
padding: 2,
paddingTop: 0,
paddingTop: 0, // Keep this 0 if header handles top padding
backgroundColor: theme.colors.background,
overflow: 'hidden', // Prevent events overflowing cell boundaries
overflow: 'hidden',
},
dateNumberContainer: {
dayHeader: { // Renamed from dateNumberContainer for consistency with other views
alignItems: 'center',
justifyContent: 'center',
marginBottom: 2,
// Use minHeight instead of fixed height for flexibility
minHeight: dateNumberSize + 4,
},
dateNumber: {
dateNumberContainer: { // Base container for the date number
width: dateNumberSize,
height: dateNumberSize,
alignItems: 'center',
justifyContent: 'center',
// Circle properties moved to todayCircle
},
todayCircle: { // Style for the *filled* circle highlight
// Inherit size/alignment from dateNumberContainer, just add background/radius
backgroundColor: theme.colors.primary,
borderRadius: dateNumberSize / 2,
},
dateNumber: { // Base style for the date number text
fontSize: 12,
fontWeight: today ? 'bold' : 'normal',
marginTop: 8,
color: today ? theme.colors.primary : (isCurrentMonth ? theme.colors.onSurface : theme.colors.onSurfaceDisabled),
// Base color determined by isCurrentMonth
color: isCurrentMonth ? theme.colors.onSurface : theme.colors.onSurfaceDisabled,
textAlign: 'center',
padding: 0,
includeFontPadding: false,
// Base font weight (non-today)
fontWeight: 'normal',
},
todayDateNumber: { // Specific style for text on today's date
// Override color and weight for today
color: theme.colors.onPrimary, // Contrast with primary background
fontWeight: 'bold',
// Retain isCurrentMonth dimming logic if needed (optional, usually today is highlighted regardless)
// opacity: isCurrentMonth ? 1 : 0.6, // Example if you still want to slightly dim today if not in current month
},
eventsContainer: {
flex: 1, // Take remaining space in the cell
flex: 1,
},
});
// --- End of styles ---
return (
<View style={styles.cell}>
<View style={styles.dateNumberContainer}>
<Text style={styles.dateNumber}>{format(date, 'd')}</Text>
{/* Renamed container View for consistency */}
<View style={styles.dayHeader}>
{/* Apply base container style, and add circle style conditionally */}
<View style={[
styles.dateNumberContainer, // Base size and alignment
today && styles.todayCircle // Conditional circle background
]}>
<Text style={[
styles.dateNumber, // Base text style (includes current month color)
today && styles.todayDateNumber // Conditional color/weight override for today
]}>
{dateNumber}
</Text>
</View>
</View>
{/* Use ScrollView for month view where events might exceed fixed height */}
<ScrollView style={styles.eventsContainer} nestedScrollEnabled={true}>
{events
.sort((a, b) => new Date(a.start).getTime() - new Date(b.start).getTime()) // Sort events
.sort((a, b) => new Date(a.start).getTime() - new Date(b.start).getTime())
.map(event => (
<EventItem key={event.id} event={event} showTime={false} /> // Don't show time in month cell
<EventItem key={event.id} event={event} showTime={false} />
))}
</ScrollView>
</View>
);
};
export default React.memo(CalendarDayCell); // Memoize for performance
// Keep memoization
export default React.memo(CalendarDayCell);

View File

@@ -18,39 +18,35 @@ const CalendarHeader: React.FC<CalendarHeaderProps> = ({ currentRangeText, onPre
const styles = StyleSheet.create({
container: {
flexDirection: 'row',
justifyContent: 'flex-start',
alignItems: 'center',
paddingVertical: 8,
paddingHorizontal: 12,
paddingHorizontal: 8,
borderBottomWidth: 1,
borderBottomColor: theme.colors.outlineVariant,
backgroundColor: theme.colors.surface, // Match background
backgroundColor: theme.colors.surface,
},
leftGroup: {
flexDirection: 'row',
alignItems: 'center',
flex: 1,
},
title: {
fontSize: 18,
fontWeight: 'bold',
color: theme.colors.onSurface, // Use theme text color
color: theme.colors.onSurface,
marginLeft: 12,
flexShrink: 1,
},
});
return (
<View style={styles.container}>
<IconButton
icon="chevron-left"
onPress={onPrev}
size={24}
iconColor={theme.colors.primary} // Use theme color
/>
<IconButton
icon="chevron-right"
onPress={onNext}
size={24}
iconColor={theme.colors.primary} // Use theme color
/>
<View style={{ width: 12 }} /> {/* Placeholder for alignment */}
<Text style={styles.title}>{currentRangeText}</Text>
<View style={{ flex: 1 }} /> {/* Spacer to push ViewSwitcher to the right */}
<ViewSwitcher currentView={currentView} onViewChange={onViewChange}></ViewSwitcher>
<View style={styles.leftGroup}>
<IconButton icon="chevron-left" onPress={onPrev} size={24} iconColor={theme.colors.primary} />
<IconButton icon="chevron-right" onPress={onNext} size={24} iconColor={theme.colors.primary} />
<Text style={styles.title} ellipsizeMode='tail'>{currentRangeText}</Text>
</View>
<ViewSwitcher currentView={currentView} onViewChange={onViewChange} />
</View>
);
};

View File

@@ -0,0 +1,86 @@
import React from 'react';
import { View, Text, TouchableOpacity, StyleSheet } from 'react-native';
import { useTheme } from 'react-native-paper';
interface ButtonConfig<T extends string> {
value: T;
label: string;
checkedColor?: string; // Keep for potential future use or consistency
style?: object; // Keep for potential future use or consistency
}
interface CustomSegmentedButtonsProps<T extends string> {
value: T;
onValueChange: (value: T) => void;
buttons: ButtonConfig<T>[];
}
const CustomSegmentedButtons = <T extends string>({
value,
onValueChange,
buttons,
}: CustomSegmentedButtonsProps<T>) => {
const theme = useTheme();
const styles = StyleSheet.create({
container: {
flexDirection: 'row',
borderRadius: 20, // Increased border radius for a rounder look
overflow: 'hidden',
borderWidth: 1,
borderColor: theme.colors.outline,
},
button: {
flex: 1,
paddingVertical: 8,
paddingHorizontal: 12,
alignItems: 'center',
justifyContent: 'center',
backgroundColor: theme.colors.surface, // Default background
},
buttonSelected: {
backgroundColor: theme.colors.primaryContainer, // Selected background
},
buttonText: {
color: theme.colors.onSurface, // Default text color
},
buttonTextSelected: {
color: theme.colors.onPrimaryContainer, // Selected text color
fontWeight: 'bold',
},
separator: {
width: 1,
backgroundColor: theme.colors.outline,
},
});
return (
<View style={styles.container}>
{buttons.map((button, index) => (
<React.Fragment key={button.value}>
<TouchableOpacity
style={[
styles.button,
value === button.value && styles.buttonSelected,
button.style, // Apply individual button styles if provided
]}
onPress={() => onValueChange(button.value)}
activeOpacity={0.7}
>
<Text
style={[
styles.buttonText,
value === button.value && styles.buttonTextSelected,
]}
>
{button.label}
</Text>
</TouchableOpacity>
{index < buttons.length - 1 && <View style={styles.separator} />}
</React.Fragment>
))}
</View>
);
};
export default CustomSegmentedButtons;

View File

@@ -43,12 +43,14 @@ const EventItem: React.FC<EventItemProps> = ({ event, showTime = true }) => {
},
text: {
color: theme.colors.onPrimary, // Ensure text is readable on the background color
fontSize: 12,
fontWeight: '500',
fontSize: 10,
fontWeight: 'bold',
},
timeText: {
fontSize: 9,
fontSize: 8,
fontWeight: 'normal',
color: theme.colors.onPrimary,
marginRight: 2, // Space between time and title
},
tagContainer: {
flexDirection: 'row',
@@ -77,7 +79,7 @@ const EventItem: React.FC<EventItemProps> = ({ event, showTime = true }) => {
return (
<TouchableOpacity onPress={handlePress} style={styles.container}>
<Text style={styles.text} numberOfLines={1} ellipsizeMode="tail">
<Text style={styles.text} numberOfLines={2} ellipsizeMode='clip'>
{showTime && <Text style={styles.timeText}>{timeString} </Text>}
{event.title}
</Text>

View File

@@ -15,8 +15,9 @@ interface ThreeDayViewProps {
}
// Get screen width
const screenWidth = Dimensions.get('window').width;
const dayColumnWidth = screenWidth / 3; // Divide by 3 for 3-day view
// const screenWidth = Dimensions.get('window').width; // No longer needed here if dayColumn uses flex:1
// const dayColumnWidth = screenWidth / 3;
const dateNumberSize = 24; // Define a size for the circle/text container
const ThreeDayView: React.FC<ThreeDayViewProps> = ({ startDate, endDate, eventsByDate }) => {
const theme = useTheme();
@@ -29,86 +30,131 @@ const ThreeDayView: React.FC<ThreeDayViewProps> = ({ startDate, endDate, eventsB
// Ensure exactly 3 days are generated if interval logic is tricky
const displayDays = days.slice(0, 3);
// Get abbreviated day names for the displayed days
const weekDays = displayDays.map(day => format(day, 'EEE').toUpperCase());
// --- Define styles inside the component to access theme ---
const styles = StyleSheet.create({
container: {
flex: 1,
flexDirection: 'row', // Apply row direction directly to the container View
},
// Remove scrollViewContent style as it's no longer needed
// scrollViewContent: { flexDirection: 'row' },
dayColumn: {
width: dayColumnWidth,
borderRightWidth: 1,
borderRightColor: theme.colors.outlineVariant,
// Add flex: 1 to allow inner ScrollView to expand vertically
headerRow: {
flexDirection: 'row',
paddingVertical: 5,
paddingBottom: 0,
backgroundColor: theme.colors.background,
},
headerCell: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
borderLeftWidth: 0.5,
borderRightWidth: 0.5,
borderColor: theme.colors.outlineVariant,
backgroundColor: theme.colors.background,
},
lastDayColumn: {
borderRightWidth: 0,
headerText: {
fontSize: 11,
fontWeight: 'bold',
color: theme.colors.onSurfaceVariant,
},
contentRow: {
flex: 1,
flexDirection: 'row',
},
dayColumn: {
flex: 1,
borderWidth: 0.5,
borderTopWidth: 0,
borderColor: theme.colors.outlineVariant,
padding: 2,
paddingTop: 0, // Keep this 0 if header handles top padding
backgroundColor: theme.colors.background,
overflow: 'hidden',
},
dayHeader: {
paddingVertical: 8,
alignItems: 'center',
borderBottomWidth: 1,
borderBottomColor: theme.colors.outlineVariant,
backgroundColor: theme.colors.surfaceVariant,
justifyContent: 'center',
marginBottom: 2,
minHeight: dateNumberSize + 4, // Slightly larger than circle to give space
},
dayHeaderText: {
fontSize: 10,
fontWeight: 'bold',
color: theme.colors.onSurfaceVariant,
// Base container for the date number - useful for alignment consistency
dateNumberContainer: {
width: dateNumberSize,
height: dateNumberSize,
alignItems: 'center',
justifyContent: 'center',
// Removed borderRadius and background/border from here
},
dayNumberText: {
todayCircle: {
backgroundColor: theme.colors.primary, // Use background for filled circle
borderRadius: dateNumberSize / 2, // Make it circular
},
dateNumber: {
fontSize: 12,
color: theme.colors.onSurface,
textAlign: 'center', // Keep textAlign, helps sometimes
padding: 0, // Ensure no padding interferes
includeFontPadding: false, // Keep this
// Removed width property
},
todayDateNumber: { // Specific style for text color on today's date
color: theme.colors.onPrimary, // Color that contrasts with primary background
fontWeight: 'bold',
marginTop: 2,
color: theme.colors.onSurfaceVariant,
},
todayHeader: {
backgroundColor: theme.colors.primaryContainer,
},
todayHeaderText: {
color: theme.colors.onPrimaryContainer,
},
eventsContainer: {
// Remove flex: 1 here if dayColumn has flex: 1
padding: 4,
flex: 1,
padding: 2,
},
});
// --- End of styles ---
return (
// Change ScrollView to View
<View style={styles.container}>
{displayDays.map((day, index) => {
<View style={styles.headerRow}>
{weekDays.map((dayName, index) => (
<View key={dayName + index} style={styles.headerCell}>
<Text style={styles.headerText}>{dayName}</Text>
</View>
))}
</View>
<View style={styles.contentRow}>
{displayDays.map((day) => { // Removed index as it wasn't used after checks removed
const dateKey = format(day, 'yyyy-MM-dd');
const dayEvents = eventsByDate[dateKey] || [];
const today = isToday(day);
const isLastColumn = index === displayDays.length - 1;
return (
<View
key={dateKey}
style={[styles.dayColumn, isLastColumn && styles.lastDayColumn]}
>
<View style={[styles.dayHeader, today && styles.todayHeader]}>
<Text style={[styles.dayHeaderText, today && styles.todayHeaderText]}>
{format(day, 'EEE')}
</Text>
<Text style={[styles.dayNumberText, today && styles.todayHeaderText]}>
// Use flex: 1 container for each day column
<View key={dateKey} style={{ flex: 1 }}>
<View style={styles.dayColumn}>
<View style={styles.dayHeader}>
{/* Apply base container style, and add circle style conditionally */}
<View style={[
styles.dateNumberContainer, // Base size and alignment
today && styles.todayCircle // Conditional circle background
]}>
<Text style={[
styles.dateNumber, // Base text style
today && styles.todayDateNumber // Conditional color/weight for today
]}>
{format(day, 'd')}
</Text>
</View>
{/* Keep inner ScrollView for vertical scrolling within the column */}
<ScrollView style={styles.eventsContainer}>
</View>
<ScrollView style={styles.eventsContainer} nestedScrollEnabled={true}>
{dayEvents.sort((a, b) => new Date(a.start).getTime() - new Date(b.start).getTime())
.map(event => (
<EventItem key={event.id} event={event} showTime={true} />
))}
</ScrollView>
</View>
</View>
);
})}
</View>
</View>
);
};

View File

@@ -1,8 +1,9 @@
// src/components/calendar/ViewSwitcher.tsx
import React from 'react';
import { View, StyleSheet } from 'react-native';
import { SegmentedButtons, useTheme } from 'react-native-paper';
import { CalendarViewMode } from './CustomCalendarView'; // Import the type
import { useTheme } from 'react-native-paper'; // Keep useTheme
import { CalendarViewMode } from './CustomCalendarView';
import CustomSegmentedButtons from './CustomSegmentedButtons'; // Import the custom component
interface ViewSwitcherProps {
currentView: CalendarViewMode;
@@ -14,23 +15,24 @@ const ViewSwitcher: React.FC<ViewSwitcherProps> = ({ currentView, onViewChange }
const styles = StyleSheet.create({
container: {
paddingVertical: 8,
paddingHorizontal: 16,
backgroundColor: theme.colors.surface, // Match background
borderBottomColor: theme.colors.outlineVariant,
// Add horizontal padding if needed to center or space the component
paddingHorizontal: 8,
minWidth: 150, // Add a minimum width
alignSelf: 'center', // Center the component if it's smaller than the parent
},
});
return (
<View style={styles.container}>
<SegmentedButtons
<CustomSegmentedButtons // Use the custom component
value={currentView}
onValueChange={(value) => onViewChange(value as CalendarViewMode)} // Cast value
onValueChange={onViewChange} // No need to cast type here anymore
buttons={[
{ value: 'month', label: 'M', checkedColor: theme.colors.onPrimary },
{ value: 'week', label: 'W', checkedColor: theme.colors.onPrimary },
{ value: '3day', label: '3', checkedColor: theme.colors.onPrimary },
// Pass the same button configuration
{ value: 'month', label: 'M' /* Use full labels for clarity */ },
{ value: 'week', label: 'W' },
{ value: '3day', label: '3D' },
]}
density="high"
/>
</View>
);

View File

@@ -1,13 +1,11 @@
// src/components/calendar/WeekView.tsx
import React, { useMemo } from 'react';
// Import Dimensions
import { View, StyleSheet, ScrollView, Dimensions } from 'react-native';
import { View, StyleSheet, ScrollView } from 'react-native'; // Removed Dimensions unless used elsewhere
import { Text, useTheme } from 'react-native-paper';
import { eachDayOfInterval, format, isToday } from 'date-fns';
import CalendarDayCell from './CalendarDayCell';
import { CalendarEvent } from '../../types/calendar';
import EventItem from './EventItem'; // Import EventItem
import EventItem from './EventItem';
interface WeekViewProps {
startDate: Date; // Start of the week
@@ -15,9 +13,8 @@ interface WeekViewProps {
eventsByDate: { [key: string]: CalendarEvent[] };
}
// Get screen width
const screenWidth = Dimensions.get('window').width;
const dayColumnWidth = screenWidth / 7; // Divide by 7 for week view
// Define size here, consistent with other views
const dateNumberSize = 24;
const WeekView: React.FC<WeekViewProps> = ({ startDate, endDate, eventsByDate }) => {
const theme = useTheme();
@@ -26,86 +23,132 @@ const WeekView: React.FC<WeekViewProps> = ({ startDate, endDate, eventsByDate })
endDate,
]);
// Define standard week day names - ensure order matches your locale/calendar needs
// const weekDays = ['MON', 'TUE', 'WED', 'THU', 'FRI', 'SAT', 'SUN']; // Static names
// Or generate dynamically from the days array to be safer
const weekDays = days.map(day => format(day, 'EEE').toUpperCase());
// --- Define styles inside the component to access theme ---
const styles = StyleSheet.create({
container: {
flex: 1,
flexDirection: 'row', // Apply row direction directly to the container View
},
// Remove scrollViewContent style
// scrollViewContent: { flexDirection: 'row' },
dayColumn: {
width: dayColumnWidth,
borderRightWidth: 1,
borderRightColor: theme.colors.outlineVariant,
flex: 1, // Add flex: 1 to allow inner ScrollView to expand vertically
headerRow: {
flexDirection: 'row',
paddingVertical: 5,
paddingBottom: 0,
backgroundColor: theme.colors.background,
},
lastDayColumn: { // Add style for the last column
borderRightWidth: 0, // Remove border
},
dayHeader: {
paddingVertical: 8,
headerCell: {
flex: 1,
alignItems: 'center',
borderBottomWidth: 1,
borderBottomColor: theme.colors.outlineVariant,
backgroundColor: theme.colors.surfaceVariant,
justifyContent: 'center',
borderLeftWidth: 0.5,
borderRightWidth: 0.5,
borderColor: theme.colors.outlineVariant,
backgroundColor: theme.colors.background,
},
dayHeaderText: {
fontSize: 10,
headerText: {
fontSize: 11,
fontWeight: 'bold',
color: theme.colors.onSurfaceVariant,
},
dayNumberText: {
contentRow: {
flex: 1,
flexDirection: 'row',
},
dayColumn: {
flex: 1,
borderWidth: 0.5,
borderTopWidth: 0,
borderColor: theme.colors.outlineVariant,
padding: 2,
paddingTop: 0, // Keep this 0 if header handles top padding
backgroundColor: theme.colors.background,
overflow: 'hidden',
},
dayHeader: { // Consistent name
alignItems: 'center',
justifyContent: 'center',
marginBottom: 2,
// Use minHeight for consistency
minHeight: dateNumberSize + 4,
},
dateNumberContainer: { // Base container for the date number
width: dateNumberSize,
height: dateNumberSize,
alignItems: 'center',
justifyContent: 'center',
},
todayCircle: { // Style for the *filled* circle highlight
backgroundColor: theme.colors.primary,
borderRadius: dateNumberSize / 2,
},
dateNumber: { // Base style for the date number text
fontSize: 12,
fontWeight: 'bold',
marginTop: 2,
color: theme.colors.onSurfaceVariant,
color: theme.colors.onSurface, // Default text color
textAlign: 'center',
padding: 0,
includeFontPadding: false,
fontWeight: 'normal', // Base weight
},
todayHeader: {
backgroundColor: theme.colors.primaryContainer,
},
todayHeaderText: {
color: theme.colors.onPrimaryContainer,
todayDateNumber: { // Specific style for text on today's date
color: theme.colors.onPrimary, // Contrast with primary background
fontWeight: 'bold', // Make today bold
},
eventsContainer: {
// Remove flex: 1 here if dayColumn has flex: 1
padding: 4,
flex: 1,
padding: 2,
},
});
// --- End of styles ---
return (
// Change ScrollView to View
<View style={styles.container}>
{days.map((day, index) => { // Add index to map
<View style={styles.headerRow}>
{weekDays.map((dayName, index) => ( // Use generated weekdays map
<View key={`${dayName}-${index}`} style={styles.headerCell}>
<Text style={styles.headerText}>{dayName}</Text>
</View>
))}
</View>
<View style={styles.contentRow}>
{days.map((day) => { // Removed unused index
const dateKey = format(day, 'yyyy-MM-dd');
const dayEvents = eventsByDate[dateKey] || [];
const today = isToday(day);
const isLastColumn = index === days.length - 1; // Check if it's the last column
// Removed inline dateNumberStyle object creation
return (
<View
key={dateKey}
// Apply conditional style to remove border on the last column
style={[styles.dayColumn, isLastColumn && styles.lastDayColumn]}
>
<View style={[styles.dayHeader, today && styles.todayHeader]}>
<Text style={[styles.dayHeaderText, today && styles.todayHeaderText]}>
{format(day, 'EEE')}
</Text>
<Text style={[styles.dayNumberText, today && styles.todayHeaderText]}>
<View key={dateKey} style={{ flex: 1 }}>
<View style={styles.dayColumn}>
<View style={styles.dayHeader}>
{/* Apply base container style, and add circle style conditionally */}
<View style={[
styles.dateNumberContainer, // Base size and alignment
today && styles.todayCircle // Conditional circle background
]}>
<Text style={[
styles.dateNumber, // Base text style
today && styles.todayDateNumber // Conditional color/weight override
]}>
{format(day, 'd')}
</Text>
</View>
{/* Keep inner ScrollView for vertical scrolling within the column */}
<ScrollView style={styles.eventsContainer}>
</View>
<ScrollView style={styles.eventsContainer} nestedScrollEnabled={true}>
{dayEvents.sort((a, b) => new Date(a.start).getTime() - new Date(b.start).getTime())
.map(event => (
<EventItem key={event.id} event={event} showTime={true} />
<EventItem key={event.id} event={event} showTime={true} /> // Show time in week view
))}
</ScrollView>
</View>
</View>
);
})}
</View>
</View>
);
};

View File

@@ -0,0 +1,45 @@
// src/navigation/AppNavigator.tsx
import React from 'react';
import { createNativeStackNavigator } from '@react-navigation/native-stack';
import { useTheme } from 'react-native-paper';
import MobileTabNavigator from './MobileTabNavigator';
import EventFormScreen from '../screens/EventFormScreen';
import { AppStackParamList } from '../types/navigation';
const Stack = createNativeStackNavigator<AppStackParamList>();
const AppNavigator = () => {
const theme = useTheme();
return (
<Stack.Navigator
initialRouteName="MainTabs"
screenOptions={{
headerStyle: {
backgroundColor: theme.colors.surface,
},
headerTintColor: theme.colors.text,
headerTitleStyle: {
fontWeight: 'bold',
},
contentStyle: {
backgroundColor: theme.colors.background,
},
}}
>
<Stack.Screen
name="MainTabs"
component={MobileTabNavigator}
options={{ headerShown: false }} // Hide header for the tab navigator container
/>
<Stack.Screen
name="EventForm"
component={EventFormScreen}
options={{ title: 'Event Details' }} // Set a title for the EventForm screen header
/>
</Stack.Navigator>
);
};
export default AppNavigator;

View File

@@ -8,6 +8,7 @@ import DashboardScreen from '../screens/DashboardScreen';
import ChatScreen from '../screens/ChatScreen';
import CalendarScreen from '../screens/CalendarScreen';
import ProfileScreen from '../screens/ProfileScreen';
import EventFormScreen from '../screens/EventFormScreen';
import { MobileTabParamList } from '../types/navigation';

View File

@@ -5,7 +5,7 @@ import { Platform } from 'react-native';
import { useAuth, AuthLoadingScreen } from '../contexts/AuthContext';
import AuthNavigator from './AuthNavigator'; // Unauthenticated flow
import MobileTabNavigator from './MobileTabNavigator'; // Authenticated Mobile flow
import AppNavigator from './AppNavigator'; // Import the new App stack navigator
import WebAppLayout from './WebAppLayout'; // Authenticated Web flow
import { RootStackParamList } from '../types/navigation';
@@ -25,7 +25,8 @@ const RootNavigator = () => {
{isAuthenticated ? (
// User is logged in: Choose main app layout based on platform
<Stack.Screen name="AppFlow">
{() => Platform.OS === 'web' ? <WebAppLayout /> : <MobileTabNavigator />}
{/* Use AppNavigator for mobile, WebAppLayout for web */}
{() => Platform.OS === 'web' ? <WebAppLayout /> : <AppNavigator />}
</Stack.Screen>
) : (
// User is not logged in: Show authentication flow

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 (
// 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}>
{/* Replace the old Calendar and FlatList with the new CustomCalendarView */}
<CustomCalendarView />
{/* Keep the FAB for creating new events */}
{/* FAB is now positioned relative to the SafeAreaView's padded area */}
<FAB
style={styles.fab}
icon="plus"
onPress={() => navigation.navigate('EventForm')} // Navigate without eventId for creation
color={theme.colors.onPrimary || '#ffffff'} // Ensure icon color contrasts
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,
},
messageList: {
listContainer: { // Container for the list, should take up available space
flex: 1,
},
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,36 +223,54 @@ 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
>
{/* List container takes available space */}
<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
contentContainerStyle={styles.messageList} // Padding inside the scrollable content
onContentSizeChange={() => flatListRef.current?.scrollToEnd({ animated: false })}
onLayout={() => flatListRef.current?.scrollToEnd({ animated: false })}
/>
</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" // Or "flat"
mode="outlined" // Keep outlined or flat as preferred
multiline
onKeyPress={handleKeyPress}
blurOnSubmit={false}
blurOnSubmit={false} // Keep false for multiline + send button
disabled={isLoading}
dense // Try making the input slightly smaller vertically
/>
<IconButton
icon="send"
@@ -205,6 +280,7 @@ const ChatScreen = () => {
mode="contained"
iconColor={theme.colors.onPrimary}
containerColor={theme.colors.primary}
style={styles.sendButton} // Apply style for alignment
/>
</View>
</KeyboardAvoidingView>

View File

@@ -15,7 +15,7 @@ export type WebContentStackParamList = {
Chat: undefined;
Calendar: undefined;
Profile: undefined;
EventForm?: { eventId?: number; selectedDate?: string }; // Add EventForm with optional params
EventForm?: { eventId?: number; selectedDate?: string };
};
// Screens managed by the Root Navigator (Auth vs App)
@@ -30,5 +30,11 @@ export type AuthStackParamList = {
// Example: SignUp: undefined; ForgotPassword: undefined;
};
// Screens within the main App stack (Mobile)
export type AppStackParamList = {
MainTabs: undefined; // Represents the MobileTabNavigator
EventForm: { eventId?: number; selectedDate?: string };
};
// Type for the ref used in WebAppLayout
export type WebContentNavigationProp = NavigationContainerRef<WebContentStackParamList>;