forge
Explore
Log in

Don't you dare go Hollow

hezarfen_frontend

Clone
★ 0

0 watching0 forksTypeScript5.5 MiB5fcd955Burak Boduroğlu2 months ago730 commits

answer-sheet-view.tsx289 lines, 14.6 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 { personLabel } from "@/lib/person";
18import { useT } from "@/stores/preferences-context";
19
20export function AnswerSheetView(props: { examId: string; userId: string; userLabel?: 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 let hasSheet = true;
99 try {
100 if (mode() === "self") {
101 if (seq == null) throw new ApiError(404, "no attempts");
102 sheet = await getExamReviewAttemptAnswers(examId, seq);
103 } else {
104 sheet = latest || seq == null
105 ? await getStudentAnswers(examId, userId)
106 : await getStudentAttemptAnswers(examId, userId, seq);
107 }
108 } catch (err) {
109 if (err instanceof ApiError && (err.status === 404 || (mode() === "self" && err.status === 409))) {
110 if (mode() === "self" && err instanceof ApiError && err.status === 409) setReviewInProgress(true);
111 hasSheet = false;
112 sheet = {
113 exam: examId,
114 user: { id: userId, username: "", display_name: null },
115 answers: [],
116 auto_score: { earned: 0, possible: 0 },
117 };
118 } else {
119 throw err;
120 }
121 }
122 return { sheet, hasSheet, rows: joinAnswerSheet(questions.items, sheet.answers) };
123 },
124 );
125
126 // Per-sitting answer breakdown for the viewed attempt's header. `is_correct`
127 // is only set for auto-gradable (choice) questions: right = got it, wrong =
128 // missed it, empty = no answer given; answered text questions fall in none
129 // (a human grades those). `pending` surfaces those so the counts stay honest.
130 const sheetStats = createMemo(() => {
131 const rows = data()?.rows ?? [];
132 const answered = (a: (typeof rows)[number]["answer"]) =>
133 !!a && (a.selected != null || !!a.text || !!a.answer_image);
134 let right = 0;
135 let wrong = 0;
136 let empty = 0;
137 let pending = 0;
138 for (const r of rows) {
139 if (!answered(r.answer)) empty++;
140 else if (r.answer?.is_correct === true) right++;
141 else if (r.answer?.is_correct === false) wrong++;
142 else pending++;
143 }
144 return { right, wrong, empty, pending, total: rows.length };
145 });
146
147 return (
148 // The picker stays OUTSIDE the Suspense: switching attempts re-fetches
149 // `data`, and if the dropdown lived inside the suspending subtree it would
150 // unmount and its portalled menu would flash unpositioned (top-left) on
151 // every select. Only the answer sheet suspends.
152 <div class="space-y-4">
153 <Show when={reviewInProgress()}>
154 <p class="rounded-md border border-dashed bg-muted/20 px-3 py-2 text-sm text-muted-foreground">{t("exams.reviewInProgress")}</p>
155 </Show>
156 <Show when={(attempts() ?? []).length > 1}>
157 <div class="flex flex-col gap-1.5">
158 <span class="text-xs font-medium text-muted-foreground">{t("exams.previousAttempts")}</span>
159 <DropdownSelect
160 options={attemptOptions()}
161 value={activeSeq() ?? 0}
162 onChange={(v) => startSwitch(() => setSelectedSeq(v))}
163 triggerClass="w-full sm:w-auto"
164 />
165 </div>
166 </Show>
167 <Suspense fallback={<PageSpinner />}>
168 <Show when={!reviewInProgress() && data()}>
169 {(d) => (
170 <div class={cn("space-y-4 transition-opacity", switching() && "opacity-60")}>
171 <Show when={!isLatest()}>
172 <p class="rounded-md border border-dashed bg-muted/20 px-3 py-2 text-xs text-muted-foreground">{t("exams.pastAttemptReadOnly")}</p>
173 </Show>
174 <div class="flex flex-wrap items-center justify-between gap-2 rounded-md border bg-muted/30 px-4 py-3">
175 <p class="text-sm font-medium">{props.userLabel || (d().hasSheet ? personLabel(d().sheet.user) : "—")}</p>
176 <Show when={d().sheet.answers.length > 0} fallback={<Badge variant="outline">{t("exams.notStarted")}</Badge>}>
177 <div class="flex flex-wrap items-center gap-1.5">
178 <Badge variant="outline" class="border-success/50 bg-success/10 text-success-text">
179 {t("exams.answersRight")}: {sheetStats().right}
180 </Badge>
181 <Badge variant="outline" class="border-destructive/50 bg-destructive/10 text-destructive-text">
182 {t("exams.answersWrong")}: {sheetStats().wrong}
183 </Badge>
184 <Badge variant="outline" class="text-muted-foreground">
185 {t("exams.answersEmpty")}: {sheetStats().empty}
186 </Badge>
187 <Show when={sheetStats().pending > 0}>
188 <Badge variant="outline" class="text-muted-foreground">
189 {t("exams.answersPending")}: {sheetStats().pending}
190 </Badge>
191 </Show>
192 <Badge variant="secondary">
193 {t("exams.autoScore")}: {d().sheet.auto_score.earned}/{d().sheet.auto_score.possible}
194 </Badge>
195 </div>
196 </Show>
197 </div>
198
199 <For each={d().rows}>
200 {(row, idx) => (
201 <div class="rounded-md border p-4">
202 <div class="mb-2 flex flex-wrap items-center gap-2">
203 <span class="text-xs font-semibold text-muted-foreground">#{idx() + 1}</span>
204 <Badge variant="outline">{row.question.points} {t("questions.points")}</Badge>
205 <Show when={row.answer?.is_correct != null}>
206 <Badge variant="outline" class={cn(
207 "size-[22px] p-0 flex items-center justify-center",
208 row.answer?.is_correct ? "border-success/50 bg-success/10 text-success-text" : "border-destructive/50 bg-destructive/10 text-destructive-text",
209 )}>
210 <Show when={row.answer?.is_correct} fallback={<IconX class="h-3 w-3" />}>
211 <IconCheck class="h-3 w-3" />
212 </Show>
213 </Badge>
214 </Show>
215 <Show when={row.answer?.is_correct == null && row.question.kind === "text"}>
216 <Badge variant="outline" class="text-[11px]">{t("questions.kind.text")}</Badge>
217 </Show>
218 <Show when={row.answer?.is_correct == null && row.question.kind !== "text"}>
219 <span class="text-xs text-muted-foreground">—</span>
220 </Show>
221 </div>
222 <p class="mb-3 whitespace-pre-wrap text-sm font-medium">{row.question.text}</p>
223
224 <Show
225 when={row.question.kind === "choice"}
226 fallback={
227 <div class="rounded-sm bg-muted/40 p-3">
228 <p class="text-xs text-muted-foreground">{t("exams.textAnswer")}</p>
229 <p class="mt-1 whitespace-pre-wrap text-sm">{row.answer?.text || "—"}</p>
230 <Show when={row.answer?.answer_image}>
231 <div class="mt-3 space-y-2">
232 <ReplayableImage
233 fetchBlob={() => fetchAnswerImage(row.question.id)}
234 src={answerImageUrl(row.question.id)}
235 alt={t("exams.drawAnswer")}
236 imgClass="h-64 w-full max-w-2xl rounded-md border bg-background object-contain"
237 />
238 <a href={answerImageUrl(row.question.id)} download={`answer-${idx() + 1}.png`}>
239 <Button type="button" size="sm" variant="outline" class="rounded-lg">
240 <IconDownload class="h-4 w-4" />
241 {t("notes.downloadFile")}
242 </Button>
243 </a>
244 </div>
245 </Show>
246 </div>
247 }
248 >
249 <div class="space-y-1.5">
250 <For each={row.question.choices}>
251 {(choice, ci) => (
252 <div
253 class={`flex items-center gap-2 rounded-sm border px-3 py-2 text-sm ${
254 choice.id === row.question.correct && choice.id === row.answer?.selected
255 ? "border-success bg-success/10"
256 : choice.id === row.question.correct
257 ? "border-success/50 bg-success/5"
258 : choice.id === row.answer?.selected
259 ? "border-destructive bg-destructive/10"
260 : "border-border"
261 }`}
262 >
263 <span class="flex h-6 w-6 shrink-0 items-center justify-center rounded-md border bg-background text-[11px] font-semibold text-foreground">
264 {String.fromCharCode(65 + ci())}
265 </span>
266 <span>{choice.text}</span>
267 <Show when={choice.id === row.answer?.selected && choice.id !== row.question.correct}>
268 <Badge variant="destructive" class="ml-auto text-[11px]">✗</Badge>
269 </Show>
270 {choice.id === row.question.correct && (
271 <Badge variant="outline" class="ml-auto border-success/50 bg-success/10 text-success-text text-[11px]">
272 <IconCheck class="h-3 w-3" />
273 </Badge>
274 )}
275 </div>
276 )}
277 </For>
278 </div>
279 </Show>
280 </div>
281 )}
282 </For>
283 </div>
284 )}
285 </Show>
286 </Suspense>
287 </div>
288 );
289}