Files
2026-06-11 10:52:07 -04:00

20 KiB
Raw Permalink Blame History

VitFit V2 — Frontend Page Map

Every HTML page: purpose, access control, API calls, socket events, and key JS behavior.

All pages load core.js which calls Page.init(allowedRoles) on DOMContentLoaded. Page.init checks localStorage for a JWT (or attempts device-token re-auth), redirects to / if not authenticated or role not in allowedRoles. It also fetches branding and applies CSS vars.

CSS loaded on every page: base.css, layout.css, components.css. Display-mode pages also load: display.css (replaces layout, not combined with it).


Shared JS Modules

public/js/core.js

Loaded on every page.

Auth
  - getJwt()                      read from localStorage
  - setJwt(token)                 write to localStorage
  - getDeviceToken()              read from localStorage
  - setDeviceToken(token)         write to localStorage
  - clearSession()                remove jwt + deviceToken from localStorage
  - tryDeviceLogin()              POST /auth/device-login with stored device token
  - isTokenExpiringSoon(jwt)      true if exp < now + 1h
  - autoRefreshIfNeeded()         call /auth/refresh-token if expiring soon

Api
  - fetch(url, options?)          wraps window.fetch; injects Auth header; on 401 → tries
                                  autoRefreshIfNeeded then retries once; on 2nd 401 → shows
                                  session-expired overlay
  - get(url, params?)             Api.fetch with method GET
  - post(url, body)               Api.fetch with method POST, JSON body
  - patch(url, body)              Api.fetch with method PATCH, JSON body
  - put(url, body)                Api.fetch with method PUT, JSON body
  - del(url)                      Api.fetch with method DELETE
  - upload(url, formData)         Api.fetch with method POST, FormData body (no Content-Type header)

Nav
  - init(currentPage)             build nav drawer from config, highlight active item
  - roleVisibility(role)          filter nav links by role
  - toggle()                      open/close drawer on hamburger tap

Branding
  - load()                        GET /api/v1/org/branding → apply to :root CSS vars
  - apply(branding)               set --color-primary, --color-work, --app-name, etc.

Page
  - init(allowedRoles)            auth check + branding load + nav init
  - currentUser()                 decode jwt, return { id, username, role, organizationId }
  - showSessionExpiredOverlay()   shows tap-to-re-login overlay (non-blocking)

public/js/socket-client.js

SocketClient
  - connect()                     create io() with auth token; bind internal events
  - on(event, handler)            register event handler
  - emit(event, data)             emit to server
  - joinRoom(roomId)              emit timer:join
  - leaveRoom(roomId)             emit timer:leave
  - onDisconnect(cb)              register disconnect callback
  - onReconnect(cb)               register reconnect callback (re-joins room automatically)
  - destroy()                     disconnect and remove all listeners (called on page unload)

public/js/display.js

Used by workout-display.html and crossfit-display.html.

Display
  - renderWorkout(workout)        populate full-screen workout layout
  - renderCrossfit(crossfit)      populate full-screen CrossFit layout
  - setOffline(true|false)        show/hide reconnecting banner (content stays)
  - startKeepAlive()              begin 30s low-opacity CSS animation to prevent AirPlay freeze
  - applyBranding(branding)       set display-mode CSS vars (colors, font)

public/js/timer-display.js

TimerDisplay
  - init(sessionId)               join socket room, register event handlers
  - handleState(state)            render full timer state from timer:state event
  - handleTick(data)              update phase countdown display
  - handlePhaseChange(data)       update phase label, color, reset countdown, play sound
  - handleComplete(data)          show completion overlay
  - handleStopped(data)           show stopped overlay
  - startLocalFallback(endTime)   animationFrame loop using Date.now() diff
  - stopLocalFallback()           cancel animationFrame loop
  - formatTime(ms)                returns "MM:SS" string
  - formatHMS(ms)                 returns "H:MM:SS" string for total time
  - setPhaseColor(phase)          read CSS var for phase, apply to display elements
  - setOffline(true|false)        show/hide reconnecting indicator (timer continues)

Pages — Unauthenticated

index.html — Login

Access: Public (unauthenticated only — redirects to dashboard if already logged in).

On load:

  • Check for stored JWT; if valid, redirect to /dashboard.html
  • Check for stored deviceToken; if present, POST /api/v1/auth/device-login → redirect on success

Form submit:

POST /api/v1/auth/login
  body: { username, password, rememberDevice, deviceName, deviceType }
  on 200: store jwt (+ deviceToken if present), redirect to /dashboard.html
  on 401: show "Invalid username or password" inline error
  on 429: show "Too many attempts, please wait" inline error

