⚡ visibility-aware polling and deduped shell feed
Browse files at this commite70073f2ba61053e978eb23f58400e5cfdff066eParent: 60e4910- perf
- ⚡ visibility-aware polling and deduped shell feed
7 changed files +349 -146
- src/components/layout/app-shell.tsx +3 -0
- src/components/layout/notification-center.tsx +18 -68
- src/components/layout/right-nav.tsx +19 -74
- src/lib/create-live-poll.test.ts +96 -0
- src/lib/create-live-poll.ts +54 -0
- src/pages/appointments-page.tsx +6 -4
- src/stores/shell-feed-context.tsx +153 -0
src/components/layout/app-shell.tsxmodified+3 -0
| @@ -13,6 +13,7 @@ import { Button } from "@/components/ui/button"; | |||
| 13 | import { IconBotSquare, IconPanelLeft, IconSearch, IconX } from "@/components/ui/icons"; | 13 | import { IconBotSquare, IconPanelLeft, IconSearch, IconX } from "@/components/ui/icons"; |
| 14 | import { Toaster } from "@/components/ui/toast"; | 14 | import { Toaster } from "@/components/ui/toast"; |
| 15 | import { useAuth } from "@/stores/auth-context"; | 15 | import { useAuth } from "@/stores/auth-context"; |
| 16 | +import { ShellFeedProvider } from "@/stores/shell-feed-context"; | ||
| 16 | import { usePreferences, useT } from "@/stores/preferences-context"; | 17 | import { usePreferences, useT } from "@/stores/preferences-context"; |
| 17 | import { cn } from "@/lib/cn"; | 18 | import { cn } from "@/lib/cn"; |
| 18 | 19 | ||
| @@ -71,6 +72,7 @@ export function AppShell(props: ParentProps) { | |||
| 71 | <Show when={!auth.user()}> | 72 | <Show when={!auth.user()}> |
| 72 | <NavBar /> | 73 | <NavBar /> |
| 73 | </Show> | 74 | </Show> |
| 75 | + <ShellFeedProvider> | ||
| 74 | <div class="flex w-full"> | 76 | <div class="flex w-full"> |
| 75 | <Show when={auth.user() && !fullScreen()}> | 77 | <Show when={auth.user() && !fullScreen()}> |
| 76 | <aside | 78 | <aside |
| @@ -201,6 +203,7 @@ export function AppShell(props: ParentProps) { | |||
| 201 | <RightNav /> | 203 | <RightNav /> |
| 202 | </Show> | 204 | </Show> |
| 203 | </div> | 205 | </div> |
| 206 | + </ShellFeedProvider> | ||
| 204 | <Show when={auth.user() && !wide()}> | 207 | <Show when={auth.user() && !wide()}> |
| 205 | <MobileTabBar onMenu={() => setMobileOpen(true)} /> | 208 | <MobileTabBar onMenu={() => setMobileOpen(true)} /> |
| 206 | </Show> | 209 | </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"; |
| 2 | import { useNavigate } from "@tanstack/solid-router"; | 2 | import { useNavigate } from "@tanstack/solid-router"; |
| 3 | -import { getEvents } from "@/api/events"; | 3 | +import { patchMessageById } from "@/api/messages"; |
| 4 | -import { getExams } from "@/api/exams"; | ||
| 5 | -import { getHomework } from "@/api/homework"; | ||
| 6 | -import { getMessages, patchMessageById } from "@/api/messages"; | ||
| 7 | import { Button } from "@/components/ui/button"; | 4 | import { Button } from "@/components/ui/button"; |
| 8 | import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover"; | 5 | import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover"; |
| 9 | import { | 6 | import { |
| @@ -24,71 +21,23 @@ import { | |||
| 24 | type NotificationItem, | 21 | type NotificationItem, |
| 25 | } from "@/lib/notifications"; | 22 | } from "@/lib/notifications"; |
| 26 | import { useT } from "@/stores/preferences-context"; | 23 | import { useT } from "@/stores/preferences-context"; |
| 24 | +import { useShellFeed } from "@/stores/shell-feed-context"; | ||
| 27 | 25 | ||
| 28 | export function NotificationCenter() { | 26 | export function NotificationCenter() { |
| 29 | const t = useT(); | 27 | const t = useT(); |
| 30 | const navigate = useNavigate(); | 28 | const navigate = useNavigate(); |
| 29 | + const feed = useShellFeed(); | ||
| 31 | const [open, setOpen] = createSignal(false); | 30 | const [open, setOpen] = createSignal(false); |
| 32 | const [dismissedIds, setDismissedIds] = createSignal<Set<string>>(getDismissedNotificationIds()); | 31 | const [dismissedIds, setDismissedIds] = createSignal<Set<string>>(getDismissedNotificationIds()); |
| 33 | 32 | ||
| 34 | - // Fetch data sources. `initialValue` is required: the unread badge reads | 33 | + // Shell feed data comes from the shared poller (ShellFeedProvider): one fetch |
| 35 | - // these via `unreadCount()` OUTSIDE the popover's <Suspense>, so a bare | 34 | + // per source for the whole shell instead of a duplicate set here. Every read |
| 36 | - // `resource()` would re-suspend on every 60s `refreshAll()` refetch and — since | 35 | + // below is `feed.x()` which returns `resource.latest` — non-suspending on the |
| 37 | - // this component sits beside <Outlet> in AppShell — blank the whole page for | 36 | + // 60s refetch, so the unread badge (outside the popover's <Suspense>) never |
| 38 | - // the fetch duration. A seeded value keeps `resource()` non-suspending on | 37 | + // blanks the page beside <Outlet> (AGENTS.md #6). |
| 39 | - // refetch (matches RightNav). | 38 | + const refetchMessages = feed.refetchMessages; |
| 40 | - const [messagesRes, { refetch: refetchMessages }] = createResource( | 39 | + const refreshAll = feed.refreshAll; |
| 41 | - async () => { | 40 | + const nowMs = feed.nowMs; |
| 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)); | ||
| 92 | 41 | ||
| 93 | createEffect(() => { | 42 | createEffect(() => { |
| 94 | if (open()) refreshAll(); | 43 | if (open()) refreshAll(); |
| @@ -101,8 +50,9 @@ export function NotificationCenter() { | |||
| 101 | const allNotifications = createMemo<NotificationItem[]>(() => { | 50 | const allNotifications = createMemo<NotificationItem[]>(() => { |
| 102 | const list: NotificationItem[] = []; | 51 | const list: NotificationItem[] = []; |
| 103 | 52 | ||
| 104 | - // 1. Unread Messages | 53 | + // 1. Unread Messages — shared inbox is the full list, filter to unread here |
| 105 | - const msgs = messagesRes.latest?.items ?? []; | 54 | + // (was a dedicated read:false fetch before the shell feed consolidation). |
| 55 | + const msgs = feed.messages().items.filter((m) => !m.read); | ||
| 106 | for (const m of msgs) { | 56 | for (const m of msgs) { |
| 107 | list.push({ | 57 | list.push({ |
| 108 | id: `msg_${m.id}`, | 58 | id: `msg_${m.id}`, |
| @@ -115,7 +65,7 @@ export function NotificationCenter() { | |||
| 115 | } | 65 | } |
| 116 | 66 | ||
| 117 | // 2. Events starting today or upcoming | 67 | // 2. Events starting today or upcoming |
| 118 | - const evts = eventsRes.latest?.items ?? []; | 68 | + const evts = feed.events().items; |
| 119 | for (const e of evts) { | 69 | for (const e of evts) { |
| 120 | if (!e.starts_at) continue; | 70 | if (!e.starts_at) continue; |
| 121 | const t = new Date(e.starts_at).getTime(); | 71 | const t = new Date(e.starts_at).getTime(); |
| @@ -139,7 +89,7 @@ export function NotificationCenter() { | |||
| 139 | } | 89 | } |
| 140 | 90 | ||
| 141 | // 3. Exams starting today or upcoming | 91 | // 3. Exams starting today or upcoming |
| 142 | - const exms = examsRes.latest?.items ?? []; | 92 | + const exms = feed.exams().items; |
| 143 | for (const ex of exms) { | 93 | for (const ex of exms) { |
| 144 | if (!ex.starts_at || ex.draft) continue; | 94 | if (!ex.starts_at || ex.draft) continue; |
| 145 | const t = new Date(ex.starts_at).getTime(); | 95 | const t = new Date(ex.starts_at).getTime(); |
| @@ -163,7 +113,7 @@ export function NotificationCenter() { | |||
| 163 | } | 113 | } |
| 164 | 114 | ||
| 165 | // 4. Homework due upcoming | 115 | // 4. Homework due upcoming |
| 166 | - const hws = homeworkRes.latest?.items ?? []; | 116 | + const hws = feed.homework().items; |
| 167 | for (const hw of hws) { | 117 | for (const hw of hws) { |
| 168 | if (!hw.due_at) continue; | 118 | if (!hw.due_at) continue; |
| 169 | if (hw.due_at >= nowMs()) { | 119 | 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"; |
| 2 | import { useLocation, useNavigate } from "@tanstack/solid-router"; | 2 | import { useLocation, useNavigate } from "@tanstack/solid-router"; |
| 3 | -import { getEvents } from "@/api/events"; | 3 | +import { patchMessageById } from "@/api/messages"; |
| 4 | -import { getExams } from "@/api/exams"; | ||
| 5 | -import { getAppointments } from "@/api/appointments"; | ||
| 6 | -import { getMessages, patchMessageById } from "@/api/messages"; | ||
| 7 | import type { Appointment, Event, Exam, Message } from "@/api/client"; | 4 | import type { Appointment, Event, Exam, Message } from "@/api/client"; |
| 8 | import { appointmentStatusClass, appointmentStatusDotClass, appointmentStatusLabelKey } from "@/lib/appointment-status"; | 5 | import { appointmentStatusClass, appointmentStatusDotClass, appointmentStatusLabelKey } from "@/lib/appointment-status"; |
| 9 | import { Badge } from "@/components/ui/badge"; | 6 | import { Badge } from "@/components/ui/badge"; |
| @@ -22,6 +19,7 @@ import { | |||
| 22 | import { cn } from "@/lib/cn"; | 19 | import { cn } from "@/lib/cn"; |
| 23 | import { personLabel } from "@/lib/person"; | 20 | import { personLabel } from "@/lib/person"; |
| 24 | import { usePreferences, useT } from "@/stores/preferences-context"; | 21 | import { usePreferences, useT } from "@/stores/preferences-context"; |
| 22 | +import { useShellFeed } from "@/stores/shell-feed-context"; | ||
| 25 | 23 | ||
| 26 | type ActiveTab = "messages" | "calendar" | null; | 24 | type ActiveTab = "messages" | "calendar" | null; |
| 27 | type CalendarItemRef = | 25 | type CalendarItemRef = |
| @@ -36,6 +34,7 @@ export function RightNav() { | |||
| 36 | const navigate = useNavigate(); | 34 | const navigate = useNavigate(); |
| 37 | const location = useLocation(); | 35 | const location = useLocation(); |
| 38 | const { locale } = usePreferences(); | 36 | const { locale } = usePreferences(); |
| 37 | + const feed = useShellFeed(); | ||
| 39 | 38 | ||
| 40 | const isMessagesActive = () => location().pathname === "/messages"; | 39 | const isMessagesActive = () => location().pathname === "/messages"; |
| 41 | const isCalendarActive = () => location().pathname === "/calendar"; | 40 | const isCalendarActive = () => location().pathname === "/calendar"; |
| @@ -52,67 +51,18 @@ export function RightNav() { | |||
| 52 | const [calFilter, setCalFilter] = createSignal<"all" | "events" | "exams" | "appointments">("all"); | 51 | const [calFilter, setCalFilter] = createSignal<"all" | "events" | "exams" | "appointments">("all"); |
| 53 | const [selectedCalItem, setSelectedCalItem] = createSignal<CalendarItemRef | null>(null); | 52 | const [selectedCalItem, setSelectedCalItem] = createSignal<CalendarItemRef | null>(null); |
| 54 | 53 | ||
| 55 | - // Fetch inbox messages | 54 | + // Shell feed data comes from the shared poller (ShellFeedProvider), so |
| 56 | - const [messagesRes, { refetch: refetchMessages }] = createResource( | 55 | + // messages/events/exams/appointments are fetched once for the whole shell, |
| 57 | - async () => { | 56 | + // not independently here and in NotificationCenter. |
| 58 | - try { | 57 | + const refetchMessages = feed.refetchMessages; |
| 59 | - return await getMessages("inbox", { limit: 100 }); | 58 | + const refreshAll = feed.refreshAll; |
| 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 | - }; | ||
| 109 | 59 | ||
| 110 | // Computed message data | 60 | // Computed message data |
| 111 | - // `.latest`, not `messagesRes()`: this feeds the always-rendered unread badge, | 61 | + // `.latest` (via the store accessor), not a bare `resource()`: this feeds the |
| 112 | - // which is outside any <Suspense>. A bare read re-suspends on every 60s refetch | 62 | + // always-rendered unread badge outside any <Suspense>. A bare read re-suspends |
| 113 | - // and — since RightNav sits beside <Outlet> in AppShell — blanks the whole page | 63 | + // on every 60s refetch and — since RightNav sits beside <Outlet> in AppShell — |
| 114 | - // for the fetch duration. `.latest` keeps the last value without suspending. | 64 | + // blanks the whole page for the fetch duration. `.latest` keeps the last value. |
| 115 | - const allMessages = () => messagesRes.latest.items; | 65 | + const allMessages = () => feed.messages().items; |
| 116 | const unreadCount = createMemo(() => allMessages().filter((m: Message) => !m.read).length); | 66 | const unreadCount = createMemo(() => allMessages().filter((m: Message) => !m.read).length); |
| 117 | 67 | ||
| 118 | const filteredMessages = createMemo(() => { | 68 | const filteredMessages = createMemo(() => { |
| @@ -128,13 +78,8 @@ export function RightNav() { | |||
| 128 | return filteredMessages().slice(0, 5); | 78 | return filteredMessages().slice(0, 5); |
| 129 | }); | 79 | }); |
| 130 | 80 | ||
| 131 | - // Reactive clock so passed items clear without a remount. | 81 | + // Reactive clock from the shared poller so passed items clear without a remount. |
| 132 | - const [nowMs, setNowMs] = createSignal(Date.now()); | 82 | + const nowMs = feed.nowMs; |
| 133 | - const clockTimer = setInterval(() => { | ||
| 134 | - setNowMs(Date.now()); | ||
| 135 | - refreshAll(); | ||
| 136 | - }, 60_000); | ||
| 137 | - onCleanup(() => clearInterval(clockTimer)); | ||
| 138 | 83 | ||
| 139 | createEffect(() => { | 84 | createEffect(() => { |
| 140 | if (activeTab() !== null) refreshAll(); | 85 | if (activeTab() !== null) refreshAll(); |
| @@ -148,15 +93,15 @@ export function RightNav() { | |||
| 148 | }; | 93 | }; |
| 149 | 94 | ||
| 150 | const activeEvents = createMemo(() => { | 95 | 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)); |
| 152 | }); | 97 | }); |
| 153 | 98 | ||
| 154 | const activeExams = createMemo(() => { | 99 | 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)); |
| 156 | }); | 101 | }); |
| 157 | 102 | ||
| 158 | const activeAppointments = createMemo(() => { | 103 | const activeAppointments = createMemo(() => { |
| 159 | - return appointmentsRes.latest.filter( | 104 | + return feed.appointments().items.filter( |
| 160 | (a: Appointment) => (a.status === "pending" || a.status === "approved") && notEnded(a.starts_at, a.ends_at) | 105 | (a: Appointment) => (a.status === "pending" || a.status === "approved") && notEnded(a.starts_at, a.ends_at) |
| 161 | ); | 106 | ); |
| 162 | }); | 107 | }); |
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"; |
| 2 | import type { ColumnDef } from "@tanstack/solid-table"; | 2 | import type { ColumnDef } from "@tanstack/solid-table"; |
| 3 | import { | 3 | import { |
| 4 | deleteSlotById, | 4 | deleteSlotById, |
| @@ -15,6 +15,7 @@ import { | |||
| 15 | postSlots, | 15 | postSlots, |
| 16 | } from "@/api/appointments"; | 16 | } from "@/api/appointments"; |
| 17 | import { APPOINTMENT_LIMITS, formatApiError } from "@/api/client"; | 17 | import { APPOINTMENT_LIMITS, formatApiError } from "@/api/client"; |
| 18 | +import { createLivePoll } from "@/lib/create-live-poll"; | ||
| 18 | import type { Appointment, AppointmentSlot, AppointmentStatus } from "@/api/client"; | 19 | import type { Appointment, AppointmentSlot, AppointmentStatus } from "@/api/client"; |
| 19 | import type { MessageKey } from "@/i18n/messages"; | 20 | import type { MessageKey } from "@/i18n/messages"; |
| 20 | import { BookAppointmentForm } from "@/components/appointments/book-appointment-form"; | 21 | import { BookAppointmentForm } from "@/components/appointments/book-appointment-form"; |
| @@ -75,9 +76,10 @@ function AppointmentsContent() { | |||
| 75 | const loaded = () => slots.latest !== undefined && appts.latest !== undefined; | 76 | const loaded = () => slots.latest !== undefined && appts.latest !== undefined; |
| 76 | 77 | ||
| 77 | // Poll so statuses stay in sync when the other party acts (approve, book, | 78 | // 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 | + // cancel…). Visibility-aware: pauses on hidden tabs, refetches on tab-back so |
| 79 | - const poll = setInterval(() => void refetchAll(), 30_000); | 80 | + // a cross-actor status change isn't stale on a parked tab. Reads use `.latest`, |
| 80 | - onCleanup(() => clearInterval(poll)); | 81 | + // so a refetch never re-suspends/blanks the tables. |
| 82 | + createLivePoll(refetchAll, 10_000); | ||
| 81 | const act = async (fn: () => Promise<unknown>, successKey?: MessageKey) => { | 83 | const act = async (fn: () => Promise<unknown>, successKey?: MessageKey) => { |
| 82 | setError(""); | 84 | setError(""); |
| 83 | try { | 85 | 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 | +} | ||