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
Back: one press leaves a page a sheet or the routine chooser opened
Duarte Santosa1dc57604a3e
diff --git a/frontend/src/components/WorkoutSettingsSheet.jsx b/frontend/src/components/WorkoutSettingsSheet.jsxindex 1bad212e1..1c1ca2624 100644--- a/frontend/src/components/WorkoutSettingsSheet.jsx+++ b/frontend/src/components/WorkoutSettingsSheet.jsx@@ -5,7 +5,7 @@ import { effortOf } from '../lib/history.js'import { unlock, vibrateSupported, appleTouchDevice } from '../lib/sound.js'import { wakeLockSupported } from '../lib/wakelock.js'import { MOBILE } from '../lib/mobile.js'-import { nav } from '../lib/nav.js'+import { closeThenNav } from '../lib/nav.js'import { REST_MAX, fmtRest } from '../lib/duration.js'import { durationSheet } from './DurationWheel.jsx'import { Section, Row, Switch, Segmented, Button } from './ui.jsx'@@ -24,7 +24,7 @@ export function WorkoutSettings({ close }) {const wakeOK = wakeLockSupported()const layout = ['list', 'compact'].includes(S.active?.workoutView || S.workoutView) ? (S.active?.workoutView || S.workoutView) : 'cards'const gif = S.gifSize === 'mini' || S.gifSize === 'off' ? S.gifSize : 'full'- const allSettings = () => { close(); nav('/settings/workout') }+ const allSettings = () => closeThenNav(close, '/settings/workout')return <div className="ws-sheet"><div className="row between" style={{ marginBottom: 2 }}><h3 style={{ margin: 0 }}>{t('Workout settings')}</h3>diff --git a/frontend/src/components/WorkoutSettingsSheet.test.jsx b/frontend/src/components/WorkoutSettingsSheet.test.jsxindex a85939e56..9718674f0 100644--- a/frontend/src/components/WorkoutSettingsSheet.test.jsx+++ b/frontend/src/components/WorkoutSettingsSheet.test.jsx@@ -15,7 +15,11 @@ vi.mock('../lib/sound.js', () => ({}))vi.mock('../lib/wakelock.js', () => ({ wakeLockSupported: () => true }))const navTo = vi.hoisted(() => vi.fn())-vi.mock('../lib/nav.js', () => ({ nav: navTo }))+vi.mock('../lib/nav.js', async importOriginal => {+ const real = await importOriginal()+ real.setNav(navTo)+ return real+})let host, root, originalS, close@@ -101,4 +105,13 @@ describe('the in-workout settings sheet', () => {expect(close).toHaveBeenCalled()expect(navTo).toHaveBeenCalledWith('/settings/workout')})++ // The sheet's own history entry used to stay behind: back from Settings went to the workout, and+ // the next back landed on the same workout again and seemed to do nothing.+ it('Settings takes the sheet\'s history entry instead of leaving it behind', () => {+ history.pushState({ openGymSheet: true }, '')+ act(() => row('All settings').click())+ expect(navTo).toHaveBeenCalledWith('/settings/workout', { replace: true })+ history.replaceState(null, '')+ })})diff --git a/frontend/src/lib/nav.js b/frontend/src/lib/nav.jsindex 7aa6b4b55..0a5f1ff84 100644--- a/frontend/src/lib/nav.js+++ b/frontend/src/lib/nav.js@@ -1,4 +1,26 @@// Lets non-component modules (sheet flows) navigate. App registers the router's navigate.let _nav = () => {}export const setNav = fn => { _nav = fn }-export const nav = to => _nav(to)+// `opts` goes to the router as is ({ replace: true }).+export const nav = (to, opts) => (opts ? _nav(to, opts) : _nav(to))++// Every open sheet sits on a history entry of its own (Modals.jsx), and closing it walks back+// only while the page is still where the sheet opened. A sheet that closes and moves to another+// page at once left that entry behind: back from the new page landed on it, the same page with+// no sheet, and the next back seemed to do nothing. The new page takes the sheet's entry instead.+export const onSheetEntry = () => {+ try { return !!globalThis.history?.state?.openGymSheet } catch { return false }+}++export function closeThenNav(close, to) {+ const replace = onSheetEntry()+ close()+ nav(to, replace ? { replace: true } : undefined)+}++// Into the workout screen: from the routine chooser (already #/workout) or from a sheet's entry,+// the session takes that entry, so one back leaves it rather than landing on itself.+export function navToWorkout() {+ const here = String(globalThis.location?.hash || '').startsWith('#/workout')+ nav('/workout', here || onSheetEntry() ? { replace: true } : undefined)+}diff --git a/frontend/src/lib/nav.test.js b/frontend/src/lib/nav.test.jsnew file mode 100644index 000000000..fe0b7cde6--- /dev/null+++ b/frontend/src/lib/nav.test.js@@ -0,0 +1,52 @@+// Android back after a sheet that closes and moves on (#/workout ⋯ > Workout settings > All+// settings, Finish > Nice!, Start > a routine): the sheet's history entry, or the chooser's+// #/workout, stayed under the new page, so one back press landed on the same screen and seemed+// to do nothing.+// @vitest-environment happy-dom+import { beforeEach, describe, expect, it, vi } from 'vitest'+import { closeThenNav, nav, navToWorkout, setNav } from './nav.js'++let calls+beforeEach(() => {+ calls = []+ setNav((...args) => { calls.push(args) })+ history.replaceState(null, '', '#/home')+})++describe('nav', () => {+ it('passes the router its options', () => {+ nav('/plan', { replace: true })+ nav('/stats')+ expect(calls).toEqual([['/plan', { replace: true }], ['/stats']])+ })++ it('a closing sheet hands its history entry to the next page', () => {+ history.pushState({ openGymSheet: true }, '')+ const close = vi.fn()+ closeThenNav(close, '/settings/workout')+ expect(close).toHaveBeenCalledOnce()+ expect(calls).toEqual([['/settings/workout', { replace: true }]])+ })++ it('pushes when the entry is not a sheet\'s (it was spent already)', () => {+ closeThenNav(() => {}, '/home')+ expect(calls).toEqual([['/home']])+ })++ it('starting from the routine chooser replaces its #/workout', () => {+ history.replaceState(null, '', '#/workout')+ navToWorkout()+ expect(calls).toEqual([['/workout', { replace: true }]])+ })++ it('starting through the weigh-in sheet replaces the sheet\'s entry', () => {+ history.pushState({ openGymSheet: true }, '')+ navToWorkout()+ expect(calls).toEqual([['/workout', { replace: true }]])+ })++ it('starting from Home pushes, so back returns there', () => {+ navToWorkout()+ expect(calls).toEqual([['/workout']])+ })+})diff --git a/frontend/src/sheets.jsx b/frontend/src/sheets.jsxindex cc269fa7e..e4a3b4d7d 100644--- a/frontend/src/sheets.jsx+++ b/frontend/src/sheets.jsx@@ -10,7 +10,7 @@ import { PLATE_SIZES, pairsOf, ownsPlates, withPlatePairs, withStandardPlates, wimport { toScale, rirOf, EFFORT_PRESETS, effortColor } from './lib/effort.js'import { beep, vibrate } from './lib/sound.js'import { t, tn, dateLocale, instrFor, exerciseNameFor, exerciseNameClass, getLang, INSTR_LANGS } from './lib/i18n.js'-import { nav } from './lib/nav.js'+import { nav, closeThenNav, navToWorkout } from './lib/nav.js'import { buildStarterPlan, starterPlanDays, starterPlanOptions } from './lib/starter.js'import Media, { Thumb } from './components/Media.jsx'import CustomMediaField from './components/CustomMediaField.jsx'@@ -295,7 +295,7 @@ function BwSheet({ required, onDone, close }) {<Button variant="primary" onClick={save}>{required ? t('Save & start workout') : t('Save')}</Button>{required && <><div style={{ height: 8 }} /><Button variant="ghost" className="dim" onClick={() => { close(); onDone && onDone(null) }}>{t('Start without weighing in')}</Button>- <div style={{ height: 2 }} /><Button variant="ghost" className="dim" icon="swap" onClick={() => { close(); nav('/workout') }}>{t('Choose a different workout')}</Button>+ <div style={{ height: 2 }} /><Button variant="ghost" className="dim" icon="swap" onClick={() => closeThenNav(close, '/workout')}>{t('Choose a different workout')}</Button></>}{!required && recent.length > 0 && <><h4 className="sec">{t('Recent weigh-ins')}</h4>@@ -2214,7 +2214,7 @@ function WorkoutDetail({ w, close }) {<Button icon="pencil" disabled={!!st.active} onClick={() => {saveNote()initial.current = latest.current.trim().slice(0, NOTE_MAX)- try { update(state => { editCompletedSession(state, w) }); close(); nav('/workout') }+ try { update(state => { editCompletedSession(state, w) }); closeThenNav(close, '/workout') }catch (error) { toast(t(error.message)) }}}>{t('Edit workout')}</Button><div style={{ height: 8 }} />@@ -2354,7 +2354,7 @@ export function beginWorkout(routineIds, bw) {}})useUI.getState().stopRest()- nav('/workout')+ navToWorkout()}// "Repeat today" (#58): a saved workout's exercises as a new freestyle session dated today, each@@ -2375,8 +2375,7 @@ export function repeatWorkout(w, close) {}})useUI.getState().stopRest()- if (close) close()- nav('/workout')+ if (close) closeThenNav(close, '/workout'); else navToWorkout()if (skipped) toast(tn('{0} exercise no longer exists and was left out.', '{0} exercises no longer exist and were left out.', skipped))}if (st.weighIn === false) { go(null); return }@@ -2486,7 +2485,7 @@ function beginBackfill({ iso, time, durationMin, routineIds, replaceId }) {}})useUI.getState().stopRest()- nav('/workout')+ navToWorkout()}/* ============================ add a routine mid-session ============================ */@@ -2769,7 +2768,7 @@ function FinishSummary({ w, prs, e1prs = [], close }) {{/* The moment for a progress photo or the clip of a set: the workout is already saved, sowhat is added here goes straight onto its record. */}<div style={{ textAlign: 'start' }}><WorkoutMediaSection w={w} hint /></div>- <Button variant="primary" onClick={() => { close(); nav('/home') }}>{t('Nice!')}</Button>+ <Button variant="primary" onClick={() => closeThenNav(close, '/home')}>{t('Nice!')}</Button></div>}export function finishWorkout() {diff --git a/frontend/src/views/CoachChat.jsx b/frontend/src/views/CoachChat.jsxindex cbd0a494a..eacc836ba 100644--- a/frontend/src/views/CoachChat.jsx+++ b/frontend/src/views/CoachChat.jsx@@ -14,6 +14,7 @@// on this screen.import { useEffect, useMemo, useRef, useState } from 'react'import { useNavigate } from 'react-router-dom'+import { closeThenNav } from '../lib/nav.js'import { useStore } from '../store/useStore.js'import { useUI } from '../store/useUI.js'import { t, tn } from '../lib/i18n.js'@@ -161,7 +162,7 @@ export default function CoachChat() {{community && <Row icon="person" iconTint="var(--teal)" title={t('Compare with others here')} subtitle={t('Anonymous medians from this instance')} accessory="chevron" onClick={() => { close(); showCohort() }} />}<Row icon="history" iconTint="var(--blue)" title={t('Everything the Coach proposed')} subtitle={t('Plans, suggestions and debriefs, kept')} accessory="chevron" onClick={() => { close(); showHistory() }} />{idle && <Row icon="clipboard" iconTint="var(--indigo)" title={t('Start a new plan')} subtitle={t('A fresh plan from your answers; your workouts stay')} accessory="chevron" onClick={() => { close(); askNewPlan() }} />}- <Row icon="pencil" iconTint="var(--indigo)" title={t('Edit my answers')} subtitle={t('Goal, days, equipment, limits')} accessory="chevron" onClick={() => { close(); nav('/coach/intake?edit=1') }} />+ <Row icon="pencil" iconTint="var(--indigo)" title={t('Edit my answers')} subtitle={t('Goal, days, equipment, limits')} accessory="chevron" onClick={() => closeThenNav(close, '/coach/intake?edit=1')} /><Row icon="clock" iconTint="var(--purple)" title={t('Automatic reviews')} subtitle={cadenceLabel(coach)} accessory="chevron" onClick={() => { close(); cadenceSheet(openSheet, update) }} />{canRevert(S) && <Row icon="reset" iconTint="var(--blue)" title={t('Undo the last Coach changes')} accessory="chevron" onClick={() => { close(); doRevert() }} />}</div>