Key behavior:

  • "Remember this device" checkbox (default checked on iPad-sized screens)
  • deviceName defaults to navigator.userAgent parsed to a readable string
  • deviceType defaults to kiosk if screen width >= 768px (iPad), else personal
  • Password field: toggle show/hide button

Pages — Coach / Owner (Standard Management UI)

CSS: base.css, layout.css, components.css Shell: banner + hamburger, nav drawer, main content area.

dashboard.html — Home

Access: Owner, Coach.

On load:

GET /api/v1/workouts/today     → render "Today's Workouts" card list
GET /api/v1/org                → show org name in header
GET /api/v1/admin/storage      → (Owner only) show disk usage bar in quick-stats

Quick-stats cards:

  • Today's workouts count (link to workouts.html)
  • Active timers: count of timers defined (link to timers.html)
  • (Owner only) Disk used %

videos.html — Video Library

Access: Owner, Coach.

On load:

GET /api/v1/categories          → populate filter dropdown
GET /api/v1/videos?page=1       → render video grid

Actions:

  • Category filter dropdown → GET /api/v1/videos?category=X → re-render grid
  • Pagination controls → GET /api/v1/videos?page=N
  • Each video card: inline <video> element using streamUrl as src
  • Delete button: confirm modal → DELETE /api/v1/videos/:id → remove card from DOM

upload-video.html — Upload Video

Access: Owner, Coach.

On load:

GET /api/v1/categories    → populate category select

Form submit:

POST /api/v1/videos (multipart)
  fields: video (file), description, category
  on 201: show success toast, reset form
  on 400 UPLOAD_TYPE_INVALID: "Only MP4, MOV, and M4V files are supported."
  on 507: "Not enough disk space to upload. Contact your administrator."

Progress indicator: XMLHttpRequest.upload.onprogress for upload progress bar.


categories.html — Manage Categories

Access: Owner, Coach.

On load:

GET /api/v1/categories    → render list

Actions:

  • Create form: POST /api/v1/categories → append to list
  • Delete button: DELETE /api/v1/categories/:id
    • On CONFLICT 409: "This category has videos. Move or delete the videos first."

workouts.html — Group Workouts

Access: Owner, Coach.

On load:

GET /api/v1/workouts?page=1    → render paginated workout cards

Each workout card shows: name, date, video thumbnails (or "[Video removed]"), video descriptions.

Actions:

  • "View" link → workout-view.html?id=X
  • "Display" button → open workout-display.html?id=X in same window (full-screen takes over)
  • Delete button (own workouts for Coach, any for Owner): DELETE /api/v1/workouts/:id → remove card

create-workout.html — Create Workout

Access: Owner, Coach.

On load:

GET /api/v1/categories          → populate category dropdowns (one per slot)

Slot 1 category change:

GET /api/v1/videos?category=X   → populate video select for slot 1

Repeated for slots 2–4 (each has its own category+video selects, initially hidden, revealed by "Add Exercise" button).

Form submit:

POST /api/v1/workouts
  on 201: redirect to workouts.html
  on 400: show validation errors inline

workout-view.html — Single Workout Detail

Access: Owner, Coach.

Query param: ?id=<workoutId>

On load:

GET /api/v1/workouts/:id    → render workout detail + video players

Each video slot renders a <video> element with src = streamUrl. "Display on TV" button → navigate to workout-display.html?id=X.


timers.html — Timer List

Access: Owner, Coach.

On load:

GET /api/v1/timers    → render timer cards

Each card: name, summary (e.g. "30s work / 10s rest × 3 sets × 5 exercises × 2 laps").

Actions:

  • "Launch" button → POST /api/v1/timers/:id/launch → navigate to timer-display.html?session=<sessionId>
  • Delete button → DELETE /api/v1/timers/:id

create-timer.html — Create Timer

Access: Owner, Coach.

On load: no API calls.

Form submit:

POST /api/v1/timers
  on 201: redirect to timers.html

Live preview: calculated total time shown as user fills in fields. Formula: totalTime = setTime * setCount * exerciseCount * lapCount + restTime * ... + moveTime * ...


crossfit.html — CrossFit Workouts

Access: Owner, Coach.

On load:

GET /api/v1/crossfit-workouts?page=1    → render workout cards

Each card: name, date, bullet list of items.

Actions:

  • "Display" button → open crossfit-display.html?id=X
  • Delete button (Owner only): DELETE /api/v1/crossfit-workouts/:id

create-crossfit.html — Create CrossFit Workout

Access: Owner, Coach.

Form: name, date, textarea (one item per line).

Submit:

POST /api/v1/crossfit-workouts
  body: { name, workoutDate, workoutItems: textarea.value.split('\n').filter(Boolean) }
  on 201: redirect to crossfit.html

