SPB Git

Repository Public

notifications.setup.tsx 5.0 KB 109 lines tsx

1// SP Mail Next — notifications du navigateur (onglet caché, courrier arrivé) : veille des non lus des boîtes de réception, rafales regroupées, aperçu selon la préférence ; commandes « Réglages : Notifications / Règles ».2import { t } from "../../i18n"3import { hasFeature } from "../../next/api"4import type { Setup } from "../../next/features"5import { WEB_NOTIFY, currentPermission, decide, mergeArrivals, needsNewest, notificationText, syncWebNotify, type Arrival, type Counts, type Newest } from "../../next/notify"6import { currentPreview, loadPushPrefs, resetPush } from "../../next/push"7import { S, folderByRole, routeHref, type AppState } from "../../state/app"8import { clientFor, hasClient } from "../../state/mail"9import { navigate } from "../../state/session"10import { registerCommand } from "../commands"1112const COALESCE_MS = 15001314/** Non lus des boîtes de réception dont le compte est confirmé par le serveur (ni en chargement initial, ni servi par le cache). */15function inboxCounts(s: AppState): Counts {16  const out: Counts = {}17  for (const a of Object.values(s.accounts)) {18    if (a.status !== "ready" || a.stale) continue19    const inbox = folderByRole(a, "inbox")20    if (inbox) out[a.id] = inbox.unreadEmails21  }22  return out23}2425/** Expéditeur et objet du message non lu le plus récent de la boîte de réception (seulement si l'aperçu le demande). */26async function newestUnread(mailboxId: string): Promise<Newest | null> {27  const inbox = folderByRole(S.get().accounts[mailboxId], "inbox")28  if (!inbox || !hasClient(mailboxId)) return null29  try {30    const b = clientFor(mailboxId).batch()31    const q = b.add("Email/query", { filter: { inMailbox: inbox.id, notKeyword: "$seen" }, sort: [{ property: "receivedAt", isAscending: false }], limit: 1 })32    const g = b.add("Email/get", { "#ids": q.ref("/ids"), properties: ["from", "subject"] })33    await b.send()34    const e = g.result.list[0]35    if (!e) return null36    return { fromName: e.from?.[0]?.name ?? null, fromEmail: e.from?.[0]?.email ?? "", subject: e.subject ?? "" }37  } catch {38    return null39  }40}4142function startWebNotifications(): () => void {43  let baseline: Counts = {}44  let pending: Arrival[] = []45  let timer: ReturnType<typeof setTimeout> | undefined46  let stopped = false47  syncWebNotify()4849  const show = async (a: Arrival) => {50    const privacy = currentPreview()51    const newest = needsNewest(privacy) ? await newestUnread(a.mailboxId) : null52    if (stopped || currentPermission() !== "granted" || !WEB_NOTIFY.get().enabled) return53    const { title, body } = notificationText({ privacy, added: a.added, newest })54    try {55      // une notification par boîte : la suivante remplace la précédente au lieu de s'empiler56      const n = new Notification(title, { body, tag: `spmail-${a.mailboxId}` })57      n.onclick = () => {58        window.focus()59        const mbIndex = Math.max(0, S.get().me?.mailboxes.findIndex((m) => m.id === a.mailboxId) ?? 0)60        navigate(routeHref({ name: "mail", mbIndex, view: "inbox", threadId: null, q: "" }))61        n.close()62      }63    } catch {64      /* certains navigateurs refusent le constructeur hors service worker : rien à afficher */65    }66  }67  const flush = () => {68    timer = undefined69    const list = pending70    pending = []71    for (const a of list) void show(a)72  }73  const check = () => {74    const s = S.get()75    if (s.phase !== "ready") return76    const w = WEB_NOTIFY.get()77    const r = decide({ baseline, counts: inboxCounts(s), hidden: document.hidden, enabled: w.enabled, permission: w.enabled ? currentPermission() : w.permission })78    baseline = r.baseline79    if (!r.arrivals.length) return80    pending = mergeArrivals(pending, r.arrivals)81    if (timer === undefined) timer = setTimeout(flush, COALESCE_MS)82  }83  const off = S.subscribe(check)84  check()85  // retour sur l'onglet : le niveau d'aperçu a pu être changé ailleurs (autre onglet, app native)86  const onFocus = () => void loadPushPrefs().catch(() => {})87  window.addEventListener("focus", onFocus)88  return () => {89    stopped = true90    off()91    window.removeEventListener("focus", onFocus)92    clearTimeout(timer)93    pending = []94  }95}9697export const setupNotifications: Setup = () => {98  // l'aperçu choisi pour les appareils vaut aussi pour ce navigateur ; sans la fonction `push`, « expéditeur » par défaut99  void loadPushPrefs().catch(() => {})100  const settings = (tab: string, label: () => string, icon: "bell" | "rule", keywords: string[]) =>101    registerCommand(() => ({ id: `settings.${tab}`, section: "settings", title: `${t("nav.settings")} : ${label()}`, icon, keywords, run: () => navigate(`/settings/${tab}`) }))102  const off = [startWebNotifications(), settings("notifications", () => t("nx.settings.tab.notifications"), "bell", ["push", "alertes", "alerts", "heures calmes", "quiet hours"])]103  if (hasFeature("rules")) off.push(settings("rules", () => t("nx.settings.tab.rules"), "rule", ["automatisation", "automation", "règles", "rules"]))104  return () => {105    off.forEach((f) => f())106    resetPush()107  }108}109
Files main
Menu

Theme