forge
Explore
Log in

Don't you dare go Hollow

✂️ say when a capped list left rows out

Browse files at this commit

15be7687f0fe65523fd0b7ed2202be345c6b3deeBurak BoduroğluParent: e6e9aad
  • fix
    • ✂️ say when a capped list left rows out
Show full message
fix: ✂️ say when a capped list left rows out
- new loadCappedList: first load keeps the 100-row cap from 61d2048 but
  returns the server total, and fetches every row on request
- TruncationNotice shows "first N of total" with a Load all button, above
  the events, exams and admin users tables (users keep their 200 cap)
- tests for the helper, the notice and the events page round trip
- other capped reads (dashboard, calendar, payments, meal detail, terms and
  more) still cap silently; they follow in later layer A work
src/components/ui/truncation-notice.test.tsxadded+27 -0
@@ -0,0 +1,27 @@
1+import { cleanup, fireEvent, render, screen } from "@solidjs/testing-library";
2+import { afterEach, expect, test, vi } from "vitest";
3+import { TruncationNotice } from "@/components/ui/truncation-notice";
4+import { PreferencesProvider } from "@/stores/preferences-context";
5+
6+afterEach(cleanup);
7+
8+test("says how many rows were left out and loads the rest on request", () => {
9+ const onLoadAll = vi.fn();
10+ render(() => (
11+ <PreferencesProvider>
12+ <TruncationNotice shown={100} total={340} onLoadAll={onLoadAll} />
13+ </PreferencesProvider>
14+ ));
15+ expect(screen.getByRole("status").textContent).toContain("340");
16+ fireEvent.click(screen.getByRole("button"));
17+ expect(onLoadAll).toHaveBeenCalledOnce();
18+});
19+
20+test("stays hidden when every row is on screen", () => {
21+ const { container } = render(() => (
22+ <PreferencesProvider>
23+ <TruncationNotice shown={12} total={12} onLoadAll={() => undefined} />
24+ </PreferencesProvider>
25+ ));
26+ expect(container.textContent).toBe("");
27+});
src/components/ui/truncation-notice.tsxadded+26 -0
@@ -0,0 +1,26 @@
1+import { Show } from "solid-js";
2+import { Alert } from "@/components/ui/alert";
3+import { Button } from "@/components/ui/button";
4+import { useT } from "@/stores/preferences-context";
5+
6+/** Says a capped list left rows out, with a way to fetch the rest. */
7+export function TruncationNotice(props: { shown: number; total: number; loading?: boolean; onLoadAll: () => void }) {
8+ const t = useT();
9+ return (
10+ <Show when={props.total > props.shown}>
11+ <Alert role="status" class="flex min-h-0 flex-wrap items-center justify-between gap-3 py-3">
12+ <span class="min-w-0 flex-1">{t("common.truncatedNotice", { shown: props.shown, total: props.total })}</span>
13+ <Button
14+ type="button"
15+ size="sm"
16+ variant="outline"
17+ class="shrink-0"
18+ disabled={props.loading}
19+ onClick={() => props.onLoadAll()}
20+ >
21+ {t("common.loadAll")}
22+ </Button>
23+ </Alert>
24+ </Show>
25+ );
26+}
src/i18n/messages.tsmodified+6 -0
@@ -614,6 +614,8 @@ export type MessageKey =
614614 | "common.created"
615615 | "common.deleted"
616616 | "common.saved"
617+ | "common.loadAll"
618+ | "common.truncatedNotice"
617619 | "common.createItem"
618620 | "common.countItem"
619621 | "pool.title"
@@ -2740,6 +2742,8 @@ const en: Dict = {
27402742 "common.created": "Created.",
27412743 "common.deleted": "Deleted.",
27422744 "common.saved": "Saved successfully.",
2745+ "common.loadAll": "Load all",
2746+ "common.truncatedNotice": "Showing the first {shown} of {total} records.",
27432747 "common.createItem": "Create new {item}",
27442748 "common.countItem": "{count} {item}",
27452749 "pool.title": "Question pool",
@@ -4868,6 +4872,8 @@ const tr: Dict = {
48684872 "common.created": "Oluşturuldu.",
48694873 "common.deleted": "Silindi.",
48704874 "common.saved": "Başarıyla kaydedildi.",
4875+ "common.loadAll": "Tümünü yükle",
4876+ "common.truncatedNotice": "{total} kayıttan ilk {shown} tanesi gösteriliyor.",
48714877 "common.createItem": "Yeni {item} oluştur",
48724878 "common.countItem": "{count} {item}",
48734879 "pool.title": "Soru havuzu",
src/lib/capped-list.test.tsadded+25 -0
@@ -0,0 +1,25 @@
1+import type { Page, PageParams } from "@/api/client";
2+import { isTruncated, loadCappedList } from "./capped-list";
3+
4+const page = (items: number[], total: number): Page<number> => ({ items, total, limit: null, offset: 0 });
5+
6+it("asks for the cap and reports the server total", async () => {
7+ const fetch = vi.fn(async (_params?: PageParams) => page([1, 2], 5));
8+ const list = await loadCappedList(fetch, 2, false);
9+ expect(fetch).toHaveBeenCalledWith({ limit: 2 });
10+ expect(list).toEqual({ items: [1, 2], total: 5 });
11+ expect(isTruncated(list)).toBe(true);
12+});
13+
14+it("fetches every row without a limit when asked for all", async () => {
15+ const fetch = vi.fn(async (_params?: PageParams) => page([1, 2, 3, 4, 5], 5));
16+ const list = await loadCappedList(fetch, 2, true);
17+ expect(fetch).toHaveBeenCalledWith(undefined);
18+ expect(isTruncated(list)).toBe(false);
19+});
20+
21+it("never reports a total below the rows it holds", async () => {
22+ const list = await loadCappedList(async () => page([1, 2, 3], 1), 10, false);
23+ expect(list.total).toBe(3);
24+ expect(isTruncated(undefined)).toBe(false);
25+});
src/lib/capped-list.tsadded+30 -0
@@ -0,0 +1,30 @@
1+import type { Page, PageParams } from "@/api/client";
2+
3+/** Default first-load size for list pages that filter and page in memory. */
4+export const LIST_CAP = 100;
5+
6+export type CappedList<T> = {
7+ items: T[];
8+ /** Row count on the server, before the cap. */
9+ total: number;
10+};
11+
12+/**
13+ * Fetch the first `cap` rows of a list, or every row once the user asks for
14+ * it. The cap keeps big lists cheap; `total` lets the page say when rows were
15+ * left out instead of hiding them.
16+ */
17+export async function loadCappedList<T>(
18+ fetch: (params?: PageParams) => Promise<Page<T>>,
19+ cap: number,
20+ all: boolean,
21+): Promise<CappedList<T>> {
22+ const page = await fetch(all ? undefined : { limit: cap });
23+ const items = Array.isArray(page.items) ? page.items : [];
24+ const total = typeof page.total === "number" ? Math.max(page.total, items.length) : items.length;
25+ return { items, total };
26+}
27+
28+export function isTruncated(list: CappedList<unknown> | undefined): boolean {
29+ return !!list && list.total > list.items.length;
30+}
src/pages/admin-users-page.tsxmodified+17 -2
@@ -15,6 +15,8 @@ import { ComingSoonBadge } from "@/components/ui/coming-soon";
1515 import { DataTableSkeleton } from "@/components/ui/data-table";
1616 import { IconPlus } from "@/components/ui/icons";
1717 import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs";
18+import { TruncationNotice } from "@/components/ui/truncation-notice";
19+import { loadCappedList } from "@/lib/capped-list";
1820 import { createFlash } from "@/lib/flash";
1921 import { useAuth } from "@/stores/auth-context";
2022 import { useT } from "@/stores/preferences-context";
@@ -29,6 +31,9 @@ export default function AdminUsersPage() {
2931 );
3032 }
3133
34+/** Staff rosters run longer than other lists, so the first load holds more. */
35+const USER_LIST_CAP = 200;
36+
3237 function AdminUsersContent() {
3338 const auth = useAuth();
3439 const navigate = useNavigate();
@@ -38,8 +43,12 @@ function AdminUsersContent() {
3843 const [roleTab, setRoleTab] = createSignal<RoleTab>("all");
3944 const [creating, setCreating] = createSignal(false);
4045
41- const [list, { refetch }] = createResource(async () => (await getUsers({ limit: 200 })).items);
42- const allUsers = () => list() ?? [];
46+ const [loadAll, setLoadAll] = createSignal(false);
47+ const [list, { refetch }] = createResource(
48+ () => (loadAll() ? "all" : "capped"),
49+ (scope) => loadCappedList(getUsers, USER_LIST_CAP, scope === "all"),
50+ );
51+ const allUsers = () => list()?.items ?? [];
4352 const visibleUsers = createMemo(() => {
4453 const tab = roleTab();
4554 if (tab === "all") return allUsers();
@@ -83,6 +92,12 @@ function AdminUsersContent() {
8392
8493 <section class="data-shell space-y-4 p-4">
8594 <Suspense fallback={<DataTableSkeleton columns={6} rows={8} />}>
95+ <TruncationNotice
96+ shown={list()?.items.length ?? 0}
97+ total={list()?.total ?? 0}
98+ loading={list.loading}
99+ onLoadAll={() => setLoadAll(true)}
100+ />
86101 <Show when={list()}>
87102 <UserTable
88103 title={t("admin.title")}
src/pages/events-page.test.tsxadded+61 -0
@@ -0,0 +1,61 @@
1+import { cleanup, fireEvent, render, screen, waitFor } from "@solidjs/testing-library";
2+import type { JSX } from "solid-js";
3+import EventsPage from "@/pages/events-page";
4+import { PreferencesProvider } from "@/stores/preferences-context";
5+
6+const { getEvents } = vi.hoisted(() => ({ getEvents: vi.fn() }));
7+
8+vi.mock("@tanstack/solid-router", () => ({
9+ Link: (props: { to: string; children: JSX.Element; class?: string }) => <a href={props.to} class={props.class}>{props.children}</a>,
10+ Navigate: () => null,
11+ useNavigate: () => vi.fn(),
12+ useLocation: () => () => ({ pathname: "/events", searchStr: "" }),
13+}));
14+vi.mock("@/stores/auth-context", () => ({
15+ useAuth: () => ({
16+ user: () => ({ id: "student-1", username: "student", role: "student" }),
17+ loading: () => false,
18+ error: () => undefined,
19+ }),
20+}));
21+vi.mock("@/api/events", () => ({ getEvents, postEvent: vi.fn() }));
22+vi.mock("@/api/courses", () => ({ getCourses: vi.fn() }));
23+vi.mock("@/api/time", () => ({ getTime: vi.fn(async () => ({ now: Date.now() })) }));
24+
25+const event = (n: number) => ({
26+ id: `event-${n}`,
27+ creator: "teacher-1",
28+ title: `Event ${n}`,
29+ description: "",
30+ audience: { kind: "school" },
31+ starts_at: null,
32+ ends_at: null,
33+});
34+
35+afterEach(() => {
36+ cleanup();
37+ vi.clearAllMocks();
38+});
39+
40+test("a capped event list says rows were left out and loads them on request", async () => {
41+ getEvents.mockImplementation(async (params?: { limit?: number }) => {
42+ const all = Array.from({ length: 3 }, (_, i) => event(i + 1));
43+ const items = params?.limit ? all.slice(0, 2) : all;
44+ return { items, total: all.length, limit: params?.limit ?? null, offset: 0 };
45+ });
46+
47+ render(() => (
48+ <PreferencesProvider>
49+ <EventsPage />
50+ </PreferencesProvider>
51+ ));
52+
53+ const notice = await screen.findByRole("status");
54+ expect(getEvents).toHaveBeenCalledWith({ limit: 100 });
55+ expect(notice.textContent).toContain("3");
56+
57+ fireEvent.click(await screen.findByRole("button", { name: /Tümünü yükle|Load all/ }));
58+
59+ await waitFor(() => expect(getEvents).toHaveBeenLastCalledWith(undefined));
60+ await waitFor(() => expect(screen.queryByRole("status")).toBeNull());
61+});
src/pages/events-page.tsxmodified+14 -2
@@ -16,8 +16,10 @@ import { IconEye, IconPlus } from "@/components/ui/icons";
1616 import { DropdownSelect } from "@/components/ui/select";
1717 import { SidePanel } from "@/components/ui/side-panel";
1818 import { TableRowActions } from "@/components/ui/table-row-actions";
19+import { TruncationNotice } from "@/components/ui/truncation-notice";
1920 import { cn } from "@/lib/cn";
2021 import { createNow } from "@/lib/create-now";
22+import { LIST_CAP, loadCappedList } from "@/lib/capped-list";
2123 import { createFlash } from "@/lib/flash";
2224 import { formatDateTime } from "@/lib/format";
2325 import { hasMinRole } from "@/lib/roles";
@@ -64,8 +66,12 @@ function EventsContent() {
6466 });
6567 };
6668
67- const [list, { refetch }] = createResource(async () => (await getEvents({ limit: 100 })).items);
68- const rows = () => filterEvents(list() ?? []);
69+ const [loadAll, setLoadAll] = createSignal(false);
70+ const [list, { refetch }] = createResource(
71+ () => (loadAll() ? "all" : "capped"),
72+ (scope) => loadCappedList(getEvents, LIST_CAP, scope === "all"),
73+ );
74+ const rows = () => filterEvents(list()?.items ?? []);
6975 const eventStatus = (event: Event) => {
7076 const nowMs = now();
7177 if (event.ends_at != null && event.ends_at < nowMs) return "past";
@@ -196,6 +202,12 @@ function EventsContent() {
196202 <Show when={list.error}>
197203 <Alert variant="destructive">{formatApiError(list.error)}</Alert>
198204 </Show>
205+ <TruncationNotice
206+ shown={list()?.items.length ?? 0}
207+ total={list()?.total ?? 0}
208+ loading={list.loading}
209+ onLoadAll={() => setLoadAll(true)}
210+ />
199211 <DataTable
200212 title={t("events.title")}
201213 description={t("events.subtitle")}
src/pages/exams-page.tsxmodified+14 -4
@@ -21,11 +21,13 @@ import { DropdownSelect } from "@/components/ui/select";
2121 import { SearchableSelect } from "@/components/ui/searchable-select";
2222 import { SidePanel } from "@/components/ui/side-panel";
2323 import { TableRowActions } from "@/components/ui/table-row-actions";
24+import { TruncationNotice } from "@/components/ui/truncation-notice";
2425 import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
2526 import { createNow } from "@/lib/create-now";
2627 import { EXAM_KINDS } from "@/api/client";
2728 import { examKindLabel } from "@/lib/exam-labels";
2829 import { examDisplayStatus, examStatusMessageKey, examStatusTone, type ExamDisplayStatus } from "@/lib/exam-status";
30+import { LIST_CAP, loadCappedList } from "@/lib/capped-list";
2931 import { createFlash } from "@/lib/flash";
3032 import { formatDateTime } from "@/lib/format";
3133 import { hasMinRole } from "@/lib/roles";
@@ -128,13 +130,15 @@ function ExamsContent() {
128130 statusLabel(exam.displayStatus),
129131 );
130132
133+ const [loadAll, setLoadAll] = createSignal(false);
131134 const [list, { refetch: refetchExams }] = createResource(
132135 () => {
133136 if (sections() === undefined) return null;
134- return visibleCourses().map((row) => row.id).join(",");
137+ return `${loadAll() ? "all" : "capped"}|${visibleCourses().map((row) => row.id).join(",")}`;
135138 },
136139 async () => {
137- const items = (await getExams({ limit: 100 })).items;
140+ const page = await loadCappedList(getExams, LIST_CAP, loadAll());
141+ const items = page.items;
138142 const known = new Map(visibleCourses().map((row) => [row.id, row.label]));
139143 const missing = [...new Set(items.map((exam) => exam.class_course))].filter((instanceId) => !known.has(instanceId));
140144 if (missing.length > 0) {
@@ -150,7 +154,7 @@ function ExamsContent() {
150154 );
151155 }
152156 setCourseMap(Object.fromEntries(known));
153- return items;
157+ return page;
154158 },
155159 );
156160
@@ -168,7 +172,7 @@ function ExamsContent() {
168172 const statusLabel = (status: ExamDisplayStatus) => {
169173 return t(examStatusMessageKey(status));
170174 };
171- const rows = (): ExamRow[] => filterExams(list() ?? []).map((exam) => ({ ...exam, displayStatus: examStatus(exam) }));
175+ const rows = (): ExamRow[] => filterExams(list()?.items ?? []).map((exam) => ({ ...exam, displayStatus: examStatus(exam) }));
172176 const columns = createMemo<ColumnDef<ExamRow>[]>(() => [
173177 {
174178 accessorKey: "title",
@@ -309,6 +313,12 @@ function ExamsContent() {
309313 <Show when={list.error}>
310314 <Alert variant="destructive">{formatApiError(list.error)}</Alert>
311315 </Show>
316+ <TruncationNotice
317+ shown={list()?.items.length ?? 0}
318+ total={list()?.total ?? 0}
319+ loading={list.loading}
320+ onLoadAll={() => setLoadAll(true)}
321+ />
312322 <DataTable
313323 title={t("exams.title")}
314324 description={t("exams.subtitle")}