This commit is contained in:
Ccjcarkbla
2026-06-30 11:49:26 -04:00
parent e192aecb2f
commit 7a35165bfd
16 changed files with 559 additions and 153 deletions
+4 -3
View File
@@ -7,12 +7,13 @@ const nonNegInt = z.number().int().min(0);
const createTimer = z.object({
name: z.string().min(1).max(200),
totalTime: positiveInt,
timerMode: z.enum(['group', 'crossfit']).optional(),
workoutDate: z.string().optional().nullable(),
exerciseCount: positiveInt,
setCount: positiveInt,
setTime: positiveInt,
restTime: nonNegInt.default(0),
moveTime: nonNegInt.default(0),
setCount: positiveInt,
exerciseCount: positiveInt,
lapCount: positiveInt.default(1),
});
+13
View File
@@ -32,6 +32,19 @@ function init(httpServer) {
io.on('connection', (socket) => {
logger.debug({ userId: socket.data.user?.id }, 'Socket connected');
socket.on('timer:join', ({ sessionId } = {}) => {
if (!sessionId) return;
socket.join(sessionId);
// Lazy require avoids load-time circular dependency
const timerSvc = require('../modules/timers/service');
const engine = timerSvc.getSessionEngine(sessionId);
if (engine) socket.emit('timer:state', engine.getState());
});
socket.on('timer:leave', ({ sessionId } = {}) => {
if (sessionId) socket.leave(sessionId);
});
socket.on('disconnect', (reason) => {
logger.debug({ userId: socket.data.user?.id, reason }, 'Socket disconnected');
});
+9
View File
@@ -48,6 +48,15 @@ router.patch('/', authenticateToken, authenticateRole(OWNERS), validate(updateOr
} catch (err) { next(err); }
});
router.get('/branding/public', async (req, res, next) => {
try {
const org = await models.Organization.findOne({ order: [['id', 'ASC']] });
if (!org) return ok(res, {});
const branding = await svc.getBranding(models, org.id);
ok(res, branding);
} catch (err) { next(err); }
});
router.get('/branding', authenticateToken, async (req, res, next) => {
try {
if (!req.user.organizationId) return ok(res, {});
@@ -0,0 +1,20 @@
'use strict';
module.exports = {
async up(queryInterface, Sequelize) {
const tableDesc = await queryInterface.describeTable('Timers').catch(() => null);
if (!tableDesc) return;
const addIfMissing = async (col, def) => {
if (!tableDesc[col]) await queryInterface.addColumn('Timers', col, def);
};
await addIfMissing('timerMode', { type: Sequelize.STRING });
await addIfMissing('workoutDate', { type: Sequelize.DATEONLY });
},
async down(queryInterface) {
await queryInterface.removeColumn('Timers', 'timerMode').catch(() => {});
await queryInterface.removeColumn('Timers', 'workoutDate').catch(() => {});
},
};
+2
View File
@@ -12,6 +12,8 @@ module.exports = (sequelize, DataTypes) => {
setCount: { type: DataTypes.INTEGER, allowNull: false },
exerciseCount: { type: DataTypes.INTEGER, allowNull: false },
lapCount: { type: DataTypes.INTEGER, defaultValue: 1 },
timerMode: { type: DataTypes.STRING },
workoutDate: { type: DataTypes.DATEONLY },
createdByUserId: { type: DataTypes.INTEGER },
});
+25 -3
View File
@@ -46,6 +46,14 @@ router.get('/session/active', authenticateToken, authenticateRole(COACH_PLUS), a
} catch (err) { next(err); }
});
router.get('/session/:sessionId', authenticateToken, authenticateRole(COACH_PLUS), async (req, res, next) => {
try {
const engine = svc.getSessionEngine(req.params.sessionId);
if (!engine) return next(new AppError('NOT_FOUND', 'Session not found.', 404));
ok(res, engine.getState());
} catch (err) { next(err); }
});
router.get('/:id', authenticateToken, authenticateRole(COACH_PLUS), async (req, res, next) => {
try {
const timer = await svc.getTimerById(models, parseInt(req.params.id, 10), req.user.organizationId);
@@ -55,13 +63,27 @@ router.get('/:id', authenticateToken, authenticateRole(COACH_PLUS), async (req,
router.delete('/session', authenticateToken, authenticateRole(COACH_PLUS), async (req, res, next) => {
try {
const { sessionId } = req.body;
if (!sessionId) return next(new AppError('VALIDATION_FAILED', 'sessionId required.', 400));
await svc.stopTimer(req, sessionId, req.user.organizationId);
await svc.stopActiveSession(req, req.user.organizationId);
noContent(res);
} catch (err) { next(err); }
});
router.post('/session/pause', authenticateToken, authenticateRole(COACH_PLUS), async (req, res, next) => {
try { svc.pauseSession(req.user.organizationId); noContent(res); } catch (err) { next(err); }
});
router.post('/session/resume', authenticateToken, authenticateRole(COACH_PLUS), async (req, res, next) => {
try { svc.resumeSession(req.user.organizationId); noContent(res); } catch (err) { next(err); }
});
router.post('/session/restart-set', authenticateToken, authenticateRole(COACH_PLUS), async (req, res, next) => {
try { svc.restartSet(req.user.organizationId); noContent(res); } catch (err) { next(err); }
});
router.post('/session/restart-lap', authenticateToken, authenticateRole(COACH_PLUS), async (req, res, next) => {
try { svc.restartLap(req.user.organizationId); noContent(res); } catch (err) { next(err); }
});
router.delete('/:id', authenticateToken, authenticateRole(COACH_PLUS), async (req, res, next) => {
try {
await svc.deleteTimer(models, req, parseInt(req.params.id, 10), req.user.organizationId);
+46 -9
View File
@@ -19,7 +19,9 @@ async function getTimerById(models, id, orgId) {
}
async function createTimer(models, req, orgId, data) {
const timer = await models.Timer.create({ ...data, organizationId: orgId, createdByUserId: req.user.id });
const { exerciseCount, setCount, setTime, restTime, moveTime, lapCount } = data;
const totalTime = lapCount * (exerciseCount * (setCount * setTime + (setCount - 1) * restTime) + (exerciseCount - 1) * moveTime);
const timer = await models.Timer.create({ ...data, totalTime, organizationId: orgId, createdByUserId: req.user.id });
await auditLog(req, 'timer.create', 'timer', timer.id, { name: data.name });
return timer;
}
@@ -57,14 +59,18 @@ async function launchTimer(models, req, timerId, orgId) {
return { sessionId };
}
async function stopTimer(req, sessionId, orgId) {
const session = activeSessions.get(sessionId);
if (!session || session.orgId !== orgId) {
throw new AppError('NOT_FOUND', 'Active timer session not found.', 404);
async function stopActiveSession(req, orgId) {
let found = false;
for (const [sessionId, session] of activeSessions) {
if (session.orgId === orgId) {
session.engine.stop();
activeSessions.delete(sessionId);
await auditLog(req, 'timer.stop', null, null, { sessionId });
found = true;
break;
}
}
session.engine.stop();
activeSessions.delete(sessionId);
await auditLog(req, 'timer.stop', null, null, { sessionId });
if (!found) throw new AppError('NOT_FOUND', 'No active timer session found.', 404);
}
function getActiveSession(orgId) {
@@ -80,4 +86,35 @@ function getSessionEngine(sessionId) {
return activeSessions.get(sessionId)?.engine ?? null;
}
module.exports = { getTimers, getTimerById, createTimer, deleteTimer, launchTimer, stopTimer, getActiveSession, getSessionEngine };
function _getActiveEngine(orgId) {
for (const [, session] of activeSessions) {
if (session.orgId === orgId) return session.engine;
}
return null;
}
function pauseSession(orgId) {
const engine = _getActiveEngine(orgId);
if (!engine) throw new AppError('NOT_FOUND', 'No active timer session.', 404);
engine.pause();
}
function resumeSession(orgId) {
const engine = _getActiveEngine(orgId);
if (!engine) throw new AppError('NOT_FOUND', 'No active timer session.', 404);
engine.resume();
}
function restartSet(orgId) {
const engine = _getActiveEngine(orgId);
if (!engine) throw new AppError('NOT_FOUND', 'No active timer session.', 404);
engine.restartSet();
}
function restartLap(orgId) {
const engine = _getActiveEngine(orgId);
if (!engine) throw new AppError('NOT_FOUND', 'No active timer session.', 404);
engine.restartLap();
}
module.exports = { getTimers, getTimerById, createTimer, deleteTimer, launchTimer, stopActiveSession, getActiveSession, getSessionEngine, pauseSession, resumeSession, restartSet, restartLap };
+98 -7
View File
@@ -37,14 +37,94 @@ class TimerEngine {
this.io.to(this.roomId).emit('timer:stopped', { sessionId: this.roomId });
}
pause() {
if (this.status !== 'running') return;
const now = process.hrtime.bigint();
this._pausedPhaseRemainingMs = Math.max(0, Number((this.phaseEndTime - now) / NS_PER_MS));
this._pausedTotalRemainingMs = Math.max(0, Number((this.sessionEndTime - now) / NS_PER_MS));
this._clearInterval();
this.status = 'paused';
this.io.to(this.roomId).emit('timer:paused', this._snapshot());
}
resume() {
if (this.status !== 'paused') return;
const now = process.hrtime.bigint();
this.phaseEndTime = now + BigInt(Math.round(this._pausedPhaseRemainingMs)) * NS_PER_MS;
this.sessionEndTime = now + BigInt(Math.round(this._pausedTotalRemainingMs)) * NS_PER_MS;
this.status = 'running';
this._lastEmittedSecond = -1;
this._interval = setInterval(() => this._tick(), 100);
this.io.to(this.roomId).emit('timer:state', this._snapshot());
}
restartSet() {
const now = process.hrtime.bigint();
this.phase = 'set';
this._lastEmittedSecond = -1;
this.phaseEndTime = now + BigInt(this.config.setTime) * NS_PER_MS * BigInt(1000);
if (this.status === 'paused') {
this._pausedPhaseRemainingMs = this.config.setTime * 1000;
this.io.to(this.roomId).emit('timer:paused', this._snapshot());
} else {
if (this.status !== 'running') {
this.status = 'running';
this._interval = setInterval(() => this._tick(), 100);
}
this.io.to(this.roomId).emit('timer:phase-change', this._snapshot());
}
}
restartLap() {
const { setTime, restTime, moveTime, setCount, exerciseCount, lapCount } = this.config;
const now = process.hrtime.bigint();
this.currentSet = 1;
this.currentExercise = 1;
this.phase = 'set';
this._lastEmittedSecond = -1;
this.phaseEndTime = now + BigInt(setTime) * NS_PER_MS * BigInt(1000);
const remainingLaps = lapCount - this.currentLap + 1;
const lapSec = exerciseCount * (setCount * setTime + Math.max(0, setCount - 1) * restTime)
+ Math.max(0, exerciseCount - 1) * moveTime;
const totalRemainingMs = remainingLaps * lapSec * 1000;
this.sessionEndTime = now + BigInt(Math.round(totalRemainingMs)) * NS_PER_MS;
if (this.status === 'paused') {
this._pausedPhaseRemainingMs = setTime * 1000;
this._pausedTotalRemainingMs = totalRemainingMs;
this.io.to(this.roomId).emit('timer:paused', this._snapshot());
} else {
if (this.status !== 'running') {
this.status = 'running';
this._interval = setInterval(() => this._tick(), 100);
}
this.io.to(this.roomId).emit('timer:state', this._snapshot());
}
}
getState() {
return this._snapshot();
}
_phaseTotalMs() {
const { setTime, restTime, moveTime } = this.config;
if (this.phase === 'set') return setTime * 1000;
if (this.phase === 'rest') return restTime * 1000;
return moveTime * 1000;
}
_snapshot() {
const now = process.hrtime.bigint();
const phaseRemainingMs = Number((this.phaseEndTime - now) / NS_PER_MS);
const totalRemainingMs = Number((this.sessionEndTime - now) / NS_PER_MS);
let phaseRemainingMs, totalRemainingMs;
if (this.status === 'paused') {
phaseRemainingMs = this._pausedPhaseRemainingMs ?? 0;
totalRemainingMs = this._pausedTotalRemainingMs ?? 0;
} else {
const now = process.hrtime.bigint();
phaseRemainingMs = Number((this.phaseEndTime - now) / NS_PER_MS);
totalRemainingMs = Number((this.sessionEndTime - now) / NS_PER_MS);
}
return {
status: this.status,
phase: this.phase,
@@ -56,6 +136,10 @@ class TimerEngine {
setCount: this.config.setCount,
phaseRemainingMs: Math.max(0, phaseRemainingMs),
totalRemainingMs: Math.max(0, totalRemainingMs),
phaseTotalMs: this._phaseTotalMs(),
setTimeMs: this.config.setTime * 1000,
restTimeMs: this.config.restTime * 1000,
moveTimeMs: this.config.moveTime * 1000,
phaseEndTime: Number(this.phaseEndTime / NS_PER_MS), // ms epoch
};
}
@@ -73,10 +157,17 @@ class TimerEngine {
this.io.to(this.roomId).emit('timer:tick', {
phaseRemainingMs: Math.max(0, phaseRemainingMs),
totalRemainingMs: Math.max(0, totalRemainingMs),
phase: this.phase,
currentLap: this.currentLap,
currentExercise: this.currentExercise,
currentSet: this.currentSet,
phaseTotalMs: this._phaseTotalMs(),
setTimeMs: this.config.setTime * 1000,
restTimeMs: this.config.restTime * 1000,
moveTimeMs: this.config.moveTime * 1000,
phase: this.phase,
currentLap: this.currentLap,
currentExercise: this.currentExercise,
currentSet: this.currentSet,
lapCount: this.config.lapCount,
exerciseCount: this.config.exerciseCount,
setCount: this.config.setCount,
});
}
+35 -84
View File
@@ -30,84 +30,48 @@
<label class="form-label" for="name">Timer Name <span class="required">*</span></label>
<input class="form-input" type="text" id="name" maxlength="80" required>
</div>
<div class="form-group">
<label class="form-label" for="timer-type">Type <span class="required">*</span></label>
<select class="form-select" id="timer-type">
<option value="interval">Interval (Work / Rest)</option>
<option value="amrap">AMRAP</option>
<option value="emom">EMOM</option>
<option value="tabata">Tabata</option>
</select>
<div class="grid-2">
<div class="form-group">
<label class="form-label" for="timer-mode">Mode <span class="required">*</span></label>
<select class="form-select" id="timer-mode">
<option value="group">Group</option>
<option value="crossfit">CrossFit</option>
</select>
</div>
<div class="form-group">
<label class="form-label" for="workout-date">Workout Date</label>
<input class="form-input" type="date" id="workout-date">
</div>
</div>
</div>
<!-- Interval -->
<div class="card timer-config" id="config-interval" style="margin-bottom:var(--space-6);">
<div class="card" style="margin-bottom:var(--space-6);">
<div class="grid-2">
<div class="form-group">
<label class="form-label">Exercises per Set</label>
<label class="form-label">Exercises in Workout</label>
<input class="form-input" type="number" id="exerciseCount" min="1" value="1">
</div>
<div class="form-group">
<label class="form-label">Sets</label>
<input class="form-input" type="number" id="sets" min="1" value="3">
<input class="form-input" type="number" id="setCount" min="1" value="3">
</div>
<div class="form-group">
<label class="form-label">Work (seconds)</label>
<input class="form-input" type="number" id="workSec" min="1" value="40">
<input class="form-input" type="number" id="setTime" min="1" value="40">
</div>
<div class="form-group">
<label class="form-label">Rest (seconds)</label>
<input class="form-input" type="number" id="restSec" min="0" value="20">
<input class="form-input" type="number" id="restTime" min="0" value="20">
</div>
<div class="form-group">
<label class="form-label">Move time (seconds)</label>
<input class="form-input" type="number" id="moveSec" min="0" value="10">
<p class="form-hint">Time between exercises to transition.</p>
<input class="form-input" type="number" id="moveTime" min="0" value="10">
<p class="form-hint">Time to transition to next exercise.</p>
</div>
<div class="form-group">
<label class="form-label">Laps</label>
<input class="form-input" type="number" id="laps" min="1" value="1">
</div>
</div>
</div>
<!-- AMRAP -->
<div class="card timer-config" id="config-amrap" style="margin-bottom:var(--space-6);display:none;">
<div class="form-group">
<label class="form-label">Duration (minutes)</label>
<input class="form-input" type="number" id="amrapDuration" min="1" value="10">
</div>
</div>
<!-- EMOM -->
<div class="card timer-config" id="config-emom" style="margin-bottom:var(--space-6);display:none;">
<div class="grid-2">
<div class="form-group">
<label class="form-label">Rounds</label>
<input class="form-input" type="number" id="emomRounds" min="1" value="10">
</div>
<div class="form-group">
<label class="form-label">Exercises per round</label>
<input class="form-input" type="number" id="emomExercises" min="1" value="1">
</div>
</div>
</div>
<!-- Tabata -->
<div class="card timer-config" id="config-tabata" style="margin-bottom:var(--space-6);display:none;">
<div class="grid-2">
<div class="form-group">
<label class="form-label">Rounds</label>
<input class="form-input" type="number" id="tabataRounds" min="1" value="8">
</div>
<div class="form-group">
<label class="form-label">Work (seconds)</label>
<input class="form-input" type="number" id="tabataWork" min="1" value="20">
</div>
<div class="form-group">
<label class="form-label">Rest (seconds)</label>
<input class="form-input" type="number" id="tabataRest" min="0" value="10">
<input class="form-input" type="number" id="lapCount" min="1" value="1">
<p class="form-hint">Times through all exercises.</p>
</div>
</div>
</div>
@@ -123,46 +87,33 @@
<script src="/js/core.js"></script>
<script>
function showConfig(type) {
document.querySelectorAll('.timer-config').forEach(el => el.style.display = 'none');
const el = document.getElementById(`config-${type}`);
if (el) el.style.display = '';
}
function buildConfig(type) {
if (type === 'interval') return {
exerciseCount: +document.getElementById('exerciseCount').value,
sets: +document.getElementById('sets').value,
workSec: +document.getElementById('workSec').value,
restSec: +document.getElementById('restSec').value,
moveSec: +document.getElementById('moveSec').value,
laps: +document.getElementById('laps').value,
};
if (type === 'amrap') return { durationMin: +document.getElementById('amrapDuration').value };
if (type === 'emom') return { rounds: +document.getElementById('emomRounds').value, exercisesPerRound: +document.getElementById('emomExercises').value };
if (type === 'tabata') return { rounds: +document.getElementById('tabataRounds').value, workSec: +document.getElementById('tabataWork').value, restSec: +document.getElementById('tabataRest').value };
return {};
}
document.addEventListener('DOMContentLoaded', async () => {
await Page.init(['Owner', 'Coach']);
const typeEl = document.getElementById('timer-type');
typeEl.addEventListener('change', () => showConfig(typeEl.value));
showConfig(typeEl.value);
document.getElementById('timer-form').addEventListener('submit', async (e) => {
e.preventDefault();
const errEl = document.getElementById('form-error');
errEl.style.display = 'none';
const btn = document.getElementById('save-btn');
const type = typeEl.value;
const name = document.getElementById('name').value.trim();
if (!name) { errEl.textContent = 'Name is required.'; errEl.style.display = 'block'; return; }
const payload = {
name,
timerMode: document.getElementById('timer-mode').value,
workoutDate: document.getElementById('workout-date').value || null,
exerciseCount: +document.getElementById('exerciseCount').value,
setCount: +document.getElementById('setCount').value,
setTime: +document.getElementById('setTime').value,
restTime: +document.getElementById('restTime').value,
moveTime: +document.getElementById('moveTime').value,
lapCount: +document.getElementById('lapCount').value,
};
btn.disabled = true; btn.textContent = 'Saving…';
try {
const res = await Api.post('/api/v1/timers', { name, timerType: type, config: buildConfig(type) });
const res = await Api.post('/api/v1/timers', payload);
if (res.ok) {
toast('Timer saved!', 'success');
setTimeout(() => window.location.href = '/timers.html', 800);
+113 -10
View File
@@ -7,6 +7,10 @@ const TimerDisplay = (() => {
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');
@@ -44,12 +48,15 @@ const TimerDisplay = (() => {
_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';
@@ -64,16 +71,22 @@ const TimerDisplay = (() => {
}
function handleState(state) {
_localEndTime = state.phaseEndTime; // ms epoch from server
_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);
@@ -81,14 +94,33 @@ const TimerDisplay = (() => {
}
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);
_localEndTime = data.phaseEndTime;
// 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');
@@ -96,8 +128,7 @@ const TimerDisplay = (() => {
function handleStopped() {
stopLocalFallback();
if (overlayTitleEl()) overlayTitleEl().textContent = 'STOPPED';
overlayEl()?.classList.add('visible');
window.close();
}
function startLocalFallback(endTimeMs) {
@@ -124,8 +155,15 @@ const TimerDisplay = (() => {
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 = (state.phase || '').toUpperCase();
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}`;
@@ -136,14 +174,79 @@ const TimerDisplay = (() => {
if (!container) return;
container.className = 'display-container';
const isWarning = typeof remainingMs === 'number' && remainingMs <= 10000 && remainingMs > 0;
if (isWarning) {
// 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');
} else {
container.classList.add(`phase-${phase || 'idle'}`);
}
}
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));
@@ -160,5 +263,5 @@ const TimerDisplay = (() => {
return `${h}:${String(m).padStart(2,'0')}:${String(s).padStart(2,'0')}`;
}
return { init, handleState, handleTick, handlePhaseChange, handleComplete, handleStopped, startLocalFallback, stopLocalFallback, formatTime, formatHMS, setPhaseColor };
return { init, handleState, handleTick, handlePhaseChange, handleComplete, handleStopped, startLocalFallback, stopLocalFallback, formatTime, formatHMS, setPhaseColor, updatePie };
})();
+2 -2
View File
@@ -11,8 +11,8 @@ a { color: inherit; text-decoration: none; }
--color-primary: #00FF88;
--color-secondary: #4488FF;
--color-work: #00FF88;
--color-rest: #4488FF;
--color-move: #FF4444;
--color-rest: #FF4444;
--color-move: #FFAA00;
--color-warning: #FFAA00;
--color-complete: #FFFFFF;
--color-idle: #FFFFFF;
+121 -14
View File
@@ -26,30 +26,29 @@ html, body {
display: flex;
flex-direction: column;
position: relative;
background-color: var(--display-bg);
transition: background-color var(--transition-phase);
}
.phase-work { background-color: #061a0e; }
.phase-rest { background-color: #1a0606; }
.phase-move { background-color: #1a1300; }
.phase-idle { background-color: var(--display-bg); }
/* ── Status bar (top strip) ───────────────────────────────────────────────── */
/* ── Status bar (top strip — LAP/EX/SET only) ────────────────────────────── */
.display-status-bar {
display: flex;
align-items: center;
justify-content: space-between;
justify-content: flex-end;
padding: var(--space-4) var(--space-8);
height: 64px;
flex-shrink: 0;
}
.display-status-label {
font-size: var(--display-font-label);
font-weight: var(--weight-bold);
text-transform: uppercase;
letter-spacing: 0.06em;
transition: color var(--transition-phase);
}
.display-status-right {
display: flex;
gap: var(--space-8);
font-size: var(--display-font-label);
font-weight: var(--weight-medium);
color: var(--text-secondary);
font-weight: var(--weight-semibold);
color: #ffffff;
}
/* ── Main timer display ───────────────────────────────────────────────────── */
@@ -63,13 +62,70 @@ html, body {
text-align: center;
}
/* ── Radial pie analog clock ──────────────────────────────────────────────── */
/* CSS grid stacks SVG + timer text in the same cell so both are centered */
.display-pie-wrapper {
display: grid;
place-items: center;
width: min(55vw, 55vh);
height: min(55vw, 55vh);
}
.display-pie-svg {
grid-area: 1 / 1;
width: 100%;
height: 100%;
transform: rotate(-90deg); /* arc starts at 12 o'clock */
pointer-events: none;
}
.display-pie-track {
fill: none;
stroke: rgba(255, 255, 255, 0.07);
stroke-width: 20;
}
/* Fill ring — grows from empty to full as the phase elapses.
Color is set per phase via the container class on .display-container. */
.display-pie-fill {
fill: none;
stroke-width: 20;
stroke-linecap: round;
stroke: rgba(255, 255, 255, 0.4);
transition: stroke-dashoffset 1s linear, stroke var(--transition-phase);
}
.phase-work .display-pie-fill { stroke: var(--color-work); }
.phase-rest .display-pie-fill { stroke: var(--color-rest); }
.phase-move .display-pie-fill { stroke: var(--color-move); }
/* ── Phase label (below the ring) ────────────────────────────────────────── */
.display-phase-label {
font-size: var(--display-font-secondary);
font-weight: var(--weight-bold);
text-transform: uppercase;
letter-spacing: 0.1em;
margin-top: var(--space-6);
color: rgba(255, 255, 255, 0.5);
transition: color var(--transition-phase);
}
.phase-work .display-phase-label { color: var(--color-work); }
.phase-rest .display-phase-label { color: var(--color-rest); }
.phase-move .display-phase-label { color: var(--color-move); }
.phase-warning .display-phase-label { color: var(--color-warning); }
.display-timer {
grid-area: 1 / 1; /* sits in same grid cell as the SVG */
position: relative;
z-index: 1;
font-size: var(--display-font-primary);
font-weight: var(--weight-black);
line-height: 1;
letter-spacing: -2px;
transition: color var(--transition-phase);
font-variant-numeric: tabular-nums;
text-align: center;
}
.display-exercise {
@@ -203,17 +259,68 @@ html, body {
.touch-zone-left { left: 0; }
.touch-zone-right { right: 0; }
/* ── Pause menu overlay ──────────────────────────────────────────────────── */
.display-pause-overlay {
position: absolute;
inset: 0;
background: rgba(0, 0, 0, 0.78);
display: none;
flex-direction: column;
align-items: center;
justify-content: center;
z-index: var(--z-modal);
}
.display-pause-overlay.visible { display: flex; }
.display-pause-menu {
display: flex;
flex-direction: column;
gap: var(--space-5);
width: 420px;
max-width: 80vw;
}
.display-pause-btn {
background: rgba(255, 255, 255, 0.08);
border: 2px solid rgba(255, 255, 255, 0.25);
color: #ffffff;
font-size: var(--display-font-label);
font-weight: var(--weight-bold);
padding: var(--space-5) var(--space-8);
border-radius: var(--radius-lg);
cursor: pointer;
text-align: center;
text-transform: uppercase;
letter-spacing: 0.06em;
transition: background var(--transition-fast), border-color var(--transition-fast);
-webkit-tap-highlight-color: transparent;
}
.display-pause-btn:hover,
.display-pause-btn:active {
background: rgba(255, 255, 255, 0.18);
border-color: rgba(255, 255, 255, 0.55);
}
.display-pause-btn-stop {
border-color: rgba(255, 68, 68, 0.4);
color: var(--color-rest);
}
.display-pause-btn-stop:hover,
.display-pause-btn-stop:active {
background: rgba(255, 68, 68, 0.15);
border-color: var(--color-rest);
}
/* ── Done / stopped overlay ─────────────────────────────────────────────── */
.display-overlay {
position: absolute;
inset: 0;
background: rgba(26,26,26,0.92);
display: flex;
background: rgba(10, 10, 10, 0.96);
display: none;
flex-direction: column;
align-items: center;
justify-content: center;
gap: var(--space-6);
display: none;
z-index: var(--z-modal); /* above the grid timer (z-index:1) */
}
.display-overlay.visible { display: flex; }
.display-overlay-title {
+20 -4
View File
@@ -9,9 +9,8 @@
</head>
<body>
<div class="display-container phase-idle" id="timer-container">
<!-- Status bar: phase label + counters -->
<!-- Status bar: lap/exercise/set counters only -->
<div class="display-status-bar">
<span class="display-status-label" id="timer-phase-label">READY</span>
<div class="display-status-right">
<span id="timer-lap">LAP 1/1</span>
<span id="timer-exercise">1/1 EX</span>
@@ -21,11 +20,28 @@
<!-- Main countdown -->
<div class="display-main">
<div class="display-timer" id="timer-countdown">--:--</div>
<div class="display-exercise" id="timer-exercise-name"></div>
<div class="display-pie-wrapper">
<svg class="display-pie-svg" viewBox="0 0 400 400" aria-hidden="true">
<circle class="display-pie-track" cx="200" cy="200" r="180"/>
<circle class="display-pie-fill" id="pie-ring" cx="200" cy="200" r="180"/>
</svg>
<div class="display-timer" id="timer-countdown">--:--</div>
</div>
<!-- Phase label below the ring -->
<div class="display-phase-label" id="timer-phase-label">READY</div>
<div class="display-total-time" id="timer-total"></div>
</div>
<!-- Pause menu overlay (tap/click to open) -->
<div class="display-pause-overlay" id="pause-overlay">
<div class="display-pause-menu">
<button class="display-pause-btn" id="btn-resume">&#9654; Resume</button>
<button class="display-pause-btn" id="btn-restart-set">&#8635; Restart Set</button>
<button class="display-pause-btn" id="btn-restart-lap">&#8635; Restart Lap</button>
<button class="display-pause-btn display-pause-btn-stop" id="btn-stop">&#9632; Stop Timer</button>
</div>
</div>
<!-- Done/stopped overlay -->
<div class="display-overlay" id="timer-overlay">
<div class="display-overlay-title" id="timer-overlay-title">DONE</div>
+51 -17
View File
@@ -19,8 +19,8 @@
<nav class="nav-drawer" id="nav-drawer"><ul class="nav-list" id="nav-list"></ul></nav>
<main class="main-content">
<div class="page-header">
<h1 class="page-title">Timers</h1>
<div style="text-align:center; margin-bottom:var(--space-6);">
<h1 class="page-title" style="margin-bottom:var(--space-3);">Timers</h1>
<a href="/create-timer.html" class="btn btn-primary">Create Timer</a>
</div>
@@ -64,21 +64,44 @@
} catch {}
}
function formatDate(d) {
if (!d) return '—';
const dt = new Date(d);
return dt.toLocaleDateString(undefined, { month: 'short', day: 'numeric', year: 'numeric' });
}
function timerSummary(t) {
const parts = [];
if (t.exerciseCount) parts.push(`${t.exerciseCount} exercises`);
if (t.setCount) parts.push(`${t.setCount} sets`);
if (t.setTime) parts.push(`${t.setTime}s work`);
if (t.restTime) parts.push(`${t.restTime}s rest`);
if (t.lapCount > 1) parts.push(`${t.lapCount} laps`);
return parts.join(' · ');
}
async function loadTimers() {
const el = document.getElementById('timer-list');
try {
const res = await Api.get('/api/v1/timers');
if (!res.ok) { el.innerHTML = '<div class="empty-state"><p class="empty-state-text">Failed to load.</p></div>'; return; }
const { data } = await res.json();
if (!data.length) { el.innerHTML = '<div class="empty-state"><p class="empty-state-text">No timers yet.</p><a href="/create-timer.html" class="btn btn-primary">Create one</a></div>'; return; }
if (!data.length) {
el.innerHTML = '<div class="empty-state"><p class="empty-state-text">No timers yet.</p><a href="/create-timer.html" class="btn btn-primary">Create one</a></div>';
return;
}
el.innerHTML = `<table class="table"><thead><tr><th>Name</th><th>Type</th><th>Config</th><th></th></tr></thead><tbody>
el.innerHTML = `<table class="table"><thead><tr>
<th>Name</th><th>Mode</th><th>Date</th><th>Config</th><th></th>
</tr></thead><tbody>
${data.map(t => `<tr>
<td>${t.name}</td>
<td>${t.timerType}</td>
<td>${t.timerMode ? t.timerMode.charAt(0).toUpperCase() + t.timerMode.slice(1) : '—'}</td>
<td>${formatDate(t.workoutDate)}</td>
<td>${timerSummary(t)}</td>
<td class="table-actions">
<button class="btn btn-primary btn-sm" data-action="launch" data-id="${t.id}" data-name="${t.name.replace(/"/g, '&quot;')}">Launch</button>
<button class="btn btn-danger btn-sm" data-action="delete" data-id="${t.id}" data-name="${t.name.replace(/"/g, '&quot;')}">Delete</button>
</td>
</tr>`).join('')}
</tbody></table>`;
@@ -87,15 +110,6 @@
}
}
function timerSummary(t) {
const c = t.config || {};
if (t.timerType === 'interval') return `${c.sets ?? '?'}×${c.exerciseCount ?? '?'} ex | ${c.workSec ?? '?'}s work / ${c.restSec ?? '?'}s rest`;
if (t.timerType === 'amrap') return `${c.durationMin ?? '?'} min`;
if (t.timerType === 'emom') return `${c.rounds ?? '?'} rounds`;
if (t.timerType === 'tabata') return `${c.rounds ?? '?'} rounds`;
return '';
}
async function launchTimer(id, name) {
if (_activeSession) {
if (!confirm('A timer is already running. Stop it and launch this one?')) return;
@@ -115,12 +129,32 @@
} catch { toast('Network error.', 'error'); }
}
async function deleteTimer(id, name) {
if (!confirm(`Delete "${name}"? This cannot be undone.`)) return;
try {
const res = await Api.del(`/api/v1/timers/${id}`);
if (res.ok || res.status === 204) {
toast(`${name} deleted.`, 'success');
loadTimers();
} else {
const b = await res.json();
toast(b.message || 'Failed to delete.', 'error');
}
} catch { toast('Network error.', 'error'); }
}
document.addEventListener('DOMContentLoaded', async () => {
await Page.init(['Owner', 'Coach']);
document.getElementById('timer-list').addEventListener('click', (e) => {
const btn = e.target.closest('button[data-action="launch"]');
if (btn) launchTimer(parseInt(btn.dataset.id, 10), btn.dataset.name);
const btn = e.target.closest('button[data-action]');
if (!btn) return;
const id = parseInt(btn.dataset.id, 10);
const name = btn.dataset.name;
if (btn.dataset.action === 'launch') launchTimer(id, name);
if (btn.dataset.action === 'delete') deleteTimer(id, name);
});
loadActiveSession();
loadTimers();
@@ -128,7 +162,7 @@
if (!confirm('Stop the running timer?')) return;
try {
const res = await Api.del('/api/v1/timers/session');
if (res.ok) { toast('Timer stopped.', 'success'); loadActiveSession(); }
if (res.ok || res.status === 204) { toast('Timer stopped.', 'success'); loadActiveSession(); }
else { const b = await res.json(); toast(b.message || 'Failed.', 'error'); }
} catch { toast('Network error.', 'error'); }
});
Binary file not shown.
Binary file not shown.