/** * 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 { 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)) }