From 0c8ecec5fd85709328728201163eac6930de9626 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 10:08:22 +0300 Subject: [PATCH] =?UTF-8?q?perf:=20=F0=9F=8E=AF=20insights=20read=20only?= =?UTF-8?q?=20the=20shown=20page,=20teachers=20paint=20at=20once=20-=20ins?= =?UTF-8?q?ights=20read=20signals=20for=20the=20table=20page=20on=20screen?= =?UTF-8?q?,=20then=20per=20page=20=20=20turned;=20a=20signal=20filter=20o?= =?UTF-8?q?r=20sort=20still=20loads=20what=20it=20needs=20and=20the=20=20?= =?UTF-8?q?=20overview=20states=20its=20coverage=20(open:=20212=20?= =?UTF-8?q?=E2=86=92=2022=20requests,=2010=20s=20=E2=86=92=203=20s)=20-=20?= =?UTF-8?q?DataTable=20gains=20an=20optional=20onPageRowsChange=20for=20ca?= =?UTF-8?q?llers=20that=20load=20=20=20per-row=20data=20for=20the=20render?= =?UTF-8?q?ed=20page=20-=20teachers=20roster=20renders=20rows=20as=20soon?= =?UTF-8?q?=20as=20the=20teacher=20list=20arrives=20and=20=20=20fills=20ho?= =?UTF-8?q?meroom=20and=20sections=20from=20the=20shared=20walk;=20no=20ca?= =?UTF-8?q?talog=20read?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/components/ai/insights-board.test.tsx | 24 +++++++--- src/components/ai/insights-board.tsx | 30 ++++++------ .../insights/insight-overview.test.tsx | 2 +- src/components/insights/insight-overview.tsx | 4 +- .../insights/insight-students-table.test.tsx | 23 +++------ .../insights/insight-students-table.tsx | 20 ++------ src/components/ui/data-table.test.tsx | 31 ++++++++++++ src/components/ui/data-table.tsx | 3 ++ src/pages/teachers-roster-page.test.tsx | 31 ++++++++++-- src/pages/teachers-roster-page.tsx | 47 +++++++++---------- 10 files changed, 130 insertions(+), 85 deletions(-) diff --git a/src/components/ai/insights-board.test.tsx b/src/components/ai/insights-board.test.tsx index 5ce3e86..b01ff68 100644 --- a/src/components/ai/insights-board.test.tsx +++ b/src/components/ai/insights-board.test.tsx @@ -1,3 +1,4 @@ +import { createEffect } from "solid-js"; import { cleanup, fireEvent, render, screen, waitFor } from "@solidjs/testing-library"; import { afterEach, expect, it, vi } from "vitest"; import { InsightsBoard } from "./insights-board"; @@ -24,9 +25,15 @@ vi.mock("@/stores/preferences-context", () => ({ 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 }) => ( - - ), + InsightStudentsTable: (props: { rows: { id: string }[]; onPageRowsChange: (rows: { id: string }[]) => void; onInspectAll: () => void }) => { + createEffect(() => props.onPageRowsChange(props.rows.slice(0, 10))); + return ( +
+ + +
+ ); + }, })); afterEach(() => { @@ -35,7 +42,7 @@ afterEach(() => { vi.clearAllMocks(); }); -it("reads only the first 50 student insights until more rows are requested", async () => { +it("reads only the displayed page, then new pages or a signal filter", async () => { api.getMyStudents.mockResolvedValue({ items: Array.from({ length: 200 }, (_, index) => ({ id: `student-${index}`, username: `student-${index}`, display_name: `Student ${index}`, })) }); @@ -43,7 +50,10 @@ it("reads only the first 50 student insights until more rows are requested", asy 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)); + await waitFor(() => expect(api.getInsightByUserId).toHaveBeenCalledTimes(10)); + expect(api.getInsightByUserId).toHaveBeenCalledTimes(10); + fireEvent.click(screen.getByRole("button", { name: "Next page" })); + await waitFor(() => expect(api.getInsightByUserId).toHaveBeenCalledTimes(20)); + fireEvent.click(screen.getByRole("button", { name: "Filter by signal" })); + await waitFor(() => expect(api.getInsightByUserId).toHaveBeenCalledTimes(200)); }); diff --git a/src/components/ai/insights-board.tsx b/src/components/ai/insights-board.tsx index 5550353..37927a4 100644 --- a/src/components/ai/insights-board.tsx +++ b/src/components/ai/insights-board.tsx @@ -52,25 +52,27 @@ 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) => {}; + let requestRows = (_rows: StudentSignal[]) => {}; + let requestAll = () => {}; createEffect(on(() => students.latest, (list) => { if (!list) return; const generation = ++readGeneration; const scope = auth.user()?.id ?? ""; - let queued = 0; + const people = new Map(list.map((person) => [person.id, person])); + const requested = new Set(); 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); + const requestIds = (ids: string[]) => { + const batch = ids.flatMap((id) => { + const person = people.get(id); + if (!person || requested.has(id)) return []; + requested.add(id); + return [person]; + }); + if (!batch.length) return; reads = reads.then(() => { if (generation !== readGeneration) return; return loadStudentSignals(batch, (row) => { @@ -78,7 +80,8 @@ export function InsightsBoard() { }, undefined, scope); }); }; - requestThrough(50); + requestRows = (pageRows) => requestIds(pageRows.map((row) => row.id)); + requestAll = () => requestIds(list.map((person) => person.id)); })); const rows = createMemo(() => Object.values(signals())); const overview = createMemo(() => insightOverview(rows(), students.latest?.length ?? 0)); @@ -112,9 +115,8 @@ export function InsightsBoard() {
requestThrough(requestedCount() + 50)} - onInspectAll={() => requestThrough(students.latest?.length ?? 0)} + onPageRowsChange={(pageRows) => requestRows(pageRows)} + onInspectAll={() => requestAll()} 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/insights/insight-overview.test.tsx b/src/components/insights/insight-overview.test.tsx index 4f726f3..66eefce 100644 --- a/src/components/insights/insight-overview.test.tsx +++ b/src/components/insights/insight-overview.test.tsx @@ -20,5 +20,5 @@ it("labels partial counts and averages with their current coverage", () => { }} />); expect(screen.getByText("40 / 200")).toBeTruthy(); expect(screen.getByText("7 / 50")).toBeTruthy(); - expect(screen.getAllByText("Reading 50 of 200 students…").length).toBeGreaterThan(0); + expect(screen.getAllByText("50 / 200").length).toBeGreaterThan(0); }); diff --git a/src/components/insights/insight-overview.tsx b/src/components/insights/insight-overview.tsx index 64bd733..a46c86f 100644 --- a/src/components/insights/insight-overview.tsx +++ b/src/components/insights/insight-overview.tsx @@ -22,7 +22,7 @@ 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 }) + ? `${o().loaded} / ${o().total}` : t("insights.overview.ofTotal", { total: o().total }); return (
@@ -47,7 +47,7 @@ export function InsightOverview(props: { overview: Overview }) {

- {t("insights.overview.reading", { loaded: o().loaded, total: o().total })} + {coverage()}

diff --git a/src/components/insights/insight-students-table.test.tsx b/src/components/insights/insight-students-table.test.tsx index d7f303b..a8e71e9 100644 --- a/src/components/insights/insight-students-table.test.tsx +++ b/src/components/insights/insight-students-table.test.tsx @@ -8,9 +8,10 @@ vi.mock("@/stores/preferences-context", () => ({ usePreferences: () => ({ locale: () => "en", t: (key: string) => key }), })); vi.mock("@/components/ui/data-table", () => ({ - DataTable: (props: { filters: unknown }) => ( + DataTable: (props: { filters: unknown; onPageRowsChange?: (rows: unknown[]) => void; data: unknown[] }) => (
+ {props.filters as never}
), @@ -26,29 +27,19 @@ afterEach(() => { 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(); +it("forwards page rows and loads all for a signal filter or sort", () => { + const page = 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: "Page rows" })); + expect(page).toHaveBeenCalledOnce(); 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 22b57d3..0a1ab86 100644 --- a/src/components/insights/insight-students-table.tsx +++ b/src/components/insights/insight-students-table.tsx @@ -1,4 +1,4 @@ -import { createMemo, createSignal, onCleanup, onMount, type JSX } from "solid-js"; +import { createMemo, createSignal, 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,8 +35,7 @@ export function InsightStudentsTable(props: { description: string; empty: string; actions?: JSX.Element; - hasMore?: boolean; - onNeedMore?: () => void; + onPageRowsChange?: (rows: StudentSignal[]) => void; onInspectAll?: () => void; }) { const prefs = usePreferences(); @@ -45,19 +44,6 @@ 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, @@ -240,6 +226,7 @@ export function InsightStudentsTable(props: { actions={props.actions} columns={columns()} data={visible()} + onPageRowsChange={props.onPageRowsChange} onRowClick={(row) => void navigate({ to: "/ai/insights/$userId", params: { userId: row.id } })} empty={props.empty} emptyIllustration="people" @@ -263,7 +250,6 @@ 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 b19487c..d88657a 100644 --- a/src/components/ui/data-table.test.tsx +++ b/src/components/ui/data-table.test.tsx @@ -119,6 +119,37 @@ test("paginates client rows without observing the scroll position", () => { } }); +test("reports rendered client and manual page rows", () => { + const rows = Array.from({ length: 12 }, (_, index) => ({ name: `Person ${index + 1}` })); + const onPageRowsChange = vi.fn(); + const client = render(() => ( + + + + )); + expect(onPageRowsChange.mock.lastCall?.[0].map((row: Row) => row.name)).toEqual(rows.slice(0, 10).map((row) => row.name)); + fireEvent.click(screen.getByRole("button", { name: /Next|Sonraki/ })); + expect(onPageRowsChange.mock.lastCall?.[0].map((row: Row) => row.name)).toEqual(["Person 11", "Person 12"]); + client.unmount(); + + onPageRowsChange.mockClear(); + const [page, setPage] = createSignal(0); + render(() => ( + + + + )); + expect(onPageRowsChange.mock.lastCall?.[0].map((row: Row) => row.name)).toEqual(rows.slice(0, 5).map((row) => row.name)); + fireEvent.click(screen.getByRole("button", { name: /Next|Sonraki/ })); + expect(onPageRowsChange.mock.lastCall?.[0].map((row: Row) => row.name)).toEqual(rows.slice(5, 10).map((row) => row.name)); +}); + test("without IntersectionObserver client rows still paginate", () => { vi.stubGlobal("IntersectionObserver", undefined); const rows = Array.from({ length: 60 }, (_, index) => ({ name: `Person ${index + 1}` })); diff --git a/src/components/ui/data-table.tsx b/src/components/ui/data-table.tsx index b21b362..96c18f5 100644 --- a/src/components/ui/data-table.tsx +++ b/src/components/ui/data-table.tsx @@ -99,6 +99,8 @@ export type DataTableProps = { */ mobileLayout?: "cards" | "scroll"; onRowClick?: (row: TData) => void; + /** Reports the rows on the rendered page after paging, search, or sorting changes. */ + onPageRowsChange?: (rows: TData[]) => void; onSearchInput?: (value: string) => void; /** Rows per page on a wide screen; client tables use fewer on phones. */ pageSize?: number; @@ -339,6 +341,7 @@ export function DataTable(props: DataTableProps last) setClientPageIndex(last); }); const visibleRows = () => table.getRowModel().rows; + createEffect(on(visibleRows, (rows) => props.onPageRowsChange?.(rows.map((row) => row.original)))); let sentinel: HTMLDivElement | undefined; const observing = typeof IntersectionObserver !== "undefined"; const nearEnd = () => !!sentinel && sentinel.getBoundingClientRect().top < window.innerHeight + REVEAL_MARGIN_PX; diff --git a/src/pages/teachers-roster-page.test.tsx b/src/pages/teachers-roster-page.test.tsx index e2d50f9..8b9abf2 100644 --- a/src/pages/teachers-roster-page.test.tsx +++ b/src/pages/teachers-roster-page.test.tsx @@ -27,14 +27,37 @@ afterEach(() => { vi.clearAllMocks(); }); -test("shows teachers while section reads are still pending", async () => { +test("shows teachers before the class list and fills both columns as reads finish", async () => { + let resolveClasses!: (value: unknown) => void; + let resolveInstances!: (value: unknown) => void; getUserSearch.mockResolvedValue({ items: [{ id: "t1", username: "teacher", display_name: "Ayşe" }] }); - getClasses.mockResolvedValue({ items: [{ id: "c1", name: "9-A", grade_level: 9, teacher: null }] }); - getCourses.mockResolvedValue({ items: [{ id: "math", title: "Math" }] }); - getClassInstances.mockImplementation(() => new Promise(() => {})); + getClasses.mockImplementation(() => new Promise((resolve) => { resolveClasses = resolve; })); + getClassInstances.mockImplementation(() => new Promise((resolve) => { resolveInstances = resolve; })); render(() => ); expect(await screen.findByText("Ayşe")).toBeTruthy(); + expect(screen.getAllByLabelText("Loading…")).toHaveLength(2); + expect(getClasses).toHaveBeenCalledTimes(1); + expect(getClassInstances).not.toHaveBeenCalled(); + + resolveClasses({ items: [{ id: "c1", name: "9-A", grade_level: 9, teacher: { id: "t1" } }] }); + expect(await screen.findByText("9-A")).toBeTruthy(); await waitFor(() => expect(getClassInstances).toHaveBeenCalledTimes(1)); + expect(screen.getAllByLabelText("Loading…")).toHaveLength(1); + + resolveInstances({ items: [{ id: "i1", course: "math", title: "Advanced Math", teachers: [{ id: "t1" }] }] }); + expect(await screen.findByText("Advanced Math — 9-A")).toBeTruthy(); + expect(getCourses).not.toHaveBeenCalled(); +}); + +test("does not walk classes when the teacher list is empty", async () => { + getUserSearch.mockResolvedValue({ items: [] }); + + render(() => ); + + expect(await screen.findByText("No teachers yet.")).toBeTruthy(); + expect(getClasses).not.toHaveBeenCalled(); + expect(getClassInstances).not.toHaveBeenCalled(); + expect(getCourses).not.toHaveBeenCalled(); }); diff --git a/src/pages/teachers-roster-page.tsx b/src/pages/teachers-roster-page.tsx index 64adac7..344b885 100644 --- a/src/pages/teachers-roster-page.tsx +++ b/src/pages/teachers-roster-page.tsx @@ -3,9 +3,8 @@ import type { ColumnDef } from "@tanstack/solid-table"; import { Show, Suspense, createMemo, createSignal } from "solid-js"; import { createResource } from "@/lib/create-resource"; import { matchesSearch } from "@/lib/search-text"; -import { getCourses } from "@/api/courses"; import { getUserSearch } from "@/api/users"; -import { formatApiError, type Course, type PersonRef } from "@/api/client"; +import { formatApiError, type PersonRef } from "@/api/client"; import { formatInstanceLabel, loadSchoolSections, classList } from "@/lib/instance-labels"; import { RouteGuard } from "@/components/layout/route-guard"; import { CreateUserPanel } from "@/components/users/create-user-panel"; @@ -23,9 +22,9 @@ const ROSTER_PAGE_SIZE = 10; type TeacherRow = { person: PersonRef; /** Classes this teacher is the homeroom teacher (sınıf öğretmeni) of. */ - homeroom: string[]; + homeroom: string[] | null; /** The sections they teach, as " — <şube>". */ - sections: string[]; + sections: string[] | null; }; export default function TeachersRosterPage() { @@ -47,37 +46,33 @@ function TeachersRosterContent() { const navigate = useNavigate(); const [creating, setCreating] = createSignal(false); - const [data, { refetch }] = createResource(async () => { - const [teachers, classes] = await Promise.all([ - getUserSearch("", undefined, "teacher"), - classList().then((items) => ({ items })), - ]); + const [data, { refetch }] = createResource(() => getUserSearch("", undefined, "teacher")); + const [homeroomNames] = createResource(() => data.latest?.items.length ? true : null, async () => { + const classes = await classList(); const push = (map: Map, id: string, value: string) => map.set(id, [...(map.get(id) ?? []), value]); const byName = (a: string, b: string) => a.localeCompare(b, "tr", { numeric: true }); const homeroom = new Map(); - for (const cls of classes.items) if (cls.teacher) push(homeroom, cls.teacher.id, cls.name); - return teachers.items.map((person) => ({ - person, - homeroom: (homeroom.get(person.id) ?? []).sort(byName), - sections: [], - })); + for (const cls of classes) if (cls.teacher) push(homeroom, cls.teacher.id, cls.name); + return new Map([...homeroom].map(([id, names]) => [id, names.sort(byName)])); }); - const [sectionNames] = createResource(() => data.latest ? true : null, async () => { - const courses = await getCourses().catch(() => ({ items: [] as Course[] })); - const titles = new Map(courses.items.map((course) => [course.id, course.title])); + const [sectionNames] = createResource(() => data.latest?.items.length ? true : null, async () => { const push = (map: Map, id: string, value: string) => map.set(id, [...(map.get(id) ?? []), value]); const byName = (a: string, b: string) => a.localeCompare(b, "tr", { numeric: true }); const perClass = await loadSchoolSections(); const sections = new Map(); for (const { klass, sections: instances } of perClass) { for (const instance of instances) { - const label = formatInstanceLabel(titles.get(instance.course) ?? null, klass.name); + const label = formatInstanceLabel(instance.title?.trim() || null, klass.name); for (const teacher of instance.teachers) push(sections, teacher.id, label); } } return new Map([...sections].map(([id, names]) => [id, [...new Set(names)].sort(byName)])); }); - const mergedRows = createMemo(() => (data.latest ?? []).map((row) => ({ ...row, sections: sectionNames.latest?.get(row.person.id) ?? [] }))); + const mergedRows = createMemo(() => (data.latest?.items ?? []).map((person) => ({ + person, + homeroom: homeroomNames.latest ? homeroomNames.latest.get(person.id) ?? [] : null, + sections: sectionNames.latest ? sectionNames.latest.get(person.id) ?? [] : null, + }))); const open = (row: TeacherRow) => void navigate({ to: "/profile/$userId", params: { userId: row.person.id } }); @@ -88,21 +83,25 @@ function TeachersRosterContent() { size: 260, // Empty lists read as "" so DataTable draws its one empty-cell dash, // the same one the homeroom column gets. - accessorFn: (row) => row.sections.join(", "), + accessorFn: (row) => row.sections?.join(", ") ?? "…", header: t("roster.taughtSections"), meta: { cellClass: "max-w-0" }, cell: (cell) => { const list = cell.row.original.sections; - return {list.join(", ")}; + return }> + {(names) => {names().join(", ")}} + ; }, }, { id: "homeroom", size: 130, - accessorFn: (row) => row.homeroom.join(", "), + accessorFn: (row) => row.homeroom?.join(", ") ?? "…", header: t("roster.homeroomOf"), meta: { cellClass: "max-w-0" }, - cell: (cell) => {cell.row.original.homeroom.join(", ")}, + cell: (cell) => }> + {(names) => {names().join(", ")}} + , }, { id: "actions",