fix: make session exercise removal timer-safe
This commit is contained in:
1 parent
f32c4d0b73
commit
b42d2baa6e
15 files changed
+292
-14
No files matched your search
@@ -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',
|
||||
|
||||
@@ -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',
|
||||
|
||||
@@ -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',
|
||||
|
||||
@@ -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} आराम के लिए सेट',
|
||||
|
||||
@@ -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',
|
||||
|
||||
@@ -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}을(를) 휴식일로 설정',
|
||||
|
||||
@@ -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',
|
||||
|
||||
@@ -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',
|
||||
|
||||
@@ -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} — теперь день отдыха',
|
||||
|
||||
@@ -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ı',
|
||||
|
||||
@@ -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} 已设为休息',
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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))
|
||||
})
|
||||
})
|
||||
})
|
||||
Reference in new issue
Block a user