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 109db12..6aef667 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) @@ -1069,8 +1070,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 => { @@ -1083,8 +1084,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 <> @@ -1094,7 +1095,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 0d86b04..c9b9707 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' @@ -383,7 +383,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 @@ -391,7 +390,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). @@ -415,34 +414,37 @@ 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 + const restBeforeWarmup = nextUnit?.some(ui => + fresh.entries[ui].sets.some(set => isWarmupRow(set) && !set.done), + ) // 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 (!restBeforeWarmup && restOnRecheck({ timerRunning: !!useUI.getState().timer, unitDone: freshUnitDone, lastUnit: freshWorkoutDone })) startRest(S.restSec) return } // Singleton units are ordinary exercises: they rest between sets and after the closing - // one, and never enter superset navigation. stopRest() first so the rest that belongs - // after this set replaces the one that was running, rather than stacking on it. + // one unless the next unit has an unfinished warm-up, and never enter superset navigation. + // stopRest() first so a rest that belongs after this set replaces the one that was running. 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 (!restBeforeWarmup && 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] }) - startRest(S.restSec) + if (!askTop) update(s => { if (s.active) s.active.cur = nextUnit[0] }) + if (!restBeforeWarmup) startRest(S.restSec) } } else { if (step.nextIdx != null) update(s => { if (s.active) s.active.cur = step.nextIdx }) @@ -522,8 +524,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 18ac7bf..e094180 100644 --- a/frontend/src/views/Workout.test.jsx +++ b/frontend/src/views/Workout.test.jsx @@ -14,13 +14,21 @@ const mocks = vi.hoisted(() => { stopWork: null, confirmSheet: vi.fn(), topWeightSheet: vi.fn(), + workoutCompleteSheet: vi.fn(), + exercisePicker: vi.fn(), + exConfigSheet: vi.fn(), + toast: vi.fn(), } state.stopRest = vi.fn(() => { state.timer = null }) state.stopWork = vi.fn(() => { state.work = null }) 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 = () => ({ timer: state.timer, @@ -29,7 +37,7 @@ const mocks = vi.hoisted(() => { stopRest: state.stopRest, stopWork: state.stopWork, startWork: vi.fn(), - toast: vi.fn(), + toast: state.toast, }) return state }) @@ -47,12 +55,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: mocks.confirmSheet, // 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. @@ -80,11 +88,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, } } @@ -100,8 +110,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)) }) } @@ -126,6 +136,25 @@ async function requestDiscard() { await act(async () => { button.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() mocks.timer = null @@ -156,6 +185,85 @@ describe('Workout set completion flow', () => { expect(mocks.startRest).not.toHaveBeenCalled() }) + it.each(['warmup', 'warm-up', 'warm_up'])( + 'does not start transition rest before an incomplete %s row in the next ordinary exercise', + async phase => { + await mount([ + exercise('current', [false], { asked: true }), + exercise('next', [false, false], { + asked: true, + sets: [ + { w: 30, r: 5, done: false, phase }, + { w: 60, r: 5, done: false }, + ], + }), + ]) + + await toggleSet(0) + + expect(mocks.S.active.cur).toBe(1) + expect(mocks.startRest).not.toHaveBeenCalled() + }, + ) + + it('does not start transition rest when a completed superset advances to an incomplete warm-up', async () => { + await mount([ + exercise('superset-a', [true], { sg: 'group', asked: true }), + exercise('superset-b', [false], { sg: 'group', asked: true }), + exercise('next', [false, false], { + asked: true, + sets: [ + { w: 30, r: 5, done: false, phase: 'warmup' }, + { w: 60, r: 5, done: false }, + ], + }), + ], 1) + + await toggleSet(1) + + expect(mocks.S.active.cur).toBe(2) + expect(mocks.startRest).not.toHaveBeenCalled() + }) + + it('does not start transition rest before a warm-up while top-weight confirmation owns navigation', async () => { + await mount([ + exercise('current-loaded', [false]), + exercise('next', [false, false], { + asked: true, + sets: [ + { w: 30, r: 5, done: false, phase: 'warmup' }, + { w: 60, r: 5, done: false }, + ], + }), + ]) + + await toggleSet(0) + + expect(mocks.topWeightSheet).toHaveBeenCalledWith(0) + expect(mocks.S.active.cur).toBe(0) + expect(mocks.startRest).not.toHaveBeenCalled() + }) + + it('does not restart transition rest when re-checking a completed unit before an incomplete warm-up', async () => { + await mount([ + exercise('current', [true], { asked: true }), + exercise('next', [false, false], { + asked: true, + sets: [ + { w: 30, r: 5, done: false, phase: 'warmup' }, + { w: 60, r: 5, done: false }, + ], + }), + ]) + + await toggleSet(0) + await rerender() + await toggleSet(0) + + expect(mocks.S.active.cur).toBe(0) + 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([ @@ -169,6 +277,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('Workout discard timer lifecycle', () => {