forge
Explore
Log in

Don't you dare go Hollow

hezarfen_frontend

Clone
★ 0

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

question-form.tsx485 lines, 20.6 KiBHistoryRawDownload
1import { For, Index, Show, Suspense, createEffect, createSignal, lazy, untrack } from "solid-js";
2import { createResource } from "@/lib/create-resource";
3import { formatApiError } from "@/api/client";
4import type { Choice, ImageMeta, QuestionKind, Subject } from "@/api/client";
5import { BANK_QUESTION_LIMITS, QUESTION_KINDS } from "@/api/client";
6import { getSettings } from "@/api/settings";
7import type { DrawScene } from "@/lib/draw-stroke";
8import { Button } from "@/components/ui/button";
9import { IconCheck, IconEdit, IconFileImage, IconPlus, IconTrash } from "@/components/ui/icons";
10import { Input } from "@/components/ui/input";
11import { Label } from "@/components/ui/label";
12import { Select } from "@/components/ui/select";
13import { Textarea } from "@/components/ui/textarea";
14import {
15 addChoice as addChoiceRow,
16 blankChoiceSet,
17 removeChoice as removeChoiceRow,
18 setChoiceImage as setChoiceImageIn,
19 setChoiceText,
20 setCorrect as setCorrectIn,
21 storedChoiceSet,
22 submitChoices,
23 type ChoiceSet,
24} from "@/lib/choice-set";
25import { cn } from "@/lib/cn";
26import { formatBytes, maxUploadBytes } from "@/lib/upload-limits";
27import { useT } from "@/stores/preferences-context";
28
29// Lazy so the drawing pad rides its own chunk, off the exam editor's initial load.
30const DrawCanvas = lazy(() => import("@/components/ui/draw-canvas").then((m) => ({ default: m.DrawCanvas })));
31
32export type QuestionValues = {
33 subject_id: string;
34 text: string;
35 kind: QuestionKind;
36 points: number;
37 /** Each row keeps its key: a stored id keeps that option, a `new:` id is a new one. */
38 choices: Choice[] | null;
39 /** Choice id, never an index. */
40 correct: string | null;
41 image: File | null;
42 /** Freshly picked files, aligned to `choices`. */
43 choice_images: (File | null)[] | null;
44};
45
46/** Shape both `ExamQuestion` and `BankQuestion` satisfy — the form only needs these. */
47export type QuestionFormInitial = {
48 /** Null for a bank template whose origin subject has since been deleted. */
49 subject: string | null;
50 text: string;
51 kind: QuestionKind;
52 points: number;
53 choices: Choice[] | null;
54 correct: string | null;
55 image?: ImageMeta | null;
56 choice_images?: (ImageMeta | null)[] | null;
57};
58
59export function QuestionForm(props: {
60 initial?: QuestionFormInitial;
61 /** Starting text/kind for a new question (an AI-generated draft); ignored when `initial` is set. */
62 draft?: { text: string; kind: QuestionKind };
63 subjects: Subject[];
64 /** True while `subjects` is still loading, so a missing subject is not misreported. */
65 subjectsPending?: boolean;
66 /** Existing stored image, as a URL the browser can GET (exam or bank path). */
67 imageSrc?: string;
68 choiceImageSrc?: (choiceId: string) => string;
69 /** Reload the stored image so an existing drawing can be edited, not redrawn. */
70 loadImageBlob?: () => Promise<Blob>;
71 submitLabel?: string;
72 onSubmit: (values: QuestionValues) => Promise<void>;
73 onCancel: () => void;
74}) {
75 const t = useT();
76 let textAreaRef: HTMLTextAreaElement | undefined;
77 const [text, setText] = createSignal(props.initial?.text ?? props.draft?.text ?? "");
78 // No first-subject default: the subject is submitted, so the user picks it.
79 const [subjectId, setSubjectId] = createSignal(props.initial?.subject ?? "");
80 const [kind, setKind] = createSignal<QuestionKind>(props.initial?.kind ?? props.draft?.kind ?? "choice");
81 const [points, setPoints] = createSignal(String(props.initial?.points ?? 1));
82 const [choiceSet, setChoiceSet] = createSignal<ChoiceSet>(
83 props.initial ? storedChoiceSet(props.initial.choices, props.initial.correct) : blankChoiceSet(),
84 );
85 const [image, setImage] = createSignal<File | null>(null);
86 const [drawing, setDrawing] = createSignal(false);
87 const [editScene, setEditScene] = createSignal<DrawScene | null>(null);
88 const [error, setError] = createSignal("");
89 const [pending, setPending] = createSignal(false);
90 const [settings] = createResource(async () => {
91 try {
92 return await getSettings();
93 } catch {
94 return null;
95 }
96 });
97 const maxFileBytes = () => maxUploadBytes(settings());
98
99 // Reset on a new `initial` only — `props.subjects` may arrive after the form is
100 // open (async course subjects), and re-running then would wipe what was typed.
101 createEffect(() => {
102 const initial = props.initial;
103 untrack(() => {
104 setText(initial?.text ?? props.draft?.text ?? "");
105 setSubjectId(initial?.subject ?? "");
106 setKind(initial?.kind ?? props.draft?.kind ?? "choice");
107 setPoints(String(initial?.points ?? 1));
108 setChoiceSet(initial ? storedChoiceSet(initial.choices, initial.correct) : blankChoiceSet());
109 setImage(null);
110 setDrawing(false);
111 setEditScene(null);
112 setError("");
113 });
114 });
115
116 // The stored subject is not in the list this user can pick from (foreign course,
117 // or they lost access to it). Never swap it silently — show it, and make them pick.
118 const subjectUnavailable = () => {
119 const current = props.initial?.subject;
120 return (
121 !!current &&
122 !props.subjectsPending &&
123 subjectId() === current &&
124 !props.subjects.some((subject) => subject.id === current)
125 );
126 };
127
128 // Blank pad for a fresh drawing; reload the stored scene to edit an existing one.
129 const startDrawing = () => {
130 setEditScene(null);
131 setDrawing((open) => !open);
132 };
133
134 const editDrawing = async () => {
135 const load = props.loadImageBlob;
136 if (!props.initial?.image || !load) return;
137 setError("");
138 try {
139 const blob = await load();
140 const { pngBytesToScene } = await import("@/lib/drawing-file");
141 setEditScene(pngBytesToScene(new Uint8Array(await blob.arrayBuffer())));
142 } catch {
143 setEditScene(null); // plain image or fetch failed → start blank, never crash
144 } finally {
145 setDrawing(true);
146 }
147 };
148
149 const resizeTextArea = () => {
150 if (!textAreaRef) return;
151 textAreaRef.style.height = "auto";
152 textAreaRef.style.height = `${textAreaRef.scrollHeight}px`;
153 };
154
155 createEffect(() => {
156 text();
157 resizeTextArea();
158 });
159
160 const rows = () => choiceSet().rows;
161 // Stored option images arrive as an array aligned to `initial.choices`, so look
162 // one up by the row's id — the row's display position may have moved.
163 const storedImage = (id: string) => {
164 const index = props.initial?.choices?.findIndex((choice) => choice.id === id) ?? -1;
165 return index >= 0 ? props.initial?.choice_images?.[index] ?? null : null;
166 };
167
168 const validImage = (file: File | null): file is File => {
169 if (!file) return false;
170 if (file.size <= maxFileBytes()) return true;
171 setError(t("notes.fileTooLarge", { size: formatBytes(maxFileBytes()) }));
172 return false;
173 };
174
175 const setQuestionImage = (file: File | null) => {
176 if (!file) {
177 setImage(null);
178 return;
179 }
180 setError("");
181 if (validImage(file)) setImage(file);
182 };
183
184 const addChoice = () => setChoiceSet((set) => addChoiceRow(set, BANK_QUESTION_LIMITS.maxChoices));
185 const removeChoice = (id: string) => setChoiceSet((set) => removeChoiceRow(set, id));
186 const setChoice = (id: string, value: string) => setChoiceSet((set) => setChoiceText(set, id, value));
187 const setCorrect = (id: string) => setChoiceSet((set) => setCorrectIn(set, id));
188
189 const setChoiceImage = (id: string, file: File | null) => {
190 if (file) {
191 setError("");
192 if (!validImage(file)) return;
193 }
194 setChoiceSet((set) => setChoiceImageIn(set, id, file));
195 };
196
197 const validate = (): QuestionValues | string => {
198 const body = text().trim();
199 const subject = subjectId().trim();
200 if (!subject) return t("questions.subjectRequired");
201 if (subjectUnavailable()) return t("questions.subjectUnavailableHelp");
202 if (!body) return t("questions.textRequired");
203 if (body.length > BANK_QUESTION_LIMITS.textMaxLen) return t("form.descriptionMax");
204 const p = Number(points());
205 if (!Number.isInteger(p) || p < BANK_QUESTION_LIMITS.minPoints || p > BANK_QUESTION_LIMITS.maxPoints) return t("questions.pointsRange");
206 if (kind() === "text") {
207 return { subject_id: subject, text: body, kind: "text", points: p, choices: null, correct: null, image: image(), choice_images: null };
208 }
209 const submitted = submitChoices(choiceSet());
210 if (
211 submitted.choices.length < BANK_QUESTION_LIMITS.minChoices ||
212 submitted.choices.length > BANK_QUESTION_LIMITS.maxChoices ||
213 submitted.choices.some((choice) => choice.text.length > BANK_QUESTION_LIMITS.choiceTextMaxLen)
214 ) {
215 return t("questions.choicesRange");
216 }
217 // Nothing is marked for the user: either they never picked, or they blanked
218 // the row they had picked. Both end here, and both need a deliberate pick.
219 if (!submitted.correct) return t("questions.correctRequired");
220 return {
221 subject_id: subject,
222 text: body,
223 kind: "choice",
224 points: p,
225 choices: submitted.choices,
226 correct: submitted.correct,
227 image: image(),
228 choice_images: submitted.images,
229 };
230 };
231
232 const submit = async (e: SubmitEvent) => {
233 e.preventDefault();
234 const values = validate();
235 if (typeof values === "string") {
236 setError(values);
237 return;
238 }
239 setError("");
240 setPending(true);
241 try {
242 await props.onSubmit(values);
243 } catch (err) {
244 setError(formatApiError(err));
245 } finally {
246 setPending(false);
247 }
248 };
249
250 return (
251 <form class="flex min-h-full flex-col space-y-3" onSubmit={(e) => void submit(e)}>
252 <div class="rounded-lg border bg-card p-3.5 shadow-xs">
253 <div class="space-y-2">
254 <Label for="question-text" class="text-sm font-semibold">{t("questions.text")}</Label>
255 <Textarea
256 id="question-text"
257 ref={textAreaRef}
258 class="min-h-28 resize-none overflow-hidden bg-background text-base"
259 value={text()}
260 maxlength={2000}
261 rows={3}
262 required
263 placeholder={t("questions.text")}
264 onInput={(e) => {
265 setText(e.currentTarget.value);
266 resizeTextArea();
267 }}
268 />
269 <div class="flex items-center gap-3">
270 <Show when={props.initial?.image && props.imageSrc}>
271 <div class="relative shrink-0">
272 <img
273 src={props.imageSrc}
274 alt={t("questions.image")}
275 class="h-14 w-24 rounded border bg-muted/20 object-contain"
276 />
277 </div>
278 </Show>
279 <div class="flex items-center gap-2">
280 <input
281 id="question-image"
282 type="file"
283 accept="image/png,image/jpeg,image/webp,image/gif"
284 class="sr-only"
285 onChange={(event) => setQuestionImage(event.currentTarget.files?.[0] ?? null)}
286 />
287 <label for="question-image" class="flex cursor-pointer items-center gap-1.5 rounded-md border border-dashed bg-muted/30 px-2.5 py-1.5 text-xs font-medium text-muted-foreground transition-colors hover:bg-muted/60 hover:text-foreground">
288 <IconFileImage class="h-3.5 w-3.5" />
289 <span class="truncate">{image()?.name ?? t("questions.image")}</span>
290 </label>
291 <button
292 type="button"
293 aria-expanded={drawing()}
294 class="flex items-center gap-1.5 rounded-md border border-dashed bg-muted/30 px-2.5 py-1.5 text-xs font-medium text-muted-foreground transition-colors hover:bg-muted/60 hover:text-foreground"
295 onClick={startDrawing}
296 >
297 <IconEdit class="h-3.5 w-3.5" />
298 {t("questions.draw")}
299 </button>
300 <Show when={props.initial?.image && props.loadImageBlob}>
301 <button
302 type="button"
303 class="flex items-center gap-1.5 rounded-md border border-dashed bg-muted/30 px-2.5 py-1.5 text-xs font-medium text-muted-foreground transition-colors hover:bg-muted/60 hover:text-foreground"
304 onClick={() => void editDrawing()}
305 >
306 <IconEdit class="h-3.5 w-3.5" />
307 {t("questions.editDrawing")}
308 </button>
309 </Show>
310 </div>
311 </div>
312 <Show when={drawing()}>
313 <div class="mt-3 border-t border-border/50 pt-3">
314 <Label class="mb-2 block text-xs font-semibold text-muted-foreground">{t("questions.drawTitle")}</Label>
315 <Suspense fallback={<div class="h-88 animate-pulse rounded-lg border bg-muted/20" />}>
316 <DrawCanvas
317 fileName="question.png"
318 initialScene={editScene()}
319 onSave={(file) => {
320 if (validImage(file)) {
321 setImage(file);
322 setDrawing(false);
323 }
324 }}
325 />
326 </Suspense>
327 </div>
328 </Show>
329 </div>
330 </div>
331
332 <div class="flex flex-wrap items-end gap-3 rounded-lg border bg-card px-3.5 py-3 shadow-xs">
333 <div class="min-w-0 flex-1 basis-40">
334 <Label for="question-subject" class="mb-1 block text-xs font-semibold text-muted-foreground">{t("subjects.subject")}</Label>
335 <Select id="question-subject" class="h-9 py-1.5 text-sm" value={subjectId()} required onChange={(e) => setSubjectId(e.currentTarget.value)}>
336 <option value="">{t("subjects.select")}</option>
337 <Show when={subjectUnavailable()}>
338 <option value={props.initial?.subject ?? ""} disabled>{t("questions.subjectUnavailable")}</option>
339 </Show>
340 <For each={props.subjects}>{(subject) => <option value={subject.id}>{subject.name}</option>}</For>
341 </Select>
342 <Show when={subjectUnavailable()}>
343 <p class="mt-1 text-[11px] text-destructive-text">{t("questions.subjectUnavailableHelp")}</p>
344 </Show>
345 </div>
346 <div>
347 <Label class="mb-1 block text-xs font-semibold text-muted-foreground">{t("questions.kind")}</Label>
348 <div class="flex gap-0.5 rounded-md border bg-muted/40 p-0.5">
349 <For each={QUESTION_KINDS}>
350 {(k) => (
351 <button
352 type="button"
353 class={cn(
354 "h-7 rounded-sm px-2.5 text-xs font-semibold transition-colors",
355 kind() === k
356 ? "bg-primary text-primary-foreground shadow-2xs"
357 : "text-muted-foreground hover:text-foreground",
358 )}
359 onClick={() => setKind(k)}
360 >
361 {k === "choice" ? t("questions.kind.choice") : t("questions.kind.text")}
362 </button>
363 )}
364 </For>
365 </div>
366 </div>
367 <div class="w-20">
368 <Label for="question-points" class="mb-1 block text-xs font-semibold text-muted-foreground">{t("questions.points")}</Label>
369 <Input
370 id="question-points"
371 type="number"
372 min={1}
373 max={100}
374 value={points()}
375 class="h-9 text-sm"
376 required
377 onInput={(e) => setPoints(e.currentTarget.value)}
378 />
379 </div>
380 </div>
381
382 <Show when={kind() === "choice"}>
383 <div class="rounded-lg border bg-card p-3.5 shadow-xs">
384 <div class="mb-3 flex items-center justify-between gap-2 border-b border-border/50 pb-2">
385 <div class="min-w-0">
386 <Label class="text-sm font-semibold">{t("questions.choices")}</Label>
387 <p class="mt-0.5 text-xs text-muted-foreground">{t("questions.correctHint")}</p>
388 </div>
389 <Button type="button" variant="outline" size="sm" class="h-7 gap-1 text-xs" disabled={rows().length >= BANK_QUESTION_LIMITS.maxChoices} onClick={addChoice}>
390 <IconPlus class="h-3.5 w-3.5" />
391 {t("questions.addChoice")}
392 </Button>
393 </div>
394 <div class="space-y-2">
395 <Index each={rows()}>
396 {(row, index) => {
397 const isCorrect = () => choiceSet().correct === row().id;
398 // Keyed by the row's own id, so a stored option keeps its picture no
399 // matter where it sits now; null = a row the server has never seen.
400 const stored = () => storedImage(row().id);
401 return (
402 <div
403 data-choice-id={row().id}
404 class={cn(
405 "flex items-start gap-2 rounded-md border p-2 transition-colors",
406 isCorrect() ? "border-emerald-400/60 bg-emerald-50/60" : "border-border bg-background",
407 )}
408 >
409 <button
410 type="button"
411 class={cn(
412 "mt-0.5 inline-flex h-6 w-6 shrink-0 items-center justify-center rounded text-xs font-bold transition-colors",
413 isCorrect()
414 ? "bg-emerald-600 text-white shadow-2xs"
415 : "border bg-background text-muted-foreground hover:border-emerald-400 hover:text-emerald-600",
416 )}
417 onClick={() => setCorrect(row().id)}
418 title={t("questions.correct")}
419 >
420 {isCorrect() ? <IconCheck class="h-3.5 w-3.5" /> : String.fromCharCode(65 + index)}
421 </button>
422 <div class="min-w-0 flex-1 space-y-1.5">
423 <Input
424 class="h-8 text-sm"
425 value={row().text}
426 maxlength={500}
427 placeholder={t("questions.choicePlaceholder", { index: String.fromCharCode(65 + index) })}
428 onInput={(e) => setChoice(row().id, e.currentTarget.value)}
429 />
430 <div class="flex items-center gap-2">
431 <input
432 id={`choice-image-${index}`}
433 type="file"
434 accept="image/png,image/jpeg,image/webp,image/gif"
435 class="sr-only"
436 onChange={(event) => setChoiceImage(row().id, event.currentTarget.files?.[0] ?? null)}
437 />
438 <label for={`choice-image-${index}`} class="flex cursor-pointer items-center gap-1 rounded-md border border-dashed bg-muted/20 px-2 py-0.5 text-[11px] font-medium text-muted-foreground transition-colors hover:bg-muted/60 hover:text-foreground">
439 <IconFileImage class="h-3 w-3" />
440 {row().image?.name ?? t("questions.choiceImage")}
441 </label>
442 <Show when={stored() && props.choiceImageSrc}>
443 <img
444 src={props.choiceImageSrc?.(row().id)}
445 alt={t("questions.choiceImage")}
446 class="h-8 w-12 rounded border bg-muted/20 object-contain"
447 />
448 </Show>
449 </div>
450 </div>
451 <Button
452 type="button"
453 variant="ghost"
454 size="sm"
455 disabled={rows().length <= BANK_QUESTION_LIMITS.minChoices}
456 class="mt-0.5 h-6 w-6 p-0 text-muted-foreground hover:text-destructive-text"
457 onClick={() => removeChoice(row().id)}
458 aria-label={t("common.delete")}
459 >
460 <IconTrash class="h-3.5 w-3.5" />
461 </Button>
462 </div>
463 );
464 }}
465 </Index>
466 </div>
467 </div>
468 </Show>
469
470 {error() && <p class="rounded-sm bg-destructive/10 px-3 py-1.5 text-sm text-destructive-text">{error()}</p>}
471
472 {/* `-bottom-5 pb-5` reaches over the panel body's own bottom padding —
473 with `bottom-0` the footer stuck above it and the form scrolled
474 visibly underneath. */}
475 <div class="!mt-auto sticky -bottom-5 z-10 -mx-5 -mb-5 flex flex-wrap items-center justify-end gap-2 border-t border-border-hairline bg-surface-base px-5 pb-5 pt-4">
476 <Button type="button" variant="outline" size="sm" class="rounded-lg" onClick={props.onCancel}>
477 {t("common.cancel")}
478 </Button>
479 <Button type="submit" size="sm" class="min-w-[7.5rem] rounded-lg" disabled={pending()}>
480 {props.submitLabel ?? (props.initial ? t("common.update") : t("common.create"))}
481 </Button>
482 </div>
483 </form>
484 );
485}