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
An exercise can be logged by time instead of reps (#16)
Duarte Santosec46c7e20df6
diff --git a/frontend/src/components/RestTimer.jsx b/frontend/src/components/RestTimer.jsxindex cc6128d9d..24e24c1cb 100644--- a/frontend/src/components/RestTimer.jsx+++ b/frontend/src/components/RestTimer.jsx@@ -3,21 +3,40 @@ import { useUI } from '../store/useUI.js'import { t } from '../lib/i18n.js'import { Button } from './ui.jsx'+const clock = sec => Math.floor(sec / 60) + ':' + String(sec % 60).padStart(2, '0')++// One bar, two meanings: the rest countdown between sets, and the work countdown during a+// timed set (issue #16). They are mutually exclusive by construction — startWork() stops any+// running rest — so the bar can never have to show both, and a work set gets its own colour+// plus a "Done" that logs the time actually held.export default function RestTimer() {const timer = useUI(s => s.timer)- const { addRest, stopRest } = useUI()+ const work = useUI(s => s.work)+ const { addRest, stopRest, finishWorkEarly, stopWork } = useUI()+ const on = work || timer// The bar is fixed above the tab bar and floats over whatever is beneath it — during a// rest that was the next set's row. Extra bottom padding lets the page scroll clear.useEffect(() => {- document.body.classList.toggle('resting', !!timer)+ document.body.classList.toggle('resting', !!on)return () => document.body.classList.remove('resting')- }, [!!timer])- if (!timer) return null- const pct = (timer.left / timer.total) * 100- const m = Math.floor(timer.left / 60), s = String(timer.left % 60).padStart(2, '0')+ }, [!!on])+ if (!on) return null+ const pct = (on.left / on.total) * 100++ if (work) return (+ <div id="timer" className="working">+ <div className="t">{clock(work.left)}</div>+ <div className="grow">+ {work.label && <div className="lbl">{work.label}</div>}+ <div className="bar"><i style={{ width: pct + '%' }} /></div>+ </div>+ <Button size="sm" onClick={stopWork}>{t('Cancel')}</Button>+ <Button size="sm" variant="primary" icon="check" onClick={finishWorkEarly}>{t('Done')}</Button>+ </div>+ )return (<div id="timer">- <div className="t">{m}:{s}</div>+ <div className="t">{clock(timer.left)}</div><div className="bar"><i style={{ width: pct + '%' }} /></div><Button size="sm" icon="plus" onClick={() => addRest(15)}>15s</Button><Button size="sm" variant="primary" onClick={stopRest}>{t('Skip')}</Button>diff --git a/frontend/src/lib/history.js b/frontend/src/lib/history.jsindex 6e6b4b097..e9d773995 100644--- a/frontend/src/lib/history.js+++ b/frontend/src/lib/history.js@@ -2,15 +2,53 @@import { todayISO, isoOf, weekKey, fmtNum } from './format.js'import { isCardio } from './exercises.js'-// One-line summary of a logged set — cardio shows time/speed, strength shows weight×reps.-export function setLabel(id, s) {- if (isCardio(id)) return `${s.min || 0} min @ ${fmtNum(s.speed || 0)} km/h`+// How an exercise is logged (issue #16). This used to be derived from the body part alone,+// which meant a plank or a farmer's carry could only be timed by filing it under cardio.+// A routine entry can now say so explicitly:+// reps — weight × reps sets look like { w, r }+// time — a work duration sets look like { sec, w } (w = 0 for bodyweight)+// cardio — duration + speed sets look like { min, speed }+// An entry without `mode` behaves exactly as before, so every existing plan, workout and+// plan file is read unchanged and nothing needs migrating.+export function modeOf(cfg) {+ const m = cfg && cfg.mode+ if (m === 'reps' || m === 'time' || m === 'cardio') return m+ return isCardio(cfg && cfg.id) ? 'cardio' : 'reps'+}+export const isTimed = cfg => modeOf(cfg) === 'time'++// mm:ss for a work duration — seconds alone read badly past a minute ("90 s" vs "1:30").+export function fmtSec(sec) {+ const n = Math.max(0, Math.round(Number(sec) || 0))+ return Math.floor(n / 60) + ':' + String(n % 60).padStart(2, '0')+}++// One-line summary of a logged set. `cfg` carries the mode when the caller has it (a routine+// entry or a workout entry); passing an id alone keeps the old body-part behaviour.+export function setLabel(id, s, cfg) {+ const mode = modeOf(cfg || { id })+ if (mode === 'cardio') return `${s.min || 0} min @ ${fmtNum(s.speed || 0)} km/h`+ if (mode === 'time') return fmtSec(s.sec) + (s.w > 0 ? ` · ${fmtNum(s.w)}` : '')return `${fmtNum(s.w || 0)}×${s.r || 0}`}// Default config for a freshly added exercise.-export function defaultConfig(id) {- return isCardio(id) ? { sets: 1, min: 20, speed: 8 } : { sets: 3, reps: 10, weight: 0 }+export function defaultConfig(id, mode) {+ const m = mode || modeOf({ id })+ if (m === 'cardio') return { sets: 1, min: 20, speed: 8 }+ if (m === 'time') return { sets: 3, sec: 45, weight: 0, mode: 'time' }+ return { sets: 3, reps: 10, weight: 0, mode: 'reps' }+}+// One-line summary of a planned exercise ("3 × 10 · 60 kg"), shared by the routine editor+// and the plan export so a mode is described the same way everywhere.+export function exLine(cfg, unit) {+ const mode = modeOf(cfg)+ const n = cfg.sets || 1+ const load = cfg.weight ? ' · ' + fmtNum(cfg.weight) + ' ' + unit : ''+ if (mode === 'cardio') return `${n} × ${cfg.min || 20} min @ ${fmtNum(cfg.speed || 8)} km/h`+ if (mode === 'time') return `${n} × ${fmtSec(cfg.sec || 45)}${load}`+ return `${n} × ${cfg.reps}${load}`}+// Drop superset ids that no longer have an adjacent partner (after unlink/reorder/remove).export function cleanupSg(ex) {ex.forEach((e, i) => {@@ -21,7 +59,10 @@ export function cleanupSg(ex) {export function lastEntryFor(S, exId) {for (let i = S.workouts.length - 1; i >= 0; i--) {const en = S.workouts[i].entries.find(e => e.id === exId)- if (en && en.sets.some(s => s.done)) return { d: S.workouts[i].d, sets: en.sets.filter(s => s.done) }+ // `target` is what the session prescribed; finished workouts carry it so labels and the+ // progression engine can read a session back the way it was logged. Older workouts have+ // none — modeOf() falls back to the body part for them, which is what they were.+ if (en && en.sets.some(s => s.done)) return { d: S.workouts[i].d, sets: en.sets.filter(s => s.done), target: en.target || null }}return null}@@ -49,19 +90,34 @@ export function effectiveRoutine(S, iso) {export function buildSets(S, cfg) {const last = lastEntryFor(S, cfg.id)const n = Math.max(1, cfg.sets || 1)+ const mode = modeOf(cfg)const sets = []- if (isCardio(cfg.id)) {+ // Last time's set at the same position, falling back to its final set when the plan grew.+ const prevAt = i => (last ? (last.sets[i] || last.sets[last.sets.length - 1]) : null)++ if (mode === 'cardio') {for (let i = 0; i < n; i++) {- const prev = last ? (last.sets[i] || last.sets[last.sets.length - 1]) : null+ const prev = prevAt(i)sets.push({ min: prev ? prev.min : (cfg.min || 20), speed: prev ? prev.speed : (cfg.speed || 8), done: false })}return sets}+ if (mode === 'time') {+ for (let i = 0; i < n; i++) {+ // Only carry a previous value over when it came from a timed set — switching an+ // exercise from reps to time must not seed the duration from a rep count.+ const prev = prevAt(i)+ const carried = prev && prev.sec > 0 ? prev : null+ sets.push({ sec: carried ? carried.sec : (cfg.sec || 45), w: carried ? (carried.w || 0) : (cfg.weight || 0), done: false })+ }+ return sets+ }const conf = S.exWeights[cfg.id]for (let i = 0; i < n; i++) {- const prev = last ? (last.sets[i] || last.sets[last.sets.length - 1]) : null- const w = conf && conf.w > 0 ? conf.w : (prev ? prev.w : cfg.weight)- sets.push({ w, r: prev ? prev.r : cfg.reps, done: false })+ const prev = prevAt(i)+ const usable = prev && prev.r > 0 ? prev : null+ const w = conf && conf.w > 0 ? conf.w : (usable ? usable.w : cfg.weight)+ sets.push({ w, r: usable ? usable.r : cfg.reps, done: false })}return sets}diff --git a/frontend/src/lib/history.test.js b/frontend/src/lib/history.test.jsnew file mode 100644index 000000000..19d394444--- /dev/null+++ b/frontend/src/lib/history.test.js@@ -0,0 +1,137 @@+import { describe, it, expect } from 'vitest'+import { modeOf, isTimed, fmtSec, setLabel, defaultConfig, buildSets, exLine, workoutVolume } from './history.js'+import { EXDB } from './exercises.js'++// Real ids out of the shipped catalogue, so the body-part fallback is exercised for real.+const CARDIO = EXDB.find(e => e.bp === 'cardio').id+const LIFT = EXDB.find(e => e.bp !== 'cardio').id++describe('modeOf', () => {+ it('falls back to the body part when a plan has no mode — every existing plan keeps working', () => {+ expect(modeOf({ id: CARDIO })).toBe('cardio')+ expect(modeOf({ id: LIFT })).toBe('reps')+ expect(modeOf({ id: 'no-such-exercise' })).toBe('reps')+ expect(modeOf({})).toBe('reps')+ expect(modeOf(null)).toBe('reps')+ expect(modeOf(undefined)).toBe('reps')+ })++ it('lets an explicit mode win over the body part', () => {+ expect(modeOf({ id: LIFT, mode: 'time' })).toBe('time')+ expect(modeOf({ id: CARDIO, mode: 'reps' })).toBe('reps')+ expect(modeOf({ id: CARDIO, mode: 'time' })).toBe('time')+ })++ it('ignores a mode it does not know rather than trusting a bad file', () => {+ expect(modeOf({ id: LIFT, mode: 'nonsense' })).toBe('reps')+ expect(modeOf({ id: CARDIO, mode: '' })).toBe('cardio')+ })++ it('exposes the timed check', () => {+ expect(isTimed({ id: LIFT, mode: 'time' })).toBe(true)+ expect(isTimed({ id: LIFT })).toBe(false)+ })+})++describe('fmtSec', () => {+ it('reads as a clock, not a pile of seconds', () => {+ expect(fmtSec(0)).toBe('0:00')+ expect(fmtSec(9)).toBe('0:09')+ expect(fmtSec(45)).toBe('0:45')+ expect(fmtSec(60)).toBe('1:00')+ expect(fmtSec(90)).toBe('1:30')+ expect(fmtSec(605)).toBe('10:05')+ })+ it('is defensive about junk input', () => {+ expect(fmtSec(-5)).toBe('0:00')+ expect(fmtSec(undefined)).toBe('0:00')+ expect(fmtSec(null)).toBe('0:00')+ expect(fmtSec(NaN)).toBe('0:00')+ expect(fmtSec(44.6)).toBe('0:45')+ })+})++describe('setLabel', () => {+ it('describes each mode in its own terms', () => {+ expect(setLabel(LIFT, { w: 60, r: 10 })).toBe('60×10')+ expect(setLabel(CARDIO, { min: 20, speed: 9 })).toBe('20 min @ 9 km/h')+ expect(setLabel(LIFT, { sec: 45, w: 0 }, { mode: 'time' })).toBe('0:45')+ expect(setLabel(LIFT, { sec: 90, w: 20 }, { mode: 'time' })).toBe('1:30 · 20')+ })++ it('reads a legacy set with no config exactly as before', () => {+ expect(setLabel(LIFT, { w: 0, r: 0 })).toBe('0×0')+ expect(setLabel(CARDIO, {})).toBe('0 min @ 0 km/h')+ })+})++describe('defaultConfig', () => {+ it('gives each mode a sensible starting point', () => {+ expect(defaultConfig(LIFT)).toEqual({ sets: 3, reps: 10, weight: 0, mode: 'reps' })+ expect(defaultConfig(CARDIO)).toEqual({ sets: 1, min: 20, speed: 8 })+ expect(defaultConfig(LIFT, 'time')).toEqual({ sets: 3, sec: 45, weight: 0, mode: 'time' })+ })+})++describe('exLine', () => {+ it('summarises a planned exercise per mode', () => {+ expect(exLine({ id: LIFT, sets: 3, reps: 10 }, 'kg')).toBe('3 × 10')+ expect(exLine({ id: LIFT, sets: 3, reps: 10, weight: 60 }, 'kg')).toBe('3 × 10 · 60 kg')+ expect(exLine({ id: LIFT, sets: 3, sec: 45, mode: 'time' }, 'kg')).toBe('3 × 0:45')+ expect(exLine({ id: LIFT, sets: 2, sec: 90, weight: 20, mode: 'time' }, 'kg')).toBe('2 × 1:30 · 20 kg')+ expect(exLine({ id: CARDIO, sets: 1, min: 20, speed: 8 }, 'kg')).toBe('1 × 20 min @ 8 km/h')+ })+})++const emptyS = { workouts: [], exWeights: {} }++describe('buildSets', () => {+ it('builds reps sets from the plan when there is no history', () => {+ expect(buildSets(emptyS, { id: LIFT, sets: 3, reps: 8, weight: 50 }))+ .toEqual([{ w: 50, r: 8, done: false }, { w: 50, r: 8, done: false }, { w: 50, r: 8, done: false }])+ })++ it('builds timed sets, carrying the planned duration and load', () => {+ expect(buildSets(emptyS, { id: LIFT, mode: 'time', sets: 2, sec: 60, weight: 20 }))+ .toEqual([{ sec: 60, w: 20, done: false }, { sec: 60, w: 20, done: false }])+ })++ it('builds cardio sets unchanged', () => {+ expect(buildSets(emptyS, { id: CARDIO, sets: 1, min: 25, speed: 9 }))+ .toEqual([{ min: 25, speed: 9, done: false }])+ })++ it('carries last time\'s numbers forward within the same mode', () => {+ const S = { exWeights: {}, workouts: [{ d: '2026-01-01', entries: [{ id: LIFT, target: { mode: 'time' }, sets: [{ sec: 70, w: 10, done: true }] }] }] }+ expect(buildSets(S, { id: LIFT, mode: 'time', sets: 2, sec: 45, weight: 0 }))+ .toEqual([{ sec: 70, w: 10, done: false }, { sec: 70, w: 10, done: false }])+ })++ it('does not seed a duration from a rep count when an exercise switches to time', () => {+ const S = { exWeights: {}, workouts: [{ d: '2026-01-01', entries: [{ id: LIFT, sets: [{ w: 60, r: 10, done: true }] }] }] }+ expect(buildSets(S, { id: LIFT, mode: 'time', sets: 1, sec: 45, weight: 0 }))+ .toEqual([{ sec: 45, w: 0, done: false }])+ })++ it('does not seed reps from a timed set when an exercise switches back', () => {+ const S = { exWeights: {}, workouts: [{ d: '2026-01-01', entries: [{ id: LIFT, target: { mode: 'time' }, sets: [{ sec: 70, w: 10, done: true }] }] }] }+ expect(buildSets(S, { id: LIFT, mode: 'reps', sets: 1, reps: 8, weight: 40 }))+ .toEqual([{ w: 40, r: 8, done: false }])+ })++ it('still prefers the confirmed working weight for reps sets', () => {+ const S = { exWeights: { [LIFT]: { w: 75 } }, workouts: [{ d: '2026-01-01', entries: [{ id: LIFT, sets: [{ w: 60, r: 10, done: true }] }] }] }+ expect(buildSets(S, { id: LIFT, sets: 1, reps: 8, weight: 50 })).toEqual([{ w: 75, r: 10, done: false }])+ })+})++describe('workoutVolume', () => {+ it('counts reps work and leaves timed/cardio sets out — there is no weight × reps for a hold', () => {+ const w = { entries: [+ { id: LIFT, sets: [{ w: 60, r: 10, done: true }, { w: 60, r: 10, done: false }] },+ { id: LIFT, target: { mode: 'time' }, sets: [{ sec: 60, w: 20, done: true }] },+ { id: CARDIO, sets: [{ min: 20, speed: 9, done: true }] }+ ] }+ expect(workoutVolume(w)).toBe(600)+ })+})diff --git a/frontend/src/lib/plan-share.js b/frontend/src/lib/plan-share.jsindex 4fd2fcf47..fc595b3ef 100644--- a/frontend/src/lib/plan-share.js+++ b/frontend/src/lib/plan-share.js@@ -8,7 +8,8 @@// 2. A clean, printable page (Save as PDF) where a single exercise never splits across// a page break — each exercise, and each routine that fits, stays in one place.-import { EXIDX, isCardio } from './exercises.js'+import { EXIDX } from './exercises.js'+import { modeOf, fmtSec } from './history.js'import { uid, todayISO, DAYN, fmtNum, exCount } from './format.js'import { t } from './i18n.js'@@ -18,13 +19,25 @@ const WEEK_ORDER = [1, 2, 3, 4, 5, 6, 0] // Mon-first, matching the Plan scree// Keep only the meaningful config fields, so the file stays small and readable.function cleanEx(e) {const o = { id: e.id, sets: e.sets }- if (isCardio(e.id)) {+ const mode = modeOf(e)+ if (mode === 'cardio') {if (e.min != null) o.min = e.minif (e.speed != null) o.speed = e.speed+ } else if (mode === 'time') {+ // Written out even though 'reps' is the fallback for a non-cardio id: a plan file that+ // dropped the mode would turn a 45-second plank into a 45-rep one at the other end.+ o.mode = 'time'+ if (e.sec != null) o.sec = e.sec+ if (e.weight) o.weight = e.weight} else {if (e.reps != null) o.reps = e.repsif (e.weight) o.weight = e.weight}+ // Progression settings travel with the plan — a shared Greyskull routine that arrives+ // without its rule is just a list of weights.+ if (e.prog) o.prog = e.prog+ if (e.inc > 0) o.inc = e.inc+ if (e.repsMin != null) o.repsMin = e.repsMinif (e.sg) o.sg = e.sgreturn o}@@ -32,7 +45,7 @@ function cleanEx(e) {/** Build the shareable bundle: every routine, the week schedule, referenced customs. */export function buildPlanBundle(S, name) {const routines = (S.routines || []).map(r => ({- id: r.id, name: r.name, emoji: r.emoji, ex: (r.ex || []).map(cleanEx)+ id: r.id, name: r.name, emoji: r.emoji, ...(r.prog ? { prog: r.prog } : {}), ex: (r.ex || []).map(cleanEx)}))const usedIds = new Set(routines.flatMap(r => r.ex.map(e => e.id)))const customEx = (S.customEx || [])@@ -105,6 +118,7 @@ export function mergePlan(s, bundle, { schedule } = {}) {id: nid,name: r.name || t('Shared routine'),emoji: r.emoji,+ ...(r.prog ? { prog: r.prog } : {}),ex: (r.ex || []).map(e => ({ ...e, id: exIdMap[e.id] || e.id }))})})@@ -122,14 +136,15 @@ export function mergePlan(s, bundle, { schedule } = {}) {const esc = str => String(str == null ? '' : str).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"')-// One exercise's scheme, e.g. "3 × 10 · 60 kg" or "2 × 20 min @ 8 km/h".+// One exercise's scheme, e.g. "3 × 10 · 60 kg", "3 × 0:45" or "2 × 20 min @ 8 km/h".function scheme(e, unit) {const sets = e.sets || 1- if (isCardio(e.id)) {+ const mode = modeOf(e)+ if (mode === 'cardio') {const body = `${e.min || 20} min @ ${fmtNum(e.speed || 8)} km/h`return sets > 1 ? `${sets} × ${body}` : body}- let s = `${sets} × ${e.reps ?? 10}`+ let s = mode === 'time' ? `${sets} × ${fmtSec(e.sec || 45)}` : `${sets} × ${e.reps ?? 10}`if (e.weight) s += ` · ${fmtNum(e.weight)} ${unit}`return s}diff --git a/frontend/src/store/useUI.js b/frontend/src/store/useUI.jsindex 130c1b217..70c77bfde 100644--- a/frontend/src/store/useUI.js+++ b/frontend/src/store/useUI.js@@ -13,11 +13,15 @@ const cancelPushRestTimer = () => { if (useStore.getState().user) api('/api/pushlet toastTm = nulllet timerInt = nulllet timerTick = null+let workInt = null+let workTick = null+let workDone = nullexport const useUI = create((set, get) => ({sheets: [], // { id, render:(close)=>JSX, kind:'sheet'|'center', locked }toastMsg: '',- timer: null, // { left, total }+ timer: null, // rest countdown between sets — { left, total, endsAt }+ work: null, // work countdown DURING a timed set (issue #16) — { left, total, endsAt, label }openSheet(render, { kind = 'sheet', locked = false } = {}) {const id = uid()@@ -67,5 +71,58 @@ export const useUI = create((set, get) => ({if (timerTick) document.removeEventListener('visibilitychange', timerTick); timerTick = nullif (get().timer) cancelPushRestTimer()set({ timer: null })+ },++ /* ---- work timer (issue #16) ----+ Times the set itself, not the recovery after it. Kept separate from the rest timer on+ purpose: the two mean opposite things, they must never run together, and a work set is+ something you are watching — so it gets no server push (that endpoint says "rest over",+ and a plank does not need a notification you are staring at anyway).+ `onDone(elapsedSec)` is called both when the countdown reaches zero and on an early+ finish; the elapsed time is what actually gets logged, so stopping at 0:38 of a 0:45+ hold records 0:38 rather than crediting the full target. */+ startWork(sec, label, onDone) {+ get().stopWork()+ get().stopRest()+ const total = Math.max(1, Math.round(sec) || 1)+ const endsAt = Date.now() + total * 1000+ workDone = onDone+ set({ work: { left: total, total, endsAt, label } })+ workTick = () => {+ const wk = get().work+ if (!wk) return+ const left = Math.max(0, Math.round((wk.endsAt - Date.now()) / 1000))+ if (left === wk.left) return+ const snd = useStore.getState().S.sound+ if (left <= 0) {+ beep(snd, 880, 0.15); beep(snd, 880, 0.15, 0.25); beep(snd, 1320, 0.4, 0.5)+ vibrate([200, 100, 200])+ const done = workDone+ get().stopWork()+ if (done) done(wk.total)+ return+ }+ if (left <= 3) beep(snd, 660, 0.1)+ set({ work: { ...wk, left } })+ }+ workInt = setInterval(workTick, 1000)+ document.addEventListener('visibilitychange', workTick)+ },+ // Ended the hold early — log what was actually held.+ finishWorkEarly() {+ const wk = get().work+ if (!wk) return+ const elapsed = Math.max(1, wk.total - wk.left)+ const done = workDone+ vibrate(30)+ get().stopWork()+ if (done) done(elapsed)+ },+ // Abandon without logging anything.+ stopWork() {+ if (workInt) clearInterval(workInt); workInt = null+ if (workTick) document.removeEventListener('visibilitychange', workTick); workTick = null+ workDone = null+ set({ work: null })}}))