forge
Explore
Log in

Don't you dare go Hollow

hezarfen_frontend

Clone
★ 0

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

answer-sheet-view.tsx287 lines, 14.4 KiBHistoryRawDownload
1import { For, Show, Suspense, createMemo, createSignal, useTransition } from "solid-js";
2import { createResource } from "@/lib/create-resource";
3import { ApiError } from "@/api/client";
4import { getExamQuestions, getExamReviewQuestions } from "@/api/exams";
5import { getStudentAnswers, getStudentAnswerImage } from "@/api/exams";
6import { getStudentAttempts, getStudentAttemptAnswers, getStudentAttemptAnswerImage } from "@/api/exams";
7import { getExamReviewAttempts, getExamReviewAttemptAnswers, getExamReviewAttemptAnswerImage } from "@/api/exams";
8import type { StudentAnswerSheet } from "@/api/client";
9import { Badge } from "@/components/ui/badge";
10import { Button } from "@/components/ui/button";
11import { IconCheck, IconDownload, IconX } from "@/components/ui/icons";
12import { PageSpinner } from "@/components/ui/page-spinner";
13import { ReplayableImage } from "@/components/ui/replayable-image";
14import { DropdownSelect } from "@/components/ui/select";
15import { cn } from "@/lib/cn";
16import { joinAnswerSheet } from "@/lib/answer-sheet";
17import { personLabelWithId } from "@/lib/person";
18import { useT } from "@/stores/preferences-context";
19
20export function AnswerSheetView(props: { examId: string; userId: string; mode?: "grader" | "self" }) {
21 const t = useT();
22 // "grader" hits the teacher, userId-scoped routes; "self" hits the self-scoped
23 // /review routes (no userId in path). Everything below is identical either way.
24 const mode = () => props.mode ?? "grader";
25
26 // Self-review reads 409 while the caller's latest sitting is still in
27 // progress — a retake must submit before it can read the answer key. We
28 // degrade to a friendly banner instead of erroring the panel.
29 const [reviewInProgress, setReviewInProgress] = createSignal(false);
30
31 // Which sitting the grader is viewing. null = the latest (grade-of-record), the default.
32 const [selectedSeq, setSelectedSeq] = createSignal<number | null>(null);
33 // Switch sittings inside a transition so the current sheet stays on screen
34 // while the next one loads — otherwise the `data` resource re-suspends and
35 // the whole panel blanks to the PageSpinner on every pick.
36 const [switching, startSwitch] = useTransition();
37
38 // Attempt list + full mark history (oldest-first, index i = seq i+1). Both grader-only,
39 // both tolerate "student never sat" by degrading to empty.
40 const [attempts] = createResource(
41 () => [props.examId, props.userId] as const,
42 async ([examId, userId]) => {
43 if (mode() === "self") setReviewInProgress(false);
44 try {
45 return mode() === "self" ? await getExamReviewAttempts(examId) : await getStudentAttempts(examId, userId);
46 } catch (err) {
47 if (err instanceof ApiError && err.status === 404) return [] as number[];
48 if (mode() === "self" && err instanceof ApiError && err.status === 409) {
49 setReviewInProgress(true);
50 return [] as number[];
51 }
52 throw err;
53 }
54 },
55 );
56 const latestSeq = () => {
57 const a = attempts();
58 return a && a.length ? a[a.length - 1] : null;
59 };
60 // Effective seq being shown, and whether it's the current (re-gradable) sitting.
61 const activeSeq = () => selectedSeq() ?? latestSeq();
62 const isLatest = () => {
63 const s = activeSeq();
64 return s == null || s === latestSeq();
65 };
66 // Dropdown options, newest sitting first (a student may have many). Just the
67 // sitting label; the latest is tagged as the current one. Per-sitting stats
68 // live in the sheet header for the selected sitting, not in the dropdown.
69 const attemptOptions = () =>
70 [...(attempts() ?? [])].reverse().map((seq) => ({
71 value: seq,
72 label: `${t("exams.attemptN", { n: seq })}${seq === latestSeq() ? ` (${t("exams.currentAttempt")})` : ""}`,
73 }));
74
75 const answerImageUrl = (questionId: string) => {
76 const seq = activeSeq();
77 if (mode() === "self")
78 return `/api/exams/${props.examId}/review/attempts/${seq}/answers/${questionId}/image`;
79 return isLatest() || seq == null
80 ? `/api/exams/${props.examId}/attempts/${props.userId}/answers/${questionId}/image`
81 : `/api/exams/${props.examId}/students/${props.userId}/attempts/${seq}/answers/${questionId}/image`;
82 };
83 const fetchAnswerImage = (questionId: string) => {
84 const seq = activeSeq();
85 if (mode() === "self") return getExamReviewAttemptAnswerImage(props.examId, seq ?? 1, questionId);
86 return isLatest() || seq == null
87 ? getStudentAnswerImage(props.examId, props.userId, questionId)
88 : getStudentAttemptAnswerImage(props.examId, props.userId, seq, questionId);
89 };
90
91 const [data] = createResource(
92 // Re-fetch when the grader switches attempt. Latest uses the current-attempt route
93 // (unchanged from before); an older seq uses the per-seq history route.
94 () => [props.examId, props.userId, activeSeq(), isLatest()] as const,
95 async ([examId, userId, seq, latest]) => {
96 const questions = mode() === "self" ? await getExamReviewQuestions(examId) : await getExamQuestions(examId);
97 let sheet: StudentAnswerSheet;
98 try {
99 if (mode() === "self") {
100 if (seq == null) throw new ApiError(404, "no attempts");
101 sheet = await getExamReviewAttemptAnswers(examId, seq);
102 } else {
103 sheet = latest || seq == null
104 ? await getStudentAnswers(examId, userId)
105 : await getStudentAttemptAnswers(examId, userId, seq);
106 }
107 } catch (err) {
108 if (err instanceof ApiError && (err.status === 404 || (mode() === "self" && err.status === 409))) {
109 if (mode() === "self" && err instanceof ApiError && err.status === 409) setReviewInProgress(true);
110 sheet = {
111 exam: examId,
112 user: { id: userId, username: userId, display_name: null },
113 answers: [],
114 auto_score: { earned: 0, possible: 0 },
115 };
116 } else {
117 throw err;
118 }
119 }
120 return { sheet, rows: joinAnswerSheet(questions.items, sheet.answers) };
121 },
122 );
123
124 // Per-sitting answer breakdown for the viewed attempt's header. `is_correct`
125 // is only set for auto-gradable (choice) questions: right = got it, wrong =
126 // missed it, empty = no answer given; answered text questions fall in none
127 // (a human grades those). `pending` surfaces those so the counts stay honest.
128 const sheetStats = createMemo(() => {
129 const rows = data()?.rows ?? [];
130 const answered = (a: (typeof rows)[number]["answer"]) =>
131 !!a && (a.selected != null || !!a.text || !!a.answer_image);
132 let right = 0;
133 let wrong = 0;
134 let empty = 0;
135 let pending = 0;
136 for (const r of rows) {
137 if (!answered(r.answer)) empty++;
138 else if (r.answer?.is_correct === true) right++;
139 else if (r.answer?.is_correct === false) wrong++;
140 else pending++;
141 }
142 return { right, wrong, empty, pending, total: rows.length };
143 });
144
145 return (
146 // The picker stays OUTSIDE the Suspense: switching attempts re-fetches
147 // `data`, and if the dropdown lived inside the suspending subtree it would
148 // unmount and its portalled menu would flash unpositioned (top-left) on
149 // every select. Only the answer sheet suspends.
150 <div class="space-y-4">
151 <Show when={reviewInProgress()}>
152 <p class="rounded-md border border-dashed bg-muted/20 px-3 py-2 text-sm text-muted-foreground">{t("exams.reviewInProgress")}</p>
153 </Show>
154 <Show when={(attempts() ?? []).length > 1}>
155 <div class="flex flex-col gap-1.5">
156 <span class="text-xs font-medium text-muted-foreground">{t("exams.previousAttempts")}</span>
157 <DropdownSelect
158 options={attemptOptions()}
159 value={activeSeq() ?? 0}
160 onChange={(v) => startSwitch(() => setSelectedSeq(v))}
161 triggerClass="w-full sm:w-auto"
162 />
163 </div>
164 </Show>
165 <Suspense fallback={<PageSpinner />}>
166 <Show when={!reviewInProgress() && data()}>
167 {(d) => (
168 <div class={cn("space-y-4 transition-opacity", switching() && "opacity-60")}>
169 <Show when={!isLatest()}>
170 <p class="rounded-md border border-dashed bg-muted/20 px-3 py-2 text-xs text-muted-foreground">{t("exams.pastAttemptReadOnly")}</p>
171 </Show>
172 <div class="flex flex-wrap items-center justify-between gap-2 rounded-md border bg-muted/30 px-4 py-3">
173 <p class="text-sm font-medium">{personLabelWithId(d().sheet.user)}</p>
174 <Show when={d().sheet.answers.length > 0} fallback={<Badge variant="outline">{t("exams.notStarted")}</Badge>}>
175 <div class="flex flex-wrap items-center gap-1.5">
176 <Badge variant="outline" class="border-success/50 bg-success/10 text-success-text">
177 {t("exams.answersRight")}: {sheetStats().right}
178 </Badge>
179 <Badge variant="outline" class="border-destructive/50 bg-destructive/10 text-destructive-text">
180 {t("exams.answersWrong")}: {sheetStats().wrong}
181 </Badge>
182 <Badge variant="outline" class="text-muted-foreground">
183 {t("exams.answersEmpty")}: {sheetStats().empty}
184 </Badge>
185 <Show when={sheetStats().pending > 0}>
186 <Badge variant="outline" class="text-muted-foreground">
187 {t("exams.answersPending")}: {sheetStats().pending}
188 </Badge>
189 </Show>
190 <Badge variant="secondary">
191 {t("exams.autoScore")}: {d().sheet.auto_score.earned}/{d().sheet.auto_score.possible}
192 </Badge>
193 </div>
194 </Show>
195 </div>
196
197 <For each={d().rows}>
198 {(row, idx) => (
199 <div class="rounded-md border p-4">
200 <div class="mb-2 flex flex-wrap items-center gap-2">
201 <span class="text-xs font-semibold text-muted-foreground">#{idx() + 1}</span>
202 <Badge variant="outline">{row.question.points} {t("questions.points")}</Badge>
203 <Show when={row.answer?.is_correct != null}>
204 <Badge variant="outline" class={cn(
205 "size-[22px] p-0 flex items-center justify-center",
206 row.answer?.is_correct ? "border-success/50 bg-success/10 text-success-text" : "border-destructive/50 bg-destructive/10 text-destructive-text",
207 )}>
208 <Show when={row.answer?.is_correct} fallback={<IconX class="h-3 w-3" />}>
209 <IconCheck class="h-3 w-3" />
210 </Show>
211 </Badge>
212 </Show>
213 <Show when={row.answer?.is_correct == null && row.question.kind === "text"}>
214 <Badge variant="outline" class="text-[11px]">{t("questions.kind.text")}</Badge>
215 </Show>
216 <Show when={row.answer?.is_correct == null && row.question.kind !== "text"}>
217 <span class="text-xs text-muted-foreground">—</span>
218 </Show>
219 </div>
220 <p class="mb-3 whitespace-pre-wrap text-sm font-medium">{row.question.text}</p>
221
222 <Show
223 when={row.question.kind === "choice"}
224 fallback={
225 <div class="rounded-sm bg-muted/40 p-3">
226 <p class="text-xs text-muted-foreground">{t("exams.textAnswer")}</p>
227 <p class="mt-1 whitespace-pre-wrap text-sm">{row.answer?.text || "—"}</p>
228 <Show when={row.answer?.answer_image}>
229 <div class="mt-3 space-y-2">
230 <ReplayableImage
231 fetchBlob={() => fetchAnswerImage(row.question.id)}
232 src={answerImageUrl(row.question.id)}
233 alt={t("exams.drawAnswer")}
234 imgClass="h-64 w-full max-w-2xl rounded-md border bg-background object-contain"
235 />
236 <a href={answerImageUrl(row.question.id)} download={`answer-${idx() + 1}.png`}>
237 <Button type="button" size="sm" variant="outline" class="rounded-lg">
238 <IconDownload class="h-4 w-4" />
239 {t("notes.downloadFile")}
240 </Button>
241 </a>
242 </div>
243 </Show>
244 </div>
245 }
246 >
247 <div class="space-y-1.5">
248 <For each={row.question.choices}>
249 {(choice, ci) => (
250 <div
251 class={`flex items-center gap-2 rounded-sm border px-3 py-2 text-sm ${
252 choice.id === row.question.correct && choice.id === row.answer?.selected
253 ? "border-success bg-success/10"
254 : choice.id === row.question.correct
255 ? "border-success/50 bg-success/5"
256 : choice.id === row.answer?.selected
257 ? "border-destructive bg-destructive/10"
258 : "border-border"
259 }`}
260 >
261 <span class="flex h-6 w-6 shrink-0 items-center justify-center rounded-md border bg-background text-[11px] font-semibold text-foreground">
262 {String.fromCharCode(65 + ci())}
263 </span>
264 <span>{choice.text}</span>
265 <Show when={choice.id === row.answer?.selected && choice.id !== row.question.correct}>
266 <Badge variant="destructive" class="ml-auto text-[11px]">✗</Badge>
267 </Show>
268 {choice.id === row.question.correct && (
269 <Badge variant="outline" class="ml-auto border-success/50 bg-success/10 text-success-text text-[11px]">
270 <IconCheck class="h-3 w-3" />
271 </Badge>
272 )}
273 </div>
274 )}
275 </For>
276 </div>
277 </Show>
278 </div>
279 )}
280 </For>
281 </div>
282 )}
283 </Show>
284 </Suspense>
285 </div>
286 );
287}