forge
Explore
Log in

Don't you dare go Hollow

hezarfen_frontend

Clone
★ 0

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

shell-feed-context.tsx242 lines, 9.1 KiBHistoryRawDownload
1import {
2 type Accessor,
3 type ParentProps,
4 createContext,
5 createMemo,
6 createSignal,
7 useContext,
8} from "solid-js";
9import { createResource } from "@/lib/create-resource";
10import { getEvents } from "@/api/events";
11import { getExams } from "@/api/exams";
12import { getHomework } from "@/api/homework";
13import { getAppointments } from "@/api/appointments";
14import { getMessages } from "@/api/messages";
15import type { Appointment, Event, Exam, Homework, Message, Page } from "@/api/client";
16import { createLivePoll } from "@/lib/create-live-poll";
17import { useAuth } from "@/stores/auth-context";
18import { useModules } from "@/stores/modules-context";
19
20// One shared poller for the always-mounted shell (NotificationCenter header +
21// header message/notification controls). Both used to `createResource` messages/events/exams
22// independently — ~8 GETs/min. This fetches the widest form of each source
23// ONCE; both consumers derive their own views locally.
24//
25// Every accessor returns `resource.latest`, not `resource()`: these feed
26// always-rendered badges/counts OUTSIDE any <Suspense> (beside <Outlet>). A
27// bare read re-suspends on every 60s refetch and blanks the whole page for the
28// fetch duration (AGENTS.md #6). `.latest` + `initialValue` never suspends.
29
30type ShellFeedContextValue = {
31 messages: Accessor<Page<Message>>;
32 /** Newest unread inbox rows; `.total` is the *exact* server-side unread count. */
33 unreadMessages: Accessor<Page<Message>>;
34 events: Accessor<Page<Event>>;
35 exams: Accessor<Page<Exam>>;
36 appointments: Accessor<Page<Appointment>>;
37 homework: Accessor<Page<Homework>>;
38 nowMs: Accessor<number>;
39 refetchMessages: () => void;
40 refetchEvents: () => void;
41 refetchExams: () => void;
42 refetchAppointments: () => void;
43 refetchHomework: () => void;
44 refreshAll: () => void;
45};
46
47const ShellFeedContext = createContext<ShellFeedContextValue>();
48
49const HOMEWORK_FEED_LIMIT = 100;
50
51const emptyPage = <T,>(): Page<T> => ({ items: [], total: 0, limit: null, offset: 0 });
52
53type UserFeed = Omit<ShellFeedContextValue, "nowMs">;
54
55// Everything user-scoped lives here so it can be created per account id and
56// disposed with it (see ShellFeedProvider): a logged-out or switched account
57// gets brand-new resources seeded with empty pages, so no previous user's rows
58// can survive into the next session. Solid keeps a resource's last value when
59// its source goes falsy, so gating alone would leak user A's inbox into user
60// B's shell until the refetch resolved.
61function createUserFeed(loggedIn: boolean, modulesLoading: () => boolean, isEnabled: (module: string) => boolean): UserFeed {
62 // Only fetch for a logged-in user: source is false while logged out, so the
63 // resource keeps its seeded empty value and never hits the network.
64 // It also waits for the school's module list, so a first paint never asks a
65 // switched-off module (and gets 403) before the list says it is off.
66 const source = () => loggedIn && !modulesLoading();
67
68 const [messagesRes, { refetch: refetchInbox }] = createResource(
69 source,
70 async () => {
71 try {
72 // A switched-off module would only answer 403 on every poll.
73 if (!isEnabled("messages")) return emptyPage<Message>();
74 return await getMessages("inbox", { limit: 100 });
75 } catch {
76 return emptyPage<Message>();
77 }
78 },
79 { initialValue: emptyPage<Message>() }
80 );
81
82 // The badge cannot be derived from the inbox page above: that page is
83 // ORDER BY id DESC capped at 100, so an old unread message falls off it.
84 // `read=false` makes `total` the exact server-side unread count, and the 10
85 // items are the newest unread ones the popover lists.
86 const [unreadRes, { refetch: refetchUnread }] = createResource(
87 source,
88 async () => {
89 try {
90 if (!isEnabled("messages")) return emptyPage<Message>();
91 return await getMessages("inbox", { read: false, limit: 10 });
92 } catch {
93 return emptyPage<Message>();
94 }
95 },
96 { initialValue: emptyPage<Message>() }
97 );
98
99 // `ends_after=now` keeps only rows whose window has not finished AND flips
100 // the server order to soonest-first, so a cap finally truncates the archive
101 // end instead of the upcoming end. Without it the whole school history rode
102 // along (~3.4 MB/poll at 5k+5k rows) only to be filtered out client-side.
103 //
104 // 50: the feed drives "upcoming" badges and the calendar dot — it needs the
105 // next handful, not the archive. 50 soonest-first rows cover a busy month
106 // per source. Both consumers already show only not-yet-ended items, so the
107 // dropped rows were never rendered.
108 // ponytail: a school with >50 simultaneously-open events loses the tail —
109 // upgrade path is narrowing the window (add an upper bound), not a bigger cap.
110 const upcoming = () => ({ ends_after: Date.now(), limit: 50 });
111
112 const [eventsRes, { refetch: refetchEvents }] = createResource(
113 source,
114 async () => {
115 try {
116 if (!isEnabled("events")) return emptyPage<Event>();
117 return await getEvents(upcoming());
118 } catch {
119 return emptyPage<Event>();
120 }
121 },
122 { initialValue: emptyPage<Event>() }
123 );
124
125 const [examsRes, { refetch: refetchExams }] = createResource(
126 source,
127 async () => {
128 try {
129 if (!isEnabled("exams")) return emptyPage<Exam>();
130 return await getExams(upcoming());
131 } catch {
132 return emptyPage<Exam>();
133 }
134 },
135 { initialValue: emptyPage<Exam>() }
136 );
137
138 const [appointmentsRes, { refetch: refetchAppointments }] = createResource(
139 source,
140 async () => {
141 try {
142 if (!isEnabled("appointments")) return emptyPage<Appointment>();
143 return await getAppointments({ limit: 100 });
144 } catch {
145 return emptyPage<Appointment>();
146 }
147 },
148 { initialValue: emptyPage<Appointment>() }
149 );
150
151 const [homeworkRes, { refetch: refetchHomework }] = createResource(
152 source,
153 async () => {
154 try {
155 if (!isEnabled("homework")) return emptyPage<Homework>();
156 // `/homework` has no due-date filter and lists newest-created first,
157 // so a page of the most recent rows holds everything still upcoming
158 // in practice. Unbounded, this poll pulled the school's whole
159 // homework history every minute on every page.
160 return await getHomework({ limit: HOMEWORK_FEED_LIMIT });
161 } catch {
162 return emptyPage<Homework>();
163 }
164 },
165 { initialValue: emptyPage<Homework>() }
166 );
167
168 // One call refreshes both message views — marking a message read changes the
169 // preview list and the unread count together.
170 const refetchMessages = () => {
171 void refetchInbox();
172 void refetchUnread();
173 };
174
175 const refreshAll = () => {
176 refetchMessages();
177 void refetchEvents();
178 void refetchExams();
179 void refetchAppointments();
180 void refetchHomework();
181 };
182
183 return {
184 messages: () => messagesRes.latest,
185 unreadMessages: () => unreadRes.latest,
186 events: () => eventsRes.latest,
187 exams: () => examsRes.latest,
188 appointments: () => appointmentsRes.latest,
189 homework: () => homeworkRes.latest,
190 refetchMessages,
191 refetchEvents: () => void refetchEvents(),
192 refetchExams: () => void refetchExams(),
193 refetchAppointments: () => void refetchAppointments(),
194 refetchHomework: () => void refetchHomework(),
195 refreshAll,
196 };
197}
198
199export function ShellFeedProvider(props: ParentProps) {
200 const auth = useAuth();
201 // Keyed on the account id: logging out (null) or switching account disposes
202 // the whole feed and builds a fresh one. Children never remount, so the
203 // router tree below is untouched.
204 const userId = createMemo(() => auth.user()?.id ?? null);
205 const modules = useModules();
206 const feed = createMemo(() => createUserFeed(userId() !== null, modules.loading, modules.isEnabled));
207
208 // Reactive clock so passed items drop off without a remount. Visibility-aware:
209 // no ticks/GETs while the tab is hidden, refetch on tab-back so nothing is
210 // stale on a parked tab. This is the single shell poller — it outlives the
211 // per-user feeds and always drives the current one.
212 const [nowMs, setNowMs] = createSignal(Date.now());
213 createLivePoll(() => {
214 if (!auth.user()) return;
215 setNowMs(Date.now());
216 feed().refreshAll();
217 }, 60_000);
218
219 const value: ShellFeedContextValue = {
220 messages: () => feed().messages(),
221 unreadMessages: () => feed().unreadMessages(),
222 events: () => feed().events(),
223 exams: () => feed().exams(),
224 appointments: () => feed().appointments(),
225 homework: () => feed().homework(),
226 nowMs,
227 refetchMessages: () => feed().refetchMessages(),
228 refetchEvents: () => feed().refetchEvents(),
229 refetchExams: () => feed().refetchExams(),
230 refetchAppointments: () => feed().refetchAppointments(),
231 refetchHomework: () => feed().refetchHomework(),
232 refreshAll: () => feed().refreshAll(),
233 };
234
235 return <ShellFeedContext.Provider value={value}>{props.children}</ShellFeedContext.Provider>;
236}
237
238export function useShellFeed(): ShellFeedContextValue {
239 const ctx = useContext(ShellFeedContext);
240 if (!ctx) throw new Error("useShellFeed must be used within ShellFeedProvider");
241 return ctx;
242}