From 82f0b84766c41a2d58469e6de0f03dd7997e372b Mon Sep 17 00:00:00 2001 From: Space_Hermes Date: Thu, 27 Aug 2026 09:15:40 +0200 Subject: [PATCH] fix(workout): continue after added exercise --- frontend/src/lib/supersetFlow.js | 21 ++++ frontend/src/lib/supersetFlow.test.js | 22 +++- frontend/src/sheets.jsx | 11 +- frontend/src/views/Workout.jsx | 24 ++--- frontend/src/views/Workout.test.jsx | 149 ++++++++++++++++++++++++-- 5 files changed, 200 insertions(+), 27 deletions(-) diff --git a/frontend/src/lib/supersetFlow.js b/frontend/src/lib/supersetFlow.js index 4b8c8fb..63baecf 100644 --- a/frontend/src/lib/supersetFlow.js +++ b/frontend/src/lib/supersetFlow.js @@ -2,6 +2,27 @@ // 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) +// Return the first unfinished navigation unit after the current one, wrapping once so a user +// who completed units out of order is never offered workout completion while earlier work remains. +export function nextUnfinishedUnit(entries, units, fromIdx) { + if (!Array.isArray(entries) || !Array.isArray(units) || units.length === 0) return null + const current = units.findIndex(unit => unit.includes(fromIdx)) + const ordered = current < 0 + ? units + : [...units.slice(current + 1), ...units.slice(0, current)] + return ordered.find(unit => unit.some(idx => hasWork(entries, idx))) || null +} + +// The current exercise may be one member of a contiguous superset. Insert after that complete +// navigation unit; invalid/empty state safely falls back to the end of the entry list. +export function insertionIndexAfterCurrentUnit(units, currentIndex, entryCount) { + const length = Math.max(0, Number(entryCount) || 0) + if (!Array.isArray(units) || units.length === 0) return length + const unit = units.find(candidate => candidate.includes(currentIndex)) + if (!unit?.length) return length + return Math.min(length, Math.max(...unit) + 1) +} + // 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. diff --git a/frontend/src/lib/supersetFlow.test.js b/frontend/src/lib/supersetFlow.test.js index 91864f1..39ba4be 100644 --- a/frontend/src/lib/supersetFlow.test.js +++ b/frontend/src/lib/supersetFlow.test.js @@ -1,5 +1,5 @@ import { describe, expect, it } from 'vitest' -import { setProgressHighWater, supersetFlowStep, restAfterSet, restOnRecheck } from './supersetFlow.js' +import { insertionIndexAfterCurrentUnit, nextUnfinishedUnit, setProgressHighWater, supersetFlowStep, restAfterSet, restOnRecheck } from './supersetFlow.js' const entry = done => ({ sets: done.map(value => ({ done: value })) }) @@ -52,6 +52,26 @@ describe('supersetFlowStep', () => { }) }) +describe('active workout unit ordering', () => { + it('inserts after the whole current unit', () => { + expect(insertionIndexAfterCurrentUnit([[0, 1], [2]], 0, 3)).toBe(2) + expect(insertionIndexAfterCurrentUnit([[0], [1]], 1, 2)).toBe(2) + expect(insertionIndexAfterCurrentUnit([], 0, 0)).toBe(0) + }) + + it('finds the next unfinished unit, skips completed units, and wraps once', () => { + const entries = [entry([false]), entry([true]), entry([false]), entry([true])] + const units = [[0], [1], [2, 3]] + expect(nextUnfinishedUnit(entries, units, 0)).toEqual([2, 3]) + expect(nextUnfinishedUnit(entries, units, 2)).toEqual([0]) + }) + + it('returns null only when every unit is complete', () => { + const entries = [entry([true]), entry([true])] + expect(nextUnfinishedUnit(entries, [[0], [1]], 1)).toBeNull() + }) +}) + // Issue #3 has two halves. restAfterSet covers "no break after the LAST set of an exercise"; // this covers "after the first set, sometimes a break doesn't appear" — the uncheck/re-check // that the high-water rule swallows. diff --git a/frontend/src/sheets.jsx b/frontend/src/sheets.jsx index 00ad49f..dee1d97 100644 --- a/frontend/src/sheets.jsx +++ b/frontend/src/sheets.jsx @@ -23,6 +23,7 @@ import { nextPrescription, applyPrescription, policyFor, defaultIncrement, POLIC import { MOBILE, shareExport } from './lib/mobile.js' import { buildCompletedWorkout } from './lib/finish-workout.js' import { isWarmupRow } from './lib/workout-model.js' +import { nextUnfinishedUnit } from './lib/supersetFlow.js' const S = () => useStore.getState().S const update = (...a) => useStore.getState().update(...a) @@ -1058,8 +1059,8 @@ function TopWeight({ entryIdx, close }) { const units = supersetUnits(A ? A.entries : []) const unit = entry ? unitOf(units, entryIdx) : [] const unitDone = !!entry && unit.every(i => A.entries[i].sets.every(s => s.done)) - const unitIdx = units.findIndex(u => u === unit) - const isLastUnit = unitIdx === units.length - 1 + const nextUnit = unitDone ? nextUnfinishedUnit(A.entries, units, entryIdx) : null + const workoutDone = unitDone && !nextUnit if (!entry || !ex) return null const commit = advance => { @@ -1072,8 +1073,8 @@ function TopWeight({ entryIdx, close }) { }) close() if (advance && unitDone) { - if (isLastUnit) workoutCompleteSheet() // whole workout done → finish/continue prompt - else update(s => { s.active.cur = units[unitIdx + 1][0] }) + if (workoutDone) workoutCompleteSheet() // no unfinished unit → finish/continue prompt + else update(s => { s.active.cur = nextUnit[0] }) } else toast(t('Tracked — next time starts at {0}', fmtNum(S().exWeights[entry.id].w) + ' ' + st.unit)) } return <> @@ -1083,7 +1084,7 @@ function TopWeight({ entryIdx, close }) {
{prevBest > 0 ?
{t('Previous best:')} {fmtNum(prevBest)} {st.unit}{maxSet > prevBest && — {t('new record!')}}
:
} {unitDone ? <> - +
: } diff --git a/frontend/src/views/Workout.jsx b/frontend/src/views/Workout.jsx index d0a6279..46c222f 100644 --- a/frontend/src/views/Workout.jsx +++ b/frontend/src/views/Workout.jsx @@ -8,7 +8,7 @@ import { fmtNum, fmtDate, todayISO, exCount, DAYN } from '../lib/format.js' import { beep, vibrate } from '../lib/sound.js' import { t, exerciseNameFor } from '../lib/i18n.js' import { api } from '../lib/api.js' -import { setProgressHighWater, supersetFlowStep, restAfterSet, restOnRecheck } from '../lib/supersetFlow.js' +import { insertionIndexAfterCurrentUnit, nextUnfinishedUnit, setProgressHighWater, supersetFlowStep, restAfterSet, restOnRecheck } from '../lib/supersetFlow.js' import Media from '../components/Media.jsx' import { startFlow, exercisePicker, exConfigSheet, exerciseDetailSheet, topWeightSheet, finishWorkout, workoutCompleteSheet, confirmSheet, exerciseNoteSheet, sessionNoteSheet } from '../sheets.jsx' import Icon from '../components/Icon.jsx' @@ -382,7 +382,6 @@ function ActiveWorkout() { const toggle = (idx, i) => { const m = modeAt(idx) const cardioEntry = m === 'cardio' - const isLastUnit = unitIdx >= units.length - 1 let askTop = false, exJustDone = false, workoutDone = false, checked = false mutEntry(idx, e => { e.sets[i].done = !e.sets[i].done @@ -390,7 +389,7 @@ function ActiveWorkout() { if (e.sets[i].done) { beep(S.sound, 1040, 0.12); vibrate(30) const unitDone = unit.every(ui => (ui === idx ? e : A.entries[ui]).sets.every(x => x.done)) - if (unitDone && isLastUnit) workoutDone = true // last exercise's last set → done + if (unitDone) workoutDone = !nextUnfinishedUnit(A.entries, supersetUnits(A.entries), idx) // 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 // (issue #32: the fewest taps that still record what happened). @@ -414,14 +413,14 @@ function ActiveWorkout() { 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)) + const nextUnit = freshUnitDone ? nextUnfinishedUnit(fresh.entries, freshUnits, idx) : null + const freshWorkoutDone = freshUnitDone && !nextUnit // A re-check of finished work must not navigate or reopen a sheet, but it may still owe // you a rest — see restOnRecheck, and the other half of issue #3. if (!progress.isNew) { - if (restOnRecheck({ timerRunning: !!useUI.getState().timer, unitDone: freshUnitDone, lastUnit: freshLastUnit })) startRest(S.restSec) + if (restOnRecheck({ timerRunning: !!useUI.getState().timer, unitDone: freshUnitDone, lastUnit: freshWorkoutDone })) startRest(S.restSec) return } @@ -430,17 +429,17 @@ function ActiveWorkout() { // after this set replaces the one that was running, rather than stacking on it. if (freshUnitDone) stopRest() if (!freshUnit || freshUnit.length <= 1) { - if (restAfterSet({ unitDone: freshUnitDone, lastUnit: freshLastUnit })) startRest(S.restSec) + if (freshUnitDone && !askTop && nextUnit?.length) update(s => { if (s.active) s.active.cur = nextUnit[0] }) + if (restAfterSet({ unitDone: freshUnitDone, lastUnit: freshWorkoutDone })) startRest(S.restSec) return } const step = supersetFlowStep(fresh.entries, freshUnit, idx) if (!step) return if (step.unitDone) { - if (!freshLastUnit) { - const nextUnit = freshUnits[freshUnitIdx + 1] + if (nextUnit?.length) { // 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] }) + if (!askTop) update(s => { if (s.active) s.active.cur = nextUnit[0] }) startRest(S.restSec) } } else { @@ -521,8 +520,9 @@ function ActiveWorkout() { const plan = freestyle ? null : nextPrescription(s, full, s.routines.find(r => r.id === s.active.routineId)) const sets = buildSets(s, full, { step: defaultIncrement(ex.id, s.unit), ...(freestyle ? { preferLast: true } : {}) }) const progressed = freestyle ? sets : applyPrescription(sets, plan, defaultIncrement(ex.id, s.unit)) - s.active.entries.push({ id: ex.id, target: { ...cfg }, plan, sets: applyIntensifierPlan(progressed, full) }) - s.active.cur = s.active.entries.length - 1 + const insertAt = insertionIndexAfterCurrentUnit(supersetUnits(s.active.entries), s.active.cur, s.active.entries.length) + s.active.entries.splice(insertAt, 0, { id: ex.id, target: { ...cfg }, plan, sets: applyIntensifierPlan(progressed, full) }) + s.active.cur = insertAt }), null, routine, seed) })} icon="plus">{t('Add exercise')} {A.entries.length > 0 && <> diff --git a/frontend/src/views/Workout.test.jsx b/frontend/src/views/Workout.test.jsx index 0564b8a..ff9f8d5 100644 --- a/frontend/src/views/Workout.test.jsx +++ b/frontend/src/views/Workout.test.jsx @@ -10,18 +10,26 @@ const mocks = vi.hoisted(() => { startRest: vi.fn(), stopRest: vi.fn(), topWeightSheet: vi.fn(), + workoutCompleteSheet: vi.fn(), + exercisePicker: vi.fn(), + exConfigSheet: vi.fn(), + toast: vi.fn(), } state.storeSnapshot = () => ({ S: state.S, user: null, - update: mut => mut(state.S), + update: mut => { + const next = structuredClone(state.S) + mut(next) + state.S = next + }, }) state.uiSnapshot = () => ({ work: null, startRest: state.startRest, stopRest: state.stopRest, startWork: vi.fn(), - toast: vi.fn(), + toast: state.toast, }) return state }) @@ -39,12 +47,12 @@ vi.mock('../store/useUI.js', () => { vi.mock('react-router-dom', () => ({ useNavigate: () => () => {} })) vi.mock('../sheets.jsx', () => ({ startFlow: vi.fn(), - exercisePicker: vi.fn(), - exConfigSheet: vi.fn(), + exercisePicker: mocks.exercisePicker, + exConfigSheet: mocks.exConfigSheet, exerciseDetailSheet: vi.fn(), topWeightSheet: mocks.topWeightSheet, finishWorkout: vi.fn(), - workoutCompleteSheet: vi.fn(), + workoutCompleteSheet: mocks.workoutCompleteSheet, confirmSheet: vi.fn(), // Both note sheets belong here even though the tests never open one: Workout.jsx reads // sessionNoteSheet during render, so a missing export is a render crash, not a no-op. @@ -72,11 +80,13 @@ function exercise(id, sets, extra = {}) { } } -function workout(entries, cur = 0) { +function workout(entries, cur = 0, overrides = {}) { + const { active: activeOverrides = {}, ...stateOverrides } = overrides 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 }, + active: { id: 'active', name: 'Test workout', start: Date.now(), cur, entries, ...activeOverrides }, + ...stateOverrides, } } @@ -92,8 +102,8 @@ function installDom() { root = createRoot(container) } -async function mount(entries, cur = 0) { - mocks.S = workout(entries, cur) +async function mount(entries, cur = 0, overrides = {}) { + mocks.S = workout(entries, cur, overrides) installDom() await act(async () => { root.render(React.createElement(Workout)) }) } @@ -112,6 +122,25 @@ async function toggleSet(index) { await act(async () => { checkbox.dispatchEvent(new dom.Event('click', { bubbles: true })) }) } +async function rerender() { + await act(async () => { root.render(React.createElement(Workout)) }) +} + +async function addExerciseThroughSheets(ex = { id: 'added-exercise' }, cfg = { mode: 'reps', sets: 1, reps: 5, weight: 0 }) { + const addButton = [...container.querySelectorAll('button')] + .find(button => button.textContent.trim() === 'Add exercise') + expect(addButton).toBeTruthy() + await act(async () => { addButton.dispatchEvent(new dom.Event('click', { bubbles: true })) }) + + const pickerCall = mocks.exercisePicker.mock.calls.at(-1) + expect(pickerCall?.[0]).toEqual(expect.any(Function)) + await act(async () => { pickerCall[0](ex) }) + + const configCall = mocks.exConfigSheet.mock.calls.at(-1) + expect(configCall?.[2]).toEqual(expect.any(Function)) + await act(async () => { configCall[2](cfg) }) +} + beforeEach(() => { vi.clearAllMocks() }) @@ -153,6 +182,108 @@ describe('Workout set completion flow', () => { expect(mocks.S.active.cur).toBe(1) expect(mocks.startRest).toHaveBeenCalledWith(90) }) + + it('skips completed intervening units and selects the next unfinished superset as one unit', async () => { + await mount([ + exercise('current-hold', [false], { asked: true, target: { mode: 'time', sec: 30, weight: 0 } }), + exercise('already-done', [true], { asked: true }), + exercise('pending-a', [false], { sg: 'pending-group' }), + exercise('pending-b', [false], { sg: 'pending-group' }), + ]) + + await toggleSet(0) + + expect(mocks.S.active.cur).toBe(2) + expect(mocks.workoutCompleteSheet).not.toHaveBeenCalled() + expect(mocks.toast).toHaveBeenCalledWith('Hold logged') + expect(mocks.startRest).toHaveBeenCalledWith(90) + }) + + it('wraps to earlier unfinished work instead of showing a false completion prompt', async () => { + await mount([ + exercise('pending-earlier', [false], { asked: true }), + exercise('current-hold', [false], { asked: true, target: { mode: 'time', sec: 30, weight: 0 } }), + ], 1) + + await toggleSet(0) + + expect(mocks.S.active.cur).toBe(0) + expect(mocks.workoutCompleteSheet).not.toHaveBeenCalled() + expect(mocks.startRest).toHaveBeenCalledWith(90) + }) + + it('keeps top-weight confirmation in control without declaring completion while work remains', async () => { + await mount([ + exercise('current-loaded', [false]), + exercise('pending', [false], { asked: true }), + ]) + + await toggleSet(0) + + expect(mocks.topWeightSheet).toHaveBeenCalledWith(0) + expect(mocks.workoutCompleteSheet).not.toHaveBeenCalled() + expect(mocks.S.active.cur).toBe(0) + }) + + it('shows workout completion only when no unfinished unit remains', async () => { + await mount([ + exercise('already-done', [true], { asked: true }), + exercise('final-hold', [false], { asked: true, target: { mode: 'time', sec: 30, weight: 0 } }), + ], 1) + + await toggleSet(0) + + expect(mocks.workoutCompleteSheet).toHaveBeenCalledOnce() + expect(mocks.startRest).not.toHaveBeenCalled() + }) +}) + +describe('Workout add exercise flow', () => { + it.each([ + ['freestyle', {}], + ['planned', { + active: { routineId: 'routine-1' }, + routines: [{ id: 'routine-1', ex: [] }], + }], + ])('inserts after the current unit and continues to pending work in a %s session', async (_label, overrides) => { + await mount([ + exercise('current', [true], { asked: true }), + exercise('pending', [false], { asked: true }), + ], 0, overrides) + + await addExerciseThroughSheets( + { id: 'inserted' }, + { mode: 'time', sets: 1, sec: 30, weight: 0 }, + ) + + expect(mocks.S.active.entries.map(entry => entry.id)).toEqual(['current', 'inserted', 'pending']) + expect(mocks.S.active.cur).toBe(1) + + await rerender() + await toggleSet(0) + + expect(mocks.S.active.entries[1].sets[0].done).toBe(true) + expect(mocks.S.active.cur).toBe(2) + expect(mocks.workoutCompleteSheet).not.toHaveBeenCalled() + }) + + it('inserts after the complete current superset without splitting the group', async () => { + await mount([ + exercise('current-a', [true], { sg: 'current-group', asked: true }), + exercise('current-b', [true], { sg: 'current-group', asked: true }), + exercise('pending', [false], { asked: true }), + ]) + + await addExerciseThroughSheets({ id: 'inserted' }) + + expect(mocks.S.active.entries.map(entry => entry.id)).toEqual([ + 'current-a', 'current-b', 'inserted', 'pending', + ]) + expect(mocks.S.active.entries.slice(0, 2).map(entry => entry.sg)).toEqual([ + 'current-group', 'current-group', + ]) + expect(mocks.S.active.cur).toBe(2) + }) }) describe('superset flow survives an exercise being removed mid-session', () => {