Skip to content

Open-source gym & body-weight tracker, now in the App Store (iPhone + Apple Watch) and as an Android APK. Plan routines, log workouts, see which muscles are trained, import from Strong/Hevy/FitNotes. Self-host it or use it on the phone alone.

fix: harden muscle balance stats semantics

Space_Hermes194d62ace33a
diff --git a/frontend/src/components/BodyMap.jsx b/frontend/src/components/BodyMap.jsx
index 022f1807d..46d3f83f3 100644
--- a/frontend/src/components/BodyMap.jsx
+++ b/frontend/src/components/BodyMap.jsx
@@ -27,8 +27,13 @@ function useBodyPaths() {
}
function View({ view, levels, onMuscle, selected }) {
+ const activate = (event, slug) => {
+ if (event.key !== 'Enter' && event.key !== ' ') return
+ if (event.key === ' ') event.preventDefault()
+ onMuscle(slug)
+ }
return (
- <svg className="bm-v" viewBox={view.vb} role="img">
+ <svg className="bm-v" viewBox={view.vb} role={onMuscle ? 'group' : 'img'}>
{INERT.map(slug => (view.p[slug] || []).map((d, i) =>
<path key={slug + i} className="bm-sil" d={d} />))}
{MUSCLES.map(slug => (view.p[slug] || []).map((d, i) =>
@@ -37,6 +42,11 @@ function View({ view, levels, onMuscle, selected }) {
className={'bm-m l' + (levels[slug] || 0) + (selected === slug ? ' sel' : '')}
d={d}
onClick={onMuscle ? () => onMuscle(slug) : undefined}
+ onKeyDown={onMuscle ? event => activate(event, slug) : undefined}
+ role={onMuscle ? 'button' : undefined}
+ tabIndex={onMuscle ? 0 : undefined}
+ aria-label={onMuscle ? t(MUSCLE_NAME[slug]) : undefined}
+ aria-pressed={onMuscle ? selected === slug : undefined}
>
<title>{t(MUSCLE_NAME[slug])}</title>
</path>))}
@@ -66,7 +76,7 @@ export default function BodyMap({ load = {}, thresholds, body = 'male', onMuscle
}
export function BodyMapLegend() {
- return <div className="hm-legend">
+ return <div className="hm-legend" aria-label={`${t('Less')} ${t('More')}`}>
{t('Less')} <div className="hm-c l0" /><div className="hm-c l1" /><div className="hm-c l2" />
<div className="hm-c l3" /><div className="hm-c l4" /> {t('More')}
</div>
diff --git a/frontend/src/components/BodyMap.test.jsx b/frontend/src/components/BodyMap.test.jsx
new file mode 100644
index 000000000..1cc2b4375
--- /dev/null
+++ b/frontend/src/components/BodyMap.test.jsx
@@ -0,0 +1,62 @@
+// @vitest-environment happy-dom
+import React, { act } from 'react'
+import { createRoot } from 'react-dom/client'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import BodyMap, { BodyMapLegend } from './BodyMap.jsx'
+
+globalThis.IS_REACT_ACT_ENVIRONMENT = true
+
+let container
+let root
+
+beforeEach(() => {
+ container = document.createElement('div')
+ document.body.appendChild(container)
+ root = createRoot(container)
+})
+
+afterEach(() => {
+ act(() => root.unmount())
+ container.remove()
+})
+
+async function renderMap(props = {}) {
+ await act(async () => {
+ root.render(<BodyMap load={{ chest: 2 }} {...props} />)
+ })
+ await vi.waitFor(() => expect(container.querySelectorAll('.bm-v')).toHaveLength(2))
+ return container.querySelector('.bm-m[aria-label="Chest"]')
+}
+
+describe('BodyMap interaction semantics', () => {
+ it('keeps noninteractive maps as images without focusable muscle controls', async () => {
+ await renderMap()
+ expect(container.querySelectorAll('svg[role="img"]')).toHaveLength(2)
+ expect(container.querySelector('[role="button"]')).toBeNull()
+ })
+
+ it('exposes interactive muscles as translated pressed buttons inside groups', async () => {
+ const path = await renderMap({ selected: 'chest', onMuscle: vi.fn() })
+ expect(container.querySelectorAll('svg[role="group"]')).toHaveLength(2)
+ expect(path).toBeTruthy()
+ expect(path.tabIndex).toBe(0)
+ expect(path.getAttribute('aria-pressed')).toBe('true')
+ })
+
+ it.each(['Enter', ' '])('activates a muscle once with %s', async key => {
+ const onMuscle = vi.fn()
+ const path = await renderMap({ onMuscle })
+ const event = new KeyboardEvent('keydown', { key, bubbles: true, cancelable: true })
+
+ act(() => path.dispatchEvent(event))
+
+ expect(onMuscle).toHaveBeenCalledTimes(1)
+ expect(onMuscle).toHaveBeenCalledWith('chest')
+ expect(event.defaultPrevented).toBe(key === ' ')
+ })
+
+ it('labels the existing legend direction for assistive technology', () => {
+ act(() => root.render(<BodyMapLegend />))
+ expect(container.querySelector('.hm-legend').getAttribute('aria-label')).toBe('Less More')
+ })
+})
diff --git a/frontend/src/index.css b/frontend/src/index.css
index a34845995..088420222 100644
--- a/frontend/src/index.css
+++ b/frontend/src/index.css
@@ -838,6 +838,7 @@ h4.sec{
.bm-m.sel{stroke:var(--label);stroke-width:7}
.bodymap.tappable .bm-m{cursor:pointer}
+.bodymap.tappable .bm-m:focus-visible{outline:none;stroke:var(--label);stroke-width:7;filter:drop-shadow(0 0 2px var(--surface))}
/* A hairline in the surface colour separates neighbouring muscles; the artwork has no
outline path of its own, so without this the body reads as one flat blob. */
.bm-v path{stroke:var(--surface);stroke-width:2.5;stroke-linejoin:round}
diff --git a/frontend/src/lib/muscles.js b/frontend/src/lib/muscles.js
index 8f52b1324..8869e7b19 100644
--- a/frontend/src/lib/muscles.js
+++ b/frontend/src/lib/muscles.js
@@ -9,6 +9,7 @@
import { isWarmupRow } from './workout-model.js'
import { EXIDX, smOf } from './exercises.js'
+import { todayISO, weekKey } from './format.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.
@@ -160,7 +161,7 @@ export function muscleGroupsOf(entry) {
? [...parts.primary, ...parts.secondary]
: explicit || [ex?.tg, ex?.mg, ...arrayOf(smOf(ex))]
const out = canonicalUnique(source)
- if (!out.length && !useParts && explicit == null) {
+ if (!out.length && !useParts) {
canonicalUnique(Object.keys(BY_BODYPART[ex?.bp] || {})).forEach(slug => out.push(slug))
}
return out
@@ -259,6 +260,15 @@ export const loadOfWorkouts = (workouts, pick) =>
loadOf((workouts || []).flatMap(w =>
(w.entries || []).map(e => ({ id: e.id, ex: e.exercise || e, sets: (e.sets || []).filter(s => s.done && !isWarmupRow(s) && (!pick || pick(s))).length }))))
+/** Workouts in one existing Muscle balance range, with time injected for deterministic tests. */
+export function muscleBalanceWindow(workouts, win, now = Date.now(), today = todayISO()) {
+ return (workouts || []).filter(workout => win === 0
+ ? true
+ : win === 7
+ ? weekKey(workout.d) === weekKey(today)
+ : (workout.start || new Date(workout.d).getTime()) > now - win * 86400000)
+}
+
/** Load a routine *would* produce, from its planned set counts. */
export const loadOfRoutine = routine =>
loadOf((routine?.ex || []).map(c => ({ id: c.id, ex: c, sets: c.sets || 1 })))
@@ -304,7 +314,8 @@ export function levelsOf(load, thresholds) {
/** Muscles sorted hardest-worked first; untrained ones last, in body order. */
export function rankOf(load) {
- const worked = MUSCLES.filter(m => (load[m] || 0) > 0).sort((a, b) => load[b] - load[a])
+ const worked = MUSCLES.filter(m => (load[m] || 0) > 0)
+ .sort((a, b) => load[b] - load[a] || MUSCLES.indexOf(a) - MUSCLES.indexOf(b))
const missed = MUSCLES.filter(m => !(load[m] > 0))
return { worked, missed }
}
diff --git a/frontend/src/lib/muscles.test.js b/frontend/src/lib/muscles.test.js
index 9d6c7a3ed..9294ac758 100644
--- a/frontend/src/lib/muscles.test.js
+++ b/frontend/src/lib/muscles.test.js
@@ -1,6 +1,9 @@
import { describe, it, expect } from 'vitest'
import { EXIDX, EXDB, smOf } from './exercises.js'
-import { MUSCLE_NAME, exerciseMuscleSnapshot, hasExplicitMuscleMetadata, loadOf, loadOfWorkouts, matchesMuscleGroups, muscleGroupsOf, musclesOf } from './muscles.js'
+import {
+ MUSCLE_NAME, exerciseMuscleSnapshot, hasExplicitMuscleMetadata, levelsOf, loadOf,
+ loadOfWorkouts, matchesMuscleGroups, muscleBalanceWindow, muscleGroupsOf, musclesOf, rankOf
+} from './muscles.js'
describe('multi-muscle exercise metadata', () => {
it('normalizes legacy primary/secondary fields and removes duplicate groups', () => {
@@ -20,6 +23,12 @@ describe('multi-muscle exercise metadata', () => {
expect(matchesMuscleGroups({ bp: 'back', muscleGroups: [] }, ['lower-back'])).toBe(true)
})
+ it('falls back consistently when explicit groups contain only unknown names', () => {
+ const ex = { bp: 'back', muscleGroups: ['not-a-drawable-name'] }
+ expect(muscleGroupsOf(ex)).toEqual(['upper-back', 'lower-back'])
+ expect(musclesOf(ex)).toEqual({ 'upper-back': 0.75, 'lower-back': 0.25 })
+ })
+
it('matches an exercise when any requested muscle group matches', () => {
const ex = { muscleGroups: ['chest', 'triceps'] }
expect(matchesMuscleGroups(ex, ['hamstring', 'triceps'])).toBe(true)
@@ -172,3 +181,32 @@ describe('warm-up boundary', () => {
}
})
})
+
+describe('muscle balance windows and ranking', () => {
+ const now = new Date('2026-08-27T12:00:00').getTime()
+ const workouts = [
+ { id: 'monday', d: '2026-08-24', start: new Date('2026-08-24T12:00:00').getTime() },
+ { id: 'sunday', d: '2026-08-23', start: new Date('2026-08-23T12:00:00').getTime() },
+ { id: 'boundary', d: '2026-07-28', start: now - 30 * 86400000 },
+ { id: 'inside', d: '2026-07-29', start: now - 29 * 86400000 },
+ ]
+
+ it('preserves calendar-week, strict trailing-day, and all-history semantics', () => {
+ expect(muscleBalanceWindow(workouts, 7, now, '2026-08-27').map(w => w.id)).toEqual(['monday'])
+ expect(muscleBalanceWindow(workouts, 30, now, '2026-08-27').map(w => w.id)).toEqual(['monday', 'sunday', 'inside'])
+ expect(muscleBalanceWindow(workouts, 0, now, '2026-08-27')).toEqual(workouts)
+ })
+
+ it('uses relative levels and canonical order to break load ties', () => {
+ const load = { chest: 2, deltoids: 2, biceps: 1 }
+ expect(rankOf(load).worked).toEqual(['deltoids', 'chest', 'biceps'])
+ expect(levelsOf(load)).toMatchObject({ deltoids: 4, chest: 4, biceps: 2, abs: 0 })
+ })
+
+ it('keeps catalogue precedence and deleted-custom snapshot weights', () => {
+ const known = { id: '0025', muscleGroups: ['quadriceps'], sets: [{ done: true }] }
+ const deleted = { id: 'deleted', muscleSnapshot: { muscleWeights: { chest: 1 } }, sets: [{ done: true }] }
+ expect(loadOfWorkouts([{ entries: [known] }])).toEqual({ chest: 1, triceps: 0.4, deltoids: 0.4, biceps: 0.4 })
+ expect(loadOfWorkouts([{ entries: [deleted] }])).toEqual({ chest: 1 })
+ })
+})
diff --git a/frontend/src/views/Stats.jsx b/frontend/src/views/Stats.jsx
index 3622b7bf4..467c47d1b 100644
--- a/frontend/src/views/Stats.jsx
+++ b/frontend/src/views/Stats.jsx
@@ -3,14 +3,14 @@ import { useNavigate } from 'react-router-dom'
import { useStore } from '../store/useStore.js'
import { EXIDX } from '../lib/exercises.js'
import { lastBW, streakWeeks, setLabel, modeOf, effortOf, metricModeForEntry, metricRowsForEntry, bestWeightForEntry } from '../lib/history.js'
-import { fmtNum, fmtDate, fmtVol, todayISO, weekKey } from '../lib/format.js'
+import { fmtNum, fmtDate, fmtVol, todayISO } from '../lib/format.js'
import { t, exerciseNameFor, getLang } from '../lib/i18n.js'
import { bwSheet, goalSheet, calendarSheet, workoutDetailSheet, WorkoutRow, bwDeltaColor } from '../sheets.jsx'
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, musclesOf } from '../lib/muscles.js'
+import { loadOfWorkouts, muscleBalanceWindow, rankOf, MUSCLE_NAME, musclesOf } from '../lib/muscles.js'
import { fatigueOf, strengthOf, STRENGTH_FLOOR, LB_TO_KG } from '../lib/recovery.js'
import { strengthExerciseRowsForMuscle } from '../lib/strength-exercises.js'
import { fatigueStateOf } from '../lib/recovery-view.js'
@@ -122,10 +122,7 @@ function MuscleBalance({ S }) {
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())
- : (w.start || new Date(w.d).getTime()) > now - win * 86400000)
+ const inWin = muscleBalanceWindow(S.workouts, win, now)
// Counting only the sets taken near failure turns the map from "where did the volume go"
// into "where did the stimulus go" — a muscle can lead on sets and still never be trained
// hard. Offered only when the window holds ratings at all, since with none the hard map