Fixed entire calendar layout + chat layout + chat history
This commit is contained in:
Binary file not shown.
119
backend/alembic.ini
Normal file
119
backend/alembic.ini
Normal 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
1
backend/alembic/README
Normal file
@@ -0,0 +1 @@
|
|||||||
|
Generic single-database configuration.
|
||||||
BIN
backend/alembic/__pycache__/env.cpython-312.pyc
Normal file
BIN
backend/alembic/__pycache__/env.cpython-312.pyc
Normal file
Binary file not shown.
97
backend/alembic/env.py
Normal file
97
backend/alembic/env.py
Normal 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()
|
||||||
28
backend/alembic/script.py.mako
Normal file
28
backend/alembic/script.py.mako
Normal 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"}
|
||||||
@@ -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 ###
|
||||||
Binary file not shown.
Binary file not shown.
@@ -17,6 +17,10 @@ def get_engine():
|
|||||||
raise ValueError("DB_URL is not set in Settings.")
|
raise ValueError("DB_URL is not set in Settings.")
|
||||||
print(f"Connecting to database at {settings.DB_URL}")
|
print(f"Connecting to database at {settings.DB_URL}")
|
||||||
_engine = create_engine(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
|
Base.metadata.create_all(_engine) # Create tables here
|
||||||
return _engine
|
return _engine
|
||||||
|
|
||||||
|
|||||||
@@ -38,6 +38,7 @@ app.add_middleware(
|
|||||||
allow_origins=[
|
allow_origins=[
|
||||||
"http://localhost:8081", # Keep for web testing if needed
|
"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.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
|
# Add other origins if necessary, e.g., production frontend URL
|
||||||
],
|
],
|
||||||
allow_credentials=True,
|
allow_credentials=True,
|
||||||
|
|||||||
Binary file not shown.
@@ -57,4 +57,4 @@ class CalendarEventResponse(CalendarEventBase):
|
|||||||
return v
|
return v
|
||||||
|
|
||||||
class Config:
|
class Config:
|
||||||
from_attributes = True # Changed from orm_mode
|
from_attributes = True
|
||||||
Binary file not shown.
BIN
backend/modules/nlp/__pycache__/models.cpython-312.pyc
Normal file
BIN
backend/modules/nlp/__pycache__/models.cpython-312.pyc
Normal file
Binary file not shown.
Binary file not shown.
@@ -7,13 +7,13 @@ from core.database import get_db
|
|||||||
|
|
||||||
from modules.auth.dependencies import get_current_user
|
from modules.auth.dependencies import get_current_user
|
||||||
from modules.auth.models import User
|
from modules.auth.models import User
|
||||||
from modules.nlp.service import process_request, ask_ai
|
# Import the new service functions and Enum
|
||||||
# Import the response schema
|
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.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
|
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
|
from modules.calendar.models import CalendarEvent
|
||||||
# Import the CalendarEvent Pydantic schemas for data validation
|
|
||||||
from modules.calendar.schemas import CalendarEventCreate, CalendarEventUpdate
|
from modules.calendar.schemas import CalendarEventCreate, CalendarEventUpdate
|
||||||
|
|
||||||
router = APIRouter(prefix="/nlp", tags=["nlp"])
|
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)
|
@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)):
|
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
|
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)
|
command_data = process_request(user_input)
|
||||||
intent = command_data["intent"]
|
intent = command_data["intent"]
|
||||||
params = command_data["params"]
|
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
|
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":
|
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":
|
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)
|
return ProcessCommandResponse(responses=responses)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
@@ -56,48 +70,100 @@ def process_command(request_data: ProcessCommandRequest, current_user: User = De
|
|||||||
case "ask_ai":
|
case "ask_ai":
|
||||||
ai_answer = ask_ai(**params)
|
ai_answer = ask_ai(**params)
|
||||||
responses.append(ai_answer)
|
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)
|
return ProcessCommandResponse(responses=responses)
|
||||||
|
|
||||||
case "get_calendar_events":
|
case "get_calendar_events":
|
||||||
# get_calendar_events returns List[CalendarEvent models]
|
|
||||||
events: List[CalendarEvent] = get_calendar_events(db, current_user.id, **params)
|
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)
|
return ProcessCommandResponse(responses=responses)
|
||||||
|
|
||||||
case "add_calendar_event":
|
case "add_calendar_event":
|
||||||
# Validate input with Pydantic schema
|
|
||||||
event_data = CalendarEventCreate(**params)
|
event_data = CalendarEventCreate(**params)
|
||||||
created_event = create_calendar_event(db, current_user.id, event_data)
|
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"
|
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"
|
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)
|
return ProcessCommandResponse(responses=responses)
|
||||||
|
|
||||||
case "update_calendar_event":
|
case "update_calendar_event":
|
||||||
event_id = params.pop('event_id', None)
|
event_id = params.pop('event_id', None)
|
||||||
if event_id is None:
|
if event_id is None:
|
||||||
raise HTTPException(status_code=400, detail="Event ID is required for update.")
|
# Save the error message before raising
|
||||||
# Validate input with Pydantic schema
|
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)
|
event_data = CalendarEventUpdate(**params)
|
||||||
updated_event = update_calendar_event(db, current_user.id, event_id, event_data=event_data)
|
updated_event = update_calendar_event(db, current_user.id, event_id, event_data=event_data)
|
||||||
title = updated_event.title or "Untitled Event"
|
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)
|
return ProcessCommandResponse(responses=responses)
|
||||||
|
|
||||||
case "delete_calendar_event":
|
case "delete_calendar_event":
|
||||||
event_id = params.get('event_id')
|
event_id = params.get('event_id')
|
||||||
if event_id is None:
|
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)
|
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)
|
return ProcessCommandResponse(responses=responses)
|
||||||
|
|
||||||
case _:
|
case _:
|
||||||
print(f"Warning: Unhandled intent '{intent}' reached api.py match statement.")
|
print(f"Warning: Unhandled intent '{intent}' reached api.py match statement.")
|
||||||
|
# The initial response_text was already saved
|
||||||
return ProcessCommandResponse(responses=responses)
|
return ProcessCommandResponse(responses=responses)
|
||||||
|
|
||||||
except HTTPException as http_exc:
|
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
|
raise http_exc
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print(f"Error executing intent '{intent}': {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
|
||||||
|
# -------------------------------------
|
||||||
23
backend/modules/nlp/models.py
Normal file
23
backend/modules/nlp/models.py
Normal 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
|
||||||
@@ -1,8 +1,14 @@
|
|||||||
# modules/nlp/service.py
|
# modules/nlp/service.py
|
||||||
|
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
from sqlalchemy import desc # Import desc for ordering
|
||||||
from google import genai
|
from google import genai
|
||||||
import json
|
import json
|
||||||
from datetime import datetime, timezone
|
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
|
# from core.config import settings
|
||||||
|
|
||||||
# client = genai.Client(api_key=settings.GOOGLE_API_KEY)
|
# client = genai.Client(api_key=settings.GOOGLE_API_KEY)
|
||||||
@@ -70,6 +76,27 @@ Here is some context for you:
|
|||||||
Here is the user request:
|
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):
|
def process_request(request: str):
|
||||||
"""
|
"""
|
||||||
Process the user request using the Google GenAI API.
|
Process the user request using the Google GenAI API.
|
||||||
|
|||||||
@@ -43,3 +43,4 @@ tzdata==2025.2
|
|||||||
uvicorn==0.34.1
|
uvicorn==0.34.1
|
||||||
vine==5.1.0
|
vine==5.1.0
|
||||||
wcwidth==0.2.13
|
wcwidth==0.2.13
|
||||||
|
alembic
|
||||||
|
|||||||
@@ -19,7 +19,8 @@
|
|||||||
"adaptiveIcon": {
|
"adaptiveIcon": {
|
||||||
"foregroundImage": "./assets/adaptive-icon.png",
|
"foregroundImage": "./assets/adaptive-icon.png",
|
||||||
"backgroundColor": "#ffffff"
|
"backgroundColor": "#ffffff"
|
||||||
}
|
},
|
||||||
|
"softwareKeyboardLayoutMode": "resize"
|
||||||
},
|
},
|
||||||
"web": {
|
"web": {
|
||||||
"favicon": "./assets/favicon.png"
|
"favicon": "./assets/favicon.png"
|
||||||
|
|||||||
4
interfaces/nativeapp/package-lock.json
generated
4
interfaces/nativeapp/package-lock.json
generated
@@ -9,7 +9,7 @@
|
|||||||
"version": "1.0.0",
|
"version": "1.0.0",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@expo/metro-runtime": "~4.0.1",
|
"@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-native-community/datetimepicker": "8.2.0",
|
||||||
"@react-navigation/bottom-tabs": "^7.3.10",
|
"@react-navigation/bottom-tabs": "^7.3.10",
|
||||||
"@react-navigation/native": "^7.1.6",
|
"@react-navigation/native": "^7.1.6",
|
||||||
@@ -17,7 +17,7 @@
|
|||||||
"async-storage": "^0.1.0",
|
"async-storage": "^0.1.0",
|
||||||
"axios": "^1.8.4",
|
"axios": "^1.8.4",
|
||||||
"date-fns": "^4.1.0",
|
"date-fns": "^4.1.0",
|
||||||
"expo": "~52.0.46",
|
"expo": "^52.0.46",
|
||||||
"expo-font": "~13.0.4",
|
"expo-font": "~13.0.4",
|
||||||
"expo-secure-store": "~14.0.1",
|
"expo-secure-store": "~14.0.1",
|
||||||
"expo-splash-screen": "~0.29.24",
|
"expo-splash-screen": "~0.29.24",
|
||||||
|
|||||||
@@ -10,15 +10,18 @@
|
|||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@expo/metro-runtime": "~4.0.1",
|
"@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/bottom-tabs": "^7.3.10",
|
||||||
"@react-navigation/native": "^7.1.6",
|
"@react-navigation/native": "^7.1.6",
|
||||||
"@react-navigation/native-stack": "^7.3.10",
|
"@react-navigation/native-stack": "^7.3.10",
|
||||||
"async-storage": "^0.1.0",
|
"async-storage": "^0.1.0",
|
||||||
"axios": "^1.8.4",
|
"axios": "^1.8.4",
|
||||||
"date-fns": "^4.1.0",
|
"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-secure-store": "~14.0.1",
|
||||||
|
"expo-splash-screen": "~0.29.24",
|
||||||
"expo-status-bar": "~2.0.1",
|
"expo-status-bar": "~2.0.1",
|
||||||
"react": "18.3.1",
|
"react": "18.3.1",
|
||||||
"react-dom": "18.3.1",
|
"react-dom": "18.3.1",
|
||||||
@@ -30,10 +33,7 @@
|
|||||||
"react-native-safe-area-context": "4.12.0",
|
"react-native-safe-area-context": "4.12.0",
|
||||||
"react-native-screens": "~4.4.0",
|
"react-native-screens": "~4.4.0",
|
||||||
"react-native-vector-icons": "^10.2.0",
|
"react-native-vector-icons": "^10.2.0",
|
||||||
"react-native-web": "~0.19.13",
|
"react-native-web": "~0.19.13"
|
||||||
"@react-native-community/datetimepicker": "8.2.0",
|
|
||||||
"expo-font": "~13.0.4",
|
|
||||||
"expo-splash-screen": "~0.29.24"
|
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@babel/core": "^7.25.2",
|
"@babel/core": "^7.25.2",
|
||||||
|
|||||||
@@ -5,7 +5,8 @@ import * as SecureStore from 'expo-secure-store';
|
|||||||
import AsyncStorage from '@react-native-async-storage/async-storage';
|
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 API_BASE_URL = process.env.EXPO_PUBLIC_API_URL || 'http://localhost:8000/api'; // Use your machine's IP
|
||||||
const TOKEN_KEY = 'maia_access_token';
|
const TOKEN_KEY = 'maia_access_token';
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
// src/components/calendar/CalendarDayCell.tsx
|
// src/components/calendar/CalendarDayCell.tsx
|
||||||
import React from 'react';
|
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 { Text, useTheme } from 'react-native-paper';
|
||||||
import { format, isToday } from 'date-fns';
|
import { format, isToday } from 'date-fns';
|
||||||
|
|
||||||
@@ -11,56 +11,100 @@ interface CalendarDayCellProps {
|
|||||||
date: Date;
|
date: Date;
|
||||||
events: CalendarEvent[];
|
events: CalendarEvent[];
|
||||||
isCurrentMonth?: boolean; // Optional, mainly for month view styling
|
isCurrentMonth?: boolean; // Optional, mainly for month view styling
|
||||||
|
height?: number; // Optional fixed height
|
||||||
width?: number; // Optional fixed width
|
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 CalendarDayCell: React.FC<CalendarDayCellProps> = ({ date, events, isCurrentMonth = true, height, width }) => {
|
||||||
const theme = useTheme();
|
const theme = useTheme();
|
||||||
const today = isToday(date);
|
const today = isToday(date);
|
||||||
|
const dateNumber = format(date, 'd');
|
||||||
|
|
||||||
|
// --- Define styles inside the component to access theme ---
|
||||||
const styles = StyleSheet.create({
|
const styles = StyleSheet.create({
|
||||||
cell: {
|
cell: {
|
||||||
flex: width ? undefined : 1, // Use flex=1 if no width is provided
|
flex: width ? undefined : 1,
|
||||||
width: width,
|
width: width,
|
||||||
height: height,
|
height: height,
|
||||||
borderWidth: 0.5,
|
borderWidth: 0.5,
|
||||||
borderTopWidth: 0,
|
borderTopWidth: 0,
|
||||||
borderColor: theme.colors.outlineVariant,
|
borderColor: theme.colors.outlineVariant,
|
||||||
padding: 2,
|
padding: 2,
|
||||||
paddingTop: 0,
|
paddingTop: 0, // Keep this 0 if header handles top padding
|
||||||
backgroundColor: theme.colors.background,
|
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',
|
alignItems: 'center',
|
||||||
|
justifyContent: 'center',
|
||||||
marginBottom: 2,
|
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,
|
fontSize: 12,
|
||||||
fontWeight: today ? 'bold' : 'normal',
|
// Base color determined by isCurrentMonth
|
||||||
marginTop: 8,
|
color: isCurrentMonth ? theme.colors.onSurface : theme.colors.onSurfaceDisabled,
|
||||||
color: today ? theme.colors.primary : (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: {
|
eventsContainer: {
|
||||||
flex: 1, // Take remaining space in the cell
|
flex: 1,
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
// --- End of styles ---
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<View style={styles.cell}>
|
<View style={styles.cell}>
|
||||||
<View style={styles.dateNumberContainer}>
|
{/* Renamed container View for consistency */}
|
||||||
<Text style={styles.dateNumber}>{format(date, 'd')}</Text>
|
<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>
|
</View>
|
||||||
{/* Use ScrollView for month view where events might exceed fixed height */}
|
|
||||||
<ScrollView style={styles.eventsContainer} nestedScrollEnabled={true}>
|
<ScrollView style={styles.eventsContainer} nestedScrollEnabled={true}>
|
||||||
{events
|
{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 => (
|
.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>
|
</ScrollView>
|
||||||
</View>
|
</View>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
export default React.memo(CalendarDayCell); // Memoize for performance
|
// Keep memoization
|
||||||
|
export default React.memo(CalendarDayCell);
|
||||||
@@ -18,39 +18,35 @@ const CalendarHeader: React.FC<CalendarHeaderProps> = ({ currentRangeText, onPre
|
|||||||
const styles = StyleSheet.create({
|
const styles = StyleSheet.create({
|
||||||
container: {
|
container: {
|
||||||
flexDirection: 'row',
|
flexDirection: 'row',
|
||||||
justifyContent: 'flex-start',
|
|
||||||
alignItems: 'center',
|
alignItems: 'center',
|
||||||
paddingVertical: 8,
|
paddingVertical: 8,
|
||||||
paddingHorizontal: 12,
|
paddingHorizontal: 8,
|
||||||
borderBottomWidth: 1,
|
borderBottomWidth: 1,
|
||||||
borderBottomColor: theme.colors.outlineVariant,
|
borderBottomColor: theme.colors.outlineVariant,
|
||||||
backgroundColor: theme.colors.surface, // Match background
|
backgroundColor: theme.colors.surface,
|
||||||
|
},
|
||||||
|
leftGroup: {
|
||||||
|
flexDirection: 'row',
|
||||||
|
alignItems: 'center',
|
||||||
|
flex: 1,
|
||||||
},
|
},
|
||||||
title: {
|
title: {
|
||||||
fontSize: 18,
|
fontSize: 18,
|
||||||
fontWeight: 'bold',
|
fontWeight: 'bold',
|
||||||
color: theme.colors.onSurface, // Use theme text color
|
color: theme.colors.onSurface,
|
||||||
|
marginLeft: 12,
|
||||||
|
flexShrink: 1,
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<View style={styles.container}>
|
<View style={styles.container}>
|
||||||
<IconButton
|
<View style={styles.leftGroup}>
|
||||||
icon="chevron-left"
|
<IconButton icon="chevron-left" onPress={onPrev} size={24} iconColor={theme.colors.primary} />
|
||||||
onPress={onPrev}
|
<IconButton icon="chevron-right" onPress={onNext} size={24} iconColor={theme.colors.primary} />
|
||||||
size={24}
|
<Text style={styles.title} ellipsizeMode='tail'>{currentRangeText}</Text>
|
||||||
iconColor={theme.colors.primary} // Use theme color
|
</View>
|
||||||
/>
|
<ViewSwitcher currentView={currentView} onViewChange={onViewChange} />
|
||||||
<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>
|
</View>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -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;
|
||||||
@@ -43,12 +43,14 @@ const EventItem: React.FC<EventItemProps> = ({ event, showTime = true }) => {
|
|||||||
},
|
},
|
||||||
text: {
|
text: {
|
||||||
color: theme.colors.onPrimary, // Ensure text is readable on the background color
|
color: theme.colors.onPrimary, // Ensure text is readable on the background color
|
||||||
fontSize: 12,
|
fontSize: 10,
|
||||||
fontWeight: '500',
|
fontWeight: 'bold',
|
||||||
},
|
},
|
||||||
timeText: {
|
timeText: {
|
||||||
fontSize: 9,
|
fontSize: 8,
|
||||||
fontWeight: 'normal',
|
fontWeight: 'normal',
|
||||||
|
color: theme.colors.onPrimary,
|
||||||
|
marginRight: 2, // Space between time and title
|
||||||
},
|
},
|
||||||
tagContainer: {
|
tagContainer: {
|
||||||
flexDirection: 'row',
|
flexDirection: 'row',
|
||||||
@@ -77,7 +79,7 @@ const EventItem: React.FC<EventItemProps> = ({ event, showTime = true }) => {
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<TouchableOpacity onPress={handlePress} style={styles.container}>
|
<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>}
|
{showTime && <Text style={styles.timeText}>{timeString} </Text>}
|
||||||
{event.title}
|
{event.title}
|
||||||
</Text>
|
</Text>
|
||||||
|
|||||||
@@ -15,8 +15,9 @@ interface ThreeDayViewProps {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Get screen width
|
// Get screen width
|
||||||
const screenWidth = Dimensions.get('window').width;
|
// const screenWidth = Dimensions.get('window').width; // No longer needed here if dayColumn uses flex:1
|
||||||
const dayColumnWidth = screenWidth / 3; // Divide by 3 for 3-day view
|
// const dayColumnWidth = screenWidth / 3;
|
||||||
|
const dateNumberSize = 24; // Define a size for the circle/text container
|
||||||
|
|
||||||
const ThreeDayView: React.FC<ThreeDayViewProps> = ({ startDate, endDate, eventsByDate }) => {
|
const ThreeDayView: React.FC<ThreeDayViewProps> = ({ startDate, endDate, eventsByDate }) => {
|
||||||
const theme = useTheme();
|
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
|
// Ensure exactly 3 days are generated if interval logic is tricky
|
||||||
const displayDays = days.slice(0, 3);
|
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({
|
const styles = StyleSheet.create({
|
||||||
container: {
|
container: {
|
||||||
flex: 1,
|
flex: 1,
|
||||||
flexDirection: 'row', // Apply row direction directly to the container View
|
|
||||||
},
|
},
|
||||||
// Remove scrollViewContent style as it's no longer needed
|
headerRow: {
|
||||||
// scrollViewContent: { flexDirection: 'row' },
|
flexDirection: 'row',
|
||||||
dayColumn: {
|
paddingVertical: 5,
|
||||||
width: dayColumnWidth,
|
paddingBottom: 0,
|
||||||
borderRightWidth: 1,
|
backgroundColor: theme.colors.background,
|
||||||
borderRightColor: theme.colors.outlineVariant,
|
},
|
||||||
// Add flex: 1 to allow inner ScrollView to expand vertically
|
headerCell: {
|
||||||
flex: 1,
|
flex: 1,
|
||||||
|
alignItems: 'center',
|
||||||
|
justifyContent: 'center',
|
||||||
|
borderLeftWidth: 0.5,
|
||||||
|
borderRightWidth: 0.5,
|
||||||
|
borderColor: theme.colors.outlineVariant,
|
||||||
|
backgroundColor: theme.colors.background,
|
||||||
},
|
},
|
||||||
lastDayColumn: {
|
headerText: {
|
||||||
borderRightWidth: 0,
|
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: {
|
dayHeader: {
|
||||||
paddingVertical: 8,
|
|
||||||
alignItems: 'center',
|
alignItems: 'center',
|
||||||
borderBottomWidth: 1,
|
justifyContent: 'center',
|
||||||
borderBottomColor: theme.colors.outlineVariant,
|
marginBottom: 2,
|
||||||
backgroundColor: theme.colors.surfaceVariant,
|
minHeight: dateNumberSize + 4, // Slightly larger than circle to give space
|
||||||
},
|
},
|
||||||
dayHeaderText: {
|
// Base container for the date number - useful for alignment consistency
|
||||||
fontSize: 10,
|
dateNumberContainer: {
|
||||||
fontWeight: 'bold',
|
width: dateNumberSize,
|
||||||
color: theme.colors.onSurfaceVariant,
|
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,
|
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',
|
fontWeight: 'bold',
|
||||||
marginTop: 2,
|
|
||||||
color: theme.colors.onSurfaceVariant,
|
|
||||||
},
|
|
||||||
todayHeader: {
|
|
||||||
backgroundColor: theme.colors.primaryContainer,
|
|
||||||
},
|
|
||||||
todayHeaderText: {
|
|
||||||
color: theme.colors.onPrimaryContainer,
|
|
||||||
},
|
},
|
||||||
eventsContainer: {
|
eventsContainer: {
|
||||||
// Remove flex: 1 here if dayColumn has flex: 1
|
flex: 1,
|
||||||
padding: 4,
|
padding: 2,
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
// --- End of styles ---
|
||||||
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
// Change ScrollView to View
|
|
||||||
<View style={styles.container}>
|
<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 dateKey = format(day, 'yyyy-MM-dd');
|
||||||
const dayEvents = eventsByDate[dateKey] || [];
|
const dayEvents = eventsByDate[dateKey] || [];
|
||||||
const today = isToday(day);
|
const today = isToday(day);
|
||||||
const isLastColumn = index === displayDays.length - 1;
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<View
|
// Use flex: 1 container for each day column
|
||||||
key={dateKey}
|
<View key={dateKey} style={{ flex: 1 }}>
|
||||||
style={[styles.dayColumn, isLastColumn && styles.lastDayColumn]}
|
<View style={styles.dayColumn}>
|
||||||
>
|
<View style={styles.dayHeader}>
|
||||||
<View style={[styles.dayHeader, today && styles.todayHeader]}>
|
{/* Apply base container style, and add circle style conditionally */}
|
||||||
<Text style={[styles.dayHeaderText, today && styles.todayHeaderText]}>
|
<View style={[
|
||||||
{format(day, 'EEE')}
|
styles.dateNumberContainer, // Base size and alignment
|
||||||
</Text>
|
today && styles.todayCircle // Conditional circle background
|
||||||
<Text style={[styles.dayNumberText, today && styles.todayHeaderText]}>
|
]}>
|
||||||
|
<Text style={[
|
||||||
|
styles.dateNumber, // Base text style
|
||||||
|
today && styles.todayDateNumber // Conditional color/weight for today
|
||||||
|
]}>
|
||||||
{format(day, 'd')}
|
{format(day, 'd')}
|
||||||
</Text>
|
</Text>
|
||||||
</View>
|
</View>
|
||||||
{/* Keep inner ScrollView for vertical scrolling within the column */}
|
</View>
|
||||||
<ScrollView style={styles.eventsContainer}>
|
<ScrollView style={styles.eventsContainer} nestedScrollEnabled={true}>
|
||||||
{dayEvents.sort((a, b) => new Date(a.start).getTime() - new Date(b.start).getTime())
|
{dayEvents.sort((a, b) => new Date(a.start).getTime() - new Date(b.start).getTime())
|
||||||
.map(event => (
|
.map(event => (
|
||||||
<EventItem key={event.id} event={event} showTime={true} />
|
<EventItem key={event.id} event={event} showTime={true} />
|
||||||
))}
|
))}
|
||||||
</ScrollView>
|
</ScrollView>
|
||||||
</View>
|
</View>
|
||||||
|
</View>
|
||||||
);
|
);
|
||||||
})}
|
})}
|
||||||
</View>
|
</View>
|
||||||
|
</View>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -1,8 +1,9 @@
|
|||||||
// src/components/calendar/ViewSwitcher.tsx
|
// src/components/calendar/ViewSwitcher.tsx
|
||||||
import React from 'react';
|
import React from 'react';
|
||||||
import { View, StyleSheet } from 'react-native';
|
import { View, StyleSheet } from 'react-native';
|
||||||
import { SegmentedButtons, useTheme } from 'react-native-paper';
|
import { useTheme } from 'react-native-paper'; // Keep useTheme
|
||||||
import { CalendarViewMode } from './CustomCalendarView'; // Import the type
|
import { CalendarViewMode } from './CustomCalendarView';
|
||||||
|
import CustomSegmentedButtons from './CustomSegmentedButtons'; // Import the custom component
|
||||||
|
|
||||||
interface ViewSwitcherProps {
|
interface ViewSwitcherProps {
|
||||||
currentView: CalendarViewMode;
|
currentView: CalendarViewMode;
|
||||||
@@ -14,23 +15,24 @@ const ViewSwitcher: React.FC<ViewSwitcherProps> = ({ currentView, onViewChange }
|
|||||||
const styles = StyleSheet.create({
|
const styles = StyleSheet.create({
|
||||||
container: {
|
container: {
|
||||||
paddingVertical: 8,
|
paddingVertical: 8,
|
||||||
paddingHorizontal: 16,
|
// Add horizontal padding if needed to center or space the component
|
||||||
backgroundColor: theme.colors.surface, // Match background
|
paddingHorizontal: 8,
|
||||||
borderBottomColor: theme.colors.outlineVariant,
|
minWidth: 150, // Add a minimum width
|
||||||
|
alignSelf: 'center', // Center the component if it's smaller than the parent
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<View style={styles.container}>
|
<View style={styles.container}>
|
||||||
<SegmentedButtons
|
<CustomSegmentedButtons // Use the custom component
|
||||||
value={currentView}
|
value={currentView}
|
||||||
onValueChange={(value) => onViewChange(value as CalendarViewMode)} // Cast value
|
onValueChange={onViewChange} // No need to cast type here anymore
|
||||||
buttons={[
|
buttons={[
|
||||||
{ value: 'month', label: 'M', checkedColor: theme.colors.onPrimary },
|
// Pass the same button configuration
|
||||||
{ value: 'week', label: 'W', checkedColor: theme.colors.onPrimary },
|
{ value: 'month', label: 'M' /* Use full labels for clarity */ },
|
||||||
{ value: '3day', label: '3', checkedColor: theme.colors.onPrimary },
|
{ value: 'week', label: 'W' },
|
||||||
|
{ value: '3day', label: '3D' },
|
||||||
]}
|
]}
|
||||||
density="high"
|
|
||||||
/>
|
/>
|
||||||
</View>
|
</View>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -1,13 +1,11 @@
|
|||||||
// src/components/calendar/WeekView.tsx
|
// src/components/calendar/WeekView.tsx
|
||||||
import React, { useMemo } from 'react';
|
import React, { useMemo } from 'react';
|
||||||
// Import Dimensions
|
import { View, StyleSheet, ScrollView } from 'react-native'; // Removed Dimensions unless used elsewhere
|
||||||
import { View, StyleSheet, ScrollView, Dimensions } from 'react-native';
|
|
||||||
import { Text, useTheme } from 'react-native-paper';
|
import { Text, useTheme } from 'react-native-paper';
|
||||||
import { eachDayOfInterval, format, isToday } from 'date-fns';
|
import { eachDayOfInterval, format, isToday } from 'date-fns';
|
||||||
|
|
||||||
import CalendarDayCell from './CalendarDayCell';
|
|
||||||
import { CalendarEvent } from '../../types/calendar';
|
import { CalendarEvent } from '../../types/calendar';
|
||||||
import EventItem from './EventItem'; // Import EventItem
|
import EventItem from './EventItem';
|
||||||
|
|
||||||
interface WeekViewProps {
|
interface WeekViewProps {
|
||||||
startDate: Date; // Start of the week
|
startDate: Date; // Start of the week
|
||||||
@@ -15,9 +13,8 @@ interface WeekViewProps {
|
|||||||
eventsByDate: { [key: string]: CalendarEvent[] };
|
eventsByDate: { [key: string]: CalendarEvent[] };
|
||||||
}
|
}
|
||||||
|
|
||||||
// Get screen width
|
// Define size here, consistent with other views
|
||||||
const screenWidth = Dimensions.get('window').width;
|
const dateNumberSize = 24;
|
||||||
const dayColumnWidth = screenWidth / 7; // Divide by 7 for week view
|
|
||||||
|
|
||||||
const WeekView: React.FC<WeekViewProps> = ({ startDate, endDate, eventsByDate }) => {
|
const WeekView: React.FC<WeekViewProps> = ({ startDate, endDate, eventsByDate }) => {
|
||||||
const theme = useTheme();
|
const theme = useTheme();
|
||||||
@@ -26,86 +23,132 @@ const WeekView: React.FC<WeekViewProps> = ({ startDate, endDate, eventsByDate })
|
|||||||
endDate,
|
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({
|
const styles = StyleSheet.create({
|
||||||
container: {
|
container: {
|
||||||
flex: 1,
|
flex: 1,
|
||||||
flexDirection: 'row', // Apply row direction directly to the container View
|
|
||||||
},
|
},
|
||||||
// Remove scrollViewContent style
|
headerRow: {
|
||||||
// scrollViewContent: { flexDirection: 'row' },
|
flexDirection: 'row',
|
||||||
dayColumn: {
|
paddingVertical: 5,
|
||||||
width: dayColumnWidth,
|
paddingBottom: 0,
|
||||||
borderRightWidth: 1,
|
backgroundColor: theme.colors.background,
|
||||||
borderRightColor: theme.colors.outlineVariant,
|
|
||||||
flex: 1, // Add flex: 1 to allow inner ScrollView to expand vertically
|
|
||||||
},
|
},
|
||||||
lastDayColumn: { // Add style for the last column
|
headerCell: {
|
||||||
borderRightWidth: 0, // Remove border
|
flex: 1,
|
||||||
},
|
|
||||||
dayHeader: {
|
|
||||||
paddingVertical: 8,
|
|
||||||
alignItems: 'center',
|
alignItems: 'center',
|
||||||
borderBottomWidth: 1,
|
justifyContent: 'center',
|
||||||
borderBottomColor: theme.colors.outlineVariant,
|
borderLeftWidth: 0.5,
|
||||||
backgroundColor: theme.colors.surfaceVariant,
|
borderRightWidth: 0.5,
|
||||||
|
borderColor: theme.colors.outlineVariant,
|
||||||
|
backgroundColor: theme.colors.background,
|
||||||
},
|
},
|
||||||
dayHeaderText: {
|
headerText: {
|
||||||
fontSize: 10,
|
fontSize: 11,
|
||||||
fontWeight: 'bold',
|
fontWeight: 'bold',
|
||||||
color: theme.colors.onSurfaceVariant,
|
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,
|
fontSize: 12,
|
||||||
fontWeight: 'bold',
|
color: theme.colors.onSurface, // Default text color
|
||||||
marginTop: 2,
|
textAlign: 'center',
|
||||||
color: theme.colors.onSurfaceVariant,
|
padding: 0,
|
||||||
|
includeFontPadding: false,
|
||||||
|
fontWeight: 'normal', // Base weight
|
||||||
},
|
},
|
||||||
todayHeader: {
|
todayDateNumber: { // Specific style for text on today's date
|
||||||
backgroundColor: theme.colors.primaryContainer,
|
color: theme.colors.onPrimary, // Contrast with primary background
|
||||||
},
|
fontWeight: 'bold', // Make today bold
|
||||||
todayHeaderText: {
|
|
||||||
color: theme.colors.onPrimaryContainer,
|
|
||||||
},
|
},
|
||||||
eventsContainer: {
|
eventsContainer: {
|
||||||
// Remove flex: 1 here if dayColumn has flex: 1
|
flex: 1,
|
||||||
padding: 4,
|
padding: 2,
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
// --- End of styles ---
|
||||||
|
|
||||||
return (
|
return (
|
||||||
// Change ScrollView to View
|
|
||||||
<View style={styles.container}>
|
<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 dateKey = format(day, 'yyyy-MM-dd');
|
||||||
const dayEvents = eventsByDate[dateKey] || [];
|
const dayEvents = eventsByDate[dateKey] || [];
|
||||||
const today = isToday(day);
|
const today = isToday(day);
|
||||||
const isLastColumn = index === days.length - 1; // Check if it's the last column
|
|
||||||
|
// Removed inline dateNumberStyle object creation
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<View
|
<View key={dateKey} style={{ flex: 1 }}>
|
||||||
key={dateKey}
|
<View style={styles.dayColumn}>
|
||||||
// Apply conditional style to remove border on the last column
|
<View style={styles.dayHeader}>
|
||||||
style={[styles.dayColumn, isLastColumn && styles.lastDayColumn]}
|
{/* Apply base container style, and add circle style conditionally */}
|
||||||
>
|
<View style={[
|
||||||
<View style={[styles.dayHeader, today && styles.todayHeader]}>
|
styles.dateNumberContainer, // Base size and alignment
|
||||||
<Text style={[styles.dayHeaderText, today && styles.todayHeaderText]}>
|
today && styles.todayCircle // Conditional circle background
|
||||||
{format(day, 'EEE')}
|
]}>
|
||||||
</Text>
|
<Text style={[
|
||||||
<Text style={[styles.dayNumberText, today && styles.todayHeaderText]}>
|
styles.dateNumber, // Base text style
|
||||||
|
today && styles.todayDateNumber // Conditional color/weight override
|
||||||
|
]}>
|
||||||
{format(day, 'd')}
|
{format(day, 'd')}
|
||||||
</Text>
|
</Text>
|
||||||
</View>
|
</View>
|
||||||
{/* Keep inner ScrollView for vertical scrolling within the column */}
|
</View>
|
||||||
<ScrollView style={styles.eventsContainer}>
|
<ScrollView style={styles.eventsContainer} nestedScrollEnabled={true}>
|
||||||
{dayEvents.sort((a, b) => new Date(a.start).getTime() - new Date(b.start).getTime())
|
{dayEvents.sort((a, b) => new Date(a.start).getTime() - new Date(b.start).getTime())
|
||||||
.map(event => (
|
.map(event => (
|
||||||
<EventItem key={event.id} event={event} showTime={true} />
|
<EventItem key={event.id} event={event} showTime={true} /> // Show time in week view
|
||||||
))}
|
))}
|
||||||
</ScrollView>
|
</ScrollView>
|
||||||
</View>
|
</View>
|
||||||
|
</View>
|
||||||
);
|
);
|
||||||
})}
|
})}
|
||||||
</View>
|
</View>
|
||||||
|
</View>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
45
interfaces/nativeapp/src/navigation/AppNavigator.tsx
Normal file
45
interfaces/nativeapp/src/navigation/AppNavigator.tsx
Normal 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;
|
||||||
@@ -8,6 +8,7 @@ import DashboardScreen from '../screens/DashboardScreen';
|
|||||||
import ChatScreen from '../screens/ChatScreen';
|
import ChatScreen from '../screens/ChatScreen';
|
||||||
import CalendarScreen from '../screens/CalendarScreen';
|
import CalendarScreen from '../screens/CalendarScreen';
|
||||||
import ProfileScreen from '../screens/ProfileScreen';
|
import ProfileScreen from '../screens/ProfileScreen';
|
||||||
|
import EventFormScreen from '../screens/EventFormScreen';
|
||||||
|
|
||||||
import { MobileTabParamList } from '../types/navigation';
|
import { MobileTabParamList } from '../types/navigation';
|
||||||
|
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ import { Platform } from 'react-native';
|
|||||||
|
|
||||||
import { useAuth, AuthLoadingScreen } from '../contexts/AuthContext';
|
import { useAuth, AuthLoadingScreen } from '../contexts/AuthContext';
|
||||||
import AuthNavigator from './AuthNavigator'; // Unauthenticated flow
|
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 WebAppLayout from './WebAppLayout'; // Authenticated Web flow
|
||||||
|
|
||||||
import { RootStackParamList } from '../types/navigation';
|
import { RootStackParamList } from '../types/navigation';
|
||||||
@@ -25,7 +25,8 @@ const RootNavigator = () => {
|
|||||||
{isAuthenticated ? (
|
{isAuthenticated ? (
|
||||||
// User is logged in: Choose main app layout based on platform
|
// User is logged in: Choose main app layout based on platform
|
||||||
<Stack.Screen name="AppFlow">
|
<Stack.Screen name="AppFlow">
|
||||||
{() => Platform.OS === 'web' ? <WebAppLayout /> : <MobileTabNavigator />}
|
{/* Use AppNavigator for mobile, WebAppLayout for web */}
|
||||||
|
{() => Platform.OS === 'web' ? <WebAppLayout /> : <AppNavigator />}
|
||||||
</Stack.Screen>
|
</Stack.Screen>
|
||||||
) : (
|
) : (
|
||||||
// User is not logged in: Show authentication flow
|
// User is not logged in: Show authentication flow
|
||||||
|
|||||||
@@ -1,14 +1,14 @@
|
|||||||
// src/screens/CalendarScreen.tsx
|
// src/screens/CalendarScreen.tsx
|
||||||
import React from 'react';
|
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 { useTheme, FAB } from 'react-native-paper';
|
||||||
import { useNavigation } from '@react-navigation/native';
|
import { useNavigation } from '@react-navigation/native';
|
||||||
import { StackNavigationProp } from '@react-navigation/stack';
|
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';
|
import { AppStackParamList } from '../navigation/AppNavigator';
|
||||||
|
|
||||||
// Define navigation prop type
|
|
||||||
type CalendarScreenNavigationProp = StackNavigationProp<AppStackParamList, 'Calendar'>;
|
type CalendarScreenNavigationProp = StackNavigationProp<AppStackParamList, 'Calendar'>;
|
||||||
|
|
||||||
const CalendarScreen = () => {
|
const CalendarScreen = () => {
|
||||||
@@ -16,29 +16,45 @@ const CalendarScreen = () => {
|
|||||||
const navigation = useNavigation<CalendarScreenNavigationProp>();
|
const navigation = useNavigation<CalendarScreenNavigationProp>();
|
||||||
|
|
||||||
const styles = StyleSheet.create({
|
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: {
|
fab: {
|
||||||
position: 'absolute',
|
position: 'absolute',
|
||||||
margin: 16,
|
// Change from margin: 16, right: 0, bottom: 0
|
||||||
right: 0,
|
// Explicitly set distance from the bottom/right edges of the SAFE AREA
|
||||||
bottom: 0,
|
right: 16,
|
||||||
|
bottom: 16, // Adjust this value if needed (e.g., 20 or 24) for more padding
|
||||||
backgroundColor: theme.colors.primary,
|
backgroundColor: theme.colors.primary,
|
||||||
|
zIndex: 10,
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
return (
|
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}>
|
<View style={styles.container}>
|
||||||
{/* Replace the old Calendar and FlatList with the new CustomCalendarView */}
|
|
||||||
<CustomCalendarView />
|
<CustomCalendarView />
|
||||||
|
|
||||||
{/* Keep the FAB for creating new events */}
|
{/* FAB is now positioned relative to the SafeAreaView's padded area */}
|
||||||
<FAB
|
<FAB
|
||||||
style={styles.fab}
|
style={styles.fab}
|
||||||
icon="plus"
|
icon="plus"
|
||||||
onPress={() => navigation.navigate('EventForm')} // Navigate without eventId for creation
|
onPress={() => navigation.navigate('EventForm')}
|
||||||
color={theme.colors.onPrimary || '#ffffff'} // Ensure icon color contrasts
|
color={theme.colors.onPrimary || '#ffffff'}
|
||||||
/>
|
/>
|
||||||
</View>
|
</View>
|
||||||
|
</SafeAreaView>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
// src/screens/ChatScreen.tsx
|
// 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 { 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 { Text, useTheme, TextInput, Button, IconButton, PaperProvider } from 'react-native-paper';
|
||||||
import { SafeAreaView } from 'react-native-safe-area-context';
|
import { SafeAreaView } from 'react-native-safe-area-context';
|
||||||
@@ -13,25 +13,68 @@ interface Message {
|
|||||||
timestamp: Date;
|
timestamp: Date;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Define the expected structure for the API response
|
// Define the expected structure for the API response from /nlp/process-command
|
||||||
interface NlpResponse {
|
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 ChatScreen = () => {
|
||||||
const theme = useTheme();
|
const theme = useTheme();
|
||||||
const [messages, setMessages] = useState<Message[]>([]);
|
const [messages, setMessages] = useState<Message[]>([]);
|
||||||
const [inputText, setInputText] = useState('');
|
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);
|
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
|
// Function to handle sending a message
|
||||||
const handleSend = useCallback(async () => {
|
const handleSend = useCallback(async () => {
|
||||||
const trimmedText = inputText.trim();
|
const trimmedText = inputText.trim();
|
||||||
if (!trimmedText) return; // Don't send empty messages
|
if (!trimmedText || isLoading) return; // Prevent sending while loading
|
||||||
|
|
||||||
const userMessage: Message = {
|
const userMessage: Message = {
|
||||||
id: Date.now().toString() + '-user',
|
id: Date.now().toString() + '-user', // Temporary frontend ID
|
||||||
text: trimmedText,
|
text: trimmedText,
|
||||||
sender: 'user',
|
sender: 'user',
|
||||||
timestamp: new Date(),
|
timestamp: new Date(),
|
||||||
@@ -39,6 +82,7 @@ const ChatScreen = () => {
|
|||||||
|
|
||||||
// Add user message optimistically
|
// Add user message optimistically
|
||||||
setMessages(prevMessages => [...prevMessages, userMessage]);
|
setMessages(prevMessages => [...prevMessages, userMessage]);
|
||||||
|
|
||||||
setInputText('');
|
setInputText('');
|
||||||
setIsLoading(true);
|
setIsLoading(true);
|
||||||
|
|
||||||
@@ -48,7 +92,6 @@ const ChatScreen = () => {
|
|||||||
// --- Call Backend API ---
|
// --- Call Backend API ---
|
||||||
try {
|
try {
|
||||||
console.log(`[ChatScreen] Sending to /nlp/process-command: ${trimmedText}`);
|
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 });
|
const response = await apiClient.post<NlpResponse>('/nlp/process-command', { user_input: trimmedText });
|
||||||
console.log("[ChatScreen] Received response:", response.data);
|
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) {
|
if (response.data && Array.isArray(response.data.responses) && response.data.responses.length > 0) {
|
||||||
response.data.responses.forEach((responseText, index) => {
|
response.data.responses.forEach((responseText, index) => {
|
||||||
aiResponses.push({
|
aiResponses.push({
|
||||||
id: `${Date.now()}-ai-${index}`, // Ensure unique IDs
|
id: `${Date.now()}-ai-${index}`, // Temporary frontend ID
|
||||||
text: responseText || "...", // Handle potential empty strings
|
text: responseText || "...",
|
||||||
sender: 'ai',
|
sender: 'ai',
|
||||||
timestamp: new Date(),
|
timestamp: new Date(),
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
} else {
|
} else {
|
||||||
// Handle cases where the response format is unexpected or empty
|
|
||||||
console.warn("[ChatScreen] Received invalid or empty responses array:", response.data);
|
console.warn("[ChatScreen] Received invalid or empty responses array:", response.data);
|
||||||
aiResponses.push({
|
aiResponses.push({
|
||||||
id: Date.now().toString() + '-ai-fallback',
|
id: Date.now().toString() + '-ai-fallback',
|
||||||
@@ -92,7 +134,7 @@ const ChatScreen = () => {
|
|||||||
}
|
}
|
||||||
// --- End API Call ---
|
// --- End API Call ---
|
||||||
|
|
||||||
}, [inputText]); // Keep inputText as dependency
|
}, [inputText, isLoading, messages]); // Add isLoading and messages to dependency array
|
||||||
|
|
||||||
const handleKeyPress = (e: NativeSyntheticEvent<TextInputKeyPressEventData>) => {
|
const handleKeyPress = (e: NativeSyntheticEvent<TextInputKeyPressEventData>) => {
|
||||||
if (e.nativeEvent.key === 'Enter' && !(e.nativeEvent as any).shiftKey) {
|
if (e.nativeEvent.key === 'Enter' && !(e.nativeEvent as any).shiftKey) {
|
||||||
@@ -118,29 +160,44 @@ const ChatScreen = () => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
const styles = StyleSheet.create({
|
const styles = StyleSheet.create({
|
||||||
container: {
|
container: { // For SafeAreaView
|
||||||
flex: 1,
|
flex: 1,
|
||||||
backgroundColor: theme.colors.background,
|
backgroundColor: theme.colors.background,
|
||||||
},
|
},
|
||||||
listContainer: {
|
keyboardAvoidingContainer: { // Style for KAV
|
||||||
flex: 1,
|
flex: 1,
|
||||||
},
|
},
|
||||||
messageList: {
|
listContainer: { // Container for the list, should take up available space
|
||||||
|
flex: 1,
|
||||||
|
},
|
||||||
|
messageList: { // Padding for the list content itself
|
||||||
paddingHorizontal: 10,
|
paddingHorizontal: 10,
|
||||||
paddingVertical: 10,
|
paddingVertical: 10,
|
||||||
},
|
},
|
||||||
inputContainer: {
|
inputContainer: { // Input container should stick to the bottom
|
||||||
flexDirection: 'row',
|
flexDirection: 'row',
|
||||||
alignItems: 'center',
|
alignItems: 'center', // Align items vertically in the center
|
||||||
padding: 8,
|
paddingHorizontal: 8, // Add horizontal padding
|
||||||
|
paddingVertical: 8, // Add some vertical padding
|
||||||
borderTopWidth: StyleSheet.hairlineWidth,
|
borderTopWidth: StyleSheet.hairlineWidth,
|
||||||
borderTopColor: theme.colors.outlineVariant,
|
borderTopColor: theme.colors.outlineVariant,
|
||||||
backgroundColor: theme.colors.elevation.level2, // Slightly elevated background
|
backgroundColor: theme.colors.background, // Or theme.colors.surface
|
||||||
},
|
},
|
||||||
textInput: {
|
textInput: {
|
||||||
flex: 1,
|
flex: 1, // Take available horizontal space
|
||||||
marginRight: 8,
|
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: {
|
messageBubble: {
|
||||||
maxWidth: '80%',
|
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 (
|
return (
|
||||||
<SafeAreaView style={styles.container} edges={['bottom', 'left', 'right']}>
|
<SafeAreaView style={styles.container} edges={['bottom', 'left', 'right']}>
|
||||||
<KeyboardAvoidingView
|
<KeyboardAvoidingView
|
||||||
style={{ flex: 1 }}
|
style={styles.keyboardAvoidingContainer} // Use style with flex: 1
|
||||||
behavior={Platform.OS === "ios" ? "padding" : "height"}
|
// Use 'padding' for both iOS and Android
|
||||||
keyboardVerticalOffset={Platform.OS === "ios" ? 90 : 0} // Adjust as needed
|
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}>
|
<View style={styles.listContainer}>
|
||||||
<FlatList
|
<FlatList
|
||||||
ref={flatListRef}
|
ref={flatListRef}
|
||||||
data={messages}
|
data={messages}
|
||||||
renderItem={renderMessage}
|
renderItem={renderMessage}
|
||||||
keyExtractor={(item) => item.id}
|
keyExtractor={(item) => item.id}
|
||||||
contentContainerStyle={styles.messageList}
|
contentContainerStyle={styles.messageList} // Padding inside the scrollable content
|
||||||
onContentSizeChange={() => flatListRef.current?.scrollToEnd({ animated: false })} // Scroll on initial load/size change
|
onContentSizeChange={() => flatListRef.current?.scrollToEnd({ animated: false })}
|
||||||
onLayout={() => flatListRef.current?.scrollToEnd({ animated: false })} // Scroll on layout change
|
onLayout={() => flatListRef.current?.scrollToEnd({ animated: false })}
|
||||||
/>
|
/>
|
||||||
</View>
|
</View>
|
||||||
|
|
||||||
|
{/* Input container is last, outside the list's flex */}
|
||||||
<View style={styles.inputContainer}>
|
<View style={styles.inputContainer}>
|
||||||
<TextInput
|
<TextInput
|
||||||
style={styles.textInput}
|
style={styles.textInput}
|
||||||
value={inputText}
|
value={inputText}
|
||||||
onChangeText={setInputText}
|
onChangeText={setInputText}
|
||||||
placeholder="Type your message..."
|
placeholder="Type your message..."
|
||||||
mode="outlined" // Or "flat"
|
mode="outlined" // Keep outlined or flat as preferred
|
||||||
multiline
|
multiline
|
||||||
onKeyPress={handleKeyPress}
|
onKeyPress={handleKeyPress}
|
||||||
blurOnSubmit={false}
|
blurOnSubmit={false} // Keep false for multiline + send button
|
||||||
disabled={isLoading}
|
disabled={isLoading}
|
||||||
|
dense // Try making the input slightly smaller vertically
|
||||||
/>
|
/>
|
||||||
<IconButton
|
<IconButton
|
||||||
icon="send"
|
icon="send"
|
||||||
@@ -205,6 +280,7 @@ const ChatScreen = () => {
|
|||||||
mode="contained"
|
mode="contained"
|
||||||
iconColor={theme.colors.onPrimary}
|
iconColor={theme.colors.onPrimary}
|
||||||
containerColor={theme.colors.primary}
|
containerColor={theme.colors.primary}
|
||||||
|
style={styles.sendButton} // Apply style for alignment
|
||||||
/>
|
/>
|
||||||
</View>
|
</View>
|
||||||
</KeyboardAvoidingView>
|
</KeyboardAvoidingView>
|
||||||
|
|||||||
@@ -15,7 +15,7 @@ export type WebContentStackParamList = {
|
|||||||
Chat: undefined;
|
Chat: undefined;
|
||||||
Calendar: undefined;
|
Calendar: undefined;
|
||||||
Profile: 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)
|
// Screens managed by the Root Navigator (Auth vs App)
|
||||||
@@ -30,5 +30,11 @@ export type AuthStackParamList = {
|
|||||||
// Example: SignUp: undefined; ForgotPassword: undefined;
|
// 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
|
// Type for the ref used in WebAppLayout
|
||||||
export type WebContentNavigationProp = NavigationContainerRef<WebContentStackParamList>;
|
export type WebContentNavigationProp = NavigationContainerRef<WebContentStackParamList>;
|
||||||
Reference in New Issue
Block a user