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.

fix(picker): the Add exercise picker gets the Type row the Exercise browser has (#521)

Duarte Santos2194e87805db
diff --git a/frontend/src/lib/exercises.js b/frontend/src/lib/exercises.js
index b2efda2c1..eae63b189 100644
--- a/frontend/src/lib/exercises.js
+++ b/frontend/src/lib/exercises.js
@@ -69,6 +69,14 @@ export function categoriesOf(list) {
const have = new Set(list.map(e => e.cat).filter(Boolean))
return CATEGORIES.filter(c => have.has(c))
}
+// The Type chip row's filter, shared by the Library and the exercise picker (issue #521): the
+// options left in `list`, the choice still in effect, and the list narrowed to it. A choice the
+// search or body part has narrowed away is ignored for now, never a dead end.
+export function byCategory(list, cat) {
+ const opts = categoriesOf(list)
+ const on = opts.includes(cat) ? cat : ''
+ return { opts, on, list: on ? list.filter(e => e.cat === on) : list }
+}
// Custom (user-created) exercises live in synced state S.customEx (issue #11) and are
// merged into the id index here so every EXIDX[id] lookup keeps working unchanged.
diff --git a/frontend/src/lib/exercises.test.js b/frontend/src/lib/exercises.test.js
index b88acf3e9..0a774121f 100644
--- a/frontend/src/lib/exercises.test.js
+++ b/frontend/src/lib/exercises.test.js
@@ -1,5 +1,5 @@
import { describe, it, expect } from 'vitest'
-import { matchExercise, normalizeStr } from './exercises.js'
+import { matchExercise, normalizeStr, byCategory } from './exercises.js'
import { _setLangState } from './i18n-core.js'
describe('normalizeStr', () => {
@@ -144,3 +144,15 @@ describe('search: the everyday version first', () => {
expect(searchExercises(EXDB, 'smith leg press')[0].id).toBe('0760')
})
})
+
+// The Type chip row's filter (issue #521), shared by the Library and the exercise picker.
+describe('byCategory', () => {
+ const list = [{ id: 'a', cat: 'stretching' }, { id: 'b', cat: 'strength' }, { id: 'c' }]
+ it('offers the types present, in the fixed order, and narrows to the chosen one', () => {
+ expect(byCategory(list, '')).toEqual({ opts: ['strength', 'stretching'], on: '', list })
+ expect(byCategory(list, 'stretching')).toEqual({ opts: ['strength', 'stretching'], on: 'stretching', list: [list[0]] })
+ })
+ it('ignores a type the list has none of instead of showing nothing', () => {
+ expect(byCategory(list, 'yoga')).toEqual({ opts: ['strength', 'stretching'], on: '', list })
+ })
+})
diff --git a/frontend/src/sheets.jsx b/frontend/src/sheets.jsx
index 61e4b972d..be03e49ef 100644
--- a/frontend/src/sheets.jsx
+++ b/frontend/src/sheets.jsx
@@ -1,7 +1,7 @@
import { useDeferredValue, useEffect, useMemo, useRef, useState } from 'react'
import { useStore } from './store/useStore.js'
import { useUI } from './store/useUI.js'
-import { EXDB, EXIDX, BODYPARTS, isCardio, isBodyweightEq, allExercises, equipmentOf, smOf, searchExercises, similarExercises, exOr, isAssisted, betterWeight, beatsWeight, isCustomEx } from './lib/exercises.js'
+import { EXDB, EXIDX, BODYPARTS, isCardio, isBodyweightEq, allExercises, equipmentOf, byCategory, smOf, searchExercises, similarExercises, exOr, isAssisted, betterWeight, beatsWeight, isCustomEx } from './lib/exercises.js'
import { activeProfile, exAvailable, ALL_EQUIPMENT, newProfile, profileEquipment, ACC_V } from './lib/equipment.js'
import { fmtDate, fmtDateRange, fmtNum, fmtPlate, exerciseNameText, fmtVol, fmtDur, durPart, todayISO, isoOf, uid, exCount, routineCount, setsWorkCount, DAYN, DAYS, weekOrder, weekStartOf, weekDayOffset, MONTHS_LONG, ACCENTS } from './lib/format.js'
import { lastEntryFor, bestWeightFor, bestWeightForEntry, buildSets, effectiveRoutineIds, workoutDay, workoutVolume, setsDone, setsDoneActive, setUnitsTotal, lastBW, sessionSections, setLabel, defaultConfig, cleanupSg, modeOf, effortOf, EFFORT, capEffort, stepEffort, isBw, isPerSide, sideReps, workSetsDone, applyIntensifierPlan, MAX_PLANNED_WARMUPS, NOTE_MAX } from './lib/history.js'
@@ -1288,18 +1288,22 @@ function ExercisePicker({ onPick, title, close, like }) {
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 [cat, setCat] = useState('') // '' = any type
const [showAll, setShowAll] = useState(false)
const [shown, setShown] = useState(50)
const [byMuscle, setByMuscle] = useState(false)
const searchRef = useRef(null)
- const bpStrip = useRef(null), eqStrip = useRef(null)
+ const bpStrip = useRef(null), eqStrip = useRef(null), catStrip = useRef(null)
const onSearchFocus = useSheetKeyboard(searchRef)
const moreRef = useAutoMore(() => setShown(s => s + 50))
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(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)))
+ let inPart = searchExercises(bp === SAME ? sameMuscleFirst(all, likeEx) : all.filter(inScope), q)
+ if (bp === '★') inPart = [...inPart].sort((a, b) => (usage[b.id] - usage[a.id]) || exerciseNameFor(a).localeCompare(exerciseNameFor(b)))
+ // The Library's Type row (issue #521), with its fallback: a type the search or muscle group
+ // narrowed away is ignored for this view, not forgotten.
+ const { opts: catOpts, on: catOn, list: base } = byCategory(inPart, cat)
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.
@@ -1315,9 +1319,10 @@ function ExercisePicker({ onPick, title, close, like }) {
const favCount = (st.favEx || []).length
const special = bp === '★' || bp === '☆'
// The Library's live result count (GitLab !31), for the same reason: how many are left.
- const narrowed = !!(q.trim() || bp || eqOn)
+ const narrowed = !!(q.trim() || bp || eqOn || catOn)
useRevealActiveChip(bpStrip, bp)
useRevealActiveChip(eqStrip, eqOn)
+ useRevealActiveChip(catStrip, catOn)
// Close but not exact (a typo too many, most of the words, a similar name), listed under the
// results once you have scrolled to their end, so a search almost never ends on nothing.
// Worked out a beat behind the typing (useDeferredValue): the list itself never waits for it.
@@ -1366,13 +1371,17 @@ function ExercisePicker({ onPick, title, close, like }) {
group the filter stays applied, and if not the eqOn fallback above drops it for this view
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' }}>
+ <div className="chips" ref={bpStrip} style={{ margin: eqOpts.length > 1 || catOpts.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>
{BODYPARTS.map(b => <button key={b} className={'chip' + (bp === b ? ' on' : '')} onClick={() => { setBp(b); setShown(50) }}>{t(b)}</button>)}
</div>
+ {catOpts.length > 1 && <div className="chips" ref={catStrip} style={{ marginBottom: eqOpts.length > 1 ? 6 : 10 }}>
+ <button className={'chip nocap' + (!catOn ? ' on' : '')} onClick={() => { setCat(''); setShown(50) }}>{t('Any type')}</button>
+ {catOpts.map(x => <button key={x} className={'chip' + (catOn === x ? ' on' : '')} onClick={() => { setCat(x); setShown(50) }}>{t(x)}</button>)}
+ </div>}
{eqOpts.length > 1 && <div className="chips" ref={eqStrip} style={{ marginBottom: 10 }}>
<button className={'chip nocap' + (!eqOn ? ' on' : '')} onClick={() => { setEq(''); setShown(50) }}>{t('Any equipment')}</button>
{eqOpts.map(x => <button key={x} className={'chip' + (eqOn === x ? ' on' : '')} onClick={() => { setEq(x); setShown(50) }}>{t(x)}</button>)}
diff --git a/frontend/src/sheets.picker-type.test.jsx b/frontend/src/sheets.picker-type.test.jsx
new file mode 100644
index 000000000..861b312d3
--- /dev/null
+++ b/frontend/src/sheets.picker-type.test.jsx
@@ -0,0 +1,78 @@
+// @vitest-environment happy-dom
+// Issue #521: the workout's "Add exercise" picker showed the Muscle and Equipment chip rows but not
+// the Type row the Exercise browser has (strength, calisthenics, stretching...). Same row, same
+// fallback: a type the muscle group narrows away is ignored for that view, not forgotten.
+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 { exerciseNameFor } from './lib/i18n.js'
+import { exercisePicker } from './sheets.jsx'
+
+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 chipByText = (host, text) =>
+ [...host.querySelectorAll('.chips .chip')].find(b => b.textContent.trim() === text)
+const isOn = el => el.className.split(/\s+/).includes('on')
+// Every row's add button carries the exercise's name, so it tells which exercises are listed.
+const listed = host => [...host.querySelectorAll('.list .item button[aria-label]')]
+ .map(b => b.getAttribute('aria-label'))
+
+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('exercise picker type filter', () => {
+ it('shows the Type row between the muscle groups and the equipment, like the Library', () => {
+ exercisePicker(vi.fn())
+ const host = renderTop()
+ const strips = [...host.querySelectorAll('.chips')]
+ expect(strips).toHaveLength(3)
+ expect(strips[1].querySelector('.chip').textContent.trim()).toBe('Any type')
+ expect(isOn(chipByText(host, 'Any type'))).toBe(true)
+ expect(chipByText(host, 'stretching')).toBeTruthy()
+ expect(strips[2].querySelector('.chip').textContent.trim()).toBe('Any equipment')
+ })
+
+ it('narrows the list to the picked type', () => {
+ exercisePicker(vi.fn())
+ const host = renderTop()
+ act(() => chipByText(host, 'stretching').click())
+ expect(isOn(chipByText(host, 'stretching'))).toBe(true)
+ const names = listed(host)
+ expect(names.length).toBeGreaterThan(0)
+ const catOf = new Map(EXDB.map(e => [`Add “${exerciseNameFor(e)}”`, e.cat]))
+ expect(names.filter(n => catOf.get(n) !== 'stretching')).toEqual([])
+ })
+
+ it('keeps the type across a muscle group that has none of it, and picks it back up', () => {
+ exercisePicker(vi.fn())
+ const host = renderTop()
+ act(() => chipByText(host, 'yoga').click())
+ // Lower arms have no yoga: the row drops the choice for this view instead of listing nothing.
+ act(() => chipByText(host, 'lower arms').click())
+ expect(chipByText(host, 'yoga')).toBeFalsy()
+ expect(listed(host).length).toBeGreaterThan(0)
+ act(() => chipByText(host, 'back').click())
+ expect(isOn(chipByText(host, 'yoga'))).toBe(true)
+ })
+})
diff --git a/frontend/src/views/Library.jsx b/frontend/src/views/Library.jsx
index f0180a73e..e9df7d1d8 100644
--- a/frontend/src/views/Library.jsx
+++ b/frontend/src/views/Library.jsx
@@ -1,7 +1,7 @@
import { useDeferredValue, useMemo, useRef, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { useStore } from '../store/useStore.js'
-import { EXDB, BODYPARTS, allExercises, equipmentOf, categoriesOf, searchExercises, similarExercises } from '../lib/exercises.js'
+import { EXDB, BODYPARTS, allExercises, equipmentOf, byCategory, searchExercises, similarExercises } from '../lib/exercises.js'
import { MUSCLE_NAME } from '../lib/muscles.js'
import { activeProfile, exAvailable } from '../lib/equipment.js'
import { bestWeightFor } from '../lib/history.js'
@@ -34,9 +34,7 @@ export default function Library() {
const inPart = searchExercises(allExercises(S).filter(e => !bp || e.bp === bp), q)
// Kind of exercise (strength, stretching, cardio...), the same fallback as equipment below: a
// choice the search or body part has narrowed away is ignored for now, never a dead end.
- const catOpts = categoriesOf(inPart)
- const catOn = catOpts.includes(cat) ? cat : ''
- const base = catOn ? inPart.filter(e => e.cat === catOn) : inPart
+ const { opts: catOpts, on: catOn, list: base } = byCategory(inPart, cat)
const eqFiltered = (profile && !showAll) ? base.filter(e => exAvailable(S, e)) : base
const eqOpts = equipmentOf(eqFiltered)
// Drop the equipment filter if the search narrowed it away, so you never hit a dead end.