Merge remote-tracking branch 'pr/44'

This commit is contained in:
Duarte Santos committed 2026-08-07 11:33:51 +02:00
commit 7e60ac20f2
22 files changed
+1402 -37

No files matched your search

+5 -3
View File
@@ -47,11 +47,13 @@ function View({ view, levels, onMuscle, selected }) {
/**
* <BodyMap load={{ chest: 12, … }} body="male" />
* `load` is effective sets per muscle (see lib/muscles.js); shading is relative to
* the hardest-worked muscle in that same load, so it always reads as a balance.
* the hardest-worked muscle in that same load, so it always reads as a balance. Pass ordered
* `{ at, level, exclusive? }` `thresholds` for a fixed absolute scale (recovery views use this
* to keep their semantic bands stable); omitting it preserves the balance behavior.
*/
export default function BodyMap({ load = {}, body = 'male', onMuscle, selected, className = '' }) {
export default function BodyMap({ load = {}, thresholds, body = 'male', onMuscle, selected, className = '' }) {
const paths = useBodyPaths()
const levels = levelsOf(load)
const levels = levelsOf(load, thresholds)
const g = paths && (paths[body] || paths.male)
return (
<div className={'bodymap ' + className}>
+12
View File
@@ -777,6 +777,18 @@ h4.sec{
.bm-m.l2{fill:color-mix(in srgb,var(--acc) 56%,var(--bm-base))}
.bm-m.l3{fill:color-mix(in srgb,var(--acc) 78%,var(--bm-base))}
.bm-m.l4{fill:var(--acc)}
/* Fatigue view: attention ramp - fatigued muscles highlighted (owner tweak 2026-08-06) */
.hm-fatigue .bm-m.l4{fill:var(--red)}
.hm-fatigue .bm-m.l3{fill:var(--orange)}
.hm-fatigue .bm-m.l2{fill:var(--yellow)}
.hm-fatigue .bm-m.l1{fill:color-mix(in srgb,var(--yellow) 32%,var(--bm-base))}
.hm-fatigue .hm-c.l4{background:var(--red)}
.hm-fatigue .hm-c.l3{background:var(--orange)}
.hm-fatigue .hm-c.l2{background:var(--yellow)}
/* Strength view: top band pops gold (owner tweak 2026-08-06) */
.hm-strength .bm-m.l4{fill:var(--yellow);filter:drop-shadow(0 0 1.5px var(--yellow))}
.hm-strength .hm-c.l4{background:var(--yellow)}
.bm-m.sel{stroke:var(--label);stroke-width:7}
.bodymap.tappable .bm-m{cursor:pointer}
/* A hairline in the surface colour separates neighbouring muscles; the artwork has no
+24 -4
View File
@@ -119,11 +119,31 @@ export const loadOfActive = active =>
loadOf((active?.entries || []).map(e => ({ id: e.id, sets: (e.sets || []).filter(s => s.done).length })))
/**
* Shade buckets 0–4 per muscle, relative to the hardest-worked muscle in the same
* window. Relative rather than absolute on purpose: the map answers "is my training
* balanced", which only means anything as a comparison within one period.
* Shade buckets 0–4 per muscle.
*
* With no `thresholds`, levels remain relative to the hardest-worked muscle in the same
* window. This is the original balance-map behavior. When `thresholds` is supplied, levels
* use an absolute scale instead: it is an ordered array of `{ at, level, exclusive? }` rules,
* and the last matching rule wins. An exclusive rule matches values strictly greater than
* `at`; otherwise the boundary is inclusive. Values below the first matching rule are l0.
* Absolute rules let recovery views keep fixed semantic bands instead of renormalizing to the
* strongest muscle on screen.
*/
export function levelsOf(load) {
export function levelsOf(load, thresholds) {
if (thresholds) {
const lv = {}
MUSCLES.forEach(m => {
const value = Number(load[m] || 0)
let level = 0
for (const rule of thresholds) {
const matches = rule.exclusive ? value > rule.at : value >= rule.at
if (matches) level = Math.max(0, Math.min(4, rule.level))
}
lv[m] = level
})
return lv
}
const max = Math.max(0, ...MUSCLES.map(m => load[m] || 0))
const lv = {}
MUSCLES.forEach(m => {
+17
View File
@@ -0,0 +1,17 @@
import { FATIGUE_STATES } from './recovery.js'
/**
* Select the consumer-facing fatigue state for one numeric recovery value.
* Values below .25 are ready, .25 through .5 are recovering, and values above .5 are fatigued.
* Keeping this boundary selector in production code prevents views and tests from drifting apart.
*
* @param {number} value Numeric fatigue value from fatigueOf().
* @returns {'ready'|'recovering'|'fatigued'} The stable state label for the UI.
*/
export function fatigueStateOf(value) {
return value < 0.25
? FATIGUE_STATES.READY
: value <= 0.5
? FATIGUE_STATES.RECOVERING
: FATIGUE_STATES.FATIGUED
}
+58
View File
@@ -0,0 +1,58 @@
import { describe, expect, it } from 'vitest'
import { FATIGUE_STATES, fatigueOf, strengthOf } from './recovery.js'
import { fatigueStateOf } from './recovery-view.js'
import { MUSCLES, levelsOf } from './muscles.js'
const FATIGUE_BANDS = [
{ at: 0, level: 4 },
{ at: 0.25, level: 2 },
{ at: 0.5, level: 0, exclusive: true },
]
const STRENGTH_BANDS = [
{ at: 0.5, level: 0 },
{ at: 0.625, level: 1 },
{ at: 0.75, level: 2 },
{ at: 0.875, level: 3 },
{ at: 1, level: 4 },
]
describe('production recovery view selectors', () => {
it('preserves the relative balance scale when no thresholds are supplied', () => {
const levels = levelsOf({ chest: 10, biceps: 5 })
expect(levels.chest).toBe(4)
expect(levels.biceps).toBe(2)
})
it('uses the production fatigue selector at both approved boundaries', () => {
expect(fatigueStateOf(0.2499)).toBe(FATIGUE_STATES.READY)
expect(fatigueStateOf(0.25)).toBe(FATIGUE_STATES.RECOVERING)
expect(fatigueStateOf(0.5)).toBe(FATIGUE_STATES.RECOVERING)
expect(fatigueStateOf(0.5001)).toBe(FATIGUE_STATES.FATIGUED)
})
it('renders fatigue bands on a fixed absolute scale rather than relative to the map maximum', () => {
const levels = levelsOf({
chest: 0.25,
biceps: 0.6,
triceps: 0.1,
}, FATIGUE_BANDS)
expect(levels.chest).toBe(2)
expect(levels.biceps).toBe(0)
expect(levels.triceps).toBe(4)
})
it('renders strength on fixed .5-to-1 bands with full retention at l4', () => {
const levels = levelsOf({ chest: 0.9, biceps: 1, triceps: 0.5 }, STRENGTH_BANDS)
expect(levels.chest).toBe(3)
expect(levels.biceps).toBe(4)
expect(levels.triceps).toBe(0)
})
it('keeps selectors tied to the same render-time clock', () => {
const now = Date.UTC(2026, 0, 22)
const workout = { start: now - 15 * 86400000, d: '2026-01-07', entries: [] }
expect(strengthOf([workout], now).chest).toBe(0.5)
expect(fatigueOf([workout], now).chest).toBe(0)
expect(strengthOf([workout], now + 7 * 86400000).chest).toBe(0.5)
})
})
+197
View File
@@ -0,0 +1,197 @@
import { EXIDX } from './exercises.js'
import { MUSCLES, musclesOf } from './muscles.js'
/** Completed-workout window used when calculating current fatigue. */
// A "normal" hard session for one muscle, in primary-set equivalents. The saturation curve
// 1 - exp(-stimulus / REF) maps any session size onto [0,1) so volume raises the starting
// fatigue level without ever pinning it, and the value can then fade asymptotically.
export const FATIGUE_REF_VOLUME = 3
// Computational bound for the stimulus scan, not a semantic cliff: after 30 days (20
// half-lives) a session contributes below 1e-6 to the accumulated value.
export const FATIGUE_SCAN_MS = 30 * 24 * 60 * 60 * 1000
/** Exponential half-life for fatigue stimulus. */
export const FATIGUE_HALF_LIFE_MS = 129600000
/** Period after training during which retained strength remains at full value. */
export const STRENGTH_FULL_MS = 1209600000
/** Exponential half-life for retained strength after the full-retention period. */
export const STRENGTH_HALF_LIFE_MS = 2419200000
/** Minimum retained-strength value for an untrained or fully detrained muscle. */
export const STRENGTH_FLOOR = 0.5
/**
* Stable labels for consumer fatigue buckets: values below 0.25 are ready, values from 0.25
* through 0.5 are recovering, and values above 0.5 are fatigued.
*/
export const FATIGUE_STATES = Object.freeze({
READY: 'ready',
RECOVERING: 'recovering',
FATIGUED: 'fatigued',
})
/**
* Return exponential decay expressed as a fraction of one half-life.
*
* @param {number} ageMs Elapsed age of the stimulus in milliseconds.
* @param {number} halfLifeMs Duration of one half-life in milliseconds.
* @returns {number} Remaining fraction, using the exact `0.5 ** (age / halfLife)` formula.
*/
export function halfLifeDecay(ageMs, halfLifeMs) {
return 0.5 ** (ageMs / halfLifeMs)
}
// The v2 data contract has one timestamp per workout, not per set. Keep this fallback in one
// place so fatigue and strength use exactly the same stimulus time as effort.js.
function workoutTimestamp(workout) {
const timestamp = workout?.start || new Date(workout?.d).getTime()
return Number.isFinite(timestamp) ? timestamp : Number(timestamp)
}
function emptyMuscleMap(value) {
return Object.fromEntries(MUSCLES.map(slug => [slug, value]))
}
function clamp(value, min, max) {
return Math.min(max, Math.max(min, value))
}
// Yield one weighted stimulus per completed set. Repeating the exercise's muscle weights for
// every done set is equivalent to multiplying musclesOf(ex) by the completed-set count while
// preserving the workout/set shape already used by the app.
function completedStimuli(workouts, include) {
const stimuli = []
for (const workout of workouts || []) {
const timestamp = workoutTimestamp(workout)
if (!Number.isFinite(timestamp) || !include(timestamp)) continue
for (const entry of workout.entries || []) {
const weights = musclesOf(EXIDX[entry.id])
for (const set of entry.sets || []) {
if (set?.done !== true) continue
for (const [slug, weight] of Object.entries(weights)) {
if (Object.prototype.hasOwnProperty.call(MUSCLES_BY_SLUG, slug)) {
stimuli.push({ slug, timestamp, stimulus: weight })
}
}
}
}
}
return stimuli
}
const MUSCLES_BY_SLUG = Object.fromEntries(MUSCLES.map(slug => [slug, true]))
function fatigueValue(events, now) {
if (!events.length) return 0
events.sort((a, b) => a.timestamp - b.timestamp)
let value = 0
let lastTimestamp = events[0].timestamp
for (const event of events) {
value *= halfLifeDecay(event.timestamp - lastTimestamp, FATIGUE_HALF_LIFE_MS)
value += event.stimulus
lastTimestamp = event.timestamp
}
value *= halfLifeDecay(now - lastTimestamp, FATIGUE_HALF_LIFE_MS)
// Normalise the accumulated stimulus to a saturating fatigue level: more volume starts
// higher but never pins, and the value fades asymptotically - no window-edge cliff.
return 1 - Math.exp(-value / FATIGUE_REF_VOLUME)
}
/**
* Calculate current per-muscle fatigue from completed sets in the recent window.
*
* Stimulus time is `workout.start`, falling back to the workout date `workout.d`. Each completed
* set contributes the exercise's `musclesOf` weights; the scan is bounded to FATIGUE_SCAN_MS for
* performance, not semantics. Stimuli are accumulated chronologically with a 36-hour half-life,
* decayed to `now`, and normalised with the saturation curve 1 - exp(-v / FATIGUE_REF_VOLUME).
* The result always contains every drawable muscle slug.
*
* @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.
* @returns {Record<string, number>} Fatigue values keyed by every drawable muscle slug.
*/
export function fatigueOf(workouts, now) {
const current = Number(now)
const cutoff = current - FATIGUE_SCAN_MS
const stimuli = completedStimuli(workouts, timestamp => timestamp > cutoff)
const byMuscle = Object.fromEntries(MUSCLES.map(slug => [slug, []]))
for (const stimulus of stimuli) byMuscle[stimulus.slug].push(stimulus)
const result = emptyMuscleMap(0)
if (!Number.isFinite(current)) return result
for (const slug of MUSCLES) result[slug] = fatigueValue(byMuscle[slug], current)
return result
}
/**
* Calculate retained per-muscle strength from the latest completed stimulus in all history.
*
* A muscle with no completed set starts at the 0.5 floor. After a completed set, strength is
* 1.0 through 14 days old, then decays toward the floor with a 28-day half-life. Any later
* completed set becomes the new latest stimulus and resets the 14-day full-retention period.
* The result always contains every drawable muscle slug.
*
* @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.
* @returns {Record<string, number>} Retained-strength values keyed by every drawable muscle slug.
*/
export function strengthOf(workouts, now) {
const current = Number(now)
const latest = Object.fromEntries(MUSCLES.map(slug => [slug, -Infinity]))
const stimuli = completedStimuli(workouts, () => true)
for (const stimulus of stimuli) {
if (stimulus.timestamp > latest[stimulus.slug]) latest[stimulus.slug] = stimulus.timestamp
}
const result = emptyMuscleMap(STRENGTH_FLOOR)
if (!Number.isFinite(current)) return result
for (const slug of MUSCLES) {
const lastTimestamp = latest[slug]
if (!Number.isFinite(lastTimestamp)) continue
const age = current - lastTimestamp
if (age <= STRENGTH_FULL_MS) {
result[slug] = 1
} else {
result[slug] = Math.max(
STRENGTH_FLOOR,
halfLifeDecay(age - STRENGTH_FULL_MS, STRENGTH_HALF_LIFE_MS),
)
}
}
return result
}
/**
* List muscles currently above the fatigued threshold.
*
* @param {Array<object>} workouts Workout history passed to {@link fatigueOf}.
* @param {number} now Current time in milliseconds passed to {@link fatigueOf}.
* @returns {string[]} Muscle slugs whose fatigue value is greater than 0.5, in `MUSCLES`
* head-to-toe order.
* @example
* const avoid = fatiguedMuscles(workouts, now)
*/
export function fatiguedMuscles(workouts, now) {
return Object.entries(fatigueOf(workouts, now))
.filter(([, value]) => value > 0.5)
.map(([slug]) => slug)
}
/**
* List muscles whose retained strength is below full retention.
*
* @param {Array<object>} workouts Workout history passed to {@link strengthOf}.
* @param {number} now Current time in milliseconds passed to {@link strengthOf}.
* @returns {string[]} Muscle slugs whose retained strength is less than 1.0, in `MUSCLES`
* head-to-toe order; never-trained muscles are included at the 0.5 floor.
* @example
* const targets = detrainedMuscles(workouts, now)
*/
export function detrainedMuscles(workouts, now) {
return Object.entries(strengthOf(workouts, now))
.filter(([, value]) => value < 1)
.map(([slug]) => slug)
}
+242
View File
@@ -0,0 +1,242 @@
import { describe, expect, it } from 'vitest'
import {
FATIGUE_HALF_LIFE_MS,
FATIGUE_REF_VOLUME,
FATIGUE_SCAN_MS,
FATIGUE_STATES,
STRENGTH_FLOOR,
STRENGTH_FULL_MS,
STRENGTH_HALF_LIFE_MS,
detrainedMuscles,
fatiguedMuscles,
fatigueOf,
halfLifeDecay,
strengthOf,
} from './recovery.js'
import { EXDB } from './exercises.js'
import { MUSCLES, musclesOf } from './muscles.js'
import { fatigueStateOf } from './recovery-view.js'
const HOUR = 60 * 60 * 1000
const DAY = 24 * HOUR
const NOW = Date.UTC(2026, 0, 1, 12)
// Keep fixtures tied to the shipped catalogue while making the expected stimulus explicit.
const SINGLE = EXDB.find(ex => {
const weights = musclesOf(ex)
return ex.bp !== 'cardio' && Object.keys(weights).length === 1 && Object.values(weights)[0] === 1
})
const WEIGHTED = EXDB.find(ex => {
const weights = musclesOf(ex)
return ex.bp !== 'cardio' && Object.values(weights).includes(0.4)
})
if (!SINGLE || !WEIGHTED) throw new Error('recovery tests require single- and secondary-weight fixtures')
const SINGLE_WEIGHTS = musclesOf(SINGLE)
const WEIGHTED_WEIGHTS = musclesOf(WEIGHTED)
const SINGLE_SLUG = Object.keys(SINGLE_WEIGHTS)[0]
const WEIGHTED_PRIMARY_SLUG = Object.keys(WEIGHTED_WEIGHTS).find(slug => WEIGHTED_WEIGHTS[slug] === 1)
const SECONDARY_SLUG = Object.keys(WEIGHTED_WEIGHTS).find(slug => WEIGHTED_WEIGHTS[slug] === 0.4)
if (!WEIGHTED_PRIMARY_SLUG || !SECONDARY_SLUG) throw new Error('recovery tests require weighted primary and secondary fixtures')
const workoutAt = (id, start, sets = [{ done: true }]) => ({
d: new Date(start).toISOString(),
start,
entries: [{ id, sets: sets.map(set => ({ ...set })) }],
})
const doneWorkoutAt = (id, start, count = 1) =>
workoutAt(id, start, Array.from({ length: count }, () => ({ done: true })))
const zeroFatigue = () => Object.fromEntries(MUSCLES.map(slug => [slug, 0]))
const floorStrength = () => Object.fromEntries(MUSCLES.map(slug => [slug, STRENGTH_FLOOR]))
// Numeric fatigue remains the math API; the UI boundary selector is imported from production.
const stableFloat = value => Number(value.toFixed(12))
describe('recovery constants', () => {
it('exports the pinned windows, half-lives, floor, and state labels', () => {
expect(FATIGUE_REF_VOLUME).toBe(3)
expect(FATIGUE_SCAN_MS).toBe(30 * DAY)
expect(FATIGUE_HALF_LIFE_MS).toBe(36 * HOUR)
expect(STRENGTH_FULL_MS).toBe(14 * DAY)
expect(STRENGTH_HALF_LIFE_MS).toBe(28 * DAY)
expect(STRENGTH_FLOOR).toBe(0.5)
expect(FATIGUE_STATES).toEqual({ READY: 'ready', RECOVERING: 'recovering', FATIGUED: 'fatigued' })
expect(halfLifeDecay(FATIGUE_HALF_LIFE_MS, FATIGUE_HALF_LIFE_MS)).toBe(0.5)
})
})
describe('fatigueOf and strengthOf', () => {
it('returns every muscle, ready/floor defaults, and hook defaults for empty history', () => {
const fatigue = fatigueOf([], NOW)
const strength = strengthOf([], NOW)
expect(Object.keys(fatigue)).toEqual(MUSCLES)
expect(fatigue).toEqual(zeroFatigue())
expect(Object.values(fatigue).map(fatigueStateOf)).toEqual(
MUSCLES.map(() => FATIGUE_STATES.READY),
)
expect(Object.keys(strength)).toEqual(MUSCLES)
expect(strength).toEqual(floorStrength())
expect(fatiguedMuscles([], NOW)).toEqual([])
expect(detrainedMuscles([], NOW)).toEqual(MUSCLES)
})
it('applies one completed set to each of the exercise muscle weights', () => {
const workouts = [doneWorkoutAt(WEIGHTED.id, NOW)]
const fatigue = fatigueOf(workouts, NOW)
const strength = strengthOf(workouts, NOW)
for (const slug of MUSCLES) {
const weight = WEIGHTED_WEIGHTS[slug] || 0
expect(fatigue[slug]).toBeCloseTo(1 - Math.exp(-weight / FATIGUE_REF_VOLUME), 10)
expect(strength[slug]).toBe(weight ? 1 : STRENGTH_FLOOR)
}
// one set never crosses the fatigued threshold on the saturating curve
expect(fatiguedMuscles(workouts, NOW)).toEqual([])
})
it('raises starting fatigue with volume, never pins, and fades without a cliff', () => {
const at0 = count => fatigueOf([doneWorkoutAt(SINGLE.id, NOW, count)], NOW)[SINGLE_SLUG]
expect(at0(1)).toBeCloseTo(1 - Math.exp(-1 / FATIGUE_REF_VOLUME), 10)
expect(at0(5)).toBeCloseTo(1 - Math.exp(-5 / FATIGUE_REF_VOLUME), 10)
expect(at0(12)).toBeCloseTo(1 - Math.exp(-12 / FATIGUE_REF_VOLUME), 10)
expect(at0(12)).toBeGreaterThan(at0(5))
expect(at0(5)).toBeGreaterThan(at0(1))
expect(at0(12)).toBeLessThan(1)
// one half-life later the gradient is still visible at any volume
const later = fatigueOf([doneWorkoutAt(SINGLE.id, NOW - FATIGUE_HALF_LIFE_MS, 12)], NOW)[SINGLE_SLUG]
expect(later).toBeCloseTo(1 - Math.exp(-6 / FATIGUE_REF_VOLUME), 10)
expect(later).toBeLessThan(at0(12))
// no cliff: 72h keeps decaying instead of snapping to zero
const old = fatigueOf([doneWorkoutAt(SINGLE.id, NOW - 72 * HOUR)], NOW)[SINGLE_SLUG]
expect(old).toBeGreaterThan(0)
expect(old).toBeLessThan(0.25)
})
it('decays each weighted stimulus exactly at 36 hours and by sqrt-half at 18 hours', () => {
for (const age of [FATIGUE_HALF_LIFE_MS, FATIGUE_HALF_LIFE_MS / 2]) {
const fatigue = fatigueOf([doneWorkoutAt(WEIGHTED.id, NOW - age)], NOW)
const expectedDecay = 0.5 ** (age / FATIGUE_HALF_LIFE_MS)
for (const [slug, weight] of Object.entries(WEIGHTED_WEIGHTS)) {
expect(fatigue[slug]).toBeCloseTo(1 - Math.exp(-weight * expectedDecay / FATIGUE_REF_VOLUME), 10)
}
if (age === FATIGUE_HALF_LIFE_MS) {
expect(fatigue[WEIGHTED_PRIMARY_SLUG]).toBeCloseTo(1 - Math.exp(-0.5 / FATIGUE_REF_VOLUME), 10)
}
if (age === FATIGUE_HALF_LIFE_MS / 2) {
expect(fatigue[WEIGHTED_PRIMARY_SLUG]).toBeCloseTo(1 - Math.exp(-(0.5 ** 0.5) / FATIGUE_REF_VOLUME), 10)
}
}
})
it('fades a 72-hour-old set below the ready threshold instead of hard-cutting', () => {
const workouts = [doneWorkoutAt(SINGLE.id, NOW - 72 * HOUR)]
const value = fatigueOf(workouts, NOW)[SINGLE_SLUG]
expect(value).toBeGreaterThan(0)
expect(value).toBeLessThan(0.25)
expect(fatigueStateOf(value)).toBe(FATIGUE_STATES.READY)
expect(strengthOf(workouts, NOW)[SINGLE_SLUG]).toBe(1)
})
it('ignores sets whose done flag is false for both axes', () => {
const workouts = [workoutAt(WEIGHTED.id, NOW, [{ done: false }])]
expect(fatigueOf(workouts, NOW)).toEqual(zeroFatigue())
expect(strengthOf(workouts, NOW)).toEqual(floorStrength())
expect(fatiguedMuscles(workouts, NOW)).toEqual([])
expect(detrainedMuscles(workouts, NOW)).toEqual(MUSCLES)
})
})
describe('fatigue state boundaries', () => {
// Inverse of the saturation curve: raw stimulus needed to land exactly on a target level.
const rawAt = target => -FATIGUE_REF_VOLUME * Math.log(1 - target)
it('classifies exactly .25 as recovering and .2499 as ready', () => {
const weight = WEIGHTED_WEIGHTS[SECONDARY_SLUG]
const sets = 3
const valueAt = target => {
const age = FATIGUE_HALF_LIFE_MS * Math.log2(sets * weight / rawAt(target))
const value = fatigueOf([doneWorkoutAt(WEIGHTED.id, NOW - age, sets)], NOW)[SECONDARY_SLUG]
expect(value).toBeCloseTo(target, 10)
return stableFloat(value)
}
expect(fatigueStateOf(valueAt(0.25))).toBe(FATIGUE_STATES.RECOVERING)
expect(fatigueStateOf(valueAt(0.2499))).toBe(FATIGUE_STATES.READY)
})
it('classifies exactly .5 as recovering, .5001 as fatigued, and hooks only fatigued muscles', () => {
const sets = 3
const atHalf = [doneWorkoutAt(SINGLE.id, NOW - FATIGUE_HALF_LIFE_MS * Math.log2(sets / rawAt(0.4999)), sets)]
const aboveHalf = [
doneWorkoutAt(SINGLE.id, NOW - FATIGUE_HALF_LIFE_MS * Math.log2(sets / rawAt(0.5001)), sets),
]
const half = fatigueOf(atHalf, NOW)[SINGLE_SLUG]
const above = fatigueOf(aboveHalf, NOW)[SINGLE_SLUG]
expect(half).toBeCloseTo(0.4999, 10)
expect(fatigueStateOf(stableFloat(half))).toBe(FATIGUE_STATES.RECOVERING)
expect(fatiguedMuscles(atHalf, NOW)).toEqual([])
expect(above).toBeCloseTo(0.5001, 10)
expect(fatigueStateOf(stableFloat(above))).toBe(FATIGUE_STATES.FATIGUED)
expect(fatiguedMuscles(aboveHalf, NOW)).toEqual([SINGLE_SLUG])
})
})
describe('strengthOf', () => {
const strengthAt = age => strengthOf([doneWorkoutAt(SINGLE.id, NOW - age)], NOW)[SINGLE_SLUG]
it('stays at full retention through 14 days and decays from 15 days by the 28-day half-life', () => {
expect(strengthAt(STRENGTH_FULL_MS)).toBe(1)
expect(strengthAt(15 * DAY)).toBeCloseTo(0.5 ** (1 / 28), 10)
})
it('clamps the 42-day half-life point and later 56-day value at the .5 floor', () => {
expect(strengthAt(42 * DAY)).toBe(0.5)
expect(strengthAt(56 * DAY)).toBe(STRENGTH_FLOOR)
})
it('resets retained strength when a later completed session retrains the muscle', () => {
const workouts = [
doneWorkoutAt(SINGLE.id, NOW - 20 * DAY),
doneWorkoutAt(SINGLE.id, NOW),
]
expect(strengthOf(workouts, NOW)[SINGLE_SLUG]).toBe(1)
})
})
describe('accumulation and purity', () => {
it('matches the saturated sum of independently decayed stimuli in chronological order', () => {
const ages = [64 * HOUR, 40 * HOUR]
const workouts = ages.map(age => doneWorkoutAt(SINGLE.id, NOW - age))
const raw = ages.reduce(
(sum, age) => sum + 0.5 ** (age / FATIGUE_HALF_LIFE_MS),
0,
)
const expected = 1 - Math.exp(-raw / FATIGUE_REF_VOLUME)
expect(raw).toBeLessThan(FATIGUE_REF_VOLUME)
expect(fatigueOf(workouts, NOW)[SINGLE_SLUG]).toBeCloseTo(expected, 10)
expect(fatigueOf([...workouts].reverse(), NOW)[SINGLE_SLUG]).toBeCloseTo(expected, 10)
})
it('saturates without pinning and returns identical results without mutating inputs or sharing state', () => {
const saturated = [doneWorkoutAt(SINGLE.id, NOW, 2)]
expect(fatigueOf(saturated, NOW)[SINGLE_SLUG]).toBeCloseTo(1 - Math.exp(-2 / FATIGUE_REF_VOLUME), 10)
expect(fatigueOf(saturated, NOW)[SINGLE_SLUG]).toBeLessThan(1)
const workouts = [
doneWorkoutAt(SINGLE.id, NOW - 64 * HOUR),
doneWorkoutAt(SINGLE.id, NOW - 40 * HOUR),
]
const before = JSON.parse(JSON.stringify(workouts))
const firstFatigue = fatigueOf(workouts, NOW)
const firstStrength = strengthOf(workouts, NOW)
const secondFatigue = fatigueOf(workouts, NOW)
const secondStrength = strengthOf(workouts, NOW)
expect(secondFatigue).toEqual(firstFatigue)
expect(secondStrength).toEqual(firstStrength)
expect(workouts).toEqual(before)
})
})
+9
View File
@@ -379,6 +379,15 @@ export default {
'Admin dashboard': 'Admin-Dashboard',
// --- muscle map ---
'Muscle balance': 'Muskelbalance',
'Fatigue': 'Ermüdung',
'Ready': 'Bereit',
'Recovering': 'In Erholung',
'Fatigued': 'Ermüdet',
'Fatigue shows how recently each muscle was trained. High means rest.': 'Die Ermüdung zeigt, wie lange das Training jedes Muskels zurückliegt. Ein hoher Wert bedeutet: Pause.',
'Strength shows retained muscle strength. Train again to reset it.': 'Die Kraft zeigt, wie viel Muskelkraft erhalten ist. Trainiere erneut, um sie zurückzusetzen.',
'full': 'voll',
'floor': 'Minimum',
'Weeks since training: {0}': 'Zuletzt vor {0} Wo. trainiert',
'by sets worked': 'nach Sätzen',
'Week': 'Woche',
'not trained': 'nicht trainiert',
+9
View File
@@ -361,6 +361,15 @@ export default {
'Admin dashboard': 'Panel de administración',
// --- muscle map ---
'Muscle balance': 'Equilibrio muscular',
'Fatigue': 'Fatiga',
'Ready': 'Listo',
'Recovering': 'En recuperación',
'Fatigued': 'Fatigado',
'Fatigue shows how recently each muscle was trained. High means rest.': 'La fatiga indica cuánto tiempo ha pasado desde el último entrenamiento de cada músculo. Un valor alto indica que toca descansar.',
'Strength shows retained muscle strength. Train again to reset it.': 'La fuerza muestra cuánta fuerza muscular se conserva. Vuelve a entrenar para restablecerla.',
'full': 'completo',
'floor': 'mínimo',
'Weeks since training: {0}': 'Último entrenamiento: hace {0} sem.',
'by sets worked': 'por series trabajadas',
'Week': 'Semana',
'not trained': 'sin entrenar',
+9
View File
@@ -361,6 +361,15 @@ export default {
'Admin dashboard': 'Tableau d’administration',
// --- muscle map ---
'Muscle balance': 'Équilibre musculaire',
'Fatigue': 'Fatigue',
'Ready': 'Prêt',
'Recovering': 'En récupération',
'Fatigued': 'Fatigué',
'Fatigue shows how recently each muscle was trained. High means rest.': 'La fatigue indique à quand remonte le dernier entraînement de chaque muscle. Un niveau élevé signifie qu’il est temps de se reposer.',
'Strength shows retained muscle strength. Train again to reset it.': 'La force indique combien de force musculaire est conservée. Entraîne-toi à nouveau pour la réinitialiser.',
'full': 'complet',
'floor': 'plancher',
'Weeks since training: {0}': 'Dernier entraînement : il y a {0} sem.',
'by sets worked': 'par séries effectuées',
'Week': 'Semaine',
'not trained': 'non travaillé',
+9
View File
@@ -361,6 +361,15 @@ export default {
'Admin dashboard': 'एडमिन डैशबोर्ड',
// --- muscle map ---
'Muscle balance': 'मांसपेशी संतुलन',
'Fatigue': 'थकान',
'Ready': 'तैयार',
'Recovering': 'पुनर्प्राप्ति में',
'Fatigued': 'थकी हुई',
'Fatigue shows how recently each muscle was trained. High means rest.': 'थकान बताती है कि हर मांसपेशी की ट्रेनिंग कितनी हाल की है। अधिक थकान होने पर आराम करें।',
'Strength shows retained muscle strength. Train again to reset it.': 'शक्ति बताती है कि मांसपेशियों की कितनी ताकत बनी हुई है। इसे रीसेट करने के लिए फिर से ट्रेन करें।',
'full': 'पूर्ण',
'floor': 'न्यूनतम',
'Weeks since training: {0}': 'पिछला व्यायाम: {0} सप्ताह पहले',
'by sets worked': 'सेट के अनुसार',
'Week': 'सप्ताह',
'not trained': 'प्रशिक्षित नहीं',
+9
View File
@@ -361,6 +361,15 @@ export default {
'Admin dashboard': 'Pannello di amministrazione',
// --- muscle map ---
'Muscle balance': 'Equilibrio muscolare',
'Fatigue': 'Fatica',
'Ready': 'Pronto',
'Recovering': 'In recupero',
'Fatigued': 'Affaticato',
'Fatigue shows how recently each muscle was trained. High means rest.': 'La fatica mostra quanto è recente l’allenamento di ogni muscolo. Un valore alto significa che serve riposo.',
'Strength shows retained muscle strength. Train again to reset it.': 'La forza mostra quanta forza muscolare hai mantenuto. Allenati di nuovo per reimpostarla.',
'full': 'pieno',
'floor': 'minimo',
'Weeks since training: {0}': 'Ultimo allenamento: {0} sett. fa',
'by sets worked': 'per serie svolte',
'Week': 'Settimana',
'not trained': 'non allenato',
+9
View File
@@ -361,6 +361,15 @@ export default {
'Admin dashboard': '관리자 대시보드',
// --- muscle map ---
'Muscle balance': '근육 균형',
'Fatigue': '피로',
'Ready': '준비됨',
'Recovering': '회복 중',
'Fatigued': '피로함',
'Fatigue shows how recently each muscle was trained. High means rest.': '피로도는 각 근육을 얼마나 최근에 운동했는지 보여줍니다. 높을수록 휴식이 필요합니다.',
'Strength shows retained muscle strength. Train again to reset it.': '근력은 근육에 남아 있는 힘을 보여줍니다. 다시 운동하면 값이 초기화됩니다.',
'full': '완전',
'floor': '최소',
'Weeks since training: {0}': '마지막 운동: {0}주 전',
'by sets worked': '세트 수 기준',
'Week': '이번 주',
'not trained': '훈련 안 함',
+9
View File
@@ -361,6 +361,15 @@ export default {
'Admin dashboard': 'Panel administratora',
// --- muscle map ---
'Muscle balance': 'Równowaga mięśniowa',
'Fatigue': 'Zmęczenie',
'Ready': 'Gotowe',
'Recovering': 'W regeneracji',
'Fatigued': 'Zmęczony',
'Fatigue shows how recently each muscle was trained. High means rest.': 'Zmęczenie pokazuje, jak niedawno trenowano każdą partię mięśni. Wysoki poziom oznacza potrzebę odpoczynku.',
'Strength shows retained muscle strength. Train again to reset it.': 'Siła pokazuje, ile siły mięśniowej pozostało. Ponowny trening przywraca jej poziom wyjściowy.',
'full': 'pełna',
'floor': 'minimum',
'Weeks since training: {0}': 'Trening: {0} tyg. temu',
'by sets worked': 'wg serii',
'Week': 'Tydzień',
'not trained': 'nietrenowane',
+9
View File
@@ -361,6 +361,15 @@ export default {
'Admin dashboard': 'Painel de administração',
// --- muscle map ---
'Muscle balance': 'Equilíbrio muscular',
'Fatigue': 'Fadiga',
'Ready': 'Pronto',
'Recovering': 'Em recuperação',
'Fatigued': 'Fatigado',
'Fatigue shows how recently each muscle was trained. High means rest.': 'A fadiga mostra há quanto tempo cada músculo foi treinado. Um nível elevado significa que é preciso descansar.',
'Strength shows retained muscle strength. Train again to reset it.': 'A força mostra quanta força muscular se mantém. Treina novamente para repor o valor.',
'full': 'completo',
'floor': 'mínimo',
'Weeks since training: {0}': 'Treino: há {0} sem.',
'by sets worked': 'por séries trabalhadas',
'Week': 'Semana',
'not trained': 'sem treino',
+9
View File
@@ -361,6 +361,15 @@ export default {
'Admin dashboard': 'Панель администратора',
// --- muscle map ---
'Muscle balance': 'Баланс мышц',
'Fatigue': 'Усталость',
'Ready': 'Готова',
'Recovering': 'Восстанавливается',
'Fatigued': 'Утомлена',
'Fatigue shows how recently each muscle was trained. High means rest.': 'Усталость показывает, насколько недавно тренировалась каждая мышца. Высокий уровень означает, что пора отдохнуть.',
'Strength shows retained muscle strength. Train again to reset it.': 'Сила показывает, сколько мышечной силы сохранилось. Повторная тренировка сбрасывает это значение.',
'full': 'полная',
'floor': 'минимум',
'Weeks since training: {0}': 'Тренировка: {0} нед. назад',
'by sets worked': 'по подходам',
'Week': 'Неделя',
'not trained': 'не тренировалась',
+9
View File
@@ -361,6 +361,15 @@ export default {
'Admin dashboard': 'Yönetici paneli',
// --- muscle map ---
'Muscle balance': 'Kas dengesi',
'Fatigue': 'Yorgunluk',
'Ready': 'Hazır',
'Recovering': 'Toparlanıyor',
'Fatigued': 'Yorgun',
'Fatigue shows how recently each muscle was trained. High means rest.': 'Yorgunluk, her kasın ne kadar süre önce çalıştırıldığını gösterir. Yüksek değer dinlenmek gerektiği anlamına gelir.',
'Strength shows retained muscle strength. Train again to reset it.': 'Kuvvet, kas gücünün ne kadarının korunduğunu gösterir. Yeniden çalışarak değeri sıfırlayabilirsin.',
'full': 'tam',
'floor': 'minimum',
'Weeks since training: {0}': 'Son antrenman: {0} hafta önce',
'by sets worked': 'çalışılan sete göre',
'Week': 'Hafta',
'not trained': 'çalışılmadı',
+9
View File
@@ -361,6 +361,15 @@ export default {
'Admin dashboard': '管理后台',
// --- muscle map ---
'Muscle balance': '肌肉平衡',
'Fatigue': '疲劳',
'Ready': '准备好',
'Recovering': '恢复中',
'Fatigued': '已疲劳',
'Fatigue shows how recently each muscle was trained. High means rest.': '疲劳度显示每个肌群最近一次训练距今多久。数值越高,越需要休息。',
'Strength shows retained muscle strength. Train again to reset it.': '力量显示肌肉力量保留了多少。再次训练即可重置。',
'full': '完全',
'floor': '下限',
'Weeks since training: {0}': '上次训练:{0}周前',
'by sets worked': '按训练组数',
'Week': '本周',
'not trained': '未训练',
+156 -30
View File
@@ -1,4 +1,4 @@
import { useState } from 'react'
import { useEffect, useMemo, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { useStore } from '../store/useStore.js'
import { EXIDX } from '../lib/exercises.js'
@@ -10,7 +10,9 @@ import LineChart from '../components/LineChart.jsx'
import Heatmap from '../components/Heatmap.jsx'
import Icon from '../components/Icon.jsx'
import BodyMap, { BodyMapLegend } from '../components/BodyMap.jsx'
import { loadOfWorkouts, rankOf, MUSCLE_NAME } from '../lib/muscles.js'
import { loadOfWorkouts, rankOf, MUSCLE_NAME, musclesOf } from '../lib/muscles.js'
import { fatigueOf, strengthOf, STRENGTH_FLOOR } from '../lib/recovery.js'
import { fatigueStateOf } from '../lib/recovery-view.js'
import { e1rmSeries, best1RM } from '../lib/onerm.js'
import {
hasEffort, displayScale, scaleName, toScale, avgRir, effortSummary, effortWeeks,
@@ -20,11 +22,95 @@ import { Button, Segmented, SelectRow } from '../components/ui.jsx'
// Which muscles the training in a window actually hit — and, the point of the card,
// which ones it keeps missing. Shading is relative within the window (lib/muscles.js).
function latestMuscleTraining(workouts) {
const latest = {}
for (const workout of workouts || []) {
const timestamp = Number(workout?.start || new Date(workout?.d).getTime())
if (!Number.isFinite(timestamp)) continue
for (const entry of workout.entries || []) {
if (!(entry.sets || []).some(set => set?.done === true)) continue
for (const slug of Object.keys(musclesOf(EXIDX[entry.id]))) {
if (latest[slug] == null || timestamp > latest[slug]) latest[slug] = timestamp
}
}
}
return latest
}
const FATIGUE_LEVELS = [
{ at: 0, level: 0 },
{ at: 0.15, level: 1 },
{ at: 0.25, level: 2 },
{ at: 0.4, level: 3 },
{ at: 0.55, level: 4, exclusive: true },
]
const STRENGTH_LEVELS = [
{ at: STRENGTH_FLOOR, level: 0 },
{ at: 0.625, level: 1 },
{ at: 0.75, level: 2 },
{ at: 0.875, level: 3 },
{ at: 1, level: 4 },
]
function useNow() {
const [, setTick] = useState(0)
useEffect(() => {
const iv = setInterval(() => setTick(tick => tick + 1), 60000)
return () => clearInterval(iv)
}, [])
return Date.now()
}
/**
* Return the whole weeks since a completed muscle-training timestamp.
*
* @param {number} now Current render-time timestamp in milliseconds.
* @param {number} lastTrained Timestamp of the latest completed training event.
* @returns {number} Non-negative whole weeks, including zero for ages under seven days.
*/
export function weeksSinceTraining(now, lastTrained) {
return Math.max(0, Math.floor((now - lastTrained) / 86400000 / 7))
}
function FatigueLegend() {
return <div className="hm-legend hm-fatigue" aria-label={t('Fatigue')}>
<span>{t('Fatigued')}</span><div className="hm-c l4" />
<span>{t('Recovering')}</span><div className="hm-c l2" />
<span>{t('Ready')}</span><div className="hm-c l0" />
</div>
}
function StrengthLegend() {
return <div className="hm-legend hm-strength" aria-label={t('Strength')}>
<span>1 <span className="dim">{t('full')}</span></span><div className="hm-c l4" /><div className="hm-c l3" /><div className="hm-c l2" />
<div className="hm-c l1" /><div className="hm-c l0" /><span>{fmtNum(STRENGTH_FLOOR)} <span className="dim">{t('floor')}</span></span>
</div>
}
function fatigueLabel(value) {
const state = fatigueStateOf(value)
return t(state === 'ready' ? 'Ready' : state === 'recovering' ? 'Recovering' : 'Fatigued')
}
function MuscleBalance({ S }) {
const [view, setView] = useState('balance')
const [win, setWin] = useState(7)
const [hard, setHard] = useState(false)
const [sel, setSel] = useState(null)
const now = Date.now()
const now = useNow()
const workouts = S.workouts
const fatigue = useMemo(() => fatigueOf(workouts, now), [workouts, now])
const strength = useMemo(() => strengthOf(workouts, now), [workouts, now])
const lastTrained = useMemo(() => latestMuscleTraining(workouts), [workouts])
const { worked: strengthOrder } = rankOf(strength)
const detrained = strengthOrder.filter(slug => strength[slug] < 1)
const strengthHint = slug => {
if (lastTrained[slug] == null) return t('not trained')
const weeks = weeksSinceTraining(now, lastTrained[slug])
return t('Weeks since training: {0}', weeks)
}
const toggleSel = m => setSel(s => (s === m ? null : m))
const inWin = S.workouts.filter(w =>
win === 0 ? true
: win === 7 ? weekKey(w.d) === weekKey(todayISO())
@@ -36,41 +122,66 @@ function MuscleBalance({ S }) {
const rated = inWin.some(w => w.entries.some(e => e.sets.some(s => s.done && isHardSet(s))))
const on = hard && rated
const load = loadOfWorkouts(inWin, on ? isHardSet : null)
const volWin = S.workouts.filter(w => (w.start || new Date(w.d).getTime()) > now - 90 * 86400000)
const vol90 = loadOfWorkouts(volWin, null)
const { worked, missed } = rankOf(load)
const top = worked.slice(0, 4)
const max = worked.length ? load[worked[0]] : 0
const sets = m => Math.round((load[m] || 0) * 10) / 10
return <div className="card">
<div className="row between" style={{ marginBottom: 8 }}>
<h2 style={{ margin: 0 }}>{t('Muscle balance')} <span className="dim" style={{ textTransform: 'none', letterSpacing: 0 }}>· {on ? t('by hard sets') : t('by sets worked')}</span></h2>
{rated && <Button size="sm" icon="flame" style={on ? { color: 'var(--yellow)' } : undefined}
onClick={() => { setHard(h => !h); setSel(null) }}>{on ? t('Hard') : t('All')}</Button>}
</div>
<Segmented className="seg-range" value={win} onChange={v => { setWin(v); setSel(null) }}
options={[{ value: 7, label: t('Week') }, { value: 30, label: '30d' }, { value: 90, label: '90d' }, { value: 0, label: t('All') }]} />
{inWin.length ? <>
<BodyMap className="tappable" load={load} body={S.body} selected={sel}
onMuscle={m => setSel(s => (s === m ? null : m))} />
<BodyMapLegend />
<Segmented className="seg-range" value={view} onChange={setView}
options={[{ value: 'balance', label: t('Muscle balance') }, { value: 'fatigue', label: t('Fatigue') }, { value: 'strength', label: t('Strength') }]} />
{view === 'balance' ? <>
<div className="row between" style={{ marginBottom: 8 }}>
<h2 style={{ margin: 0 }}>{t('Muscle balance')} <span className="dim" style={{ textTransform: 'none', letterSpacing: 0 }}>· {on ? t('by hard sets') : t('by sets worked')}</span></h2>
{rated && <Button size="sm" icon="flame" style={on ? { color: 'var(--yellow)' } : undefined}
onClick={() => { setHard(h => !h); setSel(null) }}>{on ? t('Hard') : t('All')}</Button>}
</div>
<Segmented className="seg-range" value={win} onChange={v => { setWin(v); setSel(null) }}
options={[{ value: 7, label: t('Week') }, { value: 30, label: '30d' }, { value: 90, label: '90d' }, { value: 0, label: t('All') }]} />
{inWin.length ? <>
<BodyMap className="tappable" load={load} body={S.body} selected={sel}
onMuscle={m => setSel(s => (s === m ? null : m))} />
<BodyMapLegend />
{sel && <div className="mrow" style={{ borderTop: 'var(--hair) solid var(--sep)', marginTop: 4, paddingTop: 10 }}>
<span className="nm"><b>{t(MUSCLE_NAME[sel])}</b></span>
<span className="v">{sets(sel) ? t('{0} sets', sets(sel)) : on ? t('no hard sets') : t('not trained')}</span>
</div>}
{!sel && top.map(m => <div key={m} className="mrow">
<span className="nm">{t(MUSCLE_NAME[m])}</span>
<span className="bar"><i style={{ width: Math.round(load[m] / max * 100) + '%', background: on ? 'var(--yellow)' : undefined }} /></span>
<span className="v">{t('{0} sets', sets(m))}</span>
</div>)}
{missed.length > 0 && <>
<h4 className="sec" style={{ marginTop: 12 }}>{on ? t('No hard sets in this period') : t('Not trained in this period')}</h4>
<div className="mchips">{missed.map(m => <span key={m} className="mchip miss">{t(MUSCLE_NAME[m])}</span>)}</div>
</>}
{!missed.length && worked.length > 0 &&
<div className="muted small" style={{ marginTop: 10 }}>{on
? t('Every muscle group got at least one hard set in this period.')
: t('Every muscle group got some work in this period.')}</div>}
</> : <div className="muted small">{t('No workouts in this period yet.')}</div>}
</> : view === 'fatigue' ? <>
<h2>{t('Fatigue')}</h2>
<BodyMap className="tappable hm-fatigue" load={fatigue} thresholds={FATIGUE_LEVELS} body={S.body} selected={sel} onMuscle={toggleSel} />
<FatigueLegend />
<div className="muted small" style={{ marginTop: 10 }}>{t('Fatigue shows how recently each muscle was trained. High means rest.')}</div>
{sel && <div className="mrow" style={{ borderTop: 'var(--hair) solid var(--sep)', marginTop: 4, paddingTop: 10 }}>
<span className="nm"><b>{t(MUSCLE_NAME[sel])}</b></span>
<span className="v">{sets(sel) ? t('{0} sets', sets(sel)) : on ? t('no hard sets') : t('not trained')}</span>
<span className="v">{fatigueLabel(fatigue[sel])}</span>
</div>}
{!sel && top.map(m => <div key={m} className="mrow">
<span className="nm">{t(MUSCLE_NAME[m])}</span>
<span className="bar"><i style={{ width: Math.round(load[m] / max * 100) + '%', background: on ? 'var(--yellow)' : undefined }} /></span>
<span className="v">{t('{0} sets', sets(m))}</span>
</> : <>
<h2>{t('Strength')}</h2>
<BodyMap className="tappable hm-strength" load={strength} thresholds={STRENGTH_LEVELS} body={S.body} selected={sel} onMuscle={toggleSel} />
<StrengthLegend />
<div className="muted small" style={{ marginTop: 10 }}>{t('Strength shows retained muscle strength. Train again to reset it.')}</div>
{detrained.map(slug => <div key={slug} className="mrow">
<span className="nm">{t(MUSCLE_NAME[slug])}</span>
<span className="bar"><i style={{ width: Math.round(strength[slug] * 100) + '%' }} /></span>
<span className="v">{t('{0} sets', vol90[slug] || 0)}</span>
</div>)}
{missed.length > 0 && <>
<h4 className="sec" style={{ marginTop: 12 }}>{on ? t('No hard sets in this period') : t('Not trained in this period')}</h4>
<div className="mchips">{missed.map(m => <span key={m} className="mchip miss">{t(MUSCLE_NAME[m])}</span>)}</div>
</>}
{!missed.length && worked.length > 0 &&
<div className="muted small" style={{ marginTop: 10 }}>{on
? t('Every muscle group got at least one hard set in this period.')
: t('Every muscle group got some work in this period.')}</div>}
</> : <div className="muted small">{t('No workouts in this period yet.')}</div>}
</>}
</div>
}
@@ -147,7 +258,21 @@ export default function Stats() {
const bwDelta30 = bw30.length > 1 ? bw30[bw30.length - 1].w - bw30[0].w : null
const monthW = S.workouts.filter(w => w.d.slice(0, 7) === todayISO().slice(0, 7)).length
const exHist = [...new Set(S.workouts.flatMap(w => w.entries.map(e => e.id)))].filter(id => EXIDX[id]).sort((a, b) => EXIDX[a].n < EXIDX[b].n ? -1 : 1)
const currentOf = id => {
for (let i = S.workouts.length - 1; i >= 0; i--) {
const en = S.workouts[i].entries.find(e => e.id === id)
if (!en) continue
const mode = modeOf({ ...(en.target || {}), id })
const metric = s2 => mode === 'cardio' ? (s2.speed || 0) : mode === 'time' ? (s2.sec || 0) : (s2.w || 0)
const mx = Math.max(0, ...en.sets.filter(s2 => s2.done).map(metric), mode === 'time' || mode === 'cardio' ? 0 : (en.topW || 0))
if (mx > 0) return { mx, unit: mode === 'cardio' ? 'km/h' : mode === 'time' ? 's' : S.unit }
}
return { mx: 0, unit: S.unit }
}
const exHist = [...new Set(S.workouts.flatMap(w => w.entries.map(e => e.id)))].filter(id => EXIDX[id])
const exCurrent = Object.fromEntries(exHist.map(id => [id, currentOf(id)]))
exHist.sort((a, b) => exCurrent[b].mx - exCurrent[a].mx || (EXIDX[a].n < EXIDX[b].n ? -1 : 1))
const curEx = exId && exHist.includes(exId) ? exId : exHist[0] || null
// How this exercise was logged most recently decides what the curve means: top weight,
// longest hold or top speed. Sets logged in another mode lack the field and score 0, so a
@@ -232,7 +357,8 @@ export default function Stats() {
{exHist.length ? <>
<div className="sect-b" style={{ marginBottom: 10 }}>
<SelectRow title={t('Exercise')} sheetTitle={t('Exercise progress')} value={curEx} onChange={setExId}
options={exHist.map(id => ({ value: id, label: EXIDX[id].n }))} />
options={exHist.map(id => ({ value: id, label: EXIDX[id].n + (exCurrent[id].mx ? ' ' + '—' + ' ' + fmtNum(exCurrent[id].mx) + ' ' + exCurrent[id].unit : '') }))} />
</div>
{exOpts.length > 1 && <Segmented className="seg-range" value={onEff ? 'effort' : onE1 ? 'e1rm' : 'top'} onChange={setExMetric} options={exOpts} />}
<div className="chart">
+302
View File
@@ -0,0 +1,302 @@
import React, { act } from 'react'
import { createRoot } from 'react-dom/client'
import { parseHTML } from 'linkedom'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { MUSCLES, MUSCLE_NAME, levelsOf, rankOf } from '../lib/muscles.js'
import { FATIGUE_STATES, STRENGTH_FLOOR } from '../lib/recovery.js'
import { fatigueStateOf } from '../lib/recovery-view.js'
import Stats, { weeksSinceTraining } from './Stats.jsx'
const DAY = 86400000
const HOUR = 3600000
const BASE_NOW = Date.UTC(2026, 0, 22, 12)
const mocks = vi.hoisted(() => ({
maps: [],
mapMounts: 0,
S: {
unit: 'kg', body: 'male', effort: 'rir', targetW: null,
bodyweight: [], routines: [], workouts: [],
},
}))
vi.mock('../store/useStore.js', () => ({
useStore: selector => selector({ S: mocks.S }),
}))
vi.mock('react-router-dom', () => ({ useNavigate: () => () => {} }))
vi.mock('../sheets.jsx', () => ({
bwSheet: () => {}, goalSheet: () => {}, calendarSheet: () => {}, workoutDetailSheet: () => {},
WorkoutRow: () => React.createElement('div'), bwDeltaColor: () => 'inherit',
}))
vi.mock('../components/LineChart.jsx', () => ({ default: () => React.createElement('div') }))
vi.mock('../components/Heatmap.jsx', () => ({ default: () => React.createElement('div') }))
vi.mock('../components/Icon.jsx', () => ({ default: props => React.createElement('span', props) }))
vi.mock('../components/BodyMap.jsx', () => ({
default: props => {
mocks.maps.push(props)
React.useEffect(() => {
mocks.mapMounts++
return () => {}
}, [])
return React.createElement(
'div',
{ 'data-body-map': true, 'data-selected-muscle': props.selected || '' },
React.createElement('button', {
'data-muscle': 'chest',
onClick: () => props.onMuscle?.('chest'),
}, 'Chest'),
)
},
BodyMapLegend: () => React.createElement('div', { 'data-balance-legend': true }),
}))
let dom
let root
let container
function iso(timestamp) {
return new Date(timestamp).toISOString().slice(0, 10)
}
function set(done, extra = {}) {
return { done, w: 10, r: 8, unit: 'kg', ...extra }
}
function workout(id, start, entries) {
return { id, d: iso(start), start, unit: 'kg', entries }
}
function entry(id, sets) {
return { id, sets }
}
function lifecycleWorkouts(now = BASE_NOW) {
// A 6-set chest day on the saturating curve crosses .5 at ~55.05 hours, so the edge
// flips fatigued -> recovering after one 60-second interval tick.
const fatigueEdge = now - (36 * Math.log2(6 / (3 * Math.LN2)) * HOUR - 30000)
// This completed set is in the initial 30-day Balance window, then ages out after one tick.
const balanceEdge = now - (30 * DAY - 30000)
// The 14-day strength edge becomes sub-full after one tick.
const strengthEdge = now - (14 * DAY - 30000)
// This completed event must remain the latest training event for abs: the newer set is undone.
const absCompleted = now - 20 * DAY
const absUndone = now - DAY
return [
workout('fatigue-edge', fatigueEdge, [entry('1254', Array.from({ length: 6 }, () => set(true, { rir: 0 })))]),
workout('balance-edge', balanceEdge, [entry('1254', [set(true, { rir: 2 })])]),
workout('strength-edge', strengthEdge, [entry('1001', [set(true, { rir: 2 })])]),
workout('abs-completed', absCompleted, [entry('1002', [set(true, { rir: 2 })])]),
workout('abs-undone', absUndone, [entry('1002', [set(false, { rir: 0 })])]),
]
}
function allFatiguedWorkout(now = BASE_NOW) {
// Eight completed sets per exercise: on the saturating curve every involved muscle gets
// raw >= 3.2 (0.4 x 8), i.e. a fatigue value above the .55 top band regardless of the
// catalogue's secondary-muscle metadata.
const ids = [
['1018', 1], // trapezius
['1012', 1], // deltoids
['1167', 1], // chest
['1013', 1], // upper-back
['3011', 1], // serratus
['1413', 1], // biceps
['1399', 1], // triceps
['1016', 1], // forearm
['1005', 2], // abs + obliques
['1010', 1], // lower-back
['1003', 1], // gluteal
['1001', 1], // quadriceps
['1511', 1], // hamstring
['1494', 1], // adductors
['1002', 2], // abs + hip-flexors
['1000', 1], // calves
['1396', 2], // calves + tibialis
]
return workout('all-fatigued', now, ids.map(([id]) => entry(id, Array.from({ length: 8 }, () => set(true)))))
}
function allSubfullWorkout(now = BASE_NOW) {
return workout('all-subfull', now - 15 * DAY, [entry('1254', [set(true)])])
}
function resetFixture(workouts = lifecycleWorkouts()) {
mocks.S.workouts = workouts
mocks.maps.length = 0
mocks.mapMounts = 0
}
function installDom() {
const parsed = parseHTML('<!doctype html><html><body><div id="root"></div></body></html>')
dom = parsed.window
globalThis.window = dom
globalThis.document = dom.document
Object.defineProperty(globalThis, 'navigator', { configurable: true, value: dom.navigator })
for (const key of ['HTMLElement', 'Node', 'Element', 'Event']) globalThis[key] = dom[key]
globalThis.IS_REACT_ACT_ENVIRONMENT = true
container = document.getElementById('root')
root = createRoot(container)
}
async function mountStats() {
installDom()
await act(async () => { root.render(React.createElement(Stats)) })
}
async function unmountStats() {
if (!root) return
await act(async () => { root.unmount() })
root = null
container = null
dom = null
}
function muscleCard() {
return [...container.querySelectorAll('.card')].find(card =>
[...card.querySelectorAll('.seg button')].some(button =>
['Muscle balance', 'Fatigue', 'Strength'].includes(button.textContent.trim())))
}
function buttonWithText(scope, text) {
return [...scope.querySelectorAll('button')].find(button => button.textContent.trim() === text)
}
function viewButton(text) {
return buttonWithText(muscleCard(), text)
}
function balanceRangeButton(text) {
const segments = muscleCard().querySelectorAll('.seg')
return buttonWithText(segments[1], text)
}
async function click(button) {
expect(button, `expected a button named ${button?.textContent || 'unknown'}`).toBeTruthy()
await act(async () => { button.dispatchEvent(new dom.Event('click', { bubbles: true })) })
}
async function tick(milliseconds) {
await act(async () => { await vi.advanceTimersByTimeAsync(milliseconds) })
}
function lastMap() {
return mocks.maps.at(-1)
}
function expectPressed(button) {
expect(button?.getAttribute('aria-pressed')).toBe('true')
}
function strengthRows() {
return [...muscleCard().querySelectorAll('.mrow .nm')].map(node => node.textContent.trim())
}
afterEach(async () => {
await unmountStats()
vi.useRealTimers()
vi.restoreAllMocks()
})
beforeEach(() => {
vi.useFakeTimers()
vi.setSystemTime(BASE_NOW)
resetFixture()
})
describe('Stats muscle recovery view runtime', () => {
it('starts in Balance and preserves range, hard filter, and selected muscle through every real view transition', async () => {
await mountStats()
const card = muscleCard()
expectPressed(buttonWithText(card, 'Muscle balance'))
expectPressed(buttonWithText(card, 'Week'))
await click(balanceRangeButton('30d'))
await click(buttonWithText(card, 'All'))
await click(card.querySelector('[data-muscle="chest"]'))
expectPressed(balanceRangeButton('30d'))
expect(buttonWithText(muscleCard(), 'Hard')).toBeTruthy()
expect(container.querySelector('[data-selected-muscle="chest"]')).toBeTruthy()
await click(viewButton('Fatigue'))
expect(container.textContent).toContain('Fatigue shows how recently each muscle was trained. High means rest.')
await click(viewButton('Strength'))
expect(container.textContent).toContain('Strength shows retained muscle strength. Train again to reset it.')
await click(viewButton('Muscle balance'))
expectPressed(balanceRangeButton('30d'))
expect(buttonWithText(muscleCard(), 'Hard')).toBeTruthy()
expect(container.querySelector('[data-selected-muscle="chest"]')).toBeTruthy()
expect(lastMap().selected).toBe('chest')
expect(lastMap().load.chest).toBe(7)
})
it('refreshes fatigue presentation, Balance 30-day filtering, and the mounted tree on the 60-second tick', async () => {
await mountStats()
await click(balanceRangeButton('30d'))
await click(viewButton('Fatigue'))
await click(muscleCard().querySelector('[data-muscle="chest"]'))
const beforeTickMounts = mocks.mapMounts
const beforeTick = lastMap().load.chest
expect(fatigueStateOf(beforeTick)).toBe(FATIGUE_STATES.FATIGUED)
expect(container.textContent).toContain('Fatigued')
await tick(60000)
const afterTick = lastMap().load.chest
expect(mocks.mapMounts).toBe(beforeTickMounts)
expect(afterTick).toBeLessThan(0.5)
expect(fatigueStateOf(afterTick)).toBe(FATIGUE_STATES.RECOVERING)
expect(container.textContent).toContain('Recovering')
await click(viewButton('Strength'))
expect(lastMap().load.quadriceps).toBeLessThan(1)
expect(strengthRows()).toContain('Quads')
await click(viewButton('Muscle balance'))
expect(lastMap().load.chest).toBe(6)
expectPressed(balanceRangeButton('30d'))
})
it('ignores an undone latest set, floors rendered training age, and follows production rankOf ordering', async () => {
await mountStats()
await click(viewButton('Strength'))
const load = lastMap().load
const expectedRows = rankOf(load).worked
.filter(slug => load[slug] < 1)
.map(slug => MUSCLE_NAME[slug])
expect(strengthRows()).toEqual(expectedRows)
// The newer abs row is undone, so the rendered hint uses the completed event from 20 days ago.
expect(container.textContent).toContain('1 sets')
// The production helper used by Stats' rendered strength hint floors six elapsed days to zero.
expect(weeksSinceTraining(BASE_NOW, BASE_NOW - 6 * DAY)).toBe(0)
})
it('uses production boundaries and fixed absolute bands for all-fatigued and all-subfull maps', async () => {
expect(fatigueStateOf(0.2499)).toBe(FATIGUE_STATES.READY)
expect(fatigueStateOf(0.25)).toBe(FATIGUE_STATES.RECOVERING)
expect(fatigueStateOf(0.5)).toBe(FATIGUE_STATES.RECOVERING)
expect(fatigueStateOf(0.5001)).toBe(FATIGUE_STATES.FATIGUED)
resetFixture([allFatiguedWorkout()])
await mountStats()
await click(viewButton('Fatigue'))
const fatigueMap = lastMap()
expect(Object.keys(fatigueMap.load)).toEqual(MUSCLES)
expect(Object.values(fatigueMap.load).every(value => value > 0.5)).toBe(true)
expect(Object.values(levelsOf(fatigueMap.load, fatigueMap.thresholds)).every(level => level === 4)).toBe(true)
await unmountStats()
resetFixture([allSubfullWorkout()])
await mountStats()
await click(viewButton('Strength'))
const strengthMap = lastMap()
expect(Object.values(strengthMap.load).every(value => value < 1)).toBe(true)
expect(Math.min(...Object.values(strengthMap.load))).toBe(STRENGTH_FLOOR)
expect(strengthMap.thresholds.at(-1)).toEqual({ at: 1, level: 4 })
})
})