Skip to content
Open
3 changes: 3 additions & 0 deletions api/openapi.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -3198,6 +3198,9 @@ paths:
type: string
maxLength: 120
description: The set waiting after the rest, in the person's language ("Bench press, 80 kg × 8"). It becomes the push's body, one line of plain text cut at 120 characters. Optional; without it the body is the general "Time for your next set."
timer:
type: boolean
description: The workout's own Timer, not a rest after a set. The push then says the time is up ("Time’s up ⏱️", "Your timer has finished.") and `next` is ignored. Optional.
example: { seconds: 90, deviceId: "3f9c1d2e7b0a4c6d9e8f1a2b3c4d5e6f", next: "Bench press, 80 kg × 8" }
responses:
'200':
Expand Down
14 changes: 12 additions & 2 deletions api/push-messages.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ const COPY = {
en: {
restTitle: 'Rest over 💪',
restBody: 'Time for your next set.',
timerTitle: 'Time’s up ⏱️',
timerBody: 'Your timer has finished.',
testBody: 'Test notification ✅ This is what alerts look like.',
dayFallbackTitle: 'Workout planned today',
dayRoutineSuffix: 'today',
Expand All @@ -13,6 +15,8 @@ const COPY = {
'pt-BR': {
restTitle: 'Descanso terminado 💪',
restBody: 'Hora da próxima série.',
timerTitle: 'Acabou o tempo ⏱️',
timerBody: 'Seu timer terminou.',
testBody: 'Notificação de teste ✅ É assim que os alertas aparecem.',
dayFallbackTitle: 'Treino planejado para hoje',
dayRoutineSuffix: 'hoje',
Expand All @@ -21,6 +25,8 @@ const COPY = {
id: {
restTitle: 'Istirahat selesai 💪',
restBody: 'Saatnya set berikutnya.',
timerTitle: 'Waktu habis ⏱️',
timerBody: 'Timer kamu sudah selesai.',
testBody: 'Notifikasi uji coba ✅ Begini tampilan notifikasinya.',
dayFallbackTitle: 'Jadwal latihan hari ini',
dayRoutineSuffix: 'hari ini',
Expand All @@ -29,6 +35,8 @@ const COPY = {
cs: {
restTitle: 'Pauza skončila 💪',
restBody: 'Čas na další sérii.',
timerTitle: 'Čas vypršel ⏱️',
timerBody: 'Časovač doběhl.',
testBody: 'Testovací oznámení ✅ Takhle vypadají upozornění.',
dayFallbackTitle: 'Dnes máš v plánu trénink',
dayRoutineSuffix: 'dnes',
Expand Down Expand Up @@ -59,9 +67,11 @@ export function routineEmoji(value) {
}

/** The end of a rest. `next` is the set waiting ("Bench press, 80 kg × 8"), already in the
* person's language from the app; without one the body says it in general words. */
export function restTimerPush(lang, next = null) {
* person's language from the app; without one the body says it in general words. `timer`: the
* workout's own Timer ran out, not a rest, so the push says that and names no set. */
export function restTimerPush(lang, next = null, { timer = false } = {}) {
const copy = copyFor(lang);
if (timer) return { title: copy.timerTitle, body: copy.timerBody, tag: 'rest-timer' };
const line = cleanNext(next);
return { title: copy.restTitle, body: line || copy.restBody, tag: 'rest-timer' };
}
Expand Down
6 changes: 3 additions & 3 deletions api/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -405,7 +405,7 @@ const restKey = (userId, deviceId) => `${userId}:${deviceId || ''}`;
// devices they train with. Each request with a new id used to leave another hour-long timer (and
// its push to every id-less subscription) behind, without limit; past this many, the oldest goes.
const MAX_REST_TIMERS_PER_USER = 5;
function scheduleRestTimer(userId, deviceId, sec, lang, next = null) {
function scheduleRestTimer(userId, deviceId, sec, lang, next = null, timer = false) {
const k = restKey(userId, deviceId);
const t = restTimers.get(k);
if (t) clearTimeout(t);
Expand All @@ -416,7 +416,7 @@ function scheduleRestTimer(userId, deviceId, sec, lang, next = null) {
}
restTimers.set(k, setTimeout(() => {
restTimers.delete(k);
sendPush(userId, restTimerPush(lang, next), deviceId);
sendPush(userId, restTimerPush(lang, next, { timer }), deviceId);
}, sec * 1000));
}
function cancelRestTimer(userId, deviceId) {
Expand Down Expand Up @@ -3318,7 +3318,7 @@ const routes = {
const n = typeof raw === 'number' || typeof raw === 'string' ? Number(raw) : NaN;
if (!(n >= 1)) return json(res, 400, { error: 'seconds required' });
const sec = Math.min(3600, Math.round(n));
scheduleRestTimer(user.id, deviceIdOf(body.deviceId), sec, readStateCached(user.id)?.lang, typeof body.next === 'string' ? body.next : null);
scheduleRestTimer(user.id, deviceIdOf(body.deviceId), sec, readStateCached(user.id)?.lang, typeof body.next === 'string' ? body.next : null, body.timer === true);
json(res, 200, { ok: true });
},

Expand Down
13 changes: 13 additions & 0 deletions api/test/push-messages.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,19 @@ test('localizes every server-generated notification in pt-BR', () => {
});
});

test('the workout Timer\'s end says the time is up and names no next set', () => {
assert.deepEqual(restTimerPush('en', 'Bench press, 80 kg × 8', { timer: true }), {
title: 'Time’s up ⏱️',
body: 'Your timer has finished.',
tag: 'rest-timer',
});
for (const lang of ['pt-BR', 'id', 'cs']) {
const p = restTimerPush(lang, null, { timer: true });
assert.notEqual(p.title, restTimerPush(lang).title);
assert.ok(p.body);
}
});

test('localizes every server-generated notification in id', () => {
assert.deepEqual(restTimerPush('id'), {
title: 'Istirahat selesai 💪',
Expand Down
2 changes: 1 addition & 1 deletion frontend/src/components/RestTimer.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ export function applyRestLeft(v, opened) {
const now = ui.timer
if (!now) { if (v > 0) ui.startRest(v); return }
if (v <= 0) { ui.skipRest(); return }
if (now.ready) { ui.startRest(v, now.forIdx, { forSet: now.forSet, rest: now.rk }); return }
if (now.ready) { ui.startRest(v, now.forIdx, { forSet: now.forSet, rest: now.rk, clock: now.clock }); return }
if (v !== now.left) ui.addRest(v - now.left)
}

Expand Down
127 changes: 127 additions & 0 deletions frontend/src/components/WorkoutClock.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
// The workout header's clock (#1078): a Timer and a Stopwatch, neither of which writes anything
// into the workout. The Timer opens at the time it last ran (S.timerSec, else the rest from
// Settings) and runs on the rest timer, with the rest's alert at its end; starting it ends a rest
// that is running. Its countdown is marked `clock` on the timer, so the sheet tells it from a rest
// after a set and shows it as a large ring with −15 · +15 · Skip. The Stopwatch only counts
// (lib/stopwatch.js); the sheet opens on it while it has time on it.
import { useEffect, useRef, useState } from 'react'
import { useUI } from '../store/useUI.js'
import { useStore } from '../store/useStore.js'
import { useStopwatch } from '../store/useStopwatch.js'
import { t } from '../lib/i18n.js'
import { REST_MAX, fmtDuration } from '../lib/duration.js'
import { elapsed, running, startW, stopW, resetW, ofSession, showing, stopwatchText, stopwatchShort } from '../lib/stopwatch.js'
import DurationWheel from './DurationWheel.jsx'
import { Button, Segmented } from './ui.jsx'

const TIMER_MIN = 5
const lastTimer = S => (S.timerSec > 0 ? S.timerSec : S.restSec > 0 ? S.restSec : 90)
// A countdown the Timer started; the rest timer's ticks carry the mark over, a rest after a set
// starts a new timer without it, and one that ran out (ready) is over.
export const isClockTimer = tm => !!tm && tm.clock === true && !tm.ready
const fmtClock = sec => {
const n = Math.max(0, sec | 0)
return Math.floor(n / 60) + ':' + String(n % 60).padStart(2, '0')
}

// Redraws its caller every `ms` while `on`.
function useTick(ms, on = true) {
const [, tick] = useState(0)
useEffect(() => {
if (!on) return
const id = setInterval(() => tick(n => n + 1), ms)
return () => clearInterval(id)
}, [ms, on])
}

function TimerTab() {
const timer = useUI(s => s.timer)
// A hold or its count-in running: a rest started now would end it and log what was held.
const holding = useUI(s => !!(s.work || s.countIn))
const [v, setV] = useState(() => Math.min(lastTimer(useStore.getState().S), REST_MAX))
const read = useRef(null)
if (isClockTimer(timer)) {
const ui = useUI.getState()
return <Ring left={timer.left} total={timer.total}
onMinus={() => ui.addRest(-15)} onPlus={() => ui.addRest(15)} onSkip={() => ui.stopRest()} />
}
const go = () => {
const now = read.current ? read.current() : v
Comment thread
lodepav marked this conversation as resolved.
Resolved
if (!(now > 0) || holding) return
setV(now) // after Skip the wheel is back at the time that ran
useStore.getState().update(s => { s.timerSec = now })
// startRest ends a running rest first; `clock` keeps the countdown from leading into a hold.
useUI.getState().startRest(now, undefined, { clock: true })
}
return <div className="wclock">
<div className="dw-read" aria-hidden="true">{fmtDuration(v)}</div>
<DurationWheel value={v} onChange={setV} min={TIMER_MIN} max={REST_MAX} readRef={read} />
<Button variant="primary" onClick={go} disabled={holding}>{t('Start timer')}</Button>
</div>
}

// The running Timer: the time left in a ring, −15 · +15 and Skip. The rest bar counts it too, and
// its tick redraws the ring every second.
function Ring({ left, total, onMinus, onPlus, onSkip }) {
const share = total > 0 ? Math.min(1, left / total) : 0
const R = 118, C = 2 * Math.PI * R
return <div className="wclock-ring">
<div className="wclock-dial" role="timer" aria-label={t('Timer')}>
<svg viewBox="0 0 260 260" aria-hidden="true">
<circle cx="130" cy="130" r={R} className="wclock-bg" />
<circle cx="130" cy="130" r={R} className="wclock-fg" strokeDasharray={C} strokeDashoffset={C * (1 - share)} />
</svg>
<span className="wclock-t">{fmtClock(left)}</span>
</div>
<div className="wclock-btns">
<Button onClick={onMinus}>−15</Button>
<Button onClick={onPlus}>+15</Button>
<Button variant="primary" onClick={onSkip}>{t('Skip')}</Button>
</div>
</div>
}

function StopwatchTab() {
// The workout active now: another one started while the sheet is open gets its own stopwatch.
const session = useStore(s => s.S.active?.id ?? null)
const w = ofSession(useStopwatch(s => s.w), session)
const apply = useStopwatch(s => s.apply)
const on = running(w)
useTick(100, on)
const ms = elapsed(w, Date.now())
const go = fn => apply(cur => fn(ofSession(cur, session), Date.now()))
return <>
<div className="dw-read wclock-sw" role="timer" aria-label={t('Stopwatch')}>{stopwatchText(ms)}</div>
<div className="wclock-btns">
<Button onClick={() => go(resetW)} disabled={on || ms === 0}>{t('Reset')}</Button>
<Button variant="primary" onClick={() => go(on ? stopW : startW)}>{on ? t('Stop') : ms ? t('Resume') : t('Start')}</Button>
</div>
</>
}

export function WorkoutClock({ tab: first = 'timer' }) {
const [tab, setTab] = useState(first)
return <>
<Segmented value={tab} onChange={setTab}
options={[{ value: 'timer', label: t('Timer') }, { value: 'stopwatch', label: t('Stopwatch') }]} />
<div style={{ height: 12 }} />
{tab === 'timer' ? <TimerTab /> : <StopwatchTab />}
<div style={{ height: 8 }} />
</>
}

/** Opens the clock sheet from the workout header; the stopwatch is per workout (its id). */
export function workoutClockSheet() {
const session = useStore.getState().S.active?.id ?? null
const tab = showing(ofSession(useStopwatch.getState().w, session)) ? 'stopwatch' : 'timer'
return useUI.getState().openSheet(() => <WorkoutClock tab={tab} />)
}

/** The stopwatch's time beside the header's clock button while it runs ("Stopwatch 1:05" spoken). */
export function HeaderStopwatch({ session }) {
const w = ofSession(useStopwatch(s => s.w), session)
const on = running(w)
useTick(1000, on)
if (!on) return null
return <span className="wclock-hdr"><span className="vh">{t('Stopwatch')} </span>{stopwatchShort(elapsed(w, Date.now()))}</span>
}
Loading
Loading