forge
Explore
Log in

Don't you dare go Hollow

🎬 replay a student's answer drawing stroke-by-stroke

Browse files at this commit

595aa7e7a68d6f3de34dee40efde66e969a1d3deAhmet Kaan GümüşParent: 0ae3da9
  • feat
    • 🎬 replay a student's answer drawing stroke-by-stroke
Show full message
feat: 🎬 replay a student's answer drawing stroke-by-stroke

- teachers can play back a drawn exam answer in the grading answer
  sheet, watching how the student built it instead of only seeing the
  finished image
- no backend change: the drawing PNG already carries its editable stroke
  JSON in a tEXt chunk, so pngBytesToScene recovers the strokes
  client-side from the grader image that was already being served
- add a getStudentAnswerImage wrapper for
  GET /exams/{examId}/attempts/{userId}/answers/{questionId}/image;
  the route had no wrapper before, only a raw <img src>
- DrawingPlayback runs a requestAnimationFrame loop revealing points in
  drawn order at a constant POINTS_PER_SECOND, with play/pause/restart;
  pacing is order-only because the capture stores no timestamps
- pure sliceStrokes(strokes, revealCount) -> { full, partial } lives
  beside strokesBounds and is unit-tested
- the static image stays the default view; playback is a reversible
  toggle and falls back to the plain image when a PNG has no embedded
  strokes
- eraser strokes replay through a two-layer composite (ink on a
  transparent layer, then over white + paper) mirroring
  canvasToImageBlob, so a fully-revealed frame matches the saved PNG
