forge
Explore
Log in

Don't you dare go Hollow

🎬 draw-and-replay for question-pool photos, DPR-correct playback

Browse files at this commit

0fbb97c415e59f50bad31dfb0a9f69cb5b8a39a4Ahmet Kaan GümüşParent: 595aa7e
  • feat
    • 🎬 draw-and-replay for question-pool photos, DPR-correct playback
Show full message
feat: 🎬 draw-and-replay for question-pool photos, DPR-correct playback

- ask/solution forms gain a draw option alongside the existing file
  input, not instead of it: photographing a textbook problem is still
  the common case, drawing is now just another way to fill the same
  photo field
- both pool photo displays (question and solution) are now replayable
  the same way a student's answer drawing already was, via new
  getQuestionImageBlob/getSolutionImageBlob blobClient fetchers
- the img/playback toggle used to live inline in answer-sheet-view's
  AnswerDrawing; pulled out to a shared ReplayableImage (its third call
  site) so the pool views reuse it instead of a copy, and DrawingPlayback
  moved from components/exams to components/ui since it's no longer
  exam-only
- fixed a DPR mismatch in playback: an exported PNG bakes its pixel
  dimensions at the author's device-pixel-ratio, but the scene JSON only
  carried world (DPR-free) width/height, so replay on a viewer with a
  different ratio than the author rendered at half or double the
  correct size. DrawScene now carries the export's dpr, DrawCanvas
  stamps it when exporting, and a shared canvasPx() sizes both the
  export canvas and the playback canvas off the same number
- hardened parseScene's bounds: the scene JSON is recovered from a
  user-uploaded PNG's tEXt chunk and its w/h/dpr size a canvas
  allocation on the viewer's machine, so all three are now range-checked
  (0 < w,h <= 16384, 0 < dpr <= 8) instead of just type-checked
