diff --git a/frontend/src/lib/mobile.js b/frontend/src/lib/mobile.js index cc848d2..6631eb4 100644 --- a/frontend/src/lib/mobile.js +++ b/frontend/src/lib/mobile.js @@ -4,13 +4,14 @@ // mode in a browser, this is the user's only copy of their training log, so it can't depend // on WebView localStorage alone (iOS evicts that under storage pressure). Every persist() // therefore also lands in a JSON file in the app's private data directory, and boot() -// restores from it. The workout reminder uses native local notifications scheduled per -// planned weekday — no server involved, unlike Web Push in the self-hosted version. +// restores from it. The workout reminder uses native local notifications scheduled per future +// calendar date — no server involved, unlike Web Push in the self-hosted version. // // Like the demo build, MOBILE is replaced at build time, so all of this folds away in // web bundles; the Capacitor plugins are only ever imported behind it. import { t } from './i18n-core.js' -import { todayISO } from './format.js' +import { isoOf, todayISO } from './format.js' +import { effectiveRoutineId } from './history.js' export const MOBILE = import.meta.env.VITE_MOBILE === '1' @@ -52,34 +53,83 @@ export async function saveRemoteFile(data) { } catch (e) { /* worst case: onboarding asks again next launch */ } } -// (Re)schedule the workout-day reminder: one repeating notification per weekday that has a -// routine in the weekly plan. Cheap enough to run after any state change — the plan or the -// reminder time may just have been edited. `interactive` gates the OS permission prompt to -// the Settings toggle; a background resync never pops a dialog. +// Keep enough dates queued to cover normal app use between foregrounds without creating an +// unbounded notification list. The next sync cancels and replaces this whole window. +export const REMINDER_WINDOW_DAYS = 60 +const REMINDER_ID_BASE = 1000 +const LEGACY_REMINDER_IDS = Array.from({ length: 7 }, (_, d) => ({ id: 100 + d })) + +// Pure date expansion for the native reminder. `now` is injectable so the calendar boundary, +// completed-day suppression, and today's past-time rule stay deterministic in tests. +export function buildReminderNotifications(S, now = new Date()) { + const r = S?.reminder + if (!r?.on) return [] + const routines = Array.isArray(S.routines) ? S.routines : [] + const completed = new Set((S.workouts || []).map(w => w.d)) + const state = { ...S, routines, week: S.week || {}, dayPlan: S.dayPlan || {} } + const [hour, minute] = (r.time || '08:00').split(':').map(Number) + if (!Number.isInteger(hour) || !Number.isInteger(minute)) return [] + const date = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 12) + const notifications = [] + for (let offset = 0; offset < REMINDER_WINDOW_DAYS; offset++) { + const day = new Date(date) + day.setDate(date.getDate() + offset) + const iso = isoOf(day) + if (completed.has(iso)) continue + const rid = effectiveRoutineId(state, iso) + const routine = routines.find(x => x.id === rid) + if (!routine) continue + const at = new Date(day) + at.setHours(hour, minute, 0, 0) + if (at <= now) continue + notifications.push({ + id: REMINDER_ID_BASE + offset, + title: t('Workout day'), + body: t('{0} is on the plan today — let’s go!', routine.name), + schedule: { at, allowWhileIdle: true }, + }) + } + return notifications +} + +// (Re)schedule the workout-day reminder: one one-off notification per future calendar date in +// the bounded window. Cheap enough to run after any state change — the plan or the reminder time +// may just have been edited. `interactive` gates the OS permission prompt to the Settings toggle; +// a background resync never pops a dialog. export async function syncReminder(S, interactive = false) { try { const { LocalNotifications } = await import('@capacitor/local-notifications') - await LocalNotifications.cancel({ notifications: [0, 1, 2, 3, 4, 5, 6].map(d => ({ id: 100 + d })) }).catch(() => {}) + await LocalNotifications.cancel({ notifications: [ + ...LEGACY_REMINDER_IDS, + ...Array.from({ length: REMINDER_WINDOW_DAYS }, (_, d) => ({ id: REMINDER_ID_BASE + d })), + ] }).catch(() => {}) const r = S.reminder if (!r?.on) return true let perm = await LocalNotifications.checkPermissions() if (perm.display !== 'granted' && interactive) perm = await LocalNotifications.requestPermissions() if (perm.display !== 'granted') return false - const [hour, minute] = (r.time || '08:00').split(':').map(Number) - const notifications = Object.entries(S.week || {}) - .filter(([, rid]) => rid && (S.routines || []).some(x => x.id === rid)) - .map(([day, rid]) => ({ - id: 100 + Number(day), - title: t('Workout day'), - body: t('{0} is on the plan today — let’s go!', S.routines.find(x => x.id === rid).name), - // Capacitor weekdays are 1 (Sunday) … 7 (Saturday); S.week uses getDay() 0…6. - schedule: { on: { weekday: Number(day) + 1, hour, minute }, allowWhileIdle: true }, - })) + const notifications = buildReminderNotifications(S) if (notifications.length) await LocalNotifications.schedule({ notifications }) return true } catch (e) { return false } } +// Capacitor emits appStateChange when the native shell returns to the foreground. The visibility +// listener also covers WebView/browser transitions, and both are harmless on a non-mobile build. +let reminderSyncStarted = false +export function initReminderSync(getState) { + if (!MOBILE || reminderSyncStarted) return + reminderSyncStarted = true + const resync = () => { + if (document.visibilityState === 'hidden') return + syncReminder(getState()).catch(() => {}) + } + document.addEventListener('visibilitychange', resync) + import('@capacitor/app').then(({ App }) => { + App.addListener('appStateChange', ({ isActive }) => { if (isActive) resync() }) + }).catch(() => {}) +} + // WKWebView can't do blob-URL downloads, so the backup goes out through the OS share sheet // (Files, AirDrop, mail, …) from a temp file instead. export async function shareExport(json, filename) { @@ -104,4 +154,4 @@ export async function writeAutoBackup(state) { recursive: true, }) } catch (e) { /* best effort — the private mirror in Directory.Data still has the data */ } -} +} \ No newline at end of file diff --git a/frontend/src/lib/mobile.test.js b/frontend/src/lib/mobile.test.js new file mode 100644 index 0000000..c43a395 --- /dev/null +++ b/frontend/src/lib/mobile.test.js @@ -0,0 +1,62 @@ +import { describe, expect, it } from 'vitest' +import { isoOf } from './format.js' +import { buildReminderNotifications } from './mobile.js' + +const push = { id: 'push', name: 'Push' } +const pull = { id: 'pull', name: 'Pull' } +const legs = { id: 'legs', name: 'Legs' } +const state = (patch = {}) => ({ + routines: [push, pull, legs], week: {}, dayPlan: {}, workouts: [], + reminder: { on: true, time: '08:00' }, ...patch, +}) +const iso = d => isoOf(d) + +describe('buildReminderNotifications', () => { + it('expands the weekly baseline into future dated notifications', () => { + const now = new Date(2026, 5, 1, 7, 0) // Monday + const notifications = buildReminderNotifications(state({ week: { 1: 'push', 3: 'pull' } }), now) + + expect(notifications.slice(0, 2).map(n => iso(n.schedule.at))).toEqual([ + iso(now), iso(new Date(2026, 5, 3)), + ]) + expect(notifications[0].body).toContain('Push') + expect(notifications[0].schedule.allowWhileIdle).toBe(true) + }) + + it('uses rest today and a routine override tomorrow when rescheduling', () => { + const now = new Date(2026, 5, 1, 7, 0) // Monday + const today = iso(now), tomorrow = iso(new Date(2026, 5, 2)) + const notifications = buildReminderNotifications(state({ + week: { 1: 'push' }, dayPlan: { [today]: 'rest', [tomorrow]: 'pull' }, + }), now) + + expect(notifications.slice(0, 1).map(n => [iso(n.schedule.at), n.body])).toEqual([ + [tomorrow, expect.stringContaining('Pull')], + ]) + }) + + it('schedules a valid override on a weekly rest day', () => { + const now = new Date(2026, 5, 1, 7, 0) // Monday + const wednesday = new Date(2026, 5, 3) + const notifications = buildReminderNotifications(state({ dayPlan: { [iso(wednesday)]: 'legs' } }), now) + + expect(notifications.some(n => iso(n.schedule.at) === iso(wednesday) && n.body.includes('Legs'))).toBe(true) + }) + + it('suppresses dates that already have a completed workout', () => { + const now = new Date(2026, 5, 1, 7, 0) // Monday + const notifications = buildReminderNotifications(state({ + week: { 1: 'push' }, workouts: [{ d: iso(now) }], + }), now) + + expect(notifications.some(n => iso(n.schedule.at) === iso(now))).toBe(false) + }) + + it("skips today's reminder after the configured local time has passed", () => { + const now = new Date(2026, 5, 1, 9, 0) // Monday + const notifications = buildReminderNotifications(state({ week: { 1: 'push' } }), now) + + expect(notifications.some(n => iso(n.schedule.at) === iso(now))).toBe(false) + expect(notifications.some(n => iso(n.schedule.at) === iso(new Date(2026, 5, 8)))).toBe(true) + }) +}) \ No newline at end of file diff --git a/frontend/src/store/useStore.js b/frontend/src/store/useStore.js index 8697867..0ec3bdb 100644 --- a/frontend/src/store/useStore.js +++ b/frontend/src/store/useStore.js @@ -4,7 +4,7 @@ import { localTZ } from '../lib/format.js' import { registerCustom } from '../lib/exercises.js' import { DEMO, DEMO_SEEDED } from '../lib/demo.js' import { guestAllowed } from '../lib/guest.js' -import { MOBILE, nativeLoad, nativeSave, syncReminder, writeAutoBackup } from '../lib/mobile.js' +import { MOBILE, initReminderSync, nativeLoad, nativeSave, syncReminder, writeAutoBackup } from '../lib/mobile.js' import { loadRemote, chooseLocal, forgetRemote, connect } from '../lib/remote.js' const KEY = 'gym_state_v1' @@ -52,6 +52,8 @@ export const useStore = create((set, get) => { let pushTm = null let saveTm = null + initReminderSync(() => get().S) + // Mobile build: mirror the state into a file in the app's data directory (survives WebView // storage eviction) and keep the native reminder schedule in step with the weekly plan. const nativePersist = () => { @@ -81,6 +83,7 @@ export const useStore = create((set, get) => { clearTimeout(saveTm) saveTm = null nativeSave(get().S) + syncReminder(get().S) } if (pushTm) { clearTimeout(pushTm) @@ -277,4 +280,4 @@ export const useStore = create((set, get) => { } }) -export { hasData } +export { hasData } \ No newline at end of file