Skip to content
Open
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>
}
255 changes: 255 additions & 0 deletions frontend/src/components/WorkoutClock.test.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,255 @@
// @vitest-environment happy-dom
// The workout header's clock (#1078): the Timer starts a new countdown on the rest timer at the
// time it last ran, ending a rest that is running; the Stopwatch only counts.
import React, { act } from 'react'
import { createRoot } from 'react-dom/client'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'

vi.mock('../lib/sound.js', () => ({ beep: vi.fn(), chime: vi.fn(), vibrate: vi.fn(), alertBuzz: vi.fn() }))
// `h.wheel`: what the wheel reads at Start while it is still turning (its readRef), before its
// onChange has caught up. The real wheel is drawn either way.
const h = vi.hoisted(() => ({ wheel: null }))
vi.mock('./DurationWheel.jsx', async importOriginal => {
const m = await importOriginal()
const Wheel = m.default
return { ...m, default: props => {
if (h.wheel != null && props.readRef) props.readRef.current = () => h.wheel
return <Wheel {...props} readRef={h.wheel != null ? undefined : props.readRef} />
} }
})

import { HeaderStopwatch, workoutClockSheet } from './WorkoutClock.jsx'
import { cues } from '../lib/spoken-cues.js'
import { useUI, bindAuto, restoreRest, REST_KEY } from '../store/useUI.js'
import { useStore } from '../store/useStore.js'
import { useStopwatch } from '../store/useStopwatch.js'
import { applyRestLeft } from './RestTimer.jsx'

globalThis.IS_REACT_ACT_ENVIRONMENT = true

let host, root, originalS
const mount = el => {
host = document.createElement('div')
document.body.appendChild(host)
root = createRoot(host)
act(() => root.render(el))
}
const open = () => {
workoutClockSheet()
const sheet = useUI.getState().sheets.at(-1)
mount(sheet.render(() => useUI.getState().closeSheet(sheet.id)))
}
const unmount = () => { if (root) act(() => root.unmount()); host?.remove(); root = host = null }
const btn = text => [...host.querySelectorAll('button')].find(b => b.textContent.trim() === text)
const tab = text => [...host.querySelectorAll('.seg button')].find(b => b.textContent === text)

beforeEach(() => {
vi.useFakeTimers({ now: 1_000_000 })
localStorage.clear()
originalS = useStore.getState().S
const { timerSec: _t, ...S } = originalS
useStore.setState({ S: { ...S, sound: false, restSec: 120, active: { id: 'w1', start: 1000, entries: [] } } })
useUI.setState({ sheets: [], timer: null, work: null })
useStopwatch.setState({ w: { session: null, since: null, acc: 0 } })
})
afterEach(() => {
unmount()
useUI.getState().stopRest()
useUI.getState().stopCountIn()
useUI.setState({ sheets: [], work: null })
useStore.setState({ S: originalS })
h.wheel = null
vi.restoreAllMocks()
vi.useRealTimers()
})

