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
fix(android): prevent root tabs from stacking back history
Neo Changc0411b05e535
diff --git a/frontend/src/components/TabBar.jsx b/frontend/src/components/TabBar.jsxindex f374a15a7..752199008 100644--- a/frontend/src/components/TabBar.jsx+++ b/frontend/src/components/TabBar.jsx@@ -35,6 +35,11 @@ export default function TabBar({ onStart }) {const parent = cur === 'muscles' && loc.state?.from === '/stats' ? 'stats' : PARENT[cur]const on = k => cur === k || parent === k+ // Root tabs are peers, not another level to unwind with Android Back.+ const switchTab = path => {+ if (loc.pathname !== path || loc.search) nav(path, { replace: true })+ }+const running = !!S.active && cur !== 'workout' && !S.active.editingWorkoutId && !S.active.backfill && S.active.start > 0const startWorkout = () => {if (!S.active) {@@ -47,8 +52,8 @@ export default function TabBar({ onStart }) {return (<nav id="tabbar">- <Tab active={on('home')} icon="house" label={t('Home')} dot={trouble} onClick={() => nav('/home')} />- <Tab active={on('plan')} icon="calendar" label={t('Plan')} onClick={() => nav('/plan')} />+ <Tab active={on('home')} icon="house" label={t('Home')} dot={trouble} onClick={() => switchTab('/home')} />+ <Tab active={on('plan')} icon="calendar" label={t('Plan')} onClick={() => switchTab('/plan')} />{/* On the workout screen itself there is nothing to resume, so the button reads as thetab it is and stays lit (#29); anywhere else it brings you back to the exercise youwere on — the marker is kept in S.active.cur and never moves on its own (#21). The@@ -62,8 +67,8 @@ export default function TabBar({ onStart }) {{running ? <span className="tab-time"><Elapsed start={S.active.start} /></span>: <span>{S.active ? (cur === 'workout' ? t('Workout') : S.active.editingWorkoutId ? t('Edit workout') : t('Resume')) : t('Start')}</span>}</button>- <Tab active={on('stats')} icon="chart" label={t('Stats')} onClick={() => nav('/stats')} />- <Tab active={on('library')} icon="dumbbell" label={t('Exercises')} onClick={() => nav('/library')} />+ <Tab active={on('stats')} icon="chart" label={t('Stats')} onClick={() => switchTab('/stats')} />+ <Tab active={on('library')} icon="dumbbell" label={t('Exercises')} onClick={() => switchTab('/library')} /></nav>)}diff --git a/frontend/src/components/TabBar.navigation.test.jsx b/frontend/src/components/TabBar.navigation.test.jsxnew file mode 100644index 000000000..7654b8d71--- /dev/null+++ b/frontend/src/components/TabBar.navigation.test.jsx@@ -0,0 +1,83 @@+// @vitest-environment happy-dom+import React, { act } from 'react'+import { createRoot } from 'react-dom/client'+import { createMemoryRouter, RouterProvider } from 'react-router-dom'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import TabBar from './TabBar.jsx'+import { DEF, useStore } from '../store/useStore.js'++globalThis.IS_REACT_ACT_ENVIRONMENT = true++let host, root, router, originalS, originalUser, onStart+beforeEach(() => {+ const store = useStore.getState()+ originalS = store.S+ originalUser = store.user+ useStore.setState({ S: JSON.parse(JSON.stringify(DEF)), user: { id: 'test', name: 'test' } })+ host = document.createElement('div')+ document.body.appendChild(host)+ root = createRoot(host)+ onStart = vi.fn()+ router = createMemoryRouter([{ path: '*', element: <TabBar onStart={onStart} /> }], { initialEntries: ['/home'] })+ act(() => root.render(<RouterProvider router={router} />))+})+afterEach(() => {+ act(() => root.unmount())+ router.dispose()+ host.remove()+ useStore.setState({ S: originalS, user: originalUser })+})+const tap = async label => {+ const button = [...host.querySelectorAll('button')].find(b => b.textContent === label)+ expect(button).toBeTruthy()+ await act(async () => button.click())+}+const go = async to => { await act(async () => router.navigate(to)) }++describe('root tab history', () => {+ it('does not accumulate a back stack when switching tabs repeatedly', async () => {+ for (let i = 0; i < 3; i++) {+ for (const label of ['Plan', 'Stats', 'Exercises', 'Home']) await tap(label)+ }+ await tap('Plan')+ expect(router.state.location.pathname).toBe('/plan')+ await go(-1)+ expect(router.state.location.pathname).toBe('/plan')+ })++ it('ignores a tap on the current root, but clears a tab query when returning to its root', async () => {+ const key = router.state.location.key+ await tap('Home')+ expect(router.state.location.key).toBe(key)+ await go('/stats?range=month')+ await tap('Stats')+ expect(router.state.location.pathname).toBe('/stats')+ expect(router.state.location.search).toBe('')+ })++ it('still pushes a detail page and returns to the tab it opened from', async () => {+ await tap('Plan')+ await go('/plan/r/one')+ await go(-1)+ expect(router.state.location.pathname).toBe('/plan')+ await go('/settings/workout')+ await go(-1)+ expect(router.state.location.pathname).toBe('/plan')+ })++ it('opens a different tab root from a nested page of the active tab', async () => {+ await go('/plan/r/one')+ await tap('Plan')+ expect(router.state.location.pathname).toBe('/plan')+ expect(router.state.historyAction).toBe('REPLACE')+ })++ it('preserves the workout chooser return path', async () => {+ useStore.setState({ S: { ...useStore.getState().S, routines: [] } })+ await tap('Start')+ expect(router.state.location.pathname).toBe('/workout')+ await go(-1)+ expect(router.state.location.pathname).toBe('/home')+ expect(onStart).not.toHaveBeenCalled()+ })+})diff --git a/frontend/src/lib/back.js b/frontend/src/lib/back.jsindex 6bacd86fe..2e513355a 100644--- a/frontend/src/lib/back.js+++ b/frontend/src/lib/back.js@@ -17,25 +17,30 @@ import { t } from './i18n.js'export const EXIT_WINDOW = 2000// What a back press means, given what is on screen. Pure, so the table below is testable.-export function decideBack({ top, canGoBack, exitArmed }) {+export function decideBack({ top, pathname, canGoBack, exitArmed }) {if (top) return top.locked ? 'ignore' : 'sheet' // a locked sheet swallows back on purpose- if (canGoBack) return 'history' // a page/tab we pushed ourselves+ // A root tab must not replay older tabs or abandoned detail pages before it can exit.+ const atRoot = pathname === '/' || /^\/(home|plan|stats|library)\/?$/i.test(pathname)+ if (canGoBack && !atRoot) return 'history'return exitArmed ? 'exit' : 'arm-exit'}-export function makeBackHandler({ getSheets, closeSheet, toast, goBack, exit, now = Date.now }) {- let armedAt = -Infinity+export function makeBackHandler({ getSheets, getLocation = () => ({}), closeSheet, toast, goBack, exit, now = Date.now }) {+ let armedAt = -Infinity, armedKeyreturn (ev = {}) => {const sheets = getSheets()+ const { pathname, key } = getLocation()const action = decideBack({top: sheets[sheets.length - 1],+ pathname,canGoBack: !!ev.canGoBack,- exitArmed: now() - armedAt < EXIT_WINDOW,+ // A tab switch, even away and back, cancels the warning from the previous entry.+ exitArmed: key === armedKey && now() - armedAt < EXIT_WINDOW,})if (action !== 'arm-exit') armedAt = -Infinityif (action === 'sheet') closeSheet(sheets[sheets.length - 1].id)else if (action === 'history') goBack()- else if (action === 'arm-exit') { armedAt = now(); toast(t('Press back again to exit')) }+ else if (action === 'arm-exit') { armedAt = now(); armedKey = key; toast(t('Press back again to exit')) }else if (action === 'exit') exit()return action}@@ -49,6 +54,10 @@ export async function initBackButton() {const { App } = await import('@capacitor/app')const handler = makeBackHandler({getSheets: () => useUI.getState().sheets,+ getLocation: () => ({+ pathname: window.location.hash.slice(1).split('?')[0] || '/',+ key: window.history.state?.key ?? window.location.hash,+ }),closeSheet: id => useUI.getState().closeSheet(id),toast: msg => useUI.getState().toast(msg),goBack: () => window.history.back(),diff --git a/frontend/src/lib/back.native.test.js b/frontend/src/lib/back.native.test.jsnew file mode 100644index 000000000..56cfaa086--- /dev/null+++ b/frontend/src/lib/back.native.test.js@@ -0,0 +1,53 @@+// @vitest-environment happy-dom+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { initBackButton } from './back.js'++const { App, ui, remove } = vi.hoisted(() => ({+ App: { addListener: vi.fn(), exitApp: vi.fn() },+ ui: { sheets: [], closeSheet: vi.fn(), toast: vi.fn() },+ remove: vi.fn(),+}))+vi.mock('@capacitor/app', () => ({ App }))+vi.mock('./mobile.js', () => ({ MOBILE: true }))+vi.mock('../store/useUI.js', () => ({ useUI: { getState: () => ui } }))++let back+beforeEach(() => {+ vi.clearAllMocks()+ App.addListener.mockResolvedValue({ remove })+ back = vi.spyOn(window.history, 'back').mockImplementation(() => {})+})+afterEach(() => {+ back.mockRestore()+ history.replaceState(null, '', '/')+})++describe('the native back listener', () => {+ it('reads the current hash route without its query and checks the current navigation key', async () => {+ history.replaceState({ key: 'stats-1' }, '', '#/stats?range=month')+ const stop = await initBackButton()+ expect(App.addListener.mock.calls[0][0]).toBe('backButton')+ const handler = App.addListener.mock.calls[0][1]+ expect(handler({ canGoBack: true })).toBe('arm-exit')+ // Router replacements change the key even if navigation returned to the same URL.+ history.replaceState({ key: 'stats-2' }, '', '#/stats?range=month')+ expect(handler({ canGoBack: true })).toBe('arm-exit')+ expect(App.exitApp).not.toHaveBeenCalled()+ expect(handler({ canGoBack: true })).toBe('exit')+ expect(App.exitApp).toHaveBeenCalledOnce()+ expect(back).not.toHaveBeenCalled()+ await stop()+ expect(remove).toHaveBeenCalledOnce()+ })++ it('keeps native Back navigating history on a detail page', async () => {+ history.replaceState({ key: 'detail' }, '', '#/plan/r/one')+ const stop = await initBackButton()+ const handler = App.addListener.mock.calls[0][1]+ expect(handler({ canGoBack: true })).toBe('history')+ expect(back).toHaveBeenCalledOnce()+ expect(ui.toast).not.toHaveBeenCalled()+ expect(App.exitApp).not.toHaveBeenCalled()+ await stop()+ })+})diff --git a/frontend/src/lib/back.test.js b/frontend/src/lib/back.test.jsindex f0203588c..1686b50bd 100644--- a/frontend/src/lib/back.test.js+++ b/frontend/src/lib/back.test.js@@ -28,15 +28,17 @@ function harness() {const calls = { closed: [], toasts: [], back: 0, exit: 0 }let sheets = []let now = 1000+ let location = { pathname: '/settings', key: 'initial' }const handler = makeBackHandler({getSheets: () => sheets,+ getLocation: () => location,closeSheet: id => { calls.closed.push(id); sheets = sheets.filter(s => s.id !== id) },toast: m => calls.toasts.push(m),goBack: () => { calls.back++ },exit: () => { calls.exit++ },now: () => now,})- return { calls, handler, setSheets: s => { sheets = s }, tick: ms => { now += ms } }+ return { calls, handler, setSheets: s => { sheets = s }, setLocation: l => { location = l }, tick: ms => { now += ms } }}describe('makeBackHandler', () => {@@ -101,3 +103,46 @@ describe('makeBackHandler', () => {expect(h.handler()).toBe('arm-exit')})})++// Tab history is not a parent page: Android must be able to leave from any root tab,+// even after earlier navigation has left entries below it in the WebView.+describe('back from a root tab', () => {+ it.each(['/home', '/plan', '/stats', '/library', '/stats/', '/PLAN', '/'])(+ 'arms exit on %s even when the WebView can go back', pathname => {+ expect(decideBack({ pathname, canGoBack: true, exitArmed: false })).toBe('arm-exit')+ expect(decideBack({ pathname, canGoBack: true, exitArmed: true })).toBe('exit')+ })++ it.each(['/plan/r/one', '/settings', '/settings/workout', '/history', '/workout', '/coach'])(+ 'still goes back from the child or workout page %s', pathname => {+ expect(decideBack({ pathname, canGoBack: true, exitArmed: false })).toBe('history')+ })++ it('closes a sheet on a root tab before offering to exit', () => {+ const h = harness()+ h.setLocation({ pathname: '/home', key: 'home' })+ h.setSheets([{ id: 'sheet' }])+ expect(h.handler({ canGoBack: true })).toBe('sheet')+ expect(h.calls.back).toBe(0)+ expect(h.calls.toasts).toHaveLength(0)+ expect(h.handler({ canGoBack: true })).toBe('arm-exit')+ h.tick(100)+ expect(h.handler({ canGoBack: true })).toBe('exit')+ expect(h.calls.exit).toBe(1)+ expect(h.calls.back).toBe(0)+ })++ it('requires a fresh exit warning after switching tabs, including a round trip', () => {+ const h = harness()+ h.setLocation({ pathname: '/home', key: 'home-1' })+ expect(h.handler({ canGoBack: true })).toBe('arm-exit')+ h.tick(100)+ h.setLocation({ pathname: '/plan', key: 'plan' })+ h.setLocation({ pathname: '/home', key: 'home-2' })+ expect(h.handler({ canGoBack: true })).toBe('arm-exit')+ expect(h.calls.exit).toBe(0)+ expect(h.calls.toasts).toHaveLength(2)+ h.tick(100)+ expect(h.handler({ canGoBack: true })).toBe('exit')+ })+})