Rest-over alert: follow the Push switch — it fired with notifications off, asked for the permission by itself and repeated its title in the body (#239)

This commit is contained in:
Duarte Santos committed 2026-09-17 11:31:07 +02:00
1 parent 5007b05504
commit a41b0ca60f
2 files changed
+80 -22

No files matched your search

+14 -22
View File
@@ -14,7 +14,6 @@ const pushRestTimer = sec => { if (useStore.getState().user) api('/api/push/rest
const cancelPushRestTimer = () => { if (useStore.getState().user) api('/api/push/rest-timer/cancel', { method: 'POST', body: JSON.stringify({ deviceId: deviceId() }) }).catch(() => {}) }
const notificationsSupported = () => typeof window !== 'undefined' && 'Notification' in window
let requestRestNotificationPermissionP = null
// Set the moment the tab goes hidden, never cleared here — timerTick/workTick read and
// clear it themselves once they're running visible again. Lets a completion tick tell
@@ -26,34 +25,28 @@ if (typeof document !== 'undefined') {
document.addEventListener('visibilitychange', () => { if (document.hidden) pageHiddenAt = Date.now() })
}
const requestRestNotificationPermission = async () => {
if (!notificationsSupported()) return false
if (Notification.permission === 'granted') return true
if (Notification.permission === 'denied') return false
if (!requestRestNotificationPermissionP) {
requestRestNotificationPermissionP = Notification.requestPermission()
.then(perm => perm === 'granted')
.catch(() => false)
.finally(() => {
requestRestNotificationPermissionP = null
})
}
return requestRestNotificationPermissionP
// The Push switch in Settings is the one place notifications are turned on, and "on" means this
// browser holds a push subscription. This local alert used to ignore it: every rest asked for the
// permission by itself, and once granted — a page cannot hand a permission back — it fired with the
// switch off (issue #239). Off is off now; the permission is only ever asked for by the switch.
const restAlertsOn = async reg => {
if (Notification.permission !== 'granted') return false
try { return !!(await reg?.pushManager?.getSubscription?.()) } catch { return false }
}
const maybeRestNotification = async () => {
if (!notificationsSupported()) return
if (!document.hidden && document.visibilityState !== 'hidden') return
if (Notification.permission !== 'granted' && !(await requestRestNotificationPermission())) return
try {
const reg = await navigator.serviceWorker?.getRegistration?.()
if (!(await restAlertsOn(reg))) return
// Same tag as the server's push (api/push-messages.js): whichever lands second replaces the
// first instead of stacking a second banner. No body — it only repeated the title.
// Android Chrome forbids the Notification constructor (Illegal constructor) - the
// service-worker registration path is the one that actually pops there.
const reg = await navigator.serviceWorker?.getRegistration?.()
if (reg?.showNotification) {
reg.showNotification(t('Rest over — next set!'), { body: t('Rest over — next set!') })
return
}
new Notification(t('Rest over — next set!'), { body: t('Rest over — next set!') })
const opts = { tag: 'rest-timer', icon: 'icon-512.png' }
if (reg?.showNotification) { reg.showNotification(t('Rest over — next set!'), opts); return }
new Notification(t('Rest over — next set!'), opts)
} catch {
// Intentionally ignore: notification APIs vary by browser and policy in edge cases.
}
@@ -101,7 +94,6 @@ export const useUI = create((set, get) => ({
if (!(sec > 0)) return
const endsAt = Date.now() + sec * 1000
set({ timer: { left: sec, total: sec, endsAt, forIdx } })
requestRestNotificationPermission()
pushRestTimer(sec)
timerTick = () => {
const tm = get().timer
@@ -0,0 +1,66 @@
// @vitest-environment happy-dom
// Issue #239: the local "rest over" alert ignored the Push switch in Settings. Every rest asked
// for the notification permission on its own, and once granted it fired with the switch off —
// a page cannot give a permission back. "On" is this browser holding a push subscription.
import { describe, expect, it, beforeEach, afterEach, vi } from 'vitest'
import { useUI } from './useUI.js'
import { useStore } from './useStore.js'
let showNotification, requestPermission, subscription, originalSettings
const hide = hidden => {
Object.defineProperty(document, 'hidden', { configurable: true, get: () => hidden })
Object.defineProperty(document, 'visibilityState', { configurable: true, get: () => hidden ? 'hidden' : 'visible' })
document.dispatchEvent(new Event('visibilitychange'))
}
const runOut = async () => {
useUI.getState().startRest(2)
hide(true)
await vi.advanceTimersByTimeAsync(3000)
}
beforeEach(() => {
vi.useFakeTimers()
originalSettings = useStore.getState().S
useStore.setState({ S: { ...originalSettings, sound: false }, user: null })
useUI.setState({ timer: null })
showNotification = vi.fn()
requestPermission = vi.fn(async () => 'granted')
subscription = null
globalThis.Notification = Object.assign(vi.fn(), { permission: 'granted', requestPermission })
window.Notification = globalThis.Notification
Object.defineProperty(navigator, 'serviceWorker', {
configurable: true,
value: { getRegistration: async () => ({ showNotification, pushManager: { getSubscription: async () => subscription } }) },
})
})
afterEach(() => {
useUI.getState().stopRest()
hide(false)
useStore.setState({ S: originalSettings })
delete globalThis.Notification
vi.useRealTimers()
})
describe('the local rest-over alert follows the Push switch', () => {
it('stays silent with the switch off, even though the permission is granted', async () => {
await runOut()
expect(showNotification).not.toHaveBeenCalled()
})
it('fires once with the switch on, tagged like the server push, without repeating the title', async () => {
subscription = { endpoint: 'https://push.example/x' }
await runOut()
expect(showNotification).toHaveBeenCalledTimes(1)
const [title, opts] = showNotification.mock.calls[0]
expect(title).toBe('Rest over — next set!')
expect(opts.tag).toBe('rest-timer')
expect(opts.body).toBeUndefined()
})
it('never asks for the permission by itself — only the switch does', async () => {
globalThis.Notification.permission = 'default'
await runOut()
expect(requestPermission).not.toHaveBeenCalled()
expect(showNotification).not.toHaveBeenCalled()
})
})