feat(web): show pending items on the installed app icon

Keep the Badging API count equal to the primary list's pending items, update it from optimistic changes and the list's SSE stream (shared across pages), and re-sync when the app returns to the foreground.

On iOS the badge needs notification permission, so Settings offers to enable it; Android does not support numeric web app badges.
This commit is contained in:
Jose Selesan
2026-10-29 14:20:21 -03:00
parent 7ed4d27844
commit aa170de8d1
14 changed files with 432 additions and 45 deletions

View File

@@ -0,0 +1,39 @@
/**
* Name of the window event used to ask `useAppBadge` for a fresh sync (for
* example right after the user grants notification permission, which the
* effect cannot observe on its own).
*/
export const APP_BADGE_REFRESH_EVENT = 'superlist:app-badge-refresh'
/** Whether this browser can show a badge on the installed app's icon. */
export function supportsAppBadge(): boolean {
return typeof navigator !== 'undefined' && 'setAppBadge' in navigator
}
/**
* Writes `count` on the icon of the installed app (Badging API). Zero removes
* the badge. Browsers without support, calls made from a tab instead of the
* installed app, and platforms where the permission is missing (iOS needs
* notifications allowed) reject the promise; the badge simply stays as it was.
*/
export function setAppBadge(count: number): Promise<void> {
if (!supportsAppBadge()) return Promise.resolve()
const value = Math.max(0, Math.trunc(count))
const request =
value > 0
? navigator.setAppBadge(value)
: navigator.clearAppBadge
? navigator.clearAppBadge()
: Promise.resolve()
return request.catch(() => {
// Not installed, permission denied or document not fully active: a badge is
// a hint, never something worth breaking a render or logging an error for.
})
}
/** Asks the badge sync to run again, even when no data changed. */
export function refreshAppBadge() {
if (typeof window !== 'undefined') window.dispatchEvent(new Event(APP_BADGE_REFRESH_EVENT))
}