diff --git a/src/components/layout/app-shell.tsx b/src/components/layout/app-shell.tsx index fc86c0e..983bd80 100644 --- a/src/components/layout/app-shell.tsx +++ b/src/components/layout/app-shell.tsx @@ -13,6 +13,7 @@ import { Button } from "@/components/ui/button"; import { IconBotSquare, IconPanelLeft, IconSearch, IconX } from "@/components/ui/icons"; import { Toaster } from "@/components/ui/toast"; import { useAuth } from "@/stores/auth-context"; +import { ShellFeedProvider } from "@/stores/shell-feed-context"; import { usePreferences, useT } from "@/stores/preferences-context"; import { cn } from "@/lib/cn"; @@ -71,6 +72,7 @@ export function AppShell(props: ParentProps) { +
+
setMobileOpen(true)} /> diff --git a/src/components/layout/notification-center.tsx b/src/components/layout/notification-center.tsx index 49f9c3d..a4efe20 100644 --- a/src/components/layout/notification-center.tsx +++ b/src/components/layout/notification-center.tsx @@ -1,9 +1,6 @@ -import { For, Show, Suspense, createEffect, createMemo, createResource, createSignal, onCleanup } from "solid-js"; +import { For, Show, Suspense, createEffect, createMemo, createSignal } from "solid-js"; import { useNavigate } from "@tanstack/solid-router"; -import { getEvents } from "@/api/events"; -import { getExams } from "@/api/exams"; -import { getHomework } from "@/api/homework"; -import { getMessages, patchMessageById } from "@/api/messages"; +import { patchMessageById } from "@/api/messages"; import { Button } from "@/components/ui/button"; import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover"; import { @@ -24,71 +21,23 @@ import { type NotificationItem, } from "@/lib/notifications"; import { useT } from "@/stores/preferences-context"; +import { useShellFeed } from "@/stores/shell-feed-context"; export function NotificationCenter() { const t = useT(); const navigate = useNavigate(); + const feed = useShellFeed(); const [open, setOpen] = createSignal(false); const [dismissedIds, setDismissedIds] = createSignal>(getDismissedNotificationIds()); - // Fetch data sources. `initialValue` is required: the unread badge reads - // these via `unreadCount()` OUTSIDE the popover's , so a bare - // `resource()` would re-suspend on every 60s `refreshAll()` refetch and — since - // this component sits beside in AppShell — blank the whole page for - // the fetch duration. A seeded value keeps `resource()` non-suspending on - // refetch (matches RightNav). - const [messagesRes, { refetch: refetchMessages }] = createResource( - async () => { - try { - return await getMessages("inbox", { read: false, limit: 10 }); - } catch { - return { items: [], total: 0 }; - } - }, - { initialValue: { items: [], total: 0 } } - ); - - const [eventsRes, { refetch: refetchEvents }] = createResource(async () => { - try { - return await getEvents(); - } catch { - return { items: [], total: 0 }; - } - }, { initialValue: { items: [], total: 0 } }); - - const [examsRes, { refetch: refetchExams }] = createResource(async () => { - try { - return await getExams(); - } catch { - return { items: [], total: 0 }; - } - }, { initialValue: { items: [], total: 0 } }); - - const [homeworkRes, { refetch: refetchHomework }] = createResource(async () => { - try { - return await getHomework(); - } catch { - return { items: [], total: 0 }; - } - }, { initialValue: { items: [], total: 0 } }); - - // Revalidate every source so an item deleted on another page stops - // notifying: on the periodic clock tick (badge self-heals) and whenever - // the panel is opened (list is fresh on interaction). - const refreshAll = () => { - void refetchMessages(); - void refetchEvents(); - void refetchExams(); - void refetchHomework(); - }; - - // Reactive clock so passed items drop off without a remount. - const [nowMs, setNowMs] = createSignal(Date.now()); - const clockTimer = setInterval(() => { - setNowMs(Date.now()); - refreshAll(); - }, 60_000); - onCleanup(() => clearInterval(clockTimer)); + // 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(); @@ -101,8 +50,9 @@ export function NotificationCenter() { const allNotifications = createMemo(() => { const list: NotificationItem[] = []; - // 1. Unread Messages - const msgs = messagesRes.latest?.items ?? []; + // 1. Unread Messages — shared inbox is the full list, filter to unread here + // (was a dedicated read:false fetch before the shell feed consolidation). + const msgs = feed.messages().items.filter((m) => !m.read); for (const m of msgs) { list.push({ id: `msg_${m.id}`, @@ -115,7 +65,7 @@ export function NotificationCenter() { } // 2. Events starting today or upcoming - const evts = eventsRes.latest?.items ?? []; + const evts = feed.events().items; for (const e of evts) { if (!e.starts_at) continue; const t = new Date(e.starts_at).getTime(); @@ -139,7 +89,7 @@ export function NotificationCenter() { } // 3. Exams starting today or upcoming - const exms = examsRes.latest?.items ?? []; + 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(); @@ -163,7 +113,7 @@ export function NotificationCenter() { } // 4. Homework due upcoming - const hws = homeworkRes.latest?.items ?? []; + const hws = feed.homework().items; for (const hw of hws) { if (!hw.due_at) continue; if (hw.due_at >= nowMs()) { diff --git a/src/components/layout/right-nav.tsx b/src/components/layout/right-nav.tsx index 5c34e0a..6b65208 100644 --- a/src/components/layout/right-nav.tsx +++ b/src/components/layout/right-nav.tsx @@ -1,9 +1,6 @@ -import { For, Show, Suspense, createEffect, createMemo, createResource, createSignal, onCleanup } from "solid-js"; +import { For, Show, Suspense, createEffect, createMemo, createSignal } from "solid-js"; import { useLocation, useNavigate } from "@tanstack/solid-router"; -import { getEvents } from "@/api/events"; -import { getExams } from "@/api/exams"; -import { getAppointments } from "@/api/appointments"; -import { getMessages, patchMessageById } from "@/api/messages"; +import { patchMessageById } from "@/api/messages"; import type { Appointment, Event, Exam, Message } from "@/api/client"; import { appointmentStatusClass, appointmentStatusDotClass, appointmentStatusLabelKey } from "@/lib/appointment-status"; import { Badge } from "@/components/ui/badge"; @@ -22,6 +19,7 @@ import { import { cn } from "@/lib/cn"; import { personLabel } from "@/lib/person"; import { usePreferences, useT } from "@/stores/preferences-context"; +import { useShellFeed } from "@/stores/shell-feed-context"; type ActiveTab = "messages" | "calendar" | null; type CalendarItemRef = @@ -36,6 +34,7 @@ export function RightNav() { const navigate = useNavigate(); const location = useLocation(); const { locale } = usePreferences(); + const feed = useShellFeed(); const isMessagesActive = () => location().pathname === "/messages"; const isCalendarActive = () => location().pathname === "/calendar"; @@ -52,67 +51,18 @@ export function RightNav() { const [calFilter, setCalFilter] = createSignal<"all" | "events" | "exams" | "appointments">("all"); const [selectedCalItem, setSelectedCalItem] = createSignal(null); - // Fetch inbox messages - const [messagesRes, { refetch: refetchMessages }] = createResource( - async () => { - try { - return await getMessages("inbox", { limit: 100 }); - } catch { - return { items: [], total: 0, limit: 100, offset: 0 }; - } - }, - { initialValue: { items: [], total: 0, limit: 100, offset: 0 } } - ); - - // Fetch events & exams - const [eventsRes, { refetch: refetchEvents }] = createResource( - async () => { - try { - return (await getEvents({ limit: 100 })).items; - } catch { - return []; - } - }, - { initialValue: [] } - ); - - const [examsRes, { refetch: refetchExams }] = createResource( - async () => { - try { - return (await getExams({ limit: 100 })).items; - } catch { - return []; - } - }, - { initialValue: [] } - ); - - const [appointmentsRes, { refetch: refetchAppointments }] = createResource( - async () => { - try { - return (await getAppointments({ limit: 100 })).items; - } catch { - return []; - } - }, - { initialValue: [] } - ); - - // Revalidate every source so an item deleted on another page stops showing - // in the drawer/badge: on the periodic clock tick and whenever a drawer opens. - const refreshAll = () => { - void refetchMessages(); - void refetchEvents(); - void refetchExams(); - void refetchAppointments(); - }; + // Shell feed data comes from the shared poller (ShellFeedProvider), so + // messages/events/exams/appointments are fetched once for the whole shell, + // not independently here and in NotificationCenter. + const refetchMessages = feed.refetchMessages; + const refreshAll = feed.refreshAll; // Computed message data - // `.latest`, not `messagesRes()`: this feeds the always-rendered unread badge, - // which is outside any . A bare read re-suspends on every 60s refetch - // and — since RightNav sits beside in AppShell — blanks the whole page - // for the fetch duration. `.latest` keeps the last value without suspending. - const allMessages = () => messagesRes.latest.items; + // `.latest` (via the store accessor), not a bare `resource()`: this feeds the + // always-rendered unread badge outside any . A bare read re-suspends + // on every 60s refetch and — since RightNav sits beside in AppShell — + // blanks the whole page for the fetch duration. `.latest` keeps the last value. + const allMessages = () => feed.messages().items; const unreadCount = createMemo(() => allMessages().filter((m: Message) => !m.read).length); const filteredMessages = createMemo(() => { @@ -128,13 +78,8 @@ export function RightNav() { return filteredMessages().slice(0, 5); }); - // Reactive clock so passed items clear without a remount. - const [nowMs, setNowMs] = createSignal(Date.now()); - const clockTimer = setInterval(() => { - setNowMs(Date.now()); - refreshAll(); - }, 60_000); - onCleanup(() => clearInterval(clockTimer)); + // Reactive clock from the shared poller so passed items clear without a remount. + const nowMs = feed.nowMs; createEffect(() => { if (activeTab() !== null) refreshAll(); @@ -148,15 +93,15 @@ export function RightNav() { }; const activeEvents = createMemo(() => { - return eventsRes.latest.filter((e: Event) => notEnded(e.starts_at, e.ends_at)); + return feed.events().items.filter((e: Event) => notEnded(e.starts_at, e.ends_at)); }); const activeExams = createMemo(() => { - return examsRes.latest.filter((e: Exam) => !e.draft && notEnded(e.starts_at, e.ends_at)); + return feed.exams().items.filter((e: Exam) => !e.draft && notEnded(e.starts_at, e.ends_at)); }); const activeAppointments = createMemo(() => { - return appointmentsRes.latest.filter( + return feed.appointments().items.filter( (a: Appointment) => (a.status === "pending" || a.status === "approved") && notEnded(a.starts_at, a.ends_at) ); }); diff --git a/src/lib/create-live-poll.test.ts b/src/lib/create-live-poll.test.ts new file mode 100644 index 0000000..00ed6c1 --- /dev/null +++ b/src/lib/create-live-poll.test.ts @@ -0,0 +1,96 @@ +import { createRoot } from "solid-js"; +import { createLivePoll } from "./create-live-poll"; + +// vitest runs in the node environment (no jsdom). node ships global EventTarget +// and Event, so we back document/window with real EventTargets plus a settable +// `hidden` getter — enough surface for the helper (addEventListener, +// removeEventListener, dispatchEvent, document.hidden). +let hidden = false; +let doc: EventTarget & { hidden: boolean }; +let win: EventTarget; +const setHidden = (v: boolean) => { + hidden = v; +}; +const savedDoc = globalThis.document; +const savedWin = globalThis.window; + +describe("createLivePoll", () => { + beforeEach(() => { + vi.useFakeTimers(); + hidden = false; + doc = new EventTarget() as EventTarget & { hidden: boolean }; + Object.defineProperty(doc, "hidden", { get: () => hidden }); + win = new EventTarget(); + (globalThis as { document: unknown }).document = doc; + (globalThis as { window: unknown }).window = win; + }); + afterEach(() => { + vi.useRealTimers(); + vi.restoreAllMocks(); + (globalThis as { document: unknown }).document = savedDoc; + (globalThis as { window: unknown }).window = savedWin; + }); + + it("polls on the interval while visible", () => { + const refetch = vi.fn(); + createRoot((dispose) => { + createLivePoll(refetch, 1000); + expect(refetch).not.toHaveBeenCalled(); // no immediate call — resource already loaded + vi.advanceTimersByTime(3000); + expect(refetch).toHaveBeenCalledTimes(3); + dispose(); + }); + }); + + it("does not start the interval when the tab is hidden on mount", () => { + setHidden(true); + const refetch = vi.fn(); + createRoot((dispose) => { + createLivePoll(refetch, 1000); + vi.advanceTimersByTime(5000); + expect(refetch).not.toHaveBeenCalled(); + dispose(); + }); + }); + + it("refetches once on tab-back and resumes polling", () => { + const refetch = vi.fn(); + createRoot((dispose) => { + createLivePoll(refetch, 1000); + setHidden(true); + doc.dispatchEvent(new Event("visibilitychange")); + vi.advanceTimersByTime(5000); + expect(refetch).toHaveBeenCalledTimes(0); // no polls while hidden + setHidden(false); + doc.dispatchEvent(new Event("visibilitychange")); + expect(refetch).toHaveBeenCalledTimes(1); // immediate catch-up + vi.advanceTimersByTime(2000); + expect(refetch).toHaveBeenCalledTimes(3); // polling resumed + dispose(); + }); + }); + + it("collapses a visibilitychange+focus double-fire into one refetch", () => { + const refetch = vi.fn(); + createRoot((dispose) => { + createLivePoll(refetch, 10_000); + setHidden(true); + doc.dispatchEvent(new Event("visibilitychange")); + setHidden(false); + doc.dispatchEvent(new Event("visibilitychange")); + win.dispatchEvent(new Event("focus")); + expect(refetch).toHaveBeenCalledTimes(1); // 1s guard swallows the second wake + dispose(); + }); + }); + + it("stops polling after dispose", () => { + const refetch = vi.fn(); + createRoot((dispose) => { + createLivePoll(refetch, 1000); + dispose(); + }); + vi.advanceTimersByTime(5000); + expect(refetch).not.toHaveBeenCalled(); + }); +}); diff --git a/src/lib/create-live-poll.ts b/src/lib/create-live-poll.ts new file mode 100644 index 0000000..899d40e --- /dev/null +++ b/src/lib/create-live-poll.ts @@ -0,0 +1,54 @@ +import { onCleanup } from "solid-js"; + +/** + * Visibility-aware polling primitive. Call inside a component/owner scope. + * + * Why this exists: a plain `setInterval(refetch, ms)` keeps firing in hidden + * tabs (wasted GETs) and never catches up when the user returns — so state + * changed by *another* actor (e.g. a teacher approving a student's appointment) + * shows up to one full interval stale on a parked tab. This runs the interval + * only while the tab is visible, and refetches immediately when the tab becomes + * visible or the window regains focus, so tab-back is instant-fresh. + * + * Pair with `resource.latest` reads (see AGENTS.md #6): a refetch never + * re-suspends, so the poll can't blank a shell that sits beside . + * + * @param refetch called on each visible tick and on visibility/focus wake. + * @param intervalMs poll period while visible (default 30s). + */ +export function createLivePoll(refetch: () => unknown, intervalMs = 30_000): void { + let timer: ReturnType | undefined; + let lastRun = 0; + const run = () => { + lastRun = Date.now(); + void refetch(); + }; + const start = () => { + if (!timer) timer = setInterval(run, intervalMs); + }; + const stop = () => { + if (timer) { + clearInterval(timer); + timer = undefined; + } + }; + // visibilitychange (tab switch) and window focus can both fire on tab-back; + // the 1s guard collapses that into a single refetch. + const wake = () => { + if (document.hidden) { + stop(); + return; + } + if (Date.now() - lastRun > 1_000) run(); + start(); + }; + + if (!document.hidden) start(); + document.addEventListener("visibilitychange", wake); + window.addEventListener("focus", wake); + onCleanup(() => { + stop(); + document.removeEventListener("visibilitychange", wake); + window.removeEventListener("focus", wake); + }); +} diff --git a/src/pages/appointments-page.tsx b/src/pages/appointments-page.tsx index 10ba892..ffadfdd 100644 --- a/src/pages/appointments-page.tsx +++ b/src/pages/appointments-page.tsx @@ -1,4 +1,4 @@ -import { Show, createMemo, createResource, createSignal, onCleanup } from "solid-js"; +import { Show, createMemo, createResource, createSignal } from "solid-js"; import type { ColumnDef } from "@tanstack/solid-table"; import { deleteSlotById, @@ -15,6 +15,7 @@ import { postSlots, } from "@/api/appointments"; import { APPOINTMENT_LIMITS, formatApiError } from "@/api/client"; +import { createLivePoll } from "@/lib/create-live-poll"; import type { Appointment, AppointmentSlot, AppointmentStatus } from "@/api/client"; import type { MessageKey } from "@/i18n/messages"; import { BookAppointmentForm } from "@/components/appointments/book-appointment-form"; @@ -75,9 +76,10 @@ function AppointmentsContent() { const loaded = () => slots.latest !== undefined && appts.latest !== undefined; // Poll so statuses stay in sync when the other party acts (approve, book, - // cancel…). Reads use `.latest`, so a refetch never re-suspends/blanks the tables. - const poll = setInterval(() => void refetchAll(), 30_000); - onCleanup(() => clearInterval(poll)); + // cancel…). Visibility-aware: pauses on hidden tabs, refetches on tab-back so + // a cross-actor status change isn't stale on a parked tab. Reads use `.latest`, + // so a refetch never re-suspends/blanks the tables. + createLivePoll(refetchAll, 10_000); const act = async (fn: () => Promise, successKey?: MessageKey) => { setError(""); try { diff --git a/src/stores/shell-feed-context.tsx b/src/stores/shell-feed-context.tsx new file mode 100644 index 0000000..8ca8963 --- /dev/null +++ b/src/stores/shell-feed-context.tsx @@ -0,0 +1,153 @@ +import { + type Accessor, + type ParentProps, + createContext, + createResource, + createSignal, + useContext, +} from "solid-js"; +import { getEvents } from "@/api/events"; +import { getExams } from "@/api/exams"; +import { getHomework } from "@/api/homework"; +import { getAppointments } from "@/api/appointments"; +import { getMessages } from "@/api/messages"; +import type { Appointment, Event, Exam, Homework, Message, Page } from "@/api/client"; +import { createLivePoll } from "@/lib/create-live-poll"; +import { useAuth } from "@/stores/auth-context"; + +// One shared poller for the always-mounted shell (NotificationCenter header + +// RightNav sidebar). Both used to `createResource` messages/events/exams +// independently — ~8 GETs/min. This fetches the widest form of each source +// ONCE; both consumers derive their own views locally. +// +// Every accessor returns `resource.latest`, not `resource()`: these feed +// always-rendered badges/counts OUTSIDE any (beside ). A +// bare read re-suspends on every 60s refetch and blanks the whole page for the +// fetch duration (AGENTS.md #6). `.latest` + `initialValue` never suspends. + +type ShellFeedContextValue = { + messages: Accessor>; + events: Accessor>; + exams: Accessor>; + appointments: Accessor>; + homework: Accessor>; + nowMs: Accessor; + refetchMessages: () => void; + refetchEvents: () => void; + refetchExams: () => void; + refetchAppointments: () => void; + refetchHomework: () => void; + refreshAll: () => void; +}; + +const ShellFeedContext = createContext(); + +const emptyPage = (): Page => ({ items: [], total: 0, limit: null, offset: 0 }); + +export function ShellFeedProvider(props: ParentProps) { + const auth = useAuth(); + // Only fetch for a logged-in user: source is falsy while logged out, so the + // resource keeps its seeded empty value and never hits the network. + const source = () => !!auth.user(); + + const [messagesRes, { refetch: refetchMessages }] = createResource( + source, + async () => { + try { + return await getMessages("inbox", { limit: 100 }); + } catch { + return emptyPage(); + } + }, + { initialValue: emptyPage() } + ); + + const [eventsRes, { refetch: refetchEvents }] = createResource( + source, + async () => { + try { + return await getEvents({ limit: 100 }); + } catch { + return emptyPage(); + } + }, + { initialValue: emptyPage() } + ); + + const [examsRes, { refetch: refetchExams }] = createResource( + source, + async () => { + try { + return await getExams({ limit: 100 }); + } catch { + return emptyPage(); + } + }, + { initialValue: emptyPage() } + ); + + const [appointmentsRes, { refetch: refetchAppointments }] = createResource( + source, + async () => { + try { + return await getAppointments({ limit: 100 }); + } catch { + return emptyPage(); + } + }, + { initialValue: emptyPage() } + ); + + const [homeworkRes, { refetch: refetchHomework }] = createResource( + source, + async () => { + try { + return await getHomework(); + } catch { + return emptyPage(); + } + }, + { initialValue: emptyPage() } + ); + + const refreshAll = () => { + void refetchMessages(); + void refetchEvents(); + void refetchExams(); + void refetchAppointments(); + void refetchHomework(); + }; + + // Reactive clock so passed items drop off without a remount. Visibility-aware: + // no ticks/GETs while the tab is hidden, refetch on tab-back so nothing is + // stale on a parked tab. This is the single shell poller. + const [nowMs, setNowMs] = createSignal(Date.now()); + createLivePoll(() => { + if (!auth.user()) return; + setNowMs(Date.now()); + refreshAll(); + }, 60_000); + + const value: ShellFeedContextValue = { + messages: () => messagesRes.latest, + events: () => eventsRes.latest, + exams: () => examsRes.latest, + appointments: () => appointmentsRes.latest, + homework: () => homeworkRes.latest, + nowMs, + refetchMessages: () => void refetchMessages(), + refetchEvents: () => void refetchEvents(), + refetchExams: () => void refetchExams(), + refetchAppointments: () => void refetchAppointments(), + refetchHomework: () => void refetchHomework(), + refreshAll, + }; + + return {props.children}; +} + +export function useShellFeed(): ShellFeedContextValue { + const ctx = useContext(ShellFeedContext); + if (!ctx) throw new Error("useShellFeed must be used within ShellFeedProvider"); + return ctx; +}