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.
JavaScript apple-watchbodyweightdockerfitnessfitness-trackergymhealthiosmcpnodejspasskeysprogressive-web-applicationspwareactself-hostedself-hostingvitewebauthnweightliftingworkout-tracker
Routines: planned backups for an exercise, offered first in a swap (Discord)
Duarte Santosa23456954a45
diff --git a/frontend/src/lib/plan-share.js b/frontend/src/lib/plan-share.jsindex 90a6c0cf6..72b760cca 100644--- a/frontend/src/lib/plan-share.js+++ b/frontend/src/lib/plan-share.js@@ -8,7 +8,8 @@// 2. A clean, printable page (Save as PDF) where a single exercise never splits across// a page break — each exercise, and each routine that fits, stays in one place.-import { EXIDX, canonicalExId, isBodyweightEq } from './exercises.js'+import { EXIDX, canonicalExId, isBodyweightEq, isCustomEx } from './exercises.js'+import { cleanBackups } from './routine-backups.js'import { cleanUrl } from './media-refs.js'import { modeOf, exLine, MAX_PLANNED_WARMUPS } from './history.js'import { deriveSessionName } from './session-merge.js'@@ -121,6 +122,10 @@ function cleanEx(e) {if (e.restSec > 0) o.restSec = e.restSecif (e.warmupRestSec > 0) o.warmupRestSec = e.warmupRestSec // the ramp's own rest travels with the work rest// The warm-ups' "no timer" and the break between sides travel the same way, only when set.+ // Planned substitutes (lib/routine-backups.js): the catalogue's only, since the other end may+ // not have someone's own exercises.+ const subs = cleanBackups(e.subs, e.id, id => !!EXIDX[id] && !isCustomEx(EXIDX[id]))+ if (subs.length) o.subs = subsif (e.warmupRestOff === true) o.warmupRestOff = trueif (e.side && e.sideRestSec > 0) o.sideRestSec = e.sideRestSecif (e.sg) {@@ -264,15 +269,17 @@ export function parsePlan(raw, destinationUnit = 'kg') {const warmRest = cleanRestSec(e.warmupRestSec)const warmOff = e.warmupRestOff === trueconst sideRest = cleanRestSec(e.sideRestSec)+ // Planned substitutes: the catalogue's only, as they are exported.+ const subs = cleanBackups(Array.isArray(e.subs) ? e.subs.map(x => (typeof x === 'string' ? canonicalExId(x) : x)) : [], known.has(e.id) ? e.id : canonicalExId(e.id), x => !known.has(x) && !!EXIDX[x] && !isCustomEx(EXIDX[x]))// Superset meta only means something on a member of a superset; on a lone exercise it is dropped.const sgName = e.sg ? cleanSgName(e.sgName) : ''const sgRest = e.sg ? cleanRestSec(e.sgRest) : 0const pyramid = normalizePyramid(e.pyramid)const pyramidRest = pyramid.length ? normalizePyramidRest(e.pyramidRest, pyramid.length) : []const pyramidWeight = pyramid.length ? normalizePyramidWeight(e.pyramidWeight, pyramid.length) : []- const { warmupSets, intensifier, restSec, warmupRestSec, warmupRestOff: _warmOff, sideRestSec: _sideRest, pyramid: _pyramid, pyramidRest: _pyramidRest, pyramidWeight: _pyramidWeight, sgName: _sgName, sgRest: _sgRest, ...passthrough } = e+ const { warmupSets, intensifier, restSec, warmupRestSec, warmupRestOff: _warmOff, sideRestSec: _sideRest, subs: _subs, pyramid: _pyramid, pyramidRest: _pyramidRest, pyramidWeight: _pyramidWeight, sgName: _sgName, sgRest: _sgRest, ...passthrough } = eif (!known.has(passthrough.id)) passthrough.id = canonicalExId(passthrough.id)- return convertedExercise({ ...passthrough, ...(pyramid.length ? { pyramid } : {}), ...(pyramidRest.length ? { pyramidRest } : {}), ...(pyramidWeight.length ? { pyramidWeight } : {}), ...(warm ? { warmupSets: warm } : {}), ...(intens ? { intensifier: intens } : {}), ...(rest ? { restSec: rest } : {}), ...(warmOff ? { warmupRestOff: true } : warmRest ? { warmupRestSec: warmRest } : {}), ...(sideRest ? { sideRestSec: sideRest } : {}), ...(sgName ? { sgName } : {}), ...(sgRest ? { sgRest } : {}) }, sourceUnit || destination, destination)+ return convertedExercise({ ...passthrough, ...(pyramid.length ? { pyramid } : {}), ...(pyramidRest.length ? { pyramidRest } : {}), ...(pyramidWeight.length ? { pyramidWeight } : {}), ...(warm ? { warmupSets: warm } : {}), ...(intens ? { intensifier: intens } : {}), ...(rest ? { restSec: rest } : {}), ...(warmOff ? { warmupRestOff: true } : warmRest ? { warmupRestSec: warmRest } : {}), ...(sideRest ? { sideRestSec: sideRest } : {}), ...(subs.length ? { subs } : {}), ...(sgName ? { sgName } : {}), ...(sgRest ? { sgRest } : {}) }, sourceUnit || destination, destination)})}))return {diff --git a/frontend/src/lib/pt-br-locale.test.js b/frontend/src/lib/pt-br-locale.test.jsindex d362c59b7..43757e2a2 100644--- a/frontend/src/lib/pt-br-locale.test.js+++ b/frontend/src/lib/pt-br-locale.test.js@@ -41,7 +41,7 @@ describe('Brazilian Portuguese locale', () => {// has to be taught is a number nobody reads. What the numbers stood for is asserted above.// If the hash fails, review the changed keys and wording before accepting a new one. From// frontend/: node scripts/pt-br-inheritance-fingerprint.mjs --list- expect(fingerprint, 'pt-PT inheritance changed; review the inherited pt-BR wording').toBe('ee5ed544a148de826ac8ccce2f1d2adca04175f0dd4905275a5caa543e3af9a8')+ expect(fingerprint, 'pt-PT inheritance changed; review the inherited pt-BR wording').toBe('ae9fbd36838808959d9184df89a0021a5d9f04e9aa60a5019a52ffb7bbd4b15c')})// pt-PT labelled Unpair 'Desfazer': Undo, in Portuguese (it is pt-BR's Undo), on the button thatdiff --git a/frontend/src/lib/routine-backups.js b/frontend/src/lib/routine-backups.jsnew file mode 100644index 000000000..fbffd808b--- /dev/null+++ b/frontend/src/lib/routine-backups.js@@ -0,0 +1,28 @@+// Planned substitutes for an exercise in a routine (Discord "Substitutions for a routine"): the+// machine is taken, the bar is busy, and the plan already says what to do instead. An optional+// list of exercise ids on the routine's entry, `subs`, picked in the routine editor; a running+// workout's swap sheet shows them first ("Your backups"). Nothing else reads it, and a routine+// entry without it is exactly what it was.++export const MAX_BACKUPS = 5++/**+ * The list as it may be stored: unique string ids, never the exercise itself, only ones `known`+ * says exist, at most MAX_BACKUPS. An empty result is no list at all (the field is left out).+ */+export function cleanBackups(list, selfId, known = () => true) {+ if (!Array.isArray(list)) return []+ const out = []+ for (const id of list) {+ if (typeof id !== 'string' || !id || id === selfId || out.includes(id) || !known(id)) continue+ out.push(id)+ if (out.length >= MAX_BACKUPS) break+ }+ return out+}++/** `{ subs }` to spread into a saved entry, or nothing when there are none. */+export const withBackups = (list, selfId, known) => {+ const subs = cleanBackups(list, selfId, known)+ return subs.length ? { subs } : {}+}diff --git a/frontend/src/lib/routine-backups.test.js b/frontend/src/lib/routine-backups.test.jsnew file mode 100644index 000000000..d10634ea3--- /dev/null+++ b/frontend/src/lib/routine-backups.test.js@@ -0,0 +1,36 @@+import { describe, expect, it } from 'vitest'+import { cleanBackups, withBackups, MAX_BACKUPS } from './routine-backups.js'+import { replaceSlotExercise } from './routines.js'+import { parsePlan, buildPlanBundle } from './plan-share.js'++/* Planned substitutes for an exercise in a routine (Discord): an optional list on the entry. */+describe('cleanBackups', () => {+ it('unique string ids, never the exercise itself, only known ones, at most five', () => {+ expect(cleanBackups(['a', 'b', 'a', 'self', 3, '', null, 'c'], 'self')).toEqual(['a', 'b', 'c'])+ expect(cleanBackups(['a', 'gone'], 'x', id => id !== 'gone')).toEqual(['a'])+ expect(cleanBackups(['1', '2', '3', '4', '5', '6', '7'], 'x')).toHaveLength(MAX_BACKUPS)+ expect(cleanBackups('a', 'x')).toEqual([])+ })+ it('no list, no field', () => {+ expect(withBackups([], 'x')).toEqual({})+ expect(withBackups(undefined, 'x')).toEqual({})+ expect(withBackups(['a'], 'x')).toEqual({ subs: ['a'] })+ })+})++describe('a replaced exercise', () => {+ it('keeps the slot\'s backups, less the one now in the slot', () => {+ const slot = { id: '0025', sets: 3, reps: 8, weight: 60, subs: ['0047', '0289'] }+ expect(replaceSlotExercise(slot, '0047', { workouts: [] }, 'r').subs).toEqual(['0289'])+ expect('subs' in replaceSlotExercise({ ...slot, subs: ['0047'] }, '0047', { workouts: [] }, 'r')).toBe(false)+ })+})++describe('plan files', () => {+ const S = ex => ({ unit: 'kg', week: {}, customEx: [{ id: 'cu1', n: 'mine', bp: 'back', custom: true }], routines: [{ id: 'r', name: 'R', ex: [ex] }] })+ const roundTrip = ex => parsePlan(JSON.stringify(buildPlanBundle(S(ex), 'Plan'))).routines[0].ex[0]+ it('carry the catalogue backups, not someone\'s own exercises, and nothing when there are none', () => {+ expect(roundTrip({ id: '0025', sets: 3, reps: 8, subs: ['0047', 'cu1', 'nope', '0025'] }).subs).toEqual(['0047'])+ expect('subs' in roundTrip({ id: '0025', sets: 3, reps: 8 })).toBe(false)+ })+})diff --git a/frontend/src/lib/routines.js b/frontend/src/lib/routines.jsindex d956e5e1b..8c31701bd 100644--- a/frontend/src/lib/routines.js+++ b/frontend/src/lib/routines.js@@ -129,15 +129,25 @@ export function restoreRoutine(s, snap) {** Picking the exercise that is already in the slot replaces nothing, and changes nothing.*/+// The slot's planned substitutes stay with the slot (lib/routine-backups.js), less the exercise+// that now fills it: a backup of itself means nothing.+function dropSelfBackup(out) {+ if (!Array.isArray(out.subs)) return out+ const subs = out.subs.filter(x => x !== out.id)+ if (subs.length) out.subs = subs+ else delete out.subs+ return out+}+export function replaceSlotExercise(slot, id, S, rid) {const old = slot || {}if (old.id === id) return { ...old }if ((modeOf(old) === 'cardio') !== isCardio(id)) {- const kept = ['sg', 'note', 'restSec'].filter(key => old[key] != null)- return { id, ...defaultConfig(id), ...Object.fromEntries(kept.map(key => [key, old[key]])) }+ const kept = ['sg', 'note', 'restSec', 'subs'].filter(key => old[key] != null)+ return dropSelfBackup({ id, ...defaultConfig(id), ...Object.fromEntries(kept.map(key => [key, old[key]])) })}const { id: _replaced, bodyweight: _flag, assisted: _assisted, side: _side, ...carried } = old- const out = { id, ...carried }+ const out = dropSelfBackup({ id, ...carried })if (isCardio(id)) return outif (isBw(old) !== isBodyweightEq(id)) {out.weight = 0diff --git a/frontend/src/locales/ar.js b/frontend/src/locales/ar.jsindex 9212bf0ef..f9831836e 100644--- a/frontend/src/locales/ar.js+++ b/frontend/src/locales/ar.js@@ -2377,4 +2377,13 @@ export default {'{0} photos know their day and go there. The others go on the day below.': '{0} صور تعرف يومها وتذهب إليه. البقية تذهب إلى اليوم أدناه.',// --- progress photos card ---'Every progress photo, lined up by date, for any day. Plus a before/after slider.': 'كل صور التقدّم مرتبة حسب التاريخ، لأي يوم. ومعها شريط مقارنة قبل وبعد.',+ // --- routine backups ---+ 'Add a backup': 'إضافة بديل',+ 'Backups': 'البدائل',+ 'Backups for {0}': 'بدائل {0}',+ 'Everything else': 'كل ما عدا ذلك',+ 'Machine taken? Pick what you’d do instead, and a swap mid-workout offers these first.': 'الجهاز مشغول؟ اختر ما ستفعله بدلًا منه، وسيعرضها التبديل أثناء التمرين أولًا.',+ 'Remove “{0}”': 'إزالة «{0}»',+ 'That’s plenty of backups.': 'هذا عدد كافٍ من البدائل.',+ 'Your backups': 'بدائلك',}diff --git a/frontend/src/locales/bn.js b/frontend/src/locales/bn.jsindex 73669a4b3..53dc79aa1 100644--- a/frontend/src/locales/bn.js+++ b/frontend/src/locales/bn.js@@ -2401,4 +2401,13 @@ export default {'{0} photos know their day and go there. The others go on the day below.': '{0}টি ছবি তাদের দিন জানে আর সেখানে যাবে। বাকিগুলো নিচের দিনে যাবে।',// --- progress photos card ---'Every progress photo, lined up by date, for any day. Plus a before/after slider.': 'সব অগ্রগতির ছবি তারিখ অনুযায়ী সাজানো, যেকোনো দিনের। সঙ্গে আগে/পরে তুলনার স্লাইডার।',+ // --- routine backups ---+ 'Add a backup': 'বিকল্প যোগ করুন',+ 'Backups': 'বিকল্প',+ 'Backups for {0}': '{0}-এর বিকল্প',+ 'Everything else': 'বাকি সব',+ 'Machine taken? Pick what you’d do instead, and a swap mid-workout offers these first.': 'মেশিন ফাঁকা নেই? এর বদলে কী করবেন বেছে নিন, ওয়ার্কআউটের মাঝে বদলানোর সময় এগুলোই আগে আসবে।',+ 'Remove “{0}”': '“{0}” সরান',+ 'That’s plenty of backups.': 'এতগুলো বিকল্পই যথেষ্ট।',+ 'Your backups': 'আপনার বিকল্প',}diff --git a/frontend/src/locales/de.js b/frontend/src/locales/de.jsindex 1cd094888..76e980877 100644--- a/frontend/src/locales/de.js+++ b/frontend/src/locales/de.js@@ -2342,4 +2342,13 @@ export default {'{0} photos know their day and go there. The others go on the day below.': '{0} Fotos kennen ihren Tag und landen dort. Die anderen landen am Tag unten.',// --- progress photos card ---'Every progress photo, lined up by date, for any day. Plus a before/after slider.': 'Alle Fortschrittsfotos nach Datum, für jeden Tag. Dazu ein Vorher-nachher-Regler.',+ // --- routine backups ---+ 'Add a backup': 'Ausweichübung hinzufügen',+ 'Backups': 'Ausweichübungen',+ 'Backups for {0}': 'Ausweichübungen für {0}',+ 'Everything else': 'Alles andere',+ 'Machine taken? Pick what you’d do instead, and a swap mid-workout offers these first.': 'Gerät belegt? Wähl, was du stattdessen machst, und beim Tauschen im Training kommen die zuerst.',+ 'Remove “{0}”': '„{0}“ entfernen',+ 'That’s plenty of backups.': 'Das sind genug Ausweichübungen.',+ 'Your backups': 'Deine Ausweichübungen',}diff --git a/frontend/src/locales/es.js b/frontend/src/locales/es.jsindex 4ff6c6a1a..8c34b77df 100644--- a/frontend/src/locales/es.js+++ b/frontend/src/locales/es.js@@ -2322,4 +2322,13 @@ export default {'{0} photos know their day and go there. The others go on the day below.': '{0} fotos saben su día y van allí. Las demás van al día de abajo.',// --- progress photos card ---'Every progress photo, lined up by date, for any day. Plus a before/after slider.': 'Todas tus fotos de progreso por fecha, de cualquier día. Y un deslizador de antes y después.',+ // --- routine backups ---+ 'Add a backup': 'Añadir un sustituto',+ 'Backups': 'Sustitutos',+ 'Backups for {0}': 'Sustitutos de {0}',+ 'Everything else': 'Todo lo demás',+ 'Machine taken? Pick what you’d do instead, and a swap mid-workout offers these first.': '¿Máquina ocupada? Elige qué harías en su lugar y, al cambiar a mitad del entreno, salen primero.',+ 'Remove “{0}”': 'Quitar «{0}»',+ 'That’s plenty of backups.': 'Ya son bastantes sustitutos.',+ 'Your backups': 'Tus sustitutos',}diff --git a/frontend/src/locales/fr.js b/frontend/src/locales/fr.jsindex 8228e96ca..ab3421393 100644--- a/frontend/src/locales/fr.js+++ b/frontend/src/locales/fr.js@@ -2322,4 +2322,13 @@ export default {'{0} photos know their day and go there. The others go on the day below.': '{0} photos connaissent leur jour et y vont. Les autres vont au jour ci-dessous.',// --- progress photos card ---'Every progress photo, lined up by date, for any day. Plus a before/after slider.': 'Toutes tes photos de progression par date, pour n’importe quel jour. Avec un curseur avant/après.',+ // --- routine backups ---+ 'Add a backup': 'Ajouter un remplaçant',+ 'Backups': 'Remplaçants',+ 'Backups for {0}': 'Remplaçants pour {0}',+ 'Everything else': 'Tout le reste',+ 'Machine taken? Pick what you’d do instead, and a swap mid-workout offers these first.': 'Machine prise ? Choisis quoi faire à la place, et un échange en pleine séance les propose en premier.',+ 'Remove “{0}”': 'Retirer « {0} »',+ 'That’s plenty of backups.': 'Ça fait assez de remplaçants.',+ 'Your backups': 'Tes remplaçants',}diff --git a/frontend/src/locales/hi.js b/frontend/src/locales/hi.jsindex 09d90e7c4..8dbbaca1d 100644--- a/frontend/src/locales/hi.js+++ b/frontend/src/locales/hi.js@@ -2322,4 +2322,13 @@ export default {'{0} photos know their day and go there. The others go on the day below.': '{0} फ़ोटो अपना दिन जानती हैं और वहीं जाएँगी। बाकी नीचे वाले दिन पर जाएँगी।',// --- progress photos card ---'Every progress photo, lined up by date, for any day. Plus a before/after slider.': 'हर प्रोग्रेस फ़ोटो तारीख़ के क्रम में, किसी भी दिन की। साथ में पहले/बाद का स्लाइडर।',+ // --- routine backups ---+ 'Add a backup': 'विकल्प जोड़ें',+ 'Backups': 'विकल्प',+ 'Backups for {0}': '{0} के विकल्प',+ 'Everything else': 'बाकी सब',+ 'Machine taken? Pick what you’d do instead, and a swap mid-workout offers these first.': 'मशीन खाली नहीं? उसकी जगह क्या करेंगे चुनें, वर्कआउट के बीच बदलते समय ये पहले दिखेंगे।',+ 'Remove “{0}”': '“{0}” हटाएँ',+ 'That’s plenty of backups.': 'इतने विकल्प काफ़ी हैं।',+ 'Your backups': 'आपके विकल्प',}diff --git a/frontend/src/locales/hu.js b/frontend/src/locales/hu.jsindex 422126426..a3e24bcf8 100644--- a/frontend/src/locales/hu.js+++ b/frontend/src/locales/hu.js@@ -2325,4 +2325,13 @@ export default {'{0} photos know their day and go there. The others go on the day below.': '{0} fotó tudja a napját, és oda kerül. A többi a lenti napra kerül.',// --- progress photos card ---'Every progress photo, lined up by date, for any day. Plus a before/after slider.': 'Minden fejlődési fotó dátum szerint, bármelyik napról. Plusz egy előtte/utána csúszka.',+ // --- routine backups ---+ 'Add a backup': 'Helyettesítő hozzáadása',+ 'Backups': 'Helyettesítők',+ 'Backups for {0}': 'Helyettesítők ehhez: {0}',+ 'Everything else': 'Minden más',+ 'Machine taken? Pick what you’d do instead, and a swap mid-workout offers these first.': 'Foglalt a gép? Válaszd ki, mit csinálsz helyette, és edzés közbeni cserénél ezeket kínálja elsőnek.',+ 'Remove “{0}”': '„{0}” eltávolítása',+ 'That’s plenty of backups.': 'Ennyi helyettesítő bőven elég.',+ 'Your backups': 'A helyettesítőid',}diff --git a/frontend/src/locales/it.js b/frontend/src/locales/it.jsindex 508bff4ae..1f08205ee 100644--- a/frontend/src/locales/it.js+++ b/frontend/src/locales/it.js@@ -2322,4 +2322,13 @@ export default {'{0} photos know their day and go there. The others go on the day below.': '{0} foto conoscono il loro giorno e vanno lì. Le altre vanno nel giorno qui sotto.',// --- progress photos card ---'Every progress photo, lined up by date, for any day. Plus a before/after slider.': 'Tutte le foto dei progressi in ordine di data, di qualsiasi giorno. Più uno slider prima/dopo.',+ // --- routine backups ---+ 'Add a backup': 'Aggiungi un sostituto',+ 'Backups': 'Sostituti',+ 'Backups for {0}': 'Sostituti per {0}',+ 'Everything else': 'Tutto il resto',+ 'Machine taken? Pick what you’d do instead, and a swap mid-workout offers these first.': 'Macchina occupata? Scegli cosa faresti al suo posto, e uno scambio a metà allenamento li propone per primi.',+ 'Remove “{0}”': 'Rimuovi «{0}»',+ 'That’s plenty of backups.': 'Bastano così, i sostituti.',+ 'Your backups': 'I tuoi sostituti',}diff --git a/frontend/src/locales/ko.js b/frontend/src/locales/ko.jsindex e971a04cf..4518a6754 100644--- a/frontend/src/locales/ko.js+++ b/frontend/src/locales/ko.js@@ -2322,4 +2322,13 @@ export default {'{0} photos know their day and go there. The others go on the day below.': '사진 {0}장은 찍은 날을 알아서 그날로 들어가요. 나머지는 아래 날짜로 들어가요.',// --- progress photos card ---'Every progress photo, lined up by date, for any day. Plus a before/after slider.': '모든 진행 사진을 날짜순으로, 어느 날이든. 비포/애프터 슬라이더도 있어요.',+ // --- routine backups ---+ 'Add a backup': '대체 운동 추가',+ 'Backups': '대체 운동',+ 'Backups for {0}': '{0} 대체 운동',+ 'Everything else': '나머지 전부',+ 'Machine taken? Pick what you’d do instead, and a swap mid-workout offers these first.': '기구가 사용 중인가요? 대신 할 운동을 골라 두면 운동 중 교체할 때 먼저 보여 줘요.',+ 'Remove “{0}”': '“{0}” 빼기',+ 'That’s plenty of backups.': '대체 운동은 이 정도면 충분해요.',+ 'Your backups': '내 대체 운동',}diff --git a/frontend/src/locales/pl.js b/frontend/src/locales/pl.jsindex c2bba3314..3f18d4809 100644--- a/frontend/src/locales/pl.js+++ b/frontend/src/locales/pl.js@@ -2322,4 +2322,13 @@ export default {'{0} photos know their day and go there. The others go on the day below.': { one: '{0} zdjęcie zna swój dzień i tam trafi. Pozostałe trafią na dzień poniżej.', few: '{0} zdjęcia znają swój dzień i tam trafią. Pozostałe trafią na dzień poniżej.', many: '{0} zdjęć zna swój dzień i tam trafi. Pozostałe trafią na dzień poniżej.' },// --- progress photos card ---'Every progress photo, lined up by date, for any day. Plus a before/after slider.': 'Wszystkie zdjęcia postępów według daty, z dowolnego dnia. Do tego suwak przed/po.',+ // --- routine backups ---+ 'Add a backup': 'Dodaj zamiennik',+ 'Backups': 'Zamienniki',+ 'Backups for {0}': 'Zamienniki dla {0}',+ 'Everything else': 'Wszystko inne',+ 'Machine taken? Pick what you’d do instead, and a swap mid-workout offers these first.': 'Maszyna zajęta? Wybierz, co zrobisz zamiast niej, a zamiana w trakcie treningu pokaże je najpierw.',+ 'Remove “{0}”': 'Usuń „{0}”',+ 'That’s plenty of backups.': 'Tyle zamienników wystarczy.',+ 'Your backups': 'Twoje zamienniki',}diff --git a/frontend/src/locales/pt-BR.js b/frontend/src/locales/pt-BR.jsindex db0c54b08..5eb2f1fdd 100644--- a/frontend/src/locales/pt-BR.js+++ b/frontend/src/locales/pt-BR.js@@ -1466,6 +1466,10 @@ export const PT_BR_OVERRIDES = {'Your server keeps photos only on days with a workout. An update lets it keep them for any day.': 'Seu servidor só guarda fotos em dias com treino. Uma atualização permite guardá-las para qualquer dia.',// --- progress photos card ---'Every progress photo, lined up by date, for any day. Plus a before/after slider.': 'Todas as fotos de progresso por data, de qualquer dia. E um controle deslizante de antes/depois.',+ // --- routine backups ---+ 'Machine taken? Pick what you’d do instead, and a swap mid-workout offers these first.': 'Máquina ocupada? Escolha o que você faria no lugar dela, e uma troca no meio do treino mostra estes primeiro.',+ 'Remove “{0}”': 'Remover “{0}”',+ 'Your backups': 'Seus substitutos',}export default { ...pt, ...PT_BR_OVERRIDES }diff --git a/frontend/src/locales/pt.js b/frontend/src/locales/pt.jsindex c504e8085..d44ebd804 100644--- a/frontend/src/locales/pt.js+++ b/frontend/src/locales/pt.js@@ -2322,4 +2322,13 @@ export default {'{0} photos know their day and go there. The others go on the day below.': '{0} fotos sabem o seu dia e vão para lá. As outras vão para o dia abaixo.',// --- progress photos card ---'Every progress photo, lined up by date, for any day. Plus a before/after slider.': 'Todas as fotos de progresso por data, de qualquer dia. E um deslizador antes/depois.',+ // --- routine backups ---+ 'Add a backup': 'Adicionar um substituto',+ 'Backups': 'Substitutos',+ 'Backups for {0}': 'Substitutos para {0}',+ 'Everything else': 'Todo o resto',+ 'Machine taken? Pick what you’d do instead, and a swap mid-workout offers these first.': 'Máquina ocupada? Escolhe o que farias em vez dela, e uma troca a meio do treino mostra estes primeiro.',+ 'Remove “{0}”': 'Remover «{0}»',+ 'That’s plenty of backups.': 'Já chega de substitutos.',+ 'Your backups': 'Os teus substitutos',}diff --git a/frontend/src/locales/ru.js b/frontend/src/locales/ru.jsindex 1e27d10de..8dfd597cf 100644--- a/frontend/src/locales/ru.js+++ b/frontend/src/locales/ru.js@@ -2326,4 +2326,13 @@ export default {'{0} photos know their day and go there. The others go on the day below.': { one: '{0} фото знает свой день и попадёт туда. Остальные попадут в день ниже.', few: '{0} фото знают свой день и попадут туда. Остальные попадут в день ниже.', many: '{0} фото знают свой день и попадут туда. Остальные попадут в день ниже.' },// --- progress photos card ---'Every progress photo, lined up by date, for any day. Plus a before/after slider.': 'Все фото прогресса по датам, за любой день. И ползунок «до и после».',+ // --- routine backups ---+ 'Add a backup': 'Добавить замену',+ 'Backups': 'Замены',+ 'Backups for {0}': 'Замены для {0}',+ 'Everything else': 'Всё остальное',+ 'Machine taken? Pick what you’d do instead, and a swap mid-workout offers these first.': 'Тренажёр занят? Выберите, что сделаете вместо него, и при замене посреди тренировки они будут первыми.',+ 'Remove “{0}”': 'Убрать «{0}»',+ 'That’s plenty of backups.': 'Замен уже достаточно.',+ 'Your backups': 'Ваши замены',}diff --git a/frontend/src/locales/th.js b/frontend/src/locales/th.jsindex e5afb6e80..2864869f3 100644--- a/frontend/src/locales/th.js+++ b/frontend/src/locales/th.js@@ -2333,4 +2333,13 @@ export default {'{0} photos know their day and go there. The others go on the day below.': '{0} รูปรู้วันของตัวเองและจะไปอยู่ที่นั่น ที่เหลือไปอยู่ในวันด้านล่าง',// --- progress photos card ---'Every progress photo, lined up by date, for any day. Plus a before/after slider.': 'รูปความก้าวหน้าทุกรูปเรียงตามวันที่ วันไหนก็ได้ พร้อมแถบเลื่อนเปรียบเทียบก่อน/หลัง',+ // --- routine backups ---+ 'Add a backup': 'เพิ่มท่าสำรอง',+ 'Backups': 'ท่าสำรอง',+ 'Backups for {0}': 'ท่าสำรองของ {0}',+ 'Everything else': 'อย่างอื่นทั้งหมด',+ 'Machine taken? Pick what you’d do instead, and a swap mid-workout offers these first.': 'เครื่องไม่ว่างใช่ไหม เลือกว่าจะทำอะไรแทน แล้วตอนสลับท่าระหว่างออกกำลังกายจะเห็นพวกนี้ก่อน',+ 'Remove “{0}”': 'เอา “{0}” ออก',+ 'That’s plenty of backups.': 'ท่าสำรองเท่านี้ก็พอแล้ว',+ 'Your backups': 'ท่าสำรองของคุณ',}diff --git a/frontend/src/locales/tr.js b/frontend/src/locales/tr.jsindex 22ee68da9..332efb9be 100644--- a/frontend/src/locales/tr.js+++ b/frontend/src/locales/tr.js@@ -2322,4 +2322,13 @@ export default {'{0} photos know their day and go there. The others go on the day below.': '{0} fotoğraf gününü biliyor ve oraya gidiyor. Diğerleri aşağıdaki güne gider.',// --- progress photos card ---'Every progress photo, lined up by date, for any day. Plus a before/after slider.': 'Tüm ilerleme fotoğrafların tarihe göre, herhangi bir gün için. Bir de önce/sonra kaydırıcısı.',+ // --- routine backups ---+ 'Add a backup': 'Yedek ekle',+ 'Backups': 'Yedekler',+ 'Backups for {0}': '{0} için yedekler',+ 'Everything else': 'Geri kalan her şey',+ 'Machine taken? Pick what you’d do instead, and a swap mid-workout offers these first.': 'Makine dolu mu? Yerine ne yapacağını seç, antrenman ortasında değiştirirken önce bunlar çıkar.',+ 'Remove “{0}”': '“{0}” kaldır',+ 'That’s plenty of backups.': 'Bu kadar yedek yeter.',+ 'Your backups': 'Yedeklerin',}diff --git a/frontend/src/locales/uk.js b/frontend/src/locales/uk.jsindex 9a0ed482d..b660bea6f 100644--- a/frontend/src/locales/uk.js+++ b/frontend/src/locales/uk.js@@ -2319,4 +2319,13 @@ export default {'{0} photos know their day and go there. The others go on the day below.': { one: '{0} фото знає свій день і потрапить туди. Решта потраплять у день нижче.', few: '{0} фото знають свій день і потраплять туди. Решта потраплять у день нижче.', many: '{0} фото знають свій день і потраплять туди. Решта потраплять у день нижче.' },// --- progress photos card ---'Every progress photo, lined up by date, for any day. Plus a before/after slider.': 'Усі фото прогресу за датами, за будь-який день. І повзунок «до і після».',+ // --- routine backups ---+ 'Add a backup': 'Додати заміну',+ 'Backups': 'Заміни',+ 'Backups for {0}': 'Заміни для {0}',+ 'Everything else': 'Усе інше',+ 'Machine taken? Pick what you’d do instead, and a swap mid-workout offers these first.': 'Тренажер зайнятий? Виберіть, що зробите замість нього, і під час заміни посеред тренування вони будуть першими.',+ 'Remove “{0}”': 'Прибрати «{0}»',+ 'That’s plenty of backups.': 'Замін уже досить.',+ 'Your backups': 'Ваші заміни',}diff --git a/frontend/src/locales/zh-TW.js b/frontend/src/locales/zh-TW.jsindex d07d63b74..d6e91ef3d 100644--- a/frontend/src/locales/zh-TW.js+++ b/frontend/src/locales/zh-TW.js@@ -2315,4 +2315,13 @@ export default {'{0} photos know their day and go there. The others go on the day below.': '{0} 張相片知道自己的日期,會放到那天。其餘的放到下面的日期。',// --- progress photos card ---'Every progress photo, lined up by date, for any day. Plus a before/after slider.': '所有進度相片按日期排列,任何一天都行。還有前後對比滑桿。',+ // --- routine backups ---+ 'Add a backup': '新增備選動作',+ 'Backups': '備選動作',+ 'Backups for {0}': '{0} 的備選動作',+ 'Everything else': '其他全部',+ 'Machine taken? Pick what you’d do instead, and a swap mid-workout offers these first.': '器材被占用了?選好你要改做的動作,訓練中替換時會先顯示這些。',+ 'Remove “{0}”': '移除「{0}」',+ 'That’s plenty of backups.': '備選動作已經夠多了。',+ 'Your backups': '你的備選動作',}diff --git a/frontend/src/locales/zh.js b/frontend/src/locales/zh.jsindex 536205b79..4feffcd0d 100644--- a/frontend/src/locales/zh.js+++ b/frontend/src/locales/zh.js@@ -2322,4 +2322,13 @@ export default {'{0} photos know their day and go there. The others go on the day below.': '{0} 张照片知道自己的日期,会放到那天。其余的放到下面的日期。',// --- progress photos card ---'Every progress photo, lined up by date, for any day. Plus a before/after slider.': '所有进度照片按日期排列,任何一天都行。还有前后对比滑块。',+ // --- routine backups ---+ 'Add a backup': '添加备选动作',+ 'Backups': '备选动作',+ 'Backups for {0}': '{0} 的备选动作',+ 'Everything else': '其他全部',+ 'Machine taken? Pick what you’d do instead, and a swap mid-workout offers these first.': '器械被占了?选好你要换做的动作,训练中替换时会先显示这些。',+ 'Remove “{0}”': '移除“{0}”',+ 'That’s plenty of backups.': '备选动作已经够多了。',+ 'Your backups': '你的备选动作',}diff --git a/frontend/src/sheets.backups.test.jsx b/frontend/src/sheets.backups.test.jsxnew file mode 100644index 000000000..8028d129d--- /dev/null+++ b/frontend/src/sheets.backups.test.jsx@@ -0,0 +1,98 @@+// @vitest-environment happy-dom+import React, { act } from 'react'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { createRoot } from 'react-dom/client'+import { EXDB, EXIDX } from './lib/exercises.js'+import { useStore } from './store/useStore.js'+import { useUI } from './store/useUI.js'+import { exConfigSheet, exercisePicker } from './sheets.jsx'+import { exerciseNameFor } from './lib/i18n.js'++/* Planned substitutes (Discord "Substitutions for a routine"): picked in the routine editor's+ exercise sheet, offered first by the swap picker, kept by every sheet that saves the slot. */+const ex = EXDB.find(e => e.id === '0025')+const mounted = []+function render(sheet) {+ const host = document.createElement('div')+ document.body.appendChild(host)+ const root = createRoot(host)+ mounted.push([root, host])+ act(() => root.render(sheet.render(() => useUI.getState().closeSheet(sheet.id))))+ return host+}+const row = (host, title) => [...host.querySelectorAll('.lrow')].find(r => r.querySelector('.lrow-t')?.textContent === title)+const save = host => [...host.querySelectorAll('button')].find(b => b.textContent.trim() === 'Save').click()++beforeEach(() => {+ globalThis.IS_REACT_ACT_ENVIRONMENT = true+ useUI.setState({ sheets: [] })+ useStore.setState(s => ({ S: { ...s.S, unit: 'kg', restSec: 120 } }))+ document.body.innerHTML = ''+})+afterEach(() => { act(() => { mounted.splice(0).forEach(([root, host]) => { root.unmount(); host.remove() }) }) })++describe('the routine editor\'s exercise sheet', () => {+ it('shows the backups and keeps them on save; without any, no field', () => {+ const onSave = vi.fn()+ exConfigSheet(ex, { sets: 3, reps: 8, weight: 60, mode: 'reps', subs: ['0047', '0289'] }, onSave, null, null, null, null, undefined, { backups: true })+ const host = render(useUI.getState().sheets.at(-1))+ expect(row(host, 'Backups').querySelector('.lrow-v').textContent).toBe('2')+ expect(row(host, 'Backups').textContent).toContain(exerciseNameFor(EXIDX['0047']))+ act(() => save(host))+ expect(onSave.mock.calls[0][0].subs).toEqual(['0047', '0289'])++ const none = vi.fn()+ exConfigSheet(ex, { sets: 3, reps: 8, weight: 60, mode: 'reps' }, none, null, null, null, null, undefined, { backups: true })+ const second = render(useUI.getState().sheets.at(-1))+ act(() => save(second))+ expect('subs' in none.mock.calls[0][0]).toBe(false)+ })++ it('adds one from the library and removes one', () => {+ const onSave = vi.fn()+ exConfigSheet(ex, { sets: 3, reps: 8, weight: 60, mode: 'reps', subs: ['0047'] }, onSave, null, null, null, null, undefined, { backups: true })+ const host = render(useUI.getState().sheets.at(-1))+ act(() => row(host, 'Backups').click())+ const sheet = render(useUI.getState().sheets.at(-1))+ expect(sheet.querySelector('h3').textContent).toBe('Backups for ' + exerciseNameFor(ex))+ act(() => [...sheet.querySelectorAll('button')].find(b => b.textContent === 'Add a backup').click())+ const picker = render(useUI.getState().sheets.at(-1))+ const name = exerciseNameFor(EXIDX['0289'])+ act(() => [...picker.querySelectorAll('.chip')].find(c => c.textContent === 'All').click())+ const input = picker.querySelector('input.input')+ act(() => {+ Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value').set.call(input, name)+ input.dispatchEvent(new Event('input', { bubbles: true }))+ })+ const pick = [...picker.querySelectorAll('.item')].find(el => el.querySelector('.tt')?.textContent === name)+ act(() => pick.click())+ act(() => [...sheet.querySelectorAll('button')].find(b => b.getAttribute('aria-label') === 'Remove “' + exerciseNameFor(EXIDX['0047']) + '”').click())+ act(() => save(host))+ expect(onSave.mock.calls[0][0].subs).toEqual(['0289'])+ })++ it('elsewhere (a workout\'s own sheet) the row is not offered, and the backups still survive a save', () => {+ const onSave = vi.fn()+ exConfigSheet(ex, { sets: 3, reps: 8, weight: 60, mode: 'reps', subs: ['0047'] }, onSave)+ const host = render(useUI.getState().sheets.at(-1))+ expect(row(host, 'Backups')).toBeUndefined()+ act(() => save(host))+ expect(onSave.mock.calls[0][0].subs).toEqual(['0047'])+ })+})++describe('the swap picker', () => {+ it('lists the slot\'s backups first, and leaves them out while searching', () => {+ exercisePicker(() => {}, { title: 'Swap exercise', like: '0025', backups: ['0289', 'gone'] })+ const host = render(useUI.getState().sheets.at(-1))+ const heads = [...host.querySelectorAll('h4.sec')].map(h => h.textContent)+ expect(heads.slice(0, 2)).toEqual(['Your backups', 'Everything else'])+ const first = host.querySelector('h4.sec').nextElementSibling+ expect(first.textContent).toContain(exerciseNameFor(EXIDX['0289']))+ })+ it('no backups, no section', () => {+ exercisePicker(() => {}, { title: 'Swap exercise', like: '0025' })+ const host = render(useUI.getState().sheets.at(-1))+ expect([...host.querySelectorAll('h4.sec')].map(h => h.textContent)).not.toContain('Your backups')+ })+})diff --git a/frontend/src/sheets.jsx b/frontend/src/sheets.jsxindex d4a9be912..804ecdc16 100644--- a/frontend/src/sheets.jsx+++ b/frontend/src/sheets.jsx@@ -20,6 +20,7 @@ import { syncMedia } from './lib/media-sync.js'import LineChart from './components/LineChart.jsx'import Stepper from './components/Stepper.jsx'import { durationSheet } from './components/DurationWheel.jsx'+import { cleanBackups, withBackups, MAX_BACKUPS } from './lib/routine-backups.js'import { SG_NAME_MAX } from './lib/superset-meta.js'import { REST_MAX, fmtRest } from './lib/duration.js'import Icon from './components/Icon.jsx'@@ -1281,7 +1282,7 @@ function usageMap(st) {}// The swap pickers' own scope (#473): exercises sharing the swapped exercise's target muscle.const SAME = '≈'-function ExercisePicker({ onPick, title, close, like, actionIcon }) {+function ExercisePicker({ onPick, title, close, like, actionIcon, backups }) {const st = useStore(s => s.S)const isSwap = !!like || title === t('Swap exercise') || title === t('Replace exercise') || title === 'Swap exercise' || title === 'Replace exercise'const quickIcon = actionIcon || (isSwap ? 'swap' : 'plus')@@ -1290,6 +1291,7 @@ function ExercisePicker({ onPick, title, close, like, actionIcon }) {: t('Add “{0}”', exerciseNameFor(e))const usage = usageMap(st)const [q, setQ] = useState('')+ const backupList = (Array.isArray(backups) ? backups : []).map(id => EXIDX[id]).filter(Boolean)// What a swap is away from: the picker opens on what trains the same muscle, if anything you// can use does, and "All" is one tap back to everything.const likeEx = like ? (EXIDX[like] || allExercises(st).find(e => e.id === like) || null) : null@@ -1405,6 +1407,12 @@ function ExercisePicker({ onPick, title, close, like, actionIcon }) {<div className="thumb thumb-x"><Icon name="plusCircle" /></div><div className="grow"><div className="tt">{t('Create your own exercise')}</div><div className="ss">{t('name + body part, and a photo or video if you like')}</div></div><Icon name="plus" className="chev" /></div>}+ {/* The slot's planned substitutes, first, while nothing is typed: the plan already knows. */}+ {backupList.length > 0 && !q.trim() && <>+ <h4 className="sec">{t('Your backups')}</h4>+ {backupList.map(pickRow)}+ <h4 className="sec">{t('Everything else')}</h4>+ </>}{f.slice(0, shown).map(pickRow)}{f.length === 0 && bp === '★' && <div className="empty">{t('Nothing picked yet. Add some exercises and they’ll show up here.')}</div>}{f.length === 0 && bp === '☆' && <div className="empty">{t('No favourites yet. Tap the star on an exercise to add one.')}</div>}@@ -1417,7 +1425,8 @@ function ExercisePicker({ onPick, title, close, like, actionIcon }) {// `title` names what the pick is for when it is not an add — the routine editor's Replace (#110).// `like` is the exercise a swap or a replace is away from: the picker then opens on the ones that// train the same muscle, same equipment first (#473).-export const exercisePicker = (onPick, { title, like, actionIcon } = {}) => ui().openSheet(close => <ExercisePicker onPick={onPick} title={title} like={like} actionIcon={actionIcon} close={close} />)+// `backups`: the slot's planned substitutes (lib/routine-backups.js), listed first in a swap.+export const exercisePicker = (onPick, { title, like, actionIcon, backups } = {}) => ui().openSheet(close => <ExercisePicker onPick={onPick} title={title} like={like} actionIcon={actionIcon} backups={backups} close={close} />)/** Start a safe swap for one exact active-workout occurrence. */export function swapActiveWorkoutExercise(index) {@@ -1427,7 +1436,7 @@ export function swapActiveWorkoutExercise(index) {// The "+" on a picker row commits with the default config, exactly as it does in the add// flows; tapping the row still opens the config sheet first.// Worded for the session, not the routine: a swap changes today's workout only.- const picker = exercisePicker((ex, quick) => quick ? swapTo(ex, defaultConfig(ex.id)) : exConfigSheet(ex, null, cfg => swapTo(ex, cfg), null, null, null, null, t('Use in this workout')), { title: t('Swap exercise'), like: active.entries[index].id })+ const picker = exercisePicker((ex, quick) => quick ? swapTo(ex, defaultConfig(ex.id)) : exConfigSheet(ex, null, cfg => swapTo(ex, cfg), null, null, null, null, t('Use in this workout')), { title: t('Swap exercise'), like: active.entries[index].id, backups: active.entries[index].target?.subs })function swapTo(ex, cfg) {// The picker is a chooser here, not a stack you keep adding from: one swap, then back to// the workout. (The add flow deliberately leaves it open.)@@ -1657,7 +1666,34 @@ const intensifierToSave = x => (x.type === 'dropset'? { ...x, totalReps: Math.max(1, Math.round(x.totalReps) || 0), restSec: Math.max(5, Number(x.restSec) || 0) }: x)-function ExConfig({ ex, existing, onSave, onDelete, onReplace, close, routine, initial, saveLabel }) {+// The slot's planned substitutes: listed, each removable, and added from the library (the same+// picker a swap uses, opened on the same muscle).+function BackupsSheet({ ex, subs: initial, onChange, close }) {+ const [subs, setSubs] = useState(() => cleanBackups(initial, ex.id, id => !!EXIDX[id]))+ const set = next => { setSubs(next); onChange(next) }+ const add = () => {+ const picker = exercisePicker((pick) => {+ picker.close()+ set(cleanBackups([...subs, pick.id], ex.id, id => !!EXIDX[id]))+ }, { title: t('Add a backup'), like: ex.id })+ }+ return <>+ <h3>{t('Backups for {0}', exerciseNameFor(ex))}</h3>+ <div className="muted small" style={{ marginBottom: 12 }}>{t('Machine taken? Pick what you’d do instead, and a swap mid-workout offers these first.')}</div>+ {subs.length > 0 && <div className="sect-b" style={{ marginBottom: 12 }}>+ {subs.map(id => EXIDX[id]).filter(Boolean).map(b => <Row key={b.id} title={exerciseNameFor(b)} subtitle={t(b.eq)}>+ <button type="button" className="iconbtn" aria-label={t('Remove “{0}”', exerciseNameFor(b))} onClick={() => set(subs.filter(x => x !== b.id))}><Icon name="xmark" /></button>+ </Row>)}+ </div>}+ {subs.length < MAX_BACKUPS+ ? <Button icon="plus" onClick={add}>{t('Add a backup')}</Button>+ : <div className="small dim">{t('That’s plenty of backups.')}</div>}+ <div style={{ height: 8 }} />+ <Button variant="ghost" className="dim" onClick={close}>{t('Done')}</Button>+ </>+}++function ExConfig({ ex, existing, onSave, onDelete, onReplace, close, routine, initial, saveLabel, backupsEditable }) {const st = useStore(s => s.S)const cardio = isCardio(ex.id)const speedUnit = speedUnitOf(st)@@ -1739,12 +1775,15 @@ function ExConfig({ ex, existing, onSave, onDelete, onReplace, close, routine, i// The warm-ups' own rest and the break between sides (Discord "set-specific rest timers"):// optional fields, written only when chosen, so a config that never touched them keeps its// exact shape and rests as it always did (lib/supersetFlow.js warmupRestSecFor, sideRestFor).+ // Planned substitutes (lib/routine-backups.js): kept whenever the slot has them, whichever+ // sheet saves it, so an edit here never drops them; only real exercises, never itself.+ const withSubs = withBackups(c.subs, ex.id, id => !!EXIDX[id])const withSetRests = {...(c.warmupRestOff === true ? { warmupRestOff: true } : c.warmupRestSec > 0 ? { warmupRestSec: Math.round(c.warmupRestSec) } : {}),...(perSide && c.sideRestSec > 0 ? { sideRestSec: Math.round(c.sideRestSec) } : {}),}- if (cardio) onSave({ sets, min: Math.max(1, Math.round(c.min) || 20), speed: Math.max(0, c.speed || 8), ...withNote, ...withRest })- else if (mode === 'time') onSave({ sets, mode: 'time', sec: Math.max(1, Math.round(c.sec) || 45), weight: Math.max(0, c.weight || 0), ...flags, ...(perSide ? { side: true } : {}), ...prog, ...withNote, ...withWarmups, ...withRest, ...withSetRests, ...withMeant, ...withFailure })+ if (cardio) onSave({ sets, min: Math.max(1, Math.round(c.min) || 20), speed: Math.max(0, c.speed || 8), ...withNote, ...withRest, ...withSubs })+ else if (mode === 'time') onSave({ sets, mode: 'time', sec: Math.max(1, Math.round(c.sec) || 45), weight: Math.max(0, c.weight || 0), ...flags, ...(perSide ? { side: true } : {}), ...prog, ...withNote, ...withWarmups, ...withRest, ...withSetRests, ...withMeant, ...withFailure, ...withSubs })else {// A unilateral target is stored even: the split has to divide, and a typed 15 would// otherwise plan seven reps on one side and eight on the other, every session.@@ -1756,7 +1795,7 @@ function ExConfig({ ex, existing, onSave, onDelete, onReplace, close, routine, irange = normalizeRepRange(reps, c.repsMin, stride)reps = range.reps}- const out = { sets, mode: 'reps', reps, weight: Math.max(0, c.weight || 0), ...flags, ...(perSide ? { side: true } : {}), ...prog, ...withNote, ...withWarmups, ...withRest, ...withSetRests, ...withMeant }+ const out = { sets, mode: 'reps', reps, weight: Math.max(0, c.weight || 0), ...flags, ...(perSide ? { side: true } : {}), ...prog, ...withNote, ...withWarmups, ...withRest, ...withSetRests, ...withMeant, ...withSubs }// The list is the prescription; sets and reps follow it, so everything that reads the// flat target (a config sheet reopened with the toggle off, older builds) still makes sense.const list = pyramid ? normalizePyramid(c.pyramid, stride) : []@@ -1948,6 +1987,19 @@ function ExConfig({ ex, existing, onSave, onDelete, onReplace, close, routine, i{t('A breather after one side, before the other. The full rest comes once both sides are done.')}</div></>}+ {/* Planned substitutes for this slot, in the routine editor: what the swap sheet offers first+ when the machine is taken. */}+ {backupsEditable && <>+ <div className="sect-b" style={{ marginBottom: 6 }}>+ <Row icon="swap" iconTint="var(--teal)" title={t('Backups')} accessory="chevron"+ value={(c.subs || []).length ? String((c.subs || []).filter(id => EXIDX[id]).length) : t('None')}+ subtitle={(c.subs || []).map(id => EXIDX[id]).filter(Boolean).map(exerciseNameFor).join(', ') || undefined}+ onClick={() => ui().openSheet(done => <BackupsSheet ex={ex} subs={c.subs || []} onChange={subs => setC(x => ({ ...x, subs }))} close={done} />)} />+ </div>+ <div className="small dim" style={{ marginBottom: 18 }}>+ {t('Machine taken? Pick what you’d do instead, and a swap mid-workout offers these first.')}+ </div>+ </>}{/* ---------- bodyweight + per side (issues #31/#32/#33) ---------- */}{!cardio && <div className="sect-b" style={{ marginBottom: 8 }}><Row icon="figureStrength" iconTint="var(--acc)" title={t('Bodyweight')}@@ -2078,7 +2130,8 @@ function ExConfig({ ex, existing, onSave, onDelete, onReplace, close, routine, i{onDelete && <><div style={{ height: 8 }} /><Button variant="danger" onClick={() => { close(); onDelete() }}>{t('Remove from routine')}</Button></>}</>}-export const exConfigSheet = (ex, existing, onSave, onDelete, routine, initial, onReplace, saveLabel) => ui().openSheet(close => <ExConfig ex={ex} existing={existing} initial={initial} onSave={onSave} onDelete={onDelete} onReplace={onReplace} routine={routine} saveLabel={saveLabel} close={close} />)+// `opts.backups`: the routine editor's sheet, where the slot's planned substitutes are picked.+export const exConfigSheet = (ex, existing, onSave, onDelete, routine, initial, onReplace, saveLabel, opts = {}) => ui().openSheet(close => <ExConfig ex={ex} existing={existing} initial={initial} onSave={onSave} onDelete={onDelete} onReplace={onReplace} routine={routine} saveLabel={saveLabel} backupsEditable={!!opts.backups} close={close} />)/* ============================ glyph picker ============================ */// Grouped by what the glyph means for a training day, so picking one is a scandiff --git a/frontend/src/views/RoutineEdit.jsx b/frontend/src/views/RoutineEdit.jsxindex 9bc34490b..65b86f275 100644--- a/frontend/src/views/RoutineEdit.jsx+++ b/frontend/src/views/RoutineEdit.jsx@@ -415,8 +415,8 @@ export default function RoutineEdit() {if (quick && ex.id === openedOn) { picker.close(); return }if (quick) { commit(ex, current => replaceSlotExercise(current, ex.id, live, id)); return }const next = replaceSlotExercise(slot, ex.id, live, id)- exConfigSheet(ex, next, cfg => commit(ex, current => ({ id: ex.id, sg: current.sg, ...cfg })), null, r, null, null, t('Replace'))- }, { title: t('Replace exercise'), like: openedOn })+ exConfigSheet(ex, next, cfg => commit(ex, current => ({ id: ex.id, sg: current.sg, ...cfg })), null, r, null, null, t('Replace'), { backups: true })+ }, { title: t('Replace exercise'), like: openedOn, backups: r.ex[i]?.subs })}// This routine on paper (#282): the weekly printout's page for one session, through the same// two print paths — the browser's print dialog (→ Save as PDF) on the web, the native Print@@ -441,7 +441,7 @@ export default function RoutineEdit() {edit(x => x.push({ id: ex.id, ...defaultConfig(ex.id) }))toast(t('“{0}” added to {1}', exerciseNameText(ex), r.name))} else {- exConfigSheet(ex, null, cfg => edit(x => { x.push({ id: ex.id, ...cfg }) }), null, r)+ exConfigSheet(ex, null, cfg => edit(x => { x.push({ id: ex.id, ...cfg }) }), null, r, null, null, undefined, { backups: true })}})@@ -526,7 +526,7 @@ export default function RoutineEdit() {// screen reader would lose inside one): the name is, a real <button> a click bubbles up// from. The long press treats it as the row (data-row-open, useRoutineReorder).const item = <div className={'item' + (inSS.has(i) ? ' in-ss' : '')} onClick={() => {- exConfigSheet(ex, e, cfg => edit(x => { x[i] = { id: x[i].id, sg: x[i].sg, ...(x[i].sg ? { sgName: x[i].sgName, sgRest: x[i].sgRest } : {}), ...cfg }; cleanupSg(x) }), removeHere, r, null, () => replace(i))+ exConfigSheet(ex, e, cfg => edit(x => { x[i] = { id: x[i].id, sg: x[i].sg, ...(x[i].sg ? { sgName: x[i].sgName, sgRest: x[i].sgRest } : {}), ...cfg }; cleanupSg(x) }), removeHere, r, null, () => replace(i), undefined, { backups: true })}}>{/* Shown on pointer devices only (index.css .routine-grip); the Move buttons and thelong press stay the way in for a keyboard and a finger. */}