Files
vitfit-r2/V2/app/public/js/timer-display.js
T
2026-06-30 11:49:26 -04:00

268 lines
10 KiB
JavaScript

/* VitFit timer-display.js — used by timer-display.html */
'use strict';
const TimerDisplay = (() => {
let _socket = null;
let _sessionId = null;
let _localFallbackRaf = null;
let _localEndTime = null;
let _keepAliveEl = null;
let _phaseTotalMs = 0;
const PIE_R = 180;
const PIE_CIRC = 2 * Math.PI * PIE_R; // ≈ 1131
const containerEl = () => document.getElementById('timer-container');
const timerEl = () => document.getElementById('timer-countdown');
const totalEl = () => document.getElementById('timer-total');
const phaseEl = () => document.getElementById('timer-phase-label');
const lapEl = () => document.getElementById('timer-lap');
const exerciseEl = () => document.getElementById('timer-exercise');
const setEl = () => document.getElementById('timer-set');
const overlayEl = () => document.getElementById('timer-overlay');
const overlayTitleEl = () => document.getElementById('timer-overlay-title');
const offlineBanner = () => document.getElementById('display-offline-banner');
const localIndicator = () => document.getElementById('display-local-indicator');
function init(sessionId) {
_sessionId = sessionId;
_socket = new SocketClient();
_socket.onDisconnect(() => {
offlineBanner()?.classList.add('visible');
if (_localEndTime) startLocalFallback(_localEndTime);
});
_socket.onReconnect(async () => {
offlineBanner()?.classList.remove('visible');
localIndicator()?.classList.remove('visible');
stopLocalFallback();
// Re-sync state from server
const res = await Api.get(`/api/v1/timers/session/${_sessionId}`).catch(() => null);
if (res?.ok) {
const { data } = await res.json();
if (data) handleState(data);
}
});
_socket.on('timer:state', handleState);
_socket.on('timer:tick', handleTick);
_socket.on('timer:phase-change', handlePhaseChange);
_socket.on('timer:paused', handlePaused);
_socket.on('timer:complete', handleComplete);
_socket.on('timer:stopped', handleStopped);
_socket.connect();
_socket.joinRoom(sessionId);
_wirePauseMenu();
// AirPlay keep-alive
_keepAliveEl = document.createElement('div');
_keepAliveEl.className = 'keep-alive';
document.body.appendChild(_keepAliveEl);
// Cleanup on unload
window.addEventListener('beforeunload', () => {
_socket.leaveRoom(sessionId);
_socket.destroy();
stopLocalFallback();
});
}
function handleState(state) {
_localEndTime = state.phaseEndTime;
_phaseTotalMs = state.phaseTotalMs || _phaseTotalMs;
setPhaseColor(state.phase, state.phaseRemainingMs);
updateCounters(state);
updatePie(state.phaseRemainingMs, _phaseTotalMs, false);
if (timerEl()) timerEl().textContent = formatTime(state.phaseRemainingMs);
if (totalEl()) totalEl().textContent = 'Total ' + formatTime(state.totalRemainingMs);
// Close pause menu whenever the server sends a fresh running state
document.getElementById('pause-overlay')?.classList.remove('visible');
}
function handleTick(data) {
_localEndTime = data.phaseEndTime || _localEndTime;
_phaseTotalMs = data.phaseTotalMs || _phaseTotalMs;
setPhaseColor(data.phase, data.phaseRemainingMs);
updatePie(data.phaseRemainingMs, _phaseTotalMs, false);
if (timerEl()) timerEl().textContent = formatTime(data.phaseRemainingMs);
if (totalEl()) totalEl().textContent = 'Total ' + formatTime(data.totalRemainingMs);
updateCounters(data);
stopLocalFallback();
}
function handlePhaseChange(data) {
_phaseTotalMs = data.phaseTotalMs || _phaseTotalMs;
_localEndTime = data.phaseEndTime;
document.getElementById('pause-overlay')?.classList.remove('visible');
// Instant-reset ring to full (no transition) then swap the phase color
updatePie(0, 0, true);
setPhaseColor(data.phase, data.phaseRemainingMs);
updateCounters(data);
// Double-RAF: first frame paints transition:none; second frame re-enables it
requestAnimationFrame(() => requestAnimationFrame(() =>
updatePie(data.phaseRemainingMs, _phaseTotalMs, false)
));
}
function handlePaused(state) {
_phaseTotalMs = state.phaseTotalMs || _phaseTotalMs;
setPhaseColor(state.phase, state.phaseRemainingMs);
updateCounters(state);
updatePie(state.phaseRemainingMs, _phaseTotalMs, false);
if (timerEl()) timerEl().textContent = formatTime(state.phaseRemainingMs);
if (totalEl()) totalEl().textContent = 'Total ' + formatTime(state.totalRemainingMs);
document.getElementById('pause-overlay')?.classList.add('visible');
}
function handleComplete() {
stopLocalFallback();
if (timerEl()) timerEl().textContent = '00:00';
updatePie(0, _phaseTotalMs, false); // ring fully depleted at completion
if (overlayTitleEl()) overlayTitleEl().textContent = 'DONE';
overlayEl()?.classList.add('visible');
containerEl()?.classList.add('phase-complete');
}
function handleStopped() {
stopLocalFallback();
window.close();
}
function startLocalFallback(endTimeMs) {
stopLocalFallback();
localIndicator()?.classList.add('visible');
function tick() {
const remaining = Math.max(0, endTimeMs - Date.now());
if (timerEl()) timerEl().textContent = formatTime(remaining);
if (remaining > 0) {
_localFallbackRaf = requestAnimationFrame(tick);
} else {
localIndicator()?.classList.remove('visible');
}
}
_localFallbackRaf = requestAnimationFrame(tick);
}
function stopLocalFallback() {
if (_localFallbackRaf) {
cancelAnimationFrame(_localFallbackRaf);
_localFallbackRaf = null;
}
localIndicator()?.classList.remove('visible');
}
function phaseLabel(phase) {
if (phase === 'set') return 'WORKOUT';
if (phase === 'rest') return 'REST';
if (phase === 'move') return 'MOVE';
return (phase || 'READY').toUpperCase();
}
function updateCounters(state) {
if (phaseEl()) phaseEl().textContent = phaseLabel(state.phase);
if (lapEl()) lapEl().textContent = `LAP ${state.currentLap}/${state.lapCount}`;
if (exerciseEl()) exerciseEl().textContent = `${state.currentExercise}/${state.exerciseCount} EX`;
if (setEl()) setEl().textContent = `SET ${state.currentSet}/${state.setCount}`;
}
function setPhaseColor(phase, remainingMs) {
const container = containerEl();
if (!container) return;
container.className = 'display-container';
// engine uses 'set' for the workout phase; CSS uses 'work'
const displayPhase = phase === 'set' ? 'work' : (phase || 'idle');
container.classList.add(`phase-${displayPhase}`);
// warning overlays on top of the phase class (keeps background color)
if (typeof remainingMs === 'number' && remainingMs <= 10000 && remainingMs > 0) {
container.classList.add('phase-warning');
}
}
function _wirePauseMenu() {
const container = containerEl();
const overlay = document.getElementById('pause-overlay');
const doneOverlay = document.getElementById('timer-overlay');
// Tap/click the display → pause and open menu
container?.addEventListener('click', async (e) => {
if (overlay?.classList.contains('visible')) return; // menu already open
if (doneOverlay?.classList.contains('visible')) return; // timer done
// Ignore clicks that originated from the pause menu itself
if (e.target.closest('#pause-overlay')) return;
try {
await Api.post('/api/v1/timers/session/pause', {});
} catch {}
overlay?.classList.add('visible');
});
async function _menuAction(endpoint) {
overlay?.classList.remove('visible');
try { await Api.post(endpoint, {}); } catch {}
}
document.getElementById('btn-resume')?.addEventListener('click', (e) => {
e.stopPropagation();
overlay?.classList.remove('visible');
Api.post('/api/v1/timers/session/resume', {}).catch(() => {});
});
document.getElementById('btn-restart-set')?.addEventListener('click', (e) => {
e.stopPropagation();
_menuAction('/api/v1/timers/session/restart-set');
});
document.getElementById('btn-restart-lap')?.addEventListener('click', (e) => {
e.stopPropagation();
_menuAction('/api/v1/timers/session/restart-lap');
});
document.getElementById('btn-stop')?.addEventListener('click', (e) => {
e.stopPropagation();
overlay?.classList.remove('visible');
Api.del('/api/v1/timers/session').catch(() => {});
});
}
// Countdown ring: starts FULL and depletes to empty as the phase elapses.
// dasharray=[CIRC,CIRC]: offset=0 → full circle, offset=CIRC → empty.
function updatePie(phaseRemainingMs, phaseTotalMs, instantReset) {
const ring = document.getElementById('pie-ring');
if (!ring) return;
ring.style.strokeDasharray = `${PIE_CIRC} ${PIE_CIRC}`;
if (instantReset) {
// Hard-reset to full with no animation (called at the start of a new phase)
ring.style.transition = 'none';
ring.style.strokeDashoffset = 0; // full
return;
}
ring.style.transition = '';
const remaining = Math.max(0, Math.min(1, phaseTotalMs > 0 ? phaseRemainingMs / phaseTotalMs : 0));
// remaining=1 → offset=0 (full); remaining=0 → offset=CIRC (empty)
ring.style.strokeDashoffset = PIE_CIRC * (1 - remaining);
}
function formatTime(ms) {
if (typeof ms !== 'number' || isNaN(ms)) return '--:--';
const totalSec = Math.max(0, Math.ceil(ms / 1000));
const min = String(Math.floor(totalSec / 60)).padStart(2, '0');
const sec = String(totalSec % 60).padStart(2, '0');
return `${min}:${sec}`;
}
function formatHMS(ms) {
const totalSec = Math.max(0, Math.ceil(ms / 1000));
const h = Math.floor(totalSec / 3600);
const m = Math.floor((totalSec % 3600) / 60);
const s = totalSec % 60;
return `${h}:${String(m).padStart(2,'0')}:${String(s).padStart(2,'0')}`;
}
return { init, handleState, handleTick, handlePhaseChange, handleComplete, handleStopped, startLocalFallback, stopLocalFallback, formatTime, formatHMS, setPhaseColor, updatePie };
})();