fix: reschedule native workout reminders by date
This commit is contained in:
1 parent
7d2460c2c2
commit
090f615e8b
3 files changed
+140
-21
No files matched your search
+69
-19
@@ -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 */ }
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
})
|
||||
})
|
||||
Reference in new issue
Block a user