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.

feat(picker): a swap opens on exercises for the same muscle, same equipment first (#473)

Duarte Santos83f184d4a203
diff --git a/frontend/src/lib/similar-exercises.js b/frontend/src/lib/similar-exercises.js
new file mode 100644
index 000000000..1a88f0310
--- /dev/null
+++ b/frontend/src/lib/similar-exercises.js
@@ -0,0 +1,23 @@
+// What a swap picker opens on (#473): the exercises that train the same target muscle as the one
+// being replaced, the ones on the same equipment first. A machine that is taken is usually
+// swapped for another way to hit the same muscle, often on the same kind of kit.
+//
+// `tg` is the catalogue's one-word target (a custom exercise keeps the primary picked first, see
+// CustomExForm), so "same muscle" means the same primary, not merely the same body part.
+
+/** The target muscle a swap away from `ex` should start on, or '' when it has none. */
+export const swapMuscleOf = ex => (ex && typeof ex.tg === 'string' ? ex.tg : '')
+
+/**
+ * The exercises in `list` sharing `ex`'s target muscle, `ex` itself left out, those on its
+ * equipment first. Otherwise the list's own order is kept (Array#sort is stable), so favourites
+ * floated to the top earlier stay on top within each half.
+ */
+export function sameMuscleFirst(list, ex) {
+ const tg = swapMuscleOf(ex)
+ if (!tg) return []
+ const eq = ex.eq || ''
+ return list
+ .filter(e => e && e.tg === tg && e.id !== ex.id)
+ .sort((a, b) => Number(!!eq && b.eq === eq) - Number(!!eq && a.eq === eq))
+}
diff --git a/frontend/src/sheets.jsx b/frontend/src/sheets.jsx
index 934ab8e62..ad98d2fb8 100644
--- a/frontend/src/sheets.jsx
+++ b/frontend/src/sheets.jsx
@@ -28,6 +28,7 @@ import { glyphOf, GLYPH_GROUPS, DEFAULT_GLYPH } from './lib/glyphs.js'
import BodyMap from './components/BodyMap.jsx'
import MuscleExplorer from './components/MuscleExplorer.jsx'
import ExerciseViewToggle from './components/ExerciseViewToggle.jsx'
+import { sameMuscleFirst, swapMuscleOf } from './lib/similar-exercises.js'
import { exerciseMuscleSnapshot, loadOfWorkouts, MUSCLES, MUSCLE_NAME, muscleWeightsOf, normalizeMuscleGroups, hasExplicitMuscleMetadata, inMuscleOrder } from './lib/muscles.js'
import { parseImport, mergeImport } from './lib/import-csv.js'
import { importHevyData, HevyApiError, HEVY_DEV_SETTINGS, mergeHevyRoutines } from './lib/import-hevy.js'
@@ -1200,11 +1201,22 @@ function usageMap(st) {
st.workouts.forEach(w => w.entries.forEach(e => { u[e.id] = (u[e.id] || 0) + 1 }))
return u
}
-function ExercisePicker({ onPick, title, close }) {
+// The swap pickers' own scope (#473): exercises sharing the swapped exercise's target muscle.
+const SAME = '≈'
+function ExercisePicker({ onPick, title, close, like }) {
const st = useStore(s => s.S)
const usage = usageMap(st)
const [q, setQ] = useState('')
- const [bp, setBp] = useState('') // '' = all, '★' = chosen, '☆' = favourites, else a body part
+ // 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
+ // A muscle nothing else trains gets no chip at all rather than one that lists nothing.
+ const likeTg = swapMuscleOf(likeEx) && sameMuscleFirst(allExercises(st), likeEx).length ? swapMuscleOf(likeEx) : ''
+ const [bp, setBp] = useState(() => {
+ if (!likeTg) return ''
+ const prof = activeProfile(st)
+ return sameMuscleFirst(allExercises(st), likeEx).some(e => !prof || exAvailable(st, e)) ? SAME : ''
+ }) // '' = all, '★' = chosen, '☆' = favourites, '≈' = same muscle, else a body part
const [eq, setEq] = useState('') // '' = any equipment
const [showAll, setShowAll] = useState(false)
const [shown, setShown] = useState(50)
@@ -1216,14 +1228,17 @@ function ExercisePicker({ onPick, title, close }) {
const all = allExercises(st)
const profile = activeProfile(st)
const inScope = e => bp === '★' ? usage[e.id] : bp === '☆' ? isFav(st, e.id) : (!bp || e.bp === bp)
- let base = searchExercises(all.filter(inScope), q)
+ let base = searchExercises(bp === SAME ? sameMuscleFirst(all, likeEx) : all.filter(inScope), q)
if (bp === '★') base = [...base].sort((a, b) => (usage[b.id] - usage[a.id]) || exerciseNameFor(a).localeCompare(exerciseNameFor(b)))
const eqFiltered = (profile && !showAll) ? base.filter(e => exAvailable(st, e)) : base
const eqOpts = equipmentOf(eqFiltered)
// Drop the equipment filter if the search narrowed it away, so you never hit a dead end.
const eqOn = eqOpts.includes(eq) ? eq : ''
// Favourites float to the top of whatever the filters left (issue #6), the rest keeps its order.
- const f = sortFavouritesFirst(eqOn ? eqFiltered.filter(e => e.eq === eqOn) : eqFiltered, st)
+ // On the same-muscle list the equipment order wins: what is on the same kit comes first,
+ // favourites leading within each half.
+ const ranked = sortFavouritesFirst(eqOn ? eqFiltered.filter(e => e.eq === eqOn) : eqFiltered, st)
+ const f = bp === SAME ? sameMuscleFirst(ranked, likeEx) : ranked
const chosenCount = Object.keys(usage).length
const favCount = (st.favEx || []).length
const special = bp === '★' || bp === '☆'
@@ -1261,6 +1276,7 @@ function ExercisePicker({ onPick, title, close }) {
without forgetting the choice (issue #71). The favourites/chosen chips still clear it —
those are cross-body-part views where a stale equipment filter would be confusing. */}
<div className="chips" ref={bpStrip} style={{ margin: eqOpts.length > 1 ? '10px 0 6px' : '10px 0' }}>
+ {likeTg && <button className={'chip nocap' + (bp === SAME ? ' on' : '')} onClick={() => { setBp(SAME); setShown(50) }}><Icon name="figureStrength" style={{ fontSize: 12, display: 'inline-block', marginInlineEnd: 4, verticalAlign: '-1px' }} />{t('Same muscle: {0}', t(MUSCLE_NAME[likeTg] || likeTg))}</button>}
{favCount > 0 && <button className={'chip' + (bp === '☆' ? ' on' : '')} onClick={() => { setBp('☆'); setEq(''); setShown(50) }}><Icon name="starFill" className="fav-star" />{t('Favourites')} ({favCount})</button>}
{chosenCount > 0 && <button className={'chip' + (bp === '★' ? ' on' : '')} onClick={() => { setBp('★'); setEq(''); setShown(50) }}><Icon name="starFill" style={{ fontSize: 12, display: 'inline-block', marginInlineEnd: 4, verticalAlign: '-1px' }} />{t('Chosen')} ({chosenCount})</button>}
<button className={'chip nocap' + (!bp ? ' on' : '')} onClick={() => { setBp(''); setShown(50) }}>{t('All')}</button>
@@ -1294,7 +1310,9 @@ function ExercisePicker({ onPick, title, close }) {
</>
}
// `title` names what the pick is for when it is not an add — the routine editor's Replace (#110).
-export const exercisePicker = (onPick, { title } = {}) => ui().openSheet(close => <ExercisePicker onPick={onPick} title={title} close={close} />)
+// `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 } = {}) => ui().openSheet(close => <ExercisePicker onPick={onPick} title={title} like={like} close={close} />)
/** Start a safe swap for one exact active-workout occurrence. */
export function swapActiveWorkoutExercise(index) {
@@ -1304,7 +1322,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') })
+ 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 })
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.)
diff --git a/frontend/src/sheets.swap-same-muscle.test.jsx b/frontend/src/sheets.swap-same-muscle.test.jsx
new file mode 100644
index 000000000..d47b8a957
--- /dev/null
+++ b/frontend/src/sheets.swap-same-muscle.test.jsx
@@ -0,0 +1,121 @@
+// @vitest-environment happy-dom
+// #473: a swap opens on what trains the same muscle. Mid-workout (Swap exercise) and in the
+// routine editor (Replace exercise) the picker starts on the exercises sharing the swapped one's
+// target muscle, same equipment first, and "All" is one tap back to the whole list.
+import React, { act } from 'react'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { createRoot } from 'react-dom/client'
+import { DEF, useStore } from './store/useStore.js'
+import { useUI } from './store/useUI.js'
+import { EXDB } from './lib/exercises.js'
+import { exercisePicker, swapActiveWorkoutExercise } from './sheets.jsx'
+import { sameMuscleFirst } from './lib/similar-exercises.js'
+
+const mounted = []
+function renderTop() {
+ const sheet = useUI.getState().sheets.at(-1)
+ const host = document.createElement('div')
+ document.body.appendChild(host)
+ const root = createRoot(host)
+ mounted.push(root)
+ act(() => root.render(sheet.render(() => useUI.getState().closeSheet(sheet.id))))
+ return host
+}
+const chips = host => [...host.querySelectorAll('.chips .chip')]
+const chipByText = (host, text) => chips(host).find(b => b.textContent.trim() === text)
+const sameChip = host => chips(host).find(b => b.textContent.trim().startsWith('Same muscle'))
+const isOn = el => el.className.split(/\s+/).includes('on')
+const rows = host => [...host.querySelectorAll('.list .item:not(.ex-new)')].map(r => r.querySelector('.ss').textContent)
+
+// A cable triceps exercise: the catalogue has plenty of other triceps work, on cables and off.
+const CABLE_TRI = EXDB.find(e => e.tg === 'triceps' && e.eq === 'cable')
+
+beforeEach(() => {
+ globalThis.IS_REACT_ACT_ENVIRONMENT = true
+ useUI.setState({ sheets: [], toastMsg: '' })
+ useStore.setState({ S: structuredClone(DEF), user: null })
+ document.body.innerHTML = ''
+})
+afterEach(() => {
+ act(() => { mounted.splice(0).forEach(root => root.unmount()) })
+})
+
+describe('sameMuscleFirst', () => {
+ it('keeps the same target muscle, drops the exercise itself, same equipment first, order kept otherwise', () => {
+ const ex = { id: 'x', tg: 'triceps', eq: 'cable' }
+ const list = [
+ { id: 'a', tg: 'triceps', eq: 'dumbbell' },
+ { id: 'x', tg: 'triceps', eq: 'cable' },
+ { id: 'b', tg: 'biceps', eq: 'cable' },
+ { id: 'c', tg: 'triceps', eq: 'cable' },
+ { id: 'd', tg: 'triceps', eq: 'barbell' },
+ { id: 'e', tg: 'triceps', eq: 'cable' }
+ ]
+ expect(sameMuscleFirst(list, ex).map(e => e.id)).toEqual(['c', 'e', 'a', 'd'])
+ expect(sameMuscleFirst(list, { id: 'y' })).toEqual([])
+ })
+})
+
+describe('swap picker opens on the same muscle', () => {
+ it('mid-workout: Swap exercise starts on the target muscle, same equipment first, All goes back', () => {
+ expect(CABLE_TRI).toBeTruthy()
+ const S = structuredClone(DEF)
+ S.active = {
+ id: 'w', d: '2026-10-08', start: Date.now(), routineId: null, name: 'Push', bw: null, cur: 0,
+ entries: [{ id: CABLE_TRI.id, target: { mode: 'reps', sets: 3, reps: 10, weight: 20 }, sets: [{ w: 20, r: 10, done: false }] }]
+ }
+ useStore.setState({ S, user: null })
+ swapActiveWorkoutExercise(0)
+ const host = renderTop()
+
+ const chip = sameChip(host)
+ expect(chip.textContent).toContain('Triceps')
+ expect(isOn(chip)).toBe(true)
+ expect(isOn(chipByText(host, 'All'))).toBe(false)
+
+ const listed = rows(host)
+ expect(listed.length).toBeGreaterThan(1)
+ expect(listed.every(s => s.startsWith('Triceps'))).toBe(true)
+ // Cable first: once something else shows up, no cable exercise follows it.
+ const firstOther = listed.findIndex(s => !s.endsWith('cable'))
+ expect(listed[0].endsWith('cable')).toBe(true)
+ if (firstOther > 0) expect(listed.slice(firstOther).some(s => s.endsWith('cable'))).toBe(false)
+ // The exercise being swapped away is not offered as its own replacement.
+ expect([...host.querySelectorAll('.list .item .tt')].map(x => x.textContent)).not.toContain(CABLE_TRI.n)
+
+ act(() => chipByText(host, 'All').click())
+ expect(isOn(chipByText(host, 'All'))).toBe(true)
+ expect(rows(host).some(s => !s.startsWith('Triceps'))).toBe(true)
+ // …and back again.
+ act(() => sameChip(host).click())
+ expect(rows(host).every(s => s.startsWith('Triceps'))).toBe(true)
+ })
+
+ // The routine editor hands its slot's exercise in (views/RoutineEdit.replace.test.jsx).
+ it('routine editor: a picker told what it replaces opens on that muscle', () => {
+ const pick = vi.fn()
+ exercisePicker(pick, { title: 'Replace exercise', like: CABLE_TRI.id })
+ const host = renderTop()
+ expect(isOn(sameChip(host))).toBe(true)
+ expect(rows(host).every(s => s.startsWith('Triceps'))).toBe(true)
+ })
+
+ it('an add opens on the whole list, with no same-muscle chip', () => {
+ exercisePicker(vi.fn())
+ const host = renderTop()
+ expect(sameChip(host)).toBeUndefined()
+ expect(isOn(chipByText(host, 'All'))).toBe(true)
+ })
+
+ it('opens on All when nothing else trains that muscle, so a swap never starts on an empty list', () => {
+ const S = structuredClone(DEF)
+ // Every catalogue muscle has body-weight work, which no equipment profile hides, so the empty
+ // case is one of your own exercises on a muscle nothing else names.
+ S.customEx = [{ id: 'cOnly', n: 'My odd lift', bp: 'neck', tg: 'nothing-else', eq: 'body weight', custom: true }]
+ useStore.setState({ S, user: null })
+ exercisePicker(vi.fn(), { like: 'cOnly' })
+ const host = renderTop()
+ expect(isOn(chipByText(host, 'All'))).toBe(true)
+ expect(sameChip(host)).toBeUndefined()
+ })
+})
diff --git a/frontend/src/views/RoutineEdit.jsx b/frontend/src/views/RoutineEdit.jsx
index 79f28723e..dd54f4d20 100644
--- a/frontend/src/views/RoutineEdit.jsx
+++ b/frontend/src/views/RoutineEdit.jsx
@@ -416,7 +416,7 @@ export default function RoutineEdit() {
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') })
+ }, { title: t('Replace exercise'), like: openedOn })
}
// 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
diff --git a/frontend/src/views/RoutineEdit.replace.test.jsx b/frontend/src/views/RoutineEdit.replace.test.jsx
index 4e605c515..8621899b8 100644
--- a/frontend/src/views/RoutineEdit.replace.test.jsx
+++ b/frontend/src/views/RoutineEdit.replace.test.jsx
@@ -45,7 +45,8 @@ function openReplace() {
act(() => onReplace())
expect(sheets.exercisePicker).toHaveBeenCalledOnce()
const [onPick, opts] = sheets.exercisePicker.mock.calls[0]
- expect(opts).toEqual({ title: 'Replace exercise' })
+ // #473: the picker is told what it replaces, so it opens on the same muscle.
+ expect(opts).toEqual({ title: 'Replace exercise', like: BENCH })
return onPick
}