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
Exercise lists load their next page as you scroll: no more stopping at "Show more"
Aleksey Sinkevich1c14cf437828
diff --git a/frontend/src/auto-more.test.jsx b/frontend/src/auto-more.test.jsxnew file mode 100644index 000000000..6ee57152f--- /dev/null+++ b/frontend/src/auto-more.test.jsx@@ -0,0 +1,106 @@+// @vitest-environment happy-dom+// The long exercise lists — the Library, the add-exercise picker and the muscle explorer — load+// their next page by themselves once the "Show more" button at their foot comes near the screen+// (lib/use-auto-more.js). The button stays, and without IntersectionObserver it is the way on.+// happy-dom has no IntersectionObserver, so a fake one stands in and is fired by hand.+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 { exercisePicker } from './sheets.jsx'+import Library from './views/Library.jsx'+import MuscleExplorer from './components/MuscleExplorer.jsx'+import { BODYPARTS, EXDB } from './lib/exercises.js'++vi.mock('react-router-dom', () => ({ useNavigate: () => () => {} }))++const observers = []+class FakeIntersectionObserver {+ constructor(cb) { this.cb = cb; this.els = new Set(); observers.push(this) }+ observe(el) { this.els.add(el) }+ unobserve(el) { this.els.delete(el) }+ disconnect() { this.els.clear() }+}+// The button scrolls into the observed band: every live observer reports what it watches.+const comeIntoView = () => act(() => observers.forEach(o => o.els.size && o.cb([...o.els].map(target => ({ target, isIntersecting: true })))))++const mounted = []+function render(node) {+ const host = document.createElement('div')+ document.body.appendChild(host)+ const root = createRoot(host)+ mounted.push(root)+ act(() => root.render(node))+ return host+}+function renderTop() {+ const sheet = useUI.getState().sheets.at(-1)+ return render(sheet.render(() => useUI.getState().closeSheet(sheet.id)))+}+const rows = host => host.querySelectorAll('.list > .item').length - 1 // drop "Create your own"+const showMore = host => [...host.querySelectorAll('button')].find(b => b.textContent === 'Show more')++beforeEach(() => {+ globalThis.IS_REACT_ACT_ENVIRONMENT = true+ vi.stubGlobal('IntersectionObserver', FakeIntersectionObserver)+ observers.length = 0+ useUI.setState({ sheets: [], toastMsg: '' })+ useStore.setState({ S: structuredClone(DEF), user: null })+ document.body.innerHTML = ''+})+afterEach(() => {+ act(() => { mounted.splice(0).forEach(root => root.unmount()) })+ vi.unstubAllGlobals()+})++describe('lists load their next page as you scroll', () => {+ it('Library: the button coming into view loads the next 40', () => {+ const host = render(<Library />)+ expect(rows(host)).toBe(40)+ comeIntoView()+ expect(rows(host)).toBe(80)+ comeIntoView()+ expect(rows(host)).toBe(120)+ })++ it('picker: the next 50, the same way', () => {+ exercisePicker(vi.fn())+ const host = renderTop()+ expect(rows(host)).toBe(50)+ comeIntoView()+ expect(rows(host)).toBe(100)+ })++ it('muscle explorer: the results of a muscle load on too', () => {+ const host = render(<MuscleExplorer onDetail={vi.fn()} onPlan={vi.fn()} />)+ // the muscle with the most exercises, so there is a second page to load+ const chips = [...host.querySelectorAll('.chip[aria-pressed]')]+ const biggest = chips.reduce((a, b) => (+b.querySelector('.dim').textContent > +a.querySelector('.dim').textContent ? b : a))+ act(() => biggest.click())+ const before = host.querySelectorAll('.list > .item').length+ expect(before).toBe(40)+ comeIntoView()+ expect(host.querySelectorAll('.list > .item').length).toBeGreaterThan(before)+ })++ it('stops watching once everything is shown', () => {+ // a body part with a few pages, not the whole catalogue+ const count = bp => EXDB.filter(e => e.bp === bp).length+ const bp = BODYPARTS.filter(b => count(b) > 40).sort((a, b) => count(a) - count(b))[0]+ const host = render(<Library />)+ act(() => [...host.querySelectorAll('.chips .chip')].find(c => c.textContent === bp).click())+ for (let i = 0; i < 10 && showMore(host); i++) comeIntoView()+ expect(rows(host)).toBe(count(bp))+ expect(showMore(host)).toBeUndefined()+ expect(observers.every(o => o.els.size === 0)).toBe(true)+ })++ it('without IntersectionObserver the button still loads more, and nothing breaks', () => {+ vi.stubGlobal('IntersectionObserver', undefined)+ const host = render(<Library />)+ expect(rows(host)).toBe(40)+ act(() => showMore(host).click())+ expect(rows(host)).toBe(80)+ })+})diff --git a/frontend/src/components/MuscleExplorer.jsx b/frontend/src/components/MuscleExplorer.jsxindex e87a0ddf5..627813673 100644--- a/frontend/src/components/MuscleExplorer.jsx+++ b/frontend/src/components/MuscleExplorer.jsx@@ -11,6 +11,7 @@ import { Thumb } from './Media.jsx'import Icon from './Icon.jsx'import { Button } from './ui.jsx'import { tappable } from '../lib/use-sheet-keyboard.js'+import { useAutoMore } from '../lib/use-auto-more.js'import { isFav, sortFavouritesFirst } from '../lib/favourites.js'// One explorer for the Library and every catalogue picker. Supplying `onPick` turns@@ -23,6 +24,7 @@ export default function MuscleExplorer({ onPick, onDetail, onPlan }) {const [eq, setEq] = useState('')const [shown, setShown] = useState(40)const [showAll, setShowAll] = useState(false) // ignore the active equipment profile for this session+ const moreRef = useAutoMore(() => setShown(s => s + 40))// Same rule as the Library and the picker: the active equipment profile narrows the catalogue// (and the per-muscle counts) unless the user asks for everything.const profile = activeProfile(S)@@ -93,7 +95,7 @@ export default function MuscleExplorer({ onPick, onDetail, onPlan }) {})}{exercises.length === 0 && <div className="empty"><div className="ico"><Icon name="magnifier" /></div>{t('No match')}</div>}</div>- {exercises.length > shown && <><div style={{ height: 10 }} /><Button onClick={() => setShown(s => s + 40)}>{t('Show more')}</Button></>}+ {exercises.length > shown && <><div style={{ height: 10 }} /><Button ref={moreRef} onClick={() => setShown(s => s + 40)}>{t('Show more')}</Button></>}</>}</>}diff --git a/frontend/src/lib/use-auto-more.js b/frontend/src/lib/use-auto-more.jsnew file mode 100644index 000000000..4315c5b4a--- /dev/null+++ b/frontend/src/lib/use-auto-more.js@@ -0,0 +1,24 @@+import { useCallback, useRef } from 'react'++/* Long lists that page with a "Show more" button (the Library, the exercise picker, the muscle+ explorer) load their next page by themselves: the button fires once it comes within about a+ screen of the viewport, so scrolling through the catalogue never stops at it. Inside a sheet+ the sheet's own scroll clips the button, so there it fires as the button scrolls into view.++ Returns a callback ref for the button. The button itself stays: for a keyboard, a screen reader+ or a browser without IntersectionObserver it is still the way on. `onMore` may change on every+ render; the latest one is called. */+export function useAutoMore(onMore) {+ const more = useRef(onMore)+ more.current = onMore+ const observer = useRef(null)+ return useCallback(el => {+ observer.current?.disconnect()+ observer.current = null+ if (!el || typeof IntersectionObserver !== 'function') return+ observer.current = new IntersectionObserver(entries => {+ if (entries.some(e => e.isIntersecting)) more.current()+ }, { rootMargin: '0px 0px 100% 0px' })+ observer.current.observe(el)+ }, [])+}diff --git a/frontend/src/sheets.jsx b/frontend/src/sheets.jsxindex a6d1ddf34..218e32609 100644--- a/frontend/src/sheets.jsx+++ b/frontend/src/sheets.jsx@@ -40,6 +40,7 @@ import { saveSessionAsRoutine } from './lib/session-routines.js'import { nextUnfinishedUnit } from './lib/supersetFlow.js'import { swapActiveExercise } from './lib/active-exercise-swap.js'import { useSheetKeyboard, useRevealActiveChip, tappable } from './lib/use-sheet-keyboard.js'+import { useAutoMore } from './lib/use-auto-more.js'import { isFav, toggleFav, sortFavouritesFirst } from './lib/favourites.js'import { buildSessionEntries, buildPlannedEntry, builtOutOfProgression } from './lib/session-start.js'import { joinSessionNoProg } from './lib/session-noprog.js'@@ -1092,6 +1093,7 @@ function ExercisePicker({ onPick, title, close }) {const searchRef = useRef(null)const bpStrip = useRef(null), eqStrip = 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)@@ -1167,7 +1169,7 @@ function ExercisePicker({ onPick, title, close }) {{f.length === 0 && bp === '★' && <div className="empty">{t('Nothing chosen yet — add exercises and they’ll show up here.')}</div>}{f.length === 0 && bp === '☆' && <div className="empty">{t('No favourites here — tap the star on an exercise to add it.')}</div>}</div>- {f.length > shown && <><div style={{ height: 8 }} /><Button onClick={() => setShown(s => s + 50)}>{t('Show more')}</Button></>}+ {f.length > shown && <><div style={{ height: 8 }} /><Button ref={moreRef} onClick={() => setShown(s => s + 50)}>{t('Show more')}</Button></>}</>}// `title` names what the pick is for when it is not an add — the routine editor's Replace (#110).diff --git a/frontend/src/views/Library.jsx b/frontend/src/views/Library.jsxindex d6608895a..558b3b957 100644--- a/frontend/src/views/Library.jsx+++ b/frontend/src/views/Library.jsx@@ -12,6 +12,7 @@ import { exerciseDetailSheet, addToRoutineSheet, customExSheet } from '../sheetsimport Icon from '../components/Icon.jsx'import { Button } from '../components/ui.jsx'import { tappable, useRevealActiveChip } from '../lib/use-sheet-keyboard.js'+import { useAutoMore } from '../lib/use-auto-more.js'import { isFav, sortFavouritesFirst } from '../lib/favourites.js'export default function Library() {@@ -23,6 +24,7 @@ export default function Library() {const [showAll, setShowAll] = useState(false) // ignore the active equipment profile for this sessionconst [shown, setShown] = useState(40)const bpStrip = useRef(null), eqStrip = useRef(null)+ const moreRef = useAutoMore(() => setShown(s => s + 40))const profile = activeProfile(S)const base = searchExercises(allExercises(S).filter(e => !bp || e.bp === bp), q)const eqFiltered = (profile && !showAll) ? base.filter(e => exAvailable(S, e)) : base@@ -78,7 +80,7 @@ export default function Library() {})}{f.length === 0 && <div className="empty"><div className="ico"><Icon name="magnifier" /></div>{t('No match')}</div>}</div>- {f.length > shown && <><div style={{ height: 10 }} /><Button onClick={() => setShown(s => s + 40)}>{t('Show more')}</Button></>}+ {f.length > shown && <><div style={{ height: 10 }} /><Button ref={moreRef} onClick={() => setShown(s => s + 40)}>{t('Show more')}</Button></>}</>}