clients.html — Client Roster

Access: Owner (all clients), Coach (own clients only).

Feature flag: client-management.

On load:

GET /api/v1/clients    → render client cards

Each card: name, username, assigned coach name, pending workout count.

Actions:

  • Click card → client-profile.html?id=X
  • "Add Client" button (Owner) → modal with create-user form → POST /api/v1/clients

client-profile.html — Client Detail

Access: Owner, Coach (own clients only).

Query param: ?id=<clientId>

On load:

GET /api/v1/clients/:id                             → render profile header
GET /api/v1/clients/:id/workouts?includeCompleted=false  → render upcoming workouts
GET /api/v1/clients/:id/sessions?status=scheduled   → render upcoming sessions

Tabs: Workouts | Sessions | History

Actions:

  • "Assign New Workout" → modal form → POST /api/v1/clients/:id/workouts
  • "Schedule Session" → modal form → POST /api/v1/clients/:id/sessions
  • Workout "Complete" → POST /api/v1/clients/:id/workouts/:workoutId/complete
  • Workout delete → DELETE /api/v1/clients/:id/workouts/:workoutId
  • Session cancel → POST /api/v1/clients/:id/sessions/:sessionId/cancel

calendar.html — Coach Calendar

Access: Owner, Coach.

Feature flag: calendar.

On load:

GET /api/v1/calendar?startAfter=<monthStart>&endBefore=<monthEnd>    → render calendar grid

Month navigation recalculates date range and re-fetches. Click on session → expand detail inline.

Phase 2 deferrals (not in V2 MVP):

  • Conflict detection: overlapping sessions for the same coach are not flagged. The API accepts overlapping bookings. Visual collision awareness is a Phase 2 enhancement.
  • Recurring sessions: no recurrence rules (RRULE, daily, weekly, etc.). Each session is a standalone record. Repeating a session means creating copies manually. Recurrence engine is Phase 2.

profile.html — Own Profile

Access: All roles.

On load:

GET /api/v1/my/profile     → populate form
GET /api/v1/users/:id/devices  → list device tokens

Actions:

  • Save profile: PATCH /api/v1/users/:id with { firstName, lastName, email }
  • Change password: form with current + new password → PUT /api/v1/my/password
  • Revoke device: DELETE /api/v1/users/:id/devices/:tokenId

settings.html — Owner Settings

Access: Owner only.

Tabs: Users | Branding | Storage | Devices

Users tab:

GET /api/v1/users     → render user table
  • Create user: inline form → POST /api/v1/users
  • Deactivate: DELETE /api/v1/users/:id (soft)
  • Change role: inline select → PUT /api/v1/users/:id/role
  • Reset password: inline form → PUT /api/v1/users/:id/password

Branding tab:

GET /api/v1/org/branding    → populate color inputs + logo preview
  • Color pickers (HTML <input type="color">) with live preview of timer phase colors
  • Save colors: PATCH /api/v1/org/branding
  • Logo upload: POST /api/v1/org/logo

Storage tab:

GET /api/v1/admin/storage    → render disk usage bar + breakdown

Auto-refreshes every 5 minutes. Shows warning banner if data.warning === true.

Devices tab: All device tokens across all users in the org.

GET /api/v1/users    → for each user, GET /api/v1/users/:id/devices

Revoke: DELETE /api/v1/users/:id/devices/:tokenId


audit-log.html — Audit Log

Access: Owner only.

On load:

GET /api/v1/audit-logs?page=1&limit=50    → render table

Filter controls: action (dropdown), date range (from/to), user (dropdown), entity type. Any filter change: re-fetches with new params.

Expandable rows: click row → show full details JSON formatted.

"Export CSV" button: navigates to GET /api/v1/audit-logs/export?<same filters> (browser download).


sysadmin.html — System Admin Panel

Access: SystemAdmin only.

Tabs: Organizations | Health

Organizations tab:

GET /api/v1/sysadmin/orgs    → render org table
  • Click org → expand detail: name, slug, timezone, features, user counts, license info
  • Edit org: inline form → PATCH /api/v1/sysadmin/orgs/:id

Health tab:

GET /api/v1/sysadmin/health    → render health dashboard

Shows: version, uptime, DB migration status, disk stats, active timer sessions. Manual refresh button.


Pages — Display Mode (Full-Screen TV)

These pages use display.css instead of layout.css. No nav drawer, no banner. They are opened from the management pages when a coach taps "Display" or "Launch". Full-screen API is requested on load: document.documentElement.requestFullscreen().

workout-display.html

Query param: ?id=<workoutId>

