Merge remote-tracking branch 'pr/83'

This commit is contained in:
Duarte Santos committed 2026-08-18 12:02:22 +02:00
commit 8fe980343d
13 files changed
+228 -2

No files matched your search

+54 -2
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'
@@ -171,11 +171,25 @@ 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 (idx < s.active.cur) s.active.cur--
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,6 +234,38 @@ function ActiveWorkout() {
const onPairPrev = !isSuperset && cur > 0 ? () => pairAt(cur - 1, cur) : null
const onPairNext = !isSuperset && cur < A.entries.length - 1 ? () => pairAt(cur, cur + 1) : null
// 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 = removeActiveExercise
const confirmRemoveExercise = idx => {
const e = A.entries[idx]
if (!e) return
const hasDone = (e.sets || []).some(s => s.done)
confirmSheet({
title: t('Remove {0}?', exOr(e.id).n),
message: hasDone
? t('The sets you logged for this exercise in this session will be lost.')
: t('This removes the exercise from your current session.'),
confirmText: t('Remove'), danger: true, onConfirm: () => removeExercise(idx)
})
}
const removeExerciseSheet = () => {
if (unit.length > 1) {
useUI.getState().openSheet(close => (
<div>
<h3>{t('Remove exercise')}</h3>
<div className="muted small" style={{ marginBottom: 12 }}>{t('Which exercise in this superset do you want to remove?')}</div>
<div className="list">
{unit.map(idx => <div key={idx} className="item" onClick={() => { close(); confirmRemoveExercise(idx) }}>
<div className="grow"><div className="tt">{exOr(A.entries[idx]?.id).n}</div></div>
<Icon name="chevronRight" />
</div>)}
</div>
</div>
))
} else confirmRemoveExercise(cur)
}
// A timed set is held, not typed. The work timer records what was actually held — an early
// finish logs 0:38 of a 0:45 target rather than crediting the full prescription — and then
// checks the set off through the normal path, so rest, supersets and the finish prompt all
@@ -335,6 +381,12 @@ function ActiveWorkout() {
s.active.cur = s.active.entries.length - 1
}), null, routine, seed)
})} icon="plus">{t('Add exercise')}</Button>
{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
+119
View File
@@ -0,0 +1,119 @@
// @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, cur = 0) {
const S = clone(DEF)
S.active = {
id: 'remove-test', d: '2026-08-11', start: Date.now(), routineId: null,
name: 'Remove test', bw: null, cur, 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')], 1)
expect(useStore.getState().S.active.cur).toBe(1)
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.cur).toBe(0)
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))
})
})
})