LynCareOS — Care calendar composition
Version: 1.9
Last Updated: 2026-08-05 17:38:42
Status: Canonical — file map and ownership for the care calendar surface
Owner: Frontend
Location: docs/02 - ARCHITECTURE_DESIGN/15-CARE-CALENDAR-COMPOSITION.md
Visual language lives in 03-DESIGN-SYSTEM.md.
Stack and capture patterns live in 14-FRONTEND-PRESENTATION-STACK.md.
This document is the file map for the care calendar: what each module owns and why the boundaries fall where they do.
1. Why this document exists
Section titled “1. Why this document exists”The care calendar and the homepage are the two surfaces carers use most. The calendar had grown into two files that could not be reviewed safely:
| File | Before | After |
|---|---|---|
pages/calendar/CalendarView.tsx | 1,167 lines | 306 lines |
components/calendar/AddShiftFormView.tsx | 1,226 lines | 160 lines |
Both breached the limits in .cursor/rules/rules.mdc (300 lines per component, 150 per function) and both are about to take the focus-date and care-module work described in docs/superpowers/specs/2026-07-31-care-calendar-focus-date-and-care-module-tasks-design.md. Splitting first means that feature lands as additions to small files rather than edits to unreviewable ones.
The refactor was behaviour-preserving. The one deliberate behaviour change is recorded in §5.
2. Layering rule for this surface
Section titled “2. Layering rule for this surface”Three rules govern where new calendar code goes:
- Pure decisions go to
lib/. Anything expressible as “given these numbers, what should happen?” belongs in a pure module with tests, not inside an event handler. - Behaviour goes to a hook. State, effects, and API mutations live in
use*hooks that accept their dependencies as parameters. - Everything else is presentational. Section components receive data and callbacks and hold no server state.
DOM refs are created by the component, not returned from a hook. Returning a ref inside an object makes every property read off that object a render-time ref access, which the react-hooks/refs lint rule rejects. useCalendarDayGestures therefore takes gridRef and pageRef as options.
3. Calendar page — frontend/src/pages/calendar/
Section titled “3. Calendar page — frontend/src/pages/calendar/”| File | Owns |
|---|---|
CalendarView.tsx | Composition root. Month shown, dates the day panel is open for, deep-link handling. Holds no data fetching or gesture logic. |
useCalendarData.ts | Loads shifts, members, and appointments for one patient-month. Owns the three reload triggers (patient/month change, tab visibility, carer colour change) so no caller can forget one. |
useCalendarDayGestures.ts | Gesture state and listener binding: mouse drag, long-press timer, and the synthetic-click guard. Decisions come from calendarGestureRules, the touch branch from calendarTouchHandlers, month swipe from useCalendarMonthSwipe. |
useCalendarMonthSwipe.ts | Horizontal swipe on page chrome changes month. Split out because it shares no state with the day gestures and must never fire on the grid, where a horizontal drag selects a range. |
useCalendarFocusDay.ts | The focus date and everything below the grid for it: care-module action pills, the day’s tasks, and the four mutations against them. Focus date is session state — see §6. |
useCalendarSectionScroll.ts | Filter pills as scroll anchors, plus the trailing spacer that lets the last section reach the top of the viewport. |
useCalendarItemActions.ts | Delete mutations and “open this row in the day panel” for the month lists, with the arranged-by permission rule applied once. |
CalendarFilterDock.tsx | Sticky page title and the section-anchor pills. |
CalendarFocusDayPanel.tsx | The panel under the grid: focus-date heading, “Schedule care” button, task list with completion and delete, and the free-text add field. |
CalendarActionPills.tsx | The care-module action row inside that panel. Split out so the pill’s applied / suggested / busy states are readable on their own. |
CalendarMonthGrid.tsx | Month header, weekday row, date grid, carer legend, usage hint. Uses useMatchMedia(CALENDAR_DAY_CELL_COMPACT_MODULE_ICONS_QUERY) (below lg) to collapse module icons on phone and tablet. |
CalendarMonthSections.tsx | Wiring layer for the four month lists and the scroll spacer. Holds no state; exists so CalendarView stays at composition size. |
CalendarNoPatient.tsx | The empty state shown before anyone is selected. |
CalendarDayCell.tsx | One date cell: activity icons, date number, full-day and partial shift pills, focus ring, and the keyboard contract. |
CalendarListRow.tsx | A selectable month-list row. Exists so the Enter/Space keyboard contract is written once rather than three times. |
CalendarAppointmentsSection.tsx | The month’s appointments. |
CalendarTasksSection.tsx | The month’s care tasks. |
CalendarHandoversSection.tsx | The month’s handover notes. |
CalendarDayPanel.tsx | The bottom sheet wrapper — title shape and per-selection remount of the form. |
CalendarFamilyHelpOverlays.tsx | Family-help board, detail sheet, and new-request modal, grouped because one hook drives all three. |
Supporting pure modules:
| File | Owns |
|---|---|
lib/calendarGestureRules.ts | isVerticalScrollIntent, monthSwipeDirection, exceedsLongPressTolerance, and the gesture thresholds including LONG_PRESS_MS. Tested in test/lib/calendarGestureRules.test.ts. |
lib/calendarTouchHandlers.ts | createCalendarTouchHandlers — the four touch listeners as a factory over an explicit context, so the branching between tap, hold, drag, and scroll reads in one place instead of inside a long useEffect. |
lib/types/care.ts | Shift and appointment types. Re-exports DatedCareTask, CalendarAction, CalendarActionsDay from api.contracts.ts — these are generated from the backend response_model=, never hand-written (see §6, “API contract and generated types”). |
lib/calendarPageConstants.ts | Filter options, shared list/section class strings, scroll maths. CAL_DAY_MODULE_ICON_LIMIT (5) on desktop; CALENDAR_DAY_CELL_COMPACT_MODULE_ICONS_QUERY (max-width 1023px) for a single module icon on phone/tablet. |
lib/calendarViewHelpers.ts | Month layout, activity indicators, month row builders. Pre-existing. |
4. Day panel — frontend/src/components/calendar/addShift/
Section titled “4. Day panel — frontend/src/components/calendar/addShift/”AddShiftFormView.tsx is the container. It covers four flows a carer moves between without leaving the sheet: review existing shifts, edit arranged items, add shifts, add an appointment.
| File | Owns |
|---|---|
useShiftDraft.ts | The add-shift form and its two save paths — patch the lone existing shift, or create one shift per slot per date. |
useAppointmentDraft.ts | Appointment fields shared by create and inline edit, with both save paths. |
useInlineTextEditor.ts | Generic buffer + busy + error for one inline field. Used by both the care task and handover editors. The persist function is passed to submit because the target row is only known at tap time. |
useDayActivityEditing.ts | Which arranged item is open, delete handling, and the listOpen path that lands a carer directly in edit mode from a month list row. |
addShiftConstants.ts | Named limits, the oncology type list, shared class strings, and expandByRecurrence. |
DayShiftsList.tsx | Shifts already rostered on the day, with inline remove. |
DayActivityCard.tsx | Shared card shell for an editable arranged item, including the permission treatment. |
DayActivitySection.tsx | The three item types mapped onto DayActivityCard. |
ShiftRangeSummary.tsx | “N shifts selected” confirmation for a range or repeat series. |
ShiftScheduleFields.tsx | Carer, time slot, and location. |
ShiftRecurrenceControls.tsx | Repeat cadence and occurrence count. |
ShiftNotesFields.tsx | Handover, wellbeing note, and care task inputs. |
ShiftSaveBar.tsx | Sticky Save, its emphasis states, and the hint that names why Save is blocked. |
AddAppointmentForm.tsx | Create an appointment on the open day. |
5. Interaction model — tap focuses, hold schedules
Section titled “5. Interaction model — tap focuses, hold schedules”The calendar stays a rostering tool. Adding a care-module task must not cost more taps than it did before, and must never risk creating a shift by accident. That gives two gestures on a date cell:
| Gesture | Result | Why |
|---|---|---|
| Tap | The date becomes the focus date. The panel below the grid shows its action pills and tasks. No overlay. | Cheap and reversible — one touch to look at a day. |
Hold (LONG_PRESS_MS, 450ms) | The scheduling sheet opens for that date, exactly as a tap used to. | Allocating a carer is deliberate and earns the extra half second. |
| Drag across dates | The scheduling sheet opens for the range. | Unchanged. |
| Tap a carer pill inside a cell | The scheduling sheet opens for that date. | A carer pill is about staffing, so it skips the focus step. |
| Enter / Space on a cell | Focus the date. | Keyboard equivalent of tap. |
| Shift + Enter / Space | Open the scheduling sheet. | A keyboard cannot long-press; this is the stand-in. |
LONG_PRESS_MS sits above the platform tap threshold (~300ms) so an ordinary tap never trips it, and below 600ms so the carer does not assume nothing happened. A press that drifts more than LONG_PRESS_MOVE_TOLERANCE_PX becomes a range drag instead. Both thresholds are asserted in calendarGestureRules.test.ts.
Focus date is session state
Section titled “Focus date is session state”Focus resets to today on every load. It is not a URL parameter and not a stored preference: a carer returning after three days does not want to land on last Tuesday, and a stale focus date would quietly misdirect a task.
6. Care-module actions on the calendar
Section titled “6. Care-module actions on the calendar”Manifest contract
Section titled “Manifest contract”A care module publishes calendar_actions in backend/care_modules/manifests/<slug>.json. Each entry is a named bundle of structured tasks (not bare title strings):
{ "id": "infusion", "label": "Infusion day", "icon": "iv", "suggested_by_appointment_types": ["iv_infusion", "labs"], "tasks": [ { "id": "blood_tests", "title": "Confirm blood tests are done", "prompt": "Have blood tests been done?", "response_kind": "yes_no" }, { "id": "transport", "title": "Arrange driver / transport", "prompt": "Is driver or transport arranged?", "response_kind": "arrangement" } ]}-
promptis what the focus-day row displays;titleremains the stable label for audits and exports. -
response_kindselects a fixed button set frombackend/care_modules/calendar_task_responses.py(mirrored infrontend/src/lib/calendarModuleTaskResponses.ts):yes_no,symptom_check(No is the favourable answer),medication(Taken / Not taken / Not applicable),arrangement(Arranged / Not yet arranged),done_pending,recorded,comfort,line_check,flush_status. -
Legacy manifest entries that still list plain strings normalize to
done_pendingon apply. -
Answers persist on
care_tasksvia migration V027 (response_code,response_recorded_at,response_recorded_by, plussource_task_id/task_prompt/response_kind).PATCH /api/care-tasks/{id}with{ "response_code": "..." }validates against the row’s kind and stamps time;completedfollows the option’saffirmativeflag for calendar indicators. -
Focus-day module rows use the same
CAL_LIST_ROWlist styling as appointments, family help, and general care tasks (CalendarModuleDayTasks.tsx); general tasks on that day still use a checkbox. -
iconis a key inCARE_PROFILE_ICON_MAP(care-modules/shared/careProfileVisual.ts), not a Lucide component name. -
suggested_by_appointment_typeshighlights the pill when a matching appointment sits on the date. Suggested never auto-applies. The family always taps to confirm — inferring the day type from the calendar is precisely what the retired day-type mechanism got wrong. -
A module with no
calendar_actionskey simply has no pills. That is a valid state, not an error.
Modules shipping today: cancer_at_home (infusion, tablet, clinic, rest, line care) and breathing_difficulties (oxygen check, respiratory clinic).
Backend files
Section titled “Backend files”| File | Owns |
|---|---|
backend/repositories/care_tasks.py | Date-scoped task SQL (V026 range/apply; V027 structured responses on insert/read). Shift-attached task SQL stays in repositories/care_shifts.py. |
backend/care_modules/services/calendar_actions_service.py | Manifest lookup, decorating actions with applied / suggested, apply, undo, and manual dated-task creation. Kept out of board_service so the calendar inherits none of the cancer board’s oncology assumptions. |
backend/care_modules/routers/calendar_actions.py | The four action endpoints. Behind require_care_module_access — the pills surface care-module content, so they follow the preview allow-list (see doc 20 §6.3). |
backend/routers/care_tasks.py | Date-scoped task read and create. Not gated: once written, an action’s output is an ordinary care task any carer with patient access can see. |
Task titles are only ever read from the manifest, never from the request body — a client posting an unknown action_id gets a 404 rather than writing arbitrary text.
Idempotency and undo
Section titled “Idempotency and undo”Applying an action twice inserts nothing the second time. uq_care_tasks_module_action (V026) covers (patient_id, date, source_care_profile_slug, source_action_id, title) for non-deleted rows, and the insert uses ON CONFLICT DO NOTHING. Mistaps are expected on a touch calendar, so undo is a first-class path: DELETE soft-deletes only the tasks that action created, only on that date.
Every apply and undo writes an audit row per task, in the same transaction as the mutation.
Covered by backend/tests/test_calendar_actions.py and test_calendar_task_responses.py: pills listed, re-tap does not duplicate, tasks land with shift_id IS NULL, undo is scoped to one action, manual tasks need no shift, structured response_code PATCH persists, and another tenant cannot read the day.
API contract and generated types
Section titled “API contract and generated types”All six endpoints carry response_model= (DatedCareTask, DatedCareTaskList, CalendarActionsDay, CalendarActionsRange in backend/models.py), so the shapes reach openapi/openapi.json and the frontend generates them.
This is load-bearing, not housekeeping. These endpoints originally returned bare dicts, which kept them out of OpenAPI and forced lib/types/care.ts to hand-write DatedCareTask. That hand-written copy declared completed as 0 | 1 against a Postgres BOOLEAN, so task.completed === 1 was never true and CalendarFocusDayPanel rendered every completed task as outstanding — writes saved correctly, but the tick never appeared and the task could not be reopened. Nothing caught it: check:types-drift only compares generated output against OpenAPI, and === 1 type-checks perfectly against a 0 | 1 declaration.
Anything added here follows the same path — set response_model=, run python backend/scripts/export_openapi.py, then npm run generate:types, and alias in api.contracts.ts. Do not reintroduce a hand-written interface for a shape the API already returns.
CalendarFocusDayPanel.test.tsx pins the boolean contract at the component boundary.
7. Behaviour change during the refactor
Section titled “7. Behaviour change during the refactor”Inline appointment edit no longer clears the oncology type.
Opening an appointment row with the pencil used to populate time, title, and address but not appointment_type. Saving then sent appointment_type: null built from whatever stale value the shared draft held, silently clearing the type on an appointment the carer only meant to rename. Both entry points — the pencil and the month-list deep link — now go through useAppointmentDraft.populate, which loads all four fields.
No migration is needed; types already cleared this way must be re-entered by hand.
8. Known follow-ups
Section titled “8. Known follow-ups”| Item | Where | Status |
|---|---|---|
ONCOLOGY_APPT_TYPES is hardcoded for cancer_at_home and must move to a care-module manifest declaration | addShiftConstants.ts, marked TODO(D-CAL-MODULE) | Open |
CareActionsForTodayBlock — cancer-specific read-only strip | Deleted; replaced by CalendarFocusDayPanel | Done |
| Day cells had no keyboard equivalent for the scheduling gesture | CalendarDayCell.tsx now exposes role="button", tabIndex, and Shift+Enter | Done |
The cancer board’s derived day type (today_day_types, suggested_day_type_from_calendar, the amber calendar_day alert) is superseded by action pills and must be removed | cancer_hub_service.py, cancer_defaults.py, CareBoardPage.tsx | Open — separate pass, see below |
| Month grid does not yet mark which dates have applied actions | CalendarMonthGrid.tsx; wired calendar-actions/range + careModuleDayIconKeys (2026-07-31) | Done |
Why day-type removal is a separate pass
Section titled “Why day-type removal is a separate pass”Day type is threaded through the cancer hub service, its defaults, the board visual layer, the settings patch endpoint, the dashboard panel, and the board page. Removing it is a cancer-board change, not a calendar change, and it needs the board exercised end to end to verify. Doing it in the same pass as this feature would have made both unreviewable. The calendar no longer reads day type, so the two are already decoupled.
9. Document history
Section titled “9. Document history”| Version | Date | Change |
|---|---|---|
| 1.8 | 2026-07-31 22:05:51 | Module calendar tasks: manifest task objects, response kinds + V027 persistence, focus-day button UI aligned to CAL_LIST_ROW. |
| 1.7 | 2026-07-31 21:57:05 | Month-grid icons: single module icon below lg (phone/tablet); up to five per-action icons on desktop. |
| 1.6 | 2026-07-31 21:57:00 | Same breakpoint documented in constants (CALENDAR_DAY_CELL_COMPACT_MODULE_ICONS_QUERY). |
| 1.3 | 2026-07-31 21:53:15 | Month grid shows care-module action icons via calendar-actions/range and careModuleDayIconKeys. |
| 1.2 | 2026-07-31 16:33:39 | Fixed task checkboxes never ticking: DatedCareTask.completed was hand-typed `0 |
| 1.1 | 2026-07-31 15:27:24 | Added focus-date interaction model, care-module calendar_actions contract, and the backend files behind it. Split useCalendarDayGestures and CalendarView again to hold the 300-line and 150-line limits. |
| 1.0 | 2026-07-31 14:44:34 | Created after splitting CalendarView.tsx and AddShiftFormView.tsx. |