From 0fbb97c415e59f50bad31dfb0a9f69cb5b8a39a4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Wed, 22 Jul 2026 05:52:31 +0300 Subject: [PATCH] =?UTF-8?q?feat:=20=F0=9F=8E=AC=20draw-and-replay=20for=20?= =?UTF-8?q?question-pool=20photos,=20DPR-correct=20playback?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 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.ts | 16 +++- src/api/__tests__/questions/questions.test.ts | 14 +++- src/api/__tests__/questions/solutions.test.ts | 14 +++- src/api/shared/questions.ts | 7 +- src/api/shared/solutions.ts | 7 +- src/components/exams/answer-sheet-view.tsx | 74 +++---------------- src/components/ui/draw-canvas.tsx | 10 ++- .../{exams => ui}/drawing-playback.tsx | 18 +++-- src/components/ui/replayable-image.tsx | 71 ++++++++++++++++++ src/lib/draw-stroke.test.ts | 69 ++++++++++++++++- src/lib/draw-stroke.ts | 43 ++++++++++- src/lib/drawing-file.test.ts | 13 +++- src/lib/png-meta.test.ts | 19 +++++ src/pages/question-detail-page.tsx | 45 +++++++++-- src/pages/questions-page.tsx | 24 +++++- 15 files changed, 345 insertions(+), 99 deletions(-) rename src/components/{exams => ui}/drawing-playback.tsx (82%) create mode 100644 src/components/ui/replayable-image.tsx diff --git a/src/api/__tests__/exams/exam-results.test.ts b/src/api/__tests__/exams/exam-results.test.ts index 7068da2..1c3c044 100644 --- a/src/api/__tests__/exams/exam-results.test.ts +++ b/src/api/__tests__/exams/exam-results.test.ts @@ -4,8 +4,8 @@ import { getExamResult } from "../../exams"; import { postExamResult } from "../../exams"; import { deleteExamResultByUserId } from "../../exams"; import { getExamStatistics } from "../../exams"; -import { getStudentAnswers } from "../../exams"; -import { lastFetchCall, mockFetch204, mockFetchSuccess } from "../helpers/mock-fetch"; +import { getStudentAnswers, getStudentAnswerImage } from "../../exams"; +import { lastFetchCall, mockFetch204, mockFetchBlob, mockFetchSuccess } from "../helpers/mock-fetch"; describe("exams API - results", () => { afterEach(() => { @@ -83,4 +83,16 @@ describe("exams API - results", () => { expect(url).toBe("/api/exams/ex1/attempts/u1/answers"); expect(init?.method).toBe("GET"); }); + + it("getStudentAnswerImage calls the grader answer-image URL with the API prefix applied once", async () => { + mockFetchBlob(new Blob([new Uint8Array([0x89, 0x50, 0x4e, 0x47])], { type: "image/png" })); + + const result = await getStudentAnswerImage("ex1", "u1", "q1"); + expect(result).toBeInstanceOf(Blob); + + // Must match the hardcoded template in answer-sheet-view.tsx exactly, or + // "Play drawing" fetches different bytes than the static image already on screen. + const [url] = lastFetchCall(); + expect(url).toBe("/api/exams/ex1/attempts/u1/answers/q1/image"); + }); }); diff --git a/src/api/__tests__/questions/questions.test.ts b/src/api/__tests__/questions/questions.test.ts index 2bdd35e..f806e1d 100644 --- a/src/api/__tests__/questions/questions.test.ts +++ b/src/api/__tests__/questions/questions.test.ts @@ -1,6 +1,6 @@ import { afterEach, describe, expect, it, vi } from "vitest"; -import { getQuestions, getQuestionById, postQuestion, postQuestionApprove, deleteQuestionById, getQuestionImageUrl } from "../../shared"; -import { lastFetchCall, mockFetch204, mockFetchSuccess } from "../helpers/mock-fetch"; +import { getQuestions, getQuestionById, postQuestion, postQuestionApprove, deleteQuestionById, getQuestionImageUrl, getQuestionImageBlob } from "../../shared"; +import { lastFetchCall, mockFetch204, mockFetchBlob, mockFetchSuccess } from "../helpers/mock-fetch"; describe("questions API", () => { afterEach(() => { @@ -72,4 +72,14 @@ describe("questions API", () => { const url = getQuestionImageUrl("q1"); expect(url).toBe("/api/questions/q1/image"); }); + + it("getQuestionImageBlob fetches the image bytes from the same URL", async () => { + mockFetchBlob(new Blob([new Uint8Array([0x89, 0x50, 0x4e, 0x47])], { type: "image/png" })); + + const result = await getQuestionImageBlob("q1"); + expect(result).toBeInstanceOf(Blob); + + const [url] = lastFetchCall(); + expect(url).toBe(getQuestionImageUrl("q1")); + }); }); diff --git a/src/api/__tests__/questions/solutions.test.ts b/src/api/__tests__/questions/solutions.test.ts index f7402bc..2a544b2 100644 --- a/src/api/__tests__/questions/solutions.test.ts +++ b/src/api/__tests__/questions/solutions.test.ts @@ -1,6 +1,6 @@ import { afterEach, describe, expect, it, vi } from "vitest"; -import { getSolutions, postSolution, patchSolutionById, deleteSolutionById, getSolutionImageUrl } from "../../shared"; -import { lastFetchCall, mockFetch204, mockFetchSuccess } from "../helpers/mock-fetch"; +import { getSolutions, postSolution, patchSolutionById, deleteSolutionById, getSolutionImageUrl, getSolutionImageBlob } from "../../shared"; +import { lastFetchCall, mockFetch204, mockFetchBlob, mockFetchSuccess } from "../helpers/mock-fetch"; describe("solutions API", () => { afterEach(() => { @@ -61,4 +61,14 @@ describe("solutions API", () => { const url = getSolutionImageUrl("q1", "s1"); expect(url).toBe("/api/questions/q1/solutions/s1/image"); }); + + it("getSolutionImageBlob fetches the image bytes from the same URL", async () => { + mockFetchBlob(new Blob([new Uint8Array([0x89, 0x50, 0x4e, 0x47])], { type: "image/png" })); + + const result = await getSolutionImageBlob("q1", "s1"); + expect(result).toBeInstanceOf(Blob); + + const [url] = lastFetchCall(); + expect(url).toBe(getSolutionImageUrl("q1", "s1")); + }); }); diff --git a/src/api/shared/questions.ts b/src/api/shared/questions.ts index 228d6f0..d4539d1 100644 --- a/src/api/shared/questions.ts +++ b/src/api/shared/questions.ts @@ -1,4 +1,4 @@ -import { client, formClient } from "../client"; +import { blobClient, client, formClient } from "../client"; import type { Page, PageParams } from "../client"; import type { PersonRef } from "../client"; @@ -74,3 +74,8 @@ export async function deleteQuestionById(id: string): Promise { export function getQuestionImageUrl(id: string): string { return `/api/questions/${id}/image`; } + +/** Raw bytes of the same image — needed to recover an embedded drawing scene. */ +export function getQuestionImageBlob(id: string, signal?: AbortSignal): Promise { + return blobClient(`/questions/${id}/image`, signal); +} diff --git a/src/api/shared/solutions.ts b/src/api/shared/solutions.ts index e3c56dc..2219b0d 100644 --- a/src/api/shared/solutions.ts +++ b/src/api/shared/solutions.ts @@ -1,4 +1,4 @@ -import { client, formClient } from "../client"; +import { blobClient, client, formClient } from "../client"; import type { Page, PageParams } from "../client"; import type { PersonRef } from "../client"; @@ -70,3 +70,8 @@ export async function deleteSolutionById(id: string, sid: string): Promise export function getSolutionImageUrl(id: string, sid: string): string { return `/api/questions/${id}/solutions/${sid}/image`; } + +/** Raw bytes of the same image — needed to recover an embedded drawing scene. */ +export function getSolutionImageBlob(id: string, sid: string, signal?: AbortSignal): Promise { + return blobClient(`/questions/${id}/solutions/${sid}/image`, signal); +} diff --git a/src/components/exams/answer-sheet-view.tsx b/src/components/exams/answer-sheet-view.tsx index d7bd0ac..96e4a8f 100644 --- a/src/components/exams/answer-sheet-view.tsx +++ b/src/components/exams/answer-sheet-view.tsx @@ -1,79 +1,17 @@ -import { For, Show, Suspense, createResource, createSignal, lazy } from "solid-js"; +import { For, Show, Suspense, createResource } from "solid-js"; import { ApiError } from "@/api/client"; import { getExamQuestions } 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 { ReplayableImage } from "@/components/ui/replayable-image"; 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( @@ -145,7 +83,13 @@ export function AnswerSheetView(props: { examId: string; userId: string }) {

{t("exams.textAnswer")}

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

- + getStudentAnswerImage(d().sheet.exam, d().sheet.user.id, row.question.id)} + src={`/api/exams/${d().sheet.exam}/attempts/${d().sheet.user.id}/answers/${row.question.id}/image`} + alt={t("exams.drawAnswer")} + imgClass="h-64 w-full max-w-2xl rounded-md border bg-background object-contain" + /> } diff --git a/src/components/ui/draw-canvas.tsx b/src/components/ui/draw-canvas.tsx index 6d7530f..134c903 100644 --- a/src/components/ui/draw-canvas.tsx +++ b/src/components/ui/draw-canvas.tsx @@ -2,7 +2,7 @@ import { For, Match, Show, Switch, createEffect, createSignal, onCleanup, onMoun import { Button } from "@/components/ui/button"; import { IconDownload, IconEdit, IconEraser, IconGrid, IconMove, IconRuled, IconSave, IconSquareOff, IconTrash, IconUndo, IconZoomIn, IconZoomOut } from "@/components/ui/icons"; import { cn } from "@/lib/cn"; -import { PAPER_CELL, PAPER_LINE, paintStroke, paintTip, strokesBounds, type BgKind, type DrawScene, type Point, type Stroke } from "@/lib/draw-stroke"; +import { PAPER_CELL, PAPER_LINE, canvasPx, paintStroke, paintTip, strokesBounds, type BgKind, type DrawScene, type Point, type Stroke } from "@/lib/draw-stroke"; import { canvasToImageBlob, sceneToPngFile } from "@/lib/drawing-file"; import { useT } from "@/stores/preferences-context"; @@ -249,14 +249,16 @@ export function DrawCanvas(props: { const dx = EXPORT_MARGIN - b.x; const dy = EXPORT_MARGIN - b.y; const off = document.createElement("canvas"); - off.width = Math.round(w * scale); - off.height = Math.round(h * scale); + off.width = canvasPx(w, scale); + off.height = canvasPx(h, scale); const oc = off.getContext("2d"); if (!oc) return null; oc.setTransform(scale, 0, 0, scale, dx * scale, dy * scale); for (const s of list) paintStroke(oc, s); const shifted = list.map((s) => ({ ...s, points: s.points.map((p) => ({ x: p.x + dx, y: p.y + dy })) })); - const scene: DrawScene = { v: 1, w, h, strokes: shifted, bg: bg() }; + // dpr rides along: the PNG is baked at this ratio, so a viewer on a different + // display can size the replay to the same pixels instead of its own ratio. + const scene: DrawScene = { v: 1, w, h, strokes: shifted, bg: bg(), dpr: scale }; return { canvas: off, scene }; }; diff --git a/src/components/exams/drawing-playback.tsx b/src/components/ui/drawing-playback.tsx similarity index 82% rename from src/components/exams/drawing-playback.tsx rename to src/components/ui/drawing-playback.tsx index 590eff9..e401e69 100644 --- a/src/components/exams/drawing-playback.tsx +++ b/src/components/ui/drawing-playback.tsx @@ -1,7 +1,7 @@ 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 { PAPER_CELL, canvasPx, 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 @@ -15,7 +15,7 @@ const POINTS_PER_SECOND = 220; * 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 }) { +export function DrawingPlayback(props: { scene: DrawScene; class?: string; canvasClass?: string }) { const t = useT(); let canvas: HTMLCanvasElement | undefined; let layer: HTMLCanvasElement | undefined; // offscreen transparent stroke layer (the export's `source`) @@ -23,8 +23,9 @@ export function DrawingPlayback(props: { scene: DrawScene; class?: string }) { 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). + // The scene's own export DPR when it has one (older scenes fall back to this display's), + // so the canvas gets the saved PNG's exact pixels instead of the viewer's ratio. Snapshotted + // at mount so backing store and paint transform can't drift apart if zoom changes mid-run. let scale = 1; 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 }) { }; 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)); + scale = props.scene.dpr ?? (window.devicePixelRatio || 1); + const w = canvasPx(props.scene.w, scale); + const h = canvasPx(props.scene.h, scale); if (canvas) { canvas.width = w; canvas.height = h; @@ -98,7 +99,8 @@ export function DrawingPlayback(props: { scene: DrawScene; class?: string }) { return (
- + {/* Sized by the caller so the replay matches the static image it replaces. */} +
+ +
+ ); +} diff --git a/src/lib/draw-stroke.test.ts b/src/lib/draw-stroke.test.ts index 530f528..efe00dc 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, sliceStrokes, strokesBounds, type DrawScene, type Stroke } from "./draw-stroke"; +import { canvasPx, paintPaper, paintStroke, paintTip, parseScene, playableScene, 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() { @@ -120,6 +120,16 @@ describe("parseScene", () => { expect(parseScene(JSON.stringify({ ...scene, v: 2 }))).toBeNull(); }); + // w/h size the playback canvas and drive paintPaper's per-cell loop, from a PNG anyone + // can upload: a real export can be big, but never non-finite, negative or past MAX_SIDE. + it("accepts a large-but-real box, rejects non-finite, non-positive and absurd sides", () => { + expect(parseScene(JSON.stringify({ ...scene, w: 8000, h: 16384 }))).not.toBeNull(); + // 1e999 is valid JSON that parses to Infinity; null is what JSON.stringify makes of NaN. + for (const bad of ["1e999", "-1", "0", "1e9", "null", '"10"']) { + expect(parseScene(`{"v":1,"w":${bad},"h":10,"strokes":[]}`)).toBeNull(); + } + }); + it("rejects a malformed stroke shape", () => { expect(parseScene(JSON.stringify({ v: 1, w: 1, h: 1, strokes: [{ color: "#000" }] }))).toBeNull(); }); @@ -128,6 +138,18 @@ describe("parseScene", () => { expect(parseScene("not json")).toBeNull(); expect(parseScene(null)).toBeNull(); }); + + // dpr multiplies the playback canvas allocation, from a PNG anyone can upload: it must + // survive the round trip, stay optional for drawings saved before it existed, and never + // arrive as something unusable or absurd. + it("round-trips dpr, tolerates its absence, rejects bogus or out-of-range ones", () => { + expect(parseScene(JSON.stringify({ ...scene, dpr: 2 }))?.dpr).toBe(2); + expect(parseScene(JSON.stringify({ ...scene, dpr: 0.5 }))?.dpr).toBe(0.5); // zoomed-out export + expect(parseScene(JSON.stringify(scene))?.dpr).toBeUndefined(); + expect(parseScene(JSON.stringify({ ...scene, dpr: 0 }))).toBeNull(); + expect(parseScene(JSON.stringify({ ...scene, dpr: "2" }))).toBeNull(); + expect(parseScene(JSON.stringify({ ...scene, dpr: 1e9 }))).toBeNull(); // tab-killer allocation + }); }); describe("strokesBounds", () => { @@ -223,3 +245,48 @@ describe("paintPaper", () => { expect(vertical.length).toBeGreaterThan(0); }); }); + +// canvasPx is the one spot both the export (draw-canvas's renderBounds) and playback +// (drawing-playback's onMount) canvases round a world-px side into device px — if the +// two ever computed this differently, the replay would render at a different on-screen +// size than the static it swaps in for. +describe("canvasPx", () => { + it("rounds world px * dpr to the nearest device px across export- and playback-typical dprs", () => { + for (const side of [1, 16.5, 100.4, 123.7, 8000]) { + for (const dpr of [0.5, 1, 2, 3]) { + expect(canvasPx(side, dpr)).toBe(Math.max(1, Math.round(side * dpr))); + } + } + }); + + it("floors at 1 device px so a tiny side at a sub-1 dpr never yields a 0-sized canvas", () => { + expect(canvasPx(0.5, 0.5)).toBe(1); // 0.25 rounds to 0, which a canvas can't allocate + }); + + // drawing-playback's onMount resolves `scene.dpr ?? window.devicePixelRatio` before + // calling canvasPx — mirrored here since onMount itself needs a real DOM mount, which + // this repo has no headless (jsdom-free) way to drive. + it("mirrors the playback side's dpr fallback: a scene without dpr uses the viewer's ratio", () => { + const viewerRatio = 3; + const missingDpr: number | undefined = undefined; + const savedDpr: number | undefined = 2; + expect(canvasPx(100, missingDpr ?? viewerRatio)).toBe(canvasPx(100, viewerRatio)); + expect(canvasPx(100, savedDpr ?? viewerRatio)).toBe(canvasPx(100, 2)); // a saved dpr wins over the fallback + }); +}); + +describe("playableScene", () => { + const scene: DrawScene = { v: 1, w: 10, h: 10, strokes: [stroke([{ x: 0, y: 0 }, { x: 1, y: 1 }])] }; + + it("passes through a scene with at least one stroke — the playback branch", () => { + expect(playableScene(scene)).toBe(scene); + }); + + it("is null for a scene with zero strokes — an emptied drawing falls back to the static image", () => { + expect(playableScene({ ...scene, strokes: [] })).toBeNull(); + }); + + it("is null for null — a plain photo with nothing embedded", () => { + expect(playableScene(null)).toBeNull(); + }); +}); diff --git a/src/lib/draw-stroke.ts b/src/lib/draw-stroke.ts index 66b1624..10f1885 100644 --- a/src/lib/draw-stroke.ts +++ b/src/lib/draw-stroke.ts @@ -1,7 +1,8 @@ export type Point = { x: number; y: number }; export type Stroke = { color: string; width: number; erase: boolean; points: Point[] }; export type BgKind = "none" | "lines" | "grid"; -export type DrawScene = { v: 1; w: number; h: number; strokes: Stroke[]; bg?: BgKind }; +/** `w`/`h` are DPR-free world px; `dpr` is the device ratio the PNG beside them was baked at. */ +export type DrawScene = { v: 1; w: number; h: number; strokes: Stroke[]; bg?: BgKind; dpr?: number }; /** World px per notebook cell — shared by the live CSS paper and the baked export so both read as the same ruling. */ export const PAPER_CELL = 24; @@ -12,6 +13,18 @@ function isPoint(p: unknown): p is Point { return !!p && typeof p === "object" && typeof (p as Point).x === "number" && typeof (p as Point).y === "number"; } +/** + * Export-box side in world px: finite, positive, and no wider than the largest canvas a + * browser will make. A real export was itself rendered through a `w × dpr` canvas (dpr ≥ 1 + * on any normal display), so nothing legitimate can exceed this — while an unbounded side + * both sizes the playback allocation and drives paintPaper's per-cell loop. + */ +const MAX_SIDE = 16384; + +function isSide(n: unknown): n is number { + return typeof n === "number" && n > 0 && n <= MAX_SIDE; // NaN/Infinity fail the comparisons +} + function isStroke(s: unknown): s is Stroke { if (!s || typeof s !== "object") return false; const st = s as Stroke; @@ -39,15 +52,30 @@ export function parseScene(text: string | null): DrawScene | null { } if (!data || typeof data !== "object") return null; const scene = data as DrawScene; - if (scene.v !== 1 || typeof scene.w !== "number" || typeof scene.h !== "number" || !Array.isArray(scene.strokes)) { + if (scene.v !== 1 || !isSide(scene.w) || !isSide(scene.h) || !Array.isArray(scene.strokes)) { return null; } if (!scene.strokes.every(isStroke)) return null; // bg is optional (old drawings lack it); reject only a present-but-bogus value. if (scene.bg !== undefined && scene.bg !== "none" && scene.bg !== "lines" && scene.bg !== "grid") return null; + // dpr likewise optional, but it multiplies a canvas allocation on the viewer's machine, so + // cap it at 8 — well past any real display (1–3), while browser zoom-out legitimately + // exports below 1. NaN/Infinity fail the comparisons. + if (scene.dpr !== undefined && !(typeof scene.dpr === "number" && scene.dpr > 0 && scene.dpr <= 8)) return null; return scene; } +/** + * A parsed scene is only worth replaying if it has ink: a plain photo (parse failed, + * null) or an emptied drawing (parsed, zero strokes) both mean "nothing to play", so + * ReplayableImage falls back to the static image for either. Pulled out of that + * component (which has three call sites of its own) so the decision is unit-testable + * without mounting Solid. + */ +export function playableScene(parsed: DrawScene | null): DrawScene | null { + return parsed && parsed.strokes.length > 0 ? parsed : null; +} + /** * Tight bounding box over every ink (pen) stroke, padded by its half-width so a * 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 return { x: minX, y: minY, w: maxX - minX, h: maxY - minY }; } +/** + * World px → device px for one canvas side, shared by the export (`renderBounds`, + * baking `scene.w`/`scene.h` at `scene.dpr`) and playback (`onMount`, replaying them at + * that same dpr) so the two can't round differently and size the replay canvas + * differently on screen than the static image it replaces. Floors at 1: a canvas side + * of 0 throws, which a tiny world side at a sub-1 dpr could otherwise round down to. + */ +export function canvasPx(worldSide: number, dpr: number): number { + return Math.max(1, Math.round(worldSide * dpr)); +} + /** * 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 diff --git a/src/lib/drawing-file.test.ts b/src/lib/drawing-file.test.ts index 8a4b6e7..95d2afa 100644 --- a/src/lib/drawing-file.test.ts +++ b/src/lib/drawing-file.test.ts @@ -16,13 +16,22 @@ function minimalPng(): Uint8Array { } describe("pngBytesToScene", () => { - it("round-trips a scene carried in the PNG's tEXt chunk", () => { + it("round-trips a scene carried in the PNG's tEXt chunk, every field intact", () => { const scene: DrawScene = { v: 1, w: 120, h: 90, - strokes: [{ color: "#1f2937", width: 6, erase: false, points: [{ x: 1, y: 2 }, { x: 3, y: 4 }] }], + bg: "grid", + dpr: 2, + strokes: [ + { color: "#1f2937", width: 6, erase: false, points: [{ x: 1, y: 2 }, { x: 3, y: 4 }] }, + { color: "#dc2626", width: 14, erase: true, points: [{ x: 10, y: 10 }] }, + ], }; + // "hezarfen-drawing" here must match drawing-file.ts's private DRAWING_KEYWORD + // constant exactly — it's a wire format shared with every already-saved + // .hzdraw.png. If pngBytesToScene's own keyword ever drifted from this literal, + // extractPngText would find no chunk under it and this would come back null. const png = embedPngText(minimalPng(), "hezarfen-drawing", JSON.stringify(scene)); expect(pngBytesToScene(png)).toEqual(scene); }); diff --git a/src/lib/png-meta.test.ts b/src/lib/png-meta.test.ts index ee43605..1df74f9 100644 --- a/src/lib/png-meta.test.ts +++ b/src/lib/png-meta.test.ts @@ -1,4 +1,5 @@ import { describe, expect, it } from "vitest"; +import type { DrawScene } from "./draw-stroke"; import { embedPngText, extractPngText } from "./png-meta"; const SIGNATURE = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]; @@ -60,4 +61,22 @@ describe("png-meta", () => { const embedded = ((png[crcAt] << 24) | (png[crcAt + 1] << 16) | (png[crcAt + 2] << 8) | png[crcAt + 3]) >>> 0; expect(embedded).toBe(refCrc32(typeAndData)); }); + + it("round-trips a full drawing scene's JSON — strokes, points, colour, width, erase, bg, w/h, dpr — byte-for-byte", () => { + const scene: DrawScene = { + v: 1, + w: 120, + h: 80, + bg: "grid", + dpr: 2, + strokes: [ + { color: "#1f2937", width: 6, erase: false, points: [{ x: 1, y: 2 }, { x: 3.5, y: 4 }] }, + { color: "#dc2626", width: 14, erase: true, points: [{ x: 10, y: 10 }] }, + ], + }; + const json = JSON.stringify(scene); + const png = embedPngText(minimalPng(), "hezarfen-drawing", json); + expect(extractPngText(png, "hezarfen-drawing")).toBe(json); + expect(JSON.parse(extractPngText(png, "hezarfen-drawing")!)).toEqual(scene); + }); }); diff --git a/src/pages/question-detail-page.tsx b/src/pages/question-detail-page.tsx index 4b74e5c..98f11b4 100644 --- a/src/pages/question-detail-page.tsx +++ b/src/pages/question-detail-page.tsx @@ -1,7 +1,7 @@ -import { For, Show, Suspense, createResource, createSignal } from "solid-js"; +import { For, Show, Suspense, createResource, createSignal, lazy } from "solid-js"; import { useParams, useRouter } from "@tanstack/solid-router"; -import { getQuestionById, deleteQuestionById, postQuestionApprove, getQuestionImageUrl } from "@/api/shared"; -import { getSolutions, postSolution, patchSolutionById, deleteSolutionById, getSolutionImageUrl } from "@/api/shared"; +import { getQuestionById, deleteQuestionById, postQuestionApprove, getQuestionImageUrl, getQuestionImageBlob } from "@/api/shared"; +import { getSolutions, postSolution, patchSolutionById, deleteSolutionById, getSolutionImageUrl, getSolutionImageBlob } from "@/api/shared"; import type { SolutionResponse } from "@/api/shared"; import { formatApiError } from "@/api/client"; import { RouteGuard } from "@/components/layout/route-guard"; @@ -12,6 +12,7 @@ import { ConfirmDialog } from "@/components/ui/confirm-dialog"; import { Label } from "@/components/ui/label"; import { Textarea } from "@/components/ui/textarea"; import { IconTrash, IconCheck, IconX, IconEdit, IconMessage, IconPhoto } from "@/components/ui/icons"; +import { ReplayableImage } from "@/components/ui/replayable-image"; import { personLabel } from "@/lib/person"; import { ErrorAlert } from "@/components/ui/error-alert"; @@ -20,6 +21,9 @@ import { useT } from "@/stores/preferences-context"; import { useAuth } from "@/stores/auth-context"; import { hasMinRole } from "@/lib/roles"; +// Lazy so the drawing pad rides its own chunk, off the question detail's initial load. +const DrawCanvas = lazy(() => import("@/components/ui/draw-canvas").then((m) => ({ default: m.DrawCanvas }))); + export default function QuestionDetailPage() { return ( @@ -118,8 +122,13 @@ function QuestionDetailContent() {

{q().body}

-
- Question Attachment +
+ getQuestionImageBlob(q().id)} + src={getQuestionImageUrl(q().id)} + alt="Question Attachment" + imgClass="max-h-[500px] w-auto object-contain mx-auto" + />
@@ -163,8 +172,13 @@ function QuestionDetailContent() {

{sol.body}

-
- Solution Attachment +
+ getSolutionImageBlob(q().id, sol.id)} + src={getSolutionImageUrl(q().id, sol.id)} + alt="Solution Attachment" + imgClass="max-h-[300px] w-auto object-contain mx-auto" + />
@@ -236,6 +250,7 @@ function SolutionFormDialog(props: { questionId: string; initialData?: SolutionR const [error, setError] = createSignal(""); const [body, setBody] = createSignal(props.initialData?.body || ""); const [file, setFile] = createSignal(null); + const [drawing, setDrawing] = createSignal(false); const handleSubmit = async (e: Event) => { e.preventDefault(); @@ -306,6 +321,22 @@ function SolutionFormDialog(props: { questionId: string; initialData?: SolutionR onChange={(e) => setFile(e.currentTarget.files?.[0] || null)} />
+ {/* Draw instead of upload: the pad saves a PNG File, so it rides the same upload. */} + + + }> + { + setFile(drawn); + setDrawing(false); + }} + /> + +
diff --git a/src/pages/questions-page.tsx b/src/pages/questions-page.tsx index a5a73ab..a3b68f0 100644 --- a/src/pages/questions-page.tsx +++ b/src/pages/questions-page.tsx @@ -1,4 +1,4 @@ -import { For, Show, Suspense, createResource, createSignal } from "solid-js"; +import { For, Show, Suspense, createResource, createSignal, lazy } from "solid-js"; import { Link, useSearch, useNavigate } from "@tanstack/solid-router"; import { getQuestions, postQuestion } from "@/api/shared"; import { formatApiError } from "@/api/client"; @@ -11,7 +11,7 @@ import { FormDialog } from "@/components/ui/form-dialog"; import { Label } from "@/components/ui/label"; import { Input } from "@/components/ui/input"; import { Textarea } from "@/components/ui/textarea"; -import { IconPlus, IconClock, IconCheck, IconPhoto, IconX } from "@/components/ui/icons"; +import { IconPlus, IconClock, IconCheck, IconPhoto, IconX, IconEdit } from "@/components/ui/icons"; import { personLabel } from "@/lib/person"; import { ErrorAlert } from "@/components/ui/error-alert"; @@ -20,6 +20,9 @@ import { useT } from "@/stores/preferences-context"; import { useAuth } from "@/stores/auth-context"; import { cn } from "@/lib/cn"; +// Lazy so the drawing pad rides its own chunk, off the question list's initial load. +const DrawCanvas = lazy(() => import("@/components/ui/draw-canvas").then((m) => ({ default: m.DrawCanvas }))); + export default function QuestionsPage() { return ( @@ -137,6 +140,7 @@ function AskQuestionDialog(props: { onClose: () => void; onSuccess: () => void } const [title, setTitle] = createSignal(""); const [body, setBody] = createSignal(""); const [file, setFile] = createSignal(null); + const [drawing, setDrawing] = createSignal(false); const handleSubmit = async (e: Event) => { e.preventDefault(); @@ -206,6 +210,22 @@ function AskQuestionDialog(props: { onClose: () => void; onSuccess: () => void } onChange={(e) => setFile(e.currentTarget.files?.[0] || null)} />
+ {/* Draw instead of upload: the pad saves a PNG File, so it rides the same upload. */} + + + }> + { + setFile(drawn); + setDrawing(false); + }} + /> + +