From edde72f9cba3108a0fd9aa07c1fc6b4ec48ea456 Mon Sep 17 00:00:00 2001 From: root Date: Wed, 12 Aug 2026 17:20:50 +0200 Subject: [PATCH] fix: superset flow round-3 (rest gate for ordinary exercises, high-water progress, top-weight owns advance, Workout coverage) --- frontend/src/lib/supersetFlow.js | 28 +++++ frontend/src/lib/supersetFlow.test.js | 36 +++++++ frontend/src/views/Workout.jsx | 57 ++++++++-- frontend/src/views/Workout.test.jsx | 146 ++++++++++++++++++++++++++ 4 files changed, 261 insertions(+), 6 deletions(-) create mode 100644 frontend/src/lib/supersetFlow.js create mode 100644 frontend/src/lib/supersetFlow.test.js create mode 100644 frontend/src/views/Workout.test.jsx diff --git a/frontend/src/lib/supersetFlow.js b/frontend/src/lib/supersetFlow.js new file mode 100644 index 0000000..c78e72c --- /dev/null +++ b/frontend/src/lib/supersetFlow.js @@ -0,0 +1,28 @@ +// Pure decisions for the active-workout superset flow. Keeping these independent of React and +// the stores makes the uneven-round and re-check rules explicit and directly testable. +const hasWork = (entries, idx) => !!entries[idx]?.sets?.some(set => !set.done) + +// A completion is new progress only when it takes this exercise beyond the largest number of +// simultaneously completed sets seen in this mounted session. Uncheck/re-check therefore does +// not repeat navigation or rest side effects, while completing an added set still can. +export function setProgressHighWater(entry, previous = 0) { + const done = entry?.sets?.reduce((count, set) => count + (set.done ? 1 : 0), 0) || 0 + return { isNew: done > previous, highWater: Math.max(previous, done) } +} + +// Decide where a newly completed superset set goes next. Spent members are skipped, including +// across the wrap. A round ends when no later member in display order has work left; this makes +// the last *active* member the boundary rather than blindly using the group's last array index. +export function supersetFlowStep(entries, unit, fromIdx) { + if (!Array.isArray(entries) || !Array.isArray(unit) || unit.length <= 1) return null + const pos = unit.indexOf(fromIdx) + if (pos < 0) return null + + const unitDone = !unit.some(idx => hasWork(entries, idx)) + if (unitDone) return { unitDone: true, roundDone: false, nextIdx: null } + + const wrapped = [...unit.slice(pos + 1), ...unit.slice(0, pos + 1)] + const nextIdx = wrapped.find(idx => hasWork(entries, idx)) ?? null + const roundDone = !unit.slice(pos + 1).some(idx => hasWork(entries, idx)) + return { unitDone: false, roundDone, nextIdx } +} diff --git a/frontend/src/lib/supersetFlow.test.js b/frontend/src/lib/supersetFlow.test.js new file mode 100644 index 0000000..2c96a16 --- /dev/null +++ b/frontend/src/lib/supersetFlow.test.js @@ -0,0 +1,36 @@ +import { describe, expect, it } from 'vitest' +import { setProgressHighWater, supersetFlowStep } from './supersetFlow.js' + +const entry = done => ({ sets: done.map(value => ({ done: value })) }) + +describe('supersetFlowStep', () => { + it('does not create navigation or rest flow for a normal singleton exercise', () => { + const entries = [entry([true]), entry([false])] + expect(supersetFlowStep(entries, [0], 0)).toBeNull() + }) + + it('does not count an uncheck/re-check of previously completed work as new progress', () => { + const finished = entry([true, true, true]) + expect(setProgressHighWater(finished, 3)).toEqual({ isNew: false, highWater: 3 }) + expect(setProgressHighWater(finished, 2)).toEqual({ isNew: true, highWater: 3 }) + }) + + it('skips a spent short member and uses the last member with work as the round boundary', () => { + // A has just completed set two of three; B's only set was completed last round. + const entries = [entry([true, true, false]), entry([true])] + expect(supersetFlowStep(entries, [0, 1], 0)).toEqual({ + unitDone: false, + roundDone: true, + nextIdx: 0 + }) + }) + + it('wraps to the next member with work at a normal round boundary', () => { + const entries = [entry([true, false, false]), entry([true])] + expect(supersetFlowStep(entries, [0, 1], 1)).toEqual({ + unitDone: false, + roundDone: true, + nextIdx: 0 + }) + }) +}) diff --git a/frontend/src/views/Workout.jsx b/frontend/src/views/Workout.jsx index 94d7be9..0fcfeb7 100644 --- a/frontend/src/views/Workout.jsx +++ b/frontend/src/views/Workout.jsx @@ -1,4 +1,4 @@ -import { useEffect, useState } from 'react' +import { useEffect, useRef, useState } from 'react' import { useNavigate } from 'react-router-dom' import { useStore } from '../store/useStore.js' import { useUI } from '../store/useUI.js' @@ -8,6 +8,7 @@ import { fmtNum, fmtDate, todayISO, exCount, DAYN } from '../lib/format.js' import { beep, vibrate } from '../lib/sound.js' import { t } from '../lib/i18n.js' import { api } from '../lib/api.js' +import { setProgressHighWater, supersetFlowStep } from '../lib/supersetFlow.js' import Media from '../components/Media.jsx' import { startFlow, exercisePicker, exConfigSheet, exerciseDetailSheet, topWeightSheet, finishWorkout, workoutCompleteSheet, confirmSheet } from '../sheets.jsx' import Icon from '../components/Icon.jsx' @@ -180,6 +181,15 @@ function ActiveWorkout() { const unit = A.entries.length ? unitOf(units, cur) : [] const unitIdx = units.findIndex(u => u === unit) const isSuperset = unit.length > 1 + // Superset flow: keep the active exercise in view - completing a set scrolls to the + // next exercise in the group, then back up to the first exercise of the next round. + const exRefs = useRef({}) + const progressHighWater = useRef(A.entries.map(e => e.sets.filter(s => s.done).length)) + useEffect(() => { + if (!isSuperset) return + const el = exRefs.current[cur] + if (el && typeof el.scrollIntoView === 'function') el.scrollIntoView({ behavior: 'smooth', block: 'nearest' }) + }, [cur, isSuperset, A.entries.length]) const total = A.entries.reduce((n, e) => n + e.sets.length, 0) const done = setsDoneActive(A) @@ -234,15 +244,13 @@ function ActiveWorkout() { const m = modeAt(idx) const cardioEntry = m === 'cardio' const isLastUnit = unitIdx >= units.length - 1 - let askTop = false, exJustDone = false, workoutDone = false + let askTop = false, exJustDone = false, workoutDone = false, checked = false mutEntry(idx, e => { e.sets[i].done = !e.sets[i].done + checked = e.sets[i].done if (e.sets[i].done) { beep(S.sound, 1040, 0.12); vibrate(30) - const isLastExInUnit = idx === unit[unit.length - 1] const unitDone = unit.every(ui => (ui === idx ? e : A.entries[ui]).sets.every(x => x.done)) - if (isLastExInUnit && !unitDone) startRest(S.restSec) - else if (unitDone) stopRest() if (unitDone && isLastUnit) workoutDone = true // last exercise's last set โ†’ done // Only loaded reps training has a "working weight" worth confirming โ€” a bodyweight // plank has nothing to put in that slider, and neither does a set of push-ups @@ -257,6 +265,43 @@ function ActiveWorkout() { else if (workoutDone) workoutCompleteSheet() else if (exJustDone && cardioEntry) useUI.getState().toast(t('Cardio logged')) else if (exJustDone && m === 'time') useUI.getState().toast(t('Hold logged')) + + // Only progress beyond this exercise's high-water mark may navigate or change rest. This + // prevents an uncheck/re-check of finished work from replaying the flow side effects. + const fresh = useStore.getState().S.active + if (fresh && checked && fresh.entries[idx]) { + const progress = setProgressHighWater(fresh.entries[idx], progressHighWater.current[idx] || 0) + progressHighWater.current[idx] = progress.highWater + if (!progress.isNew) return + + const freshUnits = supersetUnits(fresh.entries) + const freshUnit = freshUnits.find(u => u.includes(idx)) + const freshUnitIdx = freshUnits.indexOf(freshUnit) + const freshLastUnit = freshUnitIdx >= freshUnits.length - 1 + const freshUnitDone = freshUnit?.every(ui => fresh.entries[ui].sets.every(x => x.done)) + + // Singleton units are ordinary exercises: preserve their historical between-set rest, + // while final sets finish quietly and never enter superset navigation. + if (freshUnitDone) stopRest() + if (!freshUnit || freshUnit.length <= 1) { + if (!freshUnitDone) startRest(S.restSec) + return + } + + const step = supersetFlowStep(fresh.entries, freshUnit, idx) + if (!step) return + if (step.unitDone) { + if (!freshLastUnit) { + const nextUnit = freshUnits[freshUnitIdx + 1] + // The top-weight sheet's explicit "Just close" path owns the choice not to advance. + if (!askTop && nextUnit?.length) update(s => { if (s.active) s.active.cur = nextUnit[0] }) + startRest(S.restSec) + } + } else { + if (step.nextIdx != null) update(s => { if (s.active) s.active.cur = step.nextIdx }) + if (step.roundDone) startRest(S.restSec) + } + } } // Live-presence heartbeat so the admin dashboard can show who's training now. Signed-in only โ€” @@ -302,7 +347,7 @@ function ActiveWorkout() { {t('Superset ยท do these back-to-back, rest when done')} - {unit.map((idx, k) =>
+ {unit.map((idx, k) =>
{ exRefs.current[idx] = el }} className="ss-ex" data-exidx={idx}> {k > 0 &&
+
} toggle(idx, i)} onField={(i, f, v) => setField(idx, i, f, v)} onAddSet={() => addSet(idx)} onRemoveSet={() => removeSet(idx)} onAddWarmup={() => addWarmup(idx)} onRemoveSetAt={i => removeSetAt(idx, i)} onStartTimed={i => startTimed(idx, i)} /> diff --git a/frontend/src/views/Workout.test.jsx b/frontend/src/views/Workout.test.jsx new file mode 100644 index 0000000..9794b7e --- /dev/null +++ b/frontend/src/views/Workout.test.jsx @@ -0,0 +1,146 @@ +import React, { act } from 'react' +import { createRoot } from 'react-dom/client' +import { parseHTML } from 'linkedom' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import Workout from './Workout.jsx' + +const mocks = vi.hoisted(() => { + const state = { + S: null, + startRest: vi.fn(), + stopRest: vi.fn(), + topWeightSheet: vi.fn(), + } + state.storeSnapshot = () => ({ + S: state.S, + user: null, + update: mut => mut(state.S), + }) + state.uiSnapshot = () => ({ + work: null, + startRest: state.startRest, + stopRest: state.stopRest, + startWork: vi.fn(), + toast: vi.fn(), + }) + return state +}) + +vi.mock('../store/useStore.js', () => { + const useStore = selector => selector(mocks.storeSnapshot()) + useStore.getState = mocks.storeSnapshot + return { useStore } +}) +vi.mock('../store/useUI.js', () => { + const useUI = selector => selector ? selector(mocks.uiSnapshot()) : mocks.uiSnapshot() + useUI.getState = mocks.uiSnapshot + return { useUI } +}) +vi.mock('react-router-dom', () => ({ useNavigate: () => () => {} })) +vi.mock('../sheets.jsx', () => ({ + startFlow: vi.fn(), + exercisePicker: vi.fn(), + exConfigSheet: vi.fn(), + exerciseDetailSheet: vi.fn(), + topWeightSheet: mocks.topWeightSheet, + finishWorkout: vi.fn(), + workoutCompleteSheet: vi.fn(), + confirmSheet: vi.fn(), +})) +vi.mock('../components/Media.jsx', () => ({ default: () => null })) + +let dom +let root +let container + +function exercise(id, sets, extra = {}) { + return { + id, + target: { mode: 'reps', reps: 5, weight: 60, bodyweight: false }, + sets: sets.map(done => ({ w: 60, r: 5, done })), + ...extra, + } +} + +function workout(entries, cur = 0) { + return { + unit: 'kg', restSec: 90, sound: false, effort: 'none', gifSize: 'full', + workouts: [], exWeights: {}, routines: [], + active: { id: 'active', name: 'Test workout', start: Date.now(), cur, entries }, + } +} + +function installDom() { + const parsed = parseHTML('
') + dom = parsed.window + globalThis.window = dom + globalThis.document = dom.document + Object.defineProperty(globalThis, 'navigator', { configurable: true, value: dom.navigator }) + for (const key of ['HTMLElement', 'Node', 'Element', 'Event', 'Blob']) globalThis[key] = dom[key] + globalThis.IS_REACT_ACT_ENVIRONMENT = true + container = document.getElementById('root') + root = createRoot(container) +} + +async function mount(entries, cur = 0) { + mocks.S = workout(entries, cur) + installDom() + await act(async () => { root.render(React.createElement(Workout)) }) +} + +async function unmount() { + if (!root) return + await act(async () => { root.unmount() }) + root = null + container = null + dom = null +} + +async function toggleSet(index) { + const checkbox = container.querySelectorAll('[role="checkbox"]')[index] + expect(checkbox).toBeTruthy() + await act(async () => { checkbox.dispatchEvent(new dom.Event('click', { bubbles: true })) }) +} + +beforeEach(() => { + vi.clearAllMocks() +}) + +afterEach(async () => { + await unmount() +}) + +describe('Workout set completion flow', () => { + it('starts rest after a non-final ordinary set, but stops rest without restarting it on the final set', async () => { + await mount([exercise('plain-bench', [false, false, false])]) + await toggleSet(0) + + expect(mocks.startRest).toHaveBeenCalledOnce() + expect(mocks.startRest).toHaveBeenCalledWith(90) + expect(mocks.stopRest).not.toHaveBeenCalled() + + await unmount() + vi.clearAllMocks() + await mount([exercise('plain-treadmill', [false], { + target: { mode: 'cardio', min: 20, speed: 8 }, + })]) + await toggleSet(0) + + expect(mocks.stopRest).toHaveBeenCalledOnce() + expect(mocks.startRest).not.toHaveBeenCalled() + }) + + it('leaves a completed superset selected while its top-weight sheet owns the advance choice', async () => { + const group = 'superset-1' + await mount([ + exercise('superset-a', [true, true, true], { sg: group, asked: true }), + exercise('superset-b', [true, true, false], { sg: group }), + exercise('next-exercise', [false, false, false]), + ], 1) + await toggleSet(5) + + expect(mocks.topWeightSheet).toHaveBeenCalledWith(1) + expect(mocks.S.active.cur).toBe(1) + expect(mocks.startRest).toHaveBeenCalledWith(90) + }) +})