peppa/apps/web/components/AttentionBadge.tsx
2026-11-14 05:10:20 +05:00

79 lines
2.8 KiB
TypeScript

"use client";
import { useEffect, useRef } from "react";
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. Polls
* /api/attention; a growing count plays a chime if sound is on in the settings.
*/
export function AttentionBadge({ count: initial, sound: initialSound, everyMs = 20_000 }: { count: number; sound: boolean; everyMs?: number }) {
const count = useRef(initial);
const sound = useRef(initialSound);
useEffect(() => {
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<void>; clearAppBadge?: () => Promise<void> };
if (count.current > 0) nav.setAppBadge?.(count.current).catch(() => {});
else nav.clearAppBadge?.().catch(() => {});
};
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 });
const poll = async () => {
if (document.visibilityState !== "visible") return;
try {
const r = await fetch("/api/attention", { cache: "no-store" });
if (!r.ok) return;
const j = (await r.json()) as { count: number; sound: boolean };
sound.current = j.sound;
if (j.count > count.current && sound.current) chime();
count.current = j.count;
apply();
} catch {}
};
const id = setInterval(poll, everyMs);
document.addEventListener("visibilitychange", poll);
return () => {
clearInterval(id);
titleObserver.disconnect();
document.removeEventListener("visibilitychange", poll);
};
}, [everyMs]);
// A server re-render (router.refresh) brings a fresh count too.
useEffect(() => {
if (initial > count.current && sound.current) chime();
count.current = initial;
document.title = initial > 0 ? `(${initial}) ${document.title.replace(PREFIX, "")}` : document.title.replace(PREFIX, "");
}, [initial]);
return null;
}