forge
Explore
Log in

Don't you dare go Hollow

🚀 load on sight, share the school walk, page client tables

Browse files at this commit

48313a507f62a0af9ca7b5ff6abbc288ee9a80b6Burak BoduroğluParent: f04b93a
  • perf
    • 🚀 load on sight, share the school walk, page client tables
Show full message
perf: 🚀 load on sight, share the school walk, page client tables
- insights read the first 50 students' signals, then more as the table
  scrolls or a signal filter/sort needs them; overview cards state their
  coverage while partial (212 → ~62 requests on open)
- dashboard caps the trend at six exams and loads the chart, class sizes
  and below-fold panels when they come into view
- studio shows its library at once and reads a note's outputs when its
  row is visible; staff-work and payments fetch row values on sight
- class members and section walks are a shared five-minute per-tab
  cache, invalidated after class, member and section writes
- tables and lists that are not fetched as you scroll page with numbers
  again (DataTable client mode, event roll call, studio library)

36 changed files +1328 -378

.claude/skills/ui-conventions/SKILL.mdmodified+1 -1
@@ -49,7 +49,7 @@ Active project reference docs (read the relevant one before changing that area):
49 - Actions columns stay fixed at `w-[110px] min-w-[110px] max-w-[110px] h-[45px] text-center whitespace-nowrap` to prevent localized headers like `"İŞLEMLER"` from changing their size.49 - Actions columns stay fixed at `w-[110px] min-w-[110px] max-w-[110px] h-[45px] text-center whitespace-nowrap` to prevent localized headers like `"İŞLEMLER"` from changing their size.
50 - Table-page headers fold into the `DataTable` title/description/actions area; do not render a separate `PageHeader` above table-primary pages.50 - Table-page headers fold into the `DataTable` title/description/actions area; do not render a separate `PageHeader` above table-primary pages.
51 - Every list toolbar is one card (`TOOLBAR_CARD`), even when "Sütunlar" is its only control; its controls follow the pill standard above.51 - Every list toolbar is one card (`TOOLBAR_CARD`), even when "Sütunlar" is its only control; its controls follow the pill standard above.
52-- Lists have no page numbers: server lists fetch as you scroll (`createInfiniteList` + DataTable `infinite`, or `InfiniteSentinel` for card lists), only when the backend applies every filter the list offers (sorting is off there); client tables reveal 50 rows at a time. Back from a detail page restores rows and scroll (`restoreKey`, `createScrollRestore`).52+- Server lists fetch as you scroll (`createInfiniteList` + DataTable `infinite`, or `InfiniteSentinel` for card lists) only when the backend applies every filter the list offers (sorting is off there). Client tables use page numbers through `TablePagination`. Back from a detail page restores the page and scroll (`urlState`, `createScrollRestore`).
53 - Pages/domain components must not import or render `Table` primitives directly; only the `DataTable` wrapper and table primitive files may.53 - Pages/domain components must not import or render `Table` primitives directly; only the `DataTable` wrapper and table primitive files may.
54 - Every list page uses one card: optional `Tabs` above, then `section.data-shell` holding the `DataTable` (its `title`/`description`/`actions`). Card-grid lists use `DataSection` from `src/components/ui/data-section.tsx` for the same header. No standalone `PageHeader`/`h1` above a list, and no row counts in descriptions (the pager shows them).54 - Every list page uses one card: optional `Tabs` above, then `section.data-shell` holding the `DataTable` (its `title`/`description`/`actions`). Card-grid lists use `DataSection` from `src/components/ui/data-section.tsx` for the same header. No standalone `PageHeader`/`h1` above a list, and no row counts in descriptions (the pager shows them).
55 55
docs/ui/ui-redesign-tokens.mdmodified+2 -2
@@ -93,8 +93,8 @@ display-font, translucent surface, or custom shadow rules.
93 `src/components/ui/data-toolbar.tsx`). Every list toolbar is one card.93 `src/components/ui/data-toolbar.tsx`). Every list toolbar is one card.
94 - Filled buttons carry a transparent border with `bg-clip-padding`, so they94 - Filled buttons carry a transparent border with `bg-clip-padding`, so they
95 match an outlined pill's height; a border never matches its fill colour.95 match an outlined pill's height; a border never matches its fill colour.
96-- No page numbers: server lists fetch as you scroll (`createInfiniteList` +96+- Server lists fetch as you scroll (`createInfiniteList` + `infinite`);
97- `infinite`), client lists reveal 50 rows at a time. Empty cells show `—`.97+ client tables use page numbers. Empty cells show `—`.
98 - `storageKey` remains optional. When provided, only column visibility persists98 - `storageKey` remains optional. When provided, only column visibility persists
99 under `hezarfen.table.<storageKey>`.99 under `hezarfen.table.<storageKey>`.
100 - Application tables use `DataTable`; page/domain components do not render table100 - Application tables use `DataTable`; page/domain components do not render table
src/components/ai/insights-board.test.tsxadded+49 -0
@@ -0,0 +1,49 @@
1+import { cleanup, fireEvent, render, screen, waitFor } from "@solidjs/testing-library";
2+import { afterEach, expect, it, vi } from "vitest";
3+import { InsightsBoard } from "./insights-board";
4+import { clearStudentSignalCache } from "@/lib/insight-students";
5+
6+const api = vi.hoisted(() => ({
7+ getMyStudents: vi.fn(),
8+ getInsightByUserId: vi.fn(),
9+}));
10+
11+vi.mock("@/api/parents", () => ({ getMyStudents: api.getMyStudents }));
12+vi.mock("@/api/insights", () => ({
13+ getInsightByUserId: api.getInsightByUserId,
14+ getMyInsight: vi.fn(),
15+ getInsightRuns: vi.fn(),
16+ postInsightsRefresh: vi.fn(),
17+}));
18+vi.mock("@/stores/auth-context", () => ({
19+ useAuth: () => ({ user: () => ({ id: "insights-board-viewer", role: "parent" }) }),
20+}));
21+vi.mock("@/stores/preferences-context", () => ({
22+ usePreferences: () => ({ t: (key: string) => key, locale: () => "en" }),
23+}));
24+vi.mock("@/components/ui/data-table", () => ({ DataTableSkeleton: () => null }));
25+vi.mock("@/components/insights/insight-overview", () => ({ InsightOverview: () => null }));
26+vi.mock("@/components/insights/insight-students-table", () => ({
27+ InsightStudentsTable: (props: { onNeedMore: () => void }) => (
28+ <button type="button" onClick={props.onNeedMore}>Load next rows</button>
29+ ),
30+}));
31+
32+afterEach(() => {
33+ cleanup();
34+ clearStudentSignalCache("insights-board-viewer");
35+ vi.clearAllMocks();
36+});
37+
38+it("reads only the first 50 student insights until more rows are requested", async () => {
39+ api.getMyStudents.mockResolvedValue({ items: Array.from({ length: 200 }, (_, index) => ({
40+ id: `student-${index}`, username: `student-${index}`, display_name: `Student ${index}`,
41+ })) });
42+ api.getInsightByUserId.mockImplementation(async (id: string) => ({
43+ user_id: id, summary: null, attention: [], cards: [], segments: [],
44+ }));
45+ render(() => <InsightsBoard />);
46+ await waitFor(() => expect(api.getInsightByUserId).toHaveBeenCalledTimes(50));
47+ fireEvent.click(screen.getByRole("button", { name: "Load next rows" }));
48+ await waitFor(() => expect(api.getInsightByUserId).toHaveBeenCalledTimes(100));
49+});
src/components/ai/insights-board.tsxmodified+28 -5
@@ -14,7 +14,7 @@ import { IconSparkles } from "@/components/ui/icons";
14 import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";14 import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
15 import { createFlash } from "@/lib/flash";15 import { createFlash } from "@/lib/flash";
16 import { toStudentSignal, type StudentSignal } from "@/lib/insight-run-report";16 import { toStudentSignal, type StudentSignal } from "@/lib/insight-run-report";
17-import { insightOverview, loadInsightStudents, loadStudentSignals } from "@/lib/insight-students";17+import { cachedStudentSignal, clearStudentSignalCache, insightOverview, loadInsightStudents, loadStudentSignals } from "@/lib/insight-students";
18 import { personLabel } from "@/lib/person";18 import { personLabel } from "@/lib/person";
19 import { hasMinRole } from "@/lib/roles";19 import { hasMinRole } from "@/lib/roles";
20 import { useAuth } from "@/stores/auth-context";20 import { useAuth } from "@/stores/auth-context";
@@ -52,14 +52,33 @@ export function InsightsBoard() {
52 // Each student's analysis lands in its row as it is read; rows start as52 // Each student's analysis lands in its row as it is read; rows start as
53 // "not loaded" so the table and the overview never show a guessed value.53 // "not loaded" so the table and the overview never show a guessed value.
54 const [signals, setSignals] = createSignal<Record<string, StudentSignal>>({});54 const [signals, setSignals] = createSignal<Record<string, StudentSignal>>({});
55+ const [requestedCount, setRequestedCount] = createSignal(0);
55 let readGeneration = 0;56 let readGeneration = 0;
57+ let requestThrough = (_count: number) => {};
56 createEffect(on(() => students.latest, (list) => {58 createEffect(on(() => students.latest, (list) => {
57 if (!list) return;59 if (!list) return;
58 const generation = ++readGeneration;60 const generation = ++readGeneration;
59- setSignals(Object.fromEntries(list.map((person) => [person.id, toStudentSignal({ id: person.id, name: personLabel(person) }, null, null)])));61+ const scope = auth.user()?.id ?? "";
60- void loadStudentSignals(list, (row) => {62+ let queued = 0;
61- if (generation === readGeneration) setSignals((current) => ({ ...current, [row.id]: row }));63+ let reads = Promise.resolve();
62- });64+ setSignals(Object.fromEntries(list.map((person) => [person.id,
65+ cachedStudentSignal(person, scope) ?? toStudentSignal({ id: person.id, name: personLabel(person) }, null, null),
66+ ])));
67+ setRequestedCount(Math.min(50, list.length));
68+ requestThrough = (count) => {
69+ const end = Math.min(count, list.length);
70+ if (end <= queued) return;
71+ const batch = list.slice(queued, end);
72+ queued = end;
73+ setRequestedCount(end);
74+ reads = reads.then(() => {
75+ if (generation !== readGeneration) return;
76+ return loadStudentSignals(batch, (row) => {
77+ if (generation === readGeneration) setSignals((current) => ({ ...current, [row.id]: row }));
78+ }, undefined, scope);
79+ });
80+ };
81+ requestThrough(50);
63 }));82 }));
64 const rows = createMemo(() => Object.values(signals()));83 const rows = createMemo(() => Object.values(signals()));
65 const overview = createMemo(() => insightOverview(rows(), students.latest?.length ?? 0));84 const overview = createMemo(() => insightOverview(rows(), students.latest?.length ?? 0));
@@ -70,6 +89,7 @@ export function InsightsBoard() {
70 setPageError("");89 setPageError("");
71 try {90 try {
72 await postInsightsRefresh();91 await postInsightsRefresh();
92+ clearStudentSignalCache(auth.user()?.id ?? "");
73 flash(tx("insights.refreshQueued"));93 flash(tx("insights.refreshQueued"));
74 await refetchRuns();94 await refetchRuns();
75 } catch (error) {95 } catch (error) {
@@ -92,6 +112,9 @@ export function InsightsBoard() {
92 <section>112 <section>
93 <InsightStudentsTable113 <InsightStudentsTable
94 rows={rows()}114 rows={rows()}
115+ hasMore={requestedCount() < (students.latest?.length ?? 0)}
116+ onNeedMore={() => requestThrough(requestedCount() + 50)}
117+ onInspectAll={() => requestThrough(students.latest?.length ?? 0)}
95 title={tx("insights.title")}118 title={tx("insights.title")}
96 description={role() === "parent" ? tx("insights.parentSubtitle") : tx("insights.subtitle")}119 description={role() === "parent" ? tx("insights.parentSubtitle") : tx("insights.subtitle")}
97 empty={role() === "parent" ? tx("insights.emptyLinkedStudents") : tx("insights.emptyStudents")}120 empty={role() === "parent" ? tx("insights.emptyLinkedStudents") : tx("insights.emptyStudents")}
src/components/ai/note-studio-panel.test.tsxadded+50 -0
@@ -0,0 +1,50 @@
1+import { beforeEach, describe, expect, it, vi } from "vitest";
2+import { getCachedStudioNotes, loadStudioNotes } from "@/components/ai/note-studio-panel";
3+
4+const coursesApi = vi.hoisted(() => ({ getCourses: vi.fn() }));
5+const notesApi = vi.hoisted(() => ({ getCourseNotes: vi.fn() }));
6+
7+vi.mock("@/api/courses", () => coursesApi);
8+vi.mock("@/api/course-notes", async (importOriginal) => ({
9+ ...await importOriginal<typeof import("@/api/course-notes")>(),
10+ ...notesApi,
11+}));
12+
13+describe("loadStudioNotes", () => {
14+ beforeEach(() => vi.clearAllMocks());
15+ it("limits concurrent course note requests and preserves course order", async () => {
16+ const courses = Array.from({ length: 10 }, (_, index) => ({
17+ id: `course-${index}`,
18+ title: `Course ${index}`,
19+ creator: { id: "teacher" },
20+ }));
21+ coursesApi.getCourses.mockResolvedValue({ items: courses });
22+ let active = 0;
23+ let peak = 0;
24+ notesApi.getCourseNotes.mockImplementation(async (courseId: string) => {
25+ active++;
26+ peak = Math.max(peak, active);
27+ await new Promise((resolve) => setTimeout(resolve, courseId === "course-0" ? 5 : 0));
28+ active--;
29+ return { items: [{ id: `note-${courseId}`, title: courseId }] };
30+ });
31+
32+ const notes = await loadStudioNotes();
33+
34+ expect(coursesApi.getCourses).toHaveBeenCalledWith({ limit: 100 });
35+ expect(notesApi.getCourseNotes).toHaveBeenCalledTimes(10);
36+ expect(peak).toBe(4);
37+ expect(notes.map((note) => note.courseTitle)).toEqual(courses.map((course) => course.title));
38+ });
39+
40+ it("reuses the completed course note list within a tab", async () => {
41+ coursesApi.getCourses.mockResolvedValue({ items: [] });
42+ const first = getCachedStudioNotes("cache-test-user");
43+ const second = getCachedStudioNotes("cache-test-user");
44+
45+ expect(first).toBe(second);
46+ await first;
47+ await getCachedStudioNotes("cache-test-user");
48+ expect(coursesApi.getCourses).toHaveBeenCalledTimes(1);
49+ });
50+});
src/components/ai/note-studio-panel.tsxmodified+32 -14
@@ -33,31 +33,48 @@ function readRailWidth(): number {
33 }33 }
34 34
35 type StudioNote = CourseNote & { courseTitle: string; courseCreatorId: string };35 type StudioNote = CourseNote & { courseTitle: string; courseCreatorId: string };
36+const studioNotesCache = new Map<string, Promise<StudioNote[]>>();
36 37
37 /** Every lesson note the account can produce from, with its course. */38 /** Every lesson note the account can produce from, with its course. */
38-async function loadStudioNotes(): Promise<StudioNote[]> {39+export async function loadStudioNotes(): Promise<StudioNote[]> {
39 // GET /courses is already scoped to what the caller teaches or takes.40 // GET /courses is already scoped to what the caller teaches or takes.
40 const courses = await getCourses({ limit: 100 });41 const courses = await getCourses({ limit: 100 });
41- const rows = await Promise.all(42+ const rows: StudioNote[][] = Array.from({ length: courses.items.length }, () => []);
42- courses.items.map(async (course) => {43+ let next = 0;
44+ await Promise.all(Array.from({ length: Math.min(4, courses.items.length) }, async () => {
45+ while (next < courses.items.length) {
46+ const index = next++;
47+ const course = courses.items[index]!;
43 try {48 try {
44 const page = await getCourseNotes(course.id, { limit: 100 });49 const page = await getCourseNotes(course.id, { limit: 100 });
45- return page.items.map<StudioNote>((note) => ({50+ rows[index] = page.items.map<StudioNote>((note) => ({
46 ...note,51 ...note,
47 courseTitle: course.title,52 courseTitle: course.title,
48 courseCreatorId: course.creator.id,53 courseCreatorId: course.creator.id,
49 }));54 }));
50 } catch {55 } catch {
51- return [];56+ rows[index] = [];
52 }57 }
53- }),58+ }
54- );59+ }));
55 return rows.flat();60 return rows.flat();
56 }61 }
57 62
63+export function getCachedStudioNotes(userId: string): Promise<StudioNote[]> {
64+ let pending = studioNotesCache.get(userId);
65+ if (!pending) {
66+ pending = loadStudioNotes().catch((error) => {
67+ studioNotesCache.delete(userId);
68+ throw error;
69+ });
70+ studioNotesCache.set(userId, pending);
71+ }
72+ return pending;
73+}
74+
58 function useStudioNotes() {75 function useStudioNotes() {
59 const auth = useAuth();76 const auth = useAuth();
60- return createResource(() => auth.user()?.role ?? null, () => loadStudioNotes());77+ return createResource(() => auth.user()?.id ?? null, (userId) => userId ? getCachedStudioNotes(userId) : []);
61 }78 }
62 79
63 /**80 /**
@@ -76,6 +93,11 @@ export function NoteStudioPanel() {
76 };93 };
77 94
78 return (95 return (
96+ <div class="w-full space-y-8">
97+ <header class="space-y-1.5">
98+ <h1 class="text-2xl font-semibold tracking-tight text-text-strong">{t("aiHub.tab.studio")}</h1>
99+ <p class="text-sm text-muted-foreground">{t("aiStudio.heading")}</p>
100+ </header>
79 <Suspense fallback={<PageSpinner />}>101 <Suspense fallback={<PageSpinner />}>
80 <Show when={notes.error}>102 <Show when={notes.error}>
81 <ErrorAlert message={formatApiError(notes.error)} onRetry={() => void refetch()} />103 <ErrorAlert message={formatApiError(notes.error)} onRetry={() => void refetch()} />
@@ -88,12 +110,7 @@ export function NoteStudioPanel() {
88 {/* A studio home: a plain title and one line saying what it makes,110 {/* A studio home: a plain title and one line saying what it makes,
89 the way to start on a note, then everything produced so far.111 the way to start on a note, then everything produced so far.
90 Flat hairline cards, no banner and no shadow stack. */}112 Flat hairline cards, no banner and no shadow stack. */}
91- <div class="w-full space-y-8">113+ <div class="space-y-8">
92- <header class="space-y-1.5">
93- <h1 class="text-2xl font-semibold tracking-tight text-text-strong">{t("aiHub.tab.studio")}</h1>
94- <p class="text-sm text-muted-foreground">{t("aiStudio.heading")}</p>
95- </header>
96-
97 <div class="max-w-xl space-y-2">114 <div class="max-w-xl space-y-2">
98 <Label for="sound-studio-note">{t("podcast.source")}</Label>115 <Label for="sound-studio-note">{t("podcast.source")}</Label>
99 <SearchableSelect116 <SearchableSelect
@@ -115,6 +132,7 @@ export function NoteStudioPanel() {
115 </Show>132 </Show>
116 </Show>133 </Show>
117 </Suspense>134 </Suspense>
135+ </div>
118 );136 );
119 }137 }
120 138
src/components/ai/studio-output-library.test.tsxmodified+49 -11
@@ -50,7 +50,24 @@ function summary(noteId: string): RagOutput {
50 }50 }
51 51
52 describe("StudioOutputLibrary", () => {52 describe("StudioOutputLibrary", () => {
53+ let visible: ((noteId: string) => void) | undefined;
53 beforeEach(() => {54 beforeEach(() => {
55+ const observed = new Map<Element, { callback: IntersectionObserverCallback; observer: IntersectionObserver }>();
56+ visible = (noteId) => {
57+ for (const [target, entry] of observed) {
58+ if (noteId === "__sentinel" ? (target as HTMLElement).classList.contains("h-px") : (target as HTMLElement).dataset.noteId === noteId) {
59+ entry.callback([{ target, isIntersecting: true } as IntersectionObserverEntry], entry.observer);
60+ return;
61+ }
62+ }
63+ };
64+ vi.stubGlobal("IntersectionObserver", class {
65+ private callback: IntersectionObserverCallback;
66+ constructor(callback: IntersectionObserverCallback) { this.callback = callback; }
67+ observe(element: Element) { observed.set(element, { callback: this.callback, observer: this as unknown as IntersectionObserver }); }
68+ unobserve(element: Element) { observed.delete(element); }
69+ disconnect() { for (const [element, entry] of observed) if (entry.observer === this) observed.delete(element); }
70+ });
54 localStorage.setItem("hezarfen.locale", "tr");71 localStorage.setItem("hezarfen.locale", "tr");
55 podcastApi.listPodcastJobs.mockResolvedValue(page([72 podcastApi.listPodcastJobs.mockResolvedValue(page([
56 podcast({ job_id: "job-1" }),73 podcast({ job_id: "job-1" }),
@@ -64,6 +81,7 @@ describe("StudioOutputLibrary", () => {
64 81
65 afterEach(() => {82 afterEach(() => {
66 cleanup();83 cleanup();
84+ vi.unstubAllGlobals();
67 localStorage.clear();85 localStorage.clear();
68 vi.clearAllMocks();86 vi.clearAllMocks();
69 });87 });
@@ -80,6 +98,12 @@ describe("StudioOutputLibrary", () => {
80 it("lists one row per produced artifact, newest first, failures included", async () => {98 it("lists one row per produced artifact, newest first, failures included", async () => {
81 renderLibrary();99 renderLibrary();
82 100
101+ await waitFor(() => expect(screen.getByText("Başarısız")).toBeTruthy());
102+ expect(courseNotesApi.getCourseNoteRag).not.toHaveBeenCalled();
103+ visible?.("note-1");
104+ visible?.("note-2");
105+ visible?.("note-3");
106+ await waitFor(() => expect(screen.getByText("Kuvvet")).toBeTruthy());
83 await waitFor(() => expect(screen.getAllByText("Hücre").length).toBe(2));107 await waitFor(() => expect(screen.getAllByText("Hücre").length).toBe(2));
84 // The failed run is part of the history and says so rather than vanishing.108 // The failed run is part of the history and says so rather than vanishing.
85 expect(screen.getByText("Polinomlar")).toBeTruthy();109 expect(screen.getByText("Polinomlar")).toBeTruthy();
@@ -94,12 +118,14 @@ describe("StudioOutputLibrary", () => {
94 it("marks every row of the selected note as current", async () => {118 it("marks every row of the selected note as current", async () => {
95 renderLibrary();119 renderLibrary();
96 120
121+ await waitFor(() => expect(screen.getAllByText("Hücre").length).toBe(3));
122+ visible?.("note-1");
97 await waitFor(() => expect(screen.getAllByText("Hücre").length).toBe(2));123 await waitFor(() => expect(screen.getAllByText("Hücre").length).toBe(2));
98 const current = screen.getAllByRole("button").filter((el) => el.getAttribute("aria-current") === "true");124 const current = screen.getAllByRole("button").filter((el) => el.getAttribute("aria-current") === "true");
99 expect(current.length).toBe(2);125 expect(current.length).toBe(2);
100 });126 });
101 127
102- it("reveals a long history fifty rows at a time", async () => {128+ it("pages a long history twenty rows at a time", async () => {
103 podcastApi.listPodcastJobs.mockResolvedValue(page(129 podcastApi.listPodcastJobs.mockResolvedValue(page(
104 Array.from({ length: 52 }, (_, index) =>130 Array.from({ length: 52 }, (_, index) =>
105 podcast({ job_id: `job-${index}`, source_title: `Bölüm ${index + 1}`, source_id: `other-${index}`, created_at: Date.UTC(2026, 0, 1, index), finished_at: Date.UTC(2026, 0, 1, index) }),131 podcast({ job_id: `job-${index}`, source_title: `Bölüm ${index + 1}`, source_id: `other-${index}`, created_at: Date.UTC(2026, 0, 1, index), finished_at: Date.UTC(2026, 0, 1, index) }),
@@ -108,22 +134,20 @@ describe("StudioOutputLibrary", () => {
108 courseNotesApi.getCourseNoteRag.mockResolvedValue(page([]));134 courseNotesApi.getCourseNoteRag.mockResolvedValue(page([]));
109 renderLibrary();135 renderLibrary();
110 136
111- // Newest first: episode 52 leads, episode 3 closes the first fifty.137+ // Newest first: episode 52 leads, episode 33 closes the first page.
112 await waitFor(() => expect(screen.getByText("Bölüm 52")).toBeTruthy());138 await waitFor(() => expect(screen.getByText("Bölüm 52")).toBeTruthy());
113- expect(screen.getByText("Bölüm 3")).toBeTruthy();139+ expect(screen.getByText("Bölüm 33")).toBeTruthy();
114- expect(screen.queryByText("Bölüm 2")).toBeNull();140+ expect(screen.queryByText("Bölüm 32")).toBeNull();
115-141+
116- // jsdom has no IntersectionObserver, so the next rows wait for a button.142+ fireEvent.click(screen.getByRole("button", { name: /Next|Sonraki/ }));
117- fireEvent.click(screen.getByRole("button", { name: "Devamını yükle" }));143+ expect(screen.getByText("Bölüm 32")).toBeTruthy();
118- expect(screen.getByText("Bölüm 2")).toBeTruthy();144+ expect(screen.queryByText("Bölüm 52")).toBeNull();
119- expect(screen.getByText("Bölüm 1")).toBeTruthy();
120- expect(screen.getByText("Bölüm 52")).toBeTruthy();
121 });145 });
122 146
123 it("opens an episode's note page with that episode picked", async () => {147 it("opens an episode's note page with that episode picked", async () => {
124 const onSelect = renderLibrary();148 const onSelect = renderLibrary();
125 149
126- await waitFor(() => expect(screen.getAllByText("Hücre").length).toBe(2));150+ await waitFor(() => expect(screen.getAllByText("Hücre").length).toBe(3));
127 fireEvent.click(screen.getAllByRole("button", { name: /Hücre/ })[0]!);151 fireEvent.click(screen.getAllByRole("button", { name: /Hücre/ })[0]!);
128 152
129 expect(onSelect).toHaveBeenCalledWith("note-1", expect.any(String));153 expect(onSelect).toHaveBeenCalledWith("note-1", expect.any(String));
@@ -133,8 +157,22 @@ describe("StudioOutputLibrary", () => {
133 const onSelect = renderLibrary();157 const onSelect = renderLibrary();
134 158
135 await waitFor(() => expect(screen.getByText("Kuvvet")).toBeTruthy());159 await waitFor(() => expect(screen.getByText("Kuvvet")).toBeTruthy());
160+ visible?.("note-2");
161+ await waitFor(() => expect(screen.getByText("Yapay zekâ özeti")).toBeTruthy());
136 fireEvent.click(screen.getByRole("button", { name: /Kuvvet/ }));162 fireEvent.click(screen.getByRole("button", { name: /Kuvvet/ }));
137 163
138 expect(onSelect).toHaveBeenCalledWith("note-2", undefined);164 expect(onSelect).toHaveBeenCalledWith("note-2", undefined);
139 });165 });
166+
167+ it("loads only a visible note and keeps its unknown output as a placeholder", async () => {
168+ renderLibrary();
169+ await waitFor(() => expect(screen.getByText("Başarısız")).toBeTruthy());
170+ expect(screen.getAllByText("—").length).toBeGreaterThan(0);
171+ expect(courseNotesApi.getCourseNoteRag).not.toHaveBeenCalled();
172+
173+ visible?.("note-2");
174+ await waitFor(() => expect(courseNotesApi.getCourseNoteRag).toHaveBeenCalledWith("note-2", { limit: 1 }));
175+ expect(courseNotesApi.getCourseNoteRag).toHaveBeenCalledTimes(1);
176+ await waitFor(() => expect(screen.getByText("Yapay zekâ özeti")).toBeTruthy());
177+ });
140 });178 });
src/components/ai/studio-output-library.tsxmodified+74 -44
@@ -1,4 +1,4 @@
1-import { For, Show, Suspense, createEffect, createMemo, createSignal } from "solid-js";1+import { For, Show, createEffect, createMemo, createSignal, onCleanup, onMount } from "solid-js";
2 import { createResource } from "@/lib/create-resource";2 import { createResource } from "@/lib/create-resource";
3 import { getCourseNoteRag } from "@/api/course-notes";3 import { getCourseNoteRag } from "@/api/course-notes";
4 import { listPodcastJobs } from "@/api/podcast";4 import { listPodcastJobs } from "@/api/podcast";
@@ -6,8 +6,7 @@ import type { PodcastJobSummary } from "@/api/client";
6 import { Badge } from "@/components/ui/badge";6 import { Badge } from "@/components/ui/badge";
7 import { EmptyInline } from "@/components/ui/empty-inline";7 import { EmptyInline } from "@/components/ui/empty-inline";
8 import { IconSparkles, IconWaveform } from "@/components/ui/icons";8 import { IconSparkles, IconWaveform } from "@/components/ui/icons";
9-import { InfiniteSentinel } from "@/components/ui/infinite-sentinel";9+import { TablePagination } from "@/components/ui/table-pagination";
10-import { PageSpinner } from "@/components/ui/page-spinner";
11 import { cn } from "@/lib/cn";10 import { cn } from "@/lib/cn";
12 import { formatDateTime } from "@/lib/format";11 import { formatDateTime } from "@/lib/format";
13 import { usePreferences, useT } from "@/stores/preferences-context";12 import { usePreferences, useT } from "@/stores/preferences-context";
@@ -29,13 +28,15 @@ type StudioArtifact = {
29 title: string;28 title: string;
30 courseTitle: string;29 courseTitle: string;
31 /** Sorts the list: when the run finished, else when it started. */30 /** Sorts the list: when the run finished, else when it started. */
32- at: number;31+ at?: number;
33 job: PodcastJobSummary | null;32 job: PodcastJobSummary | null;
33+ pending?: boolean;
34 };34 };
35 35
36 const LIBRARY_LIMIT = 100;36 const LIBRARY_LIMIT = 100;
37 /** Client lists reveal this many rows at a time, like client DataTables. */37 /** Client lists reveal this many rows at a time, like client DataTables. */
38-const LIBRARY_REVEAL = 50;38+/** Rows per library page; the history is already in memory, so it pages. */
39+const LIBRARY_PAGE = 20;
39 40
40 export function StudioOutputLibrary(props: {41 export function StudioOutputLibrary(props: {
41 notes: StudioLibraryNote[];42 notes: StudioLibraryNote[];
@@ -46,6 +47,37 @@ export function StudioOutputLibrary(props: {
46 const t = useT();47 const t = useT();
47 const { locale } = usePreferences();48 const { locale } = usePreferences();
48 const source = createMemo(() => props.notes.map((note) => note.id).join(","));49 const source = createMemo(() => props.notes.map((note) => note.id).join(","));
50+ const [summaries, setSummaries] = createSignal<Record<string, number | null>>({});
51+ const requested = new Set<string>();
52+ let list: HTMLUListElement | undefined;
53+ let observer: IntersectionObserver | undefined;
54+
55+ const loadSummary = (noteId: string) => {
56+ if (requested.has(noteId)) return;
57+ requested.add(noteId);
58+ void getCourseNoteRag(noteId, { limit: 1 }).then(
59+ (page) => setSummaries((current) => ({ ...current, [noteId]: page.items[0]?.generated_at ?? null })),
60+ () => setSummaries((current) => ({ ...current, [noteId]: null })),
61+ );
62+ };
63+ const watchNote = (element: HTMLLIElement, noteId: string) => {
64+ element.dataset.noteId = noteId;
65+ if (observer) observer.observe(element);
66+ else if (typeof IntersectionObserver === "undefined") loadSummary(noteId);
67+ };
68+ onMount(() => {
69+ if (typeof IntersectionObserver === "undefined") return;
70+ observer = new IntersectionObserver((entries) => {
71+ for (const entry of entries) {
72+ if (!entry.isIntersecting) continue;
73+ const noteId = (entry.target as HTMLElement).dataset.noteId;
74+ if (noteId) loadSummary(noteId);
75+ observer?.unobserve(entry.target);
76+ }
77+ }, { rootMargin: "100px" });
78+ list?.querySelectorAll<HTMLLIElement>("[data-studio-note]").forEach((element) => observer?.observe(element));
79+ });
80+ onCleanup(() => observer?.disconnect());
49 81
50 const stateVariant = (state: string) => {82 const stateVariant = (state: string) => {
51 if (state === "done") return "success" as const;83 if (state === "done") return "success" as const;
@@ -73,18 +105,15 @@ export function StudioOutputLibrary(props: {
73 return "bg-warning";105 return "bg-warning";
74 };106 };
75 107
76- const [items] = createResource(source, async (): Promise<StudioArtifact[]> => {108+ const [podcasts] = createResource(source, () => listPodcastJobs({ limit: LIBRARY_LIMIT }));
77- const [podcastResult, ...summaryResults] = await Promise.allSettled([109+ const items = createMemo((): StudioArtifact[] => {
78- listPodcastJobs({ limit: LIBRARY_LIMIT }),
79- ...props.notes.map((note) => getCourseNoteRag(note.id, { limit: 1 })),
80- ]);
81 const byId = new Map(props.notes.map((note) => [note.id, note]));110 const byId = new Map(props.notes.map((note) => [note.id, note]));
82 const rows: StudioArtifact[] = [];111 const rows: StudioArtifact[] = [];
83 112
84 // Every job, not only the finished ones: a failed or cancelled run is part113 // Every job, not only the finished ones: a failed or cancelled run is part
85 // of the history and saying so is more useful than hiding it.114 // of the history and saying so is more useful than hiding it.
86- if (podcastResult.status === "fulfilled") {115+ if (podcasts()) {
87- for (const job of podcastResult.value.items) {116+ for (const job of podcasts()!.items) {
88 const note = byId.get(job.source_id);117 const note = byId.get(job.source_id);
89 rows.push({118 rows.push({
90 key: `podcast:${job.job_id}`,119 key: `podcast:${job.job_id}`,
@@ -97,31 +126,36 @@ export function StudioOutputLibrary(props: {
97 }126 }
98 }127 }
99 128
100- props.notes.forEach((note, index) => {129+ props.notes.forEach((note) => {
101- const result = summaryResults[index];130+ const at = summaries()[note.id];
102- const summary = result?.status === "fulfilled" ? result.value.items[0] : undefined;131+ if (at === null) return;
103- if (!summary) return;
104 rows.push({132 rows.push({
105- key: `summary:${summary.id}`,133+ key: `summary:${note.id}`,
106 noteId: note.id,134 noteId: note.id,
107 title: note.title,135 title: note.title,
108 courseTitle: note.courseTitle,136 courseTitle: note.courseTitle,
109- at: summary.generated_at,137+ at,
110 job: null,138 job: null,
139+ pending: at === undefined,
111 });140 });
112 });141 });
113 142
114- return rows.sort((a, b) => b.at - a.at);143+ return rows.sort((a, b) => (b.at ?? -1) - (a.at ?? -1));
115 });144 });
116 145
117- // The history is merged here from two sources, so it is revealed in146+ // The history is merged here from two sources and held in memory, so it
118- // memory as the reader scrolls — the app's client-list standard.147+ // pages with numbers — the app's standard for lists that are not fetched as
119- const [shown, setShown] = createSignal(LIBRARY_REVEAL);148+ // you scroll. A new source goes back to the first page.
149+ const [page, setPage] = createSignal(0);
120 const total = () => items()?.length ?? 0;150 const total = () => items()?.length ?? 0;
121- const pageItems = createMemo(() => (items() ?? []).slice(0, shown()));151+ const pageCount = () => Math.max(1, Math.ceil(total() / LIBRARY_PAGE));
152+ const pageItems = createMemo(() => (items() ?? []).slice(page() * LIBRARY_PAGE, (page() + 1) * LIBRARY_PAGE));
122 createEffect(() => {153 createEffect(() => {
123 source();154 source();
124- setShown(LIBRARY_REVEAL);155+ setPage(0);
156+ });
157+ createEffect(() => {
158+ if (page() >= pageCount()) setPage(pageCount() - 1);
125 });159 });
126 160
127 const open = (item: StudioArtifact) => {161 const open = (item: StudioArtifact) => {
@@ -137,16 +171,15 @@ export function StudioOutputLibrary(props: {
137 <h2 class="text-sm font-semibold text-text-strong">{t("aiStudio.library.title")}</h2>171 <h2 class="text-sm font-semibold text-text-strong">{t("aiStudio.library.title")}</h2>
138 <p class="mt-0.5 text-xs text-muted-foreground">{t("aiStudio.library.description")}</p>172 <p class="mt-0.5 text-xs text-muted-foreground">{t("aiStudio.library.description")}</p>
139 </div>173 </div>
140- <Show when={(items()?.length ?? 0) > 0}>174+ <Show when={items().some((item) => !item.pending)}>
141 <span class="shrink-0 text-xs tabular-nums text-muted-foreground">175 <span class="shrink-0 text-xs tabular-nums text-muted-foreground">
142- {t("aiStudio.library.count", { count: items()?.length ?? 0 })}176+ {t("aiStudio.library.count", { count: items().filter((item) => !item.pending).length })}
143 </span>177 </span>
144 </Show>178 </Show>
145 </header>179 </header>
146 180
147- <Suspense fallback={<div class="py-8"><PageSpinner /></div>}>
148 <Show181 <Show
149- when={(items()?.length ?? 0) > 0}182+ when={items().length > 0 || podcasts.loading}
150 fallback={183 fallback={
151 <div class="px-4 py-5">184 <div class="px-4 py-5">
152 <EmptyInline title={t("aiStudio.library.empty")} hint={t("aiStudio.library.emptyHint")} />185 <EmptyInline title={t("aiStudio.library.empty")} hint={t("aiStudio.library.emptyHint")} />
@@ -155,10 +188,10 @@ export function StudioOutputLibrary(props: {
155 >188 >
156 {/* A run history, the way a studio lists one: hairline dividers, a189 {/* A run history, the way a studio lists one: hairline dividers, a
157 status dot, what was produced and when — no cards. */}190 status dot, what was produced and when — no cards. */}
158- <ul class="divide-y divide-border-hairline">191+ <ul ref={list} class="divide-y divide-border-hairline">
159 <For each={pageItems()}>192 <For each={pageItems()}>
160 {(item) => (193 {(item) => (
161- <li>194+ <li data-studio-note={item.pending ? "" : undefined} ref={item.pending ? (element) => watchNote(element, item.noteId) : undefined}>
162 <button195 <button
163 type="button"196 type="button"
164 aria-current={props.selectedId === item.noteId ? "true" : undefined}197 aria-current={props.selectedId === item.noteId ? "true" : undefined}
@@ -168,9 +201,7 @@ export function StudioOutputLibrary(props: {
168 )}201 )}
169 onClick={() => open(item)}202 onClick={() => open(item)}
170 >203 >
171- <span204+ <span class={cn("h-1.5 w-1.5 shrink-0 rounded-full", item.pending ? "animate-pulse bg-muted-foreground/30" : item.job ? dotClass(item.job.state) : "bg-success")} />
172- class={cn("h-1.5 w-1.5 shrink-0 rounded-full", item.job ? dotClass(item.job.state) : "bg-success")}
173- />
174 <span class="min-w-0 flex-1">205 <span class="min-w-0 flex-1">
175 <span class="block truncate text-sm font-medium text-text-strong">{item.title}</span>206 <span class="block truncate text-sm font-medium text-text-strong">{item.title}</span>
176 <span class="mt-0.5 block truncate text-xs text-muted-foreground">207 <span class="mt-0.5 block truncate text-xs text-muted-foreground">
@@ -178,7 +209,7 @@ export function StudioOutputLibrary(props: {
178 {/* Phones fold the date under the title so the title keeps the row's width. */}209 {/* Phones fold the date under the title so the title keeps the row's width. */}
179 <span class="tabular-nums sm:hidden">210 <span class="tabular-nums sm:hidden">
180 {item.courseTitle ? " · " : ""}211 {item.courseTitle ? " · " : ""}
181- {formatDateTime(item.at, locale())}212+ {item.at === undefined ? "—" : formatDateTime(item.at, locale())}
182 </span>213 </span>
183 </span>214 </span>
184 </span>215 </span>
@@ -188,7 +219,7 @@ export function StudioOutputLibrary(props: {
188 fallback={219 fallback={
189 <Badge variant="outline" class="gap-1 rounded-md font-normal">220 <Badge variant="outline" class="gap-1 rounded-md font-normal">
190 <IconSparkles class="h-3 w-3" />221 <IconSparkles class="h-3 w-3" />
191- {t("aiStudio.library.summary")}222+ {item.pending ? "—" : t("aiStudio.library.summary")}
192 </Badge>223 </Badge>
193 }224 }
194 >225 >
@@ -208,26 +239,25 @@ export function StudioOutputLibrary(props: {
208 </Show>239 </Show>
209 </span>240 </span>
210 <span class="hidden shrink-0 text-xs tabular-nums text-muted-foreground sm:block">241 <span class="hidden shrink-0 text-xs tabular-nums text-muted-foreground sm:block">
211- {formatDateTime(item.at, locale())}242+ {item.at === undefined ? "—" : formatDateTime(item.at, locale())}
212 </span>243 </span>
213 </button>244 </button>
214 </li>245 </li>
215 )}246 )}
216 </For>247 </For>
217 </ul>248 </ul>
218- <Show when={total() > LIBRARY_REVEAL}>249+ <Show when={total() > 0}>
219- <div class="flex flex-col items-start gap-2 border-t border-border-hairline px-4 py-3">250+ <div class="border-t border-border-hairline px-4 py-3">
220- <InfiniteSentinel251+ <TablePagination
221- hasMore={shown() < total()}252+ pageIndex={page()}
222- loading={false}253+ pageCount={pageCount()}
223- shown={Math.min(shown(), total())}254+ pageSize={LIBRARY_PAGE}
224 total={total()}255 total={total()}
225- onLoadMore={() => setShown((count) => count + LIBRARY_REVEAL)}256+ onPageChange={setPage}
226 />257 />
227 </div>258 </div>
228 </Show>259 </Show>
229 </Show>260 </Show>
230- </Suspense>
231 261
232 </section>262 </section>
233 );263 );
src/components/dashboard/quick-link-column.tsxmodified+18 -2
@@ -1,4 +1,4 @@
1-import { For, Show, type Component } from "solid-js";1+import { For, Show, onCleanup, type Component } from "solid-js";
2 import { EmptyInline } from "@/components/ui/empty-inline";2 import { EmptyInline } from "@/components/ui/empty-inline";
3 import { IconChevronRight } from "@/components/ui/icons";3 import { IconChevronRight } from "@/components/ui/icons";
4 import type { IllustrationName } from "@/lib/illustrations";4 import type { IllustrationName } from "@/lib/illustrations";
@@ -15,6 +15,7 @@ export type QuickLinkColumnProps = {
15 rows: QuickLinkRow[];15 rows: QuickLinkRow[];
16 empty: string;16 empty: string;
17 illustration?: IllustrationName;17 illustration?: IllustrationName;
18+ onVisible?: () => void;
18 onOpen: (row: QuickLinkRow) => void;19 onOpen: (row: QuickLinkRow) => void;
19 };20 };
20 21
@@ -22,8 +23,23 @@ export type QuickLinkColumnProps = {
22 * list of resource rows with a trailing caption, each navigating to the23 * list of resource rows with a trailing caption, each navigating to the
23 * resource's real detail page. */24 * resource's real detail page. */
24 export function QuickLinkColumn(props: QuickLinkColumnProps) {25 export function QuickLinkColumn(props: QuickLinkColumnProps) {
26+ const observe = (el: HTMLDivElement) => {
27+ if (!props.onVisible) return;
28+ if (typeof IntersectionObserver === "undefined") {
29+ props.onVisible();
30+ return;
31+ }
32+ const observer = new IntersectionObserver((entries) => {
33+ if (entries.some((entry) => entry.isIntersecting)) {
34+ observer.disconnect();
35+ props.onVisible?.();
36+ }
37+ }, { rootMargin: "160px" });
38+ observer.observe(el);
39+ onCleanup(() => observer.disconnect());
40+ };
25 return (41 return (
26- <div class="flex min-w-0 flex-1 flex-col rounded-xl border border-border-line bg-surface-base px-4 py-3">42+ <div ref={observe} class="flex min-w-0 flex-1 flex-col rounded-xl border border-border-line bg-surface-base px-4 py-3">
27 <p class="pb-2 text-[13px] font-medium text-text-subtle">{props.title}</p>43 <p class="pb-2 text-[13px] font-medium text-text-subtle">{props.title}</p>
28 <Show when={props.rows.length > 0} fallback={<EmptyInline class="border-t border-border-hairline" illustration={props.illustration} title={props.empty} />}>44 <Show when={props.rows.length > 0} fallback={<EmptyInline class="border-t border-border-hairline" illustration={props.illustration} title={props.empty} />}>
29 <For each={props.rows}>45 <For each={props.rows}>
src/components/events/event-roll-call.test.tsxmodified+22 -0
@@ -66,3 +66,25 @@ test("before the event starts nothing can be picked or saved", async () => {
66 expect((row("Bora").getByRole("radio", { name: /Katıldı|Attended/ }) as HTMLButtonElement).disabled).toBe(true);66 expect((row("Bora").getByRole("radio", { name: /Katıldı|Attended/ }) as HTMLButtonElement).disabled).toBe(true);
67 expect((saveButton() as HTMLButtonElement).disabled).toBe(true);67 expect((saveButton() as HTMLButtonElement).disabled).toBe(true);
68 });68 });
69+
70+test("pages a long roster and keeps draft marks across pages", async () => {
71+ const longRoster = Array.from({ length: 12 }, (_, index) => ({
72+ user: person(`student-${index}`, `Student ${index}`),
73+ status: null,
74+ marked_by: null,
75+ }));
76+ render(() => (
77+ <PreferencesProvider>
78+ <EventRollCall eventId="event-1" roster={longRoster} open onSaved={() => {}} />
79+ </PreferencesProvider>
80+ ));
81+ await screen.findByText("Student 0");
82+ expect(screen.queryByText("Student 10")).toBeNull();
83+ fireEvent.click(row("Student 0").getByRole("radio", { name: /Katıldı|Attended/ }));
84+ fireEvent.click(screen.getByRole("button", { name: /Next|Sonraki/ }));
85+ expect(screen.getByText("Student 10")).toBeTruthy();
86+ expect(screen.queryByText("Student 0")).toBeNull();
87+ fireEvent.click(screen.getByRole("button", { name: /Previous|Önceki/ }));
88+ expect(row("Student 0").getByRole("radio", { name: /Katıldı|Attended/ }).getAttribute("aria-checked")).toBe("true");
89+ expect(postEventAttendance).not.toHaveBeenCalled();
90+});
src/components/events/event-roll-call.tsxmodified+19 -16
@@ -11,7 +11,7 @@ import { TOOLBAR_CONTROL } from "@/components/ui/data-toolbar";
11 import { EmptyState } from "@/components/ui/empty-state";11 import { EmptyState } from "@/components/ui/empty-state";
12 import { InfoTip } from "@/components/ui/info-tip";12 import { InfoTip } from "@/components/ui/info-tip";
13 import { IconCheck } from "@/components/ui/icons";13 import { IconCheck } from "@/components/ui/icons";
14-import { InfiniteSentinel } from "@/components/ui/infinite-sentinel";14+import { TablePagination } from "@/components/ui/table-pagination";
15 import { ATTENDANCE_STATUSES, getAttendanceStatusMeta } from "@/lib/attendance-status";15 import { ATTENDANCE_STATUSES, getAttendanceStatusMeta } from "@/lib/attendance-status";
16 import { cn } from "@/lib/cn";16 import { cn } from "@/lib/cn";
17 import {17 import {
@@ -22,11 +22,9 @@ import {
22 } from "@/lib/event-roll-call";22 } from "@/lib/event-roll-call";
23 import { personLabel } from "@/lib/person";23 import { personLabel } from "@/lib/person";
24 import { matchesSearch } from "@/lib/search-text";24 import { matchesSearch } from "@/lib/search-text";
25+import { createResponsivePageSize } from "@/lib/create-page-size";
25 import { useT } from "@/stores/preferences-context";26 import { useT } from "@/stores/preferences-context";
26 27
27-/** Rows drawn at first and added each time the reader nears the end. */
28-const REVEAL_STEP = 50;
29-
30 /**28 /**
31 * Event roll call as one roster: every expected attendee (resolved by the29 * Event roll call as one roster: every expected attendee (resolved by the
32 * backend from the event's audience) with a status row. Picks stay local30 * backend from the event's audience) with a status row. Picks stay local
@@ -65,7 +63,8 @@ export function EventRollCall(props: {
65 const [summary, setSummary] = createSignal<{ kind: "success" | "destructive"; text: string } | null>(null);63 const [summary, setSummary] = createSignal<{ kind: "success" | "destructive"; text: string } | null>(null);
66 const [query, setQuery] = createSignal("");64 const [query, setQuery] = createSignal("");
67 const [onlyUnmarked, setOnlyUnmarked] = createSignal(false);65 const [onlyUnmarked, setOnlyUnmarked] = createSignal(false);
68- const [revealed, setRevealed] = createSignal(REVEAL_STEP);66+ const pageSize = createResponsivePageSize(10);
67+ const [pageIndex, setPageIndex] = createSignal(0);
69 68
70 const effective = (userId: string) => draft()[userId] ?? saved()[userId] ?? undefined;69 const effective = (userId: string) => draft()[userId] ?? saved()[userId] ?? undefined;
71 const changes = createMemo(() => rollCallChanges(saved(), draft()));70 const changes = createMemo(() => rollCallChanges(saved(), draft()));
@@ -87,10 +86,12 @@ export function EventRollCall(props: {
87 return !q || matchesSearch(q, personLabel(row.user), row.user.username, row.user.student_number);86 return !q || matchesSearch(q, personLabel(row.user), row.user.username, row.user.student_number);
88 });87 });
89 });88 });
90- // The roster is already in memory: no page numbers, the list just draws89+ createEffect(on([query, onlyUnmarked, pageSize], () => setPageIndex(0), { defer: true }));
91- // more rows as the reader scrolls (the app's client-list standard).90+ createEffect(() => {
92- createEffect(on([query, onlyUnmarked], () => setRevealed(REVEAL_STEP), { defer: true }));91+ const last = Math.max(0, Math.ceil(visible().length / pageSize()) - 1);
93- const pageRows = createMemo(() => visible().slice(0, revealed()));92+ if (pageIndex() > last) setPageIndex(last);
93+ });
94+ const pageRows = createMemo(() => visible().slice(pageIndex() * pageSize(), (pageIndex() + 1) * pageSize()));
94 95
95 const busy = () => progress() != null;96 const busy = () => progress() != null;
96 const locked = () => !props.open || busy();97 const locked = () => !props.open || busy();
@@ -301,13 +302,15 @@ export function EventRollCall(props: {
301 </For>302 </For>
302 </ul>303 </ul>
303 </Show>304 </Show>
304- <InfiniteSentinel305+ <Show when={visible().length > 0}>
305- hasMore={pageRows().length < visible().length}306+ <TablePagination
306- loading={false}307+ pageIndex={pageIndex()}
307- shown={pageRows().length}308+ pageCount={Math.ceil(visible().length / pageSize())}
308- total={visible().length}309+ pageSize={pageSize()}
309- onLoadMore={() => setRevealed((count) => count + REVEAL_STEP)}310+ total={visible().length}
310- />311+ onPageChange={setPageIndex}
312+ />
313+ </Show>
311 314
312 <Show when={summary()}>315 <Show when={summary()}>
313 {(item) => <Alert variant={item().kind}>{item().text}</Alert>}316 {(item) => <Alert variant={item().kind}>{item().text}</Alert>}
src/components/insights/insight-overview.test.tsxadded+24 -0
@@ -0,0 +1,24 @@
1+import { cleanup, render, screen } from "@solidjs/testing-library";
2+import { afterEach, expect, it, vi } from "vitest";
3+import { InsightOverview } from "./insight-overview";
4+
5+vi.mock("@/stores/preferences-context", () => ({
6+ usePreferences: () => ({
7+ locale: () => "en",
8+ t: (key: string, vars?: Record<string, number>) => key === "insights.overview.reading"
9+ ? `Reading ${vars?.loaded} of ${vars?.total} students…`
10+ : key,
11+ }),
12+}));
13+
14+afterEach(cleanup);
15+
16+it("labels partial counts and averages with their current coverage", () => {
17+ render(() => <InsightOverview overview={{
18+ total: 200, loaded: 50, analysed: 40, needAttention: 7,
19+ marksAverage: 78, attendanceRate: 0.9,
20+ }} />);
21+ expect(screen.getByText("40 / 200")).toBeTruthy();
22+ expect(screen.getByText("7 / 50")).toBeTruthy();
23+ expect(screen.getAllByText("Reading 50 of 200 students…").length).toBeGreaterThan(0);
24+});
src/components/insights/insight-overview.tsxmodified+9 -5
@@ -20,25 +20,29 @@ export function InsightOverview(props: { overview: Overview }) {
20 </div>20 </div>
21 );21 );
22 const o = () => props.overview;22 const o = () => props.overview;
23+ const partial = () => o().loaded < o().total;
24+ const coverage = () => partial()
25+ ? t("insights.overview.reading", { loaded: o().loaded, total: o().total })
26+ : t("insights.overview.ofTotal", { total: o().total });
23 return (27 return (
24 <section class="space-y-2" aria-label={t("insights.summary")}>28 <section class="space-y-2" aria-label={t("insights.summary")}>
25 <div class="grid grid-cols-2 gap-3 lg:grid-cols-4">29 <div class="grid grid-cols-2 gap-3 lg:grid-cols-4">
26- {tile(t("insights.overview.analysed"), String(o().analysed), t("insights.overview.ofTotal", { total: o().total }))}30+ {tile(t("insights.overview.analysed"), partial() ? `${o().analysed} / ${o().total}` : String(o().analysed), coverage())}
27 {tile(31 {tile(
28 t("insights.overview.needAttention"),32 t("insights.overview.needAttention"),
29- String(o().needAttention),33+ partial() ? (o().loaded ? `${o().needAttention} / ${o().loaded}` : "—") : String(o().needAttention),
30- t("insights.overview.ofTotal", { total: o().total }),34+ coverage(),
31 o().needAttention > 0 ? "warn" : undefined,35 o().needAttention > 0 ? "warn" : undefined,
32 )}36 )}
33 {tile(37 {tile(
34 t("insights.overview.marks"),38 t("insights.overview.marks"),
35 o().marksAverage == null ? "—" : runReportDecimal(o().marksAverage!, prefs.locale()),39 o().marksAverage == null ? "—" : runReportDecimal(o().marksAverage!, prefs.locale()),
36- o().marksAverage == null ? t("insights.overview.noData") : t("insights.overview.ofTotal", { total: o().analysed }),40+ partial() ? coverage() : o().marksAverage == null ? t("insights.overview.noData") : t("insights.overview.ofTotal", { total: o().analysed }),
37 )}41 )}
38 {tile(42 {tile(
39 t("insights.overview.attendance"),43 t("insights.overview.attendance"),
40 o().attendanceRate == null ? "—" : runReportPercent(o().attendanceRate, prefs.locale()),44 o().attendanceRate == null ? "—" : runReportPercent(o().attendanceRate, prefs.locale()),
41- o().attendanceRate == null ? t("insights.overview.noData") : t("insights.overview.ofTotal", { total: o().analysed }),45+ partial() ? coverage() : o().attendanceRate == null ? t("insights.overview.noData") : t("insights.overview.ofTotal", { total: o().analysed }),
42 )}46 )}
43 </div>47 </div>
44 <Show when={o().loaded < o().total}>48 <Show when={o().loaded < o().total}>
src/components/insights/insight-students-table.test.tsxadded+55 -0
@@ -0,0 +1,55 @@
1+import { cleanup, fireEvent, render, screen } from "@solidjs/testing-library";
2+import { afterEach, expect, it, vi } from "vitest";
3+import { InsightStudentsTable } from "./insight-students-table";
4+import { toStudentSignal } from "@/lib/insight-run-report";
5+
6+vi.mock("@tanstack/solid-router", () => ({ useNavigate: () => vi.fn(), Link: () => null }));
7+vi.mock("@/stores/preferences-context", () => ({
8+ usePreferences: () => ({ locale: () => "en", t: (key: string) => key }),
9+}));
10+vi.mock("@/components/ui/data-table", () => ({
11+ DataTable: (props: { filters: unknown }) => (
12+ <div>
13+ <table><thead><tr><th><button type="button">Sort</button></th></tr></thead></table>
14+ {props.filters as never}
15+ </div>
16+ ),
17+}));
18+vi.mock("@/components/ui/select", () => ({
19+ DropdownSelect: (props: { onChange: (value: "attention") => void }) => (
20+ <button type="button" onClick={() => props.onChange("attention")}>Attention filter</button>
21+ ),
22+}));
23+
24+afterEach(() => {
25+ cleanup();
26+ vi.unstubAllGlobals();
27+});
28+
29+it("requests more only near the table end, and loads all for a signal filter or sort", () => {
30+ let notify: ((entries: { isIntersecting: boolean }[]) => void) | undefined;
31+ vi.stubGlobal("IntersectionObserver", class {
32+ constructor(callback: typeof notify) { notify = callback; }
33+ observe() {}
34+ disconnect() {}
35+ });
36+ const more = vi.fn();
37+ const all = vi.fn();
38+ render(() => <InsightStudentsTable
39+ rows={[toStudentSignal({ id: "a", name: "A" }, null, null)]}
40+ title="Students"
41+ description=""
42+ empty=""
43+ hasMore
44+ onNeedMore={more}
45+ onInspectAll={all}
46+ />);
47+ expect(more).not.toHaveBeenCalled();
48+ notify?.([{ isIntersecting: false }]);
49+ expect(more).not.toHaveBeenCalled();
50+ notify?.([{ isIntersecting: true }]);
51+ expect(more).toHaveBeenCalledTimes(1);
52+ fireEvent.click(screen.getByRole("button", { name: "Sort" }));
53+ fireEvent.click(screen.getByRole("button", { name: "Attention filter" }));
54+ expect(all).toHaveBeenCalledTimes(2);
55+});
src/components/insights/insight-students-table.tsxmodified+26 -2
@@ -1,4 +1,4 @@
1-import { createMemo, createSignal, type JSX } from "solid-js";1+import { createMemo, createSignal, onCleanup, onMount, type JSX } from "solid-js";
2 import { Link, useNavigate } from "@tanstack/solid-router";2 import { Link, useNavigate } from "@tanstack/solid-router";
3 import type { ColumnDef } from "@tanstack/solid-table";3 import type { ColumnDef } from "@tanstack/solid-table";
4 import { Badge } from "@/components/ui/badge";4 import { Badge } from "@/components/ui/badge";
@@ -35,6 +35,9 @@ export function InsightStudentsTable(props: {
35 description: string;35 description: string;
36 empty: string;36 empty: string;
37 actions?: JSX.Element;37 actions?: JSX.Element;
38+ hasMore?: boolean;
39+ onNeedMore?: () => void;
40+ onInspectAll?: () => void;
38 }) {41 }) {
39 const prefs = usePreferences();42 const prefs = usePreferences();
40 const navigate = useNavigate();43 const navigate = useNavigate();
@@ -42,6 +45,19 @@ export function InsightStudentsTable(props: {
42 const t = (key: string, vars?: Record<string, string | number>) => prefs.t(key as never, vars);45 const t = (key: string, vars?: Record<string, string | number>) => prefs.t(key as never, vars);
43 const rt = (key: Parameters<typeof runReportText>[1]) => runReportText(locale(), key);46 const rt = (key: Parameters<typeof runReportText>[1]) => runReportText(locale(), key);
44 const [filter, setFilter] = createSignal<Filter>("all");47 const [filter, setFilter] = createSignal<Filter>("all");
48+ let sentinel: HTMLDivElement | undefined;
49+ onMount(() => {
50+ if (!sentinel) return;
51+ if (typeof IntersectionObserver === "undefined") {
52+ props.onInspectAll?.();
53+ return;
54+ }
55+ const observer = new IntersectionObserver((entries) => {
56+ if (entries.some((entry) => entry.isIntersecting) && props.hasMore) props.onNeedMore?.();
57+ }, { rootMargin: "0px 0px 600px 0px" });
58+ observer.observe(sentinel);
59+ onCleanup(() => observer.disconnect());
60+ });
45 const visible = createMemo(() =>61 const visible = createMemo(() =>
46 props.rows.filter((row) =>62 props.rows.filter((row) =>
47 filter() === "attention" ? row.attention > 0 : filter() === "none" ? row.state === "no_summary" : true,63 filter() === "attention" ? row.attention > 0 : filter() === "none" ? row.state === "no_summary" : true,
@@ -215,6 +231,9 @@ export function InsightStudentsTable(props: {
215 ]);231 ]);
216 232
217 return (233 return (
234+ <div onClick={(event) => {
235+ if ((event.target as Element).closest("th button")) props.onInspectAll?.();
236+ }}>
218 <DataTable237 <DataTable
219 title={props.title}238 title={props.title}
220 description={props.description}239 description={props.description}
@@ -231,7 +250,10 @@ export function InsightStudentsTable(props: {
231 <DropdownSelect250 <DropdownSelect
232 options={filters()}251 options={filters()}
233 value={filter()}252 value={filter()}
234- onChange={setFilter}253+ onChange={(value) => {
254+ setFilter(value);
255+ if (value !== "all") props.onInspectAll?.();
256+ }}
235 labelPrefix={t("common.filter")}257 labelPrefix={t("common.filter")}
236 class="min-w-44"258 class="min-w-44"
237 />259 />
@@ -241,5 +263,7 @@ export function InsightStudentsTable(props: {
241 tableClass="insight-grid-table min-w-[60rem]"263 tableClass="insight-grid-table min-w-[60rem]"
242 storageKey="insight-students-v2"264 storageKey="insight-students-v2"
243 />265 />
266+ <div ref={sentinel} aria-hidden="true" class="h-px" />
267+ </div>
244 );268 );
245 }269 }
src/components/ui/data-table.test.tsxmodified+66 -31
@@ -98,31 +98,28 @@ function stubIntersectionObserver() {
98 };98 };
99 }99 }
100 100
101-test("reveals rows in steps instead of paging", async () => {101+test("paginates client rows without observing the scroll position", () => {
102 const reachEnd = stubIntersectionObserver();102 const reachEnd = stubIntersectionObserver();
103- const rows = Array.from({ length: 120 }, (_, index) => ({ name: `Person ${index + 1}` }));103+ const rows = Array.from({ length: 21 }, (_, index) => ({ name: `Person ${index + 1}` }));
104 try {104 try {
105 render(() => (105 render(() => (
106 <PreferencesProvider>106 <PreferencesProvider>
107 <DataTable columns={[columns[0]]} data={rows} enableColumnVisibility={false} />107 <DataTable columns={[columns[0]]} data={rows} enableColumnVisibility={false} />
108 </PreferencesProvider>108 </PreferencesProvider>
109 ));109 ));
110-110+ expect(screen.getByText("Person 10")).toBeTruthy();
111- expect(screen.getByText("Person 50")).toBeTruthy();111+ expect(screen.queryByText("Person 11")).toBeNull();
112- expect(screen.queryByText("Person 51")).toBeNull();112+ expect(screen.getByText("1 / 3")).toBeTruthy();
113- expect(screen.getByText(/(Showing 50 of 120|120 kayıttan 50)/)).toBeTruthy();
114- expect(screen.queryByRole("button", { name: "Next" })).toBeNull();
115 reachEnd();113 reachEnd();
116- // jsdom lays nothing out, so the sentinel always reads as near the end114+ expect(screen.queryByText("Person 11")).toBeNull();
117- // and each reveal chains into the next until the list is complete.115+ fireEvent.click(screen.getByRole("button", { name: /Next|Sonraki/ }));
118- await new Promise((resolve) => setTimeout(resolve, 0));116+ expect(screen.getByText("Person 11")).toBeTruthy();
119- expect(screen.getByText("Person 120")).toBeTruthy();
120 } finally {117 } finally {
121 vi.unstubAllGlobals();118 vi.unstubAllGlobals();
122 }119 }
123 });120 });
124 121
125-test("without IntersectionObserver every row renders, with the total under the list", () => {122+test("without IntersectionObserver client rows still paginate", () => {
126 vi.stubGlobal("IntersectionObserver", undefined);123 vi.stubGlobal("IntersectionObserver", undefined);
127 const rows = Array.from({ length: 60 }, (_, index) => ({ name: `Person ${index + 1}` }));124 const rows = Array.from({ length: 60 }, (_, index) => ({ name: `Person ${index + 1}` }));
128 try {125 try {
@@ -131,12 +128,56 @@ test("without IntersectionObserver every row renders, with the total under the l
131 <DataTable columns={[columns[0]]} data={rows} enableColumnVisibility={false} />128 <DataTable columns={[columns[0]]} data={rows} enableColumnVisibility={false} />
132 </PreferencesProvider>129 </PreferencesProvider>
133 ));130 ));
134- expect(screen.getByText("Person 60")).toBeTruthy();131+ expect(screen.queryByText("Person 60")).toBeNull();
135- expect(screen.getByText(/^(Total|Toplam): 60$/)).toBeTruthy();132+ expect(screen.getByText("1 / 6")).toBeTruthy();
136 } finally {133 } finally {
137 vi.unstubAllGlobals();134 vi.unstubAllGlobals();
138 }135 }
139 });136 });
137+test("uses a shorter client page on phones", () => {
138+ vi.stubGlobal("matchMedia", (query: string) => ({
139+ matches: query.includes("max-width"),
140+ media: query,
141+ addEventListener: () => undefined,
142+ removeEventListener: () => undefined,
143+ }));
144+ try {
145+ render(() => (
146+ <PreferencesProvider>
147+ <DataTable
148+ columns={[columns[0]]}
149+ data={Array.from({ length: 11 }, (_, index) => ({ name: `Person ${index + 1}` }))}
150+ enableColumnVisibility={false}
151+ />
152+ </PreferencesProvider>
153+ ));
154+ expect(screen.getByText("Person 5")).toBeTruthy();
155+ expect(screen.queryByText("Person 6")).toBeNull();
156+ expect(screen.getByText("1 / 3")).toBeTruthy();
157+ } finally {
158+ vi.unstubAllGlobals();
159+ }
160+});
161+test("search resets a client page and shrinking data clamps its index", () => {
162+ const [rows, setRows] = createSignal(Array.from({ length: 22 }, (_, index) => ({ name: `Person ${index + 1}` })));
163+ render(() => (
164+ <PreferencesProvider>
165+ <DataTable
166+ columns={[columns[0]]}
167+ data={rows()}
168+ enableColumnVisibility={false}
169+ searchPredicate={(row, query) => row.name.toLowerCase().includes(query.toLowerCase())}
170+ />
171+ </PreferencesProvider>
172+ ));
173+ fireEvent.click(screen.getByRole("button", { name: /Next|Sonraki/ }));
174+ fireEvent.click(screen.getByRole("button", { name: /Next|Sonraki/ }));
175+ expect(screen.getByText("Person 22")).toBeTruthy();
176+ setRows((current) => current.slice(0, 12));
177+ expect(screen.getByText("Person 12")).toBeTruthy();
178+ fireEvent.input(screen.getByRole("textbox"), { target: { value: "Person 12" } });
179+ expect(screen.getByText("Person 12")).toBeTruthy();
180+});
140 test("a display column renders its own cell instead of the empty dash", () => {181 test("a display column renders its own cell instead of the empty dash", () => {
141 // A column with no accessorFn has no value to be empty, so the empty-cell182 // A column with no accessorFn has no value to be empty, so the empty-cell
142 // fallback must not swallow its render function.183 // fallback must not swallow its render function.
@@ -315,25 +356,19 @@ test("an empty list narrowed by the caller's filters offers to clear them", () =
315 expect(onClearFilters).toHaveBeenCalledOnce();356 expect(onClearFilters).toHaveBeenCalledOnce();
316 });357 });
317 358
318-test("revealed rows hold when the caller hands over a fresh data array", async () => {359+test("the client page holds when the caller hands over a fresh data array", () => {
319- const reachEnd = stubIntersectionObserver();
320 const [tick, setTick] = createSignal(0);360 const [tick, setTick] = createSignal(0);
321 const people = Array.from({ length: 70 }, (_, i) => ({ name: `P${String(i).padStart(2, "0")}` }));361 const people = Array.from({ length: 70 }, (_, i) => ({ name: `P${String(i).padStart(2, "0")}` }));
322- try {362+ render(() => (
323- render(() => (363+ <PreferencesProvider>
324- <PreferencesProvider>364+ <DataTable columns={[{ accessorKey: "name", header: "Name" }]} data={(tick(), people.map((row) => ({ ...row })))} enableColumnVisibility={false} />
325- {/* A new array on every read, like a page that maps rows inline. */}365+ </PreferencesProvider>
326- <DataTable columns={[{ accessorKey: "name", header: "Name" }]} data={(tick(), people.map((row) => ({ ...row })))} enableColumnVisibility={false} />366+ ));
327- </PreferencesProvider>367+ fireEvent.click(screen.getByRole("button", { name: /Next|Sonraki/ }));
328- ));368+ expect(screen.getByText("P10")).toBeTruthy();
329- reachEnd();369+ setTick(1);
330- await new Promise((resolve) => setTimeout(resolve, 0));370+ expect(screen.getByText("P10")).toBeTruthy();
331- expect(screen.getByText("P69")).toBeTruthy();371+ expect(screen.queryByText("P00")).toBeNull();
332- setTick(1);
333- expect(screen.getByText("P69")).toBeTruthy();
334- } finally {
335- vi.unstubAllGlobals();
336- }
337 });372 });
338 test("a toolbar holding only the column menu still gets its card", () => {373 test("a toolbar holding only the column menu still gets its card", () => {
339 const { container } = render(() => (374 const { container } = render(() => (
src/components/ui/data-table.tsxmodified+51 -87
@@ -11,6 +11,7 @@ import {
11 flexRender,11 flexRender,
12 getCoreRowModel,12 getCoreRowModel,
13 getFilteredRowModel,13 getFilteredRowModel,
14+ getPaginationRowModel,
14 getSortedRowModel,15 getSortedRowModel,
15 } from "@tanstack/solid-table";16 } from "@tanstack/solid-table";
16 import { Illustration } from "@/components/ui/illustration";17 import { Illustration } from "@/components/ui/illustration";
@@ -23,10 +24,10 @@ import { IconArrowDown, IconArrowUp, IconChevronsUpDown } from "@/components/ui/
23 import { InfoTip } from "@/components/ui/info-tip";24 import { InfoTip } from "@/components/ui/info-tip";
24 import { cn } from "@/lib/cn";25 import { cn } from "@/lib/cn";
25 import { createMediaQuery } from "@/lib/create-media-query";26 import { createMediaQuery } from "@/lib/create-media-query";
26-import { COMPACT_SCREEN_QUERY } from "@/lib/create-page-size";27+import { COMPACT_SCREEN_QUERY, createResponsivePageSize } from "@/lib/create-page-size";
27 import { createScrollRestore } from "@/lib/scroll-restore";28 import { createScrollRestore } from "@/lib/scroll-restore";
28 import { createTablePreferences } from "@/lib/table-preferences";29 import { createTablePreferences } from "@/lib/table-preferences";
29-import { createUrlParam, createUrlString, decodeSort, encodeSort, listParamKeys } from "@/lib/url-state";30+import { createUrlPageIndex, createUrlParam, createUrlString, decodeSort, encodeSort, listParamKeys } from "@/lib/url-state";
30 import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";31 import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
31 import { useT } from "@/stores/preferences-context";32 import { useT } from "@/stores/preferences-context";
32 33
@@ -99,10 +100,7 @@ export type DataTableProps<TData, TValue = unknown> = {
99 mobileLayout?: "cards" | "scroll";100 mobileLayout?: "cards" | "scroll";
100 onRowClick?: (row: TData) => void;101 onRowClick?: (row: TData) => void;
101 onSearchInput?: (value: string) => void;102 onSearchInput?: (value: string) => void;
102- /**103+ /** Rows per page on a wide screen; client tables use fewer on phones. */
103- * Server-paged tables only: rows per page on a wide screen. A client-side
104- * table has no pages — it reveals rows as the reader scrolls.
105- */
106 pageSize?: number;104 pageSize?: number;
107 searchPredicate?: (row: TData, query: string) => boolean;105 searchPredicate?: (row: TData, query: string) => boolean;
108 searchValue?: string;106 searchValue?: string;
@@ -136,13 +134,7 @@ const resolveUpdater = <T,>(updater: Updater<T>, old: T): T =>
136 134
137 const alignClass = { left: "text-left", center: "text-center", right: "text-right" } as const;135 const alignClass = { left: "text-left", center: "text-center", right: "text-right" } as const;
138 136
139-/**137+/** Start fetching the next server page this far before the list's end comes into view. */
140- * A client-side table renders this many rows, then this many more each time
141- * the reader nears the end. The data is already in memory, so sorting, search
142- * and filters still see every row — only the DOM is paced.
143- */
144-const REVEAL_STEP = 50;
145-/** Start revealing the next rows this far before the list's end comes into view. */
146 const REVEAL_MARGIN_PX = 600;138 const REVEAL_MARGIN_PX = 600;
147 139
148 export function DataTable<TData, TValue = unknown>(props: DataTableProps<TData, TValue>) {140 export function DataTable<TData, TValue = unknown>(props: DataTableProps<TData, TValue>) {
@@ -157,34 +149,13 @@ export function DataTable<TData, TValue = unknown>(props: DataTableProps<TData,
157 ? createUrlParam<SortingState>(urlKeys.sort, { parse: decodeSort, serialize: encodeSort })149 ? createUrlParam<SortingState>(urlKeys.sort, { parse: decodeSort, serialize: encodeSort })
158 : createSignal<SortingState>([]);150 : createSignal<SortingState>([]);
159 const [otherColumnFilters, setOtherColumnFilters] = createSignal<ColumnFiltersState>([]);151 const [otherColumnFilters, setOtherColumnFilters] = createSignal<ColumnFiltersState>([]);
160- // Client-side tables drop page numbers for scroll-to-reveal; only a152+ const clientPageSize = createResponsivePageSize(props.pageSize ?? 10);
161- // server-paged table (`manualPagination`) still pages.153+ const [clientPageIndex, setClientPageIndex] = urlKeys && !props.manualPagination && !props.infinite
162- const revealing = () => paginationEnabled && !props.manualPagination && !props.infinite;154+ ? createUrlPageIndex(urlKeys.page)
163- // How far the reader had revealed, per page and table, for this tab: coming155+ : createSignal(0);
164- // back from a detail page renders those rows again, so the router's scroll156+ const pagination = (): PaginationState => ({ pageIndex: clientPageIndex(), pageSize: clientPageSize() });
165- // restoration has somewhere to land.157+ createEffect(on(clientPageSize, () => setClientPageIndex(0), { defer: true }));
166- const revealKey = typeof window === "undefined"158+ createEffect(on(() => props.pageResetKey, () => setClientPageIndex(0), { defer: true }));
167- ? null
168- : `reveal:${window.location.pathname}${window.location.search}:${props.storageKey ?? props.title ?? ""}`;
169- const readRevealed = () => {
170- try {
171- const count = Number(revealKey ? sessionStorage.getItem(revealKey) : null);
172- return Number.isFinite(count) && count > REVEAL_STEP ? Math.floor(count) : REVEAL_STEP;
173- } catch {
174- return REVEAL_STEP;
175- }
176- };
177- const [revealed, setRevealed] = createSignal(readRevealed());
178- createEffect(on(revealed, (count) => {
179- if (!revealKey || count === Number.MAX_SAFE_INTEGER) return;
180- try {
181- sessionStorage.setItem(revealKey, String(count));
182- } catch {
183- // storage blocked: the table just starts at the first step
184- }
185- }, { defer: true }));
186- const resetReveal = () => setRevealed(REVEAL_STEP);
187- createEffect(on(() => props.pageResetKey, resetReveal, { defer: true }));
188 // The search box's text when the table owns it — the `searchPredicate`159 // The search box's text when the table owns it — the `searchPredicate`
189 // query, or the `filterColumn` filter value.160 // query, or the `filterColumn` filter value.
190 const [search, setSearch] = urlKeys && props.searchValue === undefined && !props.onSearchInput161 const [search, setSearch] = urlKeys && props.searchValue === undefined && !props.onSearchInput
@@ -208,12 +179,12 @@ export function DataTable<TData, TValue = unknown>(props: DataTableProps<TData,
208 const own = next.find((filter) => filter.id === column);179 const own = next.find((filter) => filter.id === column);
209 setSearch(typeof own?.value === "string" ? own.value : "");180 setSearch(typeof own?.value === "string" ? own.value : "");
210 setOtherColumnFilters(next.filter((filter) => filter.id !== column));181 setOtherColumnFilters(next.filter((filter) => filter.id !== column));
211- resetReveal();182+ setClientPageIndex(0);
212 };183 };
213 // A new sort order is a new list: start again from its top.184 // A new sort order is a new list: start again from its top.
214 const setSorting = (next: SortingState) => {185 const setSorting = (next: SortingState) => {
215 setSortingState(next);186 setSortingState(next);
216- resetReveal();187+ setClientPageIndex(0);
217 };188 };
218 // Sorting is client-side only, and the backend takes no sort parameter: on189 // Sorting is client-side only, and the backend takes no sort parameter: on
219 // a server-paged table it would reorder the visible page alone while the190 // a server-paged table it would reorder the visible page alone while the
@@ -240,12 +211,13 @@ export function DataTable<TData, TValue = unknown>(props: DataTableProps<TData,
240 getCoreRowModel: getCoreRowModel(),211 getCoreRowModel: getCoreRowModel(),
241 getSortedRowModel: getSortedRowModel(),212 getSortedRowModel: getSortedRowModel(),
242 getFilteredRowModel: getFilteredRowModel(),213 getFilteredRowModel: getFilteredRowModel(),
243- // Server paging is the caller's; the table itself never slices pages.214+ ...(paginationEnabled && !props.manualPagination && !props.infinite ? { getPaginationRowModel: getPaginationRowModel() } : {}),
244 autoResetPageIndex: false,215 autoResetPageIndex: false,
245 onSortingChange: (updater) => setSorting(resolveUpdater(updater, sorting())),216 onSortingChange: (updater) => setSorting(resolveUpdater(updater, sorting())),
246 onColumnFiltersChange: (updater) => setColumnFilters(resolveUpdater(updater, columnFilters())),217 onColumnFiltersChange: (updater) => setColumnFilters(resolveUpdater(updater, columnFilters())),
247 onColumnVisibilityChange: (updater) =>218 onColumnVisibilityChange: (updater) =>
248 prefs.setVisibility(resolveUpdater(updater, prefs.preferences().visibility)),219 prefs.setVisibility(resolveUpdater(updater, prefs.preferences().visibility)),
220+ onPaginationChange: (updater) => setClientPageIndex(resolveUpdater(updater, pagination()).pageIndex),
249 state: {221 state: {
250 get sorting() {222 get sorting() {
251 return sorting();223 return sorting();
@@ -259,7 +231,7 @@ export function DataTable<TData, TValue = unknown>(props: DataTableProps<TData,
259 get pagination(): PaginationState {231 get pagination(): PaginationState {
260 return props.manualPagination232 return props.manualPagination
261 ? { pageIndex: props.manualPagination.pageIndex, pageSize: props.manualPagination.pageSize }233 ? { pageIndex: props.manualPagination.pageIndex, pageSize: props.manualPagination.pageSize }
262- : { pageIndex: 0, pageSize: Number.MAX_SAFE_INTEGER };234+ : props.infinite ? { pageIndex: 0, pageSize: Number.MAX_SAFE_INTEGER } : pagination();
263 },235 },
264 },236 },
265 });237 });
@@ -349,52 +321,51 @@ export function DataTable<TData, TValue = unknown>(props: DataTableProps<TData,
349 // slot sizes them rather than trusting each page to.321 // slot sizes them rather than trusting each page to.
350 const TOOLBAR_ACTIONS =322 const TOOLBAR_ACTIONS =
351 "[&_button]:h-10 [&_button]:rounded-full [&_button]:px-3.5 [&_button]:text-[13px] sm:[&_button]:h-8 touch:[&_button]:h-10 [&_a]:h-10 [&_a]:rounded-full [&_a]:px-3.5 [&_a]:text-[13px] sm:[&_a]:h-8 touch:[&_a]:h-10";323 "[&_button]:h-10 [&_button]:rounded-full [&_button]:px-3.5 [&_button]:text-[13px] sm:[&_button]:h-8 touch:[&_button]:h-10 [&_a]:h-10 [&_a]:rounded-full [&_a]:px-3.5 [&_a]:text-[13px] sm:[&_a]:h-8 touch:[&_a]:h-10";
352- const totalRows = () => props.manualPagination?.total ?? props.infinite?.total ?? table.getRowModel().rows.length;324+ const pageCount = () => props.manualPagination
325+ ? Math.max(1, Math.ceil(props.manualPagination.total / props.manualPagination.pageSize))
326+ : table.getPageCount();
327+ const pageIndex = () => props.manualPagination?.pageIndex ?? clientPageIndex();
328+ const pageSize = () => props.manualPagination?.pageSize ?? clientPageSize();
329+ const totalRows = () => props.manualPagination?.total ?? props.infinite?.total ?? table.getFilteredRowModel().rows.length;
353 const setPageIndex = (next: number) => {330 const setPageIndex = (next: number) => {
354 if (props.manualPagination) props.manualPagination.onPageChange(next);331 if (props.manualPagination) props.manualPagination.onPageChange(next);
355- else resetReveal();332+ else setClientPageIndex(next);
356- };
357- /** The rows actually rendered: all of them, or the revealed head of the list. */
358- const visibleRows = () => {
359- const rows = table.getRowModel().rows;
360- return revealing() ? rows.slice(0, revealed()) : rows;
361 };333 };
362- const hasHidden = () => revealing() && table.getRowModel().rows.length > revealed();334+ createEffect(() => {
363- // A sentinel under the list reveals the next rows as it nears the viewport.335+ if (props.manualPagination || props.infinite || !paginationEnabled) return;
364- // Without IntersectionObserver (old engines, jsdom) everything renders.336+ const rows = table.getFilteredRowModel().rows.length;
337+ if (rows === 0) return;
338+ const last = Math.max(0, Math.ceil(rows / clientPageSize()) - 1);
339+ if (clientPageIndex() > last) setClientPageIndex(last);
340+ });
341+ const visibleRows = () => table.getRowModel().rows;
365 let sentinel: HTMLDivElement | undefined;342 let sentinel: HTMLDivElement | undefined;
366 const observing = typeof IntersectionObserver !== "undefined";343 const observing = typeof IntersectionObserver !== "undefined";
367 const nearEnd = () => !!sentinel && sentinel.getBoundingClientRect().top < window.innerHeight + REVEAL_MARGIN_PX;344 const nearEnd = () => !!sentinel && sentinel.getBoundingClientRect().top < window.innerHeight + REVEAL_MARGIN_PX;
368- const revealMore = () => {345+ const loadMore = () => {
369 if (!nearEnd()) return;346 if (!nearEnd()) return;
370 const infinite = props.infinite;347 const infinite = props.infinite;
371- if (infinite) {348+ if (infinite?.hasMore && !infinite.loading) infinite.onLoadMore();
372- if (infinite.hasMore && !infinite.loading) infinite.onLoadMore();
373- return;
374- }
375- if (hasHidden()) setRevealed((count) => count + REVEAL_STEP);
376 };349 };
377 createEffect(() => {350 createEffect(() => {
378- if (!(revealing() || props.infinite) || !observing) return;351+ if (!props.infinite || !observing) return;
379 const node = sentinel;352 const node = sentinel;
380 if (!node) return;353 if (!node) return;
381 const observer = new IntersectionObserver((entries) => {354 const observer = new IntersectionObserver((entries) => {
382- if (entries.some((entry) => entry.isIntersecting)) revealMore();355+ if (entries.some((entry) => entry.isIntersecting)) loadMore();
383 }, { rootMargin: `0px 0px ${REVEAL_MARGIN_PX}px 0px` });356 }, { rootMargin: `0px 0px ${REVEAL_MARGIN_PX}px 0px` });
384 observer.observe(node);357 observer.observe(node);
385 onCleanup(() => observer.disconnect());358 onCleanup(() => observer.disconnect());
386 });359 });
387- // The observer only fires when the sentinel crosses the margin; after a
388- // reveal of short rows it can still sit inside it, so check again.
389- createEffect(on(revealed, () => queueMicrotask(revealMore), { defer: true }));
390 // Same for a fetched page: once it lands, a short page may leave the end360 // Same for a fetched page: once it lands, a short page may leave the end
391 // in view, so ask for the next one straight away.361 // in view, so ask for the next one straight away.
392 createEffect(on(() => props.infinite?.loading, (busy) => {362 createEffect(on(() => props.infinite?.loading, (busy) => {
393- if (busy === false && observing) queueMicrotask(revealMore);363+ if (busy === false && observing) queueMicrotask(loadMore);
394 }, { defer: true }));364 }, { defer: true }));
395- if (!observing) setRevealed(Number.MAX_SAFE_INTEGER);365+ const scrollKey = typeof window === "undefined" || props.infinite || props.manualPagination
396- // Back from a detail page lands on the same row once the rows are drawn.366+ ? null
397- createScrollRestore(revealKey, () => visibleRows().length > 0);367+ : `${window.location.pathname}:${props.storageKey ?? props.title ?? ""}:${urlKeys?.page ?? "page"}`;
368+ createScrollRestore(scrollKey, () => visibleRows().length > 0);
398 const searchFieldValue = () => {369 const searchFieldValue = () => {
399 if (props.onSearchInput || props.searchPredicate || props.filterColumn) return searchValue();370 if (props.onSearchInput || props.searchPredicate || props.filterColumn) return searchValue();
400 return "";371 return "";
@@ -403,7 +374,6 @@ export function DataTable<TData, TValue = unknown>(props: DataTableProps<TData,
403 if (props.onSearchInput) props.onSearchInput(value);374 if (props.onSearchInput) props.onSearchInput(value);
404 else setSearch(value);375 else setSearch(value);
405 setPageIndex(0);376 setPageIndex(0);
406- resetReveal();
407 };377 };
408 const isInteractiveTarget = (target: EventTarget | null, row: EventTarget | null) => {378 const isInteractiveTarget = (target: EventTarget | null, row: EventTarget | null) => {
409 if (!(target instanceof Element)) return false;379 if (!(target instanceof Element)) return false;
@@ -766,20 +736,16 @@ export function DataTable<TData, TValue = unknown>(props: DataTableProps<TData,
766 </Table>736 </Table>
767 </DataTableFrame>737 </DataTableFrame>
768 </Show>738 </Show>
769- <Show when={props.manualPagination}>739+ <Show when={(props.manualPagination || paginationEnabled) && !props.infinite && totalRows() > 0}>
770- {(manual) => (740+ <TablePagination
771- <Show when={manual().total > 0}>741+ pageIndex={pageIndex()}
772- <TablePagination742+ pageCount={pageCount()}
773- pageIndex={manual().pageIndex}743+ pageSize={pageSize()}
774- pageCount={Math.max(1, Math.ceil(manual().total / manual().pageSize))}744+ total={totalRows()}
775- pageSize={manual().pageSize}745+ onPageChange={setPageIndex}
776- total={manual().total}746+ />
777- onPageChange={setPageIndex}
778- />
779- </Show>
780- )}
781 </Show>747 </Show>
782- <Show when={(revealing() || props.infinite) && totalRows() > 0}>748+ <Show when={props.infinite && totalRows() > 0}>
783 {/* One block, so the parent's space-y gap is paid once: the sentinel749 {/* One block, so the parent's space-y gap is paid once: the sentinel
784 and the count as siblings put two gaps under the scroll hint. */}750 and the count as siblings put two gaps under the scroll hint. */}
785 <div class="-mt-1.5 flex flex-col gap-2">751 <div class="-mt-1.5 flex flex-col gap-2">
@@ -789,9 +755,7 @@ export function DataTable<TData, TValue = unknown>(props: DataTableProps<TData,
789 ? t("common.loadingMore")755 ? t("common.loadingMore")
790 : props.infinite?.hasMore756 : props.infinite?.hasMore
791 ? t("common.showingOf", { shown: props.data.length, total: totalRows() })757 ? t("common.showingOf", { shown: props.data.length, total: totalRows() })
792- : hasHidden()758+ : t("common.rowCount", { total: totalRows() })}
793- ? t("common.showingOf", { shown: revealed(), total: totalRows() })
794- : t("common.rowCount", { total: totalRows() })}
795 </p>759 </p>
796 <Show when={!observing && props.infinite?.hasMore && !props.infinite.loading}>760 <Show when={!observing && props.infinite?.hasMore && !props.infinite.loading}>
797 <Button type="button" variant="outline" size="sm" class="self-start" onClick={() => props.infinite?.onLoadMore()}>761 <Button type="button" variant="outline" size="sm" class="self-start" onClick={() => props.infinite?.onLoadMore()}>
src/lib/insight-students.test.tsmodified+48 -1
@@ -1,5 +1,5 @@
1 import type { PersonRef, StudentInsight } from "@/api/client";1 import type { PersonRef, StudentInsight } from "@/api/client";
2-import { insightOverview, loadStudentSignals } from "./insight-students";2+import { cachedStudentSignal, clearStudentSignalCache, insightOverview, loadStudentSignals } from "./insight-students";
3 import { toStudentSignal } from "./insight-run-report";3 import { toStudentSignal } from "./insight-run-report";
4 4
5 const person = (id: string): PersonRef => ({ id, username: id, display_name: id.toUpperCase() });5 const person = (id: string): PersonRef => ({ id, username: id, display_name: id.toUpperCase() });
@@ -41,3 +41,50 @@ it("summarises only what the summaries measured", () => {
41 attendanceRate: 0.8,41 attendanceRate: 0.8,
42 });42 });
43 });43 });
44+
45+it("reuses successful reads within a viewer tab and keeps viewers separate", async () => {
46+ const read = vi.fn(async (id: string) => insight(id, 80, 0.9, 0));
47+ const rows: string[] = [];
48+ await loadStudentSignals([person("a")], (row) => rows.push(row.state), read, "viewer-a");
49+ expect(cachedStudentSignal(person("a"), "viewer-a")?.state).toBe("ok");
50+ await loadStudentSignals([person("a")], (row) => rows.push(row.state), read, "viewer-a");
51+ expect(read).toHaveBeenCalledTimes(1);
52+ expect(cachedStudentSignal(person("a"), "viewer-b")).toBeNull();
53+ await loadStudentSignals([person("a")], () => {}, read, "viewer-b");
54+ expect(read).toHaveBeenCalledTimes(2);
55+ expect(rows).toEqual(["ok", "ok"]);
56+ clearStudentSignalCache("viewer-a");
57+ clearStudentSignalCache("viewer-b");
58+});
59+
60+it("limits concurrent reads in a requested row window", async () => {
61+ let active = 0;
62+ let peak = 0;
63+ const pending: Array<() => void> = [];
64+ const read = vi.fn((id: string) => new Promise<StudentInsight>((resolve) => {
65+ active++;
66+ peak = Math.max(peak, active);
67+ pending.push(() => { active--; resolve(insight(id, 80, 0.9, 0)); });
68+ }));
69+ const done = loadStudentSignals(Array.from({ length: 12 }, (_, index) => person(String(index))), () => {}, read);
70+ expect(read).toHaveBeenCalledTimes(6);
71+ while (pending.length) {
72+ pending.shift()!();
73+ await Promise.resolve();
74+ }
75+ await done;
76+ expect(read).toHaveBeenCalledTimes(12);
77+ expect(peak).toBe(6);
78+});
79+
80+it("does not cache a failed read", async () => {
81+ const read = vi.fn()
82+ .mockRejectedValueOnce(new Error("temporary"))
83+ .mockResolvedValueOnce(insight("retry", 80, 0.9, 0));
84+ const states: string[] = [];
85+ await loadStudentSignals([person("retry")], (row) => states.push(row.state), read, "retry-viewer");
86+ await loadStudentSignals([person("retry")], (row) => states.push(row.state), read, "retry-viewer");
87+ expect(states).toEqual(["error", "ok"]);
88+ expect(read).toHaveBeenCalledTimes(2);
89+ clearStudentSignalCache("retry-viewer");
90+});
src/lib/insight-students.tsmodified+17 -2
@@ -14,9 +14,20 @@ export async function loadInsightStudents(role: Role): Promise<PersonRef[]> {
14 14
15 /** Parallel insight reads; there is no bulk endpoint. */15 /** Parallel insight reads; there is no bulk endpoint. */
16 const READ_CONCURRENCY = 6;16 const READ_CONCURRENCY = 6;
17+const insightCache = new Map<string, StudentInsight>();
18+const cacheKey = (scope: string, id: string) => `${scope}\0${id}`;
19+
20+export function cachedStudentSignal(person: PersonRef, scope: string): StudentSignal | null {
21+ const insight = insightCache.get(cacheKey(scope, person.id));
22+ return insight ? toStudentSignal({ id: person.id, name: personLabel(person) }, insight, null) : null;
23+}
24+
25+export function clearStudentSignalCache(scope: string): void {
26+ for (const key of insightCache.keys()) if (key.startsWith(`${scope}\0`)) insightCache.delete(key);
27+}
17 28
18 /**29 /**
19- * Read every student's insight a few at a time, reporting each row as it30+ * Read the requested students' insights a few at a time, reporting each row as it
20 * lands so the table fills progressively instead of waiting on the slowest.31 * lands so the table fills progressively instead of waiting on the slowest.
21 * A failed read becomes that row's `error` state, never a made-up value.32 * A failed read becomes that row's `error` state, never a made-up value.
22 */33 */
@@ -24,13 +35,17 @@ export async function loadStudentSignals(
24 students: PersonRef[],35 students: PersonRef[],
25 onRow: (signal: StudentSignal) => void,36 onRow: (signal: StudentSignal) => void,
26 read: (userId: string) => Promise<StudentInsight> = getInsightByUserId,37 read: (userId: string) => Promise<StudentInsight> = getInsightByUserId,
38+ scope?: string,
27 ): Promise<void> {39 ): Promise<void> {
28 const queue = [...students];40 const queue = [...students];
29 const worker = async () => {41 const worker = async () => {
30 for (let person = queue.shift(); person; person = queue.shift()) {42 for (let person = queue.shift(); person; person = queue.shift()) {
31 const identity = { id: person.id, name: personLabel(person) };43 const identity = { id: person.id, name: personLabel(person) };
32 try {44 try {
33- onRow(toStudentSignal(identity, await read(person.id), null));45+ const cached = scope ? insightCache.get(cacheKey(scope, person.id)) : undefined;
46+ const insight = cached ?? await read(person.id);
47+ if (scope && !cached) insightCache.set(cacheKey(scope, person.id), insight);
48+ onRow(toStudentSignal(identity, insight, null));
34 } catch (error) {49 } catch (error) {
35 onRow(toStudentSignal(identity, null, formatApiError(error)));50 onRow(toStudentSignal(identity, null, formatApiError(error)));
36 }51 }
src/lib/instance-labels.test.tsmodified+23 -1
@@ -1,6 +1,7 @@
1-import { formatInstanceLabel, loadInstanceLabels, resetInstanceLabelCache } from "./instance-labels";1+import { classSections, formatInstanceLabel, invalidateSchoolWalk, loadInstanceLabels, loadSchoolSections, resetInstanceLabelCache } from "./instance-labels";
2 2
3 const calls: string[] = [];3 const calls: string[] = [];
4+let failClassOnce = false;
4 5
5 vi.mock("@/api/instances", () => ({6 vi.mock("@/api/instances", () => ({
6 getInstanceById: async (id: string) => {7 getInstanceById: async (id: string) => {
@@ -17,6 +18,10 @@ vi.mock("@/api/classes", () => ({
17 },18 },
18 getClassInstances: async (classId: string) => {19 getClassInstances: async (classId: string) => {
19 calls.push(`class-instances:${classId}`);20 calls.push(`class-instances:${classId}`);
21+ if (classId === "k-9a" && failClassOnce) {
22+ failClassOnce = false;
23+ throw new Error("offline");
24+ }
20 const items = classId === "k-9a"25 const items = classId === "k-9a"
21 ? [{ id: "i2", course: "c-math", class: "k-9a", title: "Matematik" }]26 ? [{ id: "i2", course: "c-math", class: "k-9a", title: "Matematik" }]
22 : [{ id: "i1", course: "c-math", class: "k-10b", title: "Matematik" }, { id: "i3", course: "c-fiz", class: "k-10b", title: "Fizik" }];27 : [{ id: "i1", course: "c-math", class: "k-10b", title: "Matematik" }, { id: "i3", course: "c-fiz", class: "k-10b", title: "Fizik" }];
@@ -35,6 +40,7 @@ vi.mock("@/api/classes", () => ({
35 describe("instance labels", () => {40 describe("instance labels", () => {
36 beforeEach(() => {41 beforeEach(() => {
37 calls.length = 0;42 calls.length = 0;
43+ failClassOnce = false;
38 resetInstanceLabelCache();44 resetInstanceLabelCache();
39 });45 });
40 46
@@ -75,4 +81,20 @@ describe("instance labels", () => {
75 expect(calls.filter((call) => call.startsWith("instance:"))).toHaveLength(0);81 expect(calls.filter((call) => call.startsWith("instance:"))).toHaveLength(0);
76 expect(calls.filter((call) => call.startsWith("class-instances:"))).toHaveLength(2);82 expect(calls.filter((call) => call.startsWith("class-instances:"))).toHaveLength(2);
77 });83 });
84+
85+ it("shares the school walk across callers and refreshes after invalidation", async () => {
86+ await loadSchoolSections();
87+ await loadSchoolSections();
88+ expect(calls.filter((call) => call.startsWith("class-instances:"))).toHaveLength(2);
89+ invalidateSchoolWalk();
90+ await loadSchoolSections();
91+ expect(calls.filter((call) => call.startsWith("class-instances:"))).toHaveLength(4);
92+ });
93+
94+ it("retries only the class whose section read failed", async () => {
95+ failClassOnce = true;
96+ expect(await classSections("k-9a").catch(() => [])).toEqual([]);
97+ expect(await classSections("k-9a")).toHaveLength(1);
98+ expect(calls.filter((call) => call === "class-instances:k-9a")).toHaveLength(2);
99+ });
78 });100 });
src/lib/instance-labels.tsmodified+35 -15
@@ -34,11 +34,23 @@ const classCache = new Map<string, Promise<string | null>>();
34 let myClassesCache: Promise<Map<string, string>> | null = null;34 let myClassesCache: Promise<Map<string, string>> | null = null;
35 let allClassesCache: Promise<Map<string, string>> | null = null;35 let allClassesCache: Promise<Map<string, string>> | null = null;
36 let classListCache: Promise<ClassGroup[]> | null = null;36 let classListCache: Promise<ClassGroup[]> | null = null;
37-let schoolSectionsCache: Promise<{ klass: ClassGroup; sections: ClassCourse[] }[]> | null = null;37+const sectionCache = new Map<string, Promise<ClassCourse[]>>();
38 let schoolIndexCache: Promise<boolean> | null = null;38 let schoolIndexCache: Promise<boolean> | null = null;
39+const FRESH_MS = 5 * 60 * 1000;
40+let freshUntil = Date.now() + FRESH_MS;
41+
42+function ensureFresh(): void {
43+ if (Date.now() >= freshUntil) invalidateSchoolWalk();
44+}
45+
46+export function invalidateSchoolWalk(): void {
47+ resetInstanceLabelCache();
48+ freshUntil = Date.now() + FRESH_MS;
49+}
39 50
40 /** Teacher+: the school's class list, read once per tab. */51 /** Teacher+: the school's class list, read once per tab. */
41 export function classList(): Promise<ClassGroup[]> {52 export function classList(): Promise<ClassGroup[]> {
53+ ensureFresh();
42 if (!classListCache) {54 if (!classListCache) {
43 classListCache = getClasses({ limit: 200 }).then(55 classListCache = getClasses({ limit: 200 }).then(
44 (page) => page.items,56 (page) => page.items,
@@ -56,21 +68,26 @@ export function classList(): Promise<ClassGroup[]> {
56 * school-wide section route), read once per tab and shared by the label68 * school-wide section route), read once per tab and shared by the label
57 * cache and the section pickers. A class that cannot be read comes back empty.69 * cache and the section pickers. A class that cannot be read comes back empty.
58 */70 */
59-export function loadSchoolSections(): Promise<{ klass: ClassGroup; sections: ClassCourse[] }[]> {71+export function classSections(classId: string): Promise<ClassCourse[]> {
60- if (!schoolSectionsCache) {72+ ensureFresh();
61- schoolSectionsCache = classList().then((classes) =>73+ let hit = sectionCache.get(classId);
62- mapConcurrent(classes, FAN_OUT_LIMIT, (klass) =>74+ if (!hit) {
63- getClassInstances(klass.id, { limit: 200 }).then(75+ const read = getClassInstances(classId, { limit: 200 }).then((page) => page.items);
64- (page) => ({ klass, sections: page.items }),76+ const pending = read.catch((error) => {
65- () => ({ klass, sections: [] as ClassCourse[] }),77+ if (sectionCache.get(classId) === pending) sectionCache.delete(classId);
66- ),78+ throw error;
67- ),
68- ).catch(() => {
69- schoolSectionsCache = null;
70- return [];
71 });79 });
80+ hit = pending;
81+ sectionCache.set(classId, hit);
72 }82 }
73- return schoolSectionsCache;83+ return hit;
84+}
85+
86+export async function loadSchoolSections(): Promise<{ klass: ClassGroup; sections: ClassCourse[] }[]> {
87+ const classes = await classList();
88+ return mapConcurrent(classes, FAN_OUT_LIMIT, async (klass) => ({
89+ klass, sections: await classSections(klass.id).catch(() => [] as ClassCourse[]),
90+ }));
74 }91 }
75 92
76 /**93 /**
@@ -146,6 +163,7 @@ export function formatInstanceLabel(courseTitle: string | null, className: strin
146 }163 }
147 164
148 export function loadInstanceLabel(id: string, role: Role | undefined): Promise<InstanceLabel | null> {165 export function loadInstanceLabel(id: string, role: Role | undefined): Promise<InstanceLabel | null> {
166+ ensureFresh();
149 const key = `${role ?? ""}:${id}`;167 const key = `${role ?? ""}:${id}`;
150 let hit = instanceCache.get(key);168 let hit = instanceCache.get(key);
151 if (!hit) {169 if (!hit) {
@@ -172,6 +190,7 @@ export function loadInstanceLabel(id: string, role: Role | undefined): Promise<I
172 190
173 /** Labels for a bounded set of instance ids, fetched a few at a time. */191 /** Labels for a bounded set of instance ids, fetched a few at a time. */
174 export async function loadInstanceLabels(ids: readonly string[], role: Role | undefined): Promise<Map<string, InstanceLabel>> {192 export async function loadInstanceLabels(ids: readonly string[], role: Role | undefined): Promise<Map<string, InstanceLabel>> {
193+ ensureFresh();
175 const unique = [...new Set(ids)];194 const unique = [...new Set(ids)];
176 // Many labels at once: reading the school's sections class by class is195 // Many labels at once: reading the school's sections class by class is
177 // cheaper than one read per section, once they outnumber the classes.196 // cheaper than one read per section, once they outnumber the classes.
@@ -227,6 +246,7 @@ export function resetInstanceLabelCache(): void {
227 myClassesCache = null;246 myClassesCache = null;
228 allClassesCache = null;247 allClassesCache = null;
229 classListCache = null;248 classListCache = null;
230- schoolSectionsCache = null;249+ sectionCache.clear();
231 schoolIndexCache = null;250 schoolIndexCache = null;
251+ freshUntil = Date.now() + FRESH_MS;
232 }252 }
src/lib/instance-options.test.tsadded+32 -0
@@ -0,0 +1,32 @@
1+import { beforeEach, expect, test, vi } from "vitest";
2+import { loadInstanceOptions } from "./instance-options";
3+import { resetInstanceLabelCache } from "./instance-labels";
4+
5+const { getClasses, getClassInstances } = vi.hoisted(() => ({
6+ getClasses: vi.fn(),
7+ getClassInstances: vi.fn(),
8+}));
9+
10+vi.mock("@/api/classes", () => ({ getClasses, getClassInstances }));
11+vi.mock("@/api/instances", () => ({ getMyInstances: vi.fn() }));
12+
13+beforeEach(() => {
14+ resetInstanceLabelCache();
15+ getClasses.mockReset().mockResolvedValue({ items: [
16+ { id: "c1", name: "9-A", grade_level: 9 },
17+ { id: "c2", name: "9-B", grade_level: 9 },
18+ ] });
19+ getClassInstances.mockReset().mockImplementation(async (id: string) => ({ items: [
20+ { id: `i-${id}`, course: "math", class: id, title: "Math" },
21+ ] }));
22+});
23+
24+test("manager pickers reuse the school section walk across visits", async () => {
25+ const first = await loadInstanceOptions("manager");
26+ const second = await loadInstanceOptions("manager");
27+
28+ expect(first.map((row) => row.label)).toEqual(["Math — 9-A", "Math — 9-B"]);
29+ expect(second).toEqual(first);
30+ expect(getClasses).toHaveBeenCalledTimes(1);
31+ expect(getClassInstances).toHaveBeenCalledTimes(2);
32+});
src/lib/instance-options.tsmodified+3 -3
@@ -1,8 +1,8 @@
1-import { getClasses, getMyClasses } from "@/api/classes";1+import { getMyClasses } from "@/api/classes";
2 import { getMyInstances } from "@/api/instances";2 import { getMyInstances } from "@/api/instances";
3 import type { ClassGroup, Role } from "@/api/client";3 import type { ClassGroup, Role } from "@/api/client";
4 import { hasMinRole } from "@/lib/roles";4 import { hasMinRole } from "@/lib/roles";
5-import { loadSchoolSections } from "@/lib/instance-labels";5+import { classList, loadSchoolSections } from "@/lib/instance-labels";
6 import { compareClasses } from "@/lib/student-directory";6 import { compareClasses } from "@/lib/student-directory";
7 7
8 /** One pickable section: "<ders> — <şube>", plus the ids behind the label. */8 /** One pickable section: "<ders> — <şube>", plus the ids behind the label. */
@@ -41,7 +41,7 @@ export async function loadInstanceOptions(role: Role | undefined): Promise<Insta
41 } else {41 } else {
42 const [mine, classes] = await Promise.all([42 const [mine, classes] = await Promise.all([
43 getMyInstances({ limit: 200 }),43 getMyInstances({ limit: 200 }),
44- (hasMinRole(role, "teacher") ? getClasses({ limit: 200 }) : getMyClasses({ limit: 200 })).catch(44+ (hasMinRole(role, "teacher") ? classList().then((items) => ({ items })) : getMyClasses({ limit: 200 })).catch(
45 () => ({ items: [] as ClassGroup[] }),45 () => ({ items: [] as ClassGroup[] }),
46 ),46 ),
47 ]);47 ]);
src/lib/student-directory.test.tsmodified+32 -5
@@ -1,6 +1,7 @@
1 import { afterEach, describe, expect, test, vi } from "vitest";1 import { afterEach, describe, expect, test, vi } from "vitest";
2 import type { ClassGroup, ClassMember, PersonRef } from "@/api/client";2 import type { ClassGroup, ClassMember, PersonRef } from "@/api/client";
3-import { getStudentDirectory, sortByClass } from "@/lib/student-directory";3+import { classMemberCount, getStudentDirectory, invalidateStudentDirectory, sortByClass } from "@/lib/student-directory";
4+import { resetInstanceLabelCache } from "@/lib/instance-labels";
4 5
5 const cls = (name: string, gradeLevel: number): ClassGroup => ({6 const cls = (name: string, gradeLevel: number): ClassGroup => ({
6 id: name, creator: null, name, grade_level: gradeLevel, year: null, teacher: null,7 id: name, creator: null, name, grade_level: gradeLevel, year: null, teacher: null,
@@ -42,6 +43,8 @@ const jsonResponse = (data: unknown) =>
42 43
43 describe("getStudentDirectory", () => {44 describe("getStudentDirectory", () => {
44 afterEach(() => {45 afterEach(() => {
46+ invalidateStudentDirectory();
47+ resetInstanceLabelCache();
45 vi.restoreAllMocks();48 vi.restoreAllMocks();
46 });49 });
47 50
@@ -53,9 +56,9 @@ describe("getStudentDirectory", () => {
53 return jsonResponse({ items: [person("Zeynep"), person("Ali")], total: 2, limit: null, offset: 0 });56 return jsonResponse({ items: [person("Zeynep"), person("Ali")], total: 2, limit: null, offset: 0 });
54 if (url === "/api/classes?limit=200")57 if (url === "/api/classes?limit=200")
55 return jsonResponse({ items: [cls("9-A", 9), cls("10-B", 10)], total: 2, limit: 200, offset: 0 });58 return jsonResponse({ items: [cls("9-A", 9), cls("10-B", 10)], total: 2, limit: 200, offset: 0 });
56- if (url === "/api/classes/9-A/members?limit=500")59+ if (url === "/api/classes/9-A/members?limit=500&offset=0")
57 return jsonResponse({ items: [member("9-A", person("Ali"))], total: 1, limit: 500, offset: 0 });60 return jsonResponse({ items: [member("9-A", person("Ali"))], total: 1, limit: 500, offset: 0 });
58- if (url === "/api/classes/10-B/members?limit=500") return jsonResponse({ items: [], total: 0, limit: 500, offset: 0 });61+ if (url === "/api/classes/10-B/members?limit=500&offset=0") return jsonResponse({ items: [], total: 0, limit: 500, offset: 0 });
59 throw new Error(`unexpected fetch: ${url}`);62 throw new Error(`unexpected fetch: ${url}`);
60 };63 };
61 vi.stubGlobal("fetch", vi.fn(async (input: RequestInfo | URL) => respond(String(input))));64 vi.stubGlobal("fetch", vi.fn(async (input: RequestInfo | URL) => respond(String(input))));
@@ -65,8 +68,8 @@ describe("getStudentDirectory", () => {
65 expect(calls).toEqual([68 expect(calls).toEqual([
66 "/api/users/search?q=&role=student",69 "/api/users/search?q=&role=student",
67 "/api/classes?limit=200",70 "/api/classes?limit=200",
68- "/api/classes/9-A/members?limit=500",71+ "/api/classes/9-A/members?limit=500&offset=0",
69- "/api/classes/10-B/members?limit=500",72+ "/api/classes/10-B/members?limit=500&offset=0",
70 ]);73 ]);
71 expect(rows.map((row) => row.person.display_name)).toEqual(["Ali", "Zeynep"]);74 expect(rows.map((row) => row.person.display_name)).toEqual(["Ali", "Zeynep"]);
72 expect(rows[0].classes.map((c) => c.name)).toEqual(["9-A"]);75 expect(rows[0].classes.map((c) => c.name)).toEqual(["9-A"]);
@@ -108,4 +111,28 @@ describe("getStudentDirectory", () => {
108 expect(calls).toEqual(["/api/classes/c2/members?limit=500&offset=0"]);111 expect(calls).toEqual(["/api/classes/c2/members?limit=500&offset=0"]);
109 expect(rows.map((row) => row.person.display_name)).toEqual(["Ali"]);112 expect(rows.map((row) => row.person.display_name)).toEqual(["Ali"]);
110 });113 });
114+
115+ test("reuses a roster for later visits and the class count, then invalidates it", async () => {
116+ const fetch = vi.fn(async () => jsonResponse({ items: [member("c3", person("Ali"))], total: 1, limit: 500, offset: 0 }));
117+ vi.stubGlobal("fetch", fetch);
118+ const picked = { ...cls("9-A", 9), id: "c3" };
119+ await getStudentDirectory(picked);
120+ await getStudentDirectory(picked);
121+ expect(await classMemberCount("c3")).toBe(1);
122+ expect(fetch).toHaveBeenCalledTimes(1);
123+ invalidateStudentDirectory();
124+ await getStudentDirectory(picked);
125+ expect(fetch).toHaveBeenCalledTimes(2);
126+ });
127+
128+ test("retries a class whose first roster request failed", async () => {
129+ const fetch = vi.fn()
130+ .mockRejectedValueOnce(new Error("offline"))
131+ .mockResolvedValue(jsonResponse({ items: [], total: 0, limit: 500, offset: 0 }));
132+ vi.stubGlobal("fetch", fetch);
133+ const picked = { ...cls("9-A", 9), id: "c4" };
134+ await expect(getStudentDirectory(picked)).rejects.toThrow();
135+ expect(await getStudentDirectory(picked)).toEqual([]);
136+ expect(fetch).toHaveBeenCalledTimes(2);
137+ });
111 });138 });
src/lib/student-directory.tsmodified+53 -10
@@ -1,6 +1,8 @@
1-import { getClassMembers, getClasses } from "@/api/classes";1+import { getClassMembers } from "@/api/classes";
2 import { getUserSearch } from "@/api/users";2 import { getUserSearch } from "@/api/users";
3 import type { ClassGroup, ClassMember, PersonRef } from "@/api/client";3 import type { ClassGroup, ClassMember, PersonRef } from "@/api/client";
4+import { FAN_OUT_LIMIT, mapConcurrent } from "@/lib/map-concurrent";
5+import { classList } from "@/lib/instance-labels";
4 6
5 export type StudentDirectoryRow = {7 export type StudentDirectoryRow = {
6 person: PersonRef;8 person: PersonRef;
@@ -9,9 +11,19 @@ export type StudentDirectoryRow = {
9 11
10 /** Page size for the class-roster reads; the same one the full sweep asks for. */12 /** Page size for the class-roster reads; the same one the full sweep asks for. */
11 const MEMBERS_PAGE = 500;13 const MEMBERS_PAGE = 500;
14+const FRESH_MS = 5 * 60 * 1000;
15+const memberCache = new Map<string, { until: number; value: Promise<ClassMember[]> }>();
16+const countCache = new Map<string, { until: number; value: Promise<number> }>();
17+let studentsCache: { until: number; value: Promise<PersonRef[]> } | null = null;
18+
19+export function invalidateStudentDirectory(): void {
20+ memberCache.clear();
21+ countCache.clear();
22+ studentsCache = null;
23+}
12 24
13 /** Every live member of one class: the route is paged, so follow offsets to `total`. */25 /** Every live member of one class: the route is paged, so follow offsets to `total`. */
14-async function readClassMembers(classId: string): Promise<ClassMember[]> {26+async function fetchClassMembers(classId: string): Promise<ClassMember[]> {
15 const members: ClassMember[] = [];27 const members: ClassMember[] = [];
16 let offset = 0;28 let offset = 0;
17 for (;;) {29 for (;;) {
@@ -22,6 +34,40 @@ async function readClassMembers(classId: string): Promise<ClassMember[]> {
22 }34 }
23 }35 }
24 36
37+export function readClassMembers(classId: string): Promise<ClassMember[]> {
38+ const hit = memberCache.get(classId);
39+ if (hit && hit.until > Date.now()) return hit.value;
40+ const entry = { until: Date.now() + FRESH_MS, value: fetchClassMembers(classId) };
41+ memberCache.set(classId, entry);
42+ void entry.value.then((members) => {
43+ if (memberCache.get(classId) === entry) countCache.set(classId, { until: entry.until, value: Promise.resolve(members.length) });
44+ }, () => {
45+ if (memberCache.get(classId) === entry) memberCache.delete(classId);
46+ });
47+ return entry.value;
48+}
49+
50+export function classMemberCount(classId: string): Promise<number> {
51+ const roster = memberCache.get(classId);
52+ if (roster && roster.until > Date.now()) return roster.value.then((members) => members.length);
53+ const hit = countCache.get(classId);
54+ if (hit && hit.until > Date.now()) return hit.value;
55+ const entry = { until: Date.now() + FRESH_MS, value: getClassMembers(classId, { limit: 1 }).then((page) => page.total) };
56+ countCache.set(classId, entry);
57+ void entry.value.catch(() => {
58+ if (countCache.get(classId) === entry) countCache.delete(classId);
59+ });
60+ return entry.value;
61+}
62+
63+function students(): Promise<PersonRef[]> {
64+ if (studentsCache && studentsCache.until > Date.now()) return studentsCache.value;
65+ const entry = { until: Date.now() + FRESH_MS, value: getUserSearch("", undefined, "student").then((page) => page.items) };
66+ studentsCache = entry;
67+ void entry.value.catch(() => { if (studentsCache === entry) studentsCache = null; });
68+ return entry.value;
69+}
70+
25 /**71 /**
26 * Shared student list for teacher-facing reports: one name column and the classes it belongs to.72 * Shared student list for teacher-facing reports: one name column and the classes it belongs to.
27 * With `cls` the read is scoped to that class: only its roster is fetched, and73 * With `cls` the read is scoped to that class: only its roster is fetched, and
@@ -30,20 +76,17 @@ async function readClassMembers(classId: string): Promise<ClassMember[]> {
30 */76 */
31 export async function getStudentDirectory(cls?: ClassGroup): Promise<StudentDirectoryRow[]> {77 export async function getStudentDirectory(cls?: ClassGroup): Promise<StudentDirectoryRow[]> {
32 if (cls) return sortByClass((await readClassMembers(cls.id)).map((member) => ({ person: member.user, classes: [cls] })));78 if (cls) return sortByClass((await readClassMembers(cls.id)).map((member) => ({ person: member.user, classes: [cls] })));
33- const [students, classes] = await Promise.all([79+ const [people, classes] = await Promise.all([students(), classList()]);
34- getUserSearch("", undefined, "student"),
35- getClasses({ limit: 200 }),
36- ]);
37 const byStudent = new Map<string, ClassGroup[]>();80 const byStudent = new Map<string, ClassGroup[]>();
38- const memberships = await Promise.all(81+ const memberships = await mapConcurrent(classes, FAN_OUT_LIMIT, async (cls) => ({
39- classes.items.map(async (cls) => ({ cls, members: (await getClassMembers(cls.id, { limit: 500 })).items })),82+ cls, members: await readClassMembers(cls.id).catch(() => [] as ClassMember[]),
40- );83+ }));
41 for (const { cls, members } of memberships) {84 for (const { cls, members } of memberships) {
42 for (const member of members) {85 for (const member of members) {
43 byStudent.set(member.user.id, [...(byStudent.get(member.user.id) ?? []), cls]);86 byStudent.set(member.user.id, [...(byStudent.get(member.user.id) ?? []), cls]);
44 }87 }
45 }88 }
46- return sortByClass(students.items.map((person) => ({ person, classes: byStudent.get(person.id) ?? [] })));89+ return sortByClass(people.map((person) => ({ person, classes: byStudent.get(person.id) ?? [] })));
47 }90 }
48 91
49 const collator = new Intl.Collator("tr", { numeric: true, sensitivity: "base" });92 const collator = new Intl.Collator("tr", { numeric: true, sensitivity: "base" });
src/pages/class-detail-page.tsxmodified+7 -0
@@ -1,4 +1,6 @@
1 import { For, Show, createEffect, createMemo, createSignal } from "solid-js";1 import { For, Show, createEffect, createMemo, createSignal } from "solid-js";
2+import { invalidateStudentDirectory } from "@/lib/student-directory";
3+import { invalidateSchoolWalk } from "@/lib/instance-labels";
2 import { createResource } from "@/lib/create-resource";4 import { createResource } from "@/lib/create-resource";
3 import { useLocation, useNavigate, useParams } from "@tanstack/solid-router";5 import { useLocation, useNavigate, useParams } from "@tanstack/solid-router";
4 import { Breadcrumbs } from "@/components/layout/breadcrumbs";6 import { Breadcrumbs } from "@/components/layout/breadcrumbs";
@@ -149,6 +151,10 @@ function ClassDetailContent() {
149 setPending(true);151 setPending(true);
150 try {152 try {
151 await fn();153 await fn();
154+ // Every write here changes a class, its members or its sections: drop
155+ // the shared per-tab rosters and section walk so other pages re-read.
156+ invalidateStudentDirectory();
157+ invalidateSchoolWalk();
152 if (successKey) setFlash(t(successKey as never));158 if (successKey) setFlash(t(successKey as never));
153 } catch (err) {159 } catch (err) {
154 setError(formatApiError(err));160 setError(formatApiError(err));
@@ -165,6 +171,7 @@ function ClassDetailContent() {
165 setPending(true);171 setPending(true);
166 try {172 try {
167 const result = await postClassBlueprintApply(id());173 const result = await postClassBlueprintApply(id());
174+ invalidateSchoolWalk();
168 await refresh(refetchCourses);175 await refresh(refetchCourses);
169 setSkipped(result.skipped);176 setSkipped(result.skipped);
170 if (result.skipped.length === 0) setFlash(t("classBlueprints.applied"));177 if (result.skipped.length === 0) setFlash(t("classBlueprints.applied"));
src/pages/classes-page.test.tsxmodified+13 -0
@@ -3,6 +3,7 @@ import type { JSX } from "solid-js";
3 import { afterEach, expect, test, vi } from "vitest";3 import { afterEach, expect, test, vi } from "vitest";
4 import ClassesPage from "@/pages/classes-page";4 import ClassesPage from "@/pages/classes-page";
5 import { PreferencesProvider } from "@/stores/preferences-context";5 import { PreferencesProvider } from "@/stores/preferences-context";
6+import { invalidateStudentDirectory } from "@/lib/student-directory";
6 7
7 const { getClasses, getClassMembers, postClass, getCourses, navigate } = vi.hoisted(() => ({8 const { getClasses, getClassMembers, postClass, getCourses, navigate } = vi.hoisted(() => ({
8 getClasses: vi.fn(),9 getClasses: vi.fn(),
@@ -38,6 +39,7 @@ const createdClass = { id: "c-new", creator: null, name: "9-A", grade_level: 9,
38 39
39 afterEach(() => {40 afterEach(() => {
40 cleanup();41 cleanup();
42+ invalidateStudentDirectory();
41 vi.clearAllMocks();43 vi.clearAllMocks();
42 });44 });
43 45
@@ -141,3 +143,14 @@ test("the grade filter narrows on the server and keeps every option listed", asy
141 fireEvent.pointerDown(screen.getByRole("button", { name: /Grade:/ }), { button: 0, pointerType: "mouse" });143 fireEvent.pointerDown(screen.getByRole("button", { name: /Grade:/ }), { button: 0, pointerType: "mouse" });
142 expect(await screen.findByRole("menuitem", { name: "Grade 10" })).toBeTruthy();144 expect(await screen.findByRole("menuitem", { name: "Grade 10" })).toBeTruthy();
143 });145 });
146+
147+test("shows class rows before member counts finish", async () => {
148+ const grade9 = { id: "c9", creator: null, name: "9-A", grade_level: 9, year: null, teacher: null };
149+ getClasses.mockResolvedValue({ items: [grade9], total: 1, limit: 200, offset: 0 });
150+ getClassMembers.mockImplementation(() => new Promise(() => {}));
151+
152+ render(() => <PreferencesProvider><ClassesPage /></PreferencesProvider>);
153+
154+ expect(await screen.findByRole("button", { name: /^9-A/ })).toBeTruthy();
155+ expect(getClassMembers).toHaveBeenCalled();
156+});
src/pages/classes-page.tsxmodified+12 -6
@@ -2,7 +2,7 @@ import { For, Show, Suspense, createMemo, createSignal } from "solid-js";
2 import type { ColumnDef } from "@tanstack/solid-table";2 import type { ColumnDef } from "@tanstack/solid-table";
3 import { createResource } from "@/lib/create-resource";3 import { createResource } from "@/lib/create-resource";
4 import { useNavigate } from "@tanstack/solid-router";4 import { useNavigate } from "@tanstack/solid-router";
5-import { deleteClassById, getClasses, getClassMembers, postClass, postClassBlueprintApply } from "@/api/classes";5+import { deleteClassById, getClasses, postClass, postClassBlueprintApply } from "@/api/classes";
6 import { getAcademicYears } from "@/api/academic-years";6 import { getAcademicYears } from "@/api/academic-years";
7 import { getCourses } from "@/api/courses";7 import { getCourses } from "@/api/courses";
8 import { getLimits } from "@/api/limits";8 import { getLimits } from "@/api/limits";
@@ -31,7 +31,8 @@ import { createFlash } from "@/lib/flash";
31 import { matchesSearch } from "@/lib/search-text";31 import { matchesSearch } from "@/lib/search-text";
32 import { personLabel } from "@/lib/person";32 import { personLabel } from "@/lib/person";
33 import { hasMinRole } from "@/lib/roles";33 import { hasMinRole } from "@/lib/roles";
34-import { compareClasses } from "@/lib/student-directory";34+import { classMemberCount, compareClasses, invalidateStudentDirectory } from "@/lib/student-directory";
35+import { invalidateSchoolWalk } from "@/lib/instance-labels";
35 import { createUrlString } from "@/lib/url-state";36 import { createUrlString } from "@/lib/url-state";
36 import { useAuth } from "@/stores/auth-context";37 import { useAuth } from "@/stores/auth-context";
37 import { useT } from "@/stores/preferences-context";38 import { useT } from "@/stores/preferences-context";
@@ -110,7 +111,7 @@ function ClassesContent() {
110 const [memberCounts] = createResource(memberCountIds, async (ids) => {111 const [memberCounts] = createResource(memberCountIds, async (ids) => {
111 const entries = await mapConcurrent(ids, FAN_OUT_LIMIT, async (id) => {112 const entries = await mapConcurrent(ids, FAN_OUT_LIMIT, async (id) => {
112 try {113 try {
113- return [id, (await getClassMembers(id, { limit: 1 })).total] as const;114+ return [id, await classMemberCount(id)] as const;
114 } catch {115 } catch {
115 return [id, null] as const;116 return [id, null] as const;
116 }117 }
@@ -126,7 +127,7 @@ function ClassesContent() {
126 // A fresh array once the member counts land: the table redraws a row only127 // A fresh array once the member counts land: the table redraws a row only
127 // when its data changes, so the counts would otherwise stay "—".128 // when its data changes, so the counts would otherwise stay "—".
128 const rows = createMemo(() => {129 const rows = createMemo(() => {
129- memberCounts();130+ memberCounts.latest;
130 return gradeFiltered().slice();131 return gradeFiltered().slice();
131 });132 });
132 const openClass = (cls: ClassGroup) => void navigate({ to: "/management/classes/$id", params: { id: cls.id } });133 const openClass = (cls: ClassGroup) => void navigate({ to: "/management/classes/$id", params: { id: cls.id } });
@@ -137,6 +138,8 @@ function ClassesContent() {
137 const [deleteTarget, setDeleteTarget] = createSignal<ClassGroup | null>(null);138 const [deleteTarget, setDeleteTarget] = createSignal<ClassGroup | null>(null);
138 const [rowError, setRowError] = createSignal("");139 const [rowError, setRowError] = createSignal("");
139 const refreshList = async () => {140 const refreshList = async () => {
141+ invalidateStudentDirectory();
142+ invalidateSchoolWalk();
140 // The grade dropdown reads its own unfiltered page, so a create, edit or143 // The grade dropdown reads its own unfiltered page, so a create, edit or
141 // delete that changes which rungs have classes must refresh it too.144 // delete that changes which rungs have classes must refresh it too.
142 try { await Promise.all([refetch(), refetchGrades()]); } catch { /* stale rows until the next load */ }145 try { await Promise.all([refetch(), refetchGrades()]); } catch { /* stale rows until the next load */ }
@@ -149,6 +152,7 @@ function ClassesContent() {
149 setPending(true);152 setPending(true);
150 try {153 try {
151 const result = await postClassBlueprintApply(cls.id);154 const result = await postClassBlueprintApply(cls.id);
155+ invalidateSchoolWalk();
152 if (result.skipped.length === 0) {156 if (result.skipped.length === 0) {
153 setFlash(t("classBlueprints.applied"));157 setFlash(t("classBlueprints.applied"));
154 return;158 return;
@@ -207,7 +211,7 @@ function ClassesContent() {
207 },211 },
208 {212 {
209 id: "students",213 id: "students",
210- accessorFn: (row) => memberCounts()?.get(row.id) ?? -1,214+ accessorFn: (row) => memberCounts.latest?.get(row.id) ?? -1,
211 header: t("nav.studentsRoster"),215 header: t("nav.studentsRoster"),
212 size: 130,216 size: 130,
213 minSize: 100,217 minSize: 100,
@@ -219,7 +223,7 @@ function ClassesContent() {
219 headerInfo: memberCountsCapped() ? t("classGroups.memberCountCapped", { cap: MEMBER_COUNT_FETCH_CAP }) : undefined,223 headerInfo: memberCountsCapped() ? t("classGroups.memberCountCapped", { cap: MEMBER_COUNT_FETCH_CAP }) : undefined,
220 },224 },
221 cell: (cell) => {225 cell: (cell) => {
222- const count = memberCounts()?.get(cell.row.original.id);226+ const count = memberCounts.latest?.get(cell.row.original.id);
223 return count == null ? <span class="text-text-subtle">—</span> : t("classGroups.studentsCount", { count: String(count) });227 return count == null ? <span class="text-text-subtle">—</span> : t("classGroups.studentsCount", { count: String(count) });
224 },228 },
225 },229 },
@@ -274,6 +278,8 @@ function ClassesContent() {
274 year: yearId() || undefined,278 year: yearId() || undefined,
275 teacher_id: teacherId() || undefined,279 teacher_id: teacherId() || undefined,
276 });280 });
281+ invalidateStudentDirectory();
282+ invalidateSchoolWalk();
277 setName(""); setGradeLevel(null); setYearId(""); setTeacherId(""); setShowForm(false);283 setName(""); setGradeLevel(null); setYearId(""); setTeacherId(""); setShowForm(false);
278 // Reloading the list is housekeeping for a page we are leaving anyway: a284 // Reloading the list is housekeeping for a page we are leaving anyway: a
279 // failure here used to be reported as if the class had not been created,285 // failure here used to be reported as if the class had not been created,
src/pages/dashboard-page.test.tsxmodified+72 -6
@@ -3,7 +3,7 @@ import type { JSX } from "solid-js";
3 import DashboardPage from "@/pages/dashboard-page";3 import DashboardPage from "@/pages/dashboard-page";
4 import { PreferencesProvider } from "@/stores/preferences-context";4 import { PreferencesProvider } from "@/stores/preferences-context";
5 5
6-const { navigate, authUser, schoolModules, calls, refuseExams, failExams } = vi.hoisted(() => ({6+const { navigate, authUser, schoolModules, calls, refuseExams, failExams, extraExams, classRows } = vi.hoisted(() => ({
7 navigate: vi.fn(),7 navigate: vi.fn(),
8 authUser: { authenticated: true, role: "student" },8 authUser: { authenticated: true, role: "student" },
9 // null = module state unknown (fail open, everything shown).9 // null = module state unknown (fail open, everything shown).
@@ -11,6 +11,8 @@ const { navigate, authUser, schoolModules, calls, refuseExams, failExams } = vi.
11 calls: [] as string[],11 calls: [] as string[],
12 refuseExams: { on: false },12 refuseExams: { on: false },
13 failExams: { times: 0 },13 failExams: { times: 0 },
14+ extraExams: [] as { id: string; title: string; class_course: string; draft: boolean; starts_at: number; ends_at: number }[],
15+ classRows: [] as { id: string; name: string }[],
14 }));16 }));
15 17
16 vi.mock("@tanstack/solid-router", () => ({18 vi.mock("@tanstack/solid-router", () => ({
@@ -142,9 +144,10 @@ vi.mock("@/api/exams", async () => {
142 starts_at: null,144 starts_at: null,
143 ends_at: null,145 ends_at: null,
144 },146 },
147+ ...extraExams,
145 ]);148 ]);
146 },149 },
147- getExamStatistics: async (examId: string) => ({150+ getExamStatistics: async (examId: string) => (calls.push(`stats:${examId}`), {
148 exam: examId,151 exam: examId,
149 graded: 12,152 graded: 12,
150 average: 74.5,153 average: 74.5,
@@ -166,7 +169,7 @@ vi.mock("@/api/pomodoro", () => ({
166 }),169 }),
167 }));170 }));
168 vi.mock("@/api/events", () => ({171 vi.mock("@/api/events", () => ({
169- getEvents: async () => page([172+ getEvents: async (params?: { ends_after?: number }) => (calls.push(params?.ends_after ? "events:upcoming" : "events:history"), page([
170 {173 {
171 id: "event-1",174 id: "event-1",
172 title: "Event deadline",175 title: "Event deadline",
@@ -174,7 +177,7 @@ vi.mock("@/api/events", () => ({
174 ends_at: now + 4_000,177 ends_at: now + 4_000,
175 },178 },
176 { id: "event-past", title: "Past event", starts_at: now - 5 * DAY, ends_at: now - 5 * DAY + 1_000 },179 { id: "event-past", title: "Past event", starts_at: now - 5 * DAY, ends_at: now - 5 * DAY + 1_000 },
177- ]),180+ ])),
178 }));181 }));
179 vi.mock("@/api/homework", () => ({182 vi.mock("@/api/homework", () => ({
180 getHomeworkSubmissions: async () => page([183 getHomeworkSubmissions: async () => page([
@@ -215,9 +218,9 @@ vi.mock("@/api/meals", () => ({
215 vi.mock("@/api/classes", () => ({218 vi.mock("@/api/classes", () => ({
216 getMyClasses: async () => page([{ id: "class-1", name: "9-A" }]),219 getMyClasses: async () => page([{ id: "class-1", name: "9-A" }]),
217 getClassesByUserId: async () => page([]),220 getClassesByUserId: async () => page([]),
218- getClasses: async () => page([]),221+ getClasses: async () => page(classRows),
219 getClassById: async () => ({ id: "class-1", name: "9-A" }),222 getClassById: async () => ({ id: "class-1", name: "9-A" }),
220- getClassMembers: async () => page([]),223+ getClassMembers: async (id: string) => (calls.push(`members:${id}`), { ...page([]), total: Number(id.split("-")[1]) }),
221 }));224 }));
222 vi.mock("@/api/academic-years", () => ({225 vi.mock("@/api/academic-years", () => ({
223 getAcademicYears: async () => page([{ id: "y-1", name: "2026-2027" }]),226 getAcademicYears: async () => page([{ id: "y-1", name: "2026-2027" }]),
@@ -235,6 +238,9 @@ afterEach(() => {
235 calls.length = 0;238 calls.length = 0;
236 refuseExams.on = false;239 refuseExams.on = false;
237 failExams.times = 0;240 failExams.times = 0;
241+ extraExams.length = 0;
242+ classRows.length = 0;
243+ vi.unstubAllGlobals();
238 });244 });
239 245
240 function renderDashboard(role: string) {246 function renderDashboard(role: string) {
@@ -246,6 +252,66 @@ function renderDashboard(role: string) {
246 ));252 ));
247 }253 }
248 254
255+function observeOnDemand() {
256+ const targets = new Map<Element, IntersectionObserverCallback>();
257+ class Observer {
258+ constructor(private callback: IntersectionObserverCallback) {}
259+ observe(target: Element) { targets.set(target, this.callback); }
260+ disconnect() {}
261+ }
262+ vi.stubGlobal("IntersectionObserver", Observer);
263+ return (target: Element) => {
264+ const callback = targets.get(target);
265+ expect(callback).toBeTruthy();
266+ callback!([{ isIntersecting: true, target } as IntersectionObserverEntry], {} as IntersectionObserver);
267+ };
268+}
269+
270+test("teacher statistics wait for the chart and read only six recent exams", async () => {
271+ const reveal = observeOnDemand();
272+ extraExams.push(...Array.from({ length: 20 }, (_, index) => ({
273+ id: `extra-${index}`,
274+ title: `Exam ${index}`,
275+ class_course: "instance-1",
276+ draft: false,
277+ starts_at: now - (index + 1) * DAY,
278+ ends_at: now - (index + 1) * DAY + 1_000,
279+ })));
280+ renderDashboard("manager");
281+
282+ await screen.findByRole("heading", { name: "Upcoming deadlines" });
283+ expect(calls.filter((call) => call.startsWith("stats:"))).toHaveLength(0);
284+ reveal(document.querySelector("[data-dashboard-trend]")!);
285+ await waitFor(() => expect(calls.filter((call) => call.startsWith("stats:"))).toHaveLength(6));
286+ expect(calls).toContain("stats:extra-0");
287+ expect(calls).not.toContain("stats:extra-19");
288+ expect(await screen.findByText("Average of recent exams, by course.")).toBeTruthy();
289+});
290+
291+test("admin class sizes wait for their card and keep the size ranking", async () => {
292+ const reveal = observeOnDemand();
293+ classRows.push(...Array.from({ length: 10 }, (_, index) => ({ id: `class-${index + 1}`, name: `9-${index + 1}` })));
294+ renderDashboard("admin");
295+
296+ const column = await screen.findByText("Classes");
297+ expect(calls.filter((call) => call.startsWith("members:"))).toHaveLength(0);
298+ reveal(column.closest("div")!);
299+ await waitFor(() => expect(calls.filter((call) => call.startsWith("members:"))).toHaveLength(10));
300+ await waitFor(() => expect(within(column.closest("div")!).getByText("9-10")).toBeTruthy());
301+ expect(within(column.closest("div")!).getByText("9-9")).toBeTruthy();
302+});
303+
304+test("past events wait for the below-fold heatmap", async () => {
305+ const reveal = observeOnDemand();
306+ renderDashboard("manager");
307+
308+ await waitFor(() => expect(calls).toContain("events:upcoming"));
309+ expect(calls).not.toContain("events:history");
310+ reveal(document.querySelector("[data-dashboard-heatmap]")!);
311+ await waitFor(() => expect(calls).toContain("events:history"));
312+ expect(await screen.findByText("School activity")).toBeTruthy();
313+});
314+
249 test("logged-out visitor redirects before dashboard reads user role", () => {315 test("logged-out visitor redirects before dashboard reads user role", () => {
250 authUser.authenticated = false;316 authUser.authenticated = false;
251 renderDashboard("student");317 renderDashboard("student");
src/pages/dashboard-page.tsxmodified+52 -24
@@ -1,4 +1,4 @@
1-import { For, Show, Suspense, createEffect, createMemo, createSignal, type Component } from "solid-js";1+import { For, Show, Suspense, createEffect, createMemo, createSignal, onCleanup, type Component } from "solid-js";
2 import { createBoardResources } from "@/lib/board-resources";2 import { createBoardResources } from "@/lib/board-resources";
3 import { useNavigate } from "@tanstack/solid-router";3 import { useNavigate } from "@tanstack/solid-router";
4 import type { ColumnDef } from "@tanstack/solid-table";4 import type { ColumnDef } from "@tanstack/solid-table";
@@ -74,7 +74,7 @@ const HEATMAP_WEEKS = 26;
74 * `/exams/{id}/statistics` call — there is no bulk statistics endpoint — so the74 * `/exams/{id}/statistics` call — there is no bulk statistics endpoint — so the
75 * homepage keeps a bounded recent history.75 * homepage keeps a bounded recent history.
76 */76 */
77-const TREND_EXAM_CAP = 20;77+const TREND_EXAM_CAP = 6;
78 /** Marks plotted in a student's own trend. */78 /** Marks plotted in a student's own trend. */
79 const TREND_MARK_CAP = 20;79 const TREND_MARK_CAP = 20;
80 /** Classes whose roster size the admin "Şubeler" quick links read. */80 /** Classes whose roster size the admin "Şubeler" quick links read. */
@@ -159,6 +159,21 @@ function PanelSkeleton() {
159 );159 );
160 }160 }
161 161
162+function observeWhenVisible(el: Element, activate: () => void) {
163+ if (typeof IntersectionObserver === "undefined") {
164+ activate();
165+ return;
166+ }
167+ const observer = new IntersectionObserver((entries) => {
168+ if (entries.some((entry) => entry.isIntersecting)) {
169+ observer.disconnect();
170+ activate();
171+ }
172+ }, { rootMargin: "160px" });
173+ observer.observe(el);
174+ onCleanup(() => observer.disconnect());
175+}
176+
162 function DashboardContent() {177 function DashboardContent() {
163 // Every panel reads its own source; one failed request must not take the178 // Every panel reads its own source; one failed request must not take the
164 // others down with it (see createBoardResources).179 // others down with it (see createBoardResources).
@@ -185,6 +200,10 @@ function DashboardContent() {
185 // Server-anchored time (local fallback). Declared before the resources that200 // Server-anchored time (local fallback). Declared before the resources that
186 // read it in their fetchers.201 // read it in their fetchers.
187 const now = () => clock()?.now ?? Date.now();202 const now = () => clock()?.now ?? Date.now();
203+ const [trendVisible, setTrendVisible] = createSignal(false);
204+ const [heatmapVisible, setHeatmapVisible] = createSignal(false);
205+ const [classLinksVisible, setClassLinksVisible] = createSignal(false);
206+ const [childHomeworkVisible, setChildHomeworkVisible] = createSignal(false);
188 // Unpaged: the backend has no `kind` filter, so a "courses" count that207 // Unpaged: the backend has no `kind` filter, so a "courses" count that
189 // excludes studies and clubs has to be counted here over the whole list.208 // excludes studies and clubs has to be counted here over the whole list.
190 const [courses] = createResource(209 const [courses] = createResource(
@@ -192,7 +211,7 @@ function DashboardContent() {
192 () => quiet(getCourses()),211 () => quiet(getCourses()),
193 );212 );
194 const courseTitleOf = (courseId: string) => courses()?.items.find((course) => course.id === courseId)?.title ?? "…";213 const courseTitleOf = (courseId: string) => courses()?.items.find((course) => course.id === courseId)?.title ?? "…";
195- const courseCount = () => (courses.error ? "—" : String((courses()?.items ?? []).filter((course) => course.kind === "course").length));214+ const courseCount = () => courses()?.items ? String(courses()!.items.filter((course) => course.kind === "course").length) : "—";
196 // `/events` has no role gate — a parent-teacher conference is a real PAR-01215 // `/events` has no role gate — a parent-teacher conference is a real PAR-01
197 // "Yaklaşan" item, so parent reads this too (unlike `exams`/`homework`216 // "Yaklaşan" item, so parent reads this too (unlike `exams`/`homework`
198 // below, which really are course-scoped and out of a parent's reach).217 // below, which really are course-scoped and out of a parent's reach).
@@ -266,13 +285,13 @@ function DashboardContent() {
266 // `ends_after` window the deadlines table needs. The heatmap looks backwards285 // `ends_after` window the deadlines table needs. The heatmap looks backwards
267 // and there is no "before" filter, so past events need their own read.286 // and there is no "before" filter, so past events need their own read.
268 const [pastEvents] = createResource(287 const [pastEvents] = createResource(
269- () => hasMinRole(role(), "teacher") && on("events") ? true : null,288+ () => heatmapVisible() && hasMinRole(role(), "teacher") && on("events") ? true : null,
270 () => getEvents({ limit: 100 }).catch(() => null),289 () => getEvents({ limit: 100 }).catch(() => null),
271 );290 );
272 // Success trend source for teacher+. Exam statistics are grader-only, so this291 // Success trend source for teacher+. Exam statistics are grader-only, so this
273 // never runs for a student or parent — they would get a 403.292 // never runs for a student or parent — they would get a 403.
274 const [examStats] = createResource(293 const [examStats] = createResource(
275- () => hasMinRole(role(), "teacher") ? exams.latest?.items ?? null : null,294+ () => trendVisible() && hasMinRole(role(), "teacher") ? exams.latest?.items ?? null : null,
276 async (items) => {295 async (items) => {
277 // An exam with no schedule (an untimed, paper or imported one) still296 // An exam with no schedule (an untimed, paper or imported one) still
278 // gets graded — skipping unscheduled exams left the charts empty while297 // gets graded — skipping unscheduled exams left the charts empty while
@@ -396,18 +415,18 @@ function DashboardContent() {
396 () => (isAdminHome() ? true : null),415 () => (isAdminHome() ? true : null),
397 () => getUsers({ limit: 30 }),416 () => getUsers({ limit: 30 }),
398 );417 );
399- // "Şubeler" quick links: the classes with the most students, each labelled418+ // Class rows have no member count. Show the first two names immediately;
400- // with its roster size. A class carries no member count, so each one costs419+ // rank by roster size once the quick-link card enters the viewport.
401- // a `limit=1` roster read for its `total` — capped at CLASS_LINK_CAP classes
402- // (taken in name order) so a large school does not fan out on the homepage.
403 const [recentClasses] = createResource(420 const [recentClasses] = createResource(
404 () => (isAdminHome() && on("classes") ? true : null),421 () => (isAdminHome() && on("classes") ? true : null),
405- async () => {422+ () => quiet(getClasses({ limit: 200 })),
406- const page = await quiet(getClasses({ limit: 200 }));423+ );
407- if (!page) return null;424+ const classCandidates = createMemo(() => [...(recentClasses.latest?.items ?? [])]
408- const candidates = [...page.items]425+ .sort((a, b) => a.name.localeCompare(b.name, "tr", { numeric: true }))
409- .sort((a, b) => a.name.localeCompare(b.name, "tr", { numeric: true }))426+ .slice(0, CLASS_LINK_CAP));
410- .slice(0, CLASS_LINK_CAP);427+ const [classCounts] = createResource(
428+ () => classLinksVisible() && classCandidates().length > 0 ? classCandidates() : null,
429+ async (candidates) => {
411 const counted = await mapConcurrent(candidates, FAN_OUT_LIMIT, async (cls) => ({430 const counted = await mapConcurrent(candidates, FAN_OUT_LIMIT, async (cls) => ({
412 cls,431 cls,
413 students: await getClassMembers(cls.id, { limit: 1 }).then((members) => members.total, () => null),432 students: await getClassMembers(cls.id, { limit: 1 }).then((members) => members.total, () => null),
@@ -429,10 +448,10 @@ function DashboardContent() {
429 })),448 })),
430 );449 );
431 const classQuickLinks = createMemo<QuickLinkRow[]>(() =>450 const classQuickLinks = createMemo<QuickLinkRow[]>(() =>
432- (recentClasses() ?? []).map((row) => ({451+ (classCounts.latest ?? classCandidates().slice(0, 2).map((cls) => ({ cls, students: null as number | null }))).map((row) => ({
433 id: row.cls.id,452 id: row.cls.id,
434 primary: row.cls.name,453 primary: row.cls.name,
435- secondary: row.students == null ? undefined : t("classGroups.studentsCount", { count: row.students }),454+ secondary: row.students == null ? "—" : t("classGroups.studentsCount", { count: row.students }),
436 Icon: IconBook,455 Icon: IconBook,
437 })),456 })),
438 );457 );
@@ -497,7 +516,7 @@ function DashboardContent() {
497 516
498 /** A stat over a list total; a source that failed shows "—", never a made-up 0. */517 /** A stat over a list total; a source that failed shows "—", never a made-up 0. */
499 const countOf = (source: { (): { total: number } | null | undefined; error: unknown }) =>518 const countOf = (source: { (): { total: number } | null | undefined; error: unknown }) =>
500- source.error ? "—" : String(source()?.total ?? 0);519+ source()?.total == null ? "—" : String(source()!.total);
501 const allStats = createMemo<StatCardData[]>(() => {520 const allStats = createMemo<StatCardData[]>(() => {
502 const r = role();521 const r = role();
503 if (r === "student") {522 if (r === "student") {
@@ -843,6 +862,7 @@ function DashboardContent() {
843 illustration="courses"862 illustration="courses"
844 rows={classQuickLinks()}863 rows={classQuickLinks()}
845 empty={t("dashboard.quicklinks.empty")}864 empty={t("dashboard.quicklinks.empty")}
865+ onVisible={() => setClassLinksVisible(true)}
846 onOpen={(row) => navigate({ to: "/management/classes/$id", params: { id: row.id } })}866 onOpen={(row) => navigate({ to: "/management/classes/$id", params: { id: row.id } })}
847 />867 />
848 </Show>868 </Show>
@@ -974,7 +994,8 @@ function DashboardContent() {
974 </div>994 </div>
975 <div class="grid grid-cols-1 gap-3 lg:grid-cols-3">995 <div class="grid grid-cols-1 gap-3 lg:grid-cols-3">
976 <Show when={on("exams")}>996 <Show when={on("exams")}>
977- <div class="grid grid-cols-1 gap-3 sm:grid-cols-2 lg:col-span-2">997+ <div ref={(el) => observeWhenVisible(el, () => setTrendVisible(true))} data-dashboard-trend class="grid grid-cols-1 gap-3 sm:grid-cols-2 lg:col-span-2">
998+ <Show when={trendVisible() && (examStats.latest != null || !!examStats.error)} fallback={<PanelSkeleton />}>
978 <ChartLine999 <ChartLine
979 class="sm:col-span-2"1000 class="sm:col-span-2"
980 title={t("dashboard.successTrend")}1001 title={t("dashboard.successTrend")}
@@ -990,6 +1011,7 @@ function DashboardContent() {
990 maxScale={100}1011 maxScale={100}
991 itemsPerPage={5}1012 itemsPerPage={5}
992 />1013 />
1014+ </Show>
993 </div>1015 </div>
994 </Show>1016 </Show>
995 <Show when={on("appointments")}>1017 <Show when={on("appointments")}>
@@ -1027,7 +1049,8 @@ function DashboardContent() {
1027 1049
1028 <Suspense fallback={<PanelSkeleton />}>1050 <Suspense fallback={<PanelSkeleton />}>
1029 <Show when={(role() === "manager" || role() === "admin") && on("exams")}>1051 <Show when={(role() === "manager" || role() === "admin") && on("exams")}>
1030- <div class="grid grid-cols-1 gap-3 lg:grid-cols-3">1052+ <div ref={(el) => observeWhenVisible(el, () => setTrendVisible(true))} data-dashboard-trend class="grid grid-cols-1 gap-3 lg:grid-cols-3">
1053+ <Show when={trendVisible() && (examStats.latest != null || !!examStats.error)} fallback={<PanelSkeleton />}>
1031 <ChartLine1054 <ChartLine
1032 class="lg:col-span-2"1055 class="lg:col-span-2"
1033 title={t("dashboard.successTrend")}1056 title={t("dashboard.successTrend")}
@@ -1042,6 +1065,7 @@ function DashboardContent() {
1042 maxScale={100}1065 maxScale={100}
1043 itemsPerPage={5}1066 itemsPerPage={5}
1044 />1067 />
1068+ </Show>
1045 </div>1069 </div>
1046 </Show>1070 </Show>
1047 </Suspense>1071 </Suspense>
@@ -1137,9 +1161,11 @@ function DashboardContent() {
1137 {/* PAR progress: the child's homework report (a parent-readable1161 {/* PAR progress: the child's homework report (a parent-readable
1138 route) as overdue / due-this-week; marks-based progress still1162 route) as overdue / due-this-week; marks-based progress still
1139 has no parent-facing trend. */}1163 has no parent-facing trend. */}
1140- <Show when={on("homework") && selectedChildId() && clock()}>1164+ <div ref={(el) => observeWhenVisible(el, () => setChildHomeworkVisible(true))}>
1141- <ChildHomeworkPanel childId={selectedChildId()} now={clock()!.now} />1165+ <Show when={childHomeworkVisible() && on("homework") && selectedChildId() && clock()}>
1142- </Show>1166+ <ChildHomeworkPanel childId={selectedChildId()} now={clock()!.now} />
1167+ </Show>
1168+ </div>
1143 </Show>1169 </Show>
1144 </Suspense>1170 </Suspense>
1145 1171
@@ -1159,8 +1185,9 @@ function DashboardContent() {
1159 </section>1185 </section>
1160 </Suspense>1186 </Suspense>
1161 1187
1188+ <div ref={(el) => observeWhenVisible(el, () => setHeatmapVisible(true))} data-dashboard-heatmap>
1162 <Suspense fallback={<PanelSkeleton />}>1189 <Suspense fallback={<PanelSkeleton />}>
1163- <Show when={!heatmapIsFocus() || on("pomodoro")}>1190+ <Show when={heatmapVisible() && (!heatmapIsFocus() || on("pomodoro")) && (role() === "student" || role() === "parent" || !on("events") || pastEvents.state === "ready")} fallback={<PanelSkeleton />}>
1164 <ChartHeatmap1191 <ChartHeatmap
1165 title={heatmapIsFocus() ? t("dashboard.focusHeatmap") : t("dashboard.activityHeatmap")}1192 title={heatmapIsFocus() ? t("dashboard.focusHeatmap") : t("dashboard.activityHeatmap")}
1166 subtitle={heatmapIsFocus() ? t("dashboard.focusHeatmapDesc") : t("dashboard.activityHeatmapDesc")}1193 subtitle={heatmapIsFocus() ? t("dashboard.focusHeatmapDesc") : t("dashboard.activityHeatmapDesc")}
@@ -1185,6 +1212,7 @@ function DashboardContent() {
1185 />1212 />
1186 </Show>1213 </Show>
1187 </Suspense>1214 </Suspense>
1215+ </div>
1188 </Suspense>1216 </Suspense>
1189 </div>1217 </div>
1190 );1218 );
src/pages/payments-page.test.tsxadded+84 -0
@@ -0,0 +1,84 @@
1+import { cleanup, render, screen, waitFor } from "@solidjs/testing-library";
2+import { afterEach, expect, test, vi } from "vitest";
3+import PaymentsPage from "@/pages/payments-page";
4+import { PreferencesProvider } from "@/stores/preferences-context";
5+
6+const { getUserSearch, getPaymentBalanceByUserId, getPaymentPlans, getPaymentLedgerByUserId } = vi.hoisted(() => ({
7+ getUserSearch: vi.fn(),
8+ getPaymentBalanceByUserId: vi.fn(),
9+ getPaymentPlans: vi.fn(),
10+ getPaymentLedgerByUserId: vi.fn(),
11+}));
12+vi.mock("@tanstack/solid-router", () => ({
13+ Link: () => null,
14+ Navigate: () => null,
15+ useLocation: () => () => ({ pathname: "/management/payments", search: {} }),
16+ useNavigate: () => vi.fn(),
17+}));
18+vi.mock("@/stores/auth-context", () => ({
19+ useAuth: () => ({ user: () => ({ id: "manager", role: "manager" }), loading: () => false, error: () => null }),
20+}));
21+vi.mock("@/api/users", () => ({ getUserSearch, getUserProfile: vi.fn() }));
22+vi.mock("@/api/payments", () => ({
23+ getPaymentBalanceByUserId,
24+ getPaymentPlans,
25+ getPaymentLedgerByUserId,
26+ getPaymentStatementByUserId: vi.fn(),
27+ getPlanAssignments: vi.fn(),
28+ deletePaymentPlanById: vi.fn(),
29+ patchPaymentPlanById: vi.fn(),
30+ postPaymentCredit: vi.fn(),
31+ postPaymentPlan: vi.fn(),
32+ postPaymentRefund: vi.fn(),
33+ postPaymentReversal: vi.fn(),
34+ postPlanAssignment: vi.fn(),
35+}));
36+
37+let observed: Element[] = [];
38+let observers: { callback: IntersectionObserverCallback; elements: Element[] }[] = [];
39+const originalObserver = globalThis.IntersectionObserver;
40+
41+afterEach(() => {
42+ cleanup();
43+ vi.clearAllMocks();
44+ observed = [];
45+ observers = [];
46+ globalThis.IntersectionObserver = originalObserver;
47+});
48+
49+test("student rows paint before balances; only visible rows request a balance", async () => {
50+ globalThis.IntersectionObserver = class {
51+ private entry: { callback: IntersectionObserverCallback; elements: Element[] };
52+ constructor(cb: IntersectionObserverCallback) {
53+ this.entry = { callback: cb, elements: [] };
54+ observers.push(this.entry);
55+ }
56+ observe(element: Element) { observed.push(element); this.entry.elements.push(element); }
57+ unobserve() {}
58+ disconnect() {}
59+ } as unknown as typeof IntersectionObserver;
60+ getUserSearch.mockResolvedValue({ items: [
61+ { id: "a", username: "ada", display_name: "Ada" },
62+ { id: "b", username: "bora", display_name: "Bora" },
63+ ], total: 2 });
64+ getPaymentPlans.mockResolvedValue({ items: [] });
65+ getPaymentBalanceByUserId.mockResolvedValue({ balance_minor: -1000 });
66+
67+ const view = render(() => <PreferencesProvider><PaymentsPage /></PreferencesProvider>);
68+ expect(await screen.findByText("Ada")).toBeTruthy();
69+ expect(screen.getByText("Bora")).toBeTruthy();
70+ expect(getPaymentBalanceByUserId).not.toHaveBeenCalled();
71+ expect(view.container.querySelectorAll(".animate-pulse").length).toBeGreaterThan(0);
72+ expect(getPaymentLedgerByUserId).not.toHaveBeenCalled();
73+ const first = observed.find((element) => (element as HTMLElement).dataset.studentId === "a");
74+ expect(first).toBeTruthy();
75+ const observer = observers.find((entry) => entry.elements.includes(first!));
76+ expect(observer).toBeTruthy();
77+
78+ observer!.callback([{ target: first!, isIntersecting: true } as IntersectionObserverEntry], {} as IntersectionObserver);
79+ await waitFor(() => expect(getPaymentBalanceByUserId).toHaveBeenCalledTimes(1));
80+ await waitFor(() => expect(view.container.textContent).toContain("In debt"));
81+ expect(getPaymentBalanceByUserId).toHaveBeenCalledWith("a");
82+ observer!.callback([{ target: first!, isIntersecting: true } as IntersectionObserverEntry], {} as IntersectionObserver);
83+ expect(getPaymentBalanceByUserId).toHaveBeenCalledTimes(1);
84+});
src/pages/payments-page.tsxmodified+81 -36
@@ -50,7 +50,7 @@ import { formatDate, formatDateTime } from "@/lib/format";
50 import { formatTry } from "@/lib/meals";50 import { formatTry } from "@/lib/meals";
51 import { PAYMENT_METHOD_KEYS, sortStatementEntries, statementStatus } from "@/lib/payments";51 import { PAYMENT_METHOD_KEYS, sortStatementEntries, statementStatus } from "@/lib/payments";
52 import { matchesSearch } from "@/lib/search-text";52 import { matchesSearch } from "@/lib/search-text";
53-import { FAN_OUT_LIMIT, mapConcurrent } from "@/lib/map-concurrent";53+import { FAN_OUT_LIMIT } from "@/lib/map-concurrent";
54 import { personLabel } from "@/lib/person";54 import { personLabel } from "@/lib/person";
55 import { usePreferences, useT } from "@/stores/preferences-context";55 import { usePreferences, useT } from "@/stores/preferences-context";
56 56
@@ -79,8 +79,6 @@ function dateInputToMs(value: string): number | null {
79 }79 }
80 80
81 type LineAction = { line: PaymentLine; kind: "refund" | "reverse" };81 type LineAction = { line: PaymentLine; kind: "refund" | "reverse" };
82-type PaymentStudentRow = PersonRef & { balance_minor: number | null };
83-
84 export default function PaymentsPage() {82 export default function PaymentsPage() {
85 return (83 return (
86 <RouteGuard minRole="manager">84 <RouteGuard minRole="manager">
@@ -189,24 +187,61 @@ function PaymentsContent() {
189 setSelectedStudent((prev) => (prev?.id === routeId ? prev : { id: routeId, username: routeId, display_name: null }));187 setSelectedStudent((prev) => (prev?.id === routeId ? prev : { id: routeId, username: routeId, display_name: null }));
190 });188 });
191 189
192- // The backend has no bulk balance endpoint. Fetch only the visible page so190+ const [balances, setBalances] = createSignal<Record<string, number | null | undefined>>({});
193- // status/balance never disappear on schools with more than 200 students.191+ const requestedBalances = new Set<string>();
194- const [paymentStudentRows] = createResource(192+ const balanceQueue: string[] = [];
195- () => {193+ let activeBalances = 0;
196- const users = pagedStudents();194+ let disposed = false;
197- return users.length > 0 ? users : null;195+ const drainBalances = () => {
198- },196+ while (activeBalances < FAN_OUT_LIMIT && balanceQueue.length > 0) {
199- async (users): Promise<PaymentStudentRow[]> =>197+ const id = balanceQueue.shift()!;
200- mapConcurrent(users, FAN_OUT_LIMIT, async (user) => {198+ activeBalances++;
201- try {199+ void getPaymentBalanceByUserId(id)
202- return { ...user, balance_minor: (await getPaymentBalanceByUserId(user.id)).balance_minor };200+ .then((balance) => {
203- } catch {201+ if (!disposed) setBalances((prev) => ({ ...prev, [id]: balance.balance_minor }));
204- return { ...user, balance_minor: null };202+ })
205- }203+ .catch(() => {
206- }),204+ if (!disposed) setBalances((prev) => ({ ...prev, [id]: null }));
207- );205+ })
206+ .finally(() => {
207+ activeBalances--;
208+ if (!disposed) drainBalances();
209+ });
210+ }
211+ };
212+ const requestBalance = (id: string) => {
213+ if (requestedBalances.has(id)) return;
214+ requestedBalances.add(id);
215+ balanceQueue.push(id);
216+ drainBalances();
217+ };
218+ const invalidateBalance = (id: string) => {
219+ requestedBalances.delete(id);
220+ setBalances((prev) => ({ ...prev, [id]: undefined }));
221+ };
222+ let balanceObserver: IntersectionObserver | undefined;
223+ const observeBalance = (element: HTMLElement, id: string) => {
224+ if (requestedBalances.has(id)) return;
225+ if (typeof IntersectionObserver === "undefined") {
226+ requestBalance(id);
227+ return;
228+ }
229+ balanceObserver ??= new IntersectionObserver((items) => {
230+ for (const item of items) {
231+ if (!item.isIntersecting) continue;
232+ balanceObserver?.unobserve(item.target);
233+ requestBalance((item.target as HTMLElement).dataset.studentId!);
234+ }
235+ });
236+ element.dataset.studentId = id;
237+ balanceObserver.observe(element);
238+ };
239+ onCleanup(() => {
240+ disposed = true;
241+ balanceObserver?.disconnect();
242+ });
208 243
209- const studentColumns = createMemo<ColumnDef<PaymentStudentRow>[]>(() => [244+ const studentColumns = createMemo<ColumnDef<PersonRef>[]>(() => [
210 {245 {
211 id: "name",246 id: "name",
212 header: t("payments.student"),247 header: t("payments.student"),
@@ -221,26 +256,32 @@ function PaymentsContent() {
221 {256 {
222 id: "debt",257 id: "debt",
223 header: t("payments.status"),258 header: t("payments.status"),
224- accessorFn: (user) => user.balance_minor ?? 0,259+ accessorFn: (user) => balances()[user.id] ?? 0,
225 cell: (cell) => {260 cell: (cell) => {
226- const bal = cell.row.original.balance_minor;261+ const id = cell.row.original.id;
227- if (bal == null) return <span class="text-sm text-muted-foreground">—</span>;262+ return <span ref={(element) => observeBalance(element, id)}>
228- const inDebt = bal < 0;263+ <Show when={balances()[id] !== undefined} fallback={<span class="inline-block h-4 w-16 animate-pulse rounded bg-muted" />}>
229- return (264+ <Show when={balances()[id] !== null} fallback={<span class="text-sm text-muted-foreground">—</span>}>
230- <Badge variant="outline" class={inDebt ? "border-destructive/50 bg-destructive/10 text-destructive-text" : "border-success/50 bg-success/10 text-success-text"}>265+ <Badge variant="outline" class={balances()[id]! < 0 ? "border-destructive/50 bg-destructive/10 text-destructive-text" : "border-success/50 bg-success/10 text-success-text"}>
231- <span class={`mr-1.5 inline-block h-1.5 w-1.5 rounded-full ${inDebt ? "bg-destructive" : "bg-success"}`} />266+ <span class={`mr-1.5 inline-block h-1.5 w-1.5 rounded-full ${balances()[id]! < 0 ? "bg-destructive" : "bg-success"}`} />
232- {inDebt ? t("payments.inDebt") : t("payments.settled")}267+ {balances()[id]! < 0 ? t("payments.inDebt") : t("payments.settled")}
233- </Badge>268+ </Badge>
234- );269+ </Show>
270+ </Show>
271+ </span>;
235 },272 },
236 },273 },
237 {274 {
238 id: "balance",275 id: "balance",
239 header: t("payments.balance"),276 header: t("payments.balance"),
240- accessorFn: (user) => user.balance_minor ?? 0,277+ accessorFn: (user) => balances()[user.id] ?? 0,
241 cell: (cell) => {278 cell: (cell) => {
242- const bal = cell.row.original.balance_minor;279+ const id = cell.row.original.id;
243- return <span class="font-medium tabular-nums" classList={{ "text-destructive-text": (bal ?? 0) < 0 }}>{bal == null ? "—" : formatTry(bal, moneyLocale())}</span>;280+ return <span ref={(element) => observeBalance(element, id)} class="font-medium tabular-nums" classList={{ "text-destructive-text": (balances()[id] ?? 0) < 0 }}>
281+ <Show when={balances()[id] !== undefined} fallback={<span class="inline-block h-4 w-20 animate-pulse rounded bg-muted" />}>
282+ {balances()[id] === null ? "—" : formatTry(balances()[id]!, moneyLocale())}
283+ </Show>
284+ </span>;
244 },285 },
245 },286 },
246 {287 {
@@ -267,8 +308,9 @@ function PaymentsContent() {
267 () => student() || null,308 () => student() || null,
268 (userId) => getPaymentStatementByUserId(userId, { limit: 500 }),309 (userId) => getPaymentStatementByUserId(userId, { limit: 500 }),
269 );310 );
311+ const [showLedger, setShowLedger] = createSignal(false);
270 const [ledger, { refetch: refetchLedger }] = createResource(312 const [ledger, { refetch: refetchLedger }] = createResource(
271- () => student() || null,313+ () => showLedger() && student() ? student() : null,
272 (userId) => getPaymentLedgerByUserId(userId, { limit: 200 }),314 (userId) => getPaymentLedgerByUserId(userId, { limit: 200 }),
273 );315 );
274 const entries = () => statement()?.entries.items ?? [];316 const entries = () => statement()?.entries.items ?? [];
@@ -351,6 +393,7 @@ function PaymentsContent() {
351 });393 });
352 setCollectEntry(null);394 setCollectEntry(null);
353 setFlash(t("common.saved"));395 setFlash(t("common.saved"));
396+ invalidateBalance(student());
354 await Promise.all([refetchStatement(), refetchLedger()]);397 await Promise.all([refetchStatement(), refetchLedger()]);
355 } catch (err) {398 } catch (err) {
356 setError(formatApiError(err));399 setError(formatApiError(err));
@@ -408,7 +451,6 @@ function PaymentsContent() {
408 ]);451 ]);
409 452
410 // ---- account activity (advanced corrections) ----453 // ---- account activity (advanced corrections) ----
411- const [showLedger, setShowLedger] = createSignal(false);
412 const [lineAction, setLineAction] = createSignal<LineAction | null>(null);454 const [lineAction, setLineAction] = createSignal<LineAction | null>(null);
413 const [actionAmount, setActionAmount] = createSignal("");455 const [actionAmount, setActionAmount] = createSignal("");
414 const [actionNote, setActionNote] = createSignal("");456 const [actionNote, setActionNote] = createSignal("");
@@ -440,6 +482,7 @@ function PaymentsContent() {
440 }482 }
441 setLineAction(null);483 setLineAction(null);
442 setFlash(t("common.saved"));484 setFlash(t("common.saved"));
485+ invalidateBalance(student());
443 await Promise.all([refetchStatement(), refetchLedger()]);486 await Promise.all([refetchStatement(), refetchLedger()]);
444 } catch (err) {487 } catch (err) {
445 setError(formatApiError(err));488 setError(formatApiError(err));
@@ -617,7 +660,7 @@ function PaymentsContent() {
617 </Show>660 </Show>
618 <DataTable661 <DataTable
619 columns={studentColumns()}662 columns={studentColumns()}
620- data={paymentStudentRows() ?? []}663+ data={pagedStudents()}
621 onRowClick={(user) => navigate({ to: "/management/payments/$userId", params: { userId: user.id } })}664 onRowClick={(user) => navigate({ to: "/management/payments/$userId", params: { userId: user.id } })}
622 searchValue={studentQuery()}665 searchValue={studentQuery()}
623 onSearchInput={(value) => {666 onSearchInput={(value) => {
@@ -728,6 +771,7 @@ function PaymentsContent() {
728 <h2 class="font-semibold">{t("payments.ledgerAudit")}</h2>771 <h2 class="font-semibold">{t("payments.ledgerAudit")}</h2>
729 <p class="text-xs text-muted-foreground">{t("payments.appendOnly")}</p>772 <p class="text-xs text-muted-foreground">{t("payments.appendOnly")}</p>
730 </div>773 </div>
774+ <Show when={!ledger.loading} fallback={<div class="h-5 w-24 animate-pulse rounded bg-muted" />}>
731 <div class="divide-y divide-border/60">775 <div class="divide-y divide-border/60">
732 <For each={ledger()?.items ?? []}>776 <For each={ledger()?.items ?? []}>
733 {(line) => (777 {(line) => (
@@ -752,6 +796,7 @@ function PaymentsContent() {
752 <p class="py-2 text-sm text-muted-foreground">{t("payments.noLedger")}</p>796 <p class="py-2 text-sm text-muted-foreground">{t("payments.noLedger")}</p>
753 </Show>797 </Show>
754 </div>798 </div>
799+ </Show>
755 </section>800 </section>
756 </Show>801 </Show>
757 </div>802 </div>
src/pages/staff-work-page.test.tsxadded+54 -0
@@ -0,0 +1,54 @@
1+import { cleanup, render, screen, waitFor } from "@solidjs/testing-library";
2+import { afterEach, expect, test, vi } from "vitest";
3+import StaffWorkPage from "@/pages/staff-work-page";
4+import { PreferencesProvider } from "@/stores/preferences-context";
5+
6+const { getUserSearch, getUserWorkLog } = vi.hoisted(() => ({
7+ getUserSearch: vi.fn(),
8+ getUserWorkLog: vi.fn(),
9+}));
10+vi.mock("@tanstack/solid-router", () => ({ Link: () => null, Navigate: () => null, useLocation: () => () => ({ pathname: "/management/staff-work" }) }));
11+vi.mock("@/stores/auth-context", () => ({
12+ useAuth: () => ({ user: () => ({ id: "manager", role: "manager" }), loading: () => false, error: () => null }),
13+}));
14+vi.mock("@/api/users", () => ({ getUserSearch }));
15+vi.mock("@/api/work", () => ({ getUserWorkLog, patchWorkEntryById: vi.fn(), deleteWorkEntryById: vi.fn() }));
16+
17+let observed: Element[] = [];
18+let callback: IntersectionObserverCallback;
19+const originalObserver = globalThis.IntersectionObserver;
20+
21+afterEach(() => {
22+ cleanup();
23+ vi.clearAllMocks();
24+ observed = [];
25+ globalThis.IntersectionObserver = originalObserver;
26+});
27+
28+test("staff cards paint before work logs and fetch only visible cards once", async () => {
29+ globalThis.IntersectionObserver = class {
30+ constructor(cb: IntersectionObserverCallback) { callback = cb; }
31+ observe(element: Element) { observed.push(element); }
32+ unobserve() {}
33+ disconnect() {}
34+ } as unknown as typeof IntersectionObserver;
35+ getUserSearch.mockResolvedValue({ items: [
36+ { id: "a", username: "ada", display_name: "Ada" },
37+ { id: "b", username: "bora", display_name: "Bora" },
38+ ] });
39+ getUserWorkLog.mockResolvedValue({ items: [], total: 0 });
40+
41+ const view = render(() => <PreferencesProvider><StaffWorkPage /></PreferencesProvider>);
42+ expect(await screen.findByText("Ada")).toBeTruthy();
43+ expect(screen.getByText("Bora")).toBeTruthy();
44+ expect(getUserWorkLog).not.toHaveBeenCalled();
45+ expect(view.container.querySelectorAll(".animate-pulse").length).toBeGreaterThan(0);
46+ expect(observed).toHaveLength(2);
47+
48+ callback([{ target: observed[0], isIntersecting: true } as IntersectionObserverEntry], {} as IntersectionObserver);
49+ await waitFor(() => expect(getUserWorkLog).toHaveBeenCalledTimes(1));
50+ await waitFor(() => expect(screen.getByText("Ada").closest("button")?.textContent).toContain("No activity"));
51+ expect(getUserWorkLog).toHaveBeenCalledWith("a", { limit: 500 });
52+ callback([{ target: observed[0], isIntersecting: true } as IntersectionObserverEntry], {} as IntersectionObserver);
53+ expect(getUserWorkLog).toHaveBeenCalledTimes(1);
54+});
src/pages/staff-work-page.tsxmodified+76 -28
@@ -1,4 +1,4 @@
1-import { For, Show, createEffect, createMemo, createSignal } from "solid-js";1+import { For, Show, createEffect, createMemo, createSignal, onCleanup } from "solid-js";
2 import { createResponsivePageSize } from "@/lib/create-page-size";2 import { createResponsivePageSize } from "@/lib/create-page-size";
3 import { createResource } from "@/lib/create-resource";3 import { createResource } from "@/lib/create-resource";
4 import type { ColumnDef } from "@tanstack/solid-table";4 import type { ColumnDef } from "@tanstack/solid-table";
@@ -29,6 +29,7 @@ import { TableRowActions } from "@/components/ui/table-row-actions";
29 import { formatDateTime, formatDurationMinutes } from "@/lib/format";29 import { formatDateTime, formatDurationMinutes } from "@/lib/format";
30 import { matchesSearch } from "@/lib/search-text";30 import { matchesSearch } from "@/lib/search-text";
31 import { personLabel } from "@/lib/person";31 import { personLabel } from "@/lib/person";
32+import { FAN_OUT_LIMIT } from "@/lib/map-concurrent";
32 import { usePreferences, useT } from "@/stores/preferences-context";33 import { usePreferences, useT } from "@/stores/preferences-context";
33 34
34 const PEOPLE_PAGE_SIZE = 9;35 const PEOPLE_PAGE_SIZE = 9;
@@ -126,11 +127,69 @@ function StaffWorkContent() {
126 { initialValue: [] },127 { initialValue: [] },
127 );128 );
128 129
130+ const workLogs = new Map<string, Page<WorkEntry>>();
131+ const workLogReads = new Map<string, Promise<Page<WorkEntry>>>();
132+ const [statsByUser, setStatsByUser] = createSignal<Record<string, StaffCardStats | null | undefined>>({});
133+ const requestedStats = new Set<string>();
134+ const statsQueue: string[] = [];
135+ let activeStats = 0;
136+ let disposed = false;
137+ const drainStats = () => {
138+ while (activeStats < FAN_OUT_LIMIT && statsQueue.length > 0) {
139+ const id = statsQueue.shift()!;
140+ activeStats++;
141+ const read = getUserWorkLog(id, { limit: WORK_LOG_FETCH_LIMIT });
142+ workLogReads.set(id, read);
143+ void read
144+ .then((log) => {
145+ workLogs.set(id, log);
146+ if (!disposed) setStatsByUser((prev) => ({ ...prev, [id]: summarizeWorkLog(log) }));
147+ })
148+ .catch(() => {
149+ if (!disposed) setStatsByUser((prev) => ({ ...prev, [id]: null }));
150+ })
151+ .finally(() => {
152+ workLogReads.delete(id);
153+ activeStats--;
154+ if (!disposed) drainStats();
155+ });
156+ }
157+ };
158+ const requestStats = (id: string) => {
159+ if (requestedStats.has(id)) return;
160+ requestedStats.add(id);
161+ statsQueue.push(id);
162+ drainStats();
163+ };
164+ let statsObserver: IntersectionObserver | undefined;
165+ const observeStats = (element: HTMLElement, id: string) => {
166+ if (requestedStats.has(id)) return;
167+ if (typeof IntersectionObserver === "undefined") {
168+ requestStats(id);
169+ return;
170+ }
171+ statsObserver ??= new IntersectionObserver((items) => {
172+ for (const item of items) {
173+ if (!item.isIntersecting) continue;
174+ statsObserver?.unobserve(item.target);
175+ requestStats((item.target as HTMLElement).dataset.staffId!);
176+ }
177+ });
178+ element.dataset.staffId = id;
179+ statsObserver.observe(element);
180+ };
181+ onCleanup(() => {
182+ disposed = true;
183+ statsObserver?.disconnect();
184+ });
185+
129 const [entries, { refetch: refetchEntries }] = createResource(186 const [entries, { refetch: refetchEntries }] = createResource(
130 () => viewUser()?.id ?? null,187 () => viewUser()?.id ?? null,
131 async (id) => {188 async (id) => {
132 try {189 try {
133- return await getUserWorkLog(id);190+ const cached = workLogs.get(id);
191+ const log = cached ?? await workLogReads.get(id);
192+ return log && log.total <= log.items.length ? log : await getUserWorkLog(id);
134 } catch (err) {193 } catch (err) {
135 if (err instanceof ApiError && err.status === 404) {194 if (err instanceof ApiError && err.status === 404) {
136 setError(t("work.userNotFound"));195 setError(t("work.userNotFound"));
@@ -164,26 +223,6 @@ function StaffWorkContent() {
164 setStaffPage(0);223 setStaffPage(0);
165 });224 });
166 225
167- // Card stats are only fetched for the staff on the visible page — the same
168- // "bounded to what's on screen" shape as the payments roster balances and
169- // the classes-page member counts, so paging through the whole staff list
170- // never fires more than PEOPLE_PAGE_SIZE work-log requests at once.
171- const [cardStats] = createResource(
172- () => pagedPeople().map((person) => person.id),
173- async (ids) => {
174- const rows = await Promise.all(
175- ids.map(async (id) => {
176- try {
177- return [id, summarizeWorkLog(await getUserWorkLog(id, { limit: WORK_LOG_FETCH_LIMIT }))] as const;
178- } catch {
179- return [id, null] as const;
180- }
181- }),
182- );
183- return new Map(rows);
184- },
185- );
186-
187 const entryColumns = createMemo<ColumnDef<WorkEntry>[]>(() => [226 const entryColumns = createMemo<ColumnDef<WorkEntry>[]>(() => [
188 {227 {
189 id: "time",228 id: "time",
@@ -282,6 +321,10 @@ function StaffWorkContent() {
282 await patchWorkEntryById(entry.id, { check_in, check_out });321 await patchWorkEntryById(entry.id, { check_in, check_out });
283 setEditTarget(null);322 setEditTarget(null);
284 await refetchEntries();323 await refetchEntries();
324+ workLogs.delete(entry.user);
325+ setStatsByUser((prev) => ({ ...prev, [entry.user]: undefined }));
326+ requestedStats.delete(entry.user);
327+ requestStats(entry.user);
285 setFlash(t("common.saved"));328 setFlash(t("common.saved"));
286 } catch (err) {329 } catch (err) {
287 setError(formatApiError(err));330 setError(formatApiError(err));
@@ -318,7 +361,8 @@ function StaffWorkContent() {
318 {(person) => (361 {(person) => (
319 <StaffCard362 <StaffCard
320 person={person}363 person={person}
321- stats={cardStats()?.get(person.id) ?? undefined}364+ stats={statsByUser()[person.id]}
365+ observe={observeStats}
322 locale={locale()}366 locale={locale()}
323 onClick={() => {367 onClick={() => {
324 setError("");368 setError("");
@@ -425,6 +469,10 @@ function StaffWorkContent() {
425 try {469 try {
426 await deleteWorkEntryById(entry.id);470 await deleteWorkEntryById(entry.id);
427 await refetchEntries();471 await refetchEntries();
472+ workLogs.delete(entry.user);
473+ setStatsByUser((prev) => ({ ...prev, [entry.user]: undefined }));
474+ requestedStats.delete(entry.user);
475+ requestStats(entry.user);
428 setFlash(t("common.deleted"));476 setFlash(t("common.deleted"));
429 } catch (err) {477 } catch (err) {
430 setError(formatApiError(err));478 setError(formatApiError(err));
@@ -437,7 +485,7 @@ function StaffWorkContent() {
437 );485 );
438 }486 }
439 487
440-function StaffCard(props: { person: PersonRef; stats: StaffCardStats | null | undefined; locale: Locale; onClick: () => void }) {488+function StaffCard(props: { person: PersonRef; stats: StaffCardStats | null | undefined; locale: Locale; onClick: () => void; observe: (element: HTMLElement, id: string) => void }) {
441 const t = useT();489 const t = useT();
442 const latest = () => props.stats?.latest ?? null;490 const latest = () => props.stats?.latest ?? null;
443 const isOpen = () => latest() != null && latest()!.check_out == null;491 const isOpen = () => latest() != null && latest()!.check_out == null;
@@ -450,6 +498,7 @@ function StaffCard(props: { person: PersonRef; stats: StaffCardStats | null | un
450 return (498 return (
451 <button499 <button
452 type="button"500 type="button"
501+ ref={(element) => props.observe(element, props.person.id)}
453 onClick={props.onClick}502 onClick={props.onClick}
454 class="flex flex-col gap-3 rounded-lg border border-border-line bg-surface-base p-4 text-left shadow-xs transition hover:-translate-y-0.5 hover:border-primary/40 hover:shadow-md focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"503 class="flex flex-col gap-3 rounded-lg border border-border-line bg-surface-base p-4 text-left shadow-xs transition hover:-translate-y-0.5 hover:border-primary/40 hover:shadow-md focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
455 >504 >
@@ -464,10 +513,8 @@ function StaffCard(props: { person: PersonRef; stats: StaffCardStats | null | un
464 <IconChevronRight class="h-4 w-4 shrink-0 text-text-subtle" />513 <IconChevronRight class="h-4 w-4 shrink-0 text-text-subtle" />
465 </div>514 </div>
466 515
467- <Show516+ <Show when={props.stats !== undefined} fallback={<div class="h-4 w-24 animate-pulse rounded bg-muted" />}>
468- when={latest()}517+ <Show when={latest()} fallback={<p class="text-xs text-text-subtle">{props.stats === null ? "—" : t("work.noActivity")}</p>}>
469- fallback={<p class="text-xs text-text-subtle">{t("work.noActivity")}</p>}
470- >
471 {(entry) => (518 {(entry) => (
472 <div class="grid grid-cols-3 gap-2 text-xs">519 <div class="grid grid-cols-3 gap-2 text-xs">
473 <div>520 <div>
@@ -485,6 +532,7 @@ function StaffCard(props: { person: PersonRef; stats: StaffCardStats | null | un
485 </div>532 </div>
486 )}533 )}
487 </Show>534 </Show>
535+ </Show>
488 536
489 {/* No stats (still loading, or the read failed): no footer, rather than537 {/* No stats (still loading, or the read failed): no footer, rather than
490 an empty band under a hairline. */}538 an empty band under a hairline. */}
src/pages/teachers-roster-page.test.tsxadded+40 -0
@@ -0,0 +1,40 @@
1+import { cleanup, render, screen, waitFor } from "@solidjs/testing-library";
2+import type { JSX } from "solid-js";
3+import { afterEach, expect, test, vi } from "vitest";
4+import TeachersRosterPage from "./teachers-roster-page";
5+import { resetInstanceLabelCache } from "@/lib/instance-labels";
6+import { PreferencesProvider } from "@/stores/preferences-context";
7+
8+const { getClasses, getClassInstances, getUserSearch, getCourses } = vi.hoisted(() => ({
9+ getClasses: vi.fn(), getClassInstances: vi.fn(), getUserSearch: vi.fn(), getCourses: vi.fn(),
10+}));
11+
12+vi.mock("@tanstack/solid-router", () => ({
13+ Link: (props: { to: string; children: JSX.Element }) => <a href={props.to}>{props.children}</a>,
14+ useNavigate: () => vi.fn(),
15+ useLocation: () => () => ({ pathname: "/management/teachers", search: {}, searchStr: "", hash: "" }),
16+}));
17+vi.mock("@/stores/auth-context", () => ({
18+ useAuth: () => ({ user: () => ({ id: "admin", role: "manager" }), loading: () => false, error: () => null }),
19+}));
20+vi.mock("@/api/classes", () => ({ getClasses, getClassInstances }));
21+vi.mock("@/api/users", () => ({ getUserSearch }));
22+vi.mock("@/api/courses", () => ({ getCourses }));
23+
24+afterEach(() => {
25+ cleanup();
26+ resetInstanceLabelCache();
27+ vi.clearAllMocks();
28+});
29+
30+test("shows teachers while section reads are still pending", async () => {
31+ getUserSearch.mockResolvedValue({ items: [{ id: "t1", username: "teacher", display_name: "Ayşe" }] });
32+ getClasses.mockResolvedValue({ items: [{ id: "c1", name: "9-A", grade_level: 9, teacher: null }] });
33+ getCourses.mockResolvedValue({ items: [{ id: "math", title: "Math" }] });
34+ getClassInstances.mockImplementation(() => new Promise(() => {}));
35+
36+ render(() => <PreferencesProvider><TeachersRosterPage /></PreferencesProvider>);
37+
38+ expect(await screen.findByText("Ayşe")).toBeTruthy();
39+ await waitFor(() => expect(getClassInstances).toHaveBeenCalledTimes(1));
40+});
src/pages/teachers-roster-page.tsxmodified+19 -21
@@ -3,12 +3,10 @@ import type { ColumnDef } from "@tanstack/solid-table";
3 import { Show, Suspense, createMemo, createSignal } from "solid-js";3 import { Show, Suspense, createMemo, createSignal } from "solid-js";
4 import { createResource } from "@/lib/create-resource";4 import { createResource } from "@/lib/create-resource";
5 import { matchesSearch } from "@/lib/search-text";5 import { matchesSearch } from "@/lib/search-text";
6-import { getClassInstances, getClasses } from "@/api/classes";
7 import { getCourses } from "@/api/courses";6 import { getCourses } from "@/api/courses";
8 import { getUserSearch } from "@/api/users";7 import { getUserSearch } from "@/api/users";
9 import { formatApiError, type Course, type PersonRef } from "@/api/client";8 import { formatApiError, type Course, type PersonRef } from "@/api/client";
10-import { formatInstanceLabel } from "@/lib/instance-labels";9+import { formatInstanceLabel, loadSchoolSections, classList } from "@/lib/instance-labels";
11-import { FAN_OUT_LIMIT, mapConcurrent } from "@/lib/map-concurrent";
12 import { RouteGuard } from "@/components/layout/route-guard";10 import { RouteGuard } from "@/components/layout/route-guard";
13 import { CreateUserPanel } from "@/components/users/create-user-panel";11 import { CreateUserPanel } from "@/components/users/create-user-panel";
14 import { RosterPersonCell } from "@/components/users/roster-person-cell";12 import { RosterPersonCell } from "@/components/users/roster-person-cell";
@@ -50,34 +48,36 @@ function TeachersRosterContent() {
50 const [creating, setCreating] = createSignal(false);48 const [creating, setCreating] = createSignal(false);
51 49
52 const [data, { refetch }] = createResource(async () => {50 const [data, { refetch }] = createResource(async () => {
53- const [teachers, classes, courses] = await Promise.all([51+ const [teachers, classes] = await Promise.all([
54 getUserSearch("", undefined, "teacher"),52 getUserSearch("", undefined, "teacher"),
55- getClasses(),53+ classList().then((items) => ({ items })),
56- getCourses().catch(() => ({ items: [] as Course[] })),
57 ]);54 ]);
58 const push = (map: Map<string, string[]>, id: string, value: string) => map.set(id, [...(map.get(id) ?? []), value]);55 const push = (map: Map<string, string[]>, id: string, value: string) => map.set(id, [...(map.get(id) ?? []), value]);
59 const byName = (a: string, b: string) => a.localeCompare(b, "tr", { numeric: true });56 const byName = (a: string, b: string) => a.localeCompare(b, "tr", { numeric: true });
60 const homeroom = new Map<string, string[]>();57 const homeroom = new Map<string, string[]>();
61 for (const cls of classes.items) if (cls.teacher) push(homeroom, cls.teacher.id, cls.name);58 for (const cls of classes.items) if (cls.teacher) push(homeroom, cls.teacher.id, cls.name);
62- const titles = new Map(courses.items.map((course) => [course.id, course.title]));59+ return teachers.items.map<TeacherRow>((person) => ({
63- const perClass = await mapConcurrent(classes.items, FAN_OUT_LIMIT, async (cls) => ({60+ person,
64- cls,61+ homeroom: (homeroom.get(person.id) ?? []).sort(byName),
65- // One unreadable class must not empty the whole column.62+ sections: [],
66- instances: await getClassInstances(cls.id).then((page) => page.items, () => []),
67 }));63 }));
64+ });
65+ const [sectionNames] = createResource(() => data.latest ? true : null, async () => {
66+ const courses = await getCourses().catch(() => ({ items: [] as Course[] }));
67+ const titles = new Map(courses.items.map((course) => [course.id, course.title]));
68+ const push = (map: Map<string, string[]>, id: string, value: string) => map.set(id, [...(map.get(id) ?? []), value]);
69+ const byName = (a: string, b: string) => a.localeCompare(b, "tr", { numeric: true });
70+ const perClass = await loadSchoolSections();
68 const sections = new Map<string, string[]>();71 const sections = new Map<string, string[]>();
69- for (const { cls, instances } of perClass) {72+ for (const { klass, sections: instances } of perClass) {
70 for (const instance of instances) {73 for (const instance of instances) {
71- const label = formatInstanceLabel(titles.get(instance.course) ?? null, cls.name);74+ const label = formatInstanceLabel(titles.get(instance.course) ?? null, klass.name);
72 for (const teacher of instance.teachers) push(sections, teacher.id, label);75 for (const teacher of instance.teachers) push(sections, teacher.id, label);
73 }76 }
74 }77 }
75- return teachers.items.map<TeacherRow>((person) => ({78+ return new Map([...sections].map(([id, names]) => [id, [...new Set(names)].sort(byName)]));
76- person,
77- homeroom: (homeroom.get(person.id) ?? []).sort(byName),
78- sections: [...new Set(sections.get(person.id) ?? [])].sort(byName),
79- }));
80 });79 });
80+ const mergedRows = createMemo(() => (data.latest ?? []).map((row) => ({ ...row, sections: sectionNames.latest?.get(row.person.id) ?? [] })));
81 81
82 const open = (row: TeacherRow) => void navigate({ to: "/profile/$userId", params: { userId: row.person.id } });82 const open = (row: TeacherRow) => void navigate({ to: "/profile/$userId", params: { userId: row.person.id } });
83 83
@@ -125,7 +125,6 @@ function TeachersRosterContent() {
125 <ErrorAlert message={formatApiError(data.error)} onRetry={() => void refetch()} />125 <ErrorAlert message={formatApiError(data.error)} onRetry={() => void refetch()} />
126 </Show>126 </Show>
127 <Show when={!data.error && data()}>127 <Show when={!data.error && data()}>
128- {(rows) => (
129 <DataTable128 <DataTable
130 urlState129 urlState
131 surfaceSections130 surfaceSections
@@ -138,7 +137,7 @@ function TeachersRosterContent() {
138 </Button>137 </Button>
139 </Show></>}138 </Show></>}
140 columns={columns()}139 columns={columns()}
141- data={rows()}140+ data={mergedRows()}
142 tableClass="min-w-2xl"141 tableClass="min-w-2xl"
143 empty={t("roster.noTeachers")}142 empty={t("roster.noTeachers")}
144 filterPlaceholder={t("roster.searchTeachers")}143 filterPlaceholder={t("roster.searchTeachers")}
@@ -151,7 +150,6 @@ function TeachersRosterContent() {
151 storageKey="teachers-roster"150 storageKey="teachers-roster"
152 onRowClick={open}151 onRowClick={open}
153 />152 />
154- )}
155 </Show>153 </Show>
156 </Suspense>154 </Suspense>
157 </section>155 </section>