From 48313a507f62a0af9ca7b5ff6abbc288ee9a80b6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Burak=20Boduro=C4=9Flu?= <80620802+burakboduroglu@users.noreply.github.com> Date: Sun, 27 Sep 2026 09:59:56 +0300 Subject: [PATCH] =?UTF-8?q?perf:=20=F0=9F=9A=80=20load=20on=20sight,=20sha?= =?UTF-8?q?re=20the=20school=20walk,=20page=20client=20tables=20-=20insigh?= =?UTF-8?q?ts=20read=20the=20first=2050=20students'=20signals,=20then=20mo?= =?UTF-8?q?re=20as=20the=20table=20=20=20scrolls=20or=20a=20signal=20filte?= =?UTF-8?q?r/sort=20needs=20them;=20overview=20cards=20state=20their=20=20?= =?UTF-8?q?=20coverage=20while=20partial=20(212=20=E2=86=92=20~62=20reques?= =?UTF-8?q?ts=20on=20open)=20-=20dashboard=20caps=20the=20trend=20at=20six?= =?UTF-8?q?=20exams=20and=20loads=20the=20chart,=20class=20sizes=20=20=20a?= =?UTF-8?q?nd=20below-fold=20panels=20when=20they=20come=20into=20view=20-?= =?UTF-8?q?=20studio=20shows=20its=20library=20at=20once=20and=20reads=20a?= =?UTF-8?q?=20note's=20outputs=20when=20its=20=20=20row=20is=20visible;=20?= =?UTF-8?q?staff-work=20and=20payments=20fetch=20row=20values=20on=20sight?= =?UTF-8?q?=20-=20class=20members=20and=20section=20walks=20are=20a=20shar?= =?UTF-8?q?ed=20five-minute=20per-tab=20=20=20cache,=20invalidated=20after?= =?UTF-8?q?=20class,=20member=20and=20section=20writes=20-=20tables=20and?= =?UTF-8?q?=20lists=20that=20are=20not=20fetched=20as=20you=20scroll=20pag?= =?UTF-8?q?e=20with=20numbers=20=20=20again=20(DataTable=20client=20mode,?= =?UTF-8?q?=20event=20roll=20call,=20studio=20library)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .claude/skills/ui-conventions/SKILL.md | 2 +- docs/ui/ui-redesign-tokens.md | 4 +- src/components/ai/insights-board.test.tsx | 49 +++++++ src/components/ai/insights-board.tsx | 33 ++++- src/components/ai/note-studio-panel.test.tsx | 50 +++++++ src/components/ai/note-studio-panel.tsx | 46 ++++-- .../ai/studio-output-library.test.tsx | 60 ++++++-- src/components/ai/studio-output-library.tsx | 118 +++++++++------ .../dashboard/quick-link-column.tsx | 20 ++- .../events/event-roll-call.test.tsx | 22 +++ src/components/events/event-roll-call.tsx | 35 +++-- .../insights/insight-overview.test.tsx | 24 +++ src/components/insights/insight-overview.tsx | 14 +- .../insights/insight-students-table.test.tsx | 55 +++++++ .../insights/insight-students-table.tsx | 28 +++- src/components/ui/data-table.test.tsx | 97 ++++++++---- src/components/ui/data-table.tsx | 138 +++++++----------- src/lib/insight-students.test.ts | 49 ++++++- src/lib/insight-students.ts | 19 ++- src/lib/instance-labels.test.ts | 24 ++- src/lib/instance-labels.ts | 50 +++++-- src/lib/instance-options.test.ts | 32 ++++ src/lib/instance-options.ts | 6 +- src/lib/student-directory.test.ts | 37 ++++- src/lib/student-directory.ts | 63 ++++++-- src/pages/class-detail-page.tsx | 7 + src/pages/classes-page.test.tsx | 13 ++ src/pages/classes-page.tsx | 18 ++- src/pages/dashboard-page.test.tsx | 78 +++++++++- src/pages/dashboard-page.tsx | 76 +++++++--- src/pages/payments-page.test.tsx | 84 +++++++++++ src/pages/payments-page.tsx | 117 ++++++++++----- src/pages/staff-work-page.test.tsx | 54 +++++++ src/pages/staff-work-page.tsx | 104 +++++++++---- src/pages/teachers-roster-page.test.tsx | 40 +++++ src/pages/teachers-roster-page.tsx | 40 +++-- 36 files changed, 1328 insertions(+), 378 deletions(-) create mode 100644 src/components/ai/insights-board.test.tsx create mode 100644 src/components/ai/note-studio-panel.test.tsx create mode 100644 src/components/insights/insight-overview.test.tsx create mode 100644 src/components/insights/insight-students-table.test.tsx create mode 100644 src/lib/instance-options.test.ts create mode 100644 src/pages/payments-page.test.tsx create mode 100644 src/pages/staff-work-page.test.tsx create mode 100644 src/pages/teachers-roster-page.test.tsx diff --git a/.claude/skills/ui-conventions/SKILL.md b/.claude/skills/ui-conventions/SKILL.md index bde595b..4a006aa 100644 --- a/.claude/skills/ui-conventions/SKILL.md +++ b/.claude/skills/ui-conventions/SKILL.md @@ -49,7 +49,7 @@ Active project reference docs (read the relevant one before changing that area): - 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. - Table-page headers fold into the `DataTable` title/description/actions area; do not render a separate `PageHeader` above table-primary pages. - Every list toolbar is one card (`TOOLBAR_CARD`), even when "Sütunlar" is its only control; its controls follow the pill standard above. -- 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`). +- 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`). - Pages/domain components must not import or render `Table` primitives directly; only the `DataTable` wrapper and table primitive files may. - 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). diff --git a/docs/ui/ui-redesign-tokens.md b/docs/ui/ui-redesign-tokens.md index 2b032df..765dc4a 100644 --- a/docs/ui/ui-redesign-tokens.md +++ b/docs/ui/ui-redesign-tokens.md @@ -93,8 +93,8 @@ display-font, translucent surface, or custom shadow rules. `src/components/ui/data-toolbar.tsx`). Every list toolbar is one card. - Filled buttons carry a transparent border with `bg-clip-padding`, so they match an outlined pill's height; a border never matches its fill colour. -- No page numbers: server lists fetch as you scroll (`createInfiniteList` + - `infinite`), client lists reveal 50 rows at a time. Empty cells show `—`. +- Server lists fetch as you scroll (`createInfiniteList` + `infinite`); + client tables use page numbers. Empty cells show `—`. - `storageKey` remains optional. When provided, only column visibility persists under `hezarfen.table.`. - Application tables use `DataTable`; page/domain components do not render table diff --git a/src/components/ai/insights-board.test.tsx b/src/components/ai/insights-board.test.tsx new file mode 100644 index 0000000..5ce3e86 --- /dev/null +++ b/src/components/ai/insights-board.test.tsx @@ -0,0 +1,49 @@ +import { cleanup, fireEvent, render, screen, waitFor } from "@solidjs/testing-library"; +import { afterEach, expect, it, vi } from "vitest"; +import { InsightsBoard } from "./insights-board"; +import { clearStudentSignalCache } from "@/lib/insight-students"; + +const api = vi.hoisted(() => ({ + getMyStudents: vi.fn(), + getInsightByUserId: vi.fn(), +})); + +vi.mock("@/api/parents", () => ({ getMyStudents: api.getMyStudents })); +vi.mock("@/api/insights", () => ({ + getInsightByUserId: api.getInsightByUserId, + getMyInsight: vi.fn(), + getInsightRuns: vi.fn(), + postInsightsRefresh: vi.fn(), +})); +vi.mock("@/stores/auth-context", () => ({ + useAuth: () => ({ user: () => ({ id: "insights-board-viewer", role: "parent" }) }), +})); +vi.mock("@/stores/preferences-context", () => ({ + usePreferences: () => ({ t: (key: string) => key, locale: () => "en" }), +})); +vi.mock("@/components/ui/data-table", () => ({ DataTableSkeleton: () => null })); +vi.mock("@/components/insights/insight-overview", () => ({ InsightOverview: () => null })); +vi.mock("@/components/insights/insight-students-table", () => ({ + InsightStudentsTable: (props: { onNeedMore: () => void }) => ( + + ), +})); + +afterEach(() => { + cleanup(); + clearStudentSignalCache("insights-board-viewer"); + vi.clearAllMocks(); +}); + +it("reads only the first 50 student insights until more rows are requested", async () => { + api.getMyStudents.mockResolvedValue({ items: Array.from({ length: 200 }, (_, index) => ({ + id: `student-${index}`, username: `student-${index}`, display_name: `Student ${index}`, + })) }); + api.getInsightByUserId.mockImplementation(async (id: string) => ({ + user_id: id, summary: null, attention: [], cards: [], segments: [], + })); + render(() => ); + await waitFor(() => expect(api.getInsightByUserId).toHaveBeenCalledTimes(50)); + fireEvent.click(screen.getByRole("button", { name: "Load next rows" })); + await waitFor(() => expect(api.getInsightByUserId).toHaveBeenCalledTimes(100)); +}); diff --git a/src/components/ai/insights-board.tsx b/src/components/ai/insights-board.tsx index c90e12f..5550353 100644 --- a/src/components/ai/insights-board.tsx +++ b/src/components/ai/insights-board.tsx @@ -14,7 +14,7 @@ import { IconSparkles } from "@/components/ui/icons"; import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"; import { createFlash } from "@/lib/flash"; import { toStudentSignal, type StudentSignal } from "@/lib/insight-run-report"; -import { insightOverview, loadInsightStudents, loadStudentSignals } from "@/lib/insight-students"; +import { cachedStudentSignal, clearStudentSignalCache, insightOverview, loadInsightStudents, loadStudentSignals } from "@/lib/insight-students"; import { personLabel } from "@/lib/person"; import { hasMinRole } from "@/lib/roles"; import { useAuth } from "@/stores/auth-context"; @@ -52,14 +52,33 @@ export function InsightsBoard() { // Each student's analysis lands in its row as it is read; rows start as // "not loaded" so the table and the overview never show a guessed value. const [signals, setSignals] = createSignal>({}); + const [requestedCount, setRequestedCount] = createSignal(0); let readGeneration = 0; + let requestThrough = (_count: number) => {}; createEffect(on(() => students.latest, (list) => { if (!list) return; const generation = ++readGeneration; - setSignals(Object.fromEntries(list.map((person) => [person.id, toStudentSignal({ id: person.id, name: personLabel(person) }, null, null)]))); - void loadStudentSignals(list, (row) => { - if (generation === readGeneration) setSignals((current) => ({ ...current, [row.id]: row })); - }); + const scope = auth.user()?.id ?? ""; + let queued = 0; + let reads = Promise.resolve(); + setSignals(Object.fromEntries(list.map((person) => [person.id, + cachedStudentSignal(person, scope) ?? toStudentSignal({ id: person.id, name: personLabel(person) }, null, null), + ]))); + setRequestedCount(Math.min(50, list.length)); + requestThrough = (count) => { + const end = Math.min(count, list.length); + if (end <= queued) return; + const batch = list.slice(queued, end); + queued = end; + setRequestedCount(end); + reads = reads.then(() => { + if (generation !== readGeneration) return; + return loadStudentSignals(batch, (row) => { + if (generation === readGeneration) setSignals((current) => ({ ...current, [row.id]: row })); + }, undefined, scope); + }); + }; + requestThrough(50); })); const rows = createMemo(() => Object.values(signals())); const overview = createMemo(() => insightOverview(rows(), students.latest?.length ?? 0)); @@ -70,6 +89,7 @@ export function InsightsBoard() { setPageError(""); try { await postInsightsRefresh(); + clearStudentSignalCache(auth.user()?.id ?? ""); flash(tx("insights.refreshQueued")); await refetchRuns(); } catch (error) { @@ -92,6 +112,9 @@ export function InsightsBoard() {
requestThrough(requestedCount() + 50)} + onInspectAll={() => requestThrough(students.latest?.length ?? 0)} title={tx("insights.title")} description={role() === "parent" ? tx("insights.parentSubtitle") : tx("insights.subtitle")} empty={role() === "parent" ? tx("insights.emptyLinkedStudents") : tx("insights.emptyStudents")} diff --git a/src/components/ai/note-studio-panel.test.tsx b/src/components/ai/note-studio-panel.test.tsx new file mode 100644 index 0000000..ecddea3 --- /dev/null +++ b/src/components/ai/note-studio-panel.test.tsx @@ -0,0 +1,50 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; +import { getCachedStudioNotes, loadStudioNotes } from "@/components/ai/note-studio-panel"; + +const coursesApi = vi.hoisted(() => ({ getCourses: vi.fn() })); +const notesApi = vi.hoisted(() => ({ getCourseNotes: vi.fn() })); + +vi.mock("@/api/courses", () => coursesApi); +vi.mock("@/api/course-notes", async (importOriginal) => ({ + ...await importOriginal(), + ...notesApi, +})); + +describe("loadStudioNotes", () => { + beforeEach(() => vi.clearAllMocks()); + it("limits concurrent course note requests and preserves course order", async () => { + const courses = Array.from({ length: 10 }, (_, index) => ({ + id: `course-${index}`, + title: `Course ${index}`, + creator: { id: "teacher" }, + })); + coursesApi.getCourses.mockResolvedValue({ items: courses }); + let active = 0; + let peak = 0; + notesApi.getCourseNotes.mockImplementation(async (courseId: string) => { + active++; + peak = Math.max(peak, active); + await new Promise((resolve) => setTimeout(resolve, courseId === "course-0" ? 5 : 0)); + active--; + return { items: [{ id: `note-${courseId}`, title: courseId }] }; + }); + + const notes = await loadStudioNotes(); + + expect(coursesApi.getCourses).toHaveBeenCalledWith({ limit: 100 }); + expect(notesApi.getCourseNotes).toHaveBeenCalledTimes(10); + expect(peak).toBe(4); + expect(notes.map((note) => note.courseTitle)).toEqual(courses.map((course) => course.title)); + }); + + it("reuses the completed course note list within a tab", async () => { + coursesApi.getCourses.mockResolvedValue({ items: [] }); + const first = getCachedStudioNotes("cache-test-user"); + const second = getCachedStudioNotes("cache-test-user"); + + expect(first).toBe(second); + await first; + await getCachedStudioNotes("cache-test-user"); + expect(coursesApi.getCourses).toHaveBeenCalledTimes(1); + }); +}); diff --git a/src/components/ai/note-studio-panel.tsx b/src/components/ai/note-studio-panel.tsx index abb1fac..4f7153b 100644 --- a/src/components/ai/note-studio-panel.tsx +++ b/src/components/ai/note-studio-panel.tsx @@ -33,31 +33,48 @@ function readRailWidth(): number { } type StudioNote = CourseNote & { courseTitle: string; courseCreatorId: string }; +const studioNotesCache = new Map>(); /** Every lesson note the account can produce from, with its course. */ -async function loadStudioNotes(): Promise { +export async function loadStudioNotes(): Promise { // GET /courses is already scoped to what the caller teaches or takes. const courses = await getCourses({ limit: 100 }); - const rows = await Promise.all( - courses.items.map(async (course) => { + const rows: StudioNote[][] = Array.from({ length: courses.items.length }, () => []); + let next = 0; + await Promise.all(Array.from({ length: Math.min(4, courses.items.length) }, async () => { + while (next < courses.items.length) { + const index = next++; + const course = courses.items[index]!; try { const page = await getCourseNotes(course.id, { limit: 100 }); - return page.items.map((note) => ({ + rows[index] = page.items.map((note) => ({ ...note, courseTitle: course.title, courseCreatorId: course.creator.id, })); } catch { - return []; + rows[index] = []; } - }), - ); + } + })); return rows.flat(); } +export function getCachedStudioNotes(userId: string): Promise { + let pending = studioNotesCache.get(userId); + if (!pending) { + pending = loadStudioNotes().catch((error) => { + studioNotesCache.delete(userId); + throw error; + }); + studioNotesCache.set(userId, pending); + } + return pending; +} + function useStudioNotes() { const auth = useAuth(); - return createResource(() => auth.user()?.role ?? null, () => loadStudioNotes()); + return createResource(() => auth.user()?.id ?? null, (userId) => userId ? getCachedStudioNotes(userId) : []); } /** @@ -76,6 +93,11 @@ export function NoteStudioPanel() { }; return ( +
+
+

{t("aiHub.tab.studio")}

+

{t("aiStudio.heading")}

+
}> void refetch()} /> @@ -88,12 +110,7 @@ export function NoteStudioPanel() { {/* A studio home: a plain title and one line saying what it makes, the way to start on a note, then everything produced so far. Flat hairline cards, no banner and no shadow stack. */} -
-
-

{t("aiHub.tab.studio")}

-

{t("aiStudio.heading")}

-
- +
+
); } diff --git a/src/components/ai/studio-output-library.test.tsx b/src/components/ai/studio-output-library.test.tsx index 8ba3baa..b2c78c0 100644 --- a/src/components/ai/studio-output-library.test.tsx +++ b/src/components/ai/studio-output-library.test.tsx @@ -50,7 +50,24 @@ function summary(noteId: string): RagOutput { } describe("StudioOutputLibrary", () => { + let visible: ((noteId: string) => void) | undefined; beforeEach(() => { + const observed = new Map(); + visible = (noteId) => { + for (const [target, entry] of observed) { + if (noteId === "__sentinel" ? (target as HTMLElement).classList.contains("h-px") : (target as HTMLElement).dataset.noteId === noteId) { + entry.callback([{ target, isIntersecting: true } as IntersectionObserverEntry], entry.observer); + return; + } + } + }; + vi.stubGlobal("IntersectionObserver", class { + private callback: IntersectionObserverCallback; + constructor(callback: IntersectionObserverCallback) { this.callback = callback; } + observe(element: Element) { observed.set(element, { callback: this.callback, observer: this as unknown as IntersectionObserver }); } + unobserve(element: Element) { observed.delete(element); } + disconnect() { for (const [element, entry] of observed) if (entry.observer === this) observed.delete(element); } + }); localStorage.setItem("hezarfen.locale", "tr"); podcastApi.listPodcastJobs.mockResolvedValue(page([ podcast({ job_id: "job-1" }), @@ -64,6 +81,7 @@ describe("StudioOutputLibrary", () => { afterEach(() => { cleanup(); + vi.unstubAllGlobals(); localStorage.clear(); vi.clearAllMocks(); }); @@ -80,6 +98,12 @@ describe("StudioOutputLibrary", () => { it("lists one row per produced artifact, newest first, failures included", async () => { renderLibrary(); + await waitFor(() => expect(screen.getByText("Başarısız")).toBeTruthy()); + expect(courseNotesApi.getCourseNoteRag).not.toHaveBeenCalled(); + visible?.("note-1"); + visible?.("note-2"); + visible?.("note-3"); + await waitFor(() => expect(screen.getByText("Kuvvet")).toBeTruthy()); await waitFor(() => expect(screen.getAllByText("Hücre").length).toBe(2)); // The failed run is part of the history and says so rather than vanishing. expect(screen.getByText("Polinomlar")).toBeTruthy(); @@ -94,12 +118,14 @@ describe("StudioOutputLibrary", () => { it("marks every row of the selected note as current", async () => { renderLibrary(); + await waitFor(() => expect(screen.getAllByText("Hücre").length).toBe(3)); + visible?.("note-1"); await waitFor(() => expect(screen.getAllByText("Hücre").length).toBe(2)); const current = screen.getAllByRole("button").filter((el) => el.getAttribute("aria-current") === "true"); expect(current.length).toBe(2); }); - it("reveals a long history fifty rows at a time", async () => { + it("pages a long history twenty rows at a time", async () => { podcastApi.listPodcastJobs.mockResolvedValue(page( Array.from({ length: 52 }, (_, index) => 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", () => { courseNotesApi.getCourseNoteRag.mockResolvedValue(page([])); renderLibrary(); - // Newest first: episode 52 leads, episode 3 closes the first fifty. + // Newest first: episode 52 leads, episode 33 closes the first page. await waitFor(() => expect(screen.getByText("Bölüm 52")).toBeTruthy()); - expect(screen.getByText("Bölüm 3")).toBeTruthy(); - expect(screen.queryByText("Bölüm 2")).toBeNull(); - - // jsdom has no IntersectionObserver, so the next rows wait for a button. - fireEvent.click(screen.getByRole("button", { name: "Devamını yükle" })); - expect(screen.getByText("Bölüm 2")).toBeTruthy(); - expect(screen.getByText("Bölüm 1")).toBeTruthy(); - expect(screen.getByText("Bölüm 52")).toBeTruthy(); + expect(screen.getByText("Bölüm 33")).toBeTruthy(); + expect(screen.queryByText("Bölüm 32")).toBeNull(); + + fireEvent.click(screen.getByRole("button", { name: /Next|Sonraki/ })); + expect(screen.getByText("Bölüm 32")).toBeTruthy(); + expect(screen.queryByText("Bölüm 52")).toBeNull(); }); it("opens an episode's note page with that episode picked", async () => { const onSelect = renderLibrary(); - await waitFor(() => expect(screen.getAllByText("Hücre").length).toBe(2)); + await waitFor(() => expect(screen.getAllByText("Hücre").length).toBe(3)); fireEvent.click(screen.getAllByRole("button", { name: /Hücre/ })[0]!); expect(onSelect).toHaveBeenCalledWith("note-1", expect.any(String)); @@ -133,8 +157,22 @@ describe("StudioOutputLibrary", () => { const onSelect = renderLibrary(); await waitFor(() => expect(screen.getByText("Kuvvet")).toBeTruthy()); + visible?.("note-2"); + await waitFor(() => expect(screen.getByText("Yapay zekâ özeti")).toBeTruthy()); fireEvent.click(screen.getByRole("button", { name: /Kuvvet/ })); expect(onSelect).toHaveBeenCalledWith("note-2", undefined); }); + + it("loads only a visible note and keeps its unknown output as a placeholder", async () => { + renderLibrary(); + await waitFor(() => expect(screen.getByText("Başarısız")).toBeTruthy()); + expect(screen.getAllByText("—").length).toBeGreaterThan(0); + expect(courseNotesApi.getCourseNoteRag).not.toHaveBeenCalled(); + + visible?.("note-2"); + await waitFor(() => expect(courseNotesApi.getCourseNoteRag).toHaveBeenCalledWith("note-2", { limit: 1 })); + expect(courseNotesApi.getCourseNoteRag).toHaveBeenCalledTimes(1); + await waitFor(() => expect(screen.getByText("Yapay zekâ özeti")).toBeTruthy()); + }); }); diff --git a/src/components/ai/studio-output-library.tsx b/src/components/ai/studio-output-library.tsx index b07328e..b8131a9 100644 --- a/src/components/ai/studio-output-library.tsx +++ b/src/components/ai/studio-output-library.tsx @@ -1,4 +1,4 @@ -import { For, Show, Suspense, createEffect, createMemo, createSignal } from "solid-js"; +import { For, Show, createEffect, createMemo, createSignal, onCleanup, onMount } from "solid-js"; import { createResource } from "@/lib/create-resource"; import { getCourseNoteRag } from "@/api/course-notes"; import { listPodcastJobs } from "@/api/podcast"; @@ -6,8 +6,7 @@ import type { PodcastJobSummary } from "@/api/client"; import { Badge } from "@/components/ui/badge"; import { EmptyInline } from "@/components/ui/empty-inline"; import { IconSparkles, IconWaveform } from "@/components/ui/icons"; -import { InfiniteSentinel } from "@/components/ui/infinite-sentinel"; -import { PageSpinner } from "@/components/ui/page-spinner"; +import { TablePagination } from "@/components/ui/table-pagination"; import { cn } from "@/lib/cn"; import { formatDateTime } from "@/lib/format"; import { usePreferences, useT } from "@/stores/preferences-context"; @@ -29,13 +28,15 @@ type StudioArtifact = { title: string; courseTitle: string; /** Sorts the list: when the run finished, else when it started. */ - at: number; + at?: number; job: PodcastJobSummary | null; + pending?: boolean; }; const LIBRARY_LIMIT = 100; /** Client lists reveal this many rows at a time, like client DataTables. */ -const LIBRARY_REVEAL = 50; +/** Rows per library page; the history is already in memory, so it pages. */ +const LIBRARY_PAGE = 20; export function StudioOutputLibrary(props: { notes: StudioLibraryNote[]; @@ -46,6 +47,37 @@ export function StudioOutputLibrary(props: { const t = useT(); const { locale } = usePreferences(); const source = createMemo(() => props.notes.map((note) => note.id).join(",")); + const [summaries, setSummaries] = createSignal>({}); + const requested = new Set(); + let list: HTMLUListElement | undefined; + let observer: IntersectionObserver | undefined; + + const loadSummary = (noteId: string) => { + if (requested.has(noteId)) return; + requested.add(noteId); + void getCourseNoteRag(noteId, { limit: 1 }).then( + (page) => setSummaries((current) => ({ ...current, [noteId]: page.items[0]?.generated_at ?? null })), + () => setSummaries((current) => ({ ...current, [noteId]: null })), + ); + }; + const watchNote = (element: HTMLLIElement, noteId: string) => { + element.dataset.noteId = noteId; + if (observer) observer.observe(element); + else if (typeof IntersectionObserver === "undefined") loadSummary(noteId); + }; + onMount(() => { + if (typeof IntersectionObserver === "undefined") return; + observer = new IntersectionObserver((entries) => { + for (const entry of entries) { + if (!entry.isIntersecting) continue; + const noteId = (entry.target as HTMLElement).dataset.noteId; + if (noteId) loadSummary(noteId); + observer?.unobserve(entry.target); + } + }, { rootMargin: "100px" }); + list?.querySelectorAll("[data-studio-note]").forEach((element) => observer?.observe(element)); + }); + onCleanup(() => observer?.disconnect()); const stateVariant = (state: string) => { if (state === "done") return "success" as const; @@ -73,18 +105,15 @@ export function StudioOutputLibrary(props: { return "bg-warning"; }; - const [items] = createResource(source, async (): Promise => { - const [podcastResult, ...summaryResults] = await Promise.allSettled([ - listPodcastJobs({ limit: LIBRARY_LIMIT }), - ...props.notes.map((note) => getCourseNoteRag(note.id, { limit: 1 })), - ]); + const [podcasts] = createResource(source, () => listPodcastJobs({ limit: LIBRARY_LIMIT })); + const items = createMemo((): StudioArtifact[] => { const byId = new Map(props.notes.map((note) => [note.id, note])); const rows: StudioArtifact[] = []; // Every job, not only the finished ones: a failed or cancelled run is part // of the history and saying so is more useful than hiding it. - if (podcastResult.status === "fulfilled") { - for (const job of podcastResult.value.items) { + if (podcasts()) { + for (const job of podcasts()!.items) { const note = byId.get(job.source_id); rows.push({ key: `podcast:${job.job_id}`, @@ -97,31 +126,36 @@ export function StudioOutputLibrary(props: { } } - props.notes.forEach((note, index) => { - const result = summaryResults[index]; - const summary = result?.status === "fulfilled" ? result.value.items[0] : undefined; - if (!summary) return; + props.notes.forEach((note) => { + const at = summaries()[note.id]; + if (at === null) return; rows.push({ - key: `summary:${summary.id}`, + key: `summary:${note.id}`, noteId: note.id, title: note.title, courseTitle: note.courseTitle, - at: summary.generated_at, + at, job: null, + pending: at === undefined, }); }); - return rows.sort((a, b) => b.at - a.at); + return rows.sort((a, b) => (b.at ?? -1) - (a.at ?? -1)); }); - // The history is merged here from two sources, so it is revealed in - // memory as the reader scrolls — the app's client-list standard. - const [shown, setShown] = createSignal(LIBRARY_REVEAL); + // The history is merged here from two sources and held in memory, so it + // pages with numbers — the app's standard for lists that are not fetched as + // you scroll. A new source goes back to the first page. + const [page, setPage] = createSignal(0); const total = () => items()?.length ?? 0; - const pageItems = createMemo(() => (items() ?? []).slice(0, shown())); + const pageCount = () => Math.max(1, Math.ceil(total() / LIBRARY_PAGE)); + const pageItems = createMemo(() => (items() ?? []).slice(page() * LIBRARY_PAGE, (page() + 1) * LIBRARY_PAGE)); createEffect(() => { source(); - setShown(LIBRARY_REVEAL); + setPage(0); + }); + createEffect(() => { + if (page() >= pageCount()) setPage(pageCount() - 1); }); const open = (item: StudioArtifact) => { @@ -137,16 +171,15 @@ export function StudioOutputLibrary(props: {

{t("aiStudio.library.title")}

{t("aiStudio.library.description")}

- 0}> + !item.pending)}> - {t("aiStudio.library.count", { count: items()?.length ?? 0 })} + {t("aiStudio.library.count", { count: items().filter((item) => !item.pending).length })} -
}> 0} + when={items().length > 0 || podcasts.loading} fallback={
@@ -155,10 +188,10 @@ export function StudioOutputLibrary(props: { > {/* A run history, the way a studio lists one: hairline dividers, a status dot, what was produced and when — no cards. */} -
    +
      {(item) => ( -
    • +
    • watchNote(element, item.noteId) : undefined}>
    • )}
    - LIBRARY_REVEAL}> -
    - 0}> +
    + setShown((count) => count + LIBRARY_REVEAL)} + onPageChange={setPage} />
    -
); diff --git a/src/components/dashboard/quick-link-column.tsx b/src/components/dashboard/quick-link-column.tsx index 8501374..d9a831e 100644 --- a/src/components/dashboard/quick-link-column.tsx +++ b/src/components/dashboard/quick-link-column.tsx @@ -1,4 +1,4 @@ -import { For, Show, type Component } from "solid-js"; +import { For, Show, onCleanup, type Component } from "solid-js"; import { EmptyInline } from "@/components/ui/empty-inline"; import { IconChevronRight } from "@/components/ui/icons"; import type { IllustrationName } from "@/lib/illustrations"; @@ -15,6 +15,7 @@ export type QuickLinkColumnProps = { rows: QuickLinkRow[]; empty: string; illustration?: IllustrationName; + onVisible?: () => void; onOpen: (row: QuickLinkRow) => void; }; @@ -22,8 +23,23 @@ export type QuickLinkColumnProps = { * list of resource rows with a trailing caption, each navigating to the * resource's real detail page. */ export function QuickLinkColumn(props: QuickLinkColumnProps) { + const observe = (el: HTMLDivElement) => { + if (!props.onVisible) return; + if (typeof IntersectionObserver === "undefined") { + props.onVisible(); + return; + } + const observer = new IntersectionObserver((entries) => { + if (entries.some((entry) => entry.isIntersecting)) { + observer.disconnect(); + props.onVisible?.(); + } + }, { rootMargin: "160px" }); + observer.observe(el); + onCleanup(() => observer.disconnect()); + }; return ( -
+

{props.title}

0} fallback={}> diff --git a/src/components/events/event-roll-call.test.tsx b/src/components/events/event-roll-call.test.tsx index 8d50cb7..455886a 100644 --- a/src/components/events/event-roll-call.test.tsx +++ b/src/components/events/event-roll-call.test.tsx @@ -66,3 +66,25 @@ test("before the event starts nothing can be picked or saved", async () => { expect((row("Bora").getByRole("radio", { name: /Katıldı|Attended/ }) as HTMLButtonElement).disabled).toBe(true); expect((saveButton() as HTMLButtonElement).disabled).toBe(true); }); + +test("pages a long roster and keeps draft marks across pages", async () => { + const longRoster = Array.from({ length: 12 }, (_, index) => ({ + user: person(`student-${index}`, `Student ${index}`), + status: null, + marked_by: null, + })); + render(() => ( + + {}} /> + + )); + await screen.findByText("Student 0"); + expect(screen.queryByText("Student 10")).toBeNull(); + fireEvent.click(row("Student 0").getByRole("radio", { name: /Katıldı|Attended/ })); + fireEvent.click(screen.getByRole("button", { name: /Next|Sonraki/ })); + expect(screen.getByText("Student 10")).toBeTruthy(); + expect(screen.queryByText("Student 0")).toBeNull(); + fireEvent.click(screen.getByRole("button", { name: /Previous|Önceki/ })); + expect(row("Student 0").getByRole("radio", { name: /Katıldı|Attended/ }).getAttribute("aria-checked")).toBe("true"); + expect(postEventAttendance).not.toHaveBeenCalled(); +}); diff --git a/src/components/events/event-roll-call.tsx b/src/components/events/event-roll-call.tsx index f8838d6..fdbea27 100644 --- a/src/components/events/event-roll-call.tsx +++ b/src/components/events/event-roll-call.tsx @@ -11,7 +11,7 @@ import { TOOLBAR_CONTROL } from "@/components/ui/data-toolbar"; import { EmptyState } from "@/components/ui/empty-state"; import { InfoTip } from "@/components/ui/info-tip"; import { IconCheck } from "@/components/ui/icons"; -import { InfiniteSentinel } from "@/components/ui/infinite-sentinel"; +import { TablePagination } from "@/components/ui/table-pagination"; import { ATTENDANCE_STATUSES, getAttendanceStatusMeta } from "@/lib/attendance-status"; import { cn } from "@/lib/cn"; import { @@ -22,11 +22,9 @@ import { } from "@/lib/event-roll-call"; import { personLabel } from "@/lib/person"; import { matchesSearch } from "@/lib/search-text"; +import { createResponsivePageSize } from "@/lib/create-page-size"; import { useT } from "@/stores/preferences-context"; -/** Rows drawn at first and added each time the reader nears the end. */ -const REVEAL_STEP = 50; - /** * Event roll call as one roster: every expected attendee (resolved by the * backend from the event's audience) with a status row. Picks stay local @@ -65,7 +63,8 @@ export function EventRollCall(props: { const [summary, setSummary] = createSignal<{ kind: "success" | "destructive"; text: string } | null>(null); const [query, setQuery] = createSignal(""); const [onlyUnmarked, setOnlyUnmarked] = createSignal(false); - const [revealed, setRevealed] = createSignal(REVEAL_STEP); + const pageSize = createResponsivePageSize(10); + const [pageIndex, setPageIndex] = createSignal(0); const effective = (userId: string) => draft()[userId] ?? saved()[userId] ?? undefined; const changes = createMemo(() => rollCallChanges(saved(), draft())); @@ -87,10 +86,12 @@ export function EventRollCall(props: { return !q || matchesSearch(q, personLabel(row.user), row.user.username, row.user.student_number); }); }); - // The roster is already in memory: no page numbers, the list just draws - // more rows as the reader scrolls (the app's client-list standard). - createEffect(on([query, onlyUnmarked], () => setRevealed(REVEAL_STEP), { defer: true })); - const pageRows = createMemo(() => visible().slice(0, revealed())); + createEffect(on([query, onlyUnmarked, pageSize], () => setPageIndex(0), { defer: true })); + createEffect(() => { + const last = Math.max(0, Math.ceil(visible().length / pageSize()) - 1); + if (pageIndex() > last) setPageIndex(last); + }); + const pageRows = createMemo(() => visible().slice(pageIndex() * pageSize(), (pageIndex() + 1) * pageSize())); const busy = () => progress() != null; const locked = () => !props.open || busy(); @@ -301,13 +302,15 @@ export function EventRollCall(props: { - setRevealed((count) => count + REVEAL_STEP)} - /> + 0}> + + {(item) => {item().text}} diff --git a/src/components/insights/insight-overview.test.tsx b/src/components/insights/insight-overview.test.tsx new file mode 100644 index 0000000..4f726f3 --- /dev/null +++ b/src/components/insights/insight-overview.test.tsx @@ -0,0 +1,24 @@ +import { cleanup, render, screen } from "@solidjs/testing-library"; +import { afterEach, expect, it, vi } from "vitest"; +import { InsightOverview } from "./insight-overview"; + +vi.mock("@/stores/preferences-context", () => ({ + usePreferences: () => ({ + locale: () => "en", + t: (key: string, vars?: Record) => key === "insights.overview.reading" + ? `Reading ${vars?.loaded} of ${vars?.total} students…` + : key, + }), +})); + +afterEach(cleanup); + +it("labels partial counts and averages with their current coverage", () => { + render(() => ); + expect(screen.getByText("40 / 200")).toBeTruthy(); + expect(screen.getByText("7 / 50")).toBeTruthy(); + expect(screen.getAllByText("Reading 50 of 200 students…").length).toBeGreaterThan(0); +}); diff --git a/src/components/insights/insight-overview.tsx b/src/components/insights/insight-overview.tsx index 9789303..64bd733 100644 --- a/src/components/insights/insight-overview.tsx +++ b/src/components/insights/insight-overview.tsx @@ -20,25 +20,29 @@ export function InsightOverview(props: { overview: Overview }) {
); const o = () => props.overview; + const partial = () => o().loaded < o().total; + const coverage = () => partial() + ? t("insights.overview.reading", { loaded: o().loaded, total: o().total }) + : t("insights.overview.ofTotal", { total: o().total }); return (
- {tile(t("insights.overview.analysed"), String(o().analysed), t("insights.overview.ofTotal", { total: o().total }))} + {tile(t("insights.overview.analysed"), partial() ? `${o().analysed} / ${o().total}` : String(o().analysed), coverage())} {tile( t("insights.overview.needAttention"), - String(o().needAttention), - t("insights.overview.ofTotal", { total: o().total }), + partial() ? (o().loaded ? `${o().needAttention} / ${o().loaded}` : "—") : String(o().needAttention), + coverage(), o().needAttention > 0 ? "warn" : undefined, )} {tile( t("insights.overview.marks"), o().marksAverage == null ? "—" : runReportDecimal(o().marksAverage!, prefs.locale()), - o().marksAverage == null ? t("insights.overview.noData") : t("insights.overview.ofTotal", { total: o().analysed }), + partial() ? coverage() : o().marksAverage == null ? t("insights.overview.noData") : t("insights.overview.ofTotal", { total: o().analysed }), )} {tile( t("insights.overview.attendance"), o().attendanceRate == null ? "—" : runReportPercent(o().attendanceRate, prefs.locale()), - o().attendanceRate == null ? t("insights.overview.noData") : t("insights.overview.ofTotal", { total: o().analysed }), + partial() ? coverage() : o().attendanceRate == null ? t("insights.overview.noData") : t("insights.overview.ofTotal", { total: o().analysed }), )}
diff --git a/src/components/insights/insight-students-table.test.tsx b/src/components/insights/insight-students-table.test.tsx new file mode 100644 index 0000000..d7f303b --- /dev/null +++ b/src/components/insights/insight-students-table.test.tsx @@ -0,0 +1,55 @@ +import { cleanup, fireEvent, render, screen } from "@solidjs/testing-library"; +import { afterEach, expect, it, vi } from "vitest"; +import { InsightStudentsTable } from "./insight-students-table"; +import { toStudentSignal } from "@/lib/insight-run-report"; + +vi.mock("@tanstack/solid-router", () => ({ useNavigate: () => vi.fn(), Link: () => null })); +vi.mock("@/stores/preferences-context", () => ({ + usePreferences: () => ({ locale: () => "en", t: (key: string) => key }), +})); +vi.mock("@/components/ui/data-table", () => ({ + DataTable: (props: { filters: unknown }) => ( +
+
+ {props.filters as never} +
+ ), +})); +vi.mock("@/components/ui/select", () => ({ + DropdownSelect: (props: { onChange: (value: "attention") => void }) => ( + + ), +})); + +afterEach(() => { + cleanup(); + vi.unstubAllGlobals(); +}); + +it("requests more only near the table end, and loads all for a signal filter or sort", () => { + let notify: ((entries: { isIntersecting: boolean }[]) => void) | undefined; + vi.stubGlobal("IntersectionObserver", class { + constructor(callback: typeof notify) { notify = callback; } + observe() {} + disconnect() {} + }); + const more = vi.fn(); + const all = vi.fn(); + render(() => ); + expect(more).not.toHaveBeenCalled(); + notify?.([{ isIntersecting: false }]); + expect(more).not.toHaveBeenCalled(); + notify?.([{ isIntersecting: true }]); + expect(more).toHaveBeenCalledTimes(1); + fireEvent.click(screen.getByRole("button", { name: "Sort" })); + fireEvent.click(screen.getByRole("button", { name: "Attention filter" })); + expect(all).toHaveBeenCalledTimes(2); +}); diff --git a/src/components/insights/insight-students-table.tsx b/src/components/insights/insight-students-table.tsx index fcf4282..22b57d3 100644 --- a/src/components/insights/insight-students-table.tsx +++ b/src/components/insights/insight-students-table.tsx @@ -1,4 +1,4 @@ -import { createMemo, createSignal, type JSX } from "solid-js"; +import { createMemo, createSignal, onCleanup, onMount, type JSX } from "solid-js"; import { Link, useNavigate } from "@tanstack/solid-router"; import type { ColumnDef } from "@tanstack/solid-table"; import { Badge } from "@/components/ui/badge"; @@ -35,6 +35,9 @@ export function InsightStudentsTable(props: { description: string; empty: string; actions?: JSX.Element; + hasMore?: boolean; + onNeedMore?: () => void; + onInspectAll?: () => void; }) { const prefs = usePreferences(); const navigate = useNavigate(); @@ -42,6 +45,19 @@ export function InsightStudentsTable(props: { const t = (key: string, vars?: Record) => prefs.t(key as never, vars); const rt = (key: Parameters[1]) => runReportText(locale(), key); const [filter, setFilter] = createSignal("all"); + let sentinel: HTMLDivElement | undefined; + onMount(() => { + if (!sentinel) return; + if (typeof IntersectionObserver === "undefined") { + props.onInspectAll?.(); + return; + } + const observer = new IntersectionObserver((entries) => { + if (entries.some((entry) => entry.isIntersecting) && props.hasMore) props.onNeedMore?.(); + }, { rootMargin: "0px 0px 600px 0px" }); + observer.observe(sentinel); + onCleanup(() => observer.disconnect()); + }); const visible = createMemo(() => props.rows.filter((row) => filter() === "attention" ? row.attention > 0 : filter() === "none" ? row.state === "no_summary" : true, @@ -215,6 +231,9 @@ export function InsightStudentsTable(props: { ]); return ( +
{ + if ((event.target as Element).closest("th button")) props.onInspectAll?.(); + }}> { + setFilter(value); + if (value !== "all") props.onInspectAll?.(); + }} labelPrefix={t("common.filter")} class="min-w-44" /> @@ -241,5 +263,7 @@ export function InsightStudentsTable(props: { tableClass="insight-grid-table min-w-[60rem]" storageKey="insight-students-v2" /> + ); } diff --git a/src/components/ui/data-table.test.tsx b/src/components/ui/data-table.test.tsx index b7044bc..b19487c 100644 --- a/src/components/ui/data-table.test.tsx +++ b/src/components/ui/data-table.test.tsx @@ -98,31 +98,28 @@ function stubIntersectionObserver() { }; } -test("reveals rows in steps instead of paging", async () => { +test("paginates client rows without observing the scroll position", () => { const reachEnd = stubIntersectionObserver(); - const rows = Array.from({ length: 120 }, (_, index) => ({ name: `Person ${index + 1}` })); + const rows = Array.from({ length: 21 }, (_, index) => ({ name: `Person ${index + 1}` })); try { render(() => ( )); - - expect(screen.getByText("Person 50")).toBeTruthy(); - expect(screen.queryByText("Person 51")).toBeNull(); - expect(screen.getByText(/(Showing 50 of 120|120 kayıttan 50)/)).toBeTruthy(); - expect(screen.queryByRole("button", { name: "Next" })).toBeNull(); + expect(screen.getByText("Person 10")).toBeTruthy(); + expect(screen.queryByText("Person 11")).toBeNull(); + expect(screen.getByText("1 / 3")).toBeTruthy(); reachEnd(); - // jsdom lays nothing out, so the sentinel always reads as near the end - // and each reveal chains into the next until the list is complete. - await new Promise((resolve) => setTimeout(resolve, 0)); - expect(screen.getByText("Person 120")).toBeTruthy(); + expect(screen.queryByText("Person 11")).toBeNull(); + fireEvent.click(screen.getByRole("button", { name: /Next|Sonraki/ })); + expect(screen.getByText("Person 11")).toBeTruthy(); } finally { vi.unstubAllGlobals(); } }); -test("without IntersectionObserver every row renders, with the total under the list", () => { +test("without IntersectionObserver client rows still paginate", () => { vi.stubGlobal("IntersectionObserver", undefined); const rows = Array.from({ length: 60 }, (_, index) => ({ name: `Person ${index + 1}` })); try { @@ -131,12 +128,56 @@ test("without IntersectionObserver every row renders, with the total under the l )); - expect(screen.getByText("Person 60")).toBeTruthy(); - expect(screen.getByText(/^(Total|Toplam): 60$/)).toBeTruthy(); + expect(screen.queryByText("Person 60")).toBeNull(); + expect(screen.getByText("1 / 6")).toBeTruthy(); } finally { vi.unstubAllGlobals(); } }); +test("uses a shorter client page on phones", () => { + vi.stubGlobal("matchMedia", (query: string) => ({ + matches: query.includes("max-width"), + media: query, + addEventListener: () => undefined, + removeEventListener: () => undefined, + })); + try { + render(() => ( + + ({ name: `Person ${index + 1}` }))} + enableColumnVisibility={false} + /> + + )); + expect(screen.getByText("Person 5")).toBeTruthy(); + expect(screen.queryByText("Person 6")).toBeNull(); + expect(screen.getByText("1 / 3")).toBeTruthy(); + } finally { + vi.unstubAllGlobals(); + } +}); +test("search resets a client page and shrinking data clamps its index", () => { + const [rows, setRows] = createSignal(Array.from({ length: 22 }, (_, index) => ({ name: `Person ${index + 1}` }))); + render(() => ( + + row.name.toLowerCase().includes(query.toLowerCase())} + /> + + )); + fireEvent.click(screen.getByRole("button", { name: /Next|Sonraki/ })); + fireEvent.click(screen.getByRole("button", { name: /Next|Sonraki/ })); + expect(screen.getByText("Person 22")).toBeTruthy(); + setRows((current) => current.slice(0, 12)); + expect(screen.getByText("Person 12")).toBeTruthy(); + fireEvent.input(screen.getByRole("textbox"), { target: { value: "Person 12" } }); + expect(screen.getByText("Person 12")).toBeTruthy(); +}); test("a display column renders its own cell instead of the empty dash", () => { // A column with no accessorFn has no value to be empty, so the empty-cell // 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", () = expect(onClearFilters).toHaveBeenCalledOnce(); }); -test("revealed rows hold when the caller hands over a fresh data array", async () => { - const reachEnd = stubIntersectionObserver(); +test("the client page holds when the caller hands over a fresh data array", () => { const [tick, setTick] = createSignal(0); const people = Array.from({ length: 70 }, (_, i) => ({ name: `P${String(i).padStart(2, "0")}` })); - try { - render(() => ( - - {/* A new array on every read, like a page that maps rows inline. */} - ({ ...row })))} enableColumnVisibility={false} /> - - )); - reachEnd(); - await new Promise((resolve) => setTimeout(resolve, 0)); - expect(screen.getByText("P69")).toBeTruthy(); - setTick(1); - expect(screen.getByText("P69")).toBeTruthy(); - } finally { - vi.unstubAllGlobals(); - } + render(() => ( + + ({ ...row })))} enableColumnVisibility={false} /> + + )); + fireEvent.click(screen.getByRole("button", { name: /Next|Sonraki/ })); + expect(screen.getByText("P10")).toBeTruthy(); + setTick(1); + expect(screen.getByText("P10")).toBeTruthy(); + expect(screen.queryByText("P00")).toBeNull(); }); test("a toolbar holding only the column menu still gets its card", () => { const { container } = render(() => ( diff --git a/src/components/ui/data-table.tsx b/src/components/ui/data-table.tsx index 07be519..b21b362 100644 --- a/src/components/ui/data-table.tsx +++ b/src/components/ui/data-table.tsx @@ -11,6 +11,7 @@ import { flexRender, getCoreRowModel, getFilteredRowModel, + getPaginationRowModel, getSortedRowModel, } from "@tanstack/solid-table"; import { Illustration } from "@/components/ui/illustration"; @@ -23,10 +24,10 @@ import { IconArrowDown, IconArrowUp, IconChevronsUpDown } from "@/components/ui/ import { InfoTip } from "@/components/ui/info-tip"; import { cn } from "@/lib/cn"; import { createMediaQuery } from "@/lib/create-media-query"; -import { COMPACT_SCREEN_QUERY } from "@/lib/create-page-size"; +import { COMPACT_SCREEN_QUERY, createResponsivePageSize } from "@/lib/create-page-size"; import { createScrollRestore } from "@/lib/scroll-restore"; import { createTablePreferences } from "@/lib/table-preferences"; -import { createUrlParam, createUrlString, decodeSort, encodeSort, listParamKeys } from "@/lib/url-state"; +import { createUrlPageIndex, createUrlParam, createUrlString, decodeSort, encodeSort, listParamKeys } from "@/lib/url-state"; import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"; import { useT } from "@/stores/preferences-context"; @@ -99,10 +100,7 @@ export type DataTableProps = { mobileLayout?: "cards" | "scroll"; onRowClick?: (row: TData) => void; onSearchInput?: (value: string) => void; - /** - * Server-paged tables only: rows per page on a wide screen. A client-side - * table has no pages — it reveals rows as the reader scrolls. - */ + /** Rows per page on a wide screen; client tables use fewer on phones. */ pageSize?: number; searchPredicate?: (row: TData, query: string) => boolean; searchValue?: string; @@ -136,13 +134,7 @@ const resolveUpdater = (updater: Updater, old: T): T => const alignClass = { left: "text-left", center: "text-center", right: "text-right" } as const; -/** - * A client-side table renders this many rows, then this many more each time - * the reader nears the end. The data is already in memory, so sorting, search - * and filters still see every row — only the DOM is paced. - */ -const REVEAL_STEP = 50; -/** Start revealing the next rows this far before the list's end comes into view. */ +/** Start fetching the next server page this far before the list's end comes into view. */ const REVEAL_MARGIN_PX = 600; export function DataTable(props: DataTableProps) { @@ -157,34 +149,13 @@ export function DataTable(props: DataTableProps(urlKeys.sort, { parse: decodeSort, serialize: encodeSort }) : createSignal([]); const [otherColumnFilters, setOtherColumnFilters] = createSignal([]); - // Client-side tables drop page numbers for scroll-to-reveal; only a - // server-paged table (`manualPagination`) still pages. - const revealing = () => paginationEnabled && !props.manualPagination && !props.infinite; - // How far the reader had revealed, per page and table, for this tab: coming - // back from a detail page renders those rows again, so the router's scroll - // restoration has somewhere to land. - const revealKey = typeof window === "undefined" - ? null - : `reveal:${window.location.pathname}${window.location.search}:${props.storageKey ?? props.title ?? ""}`; - const readRevealed = () => { - try { - const count = Number(revealKey ? sessionStorage.getItem(revealKey) : null); - return Number.isFinite(count) && count > REVEAL_STEP ? Math.floor(count) : REVEAL_STEP; - } catch { - return REVEAL_STEP; - } - }; - const [revealed, setRevealed] = createSignal(readRevealed()); - createEffect(on(revealed, (count) => { - if (!revealKey || count === Number.MAX_SAFE_INTEGER) return; - try { - sessionStorage.setItem(revealKey, String(count)); - } catch { - // storage blocked: the table just starts at the first step - } - }, { defer: true })); - const resetReveal = () => setRevealed(REVEAL_STEP); - createEffect(on(() => props.pageResetKey, resetReveal, { defer: true })); + const clientPageSize = createResponsivePageSize(props.pageSize ?? 10); + const [clientPageIndex, setClientPageIndex] = urlKeys && !props.manualPagination && !props.infinite + ? createUrlPageIndex(urlKeys.page) + : createSignal(0); + const pagination = (): PaginationState => ({ pageIndex: clientPageIndex(), pageSize: clientPageSize() }); + createEffect(on(clientPageSize, () => setClientPageIndex(0), { defer: true })); + createEffect(on(() => props.pageResetKey, () => setClientPageIndex(0), { defer: true })); // The search box's text when the table owns it — the `searchPredicate` // query, or the `filterColumn` filter value. const [search, setSearch] = urlKeys && props.searchValue === undefined && !props.onSearchInput @@ -208,12 +179,12 @@ export function DataTable(props: DataTableProps filter.id === column); setSearch(typeof own?.value === "string" ? own.value : ""); setOtherColumnFilters(next.filter((filter) => filter.id !== column)); - resetReveal(); + setClientPageIndex(0); }; // A new sort order is a new list: start again from its top. const setSorting = (next: SortingState) => { setSortingState(next); - resetReveal(); + setClientPageIndex(0); }; // Sorting is client-side only, and the backend takes no sort parameter: on // a server-paged table it would reorder the visible page alone while the @@ -240,12 +211,13 @@ export function DataTable(props: DataTableProps setSorting(resolveUpdater(updater, sorting())), onColumnFiltersChange: (updater) => setColumnFilters(resolveUpdater(updater, columnFilters())), onColumnVisibilityChange: (updater) => prefs.setVisibility(resolveUpdater(updater, prefs.preferences().visibility)), + onPaginationChange: (updater) => setClientPageIndex(resolveUpdater(updater, pagination()).pageIndex), state: { get sorting() { return sorting(); @@ -259,7 +231,7 @@ export function DataTable(props: DataTableProps(props: DataTableProps props.manualPagination?.total ?? props.infinite?.total ?? table.getRowModel().rows.length; + const pageCount = () => props.manualPagination + ? Math.max(1, Math.ceil(props.manualPagination.total / props.manualPagination.pageSize)) + : table.getPageCount(); + const pageIndex = () => props.manualPagination?.pageIndex ?? clientPageIndex(); + const pageSize = () => props.manualPagination?.pageSize ?? clientPageSize(); + const totalRows = () => props.manualPagination?.total ?? props.infinite?.total ?? table.getFilteredRowModel().rows.length; const setPageIndex = (next: number) => { if (props.manualPagination) props.manualPagination.onPageChange(next); - else resetReveal(); - }; - /** The rows actually rendered: all of them, or the revealed head of the list. */ - const visibleRows = () => { - const rows = table.getRowModel().rows; - return revealing() ? rows.slice(0, revealed()) : rows; + else setClientPageIndex(next); }; - const hasHidden = () => revealing() && table.getRowModel().rows.length > revealed(); - // A sentinel under the list reveals the next rows as it nears the viewport. - // Without IntersectionObserver (old engines, jsdom) everything renders. + createEffect(() => { + if (props.manualPagination || props.infinite || !paginationEnabled) return; + const rows = table.getFilteredRowModel().rows.length; + if (rows === 0) return; + const last = Math.max(0, Math.ceil(rows / clientPageSize()) - 1); + if (clientPageIndex() > last) setClientPageIndex(last); + }); + const visibleRows = () => table.getRowModel().rows; let sentinel: HTMLDivElement | undefined; const observing = typeof IntersectionObserver !== "undefined"; const nearEnd = () => !!sentinel && sentinel.getBoundingClientRect().top < window.innerHeight + REVEAL_MARGIN_PX; - const revealMore = () => { + const loadMore = () => { if (!nearEnd()) return; const infinite = props.infinite; - if (infinite) { - if (infinite.hasMore && !infinite.loading) infinite.onLoadMore(); - return; - } - if (hasHidden()) setRevealed((count) => count + REVEAL_STEP); + if (infinite?.hasMore && !infinite.loading) infinite.onLoadMore(); }; createEffect(() => { - if (!(revealing() || props.infinite) || !observing) return; + if (!props.infinite || !observing) return; const node = sentinel; if (!node) return; const observer = new IntersectionObserver((entries) => { - if (entries.some((entry) => entry.isIntersecting)) revealMore(); + if (entries.some((entry) => entry.isIntersecting)) loadMore(); }, { rootMargin: `0px 0px ${REVEAL_MARGIN_PX}px 0px` }); observer.observe(node); onCleanup(() => observer.disconnect()); }); - // The observer only fires when the sentinel crosses the margin; after a - // reveal of short rows it can still sit inside it, so check again. - createEffect(on(revealed, () => queueMicrotask(revealMore), { defer: true })); // Same for a fetched page: once it lands, a short page may leave the end // in view, so ask for the next one straight away. createEffect(on(() => props.infinite?.loading, (busy) => { - if (busy === false && observing) queueMicrotask(revealMore); + if (busy === false && observing) queueMicrotask(loadMore); }, { defer: true })); - if (!observing) setRevealed(Number.MAX_SAFE_INTEGER); - // Back from a detail page lands on the same row once the rows are drawn. - createScrollRestore(revealKey, () => visibleRows().length > 0); + const scrollKey = typeof window === "undefined" || props.infinite || props.manualPagination + ? null + : `${window.location.pathname}:${props.storageKey ?? props.title ?? ""}:${urlKeys?.page ?? "page"}`; + createScrollRestore(scrollKey, () => visibleRows().length > 0); const searchFieldValue = () => { if (props.onSearchInput || props.searchPredicate || props.filterColumn) return searchValue(); return ""; @@ -403,7 +374,6 @@ export function DataTable(props: DataTableProps { if (!(target instanceof Element)) return false; @@ -766,20 +736,16 @@ export function DataTable(props: DataTableProps - - {(manual) => ( - 0}> - - - )} + 0}> + - 0}> + 0}> {/* One block, so the parent's space-y gap is paid once: the sentinel and the count as siblings put two gaps under the scroll hint. */}
@@ -789,9 +755,7 @@ export function DataTable(props: DataTableProps
-
+
observeWhenVisible(el, () => setTrendVisible(true))} data-dashboard-trend class="grid grid-cols-1 gap-3 sm:grid-cols-2 lg:col-span-2"> + }> +
@@ -1027,7 +1049,8 @@ function DashboardContent() { }> -
+
observeWhenVisible(el, () => setTrendVisible(true))} data-dashboard-trend class="grid grid-cols-1 gap-3 lg:grid-cols-3"> + }> +
@@ -1137,9 +1161,11 @@ function DashboardContent() { {/* PAR progress: the child's homework report (a parent-readable route) as overdue / due-this-week; marks-based progress still has no parent-facing trend. */} - - - +
observeWhenVisible(el, () => setChildHomeworkVisible(true))}> + + + +
@@ -1159,8 +1185,9 @@ function DashboardContent() {
+
observeWhenVisible(el, () => setHeatmapVisible(true))} data-dashboard-heatmap> }> - + }> +
); diff --git a/src/pages/payments-page.test.tsx b/src/pages/payments-page.test.tsx new file mode 100644 index 0000000..8f59a3e --- /dev/null +++ b/src/pages/payments-page.test.tsx @@ -0,0 +1,84 @@ +import { cleanup, render, screen, waitFor } from "@solidjs/testing-library"; +import { afterEach, expect, test, vi } from "vitest"; +import PaymentsPage from "@/pages/payments-page"; +import { PreferencesProvider } from "@/stores/preferences-context"; + +const { getUserSearch, getPaymentBalanceByUserId, getPaymentPlans, getPaymentLedgerByUserId } = vi.hoisted(() => ({ + getUserSearch: vi.fn(), + getPaymentBalanceByUserId: vi.fn(), + getPaymentPlans: vi.fn(), + getPaymentLedgerByUserId: vi.fn(), +})); +vi.mock("@tanstack/solid-router", () => ({ + Link: () => null, + Navigate: () => null, + useLocation: () => () => ({ pathname: "/management/payments", search: {} }), + useNavigate: () => vi.fn(), +})); +vi.mock("@/stores/auth-context", () => ({ + useAuth: () => ({ user: () => ({ id: "manager", role: "manager" }), loading: () => false, error: () => null }), +})); +vi.mock("@/api/users", () => ({ getUserSearch, getUserProfile: vi.fn() })); +vi.mock("@/api/payments", () => ({ + getPaymentBalanceByUserId, + getPaymentPlans, + getPaymentLedgerByUserId, + getPaymentStatementByUserId: vi.fn(), + getPlanAssignments: vi.fn(), + deletePaymentPlanById: vi.fn(), + patchPaymentPlanById: vi.fn(), + postPaymentCredit: vi.fn(), + postPaymentPlan: vi.fn(), + postPaymentRefund: vi.fn(), + postPaymentReversal: vi.fn(), + postPlanAssignment: vi.fn(), +})); + +let observed: Element[] = []; +let observers: { callback: IntersectionObserverCallback; elements: Element[] }[] = []; +const originalObserver = globalThis.IntersectionObserver; + +afterEach(() => { + cleanup(); + vi.clearAllMocks(); + observed = []; + observers = []; + globalThis.IntersectionObserver = originalObserver; +}); + +test("student rows paint before balances; only visible rows request a balance", async () => { + globalThis.IntersectionObserver = class { + private entry: { callback: IntersectionObserverCallback; elements: Element[] }; + constructor(cb: IntersectionObserverCallback) { + this.entry = { callback: cb, elements: [] }; + observers.push(this.entry); + } + observe(element: Element) { observed.push(element); this.entry.elements.push(element); } + unobserve() {} + disconnect() {} + } as unknown as typeof IntersectionObserver; + getUserSearch.mockResolvedValue({ items: [ + { id: "a", username: "ada", display_name: "Ada" }, + { id: "b", username: "bora", display_name: "Bora" }, + ], total: 2 }); + getPaymentPlans.mockResolvedValue({ items: [] }); + getPaymentBalanceByUserId.mockResolvedValue({ balance_minor: -1000 }); + + const view = render(() => ); + expect(await screen.findByText("Ada")).toBeTruthy(); + expect(screen.getByText("Bora")).toBeTruthy(); + expect(getPaymentBalanceByUserId).not.toHaveBeenCalled(); + expect(view.container.querySelectorAll(".animate-pulse").length).toBeGreaterThan(0); + expect(getPaymentLedgerByUserId).not.toHaveBeenCalled(); + const first = observed.find((element) => (element as HTMLElement).dataset.studentId === "a"); + expect(first).toBeTruthy(); + const observer = observers.find((entry) => entry.elements.includes(first!)); + expect(observer).toBeTruthy(); + + observer!.callback([{ target: first!, isIntersecting: true } as IntersectionObserverEntry], {} as IntersectionObserver); + await waitFor(() => expect(getPaymentBalanceByUserId).toHaveBeenCalledTimes(1)); + await waitFor(() => expect(view.container.textContent).toContain("In debt")); + expect(getPaymentBalanceByUserId).toHaveBeenCalledWith("a"); + observer!.callback([{ target: first!, isIntersecting: true } as IntersectionObserverEntry], {} as IntersectionObserver); + expect(getPaymentBalanceByUserId).toHaveBeenCalledTimes(1); +}); diff --git a/src/pages/payments-page.tsx b/src/pages/payments-page.tsx index 7fdba7b..13e9a8e 100644 --- a/src/pages/payments-page.tsx +++ b/src/pages/payments-page.tsx @@ -50,7 +50,7 @@ import { formatDate, formatDateTime } from "@/lib/format"; import { formatTry } from "@/lib/meals"; import { PAYMENT_METHOD_KEYS, sortStatementEntries, statementStatus } from "@/lib/payments"; import { matchesSearch } from "@/lib/search-text"; -import { FAN_OUT_LIMIT, mapConcurrent } from "@/lib/map-concurrent"; +import { FAN_OUT_LIMIT } from "@/lib/map-concurrent"; import { personLabel } from "@/lib/person"; import { usePreferences, useT } from "@/stores/preferences-context"; @@ -79,8 +79,6 @@ function dateInputToMs(value: string): number | null { } type LineAction = { line: PaymentLine; kind: "refund" | "reverse" }; -type PaymentStudentRow = PersonRef & { balance_minor: number | null }; - export default function PaymentsPage() { return ( @@ -189,24 +187,61 @@ function PaymentsContent() { setSelectedStudent((prev) => (prev?.id === routeId ? prev : { id: routeId, username: routeId, display_name: null })); }); - // The backend has no bulk balance endpoint. Fetch only the visible page so - // status/balance never disappear on schools with more than 200 students. - const [paymentStudentRows] = createResource( - () => { - const users = pagedStudents(); - return users.length > 0 ? users : null; - }, - async (users): Promise => - mapConcurrent(users, FAN_OUT_LIMIT, async (user) => { - try { - return { ...user, balance_minor: (await getPaymentBalanceByUserId(user.id)).balance_minor }; - } catch { - return { ...user, balance_minor: null }; - } - }), - ); + const [balances, setBalances] = createSignal>({}); + const requestedBalances = new Set(); + const balanceQueue: string[] = []; + let activeBalances = 0; + let disposed = false; + const drainBalances = () => { + while (activeBalances < FAN_OUT_LIMIT && balanceQueue.length > 0) { + const id = balanceQueue.shift()!; + activeBalances++; + void getPaymentBalanceByUserId(id) + .then((balance) => { + if (!disposed) setBalances((prev) => ({ ...prev, [id]: balance.balance_minor })); + }) + .catch(() => { + if (!disposed) setBalances((prev) => ({ ...prev, [id]: null })); + }) + .finally(() => { + activeBalances--; + if (!disposed) drainBalances(); + }); + } + }; + const requestBalance = (id: string) => { + if (requestedBalances.has(id)) return; + requestedBalances.add(id); + balanceQueue.push(id); + drainBalances(); + }; + const invalidateBalance = (id: string) => { + requestedBalances.delete(id); + setBalances((prev) => ({ ...prev, [id]: undefined })); + }; + let balanceObserver: IntersectionObserver | undefined; + const observeBalance = (element: HTMLElement, id: string) => { + if (requestedBalances.has(id)) return; + if (typeof IntersectionObserver === "undefined") { + requestBalance(id); + return; + } + balanceObserver ??= new IntersectionObserver((items) => { + for (const item of items) { + if (!item.isIntersecting) continue; + balanceObserver?.unobserve(item.target); + requestBalance((item.target as HTMLElement).dataset.studentId!); + } + }); + element.dataset.studentId = id; + balanceObserver.observe(element); + }; + onCleanup(() => { + disposed = true; + balanceObserver?.disconnect(); + }); - const studentColumns = createMemo[]>(() => [ + const studentColumns = createMemo[]>(() => [ { id: "name", header: t("payments.student"), @@ -221,26 +256,32 @@ function PaymentsContent() { { id: "debt", header: t("payments.status"), - accessorFn: (user) => user.balance_minor ?? 0, + accessorFn: (user) => balances()[user.id] ?? 0, cell: (cell) => { - const bal = cell.row.original.balance_minor; - if (bal == null) return —; - const inDebt = bal < 0; - return ( - - - {inDebt ? t("payments.inDebt") : t("payments.settled")} - - ); + const id = cell.row.original.id; + return observeBalance(element, id)}> + }> + —}> + + + {balances()[id]! < 0 ? t("payments.inDebt") : t("payments.settled")} + + + + ; }, }, { id: "balance", header: t("payments.balance"), - accessorFn: (user) => user.balance_minor ?? 0, + accessorFn: (user) => balances()[user.id] ?? 0, cell: (cell) => { - const bal = cell.row.original.balance_minor; - return {bal == null ? "—" : formatTry(bal, moneyLocale())}; + const id = cell.row.original.id; + return observeBalance(element, id)} class="font-medium tabular-nums" classList={{ "text-destructive-text": (balances()[id] ?? 0) < 0 }}> + }> + {balances()[id] === null ? "—" : formatTry(balances()[id]!, moneyLocale())} + + ; }, }, { @@ -267,8 +308,9 @@ function PaymentsContent() { () => student() || null, (userId) => getPaymentStatementByUserId(userId, { limit: 500 }), ); + const [showLedger, setShowLedger] = createSignal(false); const [ledger, { refetch: refetchLedger }] = createResource( - () => student() || null, + () => showLedger() && student() ? student() : null, (userId) => getPaymentLedgerByUserId(userId, { limit: 200 }), ); const entries = () => statement()?.entries.items ?? []; @@ -351,6 +393,7 @@ function PaymentsContent() { }); setCollectEntry(null); setFlash(t("common.saved")); + invalidateBalance(student()); await Promise.all([refetchStatement(), refetchLedger()]); } catch (err) { setError(formatApiError(err)); @@ -408,7 +451,6 @@ function PaymentsContent() { ]); // ---- account activity (advanced corrections) ---- - const [showLedger, setShowLedger] = createSignal(false); const [lineAction, setLineAction] = createSignal(null); const [actionAmount, setActionAmount] = createSignal(""); const [actionNote, setActionNote] = createSignal(""); @@ -440,6 +482,7 @@ function PaymentsContent() { } setLineAction(null); setFlash(t("common.saved")); + invalidateBalance(student()); await Promise.all([refetchStatement(), refetchLedger()]); } catch (err) { setError(formatApiError(err)); @@ -617,7 +660,7 @@ function PaymentsContent() { navigate({ to: "/management/payments/$userId", params: { userId: user.id } })} searchValue={studentQuery()} onSearchInput={(value) => { @@ -728,6 +771,7 @@ function PaymentsContent() {

{t("payments.ledgerAudit")}

{t("payments.appendOnly")}

+ }>
{(line) => ( @@ -752,6 +796,7 @@ function PaymentsContent() {

{t("payments.noLedger")}

+
diff --git a/src/pages/staff-work-page.test.tsx b/src/pages/staff-work-page.test.tsx new file mode 100644 index 0000000..76d789c --- /dev/null +++ b/src/pages/staff-work-page.test.tsx @@ -0,0 +1,54 @@ +import { cleanup, render, screen, waitFor } from "@solidjs/testing-library"; +import { afterEach, expect, test, vi } from "vitest"; +import StaffWorkPage from "@/pages/staff-work-page"; +import { PreferencesProvider } from "@/stores/preferences-context"; + +const { getUserSearch, getUserWorkLog } = vi.hoisted(() => ({ + getUserSearch: vi.fn(), + getUserWorkLog: vi.fn(), +})); +vi.mock("@tanstack/solid-router", () => ({ Link: () => null, Navigate: () => null, useLocation: () => () => ({ pathname: "/management/staff-work" }) })); +vi.mock("@/stores/auth-context", () => ({ + useAuth: () => ({ user: () => ({ id: "manager", role: "manager" }), loading: () => false, error: () => null }), +})); +vi.mock("@/api/users", () => ({ getUserSearch })); +vi.mock("@/api/work", () => ({ getUserWorkLog, patchWorkEntryById: vi.fn(), deleteWorkEntryById: vi.fn() })); + +let observed: Element[] = []; +let callback: IntersectionObserverCallback; +const originalObserver = globalThis.IntersectionObserver; + +afterEach(() => { + cleanup(); + vi.clearAllMocks(); + observed = []; + globalThis.IntersectionObserver = originalObserver; +}); + +test("staff cards paint before work logs and fetch only visible cards once", async () => { + globalThis.IntersectionObserver = class { + constructor(cb: IntersectionObserverCallback) { callback = cb; } + observe(element: Element) { observed.push(element); } + unobserve() {} + disconnect() {} + } as unknown as typeof IntersectionObserver; + getUserSearch.mockResolvedValue({ items: [ + { id: "a", username: "ada", display_name: "Ada" }, + { id: "b", username: "bora", display_name: "Bora" }, + ] }); + getUserWorkLog.mockResolvedValue({ items: [], total: 0 }); + + const view = render(() => ); + expect(await screen.findByText("Ada")).toBeTruthy(); + expect(screen.getByText("Bora")).toBeTruthy(); + expect(getUserWorkLog).not.toHaveBeenCalled(); + expect(view.container.querySelectorAll(".animate-pulse").length).toBeGreaterThan(0); + expect(observed).toHaveLength(2); + + callback([{ target: observed[0], isIntersecting: true } as IntersectionObserverEntry], {} as IntersectionObserver); + await waitFor(() => expect(getUserWorkLog).toHaveBeenCalledTimes(1)); + await waitFor(() => expect(screen.getByText("Ada").closest("button")?.textContent).toContain("No activity")); + expect(getUserWorkLog).toHaveBeenCalledWith("a", { limit: 500 }); + callback([{ target: observed[0], isIntersecting: true } as IntersectionObserverEntry], {} as IntersectionObserver); + expect(getUserWorkLog).toHaveBeenCalledTimes(1); +}); diff --git a/src/pages/staff-work-page.tsx b/src/pages/staff-work-page.tsx index b20a0e0..c46c005 100644 --- a/src/pages/staff-work-page.tsx +++ b/src/pages/staff-work-page.tsx @@ -1,4 +1,4 @@ -import { For, Show, createEffect, createMemo, createSignal } from "solid-js"; +import { For, Show, createEffect, createMemo, createSignal, onCleanup } from "solid-js"; import { createResponsivePageSize } from "@/lib/create-page-size"; import { createResource } from "@/lib/create-resource"; import type { ColumnDef } from "@tanstack/solid-table"; @@ -29,6 +29,7 @@ import { TableRowActions } from "@/components/ui/table-row-actions"; import { formatDateTime, formatDurationMinutes } from "@/lib/format"; import { matchesSearch } from "@/lib/search-text"; import { personLabel } from "@/lib/person"; +import { FAN_OUT_LIMIT } from "@/lib/map-concurrent"; import { usePreferences, useT } from "@/stores/preferences-context"; const PEOPLE_PAGE_SIZE = 9; @@ -126,11 +127,69 @@ function StaffWorkContent() { { initialValue: [] }, ); + const workLogs = new Map>(); + const workLogReads = new Map>>(); + const [statsByUser, setStatsByUser] = createSignal>({}); + const requestedStats = new Set(); + const statsQueue: string[] = []; + let activeStats = 0; + let disposed = false; + const drainStats = () => { + while (activeStats < FAN_OUT_LIMIT && statsQueue.length > 0) { + const id = statsQueue.shift()!; + activeStats++; + const read = getUserWorkLog(id, { limit: WORK_LOG_FETCH_LIMIT }); + workLogReads.set(id, read); + void read + .then((log) => { + workLogs.set(id, log); + if (!disposed) setStatsByUser((prev) => ({ ...prev, [id]: summarizeWorkLog(log) })); + }) + .catch(() => { + if (!disposed) setStatsByUser((prev) => ({ ...prev, [id]: null })); + }) + .finally(() => { + workLogReads.delete(id); + activeStats--; + if (!disposed) drainStats(); + }); + } + }; + const requestStats = (id: string) => { + if (requestedStats.has(id)) return; + requestedStats.add(id); + statsQueue.push(id); + drainStats(); + }; + let statsObserver: IntersectionObserver | undefined; + const observeStats = (element: HTMLElement, id: string) => { + if (requestedStats.has(id)) return; + if (typeof IntersectionObserver === "undefined") { + requestStats(id); + return; + } + statsObserver ??= new IntersectionObserver((items) => { + for (const item of items) { + if (!item.isIntersecting) continue; + statsObserver?.unobserve(item.target); + requestStats((item.target as HTMLElement).dataset.staffId!); + } + }); + element.dataset.staffId = id; + statsObserver.observe(element); + }; + onCleanup(() => { + disposed = true; + statsObserver?.disconnect(); + }); + const [entries, { refetch: refetchEntries }] = createResource( () => viewUser()?.id ?? null, async (id) => { try { - return await getUserWorkLog(id); + const cached = workLogs.get(id); + const log = cached ?? await workLogReads.get(id); + return log && log.total <= log.items.length ? log : await getUserWorkLog(id); } catch (err) { if (err instanceof ApiError && err.status === 404) { setError(t("work.userNotFound")); @@ -164,26 +223,6 @@ function StaffWorkContent() { setStaffPage(0); }); - // Card stats are only fetched for the staff on the visible page — the same - // "bounded to what's on screen" shape as the payments roster balances and - // the classes-page member counts, so paging through the whole staff list - // never fires more than PEOPLE_PAGE_SIZE work-log requests at once. - const [cardStats] = createResource( - () => pagedPeople().map((person) => person.id), - async (ids) => { - const rows = await Promise.all( - ids.map(async (id) => { - try { - return [id, summarizeWorkLog(await getUserWorkLog(id, { limit: WORK_LOG_FETCH_LIMIT }))] as const; - } catch { - return [id, null] as const; - } - }), - ); - return new Map(rows); - }, - ); - const entryColumns = createMemo[]>(() => [ { id: "time", @@ -282,6 +321,10 @@ function StaffWorkContent() { await patchWorkEntryById(entry.id, { check_in, check_out }); setEditTarget(null); await refetchEntries(); + workLogs.delete(entry.user); + setStatsByUser((prev) => ({ ...prev, [entry.user]: undefined })); + requestedStats.delete(entry.user); + requestStats(entry.user); setFlash(t("common.saved")); } catch (err) { setError(formatApiError(err)); @@ -318,7 +361,8 @@ function StaffWorkContent() { {(person) => ( { setError(""); @@ -425,6 +469,10 @@ function StaffWorkContent() { try { await deleteWorkEntryById(entry.id); await refetchEntries(); + workLogs.delete(entry.user); + setStatsByUser((prev) => ({ ...prev, [entry.user]: undefined })); + requestedStats.delete(entry.user); + requestStats(entry.user); setFlash(t("common.deleted")); } catch (err) { setError(formatApiError(err)); @@ -437,7 +485,7 @@ function StaffWorkContent() { ); } -function StaffCard(props: { person: PersonRef; stats: StaffCardStats | null | undefined; locale: Locale; onClick: () => void }) { +function StaffCard(props: { person: PersonRef; stats: StaffCardStats | null | undefined; locale: Locale; onClick: () => void; observe: (element: HTMLElement, id: string) => void }) { const t = useT(); const latest = () => props.stats?.latest ?? null; const isOpen = () => latest() != null && latest()!.check_out == null; @@ -450,6 +498,7 @@ function StaffCard(props: { person: PersonRef; stats: StaffCardStats | null | un return (