forge
Explore
Log in

Don't you dare go Hollow

🖼️ let question and solution images be replaced or removed

Browse files at this commit

f923bbf2c8181c94b51aa60a53ce2f40fe81eb51Burak BoduroğluParent: 7f602db
  • feat
    • 🖼️ let question and solution images be replaced or removed
Show full message
feat: 🖼️ let question and solution images be replaced or removed
- add the two endpoints the API layer never covered, DELETE
  /questions/{id}/image and DELETE /questions/{id}/solutions/{sid}/image,
  and export the upload calls that were buried inside postQuestion and
  postSolution so an existing record can be re-imaged
- editing a solution silently discarded the picked image and offered no
  way to drop the stored one: patchSolutionById only ever sent the body.
  The dialog now shows the current attachment with a remove control, and
  a newly picked file replaces it server-side
- the question bank could attach pictures but never delete them, leaving
  deleteBankQuestionImage and deleteBankChoiceImage unused. The detail
  page gets remove controls for the question image and each choice
  image, behind the same owner/admin gate as every other edit
src/api/__tests__/questions/questions.test.tsmodified+23 -1
@@ -1,5 +1,5 @@
11 import { afterEach, describe, expect, it, vi } from "vitest";
2-import { getQuestions, getQuestionById, postQuestion, postQuestionApprove, deleteQuestionById, getQuestionImageUrl, getQuestionImageBlob } from "../../shared";
2+import { getQuestions, getQuestionById, postQuestion, postQuestionApprove, deleteQuestionById, getQuestionImageUrl, getQuestionImageBlob, postQuestionImage, deleteQuestionImage } from "../../shared";
33 import { lastFetchCall, mockFetch204, mockFetchBlob, mockFetchSuccess } from "../helpers/mock-fetch";
44
55 describe("questions API", () => {
@@ -82,4 +82,26 @@ describe("questions API", () => {
8282 const [url] = lastFetchCall();
8383 expect(url).toBe(getQuestionImageUrl("q1"));
8484 });
85+
86+ it("postQuestionImage uploads multipart to /questions/:id/image", async () => {
87+ mockFetch204();
88+
89+ await postQuestionImage("q1", new File(["x"], "sketch.png", { type: "image/png" }));
90+
91+ const [url, init] = lastFetchCall();
92+ expect(url).toBe("/api/questions/q1/image");
93+ expect(init?.method).toBe("POST");
94+ expect(init?.body).toBeInstanceOf(FormData);
95+ expect((init?.body as FormData).get("file")).toBeInstanceOf(File);
96+ });
97+
98+ it("deleteQuestionImage calls /questions/:id/image", async () => {
99+ mockFetch204();
100+
101+ await deleteQuestionImage("q1");
102+
103+ const [url, init] = lastFetchCall();
104+ expect(url).toBe("/api/questions/q1/image");
105+ expect(init?.method).toBe("DELETE");
106+ });
85107 });
src/api/__tests__/questions/solutions.test.tsmodified+23 -1
@@ -1,5 +1,5 @@
11 import { afterEach, describe, expect, it, vi } from "vitest";
2-import { getSolutions, postSolution, patchSolutionById, deleteSolutionById, getSolutionImageUrl, getSolutionImageBlob } from "../../shared";
2+import { getSolutions, postSolution, patchSolutionById, deleteSolutionById, getSolutionImageUrl, getSolutionImageBlob, postSolutionImage, deleteSolutionImage } from "../../shared";
33 import { lastFetchCall, mockFetch204, mockFetchBlob, mockFetchSuccess } from "../helpers/mock-fetch";
44
55 describe("solutions API", () => {
@@ -71,4 +71,26 @@ describe("solutions API", () => {
7171 const [url] = lastFetchCall();
7272 expect(url).toBe(getSolutionImageUrl("q1", "s1"));
7373 });
74+
75+ it("postSolutionImage uploads multipart to /questions/:id/solutions/:sid/image", async () => {
76+ mockFetch204();
77+
78+ await postSolutionImage("q1", "s1", new File(["x"], "work.png", { type: "image/png" }));
79+
80+ const [url, init] = lastFetchCall();
81+ expect(url).toBe("/api/questions/q1/solutions/s1/image");
82+ expect(init?.method).toBe("POST");
83+ expect(init?.body).toBeInstanceOf(FormData);
84+ expect((init?.body as FormData).get("file")).toBeInstanceOf(File);
85+ });
86+
87+ it("deleteSolutionImage calls /questions/:id/solutions/:sid/image", async () => {
88+ mockFetch204();
89+
90+ await deleteSolutionImage("q1", "s1");
91+
92+ const [url, init] = lastFetchCall();
93+ expect(url).toBe("/api/questions/q1/solutions/s1/image");
94+ expect(init?.method).toBe("DELETE");
95+ });
7496 });
src/api/shared/questions.tsmodified+14 -5
@@ -50,15 +50,24 @@ export async function postQuestion(body: AskQuestion, image?: File): Promise<Poo
5050 body,
5151 });
5252
53- if (image) {
54- const fd = new FormData();
55- fd.append("file", image);
56- await formClient(`/questions/${res.id}/image`, fd);
57- }
53+ if (image) await postQuestionImage(res.id, image);
5854
5955 return res;
6056 }
6157
58+/** Attaches or replaces the question's single illustration. */
59+export async function postQuestionImage(id: string, image: File): Promise<void> {
60+ const fd = new FormData();
61+ fd.append("file", image);
62+ await formClient(`/questions/${id}/image`, fd);
63+}
64+
65+export async function deleteQuestionImage(id: string): Promise<void> {
66+ return client(`/questions/${id}/image`, {
67+ method: "DELETE",
68+ });
69+}
70+
6271 export async function postQuestionApprove(id: string): Promise<PoolQuestionResponse> {
6372 return client(`/questions/${id}/approve`, {
6473 method: "POST",
src/api/shared/solutions.tsmodified+14 -5
@@ -41,15 +41,24 @@ export async function postSolution(
4141 body,
4242 });
4343
44- if (image) {
45- const fd = new FormData();
46- fd.append("file", image);
47- await formClient(`/questions/${id}/solutions/${res.id}/image`, fd);
48- }
44+ if (image) await postSolutionImage(id, res.id, image);
4945
5046 return res;
5147 }
5248
49+/** Attaches or replaces the solution's single attachment. */
50+export async function postSolutionImage(id: string, sid: string, image: File): Promise<void> {
51+ const fd = new FormData();
52+ fd.append("file", image);
53+ await formClient(`/questions/${id}/solutions/${sid}/image`, fd);
54+}
55+
56+export async function deleteSolutionImage(id: string, sid: string): Promise<void> {
57+ return client(`/questions/${id}/solutions/${sid}/image`, {
58+ method: "DELETE",
59+ });
60+}
61+
5362 export async function patchSolutionById(
5463 id: string,
5564 sid: string,
src/pages/bank-question-detail-page.tsxmodified+54 -6
@@ -1,6 +1,11 @@
11 import { Link, useLocation, useNavigate, useParams } from "@tanstack/solid-router";
22 import { For, Show, Suspense, createMemo, createResource, createSignal } from "solid-js";
3-import { deleteBankQuestionById, getBankQuestionById } from "@/api/bank-questions";
3+import {
4+ deleteBankChoiceImage,
5+ deleteBankQuestionById,
6+ deleteBankQuestionImage,
7+ getBankQuestionById,
8+} from "@/api/bank-questions";
49 import { getCourses } from "@/api/courses";
510 import { formatApiError } from "@/api/client";
611 import { BankQuestionForm } from "@/components/exams/bank-question-form";
@@ -55,6 +60,23 @@ function BankQuestionDetailContent() {
5560 const [error, setError] = createSignal("");
5661 const canEdit = () => question()?.owner === auth.user()?.id || hasMinRole(auth.user()?.role, "admin");
5762
63+ // The form can attach a picture but never drop one, so removal lives here
64+ // beside the image it deletes — same owner/admin gate as every other edit.
65+ const [imagePending, setImagePending] = createSignal("");
66+ const removeImage = async (key: string, remove: () => Promise<void>) => {
67+ if (imagePending()) return;
68+ setError("");
69+ setImagePending(key);
70+ try {
71+ await remove();
72+ await refetch();
73+ } catch (err) {
74+ setError(formatApiError(err));
75+ } finally {
76+ setImagePending("");
77+ }
78+ };
79+
5880 return (
5981 <Suspense fallback={<PageSpinner />}>
6082 <Show
@@ -109,11 +131,25 @@ function BankQuestionDetailContent() {
109131 </div>
110132
111133 <Show when={current().image}>
112- <img
113- src={`/api/bank-questions/${current().id}/image`}
114- alt={t("questions.image")}
115- class="max-h-80 rounded-lg border object-contain"
116- />
134+ <div class="space-y-2">
135+ <img
136+ src={`/api/bank-questions/${current().id}/image`}
137+ alt={t("questions.image")}
138+ class="max-h-80 rounded-lg border object-contain"
139+ />
140+ <Show when={canEdit()}>
141+ <Button
142+ variant="outline"
143+ size="sm"
144+ class="text-destructive hover:text-destructive"
145+ disabled={imagePending() === "question"}
146+ onClick={() => void removeImage("question", () => deleteBankQuestionImage(current().id))}
147+ >
148+ <IconTrash class="h-4 w-4" />
149+ {t("common.remove")}
150+ </Button>
151+ </Show>
152+ </div>
117153 </Show>
118154
119155 <Show when={current().choices?.length}>
@@ -130,6 +166,18 @@ function BankQuestionDetailContent() {
130166 alt=""
131167 class="h-12 w-12 rounded-md border object-cover"
132168 />
169+ <Show when={canEdit()}>
170+ <Button
171+ variant="ghost"
172+ size="icon"
173+ class="h-8 w-8 text-destructive hover:bg-destructive/10"
174+ aria-label={t("common.remove")}
175+ disabled={imagePending() === choice.id}
176+ onClick={() => void removeImage(choice.id, () => deleteBankChoiceImage(current().id, choice.id))}
177+ >
178+ <IconTrash class="h-4 w-4" />
179+ </Button>
180+ </Show>
133181 </Show>
134182 </div>
135183 )}
src/pages/question-detail-page.tsxmodified+36 -6
@@ -1,7 +1,7 @@
11 import { For, Show, Suspense, createResource, createSignal, lazy } from "solid-js";
22 import { useParams, useRouter } from "@tanstack/solid-router";
33 import { getQuestionById, deleteQuestionById, postQuestionApprove, getQuestionImageUrl, getQuestionImageBlob } from "@/api/shared";
4-import { getSolutions, postSolution, patchSolutionById, deleteSolutionById, getSolutionImageUrl, getSolutionImageBlob } from "@/api/shared";
4+import { getSolutions, postSolution, patchSolutionById, deleteSolutionById, getSolutionImageUrl, getSolutionImageBlob, postSolutionImage, deleteSolutionImage } from "@/api/shared";
55 import { getSettings } from "@/api/settings";
66 import type { SolutionResponse } from "@/api/shared";
77 import { formatApiError } from "@/api/client";
@@ -254,7 +254,10 @@ function SolutionFormDialog(props: { questionId: string; initialData?: SolutionR
254254 const [error, setError] = createSignal("");
255255 const [body, setBody] = createSignal(props.initialData?.body || "");
256256 const [file, setFile] = createSignal<File | null>(null);
257+ const [removeImage, setRemoveImage] = createSignal(false);
257258 const [drawing, setDrawing] = createSignal(false);
259+ /** The already-uploaded attachment, until it is dropped or superseded. */
260+ const keptImage = () => Boolean(props.initialData?.image) && !removeImage() && !file();
258261 const [settings] = createResource(async () => {
259262 try {
260263 return await getSettings();
@@ -283,7 +286,13 @@ function SolutionFormDialog(props: { questionId: string; initialData?: SolutionR
283286 setError("");
284287 try {
285288 if (props.initialData) {
286- await patchSolutionById(props.questionId, props.initialData.id, { body: body().trim() });
289+ const solutionId = props.initialData.id;
290+ await patchSolutionById(props.questionId, solutionId, { body: body().trim() });
291+ // A re-upload replaces the stored image, so only an untouched picker
292+ // with the remove flag set needs the explicit DELETE.
293+ const picked = file();
294+ if (picked) await postSolutionImage(props.questionId, solutionId, picked);
295+ else if (removeImage()) await deleteSolutionImage(props.questionId, solutionId);
287296 } else {
288297 await postSolution(props.questionId, { body: body().trim() }, file() || undefined);
289298 }
@@ -301,9 +310,31 @@ function SolutionFormDialog(props: { questionId: string; initialData?: SolutionR
301310 <Label for="s-body">{t("pool.body")}</Label>
302311 <Textarea id="s-body" value={body()} onInput={(e) => setBody(e.currentTarget.value)} required rows={5} />
303312 </div>
304- <Show when={!props.initialData}>
305- <div class="space-y-2">
313+ <div class="space-y-2">
306314 <Label>{t("pool.image")}</Label>
315+ {/* Editing keeps the attachment editable too: the backend replaces
316+ the image on re-upload and drops it on DELETE, so the form must
317+ offer both rather than silently keeping whatever was there. */}
318+ <Show when={keptImage()}>
319+ <div class="flex items-center gap-3 rounded-lg border border-border p-2">
320+ <ReplayableImage
321+ fetchBlob={() => getSolutionImageBlob(props.questionId, props.initialData!.id)}
322+ src={getSolutionImageUrl(props.questionId, props.initialData!.id)}
323+ alt=""
324+ imgClass="max-h-20 w-auto rounded object-contain"
325+ />
326+ <Button
327+ type="button"
328+ variant="ghost"
329+ size="sm"
330+ class="ml-auto text-destructive hover:bg-destructive/10"
331+ onClick={() => setRemoveImage(true)}
332+ >
333+ <IconX class="mr-1 h-4 w-4" />
334+ {t("common.remove")}
335+ </Button>
336+ </div>
337+ </Show>
307338 <div class="relative flex flex-col items-center justify-center rounded-lg border-2 border-dashed border-border p-6 transition-colors hover:bg-muted/50 focus-within:ring-2 focus-within:ring-primary focus-within:ring-offset-2">
308339 <Show
309340 when={!file()}
@@ -362,8 +393,7 @@ function SolutionFormDialog(props: { questionId: string; initialData?: SolutionR
362393 />
363394 </Suspense>
364395 </Show>
365- </div>
366- </Show>
396+ </div>
367397 <div class="flex justify-end gap-3 pt-4">
368398 <Button type="button" variant="outline" onClick={props.onClose}>
369399 {t("common.cancel")}