Skip to content

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.

Routine editor: Replace exercise swaps what is in a slot and keeps its sets, reps, weight, rule and note (#110)

Duarte Santose9208d139ea1
diff --git a/frontend/src/lib/pt-br-locale.test.js b/frontend/src/lib/pt-br-locale.test.js
index 680046ae9..b89a4f3a3 100644
--- a/frontend/src/lib/pt-br-locale.test.js
+++ b/frontend/src/lib/pt-br-locale.test.js
@@ -27,11 +27,11 @@ describe('Brazilian Portuguese locale', () => {
.sort(byCodeUnit)
const fingerprint = createHash('sha256').update(JSON.stringify(inherited)).digest('hex')
- expect(Object.keys(PT_BR_OVERRIDES)).toHaveLength(679)
- expect(inherited).toHaveLength(674)
+ expect(Object.keys(PT_BR_OVERRIDES)).toHaveLength(680)
+ expect(inherited).toHaveLength(675)
// If this fails, review the changed keys and wording before accepting a new hash. From
// frontend/: node scripts/pt-br-inheritance-fingerprint.mjs --list
- expect(fingerprint, 'pt-PT inheritance changed; review the inherited pt-BR wording').toBe('f81cca4b7e73e229526217b8a3825069ee65fb6a5586c143b324038f99499f75')
+ expect(fingerprint, 'pt-PT inheritance changed; review the inherited pt-BR wording').toBe('a173a05c6ada8fed6f9ee9f4e4f1745bc8f96b9b68c506bddaa4a499b6ff3643')
})
test('does not leak European Portuguese UI terms', () => {
diff --git a/frontend/src/lib/routines.js b/frontend/src/lib/routines.js
index 13678f012..d40f8f580 100644
--- a/frontend/src/lib/routines.js
+++ b/frontend/src/lib/routines.js
@@ -1,4 +1,6 @@
import { uid } from './format.js'
+import { defaultConfig, isBw, modeOf } from './history.js'
+import { isBodyweightEq, isCardio } from './exercises.js'
/**
* Create a deep copy of a routine with a new id and a "(Copy)" suffix.
@@ -13,3 +15,37 @@ export function copyRoutine(routine, suffix = 'Copy') {
copy.name = m ? m[1] + ' (' + suffix + ' ' + ((Number(m[2]) || 1) + 1) + ')' : routine.name + ' (' + suffix + ')'
return copy
}
+
+/**
+ * A routine slot with another exercise in it (#110): the machine you planned around is gone, or
+ * a variation takes over the lift for a block. The slot keeps its place and what was set up for
+ * it — sets, reps, weight, rest, warm-ups, the progression rule, the note, its superset — and only
+ * the exercise changes. The old way (remove, add, configure again) lost all of that.
+ *
+ * Two things cannot come along. A cardio slot is minutes at a speed and a lifting slot is sets of
+ * reps at a load, so between the two only the note, the rest and the superset carry over and the
+ * rest starts from the new exercise's defaults. And a load means something else once the new
+ * exercise is bodyweight where the old one was not, or the other way round: 60 kg on a bench is
+ * not 60 kg added to a push-up. There the weight goes back to 0. The bodyweight flag is stored
+ * only where it overrides an exercise's equipment, so it is always dropped and the new exercise
+ * follows its own.
+ *
+ * What is not carried is history. Progress belongs to a routine and an exercise together (#216),
+ * so the new exercise starts on its own line — its own sessions in this routine, and until there
+ * are any, the slot's numbers — and the old exercise keeps its sessions, ready if it comes back.
+ */
+export function replaceSlotExercise(slot, id) {
+ const old = slot || {}
+ if ((modeOf(old) === 'cardio') !== isCardio(id)) {
+ const kept = ['sg', 'note', 'restSec'].filter(key => old[key] != null)
+ return { id, ...defaultConfig(id), ...Object.fromEntries(kept.map(key => [key, old[key]])) }
+ }
+ const { id: _replaced, bodyweight: _flag, ...carried } = old
+ const out = { id, ...carried }
+ if (!isCardio(id) && isBw(old) !== isBodyweightEq(id)) {
+ out.weight = 0
+ // A rep ceiling belongs to bodyweight work: it adds sets where there is no load to add.
+ delete out.repsMax
+ }
+ return out
+}
diff --git a/frontend/src/lib/routines.replace.test.js b/frontend/src/lib/routines.replace.test.js
new file mode 100644
index 000000000..7568d5581
--- /dev/null
+++ b/frontend/src/lib/routines.replace.test.js
@@ -0,0 +1,105 @@
+// Replace an exercise in a routine (#110): the slot keeps what was set up for it, only the
+// exercise changes — and the new exercise does not inherit the old one's progress.
+import { describe, it, expect } from 'vitest'
+import { replaceSlotExercise } from './routines.js'
+import { buildCombinedEntries } from './session-merge.js'
+import { buildCompletedWorkout } from './finish-workout.js'
+import { lastEntryFor } from './history.js'
+import { isWarmupRow } from './workout-model.js'
+
+const BENCH = '0025' // barbell bench press
+const DB_BENCH = '0289' // dumbbell bench press
+const PUSH_UP = '0662' // push-up, body weight
+const PULL_UP = '0652' // pull-up, body weight
+const BIKE = '2138' // stationary bike, cardio
+
+describe('replaceSlotExercise', () => {
+ it('keeps the slot\'s sets, reps, weight, rule, rest, warm-ups, note and superset', () => {
+ const slot = {
+ id: BENCH, sg: 'sgA', sets: 4, mode: 'reps', reps: 8, repsMin: 6, weight: 60, prog: 'double', inc: 1.25,
+ deloadFactor: 0.85, note: 'pause on the chest', warmupSets: 2, restSec: 150, side: true,
+ intensifier: { type: 'dropset', count: 1, pct: 20 },
+ }
+ const next = replaceSlotExercise(slot, DB_BENCH)
+ expect(next).toEqual({ ...slot, id: DB_BENCH })
+ // A new object — the routine's own slot is not edited behind the store's back.
+ expect(slot.id).toBe(BENCH)
+ })
+
+ it('keeps a timed slot timed', () => {
+ const next = replaceSlotExercise({ id: BENCH, sets: 3, mode: 'time', sec: 40, weight: 20 }, DB_BENCH)
+ expect(next).toEqual({ id: DB_BENCH, sets: 3, mode: 'time', sec: 40, weight: 20 })
+ })
+
+ it('drops a load that means something else once the exercise is bodyweight, or stops being', () => {
+ // 60 kg on a bar is not 60 kg added to a push-up …
+ expect(replaceSlotExercise({ id: BENCH, sets: 3, mode: 'reps', reps: 10, weight: 60 }, PUSH_UP))
+ .toEqual({ id: PUSH_UP, sets: 3, mode: 'reps', reps: 10, weight: 0 })
+ // … and a push-up's rep ceiling and belt are not a bench press's numbers.
+ expect(replaceSlotExercise({ id: PUSH_UP, sets: 3, mode: 'reps', reps: 12, weight: 10, repsMax: 20, bodyweight: true }, BENCH))
+ .toEqual({ id: BENCH, sets: 3, mode: 'reps', reps: 12, weight: 0 })
+ })
+
+ it('keeps an added weight from one bodyweight exercise to another, and lets the new one follow its own equipment', () => {
+ expect(replaceSlotExercise({ id: PUSH_UP, sets: 3, mode: 'reps', reps: 8, weight: 10, repsMax: 15, bodyweight: true }, PULL_UP))
+ .toEqual({ id: PULL_UP, sets: 3, mode: 'reps', reps: 8, weight: 10, repsMax: 15 })
+ // A push-up the user had turned into a loaded exercise: that choice was about the push-up.
+ expect(replaceSlotExercise({ id: PUSH_UP, sets: 3, mode: 'reps', reps: 8, weight: 20, bodyweight: false }, PULL_UP))
+ .toEqual({ id: PULL_UP, sets: 3, mode: 'reps', reps: 8, weight: 0 })
+ })
+
+ it('starts from the new exercise\'s defaults between cardio and lifting, keeping the note, rest and superset', () => {
+ expect(replaceSlotExercise({ id: BENCH, sg: 'sgA', sets: 4, mode: 'reps', reps: 8, weight: 60, note: 'n', restSec: 90 }, BIKE))
+ .toEqual({ id: BIKE, sets: 1, min: 20, speed: 8, sg: 'sgA', note: 'n', restSec: 90 })
+ expect(replaceSlotExercise({ id: BIKE, sets: 2, min: 30, speed: 12, note: 'easy' }, BENCH))
+ .toEqual({ id: BENCH, sets: 3, reps: 10, weight: 0, mode: 'reps', note: 'easy' })
+ })
+
+ it('keeps a cardio slot\'s minutes and speed on another cardio exercise', () => {
+ expect(replaceSlotExercise({ id: BIKE, sets: 2, min: 30, speed: 12 }, '3666'))
+ .toEqual({ id: '3666', sets: 2, min: 30, speed: 12 })
+ })
+})
+
+// Per-slot history is the routine and the exercise together (#216), so a replaced slot is a new
+// line of progress: the new exercise opens at the slot's numbers, and the old exercise's
+// sessions stay its own. These start and finish sessions the way the app does.
+describe('history after a replace', () => {
+ const work = e => e.sets.filter(s => !isWarmupRow(s))
+ let day = 1
+ function train(st, rid) {
+ const entries = buildCombinedEntries(st, [rid]).entries
+ .map(e => ({ ...e, sets: e.sets.map(s => ({ ...s, done: true })) }))
+ const active = { id: 'w' + day, d: `2026-08-${String(day).padStart(2, '0')}`, start: day * 1000, routineIds: [rid], name: 'x', entries }
+ day++
+ st.workouts.push(buildCompletedWorkout(active, { end: active.start + 1 }))
+ }
+ const state = () => ({
+ unit: 'kg', exWeights: {}, workouts: [], week: {}, dayPlan: {},
+ routines: [{ id: 'A', name: 'Push', ex: [{ id: BENCH, sets: 2, mode: 'reps', reps: 10, weight: 60 }] }],
+ })
+
+ it('starts the new exercise fresh at the slot\'s numbers, and leaves the old one\'s progress where it was', () => {
+ const st = state()
+ train(st, 'A')
+ train(st, 'A')
+ // The bench has moved on from the plan's 60 in this routine.
+ const [bench] = buildCombinedEntries(st, ['A']).entries
+ expect(work(bench).map(s => s.w)).toEqual([65, 65])
+
+ st.routines[0].ex[0] = replaceSlotExercise(st.routines[0].ex[0], DB_BENCH)
+ const [db] = buildCombinedEntries(st, ['A']).entries
+ expect(db.id).toBe(DB_BENCH)
+ // Not the bench's 65: the dumbbells have never been logged, so they open at the slot's own
+ // sets × reps × weight, and say why.
+ expect(work(db).map(s => [s.w, s.r])).toEqual([[60, 10], [60, 10]])
+ expect(db.plan.why[0]).toBe('Nothing logged yet — this session sets the baseline.')
+ expect(lastEntryFor(st, DB_BENCH, 'A')).toBeNull()
+
+ // The bench's sessions in this routine are still there if it comes back.
+ expect(lastEntryFor(st, BENCH, 'A')?.sets.map(s => s.w)).toEqual([62.5, 62.5])
+ st.routines[0].ex[0] = replaceSlotExercise(st.routines[0].ex[0], BENCH)
+ const [back] = buildCombinedEntries(st, ['A']).entries
+ expect(work(back).map(s => s.w)).toEqual([65, 65])
+ })
+})
diff --git a/frontend/src/locales/de.js b/frontend/src/locales/de.js
index d736fc60a..63ac3fd89 100644
--- a/frontend/src/locales/de.js
+++ b/frontend/src/locales/de.js
@@ -449,6 +449,8 @@ export default {
'Delete exercise': 'Übung löschen',
'Edit or delete this exercise': 'Übung bearbeiten oder löschen',
'Remove from routine': 'Aus Routine entfernen',
+ 'Replace exercise': 'Übung ersetzen',
+ 'Replaced with “{0}”': 'Ersetzt durch „{0}“',
'Minimize': 'Verkleinern',
'Expand': 'Vergrößern',
'Exercise animations': 'Übungs-Animationen',
diff --git a/frontend/src/locales/es.js b/frontend/src/locales/es.js
index 5764277a7..85cba1a8c 100644
--- a/frontend/src/locales/es.js
+++ b/frontend/src/locales/es.js
@@ -430,6 +430,8 @@ export default {
'Delete exercise': 'Eliminar ejercicio',
'Edit or delete this exercise': 'Editar o eliminar este ejercicio',
'Remove from routine': 'Quitar de la rutina',
+ 'Replace exercise': 'Reemplazar ejercicio',
+ 'Replaced with “{0}”': 'Reemplazado por «{0}»',
'Minimize': 'Minimizar',
'Expand': 'Ampliar',
'Exercise animations': 'Animaciones de los ejercicios',
diff --git a/frontend/src/locales/fr.js b/frontend/src/locales/fr.js
index 277c4dbc0..52b9df7ab 100644
--- a/frontend/src/locales/fr.js
+++ b/frontend/src/locales/fr.js
@@ -430,6 +430,8 @@ export default {
'Delete exercise': 'Supprimer l’exercice',
'Edit or delete this exercise': 'Modifier ou supprimer cet exercice',
'Remove from routine': 'Retirer de la routine',
+ 'Replace exercise': 'Remplacer l’exercice',
+ 'Replaced with “{0}”': 'Remplacé par « {0} »',
'Minimize': 'Réduire',
'Expand': 'Agrandir',
'Exercise animations': 'Animations des exercices',
diff --git a/frontend/src/locales/hi.js b/frontend/src/locales/hi.js
index 303289210..54ba8c528 100644
--- a/frontend/src/locales/hi.js
+++ b/frontend/src/locales/hi.js
@@ -430,6 +430,8 @@ export default {
'Delete exercise': 'एक्सरसाइज़ हटाएं',
'Edit or delete this exercise': 'इस एक्सरसाइज़ को संपादित या हटाएं',
'Remove from routine': 'रूटीन से हटाएं',
+ 'Replace exercise': 'व्यायाम बदलें',
+ 'Replaced with “{0}”': '"{0}" से बदला गया',
'Minimize': 'छोटा करें',
'Expand': 'बड़ा करें',
'Exercise animations': 'व्यायाम एनिमेशन',
diff --git a/frontend/src/locales/hu.js b/frontend/src/locales/hu.js
index 28c1a24a8..629b9079c 100644
--- a/frontend/src/locales/hu.js
+++ b/frontend/src/locales/hu.js
@@ -435,6 +435,8 @@ export default {
'Delete exercise': 'Gyakorlat törlése',
'Edit or delete this exercise': 'Gyakorlat szerkesztése vagy törlése',
'Remove from routine': 'Eltávolítás a rutinból',
+ 'Replace exercise': 'Gyakorlat lecserélése',
+ 'Replaced with “{0}”': 'Lecserélve erre: „{0}”',
'Minimize': 'Kicsinyítés',
'Expand': 'Kibontás',
'Exercise animations': 'Gyakorlat-animációk',
diff --git a/frontend/src/locales/it.js b/frontend/src/locales/it.js
index 65fbe048b..e7a515a1c 100644
--- a/frontend/src/locales/it.js
+++ b/frontend/src/locales/it.js
@@ -430,6 +430,8 @@ export default {
'Delete exercise': 'Elimina esercizio',
'Edit or delete this exercise': 'Modifica o elimina questo esercizio',
'Remove from routine': 'Rimuovi dalla routine',
+ 'Replace exercise': 'Sostituisci esercizio',
+ 'Replaced with “{0}”': 'Sostituito con «{0}»',
'Minimize': 'Riduci',
'Expand': 'Ingrandisci',
'Exercise animations': 'Animazioni degli esercizi',
diff --git a/frontend/src/locales/ko.js b/frontend/src/locales/ko.js
index 9018a95d3..faaae4872 100644
--- a/frontend/src/locales/ko.js
+++ b/frontend/src/locales/ko.js
@@ -430,6 +430,8 @@ export default {
'Delete exercise': '운동 삭제',
'Edit or delete this exercise': '이 운동 편집 또는 삭제',
'Remove from routine': '루틴에서 제거',
+ 'Replace exercise': '운동 교체',
+ 'Replaced with “{0}”': '"{0}"(으)로 교체됨',
'Minimize': '축소',
'Expand': '확대',
'Exercise animations': '운동 애니메이션',
diff --git a/frontend/src/locales/pl.js b/frontend/src/locales/pl.js
index 668ec24b2..a0768410b 100644
--- a/frontend/src/locales/pl.js
+++ b/frontend/src/locales/pl.js
@@ -430,6 +430,8 @@ export default {
'Delete exercise': 'Usuń ćwiczenie',
'Edit or delete this exercise': 'Edytuj lub usuń to ćwiczenie',
'Remove from routine': 'Usuń z planu',
+ 'Replace exercise': 'Zastąp ćwiczenie',
+ 'Replaced with “{0}”': 'Zastąpiono przez „{0}”',
'Minimize': 'Zmniejsz',
'Expand': 'Powiększ',
'Exercise animations': 'Animacje ćwiczeń',
diff --git a/frontend/src/locales/pt-BR.js b/frontend/src/locales/pt-BR.js
index 54b70d992..b1d644157 100644
--- a/frontend/src/locales/pt-BR.js
+++ b/frontend/src/locales/pt-BR.js
@@ -709,6 +709,7 @@ export const PT_BR_OVERRIDES = {
'First time in this routine — starting from its own target.': 'Primeira vez nesta rotina — você começa pela meta dela.',
'No weight logged last time — enter what you lift and progression takes it from there.': 'Nenhum peso registrado na última vez — informe quanto você levanta e a progressão segue a partir daí.',
'reps from your last session': 'reps da sua última sessão',
+ 'Replaced with “{0}”': 'Substituído por “{0}”',
}
export default { ...pt, ...PT_BR_OVERRIDES }
diff --git a/frontend/src/locales/pt.js b/frontend/src/locales/pt.js
index fb5d3ef38..71533b633 100644
--- a/frontend/src/locales/pt.js
+++ b/frontend/src/locales/pt.js
@@ -430,6 +430,8 @@ export default {
'Delete exercise': 'Eliminar exercício',
'Edit or delete this exercise': 'Editar ou eliminar este exercício',
'Remove from routine': 'Remover da rotina',
+ 'Replace exercise': 'Substituir exercício',
+ 'Replaced with “{0}”': 'Substituído por «{0}»',
'Minimize': 'Minimizar',
'Expand': 'Ampliar',
'Exercise animations': 'Animações dos exercícios',
diff --git a/frontend/src/locales/ru.js b/frontend/src/locales/ru.js
index 9bfac9658..280caddeb 100644
--- a/frontend/src/locales/ru.js
+++ b/frontend/src/locales/ru.js
@@ -430,6 +430,8 @@ export default {
'Delete exercise': 'Удалить упражнение',
'Edit or delete this exercise': 'Изменить или удалить это упражнение',
'Remove from routine': 'Убрать из программы',
+ 'Replace exercise': 'Заменить упражнение',
+ 'Replaced with “{0}”': 'Заменено на «{0}»',
'Minimize': 'Свернуть',
'Expand': 'Развернуть',
'Exercise animations': 'Анимации упражнений',
diff --git a/frontend/src/locales/th.js b/frontend/src/locales/th.js
index 952e70287..cd6493954 100644
--- a/frontend/src/locales/th.js
+++ b/frontend/src/locales/th.js
@@ -435,6 +435,8 @@ export default {
'Delete exercise': 'ลบท่าออกกำลังกาย',
'Edit or delete this exercise': 'แก้ไขหรือลบท่านี้',
'Remove from routine': 'ลบออกจากรูทีน',
+ 'Replace exercise': 'แทนที่ท่าออกกำลังกาย',
+ 'Replaced with “{0}”': 'แทนที่ด้วย “{0}” แล้ว',
'Minimize': 'ย่อ',
'Expand': 'ขยาย',
'Exercise animations': 'ภาพเคลื่อนไหวท่าออกกำลังกาย',
diff --git a/frontend/src/locales/tr.js b/frontend/src/locales/tr.js
index 6f0a9eca2..9a19cb8d7 100644
--- a/frontend/src/locales/tr.js
+++ b/frontend/src/locales/tr.js
@@ -430,6 +430,8 @@ export default {
'Delete exercise': 'Egzersizi sil',
'Edit or delete this exercise': 'Bu egzersizi düzenle veya sil',
'Remove from routine': 'Rutinden çıkar',
+ 'Replace exercise': 'Egzersizi değiştir',
+ 'Replaced with “{0}”': '“{0}” ile değiştirildi',
'Minimize': 'Küçült',
'Expand': 'Büyüt',
'Exercise animations': 'Egzersiz animasyonları',
diff --git a/frontend/src/locales/zh.js b/frontend/src/locales/zh.js
index 5ad7f7998..f7793562f 100644
--- a/frontend/src/locales/zh.js
+++ b/frontend/src/locales/zh.js
@@ -430,6 +430,8 @@ export default {
'Delete exercise': '删除动作',
'Edit or delete this exercise': '编辑或删除此动作',
'Remove from routine': '从计划中移除',
+ 'Replace exercise': '替换动作',
+ 'Replaced with “{0}”': '已替换为“{0}”',
'Minimize': '缩小',
'Expand': '放大',
'Exercise animations': '动作动画',
diff --git a/frontend/src/sheets.jsx b/frontend/src/sheets.jsx
index 90871a73a..d2f0333fe 100644
--- a/frontend/src/sheets.jsx
+++ b/frontend/src/sheets.jsx
@@ -912,7 +912,7 @@ function usageMap(st) {
st.workouts.forEach(w => w.entries.forEach(e => { u[e.id] = (u[e.id] || 0) + 1 }))
return u
}
-function ExercisePicker({ onPick, close }) {
+function ExercisePicker({ onPick, title, close }) {
const st = useStore(s => s.S)
const usage = usageMap(st)
const [q, setQ] = useState('')
@@ -941,14 +941,14 @@ function ExercisePicker({ onPick, close }) {
useRevealActiveChip(bpStrip, bp)
useRevealActiveChip(eqStrip, eqOn)
if (byMuscle) return <>
- <div className="row between" style={{ marginBottom: 10 }}><h3>{t('Add exercise')}</h3>
+ <div className="row between" style={{ marginBottom: 10 }}><h3>{title || t('Add exercise')}</h3>
<Button size="sm" variant="ghost" onClick={() => setByMuscle(false)}>{t('All')}</Button>
</div>
<MuscleExplorer onPick={onPick} />
</>
return <>
- <div className="row between" style={{ marginBottom: 10 }}><h3>{t('Add exercise')}</h3>
+ <div className="row between" style={{ marginBottom: 10 }}><h3>{title || t('Add exercise')}</h3>
<Button size="sm" variant="tinted" icon="target" onClick={() => setByMuscle(true)}>{t('By muscle')}</Button>
</div>
{/* .picker-search is what index.css keys the keyboard-aware sheet layout on: the sheet
@@ -999,7 +999,8 @@ function ExercisePicker({ onPick, close }) {
{f.length > shown && <><div style={{ height: 8 }} /><Button onClick={() => setShown(s => s + 50)}>{t('Show more')}</Button></>}
</>
}
-export const exercisePicker = onPick => ui().openSheet(close => <ExercisePicker onPick={onPick} close={close} />)
+// `title` names what the pick is for when it is not an add — the routine editor's Replace (#110).
+export const exercisePicker = (onPick, { title } = {}) => ui().openSheet(close => <ExercisePicker onPick={onPick} title={title} close={close} />)
/** Start a safe swap for one exact active-workout occurrence. */
export function swapActiveWorkoutExercise(index) {
@@ -1175,7 +1176,7 @@ function ProgressionFields({ ex, mode, c, setC, routine, unit, perSide }) {
</>
}
-function ExConfig({ ex, existing, onSave, onDelete, close, routine, initial }) {
+function ExConfig({ ex, existing, onSave, onDelete, onReplace, close, routine, initial }) {
const st = useStore(s => s.S)
const cardio = isCardio(ex.id)
const seed = existing || initial || defaultConfig(ex.id)
@@ -1419,10 +1420,14 @@ function ExConfig({ ex, existing, onSave, onDelete, close, routine, initial }) {
value={c.note || ''} onChange={e => setC(x => ({ ...x, note: e.target.value }))} />
<Button variant="primary" disabled={progressionStepInvalid} 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></>}
+ {/* The routine editor's counterpart to a workout's Swap (#110): another exercise in this
+ slot, with the slot's sets, reps, weight, rule and note kept (lib/routines.js). What was
+ changed on this sheet and not saved is left behind, as closing it would. */}
+ {onReplace && <><div style={{ height: 8 }} /><Button icon="shuffle" onClick={() => { close(); onReplace() }}>{t('Replace 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, routine, initial) => ui().openSheet(close => <ExConfig ex={ex} existing={existing} initial={initial} onSave={onSave} onDelete={onDelete} routine={routine} close={close} />)
+export const exConfigSheet = (ex, existing, onSave, onDelete, routine, initial, onReplace) => ui().openSheet(close => <ExConfig ex={ex} existing={existing} initial={initial} onSave={onSave} onDelete={onDelete} onReplace={onReplace} routine={routine} close={close} />)
/* ============================ glyph picker ============================ */
// Grouped by what the glyph means for a training day, so picking one is a scan
diff --git a/frontend/src/sheets.replace.test.jsx b/frontend/src/sheets.replace.test.jsx
new file mode 100644
index 000000000..f0cb181ab
--- /dev/null
+++ b/frontend/src/sheets.replace.test.jsx
@@ -0,0 +1,57 @@
+// @vitest-environment happy-dom
+// #110: an exercise's settings sheet in the routine editor offers Replace, and the picker it opens
+// says what the pick is for.
+import React, { act } from 'react'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { createRoot } from 'react-dom/client'
+import { EXIDX } from './lib/exercises.js'
+import { useStore } from './store/useStore.js'
+import { useUI } from './store/useUI.js'
+import { exConfigSheet, exercisePicker } from './sheets.jsx'
+
+const mounted = []
+function renderTop() {
+ const sheet = useUI.getState().sheets.at(-1)
+ const host = document.createElement('div')
+ document.body.appendChild(host)
+ const root = createRoot(host)
+ mounted.push(root)
+ act(() => root.render(sheet.render(() => useUI.getState().closeSheet(sheet.id))))
+ return host
+}
+const button = (host, label) => [...host.querySelectorAll('button')].find(b => b.textContent.trim() === label)
+
+beforeEach(() => {
+ globalThis.IS_REACT_ACT_ENVIRONMENT = true
+ useUI.setState({ sheets: [] })
+ useStore.setState(s => ({ S: { ...s.S, unit: 'kg' } }))
+ document.body.innerHTML = ''
+})
+afterEach(() => {
+ act(() => { mounted.splice(0).forEach(root => root.unmount()) })
+})
+
+describe('Replace exercise', () => {
+ it('sits on the settings sheet of a routine exercise and closes it before handing over', () => {
+ const onReplace = vi.fn()
+ exConfigSheet(EXIDX['0025'], { sets: 3, mode: 'reps', reps: 10, weight: 60 }, vi.fn(), vi.fn(), null, null, onReplace)
+ const host = renderTop()
+ const replace = button(host, 'Replace exercise')
+ expect(replace).toBeTruthy()
+ act(() => replace.click())
+ expect(onReplace).toHaveBeenCalledOnce()
+ expect(useUI.getState().sheets).toHaveLength(0)
+ })
+
+ it('is not offered where there is no slot to replace', () => {
+ exConfigSheet(EXIDX['0025'], null, vi.fn(), null, null)
+ expect(button(renderTop(), 'Replace exercise')).toBeUndefined()
+ })
+
+ it('titles the picker for what the pick is for', () => {
+ exercisePicker(vi.fn(), { title: 'Replace exercise' })
+ expect(renderTop().querySelector('h3').textContent).toBe('Replace exercise')
+ exercisePicker(vi.fn())
+ expect(renderTop().querySelector('h3').textContent).toBe('Add exercise')
+ })
+})
diff --git a/frontend/src/views/RoutineEdit.jsx b/frontend/src/views/RoutineEdit.jsx
index b6b18d103..87e924950 100644
--- a/frontend/src/views/RoutineEdit.jsx
+++ b/frontend/src/views/RoutineEdit.jsx
@@ -4,7 +4,7 @@ import { useStore } from '../store/useStore.js'
import { useUI } from '../store/useUI.js'
import { exOr } from '../lib/exercises.js'
import { activeProfile, exAvailable } from '../lib/equipment.js'
-import { uid } from '../lib/format.js'
+import { uid, capWords } from '../lib/format.js'
import { t, exerciseNameFor } from '../lib/i18n.js'
import { supersetUnits, moveSupersetUnit, cleanupSg, exLine, defaultConfig } from '../lib/history.js'
import { Thumb } from '../components/Media.jsx'
@@ -13,7 +13,7 @@ import Icon from '../components/Icon.jsx'
import { glyphOf } from '../lib/glyphs.js'
import { Button, Row, SelectRow, Switch } from '../components/ui.jsx'
import SwipeToDelete from '../components/SwipeToDelete.jsx'
-import { copyRoutine } from '../lib/routines.js'
+import { copyRoutine, replaceSlotExercise } from '../lib/routines.js'
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'
@@ -330,6 +330,25 @@ export default function RoutineEdit() {
cleanupSg(ex)
})
}
+ // Replace (#110): the picker chooses what goes into slot `i`, and the slot keeps its sets, reps,
+ // weight and the rest (lib/routines.js replaceSlotExercise). "+" on a picker row replaces at
+ // once; tapping the row opens the new exercise's settings at those numbers first, the way the
+ // add flow does. One pick and the picker closes — it is a chooser here, not a stack you keep
+ // adding from. A slot that is no longer the exercise the sheet was opened on is left alone.
+ const replace = i => {
+ const openedOn = r.ex[i]?.id
+ const commit = (ex, fn) => {
+ picker.close()
+ let done = false
+ edit(x => { if (x[i] && x[i].id === openedOn) { x[i] = fn(x[i]); done = true } })
+ if (done) toast(t('Replaced with “{0}”', capWords(exerciseNameFor(ex))))
+ }
+ const picker = exercisePicker((ex, quick) => {
+ if (quick) { commit(ex, slot => replaceSlotExercise(slot, ex.id)); return }
+ const next = replaceSlotExercise(r.ex[i], ex.id)
+ exConfigSheet(ex, next, cfg => commit(ex, slot => ({ id: ex.id, sg: slot.sg, ...cfg })), null, r)
+ }, { title: t('Replace exercise') })
+ }
const toggleLink = i => edit(ex => {
if (i < 1) return
const cur = ex[i], prev = ex[i - 1]
@@ -397,7 +416,7 @@ export default function RoutineEdit() {
deleteLabel={t('Remove from routine')}
onDelete={() => edit(x => { x.splice(i, 1); cleanupSg(x) })}
onClick={() => {
- 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)
+ 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, null, () => replace(i))
}}>
<Thumb ex={ex} />
<div className="grow"><div className="tt capitalize">{exerciseNameFor(ex)}</div><div className="ss">{exLine(e, S.unit)}</div>
diff --git a/frontend/src/views/RoutineEdit.replace.test.jsx b/frontend/src/views/RoutineEdit.replace.test.jsx
new file mode 100644
index 000000000..77865680d
--- /dev/null
+++ b/frontend/src/views/RoutineEdit.replace.test.jsx
@@ -0,0 +1,99 @@
+// @vitest-environment happy-dom
+// Replace exercise in the routine editor (#110): the exercise's settings sheet offers Replace,
+// the picker chooses the new exercise, and the slot keeps its place and its numbers.
+import React, { act } from 'react'
+import { createRoot } from 'react-dom/client'
+import { MemoryRouter, Route, Routes } from 'react-router-dom'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+
+const sheets = vi.hoisted(() => ({
+ exConfigSheet: vi.fn(), exercisePicker: vi.fn(), glyphPicker: vi.fn(), confirmSheet: vi.fn(),
+}))
+vi.mock('../lib/api.js', () => ({ api: vi.fn(() => Promise.resolve({})) }))
+vi.mock('../sheets.jsx', () => sheets)
+vi.mock('../components/Media.jsx', () => ({ Thumb: () => null }))
+vi.mock('../components/BodyMap.jsx', () => ({ default: () => null }))
+
+import RoutineEdit from './RoutineEdit.jsx'
+import { DEF, useStore } from '../store/useStore.js'
+import { useUI } from '../store/useUI.js'
+import { EXIDX } from '../lib/exercises.js'
+
+globalThis.IS_REACT_ACT_ENVIRONMENT = true
+const clone = value => JSON.parse(JSON.stringify(value))
+const BENCH = '0025', DB_BENCH = '0289', ROW = '0027'
+const benchSlot = { id: BENCH, sg: 'g1', sets: 4, mode: 'reps', reps: 6, weight: 80, prog: 'double', repsMin: 4, note: 'touch and go', restSec: 180 }
+const rowSlot = { id: ROW, sg: 'g1', sets: 3, mode: 'reps', reps: 10, weight: 50 }
+let root, host, picker
+
+function mount() {
+ const S = clone(DEF)
+ S.routines = [{ id: 'r1', name: 'Push', emoji: 'dumbbell', ex: [clone(benchSlot), clone(rowSlot)] }]
+ useStore.setState({ S, user: null })
+ host = document.createElement('div')
+ document.body.appendChild(host)
+ root = createRoot(host)
+ act(() => root.render(<MemoryRouter initialEntries={['/plan/r/r1']}><Routes><Route path="/plan/r/:id" element={<RoutineEdit />} /></Routes></MemoryRouter>))
+}
+const slots = () => useStore.getState().S.routines[0].ex
+// Tap the first row, then Replace on its settings sheet: the picker it opens is returned.
+function openReplace() {
+ act(() => host.querySelector('[data-routine-row] .item').click())
+ const onReplace = sheets.exConfigSheet.mock.calls[0][6]
+ expect(onReplace).toBeTypeOf('function')
+ act(() => onReplace())
+ expect(sheets.exercisePicker).toHaveBeenCalledOnce()
+ const [onPick, opts] = sheets.exercisePicker.mock.calls[0]
+ expect(opts).toEqual({ title: 'Replace exercise' })
+ return onPick
+}
+
+beforeEach(() => {
+ localStorage.clear()
+ Object.values(sheets).forEach(mock => mock.mockReset())
+ picker = { close: vi.fn() }
+ sheets.exercisePicker.mockImplementation(() => picker)
+ useUI.setState({ toastMsg: '' })
+})
+afterEach(() => {
+ act(() => root.unmount())
+ host.remove()
+})
+
+describe('RoutineEdit — Replace exercise', () => {
+ it('"+" on a picker row swaps the exercise in place and keeps the slot\'s numbers', () => {
+ mount()
+ const onPick = openReplace()
+ act(() => onPick(EXIDX[DB_BENCH], true))
+ expect(slots()).toEqual([{ ...benchSlot, id: DB_BENCH }, rowSlot])
+ expect(picker.close).toHaveBeenCalledOnce()
+ expect(useUI.getState().toastMsg).toBe('Replaced with “Dumbbell Bench Press”')
+ })
+
+ it('a tapped picker row opens the new exercise\'s settings at the slot\'s numbers first', () => {
+ mount()
+ const onPick = openReplace()
+ act(() => onPick(EXIDX[DB_BENCH], false))
+ // No replace yet: the settings sheet for the new exercise is open, seeded with the slot.
+ expect(slots()[0].id).toBe(BENCH)
+ const [ex, seeded, onSave, onDelete] = sheets.exConfigSheet.mock.calls[1]
+ expect(ex.id).toBe(DB_BENCH)
+ expect(seeded).toEqual({ ...benchSlot, id: DB_BENCH })
+ expect(onDelete).toBeNull()
+ act(() => onSave({ sets: 3, mode: 'reps', reps: 8, weight: 30 }))
+ // Saved as the sheet left it, in the same place and the same superset.
+ expect(slots()[0]).toEqual({ id: DB_BENCH, sg: 'g1', sets: 3, mode: 'reps', reps: 8, weight: 30 })
+ expect(slots()[1]).toEqual(rowSlot)
+ expect(picker.close).toHaveBeenCalledOnce()
+ })
+
+ it('leaves a slot alone that changed under the picker', () => {
+ mount()
+ const onPick = openReplace()
+ // Another device's routine arrives while the picker is open: the rows moved.
+ act(() => useStore.getState().update(s => { s.routines[0].ex.reverse() }))
+ act(() => onPick(EXIDX[DB_BENCH], true))
+ expect(slots().map(e => e.id)).toEqual([ROW, BENCH])
+ expect(useUI.getState().toastMsg).toBe('')
+ })
+})