🎯 insights read only the shown page, teachers paint at once
Browse files at this commit0c8ecec5fd85709328728201163eac6930de9626Parent: 48313a5- perf
- 🎯 insights read only the shown page, teachers paint at once
10 changed files +130 -85
- src/components/ai/insights-board.test.tsx +17 -7
- src/components/ai/insights-board.tsx +16 -14
- src/components/insights/insight-overview.test.tsx +1 -1
- src/components/insights/insight-overview.tsx +2 -2
- src/components/insights/insight-students-table.test.tsx +7 -16
- src/components/insights/insight-students-table.tsx +3 -17
- src/components/ui/data-table.test.tsx +31 -0
- src/components/ui/data-table.tsx +3 -0
- src/pages/teachers-roster-page.test.tsx +27 -4
- src/pages/teachers-roster-page.tsx +23 -24
src/components/ai/insights-board.test.tsxmodified+17 -7
| @@ -1,3 +1,4 @@ | |||
| 1 | +import { createEffect } from "solid-js"; | ||
| 1 | import { cleanup, fireEvent, render, screen, waitFor } from "@solidjs/testing-library"; | 2 | import { cleanup, fireEvent, render, screen, waitFor } from "@solidjs/testing-library"; |
| 2 | import { afterEach, expect, it, vi } from "vitest"; | 3 | import { afterEach, expect, it, vi } from "vitest"; |
| 3 | import { InsightsBoard } from "./insights-board"; | 4 | import { InsightsBoard } from "./insights-board"; |
| @@ -24,9 +25,15 @@ vi.mock("@/stores/preferences-context", () => ({ | |||
| 24 | vi.mock("@/components/ui/data-table", () => ({ DataTableSkeleton: () => null })); | 25 | vi.mock("@/components/ui/data-table", () => ({ DataTableSkeleton: () => null })); |
| 25 | vi.mock("@/components/insights/insight-overview", () => ({ InsightOverview: () => null })); | 26 | vi.mock("@/components/insights/insight-overview", () => ({ InsightOverview: () => null })); |
| 26 | vi.mock("@/components/insights/insight-students-table", () => ({ | 27 | vi.mock("@/components/insights/insight-students-table", () => ({ |
| 27 | - InsightStudentsTable: (props: { onNeedMore: () => void }) => ( | 28 | + InsightStudentsTable: (props: { rows: { id: string }[]; onPageRowsChange: (rows: { id: string }[]) => void; onInspectAll: () => void }) => { |
| 28 | - <button type="button" onClick={props.onNeedMore}>Load next rows</button> | 29 | + createEffect(() => props.onPageRowsChange(props.rows.slice(0, 10))); |
| 29 | - ), | 30 | + return ( |
| 31 | + <div> | ||
| 32 | + <button type="button" onClick={() => props.onPageRowsChange(props.rows.slice(10, 20))}>Next page</button> | ||
| 33 | + <button type="button" onClick={props.onInspectAll}>Filter by signal</button> | ||
| 34 | + </div> | ||
| 35 | + ); | ||
| 36 | + }, | ||
| 30 | })); | 37 | })); |
| 31 | 38 | ||
| 32 | afterEach(() => { | 39 | afterEach(() => { |
| @@ -35,7 +42,7 @@ afterEach(() => { | |||
| 35 | vi.clearAllMocks(); | 42 | vi.clearAllMocks(); |
| 36 | }); | 43 | }); |
| 37 | 44 | ||
| 38 | -it("reads only the first 50 student insights until more rows are requested", async () => { | 45 | +it("reads only the displayed page, then new pages or a signal filter", async () => { |
| 39 | api.getMyStudents.mockResolvedValue({ items: Array.from({ length: 200 }, (_, index) => ({ | 46 | api.getMyStudents.mockResolvedValue({ items: Array.from({ length: 200 }, (_, index) => ({ |
| 40 | id: `student-${index}`, username: `student-${index}`, display_name: `Student ${index}`, | 47 | id: `student-${index}`, username: `student-${index}`, display_name: `Student ${index}`, |
| 41 | })) }); | 48 | })) }); |
| @@ -43,7 +50,10 @@ it("reads only the first 50 student insights until more rows are requested", asy | |||
| 43 | user_id: id, summary: null, attention: [], cards: [], segments: [], | 50 | user_id: id, summary: null, attention: [], cards: [], segments: [], |
| 44 | })); | 51 | })); |
| 45 | render(() => <InsightsBoard />); | 52 | render(() => <InsightsBoard />); |
| 46 | - await waitFor(() => expect(api.getInsightByUserId).toHaveBeenCalledTimes(50)); | 53 | + await waitFor(() => expect(api.getInsightByUserId).toHaveBeenCalledTimes(10)); |
| 47 | - fireEvent.click(screen.getByRole("button", { name: "Load next rows" })); | 54 | + expect(api.getInsightByUserId).toHaveBeenCalledTimes(10); |
| 48 | - await waitFor(() => expect(api.getInsightByUserId).toHaveBeenCalledTimes(100)); | 55 | + fireEvent.click(screen.getByRole("button", { name: "Next page" })); |
| 56 | + await waitFor(() => expect(api.getInsightByUserId).toHaveBeenCalledTimes(20)); | ||
| 57 | + fireEvent.click(screen.getByRole("button", { name: "Filter by signal" })); | ||
| 58 | + await waitFor(() => expect(api.getInsightByUserId).toHaveBeenCalledTimes(200)); | ||
| 49 | }); | 59 | }); |
src/components/ai/insights-board.tsxmodified+16 -14
| @@ -52,25 +52,27 @@ export function InsightsBoard() { | |||
| 52 | // Each student's analysis lands in its row as it is read; rows start as | 52 | // Each student's analysis lands in its row as it is read; rows start as |
| 53 | // "not loaded" so the table and the overview never show a guessed value. | 53 | // "not loaded" so the table and the overview never show a guessed value. |
| 54 | const [signals, setSignals] = createSignal<Record<string, StudentSignal>>({}); | 54 | const [signals, setSignals] = createSignal<Record<string, StudentSignal>>({}); |
| 55 | - const [requestedCount, setRequestedCount] = createSignal(0); | ||
| 56 | let readGeneration = 0; | 55 | let readGeneration = 0; |
| 57 | - let requestThrough = (_count: number) => {}; | 56 | + let requestRows = (_rows: StudentSignal[]) => {}; |
| 57 | + let requestAll = () => {}; | ||
| 58 | createEffect(on(() => students.latest, (list) => { | 58 | createEffect(on(() => students.latest, (list) => { |
| 59 | if (!list) return; | 59 | if (!list) return; |
| 60 | const generation = ++readGeneration; | 60 | const generation = ++readGeneration; |
| 61 | const scope = auth.user()?.id ?? ""; | 61 | const scope = auth.user()?.id ?? ""; |
| 62 | - let queued = 0; | 62 | + const people = new Map(list.map((person) => [person.id, person])); |
| 63 | + const requested = new Set<string>(); | ||
| 63 | let reads = Promise.resolve(); | 64 | let reads = Promise.resolve(); |
| 64 | setSignals(Object.fromEntries(list.map((person) => [person.id, | 65 | setSignals(Object.fromEntries(list.map((person) => [person.id, |
| 65 | cachedStudentSignal(person, scope) ?? toStudentSignal({ id: person.id, name: personLabel(person) }, null, null), | 66 | cachedStudentSignal(person, scope) ?? toStudentSignal({ id: person.id, name: personLabel(person) }, null, null), |
| 66 | ]))); | 67 | ]))); |
| 67 | - setRequestedCount(Math.min(50, list.length)); | 68 | + const requestIds = (ids: string[]) => { |
| 68 | - requestThrough = (count) => { | 69 | + const batch = ids.flatMap((id) => { |
| 69 | - const end = Math.min(count, list.length); | 70 | + const person = people.get(id); |
| 70 | - if (end <= queued) return; | 71 | + if (!person || requested.has(id)) return []; |
| 71 | - const batch = list.slice(queued, end); | 72 | + requested.add(id); |
| 72 | - queued = end; | 73 | + return [person]; |
| 73 | - setRequestedCount(end); | 74 | + }); |
| 75 | + if (!batch.length) return; | ||
| 74 | reads = reads.then(() => { | 76 | reads = reads.then(() => { |
| 75 | if (generation !== readGeneration) return; | 77 | if (generation !== readGeneration) return; |
| 76 | return loadStudentSignals(batch, (row) => { | 78 | return loadStudentSignals(batch, (row) => { |
| @@ -78,7 +80,8 @@ export function InsightsBoard() { | |||
| 78 | }, undefined, scope); | 80 | }, undefined, scope); |
| 79 | }); | 81 | }); |
| 80 | }; | 82 | }; |
| 81 | - requestThrough(50); | 83 | + requestRows = (pageRows) => requestIds(pageRows.map((row) => row.id)); |
| 84 | + requestAll = () => requestIds(list.map((person) => person.id)); | ||
| 82 | })); | 85 | })); |
| 83 | const rows = createMemo(() => Object.values(signals())); | 86 | const rows = createMemo(() => Object.values(signals())); |
| 84 | const overview = createMemo(() => insightOverview(rows(), students.latest?.length ?? 0)); | 87 | const overview = createMemo(() => insightOverview(rows(), students.latest?.length ?? 0)); |
| @@ -112,9 +115,8 @@ export function InsightsBoard() { | |||
| 112 | <section> | 115 | <section> |
| 113 | <InsightStudentsTable | 116 | <InsightStudentsTable |
| 114 | rows={rows()} | 117 | rows={rows()} |
| 115 | - hasMore={requestedCount() < (students.latest?.length ?? 0)} | 118 | + onPageRowsChange={(pageRows) => requestRows(pageRows)} |
| 116 | - onNeedMore={() => requestThrough(requestedCount() + 50)} | 119 | + onInspectAll={() => requestAll()} |
| 117 | - onInspectAll={() => requestThrough(students.latest?.length ?? 0)} | ||
| 118 | title={tx("insights.title")} | 120 | title={tx("insights.title")} |
| 119 | description={role() === "parent" ? tx("insights.parentSubtitle") : tx("insights.subtitle")} | 121 | description={role() === "parent" ? tx("insights.parentSubtitle") : tx("insights.subtitle")} |
| 120 | empty={role() === "parent" ? tx("insights.emptyLinkedStudents") : tx("insights.emptyStudents")} | 122 | empty={role() === "parent" ? tx("insights.emptyLinkedStudents") : tx("insights.emptyStudents")} |
src/components/insights/insight-overview.test.tsxmodified+1 -1
| @@ -20,5 +20,5 @@ it("labels partial counts and averages with their current coverage", () => { | |||
| 20 | }} />); | 20 | }} />); |
| 21 | expect(screen.getByText("40 / 200")).toBeTruthy(); | 21 | expect(screen.getByText("40 / 200")).toBeTruthy(); |
| 22 | expect(screen.getByText("7 / 50")).toBeTruthy(); | 22 | expect(screen.getByText("7 / 50")).toBeTruthy(); |
| 23 | - expect(screen.getAllByText("Reading 50 of 200 students…").length).toBeGreaterThan(0); | 23 | + expect(screen.getAllByText("50 / 200").length).toBeGreaterThan(0); |
| 24 | }); | 24 | }); |
src/components/insights/insight-overview.tsxmodified+2 -2
| @@ -22,7 +22,7 @@ export function InsightOverview(props: { overview: Overview }) { | |||
| 22 | const o = () => props.overview; | 22 | const o = () => props.overview; |
| 23 | const partial = () => o().loaded < o().total; | 23 | const partial = () => o().loaded < o().total; |
| 24 | const coverage = () => partial() | 24 | const coverage = () => partial() |
| 25 | - ? t("insights.overview.reading", { loaded: o().loaded, total: o().total }) | 25 | + ? `${o().loaded} / ${o().total}` |
| 26 | : t("insights.overview.ofTotal", { total: o().total }); | 26 | : t("insights.overview.ofTotal", { total: o().total }); |
| 27 | return ( | 27 | return ( |
| 28 | <section class="space-y-2" aria-label={t("insights.summary")}> | 28 | <section class="space-y-2" aria-label={t("insights.summary")}> |
| @@ -47,7 +47,7 @@ export function InsightOverview(props: { overview: Overview }) { | |||
| 47 | </div> | 47 | </div> |
| 48 | <Show when={o().loaded < o().total}> | 48 | <Show when={o().loaded < o().total}> |
| 49 | <p class="text-xs text-muted-foreground" role="status"> | 49 | <p class="text-xs text-muted-foreground" role="status"> |
| 50 | - {t("insights.overview.reading", { loaded: o().loaded, total: o().total })} | 50 | + {coverage()} |
| 51 | </p> | 51 | </p> |
| 52 | </Show> | 52 | </Show> |
| 53 | </section> | 53 | </section> |
src/components/insights/insight-students-table.test.tsxmodified+7 -16
| @@ -8,9 +8,10 @@ vi.mock("@/stores/preferences-context", () => ({ | |||
| 8 | usePreferences: () => ({ locale: () => "en", t: (key: string) => key }), | 8 | usePreferences: () => ({ locale: () => "en", t: (key: string) => key }), |
| 9 | })); | 9 | })); |
| 10 | vi.mock("@/components/ui/data-table", () => ({ | 10 | vi.mock("@/components/ui/data-table", () => ({ |
| 11 | - DataTable: (props: { filters: unknown }) => ( | 11 | + DataTable: (props: { filters: unknown; onPageRowsChange?: (rows: unknown[]) => void; data: unknown[] }) => ( |
| 12 | <div> | 12 | <div> |
| 13 | <table><thead><tr><th><button type="button">Sort</button></th></tr></thead></table> | 13 | <table><thead><tr><th><button type="button">Sort</button></th></tr></thead></table> |
| 14 | + <button type="button" onClick={() => props.onPageRowsChange?.(props.data)}>Page rows</button> | ||
| 14 | {props.filters as never} | 15 | {props.filters as never} |
| 15 | </div> | 16 | </div> |
| 16 | ), | 17 | ), |
| @@ -26,29 +27,19 @@ afterEach(() => { | |||
| 26 | vi.unstubAllGlobals(); | 27 | vi.unstubAllGlobals(); |
| 27 | }); | 28 | }); |
| 28 | 29 | ||
| 29 | -it("requests more only near the table end, and loads all for a signal filter or sort", () => { | 30 | +it("forwards page rows and loads all for a signal filter or sort", () => { |
| 30 | - let notify: ((entries: { isIntersecting: boolean }[]) => void) | undefined; | 31 | + const page = vi.fn(); |
| 31 | - vi.stubGlobal("IntersectionObserver", class { | ||
| 32 | - constructor(callback: typeof notify) { notify = callback; } | ||
| 33 | - observe() {} | ||
| 34 | - disconnect() {} | ||
| 35 | - }); | ||
| 36 | - const more = vi.fn(); | ||
| 37 | const all = vi.fn(); | 32 | const all = vi.fn(); |
| 38 | render(() => <InsightStudentsTable | 33 | render(() => <InsightStudentsTable |
| 39 | rows={[toStudentSignal({ id: "a", name: "A" }, null, null)]} | 34 | rows={[toStudentSignal({ id: "a", name: "A" }, null, null)]} |
| 40 | title="Students" | 35 | title="Students" |
| 41 | description="" | 36 | description="" |
| 42 | empty="" | 37 | empty="" |
| 43 | - hasMore | 38 | + onPageRowsChange={page} |
| 44 | - onNeedMore={more} | ||
| 45 | onInspectAll={all} | 39 | onInspectAll={all} |
| 46 | />); | 40 | />); |
| 47 | - expect(more).not.toHaveBeenCalled(); | 41 | + fireEvent.click(screen.getByRole("button", { name: "Page rows" })); |
| 48 | - notify?.([{ isIntersecting: false }]); | 42 | + expect(page).toHaveBeenCalledOnce(); |
| 49 | - expect(more).not.toHaveBeenCalled(); | ||
| 50 | - notify?.([{ isIntersecting: true }]); | ||
| 51 | - expect(more).toHaveBeenCalledTimes(1); | ||
| 52 | fireEvent.click(screen.getByRole("button", { name: "Sort" })); | 43 | fireEvent.click(screen.getByRole("button", { name: "Sort" })); |
| 53 | fireEvent.click(screen.getByRole("button", { name: "Attention filter" })); | 44 | fireEvent.click(screen.getByRole("button", { name: "Attention filter" })); |
| 54 | expect(all).toHaveBeenCalledTimes(2); | 45 | expect(all).toHaveBeenCalledTimes(2); |
src/components/insights/insight-students-table.tsxmodified+3 -17
| @@ -1,4 +1,4 @@ | |||
| 1 | -import { createMemo, createSignal, onCleanup, onMount, type JSX } from "solid-js"; | 1 | +import { createMemo, createSignal, type JSX } from "solid-js"; |
| 2 | import { Link, useNavigate } from "@tanstack/solid-router"; | 2 | import { Link, useNavigate } from "@tanstack/solid-router"; |
| 3 | import type { ColumnDef } from "@tanstack/solid-table"; | 3 | import type { ColumnDef } from "@tanstack/solid-table"; |
| 4 | import { Badge } from "@/components/ui/badge"; | 4 | import { Badge } from "@/components/ui/badge"; |
| @@ -35,8 +35,7 @@ export function InsightStudentsTable(props: { | |||
| 35 | description: string; | 35 | description: string; |
| 36 | empty: string; | 36 | empty: string; |
| 37 | actions?: JSX.Element; | 37 | actions?: JSX.Element; |
| 38 | - hasMore?: boolean; | 38 | + onPageRowsChange?: (rows: StudentSignal[]) => void; |
| 39 | - onNeedMore?: () => void; | ||
| 40 | onInspectAll?: () => void; | 39 | onInspectAll?: () => void; |
| 41 | }) { | 40 | }) { |
| 42 | const prefs = usePreferences(); | 41 | const prefs = usePreferences(); |
| @@ -45,19 +44,6 @@ export function InsightStudentsTable(props: { | |||
| 45 | const t = (key: string, vars?: Record<string, string | number>) => prefs.t(key as never, vars); | 44 | const t = (key: string, vars?: Record<string, string | number>) => prefs.t(key as never, vars); |
| 46 | const rt = (key: Parameters<typeof runReportText>[1]) => runReportText(locale(), key); | 45 | const rt = (key: Parameters<typeof runReportText>[1]) => runReportText(locale(), key); |
| 47 | const [filter, setFilter] = createSignal<Filter>("all"); | 46 | const [filter, setFilter] = createSignal<Filter>("all"); |
| 48 | - let sentinel: HTMLDivElement | undefined; | ||
| 49 | - onMount(() => { | ||
| 50 | - if (!sentinel) return; | ||
| 51 | - if (typeof IntersectionObserver === "undefined") { | ||
| 52 | - props.onInspectAll?.(); | ||
| 53 | - return; | ||
| 54 | - } | ||
| 55 | - const observer = new IntersectionObserver((entries) => { | ||
| 56 | - if (entries.some((entry) => entry.isIntersecting) && props.hasMore) props.onNeedMore?.(); | ||
| 57 | - }, { rootMargin: "0px 0px 600px 0px" }); | ||
| 58 | - observer.observe(sentinel); | ||
| 59 | - onCleanup(() => observer.disconnect()); | ||
| 60 | - }); | ||
| 61 | const visible = createMemo(() => | 47 | const visible = createMemo(() => |
| 62 | props.rows.filter((row) => | 48 | props.rows.filter((row) => |
| 63 | filter() === "attention" ? row.attention > 0 : filter() === "none" ? row.state === "no_summary" : true, | 49 | filter() === "attention" ? row.attention > 0 : filter() === "none" ? row.state === "no_summary" : true, |
| @@ -240,6 +226,7 @@ export function InsightStudentsTable(props: { | |||
| 240 | actions={props.actions} | 226 | actions={props.actions} |
| 241 | columns={columns()} | 227 | columns={columns()} |
| 242 | data={visible()} | 228 | data={visible()} |
| 229 | + onPageRowsChange={props.onPageRowsChange} | ||
| 243 | onRowClick={(row) => void navigate({ to: "/ai/insights/$userId", params: { userId: row.id } })} | 230 | onRowClick={(row) => void navigate({ to: "/ai/insights/$userId", params: { userId: row.id } })} |
| 244 | empty={props.empty} | 231 | empty={props.empty} |
| 245 | emptyIllustration="people" | 232 | emptyIllustration="people" |
| @@ -263,7 +250,6 @@ export function InsightStudentsTable(props: { | |||
| 263 | tableClass="insight-grid-table min-w-[60rem]" | 250 | tableClass="insight-grid-table min-w-[60rem]" |
| 264 | storageKey="insight-students-v2" | 251 | storageKey="insight-students-v2" |
| 265 | /> | 252 | /> |
| 266 | - <div ref={sentinel} aria-hidden="true" class="h-px" /> | ||
| 267 | </div> | 253 | </div> |
| 268 | ); | 254 | ); |
| 269 | } | 255 | } |
src/components/ui/data-table.test.tsxmodified+31 -0
| @@ -119,6 +119,37 @@ test("paginates client rows without observing the scroll position", () => { | |||
| 119 | } | 119 | } |
| 120 | }); | 120 | }); |
| 121 | 121 | ||
| 122 | +test("reports rendered client and manual page rows", () => { | ||
| 123 | + const rows = Array.from({ length: 12 }, (_, index) => ({ name: `Person ${index + 1}` })); | ||
| 124 | + const onPageRowsChange = vi.fn(); | ||
| 125 | + const client = render(() => ( | ||
| 126 | + <PreferencesProvider> | ||
| 127 | + <DataTable columns={[columns[0]]} data={rows} onPageRowsChange={onPageRowsChange} enableColumnVisibility={false} /> | ||
| 128 | + </PreferencesProvider> | ||
| 129 | + )); | ||
| 130 | + expect(onPageRowsChange.mock.lastCall?.[0].map((row: Row) => row.name)).toEqual(rows.slice(0, 10).map((row) => row.name)); | ||
| 131 | + fireEvent.click(screen.getByRole("button", { name: /Next|Sonraki/ })); | ||
| 132 | + expect(onPageRowsChange.mock.lastCall?.[0].map((row: Row) => row.name)).toEqual(["Person 11", "Person 12"]); | ||
| 133 | + client.unmount(); | ||
| 134 | + | ||
| 135 | + onPageRowsChange.mockClear(); | ||
| 136 | + const [page, setPage] = createSignal(0); | ||
| 137 | + render(() => ( | ||
| 138 | + <PreferencesProvider> | ||
| 139 | + <DataTable | ||
| 140 | + columns={[columns[0]]} | ||
| 141 | + data={rows.slice(page() * 5, page() * 5 + 5)} | ||
| 142 | + manualPagination={{ pageIndex: page(), pageSize: 5, total: rows.length, onPageChange: setPage }} | ||
| 143 | + onPageRowsChange={onPageRowsChange} | ||
| 144 | + enableColumnVisibility={false} | ||
| 145 | + /> | ||
| 146 | + </PreferencesProvider> | ||
| 147 | + )); | ||
| 148 | + expect(onPageRowsChange.mock.lastCall?.[0].map((row: Row) => row.name)).toEqual(rows.slice(0, 5).map((row) => row.name)); | ||
| 149 | + fireEvent.click(screen.getByRole("button", { name: /Next|Sonraki/ })); | ||
| 150 | + expect(onPageRowsChange.mock.lastCall?.[0].map((row: Row) => row.name)).toEqual(rows.slice(5, 10).map((row) => row.name)); | ||
| 151 | +}); | ||
| 152 | + | ||
| 122 | test("without IntersectionObserver client rows still paginate", () => { | 153 | test("without IntersectionObserver client rows still paginate", () => { |
| 123 | vi.stubGlobal("IntersectionObserver", undefined); | 154 | vi.stubGlobal("IntersectionObserver", undefined); |
| 124 | const rows = Array.from({ length: 60 }, (_, index) => ({ name: `Person ${index + 1}` })); | 155 | const rows = Array.from({ length: 60 }, (_, index) => ({ name: `Person ${index + 1}` })); |
src/components/ui/data-table.tsxmodified+3 -0
| @@ -99,6 +99,8 @@ export type DataTableProps<TData, TValue = unknown> = { | |||
| 99 | */ | 99 | */ |
| 100 | mobileLayout?: "cards" | "scroll"; | 100 | mobileLayout?: "cards" | "scroll"; |
| 101 | onRowClick?: (row: TData) => void; | 101 | onRowClick?: (row: TData) => void; |
| 102 | + /** Reports the rows on the rendered page after paging, search, or sorting changes. */ | ||
| 103 | + onPageRowsChange?: (rows: TData[]) => void; | ||
| 102 | onSearchInput?: (value: string) => void; | 104 | onSearchInput?: (value: string) => void; |
| 103 | /** Rows per page on a wide screen; client tables use fewer on phones. */ | 105 | /** Rows per page on a wide screen; client tables use fewer on phones. */ |
| 104 | pageSize?: number; | 106 | pageSize?: number; |
| @@ -339,6 +341,7 @@ export function DataTable<TData, TValue = unknown>(props: DataTableProps<TData, | |||
| 339 | if (clientPageIndex() > last) setClientPageIndex(last); | 341 | if (clientPageIndex() > last) setClientPageIndex(last); |
| 340 | }); | 342 | }); |
| 341 | const visibleRows = () => table.getRowModel().rows; | 343 | const visibleRows = () => table.getRowModel().rows; |
| 344 | + createEffect(on(visibleRows, (rows) => props.onPageRowsChange?.(rows.map((row) => row.original)))); | ||
| 342 | let sentinel: HTMLDivElement | undefined; | 345 | let sentinel: HTMLDivElement | undefined; |
| 343 | const observing = typeof IntersectionObserver !== "undefined"; | 346 | const observing = typeof IntersectionObserver !== "undefined"; |
| 344 | const nearEnd = () => !!sentinel && sentinel.getBoundingClientRect().top < window.innerHeight + REVEAL_MARGIN_PX; | 347 | const nearEnd = () => !!sentinel && sentinel.getBoundingClientRect().top < window.innerHeight + REVEAL_MARGIN_PX; |
src/pages/teachers-roster-page.test.tsxmodified+27 -4
| @@ -27,14 +27,37 @@ afterEach(() => { | |||
| 27 | vi.clearAllMocks(); | 27 | vi.clearAllMocks(); |
| 28 | }); | 28 | }); |
| 29 | 29 | ||
| 30 | -test("shows teachers while section reads are still pending", async () => { | 30 | +test("shows teachers before the class list and fills both columns as reads finish", async () => { |
| 31 | + let resolveClasses!: (value: unknown) => void; | ||
| 32 | + let resolveInstances!: (value: unknown) => void; | ||
| 31 | getUserSearch.mockResolvedValue({ items: [{ id: "t1", username: "teacher", display_name: "Ayşe" }] }); | 33 | getUserSearch.mockResolvedValue({ items: [{ id: "t1", username: "teacher", display_name: "Ayşe" }] }); |
| 32 | - getClasses.mockResolvedValue({ items: [{ id: "c1", name: "9-A", grade_level: 9, teacher: null }] }); | 34 | + getClasses.mockImplementation(() => new Promise((resolve) => { resolveClasses = resolve; })); |
| 33 | - getCourses.mockResolvedValue({ items: [{ id: "math", title: "Math" }] }); | 35 | + getClassInstances.mockImplementation(() => new Promise((resolve) => { resolveInstances = resolve; })); |
| 34 | - getClassInstances.mockImplementation(() => new Promise(() => {})); | ||
| 35 | 36 | ||
| 36 | render(() => <PreferencesProvider><TeachersRosterPage /></PreferencesProvider>); | 37 | render(() => <PreferencesProvider><TeachersRosterPage /></PreferencesProvider>); |
| 37 | 38 | ||
| 38 | expect(await screen.findByText("Ayşe")).toBeTruthy(); | 39 | expect(await screen.findByText("Ayşe")).toBeTruthy(); |
| 40 | + expect(screen.getAllByLabelText("Loading…")).toHaveLength(2); | ||
| 41 | + expect(getClasses).toHaveBeenCalledTimes(1); | ||
| 42 | + expect(getClassInstances).not.toHaveBeenCalled(); | ||
| 43 | + | ||
| 44 | + resolveClasses({ items: [{ id: "c1", name: "9-A", grade_level: 9, teacher: { id: "t1" } }] }); | ||
| 45 | + expect(await screen.findByText("9-A")).toBeTruthy(); | ||
| 39 | await waitFor(() => expect(getClassInstances).toHaveBeenCalledTimes(1)); | 46 | await waitFor(() => expect(getClassInstances).toHaveBeenCalledTimes(1)); |
| 47 | + expect(screen.getAllByLabelText("Loading…")).toHaveLength(1); | ||
| 48 | + | ||
| 49 | + resolveInstances({ items: [{ id: "i1", course: "math", title: "Advanced Math", teachers: [{ id: "t1" }] }] }); | ||
| 50 | + expect(await screen.findByText("Advanced Math — 9-A")).toBeTruthy(); | ||
| 51 | + expect(getCourses).not.toHaveBeenCalled(); | ||
| 52 | +}); | ||
| 53 | + | ||
| 54 | +test("does not walk classes when the teacher list is empty", async () => { | ||
| 55 | + getUserSearch.mockResolvedValue({ items: [] }); | ||
| 56 | + | ||
| 57 | + render(() => <PreferencesProvider><TeachersRosterPage /></PreferencesProvider>); | ||
| 58 | + | ||
| 59 | + expect(await screen.findByText("No teachers yet.")).toBeTruthy(); | ||
| 60 | + expect(getClasses).not.toHaveBeenCalled(); | ||
| 61 | + expect(getClassInstances).not.toHaveBeenCalled(); | ||
| 62 | + expect(getCourses).not.toHaveBeenCalled(); | ||
| 40 | }); | 63 | }); |
src/pages/teachers-roster-page.tsxmodified+23 -24
| @@ -3,9 +3,8 @@ import type { ColumnDef } from "@tanstack/solid-table"; | |||
| 3 | import { Show, Suspense, createMemo, createSignal } from "solid-js"; | 3 | import { Show, Suspense, createMemo, createSignal } from "solid-js"; |
| 4 | import { createResource } from "@/lib/create-resource"; | 4 | import { createResource } from "@/lib/create-resource"; |
| 5 | import { matchesSearch } from "@/lib/search-text"; | 5 | import { matchesSearch } from "@/lib/search-text"; |
| 6 | -import { getCourses } from "@/api/courses"; | ||
| 7 | import { getUserSearch } from "@/api/users"; | 6 | import { getUserSearch } from "@/api/users"; |
| 8 | -import { formatApiError, type Course, type PersonRef } from "@/api/client"; | 7 | +import { formatApiError, type PersonRef } from "@/api/client"; |
| 9 | import { formatInstanceLabel, loadSchoolSections, classList } from "@/lib/instance-labels"; | 8 | import { formatInstanceLabel, loadSchoolSections, classList } from "@/lib/instance-labels"; |
| 10 | import { RouteGuard } from "@/components/layout/route-guard"; | 9 | import { RouteGuard } from "@/components/layout/route-guard"; |
| 11 | import { CreateUserPanel } from "@/components/users/create-user-panel"; | 10 | import { CreateUserPanel } from "@/components/users/create-user-panel"; |
| @@ -23,9 +22,9 @@ const ROSTER_PAGE_SIZE = 10; | |||
| 23 | type TeacherRow = { | 22 | type TeacherRow = { |
| 24 | person: PersonRef; | 23 | person: PersonRef; |
| 25 | /** Classes this teacher is the homeroom teacher (sınıf öğretmeni) of. */ | 24 | /** Classes this teacher is the homeroom teacher (sınıf öğretmeni) of. */ |
| 26 | - homeroom: string[]; | 25 | + homeroom: string[] | null; |
| 27 | /** The sections they teach, as "<ders> — <şube>". */ | 26 | /** The sections they teach, as "<ders> — <şube>". */ |
| 28 | - sections: string[]; | 27 | + sections: string[] | null; |
| 29 | }; | 28 | }; |
| 30 | 29 | ||
| 31 | export default function TeachersRosterPage() { | 30 | export default function TeachersRosterPage() { |
| @@ -47,37 +46,33 @@ function TeachersRosterContent() { | |||
| 47 | const navigate = useNavigate(); | 46 | const navigate = useNavigate(); |
| 48 | const [creating, setCreating] = createSignal(false); | 47 | const [creating, setCreating] = createSignal(false); |
| 49 | 48 | ||
| 50 | - const [data, { refetch }] = createResource(async () => { | 49 | + const [data, { refetch }] = createResource(() => getUserSearch("", undefined, "teacher")); |
| 51 | - const [teachers, classes] = await Promise.all([ | 50 | + const [homeroomNames] = createResource(() => data.latest?.items.length ? true : null, async () => { |
| 52 | - getUserSearch("", undefined, "teacher"), | 51 | + const classes = await classList(); |
| 53 | - classList().then((items) => ({ items })), | ||
| 54 | - ]); | ||
| 55 | const push = (map: Map<string, string[]>, id: string, value: string) => map.set(id, [...(map.get(id) ?? []), value]); | 52 | const push = (map: Map<string, string[]>, id: string, value: string) => map.set(id, [...(map.get(id) ?? []), value]); |
| 56 | const byName = (a: string, b: string) => a.localeCompare(b, "tr", { numeric: true }); | 53 | const byName = (a: string, b: string) => a.localeCompare(b, "tr", { numeric: true }); |
| 57 | const homeroom = new Map<string, string[]>(); | 54 | const homeroom = new Map<string, string[]>(); |
| 58 | - for (const cls of classes.items) if (cls.teacher) push(homeroom, cls.teacher.id, cls.name); | 55 | + for (const cls of classes) if (cls.teacher) push(homeroom, cls.teacher.id, cls.name); |
| 59 | - return teachers.items.map<TeacherRow>((person) => ({ | 56 | + return new Map([...homeroom].map(([id, names]) => [id, names.sort(byName)])); |
| 60 | - person, | ||
| 61 | - homeroom: (homeroom.get(person.id) ?? []).sort(byName), | ||
| 62 | - sections: [], | ||
| 63 | - })); | ||
| 64 | }); | 57 | }); |
| 65 | - const [sectionNames] = createResource(() => data.latest ? true : null, async () => { | 58 | + const [sectionNames] = createResource(() => data.latest?.items.length ? true : null, async () => { |
| 66 | - const courses = await getCourses().catch(() => ({ items: [] as Course[] })); | ||
| 67 | - const titles = new Map(courses.items.map((course) => [course.id, course.title])); | ||
| 68 | const push = (map: Map<string, string[]>, id: string, value: string) => map.set(id, [...(map.get(id) ?? []), value]); | 59 | const push = (map: Map<string, string[]>, id: string, value: string) => map.set(id, [...(map.get(id) ?? []), value]); |
| 69 | const byName = (a: string, b: string) => a.localeCompare(b, "tr", { numeric: true }); | 60 | const byName = (a: string, b: string) => a.localeCompare(b, "tr", { numeric: true }); |
| 70 | const perClass = await loadSchoolSections(); | 61 | const perClass = await loadSchoolSections(); |
| 71 | const sections = new Map<string, string[]>(); | 62 | const sections = new Map<string, string[]>(); |
| 72 | for (const { klass, sections: instances } of perClass) { | 63 | for (const { klass, sections: instances } of perClass) { |
| 73 | for (const instance of instances) { | 64 | for (const instance of instances) { |
| 74 | - const label = formatInstanceLabel(titles.get(instance.course) ?? null, klass.name); | 65 | + const label = formatInstanceLabel(instance.title?.trim() || null, klass.name); |
| 75 | for (const teacher of instance.teachers) push(sections, teacher.id, label); | 66 | for (const teacher of instance.teachers) push(sections, teacher.id, label); |
| 76 | } | 67 | } |
| 77 | } | 68 | } |
| 78 | return new Map([...sections].map(([id, names]) => [id, [...new Set(names)].sort(byName)])); | 69 | return new Map([...sections].map(([id, names]) => [id, [...new Set(names)].sort(byName)])); |
| 79 | }); | 70 | }); |
| 80 | - const mergedRows = createMemo(() => (data.latest ?? []).map((row) => ({ ...row, sections: sectionNames.latest?.get(row.person.id) ?? [] }))); | 71 | + const mergedRows = createMemo(() => (data.latest?.items ?? []).map<TeacherRow>((person) => ({ |
| 72 | + person, | ||
| 73 | + homeroom: homeroomNames.latest ? homeroomNames.latest.get(person.id) ?? [] : null, | ||
| 74 | + sections: sectionNames.latest ? sectionNames.latest.get(person.id) ?? [] : null, | ||
| 75 | + }))); | ||
| 81 | 76 | ||
| 82 | const open = (row: TeacherRow) => void navigate({ to: "/profile/$userId", params: { userId: row.person.id } }); | 77 | const open = (row: TeacherRow) => void navigate({ to: "/profile/$userId", params: { userId: row.person.id } }); |
| 83 | 78 | ||
| @@ -88,21 +83,25 @@ function TeachersRosterContent() { | |||
| 88 | size: 260, | 83 | size: 260, |
| 89 | // Empty lists read as "" so DataTable draws its one empty-cell dash, | 84 | // Empty lists read as "" so DataTable draws its one empty-cell dash, |
| 90 | // the same one the homeroom column gets. | 85 | // the same one the homeroom column gets. |
| 91 | - accessorFn: (row) => row.sections.join(", "), | 86 | + accessorFn: (row) => row.sections?.join(", ") ?? "…", |
| 92 | header: t("roster.taughtSections"), | 87 | header: t("roster.taughtSections"), |
| 93 | meta: { cellClass: "max-w-0" }, | 88 | meta: { cellClass: "max-w-0" }, |
| 94 | cell: (cell) => { | 89 | cell: (cell) => { |
| 95 | const list = cell.row.original.sections; | 90 | const list = cell.row.original.sections; |
| 96 | - return <span class="block truncate text-sm" title={list.join("\n")}>{list.join(", ")}</span>; | 91 | + return <Show when={list} fallback={<span class="inline-block h-4 w-20 animate-pulse rounded bg-muted" aria-label={t("common.loading")} />}> |
| 92 | + {(names) => <span class="block truncate text-sm" title={names().join("\n")}>{names().join(", ")}</span>} | ||
| 93 | + </Show>; | ||
| 97 | }, | 94 | }, |
| 98 | }, | 95 | }, |
| 99 | { | 96 | { |
| 100 | id: "homeroom", | 97 | id: "homeroom", |
| 101 | size: 130, | 98 | size: 130, |
| 102 | - accessorFn: (row) => row.homeroom.join(", "), | 99 | + accessorFn: (row) => row.homeroom?.join(", ") ?? "…", |
| 103 | header: t("roster.homeroomOf"), | 100 | header: t("roster.homeroomOf"), |
| 104 | meta: { cellClass: "max-w-0" }, | 101 | meta: { cellClass: "max-w-0" }, |
| 105 | - cell: (cell) => <span class="block truncate text-sm" title={cell.row.original.homeroom.join(", ")}>{cell.row.original.homeroom.join(", ")}</span>, | 102 | + cell: (cell) => <Show when={cell.row.original.homeroom} fallback={<span class="inline-block h-4 w-16 animate-pulse rounded bg-muted" aria-label={t("common.loading")} />}> |
| 103 | + {(names) => <span class="block truncate text-sm" title={names().join(", ")}>{names().join(", ")}</span>} | ||
| 104 | + </Show>, | ||
| 106 | }, | 105 | }, |
| 107 | { | 106 | { |
| 108 | id: "actions", | 107 | id: "actions", |