# VitFit V2 — Display Design (iPad + AirPlay + TV) ## The Runtime Environment Understanding exactly how the display works is critical before writing a line of CSS. ``` [iPad running Safari] └── AirPlay Screen Mirror ──► [VIZIO TV in gym] (1:1 mirror, no second-screen API) ``` AirPlay screen mirroring sends the iPad's exact rendered output to the TV. What the iPad displays IS what the gym sees. There is no separate TV canvas or second-screen API involved. **Implications:** - Design for the iPad screen size and aspect ratio — the TV scales it up - The coach and the gym members see the same content at the same time - Touch interactions on the iPad are NOT visible on the TV (no cursor shown) - Safari must stay full-screen — any native UI (address bar, status bar) showing on iPad appears on the TV --- ## iPad Full-Screen in Safari On iPadOS, "full screen" in Safari means the page fills the viewport but the device is not truly in kiosk mode. To minimize Safari chrome: - Use the "Add to Home Screen" feature → launches as a standalone PWA (removes address bar entirely) - Set `` in the HTML head - Set `` **PWA approach is strongly recommended.** It eliminates the Safari address bar and tab bar from the mirrored image on the TV. Without it, the gym sees a browser UI on the TV. Required manifest and meta tags: ```html ``` Safe area insets must be handled for iPad models with rounded corners / notch: ```css padding-top: env(safe-area-inset-top); padding-bottom: env(safe-area-inset-bottom); ``` --- ## TV Readability Requirements The TV is a standard gym display. Gym members view it from across the room (estimated 10–20 feet). ### Typography | Element | Minimum Size | Notes | |---------|-------------|-------| | Primary display (current exercise, timer) | 96px+ | Must be visible at 15 feet | | Secondary info (lap count, set count) | 48px+ | Supporting info | | Labels | 32px+ | Category/phase labels | | Body text (workout list items) | 28px+ | CrossFit workout items | Font choice: Use a system font with wide character support and high legibility — `system-ui`, `-apple-system`, or a loaded sans-serif like `Inter`. Avoid decorative fonts. Font weight: Bold (700) or Black (900) for primary display numbers. High contrast is more important than style. ### Color and Contrast Minimum WCAG AA contrast ratio (4.5:1) is the floor, not the target. Aim for 7:1+ given the viewing distance. Recommended palette for display mode: | State | Background | Foreground | Purpose | |-------|-----------|-----------|---------| | Work / Active | `#1a1a1a` dark | `#00FF88` bright green | Athlete is working | | Rest | `#1a1a1a` dark | `#4488FF` bright blue | Rest period | | Transition / Move | `#1a1a1a` dark | `#FF4444` bright red | Moving to next station | | Idle / Ready | `#1a1a1a` dark | `#FFFFFF` white | Waiting to start | | Warning (10s left) | `#1a1a1a` dark | `#FFAA00` amber | Time almost up | Dark background is mandatory — it reduces TV backlight bleed and is more readable in a gym with mixed lighting. ### Layout for Display Mode The display must work in landscape orientation (iPad landscape = standard TV aspect ratio). ``` ┌─────────────────────────────────────────────┐ │ PHASE LABEL LAP X / Y SET X / Y │ ← small, top bar │ │ │ │ │ 00:45 │ ← giant timer │ │ │ BICEP CURLS │ ← exercise name │ │ │ [touch zone: prev] [touch zone: next]│ ← invisible coach controls └─────────────────────────────────────────────┘ ``` - Center the primary display number — this is what the athlete reads - Touch zones for coach are on the left/right edges — these are NOT visible on screen - No navigation drawer, no header, no admin UI in display mode - Transitions between phases: brief CSS animation (color change, not movement) --- ## 24-Hour Session Stability ### The Problem The iPad browser runs for 24h without refresh. This creates several failure modes: 1. **Memory leaks** — detached DOM nodes, uncleaned intervals, zombie event listeners 2. **Timer drift** — `setInterval` is not precise; over hours, seconds accumulate 3. **AirPlay stream freeze** — if the page becomes visually static for too long, some AirPlay implementations freeze the stream 4. **Network drops** — WebSocket disconnects; app must reconnect silently 5. **JWT expiry** — if token expires during session, app breaks silently ### Mitigations **Memory leaks:** - Every `setInterval` and `addEventListener` is stored in a reference and explicitly cleared when the component/page unmounts - Video elements: `video.src = ''` and `video.load()` before removing from DOM - No anonymous functions as event listeners (cannot be removed); always named references - Display mode DOM is kept minimal — only update `textContent`, never rebuild the DOM during a timer run **Timer drift:** - Server-side timer using `process.hrtime.bigint()` for nanosecond precision - Client receives absolute `endTime` timestamp from server, not a countdown delta - Client calculates remaining time as `endTime - Date.now()` on each tick — any network lag is self-correcting - Even if the client's `setInterval` fires late, the displayed time is always accurate **AirPlay stream freeze:** - Some AirPlay implementations pause the video stream if the content appears static - Mitigation: a subtle, imperceptible animation runs constantly in display mode (e.g., a 1px opacity pulse on a background element, or the seconds counter always changing) - This is a known AirPlay quirk; the animation must be present even during "rest" countdown **Network drops (Socket.io):** - Socket.io has built-in reconnection with exponential backoff — use default config - On reconnect, client immediately requests current timer state from server - If server has no active timer (e.g., it restarted), client shows "Reconnecting..." overlay - No user action required; overlay disappears automatically on sync **JWT expiry:** - Tokens are 7-day TTL - On every API call, if response is 401/403, show non-blocking "Session expired" overlay - Overlay has a single tap-to-refresh button (doesn't navigate away; re-auths in place) - Background token refresh: 1 hour before expiry, silently fetch a new token --- ## Offline and Degraded Modes The server is a single VPS with no redundancy. Network drops, crashes, and reboots will happen. The iPad must degrade gracefully so the gym can continue operating. ### State Categories | State | Detection | What the iPad Shows | |-------|-----------|---------------------| | **Fully online** | Socket.io connected, API responding | Normal display | | **Socket disconnected, API reachable** | Socket.io disconnect event | Soft warning banner, last displayed content remains, reconnecting silently | | **Server unreachable** | Socket.io fails + fetch fails | "Connection lost" overlay on display; last workout content stays visible underneath | | **Server back online** | Socket.io reconnects | Overlay dismissed, state re-synced, no page reload required | ### What Stays Visible Offline When the server becomes unreachable: - The currently-displayed workout or CrossFit list stays on screen (DOM is not cleared) - The TV audience continues to see workout content — the gym does not go dark - The "Connection lost" overlay is semi-transparent and positioned at the top edge, not obscuring the main content - Running timers: see below ### Timers During Server Disconnect If a timer is running and Socket.io disconnects: - The client has the `endTime` timestamp it received from the server - The client continues the countdown locally using `Date.now()` — no server ticks needed - A small "Offline - running locally" indicator appears in a corner of the display - When reconnected, the client syncs back to the server's authoritative state - If the server restarted and the timer session no longer exists server-side, the local timer continues until it reaches zero, then stops normally This means a running timer survives a brief server restart (PM2 restart < 30 seconds) without any visible interruption. ### AirPlay Drop During Active Timer If the AirPlay connection itself drops (TV loses signal from iPad): - The iPad continues running normally — this is a display problem, not an app problem - The timer keeps running on the iPad - To reconnect: coach taps the AirPlay icon on the iPad and reconnects to the TV - No app restart needed; the display resumes from current state ### Manual Recovery Steps (for staff) If the app is in an unrecoverable state on the iPad (e.g., after a very long network outage): 1. Tap the VitFit icon in the dock to bring it to focus 2. If showing a broken state, pull down the refresh gesture (if visible) or close and reopen the PWA from home screen 3. The PWA re-loads from the service worker cache (fast) and re-authenticates via device token (automatic) 4. No coach login required; device token handles re-auth silently This is the **only scenario** where a page reload is intentional. All other reconnections are handled automatically. --- ## Safari-Specific Quirks | Issue | Impact | Mitigation | |-------|--------|-----------| | Safari blocks autoplay audio/video | Timer sounds won't play unless user has interacted | Require a coach "Start Session" tap before any audio. Do not assume sounds will play automatically. | | `position: fixed` can scroll off-screen during Safari address bar hide animation | Layout jumps | Use `position: sticky` or recalculate after `visualViewport` resize events | | `100vh` includes Safari address bar height | Elements clipped at bottom | Use `window.innerHeight` or `100dvh` (dynamic viewport height) — supported in Safari 15.4+ on iPadOS 15.4+ | | WebSQL deprecated, IndexedDB quirks | Not relevant for this app | N/A — we use server-side storage only | | Back/Forward cache (bfcache) | Page may be served from cache on nav | Add `pageshow` event listener to detect bfcache restores and re-initialize Socket.io | ### `100dvh` Usage Use `100dvh` everywhere instead of `100vh`: ```css .display-container { height: 100dvh; /* respects Safari dynamic toolbar height */ } ``` Fallback for older iPadOS: ```css .display-container { height: 100vh; height: 100dvh; /* overrides above if supported */ } ``` --- ## PWA Configuration To run as a true kiosk-like experience (no browser chrome on TV): ### Required in every HTML page `
` ```html ``` ### `manifest.json` ```json { "name": "VitFit", "short_name": "VitFit", "display": "standalone", "orientation": "landscape", "background_color": "#1a1a1a", "theme_color": "#1a1a1a", "start_url": "/", "icons": [ { "src": "/icons/icon-192.png", "sizes": "192x192", "type": "image/png" }, { "src": "/icons/icon-512.png", "sizes": "512x512", "type": "image/png" } ] } ``` ### Service Worker (minimal) A minimal service worker that caches the app shell (HTML, CSS, JS) so the page loads instantly after the 24h refresh, even on slow gym wifi: ```js // Cache the app shell on install self.addEventListener('install', event => { event.waitUntil( caches.open('vitfit-shell-v1').then(cache => cache.addAll(['/', '/styles/base.css', '/styles/display.css', '/js/core.js']) ) ); }); // Serve from cache, fall back to network self.addEventListener('fetch', event => { if (event.request.url.includes('/api/') || event.request.url.includes('/socket.io/')) return; event.respondWith( caches.match(event.request).then(r => r || fetch(event.request)) ); }); ``` Note: API calls and Socket.io are never cached — always network. --- ## Orientation and Aspect Ratio - iPad in landscape: 4:3 or 3:2 depending on iPad model (not 16:9) - VIZIO TV: 16:9 - The TV will pillarbox (black bars on sides) or stretch — this depends on the TV's AirPlay display settings **Design for 4:3 safe zone** — put critical content in the center 4:3 area. Decorative elements can extend to the edges that may be cropped on some TV settings. ``` ┌──────────────────────────────────────────────────┐ │ │ │ │ │ crop │ 4:3 SAFE ZONE (all content) │ crop │ │ zone │ │ zone │ └──────────────────────────────────────────────────┘ ↑ 16:9 full TV width ```