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

+4 -3
View File
@@ -1,6 +1,6 @@
import { useLocation, useNavigate } from 'react-router-dom'
import { useStore } from '../store/useStore.js'
import { effectiveRoutine } from '../lib/history.js'
import { effectiveRoutineIds, effectiveRoutines } from '../lib/history.js'
import { todayISO } from '../lib/format.js'
import { t } from '../lib/i18n.js'
import Icon from './Icon.jsx'
@@ -17,8 +17,9 @@ export default function TabBar({ onStart }) {
const startWorkout = () => {
if (!S.active) {
const r = effectiveRoutine(S, todayISO())
if (r && r.ex.length) { onStart(r.id); return }
// A weekday can hold several routines; start the combined session if any of them has
// exercises, otherwise fall through to the picker.
if (effectiveRoutines(S, todayISO()).some(r => r.ex.length)) { onStart(effectiveRoutineIds(S, todayISO())); return }
}
nav('/workout')
}
+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()
})
})
+111
View File
@@ -0,0 +1,111 @@
// @vitest-environment happy-dom
import React, { act } from 'react'
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
import { createRoot } from 'react-dom/client'
import { useStore } from './store/useStore.js'
import { useUI } from './store/useUI.js'
import { addRoutineToSessionSheet, workoutDetailSheet } from './sheets.jsx'
import { EXDB } from './lib/exercises.js'
const clone = v => JSON.parse(JSON.stringify(v))
const ids = EXDB.filter(e => e.bp !== 'cardio').slice(0, 4).map(e => e.id)
const mounted = []
function renderTop() {
const sheet = useUI.getState().sheets.at(-1)
const host = document.createElement('div')
document.body.appendChild(host)
const root = createRoot(host)
mounted.push(root)
act(() => root.render(sheet.render(() => useUI.getState().closeSheet(sheet.id))))
return host
}
const rowFor = (host, name) => [...host.querySelectorAll('.item')].find(el => el.querySelector('.tt')?.textContent === name)
beforeEach(() => {
globalThis.IS_REACT_ACT_ENVIRONMENT = true
useUI.setState({ sheets: [], toastMsg: '' })
document.body.innerHTML = ''
})
afterEach(() => { act(() => { mounted.splice(0).forEach(r => r.unmount()) }) })
describe('Add routine mid-session sheet', () => {
const setup = () => {
const S = clone(useStore.getState().S)
S.routines = [
{ id: 'strength', name: 'Strength', emoji: '🏋️', prog: 'off', ex: [{ id: ids[0], sets: 3, reps: 5, weight: 60 }] },
{ id: 'core', name: 'Core', emoji: '🧘', prog: 'off', ex: [{ id: ids[1], sets: 3, reps: 12, weight: 0 }, { id: ids[2], sets: 3, reps: 10, weight: 0 }] },
{ id: 'empty', name: 'Empty', emoji: '📝', ex: [] },
]
S.workouts = []
S.active = {
id: 'a', d: '2026-09-06', start: 1, routineIds: ['strength'], name: 'Strength', cur: 0,
entries: [{ id: ids[0], rid: 'strength', target: {}, sets: [{ w: 60, r: 5, done: true }] }],
workoutView: 'cards',
}
useStore.setState({ S, user: null })
}
it('appends the picked routine’s entries with rid, updates routineIds + name, toasts', () => {
setup()
addRoutineToSessionSheet()
const host = renderTop()
act(() => { rowFor(host, 'Core').click() })
const a = useStore.getState().S.active
expect(a.routineIds).toEqual(['strength', 'core'])
expect(a.name).toBe('Strength + Core')
expect(a.entries.map(e => e.rid)).toEqual(['strength', 'core', 'core'])
expect(a.cur).toBe(0) // current unit is left where it was
expect(useUI.getState().toastMsg).toContain('Core added')
})
it('disables a routine already in the session and one with no exercises', () => {
setup()
addRoutineToSessionSheet()
const host = renderTop()
expect(rowFor(host, 'Strength').className).toContain('disabled')
expect(rowFor(host, 'Strength').textContent).toContain('already added')
expect(rowFor(host, 'Empty').className).toContain('disabled')
expect(rowFor(host, 'Empty').textContent).toContain('no exercises')
})
})
describe('WorkoutDetail — per-routine grouping', () => {
const combined = {
id: 'w', d: '2026-09-06', start: 1, end: 2, name: 'Strength + Core', vol: 500,
routineIds: ['strength', 'core'], prs: [],
entries: [
{ id: ids[0], rid: 'strength', target: { reps: 5 }, sets: [{ w: 60, r: 5, done: true }, { w: 60, r: 5, done: true }] },
{ id: ids[1], rid: 'core', target: { reps: 12 }, sets: [{ w: 0, r: 12, done: true }] },
],
}
const legacy = {
id: 'w2', d: '2026-09-06', start: 1, end: 2, name: 'Push', vol: 100, routineIds: ['strength'], prs: [],
entries: [{ id: ids[0], target: { reps: 5 }, sets: [{ w: 100, r: 5, done: true }] }],
}
beforeEach(() => {
const S = clone(useStore.getState().S)
S.routines = [
{ id: 'strength', name: 'Strength', emoji: '🏋️', ex: [] },
{ id: 'core', name: 'Core', emoji: '🧘', ex: [] },
]
useStore.setState({ S, user: null })
})
it('groups a combined workout into per-routine sections with a sets/volume subheader', () => {
const host = (workoutDetailSheet(combined), renderTop())
expect(host.textContent).toContain('Strength')
expect(host.textContent).toContain('Core')
expect(host.textContent).toMatch(/2 sets/)
expect(host.textContent).toMatch(/1 sets|1 set/)
})
it('renders a legacy single-routine workout flat — no routine subheader', () => {
const host = (workoutDetailSheet(legacy), renderTop())
// the only routine name that could appear is the header <h3> (w.name = "Push"); there is
// no "Strength" subheader row
expect(host.querySelectorAll('.row.between').length).toBe(0)
})
})
+69
View File
@@ -0,0 +1,69 @@
// @vitest-environment happy-dom
import { act } from 'react'
import { beforeEach, describe, expect, it } from 'vitest'
import { beginWorkout } from './sheets.jsx'
import { EXDB } from './lib/exercises.js'
import { DEF, useStore } from './store/useStore.js'
import { useUI } from './store/useUI.js'
const clone = v => JSON.parse(JSON.stringify(v))
const ids = EXDB.filter(e => e.bp !== 'cardio').slice(0, 3).map(e => e.id)
function install(routines, week = {}) {
const S = clone(DEF)
S.routines = routines
S.week = week
S.active = null
S.workouts = []
useStore.setState({ S, user: null })
}
beforeEach(() => {
localStorage.clear()
useUI.setState({ sheets: [] })
install([
{ id: 'strength', name: 'Strength', emoji: '🏋️', prog: 'off', ex: [{ id: ids[0], sets: 3, reps: 5, weight: 60 }] },
{ id: 'core', name: 'Core', emoji: '🧘', prog: 'off', ex: [{ id: ids[1], sets: 3, reps: 12, weight: 0 }, { id: ids[2], sets: 3, reps: 10, weight: 0 }] },
{ id: 'rehab', name: 'Rehab', emoji: '🩹', excludeFromProgression: true, ex: [{ id: ids[1], sets: 2, reps: 15, weight: 5 }] },
])
})
describe('beginWorkout with a routine-id list', () => {
it('concatenates the routines’ entries in order, stamps rid, derives the name', () => {
act(() => beginWorkout(['strength', 'core'], null))
const a = useStore.getState().S.active
expect(a.routineIds).toEqual(['strength', 'core'])
expect(a.name).toBe('Strength + Core')
expect(a.entries.map(e => e.rid)).toEqual(['strength', 'core', 'core'])
expect(a).not.toHaveProperty('routineId')
expect(a).not.toHaveProperty('excludeFromProgression')
})
it('a single-element list is an ordinary single-routine session', () => {
act(() => beginWorkout(['strength'], null))
const a = useStore.getState().S.active
expect(a.routineIds).toEqual(['strength'])
expect(a.name).toBe('Strength')
expect(a.entries.every(e => e.rid === 'strength')).toBe(true)
})
it('an empty list is a freestyle session — no entries, no rid', () => {
act(() => beginWorkout([], null))
const a = useStore.getState().S.active
expect(a.routineIds).toEqual([])
expect(a.name).toBe('Freestyle')
expect(a.entries).toEqual([])
})
it('carries a merged excluded routine’s per-entry noProg', () => {
act(() => beginWorkout(['strength', 'rehab'], null))
const a = useStore.getState().S.active
expect(a.entries.find(e => e.rid === 'rehab').noProg).toBe(true)
expect(a.entries.find(e => e.rid === 'strength').noProg).toBeUndefined()
})
it('drops an unknown id and de-dupes a repeat (first wins)', () => {
act(() => beginWorkout(['core', 'gone', 'core'], null))
expect(useStore.getState().S.active.routineIds).toEqual(['core'])
})
})
+151 -41
View File
@@ -4,7 +4,7 @@ import { useUI } from './store/useUI.js'
import { EXDB, EXIDX, BODYPARTS, isCardio, isBodyweightEq, allExercises, equipmentOf, smOf, matchExercise, exOr } from './lib/exercises.js'
import { activeProfile, exAvailable, ALL_EQUIPMENT, newProfile } from './lib/equipment.js'
import { fmtDate, fmtNum, fmtVol, fmtDur, durPart, todayISO, isoOf, uid, exCount, DAYN, DAYS, weekOrder, weekStartOf, weekDayOffset, MONTHS_LONG, ACCENTS } from './lib/format.js'
import { lastEntryFor, bestWeightFor, bestWeightForEntry, buildSets, effectiveRoutineId, workoutVolume, setsDone, setsDoneActive, setUnitsTotal, lastBW, supersetUnits, unitOf, setLabel, defaultConfig, cleanupSg, modeOf, effortOf, EFFORT, capEffort, stepEffort, isBw, isPerSide, sideReps, workSetsDone, applyIntensifierPlan, MAX_PLANNED_WARMUPS, NOTE_MAX } from './lib/history.js'
import { lastEntryFor, bestWeightFor, bestWeightForEntry, buildSets, effectiveRoutineIds, workoutVolume, setsDone, setsDoneActive, setUnitsTotal, lastBW, supersetUnits, unitOf, setLabel, defaultConfig, cleanupSg, modeOf, effortOf, EFFORT, capEffort, stepEffort, isBw, isPerSide, sideReps, workSetsDone, applyIntensifierPlan, MAX_PLANNED_WARMUPS, NOTE_MAX } from './lib/history.js'
import { usesBar, barWeightFor, defaultBarWeight, hasBarOverride } from './lib/bar.js'
import { toScale, rirOf, EFFORT_PRESETS, effortColor } from './lib/effort.js'
import { beep, vibrate } from './lib/sound.js'
@@ -35,6 +35,7 @@ import { swapActiveExercise } from './lib/active-exercise-swap.js'
import { useSheetKeyboard, useRevealActiveChip, tappable } from './lib/use-sheet-keyboard.js'
import { isFav, toggleFav, sortFavouritesFirst } from './lib/favourites.js'
import { buildSessionEntries } from './lib/session-start.js'
import { buildCombinedEntries, deriveSessionName } from './lib/session-merge.js'
import { workoutsOn, backfillStart, backfillEnd, completeBackfill } from './lib/backfill.js'
const S = () => useStore.getState().S
@@ -103,7 +104,7 @@ export function loadStarterPlan(planId) {
if (!plan) return false
update(st => {
st.routines.push(...plan.routines)
plan.schedule.forEach(({ day, routineId }) => { st.week[day] = routineId })
plan.schedule.forEach(({ day, routineId }) => { st.week[day] = [routineId] })
})
toast(t('{0} loaded', PLAN_COPY[planId]().name))
return true
@@ -120,7 +121,7 @@ function StarterPlanChooser({ close }) {
close()
// A confirmation is only worth showing when one of those days is actually occupied — by a
// routine that still exists, not by a stale id the Plan already shows as "Rest".
const taken = day => week[day] && routines.some(r => r.id === week[day])
const taken = day => [].concat(week[day] || []).some(id => routines.some(r => r.id === id))
if (!days.some(taken)) { loadStarterPlan(id); return }
confirmSheet({
title: t('Load {0}?', name),
@@ -950,20 +951,25 @@ export function swapActiveWorkoutExercise(index) {
picker.close()
const full = { ...cfg, id: ex.id }
const st = S()
const current = st.active?.entries?.[index]
if (!current) return
// A swap is an in-place substitution — routine identity is unchanged, so the replacement
// keeps the slot's own `rid` and reads its prescription from that routine (not a
// session-wide one). A slot with no `rid` is freestyle.
const slotRoutine = current.rid ? st.routines.find(r => r.id === current.rid) : null
const freestyle = !slotRoutine
// Same rows the add flow builds: last time's loads and, in a planned session, the
// prescription — swapping barbell for dumbbell bench must not start you at an empty bar.
const freestyle = !st.active?.routineId
const step = modeOf(full) === 'reps' ? weightIncrement(full, st.unit) : defaultIncrement(ex.id, st.unit)
const plan = freestyle ? null : nextPrescription(st, full, st.routines.find(r => r.id === st.active.routineId))
const plan = freestyle ? null : nextPrescription(st, full, slotRoutine)
const built = buildSets(st, full, { step, ...(freestyle ? { preferLast: true } : {}), ...(plan?.kind === 'off' ? { useTarget: true } : {}) })
const replacement = {
id: ex.id,
target: { ...cfg },
plan,
sets: applyIntensifierPlan(freestyle ? built : applyPrescription(built, plan, step), full)
sets: applyIntensifierPlan(freestyle ? built : applyPrescription(built, plan, step), full),
...(current.rid ? { rid: current.rid } : {}),
}
const current = S().active?.entries?.[index]
if (!current) return
const apply = options => {
// A timed callback closes over entry/set indexes. Invalidate it, and the current rest,
@@ -1515,9 +1521,12 @@ function PlanImport({ bundle, close }) {
function DayOverride({ iso, close }) {
const st = useStore(s => s.S)
const wd = new Date(iso + 'T12:00:00').getDay()
const weeklyR = st.routines.find(r => r.id === st.week[wd])
const weeklyNames = [].concat(st.week[wd] || []).map(id => st.routines.find(r => r.id === id)?.name).filter(Boolean)
const hasOvr = st.dayPlan[iso] !== undefined
const effId = effectiveRoutineId(st, iso)
// A weekday can hold several routines; the per-date override stays single-pick, so picking
// one here collapses a combined day to it (docs/COMBINE_ROUTINES.md §8). The check marks
// show everything currently planned for the day.
const effIds = effectiveRoutineIds(st, iso)
const set = v => {
update(s => { if (!v) delete s.dayPlan[iso]; else s.dayPlan[iso] = v })
close()
@@ -1525,13 +1534,13 @@ function DayOverride({ iso, close }) {
}
return <>
<h3>{fmtDate(iso, true)}</h3>
<div className="muted small" style={{ marginBottom: 12 }}>{t('Weekly plan:')} {weeklyR ? weeklyR.name : t('Rest')}{hasOvr && <span style={{ color: 'var(--orange)' }}> · {t('changed for this day')}</span>}<br />{t('Sick, missed a day or want a different session? Pick what to train instead.')}</div>
<div className="muted small" style={{ marginBottom: 12 }}>{t('Weekly plan:')} {weeklyNames.length ? deriveSessionName(weeklyNames) : t('Rest')}{hasOvr && <span style={{ color: 'var(--orange)' }}> · {t('changed for this day')}</span>}<br />{t('Sick, missed a day or want a different session? Pick what to train instead.')}</div>
<div className="list">
{st.routines.map(r => <div key={r.id} className="item" {...tappable(() => set(r.id))}>
<span className="lrow-i"><Icon name={glyphOf(r.emoji)} /></span>
<div className="grow"><div className="tt">{r.name}</div><div className="ss">{exCount(r.ex.length)}</div></div>
{effId === r.id && <Icon name="check" className="accent" />}</div>)}
<div className="item" {...tappable(() => set('rest'))}><span className="lrow-i" style={{ background: 'var(--surface-3)' }}><Icon name="moon" /></span><div className="grow"><div className="tt">{t('Rest / skip this day')}</div></div>{effId === null && <Icon name="check" className="accent" />}</div>
{effIds.includes(r.id) && <Icon name="check" className="accent" />}</div>)}
<div className="item" {...tappable(() => set('rest'))}><span className="lrow-i" style={{ background: 'var(--surface-3)' }}><Icon name="moon" /></span><div className="grow"><div className="tt">{t('Rest / skip this day')}</div></div>{effIds.length === 0 && <Icon name="check" className="accent" />}</div>
{hasOvr && <div className="item" {...tappable(() => set(''))}><span className="lrow-i" style={{ background: 'var(--surface-3)' }}><Icon name="reset" /></span><div className="grow"><div className="tt">{t('Back to weekly plan')}</div></div></div>}
</div>
</>
@@ -1540,20 +1549,47 @@ export const dayOverrideSheet = iso => ui().openSheet(close => <DayOverride iso=
function DayAssign({ day, close }) {
const st = useStore(s => s.S)
const set = v => { update(s => { if (v) s.week[day] = v; else delete s.week[day] }); close() }
// A weekday holds a routine-id list; this single-pick sheet sets an empty day to exactly one
// routine (or rest). The inline + Add routine on the Plan screen is what appends to a
// populated day.
const cur = [].concat(st.week[day] || [])
const set = v => { update(s => { if (v) s.week[day] = [v]; else delete s.week[day] }); close() }
return <>
<h3>{t(DAYN[day])}</h3>
<div className="list">
<div className="item" {...tappable(() => set(''))}><span className="lrow-i" style={{ background: 'var(--surface-3)' }}><Icon name="moon" /></span><div className="grow"><div className="tt">{t('Rest day')}</div></div>{!st.week[day] && <Icon name="check" className="accent" />}</div>
<div className="item" {...tappable(() => set(''))}><span className="lrow-i" style={{ background: 'var(--surface-3)' }}><Icon name="moon" /></span><div className="grow"><div className="tt">{t('Rest day')}</div></div>{!cur.length && <Icon name="check" className="accent" />}</div>
{st.routines.map(r => <div key={r.id} className="item" {...tappable(() => set(r.id))}>
<span className="lrow-i"><Icon name={glyphOf(r.emoji)} /></span>
<div className="grow"><div className="tt">{r.name}</div><div className="ss">{exCount(r.ex.length)}</div></div>
{st.week[day] === r.id && <Icon name="check" className="accent" />}</div>)}
{cur.includes(r.id) && <Icon name="check" className="accent" />}</div>)}
</div>
</>
}
export const dayAssignSheet = day => ui().openSheet(close => <DayAssign day={day} close={close} />)
// + Add routine on a populated weekday: single-pick, appends to the day's list. A routine
// already on that day is disabled; picking one closes the sheet.
function DayAddRoutine({ day, close }) {
const st = useStore(s => s.S)
const on = new Set([].concat(st.week[day] || []))
const add = id => { update(s => { s.week[day] = [...[].concat(s.week[day] || []), id] }); close() }
return <>
<h3>{t('Add routine')}</h3>
<div className="list">
{st.routines.map(r => {
const already = on.has(r.id)
return <div key={r.id} className={'item' + (already ? ' disabled' : '')} aria-disabled={already || undefined}
{...tappable(already ? null : () => add(r.id))}>
<span className="lrow-i"><Icon name={glyphOf(r.emoji)} /></span>
<div className="grow"><div className="tt">{r.name}</div><div className="ss">{exCount(r.ex.length)}</div></div>
{already ? <span className="tag">{t('already added')}</span> : <Icon name="chevronRight" className="chev" />}
</div>
})}
</div>
</>
}
export const dayAddRoutineSheet = day => ui().openSheet(close => <DayAddRoutine day={day} close={close} />)
/* ============================ workout detail ============================ */
function WorkoutDetail({ w, close }) {
const noteRef = useRef(null)
@@ -1585,20 +1621,44 @@ function WorkoutDetail({ w, close }) {
if (text) rec.note = text; else delete rec.note
})
}, [])
// A combined session's entries carry a `rid`; group them into per-routine sections in merge
// order. A legacy single-routine workout (one routineIds, or no rid anywhere) renders flat.
const entryRow = (e, i) => {
const ex = EXIDX[e.id]
return <div key={i} className="row" style={{ marginBottom: 12, alignItems: 'flex-start' }}>
{ex && <Thumb ex={ex} />}
<div className="grow"><div className="tt capitalize" style={{ fontWeight: 600 }}>{ex ? exerciseNameFor(ex) : (e.n || e.id)} {w.prs && w.prs.includes(e.id) && <span className="pr"><Icon name="trophy" />PR</span>}</div>
<div className="ss">{e.sets.filter(s => s.done).map(s => setLabel(e.id, s, e.target)).join(' · ') || t('no sets')}</div>
{e.note && <div className="small dim" style={{ marginTop: 3 }}>
{e.notePin && <Icon name="flag" style={{ fontSize: 12, marginRight: 4, verticalAlign: '-1px', color: 'var(--yellow)' }} />}{e.note}
</div>}</div>
</div>
}
const groups = []
w.entries.forEach((e, i) => {
const key = e.rid || '__none'
let g = groups.find(x => x.key === key)
if (!g) { g = { key, rid: e.rid || null, items: [] }; groups.push(g) }
g.items.push([e, i])
})
const grouped = groups.length > 1 || (groups[0] && groups[0].rid && (w.routineIds || []).length > 1)
return <>
<h3>{w.name}</h3>
<div className="muted small" style={{ marginBottom: 12 }}>{[fmtDate(w.d, true), ...durPart(w.end - w.start), fmtVol(w.vol, st.unit), ...(w.bw ? [fmtNum(w.bw) + ' ' + st.unit] : [])].join(' · ')}</div>
{w.entries.map((e, i) => {
const ex = EXIDX[e.id]
return <div key={i} className="row" style={{ marginBottom: 12, alignItems: 'flex-start' }}>
{ex && <Thumb ex={ex} />}
<div className="grow"><div className="tt capitalize" style={{ fontWeight: 600 }}>{ex ? exerciseNameFor(ex) : (e.n || e.id)} {w.prs && w.prs.includes(e.id) && <span className="pr"><Icon name="trophy" />PR</span>}</div>
<div className="ss">{e.sets.filter(s => s.done).map(s => setLabel(e.id, s, e.target)).join(' · ') || t('no sets')}</div>
{e.note && <div className="small dim" style={{ marginTop: 3 }}>
{e.notePin && <Icon name="flag" style={{ fontSize: 12, marginRight: 4, verticalAlign: '-1px', color: 'var(--yellow)' }} />}{e.note}
</div>}</div>
{grouped ? groups.map(g => {
const r = g.rid ? st.routines.find(x => x.id === g.rid) : null
const setN = g.items.reduce((n, [e]) => n + e.sets.filter(s => s.done && !isWarmupRow(s)).length, 0)
const vol = workoutVolume({ entries: g.items.map(([e]) => e) })
return <div key={g.key}>
<div className="row between" style={{ margin: '2px 0 8px', paddingBottom: 6, borderBottom: '1px solid var(--sep)' }}>
<div className="row" style={{ gap: 7, fontWeight: 600 }}>
{r && <Icon name={glyphOf(r.emoji)} />}{r ? r.name : t('Freestyle')}
</div>
<div className="small dim">{t('{0} sets', setN)} · {fmtVol(vol, st.unit)}</div>
</div>
{g.items.map(([e, i]) => entryRow(e, i))}
</div>
})}
}) : w.entries.map((e, i) => entryRow(e, i))}
<div className="small muted" style={{ margin: '4px 0 6px' }}>{t('Session note')}</div>
<textarea ref={noteRef} className="input" rows={2} maxLength={NOTE_MAX} value={note}
placeholder={t('How the session went as a whole.')}
@@ -1627,8 +1687,8 @@ function Calendar({ start, close }) {
for (let i = 0; i < startOffset; i++) cells.push(<div key={'e' + i} />)
for (let d = 1; d <= daysIn; d++) {
const iso = y + '-' + String(mo + 1).padStart(2, '0') + '-' + String(d).padStart(2, '0')
const ws = byDay[iso], effId = effectiveRoutineId(st, iso), ovr = st.dayPlan[iso] !== undefined
const dotCls = ws ? 'done' : ovr && effId ? 'ovr' : effId ? 'plan' : ''
const ws = byDay[iso], planned = effectiveRoutineIds(st, iso).length > 0, ovr = st.dayPlan[iso] !== undefined
const dotCls = ws ? 'done' : ovr && planned ? 'ovr' : planned ? 'plan' : ''
cells.push(<button key={d} className={'cal-d' + (ws ? ' has' : '') + (iso === todayISO() ? ' today' : '')} onClick={() => {
if (!ws) { close(); dayOverrideSheet(iso); return }
if (ws.length === 1) { close(); workoutDetailSheet(ws[0]); return }
@@ -1667,21 +1727,25 @@ export function WorkoutRow({ w, onClick }) {
}
/* ============================ workout lifecycle ============================ */
export function startFlow(routineId) {
bwSheet({ required: true, onDone: bw => beginWorkout(routineId, bw) })
// `routineIds` accepts `string | string[] | null` — `[r.id]` for one routine,
// `effectiveRoutineIds(...)` for today's planned session, `[]` / null for explicit freestyle.
export function startFlow(routineIds) {
bwSheet({ required: true, onDone: bw => beginWorkout(routineIds, bw) })
}
export function beginWorkout(routineId, bw) {
export function beginWorkout(routineIds, bw) {
const st = S()
const r = routineId ? st.routines.find(x => x.id === routineId) : null
const { entries, excluded } = buildSessionEntries(st, r)
const { entries, routineIds: rids, routines } = buildCombinedEntries(st, routineIds)
update(s => {
s.active = {
id: uid(), d: todayISO(), start: Date.now(), routineId,
name: r ? r.name : t('Freestyle'), bw: bw || null, cur: 0, entries,
id: uid(), d: todayISO(), start: Date.now(),
// A session tracks its routines as a list; per-entry `rid` carries which one each
// exercise came from. No top-level `excludeFromProgression` — per-entry `noProg` does it.
routineIds: rids,
name: routines.length ? deriveSessionName(routines.map(r => r.name)) : t('Freestyle'),
bw: bw || null, cur: 0, entries,
// Snapshot the layout at start so the header ⋮ can change it for this session only —
// changing the saved default (Settings → Workout view) mid-session leaves it alone.
workoutView: st.workoutView || 'cards',
...(excluded ? { excludeFromProgression: true } : {})
}
})
useUI.getState().stopRest()
@@ -1746,23 +1810,69 @@ export function logPastWorkoutSheet() {
if (S().active) { toast(t('Finish the current workout first.')); return }
ui().openSheet(close => <LogPastWorkout close={close} />)
}
// Backfill stays single-routine (the LogPastWorkout UI is one picker), but it emits the new
// shape: a one-element (or empty) routine list, per-entry rid, no top-level routineId.
function beginBackfill({ iso, time, durationMin, routineId, replaceId }) {
const st = S()
const r = routineId ? st.routines.find(x => x.id === routineId) : null
const { entries, excluded } = buildSessionEntries(st, r)
const { entries, routineIds: rids, routines } = buildCombinedEntries(st, routineId ? [routineId] : [])
update(s => {
s.active = {
id: uid(), d: iso, start: backfillStart(iso, time), routineId,
name: r ? r.name : t('Freestyle'), bw: null, cur: 0, entries,
id: uid(), d: iso, start: backfillStart(iso, time),
routineIds: rids,
name: routines.length ? deriveSessionName(routines.map(r => r.name)) : t('Freestyle'),
bw: null, cur: 0, entries,
backfill: { durationMin, replaceId: replaceId || null },
// Same layout snapshot as a live session (see beginWorkout).
workoutView: st.workoutView || 'cards',
...(excluded ? { excludeFromProgression: true } : {})
}
})
useUI.getState().stopRest()
nav('/workout')
}
/* ============================ add a routine mid-session ============================ */
// The workout header ⋮ → Add routine. Single-pick: a routine already in the session, or one
// with no exercises, is shown disabled and tagged. Picking one appends its entries (each
// stamped with its `rid`), extends `s.active.routineIds`, and re-derives the session name.
// `s.active.cur` is left where it is — the appended block is reached by scrolling / Next.
function AddRoutineToSession({ close }) {
const st = useStore(s => s.S)
const active = st.active
if (!active) return null
const inSession = new Set([].concat(active.routineIds || []))
const add = r => {
const entries = buildSessionEntries(st, r).map(e => ({ ...e, rid: r.id }))
update(s => {
if (!s.active) return
s.active.entries.push(...entries)
s.active.routineIds = [...[].concat(s.active.routineIds || []), r.id]
s.active.name = deriveSessionName(s.active.routineIds.map(id => s.routines.find(x => x.id === id)?.name).filter(Boolean))
})
close()
toast(t('{0} added — {1}', r.name, exCount(r.ex.length)))
}
return <>
<h3>{t('Add routine')}</h3>
<div className="list">
{st.routines.map(r => {
const already = inSession.has(r.id)
const empty = !(r.ex || []).length
const disabled = already || empty
return <div key={r.id} className={'item' + (disabled ? ' disabled' : '')} aria-disabled={disabled || undefined}
{...tappable(disabled ? null : () => add(r))}>
<span className="lrow-i"><Icon name={glyphOf(r.emoji)} /></span>
<div className="grow"><div className="tt">{r.name}</div><div className="ss">{exCount(r.ex.length)}</div></div>
{already ? <span className="tag">{t('already added')}</span> : empty ? <span className="tag">{t('no exercises')}</span> : <Icon name="chevronRight" className="chev" />}
</div>
})}
</div>
</>
}
export function addRoutineToSessionSheet() {
if (!S().active) return
ui().openSheet(close => <AddRoutineToSession close={close} />)
}
function TopWeight({ entryIdx, close }) {
const st = useStore(s => s.S)
const A = st.active
+9 -8
View File
@@ -11,7 +11,8 @@ import { loadStarterPlan, starterPlanSheet } from './sheets.jsx'
const mounted = []
const S = () => useStore.getState().S
const nameOn = day => S().routines.find(r => r.id === S().week[day])?.name
// S.week[day] is a routine-id list now; the starter plan writes a one-element list per day.
const nameOn = day => S().routines.find(r => r.id === [].concat(S().week[day] ?? [])[0])?.name
// Renders whatever sheet is on top and returns its host element.
function renderTop() {
@@ -57,7 +58,7 @@ describe('starter plan chooser', () => {
})
it('loads straight away when the plan’s weekdays are free, without asking', () => {
useStore.setState(s => ({ S: { ...s.S, week: { 0: 'mine', 6: 'mine' } } }))
useStore.setState(s => ({ S: { ...s.S, week: { 0: ['mine'], 6: ['mine'] } } }))
choose('Upper / Lower')
expect(useUI.getState().sheets).toHaveLength(0) // no confirmation was raised
@@ -65,20 +66,20 @@ describe('starter plan chooser', () => {
expect(nameOn(2)).toBe('Lower A')
expect(nameOn(4)).toBe('Upper B')
expect(nameOn(5)).toBe('Lower B')
expect(S().week[0]).toBe('mine') // untouched weekdays stay put
expect(S().week[6]).toBe('mine')
expect(S().week[0]).toEqual(['mine']) // untouched weekdays stay put
expect(S().week[6]).toEqual(['mine'])
expect(S().routines[0].name).toBe('My routine') // and nothing is deleted
expect(useUI.getState().toastMsg).toBe('Upper / Lower loaded')
})
it('asks first when a weekday the plan wants is already taken', () => {
useStore.setState(s => ({ S: { ...s.S, week: { 3: 'mine' } } }))
useStore.setState(s => ({ S: { ...s.S, week: { 3: ['mine'] } } }))
choose('Full Body')
const confirm = renderTop()
expect(confirm.querySelector('h3').textContent).toBe('Load Full Body?')
expect(confirm.textContent).toContain('Monday, Wednesday and Friday')
expect(S().week[3]).toBe('mine') // nothing applied yet
expect(S().week[3]).toEqual(['mine']) // nothing applied yet
expect(S().routines).toHaveLength(1)
act(() => { buttonFor(confirm, 'Load plan').click() })
@@ -88,7 +89,7 @@ describe('starter plan chooser', () => {
})
it('leaves everything alone when the confirmation is cancelled', () => {
useStore.setState(s => ({ S: { ...s.S, week: { 1: 'mine' } } }))
useStore.setState(s => ({ S: { ...s.S, week: { 1: ['mine'] } } }))
const before = structuredClone(S())
choose('5×5')
@@ -99,7 +100,7 @@ describe('starter plan chooser', () => {
})
it('does not ask when only weekdays outside the plan are occupied', () => {
useStore.setState(s => ({ S: { ...s.S, week: { 2: 'mine', 4: 'mine' } } })) // Tue + Thu
useStore.setState(s => ({ S: { ...s.S, week: { 2: ['mine'], 4: ['mine'] } } })) // Tue + Thu
choose('5×5') // wants Mon/Wed/Fri
expect(useUI.getState().sheets).toHaveLength(0)
expect(nameOn(1)).toBe('5×5 A')
+12 -7
View File
@@ -1,7 +1,7 @@
import { useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { useStore } from '../store/useStore.js'
import { effectiveRoutine, effectiveRoutineId, nextTrainingDay, streakWeeks, lastBW, setsDoneActive } from '../lib/history.js'
import { effectiveRoutines, effectiveRoutineIds, nextTrainingDay, streakWeeks, lastBW, setsDoneActive } from '../lib/history.js'
import { fmtNum, fmtDate, todayISO, isoOf, weekKey, weekStartOf, weekDayOffset, DAYS, DAYN } from '../lib/format.js'
import { t, dateLocale } from '../lib/i18n.js'
import { bwSheet, goalSheet, dayOverrideSheet, calendarSheet, startFlow, starterPlanSheet, bwDeltaColor } from '../sheets.jsx'
@@ -19,10 +19,14 @@ export default function Home() {
const [weekOffset, setWeekOffset] = useState(0)
const today = new Date()
const routine = effectiveRoutine(S, todayISO())
// A weekday can hold several routines. `todayRoutines` is the whole day; `routine` is the
// first, kept for the one-routine glyph. The derived session name joins them (§9).
const todayRoutines = effectiveRoutines(S, todayISO())
const routine = todayRoutines[0] || null
const todayName = todayRoutines.map(r => r.name).join(' + ')
const todayOvr = S.dayPlan[todayISO()] !== undefined
// On a rest day, saying when you train next beats leaving the row as a full stop.
const next = !S.active && !routine ? nextTrainingDay(S, todayISO()) : null
const next = !S.active && !todayRoutines.length ? nextTrainingDay(S, todayISO()) : null
const bw = lastBW(S)
const prevBW = S.bodyweight.length > 1 ? S.bodyweight[S.bodyweight.length - 2] : null
const delta = bw && prevBW ? bw.w - prevBW.w : null
@@ -40,7 +44,7 @@ export default function Home() {
for (let i = 0; i < 7; i++) {
const d = new Date(wkStart); d.setDate(wkStart.getDate() + i)
const iso = isoOf(d)
const eff = effectiveRoutineId(S, iso), ovr = S.dayPlan[iso] !== undefined, done = doneDays.has(iso)
const eff = effectiveRoutineIds(S, iso).length > 0, ovr = S.dayPlan[iso] !== undefined, done = doneDays.has(iso)
const dot = done ? ' done' : ovr && eff ? ' ovr' : eff ? ' plan' : ''
strip.push(<div key={i} className={'wday' + (iso === todayISO() ? ' today' : '')} {...tappable(() => dayOverrideSheet(iso))}>
<div className="lbl">{t(DAYS[d.getDay()])}</div><div className="num">{d.getDate()}</div><div className={'dot' + dot} /></div>)
@@ -49,11 +53,12 @@ export default function Home() {
const wkLabel = weekOffset === 0 ? t('This week') : `${wkStart.getDate()} ${wkStart.toLocaleDateString(dateLocale(), { month: 'short' })} – ${wkEnd.getDate()} ${wkEnd.toLocaleDateString(dateLocale(), { month: 'short' })}`
const wThisWeek = S.workouts.filter(w => weekKey(w.d, ws) === weekKey(todayISO(), ws)).length
const plannedPerWeek = Object.keys(S.week).filter(k => S.week[k]).length
// Days scheduled, not routines — a combined day counts as 1, matching wThisWeek (one w).
const plannedPerWeek = Object.values(S.week).filter(ids => ids?.length).length
const bwPoints = S.bodyweight.slice(-30).map(b => ({ t: b.t || new Date(b.d).getTime(), y: b.w, d: b.d }))
// today's session shown right under the week strip
const onToday = () => { if (S.active) nav('/workout'); else if (routine) startFlow(routine.id); else dayOverrideSheet(todayISO()) }
const onToday = () => { if (S.active) nav('/workout'); else if (todayRoutines.length) startFlow(effectiveRoutineIds(S, todayISO())); else dayOverrideSheet(todayISO()) }
return <div className="narrow">
<div className="hdr">
@@ -83,7 +88,7 @@ export default function Home() {
<div className="lbl2">{t('Today')}</div>
<div className="ttl">{S.active ? t('{0} — in progress', S.active.name)
: doneToday ? (doneToday.name ? t('{0} — done', doneToday.name) : t('Workout done'))
: routine ? routine.name : t('Rest day')}{todayOvr && routine && !doneToday ? ' · ' + t('rescheduled') : ''}</div>
: routine ? todayName : t('Rest day')}{todayOvr && routine && !doneToday ? ' · ' + t('rescheduled') : ''}</div>
{next && !doneToday && <div className="ss">{t('Next session: {0}, {1}', t(DAYN[next.weekday]), next.routine.name)}</div>}
</div>
</div>
+26 -4
View File
@@ -2,7 +2,7 @@ import { useNavigate } from 'react-router-dom'
import { useStore } from '../store/useStore.js'
import { DAYN, weekOrder, weekStartOf, uid, exCount } from '../lib/format.js'
import { t } from '../lib/i18n.js'
import { dayAssignSheet, starterPlanSheet, planToolsSheet } from '../sheets.jsx'
import { dayAssignSheet, dayAddRoutineSheet, starterPlanSheet, planToolsSheet } from '../sheets.jsx'
import Icon from '../components/Icon.jsx'
import { Button } from '../components/ui.jsx'
import { tappable } from '../lib/use-sheet-keyboard.js'
@@ -31,6 +31,12 @@ export default function Plan() {
nav('/plan/r/' + r.id)
}
// Pull one routine off a weekday; drop the key when the day empties (never store []).
const removeFromDay = (d, rid) => update(s => {
const next = [].concat(s.week[d] || []).filter(id => id !== rid)
if (next.length) s.week[d] = next; else delete s.week[d]
})
return <>
<div className="hdr">
<div><h1>{t('Plan')}</h1><div className="sub">{t('Your weekly routine')}</div></div>
@@ -49,11 +55,27 @@ export default function Plan() {
<h4 className="sec">{t('Week schedule')}</h4>
<div className="list" style={{ display: 'flex', flexDirection: 'column' }}>
{weekOrder(weekStartOf(S)).map(d => {
const r = S.routines.find(x => x.id === S.week[d])
return <div key={d} className="item" {...tappable(() => dayAssignSheet(d))}>
const dayRoutines = [].concat(S.week[d] || []).map(id => S.routines.find(x => x.id === id)).filter(Boolean)
// An empty day stays one tappable row → pick its first routine (today's behaviour).
if (!dayRoutines.length) return <div key={d} className="item" {...tappable(() => dayAssignSheet(d))}>
<div className="grow"><div className="tt">{t(DAYN[d])}</div></div>
{r ? <span className="tag acc"><Icon name={glyphOf(r.emoji)} />{r.name}</span> : <span className="tag">{t('Rest')}</span>}
<span className="tag">{t('Rest')}</span>
<Icon name="chevronRight" className="chev" /></div>
// A populated day: always-visible routine sub-rows + inline ✕, then + Add routine.
return <div key={d} className="item" style={{ display: 'block', padding: '10px 14px' }}>
<div className="row between" style={{ marginBottom: 6 }}>
<div className="tt">{t(DAYN[d])}</div>
<div className="small dim">{t('{0} routines', dayRoutines.length)}</div>
</div>
{dayRoutines.map(r => <div key={r.id} className="row" style={{ gap: 8, padding: '4px 0 4px 8px' }}>
<span className="lrow-i" style={{ width: 26, height: 26, fontSize: 14 }}><Icon name={glyphOf(r.emoji)} /></span>
<div className="grow" style={{ minWidth: 0 }}><div className="tt" style={{ fontSize: 14 }}>{r.name}</div><div className="ss">{exCount(r.ex.length)}</div></div>
<button className="iconbtn sm" aria-label={t('Remove')} onClick={() => removeFromDay(d, r.id)}><Icon name="xmark" /></button>
</div>)}
<button className="btn ghost sm" style={{ marginTop: 4, marginLeft: 8 }} onClick={() => dayAddRoutineSheet(d)}>
<Icon name="plus" /> {t('Add routine')}
</button>
</div>
})}
</div>
</div><div>
+6 -1
View File
@@ -450,7 +450,12 @@ export default function RoutineEdit() {
onConfirm: () => {
update(s => {
s.routines = s.routines.filter(x => x.id !== id)
Object.keys(s.week).forEach(k => { if (s.week[k] === id) delete s.week[k] })
// A weekday holds a routine-id list: pull the deleted id from each day, drop the
// key when it empties (never store []). dayPlan stays scalar.
Object.keys(s.week).forEach(k => {
const next = [].concat(s.week[k]).filter(rid => rid !== id)
if (next.length) s.week[k] = next; else delete s.week[k]
})
Object.keys(s.dayPlan).forEach(k => { if (s.dayPlan[k] === id) delete s.dayPlan[k] })
})
nav('/plan')
+38 -19
View File
@@ -5,14 +5,14 @@ import { workoutControls } from '../lib/workout-controls.js'
import { useUI } from '../store/useUI.js'
import { exOr } from '../lib/exercises.js'
import { usesBar, barWeightFor, plateSplit } from '../lib/bar.js'
import { effectiveRoutine, lastEntryFor, bestWeightFor, bestWeightForEntry, buildSets, freestyleConfig, defaultConfig, setsDoneActive, setUnitsTotal, supersetUnits, unitOf, setLabel, modeOf, isBw, isPerSide, repStep, EFFORT, effortOf, stepEffort, capEffort, cascadeWeight, insertWarmupRow, removeRowAt, pairAdjacent, unpairSuperset, cleanupSg, applyIntensifierPlan, pinnedNoteFor, exNoteFor } from '../lib/history.js'
import { effectiveRoutines, effectiveRoutineIds, lastEntryFor, bestWeightFor, bestWeightForEntry, buildSets, freestyleConfig, defaultConfig, setsDoneActive, setUnitsTotal, supersetUnits, unitOf, setLabel, modeOf, isBw, isPerSide, repStep, EFFORT, effortOf, stepEffort, capEffort, cascadeWeight, insertWarmupRow, removeRowAt, pairAdjacent, unpairSuperset, cleanupSg, applyIntensifierPlan, pinnedNoteFor, exNoteFor } from '../lib/history.js'
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 { insertionIndexAfterCurrentUnit, nextUnfinishedUnit, setProgressHighWater, supersetFlowStep, restAfterSet, restOnRecheck, restSecFor } from '../lib/supersetFlow.js'
import Media from '../components/Media.jsx'
import { startFlow, exercisePicker, exConfigSheet, exerciseDetailSheet, finishWorkout, workoutCompleteSheet, confirmSheet, exerciseNoteSheet, sessionNoteSheet, swapActiveWorkoutExercise, barWeightSheet, menuSheet, effortPickerSheet, exerciseHistorySheet } from '../sheets.jsx'
import { startFlow, exercisePicker, exConfigSheet, exerciseDetailSheet, finishWorkout, workoutCompleteSheet, confirmSheet, exerciseNoteSheet, sessionNoteSheet, swapActiveWorkoutExercise, barWeightSheet, menuSheet, effortPickerSheet, exerciseHistorySheet, addRoutineToSessionSheet } from '../sheets.jsx'
import { effortColor } from '../lib/effort.js'
import Icon from '../components/Icon.jsx'
import { Button, Check, NumberField } from '../components/ui.jsx'
@@ -30,26 +30,29 @@ const SWIPE_IGNORED_TARGETS = 'button,input,textarea,select,a,[role="button"],[r
function StartChooser() {
const nav = useNavigate()
const S = useStore(s => s.S)
const todayR = effectiveRoutine(S, todayISO())
const todayIds = effectiveRoutineIds(S, todayISO())
const todayRoutines = effectiveRoutines(S, todayISO())
const todayName = todayRoutines.map(r => r.name).join(' + ')
const todayOvr = S.dayPlan[todayISO()] !== undefined
const others = S.routines.filter(r => r !== todayR)
const idSet = new Set(todayIds)
const others = S.routines.filter(r => !idSet.has(r.id))
return <div className="narrow">
<div className="hdr"><div><h1>{t('Start workout')}</h1><div className="sub">{t(DAYN[new Date().getDay()])} — {todayR ? t('today is {0}', todayR.name) : t('rest day, but no one’s stopping you')}</div></div></div>
{todayR && <div className="card" style={{ borderColor: 'var(--acc)' }}>
<div className="hdr"><div><h1>{t('Start workout')}</h1><div className="sub">{t(DAYN[new Date().getDay()])} — {todayRoutines.length ? t('today is {0}', todayName) : t('rest day, but no one’s stopping you')}</div></div></div>
{todayRoutines.length > 0 && <div className="card" style={{ borderColor: 'var(--acc)' }}>
<h2 className="accent">{t("Today's plan")}{todayOvr ? ' · ' + t('rescheduled') : ''}</h2>
<div className="row between" style={{ marginBottom: 12 }}>
<div><div className="big">{todayR.name}</div><div className="muted small">{exCount(todayR.ex.length)}</div></div>
<span className="lrow-i" style={{ width: 38, height: 38, borderRadius: 9, fontSize: 22 }}><Icon name={glyphOf(todayR.emoji)} /></span>
<div><div className="big">{todayName}</div><div className="muted small">{exCount(todayRoutines.reduce((n, r) => n + r.ex.length, 0))}</div></div>
<span className="lrow-i" style={{ width: 38, height: 38, borderRadius: 9, fontSize: 22 }}><Icon name={glyphOf(todayRoutines[0].emoji)} /></span>
</div>
<Button variant="primary" icon="play" onClick={() => startFlow(todayR.id)}>{t('Start {0}', todayR.name)}</Button>
<Button variant="primary" icon="play" onClick={() => startFlow(todayIds)}>{t('Start {0}', todayName)}</Button>
</div>}
{others.length > 0 && <><h4 className="sec">{t('Other routines')}</h4>
<div className="list">{others.map(r => <div key={r.id} className="item" onClick={() => startFlow(r.id)}>
<div className="list">{others.map(r => <div key={r.id} className="item" onClick={() => startFlow([r.id])}>
<span className="lrow-i"><Icon name={glyphOf(r.emoji)} /></span>
<div className="grow"><div className="tt">{r.name}</div><div className="ss">{exCount(r.ex.length)}</div></div>
<span className="tag acc">{t('Start')}</span></div>)}</div></>}
<div style={{ height: 14 }} />
<Button icon="shuffle" onClick={() => startFlow(null)}>{t('Freestyle workout (pick as you go)')}</Button>
<Button icon="shuffle" onClick={() => startFlow([])}>{t('Freestyle workout (pick as you go)')}</Button>
{!S.routines.length && <><div style={{ height: 10 }} /><Button variant="primary" onClick={() => nav('/plan')}>{t('Build a plan first')}</Button></>}
</div>
}
@@ -681,14 +684,23 @@ function ActiveWorkout() {
// (Settings → During a workout → Workout view). It writes s.active.workoutView, which the
// render above prefers over S.workoutView.
const setWorkoutView = v => update(s => { if (s.active) s.active.workoutView = v })
const openViewMenu = () => menuSheet({
title: t('Workout view'),
const LAYOUT_LABEL = { cards: t('Cards'), list: t('List'), compact: t('Compact') }
const openLayoutMenu = () => menuSheet({
title: t('Layout'),
items: [
{ icon: 'clipboard', label: t('Cards'), on: workoutView === 'cards', onClick: () => setWorkoutView('cards') },
{ icon: 'list', label: t('List'), on: workoutView === 'list', onClick: () => setWorkoutView('list') },
{ icon: 'minimize', label: t('Compact'), on: workoutView === 'compact', onClick: () => setWorkoutView('compact') },
],
})
// The header ⋮: bring another routine into the session, then the layout switch nested a
// level down (it used to be the whole menu).
const openViewMenu = () => menuSheet({
items: [
{ icon: 'plus', label: t('Add routine'), sub: t('Bring another routine into this session'), onClick: addRoutineToSessionSheet },
{ icon: 'list', label: t('Layout'), sub: LAYOUT_LABEL[workoutView] || LAYOUT_LABEL.cards, onClick: openLayoutMenu },
],
})
const onSwipePointerDown = event => {
if (swipe.current || (event.pointerType && event.pointerType !== 'touch' && event.pointerType !== 'pen')) return
if (event.target.closest?.(SWIPE_IGNORED_TARGETS)) return
@@ -714,7 +726,9 @@ function ActiveWorkout() {
const activeId = state.active.id
const entryId = entry.id
const entryCount = state.active.entries.length
const routine = state.routines.find(r => r.id === state.active.routineId)
// A combined session's entries each carry a `rid`; progression settings read from that
// entry's own routine, not a session-wide one.
const routine = state.routines.find(r => r.id === entry.rid)
exConfigSheet(exOr(entryId), entry.target, cfg => {
// Store updates clone the state tree. If this exact object is no longer at the captured
// index, the list changed while the sheet was open; an id check alone cannot distinguish
@@ -730,7 +744,7 @@ function ActiveWorkout() {
// happens to occupy the same index.
if (!activeEntry || activeEntry.id !== entryId) return
const full = { ...cfg, id: activeEntry.id }
const activeRoutine = s.routines.find(r => r.id === s.active.routineId)
const activeRoutine = s.routines.find(r => r.id === activeEntry.rid)
const step = modeOf(full) === 'reps' ? weightIncrement(full, s.unit) : defaultIncrement(activeEntry.id, s.unit)
// A config without a set count keeps the rows the session already has.
if (!(full.sets > 0)) full.sets = activeEntry.sets.filter(x => !isWarmupRow(x)).length || 1
@@ -990,15 +1004,20 @@ function ActiveWorkout() {
{!listMode && <div style={{ height: 10 }} />}
{wc.exerciseButtons && listMode && A.entries.length > 0 && <div className="muted small" style={{ marginBottom: 6 }}>{t('Move, swap and remove below act on the exercise marked {0}.', t('Current'))}</div>}
<Button onClick={() => exercisePicker((ex, quick) => {
const routine = S.routines.find(r => r.id === A.routineId)
const freestyle = !A.routineId
// A freehand add inherits the current unit's routine (its `rid`) so it lands in that
// routine's block in a combined session and gets a real prescription; a routine-less
// freestyle session has no `rid` to inherit. `noProg` is never set independently here —
// the only mid-session route to an excluded entry is "Add routine".
const curRid = A.entries[A.cur]?.rid
const routine = curRid ? S.routines.find(r => r.id === curRid) : null
const freestyle = !routine
// Freestyle has no routine prescription to apply: show the last target in the config
// sheet and carry its completed rows forward. A planned session uses its configured
// target when progression is off, while progression-enabled sessions keep their path.
const seed = freestyle ? freestyleConfig(S, { id: ex.id, ...defaultConfig(ex.id) }) : null
const commit = cfg => update(s => {
const full = { ...cfg, id: ex.id }
const plan = freestyle ? null : nextPrescription(s, full, s.routines.find(r => r.id === s.active.routineId))
const plan = freestyle ? null : nextPrescription(s, full, routine)
const sets = buildSets(s, full, {
step: modeOf(full) === 'reps' ? weightIncrement(full, s.unit) : defaultIncrement(ex.id, s.unit),
...(freestyle ? { preferLast: true } : {}),
@@ -1006,7 +1025,7 @@ function ActiveWorkout() {
})
const progressed = freestyle ? sets : applyPrescription(sets, plan, modeOf(full) === 'reps' ? weightIncrement(full, s.unit) : defaultIncrement(ex.id, s.unit))
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.entries.splice(insertAt, 0, { id: ex.id, target: { ...cfg }, plan, sets: applyIntensifierPlan(progressed, full), ...(curRid ? { rid: curRid } : {}) })
s.active.cur = insertAt
useUI.getState().shiftRestOwner(insertAt, 1)
})
+20 -10
View File
@@ -78,6 +78,7 @@ vi.mock('../sheets.jsx', () => ({
sessionNoteSheet: vi.fn(),
effortPickerSheet: mocks.effortPickerSheet,
exerciseHistorySheet: mocks.exerciseHistorySheet,
addRoutineToSessionSheet: vi.fn(),
}))
vi.mock('../components/Media.jsx', () => ({ default: () => null }))
// api.js reads navigator.userAgent at module scope. This file installs its own DOM inside the
@@ -1157,21 +1158,30 @@ describe('workout view header menu', () => {
}
const item = (menu, label) => menu.items.filter(Boolean).find(it => it.label === label)
it('offers the three layouts and marks the running session current', async () => {
await mount([exercise('plain-bench', [false])], 0, { active: { workoutView: 'list' } })
// The header ⋮ now leads with "Add routine"; the layouts moved to a nested "Layout" sheet.
const openLayout = async menu => {
await act(async () => { item(menu, 'Layout').onClick() })
return mocks.menuSheet.mock.calls.at(-1)[0]
}
it('leads with Add routine, then a Layout sheet with the three layouts marked current', async () => {
await mount([exercise('plain-bench', [false])], 0, { active: { workoutView: 'list', routineIds: [] } })
const menu = await openMenu()
expect(menu.items.filter(Boolean).map(it => it.label)).toEqual(['Cards', 'List', 'Compact'])
expect(item(menu, 'List').on).toBe(true)
expect(item(menu, 'Cards').on).toBe(false)
expect(item(menu, 'Compact').on).toBe(false)
expect(menu.items.filter(Boolean).map(it => it.label)).toEqual(['Add routine', 'Layout'])
expect(item(menu, 'Layout').sub).toBe('List')
const layout = await openLayout(menu)
expect(layout.items.filter(Boolean).map(it => it.label)).toEqual(['Cards', 'List', 'Compact'])
expect(item(layout, 'List').on).toBe(true)
expect(item(layout, 'Cards').on).toBe(false)
})
it('writes the pick onto s.active without touching the global default', async () => {
await mount([exercise('plain-bench', [false])], 0, { workoutView: 'cards', active: { workoutView: 'cards' } })
it('writes the layout pick onto s.active without touching the global default', async () => {
await mount([exercise('plain-bench', [false])], 0, { workoutView: 'cards', active: { workoutView: 'cards', routineIds: [] } })
const menu = await openMenu()
await act(async () => { item(menu, 'Compact').onClick() })
const layout = await openLayout(await openMenu())
await act(async () => { item(layout, 'Compact').onClick() })
expect(mocks.S.active.workoutView).toBe('compact')
expect(mocks.S.workoutView).toBe('cards')
+41 -1
View File
@@ -46,7 +46,7 @@ vi.mock('./MobileOnboarding.jsx', () => ({ ConnectSheet: () => null }))
vi.mock('../sheets.jsx', () => ({
starterPlanSheet: vi.fn(), confirmSheet: vi.fn(), importFromApp: vi.fn(),
importFromHevy: vi.fn(), equipmentProfileSheet: vi.fn(),
dayAssignSheet: vi.fn(), planToolsSheet: vi.fn(),
dayAssignSheet: vi.fn(), dayAddRoutineSheet: vi.fn(), planToolsSheet: vi.fn(),
}))
globalThis.__APP_VERSION__ ??= 'test'
@@ -118,3 +118,43 @@ describe('Plan — the week schedule follows the setting', () => {
expect(rows[1].textContent).not.toContain('Push')
})
})
describe('Plan — inline per-day routine management (combine routines)', () => {
const mount = () => act(() => root.render(<Plan />))
const dayContainer = name => [...host.querySelectorAll('.item')].find(el => el.querySelector('.tt')?.textContent === name)
beforeEach(() => {
mocks.S.routines = [
{ id: 'r1', name: 'Push', emoji: null, ex: [{ id: 'a' }, { id: 'b' }] },
{ id: 'r2', name: 'Core', emoji: null, ex: [{ id: 'c' }] },
]
})
it('renders a sub-row per routine on a populated day, with the count hint', () => {
mocks.S.week = { 1: ['r1', 'r2'] }
mount()
const mon = dayContainer('Monday')
expect(mon.textContent).toContain('Push')
expect(mon.textContent).toContain('Core')
expect(mon.textContent).toContain('2 routines')
})
it('✕ removes a routine, and drops the day key on the last removal', () => {
mocks.S.week = { 1: ['r1', 'r2'] }
mount()
const removeButtons = () => [...dayContainer('Monday').querySelectorAll('button[aria-label="Remove"]')]
act(() => { removeButtons()[1].dispatchEvent(new Event('click', { bubbles: true })) })
expect(mocks.S.week[1]).toEqual(['r1'])
mount()
act(() => { removeButtons()[0].dispatchEvent(new Event('click', { bubbles: true })) })
expect(mocks.S.week).not.toHaveProperty('1')
})
it('an empty day stays one tappable row', () => {
mocks.S.week = {}
mount()
const tue = dayContainer('Tuesday')
expect(tue.textContent).toContain('Rest')
expect(tue.querySelectorAll('button[aria-label="Remove"]').length).toBe(0)
})
})