import { For, Show, Suspense, createEffect, createMemo, createSignal } from "solid-js"; import { useNavigate } from "@tanstack/solid-router"; import { patchMessageById } from "@/api/messages"; import { Button } from "@/components/ui/button"; import { ComingSoonPanel } from "@/components/ui/coming-soon"; import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover"; import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"; import { IconBell, IconCalendar, IconChevronLeft, IconExam, IconExternalLink, IconHomework, IconMessage, IconTrash, IconX, } from "@/components/ui/icons"; import { cn } from "@/lib/cn"; import { personLabel } from "@/lib/person"; import { dismissAllNotificationIds, dismissNotificationId, getDismissedNotificationIds, getReadNotificationIds, markNotificationRead, type NotificationItem, type NotificationType, } from "@/lib/notifications"; import { usePreferences } from "@/stores/preferences-context"; import { useShellFeed } from "@/stores/shell-feed-context"; export function NotificationCenter() { const { t, locale } = usePreferences(); const dateLocale = () => (locale() === "tr" ? "tr-TR" : "en-US"); const navigate = useNavigate(); const feed = useShellFeed(); const [open, setOpen] = createSignal(false); const [dismissedIds, setDismissedIds] = createSignal>(getDismissedNotificationIds()); const [readIds, setReadIds] = createSignal>(getReadNotificationIds()); const [previewNotification, setPreviewNotification] = createSignal(null); // Shell feed data comes from the shared poller (ShellFeedProvider): one fetch // per source for the whole shell instead of a duplicate set here. Every read // below is `feed.x()` which returns `resource.latest` — non-suspending on the // 60s refetch, so the unread badge (outside the popover's ) never // blanks the page beside (AGENTS.md #6). const refetchMessages = feed.refetchMessages; const refreshAll = feed.refreshAll; const nowMs = feed.nowMs; createEffect(() => { if (open()) refreshAll(); }); // An item is still notifiable until it has ended (ends_at, else starts_at). const notEnded = (starts: number, ends?: number | null) => (ends ?? starts) >= nowMs(); // Combine notification items const allNotifications = createMemo(() => { const list: NotificationItem[] = []; // 1. Unread messages — the dedicated `read=false` page from the shell feed. // Never filter the shared inbox page instead: it is capped and ordered by // id DESC, so an older unread message is simply not in it. const msgs = feed.unreadMessages().items; for (const m of msgs) { const body = m.body.replace(/<[^>]*>?/gm, "").trim(); list.push({ id: `msg_${m.id}`, type: "message", title: personLabel(m.sender), description: m.subject || body, preview: m.subject ? `${m.subject}\n${body}` : body, targetUrl: "/messages", timestamp: m.sent_at, }); } // 2. Events starting today or upcoming const evts = feed.events().items; for (const e of evts) { if (!e.starts_at) continue; const t = new Date(e.starts_at).getTime(); if (notEnded(t, e.ends_at ? new Date(e.ends_at).getTime() : null)) { list.push({ id: `evt_${e.id}`, type: "event", title: e.title, description: e.starts_at ? new Date(e.starts_at).toLocaleString(dateLocale(), { month: "short", day: "numeric", hour: "2-digit", minute: "2-digit", }) : "", targetUrl: `/events/${e.id}`, timestamp: t, }); } } // 3. Exams starting today or upcoming const exms = feed.exams().items; for (const ex of exms) { if (!ex.starts_at || ex.draft) continue; const t = new Date(ex.starts_at).getTime(); if (notEnded(t, ex.ends_at ? new Date(ex.ends_at).getTime() : null)) { list.push({ id: `ex_${ex.id}`, type: "exam", title: ex.title, description: ex.starts_at ? new Date(ex.starts_at).toLocaleString(dateLocale(), { month: "short", day: "numeric", hour: "2-digit", minute: "2-digit", }) : "", targetUrl: `/exams/${ex.id}`, timestamp: t, }); } } // 4. Homework due upcoming const hws = feed.homework().items; for (const hw of hws) { if (!hw.due_at) continue; if (hw.due_at >= nowMs()) { list.push({ id: `hw_${hw.id}`, type: "homework", title: hw.title, description: hw.due_at ? `${t("homework.dueAt")}: ${new Date(hw.due_at).toLocaleDateString(dateLocale(), { month: "short", day: "numeric", })}` : "", targetUrl: `/homework/${hw.id}`, timestamp: hw.due_at, }); } } // Sort chronologically (newest/most relevant first) return list.sort((a, b) => b.timestamp - a.timestamp); }); // Filter out dismissed notifications const activeNotifications = createMemo(() => { const dismissed = dismissedIds(); return allNotifications().filter((item) => !dismissed.has(item.id)); }); const isUnread = (item: NotificationItem) => !readIds().has(item.id); const unreadNotifications = createMemo(() => activeNotifications().filter(isUnread)); const notificationGroupOrder: NotificationType[] = ["message", "event", "exam", "homework"]; const notificationGroupLabel = (type: NotificationType) => { if (type === "message") return t("nav.messages"); if (type === "event") return t("events.title"); if (type === "exam") return t("exams.title"); return t("homework.title"); }; const notificationGroupTone = (type: NotificationType) => { if (type === "message") return "border-primary/20 bg-primary/[0.035]"; if (type === "event") return "border-violet-500/20 bg-violet-500/[0.035]"; if (type === "exam") return "border-amber-500/25 bg-amber-500/[0.045]"; return "border-emerald-500/20 bg-emerald-500/[0.035]"; }; const notificationGroupIconTone = (type: NotificationType) => { if (type === "message") return "bg-primary/10 text-primary-text"; if (type === "event") return "bg-violet-500/10 text-violet-700 dark:text-violet-300"; if (type === "exam") return "bg-amber-500/10 text-amber-700 dark:text-amber-300"; return "bg-emerald-500/10 text-emerald-700 dark:text-emerald-300"; }; const notificationGroups = createMemo(() => notificationGroupOrder .map((type) => ({ type, items: activeNotifications().filter((item) => item.type === type), })) .filter((group) => group.items.length > 0) ); // The list only holds the newest 10 unread messages; `total` is the real // server-side unread count, so the rest still counts towards the badge. // Those extra rows have no id here, so they cannot be dismissed one by one: // "dismiss all" snapshots the unread total instead. Everything at or below the // snapshot counts as dismissed; anything above it arrived afterwards and still // raises the badge (minus the new rows already listed, which the active list // counts). Without the snapshot, 11 unread → dismiss all → badge stuck at 1 // over an empty popover. // ponytail: the snapshot is in-memory while dismissed ids are persisted, so a // reload re-shows unlisted unread — upgrade path is storing it next to the ids // in `lib/notifications`. const [dismissedUnreadTotal, setDismissedUnreadTotal] = createSignal(0); const activeMessageCount = () => activeNotifications().filter((item) => item.type === "message").length; const unlistedUnread = () => { const page = feed.unreadMessages(); const beyondPage = page.total - page.items.length; const sinceDismissAll = page.total - dismissedUnreadTotal() - activeMessageCount(); return Math.max(0, Math.min(beyondPage, sinceDismissAll)); }; const unreadCount = () => unreadNotifications().length + unlistedUnread(); const handleDismissSingle = (evt: MouseEvent, id: string) => { evt.stopPropagation(); const updated = dismissNotificationId(id); setDismissedIds(new Set(updated)); }; const handleDismissAll = () => { const ids = activeNotifications().map((item) => item.id); const updated = dismissAllNotificationIds(ids); setDismissedIds(new Set(updated)); setDismissedUnreadTotal(feed.unreadMessages().total); }; const handleSelectNotification = async (item: NotificationItem) => { if (isUnread(item)) { setReadIds(new Set(markNotificationRead(item.id))); } // Message notifications also need to be marked read in the backend. if (item.id.startsWith("msg_")) { const realId = item.id.replace("msg_", ""); try { await patchMessageById(realId, { read: true }); void refetchMessages(); } catch { // ignore } } setPreviewNotification(item); }; const handleNavigateToNotification = () => { const item = previewNotification(); if (!item) return; setPreviewNotification(null); setOpen(false); void navigate({ to: item.targetUrl }); }; return ( { setOpen(nextOpen); if (!nextOpen) setPreviewNotification(null); }} placement="bottom-end" gutter={8} > 0}> {unreadCount() > 9 ? "9+" : unreadCount()}

{t("notifications.title")}

0}> {unreadCount()}
0}>
{t("notifications.tabAll")} {t("notifications.tabSystem")} {t("common.loading")} } > 0} fallback={

{t("notifications.empty")}

} >
{(group) => (
{notificationGroupLabel(group.type)}
{group.items.length}
{(item) => (
handleSelectNotification(item)} class="group relative flex cursor-pointer select-none items-start gap-3 rounded-lg p-2 text-xs transition-colors hover:bg-background/70" >
{item.title}

{item.description}

)}
)}
} > {(item) => (

{item().title}

{item().preview ?? item().description}

)}
); }