🎬 draw-and-replay for question-pool photos, DPR-correct playback
Browse files at this commit0fbb97c415e59f50bad31dfb0a9f69cb5b8a39a4Parent: 595aa7e- feat
- 🎬 draw-and-replay for question-pool photos, DPR-correct playback
15 changed files +345 -99
- src/api/__tests__/exams/exam-results.test.ts +14 -2
- src/api/__tests__/questions/questions.test.ts +12 -2
- src/api/__tests__/questions/solutions.test.ts +12 -2
- src/api/shared/questions.ts +6 -1
- src/api/shared/solutions.ts +6 -1
- src/components/exams/answer-sheet-view.tsx +9 -65
- src/components/ui/draw-canvas.tsx +6 -4
- src/components/exams/drawing-playback.tsx → src/components/ui/drawing-playback.tsx +10 -8
- src/components/ui/replayable-image.tsx +71 -0
- src/lib/draw-stroke.test.ts +68 -1
- src/lib/draw-stroke.ts +41 -2
- src/lib/drawing-file.test.ts +11 -2
- src/lib/png-meta.test.ts +19 -0
- src/pages/question-detail-page.tsx +38 -7
- src/pages/questions-page.tsx +22 -2
src/api/__tests__/exams/exam-results.test.tsmodified+14 -2
| @@ -4,8 +4,8 @@ import { getExamResult } from "../../exams"; | |||
| 4 | import { postExamResult } from "../../exams"; | 4 | import { postExamResult } from "../../exams"; |
| 5 | import { deleteExamResultByUserId } from "../../exams"; | 5 | import { deleteExamResultByUserId } from "../../exams"; |
| 6 | import { getExamStatistics } from "../../exams"; | 6 | import { getExamStatistics } from "../../exams"; |
| 7 | -import { getStudentAnswers } from "../../exams"; | 7 | +import { getStudentAnswers, getStudentAnswerImage } from "../../exams"; |
| 8 | -import { lastFetchCall, mockFetch204, mockFetchSuccess } from "../helpers/mock-fetch"; | 8 | +import { lastFetchCall, mockFetch204, mockFetchBlob, mockFetchSuccess } from "../helpers/mock-fetch"; |
| 9 | 9 | ||
| 10 | describe("exams API - results", () => { | 10 | describe("exams API - results", () => { |
| 11 | afterEach(() => { | 11 | afterEach(() => { |
| @@ -83,4 +83,16 @@ describe("exams API - results", () => { | |||
| 83 | expect(url).toBe("/api/exams/ex1/attempts/u1/answers"); | 83 | expect(url).toBe("/api/exams/ex1/attempts/u1/answers"); |
| 84 | expect(init?.method).toBe("GET"); | 84 | expect(init?.method).toBe("GET"); |
| 85 | }); | 85 | }); |
| 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 | + }); | ||
| 86 | }); | 98 | }); |
src/api/__tests__/questions/questions.test.tsmodified+12 -2
| @@ -1,6 +1,6 @@ | |||
| 1 | import { afterEach, describe, expect, it, vi } from "vitest"; | 1 | import { afterEach, describe, expect, it, vi } from "vitest"; |
| 2 | -import { getQuestions, getQuestionById, postQuestion, postQuestionApprove, deleteQuestionById, getQuestionImageUrl } from "../../shared"; | 2 | +import { getQuestions, getQuestionById, postQuestion, postQuestionApprove, deleteQuestionById, getQuestionImageUrl, getQuestionImageBlob } from "../../shared"; |
| 3 | -import { lastFetchCall, mockFetch204, mockFetchSuccess } from "../helpers/mock-fetch"; | 3 | +import { lastFetchCall, mockFetch204, mockFetchBlob, mockFetchSuccess } from "../helpers/mock-fetch"; |
| 4 | 4 | ||
| 5 | describe("questions API", () => { | 5 | describe("questions API", () => { |
| 6 | afterEach(() => { | 6 | afterEach(() => { |
| @@ -72,4 +72,14 @@ describe("questions API", () => { | |||
| 72 | const url = getQuestionImageUrl("q1"); | 72 | const url = getQuestionImageUrl("q1"); |
| 73 | expect(url).toBe("/api/questions/q1/image"); | 73 | expect(url).toBe("/api/questions/q1/image"); |
| 74 | }); | 74 | }); |
| 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 | + }); | ||
| 75 | }); | 85 | }); |
src/api/__tests__/questions/solutions.test.tsmodified+12 -2
| @@ -1,6 +1,6 @@ | |||
| 1 | import { afterEach, describe, expect, it, vi } from "vitest"; | 1 | import { afterEach, describe, expect, it, vi } from "vitest"; |
| 2 | -import { getSolutions, postSolution, patchSolutionById, deleteSolutionById, getSolutionImageUrl } from "../../shared"; | 2 | +import { getSolutions, postSolution, patchSolutionById, deleteSolutionById, getSolutionImageUrl, getSolutionImageBlob } from "../../shared"; |
| 3 | -import { lastFetchCall, mockFetch204, mockFetchSuccess } from "../helpers/mock-fetch"; | 3 | +import { lastFetchCall, mockFetch204, mockFetchBlob, mockFetchSuccess } from "../helpers/mock-fetch"; |
| 4 | 4 | ||
| 5 | describe("solutions API", () => { | 5 | describe("solutions API", () => { |
| 6 | afterEach(() => { | 6 | afterEach(() => { |
| @@ -61,4 +61,14 @@ describe("solutions API", () => { | |||
| 61 | const url = getSolutionImageUrl("q1", "s1"); | 61 | const url = getSolutionImageUrl("q1", "s1"); |
| 62 | expect(url).toBe("/api/questions/q1/solutions/s1/image"); | 62 | expect(url).toBe("/api/questions/q1/solutions/s1/image"); |
| 63 | }); | 63 | }); |
| 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 | + }); | ||
| 64 | }); | 74 | }); |
src/api/shared/questions.tsmodified+6 -1
| @@ -1,4 +1,4 @@ | |||
| 1 | -import { client, formClient } from "../client"; | 1 | +import { blobClient, client, formClient } from "../client"; |
| 2 | import type { Page, PageParams } from "../client"; | 2 | import type { Page, PageParams } from "../client"; |
| 3 | import type { PersonRef } from "../client"; | 3 | import type { PersonRef } from "../client"; |
| 4 | 4 | ||
| @@ -74,3 +74,8 @@ export async function deleteQuestionById(id: string): Promise<void> { | |||
| 74 | export function getQuestionImageUrl(id: string): string { | 74 | export function getQuestionImageUrl(id: string): string { |
| 75 | return `/api/questions/${id}/image`; | 75 | return `/api/questions/${id}/image`; |
| 76 | } | 76 | } |
| 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"; |
| 2 | import type { Page, PageParams } from "../client"; | 2 | import type { Page, PageParams } from "../client"; |
| 3 | import type { PersonRef } from "../client"; | 3 | import type { PersonRef } from "../client"; |
| 4 | 4 | ||
| @@ -70,3 +70,8 @@ export async function deleteSolutionById(id: string, sid: string): Promise<void> | |||
| 70 | export function getSolutionImageUrl(id: string, sid: string): string { | 70 | export function getSolutionImageUrl(id: string, sid: string): string { |
| 71 | return `/api/questions/${id}/solutions/${sid}/image`; | 71 | return `/api/questions/${id}/solutions/${sid}/image`; |
| 72 | } | 72 | } |
| 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"; |
| 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, getStudentAnswerImage } 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"; | ||
| 8 | import { IconCheck, IconX } from "@/components/ui/icons"; | 7 | import { IconCheck, IconX } from "@/components/ui/icons"; |
| 9 | import { PageSpinner } from "@/components/ui/page-spinner"; | 8 | import { PageSpinner } from "@/components/ui/page-spinner"; |
| 9 | +import { ReplayableImage } from "@/components/ui/replayable-image"; | ||
| 10 | import { cn } from "@/lib/cn"; | 10 | import { cn } from "@/lib/cn"; |
| 11 | 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"; | ||
| 14 | import { personLabelWithId } from "@/lib/person"; | 12 | import { personLabelWithId } from "@/lib/person"; |
| 15 | import { useT } from "@/stores/preferences-context"; | 13 | import { useT } from "@/stores/preferences-context"; |
| 16 | 14 | ||
| 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 | - | ||
| 77 | export function AnswerSheetView(props: { examId: string; userId: string }) { | 15 | export function AnswerSheetView(props: { examId: string; userId: string }) { |
| 78 | const t = useT(); | 16 | const t = useT(); |
| 79 | const [data] = createResource( | 17 | const [data] = createResource( |
| @@ -145,7 +83,13 @@ export function AnswerSheetView(props: { examId: string; userId: string }) { | |||
| 145 | <p class="text-xs text-muted-foreground">{t("exams.textAnswer")}</p> | 83 | <p class="text-xs text-muted-foreground">{t("exams.textAnswer")}</p> |
| 146 | <p class="mt-1 whitespace-pre-wrap text-sm">{row.answer?.text || "—"}</p> | 84 | <p class="mt-1 whitespace-pre-wrap text-sm">{row.answer?.text || "—"}</p> |
| 147 | <Show when={row.answer?.answer_image}> | 85 | <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 | + /> | ||
| 149 | </Show> | 93 | </Show> |
| 150 | </div> | 94 | </div> |
| 151 | } | 95 | } |
src/components/ui/draw-canvas.tsxmodified+6 -4
| @@ -2,7 +2,7 @@ import { For, Match, Show, Switch, createEffect, createSignal, onCleanup, onMoun | |||
| 2 | import { Button } from "@/components/ui/button"; | 2 | import { Button } from "@/components/ui/button"; |
| 3 | import { IconDownload, IconEdit, IconEraser, IconGrid, IconMove, IconRuled, IconSave, IconSquareOff, IconTrash, IconUndo, IconZoomIn, IconZoomOut } from "@/components/ui/icons"; | 3 | import { IconDownload, IconEdit, IconEraser, IconGrid, IconMove, IconRuled, IconSave, IconSquareOff, IconTrash, IconUndo, IconZoomIn, IconZoomOut } from "@/components/ui/icons"; |
| 4 | import { cn } from "@/lib/cn"; | 4 | 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"; |
| 6 | import { canvasToImageBlob, sceneToPngFile } from "@/lib/drawing-file"; | 6 | import { canvasToImageBlob, sceneToPngFile } from "@/lib/drawing-file"; |
| 7 | import { useT } from "@/stores/preferences-context"; | 7 | import { useT } from "@/stores/preferences-context"; |
| 8 | 8 | ||
| @@ -249,14 +249,16 @@ export function DrawCanvas(props: { | |||
| 249 | const dx = EXPORT_MARGIN - b.x; | 249 | const dx = EXPORT_MARGIN - b.x; |
| 250 | const dy = EXPORT_MARGIN - b.y; | 250 | const dy = EXPORT_MARGIN - b.y; |
| 251 | const off = document.createElement("canvas"); | 251 | const off = document.createElement("canvas"); |
| 252 | - off.width = Math.round(w * scale); | 252 | + off.width = canvasPx(w, scale); |
| 253 | - off.height = Math.round(h * scale); | 253 | + off.height = canvasPx(h, scale); |
| 254 | const oc = off.getContext("2d"); | 254 | const oc = off.getContext("2d"); |
| 255 | if (!oc) return null; | 255 | if (!oc) return null; |
| 256 | oc.setTransform(scale, 0, 0, scale, dx * scale, dy * scale); | 256 | oc.setTransform(scale, 0, 0, scale, dx * scale, dy * scale); |
| 257 | for (const s of list) paintStroke(oc, s); | 257 | for (const s of list) paintStroke(oc, s); |
| 258 | const shifted = list.map((s) => ({ ...s, points: s.points.map((p) => ({ x: p.x + dx, y: p.y + dy })) })); | 258 | 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 }; | ||
| 260 | return { canvas: off, scene }; | 262 | return { canvas: off, scene }; |
| 261 | }; | 263 | }; |
| 262 | 264 | ||
src/components/exams/drawing-playback.tsx → src/components/ui/drawing-playback.tsxrenamed+10 -8
| @@ -1,7 +1,7 @@ | |||
| 1 | import { createSignal, onCleanup, onMount } from "solid-js"; | 1 | import { createSignal, onCleanup, onMount } from "solid-js"; |
| 2 | import { Button } from "@/components/ui/button"; | 2 | import { Button } from "@/components/ui/button"; |
| 3 | import { cn } from "@/lib/cn"; | 3 | 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"; |
| 5 | import { useT } from "@/stores/preferences-context"; | 5 | import { useT } from "@/stores/preferences-context"; |
| 6 | 6 | ||
| 7 | // ponytail: synthetic order-only pace — the drawing carries no per-point timing, so | 7 | // ponytail: synthetic order-only pace — the drawing carries no per-point timing, so |
| @@ -15,7 +15,7 @@ const POINTS_PER_SECOND = 220; | |||
| 15 | * transparent layer (erasers cut only ink), then that layer is composited over | 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. | 16 | * white + paper ruling. No timestamps are read — order + a synthetic pace only. |
| 17 | */ | 17 | */ |
| 18 | -export function DrawingPlayback(props: { scene: DrawScene; class?: string }) { | 18 | +export function DrawingPlayback(props: { scene: DrawScene; class?: string; canvasClass?: string }) { |
| 19 | const t = useT(); | 19 | const t = useT(); |
| 20 | let canvas: HTMLCanvasElement | undefined; | 20 | let canvas: HTMLCanvasElement | undefined; |
| 21 | let layer: HTMLCanvasElement | undefined; // offscreen transparent stroke layer (the export's `source`) | 21 | let layer: HTMLCanvasElement | undefined; // offscreen transparent stroke layer (the export's `source`) |
| @@ -23,8 +23,9 @@ export function DrawingPlayback(props: { scene: DrawScene; class?: string }) { | |||
| 23 | let startedAt = 0; // performance.now() when the current run began | 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) | 24 | let baseCount = 0; // points already revealed when the run began (so pause/resume continues) |
| 25 | let revealed = 0; | 25 | let revealed = 0; |
| 26 | - // ponytail: DPR snapshotted at mount so the backing store and the paint transform can't | 26 | + // The scene's own export DPR when it has one (older scenes fall back to this display's), |
| 27 | - // drift apart when browser zoom changes mid-run; re-inits on remount (Show image → Play). | 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. | ||
| 28 | let scale = 1; | 29 | let scale = 1; |
| 29 | 30 | ||
| 30 | const total = () => props.scene.strokes.reduce((n, s) => n + s.points.length, 0); | 31 | 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 }) { | |||
| 81 | }; | 82 | }; |
| 82 | 83 | ||
| 83 | onMount(() => { | 84 | onMount(() => { |
| 84 | - scale = window.devicePixelRatio || 1; | 85 | + scale = props.scene.dpr ?? (window.devicePixelRatio || 1); |
| 85 | - const w = Math.max(1, Math.round(props.scene.w * scale)); | 86 | + const w = canvasPx(props.scene.w, scale); |
| 86 | - const h = Math.max(1, Math.round(props.scene.h * scale)); | 87 | + const h = canvasPx(props.scene.h, scale); |
| 87 | if (canvas) { | 88 | if (canvas) { |
| 88 | canvas.width = w; | 89 | canvas.width = w; |
| 89 | canvas.height = h; | 90 | canvas.height = h; |
| @@ -98,7 +99,8 @@ export function DrawingPlayback(props: { scene: DrawScene; class?: string }) { | |||
| 98 | 99 | ||
| 99 | return ( | 100 | return ( |
| 100 | <div class={cn("space-y-2", props.class)}> | 101 | <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"} /> | ||
| 102 | <div class="flex flex-wrap items-center gap-2"> | 104 | <div class="flex flex-wrap items-center gap-2"> |
| 103 | <Button type="button" variant="outline" size="sm" onClick={() => (playing() ? pause() : play())}> | 105 | <Button type="button" variant="outline" size="sm" onClick={() => (playing() ? pause() : play())}> |
| 104 | {playing() ? t("exams.pause") : t("exams.play")} | 106 | {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 @@ | |||
| 1 | import { describe, expect, it } from "vitest"; | 1 | 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"; |
| 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() { |
| @@ -120,6 +120,16 @@ describe("parseScene", () => { | |||
| 120 | expect(parseScene(JSON.stringify({ ...scene, v: 2 }))).toBeNull(); | 120 | expect(parseScene(JSON.stringify({ ...scene, v: 2 }))).toBeNull(); |
| 121 | }); | 121 | }); |
| 122 | 122 | ||
| 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 | + | ||
| 123 | it("rejects a malformed stroke shape", () => { | 133 | it("rejects a malformed stroke shape", () => { |
| 124 | expect(parseScene(JSON.stringify({ v: 1, w: 1, h: 1, strokes: [{ color: "#000" }] }))).toBeNull(); | 134 | expect(parseScene(JSON.stringify({ v: 1, w: 1, h: 1, strokes: [{ color: "#000" }] }))).toBeNull(); |
| 125 | }); | 135 | }); |
| @@ -128,6 +138,18 @@ describe("parseScene", () => { | |||
| 128 | expect(parseScene("not json")).toBeNull(); | 138 | expect(parseScene("not json")).toBeNull(); |
| 129 | expect(parseScene(null)).toBeNull(); | 139 | expect(parseScene(null)).toBeNull(); |
| 130 | }); | 140 | }); |
| 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 | + }); | ||
| 131 | }); | 153 | }); |
| 132 | 154 | ||
| 133 | describe("strokesBounds", () => { | 155 | describe("strokesBounds", () => { |
| @@ -223,3 +245,48 @@ describe("paintPaper", () => { | |||
| 223 | expect(vertical.length).toBeGreaterThan(0); | 245 | expect(vertical.length).toBeGreaterThan(0); |
| 224 | }); | 246 | }); |
| 225 | }); | 247 | }); |
| 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 @@ | |||
| 1 | export type Point = { x: number; y: number }; | 1 | export type Point = { x: number; y: number }; |
| 2 | export type Stroke = { color: string; width: number; erase: boolean; points: Point[] }; | 2 | export type Stroke = { color: string; width: number; erase: boolean; points: Point[] }; |
| 3 | export type BgKind = "none" | "lines" | "grid"; | 3 | 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 }; | ||
| 5 | 6 | ||
| 6 | /** World px per notebook cell — shared by the live CSS paper and the baked export so both read as the same ruling. */ | 7 | /** World px per notebook cell — shared by the live CSS paper and the baked export so both read as the same ruling. */ |
| 7 | export const PAPER_CELL = 24; | 8 | export const PAPER_CELL = 24; |
| @@ -12,6 +13,18 @@ function isPoint(p: unknown): p is Point { | |||
| 12 | return !!p && typeof p === "object" && typeof (p as Point).x === "number" && typeof (p as Point).y === "number"; | 13 | return !!p && typeof p === "object" && typeof (p as Point).x === "number" && typeof (p as Point).y === "number"; |
| 13 | } | 14 | } |
| 14 | 15 | ||
| 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 | + | ||
| 15 | function isStroke(s: unknown): s is Stroke { | 28 | function isStroke(s: unknown): s is Stroke { |
| 16 | if (!s || typeof s !== "object") return false; | 29 | if (!s || typeof s !== "object") return false; |
| 17 | const st = s as Stroke; | 30 | const st = s as Stroke; |
| @@ -39,15 +52,30 @@ export function parseScene(text: string | null): DrawScene | null { | |||
| 39 | } | 52 | } |
| 40 | if (!data || typeof data !== "object") return null; | 53 | if (!data || typeof data !== "object") return null; |
| 41 | const scene = data as DrawScene; | 54 | 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)) { |
| 43 | return null; | 56 | return null; |
| 44 | } | 57 | } |
| 45 | if (!scene.strokes.every(isStroke)) return null; | 58 | if (!scene.strokes.every(isStroke)) return null; |
| 46 | // bg is optional (old drawings lack it); reject only a present-but-bogus value. | 59 | // bg is optional (old drawings lack it); reject only a present-but-bogus value. |
| 47 | if (scene.bg !== undefined && scene.bg !== "none" && scene.bg !== "lines" && scene.bg !== "grid") return null; | 60 | 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; | ||
| 48 | return scene; | 65 | return scene; |
| 49 | } | 66 | } |
| 50 | 67 | ||
| 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 | + | ||
| 51 | /** | 79 | /** |
| 52 | * Tight bounding box over every ink (pen) stroke, padded by its half-width so a | 80 | * Tight bounding box over every ink (pen) stroke, padded by its half-width so a |
| 53 | * thick line isn't clipped at the edge. Null when there's nothing drawn. Used to | 81 | * 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 | |||
| 73 | return { x: minX, y: minY, w: maxX - minX, h: maxY - minY }; | 101 | return { x: minX, y: minY, w: maxX - minX, h: maxY - minY }; |
| 74 | } | 102 | } |
| 75 | 103 | ||
| 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 | + | ||
| 76 | /** | 115 | /** |
| 77 | * Split strokes at a reveal cut for order-only playback. Points are counted across | 116 | * 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 | 117 | * 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 { | |||
| 16 | } | 16 | } |
| 17 | 17 | ||
| 18 | describe("pngBytesToScene", () => { | 18 | 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", () => { |
| 20 | const scene: DrawScene = { | 20 | const scene: DrawScene = { |
| 21 | v: 1, | 21 | v: 1, |
| 22 | w: 120, | 22 | w: 120, |
| 23 | h: 90, | 23 | 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 | + ], | ||
| 25 | }; | 30 | }; |
| 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. | ||
| 26 | const png = embedPngText(minimalPng(), "hezarfen-drawing", JSON.stringify(scene)); | 35 | const png = embedPngText(minimalPng(), "hezarfen-drawing", JSON.stringify(scene)); |
| 27 | expect(pngBytesToScene(png)).toEqual(scene); | 36 | expect(pngBytesToScene(png)).toEqual(scene); |
| 28 | }); | 37 | }); |
src/lib/png-meta.test.tsmodified+19 -0
| @@ -1,4 +1,5 @@ | |||
| 1 | import { describe, expect, it } from "vitest"; | 1 | import { describe, expect, it } from "vitest"; |
| 2 | +import type { DrawScene } from "./draw-stroke"; | ||
| 2 | import { embedPngText, extractPngText } from "./png-meta"; | 3 | import { embedPngText, extractPngText } from "./png-meta"; |
| 3 | 4 | ||
| 4 | const SIGNATURE = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]; | 5 | const SIGNATURE = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]; |
| @@ -60,4 +61,22 @@ describe("png-meta", () => { | |||
| 60 | const embedded = ((png[crcAt] << 24) | (png[crcAt + 1] << 16) | (png[crcAt + 2] << 8) | png[crcAt + 3]) >>> 0; | 61 | const embedded = ((png[crcAt] << 24) | (png[crcAt + 1] << 16) | (png[crcAt + 2] << 8) | png[crcAt + 3]) >>> 0; |
| 61 | expect(embedded).toBe(refCrc32(typeAndData)); | 62 | expect(embedded).toBe(refCrc32(typeAndData)); |
| 62 | }); | 63 | }); |
| 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 | + }); | ||
| 63 | }); | 82 | }); |
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"; |
| 2 | import { useParams, useRouter } from "@tanstack/solid-router"; | 2 | import { useParams, useRouter } from "@tanstack/solid-router"; |
| 3 | -import { getQuestionById, deleteQuestionById, postQuestionApprove, getQuestionImageUrl } from "@/api/shared"; | 3 | +import { getQuestionById, deleteQuestionById, postQuestionApprove, getQuestionImageUrl, getQuestionImageBlob } from "@/api/shared"; |
| 4 | -import { getSolutions, postSolution, patchSolutionById, deleteSolutionById, getSolutionImageUrl } from "@/api/shared"; | 4 | +import { getSolutions, postSolution, patchSolutionById, deleteSolutionById, getSolutionImageUrl, getSolutionImageBlob } from "@/api/shared"; |
| 5 | import type { SolutionResponse } from "@/api/shared"; | 5 | import type { SolutionResponse } from "@/api/shared"; |
| 6 | import { formatApiError } from "@/api/client"; | 6 | import { formatApiError } from "@/api/client"; |
| 7 | import { RouteGuard } from "@/components/layout/route-guard"; | 7 | import { RouteGuard } from "@/components/layout/route-guard"; |
| @@ -12,6 +12,7 @@ import { ConfirmDialog } from "@/components/ui/confirm-dialog"; | |||
| 12 | import { Label } from "@/components/ui/label"; | 12 | import { Label } from "@/components/ui/label"; |
| 13 | import { Textarea } from "@/components/ui/textarea"; | 13 | import { Textarea } from "@/components/ui/textarea"; |
| 14 | import { IconTrash, IconCheck, IconX, IconEdit, IconMessage, IconPhoto } from "@/components/ui/icons"; | 14 | import { IconTrash, IconCheck, IconX, IconEdit, IconMessage, IconPhoto } from "@/components/ui/icons"; |
| 15 | +import { ReplayableImage } from "@/components/ui/replayable-image"; | ||
| 15 | import { personLabel } from "@/lib/person"; | 16 | import { personLabel } from "@/lib/person"; |
| 16 | 17 | ||
| 17 | import { ErrorAlert } from "@/components/ui/error-alert"; | 18 | import { ErrorAlert } from "@/components/ui/error-alert"; |
| @@ -20,6 +21,9 @@ import { useT } from "@/stores/preferences-context"; | |||
| 20 | import { useAuth } from "@/stores/auth-context"; | 21 | import { useAuth } from "@/stores/auth-context"; |
| 21 | import { hasMinRole } from "@/lib/roles"; | 22 | import { hasMinRole } from "@/lib/roles"; |
| 22 | 23 | ||
| 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 | + | ||
| 23 | export default function QuestionDetailPage() { | 27 | export default function QuestionDetailPage() { |
| 24 | return ( | 28 | return ( |
| 25 | <RouteGuard minRole="student"> | 29 | <RouteGuard minRole="student"> |
| @@ -118,8 +122,13 @@ function QuestionDetailContent() { | |||
| 118 | <div class="rounded-xl border bg-card p-6 shadow-sm"> | 122 | <div class="rounded-xl border bg-card p-6 shadow-sm"> |
| 119 | <p class="whitespace-pre-wrap text-foreground">{q().body}</p> | 123 | <p class="whitespace-pre-wrap text-foreground">{q().body}</p> |
| 120 | <Show when={q().image}> | 124 | <Show when={q().image}> |
| 121 | - <div class="mt-4 overflow-hidden rounded-lg border bg-muted/30"> | 125 | + <div class="mt-4 overflow-hidden rounded-lg border bg-muted/30 p-2"> |
| 122 | - <img src={getQuestionImageUrl(q().id)} alt="Question Attachment" class="max-h-[500px] w-auto object-contain mx-auto" /> | 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 | + /> | ||
| 123 | </div> | 132 | </div> |
| 124 | </Show> | 133 | </Show> |
| 125 | </div> | 134 | </div> |
| @@ -163,8 +172,13 @@ function QuestionDetailContent() { | |||
| 163 | </div> | 172 | </div> |
| 164 | <p class="mt-3 whitespace-pre-wrap text-sm text-foreground">{sol.body}</p> | 173 | <p class="mt-3 whitespace-pre-wrap text-sm text-foreground">{sol.body}</p> |
| 165 | <Show when={sol.image}> | 174 | <Show when={sol.image}> |
| 166 | - <div class="mt-3 overflow-hidden rounded-lg border border-border/50"> | 175 | + <div class="mt-3 overflow-hidden rounded-lg border border-border/50 p-2"> |
| 167 | - <img src={getSolutionImageUrl(q().id, sol.id)} alt="Solution Attachment" class="max-h-[300px] w-auto object-contain mx-auto" /> | 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 | + /> | ||
| 168 | </div> | 182 | </div> |
| 169 | </Show> | 183 | </Show> |
| 170 | </div> | 184 | </div> |
| @@ -236,6 +250,7 @@ function SolutionFormDialog(props: { questionId: string; initialData?: SolutionR | |||
| 236 | const [error, setError] = createSignal(""); | 250 | const [error, setError] = createSignal(""); |
| 237 | const [body, setBody] = createSignal(props.initialData?.body || ""); | 251 | const [body, setBody] = createSignal(props.initialData?.body || ""); |
| 238 | const [file, setFile] = createSignal<File | null>(null); | 252 | const [file, setFile] = createSignal<File | null>(null); |
| 253 | + const [drawing, setDrawing] = createSignal(false); | ||
| 239 | 254 | ||
| 240 | const handleSubmit = async (e: Event) => { | 255 | const handleSubmit = async (e: Event) => { |
| 241 | e.preventDefault(); | 256 | e.preventDefault(); |
| @@ -306,6 +321,22 @@ function SolutionFormDialog(props: { questionId: string; initialData?: SolutionR | |||
| 306 | onChange={(e) => setFile(e.currentTarget.files?.[0] || null)} | 321 | onChange={(e) => setFile(e.currentTarget.files?.[0] || null)} |
| 307 | /> | 322 | /> |
| 308 | </div> | 323 | </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> | ||
| 309 | </div> | 340 | </div> |
| 310 | </Show> | 341 | </Show> |
| 311 | <div class="flex justify-end gap-3 pt-4"> | 342 | <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"; |
| 2 | import { Link, useSearch, useNavigate } from "@tanstack/solid-router"; | 2 | import { Link, useSearch, useNavigate } from "@tanstack/solid-router"; |
| 3 | import { getQuestions, postQuestion } from "@/api/shared"; | 3 | import { getQuestions, postQuestion } from "@/api/shared"; |
| 4 | import { formatApiError } from "@/api/client"; | 4 | import { formatApiError } from "@/api/client"; |
| @@ -11,7 +11,7 @@ import { FormDialog } from "@/components/ui/form-dialog"; | |||
| 11 | import { Label } from "@/components/ui/label"; | 11 | import { Label } from "@/components/ui/label"; |
| 12 | import { Input } from "@/components/ui/input"; | 12 | import { Input } from "@/components/ui/input"; |
| 13 | import { Textarea } from "@/components/ui/textarea"; | 13 | 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"; |
| 15 | import { personLabel } from "@/lib/person"; | 15 | import { personLabel } from "@/lib/person"; |
| 16 | 16 | ||
| 17 | import { ErrorAlert } from "@/components/ui/error-alert"; | 17 | import { ErrorAlert } from "@/components/ui/error-alert"; |
| @@ -20,6 +20,9 @@ import { useT } from "@/stores/preferences-context"; | |||
| 20 | import { useAuth } from "@/stores/auth-context"; | 20 | import { useAuth } from "@/stores/auth-context"; |
| 21 | import { cn } from "@/lib/cn"; | 21 | import { cn } from "@/lib/cn"; |
| 22 | 22 | ||
| 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 | + | ||
| 23 | export default function QuestionsPage() { | 26 | export default function QuestionsPage() { |
| 24 | return ( | 27 | return ( |
| 25 | <RouteGuard minRole="student"> | 28 | <RouteGuard minRole="student"> |
| @@ -137,6 +140,7 @@ function AskQuestionDialog(props: { onClose: () => void; onSuccess: () => void } | |||
| 137 | const [title, setTitle] = createSignal(""); | 140 | const [title, setTitle] = createSignal(""); |
| 138 | const [body, setBody] = createSignal(""); | 141 | const [body, setBody] = createSignal(""); |
| 139 | const [file, setFile] = createSignal<File | null>(null); | 142 | const [file, setFile] = createSignal<File | null>(null); |
| 143 | + const [drawing, setDrawing] = createSignal(false); | ||
| 140 | 144 | ||
| 141 | const handleSubmit = async (e: Event) => { | 145 | const handleSubmit = async (e: Event) => { |
| 142 | e.preventDefault(); | 146 | e.preventDefault(); |
| @@ -206,6 +210,22 @@ function AskQuestionDialog(props: { onClose: () => void; onSuccess: () => void } | |||
| 206 | onChange={(e) => setFile(e.currentTarget.files?.[0] || null)} | 210 | onChange={(e) => setFile(e.currentTarget.files?.[0] || null)} |
| 207 | /> | 211 | /> |
| 208 | </div> | 212 | </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> | ||
| 209 | </div> | 229 | </div> |
| 210 | <div class="flex justify-end gap-3 pt-4"> | 230 | <div class="flex justify-end gap-3 pt-4"> |
| 211 | <Button type="button" variant="outline" onClick={props.onClose}> | 231 | <Button type="button" variant="outline" onClick={props.onClose}> |