fix: make session exercise removal timer-safe

This commit is contained in:
root committed 2026-08-11 23:18:45 +02:00
1 parent f32c4d0b73
commit b42d2baa6e
15 files changed
+292 -14

No files matched your search

+97 -2
View File
@@ -1,12 +1,12 @@
{
"name": "opengym-frontend",
"version": "1.2.5",
"version": "1.2.6",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "opengym-frontend",
"version": "1.2.5",
"version": "1.2.6",
"license": "AGPL-3.0-or-later",
"dependencies": {
"@capacitor/core": "^7.6.8",
@@ -24,6 +24,7 @@
"@capacitor/cli": "^7.6.8",
"@capacitor/ios": "^7.6.8",
"@vitejs/plugin-react": "^6.0.3",
"happy-dom": "^20.11.2",
"linkedom": "^0.18.13",
"vite": "^8.1.5",
"vitest": "^4.1.10"
@@ -1265,6 +1266,23 @@
"integrity": "sha512-+OpjSaq85gvlZAYINyzKpLeiFkSC4EsC6IIiT6v6TLSU5k5U83fHGj9Lel8oKEXM0HqgrMVCjXPDPVICtxF7EQ==",
"dev": true
},
"node_modules/@types/whatwg-mimetype": {
"version": "3.0.2",
"resolved": "https://registry.npmjs.org/@types/whatwg-mimetype/-/whatwg-mimetype-3.0.2.tgz",
"integrity": "sha512-c2AKvDT8ToxLIOUlN51gTiHXflsfIFisS4pO7pDPoKouJCESkhZnEy623gwP9laCy5lnLDAw1vAzu2vM2YLOrA==",
"dev": true,
"license": "MIT"
},
"node_modules/@types/ws": {
"version": "8.18.1",
"resolved": "https://registry.npmjs.org/@types/ws/-/ws-8.18.1.tgz",
"integrity": "sha512-ThVF6DCVhA8kUGy+aazFQ4kXQ7E1Ty7A3ypFOe0IcJV8O/M511G99AW24irKrW56Wt44yG9+ij8FaqoBGkuBXg==",
"dev": true,
"license": "MIT",
"dependencies": {
"@types/node": "*"
}
},
"node_modules/@typescript/typescript-aix-ppc64": {
"version": "7.0.2",
"resolved": "https://registry.npmjs.org/@typescript/typescript-aix-ppc64/-/typescript-aix-ppc64-7.0.2.tgz",
@@ -2071,6 +2089,19 @@
"node": "*"
}
},
"node_modules/buffer-image-size": {
"version": "0.6.4",
"resolved": "https://registry.npmjs.org/buffer-image-size/-/buffer-image-size-0.6.4.tgz",
"integrity": "sha512-nEh+kZOPY1w+gcCMobZ6ETUp9WfibndnosbpwB1iJk/8Gt5ZF2bhS6+B6bPYz424KtwsR6Rflc3tCz1/ghX2dQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"@types/node": "*"
},
"engines": {
"node": ">=4.0"
}
},
"node_modules/camelcase": {
"version": "5.3.1",
"resolved": "https://registry.npmjs.org/camelcase/-/camelcase-5.3.1.tgz",
@@ -3276,6 +3307,38 @@
"uglify-js": "^3.1.4"
}
},
"node_modules/happy-dom": {
"version": "20.11.2",
"resolved": "https://registry.npmjs.org/happy-dom/-/happy-dom-20.11.2.tgz",
"integrity": "sha512-7MB+bJLkxu3SowAfBJbjW+c55kNz5tkR45gu2qzrxznezhLeN5YIlJbwUgSzlGc+qWoZ8Ykg71H5ezz69xixrw==",
"dev": true,
"license": "MIT",
"dependencies": {
"@types/node": ">=20.0.0",
"@types/whatwg-mimetype": "^3.0.2",
"@types/ws": "^8.18.1",
"buffer-image-size": "^0.6.4",
"entities": "^7.0.1",
"whatwg-mimetype": "^3.0.0",
"ws": "^8.21.0"
},
"engines": {
"node": ">=20.0.0"
}
},
"node_modules/happy-dom/node_modules/entities": {
"version": "7.0.1",
"resolved": "https://registry.npmjs.org/entities/-/entities-7.0.1.tgz",
"integrity": "sha512-TWrgLOFUQTH994YUyl1yT4uyavY5nNB5muff+RtWaqNVCAK408b5ZnnbNAUEWLTCpum9w6arT70i1XdQ4UeOPA==",
"dev": true,
"license": "BSD-2-Clause",
"engines": {
"node": ">=0.12"
},
"funding": {
"url": "https://github.com/fb55/entities?sponsor=1"
}
},
"node_modules/hard-rejection": {
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/hard-rejection/-/hard-rejection-2.1.0.tgz",
@@ -6418,6 +6481,16 @@
"integrity": "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==",
"dev": true
},
"node_modules/whatwg-mimetype": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/whatwg-mimetype/-/whatwg-mimetype-3.0.0.tgz",
"integrity": "sha512-nt+N2dzIutVRxARx1nghPKGv1xHikU7HKdfafKkLNLindmPU/ch3U31NOCGGA/dmPcmb1VlofO0vnKAcsm0o/Q==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=12"
}
},
"node_modules/whatwg-url": {
"version": "5.0.0",
"resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-5.0.0.tgz",
@@ -6494,6 +6567,28 @@
"integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==",
"dev": true
},
"node_modules/ws": {
"version": "8.21.3",
"resolved": "https://registry.npmjs.org/ws/-/ws-8.21.3.tgz",
"integrity": "sha512-201TZ/kPWxoPr/OKWjquZR1SWKXcvxdH+e1xrx89b3YbmzLMFCLfnaG1HFIgWzJOEWZ7MvpK++odZufgYR50Rw==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=10.0.0"
},
"peerDependencies": {
"bufferutil": "^4.0.1",
"utf-8-validate": ">=5.0.2"
},
"peerDependenciesMeta": {
"bufferutil": {
"optional": true
},
"utf-8-validate": {
"optional": true
}
}
},
"node_modules/xcode": {
"version": "3.0.1",
"resolved": "https://registry.npmjs.org/xcode/-/xcode-3.0.1.tgz",
+1
View File
@@ -28,6 +28,7 @@
"@capacitor/cli": "^7.6.8",
"@capacitor/ios": "^7.6.8",
"@vitejs/plugin-react": "^6.0.3",
"happy-dom": "^20.11.2",
"linkedom": "^0.18.13",
"vite": "^8.1.5",
"vitest": "^4.1.10"
+5
View File
@@ -94,6 +94,11 @@ export default {
'Weight ({0})': 'Gewicht ({0})',
'Add to routine': 'Zur Routine hinzufügen',
'Remove exercise': 'Übung entfernen',
'Remove {0}?': '{0} entfernen?',
'The sets you logged for this exercise in this session will be lost.': 'Die in dieser Einheit für diese Übung protokollierten Sätze gehen verloren.',
'This removes the exercise from your current session.': 'Dadurch wird die Übung aus deiner aktuellen Einheit entfernt.',
'Remove': 'Entfernen',
'Which exercise in this superset do you want to remove?': 'Welche Übung in diesem Supersatz möchtest du entfernen?',
'Pick an icon': 'Symbol auswählen',
// --- day planning / calendar ---
'Back to weekly plan': 'Zurück zum Wochenplan',
+5
View File
@@ -90,6 +90,11 @@ export default {
'Weight ({0})': 'Peso ({0})',
'Add to routine': 'Añadir a la rutina',
'Remove exercise': 'Quitar ejercicio',
'Remove {0}?': '¿Quitar {0}?',
'The sets you logged for this exercise in this session will be lost.': 'Se perderán las series que registraste para este ejercicio en esta sesión.',
'This removes the exercise from your current session.': 'Esto quita el ejercicio de tu sesión actual.',
'Remove': 'Quitar',
'Which exercise in this superset do you want to remove?': '¿Qué ejercicio de esta superserie quieres quitar?',
'Pick an icon': 'Elige un icono',
'Back to weekly plan': 'Volver al plan semanal',
'{0} set to rest': '{0} marcado como descanso',
+5
View File
@@ -90,6 +90,11 @@ export default {
'Weight ({0})': 'Poids ({0})',
'Add to routine': 'Ajouter à la routine',
'Remove exercise': "Retirer l'exercice",
'Remove {0}?': 'Retirer {0} ?',
'The sets you logged for this exercise in this session will be lost.': 'Les séries enregistrées pour cet exercice pendant cette séance seront perdues.',
'This removes the exercise from your current session.': 'Cela retire l’exercice de ta séance actuelle.',
'Remove': 'Retirer',
'Which exercise in this superset do you want to remove?': 'Quel exercice de ce superset veux-tu retirer ?',
'Pick an icon': 'Choisis une icône',
'Back to weekly plan': 'Retour au plan hebdo',
'{0} set to rest': '{0} passé en repos',
+5
View File
@@ -90,6 +90,11 @@ export default {
'Weight ({0})': 'वज़न ({0})',
'Add to routine': 'रूटीन में जोड़ें',
'Remove exercise': 'व्यायाम हटाएँ',
'Remove {0}?': '{0} हटाएँ?',
'The sets you logged for this exercise in this session will be lost.': 'इस सत्र में इस व्यायाम के लिए लॉग किए गए सेट मिट जाएँगे।',
'This removes the exercise from your current session.': 'यह व्यायाम आपके मौजूदा सत्र से हट जाएगा।',
'Remove': 'हटाएँ',
'Which exercise in this superset do you want to remove?': 'इस सुपरसेट से कौन-सा व्यायाम हटाना है?',
'Pick an icon': 'आइकन चुनें',
'Back to weekly plan': 'साप्ताहिक योजना पर वापस',
'{0} set to rest': '{0} आराम के लिए सेट',
+5
View File
@@ -90,6 +90,11 @@ export default {
'Weight ({0})': 'Peso ({0})',
'Add to routine': 'Aggiungi alla routine',
'Remove exercise': 'Rimuovi esercizio',
'Remove {0}?': 'Rimuovere {0}?',
'The sets you logged for this exercise in this session will be lost.': 'Le serie registrate per questo esercizio in questa sessione andranno perse.',
'This removes the exercise from your current session.': 'Questo rimuove l’esercizio dalla sessione corrente.',
'Remove': 'Rimuovi',
'Which exercise in this superset do you want to remove?': 'Quale esercizio di questa superserie vuoi rimuovere?',
'Pick an icon': 'Scegli un’icona',
'Back to weekly plan': 'Torna al piano settimanale',
'{0} set to rest': '{0} impostato a riposo',
+5
View File
@@ -90,6 +90,11 @@ export default {
'Weight ({0})': '무게 ({0})',
'Add to routine': '루틴에 추가',
'Remove exercise': '운동 제거',
'Remove {0}?': '{0}을(를) 제거할까요?',
'The sets you logged for this exercise in this session will be lost.': '이 세션에서 이 운동에 기록한 세트가 사라집니다.',
'This removes the exercise from your current session.': '현재 세션에서 이 운동을 제거합니다.',
'Remove': '제거',
'Which exercise in this superset do you want to remove?': '이 슈퍼세트에서 어떤 운동을 제거할까요?',
'Pick an icon': '아이콘 선택',
'Back to weekly plan': '주간 계획으로 복귀',
'{0} set to rest': '{0}을(를) 휴식일로 설정',
+5
View File
@@ -90,6 +90,11 @@ export default {
'Weight ({0})': 'Ciężar ({0})',
'Add to routine': 'Dodaj do planu',
'Remove exercise': 'Usuń ćwiczenie',
'Remove {0}?': 'Usunąć {0}?',
'The sets you logged for this exercise in this session will be lost.': 'Serie zapisane dla tego ćwiczenia w tej sesji zostaną utracone.',
'This removes the exercise from your current session.': 'Spowoduje to usunięcie ćwiczenia z bieżącej sesji.',
'Remove': 'Usuń',
'Which exercise in this superset do you want to remove?': 'Które ćwiczenie z tej superserii chcesz usunąć?',
'Pick an icon': 'Wybierz ikonę',
'Back to weekly plan': 'Wróć do planu tygodnia',
'{0} set to rest': '{0} ustawiono jako odpoczynek',
+5
View File
@@ -90,6 +90,11 @@ export default {
'Weight ({0})': 'Peso ({0})',
'Add to routine': 'Adicionar à rotina',
'Remove exercise': 'Remover exercício',
'Remove {0}?': 'Remover {0}?',
'The sets you logged for this exercise in this session will be lost.': 'As séries registadas para este exercício nesta sessão serão perdidas.',
'This removes the exercise from your current session.': 'Isto remove o exercício da tua sessão atual.',
'Remove': 'Remover',
'Which exercise in this superset do you want to remove?': 'Que exercício desta supersérie queres remover?',
'Pick an icon': 'Escolhe um ícone',
'Back to weekly plan': 'Voltar ao plano semanal',
'{0} set to rest': '{0} marcado como descanso',
+5
View File
@@ -90,6 +90,11 @@ export default {
'Weight ({0})': 'Вес ({0})',
'Add to routine': 'Добавить в программу',
'Remove exercise': 'Убрать упражнение',
'Remove {0}?': 'Удалить {0}?',
'The sets you logged for this exercise in this session will be lost.': 'Подходы, записанные для этого упражнения в этой сессии, будут потеряны.',
'This removes the exercise from your current session.': 'Упражнение будет удалено из текущей сессии.',
'Remove': 'Удалить',
'Which exercise in this superset do you want to remove?': 'Какое упражнение из этого суперсета удалить?',
'Pick an icon': 'Выбери иконку',
'Back to weekly plan': 'Вернуться к недельному плану',
'{0} set to rest': '{0} — теперь день отдыха',
+5
View File
@@ -90,6 +90,11 @@ export default {
'Weight ({0})': 'Ağırlık ({0})',
'Add to routine': 'Rutine ekle',
'Remove exercise': 'Egzersizi kaldır',
'Remove {0}?': '{0} kaldırılsın mı?',
'The sets you logged for this exercise in this session will be lost.': 'Bu seansta bu egzersiz için kaydettiğin setler kaybolacak.',
'This removes the exercise from your current session.': 'Bu işlem egzersizi mevcut seansından kaldırır.',
'Remove': 'Kaldır',
'Which exercise in this superset do you want to remove?': 'Bu süper sette hangi egzersizi kaldırmak istiyorsun?',
'Pick an icon': 'Bir simge seç',
'Back to weekly plan': 'Haftalık plana dön',
'{0} set to rest': '{0} dinlenme olarak ayarlandı',
+5
View File
@@ -90,6 +90,11 @@ export default {
'Weight ({0})': '重量({0})',
'Add to routine': '加入训练日',
'Remove exercise': '移除动作',
'Remove {0}?': '移除 {0}?',
'The sets you logged for this exercise in this session will be lost.': '本次训练中为该动作记录的组数将丢失。',
'This removes the exercise from your current session.': '这会从当前训练中移除该动作。',
'Remove': '移除',
'Which exercise in this superset do you want to remove?': '你想移除这个超级组中的哪个动作?',
'Pick an icon': '选择图标',
'Back to weekly plan': '恢复每周计划',
'{0} set to rest': '{0} 已设为休息',
+22 -12
View File
@@ -3,7 +3,7 @@ import { useNavigate } from 'react-router-dom'
import { useStore } from '../store/useStore.js'
import { useUI } from '../store/useUI.js'
import { exOr } from '../lib/exercises.js'
import { effectiveRoutine, lastEntryFor, bestWeightFor, buildSets, freestyleConfig, defaultConfig, setsDoneActive, supersetUnits, unitOf, setLabel, modeOf, isBw, isPerSide, sideReps, repStep, EFFORT, effortOf, stepEffort, capEffort, cascadeWeight, insertWarmupRow, removeRowAt, pairAdjacent, unpairSuperset } from '../lib/history.js'
import { effectiveRoutine, lastEntryFor, bestWeightFor, buildSets, freestyleConfig, defaultConfig, setsDoneActive, supersetUnits, unitOf, setLabel, modeOf, isBw, isPerSide, sideReps, repStep, EFFORT, effortOf, stepEffort, capEffort, cascadeWeight, insertWarmupRow, removeRowAt, pairAdjacent, unpairSuperset, cleanupSg } from '../lib/history.js'
import { fmtNum, fmtDate, todayISO, exCount, DAYN } from '../lib/format.js'
import { beep, vibrate } from '../lib/sound.js'
import { t } from '../lib/i18n.js'
@@ -169,11 +169,24 @@ function ExerciseBlock({ entryIdx, compact, onToggle, onField, onAddSet, onRemov
}
/* ---------- active workout ---------- */
export function removeActiveExercise(idx) {
// Clear the work callback before indexes can shift. This also protects a confirmation sheet
// that was opened first and confirmed after a timed hold started.
useUI.getState().stopWork()
useStore.getState().update(s => {
if (!s.active || !Array.isArray(s.active.entries)) return
if (idx < 0 || idx >= s.active.entries.length) return
s.active.entries.splice(idx, 1)
cleanupSg(s.active.entries)
if (s.active.cur >= s.active.entries.length) s.active.cur = Math.max(0, s.active.entries.length - 1)
}, true)
}
function ActiveWorkout() {
const nav = useNavigate()
const S = useStore(s => s.S)
const update = useStore(s => s.update)
const { startRest, stopRest } = useUI()
const { startRest, stopRest, work } = useUI()
const A = S.active
const units = supersetUnits(A.entries)
const cur = Math.min(A.cur, Math.max(0, A.entries.length - 1))
@@ -220,12 +233,7 @@ function ActiveWorkout() {
// Remove a whole exercise from the session. The confirmation always asks first; in a
// superset it asks WHICH exercise of the group to remove.
const removeExercise = idx => update(s => {
if (!s.active || !Array.isArray(s.active.entries)) return
if (idx < 0 || idx >= s.active.entries.length) return
s.active.entries.splice(idx, 1)
if (s.active.cur >= s.active.entries.length) s.active.cur = Math.max(0, s.active.entries.length - 1)
}, true)
const removeExercise = removeActiveExercise
const confirmRemoveExercise = idx => {
const e = A.entries[idx]
if (!e) return
@@ -370,10 +378,12 @@ function ActiveWorkout() {
s.active.cur = s.active.entries.length - 1
}), null, routine, seed)
})} icon="plus">{t('Add exercise')}</Button>
<div style={{ height: 6 }} />
<div style={{ display: 'flex', justifyContent: 'center' }}>
<Button size="sm" icon="minus" style={{ color: 'var(--red)' }} onClick={removeExerciseSheet}>{t('Remove exercise')}</Button>
</div>
{A.entries.length > 0 && <>
<div style={{ height: 6 }} />
<div style={{ display: 'flex', justifyContent: 'center' }}>
<Button size="sm" icon="minus" style={{ color: 'var(--red)' }} disabled={!!work} onClick={removeExerciseSheet}>{t('Remove exercise')}</Button>
</div>
</>}
<div style={{ height: 10 }} />
{(() => {
const exDone = A.entries.filter(e => e.sets.length && e.sets.every(s => s.done)).length
+117
View File
@@ -0,0 +1,117 @@
// @vitest-environment happy-dom
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, { removeActiveExercise } from './Workout.jsx'
import { DEF, useStore } from '../store/useStore.js'
import { useUI } from '../store/useUI.js'
vi.mock('../lib/sound.js', () => ({ beep: vi.fn(), vibrate: vi.fn() }))
vi.mock('../lib/api.js', () => ({ api: vi.fn(() => Promise.resolve({})) }))
globalThis.IS_REACT_ACT_ENVIRONMENT = true
const clone = value => JSON.parse(JSON.stringify(value))
const entry = (id, sg) => ({
id,
...(sg ? { sg } : {}),
target: { sets: 1, reps: 1 },
sets: [{ w: 0, r: 1, done: false }]
})
let root
let container
function setActive(entries) {
const S = clone(DEF)
S.active = {
id: 'remove-test', d: '2026-08-11', start: Date.now(), routineId: null,
name: 'Remove test', bw: null, cur: 0, entries
}
useStore.setState({ S, user: null })
}
function renderWorkout(entries) {
setActive(entries)
container = document.createElement('div')
document.body.appendChild(container)
root = createRoot(container)
act(() => root.render(<MemoryRouter><Workout /></MemoryRouter>))
}
function removeButton() {
return [...container.querySelectorAll('button')].find(button => button.textContent.includes('Remove exercise'))
}
beforeEach(() => {
vi.useFakeTimers()
localStorage.clear()
useUI.getState().stopRest()
useUI.getState().stopWork()
useUI.setState({ sheets: [], toastMsg: '', timer: null, work: null })
useStore.setState({ S: clone(DEF), user: null })
root = null
container = null
})
afterEach(() => {
if (root) act(() => root.unmount())
if (container) container.remove()
useUI.getState().stopRest()
useUI.getState().stopWork()
vi.clearAllTimers()
vi.useRealTimers()
})
describe('active-session exercise removal', () => {
it('disables removal for the whole duration of a timed hold', () => {
renderWorkout([entry('1001')])
expect(removeButton()).toBeTruthy()
expect(removeButton().disabled).toBe(false)
act(() => useUI.getState().startWork(30, 'Hold', vi.fn()))
expect(removeButton().disabled).toBe(true)
})
it('cancels a pending timed callback before indexes shift and cleans a one-member group', () => {
setActive([entry('1001', 'sg-1'), entry('1002', 'sg-1'), entry('1003')])
const wrongWrite = vi.fn(elapsed => {
useStore.getState().update(s => { s.active.entries[0].sets[0].sec = elapsed })
})
useUI.getState().startWork(5, 'Hold', wrongWrite)
removeActiveExercise(0)
vi.advanceTimersByTime(10_000)
const active = useStore.getState().S.active
expect(useUI.getState().work).toBeNull()
expect(wrongWrite).not.toHaveBeenCalled()
expect(active.entries.map(e => e.id)).toEqual(['1002', '1003'])
expect(active.entries[0].sg).toBeUndefined()
expect(active.entries[0].sets[0].sec).toBeUndefined()
})
it('hides the remove control for an empty freestyle session', () => {
renderWorkout([])
expect(removeButton()).toBeUndefined()
})
})
describe('remove-exercise locale coverage', () => {
const required = [
'Remove {0}?',
'The sets you logged for this exercise in this session will be lost.',
'This removes the exercise from your current session.',
'Remove',
'Which exercise in this superset do you want to remove?'
]
const packs = import.meta.glob('../locales/*.js', { eager: true, import: 'default' })
it('defines every new prompt in all eleven locale packs', () => {
expect(Object.keys(packs)).toHaveLength(11)
Object.entries(packs).forEach(([path, pack]) => {
required.forEach(key => expect(pack, `${path} is missing ${key}`).toHaveProperty(key))
})
})
})