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
Settings → Apple Watch opens: the route knows it is the iPhone app on the first render
Duarte Santos1fd03d60f5d9
diff --git a/frontend/src/lib/platform-now.js b/frontend/src/lib/platform-now.jsnew file mode 100644index 000000000..1d70580ca--- /dev/null+++ b/frontend/src/lib/platform-now.js@@ -0,0 +1,10 @@+// The native shell this runs in, known at once: 'ios', 'android', or null (the web, a test).+// Capacitor's native bridge puts window.Capacitor in place before the app's own script runs, so a+// route can decide on the first render, without waiting for the async import lib/mobile.js uses+// (Settings → Apple Watch was sent back to the root by a route that only knew it later).+export function platformNow () {+ try {+ const p = globalThis.Capacitor?.getPlatform?.()+ return p === 'ios' || p === 'android' ? p : null+ } catch { return null }+}diff --git a/frontend/src/lib/watch-sync.js b/frontend/src/lib/watch-sync.jsindex b1faee9d1..b713a4333 100644--- a/frontend/src/lib/watch-sync.js+++ b/frontend/src/lib/watch-sync.js@@ -506,5 +506,9 @@ export function patchSetIn (s, { wid, exId, entryIdx, setIdx, side = null }, fieexport async function watchStatus () {const p = await watchPlugin()if (!p) return { paired: false, installed: false }- try { const st = await p.WatchBridge.status(); return { paired: !!st?.paired, installed: !!st?.installed } } catch { return { paired: false, installed: false } }+ try {+ const st = await p.WatchBridge.status()+ // `activated` false: the link is still starting (right after launch), paired/installed not known yet.+ return { paired: !!st?.paired, installed: !!st?.installed, activated: st?.activated !== false }+ } catch { return { paired: false, installed: false } }}diff --git a/frontend/src/views/Settings.jsx b/frontend/src/views/Settings.jsxindex 74080f86a..1661294ed 100644--- a/frontend/src/views/Settings.jsx+++ b/frontend/src/views/Settings.jsx@@ -47,6 +47,7 @@ import { usePasskeys, PasskeysRow, DeviceLinkRow, openDeviceLinkRedeem } from '.import { DeleteAccountRow } from '../components/DeleteAccount.jsx'import { Section, Row, SelectRow, Switch, Segmented, Button, TextField, SearchField } from '../components/ui.jsx'import { PAGES, ROOT_GROUPS, pageVisible, searchSettings, pageTrail } from './settings-pages.js'+import { platformNow } from '../lib/platform-now.js'import { pathBefore } from '../lib/nav.js'import WatchSettingsPage from './WatchSettings.jsx'@@ -67,7 +68,10 @@ let lastQuery = { q: '', key: null }export function SettingsRoute() {const { page } = useParams()const loc = useLocation()- const ctx = { user: useStore(s => s.user), mobile: MOBILE }+ // `ios` now, not after an async platform check: the Apple Watch page is iPhone only, and a route+ // that did not know yet sent every visit to it straight back to the root.+ // (Unknown counts as yes inside the phone app: the page itself then says there is no watch.)+ const ctx = { user: useStore(s => s.user), mobile: MOBILE, ios: MOBILE && platformNow() !== 'android' }if (page && (!PAGES[page] || !pageVisible(PAGES[page].parent || page, ctx))) return <Navigate to="/settings" replace />if (page === 'coach') return <Navigate to="/coach/setup" replace />return <Settings key={page || 'root'} page={page || null} find={loc.state?.find || null} via={loc.state?.via || null} entryKey={loc.key} />@@ -157,7 +161,7 @@ export default function Settings({ page = null, find = null, via = null, entryKe// --- update check state ---const [updateInfo, setUpdateInfo] = useState(null) // { hasUpdate, latestVersion, apkUrl, hashUrl } | nullconst [android, setAndroid] = useState(false)- const [ios, setIos] = useState(false) // the iPhone app: Settings → Apple Watch+ const [ios, setIos] = useState(() => MOBILE && platformNow() === 'ios') // the iPhone app: Settings → Apple Watchconst [selfUpdate, setSelfUpdate] = useState(false) // the sideloaded APK, which updates itselfconst [checking, setChecking] = useState(false)// Where auto-backup writes on this Android phone, for the Auto-backup row's own subtitle.diff --git a/frontend/src/views/Settings.watch.test.jsx b/frontend/src/views/Settings.watch.test.jsxnew file mode 100644index 000000000..9eb9fe37f--- /dev/null+++ b/frontend/src/views/Settings.watch.test.jsx@@ -0,0 +1,118 @@+// @vitest-environment happy-dom+import React, { act } from 'react'+import { createRoot } from 'react-dom/client'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { MemoryRouter, Routes, Route } from 'react-router-dom'+import Settings, { SettingsRoute } from './Settings.jsx'++globalThis.IS_REACT_ACT_ENVIRONMENT = true++// Settings → Apple Watch opens on the iPhone app. The route used to decide before it knew the+// platform (an async check) and sent every visit to /settings/watch back to the root: the page+// could never be opened ("Apple Watch settings is not working"). Mocks as in Settings.health.test.+const mocks = vi.hoisted(() => {+ const state = { S: null, MOBILE: true, android: true, status: { status: 'available', granted: false }, health: { on: false, written: {}, error: null } }+ state.snapshot = () => ({+ S: state.S, user: null, update: vi.fn(),+ replaceState: vi.fn(), setUser: vi.fn(), pullState: vi.fn(), pushState: vi.fn(),+ signOut: vi.fn(), signOutAll: vi.fn(), resetDemo: vi.fn(), disconnectServer: vi.fn(),+ })+ state.enableHealth = vi.fn(async () => { state.health = { ...state.health, on: true }; return { ok: true, health: state.health } })+ state.disableHealth = vi.fn(async ({ removeWritten }) => { state.health = { ...state.health, on: false, written: removeWritten ? {} : state.health.written }; return state.health })+ state.openHealthConnect = vi.fn(async () => {})+ state.menuSheet = vi.fn()+ state.toast = vi.fn()+ return state+})+vi.mock('../store/useStore.js', () => {+ const useStore = selector => selector ? selector(mocks.snapshot()) : mocks.snapshot()+ useStore.getState = mocks.snapshot+ return { useStore, DEF: { reminder: { time: '17:30' } }, hasData: () => false }+})+vi.mock('../store/useUI.js', () => {+ const snap = () => ({ toast: mocks.toast, openSheet: vi.fn() })+ const useUI = selector => selector ? selector(snap()) : snap()+ useUI.getState = snap+ return { useUI }+})+vi.mock('./WatchSettings.jsx', () => ({ default: () => <div id="watch-page">watch page</div> }))+vi.mock('../lib/api.js', () => ({ api: vi.fn(), webauthnOK: () => false, passkeyLogin: vi.fn(), passkeyRegister: vi.fn(), IS_ANDROID: false }))+vi.mock('../lib/push.js', () => ({ pushSupported: () => false, enablePush: vi.fn(), disablePush: vi.fn(), sendTestPush: vi.fn() }))+vi.mock('../lib/wakelock.js', () => ({ wakeLockSupported: () => false }))+vi.mock('../lib/mobile.js', () => ({+ get MOBILE() { return mocks.MOBILE },+ isAndroid: () => Promise.resolve(mocks.android),+ shareExport: vi.fn(), syncReminder: vi.fn(),+}))+vi.mock('../lib/update.js', () => ({ checkForUpdate: () => Promise.resolve({ hasUpdate: false }), downloadAndInstall: vi.fn() }))+vi.mock('../lib/health-sync.js', () => ({+ healthStatus: () => Promise.resolve(mocks.status),+ loadHealth: () => Promise.resolve(mocks.health),+ enableHealth: (...a) => mocks.enableHealth(...a),+ disableHealth: (...a) => mocks.disableHealth(...a),+ openHealthConnect: (...a) => mocks.openHealthConnect(...a),+ onHealthChange: () => () => {},+}))+vi.mock('./MobileOnboarding.jsx', () => ({ ConnectSheet: () => null }))+vi.mock('../sheets.jsx', () => ({+ starterPlanSheet: vi.fn(), confirmSheet: vi.fn(), importFromApp: vi.fn(),+ importFromHevy: vi.fn(), equipmentProfileSheet: vi.fn(), menuSheet: (...a) => mocks.menuSheet(...a),+}))++globalThis.__APP_VERSION__ ??= 'test'++let host, root+beforeEach(() => {+ mocks.S = { unit: 'kg', restSec: 90, restPauseSec: 15, sound: false, effort: 'none', gifSize: 'full', workouts: [], routines: [], exWeights: {} }+ mocks.MOBILE = true+ mocks.android = false+ host = document.createElement('div')+ document.body.appendChild(host)+ root = createRoot(host)+})+afterEach(() => {+ act(() => root.unmount())+ host.remove()+ delete globalThis.Capacitor+})++const open = async path => {+ await act(async () => {+ root.render(<MemoryRouter initialEntries={[path]}><Routes>+ <Route path="/settings" element={<div id="root-page">root</div>} />+ <Route path="/settings/:page" element={<SettingsRoute />} />+ </Routes></MemoryRouter>)+ })+ await act(async () => { await Promise.resolve(); await Promise.resolve() })+}++describe('Settings → Apple Watch', () => {+ it('opens on the iPhone app, on the first render', async () => {+ globalThis.Capacitor = { getPlatform: () => 'ios' }+ await open('/settings/watch')+ expect(host.querySelector('#watch-page')).toBeTruthy()+ expect(host.querySelector('#root-page')).toBeNull()+ })++ it('opens too when the platform is not known yet inside the app (the page then says what it finds)', async () => {+ await open('/settings/watch')+ expect(host.querySelector('#watch-page')).toBeTruthy()+ })++ it('goes back to the root on Android and on the web', async () => {+ globalThis.Capacitor = { getPlatform: () => 'android' }+ mocks.android = true+ await open('/settings/watch')+ expect(host.querySelector('#root-page')).toBeTruthy()+ delete globalThis.Capacitor+ mocks.MOBILE = false+ await open('/settings/watch')+ expect(host.querySelector('#root-page')).toBeTruthy()+ })++ it('has its row on the root at once on the iPhone app', async () => {+ globalThis.Capacitor = { getPlatform: () => 'ios' }+ await act(async () => { root.render(<MemoryRouter><Settings /></MemoryRouter>) })+ expect([...host.querySelectorAll('.lrow')].some(r => r.textContent.includes('Apple Watch'))).toBe(true)+ })+})diff --git a/frontend/src/views/WatchSettings.jsx b/frontend/src/views/WatchSettings.jsxindex a79a40327..d56e78b60 100644--- a/frontend/src/views/WatchSettings.jsx+++ b/frontend/src/views/WatchSettings.jsx@@ -18,7 +18,20 @@ export default function WatchSettingsPage() {const [link, setLink] = useState(null) // { paired, installed } from the phone, or null while askingconst [healthOn, setHealthOn] = useState(null) // the phone's Apple Health switch, null while readinguseEffect(() => onWatchPrefs(() => { setPrefs(readWatchPrefs()); setStatus(readWatchStatus()) }), [])- useEffect(() => { watchStatus().then(setLink).catch(() => setLink({ paired: false, installed: false })) }, [])+ // Asked again while the phone's link to the watch is still starting (right after launch it knows+ // nothing yet, and "no watch" would be wrong), for up to a few seconds.+ useEffect(() => {+ let gone = false, tries = 0, tm = null+ const ask = () => watchStatus()+ .then(st => {+ if (gone) return+ if (st.activated === false && tries++ < 8) { tm = setTimeout(ask, 750); return }+ setLink(st)+ })+ .catch(() => { if (!gone) setLink({ paired: false, installed: false }) })+ ask()+ return () => { gone = true; clearTimeout(tm) }+ }, [])useEffect(() => {let gone = falseloadHealth().then(h => { if (!gone) setHealthOn(!!h?.on) }).catch(() => { if (!gone) setHealthOn(false) })