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
A shared plan file can no longer take the app down
Duarte Santos3d5b00cecd3a
diff --git a/frontend/src/App.jsx b/frontend/src/App.jsxindex ae9e3031c..48cba0c56 100644--- a/frontend/src/App.jsx+++ b/frontend/src/App.jsx@@ -9,6 +9,7 @@ import { setNav } from './lib/nav.js'import { startFlow } from './sheets.jsx'import Icon from './components/Icon.jsx'import TabBar from './components/TabBar.jsx'+import ErrorBoundary from './components/ErrorBoundary.jsx'import Modals from './components/Modals.jsx'import Toast from './components/Toast.jsx'import RestTimer from './components/RestTimer.jsx'@@ -57,21 +58,25 @@ function Shell() {return (<>+ {/* keyed on the route: a view that throws is contained, and switching tabs+ re-mounts the boundary, so the tab bar is always a way out */}<div id="app" className="vfade" key={loc.pathname}>- {!authed ? <Login /> : (- <Routes>- <Route path="/home" element={<Home />} />- <Route path="/plan" element={<Plan />} />- <Route path="/plan/r/:id" element={<RoutineEdit />} />- <Route path="/workout" element={<Workout />} />- <Route path="/stats" element={<Stats />} />- <Route path="/history" element={<History />} />- <Route path="/library" element={<Library />} />- <Route path="/settings" element={<Settings />} />- <Route path="/admin" element={user?.admin ? <Admin /> : <Navigate to="/home" replace />} />- <Route path="*" element={<Navigate to="/home" replace />} />- </Routes>- )}+ <ErrorBoundary>+ {!authed ? <Login /> : (+ <Routes>+ <Route path="/home" element={<Home />} />+ <Route path="/plan" element={<Plan />} />+ <Route path="/plan/r/:id" element={<RoutineEdit />} />+ <Route path="/workout" element={<Workout />} />+ <Route path="/stats" element={<Stats />} />+ <Route path="/history" element={<History />} />+ <Route path="/library" element={<Library />} />+ <Route path="/settings" element={<Settings />} />+ <Route path="/admin" element={user?.admin ? <Admin /> : <Navigate to="/home" replace />} />+ <Route path="*" element={<Navigate to="/home" replace />} />+ </Routes>+ )}+ </ErrorBoundary></div><TabBar onStart={startFlow} /><RestTimer />diff --git a/frontend/src/components/ErrorBoundary.jsx b/frontend/src/components/ErrorBoundary.jsxnew file mode 100644index 000000000..c2c0e9d68--- /dev/null+++ b/frontend/src/components/ErrorBoundary.jsx@@ -0,0 +1,41 @@+import { Component } from 'react'+import { useStore } from '../store/useStore.js'+import { t } from '../lib/i18n.js'+import Icon from './Icon.jsx'+import { Button } from './ui.jsx'++/**+ * Last line of defence: one bad render used to blank the whole app, with no way back —+ * a workout referencing an exercise the build doesn't know would white-screen and, since+ * the running workout is persisted, do it again on every reload.+ *+ * Sits inside #app so the tab bar stays usable; the shell keys this subtree on the route,+ * so switching tabs re-mounts it and clears the error by itself.+ */+export default class ErrorBoundary extends Component {+ constructor(props) { super(props); this.state = { failed: false } }+ static getDerivedStateFromError() { return { failed: true } }+ componentDidCatch(err) { console.error('openGym render error:', err) }++ render() {+ if (!this.state.failed) return this.props.children+ const active = useStore.getState().S.active+ return (+ <div className="narrow">+ <div className="empty" style={{ marginTop: '18vh' }}>+ <div className="ico"><Icon name="info" /></div>+ <div style={{ fontWeight: 600, marginBottom: 6 }}>{t('Something went wrong')}</div>+ {t('This screen could not be drawn. Your data is safe on this device.')}+ </div>+ <Button variant="primary" icon="reset" onClick={() => location.reload()}>{t('Reload openGym')}</Button>+ {active && <>+ <div style={{ height: 8 }} />+ <Button variant="danger" icon="trash" onClick={() => {+ useStore.getState().update(s => { s.active = null })+ location.reload()+ }}>{t('Discard the running workout')}</Button>+ </>}+ </div>+ )+ }+}diff --git a/frontend/src/index.css b/frontend/src/index.cssindex 4c36ef1bb..b216a4a89 100644--- a/frontend/src/index.css+++ b/frontend/src/index.css@@ -153,10 +153,12 @@ button,.chip,.tile,.item,.wday,.cal-d,.swatch,.hm-c,.lrow,.seg button,.stp butto.small{font-size:13px;line-height:1.38}.accent{color:var(--acc)}.capitalize{text-transform:capitalize}-.nocap{text-transform:none}/* exercise names and body-part/equipment terms arrive lowercase from the dataset,- so capitalising is opt-in per element — blanket-capitalising a row also turned- "60 kg" into "60 Kg" and whole sentences into Title Case. */+ so tags and chips capitalise by default. Anything that is a unit or a sentence opts+ back out — blanket-capitalising turned "60 kg" into "60 Kg" and a whole hint into+ Title Case. The compound selectors are needed: .tag/.chip come later in this file+ and would otherwise win on source order. */+.nocap,.tag.nocap,.chip.nocap{text-transform:none}/* ---------------------------------------------------------------- layout -- */#app{diff --git a/frontend/src/lib/exercises.js b/frontend/src/lib/exercises.jsindex ba39e7856..20d82d278 100644--- a/frontend/src/lib/exercises.js+++ b/frontend/src/lib/exercises.js@@ -1,4 +1,5 @@import { EXDB } from './exercises-data.js'+import { t } from './i18n.js'export { EXDB }export const EXIDX = {}@@ -35,3 +36,10 @@ export const gifSrc = ex => GIF_BASE + ex.gif// Cardio exercises log time + speed instead of weight × reps.export const isCardio = idOrEx => (typeof idOrEx === 'string' ? EXIDX[idOrEx] : idOrEx)?.bp === 'cardio'++// An id that resolves to nothing — a plan file built against a different exercise dataset,+// a custom exercise deleted on another device before the sync arrived — still has to+// render. A placeholder keeps it visible (and removable) instead of taking the whole view+// down on the first `ex.n`.+export const exOr = id => EXIDX[id] ||+ { id, n: t('Unknown exercise'), bp: '', tg: '', eq: '', sm: [], st: [], missing: true }diff --git a/frontend/src/lib/plan-share.js b/frontend/src/lib/plan-share.jsindex ef8b46b99..4fd2fcf47 100644--- a/frontend/src/lib/plan-share.js+++ b/frontend/src/lib/plan-share.js@@ -9,7 +9,7 @@// a page break — each exercise, and each routine that fits, stays in one place.import { EXIDX, isCardio } from './exercises.js'-import { uid, todayISO, DAYN, fmtNum } from './format.js'+import { uid, todayISO, DAYN, fmtNum, exCount } from './format.js'import { t } from './i18n.js'const PLAN_FMT = 1@@ -43,18 +43,37 @@ export function buildPlanBundle(S, name) {return { opengym_plan: PLAN_FMT, exported: todayISO(), name: name || '', week, routines, customEx }}-/** Validate + normalise an imported file. Throws with a friendly message if it isn't one. */+/**+ * Validate + normalise an imported file. Throws with a friendly message if it isn't one.+ *+ * Every exercise id has to resolve — either to the built-in library or to a custom+ * exercise carried in the same file. An id that resolves to neither (a hand-edited file,+ * an export from a build with a different exercise dataset) is dropped here: kept, it+ * would sit invisibly in the routine and only surface as a blank screen when the routine+ * is trained.+ */export function parsePlan(raw) {const data = typeof raw === 'string' ? JSON.parse(raw) : rawif (!data || !data.opengym_plan || !Array.isArray(data.routines)) {throw new Error(t('this isn’t an openGym plan file'))}- const routines = data.routines.filter(r => r && Array.isArray(r.ex))+ const customEx = (Array.isArray(data.customEx) ? data.customEx : []).filter(c => c && c.id)+ const known = new Set(customEx.map(c => c.id))+ let dropped = 0+ const routines = data.routines.filter(r => r && Array.isArray(r.ex)).map(r => ({+ ...r,+ ex: r.ex.filter(e => {+ const ok = !!e && (known.has(e.id) || !!EXIDX[e.id])+ if (!ok) dropped+++ return ok+ })+ }))return {name: (data.name || '').trim(),routines,week: data.week || {},- customEx: Array.isArray(data.customEx) ? data.customEx : [],+ customEx,+ dropped,routineCount: routines.length,exerciseCount: routines.reduce((n, r) => n + r.ex.length, 0),scheduledDays: WEEK_ORDER.filter(d => data.week?.[d]).length@@ -65,7 +84,8 @@ export function parsePlan(raw) {* Merge a parsed bundle into a draft state `s` (call inside store.update).* - customs: reuse one you already have with the same name + body part, else add it fresh* - routines: always added as NEW routines (fresh ids) — never overwrites yours- * - schedule: optional; when on, points your week at the freshly-added routines+ * - schedule: optional; when on, the shared week REPLACES yours (days the shared plan+ * leaves empty become rest days — a half-overwritten week would silently mix two plans)*/export function mergePlan(s, bundle, { schedule } = {}) {s.customEx = s.customEx || []@@ -89,6 +109,7 @@ export function mergePlan(s, bundle, { schedule } = {}) {})})if (schedule) {+ WEEK_ORDER.forEach(d => { delete s.week[d] })Object.entries(bundle.week || {}).forEach(([d, oldId]) => {if (ridMap[oldId]) s.week[d] = ridMap[oldId]})@@ -136,7 +157,7 @@ function routineHTML(r, unit) {? `<div class="ss"><div class="ss-tag">${esc(t('Superset'))}</div><div class="ss-items">${items}</div></div>`: items}).join('')- const count = t('{0} exercises', r.ex.length).replace('{0}', r.ex.length)+ const count = exCount(r.ex.length)return `<section class="routine"><div class="r-head"><h2>${esc(r.name)}</h2><span class="r-count">${esc(count)}</span></div><div class="ex-list">${rows || `<div class="ex empty">${esc(t('No exercises yet.'))}</div>`}</div>diff --git a/frontend/src/sheets.jsx b/frontend/src/sheets.jsxindex 2a1fe1146..fd520d671 100644--- a/frontend/src/sheets.jsx+++ b/frontend/src/sheets.jsx@@ -532,10 +532,18 @@ function PlanImport({ bundle, close }) {return <><h3>{bundle.name ? t('Import “{0}”', bundle.name) : t('Import this plan')}</h3><div className="muted small" style={{ marginBottom: 14 }}>- {t('{0} routines · {1} exercises', bundle.routineCount, bundle.exerciseCount)}- {bundle.scheduledDays > 0 ? ' · ' + t('scheduled on {0} days', bundle.scheduledDays) : ''}+ {t(bundle.routineCount === 1 ? '{0} routine' : '{0} routines', bundle.routineCount)}+ {' · ' + exCount(bundle.exerciseCount)}+ {bundle.scheduledDays > 0+ ? ' · ' + t(bundle.scheduledDays === 1 ? 'scheduled on {0} day' : 'scheduled on {0} days', bundle.scheduledDays)+ : ''}</div><div className="dim small" style={{ marginBottom: 14, lineHeight: 1.4 }}>{t('These are added as new routines — nothing you already have is changed.')}</div>+ {bundle.dropped > 0 && <div className="small" style={{ color: 'var(--yellow)', marginBottom: 14, lineHeight: 1.4 }}>+ {t(bundle.dropped === 1+ ? '{0} exercise in the file isn’t in your library and was left out.'+ : '{0} exercises in the file aren’t in your library and were left out.', bundle.dropped)}+ </div>}{bundle.scheduledDays > 0 && <div className="row between" style={{ padding: '10px 2px', borderTop: '1px solid var(--sep)', borderBottom: '1px solid var(--sep)', marginBottom: 16, gap: 12 }}><div><div className="tt" style={{ fontSize: 15 }}>{t('Use this weekly schedule')}</div><div className="small dim">{t('Replaces your current Mon–Sun assignments.')}</div></div><Switch checked={schedule} onChange={setSchedule} />diff --git a/frontend/src/views/RoutineEdit.jsx b/frontend/src/views/RoutineEdit.jsxindex 1efb4a099..3094031fa 100644--- a/frontend/src/views/RoutineEdit.jsx+++ b/frontend/src/views/RoutineEdit.jsx@@ -1,7 +1,7 @@import { useNavigate, useParams } from 'react-router-dom'import { useEffect } from 'react'import { useStore } from '../store/useStore.js'-import { EXIDX, isCardio } from '../lib/exercises.js'+import { exOr, isCardio } from '../lib/exercises.js'import { fmtNum, uid } from '../lib/format.js'import { t } from '../lib/i18n.js'import { supersetUnits, cleanupSg } from '../lib/history.js'@@ -47,7 +47,9 @@ export default function RoutineEdit() {</div>{r.ex.length ? <div className="list">{r.ex.map((e, i) => {- const ex = EXIDX[e.id]; if (!ex) return null+ // 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.+ const ex = exOr(e.id)const linkedPrev = i > 0 && e.sg && r.ex[i - 1].sg === e.sgreturn <div key={i}>{unitFirst.has(i) && <div className="ss-label"><Icon name="link" />{t('Superset')}</div>}diff --git a/frontend/src/views/Workout.jsx b/frontend/src/views/Workout.jsxindex 2c5143b18..cdb6b37a1 100644--- a/frontend/src/views/Workout.jsx+++ b/frontend/src/views/Workout.jsx@@ -2,9 +2,9 @@ import { useEffect, useState } from 'react'import { useNavigate } from 'react-router-dom'import { useStore } from '../store/useStore.js'import { useUI } from '../store/useUI.js'-import { EXIDX, isCardio } from '../lib/exercises.js'+import { exOr, isCardio } from '../lib/exercises.js'import { effectiveRoutine, lastEntryFor, bestWeightFor, buildSets, setsDoneActive, supersetUnits, unitOf, setLabel } from '../lib/history.js'-import { fmtNum, fmtDate, todayISO, DAYN } from '../lib/format.js'+import { fmtNum, fmtDate, todayISO, exCount, DAYN } from '../lib/format.js'import { beep, vibrate } from '../lib/sound.js'import { t } from '../lib/i18n.js'import { api } from '../lib/api.js'@@ -26,7 +26,7 @@ function StartChooser() {{todayR && <div className="card" style={{ borderColor: 'var(--acc)' }}><h2 className="accent">{t("Today's plan")}{todayOvr ? ' · ' + t('rescheduled') : ''}</h2><div className="row between" style={{ marginBottom: 12 }}>- <div><div className="big">{todayR.name}</div><div className="muted small">{t('{0} exercises', todayR.ex.length)}</div></div>+ <div><div className="big">{todayR.name}</div><div className="muted small">{exCount(todayR.ex.length)}</div></div><span className="lrow-i" style={{ width: 38, height: 38, borderRadius: 9, fontSize: 22 }}><Icon name={glyphOf(todayR.emoji)} /></span></div><Button variant="primary" icon="play" onClick={() => startFlow(todayR.id)}>{t('Start {0}', todayR.name)}</Button>@@ -34,7 +34,7 @@ function StartChooser() {{others.length > 0 && <><h4 className="sec">{t('Other routines')}</h4><div className="list">{others.map(r => <div key={r.id} className="item" onClick={() => startFlow(r.id)}><span className="lrow-i"><Icon name={glyphOf(r.emoji)} /></span>- <div className="grow"><div className="tt">{r.name}</div><div className="ss">{t('{0} exercises', r.ex.length)}</div></div>+ <div className="grow"><div className="tt">{r.name}</div><div className="ss">{exCount(r.ex.length)}</div></div><span className="tag acc">{t('Start')}</span></div>)}</div></>}<div style={{ height: 14 }} /><Button icon="shuffle" onClick={() => startFlow(null)}>{t('Freestyle workout (pick as you go)')}</Button>@@ -56,10 +56,12 @@ function Elapsed({ start }) {function ExerciseBlock({ entryIdx, compact, onToggle, onField, onBumpAll, onAddSet, onRemoveSet }) {const S = useStore(s => s.S)const entry = S.active.entries[entryIdx]- const ex = EXIDX[entry.id]+ const ex = exOr(entry.id)const cardio = isCardio(ex)const last = lastEntryFor(S, entry.id)- const best = cardio ? 0 : bestWeightFor(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 : nullconst 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) }@@ -81,11 +83,12 @@ function ExerciseBlock({ entryIdx, compact, onToggle, onField, onBumpAll, onAddS</div><div className="row" style={{ gap: 6, flexWrap: 'wrap', marginBottom: 8 }}>{cardio && <span className="tag acc"><Icon name="figureRun" />{t('Cardio')}</span>}- <span className="tag">{t(ex.tg || ex.bp)}</span><span className="tag">{t(ex.eq)}</span>- {best > 0 && <span className="tag">{t('Best:')} {fmtNum(best)} {S.unit}</span>}+ {(ex.tg || ex.bp) && <span className="tag">{t(ex.tg || ex.bp)}</span>}+ {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" 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>}+ {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>}<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>{entry.sets.map((s, i) => <div key={i} className={'setrow' + (s.done ? ' done' : '')}>