Add push notifications: rest-timer alert + workout-day reminder

Web Push (VAPID) backend: keys auto-generated on first run, per-user
subscriptions, one new dependency (web-push). The rest timer schedules
a server-side push on start/extend and cancels it on skip or on-screen
completion, so it only actually fires if the tab got suspended before
finishing. A per-minute check sends an optional daily reminder on days
with a planned routine that hasn't been logged yet.

Opt in per-profile in Settings — requires a signed-in passkey profile.
This commit is contained in:
Duarte Santos committed 2026-07-21 11:07:10 +02:00
1 parent 84c59129e3
commit 4c2b6344f7
11 files changed
+448 -7

No files matched your search

+18
View File
@@ -8,6 +8,24 @@ self.addEventListener('activate', e => {
Promise.all(keys.filter(k => k !== CACHE).map(k => caches.delete(k)))
).then(() => self.clients.claim()))
})
self.addEventListener('push', e => {
const data = e.data ? e.data.json() : {}
e.waitUntil(self.registration.showNotification(data.title || 'openGym', {
body: data.body || '',
icon: 'icon-512.png',
badge: 'icon-180.png',
tag: data.tag || 'opengym',
renotify: true
}))
})
self.addEventListener('notificationclick', e => {
e.notification.close()
e.waitUntil(self.clients.matchAll({ type: 'window' }).then(clients => {
const c = clients.find(c => 'focus' in c)
return c ? c.focus() : self.clients.openWindow('./')
}))
})
self.addEventListener('fetch', e => {
const url = new URL(e.request.url)
if (e.request.method !== 'GET' || url.origin !== location.origin) return
+33
View File
@@ -0,0 +1,33 @@
// Web Push subscribe/unsubscribe — requires a signed-in profile (subscriptions are stored
// server-side per user, same as everything else under /api).
import { api } from './api.js'
export const pushSupported = () => 'serviceWorker' in navigator && 'PushManager' in window && 'Notification' in window
export const pushPermission = () => (pushSupported() ? Notification.permission : 'unsupported')
const urlBase64ToUint8Array = b64 => {
const padded = (b64 + '='.repeat((4 - b64.length % 4) % 4)).replace(/-/g, '+').replace(/_/g, '/')
const raw = atob(padded)
return Uint8Array.from([...raw].map(c => c.charCodeAt(0)))
}
export async function enablePush() {
if (!pushSupported()) throw new Error('Push notifications are not supported in this browser')
const perm = await Notification.requestPermission()
if (perm !== 'granted') throw new Error('Notifications permission was not granted')
const reg = await navigator.serviceWorker.ready
const { key } = await api('/api/push/public-key')
const subscription = await reg.pushManager.subscribe({ userVisibleOnly: true, applicationServerKey: urlBase64ToUint8Array(key) })
await api('/api/push/subscribe', { method: 'POST', body: JSON.stringify({ subscription: subscription.toJSON() }) })
}
export async function disablePush() {
if (!pushSupported()) return
const reg = await navigator.serviceWorker.ready
const sub = await reg.pushManager.getSubscription()
if (!sub) return
await sub.unsubscribe()
await api('/api/push/unsubscribe', { method: 'POST', body: JSON.stringify({ endpoint: sub.endpoint }) }).catch(() => {})
}
export const sendTestPush = () => api('/api/push/test', { method: 'POST', body: '{}' })
+2 -1
View File
@@ -6,7 +6,8 @@ export const DEF = {
unit: 'kg', restSec: 90, sound: true,
theme: 'dark', accent: 'lime', targetW: null,
bodyweight: [], routines: [], week: {}, dayPlan: {},
exWeights: {}, workouts: [], active: null
exWeights: {}, workouts: [], active: null,
reminder: { on: false, time: '08:00' }
}
const clone = o => JSON.parse(JSON.stringify(o))
+15 -1
View File
@@ -1,8 +1,14 @@
import { create } from 'zustand'
import { uid } from '../lib/format.js'
import { beep, vibrate } from '../lib/sound.js'
import { api } from '../lib/api.js'
import { useStore } from './useStore.js'
// Fire-and-forget: lets the server push a "rest over" alert if this tab gets suspended
// before the local timer completes. No-ops for guests / offline.
const pushRestTimer = sec => { if (useStore.getState().user) api('/api/push/rest-timer', { method: 'POST', body: JSON.stringify({ seconds: sec }) }).catch(() => {}) }
const cancelPushRestTimer = () => { if (useStore.getState().user) api('/api/push/rest-timer/cancel', { method: 'POST', body: '{}' }).catch(() => {}) }
let toastTm = null
let timerInt = null
let timerTick = null
@@ -31,6 +37,7 @@ export const useUI = create((set, get) => ({
get().stopRest()
const endsAt = Date.now() + sec * 1000
set({ timer: { left: sec, total: sec, endsAt } })
pushRestTimer(sec)
timerTick = () => {
const t = get().timer
if (!t) return
@@ -47,10 +54,17 @@ export const useUI = create((set, get) => ({
timerInt = setInterval(timerTick, 1000)
document.addEventListener('visibilitychange', timerTick)
},
addRest(sec) { const t = get().timer; if (t) set({ timer: { ...t, left: t.left + sec, total: t.total + sec, endsAt: t.endsAt + sec * 1000 } }) },
addRest(sec) {
const t = get().timer
if (!t) return
const left = t.left + sec
set({ timer: { ...t, left, total: t.total + sec, endsAt: t.endsAt + sec * 1000 } })
pushRestTimer(left)
},
stopRest() {
if (timerInt) clearInterval(timerInt); timerInt = null
if (timerTick) document.removeEventListener('visibilitychange', timerTick); timerTick = null
if (get().timer) cancelPushRestTimer()
set({ timer: null })
}
}))
+51 -1
View File
@@ -1,9 +1,10 @@
import { useRef } from 'react'
import { useEffect, useRef, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { useStore, DEF, hasData } from '../store/useStore.js'
import { useUI } from '../store/useUI.js'
import { ACCENTS, todayISO } from '../lib/format.js'
import { webauthnOK, passkeyLogin, passkeyRegister, IS_ANDROID } from '../lib/api.js'
import { pushSupported, enablePush, disablePush, sendTestPush } from '../lib/push.js'
import { loadStarterPlan, confirmSheet } from '../sheets.jsx'
export default function Settings() {
@@ -82,6 +83,8 @@ export default function Settings() {
<div className="small dim" style={{ marginTop: 6 }}>Note: switching units only changes the label — logged numbers are not converted.</div>
</div>
{user && <NotificationsCard S={S} update={update} toast={toast} />}
<div className="card">
<h2>Data</h2>
<button className="btn" onClick={doExport}>⬇️ Export backup (JSON)</button>
@@ -100,6 +103,53 @@ export default function Settings() {
</div>
}
function NotificationsCard({ S, update, toast }) {
const [on, setOn] = useState(false)
const [busy, setBusy] = useState(false)
const supported = pushSupported()
useEffect(() => {
if (!supported) return
navigator.serviceWorker.ready.then(reg => reg.pushManager.getSubscription()).then(sub => setOn(!!sub)).catch(() => {})
}, [supported])
const toggle = async () => {
setBusy(true)
try {
if (on) { await disablePush(); setOn(false); toast('Notifications off') }
else { await enablePush(); setOn(true); toast('Notifications on 🔔') }
} catch (e) { toast(e.message || 'Could not change notification settings') }
setBusy(false)
}
const test = async () => {
try { await sendTestPush(); toast('Test sent — should arrive any second') }
catch (e) { toast(e.message || 'Test failed') }
}
return <div className="card">
<h2>Notifications</h2>
{!supported ? <div className="small dim">Not supported in this browser.</div> : <>
<div className="row between" style={{ padding: '8px 0' }}>
<div><span>Push notifications</span><div className="small muted">Rest-timer alerts, even if openGym is closed.</div></div>
<button className={'chip' + (on ? ' on' : '')} disabled={busy} onClick={toggle}>{on ? 'On 🔔' : 'Off 🔕'}</button>
</div>
{on && <>
<div className="row between" style={{ padding: '8px 0' }}>
<span>Workout day reminder</span>
<button className={'chip' + (S.reminder?.on ? ' on' : '')} onClick={() => update(s => { s.reminder = { ...(s.reminder || DEF.reminder), on: !s.reminder?.on } })}>{S.reminder?.on ? 'On' : 'Off'}</button>
</div>
{S.reminder?.on && <div className="row between" style={{ padding: '8px 0' }}>
<span>Reminder time</span>
<input type="time" className="input" style={{ width: 120 }} value={S.reminder?.time || DEF.reminder.time}
onChange={e => update(s => { s.reminder = { ...(s.reminder || DEF.reminder), time: e.target.value } })} />
</div>}
<div className="small dim" style={{ margin: '6px 0' }}>Only sent on days you have a routine planned and haven't logged a workout yet.</div>
<button className="btn sm" onClick={test}>Send test notification</button>
</>}
</>}
</div>
}
function RegisterInline({ close, setUser, pushState, pullState, toast }) {
const nameRef = useRef(null)
const go = async () => {