Files
byre/web/src/notifications.ts
T

52 lines
1.5 KiB
TypeScript
Raw Normal View History

import type { ByreEvent, InboxItem, NotificationPrefs } from "./api.js";
import { findTask, focusTask, state } from "./state.js";
function wants(p: NotificationPrefs, item: InboxItem): boolean {
switch (item.kind) {
case "question":
return p.questions;
case "session_error":
return p.errors;
case "rate_limited":
return p.rate_limits;
}
}
function itemText(item: InboxItem): string {
const p = item.payload;
return item.kind === "question" ? String(p["question"] ?? "")
: item.kind === "session_error" ? `Error: ${String(p["error"] ?? "")}`
: "Rate limited";
}
function show(taskId: string, tag: string, text: string): void {
const line = text.trim().split("\n")[0] ?? "";
const title = findTask(taskId)?.title;
const n = new Notification(title ? `byre · ${title}` : "byre", { body: line.length > 200 ? `${line.slice(0, 199)}…` : line, tag });
n.onclick = () => {
window.focus();
if (taskId) {
focusTask(taskId);
}
n.close();
};
}
function allowed(): boolean {
return "Notification" in window && Notification.permission === "granted" && !!state.me;
}
export function notifyInbox(item: InboxItem): void {
if (!allowed() || !wants(state.me!.notification_prefs, item)) {
return;
}
show(item.task_id, item.id, itemText(item));
}
export function notifyTurn(ev: ByreEvent): void {
if (!allowed() || !state.me!.notification_prefs.reports || ev.payload["summary"] !== true || !ev.task_id) {
return;
}
show(ev.task_id, `turn-${ev.seq}`, String(ev.payload["result"] ?? ""));
}