- regression tests for the bounds, canvasPx, and the new blob fetchers
src/api/__tests__/exams/exam-results.test.tsmodified+14 -2
@@ -4,8 +4,8 @@ import { getExamResult } from "../../exams";
44 import { postExamResult } from "../../exams";
55 import { deleteExamResultByUserId } from "../../exams";
66 import { getExamStatistics } from "../../exams";
7-import { getStudentAnswers } from "../../exams";
8-import { lastFetchCall, mockFetch204, mockFetchSuccess } from "../helpers/mock-fetch";
7+import { getStudentAnswers, getStudentAnswerImage } from "../../exams";
8+import { lastFetchCall, mockFetch204, mockFetchBlob, mockFetchSuccess } from "../helpers/mock-fetch";
99
1010 describe("exams API - results", () => {
1111 afterEach(() => {
@@ -83,4 +83,16 @@ describe("exams API - results", () => {
8383 expect(url).toBe("/api/exams/ex1/attempts/u1/answers");
8484 expect(init?.method).toBe("GET");
8585 });
86+
87+ it("getStudentAnswerImage calls the grader answer-image URL with the API prefix applied once", async () => {
88+ mockFetchBlob(new Blob([new Uint8Array([0x89, 0x50, 0x4e, 0x47])], { type: "image/png" }));
89+
90+ const result = await getStudentAnswerImage("ex1", "u1", "q1");
91+ expect(result).toBeInstanceOf(Blob);
92+
93+ // Must match the hardcoded <img src> template in answer-sheet-view.tsx exactly, or
94+ // "Play drawing" fetches different bytes than the static image already on screen.
95+ const [url] = lastFetchCall();
96+ expect(url).toBe("/api/exams/ex1/attempts/u1/answers/q1/image");
97+ });
8698 });
src/api/__tests__/questions/questions.test.tsmodified+12 -2
@@ -1,6 +1,6 @@
11 import { afterEach, describe, expect, it, vi } from "vitest";
2-import { getQuestions, getQuestionById, postQuestion, postQuestionApprove, deleteQuestionById, getQuestionImageUrl } from "../../shared";
3-import { lastFetchCall, mockFetch204, mockFetchSuccess } from "../helpers/mock-fetch";
2+import { getQuestions, getQuestionById, postQuestion, postQuestionApprove, deleteQuestionById, getQuestionImageUrl, getQuestionImageBlob } from "../../shared";
3+import { lastFetchCall, mockFetch204, mockFetchBlob, mockFetchSuccess } from "../helpers/mock-fetch";
44
55 describe("questions API", () => {
66 afterEach(() => {
@@ -72,4 +72,14 @@ describe("questions API", () => {
7272 const url = getQuestionImageUrl("q1");
7373 expect(url).toBe("/api/questions/q1/image");
7474 });
75+
76+ it("getQuestionImageBlob fetches the image bytes from the same URL", async () => {
77+ mockFetchBlob(new Blob([new Uint8Array([0x89, 0x50, 0x4e, 0x47])], { type: "image/png" }));
78+
79+ const result = await getQuestionImageBlob("q1");
80+ expect(result).toBeInstanceOf(Blob);
81+
82+ const [url] = lastFetchCall();
83+ expect(url).toBe(getQuestionImageUrl("q1"));
84+ });
7585 });
src/api/__tests__/questions/solutions.test.tsmodified+12 -2
@@ -1,6 +1,6 @@
11 import { afterEach, describe, expect, it, vi } from "vitest";
2-import { getSolutions, postSolution, patchSolutionById, deleteSolutionById, getSolutionImageUrl } from "../../shared";
3-import { lastFetchCall, mockFetch204, mockFetchSuccess } from "../helpers/mock-fetch";
2+import { getSolutions, postSolution, patchSolutionById, deleteSolutionById, getSolutionImageUrl, getSolutionImageBlob } from "../../shared";
3+import { lastFetchCall, mockFetch204, mockFetchBlob, mockFetchSuccess } from "../helpers/mock-fetch";
44
55 describe("solutions API", () => {
66 afterEach(() => {
@@ -61,4 +61,14 @@ describe("solutions API", () => {
6161 const url = getSolutionImageUrl("q1", "s1");
6262 expect(url).toBe("/api/questions/q1/solutions/s1/image");
6363 });
64+
65+ it("getSolutionImageBlob fetches the image bytes from the same URL", async () => {
66+ mockFetchBlob(new Blob([new Uint8Array([0x89, 0x50, 0x4e, 0x47])], { type: "image/png" }));
67+
68+ const result = await getSolutionImageBlob("q1", "s1");
69+ expect(result).toBeInstanceOf(Blob);
70+
71+ const [url] = lastFetchCall();
72+ expect(url).toBe(getSolutionImageUrl("q1", "s1"));
73+ });
6474 });
src/api/shared/questions.tsmodified+6 -1
@@ -1,4 +1,4 @@
1-import { client, formClient } from "../client";
1+import { blobClient, client, formClient } from "../client";
22 import type { Page, PageParams } from "../client";
33 import type { PersonRef } from "../client";
44
@@ -74,3 +74,8 @@ export async function deleteQuestionById(id: string): Promise<void> {
7474 export function getQuestionImageUrl(id: string): string {
7575 return `/api/questions/${id}/image`;
7676 }
77+
78+/** Raw bytes of the same image β€” needed to recover an embedded drawing scene. */
79+export function getQuestionImageBlob(id: string, signal?: AbortSignal): Promise<Blob> {
80+ return blobClient(`/questions/${id}/image`, signal);
81+}
src/api/shared/solutions.tsmodified+6 -1
@@ -1,4 +1,4 @@
1-import { client, formClient } from "../client";
1+import { blobClient, client, formClient } from "../client";
22 import type { Page, PageParams } from "../client";
33 import type { PersonRef } from "../client";
44
@@ -70,3 +70,8 @@ export async function deleteSolutionById(id: string, sid: string): Promise<void>
7070 export function getSolutionImageUrl(id: string, sid: string): string {
7171 return `/api/questions/${id}/solutions/${sid}/image`;
7272 }
73+
74+/** Raw bytes of the same image β€” needed to recover an embedded drawing scene. */
75+export function getSolutionImageBlob(id: string, sid: string, signal?: AbortSignal): Promise<Blob> {
76+ return blobClient(`/questions/${id}/solutions/${sid}/image`, signal);
77+}
src/components/exams/answer-sheet-view.tsxmodified+9 -65
@@ -1,79 +1,17 @@
1-import { For, Show, Suspense, createResource, createSignal, lazy } from "solid-js";
1+import { For, Show, Suspense, createResource } from "solid-js";
22 import { ApiError } from "@/api/client";
33 import { getExamQuestions } from "@/api/exams";
44 import { getStudentAnswers, getStudentAnswerImage } from "@/api/exams";
55 import type { StudentAnswerSheet } from "@/api/client";
66 import { Badge } from "@/components/ui/badge";
7-import { Button } from "@/components/ui/button";
87 import { IconCheck, IconX } from "@/components/ui/icons";
98 import { PageSpinner } from "@/components/ui/page-spinner";
9+import { ReplayableImage } from "@/components/ui/replayable-image";
1010 import { cn } from "@/lib/cn";
1111 import { joinAnswerSheet } from "@/lib/answer-sheet";
12-import { pngBytesToScene } from "@/lib/drawing-file";
13-import type { DrawScene } from "@/lib/draw-stroke";
1412 import { personLabelWithId } from "@/lib/person";
1513 import { useT } from "@/stores/preferences-context";
1614
17-const DrawingPlayback = lazy(() => import("@/components/exams/drawing-playback").then((m) => ({ default: m.DrawingPlayback })));
18-
19-/**
20- * A student's answer image with optional stroke-by-stroke playback. Defaults to the
21- * static <img>; "Play drawing" fetches the PNG, recovers its embedded scene, and swaps
22- * in the replay. A plain image (no embedded strokes) falls back to the img and drops
23- * the button β€” nothing to replay.
24- */
25-function AnswerDrawing(props: { examId: string; userId: string; questionId: string }) {
26- const t = useT();
27- const imgSrc = `/api/exams/${props.examId}/attempts/${props.userId}/answers/${props.questionId}/image`;
28- const [scene, setScene] = createSignal<DrawScene | null>(null);
29- const [mode, setMode] = createSignal<"image" | "loading" | "playback" | "plain">("image");
30-
31- const enterPlayback = async () => {
32- if (scene()) {
33- setMode("playback");
34- return;
35- }
36- setMode("loading");
37- try {
38- const blob = await getStudentAnswerImage(props.examId, props.userId, props.questionId);
39- const parsed = pngBytesToScene(new Uint8Array(await blob.arrayBuffer()));
40- if (parsed && parsed.strokes.length > 0) {
41- setScene(parsed);
42- setMode("playback");
43- } else {
44- setMode("plain"); // plain image or no strokes β†’ keep the img, hide Play
45- }
46- } catch {
47- setMode("image"); // fetch failed β†’ keep the img, allow a retry
48- }
49- };
50-
51- return (
52- <div class="mt-3 space-y-2">
53- {/* local boundary: the lazy playback chunk must not suspend the whole answer sheet */}
54- <Suspense fallback={<div class="h-64 w-full max-w-2xl rounded-md border bg-background" />}>
55- <Show
56- when={mode() === "playback" && scene()}
57- fallback={<img src={imgSrc} alt={t("exams.drawAnswer")} class="h-64 w-full max-w-2xl rounded-md border bg-background object-contain" />}
58- >
59- {(s) => <DrawingPlayback scene={s()} />}
60- </Show>
61- </Suspense>
62- <Show when={mode() !== "plain"}>
63- <Button
64- type="button"
65- variant="outline"
66- size="sm"
67- disabled={mode() === "loading"}
68- onClick={() => (mode() === "playback" ? setMode("image") : void enterPlayback())}
69- >
70- {mode() === "playback" ? t("exams.showImage") : t("exams.playDrawing")}
71- </Button>
72- </Show>
73- </div>
74- );
75-}
76-
7715 export function AnswerSheetView(props: { examId: string; userId: string }) {
7816 const t = useT();
7917 const [data] = createResource(
@@ -145,7 +83,13 @@ export function AnswerSheetView(props: { examId: string; userId: string }) {
14583 <p class="text-xs text-muted-foreground">{t("exams.textAnswer")}</p>
14684 <p class="mt-1 whitespace-pre-wrap text-sm">{row.answer?.text || "β€”"}</p>
14785 <Show when={row.answer?.answer_image}>
148- <AnswerDrawing examId={d().sheet.exam} userId={d().sheet.user.id} questionId={row.question.id} />
86+ <ReplayableImage
87+ class="mt-3"
88+ fetchBlob={() => getStudentAnswerImage(d().sheet.exam, d().sheet.user.id, row.question.id)}
89+ src={`/api/exams/${d().sheet.exam}/attempts/${d().sheet.user.id}/answers/${row.question.id}/image`}
90+ alt={t("exams.drawAnswer")}
91+ imgClass="h-64 w-full max-w-2xl rounded-md border bg-background object-contain"
92+ />
14993 </Show>
15094 </div>
15195 }
src/components/ui/draw-canvas.tsxmodified+6 -4
@@ -2,7 +2,7 @@ import { For, Match, Show, Switch, createEffect, createSignal, onCleanup, onMoun
22 import { Button } from "@/components/ui/button";
33 import { IconDownload, IconEdit, IconEraser, IconGrid, IconMove, IconRuled, IconSave, IconSquareOff, IconTrash, IconUndo, IconZoomIn, IconZoomOut } from "@/components/ui/icons";
44 import { cn } from "@/lib/cn";
5-import { PAPER_CELL, PAPER_LINE, paintStroke, paintTip, strokesBounds, type BgKind, type DrawScene, type Point, type Stroke } from "@/lib/draw-stroke";
5+import { PAPER_CELL, PAPER_LINE, canvasPx, paintStroke, paintTip, strokesBounds, type BgKind, type DrawScene, type Point, type Stroke } from "@/lib/draw-stroke";
66 import { canvasToImageBlob, sceneToPngFile } from "@/lib/drawing-file";
77 import { useT } from "@/stores/preferences-context";
88
@@ -249,14 +249,16 @@ export function DrawCanvas(props: {
249249 const dx = EXPORT_MARGIN - b.x;
250250 const dy = EXPORT_MARGIN - b.y;
251251 const off = document.createElement("canvas");
252- off.width = Math.round(w * scale);
253- off.height = Math.round(h * scale);
252+ off.width = canvasPx(w, scale);
253+ off.height = canvasPx(h, scale);
254254 const oc = off.getContext("2d");
255255 if (!oc) return null;
256256 oc.setTransform(scale, 0, 0, scale, dx * scale, dy * scale);
257257 for (const s of list) paintStroke(oc, s);
258258 const shifted = list.map((s) => ({ ...s, points: s.points.map((p) => ({ x: p.x + dx, y: p.y + dy })) }));
259- const scene: DrawScene = { v: 1, w, h, strokes: shifted, bg: bg() };
259+ // dpr rides along: the PNG is baked at this ratio, so a viewer on a different
260+ // display can size the replay to the same pixels instead of its own ratio.
261+ const scene: DrawScene = { v: 1, w, h, strokes: shifted, bg: bg(), dpr: scale };
260262 return { canvas: off, scene };
261263 };
262264
src/components/exams/drawing-playback.tsx β†’ src/components/ui/drawing-playback.tsxrenamed+10 -8
@@ -1,7 +1,7 @@
11 import { createSignal, onCleanup, onMount } from "solid-js";
22 import { Button } from "@/components/ui/button";
33 import { cn } from "@/lib/cn";
4-import { PAPER_CELL, paintPaper, paintStroke, sliceStrokes, type DrawScene } from "@/lib/draw-stroke";
4+import { PAPER_CELL, canvasPx, paintPaper, paintStroke, sliceStrokes, type DrawScene } from "@/lib/draw-stroke";
55 import { useT } from "@/stores/preferences-context";
66
77 // ponytail: synthetic order-only pace β€” the drawing carries no per-point timing, so
@@ -15,7 +15,7 @@ const POINTS_PER_SECOND = 220;
1515 * transparent layer (erasers cut only ink), then that layer is composited over
1616 * white + paper ruling. No timestamps are read β€” order + a synthetic pace only.
1717 */
18-export function DrawingPlayback(props: { scene: DrawScene; class?: string }) {
18+export function DrawingPlayback(props: { scene: DrawScene; class?: string; canvasClass?: string }) {
1919 const t = useT();
2020 let canvas: HTMLCanvasElement | undefined;
2121 let layer: HTMLCanvasElement | undefined; // offscreen transparent stroke layer (the export's `source`)
@@ -23,8 +23,9 @@ export function DrawingPlayback(props: { scene: DrawScene; class?: string }) {
2323 let startedAt = 0; // performance.now() when the current run began
2424 let baseCount = 0; // points already revealed when the run began (so pause/resume continues)
2525 let revealed = 0;
26- // ponytail: DPR snapshotted at mount so the backing store and the paint transform can't
27- // drift apart when browser zoom changes mid-run; re-inits on remount (Show image β†’ Play).
26+ // The scene's own export DPR when it has one (older scenes fall back to this display's),
27+ // so the canvas gets the saved PNG's exact pixels instead of the viewer's ratio. Snapshotted
28+ // at mount so backing store and paint transform can't drift apart if zoom changes mid-run.
2829 let scale = 1;
2930
3031 const total = () => props.scene.strokes.reduce((n, s) => n + s.points.length, 0);
@@ -81,9 +82,9 @@ export function DrawingPlayback(props: { scene: DrawScene; class?: string }) {
8182 };
8283
8384 onMount(() => {
84- scale = window.devicePixelRatio || 1;
85- const w = Math.max(1, Math.round(props.scene.w * scale));
86- const h = Math.max(1, Math.round(props.scene.h * scale));
85+ scale = props.scene.dpr ?? (window.devicePixelRatio || 1);
86+ const w = canvasPx(props.scene.w, scale);
87+ const h = canvasPx(props.scene.h, scale);
8788 if (canvas) {
8889 canvas.width = w;
8990 canvas.height = h;
@@ -98,7 +99,8 @@ export function DrawingPlayback(props: { scene: DrawScene; class?: string }) {
9899
99100 return (
100101 <div class={cn("space-y-2", props.class)}>
101- <canvas ref={canvas} class="h-64 w-full max-w-2xl rounded-md border bg-background object-contain" />
102+ {/* Sized by the caller so the replay matches the static image it replaces. */}
103+ <canvas ref={canvas} class={props.canvasClass ?? "h-64 w-full max-w-2xl rounded-md border bg-background object-contain"} />
102104 <div class="flex flex-wrap items-center gap-2">
103105 <Button type="button" variant="outline" size="sm" onClick={() => (playing() ? pause() : play())}>
104106 {playing() ? t("exams.pause") : t("exams.play")}
src/components/ui/replayable-image.tsxadded+71 -0
@@ -0,0 +1,71 @@
1+import { Show, Suspense, createSignal, lazy } from "solid-js";
2+import { Button } from "@/components/ui/button";
3+import { cn } from "@/lib/cn";
4+import { pngBytesToScene } from "@/lib/drawing-file";
5+import { playableScene, type DrawScene } from "@/lib/draw-stroke";
6+import { useT } from "@/stores/preferences-context";
7+
8+const DrawingPlayback = lazy(() => import("@/components/ui/drawing-playback").then((m) => ({ default: m.DrawingPlayback })));
9+
10+/**
11+ * An uploaded image with optional stroke-by-stroke playback. Defaults to the static
12+ * <img>; "Play drawing" fetches the bytes, recovers the scene embedded in the PNG and
13+ * swaps in the replay. A plain photo (no embedded strokes) falls back to the img and
14+ * drops the button β€” nothing to replay.
15+ */
16+export function ReplayableImage(props: {
17+ fetchBlob: () => Promise<Blob>;
18+ src: string;
19+ alt: string;
20+ /** Sizes the img, the loading box and the playback canvas β€” the swap can't change size. */
21+ imgClass: string;
22+ class?: string;
23+}) {
24+ const t = useT();
25+ const [scene, setScene] = createSignal<DrawScene | null>(null);
26+ const [mode, setMode] = createSignal<"image" | "loading" | "playback" | "plain">("image");
27+
28+ const enterPlayback = async () => {
29+ if (scene()) {
30+ setMode("playback");
31+ return;
32+ }
33+ setMode("loading");
34+ try {
35+ const blob = await props.fetchBlob();
36+ const parsed = pngBytesToScene(new Uint8Array(await blob.arrayBuffer()));
37+ const playable = playableScene(parsed);
38+ if (playable) {
39+ setScene(playable);
40+ setMode("playback");
41+ } else {
42+ setMode("plain"); // plain image or no strokes β†’ keep the img, hide Play
43+ }
44+ } catch {
45+ setMode("image"); // fetch failed β†’ keep the img, allow a retry
46+ }
47+ };
48+
49+ return (
50+ <div class={cn("space-y-2", props.class)}>
51+ {/* local boundary: the lazy playback chunk must not suspend the page around it */}
52+ {/* min-h reserves the box while the chunk loads: imgClass alone can be height:auto β†’ 0px */}
53+ <Suspense fallback={<div class={cn("min-h-[16rem]", props.imgClass)} />}>
54+ <Show when={mode() === "playback" && scene()} fallback={<img src={props.src} alt={props.alt} class={props.imgClass} />}>
55+ {(s) => <DrawingPlayback scene={s()} canvasClass={props.imgClass} />}
56+ </Show>
57+ </Suspense>
58+ <Show when={mode() !== "plain"}>
59+ <Button
60+ type="button"
61+ variant="outline"
62+ size="sm"
63+ disabled={mode() === "loading"}
64+ onClick={() => (mode() === "playback" ? setMode("image") : void enterPlayback())}
65+ >
66+ {mode() === "playback" ? t("exams.showImage") : t("exams.playDrawing")}
67+ </Button>
68+ </Show>
69+ </div>
70+ );
71+}
src/lib/draw-stroke.test.tsmodified+68 -1
@@ -1,5 +1,5 @@
11 import { describe, expect, it } from "vitest";
2-import { paintPaper, paintStroke, paintTip, parseScene, sliceStrokes, strokesBounds, type DrawScene, type Stroke } from "./draw-stroke";
2+import { canvasPx, paintPaper, paintStroke, paintTip, parseScene, playableScene, sliceStrokes, strokesBounds, type DrawScene, type Stroke } from "./draw-stroke";
33
44 /** Records every 2d-context call so the three geometry branches can be asserted without a DOM. */
55 function stubContext() {
@@ -120,6 +120,16 @@ describe("parseScene", () => {
120120 expect(parseScene(JSON.stringify({ ...scene, v: 2 }))).toBeNull();
121121 });
122122
123+ // w/h size the playback canvas and drive paintPaper's per-cell loop, from a PNG anyone
124+ // can upload: a real export can be big, but never non-finite, negative or past MAX_SIDE.
125+ it("accepts a large-but-real box, rejects non-finite, non-positive and absurd sides", () => {
126+ expect(parseScene(JSON.stringify({ ...scene, w: 8000, h: 16384 }))).not.toBeNull();
127+ // 1e999 is valid JSON that parses to Infinity; null is what JSON.stringify makes of NaN.
128+ for (const bad of ["1e999", "-1", "0", "1e9", "null", '"10"']) {
129+ expect(parseScene(`{"v":1,"w":${bad},"h":10,"strokes":[]}`)).toBeNull();
130+ }
131+ });
132+
123133 it("rejects a malformed stroke shape", () => {
124134 expect(parseScene(JSON.stringify({ v: 1, w: 1, h: 1, strokes: [{ color: "#000" }] }))).toBeNull();
125135 });
@@ -128,6 +138,18 @@ describe("parseScene", () => {
128138 expect(parseScene("not json")).toBeNull();
129139 expect(parseScene(null)).toBeNull();
130140 });
141+
142+ // dpr multiplies the playback canvas allocation, from a PNG anyone can upload: it must
143+ // survive the round trip, stay optional for drawings saved before it existed, and never
144+ // arrive as something unusable or absurd.
145+ it("round-trips dpr, tolerates its absence, rejects bogus or out-of-range ones", () => {
146+ expect(parseScene(JSON.stringify({ ...scene, dpr: 2 }))?.dpr).toBe(2);
147+ expect(parseScene(JSON.stringify({ ...scene, dpr: 0.5 }))?.dpr).toBe(0.5); // zoomed-out export
148+ expect(parseScene(JSON.stringify(scene))?.dpr).toBeUndefined();
149+ expect(parseScene(JSON.stringify({ ...scene, dpr: 0 }))).toBeNull();
150+ expect(parseScene(JSON.stringify({ ...scene, dpr: "2" }))).toBeNull();
151+ expect(parseScene(JSON.stringify({ ...scene, dpr: 1e9 }))).toBeNull(); // tab-killer allocation
152+ });
131153 });
132154
133155 describe("strokesBounds", () => {
@@ -223,3 +245,48 @@ describe("paintPaper", () => {
223245 expect(vertical.length).toBeGreaterThan(0);
224246 });
225247 });
248+
249+// canvasPx is the one spot both the export (draw-canvas's renderBounds) and playback
250+// (drawing-playback's onMount) canvases round a world-px side into device px β€” if the
251+// two ever computed this differently, the replay would render at a different on-screen
252+// size than the static <img> it swaps in for.
253+describe("canvasPx", () => {
254+ it("rounds world px * dpr to the nearest device px across export- and playback-typical dprs", () => {
255+ for (const side of [1, 16.5, 100.4, 123.7, 8000]) {
256+ for (const dpr of [0.5, 1, 2, 3]) {
257+ expect(canvasPx(side, dpr)).toBe(Math.max(1, Math.round(side * dpr)));
258+ }
259+ }
260+ });
261+
262+ it("floors at 1 device px so a tiny side at a sub-1 dpr never yields a 0-sized canvas", () => {
263+ expect(canvasPx(0.5, 0.5)).toBe(1); // 0.25 rounds to 0, which a canvas can't allocate
264+ });
265+
266+ // drawing-playback's onMount resolves `scene.dpr ?? window.devicePixelRatio` before
267+ // calling canvasPx β€” mirrored here since onMount itself needs a real DOM mount, which
268+ // this repo has no headless (jsdom-free) way to drive.
269+ it("mirrors the playback side's dpr fallback: a scene without dpr uses the viewer's ratio", () => {
270+ const viewerRatio = 3;
271+ const missingDpr: number | undefined = undefined;
272+ const savedDpr: number | undefined = 2;
273+ expect(canvasPx(100, missingDpr ?? viewerRatio)).toBe(canvasPx(100, viewerRatio));
274+ expect(canvasPx(100, savedDpr ?? viewerRatio)).toBe(canvasPx(100, 2)); // a saved dpr wins over the fallback
275+ });
276+});
277+
278+describe("playableScene", () => {
279+ const scene: DrawScene = { v: 1, w: 10, h: 10, strokes: [stroke([{ x: 0, y: 0 }, { x: 1, y: 1 }])] };
280+
281+ it("passes through a scene with at least one stroke β€” the playback branch", () => {
282+ expect(playableScene(scene)).toBe(scene);
283+ });
284+
285+ it("is null for a scene with zero strokes β€” an emptied drawing falls back to the static image", () => {
286+ expect(playableScene({ ...scene, strokes: [] })).toBeNull();
287+ });
288+
289+ it("is null for null β€” a plain photo with nothing embedded", () => {
290+ expect(playableScene(null)).toBeNull();
291+ });
292+});
src/lib/draw-stroke.tsmodified+41 -2
@@ -1,7 +1,8 @@
11 export type Point = { x: number; y: number };
22 export type Stroke = { color: string; width: number; erase: boolean; points: Point[] };
33 export type BgKind = "none" | "lines" | "grid";
4-export type DrawScene = { v: 1; w: number; h: number; strokes: Stroke[]; bg?: BgKind };
4+/** `w`/`h` are DPR-free world px; `dpr` is the device ratio the PNG beside them was baked at. */
5+export type DrawScene = { v: 1; w: number; h: number; strokes: Stroke[]; bg?: BgKind; dpr?: number };
56
67 /** World px per notebook cell β€” shared by the live CSS paper and the baked export so both read as the same ruling. */
78 export const PAPER_CELL = 24;
@@ -12,6 +13,18 @@ function isPoint(p: unknown): p is Point {
1213 return !!p && typeof p === "object" && typeof (p as Point).x === "number" && typeof (p as Point).y === "number";
1314 }
1415
16+/**
17+ * Export-box side in world px: finite, positive, and no wider than the largest canvas a
18+ * browser will make. A real export was itself rendered through a `w Γ— dpr` canvas (dpr β‰₯ 1
19+ * on any normal display), so nothing legitimate can exceed this β€” while an unbounded side
20+ * both sizes the playback allocation and drives paintPaper's per-cell loop.
21+ */
22+const MAX_SIDE = 16384;
23+
24+function isSide(n: unknown): n is number {
25+ return typeof n === "number" && n > 0 && n <= MAX_SIDE; // NaN/Infinity fail the comparisons
26+}
27+
1528 function isStroke(s: unknown): s is Stroke {
1629 if (!s || typeof s !== "object") return false;
1730 const st = s as Stroke;
@@ -39,15 +52,30 @@ export function parseScene(text: string | null): DrawScene | null {
3952 }
4053 if (!data || typeof data !== "object") return null;
4154 const scene = data as DrawScene;
42- if (scene.v !== 1 || typeof scene.w !== "number" || typeof scene.h !== "number" || !Array.isArray(scene.strokes)) {
55+ if (scene.v !== 1 || !isSide(scene.w) || !isSide(scene.h) || !Array.isArray(scene.strokes)) {
4356 return null;
4457 }
4558 if (!scene.strokes.every(isStroke)) return null;
4659 // bg is optional (old drawings lack it); reject only a present-but-bogus value.
4760 if (scene.bg !== undefined && scene.bg !== "none" && scene.bg !== "lines" && scene.bg !== "grid") return null;
61+ // dpr likewise optional, but it multiplies a canvas allocation on the viewer's machine, so
62+ // cap it at 8 β€” well past any real display (1–3), while browser zoom-out legitimately
63+ // exports below 1. NaN/Infinity fail the comparisons.
64+ if (scene.dpr !== undefined && !(typeof scene.dpr === "number" && scene.dpr > 0 && scene.dpr <= 8)) return null;
4865 return scene;
4966 }
5067
68+/**
69+ * A parsed scene is only worth replaying if it has ink: a plain photo (parse failed,
70+ * null) or an emptied drawing (parsed, zero strokes) both mean "nothing to play", so
71+ * ReplayableImage falls back to the static image for either. Pulled out of that
72+ * component (which has three call sites of its own) so the decision is unit-testable
73+ * without mounting Solid.
74+ */
75+export function playableScene(parsed: DrawScene | null): DrawScene | null {
76+ return parsed && parsed.strokes.length > 0 ? parsed : null;
77+}
78+
5179 /**
5280 * Tight bounding box over every ink (pen) stroke, padded by its half-width so a
5381 * thick line isn't clipped at the edge. Null when there's nothing drawn. Used to
@@ -73,6 +101,17 @@ export function strokesBounds(strokes: Stroke[]): { x: number; y: number; w: num
73101 return { x: minX, y: minY, w: maxX - minX, h: maxY - minY };
74102 }
75103
104+/**
105+ * World px β†’ device px for one canvas side, shared by the export (`renderBounds`,
106+ * baking `scene.w`/`scene.h` at `scene.dpr`) and playback (`onMount`, replaying them at
107+ * that same dpr) so the two can't round differently and size the replay canvas
108+ * differently on screen than the static image it replaces. Floors at 1: a canvas side
109+ * of 0 throws, which a tiny world side at a sub-1 dpr could otherwise round down to.
110+ */
111+export function canvasPx(worldSide: number, dpr: number): number {
112+ return Math.max(1, Math.round(worldSide * dpr));
113+}
114+
76115 /**
77116 * Split strokes at a reveal cut for order-only playback. Points are counted across
78117 * strokes in drawn order; the first `revealCount` are "revealed". `full` = strokes
src/lib/drawing-file.test.tsmodified+11 -2
@@ -16,13 +16,22 @@ function minimalPng(): Uint8Array {
1616 }
1717
1818 describe("pngBytesToScene", () => {
19- it("round-trips a scene carried in the PNG's tEXt chunk", () => {
19+ it("round-trips a scene carried in the PNG's tEXt chunk, every field intact", () => {
2020 const scene: DrawScene = {
2121 v: 1,
2222 w: 120,
2323 h: 90,
24- strokes: [{ color: "#1f2937", width: 6, erase: false, points: [{ x: 1, y: 2 }, { x: 3, y: 4 }] }],
24+ bg: "grid",
25+ dpr: 2,
26+ strokes: [
27+ { color: "#1f2937", width: 6, erase: false, points: [{ x: 1, y: 2 }, { x: 3, y: 4 }] },
28+ { color: "#dc2626", width: 14, erase: true, points: [{ x: 10, y: 10 }] },
29+ ],
2530 };
31+ // "hezarfen-drawing" here must match drawing-file.ts's private DRAWING_KEYWORD
32+ // constant exactly β€” it's a wire format shared with every already-saved
33+ // .hzdraw.png. If pngBytesToScene's own keyword ever drifted from this literal,
34+ // extractPngText would find no chunk under it and this would come back null.
2635 const png = embedPngText(minimalPng(), "hezarfen-drawing", JSON.stringify(scene));
2736 expect(pngBytesToScene(png)).toEqual(scene);
2837 });
src/lib/png-meta.test.tsmodified+19 -0
@@ -1,4 +1,5 @@
11 import { describe, expect, it } from "vitest";
2+import type { DrawScene } from "./draw-stroke";
23 import { embedPngText, extractPngText } from "./png-meta";
34
45 const SIGNATURE = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a];
@@ -60,4 +61,22 @@ describe("png-meta", () => {
6061 const embedded = ((png[crcAt] << 24) | (png[crcAt + 1] << 16) | (png[crcAt + 2] << 8) | png[crcAt + 3]) >>> 0;
6162 expect(embedded).toBe(refCrc32(typeAndData));
6263 });
64+
65+ it("round-trips a full drawing scene's JSON β€” strokes, points, colour, width, erase, bg, w/h, dpr β€” byte-for-byte", () => {
66+ const scene: DrawScene = {
67+ v: 1,
68+ w: 120,
69+ h: 80,
70+ bg: "grid",
71+ dpr: 2,
72+ strokes: [
73+ { color: "#1f2937", width: 6, erase: false, points: [{ x: 1, y: 2 }, { x: 3.5, y: 4 }] },
74+ { color: "#dc2626", width: 14, erase: true, points: [{ x: 10, y: 10 }] },
75+ ],
76+ };
77+ const json = JSON.stringify(scene);
78+ const png = embedPngText(minimalPng(), "hezarfen-drawing", json);
79+ expect(extractPngText(png, "hezarfen-drawing")).toBe(json);
80+ expect(JSON.parse(extractPngText(png, "hezarfen-drawing")!)).toEqual(scene);
81+ });
6382 });
src/pages/question-detail-page.tsxmodified+38 -7
@@ -1,7 +1,7 @@
1-import { For, Show, Suspense, createResource, createSignal } from "solid-js";
1+import { For, Show, Suspense, createResource, createSignal, lazy } from "solid-js";
22 import { useParams, useRouter } from "@tanstack/solid-router";
3-import { getQuestionById, deleteQuestionById, postQuestionApprove, getQuestionImageUrl } from "@/api/shared";
4-import { getSolutions, postSolution, patchSolutionById, deleteSolutionById, getSolutionImageUrl } from "@/api/shared";
3+import { getQuestionById, deleteQuestionById, postQuestionApprove, getQuestionImageUrl, getQuestionImageBlob } from "@/api/shared";
4+import { getSolutions, postSolution, patchSolutionById, deleteSolutionById, getSolutionImageUrl, getSolutionImageBlob } from "@/api/shared";
55 import type { SolutionResponse } from "@/api/shared";
66 import { formatApiError } from "@/api/client";
77 import { RouteGuard } from "@/components/layout/route-guard";
@@ -12,6 +12,7 @@ import { ConfirmDialog } from "@/components/ui/confirm-dialog";
1212 import { Label } from "@/components/ui/label";
1313 import { Textarea } from "@/components/ui/textarea";
1414 import { IconTrash, IconCheck, IconX, IconEdit, IconMessage, IconPhoto } from "@/components/ui/icons";
15+import { ReplayableImage } from "@/components/ui/replayable-image";
1516 import { personLabel } from "@/lib/person";
1617
1718 import { ErrorAlert } from "@/components/ui/error-alert";
@@ -20,6 +21,9 @@ import { useT } from "@/stores/preferences-context";
2021 import { useAuth } from "@/stores/auth-context";
2122 import { hasMinRole } from "@/lib/roles";
2223
24+// Lazy so the drawing pad rides its own chunk, off the question detail's initial load.
25+const DrawCanvas = lazy(() => import("@/components/ui/draw-canvas").then((m) => ({ default: m.DrawCanvas })));
26+
2327 export default function QuestionDetailPage() {
2428 return (
2529 <RouteGuard minRole="student">
@@ -118,8 +122,13 @@ function QuestionDetailContent() {
118122 <div class="rounded-xl border bg-card p-6 shadow-sm">
119123 <p class="whitespace-pre-wrap text-foreground">{q().body}</p>
120124 <Show when={q().image}>
121- <div class="mt-4 overflow-hidden rounded-lg border bg-muted/30">
122- <img src={getQuestionImageUrl(q().id)} alt="Question Attachment" class="max-h-[500px] w-auto object-contain mx-auto" />
125+ <div class="mt-4 overflow-hidden rounded-lg border bg-muted/30 p-2">
126+ <ReplayableImage
127+ fetchBlob={() => getQuestionImageBlob(q().id)}
128+ src={getQuestionImageUrl(q().id)}
129+ alt="Question Attachment"
130+ imgClass="max-h-[500px] w-auto object-contain mx-auto"
131+ />
123132 </div>
124133 </Show>
125134 </div>
@@ -163,8 +172,13 @@ function QuestionDetailContent() {
163172 </div>
164173 <p class="mt-3 whitespace-pre-wrap text-sm text-foreground">{sol.body}</p>
165174 <Show when={sol.image}>
166- <div class="mt-3 overflow-hidden rounded-lg border border-border/50">
167- <img src={getSolutionImageUrl(q().id, sol.id)} alt="Solution Attachment" class="max-h-[300px] w-auto object-contain mx-auto" />
175+ <div class="mt-3 overflow-hidden rounded-lg border border-border/50 p-2">
176+ <ReplayableImage
177+ fetchBlob={() => getSolutionImageBlob(q().id, sol.id)}
178+ src={getSolutionImageUrl(q().id, sol.id)}
179+ alt="Solution Attachment"
180+ imgClass="max-h-[300px] w-auto object-contain mx-auto"
181+ />
168182 </div>
169183 </Show>
170184 </div>
@@ -236,6 +250,7 @@ function SolutionFormDialog(props: { questionId: string; initialData?: SolutionR
236250 const [error, setError] = createSignal("");
237251 const [body, setBody] = createSignal(props.initialData?.body || "");
238252 const [file, setFile] = createSignal<File | null>(null);
253+ const [drawing, setDrawing] = createSignal(false);
239254
240255 const handleSubmit = async (e: Event) => {
241256 e.preventDefault();
@@ -306,6 +321,22 @@ function SolutionFormDialog(props: { questionId: string; initialData?: SolutionR
306321 onChange={(e) => setFile(e.currentTarget.files?.[0] || null)}
307322 />
308323 </div>
324+ {/* Draw instead of upload: the pad saves a PNG File, so it rides the same upload. */}
325+ <Button type="button" variant="outline" size="sm" aria-expanded={drawing()} onClick={() => setDrawing((open) => !open)}>
326+ <IconEdit class="mr-2 h-4 w-4" />
327+ {t("questions.draw")}
328+ </Button>
329+ <Show when={drawing()}>
330+ <Suspense fallback={<div class="h-[22rem] animate-pulse rounded-lg border bg-muted/20" />}>
331+ <DrawCanvas
332+ fileName="solution.png"
333+ onSave={(drawn) => {
334+ setFile(drawn);
335+ setDrawing(false);
336+ }}
337+ />
338+ </Suspense>
339+ </Show>
309340 </div>
310341 </Show>
311342 <div class="flex justify-end gap-3 pt-4">
src/pages/questions-page.tsxmodified+22 -2
@@ -1,4 +1,4 @@
1-import { For, Show, Suspense, createResource, createSignal } from "solid-js";
1+import { For, Show, Suspense, createResource, createSignal, lazy } from "solid-js";
22 import { Link, useSearch, useNavigate } from "@tanstack/solid-router";
33 import { getQuestions, postQuestion } from "@/api/shared";
44 import { formatApiError } from "@/api/client";
@@ -11,7 +11,7 @@ import { FormDialog } from "@/components/ui/form-dialog";
1111 import { Label } from "@/components/ui/label";
1212 import { Input } from "@/components/ui/input";
1313 import { Textarea } from "@/components/ui/textarea";
14-import { IconPlus, IconClock, IconCheck, IconPhoto, IconX } from "@/components/ui/icons";
14+import { IconPlus, IconClock, IconCheck, IconPhoto, IconX, IconEdit } from "@/components/ui/icons";
1515 import { personLabel } from "@/lib/person";
1616
1717 import { ErrorAlert } from "@/components/ui/error-alert";
@@ -20,6 +20,9 @@ import { useT } from "@/stores/preferences-context";
2020 import { useAuth } from "@/stores/auth-context";
2121 import { cn } from "@/lib/cn";
2222
23+// Lazy so the drawing pad rides its own chunk, off the question list's initial load.
24+const DrawCanvas = lazy(() => import("@/components/ui/draw-canvas").then((m) => ({ default: m.DrawCanvas })));
25+
2326 export default function QuestionsPage() {
2427 return (
2528 <RouteGuard minRole="student">
@@ -137,6 +140,7 @@ function AskQuestionDialog(props: { onClose: () => void; onSuccess: () => void }
137140 const [title, setTitle] = createSignal("");
138141 const [body, setBody] = createSignal("");
139142 const [file, setFile] = createSignal<File | null>(null);
143+ const [drawing, setDrawing] = createSignal(false);
140144
141145 const handleSubmit = async (e: Event) => {
142146 e.preventDefault();
@@ -206,6 +210,22 @@ function AskQuestionDialog(props: { onClose: () => void; onSuccess: () => void }
206210 onChange={(e) => setFile(e.currentTarget.files?.[0] || null)}
207211 />
208212 </div>
213+ {/* Draw instead of upload: the pad saves a PNG File, so it rides the same upload. */}
214+ <Button type="button" variant="outline" size="sm" aria-expanded={drawing()} onClick={() => setDrawing((open) => !open)}>
215+ <IconEdit class="mr-2 h-4 w-4" />
216+ {t("questions.draw")}
217+ </Button>
218+ <Show when={drawing()}>
219+ <Suspense fallback={<div class="h-[22rem] animate-pulse rounded-lg border bg-muted/20" />}>
220+ <DrawCanvas
221+ fileName="question.png"
222+ onSave={(drawn) => {
223+ setFile(drawn);
224+ setDrawing(false);
225+ }}
226+ />
227+ </Suspense>
228+ </Show>
209229 </div>
210230 <div class="flex justify-end gap-3 pt-4">
211231 <Button type="button" variant="outline" onClick={props.onClose}>