forge
Explore
Log in

Don't you dare go Hollow

hezarfen_frontend

Clone
★ 0

0 watching0 forksTypeScript5.5 MiBdcf123aBurak Boduroğlu2 months ago674 commits

notification-center.tsx468 lines, 19.5 KiBHistoryRawDownload
1import { For, Show, Suspense, createEffect, createMemo, createSignal } from "solid-js";
2import { useNavigate } from "@tanstack/solid-router";
3import { patchMessageById } from "@/api/messages";
4import { Button } from "@/components/ui/button";
5import { ComingSoonPanel } from "@/components/ui/coming-soon";
6import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
7import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
8import {
9 IconBell,
10 IconCalendar,
11 IconChevronLeft,
12 IconExam,
13 IconExternalLink,
14 IconHomework,
15 IconMessage,
16 IconTrash,
17 IconX,
18} from "@/components/ui/icons";
19import { cn } from "@/lib/cn";
20import { personLabel } from "@/lib/person";
21import {
22 dismissAllNotificationIds,
23 dismissNotificationId,
24 getDismissedNotificationIds,
25 getReadNotificationIds,
26 markNotificationRead,
27 type NotificationItem,
28 type NotificationType,
29} from "@/lib/notifications";
30import { usePreferences } from "@/stores/preferences-context";
31import { useShellFeed } from "@/stores/shell-feed-context";
32
33export function NotificationCenter() {
34 const { t, locale } = usePreferences();
35 const dateLocale = () => (locale() === "tr" ? "tr-TR" : "en-US");
36 const navigate = useNavigate();
37 const feed = useShellFeed();
38 const [open, setOpen] = createSignal(false);
39 const [dismissedIds, setDismissedIds] = createSignal<Set<string>>(getDismissedNotificationIds());
40 const [readIds, setReadIds] = createSignal<Set<string>>(getReadNotificationIds());
41 const [previewNotification, setPreviewNotification] = createSignal<NotificationItem | null>(null);
42
43 // Shell feed data comes from the shared poller (ShellFeedProvider): one fetch
44 // per source for the whole shell instead of a duplicate set here. Every read
45 // below is `feed.x()` which returns `resource.latest` — non-suspending on the
46 // 60s refetch, so the unread badge (outside the popover's <Suspense>) never
47 // blanks the page beside <Outlet> (AGENTS.md #6).
48 const refetchMessages = feed.refetchMessages;
49 const refreshAll = feed.refreshAll;
50 const nowMs = feed.nowMs;
51
52 createEffect(() => {
53 if (open()) refreshAll();
54 });
55
56 // An item is still notifiable until it has ended (ends_at, else starts_at).
57 const notEnded = (starts: number, ends?: number | null) => (ends ?? starts) >= nowMs();
58
59 // Combine notification items
60 const allNotifications = createMemo<NotificationItem[]>(() => {
61 const list: NotificationItem[] = [];
62
63 // 1. Unread messages — the dedicated `read=false` page from the shell feed.
64 // Never filter the shared inbox page instead: it is capped and ordered by
65 // id DESC, so an older unread message is simply not in it.
66 const msgs = feed.unreadMessages().items;
67 for (const m of msgs) {
68 const body = m.body.replace(/<[^>]*>?/gm, "").trim();
69 list.push({
70 id: `msg_${m.id}`,
71 type: "message",
72 title: personLabel(m.sender),
73 description: m.subject || body,
74 preview: m.subject ? `${m.subject}\n${body}` : body,
75 targetUrl: "/messages",
76 timestamp: m.sent_at,
77 });
78 }
79
80 // 2. Events starting today or upcoming
81 const evts = feed.events().items;
82 for (const e of evts) {
83 if (!e.starts_at) continue;
84 const t = new Date(e.starts_at).getTime();
85 if (notEnded(t, e.ends_at ? new Date(e.ends_at).getTime() : null)) {
86 list.push({
87 id: `evt_${e.id}`,
88 type: "event",
89 title: e.title,
90 description: e.starts_at
91 ? new Date(e.starts_at).toLocaleString(dateLocale(), {
92 month: "short",
93 day: "numeric",
94 hour: "2-digit",
95 minute: "2-digit",
96 })
97 : "",
98 targetUrl: `/events/${e.id}`,
99 timestamp: t,
100 });
101 }
102 }
103
104 // 3. Exams starting today or upcoming
105 const exms = feed.exams().items;
106 for (const ex of exms) {
107 if (!ex.starts_at || ex.draft) continue;
108 const t = new Date(ex.starts_at).getTime();
109 if (notEnded(t, ex.ends_at ? new Date(ex.ends_at).getTime() : null)) {
110 list.push({
111 id: `ex_${ex.id}`,
112 type: "exam",
113 title: ex.title,
114 description: ex.starts_at
115 ? new Date(ex.starts_at).toLocaleString(dateLocale(), {
116 month: "short",
117 day: "numeric",
118 hour: "2-digit",
119 minute: "2-digit",
120 })
121 : "",
122 targetUrl: `/exams/${ex.id}`,
123 timestamp: t,
124 });
125 }
126 }
127
128 // 4. Homework due upcoming
129 const hws = feed.homework().items;
130 for (const hw of hws) {
131 if (!hw.due_at) continue;
132 if (hw.due_at >= nowMs()) {
133 list.push({
134 id: `hw_${hw.id}`,
135 type: "homework",
136 title: hw.title,
137 description: hw.due_at
138 ? `${t("homework.dueAt")}: ${new Date(hw.due_at).toLocaleDateString(dateLocale(), {
139 month: "short",
140 day: "numeric",
141 })}`
142 : "",
143 targetUrl: `/homework/${hw.id}`,
144 timestamp: hw.due_at,
145 });
146 }
147 }
148
149 // Sort chronologically (newest/most relevant first)
150 return list.sort((a, b) => b.timestamp - a.timestamp);
151 });
152
153 // Filter out dismissed notifications
154 const activeNotifications = createMemo(() => {
155 const dismissed = dismissedIds();
156 return allNotifications().filter((item) => !dismissed.has(item.id));
157 });
158
159 const isUnread = (item: NotificationItem) => !readIds().has(item.id);
160 const unreadNotifications = createMemo(() => activeNotifications().filter(isUnread));
161
162 const notificationGroupOrder: NotificationType[] = ["message", "event", "exam", "homework"];
163 const notificationGroupLabel = (type: NotificationType) => {
164 if (type === "message") return t("nav.messages");
165 if (type === "event") return t("events.title");
166 if (type === "exam") return t("exams.title");
167 return t("homework.title");
168 };
169 const notificationGroupTone = (type: NotificationType) => {
170 if (type === "message") return "border-primary/20 bg-primary/[0.035]";
171 if (type === "event") return "border-violet-500/20 bg-violet-500/[0.035]";
172 if (type === "exam") return "border-amber-500/25 bg-amber-500/[0.045]";
173 return "border-emerald-500/20 bg-emerald-500/[0.035]";
174 };
175 const notificationGroupIconTone = (type: NotificationType) => {
176 if (type === "message") return "bg-primary/10 text-primary-text";
177 if (type === "event") return "bg-violet-500/10 text-violet-700 dark:text-violet-300";
178 if (type === "exam") return "bg-amber-500/10 text-amber-700 dark:text-amber-300";
179 return "bg-emerald-500/10 text-emerald-700 dark:text-emerald-300";
180 };
181 const notificationGroups = createMemo(() =>
182 notificationGroupOrder
183 .map((type) => ({
184 type,
185 items: activeNotifications().filter((item) => item.type === type),
186 }))
187 .filter((group) => group.items.length > 0)
188 );
189
190 // The list only holds the newest 10 unread messages; `total` is the real
191 // server-side unread count, so the rest still counts towards the badge.
192 // Those extra rows have no id here, so they cannot be dismissed one by one:
193 // "dismiss all" snapshots the unread total instead. Everything at or below the
194 // snapshot counts as dismissed; anything above it arrived afterwards and still
195 // raises the badge (minus the new rows already listed, which the active list
196 // counts). Without the snapshot, 11 unread → dismiss all → badge stuck at 1
197 // over an empty popover.
198 // ponytail: the snapshot is in-memory while dismissed ids are persisted, so a
199 // reload re-shows unlisted unread — upgrade path is storing it next to the ids
200 // in `lib/notifications`.
201 const [dismissedUnreadTotal, setDismissedUnreadTotal] = createSignal(0);
202 const activeMessageCount = () => activeNotifications().filter((item) => item.type === "message").length;
203 const unlistedUnread = () => {
204 const page = feed.unreadMessages();
205 const beyondPage = page.total - page.items.length;
206 const sinceDismissAll = page.total - dismissedUnreadTotal() - activeMessageCount();
207 return Math.max(0, Math.min(beyondPage, sinceDismissAll));
208 };
209 const unreadCount = () => unreadNotifications().length + unlistedUnread();
210
211 const handleDismissSingle = (evt: MouseEvent, id: string) => {
212 evt.stopPropagation();
213 const updated = dismissNotificationId(id);
214 setDismissedIds(new Set(updated));
215 };
216
217 const handleDismissAll = () => {
218 const ids = activeNotifications().map((item) => item.id);
219 const updated = dismissAllNotificationIds(ids);
220 setDismissedIds(new Set(updated));
221 setDismissedUnreadTotal(feed.unreadMessages().total);
222 };
223
224 const handleSelectNotification = async (item: NotificationItem) => {
225 if (isUnread(item)) {
226 setReadIds(new Set(markNotificationRead(item.id)));
227 }
228
229 // Message notifications also need to be marked read in the backend.
230 if (item.id.startsWith("msg_")) {
231 const realId = item.id.replace("msg_", "");
232 try {
233 await patchMessageById(realId, { read: true });
234 void refetchMessages();
235 } catch {
236 // ignore
237 }
238 }
239 setPreviewNotification(item);
240 };
241
242 const handleNavigateToNotification = () => {
243 const item = previewNotification();
244 if (!item) return;
245 setPreviewNotification(null);
246 setOpen(false);
247 void navigate({ to: item.targetUrl });
248 };
249
250 return (
251 <Popover
252 open={open()}
253 onOpenChange={(nextOpen) => {
254 setOpen(nextOpen);
255 if (!nextOpen) setPreviewNotification(null);
256 }}
257 placement="bottom-end"
258 gutter={8}
259 >
260 <PopoverTrigger
261 class={cn(
262 "topbar-control relative flex h-9 w-9 shrink-0 cursor-pointer items-center justify-center rounded-xl outline-hidden focus-visible:ring-2 focus-visible:ring-ring",
263 open() && "bg-muted text-foreground"
264 )}
265 title={t("notifications.title")}
266 aria-label={t("notifications.title")}
267 >
268 <IconBell class="h-4 w-4" />
269 <Show when={unreadCount() > 0}>
270 <span class="absolute -top-1 -right-1 flex h-5 min-w-5 items-center justify-center rounded-full bg-destructive px-1 text-[11px] font-bold text-destructive-foreground ring-2 ring-background">
271 {unreadCount() > 9 ? "9+" : unreadCount()}
272 </span>
273 </Show>
274 </PopoverTrigger>
275
276 <PopoverContent class="w-80 sm:w-96 rounded-xl border border-border-line bg-surface-base p-0 shadow-2xl overflow-hidden">
277 <div class="flex items-center justify-between border-b border-border-hairline px-4 py-3">
278 <div class="flex items-center gap-2">
279 <h3 class="text-sm font-semibold text-text-strong">{t("notifications.title")}</h3>
280 <Show when={unreadCount() > 0}>
281 <span class="rounded-full bg-primary/15 px-2 py-0.5 font-mono text-[11px] font-bold text-primary-text">
282 {unreadCount()}
283 </span>
284 </Show>
285 </div>
286
287 <Show when={unreadCount() > 0}>
288 <Button
289 type="button"
290 variant="ghost"
291 size="sm"
292 class="h-7 rounded-lg px-2 text-[11px] font-semibold text-text-subtle hover:bg-destructive/10 hover:text-destructive-text"
293 onClick={handleDismissAll}
294 title={t("notifications.clearAll")}
295 >
296 <IconTrash class="mr-1 h-3 w-3" />
297 {t("notifications.clearAll")}
298 </Button>
299 </Show>
300 </div>
301
302 <Show
303 when={previewNotification()}
304 fallback={
305 <Tabs defaultValue="all" class="p-2">
306 <TabsList class="mx-auto mb-2 h-8 w-fit min-w-[180px] p-0.5">
307 <TabsTrigger value="all" class="h-7 flex-1 px-3 text-[11px]">{t("notifications.tabAll")}</TabsTrigger>
308 <TabsTrigger value="system" class="h-7 flex-1 px-3 text-[11px]">{t("notifications.tabSystem")}</TabsTrigger>
309 </TabsList>
310
311 <TabsContent value="all" class="mt-0 max-h-80 space-y-1 overflow-y-auto">
312 <Suspense
313 fallback={
314 <div class="p-8 text-center text-xs text-text-subtle">
315 {t("common.loading")}
316 </div>
317 }
318 >
319 <Show
320 when={notificationGroups().length > 0}
321 fallback={
322 <div class="space-y-2 p-8 text-center">
323 <div class="mx-auto flex h-10 w-10 items-center justify-center rounded-full bg-surface-tint text-text-subtle">
324 <IconBell class="h-5 w-5" />
325 </div>
326 <p class="text-xs font-medium text-text-subtle">
327 {t("notifications.empty")}
328 </p>
329 </div>
330 }
331 >
332 <div class="space-y-2">
333 <For each={notificationGroups()}>
334 {(group) => (
335 <section class={cn("overflow-hidden rounded-xl border", notificationGroupTone(group.type))}>
336 <div class="flex items-center justify-between gap-2 px-2.5 py-2">
337 <div class="flex min-w-0 items-center gap-2">
338 <div class={cn("flex h-6 w-6 shrink-0 items-center justify-center rounded-md", notificationGroupIconTone(group.type))}>
339 <Show when={group.type === "message"}>
340 <IconMessage class="h-3.5 w-3.5" />
341 </Show>
342 <Show when={group.type === "event"}>
343 <IconCalendar class="h-3.5 w-3.5" />
344 </Show>
345 <Show when={group.type === "exam"}>
346 <IconExam class="h-3.5 w-3.5" />
347 </Show>
348 <Show when={group.type === "homework"}>
349 <IconHomework class="h-3.5 w-3.5" />
350 </Show>
351 </div>
352 <span class="truncate text-[11px] font-bold uppercase tracking-[0.08em] text-text-subtle">
353 {notificationGroupLabel(group.type)}
354 </span>
355 </div>
356 <span class="shrink-0 rounded-full bg-background/70 px-1.5 py-0.5 font-mono text-[11px] font-bold text-text-subtle">
357 {group.items.length}
358 </span>
359 </div>
360
361 <div class="space-y-0.5 px-1 pb-1">
362 <For each={group.items}>
363 {(item) => (
364 <div
365 onClick={() => handleSelectNotification(item)}
366 class="group relative flex cursor-pointer select-none items-start gap-3 rounded-lg p-2 text-xs transition-colors hover:bg-background/70"
367 >
368 <div class="mt-0.5 flex h-8 w-8 shrink-0 items-center justify-center rounded-lg bg-background/75 text-text-subtle transition-colors group-hover:bg-primary group-hover:text-primary-foreground">
369 <Show when={item.type === "message"}>
370 <IconMessage class="h-4 w-4" />
371 </Show>
372 <Show when={item.type === "event"}>
373 <IconCalendar class="h-4 w-4" />
374 </Show>
375 <Show when={item.type === "exam"}>
376 <IconExam class="h-4 w-4" />
377 </Show>
378 <Show when={item.type === "homework"}>
379 <IconHomework class="h-4 w-4" />
380 </Show>
381 </div>
382
383 <div class="min-w-0 flex-1 space-y-0.5 pr-6">
384 <span class="block truncate font-semibold text-text-strong">
385 {item.title}
386 </span>
387 <p class="line-clamp-2 text-[11px] leading-snug text-text-subtle">
388 {item.description}
389 </p>
390 </div>
391
392 <button
393 type="button"
394 class="absolute right-2 top-2 flex h-6 w-6 items-center justify-center rounded-md text-text-subtle/70 opacity-80 transition-all hover:bg-destructive/10 hover:text-destructive-text sm:opacity-0 sm:group-hover:opacity-100"
395 title={t("notifications.dismiss")}
396 onClick={(e) => handleDismissSingle(e, item.id)}
397 >
398 <IconX class="h-3.5 w-3.5" />
399 </button>
400 </div>
401 )}
402 </For>
403 </div>
404 </section>
405 )}
406 </For>
407 </div>
408 </Show>
409 </Suspense>
410 </TabsContent>
411
412 <TabsContent value="system" class="mt-0">
413 <ComingSoonPanel title={t("notifications.tabSystem")} class="border-0 p-3" />
414 </TabsContent>
415 </Tabs>
416 }
417 >
418 {(item) => (
419 <div class="space-y-4 p-4">
420 <div class="flex items-center gap-2">
421 <Button
422 type="button"
423 variant="ghost"
424 size="sm"
425 class="h-7 rounded-lg px-2 text-[11px] text-text-subtle"
426 onClick={() => setPreviewNotification(null)}
427 >
428 <IconChevronLeft class="mr-1 h-3.5 w-3.5" />
429 {t("common.back")}
430 </Button>
431 </div>
432
433 <div class="space-y-2">
434 <div class="flex items-start gap-3">
435 <div class={cn("flex h-10 w-10 shrink-0 items-center justify-center rounded-xl", notificationGroupIconTone(item().type))}>
436 <Show when={item().type === "message"}>
437 <IconMessage class="h-5 w-5" />
438 </Show>
439 <Show when={item().type === "event"}>
440 <IconCalendar class="h-5 w-5" />
441 </Show>
442 <Show when={item().type === "exam"}>
443 <IconExam class="h-5 w-5" />
444 </Show>
445 <Show when={item().type === "homework"}>
446 <IconHomework class="h-5 w-5" />
447 </Show>
448 </div>
449 <div class="min-w-0 space-y-1">
450 <h4 class="text-sm font-semibold leading-snug text-text-strong">{item().title}</h4>
451 <p class="whitespace-pre-line text-xs leading-relaxed text-text-subtle">
452 {item().preview ?? item().description}
453 </p>
454 </div>
455 </div>
456 </div>
457
458 <Button type="button" size="sm" class="w-full rounded-lg" onClick={handleNavigateToNotification}>
459 <IconExternalLink class="mr-1.5 h-3.5 w-3.5" />
460 {t("notifications.goToPage")}
461 </Button>
462 </div>
463 )}
464 </Show>
465 </PopoverContent>
466 </Popover>
467 );
468}