Files
tern-web/src/lib/notify.ts
T
Mateusz PstruchaandClaude Opus 5.5 fa78fe7ccf Add live updates, new-mail alerts and notify rule actions
The shell now follows the server's event stream over a WebSocket,
falling back to polling the same log (every 30 s) while it reconnects
with backoff, and reloading everything when the server says the cursor
can't be replayed. Lists, the outbox, sidebar and rules refresh on
their own events; the open conversation only reloads when its message
count changes, so flag and tag changes don't collapse it.

Mail the server marks as notifying shows an in-page notice while the
tab is in view, and otherwise counts in the tab title and — if the
reader opted in — raises an OS notification. The rule editor gains
Don't notify and Notify anyway.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-23 18:55:43 +02:00

55 lines
1.6 KiB
TypeScript

// OS-level alerts while the tab is open (webapp-client-spec.md §3): the
// Notification API works without a service worker, it just can't fire once
// the tab is closed. Off until the reader turns it on — permission is asked
// for from that click, never on page load.
const PREF_KEY = 'tern-desktop-alerts';
export type AlertState = 'unsupported' | 'blocked' | 'off' | 'on';
function stored(): boolean {
try {
return localStorage.getItem(PREF_KEY) === 'on';
} catch {
return false;
}
}
function store(on: boolean) {
try {
if (on) localStorage.setItem(PREF_KEY, 'on');
else localStorage.removeItem(PREF_KEY);
} catch {
// Private mode etc.: the setting just won't survive a reload.
}
}
export function alertState(): AlertState {
if (!('Notification' in window)) return 'unsupported';
if (Notification.permission === 'denied') return 'blocked';
return Notification.permission === 'granted' && stored() ? 'on' : 'off';
}
export async function enableAlerts(): Promise<AlertState> {
if (!('Notification' in window)) return 'unsupported';
const permission = await Notification.requestPermission();
store(permission === 'granted');
return alertState();
}
export function disableAlerts(): AlertState {
store(false);
return alertState();
}
/** Shows an alert if they're on. `tag` collapses repeats for one thread. */
export function showAlert(title: string, body: string, tag: string, onClick: () => void): void {
if (alertState() !== 'on') return;
const n = new Notification(title, { body, tag });
n.onclick = () => {
window.focus();
onClick();
n.close();
};
}