Skip to content

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.


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:

FileBeforeAfter
pages/calendar/CalendarView.tsx1,167 lines306 lines
components/calendar/AddShiftFormView.tsx1,226 lines160 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.


CalendarView.tsx

composition root

Hooks

state and behaviour

Section components

presentation

lib/calendarGestureRules.ts

pure decisions

lib/calendarPageConstants.ts

shared class strings

Three rules govern where new calendar code goes:

  1. 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.
  2. Behaviour goes to a hook. State, effects, and API mutations live in use* hooks that accept their dependencies as parameters.
  3. 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/”
FileOwns
CalendarView.tsxComposition root. Month shown, dates the day panel is open for, deep-link handling. Holds no data fetching or gesture logic.
useCalendarData.tsLoads 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.tsGesture 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.tsHorizontal 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.tsThe 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.tsFilter pills as scroll anchors, plus the trailing spacer that lets the last section reach the top of the viewport.
useCalendarItemActions.tsDelete mutations and “open this row in the day panel” for the month lists, with the arranged-by permission rule applied once.
CalendarFilterDock.tsxSticky page title and the section-anchor pills.
CalendarFocusDayPanel.tsxThe panel under the grid: focus-date heading, “Schedule care” button, task list with completion and delete, and the free-text add field.
CalendarActionPills.tsxThe care-module action row inside that panel. Split out so the pill’s applied / suggested / busy states are readable on their own.
CalendarMonthGrid.tsxMonth 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.tsxWiring layer for the four month lists and the scroll spacer. Holds no state; exists so CalendarView stays at composition size.
CalendarNoPatient.tsxThe empty state shown before anyone is selected.
CalendarDayCell.tsxOne date cell: activity icons, date number, full-day and partial shift pills, focus ring, and the keyboard contract.
CalendarListRow.tsxA selectable month-list row. Exists so the Enter/Space keyboard contract is written once rather than three times.
CalendarAppointmentsSection.tsxThe month’s appointments.
CalendarTasksSection.tsxThe month’s care tasks.
CalendarHandoversSection.tsxThe month’s handover notes.
CalendarDayPanel.tsxThe bottom sheet wrapper — title shape and per-selection remount of the form.
CalendarFamilyHelpOverlays.tsxFamily-help board, detail sheet, and new-request modal, grouped because one hook drives all three.

Supporting pure modules:

FileOwns
lib/calendarGestureRules.tsisVerticalScrollIntent, monthSwipeDirection, exceedsLongPressTolerance, and the gesture thresholds including LONG_PRESS_MS. Tested in test/lib/calendarGestureRules.test.ts.
lib/calendarTouchHandlers.tscreateCalendarTouchHandlers — 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.tsShift 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.tsFilter 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.tsMonth 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.

FileOwns
useShiftDraft.tsThe add-shift form and its two save paths — patch the lone existing shift, or create one shift per slot per date.
useAppointmentDraft.tsAppointment fields shared by create and inline edit, with both save paths.
useInlineTextEditor.tsGeneric 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.tsWhich arranged item is open, delete handling, and the listOpen path that lands a carer directly in edit mode from a month list row.
addShiftConstants.tsNamed limits, the oncology type list, shared class strings, and expandByRecurrence.
DayShiftsList.tsxShifts already rostered on the day, with inline remove.
DayActivityCard.tsxShared card shell for an editable arranged item, including the permission treatment.
DayActivitySection.tsxThe three item types mapped onto DayActivityCard.
ShiftRangeSummary.tsx“N shifts selected” confirmation for a range or repeat series.
ShiftScheduleFields.tsxCarer, time slot, and location.
ShiftRecurrenceControls.tsxRepeat cadence and occurrence count.
ShiftNotesFields.tsxHandover, wellbeing note, and care task inputs.
ShiftSaveBar.tsxSticky Save, its emphasis states, and the hint that names why Save is blocked.
AddAppointmentForm.tsxCreate 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:

GestureResultWhy
TapThe 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 datesThe scheduling sheet opens for the range.Unchanged.
Tap a carer pill inside a cellThe scheduling sheet opens for that date.A carer pill is about staffing, so it skips the focus step.
Enter / Space on a cellFocus the date.Keyboard equivalent of tap.
Shift + Enter / SpaceOpen 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 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.


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"
}
]
}
  • prompt is what the focus-day row displays; title remains the stable label for audits and exports.

  • response_kind selects a fixed button set from backend/care_modules/calendar_task_responses.py (mirrored in frontend/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_pending on apply.

  • Answers persist on care_tasks via migration V027 (response_code, response_recorded_at, response_recorded_by, plus source_task_id / task_prompt / response_kind). PATCH /api/care-tasks/{id} with { "response_code": "..." } validates against the row’s kind and stamps time; completed follows the option’s affirmative flag for calendar indicators.

  • Focus-day module rows use the same CAL_LIST_ROW list styling as appointments, family help, and general care tasks (CalendarModuleDayTasks.tsx); general tasks on that day still use a checkbox.

  • icon is a key in CARE_PROFILE_ICON_MAP (care-modules/shared/careProfileVisual.ts), not a Lucide component name.

  • suggested_by_appointment_types highlights 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_actions key 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).

FileOwns
backend/repositories/care_tasks.pyDate-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.pyManifest 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.pyThe 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.pyDate-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.

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.

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.


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.


ItemWhereStatus
ONCOLOGY_APPT_TYPES is hardcoded for cancer_at_home and must move to a care-module manifest declarationaddShiftConstants.ts, marked TODO(D-CAL-MODULE)Open
CareActionsForTodayBlock — cancer-specific read-only stripDeleted; replaced by CalendarFocusDayPanelDone
Day cells had no keyboard equivalent for the scheduling gestureCalendarDayCell.tsx now exposes role="button", tabIndex, and Shift+EnterDone
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 removedcancer_hub_service.py, cancer_defaults.py, CareBoardPage.tsxOpen — separate pass, see below
Month grid does not yet mark which dates have applied actionsCalendarMonthGrid.tsx; wired calendar-actions/range + careModuleDayIconKeys (2026-07-31)Done

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.


VersionDateChange
1.82026-07-31 22:05:51Module calendar tasks: manifest task objects, response kinds + V027 persistence, focus-day button UI aligned to CAL_LIST_ROW.
1.72026-07-31 21:57:05Month-grid icons: single module icon below lg (phone/tablet); up to five per-action icons on desktop.
1.62026-07-31 21:57:00Same breakpoint documented in constants (CALENDAR_DAY_CELL_COMPACT_MODULE_ICONS_QUERY).
1.32026-07-31 21:53:15Month grid shows care-module action icons via calendar-actions/range and careModuleDayIconKeys.
1.22026-07-31 16:33:39Fixed task checkboxes never ticking: DatedCareTask.completed was hand-typed `0
1.12026-07-31 15:27:24Added 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.02026-07-31 14:44:34Created after splitting CalendarView.tsx and AddShiftFormView.tsx.