"use client"; import { useEffect, useRef } from "react"; import { useLive } from "@/lib/live"; const PREFIX = /^\(\d+\) /; /** Short two-tone chime (WebAudio, no asset). Browsers allow it after any click on the page. */ function chime() { try { const ctx = new AudioContext(); [880, 660].forEach((f, i) => { const o = ctx.createOscillator(); const g = ctx.createGain(); o.frequency.value = f; const t = ctx.currentTime + i * 0.16; g.gain.setValueAtTime(0.0001, t); g.gain.exponentialRampToValueAtTime(0.2, t + 0.02); g.gain.exponentialRampToValueAtTime(0.0001, t + 0.15); o.connect(g).connect(ctx.destination); o.start(t); o.stop(t + 0.16); }); setTimeout(() => ctx.close(), 600); } catch {} } /** * «(N) …» in the tab title and the app badge (PEP-55): what waits for the user. The count comes * from the live channel (`attention`, PEP-225) the moment it changes; a growing count plays a * chime if sound is on in the settings. */ export function AttentionBadge({ count: initial, sound: initialSound }: { count: number; sound: boolean }) { const count = useRef(initial); const sound = useRef(initialSound); const apply = () => { const base = document.title.replace(PREFIX, ""); const want = count.current > 0 ? `(${count.current}) ${base}` : base; if (document.title !== want) document.title = want; const nav = navigator as Navigator & { setAppBadge?: (n?: number) => Promise; clearAppBadge?: () => Promise }; if (count.current > 0) nav.setAppBadge?.(count.current).catch(() => {}); else nav.clearAppBadge?.().catch(() => {}); }; useEffect(() => { apply(); // Next sets the title on navigation: put the counter back. const titleObserver = new MutationObserver(apply); titleObserver.observe(document.head, { subtree: true, childList: true, characterData: true }); return () => titleObserver.disconnect(); }, []); useLive("attention", (e) => { if (e.type !== "data") return; const d = e.data as { count: number; sound: boolean }; sound.current = d.sound; if (d.count > count.current && sound.current) chime(); count.current = d.count; apply(); }); // A server re-render brings a fresh count too. useEffect(() => { if (initial > count.current && sound.current) chime(); count.current = initial; apply(); }, [initial]); return null; }