diff --git a/frontend/src/lib/active-exercise-swap.js b/frontend/src/lib/active-exercise-swap.js new file mode 100644 index 0000000..114dbb9 --- /dev/null +++ b/frontend/src/lib/active-exercise-swap.js @@ -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 } +} diff --git a/frontend/src/lib/active-exercise-swap.test.js b/frontend/src/lib/active-exercise-swap.test.js new file mode 100644 index 0000000..c3f7eee --- /dev/null +++ b/frontend/src/lib/active-exercise-swap.test.js @@ -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) + }) +}) diff --git a/frontend/src/lib/pt-br-locale.test.js b/frontend/src/lib/pt-br-locale.test.js index 91a4a63..aaad9fa 100644 --- a/frontend/src/lib/pt-br-locale.test.js +++ b/frontend/src/lib/pt-br-locale.test.js @@ -27,7 +27,7 @@ describe('Brazilian Portuguese locale', () => { .sort(byCodeUnit) const fingerprint = createHash('sha256').update(JSON.stringify(inherited)).digest('hex') - expect(Object.keys(PT_BR_OVERRIDES)).toHaveLength(291) + expect(Object.keys(PT_BR_OVERRIDES)).toHaveLength(297) expect(inherited).toHaveLength(449) // If this fails, review the changed keys and wording before accepting a new hash. From // frontend/: node scripts/pt-br-inheritance-fingerprint.mjs --list diff --git a/frontend/src/locales/de.js b/frontend/src/locales/de.js index 8c91155..8dfbe55 100644 --- a/frontend/src/locales/de.js +++ b/frontend/src/locales/de.js @@ -95,6 +95,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.', diff --git a/frontend/src/locales/es.js b/frontend/src/locales/es.js index b1ea117..c177781 100644 --- a/frontend/src/locales/es.js +++ b/frontend/src/locales/es.js @@ -91,6 +91,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.', diff --git a/frontend/src/locales/fr.js b/frontend/src/locales/fr.js index 387bf25..18868a5 100644 --- a/frontend/src/locales/fr.js +++ b/frontend/src/locales/fr.js @@ -91,6 +91,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.', diff --git a/frontend/src/locales/hi.js b/frontend/src/locales/hi.js index 09038df..3b0135c 100644 --- a/frontend/src/locales/hi.js +++ b/frontend/src/locales/hi.js @@ -91,6 +91,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.': 'यह व्यायाम आपके मौजूदा सत्र से हट जाएगा।', diff --git a/frontend/src/locales/it.js b/frontend/src/locales/it.js index 1c53c34..b9b57a3 100644 --- a/frontend/src/locales/it.js +++ b/frontend/src/locales/it.js @@ -91,6 +91,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.', diff --git a/frontend/src/locales/ko.js b/frontend/src/locales/ko.js index 170f6d3..13743fd 100644 --- a/frontend/src/locales/ko.js +++ b/frontend/src/locales/ko.js @@ -91,6 +91,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.': '현재 세션에서 이 운동을 제거합니다.', diff --git a/frontend/src/locales/pl.js b/frontend/src/locales/pl.js index b914fbc..bf7a2f4 100644 --- a/frontend/src/locales/pl.js +++ b/frontend/src/locales/pl.js @@ -91,6 +91,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.', diff --git a/frontend/src/locales/pt-BR.js b/frontend/src/locales/pt-BR.js index 11022ba..68f328f 100644 --- a/frontend/src/locales/pt-BR.js +++ b/frontend/src/locales/pt-BR.js @@ -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', diff --git a/frontend/src/locales/pt.js b/frontend/src/locales/pt.js index d14ccb1..547b9b8 100644 --- a/frontend/src/locales/pt.js +++ b/frontend/src/locales/pt.js @@ -91,6 +91,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.', diff --git a/frontend/src/locales/ru.js b/frontend/src/locales/ru.js index 1e260d1..7b80924 100644 --- a/frontend/src/locales/ru.js +++ b/frontend/src/locales/ru.js @@ -91,6 +91,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.': 'Упражнение будет удалено из текущей сессии.', diff --git a/frontend/src/locales/tr.js b/frontend/src/locales/tr.js index 79b3125..623c53d 100644 --- a/frontend/src/locales/tr.js +++ b/frontend/src/locales/tr.js @@ -91,6 +91,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.', diff --git a/frontend/src/locales/zh.js b/frontend/src/locales/zh.js index 533434d..3529a64 100644 --- a/frontend/src/locales/zh.js +++ b/frontend/src/locales/zh.js @@ -91,6 +91,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.': '这会从当前训练中移除该动作。', diff --git a/frontend/src/sheets.jsx b/frontend/src/sheets.jsx index 00ad49f..feff6e1 100644 --- a/frontend/src/sheets.jsx +++ b/frontend/src/sheets.jsx @@ -23,6 +23,7 @@ import { nextPrescription, applyPrescription, policyFor, defaultIncrement, POLIC import { MOBILE, shareExport } from './lib/mobile.js' import { buildCompletedWorkout } from './lib/finish-workout.js' import { isWarmupRow } from './lib/workout-model.js' +import { swapActiveExercise } from './lib/active-exercise-swap.js' const S = () => useStore.getState().S const update = (...a) => useStore.getState().update(...a) @@ -499,6 +500,60 @@ function ExercisePicker({ onPick, close }) { } export const exercisePicker = onPick => ui().openSheet(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 => <> +

{t('Swap exercise?')}

+
+ {t('Logged sets stay with the original exercise. Choose where the replacement belongs.')} +
+ +
+ + ) + 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 }) { diff --git a/frontend/src/sheets.swap.test.jsx b/frontend/src/sheets.swap.test.jsx new file mode 100644 index 0000000..8a5f431 --- /dev/null +++ b/frontend/src/sheets.swap.test.jsx @@ -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)) + }) + }) +}) diff --git a/frontend/src/views/Workout.jsx b/frontend/src/views/Workout.jsx index d0a6279..fe21acb 100644 --- a/frontend/src/views/Workout.jsx +++ b/frontend/src/views/Workout.jsx @@ -10,7 +10,7 @@ import { t, exerciseNameFor } from '../lib/i18n.js' import { api } from '../lib/api.js' import { 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' @@ -526,6 +526,11 @@ function ActiveWorkout() { }), null, routine, seed) })} icon="plus">{t('Add exercise')} {A.entries.length > 0 && <> +
+
+ +
diff --git a/frontend/src/views/Workout.test.jsx b/frontend/src/views/Workout.test.jsx index 0564b8a..dcd24f2 100644 --- a/frontend/src/views/Workout.test.jsx +++ b/frontend/src/views/Workout.test.jsx @@ -10,6 +10,7 @@ const mocks = vi.hoisted(() => { startRest: vi.fn(), stopRest: vi.fn(), topWeightSheet: vi.fn(), + swapActiveWorkoutExercise: vi.fn(), } state.storeSnapshot = () => ({ S: state.S, @@ -46,6 +47,7 @@ vi.mock('../sheets.jsx', () => ({ finishWorkout: vi.fn(), workoutCompleteSheet: vi.fn(), confirmSheet: vi.fn(), + 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(), @@ -187,3 +189,16 @@ describe('superset flow survives an exercise being removed mid-session', () => { expect(mocks.startRest).toHaveBeenCalledWith(90) }) }) + +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) + }) +})