describe('workout Timer', () => {
it('opens at the rest from Settings, and starting it ends a running rest for a countdown of its own', () => {
act(() => useUI.getState().startRest(30, 2, { rest: 'work' }))
open()
expect(host.querySelector('.seg button.on').textContent).toBe('Timer')
expect(host.querySelector('.wclock-ring')).toBeNull() // a rest after a set keeps the wheel
expect(host.querySelector('.dw-read').textContent).toBe('2:00')
act(() => btn('Start timer').click())
const tm = useUI.getState().timer
expect(tm).toMatchObject({ left: 120, total: 120, clock: true })
expect(tm.forIdx).toBeUndefined()
expect(tm.rk).toBeUndefined()
expect(useStore.getState().S.timerSec).toBe(120)
expect(useStore.getState().S.edited.timerSec).toBeGreaterThan(0) // syncs as a plain setting
expect(host.querySelector('.wclock-t').textContent).toBe('2:00')
expect(btn('Skip')).toBeTruthy()
})

it('opens next time at the time it last ran, and the ring counts down and moves by 15', () => {
useStore.setState(st => ({ S: { ...st.S, timerSec: 45 } }))
open()
expect(host.querySelector('.dw-read').textContent).toBe('45s')
act(() => btn('Start timer').click())
act(() => vi.advanceTimersByTime(5000))
expect(host.querySelector('.wclock-t').textContent).toBe('0:40')
act(() => btn('+15').click())
expect(host.querySelector('.wclock-t').textContent).toBe('0:55')
act(() => btn('Skip').click())
expect(useUI.getState().timer).toBeNull()
expect(host.querySelector('.wclock-ring')).toBeNull()
})

it('the mark stays through ticks, pause, resume, ±15 and the notification, and goes when it runs out', () => {
useStore.setState(st => ({ S: { ...st.S, timerSec: 60 } }))
open()
act(() => btn('Start timer').click())
const ui = () => useUI.getState()
act(() => vi.advanceTimersByTime(3000))
expect(ui().timer.clock).toBe(true)
act(() => ui().pauseRest()); expect(ui().timer.clock).toBe(true)
act(() => ui().resumeRest()); expect(ui().timer.clock).toBe(true)
act(() => ui().addRest(-15)); expect(ui().timer.clock).toBe(true)
act(() => ui().followNativeRest({ endsAt: Date.now() + 20_000, left: 20, total: 60, paused: false }))
expect(ui().timer.clock).toBe(true)
act(() => vi.advanceTimersByTime(21_000))
expect(ui().timer.ready).toBe(true)
expect(host.querySelector('.wclock-ring')).toBeNull() // over: back to the wheel
})

it('does not start while a hold runs, so the hold is not ended and logged', () => {
const work = { left: 20, total: 30, endsAt: Date.now() + 20_000 }
useUI.setState({ work })
open()
expect(btn('Start timer').disabled).toBe(true)
act(() => btn('Start timer').click())
expect(useUI.getState().timer).toBeNull()
expect(useUI.getState().work).toBe(work)
})

it('never leads into a hold that starts by itself', () => {
const startHold = vi.fn()
const unbind = bindAuto({ peek: () => ({ idx: 0, i: 1, id: 'plank', plan: 30, label: 'Plank' }), forecast: () => [], focus: vi.fn(), startHold, stop: vi.fn() })
try {
useStore.setState(st => ({ S: { ...st.S, timerSec: 20 } }))
open()
act(() => btn('Start timer').click())
expect(useUI.getState().timer.autoNext).toBeUndefined()
act(() => vi.advanceTimersByTime(21_000))
expect(useUI.getState().countIn).toBeFalsy()
expect(useUI.getState().timer).toMatchObject({ ready: true, clock: true })
act(() => useUI.getState().stopRest())
act(() => btn('Start timer').click())
act(() => useUI.getState().skipRest()) // the rest bar's or the notification's Skip
expect(useUI.getState().countIn).toBeFalsy()
expect(startHold).not.toHaveBeenCalled()
} finally { unbind() }
})

it('started again from its Ready (+15, the wheel, a watch), it still leads into no hold', () => {
const startHold = vi.fn()
const unbind = bindAuto({ peek: () => ({ idx: 0, i: 1, id: 'plank', plan: 30, label: 'Plank' }), forecast: () => [], focus: vi.fn(), startHold, stop: vi.fn() })
try {
useStore.setState(st => ({ S: { ...st.S, timerSec: 20 } }))
open()
act(() => btn('Start timer').click())
act(() => vi.advanceTimersByTime(21_000))
expect(useUI.getState().timer.ready).toBe(true)
act(() => useUI.getState().addRest(15))
expect(useUI.getState().timer).toMatchObject({ clock: true, total: 15 })
expect(useUI.getState().timer.autoNext).toBeUndefined()
act(() => vi.advanceTimersByTime(16_000))
expect(useUI.getState().countIn).toBeFalsy()
expect(useUI.getState().timer.ready).toBe(true)
act(() => applyRestLeft(10, 0)) // the rest bar's wheel on Ready
expect(useUI.getState().timer.clock).toBe(true)
act(() => vi.advanceTimersByTime(11_000))
act(() => useUI.getState().alignRest(Date.now() + 10_000)) // a watch's +15 on Ready
expect(useUI.getState().timer.clock).toBe(true)
act(() => vi.advanceTimersByTime(11_000))
expect(useUI.getState().countIn).toBeFalsy()
expect(startHold).not.toHaveBeenCalled()
} finally { unbind() }
})

it('after Skip the wheel is at the time that just ran', () => {
h.wheel = 75
open()
act(() => btn('Start timer').click())
expect(useUI.getState().timer.total).toBe(75)
act(() => btn('Skip').click())
expect(host.querySelector('.dw-read').textContent).toBe('1:15')
})

it('says nothing of the next set when it starts, and its end says the time is up', () => {
const said = vi.spyOn(cues, 'restStarted')
useStore.setState(st => ({ S: { ...st.S, timerSec: 20 } }))
open()
act(() => btn('Start timer').click())
expect(said).not.toHaveBeenCalled()
act(() => vi.advanceTimersByTime(21_000))
expect(useUI.getState().toastMsg).toBe('Time’s up.')
act(() => useUI.getState().startRest(30, 0)) // a rest after a set still does both
expect(said).toHaveBeenCalledWith(0)
act(() => vi.advanceTimersByTime(31_000))
expect(useUI.getState().toastMsg).toBe('Rest’s over. Next set!')
})

it('stays the Timer\'s countdown across a reload', () => {
useStore.setState(st => ({ S: { ...st.S, timerSec: 60 } }))
open()
act(() => btn('Start timer').click())
const saved = localStorage.getItem(REST_KEY)
expect(JSON.parse(saved).clock).toBe(true)
act(() => useUI.getState().stopRest()) // the page gone: nothing in memory
localStorage.setItem(REST_KEY, saved)
act(() => { expect(restoreRest()).toBe(true) })
expect(useUI.getState().timer).toMatchObject({ clock: true, total: 60 })
})
})

