Open-source gym & body-weight tracker, now in the App Store (iPhone + Apple Watch) and as an Android APK. Plan routines, log workouts, see which muscles are trained, import from Strong/Hevy/FitNotes. Self-host it or use it on the phone alone.
JavaScript apple-watchbodyweightdockerfitnessfitness-trackergymhealthiosmcpnodejspasskeysprogressive-web-applicationspwareactself-hostedself-hostingvitewebauthnweightliftingworkout-tracker
feat(workout): add a persistent complete and next action
Space-Hermes26740f8c30b8
diff --git a/frontend/src/App.jsx b/frontend/src/App.jsxindex e3ab903a3..11c710ea3 100644--- a/frontend/src/App.jsx+++ b/frontend/src/App.jsx@@ -1,4 +1,4 @@-import { useEffect, useLayoutEffect, useRef } from 'react'+import { useEffect, useLayoutEffect, useRef, useState } from 'react'import { HashRouter, Routes, Route, Navigate, useNavigate, useLocation, useNavigationType } from 'react-router-dom'import { useStore } from './store/useStore.js'import { useUI } from './store/useUI.js'@@ -67,6 +67,7 @@ function applyPrefs(theme, accent) {}function Shell() {+ const [workoutAction, setWorkoutAction] = useState(null)const navigate = useNavigate()const loc = useLocation()const navType = useNavigationType()@@ -175,17 +176,17 @@ function Shell() {}, [loc.pathname, navType])// bound to the workout, not to the route — checking Stats mid-session keeps the screen onuseWakeLock(!!S.active && !S.active.editingWorkoutId && S.keepAwake !== false)- // A running workout has the whole screen (v1.3.11): no tab bar, and the rest bar docks to the- // bottom edge in its place. Its header's ⌄ goes back to the app, where the tab bar's Resume- // brings it back.+ // Workouts keep navigation hidden, with only their primary action below the rest timer.const inWorkout = loc.pathname === '/workout' && !!S.active+ const hasWorkoutAction = inWorkout && !S.active.editingWorkoutId && !S.active.backfill+ && workoutAction?.sessionId === S.active.iduseEffect(() => {- document.body.classList.toggle('no-tabbar', inWorkout)+ document.body.classList.toggle('no-tabbar', inWorkout && !hasWorkoutAction)return () => document.body.classList.remove('no-tabbar')- }, [inWorkout])+ }, [inWorkout, hasWorkoutAction])// The chat owns the bottom of the screen as well: its composer sits where the tabs would be.// The first-launch card has no tabs either: they changed the route behind it.- const noTabs = inWorkout || loc.pathname === '/coach' || needsMobileOnboarding+ const noTabs = (inWorkout && !hasWorkoutAction) || loc.pathname === '/coach' || needsMobileOnboardingconst authed = user || isGuestif (!ready && !authed) return (@@ -210,7 +211,7 @@ function Shell() {{S.checkIn !== false && <Route path="/checkin" element={<CheckIn />} />}<Route path="/plan" element={<Plan />} /><Route path="/plan/r/:id" element={<RoutineEdit />} />- <Route path="/workout" element={<Workout />} />+ <Route path="/workout" element={<Workout onActionChange={setWorkoutAction} />} /><Route path="/stats" element={<Stats />} /><Route path="/history" element={<History />} /><Route path="/library" element={<Library />} />@@ -237,7 +238,7 @@ function Shell() {would ride along with the page for the length of it. Decides for itself when to show —including on the sign-in screen, when the server has just ended the session. */}<SyncBanner />- {!noTabs && <TabBar onStart={startFlow} />}+ {!noTabs && <TabBar onStart={startFlow} workoutAction={workoutAction} workoutOnly={inWorkout} />}<RestTimer /><Modals /><Toast />diff --git a/frontend/src/App.workout-action.test.jsx b/frontend/src/App.workout-action.test.jsxnew file mode 100644index 000000000..387e94630--- /dev/null+++ b/frontend/src/App.workout-action.test.jsx@@ -0,0 +1,67 @@+// @vitest-environment happy-dom+import React, { act } from 'react'+import { createRoot } from 'react-dom/client'+import { afterEach, beforeEach, expect, it, vi } from 'vitest'+import App from './App.jsx'+import { DEF, useStore } from './store/useStore.js'+import { useUI } from './store/useUI.js'++vi.mock('./lib/sound.js', () => ({+ setPlayOnSilent: vi.fn(), setVibrate: vi.fn(), setAlarmBuzzer: vi.fn(),+ beep: vi.fn(), chime: vi.fn(), vibrate: vi.fn(), alertBuzz: vi.fn(), unlock: vi.fn(),+}))+vi.mock('./lib/api.js', async importOriginal => ({+ ...await importOriginal(), api: vi.fn(() => Promise.resolve({})), beacon: vi.fn(),+}))+globalThis.IS_REACT_ACT_ENVIRONMENT = true+let host, root, original++beforeEach(() => {+ original = useStore.getState()+ localStorage.setItem('gym_guest', '1')+ window.location.hash = '#/workout'+ window.scrollTo = vi.fn()+ const S = structuredClone(DEF)+ S.sound = false+ S.active = { id: 'test', name: 'Test', start: Date.now(), cur: 0, entries: [+ { id: '1001', target: { mode: 'reps' }, sets: [{ w: 10, r: 5, done: false }, { w: 10, r: 5, done: false }] },+ ] }+ useStore.setState({ S, user: null, ready: true, boot: vi.fn() })+ useUI.setState({ sheets: [], work: null, timer: null })+ host = document.createElement('div')+ document.body.appendChild(host)+ root = createRoot(host)+})++afterEach(() => {+ act(() => root.unmount())+ host.remove()+ useUI.getState().stopRest()+ useUI.getState().stopWork()+ useStore.setState(original)+ localStorage.clear()+})++it('shows only the action during a workout and restores navigation when minimized', async () => {+ await act(async () => root.render(<App />))+ expect(host.querySelectorAll('#tabbar button')).toHaveLength(1)+ expect(document.body.classList.contains('no-tabbar')).toBe(false)+ const action = host.querySelector('#tabbar button')+ expect(action.getAttribute('aria-label')).toBe('Complete set')+ await act(async () => action.click())+ expect(useStore.getState().S.active.entries[0].sets.map(s => s.done)).toEqual([true, false])+ expect(host.querySelector('#timer')).not.toBeNull()+ await act(async () => host.querySelector('.whdr button[aria-label="Minimize"]').click())+ expect(host.querySelectorAll('#tabbar button')).toHaveLength(5)+ expect(host.querySelector('#tabbar .start').getAttribute('aria-label')).toBe('Resume')+ await act(async () => host.querySelector('#tabbar .start').click())+ expect(host.querySelectorAll('#tabbar button')).toHaveLength(1)+ expect(useStore.getState().S.active.entries[0].sets.map(s => s.done)).toEqual([true, false])+})++it.each([{ editingWorkoutId: 'saved' }, { backfill: true }])('does not offer a live action for past workouts: %j', async flags => {+ useStore.getState().update(s => Object.assign(s.active, flags), false)+ await act(async () => root.render(<App />))+ expect(host.querySelector('#tabbar')).toBeNull()+ expect(document.body.classList.contains('no-tabbar')).toBe(true)+})diff --git a/frontend/src/components/TabBar.jsx b/frontend/src/components/TabBar.jsxindex db089dd7b..8b25d97d9 100644--- a/frontend/src/components/TabBar.jsx+++ b/frontend/src/components/TabBar.jsx@@ -19,7 +19,7 @@ function Tab({ active, icon, label, onClick, dot }) {)}-export default function TabBar({ onStart }) {+export default function TabBar({ onStart, workoutAction, workoutOnly = false }) {const nav = useNavigate()const loc = useLocation()const S = useStore(s => s.S)@@ -33,6 +33,8 @@ export default function TabBar({ onStart }) {const on = k => cur === k || (cur === 'history' && k === 'stats') || (cur === 'settings' && k === 'home') || (cur === 'muscles' && k === 'library') || (cur === 'structural-balance' && k === 'stats')const running = !!S.active && cur !== 'workout' && !S.active.editingWorkoutId && !S.active.backfill && S.active.start > 0+ const action = cur === 'workout' && S.active && !S.active.editingWorkoutId && !S.active.backfill+ && workoutAction?.sessionId === S.active.id ? workoutAction : nullconst startWorkout = () => {if (!S.active) {// A weekday can hold several routines; start the combined session if any of them has@@ -43,24 +45,18 @@ export default function TabBar({ onStart }) {}return (- <nav id="tabbar">- <Tab active={on('home')} icon="house" label={t('Home')} dot={trouble} onClick={() => nav('/home')} />- <Tab active={on('plan')} icon="calendar" label={t('Plan')} onClick={() => nav('/plan')} />- {/* On the workout screen itself there is nothing to resume, so the button reads as the- tab it is and stays lit (#29); anywhere else it brings you back to the exercise you- were on — the marker is kept in S.active.cur and never moves on its own (#21). The- glyph is always play: start and resume are one concept, and an exercise is a dumbbell.- A live session you stepped away from shows its running time instead of a word, the- button still named Resume; a past workout being edited or logged after the fact has no- clock to run. */}- <button className={'start' + (S.active ? ' rec' : '') + (S.active && cur === 'workout' ? ' on' : '')} onClick={startWorkout}- aria-label={running ? t('Resume') : undefined}>- <span className="cir"><Icon name="play" /></span>- {running ? <span className="tab-time"><Elapsed start={S.active.start} /></span>+ <nav id="tabbar" className={workoutOnly ? 'workout-action' : undefined}>+ {!workoutOnly && <Tab active={on('home')} icon="house" label={t('Home')} dot={trouble} onClick={() => nav('/home')} />}+ {!workoutOnly && <Tab active={on('plan')} icon="calendar" label={t('Plan')} onClick={() => nav('/plan')} />}+ {/* The workout owns completion; away from it this remains Start/Resume. */}+ <button className={'start' + (S.active ? ' rec' : '') + (S.active && cur === 'workout' ? ' on' : '')} onClick={action ? action.run : startWorkout}+ aria-label={action ? action.ariaLabel : running ? t('Resume') : undefined}>+ <span className="cir"><Icon name={action ? action.icon : 'play'} /></span>+ {action ? <span>{action.label}</span> : running ? <span className="tab-time"><Elapsed start={S.active.start} /></span>: <span>{S.active ? (cur === 'workout' ? t('Workout') : S.active.editingWorkoutId ? t('Edit workout') : t('Resume')) : t('Start')}</span>}</button>- <Tab active={on('stats')} icon="chart" label={t('Stats')} onClick={() => nav('/stats')} />- <Tab active={on('library')} icon="dumbbell" label={t('Exercises')} onClick={() => nav('/library')} />+ {!workoutOnly && <Tab active={on('stats')} icon="chart" label={t('Stats')} onClick={() => nav('/stats')} />}+ {!workoutOnly && <Tab active={on('library')} icon="dumbbell" label={t('Exercises')} onClick={() => nav('/library')} />}</nav>)}diff --git a/frontend/src/index.css b/frontend/src/index.cssindex 875f25be3..4573b25da 100644--- a/frontend/src/index.css+++ b/frontend/src/index.css@@ -433,6 +433,8 @@ h4.sec{#tabbar button.start .cir .icn{font-size:26px;--icon-stroke:2;color:inherit;opacity:1}#tabbar button.start span{color:var(--acc);font-weight:600}#tabbar button.start .tab-time{font-variant-numeric:tabular-nums}+#tabbar.workout-action button.start{flex:0 1 auto;flex-direction:row;gap:10px;margin-top:0;min-width:180px;justify-content:center;font-size:14px}+#tabbar.workout-action button.start .cir{width:44px;height:44px}/* `.cir` is itself a <span>, so the label rules above and below reach it too andoutrank the `.cir` block — which is how the running state ended up painting anorange play glyph onto an orange disc. Both states restate their own colour.diff --git a/frontend/src/views/FocusView.jsx b/frontend/src/views/FocusView.jsxindex aeedc137c..cb794ebdf 100644--- a/frontend/src/views/FocusView.jsx+++ b/frontend/src/views/FocusView.jsx@@ -1,4 +1,4 @@-import { useState } from 'react'+import { useEffect, useState } from 'react'import { useStore } from '../store/useStore.js'import { exOr } from '../lib/exercises.js'import { clampIncline, hasIncline, inclineFits, INCLINE_MAX, INCLINE_STEP } from '../lib/incline.js'@@ -109,7 +109,7 @@ function PlateBadge({ S, entry, set }) {export default function FocusView({entryIdx, unit, onToggle, onToggleSide, onField, onMutateSet, onStartTimed,onAddWarmup, onRemoveSetAt, onProgressionSettings, onSwap, onRemoveExercise,- onNoProg, busy, onSelectEntry, onAdvanceUnit, onPairPrev, onPairNext, onUnpair, pointerEpoch,+ onNoProg, busy, onSelectEntry, onAdvanceUnit, onPairPrev, onPairNext, onUnpair, pointerEpoch, onSetChange,}) {const S = useStore(state => state.S)const speedUnit = speedUnitOf(S)@@ -124,6 +124,7 @@ export default function FocusView({const pointers = pointerState.epoch === pointerEpoch ? pointerState.pointers : new Map()const stored = pointers.get(entryIdx)const setIdx = clampSet(entry, Number.isInteger(stored) ? stored : firstIncomplete(entry))+ useEffect(() => { onSetChange?.({ idx: entryIdx, i: setIdx }) }, [onSetChange, entryIdx, setIdx])const set = entry.sets[setIdx]const firstOpenSet = firstIncomplete(entry)const locked = !set.done && setIdx > firstOpenSetdiff --git a/frontend/src/views/Workout.jsx b/frontend/src/views/Workout.jsxindex ab8f2d316..3782f3579 100644--- a/frontend/src/views/Workout.jsx+++ b/frontend/src/views/Workout.jsx@@ -916,7 +916,7 @@ const coveredTop = () => {return inset}-function ActiveWorkout() {+function ActiveWorkout({ onActionChange }) {const nav = useNavigate()const S = useStore(s => s.S)const update = useStore(s => s.update)@@ -979,6 +979,7 @@ function ActiveWorkout() {const exRefs = useRef(new Map())const setRefs = useRef(new Map())const focusPointerEpoch = useRef(0)+ const [focusSet, setFocusSet] = useState(null)const bindExRef = (entry, el) => {if (el) exRefs.current.set(entry, el)else {@@ -1804,13 +1805,7 @@ function ActiveWorkout() {if (window.requestAnimationFrame) window.requestAnimationFrame(scroll)else window.setTimeout(scroll, 0)}- onKey.current = event => {- // A sheet on top owns the keyboard (Escape closes it, Enter confirms in it).- if (useUI.getState().sheets.length) return false- const action = workoutKeyAction(event, { tabbed: tabbed.current, rtl: document.documentElement.dir === 'rtl' })- if (!action) return false- event.preventDefault()- if (action !== 'tick') { navigateUnit(action === 'next' ? 1 : -1); showCurrent(); return true }+ const tickNext = (keepLayout = false) => {// A hold being timed: the key is its "Done", which logs what was actually held, once the// hold has run past its first moments (HOLD_KEY_GRACE_MS).const work = useUI.getState().work@@ -1823,12 +1818,62 @@ function ActiveWorkout() {if (!next) return true// The exercise on screen is finished: this press brings up the next one, and the one after// ticks its set. A key never logs a set for an exercise that was not in front of you.- if (!next.current) { focusUnit(next.idx); showCurrent(); return true }+ if (!next.current) {+ if (keepLayout) update(s => { if (s.active) s.active.cur = next.idx })+ else focusUnit(next.idx)+ showCurrent()+ return true+ }// A timed set is started rather than ticked, as its play button does; the timer ticks it.if (!next.side && modeAt(next.idx) === 'time') startTimed(next.idx, next.i)else toggle(next.idx, next.i, next.side)return true}+ onKey.current = event => {+ // A sheet on top owns the keyboard (Escape closes it, Enter confirms in it).+ if (useUI.getState().sheets.length) return false+ const action = workoutKeyAction(event, { tabbed: tabbed.current, rtl: document.documentElement.dir === 'rtl' })+ if (!action) return false+ event.preventDefault()+ if (action !== 'tick') { navigateUnit(action === 'next' ? 1 : -1); showCurrent(); return true }+ return tickNext()+ }+ const nextActionSet = nextOpenSet(A.entries, cur)+ const focusNeedsReveal = focusMode && nextActionSet?.current && focusSet+ && (focusSet.idx !== nextActionSet.idx || focusSet.i !== nextActionSet.i)+ const actionKind = editing || A.backfill || !A.entries.length ? null+ : work ? 'done' : !nextActionSet ? 'finish' : !nextActionSet.current || focusNeedsReveal ? 'next'+ : !nextActionSet.side && modeAt(nextActionSet.idx) === 'time' ? 'start'+ : nextActionSet.side || 'complete'+ const actionLabel = actionKind === 'done' ? t('Done') : actionKind === 'finish' ? t('Finish')+ : actionKind === 'next' ? t('Next') : actionKind === 'start' ? t('Start')+ : actionKind === 'L' ? t('Complete left side') : actionKind === 'R' ? t('Complete right side') : t('Complete')+ const actionAria = actionKind === 'finish' ? t('Finish workout')+ : actionKind === 'L' ? t('Complete left side') : actionKind === 'R' ? t('Complete right side')+ : actionKind === 'complete' ? t('Complete set') : actionLabel+ const primaryAction = useRef(null)+ primaryAction.current = () => {+ const fresh = useStore.getState().S.active+ if (!fresh || fresh.id !== A.id || fresh.editingWorkoutId || fresh.backfill || useUI.getState().sheets.length) return+ if (!useUI.getState().work && focusNeedsReveal) {+ focusPointerEpoch.current+++ update(s => { if (s.active) s.active.cur = nextActionSet.idx })+ return+ }+ if (!useUI.getState().work && !nextOpenSet(fresh.entries, fresh.cur)) {+ if (fresh.entries.length) finishWorkoutSheet({ onDiscard: discardWorkout })+ return+ }+ tickNext(true)+ }+ useEffect(() => {+ onActionChange?.(actionKind ? {+ sessionId: A.id, label: actionLabel, ariaLabel: actionAria,+ icon: actionKind === 'start' ? 'play' : actionKind === 'next' ? 'chevronRight' : actionKind === 'finish' ? 'flag' : 'check',+ run: () => primaryAction.current?.(),+ } : null)+ return () => onActionChange?.(null)+ }, [onActionChange, A.id, actionKind, actionLabel, actionAria])useEffect(() => {// A Space that ticked must not also press the button a click left focus on. Preventing the// keydown is enough for Chrome; Firefox presses a button on the keyup, so that goes too.@@ -2014,7 +2059,7 @@ function ActiveWorkout() {}}>{focusMode ? (<FocusView entryIdx={cur} unit={unit}- onSelectEntry={selectFocusEntry} onAdvanceUnit={advanceFocusUnit} pointerEpoch={focusPointerEpoch.current}+ onSelectEntry={selectFocusEntry} onAdvanceUnit={advanceFocusUnit} pointerEpoch={focusPointerEpoch.current} onSetChange={setFocusSet}onPairPrev={onPairPrev} onPairNext={onPairNext} onUnpair={() => unpairAt(cur)}{...blockProps(cur)} />) : isSuperset ? (@@ -2083,7 +2128,7 @@ function ActiveWorkout() {</WorkoutScrollAnchor>}-export default function Workout() {+export default function Workout({ onActionChange }) {const active = useStore(s => s.S.active)- return active ? <ActiveWorkout /> : <StartChooser />+ return active ? <ActiveWorkout onActionChange={onActionChange} /> : <StartChooser />}diff --git a/frontend/src/views/Workout.keys.test.jsx b/frontend/src/views/Workout.keys.test.jsxindex 7718d5f87..765b48702 100644--- a/frontend/src/views/Workout.keys.test.jsx+++ b/frontend/src/views/Workout.keys.test.jsx@@ -1,16 +1,17 @@// @vitest-environment happy-dom// Hardware keys on the workout screen (issue #133), against the real store and timers: what a// key press does to the session, not only what lib/workout-keys.js decides.-import React, { act } from 'react'+import React, { act, useState } from 'react'import { createRoot } from 'react-dom/client'import { MemoryRouter } from 'react-router-dom'import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import Workout from './Workout.jsx'+import TabBar from '../components/TabBar.jsx'import { DEF, useStore } from '../store/useStore.js'import { useUI } from '../store/useUI.js'vi.mock('../lib/sound.js', () => ({ beep: vi.fn(), chime: vi.fn(), vibrate: vi.fn(), alertBuzz: vi.fn(), unlock: vi.fn() }))-vi.mock('../lib/api.js', () => ({ api: vi.fn(() => Promise.resolve({})), appBase: () => '/' }))+vi.mock('../lib/api.js', () => ({ api: vi.fn(() => Promise.resolve({})), appBase: () => '/', webauthnOK: () => false }))globalThis.IS_REACT_ACT_ENVIRONMENT = trueconst clone = value => JSON.parse(JSON.stringify(value))@@ -24,14 +25,20 @@ const entry = (id, done, extra = {}) => ({let rootlet container-function renderWorkout(entries, cur = 0, extra = {}) {+function WorkoutWithAction() {+ const [action, setAction] = useState(null)+ return <><Workout onActionChange={setAction} /><TabBar workoutAction={action} onStart={() => {}} /></>+}++function renderWorkout(entries, cur = 0, extra = {}, withAction = false) {const S = clone(DEF)S.active = { id: 'keys-test', d: '2026-09-23', start: Date.now(), routineId: null, name: 'Keys', bw: null, cur, entries, ...extra }useStore.setState({ S, user: null })+ if (withAction) localStorage.setItem('gym_guest', '1')container = document.createElement('div')document.body.appendChild(container)root = createRoot(container)- act(() => root.render(<MemoryRouter><Workout /></MemoryRouter>))+ act(() => root.render(<MemoryRouter initialEntries={['/workout']}>{withAction ? <WorkoutWithAction /> : <Workout />}</MemoryRouter>))}const press = (key, target = document.body) => {@@ -50,6 +57,148 @@ beforeEach(() => {container = null})+describe('the persistent workout action', () => {+ const button = () => container.querySelector('#tabbar .start')+ const tap = () => act(() => button().click())++ it.each(['cards', 'list', 'compact', 'focus'])('completes a set and offers Next without logging unseen work in %s', workoutView => {+ renderWorkout([entry('1001', [false]), entry('1002', [false])], 0, { workoutView }, true)+ expect(button().getAttribute('aria-label')).toBe('Complete set')+ tap()+ expect(doneOf(0)).toEqual([true])+ expect(useUI.getState().timer).not.toBeNull()+ expect(button().textContent).toBe('Next')+ tap()+ expect(active().cur).toBe(1)+ expect(active().workoutView).toBe(workoutView)+ expect(doneOf(1)).toEqual([false])+ tap()+ expect(doneOf(1)).toEqual([true])+ expect(button().textContent).toBe('Finish')+ // The set completion sheet may already be open; dismiss it before reopening Finish.+ act(() => useUI.setState({ sheets: [] }))+ tap()+ expect(useUI.getState().sheets.length).toBeGreaterThan(0)+ expect(active()).not.toBeNull()+ })++ it('starts a hold, ignores a bouncing tap, then logs the actual held duration', () => {+ const plank = { id: '1001', target: { mode: 'time', sec: 45 }, sets: [{ sec: 45, w: 0, done: false }] }+ renderWorkout([plank, entry('1002', [false])], 0, {}, true)+ expect(button().textContent).toBe('Start')+ tap()+ expect(button().textContent).toBe('Done')+ tap()+ expect(doneOf(0)).toEqual([false])+ act(() => vi.advanceTimersByTime(10_000))+ tap()+ expect(active().entries[0].sets[0].sec).toBe(10)+ expect(doneOf(0)).toEqual([true])+ expect(button().textContent).toBe('Next')+ })++ it.each(['cards', 'list', 'compact', 'focus'])('logs cardio without starting a hold in %s', workoutView => {+ const row = { min: 20, speed: 6, incline: 8, done: false }+ renderWorkout([{ id: '3666', target: { mode: 'cardio' }, sets: [row] }, entry('1002', [false])], 0, { workoutView }, true)+ expect(button().textContent).toBe('Complete')+ tap()+ expect(active().entries[0].sets[0]).toMatchObject({ ...row, done: true })+ expect(useUI.getState().work).toBeNull()+ expect(button().textContent).toBe('Next')+ tap()+ expect(active().cur).toBe(1)+ expect(doneOf(1)).toEqual([false])+ })++ it.each(['cards', 'list', 'compact', 'focus'])('times both sides with switch and full rest in %s', workoutView => {+ renderWorkout([{ id: '1001', target: { mode: 'time', sets: 1, sec: 10, side: true }, sets: [+ { sec: 10, w: 0, done: false, side: 'L' }, { sec: 10, w: 0, done: false, side: 'R' },+ ] }, entry('1002', [false])], 0, { workoutView }, true)+ tap()+ act(() => vi.advanceTimersByTime(11_000))+ expect(doneOf(0)).toEqual([true, false])+ expect(useUI.getState().timer).toMatchObject({ kind: 'switch', total: 10 })+ expect(button().textContent).toBe('Start')+ tap()+ act(() => vi.advanceTimersByTime(4_000))+ tap()+ expect(doneOf(0)).toEqual([true, true])+ expect(active().entries[0].sets.map(s => s.sec)).toEqual([10, 4])+ expect(useUI.getState().timer.total).toBe(useStore.getState().S.restSec)+ expect(useUI.getState().timer.kind).toBeUndefined()+ expect(button().textContent).toBe('Next')+ })++ it.each([+ { phase: 'warmup', warmup: true },+ { type: 'dropset', drops: [{ w: 40, r: 6 }, { w: 30, r: 5 }] },+ { type: 'restpause', clusters: [{ r: 4, restSec: 15 }, { r: 2, restSec: 15 }] },+ ])('completes a specialised rep row without changing its details: %j', details => {+ const row = { w: 60, r: 12, done: false, ...details }+ renderWorkout([entry('1001', [], { sets: [row, { w: 60, r: 5, done: false }] })], 0, {}, true)+ tap()+ expect(active().entries[0].sets[0]).toMatchObject({ ...row, done: true })+ expect(doneOf(0)).toEqual([true, false])+ expect(button().textContent).toBe('Complete')+ })++ it('keeps a superset in round order', () => {+ renderWorkout([entry('1001', [false, false], { sg: 'pair' }), entry('1002', [false, false], { sg: 'pair' })], 0, {}, true)+ tap()+ expect(active().cur).toBe(1)+ tap()+ expect(active().cur).toBe(0)+ expect(doneOf(0)).toEqual([true, false])+ expect(doneOf(1)).toEqual([true, false])+ })++ it('reveals the next unfinished Focus set before completing when another set is being inspected', () => {+ renderWorkout([entry('1001', [false, false, false])], 0, { workoutView: 'focus' }, true)+ act(() => container.querySelector('button[aria-label="Set 3"]').click())+ expect(button().textContent).toBe('Next')+ tap()+ expect(doneOf(0)).toEqual([false, false, false])+ expect(active().workoutView).toBe('focus')+ expect(button().getAttribute('aria-label')).toBe('Complete set')+ tap()+ expect(doneOf(0)).toEqual([true, false, false])+ })++ it('names and completes each side separately', () => {+ renderWorkout([entry('1001', [], { sets: [{ done: false, sides: {+ L: { w: 10, r: 5, done: false }, R: { w: 10, r: 5, done: false },+ } }] }), entry('1002', [false])], 0, {}, true)+ expect(button().textContent).toBe('Complete left side')+ tap()+ expect(doneOf(0)).toEqual([false])+ expect(button().textContent).toBe('Complete right side')+ tap()+ expect(doneOf(0)).toEqual([true])+ })++ it('does not complete behind a sheet or double-log when a keyboard shortcut is used', () => {+ renderWorkout([entry('1001', [false, false, false])], 0, {}, true)+ act(() => useUI.getState().openSheet(() => null))+ tap()+ expect(doneOf(0)).toEqual([false, false, false])+ act(() => useUI.setState({ sheets: [] }))+ expect(press('Enter', button()).defaultPrevented).toBe(true)+ expect(doneOf(0)).toEqual([true, false, false])+ })++ it.each([{ editingWorkoutId: 'saved' }, { backfill: true }])('leaves historical workout controls unchanged: %j', flags => {+ renderWorkout([entry('1001', [false])], 0, flags, true)+ expect(button().textContent).toBe('Workout')+ tap()+ expect(doneOf(0)).toEqual([false])+ })++ it('leaves an empty workout as navigation', () => {+ renderWorkout([], 0, {}, true)+ expect(button().textContent).toBe('Workout')+ })+})+afterEach(() => {if (root) act(() => root.unmount())if (container) container.remove()