forge
Explore
Log in

Don't you dare go Hollow

hezarfen_frontend

Clone
★ 0

0 watching0 forksTypeScript5.5 MiBdcf123aBurak Boduroğlu2 months ago674 commits

marks-report-view.tsx258 lines, 11.3 KiBHistoryRawDownload
1import { For, Show, createMemo, createSignal } from "solid-js";
2import { createResource } from "@/lib/create-resource";
3import type { ColumnDef } from "@tanstack/solid-table";
4import { Link } from "@tanstack/solid-router";
5import { getClassesByUserId, getMyClasses } from "@/api/classes";
6import { getSettings } from "@/api/settings";
7import type { MarksReport } from "@/api/client";
8import { Badge } from "@/components/ui/badge";
9import { buttonVariants } from "@/components/ui/button";
10import { IconExternalLink } from "@/components/ui/icons";
11import { DataTable, DataTableEmpty } from "@/components/ui/data-table";
12import { ExamLink } from "@/components/exams/exam-link";
13import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs";
14import { cn } from "@/lib/cn";
15import { examKindLabel } from "@/lib/exam-labels";
16import { examWeight } from "@/lib/exam-weight";
17import { useAuth } from "@/stores/auth-context";
18import { useT } from "@/stores/preferences-context";
19
20const round = (n: number) => (Math.round(n * 100) / 100).toString();
21type MarkRow = MarksReport["courses"][number]["results"][number];
22
23function markWithGrade(mark: number | null, grade?: string | null) {
24 if (mark == null) return grade ?? "—";
25 return grade ? `${round(mark)} / ${grade}` : round(mark);
26}
27
28function scoreWidth(mark: number | null): string {
29 return `${Math.max(0, Math.min(100, Math.round(mark ?? 0)))}%`;
30}
31
32/** How many sections we bother reading before giving up on naming one. */
33const MAX_SECTIONS = 3;
34
35export function MarksReportView(props: { report: MarksReport; compact?: boolean }) {
36 const t = useT();
37 const auth = useAuth();
38 // The report names each block only by its instance id, so the section's own
39 // name has to be read separately: `/classes/me` for the student reading their
40 // own karne (the one class route a student may call), `/classes/user/{id}`
41 // for a parent or teacher reading someone else's. A refusal is not an error
42 // to show — the button simply keeps its generic label.
43 const [sections] = createResource(
44 () => props.report.user,
45 async (userId) => {
46 try {
47 const page = userId === auth.user()?.id
48 ? await getMyClasses({ limit: MAX_SECTIONS })
49 : await getClassesByUserId(userId, { limit: MAX_SECTIONS });
50 return page.items;
51 } catch {
52 return [];
53 }
54 },
55 { initialValue: [] },
56 );
57 // Naming the section is only honest when the student sits in exactly one:
58 // with two, nothing in the payload says which one teaches this course.
59 const sectionName = () => (sections().length === 1 ? sections()[0]!.name : null);
60 const openLabel = () => sectionName() ?? t("instances.open");
61 const openAria = () => (sectionName() ? `${sectionName()} — ${t("instances.open")}` : t("instances.open"));
62 type CourseBlock = MarksReport["courses"][number];
63 const courseColumns = createMemo<ColumnDef<CourseBlock>[]>(() => [
64 {
65 id: "course",
66 header: t("nav.courses"),
67 meta: { headerClass: "w-[42%]" },
68 cell: (cell) => (
69 <Link to="/courses/$id" params={{ id: cell.row.original.course.id }} class="block truncate font-medium hover:text-primary-text hover:underline">
70 {cell.row.original.course.title}
71 </Link>
72 ),
73 },
74 {
75 id: "instance",
76 header: t("instances.title"),
77 meta: { headerClass: "w-[28%]", cellClass: "text-muted-foreground" },
78 cell: (cell) => (
79 <Link
80 to="/instances/$id"
81 params={{ id: cell.row.original.instance }}
82 class={cn(buttonVariants({ variant: "outline", size: "sm" }), "h-8 max-w-full rounded-lg")}
83 aria-label={openAria()}
84 >
85 <IconExternalLink class="h-3.5 w-3.5 shrink-0" />
86 <span class="truncate">{openLabel()}</span>
87 </Link>
88 ),
89 },
90 {
91 id: "average",
92 header: t("marks.courseAvg"),
93 meta: { headerClass: "w-[30%]" },
94 cell: (cell) => (
95 <div class="flex items-center gap-2">
96 <div class="h-1.5 w-12 min-w-8 shrink overflow-hidden rounded-full bg-muted">
97 <div class="h-full rounded-full bg-primary" style={{ width: scoreWidth(cell.row.original.average) }} />
98 </div>
99 <span class="shrink-0 text-xs font-semibold tabular-nums">{markWithGrade(cell.row.original.average, cell.row.original.average_grade)}</span>
100 </div>
101 ),
102 },
103 ]);
104 const [settings] = createResource(() => getSettings());
105 const compact = () => props.compact === true;
106 const resultCount = createMemo(() => props.report.courses.reduce((total, course) => total + course.results.length, 0));
107 const [tab, setTab] = createSignal<"general" | "byCourse">("general");
108 const [activeInstanceId, setActiveInstanceId] = createSignal<string | null>(null);
109 const activeCourse = createMemo(() => {
110 const id = activeInstanceId();
111 const courses = props.report.courses;
112 return (id ? courses.find((c) => c.instance === id) : undefined) ?? courses[0];
113 });
114 const columns = createMemo<ColumnDef<MarkRow>[]>(() => [
115 {
116 accessorKey: "title",
117 header: t("marks.exam"),
118 meta: { stickyLeft: true },
119 cell: (cell) => (
120 <span class="min-w-0">
121 <ExamLink examId={cell.row.original.exam} class="block truncate font-medium hover:underline">
122 {cell.row.original.title}
123 </ExamLink>
124 <Show when={compact()}>
125 <p class="mt-0.5 truncate text-[11px] text-muted-foreground sm:hidden">
126 {examKindLabel(cell.row.original.kind, t)}
127 </p>
128 </Show>
129 </span>
130 ),
131 },
132 {
133 accessorKey: "kind",
134 header: t("exams.kind"),
135 meta: { headerClass: compact() ? "hidden sm:table-cell" : undefined, cellClass: compact() ? "hidden sm:table-cell" : undefined },
136 cell: (cell) => <Badge variant="outline" class="rounded-sm capitalize">{examKindLabel(cell.row.original.kind, t)}</Badge>,
137 },
138 {
139 id: "weight",
140 header: t("marks.weight"),
141 meta: { align: "right", divider: "left", cellClass: "" },
142 cell: (cell) => examWeight(cell.row.original, settings()?.exam_kinds) ?? "—",
143 },
144 {
145 accessorKey: "mark",
146 header: t("marks.mark"),
147 meta: { align: "right", cellClass: "font-semibold" },
148 cell: (cell) => markWithGrade(cell.row.original.mark, cell.row.original.grade),
149 },
150 ]);
151
152 return (
153 <div class="min-w-0 space-y-4">
154 <section class="grid gap-4 rounded-lg border border-border bg-card p-4 shadow-xs sm:grid-cols-[minmax(0,1fr)_auto] sm:items-center">
155 <div>
156 <p class="text-xs font-medium text-muted-foreground">{t("marks.overall")}</p>
157 <p class={cn("mt-1 font-semibold tabular-nums", compact() ? "text-3xl" : "text-4xl")}>
158 {markWithGrade(props.report.overall_average, props.report.overall_grade)}
159 </p>
160 <div class="mt-3 h-2 max-w-xl overflow-hidden rounded-full bg-muted">
161 <div class="h-full rounded-full bg-primary" style={{ width: scoreWidth(props.report.overall_average) }} />
162 </div>
163 </div>
164 <dl class="grid grid-cols-2 gap-2 sm:min-w-56">
165 <div class="rounded-xl bg-muted/45 p-3">
166 <dt class="text-[11px] text-muted-foreground">{t("nav.courses")}</dt>
167 <dd class="mt-1 text-2xl font-semibold tabular-nums">{props.report.courses.length}</dd>
168 </div>
169 <div class="rounded-xl bg-muted/45 p-3">
170 <dt class="text-[11px] text-muted-foreground">{t("exams.results")}</dt>
171 <dd class="mt-1 text-2xl font-semibold tabular-nums">{resultCount()}</dd>
172 </div>
173 </dl>
174 </section>
175
176 <Show when={props.report.courses.length > 0} fallback={<DataTableEmpty class="rounded-lg border border-border bg-card py-10">{t("marks.empty")}</DataTableEmpty>}>
177 <Tabs value={tab()} onChange={(value) => setTab(value === "byCourse" ? "byCourse" : "general")}>
178 <TabsList class="w-full sm:w-fit">
179 <TabsTrigger value="general" class="min-w-0">{t("marks.tabGeneral")}</TabsTrigger>
180 <TabsTrigger value="byCourse" class="min-w-0">{t("marks.tabByCourse")}</TabsTrigger>
181 </TabsList>
182 </Tabs>
183
184 <Show when={tab() === "general"}>
185 <DataTable
186 columns={courseColumns()}
187 data={props.report.courses}
188 enablePagination={false}
189 enableColumnVisibility={false}
190 enableSorting={false}
191 tableClass="min-w-[28rem]"
192 />
193 </Show>
194
195 <Show when={tab() === "byCourse"}>
196 <div class="space-y-3">
197 <div class="flex flex-wrap gap-1.5">
198 <For each={props.report.courses}>
199 {(block) => (
200 <button
201 type="button"
202 class={cn(
203 "rounded-lg border px-3 py-1.5 text-xs font-medium transition-colors",
204 activeCourse()?.instance === block.instance
205 ? "border-border bg-surface-base text-foreground shadow-xs"
206 : "border-transparent text-muted-foreground hover:bg-muted/60",
207 )}
208 onClick={() => setActiveInstanceId(block.instance)}
209 >
210 {block.course.title}
211 </button>
212 )}
213 </For>
214 </div>
215
216 <Show when={activeCourse()} keyed>
217 {(block) => (
218 <div class="rounded-lg border border-border bg-card p-4 shadow-xs">
219 <div class="flex flex-wrap items-center justify-between gap-3">
220 <div class="min-w-0">
221 <Link to="/courses/$id" params={{ id: block.course.id }} class="inline-flex truncate text-sm font-semibold text-primary-text hover:underline">
222 {block.course.title}
223 </Link>
224 <Link
225 to="/instances/$id"
226 params={{ id: block.instance }}
227 class={cn(buttonVariants({ variant: "outline", size: "sm" }), "mt-1.5 h-8 max-w-full rounded-lg")}
228 aria-label={openAria()}
229 >
230 <IconExternalLink class="h-3.5 w-3.5 shrink-0" />
231 <span class="truncate">{openLabel()}</span>
232 </Link>
233 </div>
234 <div class="text-right">
235 <p class="text-[11px] font-medium uppercase tracking-wider text-muted-foreground">{t("marks.courseAvg")}</p>
236 <p class="mt-0.5 text-xl font-semibold tabular-nums">{markWithGrade(block.average, block.average_grade)}</p>
237 </div>
238 </div>
239 <div class="mt-3">
240 <Show when={block.results.length > 0} fallback={<DataTableEmpty class="py-6">{t("exams.noResults")}</DataTableEmpty>}>
241 <DataTable
242 class="min-w-0"
243 columns={columns()}
244 data={block.results}
245 tableClass={cn("w-full", compact() ? "text-xs" : "table-fixed sm:min-w-xl")}
246 enableColumnVisibility={false}
247 />
248 </Show>
249 </div>
250 </div>
251 )}
252 </Show>
253 </div>
254 </Show>
255 </Show>
256 </div>
257 );
258}