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

+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))
})
})
})