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
The screens for timed sets, progression and estimated 1RM (#16 #17 #18)
Duarte Santosc248ca3baef2
diff --git a/frontend/src/index.css b/frontend/src/index.cssindex 535e2f3f3..386bd6289 100644--- a/frontend/src/index.css+++ b/frontend/src/index.css@@ -554,6 +554,23 @@ h4.sec{.setrow .stp button{width:32px;height:40px}.setrow.done .n{background:var(--acc);color:var(--on-acc)}.setrow.done{opacity:.45}+/* why the next target is what it is (issue #17) */+.progline{+ display:flex;align-items:flex-start;gap:7px;margin:6px 0 2px;+ font-size:13px;line-height:1.38;color:var(--acc);+}+.progline.warn{color:var(--yellow)}+.progline svg{flex:none;margin-top:2px}++/* start a timed set (issue #16) — sits where you'd otherwise reach for the checkbox */+.setrow .setgo{+ width:30px;height:30px;border-radius:50%;flex:none;+ display:flex;align-items:center;justify-content:center;+ background:var(--surface-2);color:var(--acc);font-size:14px;+ transition:background var(--fast),opacity var(--fast);+}+.setrow .setgo:disabled{opacity:.3;cursor:default}+.setrow .setgo:not(:disabled):active{background:var(--surface-3)}/* exercise-config sheet: three steppers side by side on narrow phones */.cfgrow{gap:8px}.cfgrow>div{flex:1;min-width:0}@@ -574,6 +591,15 @@ h4.sec{#timer .t{font-size:26px;font-weight:600;letter-spacing:-.026em;font-variant-numeric:tabular-nums;min-width:66px}#timer .bar{flex:1;height:4px;background:var(--surface-3);border-radius:99px;overflow:hidden}#timer .bar i{display:block;height:100%;background:var(--acc);transition:width 1s linear}+/* work timer (issue #16): the same bar doing the opposite job — outlined and tinted so a+ glance tells "you are holding this" apart from "you are recovering". */+#timer.working{border:var(--hair) solid var(--acc)}+#timer.working .t{color:var(--acc)}+#timer.working .grow{flex:1;min-width:0}+#timer.working .lbl{+ font-size:12px;color:var(--label-2);margin-bottom:5px;text-transform:capitalize;+ white-space:nowrap;overflow:hidden;text-overflow:ellipsis;+}/* ---------------------------------------------------------------- modal -- */#modal-root{position:fixed;inset:0;z-index:100;display:none}diff --git a/frontend/src/sheets.jsx b/frontend/src/sheets.jsxindex 5e5617c26..6acae99a5 100644--- a/frontend/src/sheets.jsx+++ b/frontend/src/sheets.jsx@@ -3,7 +3,7 @@ import { useStore } from './store/useStore.js'import { useUI } from './store/useUI.js'import { EXDB, EXIDX, BODYPARTS, isCardio, allExercises, equipmentOf } from './lib/exercises.js'import { fmtDate, fmtNum, fmtVol, fmtDur, durPart, todayISO, uid, exCount, DAYN, MONTHS_LONG, ACCENTS } from './lib/format.js'-import { lastEntryFor, bestWeightFor, buildSets, effectiveRoutineId, workoutVolume, setsDone, setsDoneActive, lastBW, supersetUnits, unitOf, setLabel, defaultConfig, cleanupSg } from './lib/history.js'+import { lastEntryFor, bestWeightFor, buildSets, effectiveRoutineId, workoutVolume, setsDone, setsDoneActive, lastBW, supersetUnits, unitOf, setLabel, defaultConfig, cleanupSg, modeOf } from './lib/history.js'import { beep, vibrate } from './lib/sound.js'import { t, instrFor, getLang, INSTR_LANGS } from './lib/i18n.js'import { nav } from './lib/nav.js'@@ -11,12 +11,14 @@ import { starterRoutines } from './lib/starter.js'import Media, { Thumb } from './components/Media.jsx'import Stepper from './components/Stepper.jsx'import Icon from './components/Icon.jsx'-import { Button, Slider, Switch } from './components/ui.jsx'+import { Button, Slider, Switch, Segmented, SelectRow } from './components/ui.jsx'import { glyphOf, GLYPH_GROUPS, DEFAULT_GLYPH } from './lib/glyphs.js'import BodyMap from './components/BodyMap.jsx'import { loadOfWorkouts } from './lib/muscles.js'import { parseImport, mergeImport } from './lib/import-csv.js'import { buildPlanBundle, parsePlan, mergePlan, printPlan } from './lib/plan-share.js'+import { estimate1RM, best1RM, is1RMRecord, REP_CAP } from './lib/onerm.js'+import { nextPrescription, applyPrescription, policyFor, defaultIncrement, POLICIES_FOR, POLICY_NAME, POLICY_DESC } from './lib/progression.js'import { MOBILE, shareExport } from './lib/mobile.js'const S = () => useStore.getState().S@@ -242,6 +244,34 @@ function GoalSheet({ close }) {export const goalSheet = () => ui().openSheet(close => <GoalSheet close={close} />)/* ============================ exercise detail ============================ */+// Estimated 1RM for one exercise (issue #18): what the log already implies, plus a calculator+// for a set you have not done — so the number is reachable before there is any history.+function OneRM({ ex }) {+ const st = useStore(s => s.S)+ const best = best1RM(st, ex.id)+ const [w, setW] = useState(best ? best.w : (st.exWeights[ex.id] || {}).w || 20)+ const [r, setR] = useState(best ? best.r : 5)+ const est = estimate1RM(w, r)+ return <>+ <h4 className="sec">{t('Estimated 1RM')}</h4>+ {best && <div className="small" style={{ marginBottom: 8 }}>+ {t('From your log:')} <b className="accent">{fmtNum(best.est)} {st.unit}</b>+ <span className="dim"> · {t('{0} × {1} on {2}', fmtNum(best.w) + ' ' + st.unit, best.r, fmtDate(best.d, true))}</span>+ </div>}+ <div className="row cfgrow" style={{ marginBottom: 10 }}>+ <Stepper label={t('Weight ({0})', st.unit)} value={w} step={2.5} onChange={setW} />+ <Stepper label={t('Reps')} value={r} step={1} decimal={false} onChange={setR} />+ </div>+ <div className="row between" style={{ marginBottom: 4 }}>+ <span className="muted small">{t('Estimate')}</span>+ <b className="accent" style={{ fontSize: 20 }}>{est === null ? '—' : fmtNum(est) + ' ' + st.unit}</b>+ </div>+ <div className="small dim">{est === null+ ? t('Enter a weight and 1–{0} reps — beyond that an estimate is guesswork.', REP_CAP)+ : t('Epley formula — a calculation from one set, not a tested max.')}</div>+ </>+}+function ExerciseDetail({ ex, close }) {const st = useStore(s => s.S)const last = lastEntryFor(st, ex.id)@@ -256,13 +286,14 @@ function ExerciseDetail({ ex, close }) {{(ex.sm || []).slice(0, 3).map((s, i) => <span key={i} className="tag">{t(s)}</span>)}</div>{ex.desc && <div className="exnote">{ex.desc}</div>}- {best > 0 && <div className="small row" style={{ marginBottom: 6, gap: 5 }}><Icon name="trophy" style={{ fontSize: 14, color: 'var(--yellow)' }} />{t('Best:')} <b className="accent">{fmtNum(best)} {st.unit}</b>{last ? ` · ${t('last')} ${fmtDate(last.d)}: ${last.sets.map(s => setLabel(ex.id, s)).join(', ')}` : ''}</div>}+ {best > 0 && <div className="small row" style={{ marginBottom: 6, gap: 5 }}><Icon name="trophy" style={{ fontSize: 14, color: 'var(--yellow)' }} />{t('Best:')} <b className="accent">{fmtNum(best)} {st.unit}</b>{last ? ` · ${t('last')} ${fmtDate(last.d)}: ${last.sets.map(s => setLabel(ex.id, s, last.target)).join(', ')}` : ''}</div>}<Button variant="primary" icon="plus" style={{ margin: '10px 0 4px' }} onClick={() => addToRoutineSheet(ex)}>{t('Add to my plan')}</Button>{ex.custom && <div className="row" style={{ gap: 8, marginTop: 8 }}><Button icon="pencil" style={{ flex: 1 }} onClick={() => { close(); customExSheet(ex) }}>{t('Edit')}</Button><Button variant="danger" icon="trash" style={{ flex: 1 }} onClick={() => deleteCustomEx(ex, close)}>{t('Delete')}</Button></div>}- {instrFor(ex).length > 0 && <><h4 className="sec">{t('How to')}{!INSTR_LANGS.includes(getLang()) && <span className="dim" style={{ textTransform: 'none', letterSpacing: 0 }}> · {t('instructions in English')}</span>}</h4><ol className="steps-list">{instrFor(ex).map((s, i) => <li key={i}>{s}</li>)}</ol></>}+ {!isCardio(ex) && <OneRM ex={ex} />}+ {instrFor(ex).length > 0 &&<><h4 className="sec">{t('How to')}{!INSTR_LANGS.includes(getLang()) && <span className="dim" style={{ textTransform: 'none', letterSpacing: 0 }}> · {t('instructions in English')}</span>}</h4><ol className="steps-list">{instrFor(ex).map((s, i) => <li key={i}>{s}</li>)}</ol></>}</>}export const exerciseDetailSheet = ex => ui().openSheet(close => <ExerciseDetail ex={ex} close={close} />)@@ -282,7 +313,7 @@ function AddToRoutine({ ex, close }) {const r = isNew ? S().routines[S().routines.length - 1] : st.routines.find(x => x.id === rid)toast(t('“{0}” added to {1}', ex.n, r ? r.name : t('routine')))if (isNew && r) nav('/plan/r/' + r.id)- })+ }, null, isNew ? null : st.routines.find(x => x.id === rid))}return <><h3 className="capitalize">{t('Add “{0}”', ex.n)}</h3>@@ -417,14 +448,57 @@ function ExercisePicker({ onPick, close }) {export const exercisePicker = onPick => ui().openSheet(close => <ExercisePicker onPick={onPick} close={close} />)/* ============================ exercise config ============================ */-function ExConfig({ ex, existing, onSave, onDelete, close }) {+// Progression settings for one exercise (issue #17). Shown inside the config sheet because+// "how does this lift go up" belongs next to sets and reps, not in a separate screen. Left+// on "follow the routine" it inherits, so most people never touch it.+function ProgressionFields({ ex, mode, c, setC, routine, unit }) {+ const options = POLICIES_FOR[mode] || ['off']+ if (options.length < 2) return null+ const inherited = policyFor({ id: ex.id }, routine, mode)+ const active = policyFor({ ...c, id: ex.id }, routine, mode)+ const inc = c.inc > 0 ? c.inc : (mode === 'time' ? 5 : defaultIncrement(ex.id, unit))+ return <>+ <h4 className="sec">{t('Progression')}</h4>+ <div className="sect-b" style={{ marginBottom: 8 }}>+ <SelectRow title={t('Rule')} sheetTitle={t('Progression')} value={c.prog || ''} onChange={v => setC(x => ({ ...x, prog: v || undefined }))}+ options={[{ value: '', label: t('Follow the routine ({0})', t(POLICY_NAME[inherited])) },+ ...options.map(p => ({ value: p, label: t(POLICY_NAME[p]) }))]} />+ </div>+ <div className="small dim" style={{ marginBottom: active === 'off' ? 18 : 10 }}>{t(POLICY_DESC[active])}</div>+ {active !== 'off' && <div className="row cfgrow" style={{ marginBottom: 18 }}>+ <Stepper label={mode === 'time' ? t('Step (seconds)') : t('Step ({0})', unit)} value={inc}+ step={mode === 'time' ? 5 : 1.25} decimal={mode !== 'time'} onChange={v => setC(x => ({ ...x, inc: v }))} />+ {active === 'double' && <Stepper label={t('Reps from')} value={c.repsMin || Math.max(1, (c.reps || 10) - 2)}+ step={1} decimal={false} onChange={v => setC(x => ({ ...x, repsMin: v }))} />}+ </div>}+ </>+}++function ExConfig({ ex, existing, onSave, onDelete, close, routine }) {const st = useStore(s => s.S)const cardio = isCardio(ex.id)const [c, setC] = useState(existing || defaultConfig(ex.id))+ // Cardio keeps its own duration+speed form; the reps/time choice (issue #16) is offered for+ // everything else, which is where the gap was — planks, hangs, wall sits, loaded carries.+ const mode = cardio ? 'cardio' : modeOf({ ...c, id: ex.id })+ // Keep whatever the other mode already had (sets, weight) and fill only what is missing.+ const setMode = m => setC(x => ({ ...defaultConfig(ex.id, m), ...x, mode: m }))const save = () => {close()- if (cardio) onSave({ sets: Math.max(1, Math.round(c.sets) || 1), min: Math.max(1, Math.round(c.min) || 20), speed: Math.max(0, c.speed || 8) })- else onSave({ sets: Math.max(1, Math.round(c.sets) || 3), reps: Math.max(1, Math.round(c.reps) || 10), weight: Math.max(0, c.weight || 0) })+ const sets = Math.max(1, Math.round(c.sets) || (cardio ? 1 : 3))+ // Only carry progression settings that differ from the inherited default, so a plan file+ // stays readable and "follow the routine" keeps meaning exactly that.+ const prog = {}+ if (c.prog) prog.prog = c.prog+ if (c.inc > 0) prog.inc = c.inc+ if (cardio) onSave({ sets, min: Math.max(1, Math.round(c.min) || 20), speed: Math.max(0, c.speed || 8) })+ else if (mode === 'time') onSave({ sets, mode: 'time', sec: Math.max(1, Math.round(c.sec) || 45), weight: Math.max(0, c.weight || 0), ...prog })+ else {+ const reps = Math.max(1, Math.round(c.reps) || 10)+ const out = { sets, mode: 'reps', reps, weight: Math.max(0, c.weight || 0), ...prog }+ if (policyFor({ ...c, id: ex.id }, routine, 'reps') === 'double') out.repsMin = Math.min(reps, Math.max(1, Math.round(c.repsMin) || Math.max(1, reps - 2)))+ onSave(out)+ }}return <><h3 className="capitalize">{ex.n}</h3>@@ -434,23 +508,35 @@ function ExConfig({ ex, existing, onSave, onDelete, close }) {<span className="tag">{t(ex.tg || ex.bp)}</span><span className="tag">{t(ex.eq)}</span></div>{ex.desc && <div className="exnote">{ex.desc}</div>}- <div className="row cfgrow" style={{ marginBottom: 18 }}>+ {!cardio && <div style={{ marginBottom: 14 }}>+ <Segmented className="seg-range" value={mode} onChange={setMode}+ options={[{ value: 'reps', label: t('Reps') }, { value: 'time', label: t('Time') }]} />+ </div>}+ <div className="row cfgrow" style={{ marginBottom: mode === 'time' ? 8 : 18 }}>{cardio ? <><Stepper label={t('Intervals')} value={c.sets} step={1} decimal={false} onChange={v => setC(x => ({ ...x, sets: v }))} /><Stepper label={t('Minutes')} value={c.min} step={1} decimal={false} onChange={v => setC(x => ({ ...x, min: v }))} /><Stepper label={t('Speed (km/h)')} value={c.speed} step={0.5} onChange={v => setC(x => ({ ...x, speed: v }))} />+ </> : mode === 'time' ? <>+ <Stepper label={t('Sets')} value={c.sets} step={1} decimal={false} onChange={v => setC(x => ({ ...x, sets: v }))} />+ <Stepper label={t('Seconds')} value={c.sec} step={5} decimal={false} onChange={v => setC(x => ({ ...x, sec: v }))} />+ <Stepper label={t('Weight ({0})', st.unit)} value={c.weight} step={2.5} onChange={v => setC(x => ({ ...x, weight: v }))} /></> : <><Stepper label={t('Sets')} value={c.sets} step={1} decimal={false} onChange={v => setC(x => ({ ...x, sets: v }))} /><Stepper label={t('Reps')} value={c.reps} step={1} decimal={false} onChange={v => setC(x => ({ ...x, reps: v }))} /><Stepper label={t('Weight ({0})', st.unit)} value={c.weight} step={2.5} onChange={v => setC(x => ({ ...x, weight: v }))} /></>}</div>+ {mode === 'time' && <div className="small dim" style={{ marginBottom: 18 }}>+ {t('A timer runs while you hold the set. Leave the weight at 0 for bodyweight holds.')}+ </div>}+ <ProgressionFields ex={ex} mode={mode} c={c} setC={setC} routine={routine} unit={st.unit} /><Button variant="primary" onClick={save}>{existing ? t('Save') : t('Add to routine')}</Button>{ex.custom && <><div style={{ height: 8 }} /><Button icon="pencil" onClick={() => { close(); customExSheet(ex) }}>{t('Edit or delete this exercise')}</Button></>}{onDelete && <><div style={{ height: 8 }} /><Button variant="danger" onClick={() => { close(); onDelete() }}>{t('Remove from routine')}</Button></>}</>}-export const exConfigSheet = (ex, existing, onSave, onDelete) => ui().openSheet(close => <ExConfig ex={ex} existing={existing} onSave={onSave} onDelete={onDelete} close={close} />)+export const exConfigSheet = (ex, existing, onSave, onDelete, routine) => ui().openSheet(close => <ExConfig ex={ex} existing={existing} onSave={onSave} onDelete={onDelete} routine={routine} close={close} />)/* ============================ glyph picker ============================ */// Grouped by what the glyph means for a training day, so picking one is a scan@@ -610,7 +696,7 @@ function WorkoutDetail({ w, close }) {return <div key={i} className="row" style={{ marginBottom: 12, alignItems: 'flex-start' }}>{ex && <Thumb ex={ex} />}<div className="grow"><div className="tt capitalize" style={{ fontWeight: 600 }}>{ex ? ex.n : (e.n || e.id)} {w.prs && w.prs.includes(e.id) && <span className="pr"><Icon name="trophy" />PR</span>}</div>- <div className="ss">{e.sets.filter(s => s.done).map(s => setLabel(e.id, s)).join(' · ') || t('no sets')}</div></div>+ <div className="ss">{e.sets.filter(s => s.done).map(s => setLabel(e.id, s, e.target)).join(' · ') || t('no sets')}</div></div></div>})}<Button variant="danger" onClick={() => confirmSheet({ title: t('Delete workout?'), message: t('This removes it from your history for good.'), confirmText: t('Delete'), danger: true, onConfirm: () => { update(s => { s.workouts = s.workouts.filter(x => x.id !== w.id) }); close(); toast(t('Workout deleted')) } })}>{t('Delete workout')}</Button>@@ -680,7 +766,13 @@ export function startFlow(routineId) {export function beginWorkout(routineId, bw) {const st = S()const r = routineId ? st.routines.find(x => x.id === routineId) : null- const entries = (r ? r.ex : []).map(cfg => ({ id: cfg.id, sg: cfg.sg, target: { ...cfg }, sets: buildSets(st, cfg) }))+ // The prescription is applied as the session is built, so you walk up to the bar with the+ // right weight already on the screen instead of being told about it afterwards. `plan` is+ // kept on the entry purely so the workout can explain the number it chose.+ const entries = (r ? r.ex : []).map(cfg => {+ const plan = nextPrescription(st, cfg, r)+ return { id: cfg.id, sg: cfg.sg, target: { ...cfg }, plan, sets: applyPrescription(buildSets(st, cfg), plan) }+ })update(s => {s.active = { id: uid(), d: todayISO(), start: Date.now(), routineId, name: r ? r.name : t('Freestyle'), bw: bw || null, cur: 0, entries }})@@ -750,7 +842,7 @@ function WorkoutComplete({ close }) {}export const workoutCompleteSheet = () => ui().openSheet(close => <WorkoutComplete close={close} />, { kind: 'center' })-function FinishSummary({ w, prs, close }) {+function FinishSummary({ w, prs, e1prs = [], close }) {const st = useStore(s => s.S)return <div style={{ textAlign: 'center', padding: '8px 0' }}><div style={{ fontSize: 44, display: 'flex', justifyContent: 'center', color: 'var(--acc)' }}><Icon name="trophy" /></div>@@ -761,7 +853,10 @@ function FinishSummary({ w, prs, close }) {<div className="tile"><div className="l">{t('Sets')}</div><div className="v" style={{ fontSize: '1.1rem' }}>{setsDone(w)}</div></div><div className="tile"><div className="l">{t('PRs')}</div><div className="v" style={{ fontSize: 20 }}>{prs.length || '—'}</div></div></div>- {prs.length > 0 && <div style={{ textAlign: 'left', marginBottom: 12 }}>{prs.map(id => <div key={id} className="small accent capitalize row" style={{ gap: 5 }}><Icon name="trophy" style={{ fontSize: 13 }} />{t('New PR:')} {(EXIDX[id] || {}).n || id}</div>)}</div>}+ {(prs.length > 0 || e1prs.length > 0) && <div style={{ textAlign: 'left', marginBottom: 12 }}>+ {prs.map(id => <div key={id} className="small accent capitalize row" style={{ gap: 5 }}><Icon name="trophy" style={{ fontSize: 13 }} />{t('New PR:')} {(EXIDX[id] || {}).n || id}</div>)}+ {e1prs.map(p => <div key={p.id} className="small accent capitalize row" style={{ gap: 5 }}><Icon name="chartLine" style={{ fontSize: 13 }} />{t('Best estimated 1RM:')} {(EXIDX[p.id] || {}).n || p.id} · {fmtNum(p.est)} {st.unit}</div>)}+ </div>}<h4 className="sec" style={{ textAlign: 'left' }}>{t('What you just trained')}</h4><BodyMap load={loadOfWorkouts([w])} body={st.body} /><div style={{ height: 14 }} />@@ -782,13 +877,21 @@ function doFinishWorkout() {const A = st.activeif (!A) returnconst prs = []+ const e1prs = []A.entries.forEach(e => {const mx = Math.max(0, ...e.sets.filter(s => s.done).map(s => s.w))if (mx > 0 && mx > bestWeightFor(st, e.id)) prs.push(e.id)+ // A heavier estimate without a heavier top set is its own kind of progress —+ // same weight for more reps. Reported separately so it can't be read as a load PR.+ const rec = is1RMRecord(st, e.id, e)+ if (rec && !prs.includes(e.id)) e1prs.push({ id: e.id, ...rec })})const w = {id: A.id, d: A.d, start: A.start, end: Date.now(), routineId: A.routineId, name: A.name, bw: A.bw,- entries: A.entries.map(e => ({ id: e.id, sets: e.sets, topW: e.topW || null })).filter(e => e.sets.some(s => s.done)),+ // `target` (what the session prescribed) is kept alongside the sets: without it a+ // finished workout cannot say whether it hit its reps, and a timed session reads back+ // as "0 reps". It is what the progression engine works from.+ entries: A.entries.map(e => ({ id: e.id, sets: e.sets, topW: e.topW || null, target: e.target || null })).filter(e => e.sets.some(s => s.done)),prs}w.vol = workoutVolume(w)@@ -802,5 +905,5 @@ function doFinishWorkout() {})useUI.getState().stopRest()beep(snd(), 880, 0.15); beep(snd(), 1100, 0.15, 0.18); beep(snd(), 1320, 0.3, 0.36)- ui().openSheet(close => <FinishSummary w={w} prs={prs} close={close} />, { kind: 'center', locked: true })+ ui().openSheet(close => <FinishSummary w={w} prs={prs} e1prs={e1prs} close={close} />, { kind: 'center', locked: true })}diff --git a/frontend/src/views/RoutineEdit.jsx b/frontend/src/views/RoutineEdit.jsxindex 3094031fa..d12adfbdb 100644--- a/frontend/src/views/RoutineEdit.jsx+++ b/frontend/src/views/RoutineEdit.jsx@@ -1,15 +1,16 @@import { useNavigate, useParams } from 'react-router-dom'import { useEffect } from 'react'import { useStore } from '../store/useStore.js'-import { exOr, isCardio } from '../lib/exercises.js'-import { fmtNum, uid } from '../lib/format.js'+import { exOr } from '../lib/exercises.js'+import { uid } from '../lib/format.js'import { t } from '../lib/i18n.js'-import { supersetUnits, cleanupSg } from '../lib/history.js'+import { supersetUnits, cleanupSg, exLine } from '../lib/history.js'import { Thumb } from '../components/Media.jsx'import { glyphPicker, exercisePicker, exConfigSheet, confirmSheet } from '../sheets.jsx'import Icon from '../components/Icon.jsx'import { glyphOf } from '../lib/glyphs.js'-import { Button } from '../components/ui.jsx'+import { Button, SelectRow } from '../components/ui.jsx'+import { POLICIES_FOR, POLICY_NAME, POLICY_DESC } from '../lib/progression.js'import BodyMap from '../components/BodyMap.jsx'import { loadOfRoutine, rankOf, MUSCLE_NAME } from '../lib/muscles.js'@@ -46,6 +47,15 @@ export default function RoutineEdit() {<button className="iconbtn" aria-label={t('Pick an icon')} onClick={() => glyphPicker(r.emoji, g => update(s => { s.routines.find(x => x.id === id).emoji = g }))}><Icon name={glyphOf(r.emoji)} /></button></div>+ <div className="sect-b" style={{ marginBottom: 16 }}>+ <SelectRow icon="chartLine" title={t('Progression')} sheetTitle={t('Progression')}+ value={r.prog || 'linear'} onChange={v => update(s => { s.routines.find(x => x.id === id).prog = v })}+ options={POLICIES_FOR.reps.map(p => ({ value: p, label: t(POLICY_NAME[p]), subtitle: t(POLICY_DESC[p]) }))} />+ </div>+ <div className="small dim" style={{ margin: '-10px 2px 16px' }}>+ {t('Applies to every exercise in this routine that does not set its own rule.')}+ </div>+{r.ex.length ? <div className="list">{r.ex.map((e, i) => {// An unresolvable id is shown rather than skipped — hiding it left an entry you// could neither see nor delete, but that still turned up in the workout.@@ -54,10 +64,10 @@ export default function RoutineEdit() {return <div key={i}>{unitFirst.has(i) && <div className="ss-label"><Icon name="link" />{t('Superset')}</div>}<div className={'item' + (inSS.has(i) ? ' in-ss' : '')} onClick={() => {- exConfigSheet(ex, e, cfg => edit(x => { Object.assign(x[i], cfg) }), () => edit(x => { x.splice(i, 1); cleanupSg(x) }))+ exConfigSheet(ex, e, cfg => edit(x => { x[i] = { id: x[i].id, sg: x[i].sg, ...cfg } }), () => edit(x => { x.splice(i, 1); cleanupSg(x) }), r)}}><Thumb ex={ex} />- <div className="grow"><div className="tt capitalize">{ex.n}</div><div className="ss">{isCardio(e.id) ? `${e.sets} × ${e.min || 20} min @ ${fmtNum(e.speed || 8)} km/h` : `${e.sets} × ${e.reps}${e.weight ? ' · ' + fmtNum(e.weight) + ' ' + S.unit : ''}`}</div></div>+ <div className="grow"><div className="tt capitalize">{ex.n}</div><div className="ss">{exLine(e, S.unit)}</div></div><div style={{ display: 'flex', flexDirection: 'column', gap: 2, flex: 'none', alignItems: 'center' }}>{i > 0 && <button className={'iconbtn' + (linkedPrev ? ' on-ss' : '')} title={t('Superset with exercise above')} style={{ width: 32, height: 28, borderRadius: 8, fontSize: 15 }} onClick={ev => { ev.stopPropagation(); toggleLink(i) }}><Icon name="link" /></button>}<div style={{ display: 'flex', gap: 2 }}>@@ -84,7 +94,7 @@ export default function RoutineEdit() {})()}<div className="small dim row" style={{ margin: '10px 2px', gap: 5 }}><Icon name="link" style={{ fontSize: 13 }} />{t('Tap the link button on an exercise to superset it with the one above — you’ll do them back-to-back.')}</div>- <Button variant="primary" onClick={() => exercisePicker(ex => exConfigSheet(ex, null, cfg => edit(x => { x.push({ id: ex.id, ...cfg }) })))} icon="plus">{t('Add exercise')}</Button>+ <Button variant="primary" onClick={() => exercisePicker(ex => exConfigSheet(ex, null, cfg => edit(x => { x.push({ id: ex.id, ...cfg }) }), null, r))} icon="plus">{t('Add exercise')}</Button><div style={{ height: 10 }} /><Button variant="danger" onClick={() => confirmSheet({title: t('Delete routine?'), message: t('“{0}” and its exercises will be removed.', r.name), confirmText: t('Delete'), danger: true,diff --git a/frontend/src/views/Stats.jsx b/frontend/src/views/Stats.jsxindex b8fd313df..01897cc7d 100644--- a/frontend/src/views/Stats.jsx+++ b/frontend/src/views/Stats.jsx@@ -1,8 +1,8 @@import { useState } from 'react'import { useNavigate } from 'react-router-dom'import { useStore } from '../store/useStore.js'-import { EXIDX, isCardio } from '../lib/exercises.js'-import { bestWeightFor, lastBW, streakWeeks, setLabel } from '../lib/history.js'+import { EXIDX } from '../lib/exercises.js'+import { lastBW, streakWeeks, setLabel, modeOf } 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'@@ -11,6 +11,7 @@ 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 { e1rmSeries, best1RM } from '../lib/onerm.js'import { Button, Segmented, SelectRow } from '../components/ui.jsx'// Which muscles the training in a window actually hit — and, the point of the card,@@ -62,6 +63,7 @@ export default function Stats() {const S = useStore(s => s.S)const [range, setRange] = useState(90)const [exId, setExId] = useState(null)+ const [exMetric, setExMetric] = useState('top')const now = Date.now()const bwPts = S.bodyweight.filter(b => range === 0 || (b.t || new Date(b.d).getTime()) > now - range * 86400000)@@ -72,17 +74,34 @@ export default function Stats() {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 curEx = exId && exHist.includes(exId) ? exId : exHist[0] || null- const curCardio = curEx && isCardio(curEx)- const metric = s => curCardio ? (s.speed || 0) : (s.w || 0)- const exUnit = curCardio ? 'km/h' : S.unit+ // 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+ // switched exercise drops its old points instead of mixing seconds into a weight chart.+ const curMode = curEx ? (() => {+ for (let i = S.workouts.length - 1; i >= 0; i--) {+ const en = S.workouts[i].entries.find(e => e.id === curEx)+ if (en) return modeOf({ ...(en.target || {}), id: curEx })+ }+ return modeOf({ id: curEx })+ })() : 'reps'+ const curCardio = curMode === 'cardio'+ const curTimed = curMode === 'time'+ const metric = s => curCardio ? (s.speed || 0) : curTimed ? (s.sec || 0) : (s.w || 0)+ const exUnit = curCardio ? 'km/h' : curTimed ? 's' : S.unitlet exPts = [], exList = [], exBest = 0if (curEx) {S.workouts.forEach(w => {const en = w.entries.find(e => e.id === curEx)- if (en) { const mx = Math.max(0, ...en.sets.filter(s => s.done).map(metric), curCardio ? 0 : (en.topW || 0)); if (mx > 0) { exPts.push({ t: w.start, y: mx, d: w.d, sets: en.sets.filter(s => s.done) }); if (mx > exBest) exBest = mx } }+ if (en) { const mx = Math.max(0, ...en.sets.filter(s => s.done).map(metric), curCardio || curTimed ? 0 : (en.topW || 0)); if (mx > 0) { exPts.push({ t: w.start, y: mx, d: w.d, sets: en.sets.filter(s => s.done), target: en.target }); if (mx > exBest) exBest = mx } }})exList = exPts.slice(-5).reverse()}+ // Estimated 1RM (issue #18) — only reps-mode training produces one, so cardio and timed+ // work simply have no points and the toggle stays hidden.+ const e1Pts = curEx ? e1rmSeries(S, curEx) : []+ const e1Best = curEx ? best1RM(S, curEx) : null+ const showE1 = e1Pts.length > 0+ const onE1 = showE1 && exMetric === 'e1rm'return <><div className="hdr"><div><h1>{t('Stats')}</h1><div className="sub">{t('Progress & history')}</div></div>@@ -123,10 +142,18 @@ 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>- <div className="chart"><LineChart points={exPts.map(p => ({ t: p.t, y: p.y, d: p.d }))} h={150} unit={exUnit} color="var(--blue)" /></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><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)).join(' ')}</span></div>)}</div>- <div className="small dim" style={{ marginTop: 8 }}>{curCardio ? t('Top speed per workout') : t('Best set weight per workout')} · {t('Best:')} <b className="accent">{fmtNum(exBest)} {exUnit}</b></div>+ <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>+ </div>+ {showE1 && <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>}</> : <div className="muted small">{t('Finish your first workout to see progress curves here.')}</div>}</div></div>diff --git a/frontend/src/views/Workout.jsx b/frontend/src/views/Workout.jsxindex cdb6b37a1..b5c2329c0 100644--- a/frontend/src/views/Workout.jsx+++ b/frontend/src/views/Workout.jsx@@ -2,8 +2,8 @@ import { useEffect, useState } from 'react'import { useNavigate } from 'react-router-dom'import { useStore } from '../store/useStore.js'import { useUI } from '../store/useUI.js'-import { exOr, isCardio } from '../lib/exercises.js'-import { effectiveRoutine, lastEntryFor, bestWeightFor, buildSets, setsDoneActive, supersetUnits, unitOf, setLabel } from '../lib/history.js'+import { exOr } from '../lib/exercises.js'+import { effectiveRoutine, lastEntryFor, bestWeightFor, buildSets, setsDoneActive, supersetUnits, unitOf, setLabel, modeOf } from '../lib/history.js'import { fmtNum, fmtDate, todayISO, exCount, DAYN } from '../lib/format.js'import { beep, vibrate } from '../lib/sound.js'import { t } from '../lib/i18n.js'@@ -12,6 +12,7 @@ import Media from '../components/Media.jsx'import { startFlow, exercisePicker, exConfigSheet, exerciseDetailSheet, topWeightSheet, finishWorkout, workoutCompleteSheet, confirmSheet } from '../sheets.jsx'import Icon from '../components/Icon.jsx'import { Button, Check, NumberField } from '../components/ui.jsx'+import { nextPrescription, applyPrescription } from '../lib/progression.js'import { glyphOf } from '../lib/glyphs.js'/* ---------- start chooser (no active workout) ---------- */@@ -52,20 +53,28 @@ function Elapsed({ start }) {return <span>{t}</span>}-/* ---------- one exercise block (strength: weight×reps · cardio: duration+speed) ---------- */-function ExerciseBlock({ entryIdx, compact, onToggle, onField, onBumpAll, onAddSet, onRemoveSet }) {+/* ---------- one exercise block (reps: weight×reps · time: a held duration · cardio: duration+speed) ---------- */+function ExerciseBlock({ entryIdx, compact, onToggle, onField, onAddSet, onRemoveSet, onStartTimed }) {const S = useStore(s => s.S)+ const working = useUI(s => s.work)const entry = S.active.entries[entryIdx]const ex = exOr(entry.id)- const cardio = isCardio(ex)+ const mode = modeOf({ ...(entry.target || {}), id: entry.id })+ const cardio = mode === 'cardio'+ const timed = mode === 'time'const last = lastEntryFor(S, entry.id)// The same number the "confirm your working weight" sheet calls your best, so the two// never disagree inside one session: heaviest logged set, or the working weight you kept.const best = cardio ? 0 : Math.max(bestWeightFor(S, entry.id), (S.exWeights[entry.id] || {}).w || 0)- const hint = !cardio && last && last.sets.length >= (entry.target.sets || 1) && last.sets.every(s => s.r >= entry.target.reps) && last.sets[0].w > 0- ? Math.max(...last.sets.map(s => s.w)) + 2.5 : null- const col1 = cardio ? { f: 'min', step: 1, dec: false, hd: t('Duration (min)') } : { f: 'w', step: 2.5, dec: true, hd: t('Weight ({0})', S.unit) }- const col2 = cardio ? { f: 'speed', step: 0.5, dec: true, hd: t('Speed (km/h)') } : { f: 'r', step: 1, dec: false, hd: t('Reps') }+ // What the progression policy decided for this session, and why (issue #17). Computed when+ // the session was built so the reason matches the numbers already in the rows.+ const plan = entry.plan+ const col1 = cardio ? { f: 'min', step: 1, dec: false, hd: t('Duration (min)') }+ : timed ? { f: 'sec', step: 5, dec: false, hd: t('Seconds') }+ : { f: 'w', step: 2.5, dec: true, hd: t('Weight ({0})', S.unit) }+ const col2 = cardio ? { f: 'speed', step: 0.5, dec: true, hd: t('Speed (km/h)') }+ : timed ? { f: 'w', step: 2.5, dec: true, hd: t('Weight ({0})', S.unit) }+ : { f: 'r', step: 1, dec: false, hd: t('Reps') }// Uses the shared stepper markup so a set row picks up the same control styling// as every other +/- field in the app.const cell = (s, i, col, cls) => (@@ -87,14 +96,21 @@ function ExerciseBlock({ entryIdx, compact, onToggle, onField, onBumpAll, onAddS{ex.eq && <span className="tag">{t(ex.eq)}</span>}{best > 0 && <span className="tag nocap">{t('Best:')} {fmtNum(best)} {S.unit}</span>}</div>- {last && <div className="small dim" style={{ marginBottom: 4 }}>{t('Last time')} ({fmtDate(last.d)}): {last.sets.map(s => setLabel(entry.id, s)).join(', ')}</div>}- {hint && <button className="tag acc nocap" style={{ border: 'none', textAlign: 'left' }} onClick={() => { onBumpAll('w', hint); useUI.getState().toast(t('Weights bumped to {0}', fmtNum(hint) + ' ' + S.unit)) }}><Icon name="lightbulb" />{t('Last time you hit all reps — try {0}', fmtNum(hint) + ' ' + S.unit)}</button>}+ {last && <div className="small dim" style={{ marginBottom: 4 }}>{t('Last time')} ({fmtDate(last.d)}): {last.sets.map(s => setLabel(entry.id, s, last.target)).join(', ')}</div>}+ {plan && plan.why && plan.kind !== 'off' && <div className={'progline' + (plan.kind === 'deload' ? ' warn' : '')}>+ <Icon name={plan.kind === 'up' ? 'arrowUp' : plan.kind === 'deload' ? 'arrowDown' : 'lightbulb'} />+ <span>{t(...plan.why)}</span>+ </div>}<div className="card" style={{ marginTop: 10, marginBottom: 0 }}>- <div className="sethead"><span className="n-sp" /><span className="w-sp">{col1.hd}</span><span className="r-sp">{col2.hd}</span><span className="ck-sp" /></div>+ <div className="sethead"><span className="n-sp" /><span className="w-sp">{col1.hd}</span><span className="r-sp">{col2.hd}</span>{timed && <span className="ck-sp" />}<span className="ck-sp" /></div>{entry.sets.map((s, i) => <div key={i} className={'setrow' + (s.done ? ' done' : '')}><div className="n">{i + 1}</div>{cell(s, i, col1, 'w')}{cell(s, i, col2, 'r')}+ {/* A timed set is started, not typed: the timer counts the hold down and checks the+ set off itself. The checkbox stays for anyone who timed it on their own watch. */}+ {timed && <button className="setgo" aria-label={t('Start set')} disabled={s.done || !!working}+ onClick={() => onStartTimed(i)}><Icon name="play" /></button>}<Check checked={s.done} onChange={() => onToggle(i)} /></div>)}<div style={{ height: 8 }} />@@ -124,16 +140,31 @@ function ActiveWorkout() {const mutEntry = (idx, fn) => update(s => { fn(s.active.entries[idx]) }, true)const setField = (idx, i, field, v) => mutEntry(idx, e => { e.sets[i][field] = v })- const bumpAll = (idx, field, v) => mutEntry(idx, e => e.sets.forEach(s => { if (!s.done) s[field] = v }))+ const modeAt = idx => modeOf({ ...(A.entries[idx].target || {}), id: A.entries[idx].id })const addSet = idx => mutEntry(idx, e => {const l = e.sets[e.sets.length - 1]- if (isCardio(e.id)) e.sets.push({ min: l ? l.min : (e.target.min || 20), speed: l ? l.speed : (e.target.speed || 8), done: false })+ const m = modeOf({ ...(e.target || {}), id: e.id })+ if (m === 'cardio') e.sets.push({ min: l ? l.min : (e.target.min || 20), speed: l ? l.speed : (e.target.speed || 8), done: false })+ else if (m === 'time') e.sets.push({ sec: l ? l.sec : (e.target.sec || 45), w: l ? (l.w || 0) : (e.target.weight || 0), done: false })else e.sets.push({ w: l ? l.w : 0, r: l ? l.r : e.target.reps, done: false })})const removeSet = idx => mutEntry(idx, e => { if (e.sets.length > 1) e.sets.pop() })+ // A timed set is held, not typed. The work timer records what was actually held — an early+ // finish logs 0:38 of a 0:45 target rather than crediting the full prescription — and then+ // checks the set off through the normal path, so rest, supersets and the finish prompt all+ // behave exactly as they do for a reps set.+ const startTimed = (idx, i) => {+ const e = A.entries[idx]+ useUI.getState().startWork(e.sets[i].sec || 45, exOr(e.id).n, elapsed => {+ mutEntry(idx, en => { en.sets[i].sec = elapsed })+ if (!useStore.getState().S.active.entries[idx].sets[i].done) toggle(idx, i)+ })+ }+const toggle = (idx, i) => {- const cardioEntry = isCardio(A.entries[idx].id)+ const m = modeAt(idx)+ const cardioEntry = m === 'cardio'const isLastUnit = unitIdx >= units.length - 1let askTop = false, exJustDone = false, workoutDone = falsemutEntry(idx, e => {@@ -145,14 +176,17 @@ function ActiveWorkout() {if (isLastExInUnit && !unitDone) startRest(S.restSec)else if (unitDone) stopRest()if (unitDone && isLastUnit) workoutDone = true // last exercise's last set → done- if (e.sets.every(x => x.done)) { exJustDone = true; if (!cardioEntry && !e.asked) { e.asked = true; askTop = true } }+ // Only reps training has a "working weight" worth confirming — a bodyweight plank+ // has nothing to put in that slider.+ if (e.sets.every(x => x.done)) { exJustDone = true; if (m === 'reps' && !e.asked) { e.asked = true; askTop = true } }}})- // non-cardio: topWeight first (it chains into the finish/continue prompt on the last unit).- // cardio or already-confirmed: go straight to the prompt.+ // reps: topWeight first (it chains into the finish/continue prompt on the last unit).+ // cardio/timed or already-confirmed: go straight to the prompt.if (askTop) topWeightSheet(idx)else if (workoutDone) workoutCompleteSheet()else if (exJustDone && cardioEntry) useUI.getState().toast(t('Cardio logged'))+ else if (exJustDone && m === 'time') useUI.getState().toast(t('Hold logged'))}// Live-presence heartbeat so the admin dashboard can show who's training now. Signed-in only —@@ -198,11 +232,11 @@ function ActiveWorkout() {{unit.map((idx, k) => <div key={idx} className="ss-ex">{k > 0 && <div className="ss-amp">+</div>}<ExerciseBlock entryIdx={idx} compact- onToggle={i => toggle(idx, i)} onField={(i, f, v) => setField(idx, i, f, v)} onBumpAll={(f, v) => bumpAll(idx, f, v)} onAddSet={() => addSet(idx)} onRemoveSet={() => removeSet(idx)} />+ onToggle={i => toggle(idx, i)} onField={(i, f, v) => setField(idx, i, f, v)} onAddSet={() => addSet(idx)} onRemoveSet={() => removeSet(idx)} onStartTimed={i => startTimed(idx, i)} /></div>)}</div>) : (- <ExerciseBlock entryIdx={cur} onToggle={i => toggle(cur, i)} onField={(i, f, v) => setField(cur, i, f, v)} onBumpAll={(f, v) => bumpAll(cur, f, v)} onAddSet={() => addSet(cur)} onRemoveSet={() => removeSet(cur)} />+ <ExerciseBlock entryIdx={cur} onToggle={i => toggle(cur, i)} onField={(i, f, v) => setField(cur, i, f, v)} onAddSet={() => addSet(cur)} onRemoveSet={() => removeSet(cur)} onStartTimed={i => startTimed(cur, i)} />)}</> : <div className="empty"><div className="ico"><Icon name="shuffle" /></div>{t('Freestyle workout — add your first exercise.')}</div>}@@ -213,9 +247,11 @@ function ActiveWorkout() {</div><div style={{ height: 10 }} /><Button onClick={() => exercisePicker(ex => exConfigSheet(ex, null, cfg => update(s => {- s.active.entries.push({ id: ex.id, target: { ...cfg }, sets: buildSets(s, { ...cfg, id: ex.id }) })+ const full = { ...cfg, id: ex.id }+ const plan = nextPrescription(s, full, s.routines.find(r => r.id === s.active.routineId))+ s.active.entries.push({ id: ex.id, target: { ...cfg }, plan, sets: applyPrescription(buildSets(s, full), plan) })s.active.cur = s.active.entries.length - 1- })))} icon="plus">{t('Add exercise')}</Button>+ }), null, S.routines.find(r => r.id === A.routineId)))} icon="plus">{t('Add exercise')}</Button><div style={{ height: 10 }} />{(() => {const exDone = A.entries.filter(e => e.sets.length && e.sets.every(s => s.done)).length