Merge !102: Workout view: Allow multiple routines

This commit is contained in:
Duarte Santos committed 2026-09-07 19:40:31 +02:00
commit b4feea6a2e
36 files changed
+1683 -174

No files matched your search

+3
View File
@@ -37,6 +37,9 @@ export function swapActiveExercise(active, index, replacement, {
const insertAt = keepGroup ? index + 1 : (unit.length > 1 ? unit.at(-1) + 1 : index + 1)
active.entries.splice(insertAt, 0, {
...replacement,
// A swap does not change which routine the slot belongs to — carry its `rid` the same
// way `sg` is carried, so a combined session's WorkoutDetail groups stay contiguous.
...(current.rid ? { rid: current.rid } : {}),
...(keepGroup ? { sg: current.sg } : {})
})
active.cur = insertAt
+29 -7
View File
@@ -98,18 +98,25 @@ export function canonicalPlan(S) {
}
})
})),
week: Object.fromEntries([1, 2, 3, 4, 5, 6, 0].filter(d => S.week?.[d]).map(d => [d, S.week[d]]))
// A weekday holds a routine-id list now. `[].concat` folds a legacy bare string and a
// one-element list to the same shape, so their fingerprint is identical — no false-stale
// storm on the first load after the upgrade. `?.length` keeps a stray `[]` out. Insertion
// order is preserved and never sorted (it is the merge order).
week: Object.fromEntries([1, 2, 3, 4, 5, 6, 0].filter(d => S.week?.[d]?.length).map(d => [d, [].concat(S.week[d])]))
}
}
/** FNV-1a-ish 64-bit fingerprint. Mirror of hashPlan in api/coach/jobs.js. */
/** FNV-1a-ish 64-bit fingerprint. Mirror of hashPlan in api/coach/core/plan-hash.js. */
export function hashPlan(plan) {
const canon = JSON.stringify({
routines: (plan?.routines || []).map(r => [r.id, r.name, r.prog, (r.ex || []).map(e =>
[e.id, e.mode, e.sets, e.reps, e.sec, e.min, e.speed, e.weight, e.prog, e.inc,
e.repsMin, e.repsMax, e.bodyweight, e.side, e.sg].join(':')
)]),
week: Object.keys(plan?.week || {}).sort().map(k => k + '=' + plan.week[k])
// `plan` is a canonicalPlan output, so each day is already an array. `{1:['r1']}` → "1=r1",
// byte-identical to the pre-upgrade fingerprint; `{3:['r2','r3']}` → "3=r2+r3". Weekday
// keys still sorted; the routine list within a day never is.
week: Object.keys(plan?.week || {}).sort().map(k => k + '=' + [].concat(plan.week[k]).join('+'))
})
let h1 = 0x811c9dc5, h2 = 0x01000193
for (let i = 0; i < canon.length; i++) {
@@ -140,7 +147,7 @@ export function currentValue(S, change) {
case 'exercise-prog': return e?.prog ?? null
case 'routine-prog': return r?.prog ?? null
case 'rename-routine': return r?.name ?? null
case 'week': return S.week?.[change.target?.weekday] ?? null
case 'week': return [].concat(S.week?.[change.target?.weekday] ?? []) // routine-id list; [] = rest
default: return undefined // structural changes have no single scalar to compare
}
}
@@ -161,6 +168,12 @@ export function markStale(proposal, S) {
let stale = false
if (c.type !== 'add-routine' && c.type !== 'week' && !r) stale = true
else if (c.target?.exId && !findEx(r, c.target.exId)) stale = true
else if (c.type === 'week') {
// The day's value is a routine-id list; `before` may be a list (a combined day) or a
// legacy bare string. Compare by canonical join so order matters but shape does not.
const join = v => [].concat(v ?? []).join('+')
if (c.before != null && join(currentValue(S, c)) !== join(c.before)) stale = true
}
else {
const cur = currentValue(S, c)
// `before` is what the Coach saw. If the live plan disagrees, someone has already
@@ -504,9 +517,12 @@ const CHANGE_APPLY = {
},
'rename-routine': (s, c) => { need(findRoutine(s, c.target.routineId)).name = c.after },
week: (s, c) => {
// A single-routine op: the slot is a list, but the Coach only ever names one routine (or
// rest), and it replaces the day. This collapses a combined day to one routine — the same
// stated limitation as a DayOverride (see docs/COMBINE_ROUTINES.md §8).
const d = c.target.weekday
if (c.after == null || c.after === 'rest') delete s.week[d]
else s.week[d] = c.after
else s.week[d] = [c.after]
}
}
export const CHANGE_TYPES = Object.keys(CHANGE_APPLY)
@@ -610,10 +626,16 @@ export function changeTitle(c, S) {
export function changeValues(c, S) {
const routineName = id => (S?.routines || []).find(r => r.id === id)?.name || id
const fmt = v => {
if (v == null) return c.type === 'week' ? t('Rest') : '—'
// `week` first — its value is a routine-id list (an array is also an object, so it has to
// win before the generic branches). Render as " + "-joined routine names; null / empty /
// "rest" all read as Rest.
if (c.type === 'week') {
const ids = [].concat(v ?? []).filter(x => x && x !== 'rest')
return ids.length ? ids.map(routineName).join(' + ') : t('Rest')
}
if (v == null) return '—'
if (typeof v === 'object') return v.id ? exTitle(v.id) : v.name || JSON.stringify(v)
if (Array.isArray(v)) return v.length + ''
if (c.type === 'week') return v === 'rest' ? t('Rest') : routineName(v)
return String(v)
}
if (['add-exercise', 'add-routine', 'reorder'].includes(c.type)) return null
+52 -7
View File
@@ -3,7 +3,7 @@ import {
canonicalPlan, planHash, hashPlan, markStale, applicable, currentValue,
pushSnapshot, revertLast, canRevert, appendLog, applyChangeSet, applyCreatedPlan,
recordDismissal, validateProposal, coachAvailable, hasConsent,
recordDebrief, logEntry, lightBundle,
recordDebrief, logEntry, lightBundle, changeValues,
CHANGE_TYPES, SNAPSHOT_MAX, LOG_MAX, CONSENT_VERSION
} from './coach.js'
import { registerCustom } from './exercises.js'
@@ -100,12 +100,31 @@ describe('plan fingerprint', () => {
const withFlags = state()
withFlags.routines[0].ex[0] = { ...withFlags.routines[0].ex[0], repsMin: 8, repsMax: 20, bodyweight: true }
withFlags.routines[1].ex[0] = { ...withFlags.routines[1].ex[0], side: true, reps: 16 }
for (const S of [state(), state({ week: {} }), state({ routines: [] }), withFlags]) {
const combined = state({ week: { 1: ['r1', 'r2'], 3: 'r2', 5: [] } })
for (const S of [state(), state({ week: {} }), state({ routines: [] }), withFlags, combined]) {
expect(canonicalPlan(S)).toEqual(serverPayload.canonicalPlan(S))
expect(planHash(S)).toBe(serverHashPlan(serverPayload.canonicalPlan(S)))
expect(hashPlan(canonicalPlan(S))).toBe(serverHashPlan(serverPayload.canonicalPlan(S)))
}
})
it('a combined day changes the fingerprint, and routine order within a day matters', () => {
const S = state()
expect(planHash(state({ week: { ...S.week, 3: ['r2', 'r1'] } }))).not.toBe(planHash(S))
expect(planHash(state({ week: { 3: ['r1', 'r2'] } }))).not.toBe(planHash(state({ week: { 3: ['r2', 'r1'] } })))
})
it('a legacy bare-string day and its one-element list are the same fingerprint (upgrade stability)', () => {
expect(planHash(state({ week: { 1: 'r1' } }))).toBe(planHash(state({ week: { 1: ['r1'] } })))
// and a stray [] is dropped, exactly like an absent key
expect(planHash(state({ week: { 1: ['r1'], 4: [] } }))).toBe(planHash(state({ week: { 1: ['r1'] } })))
})
it('canonicalPlan omits a [] day and preserves routine order', () => {
expect(canonicalPlan(state({ week: { 2: [] } })).week).toEqual({})
expect(canonicalPlan(state({ week: { 3: ['r2', 'r3'] } })).week[3]).toEqual(['r2', 'r3'])
expect(canonicalPlan(state({ week: { 3: ['r3', 'r2'] } })).week[3]).toEqual(['r3', 'r2'])
})
})
describe('staleness', () => {
@@ -135,6 +154,17 @@ describe('staleness', () => {
expect(c.status).toBe('proposed')
})
it('compares a combined-day week change by its canonical routine-list join', () => {
const wk = (weekday, before) => proposal([change({ type: 'week', target: { weekday }, before, after: 'r1' })])
const S = state({ week: { 1: ['r1', 'r2'] } })
// live matches the list the Coach saw → not stale
expect(markStale(wk(1, ['r1', 'r2']), S).changes[0].status).toBe('proposed')
// a legacy scalar `before` still compares equal to a one-element live list
expect(markStale(wk(1, 'r1'), state({ week: { 1: ['r1'] } })).changes[0].status).toBe('proposed')
// the day gained a routine since → stale
expect(markStale(wk(1, ['r1', 'r2']), state({ week: { 1: ['r1', 'r2', 'r3'] } })).changes[0].status).toBe('stale')
})
it('reads the current value for every scalar change type', () => {
const S = state()
S.routines[0].ex[0].repsMax = 20
@@ -143,7 +173,7 @@ describe('staleness', () => {
expect(currentValue(S, change({ type: 'repsMax' }))).toBe(20)
expect(currentValue(S, change({ type: 'exercise-prog' }))).toBe('linear')
expect(currentValue(S, change({ type: 'routine-prog' }))).toBe('linear')
expect(currentValue(S, change({ type: 'week', target: { weekday: 1 } }))).toBe('r1')
expect(currentValue(S, change({ type: 'week', target: { weekday: 1 } }))).toEqual(['r1']) // a routine-id list; [] = rest
})
})
@@ -269,13 +299,28 @@ describe('applying changes', () => {
expect(removed.week[3]).toBeUndefined() // Wednesday pointed at r2
})
it('moves a day, and clears one', () => {
it('moves a day, and clears one — the slot stays a routine-id list', () => {
const moved = apply(state(), proposal([change({ type: 'week', target: { weekday: 6 }, before: null, after: 'r1' })]), ['c1'])
expect(moved.week[6]).toBe('r1')
expect(moved.week[6]).toEqual(['r1'])
const cleared = apply(state(), proposal([change({ type: 'week', target: { weekday: 1 }, before: 'r1', after: 'rest' })]), ['c1'])
expect(cleared.week[1]).toBeUndefined()
})
it('collapses a combined day to the single routine the Coach named', () => {
const S = state()
S.week = { ...S.week, 3: ['r2', 'r1'] }
const out = apply(S, proposal([change({ type: 'week', target: { weekday: 3 }, before: ['r2', 'r1'], after: 'r1' })]), ['c1'])
expect(out.week[3]).toEqual(['r1'])
})
it('changeValues renders a combined-day before/after as joined routine names, not a count', () => {
const S = state()
const c = { type: 'week', target: { weekday: 3 }, before: ['r1', 'r2'], after: 'r1' }
expect(changeValues(c, S)).toEqual({ before: 'Full body A + Full body B', after: 'Full body A' })
expect(changeValues({ type: 'week', target: { weekday: 3 }, before: ['r1', 'r2'], after: 'rest' }, S).after).toBe('Rest')
expect(changeValues({ type: 'week', target: { weekday: 3 }, before: null, after: 'r2' }, S).before).toBe('Rest')
})
it('never touches history, weigh-ins or settings', () => {
const S = state({
workouts: [{ id: 'w1', d: '2026-07-20', entries: [] }],
@@ -449,8 +494,8 @@ describe('created plans', () => {
it('replaces the week only when asked, and remaps to the new ids', () => {
const s = JSON.parse(JSON.stringify(state()))
applyCreatedPlan(s, { id: 'p1', kind: 'create', bundle }, { schedule: true })
expect(s.week[1]).toBe(s.routines[2].id)
expect(s.week[3]).toBe(s.routines[3].id)
expect(s.week[1]).toEqual([s.routines[2].id]) // a weekday holds a routine-id list
expect(s.week[3]).toEqual([s.routines[3].id])
expect(s.week[5]).toBeUndefined() // a day the new plan leaves empty is rest
})
+14 -2
View File
@@ -9,6 +9,11 @@ export function buildCompletedWorkout(active, { end = Date.now(), prs = [], snap
sets: entry.sets,
topW: bestWeightForEntry(entry) || null,
target: entry.target || null,
// Which routine this entry came from, and whether it counts for progression. Written
// only when set/true, so a single-routine non-excluded session is byte-for-byte the
// shape it always was. Without this the whitelist drops both at finish.
...(entry.rid ? { rid: entry.rid } : {}),
...(entry.noProg === true ? { noProg: true } : {}),
}
const snapshot = typeof snapshotFor === 'function' ? snapshotFor(entry) : null
if (snapshot && typeof snapshot === 'object' && !Array.isArray(snapshot) && Object.keys(snapshot).length) {
@@ -26,18 +31,25 @@ export function buildCompletedWorkout(active, { end = Date.now(), prs = [], snap
}).filter(entry => entry.sets.some(set => set.done))
const sessionNote = (active?.note || '').trim()
const routineIds = [].concat(active?.routineIds ?? (active?.routineId ? [active.routineId] : []))
// Legacy `w.excludeFromProgression` mirror: kept for older builds and external readers, but
// it only makes sense when the *whole* session is excluded. Derived from the completed
// entries, not read from `active` (which no longer carries the flag). A mixed session omits
// it — that case is new territory only the per-entry `noProg` readers handle.
const allNoProg = entries.length > 0 && entries.every(e => e.noProg === true)
return {
id: active.id,
d: active.d,
start: active.start,
end,
routineId: active.routineId,
routineIds,
routineId: routineIds[0] ?? null,
name: active.name,
bw: active.bw,
entries,
prs,
...(active.excludeFromProgression === true ? { excludeFromProgression: true } : {}),
...(allNoProg ? { excludeFromProgression: true } : {}),
...(sessionNote ? { note: sessionNote } : {}),
}
}
+48 -11
View File
@@ -4,17 +4,51 @@ import { buildCompletedWorkout } from './finish-workout.js'
describe('completed workout boundary', () => {
it('builds the same legacy-shaped record doFinishWorkout stores and keeps it visible', () => {
const active = {
id: 'active-1', d: '2026-08-08', start: 1000, routineId: 'routine-1', name: 'Push', bw: 80,
id: 'active-1', d: '2026-08-08', start: 1000, routineIds: ['routine-1'], name: 'Push', bw: 80,
entries: [{ id: '0025', sets: [{ done: true, w: 60, r: 8 }], topW: 60, target: { sets: 1, reps: 8 } }],
}
const completed = buildCompletedWorkout(active, { end: 2000, prs: [] })
expect(completed).toEqual({
id: 'active-1', d: '2026-08-08', start: 1000, end: 2000, routineId: 'routine-1', name: 'Push', bw: 80,
id: 'active-1', d: '2026-08-08', start: 1000, end: 2000,
routineIds: ['routine-1'], routineId: 'routine-1', name: 'Push', bw: 80,
entries: [{ id: '0025', sets: [{ done: true, w: 60, r: 8 }], topW: 60, target: { sets: 1, reps: 8 } }],
prs: []
})
})
it('mirrors routineIds → routineId, and tolerates a legacy scalar active.routineId', () => {
const base = {
id: 'w', d: '2026-08-08', start: 1,
entries: [{ id: '0025', sets: [{ done: true, w: 60, r: 8 }], target: { sets: 1, reps: 8 } }],
}
const combined = buildCompletedWorkout({ ...base, routineIds: ['a', 'b'] })
expect(combined.routineIds).toEqual(['a', 'b'])
expect(combined.routineId).toBe('a')
const legacy = buildCompletedWorkout({ ...base, routineId: 'only' })
expect(legacy.routineIds).toEqual(['only'])
expect(legacy.routineId).toBe('only')
const freestyle = buildCompletedWorkout(base)
expect(freestyle.routineIds).toEqual([])
expect(freestyle.routineId).toBe(null)
})
it('carries per-entry rid and noProg onto the saved entry, written only when set', () => {
const active = {
id: 'w', d: '2026-08-08', start: 1, routineIds: ['strength', 'rehab'],
entries: [
{ id: '0025', rid: 'strength', sets: [{ done: true, w: 60, r: 8 }], target: { sets: 1, reps: 8 } },
{ id: '0031', rid: 'rehab', noProg: true, sets: [{ done: true, w: 10, r: 12 }], target: { sets: 1, reps: 12 } },
],
}
const [a, b] = buildCompletedWorkout(active).entries
expect(a.rid).toBe('strength')
expect('noProg' in a).toBe(false)
expect(b.rid).toBe('rehab')
expect(b.noProg).toBe(true)
})
it('derives topW from the highest completed non-warm-up work set, not stale entry data', () => {
const active = {
id: 'active-1', d: '2026-08-08', start: 1000,
@@ -45,16 +79,19 @@ describe('completed workout boundary', () => {
expect(buildCompletedWorkout(active).entries[0].topW).toBe(60)
})
it('persists progression exclusion only for a marked session', () => {
const active = {
id: 'active-1', d: '2026-08-08', start: 1000, routineId: 'routine-1', name: 'Deload', bw: 80,
excludeFromProgression: true,
entries: [{ id: '0025', sets: [{ done: true, w: 30, r: 8 }], target: { sets: 1, reps: 8 } }],
}
expect(buildCompletedWorkout(active, { end: 2000 }).excludeFromProgression).toBe(true)
it('writes the legacy excludeFromProgression mirror iff every completed entry is noProg', () => {
const mk = entries => ({ id: 'w', d: '2026-08-08', start: 1, routineIds: ['x'], entries })
const done = extra => ({ id: '0025', sets: [{ done: true, w: 30, r: 8 }], target: { sets: 1, reps: 8 }, ...extra })
const { excludeFromProgression, ...regular } = active
expect(buildCompletedWorkout(regular, { end: 2000 })).not.toHaveProperty('excludeFromProgression')
// rehab-only combined session → present
expect(buildCompletedWorkout(mk([done({ noProg: true }), done({ id: '0031', noProg: true })])))
.toHaveProperty('excludeFromProgression', true)
// rehab + strength → absent
expect(buildCompletedWorkout(mk([done({ noProg: true }), done({ id: '0031' })])))
.not.toHaveProperty('excludeFromProgression')
// all-normal → absent
expect(buildCompletedWorkout(mk([done(), done({ id: '0031' })])))
.not.toHaveProperty('excludeFromProgression')
})
it('persists a muscle snapshot only when the caller supplies one', () => {
+50 -19
View File
@@ -211,10 +211,28 @@ export function unpairSuperset(items, idx) {
return next
}
/**
* Is this completed entry excluded from progression / session read-back?
*
* "Excluded" moved from a whole-workout flag to a per-entry one (ENG-11): a rehab routine
* combined with real work excludes only its own exercises. A legacy workout carries the
* whole-workout flag and no per-entry field, so every one of its entries reads as excluded.
* `noProg` is frozen onto the entry from its source routine's `excludeFromProgression` at
* build time — editing the routine flag later never rewrites a saved session.
*/
export function entryExcluded(w, entry) {
return w?.excludeFromProgression === true || entry?.noProg === true
}
export function lastEntryFor(S, exId) {
for (let i = S.workouts.length - 1; i >= 0; i--) {
const en = S.workouts[i].entries.find(e => e.id === exId)
const w = S.workouts[i]
const en = w.entries.find(e => e.id === exId)
if (!en) continue
// A session that does not count — a planned deload, or a rehab block merged into a real
// session — is not "last time" for the next regular prescription: its reps and durations
// must not seed the rows any more than its weight seeds the progression.
if (entryExcluded(w, en)) continue
// Work sets only. Every caller asks the same question — "what did you actually lift last
// time" — to seed the next session's rows, to size a freestyle config, and to print "Last
// time" on the card. A warm-up answers none of them: seeding position 0 from a 50% ramp row
@@ -225,7 +243,7 @@ export function lastEntryFor(S, exId) {
// `target` is what the session prescribed; finished workouts carry it so labels and the
// progression engine can read a session back the way it was logged. Older workouts have
// none — modeOf() falls back to the body part for them, which is what they were.
if (done.length) return { d: S.workouts[i].d, sets: done, target: en.target || null }
if (done.length) return { d: w.d, sets: done, target: en.target || null }
}
return null
}
@@ -278,33 +296,49 @@ export function bestWeightFor(S, exId) {
}))
return best
}
export function effectiveRoutineId(S, iso) {
/**
* The routines planned for a date, in merge order. Plural is the primary form now that a
* weekday can hold several routines (`S.week[wd]` is `string[]`); the singular helpers below
* are thin wrappers. `[]` — a stray empty array, or a key that is absent — all mean rest, so
* "is this a rest day?" is `effectiveRoutineIds(S, iso).length === 0`.
*
* `S.dayPlan[iso]` stays scalar (a routine id, the `'rest'` sentinel, or undefined): the
* per-date override and Start-time are single-pick. All array-tolerance is on `S.week`.
*/
export function effectiveRoutineIds(S, iso) {
const ov = S.dayPlan[iso]
if (ov === 'rest') return null
if (ov && S.routines.some(r => r.id === ov)) return ov
if (ov === 'rest') return []
if (ov && S.routines.some(r => r.id === ov)) return [ov]
const wd = new Date(iso + 'T12:00:00').getDay()
return S.week[wd] || null
return [].concat(S.week[wd] || []).filter(id => S.routines.some(r => r.id === id))
}
export function effectiveRoutine(S, iso) {
const id = effectiveRoutineId(S, iso)
return id ? S.routines.find(r => r.id === id) || null : null
export function effectiveRoutines(S, iso) {
return effectiveRoutineIds(S, iso).map(id => S.routines.find(r => r.id === id)).filter(Boolean)
}
export const effectiveRoutineId = (S, iso) => effectiveRoutineIds(S, iso)[0] ?? null
export const effectiveRoutine = (S, iso) => effectiveRoutines(S, iso)[0] ?? null
/**
* The next day that actually has something to train, looking forward from `iso` (exclusive).
*
* Takes a date string rather than reading the clock so callers and tests agree on "today".
* A routine with no exercises does not count: starting one lands you in an empty session, so
* it is not an answer to "what is next" (the same guard TabBar applies before starting).
* it is not an answer to "what is next" (the same guard TabBar applies before starting). On a
* combined day, any one routine with exercises makes the day trainable.
* Returns null when the whole week is rest.
*
* Return shape carries `routines` (the whole day) plus `routine` = `routines[0]` for the
* "what's next" label.
*/
export function nextTrainingDay(S, iso) {
for (let i = 1; i <= 7; i++) {
const d = new Date(iso + 'T12:00:00')
d.setDate(d.getDate() + i)
const nextIso = isoOf(d)
const routine = effectiveRoutine(S, nextIso)
if (routine && (routine.ex || []).length) return { iso: nextIso, weekday: d.getDay(), routine }
const routines = effectiveRoutines(S, nextIso)
if (routines.some(r => (r.ex || []).length)) {
return { iso: nextIso, weekday: d.getDay(), routines, routine: routines[0] }
}
}
return null
}
@@ -334,13 +368,10 @@ export const MAX_PLANNED_WARMUPS = 5
function buildWorkSets(S, cfg, options = {}) {
const preferLast = !!options.preferLast
const useTarget = !!options.useTarget
// A workout flagged excludeFromProgression (a planned deload) is not "last time" for the
// next regular session either: its reps and durations must not seed the rows any more than
// its weight seeds the prescription. The deload session itself reads the routine's own target.
const regular = (S.workouts || []).some(w => w.excludeFromProgression === true)
? { ...S, workouts: S.workouts.filter(w => w.excludeFromProgression !== true) }
: S
const last = lastEntryFor(regular, cfg.id)
// `lastEntryFor` now skips any entry that does not count — a planned deload, or a rehab
// block merged into a real session (entryExcluded) — so the rows seed from the last
// *counting* session without this function pre-filtering the history itself.
const last = lastEntryFor(S, cfg.id)
const n = Math.max(1, cfg.sets || 1)
const mode = modeOf(cfg)
const sets = []
+79 -1
View File
@@ -1,5 +1,5 @@
import { describe, it, expect } from 'vitest'
import { nextTrainingDay, modeOf, isTimed, fmtSec, setLabel, defaultConfig, buildSets, freestyleConfig, exLine, workoutVolume, bestWeightFor, bestWeightForEntry, effortOf, stepEffort, capEffort, isBw, isPerSide, sideReps, repStep, cascadeWeight, insertWarmupRow, removeRowAt, workSetsDone, setsDone, setsDoneActive, setUnits, doneUnits, setUnitsTotal, pairAdjacent, unpairSuperset, supersetUnits, applyIntensifierPlan, pinnedNoteFor, exNoteFor } from './history.js'
import { nextTrainingDay, modeOf, isTimed, fmtSec, setLabel, defaultConfig, buildSets, freestyleConfig, exLine, workoutVolume, bestWeightFor, bestWeightForEntry, effortOf, stepEffort, capEffort, isBw, isPerSide, sideReps, repStep, cascadeWeight, insertWarmupRow, removeRowAt, workSetsDone, setsDone, setsDoneActive, setUnits, doneUnits, setUnitsTotal, pairAdjacent, unpairSuperset, supersetUnits, applyIntensifierPlan, pinnedNoteFor, exNoteFor, effectiveRoutineIds, effectiveRoutines, effectiveRoutineId, effectiveRoutine, lastEntryFor, entryExcluded } from './history.js'
import { makeSideSet, setSideField, toggleSide } from './workout-model.js'
import { EXDB } from './exercises.js'
@@ -1079,5 +1079,83 @@ describe('per-side set counters', () => {
expect(setUnitsTotal(A.entries)).toBe(5)
expect(setsDoneActive(A)).toBe(2)
expect(setsDone({ entries: A.entries })).toBe(2)
// ---- combine routines: plural planner resolver + per-entry noProg (ENG-9) ----
describe('effectiveRoutineIds / effectiveRoutines', () => {
const routines = [{ id: 'r1', name: 'A', ex: [{ id: '1' }] }, { id: 'r2', name: 'B', ex: [{ id: '2' }] }]
const S = (week, dayPlan = {}) => ({ routines, week, dayPlan })
const ISO = '2026-08-19' // a Wednesday → getDay() 3
it('reads a bare-string weekday value as a one-element list (tolerant reader)', () => {
expect(effectiveRoutineIds(S({ 3: 'r1' }), ISO)).toEqual(['r1'])
})
it('resolves a multi-id array and filters out routines that no longer exist', () => {
expect(effectiveRoutineIds(S({ 3: ['r1', 'gone', 'r2'] }), ISO)).toEqual(['r1', 'r2'])
expect(effectiveRoutines(S({ 3: ['r1', 'r2'] }), ISO).map(r => r.name)).toEqual(['A', 'B'])
})
it('treats [], a stray empty array and an absent key all as rest', () => {
expect(effectiveRoutineIds(S({ 3: [] }), ISO)).toEqual([])
expect(effectiveRoutineIds(S({}), ISO)).toEqual([])
})
it('a scalar dayPlan override wins and stays scalar; "rest" is empty', () => {
expect(effectiveRoutineIds(S({ 3: ['r1', 'r2'] }, { [ISO]: 'r2' }), ISO)).toEqual(['r2'])
expect(effectiveRoutineIds(S({ 3: ['r1', 'r2'] }, { [ISO]: 'rest' }), ISO)).toEqual([])
})
it('the singular wrappers return [0] ?? null', () => {
expect(effectiveRoutineId(S({ 3: ['r1', 'r2'] }), ISO)).toBe('r1')
expect(effectiveRoutine(S({ 3: ['r1', 'r2'] }), ISO).name).toBe('A')
expect(effectiveRoutineId(S({}), ISO)).toBe(null)
expect(effectiveRoutine(S({}), ISO)).toBe(null)
})
})
describe('nextTrainingDay on a combined day', () => {
const TUE = '2026-08-18'
it('is trainable when any one routine of the day has exercises; return shape carries routines', () => {
const S = {
routines: [{ id: 'r1', name: 'A', ex: [] }, { id: 'r2', name: 'B', ex: [{ id: '1' }] }],
week: { 3: ['r1', 'r2'] }, dayPlan: {},
}
const nd = nextTrainingDay(S, TUE)
expect(nd).toMatchObject({ weekday: 3 })
expect(nd.routines.map(r => r.name)).toEqual(['A', 'B'])
expect(nd.routine.name).toBe('A')
})
it('skips a day whose every routine is empty', () => {
const S = {
routines: [{ id: 'r1', name: 'A', ex: [] }, { id: 'r2', name: 'B', ex: [] }, { id: 'r3', name: 'C', ex: [{ id: '1' }] }],
week: { 3: ['r1', 'r2'], 5: ['r3'] }, dayPlan: {},
}
expect(nextTrainingDay(S, TUE)).toMatchObject({ weekday: 5 })
})
})
describe('lastEntryFor / buildSets skip a noProg entry', () => {
const LIFT2 = EXDB.find(e => e.bp !== 'cardio' && e.eq !== 'body weight').id
const wk = (d, w, r, extra) => ({ d, entries: [{ id: LIFT2, target: { sets: 1, reps: r, weight: w }, sets: [{ w, r, done: true }], ...extra }] })
it('lastEntryFor returns the prior counting session, not a later noProg one', () => {
const S = { workouts: [wk('2026-01-01', 60, 8), wk('2026-01-05', 30, 12, { noProg: true })] }
expect(lastEntryFor(S, LIFT2).d).toBe('2026-01-01')
})
it('lastEntryFor skips a legacy whole-workout excludeFromProgression session', () => {
const S = { workouts: [wk('2026-01-01', 60, 8), { d: '2026-01-05', excludeFromProgression: true, entries: [{ id: LIFT2, target: { sets: 1, reps: 12, weight: 30 }, sets: [{ w: 30, r: 12, done: true }] }] }] }
expect(lastEntryFor(S, LIFT2).d).toBe('2026-01-01')
})
it('buildSets seeds opening rows from the last counting session', () => {
const S = { exWeights: {}, workouts: [wk('2026-01-01', 60, 8), wk('2026-01-05', 30, 12, { noProg: true })] }
expect(buildSets(S, { id: LIFT2, sets: 1, reps: 5, weight: 50 })).toEqual([{ w: 60, r: 8, done: false }])
})
it('buildSets with only noProg history falls back to the routine target', () => {
const S = { exWeights: {}, workouts: [wk('2026-01-05', 30, 12, { noProg: true })] }
expect(buildSets(S, { id: LIFT2, sets: 1, reps: 5, weight: 50 })).toEqual([{ w: 50, r: 5, done: false }])
})
it('freestyleConfig ignores a noProg entry', () => {
const S = { exWeights: {}, workouts: [wk('2026-01-05', 30, 12, { noProg: true })] }
expect(freestyleConfig(S, { id: LIFT2, mode: 'reps', sets: 3, reps: 10, weight: 0 })).toEqual({ id: LIFT2, mode: 'reps', sets: 3, reps: 10, weight: 0 })
})
it('bestWeightFor is unchanged — a heavy noProg set still counts toward Best', () => {
const S = { workouts: [wk('2026-01-01', 60, 8), wk('2026-01-05', 140, 3, { noProg: true })] }
expect(bestWeightFor(S, LIFT2)).toBe(140)
})
})
+6 -5
View File
@@ -11,7 +11,7 @@
// web bundles; the Capacitor plugins are only ever imported behind it.
import { t } from './i18n-core.js'
import { isoOf, todayISO } from './format.js'
import { effectiveRoutineId } from './history.js'
import { effectiveRoutineIds } from './history.js'
export const MOBILE = import.meta.env.VITE_MOBILE === '1'
@@ -108,16 +108,17 @@ export function buildReminderNotifications(S, now = new Date()) {
day.setDate(date.getDate() + offset)
const iso = isoOf(day)
if (completed.has(iso)) continue
const rid = effectiveRoutineId(state, iso)
const routine = routines.find(x => x.id === rid)
if (!routine) continue
// A weekday can hold several routines; name them all, or fall back to a count.
const dayRoutines = effectiveRoutineIds(state, iso).map(id => routines.find(x => x.id === id)).filter(Boolean)
if (!dayRoutines.length) continue
const label = dayRoutines.length <= 2 ? dayRoutines.map(r => r.name).join(' + ') : t('{0} routines', dayRoutines.length)
const at = new Date(day)
at.setHours(hour, minute, 0, 0)
if (at <= now) continue
notifications.push({
id: REMINDER_ID_BASE + offset,
title: t('Workout day'),
body: t('{0} is on the plan today — let’s go!', routine.name),
body: t('{0} is on the plan today — let’s go!', label),
schedule: { at, allowWhileIdle: true },
})
}
+15
View File
@@ -59,4 +59,19 @@ describe('buildReminderNotifications', () => {
expect(notifications.some(n => iso(n.schedule.at) === iso(now))).toBe(false)
expect(notifications.some(n => iso(n.schedule.at) === iso(new Date(2026, 5, 8)))).toBe(true)
})
it('names both routines of a combined day, and reads a legacy scalar day the same', () => {
const now = new Date(2026, 5, 1, 7, 0) // Monday
const combined = buildReminderNotifications(state({ week: { 1: ['push', 'pull'] } }), now)[0]
expect(combined.body).toContain('Push + Pull')
const legacy = buildReminderNotifications(state({ week: { 1: 'push' } }), now)[0]
expect(legacy.body).toContain('Push')
})
it('falls back to a count for three or more routines on one day', () => {
const now = new Date(2026, 5, 1, 7, 0)
const n = buildReminderNotifications(state({ week: { 1: ['push', 'pull', 'legs'] } }), now)[0]
expect(n.body).toContain('3 routines')
})
})
+16 -6
View File
@@ -10,6 +10,7 @@
import { EXIDX, isBodyweightEq } from './exercises.js'
import { modeOf, fmtSec, isBw, isPerSide, sideReps, MAX_PLANNED_WARMUPS } from './history.js'
import { deriveSessionName } from './session-merge.js'
import { uid, todayISO, DAYN, weekOrder, weekStartOf, fmtNum, exCount } from './format.js'
import { t, exerciseNameFor } from './i18n-core.js'
@@ -103,8 +104,11 @@ export function buildPlanBundle(S, name) {
const customEx = (S.customEx || [])
.filter(c => usedIds.has(c.id))
.map(c => ({ id: c.id, n: c.n, bp: c.bp, ...(c.desc ? { desc: c.desc } : {}) }))
// A weekday can hold several routines (merge order preserved). `[].concat` normalises a
// legacy scalar id to a one-element list, so a bundle written before this change and one
// written after are read the same way at the other end.
const week = {}
WEEK_DAYS.forEach(d => { if (S.week?.[d]) week[d] = S.week[d] })
WEEK_DAYS.forEach(d => { if (S.week?.[d]?.length) week[d] = [].concat(S.week[d]) })
return { opengym_plan: PLAN_FMT, exported: todayISO(), name: name || '', week, routines, customEx }
}
@@ -149,7 +153,7 @@ export function parsePlan(raw) {
dropped,
routineCount: routines.length,
exerciseCount: routines.reduce((n, r) => n + r.ex.length, 0),
scheduledDays: WEEK_DAYS.filter(d => data.week?.[d]).length
scheduledDays: WEEK_DAYS.filter(d => data.week?.[d]?.length).length
}
}
@@ -185,8 +189,12 @@ export function mergePlan(s, bundle, { schedule } = {}) {
})
if (schedule) {
WEEK_DAYS.forEach(d => { delete s.week[d] })
Object.entries(bundle.week || {}).forEach(([d, oldId]) => {
if (ridMap[oldId]) s.week[d] = ridMap[oldId]
Object.entries(bundle.week || {}).forEach(([d, val]) => {
// `[].concat` tolerates a pre-upgrade scalar bundle value. An element whose routine id
// didn't survive parsing is dropped, not written as undefined; a day that ends up empty
// is left absent rather than stored as `[]`.
const ids = [].concat(val).map(oldId => ridMap[oldId]).filter(Boolean)
if (ids.length) s.week[d] = ids
})
}
return { routines: bundle.routines.length }
@@ -246,8 +254,10 @@ function routineHTML(r, unit) {
function weekHTML(S) {
// The printout is read by whoever exported it, so the week runs in their order.
const rows = weekOrder(weekStartOf(S)).map(d => {
const r = S.routines.find(x => x.id === S.week?.[d])
const val = r ? esc(r.name) : `<span class="rest">${esc(t('Rest'))}</span>`
const names = [].concat(S.week?.[d] || [])
.map(id => S.routines.find(x => x.id === id)?.name)
.filter(Boolean)
const val = names.length ? esc(deriveSessionName(names)) : `<span class="rest">${esc(t('Rest'))}</span>`
return `<div class="w-row"><div class="w-day">${esc(t(DAYN[d]))}</div><div class="w-r">${val}</div></div>`
}).join('')
return `<div class="week">${rows}</div>`
+45
View File
@@ -91,3 +91,48 @@ describe('what survives a shared plan', () => {
expect(parsePlan(bundle).routines[0].ex[0].intensifier).toEqual({ type: 'dropset', count: 1, pct: 20 })
})
})
// ---- combine routines: a weekday holds a routine-id list (ENG-9 §5) ----
describe('week schedule as a routine-id list', () => {
const twoRoutines = {
routines: [
{ id: 'a', name: 'A', ex: [{ id: '0025', sets: 3, reps: 5 }] },
{ id: 'b', name: 'B', ex: [{ id: '0031', sets: 3, reps: 8 }] },
],
customEx: [],
}
it('build → parse → merge round-trips an array week with arrays intact', () => {
const src = { ...twoRoutines, week: { 1: ['a', 'b'], 3: ['a'] } }
const parsed = parsePlan(JSON.stringify(buildPlanBundle(src, 'Plan')))
expect(parsed.scheduledDays).toBe(2)
const target = { routines: [], week: {}, customEx: [] }
mergePlan(target, parsed, { schedule: true })
const [idA, idB] = target.routines.map(r => r.id)
expect(target.week[1]).toEqual([idA, idB])
expect(target.week[3]).toEqual([idA])
})
it('tolerates a legacy scalar bundle value', () => {
const legacy = { opengym_plan: 1, name: 'x', customEx: [], week: { 1: 'a' }, routines: twoRoutines.routines }
const parsed = parsePlan(legacy)
expect(parsed.scheduledDays).toBe(1)
const target = { routines: [], week: {}, customEx: [] }
mergePlan(target, parsed, { schedule: true })
expect(target.week[1]).toEqual([target.routines[0].id])
})
it('mergePlan drops an element whose id did not survive parsing, never writes undefined', () => {
// 'gone' is not among the bundle routines → ridMap has no entry → filtered out
const bundle = { routines: [{ id: 'a', name: 'A', ex: [{ id: '0025', sets: 3, reps: 5 }] }], week: { 1: ['a', 'gone'], 2: ['gone'] }, customEx: [] }
const target = { routines: [], week: {}, customEx: [] }
mergePlan(target, bundle, { schedule: true })
expect(target.week[1]).toEqual([target.routines[0].id])
expect(target.week[2]).toBeUndefined() // emptied → left absent, not stored as []
})
it('scheduledDays counts a populated array day as 1 and a [] / absent day as 0', () => {
expect(parsePlan({ opengym_plan: 1, routines: [], customEx: [], week: { 1: ['a'], 2: [], 4: 'b' } }).scheduledDays).toBe(2)
})
})
+9 -6
View File
@@ -16,7 +16,7 @@
// · fewer sets than prescribed → miss
// So a session that fell apart can never advance the load as though it had succeeded.
import { modeOf, repStep, rerampWarmups, isBw, isPerSide } from './history.js'
import { modeOf, repStep, rerampWarmups, isBw, isPerSide, entryExcluded } from './history.js'
import { EXIDX } from './exercises.js'
import { isWarmupRow } from './workout-model.js'
import { normalizeRepRange } from './rep-range.js'
@@ -241,12 +241,15 @@ export function readSession(entry, fallback) {
export function sessionsFor(S, exId, fallback) {
const out = []
;(S.workouts || []).forEach(w => {
// A planned deload remains a real workout for history and statistics, but it cannot become
// the baseline for the next regular prescription. The routine flag is copied onto the
// active session, then onto this completed workout, so later routine edits do not rewrite it.
if (w.excludeFromProgression === true) return
const entry = w.entries.find(e => e.id === exId)
if (entry && entry.sets.some(s => s.done && !isWarmupRow(s))) out.push({ d: w.d, ...readSession(entry, fallback) })
if (!entry) return
// A session that does not count for this exercise cannot become the baseline for its next
// prescription. Exclusion is per-entry now (ENG-11): a legacy whole-workout
// `excludeFromProgression` flag still excludes every entry; a merged rehab block excludes
// only its own. `noProg` is frozen onto the entry at build time, so later routine edits
// never rewrite it. This is the only progression-exclusion path in the file.
if (entryExcluded(w, entry)) return
if (entry.sets.some(s => s.done && !isWarmupRow(s))) out.push({ d: w.d, ...readSession(entry, fallback) })
})
return out
}
+92
View File
@@ -4,6 +4,7 @@ import {
policyFor, defaultIncrement, weightIncrement, epley1RM, deloadTarget1RM,
deloadFactorOf, DELOAD_FACTOR, POLICIES_FOR, DELOAD_AFTER, MAX_BW_SETS
} from './progression.js'
import { entryExcluded } from './history.js'
import { EXDB } from './exercises.js'
const LIFT = EXDB.find(e => e.bp !== 'cardio' && !['upper legs', 'lower legs', 'back', 'hips', 'glutes'].includes(e.bp) && !['body weight', 'band', 'resistance band'].includes(e.eq)).id
@@ -564,6 +565,97 @@ describe('sessionsFor', () => {
})
})
// "Excluded from progression" is per-entry now (ENG-11): a rehab routine combined with real
// work must exclude only its own exercises, not the whole session.
describe('per-entry noProg (combine routines)', () => {
const PRESS = EXDB.find(e => e.bp !== 'cardio' && e.id !== LIFT && !['upper legs', 'lower legs', 'back', 'hips', 'glutes'].includes(e.bp)).id
const tgt = w => ({ sets: 3, reps: 5, weight: w })
const entry = (id, w, reps, extra) => ({ id, target: tgt(w), sets: reps.map(r => ({ w, r, done: true })), ...extra })
it('skips a noProg entry for that exercise only, in a mixed combined session', () => {
const S = {
unit: 'kg',
workouts: [{
d: '2026-02-01',
routineIds: ['strength', 'rehab'],
entries: [entry(LIFT, 60, [5, 5, 5]), entry(PRESS, 40, [5, 5, 5], { noProg: true })],
}],
}
expect(sessionsFor(S, LIFT)).toHaveLength(1)
expect(sessionsFor(S, PRESS)).toHaveLength(0)
})
it('still advances the non-excluded exercise of a mixed combined session', () => {
const S = {
unit: 'kg',
workouts: [{
d: '2026-02-01',
entries: [entry(LIFT, 60, [5, 5, 5]), entry(PRESS, 40, [5, 5, 5], { noProg: true })],
}],
}
expect(nextPrescription(S, { id: LIFT, ...tgt(60), prog: 'linear' }).weight).toBe(62.5)
})
it('a noProg gap never becomes the deload / stall baseline', () => {
const S = {
unit: 'kg',
workouts: [
{ d: '2026-02-01', entries: [entry(LIFT, 60, [5, 5, 5])] },
{ d: '2026-02-03', entries: [entry(LIFT, 60, [5, 5, 5])] },
{ d: '2026-02-05', entries: [entry(LIFT, 30, [8, 8, 8], { noProg: true })] },
],
}
expect(sessionsFor(S, LIFT).map(s => s.d)).toEqual(['2026-02-01', '2026-02-03'])
expect(nextPrescription(S, { id: LIFT, ...tgt(60), prog: 'linear' }).weight).toBe(62.5)
})
it('honours a legacy whole-workout excludeFromProgression flag (all entries skipped)', () => {
const S = {
unit: 'kg',
workouts: [
{ d: '2026-02-01', entries: [entry(LIFT, 60, [5, 5, 5])] },
{ d: '2026-02-08', excludeFromProgression: true, entries: [entry(LIFT, 30, [8, 8])] },
],
}
expect(sessionsFor(S, LIFT).map(s => s.d)).toEqual(['2026-02-01'])
})
it('an exercise only ever logged noProg → sessionsFor [] → nextPrescription kind "first"', () => {
const S = {
unit: 'kg',
workouts: [{ d: '2026-02-01', entries: [entry(LIFT, 30, [8, 8, 8], { noProg: true })] }],
}
expect(sessionsFor(S, LIFT)).toHaveLength(0)
expect(nextPrescription(S, { id: LIFT, ...tgt(50), prog: 'linear' }).kind).toBe('first')
})
it('entryExcluded truth table', () => {
expect(entryExcluded({}, {})).toBe(false)
expect(entryExcluded({ excludeFromProgression: true }, {})).toBe(true)
expect(entryExcluded({}, { noProg: true })).toBe(true)
expect(entryExcluded({ excludeFromProgression: true }, { noProg: true })).toBe(true)
})
it('stallCount is not reset by a noProg gap at the same weight', () => {
// three real misses at 60, with a noProg 60 session interleaved — still streaks to a deload
const miss = d => ({ d, entries: [entry(LIFT, 60, [4, 4, 4])] })
const S = {
unit: 'kg',
workouts: [
{ d: '2026-02-01', entries: [entry(LIFT, 60, [5, 5, 5])] },
miss('2026-02-03'),
{ d: '2026-02-04', entries: [entry(LIFT, 60, [3, 3, 3], { noProg: true })] },
miss('2026-02-05'),
miss('2026-02-07'),
],
}
const sessions = sessionsFor(S, LIFT)
expect(sessions.map(s => s.d)).toEqual(['2026-02-01', '2026-02-03', '2026-02-05', '2026-02-07'])
expect(stallCount(sessions)).toBe(3)
expect(nextPrescription(S, { id: LIFT, ...tgt(60), prog: 'linear' }).kind).toBe('deload')
})
})
// Workouts only began storing their prescription in v1.2.2. Everything logged before that is
// targetless, and reading it as "missed" would tell every long-standing user to deload on
// their first session after updating — which is exactly what the demo history did.
+44
View File
@@ -0,0 +1,44 @@
// Building one session's entries from more than one routine (the "combine routines" feature).
//
// A combined session is just the concatenation of the entries each routine would have built on
// its own, with `entry.rid` stamped so a saved workout can be read back per routine. There is
// no composite-routine object: nothing is stored that a single-routine session did not already
// store, only widened. Every start path routes through here, including a single-routine start
// (a one-element list) and freestyle (an empty list → no entries, no rid).
//
// Imported only by sheets.jsx and views/Workout.jsx; imports session-start.js (which pulls in
// history.js + progression.js). Nothing in that chain imports this file, so there is no cycle.
import { buildSessionEntries } from './session-start.js'
/**
* Build a session's entries from an ordered list of routine ids.
* - resolves + filters to still-existing routines, de-duplicates by id (first wins)
* - concatenates each routine's entries in list order
* - stamps `entry.rid` = that routine's id on every entry
*
* Returns `{ entries, routineIds, routines }` — `routineIds` / `routines` are the resolved,
* de-duplicated list, so a caller stores exactly what was built.
*/
export function buildCombinedEntries(st, routineIds) {
const seen = new Set()
const routines = [].concat(routineIds ?? [])
.filter(id => id && !seen.has(id) && seen.add(id))
.map(id => (st.routines || []).find(r => r.id === id))
.filter(Boolean)
const entries = routines.flatMap(r =>
buildSessionEntries(st, r).map(e => ({ ...e, rid: r.id }))
)
return { entries, routineIds: routines.map(r => r.id), routines }
}
/**
* The session name for a combined workout, from routine names in merge order (ENG-12 rule):
* 1–3 routines → join with " + " → "Rehab + Core"
* 4+ routines → first two, then "+ N more" → "Rehab + Core + 2 more"
* An empty list returns null — not a reachable state for a saved or active session.
*/
export function deriveSessionName(names) {
if (!names.length) return null
if (names.length <= 3) return names.join(' + ')
return `${names[0]} + ${names[1]} + ${names.length - 2} more`
}
+58
View File
@@ -0,0 +1,58 @@
import { describe, it, expect } from 'vitest'
import { buildCombinedEntries, deriveSessionName } from './session-merge.js'
import { buildSessionEntries } from './session-start.js'
const st = {
unit: 'kg', workouts: [], exWeights: {},
routines: [
{ id: 'r1', name: 'Strength', prog: 'off', ex: [{ id: '0025', sets: 3, reps: 5, weight: 60 }, { id: '0031', sets: 3, reps: 8, weight: 40 }] },
{ id: 'r2', name: 'Core', prog: 'off', ex: [{ id: '0047', sets: 3, reps: 12, weight: 0 }] },
{ id: 'rehab', name: 'Rehab', excludeFromProgression: true, ex: [{ id: '0050', sets: 2, reps: 15, weight: 5 }] },
],
}
describe('buildCombinedEntries', () => {
it('concatenates each routine’s entries in list order, stamping rid on every one', () => {
const { entries, routineIds } = buildCombinedEntries(st, ['r1', 'r2'])
expect(entries.map(e => e.id)).toEqual(['0025', '0031', '0047'])
expect(entries.map(e => e.rid)).toEqual(['r1', 'r1', 'r2'])
expect(routineIds).toEqual(['r1', 'r2'])
})
it('de-dupes a repeated id (first wins) and drops an id with no matching routine', () => {
const { entries, routineIds } = buildCombinedEntries(st, ['r1', 'gone', 'r1', 'r2'])
expect(routineIds).toEqual(['r1', 'r2'])
expect(entries.map(e => e.rid)).toEqual(['r1', 'r1', 'r2'])
})
it('an empty / null list builds nothing', () => {
expect(buildCombinedEntries(st, [])).toMatchObject({ entries: [], routineIds: [], routines: [] })
expect(buildCombinedEntries(st, null)).toMatchObject({ entries: [], routineIds: [] })
})
it('a single-element list matches the plain buildSessionEntries path (bar the rid stamp)', () => {
const combined = buildCombinedEntries(st, ['r1']).entries.map(({ rid, ...e }) => e)
expect(combined).toEqual(buildSessionEntries(st, st.routines[0]))
})
it('carries an excluded routine’s per-entry noProg through the merge', () => {
const { entries } = buildCombinedEntries(st, ['r1', 'rehab'])
expect(entries.find(e => e.id === '0050')).toMatchObject({ rid: 'rehab', noProg: true })
expect(entries.find(e => e.id === '0025').noProg).toBeUndefined()
})
})
describe('deriveSessionName', () => {
it('is null for an empty list', () => {
expect(deriveSessionName([])).toBe(null)
})
it('joins 1–3 names with " + "', () => {
expect(deriveSessionName(['Rehab'])).toBe('Rehab')
expect(deriveSessionName(['Rehab', 'Core'])).toBe('Rehab + Core')
expect(deriveSessionName(['A', 'B', 'C'])).toBe('A + B + C')
})
it('collapses 4+ to "A + B + N more"', () => {
expect(deriveSessionName(['A', 'B', 'C', 'D'])).toBe('A + B + 2 more')
expect(deriveSessionName(['A', 'B', 'C', 'D', 'E'])).toBe('A + B + 3 more')
})
})
+9 -5
View File
@@ -6,13 +6,18 @@
import { buildSets, applyIntensifierPlan, modeOf } from './history.js'
import { nextPrescription, applyPrescription, defaultIncrement, weightIncrement } from './progression.js'
// Returns a bare array of session entries. "Excluded from progression" is per-entry now
// (`entry.noProg`, written only when true) rather than a wrapper flag — a rehab routine merged
// into real work must exclude only its own exercises. The merge helper (lib/session-merge.js)
// stamps `entry.rid`; this builder is unaware of which routine it serves, so the single-routine
// and combined paths share it unchanged.
export function buildSessionEntries(st, r) {
// The prescription is applied as the session is built, so you walk up to the bar with the
// right weight already on the screen instead of being told about it afterwards. `plan` is
// kept on the entry purely so the workout can explain the number it chose.
const excluded = r?.excludeFromProgression === true
const entries = (r ? r.ex : []).map(cfg => {
const plan = excluded ? { policy: 'off', kind: 'off' } : nextPrescription(st, cfg, r)
const noProg = r?.excludeFromProgression === true
return (r ? r.ex : []).map(cfg => {
const plan = noProg ? { policy: 'off', kind: 'off' } : nextPrescription(st, cfg, r)
// The warm-up ramp and the prescription snap to the exercise's own increment (1.25 kg
// plates exist), not the unit default; a timed exercise's `inc` is seconds, so it keeps the
// default for its optional load.
@@ -23,7 +28,6 @@ export function buildSessionEntries(st, r) {
if (plan.reps != null) target.reps = plan.reps
if (plan.sec != null) target.sec = plan.sec
if (plan.sets != null) target.sets = plan.sets
return { id: cfg.id, sg: cfg.sg, target, plan, sets }
return { id: cfg.id, sg: cfg.sg, target, plan, sets, ...(noProg ? { noProg: true } : {}) }
})
return { entries, excluded }
}
+24 -3
View File
@@ -9,7 +9,7 @@ describe('buildSessionEntries', () => {
it('ramps the warm-ups on the exercise’s own increment, not the unit default', () => {
const r = { id: 'r', prog: 'off', ex: [{ id: '0025', sets: 3, reps: 5, weight: 60, inc: 1.25, warmupSets: 2 }] }
const { entries } = buildSessionEntries(st, r)
const entries = buildSessionEntries(st, r)
const warm = entries[0].sets.filter(isWarmupRow).map(s => s.w)
expect(warm).toHaveLength(2)
for (const w of warm) expect(Math.round(w / 1.25 * 1000) / 1000 % 1).toBe(0) // a multiple of 1.25
@@ -18,7 +18,7 @@ describe('buildSessionEntries', () => {
it('keeps the unit default for timed exercises, whose inc is seconds', () => {
const r = { id: 'r', prog: 'off', ex: [{ id: '0025', mode: 'time', sets: 2, sec: 30, inc: 10, weight: 0 }] }
const { entries } = buildSessionEntries(st, r)
const entries = buildSessionEntries(st, r)
expect(entries[0].sets.every(s => s.sec === 30)).toBe(true)
})
@@ -36,7 +36,7 @@ describe('buildSessionEntries', () => {
}))
}
const r = { id: 'r', prog: 'linear', ex: [cfg] }
const { entries } = buildSessionEntries(st, r)
const entries = buildSessionEntries(st, r)
const entry = entries[0]
const work = entry.sets.filter(s => !isWarmupRow(s))
@@ -44,5 +44,26 @@ describe('buildSessionEntries', () => {
expect(entry.target).toMatchObject({ reps: entry.plan.reps, weight: entry.plan.weight })
expect(readSession({ ...entry, sets: entry.sets.map(s => ({ ...s, done: true })) }, cfg).ok).toBe(true)
expect(work.every(s => s.r === entry.target.reps && s.w === entry.target.weight)).toBe(true)
it('returns a bare array — no { entries, excluded } wrapper', () => {
const r = { id: 'r', prog: 'off', ex: [{ id: '0025', sets: 3, reps: 5, weight: 60 }] }
const out = buildSessionEntries(st, r)
expect(Array.isArray(out)).toBe(true)
expect(out).toHaveLength(1)
})
it('stamps noProg + plan.kind "off" on every entry of an excluded routine, and neither on a normal one', () => {
const ex = [{ id: '0025', sets: 3, reps: 5, weight: 60 }, { id: '0031', sets: 3, reps: 8, weight: 40 }]
const excluded = buildSessionEntries(st, { id: 'rehab', excludeFromProgression: true, ex })
expect(excluded.every(e => e.noProg === true)).toBe(true)
expect(excluded.every(e => e.plan.kind === 'off')).toBe(true)
const normal = buildSessionEntries(st, { id: 'r', prog: 'off', ex })
expect(normal.every(e => e.noProg === undefined)).toBe(true)
})
it('does not stamp rid — that is the merge helper’s job', () => {
const r = { id: 'r', prog: 'off', ex: [{ id: '0025', sets: 3, reps: 5, weight: 60 }] }
expect(buildSessionEntries(st, r)[0].rid).toBeUndefined()
})
})