forge
Explore
Log in

Don't you dare go Hollow

⚡ visibility-aware polling and deduped shell feed

Browse files at this commit

e70073f2ba61053e978eb23f58400e5cfdff066eAhmet Kaan GümüşParent: 60e4910
  • perf
    • ⚡ visibility-aware polling and deduped shell feed
Show full message
perf: ⚡ visibility-aware polling and deduped shell feed
- add src/lib/create-live-poll.ts: interval runs only while the tab is
  visible, refetches on tab-back (visibilitychange + focus, 1s dedupe),
  pauses when hidden; colocated test
- appointments-page: 30s raw poll → createLivePoll at 10s, so a
  cross-actor status change (approve/reject/cancel by the other party)
  is instant on tab-back instead of up to 30s stale
- add src/stores/shell-feed-context.tsx: one ShellFeedProvider holding a
  single poll for messages/events/exams/appointments/homework, fetched
  once and read via resource.latest; fetch gated on auth.user()
- right-nav + notification-center: drop their duplicate per-component
  resources and local timers, read from useShellFeed instead — shell
  goes from ~8 GETs/min across two pollers to ~5 from one
- notification-center derives unread by filtering the shared inbox
  instead of a separate read:false fetch
src/components/layout/app-shell.tsxmodified+3 -0
@@ -13,6 +13,7 @@ import { Button } from "@/components/ui/button";
1313 import { IconBotSquare, IconPanelLeft, IconSearch, IconX } from "@/components/ui/icons";
1414 import { Toaster } from "@/components/ui/toast";
1515 import { useAuth } from "@/stores/auth-context";
16+import { ShellFeedProvider } from "@/stores/shell-feed-context";
1617 import { usePreferences, useT } from "@/stores/preferences-context";
1718 import { cn } from "@/lib/cn";
1819
@@ -71,6 +72,7 @@ export function AppShell(props: ParentProps) {
7172 <Show when={!auth.user()}>
7273 <NavBar />
7374 </Show>
75+ <ShellFeedProvider>
7476 <div class="flex w-full">
7577 <Show when={auth.user() && !fullScreen()}>
7678 <aside
@@ -201,6 +203,7 @@ export function AppShell(props: ParentProps) {
201203 <RightNav />
202204 </Show>
203205 </div>
206+ </ShellFeedProvider>
204207 <Show when={auth.user() && !wide()}>
205208 <MobileTabBar onMenu={() => setMobileOpen(true)} />
206209 </Show>
src/components/layout/notification-center.tsxmodified+18 -68
@@ -1,9 +1,6 @@
1-import { For, Show, Suspense, createEffect, createMemo, createResource, createSignal, onCleanup } from "solid-js";
1+import { For, Show, Suspense, createEffect, createMemo, createSignal } from "solid-js";
22 import { useNavigate } from "@tanstack/solid-router";
3-import { getEvents } from "@/api/events";
4-import { getExams } from "@/api/exams";
5-import { getHomework } from "@/api/homework";
6-import { getMessages, patchMessageById } from "@/api/messages";
3+import { patchMessageById } from "@/api/messages";
74 import { Button } from "@/components/ui/button";
85 import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
96 import {
@@ -24,71 +21,23 @@ import {
2421 type NotificationItem,
2522 } from "@/lib/notifications";
2623 import { useT } from "@/stores/preferences-context";
24+import { useShellFeed } from "@/stores/shell-feed-context";
2725
2826 export function NotificationCenter() {
2927 const t = useT();
3028 const navigate = useNavigate();
29+ const feed = useShellFeed();
3130 const [open, setOpen] = createSignal(false);
3231 const [dismissedIds, setDismissedIds] = createSignal<Set<string>>(getDismissedNotificationIds());
3332
34- // Fetch data sources. `initialValue` is required: the unread badge reads
35- // these via `unreadCount()` OUTSIDE the popover's <Suspense>, so a bare
36- // `resource()` would re-suspend on every 60s `refreshAll()` refetch and — since
37- // this component sits beside <Outlet> in AppShell — blank the whole page for
38- // the fetch duration. A seeded value keeps `resource()` non-suspending on
39- // refetch (matches RightNav).
40- const [messagesRes, { refetch: refetchMessages }] = createResource(
41- async () => {
42- try {
43- return await getMessages("inbox", { read: false, limit: 10 });
44- } catch {
45- return { items: [], total: 0 };
46- }
47- },
48- { initialValue: { items: [], total: 0 } }
49- );
50-
51- const [eventsRes, { refetch: refetchEvents }] = createResource(async () => {
52- try {
53- return await getEvents();
54- } catch {
55- return { items: [], total: 0 };
56- }
57- }, { initialValue: { items: [], total: 0 } });
58-
59- const [examsRes, { refetch: refetchExams }] = createResource(async () => {
60- try {
61- return await getExams();
62- } catch {
63- return { items: [], total: 0 };
64- }
65- }, { initialValue: { items: [], total: 0 } });
66-
67- const [homeworkRes, { refetch: refetchHomework }] = createResource(async () => {
68- try {
69- return await getHomework();
70- } catch {
71- return { items: [], total: 0 };
72- }
73- }, { initialValue: { items: [], total: 0 } });
74-
75- // Revalidate every source so an item deleted on another page stops
76- // notifying: on the periodic clock tick (badge self-heals) and whenever
77- // the panel is opened (list is fresh on interaction).
78- const refreshAll = () => {
79- void refetchMessages();
80- void refetchEvents();
81- void refetchExams();
82- void refetchHomework();
83- };
84-
85- // Reactive clock so passed items drop off without a remount.
86- const [nowMs, setNowMs] = createSignal(Date.now());
87- const clockTimer = setInterval(() => {
88- setNowMs(Date.now());
89- refreshAll();
90- }, 60_000);
91- onCleanup(() => clearInterval(clockTimer));
33+ // Shell feed data comes from the shared poller (ShellFeedProvider): one fetch
34+ // per source for the whole shell instead of a duplicate set here. Every read
35+ // below is `feed.x()` which returns `resource.latest` — non-suspending on the
36+ // 60s refetch, so the unread badge (outside the popover's <Suspense>) never
37+ // blanks the page beside <Outlet> (AGENTS.md #6).
38+ const refetchMessages = feed.refetchMessages;
39+ const refreshAll = feed.refreshAll;
40+ const nowMs = feed.nowMs;
9241
9342 createEffect(() => {
9443 if (open()) refreshAll();
@@ -101,8 +50,9 @@ export function NotificationCenter() {
10150 const allNotifications = createMemo<NotificationItem[]>(() => {
10251 const list: NotificationItem[] = [];
10352
104- // 1. Unread Messages
105- const msgs = messagesRes.latest?.items ?? [];
53+ // 1. Unread Messages — shared inbox is the full list, filter to unread here
54+ // (was a dedicated read:false fetch before the shell feed consolidation).
55+ const msgs = feed.messages().items.filter((m) => !m.read);
10656 for (const m of msgs) {
10757 list.push({
10858 id: `msg_${m.id}`,
@@ -115,7 +65,7 @@ export function NotificationCenter() {
11565 }
11666
11767 // 2. Events starting today or upcoming
118- const evts = eventsRes.latest?.items ?? [];
68+ const evts = feed.events().items;
11969 for (const e of evts) {
12070 if (!e.starts_at) continue;
12171 const t = new Date(e.starts_at).getTime();
@@ -139,7 +89,7 @@ export function NotificationCenter() {
13989 }
14090
14191 // 3. Exams starting today or upcoming
142- const exms = examsRes.latest?.items ?? [];
92+ const exms = feed.exams().items;
14393 for (const ex of exms) {
14494 if (!ex.starts_at || ex.draft) continue;
14595 const t = new Date(ex.starts_at).getTime();
@@ -163,7 +113,7 @@ export function NotificationCenter() {
163113 }
164114
165115 // 4. Homework due upcoming
166- const hws = homeworkRes.latest?.items ?? [];
116+ const hws = feed.homework().items;
167117 for (const hw of hws) {
168118 if (!hw.due_at) continue;
169119 if (hw.due_at >= nowMs()) {
src/components/layout/right-nav.tsxmodified+19 -74
@@ -1,9 +1,6 @@
1-import { For, Show, Suspense, createEffect, createMemo, createResource, createSignal, onCleanup } from "solid-js";
1+import { For, Show, Suspense, createEffect, createMemo, createSignal } from "solid-js";
22 import { useLocation, useNavigate } from "@tanstack/solid-router";
3-import { getEvents } from "@/api/events";
4-import { getExams } from "@/api/exams";
5-import { getAppointments } from "@/api/appointments";
6-import { getMessages, patchMessageById } from "@/api/messages";
3+import { patchMessageById } from "@/api/messages";
74 import type { Appointment, Event, Exam, Message } from "@/api/client";
85 import { appointmentStatusClass, appointmentStatusDotClass, appointmentStatusLabelKey } from "@/lib/appointment-status";
96 import { Badge } from "@/components/ui/badge";
@@ -22,6 +19,7 @@ import {
2219 import { cn } from "@/lib/cn";
2320 import { personLabel } from "@/lib/person";
2421 import { usePreferences, useT } from "@/stores/preferences-context";
22+import { useShellFeed } from "@/stores/shell-feed-context";
2523
2624 type ActiveTab = "messages" | "calendar" | null;
2725 type CalendarItemRef =
@@ -36,6 +34,7 @@ export function RightNav() {
3634 const navigate = useNavigate();
3735 const location = useLocation();
3836 const { locale } = usePreferences();
37+ const feed = useShellFeed();
3938
4039 const isMessagesActive = () => location().pathname === "/messages";
4140 const isCalendarActive = () => location().pathname === "/calendar";
@@ -52,67 +51,18 @@ export function RightNav() {
5251 const [calFilter, setCalFilter] = createSignal<"all" | "events" | "exams" | "appointments">("all");
5352 const [selectedCalItem, setSelectedCalItem] = createSignal<CalendarItemRef | null>(null);
5453
55- // Fetch inbox messages
56- const [messagesRes, { refetch: refetchMessages }] = createResource(
57- async () => {
58- try {
59- return await getMessages("inbox", { limit: 100 });
60- } catch {
61- return { items: [], total: 0, limit: 100, offset: 0 };
62- }
63- },
64- { initialValue: { items: [], total: 0, limit: 100, offset: 0 } }
65- );
66-
67- // Fetch events & exams
68- const [eventsRes, { refetch: refetchEvents }] = createResource(
69- async () => {
70- try {
71- return (await getEvents({ limit: 100 })).items;
72- } catch {
73- return [];
74- }
75- },
76- { initialValue: [] }
77- );
78-
79- const [examsRes, { refetch: refetchExams }] = createResource(
80- async () => {
81- try {
82- return (await getExams({ limit: 100 })).items;
83- } catch {
84- return [];
85- }
86- },
87- { initialValue: [] }
88- );
89-
90- const [appointmentsRes, { refetch: refetchAppointments }] = createResource(
91- async () => {
92- try {
93- return (await getAppointments({ limit: 100 })).items;
94- } catch {
95- return [];
96- }
97- },
98- { initialValue: [] }
99- );
100-
101- // Revalidate every source so an item deleted on another page stops showing
102- // in the drawer/badge: on the periodic clock tick and whenever a drawer opens.
103- const refreshAll = () => {
104- void refetchMessages();
105- void refetchEvents();
106- void refetchExams();
107- void refetchAppointments();
108- };
54+ // Shell feed data comes from the shared poller (ShellFeedProvider), so
55+ // messages/events/exams/appointments are fetched once for the whole shell,
56+ // not independently here and in NotificationCenter.
57+ const refetchMessages = feed.refetchMessages;
58+ const refreshAll = feed.refreshAll;
10959
11060 // Computed message data
111- // `.latest`, not `messagesRes()`: this feeds the always-rendered unread badge,
112- // which is outside any <Suspense>. A bare read re-suspends on every 60s refetch
113- // and — since RightNav sits beside <Outlet> in AppShell — blanks the whole page
114- // for the fetch duration. `.latest` keeps the last value without suspending.
115- const allMessages = () => messagesRes.latest.items;
61+ // `.latest` (via the store accessor), not a bare `resource()`: this feeds the
62+ // always-rendered unread badge outside any <Suspense>. A bare read re-suspends
63+ // on every 60s refetch and — since RightNav sits beside <Outlet> in AppShell —
64+ // blanks the whole page for the fetch duration. `.latest` keeps the last value.
65+ const allMessages = () => feed.messages().items;
11666 const unreadCount = createMemo(() => allMessages().filter((m: Message) => !m.read).length);
11767
11868 const filteredMessages = createMemo(() => {
@@ -128,13 +78,8 @@ export function RightNav() {
12878 return filteredMessages().slice(0, 5);
12979 });
13080
131- // Reactive clock so passed items clear without a remount.
132- const [nowMs, setNowMs] = createSignal(Date.now());
133- const clockTimer = setInterval(() => {
134- setNowMs(Date.now());
135- refreshAll();
136- }, 60_000);
137- onCleanup(() => clearInterval(clockTimer));
81+ // Reactive clock from the shared poller so passed items clear without a remount.
82+ const nowMs = feed.nowMs;
13883
13984 createEffect(() => {
14085 if (activeTab() !== null) refreshAll();
@@ -148,15 +93,15 @@ export function RightNav() {
14893 };
14994
15095 const activeEvents = createMemo(() => {
151- return eventsRes.latest.filter((e: Event) => notEnded(e.starts_at, e.ends_at));
96+ return feed.events().items.filter((e: Event) => notEnded(e.starts_at, e.ends_at));
15297 });
15398
15499 const activeExams = createMemo(() => {
155- return examsRes.latest.filter((e: Exam) => !e.draft && notEnded(e.starts_at, e.ends_at));
100+ return feed.exams().items.filter((e: Exam) => !e.draft && notEnded(e.starts_at, e.ends_at));
156101 });
157102
158103 const activeAppointments = createMemo(() => {
159- return appointmentsRes.latest.filter(
104+ return feed.appointments().items.filter(
160105 (a: Appointment) => (a.status === "pending" || a.status === "approved") && notEnded(a.starts_at, a.ends_at)
161106 );
162107 });
src/lib/create-live-poll.test.tsadded+96 -0
@@ -0,0 +1,96 @@
1+import { createRoot } from "solid-js";
2+import { createLivePoll } from "./create-live-poll";
3+
4+// vitest runs in the node environment (no jsdom). node ships global EventTarget
5+// and Event, so we back document/window with real EventTargets plus a settable
6+// `hidden` getter — enough surface for the helper (addEventListener,
7+// removeEventListener, dispatchEvent, document.hidden).
8+let hidden = false;
9+let doc: EventTarget & { hidden: boolean };
10+let win: EventTarget;
11+const setHidden = (v: boolean) => {
12+ hidden = v;
13+};
14+const savedDoc = globalThis.document;
15+const savedWin = globalThis.window;
16+
17+describe("createLivePoll", () => {
18+ beforeEach(() => {
19+ vi.useFakeTimers();
20+ hidden = false;
21+ doc = new EventTarget() as EventTarget & { hidden: boolean };
22+ Object.defineProperty(doc, "hidden", { get: () => hidden });
23+ win = new EventTarget();
24+ (globalThis as { document: unknown }).document = doc;
25+ (globalThis as { window: unknown }).window = win;
26+ });
27+ afterEach(() => {
28+ vi.useRealTimers();
29+ vi.restoreAllMocks();
30+ (globalThis as { document: unknown }).document = savedDoc;
31+ (globalThis as { window: unknown }).window = savedWin;
32+ });
33+
34+ it("polls on the interval while visible", () => {
35+ const refetch = vi.fn();
36+ createRoot((dispose) => {
37+ createLivePoll(refetch, 1000);
38+ expect(refetch).not.toHaveBeenCalled(); // no immediate call — resource already loaded
39+ vi.advanceTimersByTime(3000);
40+ expect(refetch).toHaveBeenCalledTimes(3);
41+ dispose();
42+ });
43+ });
44+
45+ it("does not start the interval when the tab is hidden on mount", () => {
46+ setHidden(true);
47+ const refetch = vi.fn();
48+ createRoot((dispose) => {
49+ createLivePoll(refetch, 1000);
50+ vi.advanceTimersByTime(5000);
51+ expect(refetch).not.toHaveBeenCalled();
52+ dispose();
53+ });
54+ });
55+
56+ it("refetches once on tab-back and resumes polling", () => {
57+ const refetch = vi.fn();
58+ createRoot((dispose) => {
59+ createLivePoll(refetch, 1000);
60+ setHidden(true);
61+ doc.dispatchEvent(new Event("visibilitychange"));
62+ vi.advanceTimersByTime(5000);
63+ expect(refetch).toHaveBeenCalledTimes(0); // no polls while hidden
64+ setHidden(false);
65+ doc.dispatchEvent(new Event("visibilitychange"));
66+ expect(refetch).toHaveBeenCalledTimes(1); // immediate catch-up
67+ vi.advanceTimersByTime(2000);
68+ expect(refetch).toHaveBeenCalledTimes(3); // polling resumed
69+ dispose();
70+ });
71+ });
72+
73+ it("collapses a visibilitychange+focus double-fire into one refetch", () => {
74+ const refetch = vi.fn();
75+ createRoot((dispose) => {
76+ createLivePoll(refetch, 10_000);
77+ setHidden(true);
78+ doc.dispatchEvent(new Event("visibilitychange"));
79+ setHidden(false);
80+ doc.dispatchEvent(new Event("visibilitychange"));
81+ win.dispatchEvent(new Event("focus"));
82+ expect(refetch).toHaveBeenCalledTimes(1); // 1s guard swallows the second wake
83+ dispose();
84+ });
85+ });
86+
87+ it("stops polling after dispose", () => {
88+ const refetch = vi.fn();
89+ createRoot((dispose) => {
90+ createLivePoll(refetch, 1000);
91+ dispose();
92+ });
93+ vi.advanceTimersByTime(5000);
94+ expect(refetch).not.toHaveBeenCalled();
95+ });
96+});
src/lib/create-live-poll.tsadded+54 -0
@@ -0,0 +1,54 @@
1+import { onCleanup } from "solid-js";
2+
3+/**
4+ * Visibility-aware polling primitive. Call inside a component/owner scope.
5+ *
6+ * Why this exists: a plain `setInterval(refetch, ms)` keeps firing in hidden
7+ * tabs (wasted GETs) and never catches up when the user returns — so state
8+ * changed by *another* actor (e.g. a teacher approving a student's appointment)
9+ * shows up to one full interval stale on a parked tab. This runs the interval
10+ * only while the tab is visible, and refetches immediately when the tab becomes
11+ * visible or the window regains focus, so tab-back is instant-fresh.
12+ *
13+ * Pair with `resource.latest` reads (see AGENTS.md #6): a refetch never
14+ * re-suspends, so the poll can't blank a shell that sits beside <Outlet>.
15+ *
16+ * @param refetch called on each visible tick and on visibility/focus wake.
17+ * @param intervalMs poll period while visible (default 30s).
18+ */
19+export function createLivePoll(refetch: () => unknown, intervalMs = 30_000): void {
20+ let timer: ReturnType<typeof setInterval> | undefined;
21+ let lastRun = 0;
22+ const run = () => {
23+ lastRun = Date.now();
24+ void refetch();
25+ };
26+ const start = () => {
27+ if (!timer) timer = setInterval(run, intervalMs);
28+ };
29+ const stop = () => {
30+ if (timer) {
31+ clearInterval(timer);
32+ timer = undefined;
33+ }
34+ };
35+ // visibilitychange (tab switch) and window focus can both fire on tab-back;
36+ // the 1s guard collapses that into a single refetch.
37+ const wake = () => {
38+ if (document.hidden) {
39+ stop();
40+ return;
41+ }
42+ if (Date.now() - lastRun > 1_000) run();
43+ start();
44+ };
45+
46+ if (!document.hidden) start();
47+ document.addEventListener("visibilitychange", wake);
48+ window.addEventListener("focus", wake);
49+ onCleanup(() => {
50+ stop();
51+ document.removeEventListener("visibilitychange", wake);
52+ window.removeEventListener("focus", wake);
53+ });
54+}
src/pages/appointments-page.tsxmodified+6 -4
@@ -1,4 +1,4 @@
1-import { Show, createMemo, createResource, createSignal, onCleanup } from "solid-js";
1+import { Show, createMemo, createResource, createSignal } from "solid-js";
22 import type { ColumnDef } from "@tanstack/solid-table";
33 import {
44 deleteSlotById,
@@ -15,6 +15,7 @@ import {
1515 postSlots,
1616 } from "@/api/appointments";
1717 import { APPOINTMENT_LIMITS, formatApiError } from "@/api/client";
18+import { createLivePoll } from "@/lib/create-live-poll";
1819 import type { Appointment, AppointmentSlot, AppointmentStatus } from "@/api/client";
1920 import type { MessageKey } from "@/i18n/messages";
2021 import { BookAppointmentForm } from "@/components/appointments/book-appointment-form";
@@ -75,9 +76,10 @@ function AppointmentsContent() {
7576 const loaded = () => slots.latest !== undefined && appts.latest !== undefined;
7677
7778 // Poll so statuses stay in sync when the other party acts (approve, book,
78- // cancel…). Reads use `.latest`, so a refetch never re-suspends/blanks the tables.
79- const poll = setInterval(() => void refetchAll(), 30_000);
80- onCleanup(() => clearInterval(poll));
79+ // cancel…). Visibility-aware: pauses on hidden tabs, refetches on tab-back so
80+ // a cross-actor status change isn't stale on a parked tab. Reads use `.latest`,
81+ // so a refetch never re-suspends/blanks the tables.
82+ createLivePoll(refetchAll, 10_000);
8183 const act = async (fn: () => Promise<unknown>, successKey?: MessageKey) => {
8284 setError("");
8385 try {
src/stores/shell-feed-context.tsxadded+153 -0
@@ -0,0 +1,153 @@
1+import {
2+ type Accessor,
3+ type ParentProps,
4+ createContext,
5+ createResource,
6+ createSignal,
7+ useContext,
8+} from "solid-js";
9+import { getEvents } from "@/api/events";
10+import { getExams } from "@/api/exams";
11+import { getHomework } from "@/api/homework";
12+import { getAppointments } from "@/api/appointments";
13+import { getMessages } from "@/api/messages";
14+import type { Appointment, Event, Exam, Homework, Message, Page } from "@/api/client";
15+import { createLivePoll } from "@/lib/create-live-poll";
16+import { useAuth } from "@/stores/auth-context";
17+
18+// One shared poller for the always-mounted shell (NotificationCenter header +
19+// RightNav sidebar). Both used to `createResource` messages/events/exams
20+// independently — ~8 GETs/min. This fetches the widest form of each source
21+// ONCE; both consumers derive their own views locally.
22+//
23+// Every accessor returns `resource.latest`, not `resource()`: these feed
24+// always-rendered badges/counts OUTSIDE any <Suspense> (beside <Outlet>). A
25+// bare read re-suspends on every 60s refetch and blanks the whole page for the
26+// fetch duration (AGENTS.md #6). `.latest` + `initialValue` never suspends.
27+
28+type ShellFeedContextValue = {
29+ messages: Accessor<Page<Message>>;
30+ events: Accessor<Page<Event>>;
31+ exams: Accessor<Page<Exam>>;
32+ appointments: Accessor<Page<Appointment>>;
33+ homework: Accessor<Page<Homework>>;
34+ nowMs: Accessor<number>;
35+ refetchMessages: () => void;
36+ refetchEvents: () => void;
37+ refetchExams: () => void;
38+ refetchAppointments: () => void;
39+ refetchHomework: () => void;
40+ refreshAll: () => void;
41+};
42+
43+const ShellFeedContext = createContext<ShellFeedContextValue>();
44+
45+const emptyPage = <T,>(): Page<T> => ({ items: [], total: 0, limit: null, offset: 0 });
46+
47+export function ShellFeedProvider(props: ParentProps) {
48+ const auth = useAuth();
49+ // Only fetch for a logged-in user: source is falsy while logged out, so the
50+ // resource keeps its seeded empty value and never hits the network.
51+ const source = () => !!auth.user();
52+
53+ const [messagesRes, { refetch: refetchMessages }] = createResource(
54+ source,
55+ async () => {
56+ try {
57+ return await getMessages("inbox", { limit: 100 });
58+ } catch {
59+ return emptyPage<Message>();
60+ }
61+ },
62+ { initialValue: emptyPage<Message>() }
63+ );
64+
65+ const [eventsRes, { refetch: refetchEvents }] = createResource(
66+ source,
67+ async () => {
68+ try {
69+ return await getEvents({ limit: 100 });
70+ } catch {
71+ return emptyPage<Event>();
72+ }
73+ },
74+ { initialValue: emptyPage<Event>() }
75+ );
76+
77+ const [examsRes, { refetch: refetchExams }] = createResource(
78+ source,
79+ async () => {
80+ try {
81+ return await getExams({ limit: 100 });
82+ } catch {
83+ return emptyPage<Exam>();
84+ }
85+ },
86+ { initialValue: emptyPage<Exam>() }
87+ );
88+
89+ const [appointmentsRes, { refetch: refetchAppointments }] = createResource(
90+ source,
91+ async () => {
92+ try {
93+ return await getAppointments({ limit: 100 });
94+ } catch {
95+ return emptyPage<Appointment>();
96+ }
97+ },
98+ { initialValue: emptyPage<Appointment>() }
99+ );
100+
101+ const [homeworkRes, { refetch: refetchHomework }] = createResource(
102+ source,
103+ async () => {
104+ try {
105+ return await getHomework();
106+ } catch {
107+ return emptyPage<Homework>();
108+ }
109+ },
110+ { initialValue: emptyPage<Homework>() }
111+ );
112+
113+ const refreshAll = () => {
114+ void refetchMessages();
115+ void refetchEvents();
116+ void refetchExams();
117+ void refetchAppointments();
118+ void refetchHomework();
119+ };
120+
121+ // Reactive clock so passed items drop off without a remount. Visibility-aware:
122+ // no ticks/GETs while the tab is hidden, refetch on tab-back so nothing is
123+ // stale on a parked tab. This is the single shell poller.
124+ const [nowMs, setNowMs] = createSignal(Date.now());
125+ createLivePoll(() => {
126+ if (!auth.user()) return;
127+ setNowMs(Date.now());
128+ refreshAll();
129+ }, 60_000);
130+
131+ const value: ShellFeedContextValue = {
132+ messages: () => messagesRes.latest,
133+ events: () => eventsRes.latest,
134+ exams: () => examsRes.latest,
135+ appointments: () => appointmentsRes.latest,
136+ homework: () => homeworkRes.latest,
137+ nowMs,
138+ refetchMessages: () => void refetchMessages(),
139+ refetchEvents: () => void refetchEvents(),
140+ refetchExams: () => void refetchExams(),
141+ refetchAppointments: () => void refetchAppointments(),
142+ refetchHomework: () => void refetchHomework(),
143+ refreshAll,
144+ };
145+
146+ return <ShellFeedContext.Provider value={value}>{props.children}</ShellFeedContext.Provider>;
147+}
148+
149+export function useShellFeed(): ShellFeedContextValue {
150+ const ctx = useContext(ShellFeedContext);
151+ if (!ctx) throw new Error("useShellFeed must be used within ShellFeedProvider");
152+ return ctx;
153+}