CSS: base.css, display.css JS: core.js, display.js

On load:

GET /api/v1/workouts/:id    → pass to Display.renderWorkout()

Layout:

┌──────────────────────────────────────────────┐
│  WORKOUT NAME             DATE                │  small top bar
│                                              │
│  [slot 1 description]         10 reps        │  large text
│  [slot 2 description]         12 reps        │
│  [slot 3 description]         8 reps         │
│                                              │
│  [touch: back]                [touch: close] │  invisible coach controls
└──────────────────────────────────────────────┘

Display.startKeepAlive() runs on load to prevent AirPlay stream freeze.


timer-display.html

Query param: ?session=<sessionId>

CSS: base.css, display.css JS: core.js, socket-client.js, timer-display.js

On load:

SocketClient.connect()
TimerDisplay.init(sessionId)   → joins socket room, registers event handlers

Layout:

┌──────────────────────────────────────────────┐
│  SET  LAP 1/2  EXERCISE 2/5  SET 1/3         │  small status bar (phase label left)
│                                              │
│           00:28                              │  giant phase countdown
│                                              │
│   Total  14:32                               │  smaller total time
│                                              │
│  [touch: stop — left edge, invisible]        │
└──────────────────────────────────────────────┘

Background color changes with phase (reads --color-work, --color-rest, --color-move CSS vars). 10-second warning: countdown turns amber (--color-warning).

On timer:complete: background fades to dark, "DONE" displayed in center. On disconnect: TimerDisplay.startLocalFallback(phaseEndTime) continues countdown locally.


crossfit-display.html

Query param: ?id=<crossfitWorkoutId>

CSS: base.css, display.css JS: core.js, display.js

On load:

GET /api/v1/crossfit-workouts/:id    → pass to Display.renderCrossfit()

Layout:

┌──────────────────────────────────────────────┐
│  HERO WOD MURPH               June 11        │  small top bar
│                                              │
│  1. 1 mile run                              │  large numbered list
│  2. 100 pull-ups                            │
│  3. 200 push-ups                            │
│  4. 300 air squats                          │
│  5. 1 mile run                              │
│                                              │
│  [touch: close — right edge, invisible]     │
└──────────────────────────────────────────────┘

Pages — Client Portal

CSS: base.css, layout.css, components.css (same shell, different nav links).

my-workouts.html

Access: Client only.

On load:

GET /api/v1/my/workouts?includeCompleted=false&page=1    → render workout cards

Each card: workout name, scheduled date, item summary (exercise count), completion status. "Mark Complete" button: POST /api/v1/clients/:ownId/workouts/:workoutId/complete "View" button: expand inline to show full items list (including video players via streamUrl).


my-schedule.html

Access: Client only.

On load:

GET /api/v1/my/sessions?status=scheduled&startAfter=<today>    → render session list

Each card: title, coach name, date/time, location, shared notes. "Cancel" button (if session > 24h away): POST /api/v1/clients/:ownId/sessions/:id/cancel


Navigation Config (core.js)

Nav links are defined in a config array in core.js. Role-based visibility is enforced client-side (cosmetic only — server enforces real access control).

const NAV_LINKS = [
  { label: 'Dashboard',      href: '/dashboard.html',        roles: ['Owner', 'Coach'] },
  { label: 'Videos',         href: '/videos.html',           roles: ['Owner', 'Coach'] },
  { label: 'Workouts',       href: '/workouts.html',         roles: ['Owner', 'Coach'] },
  { label: 'Timers',         href: '/timers.html',           roles: ['Owner', 'Coach'] },
  { label: 'CrossFit',       href: '/crossfit.html',         roles: ['Owner', 'Coach'] },
  { label: 'Clients',        href: '/clients.html',          roles: ['Owner', 'Coach'],  feature: 'client-management' },
  { label: 'Calendar',       href: '/calendar.html',         roles: ['Owner', 'Coach'],  feature: 'calendar' },
  { label: 'My Workouts',    href: '/my-workouts.html',      roles: ['Client'] },
  { label: 'My Schedule',    href: '/my-schedule.html',      roles: ['Client'],          feature: 'calendar' },
  { label: 'Settings',       href: '/settings.html',         roles: ['Owner'] },
  { label: 'Audit Log',      href: '/audit-log.html',        roles: ['Owner'] },
  { label: 'System Admin',   href: '/sysadmin.html',         roles: ['SystemAdmin'] },
  { label: 'Profile',        href: '/profile.html',          roles: ['Owner', 'Coach', 'Client'] },
  { label: 'Log Out',        href: '#',                      roles: ['Owner', 'Coach', 'Client', 'SystemAdmin'],
    action: 'logout' },
];