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.

Back buttons: the page comes back where it was scrolled, like the edge swipe

Boris 'B' Kurktchievacc332fb7757
diff --git a/frontend/src/App.back-button.test.jsx b/frontend/src/App.back-button.test.jsx
new file mode 100644
index 000000000..ad270e844
--- /dev/null
+++ b/frontend/src/App.back-button.test.jsx
@@ -0,0 +1,84 @@
+// @vitest-environment happy-dom
+// A tap on a page's own back button brings the page it goes to back where it was scrolled to, as
+// the edge swipe back (which presses that same button) and the system back already did. Its push
+// used to open the page at the top, so Stats scrolled down, then Structural balance and back,
+// started over.
+import React, { act } from 'react'
+import { createRoot } from 'react-dom/client'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import App from './App.jsx'
+import { DEF, useStore } from './store/useStore.js'
+
+vi.mock('./lib/sound.js', async importOriginal => ({ ...(await importOriginal()), setPlayOnSilent: vi.fn(), setVibrate: vi.fn(), setAlarmBuzzer: vi.fn(), setNativeBuzzer: vi.fn() }))
+vi.mock('./lib/api.js', async importOriginal => {
+ const actual = await importOriginal()
+ return { ...actual, api: vi.fn(() => Promise.resolve({})), beacon: vi.fn() }
+})
+
+globalThis.IS_REACT_ACT_ENVIRONMENT = true
+
+let host, root, originalS, scrolls
+const go = async hash => { await act(async () => { window.location.hash = hash; window.dispatchEvent(new HashChangeEvent('hashchange')); window.dispatchEvent(new PopStateEvent('popstate')) }) }
+const scrolledTo = async y => {
+ Object.defineProperty(window, 'scrollY', { configurable: true, value: y })
+ await act(async () => { window.dispatchEvent(new Event('scroll')) })
+}
+const frame = () => act(async () => { await new Promise(r => requestAnimationFrame(() => r())) })
+const tap = async el => { await act(async () => { el.click() }); await frame() }
+// A screen loaded on demand (App.jsx lazyView) renders a few turns after its route does.
+const appear = async find => {
+ const get = typeof find === 'string' ? () => document.querySelector(find) : find
+ for (let i = 0; i < 500 && !get(); i++) await act(async () => { await new Promise(r => setTimeout(r, 10)) })
+ return get()
+}
+
+beforeEach(async () => {
+ originalS = useStore.getState().S
+ useStore.setState({ S: JSON.parse(JSON.stringify(DEF)) })
+ localStorage.setItem('gym_guest', '1')
+ window.location.hash = '#/stats'
+ host = document.createElement('div'); document.body.appendChild(host); root = createRoot(host)
+ scrolls = []
+ window.scrollTo = vi.fn((x, y) => { scrolls.push([x, y]); Object.defineProperty(window, 'scrollY', { configurable: true, value: y }) })
+ await act(async () => { root.render(<App />) })
+ await appear('#app .hdr button[aria-label="History"]') // Stats loads on demand too
+})
+afterEach(() => {
+ act(() => root.unmount())
+ host.remove()
+ useStore.setState({ S: originalS })
+ localStorage.removeItem('gym_guest')
+})
+
+describe("a page's own back button", () => {
+ it('brings Stats back where it was scrolled, not at the top', async () => {
+ await scrolledTo(900)
+ await tap(document.querySelector('#app .hdr button[aria-label="History"]'))
+ expect(window.location.hash).toBe('#/history')
+ expect(scrolls.at(-1)).toEqual([0, 0]) // a page you open starts at the top
+ await tap(await appear('#app [data-back]'))
+ expect(window.location.hash).toBe('#/stats')
+ expect(scrolls.at(-1)).toEqual([0, 900])
+ })
+
+ it('takes Body measurements back to Stats, the screen it is opened from', async () => {
+ await go('#/measurements')
+ const back = await appear('#app [data-back]')
+ expect(back.getAttribute('data-back')).toBe('/stats')
+ await tap(back)
+ expect(window.location.hash).toBe('#/stats')
+ })
+
+ it('a page opened at the top is remembered at the top, though no scroll event says so', async () => {
+ const row = text => [...document.querySelectorAll('#app button, #app [role="button"]')].find(b => b.textContent.trim().startsWith(text))
+ await go('#/settings/workout')
+ await scrolledTo(400) // an earlier visit, left halfway down
+ await go('#/settings')
+ await tap(await appear(() => row('Workout'))) // opened again: at the top
+ expect(window.location.hash).toBe('#/settings/workout')
+ await tap(row('Fine-tuning'))
+ await tap(document.querySelector('#app [data-back]')) // back the way it came
+ expect(window.location.hash).toBe('#/settings/workout')
+ expect(scrolls.at(-1)).toEqual([0, 0])
+ })
+})
diff --git a/frontend/src/App.jsx b/frontend/src/App.jsx
index 3e161654a..20a41909e 100644
--- a/frontend/src/App.jsx
+++ b/frontend/src/App.jsx
@@ -198,7 +198,7 @@ function Shell() {
}, [])
// The edge swipe back (lib/edge-swipe-back.js) asks for the page it goes back to underneath
// while the finger moves (`preview`), and says where it is going as it lets go (`returning`):
- // that page comes back where it was scrolled to, as the back button's push would not.
+ // that page comes back where it was scrolled to.
const [preview, setPreview] = useState(null)
const returning = useRef(null)
useEffect(() => {
@@ -210,6 +210,18 @@ function Shell() {
window.addEventListener(BACK_PREVIEW_EVENT, on)
return () => window.removeEventListener(BACK_PREVIEW_EVENT, on)
}, [])
+ // A tap on the page's own back button lands the same way. Its push used to open the page at the
+ // top, so Stats scrolled down, then Structural balance and back, started over, while the swipe,
+ // which presses this very button, came back to where it was. Capture phase, so this is known
+ // before the button's own handler navigates.
+ useEffect(() => {
+ const onClick = e => {
+ const to = e.target.closest?.('#app > .page:not(.under) [data-back]')?.getAttribute('data-back')
+ if (to) returning.current = to
+ }
+ document.addEventListener('click', onClick, true)
+ return () => document.removeEventListener('click', onClick, true)
+ }, [])
// Any navigation ends a preview: promoted (it is the page now) or not needed any more.
useEffect(() => { setPreview(null) }, [loc.pathname])
useLayoutEffect(() => {
@@ -231,7 +243,9 @@ function Shell() {
// route — now, not a frame later: that frame landed on top of a scroll a view made on mount
// (the superset card centring its row, views/Workout.jsx), and a smooth scroll cut off by a
// scrollTo is simply gone.
- if (navType !== 'POP' || first) { window.scrollTo(0, 0); return }
+ // Remembered as the top too. When the window is at the top already no scroll event comes, and
+ // a back to this page would land where an earlier visit had left it.
+ if (navType !== 'POP' || first) { window.scrollTo(0, 0); scrollPositions.set(loc.pathname, 0); return }
// A POP that stays on the route we are on is not a back-navigation: it is the history
// entry a sheet pushed (Modals.jsx, #63) being unwound as the sheet closes. Nothing new
// mounted, Modals puts the page back where it was itself, and a view that scrolled on
diff --git a/frontend/src/components/TabBar.jsx b/frontend/src/components/TabBar.jsx
index db089dd7b..f374a15a7 100644
--- a/frontend/src/components/TabBar.jsx
+++ b/frontend/src/components/TabBar.jsx
@@ -30,7 +30,10 @@ export default function TabBar({ onStart }) {
const trouble = useConnectionTrouble()
if (!user && !isGuest) return null
const cur = loc.pathname.split('/')[1] || 'home'
- const on = k => cur === k || (cur === 'history' && k === 'stats') || (cur === 'settings' && k === 'home') || (cur === 'muscles' && k === 'library') || (cur === 'structural-balance' && k === 'stats')
+ // A screen without a tab of its own lights the tab it is opened from (Muscles from both).
+ const PARENT = { history: 'stats', 'structural-balance': 'stats', 'progress-photos': 'stats', measurements: 'stats', settings: 'home', checkin: 'home', muscles: 'library' }
+ const parent = cur === 'muscles' && loc.state?.from === '/stats' ? 'stats' : PARENT[cur]
+ const on = k => cur === k || parent === k
const running = !!S.active && cur !== 'workout' && !S.active.editingWorkoutId && !S.active.backfill && S.active.start > 0
const startWorkout = () => {
diff --git a/frontend/src/components/TabBar.test.jsx b/frontend/src/components/TabBar.test.jsx
index 921c1d94d..421b226b5 100644
--- a/frontend/src/components/TabBar.test.jsx
+++ b/frontend/src/components/TabBar.test.jsx
@@ -8,9 +8,10 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import TabBar from './TabBar.jsx'
import { DEF, useStore } from '../store/useStore.js'
+const where = vi.hoisted(() => ({ loc: { pathname: '/home' } }))
vi.mock('react-router-dom', () => ({
useNavigate: () => () => {},
- useLocation: () => ({ pathname: '/home' }),
+ useLocation: () => where.loc,
}))
globalThis.IS_REACT_ACT_ENVIRONMENT = true
@@ -31,6 +32,7 @@ afterEach(() => {
act(() => root.unmount())
host.remove()
useStore.setState({ S: originalS, user: originalUser })
+ where.loc = { pathname: '/home' }
})
const tabs = () => [...host.querySelectorAll('#tabbar button')]
@@ -115,3 +117,23 @@ describe('the tab icons and labels', () => {
} finally { vi.useRealTimers() }
})
})
+
+// A screen without a tab of its own keeps the tab it was opened from lit. Check-in, Progress photos
+// and Body measurements lit none: Measurements moved under Stats (75a3b750) and the bar never heard.
+describe('the tab a screen without its own lights', () => {
+ const lit = () => tabs().filter(b => b.classList.contains('on')).map(b => b.textContent)
+ it.each([
+ ['/history', 'Stats'], ['/structural-balance', 'Stats'], ['/progress-photos', 'Stats'], ['/measurements', 'Stats'],
+ ['/settings', 'Home'], ['/settings/units', 'Home'], ['/checkin', 'Home'], ['/muscles', 'Exercises'],
+ ])('%s lights %s', (pathname, tab) => {
+ where.loc = { pathname }
+ act(() => { root.render(<TabBar onStart={() => {}} />) })
+ expect(lit()).toEqual([tab])
+ })
+
+ it('Muscles opened from Stats lights Stats, the way its back button goes', () => {
+ where.loc = { pathname: '/muscles', state: { from: '/stats' } }
+ act(() => { root.render(<TabBar onStart={() => {}} />) })
+ expect(lit()).toEqual(['Stats'])
+ })
+})
diff --git a/frontend/src/views/Measurements.jsx b/frontend/src/views/Measurements.jsx
index ec78a7cba..fea960bfb 100644
--- a/frontend/src/views/Measurements.jsx
+++ b/frontend/src/views/Measurements.jsx
@@ -187,7 +187,7 @@ export default function Measurements() {
return <div className="narrow">
<div className="hdr">
- <button className="iconbtn" data-back="/home" onClick={() => nav('/home')} aria-label={t('Home')}><Icon name="chevronLeft" /></button>
+ <button className="iconbtn" data-back="/stats" onClick={() => nav('/stats')} aria-label={t('Stats')}><Icon name="chevronLeft" /></button>
<div style={{ flex: 1, marginLeft: 10 }}><h1>{t('Body measurements')}</h1><div className="sub">{t('Circumference & composition')}</div></div>
<button className="iconbtn" onClick={manageMeasurementsSheet} aria-label={t('Choose measurements')}><Icon name="gear" /></button>
</div>