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.

Starter plans: fit a plan to an equipment profile

Pawel4fc1c86ff8b5
diff --git a/frontend/src/lib/equipment.js b/frontend/src/lib/equipment.js
index a926a1e04..b9bc7f0f7 100644
--- a/frontend/src/lib/equipment.js
+++ b/frontend/src/lib/equipment.js
@@ -25,11 +25,16 @@ export function activeProfile(S) {
export function exAvailable(S, ex) {
const p = activeProfile(S)
if (!p) return true
+ return eqAvailable(p.equipment, ex)
+}
+
+// The same test against a bare equipment list, for callers that hold a profile rather than S.
+export function eqAvailable(equipment, ex) {
if (!ex.eq || ex.eq === ALWAYS_AVAILABLE) return true
// Equipment no profile can tick (an imported exercise's "custom") would hide the user's own
// exercise under every profile, with no way to bring it back. It stays, like body weight.
if (!ALL_EQUIPMENT.includes(ex.eq)) return true
- return (p.equipment || []).includes(ex.eq)
+ return (equipment || []).includes(ex.eq)
}
export function newProfile(name) {
diff --git a/frontend/src/lib/starter.js b/frontend/src/lib/starter.js
index e8ba7041a..041712334 100644
--- a/frontend/src/lib/starter.js
+++ b/frontend/src/lib/starter.js
@@ -6,6 +6,8 @@
// schedule points at, so a weekday never depends on the position of a routine in the array.
// Names stay canonical English — they become ordinary user routines, which are not translated.
import { uid } from './format.js'
+import { EXIDX } from './exercises.js'
+import { eqAvailable, ALL_EQUIPMENT } from './equipment.js'
const PPL = [
['push', 'Push Day', 'barbell', [['0025', 4, 8], ['0047', 3, 10], ['0426', 3, 10], ['0334', 3, 12], ['0241', 3, 12], ['0251', 3, 10]]],
@@ -56,13 +58,80 @@ export const starterPlanOptions = () =>
// The weekdays a plan would claim, or null for an unknown id.
export const starterPlanDays = id => PLANS[id]?.schedule.map(([day]) => day) ?? null
+// Words that name the equipment, not the movement ("barbell", "lever", "machine"…), so that
+// "barbell bench press" and "dumbbell bench press" read as the same lift.
+const EQ_WORDS = new Set(ALL_EQUIPMENT.flatMap(e => e.split(/[^a-z0-9]+/)).concat(['lever', 'leverage', 'machine', 'sled']))
+const words = ex => new Set(ex.n.toLowerCase().split(/[^a-z0-9]+/).filter(w => w && !EQ_WORDS.has(w)))
+const jaccard = (a, b) => {
+ const inter = [...a].filter(x => b.has(x)).length
+ return inter ? inter / (a.size + b.size - inter) : 0
+}
+
+// Names that are not working sets: stretches, holds, mobility and warm-up drills. Never a
+// stand-in for a lift, whatever body part and muscle they share with it.
+const NOT_A_LIFT = /stretch|isometric|squeeze|yoga|\bpose\b|toe touch|\broll(er)?\b|mobility|circles|warm-?up|boxing|against wall/i
+// "… on exercise ball" is tagged with its weight (dumbbell), but needs a ball nobody ticked.
+const NEEDS_BALL = /exercise ball|stability ball|swiss ball|bosu/i
+
+// The best stand-in for `ex` among exercises the equipment list allows. Same body part, and it
+// has to share the target muscle, the main muscle or a helper muscle with `ex`. Closest wins:
+// same target muscle, then the movement by name, then helper muscles. When `ex` is a loaded
+// lift, one that is loaded too beats a body-weight drill — a push-up is not a bench press.
+// `taken` keeps a routine from ending up with the same exercise twice. null when nothing fits.
+export const substituteFor = (ex, equipment, taken) => {
+ const hasBall = equipment.includes('stability ball') || equipment.includes('bosu ball')
+ const exWords = words(ex), exSm = new Set([ex.mg, ...(ex.sm || [])])
+ const loaded = ex.eq !== 'body weight'
+ let best = null, bestScore = -Infinity
+ for (const c of Object.values(EXIDX)) {
+ if (c.bp !== ex.bp || taken.has(c.id) || !eqAvailable(equipment, c)) continue
+ if (NOT_A_LIFT.test(c.n) || (!hasBall && NEEDS_BALL.test(c.n))) continue
+ const sm = jaccard(exSm, new Set([c.mg, ...(c.sm || [])]))
+ if (c.tg !== ex.tg && c.mg !== ex.mg && !sm) continue
+ const score = 2 * (c.tg === ex.tg) + (c.mg === ex.mg) + 3 * jaccard(exWords, words(c)) + 2 * sm
+ - (loaded && c.eq === 'body weight' ? 3 : 0)
+ // id as the last key: the same equipment always gives the same plan
+ if (score > bestScore || (score === bestScore && c.id < best.id)) { best = c; bestScore = score }
+ }
+ return best
+}
+
+// Re-cuts a routine list for an equipment list: what you can already do stays, what you can't
+// is swapped for its closest match, and what has no match is dropped (with its routine, when
+// that leaves it empty). Sets and reps carry over unchanged.
+const fitRoutines = (routines, equipment) => {
+ let swapped = 0, dropped = 0
+ const fitted = routines.map(([key, name, emoji, list]) => {
+ const taken = new Set(list.map(([id]) => id))
+ const out = []
+ for (const [id, sets, reps] of list) {
+ const ex = EXIDX[id]
+ if (!ex || eqAvailable(equipment, ex)) { out.push([id, sets, reps]); continue }
+ const sub = substituteFor(ex, equipment, taken)
+ if (!sub) { dropped++; continue }
+ taken.add(sub.id)
+ swapped++
+ out.push([sub.id, sets, reps])
+ }
+ return [key, name, emoji, out]
+ }).filter(([, , , list]) => list.length)
+ return { routines: fitted, swapped, dropped }
+}
+
// Fresh routines plus the weekdays to put them on, or null for an unknown id — a caller that
-// treats null as "change nothing" can never half-apply a plan.
-export const buildStarterPlan = id => {
+// treats null as "change nothing" can never half-apply a plan. With an equipment list the
+// plan is fitted to it first, and `fit` reports how many exercises that swapped or dropped.
+export const buildStarterPlan = (id, equipment) => {
const plan = PLANS[id]
if (!plan) return null
- const routines = build(plan.routines)
+ const fit = equipment ? fitRoutines(plan.routines, equipment) : null
+ const source = fit ? fit.routines : plan.routines
+ const routines = build(source)
// key → the id just minted for it, so the schedule below names its routine
- const byKey = Object.fromEntries(plan.routines.map(([key], i) => [key, routines[i].id]))
- return { routines, schedule: plan.schedule.map(([day, key]) => ({ day, routineId: byKey[key] })) }
+ const byKey = Object.fromEntries(source.map(([key], i) => [key, routines[i].id]))
+ return {
+ routines,
+ schedule: plan.schedule.filter(([, key]) => byKey[key]).map(([day, key]) => ({ day, routineId: byKey[key] })),
+ ...(fit && { fit: { swapped: fit.swapped, dropped: fit.dropped } })
+ }
}
diff --git a/frontend/src/lib/starter.test.js b/frontend/src/lib/starter.test.js
index 804c021f3..702773c58 100644
--- a/frontend/src/lib/starter.test.js
+++ b/frontend/src/lib/starter.test.js
@@ -1,5 +1,6 @@
import { describe, expect, it } from 'vitest'
import { EXIDX } from './exercises.js'
+import { ALL_EQUIPMENT, eqAvailable } from './equipment.js'
import { buildStarterPlan, starterPlanDays, starterPlanOptions, starterRoutines } from './starter.js'
// The approved prescription, written out again rather than imported: a test that reads the
@@ -102,3 +103,87 @@ describe('starterRoutines (the demo build entry point)', () => {
expect(new Set([...first, ...second]).size).toBe(6)
})
})
+
+describe('fitting a starter plan to equipment', () => {
+ const ids = plan => plan.routines.flatMap(r => r.ex.map(e => e.id))
+
+ it('changes nothing when the equipment already covers the plan', () => {
+ const all = ALL_EQUIPMENT
+ const fitted = buildStarterPlan('ppl', all)
+ expect(fitted.routines.map(shape)).toEqual(APPROVED.ppl.map(([, , list]) => list))
+ expect(fitted.fit).toEqual({ swapped: 0, dropped: 0 })
+ })
+
+ it('has no fit report when no equipment is given', () => {
+ expect(buildStarterPlan('ppl').fit).toBeUndefined()
+ })
+
+ it('swaps only what the equipment cannot do, keeping sets and reps', () => {
+ const fitted = buildStarterPlan('ppl', ['dumbbell'])
+ const push = fitted.routines[0]
+ // dumbbell exercises stay put; the barbell bench and the cable pushdown are swapped
+ expect(push.ex.map(e => e.id)).toContain('0426')
+ expect(push.ex.map(e => e.id)).toContain('0334')
+ expect(push.ex[0].id).not.toBe('0025')
+ expect(push.ex[0].sets).toBe(4)
+ expect(push.ex[0].reps).toBe(8)
+ expect(fitted.fit.swapped).toBeGreaterThan(0)
+ })
+
+ it('only ever uses exercises the equipment allows (body weight is always allowed)', () => {
+ for (const eq of [['dumbbell'], ['barbell', 'dumbbell'], ['band'], []]) {
+ for (const { id } of starterPlanOptions()) {
+ const fitted = buildStarterPlan(id, eq)
+ for (const exId of ids(fitted)) expect(eqAvailable(eq, EXIDX[exId])).toBe(true)
+ }
+ }
+ })
+
+ it('never repeats an exercise inside one routine', () => {
+ for (const eq of [['dumbbell'], ['band'], []]) {
+ for (const { id } of starterPlanOptions()) {
+ for (const r of buildStarterPlan(id, eq).routines) {
+ const own = r.ex.map(e => e.id)
+ expect(new Set(own).size).toBe(own.length)
+ }
+ }
+ }
+ })
+
+ it('never stands in with a stretch, a hold or a drill that needs a ball nobody ticked', () => {
+ const bad = /stretch|isometric|squeeze|yoga|toe touch|exercise ball|bosu/i
+ for (const eq of [['dumbbell'], ['dumbbell'], ['band'], []]) {
+ for (const { id } of starterPlanOptions()) {
+ for (const exId of ids(buildStarterPlan(id, eq))) expect(EXIDX[exId].n).not.toMatch(bad)
+ }
+ }
+ })
+
+ it('prefers a loaded exercise over a body-weight drill for a loaded lift', () => {
+ // leg extension has no dumbbell twin, so the nearest same-muscle options include plain
+ // body-weight drills; a loaded leg exercise still wins
+ const legs = buildStarterPlan('ppl', ['dumbbell']).routines.find(r => r.name === 'Leg Day')
+ const swappedIn = legs.ex[3]
+ expect(swappedIn.id).not.toBe('0585')
+ expect(EXIDX[swappedIn.id].eq).toBe('dumbbell')
+ expect(EXIDX[swappedIn.id].bp).toBe('upper legs')
+ })
+
+ it('swaps a barbell bench press for chest work with the same kit, not a push-up', () => {
+ const push = buildStarterPlan('ppl', ['dumbbell']).routines[0]
+ expect(EXIDX[push.ex[0].id].eq).toBe('dumbbell')
+ expect(EXIDX[push.ex[0].id].bp).toBe('chest')
+ })
+
+ it('is deterministic', () => {
+ const a = buildStarterPlan('upper-lower', ['dumbbell']).routines.map(shape)
+ const b = buildStarterPlan('upper-lower', ['dumbbell']).routines.map(shape)
+ expect(a).toEqual(b)
+ })
+
+ it('keeps every scheduled day pointing at a routine that exists', () => {
+ const fitted = buildStarterPlan('5x5', [])
+ const have = new Set(fitted.routines.map(r => r.id))
+ for (const { routineId } of fitted.schedule) expect(have.has(routineId)).toBe(true)
+ })
+})
diff --git a/frontend/src/locales/ar.js b/frontend/src/locales/ar.js
index b92f6745e..d34b6aa01 100644
--- a/frontend/src/locales/ar.js
+++ b/frontend/src/locales/ar.js
@@ -1187,6 +1187,10 @@ export default {
'Set up your weekly routine to get going, or grab a ready-made starter plan.': 'جهّز روتينك الأسبوعي للبدء، أو خذ خطة بداية جاهزة.',
'Load starter plan': 'تحميل خطة البداية',
'Choose starter plan': 'اختر خطة البداية',
+ 'Fit to my equipment': 'خصّص لمعداتي',
+ 'As written': 'كما هي',
+ 'Add an equipment profile in Settings to fit a plan to what you own.': 'أضف ملف معدات في الإعدادات لتكييف الخطة مع ما تملكه.',
+ '{0} loaded, fitted to "{1}": {2} swapped, {3} dropped': 'تم تحميل {0} وتكييفها مع «{1}»: استُبدل {2}، وحُذف {3}',
'{0} days per week': '{0} أيام في الأسبوع',
'{0} loaded': '{0} محمّلة',
'Load {0}?': 'تحميل {0}؟',
diff --git a/frontend/src/locales/de.js b/frontend/src/locales/de.js
index 7fdb20e04..fff2f2790 100644
--- a/frontend/src/locales/de.js
+++ b/frontend/src/locales/de.js
@@ -234,6 +234,10 @@ export default {
'Set up your weekly routine to get going, or grab a ready-made starter plan.': 'Richte deinen Wochenplan ein, um loszulegen, oder schnapp dir einen fertigen Starterplan.',
'Load starter plan': 'Starterplan laden',
'Choose starter plan': 'Starterplan wählen',
+ 'Fit to my equipment': 'An meine Ausrüstung anpassen',
+ 'As written': 'Wie vorgegeben',
+ 'Add an equipment profile in Settings to fit a plan to what you own.': 'Lege in den Einstellungen ein Ausrüstungsprofil an, um einen Plan an dein Equipment anzupassen.',
+ '{0} loaded, fitted to "{1}": {2} swapped, {3} dropped': '{0} geladen, angepasst an „{1}“: {2} ersetzt, {3} entfernt',
'{0} days per week': '{0} Tage pro Woche',
'{0} loaded': '{0} geladen',
'Load {0}?': '{0} laden?',
diff --git a/frontend/src/locales/es.js b/frontend/src/locales/es.js
index 592a333e1..0091edcd6 100644
--- a/frontend/src/locales/es.js
+++ b/frontend/src/locales/es.js
@@ -225,6 +225,10 @@ export default {
'Set up your weekly routine to get going, or grab a ready-made starter plan.': 'Configura tu rutina semanal para arrancar, o carga un plan inicial ya hecho.',
'Load starter plan': 'Cargar plan inicial',
'Choose starter plan': 'Elige un plan inicial',
+ 'Fit to my equipment': 'Adaptar a mi equipo',
+ 'As written': 'Tal cual',
+ 'Add an equipment profile in Settings to fit a plan to what you own.': 'Añade un perfil de equipamiento en Ajustes para adaptar un plan a lo que tienes.',
+ '{0} loaded, fitted to "{1}": {2} swapped, {3} dropped': '{0} cargado y adaptado a «{1}»: {2} cambiados, {3} quitados',
'{0} days per week': '{0} días por semana',
'{0} loaded': '{0} cargado',
'Load {0}?': '¿Cargar {0}?',
diff --git a/frontend/src/locales/fr.js b/frontend/src/locales/fr.js
index a6c2a3d84..7ca5079a5 100644
--- a/frontend/src/locales/fr.js
+++ b/frontend/src/locales/fr.js
@@ -225,6 +225,10 @@ export default {
'Set up your weekly routine to get going, or grab a ready-made starter plan.': 'Configure ta routine hebdo pour te lancer, ou prends un plan de départ tout prêt.',
'Load starter plan': 'Charger un plan de départ',
'Choose starter plan': 'Choisis un plan de départ',
+ 'Fit to my equipment': 'Adapter à mon matériel',
+ 'As written': 'Tel quel',
+ 'Add an equipment profile in Settings to fit a plan to what you own.': 'Ajoute un profil de matériel dans les Réglages pour adapter un plan à ce que tu possèdes.',
+ '{0} loaded, fitted to "{1}": {2} swapped, {3} dropped': '{0} chargé et adapté à « {1} » : {2} remplacés, {3} retirés',
'{0} days per week': '{0} jours par semaine',
'{0} loaded': '{0} chargé',
'Load {0}?': 'Charger {0} ?',
diff --git a/frontend/src/locales/hi.js b/frontend/src/locales/hi.js
index 8c05a4933..1703cf821 100644
--- a/frontend/src/locales/hi.js
+++ b/frontend/src/locales/hi.js
@@ -225,6 +225,10 @@ export default {
'Set up your weekly routine to get going, or grab a ready-made starter plan.': 'शुरू करने के लिए अपना साप्ताहिक रूटीन बनाएँ, या बना-बनाया स्टार्टर प्लान ले लें।',
'Load starter plan': 'स्टार्टर प्लान लोड करें',
'Choose starter plan': 'स्टार्टर प्लान चुनें',
+ 'Fit to my equipment': 'मेरे उपकरणों के अनुसार ढालें',
+ 'As written': 'जैसा है वैसा',
+ 'Add an equipment profile in Settings to fit a plan to what you own.': 'अपने पास मौजूद उपकरणों के अनुसार प्लान ढालने के लिए सेटिंग्स में उपकरण प्रोफ़ाइल जोड़ें।',
+ '{0} loaded, fitted to "{1}": {2} swapped, {3} dropped': '{0} लोड हुआ, "{1}" के अनुसार ढाला गया: {2} बदले, {3} हटाए',
'{0} days per week': 'हफ़्ते में {0} दिन',
'{0} loaded': '{0} लोड हुआ',
'Load {0}?': '{0} लोड करें?',
diff --git a/frontend/src/locales/hu.js b/frontend/src/locales/hu.js
index 3b8a3698f..f75ea53f1 100644
--- a/frontend/src/locales/hu.js
+++ b/frontend/src/locales/hu.js
@@ -224,6 +224,10 @@ export default {
'Set up your weekly routine to get going, or grab a ready-made starter plan.': 'Állítsd be a heti rutinodat az induláshoz, vagy kapj elő egy kész kezdő tervet.',
'Load starter plan': 'Kezdő terv betöltése',
'Choose starter plan': 'Válassz kezdő tervet',
+ 'Fit to my equipment': 'Igazítás a felszerelésemhez',
+ 'As written': 'Eredeti',
+ 'Add an equipment profile in Settings to fit a plan to what you own.': 'Adj hozzá felszerelésprofilt a Beállításokban, hogy a tervet ahhoz igazítsd, amid van.',
+ '{0} loaded, fitted to "{1}": {2} swapped, {3} dropped': '{0} betöltve, „{1}” profilhoz igazítva: {2} cserélve, {3} kihagyva',
'{0} days per week': 'Heti {0} nap',
'{0} loaded': '{0} betöltve',
'Load {0}?': 'Betöltöd: {0}?',
diff --git a/frontend/src/locales/it.js b/frontend/src/locales/it.js
index 81f392217..206c0559c 100644
--- a/frontend/src/locales/it.js
+++ b/frontend/src/locales/it.js
@@ -225,6 +225,10 @@ export default {
'Set up your weekly routine to get going, or grab a ready-made starter plan.': 'Imposta la tua routine settimanale per iniziare, o prendi un piano iniziale già pronto.',
'Load starter plan': 'Carica piano iniziale',
'Choose starter plan': 'Scegli un piano iniziale',
+ 'Fit to my equipment': 'Adatta alla mia attrezzatura',
+ 'As written': 'Così com\'è',
+ 'Add an equipment profile in Settings to fit a plan to what you own.': 'Aggiungi un profilo attrezzatura nelle Impostazioni per adattare una scheda a ciò che hai.',
+ '{0} loaded, fitted to "{1}": {2} swapped, {3} dropped': '{0} caricato e adattato a «{1}»: {2} sostituiti, {3} rimossi',
'{0} days per week': '{0} giorni a settimana',
'{0} loaded': '{0} caricato',
'Load {0}?': 'Caricare {0}?',
diff --git a/frontend/src/locales/ko.js b/frontend/src/locales/ko.js
index fc4f356c8..1d3d66263 100644
--- a/frontend/src/locales/ko.js
+++ b/frontend/src/locales/ko.js
@@ -225,6 +225,10 @@ export default {
'Set up your weekly routine to get going, or grab a ready-made starter plan.': '주간 루틴을 설정해 시작하거나, 미리 만들어진 스타터 계획을 가져오세요.',
'Load starter plan': '스타터 계획 불러오기',
'Choose starter plan': '스타터 계획 선택',
+ 'Fit to my equipment': '내 장비에 맞추기',
+ 'As written': '그대로',
+ 'Add an equipment profile in Settings to fit a plan to what you own.': '보유한 장비에 맞게 계획을 조정하려면 설정에서 장비 프로필을 추가하세요.',
+ '{0} loaded, fitted to "{1}": {2} swapped, {3} dropped': '{0} 불러옴, "{1}"에 맞춤: {2}개 교체, {3}개 제외',
'{0} days per week': '주 {0}일',
'{0} loaded': '{0} 불러옴',
'Load {0}?': '{0} 불러올까요?',
diff --git a/frontend/src/locales/pl.js b/frontend/src/locales/pl.js
index 92579d18f..23a6a8045 100644
--- a/frontend/src/locales/pl.js
+++ b/frontend/src/locales/pl.js
@@ -225,6 +225,10 @@ export default {
'Set up your weekly routine to get going, or grab a ready-made starter plan.': 'Ustaw swój tygodniowy plan, żeby zacząć, albo wczytaj gotowy plan startowy.',
'Load starter plan': 'Wczytaj plan startowy',
'Choose starter plan': 'Wybierz plan startowy',
+ 'Fit to my equipment': 'Dopasuj do mojego sprzętu',
+ 'As written': 'Bez zmian',
+ 'Add an equipment profile in Settings to fit a plan to what you own.': 'Dodaj profil sprzętu w Ustawieniach, aby dopasować plan do tego, co masz.',
+ '{0} loaded, fitted to "{1}": {2} swapped, {3} dropped': '{0} wczytany i dopasowany do „{1}”: zamieniono {2}, pominięto {3}',
'{0} days per week': '{0} dni w tygodniu',
'{0} loaded': 'Wczytano: {0}',
'Load {0}?': 'Wczytać {0}?',
diff --git a/frontend/src/locales/pt-BR.js b/frontend/src/locales/pt-BR.js
index c2c52d5f7..af00cc3a9 100644
--- a/frontend/src/locales/pt-BR.js
+++ b/frontend/src/locales/pt-BR.js
@@ -98,6 +98,10 @@ export const PT_BR_OVERRIDES = {
'Freestyle workout. Add your first exercise and off you go.': 'Treino livre. Adicione seu primeiro exercício e bora.',
'Set up your weekly routine to get going, or grab a ready-made starter plan.': 'Configure sua rotina semanal para começar, ou pegue um plano inicial já pronto.',
'Choose starter plan': 'Escolha um plano inicial',
+ 'Fit to my equipment': 'Adaptar ao meu equipamento',
+ 'As written': 'Do jeito que está',
+ 'Add an equipment profile in Settings to fit a plan to what you own.': 'Adicione um perfil de equipamento em Ajustes para adaptar um plano ao que você tem.',
+ '{0} loaded, fitted to "{1}": {2} swapped, {3} dropped': '{0} carregado e adaptado a "{1}": {2} trocados, {3} removidos',
'The new plan goes on {0}. Your existing routines stay; only those days of the weekly plan change.': 'O novo plano fica em {0}. Suas rotinas continuam; só esses dias do plano semanal mudam.',
'Push / Pull / Legs': 'Push / Pull / Legs',
'Build my own plan': 'Criar meu próprio plano',
diff --git a/frontend/src/locales/pt.js b/frontend/src/locales/pt.js
index ad06595ac..0578e1fcf 100644
--- a/frontend/src/locales/pt.js
+++ b/frontend/src/locales/pt.js
@@ -225,6 +225,10 @@ export default {
'Set up your weekly routine to get going, or grab a ready-made starter plan.': 'Configura a tua rotina semanal para começar, ou pega num plano inicial já feito.',
'Load starter plan': 'Carregar plano inicial',
'Choose starter plan': 'Escolhe um plano inicial',
+ 'Fit to my equipment': 'Adaptar ao meu equipamento',
+ 'As written': 'Tal como está',
+ 'Add an equipment profile in Settings to fit a plan to what you own.': 'Adiciona um perfil de equipamento nas Definições para adaptar um plano ao que tens.',
+ '{0} loaded, fitted to "{1}": {2} swapped, {3} dropped': '{0} carregado e adaptado a «{1}»: {2} trocados, {3} removidos',
'{0} days per week': '{0} dias por semana',
'{0} loaded': '{0} carregado',
'Load {0}?': 'Carregar {0}?',
diff --git a/frontend/src/locales/ru.js b/frontend/src/locales/ru.js
index 576e5cbe6..6d0ccd43f 100644
--- a/frontend/src/locales/ru.js
+++ b/frontend/src/locales/ru.js
@@ -219,6 +219,10 @@ export default {
'Set up your weekly routine to get going, or grab a ready-made starter plan.': 'Настрой свой недельный план, чтобы начать, или возьми готовый стартовый план.',
'Load starter plan': 'Загрузить стартовый план',
'Choose starter plan': 'Выбери стартовый план',
+ 'Fit to my equipment': 'Подогнать под моё оборудование',
+ 'As written': 'Как есть',
+ 'Add an equipment profile in Settings to fit a plan to what you own.': 'Добавь профиль оборудования в настройках, чтобы подогнать план под то, что у тебя есть.',
+ '{0} loaded, fitted to "{1}": {2} swapped, {3} dropped': '{0} загружен и подогнан под «{1}»: заменено {2}, убрано {3}',
'{0} days per week': 'Дней в неделю: {0}',
'{0} loaded': '{0} загружен',
'Load {0}?': 'Загрузить {0}?',
diff --git a/frontend/src/locales/th.js b/frontend/src/locales/th.js
index 1031f9448..f14dbdc4a 100644
--- a/frontend/src/locales/th.js
+++ b/frontend/src/locales/th.js
@@ -224,6 +224,10 @@ export default {
'Set up your weekly routine to get going, or grab a ready-made starter plan.': 'ตั้งค่ารูทีนรายสัปดาห์เพื่อเริ่มต้น หรือหยิบแผนเริ่มต้นสำเร็จรูปไปใช้ก็ได้',
'Load starter plan': 'โหลดแผนเริ่มต้น',
'Choose starter plan': 'เลือกแผนเริ่มต้น',
+ 'Fit to my equipment': 'ปรับให้เข้ากับอุปกรณ์ของฉัน',
+ 'As written': 'ตามเดิม',
+ 'Add an equipment profile in Settings to fit a plan to what you own.': 'เพิ่มโปรไฟล์อุปกรณ์ในการตั้งค่า เพื่อปรับแผนให้เข้ากับสิ่งที่คุณมี',
+ '{0} loaded, fitted to "{1}": {2} swapped, {3} dropped': 'โหลด {0} แล้ว ปรับให้เข้ากับ "{1}": เปลี่ยน {2} ตัด {3}',
'{0} days per week': 'สัปดาห์ละ {0} วัน',
'{0} loaded': 'โหลด {0} แล้ว',
'Load {0}?': 'โหลด {0} ไหม',
diff --git a/frontend/src/locales/tr.js b/frontend/src/locales/tr.js
index d6fa067cf..b2985ed00 100644
--- a/frontend/src/locales/tr.js
+++ b/frontend/src/locales/tr.js
@@ -225,6 +225,10 @@ export default {
'Set up your weekly routine to get going, or grab a ready-made starter plan.': 'Başlamak için haftalık rutinini kur ya da hazır bir başlangıç planı kap.',
'Load starter plan': 'Başlangıç planı yükle',
'Choose starter plan': 'Başlangıç planı seç',
+ 'Fit to my equipment': 'Ekipmanıma uyarla',
+ 'As written': 'Olduğu gibi',
+ 'Add an equipment profile in Settings to fit a plan to what you own.': 'Bir planı sahip olduklarına uyarlamak için Ayarlar\'da bir ekipman profili ekle.',
+ '{0} loaded, fitted to "{1}": {2} swapped, {3} dropped': '{0} yüklendi, "{1}" profiline uyarlandı: {2} değiştirildi, {3} çıkarıldı',
'{0} days per week': 'Haftada {0} gün',
'{0} loaded': '{0} yüklendi',
'Load {0}?': '{0} yüklensin mi?',
diff --git a/frontend/src/locales/uk.js b/frontend/src/locales/uk.js
index a4a775ede..704136098 100644
--- a/frontend/src/locales/uk.js
+++ b/frontend/src/locales/uk.js
@@ -231,6 +231,10 @@ export default {
'No routines yet.': 'Програм поки немає.',
'Make one, or grab the starter plan to get going.': 'Створи програму або візьми стартовий план, щоб почати.',
'Choose starter plan': 'Вибери стартовий план',
+ 'Fit to my equipment': 'Підібрати під моє обладнання',
+ 'As written': 'Як є',
+ 'Add an equipment profile in Settings to fit a plan to what you own.': 'Додай профіль обладнання в налаштуваннях, щоб підібрати план під те, що в тебе є.',
+ '{0} loaded, fitted to "{1}": {2} swapped, {3} dropped': '{0} завантажено й підібрано під «{1}»: замінено {2}, прибрано {3}',
'Superset with exercise above': 'Суперсет із вправою вище',
'Note (optional): loading cues, "bar only, then +1 plate/side each set", anything worth remembering': 'Нотатка (необов’язково): підказки щодо навантаження, напр. «лише гриф, потім +1 блин на сторону з кожним підходом», усе, що варто запам’ятати',
'No exercises yet. Add your first one!': 'Вправ поки немає. Додай першу!',
diff --git a/frontend/src/locales/zh-TW.js b/frontend/src/locales/zh-TW.js
index 0ab17d0bf..fbc55d0f1 100644
--- a/frontend/src/locales/zh-TW.js
+++ b/frontend/src/locales/zh-TW.js
@@ -221,6 +221,10 @@ export default {
'Set up your weekly routine to get going, or grab a ready-made starter plan.': '設定每週課表就能開始,或直接拿一份現成的初學者計畫。',
'Load starter plan': '載入初學者計畫',
'Choose starter plan': '選擇初學者計畫',
+ 'Fit to my equipment': '依我的器材調整',
+ 'As written': '保持原樣',
+ 'Add an equipment profile in Settings to fit a plan to what you own.': '在設定中新增器材設定檔,即可讓計畫配合你擁有的器材。',
+ '{0} loaded, fitted to "{1}": {2} swapped, {3} dropped': '已載入{0},並依「{1}」調整:替換 {2} 項,移除 {3} 項',
'{0} days per week': '每週 {0} 天',
'{0} loaded': '已載入 {0}',
'Load {0}?': '載入 {0}?',
diff --git a/frontend/src/locales/zh.js b/frontend/src/locales/zh.js
index 07765586e..e693054b1 100644
--- a/frontend/src/locales/zh.js
+++ b/frontend/src/locales/zh.js
@@ -225,6 +225,10 @@ export default {
'Set up your weekly routine to get going, or grab a ready-made starter plan.': '设置每周计划就能开始,或者直接拿一份现成的入门计划。',
'Load starter plan': '加载入门计划',
'Choose starter plan': '选择入门计划',
+ 'Fit to my equipment': '按我的器械调整',
+ 'As written': '保持原样',
+ 'Add an equipment profile in Settings to fit a plan to what you own.': '在设置中添加器械配置,即可让计划适配你拥有的器械。',
+ '{0} loaded, fitted to "{1}": {2} swapped, {3} dropped': '已加载{0},并按“{1}”调整:替换 {2} 项,移除 {3} 项',
'{0} days per week': '每周 {0} 天',
'{0} loaded': '已加载{0}',
'Load {0}?': '加载{0}?',
diff --git a/frontend/src/sheets.jsx b/frontend/src/sheets.jsx
index e5e4a6928..42132fdd1 100644
--- a/frontend/src/sheets.jsx
+++ b/frontend/src/sheets.jsx
@@ -166,21 +166,24 @@ const PLAN_COPY = {
// and only the weekdays the plan asks for are reassigned; an id with no plan behind it changes
// nothing at all. planId is deliberately required — a default invites `onClick={loadStarterPlan}`,
// which hands the click event in as the plan and silently loads nothing.
-export function loadStarterPlan(planId) {
- const plan = buildStarterPlan(planId)
+export function loadStarterPlan(planId, profile) {
+ const plan = buildStarterPlan(planId, profile?.equipment)
if (!plan) return false
update(st => {
- // Loading the same plan again reuses the routines it added last time (same name) for the
- // weekdays instead of a second Upper A, Lower A, ... under the same names.
+ // Loading the same plan again reuses the routines it added last time (same name, same
+ // exercises) for the weekdays instead of a second Upper A, Lower A, ... under the same names.
+ // A plan fitted to different equipment has other exercises, so it is added alongside.
const idOf = {}
+ const sameLift = (a, b) => a.ex.length === b.ex.length && a.ex.every((e, i) => e.id === b.ex[i].id)
plan.routines.forEach(r => {
- const have = st.routines.find(x => x.name === r.name)
+ const have = st.routines.find(x => x.name === r.name && sameLift(x, r))
if (have) idOf[r.id] = have.id
else { st.routines.push(r); idOf[r.id] = r.id }
})
plan.schedule.forEach(({ day, routineId }) => { st.week[day] = [idOf[routineId]] })
})
- toast(t('{0} loaded', PLAN_COPY[planId]().name))
+ if (plan.fit) toast(t('{0} loaded, fitted to "{1}": {2} swapped, {3} dropped', PLAN_COPY[planId]().name, profile.name, plan.fit.swapped, plan.fit.dropped))
+ else toast(t('{0} loaded', PLAN_COPY[planId]().name))
return true
}
@@ -190,22 +193,33 @@ const dayList = days => new Intl.ListFormat(dateLocale()).format(days.map(d => t
function StarterPlanChooser({ close }) {
const week = useStore(s => s.S.week)
const routines = useStore(s => s.S.routines)
+ const profiles = useStore(s => s.S.equipProfiles) || []
+ // Fitting starts on for the profile you already filter by; '' leaves the plan as written.
+ const [fitId, setFitId] = useState(() => activeProfile(useStore.getState().S)?.id || '')
+ const fit = profiles.find(p => p.id === fitId) || null
const choose = (id, name) => {
const days = starterPlanDays(id)
close()
// A confirmation is only worth showing when one of those days is actually occupied — by a
// routine that still exists, not by a stale id the Plan already shows as "Rest".
const taken = day => [].concat(week[day] || []).some(id => routines.some(r => r.id === id))
- if (!days.some(taken)) { loadStarterPlan(id); return }
+ if (!days.some(taken)) { loadStarterPlan(id, fit); return }
confirmSheet({
title: t('Load {0}?', name),
message: t('The new plan goes on {0}. Your existing routines stay; only those days of the weekly plan change.', dayList(days)),
confirmText: t('Load plan'),
- onConfirm: () => loadStarterPlan(id)
+ onConfirm: () => loadStarterPlan(id, fit)
})
}
return <>
<h3>{t('Choose starter plan')}</h3>
+ {profiles.length > 0
+ ? <div className="chips" style={{ margin: '0 0 10px' }}>
+ <div className="small dim" style={{ width: '100%' }}>{t('Fit to my equipment')}</div>
+ <button className={'chip nocap' + (!fit ? ' on' : '')} onClick={() => setFitId('')}>{t('As written')}</button>
+ {profiles.map(p => <button key={p.id} className={'chip nocap' + (fit?.id === p.id ? ' on' : '')} onClick={() => setFitId(p.id)}>{p.name}</button>)}
+ </div>
+ : <div className="small dim" style={{ margin: '0 0 10px' }}>{t('Add an equipment profile in Settings to fit a plan to what you own.')}</div>}
<div className="list">
{starterPlanOptions().map(({ id, days }) => {
const { name, about } = PLAN_COPY[id]()
diff --git a/frontend/src/sheets.starter.test.jsx b/frontend/src/sheets.starter.test.jsx
index a0bb45428..00097d9cf 100644
--- a/frontend/src/sheets.starter.test.jsx
+++ b/frontend/src/sheets.starter.test.jsx
@@ -117,6 +117,63 @@ describe('starter plan chooser', () => {
})
})
+describe('starter plan chooser, fitted to equipment', () => {
+ const home = { id: 'home', name: 'Home', equipment: ['dumbbell'] }
+ const chip = (host, label) => [...host.querySelectorAll('.chip')].find(b => b.textContent === label)
+ const exIds = () => S().routines.slice(1).flatMap(r => r.ex.map(e => e.id))
+
+ it('points to Settings when there is no profile, and offers no chips', () => {
+ starterPlanSheet()
+ const host = renderTop()
+ expect(host.querySelector('.chip')).toBeNull()
+ expect(host.textContent).toContain('Add an equipment profile in Settings')
+ })
+
+ it('loads the plan as written unless a profile is picked', () => {
+ useStore.setState(s => ({ S: { ...s.S, equipProfiles: [home], activeEquipId: 'home', equipFilterOn: false } }))
+ starterPlanSheet()
+ const host = renderTop()
+ expect(chip(host, 'As written').className).toContain('on')
+ act(() => { rowFor(host, 'Push / Pull / Legs').click() })
+ expect(exIds()).toContain('0025') // the barbell bench press
+ })
+
+ it('starts on the profile the library is filtered by, and fits the plan to it', () => {
+ useStore.setState(s => ({ S: { ...s.S, equipProfiles: [home], activeEquipId: 'home', equipFilterOn: true } }))
+ starterPlanSheet()
+ const host = renderTop()
+ expect(chip(host, 'Home').className).toContain('on')
+ act(() => { rowFor(host, 'Push / Pull / Legs').click() })
+ expect(exIds()).not.toContain('0025')
+ expect(useUI.getState().toastMsg).toMatch(/^Push \/ Pull \/ Legs loaded, fitted to "Home": \d+ swapped, 0 dropped$/)
+ })
+
+ it('lets you pick a profile by hand', () => {
+ useStore.setState(s => ({ S: { ...s.S, equipProfiles: [home], activeEquipId: '', equipFilterOn: false } }))
+ starterPlanSheet()
+ const host = renderTop()
+ act(() => { chip(host, 'Home').click() })
+ act(() => { rowFor(host, '5×5').click() })
+ expect(exIds()).not.toContain('0043') // no barbell squat on a dumbbell-only profile
+ })
+
+ it('adds a fitted plan beside a same-named routine with other exercises, instead of reusing it', () => {
+ loadStarterPlan('ppl')
+ loadStarterPlan('ppl', { id: 'home', name: 'Home', equipment: ['dumbbell'] })
+ const pushes = S().routines.filter(r => r.name === 'Push Day')
+ expect(pushes).toHaveLength(2)
+ expect(pushes[0].ex.map(e => e.id)).not.toEqual(pushes[1].ex.map(e => e.id))
+ expect(S().week[1]).toEqual([pushes[1].id])
+ })
+
+ it('still reuses the routines when the same fitted plan is loaded twice', () => {
+ const home = { id: 'home', name: 'Home', equipment: ['dumbbell'] }
+ loadStarterPlan('ppl', home)
+ loadStarterPlan('ppl', home)
+ expect(S().routines.filter(r => r.name === 'Push Day')).toHaveLength(1)
+ })
+})
+
describe('loadStarterPlan', () => {
it('two different plans add independent routines', () => {
loadStarterPlan('ppl')