diff --git a/frontend/src/lib/exercise-history.js b/frontend/src/lib/exercise-history.js new file mode 100644 index 0000000..e1169c6 --- /dev/null +++ b/frontend/src/lib/exercise-history.js @@ -0,0 +1,83 @@ +import { metricModeForEntry, metricRowsForEntry, bestWeightForEntry, modeOf } from './history.js' +import { extraVolumeOf } from './workout-model.js' +import { bestSetOf } from './onerm.js' + +// One exercise's past, read back for the history sheet (issue #43): a chart series and the +// last few sessions, derived in a single pass over the log so the sheet can memoise the +// result and never rescan on a re-render. +// +// The chart plots ONE number per session, chosen the way Stats does it: +// reps — the heaviest completed work set (metric 'weight'); an exercise never loaded +// (pull-ups, push-ups) plots its best rep count instead (metric 'reps'), because +// that is the thing improving +// time — the longest completed hold, in seconds (metric 'sec') +// cardio — the minutes logged that session (metric 'min') +// The mode is the one the exercise was logged in most recently; a session logged in another +// mode still appears in the list (its sets are labelled by their own target) but gets no point +// and no value, so the curve never mixes seconds with kilos. +// +// Warm-up rows are excluded from every number here, as everywhere else. + +export const HISTORY_SESSIONS = 10 + +const startOf = w => (Number.isFinite(w.start) ? w.start : new Date(w.d + 'T12:00:00').getTime()) + +// Volume of the exercise in one session: main set plus its drops/bursts, reps mode only — +// there is no honest tonnage for a hold or a run. +const entryVolume = rows => rows.reduce((v, s) => v + (s.w || 0) * (s.r || 0) + extraVolumeOf(s), 0) + +export function exerciseHistory(S, exId, { limit = HISTORY_SESSIONS } = {}) { + const workouts = S?.workouts || [] + // Chronological pairs of (workout, entry); the sort covers backfilled sessions, which are + // inserted by date rather than appended. + const logged = [] + workouts.forEach(w => { + const en = (w.entries || []).find(e => e.id === exId) + if (!en) return + const mode = metricModeForEntry(en) + if (!mode) return + const rows = metricRowsForEntry(en, mode) + if (rows.length) logged.push({ w, en, mode, rows }) + }) + logged.sort((a, b) => startOf(a.w) - startOf(b.w)) + + const empty = { mode: modeOf({ id: exId }), metric: 'weight', best: 0, prId: null, total: 0, sessions: [], points: [], e1rmPoints: [] } + if (!logged.length) return empty + + const mode = logged[logged.length - 1].mode + const repsOnly = mode === 'reps' && !logged.some(l => l.mode === 'reps' && bestWeightForEntry(l.en) > 0) + const metric = mode === 'cardio' ? 'min' : mode === 'time' ? 'sec' : repsOnly ? 'reps' : 'weight' + const valueOf = ({ en, rows }) => { + if (metric === 'min') return rows.reduce((a, s) => a + (Number(s.min) || 0), 0) + if (metric === 'sec') return Math.max(0, ...rows.map(s => Number(s.sec) || 0)) + if (metric === 'reps') return Math.max(0, ...rows.map(s => Number(s.r) || 0)) + return bestWeightForEntry(en) + } + + let best = 0, prId = null + const sessions = [], points = [], e1rmPoints = [] + logged.forEach(({ w, en, mode: m, rows }) => { + const same = m === mode + const value = same ? valueOf({ en, rows }) : null + const e1rm = m === 'reps' ? (bestSetOf(en)?.est ?? null) : null + const t = startOf(w) + // "PR" goes on the session that first reached the all-time best, not on every session + // that later matched it — one marker says where the record was set. + if (value != null && value > best) { best = value; prId = w.id } + if (value != null && value > 0) points.push({ t, d: w.d, y: value, e1rm }) + if (e1rm != null) e1rmPoints.push({ t, d: w.d, y: e1rm }) + sessions.push({ + id: w.id, d: w.d, t, mode: m, target: en.target || null, sets: rows, value, e1rm, + volume: m === 'reps' ? entryVolume(rows) : null, + }) + }) + // The "first reached" rule only holds for records above zero: a bodyweight session with + // no weight logged is not a PR of anything. + if (best <= 0) prId = null + + return { + mode, metric, best, prId, total: sessions.length, + sessions: sessions.slice(-limit).reverse().map(s => ({ ...s, pr: s.id === prId })), + points, e1rmPoints, + } +} diff --git a/frontend/src/lib/exercise-history.test.js b/frontend/src/lib/exercise-history.test.js new file mode 100644 index 0000000..a6b8e21 --- /dev/null +++ b/frontend/src/lib/exercise-history.test.js @@ -0,0 +1,112 @@ +import { describe, it, expect } from 'vitest' +import { exerciseHistory, HISTORY_SESSIONS } from './exercise-history.js' +import { estimate1RM } from './onerm.js' + +const DAY = 86400000 +const T0 = Date.UTC(2026, 0, 5, 10) +const iso = i => new Date(T0 + i * DAY).toISOString().slice(0, 10) + +// One workout on day `i` with a single bench entry made of the given rows. +const session = (i, rows, extra = {}) => ({ + id: 'w' + i, d: iso(i), start: T0 + i * DAY, entries: [{ id: 'bench', target: { mode: 'reps' }, sets: rows, ...extra }], +}) +const work = (w, r, done = true) => ({ w, r, done }) +const warm = (w, r) => ({ w, r, done: true, phase: 'warmup' }) + +describe('exerciseHistory', () => { + it('is empty when the exercise was never logged', () => { + const S = { workouts: [session(0, [work(60, 5)])] } + expect(exerciseHistory(S, 'squat')).toMatchObject({ total: 0, best: 0, prId: null, sessions: [], points: [] }) + expect(exerciseHistory({ workouts: [] }, 'bench').total).toBe(0) + expect(exerciseHistory({}, 'bench').total).toBe(0) + }) + + it('lists sessions newest first with their work sets, value and volume', () => { + const S = { workouts: [session(0, [work(60, 5), work(60, 5)]), session(2, [work(65, 5), work(65, 4)])] } + const h = exerciseHistory(S, 'bench') + expect(h.mode).toBe('reps') + expect(h.metric).toBe('weight') + expect(h.total).toBe(2) + expect(h.sessions.map(s => s.d)).toEqual([iso(2), iso(0)]) + expect(h.sessions[0]).toMatchObject({ value: 65, volume: 65 * 9, target: { mode: 'reps' } }) + expect(h.sessions[0].sets).toHaveLength(2) + expect(h.sessions[1]).toMatchObject({ value: 60, volume: 600 }) + // the chart stays chronological + expect(h.points.map(p => [p.d, p.y])).toEqual([[iso(0), 60], [iso(2), 65]]) + }) + + it('leaves warm-ups and unfinished rows out of every number', () => { + const S = { workouts: [session(0, [warm(40, 8), work(60, 5), work(100, 5, false)])] } + const h = exerciseHistory(S, 'bench') + expect(h.best).toBe(60) + expect(h.sessions[0].sets).toEqual([work(60, 5)]) + expect(h.sessions[0].volume).toBe(300) + expect(h.sessions[0].e1rm).toBe(estimate1RM(60, 5)) + }) + + it('marks the PR on the session that first reached the best weight, once', () => { + const S = { workouts: [ + session(0, [work(60, 5)]), session(1, [work(70, 5)]), session(2, [work(65, 5)]), session(3, [work(70, 3)]), + ] } + const h = exerciseHistory(S, 'bench') + expect(h.best).toBe(70) + expect(h.prId).toBe('w1') + expect(h.sessions.filter(s => s.pr).map(s => s.id)).toEqual(['w1']) + }) + + it('keeps the last ten sessions in the list but every session on the chart', () => { + const S = { workouts: Array.from({ length: 14 }, (_, i) => session(i, [work(50 + i, 5)])) } + const h = exerciseHistory(S, 'bench') + expect(h.total).toBe(14) + expect(h.sessions).toHaveLength(HISTORY_SESSIONS) + expect(h.sessions[0].d).toBe(iso(13)) + expect(h.sessions.at(-1).d).toBe(iso(4)) + expect(h.points).toHaveLength(14) + expect(h.e1rmPoints).toHaveLength(14) + // the record lives outside the listed window, so no listed session carries the marker + expect(h.prId).toBe('w13') + expect(exerciseHistory(S, 'bench', { limit: 3 }).sessions).toHaveLength(3) + }) + + it('orders backfilled sessions by date, not by position in the log', () => { + const S = { workouts: [session(5, [work(60, 5)]), { ...session(1, [work(80, 5)]), start: undefined }] } + const h = exerciseHistory(S, 'bench') + expect(h.points.map(p => p.d)).toEqual([iso(1), iso(5)]) + expect(h.sessions.map(s => s.d)).toEqual([iso(5), iso(1)]) + expect(h.prId).toBe('w1') + }) + + it('plots reps for an exercise that was never loaded', () => { + const S = { workouts: [session(0, [work(0, 8)]), session(1, [work(0, 10), work(0, 9)])] } + const h = exerciseHistory(S, 'bench') + expect(h.metric).toBe('reps') + expect(h.points.map(p => p.y)).toEqual([8, 10]) + expect(h.best).toBe(10) + expect(h.prId).toBe('w1') + }) + + it('plots the longest hold for timed work and the minutes for cardio', () => { + const hold = i => ({ id: 'h' + i, d: iso(i), start: T0 + i * DAY, entries: [{ id: 'plank', target: { mode: 'time' }, sets: [{ sec: 40 + i * 10, done: true }, { sec: 30, done: true }] }] }) + const run = i => ({ id: 'r' + i, d: iso(i), start: T0 + i * DAY, entries: [{ id: 'run', target: { mode: 'cardio' }, sets: [{ min: 20, speed: 10, done: true }, { min: 5, speed: 12, done: true }] }] }) + const S = { workouts: [hold(0), hold(1), run(0)] } + const plank = exerciseHistory(S, 'plank') + expect(plank).toMatchObject({ mode: 'time', metric: 'sec', best: 50, prId: 'h1' }) + expect(plank.points.map(p => p.y)).toEqual([40, 50]) + expect(plank.sessions[0].volume).toBeNull() + expect(plank.e1rmPoints).toEqual([]) + const cardio = exerciseHistory(S, 'run') + expect(cardio).toMatchObject({ mode: 'cardio', metric: 'min', best: 25 }) + expect(cardio.points[0].y).toBe(25) + }) + + it('gives a session logged in another mode no point, but keeps it in the list', () => { + const S = { workouts: [ + { id: 'a', d: iso(0), start: T0, entries: [{ id: 'x', target: { mode: 'time' }, sets: [{ sec: 30, done: true }] }] }, + { id: 'b', d: iso(1), start: T0 + DAY, entries: [{ id: 'x', target: { mode: 'reps' }, sets: [work(20, 10)] }] }, + ] } + const h = exerciseHistory(S, 'x') + expect(h.mode).toBe('reps') + expect(h.points).toHaveLength(1) + expect(h.sessions.map(s => [s.id, s.value])).toEqual([['b', 20], ['a', null]]) + }) +}) diff --git a/frontend/src/lib/pt-br-locale.test.js b/frontend/src/lib/pt-br-locale.test.js index a916f6a..33a297a 100644 --- a/frontend/src/lib/pt-br-locale.test.js +++ b/frontend/src/lib/pt-br-locale.test.js @@ -27,11 +27,11 @@ describe('Brazilian Portuguese locale', () => { .sort(byCodeUnit) const fingerprint = createHash('sha256').update(JSON.stringify(inherited)).digest('hex') - expect(Object.keys(PT_BR_OVERRIDES)).toHaveLength(620) - expect(inherited).toHaveLength(598) + expect(Object.keys(PT_BR_OVERRIDES)).toHaveLength(621) + expect(inherited).toHaveLength(602) // If this fails, review the changed keys and wording before accepting a new hash. From // frontend/: node scripts/pt-br-inheritance-fingerprint.mjs --list - expect(fingerprint, 'pt-PT inheritance changed; review the inherited pt-BR wording').toBe('5f1f5dcac5d51dd96f9d1e3506c6a65fd098071b971739686f3cc0360cca35ec') + expect(fingerprint, 'pt-PT inheritance changed; review the inherited pt-BR wording').toBe('fb29e798de972bf0d5a8477958b0a2836c57b2d32f0248847c4d93ebba6813c4') }) test('does not leak European Portuguese UI terms', () => { diff --git a/frontend/src/locales/de.js b/frontend/src/locales/de.js index b2f0cd0..aa8604b 100644 --- a/frontend/src/locales/de.js +++ b/frontend/src/locales/de.js @@ -577,6 +577,11 @@ export default { // --- v1.2.2: timed sets, progression, estimated 1RM (#16 #17 #18) --- 'Top set': 'Bester Satz', 'Est. 1RM': 'gesch. 1RM', + 'No sessions logged yet': 'Noch keine Einheiten eingetragen', + '{0} session': '{0} Einheit', + '{0} sessions': '{0} Einheiten', + 'Exercise history': 'Übungsverlauf', + 'Last {0} sessions': 'Letzte {0} Einheiten', 'Estimated 1RM': 'Geschätztes 1RM', 'Estimated 1RM per workout': 'Geschätztes 1RM pro Training', 'Best estimate from {0} on {1} — an estimate, not a tested max.': 'Beste Schätzung aus {0} am {1} — eine Schätzung, kein getesteter Max-Wert.', diff --git a/frontend/src/locales/es.js b/frontend/src/locales/es.js index 01e3b64..441b27a 100644 --- a/frontend/src/locales/es.js +++ b/frontend/src/locales/es.js @@ -559,6 +559,11 @@ export default { // --- v1.2.2: timed sets, progression, estimated 1RM (#16 #17 #18) --- 'Top set': 'Mejor serie', 'Est. 1RM': '1RM est.', + 'No sessions logged yet': 'Aún no hay sesiones registradas', + '{0} session': '{0} sesión', + '{0} sessions': '{0} sesiones', + 'Exercise history': 'Historial del ejercicio', + 'Last {0} sessions': 'Últimas {0} sesiones', 'Estimated 1RM': '1RM estimado', 'Estimated 1RM per workout': '1RM estimado por entrenamiento', 'Best estimate from {0} on {1} — an estimate, not a tested max.': 'Mejor estimación a partir de {0} el {1}: una estimación, no un máximo probado.', diff --git a/frontend/src/locales/fr.js b/frontend/src/locales/fr.js index 6879187..9da4b73 100644 --- a/frontend/src/locales/fr.js +++ b/frontend/src/locales/fr.js @@ -559,6 +559,11 @@ export default { // --- v1.2.2: timed sets, progression, estimated 1RM (#16 #17 #18) --- 'Top set': 'Meilleure série', 'Est. 1RM': '1RM est.', + 'No sessions logged yet': 'Aucune séance enregistrée pour l’instant', + '{0} session': '{0} séance', + '{0} sessions': '{0} séances', + 'Exercise history': 'Historique de l’exercice', + 'Last {0} sessions': '{0} dernières séances', 'Estimated 1RM': '1RM estimé', 'Estimated 1RM per workout': '1RM estimé par séance', 'Best estimate from {0} on {1} — an estimate, not a tested max.': 'Meilleure estimation d’après {0} le {1} — une estimation, pas un max testé.', diff --git a/frontend/src/locales/hi.js b/frontend/src/locales/hi.js index 96a1a2f..ee362a0 100644 --- a/frontend/src/locales/hi.js +++ b/frontend/src/locales/hi.js @@ -559,6 +559,11 @@ export default { // --- v1.2.2: timed sets, progression, estimated 1RM (#16 #17 #18) --- 'Top set': 'सर्वश्रेष्ठ सेट', 'Est. 1RM': 'अनु. 1RM', + 'No sessions logged yet': 'अभी तक कोई सत्र दर्ज नहीं', + '{0} session': '{0} सत्र', + '{0} sessions': '{0} सत्र', + 'Exercise history': 'व्यायाम इतिहास', + 'Last {0} sessions': 'पिछले {0} सत्र', 'Estimated 1RM': 'अनुमानित 1RM', 'Estimated 1RM per workout': 'प्रति वर्कआउट अनुमानित 1RM', 'Best estimate from {0} on {1} — an estimate, not a tested max.': '{1} को {0} से सर्वश्रेष्ठ अनुमान — यह अनुमान है, परखा गया अधिकतम नहीं।', diff --git a/frontend/src/locales/hu.js b/frontend/src/locales/hu.js index c2da363..ae9f983 100644 --- a/frontend/src/locales/hu.js +++ b/frontend/src/locales/hu.js @@ -543,6 +543,11 @@ export default { // --- v1.2.2: timed sets, progression, estimated 1RM (#16 #17 #18) --- 'Top set': 'Legjobb sorozat', 'Est. 1RM': 'becs. 1RM', + 'No sessions logged yet': 'Még nincs rögzített edzés', + '{0} session': '{0} edzés', + '{0} sessions': '{0} edzés', + 'Exercise history': 'Gyakorlat előzményei', + 'Last {0} sessions': 'Utolsó {0} edzés', 'Estimated 1RM': 'Becsült 1RM', 'Estimated 1RM per workout': 'Becsült 1RM edzésenként', 'Best estimate from {0} on {1} — an estimate, not a tested max.': 'Legjobb becslés innen: {0}, ekkor: {1} — ez egy becslés, nem tesztelt maximum.', diff --git a/frontend/src/locales/it.js b/frontend/src/locales/it.js index 497b575..65369b1 100644 --- a/frontend/src/locales/it.js +++ b/frontend/src/locales/it.js @@ -559,6 +559,11 @@ export default { // --- v1.2.2: timed sets, progression, estimated 1RM (#16 #17 #18) --- 'Top set': 'Serie migliore', 'Est. 1RM': '1RM stim.', + 'No sessions logged yet': 'Nessuna sessione registrata', + '{0} session': '{0} sessione', + '{0} sessions': '{0} sessioni', + 'Exercise history': 'Storico dell’esercizio', + 'Last {0} sessions': 'Ultime {0} sessioni', 'Estimated 1RM': '1RM stimato', 'Estimated 1RM per workout': '1RM stimato per allenamento', 'Best estimate from {0} on {1} — an estimate, not a tested max.': 'Stima migliore da {0} il {1} — una stima, non un massimale testato.', diff --git a/frontend/src/locales/ko.js b/frontend/src/locales/ko.js index 6b3d8d2..fdae305 100644 --- a/frontend/src/locales/ko.js +++ b/frontend/src/locales/ko.js @@ -559,6 +559,11 @@ export default { // --- v1.2.2: timed sets, progression, estimated 1RM (#16 #17 #18) --- 'Top set': '최고 세트', 'Est. 1RM': '추정 1RM', + 'No sessions logged yet': '기록된 세션이 아직 없습니다', + '{0} session': '세션 {0}회', + '{0} sessions': '세션 {0}회', + 'Exercise history': '운동 기록', + 'Last {0} sessions': '최근 {0}회 세션', 'Estimated 1RM': '추정 1RM', 'Estimated 1RM per workout': '운동별 추정 1RM', 'Best estimate from {0} on {1} — an estimate, not a tested max.': '{1}의 {0} 기준 최고 추정치 — 실제로 측정한 최대치가 아닌 추정값입니다.', diff --git a/frontend/src/locales/pl.js b/frontend/src/locales/pl.js index 1d136a9..aca82f8 100644 --- a/frontend/src/locales/pl.js +++ b/frontend/src/locales/pl.js @@ -559,6 +559,11 @@ export default { // --- v1.2.2: timed sets, progression, estimated 1RM (#16 #17 #18) --- 'Top set': 'Najlepsza seria', 'Est. 1RM': 'Szac. 1RM', + 'No sessions logged yet': 'Brak zapisanych sesji', + '{0} session': '{0} sesja', + '{0} sessions': '{0} sesji', + 'Exercise history': 'Historia ćwiczenia', + 'Last {0} sessions': 'Ostatnie {0} sesji', 'Estimated 1RM': 'Szacowany 1RM', 'Estimated 1RM per workout': 'Szacowany 1RM na trening', 'Best estimate from {0} on {1} — an estimate, not a tested max.': 'Najlepsze oszacowanie z {0} dnia {1} — to szacunek, a nie zmierzony maks.', diff --git a/frontend/src/locales/pt-BR.js b/frontend/src/locales/pt-BR.js index 9480788..00e2463 100644 --- a/frontend/src/locales/pt-BR.js +++ b/frontend/src/locales/pt-BR.js @@ -4,6 +4,7 @@ import pt from './pt.js' export const PT_BR_OVERRIDES = { + 'No sessions logged yet': 'Ainda não há sessões registradas', 'What should change?': 'O que deve mudar?', 'Coach is thinking…': 'O Coach está pensando…', 'Message the Coach…': 'Escreva ao Coach…', diff --git a/frontend/src/locales/pt.js b/frontend/src/locales/pt.js index b238688..63e9bd3 100644 --- a/frontend/src/locales/pt.js +++ b/frontend/src/locales/pt.js @@ -559,6 +559,11 @@ export default { // --- v1.2.2: timed sets, progression, estimated 1RM (#16 #17 #18) --- 'Top set': 'Melhor série', 'Est. 1RM': '1RM est.', + 'No sessions logged yet': 'Ainda não há sessões registadas', + '{0} session': '{0} sessão', + '{0} sessions': '{0} sessões', + 'Exercise history': 'Histórico do exercício', + 'Last {0} sessions': 'Últimas {0} sessões', 'Estimated 1RM': '1RM estimado', 'Estimated 1RM per workout': '1RM estimado por treino', 'Best estimate from {0} on {1} — an estimate, not a tested max.': 'Melhor estimativa a partir de {0} em {1} — uma estimativa, não um máximo testado.', diff --git a/frontend/src/locales/ru.js b/frontend/src/locales/ru.js index f05aa66..6eea327 100644 --- a/frontend/src/locales/ru.js +++ b/frontend/src/locales/ru.js @@ -559,6 +559,11 @@ export default { // --- v1.2.2: timed sets, progression, estimated 1RM (#16 #17 #18) --- 'Top set': 'Лучший подход', 'Est. 1RM': 'Расч. 1ПМ', + 'No sessions logged yet': 'Записанных сессий пока нет', + '{0} session': '{0} сессия', + '{0} sessions': '{0} сессий', + 'Exercise history': 'История упражнения', + 'Last {0} sessions': 'Последние {0} сессий', 'Estimated 1RM': 'Расчётный 1ПМ', 'Estimated 1RM per workout': 'Расчётный 1ПМ за тренировку', 'Best estimate from {0} on {1} — an estimate, not a tested max.': 'Лучшая оценка по {0} от {1} — это расчёт, а не проверенный максимум.', diff --git a/frontend/src/locales/th.js b/frontend/src/locales/th.js index e6fb2e1..22cbd3f 100644 --- a/frontend/src/locales/th.js +++ b/frontend/src/locales/th.js @@ -543,6 +543,11 @@ export default { // --- v1.2.2: timed sets, progression, estimated 1RM (#16 #17 #18) --- 'Top set': 'เซ็ตที่หนักที่สุด', 'Est. 1RM': '1RM โดยประมาณ', + 'No sessions logged yet': 'ยังไม่มีการบันทึกเซสชัน', + '{0} session': '{0} เซสชัน', + '{0} sessions': '{0} เซสชัน', + 'Exercise history': 'ประวัติท่าออกกำลังกาย', + 'Last {0} sessions': '{0} เซสชันล่าสุด', 'Estimated 1RM': '1RM โดยประมาณ', 'Estimated 1RM per workout': '1RM โดยประมาณต่อครั้ง', 'Best estimate from {0} on {1} — an estimate, not a tested max.': 'ประมาณการดีที่สุดจาก {0} เมื่อ {1} — เป็นค่าประมาณ ไม่ใช่ค่าที่ทดสอบจริง', diff --git a/frontend/src/locales/tr.js b/frontend/src/locales/tr.js index a3d5fb9..5c0f2a9 100644 --- a/frontend/src/locales/tr.js +++ b/frontend/src/locales/tr.js @@ -559,6 +559,11 @@ export default { // --- v1.2.2: timed sets, progression, estimated 1RM (#16 #17 #18) --- 'Top set': 'En iyi set', 'Est. 1RM': 'Tah. 1RM', + 'No sessions logged yet': 'Henüz kayıtlı seans yok', + '{0} session': '{0} seans', + '{0} sessions': '{0} seans', + 'Exercise history': 'Egzersiz geçmişi', + 'Last {0} sessions': 'Son {0} seans', 'Estimated 1RM': 'Tahmini 1RM', 'Estimated 1RM per workout': 'Antrenman başına tahmini 1RM', 'Best estimate from {0} on {1} — an estimate, not a tested max.': '{1} tarihli {0} setinden en iyi tahmin — test edilmiş bir maksimum değil, tahmin.', diff --git a/frontend/src/locales/zh.js b/frontend/src/locales/zh.js index 911e3d2..e13ecf0 100644 --- a/frontend/src/locales/zh.js +++ b/frontend/src/locales/zh.js @@ -559,6 +559,11 @@ export default { // --- v1.2.2: timed sets, progression, estimated 1RM (#16 #17 #18) --- 'Top set': '最佳组', 'Est. 1RM': '预估 1RM', + 'No sessions logged yet': '尚未记录任何训练', + '{0} session': '{0} 次训练', + '{0} sessions': '{0} 次训练', + 'Exercise history': '动作历史', + 'Last {0} sessions': '最近 {0} 次训练', 'Estimated 1RM': '预估 1RM', 'Estimated 1RM per workout': '每次训练的预估 1RM', 'Best estimate from {0} on {1} — an estimate, not a tested max.': '基于 {1} 的 {0} 得出的最佳预估——这是推算值,不是实测极限。', diff --git a/frontend/src/sheets.history.test.jsx b/frontend/src/sheets.history.test.jsx new file mode 100644 index 0000000..5967ae2 --- /dev/null +++ b/frontend/src/sheets.history.test.jsx @@ -0,0 +1,91 @@ +// @vitest-environment happy-dom +// The history sheet (issue #43) is the one place the workout screen answers "what did I do +// on this last time, and the time before" — worth pinning that it reads the log newest +// first, labels sets the way the rest of the app does, and does not pretend an exercise +// with no sessions has a curve. +import React, { act } from 'react' +import { afterEach, beforeEach, describe, expect, it } from 'vitest' +import { createRoot } from 'react-dom/client' +import { useStore } from './store/useStore.js' +import { useUI } from './store/useUI.js' +import { exerciseHistorySheet, exerciseDetailSheet } from './sheets.jsx' +import { EXIDX } from './lib/exercises.js' + +const mounted = [] + +function renderTop() { + const sheet = useUI.getState().sheets.at(-1) + const host = document.createElement('div') + document.body.appendChild(host) + const root = createRoot(host) + mounted.push(root) + act(() => root.render(sheet.render(() => useUI.getState().closeSheet(sheet.id)))) + return host +} + +const EX = Object.keys(EXIDX).find(id => (EXIDX[id].bp || '') !== 'cardio' && !EXIDX[id].custom) +const DAY = 86400000 +const T0 = Date.UTC(2026, 2, 2, 9) +const iso = i => new Date(T0 + i * DAY).toISOString().slice(0, 10) +const session = (i, rows) => ({ + id: 'w' + i, d: iso(i), start: T0 + i * DAY, end: T0 + i * DAY + 3600000, name: 'Push', vol: 0, + entries: [{ id: EX, target: { mode: 'reps', bodyweight: false }, sets: rows }], +}) + +beforeEach(() => { + globalThis.IS_REACT_ACT_ENVIRONMENT = true + useUI.setState({ sheets: [], toastMsg: '' }) + useStore.setState(s => ({ S: { ...s.S, unit: 'kg', workouts: [], active: null } })) + document.body.innerHTML = '' +}) + +afterEach(() => { + act(() => { mounted.splice(0).forEach(root => root.unmount()) }) +}) + +describe('exercise history sheet', () => { + it('shows an empty state instead of a chart when nothing was logged', () => { + exerciseHistorySheet(EX) + const host = renderTop() + expect(host.querySelector('.empty').textContent).toContain('No sessions logged yet') + expect(host.querySelector('.chart')).toBeNull() + }) + + it('lists sessions newest first with labelled sets, volume and one PR marker', () => { + useStore.setState(s => ({ S: { ...s.S, workouts: [ + session(0, [{ w: 40, r: 8, done: true, phase: 'warmup' }, { w: 60, r: 5, done: true }, { w: 60, r: 5, done: true }]), + session(2, [{ w: 70, r: 5, done: true }]), + session(4, [{ w: 70, r: 3, done: true }, { w: 90, r: 1, done: false }]), + ] } })) + exerciseHistorySheet(EX) + const host = renderTop() + const rows = [...host.querySelectorAll('.list .item')] + expect(rows).toHaveLength(3) + // newest first, oldest last; the warm-up and the unfinished set never show up + expect(rows[0].querySelector('.ss').textContent).toBe('70×3') + expect(rows[2].querySelector('.ss').textContent).toBe('60×5 · 60×5') + expect(rows[2].textContent).toContain('Volume 600 kg') + // the record was set in the middle session and only that one carries the badge + expect(rows.map(r => !!r.querySelector('.pr'))).toEqual([false, true, false]) + expect(host.querySelector('.chart svg')).toBeTruthy() + expect(host.textContent).toContain('Best:') + expect(host.textContent).toContain('70 kg') + }) + + it('is reachable from the exercise detail sheet once there is history', () => { + exerciseDetailSheet(EXIDX[EX]) + const before = renderTop() + expect([...before.querySelectorAll('button')].some(b => b.textContent === 'History')).toBe(false) + + useStore.setState(s => ({ S: { ...s.S, workouts: [session(0, [{ w: 60, r: 5, done: true }])] } })) + useUI.setState({ sheets: [] }) + exerciseDetailSheet(EXIDX[EX]) + const host = renderTop() + const btn = [...host.querySelectorAll('button')].find(b => b.textContent === 'History') + expect(btn).toBeTruthy() + act(() => { btn.click() }) + expect(useUI.getState().sheets).toHaveLength(2) + const top = renderTop() + expect(top.querySelectorAll('.list .item')).toHaveLength(1) + }) +}) diff --git a/frontend/src/sheets.jsx b/frontend/src/sheets.jsx index 9c795f1..66d960f 100644 --- a/frontend/src/sheets.jsx +++ b/frontend/src/sheets.jsx @@ -1,4 +1,4 @@ -import { useEffect, useRef, useState } from 'react' +import { useEffect, useMemo, useRef, useState } from 'react' import { useStore } from './store/useStore.js' import { useUI } from './store/useUI.js' import { EXDB, EXIDX, BODYPARTS, isCardio, isBodyweightEq, allExercises, equipmentOf, smOf, matchExercise, exOr } from './lib/exercises.js' @@ -12,6 +12,7 @@ import { t, dateLocale, instrFor, exerciseNameFor, getLang, INSTR_LANGS } from ' import { nav } from './lib/nav.js' import { buildStarterPlan, starterPlanDays, starterPlanOptions } from './lib/starter.js' import Media, { Thumb } from './components/Media.jsx' +import LineChart from './components/LineChart.jsx' import Stepper from './components/Stepper.jsx' import Icon from './components/Icon.jsx' import { Button, Slider, Switch, Segmented, SelectRow, Row, TextField, NumberField, MultiSelectRow } from './components/ui.jsx' @@ -23,6 +24,7 @@ import { parseImport, mergeImport } from './lib/import-csv.js' import { importHevyData, HevyApiError, HEVY_DEV_SETTINGS, mergeHevyRoutines } from './lib/import-hevy.js' import { buildPlanBundle, parsePlan, mergePlan, printPlan } from './lib/plan-share.js' import { estimate1RM, best1RM, is1RMRecord, REP_CAP } from './lib/onerm.js' +import { exerciseHistory } from './lib/exercise-history.js' import { nextPrescription, applyPrescription, policyFor, defaultIncrement, POLICIES_FOR, POLICY_NAME, POLICY_DESC, MAX_BW_SETS } from './lib/progression.js' import { normalizeRepRange } from './lib/rep-range.js' import { MOBILE, shareExport } from './lib/mobile.js' @@ -634,6 +636,7 @@ function ExerciseDetail({ ex, close }) { {ex.desc &&
{ex.desc}
} {best > 0 &&
{t('Best:')} {fmtNum(best)} {st.unit}{last ? ` · ${t('last')} ${fmtDate(last.d)}: ${last.sets.map(s => setLabel(ex.id, s, last.target)).join(', ')}` : ''}
} + {last && } {ex.custom &&
@@ -648,6 +651,56 @@ function ExerciseDetail({ ex, close }) { } export const exerciseDetailSheet = ex => ui().openSheet(close => ) +/* ============================ exercise history ============================ */ +// What you did on this exercise before, reachable mid-workout (issue #43): the curve first, +// then the last sessions set by set, so the question "what did I do last month" is answered +// without leaving the workout for Stats. Derived once per log change — the sheet re-renders on +// every store tick while a session runs, and LineChart drops its hover whenever `points` +// changes identity, so a series rebuilt per render would lose the tooltip under your finger. +function ExerciseHistory({ exId }) { + const st = useStore(s => s.S) + const ex = exOr(exId) + const h = useMemo(() => exerciseHistory(st, exId), [st.workouts, exId]) + const [curve, setCurve] = useState('top') + const onE1 = curve === 'e1rm' && h.e1rmPoints.length > 0 + const unit = h.metric === 'weight' ? st.unit : h.metric === 'reps' ? t('reps') : h.metric === 'sec' ? 's' : t('min') + const e1Best = useMemo(() => Math.max(0, ...h.e1rmPoints.map(p => p.y)), [h]) + if (!h.total) return <> +

{exerciseNameFor(ex)}

+
{t('No sessions logged yet')}
+ + const tail = s => [ + s.volume > 0 && t('Volume') + ' ' + fmtVol(s.volume, st.unit), + s.e1rm != null && t('Est. 1RM') + ' ' + fmtNum(s.e1rm) + ' ' + st.unit, + ].filter(Boolean).join(' · ') + return <> +

{exerciseNameFor(ex)}

+
{t('Exercise history')} · {t(h.total === 1 ? '{0} session' : '{0} sessions', h.total)}
+ {/* Only reps work with a load produces an estimate, so the toggle is absent for the rest. */} + {h.e1rmPoints.length > 0 && h.metric === 'weight' && } +
+ +
+
+ + {t('Best:')} {fmtNum(onE1 ? e1Best : h.best)} {onE1 ? st.unit : unit} +
+

{h.sessions.length < h.total ? t('Last {0} sessions', h.sessions.length) : t('Sessions')}

+
+ {h.sessions.map(s =>
+
+
{fmtDate(s.d, true)} {s.pr && PR}
+
{s.sets.map(x => setLabel(exId, x, s.target)).join(' · ')}
+ {tail(s) &&
{tail(s)}
} +
+ {s.value != null && s.value > 0 && {fmtNum(s.value)} {unit}} +
)} +
+ +} +export const exerciseHistorySheet = exId => ui().openSheet(close => ) + /* ============================ add to routine ============================ */ function AddToRoutine({ ex, close }) { const st = useStore(s => s.S) diff --git a/frontend/src/views/Workout.jsx b/frontend/src/views/Workout.jsx index 69b91e1..888d8fd 100644 --- a/frontend/src/views/Workout.jsx +++ b/frontend/src/views/Workout.jsx @@ -12,7 +12,7 @@ import { t, exerciseNameFor } from '../lib/i18n.js' import { api } from '../lib/api.js' import { insertionIndexAfterCurrentUnit, nextUnfinishedUnit, setProgressHighWater, supersetFlowStep, restAfterSet, restOnRecheck, restSecFor } from '../lib/supersetFlow.js' import Media from '../components/Media.jsx' -import { startFlow, exercisePicker, exConfigSheet, exerciseDetailSheet, finishWorkout, workoutCompleteSheet, confirmSheet, exerciseNoteSheet, sessionNoteSheet, swapActiveWorkoutExercise, barWeightSheet, menuSheet, effortPickerSheet } from '../sheets.jsx' +import { startFlow, exercisePicker, exConfigSheet, exerciseDetailSheet, finishWorkout, workoutCompleteSheet, confirmSheet, exerciseNoteSheet, sessionNoteSheet, swapActiveWorkoutExercise, barWeightSheet, menuSheet, effortPickerSheet, exerciseHistorySheet } from '../sheets.jsx' import { effortColor } from '../lib/effort.js' import Icon from '../components/Icon.jsx' import { Button, Check, NumberField } from '../components/ui.jsx' @@ -183,6 +183,7 @@ function ExerciseBlock({ entryIdx, compact, onToggle, onField, onAddSet, onRemov items: [ { icon: 'pencil', label: entry.note ? t('Edit note') : t('Add note'), sub: entry.note || undefined, onClick: () => exerciseNoteSheet(entryIdx) }, { icon: 'info', label: t('Details'), onClick: () => exerciseDetailSheet(ex) }, + { icon: 'history', label: t('History'), sub: last ? t('Last time') + ' ' + fmtDate(last.d) : undefined, onClick: () => exerciseHistorySheet(entry.id) }, onProgressionSettings && { icon: 'chartLine', label: t('Progression settings'), sub: guidance ? t(guidance.policyLabel) : undefined, onClick: onProgressionSettings }, barInfo && { icon: 'barbell', label: t('Bar weight'), sub: barInfo.text, onClick: () => barWeightSheet(entry.id) }, { icon: 'flame', label: t('Add warm-up set'), onClick: onAddWarmup }, diff --git a/frontend/src/views/Workout.test.jsx b/frontend/src/views/Workout.test.jsx index 72ba572..140d4ca 100644 --- a/frontend/src/views/Workout.test.jsx +++ b/frontend/src/views/Workout.test.jsx @@ -23,6 +23,7 @@ const mocks = vi.hoisted(() => { swapActiveWorkoutExercise: vi.fn(), menuSheet: vi.fn(), effortPickerSheet: vi.fn(), + exerciseHistorySheet: vi.fn(), } state.stopRest = vi.fn(() => { state.timer = null }) state.stopWork = vi.fn(() => { state.work = null }) @@ -76,6 +77,7 @@ vi.mock('../sheets.jsx', () => ({ exerciseNoteSheet: vi.fn(), sessionNoteSheet: vi.fn(), effortPickerSheet: mocks.effortPickerSheet, + exerciseHistorySheet: mocks.exerciseHistorySheet, })) vi.mock('../components/Media.jsx', () => ({ default: () => null })) // api.js reads navigator.userAgent at module scope. This file installs its own DOM inside the @@ -1109,6 +1111,16 @@ describe('workout controls: the more menu and the set menu', () => { expect(mocks.confirmSheet).toHaveBeenCalled() }) + it('opens the exercise history sheet from the More menu, for the tapped exercise', async () => { + // the screen shows one exercise at a time, so "the tapped exercise" is the current one + await mount([exercise('plain-bench', [false]), exercise('plain-row', [false])], 1) + await act(async () => { container.querySelector('button[aria-label="More"]').dispatchEvent(new dom.Event('click', { bubbles: true })) }) + const history = item('History') + expect(history.icon).toBe('history') + history.onClick() + expect(mocks.exerciseHistorySheet).toHaveBeenCalledWith('plain-row') + }) + it('opens a per-set menu from the set number with drop, burst and remove', async () => { await mount([exercise('plain-bench', [false, false])]) await act(async () => { container.querySelector('button[aria-label="Set 2"]').dispatchEvent(new dom.Event('click', { bubbles: true })) })