diff --git a/src/api/exams/getStudentAnswerImage.ts b/src/api/exams/getStudentAnswerImage.ts new file mode 100644 index 0000000..6b8545c --- /dev/null +++ b/src/api/exams/getStudentAnswerImage.ts @@ -0,0 +1,11 @@ +import { blobClient } from "../client"; + +/** Grader view of a student's drawn/uploaded answer image (plural `attempts` + explicit user). */ +export async function getStudentAnswerImage( + examId: string, + userId: string, + questionId: string, + signal?: AbortSignal, +): Promise { + return blobClient(`/exams/${examId}/attempts/${userId}/answers/${questionId}/image`, signal); +} diff --git a/src/api/exams/index.ts b/src/api/exams/index.ts index 80a2511..9bb9ade 100644 --- a/src/api/exams/index.ts +++ b/src/api/exams/index.ts @@ -27,3 +27,4 @@ export * from "./postExamAttemptAnswer"; export * from "./postExamAttemptAnswerImage"; export * from "./deleteExamAttemptAnswerImage"; export * from "./getExamAnswerImageBlob"; +export * from "./getStudentAnswerImage"; diff --git a/src/components/exams/answer-sheet-view.tsx b/src/components/exams/answer-sheet-view.tsx index b1783db..d7bd0ac 100644 --- a/src/components/exams/answer-sheet-view.tsx +++ b/src/components/exams/answer-sheet-view.tsx @@ -1,16 +1,79 @@ -import { For, Show, Suspense, createResource } from "solid-js"; +import { For, Show, Suspense, createResource, createSignal, lazy } from "solid-js"; import { ApiError } from "@/api/client"; import { getExamQuestions } from "@/api/exams"; -import { getStudentAnswers } from "@/api/exams"; +import { getStudentAnswers, getStudentAnswerImage } from "@/api/exams"; import type { StudentAnswerSheet } from "@/api/client"; import { Badge } from "@/components/ui/badge"; +import { Button } from "@/components/ui/button"; import { IconCheck, IconX } from "@/components/ui/icons"; import { PageSpinner } from "@/components/ui/page-spinner"; import { cn } from "@/lib/cn"; import { joinAnswerSheet } from "@/lib/answer-sheet"; +import { pngBytesToScene } from "@/lib/drawing-file"; +import type { DrawScene } from "@/lib/draw-stroke"; import { personLabelWithId } from "@/lib/person"; import { useT } from "@/stores/preferences-context"; +const DrawingPlayback = lazy(() => import("@/components/exams/drawing-playback").then((m) => ({ default: m.DrawingPlayback }))); + +/** + * A student's answer image with optional stroke-by-stroke playback. Defaults to the + * static ; "Play drawing" fetches the PNG, recovers its embedded scene, and swaps + * in the replay. A plain image (no embedded strokes) falls back to the img and drops + * the button — nothing to replay. + */ +function AnswerDrawing(props: { examId: string; userId: string; questionId: string }) { + const t = useT(); + const imgSrc = `/api/exams/${props.examId}/attempts/${props.userId}/answers/${props.questionId}/image`; + const [scene, setScene] = createSignal(null); + const [mode, setMode] = createSignal<"image" | "loading" | "playback" | "plain">("image"); + + const enterPlayback = async () => { + if (scene()) { + setMode("playback"); + return; + } + setMode("loading"); + try { + const blob = await getStudentAnswerImage(props.examId, props.userId, props.questionId); + const parsed = pngBytesToScene(new Uint8Array(await blob.arrayBuffer())); + if (parsed && parsed.strokes.length > 0) { + setScene(parsed); + setMode("playback"); + } else { + setMode("plain"); // plain image or no strokes → keep the img, hide Play + } + } catch { + setMode("image"); // fetch failed → keep the img, allow a retry + } + }; + + return ( +
+ {/* local boundary: the lazy playback chunk must not suspend the whole answer sheet */} + }> + } + > + {(s) => } + + + + + +
+ ); +} + export function AnswerSheetView(props: { examId: string; userId: string }) { const t = useT(); const [data] = createResource( @@ -82,11 +145,7 @@ export function AnswerSheetView(props: { examId: string; userId: string }) {

{t("exams.textAnswer")}

{row.answer?.text || "—"}

- {t("exams.drawAnswer")} + } diff --git a/src/components/exams/drawing-playback.tsx b/src/components/exams/drawing-playback.tsx new file mode 100644 index 0000000..590eff9 --- /dev/null +++ b/src/components/exams/drawing-playback.tsx @@ -0,0 +1,112 @@ +import { createSignal, onCleanup, onMount } from "solid-js"; +import { Button } from "@/components/ui/button"; +import { cn } from "@/lib/cn"; +import { PAPER_CELL, paintPaper, paintStroke, sliceStrokes, type DrawScene } from "@/lib/draw-stroke"; +import { useT } from "@/stores/preferences-context"; + +// ponytail: synthetic order-only pace — the drawing carries no per-point timing, so +// every answer replays at this constant point rate. Bump if playback feels too fast/slow. +const POINTS_PER_SECOND = 220; + +/** + * Replays a recovered drawing scene stroke-by-stroke in drawn order. Mirrors the + * export pipeline (drawing-file `renderBounds`/`canvasToImageBlob`) so a fully + * revealed frame is pixel-identical to the static answer : strokes go on a + * transparent layer (erasers cut only ink), then that layer is composited over + * white + paper ruling. No timestamps are read — order + a synthetic pace only. + */ +export function DrawingPlayback(props: { scene: DrawScene; class?: string }) { + const t = useT(); + let canvas: HTMLCanvasElement | undefined; + let layer: HTMLCanvasElement | undefined; // offscreen transparent stroke layer (the export's `source`) + let raf = 0; + let startedAt = 0; // performance.now() when the current run began + let baseCount = 0; // points already revealed when the run began (so pause/resume continues) + let revealed = 0; + // ponytail: DPR snapshotted at mount so the backing store and the paint transform can't + // drift apart when browser zoom changes mid-run; re-inits on remount (Show image → Play). + let scale = 1; + + const total = () => props.scene.strokes.reduce((n, s) => n + s.points.length, 0); + const [playing, setPlaying] = createSignal(true); + + const paint = (count: number) => { + const s = props.scene; + const lc = layer?.getContext("2d"); + const mc = canvas?.getContext("2d"); + if (!layer || !canvas || !lc || !mc) return; + // 1. stroke layer: clear + replay the revealed prefix in world coords. Strokes are + // already baked into the scene box, so a plain DPR scale places them like the export. + lc.setTransform(scale, 0, 0, scale, 0, 0); + lc.clearRect(0, 0, s.w, s.h); + const { full, partial } = sliceStrokes(s.strokes, count); + for (const st of full) paintStroke(lc, st); + if (partial) paintStroke(lc, partial); + // 2. main canvas: white → paper → composite the ink (matches canvasToImageBlob). + mc.setTransform(1, 0, 0, 1, 0, 0); + mc.fillStyle = "#ffffff"; + mc.fillRect(0, 0, canvas.width, canvas.height); + paintPaper(mc, s.bg ?? "none", canvas.width, canvas.height, PAPER_CELL * scale); + mc.drawImage(layer, 0, 0); + }; + + const loop = () => { + const elapsed = (performance.now() - startedAt) / 1000; + revealed = Math.min(total(), baseCount + Math.floor(elapsed * POINTS_PER_SECOND)); + paint(revealed); + if (revealed >= total()) { + setPlaying(false); // reached the end: freeze on the complete drawing + return; + } + raf = requestAnimationFrame(loop); + }; + + const play = () => { + if (revealed >= total()) revealed = 0; // finished → replay from the start + baseCount = revealed; + startedAt = performance.now(); + setPlaying(true); + cancelAnimationFrame(raf); + raf = requestAnimationFrame(loop); + }; + + const pause = () => { + cancelAnimationFrame(raf); + setPlaying(false); + }; + + const restart = () => { + revealed = 0; + play(); + }; + + onMount(() => { + scale = window.devicePixelRatio || 1; + const w = Math.max(1, Math.round(props.scene.w * scale)); + const h = Math.max(1, Math.round(props.scene.h * scale)); + if (canvas) { + canvas.width = w; + canvas.height = h; + } + layer = document.createElement("canvas"); + layer.width = w; + layer.height = h; + play(); // auto-start from blank — the teacher clicked "play" to get here + }); + + onCleanup(() => cancelAnimationFrame(raf)); + + return ( +
+ +
+ + +
+
+ ); +} diff --git a/src/i18n/messages.ts b/src/i18n/messages.ts index 3ab6c3c..7f91680 100644 --- a/src/i18n/messages.ts +++ b/src/i18n/messages.ts @@ -578,6 +578,11 @@ export type MessageKey = | "exams.isCorrect" | "exams.textAnswer" | "exams.drawAnswer" + | "exams.playDrawing" + | "exams.showImage" + | "exams.play" + | "exams.pause" + | "exams.restart" | "exams.editDrawing" | "exams.removeDrawing" | "exams.nameless" @@ -1306,6 +1311,11 @@ const en: Dict = { "exams.isCorrect": "Correct", "exams.textAnswer": "Text answer", "exams.drawAnswer": "Draw answer", + "exams.playDrawing": "Play drawing", + "exams.showImage": "Show image", + "exams.play": "Play", + "exams.pause": "Pause", + "exams.restart": "Restart", "exams.editDrawing": "Edit drawing", "exams.removeDrawing": "Remove drawing", "exams.nameless": "Unnamed", @@ -2028,6 +2038,11 @@ const tr: Dict = { "exams.isCorrect": "Doğru", "exams.textAnswer": "Metin cevap", "exams.drawAnswer": "Cevabı çiz", + "exams.playDrawing": "Çizimi oynat", + "exams.showImage": "Görseli göster", + "exams.play": "Oynat", + "exams.pause": "Duraklat", + "exams.restart": "Baştan al", "exams.editDrawing": "Çizimi düzenle", "exams.removeDrawing": "Çizimi kaldır", "exams.nameless": "İsimsiz", diff --git a/src/lib/draw-stroke.test.ts b/src/lib/draw-stroke.test.ts index 4b84be3..530f528 100644 --- a/src/lib/draw-stroke.test.ts +++ b/src/lib/draw-stroke.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from "vitest"; -import { paintPaper, paintStroke, paintTip, parseScene, strokesBounds, type DrawScene, type Stroke } from "./draw-stroke"; +import { paintPaper, paintStroke, paintTip, parseScene, sliceStrokes, strokesBounds, type DrawScene, type Stroke } from "./draw-stroke"; /** Records every 2d-context call so the three geometry branches can be asserted without a DOM. */ function stubContext() { @@ -158,6 +158,44 @@ describe("strokesBounds", () => { }); }); +describe("sliceStrokes", () => { + const a = stroke([{ x: 0, y: 0 }, { x: 1, y: 1 }, { x: 2, y: 2 }]); // 3 points + const b = stroke([{ x: 5, y: 5 }, { x: 6, y: 6 }, { x: 7, y: 7 }, { x: 8, y: 8 }]); // 4 points + + it("reveals nothing at count 0", () => { + expect(sliceStrokes([a, b], 0)).toEqual({ full: [], partial: null }); + }); + + it("reveals every stroke, no partial, at the total point count", () => { + expect(sliceStrokes([a, b], 7)).toEqual({ full: [a, b], partial: null }); + }); + + it("clamps past the total to the whole drawing", () => { + expect(sliceStrokes([a, b], 999)).toEqual({ full: [a, b], partial: null }); + }); + + it("truncates the stroke the cut lands inside", () => { + const { full, partial } = sliceStrokes([a, b], 5); // a whole (3) + first 2 of b + expect(full).toEqual([a]); + expect(partial).toEqual({ ...b, points: b.points.slice(0, 2) }); + }); + + it("gives no partial when the cut sits on a stroke boundary", () => { + expect(sliceStrokes([a, b], 3)).toEqual({ full: [a], partial: null }); // a done, b not started + }); + + it("handles a single-point stroke on both sides of its one point", () => { + const dot = stroke([{ x: 9, y: 9 }]); + expect(sliceStrokes([dot], 0)).toEqual({ full: [], partial: null }); + expect(sliceStrokes([dot], 1)).toEqual({ full: [dot], partial: null }); + }); + + it("is empty for no strokes", () => { + expect(sliceStrokes([], 0)).toEqual({ full: [], partial: null }); + expect(sliceStrokes([], 5)).toEqual({ full: [], partial: null }); + }); +}); + describe("paintPaper", () => { it("draws nothing for none", () => { const c = stubContext(); diff --git a/src/lib/draw-stroke.ts b/src/lib/draw-stroke.ts index 1f7082e..66b1624 100644 --- a/src/lib/draw-stroke.ts +++ b/src/lib/draw-stroke.ts @@ -73,6 +73,28 @@ export function strokesBounds(strokes: Stroke[]): { x: number; y: number; w: num return { x: minX, y: minY, w: maxX - minX, h: maxY - minY }; } +/** + * Split strokes at a reveal cut for order-only playback. Points are counted across + * strokes in drawn order; the first `revealCount` are "revealed". `full` = strokes + * shown in their entirety, `partial` = the stroke the cut lands inside, truncated to + * its revealed points (null when the cut sits on a stroke boundary). `revealCount` is + * clamped to [0, total points]; running out of strokes handles the upper bound. + */ +export function sliceStrokes(strokes: Stroke[], revealCount: number): { full: Stroke[]; partial: Stroke | null } { + let n = Math.max(0, Math.floor(revealCount)); + const full: Stroke[] = []; + for (const s of strokes) { + if (n >= s.points.length) { + full.push(s); + n -= s.points.length; + continue; + } + // cut lands inside this stroke (0 <= n < points.length); n === 0 means it hasn't started + return { full, partial: n > 0 ? { ...s, points: s.points.slice(0, n) } : null }; + } + return { full, partial: null }; +} + function applyBrush(c: CanvasRenderingContext2D, stroke: Stroke) { // The eraser cuts through the transparent drawing layer rather than painting // over it, so a saved drawing keeps whatever the caller flattens it onto.