forge
Explore
Log in

Don't you dare go Hollow

🖼️ question/choice image upload and delete UI

Browse files at this commit

758d0945ca0b4278826762267e2d9ad9c41389ccBurak BoduroğluParent: e6caffe
  • feat
    • 🖼️ question/choice image upload and delete UI
Show full message
feat: 🖼️ question/choice image upload and delete UI
- question-form: image and choice_image file inputs with preview,
  dashed dropzone labels, sr-only native file inputs
- exam-questions-panel: submit now posts images after question save,
  inline delete buttons per image/choice-image with loading guard
- 6 new API wrappers: post/delete/get blob for question and choice images
- question kind toggle: segmented button group replaces plain select
src/api/deleteExamChoiceImage.tsadded+5 -0
@@ -0,0 +1,5 @@
1+import { client } from "./client";
2+
3+export function deleteExamChoiceImage(examId: string, questionId: string, index: number): Promise<void> {
4+ return client<void>(`/exams/${examId}/questions/${questionId}/choices/${index}/image`, { method: "DELETE" });
5+}
src/api/deleteExamQuestionImage.tsadded+5 -0
@@ -0,0 +1,5 @@
1+import { client } from "./client";
2+
3+export function deleteExamQuestionImage(examId: string, questionId: string): Promise<void> {
4+ return client<void>(`/exams/${examId}/questions/${questionId}/image`, { method: "DELETE" });
5+}
src/api/getExamChoiceImageBlob.tsadded+5 -0
@@ -0,0 +1,5 @@
1+import { blobClient } from "./client";
2+
3+export function getExamChoiceImageBlob(examId: string, questionId: string, index: number, signal?: AbortSignal): Promise<Blob> {
4+ return blobClient(`/exams/${examId}/questions/${questionId}/choices/${index}/image`, signal);
5+}
src/api/getExamQuestionImageBlob.tsadded+5 -0
@@ -0,0 +1,5 @@
1+import { blobClient } from "./client";
2+
3+export function getExamQuestionImageBlob(examId: string, questionId: string, signal?: AbortSignal): Promise<Blob> {
4+ return blobClient(`/exams/${examId}/questions/${questionId}/image`, signal);
5+}
src/api/postExamChoiceImage.tsadded+8 -0
@@ -0,0 +1,8 @@
1+import { formClient } from "./client";
2+import type { ImageMeta } from "./types";
3+
4+export function postExamChoiceImage(examId: string, questionId: string, index: number, file: File, signal?: AbortSignal): Promise<ImageMeta> {
5+ const body = new FormData();
6+ body.append("file", file);
7+ return formClient<ImageMeta>(`/exams/${examId}/questions/${questionId}/choices/${index}/image`, body, signal);
8+}
src/api/postExamQuestionImage.tsadded+8 -0
@@ -0,0 +1,8 @@
1+import { formClient } from "./client";
2+import type { ImageMeta } from "./types";
3+
4+export function postExamQuestionImage(examId: string, questionId: string, file: File, signal?: AbortSignal): Promise<ImageMeta> {
5+ const body = new FormData();
6+ body.append("file", file);
7+ return formClient<ImageMeta>(`/exams/${examId}/questions/${questionId}/image`, body, signal);
8+}
src/components/exams/exam-questions-panel.tsxmodified+63 -10
@@ -1,8 +1,12 @@
1 import { For, Show, Suspense, createEffect, createMemo, createResource, createSignal } from "solid-js";1 import { For, Show, Suspense, createEffect, createMemo, createResource, createSignal } from "solid-js";
2+import { deleteExamChoiceImage } from "@/api/deleteExamChoiceImage";
3+import { deleteExamQuestionImage } from "@/api/deleteExamQuestionImage";
2 import { deleteExamQuestionById } from "@/api/deleteExamQuestionById";4 import { deleteExamQuestionById } from "@/api/deleteExamQuestionById";
3 import { getCourseSubjects } from "@/api/getCourseSubjects";5 import { getCourseSubjects } from "@/api/getCourseSubjects";
4 import { getExamQuestions } from "@/api/getExamQuestions";6 import { getExamQuestions } from "@/api/getExamQuestions";
5 import { patchExamQuestionById } from "@/api/patchExamQuestionById";7 import { patchExamQuestionById } from "@/api/patchExamQuestionById";
8+import { postExamChoiceImage } from "@/api/postExamChoiceImage";
9+import { postExamQuestionImage } from "@/api/postExamQuestionImage";
6 import { postExamQuestion } from "@/api/postExamQuestion";10 import { postExamQuestion } from "@/api/postExamQuestion";
7 import { ApiError, formatApiError } from "@/api/client";11 import { ApiError, formatApiError } from "@/api/client";
8 import type { ExamQuestion } from "@/api/types";12 import type { ExamQuestion } from "@/api/types";
@@ -34,6 +38,7 @@ export function ExamQuestionsPanel(props: { examId: string; courseId: string; re
34 const [editing, setEditing] = createSignal<ExamQuestion | null>(null);38 const [editing, setEditing] = createSignal<ExamQuestion | null>(null);
35 const [removeQuestion, setRemoveQuestion] = createSignal<ExamQuestion | null>(null);39 const [removeQuestion, setRemoveQuestion] = createSignal<ExamQuestion | null>(null);
36 const [error, setError] = createSignal("");40 const [error, setError] = createSignal("");
41+ const [imagePending, setImagePending] = createSignal("");
37 const [flash, setFlash] = createFlash();42 const [flash, setFlash] = createFlash();
38 const [page, setPage] = createSignal(0);43 const [page, setPage] = createSignal(0);
39 44
@@ -64,11 +69,17 @@ export function ExamQuestionsPanel(props: { examId: string; courseId: string; re
64 try {69 try {
65 const q = editing();70 const q = editing();
66 const isNewQuestion = !q;71 const isNewQuestion = !q;
72+ const { image, choice_images, ...body } = values;
73+ const saved = q
74+ ? await patchExamQuestionById(props.examId, q.id, body)
75+ : await postExamQuestion(props.examId, body);
76+ if (image) await postExamQuestionImage(props.examId, saved.id, image);
77+ for (const [index, file] of (choice_images ?? []).entries()) {
78+ if (file) await postExamChoiceImage(props.examId, saved.id, index, file);
79+ }
67 if (q) {80 if (q) {
68- await patchExamQuestionById(props.examId, q.id, values);
69 setFlash(t("common.saved"));81 setFlash(t("common.saved"));
70 } else {82 } else {
71- await postExamQuestion(props.examId, values);
72 setFlash(t("common.created"));83 setFlash(t("common.created"));
73 }84 }
74 setEditing(null);85 setEditing(null);
@@ -80,6 +91,36 @@ export function ExamQuestionsPanel(props: { examId: string; courseId: string; re
80 }91 }
81 };92 };
82 93
94+ const removeQuestionImage = async (question: ExamQuestion) => {
95+ if (props.readOnly) return;
96+ setError("");
97+ setImagePending(`${question.id}:question`);
98+ try {
99+ await deleteExamQuestionImage(props.examId, question.id);
100+ await refetch();
101+ setFlash(t("common.deleted"));
102+ } catch (err) {
103+ setError(formatApiError(err));
104+ } finally {
105+ setImagePending("");
106+ }
107+ };
108+
109+ const removeChoiceImage = async (question: ExamQuestion, index: number) => {
110+ if (props.readOnly) return;
111+ setError("");
112+ setImagePending(`${question.id}:choice:${index}`);
113+ try {
114+ await deleteExamChoiceImage(props.examId, question.id, index);
115+ await refetch();
116+ setFlash(t("common.deleted"));
117+ } catch (err) {
118+ setError(formatApiError(err));
119+ } finally {
120+ setImagePending("");
121+ }
122+ };
123+
83 return (124 return (
84 <div class={props.embedded ? "space-y-4" : "surface-card space-y-4 p-5"}>125 <div class={props.embedded ? "space-y-4" : "surface-card space-y-4 p-5"}>
85 <Show when={flash()}>126 <Show when={flash()}>
@@ -156,6 +197,11 @@ export function ExamQuestionsPanel(props: { examId: string; courseId: string; re
156 class="max-h-64 rounded-md border object-contain"197 class="max-h-64 rounded-md border object-contain"
157 />198 />
158 </Show>199 </Show>
200+ <Show when={!props.readOnly && q.image}>
201+ <Button type="button" variant="ghost" size="sm" class="h-8 w-fit text-destructive" disabled={imagePending() === `${q.id}:question`} onClick={() => void removeQuestionImage(q)}>
202+ {t("common.delete")}
203+ </Button>
204+ </Show>
159 <p class="whitespace-pre-wrap text-sm font-medium">{q.text}</p>205 <p class="whitespace-pre-wrap text-sm font-medium">{q.text}</p>
160 <Show when={q.kind === "choice" && q.choices}>206 <Show when={q.kind === "choice" && q.choices}>
161 <ol class="grid gap-2 text-sm text-muted-foreground">207 <ol class="grid gap-2 text-sm text-muted-foreground">
@@ -171,14 +217,21 @@ export function ExamQuestionsPanel(props: { examId: string; courseId: string; re
171 <span class="mt-0.5 inline-flex h-5 min-w-5 items-center justify-center rounded-[3px] border bg-background text-[11px] font-semibold text-foreground">217 <span class="mt-0.5 inline-flex h-5 min-w-5 items-center justify-center rounded-[3px] border bg-background text-[11px] font-semibold text-foreground">
172 {String.fromCharCode(65 + choiceIndex())}218 {String.fromCharCode(65 + choiceIndex())}
173 </span>219 </span>
174- <span class="min-w-0 whitespace-pre-wrap">{choice}</span>220+ <span class="min-w-0 flex-1 space-y-2 whitespace-pre-wrap">
175- <Show when={q.choice_images?.[choiceIndex()]}>221+ <span class="block">{choice}</span>
176- <img222+ <Show when={q.choice_images?.[choiceIndex()]}>
177- src={`/api/exams/${props.examId}/questions/${q.id}/choices/${choiceIndex()}/image`}223+ <img
178- alt={t("questions.choiceImage")}224+ src={`/api/exams/${props.examId}/questions/${q.id}/choices/${choiceIndex()}/image`}
179- class="max-h-40 rounded-md border object-contain"225+ alt={t("questions.choiceImage")}
180- />226+ class="max-h-40 rounded-md border object-contain"
181- </Show>227+ />
228+ </Show>
229+ <Show when={!props.readOnly && q.choice_images?.[choiceIndex()]}>
230+ <Button type="button" variant="ghost" size="sm" class="h-8 px-2 text-destructive" disabled={imagePending() === `${q.id}:choice:${choiceIndex()}`} onClick={() => void removeChoiceImage(q, choiceIndex())}>
231+ {t("common.delete")}
232+ </Button>
233+ </Show>
234+ </span>
182 </li>235 </li>
183 )}236 )}
184 </For>237 </For>
src/components/exams/question-form.tsxmodified+85 -11
@@ -3,11 +3,12 @@ import { formatApiError } from "@/api/client";
3 import type { ExamQuestion, QuestionKind, Subject } from "@/api/types";3 import type { ExamQuestion, QuestionKind, Subject } from "@/api/types";
4 import { QUESTION_KINDS } from "@/api/types";4 import { QUESTION_KINDS } from "@/api/types";
5 import { Button } from "@/components/ui/button";5 import { Button } from "@/components/ui/button";
6-import { IconCheck, IconPlus, IconTrash } from "@/components/ui/icons";6+import { IconCheck, IconFileImage, IconPlus, IconTrash } from "@/components/ui/icons";
7 import { Input } from "@/components/ui/input";7 import { Input } from "@/components/ui/input";
8 import { Label } from "@/components/ui/label";8 import { Label } from "@/components/ui/label";
9 import { Select } from "@/components/ui/select";9 import { Select } from "@/components/ui/select";
10 import { Textarea } from "@/components/ui/textarea";10 import { Textarea } from "@/components/ui/textarea";
11+import { cn } from "@/lib/cn";
11 import { useT } from "@/stores/preferences-context";12 import { useT } from "@/stores/preferences-context";
12 13
13 export type QuestionValues = {14 export type QuestionValues = {
@@ -17,6 +18,8 @@ export type QuestionValues = {
17 points: number;18 points: number;
18 choices: string[] | null;19 choices: string[] | null;
19 correct: number | null;20 correct: number | null;
21+ image: File | null;
22+ choice_images: (File | null)[] | null;
20 };23 };
21 24
22 export function QuestionForm(props: {25 export function QuestionForm(props: {
@@ -33,6 +36,8 @@ export function QuestionForm(props: {
33 const [points, setPoints] = createSignal(String(props.initial?.points ?? 1));36 const [points, setPoints] = createSignal(String(props.initial?.points ?? 1));
34 const [choices, setChoices] = createSignal<string[]>(props.initial?.choices ?? ["", "", "", ""]);37 const [choices, setChoices] = createSignal<string[]>(props.initial?.choices ?? ["", "", "", ""]);
35 const [correct, setCorrect] = createSignal(props.initial?.correct ?? 0);38 const [correct, setCorrect] = createSignal(props.initial?.correct ?? 0);
39+ const [image, setImage] = createSignal<File | null>(null);
40+ const [choiceImages, setChoiceImages] = createSignal<(File | null)[]>(choices().map(() => null));
36 const [error, setError] = createSignal("");41 const [error, setError] = createSignal("");
37 const [pending, setPending] = createSignal(false);42 const [pending, setPending] = createSignal(false);
38 43
@@ -44,6 +49,8 @@ export function QuestionForm(props: {
44 setPoints(String(initial?.points ?? 1));49 setPoints(String(initial?.points ?? 1));
45 setChoices(initial?.choices ?? ["", "", "", ""]);50 setChoices(initial?.choices ?? ["", "", "", ""]);
46 setCorrect(initial?.correct ?? 0);51 setCorrect(initial?.correct ?? 0);
52+ setImage(null);
53+ setChoiceImages((initial?.choices ?? ["", "", "", ""]).map(() => null));
47 setError("");54 setError("");
48 });55 });
49 56
@@ -62,12 +69,18 @@ export function QuestionForm(props: {
62 setChoices((current) => current.map((choice, i) => (i === index ? value : choice)));69 setChoices((current) => current.map((choice, i) => (i === index ? value : choice)));
63 };70 };
64 71
72+ const setChoiceImage = (index: number, file: File | null) => {
73+ setChoiceImages((current) => choices().map((_, i) => (i === index ? file : current[i] ?? null)));
74+ };
75+
65 const addChoice = () => {76 const addChoice = () => {
66 setChoices((current) => (current.length >= 10 ? current : [...current, ""]));77 setChoices((current) => (current.length >= 10 ? current : [...current, ""]));
78+ setChoiceImages((current) => (current.length >= 10 ? current : [...current, null]));
67 };79 };
68 80
69 const removeChoice = (index: number) => {81 const removeChoice = (index: number) => {
70 setChoices((current) => current.filter((_, i) => i !== index));82 setChoices((current) => current.filter((_, i) => i !== index));
83+ setChoiceImages((current) => current.filter((_, i) => i !== index));
71 setCorrect((current) => Math.max(0, Math.min(current, choices().length - 2)));84 setCorrect((current) => Math.max(0, Math.min(current, choices().length - 2)));
72 };85 };
73 86
@@ -80,15 +93,18 @@ export function QuestionForm(props: {
80 const p = Number(points());93 const p = Number(points());
81 if (!Number.isInteger(p) || p < 1 || p > 100) return t("questions.pointsRange");94 if (!Number.isInteger(p) || p < 1 || p > 100) return t("questions.pointsRange");
82 if (kind() === "text") {95 if (kind() === "text") {
83- return { subject_id: subject, text: body, kind: "text", points: p, choices: null, correct: null };96+ return { subject_id: subject, text: body, kind: "text", points: p, choices: null, correct: null, image: image(), choice_images: null };
84 }97 }
85- const cleanChoices = choices().map((choice) => choice.trim()).filter(Boolean);98+ const indexedChoices = choices()
99+ .map((choice, index) => ({ choice: choice.trim(), image: choiceImages()[index] ?? null }))
100+ .filter((item) => item.choice);
101+ const cleanChoices = indexedChoices.map((item) => item.choice);
86 if (cleanChoices.length < 2 || cleanChoices.length > 10 || cleanChoices.some((choice) => choice.length > 500)) {102 if (cleanChoices.length < 2 || cleanChoices.length > 10 || cleanChoices.some((choice) => choice.length > 500)) {
87 return t("questions.choicesRange");103 return t("questions.choicesRange");
88 }104 }
89 const c = correct();105 const c = correct();
90 if (!Number.isInteger(c) || c < 0 || c >= cleanChoices.length) return t("questions.correctRange");106 if (!Number.isInteger(c) || c < 0 || c >= cleanChoices.length) return t("questions.correctRange");
91- return { subject_id: subject, text: body, kind: "choice", points: p, choices: cleanChoices, correct: c };107+ return { subject_id: subject, text: body, kind: "choice", points: p, choices: cleanChoices, correct: c, image: image(), choice_images: indexedChoices.map((item) => item.image) };
92 };108 };
93 109
94 const submit = async (e: SubmitEvent) => {110 const submit = async (e: SubmitEvent) => {
@@ -128,19 +144,56 @@ export function QuestionForm(props: {
128 resizeTextArea();144 resizeTextArea();
129 }}145 }}
130 />146 />
147+ <div class="mt-2 rounded-lg border bg-background p-3 shadow-sm">
148+ <Label for="question-image" class="text-xs font-semibold text-muted-foreground">{t("questions.image")}</Label>
149+ <Show when={props.initial?.image}>
150+ <img
151+ src={`/api/exams/${props.initial!.exam}/questions/${props.initial!.id}/image`}
152+ alt={t("questions.image")}
153+ class="mt-2 max-h-40 rounded-md border object-contain"
154+ />
155+ </Show>
156+ <input
157+ id="question-image"
158+ type="file"
159+ accept="image/png,image/jpeg,image/webp,image/gif"
160+ class="sr-only"
161+ onChange={(event) => setImage(event.currentTarget.files?.[0] ?? null)}
162+ />
163+ <label for="question-image" class="mt-2 flex cursor-pointer items-center gap-2 rounded-md border border-dashed bg-muted/30 px-3 py-2 text-xs font-medium text-muted-foreground transition-colors hover:bg-muted/60 hover:text-foreground">
164+ <IconFileImage class="h-4 w-4" />
165+ <span class="truncate">{image()?.name ?? t("common.createItem", { item: t("questions.image") })}</span>
166+ </label>
167+ </div>
131 </div>168 </div>
132- <div class="space-y-1.5">169+ <div class="flex flex-col gap-1.5">
133- <Label for="question-kind" class="text-sm font-semibold">{t("questions.kind")}</Label>170+ <Label class="text-sm font-semibold">{t("questions.kind")}</Label>
134- <div class="flex h-[10rem] min-h-[10rem] flex-col justify-between rounded-md border bg-background p-3">171+ <div class="flex flex-1 flex-col gap-3 rounded-lg border bg-background p-3 shadow-sm">
135 <div class="space-y-1.5">172 <div class="space-y-1.5">
136 <Label for="question-subject">{t("subjects.subject")}</Label>173 <Label for="question-subject">{t("subjects.subject")}</Label>
137- <Select id="question-subject" value={subjectId()} required onChange={(e) => setSubjectId(e.currentTarget.value)}>174+ <Select id="question-subject" class="h-10 py-2" value={subjectId()} required onChange={(e) => setSubjectId(e.currentTarget.value)}>
138 <option value="">{t("subjects.select")}</option>175 <option value="">{t("subjects.select")}</option>
139 <For each={props.subjects}>{(subject) => <option value={subject.id}>{subject.name}</option>}</For>176 <For each={props.subjects}>{(subject) => <option value={subject.id}>{subject.name}</option>}</For>
140 </Select>177 </Select>
141 </div>178 </div>
142- <div class="space-y-1.5">179+ <div class="mt-3 grid grid-cols-2 gap-1 rounded-lg border bg-muted/40 p-1 pt-2">
143- <Select id="question-kind" value={kind()} onChange={(e) => setKind(e.currentTarget.value as QuestionKind)}>180+ <For each={QUESTION_KINDS}>
181+ {(k) => (
182+ <button
183+ type="button"
184+ class={cn(
185+ "h-9 rounded-md border text-xs font-semibold transition-colors",
186+ kind() === k
187+ ? "border-primary bg-primary text-primary-foreground shadow-sm"
188+ : "border-transparent text-muted-foreground hover:bg-background/70 hover:text-foreground",
189+ )}
190+ onClick={() => setKind(k)}
191+ >
192+ {k === "choice" ? t("questions.kind.choice") : t("questions.kind.text")}
193+ </button>
194+ )}
195+ </For>
196+ <Select id="question-kind" value={kind()} class="sr-only" onChange={(e) => setKind(e.currentTarget.value as QuestionKind)}>
144 <For each={QUESTION_KINDS}>197 <For each={QUESTION_KINDS}>
145 {(k) => <option value={k}>{k === "choice" ? t("questions.kind.choice") : t("questions.kind.text")}</option>}198 {(k) => <option value={k}>{k === "choice" ? t("questions.kind.choice") : t("questions.kind.text")}</option>}
146 </For>199 </For>
@@ -154,6 +207,7 @@ export function QuestionForm(props: {
154 min={1}207 min={1}
155 max={100}208 max={100}
156 value={points()}209 value={points()}
210+ class="h-10"
157 required211 required
158 onInput={(e) => setPoints(e.currentTarget.value)}212 onInput={(e) => setPoints(e.currentTarget.value)}
159 />213 />
@@ -210,11 +264,31 @@ export function QuestionForm(props: {
210 placeholder={t("questions.choicePlaceholder", { index: String.fromCharCode(65 + index) })}264 placeholder={t("questions.choicePlaceholder", { index: String.fromCharCode(65 + index) })}
211 onInput={(e) => setChoice(index, e.currentTarget.value)}265 onInput={(e) => setChoice(index, e.currentTarget.value)}
212 />266 />
267+ <Show when={props.initial?.choice_images?.[index]}>
268+ <img
269+ src={`/api/exams/${props.initial!.exam}/questions/${props.initial!.id}/choices/${index}/image`}
270+ alt={t("questions.choiceImage")}
271+ class="mt-2 max-h-32 rounded-md border object-contain"
272+ />
273+ </Show>
274+ <div class="mt-2">
275+ <Label for={`choice-image-${index}`} class="text-xs font-semibold text-muted-foreground">{t("questions.choiceImage")}</Label>
276+ <input
277+ id={`choice-image-${index}`}
278+ type="file"
279+ accept="image/png,image/jpeg,image/webp,image/gif"
280+ class="sr-only"
281+ onChange={(event) => setChoiceImage(index, event.currentTarget.files?.[0] ?? null)}
282+ />
283+ <label for={`choice-image-${index}`} class="mt-1 flex cursor-pointer items-center gap-2 rounded-md border border-dashed bg-muted/30 px-3 py-2 text-xs font-medium text-muted-foreground transition-colors hover:bg-muted/60 hover:text-foreground">
284+ <IconFileImage class="h-4 w-4" />
285+ <span class="truncate">{choiceImages()[index]?.name ?? t("common.createItem", { item: t("questions.choiceImage") })}</span>
286+ </label>
287+ </div>
213 </div>288 </div>
214 )}289 )}
215 </Index>290 </Index>
216 </div>291 </div>
217- <p class="text-xs text-muted-foreground">{t("questions.choicesHint")}</p>
218 </div>292 </div>
219 </Show>293 </Show>
220 {error() && <p class="text-sm text-destructive">{error()}</p>}294 {error() && <p class="text-sm text-destructive">{error()}</p>}