Frontend architecture¶
How the React SPA is put together: the tech stack, routing without a router, the Zustand stores and their persistence, the API client and transform layer, the Gantt and Kanban internals, the hooks catalog, the utilities worth knowing, and the What-If sandbox. It was moved verbatim out of the repo-root CLAUDE.md, which keeps the frontend conventions; the design tokens and shared components are in UI_GUIDELINES.md.
Code described: frontend/src/ — main.tsx, App.tsx, stores/, api/, components/gantt/, components/views/, hooks/, utils/, contexts/.
Frontend Architecture¶
Tech stack¶
React 18 + TypeScript 5.6, Vite 7, Vitest 4, Zustand 5, date-fns 4, react-day-picker 10 (the date fields' calendar, themed by setting its --rdp-* properties from app tokens in DateRangeField.module.css), CSS Modules; in the lazy Dashboards chunk only: ECharts 6.1.0 (tree-shaken echarts/core, canvas renderer, themed from the CSS tokens with chart.setTheme() on data-theme changes — charts/echartsTheme.ts) and react-grid-layout 2.3.0 (Responsive + useContainerWidth({measureBeforeMount: true}); rowHeight / margin are top-level props, there is no gridConfig; container breakpoints {lg: 1000, md: 700, sm: 0}, cols 12 / 8 / 4) with react-resizable 3.2.0, all pinned exactly. All data flows through the Zustand stores — there is no query library (TanStack Query was installed but unused and has been removed; don't re-add it) and no router package — react-router-dom was removed as unused; there is no route tree.
Routing without a router¶
src/main.tsxboots the theme and wires the API client (configureApiClient): What-If check + queue fromwhatIfStore, andonUnauthorized: expireSession. (The legacyrd_*storage migration was removed.)src/App.tsxrenders by branching:window.location.pathnameexactly/adminor under/admin/(isAdminPath) →AdminApp(a fully separate admin-portal app:AdminLoginScreen/AdminDashboardwith tenants/organizations/admins/stats tabs); otherwiseTenantApp: auth state decidesLoginScreenvs the main app, withLoadingScreenduring the initial load andLoadErrorScreen(Retry) if it failed, thenWebSocketProvider→MainLayout+ModalContainer+ContextMenuContainer+ActivityFeed.TenantAppalso owns thewhat-if-modebody class.- In-app navigation =
viewStore.currentView(gantt|kanban|work|dashboards|staff|equipment|crosssite|archived) switched by the sidebar; views are state, not URLs.useAllowedViews()decides which ones the sidebar lists (VIEW_PERMISSIONS:views.*keys; Gantt always, My Work for anyone signed in) and disables Cross-site while only one site is visible;MainLayoutfalls back toganttwhen the current view is no longer allowed and re-selects the lowest-id visible site when the current one is gone.setCurrentViewrefuses every view butganttwhile What-If is active (see What-If Mode). The sidebar (Navigation) lists Gantt, Kanban, My Work, Staff, Equipment, Dashboards, Cross-site, Archived (its ownNAV_ITEMSorder); the Dashboards row has a chevron (aria-expanded,viewStore.sidebarDashboardsExpanded) over a nested list ofdashboardStore.dashboards(store order; loaded byrefreshList()on mount while the entry shows and the list is not loaded) — a click goes throughleaveViewThen, thensetCurrentView('dashboards')+open(id); the open one carriesaria-current; disabled like the row (What-If); hidden in the icons-only sidebar. Another dashboard opening under the builder's draft discards it (useDashboardEditor, after the leave guard agreed). - All administration is one Settings hub (
components/settings/), a full-size sharedModalwith a grouped section list. The sidebarAdminSectionhas a single Settings entry, shown whencanOpenSettings(user)(any section gated by a held key, orsystem.audit_log, whose log has no section of its own). Sections come from theSETTINGS_SECTIONSregistry, each with apermission(a key, any-of keys, ornull) mirroring the backend: Generalnull(per-browser theme for everyone; instance-wide settings withsettings.general), Features & defaultssettings.general(DefaultsPanel: the Settings keys), Rolesroles.manage, Sitessites.manageorsites.export, Teamsteams.manage, Bank holidaysbank_holidays.manage, Company eventscompany_events.manage, Usersusers.view, Skillsskills.manage, Absence typesabsence_types.manage, Equipmentequipment.manage, Equipment typesequipment_types.manage, Predefined phasespredefined_phases.manage, Project fieldsproject_fields.manage(ProjectFieldsPanel: one list on a shared six-column CSS grid (--pf-cols: Field, Label / type, Format, In project dialog, In Gantt details, actions) — the built-in fields with their labels and Volume's Format, the non-field Gantt rows, the custom fields with drag reorder —, per-dropdown items editor with colour and site/team scope; every setting applies at once throughuseSettingWriter(components/settings/useSettingWriter.ts: optimistic store write, one PUT per key with the newest value queued, the server's value re-asserted, failure → the panel's Notice or a flash after unmount plus a settings reload;pending/savedAtfeed the "Saving… / Saved" status), hiding a field also removes it fromproject_tooltip_rows; beside the listProjectFieldsPreview(panels/ProjectFieldsPreview.tsx, a container query puts it there, sticky) shows a sample project (utils/projectFieldsPreview.ts) as the Shift-hover details or as the dialog's fields), Tagstags.manage(flat list), SSOsettings.sso. Settings → Roles has two tabs: the role list /RoleFormwith thePermissionMatrix, andApprovalPoliciesForm. The Audit log (2.4.0,panels/audit-log/AuditLogPanel.tsx) has no section:GeneralPanelshows an Audit log row first in Data management tosystem.audit_logholders (also withoutsettings.general, under Appearance), with the retention as a hint ("Kept 365 days" / "Kept indefinitely", the liveinstanceSettingsvalue) and a ghost Open audit logButton; clicking it swaps the panel to a sub-view — an "Audit log" header with a ghost Back to GeneralButton(BackIcon, the Users edit-form pattern), then the lazily loadedAuditLogPanel— while the General form stays mounted underhidden, so its unsaved edits survive and keep the hub'sonDirtyChangeguard armed; the sub-view isGeneralPanelstate (no URL, no store), opens scrolled to the top with Back focused, returns focus to Open audit log, and the hub's close unmounts it. The panel is read-only and keeps its state locally (nothing else reads the log):PanelToolbarwith the "{start}–{end} of {total}" count, the retention chip (the liveaudit_log_retention_daysofappStore.instanceSettings, edited in General → Data management with the form's Save button, notuseSettingWriter), Refresh and Export CSV (auditLogApi.exportCsv→downloadFile, same filters, the list reloads after it because the export is itself recorded); a wrapping filter bar — Search and IP address debounced 300 ms (a change of surrounding spaces only is none;maxLength200 / 45, the server's caps), Category and OutcomeFilterChips, Action (SearchableSelectoverGET /audit-log/actions, index ↔ key, raw key as the hint) and Actor (SearchableSelect: the accounts —appStore.users, orGET /userswithusers.view, since nothing else fills that slice — plus the actors of the rows held), From / ToDateFields, Clear filters — whose every change goes back to page 1; the table (eight fixed columns —table-layout: fixed, Actor / Account / Target / IP cut with an ellipsis and their full text intitle, When throughformatDateTime, the origin left to the dialog — so it fits the hub at 1440 px; a row click, or the When cell'sButton(Enter / Space,aria-haspopup="dialog"), opensAuditLogEntryModal, "Entry detail": the changes as Field / Before / After,"***"as a Secret value chip,{changed, length}as "changed (n characters)", the context as a definition list); a "Per page"Select(25 / 50 / 100 / 200) and the sharedPagination.auditFilters.tsis the one param builder (drops empty filters);auditDetails.tsreadsdetails, targets and values; the labels come fromutils/auditLabels.ts. A request counter drops an overtaken page. Two shared components came with it:components/common/FilterChips(arole="group"ofaria-pressedchips,{label, options, value, onChange}; lifted out ofWorkView, whose filters import it) andcomponents/common/Pagination(anav"Pagination" of icon-only ghostButtons First / Previous / Next / Last around "Page {n} of {m}", disabled at the ends). Add new admin UI as a registry entry +…Panelcomponent (no<Modal>wrapper), not as a new sidebar item or standalone modal. The General panel reports unsaved changes to the hub (onDirtyChange) so switching section/closing asks first. Custom columns stay in the Gantt project panel. Self-service time off is My absences (MyAbsencesModal, user menu). - The tenant prefix
/t/{slug}comes from the URL:getTenantPrefix()inclient.tsprepends it to every/api/call. Deep links work because FastAPI's catch-all (prod) ortenantSpaPlugin(dev) serveindex.htmlfor/t/*paths.
Zustand stores (src/stores/)¶
| Store | Persisted | Purpose |
|---|---|---|
appStore |
only _persistedSiteId |
Domain data (sites, projects, staff, equipment, blocks, vacations, absence types, holidays+date Sets, events + derived closureIndex (built in setCompanyEvents), users, skills, tags, projectFields (fields with their items, loaded with the initial data), teams (every site, inactive included), roles and approvalPolicies (loaded on first use by useRoles / useApprovalPolicies, not persisted), instance settings), auth state, current site/user (with its permissions), critical-path state. Site switch clears undo history. Exports only non-array selectors (selectStaffSiteIds, selectStaffTeamIds, selectTeamSiteById, selectAbsenceTypesById, selectCanManageOthersAbsences) — array selectors were removed because they re-render forever under Zustand 5 |
viewStore |
yes | View mode (week/month/quarter/year) + a single cellWidth (per-mode defaults applied on mode switch, then freely zoomed — widths are not remembered per mode), current view, current date (memory-only), resource tab, expansion Sets (persisted: projects/phases/subphases; session-only: staff/equipment/bank-holidays, and collapsedStaffGroups — the collapsed overview rows, keys "<level>:<cardId>:<staffId>", so the default is expanded; toggleStaffGroup, cleared by collapseAll / expandAll, in neither partialize nor merge), level-based expand/collapse, scroll position, panel collapse flags, overview toggles (staff/equipment — mutually exclusive), teamFilters (header team filter {teamIds, noTeam} per tenant + site, same siteKey keying, absent = Whole site, sanitised on rehydrate and listed in merge), projectFilters (the Filter {optionIds, noneFieldIds, tagIds} — OR within a field, AND across fields, tags one more bucket — keyed "<tenant slug>:<site id>" via siteKey() in utils/tags.ts (tagFilterKey is its alias) — the storage key is per origin, so tenants must not share entries; persisted, stale ids pruned when applied), ganttGrouping (project field id) + collapsedGanttSections (field-<item id>/none keys) for the Gantt "Group by", and ganttColorBy (project field id or 'tags') for the Gantt "Colour by" (independent of Group by), same siteKey keying and rehydrate sanitising (sanitizeProjectFilters / sanitizeSiteFieldIds / sanitizeSiteColorBy / sanitizeCollapsedGanttSections), not cleared on logout. Persist version 2 (VIEW_STORE_VERSION): migrateViewState drops a version-0 payload's tagFilters, ganttGrouping, ganttColorBy and collapsedGanttSections once (2.0.0 — tag-group ids could collide with field ids) and maps a v0/v1 currentView: 'todos' to 'work'; Kanban board prefs kanbanProjectId, kanbanGrouping (none/project/phase/assignee/customColumn) + kanbanGroupingColumnId, kanbanMyTodoOnly (persisted); lastDashboardId (Record<tenantKey, number | null>, the last opened dashboard per tenant, persisted, sanitised by sanitizeLastDashboardIds); sidebarDashboardsExpanded (the sidebar's dashboards list shown, default true, toggleSidebarDashboards, persisted, non-booleans ignored in merge) |
uiStore |
no | Active modal + editing context, Settings hub state (openSettings(section?, intent?) → activeModal: 'settingsHub' + settingsSection + settingsIntent view/add/edit; legacy modal keys settings/manageSites/siteManagement/site/userManagement/manageEquipment/predefinedPhases/ssoConfig/bankHoliday/customHoliday/companyEvent are aliases that open the hub at the matching section; openSettings, setActiveModal('settingsHub') and the alias keys are no-ops while What-If is active), tooltip, drag/resize state, drag indicator, dependency-linking state, phantom-sibling state, context menu, scroll/zoom triggers, completionSliderFor (openCompletionSlider(level, id) from the context menu's Set progress…; the matching PhaseRow / SubphaseRow opens its CompletionSlider anchored to its name and clears it), resource drag, Kanban card dialog (openKanbanCardModal), modalContext.returnTo (reopen the previous modal on close, e.g. My absences → absence dialog), isLoading / loadingMessage, flashNotice + showFlash(message, tone) / dismissFlash() (a detached error with no form to sit in — context-menu deletes, refused dependency links, failed card moves — rendered bottom-right on an opaque --bg-secondary surface by layout/FlashNotice, auto-cleared after 6 s) |
whatIfStore |
no | What-If mode flag, structuredClone snapshot of projects, queued operations, whatIfApplyError {applied, total, message} + dismissApplyError, reset |
undoStore |
no | Undo/redo stacks of project-tree snapshots (max 50) |
customColumnStore |
visibility only | Columns, values map (key "{columnId}-{entityType}-{entityId}"), per-column filters (__empty__ sentinel for blanks), visibility |
notificationStore |
no | In-app notification inbox (server-owned; not persisted — the bell reloads on mount/focus), unreadCount, panelOpen; receive() upserts live pushes by id: a push not newer than the stored row (equal created_at = a repeat) is ignored, a newer one (a coalesced change notification) replaces it and moves to the top, with the unread count adjusted by the difference; removeLocal(id) (the bell's ×; a derived row is ignored, the unread count drops when the row was unread) and clearLocal() (Clear all) are optimistic, the bell reloads on a failed call. Derived due-soon/overdue reminders are not here — the bell merges them in from useDerivedDueNotifications, whose dismissal re-derives every mounted copy at once (it subscribes to the dismissal map) |
workStore |
no | My Work: mine (own requests, My Requests), toDecide (My Approvals), openCount (the sidebar badge: requests to decide), activeTab (approvals / assignments / requests, opens on assignments), requestsFilter (open / done), assignmentsFilter (upcoming / all), loading / loaded / loadError; refresh() loads the two lists together (shared in-flight promise, a failed list keeps its last value), applyDecisionLocal. My Assignments is not stored: WorkView derives it from appStore.projects with collectMyAssignments (utils/myAssignments.ts; approved rows of non-archived projects at every level, upcoming = end ≥ today, soonest first). In resetAllStores() |
dashboardStore |
no | Dashboards (2.3.0, server-owned): dashboards (the list), current (the open one with its widgets), data (widget id → result or {error}), loadedAt, loading / dataLoading / loadError / listLoaded, editing (a draft is open: refreshCurrent() is held back and replayed by setEditing(false)); refreshList(), open(id) (404 → This dashboard is no longer shared with you + list reload), reloadData(immediate?) (2 s trailing debounce for live reloads), refreshCurrent() (detail + data, same debounce — a PUT reassigns widget ids), save(draft) (POST without id, PUT with it), remove(id), duplicate(id, name) (POST source_id, private), pickInitial() (viewStore.lastDashboardId[tenantKey] if still listed, else the default, else the first); generation counter + per-load sequence numbers drop stale answers. In resetAllStores() |
confirmStore |
no | Queue of pending confirmAction() requests (first in shows); ConfirmDialog settles the head. Reset by resetAllStores(), which resolves every pending request false |
adminStore |
no | Admin portal: admin user + mustChangePassword, tenants, organizations, admin users, stats, active tab, selectedTenantId / selectedOrganizationId. Not re-exported from stores/index.ts and not touched by resetAllStores() |
Persistence gotchas: Sets are serialized as arrays and restored in custom merge functions. viewStore's merge is field by field, so every field added to partialize must also be listed in merge, or it silently resets on every reload. currentDate and timelineAnchorDate are memory-only — the app always opens on today; the store holds no pixel offset of the timeline at all (viewStore.expansion.test.ts pins the sorted list of persisted keys).
API client (src/api/client.ts)¶
apiRequest<T>+apiGet/Post/Put/Patch/Delete+downloadFile(Content-Disposition-aware).- Cookie auth (
credentials: 'include') — no token headers. - Dev detection: when the page runs on port 3333, API and WS target
:8485directly (no Vite proxy). - FastAPI 422 validation errors are flattened to
field: messagestrings; non-JSON responses raise with the first 200 chars logged (catches proxy HTML). Every non-2xx throwsApiError(anErrorcarryingstatus;isForbidden(err)for 403s). A 202 own-booking body is recognised withisPendingResponse()(api/endpoints/approvals.ts), never by status. - Session expiry: a 401 on a session-bound call fires the
onUnauthorizedhook →expireSession()(src/stores/index.ts):resetAllStores()(appStore except the persisted site id, What-If, undo, notifications, custom-column data,uiStoreback to its initial state, and the transient body classesphantom-sibling-mode/resource-dragging/kanban-dragging/what-if-moderemoved; viewStore and column visibility are kept, adminStore is left alone) and back to the login screen.useAuth.logoutalso callsresetAllStores(), so nothing carries over to the next person on the tab. Add new stores toresetAllStores(). - What-If interception happens here (see What-If Mode).
- Endpoint modules beyond the per-domain ones:
health.ts(getAppVersion()),importChunks.ts(postInChunks(), used bysites.ts/vacations.ts),kanban.ts(+mentionableCache.ts:mentionableUsersFor(siteId, load), the @-mention list per site for the session, import-free, cleared byresetAllStoresand by WS batches holdingstaff/roles),notifications.ts,approvals.ts. The last three are imported directly, not re-exported fromapi/index.ts(roles.tsis).
Transform layer (src/api/endpoints/projects.ts)¶
All backend↔frontend field mapping is centralized. The frontend model is mostly snake_case like the API. Inbound, transformProject/Phase/Subphase/StaffAssignment/EquipmentAssignment map phase type→name and sort_order→order_index, reshape the tree (subphases→children, parent_type/parent_id→parent_phase_id/parent_subphase_id), camelCase the assignment arrays, map each staff assignment's approval_status (pending / approved), approval (the open request, or null) and linked (card rows; absent from an older server = linked with the card's dates; project rows false), default status to todo, and inject theme colors (getPhaseColor, getDepthColor). Outbound, only phase name→type is mapped. fetchAllProjects() loads every project with its full tree through getProjectDetails('all'), a page loop over GET /api/projects/details (200 per page, like getProjects()), and maps each item through transformProject(); before 2.5.1 it sent the list and then one GET /api/projects/{id} per project at once, which in every open browser after every change exhausted the server's connection pool. loadAllProjects() wraps it and is a no-op during What-If. A failed page rejects the whole load and is not retried (a retry would only multiply the load). Assignment CRUD routes differ by level (/assignments/{id} vs /phase-staff/{id} vs /subphase-staff/{id}) — the endpoint module picks the right one.
Gantt architecture (src/components/gantt/)¶
GanttContainerorchestrates: filters projects to the current site (non-archived), orders them withorderSiteProjects()(utils/storage.ts, shared with the Kanban board: per-site custom order from localStorage, default = confirmed-first, then name), applies the project filter (useFilteredProjects), memoizes timeline cells/headers, and rendersProjectPanel(left tree) + resizer +Timeline(right) insideTimelineScrollProvider, with optional embedded staff/equipment overview pane (for whoever may open the view of that name:useOverviewPanels)ls below (canManageAnyProject:projects.edit_any, or the PM of at least one project).ProjectPanel/: header actions, right-aligned across the name column + custom columns (new/import/manage columns/visibility/Filter —ProjectFilterDropdownfromcomponents/common(one section per dropdown field with an item at the site, "(None)" first, then "Tags"; options narrowed by the team filter, projects resolved against every site item and tag), also mounted in the Kanban toolbar — thenGroupByDropdown(dropdown fields) andColorByDropdown(dropdown fields + "Tags"), both thin wrappers over the sharedFieldChoiceDropdownshell and rendering nothing without a choice; the header dropdown panels — and the column menus and Staff/Equipment overview filters — areAnchoredPanelportals aligned to their trigger, so an open overview pane cannot clip them) +SectionRow(Group-by section header) + rowsProjectRow → PhaseRow → SubphaseRow → AssignmentRow+ custom-column cells; wrapped inReorderProvider.Timeline/:TimelineHeader(period row, day labels, and the events row holding the event strip) +TimelineBody— grid cells (weekend/holiday/company-event backgrounds; week separators when weekends are hidden: a 3 px--border-color-hoverband straddling the boundary before each Monday,left = index × cellWidth − 1, in the grid layer, under every bar, block and label, of the header, the Gantt, Equipment, Cross-site, Archived and Staff timelines — one rule everywhere),TodayLine, per-project bars (ProjectBar/PhaseBar),DependencyLayer(arrows), phantom overlays,DragIndicator,ResourceDropOverlay. Positions throughuseTimelinePosition(below), plus zoom re-centering on the visible center date, Ctrl+wheel zoom, and scroll-to-today/date triggers — both one-shot (uiStore.scrollToTodayTrigger/scrollToDateTrigger,{timestamp} | null, cleared by the one timeline that handles them, so a later navigation, zoom or remount does not re-centre; Today anchors its place throughanchorAt). The timeline opens on today; an in-session remount restores an anchor date, never a pixel offset, and a reload never restores — App renders the Gantt once before the data load with no settings (weekends shown), and a pixel stored by that throw-away mount meant a date months ahead on weekday-only cells (Timeline.scroll.test.tsx, "regression guard").- Group by a project field:
GanttContainerturnsuseGanttGrouping()+ the filtered projects into one flatGanttRow[](components/gantt/utils/projectSections.ts:buildProjectSections→buildGanttRows; sectionsfield-<item id>in item order, a project under its first item, empty sections omitted, "No" last; the pill colour is the item's) and hands the same array to ProjectPanel(SectionRow) andTimelineBody(div.groupBand, a direct child of.rows); both panes fall back to a memoised flat list whenrowsis omitted. Section rows are--section-row-height(36 px) + 1 px border, content-box, =SECTION_ROW_TOTAL_HEIGHT(37) incalculateRowPositions(rows, …), keyedsection-<key>; collapsed sections' projects get no position (no arrows, no drop target). Section class names must not containrowand carry nodata-project-id/data-phase-id(the drag/resize hooks andDependencyLayerfind rows by[class*="row"]/ data attributes). Project drag-reorder is off while grouped (onProjectReorderundefined). - Scroll sync:
TimelineScrollContext(horizontal, direct DOM with feedback-loop guard) across Gantt/Staff/Equipment timelines;useScrollSync(vertical) between tree panel and timeline body — wheel-driven in the same frame, echo-free, and padding the shorter pane so both reach the same scroll end (never a fixed scrollbar-height padding in CSS). - Drag pipeline (
useDragAndDrop): mousedown or touchstart on a bar (touches become a mouse-like event viatoMouseLikeEvent) → live DOM movement with cell snapping (week/month) and a dependency lag indicator → on drop,commitDragUpdatecomputes new dates from pixels, awaitsconfirmAction()for whole-project moves (cancel snaps the bar back), snapshots undo state, clones and mutates the project tree (cascading children + project-level assignments — pending project rows are never moved; a moved or resized card fits its own bookings locally only withfitCardBookings(card, oldStart, oldEnd)(linked rows take the card's dates, unlinked ones are translated/clamped, pending ones too) and sends no segment PUTs, the server fits them in the card PUT; everyPendingUpdatecarries its assignmentlevel, so a staff update goes to the right route), updates the store optimistically, then persists via batchedPendingUpdates (savePendingUpdates, in two waves: project/phase/subphase updates first, then staff/equipment assignment updates, so a segment PUT never precedes its card's; every update is tried, failures reported together). Any persist error → reload all projects + clear undo. The documentmousemove/mouseupandtouchmove/touchend/touchcancellisteners (here and inuseResize) are attached at drag start and removed on mouse-up/touch-end and on unmount — never left on the document between drags. Touch: the bars hand the hooks a mouse-like event built byutils/touchEvents.ts(toMouseLikeEvent, an explicit object — never spread a SyntheticEvent, its methods are lost; itspreventDefaultis a no-op for the passive touchstart), and every touch start waits for a 5 px move first (armTouchGesturefor project, assignment and resize-handle touches; the PhaseBar body has its own threshold) so a wobbly tap never commits a move; the non-passivetouchmovelistener callspreventDefault()only on interactive bars (React's roottouchstartlistener is passive, so only CSStouch-action: noneon the interactive bars — theinteractiveclass, set when a bar has drag/resize handlers, so read-only bars still scroll — plus that listener stop the timeline from scrolling),touchendis default-prevented so the browser sends no emulated click, andtouchcancelrestores the bar without saving (cancelDrag/cancelResize). A move keeps what the bar shows (2.7.0): its calendar length, or — when the weekend cells are hidden (hidesWeekendCells(viewMode, showWeekends): week / month zoom with Show Weekends off, read from the store, not the DOM) and weekends are not working days (selectWeekendsWorkingfalse) — its weekdays: one column is one Monday-to-Friday day, so the bar and everything moved with it (children, bookings) shift by whole weekdays (shiftSpanByWeekdays,utils/workingDays.ts) and Monday-to-Friday dragged one column becomes Tuesday-to-Monday instead of ending on a hidden Saturday. The puredroppedSpan(data, droppedStart, unit)is the one landing rule of the live preview, the lag indicator, the drop and the no-header-cells fallback; the move travels as aSpanMove({unit: 'days' | 'weekdays', amount}; a plain number is still a day offset) throughmovePhasesWithProject/moveChildrenByOffset, and a weekday move setsweekday_moveon the dragged card's PUT and on every moved card'sPendingUpdate, so the server fits the unlinked segments by weekdays exactly asfitCardBookings(..., { weekdayMove: true })did locally. A parent the cascade translates by that same weekday move (processSubphaseMove(..., move)→cascadeParentDatesUp: its new span equalsmoveSpan(old, move)) is flagged too, so its own segments move rather than clamp; a parent really resized, resize and dialog edits never send it. On a weekday move a child that lay inside its parent (a project's phase, a phase's or subphase's subphase) is kept inside the parent's moved span (ParentSpans,clampToCard(..., { weekdays: true }); a milestone stays on one day) — a weekend-only child would otherwise land past it. The drag records its undo entry withsaveState(projects, 'drag', { weekdayMove: true });useUndoRedopasses the marker todiffProjects, which setsweekday_moveon a card whose dates go back (or forward, on redo) by an exact weekday translation that changes its calendar length. The helpers are always Monday to Friday; with Weekends are working days on the drag does not use them (the calendar length is then the working days, and a weekday move would drop booked weekend days). - Auto-calculation semantics (
gantt/utils/autoCalculation.ts): dependencies auto-align only at creation time; moving an item does not cascade to its dependents (users keep manual lead/lag control). Moves do (a) expand/contract parents to the union of their children and (b) auto-fit project dates to phases. Staff-assignment updates must includeallocation(backend requirement). - Critical path (
components/gantt/utils/criticalPath.ts): full CPM forward/backward pass,totalFloat <= 0= critical; loaded via dynamic import fromappStore.toggleCriticalPathto avoid a circular dependency. - Undo/redo (
useUndoRedo+components/gantt/utils/diffProjects.ts): restore snapshot, diff old-vs-new date fields and dependency arrays into minimalPendingUpdates (pending assignment rows skipped; unlinked phase/subphase rows diffed with their level by calendar day, a row unlinked since the snapshot gets arelinkupdate and one linked since gets its dates again), persist; on failure reload + clear history. - Pending bookings: a pending create (
isPendingAssignment) renders as a dashedAssignmentRow/ hatchedAssignmentBarwith aPendingBadge, a row with an open change shows40% → 60%; any open request freezes the bar. The context menu offers Approve / Reject (approval.can_decide) and Cancel request (the requester); Edit followsassignmentLock(utils/pendingBookings.ts): someone else's pending create, a row carrying my own open request, or no edit right lock it;AssignmentModalapplies the same rule and opens read-only with aNotice(ASSIGNMENT_LOCK_MESSAGES), comments still usable — My Work's Open always opens the dialog. A 202 from a write goes throughutils/pendingBookings.ts(markRequestPendingLocally,reloadAfterPendingWrite,flashSentForApproval). - Card bookings (linked / unlinked): phase/subphase staff bars (
CardBookingBarinProjectTimeline.tsx) are drawn atbookingSpan(row, card); a linked bar is read-only, an unlinked one isinteractivewhencanEditAssignmentallows it and drags/resizes within its card: the bars pass{level, bounds}(CardBookingDrag, last argument ofstartStaffAssignmentDrag;DragData.level/bounds), the hooks clamp live withclampToCard(pixel viagantt/utils/timelinePixels.ts), skip the lag indicator, clamp again at commit and PUT with the level; a refused booking write is flashed with the server's text. Every booking row's card badge is one rectangle,CardBadge(ProjectPanel/CardBadgeView.tsx; styles and name fromcardBadge.ts), holding two buttons: the pin toggle (PinIconfilled = linked,PinOffIconoutlined = own dates;aria-pressed; always drawn,disabledwhen the user may not edit the row, it is pending, their own request on it is open or the card has no dates; also, with the title Can't follow the phase dates while another booking of this person overlaps them, on an unlinked row whose relink the server would refuse with a 409 —relinkWouldOverlap(row, card.staffAssignments, card)instaffGroups.ts, computed byCardStaffRows; unlinking is never blocked): unlink sends the card's dates, relinknulldates, with undo state saved, a 202 →markRequestPendingLocally; and the card name, which scrolls the timeline to the booking (triggerScrollToDateof the own start when unlinked, the card start when linked). Both stop propagation, so a click never reaches the row (a right-click still opens its menu).AssignmentModalhas the matching "Follow the phase/subphase dates"ToggleSwitch(off →DateRangeFieldwithminDate/maxDate= the card; a card moved while a new booking is open restarts dates now outside it on the card). For a new booking the switch is reactive until touched (followCardChoiceisnull,followCard = followCardChoice ?? secondBooking): a first booking opens unpinned with the card's dates prefilled and sent; picking someone already on the card turns it on. New bookings from the dialog with the switch on (also opened by the context menu's "Assign me…" / "Request to assign me…" and their "again…" forms,modalContext.staffId= the user) are sent without dates: linked when the person has no row on the card, otherwise placed by the server (plan_placement: largest free gap, or the half of a full-span booking). A resource drop onto a phase / subphase bar (ResourceDropOverlay) is sent without dates and withunpinned: true, and Kanban's assignee POST is placed the same way: a first booking gets the card's own dates (link_first=False), a second one is placed. - Overview row: a person with 2+ bookings on one card gets a
StaffGroupRow(panel, indented like a booking row: chevron, the sameCardBadgerectangle without the pin — its name scrolls to the person's earliest booking (firstStartfromCardStaffRows, the earliestbookingSpanstart) —, name, "N bookings", allocation range) whose timeline row is a read-onlySegmentsBar(one block per booking, pending ones hatched, tooltipname · dates · N%), followed by the per-booking rows while expanded. The layout rule is one:gantt/utils/staffGroups.ts(cardStaffItems(assignments, level, card, collapsed)— a group sits where the person's first row comes in API order, its rows in date order (bookingSpanstart, then id) —,staffRowCount,staffGroupKey,allocationRange,relinkWouldOverlap) feedsCardStaffRows(panel),CardStaffBars(timeline) andcalculateRowPositionsalike. Group rows carry norowclass and nodata-*-id, so the drag/resize hooks andDependencyLayernever target them; they have no context menu. - Dependencies are stored per phase/subphase as JSON
[{id, type, lag?, entity?: 'phase'|'subphase'}]. Phase and subphase ids are separate sequences, so new links always writeentity; legacy entries without it resolve phase-first. Always go throughcomponents/gantt/utils/dependencies.ts:resolveDependencyPredecessor(lookup),dependencyMatches(find/delete a link, legacy-aware, missingtype= FS),wouldCreateDependencyCycle(walks phases and subphases alike). Arrows, critical path and linking all use them. - Timeline headers: generated in
components/gantt/utils/timeline.ts(generateTimelineCells/generateTimelineHeaders); week labels are ISO 8601 (date-fnsgetISOWeek/getISOWeekYear— 1–3 Jan 2027 is W53); the current month is highlighted. Every cell carriescompanyEvents: CellEvent[]— every event overlapping its day, quarter week or year month (whole-site closures, team-limited closures, then start / name / id;compareCellEvents); the single-event fields (companyEventName/Color) are the first of the list, and the header tints a cell in that colour and names every event in itstitle. - Event strip (
Timeline/TimelineMarkers.tsx): the one holiday / company-event strip of all five timelines, mounted once byTimelineHeaderin its third row (eventsRow, 15 px with the header's bottom border, which it draws itself, below the day labels — never in a timeline body, where it would sit on the first row's bars) at every zoom (only the background tints stay week / month) with the current site's id read fromappStore(Cross-site too: events are loaded for the current site only). The header is--timeline-header-total(66 px = 23 + 28 + 15,styles/variables.css, every theme block) high, and the five left panes' headers (ProjectPanel.header, the Staff / Equipment / Cross-site / Archived.panelHeader) read the same token, so the rows stay level (timelineHeaderHeight.test.ts); the Staff / Equipment panels embedded below the Gantt have no header and no strip (the Gantt header shows it). Archived'sTimelineRowtints are plain. Day zoom: bands on up to three lanes fromgantt/utils/eventLanes.ts(assignEventLanes(cells), pure; lane 0 reserved for the holiday line,MAX_LANES = 3, a run placed whole or counted inoverflowas+N); quarter / year: one band + a count per cell. Its 12 px hit cells arebutton.markerBadge— theBadgekeeps them out of the 44 px mobile button rule (mobileTouchTargets.test.ts); the panel isAnchoredPanel(role="dialog"; hover / focus / pin, Escape throughuseDismissableOverlaywithout reopening on the returned focus for a focused or pinned panel, a hover panel's Escape closes it without a focus move and without stopping the key; no hover / focus panel during a drag or resize; a change of zoom or cells closes it for good; one panel across strips through a module-scopeEventTarget); an event name opensopenSettings('company-events', {type: 'edit', id, siteId})forcompany_events.manage. The header's day labels open the same hover panel:cellHasHit(cell, viewMode, showHolidayLine)(pure, ingantt/utils/eventLanes.ts) decides which cells have a hit button, and the component is aforwardRefwhose handle (TimelineMarkersHandle:enter(index, e), a no-op without a hit, andleave())TimelineHeadercalls from each.secondaryCell's mouse enter / leave — hover only (focus and click stay on the strip's button), the panel anchored to the strip's button of that index; those labels drop their nativetitle(a quarter week whose only mark is a holiday keeps it). It uses nodata-dateand norow/barin class or attribute names (the drag hooks andDependencyLayerquery those document-wide). Never add a per-view CSS tooltip for holidays or events. - Shift-hover details (
ShiftTooltip/):ShiftTooltipowns the hover tracking, the fixed wrapper and the measured viewport clamp; the content is the presentationalDetailsRows(all three bar types, rows gated by ashows(row)callback — a project's istooltipRowGate(settings), memoised per settings change) over plainTooltipDatafrom the pure builders intooltipData.ts(projectTooltipData(project, { tags, fields, bankHolidayDates }),phaseTooltipData,subphaseTooltipData). Settings → Project fields renders the same card from a sample project, in the page flow through the.staticmodifier ofShiftTooltip.module.css. - Custom-column cells write one value with
setCustomColumnValue, and a cascade to children withsetCustomColumnValuesBatch(chunks of ≤ 500, the backend limit); on failure the touched cells are rolled back unless edited again since.
Kanban architecture (src/components/views/KanbanView/)¶
- The board is a second rendering of the Gantt tree, not a separate dataset:
KanbanViewtakesappStore.projects, orders them withorderSiteProjects(), filters withuseFilteredProjects(), and derives cards withutils/kanbanCards.ts(card = leaf phase/subphase, milestones included;groupCards()builds the swimlanes for theviewStore.kanbanGroupingchoice).KanbanBoard→KanbanColumn→KanbanCard;KanbanToolbarholds the project picker, grouping (no project fields), Filter and My-to-do toggle. - Comment counts come from
api/endpoints/kanban.ts(getCommentCountsfor one project,getSiteCommentCountsin "All projects" mode); the card dialog ismodals/KanbanCardModal.tsx(assignees withAllocationSlider, the thread incommon/CardComments—MentionTextarea, mention candidates fromgetMentionableUsersthroughmentionableCache.ts, its own submit guard). The sameCardCommentssits inAssignmentModal(edit mode, staff) for the card's thread or, at project level, the project's thread; it renders after the<form>and every button in it istype="button", so a Comment click never submits the booking. - A card shows one avatar per person (
groupCardBookings; dashed only while none of their rows is approved, title lists every allocation), andKanbanCardModallists one line per booking (segment dates on unlinked rows) whose ✕ removes that row throughdeleteStaffAssignment(row.id, level)—unassignCardstays exported but unused (the per-person route 409s on several rows). - Assignees are approved rows only (
assigneeIdsOf); pending ones (pendingAssigneeIds) show as dashed avatars, count for My Todo, but never make a card movable or due-reminded.KanbanCardModalrelabels Join / leave / slider writes in approval mode and showsApprovalActionsto deciders. - Dragging is
contexts/KanbanDragContext.tsx— hand-rolled HTML5 drag events likeReorderContextanduseResourceDragDrop, no DnD library. The move is optimistic; the server echoes{status, completion}and the client reconciles without a refetch. - Server writes broadcast as
phase/subphase/staff_assignment/card_comment(see Real-Time Collaboration); a card status change from the Gantt slider is applied locally bystatusAfterCompletionWritebecause the rich broadcast excludes the sender.
Hooks catalog (src/hooks/)¶
| Hook | Purpose |
|---|---|
useAuth |
Mount-time checkAuth(), login/logout (logout calls resetAllStores()) |
useDataLoader |
Parallel initial data load + site resolution (the persisted site only if still visible, else the lowest-id visible site; selectSite(site) is exported) + loadGated(key, load) (no request without the view key, a 403 → empty slice; the equipment and block loads use it) + granular refreshers (refreshProjects, refreshSiteData, refreshCustomColumns, refreshStaff, refreshEquipmentBlocks, refreshAbsenceTypes) that components call after their own writes. WebSocketContext does not use it — it fetches on its own |
useWebSocket / WebSocketContext |
See Real-Time Collaboration |
useDragAndDrop |
Gantt bar dragging, mouse and touch (see drag pipeline); gated per project (canEditProjectById), per equipment booking (canBookEquipmentById) and per own assignment (canEditAssignment); unlinked phase/subphase bookings drag within their card (CardBookingDrag), linked ones never; a 202 on an own bar → reloadAfterPendingWrite() (reload, clear undo, "Sent for approval") |
useResize |
Bar edge resizing with date recalculation (mouse and touch; a touchcancel restores the bar without saving); same gates and 202 handling as useDragAndDrop |
useResourceDragDrop |
Drag source only for staff/equipment from ResourcePanel and the Staff/Equipment views: permission check (project editors drag anything; everyone else only their own staff card, and only with assignments.self_create in allow or approval mode — canBookSelf), drag data, uiStore drag state and body class. It deliberately has no create path: Timeline/ResourceDropOverlay.tsx creates the 5-day default assignment (staff allocation defaults to max_capacity), checks the target's permission and blocks drops during What-If |
useDependencyLinking |
Two-click dependency creation |
usePhantomSibling |
Shift+click spawns a phantom sibling bar following the cursor (lag computed on placement) |
useUndoRedo |
Undo/redo orchestration (see Gantt architecture) |
useKeyboardShortcuts |
Esc (linking → phantom priority), Home (today), +/- zoom (±4 px, 12–120 px), Ctrl/Cmd+Z / Ctrl/Cmd+Y / Ctrl/Cmd+Shift+Z. Every shortcut is ignored while a modal is open (uiStore.activeModal) — the modal owns the keyboard, and the shared Modal owns Escape so guarded onCloses like the Settings hub's run. Also ignored while focus is in an input, textarea or contentEditable |
useCan |
useHasPermission(key) / useNeedsApproval(key) (primitive selectors) and useCan() (a stable (key, project?) => boolean) over utils/permissions.ts |
useVisibleSites |
The sites the user may see (can_see_all_sites → every site, else site_ids), for the site selector, Cross-site and the Settings site pickers; visibleSitesFor() is the pure form |
useAllowedViews |
{visible, isAllowed} from VIEW_PERMISSIONS, Cross-site left out below two visible sites — the one key-per-view map, read by Navigation and MainLayout (whose fallback to the Gantt waits for the sites to load) |
useOverviewPanels |
{canStaff, canEquipment, showStaffPanel, showEquipmentPanel, showAny}: the Staff & Calendar / Equipment panels docked under the Gantt follow the view permissions (views.staff, views.equipment) and the two viewStore flags — the one definition, read by the Header's Panels button, GanttContainer (rendering and the admin's default panel) and Timeline (scroll sync). canManageAnyProject only gates dragging a resource since 2.7.0 |
useRoles |
appStore.roles, fetched once on first use (shared in-flight promise); refreshRoles() after writes. Import from @/hooks/useRoles |
useApprovalPolicies |
appStore.approvalPolicies, loaded on first use; useApproverSummary(action, projectId) → the PendingBadge tooltip ("Awaiting approval by … (project manager), Team Lead or an administrator") |
useMentionCandidates |
(siteId, participants, meUserId) → the @-mention picker's candidates: the people on the target first, then the site's mentionable people (mentionableCache.ts, once per site), never the signed-in user. null site loads nothing (pass it while the field is hidden). Shared by CardComments and AssignmentModal's booking comment |
useWhatIfBlocked |
{blocked, reason(action)} for create entry points during What-If (whatIfUnavailableMessage()) — use it for any new create button/dialog |
useGanttGrouping |
Current site's Gantt "Group by" ({siteId, field, fields, collapsedKeys, setField, toggleSection, collapseAll, expandAll}; fields = dropdown fields with an item at the site, fieldsForSite); primitive selectors, a stored id not among fields → field: null without a write. Import from @/hooks/useGanttGrouping (tests mock @/hooks partially) |
useGanttColorBy |
Current site's Gantt "Colour by" ({siteId, colorBy: ProjectField | 'tags' | null, fields, setColorBy}), read by every ProjectTimeline row and the ColorByDropdown; same rules as useGanttGrouping (primitive selectors, stale id → null without a write, no-op without a site). Import from @/hooks/useGanttColorBy |
useEscapeKey |
Escape-to-close for standalone dialogs that can't use the shared Modal (e.g. the admin-portal modals). Stands down while a confirmAction() request is pending, so Escape on the confirm never also closes the dialog that asked |
useCtrlScrollZoom |
Ctrl+wheel zoom keeping the date under the cursor fixed |
useTimelinePosition |
Where a timeline opens and keeps its place (Gantt Timeline, standalone Staff / Equipment views): opens on viewStore.timelineAnchorDate (the left-edge date, openingScrollLeft / scrollLeftForDate / leftEdgeDate in gantt/utils/timeline.ts) or on today; the mount writes nothing, and a mount unmounted before its frame cancels it — a debounced scroll (200 ms), a navigation, the Today button (anchorAt(scrollLeft)) or a cell-set change of a visible pane writes the anchor; a view-mode or weekend switch keeps the left-edge date (a hidden weekend day falls to the Monday). onScroll goes in the pane's scroll handler. Import from @/hooks/useTimelinePosition |
useScrollSync |
Bidirectional vertical scroll sync between two elements (used by GanttContainer and the Staff/Equipment/CrossSite/Archived views). Three behaviours: no echo (a write remembers the value and ignores the follower's matching scroll event, so the follower never snaps the source back), a non-passive wheel handler that moves both panes in the same frame (Ctrl+wheel and horizontal deltas are left alone), and equalised scroll range — it measures both panes' natural scrollHeight - clientHeight and pads the shorter one (ResizeObserver, window resize fallback), which replaced the fixed 8 px bottom padding that only matched a classic horizontal scrollbar |
useWorkloadCalculation |
Per-cell staff workload for the Staff heatmap (allocations — pending bookings excluded —, vacations incl. recurring, visual states). Only absences whose type counts_as_unavailable (or untyped ones) zero capacity. An optional closure lookup (ClosureLookup, usually getClosureOn bound to the person's sites) zeroes capacity on site-closure days → vacation/conflict state, closureName/closureColor, tooltip Site closed: …. A day that is no working day (isWorkingDay(dateStr, weekendsWorking), the last argument from selectWeekendsWorking; decided on dateStr) is nonworking before anything else — precedence nonworking > absence / closure > booking — and is drawn as nothing (no badge, no Available; the weekend tint stays). workloadRuns(cells, dates) (pure) merges index-adjacent cells that read the same — workloadLabel (badge), state, the colour of an absence/closure block and tooltip — into WorkloadRuns (from, to, workload, tooltip, startDate, endDate, availableAbsenceDays), skipping cells that draw nothing; two things do not split a run: an available absence (Home Office, also on a closure day), left out of the key and the tooltip and listed in availableAbsenceDays (index, date, color, label), and the amount booked during a closure or absence (every such day reads 0%; the run's tooltip gives the amount or its range, 50–170%); chunkRuns(runs, dates, MAX_RUN_CELLS) (pure; MAX_RUN_CELLS = 10) cuts a longer run into pieces of at most 10 cells (23 → 10, 10, 3), each with its own dates and Home Office days. StaffRow draws one solid block per piece (hidden weekends join a run: adjacency is by index): the state's colour on the whole block (partial / full blue, overloaded red, conflict red-hover, vacation the absence or closure colour), the label in --text-on-accent, 14 px tall, rounded, inset 1 px in its cells (2 px between blocks), one .availableAbsenceDay underline per Home Office day inside it and those days named in its title. There is no translucent fill any more |
useEquipmentOverlaps / useEquipmentTodayStatus |
Equipment double-booking detection / today-status (blocked > booked > available) — two hooks in one file |
useProjectFilter |
useSiteProjectFilter() → {siteId, siteFields, allSiteFields, siteTags, allSiteTags, filter, activeCount} (the current site's viewStore.projectFilters entry, shared by the Gantt, the Kanban board and ProjectFilterDropdown; site* = options narrowed by the team filter, allSite* = what projects resolve against; ids of items/tags deleted or re-scoped away are ignored on read and pruned on the next write) + useFilteredProjects(projects) |
useTeamFilter |
useTeamFilter() — the current site's header team filter (viewStore.teamFilters, keyed like projectFilters; null = Whole site) with projectMatches / staffMatches / equipmentMatches / eventMatches / tagMatches / optionMatches (field items, the tag rule), shared by TeamSelector, the views, the pickers and the Filter options. Its options are the site's active teams (stale ids ignored, pruned on the next write), but scoping considers all teams, inactive ones included — equipment limited only to an inactive team is hidden under any team filter. Plus useTeamFilteredProjects(projects) and useTeamFilteredCompanyEvents() (the current site's events and their date Set, narrowed — every timeline and the Staff view's Company Events row read it). Pure predicates live in utils/teams.ts |
useHeaderDensity |
The one definition of the header's width tiers: full ≥ 1650 px, compact ≥ 1280, condensed ≥ 1024, minimal below (matchMedia). The Header sets it as data-density and moves controls into HeaderOverflowMenu by tier; header CSS must contain no pixel breakpoints |
useDismissableOverlay |
The one dismiss behaviour for dropdowns, popovers and menus ({open, onClose, wrapperRef, triggerRef?, panelRef?} → {onBlur} for the wrapper; a portaled panel passes panelRef so clicks and focus inside it count as inside): outside mousedown, Tab out, and Escape in the capture phase with stopPropagation + focus back on the trigger, so only the innermost overlay closes and the app-wide shortcuts never see the key. Every overlay uses it (ProjectFilterDropdown, FieldChoiceDropdown, OptionPicker, MultiSelectDropdown, SearchableSelect, header menus, NotificationBell, column visibility/filters, Staff/Equipment filters, DependencyPopup, ContextMenu). Never for a dialog — Modal must not close on an outside click. Both it and useEscapeKey stand down while a confirmAction() request is pending, so the confirm on top owns Escape and the overlay that asked stays open until the answer |
useDerivedDueNotifications |
Due-soon (DUE_SOON_DAYS = 7) and overdue reminders for the current user's cards (approved assignments only), derived from appStore.projects (no scheduler server-side; nothing fires while the app is closed). Negative ids, source: 'derived'; dismissals in localStorage (STORAGE_KEYS.KANBAN_DUE_DISMISSED) keyed by card + due date, so a rescheduled card notifies afresh; dismissDerivedNotification notifies the mounted hooks (useSyncExternalStore on the stored map), so a dismissed row leaves the bell at once. Only consumer: NotificationBell (opening a reminder or its ×) |
Utilities worth knowing (src/utils/)¶
date.ts (~27 date helpers incl. week labels, formatMediumDate (a date field's text), formatDateTime(iso) (a real timestamp as local date and time without seconds, short month — the History's decision time and the audit log's When; '' when not a timestamp), plus date-fns re-exports), storage.ts (typed storage wrappers, STORAGE_KEYS incl. KANBAN_DUE_DISMISSED, theme system setting data-theme on <html>, per-site project order + orderSiteProjects() / compareProjectsDefault() — the one ordering rule for the Gantt and the Kanban board), kanbanCards.ts (card derivation from the project tree, groupCards() / KanbanGrouping, dueStateOf(), cardKey(), the pending-booking helpers isPendingAssignment / requestedAllocation / isRemovalRequested / assigneeIdsOf (approved only) / pendingAssigneeIdsOf, and the status↔completion mirror of app/services/card_status.py guarded by cardStatusMirror.test.ts), bookingSegments.ts (mirror of app/services/booking_segments.py: fitSegmentsToCard, segmentsOverlap, guarded by bookingSegmentsMirror.test.ts; plus clampToCard (live drag/resize), isUnlinkedBooking (linked === false with dates), bookingSpan(row, card) (effective days — a linked row reads its card's dates, so local moves show at once), groupCardBookings (Map<staffId, rows> in row order) and fitCardBookingRows (in-place local fit used by fitCardBookings and localProjectTree's card patches)), mentions.ts (@[Name](id) tokens — mirror of app/services/mentions.py — plus the composer's offset-anchored mentions, which survive edits instead of being re-matched by name; its diffEdit also carries the formula field's pills), formula.ts (2.6.0, the calculated widgets' formula language — mirror of app/services/formula.py through the shared FORMULA_CASES: parseFormula, canonical, formulaTokens, readBack (the formula with its names replaced, the editor's line of numbers), nextTermName), formulaField.ts (2.6.0, the editor's formula field: measure pills anchored at offsets and carried through edits like mentions (reconcilePills, segmentField, insertPill, relabelPill, pillAt), the suggestions (measureOptions, activeWord, matchMeasures), recogniseMeasures (a full name typed by hand), closestMeasure (the did-you-mean), fieldProblem (problems in the field's words) and the two conversions formulaFromField (terms a, b, … by first appearance, equal pills sharing one) / fieldFromFormula), colorSwatches.ts (EVENT_COLOR_SWATCHES / DEFAULT_EVENT_COLOR for events and absence types, SKILL_COLOR_SWATCHES), avatarColor.ts (avatarColorFor(id) — the one avatar palette for presence, activity toasts and Kanban assignees), projectLevels.ts (expansion levels shared by viewStore's level expand/collapse and the project row's +/- buttons), themeColors.ts (phase/depth colors from CSS vars), recurringVacation.ts ([R:0,2,4] pattern + absence-type helpers: getAbsenceOn() is the single "is this person on an absence / unavailable on this day" check (site closures are separate, see siteClosure.ts) — honours recurring patterns and counts_as_unavailable; guessAbsenceTypeId() for .ics imports), workingDays.ts (2.5.0, the working-day rule — mirror of app/services/working_days.py, guarded by workingDayMirror.test.ts: isWorkingDay(dateStr, weekendsWorking), countWorkingDays(start, end, {weekendsWorking, offDays}), workingDaysPerWeek; weekendsWorking comes from selectWeekendsWorking in instanceSettings.ts — a case-insensitive true, not a switch; used by calculateWorkloadCells, the Weekend badges of StaffView / ResourceCard, tooltipData's work days and the Gantt's absence markers), siteClosure.ts (buildClosureIndex() expands closure events into a day → events index once, in appStore.setCompanyEvents; getClosureOn(staffSiteIds, date, index, staffTeamIds?, teamSiteById?) is the closure counterpart of getAbsenceOn() — an event limited to teams at the shared sites applies only to their members, so every caller must pass the person's teams (selectStaffTeamIds) and selectTeamSiteById, or it falls back to whole-site; a team-limited closure never shades the timeline header (timeline.ts) — used by the Staff heatmap, StaffView calcAvailability, ResourceCard and Gantt assignment-bar markers), auditLabels.ts (the audit log's readable labels: actionLabel — turbo-ea's exact sign-in and export labels, then one rule, admin.<entity>.<verb> / <entity>.<verb> → "{Entity label} {verb}" (entityLabel: staff_assignment → Booking, …), the raw key for any other shape —, reasonLabel, categoryLabel, outcomeLabel, originLabel; an unknown code reads as recorded), permissions.ts (can() and the key-based gates, mirrors app/services/project_access.py — see Permission gates on the frontend), roles.ts (roleWithin — mirror of user_access.role_within, the escalation rule of the role pickers — roleKeyFromName, matrixEquals, confirmRoleDelete), pendingBookings.ts (the 202 helpers: markRequestPendingLocally, reloadAfterPendingWrite, flashSentForApproval, approverSummary; and assignmentLock(row, user, project) → null / 'request-open' / 'pending-other' / 'no-right' with ASSIGNMENT_LOCK_MESSAGES — the one rule for the context menu's Edit and the booking dialog's read-only mode), myAssignments.ts (collectMyAssignments(projects, userId, today), My Assignments' rows), metrics.ts (2.3.0, the dashboards' vocabulary: MEASURES ({key, label, unit, family}) + FAMILIES / FAMILY_LABELS / measureFamily / measuresByFamily (the editor's grouped list), DIMENSION_KINDS, the measure → dimensions MATRIX + isValidDimension, FILTER_KEYS / MEASURE_FILTERS / takesFilter, measureNeeds / dimensionNeeds / filterNeeds / archivedNeeds over NEEDS, NO_PERCENT_MEASURES, TERM_MEASURES / isTermMeasure / MAX_FORMULA_TERMS / MAX_FORMULA_LENGTH (2.6.0, a calculated widget's measures and limits) — mirror of app/services/metrics.py, compared with shared/metric-matrix.json by its test —, RELATIVE_PERIODS, GRAINS, UNIT_LABELS (unit number: a calculated widget's plain ratio, two decimals, no word), queryUnit (a formula query: percent or number), formatMetric(value, unit, options?), periodLabel / resolvedPeriodLabel, dimensionLabel (built-in field labels through builtInFieldLabel) / isDimensionHidden, widgetColor, OTHER_KEY), helpLinks.ts (2.6.0: DEFAULT_HELP_URL, the public manual — the one definition of its address —, CALCULATIONS_HELP_PAGE and calculationsHelpUrl(custom) — the widget editor's How calculations work: a custom address as is, else the public chapter on calculated widgets; the user menu's Help link opens helpAddress(instanceSettings) in a new tab, the instance setting help_url exactly as stored, re-checked by safeHelpUrl in instanceSettings.ts — an unsafe stored value falls back to the public manual; customHelpUrl is the stored address unless it is unset, unsafe or the public manual's own), viewLeaveGuard.ts (setViewLeaveGuard / leaveViewThen(go): the one hook that lets a view with unsaved work — the dashboard editor — ask before Navigation or the bell switch view; synchronous when no guard is set), relativeTime.ts (shared by the bell and My Work), ics.ts (the one .ics parser/generator: multi-VEVENT, all-day exclusive DTEND, RRULE:FREQ=YEARLY expansion, CATEGORIES, Outlook BUSYSTATUS, UTF-16; buildICS() for every export), equipmentOverlap.ts, csvExport.ts (MS-Project-compatible CSV: outline levels, ID{FS|SS|FF|SF}±lag predecessors), xmlExport.ts (MS Project XML), subphaseUtils.ts (subphase tree helpers), persistFailure.ts (recoverFromPersistFailure — the failure protocol), reorder.ts (local phase/subphase reorder applied before the server call, so it shows in What-If too), localProjectTree.ts (clone-and-replace patch/remove helpers for phases, subphases, assignments — dialogs apply edits to the store with these so they show while What-If skips the reload), whatIf.ts (whatIfUnavailableMessage() for blocked creates), touchEvents.ts (getEventCoordinates/getPointerClientX/isTouchEvent/toMouseLikeEvent/armTouchGesture/NON_PASSIVE — the one touch→mouse-like mapping used by PhaseBar, ProjectBar, the assignment bars and the drag/resize hooks), uniqueById.ts (dedupe the one-row-per-equipment–site-pair GET /equipment rows in unfiltered views), teams.ts (pure team helpers: teamsForSite, teamIdsWithinSites, normalizeTeamFilter, and the filter predicates projectMatchesTeamFilter / staffMatchesTeamFilter and, for per-site "no team here = whole site" entities, equipmentMatchesTeamFilter / eventMatchesTeamFilter / tagMatchesTeamFilter over siteScopedTeamsMatchFilter), tags.ts (pure tag helpers since 2.0.0: tagsForSite, tagsForProjectScope, compareTags / sortTags (sort_order, name), indexTags, siteKey + SITE_KEY_PATTERN (aliases tagFilterKey / TAG_FILTER_KEY_PATTERN), relativeLuminance, barTextColor), projectFields.ts (isDropdownField, optionsForSite, optionsForProjectScope — the twin of tagsForProjectScope —, valueOptionIds, isEmptyFieldValue, FIELD_TYPE_LABELS, the dialog draft helpers draftFromValue / valueFromDraft / normalizeStoredValue / sameFieldValue (a number drafted and sent rounded to the field's decimals), and the number decimals: roundFieldNumber — mirror of project_field_rules.round_field_number, half-up on the shortest decimal string, guarded by the shared ROUNDING_CASES table —, formatFieldNumber (the one read-only display helper, Intl.NumberFormat with exactly the field's decimals), fieldNumberInputText and acceptsNumberText(text, decimals) — the typing gate of NumberFieldInput (components/modals/ProjectFieldInputs.tsx, shared by the number fields and Volume): a keystroke adding decimals past the format is refused, blur pads; the built-in Volume's decimals come from volumeDecimals(settings) in instanceSettings.ts (volume_decimals, missing / malformed → 1, volumeDecimalsValue writes it); and the read-only display of a value, formatFieldValue(field, value) (text trimmed, numbers through formatFieldNumber, toggles Yes / No — an off toggle is a value —, dropdowns as item names joined with ,, deleted items dropped; empty → null; the words of the site export's field_value_cell) and fieldValueItems (a dropdown value's items as {id, label, color} pills) — used by the Shift-hover details. Its rows come from instanceSettings.ts too: PROJECT_TOOLTIP_ROWS (the built-in rows in display order, mirror of the backend tuple), tooltipRowLabel (renamed labels for the built-in fields), parseTooltipRows / tooltipRowsValue (setting project_tooltip_rows, canonical like the server), tooltipRowGate(settings) (parses once, returns the row test: listed and not a hidden built-in field) and isTooltipRowShown (the gate for one row)), projectFieldsPreview.ts (sampleProject(fields, tags, today?) — the preview's sample project: every field filled with a real option id, the first two tags, 90 days from the local today, one phase at 42 %, two staff rows — and sampleFieldValue), projectFilters.ts (fieldsForSite — dropdown fields with only their site items, empty ones dropped —, selectableFields, projectOptionIds (item order), indexOptions, ProjectFilter / EMPTY_PROJECT_FILTER, projectPassesFilter (OR within a field, AND across fields and the tag bucket, noneFieldIds = "no item of that field", unresolvable ids ignored), isFilterActive, normalizeSiteFilter, filterSelectionCount, projectBarColor(project, fields, tags, colorBy) — a field: the project's first item in item order (the one Group by files it under); 'tags': its first tag in tag order; null otherwise; always resolve colours through appStore.projectFields / appStore.tags by id, never from the inline project.tags[].color, which is stale during What-If). Note: the Gantt utilities live in src/components/gantt/utils/, not here — autoCalculation.ts, completionStatus.ts (statusAfterCompletionWrite — the slider applies the Kanban status locally, since the rich broadcast excludes the sender), criticalPath.ts, dependencies.ts, diffProjects.ts, projectSections.ts, rowPositions.ts (calculateRowPositions, row heights incl. SECTION_ROW_TOTAL_HEIGHT; its trailing collapsedStaffGroups argument makes a card's staff block count staffRowCount(...) rows — 1 per single booking, per group 1 + its rows while expanded; group rows get no key), staffGroups.ts (the overview-row layout rule, see Gantt architecture), timelinePixels.ts (pixelOfDate, day → pixel on the header cells for the live clamp) eventLanes.ts (assignEventLanes / MAX_LANES: the event strip's lanes) and timeline.ts (timeline cells and headers — each cell's companyEvents list, CellEvent, compareCellEvents —, calculateBarPosition, today position / scroll, centredDayRangeAtX).
What-If Mode¶
A client-side planning sandbox — the server is never aware of it.
- Entering (
WhatIfToggle, shown withwhatif.use— admins and superusers by default →whatIfStore.enterWhatIfMode) snapshotsappStore.projectsviastructuredClone;TenantAppadds thewhat-if-modebody class while the flag is on. - While active, the API client intercepts every POST/PUT/PATCH/DELETE (exemption list: see What-If exemptions): the request is queued as a
WhatIfOperation {id, method, url, body?, timestamp}and a fake success{success: true, whatIfMode: true, id: Date.now()}is returned, so optimistic local state updates normally. - Discard: restore the snapshot, drop the queue. Apply: temporarily disable the interception check (always restored in
finally), replay queued operations sequentially with real requests, then reload from the server (fetchAllProjects()) and exit. On the first failure Apply stops: the failed and remaining operations stay queued, What-If stays active, projects are reloaded from the server and the snapshot is reset to that state (so a later Discard restores what really landed), andwhatIfApplyError {applied, total, message}is set —WhatIfToggleshows it as a header banner with Retry / Discard / Dismiss (dismissApplyError), not an alert. Interception is back on during the post-Apply reload, so edits made in that window are queued and kept (appended after the remaining operations; on success What-If stays active with just those). If the stores were reset meanwhile (401 →expireSession, logout), Apply leaves them reset. - Undo history is cleared on enter, Discard and Apply (its snapshots straddle the sandbox boundary); undo/redo inside What-If persists through the API client, so it is queued like any edit.
loadAllProjects()is a no-op during What-If (returns the local projects) — every "reload after a write" goes through it, so a reload never wipes the sandbox. UsefetchAllProjects()when a real fetch is required. Consequently an edit must update the store locally (optimistically, or withutils/localProjectTree.tsafter the queued call) or it stays invisible until Apply.- Gantt-only.
Header.tsxrendersWhatIfToggleonly whilecurrentView === 'gantt'(or a sandbox is already open). While What-If is active, view switching and the Settings hub are blocked in two layers: store guards (viewStore.setCurrentViewaccepts only'gantt';uiStore.openSettings,setActiveModal('settingsHub')and the legacyopenModalsettings aliases are no-ops) cover every present or future caller, anduseWhatIfBlocked()visibly disables the controls with the reason. That coversSidebar/Navigation.tsx, the Kanban deep link inNotificationBell.tsx, and every Gantt-reachable entry point:AdminSection, the project dialog's "Manage tags…" / "Manage fields…" (ManageSettingsLink), and the embedded Staff view'sBankHolidaysRow/CompanyEventsRow. The Delete buttons inEquipmentPanel/UsersPanelare disabled too (their bookings are plan data), and so are the holiday/event deletes in the embedded rows (calendar data is not in the snapshot, and the refetch after a queued delete would resurrect the row). Nothing is auto-discarded. Keep new navigation or Settings entry points behind the same hook. - Creates are blocked during What-If (a queued POST has no server id, and the new item could only appear after Apply): Phase/Subphase/Project dialogs and the Assignment dialog in create mode, absences (
VacationModal,MyAbsencesModal), equipment blocks (EquipmentBlockModal), Kanban "add assignee"/"join", resource drops on the timeline and the context-menu "Add …"/"Assign …"/"Assign me…" items are disabled viauseWhatIfBlocked()/whatIfUnavailableMessage()(same wording as the import dialogs). Edits and deletes stay allowed, except holiday/event deletes in the Staff view rows (not snapshotted). - Project and custom-column WebSocket refreshes are deferred until What-If ends (see Real-Time Collaboration).
- Implications for new code: any new write endpoint is queued by default (see What-If exemptions); operations that depend on real server responses (created IDs used by later operations) do not work correctly inside What-If — the queue replays with the original bodies. New create entry points must be blocked the same way.
- Known limitations: MPP import uploads via a raw
fetchthat bypasses the queue, soImportProjectModalblocks importing while What-If is active..icscalendar imports (ICSImportPanel: holidays, events, absences) are blocked too — calendar data is not part of the What-If snapshot. Custom-column definition changes are queued but live incustomColumnStore, which is not snapshotted — a definition created/deleted during What-If is not rolled back locally on Discard (reload to resync). Configuration edits (tags, project fields and their items, absence types, skills, equipment types, phase templates, users, site and equipment definitions — see the exemption list in What-If exemptions) bypass the queue entirely; the Settings hub and the equipment/user Delete buttons are unreachable during What-If, so a cascading delete (site → projects, equipment → bookings, user → assignments) cannot desync the sandbox from the UI — a delete issued another way (another tab, the API) still does, and the deferred refresh resyncs once What-If ends. A queued project edit holding a tag or field item an admin meanwhile limits to other sites/teams fails on Apply with the backend 400 (Retry cannot fix it — Discard that edit); a deleted field or item is dropped silently. Own bookings stay queued: a queued own edit or removal whose key is in approval mode looks applied in the sandbox, and on Apply the server answers 202 and files an approval request instead (no "needs approval" hint is shown before Apply). Roles, approval policies, approval decisions and comments are exempt (see What-If exemptions); Approve / Reject / Cancel request are disabled while What-If is active, because the post-decision reload is a no-op there (My Work itself is unreachable; the booking dialog's comments still post).