feat: add strength exercise view and history snapshots
This commit is contained in:
1 parent
528cb70a79
commit
f3ba7de479
12 files changed
+831
-118
No files matched your search
@@ -0,0 +1,29 @@
|
||||
// The persisted boundary for a finished session. Keep this pure so compatibility tests can
|
||||
// exercise the exact shape the UI writes without mounting React or mutating store state.
|
||||
export function buildCompletedWorkout(active, { end = Date.now(), prs = [], snapshotFor } = {}) {
|
||||
const entries = (active?.entries || []).map(entry => {
|
||||
const completed = {
|
||||
id: entry.id,
|
||||
sets: entry.sets,
|
||||
topW: entry.topW || null,
|
||||
target: entry.target || null,
|
||||
}
|
||||
const snapshot = typeof snapshotFor === 'function' ? snapshotFor(entry) : null
|
||||
if (snapshot && typeof snapshot === 'object' && !Array.isArray(snapshot) && Object.keys(snapshot).length) {
|
||||
completed.muscleSnapshot = { ...snapshot }
|
||||
}
|
||||
return completed
|
||||
}).filter(entry => entry.sets.some(set => set.done))
|
||||
|
||||
return {
|
||||
id: active.id,
|
||||
d: active.d,
|
||||
start: active.start,
|
||||
end,
|
||||
routineId: active.routineId,
|
||||
name: active.name,
|
||||
bw: active.bw,
|
||||
entries,
|
||||
prs,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
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,
|
||||
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,
|
||||
entries: [{ id: '0025', sets: [{ done: true, w: 60, r: 8 }], topW: 60, target: { sets: 1, reps: 8 } }],
|
||||
prs: []
|
||||
})
|
||||
})
|
||||
|
||||
it('persists a muscle snapshot only when the caller supplies one', () => {
|
||||
const active = {
|
||||
id: 'active-1', d: '2026-08-08', start: 1000,
|
||||
entries: [
|
||||
{ id: 'catalogue', sets: [{ done: true }] },
|
||||
{ id: 'custom', sets: [{ done: true }] },
|
||||
],
|
||||
}
|
||||
const completed = buildCompletedWorkout(active, {
|
||||
end: 2000,
|
||||
snapshotFor: entry => entry.id === 'custom'
|
||||
? { n: 'Custom lift', muscleWeights: { chest: 1 } }
|
||||
: null,
|
||||
})
|
||||
|
||||
expect(completed.entries[0]).not.toHaveProperty('muscleSnapshot')
|
||||
expect(completed.entries[1].muscleSnapshot).toEqual({
|
||||
n: 'Custom lift', muscleWeights: { chest: 1 },
|
||||
})
|
||||
})
|
||||
})
|
||||
+69
-11
@@ -1,6 +1,16 @@
|
||||
// Pure helpers over the state object S (ported 1:1 from the vanilla app).
|
||||
import { todayISO, isoOf, weekKey, fmtNum } from './format.js'
|
||||
import { isCardio, isBodyweightEq } from './exercises.js'
|
||||
import { phaseForSet, modeForSet, modeForEntry, isWarmupRow, normalizeMode } from './workout-model.js'
|
||||
const objectOf = value => value && typeof value === 'object' && !Array.isArray(value) ? value : {}
|
||||
// Completed-state-independent work rows whose authoritative mode matches the requested mode.
|
||||
const workRowsForMode = (entry = {}, mode = 'reps') => {
|
||||
const source = objectOf(entry)
|
||||
const target = objectOf(source.target || source)
|
||||
const expectedMode = normalizeMode(mode, 'reps')
|
||||
return (Array.isArray(source.sets) ? source.sets : [])
|
||||
.filter(set => phaseForSet(set) === 'work' && modeForSet(set, target) === expectedMode)
|
||||
}
|
||||
// i18n-core, not i18n: this file is imported by mcp/, which is plain Node with no Vite and no
|
||||
// React. i18n.js is the Vite half — import.meta.glob over the locale packs, useSyncExternalStore
|
||||
// for the hook — and it re-exports this very `t` from core, so nothing changes here except what
|
||||
@@ -224,10 +234,7 @@ export function freestyleConfig(S, cfg) {
|
||||
export function bestWeightFor(S, exId) {
|
||||
let best = 0
|
||||
S.workouts.forEach(w => w.entries.forEach(e => {
|
||||
if (e.id === exId) {
|
||||
e.sets.forEach(s => { if (s.done && s.w > best) best = s.w })
|
||||
if (e.topW && e.topW > best) best = e.topW
|
||||
}
|
||||
if (e.id === exId) best = Math.max(best, bestWeightForEntry(e))
|
||||
}))
|
||||
return best
|
||||
}
|
||||
@@ -330,10 +337,10 @@ export function streakWeeks(S) {
|
||||
* undone take the new value (null deletes the key). Done sets are never rewritten.
|
||||
*/
|
||||
export function cascadeWeight(rows, from, value) {
|
||||
const warm = !!rows[from]?.warmup
|
||||
const warm = isWarmupRow(rows[from])
|
||||
const next = rows.slice()
|
||||
for (let j = from + 1; j < next.length; j++) {
|
||||
if (!!next[j].warmup === warm && !next[j].done) {
|
||||
if (isWarmupRow(next[j]) === warm && !next[j].done) {
|
||||
if (value == null) delete next[j].w
|
||||
else next[j].w = value
|
||||
}
|
||||
@@ -343,14 +350,14 @@ export function cascadeWeight(rows, from, value) {
|
||||
|
||||
/** Insert a warm-up row before the first work row, copying the preceding warm-up's values. */
|
||||
export function insertWarmupRow(rows, mode, target) {
|
||||
const firstWork = rows.findIndex(x => !x.warmup)
|
||||
const firstWork = rows.findIndex(x => !isWarmupRow(x))
|
||||
const at = firstWork === -1 ? rows.length : firstWork
|
||||
const l = rows[at - 1] || rows[rows.length - 1]
|
||||
const warm = mode === 'cardio'
|
||||
? { min: l ? l.min : (target.min || 20), speed: l ? l.speed : (target.speed || 8), done: false, warmup: true }
|
||||
? { min: l ? l.min : (target.min || 20), speed: l ? l.speed : (target.speed || 8), done: false, phase: 'warmup', warmup: true }
|
||||
: mode === 'time'
|
||||
? { sec: l ? l.sec : (target.sec || 45), w: l ? (l.w || 0) : (target.weight || 0), done: false, warmup: true }
|
||||
: { w: l ? l.w : 0, r: l ? l.r : target.reps, done: false, warmup: true }
|
||||
? { sec: l ? l.sec : (target.sec || 45), w: l ? (l.w || 0) : (target.weight || 0), done: false, phase: 'warmup', warmup: true }
|
||||
: { w: l ? l.w : 0, r: l ? l.r : target.reps, done: false, phase: 'warmup', warmup: true }
|
||||
const next = rows.slice()
|
||||
next.splice(at, 0, warm)
|
||||
return next
|
||||
@@ -367,6 +374,57 @@ export function removeRowAt(rows, i) {
|
||||
/** Completed non-warm-up sets across a workout's entries. */
|
||||
export function workSetsDone(w) {
|
||||
return (w?.entries || []).reduce(
|
||||
(n, e) => n + (e.sets || []).filter(s => s.done && !s.warmup).length, 0,
|
||||
(n, e) => n + (e.sets || []).filter(s => s.done && !isWarmupRow(s)).length, 0,
|
||||
)
|
||||
}
|
||||
|
||||
const METRIC_MODES = ['reps', 'time', 'cardio']
|
||||
const completedRowsForMode = (entry, mode) => workRowsForMode(entry, mode).filter(s => s.done === true && !isWarmupRow(s))
|
||||
|
||||
export function metricRowsForEntry(entry, mode) {
|
||||
const requested = typeof mode === 'string' ? mode.trim().toLowerCase() : ''
|
||||
const resolved = METRIC_MODES.includes(requested) ? requested : metricModeForEntry(entry)
|
||||
return resolved ? completedRowsForMode(entry, resolved) : []
|
||||
}
|
||||
|
||||
/** The authoritative metric for an entry; reps rows take precedence over timed/cardio rows. */
|
||||
|
||||
export function metricModeForEntry(entry, fallback = null) {
|
||||
for (const mode of METRIC_MODES) {
|
||||
if (completedRowsForMode(entry, mode).length) return mode
|
||||
}
|
||||
return modeForEntry(entry, fallback)
|
||||
}
|
||||
|
||||
/** Best load from completed work rows, with a guarded reps-only legacy topW fallback. */
|
||||
|
||||
export function bestWeightForEntry(entry = {}) {
|
||||
const target = entry.target || entry
|
||||
const workRows = Array.isArray(entry.sets)
|
||||
? entry.sets.filter(s => phaseForSet(s) === 'work')
|
||||
: []
|
||||
const repsRows = metricRowsForEntry(entry, 'reps')
|
||||
if (!repsRows.length) {
|
||||
return workRows.reduce((best, set) => {
|
||||
if (set?.done !== true || isWarmupRow(set)) return best
|
||||
const weight = Number(set.w)
|
||||
return Number.isFinite(weight) && weight > best ? weight : best
|
||||
}, 0)
|
||||
}
|
||||
|
||||
let best = 0
|
||||
repsRows.forEach(set => {
|
||||
const weight = Number(set?.w)
|
||||
if (Number.isFinite(weight) && weight > best) best = weight
|
||||
})
|
||||
|
||||
const parentMode = modeForSet({}, target)
|
||||
const hasNonRepsWorkRow = workRows.some(set => modeForSet(set, target) !== 'reps')
|
||||
const hasWarmupRow = Array.isArray(entry.sets) && entry.sets.some(isWarmupRow)
|
||||
const topWeight = Number(entry.topW)
|
||||
// topW predates phase-tagged warm-ups. It remains a fallback for legacy all-work records,
|
||||
// but cannot override resolved work rows once any warm-up marker exists.
|
||||
if (parentMode === 'reps' && !hasNonRepsWorkRow && !hasWarmupRow
|
||||
&& Number.isFinite(topWeight) && topWeight > best) best = topWeight
|
||||
return best
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { modeOf, isTimed, fmtSec, setLabel, defaultConfig, buildSets, freestyleConfig, exLine, workoutVolume, effortOf, stepEffort, capEffort, isBw, isPerSide, sideReps, repStep, cascadeWeight, insertWarmupRow, removeRowAt, pairAdjacent, unpairSuperset, supersetUnits } from './history.js'
|
||||
import { modeOf, isTimed, fmtSec, setLabel, defaultConfig, buildSets, freestyleConfig, exLine, workoutVolume, bestWeightFor, bestWeightForEntry, effortOf, stepEffort, capEffort, isBw, isPerSide, sideReps, repStep, cascadeWeight, insertWarmupRow, removeRowAt, workSetsDone, pairAdjacent, unpairSuperset, supersetUnits } from './history.js'
|
||||
import { EXDB } from './exercises.js'
|
||||
|
||||
// Real ids out of the shipped catalogue, so the body-part fallback is exercised for real.
|
||||
@@ -9,49 +9,6 @@ const CARDIO = EXDB.find(e => e.bp === 'cardio').id
|
||||
const LIFT = EXDB.find(e => e.bp !== 'cardio' && e.eq !== 'body weight').id
|
||||
const BW = EXDB.find(e => e.eq === 'body weight').id
|
||||
|
||||
describe('superset editing', () => {
|
||||
it('pairs adjacent entries without mutating the source and keeps the display units contiguous', () => {
|
||||
const entries = [{ id: 'a' }, { id: 'b' }, { id: 'c' }]
|
||||
|
||||
const paired = pairAdjacent(entries, 1, 2, 'sg-new')
|
||||
|
||||
expect(paired).toEqual([{ id: 'a' }, { id: 'b', sg: 'sg-new' }, { id: 'c', sg: 'sg-new' }])
|
||||
expect(entries).toEqual([{ id: 'a' }, { id: 'b' }, { id: 'c' }])
|
||||
expect(supersetUnits(paired)).toEqual([[0], [1, 2]])
|
||||
})
|
||||
|
||||
it('merges both contiguous groups when their boundary entries are paired', () => {
|
||||
const entries = [
|
||||
{ id: 'a', sg: 'left' }, { id: 'b', sg: 'left' },
|
||||
{ id: 'c', sg: 'right' }, { id: 'd', sg: 'right' }
|
||||
]
|
||||
|
||||
const merged = pairAdjacent(entries, 1, 2)
|
||||
|
||||
expect(merged.map(e => e.sg)).toEqual(['left', 'left', 'left', 'left'])
|
||||
expect(entries.map(e => e.sg)).toEqual(['left', 'left', 'right', 'right'])
|
||||
})
|
||||
|
||||
it('unpairs one entry and removes sg values left without an adjacent partner', () => {
|
||||
const entries = [
|
||||
{ id: 'a', sg: 'group' }, { id: 'b', sg: 'group' }, { id: 'c', sg: 'group' },
|
||||
{ id: 'd', sg: 'orphan' }
|
||||
]
|
||||
|
||||
const unpaired = unpairSuperset(entries, 1)
|
||||
|
||||
expect(unpaired).toEqual([{ id: 'a' }, { id: 'b' }, { id: 'c' }, { id: 'd' }])
|
||||
expect(entries.map(e => e.sg)).toEqual(['group', 'group', 'group', 'orphan'])
|
||||
})
|
||||
|
||||
it('rejects a non-adjacent pairing request', () => {
|
||||
const entries = [{ id: 'a' }, { id: 'b' }, { id: 'c' }]
|
||||
|
||||
expect(() => pairAdjacent(entries, 0, 2, 'sg-invalid')).toThrow(/adjacent/)
|
||||
expect(entries).toEqual([{ id: 'a' }, { id: 'b' }, { id: 'c' }])
|
||||
})
|
||||
})
|
||||
|
||||
describe('modeOf', () => {
|
||||
it('falls back to the body part when a plan has no mode — every existing plan keeps working', () => {
|
||||
expect(modeOf({ id: CARDIO })).toBe('cardio')
|
||||
@@ -520,6 +477,99 @@ describe('workoutVolume', () => {
|
||||
const w = { entries: [{ id: BW, target: { bodyweight: true }, sets: [{ w: 0, r: 20, done: true }] }] }
|
||||
expect(workoutVolume(w)).toBe(0)
|
||||
})
|
||||
|
||||
it('recognizes both warm-up schemas in work-set counts', () => {
|
||||
const w = {
|
||||
unit: 'kg',
|
||||
entries: [{
|
||||
id: LIFT,
|
||||
unit: 'kg',
|
||||
sets: [
|
||||
{ warmup: true, unit: 'kg', w: 20, r: 5, done: true },
|
||||
{ phase: 'warmup', unit: 'kg', w: 30, r: 5, done: true },
|
||||
{ phase: 'work', unit: 'kg', w: 60, r: 5, done: true },
|
||||
],
|
||||
}],
|
||||
}
|
||||
expect(workSetsDone(w)).toBe(1)
|
||||
})
|
||||
|
||||
it('does not use a warm-up as the previous best working weight', () => {
|
||||
expect(bestWeightFor({ workouts: [{ entries: [{ id: LIFT, topW: 120, sets: [
|
||||
{ phase: 'warmup', done: true, w: 120 },
|
||||
{ phase: 'work', done: true, w: 80 },
|
||||
] }] }] }, LIFT)).toBe(80)
|
||||
expect(bestWeightFor({ workouts: [{ entries: [{ id: LIFT, topW: 120, sets: [
|
||||
{ phase: 'warmup', done: true, w: 120 },
|
||||
] }] }] }, LIFT)).toBe(0)
|
||||
})
|
||||
|
||||
it('uses completed non-warm-up load for timed entries', () => {
|
||||
expect(bestWeightForEntry({ target: { mode: 'time' }, topW: 200, sets: [
|
||||
{ phase: 'warmup', sec: 30, w: 30, done: true },
|
||||
{ phase: 'work', sec: 60, w: 20, done: true },
|
||||
{ phase: 'work', sec: 75, w: 25, done: true },
|
||||
{ phase: 'work', sec: 90, w: 40, done: false },
|
||||
] })).toBe(25)
|
||||
})
|
||||
|
||||
it('does not report a repeated weighted timed hold as a new load PR (blocker 3)', () => {
|
||||
const prior = {
|
||||
id: LIFT,
|
||||
target: { mode: 'time' },
|
||||
sets: [{ phase: 'work', sec: 60, w: 20, done: true }],
|
||||
}
|
||||
const repeated = {
|
||||
id: LIFT,
|
||||
target: { mode: 'time' },
|
||||
sets: [{ phase: 'work', sec: 60, w: 20, done: true }],
|
||||
}
|
||||
const state = { workouts: [{ entries: [prior] }] }
|
||||
const repeatedWeight = Math.max(0, ...repeated.sets.filter(set => set.done).map(set => set.w || 0))
|
||||
|
||||
expect(bestWeightForEntry(prior)).toBe(20)
|
||||
expect(repeatedWeight > bestWeightFor(state, LIFT)).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('superset editing', () => {
|
||||
it('pairs adjacent entries without mutating the source and keeps the display units contiguous', () => {
|
||||
const entries = [{ id: 'a' }, { id: 'b' }, { id: 'c' }]
|
||||
const paired = pairAdjacent(entries, 1, 2, 'sg-new')
|
||||
|
||||
expect(paired).toEqual([{ id: 'a' }, { id: 'b', sg: 'sg-new' }, { id: 'c', sg: 'sg-new' }])
|
||||
expect(entries).toEqual([{ id: 'a' }, { id: 'b' }, { id: 'c' }])
|
||||
expect(supersetUnits(paired)).toEqual([[0], [1, 2]])
|
||||
})
|
||||
|
||||
it('merges both contiguous groups when their boundary entries are paired', () => {
|
||||
const entries = [
|
||||
{ id: 'a', sg: 'left' }, { id: 'b', sg: 'left' },
|
||||
{ id: 'c', sg: 'right' }, { id: 'd', sg: 'right' }
|
||||
]
|
||||
const merged = pairAdjacent(entries, 1, 2)
|
||||
|
||||
expect(merged.map(e => e.sg)).toEqual(['left', 'left', 'left', 'left'])
|
||||
expect(entries.map(e => e.sg)).toEqual(['left', 'left', 'right', 'right'])
|
||||
})
|
||||
|
||||
it('unpairs one entry and removes sg values left without an adjacent partner', () => {
|
||||
const entries = [
|
||||
{ id: 'a', sg: 'group' }, { id: 'b', sg: 'group' }, { id: 'c', sg: 'group' },
|
||||
{ id: 'd', sg: 'orphan' }
|
||||
]
|
||||
const unpaired = unpairSuperset(entries, 1)
|
||||
|
||||
expect(unpaired).toEqual([{ id: 'a' }, { id: 'b' }, { id: 'c' }, { id: 'd' }])
|
||||
expect(entries.map(e => e.sg)).toEqual(['group', 'group', 'group', 'orphan'])
|
||||
})
|
||||
|
||||
it('rejects a non-adjacent pairing request', () => {
|
||||
const entries = [{ id: 'a' }, { id: 'b' }, { id: 'c' }]
|
||||
|
||||
expect(() => pairAdjacent(entries, 0, 2, 'sg-invalid')).toThrow(/adjacent/)
|
||||
expect(entries).toEqual([{ id: 'a' }, { id: 'b' }, { id: 'c' }])
|
||||
})
|
||||
})
|
||||
|
||||
|
||||
|
||||
+111
-10
@@ -7,7 +7,8 @@
|
||||
// map can actually draw, via ALIAS below. Anything genuinely undrawable (hands,
|
||||
// ankles, "cardiovascular system") maps to null and is dropped rather than guessed at.
|
||||
|
||||
import { EXIDX , smOf } from './exercises.js'
|
||||
import { isWarmupRow } from './workout-model.js'
|
||||
import { EXIDX, smOf } from './exercises.js'
|
||||
|
||||
// The muscles a map can shade, in head-to-toe order — also the order of any list
|
||||
// built from them, so "what am I neglecting" reads top-down like a body.
|
||||
@@ -69,21 +70,118 @@ const BY_BODYPART = {
|
||||
|
||||
const SECONDARY = 0.4 // a supporting muscle counts this much against a primary
|
||||
|
||||
/** Muscles one exercise trains: { slug: 0…1 }. */
|
||||
const arrayOf = value => Array.isArray(value) ? value : value == null || value === '' ? [] : [value]
|
||||
|
||||
// Completed history entries may retain a nested snapshot after their custom exercise is
|
||||
// deleted from the profile catalogue. Prefer that snapshot when the outer entry has no muscle
|
||||
// metadata of its own, while keeping direct/legacy entry fields authoritative when present.
|
||||
function metadataOf(ex) {
|
||||
if (!ex || typeof ex !== 'object') return ex
|
||||
const hasDirect = ['muscleGroups', 'muscles', 'targetMuscles'].some(key => Object.prototype.hasOwnProperty.call(ex, key))
|
||||
|| [ex.tg, ex.mg, ...arrayOf(ex.sm)].some(value => value != null && value !== '')
|
||||
return !hasDirect && ex.muscleSnapshot && typeof ex.muscleSnapshot === 'object' && !Array.isArray(ex.muscleSnapshot)
|
||||
? ex.muscleSnapshot
|
||||
: ex
|
||||
}
|
||||
|
||||
function explicitGroupsOf(ex) {
|
||||
if (!ex || typeof ex !== 'object') return null
|
||||
if (Object.prototype.hasOwnProperty.call(ex, 'muscleGroups')) {
|
||||
const groups = arrayOf(ex.muscleGroups)
|
||||
return groups.length ? groups : null
|
||||
}
|
||||
if (Object.prototype.hasOwnProperty.call(ex, 'muscles')) {
|
||||
const groups = arrayOf(ex.muscles)
|
||||
return groups.length ? groups : null
|
||||
}
|
||||
if (Object.prototype.hasOwnProperty.call(ex, 'targetMuscles')) {
|
||||
const groups = arrayOf(ex.targetMuscles)
|
||||
return groups.length ? groups : null
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
/** True only when the catalogue explicitly supplied muscle groups, not a body-part fallback. */
|
||||
export function hasExplicitMuscleMetadata(ex) {
|
||||
const source = metadataOf(ex)
|
||||
if (!source || typeof source !== 'object') return false
|
||||
const groups = explicitGroupsOf(source)
|
||||
if (groups && groups.some(value => canonicalMuscle(value))) return true
|
||||
return [source.tg, source.mg, ...arrayOf(source.sm)].some(value => canonicalMuscle(value))
|
||||
}
|
||||
|
||||
function canonicalMuscle(value) {
|
||||
const name = String(value || '').toLowerCase().trim()
|
||||
if (MUSCLES.includes(name)) return name
|
||||
return ALIAS[name] || null
|
||||
}
|
||||
|
||||
/** Canonical unique muscle groups, accepting both new arrays and legacy single fields. */
|
||||
export function muscleGroupsOf(ex) {
|
||||
const sourceEx = metadataOf(ex)
|
||||
const explicit = explicitGroupsOf(sourceEx)
|
||||
const source = explicit || [sourceEx?.tg, sourceEx?.mg, ...arrayOf(smOf(sourceEx))]
|
||||
const out = []
|
||||
source.forEach(value => {
|
||||
const slug = canonicalMuscle(value)
|
||||
if (slug && !out.includes(slug)) out.push(slug)
|
||||
})
|
||||
if (!out.length && explicit == null) Object.keys(BY_BODYPART[sourceEx?.bp] || {}).forEach(slug => { if (!out.includes(slug)) out.push(slug) })
|
||||
return out
|
||||
}
|
||||
|
||||
export const normalizeMuscleGroups = muscleGroupsOf
|
||||
|
||||
/** True when any requested group matches; an empty request is an intentionally unfiltered query. */
|
||||
export function matchesMuscleGroups(ex, requested) {
|
||||
const wanted = arrayOf(requested).map(canonicalMuscle).filter(Boolean)
|
||||
if (!wanted.length) return true
|
||||
const groups = new Set(muscleGroupsOf(ex))
|
||||
return wanted.some(group => groups.has(group))
|
||||
}
|
||||
|
||||
/** Muscles one exercise trains: { slug: 0…1 }. Duplicate metadata never adds load twice. */
|
||||
export function musclesOf(ex) {
|
||||
if (!ex) return {}
|
||||
const sourceEx = metadataOf(ex)
|
||||
if (sourceEx !== ex) return musclesOf(sourceEx)
|
||||
if (ex.muscleWeights && typeof ex.muscleWeights === 'object' && !Array.isArray(ex.muscleWeights)) {
|
||||
const snapshot = {}
|
||||
MUSCLES.forEach(slug => {
|
||||
const weight = Number(ex.muscleWeights[slug])
|
||||
if (Number.isFinite(weight) && weight > 0) snapshot[slug] = weight
|
||||
})
|
||||
if (Object.keys(snapshot).length) return snapshot
|
||||
}
|
||||
const out = {}
|
||||
const add = (name, w) => {
|
||||
const slug = ALIAS[String(name || '').toLowerCase().trim()]
|
||||
const slug = canonicalMuscle(name)
|
||||
if (slug) out[slug] = Math.max(out[slug] || 0, w)
|
||||
}
|
||||
add(ex.tg, 1)
|
||||
;smOf(ex).forEach(m => add(m, SECONDARY))
|
||||
const explicit = explicitGroupsOf(ex)
|
||||
if (explicit) explicit.forEach(m => add(m, 1))
|
||||
else {
|
||||
add(ex.tg, 1)
|
||||
add(ex.mg, SECONDARY)
|
||||
arrayOf(smOf(ex)).forEach(m => add(m, SECONDARY))
|
||||
}
|
||||
// Nothing recognised (custom exercises, or a target we don't draw) — use the body part.
|
||||
if (!Object.keys(out).length) Object.assign(out, BY_BODYPART[ex.bp] || {})
|
||||
return out
|
||||
}
|
||||
|
||||
/** Snapshot display and weighted muscle metadata into a completed history entry. */
|
||||
export function exerciseMuscleSnapshot(ex) {
|
||||
if (!ex || typeof ex !== 'object') return {}
|
||||
const out = {}
|
||||
if (ex.n != null) out.n = ex.n
|
||||
if (ex.bp != null) out.bp = ex.bp
|
||||
const weights = musclesOf(ex)
|
||||
if (Object.keys(weights).length) out.muscleWeights = { ...weights }
|
||||
if (hasExplicitMuscleMetadata(ex)) out.muscleGroups = [...muscleGroupsOf(ex)]
|
||||
return out
|
||||
}
|
||||
|
||||
/**
|
||||
* Training load per muscle, in "effective sets".
|
||||
* `items` is [{ id, sets }] — sets being a count, so a 4×8 bench press weighs four
|
||||
@@ -92,9 +190,12 @@ export function musclesOf(ex) {
|
||||
*/
|
||||
export function loadOf(items) {
|
||||
const load = {}
|
||||
items.forEach(({ id, sets }) => {
|
||||
items.forEach(item => {
|
||||
const { id, sets } = item || {}
|
||||
if (!sets) return
|
||||
const m = musclesOf(EXIDX[id])
|
||||
const historical = item.ex || item.exercise
|
||||
const source = historical?.muscleWeights ? historical : (EXIDX[id] || historical || item)
|
||||
const m = musclesOf(source)
|
||||
for (const slug in m) load[slug] = (load[slug] || 0) + m[slug] * sets
|
||||
})
|
||||
return load
|
||||
@@ -108,15 +209,15 @@ export function loadOf(items) {
|
||||
*/
|
||||
export const loadOfWorkouts = (workouts, pick) =>
|
||||
loadOf((workouts || []).flatMap(w =>
|
||||
(w.entries || []).map(e => ({ id: e.id, sets: (e.sets || []).filter(s => s.done && !s.warmup && (!pick || pick(s))).length }))))
|
||||
(w.entries || []).map(e => ({ id: e.id, ex: e.exercise || e, sets: (e.sets || []).filter(s => s.done && !isWarmupRow(s) && (!pick || pick(s))).length }))))
|
||||
|
||||
/** Load a routine *would* produce, from its planned set counts. */
|
||||
export const loadOfRoutine = routine =>
|
||||
loadOf((routine?.ex || []).map(c => ({ id: c.id, sets: c.sets || 1 })))
|
||||
loadOf((routine?.ex || []).map(c => ({ id: c.id, ex: c, sets: c.sets || 1 })))
|
||||
|
||||
/** Load for a workout still in progress — the sets ticked so far. */
|
||||
export const loadOfActive = active =>
|
||||
loadOf((active?.entries || []).map(e => ({ id: e.id, sets: (e.sets || []).filter(s => s.done && !s.warmup).length })))
|
||||
loadOf((active?.entries || []).map(e => ({ id: e.id, ex: e.exercise || e, sets: (e.sets || []).filter(s => s.done && !isWarmupRow(s)).length })))
|
||||
|
||||
/**
|
||||
* Shade buckets 0–4 per muscle.
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { isWarmupRow } from './workout-model.js'
|
||||
// Estimated one-rep max (issue #18).
|
||||
//
|
||||
// Deliberately knows nothing about the exercise database: an estimate needs a weight AND a
|
||||
@@ -44,7 +45,7 @@ export function estimate1RM(w, r, formula = DEFAULT_FORMULA) {
|
||||
export function bestSetOf(entry, formula = DEFAULT_FORMULA) {
|
||||
let best = null
|
||||
;(entry?.sets || []).forEach(s => {
|
||||
if (!s.done || s.warmup) return
|
||||
if (!s.done || isWarmupRow(s)) return
|
||||
const est = estimate1RM(s.w, s.r, formula)
|
||||
if (est !== null && (!best || est > best.est)) best = { est, w: Number(s.w), r: Math.round(Number(s.r)) }
|
||||
})
|
||||
|
||||
@@ -111,9 +111,13 @@ function fatigueValue(events, now) {
|
||||
*
|
||||
* @param {Array<object>} workouts Workout history with `start`/`d` and entry set arrays.
|
||||
* @param {number} now Current time in milliseconds; injected to keep this function deterministic.
|
||||
* @param {{unit?: string}} options Reserved profile-level options; unit is supplied at the UI boundary.
|
||||
* @returns {Record<string, number>} Fatigue values keyed by every drawable muscle slug.
|
||||
*/
|
||||
export function fatigueOf(workouts, now) {
|
||||
export function fatigueOf(workouts, now, options = {}) {
|
||||
// Keep the profile unit at this boundary for a future separately reviewed tonnage model.
|
||||
// The current mainline set-count model is intentionally unit-independent.
|
||||
void options.unit
|
||||
const current = Number(now)
|
||||
const cutoff = current - FATIGUE_SCAN_MS
|
||||
const stimuli = completedStimuli(workouts, timestamp => timestamp > cutoff)
|
||||
|
||||
@@ -0,0 +1,143 @@
|
||||
// Per-exercise rows for the Strength view: best estimated 1RM from the user's own logged
|
||||
// sets, the exercise's OWN retained-strength decay (same 14-day plateau / 28-day half-life
|
||||
// / 0.5 floor model as the muscle map, applied to the exercise's last done work set), and
|
||||
// the expected CURRENT 1RM (= estimate x decay). The body map keeps the per-muscle model;
|
||||
// the exercise list deliberately reads per-exercise, so an old exercise shows its own
|
||||
// decline even when its muscle is kept fresh by other work. Muscle mapping is
|
||||
// catalogue-first (EXIDX), exactly like the fatigue/strength maps, falling back to the
|
||||
// logged snapshot (muscleWeights) for exercises no longer in the catalogue.
|
||||
import { best1RM } from './onerm.js'
|
||||
import { STRENGTH_FULL_MS, STRENGTH_HALF_LIFE_MS, STRENGTH_FLOOR, halfLifeDecay } from './recovery.js'
|
||||
import { musclesOf } from './muscles.js'
|
||||
import { EXIDX } from './exercises.js'
|
||||
import { isWarmupRow } from './workout-model.js'
|
||||
|
||||
const round1 = value => Math.round(value * 10) / 10
|
||||
|
||||
// Same retained-strength curve the muscle map uses, applied to one exercise's age.
|
||||
function strengthFromAge(ageMs) {
|
||||
if (!Number.isFinite(ageMs) || ageMs < 0) return STRENGTH_FLOOR
|
||||
if (ageMs <= STRENGTH_FULL_MS) return 1
|
||||
return Math.max(STRENGTH_FLOOR, halfLifeDecay(ageMs - STRENGTH_FULL_MS, STRENGTH_HALF_LIFE_MS))
|
||||
}
|
||||
|
||||
// Timestamp of the exercise's latest completed WORK set (warm-ups excluded - they are prep,
|
||||
// not stimulus, and the strength model is built on effective work).
|
||||
function lastWorkSetAt(S, id) {
|
||||
let latest = -Infinity
|
||||
for (const workout of S?.workouts || []) {
|
||||
const ts = workout.start || new Date(workout.d).getTime()
|
||||
if (!Number.isFinite(ts) || ts <= latest) continue
|
||||
const entry = (workout.entries || []).find(e => e.id === id)
|
||||
if (!entry) continue
|
||||
if ((entry.sets || []).some(s => s.done === true && !isWarmupRow(s))) latest = ts
|
||||
}
|
||||
return Number.isFinite(latest) ? latest : null
|
||||
}
|
||||
|
||||
function snapshotWeights(entry) {
|
||||
const catalogue = entry && typeof entry === 'object' ? EXIDX[entry.id] : null
|
||||
if (catalogue) {
|
||||
const weights = musclesOf(catalogue)
|
||||
if (Object.keys(weights).length) return weights
|
||||
}
|
||||
const direct = entry && typeof entry === 'object'
|
||||
? (entry.muscleWeights || entry.muscleSnapshot?.muscleWeights)
|
||||
: null
|
||||
if (direct && typeof direct === 'object' && !Array.isArray(direct) && Object.keys(direct).length) {
|
||||
return direct
|
||||
}
|
||||
return musclesOf(entry)
|
||||
}
|
||||
|
||||
// Highest-weight muscle of an exercise - used for the primary/secondary badge and the
|
||||
// per-muscle link, not for the decay (the exercise's own decay is what the row shows).
|
||||
export function primaryMuscleOf(entry) {
|
||||
const weights = snapshotWeights(entry)
|
||||
let best = null
|
||||
for (const [slug, weight] of Object.entries(weights)) {
|
||||
if (!best || weight > best.weight) best = { slug, weight }
|
||||
}
|
||||
return best
|
||||
}
|
||||
|
||||
function exerciseName(entry) {
|
||||
// Imported history often has no name snapshot (entries are { id, sets, topW }) - the
|
||||
// catalogue (or the registered custom) is the canonical name source.
|
||||
const ex = entry && typeof entry === 'object' ? EXIDX[entry.id] : null
|
||||
if (ex?.n) return ex.n
|
||||
if (entry?.muscleSnapshot?.n) return entry.muscleSnapshot.n
|
||||
return entry && typeof entry === 'object' && entry.n ? entry.n : null
|
||||
}
|
||||
|
||||
function firstEntryWithId(S, id) {
|
||||
for (const workout of S?.workouts || []) {
|
||||
const entry = (workout.entries || []).find(e => e.id === id)
|
||||
if (entry) return entry
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
/**
|
||||
* Strength rows for every exercise with an estimate: best estimated 1RM (work sets only,
|
||||
* warm-ups excluded), the estimate's date, the exercise's primary muscle, the exercise's
|
||||
* OWN decay (from its last done work set), and the expected current 1RM (estimate x decay).
|
||||
* Sorted by expected current 1RM, strongest first. Exercises without a usable estimate are
|
||||
* omitted - a made-up number is worse than no number.
|
||||
*/
|
||||
export function strengthExerciseRows(S, now) {
|
||||
const workouts = S?.workouts || []
|
||||
const ids = [...new Set(workouts.flatMap(w => (w.entries || []).map(e => e.id)))]
|
||||
const rows = []
|
||||
for (const id of ids) {
|
||||
const best = best1RM(S, id)
|
||||
if (!best) continue
|
||||
const entry = firstEntryWithId(S, id)
|
||||
const lastAt = lastWorkSetAt(S, id)
|
||||
const decay = lastAt == null ? STRENGTH_FLOOR : strengthFromAge(Number(now) - lastAt)
|
||||
rows.push({
|
||||
id,
|
||||
name: exerciseName(entry) || id,
|
||||
est: best.est,
|
||||
estDate: best.d,
|
||||
primary: primaryMuscleOf(entry) ? primaryMuscleOf(entry).slug : null,
|
||||
decay,
|
||||
current: round1(best.est * decay),
|
||||
})
|
||||
}
|
||||
return rows.sort((a, b) => b.current - a.current || String(a.name).localeCompare(String(b.name)))
|
||||
}
|
||||
|
||||
/**
|
||||
* Strength rows for the exercises whose logged snapshot includes `slug` (primary 1 /
|
||||
* secondary 0.4 badge), each with the exercise's OWN decay and expected current 1RM - the
|
||||
* tapped muscle filters the list, the row still speaks for the exercise.
|
||||
*/
|
||||
export function strengthExerciseRowsForMuscle(S, now, slug) {
|
||||
const workouts = S?.workouts || []
|
||||
const seen = new Map()
|
||||
for (const workout of workouts) {
|
||||
for (const entry of workout.entries || []) {
|
||||
if (seen.has(entry.id)) continue
|
||||
const weights = snapshotWeights(entry)
|
||||
const weight = weights[slug]
|
||||
if (!weight) continue
|
||||
const best = best1RM(S, entry.id)
|
||||
if (!best) continue
|
||||
const lastAt = lastWorkSetAt(S, entry.id)
|
||||
const decay = lastAt == null ? STRENGTH_FLOOR : strengthFromAge(Number(now) - lastAt)
|
||||
const primary = primaryMuscleOf(entry)
|
||||
seen.set(entry.id, {
|
||||
id: entry.id,
|
||||
name: exerciseName(entry) || entry.id,
|
||||
weight,
|
||||
primary: primary ? primary.slug : null,
|
||||
est: best.est,
|
||||
estDate: best.d,
|
||||
decay,
|
||||
current: round1(best.est * decay),
|
||||
})
|
||||
}
|
||||
}
|
||||
return [...seen.values()].sort((a, b) => b.current - a.current || String(a.name).localeCompare(String(b.name)))
|
||||
}
|
||||
@@ -0,0 +1,176 @@
|
||||
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
|
||||
import { strengthExerciseRows, strengthExerciseRowsForMuscle, primaryMuscleOf } from './strength-exercises.js'
|
||||
import { registerCustom } from './exercises.js'
|
||||
|
||||
const DAY = 86400000
|
||||
const NOW = Date.UTC(2026, 7, 8, 12) // 2026-08-08 12:00 UTC
|
||||
|
||||
const CUSTOMS = [
|
||||
{ id: 'bench', n: 'Bench Press', tg: 'chest', mg: 'triceps', sm: ['deltoids'] },
|
||||
{ id: 'squat', n: 'Squat', tg: 'quadriceps', mg: 'glutes' },
|
||||
{ id: 'fly', n: 'Cable Crossovers', tg: 'deltoids', mg: 'chest' },
|
||||
{ id: 'pushdown', n: 'Triceps Pushdown', tg: 'triceps' },
|
||||
{ id: 'undone', n: 'Undone Lift', tg: 'upper-back' },
|
||||
{ id: 'stretch', n: 'Chest Stretch', tg: 'chest' },
|
||||
]
|
||||
|
||||
beforeEach(() => registerCustom(CUSTOMS))
|
||||
afterEach(() => registerCustom([]))
|
||||
|
||||
function workout(dayAgo, entries) {
|
||||
const d = new Date(NOW - dayAgo * DAY)
|
||||
const iso = d.toISOString().slice(0, 10)
|
||||
return { id: 'x' + iso, d: iso, start: NOW - dayAgo * DAY, unit: 'kg', entries }
|
||||
}
|
||||
|
||||
const bench = { id: 'bench', n: 'Bench Press', muscleWeights: { chest: 1, triceps: 0.4, deltoids: 0.4 }, sets: [
|
||||
{ phase: 'warmup', w: 40, r: 8, done: true, unit: 'kg' },
|
||||
{ phase: 'work', w: 80, r: 8, done: true, unit: 'kg' },
|
||||
{ phase: 'work', w: 85, r: 6, done: true, unit: 'kg' },
|
||||
] }
|
||||
// est 85x6 -> 102.0 ; 80x8 -> 101.3 ; warmup 40x8 -> 50.7 (must never win)
|
||||
|
||||
const squat = { id: 'squat', n: 'Squat', muscleWeights: { quadriceps: 1, glutes: 0.4 }, sets: [
|
||||
{ phase: 'work', w: 100, r: 5, done: true, unit: 'kg' },
|
||||
] }
|
||||
// est 100x5 -> 116.7 ; trained 30 days ago -> quadriceps decayed (30d - 14d = 16d / 28d half-life)
|
||||
|
||||
const fly = { id: 'fly', n: 'Cable Crossovers', muscleWeights: { chest: 0.4, deltoids: 1 }, sets: [
|
||||
{ phase: 'work', w: 20, r: 12, done: true, unit: 'kg' },
|
||||
] }
|
||||
// est 20x12 -> 28 ; chest is SECONDARY here
|
||||
|
||||
const pushdown = { id: 'pushdown', n: 'Triceps Pushdown', muscleWeights: { triceps: 1 }, sets: [
|
||||
{ phase: 'work', w: 30, r: 10, done: true, unit: 'kg' },
|
||||
] }
|
||||
// est 30x10 -> 40
|
||||
|
||||
const undone = { id: 'undone', n: 'Undone Lift', muscleWeights: { 'upper-back': 1 }, sets: [
|
||||
{ phase: 'work', w: 200, r: 5, done: false, unit: 'kg' },
|
||||
] }
|
||||
|
||||
const noLoad = { id: 'stretch', n: 'Chest Stretch', muscleWeights: { chest: 0.4 }, sets: [
|
||||
{ phase: 'work', w: 0, r: 10, done: true },
|
||||
] }
|
||||
|
||||
const unitState = (workouts) => ({ unit: 'kg', workouts })
|
||||
|
||||
describe('strengthExerciseRows', () => {
|
||||
it('lists every exercise with an estimate, warm-ups excluded, sorted by expected current 1RM', () => {
|
||||
const S = unitState([
|
||||
workout(3, [bench]),
|
||||
workout(30, [squat]),
|
||||
workout(3, [fly, pushdown]),
|
||||
workout(2, [undone, noLoad]),
|
||||
])
|
||||
const rows = strengthExerciseRows(S, NOW)
|
||||
// undone (no completed set) and stretch (no load) have no estimate -> omitted
|
||||
expect(rows.map(r => r.id).sort()).toEqual(['bench', 'fly', 'pushdown', 'squat'])
|
||||
// strongest expected current first: bench 102 > squat ~78.5 > pushdown 40 > fly 28
|
||||
expect(rows[0].id).toBe('bench')
|
||||
expect(rows.at(-1).id).toBe('fly')
|
||||
})
|
||||
|
||||
it('keeps warm-up sets out of the estimate and reports the date of the best work set', () => {
|
||||
const S = unitState([workout(3, [bench])])
|
||||
const rows = strengthExerciseRows(S, NOW)
|
||||
expect(rows).toHaveLength(1)
|
||||
expect(rows[0].est).toBe(102) // 85x6, not 80x8, not the 40x8 warm-up
|
||||
expect(rows[0].estDate).toBe('2026-08-05')
|
||||
expect(rows[0].primary).toBe('chest')
|
||||
})
|
||||
|
||||
it('resolves real exercise names from the catalogue even when entries lack a name snapshot', () => {
|
||||
// Imported history entries are { id, sets, topW } - no `n` snapshot. The catalogue
|
||||
// (or the registered custom) must supply the display name, not the raw id.
|
||||
const nameless = { id: 'bench', sets: bench.sets } // no n, no muscleWeights
|
||||
const S = unitState([workout(3, [nameless])])
|
||||
const rows = strengthExerciseRows(S, NOW)
|
||||
expect(rows).toHaveLength(1)
|
||||
expect(rows[0].name).toBe('Bench Press')
|
||||
expect(rows[0].id).toBe('bench')
|
||||
const muscleRows = strengthExerciseRowsForMuscle(S, NOW, 'chest')
|
||||
expect(muscleRows[0].name).toBe('Bench Press')
|
||||
})
|
||||
|
||||
it('uses nested exercise snapshots for a deleted custom exercise', () => {
|
||||
const deleted = {
|
||||
id: 'deleted-custom',
|
||||
muscleSnapshot: { n: 'Deleted custom', muscleWeights: { chest: 1 } },
|
||||
sets: [{ phase: 'work', warmup: true, w: 80, r: 8, done: true, unit: 'kg' }],
|
||||
}
|
||||
const S = unitState([workout(3, [deleted])])
|
||||
const rows = strengthExerciseRows(S, NOW)
|
||||
expect(rows).toHaveLength(1)
|
||||
expect(rows[0]).toMatchObject({ id: 'deleted-custom', name: 'Deleted custom', primary: 'chest', est: 101.3 })
|
||||
expect(strengthExerciseRowsForMuscle(S, NOW, 'chest')[0].name).toBe('Deleted custom')
|
||||
})
|
||||
|
||||
it('applies the exercise own decay to the expected current 1RM', () => {
|
||||
const S = unitState([workout(3, [bench]), workout(30, [squat])])
|
||||
const rows = strengthExerciseRows(S, NOW)
|
||||
const benchRow = rows.find(r => r.id === 'bench')
|
||||
const squatRow = rows.find(r => r.id === 'squat')
|
||||
// bench last done 3 days ago -> still inside the 14-day full-retention plateau
|
||||
expect(benchRow.decay).toBe(1)
|
||||
expect(benchRow.current).toBe(102)
|
||||
// squat last done 30 days ago -> 16 days past the plateau at a 28-day half-life
|
||||
const squatDecay = 0.5 ** (16 / 28)
|
||||
expect(squatRow.decay).toBeCloseTo(squatDecay, 4)
|
||||
expect(squatRow.current).toBeCloseTo(Math.round(116.7 * squatDecay * 10) / 10, 2)
|
||||
})
|
||||
|
||||
it('keeps the exercise own decay even when its muscle is kept fresh by other work', () => {
|
||||
// bench last done 30 days ago, but chest is fresh (fly trained 3 days ago): the row
|
||||
// speaks for the exercise, so bench still shows its own decline.
|
||||
const S = unitState([workout(30, [bench]), workout(3, [fly])])
|
||||
const rows = strengthExerciseRows(S, NOW)
|
||||
const benchRow = rows.find(r => r.id === 'bench')
|
||||
const benchDecay = 0.5 ** (16 / 28)
|
||||
expect(benchRow.decay).toBeCloseTo(benchDecay, 4)
|
||||
expect(benchRow.current).toBeCloseTo(Math.round(102 * benchDecay * 10) / 10, 2)
|
||||
})
|
||||
})
|
||||
|
||||
describe('strengthExerciseRowsForMuscle', () => {
|
||||
it('lists primary and secondary exercises for the tapped muscle, with that muscle decay', () => {
|
||||
const S = unitState([workout(3, [bench, fly, pushdown])])
|
||||
const rows = strengthExerciseRowsForMuscle(S, NOW, 'chest')
|
||||
expect(rows.map(r => r.id).sort()).toEqual(['bench', 'fly'])
|
||||
const benchRow = rows.find(r => r.id === 'bench')
|
||||
const flyRow = rows.find(r => r.id === 'fly')
|
||||
expect(benchRow.weight).toBe(1)
|
||||
expect(benchRow.primary).toBe('chest')
|
||||
expect(flyRow.weight).toBe(0.4)
|
||||
expect(flyRow.primary).toBe('deltoids')
|
||||
expect(flyRow.decay).toBe(1) // chest is at full retention
|
||||
expect(flyRow.current).toBe(28)
|
||||
})
|
||||
|
||||
it('the tapped muscle filters the list; the row decay stays the exercise own', () => {
|
||||
const S = unitState([workout(3, [bench]), workout(30, [fly])])
|
||||
const rows = strengthExerciseRowsForMuscle(S, NOW, 'triceps')
|
||||
const benchRow = rows.find(r => r.id === 'bench')
|
||||
// bench trains triceps secondarily (0.4), so it appears under the tapped triceps -
|
||||
// but the decay is bench's own (3 days ago -> full), not triceps' stale muscle value.
|
||||
expect(benchRow.weight).toBe(0.4)
|
||||
expect(benchRow.primary).toBe('chest')
|
||||
expect(benchRow.decay).toBe(1)
|
||||
expect(benchRow.current).toBe(102)
|
||||
})
|
||||
|
||||
it('returns nothing for a muscle nothing trains', () => {
|
||||
const S = unitState([workout(3, [bench])])
|
||||
expect(strengthExerciseRowsForMuscle(S, NOW, 'biceps')).toEqual([])
|
||||
})
|
||||
})
|
||||
|
||||
describe('primaryMuscleOf', () => {
|
||||
it('prefers the catalogue, then the logged snapshot, and handles missing metadata', () => {
|
||||
expect(primaryMuscleOf({ id: 'bench', muscleWeights: {} }).slug).toBe('chest') // catalogue wins
|
||||
expect(primaryMuscleOf({ muscleWeights: { chest: 1, triceps: 0.4 } }).slug).toBe('chest') // snapshot fallback
|
||||
expect(primaryMuscleOf({ tg: 'back', mg: 'biceps' }).slug).toBe('upper-back') // canonicalised
|
||||
expect(primaryMuscleOf({})).toBeNull()
|
||||
expect(primaryMuscleOf(null)).toBeNull()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,74 @@
|
||||
// Focused workout semantics shared by session, history, and strength views.
|
||||
// Legacy records have no explicit phase or mode, so the defaults preserve main's work/reps shape.
|
||||
|
||||
const MODES = ['reps', 'time', 'cardio']
|
||||
const objectOf = value => value && typeof value === 'object' && !Array.isArray(value) ? value : {}
|
||||
|
||||
function normalizedPhase(value, fallback = 'work') {
|
||||
const token = typeof value === 'string' ? value.trim().toLowerCase() : ''
|
||||
if (token === 'warmup' || token === 'warm-up' || token === 'warm_up') return 'warmup'
|
||||
if (token === 'work') return 'work'
|
||||
return fallback === 'warmup' ? 'warmup' : 'work'
|
||||
}
|
||||
|
||||
/** Resolve a row's phase. An explicit phase wins over the legacy warmup boolean. */
|
||||
export function phaseForSet(set, fallback = 'work') {
|
||||
const source = objectOf(set)
|
||||
if (source.phase != null && source.phase !== '') return normalizedPhase(source.phase, fallback)
|
||||
return source.warmup === true ? 'warmup' : normalizedPhase(undefined, fallback)
|
||||
}
|
||||
|
||||
export function isWarmupRow(set) {
|
||||
return phaseForSet(set) === 'warmup'
|
||||
}
|
||||
|
||||
export function normalizeMode(value, fallback = 'reps') {
|
||||
const token = typeof value === 'string' ? value.trim().toLowerCase() : ''
|
||||
if (MODES.includes(token)) return token
|
||||
return MODES.includes(fallback) ? fallback : 'reps'
|
||||
}
|
||||
|
||||
function modeFromUnit(value) {
|
||||
const token = typeof value === 'string' ? value.trim().toLowerCase() : ''
|
||||
if (['rep', 'reps', 'repetition', 'repetitions'].includes(token)) return 'reps'
|
||||
if (['sec', 'secs', 'second', 'seconds'].includes(token)) return 'time'
|
||||
if (['min', 'mins', 'minute', 'minutes'].includes(token)) return 'cardio'
|
||||
return null
|
||||
}
|
||||
|
||||
function explicitMode(source) {
|
||||
const value = objectOf(source).mode
|
||||
const token = typeof value === 'string' ? value.trim().toLowerCase() : ''
|
||||
return MODES.includes(token) ? token : modeFromUnit(objectOf(source).unit)
|
||||
}
|
||||
|
||||
function inferredMode(source) {
|
||||
const value = objectOf(source)
|
||||
const explicit = explicitMode(value)
|
||||
if (explicit) return explicit
|
||||
if (String(value.mode || '').trim().toLowerCase() === 'amrap') return 'reps'
|
||||
if (value.min != null || value.speed != null) return 'cardio'
|
||||
if (value.sec != null || value.seconds != null || value.durationSec != null) return 'time'
|
||||
if (value.r != null || value.reps != null || value.actualReps != null) return 'reps'
|
||||
return null
|
||||
}
|
||||
|
||||
/** Resolve one row's mode: explicit row, parent target, then legacy result fields. */
|
||||
export function modeForSet(set, target = {}) {
|
||||
return explicitMode(set) || inferredMode(target) || inferredMode(set) || 'reps'
|
||||
}
|
||||
|
||||
/** Resolve a single mode for an entry; mixed work-row modes intentionally return null. */
|
||||
export function modeForEntry(entry, fallback = null) {
|
||||
const source = objectOf(entry)
|
||||
const target = objectOf(source.target || source)
|
||||
const sets = Array.isArray(source.sets) ? source.sets : []
|
||||
const work = sets.filter(set => !isWarmupRow(set))
|
||||
const observed = work.length ? work : sets
|
||||
const modes = [...new Set(observed.map(set => modeForSet(set, target)))]
|
||||
if (modes.length > 1) return null
|
||||
if (modes.length === 1) return modes[0]
|
||||
const targetMode = inferredMode(target)
|
||||
if (targetMode) return targetMode
|
||||
return fallback == null ? modeForSet(source, target) : normalizeMode(fallback)
|
||||
}
|
||||
Reference in new issue
Block a user