curated2: !43
This commit is contained in:
commit
0e3b8fa74b
18 files changed
+366
-2
No files matched your search
@@ -0,0 +1,44 @@
|
||||
import { supersetUnits, unitOf } from './history.js'
|
||||
|
||||
function hasLoggedSet(entry) {
|
||||
return Array.isArray(entry?.sets) && entry.sets.some(set => set?.done === true)
|
||||
}
|
||||
|
||||
/**
|
||||
* Swap one exact active-workout occurrence.
|
||||
*
|
||||
* Unlogged occurrences are replaced in place. Logged results are never relabelled: after explicit
|
||||
* confirmation, the replacement is inserted beside the original. A logged group member also
|
||||
* requires an explicit choice to keep the replacement in the group or detach it after the group.
|
||||
*/
|
||||
export function swapActiveExercise(active, index, replacement, {
|
||||
loggedConfirmed = false,
|
||||
groupDisposition
|
||||
} = {}) {
|
||||
if (!active || !Array.isArray(active.entries) || !replacement || index < 0 || index >= active.entries.length) return null
|
||||
|
||||
const current = active.entries[index]
|
||||
if (!hasLoggedSet(current)) {
|
||||
const metadata = Object.fromEntries(Object.entries(current).filter(([key]) => (
|
||||
!['id', 'target', 'plan', 'sets', 'sg'].includes(key)
|
||||
)))
|
||||
active.entries[index] = { ...metadata, ...replacement, ...(current.sg ? { sg: current.sg } : {}) }
|
||||
active.cur = index
|
||||
return { inserted: false, index }
|
||||
}
|
||||
|
||||
if (!loggedConfirmed) return { needsConfirmation: true, grouped: !!current.sg, index }
|
||||
if (current.sg && !['keep', 'detach'].includes(groupDisposition)) {
|
||||
return { needsConfirmation: true, grouped: true, index }
|
||||
}
|
||||
|
||||
const unit = unitOf(supersetUnits(active.entries), index)
|
||||
const keepGroup = current.sg && groupDisposition === 'keep'
|
||||
const insertAt = keepGroup ? index + 1 : (unit.length > 1 ? unit.at(-1) + 1 : index + 1)
|
||||
active.entries.splice(insertAt, 0, {
|
||||
...replacement,
|
||||
...(keepGroup ? { sg: current.sg } : {})
|
||||
})
|
||||
active.cur = insertAt
|
||||
return { inserted: true, index: insertAt }
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { swapActiveExercise } from './active-exercise-swap.js'
|
||||
|
||||
const entry = (id, { sg, done = false, target, sets } = {}) => ({
|
||||
id,
|
||||
...(sg ? { sg } : {}),
|
||||
target: target || { mode: 'reps', sets: 1, reps: 5, weight: 40 },
|
||||
sets: sets || [{ w: 40, r: 5, done }]
|
||||
})
|
||||
|
||||
const replacement = () => entry('incline', {
|
||||
target: { mode: 'reps', sets: 2, reps: 8, weight: 32.5, note: 'Keep elbows tucked.', intensifier: { type: 'dropset', count: 1, pct: 20 } },
|
||||
sets: [{ w: 32.5, r: 8, done: false }, { w: 32.5, r: 8, done: false }]
|
||||
})
|
||||
|
||||
describe('safe active exercise swap', () => {
|
||||
it('replaces only the selected duplicate occurrence and preserves its group and replacement metadata', () => {
|
||||
const first = entry('bench', { sg: 'pair' })
|
||||
const selected = entry('bench', { sg: 'pair' })
|
||||
selected.occurrenceId = 'bench#2'
|
||||
selected.provenance = { routineIndex: 4 }
|
||||
const unrelated = entry('row')
|
||||
const active = { cur: 1, entries: [first, selected, unrelated] }
|
||||
const next = replacement()
|
||||
|
||||
expect(swapActiveExercise(active, 1, next)).toEqual({ inserted: false, index: 1 })
|
||||
expect(active.entries.map(value => value.id)).toEqual(['bench', 'incline', 'row'])
|
||||
expect(active.entries[0]).toBe(first)
|
||||
expect(active.entries[2]).toBe(unrelated)
|
||||
expect(active.entries[1]).toEqual({
|
||||
...next,
|
||||
occurrenceId: 'bench#2',
|
||||
provenance: { routineIndex: 4 },
|
||||
sg: 'pair'
|
||||
})
|
||||
expect(active.cur).toBe(1)
|
||||
})
|
||||
|
||||
it('fails closed before a logged standalone occurrence is explicitly confirmed', () => {
|
||||
const logged = entry('bench', { sets: [{ w: 42.5, r: 7, done: true, rir: 1 }] })
|
||||
const active = { cur: 0, entries: [logged, entry('row')] }
|
||||
|
||||
expect(swapActiveExercise(active, 0, replacement())).toEqual({ needsConfirmation: true, grouped: false, index: 0 })
|
||||
expect(active.entries).toEqual([logged, active.entries[1]])
|
||||
expect(active.cur).toBe(0)
|
||||
})
|
||||
|
||||
it('preserves a confirmed logged occurrence and inserts the replacement after it', () => {
|
||||
const logged = entry('bench', { sets: [{ w: 42.5, r: 7, done: true, rir: 1 }] })
|
||||
const unrelated = entry('row')
|
||||
const active = { cur: 0, entries: [logged, unrelated] }
|
||||
|
||||
expect(swapActiveExercise(active, 0, replacement(), { loggedConfirmed: true })).toEqual({ inserted: true, index: 1 })
|
||||
expect(active.entries[0]).toBe(logged)
|
||||
expect(active.entries[0].sets[0]).toEqual({ w: 42.5, r: 7, done: true, rir: 1 })
|
||||
expect(active.entries[1].id).toBe('incline')
|
||||
expect(active.entries[2]).toBe(unrelated)
|
||||
expect(active.cur).toBe(1)
|
||||
})
|
||||
|
||||
it('requires an explicit grouped disposition before changing a logged group member', () => {
|
||||
const active = { cur: 0, entries: [entry('bench', { sg: 'pair', done: true }), entry('row', { sg: 'pair' }), entry('curl')] }
|
||||
const before = [...active.entries]
|
||||
|
||||
expect(swapActiveExercise(active, 0, replacement(), { loggedConfirmed: true }))
|
||||
.toEqual({ needsConfirmation: true, grouped: true, index: 0 })
|
||||
expect(active.entries).toEqual(before)
|
||||
})
|
||||
|
||||
it.each([
|
||||
['keep', ['bench', 'incline', 'row', 'curl'], ['pair', 'pair', 'pair', undefined], 1],
|
||||
['detach', ['bench', 'row', 'incline', 'curl'], ['pair', 'pair', undefined, undefined], 2]
|
||||
])('%s confirmation preserves logged group data and unrelated entries', (groupDisposition, ids, groups, cursor) => {
|
||||
const logged = entry('bench', { sg: 'pair', sets: [{ w: 45, r: 6, done: true }] })
|
||||
const partner = entry('row', { sg: 'pair' })
|
||||
const unrelated = entry('curl')
|
||||
const active = { cur: 0, entries: [logged, partner, unrelated] }
|
||||
|
||||
expect(swapActiveExercise(active, 0, replacement(), { loggedConfirmed: true, groupDisposition }))
|
||||
.toEqual({ inserted: true, index: cursor })
|
||||
expect(active.entries.map(value => value.id)).toEqual(ids)
|
||||
expect(active.entries.map(value => value.sg)).toEqual(groups)
|
||||
expect(active.entries[0]).toBe(logged)
|
||||
expect(active.entries.includes(partner)).toBe(true)
|
||||
expect(active.entries.at(-1)).toBe(unrelated)
|
||||
expect(active.cur).toBe(cursor)
|
||||
})
|
||||
})
|
||||
@@ -97,6 +97,12 @@ export default {
|
||||
'Weight ({0})': 'Gewicht ({0})',
|
||||
'Add to routine': 'Zur Routine hinzufügen',
|
||||
'Remove exercise': 'Übung entfernen',
|
||||
'Swap exercise': 'Übung wechseln',
|
||||
'Swap exercise?': 'Übung tauschen?',
|
||||
'Logged sets stay with the original exercise. Choose where the replacement belongs.': 'Aufgezeichnete Sätze bleiben bei der ursprünglichen Übung. Wähle, wo die Ersatzübung hingehört.',
|
||||
'Keep replacement in this group': 'Ersatzübung in dieser Gruppe behalten',
|
||||
'Insert after this group': 'Nach dieser Gruppe einfügen',
|
||||
'Logged sets stay with the original exercise. The replacement will be inserted afterward.': 'Aufgezeichnete Sätze bleiben bei der ursprünglichen Übung. Die Ersatzübung wird danach eingefügt.',
|
||||
'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.',
|
||||
|
||||
@@ -93,6 +93,12 @@ export default {
|
||||
'Weight ({0})': 'Peso ({0})',
|
||||
'Add to routine': 'Añadir a la rutina',
|
||||
'Remove exercise': 'Quitar ejercicio',
|
||||
'Swap exercise': 'Cambiar ejercicio',
|
||||
'Swap exercise?': '¿Cambiar ejercicio?',
|
||||
'Logged sets stay with the original exercise. Choose where the replacement belongs.': 'Las series registradas permanecen con el ejercicio original. Elige dónde colocar el reemplazo.',
|
||||
'Keep replacement in this group': 'Mantener el reemplazo en este grupo',
|
||||
'Insert after this group': 'Insertar después de este grupo',
|
||||
'Logged sets stay with the original exercise. The replacement will be inserted afterward.': 'Las series registradas permanecen con el ejercicio original. El reemplazo se insertará después.',
|
||||
'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.',
|
||||
|
||||
@@ -93,6 +93,12 @@ export default {
|
||||
'Weight ({0})': 'Poids ({0})',
|
||||
'Add to routine': 'Ajouter à la routine',
|
||||
'Remove exercise': "Retirer l'exercice",
|
||||
'Swap exercise': 'Remplacer l’exercice',
|
||||
'Swap exercise?': 'Remplacer l’exercice ?',
|
||||
'Logged sets stay with the original exercise. Choose where the replacement belongs.': 'Les séries enregistrées restent avec l’exercice d’origine. Choisis où placer le remplacement.',
|
||||
'Keep replacement in this group': 'Garder le remplacement dans ce groupe',
|
||||
'Insert after this group': 'Insérer après ce groupe',
|
||||
'Logged sets stay with the original exercise. The replacement will be inserted afterward.': 'Les séries enregistrées restent avec l’exercice d’origine. Le remplacement sera inséré après.',
|
||||
'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.',
|
||||
|
||||
@@ -93,6 +93,12 @@ export default {
|
||||
'Weight ({0})': 'वज़न ({0})',
|
||||
'Add to routine': 'रूटीन में जोड़ें',
|
||||
'Remove exercise': 'व्यायाम हटाएँ',
|
||||
'Swap exercise': 'व्यायाम बदलें',
|
||||
'Swap exercise?': 'एक्सरसाइज़ बदलें?',
|
||||
'Logged sets stay with the original exercise. Choose where the replacement belongs.': 'रिकॉर्ड किए गए सेट मूल एक्सरसाइज़ के साथ रहेंगे। बदलने वाली एक्सरसाइज़ की जगह चुनें।',
|
||||
'Keep replacement in this group': 'बदलने वाली एक्सरसाइज़ इसी समूह में रखें',
|
||||
'Insert after this group': 'इस समूह के बाद जोड़ें',
|
||||
'Logged sets stay with the original exercise. The replacement will be inserted afterward.': 'रिकॉर्ड किए गए सेट मूल एक्सरसाइज़ के साथ रहेंगे। बदलने वाली एक्सरसाइज़ बाद में जोड़ी जाएगी।',
|
||||
'Remove {0}?': '{0} हटाएँ?',
|
||||
'The sets you logged for this exercise in this session will be lost.': 'इस सत्र में इस व्यायाम के लिए लॉग किए गए सेट मिट जाएँगे।',
|
||||
'This removes the exercise from your current session.': 'यह व्यायाम आपके मौजूदा सत्र से हट जाएगा।',
|
||||
|
||||
@@ -93,6 +93,12 @@ export default {
|
||||
'Weight ({0})': 'Peso ({0})',
|
||||
'Add to routine': 'Aggiungi alla routine',
|
||||
'Remove exercise': 'Rimuovi esercizio',
|
||||
'Swap exercise': 'Sostituisci esercizio',
|
||||
'Swap exercise?': 'Sostituire l’esercizio?',
|
||||
'Logged sets stay with the original exercise. Choose where the replacement belongs.': 'Le serie registrate restano con l’esercizio originale. Scegli dove inserire il sostituto.',
|
||||
'Keep replacement in this group': 'Mantieni il sostituto in questo gruppo',
|
||||
'Insert after this group': 'Inserisci dopo questo gruppo',
|
||||
'Logged sets stay with the original exercise. The replacement will be inserted afterward.': 'Le serie registrate restano con l’esercizio originale. Il sostituto verrà inserito dopo.',
|
||||
'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.',
|
||||
|
||||
@@ -93,6 +93,12 @@ export default {
|
||||
'Weight ({0})': '무게 ({0})',
|
||||
'Add to routine': '루틴에 추가',
|
||||
'Remove exercise': '운동 제거',
|
||||
'Swap exercise': '운동 바꾸기',
|
||||
'Swap exercise?': '운동을 바꿀까요?',
|
||||
'Logged sets stay with the original exercise. Choose where the replacement belongs.': '기록한 세트는 원래 운동에 남습니다. 대체 운동을 넣을 위치를 선택하세요.',
|
||||
'Keep replacement in this group': '대체 운동을 이 그룹에 유지',
|
||||
'Insert after this group': '이 그룹 뒤에 삽입',
|
||||
'Logged sets stay with the original exercise. The replacement will be inserted afterward.': '기록한 세트는 원래 운동에 남습니다. 대체 운동은 뒤에 삽입됩니다.',
|
||||
'Remove {0}?': '{0}을(를) 제거할까요?',
|
||||
'The sets you logged for this exercise in this session will be lost.': '이 세션에서 이 운동에 기록한 세트가 사라집니다.',
|
||||
'This removes the exercise from your current session.': '현재 세션에서 이 운동을 제거합니다.',
|
||||
|
||||
@@ -93,6 +93,12 @@ export default {
|
||||
'Weight ({0})': 'Ciężar ({0})',
|
||||
'Add to routine': 'Dodaj do planu',
|
||||
'Remove exercise': 'Usuń ćwiczenie',
|
||||
'Swap exercise': 'Zamień ćwiczenie',
|
||||
'Swap exercise?': 'Zamienić ćwiczenie?',
|
||||
'Logged sets stay with the original exercise. Choose where the replacement belongs.': 'Zapisane serie pozostają przy oryginalnym ćwiczeniu. Wybierz miejsce dla zamiennika.',
|
||||
'Keep replacement in this group': 'Zachowaj zamiennik w tej grupie',
|
||||
'Insert after this group': 'Wstaw za tą grupą',
|
||||
'Logged sets stay with the original exercise. The replacement will be inserted afterward.': 'Zapisane serie pozostają przy oryginalnym ćwiczeniu. Zamiennik zostanie wstawiony za nim.',
|
||||
'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.',
|
||||
|
||||
@@ -28,6 +28,12 @@ export const PT_BR_OVERRIDES = {
|
||||
'Search {0} exercises…': 'Buscar entre {0} exercícios…',
|
||||
'Nothing chosen yet — add exercises and they’ll show up here.': 'Nenhum exercício escolhido — adicione exercícios e eles aparecerão aqui.',
|
||||
'The sets you logged for this exercise in this session will be lost.': 'As séries registradas para este exercício nesta sessão serão perdidas.',
|
||||
'Swap exercise': 'Trocar exercício',
|
||||
'Swap exercise?': 'Trocar exercício?',
|
||||
'Logged sets stay with the original exercise. Choose where the replacement belongs.': 'As séries registradas ficam com o exercício original. Escolha onde colocar o substituto.',
|
||||
'Keep replacement in this group': 'Manter o substituto neste grupo',
|
||||
'Insert after this group': 'Inserir depois deste grupo',
|
||||
'Logged sets stay with the original exercise. The replacement will be inserted afterward.': 'As séries registradas ficam com o exercício original. O substituto será inserido depois.',
|
||||
'This removes the exercise from your current session.': 'Isso remove o exercício da sua sessão atual.',
|
||||
'Which exercise in this superset do you want to remove?': 'Qual exercício deste superset você quer remover?',
|
||||
'Pick an icon': 'Escolha um ícone',
|
||||
|
||||
@@ -93,6 +93,12 @@ export default {
|
||||
'Weight ({0})': 'Peso ({0})',
|
||||
'Add to routine': 'Adicionar à rotina',
|
||||
'Remove exercise': 'Remover exercício',
|
||||
'Swap exercise': 'Trocar exercício',
|
||||
'Swap exercise?': 'Trocar exercício?',
|
||||
'Logged sets stay with the original exercise. Choose where the replacement belongs.': 'As séries registadas ficam com o exercício original. Escolhe onde colocar o substituto.',
|
||||
'Keep replacement in this group': 'Manter o substituto neste grupo',
|
||||
'Insert after this group': 'Inserir depois deste grupo',
|
||||
'Logged sets stay with the original exercise. The replacement will be inserted afterward.': 'As séries registadas ficam com o exercício original. O substituto será inserido depois.',
|
||||
'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.',
|
||||
|
||||
@@ -93,6 +93,12 @@ export default {
|
||||
'Weight ({0})': 'Вес ({0})',
|
||||
'Add to routine': 'Добавить в программу',
|
||||
'Remove exercise': 'Убрать упражнение',
|
||||
'Swap exercise': 'Заменить упражнение',
|
||||
'Swap exercise?': 'Заменить упражнение?',
|
||||
'Logged sets stay with the original exercise. Choose where the replacement belongs.': 'Записанные подходы останутся у исходного упражнения. Выберите место для замены.',
|
||||
'Keep replacement in this group': 'Оставить замену в этой группе',
|
||||
'Insert after this group': 'Вставить после этой группы',
|
||||
'Logged sets stay with the original exercise. The replacement will be inserted afterward.': 'Записанные подходы останутся у исходного упражнения. Замена будет вставлена после него.',
|
||||
'Remove {0}?': 'Удалить {0}?',
|
||||
'The sets you logged for this exercise in this session will be lost.': 'Подходы, записанные для этого упражнения в этой сессии, будут потеряны.',
|
||||
'This removes the exercise from your current session.': 'Упражнение будет удалено из текущей сессии.',
|
||||
|
||||
@@ -93,6 +93,12 @@ export default {
|
||||
'Weight ({0})': 'Ağırlık ({0})',
|
||||
'Add to routine': 'Rutine ekle',
|
||||
'Remove exercise': 'Egzersizi kaldır',
|
||||
'Swap exercise': 'Egzersizi değiştir',
|
||||
'Swap exercise?': 'Egzersiz değiştirilsin mi?',
|
||||
'Logged sets stay with the original exercise. Choose where the replacement belongs.': 'Kaydedilen setler özgün egzersizde kalır. Yeni egzersizin nereye geleceğini seç.',
|
||||
'Keep replacement in this group': 'Yeni egzersizi bu grupta tut',
|
||||
'Insert after this group': 'Bu gruptan sonra ekle',
|
||||
'Logged sets stay with the original exercise. The replacement will be inserted afterward.': 'Kaydedilen setler özgün egzersizde kalır. Yeni egzersiz sonrasına eklenir.',
|
||||
'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.',
|
||||
|
||||
@@ -93,6 +93,12 @@ export default {
|
||||
'Weight ({0})': '重量({0})',
|
||||
'Add to routine': '加入训练日',
|
||||
'Remove exercise': '移除动作',
|
||||
'Swap exercise': '更换动作',
|
||||
'Swap exercise?': '要更换动作吗?',
|
||||
'Logged sets stay with the original exercise. Choose where the replacement belongs.': '已记录的组数会保留在原动作上。请选择替换动作的位置。',
|
||||
'Keep replacement in this group': '将替换动作保留在此组',
|
||||
'Insert after this group': '插入到此组之后',
|
||||
'Logged sets stay with the original exercise. The replacement will be inserted afterward.': '已记录的组数会保留在原动作上。替换动作将插入其后。',
|
||||
'Remove {0}?': '移除 {0}?',
|
||||
'The sets you logged for this exercise in this session will be lost.': '本次训练中为该动作记录的组数将丢失。',
|
||||
'This removes the exercise from your current session.': '这会从当前训练中移除该动作。',
|
||||
|
||||
@@ -25,6 +25,7 @@ import { MOBILE, shareExport } from './lib/mobile.js'
|
||||
import { buildCompletedWorkout } from './lib/finish-workout.js'
|
||||
import { isWarmupRow } from './lib/workout-model.js'
|
||||
import { nextUnfinishedUnit } from './lib/supersetFlow.js'
|
||||
import { swapActiveExercise } from './lib/active-exercise-swap.js'
|
||||
|
||||
const S = () => useStore.getState().S
|
||||
const update = (...a) => useStore.getState().update(...a)
|
||||
@@ -709,6 +710,60 @@ function ExercisePicker({ onPick, close }) {
|
||||
}
|
||||
export const exercisePicker = onPick => ui().openSheet(close => <ExercisePicker onPick={onPick} close={close} />)
|
||||
|
||||
/** Start a safe swap for one exact active-workout occurrence. */
|
||||
export function swapActiveWorkoutExercise(index) {
|
||||
const active = S().active
|
||||
if (!active?.entries?.[index]) return
|
||||
|
||||
exercisePicker(ex => exConfigSheet(ex, null, cfg => {
|
||||
const full = { ...cfg, id: ex.id }
|
||||
const replacement = {
|
||||
id: ex.id,
|
||||
target: { ...cfg },
|
||||
plan: null,
|
||||
sets: applyIntensifierPlan(buildSets({ ...S(), workouts: [] }, full, {
|
||||
step: defaultIncrement(ex.id, S().unit)
|
||||
}), full)
|
||||
}
|
||||
const current = S().active?.entries?.[index]
|
||||
if (!current) return
|
||||
|
||||
const apply = options => {
|
||||
// A timed callback closes over entry/set indexes. Invalidate it, and the current rest,
|
||||
// before the selected occurrence can be replaced or a new entry shifts those indexes.
|
||||
ui().stopWork()
|
||||
ui().stopRest()
|
||||
update(state => { swapActiveExercise(state.active, index, replacement, options) }, true)
|
||||
}
|
||||
const logged = (current.sets || []).some(set => set.done === true)
|
||||
if (!logged) { apply(); return }
|
||||
|
||||
if (current.sg) {
|
||||
ui().openSheet(close => <>
|
||||
<h3>{t('Swap exercise?')}</h3>
|
||||
<div className="muted small" style={{ marginBottom: 12 }}>
|
||||
{t('Logged sets stay with the original exercise. Choose where the replacement belongs.')}
|
||||
</div>
|
||||
<Button variant="primary" onClick={() => { close(); apply({ loggedConfirmed: true, groupDisposition: 'keep' }) }}>
|
||||
{t('Keep replacement in this group')}
|
||||
</Button>
|
||||
<div style={{ height: 8 }} />
|
||||
<Button variant="ghost" onClick={() => { close(); apply({ loggedConfirmed: true, groupDisposition: 'detach' }) }}>
|
||||
{t('Insert after this group')}
|
||||
</Button>
|
||||
</>)
|
||||
return
|
||||
}
|
||||
|
||||
confirmSheet({
|
||||
title: t('Swap exercise?'),
|
||||
message: t('Logged sets stay with the original exercise. The replacement will be inserted afterward.'),
|
||||
confirmText: t('Continue'),
|
||||
onConfirm: () => apply({ loggedConfirmed: true })
|
||||
})
|
||||
}))
|
||||
}
|
||||
|
||||
/* ============================ equipment profiles ============================ */
|
||||
// Create or edit one profile ("Home", "Gym", ...): a name plus a checklist of what you have.
|
||||
function EquipmentProfileSheet({ profile, close }) {
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
// @vitest-environment happy-dom
|
||||
import { act } from 'react'
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { swapActiveWorkoutExercise } from './sheets.jsx'
|
||||
import { EXDB } from './lib/exercises.js'
|
||||
import { DEF, useStore } from './store/useStore.js'
|
||||
import { useUI } from './store/useUI.js'
|
||||
|
||||
const clone = value => JSON.parse(JSON.stringify(value))
|
||||
const ids = EXDB.slice(0, 3).map(exercise => exercise.id)
|
||||
|
||||
function entry(id, done = false) {
|
||||
return {
|
||||
id,
|
||||
target: { mode: 'reps', sets: 1, reps: 5, weight: 40 },
|
||||
sets: [{ w: 40, r: 5, done }]
|
||||
}
|
||||
}
|
||||
|
||||
function installActive() {
|
||||
const S = clone(DEF)
|
||||
S.active = {
|
||||
id: 'swap-test', d: '2026-08-27', start: Date.now(), routineId: null,
|
||||
name: 'Swap test', bw: null, cur: 1,
|
||||
entries: [entry(ids[0]), entry(ids[0]), entry(ids[1])]
|
||||
}
|
||||
useStore.setState({ S, user: null })
|
||||
}
|
||||
|
||||
function submitSwap(index, exercise, config) {
|
||||
swapActiveWorkoutExercise(index)
|
||||
const picker = useUI.getState().sheets.at(-1)
|
||||
const pickerView = picker.render(picker.close)
|
||||
act(() => pickerView.props.onPick(exercise))
|
||||
const configSheet = useUI.getState().sheets.at(-1)
|
||||
const configView = configSheet.render(configSheet.close)
|
||||
act(() => configView.props.onSave(config))
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers()
|
||||
localStorage.clear()
|
||||
useUI.getState().stopRest()
|
||||
useUI.getState().stopWork()
|
||||
useUI.setState({ sheets: [], timer: null, work: null })
|
||||
installActive()
|
||||
})
|
||||
|
||||
describe('active exercise swap sheet flow', () => {
|
||||
it('invalidates a timed callback and replaces only the selected duplicate', () => {
|
||||
const callback = vi.fn()
|
||||
useUI.getState().startWork(5, 'Hold', callback)
|
||||
|
||||
submitSwap(1, EXDB[2], { mode: 'reps', sets: 2, reps: 8, weight: 30, note: 'New target' })
|
||||
vi.advanceTimersByTime(10_000)
|
||||
|
||||
const active = useStore.getState().S.active
|
||||
expect(useUI.getState().work).toBeNull()
|
||||
expect(callback).not.toHaveBeenCalled()
|
||||
expect(active.entries.map(value => value.id)).toEqual([ids[0], ids[2], ids[1]])
|
||||
expect(active.entries[1].target).toMatchObject({ mode: 'reps', sets: 2, reps: 8, weight: 30, note: 'New target' })
|
||||
expect(active.entries[0].sets).toEqual([{ w: 40, r: 5, done: false }])
|
||||
expect(active.entries[2].sets).toEqual([{ w: 40, r: 5, done: false }])
|
||||
expect(active.cur).toBe(1)
|
||||
})
|
||||
})
|
||||
|
||||
describe('active exercise swap locale coverage', () => {
|
||||
const required = [
|
||||
'Swap exercise',
|
||||
'Swap exercise?',
|
||||
'Logged sets stay with the original exercise. Choose where the replacement belongs.',
|
||||
'Keep replacement in this group',
|
||||
'Insert after this group',
|
||||
'Logged sets stay with the original exercise. The replacement will be inserted afterward.'
|
||||
]
|
||||
const packs = import.meta.glob('./locales/*.js', { eager: true, import: 'default' })
|
||||
|
||||
it('defines every new prompt in all twelve locale packs', () => {
|
||||
expect(Object.keys(packs)).toHaveLength(12)
|
||||
Object.entries(packs).forEach(([path, pack]) => {
|
||||
required.forEach(key => expect(pack, `${path} is missing ${key}`).toHaveProperty(key))
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -10,7 +10,7 @@ import { t, exerciseNameFor } from '../lib/i18n.js'
|
||||
import { api } from '../lib/api.js'
|
||||
import { insertionIndexAfterCurrentUnit, nextUnfinishedUnit, setProgressHighWater, supersetFlowStep, restAfterSet, restOnRecheck } from '../lib/supersetFlow.js'
|
||||
import Media from '../components/Media.jsx'
|
||||
import { startFlow, exercisePicker, exConfigSheet, exerciseDetailSheet, topWeightSheet, finishWorkout, workoutCompleteSheet, confirmSheet, exerciseNoteSheet, sessionNoteSheet } from '../sheets.jsx'
|
||||
import { startFlow, exercisePicker, exConfigSheet, exerciseDetailSheet, topWeightSheet, finishWorkout, workoutCompleteSheet, confirmSheet, exerciseNoteSheet, sessionNoteSheet, swapActiveWorkoutExercise } from '../sheets.jsx'
|
||||
import Icon from '../components/Icon.jsx'
|
||||
import { Button, Check, NumberField } from '../components/ui.jsx'
|
||||
import { nextPrescription, applyPrescription, defaultIncrement } from '../lib/progression.js'
|
||||
@@ -645,6 +645,11 @@ function ActiveWorkout() {
|
||||
disabled={!!work || !canMoveActiveWorkoutUnit(A, cur, 1)} onClick={() => moveCurrentUnit(1)}>{t('Move down')}</Button>
|
||||
</div>
|
||||
<div style={{ height: 6 }} />
|
||||
<div style={{ display: 'flex', justifyContent: 'center' }}>
|
||||
<Button size="sm" icon="shuffle" aria-label={t('Swap exercise')} disabled={!!work}
|
||||
onClick={() => swapActiveWorkoutExercise(cur)}>{t('Swap exercise')}</Button>
|
||||
</div>
|
||||
<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>
|
||||
|
||||
@@ -19,6 +19,7 @@ const mocks = vi.hoisted(() => {
|
||||
exConfigSheet: vi.fn(),
|
||||
toast: vi.fn(),
|
||||
scrollCalls: [],
|
||||
swapActiveWorkoutExercise: vi.fn(),
|
||||
}
|
||||
state.stopRest = vi.fn(() => { state.timer = null })
|
||||
state.stopWork = vi.fn(() => { state.work = null })
|
||||
@@ -64,6 +65,7 @@ vi.mock('../sheets.jsx', () => ({
|
||||
finishWorkout: vi.fn(),
|
||||
workoutCompleteSheet: mocks.workoutCompleteSheet,
|
||||
confirmSheet: mocks.confirmSheet,
|
||||
swapActiveWorkoutExercise: mocks.swapActiveWorkoutExercise,
|
||||
// Both note sheets belong here even though the tests never open one: Workout.jsx reads
|
||||
// sessionNoteSheet during render, so a missing export is a render crash, not a no-op.
|
||||
exerciseNoteSheet: vi.fn(),
|
||||
@@ -543,7 +545,7 @@ describe('active workout whole-unit move controls', () => {
|
||||
expect(mocks.S.active.entries[1].sets).toEqual([{ w: 77.5, r: 6, done: true, rir: 2 }])
|
||||
expect(mocks.S.active.cur).toBe(1)
|
||||
expect(mocks.stopWork).toHaveBeenCalledOnce()
|
||||
expect(mocks.stopRest).toHaveBeenCalledOnce()
|
||||
expect(mocks.stopRest).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('moves the selected contiguous group as one unit without changing its metadata', async () => {
|
||||
@@ -575,3 +577,16 @@ describe('active workout whole-unit move controls', () => {
|
||||
expect(action('Move down')?.disabled).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
describe('active exercise swap control', () => {
|
||||
it('opens the swap flow for the selected duplicate occurrence', async () => {
|
||||
await mount([exercise('bench', [false]), exercise('bench', [false]), exercise('row', [false])], 1)
|
||||
|
||||
const swap = container.querySelector('button[aria-label="Swap exercise"]')
|
||||
expect(swap).toBeTruthy()
|
||||
await act(async () => { swap.dispatchEvent(new dom.Event('click', { bubbles: true })) })
|
||||
|
||||
expect(mocks.swapActiveWorkoutExercise).toHaveBeenCalledOnce()
|
||||
expect(mocks.swapActiveWorkoutExercise).toHaveBeenCalledWith(1)
|
||||
})
|
||||
})
|
||||
Reference in new issue
Block a user