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
Follow-up to #296: the iOS app no longer starts with a rejected promise from a rest-notification plugin it does not have, and the Android app registers that plugin once instead of on every rest
Duarte Santosabbcfd86e661
diff --git a/frontend/src/lib/rest-alert.js b/frontend/src/lib/rest-alert.jsindex f67021515..f468e70e0 100644--- a/frontend/src/lib/rest-alert.js+++ b/frontend/src/lib/rest-alert.js@@ -60,6 +60,18 @@ const enqueue = fn => {return run}+// The native plugin, registered once: registerPlugin() warns on every call after the first. It+// travels inside an object because a Capacitor plugin proxy answers `then` with a native call that+// never settles, so a promise resolved with the bare proxy hangs for good (the Coach hang, #42).+// Anything but the Android app gets null and registers nothing: iOS has no RestAlert, and every+// call to it there, addListener included, rejects.+let pluginP = null+const restPlugin = () => pluginP || (pluginP = (async () => {+ if (!(await isAndroid())) return null+ const { registerPlugin } = await import('@capacitor/core')+ return { RestAlert: registerPlugin('RestAlert') }+})().catch(() => null))+// Resolves true only when an Android alarm was scheduled. Callers use false as// "fall back to the server push" — web, iOS, and a failed schedule.export function armRestAlert(at, opts = {}) {@@ -88,11 +100,12 @@ export function disarmRestAlert() {let onNativeRest = nullexport function bindNativeRest(cb) { onNativeRest = cb }+// Caught, and only on Android: in the iOS app this listener used to reject at startup with+// nobody to catch it.if (MOBILE) {- import('@capacitor/core').then(({ registerPlugin }) => {- const RestAlert = registerPlugin('RestAlert')- RestAlert.addListener('rest', ev => { if (onNativeRest) onNativeRest(ev) })- }).catch(() => {})+ restPlugin()+ .then(p => p && p.RestAlert.addListener('rest', ev => { if (onNativeRest) onNativeRest(ev) }))+ .catch(() => {})}// The running countdown repaints with this swatch. No-op when no rest is on screen.@@ -100,20 +113,16 @@ export function setRestAccent(key) {if (!MOBILE) returnconst { accent, ink } = accentColors(key)enqueue(async () => {- if (!(await isAndroid())) return- const { registerPlugin } = await import('@capacitor/core')- const RestAlert = registerPlugin('RestAlert')- await RestAlert.setAccent({ accent, ink })+ const p = await restPlugin()+ if (p) await p.RestAlert.setAccent({ accent, ink })})}export function hushRestTone() {if (!MOBILE) returnenqueue(async () => {- if (!(await isAndroid())) return- const { registerPlugin } = await import('@capacitor/core')- const RestAlert = registerPlugin('RestAlert')- await RestAlert.suppressTone()+ const p = await restPlugin()+ if (p) await p.RestAlert.suppressTone()})}@@ -131,10 +140,10 @@ async function ensureNotifPermission() {}async function deliver(alert) {- if (!(await isAndroid())) return 'skipped'+ const p = await restPlugin()+ if (!p) return 'skipped'+ const { RestAlert } = pawait ensureNotifPermission()- const { registerPlugin } = await import('@capacitor/core')- const RestAlert = registerPlugin('RestAlert')// Sound still schedules when notification permission is missing: the alarm tone does// not need it. The notification does, which is why we ask above.await RestAlert.schedule({@@ -160,8 +169,6 @@ async function deliver(alert) {}async function cancelDelivered() {- if (!(await isAndroid())) return- const { registerPlugin } = await import('@capacitor/core')- const RestAlert = registerPlugin('RestAlert')- await RestAlert.cancel({ id: REST_ALERT_ID })+ const p = await restPlugin()+ if (p) await p.RestAlert.cancel({ id: REST_ALERT_ID })}diff --git a/frontend/src/lib/rest-alert.native.test.js b/frontend/src/lib/rest-alert.native.test.jsnew file mode 100644index 000000000..17d5a0050--- /dev/null+++ b/frontend/src/lib/rest-alert.native.test.js@@ -0,0 +1,97 @@+// The Capacitor side of the rest alert (#296). The iOS app has no RestAlert plugin, and the+// listener this file adds at startup used to reject there with nothing to catch it. On Android+// the plugin is a Capacitor proxy that answers `then` with a native call that never settles, so+// it must never become the value of a promise (the Coach hang, #42): here that would hang every+// rest alert call.+import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest'++const h = vi.hoisted(() => {+ vi.stubEnv('VITE_MOBILE', '1') // lib/mobile.js: MOBILE = import.meta.env.VITE_MOBILE === '1'+ return { platform: 'android', calls: [], registerPlugin: null }+})++// Shaped like the proxy registerPlugin() returns: every property is a native method, `then`+// included, and that one never calls back. Off Android every method rejects, as Capacitor's do+// for a plugin the platform does not have.+const pluginProxy = () => new Proxy({}, {+ get: (_, prop) => {+ if (prop === 'then') return () => new Promise(() => {})+ return (...args) => {+ h.calls.push(String(prop))+ if (h.platform !== 'android') return Promise.reject(new Error(`"RestAlert.${String(prop)}()" is not implemented on ${h.platform}`))+ return Promise.resolve(prop === 'addListener' ? { remove: async () => {} } : undefined)+ }+ },+})++vi.mock('@capacitor/core', () => ({+ Capacitor: { getPlatform: () => h.platform },+ registerPlugin: (...args) => h.registerPlugin(...args),+}))+vi.mock('@capacitor/local-notifications', () => ({+ LocalNotifications: {+ checkPermissions: async () => ({ display: 'granted' }),+ requestPermissions: async () => ({ display: 'granted' }),+ },+}))++const settle = async () => { for (let i = 0; i < 10; i++) await new Promise(r => setTimeout(r, 0)) }++const unhandled = []+const onUnhandled = reason => unhandled.push(reason)++beforeEach(() => {+ vi.resetModules()+ h.calls = []+ h.registerPlugin = vi.fn(() => pluginProxy())+ unhandled.length = 0+ process.on('unhandledRejection', onUnhandled)+})+afterAll(() => {+ process.off('unhandledRejection', onUnhandled)+ vi.unstubAllEnvs()+})++describe('the rest alert in the iOS app', () => {+ it('registers nothing, rejects nothing and leaves the end to the server push', async () => {+ h.platform = 'ios'+ const alert = await import('./rest-alert.js')+ await expect(alert.armRestAlert(Date.now() + 90_000, { totalSec: 90 })).resolves.toBe(false)+ alert.setRestAccent('red')+ alert.disarmRestAlert()+ await settle()+ expect(h.registerPlugin).not.toHaveBeenCalled()+ expect(h.calls).toEqual([])+ expect(unhandled).toEqual([])+ })+})++describe('the rest alert in the Android app', () => {+ it('reaches the plugin without ever waiting on the proxy, and registers it once', async () => {+ h.platform = 'android'+ const alert = await import('./rest-alert.js')+ await expect(alert.armRestAlert(Date.now() + 90_000, { totalSec: 90 })).resolves.toBe(true)+ alert.setRestAccent('red')+ alert.disarmRestAlert()+ await settle()+ expect(h.registerPlugin).toHaveBeenCalledTimes(1)+ expect(h.calls).toContain('addListener')+ expect(h.calls.filter(c => c !== 'addListener')).toEqual(['schedule', 'setAccent', 'cancel'])+ expect(unhandled).toEqual([])+ })++ it('passes what the notification needs: the end, the whole rest, the labels and the accent', async () => {+ h.platform = 'android'+ const schedule = vi.fn(async () => {})+ h.registerPlugin = vi.fn(() => new Proxy({}, {+ get: (_, prop) => prop === 'then' ? () => new Promise(() => {}) : prop === 'schedule' ? schedule : async () => ({ remove: async () => {} }),+ }))+ const alert = await import('./rest-alert.js')+ const at = Date.now() + 90_000+ await alert.armRestAlert(at, { totalSec: 90, accent: 'red', sound: false })+ expect(schedule).toHaveBeenCalledWith(expect.objectContaining({+ at, totalMs: 90_000, sound: false, pause: 'Pause', resume: 'Resume', skip: 'Skip',+ accent: (0xff000000 | 0xff453a) >>> 0, ink: 0xffffffff,+ }))+ })+})