fix(workout): preserve per-side data across progression and session flows
- Apply progression targets to each unfinished side - Convert per-side weights and drops between kg and lb - Preserve partially completed sets when finishing early - Calculate volume from each side's actual completed work - Keep L/R tracking for planned rest-pause sets - Auto-complete the rated side when logging RIR/RPE - Add regression tests for these flows Validation: 1341 frontend tests passed; production build passed.
This commit is contained in:
1 parent
acff80348f
commit
195db73600
10 files changed
+201
-17
No files matched your search
@@ -1,5 +1,5 @@
|
||||
import { metricModeForEntry, metricRowsForEntry, bestWeightForEntry, modeOf } from './history.js'
|
||||
import { extraVolumeOf } from './workout-model.js'
|
||||
import { completedVolumeOf } from './workout-model.js'
|
||||
import { bestSetOf } from './onerm.js'
|
||||
|
||||
// One exercise's past, read back for the history sheet (issue #43): a chart series and the
|
||||
@@ -24,7 +24,7 @@ const startOf = w => (Number.isFinite(w.start) ? w.start : new Date(w.d + 'T12:0
|
||||
|
||||
// Volume of the exercise in one session: main set plus its drops/bursts, reps mode only —
|
||||
// there is no honest tonnage for a hold or a run.
|
||||
const entryVolume = rows => rows.reduce((v, s) => v + (s.w || 0) * (s.r || 0) + extraVolumeOf(s), 0)
|
||||
const entryVolume = rows => rows.reduce((v, s) => v + completedVolumeOf(s), 0)
|
||||
|
||||
export function exerciseHistory(S, exId, { limit = HISTORY_SESSIONS } = {}) {
|
||||
const workouts = S?.workouts || []
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
// The persisted boundary for a finished session. Keep this pure so compatibility tests can
|
||||
// exercise the exact shape the UI writes without mounting React or mutating store state.
|
||||
import { bestWeightForEntry } from './history.js'
|
||||
import { hasCompletedWork } from './workout-model.js'
|
||||
|
||||
export function buildCompletedWorkout(active, { end = Date.now(), prs = [], snapshotFor } = {}) {
|
||||
const entries = (active?.entries || []).map(entry => {
|
||||
@@ -28,7 +29,7 @@ export function buildCompletedWorkout(active, { end = Date.now(), prs = [], snap
|
||||
if (entry.notePin) completed.notePin = true
|
||||
}
|
||||
return completed
|
||||
}).filter(entry => entry.sets.some(set => set.done))
|
||||
}).filter(entry => entry.sets.some(hasCompletedWork))
|
||||
|
||||
const sessionNote = (active?.note || '').trim()
|
||||
const routineIds = [].concat(active?.routineIds ?? (active?.routineId ? [active.routineId] : []))
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// Pure helpers over the state object S (ported 1:1 from the vanilla app).
|
||||
import { todayISO, isoOf, weekKey, weekStartOf, fmtNum } from './format.js'
|
||||
import { isCardio, isBodyweightEq } from './exercises.js'
|
||||
import { phaseForSet, modeForSet, modeForEntry, isWarmupRow, normalizeMode, extraVolumeOf, nextDropWeight, splitBurstReps, makeSideSet, isSideSet, syncSideAggregate } from './workout-model.js'
|
||||
import { phaseForSet, modeForSet, modeForEntry, isWarmupRow, normalizeMode, completedVolumeOf, nextDropWeight, splitBurstReps, makeSideSet, isSideSet, syncSideAggregate } from './workout-model.js'
|
||||
const objectOf = value => value && typeof value === 'object' && !Array.isArray(value) ? value : {}
|
||||
// Completed-state-independent work rows whose authoritative mode matches the requested mode.
|
||||
const workRowsForMode = (entry = {}, mode = 'reps') => {
|
||||
@@ -120,7 +120,11 @@ export function setLabel(id, s, cfg) {
|
||||
// A unilateral set logged per side (issue #60) reads "L 15×8 · R 15×7" — the asymmetry is the
|
||||
// whole point, so both sides are shown rather than a single combined total.
|
||||
if (isSideSet(s)) {
|
||||
return `${t('L')} ${oneSide(s.sides.L)}${effortTail(s.sides.L)} · ${t('R')} ${oneSide(s.sides.R)}${effortTail(s.sides.R)}`
|
||||
const partial = s.sides.L.done !== s.sides.R.done
|
||||
return ['L', 'R'].map(key => {
|
||||
const side = s.sides[key]
|
||||
return `${t(key)} ${partial && !side.done ? '—' : oneSide(side) + effortTail(side)}`
|
||||
}).join(' · ')
|
||||
}
|
||||
// Bodyweight reads as what you did — "12", or "+10 × 12" once there is a belt involved —
|
||||
// rather than "0×12", which says a set was performed with no weight and means nothing.
|
||||
@@ -471,20 +475,30 @@ export function applyIntensifierPlan(sets, cfg) {
|
||||
const w = (sets.find(s => !isWarmupRow(s)) || sets[0] || {}).w || 0
|
||||
const warmup = { w, r: Math.max(1, Math.round(cfg.reps) || 1), done: false, phase: 'warmup' }
|
||||
const work = { w, r: totalReps, done: false, type: 'restpause', clusters: splitBurstReps(totalReps).map(r => ({ r, restSec })) }
|
||||
if (isPerSide(cfg)) {
|
||||
const source = sets.find(s => !isWarmupRow(s))
|
||||
// The configured total covers both limbs; preserve it even for an odd total.
|
||||
const side = (key, reps) => ({
|
||||
w: source?.sides?.[key]?.w ?? w, r: reps, done: false, type: 'restpause',
|
||||
clusters: splitBurstReps(reps).map(r => ({ r, restSec })),
|
||||
})
|
||||
return [warmup, syncSideAggregate({ ...work, sides: {
|
||||
L: side('L', Math.ceil(totalReps / 2)), R: side('R', Math.floor(totalReps / 2)),
|
||||
} })]
|
||||
}
|
||||
return [warmup, work]
|
||||
}
|
||||
export function workoutVolume(w) {
|
||||
let v = 0
|
||||
// No special case for unilateral work: a per-side set logs its total, so both sides are
|
||||
// already in the rep count that arrives here. Drop-set drops and rest-pause bursts add their
|
||||
// own weight x reps on top of the row's main/activation set (see extraVolumeOf).
|
||||
// Count each completed limb at its own load, including drops. A rest-pause side's r already
|
||||
// includes its bursts. Unchecked limbs and warm-ups contribute no volume.
|
||||
// Warm-ups are excluded here as everywhere else. The config sheet promises it in so many
|
||||
// words ("left out of volume, records and progression") and every other consumer already
|
||||
// does it; this line was the one that did not, which only stopped being harmless when a
|
||||
// routine started planning warm-ups by default. The number is written into the saved
|
||||
// workout, so an inflated one would stay wrong forever.
|
||||
w.entries.forEach(e => e.sets.forEach(s => {
|
||||
if (s.done && !isWarmupRow(s)) v += (s.w || 0) * (s.r || 0) + extraVolumeOf(s)
|
||||
if (!isWarmupRow(s)) v += completedVolumeOf(s)
|
||||
}))
|
||||
return v
|
||||
}
|
||||
|
||||
@@ -18,7 +18,7 @@
|
||||
|
||||
import { modeOf, repStep, rerampWarmups, isBw, isPerSide, entryExcluded } from './history.js'
|
||||
import { EXIDX } from './exercises.js'
|
||||
import { isWarmupRow } from './workout-model.js'
|
||||
import { isWarmupRow, isSideSet, syncSideAggregate, makeSideSet } from './workout-model.js'
|
||||
import { normalizeRepRange } from './rep-range.js'
|
||||
|
||||
export const POLICIES = ['off', 'linear', 'greyskull', 'double', 'time']
|
||||
@@ -444,6 +444,16 @@ export function applyPrescription(sets, p, step = 2.5) {
|
||||
// the work rows only (a ticked warm-up falling through here would be the data-loss the
|
||||
// cascade fix removed, two files over).
|
||||
if (s.done || isWarmupRow(s)) return s
|
||||
if (isSideSet(s)) {
|
||||
const sides = Object.fromEntries(['L', 'R'].map(side => {
|
||||
const row = s.sides[side]
|
||||
return [side, row.done ? row : { ...row,
|
||||
...(p.weight != null ? { w: p.weight } : {}),
|
||||
...(p.reps != null ? { r: p.reps / 2 } : {}),
|
||||
}]
|
||||
}))
|
||||
return syncSideAggregate({ ...s, sides })
|
||||
}
|
||||
const o = { ...s }
|
||||
if (p.weight != null) o.w = p.weight
|
||||
if (p.reps != null) o.r = p.reps
|
||||
@@ -464,7 +474,11 @@ export function applyPrescription(sets, p, step = 2.5) {
|
||||
// `type` is kept: that's the exercise's plan (every set is a drop-set/rest-pause), not
|
||||
// something this particular row logged.
|
||||
const { drops, clusters, ...plainSeed } = seed
|
||||
while (out.filter(s => !isWarmupRow(s)).length < p.sets) out.push({ ...plainSeed, done: false })
|
||||
while (out.filter(s => !isWarmupRow(s)).length < p.sets) {
|
||||
out.push(isSideSet(seed) ? makeSideSet({
|
||||
w: p.weight ?? seed.w, r: p.reps ?? seed.r,
|
||||
}) : { ...plainSeed, done: false })
|
||||
}
|
||||
}
|
||||
// Last, because the work rows now carry their final weight: the warm-up block ramps toward
|
||||
// what you are actually about to lift, not toward what you lifted last time.
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { makeSideSet, setSideField, toggleSide, addSideDrop, setSideDropAt, isSideSet } from './workout-model.js'
|
||||
import { applyPrescription } from './progression.js'
|
||||
import { buildSessionEntries } from './session-start.js'
|
||||
import { workoutVolume, applyIntensifierPlan, setLabel, setsDone } from './history.js'
|
||||
import { convertStateUnit } from './units.js'
|
||||
import { buildCompletedWorkout } from './finish-workout.js'
|
||||
import { exerciseHistory } from './exercise-history.js'
|
||||
|
||||
const row = () => makeSideSet({ w: 20, r: 16 })
|
||||
const done = s => toggleSide(toggleSide(s, 'L'), 'R')
|
||||
const entry = s => ({ id: '0025', target: { mode: 'reps', side: true, bodyweight: false }, sets: [s] })
|
||||
|
||||
describe('unilateral sets across session boundaries', () => {
|
||||
it('applies weight and rep targets to the displayed sides and survives completion', () => {
|
||||
const source = row()
|
||||
const [next] = applyPrescription([source], { kind: 'up', weight: 22.5, reps: 20 })
|
||||
expect(next.sides.L).toMatchObject({ w: 22.5, r: 10, done: false })
|
||||
expect(next.sides.R).toMatchObject({ w: 22.5, r: 10, done: false })
|
||||
expect(done(next)).toMatchObject({ w: 22.5, r: 20, done: true })
|
||||
expect(source.sides.L.w).toBe(20)
|
||||
})
|
||||
|
||||
it('preserves a logged side when applying a prescription mid-session', () => {
|
||||
const source = toggleSide(setSideField(row(), 'L', 'rir', 2), 'L')
|
||||
const [next] = applyPrescription([source], { kind: 'up', weight: 25, reps: 20 })
|
||||
expect(next.sides.L).toEqual(source.sides.L)
|
||||
expect(next.sides.R).toMatchObject({ w: 25, r: 10, done: false })
|
||||
})
|
||||
|
||||
it('grows fresh independent side rows without copying completed work or drops', () => {
|
||||
const source = done(addSideDrop(row()))
|
||||
const next = applyPrescription([source], { kind: 'up', weight: 25, reps: 20, sets: 3 })
|
||||
expect(next).toHaveLength(3)
|
||||
expect(next[0]).toBe(source)
|
||||
for (const s of next.slice(1)) {
|
||||
expect(s.sides.L).toEqual({ w: 25, r: 10, done: false })
|
||||
expect(s.sides.R).toEqual({ w: 25, r: 10, done: false })
|
||||
}
|
||||
expect(next[1].sides.L).not.toBe(next[2].sides.L)
|
||||
})
|
||||
|
||||
it('uses progressed side weights when building a routine session and its planned drops', () => {
|
||||
const cfg = { id: '0025', mode: 'reps', side: true, bodyweight: false, sets: 1, reps: 16, weight: 20, policy: 'linear', inc: 2.5, intensifier: { type: 'dropset', count: 1, pct: 20 } }
|
||||
const S = { unit: 'kg', exWeights: {}, workouts: [{ id: 'w', d: '2026-09-01', entries: [{ ...entry(done(row())), target: cfg }] }] }
|
||||
const [built] = buildSessionEntries(S, { id: 'r', policy: 'linear', ex: [cfg] })
|
||||
expect(built.plan.kind).toBe('up')
|
||||
expect(built.sets[0].sides.L.w).toBe(built.plan.weight)
|
||||
expect(built.sets[0].sides.L.drops[0].w).toBe(18)
|
||||
})
|
||||
|
||||
it('converts both limbs and their drops in history and the active session', () => {
|
||||
const s = setSideDropAt(addSideDrop(setSideField(row(), 'R', 'w', 30)), 'R', 0, { w: 10 })
|
||||
const state = { unit: 'kg', active: { entries: [entry(s)] }, workouts: [{ entries: [entry(done(s))] }] }
|
||||
const result = convertStateUnit(state, 'lb')
|
||||
for (const e of [result.active.entries[0], result.workouts[0].entries[0]]) {
|
||||
expect(e.sets[0].sides.L.w).toBe(44)
|
||||
expect(e.sets[0].sides.R.w).toBe(66)
|
||||
expect(e.sets[0].sides.L.drops[0].w).toBe(35.5)
|
||||
expect(e.sets[0].sides.R.drops[0].w).toBe(22)
|
||||
expect(toggleSide(e.sets[0], 'L').w).toBe(66)
|
||||
}
|
||||
expect(state.active.entries[0].sets[0].sides.L.w).toBe(20)
|
||||
expect(convertStateUnit(result, 'kg').active.entries[0].sets[0].sides.R.w).toBe(30)
|
||||
})
|
||||
|
||||
it('counts asymmetric loads correctly in workout and exercise-history volume', () => {
|
||||
const s = done(setSideField(row(), 'R', 'w', 30))
|
||||
const w = { id: 'w', d: '2026-09-01', entries: [entry(s)] }
|
||||
expect(workoutVolume(w)).toBe(400)
|
||||
expect(exerciseHistory({ workouts: [w] }, '0025').sessions[0].volume).toBe(400)
|
||||
})
|
||||
|
||||
it('retains a single completed limb, counts only its volume and labels its partner as unlogged', () => {
|
||||
const s = toggleSide(addSideDrop(row()), 'L')
|
||||
const completed = buildCompletedWorkout({ id: 'a', entries: [entry(s), entry(row())] })
|
||||
expect(completed.entries).toHaveLength(1)
|
||||
expect(completed.entries[0].sets[0]).toEqual(s)
|
||||
expect(setsDone(completed)).toBe(1)
|
||||
expect(workoutVolume(completed)).toBe(20 * 8 + 16 * 8)
|
||||
expect(setLabel('0025', s, entry(s).target)).toBe('L 20×8 · R —')
|
||||
expect(workoutVolume({ entries: [entry({ ...s, phase: 'warmup' })] })).toBe(0)
|
||||
})
|
||||
|
||||
it.each([12, 13])('preserves L/R rows and total reps for a planned rest-pause of %i', totalReps => {
|
||||
const [warmup, work] = applyIntensifierPlan([setSideField(row(), 'R', 'w', 30)], {
|
||||
side: true, reps: 16, intensifier: { type: 'restpause', totalReps, restSec: 15 },
|
||||
})
|
||||
expect(warmup.phase).toBe('warmup')
|
||||
expect(isSideSet(work)).toBe(true)
|
||||
expect(work.r).toBe(totalReps)
|
||||
for (const side of [work.sides.L, work.sides.R]) {
|
||||
expect(side.clusters.reduce((n, c) => n + c.r, 0)).toBe(side.r)
|
||||
expect(side.clusters.every(c => c.restSec === 15)).toBe(true)
|
||||
}
|
||||
expect(work.sides.L.w).toBe(20)
|
||||
expect(work.sides.R.w).toBe(30)
|
||||
expect(workoutVolume({ entries: [entry(done(work))] })).toBe(20 * Math.ceil(totalReps / 2) + 30 * Math.floor(totalReps / 2))
|
||||
})
|
||||
})
|
||||
@@ -2,6 +2,8 @@
|
||||
// (60 kg became "60 lb", issue #22); this walks every stored weight once. Rounded to what a gym
|
||||
// can load: lb to the nearest 0.5, kg to the nearest 0.25 — enough that a value converted there
|
||||
// and back lands where it started for any plate-loadable number.
|
||||
import { isSideSet, syncSideAggregate } from './workout-model.js'
|
||||
|
||||
const LB_PER_KG = 2.2046226218
|
||||
|
||||
export function convertWeight(value, from, to) {
|
||||
@@ -14,6 +16,9 @@ export function convertWeight(value, from, to) {
|
||||
const convSet = (set, from, to) => {
|
||||
if (!set || typeof set !== 'object') return set
|
||||
const out = { ...set }
|
||||
if (isSideSet(set)) return syncSideAggregate({ ...set, sides: {
|
||||
L: convSet(set.sides.L, from, to), R: convSet(set.sides.R, from, to),
|
||||
} })
|
||||
if (out.w != null) out.w = convertWeight(out.w, from, to)
|
||||
if (Array.isArray(out.drops)) out.drops = out.drops.map(d => ({ ...d, w: convertWeight(d.w, from, to) }))
|
||||
return out
|
||||
|
||||
@@ -142,9 +142,8 @@ export function splitBurstReps(total) {
|
||||
// exactly what a single combined row hides. So a per-side row logs each side on its own: weight,
|
||||
// reps, effort and its own done tick, held in `sides: { L, R }`.
|
||||
//
|
||||
// Like `drops`/`clusters`, this rides on the row while the row's own `w`/`r`/`done`/effort stay a
|
||||
// correct aggregate of the two sides — so volume, 1RM, PRs, progression, recovery, history and the
|
||||
// coach keep reading a row's scalar fields and need not know sides exist:
|
||||
// The row keeps a scalar summary for existing consumers. These fields cannot reconstruct
|
||||
// asymmetric loads: volume and edits must read the individual sides instead.
|
||||
// r = L.r + R.r (the both-sides total, exactly what those readers expect of a per-side set)
|
||||
// w = max(L.w, R.w) (the heavier side; the two are usually equal)
|
||||
// done = L.done && R.done (a set counts done only once both sides are)
|
||||
@@ -155,6 +154,18 @@ export function isSideSet(set) {
|
||||
return !!(s.sides && typeof s.sides === 'object' && s.sides.L && s.sides.R)
|
||||
}
|
||||
|
||||
/** Includes a completed limb even when its partner is still unchecked. */
|
||||
export const hasCompletedWork = set => isSideSet(set)
|
||||
? set.sides.L.done === true || set.sides.R.done === true
|
||||
: set?.done === true
|
||||
|
||||
/** Actual completed load x reps; the scalar maximum weight is only a summary. */
|
||||
export function completedVolumeOf(set) {
|
||||
if (isSideSet(set)) return completedVolumeOf(set.sides.L) + completedVolumeOf(set.sides.R)
|
||||
if (!set?.done) return 0
|
||||
return (Number(set.w) || 0) * (Number(set.r) || 0) + extraVolumeOf(set)
|
||||
}
|
||||
|
||||
const sideOf = value => {
|
||||
const v = objectOf(value)
|
||||
const out = { w: Number(v.w) || 0, r: Number(v.r) || 0, done: v.done === true }
|
||||
|
||||
Reference in new issue
Block a user