A shared plan file can no longer take the app down

Importing a plan whose exercise ids this build doesn't know — a
hand-edited file, an export from a build with a different dataset — put
those ids straight into a routine. The routine editor skipped them
silently (you could neither see nor delete them), and starting the
routine reached for ex.n on undefined: white screen, no tab bar, no way
back. The running workout is persisted, so it came back on every reload.

Three layers, so this class of bug can't reach the screen again:

  · parsePlan() drops ids that resolve to neither the library nor a
    custom exercise carried in the same file, and the import sheet says
    how many were left out.
  · exOr() renders an unresolvable id as a placeholder, so the routine
    editor shows it (and lets you remove it) instead of hiding it, and
    the workout view survives one.
  · an ErrorBoundary around the routes: it keeps the tab bar alive,
    offers a reload, and can discard a running workout that can't be
    drawn. It is keyed on the route, so switching tabs clears it.

Turning the schedule switch on now really replaces Mon–Sun, as the
switch has always claimed. It only wrote the days the shared plan filled,
so days it left empty kept your own routine and you silently ended up
training a mix of two plans.

Also here, because they sit in the same lines: the tags that carry a unit
or a whole sentence opt out of the capitalise rule ("Best: 85 Kg", "Last
Time You Hit All Reps"), and the workout header's "best" now includes the
working weight you confirmed, so it agrees with the sheet that asked for
it.
This commit is contained in:
Duarte Santos committed 2026-07-24 23:45:04 +02:00
1 parent c8a68e37e1
commit 3d5b00cecd
8 files changed
+126 -36

No files matched your search

+19 -14
View File
@@ -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 />
+41
View File
@@ -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>
)
}
}
+5 -3
View File
@@ -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{
+8
View File
@@ -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 }
+27 -6
View File
@@ -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) : raw
if (!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>
+10 -2
View File
@@ -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} />
+4 -2
View File
@@ -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.sg
return <div key={i}>
{unitFirst.has(i) && <div className="ss-label"><Icon name="link" />{t('Superset')}</div>}
+12 -9
View File
@@ -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 : 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) }
@@ -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' : '')}>