diff --git a/bun.lock b/bun.lock index f756e61..57bfb3c 100644 --- a/bun.lock +++ b/bun.lock @@ -18,6 +18,7 @@ "@tailwindcss/postcss": "^4.3.3", "@tanstack/solid-router-devtools": "^1.167.0", "@types/node": "^26.1.1", + "fast-check": "^4.9.0", "postcss": "^8.5.22", "tailwindcss": "^4.3.3", "tailwindcss-animate": "^1.0.7", @@ -447,6 +448,8 @@ "expect-type": ["expect-type@1.4.0", "", {}, "sha512-KfYbmpRm0VbLjEvVa9yGwCi9GI34xvi7A/HXYWQO65CSD2u3MczUJSuwXKFIxlGsgBQizV9q5J9NHj4VG0n+pA=="], + "fast-check": ["fast-check@4.9.0", "", { "dependencies": { "pure-rand": "^8.0.0" } }, "sha512-7ms6T7SybUev/PQITciI0yLM2pOSFy5zpG8Ty7tQofcVaQUvrMXp6CBwqF6fThLCLOrfBtuHAtwq6Yu4XPCllg=="], + "fdir": ["fdir@6.5.0", "", { "peerDependencies": { "picomatch": "^3 || ^4" } }, "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg=="], "fsevents": ["fsevents@2.3.3", "", { "os": "darwin" }, "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw=="], @@ -521,6 +524,8 @@ "postcss": ["postcss@8.5.22", "", { "dependencies": { "nanoid": "^3.3.16", "picocolors": "^1.1.1", "source-map-js": "^1.2.1" } }, "sha512-KBDEIpLrvpv16pp3K0Fw+UCoZfopFjjgeB+0tA/aaThfEE74kKDLrgg603YvOWJyg3+WYtyq3xYsQWsIyZlPqQ=="], + "pure-rand": ["pure-rand@8.4.2", "", {}, "sha512-vvuOGgcuPJAirlHvuQw1TrOiw7ptaIXXmIbNuiNOY6lNGJJH49PQ1Kj4nd783nPdQhQdicgOjVI2yI/9BD6/Ng=="], + "rolldown": ["rolldown@1.1.5", "", { "dependencies": { "@oxc-project/types": "=0.139.0", "@rolldown/pluginutils": "^1.0.0" }, "optionalDependencies": { "@rolldown/binding-android-arm64": "1.1.5", "@rolldown/binding-darwin-arm64": "1.1.5", "@rolldown/binding-darwin-x64": "1.1.5", "@rolldown/binding-freebsd-x64": "1.1.5", "@rolldown/binding-linux-arm-gnueabihf": "1.1.5", "@rolldown/binding-linux-arm64-gnu": "1.1.5", "@rolldown/binding-linux-arm64-musl": "1.1.5", "@rolldown/binding-linux-ppc64-gnu": "1.1.5", "@rolldown/binding-linux-s390x-gnu": "1.1.5", "@rolldown/binding-linux-x64-gnu": "1.1.5", "@rolldown/binding-linux-x64-musl": "1.1.5", "@rolldown/binding-openharmony-arm64": "1.1.5", "@rolldown/binding-wasm32-wasi": "1.1.5", "@rolldown/binding-win32-arm64-msvc": "1.1.5", "@rolldown/binding-win32-x64-msvc": "1.1.5" }, "bin": { "rolldown": "./bin/cli.mjs" } }, "sha512-t9z29cJjXf/vxQ8dyhCSpt6H6aSwHTk8cT5I3iy6SMXuFpk5mB6PL6XfC8PCwrPTx93udwKUm9HRteAlTGBLiA=="], "rollup": ["rollup@4.62.2", "", { "dependencies": { "@types/estree": "1.0.9" }, "optionalDependencies": { "@rollup/rollup-android-arm-eabi": "4.62.2", "@rollup/rollup-android-arm64": "4.62.2", "@rollup/rollup-darwin-arm64": "4.62.2", "@rollup/rollup-darwin-x64": "4.62.2", "@rollup/rollup-freebsd-arm64": "4.62.2", "@rollup/rollup-freebsd-x64": "4.62.2", "@rollup/rollup-linux-arm-gnueabihf": "4.62.2", "@rollup/rollup-linux-arm-musleabihf": "4.62.2", "@rollup/rollup-linux-arm64-gnu": "4.62.2", "@rollup/rollup-linux-arm64-musl": "4.62.2", "@rollup/rollup-linux-loong64-gnu": "4.62.2", "@rollup/rollup-linux-loong64-musl": "4.62.2", "@rollup/rollup-linux-ppc64-gnu": "4.62.2", "@rollup/rollup-linux-ppc64-musl": "4.62.2", "@rollup/rollup-linux-riscv64-gnu": "4.62.2", "@rollup/rollup-linux-riscv64-musl": "4.62.2", "@rollup/rollup-linux-s390x-gnu": "4.62.2", "@rollup/rollup-linux-x64-gnu": "4.62.2", "@rollup/rollup-linux-x64-musl": "4.62.2", "@rollup/rollup-openbsd-x64": "4.62.2", "@rollup/rollup-openharmony-arm64": "4.62.2", "@rollup/rollup-win32-arm64-msvc": "4.62.2", "@rollup/rollup-win32-ia32-msvc": "4.62.2", "@rollup/rollup-win32-x64-gnu": "4.62.2", "@rollup/rollup-win32-x64-msvc": "4.62.2", "fsevents": "~2.3.2" }, "bin": "dist/bin/rollup" }, "sha512-RFnrW4lhXA3s3eqHDZvN654g8OTjzRfqpIRJYczCGB6HzphckVAi/Qh4tbPUbRuDi7s1Llv8g/NspLkttY3gTA=="], diff --git a/history.txt b/history.txt new file mode 100644 index 0000000..31e39ef --- /dev/null +++ b/history.txt @@ -0,0 +1,5 @@ +#V2 +DELETE subject:`01KYB0E968ZHJ7CRP1TXXZDHT1`; DELETE user:`01KYB0E963KQ4NRX8AHVQ7795J`; +SELECT VALUE [path, sha256] FROM meta; +REMOVE TABLE IF EXISTS doc; +REMOVE TABLE IF EXISTS meta; diff --git a/package.json b/package.json index 1cde1cf..cf9ca7b 100644 --- a/package.json +++ b/package.json @@ -9,7 +9,8 @@ "preview": "vite preview", "check": "tsc --noEmit", "test": "vitest run", - "test:watch": "vitest" + "test:watch": "vitest", + "test:contract": "vitest run --config vitest.contract.config.ts" }, "dependencies": { "@kobalte/core": "^0.13.12", @@ -25,6 +26,7 @@ "@tailwindcss/postcss": "^4.3.3", "@tanstack/solid-router-devtools": "^1.167.0", "@types/node": "^26.1.1", + "fast-check": "^4.9.0", "postcss": "^8.5.22", "tailwindcss": "^4.3.3", "tailwindcss-animate": "^1.0.7", diff --git a/src/api/__tests__/bank-questions/bank-questions.test.ts b/src/api/__tests__/bank-questions/bank-questions.test.ts index 5d76ac8..0e41c62 100644 --- a/src/api/__tests__/bank-questions/bank-questions.test.ts +++ b/src/api/__tests__/bank-questions/bank-questions.test.ts @@ -45,13 +45,40 @@ describe("bank-questions API", () => { expect(init?.method).toBe("GET"); }); - it("getBankQuestions passes subject, owner and page params", async () => { + it("getBankQuestions carries used_count, the list-only copy tally", async () => { + // How many exam questions were copied out of each template — joined for the + // whole page by the backend. An untouched template is 0, and the UI stays + // quiet on 0 rather than printing it. + const mockPage = { + items: [ + { id: "b1", text: "reused", used_count: 3 }, + { id: "b2", text: "never used", used_count: 0 }, + ], + total: 2, + }; + mockFetchSuccess(mockPage); + + const result = await getBankQuestions(); + expect(result.items[0].used_count).toBe(3); + expect(result.items[1].used_count).toBe(0); + }); + + it("getBankQuestions passes subject, owner, q and page params", async () => { + mockFetchSuccess({ items: [], total: 0 }); + + await getBankQuestions({ subject: "sub1", owner: "me", q: "newton", limit: 20, offset: 40 }); + + const [url] = lastFetchCall(); + expect(url).toBe("/api/bank-questions?subject=sub1&owner=me&q=newton&limit=20&offset=40"); + }); + + it("getBankQuestions sends the visibility filter server-side, with paging", async () => { mockFetchSuccess({ items: [], total: 0 }); - await getBankQuestions({ subject: "sub1", owner: "me", limit: 20, offset: 40 }); + await getBankQuestions({ visibility: "private", limit: 12, offset: 12 }); const [url] = lastFetchCall(); - expect(url).toBe("/api/bank-questions?subject=sub1&owner=me&limit=20&offset=40"); + expect(url).toBe("/api/bank-questions?visibility=private&limit=12&offset=12"); }); it("getBankQuestionById calls /bank-questions/:bid", async () => { @@ -90,6 +117,18 @@ describe("bank-questions API", () => { expect(init?.method).toBe("DELETE"); }); + it("patchBankQuestionById serializes a visibility change", async () => { + mockFetchSuccess({ id: "b1", visibility: "school" }); + + const result = await patchBankQuestionById("b1", { visibility: "school" }); + expect(result.visibility).toBe("school"); + + const [url, init] = lastFetchCall(); + expect(url).toBe("/api/bank-questions/b1"); + expect(init?.method).toBe("PATCH"); + expect(init?.body).toBe(JSON.stringify({ visibility: "school" })); + }); + it("postBankQuestionImage calls /bank-questions/:bid/image with FormData", async () => { const mockMeta = { content_type: "image/png", size: 100 }; mockFetchSuccess(mockMeta, 201); @@ -125,37 +164,37 @@ describe("bank-questions API", () => { expect(init?.method).toBe("DELETE"); }); - it("postBankChoiceImage calls /bank-questions/:bid/choices/:index/image with FormData", async () => { + it("postBankChoiceImage calls /bank-questions/:bid/choices/:choiceId/image with FormData", async () => { const mockMeta = { content_type: "image/png", size: 100 }; mockFetchSuccess(mockMeta, 201); const file = new File(["test"], "test.png", { type: "image/png" }); - const result = await postBankChoiceImage("b1", 2, file); + const result = await postBankChoiceImage("b1", "c2", file); expect(result).toEqual(mockMeta); const [url, init] = lastFetchCall(); - expect(url).toBe("/api/bank-questions/b1/choices/2/image"); + expect(url).toBe("/api/bank-questions/b1/choices/c2/image"); expect(init?.method).toBe("POST"); expect(init?.body).toBeInstanceOf(FormData); }); - it("getBankChoiceImageBlob calls /bank-questions/:bid/choices/:index/image", async () => { + it("getBankChoiceImageBlob calls /bank-questions/:bid/choices/:choiceId/image", async () => { mockFetchBlob(new Blob(["img"], { type: "image/png" })); - const result = await getBankChoiceImageBlob("b1", 2); + const result = await getBankChoiceImageBlob("b1", "c2"); expect(result).toBeInstanceOf(Blob); const [url] = lastFetchCall(); - expect(url).toBe("/api/bank-questions/b1/choices/2/image"); + expect(url).toBe("/api/bank-questions/b1/choices/c2/image"); }); - it("deleteBankChoiceImage calls /bank-questions/:bid/choices/:index/image", async () => { + it("deleteBankChoiceImage calls /bank-questions/:bid/choices/:choiceId/image", async () => { mockFetch204(); - await deleteBankChoiceImage("b1", 2); + await deleteBankChoiceImage("b1", "c2"); const [url, init] = lastFetchCall(); - expect(url).toBe("/api/bank-questions/b1/choices/2/image"); + expect(url).toBe("/api/bank-questions/b1/choices/c2/image"); expect(init?.method).toBe("DELETE"); }); }); diff --git a/src/api/__tests__/contract/bank-questions.contract.test.ts b/src/api/__tests__/contract/bank-questions.contract.test.ts new file mode 100644 index 0000000..a480d67 --- /dev/null +++ b/src/api/__tests__/contract/bank-questions.contract.test.ts @@ -0,0 +1,276 @@ +import { api, contractBaseUrl, isLive, json, loginAdmin, pngFile, SKIP_MESSAGE } from "./helpers/live-client"; +import type { BankQuestion, Course, ExamQuestion, Subject } from "@/api/client"; + +if (!isLive) console.warn(SKIP_MESSAGE); + +describe.skipIf(!isLive)(`bank-questions contract @ ${contractBaseUrl}`, () => { + let courseId = ""; + let subjectId = ""; + let questionId = ""; + + beforeAll(async () => { + await loginAdmin(); + const course = await json("/courses", { + method: "POST", + body: { title: `contract-${Date.now()}` }, + }); + courseId = course.id; + const subject = await json(`/courses/${courseId}/subjects`, { + method: "POST", + body: { name: "contract subject" }, + }); + subjectId = subject.id; + }); + + /** Templates created by the paging/search tests, torn down with the course. */ + const scratchIds: string[] = []; + + afterAll(async () => { + for (const id of scratchIds) await api(`/bank-questions/${id}`, { method: "DELETE" }); + if (questionId) await api(`/bank-questions/${questionId}`, { method: "DELETE" }); + if (courseId) await api(`/courses/${courseId}`, { method: "DELETE" }); + }); + + const createTemplate = async (text: string) => { + const created = await json("/bank-questions", { + method: "POST", + body: { subject_id: subjectId, text, kind: "text", points: 1 }, + }); + scratchIds.push(created.id); + return created; + }; + + it("GET /bank-questions answers the {items,total,limit,offset} envelope", async () => { + const page = await json>("/bank-questions?limit=5"); + expect(Array.isArray(page.items)).toBe(true); + expect(typeof page.total).toBe("number"); + expect(typeof page.limit).toBe("number"); + expect(typeof page.offset).toBe("number"); + }); + + it("a trailing slash on the nest-root route 404s", async () => { + const res = await api("/bank-questions/"); + expect(res.status).toBe(404); + }); + + it("creates a choice template, minting an id per choice and resolving correct by key", async () => { + const created = await json("/bank-questions", { + method: "POST", + body: { + subject_id: subjectId, + text: "contract: which one?", + kind: "choice", + points: 1, + // Client-local keys: the server replaces them, but `correct` may name one. + choices: [{ id: "new:1", text: "A" }, { id: "new:2", text: "B" }], + correct: "new:2", + }, + }); + questionId = created.id; + expect(created).toMatchObject({ subject: subjectId, kind: "choice", points: 1 }); + expect(created.choices?.map((choice) => choice.text)).toEqual(["A", "B"]); + for (const choice of created.choices ?? []) expect(typeof choice.id).toBe("string"); + // Server-minted, so not the key we sent — and it still names the row we marked. + expect(created.correct).toBe(created.choices?.[1].id); + expect(created.correct).not.toBe("new:2"); + expect(typeof created.owner).toBe("string"); + expect(typeof created.created_at).toBe("number"); + }); + + it("rejects a duplicate choice key and a correct that names nothing submitted", async () => { + const dupe = await api("/bank-questions", { + method: "POST", + body: { + subject_id: subjectId, + text: "contract: dupe", + kind: "choice", + points: 1, + choices: [{ id: "k", text: "A" }, { id: "k", text: "B" }], + correct: "k", + }, + }); + expect(dupe.status).toBe(400); + + const stray = await api("/bank-questions", { + method: "POST", + body: { + subject_id: subjectId, + text: "contract: stray correct", + kind: "choice", + points: 1, + choices: [{ id: "a", text: "A" }, { id: "b", text: "B" }], + correct: "zzz", + }, + }); + expect(stray.status).toBe(400); + }); + + it("stores per-option images keyed by choice id and reports them in choice_images", async () => { + const question = await json(`/bank-questions/${questionId}`); + for (const choice of question.choices ?? []) { + const body = new FormData(); + body.append("file", pngFile(`choice-${choice.id}.png`)); + const res = await api(`/bank-questions/${questionId}/choices/${choice.id}/image`, { + method: "POST", + body, + }); + expect(res.status).toBe(201); + } + const fetched = await json(`/bank-questions/${questionId}`); + expect(fetched.choice_images?.[0]).toBeTruthy(); + expect(fetched.choice_images?.[1]).toBeTruthy(); + }); + + it("PATCH without a choices key keeps the per-option images", async () => { + const patched = await json(`/bank-questions/${questionId}`, { + method: "PATCH", + body: { text: "contract: still which one?" }, + }); + expect(patched.choice_images?.[0]).toBeTruthy(); + expect(patched.choice_images?.[1]).toBeTruthy(); + }); + + // The whole point of the remodel: resubmitting the choices WITH their ids is no + // longer a wipe, so the client needs no download-then-reupload compensation. + it("PATCH resubmitting the stored ids keeps every image and the answer key", async () => { + const before = await json(`/bank-questions/${questionId}`); + const ids = (before.choices ?? []).map((choice) => choice.id); + const patched = await json(`/bank-questions/${questionId}`, { + method: "PATCH", + body: { + choices: [{ id: ids[0], text: "A" }, { id: ids[1], text: "B renamed" }], + correct: ids[1], + }, + }); + expect(patched.choices?.map((choice) => choice.id)).toEqual(ids); + expect(patched.correct).toBe(ids[1]); + expect(patched.choice_images?.[0]).toBeTruthy(); + expect(patched.choice_images?.[1]).toBeTruthy(); + const blob = await api(`/bank-questions/${questionId}/choices/${ids[0]}/image`); + expect(blob.status).toBe(200); + }); + + // Dropping option A: only A's picture goes, B keeps its own and stays markable. + it("PATCH replacing one option drops that option's image only", async () => { + const before = await json(`/bank-questions/${questionId}`); + const kept = before.choices![1]; + const patched = await json(`/bank-questions/${questionId}`, { + method: "PATCH", + body: { + choices: [{ id: "new:9", text: "A replaced" }, { id: kept.id, text: kept.text }], + correct: kept.id, + }, + }); + expect(patched.choices?.[1].id).toBe(kept.id); + expect(patched.choices?.[0].id).not.toBe(before.choices![0].id); + expect(patched.choice_images?.[0]).toBeNull(); + expect(patched.choice_images?.[1]).toBeTruthy(); + expect(patched.correct).toBe(kept.id); + + // 400, not 404: the id no longer names a choice of this question, so the + // route rejects it before it ever looks for a blob. + const gone = await api(`/bank-questions/${questionId}/choices/${before.choices![0].id}/image`); + expect(gone.ok).toBe(false); + expect(gone.status).toBe(400); + }); + + // The app is EN/TR: `İ` lowercases to `i` + U+0307 in both Rust and + // SurrealQL, so an unfolded server search made `istanbul` and `İSTANBUL` two + // disjoint queries and a Turkish teacher typing lowercase got an empty bank. + it("?q= folds Turkish casing and diacritics in both directions", async () => { + const tag = `tr${Date.now()}`; + await createTemplate(`${tag} İSTANBUL kaç ilçedir?`); + await createTemplate(`${tag} istanbul boğazı nerededir?`); + + for (const needle of ["istanbul", "İSTANBUL", "ıstanbul", "ISTANBUL"]) { + const page = await json<{ total: number; items: BankQuestion[] }>( + `/bank-questions?q=${encodeURIComponent(`${tag} ${needle}`)}`, + ); + expect(page.total, `needle ${needle}`).toBe(2); + expect(page.items).toHaveLength(2); + } + for (const needle of ["ilce", "ilçe", "bogaz", "boğaz"]) { + const page = await json<{ total: number }>( + `/bank-questions?q=${encodeURIComponent(needle)}&subject=${subjectId}`, + ); + expect(page.total, `needle ${needle}`).toBe(1); + } + const miss = await json<{ total: number }>(`/bank-questions?q=${tag}-ankara`); + expect(miss.total).toBe(0); + }); + + // Regression for the whole-table-then-slice list: template #101 onward was + // unreachable, and `total` counted the page instead of the matches. + it("pages past 100 with an honest total and joined-on names", async () => { + const tag = `pg${Date.now()}`; + for (let i = 0; i < 105; i++) await createTemplate(`${tag} ${String(i).padStart(3, "0")}`); + + type Page = { total: number; items: BankQuestion[]; limit: number; offset: number }; + const first = await json(`/bank-questions?subject=${subjectId}&q=${tag}&limit=100`); + expect(first.total).toBe(105); + expect(first.items).toHaveLength(100); + // Newest first, and the names are joined on server-side. + expect(first.items[0].text).toBe(`${tag} 104`); + expect(first.items[0].subject_name).toBe("contract subject"); + expect(typeof first.items[0].owner_name).toBe("string"); + + const second = await json( + `/bank-questions?subject=${subjectId}&q=${tag}&limit=100&offset=100`, + ); + expect(second.total).toBe(105); + expect(second.items).toHaveLength(5); + expect(second.items[4].text).toBe(`${tag} 000`); + }); + // Provenance made useful: the list says how many exam questions were copied + // out of a template, and a copy that drifted can be pulled back in line. + it("reports used_count on the list and refreshes a copy from its template", async () => { + const tag = `use${Date.now()}`; + const template = await createTemplate(`${tag} original text`); + const exam = await json<{ id: string }>(`/courses/${courseId}/exams`, { + method: "POST", + body: { title: tag, kind: "final" }, + }); + + const copy = await json( + `/exams/${exam.id}/questions/from-bank/${template.id}`, + { method: "POST", body: { subject_id: subjectId } }, + ); + expect(copy.from_bank).toBe(template.id); + + // One grouped join on the list; the single-template GET stays at 0. + const page = await json<{ items: BankQuestion[] }>(`/bank-questions?q=${tag}`); + expect(page.items.find((item) => item.id === template.id)?.used_count).toBe(1); + const single = await json(`/bank-questions/${template.id}`); + expect(single.used_count).toBe(0); + + // The copy drifts locally, the template is fixed, and the refresh wins. + await json(`/exams/${exam.id}/questions/${copy.id}`, { + method: "PATCH", + body: { text: `${tag} local drift`, points: 9 }, + }); + await json(`/bank-questions/${template.id}`, { + method: "PATCH", + body: { text: `${tag} corrected text`, points: 3 }, + }); + const refreshed = await json( + `/exams/${exam.id}/questions/${copy.id}/refresh-from-bank`, + { method: "POST" }, + ); + expect(refreshed.id).toBe(copy.id); + expect(refreshed.text).toBe(`${tag} corrected text`); + expect(refreshed.points).toBe(3); + expect(refreshed.from_bank).toBe(template.id); + + // A hand-authored question has no template to refresh from: 400, not 404. + const plain = await json(`/exams/${exam.id}/questions`, { + method: "POST", + body: { subject_id: subjectId, text: `${tag} mine`, kind: "text", points: 1 }, + }); + const refused = await api(`/exams/${exam.id}/questions/${plain.id}/refresh-from-bank`, { + method: "POST", + }); + expect(refused.status).toBe(400); + + await api(`/exams/${exam.id}`, { method: "DELETE" }); + }); +}); diff --git a/src/api/__tests__/contract/helpers/live-client.ts b/src/api/__tests__/contract/helpers/live-client.ts new file mode 100644 index 0000000..8244371 --- /dev/null +++ b/src/api/__tests__/contract/helpers/live-client.ts @@ -0,0 +1,82 @@ +/** + * Minimal live-backend client for the contract suite: a cookie jar (fetch keeps + * none of its own in bun/node) plus a hard timeout so a dead port fails fast + * instead of hanging the run. Boot recipe: see vitest.contract.config.ts. + */ +// The app's tsconfig has no node types (browser build), so reach env this way. +const env: Record = + (globalThis as { process?: { env: Record } }).process?.env ?? {}; + +export const contractBaseUrl = (env.CONTRACT_BASE_URL ?? "").replace(/\/+$/, ""); +export const isLive = contractBaseUrl !== ""; + +export const SKIP_MESSAGE = + "[contract] CONTRACT_BASE_URL unset — skipping live contract tests. " + + "Boot a scratch backend (see vitest.contract.config.ts) and re-run with " + + "CONTRACT_BASE_URL=http://127.0.0.1:8081 bun run test:contract"; + +const TIMEOUT_MS = 10_000; +let cookie = ""; + +type Init = { method?: string; body?: unknown; headers?: Record }; + +/** Raw request — returns the Response so tests can assert on status codes. */ +export async function api(path: string, init: Init = {}): Promise { + const headers: Record = { ...init.headers }; + if (cookie) headers.Cookie = cookie; + + let body: BodyInit | undefined; + if (init.body instanceof FormData) { + body = init.body; + } else if (init.body !== undefined) { + headers["Content-Type"] = "application/json"; + body = JSON.stringify(init.body); + } + + const res = await fetch(`${contractBaseUrl}${path}`, { + method: init.method ?? "GET", + headers, + body, + redirect: "manual", + signal: AbortSignal.timeout(TIMEOUT_MS), + }); + + const setCookies = res.headers.getSetCookie?.() ?? []; + for (const raw of setCookies) { + const pair = raw.split(";")[0]; + if (pair.startsWith("session=")) cookie = pair; + } + return res; +} + +/** Request + JSON body, throwing on a non-2xx so setup failures are loud. */ +export async function json(path: string, init: Init = {}): Promise { + const res = await api(path, init); + const text = await res.text(); + if (!res.ok) { + throw new Error(`${init.method ?? "GET"} ${path} → ${res.status} ${text}`); + } + return (text ? JSON.parse(text) : null) as T; +} + +/** Log in as the seeded admin; the session cookie lands in the jar. */ +export async function loginAdmin(): Promise { + await json("/auth/login", { + method: "POST", + body: { + username: env.ADMIN_USERNAME ?? "admin", + password: env.ADMIN_PASSWORD ?? "admin123", + }, + }); +} + +/** Smallest valid 1x1 PNG, for the image-upload steps. */ +export function pngFile(name: string): File { + const bytes = Uint8Array.from( + atob( + "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==", + ), + (c) => c.charCodeAt(0), + ); + return new File([bytes], name, { type: "image/png" }); +} diff --git a/src/api/__tests__/exams/exam-attempts.test.ts b/src/api/__tests__/exams/exam-attempts.test.ts index 18e34db..1ee6564 100644 --- a/src/api/__tests__/exams/exam-attempts.test.ts +++ b/src/api/__tests__/exams/exam-attempts.test.ts @@ -60,10 +60,10 @@ describe("exams API - attempts", () => { }); it("postExamAttemptAnswer calls /exams/:id/attempt/answers with data", async () => { - const mockAnswer = { selected: 1 }; + const mockAnswer = { selected: "c1" }; mockFetchSuccess(mockAnswer); - const data = { question_id: "q1", selected: 1 }; + const data = { question_id: "q1", selected: "c1" }; const result = await postExamAttemptAnswer("ex1", data); expect(result).toEqual(mockAnswer); diff --git a/src/api/__tests__/exams/exam-questions.test.ts b/src/api/__tests__/exams/exam-questions.test.ts index 58d9cd1..86509d6 100644 --- a/src/api/__tests__/exams/exam-questions.test.ts +++ b/src/api/__tests__/exams/exam-questions.test.ts @@ -8,6 +8,7 @@ import { deleteExamQuestionImage } from "../../exams"; import { postExamChoiceImage } from "../../exams"; import { deleteExamChoiceImage } from "../../exams"; import { postExamQuestionFromBank } from "../../exams"; +import { postExamQuestionRefreshFromBank } from "../../exams"; import { postExamQuestionToBank } from "../../exams"; import { lastFetchCall, mockFetch204, mockFetchSuccess } from "../helpers/mock-fetch"; @@ -17,11 +18,15 @@ describe("exams API - questions", () => { }); it("getExamQuestions calls /exams/:id/questions", async () => { - const mockPage = { items: [{ id: "q1" }], total: 1 }; + // Both provenance links ride the list untouched: `from_bank` (added out of + // the bank) and `banked_as` (a template minted by saving this question). + const mockPage = { items: [{ id: "q1", from_bank: "b1", banked_as: "b2" }], total: 1 }; mockFetchSuccess(mockPage); const result = await getExamQuestions("ex1"); expect(result).toEqual({ ...mockPage, limit: null, offset: 0 }); + expect(result.items[0].from_bank).toBe("b1"); + expect(result.items[0].banked_as).toBe("b2"); const [url, init] = lastFetchCall(); expect(url).toBe("/api/exams/ex1/questions"); @@ -90,36 +95,40 @@ describe("exams API - questions", () => { expect(init?.method).toBe("DELETE"); }); - it("postExamChoiceImage calls /exams/:id/questions/:qid/choices/:index/image with FormData", async () => { + it("postExamChoiceImage calls /exams/:id/questions/:qid/choices/:choiceId/image with FormData", async () => { const mockMeta = { content_type: "image/png", size: 100 }; mockFetchSuccess(mockMeta); const file = new File(["test"], "test.png", { type: "image/png" }); - const result = await postExamChoiceImage("ex1", "q1", 2, file); + const result = await postExamChoiceImage("ex1", "q1", "c2", file); expect(result).toEqual(mockMeta); const [url, init] = lastFetchCall(); - expect(url).toBe("/api/exams/ex1/questions/q1/choices/2/image"); + expect(url).toBe("/api/exams/ex1/questions/q1/choices/c2/image"); expect(init?.method).toBe("POST"); expect(init?.body).toBeInstanceOf(FormData); }); - it("deleteExamChoiceImage calls /exams/:id/questions/:qid/choices/:index/image", async () => { + it("deleteExamChoiceImage calls /exams/:id/questions/:qid/choices/:choiceId/image", async () => { mockFetch204(); - await deleteExamChoiceImage("ex1", "q1", 2); + await deleteExamChoiceImage("ex1", "q1", "c2"); const [url, init] = lastFetchCall(); - expect(url).toBe("/api/exams/ex1/questions/q1/choices/2/image"); + expect(url).toBe("/api/exams/ex1/questions/q1/choices/c2/image"); expect(init?.method).toBe("DELETE"); }); it("postExamQuestionFromBank calls /exams/:id/questions/from-bank/:bid with subject_id", async () => { - const mockQuestion = { id: "q9", source_bank: "b1" }; + // Provenance is two separate fields: coming *from* the bank leaves + // `banked_as` null, so the UI can't claim the question was saved to it. + const mockQuestion = { id: "q9", from_bank: "b1", banked_as: null }; mockFetchSuccess(mockQuestion, 201); const result = await postExamQuestionFromBank("ex1", "b1", "sub1"); expect(result).toEqual(mockQuestion); + expect(result.from_bank).toBe("b1"); + expect(result.banked_as).toBeNull(); const [url, init] = lastFetchCall(); expect(url).toBe("/api/exams/ex1/questions/from-bank/b1"); @@ -139,4 +148,20 @@ describe("exams API - questions", () => { expect(init?.method).toBe("POST"); expect(init?.body).toBeUndefined(); }); + + it("postExamQuestionRefreshFromBank calls /exams/:id/questions/:qid/refresh-from-bank with no body", async () => { + // The question keeps its id and its `from_bank` link; only the content is + // re-copied from the template. + const mockQuestion = { id: "q1", text: "fixed in the template", from_bank: "b1" }; + mockFetchSuccess(mockQuestion); + + const result = await postExamQuestionRefreshFromBank("ex1", "q1"); + expect(result).toEqual(mockQuestion); + expect(result.from_bank).toBe("b1"); + + const [url, init] = lastFetchCall(); + expect(url).toBe("/api/exams/ex1/questions/q1/refresh-from-bank"); + expect(init?.method).toBe("POST"); + expect(init?.body).toBeUndefined(); + }); }); diff --git a/src/api/__tests__/exams/exams.test.ts b/src/api/__tests__/exams/exams.test.ts index 1c9df5b..89fca13 100644 --- a/src/api/__tests__/exams/exams.test.ts +++ b/src/api/__tests__/exams/exams.test.ts @@ -27,14 +27,14 @@ describe("exams API - core", () => { expect(init?.method).toBe("GET"); }); - it("getExamChoiceImageBlob calls /exams/:id/questions/:qid/choices/:index/image", async () => { + it("getExamChoiceImageBlob calls /exams/:id/questions/:qid/choices/:choiceId/image", async () => { mockFetchBlob(new Blob(["img"], { type: "image/png" })); - const result = await getExamChoiceImageBlob("ex1", "q1", 2); + const result = await getExamChoiceImageBlob("ex1", "q1", "c2"); expect(result).toBeInstanceOf(Blob); const [url, init] = lastFetchCall(); - expect(url).toBe("/api/exams/ex1/questions/q1/choices/2/image"); + expect(url).toBe("/api/exams/ex1/questions/q1/choices/c2/image"); expect(init?.method).toBeUndefined(); }); diff --git a/src/api/bank-questions/deleteBankChoiceImage.ts b/src/api/bank-questions/deleteBankChoiceImage.ts index cc4e60f..35c61cd 100644 --- a/src/api/bank-questions/deleteBankChoiceImage.ts +++ b/src/api/bank-questions/deleteBankChoiceImage.ts @@ -1,5 +1,5 @@ import { client } from "../client"; -export function deleteBankChoiceImage(bankQuestionId: string, index: number): Promise { - return client(`/bank-questions/${bankQuestionId}/choices/${index}/image`, { method: "DELETE" }); +export function deleteBankChoiceImage(bankQuestionId: string, choiceId: string): Promise { + return client(`/bank-questions/${bankQuestionId}/choices/${choiceId}/image`, { method: "DELETE" }); } diff --git a/src/api/bank-questions/getBankChoiceImageBlob.ts b/src/api/bank-questions/getBankChoiceImageBlob.ts index eb834d1..b3ff7d8 100644 --- a/src/api/bank-questions/getBankChoiceImageBlob.ts +++ b/src/api/bank-questions/getBankChoiceImageBlob.ts @@ -1,5 +1,5 @@ import { blobClient } from "../client"; -export function getBankChoiceImageBlob(bankQuestionId: string, index: number, signal?: AbortSignal): Promise { - return blobClient(`/bank-questions/${bankQuestionId}/choices/${index}/image`, signal); +export function getBankChoiceImageBlob(bankQuestionId: string, choiceId: string, signal?: AbortSignal): Promise { + return blobClient(`/bank-questions/${bankQuestionId}/choices/${choiceId}/image`, signal); } diff --git a/src/api/bank-questions/getBankQuestions.ts b/src/api/bank-questions/getBankQuestions.ts index 650f894..c9353b0 100644 --- a/src/api/bank-questions/getBankQuestions.ts +++ b/src/api/bank-questions/getBankQuestions.ts @@ -1,9 +1,17 @@ import { client } from "../client"; import { appendPageParams, normalizePage, type Page, type PageParams } from "../client"; -import type { BankQuestion } from "../client"; +import type { BankQuestion, BankVisibility } from "../client"; -/** `owner` takes a user id or the literal "me". */ -export type BankQuestionFilters = PageParams & { subject?: string; owner?: string }; +/** + * `owner` takes a user id or the literal "me". `visibility` only narrows what the + * caller may already see — "private" is effectively their own drafts. + */ +export type BankQuestionFilters = PageParams & { + subject?: string; + owner?: string; + q?: string; + visibility?: BankVisibility; +}; export async function getBankQuestions( params?: BankQuestionFilters, @@ -12,6 +20,8 @@ export async function getBankQuestions( const query = new URLSearchParams(); if (params?.subject) query.set("subject", params.subject); if (params?.owner) query.set("owner", params.owner); + if (params?.q) query.set("q", params.q); + if (params?.visibility) query.set("visibility", params.visibility); appendPageParams(query, params); const value = query.toString(); const data = await client(`/bank-questions${value ? `?${value}` : ""}`, { signal }); diff --git a/src/api/bank-questions/patchBankQuestionById.ts b/src/api/bank-questions/patchBankQuestionById.ts index 4dafd6b..7276b13 100644 --- a/src/api/bank-questions/patchBankQuestionById.ts +++ b/src/api/bank-questions/patchBankQuestionById.ts @@ -1,13 +1,17 @@ import { client } from "../client"; -import type { BankQuestion, QuestionKind } from "../client"; +import type { BankQuestion, BankVisibility, QuestionKind } from "../client"; export type PatchBankQuestionBody = { subject_id?: string; text?: string; kind?: QuestionKind; points?: number; - choices?: string[] | null; - correct?: number | null; + /** Each option carries its key: a known key keeps that option (and its image), any other is new. */ + choices?: { id?: string | null; text: string }[] | null; + /** Choice id — must name one of the submitted choices. */ + correct?: string | null; + /** Publishing (`school`) hands the answer key to every teacher — send it only on an explicit choice. */ + visibility?: BankVisibility; }; export function patchBankQuestionById( diff --git a/src/api/bank-questions/postBankChoiceImage.ts b/src/api/bank-questions/postBankChoiceImage.ts index 104a7f2..8b6c277 100644 --- a/src/api/bank-questions/postBankChoiceImage.ts +++ b/src/api/bank-questions/postBankChoiceImage.ts @@ -1,8 +1,8 @@ import { formClient } from "../client"; import type { ImageMeta } from "../client"; -export function postBankChoiceImage(bankQuestionId: string, index: number, file: File, signal?: AbortSignal): Promise { +export function postBankChoiceImage(bankQuestionId: string, choiceId: string, file: File, signal?: AbortSignal): Promise { const body = new FormData(); body.append("file", file); - return formClient(`/bank-questions/${bankQuestionId}/choices/${index}/image`, body, signal); + return formClient(`/bank-questions/${bankQuestionId}/choices/${choiceId}/image`, body, signal); } diff --git a/src/api/bank-questions/postBankQuestion.ts b/src/api/bank-questions/postBankQuestion.ts index 44a1a0c..49d2ea1 100644 --- a/src/api/bank-questions/postBankQuestion.ts +++ b/src/api/bank-questions/postBankQuestion.ts @@ -6,8 +6,10 @@ export type BankQuestionBody = { text: string; kind: QuestionKind; points: number; - choices?: string[] | null; - correct?: number | null; + /** Each option carries its key: a known key keeps that option (and its image), any other is new. */ + choices?: { id?: string | null; text: string }[] | null; + /** Choice id — must name one of the submitted choices. */ + correct?: string | null; }; export function postBankQuestion(body: BankQuestionBody): Promise { diff --git a/src/api/client/types.ts b/src/api/client/types.ts index bc5dbce..3ee2564 100644 --- a/src/api/client/types.ts +++ b/src/api/client/types.ts @@ -207,6 +207,9 @@ export type ExamResult = { graded_by: PersonRef; }; +/** One option of a choice question. `id` is stable across edits, so its image survives. */ +export type Choice = { id: string; text: string }; + export type ExamQuestion = { id: string; exam: string; @@ -214,27 +217,41 @@ export type ExamQuestion = { text: string; kind: QuestionKind; points: number; - choices: string[] | null; - correct: number | null; + choices: Choice[] | null; + correct: string | null; image?: ImageMeta | null; choice_images?: (ImageMeta | null)[] | null; - source_bank?: string | null; // bank question this was copied from, if any + from_bank?: string | null; // bank template this question was added from, if any + banked_as?: string | null; // bank template last created by saving this question, if any }; +/** `private`: owner + admins only. `school`: every teacher can see it and its answer key. */ +export type BankVisibility = "private" | "school"; + /** Reusable question stored in the school-wide question bank, outside any exam. */ export type BankQuestion = { id: string; owner: string; // user id - subject: string; // subject id (origin metadata) + owner_name: string; + subject: string | null; // subject id (origin metadata); null once that subject is deleted + subject_name: string; text: string; kind: QuestionKind; points: number; - choices: string[] | null; - correct: number | null; + choices: Choice[] | null; + correct: string | null; image?: ImageMeta | null; choice_images?: (ImageMeta | null)[] | null; source_exam?: string | null; + visibility: BankVisibility; // new templates start "private" created_at: number; // UTC unix ms + /** + * How many exam questions were copied out of this template. Each copy is + * detached, so editing the template never reaches them — this is the + * divergence surface. List-only, exactly like `subject_name`/`owner_name`: + * the single-template endpoints return 0. + */ + used_count: number; }; export type ExamAttempt = { @@ -257,7 +274,7 @@ export type ExamAttempt = { }; export type AttemptAnswer = { - selected?: number | null; + selected?: string | null; text?: string | null; updated_at?: number; answer_image?: ImageMeta | null; @@ -269,7 +286,7 @@ export type AttemptQuestionResponse = { text: string; kind: QuestionKind; points: number; - choices: string[] | null; + choices: Choice[] | null; image?: ImageMeta | null; choice_images?: (ImageMeta | null)[] | null; answer: AttemptAnswer | null; @@ -364,7 +381,7 @@ export type ExamStatistics = { export type StudentAnswer = { question: string; - selected: number | null; + selected: string | null; text: string | null; updated_at: number; is_correct: boolean | null; diff --git a/src/api/exams/deleteExamChoiceImage.ts b/src/api/exams/deleteExamChoiceImage.ts index 6047c51..41c93f9 100644 --- a/src/api/exams/deleteExamChoiceImage.ts +++ b/src/api/exams/deleteExamChoiceImage.ts @@ -1,5 +1,5 @@ import { client } from "../client"; -export function deleteExamChoiceImage(examId: string, questionId: string, index: number): Promise { - return client(`/exams/${examId}/questions/${questionId}/choices/${index}/image`, { method: "DELETE" }); +export function deleteExamChoiceImage(examId: string, questionId: string, choiceId: string): Promise { + return client(`/exams/${examId}/questions/${questionId}/choices/${choiceId}/image`, { method: "DELETE" }); } diff --git a/src/api/exams/getExamChoiceImageBlob.ts b/src/api/exams/getExamChoiceImageBlob.ts index ad09223..4d31926 100644 --- a/src/api/exams/getExamChoiceImageBlob.ts +++ b/src/api/exams/getExamChoiceImageBlob.ts @@ -1,5 +1,5 @@ import { blobClient } from "../client"; -export function getExamChoiceImageBlob(examId: string, questionId: string, index: number, signal?: AbortSignal): Promise { - return blobClient(`/exams/${examId}/questions/${questionId}/choices/${index}/image`, signal); +export function getExamChoiceImageBlob(examId: string, questionId: string, choiceId: string, signal?: AbortSignal): Promise { + return blobClient(`/exams/${examId}/questions/${questionId}/choices/${choiceId}/image`, signal); } diff --git a/src/api/exams/index.ts b/src/api/exams/index.ts index b9d13ee..7645ecf 100644 --- a/src/api/exams/index.ts +++ b/src/api/exams/index.ts @@ -37,4 +37,5 @@ export * from "./getExamReviewAttemptAnswers"; export * from "./getExamReviewAttemptAnswerImage"; export * from "./getStudentMarksHistory"; export * from "./postExamQuestionFromBank"; +export * from "./postExamQuestionRefreshFromBank"; export * from "./postExamQuestionToBank"; diff --git a/src/api/exams/patchExamQuestionById.ts b/src/api/exams/patchExamQuestionById.ts index 0c2a066..212baf3 100644 --- a/src/api/exams/patchExamQuestionById.ts +++ b/src/api/exams/patchExamQuestionById.ts @@ -6,8 +6,10 @@ export type PatchExamQuestionBody = { text?: string | null; kind?: QuestionKind | null; points?: number | null; - choices?: string[] | null; - correct?: number | null; + /** Each option carries its key: a known key keeps that option (and its image), any other is new. */ + choices?: { id?: string | null; text: string }[] | null; + /** Choice id — must name one of the submitted choices. */ + correct?: string | null; }; export function patchExamQuestionById( diff --git a/src/api/exams/postExamAttemptAnswer.ts b/src/api/exams/postExamAttemptAnswer.ts index 2a0e894..951ca81 100644 --- a/src/api/exams/postExamAttemptAnswer.ts +++ b/src/api/exams/postExamAttemptAnswer.ts @@ -3,7 +3,7 @@ import type { AttemptAnswer } from "../client"; export type PostExamAttemptAnswerBody = { question_id: string; - selected?: number | null; + selected?: string | null; // choice id text?: string | null; }; diff --git a/src/api/exams/postExamChoiceImage.ts b/src/api/exams/postExamChoiceImage.ts index 748a12c..8f69b21 100644 --- a/src/api/exams/postExamChoiceImage.ts +++ b/src/api/exams/postExamChoiceImage.ts @@ -1,8 +1,8 @@ import { formClient } from "../client"; import type { ImageMeta } from "../client"; -export function postExamChoiceImage(examId: string, questionId: string, index: number, file: File, signal?: AbortSignal): Promise { +export function postExamChoiceImage(examId: string, questionId: string, choiceId: string, file: File, signal?: AbortSignal): Promise { const body = new FormData(); body.append("file", file); - return formClient(`/exams/${examId}/questions/${questionId}/choices/${index}/image`, body, signal); + return formClient(`/exams/${examId}/questions/${questionId}/choices/${choiceId}/image`, body, signal); } diff --git a/src/api/exams/postExamQuestion.ts b/src/api/exams/postExamQuestion.ts index cd45e13..cc2be5f 100644 --- a/src/api/exams/postExamQuestion.ts +++ b/src/api/exams/postExamQuestion.ts @@ -6,8 +6,10 @@ export type ExamQuestionBody = { text: string; kind: QuestionKind; points: number; - choices?: string[] | null; - correct?: number | null; + /** Each option carries its key: a known key keeps that option (and its image), any other is new. */ + choices?: { id?: string | null; text: string }[] | null; + /** Choice id — must name one of the submitted choices. */ + correct?: string | null; }; export function postExamQuestion(examId: string, body: ExamQuestionBody): Promise { diff --git a/src/api/exams/postExamQuestionRefreshFromBank.ts b/src/api/exams/postExamQuestionRefreshFromBank.ts new file mode 100644 index 0000000..0bae14b --- /dev/null +++ b/src/api/exams/postExamQuestionRefreshFromBank.ts @@ -0,0 +1,17 @@ +import { client } from "../client"; +import type { ExamQuestion } from "../client"; + +/** + * Re-copy the question's bank template over it — the escape hatch for a copy that + * drifted from its template (a bank↔exam copy is deep, never a live link). Only + * for a question that still has `from_bank`; the backend refuses with 409 once + * any attempt exists, and 400 when there is no template to refresh from. + */ +export function postExamQuestionRefreshFromBank( + examId: string, + questionId: string, +): Promise { + return client(`/exams/${examId}/questions/${questionId}/refresh-from-bank`, { + method: "POST", + }); +} diff --git a/src/components/exams/answer-sheet-view.tsx b/src/components/exams/answer-sheet-view.tsx index 8321555..7cb0975 100644 --- a/src/components/exams/answer-sheet-view.tsx +++ b/src/components/exams/answer-sheet-view.tsx @@ -234,11 +234,11 @@ export function AnswerSheetView(props: { examId: string; userId: string; mode?: {(choice, ci) => (
{String.fromCharCode(65 + ci())} - {choice} - + {choice.text} + ✗ - {ci() === row.question.correct && ( + {choice.id === row.question.correct && ( diff --git a/src/components/exams/bank-question-form.tsx b/src/components/exams/bank-question-form.tsx index 237c2d3..41c6807 100644 --- a/src/components/exams/bank-question-form.tsx +++ b/src/components/exams/bank-question-form.tsx @@ -1,7 +1,6 @@ -import { For, Show, createResource, createSignal } from "solid-js"; -import type { BankQuestion, Course } from "@/api/client"; +import { For, Show, createEffect, createResource, createSignal } from "solid-js"; +import type { BankQuestion, BankVisibility, Course } from "@/api/client"; import { - getBankChoiceImageBlob, patchBankQuestionById, postBankChoiceImage, postBankQuestion, @@ -11,7 +10,8 @@ import { getBankQuestionImageBlob } from "@/api/bank-questions"; import { getCourseSubjects } from "@/api/courses"; import { getSubjectById } from "@/api/subjects"; import { QuestionForm, type QuestionValues } from "@/components/exams/question-form"; -import { planChoiceImageRestore } from "@/lib/choice-compaction"; +import { ConfirmDialog } from "@/components/ui/confirm-dialog"; +import { IconUsers } from "@/components/ui/icons"; import { Label } from "@/components/ui/label"; import { Select } from "@/components/ui/select"; import { useT } from "@/stores/preferences-context"; @@ -24,8 +24,7 @@ import { useT } from "@/stores/preferences-context"; export function BankQuestionForm(props: { initial?: BankQuestion; courses: Course[]; - /** `imagesLost` is set when an option image could not be carried over the edit. */ - onSaved: (question: BankQuestion, imagesLost?: string) => void; + onSaved: (question: BankQuestion) => void; onCancel: () => void; }) { const t = useT(); @@ -35,57 +34,54 @@ export function BankQuestionForm(props: { async (subjectId) => (await getSubjectById(subjectId).catch(() => null))?.course ?? "", ); const [courseId, setCourseId] = createSignal(""); - const selectedCourse = () => courseId() || initialCourse() || props.courses[0]?.id || ""; + // Editing keeps the template's own course even when it is not one of ours (it is + // shown as a disabled option); only a new template falls back to the first course. + const selectedCourse = () => + courseId() || initialCourse() || (props.initial ? "" : props.courses[0]?.id) || ""; + const originUnknown = () => + !!initialCourse() && !props.courses.some((course) => course.id === initialCourse()); const [subjects] = createResource( () => selectedCourse() || null, async (id) => (await getCourseSubjects(id)).items, ); + // A template is private until its owner deliberately shares it; switching to + // "school" waits on a confirmation dialog that spells out what that hands over. + const [visibility, setVisibility] = createSignal("private"); + const [confirmShare, setConfirmShare] = createSignal<((shared: boolean) => void) | null>(null); + createEffect(() => setVisibility(props.initial?.visibility ?? "private")); + const imageBase = () => `/api/bank-questions/${props.initial?.id}`; const submit = async (values: QuestionValues) => { - const { image, choice_images, choice_sources, ...body } = values; + const { image, choice_images, ...body } = values; const existing = props.initial; - // PATCH with a `choices` key wipes every stored option image server-side, so - // fetch the ones the user is keeping first and put them back afterwards. - // `choice_sources` maps each surviving choice to the option it came from, - // because blank choices are dropped and would otherwise shift the indices. - const lost: number[] = []; - const keep: { index: number; file: File }[] = []; - if (existing && body.kind === "choice") { - const plan = planChoiceImageRestore(choice_sources ?? [], existing.choice_images ?? [], choice_images); - for (const slot of plan) { - try { - const blob = await getBankChoiceImageBlob(existing.id, slot.source); - keep.push({ index: slot.index, file: new File([blob], `choice-${slot.source}`, { type: blob.type }) }); - } catch { - lost.push(slot.index); // the PATCH below deletes it regardless — say so - } - } + // Sharing is the only irreversible half of this form — ask before anything is sent. + const sharing = visibility() === "school" && existing?.visibility !== "school"; + if (sharing) { + const confirmed = await new Promise((resolve) => setConfirmShare(() => resolve)); + setConfirmShare(null); + if (!confirmed) return; } - const saved = existing - ? await patchBankQuestionById(existing.id, body) + // POST has no visibility field — a new template is always born private, so + // sharing one is a follow-up PATCH. + let saved = existing + ? await patchBankQuestionById(existing.id, { + ...body, + ...(visibility() !== existing.visibility ? { visibility: visibility() } : {}), + }) : await postBankQuestion(body); + if (sharing && !existing) saved = await patchBankQuestionById(saved.id, { visibility: "school" }); if (image) await postBankQuestionImage(saved.id, image); + // The saved choices come back in the submitted order, so the freshly picked + // files line up with them — and every untouched option kept its own picture. for (const [index, file] of (choice_images ?? []).entries()) { - if (file) await postBankChoiceImage(saved.id, index, file); - } - // One failed restore must not abandon the rest: upload each independently. - for (const slot of keep) { - try { - await postBankChoiceImage(saved.id, slot.index, slot.file); - } catch { - lost.push(slot.index); - } + const choiceId = saved.choices?.[index]?.id; + if (file && choiceId) await postBankChoiceImage(saved.id, choiceId, file); } - props.onSaved( - saved, - lost.length > 0 - ? t("questions.imagesLost", { options: lost.sort((a, b) => a - b).map((index) => String.fromCharCode(65 + index)).join(", ") }) - : undefined, - ); + props.onSaved(saved); }; return ( @@ -102,26 +98,54 @@ export function BankQuestionForm(props: { value={selectedCourse()} onChange={(event) => setCourseId(event.currentTarget.value)} > + + + + {(course) => }

{t("bank.courseHint")}

- -

- {t("bank.choiceImagesWarning")} +

+ + +

+ {visibility() === "school" ? t("bank.sharedWithSchoolHint") : t("bank.onlyMeHint")}

- +
`${imageBase()}/choices/${index}/image`} + choiceImageSrc={(choiceId) => `${imageBase()}/choices/${choiceId}/image`} loadImageBlob={props.initial ? () => getBankQuestionImageBlob(props.initial!.id) : undefined} onSubmit={submit} onCancel={props.onCancel} /> + + { + if (!open) confirmShare()?.(false); + }} + title={t("bank.shareTitle")} + description={t("bank.shareBody")} + confirmLabel={t("bank.shareConfirm")} + icon={} + summary={props.initial?.text || t("bank.sharedWithSchoolHint")} + onConfirm={() => confirmShare()?.(true)} + /> ); } diff --git a/src/components/exams/bank-question-picker.tsx b/src/components/exams/bank-question-picker.tsx index 6e0d8b1..83171ac 100644 --- a/src/components/exams/bank-question-picker.tsx +++ b/src/components/exams/bank-question-picker.tsx @@ -1,4 +1,4 @@ -import { For, Show, createMemo, createResource, createSignal } from "solid-js"; +import { For, Show, createResource, createSignal } from "solid-js"; import type { BankQuestion, Subject } from "@/api/client"; import { formatApiError } from "@/api/client"; import { getBankQuestions } from "@/api/bank-questions"; @@ -6,11 +6,14 @@ import { Badge } from "@/components/ui/badge"; import { Button } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; import { Label } from "@/components/ui/label"; +import { PaginationControls } from "@/components/ui/pagination-controls"; import { Select } from "@/components/ui/select"; import { cn } from "@/lib/cn"; -import { usePreferences, useT } from "@/stores/preferences-context"; +import { createDebouncedSignal } from "@/lib/create-debounced-signal"; +import { totalPages as pagesOf } from "@/lib/list-page"; +import { useT } from "@/stores/preferences-context"; -const BANK_LIMIT = 100; +const PICKER_PAGE_SIZE = 20; /** Pick a bank template and copy it into an exam under one of that exam's subjects. */ export function BankQuestionPicker(props: { @@ -19,22 +22,27 @@ export function BankQuestionPicker(props: { onCancel: () => void; }) { const t = useT(); - const { locale } = usePreferences(); - const [query, setQuery] = createSignal(""); + const [query, setQuery, debouncedQuery] = createDebouncedSignal(); + const [page, setPage] = createSignal(0); const [selected, setSelected] = createSignal(null); const [subjectId, setSubjectId] = createSignal(""); const [error, setError] = createSignal(""); const [pending, setPending] = createSignal(false); - // ponytail: first 100 templates, narrowed client-side — the bank has no text - // search endpoint. Swap for a server query when the bank outgrows one page. - const [templates] = createResource(async () => (await getBankQuestions({ limit: BANK_LIMIT })).items); + const [templates] = createResource( + () => ({ page: page(), q: debouncedQuery().trim() }), + (params) => + getBankQuestions({ + limit: PICKER_PAGE_SIZE, + offset: params.page * PICKER_PAGE_SIZE, + ...(params.q ? { q: params.q } : {}), + }), + ); - const targetSubject = () => subjectId() || props.subjects[0]?.id || ""; - const visible = createMemo(() => { - const q = query().trim().toLocaleLowerCase(locale()); - const items = templates() ?? []; - return q ? items.filter((item) => item.text.toLocaleLowerCase(locale()).includes(q)) : items; - }); + // No default: the teacher files the copy under a subject deliberately, or not at all. + const targetSubject = () => subjectId(); + // .latest: the list lives in a dialog with no , so paging must not blank it. + const visible = () => templates.latest?.items ?? []; + const total = () => templates.latest?.total ?? 0; const insert = async () => { const template = selected(); @@ -61,7 +69,10 @@ export function BankQuestionPicker(props: { class="h-9 rounded-lg text-sm" value={query()} placeholder={t("bank.search")} - onInput={(event) => setQuery(event.currentTarget.value)} + onInput={(event) => { + setQuery(event.currentTarget.value); + setPage(0); + }} />
@@ -96,6 +107,15 @@ export function BankQuestionPicker(props: {
+ 0}> +

+ {t("bank.countShown", { shown: visible().length, total: total() })} +

+
+ 1}> + + + {(template) => (
@@ -114,11 +134,11 @@ export function BankQuestionPicker(props: {
  • {String.fromCharCode(65 + index())} - {choice} + {choice.text}
  • )} @@ -130,7 +150,7 @@ export function BankQuestionPicker(props: {
    0} @@ -140,10 +160,15 @@ export function BankQuestionPicker(props: { id="bank-target-subject" class="h-9 py-1.5 text-sm" value={targetSubject()} + required onChange={(event) => setSubjectId(event.currentTarget.value)} > + {(subject) => } + +

    {t("bank.targetSubjectHint")}

    +
    diff --git a/src/components/exams/exam-questions-panel.tsx b/src/components/exams/exam-questions-panel.tsx index ad8c7bc..e168ca4 100644 --- a/src/components/exams/exam-questions-panel.tsx +++ b/src/components/exams/exam-questions-panel.tsx @@ -3,10 +3,10 @@ import { deleteExamChoiceImage } from "@/api/exams"; import { deleteExamQuestionImage } from "@/api/exams"; import { deleteExamQuestionById } from "@/api/exams"; import { getCourseSubjects } from "@/api/courses"; -import { getExamChoiceImageBlob } from "@/api/exams"; import { getExamQuestionImageBlob } from "@/api/exams"; import { getExamQuestions } from "@/api/exams"; import { postExamQuestionFromBank } from "@/api/exams"; +import { postExamQuestionRefreshFromBank } from "@/api/exams"; import { postExamQuestionToBank } from "@/api/exams"; import { patchExamQuestionById } from "@/api/exams"; import { postExamChoiceImage } from "@/api/exams"; @@ -21,9 +21,8 @@ import { ConfirmDialog } from "@/components/ui/confirm-dialog"; import { FormDialog } from "@/components/ui/form-dialog"; import { BankQuestionPicker } from "@/components/exams/bank-question-picker"; import { QuestionForm, type QuestionValues } from "@/components/exams/question-form"; -import { IconArchive, IconChevronLeft, IconChevronRight, IconPlus, IconTrash } from "@/components/ui/icons"; +import { IconArchive, IconChevronLeft, IconChevronRight, IconPlus, IconRefresh, IconTrash } from "@/components/ui/icons"; import { PageSpinner } from "@/components/ui/page-spinner"; -import { planChoiceImageRestore } from "@/lib/choice-compaction"; import { createFlash } from "@/lib/flash"; import { hasMinRole } from "@/lib/roles"; import { useAuth } from "@/stores/auth-context"; @@ -57,8 +56,10 @@ export function ExamQuestionsPanel(props: { const [editing, setEditing] = createSignal(null); const [removeQuestion, setRemoveQuestion] = createSignal(null); const [confirmBank, setConfirmBank] = createSignal(null); - // Older backends never write `source_bank` back onto the exam question after a - // to-bank save, so remember what this session banked and treat both as "banked". + const [confirmRefresh, setConfirmRefresh] = createSignal(null); + // The `banked_as` back-link only shows up after the refetch (and older backends + // never write it at all), so remember what this session banked and treat both + // as saved. const [bankedIds, setBankedIds] = createSignal([]); const [error, setError] = createSignal(""); const [imagePending, setImagePending] = createSignal(""); @@ -77,7 +78,11 @@ export function ExamQuestionsPanel(props: { // `.latest` — a bare read there re-suspends on every refetch (insert-from-bank, // save, delete) and blanks the surrounding page for the whole fetch. const questionCount = () => questions.latest?.length ?? 0; - const isBanked = (question: ExamQuestion) => Boolean(question.source_bank) || bankedIds().includes(question.id); + // Two separate links, never conflated: `banked_as` is set only by a save to the + // bank, `from_bank` only by an insert out of it. A question added from the bank + // has not been saved to it, so it must not offer "save another copy". + const isSavedToBank = (question: ExamQuestion) => Boolean(question.banked_as) || bankedIds().includes(question.id); + const isFromBank = (question: ExamQuestion) => Boolean(question.from_bank); const subjectName = (subjectId: string) => subjects()?.find((subject) => subject.id === subjectId)?.name ?? subjectId; const totalPages = createMemo(() => Math.max(1, Math.ceil(questionList().length / QUESTION_PAGE_SIZE))); const safePage = createMemo(() => Math.min(page(), totalPages() - 1)); @@ -103,43 +108,17 @@ export function ExamQuestionsPanel(props: { try { const q = editing(); const isNewQuestion = !q; - // choice_sources is form-only bookkeeping — never send it to the backend. - const { image, choice_images, choice_sources, ...body } = values; - - // A PATCH carrying `choices` wipes every stored option image, so pull the - // ones the user kept first and put them back under their new indices. - const lost: number[] = []; - const keep: { index: number; file: File }[] = []; - if (q && body.kind === "choice") { - for (const slot of planChoiceImageRestore(choice_sources ?? [], q.choice_images ?? [], choice_images)) { - try { - const blob = await getExamChoiceImageBlob(props.examId, q.id, slot.source); - keep.push({ index: slot.index, file: new File([blob], `choice-${slot.source}`, { type: blob.type }) }); - } catch { - lost.push(slot.index); // the write below drops it either way — report it - } - } - } + const { image, choice_images, ...body } = values; const saved = q ? await patchExamQuestionById(props.examId, q.id, body) : await postExamQuestion(props.examId, body); if (image) await postExamQuestionImage(props.examId, saved.id, image); + // The saved choices come back in the submitted order, so the freshly picked + // files line up with them — and every untouched option kept its own picture. for (const [index, file] of (choice_images ?? []).entries()) { - if (file) await postExamChoiceImage(props.examId, saved.id, index, file); - } - // Independent uploads: one failure must not strand the remaining images. - for (const slot of keep) { - try { - await postExamChoiceImage(props.examId, saved.id, slot.index, slot.file); - } catch { - lost.push(slot.index); - } - } - if (lost.length > 0) { - setError(t("questions.imagesLost", { - options: lost.sort((a, b) => a - b).map((index) => String.fromCharCode(65 + index)).join(", "), - })); + const choiceId = saved.choices?.[index]?.id; + if (file && choiceId) await postExamChoiceImage(props.examId, saved.id, choiceId, file); } if (q) { setFlash(t("common.saved")); @@ -178,6 +157,24 @@ export function ExamQuestionsPanel(props: { } }; + // Re-copy the template over this question. Offered only while `from_bank` is + // set: the bank delete cascade clears it, so a template that is gone takes the + // action with it rather than leaving a button that can only fail. + const refreshFromBank = async (question: ExamQuestion) => { + if (banking()) return; + setError(""); + setBanking(question.id); + try { + await postExamQuestionRefreshFromBank(props.examId, question.id); + setFlash(t("bank.refreshed")); + await refetch(); + } catch (err) { + setError(formatApiError(err)); + } finally { + setBanking(""); + } + }; + const removeQuestionImage = async (question: ExamQuestion) => { if (props.readOnly) return; setError(""); @@ -193,12 +190,12 @@ export function ExamQuestionsPanel(props: { } }; - const removeChoiceImage = async (question: ExamQuestion, index: number) => { + const removeChoiceImage = async (question: ExamQuestion, choiceId: string) => { if (props.readOnly) return; setError(""); - setImagePending(`${question.id}:choice:${index}`); + setImagePending(`${question.id}:choice:${choiceId}`); try { - await deleteExamChoiceImage(props.examId, question.id, index); + await deleteExamChoiceImage(props.examId, question.id, choiceId); await refetch(); setFlash(t("common.deleted")); } catch (err) { @@ -279,8 +276,9 @@ export function ExamQuestionsPanel(props: { `/api/exams/${props.examId}/questions/${editing()?.id}/choices/${index}/image`} + choiceImageSrc={(choiceId) => `/api/exams/${props.examId}/questions/${editing()?.id}/choices/${choiceId}/image`} loadImageBlob={editing() ? () => getExamQuestionImageBlob(props.examId, editing()!.id) : undefined} onCancel={() => { setEditing(null); @@ -334,12 +332,18 @@ export function ExamQuestionsPanel(props: { {q.points} {t("questions.points")} - {/* `source_bank` is set in both directions (inserted from the - bank, or saved to it), so the badge stays origin-neutral. */} - + {/* One badge per direction: a question can be both (added + from the bank, then saved back), so they stack. */} + + + + {t("bank.fromBankBadge")} + + + - {t("bank.inBankBadge")} + {t("bank.savedToBankBadge")}
    @@ -369,7 +373,7 @@ export function ExamQuestionsPanel(props: { {(choice, choiceIndex) => (
  • - {choice} + {choice.text} {t("questions.choiceImage")} @@ -392,8 +396,8 @@ export function ExamQuestionsPanel(props: { variant="ghost" size="sm" class="h-7 px-2 text-xs text-destructive" - disabled={imagePending() === `${q.id}:choice:${choiceIndex()}`} - onClick={() => void removeChoiceImage(q, choiceIndex())} + disabled={imagePending() === `${q.id}:choice:${choice.id}`} + onClick={() => void removeChoiceImage(q, choice.id)} > {t("common.delete")} @@ -416,10 +420,27 @@ export function ExamQuestionsPanel(props: { size="sm" class="h-8 gap-1.5 px-2.5 text-xs" disabled={banking() === q.id} - onClick={() => (isBanked(q) ? setConfirmBank(q) : void saveToBank(q))} + onClick={() => (isSavedToBank(q) ? setConfirmBank(q) : void saveToBank(q))} > - {isBanked(q) ? t("bank.saveCopyToBank") : t("bank.saveToBank")} + {isSavedToBank(q) ? t("bank.saveCopyToBank") : t("bank.saveToBank")} + + + {/* Only while the question still points at a live + template: the bank delete cascade clears + `from_bank`, and the exam-side freeze is what + `readOnly` already reflects. */} + + @@ -501,6 +522,24 @@ export function ExamQuestionsPanel(props: { }} /> + { + if (!open) setConfirmRefresh(null); + }} + title={t("bank.refreshTitle")} + description={t("bank.refreshBody")} + confirmLabel={t("bank.refreshConfirm")} + icon={} + summary={confirmRefresh()?.text ?? ""} + onConfirm={async () => { + const q = confirmRefresh(); + if (!q) return; + setConfirmRefresh(null); + await refreshFromBank(q); + }} + /> + { diff --git a/src/components/exams/exam-room-ws.tsx b/src/components/exams/exam-room-ws.tsx index 8d7c334..9ec871e 100644 --- a/src/components/exams/exam-room-ws.tsx +++ b/src/components/exams/exam-room-ws.tsx @@ -256,19 +256,19 @@ export function ExamRoomWS(props: { exam: Exam }) { if (ws && ws.readyState === WebSocket.OPEN) { const payload: Record = { type: "answer", question_id: question.id }; if (question.kind === "choice") { - payload.selected = Number(value); + payload.selected = value; // choice id, not a position } else { payload.text = value; } sendWs(payload); setQuestions((prev) => - prev.map((q) => (q.id === question.id ? { ...q, answer: { ...q.answer, selected: question.kind === "choice" ? Number(value) : undefined, text: question.kind === "text" ? value : undefined } } : q)), + prev.map((q) => (q.id === question.id ? { ...q, answer: { ...q.answer, selected: question.kind === "choice" ? value : undefined, text: question.kind === "text" ? value : undefined } } : q)), ); } else { setPending(true); try { if (question.kind === "choice") { - await postExamAttemptAnswer(props.exam.id, { question_id: question.id, selected: Number(value) }); + await postExamAttemptAnswer(props.exam.id, { question_id: question.id, selected: value }); } else { await postExamAttemptAnswer(props.exam.id, { question_id: question.id, text: value }); } @@ -682,9 +682,7 @@ function QuestionAnswerCardWS(props: { const { locale } = usePreferences(); const [value, setValue] = createSignal( props.question.kind === "choice" - ? props.question.answer?.selected != null - ? String(props.question.answer.selected) - : "" + ? props.question.answer?.selected ?? "" : props.question.answer?.text ?? "", ); const [saved, setSaved] = createSignal(false); @@ -698,9 +696,7 @@ function QuestionAnswerCardWS(props: { questionId = props.question.id; setValue( props.question.kind === "choice" - ? props.question.answer?.selected != null - ? String(props.question.answer.selected) - : "" + ? props.question.answer?.selected ?? "" : props.question.answer?.text ?? "", ); setSaved(false); @@ -838,17 +834,17 @@ function QuestionAnswerCardWS(props: { disabled={props.disabled} onClick={() => { setSaved(false); - setValue(String(choiceIndex())); + setValue(choice.id); }} > - + {String.fromCharCode(65 + choiceIndex())} - {choice} + {choice.text} {t("questions.choiceImage")} diff --git a/src/components/exams/question-form.tsx b/src/components/exams/question-form.tsx index 418a45c..718f18e 100644 --- a/src/components/exams/question-form.tsx +++ b/src/components/exams/question-form.tsx @@ -1,6 +1,6 @@ import { For, Index, Show, Suspense, createEffect, createResource, createSignal, lazy, untrack } from "solid-js"; import { formatApiError } from "@/api/client"; -import type { ImageMeta, QuestionKind, Subject } 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"; @@ -10,7 +10,17 @@ 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 { compactChoices } from "@/lib/choice-compaction"; +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"; @@ -23,26 +33,24 @@ export type QuestionValues = { text: string; kind: QuestionKind; points: number; - choices: string[] | null; - correct: number | null; + /** 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; - /** - * For each surviving choice, the index it had in `initial.choices` (or -1 when - * it was added in this edit). Blank choices are dropped on submit, so callers - * that must re-attach per-choice server state need this old→new map. - */ - choice_sources: number[] | null; }; /** Shape both `ExamQuestion` and `BankQuestion` satisfy — the form only needs these. */ export type QuestionFormInitial = { - subject: string; + /** Null for a bank template whose origin subject has since been deleted. */ + subject: string | null; text: string; kind: QuestionKind; points: number; - choices: string[] | null; - correct: number | null; + choices: Choice[] | null; + correct: string | null; image?: ImageMeta | null; choice_images?: (ImageMeta | null)[] | null; }; @@ -50,9 +58,11 @@ export type QuestionFormInitial = { export function QuestionForm(props: { initial?: QuestionFormInitial; 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?: (index: number) => string; + choiceImageSrc?: (choiceId: string) => string; /** Reload the stored image so an existing drawing can be edited, not redrawn. */ loadImageBlob?: () => Promise; submitLabel?: string; @@ -62,18 +72,16 @@ export function QuestionForm(props: { const t = useT(); let textAreaRef: HTMLTextAreaElement | undefined; const [text, setText] = createSignal(props.initial?.text ?? ""); - const [subjectId, setSubjectId] = createSignal(props.initial?.subject ?? props.subjects[0]?.id ?? ""); + // 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 ?? "choice"); const [points, setPoints] = createSignal(String(props.initial?.points ?? 1)); - const [choices, setChoices] = createSignal(props.initial?.choices ?? ["", "", "", ""]); - const [correct, setCorrect] = createSignal(props.initial?.correct ?? 0); + 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 [choiceImages, setChoiceImages] = createSignal<(File | null)[]>(choices().map(() => null)); - // Index each row still holds in `initial.choices` (-1 once added here), so a - // caller can map surviving choices back to the server-side option they came from. - const [choiceSources, setChoiceSources] = createSignal(choices().map((_, index) => index)); const [error, setError] = createSignal(""); const [pending, setPending] = createSignal(false); const [settings] = createResource(async () => { @@ -91,24 +99,28 @@ export function QuestionForm(props: { const initial = props.initial; untrack(() => { setText(initial?.text ?? ""); - setSubjectId(initial?.subject ?? props.subjects[0]?.id ?? ""); + setSubjectId(initial?.subject ?? ""); setKind(initial?.kind ?? "choice"); setPoints(String(initial?.points ?? 1)); - setChoices(initial?.choices ?? ["", "", "", ""]); - setCorrect(initial?.correct ?? 0); + setChoiceSet(initial ? storedChoiceSet(initial.choices, initial.correct) : blankChoiceSet()); setImage(null); setDrawing(false); setEditScene(null); - setChoiceImages((initial?.choices ?? ["", "", "", ""]).map(() => null)); - setChoiceSources((initial?.choices ?? ["", "", "", ""]).map((_, index) => (initial ? index : -1))); setError(""); }); }); - // Once subjects load, preselect the first one if nothing is chosen yet. - createEffect(() => { - if (!subjectId()) setSubjectId(props.subjects[0]?.id ?? ""); - }); + // 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 = () => { @@ -142,8 +154,12 @@ export function QuestionForm(props: { resizeTextArea(); }); - const setChoice = (index: number, value: string) => { - setChoices((current) => current.map((choice, i) => (i === index ? value : choice))); + 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 => { @@ -162,68 +178,51 @@ export function QuestionForm(props: { if (validImage(file)) setImage(file); }; - const setChoiceImage = (index: number, file: File | null) => { + 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; } - setChoiceImages((current) => choices().map((_, i) => (i === index ? file : current[i] ?? null))); - }; - - const addChoice = () => { - const max = BANK_QUESTION_LIMITS.maxChoices; - setChoices((current) => (current.length >= max ? current : [...current, ""])); - setChoiceImages((current) => (current.length >= max ? current : [...current, null])); - setChoiceSources((current) => (current.length >= max ? current : [...current, -1])); - }; - - const removeChoice = (index: number) => { - const remaining = choices().length - 1; - setChoices((current) => current.filter((_, i) => i !== index)); - setChoiceImages((current) => current.filter((_, i) => i !== index)); - setChoiceSources((current) => current.filter((_, i) => i !== index)); - // Deleting a row above the answer shifts it down; deleting the answer row - // itself moves the mark to the row that took its place (visible in the UI). - setCorrect((current) => { - if (index < current) return Math.max(0, current - 1); - if (index > current) return current; - return Math.max(0, Math.min(current, remaining - 1)); - }); + 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, choice_sources: null }; + return { subject_id: subject, text: body, kind: "text", points: p, choices: null, correct: null, image: image(), choice_images: null }; } - const compacted = compactChoices(choices(), choiceImages(), choiceSources(), correct()); - const cleanChoices = compacted.choices; + const submitted = submitChoices(choiceSet()); if ( - cleanChoices.length < BANK_QUESTION_LIMITS.minChoices || - cleanChoices.length > BANK_QUESTION_LIMITS.maxChoices || - cleanChoices.some((choice) => choice.length > BANK_QUESTION_LIMITS.choiceTextMaxLen) + 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"); } - // The marked row survived compaction as `compacted.correct`; -1 means the user - // blanked the very choice they had marked, so make them pick again. - if (compacted.correct < 0) return t("questions.correctBlanked"); + // 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: cleanChoices, - correct: compacted.correct, + choices: submitted.choices, + correct: submitted.correct, image: image(), - choice_images: compacted.images, - choice_sources: compacted.sources, + choice_images: submitted.images, }; }; @@ -332,8 +331,14 @@ export function QuestionForm(props: { + +

    {t("questions.subjectUnavailableHelp")}

    +
    @@ -375,19 +380,18 @@ export function QuestionForm(props: {
    -
    - - {(choice, index) => { - const isCorrect = () => correct() === index; - // Stored images are keyed by the option's ORIGINAL index, which drifts - // from the display row once a choice is removed; -1 = added just now. - const storedIndex = () => choiceSources()[index] ?? -1; - const storedImage = () => (storedIndex() >= 0 ? props.initial?.choice_images?.[storedIndex()] : null); + + {(row, index) => { + const isCorrect = () => choiceSet().correct === row().id; + // Keyed by the row's own id, so a stored option keeps its picture no + // matter where it sits now; null = a row the server has never seen. + const stored = () => storedImage(row().id); return (
    setCorrect(index)} + onClick={() => setCorrect(row().id)} title={t("questions.correct")} > {isCorrect() ? : String.fromCharCode(65 + index)} @@ -411,10 +415,10 @@ export function QuestionForm(props: {
    setChoice(index, e.currentTarget.value)} + onInput={(e) => setChoice(row().id, e.currentTarget.value)} />
    setChoiceImage(index, event.currentTarget.files?.[0] ?? null)} + onChange={(event) => setChoiceImage(row().id, event.currentTarget.files?.[0] ?? null)} /> - + {t("questions.choiceImage")} @@ -441,9 +445,9 @@ export function QuestionForm(props: { type="button" variant="ghost" size="sm" - disabled={choices().length <= 2} + disabled={rows().length <= BANK_QUESTION_LIMITS.minChoices} class="mt-0.5 h-6 w-6 p-0 text-muted-foreground hover:text-destructive" - onClick={() => removeChoice(index)} + onClick={() => removeChoice(row().id)} > diff --git a/src/i18n/messages.ts b/src/i18n/messages.ts index 1fa971c..c25ce10 100644 --- a/src/i18n/messages.ts +++ b/src/i18n/messages.ts @@ -428,12 +428,13 @@ export type MessageKey = | "questions.editDrawing" | "questions.choiceImage" | "questions.subjectRequired" + | "questions.subjectUnavailable" + | "questions.subjectUnavailableHelp" | "questions.textRequired" | "questions.pointsRange" | "questions.choicesRange" + | "questions.correctRequired" | "questions.correctRange" - | "questions.correctBlanked" - | "questions.imagesLost" | "bank.title" | "bank.subtitle" | "bank.empty" @@ -444,7 +445,9 @@ export type MessageKey = | "bank.created" | "bank.copyNotice" | "bank.courseHint" - | "bank.choiceImagesWarning" + | "bank.courseSelect" + | "bank.courseUnavailable" + | "bank.targetSubjectHint" | "bank.fromBank" | "bank.pickTemplate" | "bank.targetSubject" @@ -456,10 +459,28 @@ export type MessageKey = | "bank.saveCopyBody" | "bank.saveCopyConfirm" | "bank.savedToBank" - | "bank.inBankBadge" + | "bank.fromBankBadge" + | "bank.savedToBankBadge" | "bank.search" | "bank.pickerEmpty" | "bank.noSubjects" + | "bank.countTotal" + | "bank.countShown" + | "bank.whoCanSee" + | "bank.onlyMe" + | "bank.sharedWithSchool" + | "bank.onlyMeHint" + | "bank.sharedWithSchoolHint" + | "bank.shareTitle" + | "bank.shareBody" + | "bank.shareConfirm" + | "bank.startsPrivate" + | "bank.usedInExams" + | "bank.refresh" + | "bank.refreshTitle" + | "bank.refreshBody" + | "bank.refreshConfirm" + | "bank.refreshed" | "subjects.title" | "subjects.item" | "subjects.subject" @@ -1416,12 +1437,13 @@ const en: Dict = { "questions.editDrawing": "Edit drawing", "questions.choiceImage": "Choice image", "questions.subjectRequired": "Select a subject for this question", + "questions.subjectUnavailable": "Current subject — no longer available to you", + "questions.subjectUnavailableHelp": "The subject saved on this question is not in the list you can pick from. Choose a subject from the list to save.", "questions.textRequired": "Question text is required", "questions.pointsRange": "Points must be an integer from 1 to 100", "questions.choicesRange": "Choice questions need 2–10 choices, each at most 500 characters", + "questions.correctRequired": "Mark one choice as the correct answer before saving.", "questions.correctRange": "Correct index must point to one of the choices", - "questions.correctBlanked": "The choice you marked correct is now empty. Type it back in, or mark another choice correct.", - "questions.imagesLost": "Saved, but the image for choice {options} could not be carried over the edit. Add it again.", "bank.title": "Question bank", "bank.subtitle": "Reusable question templates every teacher can use.", "bank.empty": "No templates yet.", @@ -1431,8 +1453,10 @@ const en: Dict = { "bank.mine": "Mine", "bank.created": "Created", "bank.copyNotice": "Adding a template to an exam makes a copy. Editing the template later does not change questions already added.", + "bank.courseSelect": "Select course", + "bank.courseUnavailable": "Original course — not one of your courses", + "bank.targetSubjectHint": "Pick the subject this copy belongs to in this exam.", "bank.courseHint": "Templates are tagged with a subject, so pick the course that subject belongs to. The template stays usable in every course.", - "bank.choiceImagesWarning": "Changing the choices clears the choice images stored on the server. Images for choices you keep are uploaded again, and you will be told if any could not be carried over.", "bank.fromBank": "Add from bank", "bank.pickTemplate": "Pick a template", "bank.targetSubject": "Subject in this exam", @@ -1441,13 +1465,31 @@ const en: Dict = { "bank.saveToBank": "Save to bank", "bank.saveCopyToBank": "Save another copy to bank", "bank.saveCopyTitle": "Save a second copy?", - "bank.saveCopyBody": "This question is already linked to a bank template. Saving creates a second, separate template instead of updating the existing one. The two copies are independent: editing one never changes the other.", + "bank.saveCopyBody": "This question is already linked to a bank template. Saving creates a second, separate template instead of updating the existing one. The two copies are independent: editing one never changes the other. The new template is private: only you can see it until you choose to share it.", "bank.saveCopyConfirm": "Save another copy", - "bank.savedToBank": "Question copied to the bank.", - "bank.inBankBadge": "In bank", - "bank.search": "Search templates", + "bank.savedToBank": "Question copied to the bank. Only you can see it until you share it.", + "bank.fromBankBadge": "Added from bank", + "bank.savedToBankBadge": "Saved to bank", + "bank.search": "Search question text", "bank.pickerEmpty": "No matching template.", "bank.noSubjects": "This exam's course has no subjects yet. Add a subject to the course first.", + "bank.countTotal": "{total} templates in total.", + "bank.countShown": "Showing {shown} of {total} — search to narrow it down.", + "bank.whoCanSee": "Who can see it", + "bank.onlyMe": "Only me", + "bank.sharedWithSchool": "Shared with the school", + "bank.onlyMeHint": "Only you can see this question and its answer. This is the safe choice.", + "bank.sharedWithSchoolHint": "Every teacher in the school can see this question and its correct answer.", + "bank.shareTitle": "Share this question with the whole school?", + "bank.shareBody": "Every teacher in the school will be able to see this question and its correct answer. If the question is on an exam that has not finished yet, they can see the answer before your students sit it. Other teachers can copy it into their own exams, and those copies stay with them even if you make the question private again or delete it. You cannot take a copy back.", + "bank.shareConfirm": "Yes, share it", + "bank.startsPrivate": "The saved template starts private: only you can see it until you choose to share it.", + "bank.usedInExams": "Copies in exams", + "bank.refresh": "Update from template", + "bank.refreshTitle": "Update this question from its template?", + "bank.refreshBody": "This question is a copy made from a bank template. Updating replaces its text, points, options, correct answer and pictures with what the template says today. Anything you changed on this copy is lost. It only works before anyone starts the exam, so no student's answers can be affected.", + "bank.refreshConfirm": "Yes, update it", + "bank.refreshed": "Question updated from its template.", "subjects.title": "Subjects", "subjects.item": "Subject", "subjects.subject": "Subject", @@ -2342,12 +2384,13 @@ const tr: Dict = { "questions.editDrawing": "Çizimi düzenle", "questions.choiceImage": "Seçenek görseli", "questions.subjectRequired": "Bu soru için konu seç", + "questions.subjectUnavailable": "Şu anki konu — artık sana açık değil", + "questions.subjectUnavailableHelp": "Bu soruda kayıtlı konu, seçebileceğin listede yok. Kaydetmek için listeden bir konu seç.", "questions.textRequired": "Soru metni gerekli", "questions.pointsRange": "Puan 1–100 arası tam sayı olmalı", "questions.choicesRange": "Seçmeli soruda 2–10 seçenek gerekir; her biri en fazla 500 karakter olmalı", + "questions.correctRequired": "Kaydetmeden önce bir seçeneği doğru cevap olarak işaretle.", "questions.correctRange": "Doğru indeks seçeneklerden birini göstermeli", - "questions.correctBlanked": "Doğru olarak işaretlediğin seçenek şu an boş. Metni tekrar yaz ya da başka bir seçeneği doğru işaretle.", - "questions.imagesLost": "Kaydedildi, ancak {options} seçeneğinin görseli bu düzenlemede taşınamadı. Görseli tekrar ekle.", "bank.title": "Soru bankası", "bank.subtitle": "Bütün öğretmenlerin kullanabildiği, yeniden kullanılabilir soru şablonları.", "bank.empty": "Henüz şablon yok.", @@ -2357,8 +2400,10 @@ const tr: Dict = { "bank.mine": "Benimkiler", "bank.created": "Eklenme", "bank.copyNotice": "Şablonu sınava eklemek bir kopya oluşturur. Şablonu sonradan düzenlemek, daha önce eklenmiş soruları değiştirmez.", + "bank.courseSelect": "Ders seç", + "bank.courseUnavailable": "Özgün ders — senin derslerinden değil", + "bank.targetSubjectHint": "Bu kopyanın bu sınavda hangi konuya gireceğini seç.", "bank.courseHint": "Şablonlar bir konuyla etiketlenir; o konunun bağlı olduğu dersi seç. Şablon yine de her derste kullanılabilir.", - "bank.choiceImagesWarning": "Seçenekleri değiştirmek, sunucudaki seçenek görsellerini siler. Koruduğun seçeneklerin görselleri yeniden yüklenir; taşınamayan olursa sana bildirilir.", "bank.fromBank": "Bankadan ekle", "bank.pickTemplate": "Şablon seç", "bank.targetSubject": "Bu sınavdaki konu", @@ -2367,13 +2412,31 @@ const tr: Dict = { "bank.saveToBank": "Bankaya kaydet", "bank.saveCopyToBank": "Bankaya yeni bir kopya kaydet", "bank.saveCopyTitle": "İkinci bir kopya kaydedilsin mi?", - "bank.saveCopyBody": "Bu soru bir banka şablonuna zaten bağlı. Kaydetmek mevcut şablonu güncellemez; bankada ikinci, ayrı bir şablon oluşturur. İki kopya birbirinden bağımsızdır: birini düzenlemek diğerini hiçbir zaman değiştirmez.", + "bank.saveCopyBody": "Bu soru bir banka şablonuna zaten bağlı. Kaydetmek mevcut şablonu güncellemez; bankada ikinci, ayrı bir şablon oluşturur. İki kopya birbirinden bağımsızdır: birini düzenlemek diğerini hiçbir zaman değiştirmez. Yeni şablon gizlidir: sen paylaşmayı seçene kadar onu yalnızca sen görebilirsin.", "bank.saveCopyConfirm": "Yeni kopya kaydet", - "bank.savedToBank": "Soru bankaya kopyalandı.", - "bank.inBankBadge": "Bankada", - "bank.search": "Şablonlarda ara", + "bank.savedToBank": "Soru bankaya kopyalandı. Sen paylaşana kadar onu yalnızca sen görebilirsin.", + "bank.fromBankBadge": "Bankadan eklendi", + "bank.savedToBankBadge": "Bankaya kaydedildi", + "bank.search": "Soru metninde ara", "bank.pickerEmpty": "Eşleşen şablon yok.", "bank.noSubjects": "Bu sınavın dersinde henüz konu yok. Önce derse bir konu ekle.", + "bank.countTotal": "Toplam {total} şablon.", + "bank.countShown": "{total} şablondan {shown} tanesi gösteriliyor — daraltmak için arama yap.", + "bank.whoCanSee": "Kimler görebilir", + "bank.onlyMe": "Yalnızca ben", + "bank.sharedWithSchool": "Okulla paylaşıldı", + "bank.onlyMeHint": "Bu soruyu ve cevabını yalnızca sen görebilirsin. Güvenli seçenek budur.", + "bank.sharedWithSchoolHint": "Okuldaki bütün öğretmenler bu soruyu ve doğru cevabını görebilir.", + "bank.shareTitle": "Bu soru bütün okulla paylaşılsın mı?", + "bank.shareBody": "Okuldaki bütün öğretmenler bu soruyu ve doğru cevabını görebilecek. Soru henüz bitmemiş bir sınavdaysa, öğrencilerin sınava girmeden önce cevabı görebilirler. Diğer öğretmenler soruyu kendi sınavlarına kopyalayabilir; sen soruyu sonradan yeniden gizlesen ya da silsen bile o kopyalar onlarda kalır. Alınan kopyaları geri alamazsın.", + "bank.shareConfirm": "Evet, paylaş", + "bank.startsPrivate": "Kaydedilen şablon gizli başlar: sen paylaşmayı seçene kadar onu yalnızca sen görebilirsin.", + "bank.usedInExams": "Sınavlardaki kopyalar", + "bank.refresh": "Şablondan güncelle", + "bank.refreshTitle": "Bu soru şablonundan güncellensin mi?", + "bank.refreshBody": "Bu soru, bir soru bankası şablonundan alınmış bir kopya. Güncellersen sorunun metni, puanı, seçenekleri, doğru cevabı ve resimleri şablonun bugünkü hâliyle değiştirilir. Bu kopyada yaptığın değişiklikler kaybolur. Bu işlem yalnızca sınava kimse başlamadan önce yapılabilir, bu yüzden hiçbir öğrencinin cevabı etkilenmez.", + "bank.refreshConfirm": "Evet, güncelle", + "bank.refreshed": "Soru şablonundan güncellendi.", "subjects.title": "Konular", "subjects.item": "Konu", "subjects.subject": "Konu", diff --git a/src/lib/answer-sheet.test.ts b/src/lib/answer-sheet.test.ts index 7f2d293..0f7dd33 100644 --- a/src/lib/answer-sheet.test.ts +++ b/src/lib/answer-sheet.test.ts @@ -10,8 +10,8 @@ function question(id: string, overrides: Partial = {}): ExamQuesti text: `Question ${id}`, kind: "choice", points: 10, - choices: ["a", "b"], - correct: 0, + choices: [{ id: "cA", text: "a" }, { id: "cB", text: "b" }], + correct: "cA", ...overrides, }; } @@ -19,7 +19,7 @@ function question(id: string, overrides: Partial = {}): ExamQuesti function answer(questionId: string, overrides: Partial = {}): StudentAnswer { return { question: questionId, - selected: 0, + selected: "cA", text: null, updated_at: 1, is_correct: true, @@ -30,11 +30,11 @@ function answer(questionId: string, overrides: Partial = {}): Stu test("pairs each question with its answer by id, keeping question order", () => { const rows = joinAnswerSheet( [question("q1"), question("q2")], - [answer("q2", { selected: 1, is_correct: false }), answer("q1")], + [answer("q2", { selected: "cB", is_correct: false }), answer("q1")], ); expect(rows.map((r) => r.question.id)).toEqual(["q1", "q2"]); expect(rows[0].answer?.is_correct).toBe(true); - expect(rows[1].answer?.selected).toBe(1); + expect(rows[1].answer?.selected).toBe("cB"); }); test("unanswered question yields a null answer", () => { diff --git a/src/lib/choice-compaction.test.ts b/src/lib/choice-compaction.test.ts deleted file mode 100644 index 7fd508d..0000000 --- a/src/lib/choice-compaction.test.ts +++ /dev/null @@ -1,57 +0,0 @@ -import { describe, expect, it } from "vitest"; -import { compactChoices, planChoiceImageRestore } from "./choice-compaction"; - -const meta = { content_type: "image/png", size: 1 }; -const noImages = (n: number) => Array.from({ length: n }, () => null); - -describe("compactChoices", () => { - it("keeps the answer on the same choice when a choice above it is blanked", () => { - // A B C D with D marked correct; the user blanks B. - const result = compactChoices(["A", "", "C", "D"], noImages(4), [0, 1, 2, 3], 3); - expect(result.choices).toEqual(["A", "C", "D"]); - expect(result.sources).toEqual([0, 2, 3]); - expect(result.correct).toBe(2); - expect(result.choices[result.correct]).toBe("D"); // same text the user picked - }); - - it("rejects the edit when the choice marked correct is the blanked one", () => { - const result = compactChoices(["A", "", "C"], noImages(3), [0, 1, 2], 1); - expect(result.correct).toBe(-1); - }); - - it("resolves an answer marked on a newly added row", () => { - // D was added in this edit (source -1) and marked correct; B was blanked. - const result = compactChoices(["A", "", "C", "D"], noImages(4), [0, 1, 2, -1], 3); - expect(result.correct).toBe(2); - expect(result.sources).toEqual([0, 2, -1]); - }); - - it("carries picked files with their choice and trims text", () => { - const file = new File([], "c.png"); - const result = compactChoices(["A", " ", " C "], [null, file, file], [0, 1, 2], 2); - expect(result.choices).toEqual(["A", "C"]); - expect(result.images).toEqual([null, file]); - expect(result.correct).toBe(1); - }); -}); - -describe("planChoiceImageRestore", () => { - it("restores to the post-compaction slot, not the original index", () => { - // A, B, C all had images; the user blanked B, so C survives as index 1. - const plan = planChoiceImageRestore([0, 2], [meta, meta, meta], null); - expect(plan).toEqual([ - { index: 0, source: 0 }, - { index: 1, source: 2 }, - ]); - // never plans an index past the choices that survived - expect(plan.every((slot) => slot.index < 2)).toBe(true); - }); - - it("skips new choices, imageless options, and options the user replaced", () => { - const replacements = [null, new File([], "b.png"), null]; - expect(planChoiceImageRestore([0, 1, -1], [meta, meta, null], replacements)).toEqual([ - { index: 0, source: 0 }, - ]); - expect(planChoiceImageRestore([0, 1], [null, null], null)).toEqual([]); - }); -}); diff --git a/src/lib/choice-compaction.ts b/src/lib/choice-compaction.ts deleted file mode 100644 index a33d8a0..0000000 --- a/src/lib/choice-compaction.ts +++ /dev/null @@ -1,54 +0,0 @@ -export type CompactedChoices = { - choices: string[]; - images: (File | null)[]; - /** Index each surviving choice had in the stored question, -1 if added in this edit. */ - sources: number[]; - /** Index of the correct choice after compaction, or -1 if that row was left blank. */ - correct: number; -}; - -/** - * Editing a question drops blank choices before submit, which shifts every index - * after the gap. Everything keyed by position — the answer key and the per-option - * images — has to move with it, so do the drop once, here, and hand back the - * already-shifted values. - */ -export function compactChoices( - choices: string[], - images: (File | null)[], - /** Original index per row as displayed, -1 for a row added in this edit. */ - sources: number[], - /** Row the user marked correct, as an index into `choices`. */ - correct: number, -): CompactedChoices { - const kept = choices - .map((choice, row) => ({ choice: choice.trim(), image: images[row] ?? null, source: sources[row] ?? -1, row })) - .filter((item) => item.choice); - return { - choices: kept.map((item) => item.choice), - images: kept.map((item) => item.image), - sources: kept.map((item) => item.source), - // Follow the row the user actually picked; -1 means they blanked it and must choose again. - correct: kept.findIndex((item) => item.row === correct), - }; -} - -/** - * A PATCH carrying `choices` deletes every stored option image server-side, so a - * choice edit has to re-upload the images the user kept. Blank choices are dropped - * on submit, so the option an image came from (its `source`) and the slot it must - * go back to (its new index) are different numbers — uploading to the old index - * either lands on the wrong option or is rejected as out of range. - */ -export function planChoiceImageRestore( - /** `QuestionValues.choice_sources`: original index per surviving choice, -1 if new. */ - sources: number[], - /** `choice_images` as stored on the server today, indexed by original position. */ - stored: (unknown | null)[], - /** Freshly picked files per surviving choice; a replaced option needs no restore. */ - replacements: (File | null)[] | null, -): { index: number; source: number }[] { - return sources - .map((source, index) => ({ index, source })) - .filter((slot) => slot.source >= 0 && stored[slot.source] != null && !replacements?.[slot.index]); -} diff --git a/src/lib/choice-set.property.test.ts b/src/lib/choice-set.property.test.ts new file mode 100644 index 0000000..5fd3760 --- /dev/null +++ b/src/lib/choice-set.property.test.ts @@ -0,0 +1,176 @@ +import fc from "fast-check"; +import { expect, test } from "vitest"; +import { + addChoice, + blankChoiceSet, + type ChoiceSet, + moveChoice, + removeChoice, + setChoiceImage, + setChoiceText, + setCorrect, + storedChoiceSet, + submitChoices, +} from "./choice-set"; + +/** + * The example tests pin down seven known edits. These generate the edits + * instead, because every bug this reducer exists to kill lived in a *relation* + * between values — a row, its picture, the answer key, a student's answer — + * and an example can only re-assert the author's own mental model of it. + * + * The one invariant, restated: anything attached to a row (text, picture, the + * correct mark) stays attached to that row's id across any sequence of edits. + */ + +const BASE32 = "0123456789ABCDEFGHJKMNPQRSTVWXYZ"; +const ulidArb = fc + .array(fc.constantFrom(...BASE32.split("")), { minLength: 26, maxLength: 26 }) + .map((chars) => chars.join("")); + +/** Blank, whitespace-only, duplicated and arbitrary texts all matter here. */ +const textArb = fc.oneof( + fc.constant(""), + fc.constant(" "), + fc.constant("dup"), + fc.string({ maxLength: 8 }), +); + +let stamped = 0; +const stampFile = () => ({ name: `f${(stamped += 1)}` }) as unknown as File; + +type Op = + | { t: "add" } + | { t: "remove"; p: number } + | { t: "move"; p: number; q: number } + | { t: "text"; p: number; text: string } + | { t: "image"; p: number; keep: boolean } + | { t: "correct"; p: number } + | { t: "correctUnknown"; id: string }; + +const pick = fc.double({ min: 0, max: 0.999, noNaN: true }); +const opArb: fc.Arbitrary = fc.oneof( + fc.constant({ t: "add" }), + fc.record({ t: fc.constant<"remove">("remove"), p: pick }), + fc.record({ t: fc.constant<"move">("move"), p: pick, q: pick }), + fc.record({ t: fc.constant<"text">("text"), p: pick, text: textArb }), + fc.record({ t: fc.constant<"image">("image"), p: pick, keep: fc.boolean() }), + fc.record({ t: fc.constant<"correct">("correct"), p: pick }), + fc.record({ t: fc.constant<"correctUnknown">("correctUnknown"), id: fc.oneof(ulidArb, fc.constant("new:0")) }), +); + +/** Starting points: fresh forms, stored questions, empty sets, sets at max. */ +const startArb = fc.integer({ min: 2, max: 10 }).chain((max) => + fc.oneof( + fc.integer({ min: 0, max }).map((n) => ({ max, set: blankChoiceSet(n) })), + fc + .uniqueArray(fc.record({ id: ulidArb, text: textArb }), { maxLength: max, selector: (c) => c.id }) + .chain((choices) => + (choices.length ? fc.option(fc.constantFrom(...choices.map((c) => c.id)), { nil: null }) : fc.constant(null)) + .map((correct) => ({ max, set: storedChoiceSet(choices, correct) })), + ), + ), +); + +const ids = (set: ChoiceSet) => set.rows.map((row) => row.id); +const at = (set: ChoiceSet, p: number) => (set.rows.length ? set.rows[Math.floor(p * set.rows.length)].id : "absent"); + +/** Apply one op and return it plus the id it was allowed to touch (if any). */ +function apply(set: ChoiceSet, op: Op, max: number): { next: ChoiceSet; touched: string | null } { + switch (op.t) { + case "add": + return { next: addChoice(set, max), touched: null }; + case "remove": + return { next: removeChoice(set, at(set, op.p)), touched: at(set, op.p) }; + case "move": + return { next: moveChoice(set, at(set, op.p), Math.floor(op.q * Math.max(set.rows.length, 1))), touched: null }; + case "text": + return { next: setChoiceText(set, at(set, op.p), op.text), touched: at(set, op.p) }; + case "image": + return { next: setChoiceImage(set, at(set, op.p), op.keep ? stampFile() : null), touched: at(set, op.p) }; + case "correct": + return { next: setCorrect(set, at(set, op.p)), touched: null }; + case "correctUnknown": + return { next: setCorrect(set, op.id), touched: null }; + } +} + +test("every edit sequence keeps text, picture and answer key attached to their row id", () => { + fc.assert( + fc.property(startArb, fc.array(opArb, { maxLength: 25 }), ({ max, set: start }, ops) => { + let set = start; + for (const op of ops) { + const before = set; + const { next, touched } = apply(set, op, max); + set = next; + + // Ids are unique at all times, and the row count never exceeds max. + expect(new Set(ids(set)).size).toBe(set.rows.length); + expect(set.rows.length).toBeLessThanOrEqual(max); + + // No op invents or duplicates an id: add appends exactly one new id, + // remove drops exactly the targeted one, everything else permutes. + const gained = ids(set).filter((id) => !ids(before).includes(id)); + const lost = ids(before).filter((id) => !ids(set).includes(id)); + expect(gained.length).toBe(op.t === "add" && before.rows.length < max ? 1 : 0); + expect(lost).toEqual(op.t === "remove" && ids(before).includes(touched!) ? [touched] : []); + + // The attachment invariant: a surviving row the op did not target keeps + // its exact text and its exact File object, whatever moved around it. + for (const row of set.rows) { + const was = before.rows.find((r) => r.id === row.id); + if (!was || row.id === touched) continue; + expect(row.text).toBe(was.text); + expect(row.image).toBe(was.image); + } + + // `correct` only ever names a live row (or nothing) — never an index, + // never a removed row. + if (set.correct !== null) expect(ids(set)).toContain(set.correct); + } + + const out = submitChoices(set); + const outIds = out.choices.map((c) => c.id); + + // Output is a subset of the live rows, in row order, no id invented or + // duplicated, and it is exactly the non-blank rows. + expect(new Set(outIds).size).toBe(outIds.length); + expect(outIds).toEqual(ids(set).filter((id) => set.rows.find((r) => r.id === id)!.text.trim())); + for (const [i, choice] of out.choices.entries()) { + const row = set.rows.find((r) => r.id === choice.id)!; + expect(choice.text).toBe(row.text.trim()); + // The picture rides the id, not the position, after blanks are dropped. + expect(out.images[i]).toBe(row.image); + } + + // The answer key survives the drop iff its row survived it. + const marked = set.rows.find((r) => r.id === set.correct); + expect(out.correct).toBe(marked && marked.text.trim() ? set.correct : null); + if (out.correct !== null) expect(outIds).toContain(out.correct); + }), + { numRuns: 500 }, + ); +}); + +test("reordering is invisible on the wire: same rows, same pictures, same answer key", () => { + fc.assert( + fc.property(startArb, fc.array(fc.record({ p: pick, q: pick }), { maxLength: 15 }), ({ set: start }, moves) => { + // Give every row a distinguishable picture so a positional mix-up shows. + let set = start.rows.reduce((acc, row) => setChoiceImage(acc, row.id, stampFile()), start); + const before = submitChoices(set); + for (const move of moves) { + set = moveChoice(set, at(set, move.p), Math.floor(move.q * Math.max(set.rows.length, 1))); + } + const after = submitChoices(set); + + expect(after.correct).toBe(before.correct); + expect([...after.choices].sort((a, b) => a.id.localeCompare(b.id))).toEqual( + [...before.choices].sort((a, b) => a.id.localeCompare(b.id)), + ); + // Each id keeps its own File across the reordering. + const pairs = (out: typeof before) => out.choices.map((c, i) => [c.id, out.images[i]] as const); + expect(new Map(pairs(after))).toEqual(new Map(pairs(before))); + }), + { numRuns: 300 }, + ); +}); diff --git a/src/lib/choice-set.test.ts b/src/lib/choice-set.test.ts new file mode 100644 index 0000000..ec7b5ae --- /dev/null +++ b/src/lib/choice-set.test.ts @@ -0,0 +1,61 @@ +import { expect, test } from "vitest"; +import { + addChoice, + blankChoiceSet, + moveChoice, + newChoiceId, + removeChoice, + setChoiceText, + setCorrect, + storedChoiceSet, + submitChoices, +} from "./choice-set"; + +const stored = () => + storedChoiceSet([{ id: "A", text: "one" }, { id: "B", text: "two" }, { id: "C", text: "three" }], "B"); + +test("a fresh set pre-marks nothing", () => { + const set = blankChoiceSet(); + expect(set.rows).toHaveLength(4); + expect(set.correct).toBeNull(); + expect(new Set(set.rows.map((r) => r.id)).size).toBe(4); +}); + +test("minted ids are unique and cannot collide with a stored ULID", () => { + expect(newChoiceId()).not.toBe(newChoiceId()); + expect(newChoiceId()).toContain(":"); // ':' is not in Crockford base32 +}); + +test("dropping a blank row leaves the marked row's id untouched", () => { + const set = setChoiceText(stored(), "A", " "); + expect(submitChoices(set)).toEqual({ + choices: [{ id: "B", text: "two" }, { id: "C", text: "three" }], + images: [null, null], + correct: "B", + }); +}); + +test("reordering carries ids, so the answer key follows its choice", () => { + const moved = moveChoice(stored(), "B", 2); + expect(moved.rows.map((r) => r.id)).toEqual(["A", "C", "B"]); + expect(submitChoices(moved).correct).toBe("B"); +}); + +test("removing or blanking the marked row unmarks it instead of shifting the key", () => { + expect(removeChoice(stored(), "B").correct).toBeNull(); + expect(submitChoices(setChoiceText(stored(), "B", "")).correct).toBeNull(); +}); + +test("a new row is markable, because it carries a client-minted key", () => { + const added = addChoice(stored(), 10); + const fresh = added.rows[3].id; + const marked = setChoiceText(setCorrect(added, fresh), fresh, "four"); + const out = submitChoices(marked); + expect(out.correct).toBe(fresh); + expect(out.choices.map((c) => c.id)).toContain(fresh); +}); + +test("add respects the max and setCorrect ignores an unknown id", () => { + expect(addChoice(blankChoiceSet(10), 10).rows).toHaveLength(10); + expect(setCorrect(stored(), "nope").correct).toBe("B"); +}); diff --git a/src/lib/choice-set.ts b/src/lib/choice-set.ts new file mode 100644 index 0000000..d9f52d2 --- /dev/null +++ b/src/lib/choice-set.ts @@ -0,0 +1,86 @@ +import type { Choice } from "@/api/client"; + +/** One editable choice row: a stable key, its text, and a not-yet-uploaded image. */ +export type ChoiceRow = Choice & { image: File | null }; + +/** The whole choices region of the question form. `correct` names a row by id. */ +export type ChoiceSet = { + rows: ChoiceRow[]; + correct: string | null; +}; + +let minted = 0; + +/** + * Key for a row the server has never seen. The server keeps any submitted key it + * already stores and treats every other key as a new option, so this only has to + * be unique within one payload — and `correct` can name a brand-new row with it. + * `:` is not in Crockford base32, so it can never collide with a stored ULID. + */ +export function newChoiceId(): string { + minted += 1; + return `new:${minted}`; +} + +export function blankChoiceSet(count = 4): ChoiceSet { + return { rows: Array.from({ length: count }, () => ({ id: newChoiceId(), text: "", image: null })), correct: null }; +} + +/** Edit an existing question: stored ids come along, so images stay attached. */ +export function storedChoiceSet(choices: Choice[] | null | undefined, correct: string | null | undefined): ChoiceSet { + if (!choices) return blankChoiceSet(); + return { + rows: choices.map((choice) => ({ id: choice.id, text: choice.text, image: null })), + correct: correct ?? null, + }; +} + +export function addChoice(set: ChoiceSet, max: number): ChoiceSet { + if (set.rows.length >= max) return set; + return { ...set, rows: [...set.rows, { id: newChoiceId(), text: "", image: null }] }; +} + +/** Removing the marked row unmarks it — there is no neighbouring index to fall back to. */ +export function removeChoice(set: ChoiceSet, id: string): ChoiceSet { + return { + rows: set.rows.filter((row) => row.id !== id), + correct: set.correct === id ? null : set.correct, + }; +} + +export function setChoiceText(set: ChoiceSet, id: string, text: string): ChoiceSet { + return { ...set, rows: set.rows.map((row) => (row.id === id ? { ...row, text } : row)) }; +} + +export function setChoiceImage(set: ChoiceSet, id: string, image: File | null): ChoiceSet { + return { ...set, rows: set.rows.map((row) => (row.id === id ? { ...row, image } : row)) }; +} + +export function setCorrect(set: ChoiceSet, id: string): ChoiceSet { + return set.rows.some((row) => row.id === id) ? { ...set, correct: id } : set; +} + +/** Move a row to another position; ids travel with their text, image and mark. */ +export function moveChoice(set: ChoiceSet, id: string, to: number): ChoiceSet { + const from = set.rows.findIndex((row) => row.id === id); + if (from < 0 || to < 0 || to >= set.rows.length || to === from) return set; + const rows = [...set.rows]; + const [row] = rows.splice(from, 1); + rows.splice(to, 0, row); + return { ...set, rows }; +} + +/** + * What actually goes on the wire: blank rows dropped, ids kept. Every row carries + * a key, so the server re-attaches each surviving option's picture itself — no + * index bookkeeping, no download-and-reupload. `correct` is null when the marked + * row was left blank or never picked; the caller reports that to the user. + */ +export function submitChoices(set: ChoiceSet): { choices: Choice[]; images: (File | null)[]; correct: string | null } { + const kept = set.rows.map((row) => ({ ...row, text: row.text.trim() })).filter((row) => row.text); + return { + choices: kept.map((row) => ({ id: row.id, text: row.text })), + images: kept.map((row) => row.image), + correct: kept.some((row) => row.id === set.correct) ? set.correct : null, + }; +} diff --git a/src/lib/create-debounced-signal.test.ts b/src/lib/create-debounced-signal.test.ts new file mode 100644 index 0000000..e067794 --- /dev/null +++ b/src/lib/create-debounced-signal.test.ts @@ -0,0 +1,49 @@ +import { createRoot } from "solid-js"; +import { createDebouncedSignal } from "./create-debounced-signal"; + +describe("createDebouncedSignal", () => { + beforeEach(() => vi.useFakeTimers()); + afterEach(() => vi.useRealTimers()); + + it("updates raw at once and the debounced copy only after the delay", () => { + createRoot((dispose) => { + const [raw, set, debounced] = createDebouncedSignal("", 300); + set("ne"); + expect(raw()).toBe("ne"); + expect(debounced()).toBe(""); + vi.advanceTimersByTime(299); + expect(debounced()).toBe(""); + vi.advanceTimersByTime(1); + expect(debounced()).toBe("ne"); + dispose(); + }); + }); + + it("keeps only the last keystroke when typing faster than the delay", () => { + createRoot((dispose) => { + const values: string[] = []; + const [, set, debounced] = createDebouncedSignal("", 300); + set("n"); + vi.advanceTimersByTime(100); + set("ne"); + vi.advanceTimersByTime(100); + set("newton"); + vi.advanceTimersByTime(300); + values.push(debounced()); + expect(values).toEqual(["newton"]); + dispose(); + }); + }); + + it("cancels a pending update when the owner disposes", () => { + let read = () => ""; + createRoot((dispose) => { + const [, set, debounced] = createDebouncedSignal("", 300); + read = debounced; + set("newton"); + dispose(); + }); + vi.advanceTimersByTime(500); + expect(read()).toBe(""); + }); +}); diff --git a/src/lib/create-debounced-signal.ts b/src/lib/create-debounced-signal.ts new file mode 100644 index 0000000..f4ef267 --- /dev/null +++ b/src/lib/create-debounced-signal.ts @@ -0,0 +1,18 @@ +import { createSignal, onCleanup } from "solid-js"; + +/** + * Text input signal plus a copy that only catches up `delay` ms after typing + * stops — bind the raw one to the input, the debounced one to the query params. + */ +export function createDebouncedSignal(initial = "", delay = 300) { + const [raw, setRaw] = createSignal(initial); + const [debounced, setDebounced] = createSignal(initial); + let timer: ReturnType | undefined; + const set = (value: string) => { + setRaw(value); + clearTimeout(timer); + timer = setTimeout(() => setDebounced(value), delay); + }; + onCleanup(() => clearTimeout(timer)); + return [raw, set, debounced] as const; +} diff --git a/src/pages/question-bank-page.tsx b/src/pages/question-bank-page.tsx index c55d734..3a0ce95 100644 --- a/src/pages/question-bank-page.tsx +++ b/src/pages/question-bank-page.tsx @@ -2,8 +2,6 @@ import { Show, Suspense, createMemo, createResource, createSignal } from "solid- import type { ColumnDef } from "@tanstack/solid-table"; import { deleteBankQuestionById, getBankQuestions } from "@/api/bank-questions"; import { getCourses } from "@/api/courses"; -import { getSubjectById } from "@/api/subjects"; -import { getUserById } from "@/api/users"; import { formatApiError } from "@/api/client"; import type { BankQuestion } from "@/api/client"; import { BankQuestionForm } from "@/components/exams/bank-question-form"; @@ -13,10 +11,11 @@ import { Badge } from "@/components/ui/badge"; import { Button } from "@/components/ui/button"; import { ConfirmDialog } from "@/components/ui/confirm-dialog"; import { DataTable, DataTableSkeleton } from "@/components/ui/data-table"; -import { IconEdit, IconPlus, IconTrash } from "@/components/ui/icons"; +import { IconEdit, IconEyeOff, IconPlus, IconTrash, IconUsers } from "@/components/ui/icons"; import { DropdownSelect } from "@/components/ui/select"; import { SidePanel } from "@/components/ui/side-panel"; import { TableRowActions } from "@/components/ui/table-row-actions"; +import { createDebouncedSignal } from "@/lib/create-debounced-signal"; import { createFlash } from "@/lib/flash"; import { formatDate } from "@/lib/format"; import { hasMinRole } from "@/lib/roles"; @@ -39,48 +38,44 @@ function QuestionBankContent() { const { locale } = usePreferences(); const [ownerFilter, setOwnerFilter] = createSignal<"all" | "me">("all"); const [subjectFilter, setSubjectFilter] = createSignal("all"); + const [visibilityFilter, setVisibilityFilter] = createSignal<"all" | "private" | "school">("all"); + const [page, setPage] = createSignal(0); + const [query, setQuery, debouncedQuery] = createDebouncedSignal(); const [createOpen, setCreateOpen] = createSignal(false); const [editing, setEditing] = createSignal(null); const [removing, setRemoving] = createSignal(null); + // ponytail: the subject dropdown lists the subjects seen while browsing — the + // backend has no "all subjects" endpoint. Widen once one exists. const [subjectNames, setSubjectNames] = createSignal>({}); - const [ownerNames, setOwnerNames] = createSignal>({}); const [flash, setFlash] = createFlash(); const [error, setError] = createSignal(""); - // ponytail: first 100 templates per filter — matches how the other list pages - // page client-side. Move to `manualPagination` once a school outgrows it. const [list, { refetch }] = createResource( - () => ({ owner: ownerFilter(), subject: subjectFilter() }), + () => ({ + page: page(), + owner: ownerFilter(), + subject: subjectFilter(), + visibility: visibilityFilter(), + q: debouncedQuery().trim(), + }), async (filters) => { - const items = ( - await getBankQuestions({ - limit: 100, - ...(filters.owner === "me" ? { owner: "me" } : {}), - ...(filters.subject !== "all" ? { subject: filters.subject } : {}), - }) - ).items; - const subjects = [...new Set(items.map((item) => item.subject))].filter((id) => !subjectNames()[id]); - const owners = [...new Set(items.map((item) => item.owner))].filter((id) => !ownerNames()[id]); - await Promise.all([ - ...subjects.map((id) => - getSubjectById(id) - .then((subject) => setSubjectNames((current) => ({ ...current, [id]: subject.name }))) - .catch(() => {}), - ), - ...owners.map((id) => - getUserById(id) - .then((user) => - setOwnerNames((current) => ({ - ...current, - [id]: [user.name, user.surname].filter(Boolean).join(" ") || user.username, - })), - ) - .catch(() => {}), - ), - ]); - return items; + const result = await getBankQuestions({ + limit: BANK_PAGE_SIZE, + offset: filters.page * BANK_PAGE_SIZE, + ...(filters.owner === "me" ? { owner: "me" } : {}), + ...(filters.subject !== "all" ? { subject: filters.subject } : {}), + ...(filters.visibility !== "all" ? { visibility: filters.visibility } : {}), + ...(filters.q ? { q: filters.q } : {}), + }); + setSubjectNames((current) => { + const next = { ...current }; + for (const item of result.items) if (item.subject) next[item.subject] = item.subject_name; + return next; + }); + return result; }, ); + const total = () => list.latest?.total ?? 0; // Only courses the teacher can author in supply subjects for a new template. const [courses] = createResource(async () => (await getCourses({ limit: 100 })).items); @@ -96,17 +91,9 @@ function QuestionBankContent() { }), ); - const subjectName = (id: string) => subjectNames()[id] ?? id; - const ownerName = (id: string) => ownerNames()[id] ?? id; const canEdit = (question: BankQuestion) => question.owner === auth.user()?.id || hasMinRole(auth.user()?.role, "admin"); - const searchTemplate = (question: BankQuestion, query: string) => - [question.text, subjectName(question.subject), ownerName(question.owner)] - .join(" ") - .toLocaleLowerCase(locale()) - .includes(query.toLocaleLowerCase(locale())); - const columns = createMemo[]>(() => [ { accessorKey: "text", @@ -130,16 +117,47 @@ function QuestionBankContent() { }, { id: "subject", - accessorFn: (question) => subjectName(question.subject), + accessorFn: (question) => question.subject_name, header: t("subjects.subject"), meta: { cellClass: "truncate text-muted-foreground" }, }, + { + id: "visibility", + accessorFn: (question) => question.visibility, + header: t("bank.whoCanSee"), + meta: { headerClass: "text-center", cellClass: "text-center" }, + cell: (cell) => ( + + + {t("bank.onlyMe")} + + } + > + + + {t("bank.sharedWithSchool")} + + + ), + }, { id: "owner", - accessorFn: (question) => ownerName(question.owner), + accessorFn: (question) => question.owner_name, header: t("bank.owner"), meta: { cellClass: "truncate text-muted-foreground" }, }, + { + id: "used", + accessorFn: (question) => question.used_count, + header: t("bank.usedInExams"), + meta: { headerClass: "text-center", cellClass: "mono text-center text-muted-foreground" }, + // A template nobody copied stays blank: "0" is noise on a page where + // most rows are fresh. + cell: (cell) => 0}>{cell.row.original.used_count}, + }, { accessorKey: "created_at", header: t("bank.created"), @@ -188,13 +206,13 @@ function QuestionBankContent() {
    - }> + }> {formatApiError(list.error)} 0}>