describe('workout Stopwatch', () => {
it('starts, stops, resumes and resets, and the sheet opens on it while it has time', () => {
open()
act(() => tab('Stopwatch').click())
expect(host.querySelector('.wclock-sw').textContent).toBe('0:00.0')
expect(btn('Reset').disabled).toBe(true)
act(() => btn('Start').click())
act(() => vi.advanceTimersByTime(4200))
expect(host.querySelector('.wclock-sw').textContent).toBe('0:04.2')
act(() => btn('Stop').click())
expect(btn('Resume')).toBeTruthy()
unmount()
open()
expect(host.querySelector('.seg button.on').textContent).toBe('Stopwatch')
expect(host.querySelector('.wclock-sw').textContent).toBe('0:04.2')
act(() => btn('Reset').click())
expect(host.querySelector('.wclock-sw').textContent).toBe('0:00.0')
expect(JSON.parse(localStorage.getItem('gym_stopwatch_v1'))).toMatchObject({ session: 'w1', acc: 0, since: null })
expect(useUI.getState().timer).toBeNull() // nothing of it touches the rest timer
})

it('acts on the workout that is active now, not the one the sheet was opened in', () => {
open()
act(() => tab('Stopwatch').click())
act(() => useStore.setState(st => ({ S: { ...st.S, active: { id: 'w2', start: 2000, entries: [] } } })))
act(() => btn('Start').click())
expect(useStopwatch.getState().w).toMatchObject({ session: 'w2', since: Date.now() })
})

it('a new workout starts it from zero', () => {
useStopwatch.setState({ w: { session: 'old', since: null, acc: 9000 } })
open()
expect(host.querySelector('.seg button.on').textContent).toBe('Timer')
act(() => tab('Stopwatch').click())
expect(host.querySelector('.wclock-sw').textContent).toBe('0:00.0')
})

it('the header shows a running stopwatch of this workout only', () => {
useStopwatch.setState({ w: { session: 'w1', since: Date.now() - 65_000, acc: 0 } })
mount(<HeaderStopwatch session="w1" />)
expect(host.textContent).toBe('Stopwatch 1:05') // "Stopwatch" is for screen readers (.vh)
act(() => vi.advanceTimersByTime(1000))
expect(host.textContent).toBe('Stopwatch 1:06')
act(() => root.render(<HeaderStopwatch session="w2" />))
expect(host.textContent).toBe('')
useStopwatch.setState({ w: { session: 'w1', since: null, acc: 5000 } })
act(() => root.render(<HeaderStopwatch session="w1" />))
expect(host.textContent).toBe('') // stopped: only the icon
})
})
Loading
Loading