import { For, Index, Show, Suspense, createEffect, createSignal, lazy, untrack } from "solid-js"; import { createResource } from "@/lib/create-resource"; import { formatApiError } from "@/api/client"; import type { Choice, ImageMeta, QuestionKind, Subject } from "@/api/client"; import { BANK_QUESTION_LIMITS, QUESTION_KINDS } from "@/api/client"; import { getSettings } from "@/api/settings"; import type { DrawScene } from "@/lib/draw-stroke"; import { Button } from "@/components/ui/button"; import { IconCheck, IconEdit, IconFileImage, IconPlus, IconTrash } from "@/components/ui/icons"; import { Input } from "@/components/ui/input"; import { Label } from "@/components/ui/label"; import { Select } from "@/components/ui/select"; import { Textarea } from "@/components/ui/textarea"; import { addChoice as addChoiceRow, blankChoiceSet, removeChoice as removeChoiceRow, setChoiceImage as setChoiceImageIn, setChoiceText, setCorrect as setCorrectIn, storedChoiceSet, submitChoices, type ChoiceSet, } from "@/lib/choice-set"; import { cn } from "@/lib/cn"; import { formatBytes, maxUploadBytes } from "@/lib/upload-limits"; import { useT } from "@/stores/preferences-context"; // Lazy so the drawing pad rides its own chunk, off the exam editor's initial load. const DrawCanvas = lazy(() => import("@/components/ui/draw-canvas").then((m) => ({ default: m.DrawCanvas }))); export type QuestionValues = { subject_id: string; text: string; kind: QuestionKind; points: number; /** Each row keeps its key: a stored id keeps that option, a `new:` id is a new one. */ choices: Choice[] | null; /** Choice id, never an index. */ correct: string | null; image: File | null; /** Freshly picked files, aligned to `choices`. */ choice_images: (File | null)[] | null; }; /** Shape both `ExamQuestion` and `BankQuestion` satisfy — the form only needs these. */ export type QuestionFormInitial = { /** Null for a bank template whose origin subject has since been deleted. */ subject: string | null; text: string; kind: QuestionKind; points: number; choices: Choice[] | null; correct: string | null; image?: ImageMeta | null; choice_images?: (ImageMeta | null)[] | null; }; export function QuestionForm(props: { initial?: QuestionFormInitial; /** Starting text/kind for a new question (an AI-generated draft); ignored when `initial` is set. */ draft?: { text: string; kind: QuestionKind }; subjects: Subject[]; /** True while `subjects` is still loading, so a missing subject is not misreported. */ subjectsPending?: boolean; /** Existing stored image, as a URL the browser can GET (exam or bank path). */ imageSrc?: string; choiceImageSrc?: (choiceId: string) => string; /** Reload the stored image so an existing drawing can be edited, not redrawn. */ loadImageBlob?: () => Promise; submitLabel?: string; onSubmit: (values: QuestionValues) => Promise; onCancel: () => void; }) { const t = useT(); let textAreaRef: HTMLTextAreaElement | undefined; const [text, setText] = createSignal(props.initial?.text ?? props.draft?.text ?? ""); // No first-subject default: the subject is submitted, so the user picks it. const [subjectId, setSubjectId] = createSignal(props.initial?.subject ?? ""); const [kind, setKind] = createSignal(props.initial?.kind ?? props.draft?.kind ?? "choice"); const [points, setPoints] = createSignal(String(props.initial?.points ?? 1)); const [choiceSet, setChoiceSet] = createSignal( props.initial ? storedChoiceSet(props.initial.choices, props.initial.correct) : blankChoiceSet(), ); const [image, setImage] = createSignal(null); const [drawing, setDrawing] = createSignal(false); const [editScene, setEditScene] = createSignal(null); const [error, setError] = createSignal(""); const [pending, setPending] = createSignal(false); const [settings] = createResource(async () => { try { return await getSettings(); } catch { return null; } }); const maxFileBytes = () => maxUploadBytes(settings()); // Reset on a new `initial` only — `props.subjects` may arrive after the form is // open (async course subjects), and re-running then would wipe what was typed. createEffect(() => { const initial = props.initial; untrack(() => { setText(initial?.text ?? props.draft?.text ?? ""); setSubjectId(initial?.subject ?? ""); setKind(initial?.kind ?? props.draft?.kind ?? "choice"); setPoints(String(initial?.points ?? 1)); setChoiceSet(initial ? storedChoiceSet(initial.choices, initial.correct) : blankChoiceSet()); setImage(null); setDrawing(false); setEditScene(null); setError(""); }); }); // The stored subject is not in the list this user can pick from (foreign course, // or they lost access to it). Never swap it silently — show it, and make them pick. const subjectUnavailable = () => { const current = props.initial?.subject; return ( !!current && !props.subjectsPending && subjectId() === current && !props.subjects.some((subject) => subject.id === current) ); }; // Blank pad for a fresh drawing; reload the stored scene to edit an existing one. const startDrawing = () => { setEditScene(null); setDrawing((open) => !open); }; const editDrawing = async () => { const load = props.loadImageBlob; if (!props.initial?.image || !load) return; setError(""); try { const blob = await load(); const { pngBytesToScene } = await import("@/lib/drawing-file"); setEditScene(pngBytesToScene(new Uint8Array(await blob.arrayBuffer()))); } catch { setEditScene(null); // plain image or fetch failed → start blank, never crash } finally { setDrawing(true); } }; const resizeTextArea = () => { if (!textAreaRef) return; textAreaRef.style.height = "auto"; textAreaRef.style.height = `${textAreaRef.scrollHeight}px`; }; createEffect(() => { text(); resizeTextArea(); }); const rows = () => choiceSet().rows; // Stored option images arrive as an array aligned to `initial.choices`, so look // one up by the row's id — the row's display position may have moved. const storedImage = (id: string) => { const index = props.initial?.choices?.findIndex((choice) => choice.id === id) ?? -1; return index >= 0 ? props.initial?.choice_images?.[index] ?? null : null; }; const validImage = (file: File | null): file is File => { if (!file) return false; if (file.size <= maxFileBytes()) return true; setError(t("notes.fileTooLarge", { size: formatBytes(maxFileBytes()) })); return false; }; const setQuestionImage = (file: File | null) => { if (!file) { setImage(null); return; } setError(""); if (validImage(file)) setImage(file); }; const addChoice = () => setChoiceSet((set) => addChoiceRow(set, BANK_QUESTION_LIMITS.maxChoices)); const removeChoice = (id: string) => setChoiceSet((set) => removeChoiceRow(set, id)); const setChoice = (id: string, value: string) => setChoiceSet((set) => setChoiceText(set, id, value)); const setCorrect = (id: string) => setChoiceSet((set) => setCorrectIn(set, id)); const setChoiceImage = (id: string, file: File | null) => { if (file) { setError(""); if (!validImage(file)) return; } setChoiceSet((set) => setChoiceImageIn(set, id, file)); }; const validate = (): QuestionValues | string => { const body = text().trim(); const subject = subjectId().trim(); if (!subject) return t("questions.subjectRequired"); if (subjectUnavailable()) return t("questions.subjectUnavailableHelp"); if (!body) return t("questions.textRequired"); if (body.length > BANK_QUESTION_LIMITS.textMaxLen) return t("form.descriptionMax"); const p = Number(points()); if (!Number.isInteger(p) || p < BANK_QUESTION_LIMITS.minPoints || p > BANK_QUESTION_LIMITS.maxPoints) return t("questions.pointsRange"); if (kind() === "text") { return { subject_id: subject, text: body, kind: "text", points: p, choices: null, correct: null, image: image(), choice_images: null }; } const submitted = submitChoices(choiceSet()); if ( submitted.choices.length < BANK_QUESTION_LIMITS.minChoices || submitted.choices.length > BANK_QUESTION_LIMITS.maxChoices || submitted.choices.some((choice) => choice.text.length > BANK_QUESTION_LIMITS.choiceTextMaxLen) ) { return t("questions.choicesRange"); } // Nothing is marked for the user: either they never picked, or they blanked // the row they had picked. Both end here, and both need a deliberate pick. if (!submitted.correct) return t("questions.correctRequired"); return { subject_id: subject, text: body, kind: "choice", points: p, choices: submitted.choices, correct: submitted.correct, image: image(), choice_images: submitted.images, }; }; const submit = async (e: SubmitEvent) => { e.preventDefault(); const values = validate(); if (typeof values === "string") { setError(values); return; } setError(""); setPending(true); try { await props.onSubmit(values); } catch (err) { setError(formatApiError(err)); } finally { setPending(false); } }; return (
void submit(e)}>