Skip to content

Open-source gym & body-weight tracker, now in the App Store (iPhone + Apple Watch) and as an Android APK. Plan routines, log workouts, see which muscles are trained, import from Strong/Hevy/FitNotes. Self-host it or use it on the phone alone.

Workout: save an exercise's warm-ups, rest and note back to its routine

Francisco Javier Favela Najera6f6e5f7e9b67
diff --git a/frontend/src/lib/routines.js b/frontend/src/lib/routines.js
index d2179d75c..b820fc0e5 100644
--- a/frontend/src/lib/routines.js
+++ b/frontend/src/lib/routines.js
@@ -1,7 +1,8 @@
import { uid } from './format.js'
-import { defaultConfig, isBw, modeOf } from './history.js'
+import { defaultConfig, isBw, modeOf, MAX_PLANNED_WARMUPS, NOTE_MAX } from './history.js'
import { isAssisted, isBodyweightEq, isCardio } from './exercises.js'
import { sessionsFor } from './progression.js'
+import { isWarmupRow } from './workout-model.js'
/**
* Create a deep copy of a routine with a new id and a "(Copy)" suffix.
@@ -99,3 +100,80 @@ export function replaceSlotExercise(slot, id, S, rid) {
if (last) out.weight = last.planned?.weight ?? last.weight ?? 0
return out
}
+
+/**
+ * Where a running session's exercise sits in the routine it was built from, as an index into
+ * `routine.ex`, or -1 when it does not sit anywhere: a freestyle exercise, one added from
+ * another routine, one swapped for something the routine never had.
+ *
+ * A session entry keeps the routine it came from (`rid`), and a combined day can hold the same
+ * exercise twice, so the match is by position among the twins: the second bench press of that
+ * routine in the session is the routine's second bench press.
+ */
+export function routineSlotIndex(routine, entries, idx) {
+ const entry = entries?.[idx]
+ if (!entry || !routine || !Array.isArray(routine.ex) || entry.rid !== routine.id) return -1
+ const twinsBefore = entries.slice(0, idx).filter(e => e && e.rid === routine.id && e.id === entry.id).length
+ let seen = 0
+ for (let i = 0; i < routine.ex.length; i++) {
+ if (routine.ex[i]?.id === entry.id && seen++ === twinsBefore) return i
+ }
+ return -1
+}
+
+// What the exercise config sheet writes into a routine slot that a session can also change: the
+// warm-ups added or removed on the exercise, and the rest and the note its settings sheet edits.
+// A key that does not apply to the exercise is left out, so it can never overwrite the slot's own:
+// a cardio interval has no warm-ups, and rest-pause builds its own warm-up row (ExConfig hides
+// the stepper for both).
+function setupOf(entry) {
+ const target = entry.target || {}
+ const out = {
+ restSec: Math.max(0, Math.round(Number(target.restSec)) || 0),
+ note: String(target.note || '').trim().slice(0, NOTE_MAX),
+ }
+ if (!isCardio(entry.id) && target.intensifier?.type !== 'restpause') {
+ out.warmupSets = Math.min(MAX_PLANNED_WARMUPS, (entry.sets || []).filter(isWarmupRow).length)
+ }
+ return out
+}
+
+/**
+ * What a running session's exercise would change in its routine, or null when there is nothing
+ * to change: the exercise has no routine slot, or the slot already says what the session did.
+ * `changes` are `{ key, from, to }` for `warmupSets`, `restSec` and `note`.
+ *
+ * Warm-ups added in a session used to last that session only, and so did anything edited on the
+ * exercise's settings sheet from inside it (Progression settings opens the same sheet the routine
+ * editor does). Sets, reps and weight are not offered: the progression engine moves those every
+ * session, and the routine is the plan it reads them against.
+ */
+export function routineChangesFromEntry(routine, entries, idx) {
+ const at = routineSlotIndex(routine, entries, idx)
+ if (at < 0) return null
+ const slot = routine.ex[at]
+ const now = setupOf(entries[idx])
+ const changes = []
+ for (const key of ['warmupSets', 'restSec', 'note']) {
+ if (now[key] === undefined) continue
+ const from = key === 'note' ? String(slot.note || '').trim() : Math.max(0, Math.round(Number(slot[key])) || 0)
+ if (from !== now[key]) changes.push({ key, from, to: now[key] })
+ }
+ return changes.length ? { at, changes } : null
+}
+
+/**
+ * Write those changes into the routine, in place on a store draft, the way the config sheet
+ * does: a key is only stored when it has a value, so "no warm-ups" removes it instead of leaving
+ * a 0 that no plan file ever had. Returns the changes it applied, or null.
+ */
+export function updateRoutineFromEntry(routine, entries, idx) {
+ const found = routineChangesFromEntry(routine, entries, idx)
+ if (!found) return null
+ const slot = routine.ex[found.at]
+ for (const { key, to } of found.changes) {
+ if (to) slot[key] = to
+ else delete slot[key]
+ }
+ return found.changes
+}
diff --git a/frontend/src/lib/routines.update.test.js b/frontend/src/lib/routines.update.test.js
new file mode 100644
index 000000000..31e425732
--- /dev/null
+++ b/frontend/src/lib/routines.update.test.js
@@ -0,0 +1,126 @@
+// Update a routine from a running session: the warm-ups added in the workout, and the rest and
+// note edited on the exercise's settings sheet from inside it, can be written back to the slot.
+import { describe, it, expect } from 'vitest'
+import { routineSlotIndex, routineChangesFromEntry, updateRoutineFromEntry } from './routines.js'
+import { MAX_PLANNED_WARMUPS } from './history.js'
+
+const BENCH = '0025' // barbell bench press
+const ROW = '0027' // barbell bent over row
+const BIKE = '2138' // stationary bike, cardio
+
+const work = n => Array.from({ length: n }, () => ({ w: 60, r: 5, done: false }))
+const warm = n => Array.from({ length: n }, () => ({ w: 30, r: 5, done: false, phase: 'warmup' }))
+const entry = (id, sets, target = {}, rid = 'A') => ({ id, rid, sets, target: { id, ...target } })
+
+describe('routineSlotIndex', () => {
+ const routine = { id: 'A', ex: [{ id: BENCH }, { id: ROW }, { id: BENCH }] }
+
+ it('finds the slot of the exercise in its own routine', () => {
+ const entries = [entry(ROW, work(3))]
+ expect(routineSlotIndex(routine, entries, 0)).toBe(1)
+ })
+
+ it('pairs twins by position: the second bench of the session is the second bench of the routine', () => {
+ const entries = [entry(BENCH, work(3)), entry(ROW, work(3)), entry(BENCH, work(3))]
+ expect(routineSlotIndex(routine, entries, 0)).toBe(0)
+ expect(routineSlotIndex(routine, entries, 2)).toBe(2)
+ })
+
+ it('does not count twins that came from another routine', () => {
+ const entries = [entry(BENCH, work(3), {}, 'B'), entry(BENCH, work(3))]
+ expect(routineSlotIndex(routine, entries, 1)).toBe(0)
+ })
+
+ it('is -1 for an exercise the routine never had, another routine\'s, or a freestyle one', () => {
+ expect(routineSlotIndex(routine, [entry(BIKE, work(1))], 0)).toBe(-1)
+ expect(routineSlotIndex(routine, [entry(BENCH, work(3), {}, 'B')], 0)).toBe(-1)
+ expect(routineSlotIndex(routine, [{ id: BENCH, sets: work(3), target: {} }], 0)).toBe(-1)
+ expect(routineSlotIndex(routine, [entry(BENCH, work(3))], 5)).toBe(-1)
+ expect(routineSlotIndex(null, [entry(BENCH, work(3))], 0)).toBe(-1)
+ })
+})
+
+describe('routineChangesFromEntry', () => {
+ const routineWith = slot => ({ id: 'A', ex: [{ id: BENCH, sets: 3, mode: 'reps', reps: 5, weight: 60, ...slot }] })
+
+ it('offers the warm-ups added during the session', () => {
+ const entries = [entry(BENCH, [...warm(2), ...work(3)], { warmupSets: 1 })]
+ expect(routineChangesFromEntry(routineWith({ warmupSets: 1 }), entries, 0))
+ .toEqual({ at: 0, changes: [{ key: 'warmupSets', from: 1, to: 2 }] })
+ })
+
+ it('reads a slot that never planned warm-ups as 0', () => {
+ const entries = [entry(BENCH, [...warm(1), ...work(3)])]
+ expect(routineChangesFromEntry(routineWith({}), entries, 0).changes).toEqual([{ key: 'warmupSets', from: 0, to: 1 }])
+ })
+
+ it('offers the rest and the note edited on the settings sheet mid-session', () => {
+ const entries = [entry(BENCH, work(3), { restSec: 150, note: ' pause on the chest ' })]
+ expect(routineChangesFromEntry(routineWith({ restSec: 90 }), entries, 0).changes).toEqual([
+ { key: 'restSec', from: 90, to: 150 },
+ { key: 'note', from: '', to: 'pause on the chest' },
+ ])
+ })
+
+ it('offers removing warm-ups the session left out', () => {
+ const entries = [entry(BENCH, work(3), { warmupSets: 2 })]
+ expect(routineChangesFromEntry(routineWith({ warmupSets: 2 }), entries, 0).changes)
+ .toEqual([{ key: 'warmupSets', from: 2, to: 0 }])
+ })
+
+ it('caps warm-ups at what the settings sheet allows', () => {
+ const entries = [entry(BENCH, [...warm(MAX_PLANNED_WARMUPS + 2), ...work(3)])]
+ expect(routineChangesFromEntry(routineWith({}), entries, 0).changes[0].to).toBe(MAX_PLANNED_WARMUPS)
+ })
+
+ it('is null when the slot already says what the session did', () => {
+ const entries = [entry(BENCH, [...warm(2), ...work(3)], { warmupSets: 2, restSec: 120, note: 'pause' })]
+ expect(routineChangesFromEntry(routineWith({ warmupSets: 2, restSec: 120, note: 'pause' }), entries, 0)).toBeNull()
+ })
+
+ it('is null for an exercise with no slot', () => {
+ expect(routineChangesFromEntry(routineWith({}), [entry(ROW, [...warm(1), ...work(3)])], 0)).toBeNull()
+ })
+
+ it('never offers sets, reps or weight — the progression engine moves those every session', () => {
+ const entries = [entry(BENCH, work(5), { sets: 5, reps: 8, weight: 100 })]
+ expect(routineChangesFromEntry(routineWith({}), entries, 0)).toBeNull()
+ })
+
+ it('leaves warm-ups alone on cardio and rest-pause, which the settings sheet does not offer them for', () => {
+ const bikeRoutine = { id: 'A', ex: [{ id: BIKE, sets: 1, min: 20, speed: 8, warmupSets: 2 }] }
+ expect(routineChangesFromEntry(bikeRoutine, [entry(BIKE, work(1))], 0)).toBeNull()
+ const rp = [entry(BENCH, [...warm(1), ...work(1)], { intensifier: { type: 'restpause', totalReps: 12, restSec: 15 } })]
+ expect(routineChangesFromEntry(routineWith({}), rp, 0)).toBeNull()
+ })
+})
+
+describe('updateRoutineFromEntry', () => {
+ it('writes the changes into the slot and nothing else', () => {
+ const routine = { id: 'A', ex: [{ id: BENCH, sg: 'g', sets: 3, mode: 'reps', reps: 5, weight: 60, prog: 'linear' }] }
+ const entries = [entry(BENCH, [...warm(2), ...work(3)], { restSec: 120, note: 'pause' })]
+ const applied = updateRoutineFromEntry(routine, entries, 0)
+ expect(applied.map(c => c.key)).toEqual(['warmupSets', 'restSec', 'note'])
+ expect(routine.ex[0]).toEqual({ id: BENCH, sg: 'g', sets: 3, mode: 'reps', reps: 5, weight: 60, prog: 'linear', warmupSets: 2, restSec: 120, note: 'pause' })
+ })
+
+ it('removes a key that goes back to nothing, as the settings sheet does, instead of storing 0', () => {
+ const routine = { id: 'A', ex: [{ id: BENCH, sets: 3, warmupSets: 2, restSec: 90, note: 'x' }] }
+ updateRoutineFromEntry(routine, [entry(BENCH, work(3), { restSec: 0, note: '' })], 0)
+ expect(routine.ex[0]).toEqual({ id: BENCH, sets: 3 })
+ expect('warmupSets' in routine.ex[0]).toBe(false)
+ })
+
+ it('changes only the twin the session entry stands for', () => {
+ const routine = { id: 'A', ex: [{ id: BENCH, sets: 3 }, { id: ROW, sets: 3 }, { id: BENCH, sets: 3 }] }
+ const entries = [entry(BENCH, work(3)), entry(ROW, work(3)), entry(BENCH, [...warm(1), ...work(3)])]
+ updateRoutineFromEntry(routine, entries, 2)
+ expect(routine.ex.map(e => e.warmupSets)).toEqual([undefined, undefined, 1])
+ })
+
+ it('returns null and leaves the routine alone when there is nothing to update', () => {
+ const routine = { id: 'A', ex: [{ id: BENCH, sets: 3 }] }
+ expect(updateRoutineFromEntry(routine, [entry(BENCH, work(3))], 0)).toBeNull()
+ expect(routine.ex[0]).toEqual({ id: BENCH, sets: 3 })
+ })
+})
diff --git a/frontend/src/locales/ar.js b/frontend/src/locales/ar.js
index 07697206c..71528337d 100644
--- a/frontend/src/locales/ar.js
+++ b/frontend/src/locales/ar.js
@@ -1716,4 +1716,9 @@ export default {
'Teal': 'أزرق مخضر',
'Yellow': 'أصفر',
'Enter how long it took — at least 1 minute.': 'أدخل المدة التي استغرقها — دقيقة واحدة على الأقل.',
+ // --- update a routine from a running workout ---
+ 'Update routine': 'تحديث الروتين',
+ 'Update “{0}”?': 'تحديث «{0}»؟',
+ 'Copy this exercise’s warm-up sets, rest and note from this session into the routine. Your workout history is kept.': 'انسخ مجموعات الإحماء والراحة والملاحظة الخاصة بهذا التمرين من هذه الجلسة إلى الروتين. يبقى سجل تمارينك كما هو.',
+ 'Routine updated': 'تم تحديث الروتين',
}
diff --git a/frontend/src/locales/de.js b/frontend/src/locales/de.js
index 663a5a5bb..e072ddfce 100644
--- a/frontend/src/locales/de.js
+++ b/frontend/src/locales/de.js
@@ -1683,4 +1683,9 @@ export default {
'Teal': 'Türkis',
'Yellow': 'Gelb',
'Enter how long it took — at least 1 minute.': 'Gib ein, wie lange es gedauert hat — mindestens 1 Minute.',
+ // --- update a routine from a running workout ---
+ 'Update routine': 'Routine aktualisieren',
+ 'Update “{0}”?': 'Routine „{0}“ aktualisieren?',
+ 'Copy this exercise’s warm-up sets, rest and note from this session into the routine. Your workout history is kept.': 'Übernimmt die Aufwärmsätze, die Pause und die Notiz dieser Übung aus dieser Einheit in die Routine. Dein Trainingsverlauf bleibt erhalten.',
+ 'Routine updated': 'Routine aktualisiert',
}
diff --git a/frontend/src/locales/es.js b/frontend/src/locales/es.js
index 8e1d9aa99..94fd6d058 100644
--- a/frontend/src/locales/es.js
+++ b/frontend/src/locales/es.js
@@ -1663,4 +1663,9 @@ export default {
'Teal': 'Turquesa',
'Yellow': 'Amarillo',
'Enter how long it took — at least 1 minute.': 'Indica cuánto duró — al menos 1 minuto.',
+ // --- update a routine from a running workout ---
+ 'Update routine': 'Actualizar rutina',
+ 'Update “{0}”?': '¿Actualizar «{0}»?',
+ 'Copy this exercise’s warm-up sets, rest and note from this session into the routine. Your workout history is kept.': 'Copia a la rutina las series de calentamiento, el descanso y la nota de este ejercicio de esta sesión. Tu historial de entrenamientos se conserva.',
+ 'Routine updated': 'Rutina actualizada',
}
diff --git a/frontend/src/locales/fr.js b/frontend/src/locales/fr.js
index ee904194c..5092cce98 100644
--- a/frontend/src/locales/fr.js
+++ b/frontend/src/locales/fr.js
@@ -1663,4 +1663,9 @@ export default {
'Teal': 'Turquoise',
'Yellow': 'Jaune',
'Enter how long it took — at least 1 minute.': 'Indique combien de temps ça a duré — au moins 1 minute.',
+ // --- update a routine from a running workout ---
+ 'Update routine': 'Mettre à jour la routine',
+ 'Update “{0}”?': 'Mettre à jour la routine « {0} » ?',
+ 'Copy this exercise’s warm-up sets, rest and note from this session into the routine. Your workout history is kept.': 'Copie dans la routine les séries d’échauffement, le repos et la note de cet exercice pour cette séance. Ton historique d’entraînement est conservé.',
+ 'Routine updated': 'Routine mise à jour',
}
diff --git a/frontend/src/locales/hi.js b/frontend/src/locales/hi.js
index ccb0ca2aa..7313de639 100644
--- a/frontend/src/locales/hi.js
+++ b/frontend/src/locales/hi.js
@@ -1663,4 +1663,9 @@ export default {
'Teal': 'फ़िरोज़ी',
'Yellow': 'पीला',
'Enter how long it took — at least 1 minute.': 'बताएँ कि इसमें कितना समय लगा — कम से कम 1 मिनट।',
+ // --- update a routine from a running workout ---
+ 'Update routine': 'रूटीन अपडेट करें',
+ 'Update “{0}”?': 'रूटीन “{0}” अपडेट करें?',
+ 'Copy this exercise’s warm-up sets, rest and note from this session into the routine. Your workout history is kept.': 'इस सत्र से इस एक्सरसाइज़ के वार्म-अप सेट, आराम और नोट को रूटीन में कॉपी करें। आपका वर्कआउट इतिहास सुरक्षित रहता है।',
+ 'Routine updated': 'रूटीन अपडेट हो गया',
}
diff --git a/frontend/src/locales/hu.js b/frontend/src/locales/hu.js
index 61b151edc..2f1da4a9d 100644
--- a/frontend/src/locales/hu.js
+++ b/frontend/src/locales/hu.js
@@ -1666,4 +1666,9 @@ export default {
'Teal': 'Türkiz',
'Yellow': 'Sárga',
'Enter how long it took — at least 1 minute.': 'Add meg, meddig tartott — legalább 1 perc.',
+ // --- update a routine from a running workout ---
+ 'Update routine': 'Rutin frissítése',
+ 'Update “{0}”?': 'Frissíted a(z) „{0}” rutint?',
+ 'Copy this exercise’s warm-up sets, rest and note from this session into the routine. Your workout history is kept.': 'A gyakorlat bemelegítő sorozatait, pihenőjét és jegyzetét átmásolja ebből az edzésből a rutinba. Az edzéselőzményeid megmaradnak.',
+ 'Routine updated': 'Rutin frissítve',
}
diff --git a/frontend/src/locales/it.js b/frontend/src/locales/it.js
index 48e5dd34d..9228f4975 100644
--- a/frontend/src/locales/it.js
+++ b/frontend/src/locales/it.js
@@ -1663,4 +1663,9 @@ export default {
'Teal': 'Turchese',
'Yellow': 'Giallo',
'Enter how long it took — at least 1 minute.': 'Inserisci quanto è durato — almeno 1 minuto.',
+ // --- update a routine from a running workout ---
+ 'Update routine': 'Aggiorna la routine',
+ 'Update “{0}”?': 'Aggiornare la routine «{0}»?',
+ 'Copy this exercise’s warm-up sets, rest and note from this session into the routine. Your workout history is kept.': 'Copia nella routine le serie di riscaldamento, il recupero e la nota di questo esercizio da questa sessione. Il tuo storico degli allenamenti resta intatto.',
+ 'Routine updated': 'Routine aggiornata',
}
diff --git a/frontend/src/locales/ko.js b/frontend/src/locales/ko.js
index 02628fa0a..10d16a110 100644
--- a/frontend/src/locales/ko.js
+++ b/frontend/src/locales/ko.js
@@ -1663,4 +1663,9 @@ export default {
'Teal': '청록',
'Yellow': '노랑',
'Enter how long it took — at least 1 minute.': '걸린 시간을 입력하세요 — 최소 1분.',
+ // --- update a routine from a running workout ---
+ 'Update routine': '루틴 업데이트',
+ 'Update “{0}”?': '“{0}” 루틴을 업데이트할까요?',
+ 'Copy this exercise’s warm-up sets, rest and note from this session into the routine. Your workout history is kept.': '이 세션의 워밍업 세트, 휴식, 메모를 이 운동의 루틴에 복사합니다. 운동 기록은 그대로 유지됩니다.',
+ 'Routine updated': '루틴 업데이트됨',
}
diff --git a/frontend/src/locales/pl.js b/frontend/src/locales/pl.js
index f5910a684..e824b2466 100644
--- a/frontend/src/locales/pl.js
+++ b/frontend/src/locales/pl.js
@@ -1663,4 +1663,9 @@ export default {
'Teal': 'Turkusowy',
'Yellow': 'Żółty',
'Enter how long it took — at least 1 minute.': 'Wpisz, ile to trwało — co najmniej 1 minutę.',
+ // --- update a routine from a running workout ---
+ 'Update routine': 'Zaktualizuj plan',
+ 'Update “{0}”?': 'Zaktualizować plan „{0}”?',
+ 'Copy this exercise’s warm-up sets, rest and note from this session into the routine. Your workout history is kept.': 'Kopiuje serie rozgrzewkowe, przerwę i notatkę tego ćwiczenia z tej sesji do planu. Twoja historia treningów zostaje bez zmian.',
+ 'Routine updated': 'Plan zaktualizowany',
}
diff --git a/frontend/src/locales/pt-BR.js b/frontend/src/locales/pt-BR.js
index 41505d76e..b5bc3b1a1 100644
--- a/frontend/src/locales/pt-BR.js
+++ b/frontend/src/locales/pt-BR.js
@@ -1008,6 +1008,11 @@ export const PT_BR_OVERRIDES = {
'Teal': 'Turquesa',
'Yellow': 'Amarelo',
'Enter how long it took — at least 1 minute.': 'Informe quanto tempo levou — pelo menos 1 minuto.',
+ // --- update a routine from a running workout ---
+ 'Update routine': 'Atualizar rotina',
+ 'Update “{0}”?': 'Atualizar “{0}”?',
+ 'Copy this exercise’s warm-up sets, rest and note from this session into the routine. Your workout history is kept.': 'Copia as séries de aquecimento, o descanso e a anotação deste exercício desta sessão para a rotina. Seu histórico de treinos é mantido.',
+ 'Routine updated': 'Rotina atualizada',
}
export default { ...pt, ...PT_BR_OVERRIDES }
diff --git a/frontend/src/locales/pt.js b/frontend/src/locales/pt.js
index 65dd8ff54..c88078124 100644
--- a/frontend/src/locales/pt.js
+++ b/frontend/src/locales/pt.js
@@ -1663,4 +1663,9 @@ export default {
'Teal': 'Turquesa',
'Yellow': 'Amarelo',
'Enter how long it took — at least 1 minute.': 'Indica quanto tempo demorou — pelo menos 1 minuto.',
+ // --- update a routine from a running workout ---
+ 'Update routine': 'Atualizar rotina',
+ 'Update “{0}”?': 'Atualizar «{0}»?',
+ 'Copy this exercise’s warm-up sets, rest and note from this session into the routine. Your workout history is kept.': 'Copia as séries de aquecimento, o descanso e a nota deste exercício desta sessão para a rotina. O teu histórico de treinos é mantido.',
+ 'Routine updated': 'Rotina atualizada',
}
diff --git a/frontend/src/locales/ru.js b/frontend/src/locales/ru.js
index 2df1568f7..edb304d06 100644
--- a/frontend/src/locales/ru.js
+++ b/frontend/src/locales/ru.js
@@ -1663,4 +1663,9 @@ export default {
'Teal': 'Бирюзовый',
'Yellow': 'Жёлтый',
'Enter how long it took — at least 1 minute.': 'Укажите, сколько это длилось — не меньше 1 минуты.',
+ // --- update a routine from a running workout ---
+ 'Update routine': 'Обновить программу',
+ 'Update “{0}”?': 'Обновить программу «{0}»?',
+ 'Copy this exercise’s warm-up sets, rest and note from this session into the routine. Your workout history is kept.': 'Копирует разминочные подходы, отдых и заметку этого упражнения из этой тренировки в программу. История тренировок сохраняется.',
+ 'Routine updated': 'Программа обновлена',
}
diff --git a/frontend/src/locales/th.js b/frontend/src/locales/th.js
index 3604d80fa..6cfa1ddc3 100644
--- a/frontend/src/locales/th.js
+++ b/frontend/src/locales/th.js
@@ -1674,4 +1674,9 @@ export default {
'Teal': 'เขียวน้ำทะเล',
'Yellow': 'เหลือง',
'Enter how long it took — at least 1 minute.': 'ใส่ระยะเวลาที่ใช้ — อย่างน้อย 1 นาที',
+ // --- update a routine from a running workout ---
+ 'Update routine': 'อัปเดตรูทีน',
+ 'Update “{0}”?': 'อัปเดตรูทีน “{0}” ไหม?',
+ 'Copy this exercise’s warm-up sets, rest and note from this session into the routine. Your workout history is kept.': 'คัดลอกเซ็ตวอร์มอัพ เวลาพัก และโน้ตของท่านี้จากเซสชันนี้ไปยังรูทีน ประวัติการออกกำลังกายของคุณจะยังอยู่ครบ',
+ 'Routine updated': 'อัปเดตรูทีนแล้ว',
}
diff --git a/frontend/src/locales/tr.js b/frontend/src/locales/tr.js
index 1c96ebc30..5c0c6b143 100644
--- a/frontend/src/locales/tr.js
+++ b/frontend/src/locales/tr.js
@@ -1663,4 +1663,9 @@ export default {
'Teal': 'Turkuaz',
'Yellow': 'Sarı',
'Enter how long it took — at least 1 minute.': 'Ne kadar sürdüğünü gir — en az 1 dakika.',
+ // --- update a routine from a running workout ---
+ 'Update routine': 'Rutini güncelle',
+ 'Update “{0}”?': '“{0}” rutini güncellensin mi?',
+ 'Copy this exercise’s warm-up sets, rest and note from this session into the routine. Your workout history is kept.': 'Bu egzersizin ısınma setlerini, dinlenme süresini ve notunu bu antrenmandan rutine kopyalar. Antrenman geçmişin korunur.',
+ 'Routine updated': 'Rutin güncellendi',
}
diff --git a/frontend/src/locales/uk.js b/frontend/src/locales/uk.js
index ba239e0c8..8ce85cdc6 100644
--- a/frontend/src/locales/uk.js
+++ b/frontend/src/locales/uk.js
@@ -1660,4 +1660,9 @@ export default {
'Teal': 'Бірюзовий',
'Yellow': 'Жовтий',
'Enter how long it took — at least 1 minute.': 'Вкажи, скільки це тривало — щонайменше 1 хвилину.',
+ // --- update a routine from a running workout ---
+ 'Update routine': 'Оновити програму',
+ 'Update “{0}”?': 'Оновити програму «{0}»?',
+ 'Copy this exercise’s warm-up sets, rest and note from this session into the routine. Your workout history is kept.': 'Копіює розминкові підходи, відпочинок і нотатку цієї вправи з цього тренування до програми. Історія тренувань зберігається.',
+ 'Routine updated': 'Програму оновлено',
}
diff --git a/frontend/src/locales/zh.js b/frontend/src/locales/zh.js
index 84237894a..910448c7f 100644
--- a/frontend/src/locales/zh.js
+++ b/frontend/src/locales/zh.js
@@ -1663,4 +1663,9 @@ export default {
'Teal': '青色',
'Yellow': '黄色',
'Enter how long it took — at least 1 minute.': '请输入用时 — 至少 1 分钟。',
+ // --- update a routine from a running workout ---
+ 'Update routine': '更新训练日',
+ 'Update “{0}”?': '更新训练日「{0}」?',
+ 'Copy this exercise’s warm-up sets, rest and note from this session into the routine. Your workout history is kept.': '将本次训练中该动作的热身组、休息时间和备注复制到训练日中。训练历史会保留。',
+ 'Routine updated': '训练日已更新',
}
diff --git a/frontend/src/views/Workout.jsx b/frontend/src/views/Workout.jsx
index 39340a4ed..f6eba5fa2 100644
--- a/frontend/src/views/Workout.jsx
+++ b/frontend/src/views/Workout.jsx
@@ -22,6 +22,7 @@ import { Button, Check, NumberField } from '../components/ui.jsx'
import { defaultIncrement, weightIncrement, stepWeight } from '../lib/progression.js'
import { progressionGuidance } from '../lib/progression-copy.js'
import { buildPlannedEntry, plannedConfigOf, builtOutOfProgression } from '../lib/session-start.js'
+import { routineChangesFromEntry, updateRoutineFromEntry } from '../lib/routines.js'
import { sessionNoProg, setSessionNoProg, setEntryNoProg, joinSessionNoProg } from '../lib/session-noprog.js'
import { glyphOf } from '../lib/glyphs.js'
import { markAllSetsDone, sessionHistory } from '../lib/backfill.js'
@@ -92,7 +93,7 @@ const RTL_LETTER = /[֐-ࣿיִ-﷿ﹰ-]/
// "last time" recap and the progression line — leaving the name, the ⋯ menu, the one-line plan
// the rows are measured against, and the sets.
// Nothing dropped is lost: it is all still on the ⋯ menu, or one ⋮ switch back to list/cards.
-function ExerciseBlock({ entryIdx, compact, dense, editing, onToggle, onToggleSide, onField, onAddSet, onRemoveSet, onAddWarmup, onRemoveSetAt, onStartTimed, onPairPrev, onPairNext, onSetRowRef, onProgressionSettings, onNoProg, onSwap, onMoveUp, onMoveDown, canMoveUp, canMoveDown, onRemoveExercise, busy }) {
+function ExerciseBlock({ entryIdx, compact, dense, editing, onToggle, onToggleSide, onField, onAddSet, onRemoveSet, onAddWarmup, onRemoveSetAt, onStartTimed, onPairPrev, onPairNext, onSetRowRef, onProgressionSettings, onNoProg, routineUpdate, onSwap, onMoveUp, onMoveDown, canMoveUp, canMoveDown, onRemoveExercise, busy }) {
const S = useStore(s => s.S)
const update = useStore(s => s.update)
const working = useUI(s => s.work)
@@ -353,6 +354,7 @@ function ExerciseBlock({ entryIdx, compact, dense, editing, onToggle, onToggleSi
onNoProg && { icon: 'pause', label: t('Don’t count for progression'), sub: t('This exercise, this session only'), on: entry.noProg === true, onClick: () => onNoProg(entry.noProg !== true) },
plateLoading && { icon: 'plate', label: t('Plate loading'), sub: loadSummary, onClick: () => barWeightSheet(entry.id, cfg) },
{ icon: 'flame', label: t('Add warm-up set'), onClick: onAddWarmup },
+ routineUpdate && { icon: 'upload', label: t('Update routine'), sub: routineUpdate.sub, onClick: routineUpdate.run },
onPairPrev && { icon: 'link', label: t('Make superset with previous'), onClick: onPairPrev },
onPairNext && { icon: 'link', label: t('Make superset with next'), onClick: onPairNext },
onSwap && { icon: 'shuffle', label: t('Swap exercise'), onClick: onSwap, disabled: busy },
@@ -848,6 +850,38 @@ function ActiveWorkout() {
// for the switch to change. Off counts them all again, apart from those.
const noProgSwitchable = !A.entries.length || A.entries.some(e => !routineKeepsOut(e))
const toggleSessionNoProg = () => update(s => setSessionNoProg(s.active, !sessionNoProg(s.active), routineKeepsOut))
+ // Warm-ups added in the session, and the rest or note edited on the exercise's settings sheet
+ // from inside it, belong to this session only: the routine is the plan, and finishing never
+ // edits it (lib/session-routines.js). This is the explicit way to keep them — an item in the
+ // exercise's ⋯ menu, there only while the routine's slot says something else than the session
+ // did. Sets, reps and weight are not part of it (routineChangesFromEntry).
+ const routineUpdateFor = idx => {
+ const entry = A.entries[idx]
+ const routine = !editing && entry?.rid ? S.routines.find(r => r.id === entry.rid) : null
+ const found = routine ? routineChangesFromEntry(routine, A.entries, idx) : null
+ if (!found) return null
+ const activeId = A.id
+ const entryId = entry.id
+ return {
+ sub: found.changes.map(c => c.key === 'note' ? t('Note')
+ : (c.key === 'warmupSets' ? t('Warm-up sets') : t('Rest (s)')) + ' ' + c.from + ' → ' + c.to).join(' · '),
+ run: () => confirmSheet({
+ title: t('Update “{0}”?', routine.name),
+ message: t('Copy this exercise’s warm-up sets, rest and note from this session into the routine. Your workout history is kept.'),
+ confirmText: t('Update routine'),
+ onConfirm: () => {
+ let applied = null
+ update(s => {
+ // The sheet can outlive the workout, or the exercise at this index: fail closed.
+ const target = s.routines.find(r => r.id === routine.id)
+ if (!target || s.active?.id !== activeId || s.active.entries?.[idx]?.id !== entryId) return
+ applied = updateRoutineFromEntry(target, s.active.entries, idx)
+ })
+ if (applied) useUI.getState().toast(t('Routine updated'))
+ },
+ }),
+ }
+ }
// One prop object per entry so the card and list layouts share the exact same wiring. The
// exercise-level actions (swap, move, remove) address the entry itself, so the "more" menu of
@@ -871,6 +905,7 @@ function ActiveWorkout() {
onStartTimed: i => startTimed(idx, i),
onProgressionSettings: editing ? null : () => openProgressionSettings(idx),
onNoProg: routineKeepsOut(A.entries[idx]) ? null : on => setNoProg(idx, on),
+ routineUpdate: routineUpdateFor(idx),
})
const navigateUnit = direction => {
const targetFor = active => {
diff --git a/frontend/src/views/Workout.test.jsx b/frontend/src/views/Workout.test.jsx
index f9413ea94..7c3eb9ffb 100644
--- a/frontend/src/views/Workout.test.jsx
+++ b/frontend/src/views/Workout.test.jsx
@@ -2050,3 +2050,77 @@ describe('mark all sets done while logging a past workout', () => {
expect(labels(await openMenu())).not.toContain('Mark all sets done')
})
})
+
+describe('Update routine, from the More menu of an exercise', () => {
+ const lastMenu = () => mocks.menuSheet.mock.calls.at(-1)[0]
+ const item = label => lastMenu().items.filter(Boolean).find(it => it.label === label)
+ const openMore = async () => {
+ await act(async () => { container.querySelector('button[aria-label="More"]').dispatchEvent(new dom.Event('click', { bubbles: true })) })
+ }
+ const routine = (slot = {}) => ({ id: 'A', name: 'Push', ex: [{ id: 'plain-bench', sets: 1, mode: 'reps', reps: 5, weight: 60, ...slot }] })
+ const ownEntry = (extra = {}) => exercise('plain-bench', [false], { rid: 'A', ...extra })
+
+ it('is not offered while the routine already says what the session does', async () => {
+ await mount([ownEntry()], 0, { routines: [routine()] })
+ await openMore()
+ expect(item('Update routine')).toBeUndefined()
+ })
+
+ it('is offered once a warm-up is added, and saves it into the routine after confirming', async () => {
+ await mount([ownEntry()], 0, { routines: [routine()] })
+ await openMore()
+ await act(async () => { item('Add warm-up set').onClick() })
+ await rerender()
+ await openMore()
+
+ const update = item('Update routine')
+ expect(update).toBeTruthy()
+ expect(update.sub).toBe('Warm-up sets 0 → 1')
+
+ // Nothing is written until the confirmation is accepted.
+ update.onClick()
+ expect(mocks.confirmSheet).toHaveBeenCalledOnce()
+ expect(mocks.S.routines[0].ex[0].warmupSets).toBeUndefined()
+
+ mocks.confirmSheet.mock.calls[0][0].onConfirm()
+ expect(mocks.S.routines[0].ex[0].warmupSets).toBe(1)
+ // The rest of the slot is exactly what it was.
+ expect(mocks.S.routines[0].ex[0]).toEqual({ id: 'plain-bench', sets: 1, mode: 'reps', reps: 5, weight: 60, warmupSets: 1 })
+ expect(mocks.toast).toHaveBeenCalledWith('Routine updated')
+ })
+
+ it('names the rest and note edited on the settings sheet mid-session', async () => {
+ await mount([ownEntry({ target: { mode: 'reps', reps: 5, weight: 60, restSec: 150, note: 'pause on the chest' } })], 0, { routines: [routine({ restSec: 90 })] })
+ await openMore()
+ expect(item('Update routine').sub).toBe('Rest (s) 90 → 150 · Note')
+ item('Update routine').onClick()
+ mocks.confirmSheet.mock.calls[0][0].onConfirm()
+ expect(mocks.S.routines[0].ex[0]).toMatchObject({ restSec: 150, note: 'pause on the chest' })
+ })
+
+ it('does not write into a workout that changed while the confirmation was open', async () => {
+ await mount([ownEntry({ target: { mode: 'reps', reps: 5, weight: 60, restSec: 150 } })], 0, { routines: [routine()] })
+ await openMore()
+ item('Update routine').onClick()
+ mocks.S.active = { ...mocks.S.active, id: 'another-workout' }
+ mocks.confirmSheet.mock.calls[0][0].onConfirm()
+ expect(mocks.S.routines[0].ex[0].restSec).toBeUndefined()
+ expect(mocks.toast).not.toHaveBeenCalled()
+ })
+
+ it('is not offered for a freestyle exercise, one the routine never had, or a saved workout being edited', async () => {
+ await mount([exercise('plain-bench', [false], { target: { mode: 'reps', reps: 5, weight: 60, restSec: 150 } })], 0, { routines: [routine()] })
+ await openMore()
+ expect(item('Update routine')).toBeUndefined()
+ await unmount()
+
+ await mount([ownEntry({ id: 'plain-row', target: { mode: 'reps', reps: 5, weight: 60, restSec: 150 } })], 0, { routines: [routine()] })
+ await openMore()
+ expect(item('Update routine')).toBeUndefined()
+ await unmount()
+
+ await mount([ownEntry({ target: { mode: 'reps', reps: 5, weight: 60, restSec: 150 } })], 0, { routines: [routine()], active: { editingWorkoutId: 'saved' } })
+ await openMore()
+ expect(item('Update routine')).toBeUndefined()
+ })
+})