# App Structure
Entry point, global state (contexts), the event hook, the tab shell, and the demo
clock. For individual screens see [screens.md](./screens.md); for the data layer
see [api-client.md](./api-client.md).
## Entry & providers (`main.tsx`, `App.tsx`)
`App` wraps everything in two providers, then renders the `Shell`:
```
```
- **`ToastProvider`** — outermost, so any component (including auth) can show a
toast.
- **`AuthProvider`** — holds the session + profile (below).
- **`Shell`** — decides what to render based on auth state (below).
## AuthContext (`context/AuthContext.tsx`)
Holds the Supabase **session**, the current **`Contact`**, the current
**`Registration`**, and a `loading` flag.
- On mount, reads the persisted session (`supabase.auth.getSession()`) and loads
the contact + registration for that user's email.
- Subscribes to `onAuthStateChange` so login/logout anywhere updates the context.
- `loadContact(email)` fetches `contacts` where `email = email` (RLS returns only
the caller's own row — see [../backend/rls.md](../backend/rls.md));
`loadRegistration(email)` fetches the caller's `registrations` row for the
active event.
- Exposes: `session`, `user`, `contact`, `registration`, `loading`,
`refresh()`, `signOut()`.
> The contact is the app's source of truth for the current user's `is_admin`
> (staff powers); the registration holds the user's `type`, `points`, and
> `qr_token` (the lanyard token, per event). After any points-changing action,
> screens re-fetch.
## ToastContext (`context/ToastContext.tsx`)
Transient, auto-dismissing toasts. `useToast().toast(message, 'ok' | 'err')`.
Used for login success, connection results, check-in results, and RPC errors.
## The event hook (`lib/useEvent.ts`)
Loads the active event + agenda and exposes it in a convenient shape:
```ts
interface EventData {
event: Event | null; // the active event (name, dates, location)
slots: { slot: Slot; sessions: Session[] }[]; // grouped, ordered by slot id
sessionById: Map;
slotById: Map;
now: Date; // the event clock (simulated or real, see below)
clockMode: 'simulated' | 'realtime'; // which clock `now` came from
loading: boolean;
error: string | null;
reload: () => void; // re-fetch (e.g. after a material upload)
}
```
- Calls `getAgenda()` (the `get_agenda()` RPC) and groups the flat rows with
`groupAgenda()` (see [api-client.md](./api-client.md)); also loads the active
event via `getActiveEvent()`.
- Every screen that needs the schedule calls `useEvent()` — the agenda is fetched
per screen mount (cheap, and keeps each screen self-contained).
## The event clock (`lib/time.ts`)
The app drives slot status (Live / Up next / Done) from a **"now"** that is
either the **real system clock** or a **simulated mid-event clock**, decided per
event by the `events.use_realtime_clock` flag (see
[admin-app.md](./admin-app.md) for the toggle). By default it's the simulated
clock, using the active event's first day at 10:20:
```ts
export function demoNow(eventDate: string): Date {
return new Date(`${eventDate}T10:20:00`);
}
```
`demoNow(event.start_date)` is frozen at **10:20 on the active event's start
date**, independent of the actual calendar date. Changing the active event or
its configured start date changes the simulated date after the event data loads.
There is no hardcoded seed date. The demo time remains intentionally fixed; an
event without a session at 10:20 may have no Live session.
`useEvent()` picks the clock from the flag and exposes both the resulting `now`
and which mode it used:
```ts
const clockMode: 'simulated' | 'realtime' = event?.use_realtime_clock ? 'realtime' : 'simulated';
const now = clockMode === 'simulated' && event ? demoNow(event.start_date) : new Date();
```
The Home header shows a **🎬 Demo clock** indicator only when the simulated
clock is active — when the real clock is on, nothing is shown (a real clock is
the expected state, so it needs no badge).
### How "Live" / "Up next" / "Done" is decided
`slotStatus(slot, now)` compares the slot's start/end against `now` (the clock
chosen above — simulated by default, or `new Date()` when the event's
`use_realtime_clock` is on):
```ts
export function slotStatus(slot: Slot, now: Date): SlotStatus {
if (now >= slotEnd(slot)) return 'done'; // slot ended before "now"
if (now >= slotStart(slot)) return 'now'; // "now" is inside the slot → Live
return 'next'; // slot starts after "now" → Up next
}
```
`useEvent()` exposes `now` (the chosen clock), and the screens derive:
- **current** (the **Now** card) = the first slot where `slotStatus === 'now'`
- **next** (the **Next** card) = the first slot where `slotStatus === 'next'`
At the frozen `10:20`, the seed's slots resolve to:
| Slot | Time | `slotStatus` at 10:20 |
|---|---|---|
| Slot 1 | 09:15–10:00 | `done` |
| Slot 2 | 10:15–11:00 | `now` → **● Live** |
| Slot 3 | 11:15–12:00 | `next` → **Up next** |
| Slot 4+ | … | `next` → **Up next** |
So the Home screen shows a live Now card, an upcoming Next card, and a done slot
that can carry a pending-feedback nudge.
> **Why a simulated clock by default?** Outside an event's dates, a real clock
> would show all slots as either future or past. The simulated clock lets the
> event be demonstrated at a predictable time on its configured first day.
> **Using the real clock.** This is a **frontend-only** concern — the database
> stores real slot times; the clock only decides which slot is "live" for
> display. Flip the event's **Real-time clock** toggle in the admin app
> (Events → Edit) to switch an event to the real system clock. With it on,
> `now` is `new Date()`, so a past event shows every slot as Done and no
> Now/Next card; a live event tracks the actual time of day. Turn it back off
> to return to the simulated mid-event clock.
Helpers:
| Function | Returns |
|---|---|
| `slotStatus(slot, now)` | `'done'` \| `'now'` \| `'next'` |
| `slotStart(slot)` / `slotEnd(slot)` | `Date` for the slot's start / end |
| `fmtTime(time)` | `"09:00"` from `"09:00:00"` |
| `fmtRange(slot)` | `"09:00–09:45"` |
| `greeting(now)` | "Good morning" / "afternoon" / "evening" |
## The polling hook (`lib/usePolling.ts`)
`usePolling(fn, ms, enabled)` runs `fn` every `ms` milliseconds, but **only while
the tab is visible** (`document.visibilityState === 'visible'`), and re-runs
immediately when the tab becomes visible again. No background polling. Used by
the Connections screen (5s) and the Shell's pending-connection red dot (5s).
## The Shell (`App.tsx`)
The `Shell` is the navigation container. Render logic, in order:
1. **`loading`** → full-screen spinner.
2. **No session / no profile** → `` (full screen, no tab bar).
3. **`feedbackSession` set** → `` full-screen takeover (no tab bar).
4. **Otherwise** → the active tab + the bottom tab bar.
### Tabs
| Tab id | Label | Screen | Notes |
|---|---|---|---|
| `home` | 🏠 Home | `Home` | default tab |
| `agenda` | 📅 Agenda | `Agenda` | |
| `scan` | 📷 **Scan** / **Check-in** | `Scan` | label is role-aware (below) |
| `connections` | 🤝 Connect | `Connections` | red dot when there are pending incoming requests |
| `profile` | 👤 Profile | `Profile` | |
- **Role-aware Scan tab:** if `contact.is_admin` is true, the tab label is
**"Check-in"** and the `Scan` screen defaults to staff mode. Otherwise it's
**"Scan"**.
- **Leaderboard** is *not* a tab — it's reached from the Home points pill and the
Home quick-actions. It renders as a tab in the shell but is opened via
`go('leaderboard')`.
- **Feedback** is a full-screen takeover (no tab bar), opened from the Agenda
session sheet via `openFeedback(sessionId)`.
## Shared UI components (`components/ui.tsx`)
| Component | Purpose |
|---|---|
| `Avatar` | Colored initials circle (color derived from a hash of the id) |
| `Spinner` | Loading indicator |
| `Empty` | Empty-state placeholder (icon + text) |
| `Sheet` | Bottom-sheet modal (backdrop + grab handle) |
| `QrImage` | Renders a string (e.g. a QR token) as a scannable QR (`qrcode.react`) |
| `Scanner` | Camera QR scanner (`html5-qrcode`) with a **manual-entry fallback** and a `hasCamera` guard (headless/no-camera environments fall back to typing the code) |