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
Custom exercises from an old plan import can be edited and deleted again
Duarte Santos9654fc7d12b0
diff --git a/frontend/src/components/Media.jsx b/frontend/src/components/Media.jsxindex 6ce889175..347419638 100644--- a/frontend/src/components/Media.jsx+++ b/frontend/src/components/Media.jsx@@ -1,5 +1,5 @@import { useState } from 'react'-import { imgSrc, gifSrc } from '../lib/exercises.js'+import { imgSrc, gifSrc, isCustomEx } from '../lib/exercises.js'import { useStore } from '../store/useStore.js'import { t, exerciseNameFor } from '../lib/i18n.js'import Icon from './Icon.jsx'@@ -10,7 +10,7 @@ import CustomMedia, { CustomThumb } from './CustomMedia.jsx'// name files of the shipped dataset (a stray img/gif on a custom exercise, written by a fork, is// ignored). The split is by component, not by branch, so each side keeps its own hooks in order.export default function Media(p) {- return p.ex?.custom ? <CustomMedia {...p} /> : <BuiltinMedia {...p} />+ return isCustomEx(p.ex) ? <CustomMedia {...p} /> : <BuiltinMedia {...p} />}// Big autoplaying animation; tap toggles to the still frame. `compact` shrinks it (superset cards).@@ -63,7 +63,7 @@ function BuiltinMedia({ ex, id, compact, minimizable }) {// broken-image glyph in a list of them (#281). The failure is remembered per image, so a list// that re-renders does not ask again; a new exercise in the same slot tries its own.export function Thumb(p) {- return p.ex?.custom ? <CustomThumb {...p} /> : <BuiltinThumb {...p} />+ return isCustomEx(p.ex) ? <CustomThumb {...p} /> : <BuiltinThumb {...p} />}function BuiltinThumb({ ex }) {const src = ex.img ? imgSrc(ex) : nulldiff --git a/frontend/src/lib/exercises.custom.test.js b/frontend/src/lib/exercises.custom.test.jsnew file mode 100644index 000000000..e56a59c20--- /dev/null+++ b/frontend/src/lib/exercises.custom.test.js@@ -0,0 +1,63 @@+import { afterEach, describe, expect, it } from 'vitest'+import { CATALOGUE, EXIDX, healCustomEx, isCustomEx, registerCustom } from './exercises.js'++// #378 / #358: a custom exercise stored without `custom: true` (a plan import before 1.3.8) had+// no Edit, no Delete and a broken thumbnail. Being one of the user's own is where it lives.+afterEach(() => registerCustom([]))++describe('isCustomEx', () => {+ it('a registered custom exercise without the flag is still custom', () => {+ const c = { id: 'cx1', n: 'My row', bp: 'back' }+ expect(isCustomEx(c)).toBe(false)+ registerCustom([c])+ expect(isCustomEx(c)).toBe(true)+ expect(isCustomEx({ ...c })).toBe(true) // a copy of the stored entry (a store clone)+ expect(isCustomEx(EXIDX.cx1)).toBe(true)+ })++ it('a flagged one is custom even before it is registered', () => {+ expect(isCustomEx({ id: 'cnew', n: 'x', bp: 'back', custom: true })).toBe(true)+ })++ it('a built-in is never custom, also when a custom shadows its id', () => {+ const built = CATALOGUE[0]+ expect(isCustomEx(built)).toBe(false)+ const shadow = { id: built.id, n: 'Mine', bp: 'back' }+ registerCustom([shadow])+ expect(isCustomEx(shadow)).toBe(true)+ expect(isCustomEx(built)).toBe(false)+ registerCustom([])+ expect(EXIDX[built.id]).toBe(built)+ })++ it('nothing is not custom', () => {+ expect(isCustomEx(null)).toBe(false)+ expect(isCustomEx(undefined)).toBe(false)+ expect(isCustomEx('cx1')).toBe(false)+ })+})++describe('healCustomEx', () => {+ it('puts the flag back on entries that lost it, keeping their stamp', () => {+ const list = [{ id: 'a', n: 'A', bp: 'back', _ts: 5 }, { id: 'b', n: 'B', bp: 'chest', eq: 'custom', custom: true }]+ const out = healCustomEx(list)+ expect(out).not.toBe(list)+ expect(out[0]).toEqual({ id: 'a', n: 'A', bp: 'back', _ts: 5, custom: true, eq: '' })+ expect(out[1]).toBe(list[1])+ expect(list[0].custom).toBeUndefined() // the input is not mutated+ })++ it('is idempotent and keeps identity when nothing is missing', () => {+ const once = healCustomEx([{ id: 'a', n: 'A', bp: 'back', eq: 'cable' }])+ expect(once[0].eq).toBe('cable')+ expect(healCustomEx(once)).toBe(once)+ const empty = []+ expect(healCustomEx(empty)).toBe(empty)+ expect(healCustomEx(undefined)).toBe(undefined)+ })++ it('leaves junk entries alone', () => {+ const list = [null, { id: 'a', n: 'A', bp: 'back', custom: true }]+ expect(healCustomEx(list)).toBe(list)+ })+})diff --git a/frontend/src/lib/exercises.js b/frontend/src/lib/exercises.jsindex a341b903d..ee4cd1540 100644--- a/frontend/src/lib/exercises.js+++ b/frontend/src/lib/exercises.js@@ -58,15 +58,39 @@ export function equipmentOf(list) {// Custom (user-created) exercises live in synced state S.customEx (issue #11) and are// merged into the id index here so every EXIDX[id] lookup keeps working unchanged.-let customIds = []+let customIds = new Set()+const BUILTIN = new Set(CATALOGUE)export function registerCustom(list) {customIds.forEach(id => {delete EXIDX[id]const builtIn = CATALOGUE.find(ex => ex.id === id)if (builtIn) EXIDX[id] = builtIn})- customIds = (list || []).map(e => e.id)- ;(list || []).forEach(e => { EXIDX[e.id] = e })+ const xs = (Array.isArray(list) ? list : []).filter(e => e && e.id != null)+ customIds = new Set(xs.map(e => e.id))+ xs.forEach(e => { EXIDX[e.id] = e })+}++// Whether an exercise is one of the user's own (#378, #358). Where it lives decides, not the+// `custom` flag alone: a plan import before 1.3.8 (a shared plan file, a plan from the AI coach)+// stored its exercises without the flag, and those were left with no Edit, no Delete and a+// broken thumbnail. A built-in catalogue entry is never custom, even if a custom one shadows its id.+export const isCustomEx = ex => !!ex && typeof ex === 'object' && !BUILTIN.has(ex) &&+ (ex.custom === true || customIds.has(ex.id))++// The stored list with the flag put back on every entry that lost it — the same array when+// nothing is missing, so a copy that is already right is never rewritten. The entry keeps its own+// `_ts`: the heal is no edit, and a newer stamp would let it win a merge over a real rename made+// on another device that has not healed yet.+export function healCustomEx(list) {+ if (!Array.isArray(list)) return list+ let changed = false+ const out = list.map(c => {+ if (!c || typeof c !== 'object' || c.custom === true) return c+ changed = true+ return { ...c, custom: true, ...(c.eq == null ? { eq: '' } : {}) }+ })+ return changed ? out : list}// Full searchable catalogue — customs first so your own exercises are easy to find.export const allExercises = st => [...(st.customEx || []), ...CATALOGUE]diff --git a/frontend/src/lib/media-prefetch.js b/frontend/src/lib/media-prefetch.jsindex d4fb88599..aaa5cfc42 100644--- a/frontend/src/lib/media-prefetch.js+++ b/frontend/src/lib/media-prefetch.js@@ -18,7 +18,7 @@// bounded by the plan (a few MB for a typical one) and each file goes once.//// Not in the phone app: it has no service worker, and its media comes from the CDN.-import { EXIDX, imgSrc, gifSrc } from './exercises.js'+import { EXIDX, imgSrc, gifSrc, isCustomEx } from './exercises.js'// The worker's media cache, public/sw.js MEDIA. Duplicated because the worker is not bundled;// sw-media.test.js pins the two together.@@ -42,7 +42,7 @@ export function planMediaUrls(S, base = globalThis.location?.href, index = EXIDXconst ex = index[id]// A custom exercise's photo or video is not a file of the shipped dataset: it lives in the// local media store and has its own prefetch (lib/media-sync.js). An unknown id has nothing.- if (!ex || ex.custom) continue+ if (!ex || isCustomEx(ex)) continuefor (const src of [ex.gif && gifSrc(ex), ex.img && imgSrc(ex)]) {if (!src) continueconst u = new URL(src, base)diff --git a/frontend/src/sheets.custom-edit.test.jsx b/frontend/src/sheets.custom-edit.test.jsxnew file mode 100644index 000000000..5e9d969f5--- /dev/null+++ b/frontend/src/sheets.custom-edit.test.jsx@@ -0,0 +1,136 @@+// @vitest-environment happy-dom+// #378 / #358: a custom exercise stored without `custom: true` — what a plan import (a shared+// plan file, a plan from the AI coach) wrote before 1.3.8 — showed no Edit and no Delete, in the+// exercise sheet or in the routine's exercise settings, and its thumbnail went through the+// built-in renderer. Every one of those now asks where the exercise lives, not for the flag.+import React, { act } from 'react'+import { afterEach, beforeEach, describe, expect, it } from 'vitest'+import { createRoot } from 'react-dom/client'++import { registerCustom } from './lib/exercises.js'+import { DEF, useStore } from './store/useStore.js'+import { useUI } from './store/useUI.js'+import { _setLangState } from './lib/i18n-core.js'+import { bindUI } from './components/ui.jsx'+import { Thumb } from './components/Media.jsx'+import { customExSheet, exerciseDetailSheet, exConfigSheet } from './sheets.jsx'++bindUI(useUI)++const mounted = []+const S = () => useStore.getState().S++function render(el) {+ const host = document.createElement('div')+ document.body.appendChild(host)+ const root = createRoot(host)+ mounted.push(root)+ act(() => root.render(el))+ return host+}+const renderTop = () => {+ const sheet = useUI.getState().sheets.at(-1)+ return render(sheet.render(() => useUI.getState().closeSheet(sheet.id)))+}+const buttons = host => [...host.querySelectorAll('button')].map(b => b.textContent.trim())+const click = (host, sel, text) => {+ const el = [...host.querySelectorAll(sel)].find(e => e.textContent.trim() === text)+ if (!el) throw new Error(`nothing with text "${text}"`)+ act(() => el.click())+}++// Exactly what a pre-1.3.8 plan import stored: no flag, no equipment.+const legacy = () => ({ id: 'cx1', n: 'My row', bp: 'back' })+function seed(ex, extra = {}) {+ useStore.setState(s => ({ S: { ...s.S, customEx: [ex], ...extra } }))+ registerCustom([ex])+}++beforeEach(() => {+ globalThis.IS_REACT_ACT_ENVIRONMENT = true+ useUI.setState({ sheets: [], toastMsg: '' })+ useStore.setState({ S: structuredClone(DEF), user: null, config: null })+ registerCustom([])+ _setLangState('en', null, null, null)+ document.body.innerHTML = ''+})+afterEach(() => {+ act(() => { mounted.splice(0).forEach(root => root.unmount()) })+ registerCustom([])+})++describe('a custom exercise stored without the flag', () => {+ it('its sheet offers Edit and Delete', () => {+ const ex = legacy()+ seed(ex)+ exerciseDetailSheet(ex)+ const host = renderTop()+ expect(buttons(host)).toEqual(expect.arrayContaining(['Edit', 'Delete']))+ })++ it('Edit opens the form filled in with it', () => {+ const ex = legacy()+ seed(ex)+ exerciseDetailSheet(ex)+ click(renderTop(), 'button', 'Edit')+ const form = renderTop()+ expect(form.textContent).toContain('Edit custom exercise')+ expect(form.querySelector('input.input').value).toBe('My row')+ expect(form.querySelector('.chip.on').textContent).toBe('back')+ })++ it('Delete takes it out of the routines and keeps the name in history', () => {+ const ex = legacy()+ seed(ex, {+ routines: [{ id: 'r1', name: 'A', ex: [{ id: 'cx1', sets: 3, reps: 8, w: 40 }, { id: '0027', sets: 3, reps: 8, w: 40 }] }],+ workouts: [{ d: '2026-09-01', entries: [{ id: 'cx1', sets: [{ r: 8, w: 40, done: true }] }] }],+ })+ exerciseDetailSheet(ex)+ click(renderTop(), 'button', 'Delete')+ click(renderTop(), 'button', 'Delete') // the confirmation+ expect(S().customEx).toEqual([])+ expect(S().routines[0].ex.map(e => e.id)).toEqual(['0027'])+ expect(S().workouts[0].entries[0].n).toBe('My row')+ })++ it('the routine exercise settings offer "Edit or delete this exercise"', () => {+ const ex = legacy()+ seed(ex)+ exConfigSheet(ex, { id: 'cx1', sets: 3, reps: 8, w: 40 }, () => {})+ expect(buttons(renderTop())).toContain('Edit or delete this exercise')+ })++ it('its thumbnail is the custom one, never a dataset image', () => {+ const ex = { ...legacy(), img: 'stray.jpg' }+ seed(ex)+ const host = render(<Thumb ex={ex} />)+ expect(host.querySelector('img')).toBeNull()+ expect(host.querySelector('.thumb-x')).toBeTruthy()+ })++ it('equipment from an import that the list lacks counts as picked, so Save works', () => {+ const ex = { ...legacy(), eq: 'custom', custom: true }+ seed(ex)+ customExSheet(ex)+ const form = renderTop()+ expect([...form.querySelectorAll('.chip.on')].map(c => c.textContent)).toContain('custom')+ act(() => {+ const el = form.querySelector('input.input')+ Object.getOwnPropertyDescriptor(el.constructor.prototype, 'value').set.call(el, 'My cable row')+ el.dispatchEvent(new Event('input', { bubbles: true }))+ })+ click(form, 'button', 'Save')+ expect(S().customEx[0]).toMatchObject({ id: 'cx1', n: 'My cable row', eq: 'custom' })+ })+})++describe('the store heals it', () => {+ it('a copy that enters the store gets the flag back, without a new stamp on the entry', () => {+ useStore.getState().replaceState({ ...structuredClone(DEF), customEx: [{ ...legacy(), _ts: 7 }] })+ expect(S().customEx[0]).toMatchObject({ id: 'cx1', custom: true, eq: '', _ts: 7 })+ const healed = S().customEx+ useStore.getState().update(s => { s.restDefault = 90 })+ expect(S().customEx[0]._ts).toBe(7) // healing twice changes nothing+ expect(S().customEx[0]).toEqual(healed[0])+ })+})diff --git a/frontend/src/sheets.jsx b/frontend/src/sheets.jsxindex a6d1ddf34..2cbd9229b 100644--- a/frontend/src/sheets.jsx+++ b/frontend/src/sheets.jsx@@ -1,7 +1,7 @@import { useEffect, useMemo, useRef, useState } from 'react'import { useStore } from './store/useStore.js'import { useUI } from './store/useUI.js'-import { EXDB, EXIDX, BODYPARTS, isCardio, isBodyweightEq, allExercises, equipmentOf, smOf, searchExercises, exOr, isAssisted, betterWeight, beatsWeight } from './lib/exercises.js'+import { EXDB, EXIDX, BODYPARTS, isCardio, isBodyweightEq, allExercises, equipmentOf, smOf, searchExercises, exOr, isAssisted, betterWeight, beatsWeight, isCustomEx } from './lib/exercises.js'import { activeProfile, exAvailable, ALL_EQUIPMENT, newProfile } from './lib/equipment.js'import { fmtDate, fmtDateRange, fmtNum, fmtPlate, exerciseNameText, fmtVol, fmtDur, durPart, todayISO, isoOf, uid, exCount, routineCount, setsWorkCount, DAYN, DAYS, weekOrder, weekStartOf, weekDayOffset, MONTHS_LONG, ACCENTS } from './lib/format.js'import { lastEntryFor, bestWeightFor, bestWeightForEntry, buildSets, effectiveRoutineIds, workoutDay, workoutVolume, setsDone, setsDoneActive, setUnitsTotal, lastBW, supersetUnits, sessionSections, unitOf, setLabel, defaultConfig, cleanupSg, modeOf, effortOf, EFFORT, capEffort, stepEffort, isBw, isPerSide, sideReps, workSetsDone, applyIntensifierPlan, MAX_PLANNED_WARMUPS, NOTE_MAX } from './lib/history.js'@@ -825,7 +825,7 @@ function ExerciseDetail({ ex, close }) {{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" style={{ whiteSpace: 'nowrap' }}>{fmtNum(best)} {st.unit}</b>{last ? ` · ${t('last')} ${fmtDate(last.d)}: ${last.sets.map(s => setLabel(ex.id, s, last.target, speedUnitOf(st))).join(', ')}` : ''}</div>}<Button variant="primary" icon="plus" style={{ margin: '10px 0 4px' }} onClick={() => addToRoutineSheet(ex)}>{t('Add to my plan')}</Button>{last && <Button icon="history" style={{ marginTop: 4 }} onClick={() => exerciseHistorySheet(ex.id)}>{t('History')}</Button>}- {ex.custom && <div className="row" style={{ gap: 8, marginTop: 8 }}>+ {isCustomEx(ex) && <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>}@@ -936,6 +936,7 @@ function CustomExForm({ existing, prefill, onDone, close }) {const [n, setN] = useState(existing ? existing.n : (prefill || ''))const [bp, setBp] = useState(existing ? existing.bp : '')const [eq, setEq] = useState(existing ? (existing.eq || '') : '')+ const storedEq = existing && typeof existing.eq === 'string' && existing.eq && !ALL_EQUIPMENT.includes(existing.eq) ? existing.eq : nullconst [desc, setDesc] = useState(existing ? (existing.desc || '') : '')const [media, setMedia] = useState(() => mediaOf(existing))// Whether this form changed the media at all. An edit that did not touch it writes back what the@@ -1023,6 +1024,9 @@ function CustomExForm({ existing, prefill, onDone, close }) {</div><div className="chips" style={{ margin: '12px 0' }}>{ALL_EQUIPMENT.map(k => (<button key={k} className={'chip' + (eq === k ? ' on' : '')} onClick={() => setEq(k)}>{t(k)}</button>))}+ {/* An imported exercise can carry equipment the list does not have (`custom` from a CSV or+ Hevy import). It stays a chip of its own, picked, so Save does not stop on "Pick equipment". */}+ {storedEq && <button key={storedEq} className={'chip' + (eq === storedEq ? ' on' : '')} onClick={() => setEq(storedEq)}>{t(storedEq)}</button>}</div>{bp && <>{bp !== 'cardio' && <MultiSelectRow title={t('Primary muscle groups')} sheetTitle={t('Primary muscle groups')}@@ -1614,7 +1618,7 @@ function ExConfig({ ex, existing, onSave, onDelete, onReplace, close, routine, iReplace (#110) seeds this sheet with the slot it replaces, and saving puts the exerciseinto that slot. */}<Button variant="primary" disabled={progressionStepInvalid} onClick={save}>{saveLabel || (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></>}+ {isCustomEx(ex) && <><div style={{ height: 8 }} /><Button icon="pencil" onClick={() => { close(); customExSheet(ex) }}>{t('Edit or delete this exercise')}</Button></>}{/* The routine editor's counterpart to a workout's Swap (#110): another exercise in thisslot, with the slot's sets, reps, weight, rule and note kept (lib/routines.js). What waschanged on this sheet and not saved is left behind, as closing it would. */}@@ -2658,7 +2662,7 @@ function doFinishWorkout() {const w = buildCompletedWorkout(A, {end: past ? backfillEnd(A) : Date.now(),prs,- snapshotFor: e => EXIDX[e.id]?.custom ? exerciseMuscleSnapshot(EXIDX[e.id]) : null,+ snapshotFor: e => isCustomEx(EXIDX[e.id]) ? exerciseMuscleSnapshot(EXIDX[e.id]) : null,})w.vol = workoutVolume(w)let shown = wdiff --git a/frontend/src/store/useStore.js b/frontend/src/store/useStore.jsindex ba46ca8f2..ad87486e6 100644--- a/frontend/src/store/useStore.js+++ b/frontend/src/store/useStore.js@@ -2,7 +2,7 @@ import { create } from 'zustand'import { api, setRemoteAuth } from '../lib/api.js'import { localTZ } from '../lib/format.js'import { t } from '../lib/i18n.js'-import { registerCustom } from '../lib/exercises.js'+import { registerCustom, healCustomEx } from '../lib/exercises.js'import { DEMO, DEMO_SEEDED } from '../lib/demo.js'import { rememberDefaultLang } from '../lib/default-lang.js'import { guestAllowed } from '../lib/guest.js'@@ -398,6 +398,10 @@ export const useStore = create((set, get) => {const persist = (S, push = true, stamp = true) => {const { base, owed } = metaOf() // the copy being replaced; the new one stands where it stoodif (stamp) S._ts = Math.max(Date.now(), (base?.ts || 0) + 1)+ // Every copy that enters the store — an edit, a pull, an adoption, a restored backup — has its+ // custom exercises marked as such (#378): one stored without the flag by an older plan import+ // goes out with it on the next push, without a stamp of its own (healCustomEx).+ S.customEx = healCustomEx(S.customEx)registerCustom(S.customEx)// A refused write used to take the change with it — Finish looked like it simply did// nothing. The copy is kept in memory either way and marked as owed to the server, so a@@ -913,6 +917,7 @@ export const useStore = create((set, get) => {}const S0 = loadState()+ S0.customEx = healCustomEx(S0.customEx)registerCustom(S0.customEx)// Which photos and videos are still waiting for the server, known before the first sign-out// check has to ask (lib/media-owed.js). A copy without any leaves the media store unopened.