- EN/TR i18n keys for the playback controls
src/api/exams/getStudentAnswerImage.tsadded+11 -0
@@ -0,0 +1,11 @@
1+import { blobClient } from "../client";
2+
3+/** Grader view of a student's drawn/uploaded answer image (plural `attempts` + explicit user). */
4+export async function getStudentAnswerImage(
5+ examId: string,
6+ userId: string,
7+ questionId: string,
8+ signal?: AbortSignal,
9+): Promise<Blob> {
10+ return blobClient(`/exams/${examId}/attempts/${userId}/answers/${questionId}/image`, signal);
11+}
src/api/exams/index.tsmodified+1 -0
@@ -27,3 +27,4 @@ export * from "./postExamAttemptAnswer";
27 export * from "./postExamAttemptAnswerImage";27 export * from "./postExamAttemptAnswerImage";
28 export * from "./deleteExamAttemptAnswerImage";28 export * from "./deleteExamAttemptAnswerImage";
29 export * from "./getExamAnswerImageBlob";29 export * from "./getExamAnswerImageBlob";
30+export * from "./getStudentAnswerImage";
src/components/exams/answer-sheet-view.tsxmodified+66 -7
@@ -1,16 +1,79 @@
1-import { For, Show, Suspense, createResource } from "solid-js";1+import { For, Show, Suspense, createResource, createSignal, lazy } from "solid-js";
2 import { ApiError } from "@/api/client";2 import { ApiError } from "@/api/client";
3 import { getExamQuestions } from "@/api/exams";3 import { getExamQuestions } from "@/api/exams";
4-import { getStudentAnswers } from "@/api/exams";4+import { getStudentAnswers, getStudentAnswerImage } from "@/api/exams";
5 import type { StudentAnswerSheet } from "@/api/client";5 import type { StudentAnswerSheet } from "@/api/client";
6 import { Badge } from "@/components/ui/badge";6 import { Badge } from "@/components/ui/badge";
7+import { Button } from "@/components/ui/button";
7 import { IconCheck, IconX } from "@/components/ui/icons";8 import { IconCheck, IconX } from "@/components/ui/icons";
8 import { PageSpinner } from "@/components/ui/page-spinner";9 import { PageSpinner } from "@/components/ui/page-spinner";
9 import { cn } from "@/lib/cn";10 import { cn } from "@/lib/cn";
10 import { joinAnswerSheet } from "@/lib/answer-sheet";11 import { joinAnswerSheet } from "@/lib/answer-sheet";
12+import { pngBytesToScene } from "@/lib/drawing-file";
13+import type { DrawScene } from "@/lib/draw-stroke";
11 import { personLabelWithId } from "@/lib/person";14 import { personLabelWithId } from "@/lib/person";
12 import { useT } from "@/stores/preferences-context";15 import { useT } from "@/stores/preferences-context";
13 16
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+
14 export function AnswerSheetView(props: { examId: string; userId: string }) {77 export function AnswerSheetView(props: { examId: string; userId: string }) {
15 const t = useT();78 const t = useT();
16 const [data] = createResource(79 const [data] = createResource(
@@ -82,11 +145,7 @@ export function AnswerSheetView(props: { examId: string; userId: string }) {
82 <p class="text-xs text-muted-foreground">{t("exams.textAnswer")}</p>145 <p class="text-xs text-muted-foreground">{t("exams.textAnswer")}</p>
83 <p class="mt-1 whitespace-pre-wrap text-sm">{row.answer?.text || "—"}</p>146 <p class="mt-1 whitespace-pre-wrap text-sm">{row.answer?.text || "—"}</p>
84 <Show when={row.answer?.answer_image}>147 <Show when={row.answer?.answer_image}>
85- <img148+ <AnswerDrawing examId={d().sheet.exam} userId={d().sheet.user.id} questionId={row.question.id} />
86- src={`/api/exams/${d().sheet.exam}/attempts/${d().sheet.user.id}/answers/${row.question.id}/image`}
87- alt={t("exams.drawAnswer")}
88- class="mt-3 h-64 w-full max-w-2xl rounded-md border bg-background object-contain"
89- />
90 </Show>149 </Show>
91 </div>150 </div>
92 }151 }
src/components/exams/drawing-playback.tsxadded+112 -0
@@ -0,0 +1,112 @@
1+import { createSignal, onCleanup, onMount } from "solid-js";
2+import { Button } from "@/components/ui/button";
3+import { cn } from "@/lib/cn";
4+import { PAPER_CELL, paintPaper, paintStroke, sliceStrokes, type DrawScene } from "@/lib/draw-stroke";
5+import { useT } from "@/stores/preferences-context";
6+
7+// ponytail: synthetic order-only pace — the drawing carries no per-point timing, so
8+// every answer replays at this constant point rate. Bump if playback feels too fast/slow.
9+const POINTS_PER_SECOND = 220;
10+
11+/**
12+ * Replays a recovered drawing scene stroke-by-stroke in drawn order. Mirrors the
13+ * export pipeline (drawing-file `renderBounds`/`canvasToImageBlob`) so a fully
14+ * revealed frame is pixel-identical to the static answer <img>: strokes go on a
15+ * transparent layer (erasers cut only ink), then that layer is composited over
16+ * white + paper ruling. No timestamps are read — order + a synthetic pace only.
17+ */
18+export function DrawingPlayback(props: { scene: DrawScene; class?: string }) {
19+ const t = useT();
20+ let canvas: HTMLCanvasElement | undefined;
21+ let layer: HTMLCanvasElement | undefined; // offscreen transparent stroke layer (the export's `source`)
22+ let raf = 0;
23+ let startedAt = 0; // performance.now() when the current run began
24+ let baseCount = 0; // points already revealed when the run began (so pause/resume continues)
25+ 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).
28+ let scale = 1;
29+
30+ const total = () => props.scene.strokes.reduce((n, s) => n + s.points.length, 0);
31+ const [playing, setPlaying] = createSignal(true);
32+
33+ const paint = (count: number) => {
34+ const s = props.scene;
35+ const lc = layer?.getContext("2d");
36+ const mc = canvas?.getContext("2d");
37+ if (!layer || !canvas || !lc || !mc) return;
38+ // 1. stroke layer: clear + replay the revealed prefix in world coords. Strokes are
39+ // already baked into the scene box, so a plain DPR scale places them like the export.
40+ lc.setTransform(scale, 0, 0, scale, 0, 0);
41+ lc.clearRect(0, 0, s.w, s.h);
42+ const { full, partial } = sliceStrokes(s.strokes, count);
43+ for (const st of full) paintStroke(lc, st);
44+ if (partial) paintStroke(lc, partial);
45+ // 2. main canvas: white → paper → composite the ink (matches canvasToImageBlob).
46+ mc.setTransform(1, 0, 0, 1, 0, 0);
47+ mc.fillStyle = "#ffffff";
48+ mc.fillRect(0, 0, canvas.width, canvas.height);
49+ paintPaper(mc, s.bg ?? "none", canvas.width, canvas.height, PAPER_CELL * scale);
50+ mc.drawImage(layer, 0, 0);
51+ };
52+
53+ const loop = () => {
54+ const elapsed = (performance.now() - startedAt) / 1000;
55+ revealed = Math.min(total(), baseCount + Math.floor(elapsed * POINTS_PER_SECOND));
56+ paint(revealed);
57+ if (revealed >= total()) {
58+ setPlaying(false); // reached the end: freeze on the complete drawing
59+ return;
60+ }
61+ raf = requestAnimationFrame(loop);
62+ };
63+
64+ const play = () => {
65+ if (revealed >= total()) revealed = 0; // finished → replay from the start
66+ baseCount = revealed;
67+ startedAt = performance.now();
68+ setPlaying(true);
69+ cancelAnimationFrame(raf);
70+ raf = requestAnimationFrame(loop);
71+ };
72+
73+ const pause = () => {
74+ cancelAnimationFrame(raf);
75+ setPlaying(false);
76+ };
77+
78+ const restart = () => {
79+ revealed = 0;
80+ play();
81+ };
82+
83+ 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));
87+ if (canvas) {
88+ canvas.width = w;
89+ canvas.height = h;
90+ }
91+ layer = document.createElement("canvas");
92+ layer.width = w;
93+ layer.height = h;
94+ play(); // auto-start from blank — the teacher clicked "play" to get here
95+ });
96+
97+ onCleanup(() => cancelAnimationFrame(raf));
98+
99+ return (
100+ <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+ <div class="flex flex-wrap items-center gap-2">
103+ <Button type="button" variant="outline" size="sm" onClick={() => (playing() ? pause() : play())}>
104+ {playing() ? t("exams.pause") : t("exams.play")}
105+ </Button>
106+ <Button type="button" variant="outline" size="sm" onClick={restart}>
107+ {t("exams.restart")}
108+ </Button>
109+ </div>
110+ </div>
111+ );
112+}
src/i18n/messages.tsmodified+15 -0
@@ -578,6 +578,11 @@ export type MessageKey =
578 | "exams.isCorrect"578 | "exams.isCorrect"
579 | "exams.textAnswer"579 | "exams.textAnswer"
580 | "exams.drawAnswer"580 | "exams.drawAnswer"
581+ | "exams.playDrawing"
582+ | "exams.showImage"
583+ | "exams.play"
584+ | "exams.pause"
585+ | "exams.restart"
581 | "exams.editDrawing"586 | "exams.editDrawing"
582 | "exams.removeDrawing"587 | "exams.removeDrawing"
583 | "exams.nameless"588 | "exams.nameless"
@@ -1306,6 +1311,11 @@ const en: Dict = {
1306 "exams.isCorrect": "Correct",1311 "exams.isCorrect": "Correct",
1307 "exams.textAnswer": "Text answer",1312 "exams.textAnswer": "Text answer",
1308 "exams.drawAnswer": "Draw answer",1313 "exams.drawAnswer": "Draw answer",
1314+ "exams.playDrawing": "Play drawing",
1315+ "exams.showImage": "Show image",
1316+ "exams.play": "Play",
1317+ "exams.pause": "Pause",
1318+ "exams.restart": "Restart",
1309 "exams.editDrawing": "Edit drawing",1319 "exams.editDrawing": "Edit drawing",
1310 "exams.removeDrawing": "Remove drawing",1320 "exams.removeDrawing": "Remove drawing",
1311 "exams.nameless": "Unnamed",1321 "exams.nameless": "Unnamed",
@@ -2028,6 +2038,11 @@ const tr: Dict = {
2028 "exams.isCorrect": "Doğru",2038 "exams.isCorrect": "Doğru",
2029 "exams.textAnswer": "Metin cevap",2039 "exams.textAnswer": "Metin cevap",
2030 "exams.drawAnswer": "Cevabı çiz",2040 "exams.drawAnswer": "Cevabı çiz",
2041+ "exams.playDrawing": "Çizimi oynat",
2042+ "exams.showImage": "Görseli göster",
2043+ "exams.play": "Oynat",
2044+ "exams.pause": "Duraklat",
2045+ "exams.restart": "Baştan al",
2031 "exams.editDrawing": "Çizimi düzenle",2046 "exams.editDrawing": "Çizimi düzenle",
2032 "exams.removeDrawing": "Çizimi kaldır",2047 "exams.removeDrawing": "Çizimi kaldır",
2033 "exams.nameless": "İsimsiz",2048 "exams.nameless": "İsimsiz",
src/lib/draw-stroke.test.tsmodified+39 -1
@@ -1,5 +1,5 @@
1 import { describe, expect, it } from "vitest";1 import { describe, expect, it } from "vitest";
2-import { paintPaper, paintStroke, paintTip, parseScene, strokesBounds, type DrawScene, type Stroke } from "./draw-stroke";2+import { paintPaper, paintStroke, paintTip, parseScene, sliceStrokes, strokesBounds, type DrawScene, type Stroke } from "./draw-stroke";
3 3
4 /** Records every 2d-context call so the three geometry branches can be asserted without a DOM. */4 /** Records every 2d-context call so the three geometry branches can be asserted without a DOM. */
5 function stubContext() {5 function stubContext() {
@@ -158,6 +158,44 @@ describe("strokesBounds", () => {
158 });158 });
159 });159 });
160 160
161+describe("sliceStrokes", () => {
162+ const a = stroke([{ x: 0, y: 0 }, { x: 1, y: 1 }, { x: 2, y: 2 }]); // 3 points
163+ const b = stroke([{ x: 5, y: 5 }, { x: 6, y: 6 }, { x: 7, y: 7 }, { x: 8, y: 8 }]); // 4 points
164+
165+ it("reveals nothing at count 0", () => {
166+ expect(sliceStrokes([a, b], 0)).toEqual({ full: [], partial: null });
167+ });
168+
169+ it("reveals every stroke, no partial, at the total point count", () => {
170+ expect(sliceStrokes([a, b], 7)).toEqual({ full: [a, b], partial: null });
171+ });
172+
173+ it("clamps past the total to the whole drawing", () => {
174+ expect(sliceStrokes([a, b], 999)).toEqual({ full: [a, b], partial: null });
175+ });
176+
177+ it("truncates the stroke the cut lands inside", () => {
178+ const { full, partial } = sliceStrokes([a, b], 5); // a whole (3) + first 2 of b
179+ expect(full).toEqual([a]);
180+ expect(partial).toEqual({ ...b, points: b.points.slice(0, 2) });
181+ });
182+
183+ it("gives no partial when the cut sits on a stroke boundary", () => {
184+ expect(sliceStrokes([a, b], 3)).toEqual({ full: [a], partial: null }); // a done, b not started
185+ });
186+
187+ it("handles a single-point stroke on both sides of its one point", () => {
188+ const dot = stroke([{ x: 9, y: 9 }]);
189+ expect(sliceStrokes([dot], 0)).toEqual({ full: [], partial: null });
190+ expect(sliceStrokes([dot], 1)).toEqual({ full: [dot], partial: null });
191+ });
192+
193+ it("is empty for no strokes", () => {
194+ expect(sliceStrokes([], 0)).toEqual({ full: [], partial: null });
195+ expect(sliceStrokes([], 5)).toEqual({ full: [], partial: null });
196+ });
197+});
198+
161 describe("paintPaper", () => {199 describe("paintPaper", () => {
162 it("draws nothing for none", () => {200 it("draws nothing for none", () => {
163 const c = stubContext();201 const c = stubContext();
src/lib/draw-stroke.tsmodified+22 -0
@@ -73,6 +73,28 @@ export function strokesBounds(strokes: Stroke[]): { x: number; y: number; w: num
73 return { x: minX, y: minY, w: maxX - minX, h: maxY - minY };73 return { x: minX, y: minY, w: maxX - minX, h: maxY - minY };
74 }74 }
75 75
76+/**
77+ * Split strokes at a reveal cut for order-only playback. Points are counted across
78+ * strokes in drawn order; the first `revealCount` are "revealed". `full` = strokes
79+ * shown in their entirety, `partial` = the stroke the cut lands inside, truncated to
80+ * its revealed points (null when the cut sits on a stroke boundary). `revealCount` is
81+ * clamped to [0, total points]; running out of strokes handles the upper bound.
82+ */
83+export function sliceStrokes(strokes: Stroke[], revealCount: number): { full: Stroke[]; partial: Stroke | null } {
84+ let n = Math.max(0, Math.floor(revealCount));
85+ const full: Stroke[] = [];
86+ for (const s of strokes) {
87+ if (n >= s.points.length) {
88+ full.push(s);
89+ n -= s.points.length;
90+ continue;
91+ }
92+ // cut lands inside this stroke (0 <= n < points.length); n === 0 means it hasn't started
93+ return { full, partial: n > 0 ? { ...s, points: s.points.slice(0, n) } : null };
94+ }
95+ return { full, partial: null };
96+}
97+
76 function applyBrush(c: CanvasRenderingContext2D, stroke: Stroke) {98 function applyBrush(c: CanvasRenderingContext2D, stroke: Stroke) {
77 // The eraser cuts through the transparent drawing layer rather than painting99 // The eraser cuts through the transparent drawing layer rather than painting
78 // over it, so a saved drawing keeps whatever the caller flattens it onto.100 // over it, so a saved drawing keeps whatever the caller flattens it onto.