hezarfen_frontend
Clone
https://git.tahinli.com/Hezarfen/hezarfen_frontend.git
0 watching0 forksTypeScript5.5 MiB5fcd955Burak Boduroğlu2 months ago730 commits
| 1 | import { createMemo, createSignal } from "solid-js"; |
| 2 | import { patchMessageById } from "@/api/messages"; |
| 3 | import { createInstanceLabels } from "@/lib/instance-labels"; |
| 4 | import { personLabel } from "@/lib/person"; |
| 5 | import { |
| 6 | dismissAllNotificationIds, |
| 7 | dismissNotificationId, |
| 8 | getDismissedNotificationIds, |
| 9 | getReadNotificationIds, |
| 10 | markNotificationRead, |
| 11 | type NotificationItem, |
| 12 | type NotificationType, |
| 13 | } from "@/lib/notifications"; |
| 14 | import { useAuth } from "@/stores/auth-context"; |
| 15 | import { usePreferences } from "@/stores/preferences-context"; |
| 16 | import { useShellFeed } from "@/stores/shell-feed-context"; |
| 17 | |
| 18 | /** |
| 19 | * The notification list and its read/dismissed state, apart from any chrome. |
| 20 | * The desktop header shows it in a popover and the phone shell in a panel |
| 21 | * opened from the floating action button; each mounts one of these, and the |
| 22 | * shell mounts only one of the two at a time, so the dismissed state never |
| 23 | * has two in-memory copies. |
| 24 | */ |
| 25 | export function createNotificationFeed() { |
| 26 | const { t, locale } = usePreferences(); |
| 27 | const dateLocale = () => (locale() === "tr" ? "tr-TR" : "en-US"); |
| 28 | const feed = useShellFeed(); |
| 29 | const [dismissedIds, setDismissedIds] = createSignal<Set<string>>(getDismissedNotificationIds()); |
| 30 | const [readIds, setReadIds] = createSignal<Set<string>>(getReadNotificationIds()); |
| 31 | |
| 32 | // Shell feed data comes from the shared poller (ShellFeedProvider): one fetch |
| 33 | // per source for the whole shell instead of a duplicate set here. Every read |
| 34 | // below is `feed.x()` which returns `resource.latest` — non-suspending on the |
| 35 | // 60s refetch, so the unread badge (outside the popover's <Suspense>) never |
| 36 | // blanks the page beside <Outlet> (AGENTS.md #6). |
| 37 | const nowMs = feed.nowMs; |
| 38 | |
| 39 | // An item is still notifiable until it has ended (ends_at, else starts_at). |
| 40 | const notEnded = (starts: number, ends?: number | null) => (ends ?? starts) >= nowMs(); |
| 41 | |
| 42 | // Exams and homework of one ders taught in two şubeler share titles; the |
| 43 | // row's description names "<ders> — <şube>" so they can be told apart. |
| 44 | // Only the open list shows these labels, and resolving them costs a read |
| 45 | // per section; the unread badge needs none. So they wait for the first open. |
| 46 | const auth = useAuth(); |
| 47 | const [labelsWanted, setLabelsWanted] = createSignal(false); |
| 48 | const sectionLabels = createInstanceLabels( |
| 49 | () => !labelsWanted() ? [] : [ |
| 50 | ...feed.exams().items.filter((ex) => ex.starts_at && !ex.draft && notEnded(ex.starts_at, ex.ends_at)).map((ex) => ex.class_course), |
| 51 | ...feed.homework().items.filter((hw) => hw.due_at >= nowMs()).map((hw) => hw.class_course), |
| 52 | ], |
| 53 | () => auth.user()?.role, |
| 54 | ); |
| 55 | const withSection = (instanceId: string, text: string) => { |
| 56 | const label = sectionLabels()[instanceId]?.label; |
| 57 | return label ? (text ? `${label} · ${text}` : label) : text; |
| 58 | }; |
| 59 | |
| 60 | // Combine notification items |
| 61 | const allNotifications = createMemo<NotificationItem[]>(() => { |
| 62 | const list: NotificationItem[] = []; |
| 63 | |
| 64 | // 1. Unread messages — the dedicated `read=false` page from the shell feed. |
| 65 | // Never filter the shared inbox page instead: it is capped and ordered by |
| 66 | // id DESC, so an older unread message is simply not in it. |
| 67 | const msgs = feed.unreadMessages().items; |
| 68 | for (const m of msgs) { |
| 69 | const body = m.body.replace(/<[^>]*>?/gm, "").trim(); |
| 70 | list.push({ |
| 71 | id: `msg_${m.id}`, |
| 72 | type: "message", |
| 73 | title: personLabel(m.sender), |
| 74 | description: m.subject || body, |
| 75 | preview: m.subject ? `${m.subject}\n${body}` : body, |
| 76 | targetUrl: "/messages", |
| 77 | timestamp: m.sent_at, |
| 78 | }); |
| 79 | } |
| 80 | |
| 81 | // 2. Events starting today or upcoming |
| 82 | const evts = feed.events().items; |
| 83 | for (const e of evts) { |
| 84 | if (!e.starts_at) continue; |
| 85 | const t = new Date(e.starts_at).getTime(); |
| 86 | if (notEnded(t, e.ends_at ? new Date(e.ends_at).getTime() : null)) { |
| 87 | list.push({ |
| 88 | id: `evt_${e.id}`, |
| 89 | type: "event", |
| 90 | title: e.title, |
| 91 | description: e.starts_at |
| 92 | ? new Date(e.starts_at).toLocaleString(dateLocale(), { |
| 93 | month: "short", |
| 94 | day: "numeric", |
| 95 | hour: "2-digit", |
| 96 | minute: "2-digit", |
| 97 | }) |
| 98 | : "", |
| 99 | targetUrl: `/events/${e.id}`, |
| 100 | timestamp: t, |
| 101 | }); |
| 102 | } |
| 103 | } |
| 104 | |
| 105 | // 3. Exams starting today or upcoming |
| 106 | const exms = feed.exams().items; |
| 107 | for (const ex of exms) { |
| 108 | if (!ex.starts_at || ex.draft) continue; |
| 109 | const t = new Date(ex.starts_at).getTime(); |
| 110 | if (notEnded(t, ex.ends_at ? new Date(ex.ends_at).getTime() : null)) { |
| 111 | list.push({ |
| 112 | id: `ex_${ex.id}`, |
| 113 | type: "exam", |
| 114 | title: ex.title, |
| 115 | description: withSection( |
| 116 | ex.class_course, |
| 117 | new Date(ex.starts_at).toLocaleString(dateLocale(), { |
| 118 | month: "short", |
| 119 | day: "numeric", |
| 120 | hour: "2-digit", |
| 121 | minute: "2-digit", |
| 122 | }), |
| 123 | ), |
| 124 | targetUrl: `/exams/${ex.id}`, |
| 125 | timestamp: t, |
| 126 | }); |
| 127 | } |
| 128 | } |
| 129 | |
| 130 | // 4. Homework due upcoming |
| 131 | const hws = feed.homework().items; |
| 132 | for (const hw of hws) { |
| 133 | if (!hw.due_at) continue; |
| 134 | if (hw.due_at >= nowMs()) { |
| 135 | list.push({ |
| 136 | id: `hw_${hw.id}`, |
| 137 | type: "homework", |
| 138 | title: hw.title, |
| 139 | description: withSection( |
| 140 | hw.class_course, |
| 141 | `${t("homework.dueAt")}: ${new Date(hw.due_at).toLocaleDateString(dateLocale(), { |
| 142 | month: "short", |
| 143 | day: "numeric", |
| 144 | })}`, |
| 145 | ), |
| 146 | targetUrl: `/homework/${hw.id}`, |
| 147 | timestamp: hw.due_at, |
| 148 | }); |
| 149 | } |
| 150 | } |
| 151 | |
| 152 | // Sort chronologically (newest/most relevant first) |
| 153 | return list.sort((a, b) => b.timestamp - a.timestamp); |
| 154 | }); |
| 155 | |
| 156 | // Filter out dismissed notifications |
| 157 | const activeNotifications = createMemo(() => { |
| 158 | const dismissed = dismissedIds(); |
| 159 | return allNotifications().filter((item) => !dismissed.has(item.id)); |
| 160 | }); |
| 161 | |
| 162 | const isUnread = (item: NotificationItem) => !readIds().has(item.id); |
| 163 | const unreadNotifications = createMemo(() => activeNotifications().filter(isUnread)); |
| 164 | |
| 165 | const notificationGroupOrder: NotificationType[] = ["message", "event", "exam", "homework"]; |
| 166 | const notificationGroups = createMemo(() => |
| 167 | notificationGroupOrder |
| 168 | .map((type) => ({ |
| 169 | type, |
| 170 | items: activeNotifications().filter((item) => item.type === type), |
| 171 | })) |
| 172 | .filter((group) => group.items.length > 0) |
| 173 | ); |
| 174 | |
| 175 | // The list only holds the newest 10 unread messages; `total` is the real |
| 176 | // server-side unread count, so the rest still counts towards the badge. |
| 177 | // Those extra rows have no id here, so they cannot be dismissed one by one: |
| 178 | // "dismiss all" snapshots the unread total instead. Everything at or below the |
| 179 | // snapshot counts as dismissed; anything above it arrived afterwards and still |
| 180 | // raises the badge (minus the new rows already listed, which the active list |
| 181 | // counts). Without the snapshot, 11 unread → dismiss all → badge stuck at 1 |
| 182 | // over an empty popover. |
| 183 | // ponytail: the snapshot is in-memory while dismissed ids are persisted, so a |
| 184 | // reload re-shows unlisted unread — upgrade path is storing it next to the ids |
| 185 | // in `lib/notifications`. |
| 186 | const [dismissedUnreadTotal, setDismissedUnreadTotal] = createSignal(0); |
| 187 | const activeMessageCount = () => activeNotifications().filter((item) => item.type === "message").length; |
| 188 | const unlistedUnread = () => { |
| 189 | const page = feed.unreadMessages(); |
| 190 | const beyondPage = page.total - page.items.length; |
| 191 | const sinceDismissAll = page.total - dismissedUnreadTotal() - activeMessageCount(); |
| 192 | return Math.max(0, Math.min(beyondPage, sinceDismissAll)); |
| 193 | }; |
| 194 | const unreadCount = () => unreadNotifications().length + unlistedUnread(); |
| 195 | |
| 196 | const dismiss = (id: string) => { |
| 197 | setDismissedIds(new Set(dismissNotificationId(id))); |
| 198 | }; |
| 199 | |
| 200 | const dismissAll = () => { |
| 201 | const ids = activeNotifications().map((item) => item.id); |
| 202 | setDismissedIds(new Set(dismissAllNotificationIds(ids))); |
| 203 | setDismissedUnreadTotal(feed.unreadMessages().total); |
| 204 | }; |
| 205 | |
| 206 | const markRead = async (item: NotificationItem) => { |
| 207 | if (isUnread(item)) { |
| 208 | setReadIds(new Set(markNotificationRead(item.id))); |
| 209 | } |
| 210 | |
| 211 | // Message notifications also need to be marked read in the backend. |
| 212 | if (item.id.startsWith("msg_")) { |
| 213 | const realId = item.id.replace("msg_", ""); |
| 214 | try { |
| 215 | await patchMessageById(realId, { read: true }); |
| 216 | void feed.refetchMessages(); |
| 217 | } catch { |
| 218 | // ignore |
| 219 | } |
| 220 | } |
| 221 | }; |
| 222 | |
| 223 | return { |
| 224 | groups: notificationGroups, |
| 225 | unreadCount, |
| 226 | dismiss, |
| 227 | dismissAll, |
| 228 | markRead, |
| 229 | refreshAll: feed.refreshAll, |
| 230 | /** Call when the list opens: resolves the section labels its rows show. */ |
| 231 | opened: () => setLabelsWanted(true), |
| 232 | }; |
| 233 | } |
| 234 | |
| 235 | export type NotificationFeed = ReturnType<typeof createNotificationFeed>; |