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.
JavaScript apple-watchbodyweightdockerfitnessfitness-trackergymhealthiosmcpnodejspasskeysprogressive-web-applicationspwareactself-hostedself-hostingvitewebauthnweightliftingworkout-tracker
Stats: read the effort back — trend, distribution, hard sets, per exercise
Duarte Santoscaaf61d91ede
diff --git a/frontend/src/components/LineChart.jsx b/frontend/src/components/LineChart.jsxindex 8f9302ef6..c236464e4 100644--- a/frontend/src/components/LineChart.jsx+++ b/frontend/src/components/LineChart.jsx@@ -4,8 +4,15 @@ import { t } from '../lib/i18n.js'const W = 340 // viewBox width; the svg stretches to its container, height comes from `h`-// points: [{ t: ms, y: num, d?: iso }] sorted by t. opts: { h, unit, color, axes, goal }-export default function LineChart({ points, h = 150, unit = '', color = 'var(--acc)', axes = true, goal = null }) {+// points: [{ t: ms, y: num, d?: iso, m?: 0..1, note?: str }] sorted by t.+// m marks the point — a second reading carried by the same dot (bigger and more solid =+// more of it). Used for effort on the weight curve, where the two belong on one line:+// the same weight with less left in the tank is not the same session.+// note extra text for that point's tooltip.+// opts: { h, unit, color, axes, goal, invert }+// invert flips the y axis, for a scale that counts down as it gets harder (RIR). Without it+// a curve of reps-in-reserve reads upside down, with the hardest sets at the floor.+export default function LineChart({ points, h = 150, unit = '', color = 'var(--acc)', axes = true, goal = null, invert = false }) {const svgRef = useRef(null)const wrapRef = useRef(null)const tipRef = useRef(null)@@ -42,7 +49,10 @@ export default function LineChart({ points, h = 150, unit = '', color = 'var(--aconst pad = (ymax - ymin) * 0.12; ymin -= pad; ymax += padconst t0 = pts[0].t, t1 = pts[pts.length - 1].t || t0 + 1const X = t => (t1 === t0 ? (P.l + W - P.r) / 2 : P.l + (t - t0) / (t1 - t0) * (W - P.l - P.r))- const Y = y => P.t + (1 - (y - ymin) / (ymax - ymin)) * (H - P.t - P.b)+ const Y = y => {+ const f = (y - ymin) / (ymax - ymin)+ return P.t + (invert ? f : 1 - f) * (H - P.t - P.b)+ }const gridlines = []if (axes) {@@ -81,7 +91,8 @@ export default function LineChart({ points, h = 150, unit = '', color = 'var(--aconst poly = pts.map(p => X(p.t).toFixed(1) + ',' + Y(p.y).toFixed(1)).join(' ')const last = pts[pts.length - 1]const gid = 'g' + Math.round(t0 % 1e7) + '_' + H- const hoverPts = (single ? [points[0]] : points).map(p => ({ x: X(p.t), y: Y(p.y), iso: p.d || isoOf(new Date(p.t)), v: p.y }))+ const hoverPts = (single ? [points[0]] : points).map(p => ({ x: X(p.t), y: Y(p.y), iso: p.d || isoOf(new Date(p.t)), v: p.y, note: p.note }))+ const marked = points.some(p => p.m != null)const onMove = e => {const c = e.touches ? e.touches[0] : e@@ -111,6 +122,8 @@ export default function LineChart({ points, h = 150, unit = '', color = 'var(--a</>}<polygon points={`${P.l},${H - P.b} ${poly} ${X(last.t).toFixed(1)},${H - P.b}`} fill={`url(#${gid})`} /><polyline points={poly} fill="none" stroke={color} strokeWidth="2.5" strokeLinejoin="round" strokeLinecap="round" />+ {marked && pts.map((p, i) => (p.m == null ? null :+ <circle key={'m' + i} cx={X(p.t)} cy={Y(p.y)} r={2.4 + p.m * 3} fill={color} opacity={0.3 + p.m * 0.7} />))}<circle cx={X(last.t)} cy={Y(last.y)} r="4" fill={color} />{hover && <g><line className="cvl" x1={hover.x} y1={P.t} x2={hover.x} y2={H - P.b} stroke="var(--label-3)" strokeWidth="1" strokeDasharray="3 3" />@@ -119,7 +132,7 @@ export default function LineChart({ points, h = 150, unit = '', color = 'var(--a</g>}</svg>{hover && <div className="ctip" ref={tipRef}>- {fmtDate(hover.iso, true)} · {fmtNum(hover.v)}{unit ? ' ' + unit : ''}+ {fmtDate(hover.iso, true)} · {fmtNum(hover.v)}{unit ? ' ' + unit : ''}{hover.note ? ' · ' + hover.note : ''}</div>}</div>)diff --git a/frontend/src/index.css b/frontend/src/index.cssindex 47123d713..e3eba2726 100644--- a/frontend/src/index.css+++ b/frontend/src/index.css@@ -784,6 +784,9 @@ h4.sec{.mrow .bar{width:74px;height:5px;border-radius:3px;background:var(--surface-2);flex:none;overflow:hidden}.mrow .bar i{display:block;height:100%;background:var(--acc);border-radius:3px}.mrow .v{font-size:12px;color:var(--label-2);min-width:52px;text-align:right;flex:none}+/* A headline number inside a card — tile weight without a tile around it, for the pair of+ readings at the top of the effort card. */+.stat-v{font-size:26px;font-weight:600;letter-spacing:-.026em;line-height:1.1}.mchips{display:flex;flex-wrap:wrap;gap:6px;margin-top:4px}.mchip{font-size:12px;padding:4px 9px;border-radius:99px;background:var(--surface-2);color:var(--label-2)}.mchip.miss{background:color-mix(in srgb,var(--orange) 16%,transparent);color:var(--orange)}diff --git a/frontend/src/lib/effort.js b/frontend/src/lib/effort.jsnew file mode 100644index 000000000..5c70da76e--- /dev/null+++ b/frontend/src/lib/effort.js@@ -0,0 +1,154 @@+// Effort as a statistic: one internal scale, both display scales.+//+// A set carries either `rir` or `rpe` and is never rewritten — switching the setting changes+// what new sets ask for, nothing else (see history.js). For a *chart* that is a problem: a+// history that mixes the two (own logs in RIR, an imported file in RPE) would draw two+// half-empty series. So everything aggregates in RIR and is converted back for display.+// RIR is the internal unit because it has a real zero — a set taken to failure — where RPE's+// floor of 6 is only a convention about which sets are worth rating. RPE 8 == RIR 2.+import { EFFORT, effortOf } from './history.js'+import { weekKey } from './format.js'++// At or below this a set is close enough to failure to be the kind that drives adaptation.+// 3 rather than 2: the line is a convention, and drawn one rep too generously it still+// separates working sets from the ones left in the warm-up range.+export const HARD_RIR = 3+// Below this many rated sets an average is noise. Showing "RIR 1.0" off a single set reads+// like a finding when it is one tap, so the callers show a dash instead.+export const MIN_RATED = 5++/** A set's effort in RIR, or null when it was never rated. 0 is a rating, not "empty". */+export const rirOf = s =>+ !s ? null : s.rir != null ? s.rir : s.rpe != null ? 10 - s.rpe : null++/** RIR → the scale being displayed. The reverse of rirOf, for one number. */+export const toScale = (kind, rir) =>+ rir == null ? null : Math.round((kind === 'rpe' ? 10 - rir : rir) * 10) / 10++/**+ * Which scale to *label* aggregates with. The profile's own setting wins; a profile that+ * logs nothing itself but carries rated history (the imported-from-Hevy case) is shown the+ * scale that history is actually written in, rather than an RIR it has never seen.+ */+export function displayScale(S) {+ const k = effortOf(S)+ if (EFFORT[k]) return k+ let rir = 0, rpe = 0+ eachDoneSet(S, s => { if (s.rir != null) rir++; else if (s.rpe != null) rpe++ })+ return rpe > rir ? 'rpe' : 'rir'+}+export const scaleName = kind => EFFORT[kind].hd++// Every finished set in the profile, oldest first. `fn` gets the set plus the workout it+// belongs to, which is what the windowed and per-week views need.+function eachDoneSet(S, fn) {+ ;(S.workouts || []).forEach(w =>+ (w.entries || []).forEach(e =>+ (e.sets || []).forEach(s => { if (s.done) fn(s, w, e) })))+}++// A window in days, counted back from now. 0 = everything, which is also what an empty+// history means for every caller here.+const inWindow = (w, days) =>+ !days || (w.start || new Date(w.d).getTime()) > Date.now() - days * 86400000++export const avgRir = sets => {+ const vs = (sets || []).map(rirOf).filter(v => v != null)+ return vs.length ? vs.reduce((a, b) => a + b, 0) / vs.length : null+}++/**+ * The headline numbers for a window: how hard, how much of it was hard, and — the part that+ * keeps the rest honest — how much of the training was rated at all. Effort is optional and+ * off by default, so partial coverage is the normal case; an average without its denominator+ * would quietly speak for sets that were never rated.+ */+export function effortSummary(S, days) {+ let done = 0, rated = 0, sum = 0, hard = 0+ eachDoneSet(S, (s, w) => {+ if (!inWindow(w, days)) return+ done+++ const r = rirOf(s)+ if (r == null) return+ rated++; sum += r+ if (r <= HARD_RIR) hard+++ })+ return {+ done, rated, hard,+ avg: rated >= MIN_RATED ? sum / rated : null,+ hardPct: rated >= MIN_RATED ? hard / rated : null+ }+}++/** Does this profile hold any rated set at all? Decides whether the effort UI exists. */+export function hasEffort(S) {+ let any = false+ eachDoneSet(S, s => { if (!any && rirOf(s) != null) any = true })+ return any+}++/**+ * Average effort per calendar week, with the week's set count alongside: the pair is the+ * point. Volume up with effort up is fatigue accumulating; volume up with effort flat is the+ * adaptation you were training for. Weeks with a single rated set are dropped rather than+ * drawn — one tap should not become a peak in the curve.+ */+export function effortWeeks(S, days) {+ const wk = new Map()+ eachDoneSet(S, (s, w) => {+ if (!inWindow(w, days)) return+ const k = weekKey(w.d)+ let e = wk.get(k)+ if (!e) wk.set(k, e = { k, t: mondayOf(w.d), sum: 0, n: 0, sets: 0 })+ e.sets+++ const r = rirOf(s)+ if (r != null) { e.sum += r; e.n++ }+ })+ return [...wk.values()].filter(e => e.n >= 2).sort((a, b) => a.t - b.t)+ .map(e => ({ t: e.t, rir: e.sum / e.n, n: e.n, sets: e.sets }))+}+// The Monday of an ISO date, as ms — the x position a week's point sits at.+function mondayOf(iso) {+ const d = new Date(iso + 'T12:00:00')+ d.setDate(d.getDate() - ((d.getDay() + 6) % 7))+ d.setHours(12, 0, 0, 0)+ return +d+}++/**+ * How the rated sets spread across the scale, in whole steps with everything past the top+ * bucket collapsed into it. This is the chart that answers "am I training too far from+ * failure, or leaving nothing for the next session" — an average alone hides both, because+ * half the sets at 0 and half at 4 average to a healthy-looking 2.+ */+export const BUCKETS = 4 // 0,1,2,3 and a "4+" tail+export function effortHistogram(S, days) {+ const bins = new Array(BUCKETS + 1).fill(0)+ let rated = 0+ eachDoneSet(S, (s, w) => {+ if (!inWindow(w, days)) return+ const r = rirOf(s)+ if (r == null) return+ rated+++ bins[Math.min(BUCKETS, Math.max(0, Math.floor(r)))]+++ })+ return bins.map((n, i) => ({ rir: i, tail: i === BUCKETS, n, pct: rated ? n / rated : 0 }))+}++/**+ * Average effort per session for one exercise, oldest first. Sessions where the exercise was+ * logged but never rated are absent, not zero — an unrated set must never read as failure.+ */+export function exerciseEffort(S, exId) {+ const pts = []+ ;(S.workouts || []).forEach(w => {+ const en = (w.entries || []).find(e => e.id === exId)+ if (!en) return+ const r = avgRir((en.sets || []).filter(s => s.done))+ if (r != null) pts.push({ t: w.start || new Date(w.d).getTime(), d: w.d, rir: r })+ })+ return pts+}++/** A set that counts as hard — the filter behind the muscle map's "hard sets" mode. */+export const isHardSet = s => { const r = rirOf(s); return r != null && r <= HARD_RIR }diff --git a/frontend/src/lib/effort.test.js b/frontend/src/lib/effort.test.jsnew file mode 100644index 000000000..19fd4f660--- /dev/null+++ b/frontend/src/lib/effort.test.js@@ -0,0 +1,191 @@+import { describe, it, expect } from 'vitest'+import {+ rirOf, toScale, displayScale, avgRir, effortSummary, hasEffort, effortWeeks,+ effortHistogram, exerciseEffort, isHardSet, HARD_RIR, MIN_RATED+} from './effort.js'+import { isoOf } from './format.js'++const daysAgo = n => { const d = new Date(); d.setDate(d.getDate() - n); return d }+// One workout on a day, with the sets given. Everything here is a finished set unless a set+// says otherwise, because that is what the stats read.+const W = (n, sets, id = '0025') => {+ const d = daysAgo(n)+ return { id: 'w' + n, d: isoOf(d), start: +d, entries: [{ id, sets: sets.map(s => ({ w: 60, r: 8, done: true, ...s })) }] }+}+const S = (...workouts) => ({ workouts })++describe('rirOf', () => {+ it('reads RIR straight and RPE as its mirror — RPE 8 is RIR 2', () => {+ expect(rirOf({ rir: 2 })).toBe(2)+ expect(rirOf({ rpe: 8 })).toBe(2)+ expect(rirOf({ rpe: 9.5 })).toBe(0.5)+ })++ it('keeps a rated 0 and rejects everything that only looks like one', () => {+ expect(rirOf({ rir: 0 })).toBe(0) // taken to failure — a rating, not "empty"+ expect(rirOf({ rpe: 10 })).toBe(0)+ expect(rirOf({})).toBe(null)+ expect(rirOf({ rir: null })).toBe(null)+ expect(rirOf(null)).toBe(null)+ })++ it('prefers the scale the set itself was logged on when a file wrote both', () => {+ expect(rirOf({ rir: 3, rpe: 9 })).toBe(3)+ })+})++describe('toScale', () => {+ it('converts back to whichever scale is on screen', () => {+ expect(toScale('rir', 2)).toBe(2)+ expect(toScale('rpe', 2)).toBe(8)+ expect(toScale('rpe', 0)).toBe(10)+ expect(toScale('rir', null)).toBe(null)+ })++ it('does not let the round trip produce float dust', () => {+ expect(toScale('rpe', 10 - 7.5)).toBe(7.5)+ })+})++describe('displayScale', () => {+ it('follows the profile setting when it has one', () => {+ expect(displayScale({ effort: 'rpe', workouts: [] })).toBe('rpe')+ expect(displayScale({ effort: 'rir', workouts: [] })).toBe('rir')+ })++ it('shows an unrated profile the scale its imported history is written in', () => {+ // Effort off, but a file brought RPE with it: labelling that history "RIR" would show a+ // number the profile has never entered and mean the opposite of what it says.+ expect(displayScale({ effort: 'none', ...S(W(3, [{ rpe: 8 }, { rpe: 9 }])) })).toBe('rpe')+ expect(displayScale({ effort: 'none', ...S(W(3, [{ rir: 2 }])) })).toBe('rir')+ expect(displayScale({ effort: 'none', workouts: [] })).toBe('rir')+ })+})++describe('avgRir', () => {+ it('averages the rated sets and ignores the rest', () => {+ expect(avgRir([{ rir: 1 }, { rir: 3 }])).toBe(2)+ expect(avgRir([{ rir: 1 }, {}, { rpe: 7 }])).toBe(2) // RPE 7 = RIR 3+ })++ it('is null rather than 0 when nothing was rated', () => {+ expect(avgRir([{}, { rir: null }])).toBe(null)+ expect(avgRir([])).toBe(null)+ expect(avgRir(null)).toBe(null)+ })+})++describe('effortSummary', () => {+ const st = S(+ W(2, [{ rir: 1 }, { rir: 3 }, { rir: 2 }]),+ W(4, [{ rir: 0 }, { rpe: 6 }, {}]), // RPE 6 = RIR 4, one set unrated+ W(40, [{ rir: 5 }, { rir: 5 }])+ )++ it('counts rated sets against every finished set, not against itself', () => {+ const r = effortSummary(st, 0)+ expect(r.done).toBe(8)+ expect(r.rated).toBe(7)+ })++ it('leaves unrated sets out of the average instead of reading them as failure', () => {+ const r = effortSummary(S(W(2, [{ rir: 4 }, {}, {}, {}, {}, {}])), 0)+ expect(r.rated).toBe(1)+ expect(r.avg).toBe(null) // one rating is not an average+ })++ it('waits for a real sample before reporting a number', () => {+ const few = S(W(2, new Array(MIN_RATED - 1).fill({ rir: 2 })))+ expect(effortSummary(few, 0).avg).toBe(null)+ const enough = S(W(2, new Array(MIN_RATED).fill({ rir: 2 })))+ expect(effortSummary(enough, 0).avg).toBe(2)+ })++ it('counts the sets taken close to failure', () => {+ const r = effortSummary(st, 0)+ expect(r.hard).toBe(4) // 1, 3, 2, 0 — the 4 and the two 5s are not+ expect(r.hardPct).toBeCloseTo(4 / 7)+ })++ it('honours the window', () => {+ const r = effortSummary(st, 7)+ expect(r.rated).toBe(5) // the 40-day-old session is out+ expect(effortSummary(st, 3).rated).toBe(3)+ })++ it('survives a profile with no training at all', () => {+ expect(effortSummary({ workouts: [] }, 30)).toEqual({ done: 0, rated: 0, hard: 0, avg: null, hardPct: null })+ })+})++describe('hasEffort', () => {+ it('decides whether the effort UI exists at all', () => {+ expect(hasEffort(S(W(2, [{ rir: 0 }])))).toBe(true)+ expect(hasEffort(S(W(2, [{ rpe: 8 }])))).toBe(true)+ expect(hasEffort(S(W(2, [{}, { rir: null }])))).toBe(false)+ expect(hasEffort({ workouts: [] })).toBe(false)+ })++ it('ignores sets that were never finished', () => {+ expect(hasEffort(S(W(2, [{ rir: 2, done: false }])))).toBe(false)+ })+})++describe('effortWeeks', () => {+ it('averages per calendar week and carries the week volume alongside', () => {+ const pts = effortWeeks(S(W(1, [{ rir: 1 }, { rir: 3 }, {}])), 0)+ expect(pts).toHaveLength(1)+ expect(pts[0].rir).toBe(2)+ expect(pts[0].n).toBe(2) // rated+ expect(pts[0].sets).toBe(3) // trained+ })++ it('drops a week that rests on a single tap', () => {+ expect(effortWeeks(S(W(1, [{ rir: 1 }])), 0)).toEqual([])+ })++ it('comes back oldest first, whatever order the workouts arrived in', () => {+ const pts = effortWeeks(S(W(2, [{ rir: 1 }, { rir: 1 }]), W(30, [{ rir: 3 }, { rir: 3 }])), 0)+ expect(pts.map(p => p.rir)).toEqual([3, 1])+ expect(pts[0].t).toBeLessThan(pts[1].t)+ })+})++describe('effortHistogram', () => {+ it('bins by whole steps and collapses the far end into a tail', () => {+ const h = effortHistogram(S(W(2, [{ rir: 0 }, { rir: 1.5 }, { rir: 4 }, { rir: 7 }])), 0)+ expect(h.map(b => b.n)).toEqual([1, 1, 0, 0, 2])+ expect(h[4].tail).toBe(true)+ expect(h[0].pct).toBe(0.25)+ })++ it('is all zeroes, not NaN, when nothing is rated', () => {+ const h = effortHistogram(S(W(2, [{}])), 0)+ expect(h.every(b => b.n === 0 && b.pct === 0)).toBe(true)+ })+})++describe('exerciseEffort', () => {+ it('gives one point per session, in order', () => {+ const st = S(W(20, [{ rir: 4 }, { rir: 2 }]), W(2, [{ rir: 1 }]))+ expect(exerciseEffort(st, '0025').map(p => p.rir)).toEqual([3, 1])+ })++ it('skips a session where the exercise was logged but never rated', () => {+ const st = S(W(20, [{}]), W(2, [{ rir: 1 }]))+ expect(exerciseEffort(st, '0025')).toHaveLength(1)+ })++ it('does not pick up another exercise', () => {+ expect(exerciseEffort(S(W(2, [{ rir: 1 }], '0047')), '0025')).toEqual([])+ })+})++describe('isHardSet', () => {+ it('draws the line at the effort that actually drives adaptation', () => {+ expect(isHardSet({ rir: HARD_RIR })).toBe(true)+ expect(isHardSet({ rir: HARD_RIR + 0.5 })).toBe(false)+ expect(isHardSet({ rpe: 10 })).toBe(true)+ expect(isHardSet({})).toBe(false) // unrated is not hard, and not easy either+ })+})diff --git a/frontend/src/lib/muscles.js b/frontend/src/lib/muscles.jsindex 660bbd02a..c744812a0 100644--- a/frontend/src/lib/muscles.js+++ b/frontend/src/lib/muscles.js@@ -100,10 +100,15 @@ export function loadOf(items) {return load}-/** Load for finished workouts (only sets actually ticked off count). */-export const loadOfWorkouts = workouts =>+/**+ * Load for finished workouts (only sets actually ticked off count). `pick` narrows that+ * further — the map can then answer "where did the *hard* sets go", which is a different+ * question from where the sets went: a muscle can lead on volume and still never be trained+ * near failure.+ */+export const loadOfWorkouts = (workouts, pick) =>loadOf((workouts || []).flatMap(w =>- (w.entries || []).map(e => ({ id: e.id, sets: (e.sets || []).filter(s => s.done).length }))))+ (w.entries || []).map(e => ({ id: e.id, sets: (e.sets || []).filter(s => s.done && (!pick || pick(s))).length }))))/** Load a routine *would* produce, from its planned set counts. */export const loadOfRoutine = routine =>diff --git a/frontend/src/locales/de.js b/frontend/src/locales/de.jsindex 21c106cbc..998591843 100644--- a/frontend/src/locales/de.js+++ b/frontend/src/locales/de.js@@ -531,4 +531,22 @@ export default {'Easy — warm-up territory': 'Locker — Aufwärmbereich','RIR counts the reps you left; RPE reads the same effort off a 10-point scale — so RPE ≈ 10 − RIR. Pick the one you already think in.': 'RIR zählt die Wiederholungen, die du übrig lässt; RPE liest dieselbe Anstrengung auf einer 10er-Skala ab — also RPE ≈ 10 − RIR. Nimm die Skala, in der du ohnehin denkst.','The highlighted row is where most working sets land. Sets you have already logged keep their own scale, and nothing else reads the value — progression and estimated 1RM are unaffected.': 'Die hervorgehobene Zeile ist der Bereich, in dem die meisten Arbeitssätze landen. Bereits protokollierte Sätze behalten ihre eigene Skala, und sonst liest den Wert nichts — Progression und geschätztes 1RM bleiben unberührt.',+ // --- effort in the stats ---+ 'Effort': 'Anstrengung',+ 'how close to failure': 'wie nah am Muskelversagen',+ 'by hard sets': 'nach harten Sätzen',+ 'Hard': 'Hart',+ 'no hard sets': 'keine harten Sätze',+ 'No hard sets in this period': 'Keine harten Sätze in diesem Zeitraum',+ 'Every muscle group got at least one hard set in this period.': 'Jede Muskelgruppe hat in diesem Zeitraum mindestens einen harten Satz bekommen.',+ 'No rated sets in this period.': 'Keine bewerteten Sätze in diesem Zeitraum.',+ 'average effort': 'durchschnittliche Anstrengung',+ 'at {0} {1} or harder': 'bei {0} {1} oder härter',+ '{0} of {1} finished sets rated': '{0} von {1} erledigten Sätzen bewertet',+ 'Effort per set is switched off — turn it on in Settings to keep rating.': 'Anstrengung pro Satz ist ausgeschaltet — schalte sie in den Einstellungen ein, um weiter zu bewerten.',+ 'Week by week': 'Woche für Woche',+ 'Where the sets land': 'Wo die Sätze landen',+ 'Most working sets belong close to failure without living there — half at the floor and half at the top average out to a healthy-looking middle.': 'Die meisten Arbeitssätze gehören nah ans Muskelversagen, ohne dort zu wohnen — die Hälfte ganz unten und die Hälfte ganz oben mittelt sich zu einem gesund aussehenden Mittelwert.',+ 'Average effort per workout': 'Durchschnittliche Anstrengung pro Training',+ 'A fuller dot means less left in the tank — the same weight at a lower {0} is progress the line alone does not show.': 'Ein vollerer Punkt heißt: weniger im Tank — dasselbe Gewicht bei niedrigerem {0} ist Fortschritt, den die Linie allein nicht zeigt.',}diff --git a/frontend/src/views/Stats.jsx b/frontend/src/views/Stats.jsxindex 01897cc7d..f25b3cd57 100644--- a/frontend/src/views/Stats.jsx+++ b/frontend/src/views/Stats.jsx@@ -2,7 +2,7 @@ import { useState } from 'react'import { useNavigate } from 'react-router-dom'import { useStore } from '../store/useStore.js'import { EXIDX } from '../lib/exercises.js'-import { lastBW, streakWeeks, setLabel, modeOf } from '../lib/history.js'+import { lastBW, streakWeeks, setLabel, modeOf, effortOf } from '../lib/history.js'import { fmtNum, fmtDate, fmtVol, todayISO, weekKey } from '../lib/format.js'import { t } from '../lib/i18n.js'import { bwSheet, goalSheet, calendarSheet, workoutDetailSheet, WorkoutRow, bwDeltaColor } from '../sheets.jsx'@@ -12,26 +12,41 @@ import Icon from '../components/Icon.jsx'import BodyMap, { BodyMapLegend } from '../components/BodyMap.jsx'import { loadOfWorkouts, rankOf, MUSCLE_NAME } from '../lib/muscles.js'import { e1rmSeries, best1RM } from '../lib/onerm.js'+import {+ hasEffort, displayScale, scaleName, toScale, avgRir, effortSummary, effortWeeks,+ effortHistogram, isHardSet, HARD_RIR+} from '../lib/effort.js'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 MuscleBalance({ S }) {const [win, setWin] = useState(7)+ const [hard, setHard] = useState(false)const [sel, setSel] = useState(null)const now = Date.now()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 load = loadOfWorkouts(inWin)+ // 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+ // would just be empty and read as "you trained nothing".+ 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 { worked, missed } = rankOf(load)const top = worked.slice(0, 4)const max = worked.length ? load[worked[0]] : 0const sets = m => Math.round((load[m] || 0) * 10) / 10return <div className="card">- <h2>{t('Muscle balance')} <span className="dim" style={{ textTransform: 'none', letterSpacing: 0 }}>· {t('by sets worked')}</span></h2>+ <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 ? <>@@ -40,23 +55,80 @@ function MuscleBalance({ S }) {<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)) : t('not trained')}</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) + '%' }} /></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 }}>{t('Not trained in this period')}</h4>+ <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 }}>{t('Every muscle group got some work in this period.')}</div>}+ <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>}+// How hard the training was — the half of the picture a volume chart cannot show. Everything+// is computed in RIR (lib/effort.js) and converted to whichever scale this profile reads.+// Every number carries how much of the training it speaks for: rating is optional and off by+// default, so a partly rated history is the normal case, and an average without its+// denominator would quietly speak for sets that were never rated.+function EffortCard({ S }) {+ const [win, setWin] = useState(90)+ const kind = displayScale(S)+ const hd = scaleName(kind)+ const sum = effortSummary(S, win)+ const weeks = effortWeeks(S, win)+ const hist = effortHistogram(S, win)+ const maxBin = Math.max(1, ...hist.map(b => b.n))+ // The week's set count rides along in the tooltip, because the pair is the reading:+ // volume up with effort up is fatigue piling up, volume up with effort flat is adaptation.+ const pts = weeks.map(w => ({ t: w.t, y: toScale(kind, w.rir), note: t('{0} sets', w.sets) }))+ // Bins run hardest-first in both scales: RIR 0 and RPE 10 are the same set.+ const binLabel = b => kind === 'rpe' ? (b.tail ? '≤ 6' : String(10 - b.rir)) : (b.tail ? b.rir + '+' : String(b.rir))++ return <div className="card">+ <h2>{t('Effort')} <span className="dim" style={{ textTransform: 'none', letterSpacing: 0 }}>· {t('how close to failure')}</span></h2>+ <Segmented className="seg-range" value={win} onChange={setWin}+ options={[{ value: 30, label: '30d' }, { value: 90, label: '90d' }, { value: 365, label: '1Y' }, { value: 0, label: t('All') }]} />+ {sum.rated === 0 ? <div className="muted small">{t('No rated sets in this period.')}</div> : <>+ <div className="row between" style={{ alignItems: 'flex-end', gap: 12 }}>+ <div>+ <div className="stat-v">{sum.avg == null ? '—' : fmtNum(toScale(kind, sum.avg)) + ' ' + hd}</div>+ <div className="small dim">{t('average effort')}</div>+ </div>+ <div style={{ textAlign: 'right' }}>+ <div className="stat-v" style={{ color: 'var(--yellow)' }}>{sum.hardPct == null ? '—' : Math.round(sum.hardPct * 100) + '%'}</div>+ <div className="small dim">{t('at {0} {1} or harder', hd, fmtNum(toScale(kind, HARD_RIR)))}</div>+ </div>+ </div>+ <div className="small dim" style={{ marginTop: 8 }}>{t('{0} of {1} finished sets rated', sum.rated, sum.done)}</div>+ {effortOf(S) === 'none' && <div className="small" style={{ color: 'var(--yellow)', marginTop: 4 }}>+ {t('Effort per set is switched off — turn it on in Settings to keep rating.')}+ </div>}+ {pts.length > 1 && <>+ <h4 className="sec" style={{ marginTop: 12 }}>{t('Week by week')}</h4>+ <div className="chart"><LineChart points={pts} h={140} unit={hd} color="var(--yellow)" invert={kind === 'rir'} /></div>+ </>}+ <h4 className="sec" style={{ marginTop: 12 }}>{t('Where the sets land')}</h4>+ {hist.map(b => <div key={b.rir} className="mrow">+ <span className="nm">{hd} {binLabel(b)}</span>+ <span className="bar"><i style={{ width: Math.round(b.n / maxBin * 100) + '%', background: b.rir <= HARD_RIR ? 'var(--yellow)' : 'var(--label-3)' }} /></span>+ <span className="v">{b.n ? b.n + ' · ' + Math.round(b.pct * 100) + '%' : '—'}</span>+ </div>)}+ <div className="small dim" style={{ marginTop: 8 }}>+ {t('Most working sets belong close to failure without living there — half at the floor and half at the top average out to a healthy-looking middle.')}+ </div>+ </>}+ </div>+}+// Stats = the analytics hub: all charts, progress and history live here.export default function Stats() {const nav = useNavigate()@@ -65,6 +137,9 @@ export default function Stats() {const [exId, setExId] = useState(null)const [exMetric, setExMetric] = useState('top')const now = Date.now()+ const anyEffort = hasEffort(S)+ const kind = displayScale(S)+ const hd = scaleName(kind)const bwPts = S.bodyweight.filter(b => range === 0 || (b.t || new Date(b.d).getTime()) > now - range * 86400000).map(b => ({ t: b.t || new Date(b.d).getTime(), y: b.w, d: b.d }))@@ -101,7 +176,23 @@ export default function Stats() {const e1Pts = curEx ? e1rmSeries(S, curEx) : []const e1Best = curEx ? best1RM(S, curEx) : nullconst showE1 = e1Pts.length > 0+ // Effort on this exercise, per session. It rides on the top-set curve as well as having a+ // curve of its own, because the two only mean something together: the same weight moved+ // with more left in the tank is progress a weight-only chart draws as a flat line.+ const exRir = exPts.map(p => avgRir(p.sets))+ const showEff = exRir.filter(v => v != null).length >= 3+ const effPts = exPts.map((p, i) => (exRir[i] == null ? null : { t: p.t, y: toScale(kind, exRir[i]), d: p.d })).filter(Boolean)const onE1 = showE1 && exMetric === 'e1rm'+ const onEff = showEff && exMetric === 'effort'+ const topPts = exPts.map((p, i) => ({+ t: p.t, y: p.y, d: p.d,+ // 0 RIR (nothing left) is a full dot, 4+ a faint one; unrated sessions keep the plain line.+ m: exRir[i] == null ? null : 1 - Math.min(4, Math.max(0, exRir[i])) / 4,+ note: exRir[i] == null ? undefined : hd + ' ' + fmtNum(toScale(kind, exRir[i]))+ }))+ const exOpts = [{ value: 'top', label: t('Top set') }]+ if (showE1) exOpts.push({ value: 'e1rm', label: t('Est. 1RM') })+ if (showEff) exOpts.push({ value: 'effort', label: t('Effort') })return <><div className="hdr"><div><h1>{t('Stats')}</h1><div className="sub">{t('Progress & history')}</div></div>@@ -120,6 +211,7 @@ export default function Stats() {</div>{S.workouts.length > 0 && <MuscleBalance S={S} />}+ {anyEffort && <EffortCard S={S} />}<div className="cols"><div className="card">@@ -142,18 +234,24 @@ export default function Stats() {<SelectRow title={t('Exercise')} sheetTitle={t('Exercise progress')} value={curEx} onChange={setExId}options={exHist.map(id => ({ value: id, label: EXIDX[id].n }))} /></div>- {showE1 && <Segmented className="seg-range" value={exMetric} onChange={setExMetric}- options={[{ value: 'top', label: t('Top set') }, { value: 'e1rm', label: t('Est. 1RM') }]} />}- <div className="chart"><LineChart points={(onE1 ? e1Pts : exPts).map(p => ({ t: p.t, y: p.y, d: p.d }))} h={150} unit={exUnit} color="var(--blue)" /></div>+ {exOpts.length > 1 && <Segmented className="seg-range" value={onEff ? 'effort' : onE1 ? 'e1rm' : 'top'} onChange={setExMetric} options={exOpts} />}+ <div className="chart">+ {onEff+ ? <LineChart points={effPts} h={150} unit={hd} color="var(--yellow)" invert={kind === 'rir'} />+ : <LineChart points={onE1 ? e1Pts.map(p => ({ t: p.t, y: p.y, d: p.d })) : topPts} h={150} unit={exUnit} color="var(--blue)" />}+ </div><div style={{ marginTop: 8 }}>{exList.map((p, i) => <div key={i} className="row between small" style={{ padding: '6px 0', borderBottom: 'var(--hair) solid var(--sep)' }}><span className="muted">{fmtDate(p.d, true)}</span><span>{p.sets.map(s => setLabel(curEx, s, p.target)).join(' ')}</span></div>)}</div><div className="small dim" style={{ marginTop: 8 }}>- {onE1 ? t('Estimated 1RM per workout') : curCardio ? t('Top speed per workout') : curTimed ? t('Longest hold per workout') : t('Best set weight per workout')} · {t('Best:')}- {' '}<b className="accent">{fmtNum(onE1 ? e1Best.est : exBest)} {onE1 ? S.unit : exUnit}</b>+ {onEff ? t('Average effort per workout') : onE1 ? t('Estimated 1RM per workout') : curCardio ? t('Top speed per workout') : curTimed ? t('Longest hold per workout') : t('Best set weight per workout')}+ {onEff ? '' : <> · {t('Best:')}{' '}<b className="accent">{fmtNum(onE1 ? e1Best.est : exBest)} {onE1 ? S.unit : exUnit}</b></>}</div>- {showE1 && <div className="small dim" style={{ marginTop: 4 }}>+ {onE1 && <div className="small dim" style={{ marginTop: 4 }}>{t('Best estimate from {0} on {1} — an estimate, not a tested max.', fmtNum(e1Best.w) + ' ' + S.unit + ' × ' + e1Best.r, fmtDate(e1Best.d, true))}</div>}+ {!onEff && !onE1 && showEff && <div className="small dim" style={{ marginTop: 4 }}>+ {t('A fuller dot means less left in the tank — the same weight at a lower {0} is progress the line alone does not show.', hd)}+ </div>}</> : <div className="muted small">{t('Finish your first workout to see progress curves here.')}</div>}</div></div>