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.

Saved-workout editor: saving with every set unticked or removed no longer keeps an empty workout in the history; it asks to delete the workout instead, with Keep editing to go back (#203)

Duarte Santos0df6d0f0eb04
diff --git a/frontend/src/lib/session-edit.js b/frontend/src/lib/session-edit.js
index 0e6e67ca4..7c6374e1a 100644
--- a/frontend/src/lib/session-edit.js
+++ b/frontend/src/lib/session-edit.js
@@ -59,6 +59,32 @@ function bestIn(workout, id) {
return best
}
+// The kept working weight of an exercise is lowered only when it came from this session and the
+// edit took it away — a typed 1000 corrected to 100, or deleted with the rest of the workout. Then
+// it is the best set left in history, or gone. One confirmed anywhere else ("Tracked — next time
+// starts at…") is left as it is. `saved` is the record after the edit, null once it is deleted.
+function lowerKeptWeights(state, ids, current, saved) {
+ for (const id of ids) {
+ const kept = state.exWeights?.[id]
+ const before = bestIn(current, id)
+ if (!kept || !(kept.w > 0) || kept.w !== before || !beatsWeight(id, before, bestIn(saved, id))) continue
+ let best = null
+ for (const w of state.workouts) {
+ const top = bestIn(w, id)
+ if (beatsWeight(id, top, best?.w || 0)) best = { w: top, d: w.d }
+ }
+ if (best) state.exWeights[id] = best
+ else delete state.exWeights[id]
+ }
+}
+
+/**
+ * Whether the editor holds nothing Save could keep: not one set ticked done. Save drops an
+ * exercise without one (buildCompletedWorkout), so this draft would save as a workout with no
+ * exercises in it — an empty row in the history that counts as a training day.
+ */
+export const editLeftEmpty = active => !list(active?.entries).some(entry => list(entry?.sets).some(hasCompletedWork))
+
/**
* Opens the editor on a saved workout: a copy of it becomes S.active. `ref` is the workout or its
* id. Throws while another session is running, or when the workout is gone.
@@ -103,6 +129,8 @@ export function saveWorkoutEdit(state, now = Date.now()) {
const key = active?.editingWorkoutId
const index = key == null ? -1 : list(state.workouts).findIndex(w => keyOf(w) === key)
if (index < 0) throw new Error('This workout was deleted on another device. Your edits are still here.')
+ // Never saved empty: the editor asks to delete the workout instead (deleteEditedWorkout).
+ if (editLeftEmpty(active)) throw new Error('Nothing logged yet')
const current = state.workouts[index]
const updated = buildCompletedWorkout(active, {
@@ -149,22 +177,24 @@ export function saveWorkoutEdit(state, now = Date.now()) {
const touched = [...new Set([...list(current.entries), ...record.entries].map(e => e?.id).filter(id => id != null))]
state.workouts = rebuildPrHistory(state.workouts, touched, record)
const saved = state.workouts.find(w => keyOf(w) === key)
-
- // The kept working weight of an exercise is lowered only when it came from this session and the
- // edit took it away — a typed 1000 corrected to 100. Then it is the best set left in history, or
- // gone. One confirmed anywhere else ("Tracked — next time starts at…") is left as it is.
- for (const id of touched) {
- const kept = state.exWeights?.[id]
- const before = bestIn(current, id)
- if (!kept || !(kept.w > 0) || kept.w !== before || !beatsWeight(id, before, bestIn(saved, id))) continue
- let best = null
- for (const w of state.workouts) {
- const top = bestIn(w, id)
- if (beatsWeight(id, top, best?.w || 0)) best = { w: top, d: w.d }
- }
- if (best) state.exWeights[id] = best
- else delete state.exWeights[id]
- }
+ lowerKeptWeights(state, touched, current, saved)
state.active = null
return saved
}
+
+/**
+ * Deletes the workout the editor is open on and closes the editor: what an edit that took out
+ * every set gets instead of Save (editLeftEmpty). The record is found the way Save finds it, and
+ * goes the way History's Delete takes it out; a kept working weight that came from it is lowered
+ * the way Save lowers one an edit took away. A record another device deleted meanwhile is already
+ * gone, and the editor just closes. Returns whether a record was removed.
+ */
+export function deleteEditedWorkout(state) {
+ const key = state.active?.editingWorkoutId
+ const current = key == null ? null : list(state.workouts).find(w => keyOf(w) === key)
+ state.active = null
+ if (!current) return false
+ state.workouts = state.workouts.filter(w => w !== current)
+ lowerKeptWeights(state, [...new Set(list(current.entries).map(e => e?.id).filter(id => id != null))], current, null)
+ return true
+}
diff --git a/frontend/src/lib/session-edit.test.js b/frontend/src/lib/session-edit.test.js
index 2a853b488..1db6c3c49 100644
--- a/frontend/src/lib/session-edit.test.js
+++ b/frontend/src/lib/session-edit.test.js
@@ -1,5 +1,5 @@
import { describe, expect, it } from 'vitest'
-import { editCompletedSession, saveWorkoutEdit } from './session-edit.js'
+import { editCompletedSession, saveWorkoutEdit, editLeftEmpty, deleteEditedWorkout } from './session-edit.js'
import { mergeStates } from './sync-merge.js'
import { entryExcluded, lastEntryFor } from './history.js'
@@ -255,3 +255,72 @@ describe('saved workout editing', () => {
expect(JSON.stringify(saved)).not.toMatch(/weightOrigin|"plan"|carried|editingWorkoutId/)
})
})
+
+// An edit that unticks or removes every set would save a workout with nothing in it. The editor
+// offers to delete it instead (sheets.jsx saveWorkoutEdits), and Save itself refuses.
+describe('an edit that leaves no set', () => {
+ it('is told apart from one with a set left, ticked sets only', () => {
+ const state = fixture()
+ editCompletedSession(state, 'workout')
+ expect(editLeftEmpty(state.active)).toBe(false)
+ state.active.entries[0].sets[0].done = false
+ expect(editLeftEmpty(state.active)).toBe(true)
+ state.active.entries = []
+ expect(editLeftEmpty(state.active)).toBe(true)
+ expect(editLeftEmpty(null)).toBe(true)
+ // one side of a per-side set is a set done
+ state.active.entries = [{ id: '0025', sets: [{ sides: { L: { w: 10, r: 5, done: true }, R: { w: 10, r: 5, done: false } } }] }]
+ expect(editLeftEmpty(state.active)).toBe(false)
+ })
+
+ it('is never saved: Save throws and the draft stays open', () => {
+ const state = fixture(), history = structuredClone(state.workouts)
+ editCompletedSession(state, 'workout')
+ state.active.entries = []
+ expect(() => saveWorkoutEdit(state)).toThrow('Nothing logged yet')
+ expect(state.workouts).toEqual(history)
+ expect(state.active.editingWorkoutId).toBe('workout')
+ })
+
+ it('deletes the workout and closes the editor, leaving the other workouts alone', () => {
+ const state = fixture()
+ state.workouts.push({ id: 'other', d: '2026-09-02', start: 3000, end: 4000, entries: [entry(30)], prs: [] })
+ editCompletedSession(state, 'workout')
+ state.active.entries = []
+ expect(deleteEditedWorkout(state)).toBe(true)
+ expect(state.active).toBeNull()
+ expect(state.workouts.map(w => w.id)).toEqual(['other'])
+ })
+
+ it('deletes a workout from before ids by the key the editor opened it with', () => {
+ const state = fixture()
+ delete state.workouts[0].id
+ state.workouts.push({ d: '2026-09-02', start: 3000, end: 4000, entries: [entry(30)], prs: [] })
+ editCompletedSession(state, state.workouts[1])
+ expect(deleteEditedWorkout(state)).toBe(true)
+ expect(state.workouts).toHaveLength(1)
+ expect(state.workouts[0].d).toBe('2026-09-01')
+ })
+
+ it('closes the editor when another device already deleted the workout', () => {
+ const state = fixture()
+ editCompletedSession(state, 'workout')
+ state.workouts = []
+ expect(deleteEditedWorkout(state)).toBe(false)
+ expect(state.active).toBeNull()
+ })
+
+ // A typed 1000 that a whole deleted workout carried is not left behind as the weight the next
+ // session starts from; one confirmed elsewhere stays.
+ it('lowers a kept working weight that came from the deleted workout, and only that one', () => {
+ const state = fixture()
+ state.workouts[0].entries = [entry(1000), entry(50, '0027')]
+ state.workouts.push({ id: 'earlier', d: '2026-08-20', start: 0, end: 1, entries: [entry(95)], prs: [] })
+ state.exWeights = { '0025': { w: 1000, d: '2026-09-01' }, '0027': { w: 70, d: '2026-08-01' } }
+ editCompletedSession(state, 'workout')
+ state.active.entries = []
+ deleteEditedWorkout(state)
+ expect(state.exWeights['0025']).toEqual({ w: 95, d: '2026-08-20' })
+ expect(state.exWeights['0027']).toEqual({ w: 70, d: '2026-08-01' })
+ })
+})
diff --git a/frontend/src/locales/ar.js b/frontend/src/locales/ar.js
index 7c46eb5aa..213c9a996 100644
--- a/frontend/src/locales/ar.js
+++ b/frontend/src/locales/ar.js
@@ -1598,4 +1598,5 @@ export default {
'or with your password': 'أو بكلمة المرور',
'{0} passkeys': 'مفاتيح المرور: {0}',
'Every exercise in this workout': 'كل التمارين في هذه الجلسة',
+ 'No sets are left in this workout, so there is nothing to save. Delete it from your history?': 'لم تبقَ أي مجموعة في هذا التمرين، فلا يوجد ما يُحفظ. هل تريد حذفه من سجلك؟',
}
diff --git a/frontend/src/locales/de.js b/frontend/src/locales/de.js
index e6996f3da..73b4c175f 100644
--- a/frontend/src/locales/de.js
+++ b/frontend/src/locales/de.js
@@ -1565,4 +1565,5 @@ export default {
'Log the anchor lift to score this one.': 'Trag die Anker-Übung ein, damit diese bewertet werden kann.',
'Not scored': 'Nicht bewertet',
'Every exercise in this workout': 'Alle Übungen dieses Trainings',
+ 'No sets are left in this workout, so there is nothing to save. Delete it from your history?': 'In diesem Training ist kein Satz mehr übrig, es gibt also nichts zu speichern. Aus deinem Verlauf löschen?',
}
diff --git a/frontend/src/locales/es.js b/frontend/src/locales/es.js
index db8ac5d00..9b49380b8 100644
--- a/frontend/src/locales/es.js
+++ b/frontend/src/locales/es.js
@@ -1545,4 +1545,5 @@ export default {
'Log the anchor lift to score this one.': 'Registra el ejercicio ancla para evaluar este.',
'Not scored': 'Sin evaluar',
'Every exercise in this workout': 'Todos los ejercicios de este entrenamiento',
+ 'No sets are left in this workout, so there is nothing to save. Delete it from your history?': 'No queda ninguna serie en este entrenamiento, así que no hay nada que guardar. ¿Eliminarlo de tu historial?',
}
diff --git a/frontend/src/locales/fr.js b/frontend/src/locales/fr.js
index 5422b2be7..756aefee2 100644
--- a/frontend/src/locales/fr.js
+++ b/frontend/src/locales/fr.js
@@ -1545,4 +1545,5 @@ export default {
'Log the anchor lift to score this one.': 'Note l’exercice de référence pour évaluer celui-ci.',
'Not scored': 'Non évalué',
'Every exercise in this workout': 'Tous les exercices de cette séance',
+ 'No sets are left in this workout, so there is nothing to save. Delete it from your history?': 'Il ne reste aucune série dans cette séance, il n’y a donc rien à enregistrer. La supprimer de ton historique ?',
}
diff --git a/frontend/src/locales/hi.js b/frontend/src/locales/hi.js
index ac082b97e..20241a315 100644
--- a/frontend/src/locales/hi.js
+++ b/frontend/src/locales/hi.js
@@ -1545,4 +1545,5 @@ export default {
'Log the anchor lift to score this one.': 'इसका आकलन करने के लिए आधार व्यायाम दर्ज करें।',
'Not scored': 'आकलन नहीं हुआ',
'Every exercise in this workout': 'इस वर्कआउट के सभी व्यायाम',
+ 'No sets are left in this workout, so there is nothing to save. Delete it from your history?': 'इस वर्कआउट में कोई सेट नहीं बचा है, इसलिए सहेजने को कुछ नहीं है। इसे अपने इतिहास से हटाएँ?',
}
diff --git a/frontend/src/locales/hu.js b/frontend/src/locales/hu.js
index 8e0f03b9f..714d7e8d1 100644
--- a/frontend/src/locales/hu.js
+++ b/frontend/src/locales/hu.js
@@ -1548,4 +1548,5 @@ export default {
'Log the anchor lift to score this one.': 'Rögzítsd a viszonyítási alapul szolgáló gyakorlatot, hogy ez is értékelhető legyen.',
'Not scored': 'Nincs értékelve',
'Every exercise in this workout': 'Az edzés összes gyakorlata',
+ 'No sets are left in this workout, so there is nothing to save. Delete it from your history?': 'Ebben az edzésben egy sorozat sem maradt, így nincs mit menteni. Törlöd az előzményeidből?',
}
diff --git a/frontend/src/locales/it.js b/frontend/src/locales/it.js
index 91a986f46..0daa25bac 100644
--- a/frontend/src/locales/it.js
+++ b/frontend/src/locales/it.js
@@ -1545,4 +1545,5 @@ export default {
'Log the anchor lift to score this one.': 'Registra l’esercizio di riferimento per valutare questo.',
'Not scored': 'Non valutato',
'Every exercise in this workout': 'Tutti gli esercizi di questo allenamento',
+ 'No sets are left in this workout, so there is nothing to save. Delete it from your history?': 'In questo allenamento non è rimasta nessuna serie, quindi non c’è niente da salvare. Eliminarlo dalla cronologia?',
}
diff --git a/frontend/src/locales/ko.js b/frontend/src/locales/ko.js
index 6e9120a19..13665fd28 100644
--- a/frontend/src/locales/ko.js
+++ b/frontend/src/locales/ko.js
@@ -1545,4 +1545,5 @@ export default {
'Log the anchor lift to score this one.': '이 운동을 평가하려면 기준 운동을 기록하세요.',
'Not scored': '평가 안 됨',
'Every exercise in this workout': '이번 세션의 모든 운동',
+ 'No sets are left in this workout, so there is nothing to save. Delete it from your history?': '이 운동에 남은 세트가 없어 저장할 내용이 없습니다. 기록에서 삭제할까요?',
}
diff --git a/frontend/src/locales/pl.js b/frontend/src/locales/pl.js
index 66abbcea1..4e0a33a90 100644
--- a/frontend/src/locales/pl.js
+++ b/frontend/src/locales/pl.js
@@ -1545,4 +1545,5 @@ export default {
'Log the anchor lift to score this one.': 'Zapisz ćwiczenie będące punktem odniesienia, aby ocenić to ćwiczenie.',
'Not scored': 'Bez oceny',
'Every exercise in this workout': 'Wszystkie ćwiczenia w tym treningu',
+ 'No sets are left in this workout, so there is nothing to save. Delete it from your history?': 'W tym treningu nie została żadna seria, więc nie ma czego zapisać. Usunąć go z historii?',
}
diff --git a/frontend/src/locales/pt-BR.js b/frontend/src/locales/pt-BR.js
index 87ff1a4b3..5dead0aa1 100644
--- a/frontend/src/locales/pt-BR.js
+++ b/frontend/src/locales/pt-BR.js
@@ -903,6 +903,7 @@ export const PT_BR_OVERRIDES = {
'Custom': 'Personalizado',
'Log your body weight to score this lift.': 'Registre seu peso corporal para avaliar este exercício.',
'Log the anchor lift to score this one.': 'Registre o exercício de referência para avaliar este.',
+ 'No sets are left in this workout, so there is nothing to save. Delete it from your history?': 'Não sobrou nenhuma série neste treino, então não há nada para salvar. Excluí-lo do seu histórico?',
}
export default { ...pt, ...PT_BR_OVERRIDES }
diff --git a/frontend/src/locales/pt.js b/frontend/src/locales/pt.js
index bcc9fd2ac..a2dfafb61 100644
--- a/frontend/src/locales/pt.js
+++ b/frontend/src/locales/pt.js
@@ -1545,4 +1545,5 @@ export default {
'Log the anchor lift to score this one.': 'Regista o exercício de referência para avaliar este.',
'Not scored': 'Sem avaliação',
'Every exercise in this workout': 'Todos os exercícios deste treino',
+ 'No sets are left in this workout, so there is nothing to save. Delete it from your history?': 'Não resta nenhuma série neste treino, por isso não há nada para guardar. Eliminá-lo do histórico?',
}
diff --git a/frontend/src/locales/ru.js b/frontend/src/locales/ru.js
index 7ee4aeb3c..95e75f73f 100644
--- a/frontend/src/locales/ru.js
+++ b/frontend/src/locales/ru.js
@@ -1545,4 +1545,5 @@ export default {
'Log the anchor lift to score this one.': 'Запишите опорное упражнение, чтобы оценить это.',
'Not scored': 'Не оценено',
'Every exercise in this workout': 'Все упражнения этой тренировки',
+ 'No sets are left in this workout, so there is nothing to save. Delete it from your history?': 'В этой тренировке не осталось ни одного подхода, сохранять нечего. Удалить её из истории?',
}
diff --git a/frontend/src/locales/th.js b/frontend/src/locales/th.js
index 643f5af47..f2f6d54bd 100644
--- a/frontend/src/locales/th.js
+++ b/frontend/src/locales/th.js
@@ -1556,4 +1556,5 @@ export default {
'Log the anchor lift to score this one.': 'บันทึกท่าอ้างอิงเพื่อประเมินท่านี้',
'Not scored': 'ยังไม่ได้ประเมิน',
'Every exercise in this workout': 'ทุกท่าในการออกกำลังกายครั้งนี้',
+ 'No sets are left in this workout, so there is nothing to save. Delete it from your history?': 'การออกกำลังกายนี้ไม่เหลือเซ็ตแล้ว จึงไม่มีอะไรให้บันทึก ลบออกจากประวัติไหม?',
}
diff --git a/frontend/src/locales/tr.js b/frontend/src/locales/tr.js
index fb8d2e8fb..148e6a47d 100644
--- a/frontend/src/locales/tr.js
+++ b/frontend/src/locales/tr.js
@@ -1545,4 +1545,5 @@ export default {
'Log the anchor lift to score this one.': 'Bunu değerlendirmek için referans hareketi kaydet.',
'Not scored': 'Değerlendirilmedi',
'Every exercise in this workout': 'Bu antrenmandaki tüm egzersizler',
+ 'No sets are left in this workout, so there is nothing to save. Delete it from your history?': 'Bu antrenmanda hiç set kalmadı, yani kaydedilecek bir şey yok. Geçmişinden silinsin mi?',
}
diff --git a/frontend/src/locales/uk.js b/frontend/src/locales/uk.js
index d8eb9b229..28ec1b063 100644
--- a/frontend/src/locales/uk.js
+++ b/frontend/src/locales/uk.js
@@ -1542,4 +1542,5 @@ export default {
'or with your password': 'або своїм паролем',
'{0} passkeys': 'Ключів доступу: {0}',
'Every exercise in this workout': 'Усі вправи цього тренування',
+ 'No sets are left in this workout, so there is nothing to save. Delete it from your history?': 'У цьому тренуванні не лишилося жодного підходу, тож зберігати нічого. Видалити його з історії?',
}
diff --git a/frontend/src/locales/zh.js b/frontend/src/locales/zh.js
index 79e653055..95ce8b3b3 100644
--- a/frontend/src/locales/zh.js
+++ b/frontend/src/locales/zh.js
@@ -1545,4 +1545,5 @@ export default {
'Log the anchor lift to score this one.': '记录锚点动作以评估这个动作。',
'Not scored': '未评估',
'Every exercise in this workout': '本次训练的所有动作',
+ 'No sets are left in this workout, so there is nothing to save. Delete it from your history?': '这次训练已经没有任何一组了,没有可保存的内容。要从历史中删除它吗?',
}
diff --git a/frontend/src/sheets.jsx b/frontend/src/sheets.jsx
index 39a852e37..47a289294 100644
--- a/frontend/src/sheets.jsx
+++ b/frontend/src/sheets.jsx
@@ -42,7 +42,7 @@ import { joinSessionNoProg } from './lib/session-noprog.js'
import { buildCombinedEntries, deriveSessionName } from './lib/session-merge.js'
import { workoutsOn, backfillStart, backfillEnd, completeBackfill, historyAsOf, sessionHistory } from './lib/backfill.js'
import { moveWorkout, sameWorkout, startTimeOf, durationMinOf, setWorkoutDuration } from './lib/workout-date.js'
-import { editCompletedSession } from './lib/session-edit.js'
+import { editCompletedSession, editLeftEmpty } from './lib/session-edit.js'
import { stampWorkout } from './lib/sync-merge.js'
import { weeklyWeights } from './lib/bodyweight.js'
import { workoutText } from './lib/workout-text.js'
@@ -2481,6 +2481,25 @@ function WorkoutComplete({ close }) {
export const workoutCompleteSheet = () => ui().openSheet(close => <WorkoutComplete close={close} />, { kind: 'center' })
export function saveWorkoutEdits(onExit = () => nav('/history')) {
+ // An edit that unticked or removed every set would save a workout with nothing in it, which
+ // the history would still list and count as a training day. Deleting it is what that edit
+ // means; Keep editing goes back to the sets.
+ if (editLeftEmpty(S().active)) {
+ confirmSheet({
+ title: t('Delete workout?'),
+ message: t('No sets are left in this workout, so there is nothing to save. Delete it from your history?'),
+ confirmText: t('Delete workout'), cancelText: t('Keep editing'), danger: true,
+ onConfirm: () => {
+ useStore.getState().deleteHistoryEdit()
+ useUI.getState().stopRest()
+ useUI.getState().stopWork()
+ useStore.getState().autoBackupNow()
+ toast(t('Workout deleted'))
+ onExit()
+ },
+ })
+ return
+ }
try {
useStore.getState().saveHistoryEdit()
useUI.getState().stopRest()
diff --git a/frontend/src/store/useStore.js b/frontend/src/store/useStore.js
index bee13a7a6..c58c8787c 100644
--- a/frontend/src/store/useStore.js
+++ b/frontend/src/store/useStore.js
@@ -8,7 +8,7 @@ import { guestAllowed } from '../lib/guest.js'
import { MOBILE, initReminderSync, nativeLoad, nativeSave, onAppActive, readJsonFile, syncReminder, writeAutoBackup, writeJsonFile } from '../lib/mobile.js'
import { mergeStates, localExtras, stampRoutines } from '../lib/sync-merge.js'
import { countChanges, syncFingerprint } from '../lib/sync-changes.js'
-import { saveWorkoutEdit } from '../lib/session-edit.js'
+import { saveWorkoutEdit, deleteEditedWorkout } from '../lib/session-edit.js'
import { appBase } from '../lib/app-base.js'
import { linkTokenFromSearch, stripLinkFromUrl } from '../lib/device-link.js'
import { loadRemote, chooseLocal, forgetRemote, connect, normalizeServerUrl, renewToken } from '../lib/remote.js'
@@ -738,6 +738,12 @@ export const useStore = create((set, get) => {
return saved
},
discardHistoryEdit() { get().update(S => { S.active = null }) },
+ // An edit that took out every set deletes the workout rather than saving it empty.
+ deleteHistoryEdit() {
+ let removed = false
+ get().update(S => { removed = deleteEditedWorkout(S) })
+ return removed
+ },
// A replace that is meant to reach the server (backup import, reset) is a deliberate
// overwrite, not a change to merge: the push it arms goes without a baseRev.
replaceState(S, push = false) { if (push) forceNext = true; persist(clone(S), push) },
diff --git a/frontend/src/views/Workout.edit-empty.test.jsx b/frontend/src/views/Workout.edit-empty.test.jsx
new file mode 100644
index 000000000..4e6d70490
--- /dev/null
+++ b/frontend/src/views/Workout.edit-empty.test.jsx
@@ -0,0 +1,127 @@
+// @vitest-environment happy-dom
+// Saving the #203 editor with every set unticked or removed: it would save a workout with nothing
+// in it, which the history still lists and counts as a training day. It offers to delete the
+// workout instead, with Keep editing as the way back to the sets.
+import React, { act } from 'react'
+import { createRoot } from 'react-dom/client'
+import { MemoryRouter } from 'react-router-dom'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import Workout from './Workout.jsx'
+import { DEF, useStore } from '../store/useStore.js'
+import { useUI } from '../store/useUI.js'
+import { editCompletedSession } from '../lib/session-edit.js'
+
+vi.mock('../lib/sound.js', () => ({ beep: vi.fn(), chime: vi.fn(), vibrate: vi.fn(), unlock: vi.fn() }))
+vi.mock('../lib/api.js', () => ({ api: vi.fn(() => Promise.resolve({})), appBase: () => '/' }))
+
+globalThis.IS_REACT_ACT_ENVIRONMENT = true
+const clone = value => JSON.parse(JSON.stringify(value))
+const done = (id, w) => ({ id, target: { sets: 1, reps: 5, weight: w }, sets: [{ w, r: 5, done: true }] })
+const saved = { id: 'saved', d: '2026-09-22', start: 1000, end: 2000, routineIds: [], name: 'Push', entries: [done('0025', 80), done('0027', 60)], prs: [] }
+const other = { id: 'other', d: '2026-09-20', start: 0, end: 1, routineIds: [], name: 'Pull', entries: [done('0027', 55)], prs: [] }
+
+let root
+let container
+let sheetRoot
+let sheetContainer
+
+function renderEditor() {
+ const S = clone(DEF)
+ S.workouts = [clone(other), clone(saved)]
+ S.workoutView = 'list'
+ editCompletedSession(S, 'saved')
+ useStore.setState({ S, user: null })
+ container = document.createElement('div')
+ document.body.appendChild(container)
+ root = createRoot(container)
+ act(() => root.render(<MemoryRouter><Workout /></MemoryRouter>))
+}
+function renderTopSheet() {
+ if (sheetRoot) act(() => sheetRoot.unmount())
+ if (sheetContainer) sheetContainer.remove()
+ const sheet = useUI.getState().sheets.at(-1)
+ expect(sheet).toBeTruthy()
+ sheetContainer = document.createElement('div')
+ document.body.appendChild(sheetContainer)
+ sheetRoot = createRoot(sheetContainer)
+ act(() => sheetRoot.render(sheet.render(() => useUI.getState().closeSheet(sheet.id))))
+ return sheetContainer
+}
+// Sheets render through nested act() calls, so they are opened before an act() that taps them.
+const button = (host, text) => [...host.querySelectorAll('button')].find(b => b.textContent.trim() === text)
+const S = () => useStore.getState().S
+const untickAll = () => act(() => useStore.getState().update(s => { s.active.entries.forEach(e => e.sets.forEach(set => { set.done = false })) }))
+const tapSave = () => act(() => container.querySelector('button[aria-label="Save changes"]').click())
+
+beforeEach(() => {
+ vi.useFakeTimers()
+ localStorage.clear()
+ useUI.setState({ sheets: [], toastMsg: '', timer: null, work: null })
+ root = null; container = null; sheetRoot = null; sheetContainer = null
+})
+
+afterEach(() => {
+ if (sheetRoot) act(() => sheetRoot.unmount())
+ if (sheetContainer) sheetContainer.remove()
+ if (root) act(() => root.unmount())
+ if (container) container.remove()
+ useUI.getState().stopRest()
+ vi.clearAllTimers()
+ vi.useRealTimers()
+})
+
+describe('saving an edit that leaves no set', () => {
+ it('asks to delete the workout instead; Keep editing goes back with nothing saved', () => {
+ renderEditor()
+ untickAll()
+ tapSave()
+
+ const dialog = renderTopSheet()
+ expect(dialog.querySelector('h3').textContent).toBe('Delete workout?')
+ expect(dialog.textContent).toContain('No sets are left in this workout, so there is nothing to save. Delete it from your history?')
+ expect(button(dialog, 'Delete workout').className).toContain('danger')
+ act(() => button(dialog, 'Keep editing').click())
+
+ expect(useUI.getState().sheets).toHaveLength(0)
+ expect(S().active.editingWorkoutId).toBe('saved')
+ expect(S().workouts.find(w => w.id === 'saved').entries).toHaveLength(2)
+ expect(useUI.getState().toastMsg).toBe('')
+ })
+
+ it('Delete workout takes it out of the history and closes the editor', () => {
+ renderEditor()
+ untickAll()
+ tapSave()
+ const remove = button(renderTopSheet(), 'Delete workout')
+ act(() => remove.click())
+
+ expect(S().active).toBeNull()
+ expect(S().workouts.map(w => w.id)).toEqual(['other'])
+ expect(useUI.getState().toastMsg).toBe('Workout deleted')
+ })
+
+ it('asks the same when every exercise was removed, and from the close button’s Save changes', () => {
+ renderEditor()
+ act(() => useStore.getState().update(s => { s.active.entries = [] }))
+ act(() => container.querySelector('button[aria-label="Close editor"]').click())
+ const save = button(renderTopSheet(), 'Save changes')
+ act(() => save.click())
+
+ const dialog = renderTopSheet()
+ expect(dialog.querySelector('h3').textContent).toBe('Delete workout?')
+ act(() => button(dialog, 'Delete workout').click())
+ expect(S().workouts.map(w => w.id)).toEqual(['other'])
+ })
+
+ it('an edit with a set left saves as before, with no question', () => {
+ renderEditor()
+ act(() => useStore.getState().update(s => { s.active.entries[1].sets[0].done = false }))
+ tapSave()
+
+ expect(useUI.getState().sheets).toHaveLength(0)
+ expect(S().active).toBeNull()
+ const kept = S().workouts.find(w => w.id === 'saved')
+ expect(kept.entries.map(e => e.id)).toEqual(['0025'])
+ expect(useUI.getState().toastMsg).toBe('Workout updated')
+ })
+})